@sincpro/web-framework 0.4.2 → 1.1.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 (70) hide show
  1. package/README.md +82 -41
  2. package/dist/codegen/cli.d.ts +2 -0
  3. package/dist/codegen/cli.js +82 -0
  4. package/dist/codegen/client.d.ts +14 -0
  5. package/dist/codegen/client.js +178 -0
  6. package/dist/codegen/domain.d.ts +14 -0
  7. package/dist/codegen/domain.js +195 -0
  8. package/dist/codegen/entities.d.ts +14 -0
  9. package/dist/codegen/entities.js +158 -0
  10. package/dist/codegen/index.d.ts +11 -0
  11. package/dist/codegen/index.js +9 -0
  12. package/dist/codegen/metamodel.d.ts +89 -0
  13. package/dist/codegen/metamodel.js +1 -0
  14. package/dist/codegen/names.d.ts +40 -0
  15. package/dist/codegen/names.js +114 -0
  16. package/dist/codegen/rest.d.ts +31 -0
  17. package/dist/codegen/rest.js +27 -0
  18. package/dist/core/cache.js +7 -0
  19. package/dist/core/contract.d.ts +34 -0
  20. package/dist/core/contract.js +41 -0
  21. package/dist/core/discovery.d.ts +47 -0
  22. package/dist/core/discovery.js +68 -0
  23. package/dist/core/edit.d.ts +35 -6
  24. package/dist/core/edit.js +57 -4
  25. package/dist/core/entity.d.ts +77 -9
  26. package/dist/core/entity.js +51 -6
  27. package/dist/core/index.d.ts +5 -4
  28. package/dist/core/index.js +5 -4
  29. package/dist/core/memory.d.ts +3 -0
  30. package/dist/core/memory.js +9 -0
  31. package/dist/core/meta.d.ts +7 -0
  32. package/dist/core/meta.js +1 -1
  33. package/dist/core/metas.d.ts +4 -5
  34. package/dist/core/relation.d.ts +11 -1
  35. package/dist/core/relation.js +30 -2
  36. package/dist/core/rest.d.ts +23 -0
  37. package/dist/core/rest.js +78 -3
  38. package/dist/core/schema.d.ts +5 -12
  39. package/dist/core/trail.js +1 -4
  40. package/dist/core/transport.d.ts +11 -0
  41. package/dist/core/transport.js +9 -0
  42. package/dist/react/index.d.ts +2 -1
  43. package/dist/react/index.js +1 -0
  44. package/dist/react/useCommand.d.ts +15 -5
  45. package/dist/react/useCommand.js +7 -4
  46. package/dist/react/useGroups.js +1 -2
  47. package/dist/react/useHistory.js +1 -1
  48. package/dist/react/useListing.d.ts +5 -4
  49. package/dist/react/useListing.js +9 -8
  50. package/dist/react/useLookup.js +2 -3
  51. package/dist/react/useNameOf.d.ts +13 -0
  52. package/dist/react/useNameOf.js +44 -0
  53. package/dist/react/usePivot.js +0 -1
  54. package/dist/react/useRecord.d.ts +2 -1
  55. package/dist/react/useRecord.js +15 -3
  56. package/dist/react/useRelated.js +2 -2
  57. package/dist/web/list/EntityList.d.ts +5 -4
  58. package/dist/web/list/EntityList.js +1 -1
  59. package/dist/web/list/EntitySearchBar.js +2 -2
  60. package/dist/web/list/presentation.d.ts +3 -3
  61. package/dist/web/list/presentation.js +1 -0
  62. package/dist/web/list/rowCommands.d.ts +16 -12
  63. package/dist/web/list/rowCommands.js +3 -2
  64. package/dist/web/list/search.js +1 -1
  65. package/dist/web/record/CommandButton.d.ts +9 -6
  66. package/dist/web/record/edit.js +19 -7
  67. package/dist/web/record/lines.js +23 -10
  68. package/dist/web/record/opening.js +1 -1
  69. package/dist/web/workspace/composer.js +1 -4
  70. package/package.json +18 -7
