@spacefast/common 0.0.12 → 0.0.13

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 (113) hide show
  1. package/dist/contracts/access.d.ts +386 -1201
  2. package/dist/contracts/access.js +240 -1057
  3. package/dist/contracts/activity.d.ts +1 -1
  4. package/dist/contracts/activity.js +6 -14
  5. package/dist/contracts/api-keys.d.ts +16 -0
  6. package/dist/contracts/api-keys.js +2 -0
  7. package/dist/contracts/archives.d.ts +1 -2
  8. package/dist/contracts/archives.js +4 -6
  9. package/dist/contracts/comments.d.ts +58 -85
  10. package/dist/contracts/comments.js +86 -67
  11. package/dist/contracts/countries.js +2 -7
  12. package/dist/contracts/data-source-routes.d.ts +20 -0
  13. package/dist/contracts/data-source-routes.js +15 -0
  14. package/dist/contracts/device-auth.d.ts +7 -3
  15. package/dist/contracts/enums.d.ts +2 -4
  16. package/dist/contracts/enums.js +3 -8
  17. package/dist/contracts/error-code-meta.d.ts +17 -20
  18. package/dist/contracts/error-code-meta.js +8 -5
  19. package/dist/contracts/error-codes.d.ts +1 -1
  20. package/dist/contracts/error-codes.js +4 -5
  21. package/dist/contracts/events.d.ts +13 -13
  22. package/dist/contracts/execution.d.ts +212 -0
  23. package/dist/contracts/execution.js +288 -0
  24. package/dist/contracts/feature-lifecycle.d.ts +21 -167
  25. package/dist/contracts/feature-lifecycle.js +27 -173
  26. package/dist/contracts/features.d.ts +13 -115
  27. package/dist/contracts/features.js +1 -31
  28. package/dist/contracts/functions.d.ts +729 -0
  29. package/dist/contracts/functions.js +485 -0
  30. package/dist/contracts/git.d.ts +1 -1
  31. package/dist/contracts/grants.d.ts +1158 -0
  32. package/dist/contracts/grants.js +696 -0
  33. package/dist/contracts/ids.d.ts +5 -3
  34. package/dist/contracts/ids.js +5 -3
  35. package/dist/contracts/mcp.d.ts +6 -6
  36. package/dist/contracts/oauth-resources.d.ts +5 -5
  37. package/dist/contracts/oauth-resources.js +1 -0
  38. package/dist/contracts/operations.d.ts +2 -2
  39. package/dist/contracts/pages.d.ts +6 -14
  40. package/dist/contracts/pages.js +6 -23
  41. package/dist/contracts/plan-policy.d.ts +1 -8
  42. package/dist/contracts/plan-policy.js +1 -4
  43. package/dist/contracts/platform.d.ts +78 -30
  44. package/dist/contracts/platform.js +59 -12
  45. package/dist/contracts/push-new.d.ts +26 -2
  46. package/dist/contracts/push-new.js +8 -0
  47. package/dist/contracts/quotas.d.ts +0 -1
  48. package/dist/contracts/quotas.js +0 -5
  49. package/dist/contracts/repository-connections.d.ts +1 -1
  50. package/dist/contracts/resources.d.ts +10 -66
  51. package/dist/contracts/resources.js +4 -10
  52. package/dist/contracts/runtime-api.d.ts +558 -265
  53. package/dist/contracts/runtime-api.js +178 -91
  54. package/dist/contracts/runtime-app.d.ts +138 -0
  55. package/dist/contracts/runtime-app.js +21 -0
  56. package/dist/contracts/sf-config-v1.d.ts +5 -0
  57. package/dist/contracts/sites.d.ts +5 -0
  58. package/dist/contracts/sites.js +12 -1
  59. package/dist/contracts/space-config.d.ts +46 -116
  60. package/dist/contracts/space-config.js +320 -24
  61. package/dist/contracts/spaces.d.ts +253 -158
  62. package/dist/contracts/spaces.js +68 -54
  63. package/dist/contracts/superadmin-emails.d.ts +2 -2
  64. package/dist/contracts/superadmin-spaces.d.ts +15 -130
  65. package/dist/contracts/superadmin-spaces.js +7 -0
  66. package/dist/contracts/tags.d.ts +23 -23
  67. package/dist/contracts/teams.d.ts +9 -9
  68. package/dist/contracts/transfers.d.ts +0 -1
  69. package/dist/contracts/zero.d.ts +195 -273
  70. package/dist/contracts/zero.js +78 -206
  71. package/dist/dashboard-paths/index.d.ts +2 -2
  72. package/dist/dashboard-paths/index.js +1 -0
  73. package/dist/docs/agent-prose.js +10 -8
  74. package/dist/docs/agent-setup.d.ts +2 -2
  75. package/dist/docs/agent-setup.js +11 -9
  76. package/dist/docs/agent-solutions.js +1 -1
  77. package/dist/docs/catalog.d.ts +28 -28
  78. package/dist/docs/catalog.js +29 -29
  79. package/dist/docs/error-docs.js +23 -27
  80. package/dist/utils/asset-fingerprint.d.ts +11 -0
  81. package/dist/utils/asset-fingerprint.js +46 -0
  82. package/dist/utils/auth-redirect.d.ts +1 -3
  83. package/dist/utils/auth-redirect.js +1 -21
  84. package/dist/utils/build-settings.d.ts +2 -0
  85. package/dist/utils/build-settings.js +61 -9
  86. package/dist/utils/credential-policy.d.ts +1 -1
  87. package/dist/utils/credential-policy.js +4 -0
  88. package/dist/utils/egress-policy.fixtures.json +1 -1
  89. package/dist/utils/grants.d.ts +53 -0
  90. package/dist/utils/grants.js +160 -0
  91. package/dist/utils/local-space-state.js +1 -0
  92. package/dist/utils/pages.d.ts +11 -5
  93. package/dist/utils/pages.js +19 -32
  94. package/dist/utils/publish-policy.d.ts +34 -4
  95. package/dist/utils/publish-policy.js +132 -61
  96. package/dist/utils/query-keys.d.ts +1 -6
  97. package/dist/utils/query-keys.js +1 -6
  98. package/dist/utils/space-config.d.ts +5 -1
  99. package/dist/utils/space-config.js +35 -0
  100. package/dist/utils/static-runtime-policy.d.ts +5 -0
  101. package/dist/utils/static-runtime-policy.js +54 -10
  102. package/dist/utils/upload-session.d.ts +3 -0
  103. package/dist/utils/upload-session.js +31 -0
  104. package/package.json +2 -1
  105. package/dist/utils/access-grant.d.ts +0 -14
  106. package/dist/utils/access-grant.js +0 -88
  107. package/dist/utils/access-match.d.ts +0 -46
  108. package/dist/utils/access-match.fixtures.json +0 -513
  109. package/dist/utils/access-match.js +0 -312
  110. package/dist/utils/access-verdict.fixtures.json +0 -421
  111. package/dist/utils/sf-config-v1.d.ts +0 -2
  112. package/dist/utils/sf-config-v1.fixtures.json +0 -9
  113. package/dist/utils/sf-config-v1.js +0 -551
