@intentius/chant 0.124.84 → 0.124.86
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/dist/bundle-check.d.ts +102 -0
- package/dist/bundle-check.d.ts.map +1 -0
- package/dist/bundle-check.js +310 -0
- package/dist/chant-install.d.ts +100 -0
- package/dist/chant-install.d.ts.map +1 -0
- package/dist/chant-install.js +158 -0
- package/dist/ci-commit.d.ts +19 -6
- package/dist/ci-commit.d.ts.map +1 -1
- package/dist/ci-commit.js +23 -4
- package/dist/ci-evidence-jobs.d.ts +54 -0
- package/dist/ci-evidence-jobs.d.ts.map +1 -0
- package/dist/ci-evidence-jobs.js +55 -0
- package/dist/ci-image.d.ts +274 -0
- package/dist/ci-image.d.ts.map +1 -0
- package/dist/ci-image.js +635 -0
- package/dist/ci-login.d.ts +150 -0
- package/dist/ci-login.d.ts.map +1 -0
- package/dist/ci-login.js +240 -0
- package/dist/ci-product.d.ts +16 -0
- package/dist/ci-product.d.ts.map +1 -1
- package/dist/ci-product.js +17 -0
- package/dist/cli/commands/import-index.js +2 -2
- package/dist/cli/handlers/build.d.ts +8 -0
- package/dist/cli/handlers/build.d.ts.map +1 -1
- package/dist/cli/handlers/build.js +22 -4
- package/dist/cli/handlers/ci-check.d.ts.map +1 -1
- package/dist/cli/handlers/ci-check.js +57 -2
- package/dist/cli/handlers/ci-evidence.d.ts +3 -0
- package/dist/cli/handlers/ci-evidence.d.ts.map +1 -0
- package/dist/cli/handlers/ci-evidence.js +171 -0
- package/dist/cli/handlers/components.js +3 -3
- package/dist/cli/handlers/dead-guards.d.ts +3 -0
- package/dist/cli/handlers/dead-guards.d.ts.map +1 -0
- package/dist/cli/handlers/dead-guards.js +35 -0
- package/dist/cli/handlers/graph.js +4 -4
- package/dist/cli/handlers/lifecycle.d.ts +2 -1
- package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
- package/dist/cli/handlers/lifecycle.js +5 -4
- package/dist/cli/handlers/local-chant.d.ts +16 -0
- package/dist/cli/handlers/local-chant.d.ts.map +1 -0
- package/dist/cli/handlers/local-chant.js +109 -0
- package/dist/cli/handlers/operator.js +2 -2
- package/dist/cli/handlers/search.js +5 -5
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +38 -0
- package/dist/cli/parse-args.d.ts.map +1 -1
- package/dist/cli/parse-args.js +28 -0
- package/dist/cli/registry.d.ts +16 -0
- package/dist/cli/registry.d.ts.map +1 -1
- package/dist/components/check-hooks.d.ts +49 -0
- package/dist/components/check-hooks.d.ts.map +1 -1
- package/dist/components/check-hooks.js +64 -4
- package/dist/components/check-steps.d.ts +17 -0
- package/dist/components/check-steps.d.ts.map +1 -1
- package/dist/components/check-steps.js +37 -5
- package/dist/components/product-pipeline.d.ts +23 -0
- package/dist/components/product-pipeline.d.ts.map +1 -1
- package/dist/components/product-pipeline.js +6 -2
- package/dist/components/product-plan.d.ts +137 -0
- package/dist/components/product-plan.d.ts.map +1 -0
- package/dist/components/product-plan.js +143 -0
- package/dist/components/release-compile.d.ts.map +1 -1
- package/dist/components/release-compile.js +2 -2
- package/dist/config.d.ts +39 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +35 -3
- package/dist/dead-guards.d.ts +82 -0
- package/dist/dead-guards.d.ts.map +1 -0
- package/dist/dead-guards.js +436 -0
- package/dist/discovery/files.d.ts +3 -1
- package/dist/discovery/files.d.ts.map +1 -1
- package/dist/discovery/files.js +5 -3
- package/dist/drift-issue.d.ts +152 -0
- package/dist/drift-issue.d.ts.map +1 -0
- package/dist/drift-issue.js +167 -0
- package/dist/floor-table.d.ts +30 -0
- package/dist/floor-table.d.ts.map +1 -0
- package/dist/floor-table.data.d.ts +3 -0
- package/dist/floor-table.data.d.ts.map +1 -0
- package/dist/floor-table.data.js +178 -0
- package/dist/floor-table.js +56 -0
- package/dist/forge-flags.d.ts +90 -0
- package/dist/forge-flags.d.ts.map +1 -0
- package/dist/forge-flags.js +184 -0
- package/dist/lexicon.d.ts +69 -0
- package/dist/lexicon.d.ts.map +1 -1
- package/dist/lifecycle/gated-op.d.ts +7 -1
- package/dist/lifecycle/gated-op.d.ts.map +1 -1
- package/dist/lifecycle/gated-op.js +7 -4
- package/dist/local-chant.d.ts +98 -0
- package/dist/local-chant.d.ts.map +1 -0
- package/dist/local-chant.js +307 -0
- package/dist/op/activities/predict-behaviour.js +2 -2
- package/dist/op/op-waves-evidence-spec.d.ts +13 -0
- package/dist/op/op-waves-evidence-spec.d.ts.map +1 -0
- package/dist/op/op-waves-evidence-spec.js +21 -0
- package/dist/op/op-waves-evidence.d.ts +38 -0
- package/dist/op/op-waves-evidence.d.ts.map +1 -0
- package/dist/op/op-waves-evidence.js +57 -0
- package/dist/op/op-waves-run.d.ts +4 -0
- package/dist/op/op-waves-run.d.ts.map +1 -1
- package/dist/op/op-waves-run.js +24 -1
- package/dist/op/op-waves.d.ts +17 -1
- package/dist/op/op-waves.d.ts.map +1 -1
- package/dist/op/op-waves.js +23 -0
- package/dist/op/schedule-overdue.d.ts +41 -9
- package/dist/op/schedule-overdue.d.ts.map +1 -1
- package/dist/op/schedule-overdue.js +154 -25
- package/dist/plan-summary.d.ts +25 -0
- package/dist/plan-summary.d.ts.map +1 -1
- package/dist/plan-summary.js +31 -0
- package/dist/pr-plan-note.d.ts +35 -0
- package/dist/pr-plan-note.d.ts.map +1 -1
- package/dist/pr-plan-note.js +10 -0
- package/dist/pr-post.d.ts +23 -0
- package/dist/pr-post.d.ts.map +1 -1
- package/dist/pr-post.js +125 -3
- package/dist/release-floors.d.ts +31 -1
- package/dist/release-floors.d.ts.map +1 -1
- package/dist/release-floors.js +31 -1
- package/dist/state-migration.d.ts +24 -0
- package/dist/state-migration.d.ts.map +1 -1
- package/dist/state-migration.js +100 -5
- package/dist/wave-runtime.mjs +305 -298
- package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
- package/dist/workspace/lexicon-outputs.js +21 -7
- package/dist/workspace/reason-codes.d.ts +3 -0
- package/dist/workspace/reason-codes.d.ts.map +1 -1
- package/dist/workspace/reason-codes.js +4 -0
- package/dist/workspace/ref-gate.schema.json +85 -0
- package/dist/workspace/search-contract.d.ts +1 -1
- package/dist/workspace/search-contract.d.ts.map +1 -1
- package/dist/workspace/trust/check-evidence-report.d.ts +51 -0
- package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
- package/dist/workspace/trust/check-evidence-report.js +102 -0
- package/dist/workspace/trust/check-evidence.d.ts +126 -0
- package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
- package/dist/workspace/trust/check-evidence.js +237 -0
- package/dist/workspace/trust/local-evidence.d.ts +120 -0
- package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
- package/dist/workspace/trust/local-evidence.js +259 -0
- package/dist/workspace/trust/policy.d.ts +84 -0
- package/dist/workspace/trust/policy.d.ts.map +1 -1
- package/dist/workspace/trust/policy.js +94 -1
- package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
- package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
- package/dist/workspace/trust/ref-gate-cli.js +234 -0
- package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
- package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
- package/dist/workspace/trust/ref-gate-fixture.js +97 -0
- package/dist/workspace/trust/ref-gate.d.ts +187 -0
- package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
- package/dist/workspace/trust/ref-gate.js +430 -0
- package/dist/workspace/trust/trust-files.d.ts.map +1 -1
- package/dist/workspace/trust/trust-files.js +18 -1
- package/package.json +1 -1
- package/src/bundle-check.test.ts +140 -0
- package/src/bundle-check.ts +352 -0
- package/src/chant-install.test.ts +112 -0
- package/src/chant-install.ts +179 -0
- package/src/ci-commit.test.ts +45 -0
- package/src/ci-commit.ts +38 -4
- package/src/ci-evidence-jobs.ts +67 -0
- package/src/ci-image.test.ts +506 -0
- package/src/ci-image.ts +822 -0
- package/src/ci-login.test.ts +235 -0
- package/src/ci-login.ts +307 -0
- package/src/ci-product.ts +18 -0
- package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
- package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
- package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
- package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
- package/src/cli/commands/import-index.ts +2 -2
- package/src/cli/handlers/build-source-dir.test.ts +64 -0
- package/src/cli/handlers/build.ts +21 -4
- package/src/cli/handlers/ci-check.ts +56 -3
- package/src/cli/handlers/ci-evidence.ts +162 -0
- package/src/cli/handlers/components.ts +3 -3
- package/src/cli/handlers/dead-guards.ts +37 -0
- package/src/cli/handlers/graph.ts +4 -4
- package/src/cli/handlers/lifecycle.ts +5 -4
- package/src/cli/handlers/local-chant.ts +106 -0
- package/src/cli/handlers/operator.ts +2 -2
- package/src/cli/handlers/search.ts +5 -5
- package/src/cli/main.test.ts +7 -0
- package/src/cli/main.ts +38 -0
- package/src/cli/parse-args.ts +21 -0
- package/src/cli/registry.ts +16 -0
- package/src/components/check-evidence-stage.test.ts +80 -0
- package/src/components/check-hooks.ts +84 -4
- package/src/components/check-local-evidence-stage.test.ts +141 -0
- package/src/components/check-steps.ts +56 -6
- package/src/components/product-pipeline.ts +28 -3
- package/src/components/product-plan.test.ts +87 -0
- package/src/components/product-plan.ts +226 -0
- package/src/components/release-compile.ts +2 -2
- package/src/config.ts +44 -3
- package/src/dead-guards.test.ts +206 -0
- package/src/dead-guards.ts +446 -0
- package/src/discovery/files.ts +5 -3
- package/src/drift-issue-bundle.test.ts +31 -0
- package/src/drift-issue.test.ts +206 -0
- package/src/drift-issue.ts +274 -0
- package/src/fit-note.test.ts +44 -0
- package/src/floor-table.data.ts +180 -0
- package/src/floor-table.ts +77 -0
- package/src/forge-flags.test.ts +110 -0
- package/src/forge-flags.ts +208 -0
- package/src/gate-decision-bundle.test.ts +1 -0
- package/src/lexicon.ts +68 -0
- package/src/lifecycle/gated-op.ts +10 -5
- package/src/local-chant.e2e.test.ts +94 -0
- package/src/local-chant.test.ts +162 -0
- package/src/local-chant.ts +341 -0
- package/src/op/activities/predict-behaviour.ts +2 -2
- package/src/op/op-waves-evidence-spec.ts +24 -0
- package/src/op/op-waves-evidence.test.ts +130 -0
- package/src/op/op-waves-evidence.ts +57 -0
- package/src/op/op-waves-run.ts +25 -1
- package/src/op/op-waves.ts +31 -1
- package/src/op/schedule-overdue.test.ts +85 -0
- package/src/op/schedule-overdue.ts +162 -26
- package/src/plan-summary.ts +40 -0
- package/src/pr-plan-note.ts +34 -0
- package/src/pr-post-plan-note.test.ts +146 -0
- package/src/pr-post.ts +127 -3
- package/src/release-floors.ts +44 -1
- package/src/stage-hooks-bundle.test.ts +1 -0
- package/src/state-migration.test.ts +52 -1
- package/src/state-migration.ts +107 -5
- package/src/workspace/lexicon-outputs.ts +23 -6
- package/src/workspace/reason-codes.test.ts +3 -0
- package/src/workspace/reason-codes.ts +4 -0
- package/src/workspace/ref-gate.schema.json +85 -0
- package/src/workspace/trust/check-evidence-report.ts +106 -0
- package/src/workspace/trust/check-evidence.test.ts +133 -0
- package/src/workspace/trust/check-evidence.ts +257 -0
- package/src/workspace/trust/local-evidence.test.ts +127 -0
- package/src/workspace/trust/local-evidence.ts +266 -0
- package/src/workspace/trust/policy.ts +134 -1
- package/src/workspace/trust/ref-gate-cli.ts +244 -0
- package/src/workspace/trust/ref-gate-fixture.ts +125 -0
- package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
- package/src/workspace/trust/ref-gate.test.ts +247 -0
- package/src/workspace/trust/ref-gate.ts +538 -0
- package/src/workspace/trust/trust-files.test.ts +16 -0
- package/src/workspace/trust/trust-files.ts +41 -1
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@intentius/chant/bundle-check` (#4787): how a product's bundle treats its
|
|
3
|
+
* chant imports, and the check that holds the bundle to that shape.
|
|
4
|
+
*
|
|
5
|
+
* A product (terragucci, plywood, sql-yodeler) bundles its own code into one
|
|
6
|
+
* file and imports chant from the installed, pinned package at run time,
|
|
7
|
+
* wherever that package serves the import as compiled JS under Node's
|
|
8
|
+
* `import` condition (#4591). Each product carried its own copy of this:
|
|
9
|
+
* `chantRuntimeTarget` and an esbuild plugin that leaves such imports
|
|
10
|
+
* external, and a bundle check that the bundle imports nothing else, that the
|
|
11
|
+
* package's runtime dependencies match the root's chant pin, and that the
|
|
12
|
+
* bundle stays under its size ceiling. They live here so a product only
|
|
13
|
+
* names its bundle, its ceiling and its denied inputs (`chantBundleCheck` in
|
|
14
|
+
* the package's package.json, read by `chant dev bundle-check`).
|
|
15
|
+
*
|
|
16
|
+
* This module imports only Node's own modules, so a product's build script
|
|
17
|
+
* can import it from plain Node.
|
|
18
|
+
*/
|
|
19
|
+
import { execFileSync } from "node:child_process";
|
|
20
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
21
|
+
import { builtinModules } from "node:module";
|
|
22
|
+
import { dirname, join, resolve } from "node:path";
|
|
23
|
+
|
|
24
|
+
/** Any `@intentius/chant` package, with or without a subpath: core and every lexicon. */
|
|
25
|
+
const CHANT = /^(@intentius\/chant(?:-[a-z0-9-]+)?)(\/.*)?$/;
|
|
26
|
+
const CONDITIONS = ["import", "node", "default"];
|
|
27
|
+
|
|
28
|
+
/** The target Node's ESM conditions pick from one exports value, in key order. */
|
|
29
|
+
function pick(value: unknown): string | undefined {
|
|
30
|
+
if (typeof value === "string") return value;
|
|
31
|
+
if (Array.isArray(value)) {
|
|
32
|
+
for (const v of value) {
|
|
33
|
+
const t = pick(v);
|
|
34
|
+
if (t !== undefined) return t;
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
if (value && typeof value === "object") {
|
|
39
|
+
for (const [key, v] of Object.entries(value)) {
|
|
40
|
+
if (CONDITIONS.includes(key)) return pick(v);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The file `subpath` (`.` or `./x`) of the package at `pkgDir` names under Node's ESM conditions, or undefined. */
|
|
47
|
+
function exportsTarget(pkgDir: string, subpath: string): string | undefined {
|
|
48
|
+
const map = (JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")) as { exports?: unknown }).exports;
|
|
49
|
+
if (typeof map === "string") return subpath === "." ? join(pkgDir, map) : undefined;
|
|
50
|
+
if (!map || typeof map !== "object" || Array.isArray(map)) return undefined;
|
|
51
|
+
const entries = map as Record<string, unknown>;
|
|
52
|
+
// A map of conditions alone is the root's entry.
|
|
53
|
+
if (!Object.keys(entries).some((k) => k.startsWith("."))) {
|
|
54
|
+
const t = subpath === "." ? pick(entries) : undefined;
|
|
55
|
+
return t === undefined ? undefined : join(pkgDir, t);
|
|
56
|
+
}
|
|
57
|
+
if (subpath in entries) {
|
|
58
|
+
const t = pick(entries[subpath]);
|
|
59
|
+
return t === undefined ? undefined : join(pkgDir, t);
|
|
60
|
+
}
|
|
61
|
+
// Node's pattern match: of the keys with one `*` that match, the longest prefix wins.
|
|
62
|
+
let best: { prefix: string; star: string; value: unknown } | undefined;
|
|
63
|
+
for (const key of Object.keys(entries)) {
|
|
64
|
+
const at = key.indexOf("*");
|
|
65
|
+
if (at < 0 || key.indexOf("*", at + 1) >= 0) continue;
|
|
66
|
+
const prefix = key.slice(0, at);
|
|
67
|
+
const suffix = key.slice(at + 1);
|
|
68
|
+
if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix) || subpath.length < key.length - 1) continue;
|
|
69
|
+
if (best && prefix.length <= best.prefix.length) continue;
|
|
70
|
+
best = { prefix, star: subpath.slice(prefix.length, subpath.length - suffix.length), value: entries[key] };
|
|
71
|
+
}
|
|
72
|
+
if (!best) return undefined;
|
|
73
|
+
const t = pick(best.value);
|
|
74
|
+
return t === undefined ? undefined : join(pkgDir, t.split("*").join(best.star));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The directory of `name` as Node finds it from `fromDir`, walking up the node_modules folders, or undefined. */
|
|
78
|
+
export function installedPackageDir(name: string, fromDir: string): string | undefined {
|
|
79
|
+
for (let dir = resolve(fromDir); ; dir = dirname(dir)) {
|
|
80
|
+
const pkgDir = join(dir, "node_modules", name);
|
|
81
|
+
if (existsSync(join(pkgDir, "package.json"))) return pkgDir;
|
|
82
|
+
if (dirname(dir) === dir) return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The compiled file Node would load for the chant `specifier` (core or a
|
|
88
|
+
* lexicon, with or without a subpath) imported from a file in `fromDir`, or
|
|
89
|
+
* undefined: the specifier is not chant's, the installed package does not
|
|
90
|
+
* export it, exports only TypeScript for it, or is not installed. Plain Node
|
|
91
|
+
* does not load TypeScript from node_modules, so only a compiled target can
|
|
92
|
+
* stay external.
|
|
93
|
+
*/
|
|
94
|
+
export function chantRuntimeTarget(specifier: string, fromDir: string): string | undefined {
|
|
95
|
+
const m = CHANT.exec(specifier);
|
|
96
|
+
if (!m) return undefined;
|
|
97
|
+
const pkgDir = installedPackageDir(m[1], fromDir);
|
|
98
|
+
if (pkgDir === undefined) return undefined;
|
|
99
|
+
const file = exportsTarget(pkgDir, m[2] ? `.${m[2]}` : ".");
|
|
100
|
+
return file !== undefined && /\.(?:m?js|cjs)$/.test(file) && existsSync(file) ? file : undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Whether the chant installed for the package at `pkgDir` serves its root as compiled JS (#4591 and later). */
|
|
104
|
+
export function chantServesCompiled(pkgDir: string): boolean {
|
|
105
|
+
return chantRuntimeTarget("@intentius/chant", pkgDir) !== undefined;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The part of esbuild's plugin API {@link chantExternalPlugin} uses, so this module needs no esbuild types. */
|
|
109
|
+
export interface EsbuildPluginLike {
|
|
110
|
+
name: string;
|
|
111
|
+
setup(build: {
|
|
112
|
+
onResolve(options: { filter: RegExp }, callback: (args: { path: string }) => { path: string; external: boolean } | undefined): void;
|
|
113
|
+
}): void;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* An esbuild plugin that leaves an `@intentius/chant*` import external when
|
|
118
|
+
* the chant installed for `pkgDir` (where the bin runs) serves it as compiled
|
|
119
|
+
* JS, so the bundle runs the installed, pinned chant. Any other chant import
|
|
120
|
+
* goes on to the next plugin and esbuild, which bundle it. `external`, when
|
|
121
|
+
* given, collects the specifiers left external.
|
|
122
|
+
*/
|
|
123
|
+
export function chantExternalPlugin(pkgDir: string, external?: Set<string>): EsbuildPluginLike {
|
|
124
|
+
return {
|
|
125
|
+
name: "chant-external",
|
|
126
|
+
setup(b) {
|
|
127
|
+
b.onResolve({ filter: CHANT }, (args) => {
|
|
128
|
+
if (chantRuntimeTarget(args.path, pkgDir) === undefined) return undefined;
|
|
129
|
+
external?.add(args.path);
|
|
130
|
+
return { path: args.path, external: true };
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The bare specifiers a bundle imports: static `import` and `export ... from`,
|
|
138
|
+
* `import()` and `require()` of a string. Relative imports are left out, and
|
|
139
|
+
* so are strings in minified code that the pattern also matches but that hold
|
|
140
|
+
* spaces, commas, quotes or template braces.
|
|
141
|
+
*/
|
|
142
|
+
export function bundleImports(text: string): string[] {
|
|
143
|
+
const out = new Set<string>();
|
|
144
|
+
const re = /(?:^|[;\s}])(?:import|export)\s*(?:[\w*{}\s,$]+from\s*)?["']([^"']+)["']|import\(\s*["']([^"']+)["']\s*\)|require\(\s*["']([^"']+)["']\s*\)/gm;
|
|
145
|
+
for (const m of text.matchAll(re)) {
|
|
146
|
+
const s = m[1] ?? m[2] ?? m[3];
|
|
147
|
+
if (s !== undefined && /^[\w@][\w@./:-]*$/.test(s)) out.add(s);
|
|
148
|
+
}
|
|
149
|
+
return [...out];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The package a bare specifier names: `@scope/name` or `name`. */
|
|
153
|
+
export function packageOf(specifier: string): string {
|
|
154
|
+
return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** An input the bundle must not include: a pattern matched against each metafile input with everything up to its last `node_modules/` removed. */
|
|
158
|
+
export interface DeniedInput {
|
|
159
|
+
pattern: string;
|
|
160
|
+
/** What the input is, in the failure: "the TypeScript compiler". */
|
|
161
|
+
what: string;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A product's bundle check, as `chantBundleCheck` in its package's package.json (#4787). Paths are relative to the package. */
|
|
165
|
+
export interface BundleCheckConfig {
|
|
166
|
+
/** The bundle file, such as `dist/terragucci.mjs`. */
|
|
167
|
+
bundle: string;
|
|
168
|
+
/** The most bytes the bundle file may hold. */
|
|
169
|
+
maxBytes?: number;
|
|
170
|
+
/** The most bytes the package's `npm pack` tarball may hold (`npm pack --dry-run --ignore-scripts`). */
|
|
171
|
+
maxPackBytes?: number;
|
|
172
|
+
/**
|
|
173
|
+
* Packages the code loads at run time that no import in the bundle names,
|
|
174
|
+
* such as `@intentius/chant` for a bin it spawns, or a lexicon chant's
|
|
175
|
+
* generator loads by name. Each must be a runtime dependency.
|
|
176
|
+
*/
|
|
177
|
+
needs?: string[];
|
|
178
|
+
/** Packages the bundle may import that are not dependencies: optional ones it loads when present. */
|
|
179
|
+
optional?: string[];
|
|
180
|
+
/** esbuild's metafile for the bundle, to check its inputs against `deny`. */
|
|
181
|
+
metafile?: string;
|
|
182
|
+
deny?: DeniedInput[];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface BundleCheckResult {
|
|
186
|
+
ok: boolean;
|
|
187
|
+
problems: string[];
|
|
188
|
+
/** One line saying what was checked, for a passing check. */
|
|
189
|
+
summary: string;
|
|
190
|
+
bundleBytes: number;
|
|
191
|
+
packBytes?: number;
|
|
192
|
+
/** The chant imports the bundle leaves to the installed chant. */
|
|
193
|
+
chantImports: string[];
|
|
194
|
+
/** The installed chant's version, with the commit when it is a local build (`chantLocal`). */
|
|
195
|
+
chant: string;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
interface Manifest {
|
|
199
|
+
name?: string;
|
|
200
|
+
version?: string;
|
|
201
|
+
workspaces?: unknown;
|
|
202
|
+
dependencies?: Record<string, string>;
|
|
203
|
+
devDependencies?: Record<string, string>;
|
|
204
|
+
chantBundleCheck?: BundleCheckConfig;
|
|
205
|
+
chantLocal?: { commit?: string; dir?: string };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const readManifest = (file: string): Manifest => JSON.parse(readFileSync(file, "utf8")) as Manifest;
|
|
209
|
+
|
|
210
|
+
/** The nearest directory from `pkgDir` up whose package.json declares workspaces, else `pkgDir`: where the product pins chant. */
|
|
211
|
+
export function productRoot(pkgDir: string): string {
|
|
212
|
+
for (let dir = resolve(pkgDir); ; dir = dirname(dir)) {
|
|
213
|
+
const f = join(dir, "package.json");
|
|
214
|
+
if (existsSync(f) && readManifest(f).workspaces !== undefined) return dir;
|
|
215
|
+
if (dirname(dir) === dir) return resolve(pkgDir);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The `chantBundleCheck` field of the package at `pkgDir`, or undefined when it has none. */
|
|
220
|
+
export function readBundleCheckConfig(pkgDir: string): BundleCheckConfig | undefined {
|
|
221
|
+
const f = join(pkgDir, "package.json");
|
|
222
|
+
if (!existsSync(f)) return undefined;
|
|
223
|
+
return readManifest(f).chantBundleCheck;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The size of the tarball `npm pack` would write for the package at `pkgDir`, without running its scripts. */
|
|
227
|
+
function packSize(pkgDir: string): number {
|
|
228
|
+
const out = execFileSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], { cwd: pkgDir, stdio: ["ignore", "pipe", "pipe"] }).toString();
|
|
229
|
+
const [packed] = JSON.parse(out) as { size: number }[];
|
|
230
|
+
return packed.size;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Check the package at `pkgDir` against `config` (#4787):
|
|
235
|
+
*
|
|
236
|
+
* - the bundle imports only Node's modules, its runtime dependencies and the
|
|
237
|
+
* `optional` packages, and each chant import is one the installed chant
|
|
238
|
+
* serves as compiled JS ({@link chantRuntimeTarget});
|
|
239
|
+
* - the runtime dependencies are exactly the packages the bundle imports and
|
|
240
|
+
* the `needs`, and every `@intentius/chant*` among them and among the
|
|
241
|
+
* devDependencies is pinned to the root's `@intentius/chant`, an exact version;
|
|
242
|
+
* - each installed chant package is that version, or a local build marked
|
|
243
|
+
* `chantLocal` (`chant dev local`);
|
|
244
|
+
* - the bundle and the tarball stay within `maxBytes` and `maxPackBytes`;
|
|
245
|
+
* - no metafile input matches a `deny` pattern.
|
|
246
|
+
*/
|
|
247
|
+
export function checkBundle(pkgDir: string, config: BundleCheckConfig): BundleCheckResult {
|
|
248
|
+
const dir = resolve(pkgDir);
|
|
249
|
+
const problems: string[] = [];
|
|
250
|
+
const pkg = readManifest(join(dir, "package.json"));
|
|
251
|
+
const root = productRoot(dir);
|
|
252
|
+
const rootPkg = readManifest(join(root, "package.json"));
|
|
253
|
+
const pin = rootPkg.dependencies?.["@intentius/chant"] ?? rootPkg.devDependencies?.["@intentius/chant"];
|
|
254
|
+
if (pin === undefined) problems.push(`${join(root, "package.json")} does not name @intentius/chant`);
|
|
255
|
+
else if (!/^\d+\.\d+\.\d+(?:-[\w.]+)?$/.test(pin)) problems.push(`@intentius/chant is '${pin}' in ${join(root, "package.json")}, not an exact version`);
|
|
256
|
+
|
|
257
|
+
const bundleFile = join(dir, config.bundle);
|
|
258
|
+
let text = "";
|
|
259
|
+
let bundleBytes = 0;
|
|
260
|
+
if (!existsSync(bundleFile)) problems.push(`no bundle at ${config.bundle}; build it first`);
|
|
261
|
+
else {
|
|
262
|
+
text = readFileSync(bundleFile, "utf8");
|
|
263
|
+
bundleBytes = statSync(bundleFile).size;
|
|
264
|
+
if (config.maxBytes !== undefined && bundleBytes > config.maxBytes) {
|
|
265
|
+
problems.push(`the bundle is ${Math.round(bundleBytes / 1024)} KB, over the ${Math.round(config.maxBytes / 1024)} KB ceiling`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const deps = pkg.dependencies ?? {};
|
|
270
|
+
const optional = new Set(config.optional ?? []);
|
|
271
|
+
const node = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);
|
|
272
|
+
const used = new Map<string, string>();
|
|
273
|
+
for (const n of config.needs ?? []) used.set(n, "chantBundleCheck.needs names it");
|
|
274
|
+
const chantImports: string[] = [];
|
|
275
|
+
for (const s of bundleImports(text)) {
|
|
276
|
+
if (node.has(s) || optional.has(s) || optional.has(packageOf(s))) continue;
|
|
277
|
+
const name = packageOf(s);
|
|
278
|
+
if (!(name in deps)) {
|
|
279
|
+
problems.push(`the bundle imports '${s}', which is neither a Node module nor a runtime dependency`);
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (!used.has(name)) used.set(name, `the bundle imports ${s}`);
|
|
283
|
+
if (CHANT.test(s)) {
|
|
284
|
+
if (chantRuntimeTarget(s, dir) === undefined) problems.push(`the bundle imports '${s}', which the installed package's exports do not serve as compiled JS under the import condition`);
|
|
285
|
+
else chantImports.push(s);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
for (const [name, why] of used) {
|
|
289
|
+
if (!(name in deps)) problems.push(`${name} is loaded at run time (${why}) but is not in dependencies${name in (pkg.devDependencies ?? {}) ? " (it is a devDependency, which npm install --omit=dev leaves out)" : ""}`);
|
|
290
|
+
}
|
|
291
|
+
for (const name of Object.keys(deps)) {
|
|
292
|
+
if (!used.has(name)) problems.push(`${name} is a runtime dependency that the bundle does not import and chantBundleCheck.needs does not name`);
|
|
293
|
+
}
|
|
294
|
+
if (pin !== undefined) {
|
|
295
|
+
for (const [kind, list] of [["dependencies", deps], ["devDependencies", pkg.devDependencies ?? {}]] as const) {
|
|
296
|
+
if (dir === root && kind === "devDependencies") continue;
|
|
297
|
+
for (const [name, v] of Object.entries(list)) {
|
|
298
|
+
if (CHANT.test(name) && v !== pin) problems.push(`${name} is '${v}' in ${kind}, not the root's chant pin ${pin}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// The installed copies: the pin, or a local build `chant dev local` marked.
|
|
304
|
+
let chant = "not installed";
|
|
305
|
+
const coreDir = installedPackageDir("@intentius/chant", dir);
|
|
306
|
+
if (coreDir === undefined) problems.push("@intentius/chant is not installed; run npm ci");
|
|
307
|
+
else {
|
|
308
|
+
const core = readManifest(join(coreDir, "package.json"));
|
|
309
|
+
chant = core.chantLocal ? `local chant ${core.version} (${String(core.chantLocal.commit).slice(0, 12)})` : `chant ${core.version}`;
|
|
310
|
+
}
|
|
311
|
+
for (const name of new Set([...Object.keys(deps), ...Object.keys(pkg.devDependencies ?? {})])) {
|
|
312
|
+
if (!CHANT.test(name) || pin === undefined) continue;
|
|
313
|
+
const at = installedPackageDir(name, dir);
|
|
314
|
+
if (at === undefined) {
|
|
315
|
+
if (name in deps) problems.push(`${name} is not installed; run npm ci`);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const installed = readManifest(join(at, "package.json"));
|
|
319
|
+
if (!installed.chantLocal && installed.version !== pin) problems.push(`the installed ${name} is ${installed.version}, not the pin ${pin}; run npm ci`);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (config.deny?.length) {
|
|
323
|
+
const metafile = config.metafile === undefined ? undefined : join(dir, config.metafile);
|
|
324
|
+
if (metafile === undefined || !existsSync(metafile)) problems.push(`chantBundleCheck.deny needs the build's esbuild metafile${config.metafile ? ` at ${config.metafile}` : " (chantBundleCheck.metafile)"}`);
|
|
325
|
+
else {
|
|
326
|
+
const inputs = Object.keys((JSON.parse(readFileSync(metafile, "utf8")) as { inputs?: Record<string, unknown> }).inputs ?? {});
|
|
327
|
+
const rules = config.deny.map((d) => ({ re: new RegExp(d.pattern), what: d.what }));
|
|
328
|
+
const hits = new Map<string, string[]>();
|
|
329
|
+
for (const input of inputs) {
|
|
330
|
+
const rel = input.replace(/^.*node_modules\//, "");
|
|
331
|
+
for (const r of rules) if (r.re.test(rel)) hits.set(r.what, [...(hits.get(r.what) ?? []), rel]);
|
|
332
|
+
}
|
|
333
|
+
for (const [what, list] of hits) {
|
|
334
|
+
problems.push(`the bundle includes ${what} (${list.length} inputs): ${list.slice(0, 3).join(", ")}${list.length > 3 ? `, and ${list.length - 3} more` : ""}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
let packBytes: number | undefined;
|
|
340
|
+
if (config.maxPackBytes !== undefined) {
|
|
341
|
+
packBytes = packSize(dir);
|
|
342
|
+
if (packBytes > config.maxPackBytes) problems.push(`the tarball is ${Math.round(packBytes / 1024)} KB, over the ${Math.round(config.maxPackBytes / 1024)} KB ceiling`);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const sizes = [
|
|
346
|
+
`bundle ${Math.round(bundleBytes / 1024)} KB${config.maxBytes !== undefined ? ` (ceiling ${Math.round(config.maxBytes / 1024)} KB)` : ""}`,
|
|
347
|
+
...(packBytes !== undefined ? [`tarball ${Math.round(packBytes / 1024)} KB (ceiling ${Math.round(config.maxPackBytes! / 1024)} KB)`] : []),
|
|
348
|
+
];
|
|
349
|
+
const summary = `${pkg.name ?? dir}: ${sizes.join(", ")}, ${Object.keys(deps).length} runtime dependencies at chant ${pin}, ${chantImports.length} chant imports served as compiled JS by ${chant}`;
|
|
350
|
+
return { ok: problems.length === 0, problems, summary, bundleBytes, packBytes, chantImports, chant };
|
|
351
|
+
}
|
|
352
|
+
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #4800 — the chant a product is installed with: this package itself, a
|
|
3
|
+
* walk up `node_modules` for terragucci's layout, the argv and PATH a child
|
|
4
|
+
* runs with, and plywood's resolve fallback for a repository with no chant.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { delimiter, join } from "node:path";
|
|
10
|
+
import { afterAll, describe, expect, test } from "vitest";
|
|
11
|
+
import { bundledChant, CHANT_SPECIFIER, chantArgv, chantCommand, chantEnv, chantResolveFallback, installedChant } from "./chant-install";
|
|
12
|
+
|
|
13
|
+
const scratch = mkdtempSync(join(tmpdir(), "chant-install-"));
|
|
14
|
+
afterAll(() => rmSync(scratch, { recursive: true, force: true }));
|
|
15
|
+
|
|
16
|
+
/** A package directory with a manifest and, when `bin` is given, the bin file. */
|
|
17
|
+
function pkg(dir: string, manifest: Record<string, unknown>, bin?: string): string {
|
|
18
|
+
mkdirSync(dir, { recursive: true });
|
|
19
|
+
writeFileSync(join(dir, "package.json"), JSON.stringify(manifest));
|
|
20
|
+
if (bin) {
|
|
21
|
+
mkdirSync(join(dir, "bin"), { recursive: true });
|
|
22
|
+
writeFileSync(join(dir, bin), "#!/usr/bin/env node\n");
|
|
23
|
+
}
|
|
24
|
+
return dir;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe("bundledChant", () => {
|
|
28
|
+
test("is the package this module belongs to, with its bin and version", () => {
|
|
29
|
+
const own = bundledChant();
|
|
30
|
+
expect(own).toBeDefined();
|
|
31
|
+
expect(own!.root).toBe(join(import.meta.dirname, ".."));
|
|
32
|
+
expect(own!.bin).toBe(join(own!.root, "bin", "chant"));
|
|
33
|
+
expect(own!.binDir).toBe(join(own!.root, "bin"));
|
|
34
|
+
expect(own!.version).toMatch(/^\d+\.\d+\.\d+/);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
describe("installedChant", () => {
|
|
39
|
+
const product = join(scratch, "product");
|
|
40
|
+
const root = pkg(join(product, "node_modules", "@intentius", "chant"), { name: "@intentius/chant", version: "1.2.3", bin: { chant: "./bin/chant" } }, "bin/chant");
|
|
41
|
+
const deep = join(product, "node_modules", "@x", "tool", "dist");
|
|
42
|
+
mkdirSync(deep, { recursive: true });
|
|
43
|
+
|
|
44
|
+
test("walks up from each start to node_modules/@intentius/chant and reads bin.chant", () => {
|
|
45
|
+
expect(installedChant([deep])).toEqual({ root, bin: join(root, "bin", "chant"), binDir: join(root, "bin"), version: "1.2.3" });
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("takes the first start that has one, and skips a manifest that is not chant's or names no bin there", () => {
|
|
49
|
+
const repo = join(scratch, "repo");
|
|
50
|
+
pkg(join(repo, "node_modules", "@intentius", "chant"), { name: "@intentius/chant", bin: { chant: "./bin/missing" } });
|
|
51
|
+
const other = join(scratch, "other");
|
|
52
|
+
pkg(join(other, "node_modules", "@intentius", "chant"), { name: "not-chant", bin: "./bin/chant" }, "bin/chant");
|
|
53
|
+
expect(installedChant([repo, other, deep])?.root).toBe(root);
|
|
54
|
+
expect(installedChant([repo, other])).toBeUndefined();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("a string bin is the chant bin too", () => {
|
|
58
|
+
const at = join(scratch, "string-bin");
|
|
59
|
+
pkg(join(at, "node_modules", "@intentius", "chant"), { name: "@intentius/chant", bin: "./bin/chant" }, "bin/chant");
|
|
60
|
+
expect(installedChant([at])?.bin).toBe(join(at, "node_modules", "@intentius", "chant", "bin", "chant"));
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe("running it", () => {
|
|
65
|
+
test("chantCommand: the named chant, else this package's bin", () => {
|
|
66
|
+
expect(chantCommand({ chant: "/opt/chant" })).toBe("/opt/chant");
|
|
67
|
+
expect(chantCommand()).toBe(bundledChant()!.bin);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("chantArgv runs the bin with this node and the product's node arguments", () => {
|
|
71
|
+
const own = bundledChant()!;
|
|
72
|
+
expect(chantArgv(["build", "--json"], { nodeArgs: ["--import", "data:x"] })).toEqual([process.execPath, "--import", "data:x", own.bin, "build", "--json"]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("chantEnv puts the bin directory first on PATH", () => {
|
|
76
|
+
const env = chantEnv({ PATH: "/usr/bin", HOME: "/h" });
|
|
77
|
+
expect(env.PATH).toBe([bundledChant()!.binDir, "/usr/bin"].join(delimiter));
|
|
78
|
+
expect(env.HOME).toBe("/h");
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe("chantResolveFallback", () => {
|
|
83
|
+
const from = "file:///opt/product/dist/bin.js";
|
|
84
|
+
const missing = Object.assign(new Error("not found"), { code: "ERR_MODULE_NOT_FOUND" });
|
|
85
|
+
|
|
86
|
+
test("covers chant and its lexicons, with any subpath", () => {
|
|
87
|
+
for (const s of ["@intentius/chant", "@intentius/chant/op", "@intentius/chant-lexicon-pulumi", "@intentius/chant-lexicon-sql/config"]) expect(CHANT_SPECIFIER.test(s), s).toBe(true);
|
|
88
|
+
for (const s of ["@intentius/chantx", "@intentius/plywood", "chant"]) expect(CHANT_SPECIFIER.test(s), s).toBe(false);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("retries a chant import the importer could not find from the product's install", () => {
|
|
92
|
+
const seen: Array<unknown> = [];
|
|
93
|
+
const hook = chantResolveFallback(from);
|
|
94
|
+
const next = (specifier: string, context?: Record<string, unknown>) => {
|
|
95
|
+
seen.push(context?.parentURL);
|
|
96
|
+
if (context?.parentURL !== from) throw missing;
|
|
97
|
+
return { url: `file:///opt/product/node_modules/${specifier}/index.js` };
|
|
98
|
+
};
|
|
99
|
+
expect(hook("@intentius/chant/op", { parentURL: "file:///repo/ops/up.op.ts" }, next).url).toBe("file:///opt/product/node_modules/@intentius/chant/op/index.js");
|
|
100
|
+
expect(seen).toEqual(["file:///repo/ops/up.op.ts", from]);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("leaves any other specifier, any other failure, and the product's own imports as Node reports them", () => {
|
|
104
|
+
const hook = chantResolveFallback(from);
|
|
105
|
+
const fail = (e: Error) => () => {
|
|
106
|
+
throw e;
|
|
107
|
+
};
|
|
108
|
+
expect(() => hook("left-pad", { parentURL: "file:///repo/a.ts" }, fail(missing))).toThrow("not found");
|
|
109
|
+
expect(() => hook("@intentius/chant", { parentURL: "file:///repo/a.ts" }, fail(new Error("syntax")))).toThrow("syntax");
|
|
110
|
+
expect(() => hook("@intentius/chant", { parentURL: from }, fail(missing))).toThrow("not found");
|
|
111
|
+
});
|
|
112
|
+
});
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #4800 — the chant a product is installed with, and how to run it.
|
|
3
|
+
*
|
|
4
|
+
* A product runs the `chant` CLI as a child for the commands it does not run
|
|
5
|
+
* in process, and the chant it runs must be the one in its own dependencies,
|
|
6
|
+
* not whatever `chant` is first on the PATH. Each product found it its own
|
|
7
|
+
* way: SQL Yodeler resolved `@intentius/chant` and ran `src/cli/main.ts`
|
|
8
|
+
* under its own tsx, terragucci walked up its directories for
|
|
9
|
+
* `node_modules/@intentius/chant/package.json` and read `bin.chant`, and
|
|
10
|
+
* plywood added a resolve hook so the Op files a repository holds find
|
|
11
|
+
* chant in plywood's install when the repository has none. This module is
|
|
12
|
+
* the one copy.
|
|
13
|
+
*
|
|
14
|
+
* {@link bundledChant} is the package this module belongs to, so a product
|
|
15
|
+
* that imports `@intentius/chant/chant-install` gets its own chant. When a
|
|
16
|
+
* product bundles this module into a file of its own, the module no longer
|
|
17
|
+
* sits in chant's package, and it walks up from where it is instead.
|
|
18
|
+
* {@link chantArgv} runs the package's `bin/chant` with the node running
|
|
19
|
+
* now: the bin picks the compiled CLI in an installed package and the source
|
|
20
|
+
* in a checkout (#3878), so a product never chooses between them.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
24
|
+
import * as nodeModule from "node:module";
|
|
25
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
|
|
28
|
+
/** Where a chant package is installed. */
|
|
29
|
+
export interface ChantInstall {
|
|
30
|
+
/** The `@intentius/chant` package directory. */
|
|
31
|
+
root: string;
|
|
32
|
+
/** Its `chant` bin script, from the manifest's `bin.chant`. */
|
|
33
|
+
bin: string;
|
|
34
|
+
/** The directory holding the bin, to put first on a child's PATH. */
|
|
35
|
+
binDir: string;
|
|
36
|
+
/** The package's version, from its manifest. */
|
|
37
|
+
version?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const PACKAGE = "@intentius/chant";
|
|
41
|
+
|
|
42
|
+
/** The install whose manifest is `<root>/package.json`, when it is chant's and names a bin that is there. */
|
|
43
|
+
function installAt(root: string): ChantInstall | undefined {
|
|
44
|
+
const manifest = join(root, "package.json");
|
|
45
|
+
if (!existsSync(manifest)) return undefined;
|
|
46
|
+
try {
|
|
47
|
+
const m = JSON.parse(readFileSync(manifest, "utf-8")) as { name?: unknown; version?: unknown; bin?: unknown };
|
|
48
|
+
if (m.name !== PACKAGE) return undefined;
|
|
49
|
+
const rel = typeof m.bin === "string" ? m.bin : m.bin && typeof m.bin === "object" ? (m.bin as Record<string, unknown>).chant : undefined;
|
|
50
|
+
if (typeof rel !== "string") return undefined;
|
|
51
|
+
const bin = resolve(root, rel);
|
|
52
|
+
if (!existsSync(bin)) return undefined;
|
|
53
|
+
return { root, bin, binDir: dirname(bin), ...(typeof m.version === "string" ? { version: m.version } : {}) };
|
|
54
|
+
} catch {
|
|
55
|
+
// An unreadable manifest is not an install.
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The chant installed for the first of `from` that has one: each directory
|
|
62
|
+
* and every directory above it, through `node_modules/@intentius/chant`
|
|
63
|
+
* (terragucci's `installedChant`, which looked from its own file and then
|
|
64
|
+
* from the repository). The package exports no `./package.json`, so the
|
|
65
|
+
* manifest is read from disk, not resolved. Undefined when none has it.
|
|
66
|
+
*/
|
|
67
|
+
export function installedChant(from: readonly string[]): ChantInstall | undefined {
|
|
68
|
+
for (const start of from) {
|
|
69
|
+
for (let dir = resolve(start); ; ) {
|
|
70
|
+
const found = installAt(join(dir, "node_modules", "@intentius", "chant"));
|
|
71
|
+
if (found) return found;
|
|
72
|
+
const up = dirname(dir);
|
|
73
|
+
if (up === dir) break;
|
|
74
|
+
dir = up;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let bundled: ChantInstall | null | undefined;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The chant this module is part of: `src/chant-install.ts` or
|
|
84
|
+
* `dist/chant-install.js`, one level under the package root. Bundled into a
|
|
85
|
+
* product's own file, the module is not in chant's package, and this is the
|
|
86
|
+
* chant {@link installedChant} finds from the module's directory. Undefined
|
|
87
|
+
* when neither has one.
|
|
88
|
+
*/
|
|
89
|
+
export function bundledChant(): ChantInstall | undefined {
|
|
90
|
+
if (bundled === undefined) {
|
|
91
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
92
|
+
bundled = installAt(dirname(here)) ?? installedChant([here]) ?? null;
|
|
93
|
+
}
|
|
94
|
+
return bundled ?? undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The chant executable a product runs: `chant` when the caller names one
|
|
99
|
+
* (a `--chant` flag), else {@link bundledChant}'s bin, else the first of
|
|
100
|
+
* `from` {@link installedChant} finds, else `chant` on the PATH.
|
|
101
|
+
*/
|
|
102
|
+
export function chantCommand(options: { chant?: string; from?: readonly string[] } = {}): string {
|
|
103
|
+
return options.chant ?? bundledChant()?.bin ?? installedChant(options.from ?? [])?.bin ?? "chant";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The argv to spawn `chant <args>` with: the node running now, `nodeArgs`
|
|
108
|
+
* (a product's own `--import` hooks), the install's bin and `args`. Running
|
|
109
|
+
* the bin through `process.execPath` works where a shebang does not
|
|
110
|
+
* (Windows, #4734). Throws when no install is found.
|
|
111
|
+
*/
|
|
112
|
+
export function chantArgv(args: readonly string[], options: { install?: ChantInstall; nodeArgs?: readonly string[] } = {}): string[] {
|
|
113
|
+
const install = options.install ?? bundledChant();
|
|
114
|
+
if (!install) throw new Error(`${PACKAGE} is not installed beside this module; install it, or name the chant to run`);
|
|
115
|
+
return [process.execPath, ...(options.nodeArgs ?? []), install.bin, ...args];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* `base` with the install's bin directory first on PATH, for a chant child:
|
|
120
|
+
* chant's own Op activities run `chant` themselves (`lifecycleDiff` runs
|
|
121
|
+
* `chant lifecycle diff`), and they must find the same one.
|
|
122
|
+
*/
|
|
123
|
+
export function chantEnv(base: NodeJS.ProcessEnv = process.env, install: ChantInstall | undefined = bundledChant()): NodeJS.ProcessEnv {
|
|
124
|
+
if (!install) return { ...base };
|
|
125
|
+
return { ...base, PATH: [install.binDir, base.PATH ?? ""].filter(Boolean).join(delimiter) };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The specifiers {@link chantResolveFallback} covers: chant and its lexicons, with any subpath. */
|
|
129
|
+
export const CHANT_SPECIFIER = /^@intentius\/chant(?:-lexicon-[a-z0-9-]+)?(?:\/|$)/;
|
|
130
|
+
|
|
131
|
+
// `module.registerHooks` (Node 22.15 and later) is newer than the
|
|
132
|
+
// @types/node the repository pins, so its shape is declared here.
|
|
133
|
+
interface ResolveResult {
|
|
134
|
+
url: string;
|
|
135
|
+
format?: string | null;
|
|
136
|
+
shortCircuit?: boolean;
|
|
137
|
+
}
|
|
138
|
+
type NextResolve = (specifier: string, context?: Record<string, unknown>) => ResolveResult;
|
|
139
|
+
type RegisterHooks = (hooks: { resolve: (specifier: string, context: Record<string, unknown>, next: NextResolve) => ResolveResult }) => unknown;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A resolve hook (plywood's `chantResolveHook`): a chant or lexicon import
|
|
143
|
+
* the importing file's own `node_modules` cannot satisfy resolves from
|
|
144
|
+
* `from`, a file URL in the product's install. A repository that runs the
|
|
145
|
+
* product from a global install has no chant of its own, and the Op files
|
|
146
|
+
* it holds import `@intentius/chant/op`. Any other specifier, and any other
|
|
147
|
+
* failure, is left as Node reports it.
|
|
148
|
+
*/
|
|
149
|
+
export function chantResolveFallback(from: string) {
|
|
150
|
+
return (specifier: string, context: Record<string, unknown>, next: NextResolve): ResolveResult => {
|
|
151
|
+
try {
|
|
152
|
+
return next(specifier, context);
|
|
153
|
+
} catch (err) {
|
|
154
|
+
const code = (err as { code?: unknown }).code;
|
|
155
|
+
if (!CHANT_SPECIFIER.test(specifier) || (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND")) throw err;
|
|
156
|
+
if (context.parentURL === from) throw err;
|
|
157
|
+
return next(specifier, { ...context, parentURL: from });
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const FALLBACK = Symbol.for("chant.resolveFallback");
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Install {@link chantResolveFallback} once in this process. `from` is a
|
|
166
|
+
* file URL in the product's install, by default this module's own, which
|
|
167
|
+
* sits in the chant the product depends on. Returns whether it is
|
|
168
|
+
* installed: false on a Node without `module.registerHooks`, where the
|
|
169
|
+
* repository needs chant in its own `node_modules`.
|
|
170
|
+
*/
|
|
171
|
+
export function installChantResolveFallback(from: string = import.meta.url): boolean {
|
|
172
|
+
const flags = globalThis as { [FALLBACK]?: boolean };
|
|
173
|
+
if (flags[FALLBACK]) return true;
|
|
174
|
+
const register = (nodeModule as unknown as { registerHooks?: RegisterHooks }).registerHooks;
|
|
175
|
+
if (typeof register !== "function") return false;
|
|
176
|
+
register({ resolve: chantResolveFallback(from) });
|
|
177
|
+
flags[FALLBACK] = true;
|
|
178
|
+
return true;
|
|
179
|
+
}
|