@madebyentropy/tnl 0.0.0-stage → 0.1.0

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 (198) hide show
  1. package/LICENSE +28 -0
  2. package/NOTICE +5 -0
  3. package/THIRD_PARTY_LICENSES.txt +3297 -0
  4. package/dist/adapters/ioredis.d.ts +7 -0
  5. package/dist/adapters/ioredis.js +87 -0
  6. package/dist/adapters/node-postgres.d.ts +8 -0
  7. package/dist/adapters/node-postgres.js +41 -0
  8. package/dist/adapters/postgres-js.d.ts +7 -0
  9. package/dist/adapters/postgres-js.js +55 -0
  10. package/dist/bin/tnl.d.ts +2 -0
  11. package/dist/bin/tnl.js +16 -0
  12. package/dist/browser.d.ts +18 -0
  13. package/dist/browser.js +43 -0
  14. package/dist/bun.d.ts +9 -0
  15. package/dist/bun.js +6 -0
  16. package/dist/cloudflare.d.ts +9 -0
  17. package/dist/cloudflare.js +16 -0
  18. package/dist/config.d.ts +107 -0
  19. package/dist/config.gen.d.ts +1185 -0
  20. package/dist/config.gen.js +2 -0
  21. package/dist/config.js +3 -0
  22. package/dist/control.d.ts +5 -0
  23. package/dist/control.js +9 -0
  24. package/dist/durable-object.d.ts +51 -0
  25. package/dist/durable-object.js +374 -0
  26. package/dist/durable-object.worker.d.ts +5 -0
  27. package/dist/durable-object.worker.js +11 -0
  28. package/dist/errors.d.ts +17 -0
  29. package/dist/errors.js +230 -0
  30. package/dist/index.d.ts +10 -0
  31. package/dist/index.js +2 -0
  32. package/dist/internal/connector/cancellation.d.ts +7 -0
  33. package/dist/internal/connector/cancellation.js +30 -0
  34. package/dist/internal/connector/client.d.ts +62 -0
  35. package/dist/internal/connector/client.js +504 -0
  36. package/dist/internal/connector/client_factory.d.ts +6 -0
  37. package/dist/internal/connector/client_factory.js +123 -0
  38. package/dist/internal/connector/connection.d.ts +39 -0
  39. package/dist/internal/connector/connection.js +739 -0
  40. package/dist/internal/connector/connection_ipc.d.ts +12 -0
  41. package/dist/internal/connector/connection_ipc.js +198 -0
  42. package/dist/internal/connector/context.d.ts +28 -0
  43. package/dist/internal/connector/context.js +19 -0
  44. package/dist/internal/connector/contract.d.ts +392 -0
  45. package/dist/internal/connector/contract.js +56 -0
  46. package/dist/internal/connector/deployment_types.d.ts +27 -0
  47. package/dist/internal/connector/deployment_types.js +1 -0
  48. package/dist/internal/connector/driver_socket.d.ts +21 -0
  49. package/dist/internal/connector/driver_socket.js +129 -0
  50. package/dist/internal/connector/management.d.ts +29 -0
  51. package/dist/internal/connector/management.js +118 -0
  52. package/dist/internal/connector/native_operations.d.ts +16 -0
  53. package/dist/internal/connector/native_operations.js +30 -0
  54. package/dist/internal/connector/native_stream.d.ts +7 -0
  55. package/dist/internal/connector/native_stream.js +219 -0
  56. package/dist/internal/connector/operation_handles.d.ts +9 -0
  57. package/dist/internal/connector/operation_handles.js +18 -0
  58. package/dist/internal/connector/portable_operations.d.ts +13 -0
  59. package/dist/internal/connector/portable_operations.js +25 -0
  60. package/dist/internal/connector/snapshot.d.ts +183 -0
  61. package/dist/internal/connector/snapshot.js +47 -0
  62. package/dist/internal/connector/wasm_abi.d.ts +76 -0
  63. package/dist/internal/connector/wasm_abi.js +5 -0
  64. package/dist/internal/connector/wasm_client.d.ts +58 -0
  65. package/dist/internal/connector/wasm_client.js +545 -0
  66. package/dist/internal/connector/wasm_loader.d.ts +15 -0
  67. package/dist/internal/connector/wasm_loader.js +99 -0
  68. package/dist/internal/connector/wasm_stream.d.ts +4 -0
  69. package/dist/internal/connector/wasm_stream.js +177 -0
  70. package/dist/internal/connector/workload/contract.d.ts +54 -0
  71. package/dist/internal/connector/workload/contract.js +14 -0
  72. package/dist/internal/connector/workload/provider.d.ts +24 -0
  73. package/dist/internal/connector/workload/provider.js +130 -0
  74. package/dist/internal/enrollment_source.d.ts +4 -0
  75. package/dist/internal/enrollment_source.js +34 -0
  76. package/dist/internal/management/client/client.gen.d.ts +2 -0
  77. package/dist/internal/management/client/client.gen.js +216 -0
  78. package/dist/internal/management/client/index.d.ts +10 -0
  79. package/dist/internal/management/client/index.js +6 -0
  80. package/dist/internal/management/client/types.gen.d.ts +120 -0
  81. package/dist/internal/management/client/types.gen.js +2 -0
  82. package/dist/internal/management/client/utils.gen.d.ts +37 -0
  83. package/dist/internal/management/client/utils.gen.js +228 -0
  84. package/dist/internal/management/client.gen.d.ts +12 -0
  85. package/dist/internal/management/client.gen.js +3 -0
  86. package/dist/internal/management/core/auth.gen.d.ts +25 -0
  87. package/dist/internal/management/core/auth.gen.js +14 -0
  88. package/dist/internal/management/core/bodySerializer.gen.d.ts +25 -0
  89. package/dist/internal/management/core/bodySerializer.gen.js +57 -0
  90. package/dist/internal/management/core/params.gen.d.ts +43 -0
  91. package/dist/internal/management/core/params.gen.js +109 -0
  92. package/dist/internal/management/core/pathSerializer.gen.d.ts +33 -0
  93. package/dist/internal/management/core/pathSerializer.gen.js +106 -0
  94. package/dist/internal/management/core/queryKeySerializer.gen.d.ts +18 -0
  95. package/dist/internal/management/core/queryKeySerializer.gen.js +92 -0
  96. package/dist/internal/management/core/serverSentEvents.gen.d.ts +71 -0
  97. package/dist/internal/management/core/serverSentEvents.gen.js +132 -0
  98. package/dist/internal/management/core/types.gen.d.ts +83 -0
  99. package/dist/internal/management/core/types.gen.js +2 -0
  100. package/dist/internal/management/core/utils.gen.d.ts +19 -0
  101. package/dist/internal/management/core/utils.gen.js +87 -0
  102. package/dist/internal/management/index.d.ts +2 -0
  103. package/dist/internal/management/index.js +2 -0
  104. package/dist/internal/management/sdk.gen.d.ts +73 -0
  105. package/dist/internal/management/sdk.gen.js +191 -0
  106. package/dist/internal/management/types.gen.d.ts +464 -0
  107. package/dist/internal/management/types.gen.js +2 -0
  108. package/dist/internal/management/zod.gen.d.ts +850 -0
  109. package/dist/internal/management/zod.gen.js +252 -0
  110. package/dist/internal/native/launcher.d.ts +8 -0
  111. package/dist/internal/native/launcher.js +75 -0
  112. package/dist/internal/native/native-targets.d.ts +9 -0
  113. package/dist/internal/native/native-targets.js +8 -0
  114. package/dist/internal/portable/cloudflare-publisher-client.d.ts +54 -0
  115. package/dist/internal/portable/cloudflare-publisher-client.js +91 -0
  116. package/dist/internal/portable/cloudflare-publisher.d.ts +19 -0
  117. package/dist/internal/portable/cloudflare-publisher.js +210 -0
  118. package/dist/internal/portable/durable-deployment.d.ts +10 -0
  119. package/dist/internal/portable/durable-deployment.js +22 -0
  120. package/dist/internal/portable/enrollment.d.ts +26 -0
  121. package/dist/internal/portable/enrollment.js +196 -0
  122. package/dist/internal/portable/publication.d.ts +54 -0
  123. package/dist/internal/portable/publication.js +304 -0
  124. package/dist/internal/portable/request.d.ts +1 -0
  125. package/dist/internal/portable/request.js +20 -0
  126. package/dist/internal/portable/storage-browser.d.ts +9 -0
  127. package/dist/internal/portable/storage-browser.js +115 -0
  128. package/dist/internal/portable/storage-durable-object.d.ts +11 -0
  129. package/dist/internal/portable/storage-durable-object.js +110 -0
  130. package/dist/internal/portable/storage-host.d.ts +8 -0
  131. package/dist/internal/portable/storage-host.js +142 -0
  132. package/dist/internal/portable/storage.d.ts +15 -0
  133. package/dist/internal/portable/storage.js +29 -0
  134. package/dist/internal/project/native_runtime.d.ts +24 -0
  135. package/dist/internal/project/native_runtime.js +23 -0
  136. package/dist/internal/project/runtime.d.ts +467 -0
  137. package/dist/internal/project/runtime.js +183 -0
  138. package/dist/internal/project/service_metadata.d.ts +3 -0
  139. package/dist/internal/project/service_metadata.js +12 -0
  140. package/dist/internal/publication_certificate.d.ts +28 -0
  141. package/dist/internal/publication_certificate.js +32 -0
  142. package/dist/internal/publication_run.d.ts +8 -0
  143. package/dist/internal/publication_run.js +19 -0
  144. package/dist/internal/publisher/app.d.ts +33 -0
  145. package/dist/internal/publisher/app.js +317 -0
  146. package/dist/internal/publisher/fetch.d.ts +6 -0
  147. package/dist/internal/publisher/fetch.js +135 -0
  148. package/dist/internal/publisher/fetch_types.d.ts +1 -0
  149. package/dist/internal/publisher/fetch_types.js +1 -0
  150. package/dist/internal/publisher/framework.d.ts +27 -0
  151. package/dist/internal/publisher/framework.js +82 -0
  152. package/dist/internal/publisher/local.d.ts +39 -0
  153. package/dist/internal/publisher/local.js +312 -0
  154. package/dist/internal/publisher/native_publisher.d.ts +25 -0
  155. package/dist/internal/publisher/native_publisher.js +228 -0
  156. package/dist/internal/publisher/port.d.ts +2 -0
  157. package/dist/internal/publisher/port.js +15 -0
  158. package/dist/internal/publisher/publication.d.ts +88 -0
  159. package/dist/internal/publisher/publication.js +627 -0
  160. package/dist/internal/publisher/register.d.ts +31 -0
  161. package/dist/internal/publisher/register.js +136 -0
  162. package/dist/internal/publisher/registration.d.ts +385 -0
  163. package/dist/internal/publisher/registration.js +223 -0
  164. package/dist/internal/publisher/status.d.ts +47 -0
  165. package/dist/internal/publisher/status.js +137 -0
  166. package/dist/internal/publisher/target.d.ts +6 -0
  167. package/dist/internal/publisher/target.js +44 -0
  168. package/dist/internal/runtime_resources.d.ts +38 -0
  169. package/dist/internal/runtime_resources.js +52 -0
  170. package/dist/internal/tracing.d.ts +10 -0
  171. package/dist/internal/tracing.js +78 -0
  172. package/dist/internal/validation.d.ts +3 -0
  173. package/dist/internal/validation.js +9 -0
  174. package/dist/internal/values.d.ts +27 -0
  175. package/dist/internal/values.js +54 -0
  176. package/dist/next.d.ts +12 -0
  177. package/dist/next.js +82 -0
  178. package/dist/node.d.ts +9 -0
  179. package/dist/node.js +6 -0
  180. package/dist/project.d.ts +173 -0
  181. package/dist/project.js +1 -0
  182. package/dist/response.d.ts +1 -0
  183. package/dist/response.js +34 -0
  184. package/dist/third-party-licenses.txt +1537 -0
  185. package/dist/vite.d.ts +5 -0
  186. package/dist/vite.js +200 -0
  187. package/dist/wasm/build.json +16 -0
  188. package/dist/wasm/connector.wasm +0 -0
  189. package/dist/wasm/go-license.txt +27 -0
  190. package/dist/wasm/publisher.wasm +0 -0
  191. package/dist/wasm/third-party-licenses.txt +3297 -0
  192. package/dist/wasm/wasm_exec.d.ts +1 -0
  193. package/dist/wasm/wasm_exec.js +575 -0
  194. package/dist/workload.d.ts +11 -0
  195. package/dist/workload.js +4 -0
  196. package/package.json +159 -4
  197. package/readme.md +13 -0
  198. package/README.md +0 -3
