@moinulmoin/eden-runtime-cloudflare 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 (48) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +42 -0
  3. package/dist/artifact-runtime.d.ts +27 -0
  4. package/dist/artifact-runtime.js +14 -0
  5. package/dist/eden-eve-host-worker.mjs +1960 -0
  6. package/dist/eve-host-runtime.d.ts +46 -0
  7. package/dist/eve-host-runtime.js +127 -0
  8. package/dist/eve-host.d.ts +166 -0
  9. package/dist/eve-host.js +495 -0
  10. package/dist/http-host.d.ts +6 -0
  11. package/dist/http-host.js +419 -0
  12. package/dist/index.d.ts +21 -0
  13. package/dist/index.js +7 -0
  14. package/dist/model-adapter-internal.d.ts +12 -0
  15. package/dist/model-adapter-internal.js +172 -0
  16. package/dist/model-adapter.d.ts +9 -0
  17. package/dist/model-adapter.js +56 -0
  18. package/dist/model-contracts.d.ts +92 -0
  19. package/dist/model-contracts.js +2 -0
  20. package/dist/model-normalizers.d.ts +7 -0
  21. package/dist/model-normalizers.js +453 -0
  22. package/dist/session-checkpoint.d.ts +48 -0
  23. package/dist/session-checkpoint.js +300 -0
  24. package/dist/session-identity.d.ts +9 -0
  25. package/dist/session-identity.js +45 -0
  26. package/dist/session-jobs.d.ts +69 -0
  27. package/dist/session-jobs.js +427 -0
  28. package/dist/session-journal.d.ts +154 -0
  29. package/dist/session-journal.js +391 -0
  30. package/dist/session-schema.d.ts +21 -0
  31. package/dist/session-schema.js +247 -0
  32. package/dist/session-state.d.ts +165 -0
  33. package/dist/session-state.js +168 -0
  34. package/dist/session.d.ts +40 -0
  35. package/dist/session.js +792 -0
  36. package/dist/test-execution.d.ts +8 -0
  37. package/dist/test-execution.js +12 -0
  38. package/dist/test-worker.d.ts +12 -0
  39. package/dist/test-worker.js +214 -0
  40. package/dist/tool-harness.d.ts +31 -0
  41. package/dist/tool-harness.js +226 -0
  42. package/dist/turn-runner-storage.d.ts +28 -0
  43. package/dist/turn-runner-storage.js +583 -0
  44. package/dist/turn-runner-types.d.ts +112 -0
  45. package/dist/turn-runner-types.js +21 -0
  46. package/dist/turn-runner.d.ts +6 -0
  47. package/dist/turn-runner.js +370 -0
  48. package/package.json +51 -0
