@builtbyfriends/deploy-core 0.0.0-stage → 1.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present, Built By Friends Company
4
+ Copyright (c) 2026-present, Cloudflare, Inc.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @builtbyfriends/deploy-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared deployment contracts for bwf runtimes and deployment adapters. Includes manifests, progress events, routing rules, resource plans, and SQL and Durable Object migration metadata.
4
+
5
+ This package works in Node.js and Cloudflare Workers. To deploy an application, use the `bwf` CLI.
6
+
7
+ ## Documentation
8
+
9
+ See Deployment for deploying an app and Platform Development for building a runtime or adapter.
10
+
11
+ Read the bwf documentation online or use the Markdown guides and references in `node_modules/@builtbyfriends/bwf/docs/`, included with the `bwf` package.
@@ -0,0 +1,537 @@
1
+ export declare const R2_LOCATION_HINTS: readonly ["apac", "eeur", "enam", "weur", "wnam", "oc"];
2
+ type R2LocationHint = (typeof R2_LOCATION_HINTS)[number];
3
+ type StorageConfig = {
4
+ locationHint?: R2LocationHint;
5
+ };
6
+ export declare function isR2LocationHint(value: unknown): value is R2LocationHint;
7
+ export declare const MANIFEST_REDIRECT_RULE_STATUSES: ReadonlySet<number>;
8
+ export declare const MAX_ROUTING_RULES = 2e3;
9
+ /**
10
+ * Check the shape of an incoming deploy manifest. Returns an error message, or `null` when valid.
11
+ * Deploy code reads the manifest without re-checking, so run this before creating any deploy state.
12
+ */
13
+ export declare function validateManifestShape(manifest: unknown): string | null;
14
+ type DeployResource = {
15
+ type: "d1";
16
+ bindingName: string;
17
+ } | {
18
+ type: "kv";
19
+ bindingName: string;
20
+ } | {
21
+ type: "r2";
22
+ bindingName: string;
23
+ } | {
24
+ type: "queue";
25
+ bindingName: string;
26
+ resourceName: string;
27
+ consumer: QueueMeta;
28
+ } | {
29
+ type: "hyperdrive";
30
+ bindingName: string;
31
+ };
32
+ type DeployResourcePlan = {
33
+ resources: Array<DeployResource>;
34
+ runtime: {
35
+ ai: boolean;
36
+ schedules: NonNullable<DeployManifest["schedules"]>;
37
+ websocket: DeployManifest["websocket"] | null;
38
+ sandbox: DeployManifest["sandbox"] | null;
39
+ live: DeployManifest["live"] | null;
40
+ };
41
+ };
42
+ /**
43
+ * Convert a deployment manifest into provider-neutral resource intent.
44
+ *
45
+ * Resource names, remote ids, and injected platform bindings belong to the
46
+ * target adapter and are deliberately absent from this plan.
47
+ */
48
+ export declare function createDeployResourcePlan(manifest: DeployManifest): DeployResourcePlan;
49
+ /** A concrete destination that can execute a bwf deployment. */
50
+ type DeployTarget = "cloudflare" | "nosam";
51
+ type DeployAppType = "nosam" | "spa" | "static";
52
+ /**
53
+ * @deprecated bwf does not read deploy target capabilities. Removed in the
54
+ * next major version.
55
+ */
56
+ type DeployCapabilitySupport = "supported" | "partial" | "unsupported";
57
+ /**
58
+ * @deprecated bwf does not read deploy target capabilities. They do not gate
59
+ * deploys or appear in diagnostics. Removed in the next major version.
60
+ */
61
+ type DeployTargetCapabilities = {
62
+ managedProjects: boolean;
63
+ skipBuild: boolean;
64
+ appTypes: Readonly<Record<DeployAppType, DeployCapabilitySupport>>;
65
+ features: Readonly<{
66
+ auth: DeployCapabilitySupport;
67
+ cron: DeployCapabilitySupport;
68
+ queues: DeployCapabilitySupport;
69
+ durableState: DeployCapabilitySupport;
70
+ webSockets: DeployCapabilitySupport;
71
+ live: DeployCapabilitySupport;
72
+ sandbox: DeployCapabilitySupport;
73
+ remoteDevelopment: DeployCapabilitySupport;
74
+ deploymentHistory: DeployCapabilitySupport;
75
+ rollback: DeployCapabilitySupport;
76
+ secrets: DeployCapabilitySupport;
77
+ domains: DeployCapabilitySupport;
78
+ logs: DeployCapabilitySupport;
79
+ }>;
80
+ };
81
+ /**
82
+ * Boundary implemented by deployment targets.
83
+ *
84
+ * Build classification and packaging stay outside the adapter; provider
85
+ * credentials, resource names, remote ids, and execution stay inside it.
86
+ */
87
+ type DeployTargetAdapter<TOptions, TContext> = {
88
+ readonly target: DeployTarget;
89
+ /** @deprecated bwf ignores this field. Removed in the next major version. */
90
+ readonly capabilities: DeployTargetCapabilities;
91
+ deploy(root: string, options: TOptions, context: TContext): Promise<void>;
92
+ };
93
+ type DeployRuntimeFeatures = Readonly<{
94
+ assets: boolean;
95
+ auth: boolean;
96
+ cron: boolean;
97
+ queues: boolean;
98
+ migrations: boolean;
99
+ ai: boolean;
100
+ durableObjects: boolean;
101
+ webSockets: boolean;
102
+ live: boolean;
103
+ sandbox: boolean;
104
+ }>;
105
+ /** Canonical, target-neutral interpretation of a deployment manifest. */
106
+ type DeployIntent = Readonly<{
107
+ appType: DeployAppType;
108
+ hasWorker: boolean;
109
+ manifest: DeployManifest;
110
+ resourcePlan: DeployResourcePlan;
111
+ features: DeployRuntimeFeatures;
112
+ }>;
113
+ /**
114
+ * Interpret a manifest once before a target assigns provider names and ids.
115
+ * This function performs no I/O and does not mutate the manifest.
116
+ */
117
+ export declare function createDeployIntent(manifest: DeployManifest): DeployIntent;
118
+ export declare const DEPLOY_ARTIFACT_VERSION: 1;
119
+ /** Content-addressed metadata for one static asset in a deployment artifact. */
120
+ type DeployAssetManifestEntry = {
121
+ blake3: string;
122
+ md5: string;
123
+ size: number;
124
+ /** @deprecated v1 alias of `blake3`. */
125
+ hash: string;
126
+ };
127
+ /** Target-neutral output of packaging a bwf application for deployment. */
128
+ type DeployArtifact = Readonly<{
129
+ artifactVersion: typeof DEPLOY_ARTIFACT_VERSION;
130
+ manifest: Readonly<DeployManifest>;
131
+ assetManifest: Readonly<Record<string, Readonly<DeployAssetManifestEntry>>>;
132
+ /** Worker module bytes keyed by relative path, base64-encoded for transport. */
133
+ workerFiles?: Readonly<Record<string, string>>;
134
+ }>;
135
+ type DeploySourceMetadata = {
136
+ source: string | null;
137
+ commit: string | null;
138
+ repositoryUrl: string | null;
139
+ commitUrl: string | null;
140
+ gitRef: string | null;
141
+ };
142
+ /** One Worker module uploaded to R2 before the deployment is finalized. */
143
+ type DeployWorkerModule = {
144
+ /** Module path relative to the Worker output, the same key `workerFiles` uses. */
145
+ name: string;
146
+ /** Byte length of the module. */
147
+ size: number;
148
+ /** SHA-256 of the module bytes as 64 lowercase hex characters. */
149
+ sha256: string;
150
+ };
151
+ /** Request body of `POST /projects/:id/deploy/worker-upload-urls`. */
152
+ type DeployWorkerUploadRequest = {
153
+ modules: Array<DeployWorkerModule>;
154
+ };
155
+ /** Upload URLs for each requested module, in request order. */
156
+ type DeployWorkerUploadResponse = {
157
+ id: string;
158
+ urls: Array<{
159
+ url: string;
160
+ headers: Record<string, string>;
161
+ }>;
162
+ };
163
+ /** Worker modules already uploaded through `worker-upload-urls`, named by its upload `id`. */
164
+ type DeployWorkerInput = {
165
+ id: string;
166
+ modules: Array<DeployWorkerModule>;
167
+ };
168
+ /**
169
+ * JSON payload accepted by the managed deployment API. Worker modules travel
170
+ * either inline as `workerFiles` or uploaded beforehand as `workerInput`,
171
+ * never both.
172
+ */
173
+ type DeployUploadPayload = {
174
+ manifest: DeployManifest;
175
+ assetManifest: Record<string, DeployAssetManifestEntry>;
176
+ workerFiles?: Record<string, string>;
177
+ workerInput?: DeployWorkerInput;
178
+ } & DeploySourceMetadata & {
179
+ preflight: "true" | null;
180
+ };
181
+ /** Asset declaration accepted by the direct-upload URL endpoint. */
182
+ type DeployAssetUploadRequest = {
183
+ blake3: string;
184
+ md5: string;
185
+ size: number;
186
+ contentType: string;
187
+ };
188
+ /** Build one target-neutral artifact before either target adds provider state. */
189
+ export declare function createDeployArtifact(input: {
190
+ manifest: DeployManifest;
191
+ assetManifest: Record<string, DeployAssetManifestEntry>;
192
+ workerFiles?: Record<string, string>;
193
+ }): DeployArtifact;
194
+ /**
195
+ * Convert the canonical artifact into the stable hosted-platform wire shape.
196
+ * Pass `workerInput` when the Worker modules were uploaded beforehand; the
197
+ * artifact must then carry no inline `workerFiles`.
198
+ */
199
+ export declare function createDeployUploadPayload(artifact: DeployArtifact, metadata: DeploySourceMetadata & {
200
+ preflight: "true" | null;
201
+ }, workerInput?: DeployWorkerInput): DeployUploadPayload;
202
+ export declare function canonicalJson(value: unknown): string;
203
+ /** Commit to all executable bytes, asset hashes, bindings, migrations, and routing. */
204
+ export declare function deployArtifactDigest(artifact: DeployArtifact): Promise<string>;
205
+ /** Narrow object-shaped input without accepting null or arrays. */
206
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
207
+ /**
208
+ * Char-by-char SQL tokenizer shared by the migration classifier, the
209
+ * destructive-SQL guard, and the remote migration runner.
210
+ *
211
+ * Walks the input and yields contiguous segments. `sql` runs are
212
+ * emitted as `{ kind: 'sql', start, end }` so callers can `sql.slice`
213
+ * without character-by-character allocations. Special regions are
214
+ * yielded whole with their delimiters included in `[start, end)`.
215
+ *
216
+ * Lexical forms handled (SQLite / drizzle-kit SQLite output):
217
+ * - `-- line` line comments (terminate at `\n` or EOF)
218
+ * - `/* block *\/` block comments (tolerate unterminated — span to EOF)
219
+ * - `'...'` string literals with `''` doubled-quote escape
220
+ * - `"..."` / `` `...` `` identifier quotes with `""` / `` `` `` escape
221
+ * - `[...]` bracket identifiers, NO `]]` escape — a single
222
+ * `]` closes the identifier (SQLite semantics;
223
+ * differs from MS SQL)
224
+ *
225
+ * Not handled — intentional, every caller targets SQLite only:
226
+ * - Postgres `$tag$ ... $tag$` dollar-quoting
227
+ * - Postgres `E'...'` extended string literals
228
+ *
229
+ * Adding a new quoting form anywhere should land here so every caller
230
+ * stays in lockstep.
231
+ */
232
+ type SqlSegment = {
233
+ kind: "sql";
234
+ start: number;
235
+ end: number;
236
+ } | {
237
+ kind: "line-comment";
238
+ start: number;
239
+ end: number;
240
+ } | {
241
+ kind: "block-comment";
242
+ start: number;
243
+ end: number;
244
+ } | {
245
+ kind: "string";
246
+ start: number;
247
+ end: number;
248
+ } | {
249
+ kind: "ident-quote";
250
+ open: "\"" | "`" | "[";
251
+ start: number;
252
+ end: number;
253
+ };
254
+ export declare function tokenizeSql(sql: string): Generator<SqlSegment>;
255
+ export declare const MIGRATION_CLASSIFIER_VERSION = 1;
256
+ export declare const UNSPLIT_MULTI_STATEMENT_PRAGMA = "-- nosam:allow-unsplit-multi-statement";
257
+ type SqlMigrationClassification = {
258
+ kind: "single-statement";
259
+ stability: "stable";
260
+ } | {
261
+ kind: "breakpoint-framed";
262
+ stability: "stable";
263
+ statements: Array<string>;
264
+ } | {
265
+ kind: "legacy-unsplit-multi-statement";
266
+ stability: "legacy";
267
+ allowLegacy: boolean;
268
+ };
269
+ type MigrationPlanHashInput = SqlMigrationClassification & {
270
+ name: string;
271
+ dialect: "sqlite";
272
+ classifierVersion: number;
273
+ sqlHash: string;
274
+ };
275
+ export declare function canonicalSql(sql: string): string;
276
+ export declare function hasStandalonePragma(sql: string, pragma: string): boolean;
277
+ export declare function isSingleStatement(sql: string): boolean;
278
+ /**
279
+ * Split SQL on top-level semicolons, ignoring literals and comments. Returns
280
+ * null when a statement may contain a compound `BEGIN ... END` body (such as
281
+ * CREATE TRIGGER), whose inner semicolons cannot be told apart lexically.
282
+ */
283
+ export declare function splitSqlStatements(sql: string): Array<string> | null;
284
+ /** Classify SQL without imposing the caller's execution policy or hashing implementation. */
285
+ export declare function classifySqlMigration(sql: string): SqlMigrationClassification;
286
+ /** Preserve the classifier-v1 hash preimage; policy markers and warnings are not hashed. */
287
+ export declare function getMigrationPlanHashInput(plan: MigrationPlanHashInput): unknown;
288
+ export declare const SUPPORTED_MANIFEST_VERSIONS: ReadonlyArray<number>;
289
+ export type MigrationMeta = {
290
+ name: string;
291
+ destructive: boolean;
292
+ };
293
+ export type ScheduleMeta = {
294
+ name: string;
295
+ cron: string;
296
+ };
297
+ export type QueueMeta = {
298
+ name: string;
299
+ bindingName: string;
300
+ maxBatchSize?: number;
301
+ maxBatchTimeout?: number;
302
+ maxRetries?: number;
303
+ retryDelay?: number;
304
+ };
305
+ export type HeaderRule = {
306
+ pattern: string;
307
+ headers: Array<[string, string]>;
308
+ };
309
+ /** Public wire shape of a redirect, rewrite, or fallback rule. */
310
+ export type RedirectRule = {
311
+ source: string;
312
+ destination: string;
313
+ status: number;
314
+ /** Lowercase literal hostname. Path-only rules omit this field. */
315
+ host?: string;
316
+ };
317
+ export type AssetConfig = {
318
+ not_found_handling?: "none" | "single-page-application" | "404-page";
319
+ html_handling?: "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash" | "none";
320
+ /**
321
+ * Cloudflare Workers Assets routing. Managed dispatch also keeps matching
322
+ * worker-first paths out of its shared static asset caches so middleware runs.
323
+ */
324
+ run_worker_first?: boolean | Array<string>;
325
+ };
326
+ export type WebSocketRouteMeta = {
327
+ pattern: string;
328
+ filePath: string;
329
+ className: string;
330
+ bindingName?: string;
331
+ mode: "room" | "socket";
332
+ hasAuthGate: boolean;
333
+ };
334
+ export type WebSocketMigrationMeta = {
335
+ tag: string;
336
+ newClasses?: ReadonlyArray<string>;
337
+ newSqliteClasses?: ReadonlyArray<string>;
338
+ deletedClasses?: ReadonlyArray<string>;
339
+ };
340
+ export type DurableObjectMigrationStep = {
341
+ tag?: string;
342
+ new_classes?: ReadonlyArray<string>;
343
+ new_sqlite_classes?: ReadonlyArray<string>;
344
+ deleted_classes?: ReadonlyArray<string>;
345
+ renamed_classes?: ReadonlyArray<{
346
+ from: string;
347
+ to: string;
348
+ }>;
349
+ transferred_classes?: ReadonlyArray<{
350
+ from: string;
351
+ from_script: string;
352
+ to: string;
353
+ }>;
354
+ };
355
+ export type PlannedWebSocketMigrations = {
356
+ classes: ReadonlyArray<string>;
357
+ migrations: ReadonlyArray<WebSocketMigrationMeta>;
358
+ changed: boolean;
359
+ nextVersion: number;
360
+ };
361
+ /**
362
+ * Preserve an existing WebSocket class history while assigning every genuinely
363
+ * new class to SQLite-backed Durable Object storage.
364
+ */
365
+ export declare function planWebSocketMigrations(input: {
366
+ nextClasses: ReadonlyArray<string> | undefined;
367
+ previousClasses: ReadonlyArray<string> | undefined;
368
+ previousMigrations: ReadonlyArray<WebSocketMigrationMeta> | undefined;
369
+ currentVersion: number;
370
+ tagPrefix?: string;
371
+ }): PlannedWebSocketMigrations;
372
+ /** Append one SQLite class step without reclassifying an existing namespace. */
373
+ export declare function appendSqliteClassMigration(migrations: ReadonlyArray<DurableObjectMigrationStep>, classes: ReadonlyArray<string>, baseTag: string, knownExistingClasses?: ReadonlyArray<string>): {
374
+ migrations: ReadonlyArray<DurableObjectMigrationStep>;
375
+ added: boolean;
376
+ };
377
+ export type WebSocketManifestMeta = {
378
+ routes: ReadonlyArray<WebSocketRouteMeta>;
379
+ classes: ReadonlyArray<string>;
380
+ migrations?: ReadonlyArray<WebSocketMigrationMeta>;
381
+ };
382
+ export type SandboxMigrationMeta = {
383
+ tag: string;
384
+ newSqliteClasses?: ReadonlyArray<string>;
385
+ deletedClasses?: ReadonlyArray<string>;
386
+ };
387
+ /** Named images under the Durable Object scheduling policy must be digest-pinned. */
388
+ export declare function isSandboxRegistryImage(image: string): boolean;
389
+ export type SandboxManifestMeta = {
390
+ bindingName: string;
391
+ className: string;
392
+ containerName: string;
393
+ image: string;
394
+ instanceType?: string;
395
+ maxInstances?: number;
396
+ migrations?: ReadonlyArray<SandboxMigrationMeta>;
397
+ /** Written by the managed platform, never accepted from deployment clients. */
398
+ runtime?: {
399
+ protocol: 1 | 2;
400
+ };
401
+ /** Managed transport implemented by the application's bundled bwf runtime. */
402
+ controllerProtocol?: 1 | 2;
403
+ };
404
+ export type LiveMigrationMeta = {
405
+ tag: string;
406
+ newSqliteClasses?: ReadonlyArray<string>;
407
+ };
408
+ export type LiveManifestMeta = {
409
+ bindingName: string;
410
+ className: string;
411
+ storage: "sqlite";
412
+ classes: ReadonlyArray<string>;
413
+ migrations?: ReadonlyArray<LiveMigrationMeta>;
414
+ };
415
+ export type DurableObjectManifestMeta = {
416
+ bindings: ReadonlyArray<{
417
+ bindingName: string;
418
+ className: string;
419
+ storage: "sqlite";
420
+ }>;
421
+ /** Verified by the platform; never accepted from a deployment client. */
422
+ runtime?: {
423
+ protocol: 1;
424
+ namespaces: Record<string, string>;
425
+ };
426
+ };
427
+ export type DeployManifest = {
428
+ version: number;
429
+ /** R2 creation preferences. Requires manifest version 5. */
430
+ storage?: StorageConfig;
431
+ assetManifestVersion?: 1 | 2;
432
+ /** Authenticated framed HTTP delivery for managed inbound email. */
433
+ emailProtocolVersion?: 1;
434
+ auth?: boolean;
435
+ /** SQL execution policy; omitted means apply pending application and auth migrations. */
436
+ migrationMode?: "apply" | "skip";
437
+ bindings: {
438
+ d1?: Array<string>;
439
+ kv?: Array<string>;
440
+ r2?: Array<string>;
441
+ ai?: boolean;
442
+ hyperdrive?: Array<string>;
443
+ };
444
+ migrations?: {
445
+ dialect: "sqlite" | "postgresql" | "mysql";
446
+ pending: number;
447
+ protocolVersion?: 2;
448
+ classifierVersion?: number;
449
+ migrationListHash?: string;
450
+ stability?: "stable" | "legacy";
451
+ };
452
+ schedules?: Array<ScheduleMeta>;
453
+ queues?: Array<QueueMeta>;
454
+ ssr?: boolean;
455
+ type?: "nosam" | "spa" | "static";
456
+ /** @deprecated Legacy v1 static deployment discriminator. */
457
+ static?: "spa" | "ssg";
458
+ assetConfig?: AssetConfig;
459
+ vars?: Record<string, string>;
460
+ workerMain?: string;
461
+ compatibilityDate?: string;
462
+ compatibilityFlags?: Array<string>;
463
+ limits?: {
464
+ cpuMs?: number;
465
+ };
466
+ hashedAssetsPrefix?: string;
467
+ headerRules?: Array<HeaderRule>;
468
+ redirectRules?: Array<RedirectRule>;
469
+ /** Omitted values inherit the platform default; preserve explicit false. */
470
+ alwaysUseHttps?: boolean;
471
+ fallbackRules?: Array<RedirectRule>;
472
+ websocket?: WebSocketManifestMeta;
473
+ sandbox?: SandboxManifestMeta;
474
+ live?: LiveManifestMeta;
475
+ durableObjects?: DurableObjectManifestMeta;
476
+ };
477
+ export type DeployEvent = {
478
+ event: "start";
479
+ deploymentId: string;
480
+ } | {
481
+ event: "heartbeat";
482
+ deploymentId?: string;
483
+ step: string;
484
+ status?: "queued" | "running" | "recovering";
485
+ recoveryAt?: string;
486
+ } | {
487
+ event: "asset_upload";
488
+ total: number;
489
+ new: number;
490
+ cached: number;
491
+ } | {
492
+ event: "asset_upload_done";
493
+ } | {
494
+ event: "provisioning";
495
+ bindings: Array<string>;
496
+ } | {
497
+ event: "provisioning_done";
498
+ } | {
499
+ event: "worker_readiness";
500
+ } | {
501
+ event: "migration_start";
502
+ pending: number;
503
+ } | {
504
+ event: "migration";
505
+ name: string;
506
+ durationMs: number;
507
+ stability?: "stable" | "legacy";
508
+ } | {
509
+ event: "migration_warning";
510
+ message: string;
511
+ } | {
512
+ event: "worker_upload";
513
+ modules: number;
514
+ } | {
515
+ event: "worker_upload_done";
516
+ } | {
517
+ event: "queue_setup";
518
+ queues: Array<string>;
519
+ } | {
520
+ event: "queue_consumer_conflict";
521
+ queue: string;
522
+ ownerScript: string;
523
+ } | {
524
+ event: "done";
525
+ deployment: string;
526
+ url: string;
527
+ urls: Array<string>;
528
+ assets: number;
529
+ workers: number;
530
+ migrations?: number;
531
+ published?: boolean;
532
+ } | {
533
+ event: "error";
534
+ message: string;
535
+ step: string;
536
+ };
537
+ export type { DeployAppType, DeployArtifact, DeployAssetManifestEntry, DeployAssetUploadRequest, DeployCapabilitySupport, DeployIntent, DeployResource, DeployResourcePlan, DeployRuntimeFeatures, DeploySourceMetadata, DeployTarget, DeployTargetAdapter, DeployTargetCapabilities, DeployUploadPayload, DeployWorkerInput, DeployWorkerModule, DeployWorkerUploadRequest, DeployWorkerUploadResponse, MigrationPlanHashInput, R2LocationHint, SqlMigrationClassification, SqlSegment, StorageConfig };
package/dist/index.mjs ADDED
@@ -0,0 +1,700 @@
1
+ // src/storage.ts
2
+ const R2_LOCATION_HINTS = [
3
+ "apac",
4
+ "eeur",
5
+ "enam",
6
+ "weur",
7
+ "wnam",
8
+ "oc"
9
+ ];
10
+ function isR2LocationHint(value) {
11
+ return typeof value === "string" && R2_LOCATION_HINTS.some((hint) => hint === value);
12
+ }
13
+ // src/is-record.ts
14
+ /** Narrow object-shaped input without accepting null or arrays. */
15
+ function isRecord(value) {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+ // src/validate.ts
19
+ const MANIFEST_REDIRECT_RULE_STATUSES = /* @__PURE__ */ new Set([
20
+ 200,
21
+ 301,
22
+ 302,
23
+ 303,
24
+ 307,
25
+ 308
26
+ ]);
27
+ const MAX_ROUTING_RULES = 2e3;
28
+ const MAX_CRON_EXPRESSIONS = 100;
29
+ const MAX_SCHEDULES = 1e3;
30
+ const LITERAL_HOSTNAME_REGEX = /^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/;
31
+ function validateRuleHost(rule, kind, sourceRef) {
32
+ if (rule.host === void 0) return null;
33
+ if (typeof rule.host !== "string") return `invalid manifest shape: ${kind} entry ${sourceRef} host must be a string`;
34
+ const normalized = rule.host.toLowerCase();
35
+ if (!LITERAL_HOSTNAME_REGEX.test(normalized)) return `invalid manifest shape: ${kind} entry ${sourceRef} host must be a literal hostname (e.g. "www.example.com"; no scheme, port, path, or wildcards): ${JSON.stringify(rule.host)}`;
36
+ rule.host = normalized;
37
+ return null;
38
+ }
39
+ function validateRoutingRules(rules, kind) {
40
+ if (rules === void 0) return null;
41
+ if (!Array.isArray(rules)) return `invalid manifest shape: ${kind} must be an array`;
42
+ if (rules.length > 2e3) return `invalid manifest shape: ${kind} has ${rules.length} entries, exceeds the ${MAX_ROUTING_RULES} per-list limit`;
43
+ const rewritesOnly = kind === "fallbackRules";
44
+ for (const rule of rules) {
45
+ if (!isRecord(rule)) return `invalid manifest shape: ${kind} entries must be objects`;
46
+ if (typeof rule.source !== "string" || typeof rule.destination !== "string" || typeof rule.status !== "number") return `invalid manifest shape: ${kind} entries must have string source, string destination, and numeric status`;
47
+ const sourceRef = JSON.stringify(rule.source);
48
+ if (rewritesOnly && rule.status !== 200) return `invalid manifest shape: ${kind} entry ${sourceRef} status must be 200 (fallbacks are rewrites only)`;
49
+ if (!rewritesOnly && !MANIFEST_REDIRECT_RULE_STATUSES.has(rule.status)) return `invalid manifest shape: ${kind} entry ${sourceRef} status must be one of ${[...MANIFEST_REDIRECT_RULE_STATUSES].join(", ")} (200 = rewrite, 3xx = redirect)`;
50
+ if (rule.status === 200) {
51
+ const condition = rewritesOnly ? "" : " when status is 200";
52
+ if (rule.destination.includes("?")) return `invalid manifest shape: ${kind} entry ${sourceRef} destination must not contain a query string${condition}`;
53
+ if (!rule.destination.startsWith("/")) return `invalid manifest shape: ${kind} entry ${sourceRef} destination must be path-absolute (start with "/")${condition}`;
54
+ if (rule.destination.startsWith("//")) return `invalid manifest shape: ${kind} entry ${sourceRef} destination must not start with "//" (protocol-relative URLs parse cross-origin; use a single-slash path-absolute destination)`;
55
+ }
56
+ const hostError = validateRuleHost(rule, kind, sourceRef);
57
+ if (hostError) return hostError;
58
+ }
59
+ return null;
60
+ }
61
+ function validateClassMigrations(path, migrations, fields, requireNonEmptyTag = false) {
62
+ if (migrations === void 0) return null;
63
+ if (!Array.isArray(migrations)) return `invalid manifest shape: ${path} must be an array`;
64
+ for (const migration of migrations) {
65
+ if (!isRecord(migration)) return `invalid manifest shape: ${path} entries must be objects`;
66
+ if (typeof migration.tag !== "string" || requireNonEmptyTag && migration.tag.length === 0) return `invalid manifest shape: ${path} entries must have a ${requireNonEmptyTag ? "non-empty " : ""}string tag`;
67
+ for (const field of fields) {
68
+ const value = migration[field];
69
+ if (value !== void 0 && (!Array.isArray(value) || !value.every((className) => typeof className === "string"))) return `invalid manifest shape: ${path} ${field} must be an array of strings`;
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+ /**
75
+ * Check the shape of an incoming deploy manifest. Returns an error message, or `null` when valid.
76
+ * Deploy code reads the manifest without re-checking, so run this before creating any deploy state.
77
+ */
78
+ function validateManifestShape(manifest) {
79
+ if (!isRecord(manifest)) return "invalid manifest shape: expected a JSON object";
80
+ if (manifest.storage !== void 0) {
81
+ if (manifest.version !== 5) return "invalid manifest shape: storage requires manifest version 5";
82
+ if (!isRecord(manifest.storage) || !isR2LocationHint(manifest.storage.locationHint) || Object.keys(manifest.storage).some((key) => key !== "locationHint")) return "invalid manifest shape: storage.locationHint must be a supported R2 location hint";
83
+ }
84
+ if (manifest.emailProtocolVersion !== void 0 && manifest.emailProtocolVersion !== 1) return "invalid manifest shape: emailProtocolVersion must be 1";
85
+ if (manifest.migrationMode !== void 0 && manifest.migrationMode !== "apply" && manifest.migrationMode !== "skip") return "invalid manifest shape: migrationMode must be apply or skip";
86
+ if (!isRecord(manifest.bindings)) return "invalid manifest shape: bindings must be an object";
87
+ const bindings = manifest.bindings;
88
+ for (const key of [
89
+ "d1",
90
+ "kv",
91
+ "r2",
92
+ "hyperdrive"
93
+ ]) {
94
+ const bindingValue = bindings[key];
95
+ if (bindingValue === void 0) continue;
96
+ if (!Array.isArray(bindingValue) || !bindingValue.every((value) => typeof value === "string")) return `invalid manifest shape: bindings.${key} must be an array of strings`;
97
+ }
98
+ if (manifest.queues !== void 0) {
99
+ if (!Array.isArray(manifest.queues)) return "invalid manifest shape: queues must be an array";
100
+ for (const queue of manifest.queues) {
101
+ if (!isRecord(queue)) return "invalid manifest shape: queues entries must be objects";
102
+ if (typeof queue.name !== "string" || typeof queue.bindingName !== "string") return "invalid manifest shape: queues entries must have string name and bindingName";
103
+ for (const tuning of [
104
+ "maxBatchSize",
105
+ "maxBatchTimeout",
106
+ "maxRetries",
107
+ "retryDelay"
108
+ ]) {
109
+ const tuningValue = queue[tuning];
110
+ if (tuningValue === void 0) continue;
111
+ if (typeof tuningValue !== "number" || !Number.isFinite(tuningValue)) return `invalid manifest shape: queues entry ${tuning} must be a finite number`;
112
+ }
113
+ }
114
+ }
115
+ if (manifest.schedules !== void 0) {
116
+ if (!Array.isArray(manifest.schedules)) return "invalid manifest shape: schedules must be an array";
117
+ if (manifest.schedules.length > MAX_SCHEDULES) return `invalid manifest shape: schedules has ${manifest.schedules.length} entries, exceeds the ${MAX_SCHEDULES} per-project limit`;
118
+ const cronExpressions = /* @__PURE__ */ new Set();
119
+ for (const schedule of manifest.schedules) {
120
+ if (!isRecord(schedule)) return "invalid manifest shape: schedules entries must be objects";
121
+ if (typeof schedule.name !== "string" || typeof schedule.cron !== "string") return "invalid manifest shape: schedules entries must have string name and cron";
122
+ cronExpressions.add(schedule.cron);
123
+ }
124
+ if (cronExpressions.size > MAX_CRON_EXPRESSIONS) return `invalid manifest shape: schedules has ${cronExpressions.size} distinct cron expressions, exceeds the ${MAX_CRON_EXPRESSIONS} per-project limit`;
125
+ }
126
+ if (manifest.vars !== void 0) {
127
+ if (!isRecord(manifest.vars)) return "invalid manifest shape: vars must be an object";
128
+ for (const [k, v] of Object.entries(manifest.vars)) if (typeof v !== "string") return `invalid manifest shape: vars.${k} must be a string`;
129
+ }
130
+ if (manifest.migrations !== void 0) {
131
+ if (!isRecord(manifest.migrations)) return "invalid manifest shape: migrations must be an object";
132
+ const mig = manifest.migrations;
133
+ if (mig.dialect !== void 0) {
134
+ const allowed = [
135
+ "sqlite",
136
+ "postgresql",
137
+ "mysql"
138
+ ];
139
+ if (typeof mig.dialect !== "string" || !allowed.includes(mig.dialect)) return `invalid manifest shape: migrations.dialect must be one of ${allowed.join(", ")}`;
140
+ }
141
+ if (mig.pending !== void 0) {
142
+ if (typeof mig.pending !== "number" || !Number.isInteger(mig.pending) || mig.pending < 0) return "invalid manifest shape: migrations.pending must be a non-negative integer";
143
+ }
144
+ if (mig.protocolVersion !== void 0 && mig.protocolVersion !== 2) return "invalid manifest shape: migrations.protocolVersion must be 2";
145
+ if (mig.classifierVersion !== void 0 && (typeof mig.classifierVersion !== "number" || !Number.isInteger(mig.classifierVersion))) return "invalid manifest shape: migrations.classifierVersion must be an integer";
146
+ if (mig.migrationListHash !== void 0 && typeof mig.migrationListHash !== "string") return "invalid manifest shape: migrations.migrationListHash must be a string";
147
+ if (mig.stability !== void 0 && mig.stability !== "stable" && mig.stability !== "legacy") return "invalid manifest shape: migrations.stability must be stable or legacy";
148
+ }
149
+ if (manifest.auth !== void 0 && typeof manifest.auth !== "boolean") return "invalid manifest shape: auth must be a boolean";
150
+ if (manifest.ssr !== void 0 && typeof manifest.ssr !== "boolean") return "invalid manifest shape: ssr must be a boolean";
151
+ for (const key of [
152
+ "workerMain",
153
+ "compatibilityDate",
154
+ "hashedAssetsPrefix"
155
+ ]) if (manifest[key] !== void 0 && typeof manifest[key] !== "string") return `invalid manifest shape: ${key} must be a string`;
156
+ if (manifest.assetManifestVersion !== void 0) {
157
+ if (manifest.assetManifestVersion !== 1 && manifest.assetManifestVersion !== 2) return "invalid manifest shape: assetManifestVersion must be 1 or 2";
158
+ }
159
+ if (manifest.compatibilityFlags !== void 0) {
160
+ if (!Array.isArray(manifest.compatibilityFlags) || !manifest.compatibilityFlags.every((x) => typeof x === "string")) return "invalid manifest shape: compatibilityFlags must be an array of strings";
161
+ }
162
+ if (manifest.limits !== void 0) {
163
+ if (!isRecord(manifest.limits)) return "invalid manifest shape: limits must be an object";
164
+ const limits = manifest.limits;
165
+ if (limits.cpuMs !== void 0) {
166
+ if (typeof limits.cpuMs !== "number" || !Number.isSafeInteger(limits.cpuMs) || limits.cpuMs < 1) return "invalid manifest shape: limits.cpuMs must be a positive integer";
167
+ }
168
+ }
169
+ if (manifest.type !== void 0) {
170
+ const allowed = [
171
+ "nosam",
172
+ "spa",
173
+ "static"
174
+ ];
175
+ if (typeof manifest.type !== "string" || !allowed.includes(manifest.type)) return `invalid manifest shape: type must be one of ${allowed.join(", ")}`;
176
+ }
177
+ if (manifest.assetConfig !== void 0) {
178
+ if (!isRecord(manifest.assetConfig)) return "invalid manifest shape: assetConfig must be an object";
179
+ const assetConfig = manifest.assetConfig;
180
+ if (assetConfig.not_found_handling !== void 0 && ![
181
+ "none",
182
+ "single-page-application",
183
+ "404-page"
184
+ ].includes(assetConfig.not_found_handling)) return "invalid manifest shape: assetConfig.not_found_handling must be one of none, single-page-application, 404-page";
185
+ if (assetConfig.html_handling !== void 0 && ![
186
+ "auto-trailing-slash",
187
+ "force-trailing-slash",
188
+ "drop-trailing-slash",
189
+ "none"
190
+ ].includes(assetConfig.html_handling)) return "invalid manifest shape: assetConfig.html_handling must be one of auto-trailing-slash, force-trailing-slash, drop-trailing-slash, none";
191
+ }
192
+ if (manifest.headerRules !== void 0) {
193
+ if (!Array.isArray(manifest.headerRules)) return "invalid manifest shape: headerRules must be an array";
194
+ for (const rule of manifest.headerRules) {
195
+ if (!isRecord(rule)) return "invalid manifest shape: headerRules entries must be objects";
196
+ if (typeof rule.pattern !== "string") return "invalid manifest shape: headerRules entries must have a string pattern";
197
+ if (!Array.isArray(rule.headers)) return "invalid manifest shape: headerRules entries must have a headers array";
198
+ for (const pair of rule.headers) if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string" || typeof pair[1] !== "string") return "invalid manifest shape: headerRules headers entries must be [name, value] string pairs";
199
+ }
200
+ }
201
+ if (manifest.alwaysUseHttps !== void 0 && typeof manifest.alwaysUseHttps !== "boolean") return "invalid manifest shape: alwaysUseHttps must be a boolean";
202
+ const redirectRulesError = validateRoutingRules(manifest.redirectRules, "redirectRules");
203
+ if (redirectRulesError) return redirectRulesError;
204
+ const fallbackRulesError = validateRoutingRules(manifest.fallbackRules, "fallbackRules");
205
+ if (fallbackRulesError) return fallbackRulesError;
206
+ if (manifest.websocket !== void 0) {
207
+ if (!isRecord(manifest.websocket)) return "invalid manifest shape: websocket must be an object";
208
+ const websocket = manifest.websocket;
209
+ if (!Array.isArray(websocket.routes)) return "invalid manifest shape: websocket.routes must be an array";
210
+ for (const route of websocket.routes) {
211
+ if (!isRecord(route)) return "invalid manifest shape: websocket.routes entries must be objects";
212
+ if (typeof route.className !== "string") return "invalid manifest shape: websocket.routes entries must have a string className";
213
+ if (route.bindingName !== void 0 && typeof route.bindingName !== "string") return "invalid manifest shape: websocket.routes entry bindingName must be a string";
214
+ }
215
+ if (!Array.isArray(websocket.classes) || !websocket.classes.every((x) => typeof x === "string")) return "invalid manifest shape: websocket.classes must be an array of strings";
216
+ const migrationsError = validateClassMigrations("websocket.migrations", websocket.migrations, [
217
+ "newClasses",
218
+ "newSqliteClasses",
219
+ "deletedClasses"
220
+ ], true);
221
+ if (migrationsError) return migrationsError;
222
+ }
223
+ if (manifest.sandbox !== void 0) {
224
+ if (manifest.type === "static" || manifest.type === "spa") return "sandbox is not supported for static/spa deployments";
225
+ if (!isRecord(manifest.sandbox)) return "invalid manifest shape: sandbox must be an object";
226
+ const sandbox = manifest.sandbox;
227
+ for (const key of [
228
+ "bindingName",
229
+ "className",
230
+ "containerName",
231
+ "image"
232
+ ]) if (typeof sandbox[key] !== "string" || sandbox[key].length === 0) return `invalid manifest shape: sandbox.${key} must be a non-empty string`;
233
+ if (isLocalImageReference(sandbox.image)) return "invalid manifest shape: sandbox.image must be a registry image reference";
234
+ if (sandbox.instanceType !== void 0 && typeof sandbox.instanceType !== "string") return "invalid manifest shape: sandbox.instanceType must be a string";
235
+ if (sandbox.maxInstances !== void 0 && (typeof sandbox.maxInstances !== "number" || !Number.isInteger(sandbox.maxInstances) || sandbox.maxInstances < 1)) return "invalid manifest shape: sandbox.maxInstances must be a positive integer";
236
+ const migrationsError = validateClassMigrations("sandbox.migrations", sandbox.migrations, ["newSqliteClasses", "deletedClasses"]);
237
+ if (migrationsError) return migrationsError;
238
+ }
239
+ if (manifest.live !== void 0) {
240
+ if (!isRecord(manifest.live)) return "invalid manifest shape: live must be an object";
241
+ const live = manifest.live;
242
+ for (const key of ["bindingName", "className"]) if (typeof live[key] !== "string" || live[key].length === 0) return `invalid manifest shape: live.${key} must be a non-empty string`;
243
+ if (live.storage !== "sqlite") return "invalid manifest shape: live.storage must be \"sqlite\"";
244
+ if (!Array.isArray(live.classes) || !live.classes.every((x) => typeof x === "string")) return "invalid manifest shape: live.classes must be an array of strings";
245
+ const migrationsError = validateClassMigrations("live.migrations", live.migrations, ["newSqliteClasses"]);
246
+ if (migrationsError) return migrationsError;
247
+ }
248
+ if (manifest.durableObjects !== void 0) {
249
+ const durable = manifest.durableObjects;
250
+ if (manifest.version !== 4 && manifest.version !== 5 || !isRecord(durable) || !Array.isArray(durable.bindings)) return "invalid manifest shape: durableObjects requires manifest version 4 and a bindings array";
251
+ if (durable.bindings.length > 32) return "invalid manifest shape: at most 32 custom Durable Objects are supported";
252
+ const names = /* @__PURE__ */ new Set();
253
+ const classes = /* @__PURE__ */ new Set();
254
+ const otherBindings = /* @__PURE__ */ new Set([
255
+ ...Object.values(bindings).filter(Array.isArray).flat(),
256
+ ...Object.keys(isRecord(manifest.vars) ? manifest.vars : {}),
257
+ ...Array.isArray(manifest.queues) ? manifest.queues.map((q) => q.bindingName) : [],
258
+ ...isRecord(manifest.websocket) && Array.isArray(manifest.websocket.routes) ? manifest.websocket.routes.map((r) => r.bindingName ?? r.className) : [],
259
+ ...isRecord(manifest.live) ? [manifest.live.bindingName] : []
260
+ ]);
261
+ for (const binding of durable.bindings) {
262
+ if (!isRecord(binding) || Object.keys(binding).some((key) => ![
263
+ "bindingName",
264
+ "className",
265
+ "storage"
266
+ ].includes(key)) || typeof binding.bindingName !== "string" || !/^[A-Za-z_$][\w$]{0,127}$/.test(binding.bindingName) || binding.bindingName.startsWith("__") || [
267
+ "ASSETS",
268
+ "SEND_EMAIL",
269
+ "USAGE_EVENTS_QUEUE"
270
+ ].includes(binding.bindingName) || typeof binding.className !== "string" || !/^[A-Za-z_$][\w$]{0,127}$/.test(binding.className) || binding.storage !== "sqlite") return "invalid manifest shape: custom Durable Objects require local SQLite classes and valid binding names";
271
+ if (names.has(binding.bindingName) || classes.has(binding.className) || otherBindings.has(binding.bindingName)) return "invalid manifest shape: custom Durable Object bindings and classes must be unique";
272
+ names.add(binding.bindingName);
273
+ classes.add(binding.className);
274
+ }
275
+ }
276
+ return null;
277
+ }
278
+ function isLocalImageReference(image) {
279
+ return image.startsWith(".") || image.startsWith("/") || image.toLowerCase().includes("dockerfile");
280
+ }
281
+ // src/resource-plan.ts
282
+ /**
283
+ * Convert a deployment manifest into provider-neutral resource intent.
284
+ *
285
+ * Resource names, remote ids, and injected platform bindings belong to the
286
+ * target adapter and are deliberately absent from this plan.
287
+ */
288
+ function createDeployResourcePlan(manifest) {
289
+ const resources = [];
290
+ for (const bindingName of manifest.bindings.d1 ?? []) resources.push({
291
+ type: "d1",
292
+ bindingName
293
+ });
294
+ for (const bindingName of manifest.bindings.kv ?? []) resources.push({
295
+ type: "kv",
296
+ bindingName
297
+ });
298
+ for (const bindingName of manifest.bindings.r2 ?? []) resources.push({
299
+ type: "r2",
300
+ bindingName
301
+ });
302
+ for (const consumer of manifest.queues ?? []) resources.push({
303
+ type: "queue",
304
+ bindingName: consumer.bindingName,
305
+ resourceName: consumer.name,
306
+ consumer
307
+ });
308
+ for (const bindingName of manifest.bindings.hyperdrive ?? []) resources.push({
309
+ type: "hyperdrive",
310
+ bindingName
311
+ });
312
+ return {
313
+ resources,
314
+ runtime: {
315
+ ai: manifest.bindings.ai === true,
316
+ schedules: manifest.schedules ?? [],
317
+ websocket: manifest.websocket ?? null,
318
+ sandbox: manifest.sandbox ?? null,
319
+ live: manifest.live ?? null
320
+ }
321
+ };
322
+ }
323
+ // src/intent.ts
324
+ /**
325
+ * Interpret a manifest once before a target assigns provider names and ids.
326
+ * This function performs no I/O and does not mutate the manifest.
327
+ */
328
+ function createDeployIntent(manifest) {
329
+ const appType = manifest.type ?? "nosam";
330
+ const webSockets = (manifest.websocket?.classes.length ?? 0) > 0;
331
+ const live = manifest.live !== void 0;
332
+ const sandbox = manifest.sandbox !== void 0;
333
+ return {
334
+ appType,
335
+ hasWorker: appType === "nosam",
336
+ manifest,
337
+ resourcePlan: createDeployResourcePlan(manifest),
338
+ features: {
339
+ assets: manifest.assetConfig !== void 0,
340
+ auth: manifest.auth === true,
341
+ cron: (manifest.schedules?.length ?? 0) > 0,
342
+ queues: (manifest.queues?.length ?? 0) > 0,
343
+ migrations: (manifest.migrations?.pending ?? 0) > 0,
344
+ ai: manifest.bindings.ai === true,
345
+ durableObjects: webSockets || live || sandbox,
346
+ webSockets,
347
+ live,
348
+ sandbox
349
+ }
350
+ };
351
+ }
352
+ // src/artifact.ts
353
+ const DEPLOY_ARTIFACT_VERSION = 1;
354
+ /** Build one target-neutral artifact before either target adds provider state. */
355
+ function createDeployArtifact(input) {
356
+ return {
357
+ artifactVersion: 1,
358
+ manifest: input.manifest,
359
+ assetManifest: input.assetManifest,
360
+ ...input.workerFiles && Object.keys(input.workerFiles).length > 0 ? { workerFiles: input.workerFiles } : {}
361
+ };
362
+ }
363
+ /**
364
+ * Convert the canonical artifact into the stable hosted-platform wire shape.
365
+ * Pass `workerInput` when the Worker modules were uploaded beforehand; the
366
+ * artifact must then carry no inline `workerFiles`.
367
+ */
368
+ function createDeployUploadPayload(artifact, metadata, workerInput) {
369
+ if (workerInput && artifact.workerFiles) throw new Error("A deployment sends its Worker modules inline or as uploads, not both.");
370
+ return {
371
+ manifest: {
372
+ ...artifact.manifest,
373
+ bindings: { ...artifact.manifest.bindings }
374
+ },
375
+ assetManifest: { ...artifact.assetManifest },
376
+ ...artifact.workerFiles ? { workerFiles: { ...artifact.workerFiles } } : {},
377
+ ...workerInput ? { workerInput: {
378
+ id: workerInput.id,
379
+ modules: workerInput.modules.map((module) => ({ ...module }))
380
+ } } : {},
381
+ ...metadata
382
+ };
383
+ }
384
+ // src/canonical-json.ts
385
+ function canonicalJson(value) {
386
+ if (value === null) return "null";
387
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return JSON.stringify(value);
388
+ if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`;
389
+ if (typeof value === "object") {
390
+ const object = value;
391
+ return `{${Object.keys(object).sort().filter((key) => object[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`;
392
+ }
393
+ throw new TypeError(`Unsupported canonical JSON value: ${typeof value}`);
394
+ }
395
+ // src/artifact-digest.ts
396
+ /** Commit to all executable bytes, asset hashes, bindings, migrations, and routing. */
397
+ async function deployArtifactDigest(artifact) {
398
+ const host = globalThis;
399
+ const data = canonicalJson({
400
+ manifest: artifact.manifest,
401
+ assetManifest: artifact.assetManifest,
402
+ workerFiles: artifact.workerFiles ?? {}
403
+ });
404
+ const bytes = await host.crypto.subtle.digest("SHA-256", new host.TextEncoder().encode(data));
405
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
406
+ }
407
+ // src/sql-tokenize.ts
408
+ function* tokenizeSql(sql) {
409
+ const sqlLength = sql.length;
410
+ let index = 0;
411
+ let runStart = 0;
412
+ const flushRun = (upTo) => {
413
+ if (upTo > runStart) return {
414
+ kind: "sql",
415
+ start: runStart,
416
+ end: upTo
417
+ };
418
+ };
419
+ while (index < sqlLength) {
420
+ const character = sql[index];
421
+ const next = index + 1 < sqlLength ? sql[index + 1] : "";
422
+ if (character === "-" && next === "-") {
423
+ const run = flushRun(index);
424
+ if (run) yield run;
425
+ let scanIndex = index + 2;
426
+ while (scanIndex < sqlLength && sql[scanIndex] !== "\n") scanIndex++;
427
+ yield {
428
+ kind: "line-comment",
429
+ start: index,
430
+ end: scanIndex
431
+ };
432
+ index = scanIndex;
433
+ runStart = index;
434
+ continue;
435
+ }
436
+ if (character === "/" && next === "*") {
437
+ const run = flushRun(index);
438
+ if (run) yield run;
439
+ let scanIndex = index + 2;
440
+ while (scanIndex < sqlLength - 1 && !(sql[scanIndex] === "*" && sql[scanIndex + 1] === "/")) scanIndex++;
441
+ const end = Math.min(scanIndex + 2, sqlLength);
442
+ yield {
443
+ kind: "block-comment",
444
+ start: index,
445
+ end
446
+ };
447
+ index = end;
448
+ runStart = index;
449
+ continue;
450
+ }
451
+ if (character === "'") {
452
+ const run = flushRun(index);
453
+ if (run) yield run;
454
+ let scanIndex = index + 1;
455
+ while (scanIndex < sqlLength) {
456
+ if (sql[scanIndex] === "'" && sql[scanIndex + 1] === "'") {
457
+ scanIndex += 2;
458
+ continue;
459
+ }
460
+ if (sql[scanIndex] === "'") {
461
+ scanIndex++;
462
+ break;
463
+ }
464
+ scanIndex++;
465
+ }
466
+ yield {
467
+ kind: "string",
468
+ start: index,
469
+ end: scanIndex
470
+ };
471
+ index = scanIndex;
472
+ runStart = index;
473
+ continue;
474
+ }
475
+ if (character === "\"" || character === "`" || character === "[") {
476
+ const run = flushRun(index);
477
+ if (run) yield run;
478
+ const close = character === "[" ? "]" : character;
479
+ let scanIndex = index + 1;
480
+ while (scanIndex < sqlLength) {
481
+ if (close !== "]" && sql[scanIndex] === close && sql[scanIndex + 1] === close) {
482
+ scanIndex += 2;
483
+ continue;
484
+ }
485
+ if (sql[scanIndex] === close) {
486
+ scanIndex++;
487
+ break;
488
+ }
489
+ scanIndex++;
490
+ }
491
+ yield {
492
+ kind: "ident-quote",
493
+ open: character,
494
+ start: index,
495
+ end: scanIndex
496
+ };
497
+ index = scanIndex;
498
+ runStart = index;
499
+ continue;
500
+ }
501
+ index++;
502
+ }
503
+ const tail = flushRun(sqlLength);
504
+ if (tail) yield tail;
505
+ }
506
+ // src/migration-plan.ts
507
+ const MIGRATION_CLASSIFIER_VERSION = 1;
508
+ const UNSPLIT_MULTI_STATEMENT_PRAGMA = "-- nosam:allow-unsplit-multi-statement";
509
+ function canonicalSql(sql) {
510
+ return (sql.charCodeAt(0) === 65279 ? sql.slice(1) : sql).replace(/\r\n?/g, "\n");
511
+ }
512
+ function hasStandalonePragma(sql, pragma) {
513
+ return canonicalSql(sql).split("\n").some((line) => line.trim() === pragma);
514
+ }
515
+ /** Yield `--> statement-breakpoint` line comments outside literals. */
516
+ function* breakpointComments(normalized) {
517
+ for (const segment of tokenizeSql(normalized)) if (segment.kind === "line-comment" && normalized.slice(segment.start, segment.end).trim() === "--> statement-breakpoint") yield segment;
518
+ }
519
+ function splitBreakpointFramedSql(sql) {
520
+ const normalized = canonicalSql(sql);
521
+ const statements = [];
522
+ let cursor = 0;
523
+ for (const segment of breakpointComments(normalized)) {
524
+ const statement = normalized.slice(cursor, segment.start).trim();
525
+ if (statement) statements.push(statement);
526
+ cursor = segment.end;
527
+ }
528
+ const statement = normalized.slice(cursor).trim();
529
+ if (statement) statements.push(statement);
530
+ return statements;
531
+ }
532
+ function hasStatementBreakpointOutsideLiterals(sql) {
533
+ return !breakpointComments(canonicalSql(sql)).next().done;
534
+ }
535
+ function scanStatements(sql) {
536
+ const normalized = canonicalSql(sql);
537
+ const ranges = [];
538
+ let cursor = 0;
539
+ let inStatement = false;
540
+ let hasCompoundBody = false;
541
+ for (const segment of tokenizeSql(normalized)) {
542
+ if (segment.kind === "line-comment" || segment.kind === "block-comment") continue;
543
+ if (segment.kind === "string" || segment.kind === "ident-quote") {
544
+ inStatement = true;
545
+ continue;
546
+ }
547
+ if (/\b(?:BEGIN|TRIGGER)\b/i.test(normalized.slice(segment.start, segment.end))) hasCompoundBody = true;
548
+ for (let index = segment.start; index < segment.end; index++) {
549
+ const character = normalized[index];
550
+ if (character === ";") {
551
+ if (inStatement) {
552
+ ranges.push({
553
+ start: cursor,
554
+ end: index + 1
555
+ });
556
+ inStatement = false;
557
+ }
558
+ cursor = index + 1;
559
+ continue;
560
+ }
561
+ if (character !== " " && character !== " " && character !== "\n" && character !== "\r") inStatement = true;
562
+ }
563
+ }
564
+ if (inStatement) ranges.push({
565
+ start: cursor,
566
+ end: normalized.length
567
+ });
568
+ return {
569
+ normalized,
570
+ ranges,
571
+ hasCompoundBody
572
+ };
573
+ }
574
+ function isSingleStatement(sql) {
575
+ return scanStatements(sql).ranges.length === 1;
576
+ }
577
+ /**
578
+ * Split SQL on top-level semicolons, ignoring literals and comments. Returns
579
+ * null when a statement may contain a compound `BEGIN ... END` body (such as
580
+ * CREATE TRIGGER), whose inner semicolons cannot be told apart lexically.
581
+ */
582
+ function splitSqlStatements(sql) {
583
+ const { normalized, ranges, hasCompoundBody } = scanStatements(sql);
584
+ if (hasCompoundBody) return null;
585
+ return ranges.map((range) => normalized.slice(range.start, range.end).trim());
586
+ }
587
+ /** Classify SQL without imposing the caller's execution policy or hashing implementation. */
588
+ function classifySqlMigration(sql) {
589
+ if (hasStatementBreakpointOutsideLiterals(sql)) return {
590
+ kind: "breakpoint-framed",
591
+ stability: "stable",
592
+ statements: splitBreakpointFramedSql(sql)
593
+ };
594
+ if (isSingleStatement(sql)) return {
595
+ kind: "single-statement",
596
+ stability: "stable"
597
+ };
598
+ return {
599
+ kind: "legacy-unsplit-multi-statement",
600
+ stability: "legacy",
601
+ allowLegacy: hasStandalonePragma(sql, UNSPLIT_MULTI_STATEMENT_PRAGMA)
602
+ };
603
+ }
604
+ /** Preserve the classifier-v1 hash preimage; policy markers and warnings are not hashed. */
605
+ function getMigrationPlanHashInput(plan) {
606
+ const base = {
607
+ classifierVersion: plan.classifierVersion,
608
+ dialect: plan.dialect,
609
+ kind: plan.kind,
610
+ name: plan.name,
611
+ sqlHash: plan.sqlHash,
612
+ stability: plan.stability
613
+ };
614
+ if (plan.kind === "breakpoint-framed") base.statements = plan.statements;
615
+ return base;
616
+ }
617
+ // src/index.ts
618
+ const SUPPORTED_MANIFEST_VERSIONS = [
619
+ 3,
620
+ 4,
621
+ 5
622
+ ];
623
+ /**
624
+ * Preserve an existing WebSocket class history while assigning every genuinely
625
+ * new class to SQLite-backed Durable Object storage.
626
+ */
627
+ function planWebSocketMigrations(input) {
628
+ const nextClasses = sortUniqueStrings(input.nextClasses);
629
+ const previousClasses = sortUniqueStrings(input.previousClasses);
630
+ const previousMigrations = input.previousMigrations ?? [];
631
+ if (!!sameStringSet(nextClasses, previousClasses)) return {
632
+ classes: nextClasses,
633
+ migrations: previousMigrations,
634
+ changed: false,
635
+ nextVersion: input.currentVersion
636
+ };
637
+ const existingClasses = new Set(previousClasses);
638
+ for (const migration of previousMigrations) {
639
+ for (const name of migration.newClasses ?? []) existingClasses.add(name);
640
+ for (const name of migration.newSqliteClasses ?? []) existingClasses.add(name);
641
+ for (const name of migration.deletedClasses ?? []) existingClasses.delete(name);
642
+ }
643
+ const additions = nextClasses.filter((name) => !existingClasses.has(name));
644
+ if (additions.length === 0) return {
645
+ classes: nextClasses,
646
+ migrations: previousMigrations,
647
+ changed: true,
648
+ nextVersion: input.currentVersion
649
+ };
650
+ const nextVersion = input.currentVersion + 1;
651
+ return {
652
+ classes: nextClasses,
653
+ migrations: [...previousMigrations, {
654
+ tag: `${input.tagPrefix ?? "ws"}-v${nextVersion}`,
655
+ newSqliteClasses: additions
656
+ }],
657
+ changed: true,
658
+ nextVersion
659
+ };
660
+ }
661
+ /** Append one SQLite class step without reclassifying an existing namespace. */
662
+ function appendSqliteClassMigration(migrations, classes, baseTag, knownExistingClasses = []) {
663
+ const existingClasses = new Set(knownExistingClasses);
664
+ for (const migration of migrations) {
665
+ for (const name of migration.new_classes ?? []) existingClasses.add(name);
666
+ for (const name of migration.new_sqlite_classes ?? []) existingClasses.add(name);
667
+ for (const rename of migration.renamed_classes ?? []) {
668
+ existingClasses.delete(rename.from);
669
+ existingClasses.add(rename.to);
670
+ }
671
+ for (const transfer of migration.transferred_classes ?? []) existingClasses.add(transfer.to);
672
+ for (const name of migration.deleted_classes ?? []) existingClasses.delete(name);
673
+ }
674
+ const additions = sortUniqueStrings(classes).filter((name) => !existingClasses.has(name));
675
+ if (additions.length === 0) return {
676
+ migrations,
677
+ added: false
678
+ };
679
+ const tags = new Set(migrations.map((migration) => migration.tag).filter(Boolean));
680
+ let tag = baseTag;
681
+ for (let suffix = 2; tags.has(tag); suffix++) tag = `${baseTag}-${suffix}`;
682
+ return {
683
+ migrations: [...migrations, {
684
+ tag,
685
+ new_sqlite_classes: additions
686
+ }],
687
+ added: true
688
+ };
689
+ }
690
+ function sortUniqueStrings(values) {
691
+ return [...new Set(values ?? [])].sort((a, b) => a.localeCompare(b));
692
+ }
693
+ function sameStringSet(a, b) {
694
+ return a.length === b.length && a.every((value, index) => value === b[index]);
695
+ }
696
+ /** Named images under the Durable Object scheduling policy must be digest-pinned. */
697
+ function isSandboxRegistryImage(image) {
698
+ return /^registry\.cloudflare\.com\/[^/@\s]+\/[^@\s]+@sha256:[a-f\d]{64}$/.test(image);
699
+ }
700
+ export { DEPLOY_ARTIFACT_VERSION, MANIFEST_REDIRECT_RULE_STATUSES, MAX_ROUTING_RULES, MIGRATION_CLASSIFIER_VERSION, R2_LOCATION_HINTS, SUPPORTED_MANIFEST_VERSIONS, UNSPLIT_MULTI_STATEMENT_PRAGMA, appendSqliteClassMigration, canonicalJson, canonicalSql, classifySqlMigration, createDeployArtifact, createDeployIntent, createDeployResourcePlan, createDeployUploadPayload, deployArtifactDigest, getMigrationPlanHashInput, hasStandalonePragma, isR2LocationHint, isRecord, isSandboxRegistryImage, isSingleStatement, planWebSocketMigrations, splitSqlStatements, tokenizeSql, validateManifestShape };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@builtbyfriends/deploy-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.9.2",
4
+ "description": "Shared deployment contracts, manifests, and resource plans for bwf.",
5
+ "homepage": "https://github.com/builtbyfriends/platform",
6
+ "bugs": {
7
+ "url": "https://github.com/builtbyfriends/platform/issues"
8
+ },
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/builtbyfriends/platform.git",
13
+ "directory": "packages/deploy-core"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "type": "module",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.mts",
22
+ "import": "./dist/index.mjs"
23
+ }
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "devDependencies": {
29
+ "typescript": "7.0.2",
30
+ "vite-plus": "1.6.0"
31
+ },
32
+ "scripts": {
33
+ "build": "vp pack",
34
+ "dev": "vp pack --watch",
35
+ "typecheck": "tsc --noEmit"
36
+ }
6
37
  }