@sincpro/web-framework 3.8.0 → 3.10.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
@@ -466,6 +466,68 @@ const tickets = defineMeta({
466
466
  });
467
467
  ```
468
468
 
469
+ **8. Rendered on a server** — only when the application renders pages on one (Next.js, TanStack
470
+ Start, Remix); a single-page application skips it and ships nothing of it. Three pieces, and none
471
+ imports an SSR framework: the application wires its own framework's hooks.
472
+
473
+ A page reads on the server with the use case it reads with in the browser, and arrives with its
474
+ data in its HTML. `readOnServer` answers plain JSON — a Client Component receives data, never
475
+ instances — and, when the read fails, `undefined` and one line on the process's log: the page is
476
+ drawn anyway and the browser reads it on mount. `ServerRead<typeof useCase>` types the page's
477
+ `initial`:
478
+
479
+ ```tsx
480
+ // a route's loader or a Server Component — plain logic, no screen loaded
481
+ import { readOnServer } from "@sincpro/web-framework/core";
482
+ const balance = await readOnServer(project.Accounts.balance, [{ member_id }]);
483
+ return <Balance member={member_id} initial={balance} />;
484
+
485
+ // the page, rendered there and hydrated in the browser: it asks nothing on mount
486
+ const balance = useServiceReading(project.Accounts.balance, [{ member_id: member }], {
487
+ initial,
488
+ });
489
+ ```
490
+
491
+ The server's use cases are traced like the browser's and their `traceparent` reaches the API —
492
+ the counterpart of `browserTracer`, in its own optional entry. The provider is registered once
493
+ per process, where the SSR framework's own spans land too; the process is configured once per
494
+ realm (Next bundles instrumentation, Server Components and server rendering apart), and never in
495
+ a browser:
496
+
497
+ ```ts
498
+ // instrumentation.ts (Next) — once per process
499
+ export async function register() {
500
+ if (process.env.NEXT_RUNTIME !== "nodejs") return;
501
+ const { registerServerTracing } = await import("@sincpro/web-framework/telemetry/server");
502
+ const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; // none: tracing stays off
503
+ await registerServerTracing({ endpoint, release, environment, oneTreePerRequest: true });
504
+ }
505
+
506
+ // where the server runs use cases — once per realm; in a browser it does nothing
507
+ import { configureServerProcess } from "@sincpro/web-framework/telemetry/server";
508
+ configureServerProcess({ identity: { release } });
509
+ ```
510
+
511
+ With `oneTreePerRequest`, each request is one trace: the request the SSR framework traced, its
512
+ renders, the use cases its page read and what the API did with them. It registers Node's
513
+ `AsyncLocalStorage` context manager (the optional peer `@opentelemetry/context-async-hooks`),
514
+ unless the platform registered one first, and a use case with no parent of its own starts under
515
+ the active span (client-framework 2.5's `adoptActiveSpan`). Without it — the default — each use
516
+ case's span starts a trace of its own, as before.
517
+
518
+ A page that broke while drawing shows the route's error screen instead of the framework's generic
519
+ one: plain words, the code the server logged it with (Next's `digest`), «try again» and «home»,
520
+ reported once through the process:
521
+
522
+ ```tsx
523
+ // app/(portal)/error.tsx (Next) — the boundary is the framework's, the screen this one
524
+ "use client";
525
+ import { RouteError } from "@sincpro/web-framework";
526
+ export default function PortalError({ error, reset }: { error: Error; reset: () => void }) {
527
+ return <RouteError error={error} reset={reset} where="portal" home="/panel" />;
528
+ }
529
+ ```
530
+
469
531
  ## The abstractions
470
532
 
471
533
  Each answers one question, and each comes in the three levels — use the component, drop to the
@@ -476,8 +538,11 @@ hook and draw your own, or go straight to the loose piece.
476
538
  | Where is the data? | `entity()` (client-framework) | — | `restTransport`, `memoryTransport` |
477
539
  | The application's logic | its `Feature`s and `ApplicationService`s (client-framework) | `useService` | `project.Issues.close(…)` |
478
540
  | Read through a use case | its `Feature`s (client-framework) | `useServiceReading` | `project.Accounts.balance(…)` |
541
+ | Read it on the server first | the same use case, before the page is drawn | `useServiceReading(…, { initial })` | `readOnServer`, `ServerRead` |
479
542
  | What every use case runs with | `processContext`, `project.context` (client-framework) | `useContextValues` | `ContextStore` |
480
543
  | What happened, what broke | `./telemetry`, `./errors` (optional) | — | `configureProcess({ tracer, reporter })` |
544
+ | What happened, on the server | `configureServerProcess` (`./telemetry/server`, optional) | — | `registerServerTracing`, `serverTracer` |
545
+ | A page that broke | `RouteError`, in the route's error boundary | — | `reportError` (client-framework) |
481
546
  | What is each field? | `Meta` from the server, or `defineMeta` | — | `textOf`, `viewOf`, `metaFromSchema` |
482
547
  | A value outside a model | — | `useTextOf` | `moneyTextOf`, `dayTextOf`, `instantTextOf`, `numberTextOf` |
483
548
  | A file or a photo it holds | `EntityList`, `RecordField`: by its widget, as a `FileValue` | — | `attachmentOf`, `storedFileOf`, `renditionUrl` |
@@ -542,7 +607,7 @@ Not yet: a new record does not take the `params` it was opened with as its initi
542
607
 
543
608
  ### Inside
544
609
 
545
- Three levels, one direction, and two optional entries — `make doctor` keeps the arrows:
610
+ Three levels, one direction, and optional entries — `make doctor` keeps the arrows:
546
611
 
547
612
  | Folder | Knows | Why apart |
548
613
  | --------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
@@ -552,6 +617,7 @@ Three levels, one direction, and two optional entries — `make doctor` keeps th
552
617
  | `web/record` | one record: `RecordField`, `factsOf`, `RelatedList`, `EntityPicker`, `cardOf` | works outside a workspace (no composer) |
553
618
  | `web/workspace` | the composer: `entityView`, `openIn`, `RelatedRecord`, `<SincproApp>` | where it opens, the application context |
554
619
  | `telemetry`, `errors` | `browserTracer`, `glitchtipReporter`: built from the application's settings | optional peers, loaded after the first render; nothing else imports them |
620
+ | `telemetry/server` | `registerServerTracing`, `configureServerProcess`: a server's use cases traced | optional peers too; Node only — a browser never loads it |
555
621
 
556
622
  Screens import from `@sincpro/web-framework`. What every platform shares — the transport,
557
623
  `entity()`, model definitions, `Feature` and `ApplicationService`, the generated client — is
@@ -591,7 +657,10 @@ moves to the generated one — is [`docs/ADOPTION.md`](docs/ADOPTION.md).
591
657
  | `restTransport`, `memoryTransport` | The backend, or the same engine in memory (client-framework) | ✅ |
592
658
  | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI (client-framework) | ✅ |
593
659
  | `useService` | A screen runs one of the application's use cases: run, busy, answer, error | ✅ |
660
+ | `readOnServer` | A page read on the server by the browser's use case: plain JSON, a failure left to the browser | ✅ |
594
661
  | `./telemetry`, `./errors` | Optional: the application's traces to its OTLP endpoint, its errors to GlitchTip | ✅ |
662
+ | `./telemetry/server` | Optional: a rendering server's use cases on its OTLP provider, their trace continued by the API | ✅ |
663
+ | `RouteError` | A page that broke: plain words, the server's code, retry and home; reported once | ✅ |
595
664
  | `selection` | Filters named as criteria 2.0 and the backend read them, the search bar's included | ✅ |
596
665
  | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
597
666
  | `useRecord`, `factsOf`, `RecordLines` | One record: facts, relations with their real total | ✅ |
@@ -130,10 +130,30 @@ export type FrameworkCopy = {
130
130
  * its own refusal. */
131
131
  next: Partial<Record<FailureKind, string>>;
132
132
  };
133
+ /**
134
+ * A page that broke while drawing (`RouteError`). Optional, so a table an application wrote
135
+ * before it keeps compiling; without it the English words stand in.
136
+ */
137
+ route?: {
138
+ /** The heading: something went wrong showing the page. */
139
+ broke: string;
140
+ /** What it means, in plain words: not the person's doing; try again, say it if it repeats. */
141
+ sentence: string;
142
+ /** The code the server logged it with (`digest`), as the page shows it. */
143
+ code: (digest: string) => string;
144
+ /** Draws the page again. */
145
+ retry: string;
146
+ /** Leaves for the application's start. */
147
+ home: string;
148
+ };
133
149
  };
150
+ type RouteCopy = NonNullable<FrameworkCopy["route"]>;
134
151
  export declare const ENGLISH_FRAMEWORK_COPY: FrameworkCopy;
135
152
  export declare const SPANISH_FRAMEWORK_COPY: FrameworkCopy;
136
153
  /** Install the framework's words once, where the application starts. */
137
154
  export declare function installFrameworkCopy(copy: FrameworkCopy): void;
138
155
  /** The words in use. A plain read: they are installed before anything draws. */
139
156
  export declare const frameworkCopy: () => FrameworkCopy;
157
+ /** The words of a page that broke: the installed table's, or English when it has none. */
158
+ export declare const routeCopy: () => RouteCopy;
159
+ export {};
package/dist/core/copy.js CHANGED
@@ -1,3 +1,10 @@
1
+ const ENGLISH_ROUTE = {
2
+ broke: "Something went wrong showing this page",
3
+ sentence: "It is not something you did. Try again; if it happens again, report it.",
4
+ code: (digest) => `Code: ${digest}`,
5
+ retry: "Try again",
6
+ home: "Back to the start",
7
+ };
1
8
  export const ENGLISH_FRAMEWORK_COPY = {
2
9
  value: {
3
10
  yes: "yes",
@@ -100,6 +107,7 @@ export const ENGLISH_FRAMEWORK_COPY = {
100
107
  internal: "If it happens again, report it.",
101
108
  },
102
109
  },
110
+ route: ENGLISH_ROUTE,
103
111
  };
104
112
  export const SPANISH_FRAMEWORK_COPY = {
105
113
  value: {
@@ -203,6 +211,13 @@ export const SPANISH_FRAMEWORK_COPY = {
203
211
  internal: "Si vuelve a pasar, avisá a soporte.",
204
212
  },
205
213
  },
214
+ route: {
215
+ broke: "Algo salió mal al mostrar esta página",
216
+ sentence: "No es algo que hayas hecho. Intentá de nuevo; si vuelve a pasar, avisá a soporte.",
217
+ code: (digest) => `Código: ${digest}`,
218
+ retry: "Intentar de nuevo",
219
+ home: "Volver al inicio",
220
+ },
206
221
  };
207
222
  let installed = ENGLISH_FRAMEWORK_COPY;
208
223
  /** Install the framework's words once, where the application starts. */
@@ -211,3 +226,5 @@ export function installFrameworkCopy(copy) {
211
226
  }
212
227
  /** The words in use. A plain read: they are installed before anything draws. */
213
228
  export const frameworkCopy = () => installed;
229
+ /** The words of a page that broke: the installed table's, or English when it has none. */
230
+ export const routeCopy = () => installed.route ?? ENGLISH_ROUTE;
@@ -23,5 +23,6 @@ export { detailOf, measuresOf, sumsOf, type Total, totalOf, } from "./measure.js
23
23
  export { BOOKKEEPING, currencyNow, type DateStyle, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, type FieldView, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
24
24
  export { type Related, relatedOf } from "./related.js";
25
25
  export { backReference, entityFor, relatedScope, type RelationField, relationFieldOf, } from "./relation.js";
26
+ export { readOnServer, type ServerRead } from "./server.js";
26
27
  export { type RecordSummary, summaryFieldsOf, summaryOf, } from "./summary.js";
27
28
  export { placeOf, stepIn, type Trail } from "./trail.js";
@@ -23,5 +23,6 @@ export { detailOf, measuresOf, sumsOf, totalOf, } from "./measure.js";
23
23
  export { BOOKKEEPING, currencyNow, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
24
24
  export { relatedOf } from "./related.js";
25
25
  export { backReference, entityFor, relatedScope, relationFieldOf, } from "./relation.js";
26
+ export { readOnServer } from "./server.js";
26
27
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
27
28
  export { placeOf, stepIn } from "./trail.js";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A use case's answer read on the server that renders a page, before it is drawn — the very use
3
+ * case the page reads with in the browser (`useServiceReading`), so the page arrives with its
4
+ * data in the HTML (what a search engine, a crawler and a shared link read) and the browser does
5
+ * not ask again.
6
+ *
7
+ * // the server: a route's loader, a Server Component
8
+ * const balance = await readOnServer(project.Accounts.balance, [{ member_id }]);
9
+ * <Balance member={member_id} initial={balance} />
10
+ *
11
+ * // the page, rendered there and hydrated in the browser: the same use case, the same args
12
+ * type Props = { member: string; initial?: ServerRead<typeof project.Accounts.balance> };
13
+ * function Balance({ member, initial }: Props) {
14
+ * const balance = useServiceReading(project.Accounts.balance, [{ member_id: member }], {
15
+ * initial,
16
+ * });
17
+ * }
18
+ *
19
+ * Context: what crosses from the server to the browser is plain JSON — a Client Component is
20
+ * handed data, never instances, and a `Date` arrives as its text —, so the answer is written and
21
+ * read back as JSON here: a framework that refuses a class instance as a prop never sees one.
22
+ *
23
+ * A read that fails never refuses the page: it answers `undefined`, the page is drawn without
24
+ * it, and the browser reads it on mount, as a single-page application does. The failure is one
25
+ * line on the process's log (client-framework's `logger`, WARN: it always speaks) saying `what`
26
+ * was not read — the use case's own name when not given. A use case run through its bounded
27
+ * context already traced and reported its failure, so nothing is reported twice here; and, as
28
+ * there, a refusal (a 404, a permission) says its type and kind, never its message. A use case
29
+ * that answers nothing stays nothing, without a line.
30
+ *
31
+ * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
32
+ * script import it from `@sincpro/web-framework/core` without loading any screen.
33
+ */
34
+ export declare function readOnServer<A extends unknown[], R>(useCase: (...args: A) => R | Promise<R>, args: A, options?: {
35
+ what?: string;
36
+ }): Promise<Awaited<R> | undefined>;
37
+ /**
38
+ * What `readOnServer` answers for a use case — its answer, or `undefined` when it could not be
39
+ * read —: the type of a page's `initial`, handed to `useServiceReading(useCase, args, {
40
+ * initial })` as it is.
41
+ *
42
+ * type Props = { initial?: ServerRead<typeof project.Accounts.balance> };
43
+ */
44
+ export type ServerRead<U extends (...args: never[]) => unknown> = Awaited<ReturnType<U>> | undefined;
@@ -0,0 +1,54 @@
1
+ import { describeFailure, logger, outcomeOf } from "@sincpro/client-framework";
2
+ /**
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.
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} />
11
+ *
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
+ * }
19
+ *
20
+ * 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.
23
+ *
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.
31
+ *
32
+ * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
33
+ * script import it from `@sincpro/web-framework/core` without loading any screen.
34
+ */
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)
41
+ return undefined;
42
+ return JSON.parse(JSON.stringify(answer));
43
+ }
44
+ catch (error) {
45
+ const failure = describeFailure(error, outcomeOf(error));
46
+ logger.warn("read on the server failed: the page is drawn without it", {
47
+ what: options.what ?? (useCase.name || "a use case"),
48
+ "error.type": failure.type,
49
+ "error.kind": failure.kind,
50
+ ...(failure.message === undefined ? {} : { "error.message": failure.message }),
51
+ });
52
+ return undefined;
53
+ }
54
+ }
@@ -29,6 +29,17 @@ export type Trail = {
29
29
  /** How many there are in all, when the server counted them. */
30
30
  total: number | null;
31
31
  };
32
+ /**
33
+ * The key a list's trail is kept by — and the `from` the records opened from it carry in their
34
+ * link: the list's React id (`useId()`), marked with this page load.
35
+ *
36
+ * Context: React's ids start over on every load, and a workspace restores its links from the
37
+ * URL. Unmarked, a record restored after a reload could name the trail of whichever new list
38
+ * happened to get the same id, and show its «3 / 64» and walk its rows. Marked, an old link
39
+ * names no trail of this load, and the record simply shows none. The key never reaches the
40
+ * HTML (a row opens its record on a click), so it cannot differ between server and browser.
41
+ */
42
+ export declare function trailKeyOf(listId: string): string;
32
43
  /** Where a record stands in its trail: «3 of 64», 1-based. */
33
44
  export declare function placeOf(trail: Trail, id: string): {
34
45
  index: number;
@@ -1,5 +1,20 @@
1
1
  import {} from "@sincpro/client-framework";
2
2
  import { resumingFrom } from "@sincpro/criteria";
3
+ /** This page load's mark: drawn once per load of this module, never sent anywhere. */
4
+ const PAGE_LOAD = Math.random().toString(36).slice(2, 8);
5
+ /**
6
+ * The key a list's trail is kept by — and the `from` the records opened from it carry in their
7
+ * link: the list's React id (`useId()`), marked with this page load.
8
+ *
9
+ * Context: React's ids start over on every load, and a workspace restores its links from the
10
+ * URL. Unmarked, a record restored after a reload could name the trail of whichever new list
11
+ * happened to get the same id, and show its «3 / 64» and walk its rows. Marked, an old link
12
+ * names no trail of this load, and the record simply shows none. The key never reaches the
13
+ * HTML (a row opens its record on a click), so it cannot differ between server and browser.
14
+ */
15
+ export function trailKeyOf(listId) {
16
+ return `trail:${PAGE_LOAD}${listId}`;
17
+ }
3
18
  /** Where a record stands in its trail: «3 of 64», 1-based. */
4
19
  export function placeOf(trail, id) {
5
20
  const at = trail.ids.indexOf(id);
@@ -0,0 +1,115 @@
1
+ import { type Attributes, type ProcessOptions, type Tracer } from "@sincpro/client-framework";
2
+ /**
3
+ * The server's side of `./telemetry`: what a server that renders pages — Next.js, TanStack
4
+ * Start, Remix, a Node process of one's own — needs so its use cases are traced like the
5
+ * browser's, and their `traceparent` reaches the API.
6
+ *
7
+ * // once per process — Next's instrumentation.ts (no Next here: the application wires it)
8
+ * export async function register() {
9
+ * if (process.env.NEXT_RUNTIME !== "nodejs") return;
10
+ * const { registerServerTracing } = await import("./server.js");
11
+ * const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; // from its settings
12
+ * await registerServerTracing({ endpoint, release, environment, oneTreePerRequest: true });
13
+ * }
14
+ *
15
+ * // once per realm, where the server runs use cases — a module that reads on the server
16
+ * configureServerProcess({ identity: { release } });
17
+ *
18
+ * Context: two lifetimes, because a server that renders is one process with several module
19
+ * realms — Next loads instrumentation, its Server Components and its server rendering of Client
20
+ * Components as separate bundles, each with its own copy of this package and of
21
+ * @sincpro/client-framework, so each its own `configureProcess`. What is per PROCESS lives where
22
+ * every realm sees it: OpenTelemetry's global provider (`registerServerTracing`), which the
23
+ * SSR framework's own spans reach too. What is per REALM is the process's configuration
24
+ * (`configureServerProcess`), tracing on that global provider — whoever registered it, this
25
+ * entry or the application's own SDK (`@vercel/otel`, `NodeSDK`).
26
+ *
27
+ * Optional on every count, like `./telemetry`: an entry of its own that nothing else imports,
28
+ * the same optional peers (`@opentelemetry/api`, `@opentelemetry/sdk-trace`,
29
+ * `@opentelemetry/exporter-trace-otlp-http`, `@opentelemetry/resources`, and
30
+ * `@opentelemetry/context-async-hooks` for `oneTreePerRequest`) loaded with `import()`,
31
+ * and nothing throws: without an endpoint nothing loads and nothing is registered; if the SDK
32
+ * is not installed or fails, that is said once on the console and use cases run untraced,
33
+ * sending no `traceparent`. Node only — an edge runtime skips it (its exporter speaks `http`).
34
+ */
35
+ export type ServerTracingOptions = {
36
+ /**
37
+ * The OTLP/HTTP traces endpoint (`https://collector.example.com/v1/traces`), from the
38
+ * application's settings. None — an empty setting — and tracing is off: nothing is loaded.
39
+ */
40
+ endpoint: string | undefined;
41
+ /** `<name>:<version>` as deployed, the backend's `APP_RELEASE`: read as `tracerResource` reads it. */
42
+ release?: string;
43
+ /** `service.name`, when it is not the release's name. */
44
+ service?: string;
45
+ /** `deployment.environment.name`: `production`, `staging`… */
46
+ environment?: string;
47
+ /** Headers the endpoint asks for. A secret may go here: it never leaves the server. */
48
+ headers?: Readonly<Record<string, string>>;
49
+ /** Fraction of traces kept, 0 to 1 — a trace begun elsewhere keeps its decision. Default 1. */
50
+ sampling?: number;
51
+ /** More resource attributes (`tenant.group`, …). */
52
+ attributes?: Attributes;
53
+ /**
54
+ * Each request one tree — the request the SSR framework traces, its renders, the use cases a
55
+ * page reads and what the backend did with them. Node's AsyncLocalStorage carries the active
56
+ * span through each request's awaits (registered here, unless the platform registered a
57
+ * context manager of its own first), and a use case run with no parent of its own starts
58
+ * under it (client-framework's `adoptActiveSpan`, 2.5+).
59
+ *
60
+ * Default `false`, as before: a use case's span is the root of its trace. Turning it on loads
61
+ * one more optional peer, `@opentelemetry/context-async-hooks`; if it does not load, that is
62
+ * said once and the rest works as without it.
63
+ */
64
+ oneTreePerRequest?: boolean;
65
+ };
66
+ /** The process's tracing, once registered. */
67
+ export type ServerTracing = {
68
+ /** Sends what is buffered now: a script that ends, a test. */
69
+ flush: () => Promise<void>;
70
+ /** Sends what is buffered and stops: a server shutting down. */
71
+ shutdown: () => Promise<void>;
72
+ };
73
+ /**
74
+ * OpenTelemetry's provider for this server process: OTLP/HTTP to the application's endpoint,
75
+ * resource and sampling as `browserTracer`'s (`tracerResource`), registered GLOBALLY — so the
76
+ * SSR framework's own spans (each request, each render) go there, and every realm's use cases
77
+ * (`configureServerProcess`). Once per process: a second call, from any realm, answers the
78
+ * first's. It answers `undefined` when tracing stays off — no endpoint, the SDK did not load, or
79
+ * another provider was registered first (then use cases trace on THAT one).
80
+ */
81
+ export declare function registerServerTracing(options: ServerTracingOptions): Promise<ServerTracing | undefined>;
82
+ /**
83
+ * A `Tracer` over the process's OpenTelemetry provider — the loose piece `configureServerProcess`
84
+ * plugs, for an application that calls `configureProcess` itself:
85
+ *
86
+ * configureProcess({ identity: { release }, tracer: serverTracer({ release }), logger });
87
+ *
88
+ * Context: the provider is the process's, never this tracer's: the one `registerServerTracing`
89
+ * registered, or the application's own SDK. Read synchronously once some realm of the process
90
+ * loaded OpenTelemetry's API — `registerServerTracing` does, before the first page —; until then
91
+ * (a realm that registers nothing, the first moment), use cases run untraced. With no provider
92
+ * registered OpenTelemetry records nothing, so no `traceparent` claims a trace that does not
93
+ * exist.
94
+ */
95
+ export declare function serverTracer(options?: {
96
+ release?: string;
97
+ service?: string;
98
+ }): Tracer;
99
+ /**
100
+ * The process configured for the use cases a server runs, once per realm: client-framework's
101
+ * `configureProcess` with these options — `identity`, `reporter`, `logger`, `context`… — and,
102
+ * unless one is given, a tracer on the process's OpenTelemetry provider (`serverTracer`). Every
103
+ * module that reads on the server may call it at its top: the first call in a realm configures,
104
+ * the rest do nothing. In a browser it does nothing — the browser's process is its `main`'s
105
+ * (`browserTracer`) —, so a module the server and the browser both load may call it too. It
106
+ * answers whether this call configured the process.
107
+ *
108
+ * // domains/common/infrastructure/server.ts — imported where the server reads
109
+ * configureServerProcess({ identity: { release: "my-web:1.4.0" } });
110
+ *
111
+ * Context: `configureProcess` replaces everything it is given — the context store included —,
112
+ * so a second call per realm would start the process over between two requests. A test that
113
+ * needs its own tracer calls `configureProcess` directly.
114
+ */
115
+ export declare function configureServerProcess(options?: ProcessOptions): boolean;
@@ -0,0 +1,158 @@
1
+ import { configureProcess, identityOf, NO_TRACER, } from "@sincpro/client-framework";
2
+ import { tracerResource } from "./index.js";
3
+ const HELD = Symbol.for("@sincpro/web-framework/telemetry/server");
4
+ function held() {
5
+ const global = globalThis;
6
+ return (global[HELD] ??= {});
7
+ }
8
+ const WHO = "@sincpro/web-framework/telemetry/server";
9
+ /**
10
+ * OpenTelemetry's provider for this server process: OTLP/HTTP to the application's endpoint,
11
+ * resource and sampling as `browserTracer`'s (`tracerResource`), registered GLOBALLY — so the
12
+ * SSR framework's own spans (each request, each render) go there, and every realm's use cases
13
+ * (`configureServerProcess`). Once per process: a second call, from any realm, answers the
14
+ * first's. It answers `undefined` when tracing stays off — no endpoint, the SDK did not load, or
15
+ * another provider was registered first (then use cases trace on THAT one).
16
+ */
17
+ export function registerServerTracing(options) {
18
+ const endpoint = options.endpoint;
19
+ if (!endpoint)
20
+ return Promise.resolve(undefined);
21
+ const shared = held();
22
+ if (shared.registered === undefined) {
23
+ // Before the first page: every realm's tracer reads it when it is first asked for.
24
+ shared.adoptActiveSpan = options.oneTreePerRequest === true;
25
+ shared.registered = started({ ...options, endpoint });
26
+ }
27
+ return shared.registered;
28
+ }
29
+ /** A tracer of client-framework's over OpenTelemetry's, as this process's registration asked. */
30
+ function tracerOver(trace, overOpenTelemetry) {
31
+ return (name) => overOpenTelemetry(trace.getTracer(name), {
32
+ adoptActiveSpan: held().adoptActiveSpan === true,
33
+ });
34
+ }
35
+ /**
36
+ * What is active follows each request through its awaits: Node's AsyncLocalStorage, registered
37
+ * with OpenTelemetry's API — unless the platform registered a context manager first, which then
38
+ * carries it.
39
+ */
40
+ async function followEachRequest() {
41
+ try {
42
+ const [{ context }, { AsyncLocalStorageContextManager }] = await Promise.all([
43
+ import("@opentelemetry/api"),
44
+ import("@opentelemetry/context-async-hooks"),
45
+ ]);
46
+ const manager = new AsyncLocalStorageContextManager().enable();
47
+ if (!context.setGlobalContextManager(manager))
48
+ manager.disable();
49
+ }
50
+ catch (error) {
51
+ console.warn(`${WHO}: a request is not one tree — @opentelemetry/context-async-hooks did not load`, error);
52
+ }
53
+ }
54
+ async function started(options) {
55
+ try {
56
+ const [{ trace }, { TracerProvider, BatchSpanProcessor, TraceIdRatioBasedSampler, ParentBasedSampler }, { OTLPTraceExporter }, { resourceFromAttributes }, { openTelemetryTracer },] = await Promise.all([
57
+ import("@opentelemetry/api"),
58
+ import("@opentelemetry/sdk-trace"),
59
+ import("@opentelemetry/exporter-trace-otlp-http"),
60
+ import("@opentelemetry/resources"),
61
+ import("@sincpro/client-framework/opentelemetry"),
62
+ ]);
63
+ if (options.oneTreePerRequest === true)
64
+ await followEachRequest();
65
+ const exporter = new OTLPTraceExporter({
66
+ url: options.endpoint,
67
+ ...(options.headers ? { headers: { ...options.headers } } : {}),
68
+ });
69
+ const provider = new TracerProvider({
70
+ resource: resourceFromAttributes(tracerResource(options)),
71
+ sampler: new ParentBasedSampler({
72
+ root: new TraceIdRatioBasedSampler(options.sampling ?? 1),
73
+ }),
74
+ spanProcessors: [new BatchSpanProcessor({ exporter })],
75
+ });
76
+ held().tracerOf ??= tracerOver(trace, openTelemetryTracer);
77
+ if (!trace.setGlobalTracerProvider(provider)) {
78
+ await provider.shutdown();
79
+ console.warn(`${WHO}: another provider was registered first — use cases trace on it`);
80
+ return undefined;
81
+ }
82
+ return { flush: () => provider.forceFlush(), shutdown: () => provider.shutdown() };
83
+ }
84
+ catch (error) {
85
+ console.warn(`${WHO}: tracing is off — OpenTelemetry's SDK did not load`, error);
86
+ return undefined;
87
+ }
88
+ }
89
+ let loading;
90
+ /** OpenTelemetry's API, for a realm that did not register the provider itself. */
91
+ function loadApi() {
92
+ loading ??= (async () => {
93
+ try {
94
+ const [{ trace }, { openTelemetryTracer }] = await Promise.all([
95
+ import("@opentelemetry/api"),
96
+ import("@sincpro/client-framework/opentelemetry"),
97
+ ]);
98
+ held().tracerOf ??= tracerOver(trace, openTelemetryTracer);
99
+ }
100
+ catch (error) {
101
+ console.warn(`${WHO}: tracing is off — @opentelemetry/api did not load`, error);
102
+ }
103
+ })();
104
+ return loading;
105
+ }
106
+ /**
107
+ * A `Tracer` over the process's OpenTelemetry provider — the loose piece `configureServerProcess`
108
+ * plugs, for an application that calls `configureProcess` itself:
109
+ *
110
+ * configureProcess({ identity: { release }, tracer: serverTracer({ release }), logger });
111
+ *
112
+ * Context: the provider is the process's, never this tracer's: the one `registerServerTracing`
113
+ * registered, or the application's own SDK. Read synchronously once some realm of the process
114
+ * loaded OpenTelemetry's API — `registerServerTracing` does, before the first page —; until then
115
+ * (a realm that registers nothing, the first moment), use cases run untraced. With no provider
116
+ * registered OpenTelemetry records nothing, so no `traceparent` claims a trace that does not
117
+ * exist.
118
+ */
119
+ export function serverTracer(options = {}) {
120
+ const name = options.service ??
121
+ (options.release ? identityOf(options.release).serviceName : undefined) ??
122
+ "unknown_service";
123
+ let ready;
124
+ const now = () => (ready ??= held().tracerOf?.(name));
125
+ if (now() === undefined)
126
+ void loadApi();
127
+ return {
128
+ start: (span, startOptions) => (now() ?? NO_TRACER).start(span, startOptions),
129
+ };
130
+ }
131
+ let configured = false;
132
+ /**
133
+ * The process configured for the use cases a server runs, once per realm: client-framework's
134
+ * `configureProcess` with these options — `identity`, `reporter`, `logger`, `context`… — and,
135
+ * unless one is given, a tracer on the process's OpenTelemetry provider (`serverTracer`). Every
136
+ * module that reads on the server may call it at its top: the first call in a realm configures,
137
+ * the rest do nothing. In a browser it does nothing — the browser's process is its `main`'s
138
+ * (`browserTracer`) —, so a module the server and the browser both load may call it too. It
139
+ * answers whether this call configured the process.
140
+ *
141
+ * // domains/common/infrastructure/server.ts — imported where the server reads
142
+ * configureServerProcess({ identity: { release: "my-web:1.4.0" } });
143
+ *
144
+ * Context: `configureProcess` replaces everything it is given — the context store included —,
145
+ * so a second call per realm would start the process over between two requests. A test that
146
+ * needs its own tracer calls `configureProcess` directly.
147
+ */
148
+ export function configureServerProcess(options = {}) {
149
+ if (configured || typeof window !== "undefined")
150
+ return false;
151
+ configured = true;
152
+ configureProcess({
153
+ ...options,
154
+ tracer: options.tracer ??
155
+ serverTracer(options.identity ? { release: options.identity.release } : {}),
156
+ });
157
+ return true;
158
+ }
@@ -0,0 +1,36 @@
1
+ export type RouteErrorProps = {
2
+ /**
3
+ * What broke, as the route's error boundary hands it: Next's `error.tsx` and TanStack
4
+ * Router's `errorComponent` give it as a prop, React Router's `useRouteError()` returns it.
5
+ * Its `digest`, when there is one, is the code the server logged the failure with.
6
+ */
7
+ error: unknown;
8
+ /** Draws the page again — the boundary's `reset`. None: no «try again». */
9
+ reset?: () => void;
10
+ /** Where it broke, for the report («portal», «admin»): the name the report goes by. */
11
+ where?: string;
12
+ /** Where «back to the start» leads: the application's own start. None: no link. */
13
+ home?: string;
14
+ };
15
+ /**
16
+ * What a person sees when a page broke while drawing, instead of the framework's generic page:
17
+ * what happened in plain words, the code that finds it in the server's logs, a way to try again
18
+ * and a way to the start. The failure is reported once, through the process
19
+ * (`reportError`): to GlitchTip when the application reports.
20
+ *
21
+ * // Next — app/(portal)/error.tsx; the boundary is the framework's, the screen this one
22
+ * "use client";
23
+ * type Props = { error: Error & { digest?: string }; reset: () => void };
24
+ * export default function PortalError({ error, reset }: Props) {
25
+ * return <RouteError error={error} reset={reset} where="portal" home="/panel" />;
26
+ * }
27
+ *
28
+ * Context: no router is imported here — Next, TanStack Start and React Router each hand their
29
+ * boundary's error (and a way to reset it), and the application passes them on. A server render
30
+ * that fails reaches the browser without its message — only the `digest` the server logged it
31
+ * with —, so the code is what is shown: what the person quotes is what support searches for
32
+ * (web-ui's `Failed` draws it as data and copies it with «Copiar el error»). The message itself
33
+ * is never drawn: it is the system's, not the person's. The words are the copy table's
34
+ * (`route`); `reportError` reports an error once, however many times this renders.
35
+ */
36
+ export declare function RouteError({ error, reset, where, home }: RouteErrorProps): import("react").JSX.Element;
@@ -0,0 +1,41 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { reportError } from "@sincpro/client-framework";
4
+ import { routeCopy } from "../core/copy.js";
5
+ import { Button, ButtonLink, Failed } from "@sincpro/web-ui";
6
+ import { useEffect } from "react";
7
+ /** The code a server gave the failure — Next's `digest` — when it gave one. */
8
+ function digestOf(error) {
9
+ if (typeof error !== "object" || error === null || !("digest" in error))
10
+ return undefined;
11
+ const digest = error.digest;
12
+ return typeof digest === "string" && digest !== "" ? digest : undefined;
13
+ }
14
+ /**
15
+ * What a person sees when a page broke while drawing, instead of the framework's generic page:
16
+ * what happened in plain words, the code that finds it in the server's logs, a way to try again
17
+ * and a way to the start. The failure is reported once, through the process
18
+ * (`reportError`): to GlitchTip when the application reports.
19
+ *
20
+ * // Next — app/(portal)/error.tsx; the boundary is the framework's, the screen this one
21
+ * "use client";
22
+ * type Props = { error: Error & { digest?: string }; reset: () => void };
23
+ * export default function PortalError({ error, reset }: Props) {
24
+ * return <RouteError error={error} reset={reset} where="portal" home="/panel" />;
25
+ * }
26
+ *
27
+ * Context: no router is imported here — Next, TanStack Start and React Router each hand their
28
+ * boundary's error (and a way to reset it), and the application passes them on. A server render
29
+ * that fails reaches the browser without its message — only the `digest` the server logged it
30
+ * with —, so the code is what is shown: what the person quotes is what support searches for
31
+ * (web-ui's `Failed` draws it as data and copies it with «Copiar el error»). The message itself
32
+ * is never drawn: it is the system's, not the person's. The words are the copy table's
33
+ * (`route`); `reportError` reports an error once, however many times this renders.
34
+ */
35
+ export function RouteError({ error, reset, where = "route", home }) {
36
+ useEffect(() => reportError(error, where), [error, where]);
37
+ const copy = routeCopy();
38
+ const digest = digestOf(error);
39
+ const actions = reset === undefined && home === undefined ? undefined : (_jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [reset === undefined ? null : (_jsx(Button, { role: "primary", onClick: () => reset(), children: copy.retry })), home === undefined ? null : (_jsx(ButtonLink, { role: "secondary", href: home, children: copy.home }))] }));
40
+ return (_jsx("div", { role: "alert", className: "mx-auto flex max-w-prose flex-col px-4 py-10", children: _jsx(Failed, { heading: copy.broke, sentence: copy.sentence, detail: digest === undefined ? undefined : copy.code(digest), action: actions }) }));
41
+ }
@@ -30,6 +30,7 @@ export { RelatedList } from "./record/RelatedList.js";
30
30
  export { type ServiceActionProps, ServiceButton, useServiceAction, } from "./record/ServiceButton.js";
