@sincpro/web-framework 3.8.0 → 3.9.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,61 @@ 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 });
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
+ A page that broke while drawing shows the route's error screen instead of the framework's generic
512
+ one: plain words, the code the server logged it with (Next's `digest`), «try again» and «home»,
513
+ reported once through the process:
514
+
515
+ ```tsx
516
+ // app/(portal)/error.tsx (Next) — the boundary is the framework's, the screen this one
517
+ "use client";
518
+ import { RouteError } from "@sincpro/web-framework";
519
+ export default function PortalError({ error, reset }: { error: Error; reset: () => void }) {
520
+ return <RouteError error={error} reset={reset} where="portal" home="/panel" />;
521
+ }
522
+ ```
523
+
469
524
  ## The abstractions
470
525
 
471
526
  Each answers one question, and each comes in the three levels — use the component, drop to the
@@ -476,8 +531,11 @@ hook and draw your own, or go straight to the loose piece.
476
531
  | Where is the data? | `entity()` (client-framework) | — | `restTransport`, `memoryTransport` |
477
532
  | The application's logic | its `Feature`s and `ApplicationService`s (client-framework) | `useService` | `project.Issues.close(…)` |
478
533
  | Read through a use case | its `Feature`s (client-framework) | `useServiceReading` | `project.Accounts.balance(…)` |
534
+ | Read it on the server first | the same use case, before the page is drawn | `useServiceReading(…, { initial })` | `readOnServer`, `ServerRead` |
479
535
  | What every use case runs with | `processContext`, `project.context` (client-framework) | `useContextValues` | `ContextStore` |
480
536
  | What happened, what broke | `./telemetry`, `./errors` (optional) | — | `configureProcess({ tracer, reporter })` |
537
+ | What happened, on the server | `configureServerProcess` (`./telemetry/server`, optional) | — | `registerServerTracing`, `serverTracer` |
538
+ | A page that broke | `RouteError`, in the route's error boundary | — | `reportError` (client-framework) |
481
539
  | What is each field? | `Meta` from the server, or `defineMeta` | — | `textOf`, `viewOf`, `metaFromSchema` |
482
540
  | A value outside a model | — | `useTextOf` | `moneyTextOf`, `dayTextOf`, `instantTextOf`, `numberTextOf` |
483
541
  | A file or a photo it holds | `EntityList`, `RecordField`: by its widget, as a `FileValue` | — | `attachmentOf`, `storedFileOf`, `renditionUrl` |
@@ -542,7 +600,7 @@ Not yet: a new record does not take the `params` it was opened with as its initi
542
600
 
543
601
  ### Inside
544
602
 
545
- Three levels, one direction, and two optional entries — `make doctor` keeps the arrows:
603
+ Three levels, one direction, and optional entries — `make doctor` keeps the arrows:
546
604
 
547
605
  | Folder | Knows | Why apart |
548
606
  | --------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
@@ -552,6 +610,7 @@ Three levels, one direction, and two optional entries — `make doctor` keeps th
552
610
  | `web/record` | one record: `RecordField`, `factsOf`, `RelatedList`, `EntityPicker`, `cardOf` | works outside a workspace (no composer) |
553
611
  | `web/workspace` | the composer: `entityView`, `openIn`, `RelatedRecord`, `<SincproApp>` | where it opens, the application context |
554
612
  | `telemetry`, `errors` | `browserTracer`, `glitchtipReporter`: built from the application's settings | optional peers, loaded after the first render; nothing else imports them |
613
+ | `telemetry/server` | `registerServerTracing`, `configureServerProcess`: a server's use cases traced | optional peers too; Node only — a browser never loads it |
555
614
 
556
615
  Screens import from `@sincpro/web-framework`. What every platform shares — the transport,
557
616
  `entity()`, model definitions, `Feature` and `ApplicationService`, the generated client — is
@@ -591,7 +650,10 @@ moves to the generated one — is [`docs/ADOPTION.md`](docs/ADOPTION.md).
591
650
  | `restTransport`, `memoryTransport` | The backend, or the same engine in memory (client-framework) | ✅ |
592
651
  | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI (client-framework) | ✅ |
593
652
  | `useService` | A screen runs one of the application's use cases: run, busy, answer, error | ✅ |
653
+ | `readOnServer` | A page read on the server by the browser's use case: plain JSON, a failure left to the browser | ✅ |
594
654
  | `./telemetry`, `./errors` | Optional: the application's traces to its OTLP endpoint, its errors to GlitchTip | ✅ |
655
+ | `./telemetry/server` | Optional: a rendering server's use cases on its OTLP provider, their trace continued by the API | ✅ |
656
+ | `RouteError` | A page that broke: plain words, the server's code, retry and home; reported once | ✅ |
595
657
  | `selection` | Filters named as criteria 2.0 and the backend read them, the search bar's included | ✅ |
596
658
  | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
597
659
  | `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
+ }
@@ -0,0 +1,102 @@
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 });
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`) loaded with `import()`,
30
+ * and nothing throws: without an endpoint nothing loads and nothing is registered; if the SDK
31
+ * is not installed or fails, that is said once on the console and use cases run untraced,
32
+ * sending no `traceparent`. Node only — an edge runtime skips it (its exporter speaks `http`).
33
+ */
34
+ export type ServerTracingOptions = {
35
+ /**
36
+ * The OTLP/HTTP traces endpoint (`https://collector.example.com/v1/traces`), from the
37
+ * application's settings. None — an empty setting — and tracing is off: nothing is loaded.
38
+ */
39
+ endpoint: string | undefined;
40
+ /** `<name>:<version>` as deployed, the backend's `APP_RELEASE`: read as `tracerResource` reads it. */
41
+ release?: string;
42
+ /** `service.name`, when it is not the release's name. */
43
+ service?: string;
44
+ /** `deployment.environment.name`: `production`, `staging`… */
45
+ environment?: string;
46
+ /** Headers the endpoint asks for. A secret may go here: it never leaves the server. */
47
+ headers?: Readonly<Record<string, string>>;
48
+ /** Fraction of traces kept, 0 to 1 — a trace begun elsewhere keeps its decision. Default 1. */
49
+ sampling?: number;
50
+ /** More resource attributes (`tenant.group`, …). */
51
+ attributes?: Attributes;
52
+ };
53
+ /** The process's tracing, once registered. */
54
+ export type ServerTracing = {
55
+ /** Sends what is buffered now: a script that ends, a test. */
56
+ flush: () => Promise<void>;
57
+ /** Sends what is buffered and stops: a server shutting down. */
58
+ shutdown: () => Promise<void>;
59
+ };
60
+ /**
61
+ * OpenTelemetry's provider for this server process: OTLP/HTTP to the application's endpoint,
62
+ * resource and sampling as `browserTracer`'s (`tracerResource`), registered GLOBALLY — so the
63
+ * SSR framework's own spans (each request, each render) go there, and every realm's use cases
64
+ * (`configureServerProcess`). Once per process: a second call, from any realm, answers the
65
+ * first's. It answers `undefined` when tracing stays off — no endpoint, the SDK did not load, or
66
+ * another provider was registered first (then use cases trace on THAT one).
67
+ */
68
+ export declare function registerServerTracing(options: ServerTracingOptions): Promise<ServerTracing | undefined>;
69
+ /**
70
+ * A `Tracer` over the process's OpenTelemetry provider — the loose piece `configureServerProcess`
71
+ * plugs, for an application that calls `configureProcess` itself:
72
+ *
73
+ * configureProcess({ identity: { release }, tracer: serverTracer({ release }), logger });
74
+ *
75
+ * Context: the provider is the process's, never this tracer's: the one `registerServerTracing`
76
+ * registered, or the application's own SDK. Read synchronously once some realm of the process
77
+ * loaded OpenTelemetry's API — `registerServerTracing` does, before the first page —; until then
78
+ * (a realm that registers nothing, the first moment), use cases run untraced. With no provider
79
+ * registered OpenTelemetry records nothing, so no `traceparent` claims a trace that does not
80
+ * exist.
81
+ */
82
+ export declare function serverTracer(options?: {
83
+ release?: string;
84
+ service?: string;
85
+ }): Tracer;
86
+ /**
87
+ * The process configured for the use cases a server runs, once per realm: client-framework's
88
+ * `configureProcess` with these options — `identity`, `reporter`, `logger`, `context`… — and,
89
+ * unless one is given, a tracer on the process's OpenTelemetry provider (`serverTracer`). Every
90
+ * module that reads on the server may call it at its top: the first call in a realm configures,
91
+ * the rest do nothing. In a browser it does nothing — the browser's process is its `main`'s
92
+ * (`browserTracer`) —, so a module the server and the browser both load may call it too. It
93
+ * answers whether this call configured the process.
94
+ *
95
+ * // domains/common/infrastructure/server.ts — imported where the server reads
96
+ * configureServerProcess({ identity: { release: "my-web:1.4.0" } });
97
+ *
98
+ * Context: `configureProcess` replaces everything it is given — the context store included —,
99
+ * so a second call per realm would start the process over between two requests. A test that
100
+ * needs its own tracer calls `configureProcess` directly.
101
+ */
102
+ export declare function configureServerProcess(options?: ProcessOptions): boolean;
@@ -0,0 +1,127 @@
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
+ shared.registered ??= started({ ...options, endpoint });
23
+ return shared.registered;
24
+ }
25
+ async function started(options) {
26
+ try {
27
+ const [{ trace }, { TracerProvider, BatchSpanProcessor, TraceIdRatioBasedSampler, ParentBasedSampler }, { OTLPTraceExporter }, { resourceFromAttributes }, { openTelemetryTracer },] = await Promise.all([
28
+ import("@opentelemetry/api"),
29
+ import("@opentelemetry/sdk-trace"),
30
+ import("@opentelemetry/exporter-trace-otlp-http"),
31
+ import("@opentelemetry/resources"),
32
+ import("@sincpro/client-framework/opentelemetry"),
33
+ ]);
34
+ const exporter = new OTLPTraceExporter({
35
+ url: options.endpoint,
36
+ ...(options.headers ? { headers: { ...options.headers } } : {}),
37
+ });
38
+ const provider = new TracerProvider({
39
+ resource: resourceFromAttributes(tracerResource(options)),
40
+ sampler: new ParentBasedSampler({
41
+ root: new TraceIdRatioBasedSampler(options.sampling ?? 1),
42
+ }),
43
+ spanProcessors: [new BatchSpanProcessor({ exporter })],
44
+ });
45
+ held().tracerOf ??= (name) => openTelemetryTracer(trace.getTracer(name));
46
+ if (!trace.setGlobalTracerProvider(provider)) {
47
+ await provider.shutdown();
48
+ console.warn(`${WHO}: another provider was registered first — use cases trace on it`);
49
+ return undefined;
50
+ }
51
+ return { flush: () => provider.forceFlush(), shutdown: () => provider.shutdown() };
52
+ }
53
+ catch (error) {
54
+ console.warn(`${WHO}: tracing is off — OpenTelemetry's SDK did not load`, error);
55
+ return undefined;
56
+ }
57
+ }
58
+ let loading;
59
+ /** OpenTelemetry's API, for a realm that did not register the provider itself. */
60
+ function loadApi() {
61
+ loading ??= (async () => {
62
+ try {
63
+ const [{ trace }, { openTelemetryTracer }] = await Promise.all([
64
+ import("@opentelemetry/api"),
65
+ import("@sincpro/client-framework/opentelemetry"),
66
+ ]);
67
+ held().tracerOf ??= (name) => openTelemetryTracer(trace.getTracer(name));
68
+ }
69
+ catch (error) {
70
+ console.warn(`${WHO}: tracing is off — @opentelemetry/api did not load`, error);
71
+ }
72
+ })();
73
+ return loading;
74
+ }
75
+ /**
76
+ * A `Tracer` over the process's OpenTelemetry provider — the loose piece `configureServerProcess`
77
+ * plugs, for an application that calls `configureProcess` itself:
78
+ *
79
+ * configureProcess({ identity: { release }, tracer: serverTracer({ release }), logger });
80
+ *
81
+ * Context: the provider is the process's, never this tracer's: the one `registerServerTracing`
82
+ * registered, or the application's own SDK. Read synchronously once some realm of the process
83
+ * loaded OpenTelemetry's API — `registerServerTracing` does, before the first page —; until then
84
+ * (a realm that registers nothing, the first moment), use cases run untraced. With no provider
85
+ * registered OpenTelemetry records nothing, so no `traceparent` claims a trace that does not
86
+ * exist.
87
+ */
88
+ export function serverTracer(options = {}) {
89
+ const name = options.service ??
90
+ (options.release ? identityOf(options.release).serviceName : undefined) ??
91
+ "unknown_service";
92
+ let ready;
93
+ const now = () => (ready ??= held().tracerOf?.(name));
94
+ if (now() === undefined)
95
+ void loadApi();
96
+ return {
97
+ start: (span, startOptions) => (now() ?? NO_TRACER).start(span, startOptions),
98
+ };
99
+ }
100
+ let configured = false;
101
+ /**
102
+ * The process configured for the use cases a server runs, once per realm: client-framework's
103
+ * `configureProcess` with these options — `identity`, `reporter`, `logger`, `context`… — and,
104
+ * unless one is given, a tracer on the process's OpenTelemetry provider (`serverTracer`). Every
105
+ * module that reads on the server may call it at its top: the first call in a realm configures,
106
+ * the rest do nothing. In a browser it does nothing — the browser's process is its `main`'s
107
+ * (`browserTracer`) —, so a module the server and the browser both load may call it too. It
108
+ * answers whether this call configured the process.
109
+ *
110
+ * // domains/common/infrastructure/server.ts — imported where the server reads
111
+ * configureServerProcess({ identity: { release: "my-web:1.4.0" } });
112
+ *
113
+ * Context: `configureProcess` replaces everything it is given — the context store included —,
114
+ * so a second call per realm would start the process over between two requests. A test that
115
+ * needs its own tracer calls `configureProcess` directly.
116
+ */
117
+ export function configureServerProcess(options = {}) {
118
+ if (configured || typeof window !== "undefined")
119
+ return false;
120
+ configured = true;
121
+ configureProcess({
122
+ ...options,
123
+ tracer: options.tracer ??
124
+ serverTracer(options.identity ? { release: options.identity.release } : {}),
125
+ });
126
+ return true;
127
+ }
@@ -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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-framework",
3
- "version": "3.8.0",
3
+ "version": "3.9.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"