Skip to content
This repository was archived by the owner on Nov 29, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions landing-astro/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,57 @@ const content = workbenchContent.parse(json);
<Layout content={content}>
<WorkbenchPage content={content} />
</Layout>

<script>
const analytics = window as Window & {
appHealth?: {
track(name: string): void;
flushForNavigation?: () => Promise<boolean>;
};
clarity?: (command: 'event', name: string) => void;
};

let signInNavigationPending = false;

document.addEventListener('click', (event) => {
if (event.defaultPrevented || !(event.target instanceof Element)) return;
const link = event.target.closest<HTMLAnchorElement>('a[href="/login"]');
if (!link) return;

const sameTab =
event.button === 0 &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey &&
(!link.target || link.target === '_self') &&
!link.hasAttribute('download');
if (sameTab && signInNavigationPending) {
event.preventDefault();
return;
}

const tracker = analytics.appHealth;
tracker?.track('sign_in_opened');
analytics.clarity?.('event', 'sign_in_opened');
const flushForNavigation = tracker?.flushForNavigation;
if (!sameTab || !flushForNavigation) return;

event.preventDefault();
signInNavigationPending = true;
const destination = link.href;
let navigated = false;
const navigate = () => {
if (navigated) return;
navigated = true;
window.clearTimeout(deadline);
signInNavigationPending = false;
location.assign(destination);
};
const deadline = window.setTimeout(navigate, 150);
void Promise.resolve()
.then(() => flushForNavigation.call(tracker))
.catch(() => {})
.finally(navigate);
});
</script>
23 changes: 17 additions & 6 deletions src/worker/app-health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
type AppHealthClientOptions,
} from '@saas-maker/app-health';
import { honoMiddleware } from '@saas-maker/app-health/hono';
import type { Context, Env, MiddlewareHandler } from 'hono';
import type { Env, MiddlewareHandler } from 'hono';
import { routePath } from 'hono/route';

