@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
package/src/cloudflare.ts DELETED
@@ -1,321 +0,0 @@
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
-
12
- import type { DeployCtx, DomainAdapter, WatchCtx } from '@astrale-os/sdk'
13
-
14
- import { defineAdapter } from '@astrale-os/sdk'
15
- import { mkdir, rename, writeFile } from 'node:fs/promises'
16
- import { join } from 'node:path'
17
-
18
- import type { CloudflareParams } from './params'
19
-
20
- import { buildClient, resolveClientDir } from './client'
21
- import { ensureIdentity } from './codegen/identity'
22
- import { generateWorkerEntry } from './codegen/worker'
23
- import { generateWranglerConfig } from './codegen/wrangler'
24
- import { bulkPutSecrets, runWranglerDeploy, runWranglerDev } from './wrangler-cli'
25
-
26
- const DEFAULT_PORT = 8787
27
-
28
- export function cloudflare(
29
- envs: Record<string, CloudflareParams>,
30
- ): DomainAdapter<CloudflareParams> {
31
- return defineAdapter<CloudflareParams>({
32
- name: 'cloudflare',
33
- envs,
34
-
35
- async watch(params, ctx) {
36
- const clientDir = resolveCloudflareClientDir(params, ctx)
37
- const { configPath, port } = await prepare(params, ctx, 'dev', {
38
- servesClient: Boolean(clientDir),
39
- bundleAssets: Boolean(clientDir),
40
- })
41
- if (clientDir) await buildClient(clientDir, ctx.projectDir, logTo())
42
- const handle = await runWranglerDev({
43
- projectDir: ctx.projectDir,
44
- configPath,
45
- port,
46
- remote: Boolean(params.remote),
47
- autoPickPort: params.port === undefined,
48
- ...(params.host ? { ip: '0.0.0.0' } : {}),
49
- onReload: ctx.onReload,
50
- onLog: logTo(),
51
- })
52
- // With --host the actionable URL is the PUBLIC one (the tunnel/proxy
53
- // front), not the local bind — print and spec-stamp that.
54
- return { url: params.host ?? handle.url, stop: handle.stop }
55
- },
56
-
57
- // Config hot-regen: rewrite the generated files only — the running
58
- // `wrangler dev` watches its `--config` (and the worker entry) and reloads
59
- // them itself, so a `astrale.config.ts` edit lands without a restart.
60
- // Mirrors `watch`'s prep exactly (codegen + client build), minus the spawn.
61
- async regenerate(params, ctx) {
62
- const clientDir = resolveCloudflareClientDir(params, ctx)
63
- await prepare(params, ctx, 'dev', {
64
- servesClient: Boolean(clientDir),
65
- bundleAssets: Boolean(clientDir),
66
- })
67
- if (clientDir) await buildClient(clientDir, ctx.projectDir, logTo())
68
- },
69
-
70
- async deploy(params, ctx) {
71
- const clientDir = resolveCloudflareClientDir(params, ctx)
72
- const {
73
- configPath,
74
- fallbackConfigPath,
75
- workerName: name,
76
- } = await prepare(params, ctx, 'deploy', {
77
- servesClient: Boolean(clientDir),
78
- bundleAssets: Boolean(clientDir),
79
- })
80
- if (clientDir) await buildClient(clientDir, ctx.projectDir, logTo())
81
- const { url } = await runWranglerDeploy({
82
- projectDir: ctx.projectDir,
83
- configPath,
84
- workerName: name,
85
- ...(fallbackConfigPath ? { fallbackConfigPath } : {}),
86
- ...(params.route ? { route: params.route } : {}),
87
- onLog: logTo(),
88
- })
89
- if (Object.keys(ctx.secrets).length > 0) {
90
- await bulkPutSecrets({
91
- projectDir: ctx.projectDir,
92
- configPath,
93
- secrets: ctx.secrets,
94
- onLog: logTo(),
95
- })
96
- }
97
- // A first deploy on a fresh `*.workers.dev` host can take ~30-60s to
98
- // propagate; an `astrale domain install <url>` issued right away would
99
- // 404 (Cloudflare 1042). Block until the URL actually serves so the
100
- // install line we print is immediately actionable.
101
- await waitUntilLive(url, logTo())
102
- return { url }
103
- },
104
-
105
- secretsFile(params) {
106
- return params.secrets
107
- },
108
- })
109
- }
110
-
111
- function resolveCloudflareClientDir(
112
- params: CloudflareParams,
113
- ctx: WatchCtx | DeployCtx,
114
- ): string | undefined {
115
- return resolveClientDir({
116
- adapterName: 'cloudflare',
117
- env: ctx.env,
118
- projectDir: ctx.projectDir,
119
- domain: ctx.domain,
120
- ...(params.client ? { client: params.client } : {}),
121
- })
122
- }
123
-
124
- // ── codegen orchestration ──────────────────────────────────────────────────
125
-
126
- export async function prepare(
127
- params: CloudflareParams,
128
- ctx: WatchCtx | DeployCtx,
129
- mode: 'dev' | 'deploy',
130
- clientAssets: { servesClient: boolean; bundleAssets: boolean } = {
131
- servesClient: false,
132
- bundleAssets: false,
133
- },
134
- ): Promise<{ configPath: string; fallbackConfigPath?: string; port: number; workerName: string }> {
135
- const astraleDir = join(ctx.projectDir, '.astrale')
136
- await mkdir(astraleDir, { recursive: true })
137
- await ensureIdentity(astraleDir, ctx.domain.origin)
138
-
139
- const name = workerName(params, ctx.domain.origin)
140
- // Instance-router service binding (on by default → admin-router): lets the
141
- // worker reach other instances' hosts internally, so a cross-instance JWKS
142
- // fetch doesn't 522. Resolved once, fed to BOTH codegens below.
143
- const router = resolveRouter(params.router)
144
- // Two distinct client signals: the WORKER's `/ui` hook and Wrangler's local
145
- // assets binding. Direct Cloudflare deploys use both; managed deploys ship
146
- // assets separately but still need the worker hook.
147
- const servesClient = clientAssets.servesClient
148
- const bundleAssets = clientAssets.bundleAssets
149
-
150
- await writeFileAtomic(
151
- join(astraleDir, 'worker.gen.ts'),
152
- // Everything else — schema/methods/deps/views/functions/requires/postInstall —
153
- // rides the `...domain` spread the generated entry imports from `../domain`;
154
- // the only remaining build-time signal is whether to wire the /ui asset hook.
155
- generateWorkerEntry({
156
- origin: ctx.domain.origin,
157
- hasClient: servesClient,
158
- ...(router
159
- ? {
160
- router: {
161
- binding: router.binding,
162
- hostSuffix: router.hostSuffix,
163
- minLabels: router.minLabels,
164
- },
165
- }
166
- : {}),
167
- }),
168
- )
169
-
170
- // Pin the worker's canonical serving URL (its `iss` identity) for routed
171
- // deploys: a routed worker may ALSO be reachable via `*.workers.dev`, so
172
- // resolving the URL from the per-request Host would let `iss` drift between
173
- // hostnames. Dev + workers.dev-only deploys are single-host, so the worker
174
- // falls back to the per-request Host (always the canonical URL there).
175
- // An explicit `vars.WORKER_URL` (e.g. a tunnel/proxy front) wins.
176
- // Dev behind a tunnel/proxy (`--host`) pins WORKER_URL the same way a routed
177
- // deploy does — the per-request Host there is the proxy's INTERNAL hostname
178
- // and would corrupt the worker's `iss`.
179
- const workerUrl =
180
- mode === 'deploy' && params.route
181
- ? `https://${params.route}`
182
- : mode === 'dev' && params.host
183
- ? params.host
184
- : undefined
185
-
186
- // Dev injects secrets as local vars (the gitignored .astrale config never
187
- // ships); deploy keeps secrets out of the config and pushes them encrypted.
188
- const vars = {
189
- ...(workerUrl ? { WORKER_URL: workerUrl } : {}),
190
- ...(mode === 'dev' ? { ...params.vars, ...ctx.secrets } : { ...params.vars }),
191
- }
192
-
193
- const baseConfig = {
194
- workerName: name,
195
- ...(mode === 'deploy' && params.route ? { route: params.route } : {}),
196
- hasClient: bundleAssets,
197
- vars,
198
- // Router service binding flows into BOTH the SELF and SELF-less fallback
199
- // configs — the first-deploy two-pass must keep it. `admin-router` already
200
- // exists, so unlike SELF it always resolves (no first-deploy chicken-egg).
201
- ...(router ? { router: { binding: router.binding, service: router.service } } : {}),
202
- // Escape hatch: extra bindings (KV/R2/D1/queues/…) deep-merged on top. Same
203
- // overlay in dev and deploy — it's infra, not env-specific plumbing — and it
204
- // flows into both the SELF and the SELF-less fallback config below.
205
- ...(params.wrangler ? { wrangler: params.wrangler } : {}),
206
- }
207
-
208
- // Always self-bind: it enables autobinding (a handler calling its own domain).
209
- // Locally the dev registry resolves it; on deploy the first deploy of a fresh
210
- // worker can't (the script doesn't exist yet), so we also emit a SELF-less
211
- // fallback config that `runWranglerDeploy` uses for a one-time two-pass deploy.
212
- const configPath = join(astraleDir, 'wrangler.gen.jsonc')
213
- await writeFileAtomic(configPath, generateWranglerConfig({ ...baseConfig, selfBinding: true }))
214
-
215
- let fallbackConfigPath: string | undefined
216
- if (mode === 'deploy') {
217
- fallbackConfigPath = join(astraleDir, 'wrangler.no-self.gen.jsonc')
218
- await writeFileAtomic(
219
- fallbackConfigPath,
220
- generateWranglerConfig({ ...baseConfig, selfBinding: false }),
221
- )
222
- }
223
-
224
- return {
225
- configPath,
226
- ...(fallbackConfigPath ? { fallbackConfigPath } : {}),
227
- port: params.port ?? DEFAULT_PORT,
228
- workerName: name,
229
- }
230
- }
231
-
232
- /**
233
- * Write-then-rename: hot-regen rewrites these files while a live `wrangler dev`
234
- * watches them — a plain `writeFile` can be read truncated mid-write.
235
- */
236
- async function writeFileAtomic(path: string, content: string): Promise<void> {
237
- const tmp = `${path}.tmp`
238
- await writeFile(tmp, content)
239
- await rename(tmp, path)
240
- }
241
-
242
- /**
243
- * Poll the deployed URL until the worker answers (anything but the Cloudflare
244
- * 1042 "no script on this host" 404), or give up after `timeoutMs`. Resolves
245
- * silently on the fast path; logs only when propagation actually makes us wait.
246
- */
247
- async function waitUntilLive(
248
- url: string,
249
- onLog: (line: string) => void,
250
- timeoutMs = 90_000,
251
- ): Promise<void> {
252
- const probe = new URL('/health', url)
253
- const deadline = Date.now() + timeoutMs
254
- let waited = false
255
- for (;;) {
256
- try {
257
- const res = await fetch(probe, { redirect: 'manual' })
258
- if (res.status !== 404) return
259
- } catch {
260
- // Network hiccup — treat like "not live yet" and keep polling.
261
- }
262
- if (Date.now() >= deadline) {
263
- onLog(`URL not reachable yet after ${Math.round(timeoutMs / 1000)}s — it may need a moment.`)
264
- return
265
- }
266
- if (!waited) {
267
- waited = true
268
- onLog('waiting for the URL to go live (first deploys can take ~30-60s)…')
269
- }
270
- await new Promise((r) => setTimeout(r, 3000))
271
- }
272
- }
273
-
274
- const WORKER_NAME_RE = /^[a-z0-9][a-z0-9-]*$/
275
-
276
- export function workerName(params: CloudflareParams, origin: string): string {
277
- // An explicit name is the deployed worker's identity (and the SELF service
278
- // target) — validate and reject an invalid one rather than silently rewriting
279
- // it, so the dev fixes it instead of deploying under a surprising name.
280
- if (params.workerName !== undefined) {
281
- if (!WORKER_NAME_RE.test(params.workerName) || params.workerName.length > 63) {
282
- throw new Error(
283
- `cloudflare adapter: invalid \`workerName\` "${params.workerName}". A Cloudflare worker ` +
284
- 'name must be lowercase, start with a letter or digit, contain only letters, digits and ' +
285
- 'dashes, and be at most 63 chars.',
286
- )
287
- }
288
- return params.workerName
289
- }
290
- // Derive from the origin: lowercase, collapse non-alphanumerics to a dash, then
291
- // SLICE before trimming dashes so a cut landing mid-dash can't leave a trailing
292
- // "-" (which wrangler rejects).
293
- return origin
294
- .toLowerCase()
295
- .replace(/[^a-z0-9]+/g, '-')
296
- .slice(0, 54)
297
- .replace(/^-+|-+$/g, '')
298
- }
299
-
300
- /**
301
- * Resolve the instance-router config. ON by default (targets `admin-router`) so
302
- * every adapter-deployed worker can reach other instances' hosts internally and
303
- * verify cross-instance credentials without a 522; `false` disables it. The
304
- * returned shape carries every value the worker- and wrangler-codegen need.
305
- */
306
- export function resolveRouter(
307
- ir: CloudflareParams['router'],
308
- ): { binding: string; service: string; hostSuffix: string; minLabels: number } | undefined {
309
- if (ir === false) return undefined
310
- const cfg = ir ?? {}
311
- return {
312
- binding: cfg.binding ?? 'ROUTER',
313
- service: cfg.service ?? 'admin-router',
314
- hostSuffix: cfg.hostSuffix ?? '.astrale.ai',
315
- minLabels: cfg.minLabels ?? 4,
316
- }
317
- }
318
-
319
- export function logTo(): (line: string) => void {
320
- return (line: string) => process.stderr.write(`\x1b[2m ${line}\x1b[0m\n`)
321
- }
@@ -1,40 +0,0 @@
1
- /**
2
- * Ensure the domain has a stable Ed25519 signing identity at
3
- * `.astrale/identity.ts`. Generated ONCE (first `dev`/`deploy` or by the
4
- * scaffolder) and never regenerated — the private key IS the domain's identity,
5
- * so rotating it would orphan every instance that installed the old key. The
6
- * file is gitignored; for real production this key should graduate to a managed
7
- * secret.
8
- */
9
-
10
- import { exportJWK, generateKeyPair } from 'jose'
11
- import { existsSync } from 'node:fs'
12
- import { mkdir, writeFile } from 'node:fs/promises'
13
- import { join } from 'node:path'
14
-
15
- export async function ensureIdentity(astraleDir: string, origin: string): Promise<void> {
16
- const file = join(astraleDir, 'identity.ts')
17
- if (existsSync(file)) return
18
-
19
- const { privateKey } = await generateKeyPair('EdDSA', { extractable: true })
20
- const jwk = (await exportJWK(privateKey)) as Record<string, unknown>
21
- jwk.alg = 'EdDSA'
22
- jwk.kid = `${origin}-key`
23
-
24
- await mkdir(astraleDir, { recursive: true })
25
- await writeFile(
26
- file,
27
- `// AUTO-GENERATED stable signing identity for "${origin}" — do not edit, do not commit.\n` +
28
- `export const PRIVATE_JWK = ${JSON.stringify(jwk, null, 2)} as const\n`,
29
- )
30
-
31
- // Loud on purpose: the file is gitignored, so a fresh clone / CI runner
32
- // silently mints a NEW key — and a redeploy with a new key breaks JWKS
33
- // verification on every instance that installed the old one, with no hint
34
- // why. Make the lifecycle visible the one time it happens.
35
- process.stderr.write(
36
- `\x1b[33m!\x1b[0m new signing identity generated at .astrale/identity.ts (kid ${String(jwk.kid)}).\n` +
37
- ` This key IS "${origin}"'s identity: back it up (or move it to a managed secret) —\n` +
38
- ` deploying from another machine without it re-keys the domain and breaks existing installs.\n`,
39
- )
40
- }
@@ -1,92 +0,0 @@
1
- /**
2
- * Deep-merge for the generated wrangler config. `base` is what the adapter
3
- * generates; `overlay` is the dev's `params.wrangler` escape hatch. The merge
4
- * is additive so a dev can declare extra bindings without losing the adapter's
5
- * invariants:
6
- * - plain objects → recurse
7
- * - arrays → concat, de-duplicating BOTH primitive members and
8
- * object bindings by an identity key (`binding` /
9
- * `pattern` / `queue` / `name`, else structural value),
10
- * with the overlay entry overriding a base entry of the
11
- * same identity. So a dev overlay that re-declares the
12
- * adapter's `SELF` service (or any binding) replaces it
13
- * instead of emitting a duplicate wrangler rejects.
14
- * - scalars / new keys → overlay wins
15
- *
16
- * Protecting the load-bearing keys (`main`, `assets`, …) is policy enforced by
17
- * the caller (`generateWranglerConfig`), not here — this stays a generic merge.
18
- */
19
- export function deepMergeConfig(
20
- base: Record<string, unknown>,
21
- overlay: Record<string, unknown>,
22
- ): Record<string, unknown> {
23
- const out: Record<string, unknown> = { ...base }
24
- for (const [key, value] of Object.entries(overlay)) {
25
- const prev = out[key]
26
- if (isPlainObject(prev) && isPlainObject(value)) {
27
- out[key] = deepMergeConfig(prev, value)
28
- } else if (Array.isArray(prev) && Array.isArray(value)) {
29
- out[key] = mergeArrays(prev, value)
30
- } else {
31
- out[key] = value
32
- }
33
- }
34
- return out
35
- }
36
-
37
- /**
38
- * Concat two arrays, de-duplicating by identity. Primitives dedup by value;
39
- * objects dedup by an identity key (`binding`/`pattern`/`queue`/`name`, else
40
- * their structural JSON) with the later (overlay) entry overriding an earlier
41
- * (base) one at the base entry's position. This stops a re-declared object
42
- * binding (e.g. a second `SELF` service) from producing a duplicate that
43
- * wrangler rejects, while still appending genuinely distinct bindings.
44
- */
45
- function mergeArrays(a: unknown[], b: unknown[]): unknown[] {
46
- const out: unknown[] = []
47
- const seenPrimitives = new Set<unknown>()
48
- const indexByKey = new Map<string, number>()
49
- for (const item of [...a, ...b]) {
50
- if (isPrimitive(item)) {
51
- if (seenPrimitives.has(item)) continue
52
- seenPrimitives.add(item)
53
- out.push(item)
54
- continue
55
- }
56
- const key = identityKey(item)
57
- const existing = indexByKey.get(key)
58
- if (existing !== undefined) {
59
- out[existing] = item // overlay (later) overrides the base entry in place
60
- continue
61
- }
62
- indexByKey.set(key, out.length)
63
- out.push(item)
64
- }
65
- return out
66
- }
67
-
68
- /**
69
- * Stable identity for an array's object member: the first recognized wrangler
70
- * binding field (`binding` for services/KV/R2/D1/queue producers, `pattern` for
71
- * routes, `queue` for consumers, `name` as a generic fallback), else the member's
72
- * full structural JSON so identical objects dedup but distinct ones all survive.
73
- */
74
- function identityKey(item: unknown): string {
75
- const rec = item as Record<string, unknown>
76
- for (const field of ['binding', 'pattern', 'queue', 'name']) {
77
- if (typeof rec[field] === 'string') return `${field}:${rec[field] as string}`
78
- }
79
- try {
80
- return `json:${JSON.stringify(item)}`
81
- } catch {
82
- return `ref:${String(item)}`
83
- }
84
- }
85
-
86
- function isPlainObject(v: unknown): v is Record<string, unknown> {
87
- return typeof v === 'object' && v !== null && !Array.isArray(v)
88
- }
89
-
90
- function isPrimitive(v: unknown): boolean {
91
- return v === null || (typeof v !== 'object' && typeof v !== 'function')
92
- }
@@ -1,136 +0,0 @@
1
- /**
2
- * Codegen for the Cloudflare Worker entry (`.astrale/worker.gen.ts`).
3
- *
4
- * The dev wires the domain ONCE in a worker-safe `domain.ts`
5
- * (`export const domain = defineDomain({ schema, methods, deps, views,
6
- * functions })`) and binds it to an adapter in `astrale.config.ts`
7
- * (`deploy(domain, cloudflare({ … }))`). This generates the
8
- * `export default { fetch }` plumbing the adapter owns by importing that single
9
- * `domain` and SPREADING it into `domainWorkerEntry` — so the author's folder
10
- * layout is irrelevant (any internal organization works as long as `domain.ts`
11
- * re-exports the wired definition) and the node-only deploy adapter, which lives
12
- * in `astrale.config.ts`, never enters this worker bundle.
13
- *
14
- * Everything the entry needs — schema/methods/deps/views/functions/requires/
15
- * postInstall — rides on the spread; the only build-time signal left is whether
16
- * this adapter env serves a client SPA (`hasClient`), which gates the `/ui`
17
- * asset hook and its import. Key properties:
18
- *
19
- * • Per-request `url` = the live serving origin (`scheme://host`). It is passed
20
- * only to `createRemoteServer({ url })`; the SDK stamps every
21
- * `binding.remoteUrl` from that single value at spec-build time — so deployed
22
- * Function nodes point back at THIS worker with zero hardcoded URLs.
23
- * • Self-issued JWKS: a Worker can't fetch its own hostname; the verifier
24
- * resolves a credential whose `iss` is this worker from the in-memory key,
25
- * so no self-fetch is attempted (the worker's JWKS is served as a normal
26
- * route by createRemoteServer).
27
- * • Self-binding (autobinding): when a handler calls back into its OWN domain
28
- * (`ctx.kernel.call` / `ctx.fn.kernel().call`), the redirect resolves to
29
- * this worker's own host — a forbidden same-host subrequest. We route those
30
- * through the `SELF` service binding instead.
31
- * • SPA: `/ui/*` is served from the `ASSETS` binding (or proxied to Vite in
32
- * dev via `VIEW_DEV_URL`).
33
- */
34
-
35
- export interface WorkerCodegenOptions {
36
- origin: string
37
- hasClient: boolean
38
- /**
39
- * When set, the worker routes subrequests to platform INSTANCE hostnames
40
- * through `<binding>` (a service binding to a router Worker) instead of the
41
- * public edge — a same-zone Worker→Worker public fetch 522s, which otherwise
42
- * blocks fetching an instance kernel's JWKS to verify a cross-instance
43
- * credential.
44
- */
45
- router?: { binding: string; hostSuffix: string; minLabels: number }
46
- }
47
-
48
- export function generateWorkerEntry(opts: WorkerCodegenOptions): string {
49
- // The asset-serving hook is a library helper (`assets`), not inlined string
50
- // logic — imported only when this adapter env serves client assets.
51
- const serverImport = opts.hasClient
52
- ? `import { assets, domainWorkerEntry } from '@astrale-os/sdk/server'`
53
- : `import { domainWorkerEntry } from '@astrale-os/sdk/server'`
54
-
55
- const clientHook = opts.hasClient
56
- ? `
57
- // Client assets under /ui/* — served from the ASSETS binding (or proxied to
58
- // Vite in dev via VIEW_DEV_URL). The matching/stripping logic lives in the SDK helper.
59
- before: assets({ binding: (env) => env.ASSETS, devProxy: (env) => env.VIEW_DEV_URL }),`
60
- : ''
61
-
62
- const router = opts.router
63
- // Service binding for instance-host subrequest routing (Env field + helper +
64
- // routeSubrequest), wired only when the adapter's `router` is set.
65
- const routerEnvField = router
66
- ? `
67
- ${router.binding}?: { fetch(request: Request): Promise<Response> }
68
- // Sibling WFP services share one dispatch namespace; this binding reaches them
69
- // IN-PROCESS (a same-zone public fetch 522s; the instance router doesn't know svc
70
- // hosts). Injected by the \`services\` domain at deploy; absent → svc routing no-ops.
71
- DISPATCHER?: { get(name: string): { fetch(request: Request): Promise<Response> } }`
72
- : ''
73
- const routerHelper = router
74
- ? `
75
- // A platform INSTANCE hostname (e.g. <slug>.<region>${router.hostSuffix}) is served
76
- // by a router Worker on the SAME zone — a direct Worker→Worker public fetch 522s.
77
- // Route those subrequests (e.g. fetching an instance kernel's JWKS to verify a
78
- // cross-instance credential) through the ${router.binding} service binding instead.
79
- function isInstanceHost(host) {
80
- return host.endsWith('${router.hostSuffix}') && host.split('.').length >= ${router.minLabels}
81
- }
82
- `
83
- : ''
84
- const routerHook = router
85
- ? `
86
- // Divert platform subrequests off the same-zone public edge (CF 522s a same-zone
87
- // Worker→Worker public fetch). No-op when a binding is absent.
88
- routeSubrequest: (url, env) => {
89
- const host = url.hostname
90
- // Sibling WFP service (<script>.svc.<domain>) → in-process via the dispatch namespace.
91
- if (env.DISPATCHER && host.split('.')[1] === 'svc') return env.DISPATCHER.get(host.split('.')[0])
92
- // Instance host → router service binding.
93
- if (env.${router.binding} && isInstanceHost(host)) return env.${router.binding}
94
- return null
95
- },`
96
- : ''
97
-
98
- return `// AUTO-GENERATED by @astrale-os/adapter-cloudflare — do not edit.
99
- // Regenerated on every \`astrale-domain dev|deploy\`. Edit your domain.ts (the
100
- // wired \`defineDomain\`) and astrale.config.ts (the \`deploy(domain, …)\`).
101
- // (origin: ${opts.origin})
102
- ${serverImport}
103
-
104
- // The worker-safe domain definition — schema/methods/deps/views/functions plus
105
- // origin/requires/postInstall — wired by the author in domain.ts. Spreading it
106
- // keeps this entry layout-agnostic; the deploy adapter stays in astrale.config.ts.
107
- import { domain } from '../domain'
108
- import { PRIVATE_JWK } from './identity'
109
-
110
- interface Env {
111
- WORKER_URL?: string
112
- ASSETS?: { fetch(request: Request): Promise<Response> }
113
- SELF?: { fetch(request: Request): Promise<Response> }
114
- VIEW_DEV_URL?: string${routerEnvField}
115
- [key: string]: unknown
116
- }
117
- ${routerHelper}
118
- // \`domainWorkerEntry\` folds the runtime-domain compile + server build + the
119
- // shared worker plumbing (JWKS self-resolution, SELF-binding routing, per-URL
120
- // app cache, canonical iss resolution) into one declaration. \`deps\` (when the
121
- // domain declares one) rides the spread and runs per cold isolate / serving URL.
122
- export default domainWorkerEntry<Env>()({
123
- ...domain,
124
- privateKey: PRIVATE_JWK,
125
- // The worker's serving URL = its identity (iss). Prefer the adapter-injected
126
- // WORKER_URL (pins one canonical host for routed deploys, so iss stays stable
127
- // even when also reachable via *.workers.dev); fall back to the per-request
128
- // host for dev / workers.dev-only (single-host → it IS the canonical URL).
129
- // Behind a TLS-terminating proxy (cloudflared tunnel → wrangler dev) the SDK
130
- // upgrades the fallback origin via X-Forwarded-Proto, so iss = the public
131
- // https URL, not the raw http one workerd sees.
132
- resolveUrl: (env, requestOrigin) => env.WORKER_URL ?? requestOrigin,
133
- selfBinding: (env) => env.SELF,${routerHook}${clientHook}
134
- })
135
- `
136
- }