@sincpro/web-framework 0.4.0 → 0.4.2

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 (45) hide show
  1. package/README.md +42 -44
  2. package/dist/core/cache.d.ts +10 -2
  3. package/dist/core/cache.js +31 -9
  4. package/dist/core/copy.d.ts +4 -0
  5. package/dist/core/copy.js +4 -0
  6. package/dist/core/edit.d.ts +5 -0
  7. package/dist/core/edit.js +6 -2
  8. package/dist/core/entity.d.ts +39 -5
  9. package/dist/core/entity.js +57 -4
  10. package/dist/core/history.js +5 -1
  11. package/dist/core/ids.d.ts +17 -0
  12. package/dist/core/ids.js +52 -0
  13. package/dist/core/index.d.ts +2 -1
  14. package/dist/core/index.js +2 -1
  15. package/dist/react/index.d.ts +2 -1
  16. package/dist/react/index.js +2 -1
  17. package/dist/react/scope.d.ts +23 -0
  18. package/dist/react/scope.js +12 -0
  19. package/dist/react/useCommand.js +1 -1
  20. package/dist/react/useListing.d.ts +1 -1
  21. package/dist/react/useListing.js +11 -11
  22. package/dist/react/useLookup.d.ts +10 -1
  23. package/dist/react/useLookup.js +29 -3
  24. package/dist/react/useRecord.d.ts +13 -2
  25. package/dist/react/useRecord.js +73 -22
  26. package/dist/web/list/rowCommands.js +2 -1
  27. package/dist/web/record/CommandButton.d.ts +3 -1
  28. package/dist/web/record/CommandButton.js +2 -2
  29. package/dist/web/record/EntityPicker.d.ts +28 -9
  30. package/dist/web/record/EntityPicker.js +54 -18
  31. package/dist/web/record/EntityTags.d.ts +5 -3
  32. package/dist/web/record/EntityTags.js +29 -6
  33. package/dist/web/record/control.d.ts +4 -4
  34. package/dist/web/record/control.js +7 -17
  35. package/dist/web/record/lines.js +12 -2
  36. package/dist/web/record/opening.d.ts +17 -3
  37. package/dist/web/record/opening.js +12 -0
  38. package/dist/web/workspace/SincproApp.d.ts +15 -4
  39. package/dist/web/workspace/SincproApp.js +18 -7
  40. package/dist/web/workspace/composer.d.ts +20 -1
  41. package/dist/web/workspace/composer.js +28 -10
  42. package/dist/web/workspace/record.js +12 -2
  43. package/dist/web/workspace/workspace.d.ts +6 -2
  44. package/dist/web/workspace/workspace.js +6 -2
  45. package/package.json +3 -3
