@astrale-os/adapter-cloudflare 0.5.0-beta.23 → 0.5.0-beta.231

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 +258 -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 +23 -0
  9. package/dist/build/bundler.js +103 -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 +56 -0
  48. package/dist/build/worker/execution.prepare.d.ts +22 -0
  49. package/dist/build/worker/execution.prepare.js +131 -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 +153 -0
  67. package/dist/hosting/client.js +516 -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 +106 -0
  88. package/dist/hosting/kv.js +235 -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 +79 -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 +25 -0
  118. package/dist/hosting/time.js +48 -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 +387 -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 +32 -0
  138. package/dist/namespace/readiness.js +35 -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 +18 -0
  169. package/dist/wrangler/bundle.js +36 -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,55 @@
1
+ // RFC 9110 §5.6.7: a recipient accepts all three HTTP-date forms, each case-sensitive and in GMT.
2
+ const HTTP_DATES = [
3
+ // IMF-fixdate: Sun, 06 Nov 1994 08:49:37 GMT
4
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?<day>\d{2}) (?<month>[A-Z][a-z]{2}) (?<year>\d{4}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) GMT$/u,
5
+ // Obsolete RFC 850 form: Sunday, 06-Nov-94 08:49:37 GMT
6
+ /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?<day>\d{2})-(?<month>[A-Z][a-z]{2})-(?<year>\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) GMT$/u,
7
+ // Obsolete asctime form: Sun Nov 6 08:49:37 1994
8
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?<month>[A-Z][a-z]{2}) (?<day>\d{2}| \d) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) (?<year>\d{4})$/u,
9
+ ];
10
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
11
+ /**
12
+ * The wait an RFC 9110 `Retry-After` states, in milliseconds: delay seconds or an HTTP-date in any
13
+ * of its three forms, as of `now`. Anything else states no wait (undefined). Delay seconds too
14
+ * large to count in milliseconds state an unbounded wait, which no policy admits.
15
+ */
16
+ export function retryAfterMs(value, now) {
17
+ if (value === null)
18
+ return undefined;
19
+ const text = value.trim();
20
+ if (/^\d+$/u.test(text)) {
21
+ const waitMs = Number(text) * 1_000;
22
+ return Number.isSafeInteger(waitMs) ? waitMs : Number.POSITIVE_INFINITY;
23
+ }
24
+ const at = httpDate(text, now);
25
+ return at === undefined ? undefined : Math.max(0, at - now);
26
+ }
27
+ /** The instant an RFC 9110 HTTP-date names, or undefined when the text is not a real one. */
28
+ function httpDate(text, now) {
29
+ const fields = HTTP_DATES.map((form) => form.exec(text)?.groups).find(Boolean);
30
+ if (fields === undefined)
31
+ return undefined;
32
+ const month = MONTHS.indexOf(fields.month);
33
+ const day = Number(fields.day);
34
+ const [hour, minute, second] = [fields.hour, fields.minute, fields.second].map(Number);
35
+ if (month < 0 || hour > 23 || minute > 59 || second > 60)
36
+ return undefined;
37
+ const year = fields.year.length === 2 ? rfc850Year(Number(fields.year), now) : Number(fields.year);
38
+ // setUTCFullYear keeps years below 100 literal, which Date.UTC would move to the 1900s.
39
+ const date = new Date(0);
40
+ date.setUTCFullYear(year, month, day);
41
+ if (date.getUTCDate() !== day)
42
+ return undefined;
43
+ return date.getTime() + ((hour * 60 + minute) * 60 + second) * 1_000;
44
+ }
45
+ /**
46
+ * RFC 9110 §5.6.7: a two-digit year that would be more than 50 years ahead names the most recent
47
+ * past year with those last two digits.
48
+ */
49
+ function rfc850Year(lastTwoDigits, now) {
50
+ const current = new Date(now).getUTCFullYear();
51
+ const year = current - (current % 100) + lastTwoDigits;
52
+ if (year > current + 50)
53
+ return year - 100;
54
+ return year <= current - 50 ? year + 100 : year;
55
+ }
@@ -0,0 +1,186 @@
1
+ import type { CloudflareClient } from './client.js';
2
+ import { SIGNING_IDENTITY_BINDING } from '../identity/binding.js';
3
+ import { BUILD_DIGEST_BINDING } from '../worker/build-digest.js';
4
+ import { SETTINGS_BINDING } from '../worker/settings.js';
5
+ import { type ScriptAsset } from './assets.js';
6
+ /** The deployment URL, which is also its issuer. */
7
+ export declare const WORKER_URL_BINDING = "WORKER_URL";
8
+ /** The binding a deployment's Worker reads its provider version from, for readiness. */
9
+ export declare const VERSION_METADATA_BINDING = "ASTRALE_VERSION_METADATA";
10
+ /** The service binding through which a deployment reaches an instance router. */
11
+ export declare const ROUTER_BINDING = "ROUTER";
12
+ /** The binding of a deployment's static assets, when its build has a frontend. */
13
+ export declare const ASSETS_BINDING = "ASSETS";
14
+ /** The secret the generated Worker reads its private signing JWK from (`ASTRALE_SIGNING_IDENTITY`). */
15
+ export { BUILD_DIGEST_BINDING, SETTINGS_BINDING, SIGNING_IDENTITY_BINDING };
16
+ /** The build a script runs: `astrale-artifact:<hex digest of its build manifest>`. */
17
+ export declare const ARTIFACT_TAG_PREFIX = "astrale-artifact:";
18
+ /** The deployment line a script is a version of: `astrale-line:<line>`. */
19
+ export declare const LINE_TAG_PREFIX = "astrale-line:";
20
+ /** The signing key a script binds: `astrale-key:<RFC 7638 thumbprint>`. */
21
+ export declare const KEY_TAG_PREFIX = "astrale-key:";
22
+ /** The multipart type of each Worker module kind, as the Workers upload API reads it. */
23
+ declare const MODULE_PART_TYPES: Readonly<{
24
+ esm: "application/javascript+module";
25
+ wasm: "application/wasm";
26
+ text: "text/plain";
27
+ data: "application/octet-stream";
28
+ }>;
29
+ /** One module of a script upload. */
30
+ export interface ScriptModule {
31
+ readonly name: string;
32
+ readonly kind: keyof typeof MODULE_PART_TYPES;
33
+ readonly bytes: Uint8Array;
34
+ }
35
+ /** One binding of a script upload, as Cloudflare's upload metadata names it. */
36
+ export type ScriptBinding = {
37
+ readonly type: 'plain_text';
38
+ readonly name: string;
39
+ readonly text: string;
40
+ } | {
41
+ readonly type: 'secret_text';
42
+ readonly name: string;
43
+ readonly text: string;
44
+ } | {
45
+ readonly type: 'service';
46
+ readonly name: string;
47
+ readonly service: string;
48
+ } | {
49
+ readonly type: 'dispatch_namespace';
50
+ readonly name: string;
51
+ readonly namespace: string;
52
+ } | {
53
+ readonly type: 'version_metadata';
54
+ readonly name: string;
55
+ } | {
56
+ readonly type: 'assets';
57
+ readonly name: string;
58
+ };
59
+ /**
60
+ * What identifies one namespace script at the provider: its code hash (`etag`), its tags (the
61
+ * kit's `astrale-artifact:`, `astrale-line:` and `astrale-key:` decoded, every tag kept), and when
62
+ * Cloudflare created it. `version` is the provider version serving now (`deployment_id`), read
63
+ * only to check readiness: a secret written in place mints a new one, so nothing keeps it.
64
+ */
65
+ export interface NamespaceScript {
66
+ readonly etag: string;
67
+ readonly version: string;
68
+ readonly tags: readonly string[];
69
+ readonly artifact?: string;
70
+ readonly line?: string;
71
+ readonly keyId?: string;
72
+ readonly createdOn?: string;
73
+ }
74
+ /** Everything one new deployment binds, all fixed at its create-only upload. */
75
+ export interface DeploymentBindingsInput {
76
+ /** The deployment URL, which is its issuer (`WORKER_URL`). */
77
+ readonly url: string;
78
+ /** The build digest of the bytes uploaded (`ASTRALE_BUILD_DIGEST`). */
79
+ readonly buildDigest: string;
80
+ /**
81
+ * A generated Worker's execution settings, already encoded (`ASTRALE_SETTINGS`), bound after the
82
+ * build digest; none when absent (a Worker host binds a deployer's settings among its variables).
83
+ */
84
+ readonly settings?: string;
85
+ /** The author's plain variables, bound in name order. */
86
+ readonly vars: Readonly<Record<string, string>>;
87
+ /** Service bindings, in the order given. */
88
+ readonly services?: readonly {
89
+ readonly name: string;
90
+ readonly service: string;
91
+ }[];
92
+ /** Dispatch namespace bindings, in the order given. */
93
+ readonly dispatchNamespaces?: readonly {
94
+ readonly name: string;
95
+ readonly namespace: string;
96
+ }[];
97
+ /** The Worker the `ROUTER` service binding reaches; none when absent. */
98
+ readonly router?: string;
99
+ /** The private JWK text of its key (`ASTRALE_SIGNING_IDENTITY`); none when absent. */
100
+ readonly signingIdentity?: string;
101
+ /** Its secrets, bound in name order. */
102
+ readonly secrets: Readonly<Record<string, string>>;
103
+ }
104
+ /**
105
+ * The bindings of one new deployment, in their order: `WORKER_URL`, `ASTRALE_BUILD_DIGEST`,
106
+ * `ASTRALE_SETTINGS` (when given), the variables, the service and dispatch namespace bindings,
107
+ * `ROUTER` (when given), the version metadata `ASTRALE_VERSION_METADATA`, the key
108
+ * `ASTRALE_SIGNING_IDENTITY` (when given), then the secrets. A script upload with assets adds
109
+ * `ASSETS` last. Nothing ever adds a binding afterwards: only a secret's value is rewritten in
110
+ * place. A name bound twice is refused.
111
+ */
112
+ export declare function deploymentBindings(input: DeploymentBindingsInput): readonly ScriptBinding[];
113
+ /**
114
+ * The tags of one deployment script: the caller's `extra` tags first (a host's own, such as
115
+ * Services' `astrale-service` and `astrale-install:`), then its artifact (build), line and, when
116
+ * it binds one, key.
117
+ */
118
+ export declare function deploymentTags(input: {
119
+ readonly buildDigest: string;
120
+ readonly line: string;
121
+ readonly keyId?: string;
122
+ readonly extra?: readonly string[];
123
+ }): readonly string[];
124
+ /** The artifact tag value of one build: the hexadecimal digest of its manifest. */
125
+ export declare function artifactOf(buildDigest: string): string;
126
+ /** What one create-only script upload carries. */
127
+ export interface ScriptUpload {
128
+ readonly client: CloudflareClient;
129
+ readonly namespace: string;
130
+ /** The script name: the deployment label. */
131
+ readonly label: string;
132
+ readonly mainModule: string;
133
+ readonly modules: readonly ScriptModule[];
134
+ readonly assets?: readonly ScriptAsset[];
135
+ readonly compatibilityDate: string;
136
+ readonly compatibilityFlags: readonly string[];
137
+ /** `deploymentBindings`; `ASSETS` is added when there are assets. */
138
+ readonly bindings: readonly ScriptBinding[];
139
+ /** `deploymentTags`. */
140
+ readonly tags: readonly string[];
141
+ }
142
+ /**
143
+ * Upload one deployment script, create-only: `If-None-Match: *` makes the provider refuse with
144
+ * 412 (`isExistingScript`) when the label already names a script, so an upload never replaces
145
+ * another deployment. Its static assets are uploaded first, through the namespace's asset session;
146
+ * the Worker routes first and serves its frontend itself.
147
+ */
148
+ export declare function uploadDeploymentScript(input: ScriptUpload): Promise<NamespaceScript>;
149
+ /** Whether a create-only upload was refused because the label already names a script. */
150
+ export declare function isExistingScript(cause: unknown): boolean;
151
+ /** Read one script's identity, or undefined when the namespace holds no script by that name. */
152
+ export declare function observeScript(client: CloudflareClient, namespace: string, label: string): Promise<NamespaceScript | undefined>;
153
+ /** The names of one script's `secret_text` bindings, sorted. */
154
+ export declare function scriptSecretNames(client: CloudflareClient, namespace: string, label: string): Promise<readonly string[]>;
155
+ /** One script's settings as the provider reads them back: runtime and bindings, never secrets. */
156
+ export interface ScriptSettings {
157
+ readonly compatibilityDate: string;
158
+ readonly compatibilityFlags: readonly string[];
159
+ readonly bindings: readonly Readonly<Record<string, unknown>>[];
160
+ }
161
+ export declare function scriptSettings(client: CloudflareClient, namespace: string, label: string): Promise<ScriptSettings>;
162
+ /**
163
+ * Whether settings read back bind exactly this runtime and these bindings: compatibility date and
164
+ * flags (in any order), every binding by name, type and target or text, secrets by name only.
165
+ */
166
+ export declare function settingsBind(settings: ScriptSettings, expected: {
167
+ readonly compatibilityDate: string;
168
+ readonly compatibilityFlags: readonly string[];
169
+ readonly bindings: readonly ScriptBinding[];
170
+ }): boolean;
171
+ /**
172
+ * Rewrite one secret of one script in place. Cloudflare keeps the script's name, etag, tags and
173
+ * other bindings, mints a new version, and answers only the secret's name and type.
174
+ */
175
+ export declare function putScriptSecret(client: CloudflareClient, namespace: string, label: string, name: string, value: string): Promise<void>;
176
+ /**
177
+ * Delete one script (with `?force=true`) and require that it is gone. A delete Cloudflare answers
178
+ * as unavailable counts when the script is observed absent afterwards.
179
+ */
180
+ export declare function deleteScript(client: CloudflareClient, namespace: string, label: string): Promise<void>;
181
+ /** A provider version in the UUID form a Worker's version metadata reports. */
182
+ export declare function versionUuid(version: string): string;
183
+ /** `/accounts/<a>/workers/dispatch/namespaces/<namespace>/scripts/<label><suffix>`. */
184
+ export declare function scriptPath(client: CloudflareClient, namespace: string, label: string, suffix?: string): string;
185
+ /** Decode the script identity an upload or a script read returns. */
186
+ export declare function decodeScript(value: unknown): NamespaceScript;
@@ -0,0 +1,324 @@
1
+ import { SIGNING_IDENTITY_BINDING } from '../identity/binding.js';
2
+ import { BUILD_DIGEST_BINDING } from '../worker/build-digest.js';
3
+ import { SETTINGS_BINDING } from '../worker/settings.js';
4
+ import { uploadAssets } from './assets.js';
5
+ import { CloudflareApiError, isNotFound } from './client.js';
6
+ /** The deployment URL, which is also its issuer. */
7
+ export const WORKER_URL_BINDING = 'WORKER_URL';
8
+ /** The binding a deployment's Worker reads its provider version from, for readiness. */
9
+ export const VERSION_METADATA_BINDING = 'ASTRALE_VERSION_METADATA';
10
+ /** The service binding through which a deployment reaches an instance router. */
11
+ export const ROUTER_BINDING = 'ROUTER';
12
+ /** The binding of a deployment's static assets, when its build has a frontend. */
13
+ export const ASSETS_BINDING = 'ASSETS';
14
+ /** The secret the generated Worker reads its private signing JWK from (`ASTRALE_SIGNING_IDENTITY`). */
15
+ export { BUILD_DIGEST_BINDING, SETTINGS_BINDING, SIGNING_IDENTITY_BINDING };
16
+ /** The build a script runs: `astrale-artifact:<hex digest of its build manifest>`. */
17
+ export const ARTIFACT_TAG_PREFIX = 'astrale-artifact:';
18
+ /** The deployment line a script is a version of: `astrale-line:<line>`. */
19
+ export const LINE_TAG_PREFIX = 'astrale-line:';
20
+ /** The signing key a script binds: `astrale-key:<RFC 7638 thumbprint>`. */
21
+ export const KEY_TAG_PREFIX = 'astrale-key:';
22
+ /** The multipart type of each Worker module kind, as the Workers upload API reads it. */
23
+ const MODULE_PART_TYPES = Object.freeze({
24
+ esm: 'application/javascript+module',
25
+ wasm: 'application/wasm',
26
+ text: 'text/plain',
27
+ data: 'application/octet-stream',
28
+ });
29
+ /**
30
+ * The bindings of one new deployment, in their order: `WORKER_URL`, `ASTRALE_BUILD_DIGEST`,
31
+ * `ASTRALE_SETTINGS` (when given), the variables, the service and dispatch namespace bindings,
32
+ * `ROUTER` (when given), the version metadata `ASTRALE_VERSION_METADATA`, the key
33
+ * `ASTRALE_SIGNING_IDENTITY` (when given), then the secrets. A script upload with assets adds
34
+ * `ASSETS` last. Nothing ever adds a binding afterwards: only a secret's value is rewritten in
35
+ * place. A name bound twice is refused.
36
+ */
37
+ export function deploymentBindings(input) {
38
+ const bindings = [
39
+ { type: 'plain_text', name: WORKER_URL_BINDING, text: input.url },
40
+ { type: 'plain_text', name: BUILD_DIGEST_BINDING, text: input.buildDigest },
41
+ ...(input.settings === undefined
42
+ ? []
43
+ : [{ type: 'plain_text', name: SETTINGS_BINDING, text: input.settings }]),
44
+ ...Object.keys(input.vars)
45
+ .sort()
46
+ .map((name) => ({ type: 'plain_text', name, text: input.vars[name] })),
47
+ ...(input.services ?? []).map((binding) => ({
48
+ type: 'service',
49
+ name: binding.name,
50
+ service: binding.service,
51
+ })),
52
+ ...(input.dispatchNamespaces ?? []).map((binding) => ({
53
+ type: 'dispatch_namespace',
54
+ name: binding.name,
55
+ namespace: binding.namespace,
56
+ })),
57
+ ...(input.router === undefined
58
+ ? []
59
+ : [{ type: 'service', name: ROUTER_BINDING, service: input.router }]),
60
+ { type: 'version_metadata', name: VERSION_METADATA_BINDING },
61
+ ...(input.signingIdentity === undefined
62
+ ? []
63
+ : [
64
+ {
65
+ type: 'secret_text',
66
+ name: SIGNING_IDENTITY_BINDING,
67
+ text: input.signingIdentity,
68
+ },
69
+ ]),
70
+ ...Object.keys(input.secrets)
71
+ .sort()
72
+ .map((name) => ({ type: 'secret_text', name, text: input.secrets[name] })),
73
+ ];
74
+ const names = bindings.map((binding) => binding.name);
75
+ const repeated = names.filter((name, index) => names.indexOf(name) !== index);
76
+ if (repeated.length > 0) {
77
+ throw new TypeError(`The deployment binds ${[...new Set(repeated)].join(', ')} twice.`);
78
+ }
79
+ return Object.freeze(bindings.map((binding) => Object.freeze(binding)));
80
+ }
81
+ /**
82
+ * The tags of one deployment script: the caller's `extra` tags first (a host's own, such as
83
+ * Services' `astrale-service` and `astrale-install:`), then its artifact (build), line and, when
84
+ * it binds one, key.
85
+ */
86
+ export function deploymentTags(input) {
87
+ return Object.freeze([
88
+ ...(input.extra ?? []),
89
+ `${ARTIFACT_TAG_PREFIX}${artifactOf(input.buildDigest)}`,
90
+ `${LINE_TAG_PREFIX}${input.line}`,
91
+ ...(input.keyId === undefined ? [] : [`${KEY_TAG_PREFIX}${input.keyId}`]),
92
+ ]);
93
+ }
94
+ /** The artifact tag value of one build: the hexadecimal digest of its manifest. */
95
+ export function artifactOf(buildDigest) {
96
+ if (!/^sha256:[0-9a-f]{64}$/u.test(buildDigest)) {
97
+ throw new TypeError('Deployment build digest is invalid.');
98
+ }
99
+ return buildDigest.slice('sha256:'.length);
100
+ }
101
+ /**
102
+ * Upload one deployment script, create-only: `If-None-Match: *` makes the provider refuse with
103
+ * 412 (`isExistingScript`) when the label already names a script, so an upload never replaces
104
+ * another deployment. Its static assets are uploaded first, through the namespace's asset session;
105
+ * the Worker routes first and serves its frontend itself.
106
+ */
107
+ export async function uploadDeploymentScript(input) {
108
+ const assets = input.assets ?? [];
109
+ const assetsJwt = assets.length === 0
110
+ ? undefined
111
+ : await uploadAssets(input.client, input.namespace, input.label, assets);
112
+ const bindings = [...input.bindings];
113
+ if (assetsJwt !== undefined)
114
+ bindings.push({ type: 'assets', name: ASSETS_BINDING });
115
+ const metadata = {
116
+ main_module: input.mainModule,
117
+ compatibility_date: input.compatibilityDate,
118
+ compatibility_flags: [...input.compatibilityFlags],
119
+ bindings,
120
+ tags: [...input.tags],
121
+ observability: { enabled: true },
122
+ ...(assetsJwt === undefined
123
+ ? {}
124
+ : {
125
+ assets: {
126
+ jwt: assetsJwt,
127
+ config: { not_found_handling: 'none', html_handling: 'none', run_worker_first: true },
128
+ },
129
+ }),
130
+ };
131
+ const form = new FormData();
132
+ form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }), 'metadata');
133
+ for (const module of input.modules) {
134
+ form.append(module.name, new Blob([module.bytes], { type: MODULE_PART_TYPES[module.kind] }), module.name);
135
+ }
136
+ return decodeScript(await input.client.form('PUT', scriptPath(input.client, input.namespace, input.label), form, {
137
+ headers: { 'if-none-match': '*' },
138
+ }));
139
+ }
140
+ /** Whether a create-only upload was refused because the label already names a script. */
141
+ export function isExistingScript(cause) {
142
+ return cause instanceof CloudflareApiError && cause.status === 412;
143
+ }
144
+ /** Read one script's identity, or undefined when the namespace holds no script by that name. */
145
+ export async function observeScript(client, namespace, label) {
146
+ let result;
147
+ try {
148
+ result = await client.json('GET', scriptPath(client, namespace, label));
149
+ }
150
+ catch (cause) {
151
+ if (isNotFound(cause))
152
+ return undefined;
153
+ throw cause;
154
+ }
155
+ const script = result?.script;
156
+ if (script === null || script === undefined)
157
+ return undefined;
158
+ return decodeScript(script);
159
+ }
160
+ /** The names of one script's `secret_text` bindings, sorted. */
161
+ export async function scriptSecretNames(client, namespace, label) {
162
+ const result = await client.json('GET', scriptPath(client, namespace, label, '/secrets'));
163
+ if (!Array.isArray(result))
164
+ invalid('secrets listing');
165
+ return Object.freeze(result
166
+ .map((entry) => {
167
+ const value = entry;
168
+ if (typeof value?.name !== 'string' || value.type !== 'secret_text') {
169
+ invalid('secrets listing');
170
+ }
171
+ return value.name;
172
+ })
173
+ .sort());
174
+ }
175
+ export async function scriptSettings(client, namespace, label) {
176
+ const result = (await client.json('GET', scriptPath(client, namespace, label, '/settings')));
177
+ const flags = result?.compatibility_flags ?? [];
178
+ if (result === null ||
179
+ typeof result !== 'object' ||
180
+ typeof result.compatibility_date !== 'string' ||
181
+ !Array.isArray(flags) ||
182
+ flags.some((flag) => typeof flag !== 'string') ||
183
+ !Array.isArray(result.bindings) ||
184
+ result.bindings.some((binding) => binding === null || typeof binding !== 'object')) {
185
+ invalid('script settings');
186
+ }
187
+ return Object.freeze({
188
+ compatibilityDate: result.compatibility_date,
189
+ compatibilityFlags: flags,
190
+ bindings: result.bindings,
191
+ });
192
+ }
193
+ /**
194
+ * Whether settings read back bind exactly this runtime and these bindings: compatibility date and
195
+ * flags (in any order), every binding by name, type and target or text, secrets by name only.
196
+ */
197
+ export function settingsBind(settings, expected) {
198
+ return (settings.compatibilityDate === expected.compatibilityDate &&
199
+ JSON.stringify([...settings.compatibilityFlags].sort()) ===
200
+ JSON.stringify([...expected.compatibilityFlags].sort()) &&
201
+ JSON.stringify(settings.bindings.map(observedBinding).sort(byName)) ===
202
+ JSON.stringify(expected.bindings.map(expectedBinding).sort(byName)));
203
+ }
204
+ /**
205
+ * Rewrite one secret of one script in place. Cloudflare keeps the script's name, etag, tags and
206
+ * other bindings, mints a new version, and answers only the secret's name and type.
207
+ */
208
+ export async function putScriptSecret(client, namespace, label, name, value) {
209
+ await client.json('PUT', scriptPath(client, namespace, label, '/secrets'), {
210
+ name,
211
+ text: value,
212
+ type: 'secret_text',
213
+ });
214
+ }
215
+ /**
216
+ * Delete one script (with `?force=true`) and require that it is gone. A delete Cloudflare answers
217
+ * as unavailable counts when the script is observed absent afterwards.
218
+ */
219
+ export async function deleteScript(client, namespace, label) {
220
+ const path = scriptPath(client, namespace, label);
221
+ try {
222
+ await client.effect('DELETE', `${path}?force=true`);
223
+ }
224
+ catch (cause) {
225
+ if (isNotFound(cause))
226
+ return;
227
+ if (!(cause instanceof CloudflareApiError) || cause.kind !== 'unavailable')
228
+ throw cause;
229
+ let absent;
230
+ try {
231
+ absent = (await observeScript(client, namespace, label)) === undefined;
232
+ }
233
+ catch (observation) {
234
+ throw new AggregateError([cause, observation], 'Cloudflare script deletion and observation both failed.');
235
+ }
236
+ if (absent)
237
+ return;
238
+ throw cause;
239
+ }
240
+ if ((await observeScript(client, namespace, label)) !== undefined) {
241
+ throw new CloudflareApiError('unavailable', 'Cloudflare script deletion is not complete.');
242
+ }
243
+ }
244
+ /** A provider version in the UUID form a Worker's version metadata reports. */
245
+ export function versionUuid(version) {
246
+ const compact = version.toLowerCase().replaceAll('-', '');
247
+ if (!/^[0-9a-f]{32}$/u.test(compact))
248
+ invalid('script version');
249
+ return [
250
+ compact.slice(0, 8),
251
+ compact.slice(8, 12),
252
+ compact.slice(12, 16),
253
+ compact.slice(16, 20),
254
+ compact.slice(20),
255
+ ].join('-');
256
+ }
257
+ /** `/accounts/<a>/workers/dispatch/namespaces/<namespace>/scripts/<label><suffix>`. */
258
+ export function scriptPath(client, namespace, label, suffix = '') {
259
+ return client.account(`/workers/dispatch/namespaces/${encodeURIComponent(namespace)}/scripts/${encodeURIComponent(label)}${suffix}`);
260
+ }
261
+ /** Decode the script identity an upload or a script read returns. */
262
+ export function decodeScript(value) {
263
+ const script = value;
264
+ if (script === null || typeof script !== 'object')
265
+ invalid('namespace script evidence');
266
+ const { etag, deployment_id: version, created_on: createdOn } = script;
267
+ if (typeof etag !== 'string' || etag.length === 0)
268
+ invalid('namespace script evidence');
269
+ if (typeof version !== 'string' || version.length === 0)
270
+ invalid('namespace script evidence');
271
+ // Cloudflare returns null for a script that has never had tags.
272
+ const tags = script.tags ?? [];
273
+ if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== 'string')) {
274
+ invalid('namespace script evidence');
275
+ }
276
+ const artifact = tagValue(tags, ARTIFACT_TAG_PREFIX);
277
+ const line = tagValue(tags, LINE_TAG_PREFIX);
278
+ const keyId = tagValue(tags, KEY_TAG_PREFIX);
279
+ return Object.freeze({
280
+ etag,
281
+ version,
282
+ tags: Object.freeze([...tags]),
283
+ ...(artifact === undefined ? {} : { artifact }),
284
+ ...(line === undefined ? {} : { line }),
285
+ ...(keyId === undefined ? {} : { keyId }),
286
+ ...(typeof createdOn === 'string' && createdOn.length > 0 ? { createdOn } : {}),
287
+ });
288
+ }
289
+ function tagValue(tags, prefix) {
290
+ const selected = tags.filter((tag) => tag.startsWith(prefix));
291
+ if (selected.length > 1)
292
+ invalid('namespace script evidence');
293
+ return selected[0]?.slice(prefix.length);
294
+ }
295
+ /** A binding as a script's settings read it back: secrets by name only. */
296
+ function observedBinding(binding) {
297
+ const type = String(binding.type);
298
+ const name = String(binding.name);
299
+ if (type === 'plain_text')
300
+ return { type, name, value: String(binding.text) };
301
+ if (type === 'service')
302
+ return { type, name, value: String(binding.service) };
303
+ if (type === 'dispatch_namespace')
304
+ return { type, name, value: String(binding.namespace) };
305
+ return { type, name };
306
+ }
307
+ function expectedBinding(binding) {
308
+ if (binding.type === 'plain_text') {
309
+ return { type: binding.type, name: binding.name, value: binding.text };
310
+ }
311
+ if (binding.type === 'service') {
312
+ return { type: binding.type, name: binding.name, value: binding.service };
313
+ }
314
+ if (binding.type === 'dispatch_namespace') {
315
+ return { type: binding.type, name: binding.name, value: binding.namespace };
316
+ }
317
+ return { type: binding.type, name: binding.name };
318
+ }
319
+ function byName(left, right) {
320
+ return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
321
+ }
322
+ function invalid(what) {
323
+ throw new CloudflareApiError('upstream', `Cloudflare returned invalid ${what}.`);
324
+ }