@sincpro/client-framework 2.10.0 → 3.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.
Files changed (49) hide show
  1. package/AGENTS.md +16 -7
  2. package/README.md +83 -45
  3. package/dist/client/adapters/json-rpc.d.ts +4 -0
  4. package/dist/client/adapters/json-rpc.js +44 -38
  5. package/dist/client/adapters/memory.d.ts +5 -7
  6. package/dist/client/adapters/memory.js +82 -62
  7. package/dist/client/adapters/rest-operations.d.ts +6 -2
  8. package/dist/client/adapters/rest-operations.js +8 -5
  9. package/dist/client/adapters/rest.d.ts +2 -7
  10. package/dist/client/adapters/rest.js +12 -18
  11. package/dist/client/domain/answer.d.ts +28 -0
  12. package/dist/client/domain/answer.js +52 -0
  13. package/dist/client/domain/changes.d.ts +24 -19
  14. package/dist/client/domain/changes.js +18 -9
  15. package/dist/client/domain/entity.d.ts +74 -212
  16. package/dist/client/domain/entity.js +39 -117
  17. package/dist/client/domain/operation.d.ts +22 -1
  18. package/dist/client/domain/operation.js +4 -0
  19. package/dist/client/domain/transport.d.ts +8 -6
  20. package/dist/client/domain/transport.js +3 -3
  21. package/dist/client/index.d.ts +13 -7
  22. package/dist/client/index.js +13 -7
  23. package/dist/client/services/api.d.ts +39 -0
  24. package/dist/client/services/api.js +38 -0
  25. package/dist/client/services/changes.d.ts +13 -12
  26. package/dist/client/services/changes.js +14 -13
  27. package/dist/client/services/guarded.js +3 -3
  28. package/dist/client/services/propagation.d.ts +9 -11
  29. package/dist/client/services/propagation.js +9 -11
  30. package/dist/client/services/reads.d.ts +38 -0
  31. package/dist/client/services/reads.js +46 -0
  32. package/dist/client/services/selection.d.ts +7 -6
  33. package/dist/client/services/selection.js +6 -5
  34. package/dist/codegen/domain/names.d.ts +16 -1
  35. package/dist/codegen/domain/names.js +43 -0
  36. package/dist/codegen/services/client.d.ts +7 -7
  37. package/dist/codegen/services/client.js +120 -52
  38. package/dist/codegen/services/entities.d.ts +9 -12
  39. package/dist/codegen/services/entities.js +76 -130
  40. package/dist/codegen/services/rest.d.ts +1 -6
  41. package/dist/codegen/services/rest.js +0 -11
  42. package/dist/codegen/services/scaffold.js +5 -2
  43. package/dist/core/domain/services.d.ts +1 -1
  44. package/dist/core/domain/services.js +1 -1
  45. package/dist/core/entrypoint/screens.d.ts +14 -4
  46. package/dist/core/entrypoint/screens.js +33 -141
  47. package/dist/core/index.d.ts +2 -2
  48. package/dist/core/index.js +1 -1
  49. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
- import type { Method } from "./transport.js";
2
- import { type AnyRecord, type Criteria, type Expression } from "@sincpro/criteria";
1
+ import type { EnvelopeKey } from "./answer.js";
2
+ import type { Operation } from "./operation.js";
3
+ import { type AnyRecord, type Expression } from "@sincpro/criteria";
3
4
  /**
4
5
  * The parts any record may have beside its name: what a link, a card or a record's header says
5
6
  * about it, whatever the entity.
@@ -17,133 +18,99 @@ export type SummaryFields = Partial<Record<SummaryPart, string>> & {
17
18
  person?: boolean;
18
19
  };
19
20
  /**
20
- * What each Command of an entity is sent with, by its name: `{ send: { message: string } }`.
21
- *
22
- * Context: the default is any name and any body — every entity declared before Commands had
23
- * types keeps compiling. A typed entity is still one of these (`Entity<T, C>` is assignable to
24
- * `Entity<T>`), so every piece that takes an entity takes it.
21
+ * What an operation is for the entity it works on, as the contract says (`role`): its list, one
22
+ * record, its edit, the preview of an edit, its deletion, its trash, its history, its export.
25
23
  */