import type { WorkerEnv } from '../lib/worker-env';
Expand Down Expand Up @@ -38,11 +38,11 @@ export function createReaderAppHealthMiddlewares(
let cachedEnvironment = '';
let cachedClient: AppHealthClient | null = null;

const resolveClient = (context: Context<ReaderEnv>) => {
const key = context.env.APP_HEALTH_INGEST_KEY?.trim();
const resolveClient = (env: WorkerEnv) => {
const key = env.APP_HEALTH_INGEST_KEY?.trim();
if (!key) return null;

const environment = context.env.APP_HEALTH_ENVIRONMENT?.trim() || 'production';
const environment = env.APP_HEALTH_ENVIRONMENT?.trim() || 'production';
if (cachedClient && cachedKey === key && cachedEnvironment === environment) {
return cachedClient;
}
Expand All @@ -58,6 +58,15 @@ export function createReaderAppHealthMiddlewares(
});
return cachedClient;
};
const recordSavedLink = (env: WorkerEnv) => {
try {
// The request middleware flushes this event with the endpoint summary.
resolveClient(env)?.log('link.saved', { level: 'debug' });
} catch {
// A telemetry failure must never change the outcome of a saved link.
}
};

let firstRequest = true;
const coldRequests = new WeakSet<Request>();
const trackRequest = (request: Request) => {
Expand All @@ -74,7 +83,7 @@ export function createReaderAppHealthMiddlewares(
if (!c.env.APP_HEALTH_INGEST_KEY?.trim() || rate === 0 || Math.random() >= rate) return;
const route = routePath(c, -1);
if (!isSafeStageRoute(route)) return;
const client = resolveClient(c);
const client = resolveClient(c.env);
if (!client) return;
const colo = c.req.raw.cf?.colo;
client.log('api.stage_timing', {
Expand All @@ -101,14 +110,16 @@ export function createReaderAppHealthMiddlewares(
};

return {
appHealthMiddleware: honoMiddleware<ReaderEnv>({ client: resolveClient }),
appHealthMiddleware: honoMiddleware<ReaderEnv>({ client: (c) => resolveClient(c.env) }),
stageTimingMiddleware,
recordSavedLink,
trackRequest,
};
}

export const {
appHealthMiddleware,
stageTimingMiddleware: appHealthStageTimingMiddleware,
recordSavedLink,
trackRequest: trackAppHealthRequest,
} = createReaderAppHealthMiddlewares();
72 changes: 70 additions & 2 deletions src/worker/routes/__tests__/articles-access.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Hono } from 'hono';
import { beforeEach, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import type { WorkerEnv } from '../../../lib/worker-env';
import { appHealthMiddleware } from '../../app-health';
const mocks = vi.hoisted(() => ({
auth: vi.fn(),
add: vi.fn(),
Expand Down Expand Up @@ -29,7 +31,7 @@ it('rejects guest capture and reads before database access', async () => {
expect(mocks.mark).not.toHaveBeenCalled();
});
it('captures URL-only links and scopes updates to the authenticated account', async () => {
mocks.add.mockResolvedValue({ id: 'one' });
mocks.add.mockResolvedValue({ id: 'one', existing: false });
const response = await app.request('/api/links', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
Expand All @@ -49,3 +51,69 @@ it('captures URL-only links and scopes updates to the authenticated account', as
).toBe(404);
expect(mocks.mark).toHaveBeenCalledWith('alice', 'other', true);
});

afterEach(() => vi.unstubAllGlobals());

it('ships a content-free log only for new saved links through both capture paths', async () => {
const deliveries = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(null, { status: 202 }));
vi.stubGlobal('fetch', deliveries);
const pending: Promise<unknown>[] = [];
const ctx = { waitUntil: (work: Promise<unknown>) => pending.push(work) } as ExecutionContext;
const env = {
APP_HEALTH_INGEST_KEY: 'fixture-ingest-key',
APP_HEALTH_ENVIRONMENT: 'test',
} as WorkerEnv;
const product = new Hono<{ Bindings: WorkerEnv }>();
product.use('*', appHealthMiddleware);
product.route('/api/links', routes);
product.route('/api/articles', routes);
const save = (path: string, auth: Record<string, string>) =>
product.request(
path,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...auth },
body: JSON.stringify({
url: 'https://example.test/saved-path',
title: 'Private saved title',
}),
},
env,
ctx
);

mocks.add
.mockResolvedValueOnce({ id: 'browser-link', existing: false })
.mockResolvedValueOnce({ id: 'extension-link', existing: false })
.mockResolvedValueOnce({ id: 'extension-link', existing: true })
.mockRejectedValueOnce(new TypeError('Invalid URL'));

expect((await save('/api/links', { Cookie: 'session=fixture' })).status).toBe(200);
await Promise.all(pending.splice(0));
expect((await save('/api/articles', { Authorization: 'Bearer rdr_fixture' })).status).toBe(200);
await Promise.all(pending.splice(0));
expect(await (await save('/api/links', { Authorization: 'Bearer rdr_fixture' })).json()).toEqual({
id: 'extension-link',
existing: true,
});
await Promise.all(pending.splice(0));
expect((await save('/api/links', { Cookie: 'session=fixture' })).status).toBe(400);
await Promise.all(pending.splice(0));
mocks.auth.mockResolvedValueOnce(null);
expect((await save('/api/links', {})).status).toBe(401);
await Promise.all(pending.splice(0));

const batches = deliveries.mock.calls
.filter(([url]) => String(url) === 'https://ingest.sassmaker.com/v1/logs')
.map(([, request]) => JSON.parse(String(request?.body)));
expect(batches).toHaveLength(2);
const logs = batches.flatMap((batch) => batch.logs);
expect(logs).toHaveLength(2);
for (const log of logs) {
expect(log).toMatchObject({ event: 'link.saved', level: 'debug' });
expect(log.props).toEqual({});
expect(Object.keys(log).sort()).toEqual(['event', 'level', 'log_id', 'props', 'timestamp']);
}
});
5 changes: 4 additions & 1 deletion src/worker/routes/articles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { bodyLimit } from 'hono/body-limit';
import { getAuthenticatedUserId } from '../../lib/auth-api';
import { addLink, getLink, listLinks, setLinkRead } from '../../lib/links-db';
import type { WorkerEnv } from '../../lib/worker-env';
import { recordSavedLink } from '../app-health';

const links = new Hono<{ Bindings: WorkerEnv; Variables: { userId: string } }>();

Expand Down Expand Up @@ -39,7 +40,9 @@ links.post('/', async (c) => {
}
try {
// URL-only capture, including older extension payloads. No imports or AI calls.
return c.json(await addLink(c.get('userId'), body), 200);
const result = await addLink(c.get('userId'), body);
if (result.existing === false) recordSavedLink(c.env);
return c.json(result, 200);
} catch (error) {
if (error instanceof TypeError || (error instanceof Error && /URL/u.test(error.message))) {
return c.json({ error: error.message }, 400);
Expand Down
44 changes: 44 additions & 0 deletions tests/mobile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,47 @@ test('landing states the narrow product and fits the viewport', async ({ page },
fullPage: true,
});
});

test('landing sign-in reports one fixed event and keeps the ordinary navigation', async ({
page,
}) => {
await page.addInitScript(() => {
const record = (source: string, ...args: unknown[]) => {
const value = JSON.parse(sessionStorage.getItem('qa-cta-events') ?? '[]');
sessionStorage.setItem('qa-cta-events', JSON.stringify([...value, [source, ...args]]));
};
Object.assign(window, {
appHealth: {
track: (...args: unknown[]) => record('app-health', ...args),
flushForNavigation: () => {
record('navigation-flush');
return new Promise(() => {});
},
},
clarity: (command: string, ...args: unknown[]) => {
if (command === 'event') record('clarity', ...args);
},
});
});
await page.route('**/api/auth/get-session', (route) => route.fulfill({ json: null }));
await page.route('**/api/auth/client-config', (route) =>
route.fulfill({ json: { googleClientId: null } })
);
await page.goto('/');
await page
.locator('main a[href="/login"]')
.first()
.evaluate((link: HTMLAnchorElement) => {
link.click();
link.click();
});
await expect(page).toHaveURL(/\/login$/);
await expect(page.getByRole('button', { name: 'Sign in with Google' })).toBeVisible();
expect(
await page.evaluate(() => JSON.parse(sessionStorage.getItem('qa-cta-events') ?? '[]'))
).toEqual([
['app-health', 'sign_in_opened'],
['clarity', 'sign_in_opened'],
['navigation-flush'],
]);
});
Loading