@sincpro/client-framework 1.9.0 → 1.10.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 CHANGED
@@ -171,8 +171,8 @@ their entries — `operations.X` (an identity), `events.X` (a wire name) — as
171
171
  registered for, and executes them as data:
172
172
 
173
173
  ```ts
174
- import { events, operations } from "../generated/client";
175
- import type * as remote from "../generated/domain";
174
+ import { events, operations } from "../adapters/generated/client";
175
+ import type * as remote from "../domain/generated";
176
176
 
177
177
  @projectBoundedContext.feature([events.IssueClosed, operations.CommandArchiveIssue])
178
178
  class Archive extends Feature<remote.IssueClosed | RemoteCommand<remote.CommandArchiveIssue>, void> {
@@ -358,7 +358,7 @@ Three things a platform keeps in mind:
358
358
  `static fromJSON` to read them back as such.
359
359
 
360
360
  The events a remote service publishes arrive as generated types (`DomainEvent` in
361
- `generated/domain.ts`, a union narrowed by `name`); a local event is a class, like a local
361
+ `domain/generated/events.ts`, a union narrowed by `name`); a local event is a class, like a local
362
362
  Command.
363
363
 
364
364
  ## Extending the pipeline
@@ -632,7 +632,7 @@ which operation, with what input, and the adapter the application injects decide
632
632
  travels.
633
633
 
634
634
  ```ts
635
- import { clientOf } from "./generated/client";
635
+ import { clientOf } from "./adapters/generated/client";
636
636
 
637
637
  // pick the wire; the client, the Features and the tests stay the same
638
638
  const forge = clientOf(restOperations(restTransport({ base: "/v1", headers: session })));
@@ -660,6 +660,26 @@ its trace (`traceparent`), its context (`sincpro-context`) and its signal — as
660
660
  as metadata where a platform's adapter puts them. `screensTransport` and `entity()` stay on the
661
661
  REST `Transport`: they are how a screen reads pages of an entity, with its model and its drafts.
662
662
 
663
+ ### What a write changed
664
+
665
+ A client keeps what it read — a cache, a list on screen, a record — and every one of them goes
666
+ stale when a write lands, whoever wrote it. So every write says so: `restTransport` and
667
+ `memoryTransport` announce each `send` on the process's change feed (`processChanges`), whether it
668
+ came from a screen or from a use case's generated client, answered or refused. A preview and a dry
669
+ run announce nothing. A reader follows the feed, never the writer's transport:
670
+
671
+ ```ts
672
+ import { processChanges } from "@sincpro/client-framework";
673
+
674
+ const stop = processChanges.follow((change) => forgetUnder(change.route)); // { method, route }
675
+ stop();
676
+ ```
677
+
678
+ A change says only what was written; what it touches — the collections a route names, a record's
679
+ history — is each reader's to decide. A transport given `changes` announces there instead (a test,
680
+ a transport that must not be heard), and a platform's own adapter wraps its `send` in
681
+ `announced(feed, method, route, body, send)`.
682
+
663
683
  ### Writing an adapter for another wire
664
684
 
665
685
  An adapter is one function: read the operation's binding for its wire, send the input, answer the
@@ -693,20 +713,29 @@ Every operation in `operations` carries its identity and each wire's binding (`r
693
713
 
694
714
  ```bash
695
715
  python -m sincpro_framework.entrypoints export-client-contract app.http:gateways contracts [--events]
696
- sincpro-client generate contracts/project.contract.json --out src/domains/project/generated --domain project
716
+ sincpro-client generate contracts/project.contract.json --out src/domains/project --domain project
697
717
  sincpro-client scaffold contracts/project.contract.json --out src/domains/project
698
718
  sincpro-client check --root src
699
719
  ```
700
720
 
701
- `generate` writes, from the contract the backend exports — never edited, written again whole:
721
+ `generate` writes, from the contract the backend exports — never edited, written again whole —,
722
+ each file in the layer it belongs to, under the bounded context's folder (`--out`):
723
+
724
+ | File | What |
725
+ | -------------------------------- | --------------------------------------------------------------------------------------------- |
726
+ | `domain/generated/models.ts` | the entities and value objects: a type per model, and the definitions they hold |
727
+ | `domain/generated/commands.ts` | every operation's Command and Response, and the `<Name>Input` a caller sends |
728
+ | `domain/generated/events.ts` | the domain events and `DomainEvent`, their union — when the contract carries them |
729
+ | `domain/generated/index.ts` | the three, re-exported: `import type * as remote from "../domain/generated"` |
730
+ | `adapters/generated/client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
731
+ | `adapters/generated/entities.ts` | each entity's list, record, edit, export, Commands and history, for screens |
702
732
 
703
- | File | What |
704
- | ------------- | --------------------------------------------------------------------------------------------- |
705
- | `domain.ts` | a type per model, per `<Name>Input`, per operation's input and answer, per domain event |
706
- | `client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
707
- | `entities.ts` | each entity's list, record, edit, export, Commands and history, for screens |
733
+ The backend keeps them apart — the domain's words, the application layer's DTOs, the facts, the
734
+ adapters to another system —, and so does the application: each beside its own code of that layer.
735
+ A shared definition goes with the first kind that names it (the models, then the operations, then
736
+ the events), and a file that names one written elsewhere imports it from there.
708
737
 
709
- Each method takes the operation's input and answers its answer, as `domain.ts` types them — a
738
+ Each method takes the operation's input and answers its answer, as `commands.ts` types them — a
710
739
  search answers its `Response…` with its records and cursor, as the backend's callers get it, on
711
740
  every wire. `scaffold` writes, once, the application's own files: its dependencies (the client
712
741
  over the `operations` the application exports — `--operations <module>` —), its `framework.ts`
@@ -719,7 +748,7 @@ exported with `--events`. Then each event is a type as it is received — every
719
748
  `name` its wire name as a literal — and `DomainEvent`, their union, narrows by `name`:
720
749
 
721
750
  ```ts
722
- import type * as remote from "./generated/domain";
751
+ import type * as remote from "./domain/generated";
723
752
 
724
753
  function subjectOf(event: remote.DomainEvent): string {
725
754
  switch (event.name) {
@@ -730,7 +759,7 @@ function subjectOf(event: remote.DomainEvent): string {
730
759
  }
731
760
  ```
732
761
 
