doccupine 0.0.129 → 0.0.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,11 +19,11 @@ export function generateJsonLdScript(opts) {
19
19
  ? JSON.stringify(opts.date)
20
20
  : "undefined";
21
21
  const defaultFaviconLiteral = JSON.stringify(DEFAULT_FAVICON);
22
+ // When the page declares an image, it always wins - emitting a `||` chain
23
+ // after a string literal makes TypeScript fail the build with
24
+ // "This kind of expression is always truthy".
22
25
  const faviconLine = opts.image
23
- ? `const faviconUrl =
24
- ${JSON.stringify(opts.image)} ||
25
- config.icon ||
26
- ${defaultFaviconLiteral};`
26
+ ? `const faviconUrl = ${JSON.stringify(opts.image)};`
27
27
  : `const faviconUrl = config.icon || ${defaultFaviconLiteral};`;
28
28
  // Indent 10 + "description: ".length(13) + ",".length(1) = 24. Prettier
29
29
  // wraps the value to the next line (indent 12) once total exceeds 80.
@@ -1 +1 @@
1
- export declare const postHogProviderLazyTemplate = "\"use client\";\n\nimport posthog from \"posthog-js\";\nimport { Suspense, useEffect, useRef, useState } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport rawAnalyticsConfig from \"@/analytics.json\";\n\ninterface AnalyticsConfig {\n provider?: string;\n posthog?: {\n key?: string;\n host?: string;\n };\n}\n\nconst analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;\n\nconst posthogKey =\n analyticsConfig?.provider === \"posthog\" ? analyticsConfig.posthog?.key : null;\n\n// `host` is the *ingestion* endpoint (us.i.posthog.com); `ui_host` wants the\n// dashboard it belongs to (us.posthog.com), which is what \"view in PostHog\"\n// links and the toolbar point at. Self-hosted instances serve both from one\n// origin, so leaving those untouched is correct.\nconst uiHost = (analyticsConfig.posthog?.host || \"https://us.i.posthog.com\")\n .replace(\".i.posthog.com\", \".posthog.com\");\n\nfunction PostHogInit({ onReady }: { onReady: () => void }) {\n const initRef = useRef(false);\n\n useEffect(() => {\n if (initRef.current || !posthogKey) return;\n initRef.current = true;\n\n posthog.init(posthogKey, {\n api_host: \"/ingest\",\n ui_host: uiHost,\n capture_pageview: false,\n capture_pageleave: true,\n loaded: onReady,\n });\n }, [onReady]);\n\n return null;\n}\n\n/**\n * Captures soft navigations only.\n *\n * The document load that got the reader here was already captured in the\n * middleware (see proxy.ts), so counting it again here is what produced two\n * `$pageview` events per page load. Server owns document loads, client owns\n * soft navigations: disjoint, so neither double-counts nor leaves a gap.\n */\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRun = useRef(true);\n\n useEffect(() => {\n if (isFirstRun.current) {\n isFirstRun.current = false;\n return;\n }\n if (pathname) {\n const url = searchParams?.size\n ? `${pathname}?${searchParams.toString()}`\n : pathname;\n posthog.capture(\"$pageview\", { $current_url: url });\n }\n }, [pathname, searchParams]);\n\n return null;\n}\n\nexport function PostHogSetup() {\n const [ready, setReady] = useState(false);\n\n if (!posthogKey) {\n return null;\n }\n\n return (\n <>\n <PostHogInit onReady={() => setReady(true)} />\n <Suspense fallback={null}>{ready && <PostHogPageviewTracker />}</Suspense>\n </>\n );\n}\n";
1
+ export declare const postHogProviderLazyTemplate = "\"use client\";\n\nimport posthog from \"posthog-js\";\nimport { Suspense, useEffect, useRef, useState } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport rawAnalyticsConfig from \"@/analytics.json\";\n\ninterface AnalyticsConfig {\n provider?: string;\n posthog?: {\n key?: string;\n host?: string;\n };\n}\n\nconst analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;\n\nconst posthogKey =\n analyticsConfig?.provider === \"posthog\" ? analyticsConfig.posthog?.key : null;\n\n// `host` is the *ingestion* endpoint (us.i.posthog.com); `ui_host` wants the\n// dashboard it belongs to (us.posthog.com), which is what \"view in PostHog\"\n// links and the toolbar point at. Self-hosted instances serve both from one\n// origin, so leaving those untouched is correct.\nconst uiHost = (\n analyticsConfig.posthog?.host || \"https://us.i.posthog.com\"\n).replace(\".i.posthog.com\", \".posthog.com\");\n\n/**\n * Adopt the session id the middleware already decided on (see proxy.ts), so the\n * server's document-load `$pageview` and every client event after it land in\n * the same session.\n *\n * Without this the two disagree: the middleware used to forward posthog-js's\n * own session id without checking whether it had expired, so a returning\n * reader's pageview was filed under a dead session and the real new session\n * began with no pageview in it \u2014 wrong landing page, wrong bounce rate.\n *\n * Reading document.cookie works on the first request because the middleware\n * sets the cookie on the same response that carries this HTML. Returns\n * undefined if absent or malformed, in which case posthog-js mints its own id\n * as before: degraded, never broken.\n */\n// Both the middleware and this file WRITE the session cookie, so these three\n// must stay identical to their counterparts in proxy.ts. They are duplicated\n// rather than shared because a client component cannot import from the\n// middleware. A drifted max-age here would silently expire live sessions.\nconst SESSION_COOKIE = \"dcp_sid\";\nconst SESSION_MAX_MS = 24 * 60 * 60 * 1000;\n\nfunction isValidSessionId(id: string): boolean {\n return /^[0-9a-f]{32}$/i.test(id.replace(/-/g, \"\"));\n}\n\nfunction readSessionCookie(): { id: string; startTs: number } | undefined {\n if (typeof document === \"undefined\") return undefined;\n\n const match = document.cookie.match(/(?:^|;\\s*)dcp_sid=([^;]*)/);\n if (!match) return undefined;\n\n // Cookie is `id.startTs.lastTs`; posthog-js requires the id be a UUID and\n // logs an error if not, so check before handing it over.\n const [id, startRaw] = decodeURIComponent(match[1]).split(\".\");\n const startTs = Number(startRaw);\n if (!isValidSessionId(id) || !Number.isFinite(startTs)) return undefined;\n\n return { id, startTs };\n}\n\nfunction readEdgeSessionId(): string | undefined {\n return readSessionCookie()?.id;\n}\n\n/**\n * Keep the session cookie's last-activity fresh, from the browser.\n *\n * This is the half of session upkeep the middleware deliberately does NOT do.\n * A response carrying `Set-Cookie` is not cacheable by Vercel's CDN, so\n * refreshing last-activity server-side would have put one on roughly every doc\n * page an engaged reader loads. A `document.cookie` write sets no response\n * header at all, so your doc pages stay cacheable \u2014 and the browser is the side\n * that actually sees soft navigations and in-page activity.\n *\n * `startTs` is carried forward while the id is unchanged, so the 24h hard cap\n * still measures from when the session really began; a rotation restarts it.\n */\nfunction syncSessionCookie(sessionId: string | undefined) {\n if (typeof document === \"undefined\" || !sessionId) return;\n if (!isValidSessionId(sessionId)) return;\n\n const now = Date.now();\n const existing = readSessionCookie();\n const startTs = existing?.id === sessionId ? existing.startTs : now;\n const secure = location.protocol === \"https:\" ? \"; secure\" : \"\";\n\n document.cookie =\n SESSION_COOKIE +\n \"=\" +\n sessionId +\n \".\" +\n startTs +\n \".\" +\n now +\n \"; path=/; max-age=\" +\n SESSION_MAX_MS / 1000 +\n \"; samesite=lax\" +\n secure;\n}\n\nfunction PostHogInit({ onReady }: { onReady: () => void }) {\n const initRef = useRef(false);\n\n useEffect(() => {\n if (!posthogKey) return;\n\n // The init guard deliberately does NOT wrap the subscription below.\n //\n // Under React StrictMode's dev double-invoke the effect runs, is cleaned\n // up, then runs again. With an early `return` here, that second run would\n // skip past the subscription and leave `onSessionId` permanently\n // unsubscribed \u2014 in dev only, which is precisely where you would go to\n // check that any of this works. Initialising once while re-subscribing on\n // every run is correct in both modes.\n if (!initRef.current) {\n initRef.current = true;\n\n const sessionID = readEdgeSessionId();\n\n posthog.init(posthogKey, {\n api_host: \"/ingest\",\n ui_host: uiHost,\n capture_pageview: false,\n capture_pageleave: true,\n // The middleware owns session identity; this makes the SDK agree.\n ...(sessionID ? { bootstrap: { sessionID } } : {}),\n loaded: (ph) => {\n // Write once at startup so a session the middleware adopted (and\n // therefore did not rewrite) still gets its last-activity advanced.\n syncSessionCookie(ph.get_session_id());\n onReady();\n },\n });\n }\n\n // Fires when the session id first appears and on every rotation, so the\n // cookie follows posthog-js rather than drifting from it. posthog-js is the\n // better judge of idleness \u2014 it sees every captured event, not just\n // navigations. Returning its unsubscribe doubles as the effect cleanup.\n return posthog.onSessionId((id: string) => syncSessionCookie(id));\n }, [onReady]);\n\n return null;\n}\n\n/**\n * Captures soft navigations only.\n *\n * The document load that got the reader here was already captured in the\n * middleware (see proxy.ts), so counting it again here is what produced two\n * `$pageview` events per page load. Server owns document loads, client owns\n * soft navigations: disjoint, so neither double-counts nor leaves a gap.\n */\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRun = useRef(true);\n\n useEffect(() => {\n if (isFirstRun.current) {\n isFirstRun.current = false;\n return;\n }\n if (pathname) {\n const url = searchParams?.size\n ? `${pathname}?${searchParams.toString()}`\n : pathname;\n posthog.capture(\"$pageview\", { $current_url: url });\n\n // A soft navigation is activity the middleware never sees, and\n // `onSessionId` won't fire because the id hasn't changed. Without this, a\n // reader who browses only via client-side links would look idle to the\n // next document load and have their session rotated out from under them.\n syncSessionCookie(posthog.get_session_id());\n }\n }, [pathname, searchParams]);\n\n return null;\n}\n\nexport function PostHogSetup() {\n const [ready, setReady] = useState(false);\n\n if (!posthogKey) {\n return null;\n }\n\n return (\n <>\n <PostHogInit onReady={() => setReady(true)} />\n <Suspense fallback={null}>{ready && <PostHogPageviewTracker />}</Suspense>\n </>\n );\n}\n";
@@ -22,23 +22,131 @@ const posthogKey =
22
22
  // dashboard it belongs to (us.posthog.com), which is what "view in PostHog"
23
23
  // links and the toolbar point at. Self-hosted instances serve both from one
24
24
  // origin, so leaving those untouched is correct.
25
- const uiHost = (analyticsConfig.posthog?.host || "https://us.i.posthog.com")
26
- .replace(".i.posthog.com", ".posthog.com");
25
+ const uiHost = (
26
+ analyticsConfig.posthog?.host || "https://us.i.posthog.com"
27
+ ).replace(".i.posthog.com", ".posthog.com");
28
+
29
+ /**
30
+ * Adopt the session id the middleware already decided on (see proxy.ts), so the
31
+ * server's document-load \`$pageview\` and every client event after it land in
32
+ * the same session.
33
+ *
34
+ * Without this the two disagree: the middleware used to forward posthog-js's
35
+ * own session id without checking whether it had expired, so a returning
36
+ * reader's pageview was filed under a dead session and the real new session
37
+ * began with no pageview in it — wrong landing page, wrong bounce rate.
38
+ *
39
+ * Reading document.cookie works on the first request because the middleware
40
+ * sets the cookie on the same response that carries this HTML. Returns
41
+ * undefined if absent or malformed, in which case posthog-js mints its own id
42
+ * as before: degraded, never broken.
43
+ */
44
+ // Both the middleware and this file WRITE the session cookie, so these three
45
+ // must stay identical to their counterparts in proxy.ts. They are duplicated
46
+ // rather than shared because a client component cannot import from the
47
+ // middleware. A drifted max-age here would silently expire live sessions.
48
+ const SESSION_COOKIE = "dcp_sid";
49
+ const SESSION_MAX_MS = 24 * 60 * 60 * 1000;
50
+
51
+ function isValidSessionId(id: string): boolean {
52
+ return /^[0-9a-f]{32}$/i.test(id.replace(/-/g, ""));
53
+ }
54
+
55
+ function readSessionCookie(): { id: string; startTs: number } | undefined {
56
+ if (typeof document === "undefined") return undefined;
57
+
58
+ const match = document.cookie.match(/(?:^|;\\s*)dcp_sid=([^;]*)/);
59
+ if (!match) return undefined;
60
+
61
+ // Cookie is \`id.startTs.lastTs\`; posthog-js requires the id be a UUID and
62
+ // logs an error if not, so check before handing it over.
63
+ const [id, startRaw] = decodeURIComponent(match[1]).split(".");
64
+ const startTs = Number(startRaw);
65
+ if (!isValidSessionId(id) || !Number.isFinite(startTs)) return undefined;
66
+
67
+ return { id, startTs };
68
+ }
69
+
70
+ function readEdgeSessionId(): string | undefined {
71
+ return readSessionCookie()?.id;
72
+ }
73
+
74
+ /**
75
+ * Keep the session cookie's last-activity fresh, from the browser.
76
+ *
77
+ * This is the half of session upkeep the middleware deliberately does NOT do.
78
+ * A response carrying \`Set-Cookie\` is not cacheable by Vercel's CDN, so
79
+ * refreshing last-activity server-side would have put one on roughly every doc
80
+ * page an engaged reader loads. A \`document.cookie\` write sets no response
81
+ * header at all, so your doc pages stay cacheable — and the browser is the side
82
+ * that actually sees soft navigations and in-page activity.
83
+ *
84
+ * \`startTs\` is carried forward while the id is unchanged, so the 24h hard cap
85
+ * still measures from when the session really began; a rotation restarts it.
86
+ */
87
+ function syncSessionCookie(sessionId: string | undefined) {
88
+ if (typeof document === "undefined" || !sessionId) return;
89
+ if (!isValidSessionId(sessionId)) return;
90
+
91
+ const now = Date.now();
92
+ const existing = readSessionCookie();
93
+ const startTs = existing?.id === sessionId ? existing.startTs : now;
94
+ const secure = location.protocol === "https:" ? "; secure" : "";
95
+
96
+ document.cookie =
97
+ SESSION_COOKIE +
98
+ "=" +
99
+ sessionId +
100
+ "." +
101
+ startTs +
102
+ "." +
103
+ now +
104
+ "; path=/; max-age=" +
105
+ SESSION_MAX_MS / 1000 +
106
+ "; samesite=lax" +
107
+ secure;
108
+ }
27
109
 
28
110
  function PostHogInit({ onReady }: { onReady: () => void }) {
29
111
  const initRef = useRef(false);
30
112
 
31
113
  useEffect(() => {
32
- if (initRef.current || !posthogKey) return;
33
- initRef.current = true;
34
-
35
- posthog.init(posthogKey, {
36
- api_host: "/ingest",
37
- ui_host: uiHost,
38
- capture_pageview: false,
39
- capture_pageleave: true,
40
- loaded: onReady,
41
- });
114
+ if (!posthogKey) return;
115
+
116
+ // The init guard deliberately does NOT wrap the subscription below.
117
+ //
118
+ // Under React StrictMode's dev double-invoke the effect runs, is cleaned
119
+ // up, then runs again. With an early \`return\` here, that second run would
120
+ // skip past the subscription and leave \`onSessionId\` permanently
121
+ // unsubscribed — in dev only, which is precisely where you would go to
122
+ // check that any of this works. Initialising once while re-subscribing on
123
+ // every run is correct in both modes.
124
+ if (!initRef.current) {
125
+ initRef.current = true;
126
+
127
+ const sessionID = readEdgeSessionId();
128
+
129
+ posthog.init(posthogKey, {
130
+ api_host: "/ingest",
131
+ ui_host: uiHost,
132
+ capture_pageview: false,
133
+ capture_pageleave: true,
134
+ // The middleware owns session identity; this makes the SDK agree.
135
+ ...(sessionID ? { bootstrap: { sessionID } } : {}),
136
+ loaded: (ph) => {
137
+ // Write once at startup so a session the middleware adopted (and
138
+ // therefore did not rewrite) still gets its last-activity advanced.
139
+ syncSessionCookie(ph.get_session_id());
140
+ onReady();
141
+ },
142
+ });
143
+ }
144
+
145
+ // Fires when the session id first appears and on every rotation, so the
146
+ // cookie follows posthog-js rather than drifting from it. posthog-js is the
147
+ // better judge of idleness — it sees every captured event, not just
148
+ // navigations. Returning its unsubscribe doubles as the effect cleanup.
149
+ return posthog.onSessionId((id: string) => syncSessionCookie(id));
42
150
  }, [onReady]);
43
151
 
44
152
  return null;
@@ -67,6 +175,12 @@ function PostHogPageviewTracker() {
67
175
  ? \`\${pathname}?\${searchParams.toString()}\`
68
176
  : pathname;
69
177
  posthog.capture("$pageview", { $current_url: url });
178
+
179
+ // A soft navigation is activity the middleware never sees, and
180
+ // \`onSessionId\` won't fire because the id hasn't changed. Without this, a
181
+ // reader who browses only via client-side links would look idle to the
182
+ // next document load and have their session rotated out from under them.
183
+ syncSessionCookie(posthog.get_session_id());
70
184
  }
71
185
  }, [pathname, searchParams]);
72
186
 
@@ -22,12 +22,12 @@ export const packageJsonTemplate = JSON.stringify({
22
22
  langchain: "^1.5.3",
23
23
  "lucide-react": "^1.25.0",
24
24
  minisearch: "^7.2.0",
25
- next: "16.2.10",
25
+ next: "16.2.11",
26
26
  "next-mdx-remote": "^6.0.0",
27
- "posthog-js": "^1.405.3",
27
+ "posthog-js": "^1.406.2",
28
28
  "posthog-node": "^5.46.0",
29
- react: "19.2.7",
30
- "react-dom": "19.2.7",
29
+ react: "19.2.8",
30
+ "react-dom": "19.2.8",
31
31
  "rehype-highlight": "^7.0.2",
32
32
  "rehype-parse": "^9.0.1",
33
33
  "rehype-stringify": "^10.0.1",
@@ -37,8 +37,8 @@ export const packageJsonTemplate = JSON.stringify({
37
37
  zod: "^4.4.3",
38
38
  },
39
39
  devDependencies: {
40
- "@next/env": "16.2.10",
41
- "@next/eslint-plugin-next": "16.2.10",
40
+ "@next/env": "16.2.11",
41
+ "@next/eslint-plugin-next": "16.2.11",
42
42
  "@types/node": "^26",
43
43
  "@types/react": "^19",
44
44
  "@types/react-dom": "^19",
@@ -24,14 +24,88 @@ const ANON_ID_COOKIE = "dcp_anon_id";
24
24
 
25
25
  const ANON_ID_MAX_AGE = 60 * 60 * 24 * 365;
26
26
 
27
+ /**
28
+ * Session id, shared between the edge and posthog-js.
29
+ *
30
+ * Deliberately NOT httpOnly, unlike the anon id: the browser has to read this
31
+ * one to hand back to \`posthog.init({ bootstrap })\`. It grants no privilege,
32
+ * and posthog-js already keeps an equivalent id in a readable cookie of its own.
33
+ */
34
+ // SESSION_COOKIE, SESSION_MAX_MS and isValidSessionId are mirrored in
35
+ // PostHogProviderLazy, which also writes this cookie. Keep them in sync — a
36
+ // drifted max-age would silently expire live sessions. They are duplicated
37
+ // rather than shared because a client component cannot import from here.
38
+ const SESSION_COOKIE = "dcp_sid";
39
+
40
+ /** Same rules posthog-js uses internally. */
41
+ const SESSION_IDLE_MS = 30 * 60 * 1000;
42
+ const SESSION_MAX_MS = 24 * 60 * 60 * 1000;
43
+
27
44
  interface TrackingIdentity {
28
45
  distinctId: string;
29
46
  /** Set only when the id was just minted and still needs writing to a cookie. */
30
47
  anonIdToPersist?: string;
31
- sessionId?: string;
48
+ sessionId: string;
49
+ /** Set when the session cookie needs writing. */
50
+ sessionToPersist?: string;
32
51
  deviceId?: string;
33
52
  }
34
53
 
54
+ /** posthog-js strips dashes and requires exactly 32 hex characters. */
55
+ function isValidSessionId(id: string): boolean {
56
+ return /^[0-9a-f]{32}$/i.test(id.replace(/-/g, ""));
57
+ }
58
+
59
+ /**
60
+ * Owns session identity, rather than borrowing posthog-js's.
61
+ *
62
+ * We used to read posthog-js's \`$sesid\` cookie and forward \`$sesid[1]\` (the
63
+ * id) while ignoring \`$sesid[0]\` (last activity) and \`$sesid[2]\` (session
64
+ * start) — the fields posthog-js itself checks before deciding a session is
65
+ * still alive. A returning reader's pageview therefore went out stamped with a
66
+ * session that had expired days earlier: it stretched that dead session's
67
+ * duration, and the real new session began with no pageview in it, losing the
68
+ * landing page. Both feed bounce rate and entry-path reports.
69
+ *
70
+ * Now the middleware decides and posthog-js adopts it via bootstrap, so there is
71
+ * one authority instead of two disagreeing.
72
+ *
73
+ * **The middleware writes this cookie only when it mints a new session.**
74
+ * Keeping \`lastTs\` fresh is the browser's job (see PostHogSetup). That split is
75
+ * deliberate: a response carrying \`Set-Cookie\` is not cacheable by Vercel's CDN,
76
+ * and refreshing last-activity here would have put one on roughly every doc page
77
+ * an engaged reader loads. A \`document.cookie\` write from the browser sets no
78
+ * response header at all, so your doc pages stay cacheable.
79
+ *
80
+ * Consequence: if an ad blocker stops posthog-js, nothing refreshes \`lastTs\`, so
81
+ * that reader's sessions become fixed ~30-minute windows rather than idle-based.
82
+ * Coarser, but still correct.
83
+ */
84
+ function resolveSession(
85
+ req: NextRequest,
86
+ now: number,
87
+ ): { sessionId: string; sessionToPersist?: string } {
88
+ const parts = req.cookies.get(SESSION_COOKIE)?.value?.split(".");
89
+
90
+ if (parts?.length === 3) {
91
+ const [id, startRaw, lastRaw] = parts;
92
+ const startTs = Number(startRaw);
93
+ const lastTs = Number(lastRaw);
94
+ const alive =
95
+ isValidSessionId(id) &&
96
+ Number.isFinite(startTs) &&
97
+ Number.isFinite(lastTs) &&
98
+ now - lastTs <= SESSION_IDLE_MS &&
99
+ now - startTs <= SESSION_MAX_MS;
100
+
101
+ // Alive: adopt it and write nothing, so the response stays cacheable.
102
+ if (alive) return { sessionId: id };
103
+ }
104
+
105
+ const id = crypto.randomUUID();
106
+ return { sessionId: id, sessionToPersist: \`\${id}.\${now}.\${now}\` };
107
+ }
108
+
35
109
  /**
36
110
  * Resolves who this pageview belongs to: whatever posthog-js already
37
111
  * established for this browser, else our own anonymous cookie, else a fresh id
@@ -39,7 +113,6 @@ interface TrackingIdentity {
39
113
  */
40
114
  function resolveTrackingIdentity(req: NextRequest): TrackingIdentity {
41
115
  let distinctId: string | undefined;
42
- let sessionId: string | undefined;
43
116
  let deviceId: string | undefined;
44
117
 
45
118
  const phCookie = req.cookies.get(
@@ -49,24 +122,22 @@ function resolveTrackingIdentity(req: NextRequest): TrackingIdentity {
49
122
  try {
50
123
  const parsed = JSON.parse(phCookie);
51
124
  if (typeof parsed.distinct_id === "string") distinctId = parsed.distinct_id;
52
- // \`$sesid\` is [lastActivityTs, sessionId, sessionStartTs]. Forwarding it
53
- // keeps server events inside the client's session instead of floating free.
54
- if (Array.isArray(parsed.$sesid) && typeof parsed.$sesid[1] === "string") {
55
- sessionId = parsed.$sesid[1];
56
- }
125
+ // Note we deliberately do NOT read \`$sesid\` — see resolveSession above.
57
126
  if (typeof parsed.$device_id === "string") deviceId = parsed.$device_id;
58
127
  } catch {
59
128
  // ignore malformed cookie
60
129
  }
61
130
  }
62
131
 
63
- if (distinctId) return { distinctId, sessionId, deviceId };
132
+ const session = resolveSession(req, Date.now());
133
+
134
+ if (distinctId) return { distinctId, deviceId, ...session };
64
135
 
65
136
  const anonId = req.cookies.get(ANON_ID_COOKIE)?.value;
66
- if (anonId) return { distinctId: anonId, sessionId, deviceId };
137
+ if (anonId) return { distinctId: anonId, deviceId, ...session };
67
138
 
68
139
  const minted = crypto.randomUUID();
69
- return { distinctId: minted, anonIdToPersist: minted, sessionId, deviceId };
140
+ return { distinctId: minted, anonIdToPersist: minted, deviceId, ...session };
70
141
  }
71
142
 
72
143
  /**
@@ -82,13 +153,17 @@ function captureServerPageview(
82
153
 
83
154
  if (SKIP_PAGEVIEW_PATTERN.test(pathname)) return null;
84
155
 
156
+ // A prefetch is the router speculating, not the reader acting: it neither
157
+ // counts as a pageview nor keeps a session alive.
85
158
  const isPrefetch =
86
159
  req.headers.get("next-router-prefetch") === "1" ||
87
160
  req.headers.get("purpose") === "prefetch";
88
161
  if (isPrefetch) return null;
89
162
 
90
163
  // A soft navigation fetches an RSC payload rather than a document, and
91
- // carries this header. The client tracker owns those.
164
+ // carries this header. The client tracker owns those — and it also keeps the
165
+ // session cookie fresh from the browser, so there is nothing for us to do
166
+ // here.
92
167
  if (req.headers.get("RSC")) return null;
93
168
 
94
169
  const posthog = getPostHogServerClient();
@@ -134,6 +209,17 @@ function applyTracking(
134
209
  secure: process.env.NODE_ENV === "production",
135
210
  });
136
211
  }
212
+ if (tracking?.sessionToPersist) {
213
+ // httpOnly: false is required — the browser reads this to bootstrap
214
+ // posthog-js so the client agrees with the edge about the session.
215
+ res.cookies.set(SESSION_COOKIE, tracking.sessionToPersist, {
216
+ path: "/",
217
+ maxAge: SESSION_MAX_MS / 1000,
218
+ sameSite: "lax",
219
+ httpOnly: false,
220
+ secure: process.env.NODE_ENV === "production",
221
+ });
222
+ }
137
223
  return res;
138
224
  }
139
225
  `
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doccupine",
3
- "version": "0.0.129",
3
+ "version": "0.0.131",
4
4
  "description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -39,10 +39,10 @@
39
39
  "commander": "^15.0.0",
40
40
  "fs-extra": "^11.3.6",
41
41
  "gray-matter": "^4.0.3",
42
- "next": "^16.2.10",
42
+ "next": "^16.2.11",
43
43
  "prompts": "^2.4.2",
44
- "react": "^19.2.7",
45
- "react-dom": "^19.2.7"
44
+ "react": "^19.2.8",
45
+ "react-dom": "^19.2.8"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/fs-extra": "^11.0.4",