@astrale-os/adapter-cloudflare 0.5.0-beta.22 → 0.5.0-beta.221

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 (201) hide show
  1. package/README.md +246 -0
  2. package/dist/adapter.d.ts +9 -15
  3. package/dist/adapter.js +43 -129
  4. package/dist/build/bundle/admit.d.ts +3 -0
  5. package/dist/build/bundle/admit.js +47 -0
  6. package/dist/build/bundle/compiled-wasm-loader.d.ts +8 -0
  7. package/dist/build/bundle/compiled-wasm-loader.js +21 -0
  8. package/dist/build/bundler.d.ts +21 -0
  9. package/dist/build/bundler.js +96 -0
  10. package/dist/build/closure.d.ts +4 -1
  11. package/dist/build/closure.js +7 -1
  12. package/dist/build/codegen/execution.d.ts +3 -13
  13. package/dist/build/codegen/execution.js +2 -44
  14. package/dist/build/codegen/wrangler.d.ts +28 -10
  15. package/dist/build/codegen/wrangler.js +71 -21
  16. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  17. package/dist/build/configuration/invocation-timeout.js +9 -0
  18. package/dist/build/configuration/request-limit.d.ts +2 -0
  19. package/dist/build/configuration/request-limit.js +9 -0
  20. package/dist/build/configuration/router.d.ts +7 -0
  21. package/dist/build/configuration/router.js +17 -0
  22. package/dist/build/configuration/settings.d.ts +6 -0
  23. package/dist/build/configuration/settings.js +40 -0
  24. package/dist/build/configuration.d.ts +4 -9
  25. package/dist/build/configuration.js +4 -40
  26. package/dist/build/frontend/files.d.ts +19 -0
  27. package/dist/build/frontend/files.js +99 -0
  28. package/dist/build/frontend/readiness.d.ts +16 -0
  29. package/dist/build/frontend/readiness.js +21 -0
  30. package/dist/build/frontend/revision.d.ts +5 -0
  31. package/dist/build/frontend/revision.js +14 -0
  32. package/dist/build/frontend/vite.d.ts +14 -0
  33. package/dist/build/frontend/vite.js +42 -0
  34. package/dist/build/frontend/vite.process.d.ts +7 -0
  35. package/dist/build/frontend/vite.process.js +65 -0
  36. package/dist/build/frontend/vite.runner.d.ts +1 -0
  37. package/dist/build/frontend/vite.runner.js +155 -0
  38. package/dist/build/index.d.ts +10 -6
  39. package/dist/build/index.js +10 -6
  40. package/dist/build/material.d.ts +10 -0
  41. package/dist/build/material.js +25 -0
  42. package/dist/build/worker/codegen/entry.d.ts +9 -0
  43. package/dist/build/worker/codegen/entry.js +65 -0
  44. package/dist/build/worker/codegen/literal.d.ts +28 -0
  45. package/dist/build/worker/codegen/literal.js +136 -0
  46. package/dist/build/worker/codegen/service.d.ts +14 -0
  47. package/dist/build/worker/codegen/service.js +57 -0
  48. package/dist/build/worker/execution.prepare.d.ts +20 -0
  49. package/dist/build/worker/execution.prepare.js +129 -0
  50. package/dist/build/worker/media-type.d.ts +1 -0
  51. package/dist/build/worker/media-type.js +20 -0
  52. package/dist/build/worker/modules.d.ts +20 -0
  53. package/dist/build/worker/modules.js +32 -0
  54. package/dist/build/worker/specifier.d.ts +5 -0
  55. package/dist/build/worker/specifier.js +15 -0
  56. package/dist/build/worker/upload.d.ts +23 -0
  57. package/dist/build/worker/upload.js +42 -0
  58. package/dist/hosting/activation.d.ts +46 -0
  59. package/dist/hosting/activation.js +127 -0
  60. package/dist/hosting/assets.d.ts +14 -0
  61. package/dist/hosting/assets.js +53 -0
  62. package/dist/hosting/bounded.d.ts +10 -0
  63. package/dist/hosting/bounded.js +32 -0
  64. package/dist/hosting/bytes.d.ts +6 -0
  65. package/dist/hosting/bytes.js +25 -0
  66. package/dist/hosting/client.d.ts +144 -0
  67. package/dist/hosting/client.js +491 -0
  68. package/dist/hosting/dispatcher/cron.d.mts +10 -0
  69. package/dist/hosting/dispatcher/cron.mjs +135 -0
  70. package/dist/hosting/dispatcher/deployments.d.mts +26 -0
  71. package/dist/hosting/dispatcher/deployments.mjs +158 -0
  72. package/dist/hosting/dispatcher/dispatcher.d.mts +17 -0
  73. package/dist/hosting/dispatcher/dispatcher.mjs +76 -0
  74. package/dist/hosting/dispatcher/env.d.mts +51 -0
  75. package/dist/hosting/dispatcher/failure.d.mts +4 -0
  76. package/dist/hosting/dispatcher/failure.mjs +15 -0
  77. package/dist/hosting/dispatcher/index.d.mts +4 -0
  78. package/dist/hosting/dispatcher/index.mjs +8 -0
  79. package/dist/hosting/dispatcher/modules.d.ts +24 -0
  80. package/dist/hosting/dispatcher/modules.js +55 -0
  81. package/dist/hosting/dispatcher/services.d.mts +23 -0
  82. package/dist/hosting/dispatcher/services.mjs +202 -0
  83. package/dist/hosting/identity.d.ts +15 -0
  84. package/dist/hosting/identity.js +36 -0
  85. package/dist/hosting/index.d.ts +34 -0
  86. package/dist/hosting/index.js +32 -0
  87. package/dist/hosting/kv.d.ts +90 -0
  88. package/dist/hosting/kv.js +207 -0
  89. package/dist/hosting/listing.d.ts +34 -0
  90. package/dist/hosting/listing.js +49 -0
  91. package/dist/hosting/names.d.ts +16 -0
  92. package/dist/hosting/names.js +28 -0
  93. package/dist/hosting/provision/account.d.ts +11 -0
  94. package/dist/hosting/provision/account.js +86 -0
  95. package/dist/hosting/provision/dispatcher.d.ts +42 -0
  96. package/dist/hosting/provision/dispatcher.js +99 -0
  97. package/dist/hosting/provision/ingress.d.ts +12 -0
  98. package/dist/hosting/provision/ingress.js +31 -0
  99. package/dist/hosting/provision/plan.d.ts +143 -0
  100. package/dist/hosting/provision/plan.js +246 -0
  101. package/dist/hosting/provision/routing.d.ts +82 -0
  102. package/dist/hosting/provision/routing.js +226 -0
  103. package/dist/hosting/readiness.d.ts +53 -0
  104. package/dist/hosting/readiness.js +82 -0
  105. package/dist/hosting/refusal.d.ts +28 -0
  106. package/dist/hosting/refusal.js +13 -0
  107. package/dist/hosting/retirement.d.ts +68 -0
  108. package/dist/hosting/retirement.js +99 -0
  109. package/dist/hosting/retry-after.d.ts +6 -0
  110. package/dist/hosting/retry-after.js +55 -0
  111. package/dist/hosting/script.d.ts +186 -0
  112. package/dist/hosting/script.js +324 -0
  113. package/dist/hosting/testing/fake-cloudflare.d.ts +212 -0
  114. package/dist/hosting/testing/fake-cloudflare.js +757 -0
  115. package/dist/hosting/testing/index.d.ts +6 -0
  116. package/dist/hosting/testing/index.js +6 -0
  117. package/dist/hosting/time.d.ts +4 -0
  118. package/dist/hosting/time.js +20 -0
  119. package/dist/identity/binding.d.ts +1 -1
  120. package/dist/identity/binding.js +1 -1
  121. package/dist/identity/material.d.ts +1 -2
  122. package/dist/identity/material.js +5 -18
  123. package/dist/index.d.ts +14 -12
  124. package/dist/index.js +13 -11
  125. package/dist/namespace/configure.d.ts +22 -0
  126. package/dist/namespace/configure.js +199 -0
  127. package/dist/namespace/coordinates.d.ts +15 -0
  128. package/dist/namespace/coordinates.js +49 -0
  129. package/dist/namespace/deploy-release.d.ts +53 -0
  130. package/dist/namespace/deploy-release.js +386 -0
  131. package/dist/namespace/hosting.d.ts +29 -0
  132. package/dist/namespace/hosting.js +120 -0
  133. package/dist/namespace/index.d.ts +12 -0
  134. package/dist/namespace/index.js +12 -0
  135. package/dist/namespace/list.d.ts +18 -0
  136. package/dist/namespace/list.js +63 -0
  137. package/dist/namespace/readiness.d.ts +30 -0
  138. package/dist/namespace/readiness.js +31 -0
  139. package/dist/namespace/record.d.ts +21 -0
  140. package/dist/namespace/record.js +53 -0
  141. package/dist/params.d.ts +60 -76
  142. package/dist/release/build.d.ts +35 -0
  143. package/dist/release/build.js +44 -0
  144. package/dist/release/deployment.d.ts +44 -0
  145. package/dist/release/deployment.js +141 -0
  146. package/dist/release/index.d.ts +2 -2
  147. package/dist/release/index.js +2 -2
  148. package/dist/worker/binary.d.ts +21 -0
  149. package/dist/worker/binary.js +31 -0
  150. package/dist/worker/build-digest.d.ts +10 -0
  151. package/dist/worker/build-digest.js +22 -0
  152. package/dist/worker/cache.d.ts +28 -0
  153. package/dist/worker/cache.js +70 -0
  154. package/dist/worker/durable.d.ts +3 -0
  155. package/dist/worker/durable.js +5 -0
  156. package/dist/worker/entry.d.ts +38 -25
  157. package/dist/worker/entry.js +87 -109
  158. package/dist/worker/front.d.ts +56 -0
  159. package/dist/worker/front.js +59 -0
  160. package/dist/worker/frontend.d.ts +4 -0
  161. package/dist/worker/frontend.js +83 -0
  162. package/dist/worker/index.d.ts +4 -1
  163. package/dist/worker/index.js +4 -1
  164. package/dist/worker/restate.d.ts +6 -0
  165. package/dist/worker/restate.js +6 -0
  166. package/dist/worker/settings.d.ts +47 -0
  167. package/dist/worker/settings.js +163 -0
  168. package/dist/wrangler/bundle.d.ts +10 -0
  169. package/dist/wrangler/bundle.js +27 -0
  170. package/dist/wrangler/index.d.ts +3 -0
  171. package/dist/wrangler/index.js +3 -0
  172. package/dist/wrangler/process.d.ts +15 -0
  173. package/dist/wrangler/process.js +113 -0
  174. package/dist/wrangler/type-generation.d.ts +6 -0
  175. package/dist/wrangler/type-generation.js +19 -0
  176. package/package.json +36 -14
  177. package/template/astrale.config.ts +42 -36
  178. package/dist/build/artifact.d.ts +0 -8
  179. package/dist/build/artifact.js +0 -179
  180. package/dist/build/codegen/gateway.d.ts +0 -1
  181. package/dist/build/codegen/gateway.js +0 -7
  182. package/dist/build/frontend-v1.d.ts +0 -16
  183. package/dist/build/frontend-v1.js +0 -133
  184. package/dist/build/parse-output.d.ts +0 -26
  185. package/dist/build/parse-output.js +0 -57
  186. package/dist/build/wrangler-cli.d.ts +0 -105
  187. package/dist/build/wrangler-cli.js +0 -448
  188. package/dist/deploy/deploy.d.ts +0 -17
  189. package/dist/deploy/deploy.js +0 -207
  190. package/dist/deploy/index.d.ts +0 -1
  191. package/dist/deploy/index.js +0 -1
  192. package/dist/identity/secret.d.ts +0 -3
  193. package/dist/identity/secret.js +0 -7
  194. package/dist/identity/source.d.ts +0 -26
  195. package/dist/identity/source.js +0 -98
  196. package/dist/release/namespace.d.ts +0 -2
  197. package/dist/release/namespace.js +0 -6
  198. package/dist/release/target.d.ts +0 -2
  199. package/dist/release/target.js +0 -9
  200. package/dist/worker/gateway.d.ts +0 -15
  201. package/dist/worker/gateway.js +0 -26