@@ -0,0 +1,31 @@
1
+ import type { Metamodel, Operation } from "./metamodel.js";
2
+ /**
3
+ * How REST reaches each operation of a contract, as the generated client and entities write it.
4
+ *
5
+ * Context: the export names each path whole (`/v1/issues/{issue_id}`), version included, while
6
+ * an application's transport already prepends it (`restTransport({ base: "/v1" })`). `base`
7
+ * takes it off every path, and a path outside it is refused — a client written with half its
8
+ * routes under the wrong base would fail one call at a time.
9
+ */
10
+ export type GenerateOptions = {
11
+ /** The first part of every entity's key: `project` makes `project:issue`. The contract's
12
+ * `alias` by default. */
13
+ domain?: string;
14
+ /** What every REST path starts with and the transport prepends: `/v1`. */
15
+ base?: string;
16
+ };
17
+ export type Reached = {
18
+ method: string;
19
+ /** The path under `base`, `{field}` where a field of the input goes. */
20
+ path: string;
21
+ /** The fields of the input the path carries. */
22
+ fields: readonly string[];
23
+ };
24
+ /** What a transport can send: GET is read by `list` (a page) or `one` (a record) only. */
25
+ export declare const WRITES: Set<string>;
26
+ export declare function restOf(metamodel: Metamodel, identity: string, options: GenerateOptions): Reached | undefined;
27
+ /**
28
+ * The one entity a read belongs to: its only entity, or — when it concerns several — the one
29
+ * whose model its answer carries. `undefined` when that still leaves more than one.
30
+ */
31
+ export declare function ownerOf(metamodel: Metamodel, operation: Operation): string | undefined;
@@ -0,0 +1,27 @@
1
+ /** What a transport can send: GET is read by `list` (a page) or `one` (a record) only. */
2
+ export const WRITES = new Set(["POST", "PUT", "PATCH", "DELETE"]);
3
+ export function restOf(metamodel, identity, options) {
4
+ const binding = metamodel.bindings?.rest?.[identity];
5
+ if (binding === undefined)
6
+ return undefined;
7
+ const base = options.base ?? "";
8
+ const under = base === "" || binding.path === base || binding.path.startsWith(`${base}/`);
9
+ if (!under)
10
+ throw new Error(`${identity} is at ${binding.path}, outside the base ${base}`);
11
+ return {
12
+ method: binding.method.toUpperCase(),
13
+ path: binding.path.slice(base.length) || "/",
14
+ fields: binding.path_fields,
15
+ };
16
+ }
17
+ /**
18
+ * The one entity a read belongs to: its only entity, or — when it concerns several — the one
19
+ * whose model its answer carries. `undefined` when that still leaves more than one.
20
+ */
21
+ export function ownerOf(metamodel, operation) {
22
+ if (operation.entities.length === 1)
23
+ return operation.entities[0];
24
+ const answer = JSON.stringify(operation.output ?? {});
25
+ const carried = operation.entities.filter((one) => one in metamodel.models && answer.includes(`"#/models/${one}"`));
26
+ return carried.length === 1 ? carried[0] : undefined;
27
+ }
@@ -52,6 +52,13 @@ export function cachedTransport(transport, options = {}) {
52
52
  one(route, signal) {
53
53
  return remembered(`one ${route}`, () => transport.one(route, signal));
54
54
  },
55
+ // A read of the context's own (`GET /me`) is not an entity's: no write forgets it, so it is
56
+ // never kept — it goes to the server every time.
57
+ ...(transport.read === undefined
58
+ ? {}
59
+ : {
60
+ read: (route, signal) => transport.read(route, signal),
61
+ }),
55
62
  async send(method, route, body, signal, sending) {
56
63
  // A preview writes nothing; anything else may have changed what was read.
57
64
  const preview = route.endsWith("/preview");
@@ -0,0 +1,34 @@
1
+ import { type Contract, type Meta } from "@sincpro/criteria";
2
+ /**
3
+ * A bounded context's client contract, as the application keeps it: the snapshot
4
+ * `sincpro-web generate` writes (`contract.json`), or the document a service serves
5
+ * (`GET /client-contract/<context>.json`). Only its models are read here.
6
+ *
7
+ * Context: the generated entities are keyed `<domain>:<kind>` (`project:issue`) — the key the
8
+ * workspace refers to them by and the meta store keeps their definitions under —, so the rule
9
+ * that turns a model's name into its kind lives once, here, and both the generator and the
10
+ * preload read it.
11
+ */
12
+ export type ClientContract = {
13
+ models: Readonly<Record<string, Contract>>;
14
+ $defs?: Readonly<Record<string, Contract>>;
15
+ };
16
+ /** `ProjectEvent` → `project_event`: the kind in an entity's key. */
17
+ export declare function kindOf(model: string): string;
18
+ /** The key of a model's entity: `entityKeyOf("project", "ProjectEvent")` → `"project:project_event"`. */
19
+ export declare function entityKeyOf(domain: string, model: string): string;
20
+ /**
21
+ * The version of every entity of `contract`, by its model's name — what `restTransport`
22
+ * compares each answer with (`snapshot`) to say when the generated code is behind the server.
23
+ *
24
+ * restTransport({ base: "/v1", snapshot: versionsOf(contract), onVersionDrift: warn })
25
+ */
26
+ export declare function versionsOf(contract: ClientContract): Record<string, string>;
27
+ /**
28
+ * The definition of every model of `contract`, by its entity's key — what `FrameworkProvider
29
+ * metas` preloads, so the first screen draws its labels with no request at all. The transport
30
+ * still reads the live definition and asks again when an answer says another version.
31
+ *
32
+ * <FrameworkProvider transport={transport} metas={metasOf(contract, "project")}>
33
+ */
34
+ export declare function metasOf(contract: ClientContract, domain: string): Record<string, Meta>;
@@ -0,0 +1,41 @@
1
+ import { metaFromContract } from "@sincpro/criteria";
2
+ /** `ProjectEvent` → `project_event`: the kind in an entity's key. */
3
+ export function kindOf(model) {
4
+ return model
5
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
6
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1_$2")
7
+ .toLowerCase();
8
+ }
9
+ /** The key of a model's entity: `entityKeyOf("project", "ProjectEvent")` → `"project:project_event"`. */
10
+ export function entityKeyOf(domain, model) {
11
+ return `${domain}:${kindOf(model)}`;
12
+ }
13
+ /**
14
+ * The version of every entity of `contract`, by its model's name — what `restTransport`
15
+ * compares each answer with (`snapshot`) to say when the generated code is behind the server.
16
+ *
17
+ * restTransport({ base: "/v1", snapshot: versionsOf(contract), onVersionDrift: warn })
18
+ */
19
+ export function versionsOf(contract) {
20
+ return Object.fromEntries(Object.entries(contract.models).flatMap(([name, model]) => {
21
+ const version = model["x-sincpro"]?.version;
22
+ return model["x-sincpro"]?.identity != null && typeof version === "string"
23
+ ? [[name, version]]
24
+ : [];
25
+ }));
26
+ }
27
+ /**
28
+ * The definition of every model of `contract`, by its entity's key — what `FrameworkProvider
29
+ * metas` preloads, so the first screen draws its labels with no request at all. The transport
30
+ * still reads the live definition and asks again when an answer says another version.
31
+ *
32
+ * <FrameworkProvider transport={transport} metas={metasOf(contract, "project")}>
33
+ */
34
+ export function metasOf(contract, domain) {
35
+ // A related model, or a value a record holds, is pointed at by its name (`#/models/Run`).
36
+ const related = { ...(contract.$defs ?? {}), ...contract.models };
37
+ return Object.fromEntries(Object.entries(contract.models)
38
+ // Only an entity has a key of its own; a value it holds is described inside it.
39
+ .filter(([, model]) => model["x-sincpro"]?.identity != null)
40
+ .map(([name, model]) => [entityKeyOf(domain, name), metaFromContract(model, related)]));
41
+ }
@@ -0,0 +1,47 @@
1
+ import { type Meta } from "@sincpro/criteria";
2
+ /**
3
+ * The discovery document of a bounded context, as far as this reads it: its paths, each
4
+ * operation with the entities it belongs to, and the published contract of every model.
5
+ *
6
+ * Context: sincpro_framework describes a model once — JSON Schema with `x-sincpro`, under the
7
+ * document's `components.schemas` — and every read answers only the version of it
8
+ * (`model_version`). So the definition a list, a form and a select are built from is read here,
9
+ * once, and asked for again only when an answer says another version.
10
+ */
11
+ export type DiscoveryDocument = {
12
+ paths?: Readonly<Record<string, Readonly<Record<string, DiscoveryOperation>>>>;
13
+ components?: {
14
+ schemas?: Readonly<Record<string, DocumentSchema>>;
15
+ };
16
+ };
17
+ export type DiscoveryOperation = {
18
+ "x-sincpro-entities"?: readonly string[];
19
+ responses?: Readonly<Record<string, {
20
+ content?: Readonly<Record<string, {
21
+ schema?: DocumentSchema;
22
+ }>>;
23
+ }>>;
24
+ };
25
+ type DocumentSchema = {
26
+ $ref?: string;
27
+ items?: DocumentSchema;
28
+ anyOf?: readonly DocumentSchema[];
29
+ properties?: Readonly<Record<string, DocumentSchema>>;
30
+ "x-sincpro"?: {
31
+ entity?: string;
32
+ version?: string;
33
+ };
34
+ };
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.
38
+ *
39
+ * modelAt(published, "/v1/projects/p1", "get") // "Project"
40
+ */
41
+ export declare function modelAt(published: DiscoveryDocument, path: string, method: string): string | undefined;
42
+ /** The definition of the model named `name`, read from its contract, and its version. */
43
+ export declare function definitionOf(published: DiscoveryDocument, name: string): {
44
+ meta: Meta;
45
+ version: string | null;
46
+ } | undefined;
47
+ export {};
@@ -0,0 +1,68 @@
1
+ import { metaFromContract, versionOf } from "@sincpro/criteria";
2
+ function nameOfRef(ref) {
3
+ return ref === undefined ? undefined : ref.slice(ref.lastIndexOf("/") + 1);
4
+ }
5
+ /** Whether a document path (`/v1/projects/{id}`) answers a request path (`/v1/projects/p1`). */
6
+ function answers(template, path) {
7
+ const pattern = template
8
+ .split("/")
9
+ .map((part) => /^\{[^}]+\}$/.test(part) ? "[^/]+" : part.replace(/[.*+?^$()|[\]\\]/g, "\\$&"))
10
+ .join("/");
11
+ return new RegExp(`^${pattern}$`).test(path);
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()) {
15
+ if (schema === undefined)
16
+ return undefined;
17
+ const named = nameOfRef(schema.$ref);
18
+ if (named !== undefined) {
19
+ if (seen.has(named))
20
+ return undefined;
21
+ seen.add(named);
22
+ 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;
36
+ }
37
+ return undefined;
38
+ }
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.
42
+ *
43
+ * modelAt(published, "/v1/projects/p1", "get") // "Project"
44
+ */
45
+ export function modelAt(published, path, method) {
46
+ const schemas = published.components?.schemas ?? {};
47
+ for (const [template, item] of Object.entries(published.paths ?? {})) {
48
+ if (!answers(template, path))
49
+ continue;
50
+ const operation = item[method.toLowerCase()];
51
+ if (operation === undefined)
52
+ 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);
58
+ }
59
+ return undefined;
60
+ }
61
+ /** The definition of the model named `name`, read from its contract, and its version. */
62
+ export function definitionOf(published, name) {
63
+ const schemas = (published.components?.schemas ?? {});
64
+ const contract = schemas[name];
65
+ if (contract?.["x-sincpro"] === undefined)
66
+ return undefined;
67
+ return { meta: metaFromContract(contract, schemas), version: versionOf(contract) };
68
+ }
@@ -18,23 +18,52 @@ export type FieldState = {
18
18
  };
