@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.
Files changed (254) hide show
  1. package/dist/bundle-check.d.ts +102 -0
  2. package/dist/bundle-check.d.ts.map +1 -0
  3. package/dist/bundle-check.js +310 -0
  4. package/dist/chant-install.d.ts +100 -0
  5. package/dist/chant-install.d.ts.map +1 -0
  6. package/dist/chant-install.js +158 -0
  7. package/dist/ci-commit.d.ts +19 -6
  8. package/dist/ci-commit.d.ts.map +1 -1
  9. package/dist/ci-commit.js +23 -4
  10. package/dist/ci-evidence-jobs.d.ts +54 -0
  11. package/dist/ci-evidence-jobs.d.ts.map +1 -0
  12. package/dist/ci-evidence-jobs.js +55 -0
  13. package/dist/ci-image.d.ts +274 -0
  14. package/dist/ci-image.d.ts.map +1 -0
  15. package/dist/ci-image.js +635 -0
  16. package/dist/ci-login.d.ts +150 -0
  17. package/dist/ci-login.d.ts.map +1 -0
  18. package/dist/ci-login.js +240 -0
  19. package/dist/ci-product.d.ts +16 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +17 -0
  22. package/dist/cli/commands/import-index.js +2 -2
  23. package/dist/cli/handlers/build.d.ts +8 -0
  24. package/dist/cli/handlers/build.d.ts.map +1 -1
  25. package/dist/cli/handlers/build.js +22 -4
  26. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  27. package/dist/cli/handlers/ci-check.js +57 -2
  28. package/dist/cli/handlers/ci-evidence.d.ts +3 -0
  29. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -0
  30. package/dist/cli/handlers/ci-evidence.js +171 -0
  31. package/dist/cli/handlers/components.js +3 -3
  32. package/dist/cli/handlers/dead-guards.d.ts +3 -0
  33. package/dist/cli/handlers/dead-guards.d.ts.map +1 -0
  34. package/dist/cli/handlers/dead-guards.js +35 -0
  35. package/dist/cli/handlers/graph.js +4 -4
  36. package/dist/cli/handlers/lifecycle.d.ts +2 -1
  37. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  38. package/dist/cli/handlers/lifecycle.js +5 -4
  39. package/dist/cli/handlers/local-chant.d.ts +16 -0
  40. package/dist/cli/handlers/local-chant.d.ts.map +1 -0
  41. package/dist/cli/handlers/local-chant.js +109 -0
  42. package/dist/cli/handlers/operator.js +2 -2
  43. package/dist/cli/handlers/search.js +5 -5
  44. package/dist/cli/main.d.ts.map +1 -1
  45. package/dist/cli/main.js +38 -0
  46. package/dist/cli/parse-args.d.ts.map +1 -1
  47. package/dist/cli/parse-args.js +28 -0
  48. package/dist/cli/registry.d.ts +16 -0
  49. package/dist/cli/registry.d.ts.map +1 -1
  50. package/dist/components/check-hooks.d.ts +49 -0
  51. package/dist/components/check-hooks.d.ts.map +1 -1
  52. package/dist/components/check-hooks.js +64 -4
  53. package/dist/components/check-steps.d.ts +17 -0
  54. package/dist/components/check-steps.d.ts.map +1 -1
  55. package/dist/components/check-steps.js +37 -5
  56. package/dist/components/product-pipeline.d.ts +23 -0
  57. package/dist/components/product-pipeline.d.ts.map +1 -1
  58. package/dist/components/product-pipeline.js +6 -2
  59. package/dist/components/product-plan.d.ts +137 -0
  60. package/dist/components/product-plan.d.ts.map +1 -0
  61. package/dist/components/product-plan.js +143 -0
  62. package/dist/components/release-compile.d.ts.map +1 -1
  63. package/dist/components/release-compile.js +2 -2
  64. package/dist/config.d.ts +39 -1
  65. package/dist/config.d.ts.map +1 -1
  66. package/dist/config.js +35 -3
  67. package/dist/dead-guards.d.ts +82 -0
  68. package/dist/dead-guards.d.ts.map +1 -0
  69. package/dist/dead-guards.js +436 -0
  70. package/dist/discovery/files.d.ts +3 -1
  71. package/dist/discovery/files.d.ts.map +1 -1
  72. package/dist/discovery/files.js +5 -3
  73. package/dist/drift-issue.d.ts +152 -0
  74. package/dist/drift-issue.d.ts.map +1 -0
  75. package/dist/drift-issue.js +167 -0
  76. package/dist/floor-table.d.ts +30 -0
  77. package/dist/floor-table.d.ts.map +1 -0
  78. package/dist/floor-table.data.d.ts +3 -0
  79. package/dist/floor-table.data.d.ts.map +1 -0
  80. package/dist/floor-table.data.js +178 -0
  81. package/dist/floor-table.js +56 -0
  82. package/dist/forge-flags.d.ts +90 -0
  83. package/dist/forge-flags.d.ts.map +1 -0
  84. package/dist/forge-flags.js +184 -0
  85. package/dist/lexicon.d.ts +69 -0
  86. package/dist/lexicon.d.ts.map +1 -1
  87. package/dist/lifecycle/gated-op.d.ts +7 -1
  88. package/dist/lifecycle/gated-op.d.ts.map +1 -1
  89. package/dist/lifecycle/gated-op.js +7 -4
  90. package/dist/local-chant.d.ts +98 -0
  91. package/dist/local-chant.d.ts.map +1 -0
  92. package/dist/local-chant.js +307 -0
  93. package/dist/op/activities/predict-behaviour.js +2 -2
  94. package/dist/op/op-waves-evidence-spec.d.ts +13 -0
  95. package/dist/op/op-waves-evidence-spec.d.ts.map +1 -0
  96. package/dist/op/op-waves-evidence-spec.js +21 -0
  97. package/dist/op/op-waves-evidence.d.ts +38 -0
  98. package/dist/op/op-waves-evidence.d.ts.map +1 -0
  99. package/dist/op/op-waves-evidence.js +57 -0
  100. package/dist/op/op-waves-run.d.ts +4 -0
  101. package/dist/op/op-waves-run.d.ts.map +1 -1
  102. package/dist/op/op-waves-run.js +24 -1
  103. package/dist/op/op-waves.d.ts +17 -1
  104. package/dist/op/op-waves.d.ts.map +1 -1
  105. package/dist/op/op-waves.js +23 -0
  106. package/dist/op/schedule-overdue.d.ts +41 -9
  107. package/dist/op/schedule-overdue.d.ts.map +1 -1
  108. package/dist/op/schedule-overdue.js +154 -25
  109. package/dist/plan-summary.d.ts +25 -0
  110. package/dist/plan-summary.d.ts.map +1 -1
  111. package/dist/plan-summary.js +31 -0
  112. package/dist/pr-plan-note.d.ts +35 -0
  113. package/dist/pr-plan-note.d.ts.map +1 -1
  114. package/dist/pr-plan-note.js +10 -0
  115. package/dist/pr-post.d.ts +23 -0
  116. package/dist/pr-post.d.ts.map +1 -1
  117. package/dist/pr-post.js +125 -3
  118. package/dist/release-floors.d.ts +31 -1
  119. package/dist/release-floors.d.ts.map +1 -1
  120. package/dist/release-floors.js +31 -1
  121. package/dist/state-migration.d.ts +24 -0
  122. package/dist/state-migration.d.ts.map +1 -1
  123. package/dist/state-migration.js +100 -5
  124. package/dist/wave-runtime.mjs +305 -298
  125. package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
  126. package/dist/workspace/lexicon-outputs.js +21 -7
  127. package/dist/workspace/reason-codes.d.ts +3 -0
  128. package/dist/workspace/reason-codes.d.ts.map +1 -1
  129. package/dist/workspace/reason-codes.js +4 -0
  130. package/dist/workspace/ref-gate.schema.json +85 -0
  131. package/dist/workspace/search-contract.d.ts +1 -1
  132. package/dist/workspace/search-contract.d.ts.map +1 -1
  133. package/dist/workspace/trust/check-evidence-report.d.ts +51 -0
  134. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
  135. package/dist/workspace/trust/check-evidence-report.js +102 -0
  136. package/dist/workspace/trust/check-evidence.d.ts +126 -0
  137. package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
  138. package/dist/workspace/trust/check-evidence.js +237 -0
  139. package/dist/workspace/trust/local-evidence.d.ts +120 -0
  140. package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
  141. package/dist/workspace/trust/local-evidence.js +259 -0
  142. package/dist/workspace/trust/policy.d.ts +84 -0
  143. package/dist/workspace/trust/policy.d.ts.map +1 -1
  144. package/dist/workspace/trust/policy.js +94 -1
  145. package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
  146. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
  147. package/dist/workspace/trust/ref-gate-cli.js +234 -0
  148. package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
  149. package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
  150. package/dist/workspace/trust/ref-gate-fixture.js +97 -0
  151. package/dist/workspace/trust/ref-gate.d.ts +187 -0
  152. package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
  153. package/dist/workspace/trust/ref-gate.js +430 -0
  154. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  155. package/dist/workspace/trust/trust-files.js +18 -1
  156. package/package.json +1 -1
  157. package/src/bundle-check.test.ts +140 -0
  158. package/src/bundle-check.ts +352 -0
  159. package/src/chant-install.test.ts +112 -0
  160. package/src/chant-install.ts +179 -0
  161. package/src/ci-commit.test.ts +45 -0
  162. package/src/ci-commit.ts +38 -4
  163. package/src/ci-evidence-jobs.ts +67 -0
  164. package/src/ci-image.test.ts +506 -0
  165. package/src/ci-image.ts +822 -0
  166. package/src/ci-login.test.ts +235 -0
  167. package/src/ci-login.ts +307 -0
  168. package/src/ci-product.ts +18 -0
  169. package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
  170. package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
  171. package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
  172. package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
  173. package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
  174. package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
  175. package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
  176. package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
  177. package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
  178. package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
  179. package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
  180. package/src/cli/commands/import-index.ts +2 -2
  181. package/src/cli/handlers/build-source-dir.test.ts +64 -0
  182. package/src/cli/handlers/build.ts +21 -4
  183. package/src/cli/handlers/ci-check.ts +56 -3
  184. package/src/cli/handlers/ci-evidence.ts +162 -0
  185. package/src/cli/handlers/components.ts +3 -3
  186. package/src/cli/handlers/dead-guards.ts +37 -0
  187. package/src/cli/handlers/graph.ts +4 -4
  188. package/src/cli/handlers/lifecycle.ts +5 -4
  189. package/src/cli/handlers/local-chant.ts +106 -0
  190. package/src/cli/handlers/operator.ts +2 -2
  191. package/src/cli/handlers/search.ts +5 -5
  192. package/src/cli/main.test.ts +7 -0
  193. package/src/cli/main.ts +38 -0
  194. package/src/cli/parse-args.ts +21 -0
  195. package/src/cli/registry.ts +16 -0
  196. package/src/components/check-evidence-stage.test.ts +80 -0
  197. package/src/components/check-hooks.ts +84 -4
  198. package/src/components/check-local-evidence-stage.test.ts +141 -0
  199. package/src/components/check-steps.ts +56 -6
  200. package/src/components/product-pipeline.ts +28 -3
  201. package/src/components/product-plan.test.ts +87 -0
  202. package/src/components/product-plan.ts +226 -0
  203. package/src/components/release-compile.ts +2 -2
  204. package/src/config.ts +44 -3
  205. package/src/dead-guards.test.ts +206 -0
  206. package/src/dead-guards.ts +446 -0
  207. package/src/discovery/files.ts +5 -3
  208. package/src/drift-issue-bundle.test.ts +31 -0
  209. package/src/drift-issue.test.ts +206 -0
  210. package/src/drift-issue.ts +274 -0
  211. package/src/fit-note.test.ts +44 -0
  212. package/src/floor-table.data.ts +180 -0
  213. package/src/floor-table.ts +77 -0
  214. package/src/forge-flags.test.ts +110 -0
  215. package/src/forge-flags.ts +208 -0
  216. package/src/gate-decision-bundle.test.ts +1 -0
  217. package/src/lexicon.ts +68 -0
  218. package/src/lifecycle/gated-op.ts +10 -5
  219. package/src/local-chant.e2e.test.ts +94 -0
  220. package/src/local-chant.test.ts +162 -0
  221. package/src/local-chant.ts +341 -0
  222. package/src/op/activities/predict-behaviour.ts +2 -2
  223. package/src/op/op-waves-evidence-spec.ts +24 -0
  224. package/src/op/op-waves-evidence.test.ts +130 -0
  225. package/src/op/op-waves-evidence.ts +57 -0
  226. package/src/op/op-waves-run.ts +25 -1
  227. package/src/op/op-waves.ts +31 -1
  228. package/src/op/schedule-overdue.test.ts +85 -0
  229. package/src/op/schedule-overdue.ts +162 -26
  230. package/src/plan-summary.ts +40 -0
  231. package/src/pr-plan-note.ts +34 -0
  232. package/src/pr-post-plan-note.test.ts +146 -0
  233. package/src/pr-post.ts +127 -3
  234. package/src/release-floors.ts +44 -1
  235. package/src/stage-hooks-bundle.test.ts +1 -0
  236. package/src/state-migration.test.ts +52 -1
  237. package/src/state-migration.ts +107 -5
  238. package/src/workspace/lexicon-outputs.ts +23 -6
  239. package/src/workspace/reason-codes.test.ts +3 -0
  240. package/src/workspace/reason-codes.ts +4 -0
  241. package/src/workspace/ref-gate.schema.json +85 -0
  242. package/src/workspace/trust/check-evidence-report.ts +106 -0
  243. package/src/workspace/trust/check-evidence.test.ts +133 -0
  244. package/src/workspace/trust/check-evidence.ts +257 -0
  245. package/src/workspace/trust/local-evidence.test.ts +127 -0
  246. package/src/workspace/trust/local-evidence.ts +266 -0
  247. package/src/workspace/trust/policy.ts +134 -1
  248. package/src/workspace/trust/ref-gate-cli.ts +244 -0
  249. package/src/workspace/trust/ref-gate-fixture.ts +125 -0
  250. package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
  251. package/src/workspace/trust/ref-gate.test.ts +247 -0
  252. package/src/workspace/trust/ref-gate.ts +538 -0
  253. package/src/workspace/trust/trust-files.test.ts +16 -0
  254. package/src/workspace/trust/trust-files.ts +41 -1
