@astrale-os/adapter-cloudflare 0.5.0-beta.20 → 0.5.0-beta.200

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 +245 -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 +38 -0
  59. package/dist/hosting/activation.js +109 -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 +50 -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 +70 -0
  108. package/dist/hosting/retirement.js +107 -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 +389 -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 +39 -12
  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,10 @@
1
+ import type { BuildDigest } from '@astrale-os/sdk/deployment/build/manifest';
2
+ import type { CloudflareAdapterBindings } from './front.js';
3
+ /**
4
+ * Plain binding an immutable-deployment host (Services, the platform namespace) binds at the
5
+ * create-only upload: the build digest it recomputed from the uploaded bytes. No stable Worker
6
+ * receives it, and no author var or secret may take its name.
7
+ */
8
+ export declare const BUILD_DIGEST_BINDING = "ASTRALE_BUILD_DIGEST";
9
+ /** The exact host-bound build digest this immutable deployment serves. */
10
+ export declare function deploymentBuildDigest(bindings: CloudflareAdapterBindings): BuildDigest;
@@ -0,0 +1,22 @@
1
+ import { acceptBuildDigest } from '@astrale-os/sdk/deployment/build/manifest';
2
+ /**
3
+ * Plain binding an immutable-deployment host (Services, the platform namespace) binds at the
4
+ * create-only upload: the build digest it recomputed from the uploaded bytes. No stable Worker
5
+ * receives it, and no author var or secret may take its name.
6
+ */
7
+ export const BUILD_DIGEST_BINDING = 'ASTRALE_BUILD_DIGEST';
8
+ /** The exact host-bound build digest this immutable deployment serves. */
9
+ export function deploymentBuildDigest(bindings) {
10
+ const bound = bindings.ASTRALE_BUILD_DIGEST;
11
+ let digest;
12
+ try {
13
+ digest = acceptBuildDigest(bound);
14
+ }
15
+ catch (cause) {
16
+ throw new TypeError(`Cloudflare Worker ${BUILD_DIGEST_BINDING} binding is invalid.`, { cause });
17
+ }
18
+ if (bindings.WORKER_URL === undefined) {
19
+ throw new TypeError(`Cloudflare Worker ${BUILD_DIGEST_BINDING} requires the deployment URL bound as WORKER_URL.`);
20
+ }
21
+ return digest;
22
+ }
@@ -0,0 +1,28 @@
1
+ import type { DeploymentCache } from '@astrale-os/sdk/execution';
2
+ /**
3
+ * The Cache API cache a deployment keeps its entries in. Cloudflare isolates the Cache API of each
4
+ * Worker script, and so of each immutable deployment: no other deployment reads these entries.
5
+ */
6
+ export declare const DEPLOYMENT_CACHE_NAME = "astrale-deployment";
7
+ /** The part of the Cache API a deployment cache uses. */
8
+ export interface CacheApiStorage {
9
+ open(cacheName: string): Promise<CacheApiCache>;
10
+ }
11
+ export interface CacheApiCache {
12
+ match(request: string): Promise<Response | undefined>;
13
+ put(request: string, response: Response): Promise<void>;
14
+ }
15
+ export interface CloudflareCacheOptions {
16
+ /** The Cache API; defaults to the isolate's `caches`, and to none where the isolate has none. */
17
+ readonly caches?: CacheApiStorage;
18
+ /** The in-isolate tier read first; defaults to a bounded memory cache. */
19
+ readonly memory?: DeploymentCache;
20
+ }
21
+ /**
22
+ * A deployment cache shared by every isolate of one deployment in a data center: the Cache API,
23
+ * behind a bounded in-isolate memory tier read first. The Cache API keeps an entry for its whole
24
+ * remaining seconds at most, so an entry with less than one second left is kept in memory only.
25
+ * The cache is opened per operation and nothing pending is shared, because a Worker binds I/O to
26
+ * the request that started it.
27
+ */
28
+ export declare function cloudflareCache(options?: CloudflareCacheOptions): DeploymentCache;
@@ -0,0 +1,70 @@
1
+ import { memoryCache } from '@astrale-os/sdk/execution';
2
+ /**
3
+ * The Cache API cache a deployment keeps its entries in. Cloudflare isolates the Cache API of each
4
+ * Worker script, and so of each immutable deployment: no other deployment reads these entries.
5
+ */
6
+ export const DEPLOYMENT_CACHE_NAME = 'astrale-deployment';
7
+ /** Origin of the synthetic URLs that name entries; they are never fetched. */
8
+ const ENTRY_ORIGIN = 'https://deployment-cache.astrale.invalid/';
9
+ /** Absolute expiry of an entry, in Unix milliseconds, carried beside its value. */
10
+ const EXPIRES_AT = 'x-astrale-expires-at';
11
+ /**
12
+ * A deployment cache shared by every isolate of one deployment in a data center: the Cache API,
13
+ * behind a bounded in-isolate memory tier read first. The Cache API keeps an entry for its whole
14
+ * remaining seconds at most, so an entry with less than one second left is kept in memory only.
15
+ * The cache is opened per operation and nothing pending is shared, because a Worker binds I/O to
16
+ * the request that started it.
17
+ */
18
+ export function cloudflareCache(options = {}) {
19
+ if (options === null || typeof options !== 'object' || Array.isArray(options))
20
+ invalid();
21
+ const memory = options.memory ?? memoryCache();
22
+ const storage = options.caches ?? isolateCaches();
23
+ return Object.freeze({
24
+ async get(key) {
25
+ const near = await memory.get(key);
26
+ if (near !== undefined || storage === undefined)
27
+ return near;
28
+ const response = await (await storage.open(DEPLOYMENT_CACHE_NAME)).match(entryUrl(key));
29
+ if (response === undefined)
30
+ return undefined;
31
+ const value = await response.text();
32
+ const expiresAt = Number(response.headers.get(EXPIRES_AT));
33
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now())
34
+ return undefined;
35
+ await memory.put(key, value, expiresAt);
36
+ return value;
37
+ },
38
+ async put(key, value, expiresAt) {
39
+ await memory.put(key, value, expiresAt);
40
+ if (storage === undefined || !Number.isSafeInteger(expiresAt))
41
+ return;
42
+ const seconds = Math.floor((expiresAt - Date.now()) / 1000);
43
+ if (seconds < 1)
44
+ return;
45
+ await (await storage.open(DEPLOYMENT_CACHE_NAME)).put(entryUrl(key), new Response(value, {
46
+ headers: {
47
+ 'cache-control': `max-age=${seconds}`,
48
+ 'content-type': 'text/plain; charset=utf-8',
49
+ [EXPIRES_AT]: String(expiresAt),
50
+ },
51
+ }));
52
+ },
53
+ });
54
+ }
55
+ function entryUrl(key) {
56
+ if (typeof key !== 'string')
57
+ invalid();
58
+ return `${ENTRY_ORIGIN}${encodeURIComponent(key)}`;
59
+ }
60
+ function isolateCaches() {
61
+ const caches = Reflect.get(globalThis, 'caches');
62
+ return caches !== null &&
63
+ typeof caches === 'object' &&
64
+ typeof Reflect.get(caches, 'open') === 'function'
65
+ ? caches
66
+ : undefined;
67
+ }
68
+ function invalid() {
69
+ throw new TypeError('Cloudflare cache input is invalid.');
70
+ }
@@ -0,0 +1,3 @@
1
+ import type { DurableEngine, DurableServing } from '@astrale-os/sdk/execution';
2
+ /** Canonical callbacks discover engine authority from the Kernel named in their route. */
3
+ export declare function restateServing(engine: DurableEngine, request: Request, options?: Pick<DurableServing, 'retentionMs' | 'retry' | 'stepTimeoutMs'>): DurableServing | undefined;
@@ -0,0 +1,5 @@
1
+ import { isCanonicalDurableRequest } from '@astrale-os/sdk/execution';
2
+ /** Canonical callbacks discover engine authority from the Kernel named in their route. */
3
+ export function restateServing(engine, request, options = {}) {
4
+ return isCanonicalDurableRequest(request) ? Object.freeze({ ...options, engine }) : undefined;
5
+ }
@@ -1,34 +1,47 @@
1
1
  import type { JsonWebKey } from '@astrale-os/sdk/auth';
