simetra 0.2.0 → 0.3.0-next.2

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 (35) hide show
  1. package/dist/channel-grant-BATD6oQu.js +15 -0
  2. package/dist/compiler/index.d.ts +684 -77
  3. package/dist/compiler/index.js +24643 -13501
  4. package/dist/data/centrifugo/index.d.ts +24 -0
  5. package/dist/data/centrifugo/index.js +173 -0
  6. package/dist/data/index.d.ts +27 -0
  7. package/dist/data/index.js +9910 -0
  8. package/dist/data/react/index.d.ts +103 -0
  9. package/dist/data/react/index.js +214 -0
  10. package/dist/grant-Zg0hmqK7.d.ts +11 -0
  11. package/dist/handle-C6PFsnUX.js +44 -0
  12. package/dist/holder-CkR-qRYU.d.ts +585 -0
  13. package/dist/model/index.d.ts +4118 -476
  14. package/dist/model/index.js +4267 -380
  15. package/dist/schema/index.d.ts +1545 -572
  16. package/dist/schema/index.js +8554 -4215
  17. package/dist/server/index.d.ts +665 -21
  18. package/dist/server/index.js +4279 -426
  19. package/dist/server/signals/index.d.ts +92 -0
  20. package/dist/server/signals/index.js +140 -0
  21. package/dist/shell/index.d.ts +100 -0
  22. package/dist/shell/index.js +148 -0
  23. package/dist/ui/index.d.ts +213 -0
  24. package/dist/ui/index.js +1075 -0
  25. package/package.json +75 -3
  26. package/schemas/accumulation-registers.schema.json +46 -5
  27. package/schemas/catalogs.schema.json +110 -7
  28. package/schemas/constants.schema.json +31 -5
  29. package/schemas/custom-tables.schema.json +24 -0
  30. package/schemas/documents.schema.json +83 -5
  31. package/schemas/functions.schema.json +129 -0
  32. package/schemas/information-registers.schema.json +47 -5
  33. package/schemas/project.schema.json +11 -1
  34. package/schemas/rights-sets.schema.json +3 -1
  35. package/schemas/roles.schema.json +6 -2
