* enhance(#3911): give hooks an exit seam that needs no build ADR-3889 Phase 7 foundation. The 19 shipped enforcement hooks hold 91 of the epic's 128 terminators and cannot reach `terminateNow` today. The obvious route — requiring `gsd-core/bin/lib/cli-exit.cjs`, as gsd-agent-isolation-guard.js already does for two other modules — is rejected. That precedent carries its own warning (#3582): those files are tsc output, gitignored and absent on a raw plugin-marketplace or git-clone install, so the hook must first call ensureRuntimeBuild() to self-heal. Making the module a hook needs IN ORDER TO TERMINATE depend on a build inverts the dependency, and its failure mode is precisely the fail-open this phase exists to remove: a guard that cannot terminate cannot deny. `lint-hooks-runtime-build-seam` already encodes that concern, and Design B would have had to add an ensureRuntimeBuild() call to all 19 hooks to satisfy it. So `hooks/lib/` becomes a third emit location for cli-exit and a fifth for the registry, preserving the invariant `src/cli-exit.cts`'s own header states: it imports nothing but node:fs and its sibling registry, and the generator dual-emits that sibling alongside each copy so a relative require resolves next to whichever copy loaded it. Shipping needed no change — build-hooks.js already declares HOOKS_SUBDIRS_TO_COPY = ['lib']. Proven, not asserted: the two files are copied into an otherwise-empty tmpdir and a child process requires them and terminates — PASS exits 0, HOOK_DENY exits 2 with the payload on both stdout and stderr. That test fails the moment the hooks copy gains a require reaching outside hooks/lib/. Also fixed inline: the registry's fifth target let any `--write` test overwrite the real committed hooks/lib/exit-code-registry.js, because the test helper derived only three of the other output paths. It now redirects all five, and a regression test asserts every committed artifact is byte-identical after a redirected write. Install-tree goldens pick up the two new shipped paths across 11 runtimes — insertions only, no removals. lint:ci was green while they were stale, so this was found by regenerating rather than by a gate. Verification runs on the remote runner. Refs #3911 * enhance(#3911): declare a crash policy, and migrate the write guard Adds `hooks/lib/hook-exit.js` — the hook-facing vocabulary over `terminateNow`, hand-written because the cli-exit copy beside it is generated: allow(payload) exit 0 deny(payload, stderr?) exit 2 crash(onCrash, payload) whichever the hook DECLARED `crash()` takes the policy as a required argument with no default, which is the whole mechanism: fail-open by accident stops being expressible. A hook must name ALLOW or DENY at the call site, and an unrecognized value terminates INTERNAL rather than guessing. Fail-open stays legal; fail-open by omission does not. `gsd-write-guard.js` is the first hook migrated, all 12 sites, and it exposed a gap in the seam. `terminateNow`'s doc comment justified its fd-2 write by citing this hook's `emitBlock` — but modeled it as sending the same bytes to both streams, when `emitBlock` actually sends full JSON to stdout and only the bare `reason` string to stderr, because Kimi's hook bus feeds stderr verbatim back to the model. Migrating as written would have turned a readable sentence into a JSON blob for Kimi-backed agents. #3911 requires both "all 19 hooks terminate through terminateNow" and "no hook's effective default changes". Those are jointly satisfiable only by teaching the seam to carry a distinct stderr payload, so `terminateNow` gains an optional third argument: omitted, behavior is byte-for-byte what it was; a string is written raw, which is exactly the Kimi case. The doc comment's inaccurate claim about emitBlock is corrected in place. Proven rather than asserted: the pre-migration file is reconstructed from HEAD and driven with the same catastrophic-shrink payload as the migrated one — exit code, stdout and stderr all byte-identical. Verification runs on the remote runner. Refs #3911 * enhance(#3911): all 19 hooks terminate through the seam Migrates the remaining 18 enforcement hooks onto allow/deny/crash. An AST walk now reports zero `process.exit(` call sites across every `hooks/*.js` — down from the 91 the census measured. Each hook with an outer catch declares its policy once, at module top, with the reason that policy is right for that specific guard: a read guard that cannot scan must not block the read; a statusline that renders every prompt must degrade rather than crash; an injection scanner must not retroactively block a result already returned. Those sentences are the deliverable — they are what turns fail-open-by-accident into fail-open-on-purpose. No hook's effective default changed. Wiring exposed two defects, both fixed here rather than noted. A SECOND stdout/stderr-splitting site turned up in `gsd-workflow-guard.js`'s `emitForceAddBlock`, matching the pattern already known from the write guard — full JSON to stdout, bare reason to stderr for the Kimi bus. It uses the `stderrPayload` argument added in the previous commit, which is now carrying its second real caller rather than one special case. More seriously, `terminateNow` emitted both streams inside ONE try, so a payload that failed to serialize aborted before the stderr write ever ran. The two windsurf guards write nothing to stdout on a block and only a reason string to stderr, so `deny(undefined, reason)` exited 2 with EMPTY stderr — a deny that silently loses its reason, which is the exact "fails with success" class this epic exists to close. The streams are now emitted independently, each with its own guard, and `undefined` means "nothing to write for this stream" rather than an error. Regression tests inject a throwing write on one fd and assert the other still receives its payload; they fail against the single-try version. Byte-identity was proven per hook, not assumed: each pre-change file is reconstructed from HEAD and driven side by side with the migrated one across its normal path, its deny path, malformed stdin and empty stdin — exit code, stdout and stderr compared. Verification runs on the remote runner. Refs #3911 * enhance(#3911): harden the three shell hooks, and pin every hook's policy `gsd-phase-boundary.sh`, `gsd-session-state.sh` and `gsd-validate-commit.sh` gain `set -euo pipefail`. The expected hazard did not materialize, and that is worth recording: every intentionally-non-zero command in all three is already the condition of an `if`/`elif`, which `set -e` never fires on, and none of them reads a possibly-unset variable or pipes through a grep that may legitimately match nothing. No `|| true` guards were needed. Each hook was still checked command-by-command before the flags went in rather than after. Twenty-one before/after cases across the three hooks — disabled and enabled, planning and non-planning, missing STATE.md, malformed JSON, the Kimi payload shape, quoted and unquoted `-m`, valid and over-long Conventional Commits — all match on exit code, stdout and stderr. The hardening is shown to actually fire, not merely added: with a stubbed `node` that fails at the JSON-emit step, phase-boundary and session-state go from silently exiting 0 with empty stdout to failing visibly with the error surfaced. No such case could be constructed for `gsd-validate-commit.sh`, whose every statement already sits inside an if-condition — recorded as unproven rather than claimed. `tests/hooks-crash-policy.test.cjs` adds the per-hook coverage the issue asks for, table-driven over all 19 hooks rather than 76 hand-written cases: normal allow, deny where a deny path exists, crash-honors-the-declared-policy, and an unclosed-stdin case — the one `process.exitCode` structurally cannot serve. The deny assertions encode each hook's ACTUAL stream split rather than a uniform shape, since four of the six deliberately differ. A drift guard enumerates `hooks/*.js` and fails if a terminating hook is ever added without a row. Writing those tests surfaced two hooks that emit a block decision in their JSON body and exit 0. Both were checked rather than assumed, and neither is a fails-with-success: `gsd-read-injection-scanner.js` is PostToolUse, where the tool has already run and exit 2 has no meaning, and `gsd-cursor-subagent-start.js` follows Cursor's JSON-body protocol. They are deliberately left alone — a mechanical sweep to `deny()` would have broken exactly these two. Verification runs on the remote runner. Refs #3911 * fix(#3838): the commit validator says when it could not validate #3911 claims to subsume #3838. Measurement said otherwise, so this closes it for real rather than by assertion. `set -euo pipefail`, added earlier on this branch, does NOT fix #3838: bash exempts a command used as an `if` condition from `set -e`, and all three of the hook's swallow-and-pass sites are exactly that shape. Verified against the hardened hook with a node shim that fails only the classifier call — a non-conforming commit still exited 0 with empty stdout AND empty stderr, indistinguishable from "your commit conforms". That is the defect verbatim. All three sites named in #3838 now capture the real exit status instead of consuming it as a condition, and each distinguishes its genuine negative from "could not run": - the classifier: 0 = is a git commit, 1 = genuinely not one, anything else = could not classify. Its `node -e` now wraps the require and the call in try/catch and exits 3 on a throw, so a broken require chain can never be mistaken for `isGitSubcommand` legitimately returning false — which is the arm that matters, since `token-scanner.cjs` is a gitignored build artifact and a fresh checkout lands there. - the opt-in config read and the JSON command extraction get the same treatment. On "could not run" the hook emits a diagnostic to stderr naming which check failed and why, then exits 0. The issue confirms this is safe — it is a PreToolUse hook, so stderr does not disturb the JSON protocol — and ranks it the smallest sufficient fix. The gate still fails open, but it can no longer do so silently, which is the whole complaint: a validator that disables itself quietly costs more than one that is absent, because it is trusted. Both controls are unchanged and pinned by tests: a conforming commit still passes silently, a non-conforming one still exits 2 with its existing block payload. The defect test asserts stderr is non-empty and names the failure; it fails against the pre-fix hook. Verification runs on the remote runner. Refs #3911, #3838 * docs(#3911): document the hook crash-policy contract Reference and Explanation via a new docs/features fragment (FEATURES.md is generated from it), INVENTORY rows for the three new hooks/lib files, and an ARCHITECTURE note on the hooks section. How-To: docs/how-to/declare-a-hook-crash-policy.md, indexed from docs/README.md — a hook author now has to choose and declare a crash policy, which is more than one step and crosses into which harness protocol their hook speaks. It covers allow/deny/crash, writing an ON_CRASH reason that is actually useful, when a deny needs a distinct stderr payload, the two hooks whose harness reads a JSON-body decision and must NOT use deny(), and what to do when a check cannot run at all — with #3838 as the worked example. Refs #3911 * test(#3911): prove the seam actually ships, and stop hand-rolling temp cleanup Two review findings. The acceptance criterion 'hooks/dist/** stays in parity via the build seam (lint:hooks-runtime-build-seam)' was misstated and unmet: that lint checks something else — that a hook requiring a compiled gsd-core/bin/lib module also calls ensureRuntimeBuild(). Nothing exercised that the three new hooks/lib files reach hooks/dist/lib at all. That gap is not theoretical: #770 is a recorded ship-blocking bug where a new hook never shipped because a copy list missed it. The suite now builds dist through the repo's own ensureBuiltHooks(), byte-compares each shipped copy against its source, and spawns a child that requires the SHIPPED dist copy and denies — which is what catches a copy that exists but cannot resolve its sibling registry. gsd-validate-commit.sh hand-duplicated mktemp/run/rm three times; one idempotent trap on EXIT replaces them, guarded so cleanup cannot alter the exit status. Behavior-neutral across five cases, with temp-file counts taken before and after each run. Refs #3911 * fix(#3911): stage transitive hook lib requires, not just one level The remote run returned 7 failures across 3 real causes. The important one is a PRODUCTION bug this phase exposed rather than caused. `writeCursorHooksJson` scanned each hook script for `./lib/X` requires exactly one level deep and never re-scanned the lib files it staged for their own sibling requires. Nothing had a transitive lib dependency before, so the gap was invisible. Adding hook-exit.js -> cli-exit.js -> exit-code-registry.js made real Cursor installs ship a bundle that dies at require time with MODULE_NOT_FOUND. It now walks to a fixed point, and a real installed Cursor hook runs to completion. The staging harness in shared-hooks-dir-resolution hand-copied its fixture, so the injection scanner crashed at require time and its exit-1 was being read as a policy decision. Migrated to copyScriptWithDeps, which walks the require graph — the repo's recorded rule for this class, since adding another copyFileSync keeps it alive for the next person. The missing-lib-source test in cursor-hook-workspace-roots hardcoded which lib file it expected to be named in the abort message; the same throw now fires for a different file first. Its assertion is unchanged in substance — staging still must abort rather than ship a broken hook — only the name is no longer pinned. The last one was my own test asserting an uppercase reason code. Measured against origin/next: the pre-change hook emits the same lowercase 'config_unreadable', so the test was wrong, not the migration. Corrected to the real value rather than making the code match the test. Verification runs on the remote runner. Refs #3911 * chore(#3911): regenerate the cursor install-tree golden The staging fix means a Cursor install now correctly carries the two transitive lib files it was silently missing. Additive only — no path was removed. The golden diff is the evidence the packaging defect was real. Refs #3911 * chore(#3911): backfill the changeset PR number Refs #3911 * fix(#3911): a git probe that timed out is not a negative A macOS CI lane failed three deny cases at 2084ms, 2112ms and 2177ms — just past the 2000ms budget these hooks give their git probes. The three that passed took 72ms, 595ms and 651ms. Under shard contention `git rev-parse` overruns, the hook reads the non-zero result as "not a git repo", and allows with exit 0 and empty stdout AND empty stderr. Under load, the guards silently stop guarding. That is ADR-3889's thesis exactly, sitting inside the security hooks this phase is about. The repo had already recognized the class in one place — gsd-cursor-subagent-start.js fail-closed-denies on `git_timed_out` (#3045) — but nowhere else. `hooks/lib/git-probe.js` classifies a probe's outcome, distinguishing a real non-zero exit from ETIMEDOUT, a signal kill, and a spawn failure, rather than folding all four into `status !== 0`. Three guards route their eight git probes through it. The resolution is the same shape #3838 took, and the same one that issue endorsed as smallest-sufficient: fail open, but loudly. **No exit code changes on any path** — a developer on a loaded machine is still not blocked, which keeps #3911's declaration-pass contract intact for exit codes. What changes is that the hook now says on stderr which probe could not answer, instead of presenting silence as a clean verdict. Scope was checked across every hooks/*.js, not just the three that failed: gsd-agent-isolation-guard spawns no git; gsd-statusline's two probes gate only a cosmetic display segment, not an allow/deny decision, and are left alone. The C2 deny assertion was a real-race test — it demanded exit 2 while a slow git legitimately yields 0. It now requires the hook to either deny, or allow with a diagnostic naming the probe that could not run; a silent allow still fails, so the assertion is not vacuous. A deterministic regression stubs git on PATH to sleep past the budget rather than waiting for load to reproduce it. Verification runs on the remote runner. Refs #3911 * test(#3911): a PATH shim cannot intercept the hooks' git spawn on Windows The deterministic timeout regression stubbed git on PATH and asserted the guard reports rather than silently allows. It passes on Linux and macOS and failed on Windows in 83ms and 176ms — the stub was never invoked at all. Mechanism: the hooks call spawnSync('git', args) with no shell:true, so on Windows CreateProcess resolves git.exe only and never a PATH .cmd shim. The git.cmd branch could not have worked and is removed rather than left implying a Windows path that does. Adding shell:true to the hooks to serve a test would change product behavior and widen an injection surface, so the case is skipped on win32 only, with the mechanism written into the skip reason so a future reader does not 'fix' it that way. Linux and macOS keep the coverage, and macOS is where the underlying fail-open was actually caught. Refs #3911 --------- Co-authored-by: sim <sim@local>
762 lines
30 KiB
JavaScript
762 lines
30 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* gen-exit-code-registry.cjs — generates FIVE byte-identical/derived
|
|
* artifacts from the declaration at gsd-core/bin/shared/exit-codes.json:
|
|
* - gsd-core/bin/lib/exit-code-registry.cjs (tsc-adjacent build tree)
|
|
* - scripts/lib/exit-code-registry.cjs (committed, for scripts/
|
|
* consumers that must work on an unbuilt clone — same reason
|
|
* scripts/lib/cli-exit.cjs exists alongside gsd-core/bin/lib/cli-exit.cjs;
|
|
* see scripts/gen-scripts-cli-exit.cjs).
|
|
* - hooks/lib/exit-code-registry.js (committed, for hooks/
|
|
* consumers that must work on a raw, unbuilt clone — same reason as the
|
|
* scripts/ copy above; see scripts/gen-hooks-cli-exit.cjs, which emits
|
|
* hooks/lib/cli-exit.js's sibling `require('./exit-code-registry.js')`.
|
|
* `.js`, not `.cjs`, to match the hooks/lib/*.js convention — ADR-3889
|
|
* Phase 7, #3911).
|
|
* - src/exit-code-registry.d.cts (the ambient type declaration
|
|
* tsc uses to typecheck src/cli-exit.cts's `require('./exit-code-registry.cjs')`
|
|
* against the shape the .cjs artifacts above actually export — generated
|
|
* from the SAME ENTRY_FIELD_TYPES table serializeRegistry() uses, so the
|
|
* two can never independently drift).
|
|
* - gsd-core/bin/shared/exit-codes.sh (POSIX sh, safe under
|
|
* `set -u`: one `export EXIT_<NAME>=<code>` per entry, sourced by the
|
|
* bash scanners under scripts/ so a shell caller never re-invents a
|
|
* literal exit-code integer — ADR-3889 Phase 4, #3908).
|
|
*
|
|
* ADR-3889 ("One exit-code registry — 0 and 1 are free, everything else is
|
|
* allocated") Phase 1 (#3905) built the single-output allocator; Phase 2
|
|
* (#3906) added the second .cjs emission so scripts/ has its own committed
|
|
* copy instead of reaching into gitignored build output; a follow-up closed
|
|
* the review finding that the .d.cts was hand-maintained with no gate by
|
|
* generating it here too; Phase 4 (#3908) added the shell fragment so the
|
|
* three bash scanners can source symbolic names instead of hardcoding
|
|
* integers; Phase 7 (#3911) added the hooks/lib/ copy so a shipped hook can
|
|
* terminate through `terminateNow` without depending on any build artifact.
|
|
*
|
|
* The three .cjs/.js artifacts (primary, scripts, hooks) are byte-identical:
|
|
* serializeRegistry() only encodes the DECLARATION path (for the banner
|
|
* comment), never the output path, so one generated string is written to all
|
|
* three locations unchanged. The .d.cts and .sh artifacts are separate,
|
|
* smaller derivations but are generated and --check-gated exactly the same
|
|
* way.
|
|
*
|
|
* Nothing in this script emits a registered exit code itself; wiring
|
|
* consumers onto the registry is separate work.
|
|
*
|
|
* Usage:
|
|
* node scripts/gen-exit-code-registry.cjs # same as --write
|
|
* node scripts/gen-exit-code-registry.cjs --write # write all five artifacts
|
|
* node scripts/gen-exit-code-registry.cjs --check # exit 1 if ANY committed artifact is stale
|
|
* node scripts/gen-exit-code-registry.cjs --declaration <path> --out <path> --scripts-out <path> --hooks-out <path> --dts-out <path> --sh-out <path> # override for tests
|
|
* node scripts/gen-exit-code-registry.cjs --json # emit ONE JSON report on stdout instead of human prose
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
|
|
const REPO_ROOT = path.resolve(__dirname, '..');
|
|
const DEFAULT_DECLARATION_PATH = path.join(REPO_ROOT, 'gsd-core', 'bin', 'shared', 'exit-codes.json');
|
|
const DEFAULT_OUTPUT_PATH = path.join(REPO_ROOT, 'gsd-core', 'bin', 'lib', 'exit-code-registry.cjs');
|
|
const DEFAULT_SCRIPTS_OUTPUT_PATH = path.join(REPO_ROOT, 'scripts', 'lib', 'exit-code-registry.cjs');
|
|
const DEFAULT_HOOKS_OUTPUT_PATH = path.join(REPO_ROOT, 'hooks', 'lib', 'exit-code-registry.js');
|
|
const DEFAULT_DTS_OUTPUT_PATH = path.join(REPO_ROOT, 'src', 'exit-code-registry.d.cts');
|
|
const DEFAULT_SH_OUTPUT_PATH = path.join(REPO_ROOT, 'gsd-core', 'bin', 'shared', 'exit-codes.sh');
|
|
|
|
/**
|
|
* Single source of the entry field list (name -> TS type), in emission order.
|
|
* serializeRegistry()'s per-entry object literal and serializeDts()'s
|
|
* ExitCodeEntry interface are BOTH derived from this one table, so the two
|
|
* artifacts cannot independently drift out of shape with each other — closing
|
|
* the review finding that the ambient .d.cts was a hand-maintained guess at
|
|
* what serializeRegistry() emits.
|
|
*/
|
|
const ENTRY_FIELD_TYPES = Object.freeze({
|
|
code: 'number',
|
|
name: 'string',
|
|
meaning: 'string',
|
|
owner: 'string',
|
|
authorizedBy: 'string',
|
|
});
|
|
|
|
/** Frozen reason codes so tests assert on structure, not prose. */
|
|
const REASON = Object.freeze({
|
|
OK: 'ok_generated_sync',
|
|
DRIFTED: 'fail_generated_drifted',
|
|
USAGE: 'fail_usage',
|
|
MISSING_DECLARATION: 'fail_missing_declaration',
|
|
MALFORMED_DECLARATION: 'fail_malformed_declaration',
|
|
NOT_AN_ARRAY: 'fail_not_an_array',
|
|
EMPTY_DECLARATION: 'fail_empty_declaration',
|
|
INVALID_ENTRY: 'fail_invalid_entry',
|
|
DUPLICATE_CODE: 'fail_duplicate_code',
|
|
DUPLICATE_NAME: 'fail_duplicate_name',
|
|
RESERVED_CODE: 'fail_reserved_code',
|
|
FORBIDDEN_OWNER: 'fail_forbidden_owner',
|
|
MISSING_ARTIFACT: 'fail_missing_artifact',
|
|
});
|
|
|
|
const USAGE_MESSAGE = [
|
|
'Usage: node scripts/gen-exit-code-registry.cjs [--write|--check] [--declaration <path>] [--out <path>] [--scripts-out <path>] [--hooks-out <path>] [--dts-out <path>] [--sh-out <path>] [--json]',
|
|
' (no flag) same as --write',
|
|
' --write write all five generated registry artifacts',
|
|
' --check exit 1 if ANY committed artifact is stale',
|
|
' --declaration override the declaration path (default: gsd-core/bin/shared/exit-codes.json)',
|
|
' --out override the primary output artifact path (default: gsd-core/bin/lib/exit-code-registry.cjs)',
|
|
' --scripts-out override the secondary output artifact path (default: scripts/lib/exit-code-registry.cjs)',
|
|
' --hooks-out override the hooks output artifact path (default: hooks/lib/exit-code-registry.js)',
|
|
' --dts-out override the ambient type declaration path (default: src/exit-code-registry.d.cts)',
|
|
' --sh-out override the shell-sourceable fragment path (default: gsd-core/bin/shared/exit-codes.sh)',
|
|
' --json emit ONE JSON report ({ok, reason, context, detail?}) on stdout instead of human-readable prose',
|
|
].join('\n');
|
|
|
|
/** SCREAMING_SNAKE_CASE: starts with a letter, only uppercase letters/digits/underscores. */
|
|
const NAME_RE = /^[A-Z][A-Z0-9_]*$/;
|
|
|
|
/** Fields every entry must carry as a non-empty, non-whitespace-only string. */
|
|
const REQUIRED_STRING_FIELDS = ['meaning', 'owner', 'authorizedBy'];
|
|
|
|
/**
|
|
* Bands, per ADR-3889 §1:
|
|
* 0, 1 free (not allocatable here)
|
|
* 2 hook-adapter only
|
|
* 3-13 Node-reserved
|
|
* 14-63, 79, 126+ outside every band
|
|
* 64-78 generic
|
|
* 80-125 domain
|
|
*/
|
|
function isAllocatableCode(code) {
|
|
if (code === 2) return true;
|
|
if (code >= 64 && code <= 78) return true;
|
|
if (code >= 80 && code <= 125) return true;
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Label the non-allocatable band a rejected code falls into, per the same
|
|
* range boundaries documented on isAllocatableCode/ADR-3889 §1. Only called
|
|
* for codes that already failed isAllocatableCode, so 2 and 64-125 never
|
|
* reach here.
|
|
* @returns {string}
|
|
*/
|
|
function bandFor(code) {
|
|
if (code === 0 || code === 1) return 'free';
|
|
if (code >= 3 && code <= 13) return 'node-reserved';
|
|
if (code >= 126) return 'shell-signal';
|
|
return 'outside-every-band'; // 14-63, 79
|
|
}
|
|
|
|
/**
|
|
* Validate a single declaration entry's shape and band membership.
|
|
* @returns {{ok:true}|{ok:false,reason:string,message:string,context:object}}
|
|
*/
|
|
function validateEntry(entry, index) {
|
|
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.INVALID_ENTRY,
|
|
message: `entry[${index}] is not an object: ${JSON.stringify(entry)}`,
|
|
context: { field: 'entry', index },
|
|
};
|
|
}
|
|
|
|
const { code, name } = entry;
|
|
if (!Number.isInteger(code) || code < 0) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.INVALID_ENTRY,
|
|
message: `entry[${index}].code must be a non-negative integer (no coercion), received ${JSON.stringify(code)}`,
|
|
context: { field: 'code', index, code },
|
|
};
|
|
}
|
|
|
|
if (typeof name !== 'string' || name.trim() === '' || !NAME_RE.test(name)) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.INVALID_ENTRY,
|
|
message: `entry[${index}].name must be a non-empty SCREAMING_SNAKE_CASE string, received ${JSON.stringify(name)}`,
|
|
context: { field: 'name', index, code, name },
|
|
};
|
|
}
|
|
|
|
for (const field of REQUIRED_STRING_FIELDS) {
|
|
const value = entry[field];
|
|
if (typeof value !== 'string' || value.trim() === '') {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.INVALID_ENTRY,
|
|
message: `entry[${index}] (${name}).${field} must be a non-empty string, received ${JSON.stringify(value)}`,
|
|
context: { field, index, code, name },
|
|
};
|
|
}
|
|
}
|
|
|
|
if (!isAllocatableCode(code)) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.RESERVED_CODE,
|
|
message: `entry[${index}] (${name}) declares code ${code}, which is outside every allocatable band ` +
|
|
`(2 hook-adapter only; 64-78 generic; 80-125 domain) — see ADR-3889 §1`,
|
|
context: { code, band: bandFor(code), index, name },
|
|
};
|
|
}
|
|
|
|
if (code === 2 && entry.owner !== 'hook-adapter') {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.FORBIDDEN_OWNER,
|
|
message: `entry[${index}] (${name}) declares code 2 with owner "${entry.owner}" — code 2 is reserved to ` +
|
|
`the Claude Code hook protocol and may only be owned by "hook-adapter"`,
|
|
context: { code, owner: entry.owner, requiredOwner: 'hook-adapter', index, name },
|
|
};
|
|
}
|
|
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* Validate the whole declaration: every entry individually, then the
|
|
* cross-entry invariants (one number one meaning; one owner emits a given
|
|
* code — but the SAME owner may legitimately own several distinct codes).
|
|
* @returns {{ok:true}|{ok:false,reason:string,message:string,context:object}}
|
|
*/
|
|
function validateEntries(entries) {
|
|
for (let i = 0; i < entries.length; i++) {
|
|
const result = validateEntry(entries[i], i);
|
|
if (!result.ok) return result;
|
|
}
|
|
|
|
const byCode = new Map();
|
|
const byName = new Map();
|
|
for (const entry of entries) {
|
|
if (byCode.has(entry.code)) {
|
|
const other = byCode.get(entry.code);
|
|
return {
|
|
ok: false,
|
|
reason: REASON.DUPLICATE_CODE,
|
|
message: `code ${entry.code} is declared twice: "${other.name}" and "${entry.name}"`,
|
|
context: { code: entry.code, names: [other.name, entry.name] },
|
|
};
|
|
}
|
|
byCode.set(entry.code, entry);
|
|
|
|
if (byName.has(entry.name)) {
|
|
const other = byName.get(entry.name);
|
|
return {
|
|
ok: false,
|
|
reason: REASON.DUPLICATE_NAME,
|
|
message: `name "${entry.name}" is declared twice: code ${other.code} and code ${entry.code}`,
|
|
context: { name: entry.name, codes: [other.code, entry.code] },
|
|
};
|
|
}
|
|
byName.set(entry.name, entry);
|
|
}
|
|
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* Load and parse the declaration file.
|
|
* @returns {{ok:true,entries:Array}|{ok:false,reason:string,message:string}}
|
|
*/
|
|
function loadDeclaration(declarationPath) {
|
|
if (!fs.existsSync(declarationPath)) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.MISSING_DECLARATION,
|
|
message: `declaration not found at ${declarationPath}`,
|
|
context: { path: declarationPath },
|
|
};
|
|
}
|
|
|
|
let raw;
|
|
try {
|
|
raw = fs.readFileSync(declarationPath, 'utf8');
|
|
} catch (err) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.MISSING_DECLARATION,
|
|
message: `could not read ${declarationPath}: ${err.message}`,
|
|
context: { path: declarationPath },
|
|
};
|
|
}
|
|
|
|
let parsed;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch (err) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.MALFORMED_DECLARATION,
|
|
message: `${declarationPath} is not valid JSON: ${err.message}`,
|
|
context: { path: declarationPath },
|
|
};
|
|
}
|
|
|
|
if (!Array.isArray(parsed)) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.NOT_AN_ARRAY,
|
|
message: `${declarationPath} must be a JSON array, received ${parsed === null ? 'null' : typeof parsed}`,
|
|
context: { path: declarationPath },
|
|
};
|
|
}
|
|
|
|
if (parsed.length === 0) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.EMPTY_DECLARATION,
|
|
message: `${declarationPath} is an empty array — declare at least one exit code`,
|
|
context: { path: declarationPath },
|
|
};
|
|
}
|
|
|
|
return { ok: true, entries: parsed };
|
|
}
|
|
|
|
/**
|
|
* Hand-serialize the generated registry module (string concatenation, like
|
|
* gsd-core/bin/lib/capability-registry.cjs — no build step, no template
|
|
* engine, so the emitted bytes are exactly what `--check` re-derives).
|
|
*/
|
|
function serializeRegistry(entries, declarationPath) {
|
|
const relDeclaration = path.relative(REPO_ROOT, declarationPath).split(path.sep).join('/');
|
|
const banner = [
|
|
'\'use strict\';',
|
|
'',
|
|
'// GENERATED FILE — DO NOT EDIT BY HAND.',
|
|
`// Source of truth: ${relDeclaration}. Regenerate with:`,
|
|
'// node scripts/gen-exit-code-registry.cjs --write',
|
|
'// This exact content is emitted to THREE locations — gsd-core/bin/lib/exit-code-registry.cjs,',
|
|
'// scripts/lib/exit-code-registry.cjs, and hooks/lib/exit-code-registry.js (the latter two',
|
|
'// committed so scripts/ and hooks/ consumers work on an unbuilt clone) — all byte-compared by',
|
|
'// `npm run lint:generated-sync` (#3905 ADR-3889 Phase 1; #3906 Phase 2 added the second copy;',
|
|
'// #3911 ADR-3889 Phase 7 added the hooks/lib/ copy).',
|
|
'//',
|
|
'// exitCodeFor(name) / nameForExitCode(code) are pure and total over this',
|
|
'// closed table — each throws for anything not registered here.',
|
|
'',
|
|
].join('\n');
|
|
|
|
const entryFieldNames = Object.keys(ENTRY_FIELD_TYPES);
|
|
const entryLiterals = entries.map((e) => {
|
|
const fieldLines = entryFieldNames.map((field) => ` ${field}: ${JSON.stringify(e[field])},`).join('\n');
|
|
return ` Object.freeze({\n${fieldLines}\n })`;
|
|
}).join(',\n');
|
|
|
|
const body = [
|
|
'const EXIT_CODES = Object.freeze([',
|
|
entryLiterals,
|
|
']);',
|
|
'',
|
|
'const NAME_TO_CODE = new Map(EXIT_CODES.map((entry) => [entry.name, entry.code]));',
|
|
'const CODE_TO_NAME = new Map(EXIT_CODES.map((entry) => [entry.code, entry.name]));',
|
|
'',
|
|
'/**',
|
|
' * Resolve the registered exit code for a symbolic name. Pure, total: throws',
|
|
' * for anything not an exact, registered, exact-case key — including',
|
|
' * non-strings, the empty string, untrimmed strings, wrong case, and',
|
|
' * prototype-chain names like `__proto__`/`constructor`/`toString` (a Map',
|
|
' * lookup never touches the prototype chain, so these are indistinguishable',
|
|
' * from any other unregistered name).',
|
|
' *',
|
|
' * @param {string} name',
|
|
' * @returns {number}',
|
|
' */',
|
|
'function exitCodeFor(name) {',
|
|
' if (typeof name !== \'string\' || name.length === 0) {',
|
|
' throw new Error(`exitCodeFor: name must be a non-empty string, received ${JSON.stringify(name)}`);',
|
|
' }',
|
|
' if (!NAME_TO_CODE.has(name)) {',
|
|
' throw new Error(`exitCodeFor: unregistered exit code name: ${JSON.stringify(name)}`);',
|
|
' }',
|
|
' return NAME_TO_CODE.get(name);',
|
|
'}',
|
|
'',
|
|
'/**',
|
|
' * Reverse of exitCodeFor: resolve the symbolic name for a registered exit',
|
|
' * code. Pure, total: throws for anything not an exact, registered code.',
|
|
' *',
|
|
' * @param {number} code',
|
|
' * @returns {string}',
|
|
' */',
|
|
'function nameForExitCode(code) {',
|
|
' if (!CODE_TO_NAME.has(code)) {',
|
|
' throw new Error(`nameForExitCode: unregistered exit code: ${JSON.stringify(code)}`);',
|
|
' }',
|
|
' return CODE_TO_NAME.get(code);',
|
|
'}',
|
|
'',
|
|
'module.exports = { EXIT_CODES, exitCodeFor, nameForExitCode };',
|
|
'',
|
|
].join('\n');
|
|
|
|
return banner + '\n' + body;
|
|
}
|
|
|
|
/**
|
|
* Generate the ambient type declaration for the generated .cjs registry
|
|
* artifacts. Derived from the SAME ENTRY_FIELD_TYPES table serializeRegistry()
|
|
* iterates for its per-entry object literals, and from serializeRegistry()'s
|
|
* own fixed `module.exports = { EXIT_CODES, exitCodeFor, nameForExitCode }`
|
|
* shape — so this declaration cannot drift out of step with what the sibling
|
|
* .cjs artifacts actually export without both call sites being edited
|
|
* together. Structural only (no per-entry data): the type is the same
|
|
* regardless of how many rows the declaration has.
|
|
*/
|
|
function serializeDts(declarationPath) {
|
|
const relDeclaration = path.relative(REPO_ROOT, declarationPath).split(path.sep).join('/');
|
|
const fieldLines = Object.entries(ENTRY_FIELD_TYPES)
|
|
.map(([field, type]) => ` readonly ${field}: ${type};`)
|
|
.join('\n');
|
|
|
|
return [
|
|
'// GENERATED FILE — DO NOT EDIT BY HAND.',
|
|
`// Source of truth: ${relDeclaration} + the ENTRY_FIELD_TYPES table in`,
|
|
'// scripts/gen-exit-code-registry.cjs. Regenerate with:',
|
|
'// node scripts/gen-exit-code-registry.cjs --write',
|
|
'//',
|
|
'// Ambient type declaration for exit-code-registry.cjs — a GENERATED,',
|
|
'// committed artifact with no `.cts` source of its own (it is hand-serialized',
|
|
'// from gsd-core/bin/shared/exit-codes.json by scripts/gen-exit-code-registry.cjs,',
|
|
'// ADR-3889 §2, #3905/#3906), so tsc has nothing to compile for it. This file',
|
|
"// exists purely so `src/cli-exit.cts`'s `require('./exit-code-registry.cjs')`",
|
|
'// type-checks against the SAME shape the generated artifact actually exports',
|
|
'// at runtime — mirroring the src/vendor/*.d.cts pattern already used for',
|
|
'// other verbatim/generated JS this tree resolves types for without compiling.',
|
|
'//',
|
|
'// This declaration is generated from the same ENTRY_FIELD_TYPES table',
|
|
"// serializeRegistry()'s per-entry object literals iterate, and is",
|
|
'// byte-compared by `node scripts/gen-exit-code-registry.cjs --check`',
|
|
'// (the same check that already covers the two sibling .cjs artifacts) so a',
|
|
'// shape drift here fails the build instead of surfacing at a destructuring',
|
|
'// call site.',
|
|
'',
|
|
'export interface ExitCodeEntry {',
|
|
fieldLines,
|
|
'}',
|
|
'',
|
|
'declare const exitCodeRegistry: {',
|
|
' readonly EXIT_CODES: readonly ExitCodeEntry[];',
|
|
' // Property-typed function signatures (`name: (args) => ret`), NOT method',
|
|
' // shorthand (`name(args): ret`) — the latter is a TS "method" and trips',
|
|
' // @typescript-eslint/unbound-method at every destructuring call site',
|
|
' // (`const { exitCodeFor } = ...`), since a method may implicitly use',
|
|
' // `this`. These are pure functions that never do, so they are typed as',
|
|
' // plain function-valued properties instead.',
|
|
' exitCodeFor: (name: string) => number;',
|
|
' nameForExitCode: (code: number) => string;',
|
|
'};',
|
|
'',
|
|
'export = exitCodeRegistry;',
|
|
'',
|
|
].join('\n');
|
|
}
|
|
|
|
/**
|
|
* Generate the shell-sourceable fragment: one `export EXIT_<NAME>=<code>`
|
|
* line per declared entry, POSIX sh, safe under `set -u` (a sourced file that
|
|
* only ever ASSIGNS variables can never trip an unset-variable check,
|
|
* regardless of what the caller's shell had in scope beforehand).
|
|
*
|
|
* Consumed by the bash scanners under scripts/ via `. gsd-core/bin/shared/
|
|
* exit-codes.sh` (ADR-3889 Phase 4, #3908) so a shell caller resolves a
|
|
* symbolic name instead of hardcoding a literal integer that can silently
|
|
* drift from the registry.
|
|
*/
|
|
function serializeSh(entries, declarationPath) {
|
|
const relDeclaration = path.relative(REPO_ROOT, declarationPath).split(path.sep).join('/');
|
|
const banner = [
|
|
'#!/bin/sh',
|
|
'# GENERATED FILE — DO NOT EDIT BY HAND.',
|
|
`# Source of truth: ${relDeclaration}. Regenerate with:`,
|
|
'# node scripts/gen-exit-code-registry.cjs --write',
|
|
'#',
|
|
'# One `export EXIT_<NAME>=<code>` per gsd-core/bin/shared/exit-codes.json',
|
|
'# entry (ADR-3889 §2, #3905/#3906/#3908). POSIX sh, safe under `set -u`:',
|
|
'# sourcing this file only ever ASSIGNS variables, never reads one, so it',
|
|
'# cannot trip an unset-variable check regardless of the caller\'s existing',
|
|
'# environment.',
|
|
'#',
|
|
'# Usage (from a scanner under scripts/):',
|
|
'# . "$(dirname "$0")/../gsd-core/bin/shared/exit-codes.sh"',
|
|
'# exit "$EXIT_UNAVAILABLE"',
|
|
'',
|
|
].join('\n');
|
|
|
|
const lines = entries.map((e) => `export EXIT_${e.name}=${e.code}`);
|
|
|
|
return banner + lines.join('\n') + '\n';
|
|
}
|
|
|
|
/**
|
|
* Load, validate, and serialize the declaration in one step.
|
|
* @returns {{ok:true,content:string}|{ok:false,reason:string,message:string}}
|
|
*/
|
|
function buildRegistryContent(declarationPath) {
|
|
const loaded = loadDeclaration(declarationPath);
|
|
if (!loaded.ok) return loaded;
|
|
|
|
const validated = validateEntries(loaded.entries);
|
|
if (!validated.ok) return validated;
|
|
|
|
return { ok: true, content: serializeRegistry(loaded.entries, declarationPath), entries: loaded.entries };
|
|
}
|
|
|
|
function printFail(result) {
|
|
console.error(`FAIL gen-exit-code-registry: ${result.reason}`);
|
|
console.error(` ${result.message}`);
|
|
}
|
|
|
|
/**
|
|
* Emit a failure outcome: structured JSON on stdout (and NO stderr prose)
|
|
* when `json` is set, otherwise the legacy human-readable stderr report.
|
|
* `context` carries the specifics (offending code/name/field/path) that the
|
|
* `detail` prose currently embeds, so a `--json` consumer never needs to
|
|
* parse prose to recover them — it defaults to `null` for reasons (USAGE,
|
|
* DRIFTED, MISSING_ARTIFACT) that carry no structured specifics.
|
|
* @param {{reason:string, message?:string, context?:object}} result
|
|
* @param {boolean} json
|
|
*/
|
|
function emitFail(result, json) {
|
|
if (json) {
|
|
process.stdout.write(JSON.stringify({ ok: false, reason: result.reason, context: result.context ?? null, detail: result.message }) + '\n');
|
|
return;
|
|
}
|
|
printFail(result);
|
|
}
|
|
|
|
/**
|
|
* Emit a success outcome: structured JSON on stdout when `json` is set,
|
|
* otherwise the legacy human-readable stdout line.
|
|
* @param {string} reason
|
|
* @param {string} humanMessage
|
|
* @param {boolean} json
|
|
*/
|
|
function emitOk(reason, humanMessage, json) {
|
|
if (json) {
|
|
process.stdout.write(JSON.stringify({ ok: true, reason }) + '\n');
|
|
return;
|
|
}
|
|
console.log(humanMessage);
|
|
}
|
|
|
|
function doWrite(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, json) {
|
|
const result = buildRegistryContent(declarationPath);
|
|
if (!result.ok) {
|
|
emitFail(result, json);
|
|
return 1;
|
|
}
|
|
// The three .cjs/.js artifacts are byte-identical copies of the same
|
|
// generated content (serializeRegistry never encodes the output path), so
|
|
// the same string is written to all three locations unchanged.
|
|
for (const target of [outPath, scriptsOutPath, hooksOutPath]) {
|
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
fs.writeFileSync(target, result.content, 'utf8');
|
|
}
|
|
const dtsContent = serializeDts(declarationPath);
|
|
fs.mkdirSync(path.dirname(dtsPath), { recursive: true });
|
|
fs.writeFileSync(dtsPath, dtsContent, 'utf8');
|
|
const shContent = serializeSh(result.entries, declarationPath);
|
|
fs.mkdirSync(path.dirname(shPath), { recursive: true });
|
|
fs.writeFileSync(shPath, shContent, 'utf8');
|
|
emitOk(
|
|
REASON.OK,
|
|
`ok gen-exit-code-registry: wrote ${outPath}\nok gen-exit-code-registry: wrote ${scriptsOutPath}\n`
|
|
+ `ok gen-exit-code-registry: wrote ${hooksOutPath}\n`
|
|
+ `ok gen-exit-code-registry: wrote ${dtsPath}\nok gen-exit-code-registry: wrote ${shPath}`,
|
|
json,
|
|
);
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* Verify one committed artifact against the freshly generated content.
|
|
* @returns {{ok:true}|{ok:false,reason:string,message:string,context:object}}
|
|
*/
|
|
function checkOneArtifact(artifactLabel, artifactPath, content) {
|
|
if (!fs.existsSync(artifactPath)) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.MISSING_ARTIFACT,
|
|
message: `${artifactPath} (${artifactLabel}) does not exist. Run:\n node scripts/gen-exit-code-registry.cjs --write`,
|
|
context: { artifact: artifactLabel, path: artifactPath },
|
|
};
|
|
}
|
|
|
|
const committed = fs.readFileSync(artifactPath, 'utf8');
|
|
if (committed !== content) {
|
|
return {
|
|
ok: false,
|
|
reason: REASON.DRIFTED,
|
|
message:
|
|
`${artifactPath} (${artifactLabel}, ${committed.length} bytes) != freshly generated content (${content.length} bytes)\n\n`
|
|
+ 'Regenerate with:\n node scripts/gen-exit-code-registry.cjs --write',
|
|
context: { artifact: artifactLabel, path: artifactPath },
|
|
};
|
|
}
|
|
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* --check verifies ALL FIVE committed artifacts against the same freshly
|
|
* generated content and fails naming which one drifted (or is missing) if
|
|
* any does. Checked in a fixed order (primary, secondary, hooks, dts, sh) so
|
|
* a single-artifact failure is always reported deterministically.
|
|
*/
|
|
function doCheck(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, json) {
|
|
const result = buildRegistryContent(declarationPath);
|
|
if (!result.ok) {
|
|
emitFail(result, json);
|
|
return 1;
|
|
}
|
|
const dtsContent = serializeDts(declarationPath);
|
|
const shContent = serializeSh(result.entries, declarationPath);
|
|
|
|
const artifacts = [
|
|
['primary', outPath, result.content],
|
|
['secondary', scriptsOutPath, result.content],
|
|
['hooks', hooksOutPath, result.content],
|
|
['dts', dtsPath, dtsContent],
|
|
['sh', shPath, shContent],
|
|
];
|
|
for (const [artifactLabel, artifactPath, content] of artifacts) {
|
|
const checked = checkOneArtifact(artifactLabel, artifactPath, content);
|
|
if (!checked.ok) {
|
|
emitFail(checked, json);
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
emitOk(
|
|
REASON.OK,
|
|
`ok gen-exit-code-registry: ${outPath} matches ${declarationPath}\n`
|
|
+ `ok gen-exit-code-registry: ${scriptsOutPath} matches ${declarationPath}\n`
|
|
+ `ok gen-exit-code-registry: ${hooksOutPath} matches ${declarationPath}\n`
|
|
+ `ok gen-exit-code-registry: ${dtsPath} matches ${declarationPath}\n`
|
|
+ `ok gen-exit-code-registry: ${shPath} matches ${declarationPath}`,
|
|
json,
|
|
);
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* @returns {{mode:'write'|'check', declarationPath:?string, outPath:?string, scriptsOutPath:?string, hooksOutPath:?string, dtsPath:?string, shPath:?string, json:boolean}}
|
|
*/
|
|
function parseArgs(argv) {
|
|
let mode = null;
|
|
let declarationPath = null;
|
|
let outPath = null;
|
|
let scriptsOutPath = null;
|
|
let hooksOutPath = null;
|
|
let dtsPath = null;
|
|
let shPath = null;
|
|
let json = false;
|
|
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const arg = argv[i];
|
|
if (arg === '--write' || arg === '--check') {
|
|
if (mode !== null) {
|
|
throw new Error(`conflicting mode flags: --${mode} and ${arg}`);
|
|
}
|
|
mode = arg === '--write' ? 'write' : 'check';
|
|
} else if (arg === '--json') {
|
|
json = true;
|
|
} else if (arg === '--declaration') {
|
|
const value = argv[++i];
|
|
if (value === undefined) throw new Error('--declaration requires a value');
|
|
declarationPath = value;
|
|
} else if (arg.startsWith('--declaration=')) {
|
|
declarationPath = arg.slice('--declaration='.length);
|
|
} else if (arg === '--out') {
|
|
const value = argv[++i];
|
|
if (value === undefined) throw new Error('--out requires a value');
|
|
outPath = value;
|
|
} else if (arg.startsWith('--out=')) {
|
|
outPath = arg.slice('--out='.length);
|
|
} else if (arg === '--scripts-out') {
|
|
const value = argv[++i];
|
|
if (value === undefined) throw new Error('--scripts-out requires a value');
|
|
scriptsOutPath = value;
|
|
} else if (arg.startsWith('--scripts-out=')) {
|
|
scriptsOutPath = arg.slice('--scripts-out='.length);
|
|
} else if (arg === '--hooks-out') {
|
|
const value = argv[++i];
|
|
if (value === undefined) throw new Error('--hooks-out requires a value');
|
|
hooksOutPath = value;
|
|
} else if (arg.startsWith('--hooks-out=')) {
|
|
hooksOutPath = arg.slice('--hooks-out='.length);
|
|
} else if (arg === '--dts-out') {
|
|
const value = argv[++i];
|
|
if (value === undefined) throw new Error('--dts-out requires a value');
|
|
dtsPath = value;
|
|
} else if (arg.startsWith('--dts-out=')) {
|
|
dtsPath = arg.slice('--dts-out='.length);
|
|
} else if (arg === '--sh-out') {
|
|
const value = argv[++i];
|
|
if (value === undefined) throw new Error('--sh-out requires a value');
|
|
shPath = value;
|
|
} else if (arg.startsWith('--sh-out=')) {
|
|
shPath = arg.slice('--sh-out='.length);
|
|
} else {
|
|
throw new Error(`unrecognized argument: ${arg}`);
|
|
}
|
|
}
|
|
|
|
return { mode: mode || 'write', declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, json };
|
|
}
|
|
|
|
function main() {
|
|
// --json must be honored even on a parse failure (e.g. an unrecognized
|
|
// flag alongside --json), so it is detected from the raw argv rather
|
|
// than from parseArgs's return value, which may never be produced.
|
|
const rawArgv = process.argv.slice(2);
|
|
const jsonRequested = rawArgv.includes('--json');
|
|
|
|
let args;
|
|
try {
|
|
args = parseArgs(rawArgv);
|
|
} catch (err) {
|
|
emitFail({ reason: REASON.USAGE, message: jsonRequested ? err.message : `${err.message}\n${USAGE_MESSAGE}` }, jsonRequested);
|
|
return 1;
|
|
}
|
|
|
|
const declarationPath = args.declarationPath || DEFAULT_DECLARATION_PATH;
|
|
const outPath = args.outPath || DEFAULT_OUTPUT_PATH;
|
|
const scriptsOutPath = args.scriptsOutPath || DEFAULT_SCRIPTS_OUTPUT_PATH;
|
|
const hooksOutPath = args.hooksOutPath || DEFAULT_HOOKS_OUTPUT_PATH;
|
|
const dtsPath = args.dtsPath || DEFAULT_DTS_OUTPUT_PATH;
|
|
const shPath = args.shPath || DEFAULT_SH_OUTPUT_PATH;
|
|
|
|
return args.mode === 'check'
|
|
? doCheck(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, args.json)
|
|
: doWrite(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, args.json);
|
|
}
|
|
|
|
if (require.main === module) process.exitCode = main();
|
|
|
|
module.exports = {
|
|
REASON,
|
|
USAGE_MESSAGE,
|
|
DEFAULT_DECLARATION_PATH,
|
|
DEFAULT_OUTPUT_PATH,
|
|
DEFAULT_SCRIPTS_OUTPUT_PATH,
|
|
DEFAULT_HOOKS_OUTPUT_PATH,
|
|
DEFAULT_DTS_OUTPUT_PATH,
|
|
DEFAULT_SH_OUTPUT_PATH,
|
|
ENTRY_FIELD_TYPES,
|
|
isAllocatableCode,
|
|
bandFor,
|
|
validateEntry,
|
|
validateEntries,
|
|
loadDeclaration,
|
|
serializeRegistry,
|
|
serializeDts,
|
|
serializeSh,
|
|
buildRegistryContent,
|
|
parseArgs,
|
|
main,
|
|
};
|