better-effect 0.11.0 → 0.12.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.
- package/README.md +220 -6
- package/dist/adapters/iti.d.mts +2 -1
- package/dist/adapters/iti.d.mts.map +1 -1
- package/dist/adapters/iti.mjs +11 -10
- package/dist/adapters/iti.mjs.map +1 -1
- package/dist/{effect-2ZcGZI8A.mjs → effect-CK4YZaX0.mjs} +56 -10
- package/dist/effect-CK4YZaX0.mjs.map +1 -0
- package/dist/hono.d.mts +3 -3
- package/dist/hono.mjs +3 -3
- package/dist/{index-DStz0JMN.d.mts → index-B1nH4luq.d.mts} +73 -6
- package/dist/index-B1nH4luq.d.mts.map +1 -0
- package/dist/index-BMdU_Z72.d.mts +18 -0
- package/dist/index-BMdU_Z72.d.mts.map +1 -0
- package/dist/{index-C7Qild0_.d.mts → index-CX6iAoCB.d.mts} +15 -151
- package/dist/index-CX6iAoCB.d.mts.map +1 -0
- package/dist/index-GYJ4qm9K.d.mts +179 -0
- package/dist/index-GYJ4qm9K.d.mts.map +1 -0
- package/dist/index-heuaRmXR.d.mts.map +1 -1
- package/dist/index.d.mts +5 -3
- package/dist/index.mjs +6 -5
- package/dist/index.mjs.map +1 -1
- package/dist/{internal-identity-DmUpBeeL.mjs → internal-identity-CbXoZIfw.mjs} +3 -3
- package/dist/internal-identity-CbXoZIfw.mjs.map +1 -0
- package/dist/{signal-B97cs85Z.mjs → layer-D56fRdLt.mjs} +30 -111
- package/dist/layer-D56fRdLt.mjs.map +1 -0
- package/dist/node-context-DWsCUBRa.d.mts +12 -0
- package/dist/node-context-DWsCUBRa.d.mts.map +1 -0
- package/dist/node-context-lggRF4bR.mjs +25 -0
- package/dist/node-context-lggRF4bR.mjs.map +1 -0
- package/dist/node.d.mts +51 -0
- package/dist/node.d.mts.map +1 -0
- package/dist/node.mjs +233 -0
- package/dist/node.mjs.map +1 -0
- package/dist/{index-rQhZk3Nt.d.mts → outcome-CB43bnFW.d.mts} +29 -19
- package/dist/outcome-CB43bnFW.d.mts.map +1 -0
- package/dist/{scope-GGnmTQck.mjs → program-metadata-DhQCCirO.mjs} +18 -3
- package/dist/program-metadata-DhQCCirO.mjs.map +1 -0
- package/dist/registration-drnZk0SY.mjs +182 -0
- package/dist/registration-drnZk0SY.mjs.map +1 -0
- package/dist/runtime/node.d.mts +2 -11
- package/dist/runtime/node.mjs +2 -24
- package/dist/{runtime-DnMn0X0X.mjs → runtime-CBMrX8Wl.mjs} +210 -47
- package/dist/runtime-CBMrX8Wl.mjs.map +1 -0
- package/dist/signal-D2UTcaaG.mjs +105 -0
- package/dist/signal-D2UTcaaG.mjs.map +1 -0
- package/dist/{standard-services-BFBq-4lo.mjs → standard-services-GBZ32tll.mjs} +200 -16
- package/dist/standard-services-GBZ32tll.mjs.map +1 -0
- package/dist/standard-services.d.mts +3 -3
- package/dist/standard-services.mjs +3 -3
- package/dist/testing.d.mts +65 -6
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +191 -8
- package/dist/testing.mjs.map +1 -1
- package/package.json +8 -3
- package/dist/effect-2ZcGZI8A.mjs.map +0 -1
- package/dist/errors-Dnjhzbt0.mjs +0 -99
- package/dist/errors-Dnjhzbt0.mjs.map +0 -1
- package/dist/index-C7Qild0_.d.mts.map +0 -1
- package/dist/index-DStz0JMN.d.mts.map +0 -1
- package/dist/index-rQhZk3Nt.d.mts.map +0 -1
- package/dist/internal-identity-DmUpBeeL.mjs.map +0 -1
- package/dist/runtime/node.d.mts.map +0 -1
- package/dist/runtime/node.mjs.map +0 -1
- package/dist/runtime-DnMn0X0X.mjs.map +0 -1
- package/dist/scope-GGnmTQck.mjs.map +0 -1
- package/dist/signal-B97cs85Z.mjs.map +0 -1
- package/dist/standard-services-BFBq-4lo.mjs.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as CircularDependencyError, f as captureServiceTag, i as LayerDisposeError, l as ServiceAcquisitionError, n as normalizeLayerRegistration, o as LayerRegistrationError, r as DuplicateServiceError, s as ServiceTagCollisionError, t as captureLayerRegistrationTag, u as ServiceNotFoundError } from "./registration-drnZk0SY.mjs";
|
|
2
2
|
import { i as getRuntimeContext, l as makeRuntimeContext, u as runRuntimeContext } from "./context-BUEf1qjL.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { t as assertServiceCompatibility } from "./internal-identity-
|
|
3
|
+
import { l as defaultRuntimeContextStorage, n as linkAbortSignals } from "./signal-D2UTcaaG.mjs";
|
|
4
|
+
import { a as runScoped, i as Scope, o as ScopeRuntime, t as getProgramName } from "./program-metadata-DhQCCirO.mjs";
|
|
5
|
+
import { t as assertServiceCompatibility } from "./internal-identity-CbXoZIfw.mjs";
|
|
6
6
|
import { Err } from "better-result";
|
|
7
7
|
//#region src/layer/map-layer-backend.ts
|
|
8
8
|
/** Native map-backed Layer backend used by Runtime when no adapter is supplied. */
|
|
@@ -12,17 +12,18 @@ var MapLayerBackend = class {
|
|
|
12
12
|
pending = /* @__PURE__ */ new Map();
|
|
13
13
|
/** Register a provider, rejecting duplicate or colliding Service tags. */
|
|
14
14
|
register(registration) {
|
|
15
|
-
const
|
|
15
|
+
const normalized = normalizeLayerRegistration(registration);
|
|
16
|
+
const tag = captureLayerRegistrationTag(normalized);
|
|
16
17
|
const existing = this.providers.get(tag);
|
|
17
18
|
if (existing) {
|
|
18
|
-
if (existing.service !==
|
|
19
|
-
throw new DuplicateServiceError(
|
|
19
|
+
if (existing.service !== normalized.service) throw new ServiceTagCollisionError(existing.service, normalized.service);
|
|
20
|
+
throw new DuplicateServiceError(normalized.service);
|
|
20
21
|
}
|
|
21
|
-
this.providers.set(tag,
|
|
22
|
+
this.providers.set(tag, normalized);
|
|
22
23
|
}
|
|
23
24
|
/** Resolve and cache a provider instance by Service tag. */
|
|
24
25
|
async resolve(token) {
|
|
25
|
-
const tag = token
|
|
26
|
+
const tag = captureServiceTag(token);
|
|
26
27
|
const provider = this.providers.get(tag);
|
|
27
28
|
if (!provider) throw new ServiceNotFoundError(token);
|
|
28
29
|
const validate = (instance) => {
|
|
@@ -97,14 +98,15 @@ const notifyRuntimeObservers = (observers, select, event) => {
|
|
|
97
98
|
};
|
|
98
99
|
//#endregion
|
|
99
100
|
//#region src/layer/resolution.ts
|
|
100
|
-
const findCycleStart = (path,
|
|
101
|
+
const findCycleStart = (path, tag) => path.findIndex((current) => captureServiceTag(current) === tag);
|
|
101
102
|
const shouldPreserve = (cause) => cause instanceof CircularDependencyError || cause instanceof ServiceAcquisitionError || cause instanceof ServiceNotFoundError || cause instanceof ServiceTagCollisionError;
|
|
102
103
|
/** Wrap a backend with Runtime-local resolution paths and acquisition errors. */
|
|
103
104
|
const createResolutionResolver = (resolver, storage = defaultRuntimeContextStorage, observers = []) => {
|
|
104
105
|
const wrapped = { async resolve(token) {
|
|
106
|
+
const tag = captureServiceTag(token);
|
|
105
107
|
const context = getRuntimeContext(storage);
|
|
106
108
|
const path = context?.resolutionPath ?? [];
|
|
107
|
-
const cycleStart = findCycleStart(path,
|
|
109
|
+
const cycleStart = findCycleStart(path, tag);
|
|
108
110
|
const resolutionPath = [...path, token];
|
|
109
111
|
const notifyResolve = (outcome) => {
|
|
110
112
|
notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, {
|
|
@@ -147,6 +149,34 @@ const createResolutionResolver = (resolver, storage = defaultRuntimeContextStora
|
|
|
147
149
|
return wrapped;
|
|
148
150
|
};
|
|
149
151
|
//#endregion
|
|
152
|
+
//#region src/runtime/execution.ts
|
|
153
|
+
const hostMonotonicNow = () => {
|
|
154
|
+
if (typeof globalThis.performance?.now === "function") {
|
|
155
|
+
const value = globalThis.performance.now();
|
|
156
|
+
if (Number.isFinite(value)) return value;
|
|
157
|
+
}
|
|
158
|
+
const wallClock = Date.now();
|
|
159
|
+
return Number.isFinite(wallClock) ? wallClock : 0;
|
|
160
|
+
};
|
|
161
|
+
const makeMonotonicClock = () => {
|
|
162
|
+
let previous = 0;
|
|
163
|
+
return () => {
|
|
164
|
+
previous = Math.max(previous, hostMonotonicNow());
|
|
165
|
+
return previous;
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
let fallbackExecutionSequence = 0;
|
|
169
|
+
const makeExecutionIdGenerator = () => () => {
|
|
170
|
+
if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
|
|
171
|
+
fallbackExecutionSequence += 1;
|
|
172
|
+
return `execution-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${fallbackExecutionSequence.toString(36)}`;
|
|
173
|
+
};
|
|
174
|
+
/** Create isolated execution capabilities for one Runtime handle. */
|
|
175
|
+
const makeRuntimeExecutionDependencies = (overrides = {}) => ({
|
|
176
|
+
createExecutionId: overrides.createExecutionId ?? makeExecutionIdGenerator(),
|
|
177
|
+
now: overrides.now ?? makeMonotonicClock()
|
|
178
|
+
});
|
|
179
|
+
//#endregion
|
|
150
180
|
//#region src/layer/runtime.ts
|
|
151
181
|
const SCOPE_SUCCESS = Object.freeze({ status: "success" });
|
|
152
182
|
var RuntimeHandleDisposedError = class extends Error {
|
|
@@ -164,6 +194,34 @@ const validateDisposeOptions = (options) => {
|
|
|
164
194
|
const { gracePeriod } = options;
|
|
165
195
|
if (gracePeriod !== void 0 && (!Number.isFinite(gracePeriod) || gracePeriod < 0)) throw new RangeError("Runtime dispose gracePeriod must be a finite non-negative number");
|
|
166
196
|
};
|
|
197
|
+
const copyExecutionAttributes = (attributes) => {
|
|
198
|
+
if (attributes === void 0) return;
|
|
199
|
+
if (typeof attributes !== "object" || attributes === null) throw new TypeError("Runtime execution attributes must be an object");
|
|
200
|
+
return Object.freeze({ ...attributes });
|
|
201
|
+
};
|
|
202
|
+
const prepareExecution = (program, options, dependencies, runtimeSignal, shutdownSignal) => ({
|
|
203
|
+
metadata: makeExecutionMetadata(program, options?.attributes, dependencies),
|
|
204
|
+
signalLink: linkAbortSignals(runtimeSignal, options?.signal, shutdownSignal)
|
|
205
|
+
});
|
|
206
|
+
const makeExecutionMetadata = (program, attributes, dependencies) => {
|
|
207
|
+
const name = getProgramName(program);
|
|
208
|
+
const copiedAttributes = copyExecutionAttributes(attributes);
|
|
209
|
+
const metadata = {
|
|
210
|
+
executionId: dependencies.createExecutionId(),
|
|
211
|
+
startedAt: dependencies.now()
|
|
212
|
+
};
|
|
213
|
+
if (name !== void 0) metadata.name = name;
|
|
214
|
+
if (copiedAttributes !== void 0) metadata.attributes = copiedAttributes;
|
|
215
|
+
return Object.freeze(metadata);
|
|
216
|
+
};
|
|
217
|
+
const executionDuration = (metadata, dependencies) => {
|
|
218
|
+
try {
|
|
219
|
+
const elapsed = dependencies.now() - metadata.startedAt;
|
|
220
|
+
return Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0;
|
|
221
|
+
} catch {
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
167
225
|
const notifyShutdownFailure = async (observer, diagnostic) => {
|
|
168
226
|
if (!observer) return;
|
|
169
227
|
try {
|
|
@@ -188,6 +246,7 @@ const releaseLayerResource = async (service, release, outcome, observers) => {
|
|
|
188
246
|
};
|
|
189
247
|
const bindProviderToScope = (provider, scope, contextStorage, resolver, observers) => ({
|
|
190
248
|
service: provider.service,
|
|
249
|
+
serviceTag: provider.serviceTag,
|
|
191
250
|
acquire: () => {
|
|
192
251
|
const current = getRuntimeContext(contextStorage);
|
|
193
252
|
const context = makeRuntimeContext(resolver, scope, current?.resolutionPath ?? [], current?.signal, current);
|
|
@@ -225,11 +284,12 @@ var ExecutionLayerBackend = class {
|
|
|
225
284
|
this.root = root;
|
|
226
285
|
}
|
|
227
286
|
register(registration) {
|
|
228
|
-
this.localTags.add(registration
|
|
287
|
+
this.localTags.add(captureLayerRegistrationTag(registration));
|
|
229
288
|
this.local.register(registration);
|
|
230
289
|
}
|
|
231
290
|
async resolve(token) {
|
|
232
|
-
|
|
291
|
+
const tag = captureServiceTag(token);
|
|
292
|
+
if (this.localTags.has(tag)) return await this.local.resolve(token);
|
|
233
293
|
return await this.root.resolve(token);
|
|
234
294
|
}
|
|
235
295
|
async disposeAll() {
|
|
@@ -246,12 +306,15 @@ var RuntimeHandleImpl = class {
|
|
|
246
306
|
signal;
|
|
247
307
|
observers;
|
|
248
308
|
services;
|
|
309
|
+
executionDependencies;
|
|
249
310
|
disposePromise;
|
|
250
311
|
warmupPromise;
|
|
251
312
|
executions = /* @__PURE__ */ new Set();
|
|
313
|
+
serviceTags;
|
|
252
314
|
shutdownController = new AbortController();
|
|
253
315
|
state = "active";
|
|
254
|
-
|
|
316
|
+
warmupState = "idle";
|
|
317
|
+
constructor(backend, resolver, rootScope, onCleanupFailure, contextStorage, signal, observers, services, serviceTags, executionDependencies) {
|
|
255
318
|
this.backend = backend;
|
|
256
319
|
this.resolver = resolver;
|
|
257
320
|
this.rootScope = rootScope;
|
|
@@ -260,26 +323,80 @@ var RuntimeHandleImpl = class {
|
|
|
260
323
|
this.signal = signal;
|
|
261
324
|
this.observers = observers;
|
|
262
325
|
this.services = services;
|
|
326
|
+
this.executionDependencies = executionDependencies;
|
|
327
|
+
this.serviceTags = Object.freeze([...serviceTags]);
|
|
328
|
+
}
|
|
329
|
+
inspect() {
|
|
330
|
+
const executions = Object.freeze([...this.executions].map(({ metadata }) => {
|
|
331
|
+
const inspection = {
|
|
332
|
+
executionId: metadata.executionId,
|
|
333
|
+
startedAt: metadata.startedAt
|
|
334
|
+
};
|
|
335
|
+
if (metadata.name !== void 0) inspection.name = metadata.name;
|
|
336
|
+
return Object.freeze(inspection);
|
|
337
|
+
}));
|
|
338
|
+
return Object.freeze({
|
|
339
|
+
state: this.state,
|
|
340
|
+
warmup: this.warmupState,
|
|
341
|
+
activeExecutions: executions.length,
|
|
342
|
+
executions,
|
|
343
|
+
services: Object.freeze([...this.serviceTags]),
|
|
344
|
+
shutdownSignalAborted: this.shutdownController.signal.aborted
|
|
345
|
+
});
|
|
263
346
|
}
|
|
264
347
|
run(program, options) {
|
|
265
348
|
this.assertActive();
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
349
|
+
let prepared;
|
|
350
|
+
try {
|
|
351
|
+
prepared = prepareExecution(program, options, this.executionDependencies, this.signal, this.shutdownController.signal);
|
|
352
|
+
} catch (cause) {
|
|
353
|
+
return Promise.reject(cause);
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
this.assertActive();
|
|
357
|
+
} catch (cause) {
|
|
358
|
+
prepared.signalLink.dispose();
|
|
359
|
+
throw cause;
|
|
360
|
+
}
|
|
361
|
+
let executionScope;
|
|
362
|
+
try {
|
|
363
|
+
executionScope = this.rootScope.fork();
|
|
364
|
+
} catch (cause) {
|
|
365
|
+
prepared.signalLink.dispose();
|
|
366
|
+
throw cause;
|
|
367
|
+
}
|
|
368
|
+
return this.startExecution(prepared.signalLink, prepared.metadata, () => this.runExecution(executionScope, program, this.resolver, prepared.signalLink.signal, prepared.metadata));
|
|
269
369
|
}
|
|
270
370
|
runWith(layer, program, options) {
|
|
271
371
|
this.assertActive();
|
|
272
|
-
|
|
372
|
+
let prepared;
|
|
373
|
+
try {
|
|
374
|
+
prepared = prepareExecution(program, options, this.executionDependencies, this.signal, this.shutdownController.signal);
|
|
375
|
+
} catch (cause) {
|
|
376
|
+
return Promise.reject(cause);
|
|
377
|
+
}
|
|
378
|
+
try {
|
|
379
|
+
this.assertActive();
|
|
380
|
+
} catch (cause) {
|
|
381
|
+
prepared.signalLink.dispose();
|
|
382
|
+
throw cause;
|
|
383
|
+
}
|
|
273
384
|
const localBackend = new MapLayerBackend();
|
|
274
385
|
const backend = new ExecutionLayerBackend(localBackend, this.backend);
|
|
275
386
|
const resolver = createResolutionResolver(backend, this.contextStorage, this.observers);
|
|
276
|
-
|
|
277
|
-
|
|
387
|
+
let executionScope;
|
|
388
|
+
try {
|
|
389
|
+
executionScope = this.rootScope.fork();
|
|
390
|
+
} catch (cause) {
|
|
391
|
+
prepared.signalLink.dispose();
|
|
392
|
+
throw cause;
|
|
393
|
+
}
|
|
394
|
+
return this.startExecution(prepared.signalLink, prepared.metadata, async () => {
|
|
278
395
|
try {
|
|
279
396
|
return await this.runExecution(executionScope, async () => {
|
|
280
397
|
for (const provider of layer.providers) backend.register(bindProviderToScope(provider, executionScope, this.contextStorage, resolver, this.observers));
|
|
281
398
|
return await program();
|
|
282
|
-
}, resolver, signalLink.signal);
|
|
399
|
+
}, resolver, prepared.signalLink.signal, prepared.metadata);
|
|
283
400
|
} finally {
|
|
284
401
|
await localBackend.disposeAll();
|
|
285
402
|
}
|
|
@@ -288,25 +405,41 @@ var RuntimeHandleImpl = class {
|
|
|
288
405
|
warmup() {
|
|
289
406
|
this.assertActive();
|
|
290
407
|
if (this.warmupPromise) return this.warmupPromise;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
408
|
+
this.warmupState = "running";
|
|
409
|
+
let warmup;
|
|
410
|
+
try {
|
|
411
|
+
warmup = runRuntimeContext(this.contextStorage, makeRuntimeContext(this.resolver, this.rootScope, [], this.signal), async () => {
|
|
412
|
+
for (const service of this.services) await this.resolver.resolve(service);
|
|
413
|
+
});
|
|
414
|
+
} catch (cause) {
|
|
415
|
+
this.warmupState = "failed";
|
|
416
|
+
return Promise.reject(cause);
|
|
417
|
+
}
|
|
294
418
|
this.warmupPromise = warmup;
|
|
295
419
|
warmup.then(() => {
|
|
296
|
-
if (this.warmupPromise === warmup)
|
|
420
|
+
if (this.warmupPromise === warmup) {
|
|
421
|
+
this.warmupState = "completed";
|
|
422
|
+
this.warmupPromise = void 0;
|
|
423
|
+
}
|
|
297
424
|
}, () => {
|
|
298
|
-
if (this.warmupPromise === warmup)
|
|
425
|
+
if (this.warmupPromise === warmup) {
|
|
426
|
+
this.warmupState = "failed";
|
|
427
|
+
this.warmupPromise = void 0;
|
|
428
|
+
}
|
|
299
429
|
});
|
|
300
430
|
return warmup;
|
|
301
431
|
}
|
|
302
|
-
startExecution(signalLink, run) {
|
|
432
|
+
startExecution(signalLink, metadata, run) {
|
|
303
433
|
let resolveExecution;
|
|
304
434
|
let rejectExecution;
|
|
305
435
|
const execution = new Promise((resolve, reject) => {
|
|
306
436
|
resolveExecution = resolve;
|
|
307
437
|
rejectExecution = reject;
|
|
308
438
|
});
|
|
309
|
-
const activeExecution = {
|
|
439
|
+
const activeExecution = {
|
|
440
|
+
promise: execution,
|
|
441
|
+
metadata
|
|
442
|
+
};
|
|
310
443
|
this.executions.add(activeExecution);
|
|
311
444
|
execution.then(() => {
|
|
312
445
|
this.executions.delete(activeExecution);
|
|
@@ -316,7 +449,7 @@ var RuntimeHandleImpl = class {
|
|
|
316
449
|
signalLink.dispose();
|
|
317
450
|
});
|
|
318
451
|
try {
|
|
319
|
-
run().then((value) => {
|
|
452
|
+
run(metadata).then((value) => {
|
|
320
453
|
resolveExecution(value);
|
|
321
454
|
}, (cause) => {
|
|
322
455
|
rejectExecution(cause);
|
|
@@ -326,7 +459,7 @@ var RuntimeHandleImpl = class {
|
|
|
326
459
|
}
|
|
327
460
|
return execution;
|
|
328
461
|
}
|
|
329
|
-
runExecution(executionScope, program, resolver = this.resolver, signal = this.shutdownController.signal) {
|
|
462
|
+
runExecution(executionScope, program, resolver = this.resolver, signal = this.shutdownController.signal, metadata) {
|
|
330
463
|
let outcome;
|
|
331
464
|
const onOutcome = (determinedOutcome) => {
|
|
332
465
|
outcome = determinedOutcome;
|
|
@@ -339,21 +472,44 @@ var RuntimeHandleImpl = class {
|
|
|
339
472
|
classify: classifyRuntimeOutcome,
|
|
340
473
|
onOutcome
|
|
341
474
|
};
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
475
|
+
const startEvent = Object.freeze({
|
|
476
|
+
...metadata,
|
|
477
|
+
scope: executionScope
|
|
478
|
+
});
|
|
479
|
+
notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, startEvent);
|
|
480
|
+
let ended = false;
|
|
481
|
+
const notifyEnd = (finalOutcome) => {
|
|
482
|
+
if (ended) return;
|
|
483
|
+
ended = true;
|
|
484
|
+
const endEvent = Object.freeze({
|
|
485
|
+
...metadata,
|
|
349
486
|
scope: executionScope,
|
|
350
|
-
outcome
|
|
487
|
+
outcome: finalOutcome,
|
|
488
|
+
durationMs: executionDuration(metadata, this.executionDependencies)
|
|
489
|
+
});
|
|
490
|
+
notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, endEvent);
|
|
491
|
+
};
|
|
492
|
+
let execution;
|
|
493
|
+
try {
|
|
494
|
+
execution = runScoped(executionScope, program, {
|
|
495
|
+
...runOptions,
|
|
496
|
+
contextStorage: this.contextStorage,
|
|
497
|
+
context: makeRuntimeContext(resolver, executionScope, [], signal)
|
|
498
|
+
});
|
|
499
|
+
} catch (cause) {
|
|
500
|
+
notifyEnd({
|
|
501
|
+
status: "failure",
|
|
502
|
+
cause
|
|
351
503
|
});
|
|
504
|
+
return Promise.reject(cause);
|
|
505
|
+
}
|
|
506
|
+
return execution.then((value) => {
|
|
507
|
+
notifyEnd(outcome ?? { status: "success" });
|
|
352
508
|
return value;
|
|
353
509
|
}, (cause) => {
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
510
|
+
notifyEnd(outcome ?? {
|
|
511
|
+
status: "failure",
|
|
512
|
+
cause
|
|
357
513
|
});
|
|
358
514
|
throw cause;
|
|
359
515
|
});
|
|
@@ -417,11 +573,14 @@ var RuntimeHandleImpl = class {
|
|
|
417
573
|
}
|
|
418
574
|
};
|
|
419
575
|
/** Build a Runtime handle for a complete Layer and register its providers. */
|
|
420
|
-
const createRuntimeHandle = async (layer, backend, options = {}) => {
|
|
576
|
+
const createRuntimeHandle = async (layer, backend, options = {}, executionOverrides = {}) => {
|
|
577
|
+
const services = layer.providers.map((provider) => provider.service);
|
|
578
|
+
const serviceTags = layer.providers.map((provider) => captureLayerRegistrationTag(provider));
|
|
421
579
|
const rootScope = Scope.make();
|
|
422
580
|
const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage;
|
|
423
581
|
const observers = options.observers ?? [];
|
|
424
582
|
const resolver = createResolutionResolver(backend, contextStorage, observers);
|
|
583
|
+
const executionDependencies = makeRuntimeExecutionDependencies(executionOverrides);
|
|
425
584
|
ScopeRuntime.bind(rootScope, contextStorage);
|
|
426
585
|
let current;
|
|
427
586
|
try {
|
|
@@ -455,7 +614,7 @@ const createRuntimeHandle = async (layer, backend, options = {}) => {
|
|
|
455
614
|
const cleanupCause = cleanupCauses.length === 1 ? cleanupCauses[0] : cleanupCauses.length > 1 ? new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses)) : void 0;
|
|
456
615
|
throw new LayerRegistrationError(current?.service, registrationCause, cleanupCause);
|
|
457
616
|
}
|
|
458
|
-
return new RuntimeHandleImpl(backend, resolver, rootScope, options.onCleanupFailure, contextStorage, options.signal, observers,
|
|
617
|
+
return new RuntimeHandleImpl(backend, resolver, rootScope, options.onCleanupFailure, contextStorage, options.signal, observers, services, serviceTags, executionDependencies);
|
|
459
618
|
};
|
|
460
619
|
//#endregion
|
|
461
620
|
//#region src/runtime/runtime.ts
|
|
@@ -525,7 +684,7 @@ var Runtime = class Runtime {
|
|
|
525
684
|
let executionFailed = false;
|
|
526
685
|
let executionFailure;
|
|
527
686
|
try {
|
|
528
|
-
value = await runtime.runUnchecked(program);
|
|
687
|
+
value = await runtime.runUnchecked(program, config.options);
|
|
529
688
|
} catch (cause) {
|
|
530
689
|
executionFailed = true;
|
|
531
690
|
executionFailure = cause;
|
|
@@ -585,6 +744,10 @@ var Runtime = class Runtime {
|
|
|
585
744
|
throw cause;
|
|
586
745
|
}
|
|
587
746
|
}
|
|
747
|
+
/** Return a detached diagnostic snapshot without changing Runtime state. */
|
|
748
|
+
inspect() {
|
|
749
|
+
return this.handle.inspect();
|
|
750
|
+
}
|
|
588
751
|
/** Run one execution in this Runtime's child Scope. */
|
|
589
752
|
run(program, options) {
|
|
590
753
|
return this.handle.run(program, options);
|
|
@@ -593,8 +756,8 @@ var Runtime = class Runtime {
|
|
|
593
756
|
runWith(layer, program, options) {
|
|
594
757
|
return this.handle.runWith(layer, program, options);
|
|
595
758
|
}
|
|
596
|
-
runUnchecked(program) {
|
|
597
|
-
return this.handle.run(program);
|
|
759
|
+
runUnchecked(program, options) {
|
|
760
|
+
return this.handle.run(program, options);
|
|
598
761
|
}
|
|
599
762
|
dispose(optionsOrOutcome) {
|
|
600
763
|
return this.handle.dispose(optionsOrOutcome);
|
|
@@ -610,4 +773,4 @@ var Runtime = class Runtime {
|
|
|
610
773
|
//#endregion
|
|
611
774
|
export { MapLayerBackend as i, RuntimeObserver as n, classifyRuntimeOutcome as r, Runtime as t };
|
|
612
775
|
|
|
613
|
-
//# sourceMappingURL=runtime-
|
|
776
|
+
//# sourceMappingURL=runtime-CBMrX8Wl.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-CBMrX8Wl.mjs","names":[],"sources":["../src/layer/map-layer-backend.ts","../src/runtime/outcome.ts","../src/runtime/observer.ts","../src/layer/resolution.ts","../src/runtime/execution.ts","../src/layer/runtime.ts","../src/runtime/runtime.ts"],"sourcesContent":["import { assertServiceCompatibility } from './internal-identity'\nimport { captureLayerRegistrationTag, normalizeLayerRegistration } from './registration'\n\nimport { DuplicateServiceError, ServiceTagCollisionError } from './errors'\n\nimport type { LayerBackend, LayerBackendDisposeOptions } from './backend'\nimport type { LayerRegistration } from './types'\n\nimport { ServiceNotFoundError, type AnyServiceToken } from '../service'\nimport { captureServiceTag } from '../service/tag'\n\ntype LayerAcquiredValue = Awaited<ReturnType<LayerRegistration['acquire']>>\n\n/** Native map-backed Layer backend used by Runtime when no adapter is supplied. */\nexport class MapLayerBackend implements LayerBackend {\n private readonly providers = new Map<string, LayerRegistration>()\n\n private readonly instances = new Map<string, LayerAcquiredValue>()\n\n private readonly pending = new Map<string, Promise<LayerAcquiredValue>>()\n\n /** Register a provider, rejecting duplicate or colliding Service tags. */\n register(registration: LayerRegistration): void {\n const normalized = normalizeLayerRegistration(registration)\n const tag = captureLayerRegistrationTag(normalized)\n const existing = this.providers.get(tag)\n\n if (existing) {\n if (existing.service !== normalized.service) {\n throw new ServiceTagCollisionError(existing.service, normalized.service)\n }\n\n throw new DuplicateServiceError(normalized.service)\n }\n\n this.providers.set(tag, normalized)\n }\n\n /** Resolve and cache a provider instance by Service tag. */\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n const provider = this.providers.get(tag)\n\n if (!provider) {\n throw new ServiceNotFoundError(token)\n }\n\n const validate = (instance: LayerAcquiredValue): InstanceType<T> => {\n assertServiceCompatibility(token, provider.service, instance)\n\n // SAFETY: The provider and requested token share a tag, and compatibility checks verify the registered members before restoring the token-specific instance type.\n return instance as InstanceType<T>\n }\n\n const cached = this.instances.get(tag)\n\n if (cached !== undefined) {\n return validate(cached)\n }\n\n const pending = this.pending.get(tag)\n\n if (pending) {\n return validate(await pending)\n }\n\n const acquisition = Promise.resolve()\n .then(() => provider.acquire())\n .then((instance) => {\n validate(instance)\n this.instances.set(tag, instance)\n\n return instance\n })\n .finally(() => {\n this.pending.delete(tag)\n })\n\n this.pending.set(tag, acquisition)\n\n return validate(await acquisition)\n }\n\n /** Clear pending acquisitions, cached instances, and provider registrations. */\n async disposeAll(options?: LayerBackendDisposeOptions): Promise<void> {\n const acquisitions = [...this.pending.values()]\n\n if (acquisitions.length > 0) {\n const observePending = options?.onPendingAcquisitions\n\n if (observePending) {\n await observePending(acquisitions)\n }\n\n await Promise.allSettled(acquisitions)\n }\n\n this.instances.clear()\n this.pending.clear()\n this.providers.clear()\n }\n}\n","import { Err } from 'better-result'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from '../scope'\n\nimport type { LayerDisposeError } from '../layer/errors'\n\nimport type { LayerBackend } from '../layer/backend'\n\nimport type { RuntimeContextStorage } from './context'\n\nimport type { RuntimeExecutionAttributes, RuntimeObserver } from './observer'\n\n/** Aggregated cleanup information reported during Runtime shutdown. */\nexport type RuntimeShutdownDiagnostic = {\n /** Final outcome supplied to the Runtime root Scope. */\n readonly outcome: ScopeOutcome\n /** Aggregated root-Scope and backend cleanup failure. */\n readonly error: LayerDisposeError\n}\n\n/** Observer notified about cleanup failures without changing primary results. */\nexport type CleanupFailureObserver = (\n diagnostic: CleanupFailureDiagnostic | RuntimeShutdownDiagnostic\n) => MaybePromise<void>\n\n/** Optional Runtime configuration for cleanup diagnostics. */\nexport type RuntimeOptions = {\n /** Backend used to register and resolve the Layer. Defaults to MapLayerBackend. */\n readonly backend?: LayerBackend\n /** Resolve every Layer provider before Runtime.make resolves. */\n readonly warmup?: boolean\n /** Best-effort lifecycle and Service resolution observers. */\n readonly observers?: readonly RuntimeObserver[]\n /** Optional observer for best-effort cleanup diagnostics. */\n readonly onCleanupFailure?: CleanupFailureObserver\n /** Context storage used by Service, Scope and Layer resolution. */\n readonly contextStorage?: RuntimeContextStorage\n /** Optional signal exposed through the RuntimeContext. */\n readonly signal?: AbortSignal\n}\n\n/** Optional signal and diagnostic attributes supplied to one Runtime execution. */\nexport type RuntimeRunOptions = {\n readonly signal?: AbortSignal\n /** Copied once and exposed as a readonly event view. */\n readonly attributes?: RuntimeExecutionAttributes\n}\n\n/** Cooperative shutdown policy for a managed Runtime. */\nexport type RuntimeDisposeOptions = {\n /** Time to let active executions settle before requesting cancellation. */\n readonly gracePeriod?: number\n /** Abort active execution signals after the grace period expires. */\n readonly abortAfterGracePeriod?: boolean\n}\n\n/** Classify only a nominal better-result Err as a failed Runtime outcome. */\nexport const classifyRuntimeOutcome = <A>(value: A): ScopeOutcome => {\n if (value instanceof Err) {\n return {\n status: 'failure',\n cause: value.error\n }\n }\n\n return {\n status: 'success'\n }\n}\n","import type { AnyServiceToken } from '../service'\nimport type { Scope } from '../scope'\nimport type { ScopeOutcome } from '../scope'\nimport type { MaybePromise } from '../utils/types'\n\n/** Event emitted after a Service resolution attempt settles. */\nexport type RuntimeServiceResolveEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted after a provider acquisition attempt settles. */\nexport type RuntimeServiceAcquireEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n}\n\n/** Values supplied to one Runtime execution for diagnostic correlation. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- attributes intentionally accept caller-defined values.\nexport type RuntimeExecutionAttributes = Readonly<Record<string, unknown>>\n\n/** Metadata shared by the start and end events for one execution. */\nexport type RuntimeExecutionMetadata = {\n readonly executionId: string\n readonly name?: string\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- preserve the caller-defined attribute contract.\n readonly attributes?: RuntimeExecutionAttributes\n /** Monotonic host timestamp captured immediately before the Program starts. */\n readonly startedAt: number\n}\n\n/** Event emitted immediately before a program starts in an execution Scope. */\nexport type RuntimeExecutionStartEvent = RuntimeExecutionMetadata & {\n readonly scope: Scope\n}\n\n/** Event emitted after a program and its execution Scope settle. */\nexport type RuntimeExecutionEndEvent = RuntimeExecutionMetadata & {\n readonly scope: Scope\n readonly outcome: ScopeOutcome\n /** Monotonic elapsed time for the Program and its execution cleanup. */\n readonly durationMs: number\n}\n\n/** Event emitted after a Layer provider release callback settles. */\nexport type RuntimeResourceReleaseEvent = {\n readonly service: AnyServiceToken\n readonly outcome: ScopeOutcome\n readonly error?: unknown\n}\n\n/** Optional best-effort hooks for Runtime lifecycle and resolution events. */\nexport type RuntimeObserver = {\n readonly onServiceResolve?: (event: RuntimeServiceResolveEvent) => MaybePromise<void>\n readonly onServiceAcquire?: (event: RuntimeServiceAcquireEvent) => MaybePromise<void>\n readonly onExecutionStart?: (event: RuntimeExecutionStartEvent) => MaybePromise<void>\n readonly onExecutionEnd?: (event: RuntimeExecutionEndEvent) => MaybePromise<void>\n readonly onResourceRelease?: (event: RuntimeResourceReleaseEvent) => MaybePromise<void>\n}\n\n/** Compose best-effort Runtime observers into one observer. */\nexport const RuntimeObserver = {\n compose: (...observers: readonly RuntimeObserver[]): RuntimeObserver => ({\n onServiceResolve: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, event)\n },\n onServiceAcquire: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\n },\n onExecutionStart: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onExecutionStart, event)\n },\n onExecutionEnd: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onExecutionEnd, event)\n },\n onResourceRelease: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n }\n })\n}\n\nexport const notifyRuntimeObservers = <Event>(\n observers: readonly RuntimeObserver[],\n select: (observer: RuntimeObserver) => ((event: Event) => MaybePromise<void>) | undefined,\n event: Event\n): void => {\n for (const observer of observers) {\n const callback = select(observer)\n\n if (!callback) {\n continue\n }\n\n try {\n void Promise.resolve(callback(event)).catch(() => {})\n } catch {\n // Observability must never change the Runtime result.\n }\n }\n}\n","import { captureServiceTag } from '../service/tag'\n\nimport {\n CircularDependencyError,\n ServiceAcquisitionError,\n ServiceNotFoundError,\n type AnyServiceToken,\n type ServiceResolver\n} from '../service'\n\nimport { getRuntimeContext, makeRuntimeContext, runRuntimeContext } from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nimport { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport { ServiceTagCollisionError } from './errors'\n\nconst findCycleStart = (path: readonly AnyServiceToken[], tag: string): number =>\n path.findIndex((current) => captureServiceTag(current) === tag)\n\nconst shouldPreserve = (cause: unknown): boolean =>\n cause instanceof CircularDependencyError ||\n cause instanceof ServiceAcquisitionError ||\n cause instanceof ServiceNotFoundError ||\n cause instanceof ServiceTagCollisionError\n\n/** Wrap a backend with Runtime-local resolution paths and acquisition errors. */\nexport const createResolutionResolver = (\n resolver: ServiceResolver,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage,\n observers: readonly RuntimeObserver[] = []\n): ServiceResolver => {\n const wrapped: ServiceResolver = {\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n const context = getRuntimeContext(storage)\n const path = context?.resolutionPath ?? []\n const cycleStart = findCycleStart(path, tag)\n const resolutionPath = [...path, token]\n\n const notifyResolve = (outcome: ScopeOutcome): void => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, {\n service: token,\n resolutionPath,\n outcome\n })\n }\n\n if (cycleStart >= 0) {\n const error = new CircularDependencyError([...path.slice(cycleStart), token])\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n\n const nextContext = makeRuntimeContext(\n wrapped,\n context?.scope,\n resolutionPath,\n context?.signal,\n context\n )\n\n return await runRuntimeContext(storage, nextContext, async () => {\n try {\n const instance = await resolver.resolve(token)\n notifyResolve({ status: 'success' })\n return instance\n } catch (cause) {\n if (shouldPreserve(cause)) {\n notifyResolve({ status: 'failure', cause })\n throw cause\n }\n\n const error = new ServiceAcquisitionError(token, resolutionPath, cause)\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n })\n }\n }\n\n return wrapped\n}\n","export type RuntimeExecutionIdGenerator = () => string\n\nexport type RuntimeMonotonicClock = () => number\n\n/** Per-Runtime host capabilities used to correlate and time executions. */\nexport type RuntimeExecutionDependencies = {\n readonly createExecutionId: RuntimeExecutionIdGenerator\n readonly now: RuntimeMonotonicClock\n}\n\nexport type RuntimeExecutionDependencyOverrides = {\n readonly createExecutionId?: RuntimeExecutionIdGenerator\n readonly now?: RuntimeMonotonicClock\n}\n\nconst hostMonotonicNow = (): number => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- feature-detect the optional host clock.\n if (typeof globalThis.performance?.now === 'function') {\n const value = globalThis.performance.now()\n\n if (Number.isFinite(value)) {\n return value\n }\n }\n\n const wallClock = Date.now()\n return Number.isFinite(wallClock) ? wallClock : 0\n}\n\nconst makeMonotonicClock = (): RuntimeMonotonicClock => {\n let previous = 0\n\n return () => {\n previous = Math.max(previous, hostMonotonicNow())\n return previous\n }\n}\n\nlet fallbackExecutionSequence = 0\n\nconst makeExecutionIdGenerator = (): RuntimeExecutionIdGenerator => () => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- feature-detect the optional host ID source.\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID()\n }\n\n fallbackExecutionSequence += 1\n\n return `execution-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${fallbackExecutionSequence.toString(36)}`\n}\n\n/** Create isolated execution capabilities for one Runtime handle. */\nexport const makeRuntimeExecutionDependencies = (\n overrides: RuntimeExecutionDependencyOverrides = {}\n): RuntimeExecutionDependencies => ({\n createExecutionId: overrides.createExecutionId ?? makeExecutionIdGenerator(),\n now: overrides.now ?? makeMonotonicClock()\n})\n","import { captureServiceTag } from '../service/tag'\nimport type { AnyService, AnyServiceToken, ServiceResolver } from '../service'\n\nimport { Scope, type CloseableScope } from '../scope'\nimport { runScoped } from '../scope/internal'\nimport { ScopeRuntime } from '../scope/runtime'\n\nimport {\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport {\n classifyRuntimeOutcome,\n type CleanupFailureObserver,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from '../runtime/outcome'\n\nimport { linkAbortSignals, type AbortSignalLink } from '../runtime/signal'\n\nimport { LayerDisposeError, LayerRegistrationError } from './errors'\nimport { captureLayerRegistrationTag } from './registration'\n\nimport { createResolutionResolver } from './resolution'\n\nimport { getProgramName } from '../effect/program-metadata'\nimport type { ProgramIdentity } from '../effect/program-metadata'\n\nimport {\n makeRuntimeExecutionDependencies,\n type RuntimeExecutionDependencies,\n type RuntimeExecutionDependencyOverrides\n} from '../runtime/execution'\n\nimport { notifyRuntimeObservers } from '../runtime/observer'\n\nimport type {\n RuntimeExecutionAttributes,\n RuntimeExecutionMetadata,\n RuntimeObserver\n} from '../runtime/observer'\n\nimport type { RuntimeInspection } from '../runtime/types'\n\nimport type { LayerBackend } from './backend'\n\nimport { MapLayerBackend } from './map-layer-backend'\n\nimport type {\n CompleteExecution,\n CompleteExecutionLayer,\n CompleteInput,\n LayerInput,\n ProvidedEnvironment\n} from './inference'\n\nimport type { LayerRegistration } from './types'\n\nimport type { ScopeFinalizer, ScopeOutcome } from '../scope'\n\ntype LayerProvider = LayerInput['providers'][number]\n\ninterface RuntimeHandleCore<Provided extends AnyService> {\n /** The backend used to resolve this Layer's providers. */\n readonly backend: LayerBackend\n\n /** Run a program in a child Scope of the Layer's root Scope. */\n run<A>(program: CompleteExecution<Provided, A>, options?: RuntimeRunOptions): Promise<Awaited<A>>\n\n /** Run a program with providers owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>>\n\n /** Resolve every registered provider before accepting normal executions. */\n warmup(): Promise<void>\n\n /** Return a detached diagnostic snapshot without changing Runtime state. */\n inspect(): RuntimeInspection\n\n /** Stop new executions and release Layer-owned resources. */\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void>\n}\n\n/** Runtime-facing handle that owns a Layer's resources and execution scopes. */\nexport type RuntimeHandle<Provided extends AnyService = any> = RuntimeHandleCore<Provided>\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass RuntimeHandleDisposedError extends Error {\n constructor() {\n super('Cannot run a program using a disposed Layer')\n\n this.name = 'RuntimeHandleDisposedError'\n }\n}\n\nconst normalizeDisposeCauses = (cause: unknown): readonly unknown[] => {\n if (cause instanceof AggregateError) {\n return [...cause.errors]\n }\n\n return [cause]\n}\n\nconst isScopeOutcome = (\n input: RuntimeDisposeOptions | ScopeOutcome | undefined\n): input is ScopeOutcome => input !== undefined && 'status' in input\n\nconst validateDisposeOptions = (options: RuntimeDisposeOptions): void => {\n const { gracePeriod } = options\n\n if (gracePeriod !== undefined && (!Number.isFinite(gracePeriod) || gracePeriod < 0)) {\n throw new RangeError('Runtime dispose gracePeriod must be a finite non-negative number')\n }\n}\n\ntype ActiveExecution = {\n readonly promise: Promise<unknown>\n readonly metadata: RuntimeExecutionMetadata\n}\n\ntype MutableRuntimeExecutionInspection = {\n executionId: string\n startedAt: number\n name?: string\n}\n\nconst copyExecutionAttributes = (\n attributes: RuntimeExecutionAttributes | undefined\n): RuntimeExecutionAttributes | undefined => {\n if (attributes === undefined) {\n return undefined\n }\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validate JavaScript callers at the Runtime boundary.\n if (typeof attributes !== 'object' || attributes === null) {\n throw new TypeError('Runtime execution attributes must be an object')\n }\n\n return Object.freeze({ ...attributes })\n}\n\ntype MutableRuntimeExecutionMetadata = {\n executionId: string\n startedAt: number\n name?: string\n attributes?: RuntimeExecutionAttributes\n}\n\ntype PreparedExecution = {\n readonly metadata: RuntimeExecutionMetadata\n readonly signalLink: AbortSignalLink\n}\n\nconst prepareExecution = <ProgramValue>(\n program: () => ProgramValue | PromiseLike<ProgramValue>,\n options: RuntimeRunOptions | undefined,\n dependencies: RuntimeExecutionDependencies,\n runtimeSignal: AbortSignal | undefined,\n shutdownSignal: AbortSignal\n): PreparedExecution => ({\n metadata: makeExecutionMetadata(program, options?.attributes, dependencies),\n signalLink: linkAbortSignals(runtimeSignal, options?.signal, shutdownSignal)\n})\n\nconst makeExecutionMetadata = (\n program: ProgramIdentity,\n attributes: RuntimeExecutionAttributes | undefined,\n dependencies: RuntimeExecutionDependencies\n): RuntimeExecutionMetadata => {\n const name = getProgramName(program)\n const copiedAttributes = copyExecutionAttributes(attributes)\n\n const metadata: MutableRuntimeExecutionMetadata = {\n executionId: dependencies.createExecutionId(),\n startedAt: dependencies.now()\n }\n\n if (name !== undefined) {\n metadata.name = name\n }\n\n if (copiedAttributes !== undefined) {\n metadata.attributes = copiedAttributes\n }\n\n return Object.freeze(metadata)\n}\n\nconst executionDuration = (\n metadata: RuntimeExecutionMetadata,\n dependencies: RuntimeExecutionDependencies\n): number => {\n try {\n const elapsed = dependencies.now() - metadata.startedAt\n\n return Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0\n } catch {\n return 0\n }\n}\n\nconst notifyShutdownFailure = async (\n observer: CleanupFailureObserver | undefined,\n diagnostic: RuntimeShutdownDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Shutdown diagnostics are best effort and never affect the primary result.\n }\n}\n\nconst releaseLayerResource = async (\n service: LayerProvider['service'],\n release: ScopeFinalizer,\n outcome: ScopeOutcome,\n observers: readonly RuntimeObserver[]\n): Promise<void> => {\n try {\n await release(outcome)\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service,\n outcome\n })\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service,\n outcome,\n error: cause\n })\n throw cause\n }\n}\n\nconst bindProviderToScope = (\n provider: LayerProvider,\n scope: CloseableScope,\n contextStorage: RuntimeContextStorage,\n resolver: ServiceResolver,\n observers: readonly RuntimeObserver[]\n): LayerRegistration => ({\n service: provider.service,\n serviceTag: provider.serviceTag,\n\n acquire: () => {\n const current = getRuntimeContext(contextStorage)\n const context = makeRuntimeContext(\n resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal,\n current\n )\n\n return runRuntimeContext(contextStorage, context, () =>\n ScopeRuntime.run(\n scope,\n async () => {\n const resolutionPath = current?.resolutionPath ?? [provider.service]\n\n try {\n const instance = provider.acquireWithRelease\n ? (\n await scope.acquire(provider.acquireWithRelease, (acquired, outcome) =>\n releaseLayerResource(provider.service, acquired.release, outcome, observers)\n )\n ).instance\n : provider.release\n ? await scope.acquire(\n () => provider.acquire(),\n (resource, outcome) =>\n releaseLayerResource(\n provider.service,\n (releaseOutcome) => provider.release!(resource, releaseOutcome),\n outcome,\n observers\n )\n )\n : await provider.acquire()\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: SCOPE_SUCCESS\n })\n\n return instance\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: {\n status: 'failure',\n cause\n }\n })\n throw cause\n }\n },\n contextStorage\n )\n )\n }\n})\n\n/** Resolve request-local providers first, then fall back to the Runtime root. */\nclass ExecutionLayerBackend implements LayerBackend {\n private readonly localTags = new Set<string>()\n\n constructor(\n private readonly local: MapLayerBackend,\n private readonly root: LayerBackend\n ) {}\n\n register(registration: LayerRegistration): void {\n this.localTags.add(captureLayerRegistrationTag(registration))\n this.local.register(registration)\n }\n\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n\n if (this.localTags.has(tag)) {\n return await this.local.resolve(token)\n }\n\n return await this.root.resolve(token)\n }\n\n async disposeAll(): Promise<void> {\n await this.local.disposeAll()\n this.localTags.clear()\n }\n}\n\nclass RuntimeHandleImpl<Provided extends AnyService> implements RuntimeHandleCore<Provided> {\n private disposePromise: Promise<void> | undefined\n\n private warmupPromise: Promise<void> | undefined\n\n private readonly executions = new Set<ActiveExecution>()\n\n private readonly serviceTags: readonly string[]\n\n private readonly shutdownController = new AbortController()\n\n private state: 'active' | 'disposing' | 'disposed' = 'active'\n\n private warmupState: RuntimeInspection['warmup'] = 'idle'\n\n constructor(\n readonly backend: LayerBackend,\n private readonly resolver: ServiceResolver,\n private readonly rootScope: CloseableScope,\n private readonly onCleanupFailure: CleanupFailureObserver | undefined,\n private readonly contextStorage: RuntimeContextStorage,\n private readonly signal: AbortSignal | undefined,\n private readonly observers: readonly RuntimeObserver[],\n private readonly services: readonly AnyServiceToken[],\n serviceTags: readonly string[],\n private readonly executionDependencies: RuntimeExecutionDependencies\n ) {\n this.serviceTags = Object.freeze([...serviceTags])\n }\n\n inspect(): RuntimeInspection {\n const executions = Object.freeze(\n [...this.executions].map(({ metadata }) => {\n const inspection: MutableRuntimeExecutionInspection = {\n executionId: metadata.executionId,\n startedAt: metadata.startedAt\n }\n\n if (metadata.name !== undefined) {\n inspection.name = metadata.name\n }\n\n return Object.freeze(inspection)\n })\n )\n\n return Object.freeze({\n state: this.state,\n warmup: this.warmupState,\n activeExecutions: executions.length,\n executions,\n services: Object.freeze([...this.serviceTags]),\n shutdownSignalAborted: this.shutdownController.signal.aborted\n })\n }\n\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n let prepared: PreparedExecution\n\n try {\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal\n )\n } catch (cause) {\n return Promise.reject(cause)\n }\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n return this.startExecution<Awaited<A>>(prepared.signalLink, prepared.metadata, () =>\n this.runExecution(\n executionScope,\n program,\n this.resolver,\n prepared.signalLink.signal,\n prepared.metadata\n )\n )\n }\n\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n let prepared: PreparedExecution\n\n try {\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal\n )\n } catch (cause) {\n return Promise.reject(cause)\n }\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n return this.startExecution<Awaited<A>>(\n prepared.signalLink,\n prepared.metadata,\n async (): Promise<Awaited<A>> => {\n try {\n return await this.runExecution<Awaited<A>>(\n executionScope,\n async (): Promise<Awaited<A>> => {\n for (const provider of layer.providers) {\n backend.register(\n bindProviderToScope(\n provider,\n executionScope,\n this.contextStorage,\n resolver,\n this.observers\n )\n )\n }\n\n return await program()\n },\n resolver,\n prepared.signalLink.signal,\n prepared.metadata\n )\n } finally {\n await localBackend.disposeAll()\n }\n }\n )\n }\n\n warmup(): Promise<void> {\n this.assertActive()\n\n if (this.warmupPromise) {\n return this.warmupPromise\n }\n\n this.warmupState = 'running'\n\n let warmup: Promise<void>\n\n try {\n warmup = runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], this.signal),\n async () => {\n for (const service of this.services) {\n await this.resolver.resolve(service)\n }\n }\n )\n } catch (cause) {\n this.warmupState = 'failed'\n return Promise.reject(cause)\n }\n\n this.warmupPromise = warmup\n\n void warmup.then(\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupState = 'completed'\n this.warmupPromise = undefined\n }\n },\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupState = 'failed'\n this.warmupPromise = undefined\n }\n }\n )\n\n return warmup\n }\n\n private startExecution<A>(\n signalLink: AbortSignalLink,\n metadata: RuntimeExecutionMetadata,\n run: (metadata: RuntimeExecutionMetadata) => PromiseLike<A>\n ): Promise<A> {\n let resolveExecution!: (value: A | PromiseLike<A>) => void\n let rejectExecution!: (cause?: unknown) => void\n\n const execution = new Promise<A>((resolve, reject) => {\n resolveExecution = resolve\n rejectExecution = reject\n })\n\n const activeExecution: ActiveExecution = { promise: execution, metadata }\n\n this.executions.add(activeExecution)\n\n void execution.then(\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n },\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n }\n )\n\n try {\n const running = run(metadata)\n\n void running.then(\n (value) => {\n resolveExecution(value)\n },\n (cause) => {\n rejectExecution(cause)\n }\n )\n } catch (cause) {\n rejectExecution(cause)\n }\n\n return execution\n }\n\n private runExecution<A>(\n executionScope: CloseableScope,\n program: () => A | PromiseLike<A>,\n resolver: ServiceResolver = this.resolver,\n signal: AbortSignal = this.shutdownController.signal,\n metadata: RuntimeExecutionMetadata\n ): Promise<Awaited<A>> {\n let outcome: ScopeOutcome | undefined\n const onOutcome = (determinedOutcome: ScopeOutcome): void => {\n outcome = determinedOutcome\n }\n const runOptions = this.onCleanupFailure\n ? {\n classify: classifyRuntimeOutcome,\n onOutcome,\n onCleanupFailure: this.onCleanupFailure\n }\n : {\n classify: classifyRuntimeOutcome,\n onOutcome\n }\n\n const startEvent = Object.freeze({\n ...metadata,\n scope: executionScope\n })\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, startEvent)\n\n let ended = false\n const notifyEnd = (finalOutcome: ScopeOutcome): void => {\n if (ended) {\n return\n }\n\n ended = true\n const endEvent = Object.freeze({\n ...metadata,\n scope: executionScope,\n outcome: finalOutcome,\n durationMs: executionDuration(metadata, this.executionDependencies)\n })\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, endEvent)\n }\n\n let execution: Promise<Awaited<A>>\n\n try {\n execution = runScoped(executionScope, program, {\n ...runOptions,\n contextStorage: this.contextStorage,\n context: makeRuntimeContext(resolver, executionScope, [], signal)\n })\n } catch (cause) {\n const failure: ScopeOutcome = {\n status: 'failure',\n cause\n }\n notifyEnd(failure)\n return Promise.reject(cause)\n }\n\n return execution.then(\n (value) => {\n notifyEnd(\n outcome ?? {\n status: 'success'\n }\n )\n return value\n },\n (cause) => {\n notifyEnd(\n outcome ?? {\n status: 'failure',\n cause\n }\n )\n throw cause\n }\n )\n }\n\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n if (this.disposePromise) {\n return this.disposePromise\n }\n\n const outcome =\n isScopeOutcome(input) || input === undefined ? (input ?? SCOPE_SUCCESS) : SCOPE_SUCCESS\n const options = isScopeOutcome(input) || input === undefined ? {} : input\n\n validateDisposeOptions(options)\n this.state = 'disposing'\n\n const executions = [...this.executions]\n\n this.disposePromise = this.performDispose(executions, outcome, options)\n\n return this.disposePromise\n }\n\n private async performDispose(\n executions: readonly ActiveExecution[],\n outcome: ScopeOutcome,\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const failures: unknown[] = []\n\n await Promise.allSettled(this.warmupPromise ? [this.warmupPromise] : [])\n await this.waitForExecutions(executions, options)\n\n try {\n const signalLink = linkAbortSignals(this.signal, this.shutdownController.signal)\n\n try {\n await runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], signalLink.signal),\n () => this.rootScope.close(outcome)\n )\n } finally {\n signalLink.dispose()\n }\n } catch (cause) {\n failures.push(cause)\n }\n\n try {\n await this.backend.disposeAll()\n } catch (cause) {\n failures.push(cause)\n }\n\n this.state = 'disposed'\n\n if (failures.length > 0) {\n const error = new LayerDisposeError(failures.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(this.onCleanupFailure, {\n outcome,\n error\n })\n\n throw error\n }\n }\n\n private async waitForExecutions(\n executions: readonly ActiveExecution[],\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const settled = Promise.allSettled(executions.map((execution) => execution.promise))\n\n if (options.abortAfterGracePeriod !== true || executions.length === 0) {\n await settled\n return\n }\n\n const gracePeriod = options.gracePeriod ?? 0\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const timedOut = await Promise.race([\n settled.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), gracePeriod)\n })\n ])\n\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n\n if (timedOut && !this.shutdownController.signal.aborted) {\n this.shutdownController.abort(new Error('Runtime shutdown grace period exceeded'))\n }\n\n await settled\n }\n\n private assertActive(): void {\n if (this.state !== 'active') {\n throw new RuntimeHandleDisposedError()\n }\n }\n}\n\n/** Build a Runtime handle for a complete Layer and register its providers. */\nexport const createRuntimeHandle = async <L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options: RuntimeOptions = {},\n executionOverrides: RuntimeExecutionDependencyOverrides = {}\n): Promise<RuntimeHandle<ProvidedEnvironment<L>>> => {\n const services = layer.providers.map((provider) => provider.service)\n const serviceTags = layer.providers.map((provider) => captureLayerRegistrationTag(provider))\n const rootScope = Scope.make()\n const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage\n const observers = options.observers ?? []\n const resolver = createResolutionResolver(backend, contextStorage, observers)\n const executionDependencies = makeRuntimeExecutionDependencies(executionOverrides)\n ScopeRuntime.bind(rootScope, contextStorage)\n let current: LayerProvider | undefined\n\n try {\n for (const provider of layer.providers) {\n current = provider\n\n await backend.register(\n bindProviderToScope(provider, rootScope, contextStorage, resolver, observers)\n )\n }\n } catch (registrationCause) {\n const outcome: ScopeOutcome = {\n status: 'failure',\n cause: registrationCause\n }\n const cleanupCauses: unknown[] = []\n\n try {\n await runRuntimeContext(\n contextStorage,\n makeRuntimeContext(resolver, rootScope, [], options.signal),\n () => rootScope.close(outcome)\n )\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n try {\n await backend.disposeAll()\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n if (cleanupCauses.length > 0) {\n const shutdownError = new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(options.onCleanupFailure, {\n outcome,\n error: shutdownError\n })\n }\n\n const cleanupCause =\n cleanupCauses.length === 1\n ? cleanupCauses[0]\n : cleanupCauses.length > 1\n ? new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n : undefined\n\n throw new LayerRegistrationError(current?.service, registrationCause, cleanupCause)\n }\n\n return new RuntimeHandleImpl<ProvidedEnvironment<L>>(\n backend,\n resolver,\n rootScope,\n options.onCleanupFailure,\n contextStorage,\n options.signal,\n observers,\n services,\n serviceTags,\n executionDependencies\n )\n}\n","import type { LayerBackend } from '../layer'\n\nimport { MapLayerBackend } from '../layer/map-layer-backend'\n\nimport { createRuntimeHandle, type RuntimeHandle } from '../layer/runtime'\n\nimport type {\n CompleteExecutionLayer,\n LayerInput,\n CompleteInput,\n ProvidedEnvironment\n} from '../layer/inference'\n\nimport type { CompleteExecution } from '../layer/inference'\n\nimport type { AnyService } from '../service'\n\nimport {\n classifyRuntimeOutcome,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from './outcome'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport type { RuntimeExecutionInspection, RuntimeFor, RuntimeInspection } from './types'\n\nimport type { RuntimeObserver } from './observer'\n\ntype RuntimeOptionsInput = RuntimeOptions & RuntimeRunOptions\n\ntype RuntimeBackendInput = LayerBackend | RuntimeOptionsInput | undefined\n\ntype RuntimeConfig = {\n readonly backend: LayerBackend\n readonly options: RuntimeOptionsInput\n}\n\nconst isLayerBackend = (value: RuntimeBackendInput): value is LayerBackend =>\n value !== undefined && 'register' in value && 'resolve' in value && 'disposeAll' in value\n\nconst resolveRuntimeConfig = (\n backendOrOptions: RuntimeBackendInput,\n legacyOptions?: RuntimeOptionsInput\n): RuntimeConfig => {\n if (isLayerBackend(backendOrOptions)) {\n return {\n backend: backendOrOptions,\n options: legacyOptions ?? {}\n }\n }\n\n const options = backendOrOptions ?? {}\n\n return {\n backend: options.backend ?? new MapLayerBackend(),\n options\n }\n}\n\n/**\n * Long-lived execution environment backed by a complete Layer.\n *\n * A Runtime owns Layer resources until `dispose()` is called. Each `run()` is\n * isolated in a child Scope, while Layer-scoped resources remain shared.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(loadUser('u1'))\n * await runtime.dispose()\n * ```\n *\n * @typeParam Provided The branded Service instances supplied by the Layer.\n */\nexport class Runtime<Provided extends AnyService = any> {\n private constructor(private readonly handle: RuntimeHandle<Provided>) {}\n\n /**\n * Create a long-lived Runtime that owns its Layer resources.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(program)\n * await runtime.dispose()\n * ```\n */\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static async make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrOptions?: LayerBackend | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>> {\n const { backend, options } = resolveRuntimeConfig(backendOrOptions, legacyOptions)\n const handle = await createRuntimeHandle(layer, backend, options)\n const runtime = new Runtime<ProvidedEnvironment<L>>(handle)\n\n if (options.warmup) {\n await runtime.warmup()\n }\n\n return runtime\n }\n\n /**\n * Run one program and dispose its Layer resources before resolving.\n *\n * This is convenient for request-style or command-style execution where a\n * Runtime should not outlive the operation.\n */\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptionsInput\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptionsInput\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options: RuntimeOptionsInput,\n program: CompleteExecution<ProvidedEnvironment<L>, A>\n ): Promise<Awaited<A>>\n\n static async run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrProgramOrOptions:\n | LayerBackend\n | RuntimeOptionsInput\n | CompleteExecution<ProvidedEnvironment<L>, A>,\n programOrOptions?: CompleteExecution<ProvidedEnvironment<L>, A> | RuntimeOptionsInput,\n legacyOptions?: RuntimeOptionsInput\n ): Promise<Awaited<A>> {\n let program: CompleteExecution<ProvidedEnvironment<L>, A>\n let backendOrOptions: RuntimeBackendInput\n let options: RuntimeOptionsInput | undefined\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch needs to distinguish a Program callback from configuration.\n if (typeof backendOrProgramOrOptions === 'function') {\n program = backendOrProgramOrOptions\n // SAFETY: The function overload branch establishes that this argument is the optional RuntimeOptions value.\n backendOrOptions = programOrOptions as RuntimeOptionsInput | undefined\n options = undefined\n } else {\n backendOrOptions = backendOrProgramOrOptions\n // SAFETY: The non-function overload branch establishes that this argument is the complete execution callback.\n program = programOrOptions as CompleteExecution<ProvidedEnvironment<L>, A>\n options = legacyOptions\n }\n\n const config = resolveRuntimeConfig(backendOrOptions, options)\n let programOutcome: ScopeOutcome | undefined\n const outcomeObserver: RuntimeObserver = {\n onExecutionEnd: ({ outcome }) => {\n programOutcome = outcome\n }\n }\n const runtimeOptions: RuntimeOptions = {\n ...config.options,\n observers: [outcomeObserver, ...(config.options.observers ?? [])]\n }\n const runtime = await Runtime.make(layer, config.backend, runtimeOptions)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n\n try {\n value = await runtime.runUnchecked(program, config.options)\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Run a callback with a managed Runtime and always dispose it afterward. */\n static use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static async use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>> {\n const runtime = await Runtime.make(layer, options)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n let programOutcome: ScopeOutcome | undefined\n\n try {\n value = await use(runtime)\n programOutcome = classifyRuntimeOutcome(value)\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n programOutcome = {\n status: 'failure',\n cause\n }\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Resolve every Layer provider and dispose the Runtime if warmup fails. */\n async warmup(): Promise<void> {\n try {\n await this.handle.warmup()\n } catch (cause) {\n try {\n await this.handle.dispose({ status: 'failure', cause })\n } catch {\n // Warmup failure remains the primary error; cleanup is best effort.\n }\n\n throw cause\n }\n }\n\n /** Return a detached diagnostic snapshot without changing Runtime state. */\n inspect(): RuntimeInspection {\n return this.handle.inspect()\n }\n\n /** Run one execution in this Runtime's child Scope. */\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.run(program, options)\n }\n\n /** Run one execution with a Layer owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.runWith(layer, program, options)\n }\n\n private runUnchecked<A>(\n program: () => A | PromiseLike<A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n // SAFETY: One-shot Runtime.run performs the same complete-program validation at its public boundary before using this internal escape hatch.\n return this.handle.run(program as CompleteExecution<Provided, A>, options)\n }\n\n /** Stop new executions and release the Runtime's Layer resources. */\n dispose(options?: RuntimeDisposeOptions): Promise<void>\n\n /** @deprecated Scope outcomes are kept for internal compatibility. */\n dispose(outcome: ScopeOutcome): Promise<void>\n\n dispose(optionsOrOutcome?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n return this.handle.dispose(optionsOrOutcome)\n }\n\n /** Release Runtime-owned resources through JavaScript's async disposal protocol. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose()\n }\n\n private disposeWithOutcome(outcome: ScopeOutcome): Promise<void> {\n return this.handle.dispose(outcome)\n }\n}\n\n/** Type-level aliases for naming Runtime handles and shutdown options. */\nexport declare namespace Runtime {\n /** Name a Runtime type from a concrete Layer. */\n export type For<L extends LayerInput> = RuntimeFor<L>\n\n /** Optional Runtime shutdown configuration. */\n export type Options = RuntimeOptions\n\n /** Optional signal supplied to one managed Runtime execution. */\n export type RunOptions = RuntimeRunOptions\n\n /** Cooperative shutdown policy for a managed Runtime. */\n export type DisposeOptions = RuntimeDisposeOptions\n\n /** Diagnostic reported for aggregated Runtime shutdown cleanup failures. */\n export type ShutdownDiagnostic = RuntimeShutdownDiagnostic\n\n /** Detached diagnostic snapshot returned by `Runtime.inspect()`. */\n export type Inspection = RuntimeInspection\n\n /** Detached diagnostic view of one active execution. */\n export type ExecutionInspection = RuntimeExecutionInspection\n}\n"],"mappings":";;;;;;;;AAcA,IAAa,kBAAb,MAAqD;CACnD,4BAA6B,IAAI,IAA+B;CAEhE,4BAA6B,IAAI,IAAgC;CAEjE,0BAA2B,IAAI,IAAyC;;CAGxE,SAAS,cAAuC;EAC9C,MAAM,aAAa,2BA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