@cairnvibe/indexer 0.2.1 → 0.2.2

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.
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ // `cairn setup`'s other departure from `init`'s "never touch an existing
3
+ // file" rule, for the same class of reason as inject-widget.ts: without
4
+ // this, @cairnvibe/sdk and @cairnvibe/core — which ship raw, untranspiled
5
+ // .tsx/.ts as their main entry deliberately, so bundlers apply the
6
+ // *consuming* project's own JSX/TS settings — have no instruction telling
7
+ // Next.js to transform that source at all. Found live, not theoretical:
8
+ // a real project on Next.js 16 + Turbopack failed cold with "Unknown
9
+ // module type" on @cairnvibe/sdk/src/index.tsx the moment `next dev` ran,
10
+ // because nothing in that project's next.config.ts listed it in
11
+ // transpilePackages. Fixing that one project by hand isn't the fix — every
12
+ // consuming project needs this, automatically, which is what this does.
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ensureTranspilePackages = ensureTranspilePackages;
18
+ const node_fs_1 = __importDefault(require("node:fs"));
19
+ const node_path_1 = __importDefault(require("node:path"));
20
+ const ts_morph_1 = require("ts-morph");
21
+ const REQUIRED_PACKAGES = ["@cairnvibe/sdk", "@cairnvibe/core"];
22
+ const CONFIG_CANDIDATES = ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"];
23
+ function findConfigFile(absDir) {
24
+ for (const name of CONFIG_CANDIDATES) {
25
+ const p = node_path_1.default.join(absDir, name);
26
+ if (node_fs_1.default.existsSync(p))
27
+ return p;
28
+ }
29
+ return null;
30
+ }
31
+ /** Resolves `export default X` / `module.exports = X` down to the actual
32
+ * object literal, following one level of `const nextConfig = {...}`
33
+ * indirection — covers the two shapes basically every real Next.js
34
+ * config file uses. Anything else (a config wrapped in a plugin function
35
+ * call like `withSentryConfig(nextConfig)`) returns null on purpose —
36
+ * safely falling back to printed instructions beats guessing which
37
+ * argument of an arbitrary function call is the "real" config. */
38
+ function resolveConfigObject(sf, expr) {
39
+ if (!expr)
40
+ return null;
41
+ if (expr.getKind() === ts_morph_1.SyntaxKind.ObjectLiteralExpression)
42
+ return expr;
43
+ if (expr.getKind() === ts_morph_1.SyntaxKind.Identifier) {
44
+ const varDecl = sf.getVariableDeclaration(expr.getText());
45
+ const init = varDecl?.getInitializer();
46
+ if (init?.getKind() === ts_morph_1.SyntaxKind.ObjectLiteralExpression)
47
+ return init;
48
+ }
49
+ return null;
50
+ }
51
+ function findExportedConfigObject(sf) {
52
+ // `export default X;`
53
+ const defaultExport = sf.getExportAssignments()[0];
54
+ if (defaultExport) {
55
+ const resolved = resolveConfigObject(sf, defaultExport.getExpression());
56
+ if (resolved)
57
+ return resolved;
58
+ }
59
+ // `module.exports = X;`
60
+ const moduleExports = sf
61
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.BinaryExpression)
62
+ .find((b) => b.getOperatorToken().getText() === "=" && b.getLeft().getText() === "module.exports");
63
+ if (moduleExports) {
64
+ const resolved = resolveConfigObject(sf, moduleExports.getRight());
65
+ if (resolved)
66
+ return resolved;
67
+ }
68
+ return null;
69
+ }
70
+ function ensureTranspilePackages(dir) {
71
+ const absDir = node_path_1.default.resolve(dir);
72
+ const existing = findConfigFile(absDir);
73
+ if (!existing) {
74
+ // No config at all yet — the simplest possible one, ESM since that's
75
+ // what every current Next.js version accepts for a fresh project.
76
+ const newPath = node_path_1.default.join(absDir, "next.config.mjs");
77
+ node_fs_1.default.writeFileSync(newPath, `/** @type {import('next').NextConfig} */\nconst nextConfig = {\n transpilePackages: ${JSON.stringify(REQUIRED_PACKAGES)},\n};\n\nexport default nextConfig;\n`);
78
+ return { ok: true, filePath: newPath, created: true };
79
+ }
80
+ const relTarget = node_path_1.default.relative(absDir, existing) || existing;
81
+ const manualHint = `add manually: transpilePackages: ${JSON.stringify(REQUIRED_PACKAGES)}`;
82
+ try {
83
+ const project = new ts_morph_1.Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true });
84
+ const sf = project.addSourceFileAtPath(existing);
85
+ const configObject = findExportedConfigObject(sf);
86
+ if (!configObject) {
87
+ return { ok: false, reason: `couldn't confidently find the config object in ${relTarget} (it may be wrapped in a plugin function) — ${manualHint}` };
88
+ }
89
+ const existingProp = configObject.getProperty("transpilePackages");
90
+ if (existingProp?.getKind() === ts_morph_1.SyntaxKind.PropertyAssignment) {
91
+ const initializer = existingProp.asKindOrThrow(ts_morph_1.SyntaxKind.PropertyAssignment).getInitializer();
92
+ if (initializer?.getKind() !== ts_morph_1.SyntaxKind.ArrayLiteralExpression) {
93
+ return { ok: false, reason: `${relTarget}'s transpilePackages isn't a plain array — ${manualHint}` };
94
+ }
95
+ const arr = initializer.asKindOrThrow(ts_morph_1.SyntaxKind.ArrayLiteralExpression);
96
+ const current = arr.getElements().map((e) => e.getText().replace(/^["']|["']$/g, ""));
97
+ const toAdd = REQUIRED_PACKAGES.filter((p) => !current.includes(p));
98
+ if (toAdd.length === 0) {
99
+ return { ok: false, reason: `${relTarget} already lists these packages — leaving it alone` };
100
+ }
101
+ for (const pkg of toAdd)
102
+ arr.addElement(`"${pkg}"`);
103
+ }
104
+ else {
105
+ configObject.addPropertyAssignment({ name: "transpilePackages", initializer: JSON.stringify(REQUIRED_PACKAGES) });
106
+ }
107
+ sf.saveSync();
108
+ return { ok: true, filePath: existing };
109
+ }
110
+ catch (err) {
111
+ return { ok: false, reason: `couldn't safely modify ${relTarget} (${err.message}) — ${manualHint}` };
112
+ }
113
+ }
@@ -1,11 +1,29 @@
1
1
  "use strict";
2
2
  // `cairn setup`'s one departure from `init`'s "never touch an existing
3
- // file" rule — but only for this one, narrow, reversible edit (adding an
4
- // import + one JSX tag), and only ever via a real AST parse, never blind
5
- // string splicing. Any structure this doesn't recognize falls back to
6
- // printing the two-line manual instruction instead of guessing the
7
- // same "don't corrupt what you don't understand" discipline `init` uses
8
- // for whole files, applied here at the node level.
3
+ // file" rule — but only for this one, narrow, reversible edit (a new
4
+ // wrapper component file, plus one import + one JSX tag in the real
5
+ // layout), and only ever via a real AST parse, never blind string
6
+ // splicing. Any structure this doesn't recognize falls back to printing
7
+ // the two-line manual instruction instead of guessing the same "don't
8
+ // corrupt what you don't understand" discipline `init` uses for whole
9
+ // files, applied here at the node level.
10
+ //
11
+ // Real bug this fixes, found by testing against an actual project, not
12
+ // a synthetic fixture: an earlier version inserted `<Copilot
13
+ // onDo={(action, target) => {...}} />` directly into app/layout.tsx.
14
+ // layout.tsx is a Server Component by default (App Router) — React
15
+ // Server Components cannot accept a plain inline function as a prop on
16
+ // a Client Component, which <Copilot/> is ("Event handlers cannot be
17
+ // passed to Client Component props"). The working example app
18
+ // (examples/demo-app/components/CopilotWithActions.tsx) already solved
19
+ // this the right way: a small "use client" wrapper component that
20
+ // *defines* onDo itself, so no function ever crosses the server/client
21
+ // boundary — layout.tsx only ever references the wrapper by name, with
22
+ // zero function props. This module now generates that same wrapper
23
+ // instead of inlining Copilot directly, for both App Router and Pages
24
+ // Router (Pages Router doesn't strictly need it — no RSC boundary
25
+ // there — but the same shape avoids a special case and matches the one
26
+ // real, working example this project has).
9
27
  var __importDefault = (this && this.__importDefault) || function (mod) {
10
28
  return (mod && mod.__esModule) ? mod : { "default": mod };
11
29
  };
@@ -14,7 +32,27 @@ exports.injectWidget = injectWidget;
14
32
  const node_fs_1 = __importDefault(require("node:fs"));
15
33
  const node_path_1 = __importDefault(require("node:path"));
16
34
  const ts_morph_1 = require("ts-morph");
17
- const WIDGET_JSX = `<Copilot registeredActions={[]} onDo={(action, target) => { /* run it through your own auth */ }} />`;
35
+ const WRAPPER_COMPONENT_NAME = "CairnCopilot";
36
+ function wrapperSource() {
37
+ return `"use client";
38
+
39
+ import { Copilot } from "@cairnvibe/sdk";
40
+
41
+ // A small client wrapper so the layout/app file (a server component, for
42
+ // metadata etc.) never has to pass a function prop across the server/client
43
+ // boundary — see the comment in inject-widget.ts for why that fails.
44
+ export function ${WRAPPER_COMPONENT_NAME}() {
45
+ return (
46
+ <Copilot
47
+ registeredActions={[]}
48
+ onDo={(action, target) => {
49
+ // run it through your own auth
50
+ }}
51
+ />
52
+ );
53
+ }
54
+ `;
55
+ }
18
56
  function findLayoutFile(absDir, framework) {
19
57
  const candidates = framework === "next-app-router"
20
58
  ? ["app/layout.tsx", "app/layout.jsx"]
@@ -26,17 +64,34 @@ function findLayoutFile(absDir, framework) {
26
64
  }
27
65
  return null;
28
66
  }
67
+ function toPosixRelativeImport(fromFile, toFileNoExt) {
68
+ let rel = node_path_1.default.relative(node_path_1.default.dirname(fromFile), toFileNoExt).split(node_path_1.default.sep).join("/");
69
+ if (!rel.startsWith("."))
70
+ rel = `./${rel}`;
71
+ return rel;
72
+ }
29
73
  function injectWidget(dir, framework) {
30
74
  const absDir = node_path_1.default.resolve(dir);
31
75
  const target = findLayoutFile(absDir, framework);
32
76
  if (!target) {
33
- return { injected: false, reason: "no app/layout.tsx or pages/_app.tsx found — add <Copilot/> manually" };
77
+ return { injected: false, reason: "no app/layout.tsx or pages/_app.tsx found — add the widget manually" };
34
78
  }
35
79
  const relTarget = node_path_1.default.relative(absDir, target) || target;
36
80
  const original = node_fs_1.default.readFileSync(target, "utf8");
37
- if (original.includes("@cairnvibe/sdk") || original.includes("<Copilot")) {
38
- return { injected: false, reason: `${relTarget} already references Copilot — leaving it alone` };
81
+ if (original.includes(WRAPPER_COMPONENT_NAME) || original.includes("@cairnvibe/sdk") || original.includes("<Copilot")) {
82
+ return { injected: false, reason: `${relTarget} already references the widget — leaving it alone` };
83
+ }
84
+ // The wrapper always matches the layout file's own extension (.tsx stays
85
+ // .tsx, .jsx stays .jsx — a .tsx file dropped into a plain-JS project has
86
+ // no type checker configured for it and would just confuse tooling).
87
+ const ext = node_path_1.default.extname(target); // ".tsx" or ".jsx"
88
+ const wrapperPath = node_path_1.default.join(absDir, "components", `${WRAPPER_COMPONENT_NAME}${ext}`);
89
+ if (!node_fs_1.default.existsSync(wrapperPath)) {
90
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(wrapperPath), { recursive: true });
91
+ node_fs_1.default.writeFileSync(wrapperPath, wrapperSource());
39
92
  }
93
+ const importPath = toPosixRelativeImport(target, wrapperPath.slice(0, -ext.length));
94
+ const widgetJsx = `<${WRAPPER_COMPONENT_NAME} />`;
40
95
  try {
41
96
  const project = new ts_morph_1.Project({
42
97
  useInMemoryFileSystem: false,
@@ -44,9 +99,9 @@ function injectWidget(dir, framework) {
44
99
  compilerOptions: { jsx: ts_morph_1.ts.JsxEmit.ReactJSX, allowJs: true, esModuleInterop: true, target: ts_morph_1.ts.ScriptTarget.ES2022 },
45
100
  });
46
101
  const sf = project.addSourceFileAtPath(target);
47
- const hasImport = sf.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "@cairnvibe/sdk");
102
+ const hasImport = sf.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === importPath);
48
103
  if (!hasImport) {
49
- sf.addImportDeclaration({ moduleSpecifier: "@cairnvibe/sdk", namedImports: ["Copilot"] });
104
+ sf.addImportDeclaration({ moduleSpecifier: importPath, namedImports: [WRAPPER_COMPONENT_NAME] });
50
105
  }
51
106
  // `insertText` at a position, not `replaceWithText` on a node — the latter
52
107
  // asks ts-morph to structurally reconcile old vs. new trees, which fails
@@ -62,7 +117,7 @@ function injectWidget(dir, framework) {
62
117
  if (bodyOpening) {
63
118
  const closing = bodyOpening.getParentIfKind(ts_morph_1.SyntaxKind.JsxElement)?.getClosingElement();
64
119
  if (closing) {
65
- sf.insertText(closing.getStart(), `${WIDGET_JSX}\n `);
120
+ sf.insertText(closing.getStart(), `${widgetJsx}\n `);
66
121
  inserted = true;
67
122
  }
68
123
  }
@@ -72,7 +127,7 @@ function injectWidget(dir, framework) {
72
127
  .getDescendantsOfKind(ts_morph_1.SyntaxKind.JsxExpression)
73
128
  .find((e) => e.getExpression()?.getText() === "children");
74
129
  if (childrenExpr) {
75
- sf.insertText(childrenExpr.getEnd(), `\n ${WIDGET_JSX}`);
130
+ sf.insertText(childrenExpr.getEnd(), `\n ${widgetJsx}`);
76
131
  inserted = true;
77
132
  }
78
133
  }
@@ -89,20 +144,22 @@ function injectWidget(dir, framework) {
89
144
  // first insertion changes the source text underneath it.
90
145
  const start = componentTag.getStart();
91
146
  const end = componentTag.getEnd();
92
- sf.insertText(end, `\n ${WIDGET_JSX}\n </>`);
147
+ sf.insertText(end, `\n ${widgetJsx}\n </>`);
93
148
  sf.insertText(start, `<>\n `);
94
149
  inserted = true;
95
150
  }
96
151
  }
97
152
  if (!inserted) {
98
- return { injected: false, reason: `couldn't find a safe spot in ${relTarget} — add <Copilot/> manually` };
153
+ return { injected: false, reason: `couldn't find a safe spot in ${relTarget} — add the widget manually` };
99
154
  }
100
155
  sf.saveSync();
101
- return { injected: true, filePath: target };
156
+ return { injected: true, filePath: target, wrapperPath };
102
157
  }
103
158
  catch (err) {
104
159
  // Never leave a half-written file — ts-morph only writes on saveSync(),
105
160
  // so a thrown error here means the original file on disk is untouched.
106
- return { injected: false, reason: `couldn't safely modify ${relTarget} (${err.message}) add <Copilot/> manually` };
161
+ // The wrapper component file, if it was just created, is still valid
162
+ // and harmless on its own — it's just not referenced from anywhere yet.
163
+ return { injected: false, reason: `couldn't safely modify ${relTarget} (${err.message}) — add the widget manually` };
107
164
  }
108
165
  }
