@ekanos/cli 0.1.5 → 0.1.6
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 +79 -0
- package/dist/bin.js +14 -1
- package/dist/bin.js.map +1 -1
- package/dist/commands/dev.d.ts +4 -0
- package/dist/commands/dev.js +6 -20
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/init.d.ts +25 -0
- package/dist/commands/init.js +19 -8
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/publish.d.ts +13 -0
- package/dist/commands/publish.js +38 -15
- package/dist/commands/publish.js.map +1 -1
- package/dist/commands/status.js +9 -2
- package/dist/commands/status.js.map +1 -1
- package/dist/commands/upgrade.d.ts +47 -0
- package/dist/commands/upgrade.js +445 -0
- package/dist/commands/upgrade.js.map +1 -0
- package/dist/commands/validate.d.ts +5 -0
- package/dist/commands/validate.js +20 -6
- package/dist/commands/validate.js.map +1 -1
- package/dist/context.d.ts +9 -0
- package/dist/context.js +9 -0
- package/dist/context.js.map +1 -1
- package/dist/delegate.d.ts +28 -0
- package/dist/delegate.js +136 -0
- package/dist/delegate.js.map +1 -0
- package/dist/harness-scaffold.d.ts +21 -6
- package/dist/harness-scaffold.js +8 -5
- package/dist/harness-scaffold.js.map +1 -1
- package/dist/index.js +35 -2
- package/dist/index.js.map +1 -1
- package/dist/package-manager.d.ts +10 -0
- package/dist/package-manager.js +32 -0
- package/dist/package-manager.js.map +1 -1
- package/dist/schema-skew.d.ts +77 -0
- package/dist/schema-skew.js +163 -0
- package/dist/schema-skew.js.map +1 -0
- package/dist/toolchain-api.d.ts +54 -0
- package/dist/toolchain-api.js +58 -0
- package/dist/toolchain-api.js.map +1 -0
- package/dist/toolchain-resolve.d.ts +26 -0
- package/dist/toolchain-resolve.js +100 -0
- package/dist/toolchain-resolve.js.map +1 -0
- package/dist/toolchain.d.ts +21 -0
- package/dist/toolchain.js +16 -0
- package/dist/toolchain.js.map +1 -0
- package/dist/update-notice.d.ts +32 -0
- package/dist/update-notice.js +180 -0
- package/dist/update-notice.js.map +1 -0
- package/dist/validate-findings.d.ts +12 -0
- package/dist/validate-findings.js +12 -0
- package/dist/validate-findings.js.map +1 -1
- package/package.json +1 -1
- package/templates/AGENTS.md.tmpl +24 -0
- package/templates/CLAUDE.md.tmpl +2 -1
- package/templates/claude-skill.md.tmpl +13 -2
package/dist/context.js
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import { EXIT_CODES } from './exit-codes.js';
|
|
2
|
+
/**
|
|
3
|
+
* `data` is deliberately `unknown` above — each verb owns its own shape — but
|
|
4
|
+
* one convention spans several of them: `validate`, `dev`, `publish` and
|
|
5
|
+
* `status` all add an OPTIONAL `toolchain` field to `data` (never to the
|
|
6
|
+
* envelope's top level) when the proactive update check in `update-notice.ts`
|
|
7
|
+
* finds this CLI is behind. See that file's `ToolchainNoticeData` for the
|
|
8
|
+
* shape, and `README.md`'s "Keeping the toolchain current" section for the
|
|
9
|
+
* full contract. It is absent, not `null`, when there is nothing to report.
|
|
10
|
+
*/
|
|
2
11
|
/**
|
|
3
12
|
* The agent-native output envelope, resolved ONCE at startup and threaded
|
|
4
13
|
* through every command.
|
package/dist/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAiB,MAAM,cAAc,CAAC;AAqCzD;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,UAAU;IAYrB,YAAY,QAAsB,EAAE;;QAF5B,YAAO,GAAG,KAAK,CAAC;QAGtB,MAAM,MAAM,GAAG,MAAA,KAAK,CAAC,MAAM,mCAAI,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,MAAM,GAAG,MAAA,KAAK,CAAC,MAAM,mCAAI,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,GAAG,GAAG,MAA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,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;YAChD,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,MAAM,CAAC,QAAQ,CAAC;IACzB,CAAC;IAEO,MAAM;QACZ,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CACb,8DAA8D;gBAC5D,mEAAmE;gBACnE,wCAAwC,CAC3C,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;CACF;AAED,SAAS,aAAa,CAAC,MAA0B;IAC/C,OAAO;QACL,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE;YACvB,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { CliError } from './errors';\nimport { EXIT_CODES, type ExitCode } from './exit-codes';\n\n/**\n * A single writable sink. Real streams satisfy this; tests pass a capturing\n * buffer so the stdout-purity invariant can be asserted byte-for-byte.\n */\nexport interface WriteStream {\n write(chunk: string): void;\n isTTY?: boolean;\n}\n\nexport interface ContextInput {\n /**\n * The user's EXPLICIT preference, already parsed: `true` for `--json`,\n * `false` for `--no-json`, `undefined` when neither was passed. The\n * undefined case is what allows the mode to be inferred instead.\n */\n jsonFlag?: boolean;\n stdout?: WriteStream;\n stderr?: WriteStream;\n /** Overrides process.env for CLAUDECODE detection (tests). */\n env?: Record<string, string | undefined>;\n}\n\n/** The success envelope. */\ninterface OkEnvelope {\n ok: true;\n data: unknown;\n}\n\n/** The error envelope. `data` is optional — validate carries its findings here. */\ninterface ErrEnvelope {\n ok: false;\n data?: unknown;\n error: { code: string; message: string; hint: string };\n}\n\n/**\n * The agent-native output envelope, resolved ONCE at startup and threaded\n * through every command.\n *\n * The load-bearing invariant: in JSON mode, stdout receives EXACTLY ONE JSON\n * object for the whole process — nothing else, ever. Every progress line, warn,\n * and scrap of human prose goes to stderr. This is the single most common way\n * an agent's tool call breaks (a stray log line on stdout makes the JSON\n * unparseable), so the context enforces it structurally: `succeed`/`fail` are\n * the only writers of stdout, and a `settled` latch makes a second call throw\n * rather than emit a second object.\n */\nexport class CliContext {\n readonly jsonMode: boolean;\n /**\n * The environment the context resolved against — exposed so decoration\n * (the gradient banner) can honour `NO_COLOR` / `EKANOS_NO_BANNER` without\n * every call site threading `process.env` through by hand.\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n private readonly stdout: WriteStream;\n private readonly stderr: WriteStream;\n private settled = false;\n\n constructor(input: ContextInput = {}) {\n const stdout = input.stdout ?? defaultStream(process.stdout);\n const stderr = input.stderr ?? defaultStream(process.stderr);\n const env = input.env ?? process.env;\n\n this.stdout = stdout;\n this.stderr = stderr;\n this.env = env;\n\n // Resolve JSON mode once. An EXPLICIT flag always wins: `--json` forces the\n // envelope on even at a terminal, `--no-json` forces the human form even\n // when piped. Only when the user expressed no preference is the mode\n // inferred — from a non-TTY stdout (piped into another program or an agent)\n // or the CLAUDECODE marker.\n const nonTty = stdout.isTTY !== true;\n this.jsonMode = input.jsonFlag ?? (nonTty || env.CLAUDECODE === '1');\n }\n\n /** Whether stderr is a real terminal — decoration (the banner) gates on this. */\n get stderrIsTTY(): boolean {\n return this.stderr.isTTY === true;\n }\n\n /** Human/progress output — ALWAYS stderr, so stdout stays pure in JSON mode. */\n log(message: string): void {\n this.stderr.write(`${message}\\n`);\n }\n\n /** A warning — stderr, no ANSI. */\n warn(message: string): void {\n this.stderr.write(`${message}\\n`);\n }\n\n /**\n * Emit the `claude-code-hint` protocol line to STDERR. Used on --help and on\n * an unknown command so an agent reading stderr is told what to do next\n * without the line ever touching stdout.\n */\n emitClaudeCodeHint(payload: Record<string, unknown>): void {\n this.stderr.write(`claude-code-hint: ${JSON.stringify(payload)}\\n`);\n }\n\n /**\n * Terminal success. Writes the single stdout object (JSON mode) or a concise\n * human line (human mode). Returns the OK exit code so the caller can end the\n * process with it. Idempotent-by-latch: a second settle throws.\n */\n succeed(data: unknown, humanSummary?: string): ExitCode {\n this.settle();\n if (this.jsonMode) {\n const envelope: OkEnvelope = { ok: true, data };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else {\n this.stdout.write(`${humanSummary ?? 'OK'}\\n`);\n }\n return EXIT_CODES.OK;\n }\n\n /**\n * Terminal failure. Writes the single stdout error object (JSON mode) or the\n * message + hint to stderr (human mode). Returns the error's exit code.\n *\n * `error.hint` is guaranteed non-empty by CliError's constructor, so the\n * envelope's \"every error carries a hint\" invariant holds for every path\n * that reaches here.\n */\n fail(error: CliError, data?: unknown): ExitCode {\n this.failWith({\n code: error.code,\n message: error.message,\n hint: error.hint,\n exitCode: error.exitCode,\n data,\n });\n return error.exitCode;\n }\n\n /**\n * The low-level failure emitter. Used directly by `test`, whose exit code is\n * a TRANSPARENT passthrough of the delegated runner's exit code (which is not\n * one of the CLI's own frozen numeric conditions) and whose error `code` is\n * an out-of-taxonomy string. Enforces the same non-empty-hint invariant as\n * CliError so no failure path can emit an empty hint.\n */\n failWith(params: {\n code: string;\n message: string;\n hint: string;\n exitCode: number;\n data?: unknown;\n }): number {\n this.settle();\n if (!params.hint || params.hint.trim().length === 0) {\n throw new Error(\n `failWith for \"${params.message}\" was given an empty hint. Every CLI ` +\n 'error must carry an imperative remediation.',\n );\n }\n if (this.jsonMode) {\n const envelope: ErrEnvelope = {\n ok: false,\n ...(params.data !== undefined ? { data: params.data } : {}),\n error: {\n code: params.code,\n message: params.message,\n hint: params.hint,\n },\n };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else {\n this.stderr.write(`Error: ${params.message}\\n`);\n this.stderr.write(`Hint: ${params.hint}\\n`);\n }\n return params.exitCode;\n }\n\n private settle(): void {\n if (this.settled) {\n throw new Error(\n 'CliContext settled twice — a command tried to emit a second ' +\n 'terminal result. In JSON mode this would corrupt stdout with two ' +\n 'objects. This is a bug in the command.',\n );\n }\n this.settled = true;\n }\n}\n\nfunction defaultStream(stream: NodeJS.WriteStream): WriteStream {\n return {\n write: (chunk: string) => {\n stream.write(chunk);\n },\n isTTY: stream.isTTY,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAiB,MAAM,cAAc,CAAC;AAqCzD;;;;;;;;GAQG;AAEH;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,UAAU;IAYrB,YAAY,QAAsB,EAAE;;QAF5B,YAAO,GAAG,KAAK,CAAC;QAGtB,MAAM,MAAM,GAAG,MAAA,KAAK,CAAC,MAAM,mCAAI,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,MAAM,GAAG,MAAA,KAAK,CAAC,MAAM,mCAAI,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,GAAG,GAAG,MAAA,KAAK,CAAC,GAAG,mCAAI,OAAO,CAAC,GAAG,CAAC;QAErC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QAEf,4EAA4E;QAC5E,yEAAyE;QACzE,qEAAqE;QACrE,4EAA4E;QAC5E,4BAA4B;QAC5B,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,KAAK,IAAI,CAAC;QACrC,IAAI,CAAC,QAAQ,GAAG,MAAA,KAAK,CAAC,QAAQ,mCAAI,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,CAAC,CAAC;IACvE,CAAC;IAED,iFAAiF;IACjF,IAA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C,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;CACF;AAED,SAAS,aAAa,CAAC,MAA0B;IAC/C,OAAO;QACL,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE;YACvB,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { CliError } from './errors';\nimport { EXIT_CODES, type ExitCode } from './exit-codes';\n\n/**\n * A single writable sink. Real streams satisfy this; tests pass a capturing\n * buffer so the stdout-purity invariant can be asserted byte-for-byte.\n */\nexport interface WriteStream {\n write(chunk: string): void;\n isTTY?: boolean;\n}\n\nexport interface ContextInput {\n /**\n * The user's EXPLICIT preference, already parsed: `true` for `--json`,\n * `false` for `--no-json`, `undefined` when neither was passed. The\n * undefined case is what allows the mode to be inferred instead.\n */\n jsonFlag?: boolean;\n stdout?: WriteStream;\n stderr?: WriteStream;\n /** Overrides process.env for CLAUDECODE detection (tests). */\n env?: Record<string, string | undefined>;\n}\n\n/** The success envelope. */\ninterface OkEnvelope {\n ok: true;\n data: unknown;\n}\n\n/** The error envelope. `data` is optional — validate carries its findings here. */\ninterface ErrEnvelope {\n ok: false;\n data?: unknown;\n error: { code: string; message: string; hint: string };\n}\n\n/**\n * `data` is deliberately `unknown` above — each verb owns its own shape — but\n * one convention spans several of them: `validate`, `dev`, `publish` and\n * `status` all add an OPTIONAL `toolchain` field to `data` (never to the\n * envelope's top level) when the proactive update check in `update-notice.ts`\n * finds this CLI is behind. See that file's `ToolchainNoticeData` for the\n * shape, and `README.md`'s \"Keeping the toolchain current\" section for the\n * full contract. It is absent, not `null`, when there is nothing to report.\n */\n\n/**\n * The agent-native output envelope, resolved ONCE at startup and threaded\n * through every command.\n *\n * The load-bearing invariant: in JSON mode, stdout receives EXACTLY ONE JSON\n * object for the whole process — nothing else, ever. Every progress line, warn,\n * and scrap of human prose goes to stderr. This is the single most common way\n * an agent's tool call breaks (a stray log line on stdout makes the JSON\n * unparseable), so the context enforces it structurally: `succeed`/`fail` are\n * the only writers of stdout, and a `settled` latch makes a second call throw\n * rather than emit a second object.\n */\nexport class CliContext {\n readonly jsonMode: boolean;\n /**\n * The environment the context resolved against — exposed so decoration\n * (the gradient banner) can honour `NO_COLOR` / `EKANOS_NO_BANNER` without\n * every call site threading `process.env` through by hand.\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n private readonly stdout: WriteStream;\n private readonly stderr: WriteStream;\n private settled = false;\n\n constructor(input: ContextInput = {}) {\n const stdout = input.stdout ?? defaultStream(process.stdout);\n const stderr = input.stderr ?? defaultStream(process.stderr);\n const env = input.env ?? process.env;\n\n this.stdout = stdout;\n this.stderr = stderr;\n this.env = env;\n\n // Resolve JSON mode once. An EXPLICIT flag always wins: `--json` forces the\n // envelope on even at a terminal, `--no-json` forces the human form even\n // when piped. Only when the user expressed no preference is the mode\n // inferred — from a non-TTY stdout (piped into another program or an agent)\n // or the CLAUDECODE marker.\n const nonTty = stdout.isTTY !== true;\n this.jsonMode = input.jsonFlag ?? (nonTty || env.CLAUDECODE === '1');\n }\n\n /** Whether stderr is a real terminal — decoration (the banner) gates on this. */\n get stderrIsTTY(): boolean {\n return this.stderr.isTTY === true;\n }\n\n /** Human/progress output — ALWAYS stderr, so stdout stays pure in JSON mode. */\n log(message: string): void {\n this.stderr.write(`${message}\\n`);\n }\n\n /** A warning — stderr, no ANSI. */\n warn(message: string): void {\n this.stderr.write(`${message}\\n`);\n }\n\n /**\n * Emit the `claude-code-hint` protocol line to STDERR. Used on --help and on\n * an unknown command so an agent reading stderr is told what to do next\n * without the line ever touching stdout.\n */\n emitClaudeCodeHint(payload: Record<string, unknown>): void {\n this.stderr.write(`claude-code-hint: ${JSON.stringify(payload)}\\n`);\n }\n\n /**\n * Terminal success. Writes the single stdout object (JSON mode) or a concise\n * human line (human mode). Returns the OK exit code so the caller can end the\n * process with it. Idempotent-by-latch: a second settle throws.\n */\n succeed(data: unknown, humanSummary?: string): ExitCode {\n this.settle();\n if (this.jsonMode) {\n const envelope: OkEnvelope = { ok: true, data };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else {\n this.stdout.write(`${humanSummary ?? 'OK'}\\n`);\n }\n return EXIT_CODES.OK;\n }\n\n /**\n * Terminal failure. Writes the single stdout error object (JSON mode) or the\n * message + hint to stderr (human mode). Returns the error's exit code.\n *\n * `error.hint` is guaranteed non-empty by CliError's constructor, so the\n * envelope's \"every error carries a hint\" invariant holds for every path\n * that reaches here.\n */\n fail(error: CliError, data?: unknown): ExitCode {\n this.failWith({\n code: error.code,\n message: error.message,\n hint: error.hint,\n exitCode: error.exitCode,\n data,\n });\n return error.exitCode;\n }\n\n /**\n * The low-level failure emitter. Used directly by `test`, whose exit code is\n * a TRANSPARENT passthrough of the delegated runner's exit code (which is not\n * one of the CLI's own frozen numeric conditions) and whose error `code` is\n * an out-of-taxonomy string. Enforces the same non-empty-hint invariant as\n * CliError so no failure path can emit an empty hint.\n */\n failWith(params: {\n code: string;\n message: string;\n hint: string;\n exitCode: number;\n data?: unknown;\n }): number {\n this.settle();\n if (!params.hint || params.hint.trim().length === 0) {\n throw new Error(\n `failWith for \"${params.message}\" was given an empty hint. Every CLI ` +\n 'error must carry an imperative remediation.',\n );\n }\n if (this.jsonMode) {\n const envelope: ErrEnvelope = {\n ok: false,\n ...(params.data !== undefined ? { data: params.data } : {}),\n error: {\n code: params.code,\n message: params.message,\n hint: params.hint,\n },\n };\n this.stdout.write(`${JSON.stringify(envelope)}\\n`);\n } else {\n this.stderr.write(`Error: ${params.message}\\n`);\n this.stderr.write(`Hint: ${params.hint}\\n`);\n }\n return params.exitCode;\n }\n\n private settle(): void {\n if (this.settled) {\n throw new Error(\n 'CliContext settled twice — a command tried to emit a second ' +\n 'terminal result. In JSON mode this would corrupt stdout with two ' +\n 'objects. This is a bug in the command.',\n );\n }\n this.settled = true;\n }\n}\n\nfunction defaultStream(stream: NodeJS.WriteStream): WriteStream {\n return {\n write: (chunk: string) => {\n stream.write(chunk);\n },\n isTTY: stream.isTTY,\n };\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
export interface DelegationPlan {
|
|
3
|
+
shouldDelegate: boolean;
|
|
4
|
+
ownVersion: string;
|
|
5
|
+
localVersion?: string;
|
|
6
|
+
/** Absolute path to the local CLI's bin entry, when `shouldDelegate`. */
|
|
7
|
+
localBinPath?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Decide whether this invocation should delegate. Pure and side-effect-free
|
|
11
|
+
* (beyond the one file read of the local `@ekanos/cli` manifest, mirroring
|
|
12
|
+
* `readInstalledHarness`/`dev`'s own project-package resolution rather than
|
|
13
|
+
* writing a second one) so it is directly testable without spawning anything.
|
|
14
|
+
*/
|
|
15
|
+
export declare function planDelegation(argv: readonly string[], env: Record<string, string | undefined>, cwd: string): DelegationPlan;
|
|
16
|
+
/**
|
|
17
|
+
* The one-line stderr announcement — human mode only, and NEVER on stdout
|
|
18
|
+
* (a delegated `validate --json` must still emit exactly one JSON object on
|
|
19
|
+
* stdout, from the CHILD, with nothing of ours ahead of it).
|
|
20
|
+
*/
|
|
21
|
+
export declare function announceDelegation(plan: DelegationPlan, argv: readonly string[], env: Record<string, string | undefined>, stdoutIsTTY: boolean): void;
|
|
22
|
+
/**
|
|
23
|
+
* Spawn the local CLI's own bin entry with the SAME node executable,
|
|
24
|
+
* `stdio: 'inherit'` so the JSON envelope and banner gating are
|
|
25
|
+
* byte-identical to a direct run, and propagate its exit code exactly.
|
|
26
|
+
* `spawnFn` is injectable so tests never actually fork a process.
|
|
27
|
+
*/
|
|
28
|
+
export declare function delegate(plan: DelegationPlan, argv: readonly string[], env: NodeJS.ProcessEnv, spawnFn?: typeof spawn): Promise<number>;
|
package/dist/delegate.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { cliVersion } from './compatibility.js';
|
|
4
|
+
import { readInstalledPackageManifest } from './harness-scaffold.js';
|
|
5
|
+
/**
|
|
6
|
+
* Wrapper-style delegation to the project-local `@ekanos/cli` — the
|
|
7
|
+
* Gradle-wrapper / Yarn / `npx` pattern, applied to this CLI.
|
|
8
|
+
*
|
|
9
|
+
* A global install bundles ONE `@ekanos/integration-schema` version but
|
|
10
|
+
* routinely serves N projects on different `@ekanos/sdk` versions — it
|
|
11
|
+
* cannot be correct for all of them simultaneously (this is exactly the
|
|
12
|
+
* failure mode `schema-skew.ts` detects). Delegation dissolves the tension:
|
|
13
|
+
* `ekanos` stays on PATH for convenience, but the four verbs that actually
|
|
14
|
+
* read or generate project files always run through the project's OWN
|
|
15
|
+
* pinned copy when one is installed and differs from the invoked binary.
|
|
16
|
+
*
|
|
17
|
+
* Machine-level verbs (`init`, `login`, `logout`, `whoami`, `sources`,
|
|
18
|
+
* `use`, `status`, `upgrade`) are deliberately NEVER delegated: you never
|
|
19
|
+
* want an old local copy handling credentials, and `upgrade` must always be
|
|
20
|
+
* the newest logic doing the upgrading — delegating it could have an old CLI
|
|
21
|
+
* "upgrade" a project using its own out-of-date resolution.
|
|
22
|
+
*/
|
|
23
|
+
const DELEGATABLE_VERBS = new Set(['validate', 'publish', 'dev', 'test']);
|
|
24
|
+
/** The first bare (non-flag) token before a standalone `--` — mirrors `splitCommand` in `index.ts`. */
|
|
25
|
+
function firstCommand(argv) {
|
|
26
|
+
for (const token of argv) {
|
|
27
|
+
if (token === '--')
|
|
28
|
+
break;
|
|
29
|
+
if (!token.startsWith('-'))
|
|
30
|
+
return token;
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
/** `--dir <path>` / `--dir=<path>`, before a standalone `--`. */
|
|
35
|
+
function scanDirFlag(argv) {
|
|
36
|
+
for (let i = 0; i < argv.length; i++) {
|
|
37
|
+
const token = argv[i];
|
|
38
|
+
if (token === '--')
|
|
39
|
+
break;
|
|
40
|
+
if (token === '--dir')
|
|
41
|
+
return argv[i + 1];
|
|
42
|
+
if (token.startsWith('--dir='))
|
|
43
|
+
return token.slice('--dir='.length);
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Decide whether this invocation should delegate. Pure and side-effect-free
|
|
49
|
+
* (beyond the one file read of the local `@ekanos/cli` manifest, mirroring
|
|
50
|
+
* `readInstalledHarness`/`dev`'s own project-package resolution rather than
|
|
51
|
+
* writing a second one) so it is directly testable without spawning anything.
|
|
52
|
+
*/
|
|
53
|
+
export function planDelegation(argv, env, cwd) {
|
|
54
|
+
var _a;
|
|
55
|
+
const ownVersion = cliVersion();
|
|
56
|
+
// The recursion guard, and the explicit escape hatch, both win outright.
|
|
57
|
+
if (env.EKANOS_DELEGATED === '1' || env.EKANOS_NO_DELEGATE === '1') {
|
|
58
|
+
return { shouldDelegate: false, ownVersion };
|
|
59
|
+
}
|
|
60
|
+
const command = firstCommand(argv);
|
|
61
|
+
if (!command || !DELEGATABLE_VERBS.has(command)) {
|
|
62
|
+
return { shouldDelegate: false, ownVersion };
|
|
63
|
+
}
|
|
64
|
+
const projectDir = path.resolve(cwd, (_a = scanDirFlag(argv)) !== null && _a !== void 0 ? _a : '.');
|
|
65
|
+
// Best-effort, like every other resolution this function does: a corrupt
|
|
66
|
+
// local manifest must fall through to "don't delegate", never throw. This
|
|
67
|
+
// runs in `bin.ts` BEFORE `run()`'s try/catch exists, so an uncaught throw
|
|
68
|
+
// here would bypass the JSON-envelope error machinery entirely and print a
|
|
69
|
+
// raw stderr string instead — a real regression in the "exactly one
|
|
70
|
+
// terminal emission" contract the rest of this package guarantees.
|
|
71
|
+
let local = null;
|
|
72
|
+
try {
|
|
73
|
+
local = readInstalledPackageManifest(projectDir, '@ekanos/cli');
|
|
74
|
+
}
|
|
75
|
+
catch (_b) {
|
|
76
|
+
local = null;
|
|
77
|
+
}
|
|
78
|
+
if (!local || local.version === ownVersion) {
|
|
79
|
+
return { shouldDelegate: false, ownVersion, localVersion: local === null || local === void 0 ? void 0 : local.version };
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
shouldDelegate: true,
|
|
83
|
+
ownVersion,
|
|
84
|
+
localVersion: local.version,
|
|
85
|
+
localBinPath: path.join(projectDir, 'node_modules', '@ekanos', 'cli', 'dist', 'bin.js'),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Same JSON-mode inference `CliContext` uses (`context.ts`) — duplicated
|
|
90
|
+
* deliberately rather than shared, because this runs BEFORE a `CliContext`
|
|
91
|
+
* exists (delegation is decided ahead of the whole `run()` machinery). Keep
|
|
92
|
+
* this in sync with `CliContext`'s constructor if that heuristic ever
|
|
93
|
+
* changes: an explicit `--json`/`--no-json` wins, otherwise a non-TTY stdout
|
|
94
|
+
* or `CLAUDECODE=1` means JSON mode.
|
|
95
|
+
*/
|
|
96
|
+
function looksLikeJsonMode(argv, env, stdoutIsTTY) {
|
|
97
|
+
for (const token of argv) {
|
|
98
|
+
if (token === '--')
|
|
99
|
+
break;
|
|
100
|
+
if (token === '--json')
|
|
101
|
+
return true;
|
|
102
|
+
if (token === '--no-json')
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
return !stdoutIsTTY || env.CLAUDECODE === '1';
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The one-line stderr announcement — human mode only, and NEVER on stdout
|
|
109
|
+
* (a delegated `validate --json` must still emit exactly one JSON object on
|
|
110
|
+
* stdout, from the CHILD, with nothing of ours ahead of it).
|
|
111
|
+
*/
|
|
112
|
+
export function announceDelegation(plan, argv, env, stdoutIsTTY) {
|
|
113
|
+
if (!plan.shouldDelegate)
|
|
114
|
+
return;
|
|
115
|
+
if (looksLikeJsonMode(argv, env, stdoutIsTTY))
|
|
116
|
+
return;
|
|
117
|
+
process.stderr.write(`ekanos: using this project's pinned CLI ${plan.localVersion} (global: ` +
|
|
118
|
+
`${plan.ownVersion}). Set EKANOS_NO_DELEGATE=1 to bypass.\n`);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Spawn the local CLI's own bin entry with the SAME node executable,
|
|
122
|
+
* `stdio: 'inherit'` so the JSON envelope and banner gating are
|
|
123
|
+
* byte-identical to a direct run, and propagate its exit code exactly.
|
|
124
|
+
* `spawnFn` is injectable so tests never actually fork a process.
|
|
125
|
+
*/
|
|
126
|
+
export function delegate(plan, argv, env, spawnFn = spawn) {
|
|
127
|
+
return new Promise((resolve) => {
|
|
128
|
+
const child = spawnFn(process.execPath, [plan.localBinPath, ...argv], {
|
|
129
|
+
stdio: 'inherit',
|
|
130
|
+
env: Object.assign(Object.assign({}, env), { EKANOS_DELEGATED: '1' }),
|
|
131
|
+
});
|
|
132
|
+
child.on('error', () => resolve(1));
|
|
133
|
+
child.on('exit', (code) => resolve(code !== null && code !== void 0 ? code : 1));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
//# sourceMappingURL=delegate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"delegate.js","sourceRoot":"","sources":["../src/delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAElE;;;;;;;;;;;;;;;;;GAiBG;AAEH,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,UAAU,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AAU1E,uGAAuG;AACvG,SAAS,YAAY,CAAC,IAAuB;IAC3C,KAAK,MAAM,KAAK,IAAI,IAAI,EAAE,CAAC;QACzB,IAAI,KAAK,KAAK,IAAI;YAAE,MA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O;IACjC,IAAI,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,CAAC;QAAE,OAAO;IAEtD,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,2CAA2C,IAAI,CAAC,YAAY,YAAY;QACtE,GAAG,IAAI,CAAC,UAAU,0CAA0C,CAC/D,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CACtB,IAAoB,EACpB,IAAuB,EACvB,GAAsB,EACtB,UAAwB,KAAK;IAE7B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,YAAa,EAAE,GAAG,IAAI,CAAC,EAAE;YACrE,KAAK,EAAE,SAAS;YAChB,GAAG,kCAAO,GAAG,KAAE,gBAAgB,EAAE,GAAG,GAAE;SACvC,CAAC,CAAC;QACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QACpC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,CAAC,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { spawn } from 'node:child_process';\nimport * as path from 'node:path';\n\nimport { cliVersion } from './compatibility';\nimport { readInstalledPackageManifest } from './harness-scaffold';\n\n/**\n * Wrapper-style delegation to the project-local `@ekanos/cli` — the\n * Gradle-wrapper / Yarn / `npx` pattern, applied to this CLI.\n *\n * A global install bundles ONE `@ekanos/integration-schema` version but\n * routinely serves N projects on different `@ekanos/sdk` versions — it\n * cannot be correct for all of them simultaneously (this is exactly the\n * failure mode `schema-skew.ts` detects). Delegation dissolves the tension:\n * `ekanos` stays on PATH for convenience, but the four verbs that actually\n * read or generate project files always run through the project's OWN\n * pinned copy when one is installed and differs from the invoked binary.\n *\n * Machine-level verbs (`init`, `login`, `logout`, `whoami`, `sources`,\n * `use`, `status`, `upgrade`) are deliberately NEVER delegated: you never\n * want an old local copy handling credentials, and `upgrade` must always be\n * the newest logic doing the upgrading — delegating it could have an old CLI\n * \"upgrade\" a project using its own out-of-date resolution.\n */\n\nconst DELEGATABLE_VERBS = new Set(['validate', 'publish', 'dev', 'test']);\n\nexport interface DelegationPlan {\n shouldDelegate: boolean;\n ownVersion: string;\n localVersion?: string;\n /** Absolute path to the local CLI's bin entry, when `shouldDelegate`. */\n localBinPath?: string;\n}\n\n/** The first bare (non-flag) token before a standalone `--` — mirrors `splitCommand` in `index.ts`. */\nfunction firstCommand(argv: readonly string[]): string | null {\n for (const token of argv) {\n if (token === '--') break;\n if (!token.startsWith('-')) return token;\n }\n return null;\n}\n\n/** `--dir <path>` / `--dir=<path>`, before a standalone `--`. */\nfunction scanDirFlag(argv: readonly string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i]!;\n if (token === '--') break;\n if (token === '--dir') return argv[i + 1];\n if (token.startsWith('--dir=')) return token.slice('--dir='.length);\n }\n return undefined;\n}\n\n/**\n * Decide whether this invocation should delegate. Pure and side-effect-free\n * (beyond the one file read of the local `@ekanos/cli` manifest, mirroring\n * `readInstalledHarness`/`dev`'s own project-package resolution rather than\n * writing a second one) so it is directly testable without spawning anything.\n */\nexport function planDelegation(\n argv: readonly string[],\n env: Record<string, string | undefined>,\n cwd: string,\n): DelegationPlan {\n const ownVersion = cliVersion();\n\n // The recursion guard, and the explicit escape hatch, both win outright.\n if (env.EKANOS_DELEGATED === '1' || env.EKANOS_NO_DELEGATE === '1') {\n return { shouldDelegate: false, ownVersion };\n }\n\n const command = firstCommand(argv);\n if (!command || !DELEGATABLE_VERBS.has(command)) {\n return { shouldDelegate: false, ownVersion };\n }\n\n const projectDir = path.resolve(cwd, scanDirFlag(argv) ?? '.');\n // Best-effort, like every other resolution this function does: a corrupt\n // local manifest must fall through to \"don't delegate\", never throw. This\n // runs in `bin.ts` BEFORE `run()`'s try/catch exists, so an uncaught throw\n // here would bypass the JSON-envelope error machinery entirely and print a\n // raw stderr string instead — a real regression in the \"exactly one\n // terminal emission\" contract the rest of this package guarantees.\n let local: ReturnType<typeof readInstalledPackageManifest> = null;\n try {\n local = readInstalledPackageManifest(projectDir, '@ekanos/cli');\n } catch {\n local = null;\n }\n\n if (!local || local.version === ownVersion) {\n return { shouldDelegate: false, ownVersion, localVersion: local?.version };\n }\n\n return {\n shouldDelegate: true,\n ownVersion,\n localVersion: local.version,\n localBinPath: path.join(\n projectDir,\n 'node_modules',\n '@ekanos',\n 'cli',\n 'dist',\n 'bin.js',\n ),\n };\n}\n\n/**\n * Same JSON-mode inference `CliContext` uses (`context.ts`) — duplicated\n * deliberately rather than shared, because this runs BEFORE a `CliContext`\n * exists (delegation is decided ahead of the whole `run()` machinery). Keep\n * this in sync with `CliContext`'s constructor if that heuristic ever\n * changes: an explicit `--json`/`--no-json` wins, otherwise a non-TTY stdout\n * or `CLAUDECODE=1` means JSON mode.\n */\nfunction looksLikeJsonMode(\n argv: readonly string[],\n env: Record<string, string | undefined>,\n stdoutIsTTY: boolean,\n): boolean {\n for (const token of argv) {\n if (token === '--') break;\n if (token === '--json') return true;\n if (token === '--no-json') return false;\n }\n return !stdoutIsTTY || env.CLAUDECODE === '1';\n}\n\n/**\n * The one-line stderr announcement — human mode only, and NEVER on stdout\n * (a delegated `validate --json` must still emit exactly one JSON object on\n * stdout, from the CHILD, with nothing of ours ahead of it).\n */\nexport function announceDelegation(\n plan: DelegationPlan,\n argv: readonly string[],\n env: Record<string, string | undefined>,\n stdoutIsTTY: boolean,\n): void {\n if (!plan.shouldDelegate) return;\n if (looksLikeJsonMode(argv, env, stdoutIsTTY)) return;\n\n process.stderr.write(\n `ekanos: using this project's pinned CLI ${plan.localVersion} (global: ` +\n `${plan.ownVersion}). Set EKANOS_NO_DELEGATE=1 to bypass.\\n`,\n );\n}\n\n/**\n * Spawn the local CLI's own bin entry with the SAME node executable,\n * `stdio: 'inherit'` so the JSON envelope and banner gating are\n * byte-identical to a direct run, and propagate its exit code exactly.\n * `spawnFn` is injectable so tests never actually fork a process.\n */\nexport function delegate(\n plan: DelegationPlan,\n argv: readonly string[],\n env: NodeJS.ProcessEnv,\n spawnFn: typeof spawn = spawn,\n): Promise<number> {\n return new Promise((resolve) => {\n const child = spawnFn(process.execPath, [plan.localBinPath!, ...argv], {\n stdio: 'inherit',\n env: { ...env, EKANOS_DELEGATED: '1' },\n });\n child.on('error', () => resolve(1));\n child.on('exit', (code) => resolve(code ?? 1));\n });\n}\n"]}
|
|
@@ -44,16 +44,31 @@ export interface WrittenFiles {
|
|
|
44
44
|
unchanged: string[];
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
|
-
* Read
|
|
48
|
-
* `node_modules`. Resolved by path rather than `require.resolve`
|
|
49
|
-
*
|
|
50
|
-
*
|
|
47
|
+
* Read an installed package's `package.json` out of a project's TOP-LEVEL
|
|
48
|
+
* `node_modules`. Resolved by direct path join rather than `require.resolve`
|
|
49
|
+
* on purpose, for two independent reasons:
|
|
50
|
+
*
|
|
51
|
+
* - The CLI runs from its own install and must read the version of the copy
|
|
52
|
+
* in THE CALLER'S project, not one hoisted next to itself.
|
|
53
|
+
* - Several of the packages this reads (`@ekanos/integration-schema`
|
|
54
|
+
* included) declare an `exports` map with no `./package.json` subpath, so
|
|
55
|
+
* `require.resolve('<pkg>/package.json')` throws
|
|
56
|
+
* `ERR_PACKAGE_PATH_NOT_EXPORTED` under Node's ESM resolver. A plain file
|
|
57
|
+
* read is not subject to the export map at all.
|
|
58
|
+
*
|
|
59
|
+
* Shared by every "what does this project have installed?" check in the
|
|
60
|
+
* CLI — `readInstalledHarness` below, the schema-skew gate, and `upgrade`'s
|
|
61
|
+
* current-toolchain report — so there is exactly one implementation of "read
|
|
62
|
+
* a package's on-disk version", not a subtly different one per call site.
|
|
51
63
|
*/
|
|
52
|
-
export interface
|
|
64
|
+
export interface InstalledPackage {
|
|
53
65
|
version: string;
|
|
54
|
-
/** The raw package.json,
|
|
66
|
+
/** The raw package.json, for callers that need more than the version. */
|
|
55
67
|
manifest: unknown;
|
|
56
68
|
}
|
|
69
|
+
export declare function readInstalledPackageManifest(projectDir: string, packageName: string): InstalledPackage | null;
|
|
70
|
+
/** Read the installed `@ekanos/harness` version out of the partner's project. */
|
|
71
|
+
export type InstalledHarness = InstalledPackage;
|
|
57
72
|
export declare function readInstalledHarness(projectDir: string): InstalledHarness | null;
|
|
58
73
|
/** Just the installed version, for callers that need nothing else. */
|
|
59
74
|
export declare function readInstalledHarnessVersion(projectDir: string): string | null;
|
package/dist/harness-scaffold.js
CHANGED
|
@@ -88,12 +88,12 @@ export const REQUIRED_DEPENDENCIES = [
|
|
|
88
88
|
'tailwindcss',
|
|
89
89
|
'@tailwindcss/postcss',
|
|
90
90
|
];
|
|
91
|
-
export function
|
|
92
|
-
const
|
|
93
|
-
if (!fs.existsSync(
|
|
91
|
+
export function readInstalledPackageManifest(projectDir, packageName) {
|
|
92
|
+
const manifestPath = path.join(projectDir, 'node_modules', ...packageName.split('/'), 'package.json');
|
|
93
|
+
if (!fs.existsSync(manifestPath))
|
|
94
94
|
return null;
|
|
95
95
|
try {
|
|
96
|
-
const parsed = JSON.parse(fs.readFileSync(
|
|
96
|
+
const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
97
97
|
const version = typeof parsed === 'object' && parsed !== null
|
|
98
98
|
? parsed.version
|
|
99
99
|
: undefined;
|
|
@@ -102,9 +102,12 @@ export function readInstalledHarness(projectDir) {
|
|
|
102
102
|
return { version, manifest: parsed };
|
|
103
103
|
}
|
|
104
104
|
catch (error) {
|
|
105
|
-
throw preconditionError(`${
|
|
105
|
+
throw preconditionError(`${packageName}'s package.json in node_modules is unreadable: ${error instanceof Error ? error.message : String(error)}`, `Reinstall dependencies in ${projectDir} so ${packageName} resolves.`);
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
|
+
export function readInstalledHarness(projectDir) {
|
|
109
|
+
return readInstalledPackageManifest(projectDir, HARNESS_PACKAGE);
|
|
110
|
+
}
|
|
108
111
|
/** Just the installed version, for callers that need nothing else. */
|
|
109
112
|
export function readInstalledHarnessVersion(projectDir) {
|
|
110
113
|
var _a, _b;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"harness-scaffold.js","sourceRoot":"","sources":["../src/harness-scaffold.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,gEAAgE;AAChE,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAEjD,qEAAqE;AACrE,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AAE3D,yEAAyE;AACzE,MAAM,CAAC,MAAM,eAAe,GAAG,UAAU,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,iBAAiB,CAAC;AAEhD,0EAA0E;AAC1E,MAAM,CAAC,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAE3D;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,WAAW,GAAkD;IACxE,EAAE,QAAQ,EAAE,6BAA6B,EAAE,IAAI,EAAE,gBAAgB,EAAE;IACnE;QACE,QAAQ,EAAE,oCAAoC;QAC9C,IAAI,EA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AAC;AAED,SAAS,eAAe,CAAC,MAAc;IACrC,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;IAC9E,OAAO,MAAM;SACV,KAAK,CAAC,IAAI,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC1B,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { cliVersion, templatesFingerprint } from './compatibility';\nimport { invalidStateError, preconditionError } from './errors';\nimport {\n appendFileNoFollow,\n classifyPath,\n readFileNoFollow,\n writeFileNoFollow,\n} from './safe-fs';\nimport { readTemplate } from './templates';\n\n/** The dependency that owns every line of harness behaviour. */\nexport const HARNESS_PACKAGE = '@ekanos/harness';\n\n/** Where the generated shell lives, relative to the project root. */\nexport const HARNESS_DIR = path.join('.ekanos', 'harness');\n\n/** The single `.gitignore` line that covers the whole generated tree. */\nexport const GITIGNORE_ENTRY = '.ekanos/';\n\n/**\n * The staleness marker, inside the generated tree so deleting the tree also\n * deletes the marker. Holds the `@ekanos/harness` version that generated the\n * shell — a version bump means the shell may be wired against an older export\n * surface, so it is regenerated.\n */\nexport const VERSION_MARKER = '.ekanos-version';\n\n/** The partner-owned registry, at the PROJECT ROOT. Never regenerated. */\nexport const HARNESS_CONFIG_FILENAME = 'harness.config.ts';\n\n/**\n * Every file in the generated shell: bundled template → path inside\n * `.ekanos/harness/`. The nine route files are mechanically derivable from the\n * export map alone — which is the test of whether the package boundary is in\n * the right place. If a shell file ever needs a judgment call, the boundary\n * has moved, not the template.\n *\n * `app/harness-shell.tsx` exists because a `HarnessIntegration` holds React\n * component references and MCP `run` functions. Next cannot serialize those\n * across a server→client boundary, so the `'use client'` mark has to sit ABOVE\n * the point where the registry is injected — hence a client shell of its own\n * rather than a client `RootLayout` called from a server layout. Keeping\n * `app/page.tsx` a server component is what lets `/` prerender static.\n */\nexport const SHELL_FILES: readonly { template: string; dest: string }[] = [\n { template: 'harness/app/layout.tsx.tmpl', dest: 'app/layout.tsx' },\n {\n template: 'harness/app/harness-shell.tsx.tmpl',\n dest: 'app/harness-shell.tsx',\n },\n { template: 'harness/app/page.tsx.tmpl', dest: 'app/page.tsx' },\n {\n template: 'harness/app/[slug]/layout.tsx.tmpl',\n dest: 'app/[slug]/layout.tsx',\n },\n {\n template: 'harness/app/[slug]/widgets/page.tsx.tmpl',\n dest: 'app/[slug]/widgets/page.tsx',\n },\n {\n template: 'harness/app/[slug]/widgets/[widgetId]/page.tsx.tmpl',\n dest: 'app/[slug]/widgets/[widgetId]/page.tsx',\n },\n {\n template: 'harness/app/[slug]/tile/page.tsx.tmpl',\n dest: 'app/[slug]/tile/page.tsx',\n },\n {\n template: 'harness/app/[slug]/activation/page.tsx.tmpl',\n dest: 'app/[slug]/activation/page.tsx',\n },\n {\n template: 'harness/app/[slug]/triggers/page.tsx.tmpl',\n dest: 'app/[slug]/triggers/page.tsx',\n },\n { template: 'harness/next.config.mjs.tmpl', dest: 'next.config.mjs' },\n { template: 'harness/postcss.config.mjs.tmpl', dest: 'postcss.config.mjs' },\n { template: 'harness/tsconfig.json.tmpl', dest: 'tsconfig.json' },\n { template: 'harness/styles/globals.css.tmpl', dest: 'styles/globals.css' },\n { template: 'harness/package.json.tmpl', dest: 'package.json' },\n {\n template: 'harness/types/team-accounts.d.ts.tmpl',\n dest: 'types/team-accounts.d.ts',\n },\n];\n\n/**\n * Packages the shell needs to resolve upward out of the partner's own\n * `node_modules`. The shell declares no dependencies of its own by design, so\n * a missing one shows up as an opaque Next resolution error at dev-server\n * start; checking here turns that into one precondition with one fix.\n */\nexport const REQUIRED_DEPENDENCIES = [\n HARNESS_PACKAGE,\n 'next',\n 'react',\n 'react-dom',\n 'tailwindcss',\n '@tailwindcss/postcss',\n] as const;\n\nexport interface WrittenFiles {\n created: string[];\n updated: string[];\n unchanged: string[];\n}\n\n/**\n * Read the installed `@ekanos/harness` version out of the partner's\n * `node_modules`. Resolved by path rather than `require.resolve` on purpose:\n * the CLI runs from its own install and must read the version of the copy in\n * THEIR project, not one hoisted next to itself.\n */\nexport interface InstalledHarness {\n version: string;\n /** The raw package.json, so compatibility can read its `ekanos` block. */\n manifest: unknown;\n}\n\nexport function readInstalledHarness(\n projectDir: string,\n): InstalledHarness | null {\n const manifest = path.join(\n projectDir,\n 'node_modules',\n HARNESS_PACKAGE,\n 'package.json',\n );\n if (!fs.existsSync(manifest)) return null;\n\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(manifest, 'utf8'));\n const version =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { version?: unknown }).version\n : undefined;\n if (typeof version !== 'string' || version.length === 0) return null;\n return { version, manifest: parsed };\n } catch (error) {\n throw preconditionError(\n `${HARNESS_PACKAGE}'s package.json in node_modules is unreadable: ${\n error instanceof Error ? error.message : String(error)\n }`,\n `Reinstall dependencies in ${projectDir} so ${HARNESS_PACKAGE} resolves.`,\n );\n }\n}\n\n/** Just the installed version, for callers that need nothing else. */\nexport function readInstalledHarnessVersion(projectDir: string): string | null {\n return readInstalledHarness(projectDir)?.version ?? null;\n}\n\n/** Which of `REQUIRED_DEPENDENCIES` are not installed in the project root. */\nexport function missingDependencies(projectDir: string): string[] {\n return REQUIRED_DEPENDENCIES.filter(\n (name) =>\n !fs.existsSync(\n path.join(projectDir, 'node_modules', name, 'package.json'),\n ),\n );\n}\n\n/**\n * What generated an existing shell.\n *\n * All three fields matter, and recording only `harness` was a real hole: the\n * templates ship with the CLI, so a shell can be stale because the CLI changed\n * while the harness did not. `templates` is the authoritative one — it is a\n * hash of the template sources, so it moves whenever what we generate moves,\n * including for a CLI build that never shipped a version bump.\n */\nexport interface ShellMarker {\n harness: string;\n /** null for a legacy bare-version marker written before this was recorded. */\n cli: string | null;\n templates: string | null;\n}\n\n/**\n * Three outcomes, not two, because \"no marker\" and \"unreadable marker\" call\n * for opposite responses.\n *\n * A marker's PRESENCE is itself evidence the tree is ours — a squatter does\n * not write `.ekanos-version` — and the likeliest cause of an unreadable one\n * is our own interrupted write. Everything under `.ekanos/harness/` is\n * CLI-owned, gitignored and reproducible from the templates, so regenerating\n * destroys nothing: there is no value at risk to justify charging a partner a\n * confusing `--force` to recover from our own bad write.\n *\n * An ABSENT marker over a non-empty tree is the opposite: nothing says the\n * files are ours, so we refuse. That is the L1 rule and it stays.\n */\nexport type MarkerState =\n | { kind: 'missing' }\n | { kind: 'corrupt' }\n | { kind: 'ok'; marker: ShellMarker };\n\nexport function readShellMarkerState(harnessDir: string): MarkerState {\n const marker = path.join(harnessDir, VERSION_MARKER);\n if (classifyPath(marker) !== 'file') return { kind: 'missing' };\n\n const raw = (readFileNoFollow(harnessDir, marker) ?? '').trim();\n if (raw.length === 0) return { kind: 'corrupt' };\n\n const parsed = parseMarker(raw);\n return parsed === null ? { kind: 'corrupt' } : { kind: 'ok', marker: parsed };\n}\n\nfunction parseMarker(raw: string): ShellMarker | null {\n // v1 markers were a bare version string. Read them rather than crashing, and\n // report the unknown fields as null so the shell counts as stale and is\n // regenerated once — which is the correct outcome for an upgrade.\n //\n // It must actually LOOK like a version: without this, any garbage that does\n // not happen to start with `{` — a truncated write, a stray word — reads as\n // a legacy marker named after the garbage, and the corrupt-marker path never\n // fires. That is how a truncated `.ekanos-version` was silently reported as\n // \"@ekanos/harness truncat → 0.1.0\" instead of \"unreadable\".\n if (!raw.startsWith('{')) {\n return /^\\d+\\.\\d+/.test(raw)\n ? { harness: raw, cli: null, templates: null }\n : null;\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed !== 'object' || parsed === null) return null;\n const record = parsed as Record<string, unknown>;\n const harness = record.harness;\n if (typeof harness !== 'string') return null;\n return {\n harness,\n cli: typeof record.cli === 'string' ? record.cli : null,\n templates: typeof record.templates === 'string' ? record.templates : null,\n };\n } catch {\n return null;\n }\n}\n\n/** The parsed marker, or null when it is absent OR unreadable. */\nexport function readShellMarker(harnessDir: string): ShellMarker | null {\n const state = readShellMarkerState(harnessDir);\n return state.kind === 'ok' ? state.marker : null;\n}\n\n/** The `@ekanos/harness` version an existing shell was generated against. */\nexport function readShellVersion(harnessDir: string): string | null {\n return readShellMarker(harnessDir)?.harness ?? null;\n}\n\nfunction serializeMarker(marker: ShellMarker): string {\n return `${JSON.stringify(marker, null, 2)}\\n`;\n}\n\n/**\n * Write a generated file, but ONLY when its bytes would change.\n *\n * This is what makes a re-run cheap and a watcher quiet: an unchanged file is\n * not rewritten, so its mtime does not move and Next's dev server does not\n * rebuild. It also means a hand-edit inside the CLI-owned tree is silently\n * corrected on the next run, which is the intended contract for `.ekanos/`.\n */\nexport function writeIfChanged(\n root: string,\n destPath: string,\n contents: string,\n into: WrittenFiles,\n label: string,\n force: boolean,\n): void {\n // `classifyPath` uses lstat, so a symlink here is reported as a symlink\n // rather than as whatever it points at — including a DANGLING one, which\n // `existsSync` would call absent and a plain write would then materialize\n // outside the project.\n const kind = classifyPath(destPath);\n const exists = kind !== 'missing';\n\n if (\n !force &&\n kind === 'file' &&\n readFileNoFollow(root, destPath) === contents\n ) {\n into.unchanged.push(label);\n return;\n }\n\n writeFileNoFollow(root, destPath, contents);\n (exists ? into.updated : into.created).push(label);\n}\n\nexport interface ScaffoldShellArgs {\n projectDir: string;\n slug: string;\n harnessVersion: string;\n /** Rewrite every file even when its bytes already match. */\n force: boolean;\n /** Extra Tailwind @source globs from ekanos.json, already validated. */\n sourceGlobs?: readonly string[];\n}\n\nexport interface ScaffoldShellResult extends WrittenFiles {\n harnessDir: string;\n /** The version the shell carried before this run — null on a first run. */\n previousVersion: string | null;\n /** What generated the previous shell, or null on a first run. */\n previousMarker: ShellMarker | null;\n /** True when anything that generated the shell has since changed. */\n stale: boolean;\n /**\n * Which of harness / cli / templates moved. Empty on a first run; this is\n * what lets `dev` say WHY it regenerated rather than just that it did.\n */\n staleReasons: string[];\n}\n\n/**\n * Generate `.ekanos/harness/**` for `harnessVersion`. Every file here is\n * CLI-owned and gitignored, so regeneration needs no permission and asks no\n * question — the partner owns `harness.config.ts` and their integration\n * source, and nothing else.\n */\nexport function scaffoldShell(args: ScaffoldShellArgs): ScaffoldShellResult {\n const harnessDir = path.join(args.projectDir, HARNESS_DIR);\n assertShellDirIsOurs(harnessDir, args.force);\n\n const markerState = readShellMarkerState(harnessDir);\n const previousMarker = markerState.kind === 'ok' ? markerState.marker : null;\n const previousVersion = previousMarker?.harness ?? null;\n const marker: ShellMarker = {\n harness: args.harnessVersion,\n cli: cliVersion(),\n templates: templatesFingerprint(SHELL_FILES.map((f) => f.template)),\n };\n\n // A shell is current only if EVERYTHING that produced it is unchanged.\n // Checking the harness version alone certified shells generated by an older\n // CLI, against templates that had since moved, as up to date.\n const staleReasons: string[] = [];\n if (markerState.kind === 'corrupt') {\n staleReasons.push(\n `${VERSION_MARKER} was unreadable, so the existing shell could not be ` +\n 'certified',\n );\n }\n if (previousMarker !== null) {\n if (previousMarker.harness !== marker.harness) {\n staleReasons.push(\n `@ekanos/harness ${previousMarker.harness} → ${marker.harness}`,\n );\n }\n if (previousMarker.cli !== marker.cli) {\n staleReasons.push(\n `@ekanos/cli ${previousMarker.cli ?? 'unknown'} → ${marker.cli}`,\n );\n }\n if (previousMarker.templates !== marker.templates) {\n staleReasons.push('the shell templates changed');\n }\n }\n const stale = staleReasons.length > 0;\n\n const files: WrittenFiles = { created: [], updated: [], unchanged: [] };\n const vars = {\n SLUG: args.slug,\n SOURCE_GLOBS: renderSourceGlobs(args.sourceGlobs ?? []),\n };\n\n for (const { template, dest } of SHELL_FILES) {\n writeIfChanged(\n args.projectDir,\n path.join(harnessDir, dest),\n readTemplate(template, vars),\n files,\n dest,\n args.force,\n );\n }\n\n writeIfChanged(\n args.projectDir,\n path.join(harnessDir, VERSION_MARKER),\n serializeMarker(marker),\n files,\n VERSION_MARKER,\n args.force,\n );\n\n return {\n ...files,\n harnessDir,\n previousVersion,\n previousMarker,\n stale,\n staleReasons,\n };\n}\n\n/**\n * Turn validated `sourceGlobs` into the `@source` lines the generated\n * stylesheet carries, each relative to the shell's `styles/` directory.\n *\n * Tailwind never scans what it is not pointed at, and a glob that matches\n * nothing fails silently — so an integration living outside the default\n * layout renders completely unstyled with no error anywhere. That is what\n * `sourceGlobs` is for, and until now it was parsed and thrown away.\n */\nfunction renderSourceGlobs(globs: readonly string[]): string {\n if (globs.length === 0) return '';\n const lines = globs.map((glob) => `@source '${SHELL_TO_PROJECT}${glob}';`);\n return `\\n/* From \"sourceGlobs\" in ekanos.json. */\\n${lines.join('\\n')}\\n`;\n}\n\n/** From `.ekanos/harness/styles/` back up to the project root. */\nconst SHELL_TO_PROJECT = '../../../';\n\n/**\n * Establish that `.ekanos/harness` is a tree WE generated before writing a\n * single byte into it, and return the version marker it carried.\n *\n * Path location alone is not ownership. A directory that exists but carries no\n * `.ekanos-version` was put there by something else — a partner, another tool,\n * a symlink — and clobbering it because it happens to sit at the path we like\n * is the same class of mistake as following a symlink. An empty directory is\n * fine (that is just `mkdir -p` having run), and `--force` is the explicit\n * override.\n *\n * Runs BEFORE `bootstrapHarnessConfig` in `dev`, so a shell that cannot be\n * written leaves the project completely untouched rather than half-scaffolded.\n */\nexport function assertShellDirIsOurs(\n harnessDir: string,\n force: boolean,\n): string | null {\n const kind = classifyPath(harnessDir);\n\n if (kind === 'symlink') {\n throw invalidStateError(\n `${harnessDir} is a symlink, so \"ekanos dev\" will not write through it.`,\n `Delete ${harnessDir} and re-run \"ekanos dev\" — the shell is generated, ` +\n 'so nothing is lost.',\n );\n }\n\n if (kind !== 'missing' && kind !== 'directory') {\n throw invalidStateError(\n `${harnessDir} exists and is not a directory.`,\n `Move or delete ${harnessDir}, then re-run \"ekanos dev\".`,\n );\n }\n\n if (kind === 'missing') return null;\n\n const state = readShellMarkerState(harnessDir);\n\n // A marker we wrote, however mangled, still identifies the tree as ours.\n if (state.kind === 'ok') return state.marker.harness;\n if (state.kind === 'corrupt' || force) return null;\n\n if (fs.readdirSync(harnessDir).length === 0) return null;\n\n throw invalidStateError(\n `${harnessDir} already contains files but no ${VERSION_MARKER} marker, ` +\n 'so it was not generated by \"ekanos dev\".',\n `Delete ${harnessDir} if you do not need it, or pass --force to ` +\n 'overwrite it. Everything \"ekanos dev\" generates is reproducible; ' +\n 'anything else in there is not.',\n );\n}\n\n/**\n * The module specifier `harness.config.ts` uses to import the partner's\n * integration: the `entry` from ekanos.json, made relative and extension-free.\n * \"src/integration.ts\" → \"src/integration\".\n */\nexport function entryImportSpecifier(entry: string): string {\n const normalized = entry.split(path.sep).join('/').replace(/^\\.\\//, '');\n return normalized.replace(/\\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/, '');\n}\n\n/**\n * The same specifier as a JavaScript string LITERAL, ready to drop into a\n * generated `import` statement.\n *\n * `entry` is attacker-influenced data from `ekanos.json`, and a POSIX filename\n * may legally contain a quote or a newline. Interpolating it raw would let a\n * crafted-but-valid path close the string and append statements to the module\n * we generate. `JSON.stringify` produces a correctly escaped literal, which is\n * the actual fix; the explicit rejection below is a second line that also\n * gives the partner a comprehensible error instead of a bizarre filename\n * silently appearing, escaped, in their config.\n *\n * This does not cross a trust boundary on its own — a partner's own code runs\n * unsandboxed anyway — but \"the templates cannot be injected into\" is a claim\n * we make, and it should be true.\n */\nexport function entryImportLiteral(entry: string): string {\n const specifier = entryImportSpecifier(entry);\n\n // eslint-disable-next-line no-control-regex\n if (/[\"'`\\\\\\n\\r\\u0000-\\u001f]/.test(specifier)) {\n throw preconditionError(\n `The \"entry\" in ekanos.json contains characters that cannot appear in ` +\n `an import specifier: ${JSON.stringify(specifier)}.`,\n 'Rename the file so its path has no quotes, backslashes or control ' +\n 'characters, then update \"entry\" in ekanos.json to match.',\n );\n }\n\n return JSON.stringify(`./${specifier}`);\n}\n\nexport interface BootstrapConfigResult {\n /** True only when this run created the file. */\n bootstrapped: boolean;\n configPath: string;\n}\n\n/**\n * Write a starter `harness.config.ts` at the project root — ONCE.\n *\n * An existing file is left strictly alone, byte for byte, and no flag changes\n * that: it is the one harness file the partner owns, it is git-tracked, and\n * regenerating it would throw away their fixtures. `--force` regenerates the\n * shell, never this.\n */\nexport function bootstrapHarnessConfig(\n projectDir: string,\n integrations: readonly { slug: string; entry: string }[],\n): BootstrapConfigResult {\n const configPath = path.join(projectDir, HARNESS_CONFIG_FILENAME);\n const kind = classifyPath(configPath);\n\n // A symlink here — including a dangling one, which `existsSync` reports as\n // absent — would have us write through to its target. Since this file is the\n // partner's to own, the only safe answer is to touch nothing and say why.\n if (kind === 'symlink') {\n throw invalidStateError(\n `${configPath} is a symlink, so \"ekanos dev\" will not write through it.`,\n `Replace ${configPath} with a real file (or delete it to have one ` +\n 'generated), then re-run \"ekanos dev\".',\n );\n }\n\n if (kind !== 'missing') {\n return { bootstrapped: false, configPath };\n }\n\n writeFileNoFollow(projectDir, configPath, renderHarnessConfig(integrations));\n\n return { bootstrapped: true, configPath };\n}\n\n/**\n * Render the starter registry for EVERY integration the project declares.\n *\n * The harness registry is an array and `ekanos.json` can now hold a list, so a\n * project's second integration reaches the harness the same way its first\n * does. Each entry imports the definition under a distinct local identifier\n * derived from its slug, because two `integration` imports in one module do\n * not compile.\n */\nfunction renderHarnessConfig(\n integrations: readonly { slug: string; entry: string }[],\n): string {\n const imports: string[] = [];\n const entries: string[] = [];\n\n for (const integration of integrations) {\n const ident = identifierForSlug(integration.slug);\n imports.push(\n `import { integration as ${ident} } from ${entryImportLiteral(\n integration.entry,\n )};`,\n );\n entries.push(\n readTemplate('harness.config.entry.ts.tmpl', {\n IDENT: ident,\n SLUG: integration.slug,\n }),\n );\n }\n\n return readTemplate('harness.config.ts.tmpl', {\n INTEGRATION_IMPORTS: imports.join('\\n'),\n INTEGRATION_ENTRIES: entries.join(''),\n });\n}\n\n/**\n * \"acme-crm\" → \"acmeCrm\". A slug is kebab-case by schema, so this only has to\n * handle hyphens, and a leading digit is impossible.\n */\nexport function identifierForSlug(slug: string): string {\n const camel = slug.replace(/-([a-z0-9])/g, (_, char: string) =>\n char.toUpperCase(),\n );\n return /^[0-9]/.test(camel) ? `i${camel}` : camel;\n}\n\n/**\n * Add `.ekanos/` to the project `.gitignore`, exactly once.\n *\n * Matching is line-wise over the spellings git treats as the same rule\n * (`.ekanos`, `.ekanos/`, `/.ekanos/`), so re-running never appends a\n * duplicate — the thing that makes a scaffold verb safe to run in a loop.\n * A negation (`!.ekanos/`) is deliberately NOT treated as a match: the\n * partner meant to un-ignore it, and we do not fight that silently.\n */\nexport function ensureGitignoreEntry(projectDir: string): boolean {\n const gitignorePath = path.join(projectDir, '.gitignore');\n const block = `# Ekanos dev harness — generated by \"ekanos dev\", never edited by hand\\n${GITIGNORE_ENTRY}\\n`;\n\n const kind = classifyPath(gitignorePath);\n\n if (kind === 'symlink') {\n throw invalidStateError(\n `${gitignorePath} is a symlink, so \"ekanos dev\" will not append to it.`,\n `Add \"${GITIGNORE_ENTRY}\" to your real .gitignore yourself, or replace ` +\n `${gitignorePath} with a regular file, then re-run \"ekanos dev\".`,\n );\n }\n\n if (kind === 'missing') {\n writeFileNoFollow(projectDir, gitignorePath, block);\n return true;\n }\n\n const existing = readFileNoFollow(projectDir, gitignorePath) ?? '';\n if (gitignoreCovers(existing)) return false;\n\n const separator =\n existing.length === 0 || existing.endsWith('\\n') ? '' : '\\n';\n appendFileNoFollow(projectDir, gitignorePath, `${separator}\\n${block}`);\n return true;\n}\n\nfunction gitignoreCovers(source: string): boolean {\n const equivalents = new Set(['.ekanos', '.ekanos/', '/.ekanos', '/.ekanos/']);\n return source\n .split('\\n')\n .map((line) => line.trim())\n .some((line) => equivalents.has(line));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"harness-scaffold.js","sourceRoot":"","sources":["../src/harness-scaffold.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO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E,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC1B,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { cliVersion, templatesFingerprint } from './compatibility';\nimport { invalidStateError, preconditionError } from './errors';\nimport {\n appendFileNoFollow,\n classifyPath,\n readFileNoFollow,\n writeFileNoFollow,\n} from './safe-fs';\nimport { readTemplate } from './templates';\n\n/** The dependency that owns every line of harness behaviour. */\nexport const HARNESS_PACKAGE = '@ekanos/harness';\n\n/** Where the generated shell lives, relative to the project root. */\nexport const HARNESS_DIR = path.join('.ekanos', 'harness');\n\n/** The single `.gitignore` line that covers the whole generated tree. */\nexport const GITIGNORE_ENTRY = '.ekanos/';\n\n/**\n * The staleness marker, inside the generated tree so deleting the tree also\n * deletes the marker. Holds the `@ekanos/harness` version that generated the\n * shell — a version bump means the shell may be wired against an older export\n * surface, so it is regenerated.\n */\nexport const VERSION_MARKER = '.ekanos-version';\n\n/** The partner-owned registry, at the PROJECT ROOT. Never regenerated. */\nexport const HARNESS_CONFIG_FILENAME = 'harness.config.ts';\n\n/**\n * Every file in the generated shell: bundled template → path inside\n * `.ekanos/harness/`. The nine route files are mechanically derivable from the\n * export map alone — which is the test of whether the package boundary is in\n * the right place. If a shell file ever needs a judgment call, the boundary\n * has moved, not the template.\n *\n * `app/harness-shell.tsx` exists because a `HarnessIntegration` holds React\n * component references and MCP `run` functions. Next cannot serialize those\n * across a server→client boundary, so the `'use client'` mark has to sit ABOVE\n * the point where the registry is injected — hence a client shell of its own\n * rather than a client `RootLayout` called from a server layout. Keeping\n * `app/page.tsx` a server component is what lets `/` prerender static.\n */\nexport const SHELL_FILES: readonly { template: string; dest: string }[] = [\n { template: 'harness/app/layout.tsx.tmpl', dest: 'app/layout.tsx' },\n {\n template: 'harness/app/harness-shell.tsx.tmpl',\n dest: 'app/harness-shell.tsx',\n },\n { template: 'harness/app/page.tsx.tmpl', dest: 'app/page.tsx' },\n {\n template: 'harness/app/[slug]/layout.tsx.tmpl',\n dest: 'app/[slug]/layout.tsx',\n },\n {\n template: 'harness/app/[slug]/widgets/page.tsx.tmpl',\n dest: 'app/[slug]/widgets/page.tsx',\n },\n {\n template: 'harness/app/[slug]/widgets/[widgetId]/page.tsx.tmpl',\n dest: 'app/[slug]/widgets/[widgetId]/page.tsx',\n },\n {\n template: 'harness/app/[slug]/tile/page.tsx.tmpl',\n dest: 'app/[slug]/tile/page.tsx',\n },\n {\n template: 'harness/app/[slug]/activation/page.tsx.tmpl',\n dest: 'app/[slug]/activation/page.tsx',\n },\n {\n template: 'harness/app/[slug]/triggers/page.tsx.tmpl',\n dest: 'app/[slug]/triggers/page.tsx',\n },\n { template: 'harness/next.config.mjs.tmpl', dest: 'next.config.mjs' },\n { template: 'harness/postcss.config.mjs.tmpl', dest: 'postcss.config.mjs' },\n { template: 'harness/tsconfig.json.tmpl', dest: 'tsconfig.json' },\n { template: 'harness/styles/globals.css.tmpl', dest: 'styles/globals.css' },\n { template: 'harness/package.json.tmpl', dest: 'package.json' },\n {\n template: 'harness/types/team-accounts.d.ts.tmpl',\n dest: 'types/team-accounts.d.ts',\n },\n];\n\n/**\n * Packages the shell needs to resolve upward out of the partner's own\n * `node_modules`. The shell declares no dependencies of its own by design, so\n * a missing one shows up as an opaque Next resolution error at dev-server\n * start; checking here turns that into one precondition with one fix.\n */\nexport const REQUIRED_DEPENDENCIES = [\n HARNESS_PACKAGE,\n 'next',\n 'react',\n 'react-dom',\n 'tailwindcss',\n '@tailwindcss/postcss',\n] as const;\n\nexport interface WrittenFiles {\n created: string[];\n updated: string[];\n unchanged: string[];\n}\n\n/**\n * Read an installed package's `package.json` out of a project's TOP-LEVEL\n * `node_modules`. Resolved by direct path join rather than `require.resolve`\n * on purpose, for two independent reasons:\n *\n * - The CLI runs from its own install and must read the version of the copy\n * in THE CALLER'S project, not one hoisted next to itself.\n * - Several of the packages this reads (`@ekanos/integration-schema`\n * included) declare an `exports` map with no `./package.json` subpath, so\n * `require.resolve('<pkg>/package.json')` throws\n * `ERR_PACKAGE_PATH_NOT_EXPORTED` under Node's ESM resolver. A plain file\n * read is not subject to the export map at all.\n *\n * Shared by every \"what does this project have installed?\" check in the\n * CLI — `readInstalledHarness` below, the schema-skew gate, and `upgrade`'s\n * current-toolchain report — so there is exactly one implementation of \"read\n * a package's on-disk version\", not a subtly different one per call site.\n */\nexport interface InstalledPackage {\n version: string;\n /** The raw package.json, for callers that need more than the version. */\n manifest: unknown;\n}\n\nexport function readInstalledPackageManifest(\n projectDir: string,\n packageName: string,\n): InstalledPackage | null {\n const manifestPath = path.join(\n projectDir,\n 'node_modules',\n ...packageName.split('/'),\n 'package.json',\n );\n if (!fs.existsSync(manifestPath)) return null;\n\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));\n const version =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { version?: unknown }).version\n : undefined;\n if (typeof version !== 'string' || version.length === 0) return null;\n return { version, manifest: parsed };\n } catch (error) {\n throw preconditionError(\n `${packageName}'s package.json in node_modules is unreadable: ${\n error instanceof Error ? error.message : String(error)\n }`,\n `Reinstall dependencies in ${projectDir} so ${packageName} resolves.`,\n );\n }\n}\n\n/** Read the installed `@ekanos/harness` version out of the partner's project. */\nexport type InstalledHarness = InstalledPackage;\n\nexport function readInstalledHarness(\n projectDir: string,\n): InstalledHarness | null {\n return readInstalledPackageManifest(projectDir, HARNESS_PACKAGE);\n}\n\n/** Just the installed version, for callers that need nothing else. */\nexport function readInstalledHarnessVersion(projectDir: string): string | null {\n return readInstalledHarness(projectDir)?.version ?? null;\n}\n\n/** Which of `REQUIRED_DEPENDENCIES` are not installed in the project root. */\nexport function missingDependencies(projectDir: string): string[] {\n return REQUIRED_DEPENDENCIES.filter(\n (name) =>\n !fs.existsSync(\n path.join(projectDir, 'node_modules', name, 'package.json'),\n ),\n );\n}\n\n/**\n * What generated an existing shell.\n *\n * All three fields matter, and recording only `harness` was a real hole: the\n * templates ship with the CLI, so a shell can be stale because the CLI changed\n * while the harness did not. `templates` is the authoritative one — it is a\n * hash of the template sources, so it moves whenever what we generate moves,\n * including for a CLI build that never shipped a version bump.\n */\nexport interface ShellMarker {\n harness: string;\n /** null for a legacy bare-version marker written before this was recorded. */\n cli: string | null;\n templates: string | null;\n}\n\n/**\n * Three outcomes, not two, because \"no marker\" and \"unreadable marker\" call\n * for opposite responses.\n *\n * A marker's PRESENCE is itself evidence the tree is ours — a squatter does\n * not write `.ekanos-version` — and the likeliest cause of an unreadable one\n * is our own interrupted write. Everything under `.ekanos/harness/` is\n * CLI-owned, gitignored and reproducible from the templates, so regenerating\n * destroys nothing: there is no value at risk to justify charging a partner a\n * confusing `--force` to recover from our own bad write.\n *\n * An ABSENT marker over a non-empty tree is the opposite: nothing says the\n * files are ours, so we refuse. That is the L1 rule and it stays.\n */\nexport type MarkerState =\n | { kind: 'missing' }\n | { kind: 'corrupt' }\n | { kind: 'ok'; marker: ShellMarker };\n\nexport function readShellMarkerState(harnessDir: string): MarkerState {\n const marker = path.join(harnessDir, VERSION_MARKER);\n if (classifyPath(marker) !== 'file') return { kind: 'missing' };\n\n const raw = (readFileNoFollow(harnessDir, marker) ?? '').trim();\n if (raw.length === 0) return { kind: 'corrupt' };\n\n const parsed = parseMarker(raw);\n return parsed === null ? { kind: 'corrupt' } : { kind: 'ok', marker: parsed };\n}\n\nfunction parseMarker(raw: string): ShellMarker | null {\n // v1 markers were a bare version string. Read them rather than crashing, and\n // report the unknown fields as null so the shell counts as stale and is\n // regenerated once — which is the correct outcome for an upgrade.\n //\n // It must actually LOOK like a version: without this, any garbage that does\n // not happen to start with `{` — a truncated write, a stray word — reads as\n // a legacy marker named after the garbage, and the corrupt-marker path never\n // fires. That is how a truncated `.ekanos-version` was silently reported as\n // \"@ekanos/harness truncat → 0.1.0\" instead of \"unreadable\".\n if (!raw.startsWith('{')) {\n return /^\\d+\\.\\d+/.test(raw)\n ? { harness: raw, cli: null, templates: null }\n : null;\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed !== 'object' || parsed === null) return null;\n const record = parsed as Record<string, unknown>;\n const harness = record.harness;\n if (typeof harness !== 'string') return null;\n return {\n harness,\n cli: typeof record.cli === 'string' ? record.cli : null,\n templates: typeof record.templates === 'string' ? record.templates : null,\n };\n } catch {\n return null;\n }\n}\n\n/** The parsed marker, or null when it is absent OR unreadable. */\nexport function readShellMarker(harnessDir: string): ShellMarker | null {\n const state = readShellMarkerState(harnessDir);\n return state.kind === 'ok' ? state.marker : null;\n}\n\n/** The `@ekanos/harness` version an existing shell was generated against. */\nexport function readShellVersion(harnessDir: string): string | null {\n return readShellMarker(harnessDir)?.harness ?? null;\n}\n\nfunction serializeMarker(marker: ShellMarker): string {\n return `${JSON.stringify(marker, null, 2)}\\n`;\n}\n\n/**\n * Write a generated file, but ONLY when its bytes would change.\n *\n * This is what makes a re-run cheap and a watcher quiet: an unchanged file is\n * not rewritten, so its mtime does not move and Next's dev server does not\n * rebuild. It also means a hand-edit inside the CLI-owned tree is silently\n * corrected on the next run, which is the intended contract for `.ekanos/`.\n */\nexport function writeIfChanged(\n root: string,\n destPath: string,\n contents: string,\n into: WrittenFiles,\n label: string,\n force: boolean,\n): void {\n // `classifyPath` uses lstat, so a symlink here is reported as a symlink\n // rather than as whatever it points at — including a DANGLING one, which\n // `existsSync` would call absent and a plain write would then materialize\n // outside the project.\n const kind = classifyPath(destPath);\n const exists = kind !== 'missing';\n\n if (\n !force &&\n kind === 'file' &&\n readFileNoFollow(root, destPath) === contents\n ) {\n into.unchanged.push(label);\n return;\n }\n\n writeFileNoFollow(root, destPath, contents);\n (exists ? into.updated : into.created).push(label);\n}\n\nexport interface ScaffoldShellArgs {\n projectDir: string;\n slug: string;\n harnessVersion: string;\n /** Rewrite every file even when its bytes already match. */\n force: boolean;\n /** Extra Tailwind @source globs from ekanos.json, already validated. */\n sourceGlobs?: readonly string[];\n}\n\nexport interface ScaffoldShellResult extends WrittenFiles {\n harnessDir: string;\n /** The version the shell carried before this run — null on a first run. */\n previousVersion: string | null;\n /** What generated the previous shell, or null on a first run. */\n previousMarker: ShellMarker | null;\n /** True when anything that generated the shell has since changed. */\n stale: boolean;\n /**\n * Which of harness / cli / templates moved. Empty on a first run; this is\n * what lets `dev` say WHY it regenerated rather than just that it did.\n */\n staleReasons: string[];\n}\n\n/**\n * Generate `.ekanos/harness/**` for `harnessVersion`. Every file here is\n * CLI-owned and gitignored, so regeneration needs no permission and asks no\n * question — the partner owns `harness.config.ts` and their integration\n * source, and nothing else.\n */\nexport function scaffoldShell(args: ScaffoldShellArgs): ScaffoldShellResult {\n const harnessDir = path.join(args.projectDir, HARNESS_DIR);\n assertShellDirIsOurs(harnessDir, args.force);\n\n const markerState = readShellMarkerState(harnessDir);\n const previousMarker = markerState.kind === 'ok' ? markerState.marker : null;\n const previousVersion = previousMarker?.harness ?? null;\n const marker: ShellMarker = {\n harness: args.harnessVersion,\n cli: cliVersion(),\n templates: templatesFingerprint(SHELL_FILES.map((f) => f.template)),\n };\n\n // A shell is current only if EVERYTHING that produced it is unchanged.\n // Checking the harness version alone certified shells generated by an older\n // CLI, against templates that had since moved, as up to date.\n const staleReasons: string[] = [];\n if (markerState.kind === 'corrupt') {\n staleReasons.push(\n `${VERSION_MARKER} was unreadable, so the existing shell could not be ` +\n 'certified',\n );\n }\n if (previousMarker !== null) {\n if (previousMarker.harness !== marker.harness) {\n staleReasons.push(\n `@ekanos/harness ${previousMarker.harness} → ${marker.harness}`,\n );\n }\n if (previousMarker.cli !== marker.cli) {\n staleReasons.push(\n `@ekanos/cli ${previousMarker.cli ?? 'unknown'} → ${marker.cli}`,\n );\n }\n if (previousMarker.templates !== marker.templates) {\n staleReasons.push('the shell templates changed');\n }\n }\n const stale = staleReasons.length > 0;\n\n const files: WrittenFiles = { created: [], updated: [], unchanged: [] };\n const vars = {\n SLUG: args.slug,\n SOURCE_GLOBS: renderSourceGlobs(args.sourceGlobs ?? []),\n };\n\n for (const { template, dest } of SHELL_FILES) {\n writeIfChanged(\n args.projectDir,\n path.join(harnessDir, dest),\n readTemplate(template, vars),\n files,\n dest,\n args.force,\n );\n }\n\n writeIfChanged(\n args.projectDir,\n path.join(harnessDir, VERSION_MARKER),\n serializeMarker(marker),\n files,\n VERSION_MARKER,\n args.force,\n );\n\n return {\n ...files,\n harnessDir,\n previousVersion,\n previousMarker,\n stale,\n staleReasons,\n };\n}\n\n/**\n * Turn validated `sourceGlobs` into the `@source` lines the generated\n * stylesheet carries, each relative to the shell's `styles/` directory.\n *\n * Tailwind never scans what it is not pointed at, and a glob that matches\n * nothing fails silently — so an integration living outside the default\n * layout renders completely unstyled with no error anywhere. That is what\n * `sourceGlobs` is for, and until now it was parsed and thrown away.\n */\nfunction renderSourceGlobs(globs: readonly string[]): string {\n if (globs.length === 0) return '';\n const lines = globs.map((glob) => `@source '${SHELL_TO_PROJECT}${glob}';`);\n return `\\n/* From \"sourceGlobs\" in ekanos.json. */\\n${lines.join('\\n')}\\n`;\n}\n\n/** From `.ekanos/harness/styles/` back up to the project root. */\nconst SHELL_TO_PROJECT = '../../../';\n\n/**\n * Establish that `.ekanos/harness` is a tree WE generated before writing a\n * single byte into it, and return the version marker it carried.\n *\n * Path location alone is not ownership. A directory that exists but carries no\n * `.ekanos-version` was put there by something else — a partner, another tool,\n * a symlink — and clobbering it because it happens to sit at the path we like\n * is the same class of mistake as following a symlink. An empty directory is\n * fine (that is just `mkdir -p` having run), and `--force` is the explicit\n * override.\n *\n * Runs BEFORE `bootstrapHarnessConfig` in `dev`, so a shell that cannot be\n * written leaves the project completely untouched rather than half-scaffolded.\n */\nexport function assertShellDirIsOurs(\n harnessDir: string,\n force: boolean,\n): string | null {\n const kind = classifyPath(harnessDir);\n\n if (kind === 'symlink') {\n throw invalidStateError(\n `${harnessDir} is a symlink, so \"ekanos dev\" will not write through it.`,\n `Delete ${harnessDir} and re-run \"ekanos dev\" — the shell is generated, ` +\n 'so nothing is lost.',\n );\n }\n\n if (kind !== 'missing' && kind !== 'directory') {\n throw invalidStateError(\n `${harnessDir} exists and is not a directory.`,\n `Move or delete ${harnessDir}, then re-run \"ekanos dev\".`,\n );\n }\n\n if (kind === 'missing') return null;\n\n const state = readShellMarkerState(harnessDir);\n\n // A marker we wrote, however mangled, still identifies the tree as ours.\n if (state.kind === 'ok') return state.marker.harness;\n if (state.kind === 'corrupt' || force) return null;\n\n if (fs.readdirSync(harnessDir).length === 0) return null;\n\n throw invalidStateError(\n `${harnessDir} already contains files but no ${VERSION_MARKER} marker, ` +\n 'so it was not generated by \"ekanos dev\".',\n `Delete ${harnessDir} if you do not need it, or pass --force to ` +\n 'overwrite it. Everything \"ekanos dev\" generates is reproducible; ' +\n 'anything else in there is not.',\n );\n}\n\n/**\n * The module specifier `harness.config.ts` uses to import the partner's\n * integration: the `entry` from ekanos.json, made relative and extension-free.\n * \"src/integration.ts\" → \"src/integration\".\n */\nexport function entryImportSpecifier(entry: string): string {\n const normalized = entry.split(path.sep).join('/').replace(/^\\.\\//, '');\n return normalized.replace(/\\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/, '');\n}\n\n/**\n * The same specifier as a JavaScript string LITERAL, ready to drop into a\n * generated `import` statement.\n *\n * `entry` is attacker-influenced data from `ekanos.json`, and a POSIX filename\n * may legally contain a quote or a newline. Interpolating it raw would let a\n * crafted-but-valid path close the string and append statements to the module\n * we generate. `JSON.stringify` produces a correctly escaped literal, which is\n * the actual fix; the explicit rejection below is a second line that also\n * gives the partner a comprehensible error instead of a bizarre filename\n * silently appearing, escaped, in their config.\n *\n * This does not cross a trust boundary on its own — a partner's own code runs\n * unsandboxed anyway — but \"the templates cannot be injected into\" is a claim\n * we make, and it should be true.\n */\nexport function entryImportLiteral(entry: string): string {\n const specifier = entryImportSpecifier(entry);\n\n // eslint-disable-next-line no-control-regex\n if (/[\"'`\\\\\\n\\r\\u0000-\\u001f]/.test(specifier)) {\n throw preconditionError(\n `The \"entry\" in ekanos.json contains characters that cannot appear in ` +\n `an import specifier: ${JSON.stringify(specifier)}.`,\n 'Rename the file so its path has no quotes, backslashes or control ' +\n 'characters, then update \"entry\" in ekanos.json to match.',\n );\n }\n\n return JSON.stringify(`./${specifier}`);\n}\n\nexport interface BootstrapConfigResult {\n /** True only when this run created the file. */\n bootstrapped: boolean;\n configPath: string;\n}\n\n/**\n * Write a starter `harness.config.ts` at the project root — ONCE.\n *\n * An existing file is left strictly alone, byte for byte, and no flag changes\n * that: it is the one harness file the partner owns, it is git-tracked, and\n * regenerating it would throw away their fixtures. `--force` regenerates the\n * shell, never this.\n */\nexport function bootstrapHarnessConfig(\n projectDir: string,\n integrations: readonly { slug: string; entry: string }[],\n): BootstrapConfigResult {\n const configPath = path.join(projectDir, HARNESS_CONFIG_FILENAME);\n const kind = classifyPath(configPath);\n\n // A symlink here — including a dangling one, which `existsSync` reports as\n // absent — would have us write through to its target. Since this file is the\n // partner's to own, the only safe answer is to touch nothing and say why.\n if (kind === 'symlink') {\n throw invalidStateError(\n `${configPath} is a symlink, so \"ekanos dev\" will not write through it.`,\n `Replace ${configPath} with a real file (or delete it to have one ` +\n 'generated), then re-run \"ekanos dev\".',\n );\n }\n\n if (kind !== 'missing') {\n return { bootstrapped: false, configPath };\n }\n\n writeFileNoFollow(projectDir, configPath, renderHarnessConfig(integrations));\n\n return { bootstrapped: true, configPath };\n}\n\n/**\n * Render the starter registry for EVERY integration the project declares.\n *\n * The harness registry is an array and `ekanos.json` can now hold a list, so a\n * project's second integration reaches the harness the same way its first\n * does. Each entry imports the definition under a distinct local identifier\n * derived from its slug, because two `integration` imports in one module do\n * not compile.\n */\nfunction renderHarnessConfig(\n integrations: readonly { slug: string; entry: string }[],\n): string {\n const imports: string[] = [];\n const entries: string[] = [];\n\n for (const integration of integrations) {\n const ident = identifierForSlug(integration.slug);\n imports.push(\n `import { integration as ${ident} } from ${entryImportLiteral(\n integration.entry,\n )};`,\n );\n entries.push(\n readTemplate('harness.config.entry.ts.tmpl', {\n IDENT: ident,\n SLUG: integration.slug,\n }),\n );\n }\n\n return readTemplate('harness.config.ts.tmpl', {\n INTEGRATION_IMPORTS: imports.join('\\n'),\n INTEGRATION_ENTRIES: entries.join(''),\n });\n}\n\n/**\n * \"acme-crm\" → \"acmeCrm\". A slug is kebab-case by schema, so this only has to\n * handle hyphens, and a leading digit is impossible.\n */\nexport function identifierForSlug(slug: string): string {\n const camel = slug.replace(/-([a-z0-9])/g, (_, char: string) =>\n char.toUpperCase(),\n );\n return /^[0-9]/.test(camel) ? `i${camel}` : camel;\n}\n\n/**\n * Add `.ekanos/` to the project `.gitignore`, exactly once.\n *\n * Matching is line-wise over the spellings git treats as the same rule\n * (`.ekanos`, `.ekanos/`, `/.ekanos/`), so re-running never appends a\n * duplicate — the thing that makes a scaffold verb safe to run in a loop.\n * A negation (`!.ekanos/`) is deliberately NOT treated as a match: the\n * partner meant to un-ignore it, and we do not fight that silently.\n */\nexport function ensureGitignoreEntry(projectDir: string): boolean {\n const gitignorePath = path.join(projectDir, '.gitignore');\n const block = `# Ekanos dev harness — generated by \"ekanos dev\", never edited by hand\\n${GITIGNORE_ENTRY}\\n`;\n\n const kind = classifyPath(gitignorePath);\n\n if (kind === 'symlink') {\n throw invalidStateError(\n `${gitignorePath} is a symlink, so \"ekanos dev\" will not append to it.`,\n `Add \"${GITIGNORE_ENTRY}\" to your real .gitignore yourself, or replace ` +\n `${gitignorePath} with a regular file, then re-run \"ekanos dev\".`,\n );\n }\n\n if (kind === 'missing') {\n writeFileNoFollow(projectDir, gitignorePath, block);\n return true;\n }\n\n const existing = readFileNoFollow(projectDir, gitignorePath) ?? '';\n if (gitignoreCovers(existing)) return false;\n\n const separator =\n existing.length === 0 || existing.endsWith('\\n') ? '' : '\\n';\n appendFileNoFollow(projectDir, gitignorePath, `${separator}\\n${block}`);\n return true;\n}\n\nfunction gitignoreCovers(source: string): boolean {\n const equivalents = new Set(['.ekanos', '.ekanos/', '/.ekanos', '/.ekanos/']);\n return source\n .split('\\n')\n .map((line) => line.trim())\n .some((line) => equivalents.has(line));\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { runPublish } from './commands/publish.js';
|
|
|
7
7
|
import { runSources } from './commands/sources.js';
|
|
8
8
|
import { runStatus } from './commands/status.js';
|
|
9
9
|
import { runTest } from './commands/test.js';
|
|
10
|
+
import { runUpgrade } from './commands/upgrade.js';
|
|
10
11
|
import { runUse } from './commands/use.js';
|
|
11
12
|
import { runValidate } from './commands/validate.js';
|
|
12
13
|
import { runWhoami } from './commands/whoami.js';
|
|
@@ -70,6 +71,15 @@ const COMMAND_SPECS = {
|
|
|
70
71
|
dir: { type: 'string' },
|
|
71
72
|
yes: { type: 'boolean' },
|
|
72
73
|
},
|
|
74
|
+
upgrade: {
|
|
75
|
+
dir: { type: 'string' },
|
|
76
|
+
host: { type: 'string' },
|
|
77
|
+
check: { type: 'boolean' },
|
|
78
|
+
yes: { type: 'boolean' },
|
|
79
|
+
// `--no-verify` is the negation of this — parse-argv's `--no-<bool>`
|
|
80
|
+
// convention (same as `--no-json`/`--no-start`), not a flag of its own.
|
|
81
|
+
verify: { type: 'boolean' },
|
|
82
|
+
},
|
|
73
83
|
};
|
|
74
84
|
/** Commands that take a positional argument, and what it means. Every other command is positional-free. */
|
|
75
85
|
const POSITIONAL_COMMANDS = {
|
|
@@ -92,8 +102,19 @@ const USAGE = [
|
|
|
92
102
|
' sources List every source you hold a developer/admin seat on',
|
|
93
103
|
' use Set this project\'s publish target ("ekanos use <source-slug>")',
|
|
94
104
|
' publish Validate, pack and submit the integration to a Fusion host',
|
|
105
|
+
' upgrade Move this toolchain to a coherent target version, with',
|
|
106
|
+
' verify-and-rollback (--check --yes --no-verify --host <url>)',
|
|
95
107
|
'',
|
|
96
|
-
'
|
|
108
|
+
'Keeping the toolchain current:',
|
|
109
|
+
' validate, dev and publish all check for a newer @ekanos/cli in the',
|
|
110
|
+
' background (never blocking, silenced by EKANOS_NO_UPDATE_CHECK) and warn',
|
|
111
|
+
' on stderr when one exists. Run "ekanos upgrade --check" any time a',
|
|
112
|
+
' validate finding smells like version skew (an unrecognized-key error you',
|
|
113
|
+
' are confident is correct) — it is read-only and safe to run freely. A',
|
|
114
|
+
' bare "ekanos upgrade" MUTATES the project (installs the target versions,',
|
|
115
|
+
' verifies with validate + the test script, rolls back on any failure).',
|
|
116
|
+
'',
|
|
117
|
+
'Host resolution (logout, whoami, status, sources, use, publish, upgrade):',
|
|
97
118
|
' --host, else EKANOS_HOST, else the "host" field in ekanos.json, else the',
|
|
98
119
|
' sole stored login. "ekanos publish" saves host and source to ekanos.json.',
|
|
99
120
|
' "ekanos login" never reads ekanos.json for a host (--host, else',
|
|
@@ -186,7 +207,7 @@ export async function run(argv, options = {}) {
|
|
|
186
207
|
yes: parsed.flags.yes === true,
|
|
187
208
|
});
|
|
188
209
|
case 'validate':
|
|
189
|
-
return await runValidate(ctx, { dir });
|
|
210
|
+
return await runValidate(ctx, { dir, env });
|
|
190
211
|
case 'dev':
|
|
191
212
|
return await runDev(ctx, {
|
|
192
213
|
dir,
|
|
@@ -194,6 +215,7 @@ export async function run(argv, options = {}) {
|
|
|
194
215
|
host: parsed.flags.host,
|
|
195
216
|
force: parsed.flags.force === true,
|
|
196
217
|
start: parsed.flags.start,
|
|
218
|
+
env,
|
|
197
219
|
});
|
|
198
220
|
case 'test':
|
|
199
221
|
return await runTest(ctx, { dir, passthrough: parsed.passthrough });
|
|
@@ -246,6 +268,17 @@ export async function run(argv, options = {}) {
|
|
|
246
268
|
stdinIsTTY: options.stdinIsTTY,
|
|
247
269
|
confirm: options.confirm,
|
|
248
270
|
});
|
|
271
|
+
case 'upgrade':
|
|
272
|
+
return await runUpgrade(ctx, {
|
|
273
|
+
dir,
|
|
274
|
+
host: parsed.flags.host,
|
|
275
|
+
env,
|
|
276
|
+
check: parsed.flags.check === true,
|
|
277
|
+
yes: parsed.flags.yes === true,
|
|
278
|
+
noVerify: parsed.flags.verify === false,
|
|
279
|
+
stdinIsTTY: options.stdinIsTTY,
|
|
280
|
+
confirm: options.confirm,
|
|
281
|
+
});
|
|
249
282
|
default:
|
|
250
283
|
// Unreachable — COMMANDS gate above — but keeps the switch total.
|
|
251
284
|
throw usageError(`Unknown command "${command}".`, `Run one of: ${COMMANDS.join(', ')}.`);
|