31
31
  export { cardOf, relationOf } from "./record/summary.js";
32
32
  export { Refused } from "./Refused.js";
33
+ export { RouteError, type RouteErrorProps } from "./RouteError.js";
33
34
  export { entityView, type EntityViewOptions, listView, type ListViewOptions, } from "./workspace/composer.js";
34
35
  export { openIn, openOptions, RECORD_SIZE, RelatedRecord, targetsFor, } from "./workspace/open.js";
35
36
  export { EntityRecord, type Stamp, useRecordScreen, } from "./workspace/record.js";
package/dist/web/index.js CHANGED
@@ -30,6 +30,7 @@ export { RelatedList } from "./record/RelatedList.js";
30
30
  export { ServiceButton, useServiceAction, } from "./record/ServiceButton.js";
31
31
  export { cardOf, relationOf } from "./record/summary.js";
32
32
  export { Refused } from "./Refused.js";
33
+ export { RouteError } from "./RouteError.js";
33
34
  export { entityView, listView, } from "./workspace/composer.js";
34
35
  export { openIn, openOptions, RECORD_SIZE, RelatedRecord, targetsFor, } from "./workspace/open.js";
35
36
  export { EntityRecord, useRecordScreen, } from "./workspace/record.js";
@@ -9,6 +9,7 @@ import { explain } from "../../core/explain.js";
9
9
  import { choosesMany, } from "../../core/list.js";
