@astrale-os/adapter-cloudflare 0.4.10 → 0.5.0-beta.100

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 (214) hide show
  1. package/CHANGELOG.md +1193 -0
  2. package/README.md +29 -0
  3. package/dist/adapter.d.ts +15 -0
  4. package/dist/adapter.js +76 -0
  5. package/dist/build/artifact.d.ts +7 -0
  6. package/dist/build/artifact.js +165 -0
  7. package/dist/build/bundle/admit.d.ts +1 -0
  8. package/dist/build/bundle/admit.js +9 -0
  9. package/dist/build/closure.d.ts +2 -0
  10. package/dist/build/closure.js +22 -0
  11. package/dist/build/codegen/execution.d.ts +3 -0
  12. package/dist/build/codegen/execution.js +2 -0
  13. package/dist/{codegen → build/codegen}/merge.d.ts +0 -1
  14. package/dist/{codegen → build/codegen}/merge.js +0 -1
  15. package/dist/{codegen → build/codegen}/wrangler.d.ts +19 -4
  16. package/dist/{codegen → build/codegen}/wrangler.js +49 -13
  17. package/dist/build/configuration/addressing.d.ts +2 -0
  18. package/dist/build/configuration/addressing.js +11 -0
  19. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  20. package/dist/build/configuration/invocation-timeout.js +9 -0
  21. package/dist/build/configuration/request-limit.d.ts +2 -0
  22. package/dist/build/configuration/request-limit.js +9 -0
  23. package/dist/build/configuration/router.d.ts +7 -0
  24. package/dist/build/configuration/router.js +11 -0
  25. package/dist/build/configuration/worker-name.d.ts +2 -0
  26. package/dist/build/configuration/worker-name.js +18 -0
  27. package/dist/build/configuration.d.ts +5 -0
  28. package/dist/build/configuration.js +5 -0
  29. package/dist/build/direct.d.ts +4 -0
  30. package/dist/build/direct.js +93 -0
  31. package/dist/build/frontend/files.d.ts +7 -0
  32. package/dist/build/frontend/files.js +60 -0
  33. package/dist/build/frontend/routes.d.ts +2 -0
  34. package/dist/build/frontend/routes.js +11 -0
  35. package/dist/build/index.d.ts +8 -0
  36. package/dist/build/index.js +7 -0
  37. package/dist/build/materialize.d.ts +4 -0
  38. package/dist/build/materialize.js +10 -0
  39. package/dist/build/metafile.d.ts +5 -0
  40. package/dist/build/metafile.js +14 -0
  41. package/dist/build/qualification.d.ts +5 -0
  42. package/dist/build/qualification.js +7 -0
  43. package/dist/build/roots.d.ts +2 -0
  44. package/dist/build/roots.js +34 -0
  45. package/dist/build/worker/artifact.d.ts +40 -0
  46. package/dist/build/worker/artifact.js +1 -0
  47. package/dist/build/worker/artifact.load.d.ts +3 -0
  48. package/dist/build/worker/artifact.load.js +308 -0
  49. package/dist/build/worker/artifact.manifest.d.ts +48 -0
  50. package/dist/build/worker/artifact.manifest.js +87 -0
  51. package/dist/build/worker/artifact.paths.d.ts +4 -0
  52. package/dist/build/worker/artifact.paths.js +25 -0
  53. package/dist/build/worker/codegen/entry.d.ts +2 -0
  54. package/dist/build/worker/codegen/entry.js +28 -0
  55. package/dist/build/worker/codegen/service.d.ts +18 -0
  56. package/dist/build/worker/codegen/service.js +53 -0
  57. package/dist/build/worker/execution.prepare.d.ts +18 -0
  58. package/dist/build/worker/execution.prepare.js +112 -0
  59. package/dist/build/worker/index.d.ts +2 -0
  60. package/dist/build/worker/index.js +1 -0
  61. package/dist/build/worker/modules.d.ts +11 -0
  62. package/dist/build/worker/modules.js +26 -0
  63. package/dist/build/worker/runtime.d.ts +10 -0
  64. package/dist/build/worker/runtime.js +35 -0
  65. package/dist/build/worker/specifier.d.ts +1 -0
  66. package/dist/build/worker/specifier.js +5 -0
  67. package/dist/cloudflare.d.ts +1 -37
  68. package/dist/cloudflare.js +1 -271
  69. package/dist/deploy/deploy.d.ts +16 -0
  70. package/dist/deploy/deploy.js +204 -0
  71. package/dist/deploy/index.d.ts +1 -0
  72. package/dist/deploy/index.js +1 -0
  73. package/dist/deploy/output.d.ts +2 -0
  74. package/dist/deploy/output.js +10 -0
  75. package/dist/development/develop.d.ts +15 -0
  76. package/dist/development/develop.js +270 -0
  77. package/dist/development/frontend.d.ts +11 -0
  78. package/dist/development/frontend.js +109 -0
  79. package/dist/development/host.d.ts +2 -0
  80. package/dist/development/host.js +46 -0
  81. package/dist/development/port.d.ts +1 -0
  82. package/dist/development/port.js +12 -0
  83. package/dist/development/readiness.d.ts +14 -0
  84. package/dist/development/readiness.js +71 -0
  85. package/dist/development/resolved-fetch.d.ts +17 -0
  86. package/dist/development/resolved-fetch.js +80 -0
  87. package/dist/development/worker-output.d.ts +2 -0
  88. package/dist/development/worker-output.js +25 -0
  89. package/dist/development/worker.d.ts +17 -0
  90. package/dist/development/worker.js +147 -0
  91. package/dist/identity/binding.d.ts +2 -0
  92. package/dist/identity/binding.js +2 -0
  93. package/dist/identity/index.d.ts +3 -0
  94. package/dist/identity/index.js +3 -0
  95. package/dist/identity/material.d.ts +7 -0
  96. package/dist/identity/material.js +42 -0
  97. package/dist/identity/secret.d.ts +3 -0
  98. package/dist/identity/secret.js +7 -0
  99. package/dist/identity/source.d.ts +26 -0
  100. package/dist/identity/source.js +127 -0
  101. package/dist/index.d.ts +8 -8
  102. package/dist/index.js +7 -7
  103. package/dist/params.d.ts +50 -23
  104. package/dist/params.js +0 -1
  105. package/dist/release/deployment.d.ts +44 -0
  106. package/dist/release/deployment.js +141 -0
  107. package/dist/release/index.d.ts +2 -0
  108. package/dist/release/index.js +2 -0
  109. package/dist/release/staged-worker-name.d.ts +3 -0
  110. package/dist/release/staged-worker-name.js +10 -0
  111. package/dist/worker/entry.d.ts +44 -0
  112. package/dist/worker/entry.js +184 -0
  113. package/dist/worker/fetch.d.ts +11 -0
  114. package/dist/worker/fetch.js +31 -0
  115. package/dist/worker/identity.d.ts +7 -0
  116. package/dist/worker/identity.js +23 -0
  117. package/dist/worker/index.d.ts +2 -0
  118. package/dist/worker/index.js +2 -0
  119. package/dist/wrangler/bundle.d.ts +10 -0
  120. package/dist/wrangler/bundle.js +27 -0
  121. package/dist/wrangler/deploy.d.ts +24 -0
  122. package/dist/wrangler/deploy.js +44 -0
  123. package/dist/wrangler/index.d.ts +5 -0
  124. package/dist/wrangler/index.js +5 -0
  125. package/dist/wrangler/process.d.ts +17 -0
  126. package/dist/wrangler/process.js +115 -0
  127. package/dist/wrangler/secrets.d.ts +6 -0
  128. package/dist/wrangler/secrets.js +58 -0
  129. package/dist/wrangler/status.d.ts +14 -0
  130. package/dist/wrangler/status.js +56 -0
  131. package/dist/wrangler/type-generation.d.ts +6 -0
  132. package/dist/wrangler/type-generation.js +19 -0
  133. package/package.json +41 -18
  134. package/template/astrale.config.ts +26 -18
  135. package/dist/assets-pack.d.ts +0 -8
  136. package/dist/assets-pack.d.ts.map +0 -1
  137. package/dist/assets-pack.js +0 -30
  138. package/dist/assets-pack.js.map +0 -1
  139. package/dist/build.d.ts +0 -16
  140. package/dist/build.d.ts.map +0 -1
  141. package/dist/build.js +0 -15
  142. package/dist/build.js.map +0 -1
  143. package/dist/client.d.ts +0 -17
  144. package/dist/client.d.ts.map +0 -1
  145. package/dist/client.js +0 -59
  146. package/dist/client.js.map +0 -1
  147. package/dist/cloudflare.d.ts.map +0 -1
  148. package/dist/cloudflare.js.map +0 -1
  149. package/dist/codegen/identity.d.ts +0 -10
  150. package/dist/codegen/identity.d.ts.map +0 -1
  151. package/dist/codegen/identity.js +0 -32
  152. package/dist/codegen/identity.js.map +0 -1
  153. package/dist/codegen/merge.d.ts.map +0 -1
  154. package/dist/codegen/merge.js.map +0 -1
  155. package/dist/codegen/worker.d.ts +0 -51
  156. package/dist/codegen/worker.d.ts.map +0 -1
  157. package/dist/codegen/worker.js +0 -120
  158. package/dist/codegen/worker.js.map +0 -1
  159. package/dist/codegen/wrangler.d.ts.map +0 -1
  160. package/dist/codegen/wrangler.js.map +0 -1
  161. package/dist/index.d.ts.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/params.d.ts.map +0 -1
  164. package/dist/params.js.map +0 -1
  165. package/dist/parse-output.d.ts +0 -25
  166. package/dist/parse-output.d.ts.map +0 -1
  167. package/dist/parse-output.js +0 -53
  168. package/dist/parse-output.js.map +0 -1
  169. package/dist/wrangler-cli.d.ts +0 -78
  170. package/dist/wrangler-cli.d.ts.map +0 -1
  171. package/dist/wrangler-cli.js +0 -251
  172. package/dist/wrangler-cli.js.map +0 -1
  173. package/src/assets-pack.ts +0 -32
  174. package/src/build.ts +0 -16
  175. package/src/client.ts +0 -89
  176. package/src/cloudflare.ts +0 -321
  177. package/src/codegen/identity.ts +0 -40
  178. package/src/codegen/merge.ts +0 -92
  179. package/src/codegen/worker.ts +0 -136
  180. package/src/codegen/wrangler.ts +0 -105
  181. package/src/index.ts +0 -21
  182. package/src/params.ts +0 -96
  183. package/src/parse-output.ts +0 -54
  184. package/src/wrangler-cli.ts +0 -324
  185. package/template/.env.example +0 -9
  186. package/template/.gitignore.template +0 -16
  187. package/template/CLAUDE.md +0 -13
  188. package/template/README.md +0 -47
  189. package/template/client/.gitignore.template +0 -4
  190. package/template/client/__tests__/app.test.tsx +0 -15
  191. package/template/client/components.json +0 -25
  192. package/template/client/index.html +0 -12
  193. package/template/client/package.json +0 -35
  194. package/template/client/src/app.tsx +0 -52
  195. package/template/client/src/components/ui/cn.ts +0 -6
  196. package/template/client/src/main.tsx +0 -9
  197. package/template/client/src/styles.css +0 -78
  198. package/template/client/tsconfig.json +0 -26
  199. package/template/client/vite.config.ts +0 -22
  200. package/template/client/vitest.config.ts +0 -13
  201. package/template/core/README.md +0 -7
  202. package/template/deps.ts +0 -9
  203. package/template/domain.ts +0 -11
  204. package/template/env.ts +0 -8
  205. package/template/icons.ts +0 -4
  206. package/template/integrations/README.md +0 -7
  207. package/template/oxlint.config.ts +0 -1
  208. package/template/package.json +0 -58
  209. package/template/pnpm-workspace.yaml +0 -31
  210. package/template/runtime/index.ts +0 -8
  211. package/template/schema/index.ts +0 -10
  212. package/template/simulation/README.md +0 -12
  213. package/template/tsconfig.json +0 -28
  214. package/template/vitest.config.ts +0 -7
