@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,105 +0,0 @@
1
- /**
2
- * Codegen for the Worker config (`.astrale/wrangler.gen.jsonc`). This is the
3
- * `wrangler.jsonc` that used to be hand-copied into every domain — now an
4
- * internal adapter detail the dev never sees.
5
- *
6
- * `main` is `./worker.gen.ts` (same dir). `assets.directory` points at the
7
- * project's Vite build (`CLIENT_DIST_DIR`). A `SELF` service binding enables autobinding
8
- * (a handler calling back into its own domain). Custom-domain deploys attach a
9
- * `custom_domain` route; otherwise the Worker ships to `*.workers.dev`.
10
- *
11
- * A dev's `params.wrangler` escape hatch is deep-merged on top of this base
12
- * (extra bindings: KV, R2, D1, queues, …) — see `mergeUserConfig`.
13
- */
14
-
15
- import { CLIENT_DIST_DIR } from '../client'
16
- import { deepMergeConfig } from './merge'
17
-
18
- export interface WranglerCodegenOptions {
19
- workerName: string
20
- /** Full custom hostname for a routed deploy (e.g. 'crm.acme.dev'). */
21
- route?: string
22
- /** Whether the project has a built client SPA to serve under /ui/*. */
23
- hasClient: boolean
24
- /** Plain (non-secret) vars to bake in. */
25
- vars?: Record<string, string>
26
- /** Add the SELF service binding (autobinding). */
27
- selfBinding: boolean
28
- /**
29
- * Add a service binding to a router Worker for instance-host subrequest
30
- * routing (see `CloudflareParams.router`). Pairs with the worker
31
- * entry's `routeSubrequest`.
32
- */
33
- router?: { binding: string; service: string }
34
- /**
35
- * Raw wrangler config to deep-merge over the generated base — the escape
36
- * hatch for extra bindings (KV, R2, D1, queues, service bindings, extra
37
- * `compatibility_flags`, cron `triggers`, …). Arrays concat; new keys are
38
- * added as-is. The adapter-owned keys `name`, `main`, `assets`, `routes` are
39
- * rejected (throws) — use `workerName` / `route` instead.
40
- */
41
- wrangler?: Record<string, unknown>
42
- }
43
-
44
- const COMPATIBILITY_DATE = '2026-07-07'
45
-
46
- export function generateWranglerConfig(opts: WranglerCodegenOptions): string {
47
- const config: Record<string, unknown> = {
48
- name: opts.workerName,
49
- main: './worker.gen.ts',
50
- compatibility_date: COMPATIBILITY_DATE,
51
- compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],
52
- workers_dev: true,
53
- observability: { enabled: true },
54
- }
55
-
56
- if (opts.route) {
57
- config.routes = [{ pattern: opts.route, custom_domain: true }]
58
- }
59
-
60
- if (opts.hasClient) {
61
- config.assets = {
62
- directory: `../${CLIENT_DIST_DIR}`,
63
- binding: 'ASSETS',
64
- not_found_handling: 'single-page-application',
65
- run_worker_first: true,
66
- }
67
- }
68
-
69
- const services: Array<{ binding: string; service: string }> = []
70
- if (opts.selfBinding) services.push({ binding: 'SELF', service: opts.workerName })
71
- if (opts.router) {
72
- services.push({ binding: opts.router.binding, service: opts.router.service })
73
- }
74
- if (services.length > 0) config.services = services
75
-
76
- if (opts.vars && Object.keys(opts.vars).length > 0) {
77
- config.vars = opts.vars
78
- }
79
-
80
- const merged = opts.wrangler ? mergeUserConfig(config, opts.wrangler) : config
81
- return JSON.stringify(merged, null, 2) + '\n'
82
- }
83
-
84
- /** Keys the adapter owns and won't let `params.wrangler` clobber. */
85
- const ADAPTER_OWNED_KEYS = ['name', 'main', 'assets', 'routes']
86
-
87
- /**
88
- * Deep-merge the dev's raw wrangler overlay over the generated config, after
89
- * refusing any attempt to override an adapter-owned key. Throwing (rather than
90
- * silently dropping) keeps a stray `main` from breaking the Worker unnoticed.
91
- */
92
- function mergeUserConfig(
93
- base: Record<string, unknown>,
94
- user: Record<string, unknown>,
95
- ): Record<string, unknown> {
96
- const collisions = ADAPTER_OWNED_KEYS.filter((k) => k in user)
97
- if (collisions.length > 0) {
98
- throw new Error(
99
- `wrangler: cannot override adapter-managed key(s): ${collisions.join(', ')}. ` +
100
- 'Use `workerName` for the worker name and `route` for routing; ' +
101
- '`main` and `assets` are generated by the adapter.',
102
- )
103
- }
104
- return deepMergeConfig(base, user)
105
- }
package/src/index.ts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * `@astrale-os/adapter-cloudflare` — deploy an Astrale domain as a standalone
3
- * Cloudflare Worker on YOUR OWN Cloudflare account.
4
- *
5
- * import { cloudflare } from '@astrale-os/adapter-cloudflare'
6
- *
7
- * adapter: cloudflare({
8
- * dev: { client: { dir: 'client' }, secrets: '.env.dev' },
9
- * prod: { client: { dir: 'client' }, route: 'crm.acme.dev', secrets: '.env.prod' },
10
- * })
11
- *
12
- * `dev` runs `wrangler dev` locally; an env with no `route` ships to
13
- * `*.workers.dev`; an env with a `route` ships to that custom domain.
14
- *
15
- * Prefer a managed deploy (no Cloudflare account)? Use
16
- * `@astrale-os/adapter-astrale`, which builds the same bundle via this package's
17
- * `/build` toolkit and ships it through the Astrale platform.
18
- */
19
-
20
- export { cloudflare } from './cloudflare'
21
- export type { CloudflareParams } from './params'
package/src/params.ts DELETED
@@ -1,96 +0,0 @@
1
- import type { ClientConfig } from './client'
2
-
3
- /**
4
- * `CloudflareParams` — the provider-typed config for the Cloudflare adapter.
5
- *
6
- * One type covers every env; per-env differences are just optional fields. The
7
- * same `{ dev, prod, canary, … }` map a developer writes in `astrale.config.ts`
8
- * is `Record<string, CloudflareParams>`.
9
- *
10
- * Three deployment shapes fall out of which fields are set:
11
- * • dev (local) — `watch()` runs `wrangler dev`; URL = http://localhost:<port>
12
- * • dev-remote — `deploy()` with no `route`; URL = https://<name>.<sub>.workers.dev
13
- * • remote (custom) — `deploy()` with `route`; URL = https://<route>
14
- */
15
- export interface CloudflareParams {
16
- /** Frontend assets to build and serve for this env's mounted `/ui` views. */
17
- client?: ClientConfig
18
- /**
19
- * Custom route / hostname for a routed deploy, e.g. `'crm.acme.dev'`. Omit to
20
- * deploy to `*.workers.dev`. Ignored by local `wrangler dev` (URL is
21
- * localhost) but still used as the placeholder base domain there.
22
- */
23
- route?: string
24
- /** Gitignored secrets file (whole contents = secrets), e.g. `'.env.dev'`. */
25
- secrets?: string
26
- /** Local dev port for `wrangler dev`. Default 8787. */
27
- port?: number
28
- /**
29
- * Public URL the dev server is reached through (tunnel / sandbox preview /
30
- * reverse proxy), e.g. `'https://my-box.preview.dev'`. Sets BOTH effects an
31
- * off-localhost dev needs: wrangler binds 0.0.0.0 (reachable from outside)
32
- * and `WORKER_URL` is pinned to this URL so the worker's per-request-Host
33
- * identity (`iss`) doesn't drift to the proxy's internal hostname.
34
- * Usually injected by `pnpm dev --host <url>` rather than written here.
35
- */
36
- host?: string
37
- /** Override the Worker name. Default: derived from the domain origin. */
38
- workerName?: string
39
- /** Run `wrangler dev --remote` (edge isolate) instead of local workerd. */
40
- remote?: boolean
41
- /** Extra plain (non-secret) vars to inject as Worker vars. */
42
- vars?: Record<string, string>
43
- /**
44
- * Escape hatch: raw wrangler config deep-merged over the generated base. Use
45
- * it to declare extra bindings the adapter has no typed field for — KV, R2,
46
- * D1, queues, service bindings, extra `compatibility_flags`, cron `triggers`,
47
- * Hyperdrive, etc.
48
- *
49
- * wrangler: {
50
- * kv_namespaces: [{ binding: 'CACHE', id: '<kv-id>' }],
51
- * r2_buckets: [{ binding: 'FILES', bucket_name: 'my-bucket' }],
52
- * }
53
- *
54
- * The merge is additive: arrays concat (so your `services` keep the adapter's
55
- * `SELF` binding and your `compatibility_flags` keep `nodejs_compat`); new
56
- * keys are added as-is. The adapter-owned keys `name`, `main`, `assets`,
57
- * `routes` are rejected — use `workerName` and `route` instead. Avoid
58
- * the reserved binding names `SELF` and `ASSETS`. Durable Objects need extra
59
- * worker-entry codegen and aren't supported through this field yet.
60
- */
61
- wrangler?: Record<string, unknown>
62
- /**
63
- * Route subrequests to platform INSTANCE hostnames through a service binding
64
- * instead of the public edge. A Cloudflare Worker can't fetch a same-zone
65
- * hostname served by another Worker — Cloudflare 522s it — so without this the
66
- * worker can't fetch an instance kernel's JWKS to verify an inbound credential
67
- * from that instance, and every cross-instance call (install hooks, the GUI's
68
- * delegated calls, authed views) fails with `2002 Credential verification
69
- * failed`. Point it at a router Worker that reaches those hosts internally
70
- * (Astrale: `admin-router`).
71
- *
72
- * Wires BOTH halves the SDK needs: the `<binding>` service binding in the
73
- * generated wrangler config, and a `routeSubrequest` predicate in the worker
74
- * entry that diverts matching hosts through it.
75
- *
76
- * ON BY DEFAULT (targets `admin-router`) so every adapter-deployed worker can
77
- * verify cross-instance credentials out of the box. Pass `false` to disable
78
- * (a domain that never talks to another instance, or an account without a
79
- * router), or an object to override the target / binding name / host match.
80
- *
81
- * router: false // opt out
82
- * router: { service: 'my-router' } // override target
83
- */
84
- router?:
85
- | false
86
- | {
87
- /** Router Worker the binding targets. Default `'admin-router'`. */
88
- service?: string
89
- /** Service-binding name the worker reads. Default `'ROUTER'`. */
90
- binding?: string
91
- /** Host suffix that marks an instance host. Default `'.astrale.ai'`. */
92
- hostSuffix?: string
93
- /** Min dot-separated label count for an instance host. Default `4` (`<slug>.<region>.astrale.ai`). */
94
- minLabels?: number
95
- }
96
- }
@@ -1,54 +0,0 @@
1
- /**
2
- * Pure parsers for `wrangler` stdout. Kept separate from the process-spawning in
3
- * `wrangler-cli.ts` so the brittle bit — scraping wrangler's human output — is
4
- * unit-testable against captured fixtures without shelling out.
5
- */
6
-
7
- const READY_RE = /(?:Ready on|Listening on|⎔.*?at)\s+(https?:\/\/[^\s]+)/i
8
- const WORKERS_DEV_RE = /(https:\/\/[^\s]+\.workers\.dev)/i
9
-
10
- /**
11
- * Local dev URL from `wrangler dev` output, normalized to an origin on the given
12
- * port. Returns `undefined` when the output hasn't reported readiness yet.
13
- *
14
- * The fallback (when no explicit "Ready on" line) only accepts a localhost URL
15
- * on the EXPECTED port — wrangler may print unrelated localhost URLs (e.g. an
16
- * inspector/devtools endpoint on a different port) before readiness, and taking
17
- * one of those would point `astrale domain install <url>` at a dead endpoint.
18
- */
19
- export function parseDevReadyUrl(text: string, port: number): string | undefined {
20
- const ready = READY_RE.exec(text)
21
- if (ready) return normalizeLocal(ready[1]!, port)
22
- // `port` is a number, so it's safe to interpolate into the pattern. The
23
- // negative lookahead stops `:8787` from matching inside `:87870`.
24
- const localhostOnPort = new RegExp(
25
- `(https?://(?:localhost|127\\.0\\.0\\.1):${port})(?![0-9])`,
26
- 'i',
27
- )
28
- const m = localhostOnPort.exec(text)
29
- return m ? normalizeLocal(m[1]!, port) : undefined
30
- }
31
-
32
- /**
33
- * Authoritative public URL from `wrangler deploy` output. A custom-domain
34
- * `route` wins (the deploy attaches it); otherwise the printed `*.workers.dev`
35
- * URL. Returns `undefined` when neither is available (caller surfaces the raw
36
- * output).
37
- */
38
- export function parseDeployUrl(text: string, route?: string): string | undefined {
39
- if (route) return `https://${route.replace(/\/.*$/, '')}`
40
- const m = WORKERS_DEV_RE.exec(text)
41
- return m ? m[1] : undefined
42
- }
43
-
44
- /** Normalize a local dev URL to an origin: `0.0.0.0` → `localhost`, fill the port. */
45
- export function normalizeLocal(url: string, port: number): string {
46
- try {
47
- const u = new URL(url)
48
- if (u.hostname === '0.0.0.0') u.hostname = 'localhost'
49
- if (!u.port) u.port = String(port)
50
- return u.origin
51
- } catch {
52
- return `http://localhost:${port}`
53
- }
54
- }
@@ -1,324 +0,0 @@
1
- /**
2
- * Thin wrapper around the `wrangler` binary — the only place the adapter shells
3
- * out. `watch` runs `wrangler dev` (local workerd) and resolves once the worker
4
- * reports its local URL; `deploy` runs `wrangler deploy` and parses the
5
- * authoritative public URL from the output; secrets go through `wrangler secret
6
- * bulk`. The wrangler binary is resolved from the project's `node_modules/.bin`,
7
- * falling back to `npx wrangler`.
8
- */
9
-
10
- import type { ChildProcess } from 'node:child_process'
11
-
12
- import { spawn } from 'node:child_process'
13
- import { existsSync, readdirSync } from 'node:fs'
14
- import { mkdtemp, rm, writeFile } from 'node:fs/promises'
15
- import { createServer } from 'node:net'
16
- import { tmpdir } from 'node:os'
17
- import { join } from 'node:path'
18
-
19
- import { parseDeployUrl, parseDevReadyUrl } from './parse-output'
20
-
21
- function wranglerCommand(projectDir: string): { cmd: string; prefix: string[] } {
22
- const local = join(projectDir, 'node_modules', '.bin', 'wrangler')
23
- if (existsSync(local)) return { cmd: local, prefix: [] }
24
- return { cmd: 'npx', prefix: ['--yes', 'wrangler'] }
25
- }
26
-
27
- export interface DevHandle {
28
- url: string
29
- stop(): Promise<void>
30
- }
31
-
32
- /**
33
- * True when `port` is free on `host`. A taken port previously made `wrangler
34
- * dev` either die ("Address already in use") or — worse — a FIRST probe hit a
35
- * DIFFERENT project's dev server on the same port (observed in agent runs:
36
- * every reader of the docs converges on 8787/8899).
37
- */
38
- function portFree(port: number, host: string): Promise<boolean> {
39
- return new Promise((resolve) => {
40
- const srv = createServer()
41
- srv.once('error', () => resolve(false))
42
- srv.once('listening', () => srv.close(() => resolve(true)))
43
- srv.listen(port, host)
44
- })
45
- }
46
-
47
- /** An OS-assigned free port. */
48
- function ephemeralPort(host: string): Promise<number> {
49
- return new Promise((resolve, reject) => {
50
- const srv = createServer()
51
- srv.once('error', reject)
52
- srv.listen(0, host, () => {
53
- const addr = srv.address()
54
- const port = typeof addr === 'object' && addr ? addr.port : 0
55
- srv.close(() => resolve(port))
56
- })
57
- })
58
- }
59
-
60
- export async function runWranglerDev(args: {
61
- projectDir: string
62
- configPath: string
63
- port: number
64
- remote: boolean
65
- /** Bind address — '0.0.0.0' for tunneled/proxied dev (`--host`). Default loopback. */
66
- ip?: string
67
- /** When the port was NOT explicitly chosen, dodge a taken one automatically. */
68
- autoPickPort?: boolean
69
- onReload: () => void
70
- onLog?: (line: string) => void
71
- }): Promise<DevHandle> {
72
- const { cmd, prefix } = wranglerCommand(args.projectDir)
73
- const bindHost = args.ip ?? '127.0.0.1'
74
- if (args.autoPickPort && !(await portFree(args.port, bindHost))) {
75
- const picked = await ephemeralPort(bindHost)
76
- args.onLog?.(`port ${args.port} is taken — using ${picked} instead (pass --port to pin one)`)
77
- args = { ...args, port: picked }
78
- }
79
- const wranglerArgs = [
80
- ...prefix,
81
- 'dev',
82
- '--config',
83
- args.configPath,
84
- '--port',
85
- String(args.port),
86
- '--local-protocol',
87
- 'http',
88
- '--ip',
89
- args.ip ?? '127.0.0.1',
90
- ...(args.remote ? ['--remote'] : []),
91
- ]
92
-
93
- const child = spawn(cmd, wranglerArgs, {
94
- cwd: args.projectDir,
95
- stdio: ['ignore', 'pipe', 'pipe'],
96
- env: { ...process.env, WRANGLER_SEND_METRICS: 'false' },
97
- })
98
-
99
- const fallbackUrl = `http://localhost:${args.port}`
100
- // (args.port may have been re-picked above — everything below reads args.port)
101
- let resolved = false
102
- // Wrangler's watch mode STAYS ALIVE on a build failure (listener up, worker
103
- // never answers) — the classic silent hang. Track build errors so the
104
- // safety net can fail LOUD instead of resolving a dead URL.
105
- let buildErrorTail = ''
106
-
107
- const url = await new Promise<string>((resolve, reject) => {
108
- const onData = (buf: Buffer) => {
109
- const text = buf.toString()
110
- for (const line of text.split('\n')) {
111
- if (line.trim()) args.onLog?.(line)
112
- }
113
- if (/✘ \[ERROR\]|Build failed|Could not resolve "/.test(text)) {
114
- buildErrorTail = (buildErrorTail + text).slice(-2000)
115
- }
116
- if (!resolved) {
117
- const ready = parseDevReadyUrl(text, args.port)
118
- if (ready) {
119
- resolved = true
120
- resolve(ready)
121
- }
122
- } else if (/Reloading|Detected changes|Updated/i.test(text)) {
123
- args.onReload()
124
- }
125
- }
126
- child.stdout?.on('data', onData)
127
- child.stderr?.on('data', onData)
128
- child.on('exit', (code) => {
129
- if (!resolved) {
130
- resolved = true
131
- reject(new Error(`wrangler dev exited before becoming ready (code ${code ?? 'null'}).`))
132
- }
133
- })
134
- child.on('error', (err) => {
135
- if (!resolved) {
136
- resolved = true
137
- reject(err)
138
- }
139
- })
140
- // Safety net: if we never matched a URL but the process is alive, assume the
141
- // conventional localhost URL after a grace period — UNLESS the build
142
- // failed, in which case a listener may be up but the worker will never
143
- // answer: fail loud with the build output instead of handing back a dead
144
- // URL.
145
- setTimeout(() => {
146
- if (!resolved && child.exitCode === null) {
147
- resolved = true
148
- if (buildErrorTail) {
149
- void stopChild(child)
150
- reject(
151
- new Error(
152
- `worker build failed — the dev server would hang silently.\n${buildErrorTail}`,
153
- ),
154
- )
155
- } else {
156
- resolve(fallbackUrl)
157
- }
158
- }
159
- }, 15_000).unref?.()
160
- })
161
-
162
- return { url, stop: () => stopChild(child) }
163
- }
164
-
165
- export interface DeployArgs {
166
- configPath: string
167
- /** SELF-less config for the first-deploy two-pass (see `deployWithSelfFallback`). */
168
- fallbackConfigPath?: string
169
- /** The worker's own name, to scope the self-binding-missing detection. */
170
- workerName?: string
171
- route?: string
172
- onLog?: (line: string) => void
173
- }
174
-
175
- export async function runWranglerDeploy(
176
- args: DeployArgs & { projectDir: string },
177
- ): Promise<{ url: string; raw: string }> {
178
- const { cmd, prefix } = wranglerCommand(args.projectDir)
179
- const deploy = (configPath: string) =>
180
- runCapture(cmd, [...prefix, 'deploy', '--config', configPath], args.projectDir, args.onLog)
181
- return deployWithSelfFallback(deploy, args)
182
- }
183
-
184
- /**
185
- * Deploy with a one-time SELF-binding first-deploy recovery. A fresh worker that
186
- * declares a `services: SELF` binding can't deploy (its own script doesn't exist
187
- * yet); on THAT specific failure we deploy the SELF-less fallback to create the
188
- * script, then redeploy WITH SELF so autobinding works. Steady state (every
189
- * deploy after the first) is a single pass. The `deploy` runner is injected so
190
- * the orchestration is unit-testable without shelling out.
191
- */
192
- export async function deployWithSelfFallback(
193
- deploy: (configPath: string) => Promise<{ code: number; out: string }>,
194
- args: DeployArgs,
195
- ): Promise<{ url: string; raw: string }> {
196
- let { code, out } = await deploy(args.configPath)
197
-
198
- if (code !== 0 && args.fallbackConfigPath && isSelfBindingMissing(out, args.workerName)) {
199
- args.onLog?.(
200
- 'SELF service binding not resolvable yet (first deploy) — creating the worker, then re-binding SELF',
201
- )
202
- const first = await deploy(args.fallbackConfigPath)
203
- if (first.code !== 0) {
204
- throw new Error(
205
- `wrangler deploy (no-self pass) failed (code ${first.code}):\n${first.out.slice(-2000)}`,
206
- )
207
- }
208
- ;({ code, out } = await deploy(args.configPath))
209
- }
210
-
211
- if (code !== 0) {
212
- throw new Error(`wrangler deploy failed (code ${code}):\n${out.slice(-2000)}`)
213
- }
214
- const url = parseDeployUrl(out, args.route)
215
- if (!url) {
216
- throw new Error(`could not determine deployed URL from wrangler output:\n${out.slice(-2000)}`)
217
- }
218
- return { url, raw: out }
219
- }
220
-
221
- /**
222
- * True when wrangler failed specifically because the worker's OWN `SELF` service
223
- * binding can't resolve yet (first deploy of a fresh script). Requires the
224
- * worker name so an unrelated missing-service error doesn't trigger the two-pass.
225
- */
226
- export function isSelfBindingMissing(out: string, workerName?: string): boolean {
227
- const bindingError =
228
- /could not resolve binding/i.test(out) ||
229
- /service\b[^\n]*\bnot found/i.test(out) ||
230
- /script\b[^\n]*\bnot found/i.test(out)
231
- if (!bindingError || !/\bSELF\b/.test(out)) return false
232
- return workerName ? out.includes(workerName) : true
233
- }
234
-
235
- export async function bulkPutSecrets(args: {
236
- projectDir: string
237
- configPath: string
238
- secrets: Record<string, string>
239
- onLog?: (line: string) => void
240
- }): Promise<void> {
241
- const names = Object.keys(args.secrets)
242
- if (names.length === 0) return
243
- const { cmd, prefix } = wranglerCommand(args.projectDir)
244
- const dir = await mkdtemp(join(tmpdir(), 'astrale-secrets-'))
245
- const file = join(dir, 'secrets.json')
246
- try {
247
- await writeFile(file, JSON.stringify(args.secrets))
248
- const { code, out } = await runCapture(
249
- cmd,
250
- [...prefix, 'secret', 'bulk', file, '--config', args.configPath],
251
- args.projectDir,
252
- args.onLog,
253
- )
254
- if (code !== 0) {
255
- throw new Error(`wrangler secret bulk failed (code ${code}):\n${out.slice(-1500)}`)
256
- }
257
- } finally {
258
- await rm(dir, { recursive: true, force: true })
259
- }
260
- }
261
-
262
- // ── internals ──────────────────────────────────────────────────────────────
263
-
264
- function runCapture(
265
- cmd: string,
266
- args: string[],
267
- cwd: string,
268
- onLog?: (line: string) => void,
269
- ): Promise<{ code: number; out: string }> {
270
- return new Promise((resolve, reject) => {
271
- const child = spawn(cmd, args, {
272
- cwd,
273
- stdio: ['ignore', 'pipe', 'pipe'],
274
- env: { ...process.env, WRANGLER_SEND_METRICS: 'false' },
275
- })
276
- let out = ''
277
- const onData = (buf: Buffer) => {
278
- const text = buf.toString()
279
- out += text
280
- for (const line of text.split('\n')) if (line.trim()) onLog?.(line)
281
- }
282
- child.stdout?.on('data', onData)
283
- child.stderr?.on('data', onData)
284
- child.on('exit', (code) => resolve({ code: code ?? 1, out }))
285
- child.on('error', reject)
286
- })
287
- }
288
-
289
- async function stopChild(child: ChildProcess): Promise<void> {
290
- if (child.exitCode !== null) return
291
- await new Promise<void>((resolve) => {
292
- child.on('exit', () => resolve())
293
- child.kill('SIGTERM')
294
- setTimeout(() => {
295
- if (child.exitCode === null) child.kill('SIGKILL')
296
- resolve()
297
- }, 4000).unref?.()
298
- })
299
- }
300
-
301
- /**
302
- * Build the single-module worker bundle WITHOUT deploying — `wrangler deploy
303
- * --dry-run --outdir` (no Cloudflare auth required). Returns the path of the
304
- * bundled .js module (the managed adapter publishes its bytes).
305
- */
306
- export async function runWranglerBundle(args: {
307
- projectDir: string
308
- configPath: string
309
- outDir: string
310
- onLog?: (line: string) => void
311
- }): Promise<string> {
312
- const { cmd, prefix } = wranglerCommand(args.projectDir)
313
- const { code, out } = await runCapture(
314
- cmd,
315
- [...prefix, 'deploy', '--dry-run', '--outdir', args.outDir, '--config', args.configPath],
316
- args.projectDir,
317
- args.onLog,
318
- )
319
- if (code !== 0) throw new Error(`wrangler bundle failed (exit ${code}): ${out.slice(-400)}`)
320
- const js = readdirSync(args.outDir).filter((f) => f.endsWith('.js'))
321
- if (js.length === 0) throw new Error(`wrangler bundle produced no .js in ${args.outDir}`)
322
- const preferred = js.find((f) => f.startsWith('worker')) ?? js[0]!
323
- return join(args.outDir, preferred)
324
- }
@@ -1,9 +0,0 @@
1
- # Secrets for an env live in `.env.<env>` (e.g. .env.dev, .env.prod), pointed at
2
- # by `secrets:` in astrale.config.ts. The ENTIRE file is treated as secrets:
3
- # injected into the local runtime in dev, pushed to the Worker secret store in
4
- # prod. These files are gitignored — copy this to `.env.dev` and fill in.
5
- #
6
- # Add one line per secret your handlers read (they arrive as typed fields on
7
- # `Env` — see `env.ts`). For example:
8
- #
9
- # EXAMPLE_API_KEY=sk-...
@@ -1,16 +0,0 @@
1
- # Deps
2
- node_modules/
3
-
4
- # Generated plumbing (worker entry, wrangler config, identity, spec)
5
- .astrale/
6
- .domain-studio/.cache/
7
-
8
- # Worker dev + build artifacts
9
- .dev.vars
10
- .wrangler/
11
- .dist/
12
-
13
- # Secrets — every .env.<env> is gitignored; .env.example is the only one tracked
14
- .env
15
- .env.*
16
- !.env.example
@@ -1,13 +0,0 @@
1
- # Astrale domain
2
-
3
- Load the `astrale-domain` skill before changing schema, runtime, views, integrations, security, or
4
- simulation code. Install it user-level if needed:
5
-
6
- ```bash
7
- npx skills add astrale-os/cli -g
8
- ```
9
-
10
- This scaffold is intentionally empty. Organize schema, runtime, core, simulation, and client code by
11
- real bounded contexts. Keep I/O out of `core/`, use one explicit file per method or standalone function,
12
- wrap nondeterministic handler work in `step`, derive graph keys and paths from the compiled schema, and
13
- batch graph reads or mutations where possible.