@prisma/composer 0.1.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.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/dist/app-config-BUqyK6N6-CVq3uvHF.d.mts +188 -0
  3. package/dist/assertions.d.mts +31 -0
  4. package/dist/assertions.mjs +35 -0
  5. package/dist/assertions.mjs.map +1 -0
  6. package/dist/bin.mjs +1134 -0
  7. package/dist/bin.mjs.map +1 -0
  8. package/dist/casts-Ci5rYYaR.mjs +82 -0
  9. package/dist/casts-Ci5rYYaR.mjs.map +1 -0
  10. package/dist/casts.d.mts +78 -0
  11. package/dist/casts.mjs +2 -0
  12. package/dist/config-BVVgDSdq.d.mts +1 -0
  13. package/dist/config-ob5OhCSP-sP3GW3uu.d.mts +477 -0
  14. package/dist/config.d.mts +2 -0
  15. package/dist/config.mjs +9 -0
  16. package/dist/config.mjs.map +1 -0
  17. package/dist/deploy-BVVgDSdq.d.mts +1 -0
  18. package/dist/deploy.d.mts +2 -0
  19. package/dist/deploy.mjs +154 -0
  20. package/dist/deploy.mjs.map +1 -0
  21. package/dist/dist-zBU8ASQW.mjs +181 -0
  22. package/dist/dist-zBU8ASQW.mjs.map +1 -0
  23. package/dist/graph-BYdCQKya-BI0njTow.mjs +595 -0
  24. package/dist/graph-BYdCQKya-BI0njTow.mjs.map +1 -0
  25. package/dist/index-CZSc9drz.d.mts +47 -0
  26. package/dist/index-Dh4Zro0y.d.mts +15 -0
  27. package/dist/index.d.mts +3 -0
  28. package/dist/index.mjs +3 -0
  29. package/dist/nextjs-control.d.mts +13 -0
  30. package/dist/nextjs-control.mjs +108 -0
  31. package/dist/nextjs-control.mjs.map +1 -0
  32. package/dist/nextjs.d.mts +2 -0
  33. package/dist/nextjs.mjs +12 -0
  34. package/dist/nextjs.mjs.map +1 -0
  35. package/dist/node-control.d.mts +9 -0
  36. package/dist/node-control.mjs +70 -0
  37. package/dist/node-control.mjs.map +1 -0
  38. package/dist/node.d.mts +10 -0
  39. package/dist/node.mjs +11 -0
  40. package/dist/node.mjs.map +1 -0
  41. package/dist/rpc.d.mts +43 -0
  42. package/dist/rpc.mjs +132 -0
  43. package/dist/rpc.mjs.map +1 -0
  44. package/dist/testing.d.mts +24 -0
  45. package/dist/testing.mjs +45 -0
  46. package/dist/testing.mjs.map +1 -0
  47. package/dist/tsdown.d.mts +9 -0
  48. package/dist/tsdown.mjs +35 -0
  49. package/dist/tsdown.mjs.map +1 -0
  50. package/package.json +68 -0
