@sincpro/web-framework 4.0.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.
Files changed (46) hide show
  1. package/README.md +37 -28
  2. package/dist/core/index.d.ts +4 -2
  3. package/dist/core/index.js +4 -2
  4. package/dist/core/models.d.ts +16 -0
  5. package/dist/core/models.js +18 -0
  6. package/dist/core/names.js +2 -1
  7. package/dist/core/queries.d.ts +73 -0
  8. package/dist/core/queries.js +159 -0
  9. package/dist/core/server.d.ts +24 -36
  10. package/dist/core/server.js +36 -36
  11. package/dist/react/context.d.ts +3 -0
  12. package/dist/react/context.js +23 -1
  13. package/dist/react/hydration.d.ts +20 -0
  14. package/dist/react/hydration.js +23 -0
  15. package/dist/react/index.d.ts +4 -2
  16. package/dist/react/index.js +4 -2
  17. package/dist/react/useBatchCommand.js +2 -1
  18. package/dist/react/useHistory.js +2 -1
  19. package/dist/react/useListing.js +3 -2
  20. package/dist/react/useLookup.js +3 -2
  21. package/dist/react/useQueryCache.d.ts +13 -0
  22. package/dist/react/useQueryCache.js +16 -0
  23. package/dist/react/useRecord.js +5 -4
  24. package/dist/react/useRunning.d.ts +32 -0
  25. package/dist/react/{useService.js → useRunning.js} +3 -14
  26. package/dist/react/useServiceCommand.d.ts +42 -0
  27. package/dist/react/useServiceCommand.js +41 -0
  28. package/dist/react/useServiceQuery.d.ts +46 -0
  29. package/dist/react/useServiceQuery.js +79 -0
  30. package/dist/react/useSummary.js +2 -1
  31. package/dist/web/list/records.js +4 -3
  32. package/dist/web/record/ActionButton.d.ts +1 -1
  33. package/dist/web/record/CommandButton.js +2 -1
  34. package/dist/web/record/EntityPicker.js +2 -1
  35. package/dist/web/record/EntityTags.js +3 -2
  36. package/dist/web/record/ServiceButton.d.ts +1 -1
  37. package/dist/web/record/ServiceButton.js +9 -4
  38. package/dist/web/record/choice.js +2 -1
  39. package/dist/web/record/edit.js +2 -1
  40. package/dist/web/record/lines.js +2 -1
  41. package/dist/web/workspace/composer.d.ts +2 -2
  42. package/dist/web/workspace/composer.js +3 -1
  43. package/package.json +3 -3
  44. package/dist/react/useService.d.ts +0 -42
  45. package/dist/react/useServiceReading.d.ts +0 -51
  46. package/dist/react/useServiceReading.js +0 -88
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)
@@ -205,10 +205,11 @@ export const transport = restTransport({
205
205
  export const operations = restOperations(transport); // JSON-RPC: jsonRpcOperations(…)
206
206
  ```
207
207
 
208
- The definition of every model — its fields, operators, hints, widgets, formulas — comes with the
209
- contract (`metasOf(contract, "sales")`), handed to the app once (`SincproApp metas`, or
210
- `ModelDefinitions` for the face that needs them): an answer says only its `model_version`, and
211
- nothing reads a model at runtime. A form computes a published formula itself and asks the server
208
+ The definition of every model — its fields, operators, hints, widgets, formulas — is the
209
+ contract's, and each generated entity carries its own (`meta`): a face that imports an entity has
210
+ its model, with nothing to declare and no contract to download. An answer says only its
211
+ `model_version`, and nothing reads a model at runtime. `metas` (on `SincproApp`,
212
+ `FrameworkProvider` or `ModelDefinitions`) only replaces one. A form computes a published formula itself and asks the server
212
213
  for a preview only when a change reaches something it cannot answer.
213
214
 
214
215
  **3. The entities** — written by `sincpro-client generate` from the contract («From the
@@ -316,7 +317,6 @@ words), cache, toasts and the workspace, in one place. `transport` is only where
316
317
  ```tsx
317
318
  <SincproApp
318
319
  operations={operations}
319
- metas={metasOf(salesContract, "sales")}
320
320
  transport={transport}
321
321
  views={views}
322
322
  entities={[invoices, customers]} // a relation of a model resolves to one of these, alone
@@ -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 | ✅ |
@@ -855,7 +864,7 @@ moves to the generated one — is [`docs/ADOPTION.md`](docs/ADOPTION.md).
855
864
  | `selection` | Filters named as criteria 2.0 and the backend read them, the search bar's included | ✅ |
856
865
  | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
857
866
  | `useRecord`, `factsOf`, `RecordLines` | One record: facts, relations with their real total | ✅ |
858
- | Definitions | `FrameworkProvider metas`: the contract's models (`metasOf`); no answer carries one | ✅ |
867
+ | Definitions | Each generated entity carries its model (`meta`); `metas` replaces one; no answer carries one | ✅ |
859
868
  | `useLookup`, `EntityPicker` | Literal search: a many2one select, ⌘K | ✅ |
860
869
  | `useRecord` + `RecordField`, `dirtyOf` | Editing: hints evaluated live, preview, save with version (409), server drafts | ✅ |
861
870
  | `useCommand`, `CommandButton` | An entity's actions, with a dry run before what destroys | ✅ |
@@ -8,7 +8,7 @@
8
8
  * @sincpro/client-framework's — the same on every platform — and are imported from there.
9
9
  */
10
10
  export { type CachedOperations, cachedOperations, type CacheOptions, } from "./cache.js";
11
- export { type AnswerOf, callFor, type InputOf } from "./command.js";
11
+ export { type AnswerOf, type BodyOf, callFor, type CommandName, type CommandsOf, type InputOf, } from "./command.js";
12
12
  export { ENGLISH_FRAMEWORK_COPY, type FrameworkCopy, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, SPANISH_FRAMEWORK_COPY_TU, } from "./copy.js";
13
13
  export { type Advice, adviceAt, canCreate, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, isEmptyValue, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, type ServerFieldState, } from "./edit.js";
14
14
  export { explain } from "./explain.js";
@@ -21,11 +21,13 @@ export { addingOf, type AddingRule, addManyOf, blankLine, type Declared, editabl
21
21
  export { CHOOSE_MANY, choosesMany, defineList, type GroupLevel, isList, type ListDefinition, listingAsk, type ListingQuestion, type ListSpec, type NamedFilter, readListing, scopeOf, trashOf, } from "./list.js";
22
22
  export { lookupOf, type LookupOption } from "./lookup.js";
23
23
  export { detailOf, measuresOf, sumsOf, type Total, totalOf, } from "./measure.js";
24
+ export { knownModelOf, modelsOf } from "./models.js";
24
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";
25
27
  export { type Related, relatedOf } from "./related.js";
26
28
  export { backReference, entityFor, relatedScope, type RelationField, relationFieldOf, } from "./relation.js";
27
29
  export { GAP, HANDLE_WIDGET, handleOf, type Move, movesFor, placed, type Reordering, reorderingOf, } from "./reorder.js";
28
30
  export { holdsRichText, RICH_TEXT_WIDGET, richTextPlainOf, type RichTextSettings, } from "./richText.js";
29
- export { readOnServer, readRecordOnServer, type RecordRead, type ServerRead, } from "./server.js";
31
+ export { prefetchQueries, readRecordOnServer, type RecordRead, } from "./server.js";
30
32
  export { type RecordSummary, summaryFieldsOf, summaryOf, } from "./summary.js";
31
33
  export { placeOf, stepIn, type Trail } from "./trail.js";
@@ -8,7 +8,7 @@
8
8
  * @sincpro/client-framework's — the same on every platform — and are imported from there.
9
9
  */
10
10
  export { cachedOperations, } from "./cache.js";
11
- export { callFor } from "./command.js";
11
+ export { callFor, } from "./command.js";
12
12
  export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, SPANISH_FRAMEWORK_COPY_TU, } from "./copy.js";
13
13
  export { adviceAt, canCreate, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, fieldStateOf, isEmptyValue, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, } from "./edit.js";
14
14
  export { explain } from "./explain.js";
@@ -21,11 +21,13 @@ export { addingOf, addManyOf, blankLine, editableLines, isReference, lineFields,
21
21
  export { CHOOSE_MANY, choosesMany, defineList, isList, listingAsk, readListing, scopeOf, trashOf, } from "./list.js";
22
22
  export { lookupOf } from "./lookup.js";
23
23
  export { detailOf, measuresOf, sumsOf, totalOf, } from "./measure.js";
24
+ export { knownModelOf, modelsOf } from "./models.js";
24
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";
25
27
  export { relatedOf } from "./related.js";
26
28
  export { backReference, entityFor, relatedScope, relationFieldOf, } from "./relation.js";
27
29
  export { GAP, HANDLE_WIDGET, handleOf, movesFor, placed, reorderingOf, } from "./reorder.js";
28
30
  export { holdsRichText, RICH_TEXT_WIDGET, richTextPlainOf, } from "./richText.js";
29
- export { readOnServer, readRecordOnServer, } from "./server.js";
31
+ export { prefetchQueries, readRecordOnServer, } from "./server.js";
30
32
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
31
33
  export { placeOf, stepIn } from "./trail.js";
@@ -0,0 +1,16 @@
1
+ import type { Entity, MetaStore } from "@sincpro/client-framework";
2
+ import type { Meta } from "@sincpro/criteria";
3
+ /**
4
+ * An entity's model as the screens know it: what the provider's store holds for its key — the
5
+ * contract's, or what a face brought (`ModelDefinitions`) —, else the one the entity carries (a
6
+ * generated entity always does, `meta`).
7
+ *
8
+ * knownModelOf(metas, invoices) -> the invoices' model, with nothing declared
9
+ *
10
+ * Context: a server's answer never carries its model, so a screen draws with the contract's. A
11
+ * generated entity carries it, so a face that imports the entity has it — no contract imported,
12
+ * no `metasOf` wired. The store still wins: a face may bring a model of its own for a key.
13
+ */
14
+ export declare function knownModelOf(metas: Pick<MetaStore, "get">, entity: Pick<Entity, "key" | "meta">): Meta | undefined;
15
+ /** The models the entities carry, by their keys: what a provider starts its store with. */
16
+ export declare function modelsOf(entities: readonly Pick<Entity, "key" | "meta">[]): Record<string, Meta>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * An entity's model as the screens know it: what the provider's store holds for its key — the
3
+ * contract's, or what a face brought (`ModelDefinitions`) —, else the one the entity carries (a
4
+ * generated entity always does, `meta`).
5
+ *
6
+ * knownModelOf(metas, invoices) -> the invoices' model, with nothing declared
7
+ *
8
+ * Context: a server's answer never carries its model, so a screen draws with the contract's. A
9
+ * generated entity carries it, so a face that imports the entity has it — no contract imported,
10
+ * no `metasOf` wired. The store still wins: a face may bring a model of its own for a key.
11
+ */
12
+ export function knownModelOf(metas, entity) {
13
+ return metas.get(entity.key) ?? entity.meta;
14
+ }
15
+ /** The models the entities carry, by their keys: what a provider starts its store with. */
16
+ export function modelsOf(entities) {
17
+ return Object.fromEntries(entities.flatMap((one) => (one.meta === undefined ? [] : [[one.key, one.meta]])));
18
+ }
@@ -1,6 +1,7 @@
1
1
  import { readPage, } from "@sincpro/client-framework";
2
2
  import { touches } from "./changes.js";
3
3
  import { lookupOf } from "./lookup.js";
4
+ import { knownModelOf } from "./models.js";
4
5
  /** The most keys one request asks for. */
5
6
  const SLICE = 100;
6
7
  /** Whether an entity is searched on its own — not only under a record of another model. */
@@ -18,7 +19,7 @@ export function nameBook(transport, metas) {
18
19
  return;
19
20
  asking.delete(entityKey);
20
21
  const { entity, waiting } = batch;
21
- const meta = metas.get(entity.key);
22
+ const meta = knownModelOf(metas, entity);
22
23
  const field = meta?.get_id || meta?.identity || "id";
23
24
  const keys = [...waiting.keys()];
24
25
  for (let at = 0; at < keys.length; at += SLICE) {
@@ -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