@sincpro/client-framework 1.11.0 → 2.0.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 +37 -2
- package/dist/client/adapters/memory.d.ts +51 -1
- package/dist/client/adapters/memory.js +138 -2
- package/dist/client/adapters/rest-operations.d.ts +8 -6
- package/dist/client/adapters/rest-operations.js +12 -19
- package/dist/client/adapters/rest.d.ts +30 -0
- package/dist/client/adapters/rest.js +51 -3
- package/dist/client/domain/entity.d.ts +75 -14
- package/dist/client/domain/entity.js +29 -2
- package/dist/client/domain/transport.d.ts +5 -1
- package/dist/client/index.d.ts +2 -2
- package/dist/client/index.js +2 -2
- package/dist/codegen/services/client.d.ts +1 -0
- package/dist/codegen/services/client.js +32 -2
- package/dist/codegen/services/domain.js +18 -4
- package/dist/codegen/services/entities.d.ts +4 -3
- package/dist/codegen/services/entities.js +7 -4
- package/dist/common/entity-ref.d.ts +49 -0
- package/dist/common/entity-ref.js +55 -0
- package/dist/common/ids.d.ts +2 -1
- package/dist/common/ids.js +2 -1
- package/dist/common/index.d.ts +3 -1
- package/dist/common/index.js +3 -1
- package/dist/model/domain/meta.d.ts +9 -0
- package/dist/model/domain/meta.js +12 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -666,10 +666,11 @@ await forge.sendIssue({ issue_id: "acme-3", message: "hola" }); // ResponseSendI
|
|
|
666
666
|
| Piece | What it does |
|
|
667
667
|
| --------------------------------- | ------------------------------------------------------------------------------------- |
|
|
668
668
|
| `OperationTransport` port | `call(operation, input, options)`: an operation by who it is, over any wire |
|
|
669
|
-
| `restOperations(transport)` | over REST: the path from the input's
|
|
669
|
+
| `restOperations(transport)` | over REST: the path from the input, a Query's and a DELETE's query, a Command's body |
|
|
670
670
|
| `jsonRpcOperations({ endpoint })` | over JSON-RPC 2.0: one `POST`, the operation's method, its input as named params |
|
|
671
671
|
| `restTransport({ base })` | REST over `fetch`: `Idempotency-Key`, the server's `Problem`, model versions, Parquet |
|
|
672
672
|
| `memoryTransport(tables)` | the same REST contract in memory, copying by the wire's rules — for tests and demos |
|
|
673
|
+
| `assignableValues(route, values)` | an `Edit`'s values as the server reads them, for a memory `handle` |
|
|
673
674
|
| `entity(key, routes)` | a model's routes and Commands, typed — what a generated `entities.ts` declares |
|
|
674
675
|
| `retryKeys()` | one `Idempotency-Key` per gesture, kept while a retry may repeat it |
|
|
675
676
|
| `guardedTransport(t, breaker)` | every call of a transport through a circuit breaker |
|
|
@@ -682,6 +683,30 @@ its trace (`traceparent`), its context (`sincpro-context`) and its signal — as
|
|
|
682
683
|
as metadata where a platform's adapter puts them. `screensTransport` and `entity()` stay on the
|
|
683
684
|
REST `Transport`: they are how a screen reads pages of an entity, with its model and its drafts.
|
|
684
685
|
|
|
686
|
+
An edit — the backend's `Edit`, role `edit` — creates a record under the key its caller names.
|
|
687
|
+
Its generated method mints one when the input names none (`newEntityId`, a UUID v7, as the
|
|
688
|
+
server would), so `forge.editProject({ values, action: "save" })` creates a project over any
|
|
689
|
+
wire, REST's `PUT /projects/{id}/edit` included. A screen that keeps a draft of a new record
|
|
690
|
+
names its key once, so every save of the draft reaches the same record. A Command that answers
|
|
691
|
+
nothing — a `DELETE`'s 204 — resolves `null`, never `undefined`, over REST and in memory alike.
|
|
692
|
+
|
|
693
|
+
A `DELETE` — the backend's `Delete`, role `delete`, an entity's `delete` route — is read from its
|
|
694
|
+
URL, never from a body. `restTransport` sends its fields in the query string, as the server decodes
|
|
695
|
+
them (plain values as text, anything else as JSON): `DELETE /projects/acme?dry_run=true` answers
|
|
696
|
+
the `Preview` of what would go, and `origin_version` refuses a delete of a record that moved on.
|
|
697
|
+
Sent in a body they are dropped, and a rehearsal would run the real delete.
|
|
698
|
+
|
|
699
|
+
A trash — the backend's `Archive`, `Restore` and `Purge`, roles `archive`, `restore` and `purge` —
|
|
700
|
+
is three more routes of an entity: `archive` and `restore` by the record's key, `purge` over the
|
|
701
|
+
whole collection (`older_than`, a duration as the contract writes it: `"P30D"`). Each answers
|
|
702
|
+
nothing — `null` — or, with `dry_run: true`, the `Preview` of what it would do; a purge's says how
|
|
703
|
+
many would go (`data: { count }`). The trash itself is the entity's list asked for what is
|
|
704
|
+
archived (`archived_at` not null), which every other reading leaves out.
|
|
705
|
+
|
|
706
|
+
Which of the ways a screen reaches the backend fits a call — an entity's screens, the generated
|
|
707
|
+
client over the screens transport, or a Command and its Feature — is in
|
|
708
|
+
[docs/WEB.md](docs/WEB.md#which-way-a-screen-reaches-the-backend).
|
|
709
|
+
|
|
685
710
|
A wrapper over a screens transport — a cache, a guard — keeps its mark, so the screens are not made
|
|
686
711
|
twice: `guardedTransport` does it, and a platform's own wrapper calls `markedAs(wrapper, inner)`.
|
|
687
712
|
One span then answers each screen read, whether the wrapper answered it from its own memory or not.
|
|
@@ -754,7 +779,7 @@ each file in the layer it belongs to, under the bounded context's folder (`--out
|
|
|
754
779
|
| `domain/generated/events.ts` | the domain events and `DomainEvent`, their union — when the contract carries them |
|
|
755
780
|
| `domain/generated/index.ts` | the three, re-exported: `import type * as remote from "../domain/generated"` |
|
|
756
781
|
| `adapters/generated/client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
|
|
757
|
-
| `adapters/generated/entities.ts` | each entity's list, record, edit, export, Commands and history, for screens
|
|
782
|
+
| `adapters/generated/entities.ts` | each entity's list, record, edit, delete, trash, export, Commands and history, for screens |
|
|
758
783
|
|
|
759
784
|
The backend keeps them apart — the domain's words, the application layer's DTOs, the facts, the
|
|
760
785
|
adapters to another system —, and so does the application: each beside its own code of that layer.
|
|
@@ -834,6 +859,7 @@ needs them.
|
|
|
834
859
|
| Day | `"2026-10-02"`, never an instant | `isDay`, `dayOf` |
|
|
835
860
|
| Instant | ISO text | `wallTimeOf`, `instantOf`, `timeZoneOf` |
|
|
836
861
|
| ID | UUID v7 as 32 hex | `newEntityId`, `isEntityId`, `momentOf` |
|
|
862
|
+
| Entity ref | `"billing.Invoice:0192…"` | `EntityRef`, `parseEntityRef`, `entityRefOf` |
|
|
837
863
|
| Bytes | `{ "$bytes": "<base64>" }` | `valuesOf`, `readValues` |
|
|
838
864
|
| Collection | items, count and cursor | `collectionOf`, `isPartial`, `relatedCriteria` |
|
|
839
865
|
| Export | Parquet, Arrow or JSON Lines | `downloadRoute`, `exportRoute` |
|
|
@@ -843,6 +869,15 @@ never a `Date`. `valuesOf`/`pack` write; `readValues` reads tagged values back;
|
|
|
843
869
|
use a reader given explicitly. Cycles, functions and non-finite numbers are refused. How a value
|
|
844
870
|
is shown, typed or stored is the platform's.
|
|
845
871
|
|
|
872
|
+
An entity ref — the backend's `EntityRef` — names a record of any bounded context by one text,
|
|
873
|
+
`bounded_context.Entity:key`: what a payment's metadata, a webhook or a notification carries to
|
|
874
|
+
say which record it is about. It is a text on the wire, so it is a text here, typed by its form:
|
|
875
|
+
the generator types a field published as `format: "entity-ref"` as `EntityRef`, `parseEntityRef`
|
|
876
|
+
reads one (refusing what the backend refuses), `isEntityRef` checks a string read from outside,
|
|
877
|
+
and `entityRefOf({ boundedContext, entity, key })` writes one. Resolving it is the backend's
|
|
878
|
+
`Resolve` — `GET …/refs?refs=[…]` — a generated operation of whichever bounded context publishes
|
|
879
|
+
it, never a route of this package.
|
|
880
|
+
|
|
846
881
|
## An application's layout
|
|
847
882
|
|
|
848
883
|
An application is laid out as a sincpro_framework service is — the entrypoints call the bus, the
|
|
@@ -29,7 +29,13 @@ export type MemoryOptions = {
|
|
|
29
29
|
/**
|
|
30
30
|
* Answer a Command — a write, an action, a preview — the way the service would. It may
|
|
31
31
|
* change the tables' rows (they are read on every request) and throw a `TransportError` to
|
|
32
|
-
* refuse. Without it, every Command is a 404.
|
|
32
|
+
* refuse. Without it, every Command is a 404. What it returns is the answer; nothing — a
|
|
33
|
+
* Command that answers nothing — is `null`, as REST's 204. An `Edit`'s `values` are read as the
|
|
34
|
+
* server reads them with `assignableValues`.
|
|
35
|
+
*
|
|
36
|
+
* Its `body` is the Command's fields whatever the method — a `DELETE`'s too, which REST sends
|
|
37
|
+
* in its query string (`restTransport`): this stands for the service, which reads a DTO, not a
|
|
38
|
+
* URL.
|
|
33
39
|
*/
|
|
34
40
|
handle?: (method: Method, route: string, body: unknown) => unknown;
|
|
35
41
|
/** Answer a read that is neither a page nor a record (`GET /me`), its route with its query.
|
|
@@ -48,3 +54,47 @@ export type MemoryOptions = {
|
|
|
48
54
|
changes?: ChangeFeed;
|
|
49
55
|
};
|
|
50
56
|
export declare function memoryTransport(tables: Readonly<Record<string, MemoryTable>>, options?: MemoryOptions): Transport;
|
|
57
|
+
export type AssignableOptions = {
|
|
58
|
+
/** The key of the record the edit names — its `Edit`'s `id`: an identity in the values other
|
|
59
|
+
* than it is refused. */
|
|
60
|
+
id?: string;
|
|
61
|
+
/** The record's definition: a name it does not declare is refused, and its `identity` is the
|
|
62
|
+
* field checked against `id`. */
|
|
63
|
+
meta?: Meta;
|
|
64
|
+
/** What the framework writes on the record — left out at every level, a nested record keeping
|
|
65
|
+
* its `id`. By default `Entity`'s (`id`, `version`, `created_at`, `updated_at`) and its
|
|
66
|
+
* mixins' (`created_by`, `updated_by`, `archived_at`); a project's own framework base names
|
|
67
|
+
* its own. */
|
|
68
|
+
framework?: readonly string[];
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* The values of an `Edit` its record may be assigned, read as sincpro_framework 3.37 reads them
|
|
72
|
+
* (`assignable`, `form_values`, `apply_values`) — for a `memoryTransport`'s `handle` that stands
|
|
73
|
+
* for a service's `Edit`:
|
|
74
|
+
*
|
|
75
|
+
* handle(method, route, body) {
|
|
76
|
+
* const sent = body as { id: string; values?: AnyRecord; action?: string };
|
|
77
|
+
* const values = assignableValues(route, sent.values, { id: sent.id, meta: invoiceMeta });
|
|
78
|
+
* …
|
|
79
|
+
* }
|
|
80
|
+
*
|
|
81
|
+
* 1. The values are an object of fields (none is `{}`); anything else is refused.
|
|
82
|
+
* 2. An identity other than the record's (`id`) is refused: it would put one record's values on
|
|
83
|
+
* another.
|
|
84
|
+
* 3. What the framework writes is the record's echo — a form reads a record whole and sends it
|
|
85
|
+
* back whole —: left out, never assigned and never refused. In a record a list holds (a line),
|
|
86
|
+
* all of it but its `id`, the way a form names the line it edits.
|
|
87
|
+
* 4. A name the definition does not declare is refused.
|
|
88
|
+
* 5. A list of records goes whole: the collection a reading answered is read as its records, each
|
|
89
|
+
* as in 3; a page of it is refused (`heldValue`). A record held as one object (a many2one
|
|
90
|
+
* sent expanded) is passed as it came: which fields of it are the record's is the service's.
|
|
91
|
+
* Final: the values to assign. Each refusal is a `TransportError` 422 — `invalid`,
|
|
92
|
+
* `INVALID_VALUE` — pointing at the value (`#/values/lines/l1/parts`): a nested record by its
|
|
93
|
+
* `id`, by its position when it has none, as the server's `InvalidValue` points.
|
|
94
|
+
*
|
|
95
|
+
* Context: opt-in, and generic. A fake server that took whatever came hid that a form sent the
|
|
96
|
+
* record whole — the framework's echo, a relation read as a page — while the real `Edit` refused
|
|
97
|
+
* it: stories passed, and a stored record could not be edited against the real backend. A `handle`
|
|
98
|
+
* that does not call it reads `values` as it likes.
|
|
99
|
+
*/
|
|
100
|
+
export declare function assignableValues(route: string, values: unknown, options?: AssignableOptions): AnyRecord;
|
|
@@ -105,8 +105,9 @@ export function memoryTransport(tables, options = {}) {
|
|
|
105
105
|
extensions: {},
|
|
106
106
|
detail: `Nothing answers ${method} ${route}.`,
|
|
107
107
|
});
|
|
108
|
-
// A deep copy: what the caller sent is not what the server keeps.
|
|
109
|
-
|
|
108
|
+
// A deep copy: what the caller sent is not what the server keeps. A Command that
|
|
109
|
+
// answers nothing is `null`, as REST's 204 is — never `undefined`.
|
|
110
|
+
const answer = (await options.handle(method, route, copyOf(body))) ?? null;
|
|
110
111
|
if (key !== undefined)
|
|
111
112
|
answered.set(key, copyOf(answer));
|
|
112
113
|
return answer;
|
|
@@ -123,3 +124,138 @@ export function memoryTransport(tables, options = {}) {
|
|
|
123
124
|
}),
|
|
124
125
|
});
|
|
125
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* What sincpro_framework writes on a record — `Entity`'s fields and its mixins' (`AuditedMixin`'s
|
|
129
|
+
* `created_by` / `updated_by`, `ArchivableMixin`'s `archived_at`): in a form's values only as the
|
|
130
|
+
* record's echo. A record without a mixin never holds its fields, so a form never sends them.
|
|
131
|
+
*/
|
|
132
|
+
const FRAMEWORK_FIELDS = [
|
|
133
|
+
"id",
|
|
134
|
+
"version",
|
|
135
|
+
"created_at",
|
|
136
|
+
"updated_at",
|
|
137
|
+
"created_by",
|
|
138
|
+
"updated_by",
|
|
139
|
+
"archived_at",
|
|
140
|
+
];
|
|
141
|
+
/** A refusal of a value, as the server's `InvalidValue` answers it: a 422 pointing at it. */
|
|
142
|
+
function invalidValue(route, path, detail) {
|
|
143
|
+
const pointer = ["values", ...path]
|
|
144
|
+
.map((one) => String(one).replaceAll("~", "~0").replaceAll("/", "~1"))
|
|
145
|
+
.join("/");
|
|
146
|
+
return new TransportError(route, 422, {
|
|
147
|
+
kind: "invalid",
|
|
148
|
+
reason: "INVALID_VALUE",
|
|
149
|
+
status: 422,
|
|
150
|
+
detail,
|
|
151
|
+
next_step: "fix_request",
|
|
152
|
+
retryable: false,
|
|
153
|
+
errors: [{ pointer: `#/${pointer}`, detail }],
|
|
154
|
+
extensions: {},
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function isFields(value) {
|
|
158
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
159
|
+
}
|
|
160
|
+
/** Each record of a list as a form sends it — its echo left out, its `id` kept —, named by its
|
|
161
|
+
* `id` where a refusal inside it points, by its position when it has none. */
|
|
162
|
+
function recordsOf(route, records, path, framework) {
|
|
163
|
+
return records.map((one, index) => {
|
|
164
|
+
if (!isFields(one))
|
|
165
|
+
return one;
|
|
166
|
+
const named = one["id"];
|
|
167
|
+
const at = named === undefined || named === null || named === "" ? index : String(named);
|
|
168
|
+
return formValues(route, one, [...path, at], framework, true);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* A list of records as a form sends it — sincpro_framework's `_sent_whole`: the list, or the
|
|
173
|
+
* collection a reading answered (`{items, count, cursor}`) sent back whole, as its records. A page
|
|
174
|
+
* of it — a cursor, or a count that is only a floor — is refused: written back, it would remove
|
|
175
|
+
* every record it did not bring. An exact count above what it holds is a whole collection a form
|
|
176
|
+
* edited (a record removed), not a page — the server's rule, not `isPartial`'s.
|
|
177
|
+
*/
|
|
178
|
+
function heldValue(route, value, path, framework) {
|
|
179
|
+
if (Array.isArray(value))
|
|
180
|
+
return recordsOf(route, value, path, framework);
|
|
181
|
+
if (!isFields(value) || !("items" in value))
|
|
182
|
+
return value;
|
|
183
|
+
const name = String(path[path.length - 1]);
|
|
184
|
+
const items = value["items"];
|
|
185
|
+
if (!Array.isArray(items))
|
|
186
|
+
throw invalidValue(route, path, `${name} holds records: send them as a list`);
|
|
187
|
+
const count = isFields(value["count"]) ? value["count"] : {};
|
|
188
|
+
const floor = count["exact"] === false;
|
|
189
|
+
if ((value["cursor"] !== undefined && value["cursor"] !== null) || floor) {
|
|
190
|
+
const total = typeof count["value"] === "number" ? count["value"] : items.length;
|
|
191
|
+
throw invalidValue(route, path, `${name} was sent as a page — ${items.length} of ${floor ? "at least " : ""}${total} — ` +
|
|
192
|
+
"and a page written back would remove every record it did not bring: send all of them");
|
|
193
|
+
}
|
|
194
|
+
return recordsOf(route, items, path, framework);
|
|
195
|
+
}
|
|
196
|
+
/** A record's values without what the framework writes — a nested one keeping its `id`. */
|
|
197
|
+
function formValues(route, values, path, framework, nested) {
|
|
198
|
+
const read = {};
|
|
199
|
+
for (const [name, value] of Object.entries(values)) {
|
|
200
|
+
if (framework.has(name) && !(nested && name === "id"))
|
|
201
|
+
continue;
|
|
202
|
+
read[name] = heldValue(route, value, [...path, name], framework);
|
|
203
|
+
}
|
|
204
|
+
return read;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* The values of an `Edit` its record may be assigned, read as sincpro_framework 3.37 reads them
|
|
208
|
+
* (`assignable`, `form_values`, `apply_values`) — for a `memoryTransport`'s `handle` that stands
|
|
209
|
+
* for a service's `Edit`:
|
|
210
|
+
*
|
|
211
|
+
* handle(method, route, body) {
|
|
212
|
+
* const sent = body as { id: string; values?: AnyRecord; action?: string };
|
|
213
|
+
* const values = assignableValues(route, sent.values, { id: sent.id, meta: invoiceMeta });
|
|
214
|
+
* …
|
|
215
|
+
* }
|
|
216
|
+
*
|
|
217
|
+
* 1. The values are an object of fields (none is `{}`); anything else is refused.
|
|
218
|
+
* 2. An identity other than the record's (`id`) is refused: it would put one record's values on
|
|
219
|
+
* another.
|
|
220
|
+
* 3. What the framework writes is the record's echo — a form reads a record whole and sends it
|
|
221
|
+
* back whole —: left out, never assigned and never refused. In a record a list holds (a line),
|
|
222
|
+
* all of it but its `id`, the way a form names the line it edits.
|
|
223
|
+
* 4. A name the definition does not declare is refused.
|
|
224
|
+
* 5. A list of records goes whole: the collection a reading answered is read as its records, each
|
|
225
|
+
* as in 3; a page of it is refused (`heldValue`). A record held as one object (a many2one
|
|
226
|
+
* sent expanded) is passed as it came: which fields of it are the record's is the service's.
|
|
227
|
+
* Final: the values to assign. Each refusal is a `TransportError` 422 — `invalid`,
|
|
228
|
+
* `INVALID_VALUE` — pointing at the value (`#/values/lines/l1/parts`): a nested record by its
|
|
229
|
+
* `id`, by its position when it has none, as the server's `InvalidValue` points.
|
|
230
|
+
*
|
|
231
|
+
* Context: opt-in, and generic. A fake server that took whatever came hid that a form sent the
|
|
232
|
+
* record whole — the framework's echo, a relation read as a page — while the real `Edit` refused
|
|
233
|
+
* it: stories passed, and a stored record could not be edited against the real backend. A `handle`
|
|
234
|
+
* that does not call it reads `values` as it likes.
|
|
235
|
+
*/
|
|
236
|
+
export function assignableValues(route, values, options = {}) {
|
|
237
|
+
if (values === undefined || values === null)
|
|
238
|
+
return {};
|
|
239
|
+
if (!isFields(values))
|
|
240
|
+
throw invalidValue(route, [], "values is the record's fields, as an object");
|
|
241
|
+
const { meta, id } = options;
|
|
242
|
+
const aggregate = meta?.aggregate ?? "The record";
|
|
243
|
+
const identity = meta?.identity ?? "id";
|
|
244
|
+
const echoed = values[identity];
|
|
245
|
+
// Only where the record is found by its identity: a key of its own is another field.
|
|
246
|
+
const byIdentity = meta === undefined || (meta.get_id || meta.identity) === identity;
|
|
247
|
+
if (id !== undefined &&
|
|
248
|
+
byIdentity &&
|
|
249
|
+
echoed !== undefined &&
|
|
250
|
+
echoed !== null &&
|
|
251
|
+
String(echoed) !== id)
|
|
252
|
+
throw invalidValue(route, [identity], `${aggregate} ${id} was sent the values of ${aggregate} ${String(echoed)}`);
|
|
253
|
+
const framework = new Set(options.framework ?? FRAMEWORK_FIELDS);
|
|
254
|
+
if (meta !== undefined) {
|
|
255
|
+
const unknown = Object.keys(values).filter((name) => !framework.has(name) && !(name in meta.fields));
|
|
256
|
+
const [first] = unknown;
|
|
257
|
+
if (first !== undefined)
|
|
258
|
+
throw invalidValue(route, [first], `${aggregate} has no field ${unknown.join(", ")} to assign`);
|
|
259
|
+
}
|
|
260
|
+
return formValues(route, values, [], framework, false);
|
|
261
|
+
}
|
|
@@ -9,11 +9,13 @@ import { type Transport } from "../domain/transport.js";
|
|
|
9
9
|
*
|
|
10
10
|
* 1. The operation's REST binding (`operation.rest`); none: `OperationNotPublished`.
|
|
11
11
|
* 2. Each `{field}` of its path taken from the input.
|
|
12
|
-
* 3. A `GET` — a Query — sends every other field as its query
|
|
13
|
-
*
|
|
14
|
-
* an export) is downloaded.
|
|
15
|
-
* 4. Anything else — a Command —
|
|
16
|
-
* `
|
|
17
|
-
*
|
|
12
|
+
* 3. A `GET` — a Query — sends every other field as its query, as the wire reads it back
|
|
13
|
+
* (`queryOf`: plain values as text, `criteria` and any other value as JSON), and reads the
|
|
14
|
+
* answer as it came; one that answers bytes (`streamed`, an export) is downloaded.
|
|
15
|
+
* 4. Anything else — a Command — is sent with the gesture's `Idempotency-Key`: the input whole as
|
|
16
|
+
* its body; a `DELETE`, read from its URL as a `GET` is, only the fields its path did not take
|
|
17
|
+
* — the REST transport writes them as its query (`restTransport`), and a key is not said twice.
|
|
18
|
+
* Final: the operation's answer, as the contract describes it — `null` for one that answers
|
|
19
|
+
* nothing (a `DELETE`'s 204).
|
|
18
20
|
*/
|
|
19
21
|
export declare function restOperations(transport: Transport): OperationTransport;
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
+
import { queryOf, withQuery } from "./rest.js";
|
|
1
2
|
import { OperationNotPublished, } from "../domain/operation.js";
|
|
2
3
|
import { downloadRoute, readRoute, } from "../domain/transport.js";
|
|
3
4
|
import { bindableOperations } from "../services/propagation.js";
|
|
4
5
|
const PATH_KEY = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
5
|
-
/** What a value is in a query string: text as it is, anything else as JSON (`criteria`). */
|
|
6
|
-
function queryValue(value) {
|
|
7
|
-
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8
|
-
}
|
|
9
6
|
/** The path with each `{field}` taken from the input, and the input's fields it did not take. */
|
|
10
7
|
function placed(operation, path, input) {
|
|
11
8
|
const rest = { ...input };
|
|
@@ -18,13 +15,6 @@ function placed(operation, path, input) {
|
|
|
18
15
|
});
|
|
19
16
|
return { route, rest };
|
|
20
17
|
}
|
|
21
|
-
/** The route with every other field of a GET as its query. */
|
|
22
|
-
function withQuery(route, fields) {
|
|
23
|
-
const query = new URLSearchParams(Object.entries(fields)
|
|
24
|
-
.filter(([, value]) => value !== undefined && value !== null && value !== "")
|
|
25
|
-
.map(([name, value]) => [name, queryValue(value)])).toString();
|
|
26
|
-
return query === "" ? route : `${route}${route.includes("?") ? "&" : "?"}${query}`;
|
|
27
|
-
}
|
|
28
18
|
/**
|
|
29
19
|
* Operations over REST, as sincpro_framework's REST gateway publishes them — on a `Transport`
|
|
30
20
|
* (`restTransport`, `memoryTransport`, a platform's):
|
|
@@ -34,12 +24,14 @@ function withQuery(route, fields) {
|
|
|
34
24
|
*
|
|
35
25
|
* 1. The operation's REST binding (`operation.rest`); none: `OperationNotPublished`.
|
|
36
26
|
* 2. Each `{field}` of its path taken from the input.
|
|
37
|
-
* 3. A `GET` — a Query — sends every other field as its query
|
|
38
|
-
*
|
|
39
|
-
* an export) is downloaded.
|
|
40
|
-
* 4. Anything else — a Command —
|
|
41
|
-
* `
|
|
42
|
-
*
|
|
27
|
+
* 3. A `GET` — a Query — sends every other field as its query, as the wire reads it back
|
|
28
|
+
* (`queryOf`: plain values as text, `criteria` and any other value as JSON), and reads the
|
|
29
|
+
* answer as it came; one that answers bytes (`streamed`, an export) is downloaded.
|
|
30
|
+
* 4. Anything else — a Command — is sent with the gesture's `Idempotency-Key`: the input whole as
|
|
31
|
+
* its body; a `DELETE`, read from its URL as a `GET` is, only the fields its path did not take
|
|
32
|
+
* — the REST transport writes them as its query (`restTransport`), and a key is not said twice.
|
|
33
|
+
* Final: the operation's answer, as the contract describes it — `null` for one that answers
|
|
34
|
+
* nothing (a `DELETE`'s 204).
|
|
43
35
|
*/
|
|
44
36
|
export function restOperations(transport) {
|
|
45
37
|
return bindableOperations({
|
|
@@ -52,12 +44,13 @@ export function restOperations(transport) {
|
|
|
52
44
|
try {
|
|
53
45
|
const { route, rest: others } = placed(operation, rest.path, fields);
|
|
54
46
|
if (rest.method === "GET") {
|
|
55
|
-
const asked = withQuery(route, others);
|
|
47
|
+
const asked = withQuery(route, queryOf(others));
|
|
56
48
|
return operation.streamed
|
|
57
49
|
? downloadRoute(transport, asked, signal, call)
|
|
58
50
|
: readRoute(transport, asked, signal, call);
|
|
59
51
|
}
|
|
60
|
-
|
|
52
|
+
const sent = rest.method === "DELETE" ? others : fields;
|
|
53
|
+
return transport.send(rest.method, route, sent, signal, call);
|
|
61
54
|
}
|
|
62
55
|
catch (error) {
|
|
63
56
|
return Promise.reject(error);
|
|
@@ -10,6 +10,19 @@ import { type Criteria } from "@sincpro/criteria";
|
|
|
10
10
|
* one record (`one()`), a write (`send()`, with its `Idempotency-Key`), and its refusals as a
|
|
11
11
|
* `TransportError`, the one error every screen explains.
|
|
12
12
|
*
|
|
13
|
+
* A write's fields travel where the wire reads them. sincpro_framework reads a `DELETE`'s DTO
|
|
14
|
+
* from its URL, as a `GET`'s (`READ_FROM_URL`), and never its body: a field sent there is dropped
|
|
15
|
+
* — or refused with a 422 (`out_of_place`) where the server checks it. So a `DELETE` sends its
|
|
16
|
+
* fields as its query string (`queryOf`) and no body; every other method sends them as a JSON
|
|
17
|
+
* body. Sent in a body, `dry_run` is lost and a rehearsal would run the real delete, and so is
|
|
18
|
+
* `origin_version`, so a stale delete would go through.
|
|
19
|
+
*
|
|
20
|
+
* The fields reach `send` as its `body` whatever the method — the change feed reads `dry_run`
|
|
21
|
+
* there — and `send` gets the path already filled, so leaving out a key the path took is the
|
|
22
|
+
* caller's, who knows the template: `restOperations` does, and an entity's `delete` puts its key
|
|
23
|
+
* only in the path. A key that travels in both is harmless: the wire reads a `DELETE` as
|
|
24
|
+
* `{**query, **path_params}` — the path wins — and looks for misplaced fields only in its body.
|
|
25
|
+
*
|
|
13
26
|
* The definition of each model — what a list, a form and a select are built from — is read
|
|
14
27
|
* from the bounded context's discovery document (`document`, `/openapi.json` by default), once,
|
|
15
28
|
* and read again only when an answer says another version of its model (`model_version`); the
|
|
@@ -55,5 +68,22 @@ export type VersionDrift = {
|
|
|
55
68
|
snapshot: string;
|
|
56
69
|
live: string;
|
|
57
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* The fields of a DTO as a query string, the way sincpro_framework's REST wire reads them back
|
|
73
|
+
* (`payload_from_query`): a plain value — text, a number, a boolean — as its text, which the
|
|
74
|
+
* server coerces to the field's type; anything else — a list, an object, a `Money` — as JSON,
|
|
75
|
+
* which it decodes. A value with a wire form of its own is written as that first (`valuesOf`):
|
|
76
|
+
* a `Decimal` as its text, a `Date` as its instant. A field with no value (`undefined`, `null`,
|
|
77
|
+
* `""`) is not sent, and the DTO's default stands — as a filter left blank.
|
|
78
|
+
*
|
|
79
|
+
* queryOf({ dry_run: true, origin_version: 3, tags: ["a"] })
|
|
80
|
+
* -> "dry_run=true&origin_version=3&tags=%5B%22a%22%5D"
|
|
81
|
+
*
|
|
82
|
+
* Context: the client does not know each field's schema, so `null` cannot be told apart: as
|
|
83
|
+
* text it would be the word «null» for a plain field. Left out, the field takes its default.
|
|
84
|
+
*/
|
|
85
|
+
export declare function queryOf(fields: Readonly<Record<string, unknown>>): string;
|
|
86
|
+
/** `route` with `query` added to the query it may already carry. */
|
|
87
|
+
export declare function withQuery(route: string, query: string): string;
|
|
58
88
|
export declare function urlOf<T>(base: string, route: string, criteria?: Criteria<T>): string;
|
|
59
89
|
export declare function restTransport(options?: RestOptions): Transport;
|
|
@@ -2,6 +2,7 @@ import { TransportError, } from "../domain/transport.js";
|
|
|
2
2
|
import { announced, processChanges } from "../services/changes.js";
|
|
3
3
|
import { definitionOf, modelAt, } from "../services/discovery.js";
|
|
4
4
|
import { bindableTransport } from "../services/propagation.js";
|
|
5
|
+
import { valuesOf } from "../../common/serialization.js";
|
|
5
6
|
import { readProblem } from "@sincpro/criteria";
|
|
6
7
|
import { RestError, restSource } from "@sincpro/criteria/rest";
|
|
7
8
|
/** The keys of an answer that are not the record: what is left is the record's own field. */
|
|
@@ -25,6 +26,47 @@ function filenameOf(disposition) {
|
|
|
25
26
|
const plain = /filename\s*=\s*("([^"]*)"|[^;]+)/i.exec(said);
|
|
26
27
|
return (plain?.[2] ?? plain?.[1] ?? "").trim();
|
|
27
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* The fields of a DTO as a query string, the way sincpro_framework's REST wire reads them back
|
|
31
|
+
* (`payload_from_query`): a plain value — text, a number, a boolean — as its text, which the
|
|
32
|
+
* server coerces to the field's type; anything else — a list, an object, a `Money` — as JSON,
|
|
33
|
+
* which it decodes. A value with a wire form of its own is written as that first (`valuesOf`):
|
|
34
|
+
* a `Decimal` as its text, a `Date` as its instant. A field with no value (`undefined`, `null`,
|
|
35
|
+
* `""`) is not sent, and the DTO's default stands — as a filter left blank.
|
|
36
|
+
*
|
|
37
|
+
* queryOf({ dry_run: true, origin_version: 3, tags: ["a"] })
|
|
38
|
+
* -> "dry_run=true&origin_version=3&tags=%5B%22a%22%5D"
|
|
39
|
+
*
|
|
40
|
+
* Context: the client does not know each field's schema, so `null` cannot be told apart: as
|
|
41
|
+
* text it would be the word «null» for a plain field. Left out, the field takes its default.
|
|
42
|
+
*/
|
|
43
|
+
export function queryOf(fields) {
|
|
44
|
+
return new URLSearchParams(Object.entries(fields).flatMap(([name, value]) => {
|
|
45
|
+
const wire = value === undefined ? null : valuesOf(value);
|
|
46
|
+
if (wire === null || wire === "")
|
|
47
|
+
return [];
|
|
48
|
+
return [[name, typeof wire === "object" ? JSON.stringify(wire) : String(wire)]];
|
|
49
|
+
})).toString();
|
|
50
|
+
}
|
|
51
|
+
/** `route` with `query` added to the query it may already carry. */
|
|
52
|
+
export function withQuery(route, query) {
|
|
53
|
+
return query === "" ? route : `${route}${route.includes("?") ? "&" : "?"}${query}`;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The fields a `DELETE` carries in its URL: its body, which must be a set of fields as the wire
|
|
57
|
+
* writes it — a list or a lone value has no field to put in a query, and dropping it silently is
|
|
58
|
+
* the bug this exists to prevent.
|
|
59
|
+
*/
|
|
60
|
+
function urlFieldsOf(route, body) {
|
|
61
|
+
if (body === undefined || body === null)
|
|
62
|
+
return {};
|
|
63
|
+
const fields = valuesOf(body);
|
|
64
|
+
if (fields === null || typeof fields !== "object" || Array.isArray(fields))
|
|
65
|
+
throw new TypeError(`DELETE ${route} sends its fields in the URL: its body is an object of them, not ${Array.isArray(fields) ? "a list" : typeof fields}`);
|
|
66
|
+
return fields;
|
|
67
|
+
}
|
|
68
|
+
/** The methods of a write sincpro_framework reads from the URL alone (its `READ_FROM_URL`). */
|
|
69
|
+
const FROM_URL = new Set(["DELETE"]);
|
|
28
70
|
export function urlOf(base, route, criteria) {
|
|
29
71
|
const url = `${base}${route}`;
|
|
30
72
|
if (criteria === undefined)
|
|
@@ -114,18 +156,22 @@ export function restTransport(options = {}) {
|
|
|
114
156
|
const again = await documentRead(true);
|
|
115
157
|
return (again === null ? undefined : definitionOf(again, name))?.meta ?? known.meta;
|
|
116
158
|
}
|
|
159
|
+
/** A request and its answer: a write's body as JSON — none for one read from its URL. */
|
|
117
160
|
async function get(route, url, signal, write, call) {
|
|
161
|
+
const json = write !== undefined && !FROM_URL.has(write.method);
|
|
118
162
|
const headers = write
|
|
119
163
|
? {
|
|
120
164
|
...own(),
|
|
121
165
|
...call?.headers,
|
|
122
|
-
"Content-Type": "application/json",
|
|
166
|
+
...(json ? { "Content-Type": "application/json" } : {}),
|
|
123
167
|
...(write.key === undefined ? {} : { "Idempotency-Key": write.key }),
|
|
124
168
|
}
|
|
125
169
|
: { ...own(), ...call?.headers };
|
|
126
170
|
const response = await doFetch(url, {
|
|
127
171
|
headers,
|
|
128
|
-
...(write
|
|
172
|
+
...(write
|
|
173
|
+
? { method: write.method, ...(json ? { body: JSON.stringify(write.body) } : {}) }
|
|
174
|
+
: {}),
|
|
129
175
|
...(signal ? { signal } : {}),
|
|
130
176
|
});
|
|
131
177
|
const text = await response.text();
|
|
@@ -185,8 +231,10 @@ export function restTransport(options = {}) {
|
|
|
185
231
|
};
|
|
186
232
|
},
|
|
187
233
|
async send(method, route, body, signal, sending) {
|
|
234
|
+
// A DELETE is read from its URL: its fields go in the query, and it has no body.
|
|
235
|
+
const url = urlOf(base, FROM_URL.has(method) ? withQuery(route, queryOf(urlFieldsOf(route, body))) : route);
|
|
188
236
|
return announced(changes, method, route, body, async () => {
|
|
189
|
-
return (await get(route,
|
|
237
|
+
return (await get(route, url, signal, { method, body, key: sending?.idempotencyKey }, sending));
|
|
190
238
|
});
|
|
191
239
|
},
|
|
192
240
|
});
|
|
@@ -36,9 +36,10 @@ export type CommandAnswers = Readonly<Record<string, unknown>>;
|
|
|
36
36
|
* Everything a screen needs to know about where an entity lives on the server, declared once.
|
|
37
37
|
*
|
|
38
38
|
* Context: a screen should not know a URL. It names the entity, and the entity says where its
|
|
39
|
-
* list is, where one record is, which Commands it takes, how it is saved
|
|
40
|
-
*
|
|
41
|
-
* (`domain:kind`, the shape of a composer
|
|
39
|
+
* list is, where one record is, which Commands it takes, how it is saved, previewed and deleted
|
|
40
|
+
* — or put in a trash, brought back and purged —, where a draft is kept and where its history
|
|
41
|
+
* is. `key` is how the workspace refers to it (`domain:kind`, the shape of a composer
|
|
42
|
+
* `ResourceRef`).
|
|
42
43
|
*
|
|
43
44
|
* The routes are declared, not guessed: sincpro_framework publishes a route per use case and
|
|
44
45
|
* its model definition does not list them (yet). A route is `"METHOD /path/{id}"` for a write.
|
|
@@ -48,6 +49,10 @@ export type CommandAnswers = Readonly<Record<string, unknown>>;
|
|
|
48
49
|
* create: "POST /invoices",
|
|
49
50
|
* save: "PUT /invoices/{id}",
|
|
50
51
|
* preview: "POST /invoices/preview",
|
|
52
|
+
* delete: "DELETE /invoices/{id}",
|
|
53
|
+
* archive: "POST /invoices/{id}/archive",
|
|
54
|
+
* restore: "POST /invoices/{id}/restore",
|
|
55
|
+
* purge: "POST /invoices/purge",
|
|
51
56
|
* commands: { confirm: "POST /invoices/{id}/confirm", cancel: "POST /invoices/{id}/cancel" },
|
|
52
57
|
* history: "/invoices/{id}/events",
|
|
53
58
|
* });
|
|
@@ -65,15 +70,21 @@ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = Co
|
|
|
65
70
|
kind: string;
|
|
66
71
|
/** Where the workspace finds it: the list without an id, one record with it — the shape of a
|
|
67
72
|
* composer `ResourceRef`, built here so no screen writes `{ domain, kind, id }` by hand. */
|
|
68
|
-
ref: (id?: string) =>
|
|
73
|
+
ref: (id?: string) => ResourceRef;
|
|
69
74
|
/** A record that does not exist yet — the form that creates one. Its view is the record's.
|
|
70
75
|
* With `values`, the form starts with them over the model's defaults: an invoice created
|
|
71
76
|
* from its customer starts with that customer (`startingValuesOf`). */
|
|
72
|
-
newRef: (values?: AnyRecord) =>
|
|
77
|
+
newRef: (values?: AnyRecord) => ResourceRef;
|
|
73
78
|
/** Its list opened to CHOOSE one: a row answers whoever asked (composer's `api.pick`). With
|
|
74
79
|
* `query`, the list opens on that literal search — what was typed in the picker; with
|
|
75
80
|
* `scope`, it offers only what the picker may choose (`scopeOfRef`). */
|
|
76
|
-
chooserRef: (query?: string, scope?: Expression) =>
|
|
81
|
+
chooserRef: (query?: string, scope?: Expression) => ResourceRef;
|
|
82
|
+
/** Its list opened under a cut — «this member's payments», what a smart button opens. With
|
|
83
|
+
* `name`, the list says whose it is («Payments · María»): a cut that travels without one
|
|
84
|
+
* reads as the whole list. The cut travels as a chooser's does (`scopeOfRef`), the name
|
|
85
|
+
* under `SCOPE_NAME_PARAM` (`scopeNameOf`). A method, so an `Entity<Invoice>` is still an
|
|
86
|
+
* `Entity`. */
|
|
87
|
+
listRef(cut: Expression<T>, name?: string): ResourceRef;
|
|
77
88
|
/** The route of its list. */
|
|
78
89
|
list: string;
|
|
79
90
|
/** The route of one record. */
|
|
@@ -89,9 +100,32 @@ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = Co
|
|
|
89
100
|
/** Where this caller keeps an edit between requests — sincpro_framework's `Drafts`. */
|
|
90
101
|
draft?: WriteRoute;
|
|
91
102
|
/** sincpro_framework's `Edit`: ONE route that keeps the draft, saves and discards, by its
|
|
92
|
-
* `action`. Declared, a save
|
|
93
|
-
*
|
|
103
|
+
* `action`. Declared, a save goes through it — what changed, with the draft and stored
|
|
104
|
+
* versions it started from: the server puts it over what it stored and the caller's draft —
|
|
105
|
+
* and it is also where the draft is kept. */
|
|
94
106
|
edit?: WriteRoute;
|
|
107
|
+
/** sincpro_framework's `Delete`: the record deleted by its key, `{id}` in the path. It answers
|
|
108
|
+
* nothing (`null`); with `dry_run: true` it answers the `Preview` of what would go and deletes
|
|
109
|
+
* nothing, and `origin_version` refuses it when the record moved past the version read. Over
|
|
110
|
+
* REST those fields travel in the query string — a `DELETE` is read from its URL. */
|
|
111
|
+
delete?: WriteRoute;
|
|
112
|
+
/** sincpro_framework's `Archive`: the record put in the trash by its key, `{id}` in the path —
|
|
113
|
+
* left out of every reading, nothing lost. It answers nothing (`null`); with `dry_run: true`
|
|
114
|
+
* it answers the `Preview` of what would be archived and archives nothing, and
|
|
115
|
+
* `origin_version` refuses it when the record moved past the version read. The trash itself
|
|
116
|
+
* is the entity's list asked for what is archived (`archived_at` not null), which every other
|
|
117
|
+
* reading leaves out. */
|
|
118
|
+
archive?: WriteRoute;
|
|
119
|
+
/** sincpro_framework's `Restore`: an archived record brought back by its key, `{id}` in the
|
|
120
|
+
* path — into every reading again. It answers as `archive` does, `dry_run` and
|
|
121
|
+
* `origin_version` included. */
|
|
122
|
+
restore?: WriteRoute;
|
|
123
|
+
/** sincpro_framework's `Purge`: every record archived longer ago than `older_than` — a
|
|
124
|
+
* duration as the contract writes it (`"P30D"`) — deleted for good. The route of the whole
|
|
125
|
+
* collection, no `{id}`. It answers nothing; with `dry_run: true`, the `Preview` of how many
|
|
126
|
+
* would go (`data: { count }`), deleting nothing. The backend never purges on its own: a cron
|
|
127
|
+
* of the project runs it, or a screen's «empty the trash». */
|
|
128
|
+
purge?: WriteRoute;
|
|
95
129
|
/** Its business events: where ONE record's events are read (sincpro_framework's
|
|
96
130
|
* `DomainEvents`), `{id}` where its key goes — a page of them, as a list answers. */
|
|
97
131
|
history?: string;
|
|
@@ -110,8 +144,15 @@ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = Co
|
|
|
110
144
|
/** Only carries what each Command answers; never read. */
|
|
111
145
|
readonly _answers?: A;
|
|
112
146
|
};
|
|
113
|
-
/**
|
|
114
|
-
|
|
147
|
+
/**
|
|
148
|
+
* Where the workspace opens an entity — its list, one record, a new one, a chooser —: a composer
|
|
149
|
+
* `ResourceRef`, structurally, since nothing here imports the composer.
|
|
150
|
+
*
|
|
151
|
+
* Context: named as composer names it. `EntityRef` is sincpro_framework's word for something
|
|
152
|
+
* else — a record of any bounded context written as one text (`billing.Invoice:01a1…`), what a
|
|
153
|
+
* payload carries —, and two types of one name cannot both be public.
|
|
154
|
+
*/
|
|
155
|
+
export type ResourceRef = {
|
|
115
156
|
domain: string;
|
|
116
157
|
kind: string;
|
|
117
158
|
id?: string;
|
|
@@ -131,16 +172,19 @@ export declare const TRAIL_PARAM = "from";
|
|
|
131
172
|
/** What a new record starts with, as JSON: one param keeps each value's type (a number stays
|
|
132
173
|
* a number), where a param per field would turn all of them into text. */
|
|
133
174
|
export declare const WITH_PARAM = "with";
|
|
134
|
-
/** What a chooser may offer at all,
|
|
135
|
-
* excludes, its named list's scope — that the list
|
|
175
|
+
/** What a chooser may offer at all, or what a list opened under a cut shows (`listRef`), as
|
|
176
|
+
* JSON: the cut — its criteria, the keys it excludes, its named list's scope — that the list
|
|
177
|
+
* it opens ANDs under everything. */
|
|
136
178
|
export declare const SCOPE_PARAM = "scope";
|
|
179
|
+
/** Whose a list opened under a cut is (`listRef(cut, name)`): «María» of «Payments · María». */
|
|
180
|
+
export declare const SCOPE_NAME_PARAM = "of";
|
|
137
181
|
/**
|
|
138
182
|
* What a new record's reference says it starts with (`newRef(values)`), or nothing.
|
|
139
183
|
*
|
|
140
184
|
* Context: a reference survives a reload and a link, so its params can be anything a person
|
|
141
185
|
* typed in the address bar — a value that is not a JSON object is not a start, never an error.
|
|
142
186
|
*/
|
|
143
|
-
export declare function startingValuesOf(ref: Pick<
|
|
187
|
+
export declare function startingValuesOf(ref: Pick<ResourceRef, "params">): AnyRecord;
|
|
144
188
|
/**
|
|
145
189
|
* The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
|
|
146
190
|
*
|
|
@@ -151,7 +195,16 @@ export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRec
|
|
|
151
195
|
* (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
|
|
152
196
|
* OFFERED; the server still decides what may be stored.
|
|
153
197
|
*/
|
|
154
|
-
export declare function scopeOfRef(ref: Pick<
|
|
198
|
+
export declare function scopeOfRef(ref: Pick<ResourceRef, "params">): Expression | undefined;
|
|
199
|
+
/**
|
|
200
|
+
* Whose a list opened under a cut is (`listRef(cut, name)`), or nothing: what its heading, its
|
|
201
|
+
* tab and its breadcrumb say beside the list's name.
|
|
202
|
+
*
|
|
203
|
+
* Context: a cut that travels without a name reads as the whole list — «Payments» showing one
|
|
204
|
+
* member's. The name travels beside the cut, in the reference, so a reload and a link keep it;
|
|
205
|
+
* an empty one is none.
|
|
206
|
+
*/
|
|
207
|
+
export declare function scopeNameOf(ref: Pick<ResourceRef, "params">): string | undefined;
|
|
155
208
|
/**
|
|
156
209
|
* A write: its method and its path, `{id}` where the record's key goes. A Command may also say
|
|
157
210
|
* which field of its body names the record it runs on (`target`: `issue_id`), and then the
|
|
@@ -189,6 +242,14 @@ export type EntityRoutes<C extends CommandBodies = CommandBodies> = CommandRoute
|
|
|
189
242
|
draft?: string;
|
|
190
243
|
/** `"PUT /invoices/{id}/edit"`: the use case that answers sincpro_framework's `Edit`. */
|
|
191
244
|
edit?: string;
|
|
245
|
+
/** `"DELETE /invoices/{id}"`: the use case that answers sincpro_framework's `Delete`. */
|
|
246
|
+
delete?: string;
|
|
247
|
+
/** `"POST /invoices/{id}/archive"`: the use case that answers sincpro_framework's `Archive`. */
|
|
248
|
+
archive?: string;
|
|
249
|
+
/** `"POST /invoices/{id}/restore"`: the use case that answers sincpro_framework's `Restore`. */
|
|
250
|
+
restore?: string;
|
|
251
|
+
/** `"POST /invoices/purge"`: the use case that answers sincpro_framework's `Purge`. */
|
|
252
|
+
purge?: string;
|
|
192
253
|
/** `"/invoices/{id}/events"`: a record's events (`DomainEvents[Invoice, …]`), oldest first. */
|
|
193
254
|
history?: string;
|
|
194
255
|
/** `"/invoices/export"`: every record of a criteria as a file (`Export[Invoice, Streamed]`),
|
|
@@ -13,9 +13,12 @@ export const TRAIL_PARAM = "from";
|
|
|
13
13
|
/** What a new record starts with, as JSON: one param keeps each value's type (a number stays
|
|
14
14
|
* a number), where a param per field would turn all of them into text. */
|
|
15
15
|
export const WITH_PARAM = "with";
|
|
16
|
-
/** What a chooser may offer at all,
|
|
17
|
-
* excludes, its named list's scope — that the list
|
|
16
|
+
/** What a chooser may offer at all, or what a list opened under a cut shows (`listRef`), as
|
|
17
|
+
* JSON: the cut — its criteria, the keys it excludes, its named list's scope — that the list
|
|
18
|
+
* it opens ANDs under everything. */
|
|
18
19
|
export const SCOPE_PARAM = "scope";
|
|
20
|
+
/** Whose a list opened under a cut is (`listRef(cut, name)`): «María» of «Payments · María». */
|
|
21
|
+
export const SCOPE_NAME_PARAM = "of";
|
|
19
22
|
/**
|
|
20
23
|
* What a new record's reference says it starts with (`newRef(values)`), or nothing.
|
|
21
24
|
*
|
|
@@ -57,6 +60,18 @@ export function scopeOfRef(ref) {
|
|
|
57
60
|
return undefined;
|
|
58
61
|
}
|
|
59
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Whose a list opened under a cut is (`listRef(cut, name)`), or nothing: what its heading, its
|
|
65
|
+
* tab and its breadcrumb say beside the list's name.
|
|
66
|
+
*
|
|
67
|
+
* Context: a cut that travels without a name reads as the whole list — «Payments» showing one
|
|
68
|
+
* member's. The name travels beside the cut, in the reference, so a reload and a link keep it;
|
|
69
|
+
* an empty one is none.
|
|
70
|
+
*/
|
|
71
|
+
export function scopeNameOf(ref) {
|
|
72
|
+
const name = ref.params?.[SCOPE_NAME_PARAM];
|
|
73
|
+
return name === undefined || name === "" ? undefined : name;
|
|
74
|
+
}
|
|
60
75
|
const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
61
76
|
/** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
|
|
62
77
|
export function writeRoute(text) {
|
|
@@ -182,6 +197,14 @@ export function entity(key, routes) {
|
|
|
182
197
|
...(scope === undefined ? {} : { [SCOPE_PARAM]: JSON.stringify(scope) }),
|
|
183
198
|
},
|
|
184
199
|
}),
|
|
200
|
+
listRef: (cut, name) => ({
|
|
201
|
+
domain,
|
|
202
|
+
kind,
|
|
203
|
+
params: {
|
|
204
|
+
[SCOPE_PARAM]: JSON.stringify(cut),
|
|
205
|
+
...(name === undefined || name.trim() === "" ? {} : { [SCOPE_NAME_PARAM]: name }),
|
|
206
|
+
},
|
|
207
|
+
}),
|
|
185
208
|
list: routes.list,
|
|
186
209
|
one: (id) => template.replace("{id}", encodeURIComponent(id)),
|
|
187
210
|
// Built from exactly the names `routes.commands` was typed with.
|
|
@@ -194,6 +217,10 @@ export function entity(key, routes) {
|
|
|
194
217
|
...(routes.preview === undefined ? {} : { preview: writeRoute(routes.preview) }),
|
|
195
218
|
...(routes.draft === undefined ? {} : { draft: writeRoute(routes.draft) }),
|
|
196
219
|
...(routes.edit === undefined ? {} : { edit: writeRoute(routes.edit) }),
|
|
220
|
+
...(routes.delete === undefined ? {} : { delete: writeRoute(routes.delete) }),
|
|
221
|
+
...(routes.archive === undefined ? {} : { archive: writeRoute(routes.archive) }),
|
|
222
|
+
...(routes.restore === undefined ? {} : { restore: writeRoute(routes.restore) }),
|
|
223
|
+
...(routes.purge === undefined ? {} : { purge: writeRoute(routes.purge) }),
|
|
197
224
|
...(routes.history === undefined ? {} : { history: routes.history }),
|
|
198
225
|
...(routes.export === undefined ? {} : { export: routes.export }),
|
|
199
226
|
summary: routes.summary ?? {},
|
|
@@ -27,7 +27,11 @@ export interface Transport {
|
|
|
27
27
|
list<T>(route: string, criteria: Criteria<T>, signal?: AbortSignal, options?: CallOptions): Promise<Page<T>>;
|
|
28
28
|
/** One record, with the definition of its model. */
|
|
29
29
|
one<T>(route: string, signal?: AbortSignal, options?: CallOptions): Promise<One<T>>;
|
|
30
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* A Command — a write, an action, a preview: `method` and its fields (`body`), its answer back,
|
|
32
|
+
* `null` when it answers nothing. Where the fields travel is the wire's: over REST a `DELETE` is
|
|
33
|
+
* read from its URL, so its fields go in the query string; any other method's, in a JSON body.
|
|
34
|
+
*/
|
|
31
35
|
send<T>(method: Method, route: string, body: unknown, signal?: AbortSignal, options?: SendOptions): Promise<T>;
|
|
32
36
|
/**
|
|
33
37
|
* A read that is neither a page nor one record — a Query of the context's own, `GET /me` —:
|
package/dist/client/index.d.ts
CHANGED
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
* process's change feed (`processChanges`)
|
|
10
10
|
*/
|
|
11
11
|
export { JsonRpcError, jsonRpcOperations, type JsonRpcOptions, } from "./adapters/json-rpc.js";
|
|
12
|
-
export { type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
|
|
12
|
+
export { type AssignableOptions, assignableValues, type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
|
|
13
13
|
export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./adapters/rest.js";
|
|
14
14
|
export { restOperations } from "./adapters/rest-operations.js";
|
|
15
15
|
export { type Change, type ChangeFeed, changeOf, } from "./domain/changes.js";
|
|
16
16
|
export { type ClientContract, entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
|
|
17
|
-
export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type
|
|
17
|
+
export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type EntityRoutes, type ExportFormat, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, type ResourceRef, SCOPE_NAME_PARAM, SCOPE_PARAM, scopeNameOf, scopeOfRef, startingValuesOf, type SummaryFields, type SummaryPart, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./domain/entity.js";
|
|
18
18
|
export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
|
|
19
19
|
export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, markedAs, type Method, type One, readRoute, SCREENS, type SendOptions, type Transport, TransportError, } from "./domain/transport.js";
|
|
20
20
|
export { announced, changeFeed, processChanges, } from "./services/changes.js";
|
package/dist/client/index.js
CHANGED
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
* process's change feed (`processChanges`)
|
|
10
10
|
*/
|
|
11
11
|
export { JsonRpcError, jsonRpcOperations, } from "./adapters/json-rpc.js";
|
|
12
|
-
export { memoryTransport, } from "./adapters/memory.js";
|
|
12
|
+
export { assignableValues, memoryTransport, } from "./adapters/memory.js";
|
|
13
13
|
export { restTransport, urlOf, } from "./adapters/rest.js";
|
|
14
14
|
export { restOperations } from "./adapters/rest-operations.js";
|
|
15
15
|
export { changeOf, } from "./domain/changes.js";
|
|
16
16
|
export { entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
|
|
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";
|
|
17
|
+
export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_NAME_PARAM, SCOPE_PARAM, scopeNameOf, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./domain/entity.js";
|
|
18
18
|
export { OperationNotPublished, } from "./domain/operation.js";
|
|
19
19
|
export { downloadRoute, markedAs, readRoute, SCREENS, TransportError, } from "./domain/transport.js";
|
|
20
20
|
export { announced, changeFeed, processChanges, } from "./services/changes.js";
|
|
@@ -7,6 +7,7 @@ import { type GenerateOptions } from "./rest.js";
|
|
|
7
7
|
* whether it answers bytes, and the binding of each wire that publishes it.
|
|
8
8
|
* 2. A method per operation, named by `methodOf`: its input — optional when nothing in it is
|
|
9
9
|
* required — and the call's options (headers, signal, idempotency key), answering its answer.
|
|
10
|
+
* An edit's method mints the record's key when the input names none (`mintsKey`).
|
|
10
11
|
* 3. When the contract carries them, every domain event as data, by its type's name: its wire
|
|
11
12
|
* name, and whether the bounded context records it or handles it.
|
|
12
13
|
* Final: `clientOf(transport)` over an `OperationTransport`, bound to each run that uses it; two
|
|
@@ -27,6 +27,29 @@ function isStreamed(operation) {
|
|
|
27
27
|
return (operation.output !== null &&
|
|
28
28
|
operation.output["x-sincpro-streamed"] !== undefined);
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* The field of an edit that names its record, minted by the client when the caller names none.
|
|
32
|
+
*
|
|
33
|
+
* Context: an operation of role `edit` is sincpro_framework's `Edit` (`role_of`: what descends
|
|
34
|
+
* from it), whose `id` — the record's key — the server mints with `new_entity_id()` when none is
|
|
35
|
+
* sent. Over REST its route carries the key in its path (`PUT /invoices/{id}/edit`), so creating
|
|
36
|
+
* a record through the generated method failed before it left («needs "id"»). The method mints it
|
|
37
|
+
* as the server would (`newEntityId`, a UUID v7), the same on every wire; a key the caller names
|
|
38
|
+
* — a stored record's, or the one a form minted for its draft — goes as it is.
|
|
39
|
+
*/
|
|
40
|
+
const EDIT_KEY = "id";
|
|
41
|
+
/** Whether `operation` is an edit whose key the caller may leave out — the method mints it. */
|
|
42
|
+
function mintsKey(operation) {
|
|
43
|
+
return (operation.role === "edit" &&
|
|
44
|
+
operation.input.properties?.[EDIT_KEY] !== undefined &&
|
|
45
|
+
!(operation.input.required ?? []).includes(EDIT_KEY));
|
|
46
|
+
}
|
|
47
|
+
/** The input a method hands the transport: as the caller gave it, an edit's key minted if absent. */
|
|
48
|
+
function inputOf(operation, optional) {
|
|
49
|
+
if (mintsKey(operation))
|
|
50
|
+
return `{ ...input, ${EDIT_KEY}: input?.${EDIT_KEY} || newEntityId() }`;
|
|
51
|
+
return optional ? "input ?? {}" : "input";
|
|
52
|
+
}
|
|
30
53
|
/** The data of one operation: what it is, and how each wire reaches it. */
|
|
31
54
|
function dataOf(metamodel, identity, operation, rest) {
|
|
32
55
|
const lines = [
|
|
@@ -58,6 +81,7 @@ function dataOf(metamodel, identity, operation, rest) {
|
|
|
58
81
|
* whether it answers bytes, and the binding of each wire that publishes it.
|
|
59
82
|
* 2. A method per operation, named by `methodOf`: its input — optional when nothing in it is
|
|
60
83
|
* required — and the call's options (headers, signal, idempotency key), answering its answer.
|
|
84
|
+
* An edit's method mints the record's key when the input names none (`mintsKey`).
|
|
61
85
|
* 3. When the contract carries them, every domain event as data, by its type's name: its wire
|
|
62
86
|
* name, and whether the bounded context records it or handles it.
|
|
63
87
|
* Final: `clientOf(transport)` over an `OperationTransport`, bound to each run that uses it; two
|
|
@@ -67,26 +91,32 @@ export function clientFileOf(metamodel, options = {}) {
|
|
|
67
91
|
const claim = claimed();
|
|
68
92
|
const data = [];
|
|
69
93
|
const methods = [];
|
|
94
|
+
let minting = false;
|
|
70
95
|
for (const [identity, operation] of sorted(metamodel.operations)) {
|
|
71
96
|
const local = localOf(metamodel, identity);
|
|
72
97
|
data.push(dataOf(metamodel, identity, operation, restOf(metamodel, identity, options)));
|
|
73
98
|
const method = methodOf(local);
|
|
74
99
|
claim(method, `operation ${identity}`);
|
|
75
100
|
const wires = wiresOf(metamodel, identity);
|
|
101
|
+
const mints = mintsKey(operation);
|
|
102
|
+
minting ||= mints;
|
|
76
103
|
const doc = docOf([
|
|
77
104
|
operation.description,
|
|
78
105
|
deprecationOf(metamodel, operation),
|
|
106
|
+
mints
|
|
107
|
+
? `A new record's \`${EDIT_KEY}\` is minted here when the input names none (\`newEntityId\`).`
|
|
108
|
+
: undefined,
|
|
79
109
|
wires.length === 0 ? undefined : `Published over ${wires.join(", ")}.`,
|
|
80
110
|
], " ");
|
|
81
111
|
const optional = (operation.input.required ?? []).length === 0;
|
|
82
112
|
methods.push([
|
|
83
113
|
`${doc} ${method}: (input${optional ? "?" : ""}: dto.${local}, options?: OperationOptions) =>`,
|
|
84
|
-
` transport.call<dto.${answerOf(metamodel, identity)}>(operations.${local},
|
|
114
|
+
` transport.call<dto.${answerOf(metamodel, identity)}>(operations.${local}, ${inputOf(operation, optional)}, options),`,
|
|
85
115
|
].join("\n"));
|
|
86
116
|
}
|
|
87
117
|
const events = sorted(metamodel.events ?? {}).map(([name, event]) => ` ${identifierOf(event.title)}: { name: ${JSON.stringify(name)}, recorded: ${event.recorded}, handled: ${event.handled} },`);
|
|
88
118
|
const imports = [
|
|
89
|
-
`import { bindable, type OperationOptions, type OperationTransport } from "${FRAMEWORK}";`,
|
|
119
|
+
`import { bindable,${minting ? " newEntityId," : ""} type OperationOptions, type OperationTransport } from "${FRAMEWORK}";`,
|
|
90
120
|
"",
|
|
91
121
|
`import type * as dto from "${DOMAIN_MODULE}";`,
|
|
92
122
|
].join("\n");
|
|
@@ -30,7 +30,9 @@ import { aliasOf, answerOf, claimed, contextOf, deprecationOf, docOf, headerOf,
|
|
|
30
30
|
* name is claimed once across the files: `index.ts` re-exports them side by side.
|
|
31
31
|
*
|
|
32
32
|
* criteria's grammar comes with every metamodel (`$defs.Criteria`); `@sincpro/criteria` already
|
|
33
|
-
* types it, so it is imported, never written a second time.
|
|
33
|
+
* types it, so it is imported, never written a second time. So is a text whose `format` this
|
|
34
|
+
* package types: a ref to a record of any bounded context (`format: "entity-ref"`) is an
|
|
35
|
+
* `EntityRef`, never a bare `string`.
|
|
34
36
|
*
|
|
35
37
|
* domainFilesOf(JSON.parse(readFileSync("project.contract.json", "utf8")))
|
|
36
38
|
* -> { "models.ts": "…", "commands.ts": "…", "index.ts": "…" }
|
|
@@ -43,6 +45,13 @@ const IMPORTED = {
|
|
|
43
45
|
Download: { name: "Download", from: "@sincpro/client-framework" },
|
|
44
46
|
EntityCollection: { name: "EntityCollection", from: "@sincpro/client-framework" },
|
|
45
47
|
};
|
|
48
|
+
/** A text whose `format` a package of the stack already types — the backend's `EntityRef`,
|
|
49
|
+
* `bounded_context.Entity:key` —: the field is that type, imported. */
|
|
50
|
+
const FORMATS = {
|
|
51
|
+
"entity-ref": { name: "EntityRef", from: "@sincpro/client-framework" },
|
|
52
|
+
};
|
|
53
|
+
/** Everything a file may import from the stack, by the name it imports. */
|
|
54
|
+
const STACK = new Map([...Object.values(IMPORTED), ...Object.values(FORMATS)].map((one) => [one.name, one]));
|
|
46
55
|
/** A relation that holds several records: a reading answers it as a page of them. */
|
|
47
56
|
const TO_MANY = new Set(["one2many", "many2many"]);
|
|
48
57
|
/** The field types whose value is the record itself, not a key that names it. */
|
|
@@ -170,8 +179,13 @@ function typeOf(schema, scope, depth, record) {
|
|
|
170
179
|
if (types.length > 1)
|
|
171
180
|
return union(types.map((one) => typeOf({ ...schema, type: one }, scope, depth, record)));
|
|
172
181
|
switch (types[0]) {
|
|
173
|
-
case "string":
|
|
174
|
-
|
|
182
|
+
case "string": {
|
|
183
|
+
const typed = schema.format === undefined ? undefined : FORMATS[schema.format];
|
|
184
|
+
if (typed === undefined)
|
|
185
|
+
return "string";
|
|
186
|
+
scope.imports.add(typed.name);
|
|
187
|
+
return typed.name;
|
|
188
|
+
}
|
|
175
189
|
case "integer":
|
|
176
190
|
case "number":
|
|
177
191
|
return "number";
|
|
@@ -241,7 +255,7 @@ function definitionsOf(metamodel, scope, elsewhere) {
|
|
|
241
255
|
function importsOf(scope, siblings) {
|
|
242
256
|
const byPackage = new Map();
|
|
243
257
|
for (const name of [...scope.imports].sort()) {
|
|
244
|
-
const imported =
|
|
258
|
+
const imported = STACK.get(name);
|
|
245
259
|
byPackage.set(imported.from, [...(byPackage.get(imported.from) ?? []), imported.name]);
|
|
246
260
|
}
|
|
247
261
|
const packages = [...byPackage.keys()]
|
|
@@ -5,9 +5,10 @@ import { type GenerateOptions } from "./rest.js";
|
|
|
5
5
|
*
|
|
6
6
|
* 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
|
|
7
7
|
* several) — none, and the model gets no entity, said in the file's own doc.
|
|
8
|
-
* 2. Its `get`, `edit` and `
|
|
9
|
-
*
|
|
10
|
-
* record
|
|
8
|
+
* 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`,
|
|
9
|
+
* and its trash's — `archive`, `restore` and `purge`, this one by its path —; its `events` — a
|
|
10
|
+
* record's `DomainEvents` — as `history`, the same way; and its `export` — every record of a
|
|
11
|
+
* criteria as a file — by its path.
|
|
11
12
|
* 3. Every write of role `command` that concerns it: with `target` when its body names the
|
|
12
13
|
* record, as it is when it creates one; its body typed without that field.
|
|
13
14
|
* Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
|
|
@@ -78,7 +78,9 @@ function entitySourceOf(metamodel, model, domain, options, claim) {
|
|
|
78
78
|
}
|
|
79
79
|
else if (one !== undefined)
|
|
80
80
|
missing.push(`one: ${one.missing}`);
|
|
81
|
-
|
|
81
|
+
// sincpro_framework's `Delete` (role `delete`) is the record's own route too, never a Command;
|
|
82
|
+
// so are its trash's `Archive` and `Restore`, and `Purge`, the route of the whole collection.
|
|
83
|
+
for (const role of ["edit", "preview", "delete", "archive", "restore", "purge"]) {
|
|
82
84
|
const write = oneOf(reads(role, isWrite), role);
|
|
83
85
|
if (write === undefined)
|
|
84
86
|
continue;
|
|
@@ -155,9 +157,10 @@ function entitySourceOf(metamodel, model, domain, options, claim) {
|
|
|
155
157
|
*
|
|
156
158
|
* 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
|
|
157
159
|
* several) — none, and the model gets no entity, said in the file's own doc.
|
|
158
|
-
* 2. Its `get`, `edit` and `
|
|
159
|
-
*
|
|
160
|
-
* record
|
|
160
|
+
* 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`,
|
|
161
|
+
* and its trash's — `archive`, `restore` and `purge`, this one by its path —; its `events` — a
|
|
162
|
+
* record's `DomainEvents` — as `history`, the same way; and its `export` — every record of a
|
|
163
|
+
* criteria as a file — by its path.
|
|
161
164
|
* 3. Every write of role `command` that concerns it: with `target` when its body names the
|
|
162
165
|
* record, as it is when it creates one; its body typed without that field.
|
|
163
166
|
* Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A record of any bounded context, named by one text — sincpro_framework's `EntityRef`:
|
|
3
|
+
* `billing.Invoice:01a1e6f2c0b37a4e9b1d2c3e4f5a6b7c`.
|
|
4
|
+
*
|
|
5
|
+
* parseEntityRef("billing.Invoice:F:7") -> { boundedContext: "billing", entity: "Invoice", key: "F:7" }
|
|
6
|
+
* entityRefOf({ boundedContext: "billing", entity: "Invoice", key: "F:7" }) -> "billing.Invoice:F:7"
|
|
7
|
+
* isEntityRef("Invoice:F:7") -> false: no bounded context
|
|
8
|
+
*
|
|
9
|
+
* Context: what travels in a payload that comes back later — a payment's metadata, a webhook, a
|
|
10
|
+
* notification — says which record it is about this way, and whoever receives it reads the
|
|
11
|
+
* record by its own `Get` (the backend's `Resolve`, an operation of whichever bounded context
|
|
12
|
+
* publishes it) without knowing its route. On the wire a ref is always its text, published as
|
|
13
|
+
* `{"type": "string", "format": "entity-ref"}`, so here it is a text too, typed by its form: the
|
|
14
|
+
* generator types a field of that format as `EntityRef`, a literal in the form type-checks, and
|
|
15
|
+
* any other string is read with `parseEntityRef` or checked with `isEntityRef` first. The bounded
|
|
16
|
+
* context and the entity are named as a `Reference` names a relation (`auth.Tenant`) — the
|
|
17
|
+
* entity by its class's name, never a workspace's `kind` —, and the key is the one its `Get`
|
|
18
|
+
* finds it by.
|
|
19
|
+
*
|
|
20
|
+
* The rule is the backend's `EntityRef.parse`: the key is everything after the FIRST `:` (a key
|
|
21
|
+
* may hold one), the entity what follows the LAST `.` before it (a bounded context may hold one),
|
|
22
|
+
* and none of the three empty. The entity is checked as the contract's `pattern` publishes it
|
|
23
|
+
* (`[A-Za-z_][A-Za-z0-9_]*`), so a ref the client accepts is one the published schema accepts.
|
|
24
|
+
*/
|
|
25
|
+
export type EntityRef = `${string}.${string}:${string}`;
|
|
26
|
+
/** What a ref names: its bounded context, its entity — the class's name — and its key. */
|
|
27
|
+
export type EntityRefParts = {
|
|
28
|
+
readonly boundedContext: string;
|
|
29
|
+
readonly entity: string;
|
|
30
|
+
readonly key: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* What a ref names — refused when `text` is not one, as the backend refuses it (a `422` on a DTO
|
|
34
|
+
* field).
|
|
35
|
+
*
|
|
36
|
+
* parseEntityRef("billing.Invoice:0192…") -> { boundedContext: "billing", entity: "Invoice", key: "0192…" }
|
|
37
|
+
* parseEntityRef("Invoice:0192…") -> throws: no bounded context
|
|
38
|
+
*/
|
|
39
|
+
export declare function parseEntityRef(text: string): EntityRefParts;
|
|
40
|
+
/** Whether `value` is a text in a ref's form — what a string read from outside is checked with. */
|
|
41
|
+
export declare function isEntityRef(value: unknown): value is EntityRef;
|
|
42
|
+
/**
|
|
43
|
+
* The text of a ref — the backend's `str(ref)`: `<bounded context>.<Entity>:<key>`. Refused when
|
|
44
|
+
* the parts would not read back as themselves: a bounded context holding a `:`, an entity that is
|
|
45
|
+
* not a name, an empty part.
|
|
46
|
+
*
|
|
47
|
+
* entityRefOf({ boundedContext: "billing", entity: "Invoice", key: "0192…" }) -> "billing.Invoice:0192…"
|
|
48
|
+
*/
|
|
49
|
+
export declare function entityRefOf(parts: EntityRefParts): EntityRef;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** How a ref is written, as a refusal names it — the backend's `FORMAT`. */
|
|
2
|
+
const FORMAT = "bounded_context.Entity:key";
|
|
3
|
+
/** An entity's name, as the contract's `pattern` publishes it. */
|
|
4
|
+
const ENTITY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
5
|
+
/** The parts `text` writes, or `undefined` when it is no ref. */
|
|
6
|
+
function partsOf(text) {
|
|
7
|
+
const colon = text.indexOf(":");
|
|
8
|
+
if (colon < 0)
|
|
9
|
+
return undefined;
|
|
10
|
+
const named = text.slice(0, colon);
|
|
11
|
+
const key = text.slice(colon + 1);
|
|
12
|
+
const dot = named.lastIndexOf(".");
|
|
13
|
+
if (dot < 0)
|
|
14
|
+
return undefined;
|
|
15
|
+
const boundedContext = named.slice(0, dot);
|
|
16
|
+
const entity = named.slice(dot + 1);
|
|
17
|
+
if (boundedContext === "" || !ENTITY.test(entity) || key === "")
|
|
18
|
+
return undefined;
|
|
19
|
+
return { boundedContext, entity, key };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What a ref names — refused when `text` is not one, as the backend refuses it (a `422` on a DTO
|
|
23
|
+
* field).
|
|
24
|
+
*
|
|
25
|
+
* parseEntityRef("billing.Invoice:0192…") -> { boundedContext: "billing", entity: "Invoice", key: "0192…" }
|
|
26
|
+
* parseEntityRef("Invoice:0192…") -> throws: no bounded context
|
|
27
|
+
*/
|
|
28
|
+
export function parseEntityRef(text) {
|
|
29
|
+
const parts = partsOf(text);
|
|
30
|
+
if (parts === undefined)
|
|
31
|
+
throw new Error(`${JSON.stringify(text)} is no entity ref: write ${FORMAT}`);
|
|
32
|
+
return parts;
|
|
33
|
+
}
|
|
34
|
+
/** Whether `value` is a text in a ref's form — what a string read from outside is checked with. */
|
|
35
|
+
export function isEntityRef(value) {
|
|
36
|
+
return typeof value === "string" && partsOf(value) !== undefined;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The text of a ref — the backend's `str(ref)`: `<bounded context>.<Entity>:<key>`. Refused when
|
|
40
|
+
* the parts would not read back as themselves: a bounded context holding a `:`, an entity that is
|
|
41
|
+
* not a name, an empty part.
|
|
42
|
+
*
|
|
43
|
+
* entityRefOf({ boundedContext: "billing", entity: "Invoice", key: "0192…" }) -> "billing.Invoice:0192…"
|
|
44
|
+
*/
|
|
45
|
+
export function entityRefOf(parts) {
|
|
46
|
+
const text = `${parts.boundedContext}.${parts.entity}:${parts.key}`;
|
|
47
|
+
const read = partsOf(text);
|
|
48
|
+
if (read === undefined ||
|
|
49
|
+
read.boundedContext !== parts.boundedContext ||
|
|
50
|
+
read.entity !== parts.entity ||
|
|
51
|
+
read.key !== parts.key)
|
|
52
|
+
throw new Error(`${JSON.stringify(parts)} writes no entity ref: ${FORMAT}, the bounded context without «:» ` +
|
|
53
|
+
"and the entity a name");
|
|
54
|
+
return text;
|
|
55
|
+
}
|
package/dist/common/ids.d.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
|
|
6
6
|
* UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
|
|
7
7
|
* A form that waited for the server to name it could neither keep a draft of a new record nor
|
|
8
|
-
* reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path)
|
|
8
|
+
* reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path) — so a
|
|
9
|
+
* generated client's edit mints one here when its caller names none. The layout
|
|
9
10
|
* is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
|
|
10
11
|
* within the millisecond, the variant and 62 random bits — so ids minted here sort by when
|
|
11
12
|
* they were minted, like the server's, and ordering by `id` is still ordering by creation.
|
package/dist/common/ids.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
|
|
6
6
|
* UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
|
|
7
7
|
* A form that waited for the server to name it could neither keep a draft of a new record nor
|
|
8
|
-
* reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path)
|
|
8
|
+
* reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path) — so a
|
|
9
|
+
* generated client's edit mints one here when its caller names none. The layout
|
|
9
10
|
* is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
|
|
10
11
|
* within the millisecond, the variant and 62 random bits — so ids minted here sort by when
|
|
11
12
|
* they were minted, like the server's, and ordering by `id` is still ordering by creation.
|
package/dist/common/index.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The values of the wire, as the backend writes them: ids, a day and an instant, `Decimal`,
|
|
3
|
-
* `Money`, a to-many as a page of its records,
|
|
3
|
+
* `Money`, a to-many as a page of its records, a ref to a record of any bounded context, and how
|
|
4
|
+
* any value is written and read.
|
|
4
5
|
*/
|
|
5
6
|
export { collectionOf, type EntityCollection, type HeldCollection, isCollection, isPartial, relatedCriteria, type RelationKeys, totalOf, } from "./collection.js";
|
|
6
7
|
export { Decimal, type DecimalLike } from "./decimal.js";
|
|
8
|
+
export { type EntityRef, entityRefOf, type EntityRefParts, isEntityRef, parseEntityRef, } from "./entity-ref.js";
|
|
7
9
|
export { type DeclaredFailure, type Failure, failureOf, kindOfGrpcCode, kindOfHttpStatus, kindOfJsonRpcCode, PERMANENT_KINDS, } from "./failures.js";
|
|
8
10
|
export { isEntityId, momentOf, newEntityId } from "./ids.js";
|
|
9
11
|
export { Money } from "./money.js";
|
package/dist/common/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The values of the wire, as the backend writes them: ids, a day and an instant, `Decimal`,
|
|
3
|
-
* `Money`, a to-many as a page of its records,
|
|
3
|
+
* `Money`, a to-many as a page of its records, a ref to a record of any bounded context, and how
|
|
4
|
+
* any value is written and read.
|
|
4
5
|
*/
|
|
5
6
|
export { collectionOf, isCollection, isPartial, relatedCriteria, totalOf, } from "./collection.js";
|
|
6
7
|
export { Decimal } from "./decimal.js";
|
|
8
|
+
export { entityRefOf, isEntityRef, parseEntityRef, } from "./entity-ref.js";
|
|
7
9
|
export { failureOf, kindOfGrpcCode, kindOfHttpStatus, kindOfJsonRpcCode, PERMANENT_KINDS, } from "./failures.js";
|
|
8
10
|
export { isEntityId, momentOf, newEntityId } from "./ids.js";
|
|
9
11
|
export { Money } from "./money.js";
|
|
@@ -35,6 +35,15 @@ export type FieldOptions = {
|
|
|
35
35
|
readonlyWhen?: Expression;
|
|
36
36
|
requiredWhen?: Expression;
|
|
37
37
|
visibleWhen?: Expression;
|
|
38
|
+
/** How a form shows the field, when not the way its kind is shown: any name a client
|
|
39
|
+
* registers a component under (`"textarea"`) — what sincpro_framework's `presentation`
|
|
40
|
+
* publishes as the field's `widget`. A name, never a component: which component answers it
|
|
41
|
+
* is the platform's. */
|
|
42
|
+
widget?: string;
|
|
43
|
+
/** `false`: a grouping never splits by it — an identity, a trace id, each value its own
|
|
44
|
+
* group —, as sincpro_framework publishes a field declared `groupable: False` (3.37). It only
|
|
45
|
+
* turns grouping off: a list of tags is never grouped. */
|
|
46
|
+
groupable?: boolean;
|
|
38
47
|
};
|
|
39
48
|
/** The field builders: one per type the framework publishes. */
|
|
40
49
|
export declare const field: {
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/** What a scalar and a relation both say of themselves: their words and their widget. */
|
|
2
|
+
function common(options) {
|
|
3
|
+
return {
|
|
4
|
+
...(options.label === undefined ? {} : { label: words(options.label) }),
|
|
5
|
+
...(options.help === undefined ? {} : { help: words(options.help) }),
|
|
6
|
+
...(options.widget === undefined ? {} : { widget: options.widget }),
|
|
7
|
+
};
|
|
8
|
+
}
|
|
1
9
|
function hints(options) {
|
|
2
10
|
return {
|
|
3
11
|
...(options.readonlyWhen ? { readonly_when: options.readonlyWhen } : {}),
|
|
@@ -31,10 +39,9 @@ function scalar(type, options = {}) {
|
|
|
31
39
|
kind: "scalar",
|
|
32
40
|
nullable,
|
|
33
41
|
sortable: !listed,
|
|
34
|
-
groupable: !listed,
|
|
42
|
+
groupable: !listed && options.groupable !== false,
|
|
35
43
|
ops,
|
|
36
|
-
...(options
|
|
37
|
-
...(options.help === undefined ? {} : { help: words(options.help) }),
|
|
44
|
+
...common(options),
|
|
38
45
|
...(options.required === undefined ? {} : { required: options.required }),
|
|
39
46
|
...(options.readonly === undefined ? {} : { readonly: options.readonly }),
|
|
40
47
|
...(options.default === undefined ? {} : { default: options.default }),
|
|
@@ -52,8 +59,7 @@ function relational(type, relation, keys, options = {}) {
|
|
|
52
59
|
relation,
|
|
53
60
|
identified_by: keys.identifiedBy,
|
|
54
61
|
...(keys.definition === undefined ? {} : { definition: keys.definition }),
|
|
55
|
-
...(options
|
|
56
|
-
...(options.help === undefined ? {} : { help: words(options.help) }),
|
|
62
|
+
...common(options),
|
|
57
63
|
...(options.readonly === undefined ? {} : { readonly: options.readonly }),
|
|
58
64
|
};
|
|
59
65
|
}
|
|
@@ -96,6 +102,7 @@ export const field = {
|
|
|
96
102
|
definition,
|
|
97
103
|
...(options.many ? { many: true } : {}),
|
|
98
104
|
...(options.label === undefined ? {} : { label: words(options.label) }),
|
|
105
|
+
...(options.widget === undefined ? {} : { widget: options.widget }),
|
|
99
106
|
}),
|
|
100
107
|
};
|
|
101
108
|
/** The template a typed text fills: `like` over each field, any of them matching. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sincpro/client-framework",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.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",
|