@@ -0,0 +1,485 @@
1
+ import { z } from "zod";
2
+ import { appRoutePathSchema, executionCapabilitiesSchema, executionEndpointSourceSchema, executionInspectPolicySchema, executionLogEntrySchema, executionLogListQuerySchema, executionLogListResponseSchema, executionSha256Schema, httpMethodSchema, runtimeKindSchema, } from "./execution.js";
3
+ /**
4
+ * Spacefast Functions: tenant workers run as Cloudflare Dynamic Workers.
5
+ *
6
+ * The shape of this product follows from two constraints that are not
7
+ * negotiable and that together rule out the obvious architecture:
8
+ *
9
+ * 1. **Cloudflare is reached from wp.cloud, never from the control plane.**
10
+ * The control plane records intent; the space's own origin performs every
11
+ * Cloudflare call.
12
+ * 2. **Every asset is served by wp.cloud.** We deliberately decline
13
+ * Cloudflare's static-asset support for user workers. A worker receives
14
+ * only the requests that could not be answered from bytes on disk, and
15
+ * `/_next/static/*` and friends never leave our origin.
16
+ *
17
+ * Dynamic Workers is what makes both hold at once. There is no upload: a
18
+ * version's bundle stays in its own content store on wp.cloud, and the host
19
+ * worker pulls it on demand through the Worker Loader binding. So there is no
20
+ * script lifecycle here — no namespace, no script name, no tag budget, no
21
+ * eviction, no garbage collection — because there is no artefact of ours living
22
+ * on Cloudflare to manage. What Cloudflare holds is a warm isolate, which is a
23
+ * cache, not a record.
24
+ *
25
+ * That also keeps the exit cheap. The contract below is "here is a module
26
+ * graph, here is its configuration, run it", which is workerd's own shape; the
27
+ * managed runtime is an implementation of it rather than the thing we built
28
+ * against.
29
+ *
30
+ * What the worker gets in exchange is the thing we could not build: a real V8
31
+ * isolate that runs npm packages and framework output — OpenNext Next.js among
32
+ * them — without us having to sandbox any of it.
33
+ *
34
+ * The cost is that the worker is a continent away from the space's MySQL.
35
+ * `ctx.db` therefore travels back over an HTTPS relay to the same PHP broker
36
+ * the local tier speaks to over a pipe, which is slower and batched rather
37
+ * than transactional. That is why capsules are a different product rather
38
+ * than a placement option — see `endpointIsPortable` in `./execution.js`.
39
+ */
40
+ export const FUNCTIONS_RUNTIME_KIND = "functions";
41
+ export const FUNCTIONS_SOURCE_METADATA_KEY = "spacefastFunctions";
42
+ export const FUNCTIONS_PLATFORM_ROUTE_PREFIX = "/__spacefast/functions";
43
+ export const FUNCTIONS_RUNTIME_ROUTE_PATHS = {
44
+ config: `${FUNCTIONS_PLATFORM_ROUTE_PREFIX}/config`,
45
+ inspect: `${FUNCTIONS_PLATFORM_ROUTE_PREFIX}/inspect`,
46
+ logs: `${FUNCTIONS_PLATFORM_ROUTE_PREFIX}/logs`,
47
+ /** Where a dispatched worker calls back for brokered capabilities. */
48
+ relay: `${FUNCTIONS_PLATFORM_ROUTE_PREFIX}/relay`,
49
+ };
50
+ /** Public, signed read path. Distinct from storage so the token is never a filename. */
51
+ export const FUNCTIONS_BUNDLE_ROUTE_PREFIX = `${FUNCTIONS_PLATFORM_ROUTE_PREFIX}/b`;
52
+ export const FUNCTIONS_RUNTIME_STORAGE_ROOT = "__spacefast/functions";
53
+ /**
54
+ * Where a version's compiled bundle lives.
55
+ *
56
+ * Under the same `__spacefast/` prefix as every other platform-owned path, so
57
+ * there is one convention rather than one per product. Two consequences fall
58
+ * out of that placement, and both are wanted:
59
+ *
60
+ * - It is not servable as static content. The runtime treats the whole prefix
61
+ * as control paths, so a tenant's compiled source is not readable at a
62
+ * guessable URL — and the digest that would make it guessable appears in
63
+ * build output.
64
+ * - It is written by the ordinary publish path anyway. The upload policy
65
+ * carves out exactly this subtree (`publish-policy.ts`), so the bundle rides
66
+ * the normal manifest and upload passes instead of needing a parallel one.
67
+ *
68
+ * The dispatch configuration — host, capabilities, relay credential — is not
69
+ * here and is not content at all. The engine writes it beside the version's
70
+ * file tree rather than inside it, exactly as it does for Zero, so a publish
71
+ * cannot reach it: no carve-out, no upload path, nothing to guard. A publish
72
+ * able to write that file would be a publish able to grant itself authority it
73
+ * was never given.
74
+ */
75
+ export const FUNCTIONS_RUNTIME_BUNDLE_ROOT = `${FUNCTIONS_RUNTIME_STORAGE_ROOT}/bundles`;
76
+ export const FUNCTIONS_BUNDLE_FORMAT = "spacefast.functions.bundle.v1";
77
+ /**
78
+ * Ceiling on a bundle's decoded size.
79
+ *
80
+ * The whole module graph arrives in one response so a cold isolate costs a
81
+ * single round trip, which means this number is also how much the host holds in
82
+ * memory before instantiating anything. Set below the runtime's own script
83
+ * limit so an oversized build fails in our tooling, where we can say which
84
+ * modules are large, rather than at dispatch, where the tenant sees a 502.
85
+ */
86
+ export const FUNCTIONS_BUNDLE_MAX_BYTES = 8 * 1024 * 1024;
87
+ const functionsRoutePathSchema = appRoutePathSchema({
88
+ subject: "Function routes",
89
+ });
90
+ /**
91
+ * A worker's dynamic route table. Anything not matched here is answered from
92
+ * the version's static content by wp.cloud and never reaches Cloudflare, which
93
+ * is both the cheaper path and the one that keeps assets ours.
94
+ */
95
+ export const functionsRouteSchema = z
96
+ .object({
97
+ method: httpMethodSchema.nullable().default(null),
98
+ path: functionsRoutePathSchema,
99
+ /** A terminal `:splat` route claims the whole subtree below `path`. */
100
+ subtree: z.boolean().default(false),
101
+ })
102
+ .strict();
103
+ export const functionsEndpointSourceSchema = executionEndpointSourceSchema(functionsRoutePathSchema);
104
+ /**
105
+ * One module in a bundle, in the shape the Worker Loader consumes.
106
+ *
107
+ * `commonjs` exists because bundlers still emit it and rejecting it would fail
108
+ * builds for a format the runtime accepts. Binary module types are deliberately
109
+ * absent: nothing we build today emits them, and adding one later is additive.
110
+ */
111
+ export const functionsBundleModuleSchema = z.union([
112
+ z.object({ js: z.string() }).strict(),
113
+ z.object({ cjs: z.string() }).strict(),
114
+ z.object({ text: z.string() }).strict(),
115
+ z.object({ json: z.unknown() }).strict(),
116
+ ]);
117
+ /**
118
+ * The document served at a bundle URL and parsed by the host.
119
+ *
120
+ * Both sides of that exchange validate against this schema, which is the point
121
+ * of it living here: the CLI's bundler and the host's loader are separate
122
+ * deployments that must agree, and the only thing keeping them honest is a
123
+ * shared definition of the bytes in between.
124
+ */
125
+ export const functionsBundleManifestSchema = z
126
+ .object({
127
+ format: z.literal(FUNCTIONS_BUNDLE_FORMAT),
128
+ mainModule: z.string().min(1).max(1024),
129
+ modules: z.record(z.string().min(1).max(1024), functionsBundleModuleSchema),
130
+ })
131
+ .strict()
132
+ .refine((manifest) => Object.hasOwn(manifest.modules, manifest.mainModule), {
133
+ message: "A bundle manifest must contain its own entry module.",
134
+ path: ["mainModule"],
135
+ });
136
+ /**
137
+ * Where the worker's compiled bytes live in the version's own content store.
138
+ * Unlike Zero's bundles these are not carried inline in the finalize payload:
139
+ * framework output routinely runs to megabytes, and inlining it would put the
140
+ * whole thing through the control plane, which the direct-from-wp.cloud rule
141
+ * forbids.
142
+ */
143
+ export const functionsBundleRefSchema = z
144
+ .object({
145
+ path: z
146
+ .string()
147
+ .min(1)
148
+ .startsWith(`${FUNCTIONS_RUNTIME_BUNDLE_ROOT}/`)
149
+ .refine((path) => !path.split("/").includes(".."), {
150
+ message: "Function bundle paths cannot traverse outside the bundle root.",
151
+ }),
152
+ sha256: executionSha256Schema,
153
+ size: z.number().int().nonnegative().max(FUNCTIONS_BUNDLE_MAX_BYTES),
154
+ })
155
+ .strict();
156
+ /**
157
+ * The path a bundle is served from.
158
+ *
159
+ * Content-addressed, so the response is immutable and can be cached at our edge
160
+ * forever — a cold isolate anywhere in the world costs one CDN hit rather than
161
+ * a round trip to the space's origin.
162
+ *
163
+ * The token rides in the path rather than the query string for exactly that
164
+ * reason: a query parameter is subject to cache-key normalisation, and a token
165
+ * that gets stripped from the key would let one space's cached bundle answer
166
+ * another space's URL.
167
+ *
168
+ * Both halves are load-bearing. The digest alone is unguessable to anyone who
169
+ * lacks the bytes, but it is derivable by anyone who *has* them, and it shows up
170
+ * in build output and `sf functions inspect`. The token adds the dimension the
171
+ * digest cannot: holding the code does not entitle you to fetch it from us, and
172
+ * rotating the site secret invalidates every URL at once.
173
+ */
174
+ export function functionsBundlePath(input) {
175
+ return `${FUNCTIONS_BUNDLE_ROUTE_PREFIX}/${bundleDigest(input.sha256)}/${input.token}/bundle.json`;
176
+ }
177
+ /**
178
+ * Where the bundle actually sits in the published version — the same path minus
179
+ * the token segment. The token authorises the read; it does not name the file,
180
+ * so rotating the signing key changes every URL without moving a single byte.
181
+ */
182
+ export function functionsBundleStoragePath(input) {
183
+ return `${FUNCTIONS_RUNTIME_BUNDLE_ROOT}/${bundleDigest(input.sha256)}/bundle.json`;
184
+ }
185
+ /**
186
+ * The digest is carried in contracts as `sha256:<hex>` but appears in paths as
187
+ * bare hex: a colon is legal in a path segment yet needlessly invites
188
+ * normalisation differences between the edge, the origin, and fetch.
189
+ */
190
+ function bundleDigest(sha256) {
191
+ return sha256.startsWith("sha256:") ? sha256.slice(7) : sha256;
192
+ }
193
+ /**
194
+ * Cloudflare pins runtime behaviour to a date rather than a version number, so
195
+ * a worker built today keeps today's semantics forever. We record the author's
196
+ * choice on the version, which is what makes rollback honest: promoting an old
197
+ * version restores the compatibility date it was built against.
198
+ */
199
+ const functionsCompatibilityDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
200
+ export const functionsWorkerArtifactSchema = z
201
+ .object({
202
+ format: z.literal("spacefast.functions.worker.v1"),
203
+ appName: z.string().min(1).max(128),
204
+ /**
205
+ * What the author wrote, for display: `handler.ts`, `.open-next/worker.js`.
206
+ * It names a file in their project, which after bundling no longer exists.
207
+ */
208
+ entry: z.string().min(1).max(1024),
209
+ /**
210
+ * The entry module's name *inside the bundle manifest* — what the loader
211
+ * instantiates. Carried here rather than read from the manifest because the
212
+ * origin dispatches without ever opening the bundle: the bytes go from our
213
+ * CDN straight to the isolate, and the origin only routes.
214
+ */
215
+ mainModule: z.string().min(1).max(1024),
216
+ bundle: functionsBundleRefSchema,
217
+ compatibilityDate: functionsCompatibilityDateSchema,
218
+ compatibilityFlags: z.array(z.string().min(1).max(128)).max(32).default([]),
219
+ routes: z.array(functionsRouteSchema).max(256).default([]),
220
+ /**
221
+ * Aggregate of what the worker's handlers reach, used to decide which
222
+ * brokered capabilities the relay will honour for this version. A worker
223
+ * that never declares `db` gets a relay that refuses `db.read` outright,
224
+ * so an injected dependency cannot widen authority at runtime.
225
+ */
226
+ capabilities: executionCapabilitiesSchema,
227
+ endpoints: z.array(functionsEndpointSourceSchema).max(256).default([]),
228
+ })
229
+ .strict();
230
+ /**
231
+ * The authority a dispatched worker may exercise, in the vocabulary the host
232
+ * speaks on the wire.
233
+ *
234
+ * Deliberately a different, narrower list than `executionCapabilitiesSchema`.
235
+ * That one records what a build *declared* it uses; this one is what the origin
236
+ * *grants*, resolved by the control plane at finalize so the origin forwards a
237
+ * decision rather than making one. Anything absent fails closed at the relay.
238
+ */
239
+ export const FUNCTIONS_DISPATCH_CAPABILITIES = ["db.read", "db.write", "fetch", "log"];
240
+ export const functionsDispatchCapabilitySchema = z.enum(FUNCTIONS_DISPATCH_CAPABILITIES);
241
+ /**
242
+ * Resolves a build's declared capabilities into the grant a dispatch carries.
243
+ *
244
+ * Three of the six declared capabilities have no dispatch counterpart, and each
245
+ * for its own reason:
246
+ *
247
+ * - `env` is not a runtime call at all. Values are resolved at finalize and
248
+ * travel in the config, so a worker reading `env` reaches nothing.
249
+ * - `auth` and `realtime` bind a handler to the local tier — see
250
+ * `endpointIsPortable` — so code declaring them deploys as a capsule and
251
+ * never arrives here.
252
+ *
253
+ * `db` widens to both read and write because a declaration says a handler
254
+ * touches the database, not how. Narrowing it would take per-statement analysis
255
+ * we do not do, and guessing "read-only" from a declaration would be a grant
256
+ * the author never asked for and cannot see.
257
+ */
258
+ export function functionsDispatchCapabilities(capabilities) {
259
+ const granted = new Set();
260
+ if (capabilities.db) {
261
+ granted.add("db.read");
262
+ granted.add("db.write");
263
+ }
264
+ if (capabilities.fetch) {
265
+ granted.add("fetch");
266
+ }
267
+ if (capabilities.logging) {
268
+ granted.add("log");
269
+ }
270
+ // Filtered from the canonical list so the order is stable: the grant is part
271
+ // of the host's isolate identity, and a reordering would retire warm isolates
272
+ // for no reason.
273
+ return FUNCTIONS_DISPATCH_CAPABILITIES.filter((capability) => granted.has(capability));
274
+ }
275
+ /** Everything except `log` needs the relay to mean anything. */
276
+ export function functionsGrantNeedsRelay(granted) {
277
+ return granted.some((capability) => capability !== "log");
278
+ }
279
+ /**
280
+ * What the space origin needs in order to dispatch to the host on its own. The
281
+ * shared secret is a wp.cloud site secret; it is never part of a version's
282
+ * content and never reaches tenant code, so it is not modelled here.
283
+ *
284
+ * There is no account id and no namespace: the origin talks to one host worker
285
+ * over HTTPS and holds no Cloudflare API credential at all.
286
+ */
287
+ export const functionsHostConfigSchema = z
288
+ .object({
289
+ /** The host worker's hostname, which wp.cloud dispatches to. */
290
+ hostname: z.string().min(1).max(255),
291
+ /**
292
+ * Where the host pulls this version's module graph, signed and minted at
293
+ * finalize.
294
+ *
295
+ * It is here rather than on the artifact because the artifact records what
296
+ * was built — a path and a digest, both stable — while this records how to
297
+ * reach it, which depends on a signing key and a hostname the build knew
298
+ * nothing about. Rotating the key changes every URL without changing a
299
+ * single artifact.
300
+ */
301
+ bundleUrl: z.string().url(),
302
+ })
303
+ .strict();
304
+ /**
305
+ * The callback a dispatched worker uses for `ctx.db`, `ctx.fetch` and logging.
306
+ *
307
+ * Each relay call re-enters the space's PHP-FPM pool, which is the deadlock
308
+ * hazard this product's admission control exists to bound: a proxied request
309
+ * occupies a worker for its whole life while its relay calls demand more. The
310
+ * batching allowance below is the other half of the answer — a handler that
311
+ * issues twenty statements must cost one relay round trip, not twenty. Measured
312
+ * against the PHP broker, batching twenty writes into one call is 8.3x faster
313
+ * than twenty separate ones.
314
+ */
315
+ export const functionsRelayConfigSchema = z
316
+ .object({
317
+ url: z.string().url(),
318
+ /**
319
+ * Bearer credential minted per version. Rotating it also retires the warm
320
+ * isolate holding it: the host folds this token into the isolate's identity
321
+ * precisely so that a revoked credential cannot outlive its revocation.
322
+ */
323
+ token: z.string().min(1),
324
+ maxBatchStatements: z.number().int().min(1).max(256),
325
+ maxConcurrentCalls: z.number().int().min(1).max(64),
326
+ })
327
+ .strict();
328
+ /**
329
+ * What a build declares about its worker — everything the CLI can know from the
330
+ * author's project alone.
331
+ *
332
+ * Unlike Zero, this is *not* the same document the runtime receives. A build
333
+ * cannot name the host it will be dispatched to, cannot mint the credential its
334
+ * relay calls will carry, and cannot decide what authority it is granted; all
335
+ * three are the platform's to say. Keeping them out of this schema is what makes
336
+ * that structural rather than a convention — a version's own metadata has no
337
+ * field in which to assert authority it was not given.
338
+ */
339
+ export const functionsSourceFinalizeSchema = z
340
+ .object({
341
+ runtimeKind: z.literal(FUNCTIONS_RUNTIME_KIND),
342
+ artifact: functionsWorkerArtifactSchema,
343
+ variables: z
344
+ .object({
345
+ source: z.literal("spacefast-variables"),
346
+ names: z.array(z.string().min(1)).default([]),
347
+ })
348
+ .strict()
349
+ .default({ source: "spacefast-variables", names: [] }),
350
+ inspect: z
351
+ .object({
352
+ policy: executionInspectPolicySchema.default("private"),
353
+ })
354
+ .strict()
355
+ .default({ policy: "private" }),
356
+ })
357
+ .strict();
358
+ /**
359
+ * The document the control plane sends to the runtime, which the engine stores
360
+ * beside the version's files and the origin reads on every dispatch.
361
+ *
362
+ * It is the build's declaration plus the four things only the platform can
363
+ * supply: where to dispatch, what the worker is allowed to do, the credential
364
+ * that lets it do those things, and the resolved values of its variables.
365
+ */
366
+ export const functionsRuntimeConfigSchema = functionsSourceFinalizeSchema
367
+ .extend({
368
+ host: functionsHostConfigSchema,
369
+ grantedCapabilities: z.array(functionsDispatchCapabilitySchema).max(8).default([]),
370
+ relay: functionsRelayConfigSchema.nullable().default(null),
371
+ /**
372
+ * Resolved at finalize, so a worker reading configuration never calls back
373
+ * to us for it — and so rotating a variable is a republish with an audit
374
+ * trail rather than a live mutation of what running code sees.
375
+ */
376
+ variableValues: z.record(z.string(), z.string()).default({}),
377
+ })
378
+ .strict()
379
+ .refine((config) => !functionsGrantNeedsRelay(config.grantedCapabilities) || config.relay, {
380
+ message: "Capabilities were granted without a relay to serve them.",
381
+ path: ["relay"],
382
+ });
383
+ export const functionsDeployMetadataSchema = z
384
+ .object({
385
+ artifactId: z.string().min(1).optional(),
386
+ finalize: functionsSourceFinalizeSchema,
387
+ })
388
+ .strict();
389
+ /**
390
+ * Builds the declaration a publish attaches to its version.
391
+ *
392
+ * Exists so the CLI's publish step and every test that needs a Functions
393
+ * version agree on the shape by construction rather than by copying an object
394
+ * literal around — the same reason `createZeroRuntimeFinalizePayload` exists.
395
+ */
396
+ export function createFunctionsSourceFinalize(input) {
397
+ return functionsSourceFinalizeSchema.parse({
398
+ runtimeKind: FUNCTIONS_RUNTIME_KIND,
399
+ artifact: {
400
+ format: "spacefast.functions.worker.v1",
401
+ appName: input.appName,
402
+ entry: input.entry,
403
+ mainModule: input.mainModule,
404
+ bundle: input.bundle,
405
+ compatibilityDate: input.compatibilityDate,
406
+ compatibilityFlags: input.compatibilityFlags ?? [],
407
+ routes: input.routes ?? [],
408
+ capabilities: input.capabilities ?? {},
409
+ endpoints: [],
410
+ },
411
+ variables: {
412
+ source: "spacefast-variables",
413
+ names: input.variableNames ?? [],
414
+ },
415
+ ...(input.inspectPolicy ? { inspect: { policy: input.inspectPolicy } } : {}),
416
+ });
417
+ }
418
+ /**
419
+ * What a version's worker is currently doing, as an observer of the space can
420
+ * actually determine.
421
+ *
422
+ * There is no upload state to report. A bundle is either in the version's
423
+ * content store or it is not, and dispatch is decided by which version is
424
+ * serving — so these three cover the whole space of answers, and each one is
425
+ * checkable rather than inferred from a job we ran earlier.
426
+ */
427
+ export const functionsExecutionStateSchema = z.enum([
428
+ /** No bundle at the version's bundle path. */
429
+ "absent",
430
+ /** Bundle present and dispatchable, but this version is not the live one. */
431
+ "ready",
432
+ /** This version is live: its routes dispatch to the host. */
433
+ "serving",
434
+ ]);
435
+ /**
436
+ * What a live worker is, as the `app` member of a space's runtime status.
437
+ *
438
+ * Shaped like `zeroAppSchema` and discriminated by the same `runtimeKind`, so a
439
+ * reader switches on one field rather than probing for which product answered.
440
+ * No `versionId`: the status response it rides in already names the live
441
+ * version.
442
+ */
443
+ export const functionsAppSchema = z
444
+ .object({
445
+ runtimeKind: z.literal(FUNCTIONS_RUNTIME_KIND),
446
+ artifactId: z.string().min(1),
447
+ appName: z.string().min(1),
448
+ entry: z.string().min(1),
449
+ compatibilityDate: functionsCompatibilityDateSchema,
450
+ compatibilityFlags: z.array(z.string()).default([]),
451
+ routes: z.array(functionsRouteSchema).default([]),
452
+ capabilities: executionCapabilitiesSchema,
453
+ executionState: functionsExecutionStateSchema,
454
+ bundleSize: z.number().int().nonnegative(),
455
+ variables: z
456
+ .object({
457
+ source: z.literal("spacefast-variables"),
458
+ names: z.array(z.string()).default([]),
459
+ })
460
+ .strict(),
461
+ inspect: z
462
+ .object({
463
+ policy: executionInspectPolicySchema,
464
+ })
465
+ .strict(),
466
+ })
467
+ .strict();
468
+ /**
469
+ * The wire shape of the origin's log-read route, not a public API contract.
470
+ *
471
+ * Handler logs reach callers through `GET /v1/spaces/:spaceId/logs/runtime`,
472
+ * which serves the platform's own `runtimeLogListResponseSchema` for both
473
+ * execution tiers. These aliases describe the hop underneath it: a worker tails
474
+ * its output to the origin that dispatched it, and the control plane reads it
475
+ * back from there. Keeping them named after this product is the point — the
476
+ * origin is the only place a wp.cloud-hosted space keeps anything, and Zero's
477
+ * records never travel this path at all.
478
+ */
479
+ export const functionsLogEntrySchema = executionLogEntrySchema;
480
+ export const functionsLogListQuerySchema = executionLogListQuerySchema;
481
+ export const functionsLogListResponseSchema = executionLogListResponseSchema;
482
+ /** Narrows a space's live runtime kind to this product. */
483
+ export function isFunctionsRuntime(kind) {
484
+ return kind === FUNCTIONS_RUNTIME_KIND;
485
+ }
@@ -2,8 +2,8 @@ import { z } from "zod";
2
2
  export declare const buildTargetValues: readonly ["production", "preview"];
3
3
  export declare const buildTriggerValues: readonly ["manual", "push", "pull_request", "retry"];
4
4
  export declare const buildTarget: z.ZodEnum<{
5
- production: "production";
6
5
  preview: "preview";
6
+ production: "production";
7
7
  }>;
8
8
  export declare const buildTrigger: z.ZodEnum<{
9
9
  push: "push";