package/README.md CHANGED
@@ -262,13 +262,9 @@ function InvoiceView({ api, resource }: ViewProps) {
262
262
  <RecordField
263
263
  record={invoice}
264
264
  name="customer_id"
265
+ // Inside a workspace the picker opens the chosen and «see all…» there by itself.
265
266
  as={({ value, set }) => (
266
- <EntityPicker
267
- entity={customers}
268
- value={String(value ?? "")}
269
- onChange={set}
270
- onBrowseAll={chooserIn(api, customers, set)}
271
- />
267
+ <EntityPicker entity={customers} value={String(value ?? "")} onChange={set} />
272
268
  )}
273
269
  />
274
270
  <RecordField record={invoice} name="notes" />
@@ -394,44 +390,46 @@ Everything is imported from `@sincpro/web-framework`.
394
390
 
395
391
  ## Where it stands
396
392
 
397
- | Piece | What it solves | Status |
398
- | -------------------------------------- | ------------------------------------------------------------------------------------------ | ------ |
399
- | `restTransport`, `memoryTransport` | The backend, or the same engine in memory | ✅ |
400
- | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI | ✅ |
401
- | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
402
- | `useRecord`, `factsOf`, `RecordLines` | One record: facts, relations with their real total | ✅ |
403
- | Preloaded definitions | `FrameworkProvider metas`: the model asked once, or never | ✅ |
404
- | `useLookup`, `EntityPicker` | Literal search: a many2one select, ⌘K | ✅ |
405
- | `useRecord` + `RecordField`, `dirtyOf` | Editing: hints evaluated live, preview, save with version (409), server drafts | ✅ |
406
- | `useCommand`, `CommandButton` | An entity's actions, with a dry run before what destroys | ✅ |
407
- | `useHistory` | Business events in `Record.Activity` (comments: backend first) | ✅ |
408
- | `entityView` | An entity as a composer view: list, record, ⌘K search | ✅ |
409
- | `<SincproApp>` | The application context in one place, the workspace dressed as web-ui (`webUiSkin`) | ✅ |
410
- | `useRecordInWorkspace` | A record tells the workspace its real name and its unsaved work (composer 1.0) | ✅ |
411
- | Paging by pages, ceiling on «more» | One page on screen, walked by the server's cursor: a million rows never freeze it | ✅ |
412
- | `cachedTransport` | Repeated reads from memory, forgotten when a write touches the entity (on in `SincproApp`) | ✅ |
413
- | `EntitySearchBar` | The search bar + criteria builder as a loose piece, for any `List` | ✅ |
414
- | `EntityList` views | The same set as table, rows or board | ✅ |
415
- | `useRelated`, `RelatedList` | A record's relation as a live list: searched and paged by the server, inside a form | ✅ |
416
- | `EntityPicker` chooser | «see all…» opens the whole set, searched on the server: a many2one over millions | ✅ |
417
- | `useRecord(entity, "")`, `create` | A new record: the model's defaults, saved to `create`, then it IS the record it became | ✅ |
418
- | `retryKeys`, `Idempotency-Key` | A Command or a create retried after a lost answer runs once, not twice | ✅ |
419
- | `entity.newRef()`, «New» in the list | The record's form with no id, in a page or a window; replaced by the record once created | ✅ |
420
- | `EntityPicker criteria` | A many2one narrowed by another field: the invoices OF the chosen customer | ✅ |
421
- | `chooserIn`, `entity.chooserRef()` | «see all…» as the composer's chooser: a row answers (`api.pick`) | ✅ |
422
- | `useGroups`, «Group by» | Groups counted by the server over the whole set; a group's rows read when it is opened | ✅ |
423
- | `defineList`, `listView` | A named list (a fixed scope, its columns and filters) as data, and as a workspace view | ✅ |
424
- | `EntityPicker` `browse`, `columns` | The chooser always a click away, as a table searched literally by the server | ✅ |
425
- | `useFollowed` | A detail panel follows the record the person is on, without knowing the list | ✅ |
426
- | `commands`, `useRowCommands` | An entity's Commands on each row, idempotent, offered only where `when` holds | ✅ |
427
- | `summaryOf`, `cardOf`, `relationOf` | Any record at any size: name, description, state, type, picture, who made and changed it | ✅ |
428
- | `openIn`, `RelatedRecord` | A related record opens in a modal; «Abrir en…» for the rest; never a modal over a modal | ✅ |
429
- | Literal search everywhere | Picker: the first ten, the server's search as you type; tables: «Buscar «X»» on Enter | ✅ |
430
- | `EntityTags` | A many2many as chips over thousands: the server's search, faces, the chosen never again | ✅ |
431
- | `RecordField` + `entities` | A many2one / one2many drawn from the model alone, opened where the view says | ✅ |
432
- | `EntityRecord`, `formOf` | Any entity's record screen without writing it | ✅ |
433
- | `Trail`, `Record.Pager` | Previous / next from a record, across the server's pages | ✅ |
434
- | `EntityList sums` | Each group says how much it adds up, summed by the server over all of it | ✅ |
393
+ | Piece | What it solves | Status |
394
+ | --------------------------------------- | ------------------------------------------------------------------------------------------ | ------ |
395
+ | `restTransport`, `memoryTransport` | The backend, or the same engine in memory | ✅ |
396
+ | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI | ✅ |
397
+ | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
398
+ | `useRecord`, `factsOf`, `RecordLines` | One record: facts, relations with their real total | ✅ |
399
+ | Preloaded definitions | `FrameworkProvider metas`: the model asked once, or never | ✅ |
400
+ | `useLookup`, `EntityPicker` | Literal search: a many2one select, ⌘K | ✅ |
401
+ | `useRecord` + `RecordField`, `dirtyOf` | Editing: hints evaluated live, preview, save with version (409), server drafts | ✅ |
402
+ | `useCommand`, `CommandButton` | An entity's actions, with a dry run before what destroys | ✅ |
403
+ | `useHistory` | Business events in `Record.Activity` (comments: backend first) | ✅ |
404
+ | `entityView` | An entity as a composer view: list, record, ⌘K search | ✅ |
405
+ | `<SincproApp>` | The application context in one place, the workspace dressed as web-ui (`webUiSkin`) | ✅ |
406
+ | `useRecordInWorkspace` | A record tells the workspace its real name and its unsaved work (composer 1.0) | ✅ |
407
+ | Paging by pages, ceiling on «more» | One page on screen, walked by the server's cursor: a million rows never freeze it | ✅ |
408
+ | `cachedTransport` | Repeated reads from memory, forgotten when a write touches the entity (on in `SincproApp`) | ✅ |
409
+ | `EntitySearchBar` | The search bar + criteria builder as a loose piece, for any `List` | ✅ |
410
+ | `EntityList` views | The same set as table, rows or board | ✅ |
411
+ | `useRelated`, `RelatedList` | A record's relation as a live list: searched and paged by the server, inside a form | ✅ |
412
+ | `EntityPicker` chooser | «see all…» opens the whole set, searched on the server: a many2one over millions | ✅ |
413
+ | `useRecord(entity, "")`, `create` | A new record: the model's defaults, saved to `create` (or `edit`), then it IS that record | ✅ |
414
+ | `retryKeys`, `Idempotency-Key` | A Command or a create retried after a lost answer runs once, not twice | ✅ |
415
+ | `entity.newRef()`, «New» in the list | The record's form with no id, in a page or a window; replaced by the record once created | ✅ |
416
+ | `EntityPicker criteria` | A many2one narrowed by another field: the invoices OF the chosen customer | ✅ |
417
+ | `chooserIn`, `entity.chooserRef()` | «see all…» as the composer's chooser: a row answers (`api.pick`) | ✅ |
418
+ | `EntityPicker` / `EntityTags` in a view | Open and choose in the workspace by themselves; the chooser carries the picker's cut | ✅ |
419
+ | `newEntityId`, `edit` on a new record | A new record born under a UUID v7 minted here: its draft and its save go through `Edit` | ✅ |
420
+ | `useGroups`, «Group by» | Groups counted by the server over the whole set; a group's rows read when it is opened | ✅ |
421
+ | `defineList`, `listView` | A named list (a fixed scope, its columns and filters) as data, and as a workspace view | ✅ |
422
+ | `EntityPicker` `browse`, `columns` | The chooser always a click away, as a table searched literally by the server | ✅ |
423
+ | `useFollowed` | A detail panel follows the record the person is on, without knowing the list | ✅ |
424
+ | `commands`, `useRowCommands` | An entity's Commands on each row, idempotent, offered only where `when` holds | ✅ |
425
+ | `summaryOf`, `cardOf`, `relationOf` | Any record at any size: name, description, state, type, picture, who made and changed it | ✅ |
426
+ | `openIn`, `RelatedRecord` | A related record opens in a modal; «Abrir en…» for the rest; never a modal over a modal | ✅ |
427
+ | Literal search everywhere | Picker: the first ten, the server's search as you type; tables: «Buscar «X»» on Enter | ✅ |
428
+ | `EntityTags` | A many2many as chips over thousands: the server's search, faces, the chosen never again | ✅ |
429
+ | `RecordField` + `entities` | A many2one / one2many drawn from the model alone, opened where the view says | ✅ |
430
+ | `EntityRecord`, `formOf` | Any entity's record screen without writing it | ✅ |
431
+ | `Trail`, `Record.Pager` | Previous / next from a record, across the server's pages | ✅ |
432
+ | `EntityList sums` | Each group says how much it adds up, summed by the server over all of it | ✅ |
435
433
 
436
434
  What it does **not** do: mobile (`sincpro_mobile` has its own core), sessions and login (the
437
435
  application's), routing (composer's), string-named widget registries, technical logs on a
@@ -1,3 +1,4 @@
1
+ import type { Entity } from "./entity.js";
1
2
  import type { Transport } from "./transport.js";
2
3
  /**
3
4
  * A transport that remembers what it read, for a while, and forgets it when something writes.
@@ -13,12 +14,17 @@ import type { Transport } from "./transport.js";
13
14
  * different filters, orders or pages never share an answer. A read that fails is not kept.
14
15
  * Only completed answers are remembered: a request aborted half-way is simply not cached.
15
16
  *
17
+ * A write forgets every collection its route NAMES, not only the first: «leave a tenant»
18
+ * (`POST /users/{email}/tenants/{tenant}/leave`) changes the tenant's members as much as the
19
+ * user. And an entity's business events live on a route of their own (`/project-events`): with
20
+ * `entities`, a write under an entity's list also forgets its history.
21
+ *
16
22
  * const transport = cachedTransport(restTransport({ base: "/v1" }), { ttl: 30_000 });
17
23
  * transport.invalidate("/facturas"); // forget an entity by hand (a push from the server)
18
24
  */
19
25
  export type CachedTransport = Transport & {
20
- /** Forget every answer whose route starts with this path: `"/facturas"` forgets the list,
21
- * every page and filter of it, and every record under it. */
26
+ /** Forget every answer whose route lies under this path: `"/facturas"` forgets the list,
27
+ * every page and filter of it, and every record under it — not `"/facturas-events"`. */
22
28
  invalidate: (path?: string) => void;
23
29
  };
24
30
  export type CacheOptions = {
@@ -26,5 +32,7 @@ export type CacheOptions = {
26
32
  ttl?: number;
27
33
  /** The clock — for tests. */
28
34
  now?: () => number;
35
+ /** The application's entities: a write to one also forgets its history route. */
36
+ entities?: readonly Entity[];
29
37
  };
30
38
  export declare function cachedTransport(transport: Transport, options?: CacheOptions): CachedTransport;
@@ -1,8 +1,20 @@
1
- /** The entity a route belongs to: its first segment, `"/facturas/F-1/confirm"` → `"/facturas"`. */
2
- function rootOf(route) {
3
- const path = route.split("?")[0] ?? route;
4
- const [, first = ""] = path.split("/");
5
- return `/${first}`;
1
+ function pathOf(route) {
2
+ return route.split("?")[0] ?? route;
3
+ }
4
+ /** `route` is `path` or lies under it: `"/facturas"` holds `"/facturas/F-1"`, never `"/facturas-events"`. */
5
+ function under(route, path) {
6
+ const own = pathOf(route);
7
+ return own === path || own.startsWith(path.endsWith("/") ? path : `${path}/`);
8
+ }
9
+ /** What a write may have changed: every segment of its route as a collection, and the history
10
+ * of each entity it writes under. A segment that is a key (`/F-1`) forgets nothing. */
11
+ function touchedBy(route, entities) {
12
+ const path = pathOf(route);
13
+ const segments = path.split("/").filter((one) => one !== "");
14
+ const history = entities
15
+ .filter((one) => one.history !== undefined && under(path, pathOf(one.list)))
16
+ .map((one) => pathOf(one.history?.route ?? ""));
17
+ return [...segments.map((one) => `/${one}`), ...history];
6
18
  }
7
19
  export function cachedTransport(transport, options = {}) {
8
20
  const ttl = options.ttl ?? 30_000;
@@ -16,12 +28,22 @@ export function cachedTransport(transport, options = {}) {
16
28
  entries.set(key, { at: now(), answer });
17
29
  return answer;
18
30
  }
31
+ const entities = options.entities ?? [];
32
+ /** Forget every answer under any of `paths` — one walk over the entries, whatever their
33
+ * number. A path with a query (`/projects?tenant_id=acme`) forgets its whole collection. */
34
+ const forget = (paths) => {
35
+ const targets = paths.map(pathOf);
36
+ for (const key of [...entries.keys()]) {
37
+ // `list <route> <criteria>` / `one <route>`: the route is the second word.
38
+ const route = key.split(" ", 2)[1] ?? "";
39
+ if (targets.some((path) => under(route, path)))
40
+ entries.delete(key);
41
+ }
42
+ };
19
43
  const invalidate = (path) => {
20
44
  if (path === undefined)
21
45
  return entries.clear();
22
- for (const key of [...entries.keys()])
23
- if (key.slice(key.indexOf(" ") + 1).startsWith(path))
24
- entries.delete(key);
46
+ forget([path]);
25
47
  };
26
48
  return {
27
49
  list(route, criteria, signal) {
@@ -39,7 +61,7 @@ export function cachedTransport(transport, options = {}) {
39
61
  finally {
40
62
  // Even a refused write may have changed something (a 409 says someone else did).
41
63
  if (!preview)
42
- invalidate(rootOf(route));
64
+ forget(touchedBy(route, entities));
43
65
  }
44
66
  },
45
67
  invalidate,
@@ -59,6 +59,8 @@ export type FrameworkCopy = {
59
59
  picker: {
60
60
  /** The button beside a many2one that opens the chooser over the whole set. */
61
61
  browse: string;
62
+ /** The choice of nothing, when a field may be left empty (`EntityPicker none`). */
63
+ none: string;
62
64
  };
63
65
  summary: {
64
66
  /** The facts of a record's summary: when it was made and last changed. */
@@ -69,6 +71,8 @@ export type FrameworkCopy = {
69
71
  /** A card's last line: «Updated 12 Mar 2026 by Ana», or «Created …» if never changed. */
70
72
  updatedLine: (at: string, by: string | null) => string;
71
73
  createdLine: (at: string, by: string | null) => string;
74
+ /** A fact of a record's history that carries no label of its own. */
75
+ recorded: string;
72
76
  };
73
77
  command: {
74
78
  /** The confirmation of an action that cannot be undone, after its dry run. */
package/dist/core/copy.js CHANGED
@@ -33,6 +33,7 @@ export const ENGLISH_FRAMEWORK_COPY = {
33
33
  },
34
34
  picker: {
35
35
  browse: "Search all",
36
+ none: "None",
36
37
  },
37
38
  summary: {
38
39
  created: "Created",
@@ -40,6 +41,7 @@ export const ENGLISH_FRAMEWORK_COPY = {
40
41
  when: (at, by) => (by === null ? at : `${at} · ${by}`),
41
42
  updatedLine: (at, by) => (by === null ? `Updated ${at}` : `Updated ${at} by ${by}`),
42
43
  createdLine: (at, by) => (by === null ? `Created ${at}` : `Created ${at} by ${by}`),
44
+ recorded: "Change recorded",
43
45
  },
44
46
  command: {
45
47
  confirm: "Do it",
@@ -101,6 +103,7 @@ export const SPANISH_FRAMEWORK_COPY = {
101
103
  },
102
104
  picker: {
103
105
  browse: "Buscar en todos",
106
+ none: "Ninguno",
104
107
  },
105
108
  summary: {
106
109
  created: "Creado",
@@ -108,6 +111,7 @@ export const SPANISH_FRAMEWORK_COPY = {
108
111
  when: (at, by) => (by === null ? at : `${at} · ${by}`),
109
112
  updatedLine: (at, by) => by === null ? `Actualizado el ${at}` : `Actualizado el ${at} por ${by}`,
110
113
  createdLine: (at, by) => (by === null ? `Creado el ${at}` : `Creado el ${at} por ${by}`),
114
+ recorded: "Cambio registrado",
111
115
  },
112
116
  command: {
113
117
  confirm: "Hacerlo",
@@ -68,5 +68,10 @@ export declare function defaultsOf(meta: Meta | null | undefined): AnyRecord;
68
68
  * What a create sends: every value on screen the caller may write. A field the model marks
69
69
  * `readonly` is the server's to fill (the number, the totals), and an empty one is left for
70
70
  * the server's own default — never sent as `""`.
71
+ *
72
+ * Context: only the model's fixed `readonly` counts, never a `readonly_when`: a currency chosen
73
+ * and then locked by the lines added after it is still the record's currency, and a key written
74
+ * when creating and never after (a tenant's slug) is a `readonly_when` the backend publishes for
75
+ * the stored record. Both travel.
71
76
  */
72
77
  export declare function creationOf(meta: Meta | null | undefined, values: AnyRecord): AnyRecord;
package/dist/core/edit.js CHANGED
@@ -110,12 +110,16 @@ export function defaultsOf(meta) {
110
110
  * What a create sends: every value on screen the caller may write. A field the model marks
111
111
  * `readonly` is the server's to fill (the number, the totals), and an empty one is left for
112
112
  * the server's own default — never sent as `""`.
113
+ *
114
+ * Context: only the model's fixed `readonly` counts, never a `readonly_when`: a currency chosen
115
+ * and then locked by the lines added after it is still the record's currency, and a key written
116
+ * when creating and never after (a tenant's slug) is a `readonly_when` the backend publishes for
117
+ * the stored record. Both travel.
113
118
  */
114
119
  export function creationOf(meta, values) {
115
120
  const sent = {};
116
121
  for (const [name, value] of Object.entries(values)) {
117
- const field = meta?.fields[name];
118
- if (field?.readonly === true)
122
+ if (meta?.fields[name]?.readonly === true)
119
123
  continue;
120
124
  if (value === undefined || value === null || value === "")
121
125
  continue;
@@ -1,4 +1,4 @@
1
- import type { AnyRecord } from "@sincpro/criteria";
1
+ import { type AnyRecord, type Expression } from "@sincpro/criteria";
2
2
  import type { SummaryFields } from "./summary.js";
3
3
  import type { Method } from "./transport.js";
4
4
  /**
@@ -34,8 +34,9 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
34
34
  * from its customer starts with that customer (`startingValuesOf`). */
35
35
  newRef: (values?: AnyRecord) => EntityRef;
36
36
  /** Its list opened to CHOOSE one: a row answers whoever asked (composer's `api.pick`). With
37
- * `query`, the list opens on that literal search — what was typed in the picker. */
38
- chooserRef: (query?: string) => EntityRef;
37
+ * `query`, the list opens on that literal search — what was typed in the picker; with
38
+ * `scope`, it offers only what the picker may choose (`scopeOfRef`). */
39
+ chooserRef: (query?: string, scope?: Expression) => EntityRef;
39
40
  /** The route of its list. */
40
41
  list: string;
41
42
  /** The route of one record. */
@@ -50,6 +51,10 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
50
51
  preview?: WriteRoute;
51
52
  /** Where this caller keeps an edit between requests — sincpro_framework's `Drafts`. */
52
53
  draft?: WriteRoute;
54
+ /** sincpro_framework's `Edit`: ONE route that keeps the draft, saves and discards, by its
55
+ * `action`. Declared, a save sends the record whole as the form holds it — not the fields
56
+ * that changed under `save` — and it is also where the draft is kept. */
57
+ edit?: WriteRoute;
53
58
  /** Its business events: the context's events route, and the `entity_type` they carry. */
54
59
  history?: {
55
60
  route: string;
@@ -85,6 +90,9 @@ export declare const TRAIL_PARAM = "from";
85
90
  /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
86
91
  * a number), where a param per field would turn all of them into text. */
87
92
  export declare const WITH_PARAM = "with";
93
+ /** What a chooser may offer at all, as JSON: the picker's cut — its criteria, the keys it
94
+ * excludes, its named list's scope — that the list it opens ANDs under everything. */
95
+ export declare const SCOPE_PARAM = "scope";
88
96
  /**
89
97
  * What a new record's reference says it starts with (`newRef(values)`), or nothing.
90
98
  *
@@ -92,6 +100,17 @@ export declare const WITH_PARAM = "with";
92
100
  * typed in the address bar — a value that is not a JSON object is not a start, never an error.
93
101
  */
94
102
  export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRecord;
103
+ /**
104
+ * The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
105
+ *
106
+ * Context: a picker that may offer only some records — the contacts of the chosen customer, the
107
+ * tenants a project is not shared with yet — opened the workspace's chooser on the WHOLE
108
+ * entity, and offered the rest. The cut travels in the reference, so it survives a reload; read
109
+ * from an address bar it is untyped, so it is read the way criteria reads a filter from outside
110
+ * (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
111
+ * OFFERED; the server still decides what may be stored.
112
+ */
113
+ export declare function scopeOfRef(ref: Pick<EntityRef, "params">): Expression | undefined;
95
114
  /** A write: its method and its path, `{id}` where the record's key goes. */
96
115
  export type WriteRoute = {
97
116
  method: Method;
@@ -108,6 +127,8 @@ export type EntityRoutes = {
108
127
  save?: string;
109
128
  preview?: string;
110
129
  draft?: string;
130
+ /** `"PUT /invoices/{id}/edit"`: the use case that answers sincpro_framework's `Edit`. */
131
+ edit?: string;
111
132
  history?: {
112
133
  route: string;
113
134
  type: string;
@@ -120,6 +141,19 @@ export type EntityRoutes = {
120
141
  };
121
142
  /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
122
143
  export declare function writeRoute(text: string): WriteRoute;
123
- /** The path with the record's key in place of `{id}`. */
124
- export declare function pathFor(route: WriteRoute, id?: string): string;
144
+ /**
145
+ * The path with the record's key in place of `{id}`, and every other `{name}` taken from the
146
+ * body's field of that name: `POST /projects/{id}/shares/{tenant_id}/revoke` with
147
+ * `{ tenant_id: "acme" }`.
148
+ *
149
+ * Context: sincpro_framework reads a path parameter as a field of the use case's DTO (its
150
+ * wire merges `{...body, ...path_params}`), so the body already names every key a route
151
+ * needs — a second argument for them would say the same thing twice. A key the body lacks is
152
+ * the screen's bug, said before anything is sent. Without an `id`, `{id}` stays: a create or a
153
+ * preview of a new record has none.
154
+ */
155
+ export declare function pathFor(route: WriteRoute, id?: string, body?: AnyRecord): string;
156
+ /** A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
157
+ * An empty value is no parameter — a filter left blank. */
158
+ export declare function listRoute(list: string, params?: Readonly<Record<string, string>>): string;
125
159
  export declare function entity<T extends AnyRecord = AnyRecord>(key: string, routes: EntityRoutes): Entity<T>;
@@ -1,3 +1,4 @@
1
+ import { readExpression } from "@sincpro/criteria";
1
2
  /**
2
3
  * The params that say what a reference without an id is for: `new` is the form of a record
3
4
  * that does not exist yet, `pick` is the list opened to choose one. Params, because they are
@@ -12,6 +13,9 @@ export const TRAIL_PARAM = "from";
12
13
  /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
13
14
  * a number), where a param per field would turn all of them into text. */
14
15
  export const WITH_PARAM = "with";
16
+ /** What a chooser may offer at all, as JSON: the picker's cut — its criteria, the keys it
17
+ * excludes, its named list's scope — that the list it opens ANDs under everything. */
18
+ export const SCOPE_PARAM = "scope";
15
19
  /**
16
20
  * What a new record's reference says it starts with (`newRef(values)`), or nothing.
17
21
  *
@@ -32,6 +36,27 @@ export function startingValuesOf(ref) {
32
36
  return {};
33
37
  }
34
38
  }
39
+ /**
40
+ * The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
41
+ *
42
+ * Context: a picker that may offer only some records — the contacts of the chosen customer, the
43
+ * tenants a project is not shared with yet — opened the workspace's chooser on the WHOLE
44
+ * entity, and offered the rest. The cut travels in the reference, so it survives a reload; read
45
+ * from an address bar it is untyped, so it is read the way criteria reads a filter from outside
46
+ * (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
47
+ * OFFERED; the server still decides what may be stored.
48
+ */
49
+ export function scopeOfRef(ref) {
50
+ const written = ref.params?.[SCOPE_PARAM];
51
+ if (written === undefined)
52
+ return undefined;
53
+ try {
54
+ return readExpression(JSON.parse(written));
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ }
35
60
  const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
36
61
  /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
37
62
  export function writeRoute(text) {
@@ -40,9 +65,35 @@ export function writeRoute(text) {
40
65
  throw new Error(`"${text}" is not "METHOD /path": a write says how it is sent`);
41
66
  return { method: method, path };
42
67
  }
43
- /** The path with the record's key in place of `{id}`. */
44
- export function pathFor(route, id) {
45
- return id === undefined ? route.path : route.path.replace("{id}", encodeURIComponent(id));
68
+ const PATH_KEY = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
69
+ /**
70
+ * The path with the record's key in place of `{id}`, and every other `{name}` taken from the
71
+ * body's field of that name: `POST /projects/{id}/shares/{tenant_id}/revoke` with
72
+ * `{ tenant_id: "acme" }`.
73
+ *
74
+ * Context: sincpro_framework reads a path parameter as a field of the use case's DTO (its
75
+ * wire merges `{...body, ...path_params}`), so the body already names every key a route
76
+ * needs — a second argument for them would say the same thing twice. A key the body lacks is
77
+ * the screen's bug, said before anything is sent. Without an `id`, `{id}` stays: a create or a
78
+ * preview of a new record has none.
79
+ */
80
+ export function pathFor(route, id, body) {
81
+ return route.path.replace(PATH_KEY, (whole, name) => {
82
+ if (name === "id")
83
+ return id === undefined ? whole : encodeURIComponent(id);
84
+ const value = body?.[name];
85
+ if (value === undefined || value === null || value === "")
86
+ throw new Error(`"${route.method} ${route.path}" needs "${name}" in the body`);
87
+ return encodeURIComponent(String(value));
88
+ });
89
+ }
90
+ /** A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
91
+ * An empty value is no parameter — a filter left blank. */
92
+ export function listRoute(list, params) {
93
+ const query = new URLSearchParams(Object.entries(params ?? {}).filter(([, value]) => value !== "")).toString();
94
+ if (query === "")
95
+ return list;
96
+ return `${list}${list.includes("?") ? "&" : "?"}${query}`;
46
97
  }
47
98
  export function entity(key, routes) {
48
99
  if (!/^[^:\s]+:[^:\s]+$/.test(key))
@@ -65,7 +116,7 @@ export function entity(key, routes) {
65
116
  : { [WITH_PARAM]: JSON.stringify(values) }),
66
117
  },
67
118
  }),
68
- chooserRef: (query) => ({
119
+ chooserRef: (query, scope) => ({
69
120
  domain,
70
121
  kind,
71
122
  params: {
@@ -73,6 +124,7 @@ export function entity(key, routes) {
73
124
  ...(query === undefined || query.trim() === ""
74
125
  ? {}
75
126
  : { [QUERY_PARAM]: query.trim() }),
127
+ ...(scope === undefined ? {} : { [SCOPE_PARAM]: JSON.stringify(scope) }),
76
128
  },
77
129
  }),
78
130
  list: routes.list,
@@ -82,6 +134,7 @@ export function entity(key, routes) {
82
134
  ...(routes.save === undefined ? {} : { save: writeRoute(routes.save) }),
83
135
  ...(routes.preview === undefined ? {} : { preview: writeRoute(routes.preview) }),
84
136
  ...(routes.draft === undefined ? {} : { draft: writeRoute(routes.draft) }),
137
+ ...(routes.edit === undefined ? {} : { edit: writeRoute(routes.edit) }),
85
138
  ...(routes.history === undefined ? {} : { history: routes.history }),
86
139
  summary: routes.summary ?? {},
87
140
  ...(routes.aggregate === undefined ? {} : { aggregate: routes.aggregate }),
@@ -1,4 +1,5 @@
1
1
  import { labelOf } from "@sincpro/criteria";
2
+ import { frameworkCopy } from "./copy.js";
2
3
  /** What every fact carries: what remains is what this fact says. */
3
4
  const ENVELOPE = new Set([
4
5
  "id",
@@ -24,7 +25,10 @@ export function historyOf(rows, meta, locale) {
24
25
  const label = row["label"];
25
26
  const word = typeof label === "string"
26
27
  ? label
27
- : ((locale ? label?.[locale] : undefined) ?? label?.["default"] ?? String(row["id"]));
28
+ : // A fact without a label is still a change; its id is not a word anyone reads.
29
+ ((locale ? label?.[locale] : undefined) ??
30
+ label?.["default"] ??
31
+ frameworkCopy().summary.recorded);
28
32
  const parts = Object.entries(row)
29
33
  .filter(([key]) => !ENVELOPE.has(key))
30
34
  .map(([key, value]) => [key, said(value)])
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A new record's key, minted where the record is born: a UUID v7 as 32 hex characters —
3
+ * sincpro_framework's `new_entity_id`.
4
+ *
5
+ * Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
6
+ * UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
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). The layout
9
+ * is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
10
+ * within the millisecond, the variant and 62 random bits — so ids minted here sort by when
11
+ * they were minted, like the server's, and ordering by `id` is still ordering by creation.
12
+ *
13
+ * newEntityId() // "019a4c2e7f1074a8b13fa739ccbdcd53"
14
+ */
15
+ export declare function newEntityId(now?: number): string;
16
+ /** A key that is a UUID v7 as sincpro_framework writes it: 32 hex, version 7, variant `10`. */
17
+ export declare function isEntityId(text: string): boolean;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A new record's key, minted where the record is born: a UUID v7 as 32 hex characters —
3
+ * sincpro_framework's `new_entity_id`.
4
+ *
5
+ * Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
6
+ * UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
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). The layout
9
+ * is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
10
+ * within the millisecond, the variant and 62 random bits — so ids minted here sort by when
11
+ * they were minted, like the server's, and ordering by `id` is still ordering by creation.
12
+ *
13
+ * newEntityId() // "019a4c2e7f1074a8b13fa739ccbdcd53"
14
+ */
15
+ const COUNTER_MAX = 0xfff;
16
+ let lastMillis = -1;
17
+ let counter = 0;
18
+ function randomBytes(count) {
19
+ return globalThis.crypto.getRandomValues(new Uint8Array(count));
20
+ }
21
+ function hex(value, digits) {
22
+ return value.toString(16).padStart(digits, "0");
23
+ }
24
+ export function newEntityId(now = Date.now()) {
25
+ // The clock never runs backwards for these ids: the same millisecond (or an earlier one, a
26
+ // clock moved back) counts up; a full counter borrows the next millisecond.
27
+ let millis = now;
28
+ if (millis <= lastMillis) {
29
+ millis = lastMillis;
30
+ counter += 1;
31
+ if (counter > COUNTER_MAX) {
32
+ millis += 1;
33
+ counter = 0;
34
+ }
35
+ }
36
+ else {
37
+ // A fresh millisecond starts the counter at a random point of its lower half: room to count.
38
+ const [high = 0, low = 0] = randomBytes(2);
39
+ counter = ((high << 8) | low) & 0x7ff;
40
+ }
41
+ lastMillis = millis;
42
+ const tail = randomBytes(8);
43
+ tail[0] = ((tail[0] ?? 0) & 0x3f) | 0x80; // the variant, `10`
44
+ return (hex(millis, 12) +
45
+ "7" + // the version
46
+ hex(counter, 3) +
47
+ Array.from(tail, (byte) => hex(byte, 2)).join(""));
48
+ }
49
+ /** A key that is a UUID v7 as sincpro_framework writes it: 32 hex, version 7, variant `10`. */
50
+ export function isEntityId(text) {
51
+ return /^[0-9a-f]{12}7[0-9a-f]{3}[89ab][0-9a-f]{15}$/.test(text);
52
+ }
@@ -6,9 +6,10 @@
6
6
  export { type CachedTransport, cachedTransport, type CacheOptions, } from "./cache.js";
7
7
  export { ENGLISH_FRAMEWORK_COPY, type FrameworkCopy, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
8
8
  export { type Advice, adviceAt, changesOf, creationOf, defaultsOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, lineStatesOf, missingOf, pathOf, type ServerFieldState, } from "./edit.js";
9
- export { type Entity, entity, type EntityRef, type EntityRoutes, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, startingValuesOf, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./entity.js";
9
+ export { type Entity, entity, type EntityRef, type EntityRoutes, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./entity.js";
10
10
  export { type FormLayout, formOf } from "./form.js";
11
11
  export { type HistoryEntry, historyOf } from "./history.js";
12
+ export { isEntityId, newEntityId } from "./ids.js";
12
13
  export { addingOf, type AddingRule, blankLine, type Declared, editableLines, type LineAdding, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
13
14
  export { defineList, type GroupLevel, isList, type ListDefinition, type ListSpec, type NamedFilter, scopeOf, } from "./list.js";
14
15
  export { lookupOf, type LookupOption } from "./lookup.js";
@@ -6,9 +6,10 @@
6
6
  export { cachedTransport, } from "./cache.js";
7
7
  export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
8
8
  export { adviceAt, changesOf, creationOf, defaultsOf, errorAt, errorsByField, fieldStateOf, lineStatesOf, missingOf, pathOf, } from "./edit.js";
9
- export { entity, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
9
+ export { entity, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
10
10
  export { formOf } from "./form.js";
11
11
  export { historyOf } from "./history.js";
12
+ export { isEntityId, newEntityId } from "./ids.js";
12
13
  export { addingOf, blankLine, editableLines, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
13
14
  export { defineList, isList, scopeOf, } from "./list.js";
14
15
  export { lookupOf } from "./lookup.js";
@@ -4,11 +4,12 @@
4
4
  * keeps it that way.
5
5
  */
6
6
  export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
+ export { type ListScope, ListScopeProvider, useListScope, } from "./scope.js";
7
8
  export { type CommandState, type Rehearsal, useCommand, } from "./useCommand.js";
8
9
  export { type Groups, useGroups } from "./useGroups.js";
9
10
  export { useHistory } from "./useHistory.js";
10
11
  export { type Listing, type ListingOptions, type Paging, useListing, } from "./useListing.js";
11
- export { type Lookup, useLookup } from "./useLookup.js";
12
+ export { excluding, type Lookup, useLookup } from "./useLookup.js";
12
13
  export { type PivotAxes, type PivotReading, usePivot, } from "./usePivot.js";
13
14
  export { type Editing, type RecordReading, type RecordState, useRecord, } from "./useRecord.js";
14
15
  export { useRelated } from "./useRelated.js";
@@ -4,11 +4,12 @@
4
4
  * keeps it that way.
5
5
  */
6
6
  export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
+ export { ListScopeProvider, useListScope, } from "./scope.js";
7
8
  export { useCommand, } from "./useCommand.js";
8
9
  export { useGroups } from "./useGroups.js";
9
10
  export { useHistory } from "./useHistory.js";
10
11
  export { useListing, } from "./useListing.js";
11
- export { useLookup } from "./useLookup.js";
12
+ export { excluding, useLookup } from "./useLookup.js";
12
13
  export { usePivot, } from "./usePivot.js";
13
14
  export { useRecord, } from "./useRecord.js";
14
15
  export { useRelated } from "./useRelated.js";