26
- export type CommandBodies = Readonly<Record<string, AnyRecord>>;
24
+ export declare const ENTITY_ROLES: readonly ["search", "get", "edit", "preview", "delete", "archive", "restore", "purge", "events", "export"];
25
+ export type EntityRole = (typeof ENTITY_ROLES)[number];
27
26
  /**
28
- * What each Command of an entity answers, by its name: `{ send: { run_id: string } }` — what a
29
- * generated entity reads off each operation's `output`.
30
- *
31
- * Context: `useCommand(issues, "send").run(…)` returns it with no type argument written; a
32
- * Command it does not name answers `unknown`, as every Command did before.
27
+ * An entity's operations: the one of each role it has — `search` always —, and its Commands by
28
+ * name. Operations, never routes: how each travels is the wire's (`OperationTransport`).
33
29
  */
34
- export type CommandAnswers = Readonly<Record<string, unknown>>;
30
+ export type EntityOperations = {
31
+ readonly search: Operation;
32
+ } & {
33
+ readonly [R in Exclude<EntityRole, "search">]?: Operation;
34
+ } & {
35
+ readonly commands?: Readonly<Record<string, Operation>>;
36
+ };
35
37
  /**
36
- * Everything a screen needs to know about where an entity lives on the server, declared once.
37
- *
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, 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`).
43
- *
44
- * The routes are declared, not guessed: sincpro_framework publishes a route per use case and
45
- * its model definition does not list them (yet). A route is `"METHOD /path/{id}"` for a write.
46
- *
47
- * export const invoices = entity<Invoice>("billing:invoice", {
48
- * list: "/invoices",
49
- * create: "POST /invoices",
50
- * save: "PUT /invoices/{id}",
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",
56
- * commands: { confirm: "POST /invoices/{id}/confirm", cancel: "POST /invoices/{id}/cancel" },
57
- * history: "/invoices/{id}/events",
38
+ * The record an entity's operations answer: the one field of its `search` answer that is not
39
+ * the envelope (`issues: Issue[]` → `Issue`), as sincpro_framework names it after its model.
40
+ */
41
+ export type RecordOf<O extends EntityOperations> = O["search"] extends Operation<unknown, infer A> ? A extends AnyRecord ? A[Exclude<keyof A, EnvelopeKey>] extends readonly (infer R extends AnyRecord)[] ? R : AnyRecord : AnyRecord : AnyRecord;
42
+ /** What an entity is besides its operations — declared once, for every screen. */
43
+ export type EntityOptions = {
44
+ /** The model's name in the contract (`Issue`): what each operation's `targets` keys. */
45
+ model: string;
46
+ /** Its record is read with the caller's draft (`get` with `draft: true`): it is edited through
47
+ * sincpro_framework's `Edit`, which keeps drafts. */
48
+ drafts?: boolean;
49
+ /** Which fields are its description, state, picture… when they are not the conventional ones. */
50
+ summary?: SummaryFields;
51
+ /** `"Cliente"`: what a many2one of another model calls it, so a form resolves it alone. */
52
+ aggregate?: string;
53
+ };
54
+ /**
55
+ * Everything a screen needs to know about an entity, declared once: who it is for the workspace
56
+ * (`key`, its references), and which operation does each thing to it — list it, read one, edit,
57
+ * delete, archive, run each Command. A screen names the entity and calls the operation through
58
+ * an `OperationTransport`; it never knows a route, a verb or an RPC method.
59
+ *
60
+ * export const issues = entity("project:issue", {
61
+ * model: "Issue",
62
+ * search: operations.CommandListIssues,
63
+ * get: operations.CommandGetIssue,
64
+ * events: operations.CommandListIssueEvents,
65
+ * commands: { cancel: operations.CommandCancelIssue, send: operations.CommandSendIssue },
58
66
  * });
59
67
  *
60
- * Its Commands may be typed too — what each one is sent with, by name (`CommandBodies`), and
61
- * what each one answers (`CommandAnswers`) — and then `useCommand` and `CommandButton` take
62
- * only those names and those bodies, and give back that answer:
63
- *
64
- * entity<Issue, { send: { message: string } }, { send: { run_id: string } }>(…)
68
+ * Context: the contract publishes each operation once, with what it is for its entity (`role`),
69
+ * which input field names the record (`targets`) and how every wire reaches it. An entity used to
70
+ * be a second description of the same operations as REST routes, so its screens spoke only REST
71
+ * and drifted from the client; now it is an index over the operations themselves. Its record type
72
+ * comes from its `search` (`RecordOf`); each Command is typed by its operation.
65
73
  */