19
19
  /**
20
20
  * What a server preview said about a field. A list of records — an invoice's lines — carries
21
- * each one's own in `items`, in the order the form sent them (sincpro_framework's
22
- * `FieldState.items`).
21
+ * each one's own in `items`, by the line: its identity, or its position for a line that has
22
+ * none (sincpro_framework's `FieldState.items`).
23
23
  */
24
24
  export type ServerFieldState = Partial<FieldState> & {
25
- items?: readonly Readonly<Record<string, ServerFieldState>>[];
25
+ items?: Readonly<Record<string, Readonly<Record<string, ServerFieldState>>>>;
26
26
  };
27
27
  export type FieldStates = Readonly<Record<string, ServerFieldState>>;
28
28
  /** What the server's preview warned about, pointing where it belongs (`path`: the field, or a
29
- * line's cell — `["lines", 1, "price"]`). It refuses nothing. sincpro_framework's warning. */
29
+ * line's cell — `["lines", "0192…", "price"]`, the line by its identity, by its position when
30
+ * it has none). It refuses nothing. sincpro_framework's warning. */
30
31
  export type Advice = {
31
32
  message: string;
32
33
  field?: string | null;
33
34
  path?: readonly (string | number)[];
35
+ /** The rule that said it (`Sale.delivery_when_confirmed`), when one did. */
36
+ rule?: string | null;
37
+ /** A rule the save enforces (`@check`): the save will be refused while it holds. */
38
+ blocks_save?: boolean;
34
39
  };
