@celobus/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +91 -0
  2. package/README.md +38 -2
  3. package/dist/access.d.ts +141 -0
  4. package/dist/access.js +232 -0
  5. package/dist/codec.d.ts +29 -0
  6. package/dist/codec.js +361 -0
  7. package/dist/cron.d.ts +2 -0
  8. package/dist/cron.js +113 -0
  9. package/dist/ctx.d.ts +644 -0
  10. package/dist/ctx.js +657 -0
  11. package/dist/db.d.ts +234 -0
  12. package/dist/db.js +495 -0
  13. package/dist/decimal.d.ts +39 -0
  14. package/dist/decimal.js +158 -0
  15. package/dist/declare.d.ts +311 -0
  16. package/dist/declare.js +78 -0
  17. package/dist/descriptor.d.ts +229 -0
  18. package/dist/descriptor.js +899 -0
  19. package/dist/errors.d.ts +65 -0
  20. package/dist/errors.js +114 -0
  21. package/dist/index.d.ts +17 -0
  22. package/dist/index.js +34 -0
  23. package/dist/log.d.ts +39 -0
  24. package/dist/log.js +101 -0
  25. package/dist/names.d.ts +12 -0
  26. package/dist/names.js +41 -0
  27. package/dist/notify.d.ts +185 -0
  28. package/dist/notify.js +234 -0
  29. package/dist/platform.d.ts +61 -0
  30. package/dist/platform.js +47 -0
  31. package/dist/plugin.d.ts +43 -0
  32. package/dist/plugin.js +117 -0
  33. package/dist/query.d.ts +326 -0
  34. package/dist/query.js +794 -0
  35. package/dist/remote.d.ts +8 -0
  36. package/dist/remote.js +19 -0
  37. package/dist/schema.d.ts +487 -0
  38. package/dist/schema.js +405 -0
  39. package/dist/serve.d.ts +63 -0
  40. package/dist/serve.js +411 -0
  41. package/dist/sql.d.ts +13 -0
  42. package/dist/sql.js +33 -0
  43. package/dist/ui.d.ts +1867 -0
  44. package/dist/ui.js +3964 -0
  45. package/dist/viz-kinds.d.ts +12 -0
  46. package/dist/viz-kinds.js +14 -0
  47. package/package.json +33 -4
  48. package/proto/plugin.proto +994 -0