2
- import type { BuildMaterial } from '@astrale-os/sdk/deployment/build/material';
3
- import type { ExecutionContext } from '@astrale-os/sdk/execution';
2
+ import type { BuildMaterial, GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build/material';
3
+ import type { DurableServingProvider, ExecutionContext } from '@astrale-os/sdk/execution';
4
4
  import type { Runtime } from '@astrale-os/sdk/runtime';
5
- export interface Fetcher {
6
- fetch(request: Request): Response | Promise<Response>;
7
- }
8
- export interface CloudflareAdapterBindings {
9
- readonly ASTRALE_SIGNING_IDENTITY?: string;
10
- readonly WORKER_URL?: string;
11
- readonly IDENTITY_ISS?: string;
12
- readonly ASSETS?: Fetcher;
13
- readonly SELF?: Fetcher;
14
- readonly FRONTEND_DEV_URL?: string;
15
- readonly DISPATCHER?: {
16
- get(name: string): Fetcher;
17
- };
18
- }
19
- export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings extends CloudflareAdapterBindings, Environment> {
20
- readonly runtime: RuntimeValue;
21
- readonly material: BuildMaterial;
5
+ import type { DurableWorkerOptions } from '../params.js';
6
+ import type { CloudflareAdapterBindings, CloudflareFrontDoorConfig, Fetcher } from './front.js';
7
+ import type { CloudflareWorkerSettings } from './settings.js';
8
+ export type { CloudflareAdapterBindings, Fetcher } from './front.js';
9
+ export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings extends CloudflareAdapterBindings, Environment, Material = BuildMaterial> extends CloudflareFrontDoorConfig, CloudflareWorkerSettings<Bindings> {
10
+ /**
11
+ * Load the exact local Runtime and Build once per entrypoint, after the isolate has accepted a
12
+ * request or execution is prepared. Concurrent callers share the result, including a rejection;
13
+ * later calls do not retry loading. A new entrypoint has an independent load. Keep recoverable
14
+ * remote preparation in its own lifecycle rather than this deterministic module loader.
15
+ */
16
+ readonly load: () => CloudflareWorkerSource<RuntimeValue, Material> | Promise<CloudflareWorkerSource<RuntimeValue, Material>>;
22
17
  readonly privateKey: JsonWebKey | ((bindings: Bindings) => JsonWebKey);
23
18
  readonly resolveEnvironment?: (bindings: Bindings) => Environment;
24
- readonly resolveUrl?: (bindings: Bindings, requestOrigin: string) => string;
25
- readonly providerAssignedWorker?: string;
26
19
  readonly selfBinding?: (bindings: Bindings) => Fetcher | null | undefined;
27
- readonly routeSubrequest?: (url: URL, bindings: Bindings) => Fetcher | null | undefined;
28
- readonly invocationTimeoutMs?: number;
20
+ /**
21
+ * Read the execution settings from the deployment's bindings on the isolate's first execution
22
+ * request, as generated Workers do with `deploymentSettings`. A hand-composed Worker states
23
+ * them in this configuration instead; one Worker never takes both.
24
+ */
25
+ readonly settings?: (bindings: Bindings) => CloudflareWorkerSettings<Bindings>;
26
+ /**
27
+ * The deployment cache, which keeps the admissions of callables that declare an admission age:
28
+ * by default the Cache API behind an in-isolate memory tier. `false` keeps nothing, and every
29
+ * call is admitted by its source Kernel.
30
+ */
31
+ readonly cache?: false;
32
+ /** Resolve the engine for this durable request with the deployment's captured options. */
33
+ readonly durable?: (bindings: Bindings, request: Request, options?: DurableWorkerOptions) => ReturnType<DurableServingProvider>;
34
+ }
35
+ export interface CloudflareWorkerSource<RuntimeValue extends Runtime, Material = BuildMaterial> {
36
+ readonly runtime: RuntimeValue;
37
+ readonly material: Material;
29
38
  }
30
39
  export interface CloudflareWorker<Bindings> {
31
40
  fetch(request: Request, environment: Bindings, executionContext?: ExecutionContext): Response | Promise<Response>;
41
+ /** Realize execution ahead of the request that needs it; failures resurface on that request. */
42
+ prepare?(): Promise<void>;
32
43
  }
33
- /** Compose one exact revision Service; the provider gateway owns revision selection. */
34
- export declare function cloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment>) => CloudflareWorker<Bindings>;
44
+ /** Compose one installed Domain implementation at its immutable deployment URL. */
45
+ export declare function cloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, BuildMaterial>) => CloudflareWorker<Bindings>;
46
+ /** Compose generated execution code whose exact Build material carries build-owner evidence. */
47
+ export declare function generatedCloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, GeneratedBuildMaterial>) => CloudflareWorker<Bindings>;
@@ -1,157 +1,135 @@
1
1
  import { issuer } from '@astrale-os/sdk/auth';