@@ -1,271 +1 @@
1
- /**
2
- * `cloudflare(envs)` — the Cloudflare deployment adapter.
3
- *
4
- * Owns everything target-specific: it codegens the Worker entry + wrangler
5
- * config (the dev never sees a `wrangler.jsonc`), builds the optional client
6
- * SPA, and shells out to `wrangler`. `watch` → `wrangler dev` (local URL);
7
- * `deploy` → `wrangler deploy` (workers.dev or a custom-domain URL); secrets →
8
- * `wrangler secret bulk`. Both `watch` and `deploy` return the URL the CLI
9
- * prints and `astrale domain install <url>` consumes.
10
- */
11
- import { defineAdapter } from '@astrale-os/sdk';
12
- import { mkdir, rename, writeFile } from 'node:fs/promises';
13
- import { join } from 'node:path';
14
- import { buildClient, resolveClientDir } from './client';
15
- import { ensureIdentity } from './codegen/identity';
16
- import { generateWorkerEntry } from './codegen/worker';
17
- import { generateWranglerConfig } from './codegen/wrangler';
18
- import { bulkPutSecrets, runWranglerDeploy, runWranglerDev } from './wrangler-cli';
19
- const DEFAULT_PORT = 8787;
20
- export function cloudflare(envs) {
21
- return defineAdapter({
22
- name: 'cloudflare',
23
- envs,
24
- async watch(params, ctx) {
25
- const clientDir = resolveCloudflareClientDir(params, ctx);
26
- const { configPath, port } = await prepare(params, ctx, 'dev', {
27
- servesClient: Boolean(clientDir),
28
- bundleAssets: Boolean(clientDir),
29
- });
30
- if (clientDir)
31
- await buildClient(clientDir, ctx.projectDir, logTo());
32
- const handle = await runWranglerDev({
33
- projectDir: ctx.projectDir,
34
- configPath,
35
- port,
36
- remote: Boolean(params.remote),
37
- autoPickPort: params.port === undefined,
38
- ...(params.host ? { ip: '0.0.0.0' } : {}),
39
- onReload: ctx.onReload,
40
- onLog: logTo(),
41
- });
42
- // With --host the actionable URL is the PUBLIC one (the tunnel/proxy
43
- // front), not the local bind — print and spec-stamp that.
44
- return { url: params.host ?? handle.url, stop: handle.stop };
45
- },
46
- // Config hot-regen: rewrite the generated files only — the running
47
- // `wrangler dev` watches its `--config` (and the worker entry) and reloads
48
- // them itself, so a `astrale.config.ts` edit lands without a restart.
49
- // Mirrors `watch`'s prep exactly (codegen + client build), minus the spawn.
50
- async regenerate(params, ctx) {
51
- const clientDir = resolveCloudflareClientDir(params, ctx);
52
- await prepare(params, ctx, 'dev', {
53
- servesClient: Boolean(clientDir),
54
- bundleAssets: Boolean(clientDir),
55
- });
56
- if (clientDir)
57
- await buildClient(clientDir, ctx.projectDir, logTo());
58
- },
59
- async deploy(params, ctx) {
60
- const clientDir = resolveCloudflareClientDir(params, ctx);
61
- const { configPath, fallbackConfigPath, workerName: name, } = await prepare(params, ctx, 'deploy', {
62
- servesClient: Boolean(clientDir),
63
- bundleAssets: Boolean(clientDir),
64
- });
65
- if (clientDir)
66
- await buildClient(clientDir, ctx.projectDir, logTo());
67
- const { url } = await runWranglerDeploy({
68
- projectDir: ctx.projectDir,
69
- configPath,
70
- workerName: name,
71
- ...(fallbackConfigPath ? { fallbackConfigPath } : {}),
72
- ...(params.route ? { route: params.route } : {}),
73
- onLog: logTo(),
74
- });
75
- if (Object.keys(ctx.secrets).length > 0) {
76
- await bulkPutSecrets({
77
- projectDir: ctx.projectDir,
78
- configPath,
79
- secrets: ctx.secrets,
80
- onLog: logTo(),
81
- });
82
- }
83
- // A first deploy on a fresh `*.workers.dev` host can take ~30-60s to
84
- // propagate; an `astrale domain install <url>` issued right away would
85
- // 404 (Cloudflare 1042). Block until the URL actually serves so the
86
- // install line we print is immediately actionable.
87
- await waitUntilLive(url, logTo());
88
- return { url };
89
- },
90
- secretsFile(params) {
91
- return params.secrets;
92
- },
93
- });
94
- }
95
- function resolveCloudflareClientDir(params, ctx) {
96
- return resolveClientDir({
97
- adapterName: 'cloudflare',
98
- env: ctx.env,
99
- projectDir: ctx.projectDir,
100
- domain: ctx.domain,
101
- ...(params.client ? { client: params.client } : {}),
102
- });
103
- }
104
- // ── codegen orchestration ──────────────────────────────────────────────────
105
- export async function prepare(params, ctx, mode, clientAssets = {
106
- servesClient: false,
107
- bundleAssets: false,
108
- }) {
109
- const astraleDir = join(ctx.projectDir, '.astrale');
110
- await mkdir(astraleDir, { recursive: true });
111
- await ensureIdentity(astraleDir, ctx.domain.origin);
112
- const name = workerName(params, ctx.domain.origin);
113
- // Instance-router service binding (on by default → admin-router): lets the
114
- // worker reach other instances' hosts internally, so a cross-instance JWKS
115
- // fetch doesn't 522. Resolved once, fed to BOTH codegens below.
116
- const router = resolveRouter(params.router);
117
- // Two distinct client signals: the WORKER's `/ui` hook and Wrangler's local
118
- // assets binding. Direct Cloudflare deploys use both; managed deploys ship
119
- // assets separately but still need the worker hook.
120
- const servesClient = clientAssets.servesClient;
121
- const bundleAssets = clientAssets.bundleAssets;
122
- await writeFileAtomic(join(astraleDir, 'worker.gen.ts'),
123
- // Everything else — schema/methods/deps/views/functions/requires/postInstall —
124
- // rides the `...domain` spread the generated entry imports from `../domain`;
125
- // the only remaining build-time signal is whether to wire the /ui asset hook.
126
- generateWorkerEntry({
127
- origin: ctx.domain.origin,
128
- hasClient: servesClient,
129
- ...(router
130
- ? {
131
- router: {
132
- binding: router.binding,
133
- hostSuffix: router.hostSuffix,
134
- minLabels: router.minLabels,
135
- },
136
- }
137
- : {}),
138
- }));
139
- // Pin the worker's canonical serving URL (its `iss` identity) for routed
140
- // deploys: a routed worker may ALSO be reachable via `*.workers.dev`, so
141
- // resolving the URL from the per-request Host would let `iss` drift between
142
- // hostnames. Dev + workers.dev-only deploys are single-host, so the worker
143
- // falls back to the per-request Host (always the canonical URL there).
144
- // An explicit `vars.WORKER_URL` (e.g. a tunnel/proxy front) wins.
145
- // Dev behind a tunnel/proxy (`--host`) pins WORKER_URL the same way a routed
146
- // deploy does — the per-request Host there is the proxy's INTERNAL hostname
147
- // and would corrupt the worker's `iss`.
148
- const workerUrl = mode === 'deploy' && params.route
149
- ? `https://${params.route}`
150
- : mode === 'dev' && params.host
151
- ? params.host
152
- : undefined;
153
- // Dev injects secrets as local vars (the gitignored .astrale config never
154
- // ships); deploy keeps secrets out of the config and pushes them encrypted.
155
- const vars = {
156
- ...(workerUrl ? { WORKER_URL: workerUrl } : {}),
157
- ...(mode === 'dev' ? { ...params.vars, ...ctx.secrets } : { ...params.vars }),
158
- };
159
- const baseConfig = {
160
- workerName: name,
161
- ...(mode === 'deploy' && params.route ? { route: params.route } : {}),
162
- hasClient: bundleAssets,
163
- vars,
164
- // Router service binding flows into BOTH the SELF and SELF-less fallback
165
- // configs — the first-deploy two-pass must keep it. `admin-router` already
166
- // exists, so unlike SELF it always resolves (no first-deploy chicken-egg).
167
- ...(router ? { router: { binding: router.binding, service: router.service } } : {}),
168
- // Escape hatch: extra bindings (KV/R2/D1/queues/…) deep-merged on top. Same
169
- // overlay in dev and deploy — it's infra, not env-specific plumbing — and it
170
- // flows into both the SELF and the SELF-less fallback config below.
171
- ...(params.wrangler ? { wrangler: params.wrangler } : {}),
172
- };
173
- // Always self-bind: it enables autobinding (a handler calling its own domain).
174
- // Locally the dev registry resolves it; on deploy the first deploy of a fresh
175
- // worker can't (the script doesn't exist yet), so we also emit a SELF-less
176
- // fallback config that `runWranglerDeploy` uses for a one-time two-pass deploy.
177
- const configPath = join(astraleDir, 'wrangler.gen.jsonc');
178
- await writeFileAtomic(configPath, generateWranglerConfig({ ...baseConfig, selfBinding: true }));
179
- let fallbackConfigPath;
180
- if (mode === 'deploy') {
181
- fallbackConfigPath = join(astraleDir, 'wrangler.no-self.gen.jsonc');
182
- await writeFileAtomic(fallbackConfigPath, generateWranglerConfig({ ...baseConfig, selfBinding: false }));
183
- }
184
- return {
185
- configPath,
186
- ...(fallbackConfigPath ? { fallbackConfigPath } : {}),
187
- port: params.port ?? DEFAULT_PORT,
188
- workerName: name,
189
- };
190
- }
191
- /**
192
- * Write-then-rename: hot-regen rewrites these files while a live `wrangler dev`
193
- * watches them — a plain `writeFile` can be read truncated mid-write.
194
- */
195
- async function writeFileAtomic(path, content) {
196
- const tmp = `${path}.tmp`;
197
- await writeFile(tmp, content);
198
- await rename(tmp, path);
199
- }
200
- /**
201
- * Poll the deployed URL until the worker answers (anything but the Cloudflare
202
- * 1042 "no script on this host" 404), or give up after `timeoutMs`. Resolves
203
- * silently on the fast path; logs only when propagation actually makes us wait.
204
- */
205
- async function waitUntilLive(url, onLog, timeoutMs = 90_000) {
206
- const probe = new URL('/health', url);
207
- const deadline = Date.now() + timeoutMs;
208
- let waited = false;
209
- for (;;) {
210
- try {
211
- const res = await fetch(probe, { redirect: 'manual' });
212
- if (res.status !== 404)
213
- return;
214
- }
215
- catch {
216
- // Network hiccup — treat like "not live yet" and keep polling.
217
- }
218
- if (Date.now() >= deadline) {
219
- onLog(`URL not reachable yet after ${Math.round(timeoutMs / 1000)}s — it may need a moment.`);
220
- return;
221
- }
222
- if (!waited) {
223
- waited = true;
224
- onLog('waiting for the URL to go live (first deploys can take ~30-60s)…');
225
- }
226
- await new Promise((r) => setTimeout(r, 3000));
227
- }
228
- }
229
- const WORKER_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
230
- export function workerName(params, origin) {
231
- // An explicit name is the deployed worker's identity (and the SELF service
232
- // target) — validate and reject an invalid one rather than silently rewriting
233
- // it, so the dev fixes it instead of deploying under a surprising name.
234
- if (params.workerName !== undefined) {
235
- if (!WORKER_NAME_RE.test(params.workerName) || params.workerName.length > 63) {
236
- throw new Error(`cloudflare adapter: invalid \`workerName\` "${params.workerName}". A Cloudflare worker ` +
237
- 'name must be lowercase, start with a letter or digit, contain only letters, digits and ' +
238
- 'dashes, and be at most 63 chars.');
239
- }
240
- return params.workerName;
241
- }
242
- // Derive from the origin: lowercase, collapse non-alphanumerics to a dash, then
243
- // SLICE before trimming dashes so a cut landing mid-dash can't leave a trailing
244
- // "-" (which wrangler rejects).
245
- return origin
246
- .toLowerCase()
247
- .replace(/[^a-z0-9]+/g, '-')
248
- .slice(0, 54)
249
- .replace(/^-+|-+$/g, '');
250
- }
251
- /**
252
- * Resolve the instance-router config. ON by default (targets `admin-router`) so
253
- * every adapter-deployed worker can reach other instances' hosts internally and
254
- * verify cross-instance credentials without a 522; `false` disables it. The
255
- * returned shape carries every value the worker- and wrangler-codegen need.
256
- */
257
- export function resolveRouter(ir) {
258
- if (ir === false)
259
- return undefined;
260
- const cfg = ir ?? {};
261
- return {
262
- binding: cfg.binding ?? 'ROUTER',
263
- service: cfg.service ?? 'admin-router',
264
- hostSuffix: cfg.hostSuffix ?? '.astrale.ai',
265
- minLabels: cfg.minLabels ?? 4,
266
- };
267
- }
268
- export function logTo() {
269
- return (line) => process.stderr.write(`\x1b[2m ${line}\x1b[0m\n`);
270
- }
271
- //# sourceMappingURL=cloudflare.js.map
1
+ export { cloudflare } from './adapter.js';
@@ -0,0 +1,16 @@
1
+ import type { DeployContext, DeployResult } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { Release } from '@astrale-os/sdk/deployment/release';
3
+ import type { materialize } from '../build/artifact.js';
4
+ import type { signingIdentity } from '../identity/source.js';
5
+ import type { CloudflareParams } from '../params.js';
6
+ import type { runWranglerDeploy } from '../wrangler/deploy.js';
7
+ import type { runWranglerDeploymentStatus } from '../wrangler/status.js';
8
+ export interface CloudflareDeployDependencies {
9
+ readonly materialize: typeof materialize;
10
+ readonly runWranglerDeploy: typeof runWranglerDeploy;
11
+ readonly runWranglerDeploymentStatus: typeof runWranglerDeploymentStatus;
12
+ readonly waitForReadiness: (release: Release, signal: AbortSignal) => Promise<void>;
13
+ readonly signingIdentity: typeof signingIdentity;
14
+ }
15
+ /** Atomically advance one stable Worker address to the prepared implementation. */
16
+ export declare function deployCloudflare(parameters: CloudflareParams, context: DeployContext, dependencies: CloudflareDeployDependencies): Promise<DeployResult>;
@@ -0,0 +1,204 @@
1
+ import { addressing, assemble } from '@astrale-os/sdk/deployment/release';
2
+ import { mkdir, mkdtemp, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { workerName } from '../build/configuration.js';
5
+ import { admitDirectPlacement } from '../build/direct.js';
6
+ import { loadWorkerArtifact } from '../build/worker/index.js';
7
+ import { signingIdentitySecrets } from '../identity/secret.js';
8
+ import { WranglerDeployError } from '../wrangler/deploy.js';
9
+ const NONE = Object.freeze({ kind: 'none' });
10
+ /** Atomically advance one stable Worker address to the prepared implementation. */
11
+ export async function deployCloudflare(parameters, context, dependencies) {
12
+ let secrets;
13
+ try {
14
+ const identity = await dependencies.signingIdentity({
15
+ projectDir: context.projectDir,
16
+ source: parameters.signingIdentity,
17
+ origin: context.artifact.build.schema.compiled.root.origin,
18
+ mode: 'deploy',
19
+ });
20
+ secrets = signingIdentitySecrets(context.secrets, identity);
21
+ }
22
+ catch (cause) {
23
+ return failed('prerequisite', progress({}), cause);
24
+ }
25
+ let worker;
26
+ try {
27
+ worker = loadWorkerArtifact(context.artifact);
28
+ for (const name of worker.bindings.requiredSecrets) {
29
+ if (!Object.hasOwn(secrets, name)) {
30
+ throw new TypeError(`Cloudflare Worker requires secret ${name}.`);
31
+ }
32
+ }
33
+ admitDirectPlacement(context.artifact, worker, parameters);
34
+ }
35
+ catch (cause) {
36
+ return failed('prerequisite', progress({}), cause);
37
+ }
38
+ const stateDirectory = join(context.projectDir, '.astrale');
39
+ await mkdir(stateDirectory, { recursive: true });
40
+ const directory = await mkdtemp(join(stateDirectory, 'deploy-'));
41
+ try {
42
+ await dependencies.materialize(directory, context.artifact.files);
43
+ const name = workerName(parameters, context.artifact.build.schema.compiled.root.origin);
44
+ const configPath = join(directory, 'wrangler.jsonc');
45
+ let deployed;
46
+ try {
47
+ deployed = await dependencies.runWranglerDeploy({
48
+ projectDir: context.projectDir,
49
+ configPath,
50
+ secrets,
51
+ ...(parameters.route === undefined ? {} : { route: parameters.route }),
52
+ signal: context.signal,
53
+ });
54
+ }
55
+ catch (cause) {
56
+ return failed('provider', progress({ provider: partialProvider(cause, context.artifact) }), cause);
57
+ }
58
+ const configuration = Object.freeze({
59
+ kind: 'applied',
60
+ evidence: Object.freeze({ names: Object.keys(secrets).sort() }),
61
+ });
62
+ const retained = Object.freeze({
63
+ kind: 'partial',
64
+ evidence: Object.freeze({
65
+ provider: 'cloudflare',
66
+ deployment: deployed.deploymentVersion,
67
+ artifact: context.artifact.digest,
68
+ }),
69
+ });
70
+ let selected;
71
+ try {
72
+ selected = observeAddressing(context.artifact, deployed.url, name);
73
+ }
74
+ catch (cause) {
75
+ return failed('addressing', progress({
76
+ provider: retained,
77
+ configuration,
78
+ }), cause);
79
+ }
80
+ let observed;
81
+ try {
82
+ observed = await dependencies.runWranglerDeploymentStatus({
83
+ projectDir: context.projectDir,
84
+ configPath,
85
+ workerName: name,
86
+ signal: context.signal,
87
+ });
88
+ requireCurrentDeployment(observed, deployed.deploymentVersion);
89
+ }
90
+ catch (cause) {
91
+ return failed('readiness', progress({
92
+ provider: retained,
93
+ configuration,
94
+ }), cause);
95
+ }
96
+ let release;
97
+ try {
98
+ release = assemble(context.artifact.build, selected);
99
+ }
100
+ catch (cause) {
101
+ return failed('release', progress({ provider: retained, configuration }), cause);
102
+ }
103
+ try {
104
+ await dependencies.waitForReadiness(release, context.signal);
105
+ }
106
+ catch (cause) {
107
+ return failed('readiness', progress({ provider: retained, configuration }), cause, release);
108
+ }
109
+ const provider = Object.freeze({
110
+ kind: 'applied',
111
+ evidence: Object.freeze({
112
+ provider: 'cloudflare',
113
+ deployment: deployed.deploymentVersion,
114
+ artifact: context.artifact.digest,
115
+ issuer: selected.issuer,
116
+ }),
117
+ });
118
+ return Object.freeze({
119
+ status: 'ready',
120
+ phase: 'complete',
121
+ progress: Object.freeze({ ...progress({ configuration }), provider }),
122
+ release,
123
+ });
124
+ }
125
+ finally {
126
+ await rm(directory, { recursive: true, force: true });
127
+ }
128
+ }
129
+ function partialProvider(cause, artifact) {
130
+ if (!(cause instanceof WranglerDeployError) || cause.applied?.deploymentVersion === undefined) {
131
+ return Object.freeze({ kind: 'unknown' });
132
+ }
133
+ let issuer;
134
+ if (cause.applied.url !== undefined) {
135
+ try {
136
+ issuer = addressing(cause.applied.url).issuer;
137
+ }
138
+ catch {
139
+ // The provider effect remains known when its printed URL is not Addressing.
140
+ }
141
+ }
142
+ return Object.freeze({
143
+ kind: 'partial',
144
+ evidence: Object.freeze({
145
+ provider: 'cloudflare',
146
+ deployment: cause.applied.deploymentVersion,
147
+ artifact: artifact.digest,
148
+ ...(issuer === undefined ? {} : { issuer }),
149
+ }),
150
+ });
151
+ }
152
+ function requireCurrentDeployment(observed, expectedVersion) {
153
+ if (observed.versions.length !== 1 ||
154
+ observed.versions[0].percentage !== 100 ||
155
+ observed.versions[0].version !== expectedVersion) {
156
+ throw new TypeError('Cloudflare Worker is not one exact version at 100%.');
157
+ }
158
+ }
159
+ function observeAddressing(artifact, deployedUrl, expectedWorker) {
160
+ if (artifact.addressing.kind === 'configured') {
161
+ if (deployedUrl === undefined)
162
+ return artifact.addressing.addressing;
163
+ const observed = addressing(deployedUrl);
164
+ if (observed.issuer !== artifact.addressing.addressing.issuer) {
165
+ throw new TypeError('Cloudflare deployed URL differs from configured Addressing.');
166
+ }
167
+ return observed;
168
+ }
169
+ if (deployedUrl === undefined) {
170
+ throw new TypeError('Cloudflare did not report provider-assigned Addressing.');
171
+ }
172
+ const observed = addressing(deployedUrl);
173
+ if (artifact.addressing.claim !== expectedWorker) {
174
+ throw new TypeError('PreparedArtifact worker claim differs from the deployment target.');
175
+ }
176
+ const url = new URL(observed.issuer);
177
+ const labels = url.hostname.split('.');
178
+ if (url.protocol !== 'https:' ||
179
+ labels.length < 4 ||
180
+ labels[0] !== artifact.addressing.claim ||
181
+ labels.at(-2) !== 'workers' ||
182
+ labels.at(-1) !== 'dev') {
183
+ throw new TypeError('Cloudflare workers.dev URL does not satisfy its prepared worker claim.');
184
+ }
185
+ return observed;
186
+ }
187
+ function progress(input) {
188
+ return Object.freeze({
189
+ prerequisite: input.prerequisite ?? NONE,
190
+ provider: input.provider ?? NONE,
191
+ configuration: input.configuration ?? NONE,
192
+ installation: input.installation ?? NONE,
193
+ });
194
+ }
195
+ function failed(phase, progressValue, cause, release) {
196
+ const error = cause instanceof Error ? cause : new Error(String(cause));
197
+ return Object.freeze({
198
+ status: 'failed',
199
+ phase,
200
+ progress: progressValue,
201
+ error,
202
+ ...(release === undefined ? {} : { release }),
203
+ });
204
+ }
@@ -0,0 +1 @@
1
+ export { deployCloudflare, type CloudflareDeployDependencies } from './deploy.js';
@@ -0,0 +1 @@
1
+ export { deployCloudflare } from './deploy.js';
@@ -0,0 +1,2 @@
1
+ export declare function parseDeployUrl(text: string, route?: string): string | undefined;
2
+ export declare function parseDeployVersionId(text: string): string | undefined;
@@ -0,0 +1,10 @@
1
+ const WORKERS_DEV_RE = /(https:\/\/[^\s]+\.workers\.dev)/iu;
2
+ const VERSION_ID_RE = /(?:Current\s+)?Version ID:\s*([a-z0-9_-]+)/iu;
3
+ export function parseDeployUrl(text, route) {
4
+ if (route !== undefined)
5
+ return `https://${route.replace(/\/.*$/u, '')}`;
6
+ return WORKERS_DEV_RE.exec(text)?.[1];
7
+ }
8
+ export function parseDeployVersionId(text) {
9
+ return VERSION_ID_RE.exec(text)?.[1];
10
+ }
@@ -0,0 +1,15 @@
1
+ import type { DevelopmentContext, DevelopmentSession } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { CloudflareParams } from '../params.js';
3
+ import { signingIdentity } from '../identity/source.js';
4
+ import { startFrontend } from './frontend.js';
5
+ import { allocatePort } from './port.js';
6
+ import { verifyDevelopmentRelease } from './readiness.js';
7
+ import { startWorker } from './worker.js';
8
+ export interface CloudflareDevelopmentDependencies {
9
+ readonly signingIdentity: typeof signingIdentity;
10
+ readonly startFrontend: typeof startFrontend;
11
+ readonly startWorker: typeof startWorker;
12
+ readonly allocatePort: typeof allocatePort;
13
+ readonly verify: typeof verifyDevelopmentRelease;
14
+ }
15
+ export declare function developCloudflare(parameters: CloudflareParams, context: DevelopmentContext, dependencies?: CloudflareDevelopmentDependencies): Promise<DevelopmentSession>;