@@ -0,0 +1,2 @@
1
+ // Code generated by scripts/generate/config-types.ts. DO NOT EDIT.
2
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,3 @@
1
+ export function defineConfig(config) {
2
+ return config;
3
+ }
@@ -0,0 +1,5 @@
1
+ import { type Config } from "./internal/management/client/index.js";
2
+ export { createConfig } from "./internal/management/client/index.js";
3
+ export declare function control(options?: Config): import("./internal/management/client/types.gen.js").Client;
4
+ export { createDeployment, deleteDeployment, getDeployment, listDeployments, updateDeployment, createDeploymentPublisherEnrollment as createPublisherEnrollment, getDeploymentPublisher as getPublisher, listDeploymentPublishers as listPublishers, revokeDeploymentPublisher as revokePublisher, } from "./internal/management/sdk.gen.js";
5
+ export type * from "./internal/management/types.gen.js";
@@ -0,0 +1,9 @@
1
+ // this entry point contains only generated Fetch operations and their contracts.
2
+ // it must not import native process, project configuration, or credential stores.
3
+ import { createClient } from "./internal/management/client/index.js";
4
+ import { client as generatedClient } from "./internal/management/client.gen.js";
5
+ export { createConfig } from "./internal/management/client/index.js";
6
+ export function control(options) {
7
+ return createClient({ ...generatedClient.getConfig(), ...options });
8
+ }
9
+ export { createDeployment, deleteDeployment, getDeployment, listDeployments, updateDeployment, createDeploymentPublisherEnrollment as createPublisherEnrollment, getDeploymentPublisher as getPublisher, listDeploymentPublishers as listPublishers, revokeDeploymentPublisher as revokePublisher, } from "./internal/management/sdk.gen.js";
@@ -0,0 +1,51 @@
1
+ import type { FetchHandler } from "./internal/publisher/fetch_types.js";
2
+ import type { NamedPublicationOptions, Publication, TemporaryPublicationOptions, ServiceCertificateSource } from "./internal/publisher/publication.js";
3
+ import { createDurableObjectPublisherStorage, type PublisherSQLiteStorage } from "./internal/portable/storage-durable-object.js";
4
+ import { type PublisherStorage } from "./internal/portable/storage.js";
5
+ import { createPublisherStorageHost, type PublisherStorageHost } from "./internal/portable/storage-host.js";
6
+ export { createDurableObjectPublisherStorage, createPublisherStorageHost };
7
+ export type { PublisherSQLiteStorage, PublisherStorage, PublisherStorageHost };
8
+ export { PublisherStorageError, type PublisherStorageErrorCode, } from "./internal/portable/storage.js";
9
+ export interface DurableObjectPublisherState {
10
+ readonly storage: PublisherSQLiteStorage & {
11
+ setAlarm(scheduledTime: number | Date): Promise<void>;
12
+ deleteAlarm(): Promise<void>;
13
+ };
14
+ waitUntil(promise: Promise<unknown>): void;
15
+ }
16
+ export interface DurablePublicationConfiguration {
17
+ readonly project: string;
18
+ readonly deployment: string;
19
+ readonly service?: string;
20
+ readonly options?: Omit<TemporaryPublicationOptions, "signal" | "certificate">;
21
+ }
22
+ export interface DurablePublisherDeployment {
23
+ publish(name: string, handler: FetchHandler, options?: NamedPublicationOptions): Promise<Publication>;
24
+ publish(handler: FetchHandler, options?: TemporaryPublicationOptions): Promise<Publication>;
25
+ close(): Promise<void>;
26
+ }
27
+ export interface DurableObjectPublisherOptions {
28
+ readonly configuration: DurablePublicationConfiguration;
29
+ readonly certificate?: ServiceCertificateSource;
30
+ readonly identity: () => Uint8Array | Promise<Uint8Array>;
31
+ readonly handler: (configuration: DurablePublicationConfiguration) => FetchHandler | Promise<FetchHandler>;
32
+ readonly createDeployment: (context: {
33
+ readonly configuration: DurablePublicationConfiguration;
34
+ readonly identity: Uint8Array;
35
+ readonly storage: PublisherStorage;
36
+ readonly storageHost: PublisherStorageHost;
37
+ readonly signal: AbortSignal;
38
+ }) => DurablePublisherDeployment | Promise<DurablePublisherDeployment>;
39
+ readonly storageNamespace?: string;
40
+ readonly restartIntervalMs?: number;
41
+ }
42
+ export type DurableObjectWasmPublisherOptions = Omit<DurableObjectPublisherOptions, "createDeployment">;
43
+ export declare class DurableObjectPublisher {
44
+ #private;
45
+ readonly ready: Promise<void>;
46
+ constructor(state: DurableObjectPublisherState, options: DurableObjectPublisherOptions);
47
+ start(): Promise<Publication>;
48
+ stop(): Promise<void>;
49
+ resume(): Promise<void>;
50
+ alarm(): Promise<void>;
51
+ }
@@ -0,0 +1,374 @@
1
+ import * as z from "zod";
2
+ import { TnlError } from "./errors.js";
3
+ import { createDurableObjectPublisherStorage, } from "./internal/portable/storage-durable-object.js";
4
+ import { PublisherStorageError, storageBytes, } from "./internal/portable/storage.js";
5
+ import { createPublisherStorageHost, } from "./internal/portable/storage-host.js";
6
+ export { createDurableObjectPublisherStorage, createPublisherStorageHost };
7
+ export { PublisherStorageError, } from "./internal/portable/storage.js";
8
+ const publicationOptionsSchema = z.strictObject({
9
+ public: z.boolean().exactOptional(),
10
+ targetHostname: z.string().min(1).max(253).exactOptional(),
11
+ telemetry: z.boolean().exactOptional(),
12
+ requirePostQuantum: z.boolean().exactOptional(),
13
+ access: z
14
+ .union([
15
+ z.enum(["restricted", "anonymous"]),
16
+ z.strictObject({
17
+ mode: z.enum(["restricted", "anonymous"]).exactOptional(),
18
+ ip: z.array(z.string().min(1).max(64)).min(1).max(32).exactOptional(),
19
+ }),
20
+ ])
21
+ .exactOptional(),
22
+ limits: z
23
+ .strictObject({
24
+ requests: z.number().int().positive().exactOptional(),
25
+ concurrency: z.number().int().positive().exactOptional(),
26
+ rate: z
27
+ .strictObject({
28
+ requests: z.number().int().positive(),
29
+ per: z.custom((value) => typeof value === "string" &&
30
+ /^(?:[0-9]+(?:\.[0-9]+)?(?:ns|us|µs|ms|s|m|h)){1,4}$/.test(value)),
31
+ })
32
+ .exactOptional(),
33
+ })
34
+ .exactOptional(),
35
+ });
36
+ const configurationSchema = z
37
+ .strictObject({
38
+ project: z.string().min(1).max(253),
39
+ deployment: z.string().min(1).max(253),
40
+ service: z.string().min(1).max(253).exactOptional(),
41
+ options: publicationOptionsSchema.exactOptional(),
42
+ })
43
+ .refine((value) => value.service === undefined ||
44
+ value.options === undefined ||
45
+ Object.keys(value.options).every((key) => ["targetHostname", "telemetry"].includes(key)));
46
+ const intentSchema = z.strictObject({
47
+ version: z.literal(1),
48
+ status: z.enum(["running", "stopped"]),
49
+ configuration: configurationSchema,
50
+ });
51
+ const intentKey = "@tnl/publisher-owner/v1";
52
+ const identityKey = "@tnl/publisher-identity/v1";
53
+ // create one owner per Durable Object instance, not per request, and forward
54
+ // its alarm() to this owner. the attached SQLite database retains intent,
55
+ // identity, and certificate records across restarts. a wake rebuilds the
56
+ // handler and connections; outbound WebSockets are not hibernated, and
57
+ // in-flight requests are not resumed.
58
+ export class DurableObjectPublisher {
59
+ ready;
60
+ #state;
61
+ #options;
62
+ #configuration;
63
+ #storage;
64
+ #storageHost;
65
+ #interval;
66
+ #intent;
67
+ #revision = 0;
68
+ #running;
69
+ #intentQueue;
70
+ #runtimeQueue = Promise.resolve();
71
+ #completions = new WeakMap();
72
+ constructor(state, options) {
73
+ const configuration = configurationSchema.safeParse(options.configuration);
74
+ const interval = options.restartIntervalMs ?? 60_000;
75
+ if (!configuration.success ||
76
+ typeof options.identity !== "function" ||
77
+ typeof options.handler !== "function" ||
78
+ typeof options.createDeployment !== "function" ||
79
+ !Number.isSafeInteger(interval) ||
80
+ interval < 1000 ||
81
+ interval > 24 * 60 * 60 * 1000)
82
+ throw new TnlError("sdk.configuration_invalid");
83
+ if (typeof state?.waitUntil !== "function" ||
84
+ typeof state.storage?.setAlarm !== "function" ||
85
+ typeof state.storage.deleteAlarm !== "function")
86
+ throw new PublisherStorageError();
87
+ this.#state = state;
88
+ this.#options = options;
89
+ this.#configuration = configuration.data;
90
+ this.#interval = interval;
91
+ this.#storage = createDurableObjectPublisherStorage(state.storage, options.storageNamespace);
92
+ this.#storageHost = createPublisherStorageHost(this.#storage);
93
+ this.#intentQueue = this.#load();
94
+ // waitUntil keeps the finite startup work alive past the request, not the
95
+ // lifetime of the publication. the object instance owns the live runtime.
96
+ this.ready = this.resume();
97
+ void this.ready.catch(() => { });
98
+ }
99
+ start() {
100
+ return this.#retain(this.#start());
101
+ }
102
+ async #start() {
103
+ await this.#serializeIntent(async () => {
104
+ // set the alarm before saving running intent. if the object restarts
105
+ // between these writes, the alarm can still wake it to read the prior intent.
106
+ await this.#arm();
107
+ const next = {
108
+ version: 1,
109
+ status: "running",
110
+ configuration: this.#configuration,
111
+ };
112
+ await this.#save(next);
113
+ if (JSON.stringify(this.#intent) !== JSON.stringify(next)) {
114
+ this.#revision++;
115
+ this.#running?.controller.abort();
116
+ }
117
+ this.#intent = next;
118
+ });
119
+ const revision = this.#revision;
120
+ const publication = await this.#reconcile();
121
+ if (publication === undefined || revision !== this.#revision)
122
+ throw new DOMException("publication was stopped", "AbortError");
123
+ const completion = this.#completions.get(publication);
124
+ if (completion === undefined)
125
+ throw new TnlError("sdk.publication_failed");
126
+ return Object.freeze({
127
+ ...(publication.url === undefined ? {} : { url: publication.url }),
128
+ get publisherURL() {
129
+ return publication.publisherURL;
130
+ },
131
+ get run() {
132
+ return publication.run;
133
+ },
134
+ exportCertificate: () => publication.exportCertificate(),
135
+ close: () => this.#retain(this.#stop(revision)),
136
+ wait: () => completion,
137
+ [Symbol.asyncDispose]: () => this.#retain(this.#stop(revision)),
138
+ });
139
+ }
140
+ stop() {
141
+ return this.#retain(this.#stop());
142
+ }
143
+ // resume never changes stopped or absent intent to running. it is safe to
144
+ // call for an ordinary incoming request as well as during construction.
145
+ resume() {
146
+ return this.#retain(this.#resume());
147
+ }
148
+ async #resume() {
149
+ await this.#serializeIntent(async () => {
150
+ if (this.#intent?.status === "running")
151
+ await this.#arm();
152
+ });
153
+ await this.#reconcile();
154
+ }
155
+ async alarm() {
156
+ await this.resume();
157
+ }
158
+ #retain(operation) {
159
+ this.#state.waitUntil(operation.then(() => { }, () => { }));
160
+ return operation;
161
+ }
162
+ async #load() {
163
+ const bytes = await this.#storage.get(intentKey);
164
+ if (bytes === undefined)
165
+ return;
166
+ let value;
167
+ try {
168
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
169
+ }
170
+ catch {
171
+ throw new PublisherStorageError("sdk.publisher_storage_invalid");
172
+ }
173
+ const intent = intentSchema.safeParse(value);
174
+ if (!intent.success)
175
+ throw new PublisherStorageError("sdk.publisher_storage_invalid");
176
+ this.#intent = intent.data;
177
+ }
178
+ #serializeIntent(operation) {
179
+ const result = this.#intentQueue.then(operation);
180
+ // a corrupt initial record must remain a failure, not silently become an
181
+ // empty owner after a later request. later operation failures are retryable.
182
+ this.#intentQueue = result.then(() => { }, () => this.#load());
183
+ void this.#intentQueue.catch(() => { });
184
+ return result;
185
+ }
186
+ async #save(intent) {
187
+ await this.#storage.put(intentKey, new TextEncoder().encode(JSON.stringify(intent)));
188
+ await this.#storage.sync(intentKey);
189
+ }
190
+ async #arm() {
191
+ try {
192
+ await this.#state.storage.setAlarm(Date.now() + this.#interval);
193
+ }
194
+ catch {
195
+ throw new PublisherStorageError();
196
+ }
197
+ }
198
+ async #stop(expectedRevision) {
199
+ const failures = [];
200
+ await this.#serializeIntent(async () => {
201
+ if (expectedRevision !== undefined && expectedRevision !== this.#revision)
202
+ return;
203
+ const next = {
204
+ version: 1,
205
+ status: "stopped",
206
+ configuration: this.#intent?.configuration ?? this.#configuration,
207
+ };
208
+ try {
209
+ // persist before touching live sockets. an alarm racing this write must
210
+ // never turn a successful stop back into a publication after restart.
211
+ await this.#save(next);
212
+ }
213
+ catch {
214
+ failures.push(new PublisherStorageError());
215
+ }
216
+ this.#intent = next;
217
+ this.#revision++;
218
+ this.#running?.controller.abort();
219
+ try {
220
+ await this.#state.storage.deleteAlarm();
221
+ }
222
+ catch {
223
+ failures.push(new PublisherStorageError());
224
+ }
225
+ });
226
+ try {
227
+ await this.#reconcile();
228
+ }
229
+ catch (error) {
230
+ appendCleanupFailures(failures, error);
231
+ }
232
+ throwFailures(failures);
233
+ }
234
+ #reconcile() {
235
+ const result = this.#runtimeQueue.then(async () => {
236
+ if (this.#intent?.status !== "running") {
237
+ await this.#closeRunning();
238
+ return undefined;
239
+ }
240
+ if (this.#running?.revision === this.#revision && this.#running.publication !== undefined)
241
+ return this.#running.publication;
242
+ const revision = this.#revision;
243
+ await this.#closeRunning();
244
+ // intent can change while a retained runtime's cleanup is joining. never
245
+ // allocate a fresh controller for an intent retired during that wait.
246
+ if (this.#intent?.status !== "running" || this.#revision !== revision)
247
+ return undefined;
248
+ const running = {
249
+ revision,
250
+ controller: new AbortController(),
251
+ };
252
+ const configuration = this.#intent.configuration;
253
+ this.#running = running;
254
+ try {
255
+ const handler = await this.#options.handler(structuredClone(configuration));
256
+ if (typeof handler !== "function")
257
+ throw new TnlError("sdk.configuration_invalid");
258
+ if (running.controller.signal.aborted)
259
+ return undefined;
260
+ const identity = await this.#storage.withLock(identityKey, async () => {
261
+ const saved = await this.#storage.get(identityKey);
262
+ if (saved !== undefined)
263
+ return saved;
264
+ const imported = storageBytes(await this.#options.identity());
265
+ if (imported.byteLength === 0)
266
+ throw new PublisherStorageError("sdk.publisher_storage_invalid");
267
+ await this.#storage.put(identityKey, imported);
268
+ await this.#storage.sync(identityKey);
269
+ return imported;
270
+ }, running.controller.signal);
271
+ if (running.controller.signal.aborted) {
272
+ await this.#closeRunning();
273
+ return undefined;
274
+ }
275
+ running.deployment = await this.#options.createDeployment({
276
+ configuration: structuredClone(configuration),
277
+ identity,
278
+ storage: this.#storage,
279
+ storageHost: this.#storageHost,
280
+ signal: running.controller.signal,
281
+ });
282
+ if (running.controller.signal.aborted) {
283
+ await this.#closeRunning();
284
+ return undefined;
285
+ }
286
+ const options = {
287
+ ...structuredClone(configuration.options),
288
+ ...(this.#options.certificate === undefined
289
+ ? {}
290
+ : { certificate: this.#options.certificate }),
291
+ signal: running.controller.signal,
292
+ };
293
+ running.publication =
294
+ configuration.service === undefined
295
+ ? await running.deployment.publish(handler, options)
296
+ : await running.deployment.publish(configuration.service, handler, options);
297
+ if (running.controller.signal.aborted) {
298
+ await this.#closeRunning();
299
+ return undefined;
300
+ }
301
+ // the owner retains the deployment and handle after start() returns.
302
+ // a finite completion retires its resources; the already-durable alarm
303
+ // retries a fresh authorized runtime rather than replaying live state.
304
+ const completion = running.publication.wait().then(() => this.#retain(this.#ended(running)), async () => {
305
+ const failures = [new TnlError("sdk.publication_failed")];
306
+ try {
307
+ await this.#retain(this.#ended(running));
308
+ }
309
+ catch (error) {
310
+ appendCleanupFailures(failures, error);
311
+ }
312
+ throwFailures(failures);
313
+ });
314
+ this.#completions.set(running.publication, completion);
315
+ void completion.catch(() => { });
316
+ return running.publication;
317
+ }
318
+ catch {
319
+ const failures = [new TnlError("sdk.publication_failed")];
320
+ try {
321
+ await this.#closeRunning();
322
+ }
323
+ catch (error) {
324
+ appendCleanupFailures(failures, error);
325
+ }
326
+ throwFailures(failures);
327
+ return undefined;
328
+ }
329
+ });
330
+ this.#runtimeQueue = result.then(() => { }, () => { });
331
+ return result;
332
+ }
333
+ async #ended(running) {
334
+ const cleanup = this.#runtimeQueue.then(async () => {
335
+ if (this.#running === running)
336
+ await this.#closeRunning();
337
+ });
338
+ this.#runtimeQueue = cleanup.catch(() => { });
339
+ await cleanup;
340
+ }
341
+ async #closeRunning() {
342
+ const running = this.#running;
343
+ if (running === undefined)
344
+ return;
345
+ running.controller.abort();
346
+ const failures = [];
347
+ try {
348
+ await running.publication?.close();
349
+ }
350
+ catch {
351
+ failures.push(new TnlError("sdk.publication_cleanup_failed"));
352
+ }
353
+ try {
354
+ await running.deployment?.close();
355
+ }
356
+ catch {
357
+ failures.push(new TnlError("sdk.publication_cleanup_failed"));
358
+ }
359
+ if (failures.length === 0)
360
+ this.#running = undefined;
361
+ throwFailures(failures);
362
+ }
363
+ }
364
+ function throwFailures(failures) {
365
+ if (failures.length === 1)
366
+ throw failures[0];
367
+ if (failures.length > 1)
368
+ throw new AggregateError(failures, "publisher operation and cleanup failed");
369
+ }
370
+ function appendCleanupFailures(failures, error) {
371
+ const count = error instanceof AggregateError ? error.errors.length : 1;
372
+ for (let index = 0; index < count; index++)
373
+ failures.push(new TnlError("sdk.publication_cleanup_failed"));
374
+ }
@@ -0,0 +1,5 @@
1
+ import { DurableObjectPublisher, type DurableObjectPublisherState, type DurableObjectWasmPublisherOptions } from "./durable-object.js";
2
+ export { createDurableObjectPublisherStorage, createPublisherStorageHost, PublisherStorageError, } from "./durable-object.js";
3
+ export type { DurableObjectPublisher, DurableObjectPublisherState, DurableObjectWasmPublisherOptions, DurablePublicationConfiguration, PublisherSQLiteStorage, PublisherStorage, PublisherStorageHost, PublisherStorageErrorCode, } from "./durable-object.js";
4
+ /** workerd reuses compiled code, not live runtimes or request-scoped sockets. */
5
+ export declare function durablePublisher(state: DurableObjectPublisherState, options: DurableObjectWasmPublisherOptions): DurableObjectPublisher;
@@ -0,0 +1,11 @@
1
+ import module from "./wasm/publisher.wasm";
2
+ import { DurableObjectPublisher, } from "./durable-object.js";
3
+ import { durablePublisherDeployment } from "./internal/portable/durable-deployment.js";
4
+ export { createDurableObjectPublisherStorage, createPublisherStorageHost, PublisherStorageError, } from "./durable-object.js";
5
+ /** workerd reuses compiled code, not live runtimes or request-scoped sockets. */
6
+ export function durablePublisher(state, options) {
7
+ return new DurableObjectPublisher(state, {
8
+ ...options,
9
+ createDeployment: (context) => durablePublisherDeployment(context, module),
10
+ });
11
+ }
@@ -0,0 +1,17 @@
1
+ export type TnlErrorCode = "sdk.publication_failed" | "sdk.certificate_unavailable" | "sdk.certificate_invalid" | "sdk.publication_cleanup_failed" | "sdk.owner_conflict" | "sdk.registration_stale" | "sdk.authentication_required" | "sdk.publisher_setup_required" | "sdk.publisher_credential_file_invalid" | "sdk.configuration_invalid" | "sdk.service_unprepared" | "sdk.connection_unavailable" | "sdk.local_connection_unavailable" | "sdk.connection_server_only" | "sdk.capability_unsupported" | "sdk.wasm_unavailable" | "sdk.wasm_invalid" | "sdk.client_closed" | "sdk.client_capacity" | "sdk.workload_required" | "sdk.workload_manifest_invalid" | "sdk.workload_assertion_unavailable" | "sdk.workload_denied" | "sdk.workload_unavailable" | "sdk.workload_response_invalid" | "sdk.runtime_invalid" | "sdk.protocol_unsupported" | "sdk.project_unavailable" | "sdk.target_invalid" | "sdk.dev_unavailable" | "sdk.response_invalid" | "sdk.request_rejected" | "sdk.listener_failed" | "sdk.cleanup_failed" | "sdk.native_unsupported" | "sdk.native_missing" | "sdk.native_invalid" | "sdk.process_unavailable" | "sdk.unexpected";
2
+ type FailureClass = "invalid" | "internal" | "unavailable" | "conflict";
3
+ type Retry = "never" | "later" | "after_change";
4
+ export declare class TnlError extends Error {
5
+ readonly code: TnlErrorCode;
6
+ readonly class: FailureClass;
7
+ readonly retry: Retry;
8
+ constructor(code: TnlErrorCode, options?: ErrorOptions);
9
+ }
10
+ export declare function privateTnlError(code: TnlErrorCode, cause: unknown): TnlError;
11
+ export declare class TnlCleanupError extends TnlError {
12
+ readonly errors: readonly unknown[];
13
+ constructor(error: unknown, cleanupError: unknown);
14
+ }
15
+ export declare function classifyTnlError(error: unknown, code: TnlErrorCode): TnlError;
16
+ export declare function safeTnlMessage(error: unknown): string;
17
+ export {};