40
+ /**
41
+ * What a change of `name` moves, computed here when every field it reaches says how
42
+ * (`computes`, the formula the server published): each in the order the server runs them, a
43
+ * computation of a computation reading the one before. `undefined` when one of them does not
44
+ * say — the server's preview answers it — or the change reaches nothing.
45
+ *
46
+ * computedLocally(saleMeta, { subtotal: "25.30", discount: "1.5" }, "discount")
47
+ * -> { total: "22.105" }
48
+ */
49
+ export declare function computedLocally(meta: Meta | null | undefined, values: AnyRecord, name: string): AnyRecord | undefined;
50
+ /**
51
+ * Whether a change of `name` needs the server's preview: when the model says what each change
52
+ * reaches (`affects`, `judged_by` — sincpro_framework publishes them in the contract), only a
53
+ * field that reaches something does; a model that says nothing of it is always asked.
54
+ */
55
+ export declare function needsPreview(meta: Meta | null | undefined, name: string): boolean;
35
56
  export declare function fieldStateOf(meta: Meta | null | undefined, name: string, values: AnyRecord, fromServer?: FieldStates): FieldState;
36
- /** Each line's states of a list of records, as the server said them — by position. */
37
- export declare function lineStatesOf(fromServer: FieldStates | undefined, name: string): readonly FieldStates[];
57
+ /**
58
+ * The states the server said of one line of a list of records: under the line's identity —
59
+ * the same line wherever it moved — or under its position when it has none.
60
+ */
61
+ export declare function lineStatesOf(fromServer: FieldStates | undefined, name: string, line: AnyRecord | undefined, index: number, identity: string): FieldStates | undefined;
62
+ /**
63
+ * Where the server names a line in a path, most specific first: `lines/0192…` by its identity,
64
+ * `lines/2` by its position — an error, a warning and a state are looked for under each.
65
+ */
66
+ export declare function linePlacesOf(name: string, line: AnyRecord, index: number, identity: string): string[];
38
67
  /** The fields whose value differs from the record's — what a save or a draft sends. */