@@ -0,0 +1,92 @@
1
+ import { t as ChannelGrant } from "../../grant-Zg0hmqK7.js";
2
+ /** The host path that serves `SignalTokens.jwks()` (postgres profile spec §6.3). */
3
+ export declare const SIGNALS_JWKS_PATH = "/simetra/signals/jwks";
4
+ /** A private Ed25519 key in JWK form (`kty: "OKP"`, `crv: "Ed25519"`, `x`, `d`). */
5
+ interface PrivateJwk {
6
+ kty?: string;
7
+ crv?: string;
8
+ x?: string;
9
+ d?: string;
10
+ [member: string]: unknown;
11
+ }
12
+ /**
13
+ * One signing key of the host. A new key is added to the JWKS first and signs
14
+ * no earlier than 65 minutes after `addedAt`; `retiredAt` is when it stopped
15
+ * signing, and it stays in the JWKS for 20 minutes more (postgres profile spec
16
+ * §6.3).
17
+ */
18
+ interface SigningKey {
19
+ kid: string;
20
+ privateJwk: PrivateJwk;
21
+ addedAt: Date;
22
+ retiredAt?: Date;
23
+ }
24
+ /** A public key of the JWKS: exactly these members, never a private one. */
25
+ interface SignalPublicJwk {
26
+ kty: "OKP";
27
+ crv: "Ed25519";
28
+ x: string;
29
+ kid: string;
30
+ alg: "EdDSA";
31
+ use: "sig";
32
+ }
33
+ /** A signed JWT and the moment it stops being valid. */
34
+ interface SignalToken {
35
+ token: string;
36
+ expiresAt: Date;
37
+ }
38
+ /** A subscription token bound to one channel. */
39
+ interface SignalChannelToken extends SignalToken {
40
+ channel: string;
41
+ }
42
+ /**
43
+ * Signs Centrifugo tokens (P4-B spec §8.3). It reads no database: what it
44
+ * signs comes only from a `ChannelGrant` of `runtime.authorizeChannels`.
45
+ */
46
+ interface SignalTokens {
47
+ /** The connection token of the grant's subject; a grant without a user has none. */
48
+ connectionToken(grant: ChannelGrant): Promise<SignalToken>;
49
+ /** One token per channel of the grant, exactly those channels. */
50
+ channelTokens(grant: ChannelGrant): Promise<SignalChannelToken[]>;
51
+ /** The keys Centrifugo verifies with: active ones and ones retired under 20 minutes ago; never throws. */
52
+ jwks(): {
53
+ keys: SignalPublicJwk[];
54
+ };
55
+ }
56
+ interface CentrifugoTokensOptions {
57
+ /** The host's signing keys; at least one must be active and, after a retirement, mature. */
58
+ keys: readonly SigningKey[];
59
+ /** `centrifugo:<project.name>`. */
60
+ audience: string;
61
+ /** The host origin. */
62
+ issuer: string;
63
+ /** The clock; defaults to the system time, replaced in tests. */
64
+ now?: () => Date;
65
+ }
66
+ /**
67
+ * Why signing failed; a host maps the code to its response.
68
+ * - `signals.invalid-key`, `signals.duplicate-kid`: a configuration error, fail at start-up.
69
+ * - `signals.no-signing-key`, `signals.no-mature-key`: no key may sign now, answer 503 and alert.
70
+ * - `signals.forged-grant`: the grant did not come from `authorizeChannels`, a host bug, answer 500.
71
+ * - `signals.no-user`: the grant has no valid user, answer 401.
72
+ */
73
+ type SignalTokenErrorCode = "signals.invalid-key" | "signals.duplicate-kid" | "signals.no-signing-key" | "signals.no-mature-key" | "signals.forged-grant" | "signals.no-user";
74
+ export declare class SignalTokenError extends Error {
75
+ readonly code: SignalTokenErrorCode;
76
+ constructor(code: SignalTokenErrorCode, message: string);
77
+ }
78
+ /**
79
+ * Whether no key of the set may sign at `at`, by the same rule the port signs
80
+ * with: `signals.no-signing-key` (every key is retired) or
81
+ * `signals.no-mature-key` (a key was retired and no active key is mature yet);
82
+ * `undefined` when a key can sign. A host calls it at start-up to warn about a
83
+ * rotation phase that makes every token request fail with 503.
84
+ */
85
+ export declare function signingKeyProblem(keys: readonly SigningKey[], at?: Date): "signals.no-signing-key" | "signals.no-mature-key" | undefined;
86
+ /**
87
+ * The port over Centrifugo: Ed25519 JWTs (`alg: "EdDSA"`, a `kid` in every
88
+ * header), a 15-minute connection token and 5-minute channel tokens. Throws
89
+ * `SignalTokenError` on a non-Ed25519 key or a repeated `kid`.
90
+ */
91
+ export declare function createCentrifugoTokens(options: CentrifugoTokensOptions): Promise<SignalTokens>;
92
+ export type { CentrifugoTokensOptions, ChannelGrant, PrivateJwk, SignalChannelToken, SignalPublicJwk, SignalToken, SignalTokenErrorCode, SignalTokens, SigningKey };
@@ -0,0 +1,140 @@
1
+ import { n as isChannelGrant } from "../../channel-grant-BATD6oQu.js";
2
+ // src/server/signals/tokens.ts
3
+ /** The host path that serves `SignalTokens.jwks()` (postgres profile spec §6.3). */
4
+ const SIGNALS_JWKS_PATH = "/simetra/signals/jwks";
5
+ var SignalTokenError = class extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.name = "SignalTokenError";
10
+ this.code = code;
11
+ }
12
+ };
13
+ const MINUTE = 6e4;
14
+ const MATURE_AFTER = 65 * MINUTE;
15
+ const JWKS_GRACE = 20 * MINUTE;
16
+ const CONNECTION_TTL = 15 * MINUTE;
17
+ const CHANNEL_TTL = 5 * MINUTE;
18
+ const ED25519 = { name: "Ed25519" };
19
+ const encoder = new TextEncoder();
20
+ function base64url(bytes) {
21
+ let binary = "";
22
+ for (const byte of bytes) binary += String.fromCharCode(byte);
23
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ const encodeJson = (value) => base64url(encoder.encode(JSON.stringify(value)));
26
+ async function load(key) {
27
+ const jwk = key.privateJwk;
28
+ const invalid = (why) => new SignalTokenError("signals.invalid-key", `Signing key "${key.kid}": ${why}.`);
29
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") throw invalid("only Ed25519 keys (kty \"OKP\", crv \"Ed25519\") are accepted");
30
+ if (typeof jwk.x !== "string" || typeof jwk.d !== "string") throw invalid("a private JWK with both x and d is required");
31
+ const publicJwk = {
32
+ kty: "OKP",
33
+ crv: "Ed25519",
34
+ x: jwk.x,
35
+ kid: key.kid,
36
+ alg: "EdDSA",
37
+ use: "sig"
38
+ };
39
+ let privateKey;
40
+ try {
41
+ privateKey = await crypto.subtle.importKey("jwk", {
42
+ kty: "OKP",
43
+ crv: "Ed25519",
44
+ x: jwk.x,
45
+ d: jwk.d
46
+ }, ED25519, false, ["sign"]);
47
+ } catch {
48
+ throw invalid("the JWK is not an Ed25519 key pair (x must match d)");
49
+ }
50
+ return {
51
+ key,
52
+ privateKey,
53
+ publicJwk
54
+ };
55
+ }
56
+ const retiredBy = (key, now) => key.retiredAt !== void 0 && key.retiredAt.getTime() <= now;
57
+ function chooseSigningKey(keys, at) {
58
+ const active = keys.filter((k) => !retiredBy(k, at));
59
+ if (active.length === 0) return { problem: "signals.no-signing-key" };
60
+ const byAdded = [...active].sort((a, b) => a.addedAt.getTime() - b.addedAt.getTime());
61
+ const newest = byAdded.filter((k) => k.addedAt.getTime() <= at - MATURE_AFTER).at(-1);
62
+ if (newest !== void 0) return { key: newest };
63
+ if (keys.every((k) => k.retiredAt === void 0)) return { key: byAdded[0] };
64
+ return { problem: "signals.no-mature-key" };
65
+ }
66
+ /**
67
+ * Whether no key of the set may sign at `at`, by the same rule the port signs
68
+ * with: `signals.no-signing-key` (every key is retired) or
69
+ * `signals.no-mature-key` (a key was retired and no active key is mature yet);
70
+ * `undefined` when a key can sign. A host calls it at start-up to warn about a
71
+ * rotation phase that makes every token request fail with 503.
72
+ */
73
+ function signingKeyProblem(keys, at = /* @__PURE__ */ new Date()) {
74
+ return chooseSigningKey(keys, at.getTime()).problem;
75
+ }
76
+ /**
77
+ * The port over Centrifugo: Ed25519 JWTs (`alg: "EdDSA"`, a `kid` in every
78
+ * header), a 15-minute connection token and 5-minute channel tokens. Throws
79
+ * `SignalTokenError` on a non-Ed25519 key or a repeated `kid`.
80
+ */
81
+ async function createCentrifugoTokens(options) {
82
+ const { audience, issuer } = options;
83
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
84
+ const seen = /* @__PURE__ */ new Set();
85
+ for (const key of options.keys) {
86
+ if (seen.has(key.kid)) throw new SignalTokenError("signals.duplicate-kid", `Signing key id "${key.kid}" is repeated; every key needs its own kid.`);
87
+ seen.add(key.kid);
88
+ }
89
+ const keys = await Promise.all(options.keys.map(load));
90
+ const byKid = new Map(keys.map((k) => [k.key.kid, k]));
91
+ function signer(at) {
92
+ const choice = chooseSigningKey(options.keys, at);
93
+ if (choice.key !== void 0) return byKid.get(choice.key.kid);
94
+ if (choice.problem === "signals.no-signing-key") throw new SignalTokenError("signals.no-signing-key", "No signing key is active: every key is retired.");
95
+ throw new SignalTokenError("signals.no-mature-key", "A key is retired but no active key was added at least 65 minutes ago; Centrifugo may not know the successor yet.");
96
+ }
97
+ async function sign(claims, ttl) {
98
+ const at = now().getTime();
99
+ const { key, privateKey } = signer(at);
100
+ const expiresAt = new Date(at + ttl);
101
+ const head = `${encodeJson({
102
+ alg: "EdDSA",
103
+ typ: "JWT",
104
+ kid: key.kid
105
+ })}.${encodeJson({
106
+ ...claims,
107
+ aud: audience,
108
+ iss: issuer,
109
+ exp: Math.floor(expiresAt.getTime() / 1e3)
110
+ })}`;
111
+ const signature = await crypto.subtle.sign(ED25519, privateKey, encoder.encode(head));
112
+ return {
113
+ token: `${head}.${base64url(new Uint8Array(signature))}`,
114
+ expiresAt
115
+ };
116
+ }
117
+ function subjectOf(grant) {
118
+ if (!isChannelGrant(grant)) throw new SignalTokenError("signals.forged-grant", "Tokens are signed only for a grant of runtime.authorizeChannels.");
119
+ if (grant.subject === null) throw new SignalTokenError("signals.no-user", "The grant has no valid user; signals need a signed-in user.");
120
+ return grant.subject;
121
+ }
122
+ return {
123
+ connectionToken: async (grant) => sign({ sub: subjectOf(grant) }, CONNECTION_TTL),
124
+ channelTokens: async (grant) => {
125
+ const sub = subjectOf(grant);
126
+ return Promise.all(grant.channels.map(async (channel) => ({
127
+ channel,
128
+ ...await sign({
129
+ sub,
130
+ channel
131
+ }, CHANNEL_TTL)
132
+ })));
133
+ },
134
+ jwks: () => {
135
+ const at = now().getTime();
136
+ return { keys: keys.filter(({ key }) => key.retiredAt === void 0 || key.retiredAt.getTime() > at - JWKS_GRACE).map(({ publicJwk }) => ({ ...publicJwk })) };
137
+ }
138
+ };
139
+ }
140
+ export { SIGNALS_JWKS_PATH, SignalTokenError, createCentrifugoTokens, signingKeyProblem };
@@ -0,0 +1,100 @@
1
+ import { CatalogEntry, ClientCatalog, MetadataRef, OrderBy } from "simetra/model";
2
+ import { ReactElement, ReactNode } from "react";
3
+ import { DataRuntime, DataRuntimeOptions, RuntimeHolder } from "simetra/data";
4
+ import { NavigationAdapter } from "simetra/ui";
5
+ import { AnyRouter } from "@tanstack/react-router";
6
+ /** An object of the catalog as routes take it (P4-D spec §6). */
7
+ interface EntityDescriptor {
8
+ /** Logical object name `"<kind>.<name>"`. */
9
+ readonly ref: string;
10
+ /** The object UUID. */
11
+ readonly id: string;
12
+ }
13
+ interface SimetraApp {
14
+ /**
15
+ * The descriptor of an object; a `TypeError` for an object outside the
16
+ * catalog, so a wrong route fails when the module is imported.
17
+ */
18
+ object(ref: MetadataRef): EntityDescriptor;
19
+ /** Creates the data runtime of a session over this app's catalog. */
20
+ createRuntime(options: Omit<DataRuntimeOptions, "catalog">): DataRuntime;
21
+ /** Provides the same catalog to the T5 hosts; the only place that mounts `CatalogProvider`. */
22
+ Provider(props: {
23
+ children?: ReactNode;
24
+ }): ReactElement;
25
+ }
26
+ /**
27
+ * The app over one client catalog (`client-catalog.json`): the runtime and the
28
+ * T5 hosts read the same object, so they cannot disagree (P4-D spec §5).
29
+ */
30
+ export declare function simetraApp(catalog: ClientCatalog): SimetraApp;
31
+ /**
32
+ * The router context the simetra routes read (P4-D spec §6). The router
33
+ * factory of the app puts the holder of the request's runtime here; `null`
34
+ * means there is no runtime (an anonymous request), so a loader loads nothing.
35
+ */
36
+ interface SimetraRouterContext {
37
+ data: RuntimeHolder | null;
38
+ }
39
+ declare module "@tanstack/react-router" {
40
+ interface StaticDataRouteOption {
41
+ /** Set on the list route of an object: its UUID. */
42
+ simetraList?: string;
43
+ /**
44
+ * Set on the card route of an object: its UUID. `entityCardRoute` also
45
+ * sets {@link simetraObject}.
46
+ */
47
+ simetraCard?: string;
48
+ /** The logical name of the object of a simetra route. */
49
+ simetraObject?: string;
50
+ }
51
+ }
52
+ interface EntityListRouteOptions {
53
+ orderBy?: OrderBy;
54
+ include?: readonly string[];
55
+ }
56
+ /**
57
+ * The route options of the standard list of an object: a loader that
58
+ * preloads the list view, the `ListHost` component, `ssr: true` and the
59
+ * `staticData` the navigation adapter looks up (P4-D spec §6). Use it as
60
+ * `createFileRoute("/clients/")(entityListRoute(Client))`.
61
+ */
62
+ export declare function entityListRoute(entity: EntityDescriptor, options?: EntityListRouteOptions): {
63
+ loader: ({ context }: {
64
+ context: SimetraRouterContext;
65
+ }) => Promise<void>;
66
+ component: () => ReactElement;
67
+ ssr: true;
68
+ staticData: {
69
+ simetraList: string;
70
+ simetraObject: string;
71
+ };
72
+ };
73
+ /**
74
+ * The route options of the standard card of an object: a loader that
75
+ * preloads the card view and its tabular sections for the `id` path
76
+ * parameter, the `CardHost` component, `ssr: true` and the `staticData` the
77
+ * navigation adapter looks up (P4-D spec §6). Use it as
78
+ * `createFileRoute("/clients/$id")(entityCardRoute(Client))`.
79
+ */
80
+ export declare function entityCardRoute(entity: EntityDescriptor): {
81
+ loader: ({ context, params }: {
82
+ context: SimetraRouterContext;
83
+ params: {
84
+ id: string;
85
+ };
86
+ }) => Promise<void>;
87
+ component: () => ReactElement;
88
+ ssr: true;
89
+ staticData: {
90
+ simetraCard: string;
91
+ simetraObject: string;
92
+ };
93
+ };
94
+ /**
95
+ * The navigation adapter of T5 over TanStack Router (P4-D spec §6). The card
96
+ * route is the one with `staticData.simetraCard` of the object, the list
97
+ * route the one with `simetraList`; the path comes from the app's route tree.
98
+ */
99
+ export declare function routerNavigation(router: AnyRouter): NavigationAdapter;
100
+ export type { EntityDescriptor, EntityListRouteOptions, SimetraApp, SimetraRouterContext };
@@ -0,0 +1,148 @@
1
+ import { catalogIndex } from "simetra/model";
2
+ import { createElement } from "react";
3
+ import { createDataRuntime } from "simetra/data";
4
+ import { CardHost, CatalogProvider, ListHost, cardQuery, listQuery } from "simetra/ui";
5
+ import { useBlocker, useParams } from "@tanstack/react-router";
6
+ // src/shell/app.ts
7
+ const entries = /* @__PURE__ */ new WeakMap();
8
+ /** The catalog entry behind a descriptor made by `simetraApp(...).object`. */
9
+ function entryOf(entity) {
10
+ const entry = entries.get(entity);
11
+ if (entry === void 0) throw new TypeError("not a descriptor made by simetraApp(catalog).object");
12
+ return entry;
13
+ }
14
+ /**
15
+ * The app over one client catalog (`client-catalog.json`): the runtime and the
16
+ * T5 hosts read the same object, so they cannot disagree (P4-D spec §5).
17
+ */
18
+ function simetraApp(catalog) {
19
+ const index = catalogIndex(catalog.objects);
20
+ return {
21
+ object(ref) {
22
+ const name = `${ref.kind}.${ref.name}`;
23
+ const entry = index.byRef.get(name);
24
+ if (entry === void 0) throw new TypeError(`simetraApp: unknown object ${name}`);
25
+ const entity = {
26
+ ref: name,
27
+ id: entry.id
28
+ };
29
+ entries.set(entity, entry);
30
+ return entity;
31
+ },
32
+ createRuntime: (options) => createDataRuntime({
33
+ ...options,
34
+ catalog
35
+ }),
36
+ Provider: (props) => createElement(CatalogProvider, { catalog }, props.children)
37
+ };
38
+ }
39
+ // src/shell/routes.ts
40
+ /**
41
+ * The route options of the standard list of an object: a loader that
42
+ * preloads the list view, the `ListHost` component, `ssr: true` and the
43
+ * `staticData` the navigation adapter looks up (P4-D spec §6). Use it as
44
+ * `createFileRoute("/clients/")(entityListRoute(Client))`.
45
+ */
46
+ function entityListRoute(entity, options = {}) {
47
+ const query = listQuery(entryOf(entity), options);
48
+ return {
49
+ loader: async ({ context }) => {
50
+ const runtime = context.data?.current();
51
+ if (runtime === void 0) return;
52
+ await runtime.preload({
53
+ kind: runtime.residencyOf(entity.ref),
54
+ object: entity.ref,
55
+ ...query
56
+ });
57
+ },
58
+ component: () => createElement(ListHost, {
59
+ object: entity.ref,
60
+ ...options
61
+ }),
62
+ ssr: true,
63
+ staticData: {
64
+ simetraList: entity.id,
65
+ simetraObject: entity.ref
66
+ }
67
+ };
68
+ }
69
+ /**
70
+ * The route options of the standard card of an object: a loader that
71
+ * preloads the card view and its tabular sections for the `id` path
72
+ * parameter, the `CardHost` component, `ssr: true` and the `staticData` the
73
+ * navigation adapter looks up (P4-D spec §6). Use it as
74
+ * `createFileRoute("/clients/$id")(entityCardRoute(Client))`.
75
+ */
76
+ function entityCardRoute(entity) {
77
+ const { tabularSections } = cardQuery(entryOf(entity));
78
+ const object = entity.ref;
79
+ return {
80
+ loader: async ({ context, params }) => {
81
+ const runtime = context.data?.current();
82
+ if (runtime === void 0) return;
83
+ const id = params.id;
84
+ await Promise.all([runtime.preload({
85
+ kind: "card",
86
+ object,
87
+ key: id
88
+ }), ...tabularSections.map((section) => runtime.preload({
89
+ kind: "section",
90
+ object,
91
+ owner: id,
92
+ section
93
+ }))]);
94
+ },
95
+ component: function EntityCard() {
96
+ const { id } = useParams({ strict: false });
97
+ return createElement(CardHost, {
98
+ object,
99
+ id
100
+ });
101
+ },
102
+ ssr: true,
103
+ staticData: {
104
+ simetraCard: entity.id,
105
+ simetraObject: object
106
+ }
107
+ };
108
+ }
109
+ // src/shell/navigation.ts
110
+ function go(router, options) {
111
+ router.navigate(options);
112
+ }
113
+ function findRoute(router, field, object) {
114
+ return Object.values(router.routesById).find((route) => {
115
+ const data = route.options.staticData;
116
+ return data?.[field] !== void 0 && data.simetraObject === object;
117
+ });
118
+ }
119
+ /**
120
+ * The navigation adapter of T5 over TanStack Router (P4-D spec §6). The card
121
+ * route is the one with `staticData.simetraCard` of the object, the list
122
+ * route the one with `simetraList`; the path comes from the app's route tree.
123
+ */
124
+ function routerNavigation(router) {
125
+ return {
126
+ openCard(object, key) {
127
+ const route = findRoute(router, "simetraCard", object);
128
+ if (route === void 0) throw new Error(`routerNavigation: no card route for ${object}`);
129
+ go(router, {
130
+ to: route.fullPath,
131
+ params: { id: key }
132
+ });
133
+ },
134
+ openList(object) {
135
+ const route = findRoute(router, "simetraList", object);
136
+ if (route === void 0) throw new Error(`routerNavigation: no list route for ${object}`);
137
+ go(router, { to: route.fullPath });
138
+ },
139
+ useBlockWhile(dirty) {
140
+ useBlocker({
141
+ shouldBlockFn: () => dirty,
142
+ enableBeforeUnload: dirty,
143
+ disabled: !dirty
144
+ });
145
+ }
146
+ };
147
+ }
148
+ export { entityCardRoute, entityListRoute, routerNavigation, simetraApp };