@sincpro/client-framework 2.6.0 → 2.7.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/AGENTS.md CHANGED
@@ -247,6 +247,13 @@ options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `r
247
247
  a collector down, Loki unreachable or no network leave the run's own answer — or its own error —
248
248
  untouched.
249
249
 
250
+ - **A file never travels inside a Command** (sincpro_framework #364): a Command asks for an upload
251
+ id, the raw bytes go to it (`Transport.upload`, `uploadTo` — `PUT /files/uploads/{id}` or a
252
+ bucket's presigned URL), and the next Command names it. No multipart body and no `File` type in
253
+ the generator until the backend publishes one. A path link is the service's and gets its
254
+ headers; a full URL of another origin gets none of them. Progress needs `XMLHttpRequest`
255
+ (`RestOptions.xmlHttpRequest`); without it, `fetch` and one report at the end.
256
+
250
257
  - **Only what is transversal comes here.** A value's wire form (a decimal as text, a day never
251
258
  an instant, a money with its currency) is the backend's contract, the same on every platform,
252
259
  so it lives in `src/common/`. How a value is shown to a person, typed in an input, or kept in
package/README.md CHANGED
@@ -829,6 +829,34 @@ history — is each reader's to decide. A transport given `changes` announces th
829
829
  a transport that must not be heard), and a platform's own adapter wraps its `send` in
830
830
  `announced(feed, method, route, body, send)`.
831
831
 
832
+ ### Sending a file
833
+
834
+ A file never travels inside a Command — sincpro_framework takes none (#364). A Command asks the
835
+ backend for an upload id, the file's bytes go to it, and the next Command names the id: the same
836
+ request whether the bytes land on the service (`PUT /files/uploads/{id}`) or on a bucket's
837
+ presigned URL. `uploadTo` sends them raw — never a form, never base64 — with the progress a screen
838
+ draws and the signal that cancels it:
839
+
840
+ ```ts
841
+ import { uploadTo } from "@sincpro/client-framework";
842
+
843
+ const kept = await uploadTo(transport, `/files/uploads/${id}`, file, signal, {
844
+ onProgress: ({ loaded, total }) => setProgress(loaded / total),
845
+ }); // { key, size, content_type } — null from a bucket
846
+ ```
847
+
848
+ `restTransport` sends it over `XMLHttpRequest` where the platform has one (a browser, React
849
+ Native), the only way to watch a body leave, and over `fetch` elsewhere, telling the progress once
850
+ at the end. A link that is a path is the service's, at the origin of `base`, and gets its headers
851
+ — the token, the trace —; a full URL of another origin (a bucket) gets none of them. Inside a use
852
+ case the bound transport carries the run's trace and signal, as every other call.
853
+
854
+ A refusal is a `TransportError` whose problem says why by `reason`: `FILE_TOO_LARGE` (413,
855
+ `max_bytes`), `FILE_TYPE_NOT_ALLOWED` (422, `allowed`, `found`), `FILE_EMPTY` (422),
856
+ `PUBLICATION_EXPIRED` / `PUBLICATION_USED_UP` (410: ask for a new id), `PUBLICATION_FORGED` /
857
+ `PUBLICATION_WRONG_ACCESS` (403), `PUBLICATION_UNKNOWN` (404). What a file may be is read from
858
+ `problem.extensions`, never written in a screen.
859
+
832
860
  ### Acting on many records
833
861
 
834
862
  What a person chose — or a script found — is a `Selection`: a value, plain data, never a store.
@@ -1017,6 +1045,7 @@ needs them.
1017
1045
  | Bytes | `{ "$bytes": "<base64>" }` | `valuesOf`, `readValues` |
1018
1046
  | Collection | items, count and cursor | `collectionOf`, `isPartial`, `relatedCriteria` |
1019
1047
  | Export | Parquet, Arrow or JSON Lines | `downloadRoute`, `exportRoute` |
1048
+ | Upload | raw bytes to an upload id, never JSON | `uploadTo` |
1020
1049
 
1021
1050
  `Decimal` and `Money` compute exactly, on `BigInt`; a decimal never becomes a `number` and a day
1022
1051
  never a `Date`. `valuesOf`/`pack` write; `readValues` reads tagged values back; `rebuilt`/`unpack`
@@ -1,5 +1,5 @@
1
1
  import type { ChangeFeed } from "../domain/changes.js";
2
- import { type Draft, type Method, type Transport } from "../domain/transport.js";
2
+ import { type Draft, type Method, type Transport, type Uploaded } from "../domain/transport.js";
3
3
  import type { AnyRecord, Criteria, Meta, Problem } from "@sincpro/criteria";
4
4
  /**
5
5
  * A server held in memory: tables of rows with their definition, answered with the same
@@ -41,6 +41,13 @@ export type MemoryOptions = {
41
41
  /** Answer a read that is neither a page nor a record (`GET /me`), its route with its query.
42
42
  * Without it, the transport has no `read`. */
43
43
  read?: (route: string) => unknown;
44
+ /**
45
+ * Keep a file sent to an upload link (`PUT /files/uploads/{id}`), the way the service would:
46
+ * answer what it kept, `null` as a bucket, or throw a `TransportError` with the problem it
47
+ * refuses with (`FILE_TOO_LARGE`, `PUBLICATION_EXPIRED`…). Without it, the transport has no
48
+ * `upload`. Its progress is told once, when it is kept.
49
+ */
50
+ upload?: (link: string, file: Blob) => Uploaded | null | Promise<Uploaded | null>;
44
51
  /** The draft this caller kept of a record, answered with it — sincpro_framework's `Drafts`. */
45
52
  draft?: (route: string) => Draft | null;
46
53
  /** Every list request, as it arrived: what a story or a test checks was really asked. */
@@ -122,6 +122,16 @@ export function memoryTransport(tables, options = {}) {
122
122
  return copyOf(await options.read(route));
123
123
  },
124
124
  }),
125
+ ...(options.upload === undefined
126
+ ? {}
127
+ : {
128
+ async upload(link, file, signal, call) {
129
+ await check(link, signal);
130
+ const kept = (await options.upload(link, file)) ?? null;
131
+ call?.onProgress?.({ loaded: file.size, total: file.size });
132
+ return copyOf(kept);
133
+ },
134
+ }),
125
135
  });
126
136
  }
127
137
  /**
@@ -23,6 +23,11 @@ import { type Criteria } from "@sincpro/criteria";
23
23
  * only in the path. A key that travels in both is harmless: the wire reads a `DELETE` as
24
24
  * `{**query, **path_params}` — the path wins — and looks for misplaced fields only in its body.
25
25
  *
26
+ * A file goes as its own bytes to the link the server handed out for it (`upload`, sincpro_framework
27
+ * #364): a raw `PUT`, never a form, so the same call fills sincpro_framework's
28
+ * `/files/uploads/{id}` and a bucket's presigned URL. It goes over `XMLHttpRequest` where the
29
+ * platform has one, the only way to watch a body leave; `fetch` otherwise.
30
+ *
26
31
  * The definition of each model — what a list, a form and a select are built from — is read
27
32
  * from the bounded context's discovery document (`document`, `/openapi.json` by default), once,
28
33
  * and read again only when an answer says another version of its model (`model_version`); the
@@ -61,6 +66,21 @@ export type RestOptions = {
61
66
  /** Where each write is announced (`Change`): the process's feed (`processChanges`) by default,
62
67
  * so a cache or a screen hears it whoever wrote — a screen, or a use case's client. */
63
68
  changes?: ChangeFeed;
69
+ /**
70
+ * What an upload is sent with, to tell its progress: the platform's `XMLHttpRequest` by default
71
+ * (a browser, React Native). `null`, or a platform with none: it goes over `fetch`, and its
72
+ * progress is told once, when it has all gone. Inject one for tests.
73
+ */
74
+ xmlHttpRequest?: XhrConstructor | null;
75
+ };
76
+ /** The part of `XMLHttpRequest` an upload uses — what a browser and React Native both have. */
77
+ export type XhrConstructor = new () => Pick<XMLHttpRequest, "open" | "setRequestHeader" | "send" | "abort" | "status" | "responseText"> & {
78
+ upload: {
79
+ onprogress: ((event: ProgressEvent) => void) | null;
80
+ } | null;
81
+ onload: (() => void) | null;
82
+ onerror: (() => void) | null;
83
+ onabort: (() => void) | null;
64
84
  };
65
85
  /** A model the server answers at another version than the snapshot the code came from. */
66
86
  export type VersionDrift = {
@@ -79,6 +79,30 @@ function pathOf(url) {
79
79
  const path = url.split("?")[0] ?? url;
80
80
  return /^https?:\/\//.test(path) ? new URL(path).pathname : path;
81
81
  }
82
+ /**
83
+ * Where an upload's link is, and whether it is this service's: a path from the origin, as
84
+ * sincpro_framework hands its links out (`/files/uploads/{id}`), is at the origin of `base`; a
85
+ * full URL is where it says — a bucket's presigned one, which must get no header of this
86
+ * service's: not its token, and nothing a bucket's CORS would have to allow.
87
+ */
88
+ function uploadTarget(base, link) {
89
+ if (!/^https?:\/\//.test(link))
90
+ return {
91
+ url: /^https?:\/\//.test(base) ? new URL(link, base).toString() : link,
92
+ own: true,
93
+ };
94
+ return {
95
+ url: link,
96
+ own: /^https?:\/\//.test(base) && new URL(link).origin === new URL(base).origin,
97
+ };
98
+ }
99
+ /** What a cancelled upload fails with — what `fetch` fails with: the signal's reason. */
100
+ function abortedWith(signal) {
101
+ const reason = signal?.reason;
102
+ return reason instanceof Error
103
+ ? reason
104
+ : Object.assign(new Error("The upload was cancelled"), { name: "AbortError" });
105
+ }
82
106
  /** Where the document is: `document` as given when absolute, else at the origin of `base`. */
83
107
  function documentUrl(base, document) {
84
108
  if (/^https?:\/\//.test(document) || !/^https?:\/\//.test(base))
@@ -89,6 +113,9 @@ export function restTransport(options = {}) {
89
113
  const base = options.base ?? "";
90
114
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
91
115
  const changes = options.changes ?? processChanges;
116
+ const xhr = options.xmlHttpRequest === undefined
117
+ ? globalThis.XMLHttpRequest
118
+ : (options.xmlHttpRequest ?? undefined);
92
119
  const decoders = options.decoders ?? [];
93
120
  const accept = decoders.length === 0
94
121
  ? {}
@@ -179,7 +206,74 @@ export function restTransport(options = {}) {
179
206
  throw new TransportError(route, response.status, readProblem(text), undefined);
180
207
  return text ? JSON.parse(text) : null;
181
208
  }
209
+ /** An upload's answer: what the service kept, `null` for a bucket's empty one, or its refusal. */
210
+ function uploaded(link, status, text) {
211
+ if (status < 200 || status >= 300)
212
+ throw new TransportError(link, status, readProblem(text), undefined);
213
+ return text ? JSON.parse(text) : null;
214
+ }
215
+ /** The bytes over `fetch`: all at once, the progress told when they have gone. */
216
+ async function uploadByFetch(link, url, file, headers, signal, onProgress) {
217
+ const response = await doFetch(url, {
218
+ method: "PUT",
219
+ headers,
220
+ body: file,
221
+ ...(signal ? { signal } : {}),
222
+ });
223
+ const text = await response.text();
224
+ const answer = uploaded(link, response.status, text);
225
+ onProgress?.({ loaded: file.size, total: file.size });
226
+ return answer;
227
+ }
228
+ /** The bytes over `XMLHttpRequest`, telling how far they got; cancelled with `signal`. */
229
+ function uploadByXhr(Xhr, link, url, file, headers, signal, onProgress) {
230
+ return new Promise((resolve, reject) => {
231
+ if (signal?.aborted)
232
+ return reject(abortedWith(signal));
233
+ const request = new Xhr();
234
+ const cancel = () => request.abort();
235
+ const settled = () => signal?.removeEventListener("abort", cancel);
236
+ request.open("PUT", url);
237
+ for (const [name, value] of Object.entries(headers))
238
+ request.setRequestHeader(name, value);
239
+ if (onProgress !== undefined && request.upload !== null)
240
+ request.upload.onprogress = (event) => onProgress({
241
+ loaded: event.loaded,
242
+ total: event.lengthComputable ? event.total : file.size,
243
+ });
244
+ request.onload = () => {
245
+ settled();
246
+ try {
247
+ resolve(uploaded(link, request.status, request.responseText));
248
+ }
249
+ catch (error) {
250
+ reject(error);
251
+ }
252
+ };
253
+ request.onerror = () => {
254
+ settled();
255
+ reject(new TransportError(link, null, null, `no answer to PUT ${link}`));
256
+ };
257
+ request.onabort = () => {
258
+ settled();
259
+ reject(abortedWith(signal));
260
+ };
261
+ signal?.addEventListener("abort", cancel, { once: true });
262
+ request.send(file);
263
+ });
264
+ }
182
265
  return bindableTransport({
266
+ async upload(link, file, signal, call) {
267
+ const target = uploadTarget(base, link);
268
+ // The bytes' own type, as a bucket's presigned PUT expects; the service judges them anyway.
269
+ const headers = {
270
+ ...(target.own ? { ...own(), ...call?.headers } : {}),
271
+ ...(file.type ? { "Content-Type": file.type } : {}),
272
+ };
273
+ return xhr === undefined
274
+ ? uploadByFetch(link, target.url, file, headers, signal, call?.onProgress)
275
+ : uploadByXhr(xhr, link, target.url, file, headers, signal, call?.onProgress);
276
+ },
183
277
  async list(route, criteria, signal, call) {
184
278
  const source = restSource(`${base}${route}`, {
185
279
  // Only a page may come in another format: the decoders are said here, and nowhere else.
@@ -45,7 +45,38 @@ export interface Transport {
45
45
  * `downloadRoute`.
46
46
  */
47
47
  download?(route: string, signal?: AbortSignal, options?: CallOptions): Promise<Download>;
48
+ /**
49
+ * A file's bytes sent to the link a server handed out for them — sincpro_framework's
50
+ * `PUT /files/uploads/{id}`, or a bucket's presigned URL —: the raw body, never a form, and
51
+ * what the server says it kept. Optional, as `read`; call it through `uploadTo`.
52
+ */
53
+ upload?(link: string, file: Blob, signal?: AbortSignal, options?: UploadOptions): Promise<Uploaded | null>;
48
54
  }
55
+ /**
56
+ * How an upload travels besides its bytes: the call's headers, and who hears how far it got.
57
+ *
58
+ * Context: a picture from a phone takes seconds; a screen shows its bar and lets the person
59
+ * cancel it (the call's `signal`). Where the platform has no way to watch a body leave (no
60
+ * `XMLHttpRequest`), the progress is told once, when it has all gone.
61
+ */
62
+ export type UploadOptions = CallOptions & {
63
+ onProgress?: (progress: UploadProgress) => void;
64
+ };
65
+ /** How many of an upload's bytes have left: `loaded` of `total`. */
66
+ export type UploadProgress = {
67
+ loaded: number;
68
+ total: number;
69
+ };
70
+ /**
71
+ * What sincpro_framework says it kept of an upload (`201`): the key the publication opened, its
72
+ * size, and its type as its bytes say — not as the client named it. A bucket's presigned `PUT`
73
+ * says nothing, and is answered `null`.
74
+ */
75
+ export type Uploaded = {
76
+ key: string;
77
+ size: number;
78
+ content_type: string;
79
+ };
49
80
  /**
50
81
  * What a server streams instead of answering JSON — every record of a criteria as Parquet, an
51
82
  * Arrow stream or JSON Lines: what it is, the name to save it under, and its bytes.
@@ -76,6 +107,24 @@ export type Decoder = {
76
107
  };
77
108
  /** A download through `transport.download`, or the reason it cannot be, by name. */
78
109
  export declare function downloadRoute(transport: Transport, route: string, signal?: AbortSignal, options?: CallOptions): Promise<Download>;
110
+ /**
111
+ * A file sent through `transport.upload` to the link a server handed out for it, or the reason it
112
+ * cannot be, by name.
113
+ *
114
+ * const { id } = await client.attachProof({ payment_id }); // the backend publishes it
115
+ * const kept = await uploadTo(transport, `/files/uploads/${id}`, file, signal, {
116
+ * onProgress: ({ loaded, total }) => bar.set(loaded / total),
117
+ * });
118
+ * await client.confirmProof({ payment_id, upload_id: id }); // the Command names it
119
+ *
120
+ * Context: sincpro_framework takes no file inside a Command (#364): the Command asks for an upload
121
+ * id, the bytes go to it, and the next Command names it — the same request whether the bytes land
122
+ * on the service or on a bucket. A refusal is a `TransportError` whose problem says why by
123
+ * `reason` — `FILE_TOO_LARGE` (`max_bytes`), `FILE_TYPE_NOT_ALLOWED` (`allowed`, `found`),
124
+ * `FILE_EMPTY`, `PUBLICATION_EXPIRED` / `PUBLICATION_USED_UP` (ask for a new id) — read from its
125
+ * `extensions`, never written in the screen.
126
+ */
127
+ export declare function uploadTo(transport: Transport, link: string, file: Blob, signal?: AbortSignal, options?: UploadOptions): Promise<Uploaded | null>;
79
128
  /**
80
129
  * A read through `transport.read`, or the reason it cannot be: a transport that has no `read`
81
130
  * is said so by name, never a `TypeError` from somewhere inside a screen.
@@ -25,6 +25,28 @@ export function downloadRoute(transport, route, signal, options) {
25
25
  return Promise.reject(new Error(`this transport has no download(): it cannot ask GET ${route} — give it one`));
26
26
  return transport.download(route, signal, options);
27
27
  }
28
+ /**
29
+ * A file sent through `transport.upload` to the link a server handed out for it, or the reason it
30
+ * cannot be, by name.
31
+ *
32
+ * const { id } = await client.attachProof({ payment_id }); // the backend publishes it
33
+ * const kept = await uploadTo(transport, `/files/uploads/${id}`, file, signal, {
34
+ * onProgress: ({ loaded, total }) => bar.set(loaded / total),
35
+ * });
36
+ * await client.confirmProof({ payment_id, upload_id: id }); // the Command names it
37
+ *
38
+ * Context: sincpro_framework takes no file inside a Command (#364): the Command asks for an upload
39
+ * id, the bytes go to it, and the next Command names it — the same request whether the bytes land
40
+ * on the service or on a bucket. A refusal is a `TransportError` whose problem says why by
41
+ * `reason` — `FILE_TOO_LARGE` (`max_bytes`), `FILE_TYPE_NOT_ALLOWED` (`allowed`, `found`),
42
+ * `FILE_EMPTY`, `PUBLICATION_EXPIRED` / `PUBLICATION_USED_UP` (ask for a new id) — read from its
43
+ * `extensions`, never written in the screen.
44
+ */
45
+ export function uploadTo(transport, link, file, signal, options) {
46
+ if (transport.upload === undefined)
47
+ return Promise.reject(new Error(`this transport has no upload(): it cannot send PUT ${link} — give it one`));
48
+ return transport.upload(link, file, signal, options);
49
+ }
28
50
  /**
29
51
  * A read through `transport.read`, or the reason it cannot be: a transport that has no `read`
30
52
  * is said so by name, never a `TypeError` from somewhere inside a screen.
@@ -11,14 +11,14 @@
11
11
  */
12
12
  export { JsonRpcError, jsonRpcOperations, type JsonRpcOptions, } from "./adapters/json-rpc.js";
13
13
  export { type AssignableOptions, assignableValues, type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
14
- export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./adapters/rest.js";
14
+ export { type RestOptions, restTransport, urlOf, type VersionDrift, type XhrConstructor, } from "./adapters/rest.js";
15
15
  export { restOperations } from "./adapters/rest-operations.js";
16
16
  export { type Change, type ChangeFeed, changeOf, } from "./domain/changes.js";
17
17
  export { type ClientContract, entityKeyOf, eventMetasOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
18
18
  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";
19
19
  export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
20
20
  export { type AllMatching, allMatching, chosen, type ChosenKeys, criteriaOf, isChosen, isEmpty, NOTHING_CHOSEN, type Selection, SelectionTooLarge, sizeOf, toggled, } from "./domain/selection.js";
21
- 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";
21
+ export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, markedAs, type Method, type One, readRoute, SCREENS, type SendOptions, type Transport, TransportError, type Uploaded, type UploadOptions, type UploadProgress, uploadTo, } from "./domain/transport.js";
22
22
  export { announced, changeFeed, processChanges, } from "./services/changes.js";
23
23
  export { guardedTransport } from "./services/guarded.js";
24
24
  export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
@@ -18,7 +18,7 @@ export { entityKeyOf, eventMetasOf, kindOf, metasOf, versionsOf, } from "./domai
18
18
  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";
19
19
  export { OperationNotPublished, } from "./domain/operation.js";
20
20
  export { allMatching, chosen, criteriaOf, isChosen, isEmpty, NOTHING_CHOSEN, SelectionTooLarge, sizeOf, toggled, } from "./domain/selection.js";
21
- export { downloadRoute, markedAs, readRoute, SCREENS, TransportError, } from "./domain/transport.js";
21
+ export { downloadRoute, markedAs, readRoute, SCREENS, TransportError, uploadTo, } from "./domain/transport.js";
22
22
  export { announced, changeFeed, processChanges, } from "./services/changes.js";
23
23
  export { guardedTransport } from "./services/guarded.js";
24
24
  export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
@@ -33,10 +33,18 @@ type DocumentSchema = {
33
33
  };
34
34
  };
35
35
  /**
36
- * The model a request to `path` answers, by the name of its contract in the document: the
37
- * entity the operation says it belongs to, else the one its answer holds.
36
+ * The model a request to `path` answers, by the name of its contract in the document: the one
37
+ * its answer holds, else the entity the operation says it belongs to.
38
38
  *
39
- * modelAt(published, "/v1/projects/p1", "get") // "Project"
39
+ * modelAt(published, "/v1/projects/p1", "get") // "Project"
40
+ * modelAt(published, "/v1/pagos/p1/events", "get") // "PagosEvent", not "Pago"
41
+ *
42
+ * Context: an operation declares the entities it concerns (`x-sincpro-entities`), which is not
43
+ * always the model it answers: `GET /pagos/{id}/events` concerns a `Pago` and answers its
44
+ * events, with the event model's own `model_version`. Taking the declared entity compared that
45
+ * version with `Pago`'s — a false drift, and the document read again on every history read. So
46
+ * the answer's model wins; when it holds several, a declared one among them; and the declared
47
+ * entity stays for an answer that names no model (`execute` typed nothing).
40
48
  */
41
49
  export declare function modelAt(published: DiscoveryDocument, path: string, method: string): string | undefined;
42
50
  /** The definition of the model named `name`, read from its contract, and its version. */
@@ -10,37 +10,45 @@ function answers(template, path) {
10
10
  .join("/");
11
11
  return new RegExp(`^${pattern}$`).test(path);
12
12
  }
13
- /** The entity a schema describes, or the one its records hold: an answer's records field. */
14
- function entityIn(schema, schemas, seen = new Set()) {
13
+ /**
14
+ * The models a schema holds, in the order it names them: itself when it is one (`x-sincpro`),
15
+ * else the ones its records are — an answer's records field, a list's items. A model is not
16
+ * looked into: the models its own fields point at are its relations, not what was answered.
17
+ */
18
+ function modelsIn(schema, schemas, found = [], seen = new Set()) {
15
19
  if (schema === undefined)
16
- return undefined;
20
+ return found;
17
21
  const named = nameOfRef(schema.$ref);
18
22
  if (named !== undefined) {
19
23
  if (seen.has(named))
20
- return undefined;
24
+ return found;
21
25
  seen.add(named);
22
26
  const target = schemas[named];
23
- return target?.["x-sincpro"]?.entity !== undefined
24
- ? named
25
- : entityIn(target, schemas, seen);
26
- }
27
- for (const one of [schema.items, ...(schema.anyOf ?? [])]) {
28
- const found = entityIn(one, schemas, seen);
29
- if (found !== undefined)
30
- return found;
31
- }
32
- for (const one of Object.values(schema.properties ?? {})) {
33
- const found = entityIn(one, schemas, seen);
34
- if (found !== undefined)
35
- return found;
27
+ if (target?.["x-sincpro"]?.entity !== undefined)
28
+ found.push(named);
29
+ else
30
+ modelsIn(target, schemas, found, seen);
31
+ return found;
36
32
  }
37
- return undefined;
33
+ for (const one of [schema.items, ...(schema.anyOf ?? [])])
34
+ modelsIn(one, schemas, found, seen);
35
+ for (const one of Object.values(schema.properties ?? {}))
36
+ modelsIn(one, schemas, found, seen);
37
+ return found;
38
38
  }
39
39
  /**
40
- * The model a request to `path` answers, by the name of its contract in the document: the
41
- * entity the operation says it belongs to, else the one its answer holds.
40
+ * The model a request to `path` answers, by the name of its contract in the document: the one
41
+ * its answer holds, else the entity the operation says it belongs to.
42
+ *
43
+ * modelAt(published, "/v1/projects/p1", "get") // "Project"
44
+ * modelAt(published, "/v1/pagos/p1/events", "get") // "PagosEvent", not "Pago"
42
45
  *
43
- * modelAt(published, "/v1/projects/p1", "get") // "Project"
46
+ * Context: an operation declares the entities it concerns (`x-sincpro-entities`), which is not
47
+ * always the model it answers: `GET /pagos/{id}/events` concerns a `Pago` and answers its
48
+ * events, with the event model's own `model_version`. Taking the declared entity compared that
49
+ * version with `Pago`'s — a false drift, and the document read again on every history read. So
50
+ * the answer's model wins; when it holds several, a declared one among them; and the declared
51
+ * entity stays for an answer that names no model (`execute` typed nothing).
44
52
  */
45
53
  export function modelAt(published, path, method) {
46
54
  const schemas = published.components?.schemas ?? {};
@@ -50,11 +58,9 @@ export function modelAt(published, path, method) {
50
58
  const operation = item[method.toLowerCase()];
51
59
  if (operation === undefined)
52
60
  continue;
53
- const declared = operation["x-sincpro-entities"]?.[0];
54
- if (declared !== undefined && schemas[declared] !== undefined)
55
- return declared;
56
- const answered = operation.responses?.["200"]?.content?.["application/json"]?.schema;
57
- return entityIn(answered, schemas);
61
+ const declared = (operation["x-sincpro-entities"] ?? []).filter((one) => schemas[one] !== undefined);
62
+ const answered = modelsIn(operation.responses?.["200"]?.content?.["application/json"]?.schema, schemas);
63
+ return answered.find((one) => declared.includes(one)) ?? answered[0] ?? declared[0];
58
64
  }
59
65
  return undefined;
60
66
  }
@@ -17,5 +17,8 @@ export function guardedTransport(transport, breaker) {
17
17
  const download = transport.download;
18
18
  if (download !== undefined)
19
19
  guarded.download = (route, signal, options) => breaker.call(() => download.call(transport, route, signal, options));
20
+ const upload = transport.upload;
21
+ if (upload !== undefined)
22
+ guarded.upload = (link, file, signal, options) => breaker.call(() => upload.call(transport, link, file, signal, options));
20
23
  return bindableTransport(markedAs(guarded, transport));
21
24
  }
@@ -78,6 +78,9 @@ export function bindTransport(transport, execution) {
78
78
  const download = transport.download;
79
79
  if (download !== undefined)
80
80
  bound.download = (route, signal, options) => download.call(transport, route, signal ?? cancels, call(options));
81
+ const upload = transport.upload;
82
+ if (upload !== undefined)
83
+ bound.upload = (link, file, signal, options) => upload.call(transport, link, file, signal ?? cancels, call(options));
81
84
  return keeping(transport, bound);
82
85
  }
83
86
  /**
@@ -49,6 +49,19 @@ class Export extends Command {
49
49
  this.options = options;
50
50
  }
51
51
  }
52
+ class Upload extends Command {
53
+ link;
54
+ file;
55
+ signal;
56
+ options;
57
+ constructor(link, file, signal, options) {
58
+ super();
59
+ this.link = link;
60
+ this.file = file;
61
+ this.signal = signal;
62
+ this.options = options;
63
+ }
64
+ }
52
65
  class Send extends Command {
53
66
  method;
54
67
  route;
@@ -96,6 +109,18 @@ class EntityExport extends Feature {
96
109
  return transport.download(dto.route, dto.signal, dto.options);
97
110
  }
98
111
  }
112
+ class EntityUpload extends Feature {
113
+ execute(dto) {
114
+ // The link holds the upload's id — a capability —, so the span names the route, not the id.
115
+ const path = dto.link.split("?")[0] ?? dto.link;
116
+ this.span.set({ "http.method": "PUT", "http.route": path.replace(/[^/]+$/, "{id}") });
117
+ const transport = this.transport;
118
+ if (!transport.upload) {
119
+ return Promise.reject(new Error(`this transport cannot upload to ${dto.link}: it has no upload()`));
120
+ }
121
+ return transport.upload(dto.link, dto.file, dto.signal, dto.options);
122
+ }
123
+ }
99
124
  class EntitySend extends Feature {
100
125
  execute(dto) {
101
126
  this.span.set({ "http.method": dto.method, "http.route": dto.route });
@@ -116,6 +141,7 @@ export function screensTransport(transport, name = "screens") {
116
141
  screens.feature(Read)(EntityRead);
117
142
  screens.feature(Export)(EntityExport);
118
143
  screens.feature(Send)(EntitySend);
144
+ screens.feature(Upload)(EntityUpload);
119
145
  const through = {
120
146
  list: (route, criteria, signal, options) => screens.execute(new List(route, criteria, signal, options)),
121
147
  one: (route, signal, options) => screens.execute(new Get(route, signal, options)),
@@ -127,6 +153,9 @@ export function screensTransport(transport, name = "screens") {
127
153
  if (transport.download) {
128
154
  through.download = (route, signal, options) => screens.execute(new Export(route, signal, options));
129
155
  }
156
+ if (transport.upload) {
157
+ through.upload = (link, file, signal, options) => screens.execute(new Upload(link, file, signal, options));
158
+ }
130
159
  through[SCREENS] = true;
131
160
  return bindableTransport(through);
132
161
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "2.6.0",
3
+ "version": "2.7.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",