@powerhousedao/host-core 6.2.3-dev.70 → 6.2.3-dev.72
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/compound-B6RZMA0Y.mjs +2804 -0
- package/dist/compound-B6RZMA0Y.mjs.map +1 -0
- package/dist/compound-PhoVeqe1.d.mts +2401 -0
- package/dist/compound-PhoVeqe1.d.mts.map +1 -0
- package/dist/env-substitution-C_fVirPh.d.mts +17 -0
- package/dist/env-substitution-C_fVirPh.d.mts.map +1 -0
- package/dist/env-substitution-Dj3pdsut.mjs +330 -0
- package/dist/env-substitution-Dj3pdsut.mjs.map +1 -0
- package/dist/host-schemas-mqOYNGot.d.mts +2153 -0
- package/dist/host-schemas-mqOYNGot.d.mts.map +1 -0
- package/dist/index.d.mts +908 -691
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +335 -109
- package/dist/index.mjs.map +1 -1
- package/dist/plugins-XL6WsvTL.d.mts +182 -0
- package/dist/plugins-XL6WsvTL.d.mts.map +1 -0
- package/dist/plugins.d.mts +2 -120
- package/dist/plugins.mjs.map +1 -1
- package/dist/projection.d.mts +586 -0
- package/dist/projection.d.mts.map +1 -0
- package/dist/projection.mjs +1505 -0
- package/dist/projection.mjs.map +1 -0
- package/dist/runners/compound.d.mts +157 -12
- package/dist/runners/compound.d.mts.map +1 -1
- package/dist/runners/compound.mjs +5 -13
- package/dist/runners/compound.mjs.map +1 -1
- package/dist/schema.d.mts +105 -0
- package/dist/schema.d.mts.map +1 -0
- package/dist/schema.mjs +35 -0
- package/dist/schema.mjs.map +1 -0
- package/package.json +16 -4
- package/dist/compound-C8P0kvPJ.d.mts +0 -157
- package/dist/compound-C8P0kvPJ.d.mts.map +0 -1
- package/dist/host-schemas-CtPNRr5v.mjs +0 -720
- package/dist/host-schemas-CtPNRr5v.mjs.map +0 -1
- package/dist/plugins.d.mts.map +0 -1
|
@@ -0,0 +1,1505 @@
|
|
|
1
|
+
import { B as tokenSchema, E as TOKEN_ESCAPE_KEY, t as substituteBuiltinEnv, x as runnerKindSchema, z as tokenKeyOf } from "./env-substitution-Dj3pdsut.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region src/reactor-config.ts
|
|
4
|
+
/** The single primary backend for phase-2 projection (multi-backend routing is
|
|
5
|
+
* track R). Prefers placement.primary, else "main"/"local", else the first. */
|
|
6
|
+
function primaryBackend(reactor) {
|
|
7
|
+
const backends = reactor?.backends;
|
|
8
|
+
if (!backends) return void 0;
|
|
9
|
+
const names = Object.keys(backends);
|
|
10
|
+
if (names.length === 0) return void 0;
|
|
11
|
+
return backends[reactor.placement?.primary ?? (names.includes("main") ? "main" : names.includes("local") ? "local" : names[0])];
|
|
12
|
+
}
|
|
13
|
+
const FLAG_ENV = {
|
|
14
|
+
documentDecisions: "REACTOR_DOCUMENT_DECISIONS",
|
|
15
|
+
authEnforcement: "REACTOR_AUTH_ENFORCEMENT",
|
|
16
|
+
authGroups: "REACTOR_AUTH_GROUPS",
|
|
17
|
+
authConditions: "REACTOR_AUTH_CONDITIONS"
|
|
18
|
+
};
|
|
19
|
+
/** The env vars a protocol block maps onto, with their string values. Only
|
|
20
|
+
* keys the block actually sets appear. */
|
|
21
|
+
function protocolEnv(protocol) {
|
|
22
|
+
const env = {};
|
|
23
|
+
if (!protocol) return env;
|
|
24
|
+
for (const [key, varName] of Object.entries(FLAG_ENV)) {
|
|
25
|
+
const value = protocol.featureFlags?.[key];
|
|
26
|
+
if (value !== void 0) env[varName] = value ? "true" : "false";
|
|
27
|
+
}
|
|
28
|
+
if (protocol.createSignaturePolicy !== void 0) env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;
|
|
29
|
+
if (protocol.unsupportedStoredDocuments !== void 0) env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS = protocol.unsupportedStoredDocuments;
|
|
30
|
+
return env;
|
|
31
|
+
}
|
|
32
|
+
/** Project the reactor block onto the switchboard's env + options. */
|
|
33
|
+
function projectReactorToSwitchboard(reactor) {
|
|
34
|
+
const env = protocolEnv(reactor?.protocol);
|
|
35
|
+
const backend = primaryBackend(reactor);
|
|
36
|
+
const options = {};
|
|
37
|
+
if (backend?.storage) {
|
|
38
|
+
const s = backend.storage;
|
|
39
|
+
const dbUrl = s.kind === "postgres" ? s.url : s.dataDir;
|
|
40
|
+
if (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;
|
|
41
|
+
}
|
|
42
|
+
if (backend?.readModel?.url) options.dbPath = backend.readModel.url;
|
|
43
|
+
if (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = "true";
|
|
44
|
+
if (reactor?.workflows !== void 0) env.PH_WORKFLOWS_ENABLED = reactor.workflows ? "1" : "0";
|
|
45
|
+
return {
|
|
46
|
+
env,
|
|
47
|
+
options
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const LOCAL_BACKEND_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
|
|
51
|
+
/**
|
|
52
|
+
* Which reactor client the backend topology asks for:
|
|
53
|
+
* - local (in-process/worker) AND remote backends -> `router`
|
|
54
|
+
* - remote backend(s) only -> `remote`
|
|
55
|
+
* - a worker backend -> `worker`
|
|
56
|
+
* - anything else local -> `in-process`
|
|
57
|
+
* `undefined` when no backends are declared — the caller then keeps the
|
|
58
|
+
* legacy reactorWorker/multiReactor behaviour untouched.
|
|
59
|
+
*/
|
|
60
|
+
function reactorClientMode(reactor) {
|
|
61
|
+
const backends = reactor?.backends;
|
|
62
|
+
if (!backends) return void 0;
|
|
63
|
+
const kinds = Object.values(backends).map((b) => b.kind);
|
|
64
|
+
if (kinds.length === 0) return void 0;
|
|
65
|
+
const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));
|
|
66
|
+
const hasRemote = kinds.some((k) => k === "remote");
|
|
67
|
+
if (hasLocal && hasRemote) return "router";
|
|
68
|
+
if (hasRemote) return "remote";
|
|
69
|
+
return primaryBackend(reactor)?.kind === "worker" ? "worker" : "in-process";
|
|
70
|
+
}
|
|
71
|
+
/** Project the reactor block onto the Connect runtime config: protocol →
|
|
72
|
+
* connect.reactor (same shape), backend topology → instance.reactorWorker
|
|
73
|
+
* (legacy) + instance.reactorClient (the explicit 4-way selector),
|
|
74
|
+
* workflows → app.workflowsEnabled. */
|
|
75
|
+
function projectReactorToConnect(reactor) {
|
|
76
|
+
const connect = {};
|
|
77
|
+
if (reactor?.protocol) connect.reactor = reactor.protocol;
|
|
78
|
+
const backend = primaryBackend(reactor);
|
|
79
|
+
const mode = reactorClientMode(reactor);
|
|
80
|
+
if (backend?.kind !== void 0 || mode !== void 0) connect.instance = {
|
|
81
|
+
...backend?.kind !== void 0 ? { reactorWorker: backend.kind === "worker" } : {},
|
|
82
|
+
...mode !== void 0 ? { reactorClient: mode } : {}
|
|
83
|
+
};
|
|
84
|
+
if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
|
|
85
|
+
return { connect };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS
|
|
89
|
+
* the host's protocol block, fail loudly naming the var, the host value, and
|
|
90
|
+
* the env value. An env var that merely matches, or is unset, is fine (phase-2
|
|
91
|
+
* transition keeps an operator's explicit env as an escape hatch unless it
|
|
92
|
+
* disagrees with the protocol — see the WBS precedence note).
|
|
93
|
+
*/
|
|
94
|
+
function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
|
|
95
|
+
if (!protocol) return;
|
|
96
|
+
const expected = protocolEnv(protocol);
|
|
97
|
+
for (const [varName, hostValue] of Object.entries(expected)) {
|
|
98
|
+
const envValue = env[varName];
|
|
99
|
+
if (envValue !== void 0 && envValue !== hostValue) throw new Error(`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/backend-projection.ts
|
|
104
|
+
function projectStorage(name, storage) {
|
|
105
|
+
switch (storage.kind) {
|
|
106
|
+
case "idb": return { kind: "idb" };
|
|
107
|
+
case "memory": return { kind: "memory" };
|
|
108
|
+
case "path":
|
|
109
|
+
if (!storage.dataDir) throw new Error(`Backend "${name}": storage kind "path" requires dataDir.`);
|
|
110
|
+
return {
|
|
111
|
+
kind: "path",
|
|
112
|
+
dataDir: storage.dataDir
|
|
113
|
+
};
|
|
114
|
+
case "postgres": throw new Error(`Backend "${name}": storage kind "postgres" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a "remote" backend at the switchboard that owns that database instead.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** One backend → one descriptor. The protocol's featureFlags ride every
|
|
118
|
+
* descriptor (they are fleet consensus, not per-backend). A remote backend
|
|
119
|
+
* must carry remote.url — provision() requires it. */
|
|
120
|
+
function backendToDescriptor(name, backend, protocol) {
|
|
121
|
+
const descriptor = {
|
|
122
|
+
kind: backend.kind,
|
|
123
|
+
name
|
|
124
|
+
};
|
|
125
|
+
if (descriptor.kind === "remote") {
|
|
126
|
+
const url = backend.remote?.url;
|
|
127
|
+
if (!url) throw new Error(`Backend "${name}" is kind "remote" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);
|
|
128
|
+
descriptor.remote = { url };
|
|
129
|
+
return descriptor;
|
|
130
|
+
}
|
|
131
|
+
if (backend.storage) descriptor.storage = projectStorage(name, backend.storage);
|
|
132
|
+
if (backend.packages) descriptor.packages = backend.packages;
|
|
133
|
+
if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;
|
|
134
|
+
return descriptor;
|
|
135
|
+
}
|
|
136
|
+
/** All named backends, in placement-primary-first order (the order a
|
|
137
|
+
* createReactorClients step would provision them). */
|
|
138
|
+
function backendsToDescriptors(reactor) {
|
|
139
|
+
const backends = reactor?.backends;
|
|
140
|
+
if (!backends) return [];
|
|
141
|
+
const names = Object.keys(backends);
|
|
142
|
+
const primary = reactor.placement?.primary;
|
|
143
|
+
return (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));
|
|
144
|
+
}
|
|
145
|
+
const LOCAL_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
|
|
146
|
+
/**
|
|
147
|
+
* Structural multi-reactor (phase 4): true when the block names BOTH a local
|
|
148
|
+
* backend (in-process/worker — the tab's own reactor) and a remote one. This
|
|
149
|
+
* is the shape Connect's routing client serves; a lone remote backend is an
|
|
150
|
+
* attach-only host (assistant/agent shape), not a routed tab.
|
|
151
|
+
*/
|
|
152
|
+
function isStructuralMultiReactor(reactor) {
|
|
153
|
+
const backends = reactor?.backends;
|
|
154
|
+
if (!backends) return false;
|
|
155
|
+
const kinds = Object.values(backends).map((b) => b.kind);
|
|
156
|
+
return kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === "remote");
|
|
157
|
+
}
|
|
158
|
+
/** The remote backends' urls, placement order — what the routing client dials. */
|
|
159
|
+
function remoteBackendUrls(reactor) {
|
|
160
|
+
return backendsToDescriptors(reactor).filter((d) => d.kind === "remote").map((d) => d.remote?.url).filter((u) => typeof u === "string");
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/connect-projection.ts
|
|
164
|
+
/**
|
|
165
|
+
* Instance-fact projection for compound hosts: the drives a compound's
|
|
166
|
+
* reactor member created, projected into the Connect member's runtime-config
|
|
167
|
+
* override. Pure functions, moved from ph-cli's vetra service so the generic
|
|
168
|
+
* compound and the classic path share one implementation.
|
|
169
|
+
*/
|
|
170
|
+
function isLocalDrive(drive) {
|
|
171
|
+
return "local" in drive;
|
|
172
|
+
}
|
|
173
|
+
const driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;
|
|
174
|
+
/**
|
|
175
|
+
* Concatenate groups of `connect.drives.defaultDrives` in the order given,
|
|
176
|
+
* de-duplicating by drive identity (URL for remote entries, id for local
|
|
177
|
+
* ones). The first occurrence of a drive wins, so earlier groups keep their
|
|
178
|
+
* position and metadata — e.g. the Vetra drive `ph vetra` starts stays first
|
|
179
|
+
* even when the project's `powerhouse.config.json` lists the same drive.
|
|
180
|
+
*/
|
|
181
|
+
function mergeDefaultDrives(...groups) {
|
|
182
|
+
const seen = /* @__PURE__ */ new Set();
|
|
183
|
+
const out = [];
|
|
184
|
+
for (const group of groups) for (const drive of group) {
|
|
185
|
+
const key = driveKey(drive);
|
|
186
|
+
if (seen.has(key)) continue;
|
|
187
|
+
seen.add(key);
|
|
188
|
+
out.push(drive);
|
|
189
|
+
}
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Rebase a local drive URL onto a public base: keeps the /d/<slug> path,
|
|
194
|
+
* swaps the loopback origin for the public base. Browser clients behind a
|
|
195
|
+
* reverse proxy can't reach http://localhost:<port>. Non-loopback URLs
|
|
196
|
+
* (e.g. a remote drive) are already public and pass through unchanged, as do
|
|
197
|
+
* unparseable ones.
|
|
198
|
+
*/
|
|
199
|
+
function rebaseDriveUrl(driveUrl, publicBase) {
|
|
200
|
+
let url;
|
|
201
|
+
try {
|
|
202
|
+
url = new URL(driveUrl);
|
|
203
|
+
} catch {
|
|
204
|
+
return driveUrl;
|
|
205
|
+
}
|
|
206
|
+
if (![
|
|
207
|
+
"localhost",
|
|
208
|
+
"127.0.0.1",
|
|
209
|
+
"[::1]"
|
|
210
|
+
].includes(url.hostname)) return driveUrl;
|
|
211
|
+
return `${publicBase.replace(/\/+$/, "")}${url.pathname}`;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* The compound's drives projection: created drives first (rebased onto the
|
|
215
|
+
* public base when given), then the project's configured drives, de-duplicated
|
|
216
|
+
* — and `preserve-all`, because compound-injected drive lists change per
|
|
217
|
+
* launch context and must never detach drives the user added by hand.
|
|
218
|
+
*/
|
|
219
|
+
function projectDrivesIntoConnect(input) {
|
|
220
|
+
return { drives: {
|
|
221
|
+
defaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === "string" && url.length > 0).map((url) => ({
|
|
222
|
+
url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,
|
|
223
|
+
name: null,
|
|
224
|
+
icon: null
|
|
225
|
+
})), input.configuredDefaultDrives ?? []),
|
|
226
|
+
preserveStrategy: "preserve-all"
|
|
227
|
+
} };
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/run-record-schema.ts
|
|
231
|
+
/**
|
|
232
|
+
* `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running
|
|
233
|
+
* host and its members produced. Validated on read; a v1 (or any invalid)
|
|
234
|
+
* record reads as "not running". `projectName` is kept beyond the plan's
|
|
235
|
+
* sketch because the live/foreign probe needs it. `host` is the host's
|
|
236
|
+
* `name` (the file key), not its folder.
|
|
237
|
+
*/
|
|
238
|
+
const outputsSchema = z.record(z.string(), z.unknown());
|
|
239
|
+
const runRecordMemberSchema = z.strictObject({
|
|
240
|
+
/** The member's host folder (`children.<key>.host`). */
|
|
241
|
+
host: z.string().min(1),
|
|
242
|
+
runnerModule: z.string().min(1),
|
|
243
|
+
kind: runnerKindSchema,
|
|
244
|
+
verb: z.string().min(1),
|
|
245
|
+
outputs: outputsSchema
|
|
246
|
+
});
|
|
247
|
+
const runRecordSchema = z.strictObject({
|
|
248
|
+
version: z.literal(2),
|
|
249
|
+
host: z.string().min(1),
|
|
250
|
+
projectName: z.string(),
|
|
251
|
+
kind: runnerKindSchema,
|
|
252
|
+
verb: z.string().min(1),
|
|
253
|
+
pid: z.number().int(),
|
|
254
|
+
startedAt: z.string(),
|
|
255
|
+
/** Standalone hosts: the runner's outputs. */
|
|
256
|
+
outputs: outputsSchema.optional(),
|
|
257
|
+
/** Compounds: one entry per started member, keyed by member name. */
|
|
258
|
+
members: z.record(z.string(), runRecordMemberSchema).optional(),
|
|
259
|
+
/** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */
|
|
260
|
+
extra: z.record(z.string(), z.unknown()).optional()
|
|
261
|
+
});
|
|
262
|
+
//#endregion
|
|
263
|
+
//#region src/resolve/walk.ts
|
|
264
|
+
function isPlainObject(value) {
|
|
265
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
266
|
+
const proto = Object.getPrototypeOf(value);
|
|
267
|
+
return proto === Object.prototype || proto === null;
|
|
268
|
+
}
|
|
269
|
+
/** `a.b[2].c` (or `<root>`). */
|
|
270
|
+
function formatPath(path) {
|
|
271
|
+
let out = "";
|
|
272
|
+
for (const segment of path) if (typeof segment === "number") out += `[${segment}]`;
|
|
273
|
+
else out += out ? `.${segment}` : segment;
|
|
274
|
+
return out || "<root>";
|
|
275
|
+
}
|
|
276
|
+
/** Is this object a `$$` escape (`{ $$: literal }`)? */
|
|
277
|
+
function isEscape(value) {
|
|
278
|
+
const keys = Object.keys(value);
|
|
279
|
+
return keys.length === 1 && keys[0] === TOKEN_ESCAPE_KEY;
|
|
280
|
+
}
|
|
281
|
+
/** Every token in `value`, in document order. `$concat` parts and `$map`
|
|
282
|
+
* operands (`over`, then the `to` template) are visited: they may hold tokens
|
|
283
|
+
* themselves. Each site carries the `$map` scopes it sits in. A `$$` escape
|
|
284
|
+
* hides its operand. */
|
|
285
|
+
function collectTokenSites(value) {
|
|
286
|
+
const sites = [];
|
|
287
|
+
visit(value, [], "root", [], sites);
|
|
288
|
+
return sites;
|
|
289
|
+
}
|
|
290
|
+
function visit(value, path, position, scopes, sites) {
|
|
291
|
+
const key = tokenKeyOf(value);
|
|
292
|
+
if (key && isPlainObject(value)) {
|
|
293
|
+
sites.push({
|
|
294
|
+
path,
|
|
295
|
+
key,
|
|
296
|
+
token: value,
|
|
297
|
+
position,
|
|
298
|
+
scopes
|
|
299
|
+
});
|
|
300
|
+
const operand = value[key];
|
|
301
|
+
if (key === "$concat" && Array.isArray(operand)) operand.forEach((part, index) => visit(part, [
|
|
302
|
+
...path,
|
|
303
|
+
"$concat",
|
|
304
|
+
index
|
|
305
|
+
], "concat", scopes, sites));
|
|
306
|
+
if (key === "$map" && isPlainObject(operand)) {
|
|
307
|
+
const at = [...path, "$map"];
|
|
308
|
+
if ("over" in operand) visit(operand.over, [...at, "over"], "over", scopes, sites);
|
|
309
|
+
if ("to" in operand) {
|
|
310
|
+
const scope = {
|
|
311
|
+
path,
|
|
312
|
+
token: value,
|
|
313
|
+
...typeof operand.as === "string" ? { as: operand.as } : {}
|
|
314
|
+
};
|
|
315
|
+
visit(operand.to, [...at, "to"], "template", [...scopes, scope], sites);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (Array.isArray(value)) {
|
|
321
|
+
value.forEach((child, index) => visit(child, [...path, index], "element", scopes, sites));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (!isPlainObject(value) || isEscape(value)) return;
|
|
325
|
+
for (const [childKey, child] of Object.entries(value)) visit(child, [...path, childKey], "property", scopes, sites);
|
|
326
|
+
}
|
|
327
|
+
/** An `$item` path as text: `url`, `drives.x`, `<element>` for `[]`. */
|
|
328
|
+
function pathText(path) {
|
|
329
|
+
if (path.length === 0) return "<element>";
|
|
330
|
+
return formatPath(path.filter((p) => typeof p === "string" || typeof p === "number"));
|
|
331
|
+
}
|
|
332
|
+
/** A one-line human rendering of a token, for `--explain` and messages. */
|
|
333
|
+
function describeToken(token) {
|
|
334
|
+
const key = tokenKeyOf(token);
|
|
335
|
+
if (!key || !isPlainObject(token)) return JSON.stringify(token);
|
|
336
|
+
const operand = token[key];
|
|
337
|
+
if (key === "$output" && isPlainObject(operand)) return `$output ${typeof operand.host === "string" ? operand.host : "?"}${typeof operand.member === "string" ? ` (member ${operand.member})` : ""} › ${Array.isArray(operand.path) ? formatPath(operand.path.filter((p) => typeof p === "string" || typeof p === "number")) : "?"}`;
|
|
338
|
+
if (key === "$env") {
|
|
339
|
+
if (typeof operand === "string") return `$env ${operand}`;
|
|
340
|
+
if (isPlainObject(operand) && typeof operand.name === "string") return `$env ${operand.name} (optional)`;
|
|
341
|
+
}
|
|
342
|
+
if (key === "$item") {
|
|
343
|
+
const named = isPlainObject(operand) ? operand : void 0;
|
|
344
|
+
const raw = named ? named.path : operand;
|
|
345
|
+
const path = Array.isArray(raw) ? pathText(raw) : "?";
|
|
346
|
+
return `$item${named && typeof named.as === "string" ? `(${named.as})` : ""} ${path}`;
|
|
347
|
+
}
|
|
348
|
+
if (key === "$key") return typeof operand === "string" ? `$key(${operand})` : "$key";
|
|
349
|
+
if (key === "$map" && isPlainObject(operand)) {
|
|
350
|
+
const as = typeof operand.as === "string" ? ` as ${operand.as}` : "";
|
|
351
|
+
const into = operand.into === "record" ? " into record" : "";
|
|
352
|
+
return `$map over [${describeToken(operand.over)}]${as}${into} → ${JSON.stringify(render(operand.to))}`;
|
|
353
|
+
}
|
|
354
|
+
if (key === "$concat" && Array.isArray(operand)) return `$concat ${operand.map((part) => typeof part === "string" ? JSON.stringify(part) : typeof part === "number" ? String(part) : `[${describeToken(part)}]`).join(" + ")}`;
|
|
355
|
+
return `${key} ${JSON.stringify(operand)}`;
|
|
356
|
+
}
|
|
357
|
+
/** A display copy of `value` with every token replaced by `«description»`
|
|
358
|
+
* (for printing declared hosts, e.g. `--explain drives`). */
|
|
359
|
+
function renderTokens(value) {
|
|
360
|
+
return render(value);
|
|
361
|
+
}
|
|
362
|
+
function render(value) {
|
|
363
|
+
if (tokenKeyOf(value)) return `«${describeToken(value)}»`;
|
|
364
|
+
if (Array.isArray(value)) return value.map(render);
|
|
365
|
+
if (!isPlainObject(value) || isEscape(value)) return value;
|
|
366
|
+
const out = {};
|
|
367
|
+
for (const [key, child] of Object.entries(value)) out[key] = render(child);
|
|
368
|
+
return out;
|
|
369
|
+
}
|
|
370
|
+
/** A copy of `value` with every `$$` escape replaced by its operand (the
|
|
371
|
+
* literal it protects). Run after the no-token walk. */
|
|
372
|
+
function unwrapEscapes(value) {
|
|
373
|
+
return unwrap(value);
|
|
374
|
+
}
|
|
375
|
+
function unwrap(value) {
|
|
376
|
+
if (Array.isArray(value)) return value.map(unwrap);
|
|
377
|
+
if (!isPlainObject(value)) return value;
|
|
378
|
+
if (isEscape(value)) return structuredClone(value[TOKEN_ESCAPE_KEY]);
|
|
379
|
+
const out = {};
|
|
380
|
+
for (const [key, child] of Object.entries(value)) out[key] = unwrap(child);
|
|
381
|
+
return out;
|
|
382
|
+
}
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region src/resolve/declared.ts
|
|
385
|
+
function refOf(site) {
|
|
386
|
+
const operand = site.token.$output;
|
|
387
|
+
if (!isPlainObject(operand) || typeof operand.host !== "string") return;
|
|
388
|
+
return typeof operand.member === "string" ? {
|
|
389
|
+
host: operand.host,
|
|
390
|
+
member: operand.member
|
|
391
|
+
} : { host: operand.host };
|
|
392
|
+
}
|
|
393
|
+
function pathOf(site) {
|
|
394
|
+
const operand = site.token.$output;
|
|
395
|
+
if (!isPlainObject(operand) || !Array.isArray(operand.path)) return [];
|
|
396
|
+
return operand.path.filter((p) => typeof p === "string" || typeof p === "number");
|
|
397
|
+
}
|
|
398
|
+
function refKey(ref) {
|
|
399
|
+
return ref.member ? `${ref.host}#${ref.member}` : ref.host;
|
|
400
|
+
}
|
|
401
|
+
/** The distinct producers a host's `$output` tokens name, in document order. */
|
|
402
|
+
function outputRefsOf(host) {
|
|
403
|
+
const seen = /* @__PURE__ */ new Map();
|
|
404
|
+
for (const site of collectTokenSites(host)) {
|
|
405
|
+
if (site.key !== "$output") continue;
|
|
406
|
+
const ref = refOf(site);
|
|
407
|
+
if (ref && !seen.has(refKey(ref))) seen.set(refKey(ref), ref);
|
|
408
|
+
}
|
|
409
|
+
return [...seen.values()];
|
|
410
|
+
}
|
|
411
|
+
/** Every `$output` token with its host path and producer (for the plan and
|
|
412
|
+
* `--explain outputs`). */
|
|
413
|
+
function outputSitesOf(host) {
|
|
414
|
+
return collectTokenSites(host).flatMap((site) => {
|
|
415
|
+
if (site.key !== "$output") return [];
|
|
416
|
+
const ref = refOf(site);
|
|
417
|
+
return ref ? [{
|
|
418
|
+
path: formatPath(site.path),
|
|
419
|
+
ref,
|
|
420
|
+
outputPath: pathOf(site)
|
|
421
|
+
}] : [];
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
/** Every `$env` token with its host path (for `--explain outputs`). */
|
|
425
|
+
function envSitesOf(host) {
|
|
426
|
+
return collectTokenSites(host).flatMap((site) => {
|
|
427
|
+
if (site.key !== "$env") return [];
|
|
428
|
+
const operand = site.token.$env;
|
|
429
|
+
if (typeof operand === "string") return [{
|
|
430
|
+
path: formatPath(site.path),
|
|
431
|
+
name: operand,
|
|
432
|
+
optional: false
|
|
433
|
+
}];
|
|
434
|
+
if (isPlainObject(operand) && typeof operand.name === "string") return [{
|
|
435
|
+
path: formatPath(site.path),
|
|
436
|
+
name: operand.name,
|
|
437
|
+
optional: true
|
|
438
|
+
}];
|
|
439
|
+
return [];
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
/** The binding name an `$item`/`$key` site names (undefined: innermost). */
|
|
443
|
+
function bindingNameOf(site) {
|
|
444
|
+
const operand = site.token[site.key];
|
|
445
|
+
if (site.key === "$key") return typeof operand === "string" ? operand : void 0;
|
|
446
|
+
if (site.key === "$item" && isPlainObject(operand)) return typeof operand.as === "string" ? operand.as : void 0;
|
|
447
|
+
}
|
|
448
|
+
/** The enclosing `$map` an `$item`/`$key` site binds to, or why none. */
|
|
449
|
+
function scopeOf(site) {
|
|
450
|
+
const name = bindingNameOf(site);
|
|
451
|
+
if (site.scopes.length === 0) return { error: `${site.key} is used outside any $map; it reads the element a $map template is rendering, so it is legal only inside a $map's \`to\` (or a nested $map's \`over\`).` };
|
|
452
|
+
if (name === void 0) return site.scopes[site.scopes.length - 1];
|
|
453
|
+
for (let i = site.scopes.length - 1; i >= 0; i--) if (site.scopes[i].as === name) return site.scopes[i];
|
|
454
|
+
const named = site.scopes.flatMap((s) => s.as ? [`"${s.as}"`] : []);
|
|
455
|
+
return { error: `${describeToken(site.token)} names the $map binding "${name}", which no enclosing $map declares (enclosing bindings: ${named.join(", ") || "none; add as: \"" + name + "\" to the outer $map"}).` };
|
|
456
|
+
}
|
|
457
|
+
/** Item path of an `$item` site. */
|
|
458
|
+
function itemPathOf(site) {
|
|
459
|
+
const operand = site.token.$item;
|
|
460
|
+
const raw = isPlainObject(operand) ? operand.path : operand;
|
|
461
|
+
return Array.isArray(raw) ? raw.filter((p) => typeof p === "string" || typeof p === "number") : [];
|
|
462
|
+
}
|
|
463
|
+
/** Operator shapes and placement: malformed operands, `$item`/`$key`
|
|
464
|
+
* outside any `$map` or naming an unknown binding, and
|
|
465
|
+
* `{ $env: { name, optional: true } }` anywhere but the direct value of an
|
|
466
|
+
* object property (it omits that property when unset). */
|
|
467
|
+
function checkTokenSites(host) {
|
|
468
|
+
const issues = [];
|
|
469
|
+
for (const site of collectTokenSites(host)) {
|
|
470
|
+
const path = formatPath(site.path);
|
|
471
|
+
if (!tokenSchema.safeParse(site.token).success) {
|
|
472
|
+
issues.push({
|
|
473
|
+
path,
|
|
474
|
+
message: `malformed ${site.key} token ${JSON.stringify(site.token)}. Shapes: { $output: { host, member?, path: [...] } }, { $concat: [string | number | token, ...] }, { $env: "NAME" } or { $env: { name: "NAME", optional: true } }, { $map: { over: $output | $item, as?: "name", to: template, into?: "record" } }, { $item: [path] } or { $item: { as: "name", path: [...] } }, { $key: true } or { $key: "name" }.`
|
|
475
|
+
});
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (site.key === "$item" || site.key === "$key") {
|
|
479
|
+
const scope = scopeOf(site);
|
|
480
|
+
if ("error" in scope) issues.push({
|
|
481
|
+
path,
|
|
482
|
+
message: scope.error
|
|
483
|
+
});
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
const operand = site.token.$env;
|
|
487
|
+
if (site.key === "$env" && isPlainObject(operand) && site.position !== "property") {
|
|
488
|
+
const where = site.position === "concat" ? "a $concat part" : site.position === "element" ? "an array element" : site.position === "template" ? "the whole $map template" : "the whole host";
|
|
489
|
+
issues.push({
|
|
490
|
+
path,
|
|
491
|
+
message: `{ $env: { name, optional: true } } is legal only as the direct value of an object property (it omits that property when ${String(operand.name)} is unset), not as ${where}. Use { $env: ${JSON.stringify(operand.name)} } here.`
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return issues;
|
|
496
|
+
}
|
|
497
|
+
function defOf(schema) {
|
|
498
|
+
if (!isPlainObjectLike(schema)) return void 0;
|
|
499
|
+
const internals = schema._zod;
|
|
500
|
+
if (!isPlainObjectLike(internals)) return void 0;
|
|
501
|
+
const def = internals.def;
|
|
502
|
+
if (!isPlainObjectLike(def) || typeof def.type !== "string") return void 0;
|
|
503
|
+
return {
|
|
504
|
+
...def,
|
|
505
|
+
type: def.type
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function isPlainObjectLike(value) {
|
|
509
|
+
return (typeof value === "object" || typeof value === "function") && value !== null;
|
|
510
|
+
}
|
|
511
|
+
const WRAPPERS = /* @__PURE__ */ new Set([
|
|
512
|
+
"optional",
|
|
513
|
+
"nullable",
|
|
514
|
+
"default",
|
|
515
|
+
"prefault",
|
|
516
|
+
"readonly",
|
|
517
|
+
"nonoptional",
|
|
518
|
+
"catch",
|
|
519
|
+
"success"
|
|
520
|
+
]);
|
|
521
|
+
/** The schema at `path` inside a zod schema (walking objects, records,
|
|
522
|
+
* arrays, tuples, unions and wrappers), or why the path does not exist. */
|
|
523
|
+
function schemaAtPath(schema, path) {
|
|
524
|
+
let current = schema;
|
|
525
|
+
for (let i = 0; i <= path.length; i++) {
|
|
526
|
+
for (let guard = 0; guard < 32; guard++) {
|
|
527
|
+
const def = defOf(current);
|
|
528
|
+
if (!def) break;
|
|
529
|
+
if (WRAPPERS.has(def.type)) current = def.innerType;
|
|
530
|
+
else if (def.type === "lazy" && typeof def.getter === "function") {
|
|
531
|
+
const getter = def.getter;
|
|
532
|
+
current = getter();
|
|
533
|
+
} else if (def.type === "pipe") {
|
|
534
|
+
const out = defOf(def.out);
|
|
535
|
+
current = out && out.type !== "transform" ? def.out : def.in;
|
|
536
|
+
} else break;
|
|
537
|
+
}
|
|
538
|
+
if (i === path.length) return {
|
|
539
|
+
ok: true,
|
|
540
|
+
schema: current
|
|
541
|
+
};
|
|
542
|
+
const segment = path[i];
|
|
543
|
+
const def = defOf(current);
|
|
544
|
+
if (!def) return {
|
|
545
|
+
ok: false,
|
|
546
|
+
at: i,
|
|
547
|
+
reason: "is not a schema"
|
|
548
|
+
};
|
|
549
|
+
switch (def.type) {
|
|
550
|
+
case "any":
|
|
551
|
+
case "unknown": return {
|
|
552
|
+
ok: true,
|
|
553
|
+
schema: current
|
|
554
|
+
};
|
|
555
|
+
case "object": {
|
|
556
|
+
const shape = isPlainObjectLike(def.shape) ? def.shape : {};
|
|
557
|
+
if (typeof segment === "string" && segment in shape) {
|
|
558
|
+
current = shape[segment];
|
|
559
|
+
break;
|
|
560
|
+
}
|
|
561
|
+
const catchall = defOf(def.catchall);
|
|
562
|
+
if (catchall && catchall.type !== "never") {
|
|
563
|
+
current = def.catchall;
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
const keys = Object.keys(shape);
|
|
567
|
+
return {
|
|
568
|
+
ok: false,
|
|
569
|
+
at: i,
|
|
570
|
+
reason: `has no key ${JSON.stringify(segment)} (keys: ${keys.join(", ") || "none"})`
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
case "record":
|
|
574
|
+
if (typeof segment !== "string") return {
|
|
575
|
+
ok: false,
|
|
576
|
+
at: i,
|
|
577
|
+
reason: "is a record (string keys)"
|
|
578
|
+
};
|
|
579
|
+
current = def.valueType;
|
|
580
|
+
break;
|
|
581
|
+
case "array":
|
|
582
|
+
if (typeof segment !== "number") return {
|
|
583
|
+
ok: false,
|
|
584
|
+
at: i,
|
|
585
|
+
reason: "is an array (numeric index)"
|
|
586
|
+
};
|
|
587
|
+
current = def.element;
|
|
588
|
+
break;
|
|
589
|
+
case "tuple": {
|
|
590
|
+
const items = Array.isArray(def.items) ? def.items : [];
|
|
591
|
+
if (typeof segment !== "number" || segment >= items.length) return {
|
|
592
|
+
ok: false,
|
|
593
|
+
at: i,
|
|
594
|
+
reason: `is a ${items.length}-tuple`
|
|
595
|
+
};
|
|
596
|
+
current = items[segment];
|
|
597
|
+
break;
|
|
598
|
+
}
|
|
599
|
+
case "union": {
|
|
600
|
+
const options = Array.isArray(def.options) ? def.options : [];
|
|
601
|
+
for (const option of options) {
|
|
602
|
+
const hit = schemaAtPath(option, path.slice(i));
|
|
603
|
+
if (hit.ok) return hit;
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
ok: false,
|
|
607
|
+
at: i,
|
|
608
|
+
reason: "matches no union member"
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
default: return {
|
|
612
|
+
ok: false,
|
|
613
|
+
at: i,
|
|
614
|
+
reason: `is a ${def.type}, not a container`
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
ok: true,
|
|
620
|
+
schema: current
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
/** Whether a (property) schema admits an absent value on the OUTPUT side:
|
|
624
|
+
* `.optional()` does; `.default()`/`.prefault()` fill it in, and
|
|
625
|
+
* `.nonoptional()` forbids it. */
|
|
626
|
+
function mayBeAbsent(schema) {
|
|
627
|
+
let current = schema;
|
|
628
|
+
for (let guard = 0; guard < 32; guard++) {
|
|
629
|
+
const internals = isPlainObjectLike(current) ? current._zod : void 0;
|
|
630
|
+
if (isPlainObjectLike(internals) && internals.optout === "optional") return true;
|
|
631
|
+
const def = defOf(current);
|
|
632
|
+
if (!def) return false;
|
|
633
|
+
if (def.type === "optional") return true;
|
|
634
|
+
if (def.type === "default" || def.type === "prefault" || def.type === "nonoptional" || !WRAPPERS.has(def.type)) return false;
|
|
635
|
+
current = def.innerType;
|
|
636
|
+
}
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
/** Whether `key` may be absent from a value of the object schema `schema`:
|
|
640
|
+
* an optional property, or (in a union) one some member makes optional or
|
|
641
|
+
* lacks. A record value or an array element is never optional. */
|
|
642
|
+
function optionalKeyIn(schema, key) {
|
|
643
|
+
const unwrapped = schemaAtPath(schema, []);
|
|
644
|
+
const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
|
|
645
|
+
if (def?.type === "object") {
|
|
646
|
+
const shape = isPlainObjectLike(def.shape) ? def.shape : {};
|
|
647
|
+
return key in shape && mayBeAbsent(shape[key]);
|
|
648
|
+
}
|
|
649
|
+
if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => {
|
|
650
|
+
const inner = schemaAtPath(option, []);
|
|
651
|
+
const optionDef = inner.ok ? defOf(inner.schema) : void 0;
|
|
652
|
+
const shape = optionDef?.type === "object" && isPlainObjectLike(optionDef.shape) ? optionDef.shape : void 0;
|
|
653
|
+
return shape !== void 0 && (!(key in shape) || mayBeAbsent(shape[key]));
|
|
654
|
+
});
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Whether the field `path[at]` is OPTIONAL in `schema` (a producer's
|
|
659
|
+
* `outputsSchema`, or a `$map` element schema), given that `path[0..at-1]`
|
|
660
|
+
* exists: the codegen'd `OutputToken<T | undefined>` / `ItemToken<T |
|
|
661
|
+
* undefined>` positions, whose rendered property the resolver omits when
|
|
662
|
+
* the field is absent. False for a record key, an array index, or a path
|
|
663
|
+
* the schema does not describe.
|
|
664
|
+
*/
|
|
665
|
+
function isOptionalField(schema, path, at) {
|
|
666
|
+
const key = path[at];
|
|
667
|
+
if (typeof key !== "string") return false;
|
|
668
|
+
const parent = schemaAtPath(schema, path.slice(0, at));
|
|
669
|
+
return parent.ok && optionalKeyIn(parent.schema, key);
|
|
670
|
+
}
|
|
671
|
+
/** The element schema of a collection schema (array element, record
|
|
672
|
+
* value), or undefined when the schema does not say. */
|
|
673
|
+
function elementSchemaOf(schema) {
|
|
674
|
+
const collection = collectionOf(schema);
|
|
675
|
+
return collection.kind === "array" || collection.kind === "record" ? collection.element : void 0;
|
|
676
|
+
}
|
|
677
|
+
/** The collection kind of a schema (unwrapped): array, record, unknown (no
|
|
678
|
+
* check possible) or something else. */
|
|
679
|
+
function collectionOf(schema) {
|
|
680
|
+
const unwrapped = schemaAtPath(schema, []);
|
|
681
|
+
const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
|
|
682
|
+
if (!def) return { kind: "unknown" };
|
|
683
|
+
if (def.type === "array") return {
|
|
684
|
+
kind: "array",
|
|
685
|
+
element: def.element
|
|
686
|
+
};
|
|
687
|
+
if (def.type === "record") return {
|
|
688
|
+
kind: "record",
|
|
689
|
+
element: def.valueType
|
|
690
|
+
};
|
|
691
|
+
if (def.type === "object") {
|
|
692
|
+
const catchall = defOf(def.catchall);
|
|
693
|
+
if (catchall && catchall.type !== "never") {
|
|
694
|
+
const shape = isPlainObjectLike(def.shape) ? def.shape : {};
|
|
695
|
+
return Object.keys(shape).length === 0 ? {
|
|
696
|
+
kind: "record",
|
|
697
|
+
element: def.catchall
|
|
698
|
+
} : {
|
|
699
|
+
kind: "record",
|
|
700
|
+
element: void 0
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
if (def.type === "tuple") return {
|
|
705
|
+
kind: "array",
|
|
706
|
+
element: void 0
|
|
707
|
+
};
|
|
708
|
+
if (def.type === "any" || def.type === "unknown" || def.type === "union") return { kind: "unknown" };
|
|
709
|
+
return {
|
|
710
|
+
kind: "other",
|
|
711
|
+
type: def.type
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
/** Every `$output` token's producer exists and its path is valid against
|
|
715
|
+
* the producer's `outputsSchema`; every `$map`'s `over` is a collection
|
|
716
|
+
* there (a record under `into: "record"`), and every `$item` path exists
|
|
717
|
+
* in the element schema of the map it binds. */
|
|
718
|
+
function checkOutputPaths(host, outputsSchemaOf) {
|
|
719
|
+
const issues = [];
|
|
720
|
+
const elements = /* @__PURE__ */ new Map();
|
|
721
|
+
const elementOf = (scope) => "error" in scope ? void 0 : elements.get(scope.token);
|
|
722
|
+
for (const site of collectTokenSites(host)) {
|
|
723
|
+
if (!tokenSchema.safeParse(site.token).success) continue;
|
|
724
|
+
if (site.key === "$map") {
|
|
725
|
+
elements.set(site.token, checkMap(site, outputsSchemaOf, elementOf, issues));
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (site.key === "$item") {
|
|
729
|
+
const scope = scopeOf(site);
|
|
730
|
+
const element = elementOf(scope);
|
|
731
|
+
if (!element || element.element === void 0 || "error" in scope) continue;
|
|
732
|
+
const itemPath = itemPathOf(site);
|
|
733
|
+
const hit = schemaAtPath(element.element, itemPath);
|
|
734
|
+
if (!hit.ok) {
|
|
735
|
+
const parent = itemPath.slice(0, hit.at);
|
|
736
|
+
issues.push({
|
|
737
|
+
path: formatPath(site.path),
|
|
738
|
+
message: `${describeToken(site.token)}: the element${parent.length ? `'s ${formatPath(parent)}` : ""} of the $map at ${formatPath(scope.path)}${scope.as ? ` (as "${scope.as}")` : ""} ${hit.reason} (element of ${element.label}).`
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
if (site.key !== "$output") continue;
|
|
744
|
+
const ref = refOf(site);
|
|
745
|
+
if (!ref) continue;
|
|
746
|
+
const path = formatPath(site.path);
|
|
747
|
+
const lookup = outputsSchemaOf(ref);
|
|
748
|
+
if ("error" in lookup) {
|
|
749
|
+
issues.push({
|
|
750
|
+
path,
|
|
751
|
+
message: lookup.error
|
|
752
|
+
});
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
const outputPath = pathOf(site);
|
|
756
|
+
const hit = schemaAtPath(lookup.schema, outputPath);
|
|
757
|
+
if (!hit.ok) {
|
|
758
|
+
const parent = outputPath.slice(0, hit.at);
|
|
759
|
+
const where = parent.length ? `outputs.${formatPath(parent)}` : "the outputs";
|
|
760
|
+
issues.push({
|
|
761
|
+
path,
|
|
762
|
+
message: `${describeToken(site.token)}: ${where} ${hit.reason} in the outputsSchema of ${lookup.label}.`
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return issues;
|
|
767
|
+
}
|
|
768
|
+
/** A `$map`'s `over` against its schema: a collection (a record under
|
|
769
|
+
* `into: "record"`). Returns the element schema for the map's `$item`s. */
|
|
770
|
+
function checkMap(site, outputsSchemaOf, elementOf, issues) {
|
|
771
|
+
const operand = site.token.$map;
|
|
772
|
+
if (!isPlainObject(operand)) return void 0;
|
|
773
|
+
const over = operand.over;
|
|
774
|
+
const into = operand.into === "record";
|
|
775
|
+
let schema;
|
|
776
|
+
let label;
|
|
777
|
+
if (isPlainObject(over) && "$output" in over) {
|
|
778
|
+
const overSite = {
|
|
779
|
+
...site,
|
|
780
|
+
key: "$output",
|
|
781
|
+
token: over
|
|
782
|
+
};
|
|
783
|
+
const ref = refOf(overSite);
|
|
784
|
+
if (!ref) return void 0;
|
|
785
|
+
const lookup = outputsSchemaOf(ref);
|
|
786
|
+
if ("error" in lookup) return void 0;
|
|
787
|
+
const hit = schemaAtPath(lookup.schema, pathOf(overSite));
|
|
788
|
+
if (!hit.ok) return void 0;
|
|
789
|
+
schema = hit.schema;
|
|
790
|
+
label = `${describeToken(over)} in the outputsSchema of ${lookup.label}`;
|
|
791
|
+
} else if (isPlainObject(over) && "$item" in over) {
|
|
792
|
+
const overSite = {
|
|
793
|
+
...site,
|
|
794
|
+
key: "$item",
|
|
795
|
+
token: over
|
|
796
|
+
};
|
|
797
|
+
const outer = elementOf(scopeOf(overSite));
|
|
798
|
+
if (!outer || outer.element === void 0) return void 0;
|
|
799
|
+
const hit = schemaAtPath(outer.element, itemPathOf(overSite));
|
|
800
|
+
if (!hit.ok) return void 0;
|
|
801
|
+
schema = hit.schema;
|
|
802
|
+
label = `${describeToken(over)} (element of ${outer.label})`;
|
|
803
|
+
} else return;
|
|
804
|
+
const path = formatPath(site.path);
|
|
805
|
+
const collection = collectionOf(schema);
|
|
806
|
+
if (collection.kind === "unknown") return void 0;
|
|
807
|
+
if (collection.kind === "other") {
|
|
808
|
+
issues.push({
|
|
809
|
+
path,
|
|
810
|
+
message: `$map over ${label} is a ${collection.type}, not an array or a record; a $map iterates a collection.`
|
|
811
|
+
});
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
if (into && collection.kind === "array") {
|
|
815
|
+
issues.push({
|
|
816
|
+
path,
|
|
817
|
+
message: `$map with into: "record" maps over ${label}, which is an array: an array has no keys to keep. Drop into: "record" (the result is an array) or map over a record.`
|
|
818
|
+
});
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
return {
|
|
822
|
+
element: collection.element,
|
|
823
|
+
label
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
//#endregion
|
|
827
|
+
//#region src/resolve/plan.ts
|
|
828
|
+
/**
|
|
829
|
+
* The dependency plan (pipeline step 4): which compound member consumes
|
|
830
|
+
* which member's outputs, and the start order that follows. Producers start
|
|
831
|
+
* before consumers; `config.startOrder` is optional and, when given, must
|
|
832
|
+
* agree with the tokens. Cycles fail. Pure.
|
|
833
|
+
*/
|
|
834
|
+
var PlanError = class extends Error {
|
|
835
|
+
constructor(message) {
|
|
836
|
+
super(message);
|
|
837
|
+
this.name = "PlanError";
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
/** The member a ref names: the unique member running `ref.host`, or the
|
|
841
|
+
* member `ref.member` when given (it must run `ref.host`). */
|
|
842
|
+
function memberForRef(ref, members) {
|
|
843
|
+
if (ref.member !== void 0) {
|
|
844
|
+
const named = members.find((m) => m.key === ref.member);
|
|
845
|
+
if (!named) return { error: `names member "${ref.member}", which this compound does not declare (members: ${members.map((m) => m.key).join(", ")}).` };
|
|
846
|
+
if (named.host !== ref.host) return { error: `names member "${ref.member}" of host "${ref.host}", but that member runs host "${named.host}".` };
|
|
847
|
+
return { key: named.key };
|
|
848
|
+
}
|
|
849
|
+
const running = members.filter((m) => m.host === ref.host);
|
|
850
|
+
if (running.length === 1) return { key: running[0].key };
|
|
851
|
+
if (running.length === 0) return { error: `names host "${ref.host}", which no member of this compound runs (members run: ${[...new Set(members.map((m) => m.host))].join(", ")}).` };
|
|
852
|
+
return { error: `names host "${ref.host}", which members ${running.map((m) => `"${m.key}"`).join(" and ")} both run; add member: "<key>" to pick one.` };
|
|
853
|
+
}
|
|
854
|
+
function edgesOf(members) {
|
|
855
|
+
const edges = [];
|
|
856
|
+
const problems = [];
|
|
857
|
+
for (const member of members) {
|
|
858
|
+
const seen = /* @__PURE__ */ new Set();
|
|
859
|
+
for (const { ref, path } of member.refs) {
|
|
860
|
+
const target = memberForRef(ref, members);
|
|
861
|
+
if ("error" in target) {
|
|
862
|
+
problems.push(`${member.key}: ${path} ${target.error}`);
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
if (target.key === member.key) {
|
|
866
|
+
problems.push(`${member.key}: ${path} reads ${refKey(ref)}'s outputs, which is this member itself.`);
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
if (seen.has(target.key)) continue;
|
|
870
|
+
seen.add(target.key);
|
|
871
|
+
edges.push({
|
|
872
|
+
consumer: member.key,
|
|
873
|
+
producer: target.key,
|
|
874
|
+
path
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (problems.length > 0) throw new PlanError(problems.join("\n"));
|
|
879
|
+
return edges;
|
|
880
|
+
}
|
|
881
|
+
/** Declared start order: the named members first, then the rest in
|
|
882
|
+
* declaration order. */
|
|
883
|
+
function declaredOrder(members, startOrder) {
|
|
884
|
+
const keys = members.map((m) => m.key);
|
|
885
|
+
const named = [...new Set(startOrder)].filter((k) => keys.includes(k));
|
|
886
|
+
return [...named, ...keys.filter((k) => !named.includes(k))];
|
|
887
|
+
}
|
|
888
|
+
function planCompound(members, startOrder) {
|
|
889
|
+
const edges = edgesOf(members);
|
|
890
|
+
if (startOrder) {
|
|
891
|
+
const order = declaredOrder(members, startOrder);
|
|
892
|
+
const index = new Map(order.map((k, i) => [k, i]));
|
|
893
|
+
const bad = edges.filter((e) => (index.get(e.producer) ?? 0) > (index.get(e.consumer) ?? 0));
|
|
894
|
+
if (bad.length > 0) throw new PlanError(bad.map((e) => `config.startOrder starts "${e.consumer}" before "${e.producer}", but ${e.consumer}.${e.path} consumes "${e.producer}"'s outputs. Reorder startOrder (or omit it: the order follows the tokens).`).join("\n"));
|
|
895
|
+
return {
|
|
896
|
+
order,
|
|
897
|
+
edges,
|
|
898
|
+
source: "startOrder"
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
const pending = new Map(members.map((m) => [m.key, /* @__PURE__ */ new Set()]));
|
|
902
|
+
for (const e of edges) pending.get(e.consumer)?.add(e.producer);
|
|
903
|
+
const order = [];
|
|
904
|
+
while (order.length < members.length) {
|
|
905
|
+
const next = members.find((m) => !order.includes(m.key) && pending.get(m.key)?.size === 0);
|
|
906
|
+
if (!next) {
|
|
907
|
+
const stuck = members.filter((m) => !order.includes(m.key));
|
|
908
|
+
throw new PlanError(`output tokens form a cycle between ${stuck.map((m) => `"${m.key}"`).join(", ")}: ${edges.filter((e) => stuck.some((m) => m.key === e.consumer) && stuck.some((m) => m.key === e.producer)).map((e) => `${e.consumer} (${e.path}) needs ${e.producer}`).join("; ")}.`);
|
|
909
|
+
}
|
|
910
|
+
order.push(next.key);
|
|
911
|
+
for (const set of pending.values()) set.delete(next.key);
|
|
912
|
+
}
|
|
913
|
+
return {
|
|
914
|
+
order,
|
|
915
|
+
edges,
|
|
916
|
+
source: "tokens"
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
//#endregion
|
|
920
|
+
//#region src/resolve/resolve.ts
|
|
921
|
+
var TokenResolutionError = class extends Error {
|
|
922
|
+
constructor(message) {
|
|
923
|
+
super(message);
|
|
924
|
+
this.name = "TokenResolutionError";
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
/** A resolved `{ $env: { name, optional: true } }` whose variable is unset,
|
|
928
|
+
* or an `$output`/`$item` reading an absent optional field: its enclosing
|
|
929
|
+
* property is omitted. */
|
|
930
|
+
const OMIT = Symbol("omit");
|
|
931
|
+
/** `reactor.drives["workflows"]` (or `…[2]` for an array element). */
|
|
932
|
+
function elementText(binding) {
|
|
933
|
+
const key = typeof binding.key === "number" ? `[${binding.key}]` : `[${JSON.stringify(binding.key)}]`;
|
|
934
|
+
return `${formatPath(binding.path)}${key}`;
|
|
935
|
+
}
|
|
936
|
+
/** Provenance of `$map`-rendered arrays: element index → the input key
|
|
937
|
+
* (record key, or array index) it was rendered from. Lets resolved
|
|
938
|
+
* validation name the element key, not just the result index. */
|
|
939
|
+
const renderedKeys = /* @__PURE__ */ new WeakMap();
|
|
940
|
+
/**
|
|
941
|
+
* The `$map` elements an issue path (from resolved validation of a resolved
|
|
942
|
+
* host) passes through, as text: `$map element "workflows"`. Undefined when
|
|
943
|
+
* the path crosses no `$map`-rendered array. Walk the SAME object
|
|
944
|
+
* `resolveHostOutputs` returned (provenance is by identity).
|
|
945
|
+
*/
|
|
946
|
+
function describeMapElements(host, path) {
|
|
947
|
+
const found = [];
|
|
948
|
+
let current = host;
|
|
949
|
+
for (const segment of path) if (Array.isArray(current) && typeof segment === "number") {
|
|
950
|
+
const key = renderedKeys.get(current)?.[segment];
|
|
951
|
+
if (key !== void 0) found.push(`$map element ${typeof key === "number" ? `[${key}]` : JSON.stringify(key)}`);
|
|
952
|
+
current = current[segment];
|
|
953
|
+
} else if (isPlainObject(current) && typeof segment === "string") current = current[segment];
|
|
954
|
+
else break;
|
|
955
|
+
return found.length ? found.join(" › ") : void 0;
|
|
956
|
+
}
|
|
957
|
+
/** A deep copy of a resolved (JSON-shaped) value that keeps the `$map`
|
|
958
|
+
* provenance of its rendered arrays (structuredClone would drop it). */
|
|
959
|
+
function cloneWithProvenance(value) {
|
|
960
|
+
if (Array.isArray(value)) {
|
|
961
|
+
const copy = value.map(cloneWithProvenance);
|
|
962
|
+
const keys = renderedKeys.get(value);
|
|
963
|
+
if (keys) renderedKeys.set(copy, keys);
|
|
964
|
+
return copy;
|
|
965
|
+
}
|
|
966
|
+
if (isPlainObject(value)) {
|
|
967
|
+
const copy = {};
|
|
968
|
+
for (const [key, child] of Object.entries(value)) copy[key] = cloneWithProvenance(child);
|
|
969
|
+
return copy;
|
|
970
|
+
}
|
|
971
|
+
return value;
|
|
972
|
+
}
|
|
973
|
+
/** The value at `path` inside `root` (output data: records and arrays). */
|
|
974
|
+
function walkPath(root, path) {
|
|
975
|
+
let current = root;
|
|
976
|
+
for (let i = 0; i < path.length; i++) {
|
|
977
|
+
const segment = path[i];
|
|
978
|
+
const next = Array.isArray(current) ? typeof segment === "number" ? current[segment] : void 0 : isPlainObject(current) && typeof segment === "string" ? current[segment] : void 0;
|
|
979
|
+
if (next === void 0) {
|
|
980
|
+
const has = isPlainObject(current) ? Object.keys(current).join(", ") || "nothing" : Array.isArray(current) ? `${current.length} elements` : JSON.stringify(current);
|
|
981
|
+
return {
|
|
982
|
+
ok: false,
|
|
983
|
+
at: i,
|
|
984
|
+
has
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
current = next;
|
|
988
|
+
}
|
|
989
|
+
return {
|
|
990
|
+
ok: true,
|
|
991
|
+
value: current
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
/** The schema at `path` inside `schema`, when both are known. */
|
|
995
|
+
function schemaOf(schema, path) {
|
|
996
|
+
if (schema === void 0) return void 0;
|
|
997
|
+
const hit = schemaAtPath(schema, path);
|
|
998
|
+
return hit.ok ? hit.schema : void 0;
|
|
999
|
+
}
|
|
1000
|
+
function pathSegments(path) {
|
|
1001
|
+
return path.filter((p) => typeof p === "string" || typeof p === "number");
|
|
1002
|
+
}
|
|
1003
|
+
var Resolver = class {
|
|
1004
|
+
sources;
|
|
1005
|
+
self;
|
|
1006
|
+
deferred = [];
|
|
1007
|
+
/** What the last OMIT stood for, for the "nothing to omit" errors. */
|
|
1008
|
+
omitted = "an optional $env";
|
|
1009
|
+
constructor(sources, self) {
|
|
1010
|
+
this.sources = sources;
|
|
1011
|
+
this.self = self;
|
|
1012
|
+
}
|
|
1013
|
+
/** The member keys a token reads (`$output` on a member's host), when
|
|
1014
|
+
* resolving a compound's own fields with `deferSelf`. */
|
|
1015
|
+
selfRefs(token, trail) {
|
|
1016
|
+
if (!this.self) return [];
|
|
1017
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1018
|
+
for (const site of collectTokenSites(token)) {
|
|
1019
|
+
const operand = site.token.$output;
|
|
1020
|
+
if (site.key !== "$output" || !isPlainObject(operand)) continue;
|
|
1021
|
+
if (typeof operand.host !== "string") continue;
|
|
1022
|
+
const ref = typeof operand.member === "string" ? {
|
|
1023
|
+
host: operand.host,
|
|
1024
|
+
member: operand.member
|
|
1025
|
+
} : { host: operand.host };
|
|
1026
|
+
if (!this.self.members.some((m) => m.host === ref.host)) continue;
|
|
1027
|
+
const target = memberForRef(ref, this.self.members);
|
|
1028
|
+
if ("error" in target) this.fail([...trail, ...site.path], `in a compound ${target.error}`);
|
|
1029
|
+
keys.add(target.key);
|
|
1030
|
+
}
|
|
1031
|
+
return [...keys];
|
|
1032
|
+
}
|
|
1033
|
+
fail(trail, message, scope = []) {
|
|
1034
|
+
const where = this.sources.where ? `${this.sources.where}: ` : "";
|
|
1035
|
+
const inside = scope.length ? ` (rendering $map element ${scope.map(elementText).join(" › ")})` : "";
|
|
1036
|
+
throw new TokenResolutionError(`${where}\`${formatPath(trail)}\` ${message}${inside}`);
|
|
1037
|
+
}
|
|
1038
|
+
value(value, trail, scope = []) {
|
|
1039
|
+
if (typeof value === "string") return this.sources.builtins ? substituteBuiltinEnv(value, this.sources.builtins) : value;
|
|
1040
|
+
if (Array.isArray(value)) return value.map((child, index) => {
|
|
1041
|
+
const out = this.value(child, [...trail, index], scope);
|
|
1042
|
+
if (out === OMIT) this.fail([...trail, index], `is ${this.omitted} inside an array.`, scope);
|
|
1043
|
+
return out;
|
|
1044
|
+
});
|
|
1045
|
+
if (!isPlainObject(value)) return value;
|
|
1046
|
+
if (isEscape(value)) return structuredClone(value);
|
|
1047
|
+
if (tokenKeyOf(value)) {
|
|
1048
|
+
const members = scope.length === 0 ? this.selfRefs(value, trail) : [];
|
|
1049
|
+
if (members.length > 0) {
|
|
1050
|
+
this.deferred.push({
|
|
1051
|
+
trail,
|
|
1052
|
+
token: value,
|
|
1053
|
+
members
|
|
1054
|
+
});
|
|
1055
|
+
return structuredClone(value);
|
|
1056
|
+
}
|
|
1057
|
+
return this.token(value, trail, scope);
|
|
1058
|
+
}
|
|
1059
|
+
const out = {};
|
|
1060
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1061
|
+
if (this.self && trail.length === 0 && key === "children") {
|
|
1062
|
+
out[key] = child;
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
const resolved = this.value(child, [...trail, key], scope);
|
|
1066
|
+
if (resolved !== OMIT) out[key] = resolved;
|
|
1067
|
+
}
|
|
1068
|
+
return out;
|
|
1069
|
+
}
|
|
1070
|
+
token(token, trail, scope = []) {
|
|
1071
|
+
if (!tokenSchema.safeParse(token).success) this.fail(trail, `is a malformed token: ${JSON.stringify(token)}.`, scope);
|
|
1072
|
+
switch (tokenKeyOf(token)) {
|
|
1073
|
+
case "$output": return this.output(token, trail, scope);
|
|
1074
|
+
case "$env": return this.env(token.$env, trail, scope);
|
|
1075
|
+
case "$concat": return this.concat(token.$concat, trail, scope);
|
|
1076
|
+
case "$map": return this.map(token.$map, trail, scope);
|
|
1077
|
+
case "$item": return this.item(token.$item, trail, scope);
|
|
1078
|
+
case "$key": return this.key(token.$key, trail, scope);
|
|
1079
|
+
default: return this.fail(trail, `is not a token.`, scope);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
/** The binding an `$item`/`$key` names: the innermost map, or the
|
|
1083
|
+
* enclosing map whose `as` is `name`. */
|
|
1084
|
+
binding(name, operator, trail, scope) {
|
|
1085
|
+
if (scope.length === 0) return this.fail(trail, `uses ${operator} outside any $map; ${operator} reads the element a $map template is rendering.`);
|
|
1086
|
+
if (name === void 0) return scope[scope.length - 1];
|
|
1087
|
+
for (let i = scope.length - 1; i >= 0; i--) if (scope[i].as === name) return scope[i];
|
|
1088
|
+
const named = scope.flatMap((b) => b.as ? [`"${b.as}"`] : []);
|
|
1089
|
+
return this.fail(trail, `uses ${operator} with binding "${name}", which no enclosing $map declares (as: ${named.join(", ") || "none"}).`, scope);
|
|
1090
|
+
}
|
|
1091
|
+
map(operand, trail, scope) {
|
|
1092
|
+
if (!isPlainObject(operand)) return this.fail(trail, "is a malformed $map token.", scope);
|
|
1093
|
+
const into = operand.into === "record";
|
|
1094
|
+
const as = typeof operand.as === "string" ? operand.as : void 0;
|
|
1095
|
+
const read = this.readWithSchema(operand.over, [
|
|
1096
|
+
...trail,
|
|
1097
|
+
"$map",
|
|
1098
|
+
"over"
|
|
1099
|
+
], scope);
|
|
1100
|
+
const over = read.value;
|
|
1101
|
+
if (over === OMIT) return OMIT;
|
|
1102
|
+
const element = read.schema === void 0 ? void 0 : elementSchemaOf(read.schema);
|
|
1103
|
+
const render = (key, item) => {
|
|
1104
|
+
const inner = [...scope, {
|
|
1105
|
+
path: trail,
|
|
1106
|
+
key,
|
|
1107
|
+
item,
|
|
1108
|
+
...as !== void 0 ? { as } : {},
|
|
1109
|
+
...element !== void 0 ? { schema: element } : {}
|
|
1110
|
+
}];
|
|
1111
|
+
const at = [
|
|
1112
|
+
...trail,
|
|
1113
|
+
"$map",
|
|
1114
|
+
"to"
|
|
1115
|
+
];
|
|
1116
|
+
const out = this.value(operand.to, at, inner);
|
|
1117
|
+
if (out === OMIT) return this.fail(at, `is ${this.omitted} as the whole $map template; there is no property to omit.`, inner);
|
|
1118
|
+
return out;
|
|
1119
|
+
};
|
|
1120
|
+
if (Array.isArray(over)) {
|
|
1121
|
+
if (into) return this.fail(trail, `is a $map with into: "record", but its over (${describeToken(operand.over)}) resolved to an array, which has no keys to keep. Drop into: "record" (the result is an array) or map over a record.`, scope);
|
|
1122
|
+
const rendered = over.map((item, index) => render(index, item));
|
|
1123
|
+
renderedKeys.set(rendered, over.map((_, index) => index));
|
|
1124
|
+
return rendered;
|
|
1125
|
+
}
|
|
1126
|
+
if (isPlainObject(over)) {
|
|
1127
|
+
const keys = Object.keys(over).sort();
|
|
1128
|
+
if (!into) {
|
|
1129
|
+
const rendered = keys.map((key) => render(key, over[key]));
|
|
1130
|
+
renderedKeys.set(rendered, keys);
|
|
1131
|
+
return rendered;
|
|
1132
|
+
}
|
|
1133
|
+
const out = {};
|
|
1134
|
+
for (const key of keys) out[key] = render(key, over[key]);
|
|
1135
|
+
return out;
|
|
1136
|
+
}
|
|
1137
|
+
return this.fail(trail, `is a $map whose over (${describeToken(operand.over)}) resolved to ${JSON.stringify(over)}${into ? `; into: "record" needs a record` : ", which is not an array or a record"}.`, scope);
|
|
1138
|
+
}
|
|
1139
|
+
item(operand, trail, scope) {
|
|
1140
|
+
return this.readItem(operand, trail, scope).value;
|
|
1141
|
+
}
|
|
1142
|
+
/** A `$map`'s `over` with the schema describing it, when it reads a
|
|
1143
|
+
* schema'd `$output` (or an `$item` of a schema'd element). */
|
|
1144
|
+
readWithSchema(value, trail, scope) {
|
|
1145
|
+
const key = tokenKeyOf(value);
|
|
1146
|
+
if (isPlainObject(value) && (key === "$output" || key === "$item") && tokenSchema.safeParse(value).success) return key === "$output" ? this.readOutput(value, trail, scope) : this.readItem(value.$item, trail, scope);
|
|
1147
|
+
return { value: this.value(value, trail, scope) };
|
|
1148
|
+
}
|
|
1149
|
+
omit(what) {
|
|
1150
|
+
this.omitted = what;
|
|
1151
|
+
return { value: OMIT };
|
|
1152
|
+
}
|
|
1153
|
+
readItem(operand, trail, scope) {
|
|
1154
|
+
const named = isPlainObject(operand) ? operand : void 0;
|
|
1155
|
+
const name = named && typeof named.as === "string" ? named.as : void 0;
|
|
1156
|
+
const raw = named ? named.path : operand;
|
|
1157
|
+
const path = pathSegments(Array.isArray(raw) ? raw : []);
|
|
1158
|
+
const binding = this.binding(name, "$item", trail, scope);
|
|
1159
|
+
const hit = walkPath(binding.item, path);
|
|
1160
|
+
if (!hit.ok) {
|
|
1161
|
+
if (binding.schema !== void 0 && isOptionalField(binding.schema, path, hit.at)) return this.omit("an absent optional $item field");
|
|
1162
|
+
const missing = formatPath(path.slice(0, hit.at + 1));
|
|
1163
|
+
return this.fail(trail, `reads $item ${formatPath(path)}, but $map element ${elementText(binding)} has no ${missing} (it has: ${hit.has}).`, scope);
|
|
1164
|
+
}
|
|
1165
|
+
return {
|
|
1166
|
+
value: structuredClone(hit.value),
|
|
1167
|
+
schema: schemaOf(binding.schema, path)
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
key(operand, trail, scope) {
|
|
1171
|
+
const name = typeof operand === "string" ? operand : void 0;
|
|
1172
|
+
return this.binding(name, "$key", trail, scope).key;
|
|
1173
|
+
}
|
|
1174
|
+
output(token, trail, scope = []) {
|
|
1175
|
+
return this.readOutput(token, trail, scope).value;
|
|
1176
|
+
}
|
|
1177
|
+
readOutput(token, trail, scope) {
|
|
1178
|
+
const operand = token.$output;
|
|
1179
|
+
if (!isPlainObject(operand) || typeof operand.host !== "string") return this.fail(trail, "is a malformed $output token.", scope);
|
|
1180
|
+
const ref = typeof operand.member === "string" ? {
|
|
1181
|
+
host: operand.host,
|
|
1182
|
+
member: operand.member
|
|
1183
|
+
} : { host: operand.host };
|
|
1184
|
+
const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);
|
|
1185
|
+
if (!this.sources.outputs) return this.fail(trail, `reads ${describeToken(token)}, but no outputs are available here.`, scope);
|
|
1186
|
+
const lookup = this.sources.outputs.lookup(ref);
|
|
1187
|
+
if (lookup.status === "unavailable") throw new TokenResolutionError(`${this.sources.where ? `${this.sources.where}: ` : ""}${lookup.message}\n (needed by \`${formatPath(trail)}\`: ${describeToken(token)})`);
|
|
1188
|
+
const hit = walkPath(lookup.outputs, path);
|
|
1189
|
+
if (!hit.ok) {
|
|
1190
|
+
if (lookup.schema !== void 0 && isOptionalField(lookup.schema, path, hit.at)) return this.omit("an absent optional output");
|
|
1191
|
+
const parent = path.slice(0, hit.at);
|
|
1192
|
+
const container = parent.length ? `outputs.${formatPath(parent)}` : "its outputs";
|
|
1193
|
+
const missing = formatPath(path.slice(0, hit.at + 1));
|
|
1194
|
+
return this.fail(trail, `reads ${describeToken(token)}, but host "${ref.host}" has no output at ${missing} (${container} has: ${hit.has}).`, scope);
|
|
1195
|
+
}
|
|
1196
|
+
return {
|
|
1197
|
+
value: structuredClone(hit.value),
|
|
1198
|
+
schema: schemaOf(lookup.schema, path)
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
env(operand, trail, scope = []) {
|
|
1202
|
+
const optional = isPlainObject(operand);
|
|
1203
|
+
const name = optional ? operand.name : operand;
|
|
1204
|
+
if (typeof name !== "string") return this.fail(trail, "is a malformed $env token.", scope);
|
|
1205
|
+
const builtins = this.sources.builtins;
|
|
1206
|
+
if ((name === "userData" || name === "projectRoot") && builtins?.[name]) return builtins[name];
|
|
1207
|
+
const value = this.sources.env?.[name];
|
|
1208
|
+
if (value !== void 0) return value;
|
|
1209
|
+
if (optional) return this.omit("an optional $env").value;
|
|
1210
|
+
return this.fail(trail, `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: "${name}", optional: true } } to omit the property when unset).`, scope);
|
|
1211
|
+
}
|
|
1212
|
+
concat(parts, trail, scope = []) {
|
|
1213
|
+
if (!Array.isArray(parts)) return this.fail(trail, "is a malformed $concat token.", scope);
|
|
1214
|
+
return parts.map((part, index) => {
|
|
1215
|
+
const at = [
|
|
1216
|
+
...trail,
|
|
1217
|
+
"$concat",
|
|
1218
|
+
index
|
|
1219
|
+
];
|
|
1220
|
+
const value = this.value(part, at, scope);
|
|
1221
|
+
if (value === OMIT) return this.fail(at, `is ${this.omitted} inside $concat.`, scope);
|
|
1222
|
+
if (typeof value === "string") return value;
|
|
1223
|
+
if (typeof value === "number") return String(value);
|
|
1224
|
+
return this.fail(at, `resolved to ${JSON.stringify(value)}; every $concat part must be a string or a number.`, scope);
|
|
1225
|
+
}).join("");
|
|
1226
|
+
}
|
|
1227
|
+
};
|
|
1228
|
+
function resolveHostOutputs(host, sources, options) {
|
|
1229
|
+
const resolver = new Resolver(sources, options?.deferSelf);
|
|
1230
|
+
const out = resolver.value(host, []);
|
|
1231
|
+
if (out === OMIT) resolver.fail([], `is ${resolver.omitted} with nothing to omit it from.`);
|
|
1232
|
+
const partial = out;
|
|
1233
|
+
if (!options) return partial;
|
|
1234
|
+
const sites = resolver.deferred;
|
|
1235
|
+
return {
|
|
1236
|
+
host: partial,
|
|
1237
|
+
deferred: sites.map((d) => ({
|
|
1238
|
+
path: formatPath(d.trail),
|
|
1239
|
+
members: d.members
|
|
1240
|
+
})),
|
|
1241
|
+
needs: [...new Set(sites.flatMap((d) => d.members))],
|
|
1242
|
+
finish(outputs) {
|
|
1243
|
+
const done = cloneWithProvenance(partial);
|
|
1244
|
+
const late = new Resolver({
|
|
1245
|
+
...sources,
|
|
1246
|
+
outputs
|
|
1247
|
+
});
|
|
1248
|
+
for (const site of sites) {
|
|
1249
|
+
const value = late.token(site.token, site.trail);
|
|
1250
|
+
if (value === OMIT && typeof site.trail.at(-1) === "number") late.fail(site.trail, `is ${late.omitted} inside an array.`);
|
|
1251
|
+
setAt(done, site.trail, value === OMIT ? void 0 : value, value === OMIT);
|
|
1252
|
+
}
|
|
1253
|
+
return done;
|
|
1254
|
+
}
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
function setAt(root, trail, value, omit) {
|
|
1258
|
+
let current = root;
|
|
1259
|
+
for (const key of trail.slice(0, -1)) if (Array.isArray(current) && typeof key === "number") current = current[key];
|
|
1260
|
+
else if (isPlainObject(current) && typeof key === "string") current = current[key];
|
|
1261
|
+
else return;
|
|
1262
|
+
const last = trail[trail.length - 1];
|
|
1263
|
+
if (Array.isArray(current) && typeof last === "number") current[last] = value;
|
|
1264
|
+
else if (isPlainObject(current) && typeof last === "string") {
|
|
1265
|
+
if (omit) delete current[last];
|
|
1266
|
+
else current[last] = value;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
//#endregion
|
|
1270
|
+
//#region src/resolve/removed-forms.ts
|
|
1271
|
+
function outputToken(host, path, member) {
|
|
1272
|
+
return `{ $output: { host: "${host}"${member ? `, member: "${member}"` : ""}, path: [${path.map((p) => JSON.stringify(p)).join(", ")}] } }`;
|
|
1273
|
+
}
|
|
1274
|
+
function isDriveReference(value) {
|
|
1275
|
+
if (!isPlainObject(value)) return false;
|
|
1276
|
+
const keys = Object.keys(value).sort();
|
|
1277
|
+
return keys.length === 2 && keys[0] === "from" && keys[1] === "slug" && typeof value.from === "string" && typeof value.slug === "string";
|
|
1278
|
+
}
|
|
1279
|
+
function checkReactor(reactor, base, found) {
|
|
1280
|
+
if (!isPlainObject(reactor) || !isPlainObject(reactor.backends)) return;
|
|
1281
|
+
for (const [name, backend] of Object.entries(reactor.backends)) {
|
|
1282
|
+
if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;
|
|
1283
|
+
const host = backend.remote.host;
|
|
1284
|
+
if (host === void 0) continue;
|
|
1285
|
+
const producer = typeof host === "string" ? host : "switchboard";
|
|
1286
|
+
found.push({
|
|
1287
|
+
path: `${base}reactor.backends.${name}.remote.host`,
|
|
1288
|
+
message: `remote: { host } was removed; use remote: { url: ${producer}.endpoints.graphql } with ${producer} from ../${producer}/outputs.js, or remote: { url: ${outputToken(producer, ["endpoints", "graphql"])} }.`
|
|
1289
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
function checkPlugins(runner, base, memberHosts, found) {
|
|
1293
|
+
if (!isPlainObject(runner) || !Array.isArray(runner.plugins)) return;
|
|
1294
|
+
runner.plugins.forEach((entry, index) => {
|
|
1295
|
+
if (!isPlainObject(entry) || !isPlainObject(entry.config)) return;
|
|
1296
|
+
for (const [key, value] of Object.entries(entry.config)) {
|
|
1297
|
+
if (!isDriveReference(value)) continue;
|
|
1298
|
+
const host = memberHosts[value.from] ?? value.from;
|
|
1299
|
+
const member = memberHosts[value.from] ? value.from : void 0;
|
|
1300
|
+
found.push({
|
|
1301
|
+
path: `${base}runner.plugins[${index}].config.${key}`,
|
|
1302
|
+
message: `${key}: { from, slug } was removed; use ${host}.drives.${value.slug}.url from ../${host}/outputs.js, or ${outputToken(host, [
|
|
1303
|
+
"drives",
|
|
1304
|
+
value.slug,
|
|
1305
|
+
"url"
|
|
1306
|
+
])}${member ? ` (add member: "${member}" if two members run host "${host}")` : ""}.`
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
/** Every removed form in a host file (reactor or compound), in document
|
|
1312
|
+
* order. Compound wrappers are checked too. */
|
|
1313
|
+
function findRemovedForms(host) {
|
|
1314
|
+
const found = [];
|
|
1315
|
+
if (!isPlainObject(host)) return found;
|
|
1316
|
+
const children = isPlainObject(host.children) ? host.children : void 0;
|
|
1317
|
+
const memberHosts = {};
|
|
1318
|
+
for (const [key, wrapper] of Object.entries(children ?? {})) if (isPlainObject(wrapper) && typeof wrapper.host === "string") memberHosts[key] = wrapper.host;
|
|
1319
|
+
checkReactor(host.reactor, "", found);
|
|
1320
|
+
checkPlugins(host.runner, "", memberHosts, found);
|
|
1321
|
+
for (const [key, wrapper] of Object.entries(children ?? {})) {
|
|
1322
|
+
if (!isPlainObject(wrapper)) continue;
|
|
1323
|
+
checkReactor(wrapper.reactor, `children.${key}.`, found);
|
|
1324
|
+
checkPlugins(wrapper.runner, `children.${key}.`, memberHosts, found);
|
|
1325
|
+
}
|
|
1326
|
+
if (children && isPlainObject(host.config)) for (const key of ["projectDrivesIntoConnect", "drivesPublicBase"]) {
|
|
1327
|
+
if (host.config[key] === void 0) continue;
|
|
1328
|
+
found.push({
|
|
1329
|
+
path: `config.${key}`,
|
|
1330
|
+
message: `config.${key} was removed; declare the drives on the member that consumes them, by output token: reactor.drives: [{ slug: "<slug>", remote: { url: ${outputToken("switchboard", [
|
|
1331
|
+
"drives",
|
|
1332
|
+
"<slug>",
|
|
1333
|
+
"url"
|
|
1334
|
+
])} } }].`
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
return found;
|
|
1338
|
+
}
|
|
1339
|
+
//#endregion
|
|
1340
|
+
//#region src/resolve/sources.ts
|
|
1341
|
+
/**
|
|
1342
|
+
* The compound output source: a member's `$output` tokens read the live
|
|
1343
|
+
* `RunnerHandle.outputs` of the members started before it. `schemas` (member
|
|
1344
|
+
* key → its runner's `outputsSchema`) lets an absent optional output field
|
|
1345
|
+
* omit the consuming property. Pure (the run-record source for standalone
|
|
1346
|
+
* hosts is node: ./node.ts).
|
|
1347
|
+
*/
|
|
1348
|
+
function compoundOutputSource(members, started, compound, schemas) {
|
|
1349
|
+
return { lookup(ref) {
|
|
1350
|
+
const target = memberForRef(ref, members);
|
|
1351
|
+
if ("error" in target) return {
|
|
1352
|
+
status: "unavailable",
|
|
1353
|
+
message: `compound "${compound}": a token ${target.error}`
|
|
1354
|
+
};
|
|
1355
|
+
if (!started.has(target.key)) return {
|
|
1356
|
+
status: "unavailable",
|
|
1357
|
+
message: `compound "${compound}": member "${target.key}" (host "${ref.host}") has not started yet; a producer must start before its consumers.`
|
|
1358
|
+
};
|
|
1359
|
+
const schema = schemas?.get(target.key);
|
|
1360
|
+
return {
|
|
1361
|
+
status: "available",
|
|
1362
|
+
outputs: started.get(target.key),
|
|
1363
|
+
...schema !== void 0 ? { schema } : {}
|
|
1364
|
+
};
|
|
1365
|
+
} };
|
|
1366
|
+
}
|
|
1367
|
+
//#endregion
|
|
1368
|
+
//#region src/expect-host.ts
|
|
1369
|
+
function isRecord(value) {
|
|
1370
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1371
|
+
}
|
|
1372
|
+
function runnerOf(host) {
|
|
1373
|
+
return isRecord(host.runner) ? host.runner : {};
|
|
1374
|
+
}
|
|
1375
|
+
function defaultVerbOf(host) {
|
|
1376
|
+
const verb = runnerOf(host).defaultVerb;
|
|
1377
|
+
return typeof verb === "string" ? verb : void 0;
|
|
1378
|
+
}
|
|
1379
|
+
/** At compound verb "run" each member runs its own defaultVerb; any other
|
|
1380
|
+
* compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */
|
|
1381
|
+
function memberVerb(compoundVerb, member) {
|
|
1382
|
+
return compoundVerb === "run" ? defaultVerbOf(member) ?? "run" : compoundVerb;
|
|
1383
|
+
}
|
|
1384
|
+
/** Backend names, placement-primary first (`backendsToDescriptors` order). */
|
|
1385
|
+
function orderedBackends(reactor) {
|
|
1386
|
+
const backends = Object.entries(reactor.backends ?? {});
|
|
1387
|
+
const primary = reactor.placement?.primary;
|
|
1388
|
+
return [...backends.filter(([name]) => name === primary), ...backends.filter(([name]) => name !== primary)];
|
|
1389
|
+
}
|
|
1390
|
+
function expectBackend(name, backend, reactor) {
|
|
1391
|
+
const out = {
|
|
1392
|
+
name,
|
|
1393
|
+
kind: backend.kind
|
|
1394
|
+
};
|
|
1395
|
+
if (backend.storage) out.storage = backend.storage.kind;
|
|
1396
|
+
if (typeof backend.storage?.dataDir === "string") out.dataDir = backend.storage.dataDir;
|
|
1397
|
+
try {
|
|
1398
|
+
backendToDescriptor(name, backend, reactor.protocol);
|
|
1399
|
+
} catch (error) {
|
|
1400
|
+
out.provisionError = error instanceof Error ? error.message : String(error);
|
|
1401
|
+
}
|
|
1402
|
+
return out;
|
|
1403
|
+
}
|
|
1404
|
+
function expectDrive(declaration, source) {
|
|
1405
|
+
if (typeof declaration.slug !== "string") return void 0;
|
|
1406
|
+
const remote = isRecord(declaration.remote) ? declaration.remote : void 0;
|
|
1407
|
+
const drive = {
|
|
1408
|
+
slug: declaration.slug,
|
|
1409
|
+
kind: remote ? "remote" : "local",
|
|
1410
|
+
source
|
|
1411
|
+
};
|
|
1412
|
+
if (remote && typeof remote.url === "string") drive.url = remote.url;
|
|
1413
|
+
if (typeof declaration.id === "string") drive.id = declaration.id;
|
|
1414
|
+
const projectHash = declaration.projectHash;
|
|
1415
|
+
if (typeof projectHash === "boolean" || projectHash === "id") drive.projectHash = projectHash;
|
|
1416
|
+
return drive;
|
|
1417
|
+
}
|
|
1418
|
+
/** The key `mergeDrivePlan` merges on: the SERVED slug, which for
|
|
1419
|
+
* `projectHash: true` is the hashed id (never equal to a plain slug). */
|
|
1420
|
+
function servedSlugKey(drive) {
|
|
1421
|
+
return drive.projectHash === true ? `${drive.slug}\0hashed` : drive.slug;
|
|
1422
|
+
}
|
|
1423
|
+
/** Contributions first, then host declarations; keyed by served slug, the
|
|
1424
|
+
* host wins (and keeps the contribution's position), like `mergeDrivePlan`. */
|
|
1425
|
+
function drivePlan(reactor, contributed) {
|
|
1426
|
+
const plan = /* @__PURE__ */ new Map();
|
|
1427
|
+
for (const { declaration, source } of contributed) {
|
|
1428
|
+
const drive = expectDrive(declaration, source);
|
|
1429
|
+
if (drive) plan.set(servedSlugKey(drive), drive);
|
|
1430
|
+
}
|
|
1431
|
+
for (const declaration of reactor?.drives ?? []) {
|
|
1432
|
+
const drive = expectDrive(declaration, "host");
|
|
1433
|
+
if (drive) plan.set(servedSlugKey(drive), drive);
|
|
1434
|
+
}
|
|
1435
|
+
return [...plan.values()];
|
|
1436
|
+
}
|
|
1437
|
+
/** Token facts of the host's OWN fields (a compound's `children` are its
|
|
1438
|
+
* members' own). */
|
|
1439
|
+
function tokenFacts(declared, kind) {
|
|
1440
|
+
const own = kind === "compound" ? Object.fromEntries(Object.entries(declared).filter(([key]) => key !== "children")) : declared;
|
|
1441
|
+
const sites = outputSitesOf(own);
|
|
1442
|
+
const consumes = sites.map(({ path, ref, outputPath }) => ({
|
|
1443
|
+
at: path,
|
|
1444
|
+
host: ref.host,
|
|
1445
|
+
...ref.member !== void 0 ? { member: ref.member } : {},
|
|
1446
|
+
path: outputPath
|
|
1447
|
+
}));
|
|
1448
|
+
return {
|
|
1449
|
+
dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),
|
|
1450
|
+
consumes,
|
|
1451
|
+
env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort()
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
function expectOwn(input, verb) {
|
|
1455
|
+
const resolved = input.resolved ?? input.declared;
|
|
1456
|
+
const expectation = {
|
|
1457
|
+
name: typeof resolved.name === "string" ? resolved.name : "",
|
|
1458
|
+
kind: input.kind,
|
|
1459
|
+
verb,
|
|
1460
|
+
...tokenFacts(input.declared, input.kind)
|
|
1461
|
+
};
|
|
1462
|
+
if (input.kind !== "reactor") return expectation;
|
|
1463
|
+
const reactor = isRecord(resolved.reactor) ? resolved.reactor : void 0;
|
|
1464
|
+
const mode = reactorClientMode(reactor);
|
|
1465
|
+
if (mode !== void 0) expectation.clientMode = mode;
|
|
1466
|
+
expectation.multiReactor = isStructuralMultiReactor(reactor);
|
|
1467
|
+
const backends = reactor ? orderedBackends(reactor) : [];
|
|
1468
|
+
if (reactor && backends.length > 0) {
|
|
1469
|
+
expectation.backends = backends.map(([name, backend]) => expectBackend(name, backend, reactor));
|
|
1470
|
+
expectation.remotes = backends.flatMap(([, backend]) => backend.kind === "remote" && typeof backend.remote?.url === "string" ? [backend.remote.url] : []);
|
|
1471
|
+
}
|
|
1472
|
+
expectation.drives = drivePlan(reactor, input.contributed ?? []);
|
|
1473
|
+
return expectation;
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* The expectation for one host. A reactor host's comes from its resolved
|
|
1477
|
+
* reactor block and contributed drives; a compound's lists its members in
|
|
1478
|
+
* plan order, each with the verb it runs at under the compound's own verb
|
|
1479
|
+
* and the members it starts after.
|
|
1480
|
+
*/
|
|
1481
|
+
function expectHost(input) {
|
|
1482
|
+
const verb = defaultVerbOf(input.declared) ?? "run";
|
|
1483
|
+
const expectation = expectOwn(input, verb);
|
|
1484
|
+
if (input.kind !== "compound" || !input.members) return expectation;
|
|
1485
|
+
const order = input.plan?.order ?? input.members.map((m) => m.key);
|
|
1486
|
+
const edges = input.plan?.edges ?? [];
|
|
1487
|
+
const byKey = new Map(input.members.map((m) => [m.key, m]));
|
|
1488
|
+
const members = {};
|
|
1489
|
+
for (const key of order) {
|
|
1490
|
+
const member = byKey.get(key);
|
|
1491
|
+
if (!member) continue;
|
|
1492
|
+
members[key] = {
|
|
1493
|
+
host: member.host,
|
|
1494
|
+
...expectOwn(member, memberVerb(verb, member.declared)),
|
|
1495
|
+
after: [...new Set(edges.filter((e) => e.consumer === key).map((e) => e.producer))].sort()
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
expectation.startOrder = order.filter((key) => byKey.has(key));
|
|
1499
|
+
expectation.members = members;
|
|
1500
|
+
return expectation;
|
|
1501
|
+
}
|
|
1502
|
+
//#endregion
|
|
1503
|
+
export { PlanError, TokenResolutionError, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, checkOutputPaths, checkTokenSites, collectTokenSites, compoundOutputSource, describeMapElements, describeToken, envSitesOf, expectHost, findRemovedForms, formatPath, isStructuralMultiReactor, memberForRef, mergeDefaultDrives, outputRefsOf, outputSitesOf, planCompound, primaryBackend, projectDrivesIntoConnect, projectReactorToConnect, projectReactorToSwitchboard, protocolEnv, reactorClientMode, rebaseDriveUrl, refKey, remoteBackendUrls, renderTokens, resolveHostOutputs, runRecordMemberSchema, runRecordSchema, schemaAtPath, unwrapEscapes };
|
|
1504
|
+
|
|
1505
|
+
//# sourceMappingURL=projection.mjs.map
|