39
68
  export declare function changesOf(record: AnyRecord, values: AnyRecord): AnyRecord;
40
69
  /** What is missing before it can be saved: a required, visible, editable field left empty. */
package/dist/core/edit.js CHANGED
@@ -1,4 +1,41 @@
1
- import { matches, } from "@sincpro/criteria";
1
+ import { matches, valueOf, } from "@sincpro/criteria";
2
+ /**
3
+ * What a change of `name` moves, computed here when every field it reaches says how
4
+ * (`computes`, the formula the server published): each in the order the server runs them, a
5
+ * computation of a computation reading the one before. `undefined` when one of them does not
6
+ * say — the server's preview answers it — or the change reaches nothing.
7
+ *
8
+ * computedLocally(saleMeta, { subtotal: "25.30", discount: "1.5" }, "discount")
9
+ * -> { total: "22.105" }
10
+ */
11
+ export function computedLocally(meta, values, name) {
12
+ const reached = meta?.fields[name]?.affects ?? [];
13
+ if (meta == null || reached.length === 0)
14
+ return undefined;
15
+ const working = { ...values };
16
+ const moved = {};
17
+ for (const one of reached) {
18
+ const formula = meta.fields[one]?.computes;
19
+ if (formula === undefined || formula === null)
20
+ return undefined;
21
+ working[one] = valueOf(formula, working);
22
+ moved[one] = working[one];
23
+ }
24
+ return moved;
25
+ }
26
+ /**
27
+ * Whether a change of `name` needs the server's preview: when the model says what each change
28
+ * reaches (`affects`, `judged_by` — sincpro_framework publishes them in the contract), only a
29
+ * field that reaches something does; a model that says nothing of it is always asked.
30
+ */
31
+ export function needsPreview(meta, name) {
32
+ const fields = Object.values(meta?.fields ?? {});
33
+ const says = fields.some((one) => one.affects !== undefined || one.judged_by !== undefined);
34
+ if (!says)
35
+ return true;
36
+ const field = meta?.fields[name];
37
+ return (field?.affects?.length ?? 0) > 0 || (field?.judged_by?.length ?? 0) > 0;
38
+ }
2
39
  function holds(values, condition, meta) {
3
40
  if (condition === null || condition === undefined)
4
41
  return false;
@@ -19,9 +56,25 @@ export function fieldStateOf(meta, name, values, fromServer) {
19
56
  const { items: _lines, ...server } = fromServer?.[name] ?? {};
20
57
  return { ...own, ...server };
21
58
  }
22
- /** Each line's states of a list of records, as the server said them — by position. */
23
- export function lineStatesOf(fromServer, name) {
24
- return fromServer?.[name]?.items ?? [];
59
+ /**
60
+ * The states the server said of one line of a list of records: under the line's identity —
61
+ * the same line wherever it moved — or under its position when it has none.
62
+ */
63
+ export function lineStatesOf(fromServer, name, line, index, identity) {
64
+ const items = fromServer?.[name]?.items ?? {};
65
+ const own = line?.[identity];
66
+ const named = own === undefined || own === null || own === "" ? undefined : items[String(own)];
67
+ return named ?? items[String(index)];
68
+ }
69
+ /**
70
+ * Where the server names a line in a path, most specific first: `lines/0192…` by its identity,
71
+ * `lines/2` by its position — an error, a warning and a state are looked for under each.
72
+ */
73
+ export function linePlacesOf(name, line, index, identity) {
74
+ const own = line[identity];
75
+ return own === undefined || own === null || own === ""
76
+ ? [`${name}/${index}`]
77
+ : [`${name}/${String(own)}`, `${name}/${index}`];
25
78
  }
26
79
  /** The fields whose value differs from the record's — what a save or a draft sends. */
27
80
  export function changesOf(record, values) {
@@ -1,6 +1,22 @@
1
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
+ /**
5
+ * What each Command of an entity is sent with, by its name: `{ send: { message: string } }`.
6
+ *
7
+ * Context: the default is any name and any body — every entity declared before Commands had
8
+ * types keeps compiling. A typed entity is still one of these (`Entity<T, C>` is assignable to
9
+ * `Entity<T>`), so every piece that takes an entity takes it.
10
+ */
11
+ export type CommandBodies = Readonly<Record<string, AnyRecord>>;
12
+ /**
13
+ * What each Command of an entity answers, by its name: `{ send: { run_id: string } }` — what a
14
+ * generated entity reads off each operation's `output`.
15
+ *
16
+ * Context: `useCommand(issues, "send").run(…)` returns it with no type argument written; a
17
+ * Command it does not name answers `unknown`, as every Command did before.
18
+ */
19
+ export type CommandAnswers = Readonly<Record<string, unknown>>;
4
20
  /**
5
21
  * Everything a screen needs to know about where an entity lives on the server, declared once.
6
22
  *
@@ -20,8 +36,14 @@ import type { Method } from "./transport.js";
20
36
  * commands: { confirm: "POST /invoices/{id}/confirm", cancel: "POST /invoices/{id}/cancel" },
21
37
  * history: { route: "/billing-events", type: "Invoice" },
22
38
  * });
39
+ *
40
+ * Its Commands may be typed too — what each one is sent with, by name (`CommandBodies`), and
41
+ * what each one answers (`CommandAnswers`) — and then `useCommand` and `CommandButton` take
42
+ * only those names and those bodies, and give back that answer:
43
+ *
44
+ * entity<Issue, { send: { message: string } }, { send: { run_id: string } }>(…)
23
45
  */
24
- export type Entity<T extends AnyRecord = AnyRecord> = {
46
+ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = CommandBodies, A extends CommandAnswers = CommandAnswers> = {
25
47
  /** `domain:kind`, e.g. `"billing:invoice"`. */
26
48
  key: string;
27
49
  domain: string;
@@ -42,7 +64,7 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
42
64
  /** The route of one record. */
43
65
  one: (id: string) => string;
44
66
  /** Its Commands, by name. */
45
- commands: Readonly<Record<string, WriteRoute>>;
67
+ commands: Readonly<Record<keyof C & string, WriteRoute>>;
46
68
  /** How a new record is created: the list's own route, usually. */
47
69
  create?: WriteRoute;
48
70
  /** How an edit is saved: the record's own route with `{id}`. */
@@ -68,6 +90,10 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
68
90
  aggregate?: string;
69
91
  /** Only carries the record type; never read. */
70
92
  readonly _record?: T;
93
+ /** Only carries what each Command is sent with; never read. */
94
+ readonly _commands?: C;
95
+ /** Only carries what each Command answers; never read. */
96
+ readonly _answers?: A;
71
97
  };
72
98
  /** A composer `ResourceRef`, structurally: `core/` does not import the composer. */
73
99
  export type EntityRef = {
@@ -111,17 +137,36 @@ export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRec
111
137
  * OFFERED; the server still decides what may be stored.
112
138
  */
113
139
  export declare function scopeOfRef(ref: Pick<EntityRef, "params">): Expression | undefined;
114
- /** A write: its method and its path, `{id}` where the record's key goes. */
140
+ /**
141
+ * A write: its method and its path, `{id}` where the record's key goes. A Command may also say
142
+ * which field of its body names the record it runs on (`target`: `issue_id`), and then the
143
+ * record's id is written there when it is sent (`bodyFor`).
144
+ */
115
145
  export type WriteRoute = {
116
146
  method: Method;
117
147
  path: string;
148
+ target?: string;
118
149
  };
119
- export type EntityRoutes = {
150
+ /**
151
+ * A Command's route: `"POST /invoices/{id}/confirm"`, or, when its body names the record —
152
+ * sincpro_framework's `targets`, what a generated entity declares —, the route and that field:
153
+ * `{ route: "POST /issues", target: "project_id" }`.
154
+ */
155
+ export type CommandRoute = string | {
156
+ route: string;
157
+ target: string;
158
+ };
159
+ /** Each Command's route, by name. Typed Commands MUST each have their route — a name a screen
160
+ * may run with nowhere to send it is caught here, not on the click. */
161
+ type CommandRoutes<C extends CommandBodies> = string extends keyof C ? {
162
+ commands?: Readonly<Record<string, CommandRoute>>;
163
+ } : {
164
+ commands: Readonly<Record<keyof C & string, CommandRoute>>;
165
+ };
166
+ export type EntityRoutes<C extends CommandBodies = CommandBodies> = CommandRoutes<C> & {
120
167
  list: string;
121
168
  /** With `{id}` where the key goes. Without it, `<list>/<id>` — sincpro_framework's convention. */
122
169
  one?: string;
123
- /** `"POST /invoices/{id}/confirm"`, by name. */
124
- commands?: Readonly<Record<string, string>>;
125
170
  /** `"POST /invoices"`: where a new record goes. */
126
171
  create?: string;
127
172
  save?: string;
@@ -153,7 +198,30 @@ export declare function writeRoute(text: string): WriteRoute;
153
198
  * preview of a new record has none.
154
199
  */
155
200
  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. */
201
+ /**
202
+ * What a Command of a record is sent with: the body as given, and — when its route says which
203
+ * field names the record (`target`) — the record's id in that field.
204
+ *
205
+ * bodyFor({ method: "POST", path: "/issues", target: "project_id" }, "p1", { title: "x" })
206
+ * -> { title: "x", project_id: "p1" }
207
+ *
208
+ * Context: sincpro_framework says, per operation, which input field holds the key of each
209
+ * entity it runs on (`targets`). A path that carries it (`/issues/{issue_id}/messages`) and a
210
+ * body that carries it (`POST /issues` with `project_id`) are the same thing to the server — a
211
+ * path parameter is read as a field of the DTO — so it goes in the body, and `pathFor` takes it
212
+ * from there. Without an id (a Command that creates) the body is sent as it is.
213
+ */
214
+ export declare function bodyFor(route: WriteRoute, id: string | undefined, body: AnyRecord): AnyRecord;
215
+ /**
216
+ * A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
217
+ * An empty value is no parameter — a filter left blank. A list under a record names its key in
218
+ * the path (`/tenants/{tenant_id}/members`): that parameter fills it, and only the rest goes in
219
+ * the query.
220
+ *
221
+ * Context: sincpro_framework reads a path parameter as a field of the search's DTO, the same
222
+ * field a query parameter would fill, so the screen gives them all as one set of parameters. A
223
+ * key the path needs and the parameters lack is the screen's bug, said before anything is sent.
224
+ */
158
225
  export declare function listRoute(list: string, params?: Readonly<Record<string, string>>): string;
159
- export declare function entity<T extends AnyRecord = AnyRecord>(key: string, routes: EntityRoutes): Entity<T>;
226
+ 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>;
227
+ export {};
@@ -87,13 +87,54 @@ export function pathFor(route, id, body) {
87
87
  return encodeURIComponent(String(value));
88
88
  });
89
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. */
90
+ /**
91
+ * What a Command of a record is sent with: the body as given, and — when its route says which
92
+ * field names the record (`target`) — the record's id in that field.
93
+ *
94
+ * bodyFor({ method: "POST", path: "/issues", target: "project_id" }, "p1", { title: "x" })
95
+ * -> { title: "x", project_id: "p1" }
96
+ *
97
+ * Context: sincpro_framework says, per operation, which input field holds the key of each
98
+ * entity it runs on (`targets`). A path that carries it (`/issues/{issue_id}/messages`) and a
99
+ * body that carries it (`POST /issues` with `project_id`) are the same thing to the server — a
100
+ * path parameter is read as a field of the DTO — so it goes in the body, and `pathFor` takes it
101
+ * from there. Without an id (a Command that creates) the body is sent as it is.
102
+ */
103
+ export function bodyFor(route, id, body) {
104
+ if (route.target === undefined || id === undefined || id === "")
105
+ return body;
106
+ return { ...body, [route.target]: id };
107
+ }
108
+ /** A Command's route as declared: a `"METHOD /path"`, or that and the field naming its record. */
109
+ function commandRoute(declared) {
110
+ if (typeof declared === "string")
111
+ return writeRoute(declared);
112
+ return { ...writeRoute(declared.route), target: declared.target };
113
+ }
114
+ /**
115
+ * A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
116
+ * An empty value is no parameter — a filter left blank. A list under a record names its key in
117
+ * the path (`/tenants/{tenant_id}/members`): that parameter fills it, and only the rest goes in
118
+ * the query.
119
+ *
120
+ * Context: sincpro_framework reads a path parameter as a field of the search's DTO, the same
121
+ * field a query parameter would fill, so the screen gives them all as one set of parameters. A
122
+ * key the path needs and the parameters lack is the screen's bug, said before anything is sent.
123
+ */
92
124
  export function listRoute(list, params) {
93
- const query = new URLSearchParams(Object.entries(params ?? {}).filter(([, value]) => value !== "")).toString();
125
+ const given = params ?? {};
126
+ const placed = new Set();
127
+ const path = list.replace(PATH_KEY, (_whole, name) => {
128
+ const value = given[name];
129
+ if (value === undefined || value === "")
130
+ throw new Error(`the list "${list}" needs "${name}" in its parameters`);
131
+ placed.add(name);
132
+ return encodeURIComponent(value);
133
+ });
134
+ const query = new URLSearchParams(Object.entries(given).filter(([name, value]) => value !== "" && !placed.has(name))).toString();
94
135
  if (query === "")
95
- return list;
96
- return `${list}${list.includes("?") ? "&" : "?"}${query}`;
136
+ return path;
137
+ return `${path}${path.includes("?") ? "&" : "?"}${query}`;
97
138
  }
98
139
  export function entity(key, routes) {
99
140
  if (!/^[^:\s]+:[^:\s]+$/.test(key))
@@ -129,7 +170,11 @@ export function entity(key, routes) {
129
170
  }),
130
171
  list: routes.list,
131
172
  one: (id) => template.replace("{id}", encodeURIComponent(id)),
132
- commands: Object.fromEntries(Object.entries(routes.commands ?? {}).map(([name, text]) => [name, writeRoute(text)])),
173
+ // Built from exactly the names `routes.commands` was typed with.
174
+ commands: Object.fromEntries(Object.entries(routes.commands ?? {}).map(([name, declared]) => [
175
+ name,
176
+ commandRoute(declared),
177
+ ])),
133
178
  ...(routes.create === undefined ? {} : { create: writeRoute(routes.create) }),
134
179
  ...(routes.save === undefined ? {} : { save: writeRoute(routes.save) }),
135
180
  ...(routes.preview === undefined ? {} : { preview: writeRoute(routes.preview) }),
@@ -4,9 +4,10 @@
4
4
  * `make doctor` keeps it that way.
5
5
  */
6
6
  export { type CachedTransport, cachedTransport, type CacheOptions, } from "./cache.js";
7
+ export { type ClientContract, entityKeyOf, metasOf, versionsOf, } from "./contract.js";
7
8
  export { ENGLISH_FRAMEWORK_COPY, type FrameworkCopy, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
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, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./entity.js";
9
+ export { type Advice, adviceAt, changesOf, computedLocally, creationOf, defaultsOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, type ServerFieldState, } from "./edit.js";
10
+ export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, 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
11
  export { type FormLayout, formOf } from "./form.js";
11
12
  export { type HistoryEntry, historyOf } from "./history.js";
12
13
  export { isEntityId, newEntityId } from "./ids.js";
@@ -20,10 +21,10 @@ export { type MetaStore, metaStore } from "./metas.js";
20
21
  export { BOOKKEEPING, defaultFields, type FieldView, sortKeyOf, textOf, viewOf, } from "./present.js";
21
22
  export { type Related, relatedOf } from "./related.js";
22
23
  export { entityFor, type RelationField, relationFieldOf, } from "./relation.js";
23
- export { type RestOptions, restTransport, urlOf } from "./rest.js";
24
+ export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./rest.js";
24
25
  export { type RetryKeys, retryKeys, unanswered } from "./retry.js";
25
26
  export { completeMeta, type JsonSchema, metaFromSchema, type SchemaComponents, } from "./schema.js";
26
27
  export { type RecordSummary, type SummaryFields, summaryFieldsOf, summaryOf, type SummaryPart, } from "./summary.js";
27
28
  export { placeOf, stepIn, type Trail } from "./trail.js";
28
- export { type Draft, explain, type Method, type One, type SendOptions, type Transport, TransportError, } from "./transport.js";
29
+ export { type Draft, explain, type Method, type One, readRoute, type SendOptions, type Transport, TransportError, } from "./transport.js";
29
30
  export { installTimeZone, instantOf, timeZoneNow, wallTimeOf, } from "./zone.js";