@commentkit/comment-kit 1.6.0 → 2.0.1
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/CHANGELOG.md +298 -590
- package/README.md +421 -145
- package/SECURITY.md +47 -46
- package/dist/node/THIRD_PARTY_NOTICES.txt +56 -0
- package/dist/node/browser.js +17 -0
- package/dist/node/cli/api.js +226 -0
- package/dist/node/cli/bin.js +18 -0
- package/dist/node/cli/credentials.js +268 -0
- package/dist/node/cli/doctor.js +789 -0
- package/dist/node/cli/format.js +54 -0
- package/dist/node/cli/init.js +686 -0
- package/dist/node/cli/main.js +537 -0
- package/dist/node/cli/mcp.js +295 -0
- package/dist/node/cli/open.js +20 -0
- package/dist/node/plugins/astro-B5y1Gtbf.js +31 -0
- package/dist/node/plugins/astro.js +26 -0
- package/dist/node/plugins/git-BIXLbL3f.js +92 -0
- package/dist/node/plugins/jsx-Bg4BdSph.js +7958 -0
- package/dist/node/plugins/next.js +48 -0
- package/dist/node/plugins/options-THop1K92.js +71 -0
- package/dist/node/plugins/transform-CKiAuSbk.js +1155 -0
- package/dist/node/plugins/vite-BdAYUW10.js +74 -0
- package/dist/node/plugins/vite.js +1 -0
- package/dist/node/plugins/webpack-R2U2DLlY.js +35 -0
- package/dist/node/plugins/webpack-loader.cjs +21 -0
- package/dist/node/plugins/webpack-loader.js +18 -0
- package/dist/node/plugins/webpack.js +1 -0
- package/dist/node/shared/dashboard-places.js +33 -0
- package/dist/node/shared/endpoint.js +26 -0
- package/dist/node/shared/format.js +63 -0
- package/dist/node/types/astro.d.ts +11 -0
- package/dist/node/types/next.d.ts +34 -0
- package/dist/node/types/options.d.ts +59 -0
- package/dist/node/types/vite.d.ts +11 -0
- package/dist/node/types/webpack-loader.d.ts +22 -0
- package/dist/node/types/webpack.d.ts +27 -0
- package/dist/npm/THIRD_PARTY_NOTICES.txt +6 -6
- package/dist/npm/chunks/AgentSend-DOy3jhyF.js +68 -0
- package/dist/npm/chunks/Checklist-CW_SwMpS.js +282 -0
- package/dist/npm/chunks/Composer-Bveq5QrK.js +727 -0
- package/dist/npm/chunks/Guest-7hcN765o.js +270 -0
- package/dist/npm/chunks/MarkupEditor-6bJGpWGO.js +345 -0
- package/dist/npm/chunks/Panel-ChPUB68C.js +1211 -0
- package/dist/npm/chunks/Settings-CB5eEKnf.js +231 -0
- package/dist/npm/chunks/Shortcuts-eAyjJ89P.js +62 -0
- package/dist/npm/chunks/StyleEditor-CZTdAA5c.js +46 -0
- package/dist/npm/chunks/StylePanel-B4pHQUL9.js +199 -0
- package/dist/npm/chunks/TaskFields-C8BX0Sgg.js +289 -0
- package/dist/npm/chunks/ThreadCard-B1EsX3PR.js +1160 -0
- package/dist/npm/chunks/Viewer-DY6zb90M.js +114 -0
- package/dist/npm/chunks/{agent-BDMQtOzH.js → agent-MTQHr9ei.js} +9 -9
- package/dist/npm/chunks/{anchor-BsradQhn.js → anchor-BsQNVkHj.js} +108 -85
- package/dist/npm/chunks/{ar-8tPch6W4.js → ar-L5cQ-NPe.js} +71 -19
- package/dist/npm/chunks/card-bits-CTdrkYn8.js +53 -0
- package/dist/npm/chunks/{client-EFTWxHbJ.js → client-7eVxvg5j.js} +282 -290
- package/dist/npm/chunks/confetti-BIs5s14P.js +49 -0
- package/dist/npm/chunks/context-BuMl7A07.js +48 -0
- package/dist/npm/chunks/context-Cf6khm7A.js +20 -0
- package/dist/npm/chunks/{de-C63897uD.js → de-D0C-v6tP.js} +62 -18
- package/dist/npm/chunks/dialog-DvdIkCW0.js +3 -0
- package/dist/npm/chunks/dpop-0A76OPa9.js +96 -0
- package/dist/npm/chunks/drafts-B0ctr1g9.js +21 -0
- package/dist/npm/chunks/{es-CI2bSpvB.js → es-Bw4Dj9tN.js} +62 -18
- package/dist/npm/chunks/extension-DFVOvciD.js +62 -0
- package/dist/npm/chunks/{extension-BST6LH1q.js → extension-SmoH5AA4.js} +20 -12
- package/dist/npm/chunks/files-4lV9YQIX.js +114 -0
- package/dist/npm/chunks/{fr-rsVe-Lqk.js → fr-TkuQaIAa.js} +120 -76
- package/dist/npm/chunks/{hi-cvwbSaWP.js → hi-DXSH2U8d.js} +63 -19
- package/dist/npm/chunks/{i18n-C4v0M-6z.js → i18n-aVSu9TcJ.js} +136 -92
- package/dist/npm/chunks/identify-BGYh2dVo.js +106 -0
- package/dist/npm/chunks/{it-C8tnV0BF.js → it-CiWA_bch.js} +81 -37
- package/dist/npm/chunks/{ja-BWxDfC2f.js → ja-C-QmR3yz.js} +60 -16
- package/dist/npm/chunks/late-words-80_VWt8S.js +14 -0
- package/dist/npm/chunks/live-BExWHzQ7.js +85 -0
- package/dist/npm/chunks/locale-D8Q4Q2Nt.js +26 -0
- package/dist/npm/chunks/{nl-DNQ6eCht.js → nl-CEmZRqjX.js} +63 -19
- package/dist/npm/chunks/page-key-HSY3Lze5.js +62 -0
- package/dist/npm/chunks/{pick-CLyOdjnD.js → pick-B3sR7jtS.js} +45 -44
- package/dist/npm/chunks/pkce-CfZhiNBi.js +8 -0
- package/dist/npm/chunks/placement-BF_HOUDD.js +74 -0
- package/dist/npm/chunks/privacy-BWUGlHw5.js +57 -0
- package/dist/npm/chunks/{pt-BR-CkG7vpU2.js → pt-BR-b-a8sxO8.js} +62 -18
- package/dist/npm/chunks/{realtime-DIo-Wth4.js → realtime-C79zF50C.js} +14 -12
- package/dist/npm/chunks/report-DaVuoRYS.js +44 -0
- package/dist/npm/chunks/show-BoN8AC-F.js +97 -0
- package/dist/npm/chunks/signin-BOWr_WCo.js +75 -0
- package/dist/npm/chunks/{source-CS7C6wJA.js → source-mk3rGBBQ.js} +1 -1
- package/dist/npm/chunks/src-C8rZFyL_.js +215 -0
- package/dist/npm/chunks/start-CV4j78_q.js +1894 -0
- package/dist/npm/chunks/states-b9Bv3Ci7.js +3 -0
- package/dist/npm/chunks/upload-B2mkgMeJ.js +42 -0
- package/dist/npm/chunks/uploads-8AxyRq7g.js +1147 -0
- package/dist/npm/chunks/wrap-DW6EFbVQ.js +69 -0
- package/dist/npm/chunks/{zh-CN-BKuZOLBE.js → zh-CN-JTscW8u8.js} +61 -17
- package/dist/npm/element.js +58 -21
- package/dist/npm/headless.js +7 -3
- package/dist/npm/index.js +3 -3
- package/dist/npm/react.js +18 -11
- package/dist/npm/svelte.js +28 -12
- package/dist/npm/types/adapters/react.d.ts +4 -1
- package/dist/npm/types/adapters/svelte.d.ts +4 -1
- package/dist/npm/types/adapters/vue.d.ts +35 -2
- package/dist/npm/types/anchor/index.d.ts +19 -0
- package/dist/npm/types/capture/privacy.d.ts +14 -0
- package/dist/npm/types/core/api.d.ts +20 -1
- package/dist/npm/types/core/auth.d.ts +40 -21
- package/dist/npm/types/core/client.d.ts +60 -4
- package/dist/npm/types/core/page-key.d.ts +42 -0
- package/dist/npm/types/core/types.d.ts +87 -4
- package/dist/npm/types/element.d.ts +17 -7
- package/dist/npm/types/headless.d.ts +2 -1
- package/dist/npm/types/index.d.ts +16 -6
- package/dist/npm/vue.js +44 -9
- package/package.json +90 -14
- package/dist/npm/chunks/AgentSend-2JPDseOo.js +0 -63
- package/dist/npm/chunks/Checklist-BpDXQebo.js +0 -257
- package/dist/npm/chunks/Composer-CAyj-c8e.js +0 -677
- package/dist/npm/chunks/Guest-ZdFmTcXI.js +0 -187
- package/dist/npm/chunks/MarkupEditor-BFplZwFy.js +0 -332
- package/dist/npm/chunks/Panel-BhZ4XRDR.js +0 -861
- package/dist/npm/chunks/Settings-SPG9EHUZ.js +0 -204
- package/dist/npm/chunks/Shortcuts-C28HVDw6.js +0 -58
- package/dist/npm/chunks/StyleEditor-ByZMtq10.js +0 -43
- package/dist/npm/chunks/StylePanel-Iwhce2tE.js +0 -197
- package/dist/npm/chunks/TaskFields-BsP_fVJg.js +0 -273
- package/dist/npm/chunks/ThreadCard-BzVZdDCb.js +0 -1030
- package/dist/npm/chunks/Viewer-CqtGrdD8.js +0 -108
- package/dist/npm/chunks/card-bits-Bna-g3Py.js +0 -124
- package/dist/npm/chunks/confetti-DTKpwF3O.js +0 -40
- package/dist/npm/chunks/drafts-akdBsOd0.js +0 -50
- package/dist/npm/chunks/extension-D-V3utTm.js +0 -53
- package/dist/npm/chunks/live-BCpJVBeN.js +0 -33
- package/dist/npm/chunks/report-BBrT3r89.js +0 -27
- package/dist/npm/chunks/src-C4FsVoUp.js +0 -148
- package/dist/npm/chunks/start-i9M-r3aH.js +0 -1800
- package/dist/npm/chunks/upload-DSv7EyBD.js +0 -41
- package/dist/npm/chunks/uploads-I01kdqQF.js +0 -1103
|
@@ -0,0 +1,686 @@
|
|
|
1
|
+
// `npx @commentkit/comment-kit init`: find the framework, then add the key, the build plugin and the widget.
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, posix, resolve } from "node:path";
|
|
5
|
+
/** The Node versions the build plugins' source locations need (plugins/node-version.ts PLUGIN_NODE; a test keeps them equal). */
|
|
6
|
+
export const PLUGIN_NODE = "22.18 or 24.11";
|
|
7
|
+
export const PLUGIN_NODE_NOTE = `The build plugin's source locations need Node ${PLUGIN_NODE} or newer; on an older Node (a deploy server that builds, for example) it prints one warning and the build carries on without them.`;
|
|
8
|
+
function readJsonFile(file) {
|
|
9
|
+
try {
|
|
10
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
11
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** A Laravel app: `artisan` next to a composer.json that requires laravel/framework. */
|
|
18
|
+
export function isLaravel(dir) {
|
|
19
|
+
if (!existsSync(join(dir, "artisan")))
|
|
20
|
+
return false;
|
|
21
|
+
const composer = readJsonFile(join(dir, "composer.json"));
|
|
22
|
+
return Boolean(composer?.require?.["laravel/framework"] || composer?.["require-dev"]?.["laravel/framework"]);
|
|
23
|
+
}
|
|
24
|
+
function detect(dir) {
|
|
25
|
+
const pkg = readJsonFile(join(dir, "package.json"));
|
|
26
|
+
// No package.json: a plain website (or a Laravel app without a JavaScript build).
|
|
27
|
+
const deps = pkg ? { ...pkg.dependencies, ...pkg.devDependencies } : {};
|
|
28
|
+
// React Router 7 (framework mode) and Remix build with Vite but render the page from app/root: not a plain Vite app.
|
|
29
|
+
const reactRouter = deps["@react-router/dev"] || deps["@remix-run/dev"] || deps["@remix-run/react"];
|
|
30
|
+
// Laravel first: its apps also list vite, but keep their entries in resources/js and render pages from Blade.
|
|
31
|
+
const framework = isLaravel(dir) ? "laravel" : deps.next ? "next" : deps.astro ? "astro" : deps.nuxt ? "nuxt" : deps["@sveltejs/kit"] ? "sveltekit" : reactRouter ? "react-router" : deps.vite ? "vite" : "html";
|
|
32
|
+
return { framework, packageManager: packageManagerFor(dir), deps };
|
|
33
|
+
}
|
|
34
|
+
/** Lockfiles decide first: a stray pnpm-workspace.yaml next to package-lock.json is not a pnpm project. */
|
|
35
|
+
const LOCKFILES = [["package-lock.json", "npm"], ["npm-shrinkwrap.json", "npm"], ["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lock", "bun"], ["bun.lockb", "bun"]];
|
|
36
|
+
/** Weaker hints, used only when a folder has neither a lockfile nor "packageManager". */
|
|
37
|
+
const HINTS = [["pnpm-workspace.yaml", "pnpm"], [".yarnrc.yml", "yarn"], ["bunfig.toml", "bun"]];
|
|
38
|
+
/**
|
|
39
|
+
* The package manager of the project, or of the workspace it belongs to: the nearest folder (this one or
|
|
40
|
+
* a parent, up to the repository root or the home folder) that has a lockfile, names one in package.json
|
|
41
|
+
* ("packageManager": "pnpm@9…") or has another hint (pnpm-workspace.yaml). In each folder a lockfile wins;
|
|
42
|
+
* with lockfiles of two managers, "packageManager" breaks the tie. npm when nothing says.
|
|
43
|
+
*/
|
|
44
|
+
export function packageManagerFor(dir, home = homedir()) {
|
|
45
|
+
let current = resolve(dir);
|
|
46
|
+
for (;;) {
|
|
47
|
+
const declared = /^(npm|pnpm|yarn|bun)@/.exec(String(readJsonFile(join(current, "package.json"))?.packageManager ?? ""))?.[1];
|
|
48
|
+
const locks = [...new Set(LOCKFILES.filter(([file]) => existsSync(join(current, file))).map(([, pm]) => pm))];
|
|
49
|
+
if (locks.length)
|
|
50
|
+
return declared && locks.includes(declared) ? declared : locks[0];
|
|
51
|
+
if (declared)
|
|
52
|
+
return declared;
|
|
53
|
+
const hint = HINTS.find(([file]) => existsSync(join(current, file)));
|
|
54
|
+
if (hint)
|
|
55
|
+
return hint[1];
|
|
56
|
+
const parent = dirname(current);
|
|
57
|
+
if (parent === current || current === resolve(home) || existsSync(join(current, ".git")))
|
|
58
|
+
return "npm";
|
|
59
|
+
current = parent;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const first = (dir, names) => names.find((n) => existsSync(join(dir, n))) ?? null;
|
|
63
|
+
/** 1 for each character of `source` that is code; 0 inside strings, template literals and comments. */
|
|
64
|
+
function codeMask(source) {
|
|
65
|
+
const mask = new Uint8Array(source.length);
|
|
66
|
+
let i = 0;
|
|
67
|
+
while (i < source.length) {
|
|
68
|
+
const c = source[i];
|
|
69
|
+
if (c === "/" && source[i + 1] === "/") {
|
|
70
|
+
while (i < source.length && source[i] !== "\n")
|
|
71
|
+
i++;
|
|
72
|
+
}
|
|
73
|
+
else if (c === "/" && source[i + 1] === "*") {
|
|
74
|
+
const end = source.indexOf("*/", i + 2);
|
|
75
|
+
i = end < 0 ? source.length : end + 2;
|
|
76
|
+
}
|
|
77
|
+
else if (c === '"' || c === "'" || c === "`") {
|
|
78
|
+
i++;
|
|
79
|
+
while (i < source.length && source[i] !== c && !(c !== "`" && source[i] === "\n"))
|
|
80
|
+
i += source[i] === "\\" ? 2 : 1;
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
mask[i++] = 1;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return mask;
|
|
88
|
+
}
|
|
89
|
+
/** How many `{` enclose each character, counting code only. */
|
|
90
|
+
function braceDepths(source, mask) {
|
|
91
|
+
const depths = new Int32Array(source.length);
|
|
92
|
+
let depth = 0;
|
|
93
|
+
for (let i = 0; i < source.length; i++) {
|
|
94
|
+
if (mask[i] && source[i] === "}")
|
|
95
|
+
depth--;
|
|
96
|
+
depths[i] = depth;
|
|
97
|
+
if (mask[i] && source[i] === "{")
|
|
98
|
+
depth++;
|
|
99
|
+
}
|
|
100
|
+
return depths;
|
|
101
|
+
}
|
|
102
|
+
/** The index of the bracket that closes the one at `open`, or -1 when brackets do not balance. */
|
|
103
|
+
function closing(source, mask, open) {
|
|
104
|
+
const pairs = { "(": ")", "[": "]", "{": "}" };
|
|
105
|
+
const stack = [];
|
|
106
|
+
for (let i = open; i < source.length; i++) {
|
|
107
|
+
if (!mask[i])
|
|
108
|
+
continue;
|
|
109
|
+
const c = source[i];
|
|
110
|
+
if (pairs[c])
|
|
111
|
+
stack.push(pairs[c]);
|
|
112
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
113
|
+
if (stack.pop() !== c)
|
|
114
|
+
return -1;
|
|
115
|
+
if (!stack.length)
|
|
116
|
+
return i;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return -1;
|
|
120
|
+
}
|
|
121
|
+
/** A build config that already imports a CommentKit build plugin. */
|
|
122
|
+
export const PLUGIN_IMPORT = /["']@commentkit\/comment-kit\/(?:vite|next|webpack|astro)["']/;
|
|
123
|
+
/**
|
|
124
|
+
* Add `import line` after the last import and `call` as the first item of `key: [`. Only a `key: [` at
|
|
125
|
+
* the top level of the config object counts (never, say, css.postcss.plugins), and there must be exactly
|
|
126
|
+
* one. Null when the shape is unusual: the person gets the snippet instead.
|
|
127
|
+
*/
|
|
128
|
+
export function addToArray(source, key, call, importLine) {
|
|
129
|
+
if (PLUGIN_IMPORT.test(source))
|
|
130
|
+
return source; // already set up
|
|
131
|
+
const mask = codeMask(source);
|
|
132
|
+
const depths = braceDepths(source, mask);
|
|
133
|
+
const hits = [...source.matchAll(new RegExp(`\\b${key}\\s*:\\s*\\[`, "g"))].filter((m) => mask[m.index] && depths[m.index] === 1);
|
|
134
|
+
if (hits.length !== 1)
|
|
135
|
+
return null;
|
|
136
|
+
const at = hits[0].index;
|
|
137
|
+
const open = source.indexOf("[", at) + 1;
|
|
138
|
+
// A list written one item per line gets commentkit() on its own line, indented like the first item.
|
|
139
|
+
const lead = /^[ \t]*\r?\n[ \t]*(?=[^\s\]])/.exec(source.slice(open))?.[0];
|
|
140
|
+
if (lead)
|
|
141
|
+
return withImport(`${source.slice(0, open)}${lead}${call},${source.slice(open)}`, importLine);
|
|
142
|
+
let out = `${source.slice(0, open)}${call}, ${source.slice(open).replace(/^\s*(?=\])/, "")}`;
|
|
143
|
+
out = out.replace(new RegExp(`\\[${call.replace(/[()]/g, "\\$&")}, \\]`), `[${call}]`);
|
|
144
|
+
return withImport(out, importLine);
|
|
145
|
+
}
|
|
146
|
+
/** Where the last top-level import statement ends (multi-line imports included), or after leading directives. */
|
|
147
|
+
function importsEnd(source) {
|
|
148
|
+
let end = -1;
|
|
149
|
+
for (const start of source.matchAll(/^import\b/gm)) {
|
|
150
|
+
if (start.index < end)
|
|
151
|
+
continue;
|
|
152
|
+
// An import ends at its module string: `from "x"` or a bare `import "x"`, then an optional semicolon.
|
|
153
|
+
const tail = /(?:\bfrom\s*|^import\s*)(["'])[^"'\n]+\1[ \t]*;?/m.exec(source.slice(start.index));
|
|
154
|
+
if (!tail)
|
|
155
|
+
break;
|
|
156
|
+
end = start.index + tail.index + tail[0].length;
|
|
157
|
+
}
|
|
158
|
+
if (end >= 0)
|
|
159
|
+
return end;
|
|
160
|
+
const directives = /^(?:\s*(["'])use [a-z ]+\1;?[ \t]*\n)+/.exec(source);
|
|
161
|
+
return directives ? directives[0].length - 1 : -1;
|
|
162
|
+
}
|
|
163
|
+
function withImport(source, importLine) {
|
|
164
|
+
const end = importsEnd(source);
|
|
165
|
+
if (end < 0)
|
|
166
|
+
return `${importLine}\n${source}`;
|
|
167
|
+
return `${source.slice(0, end)}\n${importLine}${source.slice(end)}`;
|
|
168
|
+
}
|
|
169
|
+
/** The widget is already set up in this file. */
|
|
170
|
+
const HAS_WIDGET = /@commentkit\/comment-kit|commentkit\.dev\/cdn\/|loader\.js["'][^>]*data-project/;
|
|
171
|
+
/** The CDN script tag (any version folder), as a page or template writes it. */
|
|
172
|
+
const LOADER_TAG = /<script\b[^>]*\bsrc\s*=\s*["']?[^"'\s>]*\/cdn\/[^"'\s>/]+\/loader\.js[^>]*>/i;
|
|
173
|
+
const VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
|
|
174
|
+
const SCRIPT_FILE = /\.(?:[mc]?[jt]sx?)$/;
|
|
175
|
+
const LARAVEL_ENTRIES = ["resources/js/app.ts", "resources/js/app.tsx", "resources/js/app.js", "resources/js/app.jsx"];
|
|
176
|
+
/** The string literals between the bracket at `open` and the one that closes it. */
|
|
177
|
+
function literalsIn(source, mask, open) {
|
|
178
|
+
const close = source[open] === "[" || source[open] === "{" || source[open] === "(" ? closing(source, mask, open) : -1;
|
|
179
|
+
if (close < 0)
|
|
180
|
+
return [];
|
|
181
|
+
return [...source.slice(open, close).matchAll(/(["'`])((?:(?!\1)[^\\\n$])*)\1/g)].map((m) => m[2]);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Script entries a Vite config names: `input: "…"`, `input: [...]` or `input: { name: "…" }` (Rollup and
|
|
185
|
+
* laravel-vite-plugin), and laravel([...]) / laravel("…") shorthand. Stylesheets and other files are left out.
|
|
186
|
+
*/
|
|
187
|
+
export function viteInputs(source) {
|
|
188
|
+
const mask = codeMask(source);
|
|
189
|
+
const found = [];
|
|
190
|
+
for (const m of source.matchAll(/\b(?:input\s*:|laravel\s*\()\s*/g)) {
|
|
191
|
+
if (!mask[m.index])
|
|
192
|
+
continue;
|
|
193
|
+
const at = m.index + m[0].length;
|
|
194
|
+
const c = source[at];
|
|
195
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
196
|
+
const end = source.indexOf(c, at + 1);
|
|
197
|
+
if (end > at)
|
|
198
|
+
found.push(source.slice(at + 1, end));
|
|
199
|
+
}
|
|
200
|
+
else if (c === "[" || (c === "{" && m[0].startsWith("input"))) {
|
|
201
|
+
found.push(...literalsIn(source, mask, at));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return [...new Set(found.map((f) => f.replace(/^\.?\//, "")).filter((f) => SCRIPT_FILE.test(f) && !f.includes("..")))];
|
|
205
|
+
}
|
|
206
|
+
/** The script files a Vite config's `input` names that exist in `dir`. */
|
|
207
|
+
function viteConfigEntries(dir) {
|
|
208
|
+
const config = first(dir, VITE_CONFIGS);
|
|
209
|
+
if (!config)
|
|
210
|
+
return [];
|
|
211
|
+
return viteInputs(readFileSync(join(dir, config), "utf8")).filter((f) => existsSync(join(dir, f)));
|
|
212
|
+
}
|
|
213
|
+
/** Laravel's JavaScript entries: what vite.config's input names, then resources/js/app.{ts,tsx,js,jsx}. */
|
|
214
|
+
export function laravelEntries(dir) {
|
|
215
|
+
return [...new Set([...viteConfigEntries(dir), ...LARAVEL_ENTRIES.filter((f) => existsSync(join(dir, f)))])];
|
|
216
|
+
}
|
|
217
|
+
/** The import specifiers of a module (static imports, side-effect imports and import()). */
|
|
218
|
+
function importsOf(source) {
|
|
219
|
+
const mask = codeMask(source);
|
|
220
|
+
const found = [];
|
|
221
|
+
for (const m of source.matchAll(/\b(?:import|export)\s*(?:[\w*${}\s,]+?\s*from\s*)?(["'])([^"'\n]+)\1|\bimport\s*\(\s*(["'])([^"'\n]+)\3\s*\)/g)) {
|
|
222
|
+
if (mask[m.index])
|
|
223
|
+
found.push(m[2] ?? m[4]);
|
|
224
|
+
}
|
|
225
|
+
return found;
|
|
226
|
+
}
|
|
227
|
+
/** A relative or aliased import (`./x`, `@/x` and `~/x` meaning resources/js in Laravel) as a file in `dir`, or null. */
|
|
228
|
+
function resolveImport(dir, from, spec, laravel) {
|
|
229
|
+
let base;
|
|
230
|
+
if (spec.startsWith("./") || spec.startsWith("../"))
|
|
231
|
+
base = posix.join(posix.dirname(from), spec);
|
|
232
|
+
else if (laravel && /^[@~]\//.test(spec))
|
|
233
|
+
base = posix.join("resources/js", spec.slice(2));
|
|
234
|
+
else
|
|
235
|
+
return null;
|
|
236
|
+
if (base.startsWith(".."))
|
|
237
|
+
return null;
|
|
238
|
+
const candidates = [base, ...[".ts", ".tsx", ".js", ".jsx", ".mjs", ".mts"].map((e) => base + e), ...["ts", "tsx", "js", "jsx"].map((e) => `${base}/index.${e}`)];
|
|
239
|
+
return candidates.find((f) => SCRIPT_FILE.test(f) && existsSync(join(dir, f)) && statSync(join(dir, f)).isFile()) ?? null;
|
|
240
|
+
}
|
|
241
|
+
const KEY_LITERAL = /\bpk_(?:live|test)_[a-z0-9]{20,40}\b/;
|
|
242
|
+
/** Is the widget set up in one of `entries`, or in a file one of them imports directly? */
|
|
243
|
+
export function widgetInEntries(dir, entries, laravel = false) {
|
|
244
|
+
const read = (file) => readFileSync(join(dir, file), "utf8");
|
|
245
|
+
const place = (file, text, via) => ({ file, ...(via ? { via } : {}), ...(KEY_LITERAL.test(text) ? { key: KEY_LITERAL.exec(text)[0] } : {}) });
|
|
246
|
+
for (const entry of entries) {
|
|
247
|
+
const text = read(entry);
|
|
248
|
+
if (HAS_WIDGET.test(text))
|
|
249
|
+
return place(entry, text);
|
|
250
|
+
}
|
|
251
|
+
for (const entry of entries) {
|
|
252
|
+
for (const spec of importsOf(read(entry))) {
|
|
253
|
+
const file = resolveImport(dir, entry, spec, laravel);
|
|
254
|
+
if (!file)
|
|
255
|
+
continue;
|
|
256
|
+
const text = read(file);
|
|
257
|
+
if (HAS_WIDGET.test(text))
|
|
258
|
+
return place(file, text, entry);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
const MAX_TEMPLATES = 3000;
|
|
264
|
+
/** Blade templates under resources/views (at most 3000), as paths relative to `dir`. */
|
|
265
|
+
export function bladeFiles(dir) {
|
|
266
|
+
const out = [];
|
|
267
|
+
const walk = (rel) => {
|
|
268
|
+
let names;
|
|
269
|
+
try {
|
|
270
|
+
names = readdirSync(join(dir, rel)).sort();
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
for (const name of names) {
|
|
276
|
+
if (out.length >= MAX_TEMPLATES)
|
|
277
|
+
return;
|
|
278
|
+
const path = `${rel}/${name}`;
|
|
279
|
+
let isDir = false;
|
|
280
|
+
try {
|
|
281
|
+
isDir = statSync(join(dir, path)).isDirectory();
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
if (isDir)
|
|
287
|
+
walk(path);
|
|
288
|
+
else if (name.endsWith(".blade.php"))
|
|
289
|
+
out.push(path);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
walk("resources/views");
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
/** HTML pages served as they are from public/ (top level only). */
|
|
296
|
+
function publicHtml(dir) {
|
|
297
|
+
try {
|
|
298
|
+
return readdirSync(join(dir, "public")).filter((f) => f.endsWith(".html")).sort().map((f) => `public/${f}`);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
return [];
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** Blade templates and public/*.html files that hold the CommentKit script tag. */
|
|
305
|
+
export function templatesWithTag(dir) {
|
|
306
|
+
const found = [];
|
|
307
|
+
for (const file of [...bladeFiles(dir), ...publicHtml(dir)]) {
|
|
308
|
+
const text = readFileSync(join(dir, file), "utf8");
|
|
309
|
+
const tag = LOADER_TAG.exec(text)?.[0];
|
|
310
|
+
if (!tag)
|
|
311
|
+
continue;
|
|
312
|
+
const key = /\bdata-project\s*=\s*["']?(pk_(?:live|test)_[a-z0-9]{20,40})\b/.exec(tag)?.[1] ?? /[?&]project=(pk_(?:live|test)_[a-z0-9]{20,40})\b/.exec(tag)?.[1];
|
|
313
|
+
found.push({ file, ...(key ? { key } : {}) });
|
|
314
|
+
}
|
|
315
|
+
return found;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Where the widget is set up, for the frameworks whose entry init can find more than one way: a Vite app's
|
|
319
|
+
* entry (index.html's module script or the config's `input`), a Laravel app's entries, a file one of them
|
|
320
|
+
* imports directly, or (Laravel) the script tag in a Blade layout or public/*.html. Null when none is found.
|
|
321
|
+
*/
|
|
322
|
+
export function findWidget(dir, framework) {
|
|
323
|
+
if (framework === "laravel")
|
|
324
|
+
return widgetInEntries(dir, laravelEntries(dir), true) ?? templatesWithTag(dir)[0] ?? null;
|
|
325
|
+
if (framework === "vite")
|
|
326
|
+
return widgetInEntries(dir, viteEntries(dir));
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
/** A Vite app's entries: index.html's module script, the config's `input`, then src/main.* and src/index.*. */
|
|
330
|
+
function viteEntries(dir) {
|
|
331
|
+
const out = [];
|
|
332
|
+
if (existsSync(join(dir, "index.html"))) {
|
|
333
|
+
const src = /<script\b[^>]*\btype=["']module["'][^>]*\bsrc=["']\/?([^"'?#]+\.(?:[mc]?[jt]sx?))["']/i.exec(readFileSync(join(dir, "index.html"), "utf8"))?.[1];
|
|
334
|
+
if (src && !src.includes("..") && existsSync(join(dir, src)))
|
|
335
|
+
out.push(src);
|
|
336
|
+
}
|
|
337
|
+
out.push(...viteConfigEntries(dir));
|
|
338
|
+
out.push(...["src/main.ts", "src/main.tsx", "src/main.js", "src/main.jsx", "src/index.ts", "src/index.tsx", "src/index.js", "src/index.jsx"].filter((f) => existsSync(join(dir, f))));
|
|
339
|
+
return [...new Set(out)];
|
|
340
|
+
}
|
|
341
|
+
/** The quote character most of a file's imports use (Laravel's Prettier setup uses single quotes). */
|
|
342
|
+
function quoteOf(source) {
|
|
343
|
+
let single = (source.match(/\bfrom\s*'|\bimport\s*'/g) ?? []).length;
|
|
344
|
+
let double = (source.match(/\bfrom\s*"|\bimport\s*"/g) ?? []).length;
|
|
345
|
+
if (!single && !double) {
|
|
346
|
+
// No imports yet: the quotes the file's strings use.
|
|
347
|
+
single = (source.match(/'/g) ?? []).length;
|
|
348
|
+
double = (source.match(/"/g) ?? []).length;
|
|
349
|
+
}
|
|
350
|
+
return single > double ? "'" : '"';
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Add CommentKit to a Laravel JavaScript entry: the import, then init() with the key as the default, so a
|
|
354
|
+
* server builds it without a new environment variable (VITE_COMMENTKIT_KEY still overrides it). `vite`
|
|
355
|
+
* false (Laravel Mix) has no import.meta.env, so the key is passed as it is.
|
|
356
|
+
*/
|
|
357
|
+
export function laravelInit(source, key, vite = true) {
|
|
358
|
+
const q = quoteOf(source);
|
|
359
|
+
const mask = codeMask(source);
|
|
360
|
+
// A name `init` the file already has (its own function, another library's import) keeps its meaning.
|
|
361
|
+
const taken = [...source.matchAll(/\binit\b/g)].some((m) => mask[m.index]);
|
|
362
|
+
const name = taken ? "initCommentKit" : "init";
|
|
363
|
+
const semi = /;\s*$/m.test(source) || source.trim() === "" ? ";" : "";
|
|
364
|
+
const importLine = `import { ${taken ? "init as initCommentKit" : "init"} } from ${q}@commentkit/comment-kit${q}${semi}`;
|
|
365
|
+
const project = vite ? `import.meta.env.VITE_COMMENTKIT_KEY || ${q}${key}${q}` : `${q}${key}${q}`;
|
|
366
|
+
return `${withImport(source, importLine).replace(/\s*$/, "\n")}\n${name}({ project: ${project} })${semi}\n`;
|
|
367
|
+
}
|
|
368
|
+
/** `@vite(...)` directives in a template that list only stylesheets: those pages get no JavaScript entry. */
|
|
369
|
+
export function cssOnlyVite(text) {
|
|
370
|
+
const lists = [];
|
|
371
|
+
for (const m of text.matchAll(/@vite\s*\(([^)]*)\)/g)) {
|
|
372
|
+
const files = [...m[1].matchAll(/(["'])([^"'\n]+)\1/g)].map((f) => f[2]);
|
|
373
|
+
if (files.length && !files.some((f) => SCRIPT_FILE.test(f) || f.includes("{$")))
|
|
374
|
+
lists.push(files);
|
|
375
|
+
}
|
|
376
|
+
return lists;
|
|
377
|
+
}
|
|
378
|
+
/** Blade files that look like page layouts (they close </body>), mail, PDF and vendor templates left out. */
|
|
379
|
+
export function bladeLayouts(dir, files = bladeFiles(dir)) {
|
|
380
|
+
const skip = /\/(?:mail|emails?|pdfs?|vendor|notifications|errors)\//;
|
|
381
|
+
const layouts = files.filter((f) => !skip.test(f) && /<\/body>/i.test(readFileSync(join(dir, f), "utf8")));
|
|
382
|
+
const rank = (f) => (/\/layouts?\//.test(f) ? 0 : /\/(?:app|welcome)\.blade\.php$/.test(f) ? 1 : 2);
|
|
383
|
+
return layouts.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
|
|
384
|
+
}
|
|
385
|
+
const loaderTag = (key) => `<script src="https://commentkit.dev/cdn/v1/loader.js" data-project="${key}" defer></script>`;
|
|
386
|
+
/** Insert `markup` on its own line just before the last </body>, indented like the body's content. */
|
|
387
|
+
function beforeBodyEnd(source, markup) {
|
|
388
|
+
const at = source.lastIndexOf("</body>");
|
|
389
|
+
if (at < 0)
|
|
390
|
+
return null;
|
|
391
|
+
const lineStart = source.lastIndexOf("\n", at) + 1;
|
|
392
|
+
const indent = /^[ \t]*/.exec(source.slice(lineStart, at))[0];
|
|
393
|
+
const inner = `${indent} `;
|
|
394
|
+
const block = markup.split("\n").map((line) => `${inner}${line}`).join("\n");
|
|
395
|
+
return lineStart === at - indent.length
|
|
396
|
+
? `${source.slice(0, lineStart)}${block}\n${source.slice(lineStart)}`
|
|
397
|
+
: `${source.slice(0, at)}\n${block}\n${indent}${source.slice(at)}`;
|
|
398
|
+
}
|
|
399
|
+
/** Where to show the widget, and the edit that does it. "done" when it is there already, null when it has to be done by hand. */
|
|
400
|
+
export function entryEdit(dir, framework, key, svelteMajor = 5) {
|
|
401
|
+
const read = (file) => readFileSync(join(dir, file), "utf8");
|
|
402
|
+
const edit = (file, change) => {
|
|
403
|
+
const source = read(file);
|
|
404
|
+
if (HAS_WIDGET.test(source))
|
|
405
|
+
return "done";
|
|
406
|
+
const content = change(source);
|
|
407
|
+
return content === null || content === source ? null : { file, content, created: false };
|
|
408
|
+
};
|
|
409
|
+
switch (framework) {
|
|
410
|
+
case "next": {
|
|
411
|
+
const file = first(dir, ["app/layout.tsx", "app/layout.jsx", "app/layout.js", "src/app/layout.tsx", "src/app/layout.jsx", "src/app/layout.js"]);
|
|
412
|
+
if (!file)
|
|
413
|
+
return null;
|
|
414
|
+
const bang = file.endsWith(".tsx") ? "!" : "";
|
|
415
|
+
return edit(file, (s) => {
|
|
416
|
+
const body = beforeBodyEnd(s, `<CommentKit project={process.env.NEXT_PUBLIC_COMMENTKIT_KEY${bang}} />`);
|
|
417
|
+
return body && withImport(body, 'import { CommentKit } from "@commentkit/comment-kit/react";');
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
case "react-router": {
|
|
421
|
+
// The document is rendered by app/root (its Layout or default export): the widget goes before </body> there.
|
|
422
|
+
const file = first(dir, ["app/root.tsx", "app/root.jsx", "app/root.js"]);
|
|
423
|
+
if (!file)
|
|
424
|
+
return null;
|
|
425
|
+
return edit(file, (s) => {
|
|
426
|
+
const body = beforeBodyEnd(s, "<CommentKit project={import.meta.env.VITE_COMMENTKIT_KEY} />");
|
|
427
|
+
return body && withImport(body, 'import { CommentKit } from "@commentkit/comment-kit/react";');
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
case "vite": {
|
|
431
|
+
const entries = viteEntries(dir);
|
|
432
|
+
if (widgetInEntries(dir, entries))
|
|
433
|
+
return "done";
|
|
434
|
+
const file = entries[0];
|
|
435
|
+
if (!file)
|
|
436
|
+
return null;
|
|
437
|
+
return edit(file, (s) => `${withImport(s, 'import { init } from "@commentkit/comment-kit";').replace(/\s*$/, "\n")}\ninit({ project: import.meta.env.VITE_COMMENTKIT_KEY });\n`);
|
|
438
|
+
}
|
|
439
|
+
case "laravel": {
|
|
440
|
+
if (findWidget(dir, "laravel"))
|
|
441
|
+
return "done";
|
|
442
|
+
const entries = laravelEntries(dir);
|
|
443
|
+
// The app's main entry (loaded on every Inertia page and by most layouts), else the first script input.
|
|
444
|
+
const file = entries.find((f) => LARAVEL_ENTRIES.includes(f)) ?? entries[0];
|
|
445
|
+
if (!file)
|
|
446
|
+
return null;
|
|
447
|
+
const vite = Boolean(first(dir, VITE_CONFIGS)) || !existsSync(join(dir, "webpack.mix.js"));
|
|
448
|
+
return edit(file, (s) => laravelInit(s, key, vite));
|
|
449
|
+
}
|
|
450
|
+
case "sveltekit": {
|
|
451
|
+
const file = "src/routes/+layout.svelte";
|
|
452
|
+
const use = "<svelte:body use:commentkit={{ project: import.meta.env.VITE_COMMENTKIT_KEY }} />";
|
|
453
|
+
const importLine = 'import { commentkit } from "@commentkit/comment-kit/svelte";';
|
|
454
|
+
if (!existsSync(join(dir, file))) {
|
|
455
|
+
if (!existsSync(join(dir, "src/routes")))
|
|
456
|
+
return null;
|
|
457
|
+
const content = svelteMajor >= 5
|
|
458
|
+
? `<script>\n ${importLine}\n let { children } = $props();\n</script>\n\n${use}\n{@render children()}\n`
|
|
459
|
+
: `<script>\n ${importLine}\n</script>\n\n${use}\n<slot />\n`;
|
|
460
|
+
return { file, content, created: true };
|
|
461
|
+
}
|
|
462
|
+
return edit(file, (s) => {
|
|
463
|
+
const script = /<script\b(?![^>]*\bcontext=["']module["'])(?![^>]*\bmodule\b)[^>]*>/.exec(s);
|
|
464
|
+
const withScript = script
|
|
465
|
+
? `${s.slice(0, script.index + script[0].length)}\n ${importLine}${s.slice(script.index + script[0].length)}`
|
|
466
|
+
: `<script>\n ${importLine}\n</script>\n\n${s}`;
|
|
467
|
+
return `${withScript.replace(/\s*$/, "\n")}${use}\n`;
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
case "astro": {
|
|
471
|
+
const file = first(dir, ["src/layouts/Layout.astro", "src/layouts/BaseLayout.astro", "src/layouts/Base.astro"]);
|
|
472
|
+
if (!file)
|
|
473
|
+
return null;
|
|
474
|
+
return edit(file, (s) => beforeBodyEnd(s, '<script>\n import { init } from "@commentkit/comment-kit";\n init({ project: import.meta.env.PUBLIC_COMMENTKIT_KEY });\n</script>'));
|
|
475
|
+
}
|
|
476
|
+
case "nuxt": {
|
|
477
|
+
const nuxt4 = existsSync(join(dir, "app", "app.vue")) || existsSync(join(dir, "app", "pages"));
|
|
478
|
+
const file = `${nuxt4 ? "app/" : ""}plugins/commentkit.client.ts`;
|
|
479
|
+
if (existsSync(join(dir, file)))
|
|
480
|
+
return HAS_WIDGET.test(read(file)) ? "done" : null;
|
|
481
|
+
return { file, created: true, content: 'import { init } from "@commentkit/comment-kit";\n\nexport default defineNuxtPlugin(() => {\n init({ project: useRuntimeConfig().public.commentkitKey });\n});\n' };
|
|
482
|
+
}
|
|
483
|
+
case "html": {
|
|
484
|
+
const file = first(dir, ["index.html", "public/index.html"]);
|
|
485
|
+
if (!file)
|
|
486
|
+
return null;
|
|
487
|
+
return edit(file, (s) => beforeBodyEnd(s, `<script src="https://commentkit.dev/cdn/v1/loader.js" data-project="${key}" defer></script>`));
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
/** The major version in a dependency range such as "^5.1.0", or null. */
|
|
492
|
+
export function major(range) {
|
|
493
|
+
const m = /(\d+)/.exec(range ?? "");
|
|
494
|
+
return m ? Number(m[1]) : null;
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* next.config: wrap the default export in withCommentKit(). Only a plain name (`nextConfig`), a call
|
|
498
|
+
* (`withX(nextConfig)`) or an object literal is wrapped, and only that expression: whatever follows the
|
|
499
|
+
* statement is kept. Null for CommonJS, several or no default exports, or anything else (`satisfies`,
|
|
500
|
+
* `as`, a function): the person gets the snippet instead.
|
|
501
|
+
*/
|
|
502
|
+
export function wrapNextConfig(source) {
|
|
503
|
+
if (PLUGIN_IMPORT.test(source))
|
|
504
|
+
return source;
|
|
505
|
+
if (/module\.exports/.test(source))
|
|
506
|
+
return null;
|
|
507
|
+
const mask = codeMask(source);
|
|
508
|
+
const exports = [...source.matchAll(/\bexport\s+default\s+/g)].filter((m) => mask[m.index]);
|
|
509
|
+
if (exports.length !== 1)
|
|
510
|
+
return null;
|
|
511
|
+
const start = exports[0].index + exports[0][0].length;
|
|
512
|
+
let end;
|
|
513
|
+
const name = /^[A-Za-z_$][\w$]*/.exec(source.slice(start))?.[0];
|
|
514
|
+
if (name && !["function", "class", "async", "await", "new"].includes(name)) {
|
|
515
|
+
end = start + name.length;
|
|
516
|
+
if (source[end] === "(") {
|
|
517
|
+
const close = closing(source, mask, end);
|
|
518
|
+
if (close < 0)
|
|
519
|
+
return null;
|
|
520
|
+
end = close + 1;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
else if (source[start] === "{") {
|
|
524
|
+
const close = closing(source, mask, start);
|
|
525
|
+
if (close < 0)
|
|
526
|
+
return null;
|
|
527
|
+
end = close + 1;
|
|
528
|
+
}
|
|
529
|
+
else {
|
|
530
|
+
return null;
|
|
531
|
+
}
|
|
532
|
+
// The statement must end right there: an optional semicolon, then the end of the line.
|
|
533
|
+
if (!/^[ \t]*;?[ \t]*(\/\/[^\n]*)?(\r?\n|$)/.test(source.slice(end)))
|
|
534
|
+
return null;
|
|
535
|
+
const wrapped = `${source.slice(0, start)}withCommentKit(${source.slice(start, end)})${source.slice(end)}`;
|
|
536
|
+
return withImport(wrapped, 'import { withCommentKit } from "@commentkit/comment-kit/next";');
|
|
537
|
+
}
|
|
538
|
+
export function plan(dir, key) {
|
|
539
|
+
const detected = detect(dir);
|
|
540
|
+
return { ...basePlan(dir, key, detected), entry: entryEdit(dir, detected.framework, key, major(detected.deps.svelte) ?? 5), widget: findWidget(dir, detected.framework) };
|
|
541
|
+
}
|
|
542
|
+
/** "resources/js/commentkit.ts, imported by resources/js/app.ts" */
|
|
543
|
+
export function describePlace(place) {
|
|
544
|
+
return place.via ? `${place.file}, imported by ${place.via}` : place.file;
|
|
545
|
+
}
|
|
546
|
+
const VITE_PLUGIN = 'import commentkit from "@commentkit/comment-kit/vite";\n // and in the config object: plugins: [commentkit(), ...your other plugins]';
|
|
547
|
+
/** vite-plus configs that build their plugin list in lazyPlugins(() => [...]): init does not edit inside the callback. */
|
|
548
|
+
const VITE_LAZY_PLUGIN = 'import commentkit from "@commentkit/comment-kit/vite";\n // and first in the list lazyPlugins returns: plugins: lazyPlugins(() => [commentkit(), ...your other plugins])';
|
|
549
|
+
/** What to add to a Vite config by hand, in the shape it has. */
|
|
550
|
+
export function vitePluginSnippet(source) {
|
|
551
|
+
return /\blazyPlugins\s*\(/.test(source) ? VITE_LAZY_PLUGIN : VITE_PLUGIN;
|
|
552
|
+
}
|
|
553
|
+
function basePlan(dir, key, { framework, packageManager, deps }) {
|
|
554
|
+
const add = packageManager === "npm" ? ["npm", "install"] : [packageManager, "add"];
|
|
555
|
+
// One package: the widget and the build plugins (@commentkit/comment-kit/vite, /next, /astro).
|
|
556
|
+
// Nothing to install for a plain website, or when package.json already lists the package.
|
|
557
|
+
const install = framework === "html" || deps["@commentkit/comment-kit"] ? [] : [[...add, "@commentkit/comment-kit"]];
|
|
558
|
+
const read = (file) => (file ? readFileSync(join(dir, file), "utf8") : "");
|
|
559
|
+
switch (framework) {
|
|
560
|
+
case "next": {
|
|
561
|
+
const configFile = first(dir, ["next.config.mjs", "next.config.ts", "next.config.js"]);
|
|
562
|
+
return {
|
|
563
|
+
framework, packageManager, label: "Next.js", envFile: ".env.local", envVar: "NEXT_PUBLIC_COMMENTKIT_KEY", configFile,
|
|
564
|
+
configEdit: configFile ? wrapNextConfig(read(configFile)) : null,
|
|
565
|
+
configSnippet: 'import { withCommentKit } from "@commentkit/comment-kit/next";\n // and wrap the default export: export default withCommentKit(nextConfig);',
|
|
566
|
+
notes: [], manual: configFile ? [] : ['Create next.config.mjs with: import { withCommentKit } from "@commentkit/comment-kit/next"; export default withCommentKit({});'],
|
|
567
|
+
install,
|
|
568
|
+
snippet: 'In app/layout.tsx:\n import { CommentKit } from "@commentkit/comment-kit/react";\n <CommentKit project={process.env.NEXT_PUBLIC_COMMENTKIT_KEY!} />',
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
case "astro": {
|
|
572
|
+
const configFile = first(dir, ["astro.config.mjs", "astro.config.ts", "astro.config.js"]);
|
|
573
|
+
return {
|
|
574
|
+
framework, packageManager, label: "Astro", envFile: ".env", envVar: "PUBLIC_COMMENTKIT_KEY", configFile,
|
|
575
|
+
configEdit: configFile ? addToArray(read(configFile), "integrations", "commentkit()", 'import commentkit from "@commentkit/comment-kit/astro";') : null,
|
|
576
|
+
configSnippet: 'import commentkit from "@commentkit/comment-kit/astro";\n // and in defineConfig: integrations: [commentkit(), ...your other integrations]',
|
|
577
|
+
manual: [], notes: [], install,
|
|
578
|
+
snippet: 'In your base layout:\n <script>\n import { init } from "@commentkit/comment-kit";\n init({ project: import.meta.env.PUBLIC_COMMENTKIT_KEY });\n </script>',
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
case "nuxt":
|
|
582
|
+
return {
|
|
583
|
+
framework, packageManager, label: "Nuxt", envFile: ".env", envVar: "NUXT_PUBLIC_COMMENTKIT_KEY", configFile: first(dir, ["nuxt.config.ts", "nuxt.config.js"]), configEdit: null, configSnippet: "",
|
|
584
|
+
notes: [],
|
|
585
|
+
manual: [
|
|
586
|
+
'In nuxt.config.ts add: import commentkit from "@commentkit/comment-kit/vite"; and vite: { plugins: [commentkit()] }',
|
|
587
|
+
'In nuxt.config.ts also add: runtimeConfig: { public: { commentkitKey: "" } }',
|
|
588
|
+
], install,
|
|
589
|
+
snippet: 'In a client plugin (plugins/commentkit.client.ts):\n import { init } from "@commentkit/comment-kit";\n export default defineNuxtPlugin(() => { init({ project: useRuntimeConfig().public.commentkitKey }); });',
|
|
590
|
+
};
|
|
591
|
+
case "sveltekit":
|
|
592
|
+
case "react-router":
|
|
593
|
+
case "vite": {
|
|
594
|
+
const configFile = first(dir, ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]);
|
|
595
|
+
const remix = framework === "react-router" && !deps["@react-router/dev"];
|
|
596
|
+
const snippets = {
|
|
597
|
+
sveltekit: 'In src/routes/+layout.svelte:\n <script>\n import { commentkit } from "@commentkit/comment-kit/svelte";\n let { children } = $props();\n </script>\n <svelte:body use:commentkit={{ project: import.meta.env.VITE_COMMENTKIT_KEY }} />\n {@render children()}',
|
|
598
|
+
"react-router": 'In app/root.tsx, just before </body> in your Layout:\n import { CommentKit } from "@commentkit/comment-kit/react";\n <CommentKit project={import.meta.env.VITE_COMMENTKIT_KEY} />',
|
|
599
|
+
vite: 'In your entry file (for example src/main.ts):\n import { init } from "@commentkit/comment-kit";\n init({ project: import.meta.env.VITE_COMMENTKIT_KEY });',
|
|
600
|
+
};
|
|
601
|
+
return {
|
|
602
|
+
framework, packageManager, label: framework === "sveltekit" ? "SvelteKit" : framework === "react-router" ? (remix ? "Remix" : "React Router") : "Vite", envFile: ".env.local", envVar: "VITE_COMMENTKIT_KEY", configFile,
|
|
603
|
+
configEdit: configFile ? addToArray(read(configFile), "plugins", "commentkit()", 'import commentkit from "@commentkit/comment-kit/vite";') : null,
|
|
604
|
+
configSnippet: vitePluginSnippet(read(configFile)),
|
|
605
|
+
notes: [],
|
|
606
|
+
manual: configFile || framework !== "react-router" ? [] : ['No vite.config found. If the app builds with Vite, add to its config: import commentkit from "@commentkit/comment-kit/vite"; and plugins: [commentkit(), ...]'],
|
|
607
|
+
install,
|
|
608
|
+
snippet: snippets[framework],
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
case "laravel":
|
|
612
|
+
return laravelPlan(dir, key, packageManager, deps, install);
|
|
613
|
+
default:
|
|
614
|
+
return {
|
|
615
|
+
framework, packageManager, label: "a plain website", envFile: "", envVar: "", configFile: null, configEdit: null, configSnippet: "", manual: [], notes: [], install: [],
|
|
616
|
+
snippet: `Add before </body> on every page:\n <script src="https://commentkit.dev/cdn/v1/loader.js" data-project="${key}" defer></script>`,
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
/** "Inertia React", "Livewire" or "Blade": what renders a Laravel app's pages. */
|
|
621
|
+
function laravelFlavour(dir, deps) {
|
|
622
|
+
if (deps["@inertiajs/react"])
|
|
623
|
+
return "Inertia React";
|
|
624
|
+
if (deps["@inertiajs/vue3"] || deps["@inertiajs/vue"])
|
|
625
|
+
return "Inertia Vue";
|
|
626
|
+
if (deps["@inertiajs/svelte"])
|
|
627
|
+
return "Inertia Svelte";
|
|
628
|
+
const composer = readJsonFile(join(dir, "composer.json"));
|
|
629
|
+
return composer?.require?.["livewire/livewire"] || composer?.require?.["livewire/flux"] ? "Livewire" : "Blade";
|
|
630
|
+
}
|
|
631
|
+
function laravelPlan(dir, key, packageManager, deps, install) {
|
|
632
|
+
const configFile = first(dir, VITE_CONFIGS);
|
|
633
|
+
const config = configFile ? readFileSync(join(dir, configFile), "utf8") : "";
|
|
634
|
+
const entries = laravelEntries(dir);
|
|
635
|
+
const entry = entries.find((f) => LARAVEL_ENTRIES.includes(f)) ?? entries[0] ?? null;
|
|
636
|
+
const templates = bladeFiles(dir);
|
|
637
|
+
const notes = [];
|
|
638
|
+
const manual = [];
|
|
639
|
+
const composer = readJsonFile(join(dir, "composer.json"));
|
|
640
|
+
const placed = findWidget(dir, "laravel");
|
|
641
|
+
if (entry && !placed) {
|
|
642
|
+
notes.push(`The key goes into ${entry} as the default value. Publishable keys are public by design, so it is safe to commit, and your server needs no new environment variable. To use another key in one place (pk_test_… on staging), set VITE_COMMENTKIT_KEY there before the build.`);
|
|
643
|
+
}
|
|
644
|
+
if (entry) {
|
|
645
|
+
// Layouts whose @vite(...) lists only stylesheets: their pages never load the entry, so the widget is not there.
|
|
646
|
+
for (const file of templates) {
|
|
647
|
+
for (const list of cssOnlyVite(readFileSync(join(dir, file), "utf8"))) {
|
|
648
|
+
const quoted = [...list, entry].map((f) => `'${f}'`).join(", ");
|
|
649
|
+
manual.push(`${file} loads only stylesheets with @vite, so its pages will not show the widget. To show it there, change that line to: @vite([${quoted}])`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
if (composer?.require?.["filament/filament"]) {
|
|
654
|
+
notes.push(`Filament admin panels do not load ${entry ?? "your app's JavaScript entry"}, so the widget does not show in them.`);
|
|
655
|
+
}
|
|
656
|
+
// No JavaScript entry at all: pages are plain Blade. init does not edit Blade; it prints the line and where it goes.
|
|
657
|
+
const layouts = bladeLayouts(dir, templates).slice(0, 5);
|
|
658
|
+
const where = layouts.length ? `\nLayouts that look like the place for it: ${layouts.join(", ")}` : "";
|
|
659
|
+
const snippet = entry
|
|
660
|
+
? `In ${entry}:\n import { init } from "@commentkit/comment-kit";\n init({ project: import.meta.env.VITE_COMMENTKIT_KEY || "${key}" });`
|
|
661
|
+
: `Your pages load no JavaScript entry, so add the script tag before </body> in your layout (init does not edit Blade files):\n ${loaderTag(key)}${where}`;
|
|
662
|
+
return {
|
|
663
|
+
framework: "laravel", packageManager, label: `Laravel + ${laravelFlavour(dir, deps)}`,
|
|
664
|
+
// The key is written into the entry, not an env file: .env.local is git-ignored (a server that builds on deploy has none) and Laravel itself never reads it.
|
|
665
|
+
envFile: "", envVar: "VITE_COMMENTKIT_KEY",
|
|
666
|
+
configFile: entry ? configFile : null,
|
|
667
|
+
configEdit: entry && configFile ? addToArray(config, "plugins", "commentkit()", `import commentkit from ${quoteOf(config)}@commentkit/comment-kit/vite${quoteOf(config)};`) : null,
|
|
668
|
+
configSnippet: vitePluginSnippet(config),
|
|
669
|
+
manual, notes,
|
|
670
|
+
// Plain Blade pages use the script tag: nothing to install.
|
|
671
|
+
install: entry ? install : [],
|
|
672
|
+
snippet,
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
/** Set KEY=value in an env file's text, replacing an existing line. */
|
|
676
|
+
export function setEnv(text, name, value) {
|
|
677
|
+
const line = `${name}=${value}`;
|
|
678
|
+
const re = new RegExp(`^${name}=.*$`, "m");
|
|
679
|
+
if (re.test(text))
|
|
680
|
+
return text.replace(re, line);
|
|
681
|
+
return `${text}${text && !text.endsWith("\n") ? "\n" : ""}${line}\n`;
|
|
682
|
+
}
|
|
683
|
+
/** Keep pulled feedback out of git: it holds what reviewers wrote. */
|
|
684
|
+
export function ignoreFolder(text) {
|
|
685
|
+
return /^\/?\.commentkit\/?$/m.test(text) ? text : `${text}${text && !text.endsWith("\n") ? "\n" : ""}.commentkit/\n`;
|
|
686
|
+
}
|