package/dist/setup.js CHANGED
@@ -22,6 +22,7 @@ const node_path_1 = __importDefault(require("node:path"));
22
22
  const node_child_process_1 = require("node:child_process");
23
23
  const init_1 = require("./init");
24
24
  const inject_widget_1 = require("./inject-widget");
25
+ const ensure_transpile_1 = require("./ensure-transpile");
25
26
  const prompt_1 = require("./prompt");
26
27
  const l1_scan_1 = require("./l1-scan");
27
28
  const l2_reachability_1 = require("./l2-reachability");
@@ -225,12 +226,25 @@ async function runSetup(dir) {
225
226
  const framework = init.framework;
226
227
  const inject = (0, inject_widget_1.injectWidget)(dir, framework);
227
228
  if (inject.injected) {
228
- console.log((0, ui_1.green)(`✓ wired <Copilot/> into ${node_path_1.default.relative(absDir, inject.filePath)}`));
229
+ console.log((0, ui_1.green)(`✓ wired the widget into ${node_path_1.default.relative(absDir, inject.filePath)} (via a new components/CairnCopilot.tsx wrapper)`));
229
230
  }
230
231
  else {
231
- console.log(`\n<Copilot/> not auto-wired (${inject.reason}). Add it yourself:`);
232
+ console.log(`\nWidget not auto-wired (${inject.reason}). Add it yourself:`);
232
233
  console.log(' import { Copilot } from "@cairnvibe/sdk";');
233
234
  console.log(" <Copilot registeredActions={[]} onDo={(action, target) => { /* run it */ }} />");
235
+ console.log(" (in a \"use client\" component — see examples/demo-app/components/CopilotWithActions.tsx for why)");
236
+ }
237
+ // 5b. @cairnvibe/sdk and @cairnvibe/core ship raw TS/TSX as their main
238
+ // entry deliberately — bundlers need transpilePackages to know to
239
+ // transform it. Without this, real projects fail cold at `next dev`
240
+ // with "Unknown module type", not something a demo on a fresh project
241
+ // would ever surface (this repo's own next.config.js already has it).
242
+ const transpile = (0, ensure_transpile_1.ensureTranspilePackages)(dir);
243
+ if (transpile.ok) {
244
+ console.log((0, ui_1.green)(`✓ ${transpile.created ? "created" : "updated"} ${node_path_1.default.relative(absDir, transpile.filePath)} with transpilePackages`));
245
+ }
246
+ else {
247
+ console.log(`\ntranspilePackages not auto-added (${transpile.reason})`);
234
248
  }
235
249
  // 6. Build the manifest once now, if we actually have a usable key — no
236
250
  // point trying (and failing loudly) with nothing to call. On failure,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cairnvibe/indexer",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Cairn's analyzer and installer (the `cairn` CLI) — scans Next.js source or crawls any running app, and scaffolds the backend either way.",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },