@sincpro/web-framework 4.1.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,7 +99,7 @@ flowchart LR
99
99
  subgraph fw["@sincpro/web-framework · the web"]
100
100
  direction TB
101
101
  core["core/<br/>textOf · summaryOf · forms · lines · explain"]
102
- react["react/<br/>useListing · useRecord · useCommand<br/>useLookup · useService · useContextValues"]
102
+ react["react/<br/>useListing · useRecord · useCommand<br/>useLookup · useServiceQuery · useServiceCommand · useContextValues"]
103
103
  web["web/<br/>EntityList · EntityRecord · RecordField<br/>EntityPicker · entityView · SincproApp"]
104
104
  optional["./telemetry · ./errors<br/>optional: OpenTelemetry · GlitchTip"]
105
105
  core --> react --> web
@@ -126,7 +126,7 @@ the database:
126
126
  ```mermaid
127
127
  sequenceDiagram
128
128
  actor person as Person
129
- participant screen as Screen<br/>(useService)
129
+ participant screen as Screen<br/>(useServiceCommand)
130
130
  participant service as CloseAndNotify<br/>(ApplicationService)
131
131
  participant feature as Issues<br/>(Feature)
132
132
  participant client as Generated client<br/>(bound transport)
@@ -494,10 +494,13 @@ reaches the reporter, as before.
494
494
 
495
495
  ```tsx
496
496
  function CloseButton({ issueId }: { issueId: string }) {
497
- const close = useService(project.Issues.close); // run · busy · answer · error
497
+ const close = useServiceCommand(projectBoundedContext, CommandCloseIssue); // execute · busy · response · error
498
498
  return (
499
499
  <>
500
- <Button disabled={close.busy} onClick={() => close.run({ issue_id: issueId })}>
500
+ <Button
501
+ disabled={close.busy}
502
+ onClick={() => close.execute(new CommandCloseIssue(issueId))}
503
+ >
501
504
  Close
502
505
  </Button>
503
506
  {close.error ? <Refused error={close.error} /> : null}
@@ -551,22 +554,27 @@ const tickets = defineMeta({
551
554
  Start, Remix); a single-page application skips it and ships nothing of it. Three pieces, and none
552
555
  imports an SSR framework: the application wires its own framework's hooks.
553
556
 
554
- A page reads on the server with the use case it reads with in the browser, and arrives with its
555
- data in its HTML. `readOnServer` answers plain JSON — a Client Component receives data, never
556
- instances — and, when the read fails, `undefined` and one line on the process's log: the page is
557
- drawn anyway and the browser reads it on mount. `ServerRead<typeof useCase>` types the page's
558
- `initial`:
557
+ A page prefetches on the server the queries its screens run in the browser, and arrives with its
558
+ data in its HTML. `prefetchQueries` returns the Responses as plain JSON by query key — a Client
559
+ Component receives data, never instances —, leaving out, with one line on the process's log, a
560
+ query that failed: the page is drawn anyway and the browser fetches it on mount.
561
+ `<HydrationBoundary state>` hands them to the screens below, which find them by running the same
562
+ query — no `initial` prop:
559
563
 
560
564
  ```tsx
561
565
  // a route's loader or a Server Component — plain logic, no screen loaded
562
- import { readOnServer } from "@sincpro/web-framework/core";
563
- const balance = await readOnServer(project.Accounts.balance, [{ member_id }]);
564
- return <Balance member={member_id} initial={balance} />;
566
+ import { prefetchQueries } from "@sincpro/web-framework/core";
567
+ const state = await prefetchQueries([
568
+ [membersBoundedContext, new CommandReadBalance(memberId)],
569
+ ]);
570
+ return (
571
+ <HydrationBoundary state={state}>
572
+ <Balance member={memberId} />
573
+ </HydrationBoundary>
574
+ );
565
575
 
566
- // the page, rendered there and hydrated in the browser: it asks nothing on mount
567
- const balance = useServiceReading(project.Accounts.balance, [{ member_id: member }], {
568
- initial,
569
- });
576
+ // the screen, rendered there and hydrated in the browser: it fetches nothing on mount
577
+ const balance = useServiceQuery(membersBoundedContext, new CommandReadBalance(member));
570
578
  ```
571
579
 
572
580
  A record screen starts the same way. `readRecordOnServer` reads the record with the operations the
@@ -707,9 +715,9 @@ hook and draw your own, or go straight to the loose piece.
707
715
  | Question | Declarative | Hook | Loose piece |
708
716
  | ------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------ |
709
717
  | Where is the data? | `entity()` (client-framework) | — | `restTransport`, `memoryTransport` |
710
- | The application's logic | its `Feature`s and `ApplicationService`s (client-framework) | `useService` | `project.Issues.close(…)` |
711
- | Read through a use case | its `Feature`s (client-framework) | `useServiceReading` | `project.Accounts.balance(…)` |
712
- | Read it on the server first | the same use case, before the page is drawn | `useServiceReading(…, { initial })` | `readOnServer`, `ServerRead` |
718
+ | The application's logic | its `Feature`s and `ApplicationService`s (client-framework) | `useServiceCommand` | `boundedContext.execute(new CommandX(…))` |
719
+ | Read through a use case | its `Feature`s (client-framework) | `useServiceQuery` | `QueryCache`, `queryKeyOf` |
720
+ | Read it on the server first | the same query, before the page is drawn: `<HydrationBoundary state>` | `useServiceQuery` | `prefetchQueries`, `DehydratedState` |
713
721
  | A record read on the server | `EntityRecord initial` | `useRecord(…, { initial })` | `readRecordOnServer`, `RecordRead` |
714
722
  | What every use case runs with | `processContext`, `project.context` (client-framework) | `useContextValues` | `ContextStore` |
715
723
  | What happened, what broke | `./telemetry`, `./errors` (optional) | — | `configureProcess({ tracer, reporter })` |
@@ -752,7 +760,7 @@ hook and draw your own, or go straight to the loose piece.
752
760
  | Look at the set several ways | `EntityList views` (table, rows, board, sheet, tiles) | — | web-ui's `List.*` |
753
761
  | Cross it by two fields | `EntityList pivot` | `usePivot` | `pivotOf` |
754
762
  | Order by several fields | the bar's criteria builder | `listing.orderBy([...])` | criteria's `order` |
755
- | Act on it (with a dry run) | `ServiceButton` (a use case), `CommandButton`, row commands | `useService`, `useCommand` | `callFor`, `operations.call` |
763
+ | Act on it (with a dry run) | `ServiceButton` (a use case), `CommandButton`, row commands | `useServiceCommand`, `useCommand` | `callFor`, `operations.call` |
756
764
  | What is chosen in a list | `EntityList selectable selection` | `useSelection` | `Selection`, `chosen`, `allMatching` (client-framework) |
757
765
  | Act on each chosen one | `BatchProgress`, `selectionActions={(chosen) => …}` | `useBatchCommand` | `runBatch`, `keysOf` (client-framework), `sendRoute` |
758
766
  | A list's actions, by the style | `EntityList actions`, `selectionActions` (`DockAction`s) | — | web-ui's `List.Dock`, `ViewStyleProvider` |
@@ -845,8 +853,9 @@ moves to the generated one — is [`docs/ADOPTION.md`](docs/ADOPTION.md).
845
853
  | --------------------------------------- | ----------------------------------------------------------------------------------------------- | ------ |
846
854
  | `restTransport`, `memoryTransport` | The backend, or the same engine in memory (client-framework) | ✅ |
847
855
  | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI (client-framework) | ✅ |
848
- | `useService` | A screen runs one of the application's use cases: run, busy, answer, error | ✅ |
849
- | `readOnServer` | A page read on the server by the browser's use case: plain JSON, a failure left to the browser | ✅ |
856
+ | `useServiceCommand` | A screen executes a Command on a gesture: execute, busy, response, error | ✅ |
857
+ | `useServiceQuery` | A screen queries a use case: cached by query key, shared, invalidated by writes and context | ✅ |
858
+ | `prefetchQueries` | A page's queries prefetched on the server, hydrated by `HydrationBoundary`: plain JSON | ✅ |
850
859
  | `readRecordOnServer` | A record screen filled in the server's HTML: `useRecord` starts from it, nothing asked on mount | ✅ |
851
860
  | `./telemetry`, `./errors` | Optional: the application's traces to its OTLP endpoint, its errors to GlitchTip | ✅ |
852
861
  | `./telemetry/server` | Optional: a rendering server's use cases on its OTLP provider, their trace continued by the API | ✅ |
@@ -23,10 +23,11 @@ export { lookupOf, type LookupOption } from "./lookup.js";
23
23
  export { detailOf, measuresOf, sumsOf, type Total, totalOf, } from "./measure.js";
24
24
  export { knownModelOf, modelsOf } from "./models.js";
25
25
  export { amountTextOf, BOOKKEEPING, currencyNow, type DateStyle, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, type FieldView, installCurrency, installDateStyle, installRegion, instantTextOf, moneyTextOf, numberTextOf, regionNow, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
26
+ export { type DehydratedState, getQueryData, type QueryBoundedContext, QueryCache, queryKeyOf, type QueryState, type ResponseOf, } from "./queries.js";
26
27
  export { type Related, relatedOf } from "./related.js";
27
28
  export { backReference, entityFor, relatedScope, type RelationField, relationFieldOf, } from "./relation.js";
28
29
  export { GAP, HANDLE_WIDGET, handleOf, type Move, movesFor, placed, type Reordering, reorderingOf, } from "./reorder.js";
29
30
  export { holdsRichText, RICH_TEXT_WIDGET, richTextPlainOf, type RichTextSettings, } from "./richText.js";
30
- export { readOnServer, readRecordOnServer, type RecordRead, type ServerRead, } from "./server.js";
31
+ export { prefetchQueries, readRecordOnServer, type RecordRead, } from "./server.js";
31
32
  export { type RecordSummary, summaryFieldsOf, summaryOf, } from "./summary.js";
32
33
  export { placeOf, stepIn, type Trail } from "./trail.js";
@@ -23,10 +23,11 @@ export { lookupOf } from "./lookup.js";
23
23
  export { detailOf, measuresOf, sumsOf, totalOf, } from "./measure.js";
24
24
  export { knownModelOf, modelsOf } from "./models.js";
25
25
  export { amountTextOf, BOOKKEEPING, currencyNow, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, installCurrency, installDateStyle, installRegion, instantTextOf, moneyTextOf, numberTextOf, regionNow, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
26
+ export { getQueryData, QueryCache, queryKeyOf, } from "./queries.js";
26
27
  export { relatedOf } from "./related.js";
27
28
  export { backReference, entityFor, relatedScope, relationFieldOf, } from "./relation.js";
28
29
  export { GAP, HANDLE_WIDGET, handleOf, movesFor, placed, reorderingOf, } from "./reorder.js";
29
30
  export { holdsRichText, RICH_TEXT_WIDGET, richTextPlainOf, } from "./richText.js";
30
- export { readOnServer, readRecordOnServer, } from "./server.js";
31
+ export { prefetchQueries, readRecordOnServer, } from "./server.js";
31
32
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
32
33
  export { placeOf, stepIn } from "./trail.js";
@@ -0,0 +1,73 @@
1
+ import type { BoundedContext, Command } from "@sincpro/client-framework";
2
+ /** What a screen queries: a bounded context, which executes a Command and returns its Response. */
3
+ export type QueryBoundedContext = Pick<BoundedContext, "name" | "execute">;
4
+ /** The Response a Command returns: `CommandReadShowcase extends Command<ResponseShowcase>` →
5
+ * `ResponseShowcase`. */
6
+ export type ResponseOf<C> = C extends Command<infer R> ? R : never;
7
+ /** Responses prefetched on the server that renders a page, by query key — plain JSON, what
8
+ * crosses to the browser (`prefetchQueries`, `<HydrationBoundary>`). */
9
+ export type DehydratedState = Readonly<Record<string, unknown>>;
10
+ /**
11
+ * The key of a query: its bounded context, its Command's identity and its values. Two screens
12
+ * that execute the same Command with the same values run the same query, so they share its
13
+ * Response; other values are another query, never shown its Response.
14
+ *
15
+ * Context: the Command's identity is the one its bounded context gave it when it registered it
16
+ * (`commandName`, `<context>.<Command>`), the same on the server and in the browser — the key a
17
+ * prefetched Response is found by. Its values are its own fields as JSON, in the order its
18
+ * constructor writes them: a Command that reads carries values (ids, a page, a text), never a file.
19
+ */
20
+ export declare function queryKeyOf(boundedContext: QueryBoundedContext, command: Command<unknown>): string;
21
+ /** Where a query stands — `loading` until its first Response or failure. */
22
+ export type QueryState = {
23
+ status: "loading" | "ready" | "failed";
24
+ response: unknown;
25
+ error: unknown;
26
+ /** Invalidated (a write touched it, another company, `refetch`): it is fetched again. */
27
+ stale: boolean;
28
+ };
29
+ /**
30
+ * The cache of a provider's queries: one request for every screen that runs the same query at
31
+ * once (deduplicated), its Response shared until it is invalidated.
32
+ *
33
+ * Context: an invalidated query keeps its Response on screen while it is fetched again — a
34
+ * write, another company, `refetch()` invalidate it and the screens that show it fetch once
35
+ * more —; a failure leaves no Response. A Response nobody shows stays cached, so coming back to
36
+ * a screen draws it at once and fetches it again only when it is stale.
37
+ */
38
+ export declare class QueryCache {
39
+ private readonly entries;
40
+ /** Where `key` stands, or nothing when no screen ran it yet. The same object until it changes,
41
+ * as `useSyncExternalStore` reads it. */
42
+ getState(key: string): QueryState | undefined;
43
+ /** `key`'s Response prefetched on the server, when the cache has nothing of it yet. */
44
+ hydrate(key: string, response: unknown): void;
45
+ /** A newer Response of `key` (prefetched again): it replaces the cached one, unless one is
46
+ * being fetched. */
47
+ setResponse(key: string, response: unknown): void;
48
+ subscribe(key: string, listener: () => void): () => void;
49
+ /** Fetches `key` when it has no Response yet or it is stale — once, whoever else asks. */
50
+ fetch(key: string, run: () => Promise<unknown>): void;
51
+ /** `key`'s Response may be old: the screens that show it fetch it again. */
52
+ invalidate(key: string): void;
53
+ /** Every Response may be old — another company: each stays on screen until its new one. */
54
+ invalidateAll(): void;
55
+ /**
56
+ * Forgets every Response — another person signed in, or nobody: what the last one read is never
57
+ * shown to the next, not even while it is fetched again. The screens on view start `loading`
58
+ * and fetch; a Response on its way is dropped.
59
+ */
60
+ clear(): void;
61
+ private invalidateEntry;
62
+ private done;
63
+ private entryOf;
64
+ private settle;
65
+ }
66
+ /**
67
+ * A query's Response in a prefetched state — what a page reads of it beside its screens: its
68
+ * title, its description.
69
+ *
70
+ * const state = await prefetchQueries([[coursesBoundedContext, new CommandReadCourse(id)]]);
71
+ * const course = getQueryData(state, coursesBoundedContext, new CommandReadCourse(id));
72
+ */
73
+ export declare function getQueryData<C extends Command<unknown>>(state: DehydratedState, boundedContext: QueryBoundedContext, command: C): ResponseOf<C> | undefined;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The key of a query: its bounded context, its Command's identity and its values. Two screens
3
+ * that execute the same Command with the same values run the same query, so they share its
4
+ * Response; other values are another query, never shown its Response.
5
+ *
6
+ * Context: the Command's identity is the one its bounded context gave it when it registered it
7
+ * (`commandName`, `<context>.<Command>`), the same on the server and in the browser — the key a
8
+ * prefetched Response is found by. Its values are its own fields as JSON, in the order its
9
+ * constructor writes them: a Command that reads carries values (ids, a page, a text), never a file.
10
+ */
11
+ export function queryKeyOf(boundedContext, command) {
12
+ const type = Object.getPrototypeOf(command)?.constructor;
13
+ const identity = typeof type?.commandName === "string" ? type.commandName : (type?.name ?? "Command");
14
+ return `${boundedContext.name}|${identity}|${JSON.stringify(command)}`;
15
+ }
16
+ const LOADING = {
17
+ status: "loading",
18
+ response: undefined,
19
+ error: null,
20
+ stale: false,
21
+ };
22
+ /**
23
+ * The cache of a provider's queries: one request for every screen that runs the same query at
24
+ * once (deduplicated), its Response shared until it is invalidated.
25
+ *
26
+ * Context: an invalidated query keeps its Response on screen while it is fetched again — a
27
+ * write, another company, `refetch()` invalidate it and the screens that show it fetch once
28
+ * more —; a failure leaves no Response. A Response nobody shows stays cached, so coming back to
29
+ * a screen draws it at once and fetches it again only when it is stale.
30
+ */
31
+ export class QueryCache {
32
+ entries = new Map();
33
+ /** Where `key` stands, or nothing when no screen ran it yet. The same object until it changes,
34
+ * as `useSyncExternalStore` reads it. */
35
+ getState(key) {
36
+ return this.entries.get(key)?.state;
37
+ }
38
+ /** `key`'s Response prefetched on the server, when the cache has nothing of it yet. */
39
+ hydrate(key, response) {
40
+ if (this.entries.has(key))
41
+ return;
42
+ this.entries.set(key, {
43
+ state: { status: "ready", response, error: null, stale: false },
44
+ fetching: false,
45
+ invalidated: false,
46
+ generation: 0,
47
+ listeners: new Set(),
48
+ });
49
+ }
50
+ /** A newer Response of `key` (prefetched again): it replaces the cached one, unless one is
51
+ * being fetched. */
52
+ setResponse(key, response) {
53
+ const entry = this.entries.get(key);
54
+ if (entry === undefined)
55
+ return this.hydrate(key, response);
56
+ if (entry.fetching || entry.state.response === response)
57
+ return;
58
+ this.settle(entry, { status: "ready", response, error: null, stale: false });
59
+ }
60
+ subscribe(key, listener) {
61
+ const entry = this.entryOf(key);
62
+ entry.listeners.add(listener);
63
+ return () => void entry.listeners.delete(listener);
64
+ }
65
+ /** Fetches `key` when it has no Response yet or it is stale — once, whoever else asks. */
66
+ fetch(key, run) {
67
+ const entry = this.entryOf(key);
68
+ if (entry.fetching)
69
+ return;
70
+ if (entry.state.status !== "loading" && !entry.state.stale)
71
+ return;
72
+ entry.fetching = true;
73
+ entry.invalidated = false;
74
+ const generation = entry.generation;
75
+ // Through the promise: a use case that throws before it returns is a failure like any other.
76
+ Promise.resolve()
77
+ .then(run)
78
+ .then((response) => this.done(entry, generation, {
79
+ status: "ready",
80
+ response,
81
+ error: null,
82
+ stale: false,
83
+ }), (error) => this.done(entry, generation, {
84
+ status: "failed",
85
+ response: undefined,
86
+ error,
87
+ stale: false,
88
+ }));
89
+ }
90
+ /** `key`'s Response may be old: the screens that show it fetch it again. */
91
+ invalidate(key) {
92
+ const entry = this.entries.get(key);
93
+ if (entry !== undefined)
94
+ this.invalidateEntry(entry);
95
+ }
96
+ /** Every Response may be old — another company: each stays on screen until its new one. */
97
+ invalidateAll() {
98
+ for (const entry of this.entries.values())
99
+ this.invalidateEntry(entry);
100
+ }
101
+ /**
102
+ * Forgets every Response — another person signed in, or nobody: what the last one read is never
103
+ * shown to the next, not even while it is fetched again. The screens on view start `loading`
104
+ * and fetch; a Response on its way is dropped.
105
+ */
106
+ clear() {
107
+ for (const [key, entry] of this.entries) {
108
+ entry.generation += 1;
109
+ if (entry.listeners.size === 0 && !entry.fetching)
110
+ this.entries.delete(key);
111
+ else
112
+ this.settle(entry, { ...LOADING });
113
+ }
114
+ }
115
+ invalidateEntry(entry) {
116
+ if (entry.fetching)
117
+ entry.invalidated = true;
118
+ else if (!entry.state.stale)
119
+ this.settle(entry, { ...entry.state, stale: true });
120
+ }
121
+ done(entry, generation, state) {
122
+ entry.fetching = false;
123
+ // Cleared while it was fetched: another session's Response; the screens fetch again.
124
+ if (generation !== entry.generation)
125
+ return this.settle(entry, { ...LOADING });
126
+ // Invalidated while it was fetched: what arrived may predate the write; fetched again.
127
+ this.settle(entry, entry.invalidated ? { ...state, stale: true } : state);
128
+ }
129
+ entryOf(key) {
130
+ let entry = this.entries.get(key);
131
+ if (entry === undefined) {
132
+ entry = {
133
+ state: LOADING,
134
+ fetching: false,
135
+ invalidated: false,
136
+ generation: 0,
137
+ listeners: new Set(),
138
+ };
139
+ this.entries.set(key, entry);
140
+ }
141
+ return entry;
142
+ }
143
+ settle(entry, state) {
144
+ entry.state = state;
145
+ for (const listener of [...entry.listeners])
146
+ listener();
147
+ }
148
+ }
149
+ /**
150
+ * A query's Response in a prefetched state — what a page reads of it beside its screens: its
151
+ * title, its description.
152
+ *
153
+ * const state = await prefetchQueries([[coursesBoundedContext, new CommandReadCourse(id)]]);
154
+ * const course = getQueryData(state, coursesBoundedContext, new CommandReadCourse(id));
155
+ */
156
+ export function getQueryData(state, boundedContext, command) {
157
+ const key = queryKeyOf(boundedContext, command);
158
+ return Object.hasOwn(state, key) ? state[key] : undefined;
159
+ }
@@ -1,49 +1,37 @@
1
- import { type Draft, type Entity, type OperationTransport, type ResourceRef } from "@sincpro/client-framework";
1
+ import { type Command, type Draft, type Entity, type OperationTransport, type ResourceRef } from "@sincpro/client-framework";
2
2
  import type { AnyRecord, Meta } from "@sincpro/criteria";
3
+ import { type DehydratedState, type QueryBoundedContext } from "./queries.js";
3
4
  /**
4
- * A use case's answer read on the server that renders a page, before it is drawn — the very use
5
- * case the page reads with in the browser (`useServiceReading`), so the page arrives with its
6
- * data in the HTML (what a search engine, a crawler and a shared link read) and the browser does
7
- * not ask again.
5
+ * Prefetches, on the server that renders a page, the queries its screens will run — the very
6
+ * Commands they run with `useServiceQuery` —, so the page arrives with its data in the HTML (what
7
+ * a search engine, a crawler and a shared link read) and the browser does not fetch them again.
8
8
  *
9
- * // the server: a route's loader, a Server Component
10
- * const balance = await readOnServer(project.Accounts.balance, [{ member_id }]);
11
- * <Balance member={member_id} initial={balance} />
9
+ * // the server: a route, a Server Component
10
+ * const state = await prefetchQueries([
11
+ * [shopBoundedContext, new CommandReadShowcase()],
12
+ * [coursesBoundedContext, new CommandReadCourse(id)],
13
+ * ]);
14
+ * return <HydrationBoundary state={state}><Showcase /></HydrationBoundary>;
12
15
  *
13
- * // the page, rendered there and hydrated in the browser: the same use case, the same args
14
- * type Props = { member: string; initial?: ServerRead<typeof project.Accounts.balance> };
15
- * function Balance({ member, initial }: Props) {
16
- * const balance = useServiceReading(project.Accounts.balance, [{ member_id: member }], {
17
- * initial,
18
- * });
19
- * }
16
+ * // the screen, rendered there and hydrated in the browser: the same query, no props
17
+ * const showcase = useServiceQuery(shopBoundedContext, new CommandReadShowcase());
20
18
  *
21
19
  * Context: what crosses from the server to the browser is plain JSON — a Client Component is
22
- * handed data, never instances, and a `Date` arrives as its text —, so the answer is written and
23
- * read back as JSON here: a framework that refuses a class instance as a prop never sees one.
20
+ * handed data, never instances, and a `Date` arrives as its text —, so each Response is written
21
+ * and read back as JSON here, keyed by its query (`queryKeyOf`): a screen finds it by running the
22
+ * same Command with the same values.
24
23
  *
25
- * A read that fails never refuses the page: it answers `undefined`, the page is drawn without
26
- * it, and the browser reads it on mount, as a single-page application does. The failure is one
27
- * line on the process's log (client-framework's `logger`, WARN: it always speaks) saying `what`
28
- * was not read — the use case's own name when not given. A use case run through its bounded
29
- * context already traced and reported its failure, so nothing is reported twice here; and, as
30
- * there, a refusal (a 404, a permission) says its type and kind, never its message. A use case
31
- * that answers nothing stays nothing, without a line.
24
+ * A query that fails never refuses the page: it is left out, the page is drawn without it, and the
25
+ * browser fetches it on mount, as a single-page application does. The failure is one line on the
26
+ * process's log (client-framework's `logger`, WARN: it always speaks) naming the Command. A use
27
+ * case run through its bounded context already traced and reported its failure, so nothing is
28
+ * reported twice here; and, as there, a refusal (a 404, a permission) says its type and kind,
29
+ * never its message. A Command that returns nothing is left out, without a line.
32
30
  *
33
31
  * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
34
32
  * script import it from `@sincpro/web-framework/core` without loading any screen.
35
33
  */
36
- export declare function readOnServer<A extends unknown[], R>(useCase: (...args: A) => R | Promise<R>, args: A, options?: {
37
- what?: string;
38
- }): Promise<Awaited<R> | undefined>;
39
- /**
40
- * What `readOnServer` answers for a use case — its answer, or `undefined` when it could not be
41
- * read —: the type of a page's `initial`, handed to `useServiceReading(useCase, args, {
42
- * initial })` as it is.
43
- *
44
- * type Props = { initial?: ServerRead<typeof project.Accounts.balance> };
45
- */
46
- export type ServerRead<U extends (...args: never[]) => unknown> = Awaited<ReturnType<U>> | undefined;
34
+ export declare function prefetchQueries(queries: readonly (readonly [QueryBoundedContext, Command<unknown>])[]): Promise<DehydratedState>;
47
35
  /**
48
36
  * One record of an entity and its model, as the server that renders a page read it: what
49
37
  * `useRecord(entity, opened, { initial })` starts from — `readRecordOnServer`'s answer.
@@ -85,7 +73,7 @@ export type RecordRead<T> = {
85
73
  * Context: it asks through the screens' use case (`screensOperations`), as `useRecord` and
86
74
  * `readListing` do — traced like the browser's reads, with the process's context — and answers
87
75
  * plain JSON (`RecordRead`): a Client Component is handed data, never instances. A read that
88
- * fails never refuses the page, as `readOnServer`: it answers `undefined` and one WARN line on
76
+ * fails never refuses the page, as `prefetchQueries`: it answers `undefined` and one WARN line on
89
77
  * the process's log — `what` (the entity's key when not given), the failure's type and kind, and
90
78
  * never a refusal's message (a 404, a permission) —, the page is drawn without it and the
91
79
  * browser reads the record on mount, as a single-page application does. A read the caller
@@ -1,50 +1,50 @@
1
1
  import { describeFailure, logger, outcomeOf, readRecord, screensOperations, } from "@sincpro/client-framework";
2
+ import { queryKeyOf, } from "./queries.js";
2
3
  /**
3
- * A use case's answer read on the server that renders a page, before it is drawn — the very use
4
- * case the page reads with in the browser (`useServiceReading`), so the page arrives with its
5
- * data in the HTML (what a search engine, a crawler and a shared link read) and the browser does
6
- * not ask again.
4
+ * Prefetches, on the server that renders a page, the queries its screens will run — the very
5
+ * Commands they run with `useServiceQuery` —, so the page arrives with its data in the HTML (what
6
+ * a search engine, a crawler and a shared link read) and the browser does not fetch them again.
7
7
  *
8
- * // the server: a route's loader, a Server Component
9
- * const balance = await readOnServer(project.Accounts.balance, [{ member_id }]);
10
- * <Balance member={member_id} initial={balance} />
8
+ * // the server: a route, a Server Component
9
+ * const state = await prefetchQueries([
10
+ * [shopBoundedContext, new CommandReadShowcase()],
11
+ * [coursesBoundedContext, new CommandReadCourse(id)],
12
+ * ]);
13
+ * return <HydrationBoundary state={state}><Showcase /></HydrationBoundary>;
11
14
  *
12
- * // the page, rendered there and hydrated in the browser: the same use case, the same args
13
- * type Props = { member: string; initial?: ServerRead<typeof project.Accounts.balance> };
14
- * function Balance({ member, initial }: Props) {
15
- * const balance = useServiceReading(project.Accounts.balance, [{ member_id: member }], {
16
- * initial,
17
- * });
18
- * }
15
+ * // the screen, rendered there and hydrated in the browser: the same query, no props
16
+ * const showcase = useServiceQuery(shopBoundedContext, new CommandReadShowcase());
19
17
  *
20
18
  * Context: what crosses from the server to the browser is plain JSON — a Client Component is
21
- * handed data, never instances, and a `Date` arrives as its text —, so the answer is written and
22
- * read back as JSON here: a framework that refuses a class instance as a prop never sees one.
19
+ * handed data, never instances, and a `Date` arrives as its text —, so each Response is written
20
+ * and read back as JSON here, keyed by its query (`queryKeyOf`): a screen finds it by running the
21
+ * same Command with the same values.
23
22
  *
24
- * A read that fails never refuses the page: it answers `undefined`, the page is drawn without
25
- * it, and the browser reads it on mount, as a single-page application does. The failure is one
26
- * line on the process's log (client-framework's `logger`, WARN: it always speaks) saying `what`
27
- * was not read — the use case's own name when not given. A use case run through its bounded
28
- * context already traced and reported its failure, so nothing is reported twice here; and, as
29
- * there, a refusal (a 404, a permission) says its type and kind, never its message. A use case
30
- * that answers nothing stays nothing, without a line.
23
+ * A query that fails never refuses the page: it is left out, the page is drawn without it, and the
24
+ * browser fetches it on mount, as a single-page application does. The failure is one line on the
25
+ * process's log (client-framework's `logger`, WARN: it always speaks) naming the Command. A use
26
+ * case run through its bounded context already traced and reported its failure, so nothing is
27
+ * reported twice here; and, as there, a refusal (a 404, a permission) says its type and kind,
28
+ * never its message. A Command that returns nothing is left out, without a line.
31
29
  *
32
30
  * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
33
31
  * script import it from `@sincpro/web-framework/core` without loading any screen.
34
32
  */
35
- export async function readOnServer(useCase, args, options = {}) {
36
- // A use case, not a hook: the linter reads any call to `use…` as one.
37
- const run = useCase;
38
- try {
39
- const answer = await run(...args);
40
- if (answer === undefined)
33
+ export async function prefetchQueries(queries) {
34
+ const fetched = await Promise.all(queries.map(async ([boundedContext, command]) => {
35
+ const key = queryKeyOf(boundedContext, command);
36
+ try {
37
+ const response = await boundedContext.execute(command);
38
+ if (response === undefined)
39
+ return undefined;
40
+ return [key, JSON.parse(JSON.stringify(response))];
41
+ }
42
+ catch (error) {
43
+ notRead(key.split("|")[1] ?? "a Command", error);
41
44
  return undefined;
42
- return JSON.parse(JSON.stringify(answer));
43
- }
44
- catch (error) {
45
- notRead(options.what ?? (useCase.name || "a use case"), error);
46
- return undefined;
47
- }
45
+ }
46
+ }));
47
+ return Object.fromEntries(fetched.filter((one) => one !== undefined));
48
48
  }
49
49
  /** The one line a read on the server that failed leaves on the process's log (WARN: it always
50
50
  * speaks): what was not read, and the failure's type and kind — a refusal never its message. */
@@ -77,7 +77,7 @@ function notRead(what, error) {
77
77
  * Context: it asks through the screens' use case (`screensOperations`), as `useRecord` and
78
78
  * `readListing` do — traced like the browser's reads, with the process's context — and answers
79
79
  * plain JSON (`RecordRead`): a Client Component is handed data, never instances. A read that
80
- * fails never refuses the page, as `readOnServer`: it answers `undefined` and one WARN line on
80
+ * fails never refuses the page, as `prefetchQueries`: it answers `undefined` and one WARN line on
81
81
  * the process's log — `what` (the entity's key when not given), the failure's type and kind, and
82
82
  * never a refusal's message (a 404, a permission) —, the page is drawn without it and the
83
83
  * browser reads the record on mount, as a single-page application does. A read the caller
@@ -3,6 +3,7 @@ import type { Meta } from "@sincpro/criteria";
3
3
  import type { Uploads } from "../core/files.js";
4
4
  import { type NameBook } from "../core/names.js";
5
5
  import { type DateStyle } from "../core/present.js";
6
+ import { QueryCache } from "../core/queries.js";
6
7
  import type { RichTextSettings } from "../core/richText.js";
7
8
  import type { Trail } from "../core/trail.js";
8
9
  import { type ReactNode } from "react";
@@ -48,6 +49,8 @@ type FrameworkContextValue = {
48
49
  context: Readonly<Record<string, unknown>>;
49
50
  /** Where writes are announced: a reading reads again when one touches it (`useWrites`). */
50
51
  changes: ChangeFeed;
52
+ /** The screens' queries to use cases, cached and shared by query key (`useServiceQuery`). */
53
+ queries: QueryCache;
51
54
  /** The names of records by key, asked one request per entity (`useNameOf`). */
52
55
  names: NameBook;
53
56
  /** How dates are written now — a piece that keeps its texts compares it to know when to
@@ -4,6 +4,7 @@ import { installTimeZone, metaStore, processChanges, processContext, screensOper
4
4
  import { modelsOf } from "../core/models.js";
5
5
  import { nameBook } from "../core/names.js";
6
6
  import { installCurrency, installDateStyle, installRegion, } from "../core/present.js";
7
+ import { QueryCache } from "../core/queries.js";
7
8
  import { entityFor } from "../core/relation.js";
8
9
  import { useContextValues } from "./useContextValues.js";
9
10
  import { createContext, useContext, useEffect, useMemo, useRef, useState, } from "react";
@@ -46,6 +47,7 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
46
47
  // What the entities carry (a generated entity has its model), under what the app gives.
47
48
  const [metas] = useState(() => metaStore({ ...modelsOf(entities), ...seed }));
48
49
  const [trails] = useState(() => new Map());
50
+ const [queries] = useState(() => new QueryCache());
49
51
  // What the screens read and write is a use case of `screens` (`screensOperations`,
50
52
  // client-framework): each call traced, carrying the process's context (the company, the
51
53
  // tenant) read at the moment it is sent, and reported when it failed unexpectedly.
@@ -60,6 +62,14 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
60
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
61
63
  [screens, metas, context]);
62
64
  useEffect(() => changes.follow((change) => names.changed(change)), [changes, names]);
65
+ // Another company: every cached Response may be another; the screens fetch again.
66
+ const contextShown = useRef(context);
67
+ useEffect(() => {
68
+ if (contextShown.current === context)
69
+ return;
70
+ contextShown.current = context;
71
+ queries.invalidateAll();
72
+ }, [queries, context]);
63
73
  const value = useMemo(() => ({
64
74
  operations: screens,
65
75
  transport,
@@ -69,6 +79,7 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
69
79
  trails,
70
80
  context,
71
81
  changes,
82
+ queries,
72
83
  names,
73
84
  dateStyle,
74
85
  currency,
@@ -85,6 +96,7 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
85
96
  trails,
86
97
  context,
87
98
  changes,
99
+ queries,
88
100
  names,
89
101
  dateStyle,
90
102
  currency,