2
- import { restoreBuild } from '@astrale-os/sdk/deployment/build/material';
3
- import { addressing, assemble } from '@astrale-os/sdk/deployment/release/runtime';
2
+ import { restoreBuild, restoreGeneratedBuild } from '@astrale-os/sdk/deployment/build/material';
3
+ import { assemble } from '@astrale-os/sdk/deployment/release/runtime';
4
4
  import { createIdentity, serve } from '@astrale-os/sdk/execution';
5
+ import { binaryRequestLimits } from './binary.js';
6
+ import { deploymentBuildDigest } from './build-digest.js';
7
+ import { cloudflareCache } from './cache.js';
5
8
  import { dispatchCloudflareRequest, prepareCloudflareRequest } from './fetch.js';
6
- /** Compose one exact revision Service; the provider gateway owns revision selection. */
9
+ import { cloudflareFrontDoor, withProviderVersion } from './front.js';
10
+ import { frontendAsset } from './frontend.js';
11
+ import { DEFAULT_INVOCATION_TIMEOUT_MS, DEFAULT_MAXIMUM_REQUEST_BYTES } from './settings.js';
12
+ /** Compose one installed Domain implementation at its immutable deployment URL. */
7
13
  export function cloudflareWorkerEntry() {
14
+ return createCloudflareWorkerEntry(restoreBuild);
15
+ }
16
+ /** Compose generated execution code whose exact Build material carries build-owner evidence. */
17
+ export function generatedCloudflareWorkerEntry() {
18
+ return createCloudflareWorkerEntry(restoreGeneratedBuild);
19
+ }
20
+ /** The static settings a hand-composed Worker may state instead of reading its bindings. */
21
+ const SETTINGS = [
22
+ 'routeSubrequest',
23
+ 'invocationTimeoutMs',
24
+ 'maximumRequestBytes',
25
+ 'tokenExchange',
26
+ 'durableOptions',
27
+ ];
28
+ function createCloudflareWorkerEntry(restore) {
8
29
  return function (config) {
9
- let currentIssuer;
10
- let realized;
11
- const realize = () => {
12
- if (realized !== undefined)
13
- return realized;
14
- const build = restoreBuild(config.material, config.runtime);
15
- const application = serve({
16
- runtime: config.runtime,
30
+ if (config.settings !== undefined && SETTINGS.some((key) => config[key] !== undefined)) {
31
+ throw new TypeError('Cloudflare Worker settings come from its deployment bindings or its configuration, not both.');
32
+ }
33
+ const frontDoor = cloudflareFrontDoor(config);
34
+ let restored;
35
+ let application;
36
+ const realize = () => (restored ??= Promise.resolve()
37
+ .then(config.load)
38
+ .then((source) => Object.freeze({
39
+ runtime: source.runtime,
40
+ build: restore(source.material, source.runtime),
41
+ })));
42
+ // Settings and the build digest are a deployment's, so they are read from the first execution
43
+ // request's bindings.
44
+ const served = (source, bindings) => {
45
+ if (application !== undefined)
46
+ return application;
47
+ const { build } = source;
48
+ const settings = config.settings === undefined ? config : config.settings(bindings);
49
+ const buildDigest = deploymentBuildDigest(bindings);
50
+ const invocationTimeoutMs = settings.invocationTimeoutMs ?? DEFAULT_INVOCATION_TIMEOUT_MS;
51
+ const created = serve({
52
+ runtime: source.runtime,
17
53
  load(environment) {
18
- if (currentIssuer !== environment.issuer) {
54
+ if (frontDoor.current() !== environment.publicUrl) {
19
55
  throw new TypeError('Cloudflare Worker request origin differs from its current Release.');
20
56
  }
21
- return assemble(build, addressing(environment.issuer));
57
+ return assemble(build, buildDigest, environment.publicUrl);
22
58
  },
23
59
  initialize: (environment) => config.resolveEnvironment === undefined
24
60
  ? environment.bindings
25
61
  : config.resolveEnvironment(environment.bindings),
26
62
  identity(environment) {
27
63
  return createIdentity({
28
- issuer: issuer.accept(environment.issuer),
64
+ issuer: issuer.accept(environment.publicUrl),
29
65
  subject: build.schema.compiled.root.origin,
30
66
  privateKey: typeof config.privateKey === 'function'
31
67
  ? config.privateKey(environment.bindings)
32
68
  : config.privateKey,
33
- fetch: routedFetch(application, environment, config),
34
- ...(new URL(environment.issuer).protocol === 'http:'
69
+ fetch: routedFetch(created, environment, config.selfBinding, settings.routeSubrequest),
70
+ ...(new URL(environment.publicUrl).protocol === 'http:'
35
71
  ? { allowInsecureHttp: true }
36
72
  : {}),
73
+ ...(settings.tokenExchange === undefined
74
+ ? {}
75
+ : { tokenExchange: settings.tokenExchange }),
37
76
  });
38
77
  },
78
+ cache: config.cache === false ? false : () => cloudflareCache(),
79
+ ...(config.durable === undefined
80
+ ? {}
81
+ : {
82
+ durable: (environment, request) => config.durable(environment.bindings, request, settings.durableOptions),
83
+ }),
39
84
  server: {
40
85
  health: { probe: { check: () => true } },
41
86
  limits: {
42
- maximumRequestBytes: 1024 * 1024,
43
- maximumPublicationBytes: 1024 * 1024,
87
+ maximumRequestBytes: settings.maximumRequestBytes ?? DEFAULT_MAXIMUM_REQUEST_BYTES,
88
+ maximumReleaseBytes: 1024 * 1024,
44
89
  maximumBundleBytes: 8 * 1024 * 1024,
45
90
  maximumDeliveryBytes: 8 * 1024 * 1024,
46
- invocationTimeoutMs: config.invocationTimeoutMs ?? 30_000,
91
+ invocationTimeoutMs,
92
+ // Streamed binary bodies are never buffered, so their cap follows the Domain's binary
93
+ // Functions instead of maximumRequestBytes.
94
+ ...binaryRequestLimits(build, invocationTimeoutMs),
47
95
  },
48
96
  },
49
97
  });
50
- realized = Object.freeze({ build, application });
51
- return realized;
98
+ application = created;
99
+ return created;
52
100
  };
53
101
  return Object.freeze({
54
102
  async fetch(request, bindings, context) {
55
- const url = new URL(request.url);
56
- const issuer = canonicalServingUrl(bindings.WORKER_URL ??
57
- bindings.IDENTITY_ISS ??
58
- config.resolveUrl?.(bindings, requestOrigin(url, request)) ??
59
- requestOrigin(url, request));
60
- if (config.providerAssignedWorker !== undefined &&
61
- bindings.WORKER_URL === undefined &&
62
- bindings.IDENTITY_ISS === undefined &&
63
- !matchesWorkersDevClaim(issuer, config.providerAssignedWorker)) {
64
- return new Response('Request origin differs from provider-assigned Addressing.', {
65
- status: 421,
66
- });
67
- }
68
- if (currentIssuer !== undefined && currentIssuer !== issuer) {
69
- return new Response('Request origin differs from the current Release.', { status: 421 });
103
+ const admission = await frontDoor.admit(request, bindings);
104
+ if (admission.kind !== 'execution')
105
+ return admission.response;
106
+ const { url, publicUrl } = admission;
107
+ const source = await realize();
108
+ if (config.frontend === undefined) {
109
+ const frontend = await frontendAsset(source.build.frontend, bindings.ASSETS, url, request, config.frontendRevision, config.frontendAddressed);
110
+ if (frontend !== undefined)
111
+ return withProviderVersion(frontend, bindings);
70
112
  }
71
- currentIssuer = issuer;
72
- const { application, build } = realize();
73
- const frontend = await frontendAsset(build.frontend, bindings, url, request);
74
- if (frontend !== undefined)
75
- return frontend;
76
- return application.fetch(request, Object.freeze({ bindings, issuer }), context);
113
+ const response = await served(source, bindings).fetch(request, Object.freeze({ bindings, publicUrl }), context);
114
+ return withProviderVersion(response, bindings);
115
+ },
116
+ async prepare() {
117
+ await realize();
77
118
  },
78
119
  });
79
120
  };
80
121
  }
81
- function routedFetch(application, environment, config) {
122
+ function routedFetch(application, environment, selfBinding, routeSubrequest) {
82
123
  return async (input, init) => {
83
124
  const { request, rejectRedirect } = prepareCloudflareRequest(input, init);
84
125
  const destination = new URL(request.url);
85
- if (destination.origin === environment.issuer) {
86
- const self = config.selfBinding?.(environment.bindings);
126
+ if (destination.origin === environment.publicUrl) {
127
+ const self = selfBinding?.(environment.bindings);
87
128
  return dispatchCloudflareRequest(request, rejectRedirect, (selected) => self === null || self === undefined
88
129
  ? application.fetch(selected, environment)
89
130
  : self.fetch(selected));
90
131
  }
91
- const route = config.routeSubrequest?.(destination, environment.bindings);
132
+ const route = routeSubrequest?.(destination, environment.bindings);
92
133
  return dispatchCloudflareRequest(request, rejectRedirect, (selected) => route === null || route === undefined ? fetch(selected) : route.fetch(selected));
93
134
  };
94
135
  }
95
- async function frontendAsset(frontend, environment, url, request) {
96
- if (frontend === undefined || frontend.source.kind === 'external')
97
- return undefined;
98
- if (reserved(url.pathname) || (request.method !== 'GET' && request.method !== 'HEAD')) {
99
- return undefined;
100
- }
101
- const development = environment.FRONTEND_DEV_URL?.replace(/\/+$/u, '');
102
- if (development !== undefined && development.length > 0) {
103
- return fetch(new Request(new URL(`${url.pathname}${url.search}`, `${development}/`), request));
104
- }
105
- const route = frontend.routes
106
- .filter((candidate) => candidate.path === url.pathname ||
107
- (frontend.source.kind === 'vite' &&
108
- frontend.source.spa &&
109
- (candidate.path === '/' || url.pathname.startsWith(`${candidate.path}/`))))
110
- .sort((left, right) => right.path.length - left.path.length)[0];
111
- if (route === undefined && !url.pathname.startsWith('/assets/'))
112
- return undefined;
113
- const assets = environment.ASSETS;
114
- if (assets === undefined)
115
- return undefined;
116
- const response = await assets.fetch(request);
117
- if (response.status !== 404 || route === undefined)
118
- return response;
119
- await response.body?.cancel();
120
- return assets.fetch(new Request(new URL(`/${route.document}${url.search}`, url.origin), request));
121
- }
122
- function reserved(path) {
123
- return ['/releases', '/install', '/health', '/meta', '/.well-known'].some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
124
- }
125
- function requestOrigin(url, request) {
126
- if (url.protocol !== 'http:')
127
- return url.origin;
128
- const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase();
129
- return forwarded === 'https' ? `https://${url.host}` : url.origin;
130
- }
131
- function canonicalServingUrl(input) {
132
- let url;
133
- try {
134
- url = new URL(input);
135
- }
136
- catch (cause) {
137
- throw new TypeError('Cloudflare Worker serving URL is invalid.', { cause });
138
- }
139
- if ((url.protocol !== 'https:' && url.protocol !== 'http:') ||
140
- url.username !== '' ||
141
- url.password !== '' ||
142
- url.pathname !== '/' ||
143
- url.search !== '' ||
144
- url.hash !== '') {
145
- throw new TypeError('Cloudflare Worker serving URL must be one HTTP(S) origin.');
146
- }
147
- return url.origin;
148
- }
149
- function matchesWorkersDevClaim(issuer, expectedWorker) {
150
- const url = new URL(issuer);
151
- const labels = url.hostname.split('.');
152
- return (url.protocol === 'https:' &&
153
- labels.length >= 4 &&
154
- labels[0] === expectedWorker &&
155
- labels.at(-2) === 'workers' &&
156
- labels.at(-1) === 'dev');
157
- }
@@ -0,0 +1,56 @@
1
+ import type { BuildMaterial } from '@astrale-os/sdk/deployment/build/material';
2
+ export type { CloudflareWorker } from './entry.js';
3
+ export interface Fetcher {
4
+ fetch(request: Request): Response | Promise<Response>;
5
+ }
6
+ /** Bindings the adapter owns; a deployment's host binds them beside the author's own. */
7
+ export interface CloudflareAdapterBindings {
8
+ readonly ASTRALE_SIGNING_IDENTITY?: string;
9
+ readonly ASTRALE_VERSION_METADATA?: {
10
+ readonly id: string;
11
+ };
12
+ /** Serving origin of this deployment. */
13
+ readonly WORKER_URL: string;
14
+ /**
15
+ * Build digest an immutable-deployment host recomputed from the uploaded bytes. Bound, the Worker
16
+ * serves the DomainRelease v4 of its code at release.json.
17
+ */
18
+ readonly ASTRALE_BUILD_DIGEST: string;
19
+ /** Execution settings of this deployment, as canonical JSON (see `deploymentSettings`). */
20
+ readonly ASTRALE_SETTINGS?: string;
21
+ readonly ASSETS?: Fetcher;
22
+ readonly SELF?: Fetcher;
23
+ }
24
+ export interface CloudflareFrontDoorConfig {
25
+ /** Generated frontend evidence available without restoring the execution Build. */
26
+ readonly frontend?: BuildMaterial['frontend'];
27
+ /** Generated browser-file identity used only for deployment propagation checks. */
28
+ readonly frontendRevision?: string;
29
+ /** Served frontend paths the bundler content-addressed; absent means none may be retained. */
30
+ readonly frontendAddressed?: readonly string[];
31
+ }
32
+ export type CloudflareFrontDoorAdmission =
33
+ /** The request is not for this isolate's serving origin. */
34
+ {
35
+ readonly kind: 'refused';
36
+ readonly response: Response;
37
+ }
38
+ /** A public frontend file answered the request without the execution Service. */
39
+ | {
40
+ readonly kind: 'frontend';
41
+ readonly response: Response;
42
+ }
43
+ /** The request needs the execution Service, under this isolate's one serving origin. */
44
+ | {
45
+ readonly kind: 'execution';
46
+ readonly url: URL;
47
+ readonly publicUrl: string;
48
+ };
49
+ export interface CloudflareFrontDoor<Bindings extends CloudflareAdapterBindings> {
50
+ admit(request: Request, bindings: Bindings): Promise<CloudflareFrontDoorAdmission>;
51
+ /** The serving origin this isolate pinned on its first admitted request. */
52
+ current(): string | undefined;
53
+ }
54
+ /** Admit requests to one serving origin and answer public frontend files, per isolate. */
55
+ export declare function cloudflareFrontDoor<Bindings extends CloudflareAdapterBindings>(config: CloudflareFrontDoorConfig): CloudflareFrontDoor<Bindings>;
56
+ export declare function withProviderVersion(response: Response, bindings: CloudflareAdapterBindings): Response;
@@ -0,0 +1,59 @@
1
+ import { frontendAsset } from './frontend.js';
2
+ /** Admit requests to one serving origin and answer public frontend files, per isolate. */
3
+ export function cloudflareFrontDoor(config) {
4
+ let currentPublicUrl;
5
+ return Object.freeze({
6
+ async admit(request, bindings) {
7
+ const url = new URL(request.url);
8
+ const publicUrl = canonicalServingUrl(bindings.WORKER_URL);
9
+ if (requestOrigin(url, request) !== publicUrl)
10
+ return refused('Request origin differs from this deployment URL.');
11
+ if (currentPublicUrl !== undefined && currentPublicUrl !== publicUrl) {
12
+ return refused('Request origin differs from the current Release.');
13
+ }
14
+ currentPublicUrl = publicUrl;
15
+ if (config.frontend !== undefined) {
16
+ const frontend = await frontendAsset(config.frontend, bindings.ASSETS, url, request, config.frontendRevision, config.frontendAddressed);
17
+ if (frontend !== undefined) {
18
+ return { kind: 'frontend', response: withProviderVersion(frontend, bindings) };
19
+ }
20
+ }
21
+ return { kind: 'execution', url, publicUrl };
22
+ },
23
+ current: () => currentPublicUrl,
24
+ });
25
+ }
26
+ export function withProviderVersion(response, bindings) {
27
+ if (bindings.ASTRALE_VERSION_METADATA === undefined)
28
+ return response;
29
+ const versioned = new Response(response.body, response);
30
+ versioned.headers.set('X-Astrale-Worker-Version', bindings.ASTRALE_VERSION_METADATA.id);
31
+ return versioned;
32
+ }
33
+ function refused(message) {
34
+ return { kind: 'refused', response: new Response(message, { status: 421 }) };
35
+ }
36
+ function requestOrigin(url, request) {
37
+ if (url.protocol !== 'http:')
38
+ return url.origin;
39
+ const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase();
40
+ return forwarded === 'https' ? `https://${url.host}` : url.origin;
41
+ }
42
+ function canonicalServingUrl(input) {
43
+ let url;
44
+ try {
45
+ url = new URL(input);
46
+ }
47
+ catch (cause) {
48
+ throw new TypeError('Cloudflare Worker serving URL is invalid.', { cause });
49
+ }
50
+ if ((url.protocol !== 'https:' && url.protocol !== 'http:') ||
51
+ url.username !== '' ||
52
+ url.password !== '' ||
53
+ url.pathname !== '/' ||
54
+ url.search !== '' ||
55
+ url.hash !== '') {
56
+ throw new TypeError('Cloudflare Worker serving URL must be one HTTP(S) origin.');
57
+ }
58
+ return url.origin;
59
+ }
@@ -0,0 +1,4 @@
1
+ import type { BuildMaterial } from '@astrale-os/sdk/deployment/build/material';
2
+ import type { Fetcher } from './front.js';
3
+ /** Serve public frontend files without realizing the Domain's execution Runtime. */
4
+ export declare function frontendAsset(frontend: BuildMaterial['frontend'], assets: Fetcher | undefined, url: URL, request: Request, revision?: string, addressed?: readonly string[]): Promise<Response | undefined>;