@grafctory/gear 0.0.0-stage → 0.6.1

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.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Checks if a value supports synchronous disposal.
3
+ *
4
+ * Recognises the protocol by shape rather than by declaration, so that any value carrying a callable `Symbol.dispose`
5
+ * member, own or inherited, is accepted, whether or not it was typed as `Disposable`.
6
+ *
7
+ * The two disposal protocols are independent: a value implementing both is accepted here and by
8
+ * {@link isAsyncDisposable} alike, leaving the caller to decide which one takes precedence.
9
+ *
10
+ * @param value The value to be checked
11
+ *
12
+ * @returns true if `value` is an object or a function exposing a callable `Symbol.dispose` method; false otherwise
13
+ *
14
+ * @see {@link https://tc39.es/proposal-explicit-resource-management/ ECMAScript Explicit Resource Management}
15
+ */
16
+ export declare function isDisposable(value: unknown): value is Disposable;
17
+ /**
18
+ * Checks if a value supports asynchronous disposal.
19
+ *
20
+ * Recognises the protocol by shape rather than by declaration, so that any value carrying a callable
21
+ * `Symbol.asyncDispose` member, own or inherited, is accepted, whether or not it was typed as `AsyncDisposable`.
22
+ *
23
+ * The two disposal protocols are independent: a value implementing both is accepted here and by {@link isDisposable}
24
+ * alike, leaving the caller to decide which one takes precedence.
25
+ *
26
+ * @param value The value to be checked
27
+ *
28
+ * @returns true if `value` is an object or a function exposing a callable `Symbol.asyncDispose` method; false otherwise
29
+ *
30
+ * @see {@link https://tc39.es/proposal-explicit-resource-management/ ECMAScript Explicit Resource Management}
31
+ */
32
+ export declare function isAsyncDisposable(value: unknown): value is AsyncDisposable;
33
+ /**
34
+ * Terminates the process on an uncaught exception.
35
+ *
36
+ * Prints the exception and its stack trace to the standard error stream, then exits with the status Node assigns to
37
+ * uncaught exceptions. The source excerpt Node prints by default is left out, as it points at the helper that threw
38
+ * rather than at the actual failure. The output is written synchronously, so the exit never truncates it.
39
+ *
40
+ * @param error The uncaught exception
41
+ */
42
+ export declare function terminate(error: unknown): never;
43
+ //# sourceMappingURL=index.core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.core.d.ts","sourceRoot":"","sources":["../src/index.core.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,UAAU,CAMhE;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,eAAe,CAM1E;AAGD;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAM/C"}
@@ -0,0 +1,71 @@
1
+ /*
2
+ * Copyright © 2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { writeSync } from "node:fs";
17
+ import { inspect } from "node:util";
18
+ /**
19
+ * Checks if a value supports synchronous disposal.
20
+ *
21
+ * Recognises the protocol by shape rather than by declaration, so that any value carrying a callable `Symbol.dispose`
22
+ * member, own or inherited, is accepted, whether or not it was typed as `Disposable`.
23
+ *
24
+ * The two disposal protocols are independent: a value implementing both is accepted here and by
25
+ * {@link isAsyncDisposable} alike, leaving the caller to decide which one takes precedence.
26
+ *
27
+ * @param value The value to be checked
28
+ *
29
+ * @returns true if `value` is an object or a function exposing a callable `Symbol.dispose` method; false otherwise
30
+ *
31
+ * @see {@link https://tc39.es/proposal-explicit-resource-management/ ECMAScript Explicit Resource Management}
32
+ */
33
+ export function isDisposable(value) {
34
+ return value instanceof Object
35
+ && Symbol.dispose in value
36
+ && typeof value[Symbol.dispose] === "function";
37
+ }
38
+ /**
39
+ * Checks if a value supports asynchronous disposal.
40
+ *
41
+ * Recognises the protocol by shape rather than by declaration, so that any value carrying a callable
42
+ * `Symbol.asyncDispose` member, own or inherited, is accepted, whether or not it was typed as `AsyncDisposable`.
43
+ *
44
+ * The two disposal protocols are independent: a value implementing both is accepted here and by {@link isDisposable}
45
+ * alike, leaving the caller to decide which one takes precedence.
46
+ *
47
+ * @param value The value to be checked
48
+ *
49
+ * @returns true if `value` is an object or a function exposing a callable `Symbol.asyncDispose` method; false otherwise
50
+ *
51
+ * @see {@link https://tc39.es/proposal-explicit-resource-management/ ECMAScript Explicit Resource Management}
52
+ */
53
+ export function isAsyncDisposable(value) {
54
+ return value instanceof Object
55
+ && Symbol.asyncDispose in value
56
+ && typeof value[Symbol.asyncDispose] === "function";
57
+ }
58
+ /**
59
+ * Terminates the process on an uncaught exception.
60
+ *
61
+ * Prints the exception and its stack trace to the standard error stream, then exits with the status Node assigns to
62
+ * uncaught exceptions. The source excerpt Node prints by default is left out, as it points at the helper that threw
63
+ * rather than at the actual failure. The output is written synchronously, so the exit never truncates it.
64
+ *
65
+ * @param error The uncaught exception
66
+ */
67
+ export function terminate(error) {
68
+ writeSync(process.stderr.fd, `${inspect(error)}\n`);
69
+ return process.exit(1);
70
+ }
71
+ //# sourceMappingURL=index.core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.core.js","sourceRoot":"","sources":["../src/index.core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IAE1C,OAAO,KAAK,YAAY,MAAM;WAC1B,MAAM,CAAC,OAAO,IAAI,KAAK;WACvB,OAAO,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,CAAC;AAEjD,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAE/C,OAAO,KAAK,YAAY,MAAM;WAC1B,MAAM,CAAC,YAAY,IAAI,KAAK;WAC5B,OAAO,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,KAAK,UAAU,CAAC;AAEtD,CAAC;AAGD;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,KAAc;IAEvC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAEpD,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAExB,CAAC"}
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Job executor and service locator.
3
+ *
4
+ * Provides the executor that runs jobs, together with the shared services they rely on.
5
+ *
6
+ * Service location keeps a job independent of the facilities it uses: a job names a facility by its default
7
+ * {@link Service service} rather than importing a concrete implementation, and a binding substitutes another one for
8
+ * the duration of an execution, leaving unbound facilities to fall back on their own default; custom facilities
9
+ * honouring the same contracts plug in interchangeably.
10
+ *
11
+ * > [!IMPORTANT]
12
+ * >
13
+ * > Bound implementations are constructed as the execution opens, unbound defaults on first use; either way the
14
+ * > instance is shared across the job and, where it implements a disposal protocol, disposed as the job ends.
15
+ * > Concurrent or repeated runs share nothing.
16
+ *
17
+ * @module index
18
+ *
19
+ * @example
20
+ *
21
+ * ```ts
22
+ * await executor(
23
+ *
24
+ * bind(createVault, createEnvVault)
25
+ *
26
+ * )(async () => {
27
+ *
28
+ * console.log(await service(createVault)("key"));
29
+ *
30
+ * });
31
+ * ```
32
+ */
33
+ import type { Defined } from "@grafctory/core";
34
+ import type { Awaitable } from "@grafctory/core/async";
35
+ /**
36
+ * Job executor.
37
+ *
38
+ * Opens an execution for a job, resolves the service lookups the job makes against the bindings it was created with,
39
+ * and disposes the instances constructed along the way once the job settles.
40
+ *
41
+ * Every invocation stands on its own, sharing no service instance with another. The promise handed back resolves to
42
+ * the value the job produces, settling only after disposal has completed, and rejects if the executor is invoked from
43
+ * within a running execution.
44
+ *
45
+ * Bound implementations are constructed as the execution opens, in binding order, before the job is handed control:
46
+ * an implementation may therefore await whatever it needs and still leave the job a ready instance on a synchronous
47
+ * lookup, at the cost of being constructed even where the job never resolves it. An execution failing to prepare its
48
+ * bindings rejects without running the job, disposing whatever it had already constructed.
49
+ *
50
+ * > [!IMPORTANT]
51
+ * >
52
+ * > A construction reaching a bound service the pass has yet to prepare is abandoned there and run again from the
53
+ * > start once that one is ready, as a synchronous lookup is unable to wait. Unwinding takes every factory still
54
+ * > under construction, the bound implementation and any unbound default whose own body reached the pending binding,
55
+ * > so all of them must meet the all-or-nothing requirement stated at {@link Service}: an implementation acquiring a
56
+ * > resource or recording state as it awaits is the one this catches out. An unbound default that had already
57
+ * > completed is kept, and the repeat is handed the same instance. Ordering a binding after the ones it depends on
58
+ * > spares it the repeat; implementations requiring each other are rejected as circular.
59
+ *
60
+ * > [!IMPORTANT]
61
+ * >
62
+ * > Services implementing {@link https://tc39.es/proposal-explicit-resource-management/ AsyncDisposable} or
63
+ * > {@link https://tc39.es/proposal-explicit-resource-management/ Disposable} are disposed in reverse construction
64
+ * > order, whether the job succeeded or failed, the asynchronous protocol taking precedence where both are implemented;
65
+ * > instances implementing neither are left as they are, which is not an error. Disposal runs outside the execution,
66
+ * > so a disposer resolving a service is rejected rather than constructing an instance nothing would dispose. Every
67
+ * > disposer is run even if an earlier one failed: if the job and a disposal both fail, or several disposals fail, the
68
+ * > errors are collected into an
69
+ * > {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AggregateError AggregateError},
70
+ * > in the order they were raised.
71
+ *
72
+ * > [!NOTE]
73
+ * >
74
+ * > A failure left uncaught, for instance by an entry point awaiting an execution at the top level, terminates the
75
+ * > process with its message and stack trace only, without the source excerpt Node prints by default. The first
76
+ * > execution enables this behaviour for the whole process. A handler for uncaught exceptions installed before then
77
+ * > stays in charge instead, so an application keeps full control over how its own uncaught failures are handled.
78
+ *
79
+ * @see {@link https://tc39.es/proposal-explicit-resource-management/ ECMAScript Explicit Resource Management}
80
+ */
81
+ export type Executor = <T>(job: Executable<T>) => Promise<T>;
82
+ /**
83
+ * Executable job.
84
+ *
85
+ * Carries out the work of a run and resolves to the value it produces, drawing whatever it needs from the services of
86
+ * the execution it runs in rather than from arguments, so that the same job runs under any set of bindings.
87
+ *
88
+ * Work started but left unawaited escapes the execution, as the value the job resolves to marks it as complete.
89
+ *
90
+ * @typeParam T The type of the value produced by the job
91
+ */
92
+ export type Executable<T> = () => Awaitable<T>;
93
+ /**
94
+ * Service binding.
95
+ *
96
+ * Pairs a service with the factory standing in for it, so that every lookup of the service within an execution created
97
+ * with the pair yields the substitute's instance.
98
+ *
99
+ * The substitute may await whatever it needs to construct that instance, as it is constructed when the execution opens
100
+ * rather than on first lookup, under the terms detailed at {@link Executor}.
101
+ *
102
+ * @typeParam T The type of the bound service
103
+ */
104
+ export type Binding<T extends Defined> = readonly [service: Service<T>, factory: () => Awaitable<T>];
105
+ /**
106
+ * Service factory.
107
+ *
108
+ * Constructs the instance backing a facility and identifies that facility across lookups and bindings.
109
+ *
110
+ * Doubling as the identity means services are looked up and bound by reference, so a service must be declared in a
111
+ * single module and re-exported by reference only, as wrapping it in a new function forks the identity and silently
112
+ * declares a second service.
113
+ *
114
+ * Construction must be synchronous and free of I/O, deferring such work to the instance's own methods; an
115
+ * implementation {@link bind bound} to a service is exempt, as it is constructed ahead of the job.
116
+ *
117
+ * > [!IMPORTANT]
118
+ * >
119
+ * > Construction is all or nothing, as a transaction is: a run either records an instance or rolls back, leaving
120
+ * > nothing of what it had already done. A factory letting an error through must first release whatever it holds and
121
+ * > undo whatever it has changed, then rethrow that same error: an error raised by a lookup of its own reaches the
122
+ * > caller unchanged, never replaced by another or swallowed in favour of an alternative, as it may be the signal
123
+ * > unwinding the construction: one reaching a service the execution is not yet ready to hand over is abandoned where
124
+ * > it stands and run again from the start. Nothing tells such a run from a first one, so a second must be
125
+ * > indistinguishable from a first.
126
+ *
127
+ * > [!TIP]
128
+ * >
129
+ * > Performing every lookup before constructing anything discharges the requirement outright: a factory holding
130
+ * > nothing at the point an unwinding error can reach it has nothing to release and nothing to undo.
131
+ *
132
+ * Releasing whatever the instance holds is opt-in: an instance exposing a callable `Symbol.asyncDispose` or
133
+ * `Symbol.dispose` member, either its own or inherited, is disposed as the execution ends, as detailed under
134
+ * {@link Executor}; any other instance is left as it is.
135
+ *
136
+ * > [!IMPORTANT]
137
+ * >
138
+ * > Because the constructing function carries the identity, naming a service links its default implementation: the
139
+ * > module declaring a service must stay import-light, requiring heavy clients lazily inside the default
140
+ * > implementation rather than at module level.
141
+ *
142
+ * @typeParam T The type of the constructed instance, `undefined` excepted, as it marks a service under construction
143
+ */
144
+ export type Service<T extends Defined> = () => T;
145
+ /**
146
+ * Creates a job executor.
147
+ *
148
+ * @param bindings The implementations to be substituted for the duration of each execution
149
+ *
150
+ * @returns An {@link Executor} running a job under `bindings`, rejecting as described there if a bound implementation
151
+ * fails to construct, if the job fails, if the disposal of a service fails, or if it is invoked from within a
152
+ * running execution; the returned value holds no service instances of its own and may be reused for
153
+ * independent executions
154
+ *
155
+ * @throws {@link !Error Error} If `bindings` includes more than one binding for the same service, reporting the
156
+ * services bound more than once
157
+ */
158
+ export declare function executor(...bindings: readonly Binding<Defined>[]): Executor;
159
+ /**
160
+ * Binds an implementation to a service.
161
+ *
162
+ * The implementation may be asynchronous, so that a facility whose construction depends on a value only another
163
+ * service can supply, such as a client keyed from a secret vault, is still resolved by a synchronous lookup: bound
164
+ * implementations are constructed and awaited as the execution opens, under the terms detailed at {@link Executor}.
165
+ *
166
+ * > [!IMPORTANT]
167
+ * >
168
+ * > An implementation is held to the same all-or-nothing requirement as any other {@link Service factory}, and an
169
+ * > asynchronous one is the most exposed to it: whatever it awaits may be awaited again from scratch, as the run that
170
+ * > started it may be abandoned before it records an instance.
171
+ *
172
+ * @typeParam T The type of the bound service
173
+ *
174
+ * @param service The service to be bound
175
+ * @param factory The implementation to be used in its place, awaited before the job runs where it is asynchronous
176
+ *
177
+ * @returns An immutable binding pairing `service` with `factory`
178
+ *
179
+ * @example
180
+ *
181
+ * ```ts
182
+ * bind(createClient, async () => new Client(await service(createVault)("api.key")));
183
+ * ```
184
+ */
185
+ export declare function bind<T extends Defined>(service: Service<T>, factory: NoInfer<() => Awaitable<T>>): Binding<T>;
186
+ /**
187
+ * Resolves a service.
188
+ *
189
+ * Returns the instance produced by the implementation bound to `service` in the enclosing execution, or by `service`
190
+ * itself if unbound: a bound implementation is ready before the job is handed control, an unbound default is
191
+ * constructed on first lookup, and either way every later lookup in the same execution is handed the same instance.
192
+ *
193
+ * > [!WARNING]
194
+ * >
195
+ * > A job must await the work it starts. A promise chain left unawaited keeps the execution around it, so a lookup in
196
+ * > one of its continuations resolves after disposal has run, into an instance nothing will dispose.
197
+ *
198
+ * @typeParam T The type of the resolved service
199
+ *
200
+ * @param service The service to be resolved
201
+ *
202
+ * @returns The service instance for the enclosing execution
203
+ *
204
+ * @throws {@link !Error Error} If called outside an execution, reporting `service`; disposal of the execution's own
205
+ * services counts as outside, as does a callback invoked from work that escaped the
206
+ * execution, such as a timer
207
+ *
208
+ * @throws {@link !Error Error} If the service depends on itself, either directly or through other services, reporting
209
+ * the dependency chain
210
+ *
211
+ * @throws {@link !Error Error} If `service` is bound and looked up from a factory the execution is constructing before
212
+ * that binding is ready, unwinding the construction to be run again as detailed at
213
+ * {@link Executor}; a factory must let this error through unchanged rather than replacing
214
+ * or swallowing it
215
+ */
216
+ export declare function service<T extends Defined>(service: Service<T>): T;
217
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+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
package/dist/index.js ADDED
@@ -0,0 +1,241 @@
1
+ /*
2
+ * Copyright © 2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { unique } from "@grafctory/core/arrays";
17
+ import { report } from "@grafctory/tape";
18
+ import { AsyncLocalStorage } from "node:async_hooks";
19
+ import { isAsyncDisposable, isDisposable, terminate } from "./index.core.js";
20
+ /**
21
+ * Enclosing service locator.
22
+ *
23
+ * Follows a job across the asynchronous continuations it spawns, so that a lookup made anywhere within it is resolved
24
+ * against the execution it runs in without the job carrying the locator along. An empty store marks code running
25
+ * outside any execution, disposal and work that escaped a settled job included.
26
+ */
27
+ const locators = new AsyncLocalStorage();
28
+ /**
29
+ * Unprepared binding.
30
+ *
31
+ * Unwinds a synchronous lookup reaching a bound service before the preparation pass has constructed it, naming the
32
+ * binding the pass is to prepare before running the abandoned construction again.
33
+ */
34
+ class Pending extends Error {
35
+ service;
36
+ factory;
37
+ constructor(service, factory) {
38
+ super(`pending service <${report(service)}>`);
39
+ this.service = service;
40
+ this.factory = factory;
41
+ }
42
+ }
43
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
44
+ /**
45
+ * Creates a job executor.
46
+ *
47
+ * @param bindings The implementations to be substituted for the duration of each execution
48
+ *
49
+ * @returns An {@link Executor} running a job under `bindings`, rejecting as described there if a bound implementation
50
+ * fails to construct, if the job fails, if the disposal of a service fails, or if it is invoked from within a
51
+ * running execution; the returned value holds no service instances of its own and may be reused for
52
+ * independent executions
53
+ *
54
+ * @throws {@link !Error Error} If `bindings` includes more than one binding for the same service, reporting the
55
+ * services bound more than once
56
+ */
57
+ export function executor(...bindings) {
58
+ const duplicates = unique(bindings
59
+ .map(([service]) => service)
60
+ .filter((service, index, services) => services.indexOf(service) !== index));
61
+ if (duplicates.length > 0) {
62
+ throw new Error(`duplicate service bindings ${duplicates
63
+ .map(v => report(v))
64
+ .map(v => `<${v}>`)
65
+ .join(", ")}`);
66
+ }
67
+ const aliases = new Map(bindings);
68
+ return async (job) => {
69
+ if (locators.getStore() !== undefined) {
70
+ throw new Error("nested job executions");
71
+ }
72
+ // installed once, as later executions find this handler in place; handlers installed elsewhere are left alone
73
+ if (process.listenerCount("uncaughtException") === 0) {
74
+ process.on("uncaughtException", terminate);
75
+ }
76
+ const instances = new Map();
77
+ // the job is wrapped, so that a synchronous throw is reported as a rejection; disposal is handled outside the
78
+ // execution, so that a disposer resolving a service is rejected
79
+ return locators.run(locate, async () => {
80
+ await prepareBindings();
81
+ return job();
82
+ }).then(fulfilled, rejected);
83
+ function locate(service) {
84
+ const instance = instances.get(service); // ;(cast) instances erase the service type
85
+ return instance === undefined ? construct(service) : instance; // ;(??) `null` is a legal instance
86
+ }
87
+ function construct(service) {
88
+ // a placeholder recorded by an outer construction marks a service depending on itself
89
+ if (instances.has(service)) {
90
+ const chain = [...instances]
91
+ .filter(([, pending]) => pending === undefined)
92
+ .map(([pending]) => pending)
93
+ .concat(service);
94
+ throw new Error(`circular dependency across services ${chain
95
+ .map(v => report(v))
96
+ .map(v => `<${v}>`)
97
+ .join(" => ")}`);
98
+ }
99
+ // a bound implementation is constructed by the preparation pass, which alone is able to await it
100
+ const alias = aliases.get(service);
101
+ if (alias !== undefined) {
102
+ throw new Pending(service, alias);
103
+ }
104
+ instances.set(service, undefined);
105
+ try {
106
+ const instance = service();
107
+ instances.set(service, instance);
108
+ return instance;
109
+ }
110
+ catch (error) {
111
+ instances.delete(service);
112
+ throw error;
113
+ }
114
+ }
115
+ async function prepareBindings() {
116
+ return [...aliases].reduce(async (previous, [service, factory]) => {
117
+ await previous;
118
+ // a binding reached out of turn is prepared by the construction reaching it, and skipped here
119
+ return instances.has(service) ? undefined : prepare(service, factory);
120
+ }, Promise.resolve());
121
+ async function prepare(service, factory) {
122
+ // the placeholder is retained across the whole preparation, so that a construction reaching back here
123
+ // while it is under way is reported as circular
124
+ instances.set(service, undefined);
125
+ try {
126
+ instances.set(service, await factory());
127
+ }
128
+ catch (error) {
129
+ if (error instanceof Pending) {
130
+ // the abandoned construction is run again from the start once the binding it reached is
131
+ // ready, so the runs are as many as the bindings it requires ahead of their own preparation,
132
+ // plus one
133
+ await prepare(error.service, error.factory);
134
+ await prepare(service, factory);
135
+ }
136
+ else {
137
+ instances.delete(service);
138
+ throw error;
139
+ }
140
+ }
141
+ }
142
+ }
143
+ async function fulfilled(value) {
144
+ const failure = await release();
145
+ if (failure === undefined) {
146
+ return value;
147
+ }
148
+ else {
149
+ throw failure;
150
+ }
151
+ }
152
+ async function rejected(error) {
153
+ const failure = await release();
154
+ throw failure === undefined ? error : new AggregateError([error, failure], "execution failed");
155
+ }
156
+ async function release() {
157
+ return [...instances.values()].reduceRight(async (previous, value) => {
158
+ const suppressed = await previous;
159
+ try {
160
+ // as `await using` does, preferring `@@asyncDispose` and falling back to `@@dispose`
161
+ // https://tc39.es/proposal-explicit-resource-management/#sec-getdisposemethod
162
+ await (isAsyncDisposable(value) ? value[Symbol.asyncDispose]()
163
+ : isDisposable(value) ? value[Symbol.dispose]()
164
+ : undefined);
165
+ return suppressed;
166
+ }
167
+ catch (error) {
168
+ return suppressed === undefined ? error
169
+ : new AggregateError([suppressed, error], "disposal failed");
170
+ }
171
+ }, Promise.resolve(undefined));
172
+ }
173
+ };
174
+ }
175
+ /**
176
+ * Binds an implementation to a service.
177
+ *
178
+ * The implementation may be asynchronous, so that a facility whose construction depends on a value only another
179
+ * service can supply, such as a client keyed from a secret vault, is still resolved by a synchronous lookup: bound
180
+ * implementations are constructed and awaited as the execution opens, under the terms detailed at {@link Executor}.
181
+ *
182
+ * > [!IMPORTANT]
183
+ * >
184
+ * > An implementation is held to the same all-or-nothing requirement as any other {@link Service factory}, and an
185
+ * > asynchronous one is the most exposed to it: whatever it awaits may be awaited again from scratch, as the run that
186
+ * > started it may be abandoned before it records an instance.
187
+ *
188
+ * @typeParam T The type of the bound service
189
+ *
190
+ * @param service The service to be bound
191
+ * @param factory The implementation to be used in its place, awaited before the job runs where it is asynchronous
192
+ *
193
+ * @returns An immutable binding pairing `service` with `factory`
194
+ *
195
+ * @example
196
+ *
197
+ * ```ts
198
+ * bind(createClient, async () => new Client(await service(createVault)("api.key")));
199
+ * ```
200
+ */
201
+ export function bind(service, factory) {
202
+ return Object.freeze([service, factory]);
203
+ }
204
+ /**
205
+ * Resolves a service.
206
+ *
207
+ * Returns the instance produced by the implementation bound to `service` in the enclosing execution, or by `service`
208
+ * itself if unbound: a bound implementation is ready before the job is handed control, an unbound default is
209
+ * constructed on first lookup, and either way every later lookup in the same execution is handed the same instance.
210
+ *
211
+ * > [!WARNING]
212
+ * >
213
+ * > A job must await the work it starts. A promise chain left unawaited keeps the execution around it, so a lookup in
214
+ * > one of its continuations resolves after disposal has run, into an instance nothing will dispose.
215
+ *
216
+ * @typeParam T The type of the resolved service
217
+ *
218
+ * @param service The service to be resolved
219
+ *
220
+ * @returns The service instance for the enclosing execution
221
+ *
222
+ * @throws {@link !Error Error} If called outside an execution, reporting `service`; disposal of the execution's own
223
+ * services counts as outside, as does a callback invoked from work that escaped the
224
+ * execution, such as a timer
225
+ *
226
+ * @throws {@link !Error Error} If the service depends on itself, either directly or through other services, reporting
227
+ * the dependency chain
228
+ *
229
+ * @throws {@link !Error Error} If `service` is bound and looked up from a factory the execution is constructing before
230
+ * that binding is ready, unwinding the construction to be run again as detailed at
231
+ * {@link Executor}; a factory must let this error through unchanged rather than replacing
232
+ * or swallowing it
233
+ */
234
+ export function service(service) {
235
+ const locator = locators.getStore();
236
+ if (locator === undefined) {
237
+ throw new Error(`missing executor for service <${report(service)}>`);
238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B,MAAM,IAAI,KAAK,CAAC,iCAAiC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;AAEzB,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Working space access.
3
+ *
4
+ * Gives a job the surroundings it works within, without reading them directly from the process: the base paths its
5
+ * file access is anchored to, and the prompts, templates and other resource files shipped beside its modules.
6
+ *
7
+ * @module
8
+ */
9
+ import type { URLLike } from "@grafctory/core";
10
+ /**
11
+ * Retrieves the default base path.
12
+ *
13
+ * @returns The absolute path of the working directory of the process
14
+ */
15
+ export declare function getPath(): string;
16
+ /**
17
+ * Retrieves the base path of an enclosing package.
18
+ *
19
+ * Locates the package a path belongs to by its manifest, rather than by the folder the process happens to be started
20
+ * from, so that a path anchored to it is the same however the code is launched, whether from a shell, an IDE run
21
+ * configuration or a deployed workload.
22
+ *
23
+ * @param path The absolute path the package is looked up from, typically the folder of the calling module, as given
24
+ * by `import.meta.dirname`
25
+ *
26
+ * @returns The absolute path of the closest folder holding a `package.json` file, at or above `path`
27
+ *
28
+ * @throws {@link !Error Error} If neither `path` nor any folder above it holds a `package.json` file
29
+ */
30
+ export declare function getPackage(path: string): string;
31
+ /**
32
+ * Retrieves the text of a resource file.
33
+ *
34
+ * Reads a file shipped beside the calling module, such as a prompt or template, wherever the code is launched from.
35
+ *
36
+ * @param url The URL of the file, or a path resolved against `base`; a path made only of extensions, such as `.sys.md`,
37
+ * replaces the trailing extensions of `base`, so that `module.js` can name its companion `module.sys.md`
38
+ * @param base The URL `url` is resolved against, typically the URL of the calling module, as given by `import.meta.url`
39
+ *
40
+ * @returns A promise resolving to the UTF-8 text of the file, rejected if the file can't be read
41
+ *
42
+ * @throws {@link !TypeError TypeError} If `url` is a path and `base` is missing or isn't a valid URL
43
+ */
44
+ export declare function getResource(url: URLLike, base?: URLLike): Promise<string>;
45
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/space/index.ts"],"names":[],"mappings":"AAgBA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAuB/C;;;;GAIG;AACH,wBAAgB,OAAO,IAAI,MAAM,CAIhC;AAGD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAgB/C;AAGD;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAQzE"}