10
10
  import { textOf, viewOf } from "../../core/present.js";
11
11
  import { summaryFieldsOf } from "../../core/summary.js";
12
+ import { trailKeyOf } from "../../core/trail.js";
12
13
  import { useFramework } from "../../react/context.js";
13
14
  import { useGroups } from "../../react/useGroups.js";
14
15
  import { usePivot } from "../../react/usePivot.js";
@@ -81,7 +82,7 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
81
82
  const ticking = selectable || choosingMany || selectionActions !== undefined;
82
83
  // The record opened from a row knows the page it came from: «3 / 64» and its neighbours.
83
84
  const { trails, dateStyle } = useFramework();
84
- const trailKey = `trail:${useId()}`;
85
+ const trailKey = trailKeyOf(useId());
85
86
  // Kept current with the page on screen: the row and its name (`RecordLink`) open the same
86
87
  // reference, and whichever opens it, the record finds where it came from.
87
88
  useEffect(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-framework",
3
- "version": "3.8.0",
3
+ "version": "3.10.0",
4
4
  "description": "The web client of sincpro_framework: entities, lists and records bound to the metadata the server publishes, drawn with @sincpro/web-ui and arranged with @sincpro/web-composer.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -18,6 +18,10 @@
18
18
  "types": "./dist/telemetry/index.d.ts",
19
19
  "default": "./dist/telemetry/index.js"
20
20
  },