66
- export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = CommandBodies, A extends CommandAnswers = CommandAnswers> = {
74
+ export type Entity<T extends AnyRecord = AnyRecord, O extends EntityOperations = EntityOperations> = {
67
75
  /** `domain:kind`, e.g. `"billing:invoice"`. */
68
76
  key: string;
69
77
  domain: string;
70
78
  kind: string;
79
+ /** The model's name in the contract: `targets[model]` is the input field naming its record. */
80
+ model: string;
71
81
  /** Where the workspace finds it: the list without an id, one record with it — the shape of a
72
82
  * composer `ResourceRef`, built here so no screen writes `{ domain, kind, id }` by hand. */
73
83
  ref: (id?: string) => ResourceRef;
74
84
  /** A record that does not exist yet — the form that creates one. Its view is the record's.
75
- * With `values`, the form starts with them over the model's defaults: an invoice created
76
- * from its customer starts with that customer (`startingValuesOf`). */
85
+ * With `values`, the form starts with them over the model's defaults (`startingValuesOf`). */
77
86
  newRef: (values?: AnyRecord) => ResourceRef;
78
87
  /** Its list opened to CHOOSE one: a row answers whoever asked (composer's `api.pick`). With
79
- * `query`, the list opens on that literal search — what was typed in the picker; with
80
- * `scope`, it offers only what the picker may choose (`scopeOfRef`). */
88
+ * `query`, the list opens on that literal search; with `scope`, it offers only what the
89
+ * picker may choose (`scopeOfRef`). */
81
90
  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`. */
91
+ /** Its list opened under a cut — «this member's payments». With `name`, the list says whose it
92
+ * is («Payments · María»). A method, so an `Entity<Invoice>` is still an `Entity`. */
87
93
  listRef(cut: Expression<T>, name?: string): ResourceRef;
88
- /** The route of its list. */
89
- list: string;
90
- /** The route of one record. */
91
- one: (id: string) => string;
92
- /** Its Commands, by name. */
93
- commands: Readonly<Record<keyof C & string, WriteRoute>>;
94
- /** How a new record is created: the list's own route, usually. */
95
- create?: WriteRoute;
96
- /** How an edit is saved: the record's own route with `{id}`. */
97
- save?: WriteRoute;
98
- /** «What does this record become?» before saving — sincpro_framework's `Preview`. */
99
- preview?: WriteRoute;
100
- /** Where this caller keeps an edit between requests — sincpro_framework's `Drafts`. */
101
- draft?: WriteRoute;
102
- /** sincpro_framework's `Edit`: ONE route that keeps the draft, saves and discards, by its
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. */
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;
129
- /** Its business events: where ONE record's events are read (sincpro_framework's
130
- * `DomainEvents`), `{id}` where its key goes — a page of them, as a list answers. */
131
- history?: string;
132
- /** Every record of a criteria as a file: the route `exportRoute` fills, `downloadRoute` asks. */
133
- export?: string;
134
- /** Which fields are its description, state, picture… when they are not the conventional
135
- * ones (`summaryOf`). Empty: the convention decides. */
94
+ /** Its operations by role, and its Commands by name. */
95
+ operations: O;
96
+ /** Its record is read with the caller's draft. */
97
+ drafts: boolean;
98
+ /** Which fields are its description, state, picture… Empty: the convention decides. */
136
99
  summary: SummaryFields;
137
- /** The aggregate it is, as a relation of another model names it (`relation: "Cliente"`).
138
- * Without it, the `aggregate` of its model definition, once known. */
100
+ /** The aggregate it is, as a relation of another model names it. */
139
101
  aggregate?: string;
140
102
  /** Only carries the record type; never read. */
141
103
  readonly _record?: T;
142
- /** Only carries what each Command is sent with; never read. */
143
- readonly _commands?: C;
144
- /** Only carries what each Command answers; never read. */
145
- readonly _answers?: A;
146
104
  };
105
+ /**
106
+ * The input that names one record of `entity` to `operation`: its id in the field the operation's
107
+ * `targets` say, beside the rest of `input` — as a list of one when that field holds many
108
+ * (`many`). Without a target for the model, the input as given.
109
+ *
110
+ * targeted(issues, issues.operations.commands.send, "acme-3", { message: "hola" })
111
+ * -> { issue_id: "acme-3", message: "hola" }
112
+ */
113
+ export declare function targeted(entity: Pick<Entity, "model">, operation: Operation, id: string | undefined, input?: AnyRecord): AnyRecord;
147
114
  /**
148
115
  * Where the workspace opens an entity — its list, one record, a new one, a chooser —: a composer
149
116
  * `ResourceRef`, structurally, since nothing here imports the composer.
@@ -205,110 +172,5 @@ export declare function scopeOfRef(ref: Pick<ResourceRef, "params">): Expression
205
172
  * an empty one is none.
206
173
  */
207
174
  export declare function scopeNameOf(ref: Pick<ResourceRef, "params">): string | undefined;
208
- /**
209
- * A write: its method and its path, `{id}` where the record's key goes. A Command may also say
210
- * which field of its body names the record it runs on (`target`: `issue_id`), and then the
211
- * record's id is written there when it is sent (`bodyFor`).
212
- */
213
- export type WriteRoute = {
214
- method: Method;
215
- path: string;
216
- target?: string;
217
- };
218
- /**
219
- * A Command's route: `"POST /invoices/{id}/confirm"`, or, when its body names the record —
220
- * sincpro_framework's `targets`, what a generated entity declares —, the route and that field:
221
- * `{ route: "POST /issues", target: "project_id" }`.
222
- */
223
- export type CommandRoute = string | {
224
- route: string;
225
- target: string;
226
- };
227
- /** Each Command's route, by name. Typed Commands MUST each have their route — a name a screen
228
- * may run with nowhere to send it is caught here, not on the click. */
229
- type CommandRoutes<C extends CommandBodies> = string extends keyof C ? {
230
- commands?: Readonly<Record<string, CommandRoute>>;
231
- } : {
232
- commands: Readonly<Record<keyof C & string, CommandRoute>>;
233
- };
234
- export type EntityRoutes<C extends CommandBodies = CommandBodies> = CommandRoutes<C> & {
235
- list: string;
236
- /** With `{id}` where the key goes. Without it, `<list>/<id>` — sincpro_framework's convention. */
237
- one?: string;
238
- /** `"POST /invoices"`: where a new record goes. */
239
- create?: string;
240
- save?: string;
241
- preview?: string;
242
- draft?: string;
243
- /** `"PUT /invoices/{id}/edit"`: the use case that answers sincpro_framework's `Edit`. */
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;
253
- /** `"/invoices/{id}/events"`: a record's events (`DomainEvents[Invoice, …]`), oldest first. */
254
- history?: string;
255
- /** `"/invoices/export"`: every record of a criteria as a file (`Export[Invoice, Streamed]`),
256
- * asked through `exportRoute` and `downloadRoute`. */
257
- export?: string;
258
- /** `{ image: "logo", state: "estado_pago", person: true }` — not a route, but declared once
259
- * with the rest of what a screen should not have to know. */
260
- summary?: SummaryFields;
261
- /** `"Cliente"`: what a many2one of another model calls it, so a form resolves it alone. */
262
- aggregate?: string;
263
- };
264
- /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
265
- export declare function writeRoute(text: string): WriteRoute;
266
- /**
267
- * The path with the record's key in place of `{id}`, and every other `{name}` taken from the
268
- * body's field of that name: `POST /projects/{id}/shares/{tenant_id}/revoke` with
269
- * `{ tenant_id: "acme" }`.
270
- *
271
- * Context: sincpro_framework reads a path parameter as a field of the use case's DTO (its
272
- * wire merges `{...body, ...path_params}`), so the body already names every key a route
273
- * needs — a second argument for them would say the same thing twice. A key the body lacks is
274
- * the screen's bug, said before anything is sent. Without an `id`, `{id}` stays: a create or a
275
- * preview of a new record has none.
276
- */
277
- export declare function pathFor(route: WriteRoute, id?: string, body?: AnyRecord): string;
278
- /**
279
- * What a Command of a record is sent with: the body as given, and — when its route says which
280
- * field names the record (`target`) — the record's id in that field.
281
- *
282
- * bodyFor({ method: "POST", path: "/issues", target: "project_id" }, "p1", { title: "x" })
283
- * -> { title: "x", project_id: "p1" }
284
- *
285
- * Context: sincpro_framework says, per operation, which input field holds the key of each
286
- * entity it runs on (`targets`). A path that carries it (`/issues/{issue_id}/messages`) and a
287
- * body that carries it (`POST /issues` with `project_id`) are the same thing to the server — a
288
- * path parameter is read as a field of the DTO — so it goes in the body, and `pathFor` takes it
289
- * from there. Without an id (a Command that creates) the body is sent as it is.
290
- */
291
- export declare function bodyFor(route: WriteRoute, id: string | undefined, body: AnyRecord): AnyRecord;
292
- /**
293
- * A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
294
- * An empty value is no parameter — a filter left blank. A list under a record names its key in
295
- * the path (`/tenants/{tenant_id}/members`): that parameter fills it, and only the rest goes in
296
- * the query.
297
- *
298
- * Context: sincpro_framework reads a path parameter as a field of the search's DTO, the same
299
- * field a query parameter would fill, so the screen gives them all as one set of parameters. A
300
- * key the path needs and the parameters lack is the screen's bug, said before anything is sent.
301
- */
302
- export declare function listRoute(list: string, params?: Readonly<Record<string, string>>): string;
303
- /** What an export is written as: Parquet, an Arrow IPC stream, or JSON Lines. */
304
- export type ExportFormat = "parquet" | "arrow" | "jsonl";
305
- /**
306
- * The route of an export: its path, its keys filled from `params`, the criteria and the format as
307
- * its query — what `downloadRoute` asks.
308
- *
309
- * exportRoute("/invoices/export", { selection: { field: "paid", operator: "=", value: false } }, "jsonl")
310
- * -> "/invoices/export?criteria=%7B…%7D&format=jsonl"
311
- */
312
- export declare function exportRoute<T>(path: string, criteria?: Criteria<T>, format?: ExportFormat, params?: Readonly<Record<string, string>>): string;
313
- export declare function entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = CommandBodies, A extends CommandAnswers = CommandAnswers>(key: string, routes: EntityRoutes<C>): Entity<T, C, A>;
314
- export {};
175
+ /** An entity over its operations, its record typed by its `search` (`RecordOf`). */
176
+ export declare function entity<O extends EntityOperations>(key: string, declared: O & EntityOptions): Entity<RecordOf<O>, O>;
@@ -1,4 +1,34 @@
1
- import { readExpression, } from "@sincpro/criteria";
1
+ import { readExpression } from "@sincpro/criteria";
2
+ /**
3
+ * What an operation is for the entity it works on, as the contract says (`role`): its list, one
4
+ * record, its edit, the preview of an edit, its deletion, its trash, its history, its export.
5
+ */
6
+ export const ENTITY_ROLES = [
7
+ "search",
8
+ "get",
9
+ "edit",
10
+ "preview",
11
+ "delete",
12
+ "archive",
13
+ "restore",
14
+ "purge",
15
+ "events",
16
+ "export",
17
+ ];
18
+ /**
19
+ * The input that names one record of `entity` to `operation`: its id in the field the operation's
20
+ * `targets` say, beside the rest of `input` — as a list of one when that field holds many
21
+ * (`many`). Without a target for the model, the input as given.
22
+ *
23
+ * targeted(issues, issues.operations.commands.send, "acme-3", { message: "hola" })
24
+ * -> { issue_id: "acme-3", message: "hola" }
25
+ */
26
+ export function targeted(entity, operation, id, input = {}) {
27
+ const field = operation.targets[entity.model];
28
+ if (field === undefined || id === undefined || id === "")
29
+ return input;
30
+ return { ...input, [field]: operation.many?.includes(entity.model) ? [id] : id };
31
+ }
2
32
  /**
3
33
  * The params that say what a reference without an id is for: `new` is the form of a record
4
34
  * that does not exist yet, `pick` is the list opened to choose one. Params, because they are
@@ -72,109 +102,17 @@ export function scopeNameOf(ref) {
72
102
  const name = ref.params?.[SCOPE_NAME_PARAM];
73
103
  return name === undefined || name === "" ? undefined : name;
74
104
  }
75
- const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
76
- /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
77
- export function writeRoute(text) {
78
- const [method, path] = text.trim().split(/\s+/, 2);
79
- if (!METHODS.has(method) || path === undefined)
80
- throw new Error(`"${text}" is not "METHOD /path": a write says how it is sent`);
81
- return { method: method, path };
82
- }
83
- const PATH_KEY = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
84
- /**
85
- * The path with the record's key in place of `{id}`, and every other `{name}` taken from the
86
- * body's field of that name: `POST /projects/{id}/shares/{tenant_id}/revoke` with
87
- * `{ tenant_id: "acme" }`.
88
- *
89
- * Context: sincpro_framework reads a path parameter as a field of the use case's DTO (its
90
- * wire merges `{...body, ...path_params}`), so the body already names every key a route
91
- * needs — a second argument for them would say the same thing twice. A key the body lacks is
92
- * the screen's bug, said before anything is sent. Without an `id`, `{id}` stays: a create or a
93
- * preview of a new record has none.
94
- */
95
- export function pathFor(route, id, body) {
96
- return route.path.replace(PATH_KEY, (whole, name) => {
97
- if (name === "id")
98
- return id === undefined ? whole : encodeURIComponent(id);
99
- const value = body?.[name];
100
- if (value === undefined || value === null || value === "")
101
- throw new Error(`"${route.method} ${route.path}" needs "${name}" in the body`);
102
- return encodeURIComponent(String(value));
103
- });
104
- }
105
- /**
106
- * What a Command of a record is sent with: the body as given, and — when its route says which
107
- * field names the record (`target`) — the record's id in that field.
108
- *
109
- * bodyFor({ method: "POST", path: "/issues", target: "project_id" }, "p1", { title: "x" })
110
- * -> { title: "x", project_id: "p1" }
111
- *
112
- * Context: sincpro_framework says, per operation, which input field holds the key of each
113
- * entity it runs on (`targets`). A path that carries it (`/issues/{issue_id}/messages`) and a
114
- * body that carries it (`POST /issues` with `project_id`) are the same thing to the server — a
115
- * path parameter is read as a field of the DTO — so it goes in the body, and `pathFor` takes it
116
- * from there. Without an id (a Command that creates) the body is sent as it is.
117
- */
118
- export function bodyFor(route, id, body) {
119
- if (route.target === undefined || id === undefined || id === "")
120
- return body;
121
- return { ...body, [route.target]: id };
122
- }
123
- /** A Command's route as declared: a `"METHOD /path"`, or that and the field naming its record. */
124
- function commandRoute(declared) {
125
- if (typeof declared === "string")
126
- return writeRoute(declared);
127
- return { ...writeRoute(declared.route), target: declared.target };
128
- }
129
- /**
130
- * A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
131
- * An empty value is no parameter — a filter left blank. A list under a record names its key in
132
- * the path (`/tenants/{tenant_id}/members`): that parameter fills it, and only the rest goes in
133
- * the query.
134
- *
135
- * Context: sincpro_framework reads a path parameter as a field of the search's DTO, the same
136
- * field a query parameter would fill, so the screen gives them all as one set of parameters. A
137
- * key the path needs and the parameters lack is the screen's bug, said before anything is sent.
138
- */
139
- export function listRoute(list, params) {
140
- const given = params ?? {};
141
- const placed = new Set();
142
- const path = list.replace(PATH_KEY, (_whole, name) => {
143
- const value = given[name];
144
- if (value === undefined || value === "")
145
- throw new Error(`the list "${list}" needs "${name}" in its parameters`);
146
- placed.add(name);
147
- return encodeURIComponent(value);
148
- });
149
- const query = new URLSearchParams(Object.entries(given).filter(([name, value]) => value !== "" && !placed.has(name))).toString();
150
- if (query === "")
151
- return path;
152
- return `${path}${path.includes("?") ? "&" : "?"}${query}`;
153
- }
154
- /**
155
- * The route of an export: its path, its keys filled from `params`, the criteria and the format as
156
- * its query — what `downloadRoute` asks.
157
- *
158
- * exportRoute("/invoices/export", { selection: { field: "paid", operator: "=", value: false } }, "jsonl")
159
- * -> "/invoices/export?criteria=%7B…%7D&format=jsonl"
160
- */
161
- export function exportRoute(path, criteria, format, params) {
162
- return listRoute(path, {
163
- ...params,
164
- ...(criteria === undefined ? {} : { criteria: JSON.stringify(criteria) }),
165
- ...(format === undefined ? {} : { format }),
166
- });
167
- }
168
- export function entity(key, routes) {
105
+ /** An entity over its operations, its record typed by its `search` (`RecordOf`). */
106
+ export function entity(key, declared) {
169
107
  if (!/^[^:\s]+:[^:\s]+$/.test(key))
170
108
  throw new Error(`entity key "${key}" is not domain:kind`);
171
- const list = routes.list.split("?")[0] ?? routes.list;
172
- const template = routes.one ?? `${list}/{id}`;
173
109
  const [domain = "", kind = ""] = key.split(":");
110
+ const { model, drafts, summary, aggregate, ...operations } = declared;
174
111
  return {
175
112
  key,
176
113
  domain,
177
114
  kind,
115
+ model,
178
116
  ref: (id) => ({ domain, kind, ...(id === undefined || id === "" ? {} : { id }) }),
179
117
  newRef: (values) => ({
180
118
  domain,
@@ -205,25 +143,9 @@ export function entity(key, routes) {
205
143
  ...(name === undefined || name.trim() === "" ? {} : { [SCOPE_NAME_PARAM]: name }),
206
144
  },
207
145
  }),
208
- list: routes.list,
209
- one: (id) => template.replace("{id}", encodeURIComponent(id)),
210
- // Built from exactly the names `routes.commands` was typed with.
211
- commands: Object.fromEntries(Object.entries(routes.commands ?? {}).map(([name, declared]) => [
212
- name,
213
- commandRoute(declared),
214
- ])),
215
- ...(routes.create === undefined ? {} : { create: writeRoute(routes.create) }),
216
- ...(routes.save === undefined ? {} : { save: writeRoute(routes.save) }),
217
- ...(routes.preview === undefined ? {} : { preview: writeRoute(routes.preview) }),
218
- ...(routes.draft === undefined ? {} : { draft: writeRoute(routes.draft) }),
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) }),
224
- ...(routes.history === undefined ? {} : { history: routes.history }),
225
- ...(routes.export === undefined ? {} : { export: routes.export }),
226
- summary: routes.summary ?? {},
227
- ...(routes.aggregate === undefined ? {} : { aggregate: routes.aggregate }),
146
+ operations: { commands: {}, ...operations },
147
+ drafts: drafts ?? false,
148
+ summary: summary ?? {},
149
+ ...(aggregate === undefined ? {} : { aggregate }),
228
150
  };
229
151
  }
@@ -1,4 +1,4 @@
1
- import type { SendOptions } from "./transport.js";
1
+ import type { SCREENS, SendOptions } from "./transport.js";
2
2
  /**
3
3
  * One operation of a remote service, as its client contract names it: who it is, what it does
4
4
  * for its entities, and how each wire reaches it. What a generated client's `operations` holds,
@@ -20,8 +20,13 @@ export type RemoteOperation = {
20
20
  readonly query: boolean;
21
21
  readonly entities: readonly string[];
22
22
  readonly targets: Readonly<Record<string, string>>;
23
+ /** The entities whose target field holds a list of keys (`order_ids`), not one. */
24
+ readonly many?: readonly string[];
23
25
  /** It answers bytes as they are produced (an export), not JSON. */
24
26
  readonly streamed?: boolean;
27
+ /** The field of its input the client mints when the caller names none — an `edit`'s `id`,
28
+ * minted as the server would (`newEntityId`). */
29
+ readonly mints?: string;
25
30
  readonly rest?: {
26
31
  readonly method: string;
27
32
  readonly path: string;
@@ -36,6 +41,20 @@ export type RemoteOperation = {
36
41
  readonly tool: string;
37
42
  };
38
43
  };
44
+ /**
45
+ * A remote operation with what it takes and what it answers: still data, typed.
46
+ *
47
+ * Context: the contract is the one source of the client — a generated `operations` entry carries
48
+ * its input and its answer as types (`operation<CommandSendIssue, ResponseSendIssue>({…})`), so
49
+ * the API built over it (`apiOf`) is typed without a second, hand-kept interface. `I` includes
50
+ * `undefined` when nothing of the input is required. The two fields are never set.
51
+ */
52
+ export type Operation<I = unknown, O = unknown> = RemoteOperation & {
53
+ readonly _input?: I;
54
+ readonly _output?: O;
55
+ };
56
+ /** The operation as it is, typed with its input and its answer. */
57
+ export declare function operation<I, O>(data: RemoteOperation): Operation<I, O>;
39
58
  /**
40
59
  * What one call carries besides its input: its headers (the run's trace and context), what
41
60
  * cancels it, and — for a write — the gesture's idempotency key.
@@ -59,6 +78,8 @@ export type OperationOptions = SendOptions & {
59
78
  * `failureOf` reads (a `Problem`, or a declared `failureKind`).
60
79
  */
61
80
  export interface OperationTransport {
81
+ /** Set on the screens' operations and on what wraps them (`SCREENS`). */
82
+ [SCREENS]?: true;
62
83
  call<T>(operation: RemoteOperation, input: unknown, options?: OperationOptions): Promise<T>;
63
84
  }
64
85
  /** An operation the wire an adapter speaks does not publish: a client asked for what is not there. */
@@ -1,3 +1,7 @@
1
+ /** The operation as it is, typed with its input and its answer. */
2
+ export function operation(data) {
3
+ return data;
4
+ }
1
5
  /** An operation the wire an adapter speaks does not publish: a client asked for what is not there. */
2
6
  export class OperationNotPublished extends Error {
3
7
  operation;
@@ -12,17 +12,15 @@ import type { AnyRecord, Criteria, Dropped, Envelope, Meta, Page, Problem } from
12
12
  * whichever wire it came over.
13
13
  */
14
14
  /**
15
- * The mark of a screens transport: `screensTransport` answers one it already made, and a wrapper
16
- * over one (`cachedTransport`, `guardedTransport`) copies the mark, so the screens are not made
17
- * twice — one span per screen read, however many wrappers stand between.
15
+ * The mark of the screens' operations: `screensOperations` answers one it already made, and a
16
+ * wrapper over one (a platform's cache, `guardedTransport`) copies the mark, so the screens are
17
+ * not made twice — one span per screen call, however many wrappers stand between.
18
18
  *
19
19
  * Context: a mark, not a remembered object — a wrapper is a new object, and the screens context
20
20
  * it sits on is the one that answers. A platform's wrapper copies it with `markedAs`.
21
21
  */
22
22
  export declare const SCREENS: unique symbol;
23
23
  export interface Transport {
24
- /** Set on a screens transport and on what wraps one (`SCREENS`). */
25
- [SCREENS]?: true;
26
24
  /** A page of records under the criteria. */
27
25
  list<T>(route: string, criteria: Criteria<T>, signal?: AbortSignal, options?: CallOptions): Promise<Page<T>>;
28
26
  /** One record, with the definition of its model. */
@@ -188,4 +186,8 @@ export declare class TransportError extends Error {
188
186
  constructor(route: string, status: number | null, problem: Problem | null, message?: string);
189
187
  }
190
188
  /** Carries the screens mark from `from` onto `to`, a wrapper of it; `to` is answered. */
191
- export declare function markedAs<T extends Transport>(to: T, from: Transport): T;
189
+ export declare function markedAs<T extends {
190
+ [SCREENS]?: true;
191
+ }>(to: T, from: {
192
+ [SCREENS]?: true;
193
+ }): T;
@@ -11,9 +11,9 @@
11
11
  * whichever wire it came over.
12
12
  */
13
13
  /**
14
- * The mark of a screens transport: `screensTransport` answers one it already made, and a wrapper
15
- * over one (`cachedTransport`, `guardedTransport`) copies the mark, so the screens are not made
16
- * twice — one span per screen read, however many wrappers stand between.
14
+ * The mark of the screens' operations: `screensOperations` answers one it already made, and a
15
+ * wrapper over one (a platform's cache, `guardedTransport`) copies the mark, so the screens are
16
+ * not made twice — one span per screen call, however many wrappers stand between.
17
17
  *
18
18
  * Context: a mark, not a remembered object — a wrapper is a new object, and the screens context
19
19
  * it sits on is the one that answers. A platform's wrapper copies it with `markedAs`.