@intentius/behold 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ import {
2
+ ChantConfigSchema,
3
+ DEFAULT_CHANT_CONFIG,
4
+ EXECUTOR_FORGES,
5
+ InvalidChantConfigError,
6
+ ROOT_SOURCE_EXCLUDES,
7
+ configuredSourceDir,
8
+ environmentEndpoint,
9
+ environmentExecutor,
10
+ environmentName,
11
+ environmentNames,
12
+ findProjectConfigPastFragments,
13
+ isEnvironmentPattern,
14
+ isLintOnlyFragment,
15
+ isOwnershipParamRef,
16
+ loadChantConfig,
17
+ loadChantConfigUpward,
18
+ matchesDeclaredEnvironment,
19
+ matchesEnvironmentPattern,
20
+ ownershipEnvDisagreement,
21
+ resolveAutoReleaseDisabled,
22
+ resolveDiscoveryGlobs,
23
+ resolveFoldEnabled,
24
+ resolveKnowledgeDir,
25
+ resolveOwnershipEnv,
26
+ resolveOwnershipMarker,
27
+ resolveOwnershipStack,
28
+ resolveSandboxEnabled,
29
+ resolveSbomFormat,
30
+ resolveSigningDefaults,
31
+ resolveSourceDir,
32
+ resolveVulnPolicy
33
+ } from "./chunk-GMCRBXPQ.js";
34
+ import "./chunk-JJPU2DXX.js";
35
+ import "./chunk-JHLNY324.js";
36
+ import "./chunk-7DQDWJI5.js";
37
+ export {
38
+ ChantConfigSchema,
39
+ DEFAULT_CHANT_CONFIG,
40
+ EXECUTOR_FORGES,
41
+ InvalidChantConfigError,
42
+ ROOT_SOURCE_EXCLUDES,
43
+ configuredSourceDir,
44
+ environmentEndpoint,
45
+ environmentExecutor,
46
+ environmentName,
47
+ environmentNames,
48
+ findProjectConfigPastFragments,
49
+ isEnvironmentPattern,
50
+ isLintOnlyFragment,
51
+ isOwnershipParamRef,
52
+ loadChantConfig,
53
+ loadChantConfigUpward,
54
+ matchesDeclaredEnvironment,
55
+ matchesEnvironmentPattern,
56
+ ownershipEnvDisagreement,
57
+ resolveAutoReleaseDisabled,
58
+ resolveDiscoveryGlobs,
59
+ resolveFoldEnabled,
60
+ resolveKnowledgeDir,
61
+ resolveOwnershipEnv,
62
+ resolveOwnershipMarker,
63
+ resolveOwnershipStack,
64
+ resolveSandboxEnabled,
65
+ resolveSbomFormat,
66
+ resolveSigningDefaults,
67
+ resolveSourceDir,
68
+ resolveVulnPolicy
69
+ };
@@ -0,0 +1,418 @@
1
+ import "./chunk-GMCRBXPQ.js";
2
+ import "./chunk-JJPU2DXX.js";
3
+ import {
4
+ SOURCE_EXPORT_CONDITIONS,
5
+ chantModule,
6
+ chantPackageSourceTarget,
7
+ chantSourceDir,
8
+ importOptionalPeer
9
+ } from "./chunk-JHLNY324.js";
10
+ import "./chunk-7DQDWJI5.js";
11
+
12
+ // node_modules/@intentius/chant/dist/discovery/sandbox/config-run.js
13
+ import { realpathSync as realpathSync2, rmSync as rmSync2 } from "node:fs";
14
+ import { resolve } from "node:path";
15
+
16
+ // node_modules/@intentius/chant/dist/discovery/sandbox/bundle.js
17
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { createRequire } from "node:module";
19
+ import { tmpdir } from "node:os";
20
+ import { dirname, join, resolve as resolvePath } from "node:path";
21
+ var HERE = import.meta.dirname;
22
+ var require2 = createRequire(import.meta.url);
23
+ var EXTERNAL_PACKAGES = ["typescript", "@cdktn/hcl2json"];
24
+ function getExternalPackagePathCache() {
25
+ const g = globalThis;
26
+ return g.__chantExternalPackagePathCache ?? (g.__chantExternalPackagePathCache = /* @__PURE__ */ new Map());
27
+ }
28
+ function fastResolvePackage(specifier, fromDir) {
29
+ let dir = fromDir;
30
+ for (; ; ) {
31
+ const packageDir = join(dir, "node_modules", specifier);
32
+ if (existsSync(packageDir)) {
33
+ const pkgJsonPath = join(packageDir, "package.json");
34
+ if (!existsSync(pkgJsonPath))
35
+ return void 0;
36
+ let pkg;
37
+ try {
38
+ pkg = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
39
+ } catch {
40
+ return void 0;
41
+ }
42
+ if (typeof pkg !== "object" || pkg === null || pkg.exports !== void 0) {
43
+ return void 0;
44
+ }
45
+ const main = pkg.main;
46
+ const entry = typeof main === "string" ? main : "index.js";
47
+ const resolved = resolvePath(packageDir, entry);
48
+ if (!existsSync(resolved) || !statSync(resolved).isFile())
49
+ return void 0;
50
+ try {
51
+ return realpathSync(resolved);
52
+ } catch {
53
+ return void 0;
54
+ }
55
+ }
56
+ const parent = dirname(dir);
57
+ if (parent === dir)
58
+ return void 0;
59
+ dir = parent;
60
+ }
61
+ }
62
+ function externalTrustedPackagesPlugin() {
63
+ const readPaths = [];
64
+ const resolved = /* @__PURE__ */ new Map();
65
+ const pathCache = getExternalPackagePathCache();
66
+ for (const name of EXTERNAL_PACKAGES) {
67
+ try {
68
+ let path = pathCache.get(name);
69
+ if (path === void 0 && !pathCache.has(name)) {
70
+ path = fastResolvePackage(name, HERE) ?? require2.resolve(name, { paths: [HERE] });
71
+ pathCache.set(name, path);
72
+ }
73
+ if (path === void 0)
74
+ continue;
75
+ resolved.set(name, path);
76
+ readPaths.push(dirname(path));
77
+ } catch {
78
+ pathCache.set(name, void 0);
79
+ }
80
+ }
81
+ const plugin = {
82
+ name: "chant-sandbox-external-trusted-packages",
83
+ setup(build) {
84
+ for (const [name, path] of resolved) {
85
+ const filter = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`);
86
+ build.onResolve({ filter }, () => ({ path, external: true }));
87
+ }
88
+ }
89
+ };
90
+ return { plugin, readPaths };
91
+ }
92
+ function chantCoreSourcePlugin() {
93
+ return {
94
+ name: "chant-sandbox-core-source",
95
+ setup(build) {
96
+ build.onResolve({ filter: /^@intentius\/chant(?:\/.*)?$/ }, (args) => {
97
+ if (!args.importer)
98
+ return void 0;
99
+ const target = chantPackageSourceTarget(args.path, args.importer);
100
+ return target === void 0 ? void 0 : { path: target };
101
+ });
102
+ }
103
+ };
104
+ }
105
+ async function bundleDriver(driverSource) {
106
+ const bundleDir = realpathSync(mkdtempSync(join(tmpdir(), "chant-sandbox-")));
107
+ const entryPath = join(bundleDir, "driver.mts");
108
+ writeFileSync(entryPath, driverSource, "utf-8");
109
+ const outfile = join(bundleDir, "child.mjs");
110
+ const { plugin, readPaths } = externalTrustedPackagesPlugin();
111
+ let esbuildModule;
112
+ try {
113
+ esbuildModule = await importOptionalPeer("esbuild", "bundle a TypeScript project", () => import("./main-4PGA5RJS.js"));
114
+ } catch (err) {
115
+ rmSync(bundleDir, { recursive: true, force: true });
116
+ throw err;
117
+ }
118
+ const start = performance.now();
119
+ try {
120
+ await esbuildModule.build({
121
+ entryPoints: [entryPath],
122
+ outfile,
123
+ bundle: true,
124
+ platform: "node",
125
+ format: "esm",
126
+ absWorkingDir: bundleDir,
127
+ logLevel: "silent",
128
+ // #3981 — from source, a lexicon bundles from its src/*.ts, as the
129
+ // unsandboxed build imports it; compiled, from the dist/*.js it ships.
130
+ // Setting `conditions` replaces esbuild's default ["module"], so it is
131
+ // kept, and compiled the option is left out as before.
132
+ ...SOURCE_EXPORT_CONDITIONS.length > 0 ? { conditions: ["module", ...SOURCE_EXPORT_CONDITIONS] } : {},
133
+ plugins: [chantCoreSourcePlugin(), plugin]
134
+ });
135
+ } catch (err) {
136
+ rmSync(bundleDir, { recursive: true, force: true });
137
+ throw err;
138
+ }
139
+ const durationMs = performance.now() - start;
140
+ const bytes = statSync(outfile).size;
141
+ return { bundlePath: outfile, bundleDir, externalReadPaths: readPaths, durationMs, bytes };
142
+ }
143
+
144
+ // node_modules/@intentius/chant/dist/discovery/sandbox/driver.js
145
+ import { dirname as dirname2, join as join2 } from "node:path";
146
+ var HERE2 = chantSourceDir(import.meta.url);
147
+ var DISCOVERY_DIR = join2(HERE2, "..");
148
+ var COLLECT_MODULE = chantModule(join2(DISCOVERY_DIR, "collect.ts"));
149
+ var RESOLVE_MODULE = chantModule(join2(DISCOVERY_DIR, "resolve.ts"));
150
+ var ENTITY_WIRE_CODEC_MODULE = chantModule(join2(DISCOVERY_DIR, "entity-wire-codec.ts"));
151
+ var CHILD_ERRORS_MODULE = chantModule(join2(HERE2, "child-errors.ts"));
152
+ var PROVENANCE_MODULE = chantModule(join2(dirname2(DISCOVERY_DIR), "provenance.ts"));
153
+ var CONFIG_WIRE_MODULE = chantModule(join2(HERE2, "config-wire.ts"));
154
+ var POLICY_WIRE_MODULE = chantModule(join2(HERE2, "policy-wire.ts"));
155
+ var POST_SYNTH_MODULE = chantModule(join2(dirname2(DISCOVERY_DIR), "lint", "post-synth.ts"));
156
+ var PARAMS_MODULE = chantModule(join2(dirname2(DISCOVERY_DIR), "params.ts"));
157
+ var INTEROP_MODULE = chantModule(join2(dirname2(DISCOVERY_DIR), "module-interop.ts"));
158
+ function lit(value) {
159
+ return JSON.stringify(value);
160
+ }
161
+ function sendFunctionSource(before = []) {
162
+ return [
163
+ `function send(payload) {`,
164
+ ...before.map((line) => ` ${line}`),
165
+ ` if (typeof process.send !== "function") {`,
166
+ ` console.log(JSON.stringify(payload));`,
167
+ ` return Promise.resolve();`,
168
+ ` }`,
169
+ ` return new Promise((resolve) => {`,
170
+ ` const lost = (err) => {`,
171
+ ` writeSync(2, "chant: the sandboxed child could not hand its result to the parent: " +`,
172
+ ` (err && err.message ? err.message : String(err)) + " (chant#2461)\\n");`,
173
+ ` process.exit(1);`,
174
+ ` };`,
175
+ ` try {`,
176
+ ` process.send(payload, (err) => (err ? lost(err) : resolve()));`,
177
+ ` } catch (err) {`,
178
+ ` lost(err);`,
179
+ ` }`,
180
+ ` });`,
181
+ `}`
182
+ ];
183
+ }
184
+ function generateConfigDriverSource(configPath) {
185
+ return [
186
+ `import { classifyChildError } from ${lit(CHILD_ERRORS_MODULE)};`,
187
+ `import { scanConfigWireSafety } from ${lit(CONFIG_WIRE_MODULE)};`,
188
+ `import { esModuleNamespace } from ${lit(INTEROP_MODULE)};`,
189
+ `import { writeSync } from "node:fs";`,
190
+ ``,
191
+ ...sendFunctionSource(),
192
+ ``,
193
+ `async function main() {`,
194
+ ` let namespace;`,
195
+ ` try {`,
196
+ ` namespace = esModuleNamespace(await import(${lit(configPath)}));`,
197
+ ` } catch (err) {`,
198
+ ` await send({ kind: "chant-config", ok: false, error: classifyChildError(${lit(configPath)}, err).toJSON() });`,
199
+ ` return;`,
200
+ ` }`,
201
+ ``,
202
+ // Mirrors loadChantConfig's own selection so the scan sees exactly the
203
+ // object the parent will normalize. A namespace object is not a plain
204
+ // object; scanConfigWireSafety walks its own keys rather than rejecting it.
205
+ ` const selected = namespace.default ?? namespace.config ?? namespace;`,
206
+ ``,
207
+ ` const offenders = scanConfigWireSafety(selected);`,
208
+ ` if (offenders.length > 0) {`,
209
+ ` await send({ kind: "chant-config", ok: false, offenders });`,
210
+ ` return;`,
211
+ ` }`,
212
+ ``,
213
+ ` let config;`,
214
+ ` try {`,
215
+ // Round-trip here, not just at the IPC boundary: this is what proves the
216
+ // payload really is JSON before it leaves the child, and turns anything
217
+ // the scan somehow missed into a named error instead of a quiet drop.
218
+ ` config = JSON.parse(JSON.stringify(selected ?? {}));`,
219
+ ` } catch (err) {`,
220
+ ` await send({ kind: "chant-config", ok: false, error: classifyChildError(${lit(configPath)}, err, "resolution").toJSON() });`,
221
+ ` return;`,
222
+ ` }`,
223
+ ` await send({ kind: "chant-config", ok: true, config });`,
224
+ `}`,
225
+ ``,
226
+ `main().catch((err) =>`,
227
+ ` send({ kind: "chant-config", ok: false, error: classifyChildError(${lit(configPath)}, err).toJSON() }),`,
228
+ `);`
229
+ ].join("\n");
230
+ }
231
+
232
+ // node_modules/@intentius/chant/dist/discovery/sandbox/config-wire.js
233
+ function formatConfigWireOffenders(configPath, offenders) {
234
+ const lines = offenders.map((o) => ` ${o.path || "<root>"}: ${o.found}`);
235
+ return [
236
+ `Cannot evaluate ${configPath} inside the --sandbox boundary: it holds values that are not data.`,
237
+ ...lines,
238
+ `Under --sandbox the config is evaluated in an isolated child process and only JSON crosses back, so every value must be a string, number, boolean, null, array or plain object. Move the offending value out of chant.config.ts (lint rule plugins and policy checks are referenced by path, not embedded), or drop --sandbox for this build.`
239
+ ].join("\n");
240
+ }
241
+
242
+ // node_modules/@intentius/chant/dist/discovery/sandbox/fork.js
243
+ import { fork } from "node:child_process";
244
+ function lineBuffered(emit) {
245
+ let pending = "";
246
+ return {
247
+ push(chunk) {
248
+ pending += chunk.toString();
249
+ let newlineAt = pending.indexOf("\n");
250
+ while (newlineAt !== -1) {
251
+ emit(pending.slice(0, newlineAt));
252
+ pending = pending.slice(newlineAt + 1);
253
+ newlineAt = pending.indexOf("\n");
254
+ }
255
+ },
256
+ flush() {
257
+ if (pending.length > 0) {
258
+ emit(pending);
259
+ pending = "";
260
+ }
261
+ }
262
+ };
263
+ }
264
+ function describeSilentExit(label, code, signal, stderrBuf, unrecognised) {
265
+ const stderr = stderrBuf.trim();
266
+ const head = `${label}: child exited before reporting results (code ${code}, signal ${signal})`;
267
+ if (unrecognised.length > 0) {
268
+ const shapes = unrecognised.map((m) => m && typeof m === "object" ? `{${Object.keys(m).join(", ")}}` : typeof m).join(", ");
269
+ return `${head}. It sent ${unrecognised.length} message(s) the parent did not recognise (${shapes}), so the payload shape and the parent's check disagree` + (stderr ? `: ${stderr}` : "");
270
+ }
271
+ if (stderr)
272
+ return `${head}: ${stderr}`;
273
+ if (code !== 0 || signal !== null)
274
+ return head;
275
+ return `${head}. It exited cleanly with nothing on stderr, and no message arrived even after its IPC channel closed, so it never sent one: something it awaited never settled. On the run path the usual cause is a project file with a top-level \`await\` that does not settle. Module scope is arbitrary project source, an import of such a file never completes, and a promise that never settles is not a rejection, so the driver's own \`main().catch\` does not see it either. The config driver has nothing to await that can hang, and a failed send exits non-zero with a reason on stderr, so on the config path this has no known cause: please report it with the command that produced it (chant#2461).`;
276
+ }
277
+ var EXIT_DRAIN_GRACE_MS = 2e3;
278
+ function settleOnExitAfterChannelDrains(child, onExit, graceMs = EXIT_DRAIN_GRACE_MS) {
279
+ child.on("exit", (code, signal) => {
280
+ let done = false;
281
+ let grace;
282
+ const finish = () => {
283
+ if (done)
284
+ return;
285
+ done = true;
286
+ if (grace !== void 0)
287
+ clearTimeout(grace);
288
+ onExit(code, signal);
289
+ };
290
+ if (!child.connected) {
291
+ finish();
292
+ return;
293
+ }
294
+ child.once("disconnect", finish);
295
+ grace = setTimeout(finish, graceMs);
296
+ });
297
+ }
298
+ function forkSandboxed(options, isResponse) {
299
+ const { bundlePath, bundleDir, projectRealpath, externalReadPaths, env, timeoutMs, label, send, outputPrefix } = options;
300
+ return new Promise((resolvePromise, reject) => {
301
+ const readAllowances = [bundleDir, projectRealpath, ...externalReadPaths].map((p) => `--allow-fs-read=${p}`);
302
+ const child = fork(bundlePath, [], {
303
+ execArgv: ["--permission", ...readAllowances],
304
+ env,
305
+ stdio: ["ignore", "pipe", "pipe", "ipc"]
306
+ });
307
+ let settled = false;
308
+ let stderrBuf = "";
309
+ const unrecognised = [];
310
+ const timeout = setTimeout(() => {
311
+ if (settled)
312
+ return;
313
+ settled = true;
314
+ child.kill();
315
+ reject(new Error(`${label} timed out after ${timeoutMs}ms`));
316
+ }, timeoutMs);
317
+ if (send !== void 0) {
318
+ child.send(send, (err) => {
319
+ if (settled || !err)
320
+ return;
321
+ settled = true;
322
+ clearTimeout(timeout);
323
+ child.kill();
324
+ reject(new Error(`${label}: failed to send the child its input: ${err.message}`));
325
+ });
326
+ }
327
+ const forwardLine = (line) => {
328
+ process.stderr.write(`${outputPrefix} ${line}
329
+ `);
330
+ };
331
+ const stdoutForwarder = lineBuffered(forwardLine);
332
+ const stderrForwarder = lineBuffered(forwardLine);
333
+ child.stdout?.on("data", (chunk) => {
334
+ stdoutForwarder.push(chunk);
335
+ });
336
+ child.stdout?.on("end", () => stdoutForwarder.flush());
337
+ child.stderr?.on("data", (chunk) => {
338
+ stderrBuf += chunk.toString();
339
+ stderrForwarder.push(chunk);
340
+ });
341
+ child.stderr?.on("end", () => stderrForwarder.flush());
342
+ child.on("message", (msg) => {
343
+ if (settled)
344
+ return;
345
+ if (!isResponse(msg)) {
346
+ unrecognised.push(msg);
347
+ return;
348
+ }
349
+ settled = true;
350
+ clearTimeout(timeout);
351
+ child.kill();
352
+ resolvePromise(msg);
353
+ });
354
+ child.on("error", (err) => {
355
+ if (settled)
356
+ return;
357
+ settled = true;
358
+ clearTimeout(timeout);
359
+ reject(err);
360
+ });
361
+ settleOnExitAfterChannelDrains(child, (code, signal) => {
362
+ if (settled)
363
+ return;
364
+ settled = true;
365
+ clearTimeout(timeout);
366
+ reject(new Error(describeSilentExit(label, code, signal, stderrBuf, unrecognised)));
367
+ });
368
+ });
369
+ }
370
+
371
+ // node_modules/@intentius/chant/dist/env.js
372
+ var ENV_VAR = "CHANT_ENV";
373
+
374
+ // node_modules/@intentius/chant/dist/discovery/sandbox/config-run.js
375
+ var CONFIG_CHILD_TIMEOUT_MS = 6e4;
376
+ function isConfigChildResponse(value) {
377
+ return typeof value === "object" && value !== null && value.kind === "chant-config" && typeof value.ok === "boolean";
378
+ }
379
+ async function evaluateConfigSandboxed(configPath, projectRoot) {
380
+ const driverSource = generateConfigDriverSource(configPath);
381
+ const { bundlePath, bundleDir, externalReadPaths, durationMs, bytes } = await bundleDriver(driverSource);
382
+ try {
383
+ let projectRealpath;
384
+ try {
385
+ projectRealpath = realpathSync2(resolve(projectRoot));
386
+ } catch {
387
+ projectRealpath = resolve(projectRoot);
388
+ }
389
+ const env = { PATH: process.env.PATH ?? "" };
390
+ const activeEnv = process.env[ENV_VAR];
391
+ if (activeEnv)
392
+ env[ENV_VAR] = activeEnv;
393
+ const response = await forkSandboxed({
394
+ bundlePath,
395
+ bundleDir,
396
+ projectRealpath,
397
+ externalReadPaths,
398
+ env,
399
+ timeoutMs: CONFIG_CHILD_TIMEOUT_MS,
400
+ label: `sandboxed evaluation of ${configPath}`,
401
+ // chant #1148 — the config's own console.log/error no longer goes
402
+ // nowhere; see `./fork.ts`'s `outputPrefix` doc.
403
+ outputPrefix: "[sandbox:config]"
404
+ }, isConfigChildResponse);
405
+ if (!response.ok) {
406
+ if (response.offenders && response.offenders.length > 0) {
407
+ throw new Error(formatConfigWireOffenders(configPath, response.offenders));
408
+ }
409
+ throw new Error(response.error?.message ? `Failed to evaluate ${configPath} inside the --sandbox boundary: ${response.error.message}` : `Failed to evaluate ${configPath} inside the --sandbox boundary`);
410
+ }
411
+ return { config: response.config ?? {}, bundleMs: durationMs, bundleBytes: bytes };
412
+ } finally {
413
+ rmSync2(bundleDir, { recursive: true, force: true });
414
+ }
415
+ }
416
+ export {
417
+ evaluateConfigSandboxed
418
+ };