@@ -0,0 +1,430 @@
1
+ /**
2
+ * The ref gate (#4867): a ref update is refused when the commit lacks the
3
+ * runner evidence the policy at base requires for that ref.
4
+ *
5
+ * chant judges evidence at the green tick, a land, a gate and a release cut,
6
+ * all after the push. A change that was never going to pass still reached
7
+ * the remote and started CI. The gate judges it at the ref update instead,
8
+ * from three places that all call {@link decideRefUpdate}:
9
+ *
10
+ * - a plain git remote: the `pre-receive` hook `chant workspace ref-gate
11
+ * install` writes, which refuses the push;
12
+ * - a forge: `chant workspace ref-gate status`, a commit status the forge
13
+ * requires, so the merge is refused where the push can't be;
14
+ * - the developer's side: the `pre-push` hook, which refuses before the
15
+ * network and records the request for an override.
16
+ *
17
+ * The rules are `refs` in `.chant/trust.json`, read at base like every other
18
+ * part of the trust policy (./policy.ts): the old tip of the ref, so a change
19
+ * can neither drop a check nor add the runner key that signs its own
20
+ * evidence. Evidence is the runner evidence of ./evidence.ts, kept as git
21
+ * notes on the commit under {@link EVIDENCE_NOTES_REF}, one envelope per
22
+ * line, and verified offline against the runner keys at base. A check has
23
+ * current evidence when an envelope for it verifies and every record it
24
+ * names hashes the same at the pushed commit; an envelope that names no
25
+ * records counts only for a commit with the tree it was signed over.
26
+ *
27
+ * An override is the override gate's (../../override-gate.ts): a person
28
+ * the overriders file at base lists records a reasoned approval of one
29
+ * commit and one check, subject `ref-gate-<sha12>-<check>`, and it is spent
30
+ * by the first ref update it admits. Every decision is a line of the gate's
31
+ * ledger, a JSON-lines file in the git directory ({@link refGateLedgerPath}),
32
+ * since a pre-receive hook may not move a ref.
33
+ */
34
+ import { execFileSync, spawnSync } from "node:child_process";
35
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
36
+ import { dirname, isAbsolute, join } from "node:path";
37
+ import { verifyEvidence } from "./evidence.js";
38
+ import { policyAtBase } from "./provenance.js";
39
+ import { OVERRIDE_APPLIED, OVERRIDE_LEDGER, OVERRIDERS_PATH, decideOverride, overrideCommand, overridersAt, parseAppliedOverrides, } from "../../override-gate.js";
40
+ import { parseGateLedger } from "../../lifecycle/gate-ledger.js";
41
+ import { gateSignersAt } from "../../gate-decision.js";
42
+ /** Where runner evidence for a commit is kept (#4867): a git note on the commit, one DSSE envelope per line. */
43
+ export const EVIDENCE_NOTES_REF = "refs/notes/chant/evidence";
44
+ /** The ledger branch whose override lines the gate reads. */
45
+ export const LIFECYCLE_REF = "refs/heads/chant/lifecycle";
46
+ /** The commit status a forge requires when the rule names none. */
47
+ export const REF_GATE_STATUS = "chant/ref-gate";
48
+ /** git's id for no object, in hook input. */
49
+ const ZERO = /^0+$/;
50
+ /** Why the gate cannot decide at all. Each is in `reason-codes.ts` and `ref-gate.schema.json`. */
51
+ export const REF_GATE_ERROR_CODES = ["not-a-git-repository", "revision-unknown", "trust-policy-unreadable", "ref-update-invalid"];
52
+ /** Why a required check has no current evidence. The envelope codes are those of `evidence verify`. */
53
+ export const REF_GATE_CHECK_CODES = [
54
+ "ref-evidence-missing",
55
+ "ref-evidence-stale",
56
+ "envelope-invalid",
57
+ "envelope-untrusted",
58
+ "evidence-payload-type",
59
+ "evidence-statement-invalid",
60
+ "evidence-runner-mismatch",
61
+ ];
62
+ function git(repo, args) {
63
+ return execFileSync("git", args, { cwd: repo, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
64
+ }
65
+ function tryGit(repo, args) {
66
+ const r = spawnSync("git", args, { cwd: repo, encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 });
67
+ return r.status === 0 ? r.stdout : undefined;
68
+ }
69
+ /** The commit `rev` names, peeled, or undefined. */
70
+ export function commitOf(repo, rev) {
71
+ return tryGit(repo, ["rev-parse", "--verify", "-q", `${rev}^{commit}`])?.trim() || undefined;
72
+ }
73
+ /** A ref pattern as a RegExp: `**` matches across `/`, `*` within one segment. */
74
+ export function refPatternRegExp(pattern) {
75
+ const body = pattern
76
+ .split("**")
77
+ .map((part) => part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*"))
78
+ .join(".*");
79
+ return new RegExp(`^${body}$`);
80
+ }
81
+ /**
82
+ * The checks the policy requires for `ref`: every matching rule's, each check
83
+ * once. A check two rules name is `block` when either blocks it; the first
84
+ * rule that names a status or an override mode gives it.
85
+ */
86
+ export function rulesFor(policy, ref) {
87
+ const matching = (policy.refs ?? []).filter((r) => refPatternRegExp(r.ref).test(ref));
88
+ const checks = new Map();
89
+ for (const r of matching) {
90
+ for (const c of r.checks) {
91
+ const before = checks.get(c.check);
92
+ if (!before)
93
+ checks.set(c.check, { ...c });
94
+ else if (c.action === "block")
95
+ before.action = "block";
96
+ }
97
+ }
98
+ const overrides = matching.find((r) => r.overrides)?.overrides;
99
+ return {
100
+ matched: matching.length > 0,
101
+ checks: [...checks.values()],
102
+ status: matching.find((r) => r.status)?.status ?? REF_GATE_STATUS,
103
+ ...(overrides ? { overrides } : {}),
104
+ };
105
+ }
106
+ // ── evidence notes ───────────────────────────────────────────────────────
107
+ /** The envelopes in a note's text: one per line, or the whole note as one envelope or an array of them. */
108
+ export function parseEvidenceNote(text) {
109
+ try {
110
+ const whole = JSON.parse(text);
111
+ return Array.isArray(whole) ? whole : [whole];
112
+ }
113
+ catch {
114
+ const out = [];
115
+ for (const line of text.split("\n").map((l) => l.trim()).filter(Boolean)) {
116
+ try {
117
+ out.push(JSON.parse(line));
118
+ }
119
+ catch {
120
+ out.push(line);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ }
126
+ /** The note on `commit` in the notes commit `notes`, which may fan its paths out. */
127
+ function noteText(repo, notes, commit) {
128
+ const list = tryGit(repo, ["ls-tree", "-r", "--full-tree", notes]);
129
+ if (!list)
130
+ return undefined;
131
+ for (const line of list.split("\n")) {
132
+ const tab = line.indexOf("\t");
133
+ if (tab < 0)
134
+ continue;
135
+ if (line.slice(tab + 1).replace(/\//g, "") !== commit)
136
+ continue;
137
+ const blob = line.slice(0, tab).split(" ")[2];
138
+ return tryGit(repo, ["cat-file", "blob", blob]);
139
+ }
140
+ return undefined;
141
+ }
142
+ /** The envelopes attached to `commit`, read from the notes commit `notes` (default: {@link EVIDENCE_NOTES_REF}'s tip). */
143
+ export function evidenceFor(repo, commit, notes) {
144
+ const tip = notes === undefined ? commitOf(repo, EVIDENCE_NOTES_REF) : notes;
145
+ if (!tip)
146
+ return [];
147
+ const text = noteText(repo, tip, commit);
148
+ return text === undefined ? [] : parseEvidenceNote(text);
149
+ }
150
+ /**
151
+ * Attach `envelope` to `commit` as one line of its evidence note. Pushing `refs/notes/chant/evidence` is the caller's.
152
+ * `notesRef` is another notes ref, for local evidence (#4868), which the ref gate never reads.
153
+ */
154
+ export function attachEvidence(repo, commit, envelope, notesRef = EVIDENCE_NOTES_REF) {
155
+ git(repo, [...notesIdentity(repo), "notes", `--ref=${notesRef}`, "append", "-m", JSON.stringify(envelope), commit]);
156
+ }
157
+ /**
158
+ * A notes commit needs an author and a committer, and a CI job often has no
159
+ * git identity configured, so `git notes append` failed there ("Author
160
+ * identity unknown"). Where the repository names none, the evidence notes
161
+ * are written as chant's. The envelope's signature, not the notes commit's
162
+ * author, says who signed the evidence.
163
+ */
164
+ function notesIdentity(repo) {
165
+ const named = (key) => !!tryGit(repo, ["config", "--get", key])?.trim();
166
+ return [
167
+ ...(named("user.name") || process.env.GIT_AUTHOR_NAME ? [] : ["-c", "user.name=chant evidence"]),
168
+ ...(named("user.email") || process.env.GIT_AUTHOR_EMAIL ? [] : ["-c", "user.email=chant-evidence@localhost"]),
169
+ ];
170
+ }
171
+ /** The check an envelope claims to be for, read without verifying, so a refusal can say which check a bad envelope was meant for. */
172
+ function claimedCheck(envelope) {
173
+ try {
174
+ const payload = envelope.payload;
175
+ if (typeof payload !== "string")
176
+ return undefined;
177
+ const check = JSON.parse(Buffer.from(payload, "base64").toString("utf8")).predicate?.check;
178
+ return typeof check === "string" ? check : undefined;
179
+ }
180
+ catch {
181
+ return undefined;
182
+ }
183
+ }
184
+ /** The best evidence among `envelopes` for `check` at `commit`: current beats stale beats an envelope that does not verify beats none. */
185
+ function judgeCheck(repo, policy, envelopes, check, commit, tree) {
186
+ let stale;
187
+ let bad;
188
+ for (const env of envelopes) {
189
+ const v = verifyEvidence(env, policy.runners, repo, commit);
190
+ if (!v.ok) {
191
+ if (claimedCheck(env) === check && !bad)
192
+ bad = { code: v.code, reason: v.reason };
193
+ continue;
194
+ }
195
+ if (v.statement.predicate.check !== check)
196
+ continue;
197
+ const signedAt = v.statement.predicate.commit.slice(0, 8);
198
+ if (v.subjects.length === 0 && v.statement.predicate.tree !== tree) {
199
+ stale ?? (stale = `the evidence from ${v.runner} names no records and was signed over another tree, at ${signedAt}`);
200
+ continue;
201
+ }
202
+ if (v.status === "current")
203
+ return { status: "current", runner: v.runner };
204
+ const changed = v.subjects.filter((s) => !s.matches).map((s) => (s.now === null ? `${s.name} is gone` : `${s.name} changed`));
205
+ stale ?? (stale = `the evidence from ${v.runner} was signed at ${signedAt}, and since then ${changed.join(", ")}`);
206
+ }
207
+ if (stale)
208
+ return { status: "stale", code: "ref-evidence-stale", reason: stale };
209
+ if (bad)
210
+ return { status: "missing", code: bad.code, reason: `an envelope for ${check} does not count: ${bad.reason}` };
211
+ return { status: "missing", code: "ref-evidence-missing", reason: `no evidence for ${check} is attached to ${commit.slice(0, 8)} under ${EVIDENCE_NOTES_REF}` };
212
+ }
213
+ // ── overrides ────────────────────────────────────────────────────────────
214
+ /** The subject an override of `check` for `commit` names. */
215
+ export function refGateSubject(commit, check) {
216
+ return `ref-gate-${commit.slice(0, 12)}-${check}`;
217
+ }
218
+ function blobAt(repo, rev, path) {
219
+ return tryGit(repo, ["cat-file", "blob", `${rev}:${path}`]);
220
+ }
221
+ /** Decide one ref update against the policy at base. Never throws for a policy or an envelope it can't read: it refuses. */
222
+ export function decideRefUpdate(input) {
223
+ const { repo, update } = input;
224
+ const head = { ref: update.ref, old: update.old, new: update.new, base: input.base };
225
+ const refuse = (code, message) => ({ ...head, decision: "refuse", status: null, checks: [], error: { code, message } });
226
+ if (input.base === null)
227
+ return { ...head, decision: "admit", status: null, checks: [] };
228
+ const policy = policyAtBase(repo, { commit: input.base, from: "flag" });
229
+ if (policy.problems.length > 0)
230
+ return refuse("trust-policy-unreadable", `the policy at base ${input.base.slice(0, 8)} cannot be read, so the gate refuses every update: ${policy.problems.join("; ")}`);
231
+ const rules = rulesFor(policy, update.ref);
232
+ if (!rules.matched)
233
+ return { ...head, decision: "admit", status: null, checks: [] };
234
+ // A deletion carries no commit to judge; a forge or the remote protects deletions on its own.
235
+ if (update.new === null)
236
+ return { ...head, decision: "admit", status: rules.status, checks: [] };
237
+ const commit = commitOf(repo, update.new);
238
+ if (!commit)
239
+ return refuse("revision-unknown", `${update.new} is not a commit this repository holds`);
240
+ const tree = git(repo, ["rev-parse", `${commit}^{tree}`]).trim();
241
+ const envelopes = evidenceFor(repo, commit, input.notes);
242
+ const lifecycle = input.lifecycle === undefined ? commitOf(repo, LIFECYCLE_REF) : input.lifecycle;
243
+ const ledgerText = lifecycle ? blobAt(repo, lifecycle, OVERRIDE_LEDGER) : undefined;
244
+ const appliedText = lifecycle ? blobAt(repo, lifecycle, OVERRIDE_APPLIED) : undefined;
245
+ const ledger = ledgerText ? parseGateLedger(ledgerText) : { resolutions: [], pending: [] };
246
+ const applied = [...(appliedText ? parseAppliedOverrides(appliedText) : []), ...(input.spent ?? [])];
247
+ const overriders = overridersAt(repo, input.base);
248
+ const mode = rules.overrides ?? (policy.active ? "sealed" : "ledger");
249
+ let signers;
250
+ const checks = rules.checks.map((c) => {
251
+ const subject = refGateSubject(commit, c.check);
252
+ const judged = judgeCheck(repo, policy, envelopes, c.check, commit, tree);
253
+ const base = { check: c.check, action: c.action, command: c.command, subject };
254
+ if (judged.status === "current")
255
+ return { ...base, status: "current", reason: `current evidence from ${judged.runner}`, runner: judged.runner };
256
+ if (c.action === "block") {
257
+ if (mode === "sealed" && !signers)
258
+ signers = gateSignersAt(repo, input.base);
259
+ const verdict = decideOverride({
260
+ ledger,
261
+ applied,
262
+ subject,
263
+ planDigest: commit,
264
+ rules: [c.check],
265
+ overriders: overriders.principals,
266
+ overridersPath: OVERRIDERS_PATH,
267
+ mode,
268
+ ...(signers ? { signers } : {}),
269
+ ...(input.now ? { now: input.now } : {}),
270
+ });
271
+ if (verdict.status === "overridden") {
272
+ const o = verdict.override;
273
+ return { ...base, status: "overridden", code: judged.code, reason: `${judged.reason}; let through under ${o.by}'s override: ${o.reason}`, override: { subject, by: o.by, at: o.at, reason: o.reason, digest: o.digest } };
274
+ }
275
+ const why = verdict.refusals.length ? `; ${verdict.refusals.join("; ")}` : "";
276
+ return { ...base, status: judged.status, code: judged.code, reason: `${judged.reason}${why}` };
277
+ }
278
+ return { ...base, status: judged.status, code: judged.code, reason: judged.reason };
279
+ });
280
+ const refused = checks.some((c) => c.action === "block" && (c.status === "missing" || c.status === "stale"));
281
+ return { ...head, decision: refused ? "refuse" : "admit", status: rules.status, checks };
282
+ }
283
+ /** The gate's ledger file in the git directory of `repo`, `<git dir>/chant/ref-gate.jsonl`. */
284
+ export function refGateLedgerPath(repo) {
285
+ const dir = git(repo, ["rev-parse", "--git-common-dir"]).trim();
286
+ return join(isAbsolute(dir) ? dir : join(repo, dir), "chant", "ref-gate.jsonl");
287
+ }
288
+ export function appendRefGateLedger(path, lines) {
289
+ if (lines.length === 0)
290
+ return;
291
+ mkdirSync(dirname(path), { recursive: true });
292
+ appendFileSync(path, lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
293
+ }
294
+ export function readRefGateLedger(path) {
295
+ if (!existsSync(path))
296
+ return [];
297
+ const out = [];
298
+ for (const line of readFileSync(path, "utf-8").split("\n").filter((l) => l.trim())) {
299
+ try {
300
+ const r = JSON.parse(line);
301
+ if (r.version === 1 && r.kind === "ref-update")
302
+ out.push(r);
303
+ }
304
+ catch {
305
+ continue;
306
+ }
307
+ }
308
+ return out;
309
+ }
310
+ /** The overrides the ledger's admitted updates spent: an update the remote took, or a status that passed, under an override. A pre-push or a plain check spends nothing. */
311
+ export function spentOverrides(lines) {
312
+ const out = [];
313
+ for (const l of lines) {
314
+ if (l.decision !== "admit" || l.push === "refused" || (l.site !== "pre-receive" && l.site !== "status"))
315
+ continue;
316
+ for (const c of l.checks) {
317
+ if (!c.override)
318
+ continue;
319
+ out.push({ version: 1, kind: "applied", op: "policy-override", gate: c.override.subject, planDigest: c.override.digest, approvedAt: c.override.at, approvedBy: c.override.by, timestamp: l.timestamp, ...(l.new ? { commit: l.new } : {}) });
320
+ }
321
+ }
322
+ return out;
323
+ }
324
+ // ── hook input ───────────────────────────────────────────────────────────
325
+ const OBJECT_ID = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
326
+ const oid = (s) => (ZERO.test(s) ? null : s);
327
+ /** pre-receive's stdin: `<old> <new> <ref>` per line. */
328
+ export function parsePreReceive(text) {
329
+ return text
330
+ .split("\n")
331
+ .map((l) => l.trim())
332
+ .filter(Boolean)
333
+ .map((line) => {
334
+ const [old, nu, ref, ...rest] = line.split(/\s+/);
335
+ if (rest.length || !old || !nu || !ref || !OBJECT_ID.test(old) || !OBJECT_ID.test(nu))
336
+ throw new RefUpdateInputError(`not a pre-receive line: ${JSON.stringify(line)}`);
337
+ return { ref, old: oid(old), new: oid(nu) };
338
+ });
339
+ }
340
+ /** pre-push's stdin: `<local ref> <local sha> <remote ref> <remote sha>` per line, as updates of the remote ref. */
341
+ export function parsePrePush(text) {
342
+ return text
343
+ .split("\n")
344
+ .map((l) => l.trim())
345
+ .filter(Boolean)
346
+ .map((line) => {
347
+ const [, local, ref, remote, ...rest] = line.split(/\s+/);
348
+ if (rest.length || !local || !ref || !remote || !OBJECT_ID.test(local) || !OBJECT_ID.test(remote))
349
+ throw new RefUpdateInputError(`not a pre-push line: ${JSON.stringify(line)}`);
350
+ return { ref, old: oid(remote), new: oid(local) };
351
+ });
352
+ }
353
+ export class RefUpdateInputError extends Error {
354
+ }
355
+ /**
356
+ * The remote's pre-receive hook: decide every update of the push, with the
357
+ * notes and the `chant/lifecycle` tip the push itself brings when it brings
358
+ * them, and write one ledger line per update. git refuses the whole push when
359
+ * the hook fails, so overrides are spent only when every update is admitted.
360
+ */
361
+ export function runPreReceive(repo, stdin, opts = {}) {
362
+ const updates = parsePreReceive(stdin);
363
+ const pushed = (ref) => {
364
+ const u = updates.find((x) => x.ref === ref);
365
+ return u ? (u.new ? commitOf(repo, u.new) ?? null : null) : undefined;
366
+ };
367
+ const notes = pushed(EVIDENCE_NOTES_REF);
368
+ const lifecycle = pushed(LIFECYCLE_REF);
369
+ const ledger = opts.ledger ?? refGateLedgerPath(repo);
370
+ const spent = spentOverrides(readRefGateLedger(ledger));
371
+ const now = opts.now ?? new Date().toISOString();
372
+ const decisions = [];
373
+ for (const u of updates) {
374
+ const base = u.old ? commitOf(repo, u.old) ?? null : commitOf(repo, "HEAD") ?? null;
375
+ const d = decideRefUpdate({ repo, update: u, base, ...(notes !== undefined ? { notes } : {}), ...(lifecycle !== undefined ? { lifecycle } : {}), spent, now });
376
+ decisions.push(d);
377
+ // Two refs of one push may not spend one override twice.
378
+ spent.push(...spentOverrides([{ ...d, version: 1, kind: "ref-update", site: "pre-receive", timestamp: now }]));
379
+ }
380
+ const ok = decisions.every((d) => d.decision === "admit");
381
+ appendRefGateLedger(ledger, decisions.map((d) => ({ ...d, version: 1, kind: "ref-update", site: "pre-receive", timestamp: now, ...(ok ? {} : { push: "refused" }) })));
382
+ return { ok, decisions, ledger };
383
+ }
384
+ /**
385
+ * The developer's pre-push hook: the same decision against the local
386
+ * repository, before the network. The policy is read at the remote's tip
387
+ * when the repository holds it, else at the default base. It spends nothing.
388
+ */
389
+ export function runPrePush(repo, stdin, opts = {}) {
390
+ const updates = parsePrePush(stdin);
391
+ const ledger = opts.ledger ?? refGateLedgerPath(repo);
392
+ const now = opts.now ?? new Date().toISOString();
393
+ const decisions = updates.map((u) => {
394
+ const base = (u.old ? commitOf(repo, u.old) : undefined) ?? opts.base?.(repo) ?? null;
395
+ return decideRefUpdate({ repo, update: u, base, now });
396
+ });
397
+ appendRefGateLedger(ledger, decisions.map((d) => ({ ...d, version: 1, kind: "ref-update", site: "pre-push", timestamp: now })));
398
+ return { ok: decisions.every((d) => d.decision === "admit"), decisions, ledger };
399
+ }
400
+ // ── words ────────────────────────────────────────────────────────────────
401
+ const short = (s) => (s ? s.slice(0, 8) : "(none)");
402
+ /** What the gate says about one decision: each missing check and its command, and how to override a blocked one. */
403
+ export function describeDecision(d) {
404
+ const out = [];
405
+ const verb = d.decision === "admit" ? "admitted" : "refused";
406
+ out.push(`chant ref gate: ${verb} ${d.ref} ${short(d.old)}..${short(d.new)}`);
407
+ if (d.error) {
408
+ out.push(` ${d.error.message} (${d.error.code})`);
409
+ return out;
410
+ }
411
+ for (const c of d.checks) {
412
+ if (c.status === "current") {
413
+ out.push(` ${c.check}: ${c.reason}`);
414
+ continue;
415
+ }
416
+ const what = c.status === "overridden" ? "overridden" : c.action === "warn" ? "warning" : "missing";
417
+ out.push(` ${c.check} (${what}): ${c.reason}${c.code ? ` (${c.code})` : ""}`);
418
+ if (c.status !== "overridden")
419
+ out.push(` run: ${c.command}`);
420
+ }
421
+ const blocked = d.checks.filter((c) => c.action === "block" && (c.status === "missing" || c.status === "stale"));
422
+ if (blocked.length > 0) {
423
+ out.push(` Attach each check's evidence to ${short(d.new)} (chant workspace ref-gate attach --envelope <file> --at ${short(d.new)}) and push ${EVIDENCE_NOTES_REF} with the ref.`);
424
+ out.push(` To let ${short(d.new)} through without a check, a person listed in ${OVERRIDERS_PATH} at base can override it once the request is recorded`);
425
+ out.push(` (the pre-push hook records it, or chant workspace ref-gate check --ref ${d.ref} --at ${short(d.new)}):`);
426
+ for (const c of blocked)
427
+ out.push(` ${overrideCommand(c.subject, [c.check])}`);
428
+ }
429
+ return out;
430
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"trust-files.d.ts","sourceRoot":"","sources":["../../../src/workspace/trust/trust-files.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,0GAA0G;AAC1G,eAAO,MAAM,iBAAiB,sBAAsB,CAAC;AAErD,mEAAmE;AACnE,eAAO,MAAM,oBAAoB,2BAA2B,CAAC;AAe7D,uEAAuE;AACvE,MAAM,WAAW,MAAM;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,kGAAkG;IAClG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;CACd;AAED,4DAA4D;AAC5D,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,QAAQ,EAAE,cAAc,EAAE,CAAC;CAC5B;AAmDD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAkD3D;AAED,8FAA8F;AAC9F,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAM9D;AASD,yEAAyE;AACzE,wBAAgB,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,MAAM,CAElD;AAOD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,EAAE,CA4D1D"}
1
+ {"version":3,"file":"trust-files.d.ts","sourceRoot":"","sources":["../../../src/workspace/trust/trust-files.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,0GAA0G;AAC1G,eAAO,MAAM,iBAAiB,sBAAsB,CAAC;AAErD,mEAAmE;AACnE,eAAO,MAAM,oBAAoB,2BAA2B,CAAC;AAe7D,uEAAuE;AACvE,MAAM,WAAW,MAAM;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,kGAAkG;IAClG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;CACd;AAED,4DAA4D;AAC5D,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,QAAQ,EAAE,cAAc,EAAE,CAAC;CAC5B;AAmDD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAkD3D;AAED,8FAA8F;AAC9F,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAM9D;AASD,yEAAyE;AACzE,wBAAgB,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,MAAM,CAElD;AAOD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,EAAE,CAoG1D"}
@@ -175,7 +175,7 @@ export function trustConfigProblems(raw) {
175
175
  if (!ok)
176
176
  problems.push(`${field}: ${message}`);
177
177
  };
178
- check("/", only(raw, ["schema", "signers", "roles", "adopted", "runners", "passkeys", "admitted"]), "unknown key");
178
+ check("/", only(raw, ["schema", "signers", "roles", "adopted", "runners", "passkeys", "admitted", "refs", "local"]), "unknown key");
179
179
  check("schema", raw.schema === 1, "expected 1");
180
180
  check("signers", optional(raw.signers, isRepoPath), "a path inside the repository, with / separators and no ..");
181
181
  check("roles", optional(raw.roles, (r) => isObject(r) && Object.entries(r).every(([k, v]) => /^[a-z][a-z0-9-]*$/.test(k) && Array.isArray(v) && v.every(nonEmpty))), "role names to lists of principals");
@@ -194,5 +194,22 @@ export function trustConfigProblems(raw) {
194
194
  optional(e.note, (n) => typeof n === "string") &&
195
195
  Array.isArray(e.signers) && e.signers.length > 0 &&
196
196
  e.signers.every((s) => isObject(s) && only(s, ["principal", "key"]) && nonEmpty(s.principal) && typeof s.key === "string" && SSH_KEY.test(s.key)))), "admitted signers, by return id");
197
+ check("refs", optional(raw.refs, (a) => Array.isArray(a) &&
198
+ a.every((e) => isObject(e) && only(e, ["ref", "checks", "status", "overrides"]) &&
199
+ typeof e.ref === "string" && /^refs\/[^\s\\]+$/.test(e.ref) &&
200
+ optional(e.status, nonEmpty) && optional(e.overrides, (o) => o === "ledger" || o === "sealed") &&
201
+ Array.isArray(e.checks) && e.checks.length > 0 &&
202
+ e.checks.every((c) => isObject(c) && only(c, ["check", "action", "command"]) &&
203
+ typeof c.check === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(c.check) &&
204
+ optional(c.action, (x) => x === "block" || x === "warn") && nonEmpty(c.command)))), "ref rules: a ref pattern and the checks it requires, each with a command");
205
+ // #4868: keep in step with LOCAL_EVIDENCE_NEVER in ./policy.ts.
206
+ const never = ["plan", "policy", "apply", "drift", "release", "gate", "approval", "confirm"];
207
+ check("local", optional(raw.local, (l) => isObject(l) && only(l, ["keys", "checks"]) &&
208
+ optional(l.keys, (a) => Array.isArray(a) && a.every((e) => isObject(e) && only(e, ["principal", "class", "key"]) && nonEmpty(e.principal) && (e.class === "person" || e.class === "agent") && typeof e.key === "string" && SSH_ED25519.test(e.key))) &&
209
+ optional(l.checks, (a) => Array.isArray(a) &&
210
+ a.every((c) => isObject(c) && only(c, ["check", "from"]) &&
211
+ typeof c.check === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(c.check) &&
212
+ !never.some((n) => c.check === n || c.check.startsWith(`${n}:`)) &&
213
+ optional(c.from, (f) => Array.isArray(f) && f.length > 0 && f.every((x) => x === "person" || x === "agent"))))), "local evidence: person or agent keys, and the checks it stands in for (never plan, policy, apply, drift, release, gate, approval, confirm)");
197
214
  return problems;
198
215
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant",
3
- "version": "0.124.84",
3
+ "version": "0.124.86",
4
4
  "description": "Declarative infrastructure-as-code toolkit — TypeScript on Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -0,0 +1,140 @@
1
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { describe, expect, it } from "vitest";
5
+ import { bundleImports, checkBundle, chantExternalPlugin, chantRuntimeTarget, type BundleCheckConfig } from "./bundle-check";
6
+
7
+ /** #4787: a product checked by chant's bundle check instead of its own scripts/bundle-check.mjs. */
8
+
9
+ const write = (file: string, body: string | object) => {
10
+ mkdirSync(dirname(file), { recursive: true });
11
+ writeFileSync(file, typeof body === "string" ? body : JSON.stringify(body, null, 2));
12
+ };
13
+
14
+ /** A product with one workspace package, `packages/app`, and an installed chant 1.2.3. */
15
+ function product(opts: { bundle?: string; deps?: Record<string, string>; installed?: object; config?: Partial<BundleCheckConfig> } = {}) {
16
+ const root = mkdtempSync(join(tmpdir(), "chant-4787-bundle-"));
17
+ write(join(root, "package.json"), { name: "product", private: true, workspaces: ["packages/*"], devDependencies: { "@intentius/chant": "1.2.3" } });
18
+ const chant = join(root, "node_modules/@intentius/chant");
19
+ write(join(chant, "package.json"), {
20
+ name: "@intentius/chant",
21
+ version: "1.2.3",
22
+ exports: {
23
+ ".": { types: "./dist/index.d.ts", import: "./dist/index.js", default: "./src/index.ts" },
24
+ "./ts-only": { import: "./src/ts-only.ts" },
25
+ "./*": { import: "./dist/*.js", default: "./src/*.ts" },
26
+ },
27
+ ...opts.installed,
28
+ });
29
+ write(join(chant, "dist/index.js"), "export {};\n");
30
+ write(join(chant, "dist/notify.js"), "export {};\n");
31
+ write(join(chant, "src/ts-only.ts"), "export {};\n");
32
+ const app = join(root, "packages/app");
33
+ write(join(app, "package.json"), {
34
+ name: "@example/app",
35
+ version: "0.1.0",
36
+ dependencies: opts.deps ?? { "@intentius/chant": "1.2.3" },
37
+ chantBundleCheck: { bundle: "dist/app.mjs", ...opts.config },
38
+ });
39
+ write(join(app, "dist/app.mjs"), opts.bundle ?? 'import { readFileSync } from "node:fs";\nimport { a } from "@intentius/chant";\nconst n = await import("@intentius/chant/notify");\nimport("./local.mjs");\n');
40
+ return { root, app, config: { bundle: "dist/app.mjs", ...opts.config } as BundleCheckConfig };
41
+ }
42
+
43
+ describe("chantRuntimeTarget (#4787)", () => {
44
+ it("names the compiled file for a subpath the installed chant serves as JS", () => {
45
+ const { app, root } = product();
46
+ expect(chantRuntimeTarget("@intentius/chant", app)).toBe(join(root, "node_modules/@intentius/chant/dist/index.js"));
47
+ expect(chantRuntimeTarget("@intentius/chant/notify", app)).toBe(join(root, "node_modules/@intentius/chant/dist/notify.js"));
48
+ });
49
+
50
+ it("answers undefined for TypeScript, a missing file, another package, or no install", () => {
51
+ const { app } = product();
52
+ expect(chantRuntimeTarget("@intentius/chant/ts-only", app)).toBeUndefined();
53
+ expect(chantRuntimeTarget("@intentius/chant/absent", app)).toBeUndefined();
54
+ expect(chantRuntimeTarget("left-pad", app)).toBeUndefined();
55
+ expect(chantRuntimeTarget("@intentius/chant-lexicon-k8s", app)).toBeUndefined();
56
+ });
57
+
58
+ it("the esbuild plugin leaves only compiled chant imports external", () => {
59
+ const { app } = product();
60
+ const external = new Set<string>();
61
+ let cb: ((a: { path: string }) => unknown) | undefined;
62
+ chantExternalPlugin(app, external).setup({ onResolve: (_o, f) => { cb = f; } });
63
+ expect(cb!({ path: "@intentius/chant/notify" })).toEqual({ path: "@intentius/chant/notify", external: true });
64
+ expect(cb!({ path: "@intentius/chant/ts-only" })).toBeUndefined();
65
+ expect([...external]).toEqual(["@intentius/chant/notify"]);
66
+ });
67
+ });
68
+
69
+ describe("bundleImports (#4787)", () => {
70
+ it("reads static, dynamic and require imports and skips relative ones and junk strings", () => {
71
+ const text = 'import a from "x";export{b}from"y/z";import"side";const c=import("@s/p/q");require("node:fs");import("./rel.mjs");x="import \'not a spec\'"';
72
+ expect(bundleImports(text).sort()).toEqual(["@s/p/q", "node:fs", "side", "x", "y/z"]);
73
+ });
74
+ });
75
+
76
+ describe("checkBundle (#4787)", () => {
77
+ it("passes a bundle that imports Node and chant served as compiled JS, on the root's pin", () => {
78
+ const { app, config } = product();
79
+ const r = checkBundle(app, config);
80
+ expect(r.problems).toEqual([]);
81
+ expect(r.chantImports.sort()).toEqual(["@intentius/chant", "@intentius/chant/notify"]);
82
+ expect(r.summary).toContain("chant 1.2.3");
83
+ });
84
+
85
+ it("fails a chant import served only as TypeScript and an import of a package that is not a dependency", () => {
86
+ const { app, config } = product({ bundle: 'import "@intentius/chant/ts-only";\nimport "left-pad";\n' });
87
+ const r = checkBundle(app, config);
88
+ expect(r.ok).toBe(false);
89
+ expect(r.problems.join("\n")).toContain("'@intentius/chant/ts-only', which the installed package's exports do not serve as compiled JS");
90
+ expect(r.problems.join("\n")).toContain("'left-pad', which is neither a Node module nor a runtime dependency");
91
+ });
92
+
93
+ it("lets an optional package through", () => {
94
+ const { app, config } = product({ bundle: 'import "@intentius/chant";\nimport("@cdktn/hcl2json");\n', config: { optional: ["@cdktn/hcl2json"] } });
95
+ expect(checkBundle(app, config).problems).toEqual([]);
96
+ });
97
+
98
+ it("fails a dependency nothing loads, and takes one that needs names", () => {
99
+ const deps = { "@intentius/chant": "1.2.3", "@intentius/chant-lexicon-k8s": "1.2.3" };
100
+ const unused = product({ deps });
101
+ expect(checkBundle(unused.app, unused.config).problems).toContain("@intentius/chant-lexicon-k8s is a runtime dependency that the bundle does not import and chantBundleCheck.needs does not name");
102
+ const needed = product({ deps, config: { needs: ["@intentius/chant-lexicon-k8s", "@intentius/chant-lexicon-gitlab"] } });
103
+ const problems = checkBundle(needed.app, needed.config).problems;
104
+ expect(problems).toContain("@intentius/chant-lexicon-k8s is not installed; run npm ci");
105
+ expect(problems).toContain("@intentius/chant-lexicon-gitlab is loaded at run time (chantBundleCheck.needs names it) but is not in dependencies");
106
+ });
107
+
108
+ it("fails a chant dependency off the root's pin", () => {
109
+ const { app, config } = product({ deps: { "@intentius/chant": "^1.2.0" } });
110
+ expect(checkBundle(app, config).problems).toContain("@intentius/chant is '^1.2.0' in dependencies, not the root's chant pin 1.2.3");
111
+ });
112
+
113
+ it("fails an installed chant off the pin unless chant dev local marked it", () => {
114
+ const off = product({ installed: { version: "1.3.0" } });
115
+ expect(checkBundle(off.app, off.config).problems).toContain("the installed @intentius/chant is 1.3.0, not the pin 1.2.3; run npm ci");
116
+ const local = product({ installed: { version: "1.3.0", chantLocal: { commit: "abcdef0123456789", dir: "/x/chant" } } });
117
+ const r = checkBundle(local.app, local.config);
118
+ expect(r.problems).toEqual([]);
119
+ expect(r.chant).toBe("local chant 1.3.0 (abcdef012345)");
120
+ });
121
+
122
+ it("fails a bundle over its ceiling", () => {
123
+ const { app, config } = product({ config: { maxBytes: 10 } });
124
+ expect(checkBundle(app, config).problems.join("\n")).toMatch(/the bundle is \d+ KB, over the 0 KB ceiling/);
125
+ });
126
+
127
+ it("fails a denied metafile input, and a deny list without a metafile", () => {
128
+ const deny = [{ pattern: "^typescript/", what: "the TypeScript compiler" }];
129
+ const { app, config } = product({ config: { metafile: "meta.json", deny } });
130
+ write(join(app, "meta.json"), { inputs: { "src/a.ts": {}, "../../node_modules/typescript/lib/typescript.js": {} } });
131
+ expect(checkBundle(app, config).problems).toEqual(["the bundle includes the TypeScript compiler (1 inputs): typescript/lib/typescript.js"]);
132
+ const none = product({ config: { deny } });
133
+ expect(checkBundle(none.app, none.config).problems[0]).toContain("chantBundleCheck.deny needs the build's esbuild metafile");
134
+ });
135
+
136
+ it("fails a missing bundle", () => {
137
+ const { app } = product();
138
+ expect(checkBundle(app, { bundle: "dist/none.mjs" }).problems).toContain("no bundle at dist/none.mjs; build it first");
139
+ });
140
+ });