doccupine 0.0.128 → 0.0.130
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.
- package/README.md +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.js +30 -3
- package/dist/lib/config-manager.d.ts +18 -0
- package/dist/lib/config-manager.js +60 -4
- package/dist/templates/components/PostHogProviderLazy.d.ts +1 -1
- package/dist/templates/components/PostHogProviderLazy.js +123 -10
- package/dist/templates/package.js +3 -3
- package/dist/templates/proxy.js +97 -11
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -148,7 +148,7 @@ Place these JSON files in your project root (where you run `doccupine`). They ar
|
|
|
148
148
|
|
|
149
149
|
| File | Purpose |
|
|
150
150
|
| ----------------- | --------------------------------------------------------------------------------------------------------- |
|
|
151
|
-
| `doccupine.json` | CLI config (watchDir, outputDir, port). Auto-generated on first run.
|
|
151
|
+
| `doccupine.json` | CLI config (watchDir, outputDir, port). Auto-generated on first run. Paths are stored relative to the project root, so the file is safe to commit. |
|
|
152
152
|
| `config.json` | Site metadata: `name`, `description`, `icon`, `image`, `url` (public site URL for sitemap/robots) |
|
|
153
153
|
| `theme.json` | Theme overrides for [cherry-styled-components](https://github.com/cherry-design-system/styled-components) |
|
|
154
154
|
| `navigation.json` | Manual navigation structure (overrides auto-generated) |
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
export { generateSlug, getFullSlug, escapeTemplateContent, } from "./lib/utils.js";
|
|
3
|
+
/**
|
|
4
|
+
* True when this file is what node was asked to run, rather than a module some
|
|
5
|
+
* other process imported. The test suite imports this file for its exported
|
|
6
|
+
* helpers; without this guard, that import parses argv, falls through to the
|
|
7
|
+
* default `watch` command, and prompts for config / starts file watchers.
|
|
8
|
+
*
|
|
9
|
+
* Compares realpaths because npm installs the bin as a symlink
|
|
10
|
+
* (`node_modules/.bin/doccupine` -> `dist/index.js`), so `process.argv[1]` and
|
|
11
|
+
* `import.meta.url` can name the same file by different paths.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isProcessEntrypoint(entry?: string | undefined, self?: string): boolean;
|
package/dist/index.js
CHANGED
|
@@ -1250,6 +1250,8 @@ program
|
|
|
1250
1250
|
port: options.port,
|
|
1251
1251
|
});
|
|
1252
1252
|
const generator = new MDXToNextJSGenerator(config.watchDir, config.outputDir);
|
|
1253
|
+
// Config paths are project-relative; child processes get an absolute cwd.
|
|
1254
|
+
const outputDir = path.resolve(process.cwd(), config.outputDir);
|
|
1253
1255
|
await generator.init();
|
|
1254
1256
|
let devServer = null;
|
|
1255
1257
|
console.log(chalk.blue("📦 Installing dependencies..."));
|
|
@@ -1260,7 +1262,7 @@ program
|
|
|
1260
1262
|
const packageManager = resolvePackageManager(options.packageManager ?? config.packageManager);
|
|
1261
1263
|
console.log(chalk.blue(`📦 Using ${packageManager.name}...`));
|
|
1262
1264
|
const install = spawn(packageManager.bin, ["install"], {
|
|
1263
|
-
cwd:
|
|
1265
|
+
cwd: outputDir,
|
|
1264
1266
|
stdio: "inherit",
|
|
1265
1267
|
});
|
|
1266
1268
|
await new Promise((resolve, reject) => {
|
|
@@ -1285,7 +1287,7 @@ program
|
|
|
1285
1287
|
? ["run", "dev", "--", "--port", portStr]
|
|
1286
1288
|
: ["run", "dev", "--port", portStr];
|
|
1287
1289
|
devServer = spawn(packageManager.bin, devArgs, {
|
|
1288
|
-
cwd:
|
|
1290
|
+
cwd: outputDir,
|
|
1289
1291
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1290
1292
|
});
|
|
1291
1293
|
devServer.stdout?.on("data", (data) => {
|
|
@@ -1370,4 +1372,29 @@ program
|
|
|
1370
1372
|
console.log(chalk.blue("Use --show to display configuration or --reset to reset it"));
|
|
1371
1373
|
}
|
|
1372
1374
|
});
|
|
1373
|
-
|
|
1375
|
+
/**
|
|
1376
|
+
* True when this file is what node was asked to run, rather than a module some
|
|
1377
|
+
* other process imported. The test suite imports this file for its exported
|
|
1378
|
+
* helpers; without this guard, that import parses argv, falls through to the
|
|
1379
|
+
* default `watch` command, and prompts for config / starts file watchers.
|
|
1380
|
+
*
|
|
1381
|
+
* Compares realpaths because npm installs the bin as a symlink
|
|
1382
|
+
* (`node_modules/.bin/doccupine` -> `dist/index.js`), so `process.argv[1]` and
|
|
1383
|
+
* `import.meta.url` can name the same file by different paths.
|
|
1384
|
+
*/
|
|
1385
|
+
export function isProcessEntrypoint(entry = process.argv[1], self = __filename) {
|
|
1386
|
+
if (!entry)
|
|
1387
|
+
return false;
|
|
1388
|
+
// Windows paths are case-insensitive; a false negative here would make the
|
|
1389
|
+
// CLI exit silently without running any command.
|
|
1390
|
+
const normalize = (filePath) => process.platform === "win32" ? filePath.toLowerCase() : filePath;
|
|
1391
|
+
try {
|
|
1392
|
+
return (normalize(fs.realpathSync(entry)) === normalize(fs.realpathSync(self)));
|
|
1393
|
+
}
|
|
1394
|
+
catch {
|
|
1395
|
+
return false;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
if (isProcessEntrypoint()) {
|
|
1399
|
+
program.parse();
|
|
1400
|
+
}
|
|
@@ -1,4 +1,22 @@
|
|
|
1
1
|
import type { DoccupineConfig } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Rewrites a path as project-relative so `doccupine.json` stays portable
|
|
4
|
+
* across machines, CI and containers (an absolute `/Users/you/...` breaks for
|
|
5
|
+
* every other contributor and leaks the local directory layout).
|
|
6
|
+
*
|
|
7
|
+
* Paths outside the project root have no portable form, so they are kept
|
|
8
|
+
* absolute - reads go through `path.resolve()`, which accepts both.
|
|
9
|
+
*/
|
|
10
|
+
export declare function toProjectRelativePath(targetPath: string, rootDir?: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* Migrates configs written by older versions, which stored absolute paths.
|
|
13
|
+
* Returns the normalized config plus whether anything actually changed, so
|
|
14
|
+
* callers only rewrite the file when needed.
|
|
15
|
+
*/
|
|
16
|
+
export declare function normalizeConfigPaths(config: DoccupineConfig, rootDir?: string): {
|
|
17
|
+
config: DoccupineConfig;
|
|
18
|
+
changed: boolean;
|
|
19
|
+
};
|
|
2
20
|
export declare class ConfigManager {
|
|
3
21
|
private configPath;
|
|
4
22
|
constructor(configPath?: string);
|
|
@@ -2,6 +2,46 @@ import fs from "fs-extra";
|
|
|
2
2
|
import path from "path";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import prompts from "prompts";
|
|
5
|
+
/**
|
|
6
|
+
* Rewrites a path as project-relative so `doccupine.json` stays portable
|
|
7
|
+
* across machines, CI and containers (an absolute `/Users/you/...` breaks for
|
|
8
|
+
* every other contributor and leaks the local directory layout).
|
|
9
|
+
*
|
|
10
|
+
* Paths outside the project root have no portable form, so they are kept
|
|
11
|
+
* absolute - reads go through `path.resolve()`, which accepts both.
|
|
12
|
+
*/
|
|
13
|
+
export function toProjectRelativePath(targetPath, rootDir = process.cwd()) {
|
|
14
|
+
// A hand-edited config can hold anything; leave junk untouched rather than
|
|
15
|
+
// throwing inside path.*.
|
|
16
|
+
if (typeof targetPath !== "string" || !targetPath)
|
|
17
|
+
return targetPath;
|
|
18
|
+
if (!path.isAbsolute(targetPath))
|
|
19
|
+
return targetPath;
|
|
20
|
+
const relativePath = path.relative(rootDir, targetPath);
|
|
21
|
+
// Empty means the path *is* the root; ".." or an absolute result (Windows
|
|
22
|
+
// cross-drive) means it escapes the root - neither is portable.
|
|
23
|
+
if (!relativePath)
|
|
24
|
+
return ".";
|
|
25
|
+
if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`)) {
|
|
26
|
+
return targetPath;
|
|
27
|
+
}
|
|
28
|
+
if (path.isAbsolute(relativePath))
|
|
29
|
+
return targetPath;
|
|
30
|
+
// Always store POSIX separators so a config written on Windows still
|
|
31
|
+
// resolves on macOS/Linux.
|
|
32
|
+
return relativePath.split(path.sep).join("/");
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Migrates configs written by older versions, which stored absolute paths.
|
|
36
|
+
* Returns the normalized config plus whether anything actually changed, so
|
|
37
|
+
* callers only rewrite the file when needed.
|
|
38
|
+
*/
|
|
39
|
+
export function normalizeConfigPaths(config, rootDir = process.cwd()) {
|
|
40
|
+
const watchDir = toProjectRelativePath(config.watchDir, rootDir);
|
|
41
|
+
const outputDir = toProjectRelativePath(config.outputDir, rootDir);
|
|
42
|
+
const changed = watchDir !== config.watchDir || outputDir !== config.outputDir;
|
|
43
|
+
return { config: { ...config, watchDir, outputDir }, changed };
|
|
44
|
+
}
|
|
5
45
|
export class ConfigManager {
|
|
6
46
|
configPath;
|
|
7
47
|
constructor(configPath = "doccupine.json") {
|
|
@@ -23,7 +63,7 @@ export class ConfigManager {
|
|
|
23
63
|
}
|
|
24
64
|
async saveConfig(config) {
|
|
25
65
|
try {
|
|
26
|
-
await fs.writeFile(this.configPath, JSON.stringify(config, null, 2)
|
|
66
|
+
await fs.writeFile(this.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
27
67
|
console.log(chalk.green("💾 Configuration saved to doccupine.json"));
|
|
28
68
|
}
|
|
29
69
|
catch (error) {
|
|
@@ -50,24 +90,40 @@ export class ConfigManager {
|
|
|
50
90
|
console.log(chalk.yellow("\n⚠️ Setup cancelled."));
|
|
51
91
|
process.exit(0);
|
|
52
92
|
}
|
|
93
|
+
// Resolve first so "./docs" and "docs/" collapse to the same value, then
|
|
94
|
+
// store project-relative for portability.
|
|
53
95
|
return {
|
|
54
|
-
watchDir: path.resolve(process.cwd(), watchDir),
|
|
55
|
-
outputDir: path.resolve(process.cwd(), outputDir),
|
|
96
|
+
watchDir: toProjectRelativePath(path.resolve(process.cwd(), watchDir)),
|
|
97
|
+
outputDir: toProjectRelativePath(path.resolve(process.cwd(), outputDir)),
|
|
56
98
|
port: existingConfig?.port || "3000",
|
|
57
99
|
};
|
|
58
100
|
}
|
|
59
101
|
async getConfig(options = {}) {
|
|
60
102
|
let config = null;
|
|
103
|
+
let dirty = false;
|
|
61
104
|
if (!options.reset) {
|
|
62
105
|
config = await this.loadConfig();
|
|
63
106
|
}
|
|
64
107
|
if (!config || options.reset) {
|
|
65
108
|
console.log(chalk.blue("🔧 Setting up Doccupine configuration..."));
|
|
66
109
|
config = await this.promptForConfig(config || {});
|
|
67
|
-
|
|
110
|
+
dirty = true;
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
// Configs written before 0.0.129 stored absolute paths; rewrite them in
|
|
114
|
+
// place so the file can be committed and shared.
|
|
115
|
+
const normalized = normalizeConfigPaths(config);
|
|
116
|
+
if (normalized.changed) {
|
|
117
|
+
config = normalized.config;
|
|
118
|
+
dirty = true;
|
|
119
|
+
console.log(chalk.blue("🔁 Rewriting doccupine.json paths as project-relative"));
|
|
120
|
+
}
|
|
68
121
|
}
|
|
69
122
|
if (options.port) {
|
|
70
123
|
config.port = options.port;
|
|
124
|
+
dirty = true;
|
|
125
|
+
}
|
|
126
|
+
if (dirty) {
|
|
71
127
|
await this.saveConfig(config);
|
|
72
128
|
}
|
|
73
129
|
return config;
|
|
@@ -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 (
|
|
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\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";
|
|
@@ -25,20 +25,127 @@ const posthogKey =
|
|
|
25
25
|
const uiHost = (analyticsConfig.posthog?.host || "https://us.i.posthog.com")
|
|
26
26
|
.replace(".i.posthog.com", ".posthog.com");
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Adopt the session id the middleware already decided on (see proxy.ts), so the
|
|
30
|
+
* server's document-load \`$pageview\` and every client event after it land in
|
|
31
|
+
* the same session.
|
|
32
|
+
*
|
|
33
|
+
* Without this the two disagree: the middleware used to forward posthog-js's
|
|
34
|
+
* own session id without checking whether it had expired, so a returning
|
|
35
|
+
* reader's pageview was filed under a dead session and the real new session
|
|
36
|
+
* began with no pageview in it — wrong landing page, wrong bounce rate.
|
|
37
|
+
*
|
|
38
|
+
* Reading document.cookie works on the first request because the middleware
|
|
39
|
+
* sets the cookie on the same response that carries this HTML. Returns
|
|
40
|
+
* undefined if absent or malformed, in which case posthog-js mints its own id
|
|
41
|
+
* as before: degraded, never broken.
|
|
42
|
+
*/
|
|
43
|
+
// Both the middleware and this file WRITE the session cookie, so these three
|
|
44
|
+
// must stay identical to their counterparts in proxy.ts. They are duplicated
|
|
45
|
+
// rather than shared because a client component cannot import from the
|
|
46
|
+
// middleware. A drifted max-age here would silently expire live sessions.
|
|
47
|
+
const SESSION_COOKIE = "dcp_sid";
|
|
48
|
+
const SESSION_MAX_MS = 24 * 60 * 60 * 1000;
|
|
49
|
+
|
|
50
|
+
function isValidSessionId(id: string): boolean {
|
|
51
|
+
return /^[0-9a-f]{32}$/i.test(id.replace(/-/g, ""));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readSessionCookie(): { id: string; startTs: number } | undefined {
|
|
55
|
+
if (typeof document === "undefined") return undefined;
|
|
56
|
+
|
|
57
|
+
const match = document.cookie.match(/(?:^|;\\s*)dcp_sid=([^;]*)/);
|
|
58
|
+
if (!match) return undefined;
|
|
59
|
+
|
|
60
|
+
// Cookie is \`id.startTs.lastTs\`; posthog-js requires the id be a UUID and
|
|
61
|
+
// logs an error if not, so check before handing it over.
|
|
62
|
+
const [id, startRaw] = decodeURIComponent(match[1]).split(".");
|
|
63
|
+
const startTs = Number(startRaw);
|
|
64
|
+
if (!isValidSessionId(id) || !Number.isFinite(startTs)) return undefined;
|
|
65
|
+
|
|
66
|
+
return { id, startTs };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readEdgeSessionId(): string | undefined {
|
|
70
|
+
return readSessionCookie()?.id;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Keep the session cookie's last-activity fresh, from the browser.
|
|
75
|
+
*
|
|
76
|
+
* This is the half of session upkeep the middleware deliberately does NOT do.
|
|
77
|
+
* A response carrying \`Set-Cookie\` is not cacheable by Vercel's CDN, so
|
|
78
|
+
* refreshing last-activity server-side would have put one on roughly every doc
|
|
79
|
+
* page an engaged reader loads. A \`document.cookie\` write sets no response
|
|
80
|
+
* header at all, so your doc pages stay cacheable — and the browser is the side
|
|
81
|
+
* that actually sees soft navigations and in-page activity.
|
|
82
|
+
*
|
|
83
|
+
* \`startTs\` is carried forward while the id is unchanged, so the 24h hard cap
|
|
84
|
+
* still measures from when the session really began; a rotation restarts it.
|
|
85
|
+
*/
|
|
86
|
+
function syncSessionCookie(sessionId: string | undefined) {
|
|
87
|
+
if (typeof document === "undefined" || !sessionId) return;
|
|
88
|
+
if (!isValidSessionId(sessionId)) return;
|
|
89
|
+
|
|
90
|
+
const now = Date.now();
|
|
91
|
+
const existing = readSessionCookie();
|
|
92
|
+
const startTs = existing?.id === sessionId ? existing.startTs : now;
|
|
93
|
+
const secure = location.protocol === "https:" ? "; secure" : "";
|
|
94
|
+
|
|
95
|
+
document.cookie =
|
|
96
|
+
SESSION_COOKIE +
|
|
97
|
+
"=" +
|
|
98
|
+
sessionId +
|
|
99
|
+
"." +
|
|
100
|
+
startTs +
|
|
101
|
+
"." +
|
|
102
|
+
now +
|
|
103
|
+
"; path=/; max-age=" +
|
|
104
|
+
SESSION_MAX_MS / 1000 +
|
|
105
|
+
"; samesite=lax" +
|
|
106
|
+
secure;
|
|
107
|
+
}
|
|
108
|
+
|
|
28
109
|
function PostHogInit({ onReady }: { onReady: () => void }) {
|
|
29
110
|
const initRef = useRef(false);
|
|
30
111
|
|
|
31
112
|
useEffect(() => {
|
|
32
|
-
if (
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
113
|
+
if (!posthogKey) return;
|
|
114
|
+
|
|
115
|
+
// The init guard deliberately does NOT wrap the subscription below.
|
|
116
|
+
//
|
|
117
|
+
// Under React StrictMode's dev double-invoke the effect runs, is cleaned
|
|
118
|
+
// up, then runs again. With an early \`return\` here, that second run would
|
|
119
|
+
// skip past the subscription and leave \`onSessionId\` permanently
|
|
120
|
+
// unsubscribed — in dev only, which is precisely where you would go to
|
|
121
|
+
// check that any of this works. Initialising once while re-subscribing on
|
|
122
|
+
// every run is correct in both modes.
|
|
123
|
+
if (!initRef.current) {
|
|
124
|
+
initRef.current = true;
|
|
125
|
+
|
|
126
|
+
const sessionID = readEdgeSessionId();
|
|
127
|
+
|
|
128
|
+
posthog.init(posthogKey, {
|
|
129
|
+
api_host: "/ingest",
|
|
130
|
+
ui_host: uiHost,
|
|
131
|
+
capture_pageview: false,
|
|
132
|
+
capture_pageleave: true,
|
|
133
|
+
// The middleware owns session identity; this makes the SDK agree.
|
|
134
|
+
...(sessionID ? { bootstrap: { sessionID } } : {}),
|
|
135
|
+
loaded: (ph) => {
|
|
136
|
+
// Write once at startup so a session the middleware adopted (and
|
|
137
|
+
// therefore did not rewrite) still gets its last-activity advanced.
|
|
138
|
+
syncSessionCookie(ph.get_session_id());
|
|
139
|
+
onReady();
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Fires when the session id first appears and on every rotation, so the
|
|
145
|
+
// cookie follows posthog-js rather than drifting from it. posthog-js is the
|
|
146
|
+
// better judge of idleness — it sees every captured event, not just
|
|
147
|
+
// navigations. Returning its unsubscribe doubles as the effect cleanup.
|
|
148
|
+
return posthog.onSessionId((id: string) => syncSessionCookie(id));
|
|
42
149
|
}, [onReady]);
|
|
43
150
|
|
|
44
151
|
return null;
|
|
@@ -67,6 +174,12 @@ function PostHogPageviewTracker() {
|
|
|
67
174
|
? \`\${pathname}?\${searchParams.toString()}\`
|
|
68
175
|
: pathname;
|
|
69
176
|
posthog.capture("$pageview", { $current_url: url });
|
|
177
|
+
|
|
178
|
+
// A soft navigation is activity the middleware never sees, and
|
|
179
|
+
// \`onSessionId\` won't fire because the id hasn't changed. Without this, a
|
|
180
|
+
// reader who browses only via client-side links would look idle to the
|
|
181
|
+
// next document load and have their session rotated out from under them.
|
|
182
|
+
syncSessionCookie(posthog.get_session_id());
|
|
70
183
|
}
|
|
71
184
|
}, [pathname, searchParams]);
|
|
72
185
|
|
|
@@ -24,8 +24,8 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
24
24
|
minisearch: "^7.2.0",
|
|
25
25
|
next: "16.2.10",
|
|
26
26
|
"next-mdx-remote": "^6.0.0",
|
|
27
|
-
"posthog-js": "^1.
|
|
28
|
-
"posthog-node": "^5.
|
|
27
|
+
"posthog-js": "^1.405.3",
|
|
28
|
+
"posthog-node": "^5.46.0",
|
|
29
29
|
react: "19.2.7",
|
|
30
30
|
"react-dom": "19.2.7",
|
|
31
31
|
"rehype-highlight": "^7.0.2",
|
|
@@ -51,7 +51,7 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
51
51
|
"eslint-plugin-react": "^7.37.5",
|
|
52
52
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
53
53
|
globals: "^17.7.0",
|
|
54
|
-
prettier: "^3.9.
|
|
54
|
+
prettier: "^3.9.6",
|
|
55
55
|
tsx: "^4.23.1",
|
|
56
56
|
typescript: "npm:@typescript/typescript6@^6.0.2",
|
|
57
57
|
},
|
package/dist/templates/proxy.js
CHANGED
|
@@ -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
|
|
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\`
|
|
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
|
-
|
|
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,
|
|
137
|
+
if (anonId) return { distinctId: anonId, deviceId, ...session };
|
|
67
138
|
|
|
68
139
|
const minted = crypto.randomUUID();
|
|
69
|
-
return { distinctId: minted, anonIdToPersist: minted,
|
|
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.
|
|
3
|
+
"version": "0.0.130",
|
|
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": {
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@types/fs-extra": "^11.0.4",
|
|
49
49
|
"@types/node": "^26.1.1",
|
|
50
50
|
"@types/prompts": "^2.4.9",
|
|
51
|
-
"prettier": "^3.9.
|
|
51
|
+
"prettier": "^3.9.6",
|
|
52
52
|
"typescript": "^7.0.2",
|
|
53
53
|
"vitest": "^4.1.10"
|
|
54
54
|
},
|