@@ -0,0 +1,42 @@
1
+ import type { CloudflareClient } from '../client.js';
2
+ import type { DispatcherModule } from '../dispatcher/modules.js';
3
+ /** The runtime of every dispatcher upload. */
4
+ export declare const DISPATCHER_COMPATIBILITY_DATE = "2026-08-26";
5
+ export declare const DISPATCHER_COMPATIBILITY_FLAGS: readonly string[];
6
+ /** One binding of an account Worker, as its upload metadata and settings name it. */
7
+ export type WorkerBinding = Readonly<Record<string, string>> & {
8
+ readonly type: string;
9
+ readonly name: string;
10
+ };
11
+ /**
12
+ * The bindings of one dispatcher, in their order: a consumer's own (`extra`), then the
13
+ * deployments namespace it routes to (`DEPLOYMENTS`), the routing KV it reads
14
+ * (`SCHEDULES`) and, unless `calls` is null, the calls dataset (`CALLS`).
15
+ */
16
+ export declare function dispatcherBindings(input: {
17
+ readonly namespace: string;
18
+ readonly routingKv: string;
19
+ readonly calls: string | null;
20
+ readonly extra?: readonly WorkerBinding[];
21
+ }): readonly WorkerBinding[];
22
+ /**
23
+ * Upload the dispatcher as an account Worker (a plain PUT that replaces it): `index.mjs` as its
24
+ * main module, compatibility date 2026-08-26 with `nodejs_compat`, observability on, and no
25
+ * custom limits: a `limits.subRequests` would also count the deployments' own binding calls.
26
+ */
27
+ export declare function uploadDispatcher(input: {
28
+ readonly client: CloudflareClient;
29
+ readonly worker: string;
30
+ readonly modules: readonly DispatcherModule[];
31
+ readonly bindings: readonly WorkerBinding[];
32
+ }): Promise<void>;
33
+ /** Replace the dispatcher's cron triggers: exactly `cron`, or none. */
34
+ export declare function setDispatcherCron(client: CloudflareClient, worker: string, cron: string | null): Promise<void>;
35
+ /**
36
+ * Turn a Worker's workers.dev route on or off, previews always off.
37
+ */
38
+ export declare function setWorkersDev(client: CloudflareClient, worker: string, enabled: boolean): Promise<void>;
39
+ /** The bindings of one account Worker, or undefined when it does not exist. */
40
+ export declare function workerBindings(client: CloudflareClient, worker: string): Promise<readonly WorkerBinding[] | undefined>;
41
+ /** What one binding points at: its namespace, KV namespace, dataset or service. */
42
+ export declare function bindingTarget(binding: WorkerBinding): string | undefined;
@@ -0,0 +1,99 @@
1
+ import { isNotFound, CloudflareApiError } from '../client.js';
2
+ import { isUtcCron } from '../dispatcher/cron.mjs';
3
+ import { DISPATCHER_MAIN_MODULE } from '../dispatcher/modules.js';
4
+ /** The runtime of every dispatcher upload. */
5
+ export const DISPATCHER_COMPATIBILITY_DATE = '2026-08-26';
6
+ export const DISPATCHER_COMPATIBILITY_FLAGS = Object.freeze(['nodejs_compat']);
7
+ /**
8
+ * The bindings of one dispatcher, in their order: a consumer's own (`extra`), then the
9
+ * deployments namespace it routes to (`DEPLOYMENTS`), the routing KV it reads
10
+ * (`SCHEDULES`) and, unless `calls` is null, the calls dataset (`CALLS`).
11
+ */
12
+ export function dispatcherBindings(input) {
13
+ const bindings = [
14
+ ...(input.extra ?? []),
15
+ { type: 'dispatch_namespace', name: 'DEPLOYMENTS', namespace: input.namespace },
16
+ { type: 'kv_namespace', name: 'SCHEDULES', namespace_id: input.routingKv },
17
+ ...(input.calls === null
18
+ ? []
19
+ : [{ type: 'analytics_engine', name: 'CALLS', dataset: input.calls }]),
20
+ ];
21
+ const names = bindings.map((binding) => binding.name);
22
+ if (new Set(names).size !== names.length) {
23
+ throw new TypeError('The dispatcher binds one name twice.');
24
+ }
25
+ return Object.freeze(bindings.map((binding) => Object.freeze({ ...binding })));
26
+ }
27
+ /**
28
+ * Upload the dispatcher as an account Worker (a plain PUT that replaces it): `index.mjs` as its
29
+ * main module, compatibility date 2026-08-26 with `nodejs_compat`, observability on, and no
30
+ * custom limits: a `limits.subRequests` would also count the deployments' own binding calls.
31
+ */
32
+ export async function uploadDispatcher(input) {
33
+ if (!input.modules.some((module) => module.name === DISPATCHER_MAIN_MODULE)) {
34
+ throw new TypeError(`The dispatcher upload has no ${DISPATCHER_MAIN_MODULE}.`);
35
+ }
36
+ const form = new FormData();
37
+ form.append('metadata', new Blob([
38
+ JSON.stringify({
39
+ main_module: DISPATCHER_MAIN_MODULE,
40
+ compatibility_date: DISPATCHER_COMPATIBILITY_DATE,
41
+ compatibility_flags: [...DISPATCHER_COMPATIBILITY_FLAGS],
42
+ bindings: input.bindings,
43
+ observability: { enabled: true },
44
+ }),
45
+ ], { type: 'application/json' }), 'metadata');
46
+ for (const module of input.modules) {
47
+ form.append(module.name, new Blob([module.bytes], { type: module.type }), module.name);
48
+ }
49
+ await input.client.form('PUT', workerPath(input.client, input.worker), form);
50
+ }
51
+ /** Replace the dispatcher's cron triggers: exactly `cron`, or none. */
52
+ export async function setDispatcherCron(client, worker, cron) {
53
+ if (cron !== null && !isUtcCron(cron)) {
54
+ throw new TypeError('The dispatcher cron must be a valid five-field UTC schedule.');
55
+ }
56
+ await client.json('PUT', workerPath(client, worker, '/schedules'), cron === null ? [] : [{ cron }]);
57
+ }
58
+ /**
59
+ * Turn a Worker's workers.dev route on or off, previews always off.
60
+ */
61
+ export async function setWorkersDev(client, worker, enabled) {
62
+ await client.json('POST', workerPath(client, worker, '/subdomain'), {
63
+ enabled,
64
+ previews_enabled: false,
65
+ });
66
+ }
67
+ /** The bindings of one account Worker, or undefined when it does not exist. */
68
+ export async function workerBindings(client, worker) {
69
+ let settings;
70
+ try {
71
+ settings = await client.json('GET', workerPath(client, worker, '/settings'));
72
+ }
73
+ catch (cause) {
74
+ if (isNotFound(cause))
75
+ return undefined;
76
+ throw cause;
77
+ }
78
+ const bindings = settings?.bindings ?? [];
79
+ if (!Array.isArray(bindings))
80
+ invalid();
81
+ return Object.freeze(bindings.map((binding) => {
82
+ if (binding === null || typeof binding !== 'object')
83
+ invalid();
84
+ const fields = binding;
85
+ if (typeof fields.name !== 'string' || typeof fields.type !== 'string')
86
+ invalid();
87
+ return Object.freeze(Object.fromEntries(Object.entries(fields).filter((entry) => typeof entry[1] === 'string')));
88
+ }));
89
+ }
90
+ /** What one binding points at: its namespace, KV namespace, dataset or service. */
91
+ export function bindingTarget(binding) {
92
+ return binding.namespace ?? binding.namespace_id ?? binding.dataset ?? binding.service;
93
+ }
94
+ function workerPath(client, worker, suffix = '') {
95
+ return client.account(`/workers/scripts/${encodeURIComponent(worker)}${suffix}`);
96
+ }
97
+ function invalid() {
98
+ throw new CloudflareApiError('upstream', 'Cloudflare returned invalid Worker settings.');
99
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Whether a dispatcher answers a host that names no deployment, as only the kit's dispatcher does:
3
+ * 404, `no such service: <name>`, never cached. A never-deployed name proves the wildcard DNS
4
+ * record, trusted HTTPS and the dispatcher route without reaching any deployment. A failed probe
5
+ * answers false; only the caller's cancellation rejects.
6
+ */
7
+ export declare function dispatcherIngressReady(input: {
8
+ readonly fetch: typeof fetch;
9
+ readonly hostname: string;
10
+ readonly timeoutMs: number;
11
+ readonly signal?: AbortSignal;
12
+ }): Promise<boolean>;
@@ -0,0 +1,31 @@
1
+ import { RETIREMENT_PROBE_PATH } from '../retirement.js';
2
+ /**
3
+ * Whether a dispatcher answers a host that names no deployment, as only the kit's dispatcher does:
4
+ * 404, `no such service: <name>`, never cached. A never-deployed name proves the wildcard DNS
5
+ * record, trusted HTTPS and the dispatcher route without reaching any deployment. A failed probe
6
+ * answers false; only the caller's cancellation rejects.
7
+ */
8
+ export async function dispatcherIngressReady(input) {
9
+ const timeout = AbortSignal.timeout(input.timeoutMs);
10
+ try {
11
+ const url = new URL(RETIREMENT_PROBE_PATH, `https://${input.hostname}`);
12
+ url.searchParams.set('probe', Date.now().toString(36));
13
+ const response = await input.fetch(url, {
14
+ method: 'GET',
15
+ headers: { accept: 'application/json', 'cache-control': 'no-cache' },
16
+ redirect: 'manual',
17
+ signal: input.signal === undefined ? timeout : AbortSignal.any([input.signal, timeout]),
18
+ });
19
+ const body = await response.text();
20
+ const name = url.hostname.split('.')[0];
21
+ return (name !== undefined &&
22
+ response.status === 404 &&
23
+ response.headers.get('cache-control') === 'no-store' &&
24
+ body === `no such service: ${name}`);
25
+ }
26
+ catch (cause) {
27
+ if (input.signal?.aborted === true)
28
+ throw input.signal.reason ?? cause;
29
+ return false;
30
+ }
31
+ }
@@ -0,0 +1,143 @@
1
+ import type { CloudflareClient } from '../client.js';
2
+ import type { WorkerBinding } from './dispatcher.js';
3
+ import { RoutingKv } from '../kv.js';
4
+ /** Everything one hosting (a dispatch namespace, its routing KV, dispatcher and ingress) is. */
5
+ export interface HostingConfig {
6
+ readonly client: CloudflareClient;
7
+ /** The dispatch namespace deployments are uploaded into. */
8
+ readonly namespace: string;
9
+ /** `https://<label>.<routingDomain>` reaches each deployment. */
10
+ readonly routingDomain: string;
11
+ /**
12
+ * The zone that holds the routing domain's DNS records and Worker route. Absent: no ingress is
13
+ * provisioned (the caller routes the domain itself).
14
+ */
15
+ readonly zone?: string;
16
+ readonly dispatcher: {
17
+ /** The account Worker that dispatches the namespace. */
18
+ readonly worker: string;
19
+ /** A consumer's own modules: its `index.mjs` and what it imports. */
20
+ readonly modules?: readonly {
21
+ readonly name: string;
22
+ readonly bytes: Uint8Array;
23
+ }[];
24
+ /** Bindings the consumer's own modules read, bound before the kit's. */
25
+ readonly bindings?: readonly WorkerBinding[];
26
+ /** The dispatcher's one cron trigger, which fires `cron:` schedules. Default: none. */
27
+ readonly cron?: string;
28
+ /** Whether its workers.dev route is on. Default off: deployments are reached by host only. */
29
+ readonly workersDev?: boolean;
30
+ };
31
+ /**
32
+ * The routing KV: found or created by title (default `routingKvTitle(namespace)`, which every
33
+ * namespace-mode deployer finds), or an existing one by id.
34
+ */
35
+ readonly routingKv?: {
36
+ readonly title: string;
37
+ } | {
38
+ readonly id: string;
39
+ };
40
+ /** The calls dataset bound as `CALLS`. Default `callsDataset(namespace)`; `null` binds none. */
41
+ readonly callsDataset?: string | null;
42
+ /**
43
+ * `refuse` (default): provision only a routing domain dedicated to this dispatcher; anything
44
+ * else at, under or above it blocks. `repoint`: rewrite the wildcard record and route when they
45
+ * say otherwise, and ignore everything else.
46
+ */
47
+ readonly foreign?: 'refuse' | 'repoint';
48
+ /** The comment of the wildcard DNS record. */
49
+ readonly comment?: string;
50
+ /** Reaches the routing domain over HTTPS for the ingress probe; absent: no probe. */
51
+ readonly fetch?: typeof fetch;
52
+ }
53
+ /**
54
+ * What provisioning does, read before anything is written. Every resource is `present` (adopted
55
+ * as is) or `create`; the dispatcher is uploaded again on every run.
56
+ */
57
+ export interface HostingPlan {
58
+ readonly account: string;
59
+ readonly namespace: {
60
+ readonly name: string;
61
+ readonly state: 'present' | 'create';
62
+ /**
63
+ * The scripts of the namespace with no `record:<label>`, sorted, with their tags: uploads a
64
+ * deployer has not activated yet, or never will. The dispatcher answers them `503`;
65
+ * provisioning leaves them as they are. A consumer may refuse some by their tags.
66
+ */
67
+ readonly unactivated: readonly {
68
+ readonly script: string;
69
+ readonly tags: readonly string[];
70
+ }[];
71
+ };
72
+ readonly routingKv: {
73
+ readonly title?: string;
74
+ readonly state: 'present' | 'create';
75
+ readonly id?: string;
76
+ };
77
+ /** Analytics Engine creates the dataset with its first data point: binding it provisions it. */
78
+ readonly callsDataset: string | null;
79
+ readonly dispatcher: {
80
+ readonly worker: string;
81
+ readonly state: 'present' | 'create';
82
+ readonly modules: readonly string[];
83
+ readonly bindings: readonly WorkerBinding[];
84
+ readonly cron: string | null;
85
+ /** No custom limits: `limits.subRequests` would count the deployments' binding calls. */
86
+ readonly limits: null;
87
+ readonly workersDev: boolean;
88
+ };
89
+ readonly routing: {
90
+ readonly zone: string;
91
+ readonly routingDomain: string;
92
+ readonly pattern: string;
93
+ readonly dns: 'present' | 'create' | 'repoint';
94
+ readonly route: 'present' | 'create' | 'repoint';
95
+ } | null;
96
+ /** What the reads prove of the API token; writing is proven only by provisioning itself. */
97
+ readonly token: {
98
+ readonly reads: 'proven';
99
+ readonly writes: 'unproven';
100
+ };
101
+ /**
102
+ * What forbids provisioning, each named: an account Worker under the dispatcher name that is not
103
+ * this namespace's dispatcher; an existing namespace with scripts and no routing KV (another
104
+ * data plane's); and, with `foreign: 'refuse'`, anything else that serves a host at, under or
105
+ * above the routing domain. Applying refuses before the first write when any is named; a
106
+ * consumer may add its own before applying.
107
+ */
108
+ readonly blockers: readonly string[];
109
+ }
110
+ /** What `applyHosting` provisioned. */
111
+ export type HostingProvisioning = HostingPlan & {
112
+ readonly kind: 'provisioned';
113
+ readonly routingKv: {
114
+ readonly title?: string;
115
+ readonly state: 'present' | 'create';
116
+ readonly id: string;
117
+ };
118
+ /** Whether a never-deployed host already reaches the dispatcher over HTTPS (when probed). */
119
+ readonly ingress: 'ready' | 'unverified' | 'skipped';
120
+ };
121
+ /**
122
+ * Plan one hosting with reads only: the namespace and its scripts, its routing KV, the dispatcher
123
+ * Worker and the routing domain's ingress. Provisioning never takes over what serves something
124
+ * else, and the plan names each blocker. A token that cannot read one of them is a `token-scope`
125
+ * refusal, naming the permission.
126
+ */
127
+ export declare function planHosting(config: HostingConfig): Promise<HostingPlan>;
128
+ /**
129
+ * Apply one plan: refuse any blocker it names (`resource-conflict`) before the first write, then
130
+ * converge in order: the routing KV, then the namespace (so that a namespace this provisioning
131
+ * created always has the KV that marks it as this hosting's, even after an interrupted run), the
132
+ * dispatcher (the kit's modules and the consumer's, bound to the namespace as `DEPLOYMENTS`, the
133
+ * routing KV as `SCHEDULES` and the calls dataset as `CALLS`), its cron and workers.dev route, then
134
+ * the wildcard DNS record and route of the routing domain. It is idempotent: a rerun adopts what
135
+ * exists, leaves every deployment script as it is and uploads the dispatcher again. It then
136
+ * checks, without failing, that a never-deployed host reaches the dispatcher over HTTPS: the
137
+ * routing domain's certificate is the operator's.
138
+ */
139
+ export declare function applyHosting(config: HostingConfig, plan: HostingPlan): Promise<HostingProvisioning>;
140
+ /** Plan one hosting and apply the plan (`planHosting`, then `applyHosting`). */
141
+ export declare function provisionHosting(config: HostingConfig): Promise<HostingProvisioning>;
142
+ /** Open the routing KV a provisioned hosting reads, as a deployer does. */
143
+ export declare function openHostingKv(config: Pick<HostingConfig, 'client' | 'namespace' | 'routingKv'>): Promise<RoutingKv>;
@@ -0,0 +1,246 @@
1
+ import { CLOUDFLARE_FAN_OUT, mapBounded } from '../bounded.js';
2
+ import { CloudflareApiError } from '../client.js';
3
+ import { dispatcherModules } from '../dispatcher/modules.js';
4
+ import { findKvNamespace, RECORD_PREFIX, RoutingKv } from '../kv.js';
5
+ import { callsDataset as derivedCallsDataset, routingKvTitle } from '../names.js';
6
+ import { HostingRefusal } from '../refusal.js';
7
+ import { observeScript } from '../script.js';
8
+ import { dispatchNamespaceExists, ensureDispatchNamespace, ensureKvNamespace, kvNamespaceExists, namespaceScriptNames, } from './account.js';
9
+ import { bindingTarget, dispatcherBindings, setDispatcherCron, setWorkersDev, uploadDispatcher, workerBindings, } from './dispatcher.js';
10
+ import { dispatcherIngressReady } from './ingress.js';
11
+ import { applyWildcardRouting, observeDedicatedRouting, observeWildcardRouting } from './routing.js';
12
+ const INGRESS_PROBE_TIMEOUT_MS = 10_000;
13
+ const DEFAULT_ROUTING_COMMENT = 'Astrale deployments routing';
14
+ /** How many scripts of an existing namespace a blocker names. */
15
+ const NAMED_SCRIPTS = 5;
16
+ /**
17
+ * Plan one hosting with reads only: the namespace and its scripts, its routing KV, the dispatcher
18
+ * Worker and the routing domain's ingress. Provisioning never takes over what serves something
19
+ * else, and the plan names each blocker. A token that cannot read one of them is a `token-scope`
20
+ * refusal, naming the permission.
21
+ */
22
+ export async function planHosting(config) {
23
+ const { client, namespace } = config;
24
+ const worker = config.dispatcher.worker;
25
+ const title = await routingTitle(config);
26
+ const explicitKv = config.routingKv !== undefined && 'id' in config.routingKv ? config.routingKv.id : undefined;
27
+ const [namespaceState, routingKvId] = await readable('Workers Scripts and Workers KV Storage', () => Promise.all([
28
+ dispatchNamespaceExists(client, namespace),
29
+ explicitKv === undefined
30
+ ? findKvNamespace(client, title)
31
+ : kvNamespaceExists(client, explicitKv).then((exists) => exists ? explicitKv : undefined),
32
+ ]));
33
+ const blockers = [];
34
+ if (explicitKv !== undefined && routingKvId === undefined) {
35
+ blockers.push(`the account has no KV namespace ${explicitKv}`);
36
+ }
37
+ const calls = config.callsDataset === undefined ? await derivedCallsDataset(namespace) : config.callsDataset;
38
+ const bindings = dispatcherBindings({
39
+ namespace,
40
+ routingKv: routingKvId ?? '<created>',
41
+ calls,
42
+ ...(config.dispatcher.bindings === undefined ? {} : { extra: config.dispatcher.bindings }),
43
+ });
44
+ const occupancy = namespaceState
45
+ ? await readable('Workers Scripts and Workers KV Storage', () => namespaceOccupancy(config, routingKvId))
46
+ : { blockers: [], unactivated: [] };
47
+ blockers.push(...occupancy.blockers);
48
+ const existing = await readable('Workers Scripts', () => workerBindings(client, worker));
49
+ if (existing !== undefined) {
50
+ const foreign = existing.filter((binding) => !bindings.some((expected) => expected.name === binding.name &&
51
+ expected.type === binding.type &&
52
+ bindingTarget(expected) === bindingTarget(binding)));
53
+ // Only this namespace's dispatcher is uploaded again: it binds DEPLOYMENTS to this namespace
54
+ // and nothing that points elsewhere. Any other Worker under that name is never replaced.
55
+ const dispatches = existing.some((binding) => binding.name === 'DEPLOYMENTS' &&
56
+ binding.type === 'dispatch_namespace' &&
57
+ binding.namespace === namespace);
58
+ if (!dispatches || foreign.length > 0) {
59
+ blockers.push(`the Worker ${worker} already exists and is not the dispatcher of ${namespace}` +
60
+ `${foreign.length === 0 ? '' : ` (it binds ${foreign.map((binding) => binding.name).join(', ')})`}`);
61
+ }
62
+ }
63
+ let routing = null;
64
+ if (config.zone !== undefined) {
65
+ const observed = await readable('Zone DNS, Workers Routes and Workers Scripts (custom domains)', () => observeRouting(config, config.zone));
66
+ if ('occupants' in observed)
67
+ blockers.push(...observed.occupants);
68
+ routing = Object.freeze({
69
+ zone: config.zone,
70
+ routingDomain: config.routingDomain,
71
+ pattern: observed.pattern,
72
+ dns: stateOf(observed.dns.state),
73
+ route: stateOf(observed.route.state),
74
+ });
75
+ }
76
+ const modules = await dispatcherModules(config.dispatcher.modules ?? []);
77
+ return Object.freeze({
78
+ account: client.accountId,
79
+ namespace: Object.freeze({
80
+ name: namespace,
81
+ state: namespaceState ? 'present' : 'create',
82
+ unactivated: Object.freeze(occupancy.unactivated),
83
+ }),
84
+ routingKv: Object.freeze({
85
+ ...(explicitKv === undefined ? { title } : {}),
86
+ ...(routingKvId === undefined
87
+ ? { state: 'create' }
88
+ : { state: 'present', id: routingKvId }),
89
+ }),
90
+ callsDataset: calls,
91
+ dispatcher: Object.freeze({
92
+ worker,
93
+ state: existing === undefined ? 'create' : 'present',
94
+ modules: Object.freeze(modules.map((module) => module.name)),
95
+ bindings,
96
+ cron: config.dispatcher.cron ?? null,
97
+ limits: null,
98
+ workersDev: config.dispatcher.workersDev ?? false,
99
+ }),
100
+ routing,
101
+ token: Object.freeze({ reads: 'proven', writes: 'unproven' }),
102
+ blockers: Object.freeze(blockers),
103
+ });
104
+ }
105
+ /**
106
+ * Apply one plan: refuse any blocker it names (`resource-conflict`) before the first write, then
107
+ * converge in order: the routing KV, then the namespace (so that a namespace this provisioning
108
+ * created always has the KV that marks it as this hosting's, even after an interrupted run), the
109
+ * dispatcher (the kit's modules and the consumer's, bound to the namespace as `DEPLOYMENTS`, the
110
+ * routing KV as `SCHEDULES` and the calls dataset as `CALLS`), its cron and workers.dev route, then
111
+ * the wildcard DNS record and route of the routing domain. It is idempotent: a rerun adopts what
112
+ * exists, leaves every deployment script as it is and uploads the dispatcher again. It then
113
+ * checks, without failing, that a never-deployed host reaches the dispatcher over HTTPS: the
114
+ * routing domain's certificate is the operator's.
115
+ */
116
+ export async function applyHosting(config, plan) {
117
+ const { client } = config;
118
+ if (plan.blockers.length > 0) {
119
+ throw new HostingRefusal('resource-conflict', `Provisioning ${config.namespace} would take over what serves something else: ` +
120
+ `${plan.blockers.join('; ')}. Nothing was changed.`);
121
+ }
122
+ const routingKv = plan.routingKv.id ??
123
+ (await ensureKvNamespace(client, plan.routingKv.title ?? (await routingTitle(config))));
124
+ await ensureDispatchNamespace(client, config.namespace);
125
+ const bindings = dispatcherBindings({
126
+ namespace: config.namespace,
127
+ routingKv,
128
+ calls: plan.callsDataset,
129
+ ...(config.dispatcher.bindings === undefined ? {} : { extra: config.dispatcher.bindings }),
130
+ });
131
+ await uploadDispatcher({
132
+ client,
133
+ worker: config.dispatcher.worker,
134
+ modules: await dispatcherModules(config.dispatcher.modules ?? []),
135
+ bindings,
136
+ });
137
+ await setDispatcherCron(client, config.dispatcher.worker, plan.dispatcher.cron);
138
+ await setWorkersDev(client, config.dispatcher.worker, plan.dispatcher.workersDev);
139
+ let ingress = 'skipped';
140
+ if (config.zone !== undefined) {
141
+ // Observed again: another run may have converged part of the ingress meanwhile.
142
+ const observed = await observeRouting(config, config.zone);
143
+ if ('occupants' in observed && observed.occupants.length > 0) {
144
+ throw new HostingRefusal('resource-conflict', `The routing domain ${config.routingDomain} already serves something else ` +
145
+ `(${observed.occupants.join('; ')}); the ingress was not changed.`);
146
+ }
147
+ await applyWildcardRouting({
148
+ client,
149
+ zone: config.zone,
150
+ dispatchWorker: config.dispatcher.worker,
151
+ observed,
152
+ comment: config.comment ?? DEFAULT_ROUTING_COMMENT,
153
+ });
154
+ if (config.fetch !== undefined) {
155
+ const ready = await dispatcherIngressReady({
156
+ fetch: config.fetch,
157
+ hostname: `${crypto.randomUUID()}.${config.routingDomain}`,
158
+ timeoutMs: INGRESS_PROBE_TIMEOUT_MS,
159
+ });
160
+ ingress = ready ? 'ready' : 'unverified';
161
+ }
162
+ }
163
+ return Object.freeze({
164
+ ...plan,
165
+ kind: 'provisioned',
166
+ routingKv: Object.freeze({ ...plan.routingKv, id: routingKv }),
167
+ dispatcher: Object.freeze({ ...plan.dispatcher, bindings }),
168
+ ingress,
169
+ });
170
+ }
171
+ /** Plan one hosting and apply the plan (`planHosting`, then `applyHosting`). */
172
+ export async function provisionHosting(config) {
173
+ return applyHosting(config, await planHosting(config));
174
+ }
175
+ /** Open the routing KV a provisioned hosting reads, as a deployer does. */
176
+ export async function openHostingKv(config) {
177
+ return RoutingKv.open(config.client, config.routingKv ?? { title: await routingKvTitle(config.namespace) });
178
+ }
179
+ async function routingTitle(config) {
180
+ return config.routingKv !== undefined && 'title' in config.routingKv
181
+ ? config.routingKv.title
182
+ : routingKvTitle(config.namespace);
183
+ }
184
+ function observeRouting(config, zone) {
185
+ const input = {
186
+ client: config.client,
187
+ zone,
188
+ routingDomain: config.routingDomain,
189
+ dispatchWorker: config.dispatcher.worker,
190
+ };
191
+ return (config.foreign ?? 'refuse') === 'refuse'
192
+ ? observeDedicatedRouting(input)
193
+ : observeWildcardRouting(input);
194
+ }
195
+ function stateOf(state) {
196
+ return state === 'absent' ? 'create' : state === 'exact' ? 'present' : 'repoint';
197
+ }
198
+ /**
199
+ * Who owns an existing namespace, decided once for the whole namespace rather than script by
200
+ * script. It is this hosting's when its routing KV exists: only provisioning creates it, before
201
+ * the namespace. Its scripts with no `record:<label>` are then deployments not activated yet.
202
+ * Without that KV, any script makes it another data plane's namespace, and it blocks.
203
+ */
204
+ async function namespaceOccupancy(config, routingKvId) {
205
+ const { client, namespace } = config;
206
+ const names = [...(await namespaceScriptNames(client, namespace))].sort();
207
+ if (names.length === 0)
208
+ return { blockers: [], unactivated: [] };
209
+ if (routingKvId === undefined) {
210
+ return {
211
+ blockers: [
212
+ `the namespace ${namespace} holds ${names.length} script(s) and has no routing KV, so it ` +
213
+ `is another data plane's (${named(names)})`,
214
+ ],
215
+ unactivated: [],
216
+ };
217
+ }
218
+ const kv = await RoutingKv.open(client, { id: routingKvId });
219
+ const recorded = new Set((await kv.keys(RECORD_PREFIX)).map((key) => key.slice(RECORD_PREFIX.length)));
220
+ const unrecorded = names.filter((name) => !recorded.has(name));
221
+ const scripts = await mapBounded(unrecorded, CLOUDFLARE_FAN_OUT, (name) => observeScript(client, namespace, name));
222
+ return {
223
+ blockers: [],
224
+ // A script deleted since the listing no longer exists.
225
+ unactivated: unrecorded.flatMap((script, index) => {
226
+ const observed = scripts[index];
227
+ return observed === undefined ? [] : [Object.freeze({ script, tags: observed.tags })];
228
+ }),
229
+ };
230
+ }
231
+ /** The first scripts of a list, as a blocker names them. */
232
+ function named(scripts) {
233
+ return `${scripts.slice(0, NAMED_SCRIPTS).join(', ')}${scripts.length > NAMED_SCRIPTS ? ', …' : ''}`;
234
+ }
235
+ /** Run reads, naming the permission the token lacks when Cloudflare refuses one. */
236
+ async function readable(permission, read) {
237
+ try {
238
+ return await read();
239
+ }
240
+ catch (cause) {
241
+ if (cause instanceof CloudflareApiError && cause.kind === 'unauthorized') {
242
+ throw new HostingRefusal('token-scope', `The API token cannot read ${permission}; provisioning the hosting needs it.`);
243
+ }
244
+ throw cause;
245
+ }
246
+ }
@@ -0,0 +1,82 @@
1
+ import type { CloudflareClient } from '../client.js';
2
+ /** What a zone holds for one routing domain's wildcard ingress, before any change. */
3
+ export interface WildcardRoutingObservation {
4
+ /** `*.<routing domain>` */
5
+ readonly wildcard: string;
6
+ /** `*.<routing domain>/*` */
7
+ readonly pattern: string;
8
+ /** `exact`: the proxied AAAA `100::` record ingress needs; `other`: a record with other content. */
9
+ readonly dns: {
10
+ readonly state: 'absent';
11
+ } | {
12
+ readonly state: 'exact' | 'other';
13
+ readonly id: string;
14
+ };
15
+ /** `exact`: the route already serves the dispatcher; `other`: it serves another Worker or none. */
16
+ readonly route: {
17
+ readonly state: 'absent';
18
+ } | {
19
+ readonly state: 'exact' | 'other';
20
+ readonly id: string;
21
+ readonly script?: string;
22
+ };
23
+ }
24
+ /**
25
+ * What one routing domain's wildcard ingress would take over: `*.<domain>/*` captures every
26
+ * proxied host under the domain that has no more specific route, and the wildcard record answers
27
+ * every name under it that has no record of its own. A domain dedicated to one dispatcher holds
28
+ * nothing else.
29
+ */
30
+ export interface DedicatedRoutingObservation extends WildcardRoutingObservation {
31
+ /**
32
+ * Everything that serves, or could serve, a host at, under or above the routing domain, beside
33
+ * the exact wildcard record and the exact route to this dispatcher: every DNS record at or under
34
+ * the domain (TXT and CAA aside: they carry no traffic, and a wildcard certificate may need
35
+ * them), every wildcard record above it, every Worker route whose pattern matches the domain or a
36
+ * host under it, and every Workers custom domain at or under it.
37
+ */
38
+ readonly occupants: readonly string[];
39
+ }
40
+ /** Read the wildcard DNS record and Worker route of one routing domain, changing nothing. */
41
+ export declare function observeWildcardRouting(input: {
42
+ readonly client: CloudflareClient;
43
+ readonly zone: string;
44
+ readonly routingDomain: string;
45
+ readonly dispatchWorker: string;
46
+ }): Promise<WildcardRoutingObservation>;
47
+ /**
48
+ * Read everything the zone and the account hold at, under or above one routing domain, changing
49
+ * nothing: every DNS record of the zone, every Worker route of the zone and every Workers custom
50
+ * domain of the account.
51
+ */
52
+ export declare function observeDedicatedRouting(input: {
53
+ readonly client: CloudflareClient;
54
+ readonly zone: string;
55
+ readonly routingDomain: string;
56
+ readonly dispatchWorker: string;
57
+ }): Promise<DedicatedRoutingObservation>;
58
+ /**
59
+ * Converge one routing domain's wildcard ingress on its dispatcher, from an observation: a proxied
60
+ * AAAA `100::` record `*.<domain>` and a `*.<domain>/*` route to the dispatcher. A record or route
61
+ * that says otherwise (`other`) is rewritten: callers that must not take over anything refuse
62
+ * before calling this, from `observeDedicatedRouting`'s occupants.
63
+ */
64
+ export declare function applyWildcardRouting(input: {
65
+ readonly client: CloudflareClient;
66
+ readonly zone: string;
67
+ readonly dispatchWorker: string;
68
+ readonly observed: WildcardRoutingObservation;
69
+ /** The comment of the wildcard DNS record: what its routing domain routes. */
70
+ readonly comment: string;
71
+ }): Promise<void>;
72
+ /**
73
+ * The id of the account's zone that holds `domain`: the zone named the domain itself or its
74
+ * closest parent, or undefined when the account has none.
75
+ */
76
+ export declare function findZone(client: CloudflareClient, domain: string): Promise<string | undefined>;
77
+ /**
78
+ * Whether a Worker route pattern matches the routing domain or a host under it, at any depth. A
79
+ * pattern's host is exact, `*.<suffix>` (every name under the suffix) or `*<suffix>` (every name
80
+ * ending with the suffix, the suffix itself included).
81
+ */
82
+ export declare function routeReaches(pattern: string, domain: string): boolean;