21
+ "./telemetry/server": {
22
+ "types": "./dist/telemetry/server.d.ts",
23
+ "default": "./dist/telemetry/server.js"
24
+ },
21
25
  "./errors": {
22
26
  "types": "./dist/errors/index.d.ts",
23
27
  "default": "./dist/errors/index.js"
@@ -36,6 +40,7 @@
36
40
  },
37
41
  "peerDependencies": {
38
42
  "@opentelemetry/api": "^1.10.0",
43
+ "@opentelemetry/context-async-hooks": "^3.1.0",
39
44
  "@opentelemetry/exporter-trace-otlp-http": "^0.301.0",
40
45
  "@opentelemetry/resources": "^3.1.0",
41
46
  "@opentelemetry/sdk-trace": "^3.1.0",
@@ -52,6 +57,9 @@
52
57
  "@opentelemetry/api": {
53
58
  "optional": true
54
59
  },
60
+ "@opentelemetry/context-async-hooks": {
61
+ "optional": true
62
+ },
55
63
  "@opentelemetry/exporter-trace-otlp-http": {
56
64
  "optional": true
57
65
  },
@@ -68,11 +76,12 @@
68
76
  "devDependencies": {
69
77
  "@eslint/js": "^10.0.1",
70
78
  "@opentelemetry/api": "1.10.0",
79
+ "@opentelemetry/context-async-hooks": "3.1.1",
71
80
  "@opentelemetry/exporter-trace-otlp-http": "0.301.0",
72
81
  "@opentelemetry/resources": "3.1.0",
73
82
  "@opentelemetry/sdk-trace": "3.1.0",
74
83
  "@sentry/browser": "11.11.0",
75
- "@sincpro/client-framework": "^2.3.0",
84
+ "@sincpro/client-framework": "^2.5.0",
76
85
  "@sincpro/criteria": "^2.4.0",
77
86
  "@sincpro/criteria-react": "^2.4.0",
78
87
  "@sincpro/web-composer": "^1.8.0",