package/dist/bin.mjs ADDED
@@ -0,0 +1,1134 @@
1
+ #!/usr/bin/env node
2
+ import { Cli, Command, Option, UsageError } from "clipanion";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import * as Layer from "effect/Layer";
7
+ import { createManagementApiClient } from "@prisma/management-api-sdk";
8
+ import * as Context from "effect/Context";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Redacted from "effect/Redacted";
11
+ import * as Config from "effect/Config";
12
+ import * as Data from "effect/Data";
13
+ import * as Provider from "alchemy/Provider";
14
+ import { Resource } from "alchemy";
15
+ import * as Schedule from "effect/Schedule";
16
+ import * as c12 from "c12";
17
+ import { pathToFileURL } from "node:url";
18
+ //#region ../../0-framework/3-tooling/assemble/dist/index.mjs
19
+ /**
20
+ * A user-facing assembly failure with a message that already names the fix
21
+ * (mirrors @internal/cli's CliError contract). This package must not import
22
+ * CliError — its second consumer is the future programmatic deploy API, not
23
+ * just the CLI — so it throws its own typed error; the CLI maps it (or lets
24
+ * it propagate, since bin.ts already treats every Error uniformly: print the
25
+ * message, exit nonzero).
26
+ */
27
+ var AssembleError = class extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "AssembleError";
31
+ }
32
+ };
33
+ /**
34
+ * The wrapper-inlining decision (S2's open question — see the project's
35
+ * design-notes.md and this slice's final report for the write-up).
36
+ *
37
+ * The CLI has no config file, so it can't take per-app `wrapperNoExternal`
38
+ * patterns — it needs one general rule for what an assembler inlines into
39
+ * the wrapper build besides `@prisma/*` (already the assemblers' own
40
+ * default).
41
+ *
42
+ * The rule: inline everything except the runtime's own modules — `bun`,
43
+ * `bun:*` (e.g. bun:sqlite), and `node:*` builtins — which resolve inside
44
+ * the deploy VM at runtime and must never be bundled. Verified (both
45
+ * `@prisma/composer/node/control` and `@prisma/composer/nextjs/control` set
46
+ * `external: ['bun']` ahead of `noExternal` in their tsdown call, and tsdown/
47
+ * rolldown's explicit `external` wins over a `noExternal` match — proven by
48
+ * building an app's wrapper with this exact pattern: the
49
+ * `bun` import stays external while everything else, including the app's own
50
+ * workspace deps, gets inlined) — see this slice's final report for the
51
+ * storefront-auth wrapper proof (arktype + `@storefront-auth/auth/contract`
52
+ * inlined with no other file changes there).
53
+ */
54
+ const INLINE_EVERYTHING_EXCEPT_RUNTIME_BUILTINS = [/^(?!bun$)(?!bun:)(?!node:).+/];
55
+ /**
56
+ * The registry route for one service's build: descriptor by
57
+ * `build.extension`, control by `build.type`, kind must be "build". The CLI's
58
+ * coverage validation reports the same misses earlier with the config fix;
59
+ * these errors are the backstop for programmatic callers.
60
+ */
61
+ function buildControlAssemble(config, node, address, cwd) {
62
+ const { extension, type } = node.build;
63
+ const descriptor = config.extensions.find((candidate) => candidate.id === extension);
64
+ if (descriptor === void 0) throw new AssembleError(`No extension "${extension}" is configured (needed by service "${node.name}"'s build) — add it to prisma-composer.config.ts's \`extensions\`.`);
65
+ const control = descriptor.nodes[type];
66
+ if (control === void 0) throw new AssembleError(`Extension "${extension}" has no control for build type "${type}" (known: ${Object.keys(descriptor.nodes).join(", ")}).`);
67
+ if (control.kind !== "build") throw new AssembleError(`Extension "${extension}"'s control for type "${type}" is a "${control.kind}" control — a service build descriptor needs a "build" control.`);
68
+ return control.assemble({
69
+ build: node.build,
70
+ wrapperNoExternal: INLINE_EVERYTHING_EXCEPT_RUNTIME_BUILTINS,
71
+ address,
72
+ cwd
73
+ });
74
+ }
75
+ async function assembleServices(graph, config, cwd, run) {
76
+ const runAssembler = run ?? ((node, address, nodeCwd) => buildControlAssemble(config, node, address, nodeCwd));
77
+ const serviceNodes = graph.nodes.filter((n) => n.node.kind === "service");
78
+ if (serviceNodes.length === 0) throw new AssembleError("The loaded graph has no service to assemble.");
79
+ const bundles = {};
80
+ for (const { id, node } of serviceNodes) bundles[id] = await runAssembler(node, id, cwd);
81
+ return { bundles };
82
+ }
83
+ //#endregion
84
+ //#region ../../0-framework/0-foundation/foundation/dist/casts.mjs
85
+ /**
86
+ * **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**
87
+ *
88
+ * Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes
89
+ * unnecessary**: tighten an input type, add a runtime check that narrows via a type
90
+ * predicate, restructure a generic so the compiler can see the relationship you're
91
+ * asserting, or use {@link castAs} when the value already satisfies the target type.
92
+ * Only when no rewrite is feasible does `blindCast` become the right answer — and at
93
+ * that point, the `Reason` literal you supply must articulate the compromise in
94
+ * language a reviewer can evaluate.
95
+ *
96
+ * The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,
97
+ * that is not a signal to soften the reason; it is a signal to go back and solve the
98
+ * underlying type-system problem properly. An unconvincing justification is rework,
99
+ * not a free pass.
100
+ *
101
+ * `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses
102
+ * the compiler's checks (the input type is `unknown`, the output type is whatever the
103
+ * caller asks for), but it forces the unsafety to be named at the call site instead of
104
+ * smuggled in via a bare `as`. The `Reason` type parameter exists only at compile
105
+ * time — it is not present in the emitted JavaScript — but it is grep-able and
106
+ * visible to future readers.
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const stringValue = blindCast<
111
+ * string,
112
+ * "JSON.parse returns `unknown`; this field is documented to be a string in the API contract"
113
+ * >(parsed[key]);
114
+ * ```
115
+ *
116
+ * @typeParam TargetType - The type the caller is asserting the input has.
117
+ * @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.
118
+ * Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.
119
+ */
120
+ function blindCast(input) {
121
+ return input;
122
+ }
123
+ //#endregion
124
+ //#region ../../0-framework/1-core/core/dist/graph-BYdCQKya.mjs
125
+ /** Thrown by Load when the graph is malformed. */
126
+ var LoadError = class extends Error {
127
+ constructor(message) {
128
+ super(message);
129
+ this.name = "LoadError";
130
+ }
131
+ };
132
+ /**
133
+ * Core model: node types and the factories that construct them, plain frozen
134
+ * data objects. A node's `extension` + `type` form its deploy-time registry key (ADR-0017).
135
+ */
136
+ const NODE = Symbol.for("prisma:node");
137
+ const SECRET_SOURCE = blindCast(Symbol.for("prisma:secret-source"));
138
+ /** True if `value` is a secret source (an `envSecret` result or a forwarded ctx.secrets ref). */
139
+ function isSecretSource(value) {
140
+ return typeof value === "object" && value !== null && blindCast(value)[SECRET_SOURCE] === true;
141
+ }
142
+ /**
143
+ * True if `value` was constructed by this module's factories. Checks the
144
+ * brand only, never a prototype — a graph may mix nodes from a different
145
+ * installed copy of core (dual-package hazard).
146
+ */
147
+ function isNode(value) {
148
+ return typeof value === "object" && value !== null && value[NODE] === true;
149
+ }
150
+ /**
151
+ * Stable topological sort: every edge's `from` precedes its `to` in the
152
+ * result. Ties (nodes with no ordering constraint between them) keep their
153
+ * relative order from `nodes` — so a graph already authored producer-first
154
+ * comes out byte-identical to its pre-sort layout; only a graph that
155
+ * genuinely needs reordering (e.g. a module wired via a forged ref pointing at a
156
+ * not-yet-provisioned producer) actually moves. A Kahn's-algorithm variant
157
+ * that always picks the ready node with the smallest original index. Edges
158
+ * whose endpoint falls outside `nodes` (e.g. a service-root's input edges
159
+ * targeting the root, which is appended separately) are ignored. Cycles
160
+ * cannot reach here: `assertDependencyDag` already rejects them for
161
+ * dependency edges, and input edges never cycle.
162
+ */
163
+ function topoSort(nodes, edges) {
164
+ const byId = new Map(nodes.map((n) => [n.id, n]));
165
+ const indexOf = new Map(nodes.map((n, i) => [n.id, i]));
166
+ const indegree = new Map(nodes.map((n) => [n.id, 0]));
167
+ const successors = /* @__PURE__ */ new Map();
168
+ for (const edge of edges) {
169
+ if (!byId.has(edge.from) || !byId.has(edge.to)) continue;
170
+ const targets = successors.get(edge.from) ?? [];
171
+ targets.push(edge.to);
172
+ successors.set(edge.from, targets);
173
+ indegree.set(edge.to, (indegree.get(edge.to) ?? 0) + 1);
174
+ }
175
+ const ready = new Set(nodes.filter((n) => indegree.get(n.id) === 0).map((n) => n.id));
176
+ const order = [];
177
+ while (ready.size > 0) {
178
+ let next;
179
+ let bestIndex = Number.POSITIVE_INFINITY;
180
+ for (const id of ready) {
181
+ const index = indexOf.get(id) ?? Number.POSITIVE_INFINITY;
182
+ if (index < bestIndex) {
183
+ bestIndex = index;
184
+ next = id;
185
+ }
186
+ }
187
+ if (next === void 0) break;
188
+ ready.delete(next);
189
+ order.push(next);
190
+ for (const target of successors.get(next) ?? []) {
191
+ const remaining = (indegree.get(target) ?? 0) - 1;
192
+ indegree.set(target, remaining);
193
+ if (remaining === 0) ready.add(target);
194
+ }
195
+ }
196
+ if (order.length !== nodes.length) throw new LoadError(`topological sort processed ${order.length} of ${nodes.length} nodes — the graph contains a cycle that slipped past the DAG validation.`);
197
+ return order.map((id) => byId.get(id)).filter((n) => n !== void 0);
198
+ }
199
+ function serviceInputs(service, serviceId) {
200
+ if (typeof service.inputs !== "object" || service.inputs === null) throw new LoadError(`Service "${serviceId}" has no inputs map.`);
201
+ const nodes = [];
202
+ const edges = [];
203
+ for (const [input, value] of Object.entries(service.inputs)) {
204
+ const kind = isNode(value) ? value.kind : void 0;
205
+ if (kind === "resource") throw new LoadError(`Input "${input}" of "${serviceId}" is a resource node — a resource is provisioned by the composing module, never created for a service that mentions it. Declare the input as a dependency (the pack's dependency factory) and wire the module-provisioned resource's ref into it.`);
206
+ if (kind !== "dependency") throw new LoadError(`Input "${input}" of "${serviceId}" is not a branded dependency end (construct it with the dependency() factory).`);
207
+ if (value.type.length === 0) throw new LoadError(`Input "${input}" of "${serviceId}" has an empty node type.`);
208
+ const id = `${serviceId}.${input}`;
209
+ nodes.push({
210
+ id,
211
+ node: value
212
+ });
213
+ edges.push({
214
+ from: id,
215
+ to: serviceId,
216
+ input,
217
+ kind: "input"
218
+ });
219
+ }
220
+ return {
221
+ nodes,
222
+ edges
223
+ };
224
+ }
225
+ function loadService(root, rootId) {
226
+ for (const [input, value] of Object.entries(root.inputs)) if (isNode(value) && value.kind === "dependency") throw new LoadError(`Service "${rootId}" has an unwired dependency input "${input}" — this service is composed by a module; deploy the module instead of loading "${rootId}" directly.`);
227
+ const secretSlots = Object.keys(root.secretSlots);
228
+ if (secretSlots.length > 0) {
229
+ const names = secretSlots.map((k) => `"${k}"`).join(", ");
230
+ throw new LoadError(`Service "${rootId}" declares secret slot${secretSlots.length > 1 ? "s" : ""} ${names} but is being loaded directly — a lone service has no enclosing scope to bind them. Compose it inside a module that binds each with envSecret('NAME').`);
231
+ }
232
+ const rootGraphNode = {
233
+ id: rootId,
234
+ node: root
235
+ };
236
+ const { nodes, edges } = serviceInputs(root, rootId);
237
+ return {
238
+ root: rootGraphNode,
239
+ nodes: [...topoSort(nodes, edges), rootGraphNode],
240
+ edges,
241
+ secrets: []
242
+ };
243
+ }
244
+ /**
245
+ * Builds the ref a provision() call hands back: the id (so a producer with no
246
+ * exposed ports — or an untyped slot — can still be wired wholesale) plus one
247
+ * ref-port per exposed contract, each the contract's own runtime value (so
248
+ * its `satisfies()` still works) tagged with the provider's id.
249
+ */
250
+ function refFor(id, service) {
251
+ const ports = {};
252
+ for (const [port, contract] of Object.entries(service.expose ?? {})) ports[port] = {
253
+ ...contract,
254
+ __providerId: id
255
+ };
256
+ return blindCast({
257
+ id,
258
+ ...ports
259
+ });
260
+ }
261
+ /**
262
+ * The resource variant of refFor: a resource has exactly one port — the
263
+ * contract it provides — flattened onto the ref itself, tagged with the
264
+ * provider id. `id` is written last so a hostile contract value cannot
265
+ * clobber it.
266
+ */
267
+ function refForResource(id, resource) {
268
+ return blindCast({
269
+ ...resource.provides,
270
+ __providerId: id,
271
+ id
272
+ });
273
+ }
274
+ /** A wired value's producer id: a ref-port's `__providerId`, or a bare ref's `id`. */
275
+ function producerIdOf(ref) {
276
+ if (typeof ref !== "object" || ref === null) return void 0;
277
+ if ("__providerId" in ref && typeof ref.__providerId === "string") return ref.__providerId;
278
+ if ("id" in ref && typeof ref.id === "string") return ref.id;
279
+ }
280
+ /**
281
+ * Brands each `ctx.inputs` entry with the input key it stands for (see
282
+ * flatten): diagnostic only — usage attribution relies on the per-key object
283
+ * identity the branding copy creates, never on reading this back.
284
+ */
285
+ const MODULE_INPUT_KEY = Symbol("prisma:module-input-key");
286
+ /** Same per-key identity trick as MODULE_INPUT_KEY, for the parallel `ctx.secrets` forwarding channel. */
287
+ const MODULE_SECRET_KEY = Symbol("prisma:module-secret-key");
288
+ /** Whether `ref` carries a callable `satisfies` that accepts `required` truthily. */
289
+ function satisfiesRequired(ref, required) {
290
+ return typeof ref === "object" && ref !== null && "satisfies" in ref && typeof ref.satisfies === "function" && ref.satisfies(required);
291
+ }
292
+ /**
293
+ * Checks one recorded `wiring` object against the Deps it was wired against:
294
+ * every named input exists and is a dependency slot, every referenced
295
+ * producer is a real (by-now-provisioned) address, and a wired ref whose
296
+ * slot declares a required contract must satisfy() it — no producer-kind
297
+ * branching, the contract alone determines validity, whether the producer is
298
+ * a service port or a resource. Shared by both provisioned kinds so a
299
+ * module-as-child gets exactly the checks a service gets, and run once per
300
+ * entry against the one `byId` shared by the whole recursive flatten, so a
301
+ * forwarded ref resolves through to its real producer address regardless of
302
+ * which ancestor scope provisioned it.
303
+ */
304
+ function validateWiring(pending, byId) {
305
+ const { deps, wiring, targetId, targetKind, enclosingModuleName } = pending;
306
+ for (const [input, ref] of Object.entries(wiring)) {
307
+ const declared = blindCast(deps[input]);
308
+ if (declared === void 0 || !isNode(declared) || declared.kind !== "dependency") throw new LoadError(`The deps for "${targetId}" name "${input}", which is not a dependency slot of that ${targetKind}.`);
309
+ const producerId = producerIdOf(ref);
310
+ const producer = producerId !== void 0 ? byId.get(producerId) : void 0;
311
+ if (producerId === void 0 || producer === void 0) throw new LoadError(`The deps for "${targetId}.${input}" reference "${String(producerId)}", which is not provisioned in module "${enclosingModuleName}".`);
312
+ const required = declared.required;
313
+ if (required !== void 0 && !satisfiesRequired(ref, required)) throw new LoadError(`The deps for "${targetId}.${input}" do not satisfy the slot's required contract.`);
314
+ }
315
+ for (const [input, rawValue] of Object.entries(deps)) {
316
+ const value = blindCast(rawValue);
317
+ if (!isNode(value) || wiring[input] !== void 0) continue;
318
+ if (value.kind === "dependency") throw new LoadError(`Dependency input "${input}" of provisioned ${targetKind} "${targetId}" is not wired to a producer (module "${enclosingModuleName}").`);
319
+ }
320
+ }
321
+ /** The (unvalidated) edges a `wiring` object implies — one dependency edge per entry; `validateWiring` does the real checking. */
322
+ function wiringEdges(wiring, targetId) {
323
+ return Object.entries(wiring).map(([input, ref]) => ({
324
+ from: producerIdOf(ref) ?? "",
325
+ to: targetId,
326
+ input,
327
+ kind: "dependency"
328
+ }));
329
+ }
330
+ /**
331
+ * Checks the secrets wired into one provisioned child: every declared slot is
332
+ * bound to a real secret source (an `envSecret` or a forwarded ctx.secrets
333
+ * ref), and no wired key names a slot the child doesn't declare — the secret
334
+ * analog of `validateWiring`'s per-input checks, but resolved inline (a source
335
+ * carries its own name, so no whole-graph pass is needed).
336
+ */
337
+ function validateSecretBinding(child, id, secretWiring, enclosingModuleName) {
338
+ const { kind } = child;
339
+ for (const slot of Object.keys(child.secretSlots)) {
340
+ const bound = secretWiring[slot];
341
+ if (bound === void 0) throw new LoadError(`Secret slot "${slot}" of provisioned ${kind} "${id}" is not bound (module "${enclosingModuleName}") — bind it with envSecret('NAME') or forward ctx.secrets.`);
342
+ if (!isSecretSource(bound)) throw new LoadError(`Secret slot "${slot}" of "${id}" (module "${enclosingModuleName}") was wired with a non-secret value — use envSecret('NAME') or a forwarded ctx.secrets ref.`);
343
+ }
344
+ for (const slot of Object.keys(secretWiring)) if (!Object.hasOwn(child.secretSlots, slot)) throw new LoadError(`The secrets for "${id}" name "${slot}", which is not a secret slot of that ${kind} (module "${enclosingModuleName}").`);
345
+ }
346
+ /**
347
+ * Recursively flattens one module's body into the shared graph state and
348
+ * returns its resolved ModuleOutputs (one ref-port per expose key) for the
349
+ * caller (the enclosing provision() call, or Load itself for the root) to
350
+ * use. `address` is this module's OWN full address, or `undefined` for the root
351
+ * scope — its direct children then get bare (unprefixed) addresses, keeping
352
+ * a single-level module identical to before nesting existed. `wiring` supplies a
353
+ * resolved producer ref-port for each of this module's OWN declared deps (empty
354
+ * for the root, which may not declare any — see the root non-empty-deps
355
+ * check in loadModule). `nodes`, `edges`, `pending`, and `byId` are shared
356
+ * across the ENTIRE recursive flatten, not per scope — a nested module may
357
+ * forward in a producer provisioned by an ancestor scope, and it is the
358
+ * shared `byId` (keyed by full address) that lets that resolve.
359
+ */
360
+ function flatten(moduleNode, address, wiring, secretWiring, nodes, edges, pending, secretBindings, byId) {
361
+ const localIds = /* @__PURE__ */ new Set();
362
+ const used = /* @__PURE__ */ new Set();
363
+ const usedSecrets = /* @__PURE__ */ new Set();
364
+ const ctxInputs = {};
365
+ for (const key of Object.keys(moduleNode.deps)) {
366
+ const wired = wiring[key];
367
+ ctxInputs[key] = typeof wired === "object" && wired !== null ? {
368
+ ...wired,
369
+ [MODULE_INPUT_KEY]: key
370
+ } : wired;
371
+ }
372
+ const markUsed = (values) => {
373
+ for (const value of Object.values(values)) for (const key of Object.keys(ctxInputs)) if (value === ctxInputs[key]) used.add(key);
374
+ };
375
+ const ctxSecrets = {};
376
+ for (const key of Object.keys(moduleNode.secretSlots)) {
377
+ const bound = secretWiring[key];
378
+ ctxSecrets[key] = typeof bound === "object" && bound !== null ? {
379
+ ...bound,
380
+ [MODULE_SECRET_KEY]: key
381
+ } : bound;
382
+ }
383
+ const markSecretsUsed = (values) => {
384
+ for (const value of Object.values(values)) for (const key of Object.keys(ctxSecrets)) if (value === ctxSecrets[key]) usedSecrets.add(key);
385
+ };
386
+ const provision = (child, opts) => {
387
+ const id = opts?.id ?? child.name;
388
+ const provisionWiring = opts?.deps;
389
+ const provisionSecrets = opts?.secrets;
390
+ if (typeof id !== "string" || id.length === 0) throw new LoadError(`provision() requires a non-empty id (module "${moduleNode.name}").`);
391
+ if (id.includes("_") || id.includes(".")) throw new LoadError(`provision() id "${id}" (module "${moduleNode.name}") may not contain "_" or "." — "_" is the config-key separator and "." the node-id path separator; either inside an id collides with the joined form of other names.`);
392
+ if (localIds.has(id)) throw new LoadError(`Duplicate provision id "${id}" in module "${moduleNode.name}".`);
393
+ const untrusted = child;
394
+ if (!isNode(untrusted) || untrusted.kind !== "service" && untrusted.kind !== "resource" && untrusted.kind !== "module") throw new LoadError(`provision("${id}") expects a branded service, resource, or module node (construct it with the service()/resource()/module() factories or a pack's own).`);
395
+ localIds.add(id);
396
+ const fullAddress = address === void 0 ? id : `${address}.${id}`;
397
+ if (child.kind === "resource") {
398
+ if (provisionWiring !== void 0) throw new LoadError(`provision("${id}") received deps for a resource — a resource has no dependency slots to satisfy.`);
399
+ if (provisionSecrets !== void 0) throw new LoadError(`provision("${id}") received secrets for a resource — a resource has no secret slots to satisfy.`);
400
+ if (child.type.length === 0) throw new LoadError(`provision("${id}") received a resource with an empty node type.`);
401
+ byId.set(fullAddress, child);
402
+ nodes.push({
403
+ id: fullAddress,
404
+ node: child
405
+ });
406
+ return refForResource(fullAddress, child);
407
+ }
408
+ const localWiring = { ...provisionWiring ?? {} };
409
+ markUsed(localWiring);
410
+ const localSecrets = { ...provisionSecrets ?? {} };
411
+ markSecretsUsed(localSecrets);
412
+ validateSecretBinding(child, id, localSecrets, moduleNode.name);
413
+ if (child.kind === "service") {
414
+ for (const slot of Object.keys(child.secretSlots)) {
415
+ const bound = localSecrets[slot];
416
+ if (isSecretSource(bound)) secretBindings.push({
417
+ serviceAddress: fullAddress,
418
+ slot,
419
+ source: bound
420
+ });
421
+ }
422
+ const inputs = serviceInputs(child, fullAddress);
423
+ nodes.push(...inputs.nodes, {
424
+ id: fullAddress,
425
+ node: child
426
+ });
427
+ edges.push(...inputs.edges, ...wiringEdges(localWiring, fullAddress));
428
+ pending.push({
429
+ deps: child.inputs,
430
+ wiring: localWiring,
431
+ targetId: fullAddress,
432
+ targetKind: "service",
433
+ enclosingModuleName: moduleNode.name
434
+ });
435
+ byId.set(fullAddress, child);
436
+ return refFor(fullAddress, child);
437
+ }
438
+ edges.push(...wiringEdges(localWiring, fullAddress));
439
+ pending.push({
440
+ deps: child.deps,
441
+ wiring: localWiring,
442
+ targetId: fullAddress,
443
+ targetKind: "module",
444
+ enclosingModuleName: moduleNode.name
445
+ });
446
+ const childOutputs = flatten(child, fullAddress, localWiring, localSecrets, nodes, edges, pending, secretBindings, byId);
447
+ nodes.push({
448
+ id: fullAddress,
449
+ node: child
450
+ });
451
+ byId.set(fullAddress, child);
452
+ return blindCast({
453
+ id: fullAddress,
454
+ ...childOutputs
455
+ });
456
+ };
457
+ const ctx = blindCast({
458
+ inputs: ctxInputs,
459
+ secrets: ctxSecrets,
460
+ provision: blindCast(provision)
461
+ });
462
+ const outputs = blindCast(moduleNode.body(ctx) ?? {});
463
+ markUsed(outputs);
464
+ for (const key of Object.keys(moduleNode.deps)) if (!used.has(key)) throw new LoadError(`Module "${moduleNode.name}" declares input "${key}" but never forwards it into a provision nor returns it as an output.`);
465
+ for (const key of Object.keys(moduleNode.secretSlots)) if (!usedSecrets.has(key)) throw new LoadError(`Module "${moduleNode.name}" declares secret "${key}" but never forwards it into a provision.`);
466
+ for (const [key, contract] of Object.entries(moduleNode.expose)) {
467
+ const port = outputs[key];
468
+ if (port === void 0) throw new LoadError(`Module "${moduleNode.name}" declares expose "${key}" but its body did not return a port for it.`);
469
+ if (!satisfiesRequired(port, contract)) throw new LoadError(`Module "${moduleNode.name}"'s returned port for expose "${key}" does not satisfy its declared contract.`);
470
+ }
471
+ return outputs;
472
+ }
473
+ function loadModule(root, opts) {
474
+ const rootId = opts?.id ?? root.name;
475
+ const rootDepKeys = Object.keys(root.deps);
476
+ if (rootDepKeys.length > 0) {
477
+ const names = rootDepKeys.map((k) => `"${k}"`).join(", ");
478
+ throw new LoadError(`Module "${root.name}" declares input${rootDepKeys.length > 1 ? "s" : ""} ${names} but is being deployed as the root — a root has no enclosing scope to wire them; compose "${root.name}" from another module that provisions and wires it instead.`);
479
+ }
480
+ const rootSecretKeys = Object.keys(root.secretSlots);
481
+ if (rootSecretKeys.length > 0) {
482
+ const names = rootSecretKeys.map((k) => `"${k}"`).join(", ");
483
+ throw new LoadError(`Module "${root.name}" declares secret${rootSecretKeys.length > 1 ? "s" : ""} ${names} but is being deployed as the root — a root has no enclosing scope to bind them; the root binds secrets with envSecret('NAME'), it does not declare secret slots of its own.`);
484
+ }
485
+ const nodes = [];
486
+ const edges = [];
487
+ const pending = [];
488
+ const secretBindings = [];
489
+ const byId = /* @__PURE__ */ new Map();
490
+ flatten(root, void 0, {}, {}, nodes, edges, pending, secretBindings, byId);
491
+ for (const entry of pending) validateWiring(entry, byId);
492
+ assertDependencyDag(edges);
493
+ const rootGraphNode = {
494
+ id: rootId,
495
+ node: root
496
+ };
497
+ return {
498
+ root: rootGraphNode,
499
+ nodes: [...topoSort(nodes, edges), rootGraphNode],
500
+ edges,
501
+ secrets: secretBindings
502
+ };
503
+ }
504
+ /**
505
+ * The dependency edges must form a DAG — a cycle means neither producer can
506
+ * deploy first. Resources take no wiring, so only service/module-to-service/module
507
+ * edges can ever participate in a cycle; no special-casing needed.
508
+ */
509
+ function assertDependencyDag(edges) {
510
+ const adjacency = /* @__PURE__ */ new Map();
511
+ for (const edge of edges) {
512
+ if (edge.kind !== "dependency") continue;
513
+ const targets = adjacency.get(edge.from) ?? [];
514
+ targets.push(edge.to);
515
+ adjacency.set(edge.from, targets);
516
+ }
517
+ const visiting = /* @__PURE__ */ new Set();
518
+ const done = /* @__PURE__ */ new Set();
519
+ const stack = [];
520
+ const visit = (id) => {
521
+ if (done.has(id)) return;
522
+ if (visiting.has(id)) throw new LoadError(`Dependency cycle: ${[...stack.slice(stack.indexOf(id)), id].join(" → ")} — no deploy order exists.`);
523
+ visiting.add(id);
524
+ stack.push(id);
525
+ for (const next of adjacency.get(id) ?? []) visit(next);
526
+ stack.pop();
527
+ visiting.delete(id);
528
+ done.add(id);
529
+ };
530
+ for (const id of adjacency.keys()) visit(id);
531
+ }
532
+ /**
533
+ * Builds the in-memory graph from a root node. A service root walks its own
534
+ * `inputs`; a module root executes its body (wiring, not user code — the
535
+ * designed exception to imports-run-nothing) and recursively flattens every
536
+ * module it provisions into one graph of hierarchical addresses. A malformed
537
+ * graph is a `LoadError` that names its fix; the individual validation rules
538
+ * live with `loadService` / `loadModule` and are covered by name in the Load
539
+ * tests. Executes nothing of the user's own code beyond module bodies.
540
+ */
541
+ function Load(root, opts) {
542
+ if (!isNode(root)) throw new LoadError("Load expects a branded service or module node (construct it with the service()/module() factories).");
543
+ if (root.kind === "module") return loadModule(root, opts);
544
+ if (root.kind === "service") return loadService(root, opts?.id ?? "root");
545
+ throw new LoadError("Load expects a service or module root (received another node kind).");
546
+ }
547
+ //#endregion
548
+ //#region ../../1-prisma-cloud/0-lowering/lowering/dist/http-CxGdfSAP.mjs
549
+ /**
550
+ * The Prisma service token used to authenticate Management API calls. Kept
551
+ * as a Redacted value so it never lands in logs or error output.
552
+ */
553
+ var PrismaCredentials = class extends Context.Service()("PrismaCredentials") {};
554
+ /** Resolve the token from the `PRISMA_SERVICE_TOKEN` environment variable. */
555
+ const fromEnv = () => Layer.effect(PrismaCredentials, Effect.gen(function* () {
556
+ return { token: yield* Config.redacted("PRISMA_SERVICE_TOKEN") };
557
+ }));
558
+ /**
559
+ * The typed Prisma Management API client, built once from the resolved
560
+ * credentials. Providers yield this in their outer Effect and call it inside
561
+ * `reconcile` / `delete`.
562
+ */
563
+ var ManagementClient = class extends Context.Service()("PrismaManagementClient") {};
564
+ const layer = () => Layer.effect(ManagementClient, Effect.gen(function* () {
565
+ const { token } = yield* PrismaCredentials;
566
+ return createManagementApiClient({ token: Redacted.value(token) });
567
+ }));
568
+ /** A non-2xx response from the Management API (or a transport failure). */
569
+ var PrismaApiError = class extends Data.TaggedError("PrismaApiError") {};
570
+ const attempt = (f) => Effect.tryPromise({
571
+ try: f,
572
+ catch: (cause) => new PrismaApiError({
573
+ status: 0,
574
+ message: String(cause)
575
+ })
576
+ });
577
+ const fail = (r) => Effect.fail(new PrismaApiError({
578
+ status: r.response.status,
579
+ message: JSON.stringify(r.error)
580
+ }));
581
+ /** Unwrap `data`, failing on any API error. Preserves the SDK's response type. */
582
+ const call = (f) => attempt(f).pipe(Effect.flatMap((r) => r.error !== void 0 || r.data === void 0 ? fail(r) : Effect.succeed(r.data)));
583
+ /** Fire-and-forget a call, tolerating a 404 (already deleted). */
584
+ const callVoid = (f) => attempt(f).pipe(Effect.flatMap((r) => r.response.status === 404 || r.error === void 0 ? Effect.void : fail(r)));
585
+ Schedule.both(Schedule.exponential("2 seconds", 2), Schedule.during("5 minutes"));
586
+ Resource("Prisma.ComputeService");
587
+ Resource("Prisma.Deployment");
588
+ Resource("Prisma.EnvironmentVariable");
589
+ Resource("Prisma.Connection");
590
+ Resource("Prisma.Database");
591
+ Resource("Prisma.Project");
592
+ //#endregion
593
+ //#region ../../1-prisma-cloud/0-lowering/lowering/dist/index.mjs
594
+ /** Raised with `ensure: false` when the app's Project (or a named stage's Branch) doesn't exist. */
595
+ var ContainerNotFoundError = class extends Data.TaggedError("ContainerNotFoundError") {};
596
+ const listAllProjects = (client) => Effect.gen(function* () {
597
+ const projects = [];
598
+ let cursor;
599
+ for (;;) {
600
+ const query = cursor === void 0 ? {} : { cursor };
601
+ const page = yield* call(() => client.GET("/v1/projects", { params: { query } }));
602
+ projects.push(...page.data);
603
+ if (!page.pagination.hasMore || page.pagination.nextCursor === null) break;
604
+ cursor = page.pagination.nextCursor;
605
+ }
606
+ return projects;
607
+ });
608
+ /**
609
+ * Workspace ids circulate in two shapes: `wksp_`-prefixed and bare. Compare
610
+ * bare-to-bare so a `wksp_`-prefixed API id still matches a bare configured
611
+ * one (the same normalization `state/bootstrap.ts` applies to the same
612
+ * `/v1/projects` listing).
613
+ */
614
+ const bareWorkspaceId = (id) => id.startsWith("wksp_") ? id.slice(5) : id;
615
+ /**
616
+ * Finds the app's Project by name in the workspace — PDP allows duplicate
617
+ * project names, so more than one can match; the oldest wins. Creates one
618
+ * if none match, unless `ensure` is `false` (find-only — `destroy`), in
619
+ * which case an absent Project fails with `ContainerNotFoundError`. No
620
+ * ownership marker and no `--project` override (both deferred — see
621
+ * ADR-0019).
622
+ */
623
+ const resolveProject = (client, workspaceId, appName, ensure) => Effect.gen(function* () {
624
+ const oldest = (yield* listAllProjects(client)).filter((p) => bareWorkspaceId(p.workspace.id) === bareWorkspaceId(workspaceId) && p.name === appName).sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
625
+ if (oldest !== void 0) return oldest.id;
626
+ if (!ensure) return yield* Effect.fail(new ContainerNotFoundError({ appName }));
627
+ return (yield* call(() => client.POST("/v1/projects", { body: {
628
+ name: appName,
629
+ workspaceId
630
+ } }))).data.id;
631
+ });
632
+ const findBranchId = (client, projectId, gitName) => call(() => client.GET("/v1/projects/{projectId}/branches", { params: {
633
+ path: { projectId },
634
+ query: { gitName }
635
+ } })).pipe(Effect.map((page) => page.data[0]?.id));
636
+ /**
637
+ * Finds the stage's Branch by its exact `gitName`, creating it if absent
638
+ * unless `ensure` is `false` (find-only — `destroy`), in which case an
639
+ * absent Branch fails with `ContainerNotFoundError`. The Management API has
640
+ * no server-side "create-or-return" idempotency (`POST
641
+ * /v1/projects/:id/branches` 409s on a duplicate `gitName`, with no request
642
+ * field to make that a no-op), so idempotency is client-side: observe
643
+ * first, and on a racing 409 from create, re-observe rather than fail.
644
+ */
645
+ const resolveBranch = (client, projectId, gitName, appName, ensure) => Effect.gen(function* () {
646
+ const existing = yield* findBranchId(client, projectId, gitName);
647
+ if (existing !== void 0) return existing;
648
+ if (!ensure) return yield* Effect.fail(new ContainerNotFoundError({
649
+ appName,
650
+ stage: gitName
651
+ }));
652
+ return yield* call(() => client.POST("/v1/projects/{projectId}/branches", {
653
+ params: { path: { projectId } },
654
+ body: { gitName }
655
+ })).pipe(Effect.map((r) => r.data.id), Effect.catch((err) => err.status === 409 ? findBranchId(client, projectId, gitName).pipe(Effect.flatMap((id) => id === void 0 ? Effect.fail(err) : Effect.succeed(id))) : Effect.fail(err)));
656
+ });
657
+ /**
658
+ * Resolves the two containers a stage's deploy runs into (ADR-0019): the
659
+ * app's **Project**, found-or-created by name, and — for a named stage
660
+ * only — its **Branch**, found-or-created by `gitName`. The default stage
661
+ * (no `stage`) creates no Branch; `branchId` is omitted. With `ensure:
662
+ * false` (`destroy`), nothing is created — an absent Project or Branch
663
+ * fails with `ContainerNotFoundError` instead.
664
+ */
665
+ const resolveContainer = (opts) => Effect.gen(function* () {
666
+ const client = yield* ManagementClient;
667
+ const ensure = opts.ensure ?? true;
668
+ const projectId = yield* resolveProject(client, opts.workspaceId, opts.appName, ensure);
669
+ if (opts.stage === void 0) return { projectId };
670
+ return {
671
+ projectId,
672
+ branchId: yield* resolveBranch(client, projectId, opts.stage, opts.appName, ensure)
673
+ };
674
+ });
675
+ /**
676
+ * Soft-deletes a Branch. Tolerates a 404 (already gone). The API refuses if
677
+ * the Branch still has live members or is the production/default Branch —
678
+ * that surfaces as a `PrismaApiError`.
679
+ */
680
+ const deleteBranch = (branchId) => Effect.gen(function* () {
681
+ const client = yield* ManagementClient;
682
+ yield* callVoid(() => client.DELETE("/v1/branches/{branchId}", { params: { path: { branchId } } }));
683
+ });
684
+ Provider.ProviderCollection()("Prisma");
685
+ //#endregion
686
+ //#region ../../0-framework/3-tooling/cli/dist/cli-BGF4efRK.mjs
687
+ /**
688
+ * A user-facing failure with a message that already names the fix (deploy-cli.md
689
+ * § Error surface). `bin.ts` catches this — and any other Error, including
690
+ * core's LoadError/LowerError — uniformly: print the message, exit nonzero.
691
+ */
692
+ var CliError = class extends Error {
693
+ constructor(message) {
694
+ super(message);
695
+ this.name = "CliError";
696
+ }
697
+ };
698
+ /**
699
+ * Pipeline pre-stack step: resolves the app's Project + (named stage) Branch
700
+ * via `@internal/lowering`'s `resolveContainer`, before the generated stack file
701
+ * runs — `deploy` creates-if-absent, `destroy` finds only.
702
+ */
703
+ /** Validates `stage` as a git ref name via `git check-ref-format` — no silent normalization. */
704
+ function validateStageName(stage) {
705
+ const result = spawnSync("git", ["check-ref-format", `refs/heads/${stage}`], { stdio: "ignore" });
706
+ if (result.error) throw new CliError(`git is required to validate --stage "${stage}" (git check-ref-format): ${result.error.message}.`);
707
+ if (result.status !== 0) throw new CliError(`Invalid --stage "${stage}": must be a valid git ref name (git check-ref-format rejected "refs/heads/${stage}").`);
708
+ }
709
+ async function ensureContainers(input, deps) {
710
+ const env = input.env ?? process.env;
711
+ const workspaceId = env["PRISMA_WORKSPACE_ID"];
712
+ if (workspaceId === void 0 || workspaceId.length === 0) throw new CliError("environment variable PRISMA_WORKSPACE_ID is required.");
713
+ if (deps?.client === void 0 && (env["PRISMA_SERVICE_TOKEN"] ?? "").length === 0) throw new CliError("environment variable PRISMA_SERVICE_TOKEN is required.");
714
+ if (input.stage !== void 0) validateStageName(input.stage);
715
+ const program = resolveContainer({
716
+ workspaceId,
717
+ appName: input.appName,
718
+ ...input.stage !== void 0 ? { stage: input.stage } : {},
719
+ ensure: input.command === "deploy"
720
+ }).pipe(Effect.map((c) => ({
721
+ ok: true,
722
+ container: c
723
+ })), Effect.catchTag("ContainerNotFoundError", (e) => Effect.succeed({
724
+ ok: false,
725
+ message: `Nothing deployed for ${e.appName}${e.stage ? `/${e.stage}` : ""} — deploy it first.`
726
+ })), Effect.catchTag("PrismaApiError", (e) => Effect.succeed({
727
+ ok: false,
728
+ message: `Prisma Management API error resolving containers: ${e.message}.`
729
+ })));
730
+ const provided = deps?.client !== void 0 ? program.pipe(Effect.provideService(ManagementClient, deps.client)) : program.pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))));
731
+ const outcome = await Effect.runPromise(provided);
732
+ if (!outcome.ok) throw new CliError(outcome.message);
733
+ return outcome.container;
734
+ }
735
+ /**
736
+ * Soft-deletes a named stage's Branch after a successful `alchemy destroy`
737
+ * has removed its members (spec §10) — the Management API refuses to delete
738
+ * a Branch that still has live members.
739
+ */
740
+ async function deleteStageBranch(input, deps) {
741
+ const env = input.env ?? process.env;
742
+ if (deps?.client === void 0 && (env["PRISMA_SERVICE_TOKEN"] ?? "").length === 0) throw new CliError("environment variable PRISMA_SERVICE_TOKEN is required.");
743
+ const program = deleteBranch(input.branchId).pipe(Effect.map(() => ({ ok: true })), Effect.catchTag("PrismaApiError", (e) => Effect.succeed({
744
+ ok: false,
745
+ message: `Failed to delete the stage Branch: ${e.message}.`
746
+ })));
747
+ const provided = deps?.client !== void 0 ? program.pipe(Effect.provideService(ManagementClient, deps.client)) : program.pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))));
748
+ const outcome = await Effect.runPromise(provided);
749
+ if (!outcome.ok) throw new CliError(outcome.message);
750
+ }
751
+ /** Pipeline step 6: writes a regenerated-every-run, independently runnable stack module at `.prisma-composer/alchemy.run.ts`. */
752
+ const GENERATED_DIR = ".prisma-composer";
753
+ const GENERATED_FILE = "alchemy.run.ts";
754
+ /** A relative import specifier from `.prisma-composer/alchemy.run.ts` to `target` (posix separators). */
755
+ function relativeImportSpecifier(generatedDir, target) {
756
+ const rel = path.relative(generatedDir, target).split(path.sep).join("/");
757
+ return rel.startsWith(".") ? rel : `./${rel}`;
758
+ }
759
+ function quote(value) {
760
+ return JSON.stringify(value);
761
+ }
762
+ function renderBundle(bundle) {
763
+ return `{ dir: ${quote(bundle.dir)}, entry: ${quote(bundle.entry)} }`;
764
+ }
765
+ function renderOptions(input) {
766
+ const lines = [];
767
+ lines.push(` name: ${quote(input.name)},`);
768
+ lines.push(" bundles: {");
769
+ for (const [id, bundle] of Object.entries(input.assembled.bundles)) lines.push(` ${quote(id)}: ${renderBundle(bundle)},`);
770
+ lines.push(" },");
771
+ return lines.join("\n");
772
+ }
773
+ /** Renders the stack module's source (tests assert on it without touching disk) — uses `//` headers, not a block comment, since a cwd path with a star-slash could close one early. */
774
+ function renderStackFile(input) {
775
+ const generatedDir = path.join(input.cwd, GENERATED_DIR);
776
+ const appImport = relativeImportSpecifier(generatedDir, input.entryPath);
777
+ const configImport = relativeImportSpecifier(generatedDir, input.configPath);
778
+ return `// Generated by \`prisma-composer deploy\`/\`prisma-composer destroy\` — overwritten on every
779
+ // run; do not edit by hand. Independently runnable from ${quote(input.cwd)}:
780
+ //
781
+ // alchemy deploy ${GENERATED_DIR}/${GENERATED_FILE}
782
+ //
783
+ // bisects a CLI bug from an Alchemy bug (deploy-cli.md § Implementation decisions).
784
+ import { lower } from '@prisma/composer/deploy';
785
+ import config from ${quote(configImport)};
786
+ import app from ${quote(appImport)};
787
+
788
+ export default lower(app, config, {
789
+ ${renderOptions(input)}
790
+ });
791
+ `;
792
+ }
793
+ /** Writes the stack file, returning its absolute path. */
794
+ function writeStackFile(input) {
795
+ const generatedDir = path.join(input.cwd, GENERATED_DIR);
796
+ fs.mkdirSync(generatedDir, { recursive: true });
797
+ const filePath = path.join(generatedDir, GENERATED_FILE);
798
+ fs.writeFileSync(filePath, renderStackFile(input));
799
+ return filePath;
800
+ }
801
+ const GENERATED_STACK_RELATIVE_PATH = path.join(GENERATED_DIR, GENERATED_FILE);
802
+ /**
803
+ * Pipeline step: find and load `prisma-composer.config.ts` (ADR-0017) — the ONE
804
+ * file that imports control-plane code. Discovery is the standard walk-up
805
+ * from the deploy entry's directory (mirrors prisma-next's config-loader);
806
+ * loading is c12 with that explicit path (rc/global/package.json lookups
807
+ * disabled), so the config file's own static imports resolve from the app
808
+ * root by whatever package manager runs — no specifier construction, no
809
+ * anchoring. The loaded shape is validated field-by-field with CliErrors
810
+ * naming the field.
811
+ */
812
+ const CONFIG_FILENAME = "prisma-composer.config.ts";
813
+ /** Walks UP from the entry file's directory looking for the literal CONFIG_FILENAME; undefined when the walk hits the filesystem root. */
814
+ function findConfigPathForEntry(entryPath) {
815
+ let current = path.dirname(path.resolve(entryPath));
816
+ while (true) {
817
+ const candidate = path.join(current, CONFIG_FILENAME);
818
+ if (fs.existsSync(candidate)) return candidate;
819
+ const parent = path.dirname(current);
820
+ if (parent === current) return void 0;
821
+ current = parent;
822
+ }
823
+ }
824
+ function missingConfigError(entryPath) {
825
+ return new CliError(`No ${CONFIG_FILENAME} found walking up from "${path.dirname(path.resolve(entryPath))}" — the deploy needs the app's config file. Create one next to (or above) the entry, default-exporting defineConfig({ extensions: [...], state: ... }) from '@prisma/composer/config'.`);
826
+ }
827
+ function fieldError(field, requirement) {
828
+ return new CliError(`${CONFIG_FILENAME}: \`${field}\` ${requirement} — see defineConfig() in '@prisma/composer/config'.`);
829
+ }
830
+ function isRecord(value) {
831
+ return typeof value === "object" && value !== null;
832
+ }
833
+ /**
834
+ * Field-by-field validation of the loaded default export — deliberately no
835
+ * schema library: each check is a CliError naming the offending field.
836
+ * Returns the same object, typed.
837
+ */
838
+ function validateConfigShape(loaded, configPath) {
839
+ if (!isRecord(loaded) || Object.keys(loaded).length === 0) throw new CliError(`"${configPath}" exported no config — it must default-export defineConfig({ extensions: [...], state: ... }) from '@prisma/composer/config'.`);
840
+ const extensions = loaded["extensions"];
841
+ if (!Array.isArray(extensions)) throw fieldError("extensions", "must be an array");
842
+ const seen = /* @__PURE__ */ new Set();
843
+ for (const [index, entry] of extensions.entries()) {
844
+ if (!isRecord(entry)) throw fieldError(`extensions[${index}]`, "must be an extension descriptor object");
845
+ const id = entry["id"];
846
+ if (typeof id !== "string" || id.length === 0) throw fieldError(`extensions[${index}].id`, "must be a non-empty string (the extension package name)");
847
+ if (!isRecord(entry["nodes"])) throw fieldError(`extensions[${index}].nodes`, "must be an object (the node-ID → control registry)");
848
+ if (seen.has(id)) throw new CliError(`${CONFIG_FILENAME}: extension "${id}" is listed more than once in \`extensions\`.`);
849
+ seen.add(id);
850
+ }
851
+ if (typeof loaded["state"] !== "function") throw fieldError("state", "must be a function returning the deploy state layer (e.g. () => prismaState())");
852
+ return blindCast(loaded);
853
+ }
854
+ /**
855
+ * Loads + validates the config at `configPath` via c12 (explicit file; rc /
856
+ * global-rc / package.json lookups disabled — discovery already happened in
857
+ * findConfigPathForEntry).
858
+ */
859
+ async function loadAppConfig(configPath) {
860
+ const result = await c12.loadConfig({
861
+ name: "prisma-composer",
862
+ configFile: configPath,
863
+ cwd: path.dirname(configPath),
864
+ rcFile: false,
865
+ globalRc: false,
866
+ packageJson: false
867
+ });
868
+ const loadedFile = result.configFile;
869
+ if (typeof loadedFile !== "string" || fs.realpathSync(loadedFile) !== fs.realpathSync(configPath)) throw new CliError(`Config loading resolved "${String(loadedFile)}" instead of the discovered "${configPath}" — refusing to deploy against a different file.`);
870
+ return {
871
+ path: configPath,
872
+ config: validateConfigShape(result.config, configPath)
873
+ };
874
+ }
875
+ /**
876
+ * Pipeline step 1 (deploy-cli.md § The pipeline): import the entry module
877
+ * (resolved against cwd) and require its default export to be a node — a
878
+ * service or module, branded by core's factories. Whatever this module exports
879
+ * IS the application; nothing else marks a root (ADR-0003).
880
+ */
881
+ async function loadEntry(entryArg, cwd) {
882
+ const resolvedPath = path.resolve(cwd, entryArg);
883
+ const root = (await import(pathToFileURL(resolvedPath).href)).default;
884
+ if (!isNode(root) || root.kind === "dependency" || root.kind === "resource") throw new CliError(`Entry module "${resolvedPath}" must default-export a node (a service or a module) — construct it with service() or module() from @prisma/composer.`);
885
+ return {
886
+ path: resolvedPath,
887
+ root: blindCast(root)
888
+ };
889
+ }
890
+ /**
891
+ * Pipeline step 7 (deploy-cli.md § The pipeline; design-notes.md's "Driving
892
+ * Alchemy" call): shell out to the generated stack file. Resolves the
893
+ * workspace's own installed `alchemy` bin (walking up `node_modules/.bin`
894
+ * from the generated file's package dir) rather than going through
895
+ * `bunx`/`npx`, so this works the same under node and bun — the resolved
896
+ * bin's own launcher (`alchemy/bin/cli.js`) does its own node/bun dispatch
897
+ * from there, driven by the env it inherits.
898
+ */
899
+ /** Walks up from `startDir` looking for `node_modules/.bin/alchemy`. */
900
+ function resolveAlchemyBin(startDir) {
901
+ let dir = startDir;
902
+ while (true) {
903
+ const candidate = path.join(dir, "node_modules", ".bin", "alchemy");
904
+ if (fs.existsSync(candidate)) return candidate;
905
+ const parent = path.dirname(dir);
906
+ if (parent === dir) throw new CliError(`Could not find an installed \`alchemy\` bin above "${startDir}" — add "alchemy" as a dependency of your app.`);
907
+ dir = parent;
908
+ }
909
+ }
910
+ /** Runs `alchemy deploy|destroy <stack file> --yes [--stage <stage>]`, inheriting stdio + env, plus the resolved Project/Branch ids. */
911
+ function runAlchemy(input) {
912
+ const bin = resolveAlchemyBin(input.cwd);
913
+ const args = [
914
+ input.command,
915
+ input.stackFileRelativePath,
916
+ "--yes"
917
+ ];
918
+ if (input.stage !== void 0) args.push("--stage", input.stage);
919
+ const result = spawnSync(bin, args, {
920
+ cwd: input.cwd,
921
+ stdio: "inherit",
922
+ env: {
923
+ ...input.env ?? process.env,
924
+ PRISMA_PROJECT_ID: input.projectId,
925
+ ...input.branchId !== void 0 ? { PRISMA_BRANCH_ID: input.branchId } : {}
926
+ }
927
+ });
928
+ if (result.error !== void 0) throw result.error;
929
+ return result.status ?? 1;
930
+ }
931
+ function lookup(extensions, extension, type, expectedKind, what) {
932
+ const ext = extensions.get(extension);
933
+ if (ext === void 0) throw new CliError(`No extension "${extension}" is configured (needed by ${what}) — add it to ${CONFIG_FILENAME}'s \`extensions\` (import its /control entry and list its descriptor).`);
934
+ const descriptor = ext.nodes[type];
935
+ if (descriptor === void 0) throw new CliError(`Extension "${extension}" has no descriptor for node type "${type}" (needed by ${what}; known: ${Object.keys(ext.nodes).join(", ")}).`);
936
+ if (descriptor.kind !== expectedKind) throw new CliError(`Extension "${extension}"'s descriptor for node type "${type}" is a "${descriptor.kind}" descriptor — ${what} needs a "${expectedKind}" descriptor.`);
937
+ }
938
+ /** Throws a CliError on the first uncovered `(extension, type)`; silent when the config covers the whole graph. */
939
+ function validateRegistryCoverage(graph, config) {
940
+ const extensions = new Map(config.extensions.map((descriptor) => [descriptor.id, descriptor]));
941
+ for (const { id, node } of graph.nodes) {
942
+ if (node.kind === "resource") {
943
+ lookup(extensions, node.extension, node.type, "resource", `resource node "${id}"`);
944
+ continue;
945
+ }
946
+ if (node.kind !== "service") continue;
947
+ lookup(extensions, node.extension, node.type, "service", `service node "${id}"`);
948
+ lookup(extensions, node.build.extension, node.build.type, "build", `service node "${id}"'s build descriptor`);
949
+ }
950
+ }
951
+ /**
952
+ * Argument parsing (clipanion — prisma-next's CLI idiom, see
953
+ * prisma-next/packages/1-framework/3-tooling/cli/src/migration-cli.ts) +
954
+ * orchestration of deploy-cli.md § The pipeline.
955
+ */
956
+ const BINARY_NAME = "prisma-composer";
957
+ /** The <entry>/--name/--stage surface shared by deploy and destroy; execute() is unused — run() drives the pipeline directly so error handling stays under this module's control. */
958
+ var DeployCliCommand = class extends Command {
959
+ entry = Option.String({ name: "entry" });
960
+ name = Option.String("--name", { description: "Override the root node's name — the deploy's application name." });
961
+ stage = Option.String("--stage", { description: "Alchemy stage to target." });
962
+ production = Option.Boolean("--production", false, { description: "destroy: tear down the project-level production environment (required to destroy production)." });
963
+ async execute() {
964
+ return 0;
965
+ }
966
+ };
967
+ var DeployCommand = class extends DeployCliCommand {
968
+ static paths = [["deploy"]];
969
+ static usage = Command.Usage({
970
+ description: "Deploy the application whose root node is <entry>'s default export.",
971
+ examples: [["Deploy an app", "$0 deploy src/service.ts"]]
972
+ });
973
+ action = "deploy";
974
+ };
975
+ var DestroyCommand = class extends DeployCliCommand {
976
+ static paths = [["destroy"]];
977
+ static usage = Command.Usage({
978
+ description: "Tear down the application whose root node is <entry>'s default export — same derivation as deploy, Alchemy destroy.",
979
+ examples: [["Destroy an app", "$0 destroy src/service.ts"]]
980
+ });
981
+ action = "destroy";
982
+ };
983
+ function buildCli() {
984
+ return Cli.from([DeployCommand, DestroyCommand], {
985
+ binaryName: BINARY_NAME,
986
+ binaryLabel: "The prisma-composer deploy CLI"
987
+ });
988
+ }
989
+ /** Thrown internally when the user explicitly asked for `--help`/`-h` — run() prints it to stdout and exits 0; not a usage error. */
990
+ var HelpRequested = class extends Error {};
991
+ /** Duck-typed: clipanion's UnknownSyntaxError isn't re-exported, so match its name + clipanion.type discriminator (mirrors prisma-next's migration-cli.ts). */
992
+ function isUnknownSyntaxError(error) {
993
+ if (!(error instanceof Error) || error.name !== "UnknownSyntaxError") return false;
994
+ const meta = error.clipanion;
995
+ return typeof meta === "object" && meta !== null && meta.type === "none";
996
+ }
997
+ /** Exported for direct testing (main.test.ts) — not part of the package's public barrel (see index.ts). */
998
+ function parseArgs(argv) {
999
+ const cli = buildCli();
1000
+ let command;
1001
+ try {
1002
+ command = cli.process([...argv]);
1003
+ } catch (error) {
1004
+ if (isUnknownSyntaxError(error) || error instanceof UsageError) throw new UsageError(cli.usage(null, { detailed: true }));
1005
+ throw error;
1006
+ }
1007
+ if (command instanceof DeployCommand || command instanceof DestroyCommand) return {
1008
+ command: command.action,
1009
+ entry: command.entry,
1010
+ name: command.name,
1011
+ stage: command.stage,
1012
+ production: command.production
1013
+ };
1014
+ if (argv.includes("--help") || argv.includes("-h")) throw new HelpRequested(cli.usage(null, { detailed: true }));
1015
+ throw new UsageError(cli.usage(null, { detailed: true }));
1016
+ }
1017
+ /** Destroy must name its target explicitly — no silent default to production (spec §10). */
1018
+ function effectiveStage(args) {
1019
+ if (args.command === "deploy") {
1020
+ if (args.production) throw new CliError("--production is only valid with `destroy`; `deploy` targets production by default (omit --stage).");
1021
+ return args.stage;
1022
+ }
1023
+ if (args.stage !== void 0 && args.production) throw new CliError("Pass either --stage <name> or --production to `destroy`, not both.");
1024
+ if (args.stage === void 0 && !args.production) throw new CliError("`destroy` requires an explicit target: --stage <name> to tear down a branch environment, or --production to tear down the production environment.");
1025
+ return args.production ? void 0 : args.stage;
1026
+ }
1027
+ const ALCHEMY_STATE_DIR = ".alchemy";
1028
+ /** Warns (doesn't fail) when destroy finds no local deploy state under cwd — likely wrong directory or nothing deployed yet. */
1029
+ function warnIfNoLocalDeployState(cwd) {
1030
+ const stateDir = path.join(cwd, ALCHEMY_STATE_DIR);
1031
+ if (!(fs.existsSync(stateDir) && fs.readdirSync(stateDir).length > 0)) console.warn(`\nNo prior deploy state under ${cwd} — if you deployed from a different directory, run destroy from there; otherwise this is a no-op.`);
1032
+ }
1033
+ /** Runs the full pipeline; returns the process exit code. */
1034
+ async function run(argv, deps = {}) {
1035
+ let args;
1036
+ try {
1037
+ args = parseArgs(argv);
1038
+ } catch (error) {
1039
+ if (error instanceof HelpRequested) {
1040
+ console.log(error.message);
1041
+ return 0;
1042
+ }
1043
+ throw error;
1044
+ }
1045
+ const stage = effectiveStage(args);
1046
+ const cwd = process.cwd();
1047
+ if (args.command === "destroy") warnIfNoLocalDeployState(cwd);
1048
+ const resolvedEntryPath = path.resolve(cwd, args.entry);
1049
+ const configPath = findConfigPathForEntry(resolvedEntryPath);
1050
+ if (configPath === void 0) throw missingConfigError(resolvedEntryPath);
1051
+ const config = deps.config ?? (await loadAppConfig(configPath)).config;
1052
+ const entryModule = await loadEntry(args.entry, cwd);
1053
+ const graph = Load(entryModule.root);
1054
+ if (graph.root.node.kind !== "module") throw new CliError("The deploy root must be a module — wrap your service, e.g. export default module('name', ({ provision }) => { provision(service); }).");
1055
+ validateRegistryCoverage(graph, config);
1056
+ const name = args.name ?? entryModule.root.name;
1057
+ if (name.length === 0) throw new CliError("The root node has no name — name it at authoring, or pass --name.");
1058
+ let assembled;
1059
+ try {
1060
+ assembled = await assembleServices(graph, config, cwd, deps.runAssembler);
1061
+ } catch (error) {
1062
+ if (args.command === "destroy" && error instanceof Error) throw new CliError(`${error.message}\n\ndestroy evaluates the same stack program as deploy, which packages the built artifacts — so the app must be built first. Run the build, then retry the destroy.`);
1063
+ throw error;
1064
+ }
1065
+ const { projectId, branchId } = await (deps.ensureContainers ?? ensureContainers)({
1066
+ command: args.command,
1067
+ appName: name,
1068
+ stage
1069
+ });
1070
+ if (args.command === "deploy") for (const extension of config.extensions) {
1071
+ if (extension.preflight === void 0) continue;
1072
+ try {
1073
+ await extension.preflight({
1074
+ graph,
1075
+ projectId,
1076
+ branchId,
1077
+ stage
1078
+ });
1079
+ } catch (error) {
1080
+ throw error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error));
1081
+ }
1082
+ }
1083
+ const stackPath = writeStackFile({
1084
+ entryPath: entryModule.path,
1085
+ cwd,
1086
+ configPath,
1087
+ name,
1088
+ assembled
1089
+ });
1090
+ try {
1091
+ const status = (deps.alchemy ?? runAlchemy)({
1092
+ command: args.command,
1093
+ stackFileRelativePath: GENERATED_STACK_RELATIVE_PATH,
1094
+ cwd,
1095
+ stage,
1096
+ projectId,
1097
+ ...branchId !== void 0 ? { branchId } : {}
1098
+ });
1099
+ if (status !== 0) {
1100
+ console.error(`\nGenerated stack file: ${stackPath}`);
1101
+ console.error(`Run \`alchemy ${args.command} ${GENERATED_STACK_RELATIVE_PATH} --yes\` from ${cwd} to reproduce this directly.`);
1102
+ return status;
1103
+ }
1104
+ if (args.command === "destroy" && branchId !== void 0) await (deps.deleteBranch ?? ((input) => deleteStageBranch(input)))({ branchId });
1105
+ return status;
1106
+ } catch (error) {
1107
+ console.error(`\nGenerated stack file: ${stackPath}`);
1108
+ throw error;
1109
+ }
1110
+ }
1111
+ /**
1112
+ * Run the `prisma-composer` CLI end to end: dispatch `argv`, map errors to exit
1113
+ * codes. Shared by this package's `bin` and the unscoped `prisma-composer` launcher.
1114
+ */
1115
+ async function cli(argv = process.argv.slice(2)) {
1116
+ try {
1117
+ process.exitCode = await run(argv);
1118
+ } catch (error) {
1119
+ if (error instanceof UsageError) {
1120
+ console.error(error.message);
1121
+ process.exitCode = 1;
1122
+ return;
1123
+ }
1124
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
1125
+ process.exitCode = 1;
1126
+ }
1127
+ }
1128
+ //#endregion
1129
+ //#region ../../0-framework/3-tooling/cli/dist/bin.mjs
1130
+ cli();
1131
+ //#endregion
1132
+ export {};
1133
+
1134
+ //# sourceMappingURL=bin.mjs.map