@@ -0,0 +1,1960 @@
1
+ // @moinulmoin/eden-runtime-cloudflare Eve host worker runtime bundle.
2
+ // Generated by scripts/bundle-eve-host.mjs; do not edit.
3
+ // Bundles @cloudflare/containers (Apache-2.0) with cloudflare:workers external.
4
+
5
+ // ../../node_modules/.pnpm/@cloudflare+containers@0.3.7/node_modules/@cloudflare/containers/dist/lib/helpers.js
6
+ function generateId(length = 9) {
7
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
8
+ const bytes = new Uint8Array(length);
9
+ crypto.getRandomValues(bytes);
10
+ let result = "";
11
+ for (let i = 0; i < length; i++) {
12
+ result += alphabet[bytes[i] % alphabet.length];
13
+ }
14
+ return result;
15
+ }
16
+ function parseTimeExpression(timeExpression) {
17
+ if (typeof timeExpression === "number") {
18
+ return timeExpression;
19
+ }
20
+ if (typeof timeExpression === "string") {
21
+ const match = timeExpression.match(/^(\d+)([smh])$/);
22
+ if (!match) {
23
+ throw new Error(`invalid time expression ${timeExpression}`);
24
+ }
25
+ const value = parseInt(match[1]);
26
+ const unit = match[2];
27
+ switch (unit) {
28
+ case "s":
29
+ return value;
30
+ case "m":
31
+ return value * 60;
32
+ case "h":
33
+ return value * 60 * 60;
34
+ default:
35
+ throw new Error(`unknown time unit ${unit}`);
36
+ }
37
+ }
38
+ throw new Error(`invalid type for a time expression: ${typeof timeExpression}`);
39
+ }
40
+
41
+ // ../../node_modules/.pnpm/@cloudflare+containers@0.3.7/node_modules/@cloudflare/containers/dist/lib/container.js
42
+ import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
43
+ var NO_CONTAINER_INSTANCE_ERROR = "there is no container instance that can be provided to this durable object";
44
+ var RATE_LIMITED_ERROR = "you are requesting too many containers per second";
45
+ var RUNTIME_SIGNALLED_ERROR = "runtime signalled the container to exit:";
46
+ var UNEXPECTED_EXIT_ERROR = "container exited with unexpected exit code:";
47
+ var NOT_LISTENING_ERROR = "the container is not listening";
48
+ var CONTAINER_STATE_KEY = "__CF_CONTAINER_STATE";
49
+ var OUTBOUND_CONFIGURATION_KEY = "OUTBOUND_CONFIGURATION";
50
+ var MAX_ALARM_RETRIES = 3;
51
+ var PING_TIMEOUT_MS = 5e3;
52
+ var DEFAULT_SLEEP_AFTER = "10m";
53
+ var INSTANCE_POLL_INTERVAL_MS = 300;
54
+ var TIMEOUT_TO_GET_CONTAINER_MS = 8e3;
55
+ var TIMEOUT_TO_GET_PORTS_MS = 2e4;
56
+ var FALLBACK_PORT_TO_CHECK = 33;
57
+ var outboundHandlersRegistry = /* @__PURE__ */ new Map();
58
+ var defaultOutboundHandlerNameRegistry = /* @__PURE__ */ new Map();
59
+ var outboundByHostRegistry = /* @__PURE__ */ new Map();
60
+ var signalToNumbers = {
61
+ SIGINT: 2,
62
+ SIGTERM: 15,
63
+ SIGKILL: 9
64
+ };
65
+ function isErrorOfType(e, matchingString) {
66
+ const errorString = e instanceof Error ? e.message : String(e);
67
+ return errorString.toLowerCase().includes(matchingString);
68
+ }
69
+ var isNoInstanceError = (error) => isErrorOfType(error, NO_CONTAINER_INSTANCE_ERROR);
70
+ var isRateLimitedError = (error) => isErrorOfType(error, RATE_LIMITED_ERROR);
71
+ var isRuntimeSignalledError = (error) => isErrorOfType(error, RUNTIME_SIGNALLED_ERROR);
72
+ var isNotListeningError = (error) => isErrorOfType(error, NOT_LISTENING_ERROR);
73
+ var isContainerExitNonZeroError = (error) => isErrorOfType(error, UNEXPECTED_EXIT_ERROR);
74
+ function getExitCodeFromError(error) {
75
+ if (!(error instanceof Error)) {
76
+ return null;
77
+ }
78
+ if (isRuntimeSignalledError(error)) {
79
+ return +error.message.toLowerCase().slice(error.message.toLowerCase().indexOf(RUNTIME_SIGNALLED_ERROR) + RUNTIME_SIGNALLED_ERROR.length + 1);
80
+ }
81
+ if (isContainerExitNonZeroError(error)) {
82
+ return +error.message.toLowerCase().slice(error.message.toLowerCase().indexOf(UNEXPECTED_EXIT_ERROR) + UNEXPECTED_EXIT_ERROR.length + 1);
83
+ }
84
+ return null;
85
+ }
86
+ function addTimeoutSignal(existingSignal, timeoutMs) {
87
+ const controller = new AbortController();
88
+ if (existingSignal?.aborted) {
89
+ controller.abort();
90
+ return controller.signal;
91
+ }
92
+ existingSignal?.addEventListener("abort", () => controller.abort());
93
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
94
+ controller.signal.addEventListener("abort", () => clearTimeout(timeoutId));
95
+ return controller.signal;
96
+ }
97
+ var ContainerState = class {
98
+ storage;
99
+ status;
100
+ constructor(storage) {
101
+ this.storage = storage;
102
+ }
103
+ async setRunning() {
104
+ await this.setStatusAndupdate("running");
105
+ }
106
+ async setHealthy() {
107
+ await this.setStatusAndupdate("healthy");
108
+ }
109
+ async setStopping() {
110
+ await this.setStatusAndupdate("stopping");
111
+ }
112
+ async setStopped() {
113
+ await this.setStatusAndupdate("stopped");
114
+ }
115
+ async setStoppedIfUnchanged(previousState) {
116
+ if (this.status !== previousState) {
117
+ return;
118
+ }
119
+ await this.setStopped();
120
+ }
121
+ async setStoppedWithCode(exitCode) {
122
+ this.status = { status: "stopped_with_code", lastChange: Date.now(), exitCode };
123
+ await this.update();
124
+ }
125
+ async getState() {
126
+ if (!this.status) {
127
+ const state = await this.storage.get(CONTAINER_STATE_KEY);
128
+ if (!state) {
129
+ this.status = {
130
+ status: "stopped",
131
+ lastChange: Date.now()
132
+ };
133
+ await this.update();
134
+ } else {
135
+ this.status = state;
136
+ }
137
+ }
138
+ return this.status;
139
+ }
140
+ async setStatusAndupdate(status) {
141
+ this.status = { status, lastChange: Date.now() };
142
+ await this.update();
143
+ }
144
+ async update() {
145
+ if (!this.status)
146
+ throw new Error("status should be init");
147
+ await this.storage.put(CONTAINER_STATE_KEY, this.status);
148
+ }
149
+ };
150
+ var Container = class extends DurableObject {
151
+ static get outboundByHost() {
152
+ return outboundByHostRegistry.get(this.name);
153
+ }
154
+ static set outboundByHost(handlers) {
155
+ outboundByHostRegistry.set(this.name, handlers);
156
+ }
157
+ static get outboundHandlers() {
158
+ return outboundHandlersRegistry.get(this.name);
159
+ }
160
+ static set outboundHandlers(handlers) {
161
+ const existing = outboundHandlersRegistry.get(this.name) ?? {};
162
+ outboundHandlersRegistry.set(this.name, { ...existing, ...handlers });
163
+ }
164
+ static get outbound() {
165
+ const handlerName = defaultOutboundHandlerNameRegistry.get(this.name);
166
+ if (!handlerName)
167
+ return void 0;
168
+ return outboundHandlersRegistry.get(this.name)?.[handlerName];
169
+ }
170
+ static set outbound(handler) {
171
+ const key = "__outbound__";
172
+ const existing = outboundHandlersRegistry.get(this.name) ?? {};
173
+ outboundHandlersRegistry.set(this.name, { ...existing, [key]: handler });
174
+ defaultOutboundHandlerNameRegistry.set(this.name, key);
175
+ }
176
+ static get outboundProxies() {
177
+ return this.outboundHandlers;
178
+ }
179
+ static set outboundProxies(handlers) {
180
+ this.outboundHandlers = handlers;
181
+ }
182
+ static get outboundProxy() {
183
+ return this.outbound;
184
+ }
185
+ static set outboundProxy(handler) {
186
+ this.outbound = handler;
187
+ }
188
+ // =========================
189
+ // Public Attributes
190
+ // =========================
191
+ // Default port for the container (undefined means no default port)
192
+ defaultPort;
193
+ // Required ports that should be checked for availability during container startup
194
+ // Override this in your subclass to specify ports that must be ready
195
+ requiredPorts;
196
+ // Timeout after which the container will sleep if no activity
197
+ // The signal sent to the container by default is a SIGTERM.
198
+ // The container won't get a SIGKILL if this threshold is triggered.
199
+ sleepAfter = DEFAULT_SLEEP_AFTER;
200
+ // Container configuration properties
201
+ // Set these properties directly in your container instance
202
+ envVars = {};
203
+ entrypoint;
204
+ enableInternet = true;
205
+ labels = {};
206
+ // When true, outbound HTTPS traffic from the container will be intercepted.
207
+ // The container must trust /etc/cloudflare/certs/cloudflare-containers-ca.crt
208
+ interceptHttps = false;
209
+ // Hosts that are allowed to access the internet, even when enableInternet is false.
210
+ // Useful for allowing specific domains on a per-host basis.
211
+ allowedHosts;
212
+ // Hosts that are denied internet access, even when enableInternet is true.
213
+ // Also blocks hosts from being handled by the catch-all outbound handler.
214
+ deniedHosts;
215
+ // pingEndpoint is the host and path value that the class will use to send a request to the container and check if the
216
+ // instance is ready.
217
+ //
218
+ // The user does not have to implement this route by any means,
219
+ // but it's still useful if you want to control the path that
220
+ // the Container class uses to send HTTP requests to.
221
+ pingEndpoint = "ping";
222
+ applyOutboundInterceptionPromise = Promise.resolve();
223
+ usingInterception = false;
224
+ // =========================
225
+ // PUBLIC INTERFACE
226
+ // =========================
227
+ constructor(ctx, env, options) {
228
+ super(ctx, env);
229
+ if (ctx.container === void 0) {
230
+ throw new Error("Containers have not been enabled for this Durable Object class. Have you correctly setup your Wrangler config? More info: https://developers.cloudflare.com/containers/get-started/#configuration");
231
+ }
232
+ this.state = new ContainerState(this.ctx.storage);
233
+ const persistedOutboundConfiguration = this.restoreOutboundConfiguration();
234
+ this.ctx.blockConcurrencyWhile(async () => {
235
+ await this.scheduleNextAlarm();
236
+ this.renewActivityTimeout();
237
+ const ctor = this.constructor;
238
+ if (persistedOutboundConfiguration !== void 0 || ctor.outboundByHost !== void 0 || ctor.outbound !== void 0 || ctor.outboundHandlers !== void 0 || this.effectiveAllowedHosts !== void 0 || this.effectiveDeniedHosts !== void 0) {
239
+ this.usingInterception = true;
240
+ }
241
+ if (this.container.running) {
242
+ this.applyOutboundInterceptionPromise = this.applyOutboundInterception();
243
+ }
244
+ });
245
+ this.container = ctx.container;
246
+ if (options) {
247
+ if (options.defaultPort !== void 0)
248
+ this.defaultPort = options.defaultPort;
249
+ if (options.sleepAfter !== void 0)
250
+ this.sleepAfter = options.sleepAfter;
251
+ if (options.envVars !== void 0)
252
+ this.envVars = options.envVars;
253
+ if (options.entrypoint !== void 0)
254
+ this.entrypoint = options.entrypoint;
255
+ if (options.enableInternet !== void 0)
256
+ this.enableInternet = options.enableInternet;
257
+ }
258
+ this.sql`
259
+ CREATE TABLE IF NOT EXISTS container_schedules (
260
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
261
+ callback TEXT NOT NULL,
262
+ payload TEXT,
263
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed')),
264
+ time INTEGER NOT NULL,
265
+ delayInSeconds INTEGER,
266
+ created_at INTEGER DEFAULT (unixepoch())
267
+ )
268
+ `;
269
+ if (this.container.running) {
270
+ this.monitor = this.container.monitor();
271
+ this.setupMonitorCallbacks();
272
+ }
273
+ }
274
+ /**
275
+ * Gets the current state of the container
276
+ * @returns Promise<State>
277
+ */
278
+ async getState() {
279
+ return { ...await this.state.getState() };
280
+ }
281
+ // ====================================
282
+ // OUTBOUND INTERCEPTION CONFIG
283
+ // ====================================
284
+ /**
285
+ * Set the catch-all outbound handler to a named method from `outboundHandlers`.
286
+ * Overrides the default `outbound` at runtime via ContainerProxy props.
287
+ *
288
+ * @param methodName - Name of a method defined in `static outboundHandlers`
289
+ * @param params - Optional params passed to the handler as `ctx.params`
290
+ * @throws Error if the method name is not found in `outboundHandlers`
291
+ */
292
+ async setOutboundHandler(methodName, ...paramsArg) {
293
+ this.validateOutboundHandlerMethodName(methodName);
294
+ this.outboundHandlerOverride = paramsArg.length === 0 ? { method: methodName } : { method: methodName, params: paramsArg[0] };
295
+ await this.refreshOutboundInterception();
296
+ }
297
+ /**
298
+ * Add or override a hostname-specific outbound handler at runtime,
299
+ * referencing a named method from `outboundHandlers`.
300
+ * Overrides any matching entry in `static outboundByHost` for this hostname.
301
+ *
302
+ * @param hostname - The hostname or ip:port to intercept (e.g. `'google.com'`)
303
+ * @param methodName - Name of a method defined in `static outboundHandlers`
304
+ * @param params - Optional params passed to the handler as `ctx.params`
305
+ * @throws Error if the method name is not found in `outboundHandlers`
306
+ */
307
+ async setOutboundByHost(hostname, methodName, ...paramsArg) {
308
+ this.validateOutboundHandlerMethodName(methodName);
309
+ this.outboundByHostOverrides[hostname] = paramsArg.length === 0 ? { method: methodName } : { method: methodName, params: paramsArg[0] };
310
+ await this.refreshOutboundInterception();
311
+ }
312
+ /**
313
+ * Remove a runtime hostname override added via `setOutboundByHost`.
314
+ * The default handler from `static outboundByHost` (if any) will be used again.
315
+ *
316
+ * @param hostname - The hostname or ip:port to stop overriding
317
+ */
318
+ async removeOutboundByHost(hostname) {
319
+ delete this.outboundByHostOverrides[hostname];
320
+ await this.refreshOutboundInterception();
321
+ }
322
+ /**
323
+ * Replace all runtime hostname overrides at once.
324
+ * Each value may be either a method name or an object with `method` and `params`.
325
+ *
326
+ * @param handlers - Record mapping hostnames to handler configs in `outboundHandlers`
327
+ * @throws Error if any method name is not found in `outboundHandlers`
328
+ */
329
+ async setOutboundByHosts(handlers) {
330
+ for (const handler of Object.values(handlers)) {
331
+ const methodName = typeof handler === "string" ? handler : handler.method;
332
+ this.validateOutboundHandlerMethodName(methodName);
333
+ }
334
+ this.outboundByHostOverrides = Object.fromEntries(Object.entries(handlers).map(([hostname, handler]) => [
335
+ hostname,
336
+ typeof handler === "string" ? { method: handler } : handler
337
+ ]));
338
+ await this.refreshOutboundInterception();
339
+ }
340
+ // ====================================
341
+ // ALLOWED / DENIED HOSTS CONFIG
342
+ // ====================================
343
+ /**
344
+ * Replace all allowed hosts at runtime.
345
+ * Allowed hosts get internet access even when `enableInternet` is false.
346
+ *
347
+ * @param hosts - Array of hostnames to allow (e.g. `['api.stripe.com', 'example.com']`)
348
+ */
349
+ async setAllowedHosts(hosts) {
350
+ this.allowedHostsOverride = [...hosts];
351
+ this.usingInterception = true;
352
+ await this.refreshOutboundInterception();
353
+ }
354
+ /**
355
+ * Replace all denied hosts at runtime.
356
+ * Denied hosts are blocked unconditionally, even when `enableInternet` is true
357
+ * or a catch-all outbound handler is set.
358
+ *
359
+ * @param hosts - Array of hostnames to deny (e.g. `['evil.com', 'blocked.org']`)
360
+ */
361
+ async setDeniedHosts(hosts) {
362
+ this.deniedHostsOverride = [...hosts];
363
+ this.usingInterception = true;
364
+ await this.refreshOutboundInterception();
365
+ }
366
+ /**
367
+ * Add a single hostname to the allowed hosts list at runtime.
368
+ *
369
+ * @param hostname - The hostname to allow (e.g. `'api.stripe.com'`)
370
+ */
371
+ async allowHost(hostname) {
372
+ const effective = this.effectiveAllowedHosts ?? [];
373
+ if (!effective.includes(hostname)) {
374
+ this.allowedHostsOverride = [...effective, hostname];
375
+ }
376
+ this.usingInterception = true;
377
+ await this.refreshOutboundInterception();
378
+ }
379
+ /**
380
+ * Add a single hostname to the denied hosts list at runtime.
381
+ *
382
+ * @param hostname - The hostname to deny (e.g. `'evil.com'`)
383
+ */
384
+ async denyHost(hostname) {
385
+ const effective = this.effectiveDeniedHosts ?? [];
386
+ if (!effective.includes(hostname)) {
387
+ this.deniedHostsOverride = [...effective, hostname];
388
+ }
389
+ this.usingInterception = true;
390
+ await this.refreshOutboundInterception();
391
+ }
392
+ /**
393
+ * Remove a hostname from the allowed hosts list.
394
+ *
395
+ * @param hostname - The hostname to remove from the allow list
396
+ */
397
+ async removeAllowedHost(hostname) {
398
+ this.allowedHostsOverride = (this.effectiveAllowedHosts ?? []).filter((h) => h !== hostname);
399
+ await this.refreshOutboundInterception();
400
+ }
401
+ /**
402
+ * Remove a hostname from the denied hosts list.
403
+ *
404
+ * @param hostname - The hostname to remove from the deny list
405
+ */
406
+ async removeDeniedHost(hostname) {
407
+ this.deniedHostsOverride = (this.effectiveDeniedHosts ?? []).filter((h) => h !== hostname);
408
+ await this.refreshOutboundInterception();
409
+ }
410
+ // ==========================
411
+ // CONTAINER STARTING
412
+ // ==========================
413
+ /**
414
+ * Start the container if it's not running and set up monitoring and lifecycle hooks,
415
+ * without waiting for ports to be ready.
416
+ *
417
+ * It will automatically retry if the container fails to start, using the specified waitOptions
418
+ *
419
+ *
420
+ * @example
421
+ * await this.start({
422
+ * envVars: { DEBUG: 'true', NODE_ENV: 'development' },
423
+ * entrypoint: ['npm', 'run', 'dev'],
424
+ * enableInternet: false,
425
+ * labels: { tenant: 'acme', env: 'prod' },
426
+ * });
427
+ *
428
+ * @param startOptions - Override `envVars`, `entrypoint`, `enableInternet` and `labels` on a per-instance basis
429
+ * @param waitOptions - Optional wait configuration with abort signal for cancellation. Default ~8s timeout.
430
+ * @returns A promise that resolves when the container start command has been issued
431
+ * @throws Error if no container context is available or if all start attempts fail
432
+ */
433
+ async start(startOptions, waitOptions) {
434
+ const portToCheck = waitOptions?.portToCheck ?? this.defaultPort ?? (this.requiredPorts ? this.requiredPorts[0] : FALLBACK_PORT_TO_CHECK);
435
+ const pollInterval = waitOptions?.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
436
+ await this.startContainerIfNotRunning({
437
+ signal: waitOptions?.signal,
438
+ waitInterval: pollInterval,
439
+ retries: waitOptions?.retries ?? Math.ceil(TIMEOUT_TO_GET_CONTAINER_MS / pollInterval),
440
+ portToCheck
441
+ }, startOptions);
442
+ this.setupMonitorCallbacks();
443
+ await this.ctx.blockConcurrencyWhile(async () => {
444
+ await this.onStart();
445
+ });
446
+ }
447
+ async startAndWaitForPorts(portsOrArgs, cancellationOptions, startOptions) {
448
+ let ports;
449
+ let resolvedCancellationOptions;
450
+ let resolvedStartOptions;
451
+ if (typeof portsOrArgs === "object" && portsOrArgs !== null && !Array.isArray(portsOrArgs)) {
452
+ ports = portsOrArgs.ports;
453
+ resolvedCancellationOptions = portsOrArgs.cancellationOptions;
454
+ resolvedStartOptions = portsOrArgs.startOptions;
455
+ } else {
456
+ ports = portsOrArgs;
457
+ resolvedCancellationOptions = cancellationOptions;
458
+ resolvedStartOptions = startOptions;
459
+ }
460
+ const portsToCheck = await this.getPortsToCheck(ports);
461
+ await this.syncPendingStoppedEvents();
462
+ resolvedCancellationOptions ??= {};
463
+ const containerGetTimeout = resolvedCancellationOptions.instanceGetTimeoutMS ?? TIMEOUT_TO_GET_CONTAINER_MS;
464
+ const pollInterval = resolvedCancellationOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
465
+ const containerGetRetries = Math.ceil(containerGetTimeout / pollInterval);
466
+ const waitOptions = {
467
+ signal: resolvedCancellationOptions.abort,
468
+ retries: containerGetRetries,
469
+ waitInterval: pollInterval,
470
+ portToCheck: portsToCheck[0]
471
+ };
472
+ const triesUsed = await this.startContainerIfNotRunning(waitOptions, resolvedStartOptions);
473
+ const totalPortReadyTries = Math.ceil((resolvedCancellationOptions.portReadyTimeoutMS ?? TIMEOUT_TO_GET_PORTS_MS) / pollInterval);
474
+ let triesLeft = totalPortReadyTries - triesUsed;
475
+ for (const port of portsToCheck) {
476
+ triesLeft = await this.waitForPort({
477
+ signal: resolvedCancellationOptions.abort,
478
+ waitInterval: pollInterval,
479
+ retries: triesLeft,
480
+ portToCheck: port
481
+ });
482
+ }
483
+ this.setupMonitorCallbacks();
484
+ await this.ctx.blockConcurrencyWhile(async () => {
485
+ await this.state.setHealthy();
486
+ await this.onStart();
487
+ });
488
+ }
489
+ /**
490
+ *
491
+ * Waits for a specified port to be ready
492
+ *
493
+ * Returns the number of tries used to get the port, or throws if it couldn't get the port within the specified retry limits.
494
+ *
495
+ * @param waitOptions -
496
+ * - `portToCheck`: The port number to check
497
+ * - `abort`: Optional AbortSignal to cancel waiting
498
+ * - `retries`: Number of retries before giving up (default: TRIES_TO_GET_PORTS)
499
+ * - `waitInterval`: Interval between retries in milliseconds (default: INSTANCE_POLL_INTERVAL_MS)
500
+ */
501
+ async waitForPort(waitOptions) {
502
+ const port = waitOptions.portToCheck;
503
+ const tcpPort = this.container.getTcpPort(port);
504
+ const abortedSignal = new Promise((res) => {
505
+ waitOptions.signal?.addEventListener("abort", () => {
506
+ res(true);
507
+ });
508
+ });
509
+ const pollInterval = waitOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
510
+ const tries = waitOptions.retries ?? Math.ceil(TIMEOUT_TO_GET_PORTS_MS / pollInterval);
511
+ for (let i = 0; i < tries; i++) {
512
+ try {
513
+ const combinedSignal = addTimeoutSignal(waitOptions.signal, PING_TIMEOUT_MS);
514
+ await tcpPort.fetch(`http://${this.pingEndpoint}`, { signal: combinedSignal });
515
+ break;
516
+ } catch (e) {
517
+ const errorMessage = e instanceof Error ? e.message : String(e);
518
+ if (!this.container.running) {
519
+ try {
520
+ await this.onError(new Error(`Container crashed while checking for ports, did you start the container and setup the entrypoint correctly?`));
521
+ } catch {
522
+ }
523
+ throw e;
524
+ }
525
+ if (i === tries - 1) {
526
+ try {
527
+ await this.onError(`Failed to verify port ${port} is available after ${(i + 1) * pollInterval}ms, last error: ${errorMessage}`);
528
+ } catch {
529
+ }
530
+ throw e;
531
+ }
532
+ await Promise.any([
533
+ new Promise((resolve) => setTimeout(resolve, pollInterval)),
534
+ abortedSignal
535
+ ]);
536
+ if (waitOptions.signal?.aborted) {
537
+ throw new Error("Container request aborted.", { cause: e });
538
+ }
539
+ }
540
+ }
541
+ return tries;
542
+ }
543
+ // =======================
544
+ // LIFECYCLE HOOKS
545
+ // =======================
546
+ /**
547
+ * Send a signal to the container.
548
+ * @param signal - The signal to send to the container (default: 15 for SIGTERM)
549
+ */
550
+ async stop(signal = "SIGTERM") {
551
+ if (this.container.running) {
552
+ this.container.signal(typeof signal === "string" ? signalToNumbers[signal] : signal);
553
+ }
554
+ await this.syncPendingStoppedEvents();
555
+ }
556
+ /**
557
+ * Destroys the container with a SIGKILL. Triggers onStop.
558
+ */
559
+ async destroy() {
560
+ await this.container.destroy();
561
+ }
562
+ /**
563
+ * Lifecycle method called when container starts successfully
564
+ * Override this method in subclasses to handle container start events
565
+ */
566
+ onStart() {
567
+ }
568
+ /**
569
+ * Lifecycle method called when container shuts down
570
+ * Override this method in subclasses to handle Container stopped events
571
+ * @param params - Object containing exitCode and reason for the stop
572
+ */
573
+ onStop(params) {
574
+ void params;
575
+ }
576
+ /**
577
+ * Lifecycle method called when the container is running, and the activity timeout
578
+ * expiration (set by `sleepAfter`) has been reached.
579
+ *
580
+ * If you want to shutdown the container, you should call this.stop() here
581
+ *
582
+ * By default, this method calls `this.stop()`
583
+ */
584
+ async onActivityExpired() {
585
+ console.log("Activity expired, signalling container to stop");
586
+ if (!this.container.running) {
587
+ return;
588
+ }
589
+ await this.stop();
590
+ }
591
+ /**
592
+ * Error handler for container errors
593
+ * Override this method in subclasses to handle container errors
594
+ * @param error - The error that occurred
595
+ * @returns Can return any value or throw the error
596
+ */
597
+ onError(error) {
598
+ console.error("Container error:", error);
599
+ throw error;
600
+ }
601
+ /**
602
+ * Renew the container's activity timeout
603
+ *
604
+ * Call this method whenever there is activity on the container
605
+ */
606
+ renewActivityTimeout() {
607
+ const timeoutInMs = parseTimeExpression(this.sleepAfter) * 1e3;
608
+ this.sleepAfterMs = Date.now() + timeoutInMs;
609
+ }
610
+ /**
611
+ * Decrement the inflight request counter.
612
+ * When the counter transitions to 0, renew the activity timeout so the
613
+ * inactivity window starts fresh from the moment the last request completes.
614
+ */
615
+ decrementInflight() {
616
+ this.inflightRequests = Math.max(0, this.inflightRequests - 1);
617
+ if (this.inflightRequests === 0) {
618
+ this.renewActivityTimeout();
619
+ }
620
+ }
621
+ // ==================
622
+ // SCHEDULING
623
+ // ==================
624
+ /**
625
+ * Schedule a task to be executed in the future.
626
+ *
627
+ * We strongly recommend using this instead of the `alarm` handler.
628
+ *
629
+ * @template T Type of the payload data
630
+ * @param when When to execute the task (Date object or number of seconds delay)
631
+ * @param callback Name of the method to call
632
+ * @param payload Data to pass to the callback
633
+ * @returns Schedule object representing the scheduled task
634
+ */
635
+ async schedule(when, callback, payload) {
636
+ const id = generateId(9);
637
+ if (typeof callback !== "string") {
638
+ throw new Error("Callback must be a string (method name)");
639
+ }
640
+ if (typeof this[callback] !== "function") {
641
+ throw new Error(`this.${callback} is not a function`);
642
+ }
643
+ if (when instanceof Date) {
644
+ const timestamp = Math.floor(when.getTime() / 1e3);
645
+ this.sql`
646
+ INSERT OR REPLACE INTO container_schedules (id, callback, payload, type, time)
647
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
648
+ `;
649
+ await this.scheduleNextAlarm();
650
+ return {
651
+ taskId: id,
652
+ callback,
653
+ payload,
654
+ time: timestamp,
655
+ type: "scheduled"
656
+ };
657
+ }
658
+ if (typeof when === "number") {
659
+ const time = Math.floor(Date.now() / 1e3 + when);
660
+ this.sql`
661
+ INSERT OR REPLACE INTO container_schedules (id, callback, payload, type, delayInSeconds, time)
662
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${time})
663
+ `;
664
+ await this.scheduleNextAlarm();
665
+ return {
666
+ taskId: id,
667
+ callback,
668
+ payload,
669
+ delayInSeconds: when,
670
+ time,
671
+ type: "delayed"
672
+ };
673
+ }
674
+ throw new Error("Invalid schedule type. 'when' must be a Date or number of seconds");
675
+ }
676
+ // ============
677
+ // HTTP
678
+ // ============
679
+ /**
680
+ * Send a request to the container (HTTP or WebSocket) using standard fetch API signature
681
+ *
682
+ * This method handles HTTP requests to the container.
683
+ *
684
+ * WebSocket requests done outside the DO won't work until https://github.com/cloudflare/workerd/issues/2319 is addressed.
685
+ * Until then, please use `switchPort` + `fetch()`.
686
+ *
687
+ * Method supports multiple signatures to match standard fetch API:
688
+ * - containerFetch(request: Request, port?: number)
689
+ * - containerFetch(url: string | URL, init?: RequestInit, port?: number)
690
+ *
691
+ * Starts the container if not already running, and waits for the target port to be ready.
692
+ *
693
+ * @returns A Response from the container
694
+ */
695
+ async containerFetch(requestOrUrl, portOrInit, portParam) {
696
+ const { request, port } = this.requestAndPortFromContainerFetchArgs(requestOrUrl, portOrInit, portParam);
697
+ const state = await this.state.getState();
698
+ if (!this.container.running || state.status !== "healthy") {
699
+ try {
700
+ await this.startAndWaitForPorts(port, { abort: request.signal });
701
+ } catch (e) {
702
+ if (isNoInstanceError(e)) {
703
+ return new Response("There is no Container instance available at this time.\nThis is likely because you have reached your max concurrent instance count (set in wrangler config) or are you currently provisioning the Container.\nIf you are deploying your Container for the first time, check your dashboard to see provisioning status, this may take a few minutes.", { status: 503 });
704
+ }
705
+ if (isRateLimitedError(e)) {
706
+ return new Response(e instanceof Error ? e.message : String(e), { status: 429 });
707
+ }
708
+ return new Response(`Failed to start container: ${e instanceof Error ? e.message : String(e)}`, {
709
+ status: 500
710
+ });
711
+ }
712
+ }
713
+ const tcpPort = this.container.getTcpPort(port);
714
+ const containerUrl = request.url.replace("https:", "http:");
715
+ this.inflightRequests++;
716
+ try {
717
+ this.renewActivityTimeout();
718
+ const res = await tcpPort.fetch(containerUrl, request);
719
+ if (res.webSocket !== null) {
720
+ const containerWs = res.webSocket;
721
+ const [client, server] = Object.values(new WebSocketPair());
722
+ let settled = false;
723
+ const settleInflight = () => {
724
+ if (!settled) {
725
+ settled = true;
726
+ this.decrementInflight();
727
+ }
728
+ };
729
+ containerWs.accept();
730
+ server.accept();
731
+ server.addEventListener("message", async (event) => {
732
+ this.renewActivityTimeout();
733
+ try {
734
+ const data = event.data instanceof Blob ? await event.data.arrayBuffer() : event.data;
735
+ containerWs.send(data);
736
+ } catch {
737
+ server.close(1011, "Failed to forward message to container");
738
+ }
739
+ });
740
+ containerWs.addEventListener("message", async (event) => {
741
+ this.renewActivityTimeout();
742
+ try {
743
+ const data = event.data instanceof Blob ? await event.data.arrayBuffer() : event.data;
744
+ server.send(data);
745
+ } catch {
746
+ containerWs.close(1011, "Failed to forward message to client");
747
+ }
748
+ });
749
+ server.addEventListener("close", (event) => {
750
+ settleInflight();
751
+ const code = event.code === 1005 || event.code === 1006 ? 1e3 : event.code;
752
+ containerWs.close(code, event.reason);
753
+ });
754
+ containerWs.addEventListener("close", (event) => {
755
+ settleInflight();
756
+ const code = event.code === 1005 || event.code === 1006 ? 1e3 : event.code;
757
+ server.close(code, event.reason);
758
+ });
759
+ server.addEventListener("error", () => {
760
+ settleInflight();
761
+ containerWs.close(1011, "Client WebSocket error");
762
+ });
763
+ containerWs.addEventListener("error", () => {
764
+ settleInflight();
765
+ server.close(1011, "Container WebSocket error");
766
+ });
767
+ return new Response(null, { status: res.status, webSocket: client, headers: res.headers });
768
+ }
769
+ if (res.body !== null) {
770
+ const { readable, writable } = new IdentityTransformStream();
771
+ res.body?.pipeTo(writable).finally(() => {
772
+ this.decrementInflight();
773
+ });
774
+ return new Response(readable, res);
775
+ }
776
+ this.decrementInflight();
777
+ return res;
778
+ } catch (e) {
779
+ this.decrementInflight();
780
+ if (!(e instanceof Error)) {
781
+ throw e;
782
+ }
783
+ if (e.message.includes("Network connection lost.")) {
784
+ return new Response("Container suddenly disconnected, try again", { status: 500 });
785
+ }
786
+ console.error(`Error proxying request to container ${this.ctx.id}:`, e);
787
+ return new Response(`Error proxying request to container: ${e instanceof Error ? e.message : String(e)}`, { status: 500 });
788
+ }
789
+ }
790
+ /**
791
+ *
792
+ * Fetch handler on the Container class.
793
+ * By default this forwards all requests to the container by calling `containerFetch`.
794
+ * Use `switchPort` to specify which port on the container to target, or this will use `defaultPort`.
795
+ * @param request The request to handle
796
+ */
797
+ async fetch(request) {
798
+ if (this.defaultPort === void 0 && !request.headers.has("cf-container-target-port")) {
799
+ throw new Error("No port configured for this container. Set the `defaultPort` in your Container subclass, or specify a port with `container.fetch(switchPort(request, port))`.");
800
+ }
801
+ let portValue = this.defaultPort;
802
+ if (request.headers.has("cf-container-target-port")) {
803
+ const portFromHeaders = parseInt(request.headers.get("cf-container-target-port") ?? "");
804
+ if (isNaN(portFromHeaders)) {
805
+ throw new Error("port value from switchPort is not a number");
806
+ } else {
807
+ portValue = portFromHeaders;
808
+ }
809
+ }
810
+ return await this.containerFetch(request, portValue);
811
+ }
812
+ // ===============================
813
+ // ===============================
814
+ // PRIVATE METHODS & ATTRS
815
+ // ===============================
816
+ // ===============================
817
+ // ==========================
818
+ // PRIVATE ATTRIBUTES
819
+ // ==========================
820
+ container;
821
+ // onStopCalled will be true when we are in the middle of an onStop call
822
+ onStopCalled = false;
823
+ state;
824
+ monitor;
825
+ // Coalesces concurrent calls to startContainerIfNotRunning so we never
826
+ // call `this.container.start()` twice. Without this guard, two requests
827
+ // racing the readiness path can both pass the `if (this.container.running)`
828
+ // early-return (each yielding the DO input gate at storage awaits) and
829
+ // both reach the synchronous workerd `start()`, causing the second to
830
+ // throw "start() cannot be called on a container that is already running."
831
+ // See https://github.com/cloudflare/containers/issues/173.
832
+ startInFlight;
833
+ monitoredPromise;
834
+ sleepAfterMs = 0;
835
+ inflightRequests = 0;
836
+ // Outbound interception runtime overrides (passed through ContainerProxy props)
837
+ outboundByHostOverrides = {};
838
+ outboundHandlerOverride;
839
+ // Only set when the user calls setAllowedHosts/setDeniedHosts at runtime
840
+ allowedHostsOverride;
841
+ deniedHostsOverride;
842
+ // The runtime does not expose a way to remove outbound interceptions yet, so
843
+ // once we promote an instance to intercept-all we must keep using it.
844
+ hasInterceptAllRegistration = false;
845
+ // ==========================
846
+ // GENERAL HELPERS
847
+ // ==========================
848
+ /**
849
+ * Validates that a method name exists in the outboundHandlers registry for this class.
850
+ * @throws Error if the method name is not found
851
+ */
852
+ validateOutboundHandlerMethodName(methodName) {
853
+ const handlers = outboundHandlersRegistry.get(this.constructor.name);
854
+ if (!handlers || !(methodName in handlers)) {
855
+ throw new Error(`Outbound handler method '${methodName}' not found in outboundHandlers for ${this.constructor.name}`);
856
+ }
857
+ }
858
+ get effectiveAllowedHosts() {
859
+ return this.allowedHostsOverride ?? this.allowedHosts;
860
+ }
861
+ get effectiveDeniedHosts() {
862
+ return this.deniedHostsOverride ?? this.deniedHosts;
863
+ }
864
+ getOutboundConfiguration() {
865
+ return {
866
+ outboundByHostOverrides: Object.keys(this.outboundByHostOverrides).length > 0 ? this.outboundByHostOverrides : void 0,
867
+ outboundHandlerOverride: this.outboundHandlerOverride,
868
+ allowedHosts: this.effectiveAllowedHosts,
869
+ deniedHosts: this.effectiveDeniedHosts,
870
+ hasInterceptAllRegistration: this.hasInterceptAllRegistration || void 0
871
+ };
872
+ }
873
+ persistOutboundConfiguration(configuration) {
874
+ this.ctx.storage.kv.put(OUTBOUND_CONFIGURATION_KEY, {
875
+ ...configuration,
876
+ allowedHosts: this.allowedHostsOverride,
877
+ deniedHosts: this.deniedHostsOverride
878
+ });
879
+ }
880
+ restoreOutboundConfiguration() {
881
+ const configuration = this.ctx.storage.kv.get(OUTBOUND_CONFIGURATION_KEY);
882
+ if (!configuration) {
883
+ return void 0;
884
+ }
885
+ this.outboundHandlerOverride = void 0;
886
+ if (configuration.outboundHandlerOverride !== void 0) {
887
+ try {
888
+ this.validateOutboundHandlerMethodName(configuration.outboundHandlerOverride.method);
889
+ this.outboundHandlerOverride = configuration.outboundHandlerOverride;
890
+ } catch (error) {
891
+ console.warn("Ignoring invalid persisted outbound handler override:", error);
892
+ }
893
+ }
894
+ this.outboundByHostOverrides = {};
895
+ for (const [hostname, override] of Object.entries(configuration.outboundByHostOverrides ?? {})) {
896
+ try {
897
+ this.validateOutboundHandlerMethodName(override.method);
898
+ this.outboundByHostOverrides[hostname] = override;
899
+ } catch (error) {
900
+ console.warn(`Ignoring invalid persisted outbound override for ${hostname}:`, error);
901
+ }
902
+ }
903
+ this.hasInterceptAllRegistration = configuration.hasInterceptAllRegistration === true;
904
+ if (configuration.allowedHosts) {
905
+ this.allowedHostsOverride = configuration.allowedHosts;
906
+ }
907
+ if (configuration.deniedHosts) {
908
+ this.deniedHostsOverride = configuration.deniedHosts;
909
+ }
910
+ return this.getOutboundConfiguration();
911
+ }
912
+ /**
913
+ * Returns true if a catch-all outbound HTTP interception is needed.
914
+ * This is the case when a static `outbound` handler or a runtime
915
+ * `outboundHandlerOverride` (catch-all) is configured.
916
+ * When false, we only intercept specific hosts to avoid overhead.
917
+ */
918
+ needsCatchAllInterception() {
919
+ const ctor = this.constructor;
920
+ return ctor.outbound !== void 0 || this.outboundHandlerOverride !== void 0;
921
+ }
922
+ hasMutableOutboundConfiguration() {
923
+ return Object.keys(this.outboundByHostOverrides).length > 0 || this.allowedHostsOverride !== void 0 || this.deniedHostsOverride !== void 0;
924
+ }
925
+ shouldInterceptAllOutbound() {
926
+ return this.hasInterceptAllRegistration || this.needsCatchAllInterception() || this.effectiveAllowedHosts !== void 0 || this.effectiveDeniedHosts !== void 0 || this.hasMutableOutboundConfiguration();
927
+ }
928
+ getStaticOutboundByHostKeys() {
929
+ const ctor = this.constructor;
930
+ return ctor.outboundByHost ? Object.keys(ctor.outboundByHost) : [];
931
+ }
932
+ /**
933
+ * Collects all hostnames that need per-host outbound interception.
934
+ * This path is only used for the narrow optimized case where outbound
935
+ * handling is static and host-specific.
936
+ */
937
+ getHostsToIntercept() {
938
+ const hosts = /* @__PURE__ */ new Set();
939
+ const ctor = this.constructor;
940
+ if (ctor.outboundByHost) {
941
+ for (const hostname of Object.keys(ctor.outboundByHost)) {
942
+ hosts.add(hostname);
943
+ }
944
+ }
945
+ for (const hostname of Object.keys(this.outboundByHostOverrides)) {
946
+ hosts.add(hostname);
947
+ }
948
+ return [...hosts];
949
+ }
950
+ async refreshOutboundInterception() {
951
+ if (!this.usingInterception) {
952
+ return;
953
+ }
954
+ this.applyOutboundInterceptionPromise = this.applyOutboundInterception();
955
+ await this.applyOutboundInterceptionPromise;
956
+ }
957
+ /**
958
+ * Applies (or re-applies) outbound HTTP interception with the current
959
+ * default registries + runtime overrides passed through ContainerProxy props.
960
+ *
961
+ * Uses per-host interception only for static host-specific outbound handlers.
962
+ * As soon as the config needs to evaluate all hosts (catch-all outbound,
963
+ * allow/deny lists, or runtime-mutated outbound config), we promote the
964
+ * container to intercept-all and keep it there until the instance restarts.
965
+ *
966
+ * When `interceptHttps` is enabled, also applies HTTPS interception:
967
+ * - Intercept-all mode: `interceptOutboundHttps('*', ...)` for all HTTPS traffic
968
+ * - Per-host mode: `interceptOutboundHttps(host, ...)` for each known host
969
+ */
970
+ async applyOutboundInterception() {
971
+ const ctx = this.ctx;
972
+ if (ctx.exports === void 0) {
973
+ throw new Error("ctx.exports is undefined, please try to update your compatibility date or export ContainerProxy from the containers package in your worker entrypoint");
974
+ }
975
+ if (ctx.exports.ContainerProxy === void 0) {
976
+ throw new Error("ctx.exports.ContainerProxy is undefined, export ContainerProxy from the containers package in your worker entrypoint");
977
+ }
978
+ const interceptAll = this.shouldInterceptAllOutbound();
979
+ if (interceptAll) {
980
+ this.hasInterceptAllRegistration = interceptAll;
981
+ }
982
+ const outboundConfiguration = this.getOutboundConfiguration();
983
+ this.persistOutboundConfiguration(outboundConfiguration);
984
+ const hosts = this.getHostsToIntercept();
985
+ const props = {
986
+ enableInternet: this.enableInternet,
987
+ containerId: this.ctx.id.toString(),
988
+ className: this.constructor.name,
989
+ outboundByHostOverrides: outboundConfiguration.outboundByHostOverrides,
990
+ outboundHandlerOverride: outboundConfiguration.outboundHandlerOverride,
991
+ allowedHosts: outboundConfiguration.allowedHosts,
992
+ deniedHosts: outboundConfiguration.deniedHosts,
993
+ interceptAll
994
+ };
995
+ const fetcher = ctx.exports.ContainerProxy({
996
+ props
997
+ });
998
+ if (interceptAll) {
999
+ for (const host of this.getStaticOutboundByHostKeys()) {
1000
+ await this.container.interceptOutboundHttp(host, fetcher);
1001
+ if (this.interceptHttps) {
1002
+ await this.container.interceptOutboundHttps(host, fetcher);
1003
+ }
1004
+ }
1005
+ if (this.interceptHttps) {
1006
+ await this.container.interceptOutboundHttps("*", fetcher);
1007
+ }
1008
+ await this.container.interceptAllOutboundHttp(fetcher);
1009
+ } else {
1010
+ for (const host of hosts) {
1011
+ await this.container.interceptOutboundHttp(host, fetcher);
1012
+ if (this.interceptHttps) {
1013
+ await this.container.interceptOutboundHttps(host, fetcher);
1014
+ }
1015
+ }
1016
+ }
1017
+ }
1018
+ /**
1019
+ * Execute SQL queries against the Container's database
1020
+ */
1021
+ sql(strings, ...values) {
1022
+ const query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
1023
+ return [...this.ctx.storage.sql.exec(query, ...values)];
1024
+ }
1025
+ requestAndPortFromContainerFetchArgs(requestOrUrl, portOrInit, portParam) {
1026
+ let request;
1027
+ let port;
1028
+ if (requestOrUrl instanceof Request) {
1029
+ request = requestOrUrl;
1030
+ port = typeof portOrInit === "number" ? portOrInit : void 0;
1031
+ } else {
1032
+ const url = typeof requestOrUrl === "string" ? requestOrUrl : requestOrUrl.toString();
1033
+ const init = typeof portOrInit === "number" ? {} : portOrInit || {};
1034
+ port = typeof portOrInit === "number" ? portOrInit : typeof portParam === "number" ? portParam : void 0;
1035
+ request = new Request(url, init);
1036
+ }
1037
+ port ??= this.defaultPort;
1038
+ if (port === void 0) {
1039
+ throw new Error("No port specified for container fetch. Set defaultPort or specify a port parameter.");
1040
+ }
1041
+ return { request, port };
1042
+ }
1043
+ /**
1044
+ *
1045
+ * The method prioritizes port sources in this order:
1046
+ * 1. Ports specified directly in the method call
1047
+ * 2. `requiredPorts` class property (if set)
1048
+ * 3. `defaultPort` (if neither of the above is specified)
1049
+ * 4. Falls back to port 33 if none of the above are set
1050
+ */
1051
+ async getPortsToCheck(overridePorts) {
1052
+ if (overridePorts !== void 0) {
1053
+ return Array.isArray(overridePorts) ? overridePorts : [overridePorts];
1054
+ }
1055
+ if (this.requiredPorts && this.requiredPorts.length > 0) {
1056
+ return [...this.requiredPorts];
1057
+ }
1058
+ return [this.defaultPort ?? FALLBACK_PORT_TO_CHECK];
1059
+ }
1060
+ // ===========================================
1061
+ // CONTAINER INTERACTION & MONITORING
1062
+ // ===========================================
1063
+ /**
1064
+ * Tries to start a container if it's not already running
1065
+ * Returns the number of tries used
1066
+ */
1067
+ async startContainerIfNotRunning(waitOptions, options) {
1068
+ if (this.startInFlight) {
1069
+ return this.startInFlight;
1070
+ }
1071
+ if (this.container.running) {
1072
+ if (!this.monitor) {
1073
+ this.monitor = this.container.monitor();
1074
+ }
1075
+ return 0;
1076
+ }
1077
+ const startPromise = this.doStartContainer(waitOptions, options);
1078
+ this.startInFlight = startPromise;
1079
+ try {
1080
+ return await startPromise;
1081
+ } finally {
1082
+ if (this.startInFlight === startPromise) {
1083
+ this.startInFlight = void 0;
1084
+ }
1085
+ }
1086
+ }
1087
+ async doStartContainer(waitOptions, options) {
1088
+ const abortedSignal = new Promise((res) => {
1089
+ waitOptions.signal?.addEventListener("abort", () => {
1090
+ res(true);
1091
+ });
1092
+ });
1093
+ const pollInterval = waitOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
1094
+ const totalTries = waitOptions.retries ?? Math.ceil(TIMEOUT_TO_GET_CONTAINER_MS / pollInterval);
1095
+ for (let tries = 0; tries < totalTries; tries++) {
1096
+ const envVars = options?.envVars ?? this.envVars;
1097
+ const entrypoint = options?.entrypoint ?? this.entrypoint;
1098
+ const enableInternet = options?.enableInternet ?? this.enableInternet;
1099
+ const labels = options?.labels ?? this.labels;
1100
+ const startConfig = {
1101
+ enableInternet
1102
+ };
1103
+ if (envVars && Object.keys(envVars).length > 0)
1104
+ startConfig.env = envVars;
1105
+ if (entrypoint)
1106
+ startConfig.entrypoint = entrypoint;
1107
+ if (labels && Object.keys(labels).length > 0)
1108
+ startConfig.labels = labels;
1109
+ this.renewActivityTimeout();
1110
+ const handleError = async () => {
1111
+ const err = await this.monitor?.catch((err2) => err2);
1112
+ if (typeof err === "number") {
1113
+ const toThrow = new Error(`Container exited before we could determine the container health, exit code: ${err}`);
1114
+ await this.state.setStoppedWithCode(err);
1115
+ this.monitor = void 0;
1116
+ try {
1117
+ await this.onError(toThrow);
1118
+ } catch {
1119
+ }
1120
+ throw toThrow;
1121
+ } else if (!isNoInstanceError(err)) {
1122
+ await this.state.setStopped();
1123
+ this.monitor = void 0;
1124
+ try {
1125
+ await this.onError(err);
1126
+ } catch {
1127
+ }
1128
+ throw err;
1129
+ }
1130
+ };
1131
+ if (tries > 0 && !this.container.running) {
1132
+ await handleError();
1133
+ }
1134
+ await this.scheduleNextAlarm();
1135
+ if (!this.container.running) {
1136
+ await this.refreshOutboundInterception();
1137
+ this.container.start(startConfig);
1138
+ this.monitor = this.container.monitor();
1139
+ await this.state.setRunning();
1140
+ } else {
1141
+ await this.scheduleNextAlarm();
1142
+ }
1143
+ this.renewActivityTimeout();
1144
+ const port = this.container.getTcpPort(waitOptions.portToCheck);
1145
+ try {
1146
+ const combinedSignal = addTimeoutSignal(waitOptions.signal, PING_TIMEOUT_MS);
1147
+ await port.fetch("http://containerstarthealthcheck", { signal: combinedSignal });
1148
+ return tries;
1149
+ } catch (error) {
1150
+ if (isNotListeningError(error) && this.container.running) {
1151
+ return tries;
1152
+ }
1153
+ if (!this.container.running && isNotListeningError(error)) {
1154
+ await handleError();
1155
+ }
1156
+ await Promise.any([
1157
+ new Promise((res) => setTimeout(res, waitOptions.waitInterval)),
1158
+ abortedSignal
1159
+ ]);
1160
+ if (waitOptions.signal?.aborted) {
1161
+ throw new Error("Aborted waiting for container to start as we received a cancellation signal", { cause: error });
1162
+ }
1163
+ if (totalTries === tries + 1) {
1164
+ if (error instanceof Error && error.message.includes("Network connection lost")) {
1165
+ this.ctx.abort();
1166
+ }
1167
+ await handleError();
1168
+ await this.state.setStopped();
1169
+ this.monitor = void 0;
1170
+ throw new Error(NO_CONTAINER_INSTANCE_ERROR, { cause: error });
1171
+ }
1172
+ continue;
1173
+ }
1174
+ }
1175
+ throw new Error(`Container did not start after ${totalTries * pollInterval}ms`);
1176
+ }
1177
+ setupMonitorCallbacks() {
1178
+ const monitor = this.monitor;
1179
+ if (!monitor || this.monitoredPromise === monitor) {
1180
+ return;
1181
+ }
1182
+ this.monitoredPromise = monitor;
1183
+ monitor.then(async () => {
1184
+ await this.ctx.blockConcurrencyWhile(async () => {
1185
+ if (this.monitor === monitor) {
1186
+ await this.state.setStoppedWithCode(0);
1187
+ }
1188
+ });
1189
+ }).catch(async (error) => {
1190
+ if (this.monitor !== monitor) {
1191
+ return;
1192
+ }
1193
+ if (isNoInstanceError(error)) {
1194
+ await this.ctx.blockConcurrencyWhile(async () => {
1195
+ if (this.monitor === monitor) {
1196
+ await this.state.setStopped();
1197
+ }
1198
+ });
1199
+ return;
1200
+ }
1201
+ const exitCode = getExitCodeFromError(error);
1202
+ if (exitCode !== null) {
1203
+ await this.ctx.blockConcurrencyWhile(async () => {
1204
+ if (this.monitor === monitor) {
1205
+ await this.state.setStoppedWithCode(exitCode);
1206
+ }
1207
+ });
1208
+ return;
1209
+ }
1210
+ await this.ctx.blockConcurrencyWhile(async () => {
1211
+ if (this.monitor === monitor) {
1212
+ await this.state.setStopped();
1213
+ }
1214
+ });
1215
+ if (this.monitor !== monitor) {
1216
+ return;
1217
+ }
1218
+ try {
1219
+ await this.onError(error);
1220
+ } catch {
1221
+ }
1222
+ }).finally(() => {
1223
+ if (this.monitor !== monitor) {
1224
+ return;
1225
+ }
1226
+ this.monitoredPromise = void 0;
1227
+ this.monitor = void 0;
1228
+ if (this.timeout) {
1229
+ if (this.resolve)
1230
+ this.resolve();
1231
+ clearTimeout(this.timeout);
1232
+ }
1233
+ });
1234
+ }
1235
+ deleteSchedules(name) {
1236
+ this.sql`DELETE FROM container_schedules WHERE callback = ${name}`;
1237
+ }
1238
+ // ============================
1239
+ // ALARMS AND SCHEDULES
1240
+ // ============================
1241
+ /**
1242
+ * Method called when an alarm fires
1243
+ * Executes any scheduled tasks that are due
1244
+ */
1245
+ async alarm(alarmProps) {
1246
+ if (alarmProps !== void 0 && alarmProps.isRetry && alarmProps.retryCount > MAX_ALARM_RETRIES) {
1247
+ const scheduleCount = Number(this.sql`SELECT COUNT(*) as count FROM container_schedules`[0]?.count) || 0;
1248
+ const hasScheduledTasks = scheduleCount > 0;
1249
+ if (hasScheduledTasks || this.container.running) {
1250
+ await this.scheduleNextAlarm();
1251
+ }
1252
+ return;
1253
+ }
1254
+ const prevAlarm = Date.now();
1255
+ await this.ctx.storage.setAlarm(prevAlarm);
1256
+ await this.ctx.storage.sync();
1257
+ const result = this.sql`
1258
+ SELECT * FROM container_schedules;
1259
+ `;
1260
+ let minTime = Date.now() + 3 * 60 * 1e3;
1261
+ const now = Date.now() / 1e3;
1262
+ for (const row of result) {
1263
+ if (row.time > now) {
1264
+ continue;
1265
+ }
1266
+ const callback = this[row.callback];
1267
+ if (!callback || typeof callback !== "function") {
1268
+ console.error(`Callback ${row.callback} not found or is not a function`);
1269
+ continue;
1270
+ }
1271
+ const schedule = this.getSchedule(row.id);
1272
+ try {
1273
+ const payload = row.payload ? JSON.parse(row.payload) : void 0;
1274
+ await callback.call(this, payload, await schedule);
1275
+ } catch (e) {
1276
+ console.error(`Error executing scheduled callback "${row.callback}":`, e);
1277
+ }
1278
+ this.sql`DELETE FROM container_schedules WHERE id = ${row.id}`;
1279
+ }
1280
+ const resultForMinTime = this.sql`
1281
+ SELECT * FROM container_schedules;
1282
+ `;
1283
+ const minTimeFromSchedules = Math.min(...resultForMinTime.map((r) => r.time * 1e3));
1284
+ if (!this.container.running) {
1285
+ await this.syncPendingStoppedEvents();
1286
+ if (resultForMinTime.length == 0) {
1287
+ await this.ctx.storage.deleteAlarm();
1288
+ } else {
1289
+ await this.ctx.storage.setAlarm(minTimeFromSchedules);
1290
+ }
1291
+ return;
1292
+ }
1293
+ if (this.isActivityExpired()) {
1294
+ await this.onActivityExpired();
1295
+ this.renewActivityTimeout();
1296
+ return;
1297
+ }
1298
+ minTime = Math.min(minTimeFromSchedules, minTime, this.sleepAfterMs);
1299
+ const timeout = Math.max(0, minTime - Date.now());
1300
+ await new Promise((resolve) => {
1301
+ this.resolve = resolve;
1302
+ if (!this.container.running) {
1303
+ resolve();
1304
+ return;
1305
+ }
1306
+ this.timeout = setTimeout(() => {
1307
+ resolve();
1308
+ }, timeout);
1309
+ });
1310
+ await this.ctx.storage.setAlarm(Date.now());
1311
+ }
1312
+ timeout;
1313
+ resolve;
1314
+ // synchronises container state with the container source of truth to process events
1315
+ async syncPendingStoppedEvents() {
1316
+ const state = await this.state.getState();
1317
+ if (!this.container.running && (state.status === "healthy" || state.status === "running")) {
1318
+ await this.callOnStop({ exitCode: 0, reason: "exit" }, state);
1319
+ return;
1320
+ }
1321
+ if (!this.container.running && state.status === "stopped_with_code") {
1322
+ await this.callOnStop({ exitCode: state.exitCode ?? 0, reason: "exit" }, state);
1323
+ return;
1324
+ }
1325
+ }
1326
+ async callOnStop(onStopParams, stateBeforeOnStop) {
1327
+ if (this.onStopCalled) {
1328
+ return;
1329
+ }
1330
+ this.onStopCalled = true;
1331
+ const promise = this.onStop(onStopParams);
1332
+ if (promise instanceof Promise) {
1333
+ await promise.finally(() => {
1334
+ this.onStopCalled = false;
1335
+ });
1336
+ } else {
1337
+ this.onStopCalled = false;
1338
+ }
1339
+ await this.state.setStoppedIfUnchanged(stateBeforeOnStop);
1340
+ }
1341
+ /**
1342
+ * Schedule the next alarm based on upcoming tasks
1343
+ */
1344
+ async scheduleNextAlarm(ms = 1e3) {
1345
+ const nextTime = ms + Date.now();
1346
+ if (this.timeout) {
1347
+ if (this.resolve)
1348
+ this.resolve();
1349
+ clearTimeout(this.timeout);
1350
+ }
1351
+ await this.ctx.storage.setAlarm(nextTime);
1352
+ await this.ctx.storage.sync();
1353
+ }
1354
+ async listSchedules(name) {
1355
+ const result = this.sql`
1356
+ SELECT * FROM container_schedules WHERE callback = ${name} LIMIT 1
1357
+ `;
1358
+ if (!result || result.length === 0) {
1359
+ return [];
1360
+ }
1361
+ return result.map(this.toSchedule);
1362
+ }
1363
+ toSchedule(schedule) {
1364
+ let payload;
1365
+ try {
1366
+ payload = JSON.parse(schedule.payload);
1367
+ } catch (e) {
1368
+ console.error(`Error parsing payload for schedule ${schedule.id}:`, e);
1369
+ payload = void 0;
1370
+ }
1371
+ if (schedule.type === "delayed") {
1372
+ return {
1373
+ taskId: schedule.id,
1374
+ callback: schedule.callback,
1375
+ payload,
1376
+ type: "delayed",
1377
+ time: schedule.time,
1378
+ delayInSeconds: schedule.delayInSeconds
1379
+ };
1380
+ }
1381
+ return {
1382
+ taskId: schedule.id,
1383
+ callback: schedule.callback,
1384
+ payload,
1385
+ type: "scheduled",
1386
+ time: schedule.time
1387
+ };
1388
+ }
1389
+ /**
1390
+ * Get a scheduled task by ID
1391
+ * @template T Type of the payload data
1392
+ * @param id ID of the scheduled task
1393
+ * @returns The Schedule object or undefined if not found
1394
+ */
1395
+ async getSchedule(id) {
1396
+ const result = this.sql`
1397
+ SELECT * FROM container_schedules WHERE id = ${id} LIMIT 1
1398
+ `;
1399
+ if (!result || result.length === 0) {
1400
+ return void 0;
1401
+ }
1402
+ const schedule = result[0];
1403
+ return this.toSchedule(schedule);
1404
+ }
1405
+ isActivityExpired() {
1406
+ if (this.inflightRequests > 0) {
1407
+ this.renewActivityTimeout();
1408
+ return false;
1409
+ }
1410
+ return this.sleepAfterMs <= Date.now();
1411
+ }
1412
+ };
1413
+
1414
+ // src/eve-host.ts
1415
+ var EVE_HOST_DEFAULTS = {
1416
+ compatibilityDate: "2026-04-01",
1417
+ healthPath: "/eve/v1/health",
1418
+ internalPort: 8080,
1419
+ maxInstances: 1,
1420
+ startCommand: [
1421
+ "./node_modules/.bin/eve",
1422
+ "start",
1423
+ "--host",
1424
+ "0.0.0.0",
1425
+ "--port",
1426
+ "8080"
1427
+ ],
1428
+ sleepAfter: "24h"
1429
+ };
1430
+ var EVE_HOST_OWNED_HEADERS = [
1431
+ "forwarded",
1432
+ "x-forwarded-for",
1433
+ "x-forwarded-host",
1434
+ "x-forwarded-port",
1435
+ "x-forwarded-proto",
1436
+ "x-forwarded-server",
1437
+ "x-forwarded-scheme",
1438
+ "x-real-ip",
1439
+ "cf-connecting-ip",
1440
+ "cf-visitor",
1441
+ "true-client-ip",
1442
+ "x-original-host",
1443
+ "x-original-proto",
1444
+ "x-envoy-original-host",
1445
+ "x-envoy-original-proto",
1446
+ "x-proxy-host",
1447
+ "x-host",
1448
+ "x-eve-public-origin",
1449
+ "x-workflow-local-base-url",
1450
+ "x-eden-eve-callback-base",
1451
+ "x-eden-eve-deployment-id",
1452
+ "x-eden-eve-generation-id",
1453
+ "x-eden-eve-public-origin",
1454
+ "x-eden-eve-correlation-id",
1455
+ "x-eden-eve-container-name",
1456
+ "x-eden-eve-container-id",
1457
+ "x-eden-eve-runtime-revision",
1458
+ "x-eden-deployment-id",
1459
+ "x-eden-generation-id",
1460
+ "x-eden-container-name",
1461
+ "x-eden-container-id",
1462
+ "cf-container-target-port"
1463
+ ];
1464
+ var EVE_HOST_OWNED_HEADER_SET = new Set(EVE_HOST_OWNED_HEADERS);
1465
+ var WORKER_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
1466
+ var SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
1467
+ var IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
1468
+ var EveHostError = class extends Error {
1469
+ code;
1470
+ constructor(code, message) {
1471
+ super(message);
1472
+ this.name = "EveHostError";
1473
+ this.code = code;
1474
+ }
1475
+ };
1476
+ function assertNonEmpty(value, subject) {
1477
+ if (value.length === 0) {
1478
+ throw new EveHostError(
1479
+ "HOST_ORIGIN_UNAVAILABLE",
1480
+ `The ${subject} must be non-empty.`
1481
+ );
1482
+ }
1483
+ }
1484
+ function assertStableOrigin(value, workerName) {
1485
+ let origin;
1486
+ try {
1487
+ origin = new URL(value);
1488
+ } catch {
1489
+ throw new EveHostError(
1490
+ "HOST_ORIGIN_UNAVAILABLE",
1491
+ "The stable workers.dev origin is not a valid absolute URL."
1492
+ );
1493
+ }
1494
+ if (origin.protocol !== "https:" || origin.port.length !== 0 || origin.pathname !== "/" || origin.search.length !== 0 || origin.hash.length !== 0 || !origin.hostname.endsWith(".workers.dev")) {
1495
+ throw new EveHostError(
1496
+ "HOST_ORIGIN_UNAVAILABLE",
1497
+ "The stable origin must be an HTTPS provider-assigned workers.dev origin."
1498
+ );
1499
+ }
1500
+ if (workerName !== void 0 && !origin.hostname.startsWith(`${workerName}.`)) {
1501
+ throw new EveHostError(
1502
+ "HOST_ORIGIN_UNAVAILABLE",
1503
+ "The stable workers.dev origin does not belong to the exact Worker target."
1504
+ );
1505
+ }
1506
+ const labels = origin.hostname.split(".");
1507
+ if (labels.length !== 4 || labels[labels.length - 2] !== "workers" || labels[labels.length - 1] !== "dev" || !SUBDOMAIN_PATTERN.test(labels[1] ?? "") || workerName !== void 0 && labels[0] !== workerName) {
1508
+ throw new EveHostError(
1509
+ "HOST_ORIGIN_UNAVAILABLE",
1510
+ "The stable origin must be the exact provider-assigned Worker workers.dev hostname."
1511
+ );
1512
+ }
1513
+ }
1514
+ function originHost(origin) {
1515
+ const parsed = new URL(origin);
1516
+ return parsed.host;
1517
+ }
1518
+ function isBodylessMethod(method) {
1519
+ return method === "GET" || method === "HEAD";
1520
+ }
1521
+ function isHostOwnedHeader(name) {
1522
+ const lowerName = name.toLowerCase();
1523
+ return EVE_HOST_OWNED_HEADER_SET.has(lowerName) || lowerName.startsWith("x-forwarded-") || lowerName.startsWith("x-eden-") || lowerName.startsWith("cf-");
1524
+ }
1525
+ function createTrustedEveRequest(request, metadata) {
1526
+ assertStableOrigin(metadata.publicOrigin);
1527
+ assertNonEmpty(metadata.deploymentId, "deployment identity");
1528
+ assertNonEmpty(metadata.generationId, "generation identity");
1529
+ assertNonEmpty(metadata.correlationId, "correlation identity");
1530
+ const headers = new Headers(request.headers);
1531
+ const headersToStrip = [];
1532
+ headers.forEach((_value, header) => {
1533
+ if (isHostOwnedHeader(header)) {
1534
+ headersToStrip.push(header);
1535
+ }
1536
+ });
1537
+ for (const header of headersToStrip) headers.delete(header);
1538
+ const host = originHost(metadata.publicOrigin);
1539
+ const targetOrigin = new URL(metadata.publicOrigin);
1540
+ const targetUrl = new URL(request.url);
1541
+ targetUrl.protocol = targetOrigin.protocol;
1542
+ targetUrl.hostname = targetOrigin.hostname;
1543
+ targetUrl.port = targetOrigin.port;
1544
+ const edgeUrl = new URL(request.url);
1545
+ const edgeProtocol = edgeUrl.protocol === "http:" ? "http" : "https";
1546
+ const publicPort = targetOrigin.port.length > 0 ? targetOrigin.port : targetOrigin.protocol === "https:" ? "443" : "80";
1547
+ headers.set("forwarded", `proto=${edgeProtocol};host=${host}`);
1548
+ headers.set("host", host);
1549
+ headers.set("x-forwarded-host", host);
1550
+ headers.set("x-forwarded-port", publicPort);
1551
+ headers.set("x-forwarded-proto", edgeProtocol);
1552
+ headers.set("x-eden-eve-public-origin", metadata.publicOrigin);
1553
+ headers.set("x-eden-eve-deployment-id", metadata.deploymentId);
1554
+ headers.set("x-eden-eve-generation-id", metadata.generationId);
1555
+ headers.set("x-eden-eve-correlation-id", metadata.correlationId);
1556
+ if (metadata.runtimeRevisionHandle !== void 0) {
1557
+ headers.set(
1558
+ "x-eden-eve-runtime-revision",
1559
+ metadata.runtimeRevisionHandle
1560
+ );
1561
+ }
1562
+ const init = {
1563
+ method: request.method,
1564
+ headers,
1565
+ redirect: request.redirect,
1566
+ signal: request.signal,
1567
+ ...isBodylessMethod(request.method) || request.body === null ? {} : { body: request.body, duplex: "half" }
1568
+ };
1569
+ return new Request(targetUrl, init);
1570
+ }
1571
+ function throwIfAborted(signal) {
1572
+ if (signal.aborted) {
1573
+ throw new EveHostError(
1574
+ "HOST_REQUEST_ABORTED",
1575
+ "The client request was cancelled before Eve became ready."
1576
+ );
1577
+ }
1578
+ }
1579
+ function createEveHostLifecycleObserver(now = Date.now) {
1580
+ const events = [];
1581
+ return {
1582
+ events,
1583
+ record(type, safeStatus) {
1584
+ const event = {
1585
+ type,
1586
+ at: now(),
1587
+ ...safeStatus === void 0 ? {} : { safeStatus }
1588
+ };
1589
+ events.push(event);
1590
+ return event;
1591
+ }
1592
+ };
1593
+ }
1594
+ function responseBodyIsReady(value) {
1595
+ if (typeof value !== "object" || value === null) return false;
1596
+ const record = value;
1597
+ return record.status === "ready" || record.state === "ready" || record.health === "ready" || record.ready === true || record.healthy === true;
1598
+ }
1599
+ var RESERVED_EVE_HOST_VARIABLES = /* @__PURE__ */ new Set([
1600
+ "HOST",
1601
+ "NITRO_HOST",
1602
+ "PORT",
1603
+ "NITRO_PORT",
1604
+ "NODE_ENV",
1605
+ "WORKFLOW_LOCAL_BASE_URL",
1606
+ "EDEN_EVE_DEPLOYMENT_ID",
1607
+ "EDEN_EVE_GENERATION_ID",
1608
+ "EDEN_EVE_RUNTIME_REVISION"
1609
+ ]);
1610
+ function readProtectedRuntimeVariables(env) {
1611
+ const names = env.EVE_RUNTIME_VARIABLE_NAMES ?? [];
1612
+ const values = {};
1613
+ for (const name of names) {
1614
+ if (!IDENTIFIER_PATTERN.test(name) || RESERVED_EVE_HOST_VARIABLES.has(name)) {
1615
+ throw new EveHostError(
1616
+ "HOST_READINESS_UNPROVEN",
1617
+ `The protected runtime contract contains an invalid or reserved variable name ${name}.`
1618
+ );
1619
+ }
1620
+ const value = env[name];
1621
+ if (typeof value !== "string") {
1622
+ throw new EveHostError(
1623
+ "HOST_READINESS_UNPROVEN",
1624
+ `The protected runtime contract is missing variable ${name}.`
1625
+ );
1626
+ }
1627
+ values[name] = value;
1628
+ }
1629
+ return values;
1630
+ }
1631
+ function raceWithAbort(promise, signal) {
1632
+ if (signal.aborted) {
1633
+ return Promise.reject(
1634
+ new EveHostError(
1635
+ "HOST_REQUEST_ABORTED",
1636
+ "The client request was cancelled before Eve became ready."
1637
+ )
1638
+ );
1639
+ }
1640
+ return new Promise((resolve, reject) => {
1641
+ const onAbort = () => {
1642
+ reject(
1643
+ new EveHostError(
1644
+ "HOST_REQUEST_ABORTED",
1645
+ "The client request was cancelled before Eve became ready."
1646
+ )
1647
+ );
1648
+ };
1649
+ signal.addEventListener("abort", onAbort, { once: true });
1650
+ void promise.then(
1651
+ (value) => {
1652
+ signal.removeEventListener("abort", onAbort);
1653
+ resolve(value);
1654
+ },
1655
+ (error) => {
1656
+ signal.removeEventListener("abort", onAbort);
1657
+ reject(error);
1658
+ }
1659
+ );
1660
+ });
1661
+ }
1662
+ function createEveReadinessGate(options) {
1663
+ const port = options.port ?? EVE_HOST_DEFAULTS.internalPort;
1664
+ const healthPath = options.healthPath ?? EVE_HOST_DEFAULTS.healthPath;
1665
+ const instanceGetTimeoutMs = options.instanceGetTimeoutMs ?? 12e4;
1666
+ const portReadyTimeoutMs = options.portReadyTimeoutMs ?? 3e4;
1667
+ const healthTimeoutMs = options.healthTimeoutMs ?? 1e4;
1668
+ const waitIntervalMs = options.waitIntervalMs ?? 300;
1669
+ let evidence;
1670
+ let inFlight;
1671
+ let inFlightController;
1672
+ let generation = 0;
1673
+ const run = async (signal) => {
1674
+ try {
1675
+ await options.startAndWaitForPorts({
1676
+ ports: port,
1677
+ cancellationOptions: {
1678
+ abort: signal,
1679
+ instanceGetTimeoutMS: instanceGetTimeoutMs,
1680
+ portReadyTimeoutMS: portReadyTimeoutMs,
1681
+ waitInterval: waitIntervalMs
1682
+ }
1683
+ });
1684
+ } catch {
1685
+ if (signal.aborted) {
1686
+ throw new EveHostError(
1687
+ "HOST_REQUEST_ABORTED",
1688
+ "The client request was cancelled before Eve became ready."
1689
+ );
1690
+ }
1691
+ throw new EveHostError(
1692
+ "HOST_READINESS_UNPROVEN",
1693
+ "The Eve Container did not reach its internal port readiness deadline."
1694
+ );
1695
+ }
1696
+ const healthController = new AbortController();
1697
+ let rejectHealthTimeout;
1698
+ const abortHealth = () => {
1699
+ healthController.abort();
1700
+ rejectHealthTimeout?.(
1701
+ new EveHostError(
1702
+ "HOST_REQUEST_ABORTED",
1703
+ "The client request was cancelled before Eve became ready."
1704
+ )
1705
+ );
1706
+ };
1707
+ signal.addEventListener("abort", abortHealth, { once: true });
1708
+ const healthTimeoutResult = new Promise((_resolve, reject) => {
1709
+ rejectHealthTimeout = reject;
1710
+ });
1711
+ const healthTimeout = setTimeout(() => {
1712
+ healthController.abort();
1713
+ rejectHealthTimeout?.(
1714
+ new EveHostError(
1715
+ "HOST_READINESS_UNPROVEN",
1716
+ "The bounded Eve health probe timed out."
1717
+ )
1718
+ );
1719
+ }, healthTimeoutMs);
1720
+ let response;
1721
+ try {
1722
+ const healthRequest = new Request(`http://localhost${healthPath}`, {
1723
+ method: "GET",
1724
+ signal: healthController.signal
1725
+ });
1726
+ const healthResult = options.healthFetch(healthRequest);
1727
+ response = await Promise.race([healthResult, healthTimeoutResult]);
1728
+ } catch {
1729
+ if (signal.aborted) {
1730
+ throw new EveHostError(
1731
+ "HOST_REQUEST_ABORTED",
1732
+ "The client request was cancelled before Eve became ready."
1733
+ );
1734
+ }
1735
+ throw new EveHostError(
1736
+ "HOST_READINESS_UNPROVEN",
1737
+ "The bounded Eve health probe did not complete."
1738
+ );
1739
+ } finally {
1740
+ clearTimeout(healthTimeout);
1741
+ signal.removeEventListener("abort", abortHealth);
1742
+ }
1743
+ if (response.status !== 200) {
1744
+ await response.arrayBuffer().catch(() => void 0);
1745
+ throw new EveHostError(
1746
+ "HOST_READINESS_UNPROVEN",
1747
+ "The Eve health route did not return the expected successful status."
1748
+ );
1749
+ }
1750
+ if (!(response.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) {
1751
+ await response.arrayBuffer().catch(() => void 0);
1752
+ throw new EveHostError(
1753
+ "HOST_READINESS_UNPROVEN",
1754
+ "The Eve health route did not return the expected JSON contract."
1755
+ );
1756
+ }
1757
+ let body;
1758
+ try {
1759
+ body = await response.json();
1760
+ } catch {
1761
+ throw new EveHostError(
1762
+ "HOST_READINESS_UNPROVEN",
1763
+ "The Eve health route did not return a valid ready response."
1764
+ );
1765
+ }
1766
+ if (!responseBodyIsReady(body)) {
1767
+ throw new EveHostError(
1768
+ "HOST_READINESS_UNPROVEN",
1769
+ "The Eve health route is reachable but has not reported ready."
1770
+ );
1771
+ }
1772
+ return {
1773
+ healthPath,
1774
+ healthStatus: "ready",
1775
+ healthVerified: true,
1776
+ port,
1777
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
1778
+ };
1779
+ };
1780
+ const gate = ((signal) => {
1781
+ throwIfAborted(signal);
1782
+ if (evidence !== void 0) {
1783
+ return Promise.resolve(evidence);
1784
+ }
1785
+ if (inFlight === void 0) {
1786
+ const runGeneration = generation;
1787
+ inFlightController = new AbortController();
1788
+ inFlight = run(inFlightController.signal).then((result) => {
1789
+ if (runGeneration === generation) {
1790
+ evidence = result;
1791
+ }
1792
+ return result;
1793
+ }).finally(() => {
1794
+ if (runGeneration === generation) {
1795
+ inFlight = void 0;
1796
+ inFlightController = void 0;
1797
+ }
1798
+ });
1799
+ }
1800
+ return raceWithAbort(inFlight, signal);
1801
+ });
1802
+ gate.reset = () => {
1803
+ generation += 1;
1804
+ evidence = void 0;
1805
+ inFlightController?.abort();
1806
+ inFlightController = void 0;
1807
+ inFlight = void 0;
1808
+ };
1809
+ return gate;
1810
+ }
1811
+
1812
+ // src/eve-host-runtime.ts
1813
+ var EveHostContainer = class extends Container {
1814
+ defaultPort = EVE_HOST_DEFAULTS.internalPort;
1815
+ requiredPorts = [EVE_HOST_DEFAULTS.internalPort];
1816
+ sleepAfter = EVE_HOST_DEFAULTS.sleepAfter;
1817
+ entrypoint = [...EVE_HOST_DEFAULTS.startCommand];
1818
+ enableInternet = true;
1819
+ pingEndpoint = "localhost/eve/v1/health";
1820
+ lifecycle = createEveHostLifecycleObserver();
1821
+ readinessStarted = false;
1822
+ readinessEvidence;
1823
+ readiness;
1824
+ constructor(ctx, env) {
1825
+ super(ctx, env);
1826
+ const publicOrigin = env.EVE_PUBLIC_ORIGIN;
1827
+ const deploymentId = env.EDEN_EVE_DEPLOYMENT_ID;
1828
+ const generationId = env.EDEN_EVE_GENERATION_ID;
1829
+ if (publicOrigin === void 0 || deploymentId === void 0 || generationId === void 0) {
1830
+ throw new EveHostError(
1831
+ "HOST_ORIGIN_UNAVAILABLE",
1832
+ "The verified public origin and deployment identity must exist before Eve starts."
1833
+ );
1834
+ }
1835
+ assertStableOrigin(publicOrigin);
1836
+ assertNonEmpty(deploymentId, "deployment identity");
1837
+ assertNonEmpty(generationId, "generation identity");
1838
+ const runtimeEnv = readProtectedRuntimeVariables(env);
1839
+ this.envVars = {
1840
+ ...runtimeEnv,
1841
+ HOST: "0.0.0.0",
1842
+ NITRO_HOST: "0.0.0.0",
1843
+ PORT: String(EVE_HOST_DEFAULTS.internalPort),
1844
+ NITRO_PORT: String(EVE_HOST_DEFAULTS.internalPort),
1845
+ NODE_ENV: "production",
1846
+ WORKFLOW_LOCAL_BASE_URL: publicOrigin,
1847
+ EDEN_EVE_DEPLOYMENT_ID: deploymentId,
1848
+ EDEN_EVE_GENERATION_ID: generationId,
1849
+ ...env.EDEN_EVE_RUNTIME_REVISION === void 0 ? {} : { EDEN_EVE_RUNTIME_REVISION: env.EDEN_EVE_RUNTIME_REVISION }
1850
+ };
1851
+ this.readiness = createEveReadinessGate({
1852
+ startAndWaitForPorts: (options) => this.startAndWaitForPorts(options),
1853
+ healthFetch: (request) => this.containerFetch(request, EVE_HOST_DEFAULTS.internalPort)
1854
+ });
1855
+ }
1856
+ async ensureEveReady(signal = new AbortController().signal) {
1857
+ if (this.readinessEvidence !== void 0) {
1858
+ return this.readinessEvidence;
1859
+ }
1860
+ if (!this.readinessStarted) {
1861
+ this.readinessStarted = true;
1862
+ this.lifecycle.record("start_requested");
1863
+ }
1864
+ const evidence = await this.readiness(signal);
1865
+ this.readinessEvidence = evidence;
1866
+ this.lifecycle.record("health_ready", evidence.healthStatus);
1867
+ return evidence;
1868
+ }
1869
+ async fetch(request) {
1870
+ await this.ensureEveReady(request.signal);
1871
+ return super.fetch(request);
1872
+ }
1873
+ onStart() {
1874
+ if (this.lifecycle.events.some((event) => event.type === "started")) {
1875
+ this.lifecycle.record("replaced");
1876
+ }
1877
+ this.lifecycle.record("started");
1878
+ }
1879
+ onStop(params) {
1880
+ this.readinessStarted = false;
1881
+ this.readinessEvidence = void 0;
1882
+ this.readiness.reset();
1883
+ this.lifecycle.record("stopped", `${params.reason}:${params.exitCode}`);
1884
+ }
1885
+ onError(error) {
1886
+ this.readinessStarted = false;
1887
+ this.readinessEvidence = void 0;
1888
+ this.readiness.reset();
1889
+ this.lifecycle.record(
1890
+ "errored",
1891
+ error instanceof Error ? error.name : "unknown"
1892
+ );
1893
+ throw new EveHostError(
1894
+ "HOST_READINESS_UNPROVEN",
1895
+ "The Eve Container supervisor reported an error."
1896
+ );
1897
+ }
1898
+ };
1899
+ function createEveHostWorker(options) {
1900
+ if (!WORKER_NAME_PATTERN.test(options.workerName)) {
1901
+ throw new EveHostError(
1902
+ "HOST_ORIGIN_UNAVAILABLE",
1903
+ "The exact Worker name is not valid."
1904
+ );
1905
+ }
1906
+ assertStableOrigin(options.publicOrigin, options.workerName);
1907
+ assertNonEmpty(options.stableContainerInstanceName, "Container instance name");
1908
+ if (!IDENTIFIER_PATTERN.test(options.containerBindingName)) {
1909
+ throw new EveHostError(
1910
+ "HOST_READINESS_UNPROVEN",
1911
+ "The Container binding name is not valid."
1912
+ );
1913
+ }
1914
+ return {
1915
+ async fetch(request, env) {
1916
+ const namespace = env[options.containerBindingName];
1917
+ if (namespace === void 0) {
1918
+ throw new EveHostError(
1919
+ "HOST_READINESS_UNPROVEN",
1920
+ "The configured Container binding is unavailable."
1921
+ );
1922
+ }
1923
+ const container = namespace.getByName(
1924
+ options.stableContainerInstanceName
1925
+ );
1926
+ const forwarded = createTrustedEveRequest(request, {
1927
+ publicOrigin: options.publicOrigin,
1928
+ deploymentId: options.deploymentId,
1929
+ generationId: options.generationId,
1930
+ correlationId: globalThis.crypto.randomUUID(),
1931
+ ...options.runtimeRevisionHandle === void 0 ? {} : { runtimeRevisionHandle: options.runtimeRevisionHandle }
1932
+ });
1933
+ const response = await container.fetch(forwarded);
1934
+ const headers = new Headers(response.headers);
1935
+ headers.set("x-eden-eve-worker-name", options.workerName);
1936
+ headers.set("x-eden-eve-public-origin", options.publicOrigin);
1937
+ headers.set("x-eden-eve-deployment-id", options.deploymentId);
1938
+ headers.set("x-eden-eve-generation-id", options.generationId);
1939
+ headers.set(
1940
+ "x-eden-eve-container-instance",
1941
+ options.stableContainerInstanceName
1942
+ );
1943
+ if (options.runtimeRevisionHandle !== void 0) {
1944
+ headers.set(
1945
+ "x-eden-eve-runtime-revision",
1946
+ options.runtimeRevisionHandle
1947
+ );
1948
+ }
1949
+ return new Response(response.body, {
1950
+ status: response.status,
1951
+ statusText: response.statusText,
1952
+ headers
1953
+ });
1954
+ }
1955
+ };
1956
+ }
1957
+ export {
1958
+ EveHostContainer,
1959
+ createEveHostWorker
1960
+ };