@sincpro/client-framework 0.2.0 → 0.3.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.
@@ -0,0 +1,45 @@
1
+ import type { ContextStore, ContextValues } from "./store.js";
2
+ /**
3
+ * One level of the context: the process's (`processContext`) or a bounded context's
4
+ * (`project.context`), read and written the same way on every platform.
5
+ *
6
+ * processContext.set({ tenant_id: "acme" }); the company changed — every screen hears it
7
+ * processContext.get("tenant_id") → "acme"
8
+ * project.context.set({ warehouse_id: 4 }); only what `project` runs
9
+ * const stop = processContext.watch(() => redraw());
10
+ *
11
+ * Context: sincpro_framework reads its context from a tree — the process, the bounded context,
12
+ * the scope, the execution — and the nearest wins. A client has the same levels: a use case runs
13
+ * with the process's values, under them its bounded context's, under them a scope's
14
+ * (`project.scoped({...})`), read once where the gesture starts and inherited by every Feature
15
+ * it runs. That snapshot is `this.context` and what travels to the server in `sincpro-context`.
16
+ *
17
+ * Where the values live is the platform's (`ContextStore`): this is only the door. `values` is
18
+ * the same object until something changes it, so a screen can hand it straight to React's
19
+ * `useSyncExternalStore`, and `watch` is bound — pass it as it is.
20
+ */
21
+ export type Context<C extends object = ContextValues> = {
22
+ /** Its values now: the same object until they change. Never change it — `set` does. */
23
+ readonly values: Readonly<Partial<C>>;
24
+ get<K extends keyof C & string>(name: K): C[K] | undefined;
25
+ /** Adds or replaces these names; the others stay. */
26
+ set(values: Partial<C>): void;
27
+ /** Removes these names — every name when none is given. */
28
+ clear(...names: (keyof C & string)[]): void;
29
+ /** Calls `listener` whenever its values change; answers the way to stop. */
30
+ watch(listener: () => void): () => void;
31
+ };
32
+ /**
33
+ * Where a level finds its store: the one in use now, and word when another replaces it — the
34
+ * process's, which `configureProcess` may change after a screen started listening.
35
+ */
36
+ export type StoreSource = {
37
+ current(): ContextStore;
38
+ replaced(listener: () => void): () => void;
39
+ };
40
+ /**
41
+ * The level saved under `key` in whatever store `source` holds now — asked again on every call,
42
+ * so a store the process configures after this level was made is the one used, and whoever
43
+ * listens moves to it and hears the change.
44
+ */
45
+ export declare function contextAt<C extends object = ContextValues>(key: string, source: StoreSource): Context<C>;
@@ -0,0 +1,70 @@
1
+ const NOTHING = {};
2
+ /**
3
+ * The level saved under `key` in whatever store `source` holds now — asked again on every call,
4
+ * so a store the process configures after this level was made is the one used, and whoever
5
+ * listens moves to it and hears the change.
6
+ */
7
+ export function contextAt(key, source) {
8
+ const storeOf = () => source.current();
9
+ // The values last read, by store and version: a store that answers a new object on every
10
+ // `load` still gives one object per change.
11
+ let seen;
12
+ // Who listens when the store cannot say it changed (`watch` is optional).
13
+ const listeners = new Set();
14
+ const read = () => {
15
+ const store = storeOf();
16
+ const version = store.version(key);
17
+ if (seen?.store !== store || seen.version !== version)
18
+ seen = { store, version, values: store.load(key) ?? NOTHING };
19
+ return seen.values;
20
+ };
21
+ const write = (values) => {
22
+ const store = storeOf();
23
+ if (values === undefined)
24
+ store.delete(key);
25
+ else
26
+ store.save(key, values);
27
+ if (store.watch === undefined)
28
+ for (const listener of [...listeners])
29
+ listener();
30
+ };
31
+ return {
32
+ get values() {
33
+ return read();
34
+ },
35
+ get: (name) => read()[name],
36
+ set: (values) => write({ ...read(), ...values }),
37
+ clear(...names) {
38
+ if (names.length === 0)
39
+ return write(undefined);
40
+ const kept = { ...read() };
41
+ for (const name of names)
42
+ delete kept[name];
43
+ write(kept);
44
+ },
45
+ watch(listener) {
46
+ let watching;
47
+ let unwatch;
48
+ const follow = () => {
49
+ const store = storeOf();
50
+ if (store === watching)
51
+ return;
52
+ unwatch?.();
53
+ watching = store;
54
+ unwatch = store.watch?.(key, listener);
55
+ };
56
+ follow();
57
+ listeners.add(listener);
58
+ // Another store is other values: listen to it, and say so.
59
+ const unreplaced = source.replaced(() => {
60
+ follow();
61
+ listener();
62
+ });
63
+ return () => {
64
+ unwatch?.();
65
+ unreplaced();
66
+ listeners.delete(listener);
67
+ };
68
+ },
69
+ };
70
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `ContextStore`: where the context lives — the port each platform implements with its own
3
+ * technology, so every use case reads the same context the same way.
4
+ *
5
+ * store.save("process", { tenant_id: "acme", lang: "es" });
6
+ * store.load("process") → { tenant_id: "acme", lang: "es" } undefined when never saved
7
+ * store.version("process") → 1 0 when never saved
8
+ * store.watch?.("process", () => …) a change anywhere
9
+ *
10
+ * Context: sincpro_framework's `ContextStore` with the same four methods — the process's memory by
11
+ * default, a Redis when a project says so — and one more, optional, a client needs: `watch`, so
12
+ * a screen redraws when the tenant changes. The store never decides what the context is: it keeps
13
+ * values under a key (`process`, `bounded_context:<name>`), and `Context` reads and writes them.
14
+ *
15
+ * One per platform, chosen by the application (`configureProcess({ context })`):
16
+ *
17
+ * - `memoryContexts()` — this package's default, everywhere.
18
+ * - a browser: the same, or one over `sessionStorage` to survive a reload, or over the screens'
19
+ * own store (Zustand, Redux) so they share one source.
20
+ * - a phone: MMKV (synchronous), or memory hydrated from AsyncStorage at start and written through.
21
+ * - a server that renders: one over `AsyncLocalStorage`, so two requests never see each other's.
22
+ *
23
+ * Reads are synchronous on purpose: a use case reads its context where a gesture starts, and an
24
+ * asynchronous store would make every use case wait for it.
25
+ */
26
+ /** What a context holds: plain values, the way JSON carries them to the server. */
27
+ export type ContextValues = Readonly<Record<string, unknown>>;
28
+ export interface ContextStore {
29
+ /** What `key` holds, or `undefined` when nothing was saved there. */
30
+ load(key: string): ContextValues | undefined;
31
+ /** `values` under `key`, replacing what was there. Each save moves the key's version. */
32
+ save(key: string, values: ContextValues): void;
33
+ /** `key` is gone. Its version moves too. */
34
+ delete(key: string): void;
35
+ /**
36
+ * How many times `key` changed — what a reader compares to know it changed. `load` may answer
37
+ * a new object each time (a store that parses JSON does); the version is what says it is new.
38
+ */
39
+ version(key: string): number;
40
+ /**
41
+ * Calls `listener` whenever `key` changes, from here or from elsewhere (another tab, a native
42
+ * module); answers the way to stop. Optional: without it, only the changes made through this
43
+ * package's `Context` are heard.
44
+ */
45
+ watch?(key: string, listener: () => void): () => void;
46
+ }
47
+ /**
48
+ * The context in this process's memory: the default, on every platform. A test gets a fresh one
49
+ * from `configureProcess()`.
50
+ */
51
+ export declare function memoryContexts(): ContextStore;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `ContextStore`: where the context lives — the port each platform implements with its own
3
+ * technology, so every use case reads the same context the same way.
4
+ *
5
+ * store.save("process", { tenant_id: "acme", lang: "es" });
6
+ * store.load("process") → { tenant_id: "acme", lang: "es" } undefined when never saved
7
+ * store.version("process") → 1 0 when never saved
8
+ * store.watch?.("process", () => …) a change anywhere
9
+ *
10
+ * Context: sincpro_framework's `ContextStore` with the same four methods — the process's memory by
11
+ * default, a Redis when a project says so — and one more, optional, a client needs: `watch`, so
12
+ * a screen redraws when the tenant changes. The store never decides what the context is: it keeps
13
+ * values under a key (`process`, `bounded_context:<name>`), and `Context` reads and writes them.
14
+ *
15
+ * One per platform, chosen by the application (`configureProcess({ context })`):
16
+ *
17
+ * - `memoryContexts()` — this package's default, everywhere.
18
+ * - a browser: the same, or one over `sessionStorage` to survive a reload, or over the screens'
19
+ * own store (Zustand, Redux) so they share one source.
20
+ * - a phone: MMKV (synchronous), or memory hydrated from AsyncStorage at start and written through.
21
+ * - a server that renders: one over `AsyncLocalStorage`, so two requests never see each other's.
22
+ *
23
+ * Reads are synchronous on purpose: a use case reads its context where a gesture starts, and an
24
+ * asynchronous store would make every use case wait for it.
25
+ */
26
+ /**
27
+ * The context in this process's memory: the default, on every platform. A test gets a fresh one
28
+ * from `configureProcess()`.
29
+ */
30
+ export function memoryContexts() {
31
+ const held = new Map();
32
+ const versions = new Map();
33
+ const listeners = new Map();
34
+ const changed = (key) => {
35
+ versions.set(key, (versions.get(key) ?? 0) + 1);
36
+ for (const listener of [...(listeners.get(key) ?? [])])
37
+ listener();
38
+ };
39
+ return {
40
+ load: (key) => held.get(key),
41
+ save(key, values) {
42
+ // A copy: whoever handed the values may keep changing their object.
43
+ held.set(key, { ...values });
44
+ changed(key);
45
+ },
46
+ delete(key) {
47
+ if (!held.delete(key))
48
+ return;
49
+ changed(key);
50
+ },
51
+ version: (key) => versions.get(key) ?? 0,
52
+ watch(key, listener) {
53
+ const own = listeners.get(key) ?? new Set();
54
+ listeners.set(key, own);
55
+ own.add(listener);
56
+ return () => void own.delete(listener);
57
+ },
58
+ };
59
+ }
package/dist/index.d.ts CHANGED
@@ -9,7 +9,9 @@
9
9
  * client/ the seam with a server: the transport and its REST and in-memory implementations,
10
10
  * entities with typed commands, the service's client contract, client-side ids
11
11
  * model/ model definitions: written by hand, read from a JSON Schema, kept once known
12
- * services/ Feature and ApplicationService, the runtime they run in, what each run carries
12
+ * services/ the bounded context (`UseBoundedContext`), its `Feature` and `ApplicationService`,
13
+ * the process they run in (`configureProcess`), what each run carries
14
+ * context/ the context: one door (`Context`) over the store each platform plugs
13
15
  * observability/ the ports a platform plugs: a tracer and an error reporter
14
16
  *
15
17
  * The generator is `@sincpro/client-framework/codegen`, and the in-memory tracer and reporter
@@ -22,10 +24,13 @@ export { type MemoryOptions, type MemoryTable, memoryTransport, } from "./client
22
24
  export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./client/rest.js";
23
25
  export { type RetryKeys, retryKeys, unanswered, } from "./client/retry.js";
24
26
  export { type CallOptions, type Draft, type Method, type One, readRoute, type SendOptions, type Transport, TransportError, } from "./client/transport.js";
27
+ export { type Context } from "./context/context.js";
28
+ export { type ContextStore, type ContextValues, memoryContexts, } from "./context/store.js";
25
29
  export { defineMeta, field, type FieldOptions, type MetaSpec, type Words, } from "./model/meta.js";
26
30
  export { type MetaStore, metaStore } from "./model/metas.js";
27
31
  export { completeMeta, type JsonSchema, metaFromSchema, type SchemaComponents, } from "./model/schema.js";
28
32
  export { type Attributes, type ErrorAbout, type ErrorReporter, NO_TRACER, type Outcome, type Span, type Tracer, } from "./observability/ports.js";
33
+ export { type BoundedContext, UseBoundedContext, } from "./services/bounded-context.js";
29
34
  export { BIND, type Bindable, bindable, bindDependency, bindTransport, type Execution, headersOf, } from "./services/execution.js";
30
- export { ApplicationService, bindServices, Feature, } from "./services/feature.js";
31
- export { createRuntime, DETACHED, outcomeOf, type Runtime, type RuntimeOptions, } from "./services/runtime.js";
35
+ export { ApplicationService, Feature, type ServiceClasses, type ServiceMethods, type Services, } from "./services/feature.js";
36
+ export { configureProcess, outcomeOf, processContext, type ProcessOptions, } from "./services/process.js";
package/dist/index.js CHANGED
@@ -9,7 +9,9 @@
9
9
  * client/ the seam with a server: the transport and its REST and in-memory implementations,
10
10
  * entities with typed commands, the service's client contract, client-side ids
11
11
  * model/ model definitions: written by hand, read from a JSON Schema, kept once known
12
- * services/ Feature and ApplicationService, the runtime they run in, what each run carries
12
+ * services/ the bounded context (`UseBoundedContext`), its `Feature` and `ApplicationService`,
13
+ * the process they run in (`configureProcess`), what each run carries
14
+ * context/ the context: one door (`Context`) over the store each platform plugs
13
15
  * observability/ the ports a platform plugs: a tracer and an error reporter
14
16
  *
15
17
  * The generator is `@sincpro/client-framework/codegen`, and the in-memory tracer and reporter
@@ -22,10 +24,13 @@ export { memoryTransport, } from "./client/memory.js";
22
24
  export { restTransport, urlOf, } from "./client/rest.js";
23
25
  export { retryKeys, unanswered, } from "./client/retry.js";
24
26
  export { readRoute, TransportError, } from "./client/transport.js";
27
+ export {} from "./context/context.js";
28
+ export { memoryContexts, } from "./context/store.js";
25
29
  export { defineMeta, field, } from "./model/meta.js";
26
30
  export { metaStore } from "./model/metas.js";
27
31
  export { completeMeta, metaFromSchema, } from "./model/schema.js";
28
32
  export { NO_TRACER, } from "./observability/ports.js";
33
+ export { UseBoundedContext, } from "./services/bounded-context.js";
29
34
  export { BIND, bindable, bindDependency, bindTransport, headersOf, } from "./services/execution.js";
30
- export { ApplicationService, bindServices, Feature, } from "./services/feature.js";
31
- export { createRuntime, DETACHED, outcomeOf, } from "./services/runtime.js";
35
+ export { ApplicationService, Feature, } from "./services/feature.js";
36
+ export { configureProcess, outcomeOf, processContext, } from "./services/process.js";
@@ -47,13 +47,13 @@ export interface Tracer {
47
47
  }
48
48
  /** What a report says about where the error happened. */
49
49
  export type ErrorAbout = {
50
- /** `<domain>/<Feature>`, the span's name. */
50
+ /** `<bounded context>.<Service>[.<method>]`: the use case's identity, as the backend's. */
51
51
  useCase: string;
52
52
  /** The trace the error belongs to — the same id the server logged, when it got that far. */
53
53
  traceId: string;
54
54
  /** The execution's own id. */
55
55
  executionId: string;
56
- /** What the use case ran with (`Runtime` `context`). */
56
+ /** What the use case ran with: the process's context, its bounded context's, its scope's. */
57
57
  context: Readonly<Record<string, unknown>>;
58
58
  };
59
59
  /** Reports what nobody expected. One per platform; none when nothing reports. */
@@ -0,0 +1,79 @@
1
+ import { type Context } from "../context/context.js";
2
+ import type { ContextValues } from "../context/store.js";
3
+ import { type ServiceClasses, type Services } from "./feature.js";
4
+ /**
5
+ * A bounded context: its dependencies, its services, and the one object everything else uses
6
+ * them through — set up the way sincpro_framework sets one up.
7
+ *
8
+ * // domains/project/infrastructure/dependencies.ts ← what the services can count on
9
+ * export interface ProjectDependencies {
10
+ * client: ProjectClient;
11
+ * session: Session;
12
+ * }
13
+ * export function registerDependencies(bc: UseBoundedContext<ProjectDependencies>) {
14
+ * bc.addDependency("client", clientOf(transport));
15
+ * bc.addDependency("session", session);
16
+ * return bc;
17
+ * }
18
+ *
19
+ * // domains/project/infrastructure/bounded_context.ts
20
+ * export class Feature extends BaseFeature<ProjectDependencies> {}
21
+ * export class ApplicationService extends BaseApplicationService<ProjectDependencies, ProjectFeatures> {}
22
+ * export function configProjectBoundedContext(name: string) {
23
+ * return registerDependencies(new UseBoundedContext<ProjectDependencies>(name));
24
+ * }
25
+ *
26
+ * // domains/project/index.ts
27
+ * export const project = configProjectBoundedContext("project").register({
28
+ * features, // { Issues, Notices }
29
+ * applicationServices, // { CloseAndNotify }
30
+ * });
31
+ *
32
+ * // anywhere — a screen, another bounded context's adapter, a test
33
+ * await project.Issues.close(input); // span "project/Issues.close"
34
+ * await project.CloseAndNotify.execute(input); // span "project/CloseAndNotify", its Features under it
35
+ *
36
+ * Context: sincpro_framework's `UseFramework` (being renamed to bounded context) with
37
+ * `add_dependency`, and `project(Command(...))` written as a property: a service is reached by
38
+ * the name it is registered under, so its span is named by that name — a production build renames
39
+ * classes, never the keys of an object — and the type of `project` is the services it holds.
40
+ *
41
+ * `project` is light and never frozen. It holds references: the classes, the dependencies, and
42
+ * one instance of each service, made the first time it is asked for and shared by everything
43
+ * derived from it. Each call makes a small view of that instance — a few pointers — that carries
44
+ * the call's trace. A screen or a test that needs its own variant derives one, with everything
45
+ * else shared:
46
+ *
47
+ * project.with({ client: fake }) other dependencies — a test, a demo
48
+ * project.scoped({ company_id: 2 }) more context for what runs through it — a window
49
+ *
50
+ * A service is a singleton of its bounded context: what a method writes on `this` stays for the
51
+ * next call and for the call running beside it, as in sincpro_framework. What belongs to one
52
+ * request goes in its arguments or its context, never on `this`.
53
+ */
54
+ export type BoundedContext<D extends object, C extends object, F extends ServiceClasses, A extends ServiceClasses> = Services<F, D> & Services<A, D> & {
55
+ readonly name: string;
56
+ /** This bounded context's level of the context: under the process's, over a scope's. */
57
+ readonly context: Context<C>;
58
+ /** The same bounded context with other dependencies — the rest, and the services, shared. */
59
+ with(dependencies: Partial<D>): BoundedContext<D, C, F, A>;
60
+ /** The same bounded context with more context for what runs through it. */
61
+ scoped(context: Partial<C>): BoundedContext<D, C, F, A>;
62
+ };
63
+ export declare class UseBoundedContext<D extends object, C extends object = ContextValues> {
64
+ #private;
65
+ readonly name: string;
66
+ /** This bounded context's level of the context, saved in the process's store. */
67
+ readonly context: Context<C>;
68
+ constructor(name: string);
69
+ /** `value` is what every service of this bounded context finds at `this.<name>`. */
70
+ addDependency<K extends keyof D & string>(name: K, value: D[K]): this;
71
+ /**
72
+ * The object the bounded context is used through: each service under its name. A dependency
73
+ * added after this is seen too — the services read them on every call.
74
+ */
75
+ register<F extends ServiceClasses, A extends ServiceClasses = Record<never, never>>(services: {
76
+ features: F;
77
+ applicationServices?: A;
78
+ }): BoundedContext<D, C, F, A>;
79
+ }
@@ -0,0 +1,272 @@
1
+ import { newEntityId } from "../client/ids.js";
2
+ import { contextAt } from "../context/context.js";
3
+ import { bindDependency } from "./execution.js";
4
+ import { composes, isApplicationServiceClass, isFeatureClass, methodsOf, } from "./feature.js";
5
+ import { processContext, processNow, processStore, } from "./process.js";
6
+ /** Names `project` answers itself: no service is registered under them. */
7
+ const RESERVED = new Set(["name", "context", "with", "scoped"]);
8
+ /** Names a run answers on `this` itself: no dependency is added under them. */
9
+ const ANSWERED = new Set(["context", "feature"]);
10
+ export class UseBoundedContext {
11
+ name;
12
+ /** This bounded context's level of the context, saved in the process's store. */
13
+ context;
14
+ #dependencies = {};
15
+ constructor(name) {
16
+ if (name === "" || name.includes("/"))
17
+ throw new Error(`"${name}" is not a bounded context's name — it names its spans: "${name}/Issues.close"`);
18
+ this.name = name;
19
+ this.context = contextAt(`bounded_context:${name}`, processStore);
20
+ }
21
+ /** `value` is what every service of this bounded context finds at `this.<name>`. */
22
+ addDependency(name, value) {
23
+ if (ANSWERED.has(name))
24
+ throw new Error(`${this.name}: a dependency cannot be called "${name}" — every service answers this.${name} itself`);
25
+ this.#dependencies[name] = value;
26
+ return this;
27
+ }
28
+ /**
29
+ * The object the bounded context is used through: each service under its name. A dependency
30
+ * added after this is seen too — the services read them on every call.
31
+ */
32
+ register(services) {
33
+ const classes = new Map();
34
+ const add = (key, service) => {
35
+ if (RESERVED.has(key))
36
+ throw new Error(`${this.name}: no service can be called "${key}" — it is the bounded context's own`);
37
+ if (classes.has(key))
38
+ throw new Error(`${this.name}: two services are called "${key}"`);
39
+ classes.set(key, service);
40
+ };
41
+ for (const [key, service] of Object.entries(services.features)) {
42
+ if (typeof service !== "function" || !isFeatureClass(service))
43
+ throw new Error(`${this.name}: "${key}" is not a Feature — an ApplicationService goes in applicationServices`);
44
+ add(key, service);
45
+ }
46
+ for (const [key, service] of Object.entries(services.applicationServices ?? {})) {
47
+ if (typeof service !== "function" || !isApplicationServiceClass(service))
48
+ throw new Error(`${this.name}: "${key}" is not an ApplicationService — a Feature goes in features`);
49
+ add(key, service);
50
+ }
51
+ const registry = {
52
+ name: this.name,
53
+ dependencies: this.#dependencies,
54
+ classes,
55
+ features: new Set(Object.keys(services.features)),
56
+ instances: new Map(),
57
+ context: this.context,
58
+ };
59
+ return assemble({ registry, overrides: {}, scope: {} });
60
+ }
61
+ }
62
+ function assemble(binding) {
63
+ const { registry } = binding;
64
+ const held = {};
65
+ Object.defineProperties(held, {
66
+ name: { value: registry.name, enumerable: true },
67
+ context: { value: registry.context, enumerable: true },
68
+ with: {
69
+ value: (dependencies) => assemble({ ...binding, overrides: { ...binding.overrides, ...dependencies } }),
70
+ },
71
+ scoped: {
72
+ value: (values) => assemble({ ...binding, scope: { ...binding.scope, ...values } }),
73
+ },
74
+ });
75
+ // Each service is made and wrapped the first time it is asked for, then kept on this object.
76
+ for (const key of registry.classes.keys())
77
+ Object.defineProperty(held, key, {
78
+ configurable: true,
79
+ enumerable: true,
80
+ get() {
81
+ const service = intercepted(key, binding, undefined);
82
+ Object.defineProperty(held, key, { value: service, enumerable: true });
83
+ return service;
84
+ },
85
+ });
86
+ return held;
87
+ }
88
+ function instanceOf(registry, key) {
89
+ const known = registry.instances.get(key);
90
+ if (known !== undefined)
91
+ return known;
92
+ const Service = registry.classes.get(key);
93
+ if (Service === undefined)
94
+ throw new Error(`${registry.name}: no service is called "${key}"`);
95
+ const made = new Service();
96
+ registry.instances.set(key, made);
97
+ return made;
98
+ }
99
+ /**
100
+ * A service as its holder sees it: each public method runs in an execution of its own — a child
101
+ * of `parent` when an ApplicationService runs it. A method is the same function every time it is
102
+ * read, so a screen can keep it (`useService(project.Issues.close)`).
103
+ */
104
+ function intercepted(key, binding, parent) {
105
+ const target = instanceOf(binding.registry, key);
106
+ const traced = methodsOf(target);
107
+ const methods = new Map();
108
+ return new Proxy(target, {
109
+ get(held, property) {
110
+ const value = Reflect.get(held, property, held);
111
+ if (typeof property !== "string" ||
112
+ typeof value !== "function" ||
113
+ !traced.has(property))
114
+ return value;
115
+ let method = methods.get(property);
116
+ if (method === undefined) {
117
+ const body = value;
118
+ method = (...args) => run(held, key, property, body, args, binding, parent);
119
+ methods.set(property, method);
120
+ }
121
+ return method;
122
+ },
123
+ });
124
+ }
125
+ function dependencyOf(binding, name) {
126
+ if (Object.hasOwn(binding.overrides, name))
127
+ return { found: true, value: binding.overrides[name] };
128
+ if (Object.hasOwn(binding.registry.dependencies, name))
129
+ return { found: true, value: binding.registry.dependencies[name] };
130
+ return { found: false, value: undefined };
131
+ }
132
+ /**
133
+ * The run's own view of the instance: its context, its dependencies bound to this execution
134
+ * (each bound the first time it is read), and — for an ApplicationService — its Features as
135
+ * children of this run. Anything else is the instance's.
136
+ */
137
+ function viewOf(target, binding, execution) {
138
+ const bound = new Map();
139
+ let features;
140
+ const isComposer = composes(target);
141
+ return new Proxy(target, {
142
+ get(held, property, receiver) {
143
+ if (property === "context")
144
+ return execution.context;
145
+ if (property === "feature" && isComposer)
146
+ return (features ??= featuresOf(binding, execution));
147
+ if (typeof property === "string") {
148
+ if (bound.has(property))
149
+ return bound.get(property);
150
+ const dependency = dependencyOf(binding, property);
151
+ if (dependency.found) {
152
+ const value = bindDependency(dependency.value, execution);
153
+ bound.set(property, value);
154
+ return value;
155
+ }
156
+ }
157
+ return Reflect.get(held, property, receiver);
158
+ },
159
+ set(held, property, value) {
160
+ if (ANSWERED.has(String(property)))
161
+ return false;
162
+ if (typeof property === "string" && dependencyOf(binding, property).found)
163
+ return false;
164
+ // What a method writes on `this` lands on the instance — it is the bounded context's.
165
+ return Reflect.set(held, property, value);
166
+ },
167
+ });
168
+ }
169
+ /** An ApplicationService's `this.feature`: each Feature, asked by name, a child of the run. */
170
+ function featuresOf(binding, execution) {
171
+ const children = new Map();
172
+ return new Proxy({}, {
173
+ get(_, property) {
174
+ if (typeof property !== "string" || !binding.registry.features.has(property))
175
+ return undefined;
176
+ let child = children.get(property);
177
+ if (child === undefined) {
178
+ child = intercepted(property, binding, execution);
179
+ children.set(property, child);
180
+ }
181
+ return child;
182
+ },
183
+ });
184
+ }
185
+ const NOTHING = {};
186
+ /** What a gesture runs with: the process's context, under it the bounded context's, its scope's. */
187
+ function contextOf(binding) {
188
+ return {
189
+ ...processContext.values,
190
+ ...binding.registry.context.values,
191
+ ...binding.scope,
192
+ };
193
+ }
194
+ /**
195
+ * Whether this is the first run to report this error. A Feature that fails inside an
196
+ * ApplicationService throws through it: the error is reported once, by the run where it
197
+ * happened — its span is the one that says where — and every run around it still ends `failed`.
198
+ */
199
+ const REPORTED = new WeakSet();
200
+ function firstReport(error) {
201
+ if (error === null || (typeof error !== "object" && typeof error !== "function"))
202
+ return true;
203
+ if (REPORTED.has(error))
204
+ return false;
205
+ REPORTED.add(error);
206
+ return true;
207
+ }
208
+ /** What watches a use case never changes what it answers: a tracer or reporter that throws is ignored. */
209
+ function quietly(work, otherwise) {
210
+ try {
211
+ return work();
212
+ }
213
+ catch {
214
+ return otherwise;
215
+ }
216
+ }
217
+ const NO_SPAN = {
218
+ traceId: "",
219
+ spanId: "",
220
+ sampled: false,
221
+ set: () => undefined,
222
+ end: () => undefined,
223
+ };
224
+ function run(target, key, method, body, args, binding, parent) {
225
+ const settings = processNow();
226
+ const boundedContext = binding.registry.name;
227
+ // As sincpro_framework names a use case: the span `context/Name`, the identity `context.Name`.
228
+ const identity = method === "execute" ? key : `${key}.${method}`;
229
+ const useCase = `${boundedContext}.${identity}`;
230
+ const context = parent?.context ?? quietly(() => contextOf(binding), NOTHING);
231
+ const id = newEntityId();
232
+ const attributes = {
233
+ "sincpro.use_case": useCase,
234
+ "sincpro.layer": composes(target) ? "application_service" : "feature",
235
+ "sincpro.context": boundedContext,
236
+ "sincpro.execution_id": id,
237
+ };
238
+ const span = quietly(() => settings.tracer.start(`${boundedContext}/${identity}`, {
239
+ ...(parent === undefined ? {} : { parent: parent.span }),
240
+ attributes,
241
+ }), NO_SPAN);
242
+ const execution = { id, useCase, boundedContext, parent, span, context };
243
+ const finish = (failed, error) => {
244
+ const outcome = failed ? quietly(() => settings.outcomeOf(error), "failed") : "ok";
245
+ quietly(() => span.end(outcome, error), undefined);
246
+ if (outcome === "failed" && firstReport(error))
247
+ quietly(() => settings.reporter?.report(error, {
248
+ useCase,
249
+ traceId: span.traceId,
250
+ executionId: id,
251
+ context,
252
+ }), undefined);
253
+ };
254
+ let answer;
255
+ try {
256
+ answer = body.apply(viewOf(target, binding, execution), args);
257
+ }
258
+ catch (error) {
259
+ finish(true, error);
260
+ throw error;
261
+ }
262
+ if (answer instanceof Promise)
263
+ return answer.then((value) => {
264
+ finish(false);
265
+ return value;
266
+ }, (error) => {
267
+ finish(true, error);
268
+ throw error;
269
+ });
270
+ finish(false);
271
+ return answer;
272
+ }