@@ -0,0 +1,899 @@
1
+ // The descriptor (schema 1): what `--describe` prints, the same JSON
2
+ // in every SDK. Every member of the schema is emitted, with its default when not declared (empty strings, false,
3
+ // empty arrays), so all SDKs give the same shape.
4
+ //
5
+ // Order rules (arrays keep this order; object keys are sorted by the CLI when it canonicalizes):
6
+ // - roles, scopes, capabilities, agents, entities, endpoints: as declared (the key order of `plugin({...})`);
7
+ // - messages: in order of first use while walking the endpoints as declared (each endpoint's input, then its
8
+ // output; a message's nested messages right after it, depth first, in field order), then the entities'
9
+ // messages in entity order, then the extra `messages`, then the jobs' payloads (in job order), then the topics'
10
+ // key messages;
11
+ // - dependencies and their reads: as declared;
12
+ // - enums: in order of first use while walking those messages' fields, then the extra `enums`;
13
+ // - fields: declaration order; an entity's message has `id` first, then its columns. `number` is the 1-based
14
+ // position.
15
+ import { messageFields } from "./codec.js";
16
+ import { runChangeOf } from "./ctx.js";
17
+ import { describeAccess } from "./access.js";
18
+ import { cronError } from "./cron.js";
19
+ import { EndpointDef, JobDef, RoleDef, describedEndpoints, durationMs } from "./declare.js";
20
+ import { NotificationKind } from "./notify.js";
21
+ import { jsonName, humanize, pascal, snake } from "./names.js";
22
+ import { EntityDef, EnumDef, Field, MessageDef, PlatformEntity, entityNames as describedNames, foreignPlugin, navigations } from "./schema.js";
23
+ import { TopicDecl, TopicDef, UiDoc, invalidationJson, resolveUi, topicDecl } from "./ui.js";
24
+ /** `on_delete` of a ref within the plugin, and of one to another plugin or the directory. */
25
+ const ON_DELETE_OWN = ["restrict", "cascade", "set_null", "no_action"];
26
+ const ON_DELETE_CROSS = ["keep", "set_null"];
27
+ /** The languages of a `searchable` column: PostgreSQL's text search configurations. */
28
+ const SEARCH_LANGUAGES = [
29
+ "simple", "arabic", "armenian", "basque", "catalan", "danish", "dutch", "english", "estonian", "finnish", "french",
30
+ "german", "greek", "hindi", "hungarian", "indonesian", "irish", "italian", "lithuanian", "nepali", "norwegian",
31
+ "portuguese", "romanian", "russian", "serbian", "spanish", "swedish", "tamil", "turkish", "yiddish",
32
+ ];
33
+ const MAX_SEARCHABLE = 8;
34
+ const NAV_NAME = /^[a-z][a-z0-9_]{0,62}$/;
35
+ export function formatError(e) {
36
+ return `error[${e.code}] at ${e.path}: ${e.message}` + (e.help ? `\n help: ${e.help}` : "");
37
+ }
38
+ /** Thrown by `plugin.describe()` when the definition has errors. */
39
+ export class DescribeErrors extends Error {
40
+ errors;
41
+ constructor(errors) {
42
+ super(errors.map(formatError).join("\n"));
43
+ this.errors = errors;
44
+ this.name = "DescribeErrors";
45
+ }
46
+ }
47
+ /** The reserved method of the run-change hook: `/<id>.v1.<Service>/_RunChange`. */
48
+ export const RUN_CHANGE_METHOD = "_RunChange";
49
+ /** How long the run-change hook may take (ms). */
50
+ const RUN_CHANGE_TIMEOUT_MS = 30_000;
51
+ const NO_FIELDS = new MessageDef("RunChangeAnswer", {});
52
+ /** The runs a process starts at once by default, and the most it may announce. */
53
+ export const DEFAULT_JOB_SLOTS = 16;
54
+ export const MAX_JOB_SLOTS = 64;
55
+ const JOB_NAME = /^[a-z][a-z0-9_]{0,31}$/;
56
+ const JOB_MAX_RETRIES = 20;
57
+ const JOB_MAX_DELAY_MS = 3_600_000;
58
+ export const RESERVED_IDS = [
59
+ "platform", "celobus", "core", "system", "sys", "workspace", "admin", "api", "app", "auth", "ui", "sdk", "cell",
60
+ "public", "internal", "mcp",
61
+ ];
62
+ export const CAPABILITIES = [
63
+ "authz:bypass", "identity:manage", "push:send", "sql:write", "sql:unsafe", "blobs:use", "mcp:tools",
64
+ ];
65
+ const WORKSPACE_ROLES = ["workspace.owner", "workspace.admin", "workspace.member", "workspace.guest"];
66
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
67
+ const TYPE_NAME = /^[A-Z][A-Za-z0-9]*$/;
68
+ const RESERVED_COLUMNS = ["id", "created_at", "updated_at", "deleted_at", "version"];
69
+ const MAX_ERRORS = 100;
70
+ /** Milliseconds of a timeout option, or `undefined` when it cannot be read. */
71
+ export function timeoutMs(timeout) {
72
+ if (timeout === undefined)
73
+ return 30_000;
74
+ if (typeof timeout === "number")
75
+ return Number.isFinite(timeout) ? timeout : undefined;
76
+ const m = typeof timeout === "string" ? /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(timeout) : null;
77
+ if (!m)
78
+ return undefined;
79
+ return Number(m[1]) * (m[2] === "ms" ? 1 : m[2] === "s" ? 1000 : 60_000);
80
+ }
81
+ /** Whole seconds of an agent's timeout (`'90s'`, `'15m'`, `'2h'`), or `undefined` when it cannot be read. */
82
+ export function agentTimeoutSeconds(timeout) {
83
+ const m = typeof timeout === "string" ? /^(\d+)(s|m|h)$/.exec(timeout) : null;
84
+ if (!m)
85
+ return undefined;
86
+ return Number(m[1]) * (m[2] === "s" ? 1 : m[2] === "m" ? 60 : 3600);
87
+ }
88
+ function isShape(v) {
89
+ return (typeof v === "object" &&
90
+ v !== null &&
91
+ !(v instanceof Field) &&
92
+ !(v instanceof EntityDef) &&
93
+ Object.values(v).every((f) => f instanceof Field));
94
+ }
95
+ /** Builds the descriptor and the serving model; definition errors are collected, not thrown. */
96
+ export function resolve(options, version) {
97
+ const errors = [];
98
+ const err = (code, path, message, help) => {
99
+ if (errors.length < MAX_ERRORS)
100
+ errors.push(help ? { code, path, message, help } : { code, path, message });
101
+ };
102
+ const id = options.id;
103
+ // --- plugin -------------------------------------------------------------------------------------
104
+ if (typeof id !== "string" || !/^[a-z][a-z0-9]{1,15}$/.test(id)) {
105
+ err("E_PLUGIN_ID", "id", `${JSON.stringify(id)} is not a plugin id`, "2–16 characters: a lowercase letter, then lowercase letters and digits");
106
+ }
107
+ else if (RESERVED_IDS.includes(id) || id.startsWith("pg")) {
108
+ err("E_PLUGIN_ID_RESERVED", "id", `\`${id}\` is reserved`, `reserved ids: ${RESERVED_IDS.join(", ")}, pg*`);
109
+ }
110
+ if (!version || !SEMVER.test(version)) {
111
+ err("E_PLUGIN_VERSION", "version", version ? `${JSON.stringify(version)} is not semver` : "no version", "set `version` in plugin({...}) or in the plugin's package.json");
112
+ }
113
+ // --- roles --------------------------------------------------------------------------------------
114
+ const roleNames = new Map();
115
+ const roles = [];
116
+ for (const [key, r] of Object.entries(options.roles ?? {})) {
117
+ const path = `roles.${key}`;
118
+ if (!(r instanceof RoleDef)) {
119
+ err("E_SCHEMA", path, "not a role (use role({...}))");
120
+ continue;
121
+ }
122
+ const name = snake(key);
123
+ if (!/^[a-z][a-z0-9_]{1,31}$/.test(name))
124
+ err("E_ROLE_NAME", path, `\`${name}\` is not a role name`, "2–32 characters: a-z, 0-9, _");
125
+ if (roles.some((x) => x.name === name) || roleNames.has(r))
126
+ err("E_ROLE_DUP", path, `role \`${name}\` is declared twice`);
127
+ const defaultFor = r.options.defaultFor ?? "none";
128
+ if (!["none", "member", "admin"].includes(defaultFor))
129
+ err("E_SCHEMA", `${path}.defaultFor`, `\`${defaultFor}\` is not none, member or admin`);
130
+ roleNames.set(r, name);
131
+ roles.push({
132
+ name,
133
+ title: r.options.title ?? "",
134
+ description: r.options.description ?? "",
135
+ strict: r.options.strict ?? false,
136
+ default_for: defaultFor,
137
+ });
138
+ }
139
+ const roleName = (r) => (r instanceof RoleDef ? roleNames.get(r) : typeof r === "string" ? r : undefined);
140
+ const roleRefs = (list, path) => (list ?? []).flatMap((r, i) => {
141
+ const name = r instanceof RoleDef ? roleNames.get(r) : typeof r === "string" ? r : undefined;
142
+ const known = name !== undefined && (WORKSPACE_ROLES.includes(name) || roles.some((x) => x.name === name));
143
+ if (!known) {
144
+ err("E_ENDPOINT_ROLE_UNKNOWN", `${path}[${i}]`, name ? `role \`${name}\` is not declared` : "the role is not in plugin({ roles })", "declare it in plugin({ roles }) or use workspace.owner|admin|member|guest");
145
+ return [];
146
+ }
147
+ return [name];
148
+ });
149
+ // --- scopes, capabilities, permissions, agents, dependencies ------------------------------------
150
+ const scopes = [];
151
+ for (const [key, s] of Object.entries(options.scopes ?? {})) {
152
+ const name = snake(key);
153
+ const path = `scopes.${key}`;
154
+ if (!/^[a-z][a-z0-9_]{0,31}$/.test(name))
155
+ err("E_SCOPE_NAME", path, `\`${name}\` is not a scope name`);
156
+ if (scopes.some((x) => x.name === name))
157
+ err("E_SCOPE_DUP", path, `scope \`${name}\` is declared twice`);
158
+ scopes.push({ name, title: s?.title ?? "", description: s?.description ?? "", sensitive: s?.sensitive ?? false });
159
+ }
160
+ const scopeNames = new Set(["read", "write", ...scopes.map((s) => s.name)]);
161
+ const capabilities = [];
162
+ for (const [name, c] of Object.entries(options.capabilities ?? {})) {
163
+ const path = `capabilities.${JSON.stringify(name)}`;
164
+ const reason = typeof c === "string" ? c : c?.reason ?? "";
165
+ if (!CAPABILITIES.includes(name))
166
+ err("E_CAPABILITY_UNKNOWN", path, `\`${name}\` is not a capability`, `capabilities: ${CAPABILITIES.join(", ")}`);
167
+ if (!reason.trim())
168
+ err("E_CAPABILITY_REASON", path, "a capability needs a reason");
169
+ capabilities.push({ name, reason });
170
+ }
171
+ const permissions = [...(options.permissions ?? [])];
172
+ const agents = Object.entries(options.agents ?? {}).map(([key, a]) => {
173
+ const seconds = a?.timeout === undefined ? undefined : agentTimeoutSeconds(a.timeout);
174
+ if (a?.timeout !== undefined && seconds === undefined)
175
+ err("E_AGENT_TIMEOUT_RANGE", `agents.${key}.timeout`, `${JSON.stringify(a.timeout)} is not a time`, "whole seconds as '90s', '15m' or '2h'");
176
+ return {
177
+ name: snake(key),
178
+ roles: roleRefs(a?.roles, `agents.${key}.roles`),
179
+ // each left out when not declared, so a plugin without them describes itself as before
180
+ ...(a?.workspace?.length ? { workspace: [...a.workspace] } : {}),
181
+ // an agent of this plugin is named as its key is (`orderHelper` is `order_helper`); `<dependency>.<agent>` as given
182
+ ...(a?.delegates?.length ? { delegates: a.delegates.map((d) => (typeof d === "string" && !d.includes(".") ? snake(d) : d)) } : {}),
183
+ // a connection of this plugin is named as its key is; `<dependency>.<name>` as given
184
+ ...(a?.connection ? { connection: a.connection.includes(".") ? a.connection : snake(a.connection) } : {}),
185
+ ...(a?.sshKey ? { ssh_key: true } : {}),
186
+ ...(a?.admin ? { admin: true } : {}),
187
+ ...(a?.title ? { title: a.title } : {}),
188
+ ...(a?.description ? { description: a.description } : {}),
189
+ ...(a?.icon ? { icon: a.icon } : {}),
190
+ ...(a?.engine ? { engine: a.engine } : {}),
191
+ ...(a?.model ? { model: a.model } : {}),
192
+ ...(a?.session ? { session: true } : {}),
193
+ ...(seconds !== undefined ? { timeout_s: seconds } : {}),
194
+ ...(a?.skills?.length ? { skills: [...a.skills] } : {}),
195
+ ...(a?.topic instanceof TopicDef || a?.topic instanceof TopicDecl ? { topic: topicDecl(a.topic).topic.name } : {}),
196
+ };
197
+ });
198
+ const connections = Object.entries(options.connections ?? {}).map(([key, c]) => ({
199
+ name: snake(key),
200
+ kind: c?.kind ?? "",
201
+ ...(c?.title ? { title: c.title } : {}),
202
+ ...(c?.description ? { description: c.description } : {}),
203
+ }));
204
+ const dependencies = [];
205
+ (options.dependencies ?? []).forEach((d, i) => {
206
+ const dep = typeof d === "string" ? { plugin: d, calls: [] } : { plugin: d.plugin, calls: [...(d.calls ?? [])] };
207
+ // the reads as the generated client gives them, written only when there are any
208
+ if (typeof d !== "string" && d.reads?.length) {
209
+ dep.reads = d.reads.map((r) => ({ entity: r.entity, fields: (r.fields ?? []).map((f) => ({ name: f.name, type: f.type })) }));
210
+ }
211
+ const path = `dependencies[${i}]`;
212
+ if (dep.plugin === id)
213
+ err("E_DEP_SELF", path, "a plugin cannot depend on itself");
214
+ if (dependencies.some((x) => x.plugin === dep.plugin))
215
+ err("E_DEP_DUP", path, `\`${dep.plugin}\` is listed twice`);
216
+ dependencies.push(dep);
217
+ });
218
+ // --- entities: names first, so refs can name them -----------------------------------------------
219
+ const entityNames = new Map();
220
+ const entityList = [];
221
+ for (const [key, e] of Object.entries(options.entities ?? {})) {
222
+ const path = `entities.${key}`;
223
+ if (!(e instanceof EntityDef)) {
224
+ err("E_SCHEMA", path, "not an entity (use entity({...}))");
225
+ continue;
226
+ }
227
+ if (foreignPlugin(e)) {
228
+ err("E_SCHEMA", path, `\`${foreignPlugin(e)}.${e.options.name ?? ""}\` is another plugin's entity`, "read it with ctx.query() and list its reads in the dependency");
229
+ continue;
230
+ }
231
+ const name = e.options.name ?? snake(key);
232
+ if (!/^[a-z][a-z0-9_]{0,62}$/.test(name))
233
+ err("E_ENT_NAME", path, `\`${name}\` is not an entity name`);
234
+ if (name.endsWith("_with_deleted"))
235
+ err("E_ENT_NAME_RESERVED", path, "an entity name may not end in `_with_deleted`");
236
+ if ([...entityNames.values()].includes(name) || entityNames.has(e))
237
+ err("E_ENT_DUP", path, `entity \`${name}\` is declared twice`);
238
+ if (!["uuid", "i64", "string"].includes(e.key))
239
+ err("E_ENT_KEY", `${path}.key`, `\`${e.key}\` is not uuid, i64 or string`);
240
+ for (const col of Object.keys(e.columns)) {
241
+ if (RESERVED_COLUMNS.includes(snake(col)))
242
+ err("E_COL_RESERVED", `${path}.columns.${col}`, `\`${snake(col)}\` is a system column`, "`id` is implied by `key`; timestamps and `version` are the platform's");
243
+ }
244
+ entityNames.set(e, name);
245
+ describedNames.set(e, name);
246
+ entityList.push([key, e]);
247
+ }
248
+ // --- messages and enums -------------------------------------------------------------------------
249
+ const messages = [];
250
+ const enums = [];
251
+ const typeOwners = new Map(); // message and enum names share the protobuf namespace
252
+ const visited = new Map();
253
+ const claimType = (name, owner, path, code) => {
254
+ if (!TYPE_NAME.test(name))
255
+ err("E_MSG_NAME", path, `\`${name}\` is not a PascalCase type name`);
256
+ const existing = typeOwners.get(name);
257
+ if (existing && existing !== owner) {
258
+ err(code, path, `two different declarations are named \`${name}\``);
259
+ return false;
260
+ }
261
+ typeOwners.set(name, owner);
262
+ return true;
263
+ };
264
+ const visitEnum = (def, path) => {
265
+ if (typeOwners.get(def.name) === def)
266
+ return def.name;
267
+ if (!claimType(def.name, def, path, "E_ENUM_DUP"))
268
+ return def.name;
269
+ const values = [...def.values];
270
+ if (values.length === 0)
271
+ err("E_SCHEMA", `enums.${def.name}`, "an enum needs at least one value");
272
+ if (new Set(values).size !== values.length)
273
+ err("E_SCHEMA", `enums.${def.name}`, "an enum value is listed twice");
274
+ enums.push({ name: def.name, values });
275
+ return def.name;
276
+ };
277
+ const refType = (field, path) => {
278
+ const target = field.spec.ref;
279
+ if (target instanceof PlatformEntity)
280
+ return `ref:${target.ref}`;
281
+ if (typeof target === "string") {
282
+ if (!/^[a-z][a-z0-9]*\.[a-z][a-z0-9_]*$/.test(target))
283
+ err("E_FIELD_TYPE", path, `\`${target}\` is not <plugin>.<entity>`);
284
+ return `ref:${target}`;
285
+ }
286
+ let entity = target;
287
+ if (!(target instanceof EntityDef)) {
288
+ try {
289
+ entity = target();
290
+ }
291
+ catch (e) {
292
+ err("E_FIELD_TYPE", path, `the ref's target could not be read: ${e.message}`);
293
+ return "ref:";
294
+ }
295
+ }
296
+ if (entity instanceof EntityDef && foreignPlugin(entity))
297
+ return `ref:${foreignPlugin(entity)}.${entity.options.name ?? ""}`;
298
+ const name = entity instanceof EntityDef ? entityNames.get(entity) : undefined;
299
+ if (name === undefined) {
300
+ err("E_FIELD_TYPE", path, "the ref's entity is not in plugin({ entities })");
301
+ return "ref:";
302
+ }
303
+ return `ref:${id}.${name}`;
304
+ };
305
+ const fieldType = (field, path) => {
306
+ switch (field.spec.kind) {
307
+ case "scalar":
308
+ return field.spec.scalar;
309
+ case "enum":
310
+ return `enum:${visitEnum(field.spec.enumDef, path)}`;
311
+ case "message":
312
+ return `message:${visitMessage(field.spec.message, path)}`;
313
+ case "ref":
314
+ return refType(field, path);
315
+ case "array":
316
+ err("E_FIELD_TYPE", path, "an array of arrays is not a field type", "wrap the inner array in a message");
317
+ return "";
318
+ }
319
+ };
320
+ const describeFields = (source, path) => {
321
+ const seen = new Set();
322
+ return messageFields(source).map((f, i) => {
323
+ const fpath = `${path}.${f.key}`;
324
+ if (!/^[a-z][a-zA-Z0-9]*$/.test(f.key) || jsonName(f.name) !== f.key) {
325
+ err("E_FIELD_NAME", fpath, `\`${f.key}\` is not a lowerCamelCase field name`);
326
+ }
327
+ if (seen.has(f.name))
328
+ err("E_FIELD_DUP", fpath, `field \`${f.name}\` is declared twice`);
329
+ seen.add(f.name);
330
+ let field = f.field;
331
+ let repeated = false;
332
+ if (field.spec.kind === "array") {
333
+ repeated = true;
334
+ field = field.spec.inner;
335
+ if (!(field instanceof Field))
336
+ err("E_FIELD_TYPE", fpath, "t.array() needs a t.* field");
337
+ else if (field.isOptional)
338
+ err("E_FIELD_TYPE", fpath, "an array's elements cannot be optional");
339
+ }
340
+ return {
341
+ name: f.name,
342
+ number: i + 1,
343
+ type: field instanceof Field ? fieldType(field, fpath) : "",
344
+ repeated,
345
+ optional: f.field.isOptional,
346
+ description: f.field.description,
347
+ };
348
+ });
349
+ };
350
+ // Registers a message (or an entity's message) at its first use and returns its name.
351
+ function visitMessage(source, path) {
352
+ const isEntity = source instanceof EntityDef;
353
+ const name = isEntity ? pascal(entityNames.get(source) ?? "") : source.name;
354
+ if (visited.has(source))
355
+ return name;
356
+ if (!claimType(name, source, path, "E_MSG_DUP"))
357
+ return name;
358
+ const desc = {
359
+ name,
360
+ kind: "message",
361
+ description: isEntity ? source.options.description ?? "" : source.messageDescription,
362
+ fields: [],
363
+ };
364
+ visited.set(source, desc);
365
+ messages.push(desc);
366
+ desc.fields = describeFields(source, isEntity ? `entities.${entityNames.get(source)}.columns` : `messages.${name}`);
367
+ return name;
368
+ }
369
+ // --- endpoints ----------------------------------------------------------------------------------
370
+ const endpoints = [];
371
+ const endpointNames = new Map();
372
+ const resolvedEndpoints = [];
373
+ const io = (value, generated, path) => {
374
+ if (value instanceof MessageDef)
375
+ return value;
376
+ if (value instanceof EntityDef) {
377
+ if (entityNames.has(value))
378
+ return value;
379
+ err("E_ENDPOINT_MESSAGE", path, "the entity is not in plugin({ entities })");
380
+ return undefined;
381
+ }
382
+ if (isShape(value))
383
+ return new MessageDef(generated, value);
384
+ err("E_ENDPOINT_MESSAGE", path, "not a message, an entity or an object of t.* fields");
385
+ return undefined;
386
+ };
387
+ for (const [key, ep] of Object.entries(options.endpoints ?? {})) {
388
+ const path = `endpoints.${key}`;
389
+ if (!(ep instanceof EndpointDef)) {
390
+ err("E_SCHEMA", path, "not an endpoint (use endpoint({...}))");
391
+ continue;
392
+ }
393
+ const o = ep.options;
394
+ const name = pascal(key);
395
+ if (!TYPE_NAME.test(name))
396
+ err("E_ENDPOINT_NAME", path, `\`${name}\` is not an endpoint name`);
397
+ if (endpoints.some((x) => x.name === name))
398
+ err("E_ENDPOINT_DUP", path, `endpoint \`${name}\` is declared twice`);
399
+ const input = io(o.input, `${name}Request`, `${path}.input`);
400
+ const output = io(o.output, `${name}Reply`, `${path}.output`);
401
+ const inputName = input ? visitMessage(input, `${path}.input`) : "";
402
+ const outputName = output ? visitMessage(output, `${path}.output`) : "";
403
+ const scopeList = [...(o.scopes ?? (o.readOnly ? ["read"] : ["write"]))];
404
+ scopeList.forEach((s, i) => {
405
+ if (!scopeNames.has(s))
406
+ err("E_ENDPOINT_SCOPE_UNKNOWN", `${path}.scopes[${i}]`, `scope \`${s}\` is not declared`);
407
+ });
408
+ const auth = o.auth ?? "user";
409
+ if (!["user", "service", "any", "public"].includes(auth))
410
+ err("E_SCHEMA", `${path}.auth`, `\`${auth}\` is not user, service, any or public`);
411
+ const idempotency = o.idempotency ?? "off";
412
+ if (!["off", "optional", "required"].includes(idempotency))
413
+ err("E_SCHEMA", `${path}.idempotency`, `\`${idempotency}\` is not off, optional or required`);
414
+ const ms = timeoutMs(o.timeout);
415
+ if (ms === undefined || !Number.isInteger(ms) || ms < 1 || ms > 600_000) {
416
+ err("E_ENDPOINT_TIMEOUT_RANGE", `${path}.timeout`, `${JSON.stringify(o.timeout)} is not 1 ms … 600 s`, "milliseconds, or '500ms', '10s', '2m'");
417
+ }
418
+ if (typeof o.handler !== "function")
419
+ err("E_SCHEMA", `${path}.handler`, "an endpoint needs a handler");
420
+ const decl = {
421
+ name,
422
+ input: inputName,
423
+ output: outputName,
424
+ description: o.description ?? "",
425
+ auth,
426
+ roles: roleRefs(o.roles, `${path}.roles`),
427
+ scopes: scopeList,
428
+ idempotency,
429
+ timeout_ms: ms ?? 0,
430
+ };
431
+ if (o.ui) {
432
+ if (o.readOnly)
433
+ decl.read_only = true;
434
+ decl.ui = true;
435
+ }
436
+ if (o.invalidates && o.invalidates.length > 0)
437
+ decl.invalidates = o.invalidates.map(invalidationJson);
438
+ endpoints.push(decl);
439
+ if (!endpointNames.has(ep.root))
440
+ endpointNames.set(ep.root, name);
441
+ if (input && !describedEndpoints.has(ep.root))
442
+ describedEndpoints.set(ep.root, { name, input });
443
+ if (input && output) {
444
+ resolvedEndpoints.push({ key, name, input, output, timeoutMs: ms ?? 30_000, handler: o.handler });
445
+ }
446
+ }
447
+ // --- the navigations `include` reads: each entity's forward ones, and the inverse ones declared onto it --------
448
+ const entityByName = new Map(entityList.map(([, e]) => [entityNames.get(e), e]));
449
+ for (const [, e] of entityList)
450
+ navigations.set(e, new Map());
451
+ const targetOf = (field) => {
452
+ const t = field.spec.ref;
453
+ if (t === undefined || t instanceof PlatformEntity || typeof t === "string")
454
+ return undefined;
455
+ try {
456
+ const resolved = t instanceof EntityDef ? t : t();
457
+ return resolved instanceof EntityDef ? resolved : undefined;
458
+ }
459
+ catch {
460
+ return undefined;
461
+ }
462
+ };
463
+ const recordNavigations = (e, fields) => {
464
+ for (const f of fields) {
465
+ if (f.name === "id" || f.repeated || !f.type.startsWith("ref:"))
466
+ continue;
467
+ const col = Object.entries(e.columns).find(([k]) => snake(k) === f.name)?.[1];
468
+ if (!col)
469
+ continue;
470
+ const target = targetOf(col);
471
+ const own = navigations.get(e);
472
+ const nav = f.nav ?? (f.name.endsWith("_id") && f.name.length > 3 ? f.name.slice(0, -3) : f.name);
473
+ own.set(f.name, { kind: "forward", target });
474
+ own.set(nav, { kind: "forward", target });
475
+ if (f.inverse && f.type.startsWith(`ref:${id}.`)) {
476
+ const onto = entityByName.get(f.type.slice(`ref:${id}.`.length));
477
+ if (onto)
478
+ navigations.get(onto)?.set(f.inverse, { kind: "inverse", source: e });
479
+ }
480
+ }
481
+ };
482
+ // --- entities' messages, then the extra messages and enums --------------------------------------
483
+ const entities = entityList.map(([key, e]) => {
484
+ const name = entityNames.get(e);
485
+ const path = `entities.${key}`;
486
+ const message = visitMessage(e, path);
487
+ const columns = Object.keys(e.columns).map(snake);
488
+ let label;
489
+ if (e.options.label !== undefined) {
490
+ label = snake(e.options.label);
491
+ if (label !== "id" && !columns.includes(label))
492
+ err("E_ENT_LABEL", `${path}.label`, `\`${label}\` is not a column`);
493
+ }
494
+ else {
495
+ label = ["name", "title", "number"].find((c) => columns.includes(c)) ?? "id";
496
+ }
497
+ // the entity's fields are its message's, with the column modifiers (the message's copy has none)
498
+ let searchable = 0;
499
+ const fields = (visited.get(e)?.fields ?? []).map((f) => {
500
+ const entry = Object.entries(e.columns).find(([k]) => snake(k) === f.name);
501
+ const col = entry?.[1];
502
+ const cpath = `${path}.columns.${entry?.[0] ?? f.name}`;
503
+ const out = { ...f };
504
+ if (col?.column.unique)
505
+ out.unique = true;
506
+ if (col?.column.index)
507
+ out.index = true;
508
+ if (col?.column.encrypted)
509
+ out.encrypted = true;
510
+ if (col?.column.searchable !== undefined) {
511
+ out.searchable = col.column.searchable;
512
+ searchable += 1;
513
+ if (f.type !== "string" || f.repeated) {
514
+ err("E_SEARCH_TYPE", cpath, `${f.name} is not a text column: only a single string column is searchable`);
515
+ }
516
+ if (!SEARCH_LANGUAGES.includes(out.searchable)) {
517
+ err("E_SEARCH_LANGUAGE", `${cpath}.searchable`, `${JSON.stringify(out.searchable)} is not a text search language`, `one of ${SEARCH_LANGUAGES.join(", ")}`);
518
+ }
519
+ if (searchable === MAX_SEARCHABLE + 1) {
520
+ err("E_SEARCH_LIMIT", cpath, `${name} has more than ${MAX_SEARCHABLE} searchable columns`);
521
+ }
522
+ }
523
+ for (const what of ["nav", "inverse"]) {
524
+ const v = col?.column[what];
525
+ if (v === undefined)
526
+ continue;
527
+ out[what] = v;
528
+ if (!f.type.startsWith("ref:") || f.repeated) {
529
+ err("E_REF_NAME", `${cpath}.${what}`, `${f.name} is not a ref column: only a single ref has a ${what}`);
530
+ }
531
+ else if (!NAV_NAME.test(v)) {
532
+ err("E_REF_NAME", `${cpath}.${what}`, `${JSON.stringify(v)} is not a navigation name`, "snake_case, at most 63 characters");
533
+ }
534
+ }
535
+ const onDelete = col?.column.onDelete;
536
+ if (onDelete !== undefined) {
537
+ const v = snake(onDelete);
538
+ out.on_delete = v;
539
+ const dpath = `${cpath}.onDelete`;
540
+ const target = f.type.startsWith("ref:") ? f.type.slice(4).split(".")[0] : undefined;
541
+ if (target === undefined || f.repeated) {
542
+ err("E_REF_ON_DELETE", dpath, `${f.name} is not a ref column: only a single ref has an onDelete`);
543
+ }
544
+ else if (target === id && !ON_DELETE_OWN.includes(v)) {
545
+ err("E_REF_ON_DELETE", dpath, `${JSON.stringify(onDelete)} is not an onDelete of a ref within the plugin`, "one of restrict, cascade, setNull, noAction");
546
+ }
547
+ else if (target !== id && (!ON_DELETE_CROSS.includes(v) || (v === "set_null" && target !== "platform"))) {
548
+ err("E_REF_CROSS_ON_DELETE", dpath, `${JSON.stringify(onDelete)} is not an onDelete of a ref to ${f.type.slice(4)}`, target === "platform" ? "keep or setNull" : "a ref to another plugin keeps the id (keep)");
549
+ }
550
+ else if (v === "set_null" && !f.optional) {
551
+ err("E_REF_ON_DELETE", dpath, `${f.name} is required: setNull clears an optional ref`);
552
+ }
553
+ else if (v === "set_null" && e.options.appendOnly) {
554
+ err("E_ENT_APPEND_ONLY_CASCADE", dpath, `${name} is append-only: setNull would change its rows`);
555
+ }
556
+ }
557
+ return out;
558
+ });
559
+ recordNavigations(e, fields);
560
+ const decl = {
561
+ name,
562
+ message,
563
+ key: e.key,
564
+ label,
565
+ soft_delete: e.options.softDelete ?? false,
566
+ version: e.options.version ?? false,
567
+ append_only: e.options.appendOnly ?? false,
568
+ fields,
569
+ };
570
+ const indexes = (e.options.indexes ?? []).map((ix) => {
571
+ const { columns, unique } = Array.isArray(ix)
572
+ ? { columns: ix, unique: false }
573
+ : ix;
574
+ const out = {
575
+ columns: columns.map((c) => {
576
+ const [col, dir] = c.trim().split(/\s+/);
577
+ const column = { name: snake(col ?? "") };
578
+ if (dir === "desc")
579
+ column.desc = true;
580
+ return column;
581
+ }),
582
+ };
583
+ if (unique)
584
+ out.unique = true;
585
+ return out;
586
+ });
587
+ if (indexes.length > 0)
588
+ decl.indexes = indexes;
589
+ if (e.options.access) {
590
+ decl.access = describeAccess(e.options.access, {
591
+ role: roleName,
592
+ entity: (x) => entityNames.get(x) ?? (foreignPlugin(x) ? `${foreignPlugin(x)}.${x.options.name ?? ""}` : undefined),
593
+ error: (message, code) => err(code ?? "E_ACCESS_ROLE_UNKNOWN", `${path}.access`, message),
594
+ });
595
+ }
596
+ return decl;
597
+ });
598
+ // the scope of `authz:bypass`: entities by their names
599
+ for (const [name, c] of Object.entries(options.capabilities ?? {})) {
600
+ const on = typeof c === "string" ? undefined : c?.on;
601
+ if (!on?.length)
602
+ continue;
603
+ const path = `capabilities.${JSON.stringify(name)}.on`;
604
+ if (name !== "authz:bypass")
605
+ err("E_CAPABILITY_SCOPE", path, `${name} has no scope`);
606
+ const decl = capabilities.find((x) => x.name === name);
607
+ if (decl) {
608
+ decl.on = on.map((s, i) => {
609
+ const entity = entityNames.get(s.entity);
610
+ if (entity === undefined)
611
+ err("E_CAPABILITY_SCOPE", `${path}[${i}]`, "the entity is not in plugin({ entities })");
612
+ return { entity: entity ?? "", ops: [...s.ops] };
613
+ });
614
+ }
615
+ }
616
+ (options.messages ?? []).forEach((m, i) => {
617
+ if (m instanceof MessageDef)
618
+ visitMessage(m, `messages[${i}]`);
619
+ else
620
+ err("E_SCHEMA", `messages[${i}]`, "not a message (use t.message(...))");
621
+ });
622
+ // --- jobs: their payloads follow the extra messages ----------------------------------------------
623
+ const jobs = [];
624
+ const resolvedJobs = new Map();
625
+ const jobPayloads = new Map(); // payload message → the job that has it
626
+ const scheduled = []; // [path, payload] of the jobs with a schedule
627
+ for (const [key, j] of Object.entries(options.jobs ?? {})) {
628
+ const path = `jobs.${key}`;
629
+ if (!(j instanceof JobDef)) {
630
+ err("E_SCHEMA", path, "not a job (use job({...}))");
631
+ continue;
632
+ }
633
+ const o = j.options;
634
+ const name = o.name ?? snake(key);
635
+ if (typeof name !== "string" || !JOB_NAME.test(name)) {
636
+ err("E_JOB_NAME", `${path}.name`, `${JSON.stringify(name)} is not a job name`, "snake_case, at most 32 characters: remind_unpaid");
637
+ }
638
+ if (jobs.some((x) => x.name === name))
639
+ err("E_JOB_DUP", path, `job \`${name}\` is declared twice`);
640
+ let payload;
641
+ if (o.payload instanceof MessageDef)
642
+ payload = o.payload;
643
+ else if (isShape(o.payload))
644
+ payload = new MessageDef(pascal(String(name)), o.payload);
645
+ else
646
+ err("E_JOB_PAYLOAD", `${path}.payload`, "not a message or an object of t.* fields");
647
+ const payloadName = payload ? visitMessage(payload, `${path}.payload`) : "";
648
+ const desc = payload ? visited.get(payload) : undefined;
649
+ if (desc)
650
+ desc.kind = "job";
651
+ if (payload) {
652
+ const other = jobPayloads.get(payloadName);
653
+ if (other !== undefined) {
654
+ err("E_JOB_PAYLOAD_DUP", `${path}.payload`, `message \`${payloadName}\` is the payload of job \`${other}\``, "a job is enqueued by its declaration: give each job a message of its own");
655
+ }
656
+ else
657
+ jobPayloads.set(payloadName, String(name));
658
+ }
659
+ const decl = { name, payload: payloadName };
660
+ if (o.description)
661
+ decl.description = o.description;
662
+ if (o.cron !== undefined && o.cron !== "") {
663
+ const problem = typeof o.cron === "string" ? cronError(o.cron) : "not a string";
664
+ if (problem !== undefined) {
665
+ err("E_JOB_CRON", `${path}.cron`, `${JSON.stringify(o.cron)}: ${problem}`, "five fields in UTC, minute hour day-of-month month day-of-week: 0 9 * * 1-5");
666
+ }
667
+ decl.cron = String(o.cron);
668
+ if (payload)
669
+ scheduled.push([`${path}.payload`, payloadName]);
670
+ }
671
+ if (o.as !== undefined) {
672
+ if (o.as === "system")
673
+ decl.as_system = true;
674
+ else
675
+ err("E_SCHEMA", `${path}.as`, `${JSON.stringify(o.as)} is not 'system'`);
676
+ }
677
+ if (o.retry !== undefined) {
678
+ const r = o.retry;
679
+ const retries = r.retries ?? 3;
680
+ const delay = r.delay === undefined ? 30_000 : durationMs(r.delay);
681
+ const backoff = r.backoff ?? "exponential";
682
+ if (!Number.isInteger(retries) || retries < 0 || retries > JOB_MAX_RETRIES) {
683
+ err("E_JOB_RETRY", `${path}.retry.retries`, `${JSON.stringify(r.retries)} retries; a job has 0 to ${JOB_MAX_RETRIES}`);
684
+ }
685
+ if (delay === undefined || !Number.isInteger(delay) || delay < 0 || delay > JOB_MAX_DELAY_MS) {
686
+ err("E_JOB_RETRY", `${path}.retry.delay`, `a retry delay of ${JSON.stringify(r.delay)}; whole milliseconds, at most one hour`, "milliseconds, or '500ms', '30s', '5m', '1h'");
687
+ }
688
+ if (backoff !== "fixed" && backoff !== "exponential") {
689
+ err("E_JOB_RETRY", `${path}.retry.backoff`, `${JSON.stringify(backoff)} is not fixed or exponential`);
690
+ }
691
+ decl.retry = { retries, delay_ms: delay ?? 0, backoff };
692
+ }
693
+ if (o.timeout !== undefined) {
694
+ const ms = durationMs(o.timeout);
695
+ if (ms === undefined || !Number.isInteger(ms) || ms < 1000 || ms > 3_600_000) {
696
+ err("E_JOB_TIMEOUT", `${path}.timeout`, `a timeout of ${JSON.stringify(o.timeout)}; a run's timeout is 1 s to 1 h`, "milliseconds, or '10s', '2m', '1h'");
697
+ }
698
+ decl.timeout_ms = ms ?? 0;
699
+ }
700
+ if (o.concurrency !== undefined) {
701
+ if (!Number.isInteger(o.concurrency) || o.concurrency < 1 || o.concurrency > 64) {
702
+ err("E_JOB_CONCURRENCY", `${path}.concurrency`, `a concurrency of ${o.concurrency}; a job runs 1 to 64 runs at once`);
703
+ }
704
+ decl.concurrency = o.concurrency;
705
+ }
706
+ if (typeof o.handler !== "function")
707
+ err("E_SCHEMA", `${path}.handler`, "a job needs a handler");
708
+ jobs.push(decl);
709
+ if (payload && !resolvedJobs.has(name))
710
+ resolvedJobs.set(name, { def: j, name, payload, handler: o.handler });
711
+ }
712
+ const jobSlots = options.jobSlots ?? DEFAULT_JOB_SLOTS;
713
+ if (!Number.isInteger(jobSlots) || jobSlots < 1 || jobSlots > MAX_JOB_SLOTS) {
714
+ err("E_JOB_SLOTS", "jobSlots", `${jobSlots} job slots; a process runs 1 to ${MAX_JOB_SLOTS} runs at once`);
715
+ }
716
+ // --- topics: their key messages follow the jobs' payloads -----------------------------------------
717
+ const endpointName = (def, path) => {
718
+ const name = def instanceof EndpointDef ? endpointNames.get(def.root) : undefined;
719
+ if (name === undefined)
720
+ err("E_UI_ENDPOINT_UNKNOWN", path, "the endpoint is not in plugin({ endpoints })");
721
+ return name ?? "";
722
+ };
723
+ const topicList = Array.isArray(options.topics)
724
+ ? options.topics.map((t, i) => [`topics[${i}]`, t])
725
+ : Object.entries(options.topics ?? {}).map(([k, t]) => [`topics.${k}`, t]);
726
+ const topics = [];
727
+ for (const [path, t] of topicList) {
728
+ if (!(t instanceof TopicDef || t instanceof TopicDecl) || !(topicDecl(t).topic.keyMessage instanceof MessageDef)) {
729
+ err("E_SCHEMA", path, "not a topic (use topic(name, t.message(..)))");
730
+ continue;
731
+ }
732
+ const d = topicDecl(t);
733
+ const decl = {
734
+ name: d.topic.name,
735
+ key: visitMessage(d.topic.keyMessage, `${path}.key`),
736
+ description: d.description,
737
+ };
738
+ const roleList = roleRefs(d.roleList, `${path}.roles`);
739
+ if (roleList.length > 0)
740
+ decl.roles = roleList;
741
+ d.scopeList.forEach((s, i) => {
742
+ if (!scopeNames.has(s))
743
+ err("E_ENDPOINT_SCOPE_UNKNOWN", `${path}.scopes[${i}]`, `scope \`${s}\` is not declared`);
744
+ });
745
+ if (d.scopeList.length > 0)
746
+ decl.scopes = [...d.scopeList];
747
+ if (d.authorizer)
748
+ decl.authorize = endpointName(d.authorizer, `${path}.authorize`);
749
+ if (d.isManual)
750
+ decl.manual = true;
751
+ topics.push(decl);
752
+ }
753
+ // the topic an agent's runs invalidate is one of the plugin's
754
+ for (const [key, a] of Object.entries(options.agents ?? {})) {
755
+ if (a?.topic === undefined)
756
+ continue;
757
+ const named = a.topic instanceof TopicDef || a.topic instanceof TopicDecl ? topicDecl(a.topic).topic.name : undefined;
758
+ if (named === undefined)
759
+ err("E_SCHEMA", `agents.${key}.topic`, "not a topic (use topic(name, t.message(..)))");
760
+ else if (!topics.some((t) => t.name === named))
761
+ err("E_AGENT_TOPIC_UNKNOWN", `agents.${key}.topic`, `topic \`${named}\` is not declared`, "list it in plugin({ topics })");
762
+ }
763
+ (options.enums ?? []).forEach((en, i) => {
764
+ if (en instanceof EnumDef)
765
+ visitEnum(en, `enums[${i}]`);
766
+ else
767
+ err("E_SCHEMA", `enums[${i}]`, "not an enum (use t.enum(...))");
768
+ });
769
+ const descriptor = {
770
+ schema: 1,
771
+ id,
772
+ version: version ?? "",
773
+ title: options.title ?? (typeof id === "string" ? humanize(id) : ""),
774
+ description: options.description ?? "",
775
+ roles,
776
+ scopes,
777
+ capabilities,
778
+ permissions,
779
+ agents,
780
+ dependencies,
781
+ enums,
782
+ messages,
783
+ entities,
784
+ endpoints,
785
+ };
786
+ if (connections.length > 0)
787
+ descriptor.connections = connections;
788
+ if (jobs.length > 0)
789
+ descriptor.jobs = jobs;
790
+ // a scheduled job runs with its payload's defaults: a required timestamp or date has none
791
+ for (const [path, payload] of scheduled) {
792
+ const field = requiredWithoutDefault(descriptor, payload);
793
+ if (field !== undefined) {
794
+ err("E_JOB_SCHEDULE_PAYLOAD", path, `a scheduled job runs with its payload's defaults, and ${field} has none`, "make the field optional, or start the job by enqueueing it instead of a schedule");
795
+ }
796
+ }
797
+ if (topics.length > 0)
798
+ descriptor.topics = topics;
799
+ // --- notification kinds: written only when declared; they need push:send
800
+ const kinds = options.notifications ?? [];
801
+ if (kinds.length > 0 && !capabilities.some((c) => c.name === "push:send")) {
802
+ err("E_NOTIFY_CAPABILITY", "notifications", "notification kinds need the capability push:send");
803
+ }
804
+ const notifications = [];
805
+ kinds.forEach((k, i) => {
806
+ const path = `notifications[${i}]`;
807
+ if (!(k instanceof NotificationKind)) {
808
+ err("E_SCHEMA", path, "not a notification kind (use notification(name, {..}))");
809
+ return;
810
+ }
811
+ if (typeof k.name !== "string" || !/^[a-z][a-z0-9_]{0,31}$/.test(k.name)) {
812
+ err("E_NOTIFY_KIND_NAME", path, `\`${k.name}\` must match ^[a-z][a-z0-9_]{0,31}$`);
813
+ }
814
+ else if (notifications.some((x) => x.name === k.name)) {
815
+ err("E_NOTIFY_KIND_NAME", path, `notification kind \`${k.name}\` is declared twice`);
816
+ }
817
+ notifications.push({
818
+ name: k.name,
819
+ title: k.options.title ?? "",
820
+ description: k.options.description ?? "",
821
+ tab: k.options.tab ?? "for_you",
822
+ digest: !!k.options.digest,
823
+ });
824
+ });
825
+ if (notifications.length > 0)
826
+ descriptor.notifications = notifications;
827
+ // --- the run-change hook: a system route, and `runs` in the descriptor
828
+ if (options.onRunChange !== undefined) {
829
+ const handler = options.onRunChange;
830
+ if (typeof handler !== "function") {
831
+ err("E_SCHEMA", "onRunChange", "not a function (ctx, change) => ...");
832
+ }
833
+ else {
834
+ descriptor.runs = { on_change: true };
835
+ resolvedEndpoints.push({
836
+ key: "onRunChange",
837
+ name: RUN_CHANGE_METHOD,
838
+ input: NO_FIELDS,
839
+ output: NO_FIELDS,
840
+ timeoutMs: RUN_CHANGE_TIMEOUT_MS,
841
+ system: true,
842
+ decode: runChangeOf,
843
+ handler: (async (ctx, change) => {
844
+ await handler(ctx, change);
845
+ return {};
846
+ }),
847
+ });
848
+ }
849
+ }
850
+ if (options.ui !== undefined) {
851
+ if (options.ui instanceof UiDoc) {
852
+ descriptor.ui = resolveUi(options.ui, {
853
+ endpoint: endpointName,
854
+ entity: (e, path) => {
855
+ const name = entityNames.get(e);
856
+ if (name === undefined)
857
+ err("E_FIELD_TYPE", path, "the ref's entity is not in plugin({ entities })");
858
+ return `${id}.${name ?? ""}`;
859
+ },
860
+ });
861
+ }
862
+ else {
863
+ err("E_SCHEMA", "ui", "not a UI document (use ui.define({...}))");
864
+ }
865
+ }
866
+ return {
867
+ descriptor,
868
+ errors,
869
+ endpoints: resolvedEndpoints,
870
+ jobs: resolvedJobs,
871
+ jobSlots: resolvedJobs.size > 0 ? jobSlots : 0,
872
+ roleName,
873
+ };
874
+ }
875
+ /**
876
+ * The first field of message `name` that a payload read from `{}` cannot fill (`RemindUnpaid.since`): a single
877
+ * `timestamp` or `date` that is not optional, directly or in a message field that is not optional.
878
+ */
879
+ function requiredWithoutDefault(d, name, seen = []) {
880
+ if (seen.includes(name))
881
+ return undefined;
882
+ seen.push(name);
883
+ const fields = d.messages.find((m) => m.name === name)?.fields ?? d.entities.find((e) => e.message === name)?.fields;
884
+ for (const f of fields ?? []) {
885
+ if (f.optional || f.repeated)
886
+ continue;
887
+ if (f.type === "timestamp" || f.type === "date")
888
+ return `${name}.${f.name}`;
889
+ if (f.type.startsWith("message:")) {
890
+ const inner = f.type.slice("message:".length);
891
+ if (!d.messages.some((m) => m.name === inner))
892
+ continue;
893
+ const found = requiredWithoutDefault(d, inner, seen);
894
+ if (found !== undefined)
895
+ return found;
896
+ }
897
+ }
898
+ return undefined;
899
+ }