733
- `events` in `client.ts` says, per event, its wire name and whether the bounded context records it
762
+ `events` in `adapters/generated/client.ts` says, per event, its wire name and whether the bounded context records it
734
763
  (its aggregates' own) or handles it (a Feature subscribes).
735
764
 
736
765
  ### Types, not classes
@@ -747,13 +776,13 @@ types; the application's own Commands are classes, written by hand.
747
776
  a local Feature, through the injected client.
748
777
  - **Events read best as a union.** A stream of facts — a queue, a history page — is narrowed by
749
778
  `name`, with no registry of constructors to rebuild each one.
750
- - **Nothing runs.** `domain.ts` adds no byte to a bundle and no side effect; a contract of three
779
+ - **Nothing runs.** `domain/generated/` adds no byte to a bundle and no side effect; a contract of three
751
780
  hundred models costs nothing at runtime.
752
781
 
753
782
  A local class takes the contract's shape and stays checked against it:
754
783
 
755
784
  ```ts
756
- import type * as remote from "../generated/domain";
785
+ import type * as remote from "../domain/generated";
757
786
 
758
787
  class CommandCancelIssue
759
788
  extends Command<ResponseCancelIssue>
@@ -800,9 +829,10 @@ src/
800
829
  domains/
801
830
  common/infrastructure/operations.ts export const operations — the wire every client uses
802
831
  <bounded context>/
803
- generated/ sincpro-client generate — never edited
804
832
  domain/ local Commands, Responses, DomainEvents, value rules
833
+ generated/ sincpro-client generate: models, commands, events — never edited
805
834
  adapters/ repositories, printers, other systems
835
+ generated/ sincpro-client generate: the client and the entities
806
836
  services/ the use cases, one folder per aggregate or entity
807
837
  <aggregate>/ sale_order/: its Features and ApplicationServices
808
838
  confirm-quotation.feature.ts
@@ -1,3 +1,4 @@
1
+ import type { ChangeFeed } from "../domain/changes.js";
1
2
  import { type Draft, type Method, type Transport } from "../domain/transport.js";
2
3
  import type { AnyRecord, Criteria, Meta, Problem } from "@sincpro/criteria";
3
4
  /**
@@ -42,5 +43,8 @@ export type MemoryOptions = {
42
43
  refuse?: (route: string) => (Problem & {
43
44
  status?: number;
44
45
  }) | undefined;
46
+ /** Where each write is announced (`Change`), as a real server's transport does: the
47
+ * process's feed (`processChanges`) by default. */
48
+ changes?: ChangeFeed;
45
49
  };
46
50
  export declare function memoryTransport(tables: Readonly<Record<string, MemoryTable>>, options?: MemoryOptions): Transport;
@@ -1,4 +1,5 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
+ import { announced, processChanges } from "../services/changes.js";
2
3
  import { bindableTransport } from "../services/propagation.js";
3
4
  import { pack, readValues } from "../../common/serialization.js";
4
5
  import { answer, answerGroups } from "@sincpro/criteria/engine";
@@ -24,6 +25,7 @@ function wait(ms, signal) {
24
25
  }
25
26
  export function memoryTransport(tables, options = {}) {
26
27
  const answered = new Map();
28
+ const changes = options.changes ?? processChanges;
27
29
  async function check(route, signal) {
28
30
  await wait(options.latency ?? 0, signal);
29
31
  const refused = options.refuse?.(route);
@@ -86,27 +88,29 @@ export function memoryTransport(tables, options = {}) {
86
88
  };
87
89
  },
88
90
  async send(method, route, body, signal, sending) {
89
- await check(route, signal);
90
- // A key already answered is answered again, without running the Command twice — what
91
- // sincpro_framework's `@idempotency` does with a repeated `Idempotency-Key`.
92
- const key = sending?.idempotencyKey;
93
- if (key !== undefined && answered.has(key))
94
- return copyOf(answered.get(key));
95
- if (options.handle === undefined)
96
- throw new TransportError(route, 404, {
97
- kind: "not_found",
98
- reason: "ROUTE_NOT_FOUND",
99
- next_step: "fix_request",
100
- retryable: false,
101
- errors: [],
102
- extensions: {},
103
- detail: `Nothing answers ${method} ${route}.`,
104
- });
105
- // A deep copy: what the caller sent is not what the server keeps.
106
- const answer = await options.handle(method, route, copyOf(body));
107
- if (key !== undefined)
108
- answered.set(key, copyOf(answer));
109
- return answer;
91
+ return announced(changes, method, route, body, async () => {
92
+ await check(route, signal);
93
+ // A key already answered is answered again, without running the Command twice — what
94
+ // sincpro_framework's `@idempotency` does with a repeated `Idempotency-Key`.
95
+ const key = sending?.idempotencyKey;
96
+ if (key !== undefined && answered.has(key))
97
+ return copyOf(answered.get(key));
98
+ if (options.handle === undefined)
99
+ throw new TransportError(route, 404, {
100
+ kind: "not_found",
101
+ reason: "ROUTE_NOT_FOUND",
102
+ next_step: "fix_request",
103
+ retryable: false,
104
+ errors: [],
105
+ extensions: {},
106
+ detail: `Nothing answers ${method} ${route}.`,
107
+ });
108
+ // A deep copy: what the caller sent is not what the server keeps.
109
+ const answer = await options.handle(method, route, copyOf(body));
110
+ if (key !== undefined)
111
+ answered.set(key, copyOf(answer));
112
+ return answer;
113
+ });
110
114
  },
111
115
  ...(options.read === undefined
112
116
  ? {}
@@ -1,3 +1,4 @@
1
+ import type { ChangeFeed } from "../domain/changes.js";
1
2
  import { type Decoder, type Transport } from "../domain/transport.js";
2
3
  import { type Criteria } from "@sincpro/criteria";
3
4
  /**
@@ -44,6 +45,9 @@ export type RestOptions = {
44
45
  /** Called once per model and version the server answers that the snapshot does not hold —
45
46
  * never an error: the screen keeps working on the live definition. */
46
47
  onVersionDrift?: (drift: VersionDrift) => void;
48
+ /** Where each write is announced (`Change`): the process's feed (`processChanges`) by default,
49
+ * so a cache or a screen hears it whoever wrote — a screen, or a use case's client. */
50
+ changes?: ChangeFeed;
47
51
  };
48
52
  /** A model the server answers at another version than the snapshot the code came from. */
49
53
  export type VersionDrift = {
@@ -1,4 +1,5 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
+ import { announced, processChanges } from "../services/changes.js";
2
3
  import { definitionOf, modelAt, } from "../services/discovery.js";
3
4
  import { bindableTransport } from "../services/propagation.js";
4
5
  import { readProblem } from "@sincpro/criteria";
@@ -45,6 +46,7 @@ function documentUrl(base, document) {
45
46
  export function restTransport(options = {}) {
46
47
  const base = options.base ?? "";
47
48
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
49
+ const changes = options.changes ?? processChanges;
48
50
  const decoders = options.decoders ?? [];
49
51
  const accept = decoders.length === 0
50
52
  ? {}
@@ -183,7 +185,9 @@ export function restTransport(options = {}) {
183
185
  };
184
186
  },
185
187
  async send(method, route, body, signal, sending) {
186
- return (await get(route, urlOf(base, route), signal, { method, body, key: sending?.idempotencyKey }, sending));
188
+ return announced(changes, method, route, body, async () => {
189
+ return (await get(route, urlOf(base, route), signal, { method, body, key: sending?.idempotencyKey }, sending));
190
+ });
187
191
  },
188
192
  });
189
193
  }
@@ -0,0 +1,45 @@
1
+ import type { Method } from "./transport.js";
2
+ /**
3
+ * A write that may have changed what was read: how it was sent and where.
4
+ *
5
+ * Context: a client keeps what it read — a cache, a list on screen, a record, a name in a cell —
6
+ * and every one of them goes stale the moment a write lands, whoever wrote: a screen's save, a use
7
+ * case's Command, a second panel. Each used to learn it only when the write went through the same
8
+ * object it read through, so a use case writing over its generated client left every screen
9
+ * reading the old answer. A change is the fact every reader can hear instead (`ChangeFeed`). It
10
+ * says only what was written — what that touches (the collections a route names, a record's
11
+ * history) is each reader's to decide, as a cache and a screen decide differently.
12
+ *
13
+ * { method: "POST", route: "/issues/odoo-acme-7/messages" }
14
+ */
15
+ export type Change = {
16
+ readonly method: Method;
17
+ /** As the transport received it: a path under its base, maybe with a query. */
18
+ readonly route: string;
19
+ };
20
+ /**
21
+ * Who hears what was written: one feed the writers announce to and the readers follow, so neither
22
+ * knows the other.
23
+ *
24
+ * const stop = processChanges.follow((change) => cache.forget(change.route));
25
+ * processChanges.announce({ method: "PUT", route: "/projects/odoo-acme/edit" });
26
+ * stop();
27
+ *
28
+ * Context: a listener that fails is ignored — hearing a write never changes its answer, as
29
+ * tracing and listening never do.
30
+ */
31
+ export type ChangeFeed = {
32
+ /** Tells everyone who follows now: this was written. */
33
+ announce(change: Change): void;
34
+ /** `listener` hears every change announced from now on; answers the way to stop. */
35
+ follow(listener: (change: Change) => void): () => void;
36
+ };
37
+ /**
38
+ * The change a `send` makes, or `undefined` when it writes nothing: a preview (`…/preview`) and a
39
+ * dry run (`dry_run: true`, sincpro_framework's `DryRunnable`) only say what a write WOULD do.
40
+ *
41
+ * changeOf("POST", "/issues/7/cancel", {}) -> { method: "POST", route: "/issues/7/cancel" }
42
+ * changeOf("POST", "/issues/7/cancel", { dry_run: true }) -> undefined
43
+ * changeOf("POST", "/invoices/preview", { lines: [] }) -> undefined
44
+ */
45
+ export declare function changeOf(method: Method, route: string, body: unknown): Change | undefined;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The change a `send` makes, or `undefined` when it writes nothing: a preview (`…/preview`) and a
3
+ * dry run (`dry_run: true`, sincpro_framework's `DryRunnable`) only say what a write WOULD do.
4
+ *
5
+ * changeOf("POST", "/issues/7/cancel", {}) -> { method: "POST", route: "/issues/7/cancel" }
6
+ * changeOf("POST", "/issues/7/cancel", { dry_run: true }) -> undefined
7
+ * changeOf("POST", "/invoices/preview", { lines: [] }) -> undefined
8
+ */
9
+ export function changeOf(method, route, body) {
10
+ if ((route.split("?")[0] ?? route).endsWith("/preview"))
11
+ return undefined;
12
+ if (typeof body === "object" && body !== null && "dry_run" in body && body.dry_run === true)
13
+ return undefined;
14
+ return { method, route };
15
+ }
@@ -3,18 +3,21 @@
3
3
  * commands, the service's client contract, and how a run's trace and context reach the wire.
4
4
  *
5
5
  * domain/ the port and the server's words: `Transport`, `TransportError`, `entity()`, the
6
- * client contract
6
+ * client contract, what a write changed (`Change`, `ChangeFeed`)
7
7
  * adapters/ REST, memory, and Parquet (optional entry `./parquet`)
8
- * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`)
8
+ * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`), the
9
+ * process's change feed (`processChanges`)
9
10
  */
10
11
  export { JsonRpcError, jsonRpcOperations, type JsonRpcOptions, } from "./adapters/json-rpc.js";
11
12
  export { type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
12
13
  export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./adapters/rest.js";
13
14
  export { restOperations } from "./adapters/rest-operations.js";
15
+ export { type Change, type ChangeFeed, changeOf, } from "./domain/changes.js";
14
16
  export { type ClientContract, entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
15
17
  export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type EntityRef, type EntityRoutes, type ExportFormat, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, type SummaryFields, type SummaryPart, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./domain/entity.js";
16
18
  export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
17
19
  export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, type Method, type One, readRoute, type SendOptions, type Transport, TransportError, } from "./domain/transport.js";
20
+ export { announced, changeFeed, processChanges, } from "./services/changes.js";
18
21
  export { guardedTransport } from "./services/guarded.js";
19
22
  export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
20
23
  export { type RetryKeys, retryKeys, unanswered, } from "./services/retry.js";
@@ -3,18 +3,21 @@
3
3
  * commands, the service's client contract, and how a run's trace and context reach the wire.
4
4
  *
5
5
  * domain/ the port and the server's words: `Transport`, `TransportError`, `entity()`, the
6
- * client contract
6
+ * client contract, what a write changed (`Change`, `ChangeFeed`)
7
7
  * adapters/ REST, memory, and Parquet (optional entry `./parquet`)
8
- * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`)
8
+ * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`), the
9
+ * process's change feed (`processChanges`)
9
10
  */
10
11
  export { JsonRpcError, jsonRpcOperations, } from "./adapters/json-rpc.js";
11
12
  export { memoryTransport, } from "./adapters/memory.js";
12
13
  export { restTransport, urlOf, } from "./adapters/rest.js";
13
14
  export { restOperations } from "./adapters/rest-operations.js";
15
+ export { changeOf, } from "./domain/changes.js";
14
16
  export { entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
15
17
  export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./domain/entity.js";
16
18
  export { OperationNotPublished, } from "./domain/operation.js";
17
19
  export { downloadRoute, readRoute, TransportError, } from "./domain/transport.js";
20
+ export { announced, changeFeed, processChanges, } from "./services/changes.js";
18
21
  export { guardedTransport } from "./services/guarded.js";
19
22
  export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
20
23
  export { retryKeys, unanswered, } from "./services/retry.js";
@@ -0,0 +1,32 @@
1
+ import { type ChangeFeed } from "../domain/changes.js";
2
+ import type { Method } from "../domain/transport.js";
3
+ /**
4
+ * A feed in the process's memory: every listener hears every change announced while it follows.
5
+ *
6
+ * const changes = changeFeed();
7
+ * const stop = changes.follow((change) => console.log(change.route));
8
+ *
9
+ * Context: one is enough for an application — `processChanges`, which every transport of this
10
+ * package announces to by default —; another is for a test, or a transport that must not be heard.
11
+ * A listener added while a change is being announced hears the next one, not that one.
12
+ */
13
+ export declare function changeFeed(): ChangeFeed;
14
+ /**
15
+ * What the process wrote, for whoever keeps what it read: the feed this package's transports
16
+ * (`restTransport`, `memoryTransport`) announce every write to unless told otherwise, and the one
17
+ * a platform's caches and screens follow.
18
+ *
19
+ * processChanges.follow((change) => …);
20
+ *
21
+ * Context: it lives as long as the process — `configureProcess` does not clear it —, so whoever
22
+ * follows keeps the function that stops it, as with `processListeners`.
23
+ */
24
+ export declare const processChanges: ChangeFeed;
25
+ /**
26
+ * `write` — a transport's `send` —, and then its change announced on `feed`, whatever it answered:
27
+ * a refusal may have changed something too (a 409 says someone else did), and a request with no
28
+ * answer may have run. A preview or a dry run announces nothing (`changeOf`).
29
+ *
30
+ * send: (method, route, body) => announced(changes, method, route, body, () => post(…)),
31
+ */
32
+ export declare function announced<T>(feed: ChangeFeed, method: Method, route: string, body: unknown, write: () => Promise<T>): Promise<T>;
@@ -0,0 +1,60 @@
1
+ import { changeOf, } from "../domain/changes.js";
2
+ /**
3
+ * A feed in the process's memory: every listener hears every change announced while it follows.
4
+ *
5
+ * const changes = changeFeed();
6
+ * const stop = changes.follow((change) => console.log(change.route));
7
+ *
8
+ * Context: one is enough for an application — `processChanges`, which every transport of this
9
+ * package announces to by default —; another is for a test, or a transport that must not be heard.
10
+ * A listener added while a change is being announced hears the next one, not that one.
11
+ */
12
+ export function changeFeed() {
13
+ const listeners = new Set();
14
+ return {
15
+ announce(change) {
16
+ for (const listener of [...listeners]) {
17
+ try {
18
+ listener(change);
19
+ }
20
+ catch {
21
+ // Hearing a write never changes its answer, as tracing and listening never do.
22
+ }
23
+ }
24
+ },
25
+ follow(listener) {
26
+ if (typeof listener !== "function")
27
+ throw new TypeError("A listener is a function");
28
+ listeners.add(listener);
29
+ return () => void listeners.delete(listener);
30
+ },
31
+ };
32
+ }
33
+ /**
34
+ * What the process wrote, for whoever keeps what it read: the feed this package's transports
35
+ * (`restTransport`, `memoryTransport`) announce every write to unless told otherwise, and the one
36
+ * a platform's caches and screens follow.
37
+ *
38
+ * processChanges.follow((change) => …);
39
+ *
40
+ * Context: it lives as long as the process — `configureProcess` does not clear it —, so whoever
41
+ * follows keeps the function that stops it, as with `processListeners`.
42
+ */
43
+ export const processChanges = changeFeed();
44
+ /**
45
+ * `write` — a transport's `send` —, and then its change announced on `feed`, whatever it answered:
46
+ * a refusal may have changed something too (a 409 says someone else did), and a request with no
47
+ * answer may have run. A preview or a dry run announces nothing (`changeOf`).
48
+ *
49
+ * send: (method, route, body) => announced(changes, method, route, body, () => post(…)),
50
+ */
51
+ export async function announced(feed, method, route, body, write) {
52
+ try {
53
+ return await write();
54
+ }
55
+ finally {
56
+ const change = changeOf(method, route, body);
57
+ if (change !== undefined)
58
+ feed.announce(change);
59
+ }
60
+ }
@@ -5,7 +5,17 @@ import type { Metamodel } from "./metamodel.js";
5
5
  * whole, the generated files came out importing `"../index.js"` and `"./domain.js"`.
6
6
  */
7
7
  export declare const FRAMEWORK: string;
8
+ /**
9
+ * Where `generate` writes each layer of a bounded context, from its folder: the domain's types
10
+ * (`models.ts`, `commands.ts`, `events.ts`, `index.ts`) and the adapters over the service's wire
11
+ * (`client.ts`, `entities.ts`) — each beside the code of its layer, as the backend lays it out.
12
+ */
13
+ export declare const GENERATED_DOMAIN: string;
14
+ export declare const GENERATED_ADAPTERS: string;
15
+ /** What a generated adapter imports the domain's types from: `../../domain/generated/index`. */
8
16
  export declare const DOMAIN_MODULE: string;
17
+ /** A file of `domain/generated/` as its sibling imports it: `models` → `./models`. */
18
+ export declare function siblingOf(file: string): string;
9
19
  /** A name of the server's as a TypeScript identifier: `shop__orders__Line` stays, `-` is `_`. */
10
20
  export declare function identifierOf(name: string): string;
11
21
  /** A property key as TypeScript writes it: bare when it can be, quoted otherwise. */
@@ -14,7 +14,19 @@ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
14
14
  * whole, the generated files came out importing `"../index.js"` and `"./domain.js"`.
15
15
  */
16
16
  export const FRAMEWORK = ["@sincpro", "client-framework"].join("/");
17
- export const DOMAIN_MODULE = [".", "domain"].join("/");
17
+ /**
18
+ * Where `generate` writes each layer of a bounded context, from its folder: the domain's types
19
+ * (`models.ts`, `commands.ts`, `events.ts`, `index.ts`) and the adapters over the service's wire
20
+ * (`client.ts`, `entities.ts`) — each beside the code of its layer, as the backend lays it out.
21
+ */
22
+ export const GENERATED_DOMAIN = ["domain", "generated"].join("/");
23
+ export const GENERATED_ADAPTERS = ["adapters", "generated"].join("/");
24
+ /** What a generated adapter imports the domain's types from: `../../domain/generated/index`. */
25
+ export const DOMAIN_MODULE = ["..", "..", GENERATED_DOMAIN, "index"].join("/");
26
+ /** A file of `domain/generated/` as its sibling imports it: `models` → `./models`. */
27
+ export function siblingOf(file) {
28
+ return [".", file].join("/");
29
+ }
18
30
  /** A name of the server's as a TypeScript identifier: `shop__orders__Line` stays, `-` is `_`. */
19
31
  export function identifierOf(name) {
20
32
  const cleaned = name.replace(/[^A-Za-z0-9_$]/g, "_");
@@ -1,28 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
- import { aliasOf } from "../domain/names.js";
4
+ import { aliasOf, GENERATED_ADAPTERS, GENERATED_DOMAIN, } from "../domain/names.js";
5
5
  import { CheckError, checkImports } from "../services/check.js";
6
- import { clientFileOf } from "../services/client.js";
7
- import { domainFileOf } from "../services/domain.js";
8
- import { entitiesFileOf } from "../services/entities.js";
6
+ import { generatedFilesOf } from "../services/generated.js";
9
7
  import { scaffoldFilesOf } from "../services/scaffold.js";
10
8
  /**
11
9
  * `sincpro-client generate <contract.json> --out <dir> [--domain <name>] [--base <path>]` — what an
12
10
  * application's `make client` runs, once per bounded context, over the client contract
13
- * sincpro_framework exported (`export-client-contract`):
11
+ * sincpro_framework exported (`export-client-contract`). `--out` is the bounded context's folder
12
+ * (`src/domains/project`); each file goes in its layer (`generatedFilesOf`):
14
13
  *
15
- * - `domain.ts`: the DTOs, only types — and the domain events with `DomainEvent`, their union,
16
- * when the contract was exported with them (`export-client-contract --events`);
17
- * - `client.ts`: every operation (and event) as data, and `clientOf(operations)` over any wire;
18
- * - `entities.ts`: an `entity<T, C>()` per model a screen can list;
19
- * - `contract.json`: the snapshot they were written from, for `metasOf`.
14
+ * - `domain/generated/models.ts`: the entities and value objects, only types;
15
+ * - `domain/generated/commands.ts`: every operation's Command and Response;
16
+ * - `domain/generated/events.ts`: the domain events and `DomainEvent`, their union — when the
17
+ * contract was exported with them (`export-client-contract --events`);
18
+ * - `domain/generated/index.ts`: the three, re-exported;
19
+ * - `domain/generated/contract.json`: the snapshot they were written from, for `metasOf`;
20
+ * - `adapters/generated/client.ts`: every operation (and event) as data, and
21
+ * `clientOf(operations)` over any wire;
22
+ * - `adapters/generated/entities.ts`: an `entity<T, C>()` per model a screen can list.
20
23
  *
21
- * A bare metamodel (`export_metamodel`, no bindings) writes `domain.ts` and `contract.json` only.
24
+ * A bare metamodel (`export_metamodel`, no bindings) writes only `domain/generated/`.
22
25
  *
23
- * Context: it writes only into `--out`, and the same bytes for the same contract, so `make
24
- * verify-client` regenerates and fails on any difference. The folder is the generator's: keep
25
- * it out of the application's prettier and eslint, or a formatter rewrites what was generated.
26
+ * Context: it writes only its two `generated/` folders, whole every time — what is no longer
27
+ * generated goes —, and the same bytes for the same contract, so `make verify-client` regenerates
28
+ * and fails on any difference. The folders are the generator's: keep them out of the
29
+ * application's prettier and eslint, or a formatter rewrites what was generated.
26
30
  */
27
31
  const USAGE = [
28
32
  "usage: sincpro-client generate <contract.json> --out <dir> [--domain <name>] [--base <path>]",
@@ -129,15 +133,16 @@ function main(args) {
129
133
  const metamodel = JSON.parse(readFileSync(asked.source, "utf8"));
130
134
  if (asked.command === "scaffold")
131
135
  return scaffold(metamodel, asked.out, asked.operations);
132
- const files = { "domain.ts": domainFileOf(metamodel) };
133
- if (metamodel.bindings !== undefined) {
134
- files["client.ts"] = clientFileOf(metamodel, asked.options);
135
- files["entities.ts"] = entitiesFileOf(metamodel, asked.options);
136
+ const files = generatedFilesOf(metamodel, asked.options);
137
+ files[`${GENERATED_DOMAIN}/contract.json`] =
138
+ `${JSON.stringify(canonical(metamodel), null, 2)}\n`;
139
+ for (const folder of [GENERATED_DOMAIN, GENERATED_ADAPTERS])
140
+ rmSync(join(asked.out, folder), { recursive: true, force: true });
141
+ for (const [name, source] of Object.entries(files)) {
142
+ const path = join(asked.out, name);
143
+ mkdirSync(dirname(path), { recursive: true });
144
+ writeFileSync(path, source);
136
145
  }
137
- files["contract.json"] = `${JSON.stringify(canonical(metamodel), null, 2)}\n`;
138
- mkdirSync(asked.out, { recursive: true });
139
- for (const [name, source] of Object.entries(files))
140
- writeFileSync(join(asked.out, name), source);
141
146
  console.log(`✓ ${aliasOf(metamodel)} → ${asked.out} (${Object.keys(files).join(", ")})`);
142
147
  return 0;
143
148
  }
@@ -1,12 +1,14 @@
1
1
  /**
2
- * The generator: a bounded context's DTOs, client and entities out of the client contract
3
- * sincpro_framework exports (PRD_01 phase B). A build step that runs in Node — nothing in
2
+ * The generator: a bounded context's types (entities and value objects, Commands and Responses,
3
+ * domain events), client and entities out of the client contract sincpro_framework exports
4
+ * (PRD_01 phase B), each file in its layer (`generatedFilesOf`). A build step that runs in Node — nothing in
4
5
  * the runtime imports it (`make doctor`), and the package's root entry does not re-export it. `sincpro-client generate` (`cli.ts`) is the same, from a terminal.
5
6
  */
6
7
  export type { Bindings, Metamodel, Operation, RestBinding, Schema, } from "./domain/metamodel.js";
7
8
  export { CheckError, checkImports, type Place, placeOf, type Violation, violationOf, } from "./services/check.js";
8
9
  export { clientFileOf } from "./services/client.js";
9
- export { domainFileOf } from "./services/domain.js";
10
+ export { domainFilesOf } from "./services/domain.js";
10
11
  export { entitiesFileOf } from "./services/entities.js";
12
+ export { generatedFilesOf } from "./services/generated.js";
11
13
  export type { GenerateOptions } from "./services/rest.js";
12
14
  export { scaffoldFilesOf, type ScaffoldOptions, } from "./services/scaffold.js";
@@ -1,5 +1,6 @@
1
1
  export { CheckError, checkImports, placeOf, violationOf, } from "./services/check.js";
2
2
  export { clientFileOf } from "./services/client.js";
3
- export { domainFileOf } from "./services/domain.js";
3
+ export { domainFilesOf } from "./services/domain.js";
4
4
  export { entitiesFileOf } from "./services/entities.js";
5
+ export { generatedFilesOf } from "./services/generated.js";
5
6
  export { scaffoldFilesOf, } from "./services/scaffold.js";
@@ -1,20 +1,22 @@
1
1
  import type { Metamodel } from "../domain/metamodel.js";
2
2
  /**
3
- * The TypeScript of every DTO of `metamodel`, as the text of one file.
3
+ * The TypeScript of every DTO of `metamodel`, as the files of `domain/generated/`, by name.
4
4
  *
5
- * 1. The models, by name: an entity's contract, a related model by its own name.
6
- * 2. Each operation, by its local name (its identity without `<context>.`): its input as
7
- * `<Name>` and its answer by the backend's own name for it (`answerOf`: `ResponseX`) — or as
8
- * `<Name>Answer` when it has no name.
9
- * 3. A model an input carries — and the ones it carries, until none is new — as `<Name>Input`:
10
- * what a caller sends follows the contract's `required`; the server fills the rest.
11
- * 4. Each domain event, when the contract carries them, by its class's name (`title`): a record
12
- * as it is received — every field present, `name` its wire name as a literal —, and
13
- * `DomainEvent`, the union of them all, which a `switch` on `name` narrows.
14
- * 5. The shared definitions those reach — and the ones those reach, until none is new —, but
15
- * never one a package of the stack already types (`Criteria`).
16
- * Final: a header that says where it came from and not to edit it, the imports, then models,
17
- * definitions, operations and events, each sorted by name; two of them with one TypeScript
18
- * name are refused, naming both.
5
+ * 1. `models.ts`: the models, by name — an entity's contract, a related model by its own name, a
6
+ * value an entity holds —, and the shared definitions they reach.
7
+ * 2. `commands.ts`: each operation, by its local name (its identity without `<context>.`): its
8
+ * input as `<Name>` and its answer by the backend's own name for it (`answerOf`: `ResponseX`) —
9
+ * or as `<Name>Answer` when it has no name. A model an input carries — and the ones it carries,
10
+ * until none is new — as `<Name>Input`: what a caller sends follows the contract's `required`;
11
+ * the server fills the rest. Then the definitions only they reach.
12
+ * 3. `events.ts`, when the contract carries events: each one by its class's name (`title`), a
13
+ * record as it is received — every field present, `name` its wire name as a literal —, and
14
+ * `DomainEvent`, the union of them all, which a `switch` on `name` narrows. Then the
15
+ * definitions only they reach.
16
+ * 4. `index.ts`: the files above, re-exported.
17
+ * Final: each file with a header that says where it came from and not to edit it, its imports —
18
+ * a package of the stack never typed twice (`Criteria`), a sibling's type imported from it —,
19
+ * then its types, each sorted by name; two of them with one TypeScript name, in any file, are
20
+ * refused, naming both.
19
21
  */
20
- export declare function domainFileOf(metamodel: Metamodel): string;
22
+ export declare function domainFilesOf(metamodel: Metamodel): Record<string, string>;
@@ -1,9 +1,17 @@
1
- import { aliasOf, answerOf, claimed, contextOf, deprecationOf, docOf, headerOf, identifierOf, keyOf, localOf, sorted, } from "../domain/names.js";
1
+ import { aliasOf, answerOf, claimed, contextOf, deprecationOf, docOf, headerOf, identifierOf, keyOf, localOf, siblingOf, sorted, } from "../domain/names.js";
2
2
  /**
3
- * The DTOs of a bounded context as TypeScript, out of the contract sincpro_framework exports:
4
- * a type per model, per shared definition a model or an operation reaches, per operation's
5
- * input and answer, and per domain event when the contract carries them. Only types — nothing in
6
- * the file runs.
3
+ * The domain of a bounded context as TypeScript, out of the contract sincpro_framework exports —
4
+ * written in the files of `domain/generated/`, one per kind of thing, as the backend keeps them
5
+ * apart:
6
+ *
7
+ * models.ts its entities and value objects — the domain's own words
8
+ * commands.ts every operation's Command and Response, and the `<Name>Input` a caller
9
+ * sends — the application layer's
10
+ * events.ts its domain events and `DomainEvent`, their union — the facts (only when the
11
+ * contract carries them)
12
+ * index.ts the three, re-exported: what the adapters and an application import
13
+ *
14
+ * Only types — nothing in them runs.
7
15
  *
8
16
  * Context: types, never classes. The wire is JSON, and a type says exactly what it holds — a
9
17
  * decimal as text, a page as `{items, count, cursor}` —, where a class would claim more unless
@@ -11,16 +19,21 @@ import { aliasOf, answerOf, claimed, contextOf, deprecationOf, docOf, headerOf,
11
19
  * `Command` could be registered and executed locally, the confusion between a remote operation
12
20
  * and a local use case this package keeps apart. Events read best as a union narrowed by `name`.
13
21
  *
14
- * Context: the file is a snapshot for whoever writes code — a person, or an agent reading the
22
+ * Context: the files are a snapshot for whoever writes code — a person, or an agent reading the
15
23
  * repository —, never the truth at runtime: the transport keeps reading the live definition and
16
- * revalidates it by `model_version`. So it is written the same way for the same contract (every
17
- * key sorted, byte for byte, which is what `make verify-client` compares) and never edited; an
18
- * application extends a type by composition (`Wire & {…}`).
24
+ * revalidates it by `model_version`. So they are written the same way for the same contract
25
+ * (every key sorted, byte for byte, which is what `make verify-client` compares) and never
26
+ * edited; an application extends a type by composition (`Wire & {…}`).
27
+ *
28
+ * A shared definition goes with the first kind that names it — the models, then the operations,
29
+ * then the events —, and a file that names one written elsewhere imports it from there. Every
30
+ * name is claimed once across the files: `index.ts` re-exports them side by side.
19
31
  *
20
32
  * criteria's grammar comes with every metamodel (`$defs.Criteria`); `@sincpro/criteria` already
21
33
  * types it, so it is imported, never written a second time.
22
34
  *
23
- * domainFileOf(JSON.parse(readFileSync("project.contract.json", "utf8")))
35
+ * domainFilesOf(JSON.parse(readFileSync("project.contract.json", "utf8")))
36
+ * -> { "models.ts": "…", "commands.ts": "…", "index.ts": "…" }
24
37
  */
25
38
  const MODELS = "#/models/";
26
39
  const DEFINITIONS = "#/$defs/";
@@ -63,6 +76,7 @@ function scopeOf(metamodel, shared, input = false) {
63
76
  const scope = {
64
77
  reached: shared?.reached ?? new Set(),
65
78
  imports: shared?.imports ?? new Set(),
79
+ models: shared?.models ?? new Set(),
66
80
  inputs: shared?.inputs ?? new Set(),
67
81
  refer: (ref) => {
68
82
  const model = ref.startsWith(MODELS);
@@ -73,8 +87,10 @@ function scopeOf(metamodel, shared, input = false) {
73
87
  if (model || name in metamodel.models) {
74
88
  if (!(name in metamodel.models))
75
89
  throw new Error(`"${ref}" names no model of ${contextOf(metamodel)}`);
76
- if (!input)
90
+ if (!input) {
91
+ scope.models.add(name);
77
92
  return identifierOf(name);
93
+ }
78
94
  scope.inputs.add(name);
79
95
  return `${identifierOf(name)}Input`;
80
96
  }
@@ -203,33 +219,86 @@ function eventDoc(metamodel, name, event) {
203
219
  return docOf([event.description, `${facts.join(" · ")}.`], "");
204
220
  }
205
221
  /**
206
- * The TypeScript of every DTO of `metamodel`, as the text of one file.
207
- *
208
- * 1. The models, by name: an entity's contract, a related model by its own name.
209
- * 2. Each operation, by its local name (its identity without `<context>.`): its input as
210
- * `<Name>` and its answer by the backend's own name for it (`answerOf`: `ResponseX`) — or as
211
- * `<Name>Answer` when it has no name.
212
- * 3. A model an input carries — and the ones it carries, until none is new — as `<Name>Input`:
213
- * what a caller sends follows the contract's `required`; the server fills the rest.
214
- * 4. Each domain event, when the contract carries them, by its class's name (`title`): a record
215
- * as it is received — every field present, `name` its wire name as a literal —, and
216
- * `DomainEvent`, the union of them all, which a `switch` on `name` narrows.
217
- * 5. The shared definitions those reach — and the ones those reach, until none is new —, but
218
- * never one a package of the stack already types (`Criteria`).
219
- * Final: a header that says where it came from and not to edit it, the imports, then models,
220
- * definitions, operations and events, each sorted by name; two of them with one TypeScript
221
- * name are refused, naming both.
222
+ * The shared definitions `scope` reaches that no other file writes (`elsewhere`) — and the ones
223
+ * those reach, until none is new —, each as its type, by name.
222
224
  */
223
- export function domainFileOf(metamodel) {
224
- const scope = scopeOf(metamodel);
225
- const sent = scopeOf(metamodel, scope, true);
225
+ function definitionsOf(metamodel, scope, elsewhere) {
226
226
  const definitions = metamodel.$defs ?? {};
227
+ const written = new Map();
228
+ const pending = () => [...scope.reached].filter((name) => !elsewhere.has(name) && !written.has(name));
229
+ for (let next = pending(); next.length > 0; next = pending()) {
230
+ for (const name of next) {
231
+ const schema = definitions[name];
232
+ written.set(name, `${docOf([schema.description], "")}export type ${identifierOf(name)} = ${typeOf(schema, scope, 0, false)};`);
233
+ }
234
+ }
235
+ return written;
236
+ }
237
+ /**
238
+ * A file's imports: one line per package of the stack, then one per sibling it names something
239
+ * of (`import type { Issue } from "./models"`), each with its names sorted.
240
+ */
241
+ function importsOf(scope, siblings) {
242
+ const byPackage = new Map();
243
+ for (const name of [...scope.imports].sort()) {
244
+ const imported = IMPORTED[name];
245
+ byPackage.set(imported.from, [...(byPackage.get(imported.from) ?? []), imported.name]);
246
+ }
247
+ const packages = [...byPackage.keys()]
248
+ .sort()
249
+ .map((from) => `import type { ${byPackage.get(from).join(", ")} } from "${from}";`);
250
+ const own = siblings.flatMap(([file, names]) => {
251
+ const named = [...new Set([...names].map(identifierOf))].sort();
252
+ return named.length === 0
253
+ ? []
254
+ : [`import type { ${named.join(", ")} } from "${siblingOf(file)}";`];
255
+ });
256
+ return [packages, own].filter((group) => group.length > 0).map((group) => group.join("\n"));
257
+ }
258
+ /** A file of `domain/generated/`: its header, its imports, then its types. */
259
+ function fileOf(header, imports, types) {
260
+ return `${[header, ...imports, ...types].join("\n\n")}\n`;
261
+ }
262
+ /** The written definitions, sorted by name, each name claimed. */
263
+ function claimedDefinitions(written, claim) {
264
+ return [...written.keys()].sort().map((name) => {
265
+ claim(identifierOf(name), `definition ${name}`);
266
+ return written.get(name);
267
+ });
268
+ }
269
+ /**
270
+ * The TypeScript of every DTO of `metamodel`, as the files of `domain/generated/`, by name.
271
+ *
272
+ * 1. `models.ts`: the models, by name — an entity's contract, a related model by its own name, a
273
+ * value an entity holds —, and the shared definitions they reach.
274
+ * 2. `commands.ts`: each operation, by its local name (its identity without `<context>.`): its
275
+ * input as `<Name>` and its answer by the backend's own name for it (`answerOf`: `ResponseX`) —
276
+ * or as `<Name>Answer` when it has no name. A model an input carries — and the ones it carries,
277
+ * until none is new — as `<Name>Input`: what a caller sends follows the contract's `required`;
278
+ * the server fills the rest. Then the definitions only they reach.
279
+ * 3. `events.ts`, when the contract carries events: each one by its class's name (`title`), a
280
+ * record as it is received — every field present, `name` its wire name as a literal —, and
281
+ * `DomainEvent`, the union of them all, which a `switch` on `name` narrows. Then the
282
+ * definitions only they reach.
283
+ * 4. `index.ts`: the files above, re-exported.
284
+ * Final: each file with a header that says where it came from and not to edit it, its imports —
285
+ * a package of the stack never typed twice (`Criteria`), a sibling's type imported from it —,
286
+ * then its types, each sorted by name; two of them with one TypeScript name, in any file, are
287
+ * refused, naming both.
288
+ */
289
+ export function domainFilesOf(metamodel) {
227
290
  const claim = claimed();
291
+ // 1. The entities and the values they hold.
292
+ const held = scopeOf(metamodel);
228
293
  const models = sorted(metamodel.models).map(([name, schema]) => {
229
294
  claim(identifierOf(name), `model ${name}`);
230
- return `${docOf([schema.description], "")}export type ${identifierOf(name)} = ${typeOf(schema, scope, 0, true)};`;
295
+ return `${docOf([schema.description], "")}export type ${identifierOf(name)} = ${typeOf(schema, held, 0, true)};`;
231
296
  });
232
- // A Response two Commands share is written once, under the first that answers with it.
297
+ const heldDefinitions = definitionsOf(metamodel, held, new Set());
298
+ // 2. The operations. A Response two Commands share is written once, under the first that
299
+ // answers with it.
300
+ const answering = scopeOf(metamodel);
301
+ const sent = scopeOf(metamodel, answering, true);
233
302
  const answered = new Set();
234
303
  const operations = sorted(metamodel.operations).flatMap(([identity, operation]) => {
235
304
  const local = localOf(metamodel, identity);
@@ -237,7 +306,8 @@ export function domainFileOf(metamodel) {
237
306
  claim(local, `operation ${identity}`);
238
307
  const answer = operation.output === null
239
308
  ? "unknown"
240
- : (streamed(operation.output, scope) ?? typeOf(operation.output, scope, 0, false));
309
+ : (streamed(operation.output, answering) ??
310
+ typeOf(operation.output, answering, 0, false));
241
311
  const written = [
242
312
  `${operationDoc(metamodel, local, operation)}export type ${local} = ${typeOf(operation.input, sent, 0, false)};`,
243
313
  ];
@@ -248,58 +318,67 @@ export function domainFileOf(metamodel) {
248
318
  }
249
319
  return written;
250
320
  });
251
- // An event is a fact received whole: every field is there, as in a record a read answers. An
252
- // event whose class is also a model — a context's base event, when a Feature hears it — is
253
- // that model's type, narrowed to its own name: one class, one type.
321
+ // 3. The events. An event is a fact received whole: every field is there, as in a record a read
322
+ // answers. An event whose class is also a model — a context's base event, when a Feature
323
+ // hears it — is that model's type, narrowed to its own name: one class, one type.
324
+ const heard = scopeOf(metamodel);
254
325
  const members = [];
255
326
  const events = sorted(metamodel.events ?? {}).flatMap(([name, event]) => {
256
327
  const type = identifierOf(event.title);
257
328
  if (event.title in metamodel.models) {
329
+ heard.models.add(event.title);
258
330
  members.push(`(${type} & { name: ${JSON.stringify(name)} })`);
259
331
  return [];
260
332
  }
261
333
  claim(type, `event ${name}`);
262
334
  members.push(type);
263
335
  return [
264
- `${eventDoc(metamodel, name, event)}export type ${type} = ${typeOf(event.schema, scope, 0, true)};`,
336
+ `${eventDoc(metamodel, name, event)}export type ${type} = ${typeOf(event.schema, heard, 0, true)};`,
265
337
  ];
266
338
  });
267
339
  if (members.length > 0) {
268
340
  claim("DomainEvent", "the union of the domain events");
269
341
  events.push(`${docOf([`Every domain event of «${aliasOf(metamodel)}» in the contract: a \`switch\` on \`name\` tells which.`], "")}export type DomainEvent =\n${members.map((one) => ` | ${one}`).join("\n")};`);
270
342
  }
343
+ // What a caller sends of a model, and the models those carry, until none is new.
271
344
  const inputs = new Map();
272
- for (let pending = [...scope.inputs]; pending.length > 0;) {
345
+ for (let pending = [...answering.inputs]; pending.length > 0;) {
273
346
  for (const name of pending) {
274
347
  const schema = metamodel.models[name];
275
348
  inputs.set(name, `${docOf([`What a caller sends of a \`${name}\`: what the contract requires; the server fills the rest.`], "")}export type ${identifierOf(name)}Input = ${typeOf(schema, sent, 0, false)};`);
276
349
  }
277
- pending = [...scope.inputs].filter((name) => !inputs.has(name));
350
+ pending = [...answering.inputs].filter((name) => !inputs.has(name));
278
351
  }
279
352
  const sentModels = [...inputs.keys()].sort().map((name) => {
280
353
  claim(`${identifierOf(name)}Input`, `what a caller sends of model ${name}`);
281
354
  return inputs.get(name);
282
355
  });
283
- const written = new Map();
284
- for (let pending = [...scope.reached]; pending.length > 0;) {
285
- for (const name of pending) {
286
- const schema = definitions[name];
287
- written.set(name, `${docOf([schema.description], "")}export type ${identifierOf(name)} = ${typeOf(schema, scope, 0, false)};`);
288
- }
289
- pending = [...scope.reached].filter((name) => !written.has(name));
290
- }
291
- const shared = [...written.keys()].sort().map((name) => {
292
- claim(identifierOf(name), `definition ${name}`);
293
- return written.get(name);
294
- });
295
- // One line per package, its names sorted.
296
- const byPackage = new Map();
297
- for (const name of [...scope.imports].sort()) {
298
- const imported = IMPORTED[name];
299
- byPackage.set(imported.from, [...(byPackage.get(imported.from) ?? []), imported.name]);
300
- }
301
- const imports = [...byPackage.keys()]
302
- .sort()
303
- .map((from) => `import type { ${byPackage.get(from).join(", ")} } from "${from}";`);
304
- return `${[headerOf("The DTOs", metamodel), ...(imports.length === 0 ? [] : [imports.join("\n")]), ...models, ...sentModels, ...shared, ...operations, ...events].join("\n\n")}\n`;
356
+ // Each shared definition in the first file that names it: models, operations, events.
357
+ const inModels = new Set(heldDefinitions.keys());
358
+ const operationDefinitions = definitionsOf(metamodel, answering, inModels);
359
+ const inCommands = new Set(operationDefinitions.keys());
360
+ const eventDefinitions = definitionsOf(metamodel, heard, new Set([...inModels, ...inCommands]));
361
+ const ownModels = claimedDefinitions(heldDefinitions, claim);
362
+ const ownOperations = claimedDefinitions(operationDefinitions, claim);
363
+ const ownEvents = claimedDefinitions(eventDefinitions, claim);
364
+ /** What a file names that `models.ts` writes: models as records, and their definitions. */
365
+ const ofModels = (scope) => [
366
+ ...scope.models,
367
+ ...[...scope.reached].filter((name) => inModels.has(name)),
368
+ ];
369
+ const files = {
370
+ "models.ts": fileOf(headerOf("The entities and value objects", metamodel), importsOf(held, []), [...models, ...ownModels]),
371
+ "commands.ts": fileOf(headerOf("The Commands and Responses", metamodel), importsOf(answering, [["models", ofModels(answering)]]), [...sentModels, ...ownOperations, ...operations]),
372
+ };
373
+ if (events.length > 0)
374
+ files["events.ts"] = fileOf(headerOf("The domain events", metamodel), importsOf(heard, [
375
+ ["models", ofModels(heard)],
376
+ ["commands", [...heard.reached].filter((name) => inCommands.has(name))],
377
+ ]), [...ownEvents, ...events]);
378
+ files["index.ts"] = fileOf(headerOf("The domain", metamodel), [], [
379
+ Object.keys(files)
380
+ .map((file) => `export type * from "${siblingOf(file.replace(/.ts$/, ""))}";`)
381
+ .join("\n"),
382
+ ]);
383
+ return files;
305
384
  }
@@ -0,0 +1,23 @@
1
+ import type { Metamodel } from "../domain/metamodel.js";
2
+ import type { GenerateOptions } from "./rest.js";
3
+ /**
4
+ * Every file `sincpro-client generate` writes for a bounded context, by its path from the
5
+ * context's folder — each in the layer it belongs to, beside the application's own code of that
6
+ * layer:
7
+ *
8
+ * domain/generated/models.ts entities and value objects
9
+ * domain/generated/commands.ts Commands and Responses
10
+ * domain/generated/events.ts domain events (a contract exported with them)
11
+ * domain/generated/index.ts the three, re-exported
12
+ * adapters/generated/client.ts every operation, over any wire
13
+ * adapters/generated/entities.ts what screens list, read and edit
14
+ *
15
+ * Context: the backend keeps these apart — the domain's words, the application layer's DTOs, the
16
+ * facts, the adapters to another system —, and so does an application laid out like it. Written
17
+ * side by side, the application had to move them itself. A bare metamodel (`export_metamodel`,
18
+ * no bindings) is only a domain: no adapter is written.
19
+ *
20
+ * generatedFilesOf(project, { domain: "project", base: "/v1" })
21
+ * -> { "domain/generated/models.ts": "…", …, "adapters/generated/entities.ts": "…" }
22
+ */
23
+ export declare function generatedFilesOf(metamodel: Metamodel, options?: GenerateOptions): Record<string, string>;
@@ -0,0 +1,34 @@
1
+ import { GENERATED_ADAPTERS, GENERATED_DOMAIN, } from "../domain/names.js";
2
+ import { clientFileOf } from "./client.js";
3
+ import { domainFilesOf } from "./domain.js";
4
+ import { entitiesFileOf } from "./entities.js";
5
+ /**
6
+ * Every file `sincpro-client generate` writes for a bounded context, by its path from the
7
+ * context's folder — each in the layer it belongs to, beside the application's own code of that
8
+ * layer:
9
+ *
10
+ * domain/generated/models.ts entities and value objects
11
+ * domain/generated/commands.ts Commands and Responses
12
+ * domain/generated/events.ts domain events (a contract exported with them)
13
+ * domain/generated/index.ts the three, re-exported
14
+ * adapters/generated/client.ts every operation, over any wire
15
+ * adapters/generated/entities.ts what screens list, read and edit
16
+ *
17
+ * Context: the backend keeps these apart — the domain's words, the application layer's DTOs, the
18
+ * facts, the adapters to another system —, and so does an application laid out like it. Written
19
+ * side by side, the application had to move them itself. A bare metamodel (`export_metamodel`,
20
+ * no bindings) is only a domain: no adapter is written.
21
+ *
22
+ * generatedFilesOf(project, { domain: "project", base: "/v1" })
23
+ * -> { "domain/generated/models.ts": "…", …, "adapters/generated/entities.ts": "…" }
24
+ */
25
+ export function generatedFilesOf(metamodel, options = {}) {
26
+ const files = {};
27
+ for (const [name, source] of Object.entries(domainFilesOf(metamodel)))
28
+ files[`${GENERATED_DOMAIN}/${name}`] = source;
29
+ if (metamodel.bindings !== undefined) {
30
+ files[`${GENERATED_ADAPTERS}/client.ts`] = clientFileOf(metamodel, options);
31
+ files[`${GENERATED_ADAPTERS}/entities.ts`] = entitiesFileOf(metamodel, options);
32
+ }
33
+ return files;
34
+ }
@@ -4,7 +4,8 @@ import type { Metamodel } from "../domain/metamodel.js";
4
4
  * application's from then on, laid out as the backend's (`sincpro_mcp_odoo/domains/helpdesk`):
5
5
  *
6
6
  * domains/project/
7
- * generated/ `sincpro-client generate` — regenerated, never edited
7
+ * domain/generated/ `sincpro-client generate` — regenerated, never edited:
8
+ * adapters/generated/ its types, and its client and entities
8
9
  * infrastructure/dependencies.ts what its services count on, and who supplies it
9
10
  * infrastructure/framework.ts its Feature and ApplicationService — every dependency
10
11
  * typed on `this` — and `projectBoundedContext`
@@ -16,7 +17,7 @@ import type { Metamodel } from "../domain/metamodel.js";
16
17
  * imports it to register itself (`@projectBoundedContext.feature(Command)`), and ES modules run
17
18
  * their imports first, so `index.ts` importing the services could not also define it. It is the
18
19
  * application's to change: the CLI writes a file only when it is not there, and never touches one
19
- * that is — unlike `generated/`, which is written whole every time.
20
+ * that is — unlike the `generated/` folders, which are written whole every time.
20
21
  */
21
22
  export type ScaffoldOptions = {
22
23
  /**
@@ -1,4 +1,4 @@
1
- import { aliasOf, FRAMEWORK } from "../domain/names.js";
1
+ import { aliasOf, FRAMEWORK, GENERATED_ADAPTERS, GENERATED_DOMAIN, } from "../domain/names.js";
2
2
  /** `sales-orders` → `SalesOrders`. */
3
3
  function pascalOf(alias) {
4
4
  const joined = alias
@@ -29,7 +29,9 @@ export function scaffoldFilesOf(metamodel, options = {}) {
29
29
  "",
30
30
  `import type { OperationTransport } from "${FRAMEWORK}";`,
31
31
  `import type { BoundedContext } from "${at(FRAMEWORK, "core")}";`,
32
- ...(client ? ["", `import { clientOf } from "${at("..", "generated", "client")}";`] : []),
32
+ ...(client
33
+ ? ["", `import { clientOf } from "${at("..", GENERATED_ADAPTERS, "client")}";`]
34
+ : []),
33
35
  "",
34
36
  `/** What every service of «${alias}» finds on \`this\`${client ? ": `this.client`, the service's operations" : ""}. */`,
35
37
  `export interface ${Dependencies} {`,
@@ -76,7 +78,7 @@ export function scaffoldFilesOf(metamodel, options = {}) {
76
78
  "// with use cases of its own in a folder inside it). Each registers itself with",
77
79
  `// \`@${name}.feature(CommandX)\` — or a list: \`@${name}.feature([CommandX, EventY])\` — and is`,
78
80
  "// imported here, so it is registered before anyone executes. A generated DTO is a remote",
79
- `// contract (a type): \`import type * as remote from "${at("..", "generated", "domain")}"\`.`,
81
+ `// contract (a type): \`import type * as remote from "${at("..", GENERATED_DOMAIN)}"\`.`,
80
82
  "export {};",
81
83
  "",
82
84
  ].join("\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",