@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
package/dist/codec.js ADDED
@@ -0,0 +1,361 @@
1
+ // The JSON codec: request bodies to handler input and handler output to response bodies, in the protobuf JSON
2
+ // mapping. Field names are the protobuf JSON names (lowerCamelCase: the TypeScript keys); the snake_case
3
+ // descriptor names are accepted on input too. int64 is a string (a number is accepted on input), enums are their
4
+ // value names, `decimal` is a string, `timestamp` an RFC 3339 string, `date` `YYYY-MM-DD`, `bytes` base64,
5
+ // `json` the value itself. Unknown fields are ignored.
6
+ //
7
+ // Absent fields follow proto3: a required scalar, enum, ref or repeated field that is absent reads as its
8
+ // default (`""`, `0`, `0n`, `false`, the first enum value, `[]`), a required message as the message read from `{}`
9
+ // (what an `omitDefaults` message leaves out of an empty one); a required timestamp or date that is absent is
10
+ // invalid. Output emits every field that has a value, defaults included, except in an `omitDefaults` message.
11
+ import { Decimal } from "./decimal.js";
12
+ import { jsonName, snake } from "./names.js";
13
+ import { EntityDef, Field, MessageDef, PlatformEntity } from "./schema.js";
14
+ const models = new WeakMap();
15
+ function modelOf(key, field) {
16
+ const name = snake(key);
17
+ return { key, name, json: jsonName(name), field };
18
+ }
19
+ /** The fields of a message, or of an entity's message (`id` first, then the columns). */
20
+ export function messageFields(source) {
21
+ let fields = models.get(source);
22
+ if (!fields) {
23
+ if (source instanceof EntityDef) {
24
+ const id = new Field({ kind: "ref", ref: source });
25
+ // a column named `id` is a definition error (E_COL_RESERVED); the implied id stands
26
+ const columns = Object.entries(source.columns).filter(([k]) => k !== "id");
27
+ fields = [modelOf("id", id), ...columns.map(([k, f]) => modelOf(k, f))];
28
+ }
29
+ else {
30
+ fields = Object.entries(source.fields).map(([k, f]) => modelOf(k, f));
31
+ }
32
+ models.set(source, fields);
33
+ }
34
+ return fields;
35
+ }
36
+ /** The key type of a ref's target; `undefined` for the directory and other plugins' entities. */
37
+ export function refKey(target) {
38
+ if (target instanceof EntityDef)
39
+ return target.key;
40
+ if (target instanceof PlatformEntity || typeof target === "string")
41
+ return undefined;
42
+ const resolved = target();
43
+ return resolved instanceof EntityDef ? resolved.key : undefined;
44
+ }
45
+ const UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
46
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
47
+ const INT = /^-?\d+$/;
48
+ const BASE64 = /^[A-Za-z0-9+/_-]*={0,2}$/;
49
+ const INT64_MIN = -(2n ** 63n);
50
+ const INT64_MAX = 2n ** 63n - 1n;
51
+ const join = (path, key) => (path ? `${path}.${key}` : key);
52
+ function isObject(v) {
53
+ return typeof v === "object" && v !== null && !Array.isArray(v);
54
+ }
55
+ /** Decodes a JSON object into a message's TypeScript value; problems go to `errors`. */
56
+ export function decodeMessage(source, json, path, errors) {
57
+ const out = {};
58
+ if (!isObject(json)) {
59
+ errors[path || "$"] = "expected an object";
60
+ return out;
61
+ }
62
+ for (const f of messageFields(source)) {
63
+ const raw = f.json in json ? json[f.json] : f.name in json ? json[f.name] : json[f.key];
64
+ const value = decodeField(f.field, raw, join(path, f.json), errors);
65
+ if (value !== undefined)
66
+ out[f.key] = value;
67
+ }
68
+ return out;
69
+ }
70
+ /** One value of a (single) field: `undefined` for a JSON null or nothing. */
71
+ export function decodeFieldValue(field, raw, path, errors) {
72
+ if (raw === undefined || raw === null)
73
+ return undefined;
74
+ return decodeValue(field, raw, path, errors);
75
+ }
76
+ function decodeField(field, raw, path, errors) {
77
+ const { spec } = field;
78
+ if (spec.kind === "array") {
79
+ if (raw === undefined || raw === null)
80
+ return [];
81
+ if (!Array.isArray(raw)) {
82
+ errors[path] = "expected an array";
83
+ return undefined;
84
+ }
85
+ return raw.map((item, i) => decodeValue(spec.inner, item, `${path}[${i}]`, errors));
86
+ }
87
+ if (raw === undefined || raw === null) {
88
+ if (field.isOptional)
89
+ return undefined;
90
+ return defaultValue(field, path, errors);
91
+ }
92
+ return decodeValue(field, raw, path, errors);
93
+ }
94
+ function defaultValue(field, path, errors) {
95
+ const { spec } = field;
96
+ switch (spec.kind) {
97
+ case "enum":
98
+ return spec.enumDef.values[0];
99
+ case "ref":
100
+ return refKey(spec.ref) === "i64" ? "0" : "";
101
+ case "message":
102
+ return decodeMessage(spec.message, {}, path, errors);
103
+ case "scalar":
104
+ switch (spec.scalar) {
105
+ case "string":
106
+ case "uuid":
107
+ return "";
108
+ case "bool":
109
+ return false;
110
+ case "int32":
111
+ case "double":
112
+ return 0;
113
+ case "int64":
114
+ return 0n;
115
+ case "decimal":
116
+ return Decimal.ZERO;
117
+ case "bytes":
118
+ return new Uint8Array();
119
+ case "json":
120
+ return null;
121
+ default:
122
+ errors[path] = "required";
123
+ return undefined;
124
+ }
125
+ }
126
+ return undefined;
127
+ }
128
+ function decodeValue(field, raw, path, errors) {
129
+ const { spec } = field;
130
+ const fail = (message) => {
131
+ errors[path] = message;
132
+ return undefined;
133
+ };
134
+ switch (spec.kind) {
135
+ case "array":
136
+ return fail("nested arrays are not supported");
137
+ case "message":
138
+ return decodeMessage(spec.message, raw, path, errors);
139
+ case "enum": {
140
+ const values = spec.enumDef.values;
141
+ return typeof raw === "string" && values.includes(raw) ? raw : fail(`expected one of ${values.join(", ")}`);
142
+ }
143
+ case "ref": {
144
+ const key = refKey(spec.ref);
145
+ if (key === "i64") {
146
+ if (typeof raw === "number" && Number.isSafeInteger(raw))
147
+ return String(raw);
148
+ return typeof raw === "string" && INT.test(raw) ? raw : fail("expected an integer id");
149
+ }
150
+ if (typeof raw !== "string")
151
+ return fail("expected a string id");
152
+ if (key === "uuid" && !UUID.test(raw))
153
+ return fail("expected a uuid");
154
+ return raw;
155
+ }
156
+ case "scalar":
157
+ break;
158
+ }
159
+ switch (spec.scalar) {
160
+ case "string":
161
+ return typeof raw === "string" ? raw : fail("expected a string");
162
+ case "uuid":
163
+ return typeof raw === "string" && UUID.test(raw) ? raw : fail("expected a uuid");
164
+ case "bool":
165
+ return typeof raw === "boolean" ? raw : fail("expected true or false");
166
+ case "int32": {
167
+ const n = typeof raw === "string" && INT.test(raw) ? Number(raw) : raw;
168
+ return typeof n === "number" && Number.isInteger(n) && n >= -(2 ** 31) && n < 2 ** 31
169
+ ? n
170
+ : fail("expected a 32-bit integer");
171
+ }
172
+ case "int64": {
173
+ let n;
174
+ if (typeof raw === "string" && INT.test(raw))
175
+ n = BigInt(raw);
176
+ else if (typeof raw === "number" && Number.isSafeInteger(raw))
177
+ n = BigInt(raw);
178
+ return n !== undefined && n >= INT64_MIN && n <= INT64_MAX ? n : fail("expected a 64-bit integer");
179
+ }
180
+ case "double": {
181
+ if (typeof raw === "number")
182
+ return raw;
183
+ if (raw === "NaN")
184
+ return NaN;
185
+ if (raw === "Infinity")
186
+ return Infinity;
187
+ if (raw === "-Infinity")
188
+ return -Infinity;
189
+ const n = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
190
+ return Number.isNaN(n) ? fail("expected a number") : n;
191
+ }
192
+ case "decimal":
193
+ if (typeof raw !== "string" && typeof raw !== "number")
194
+ return fail("expected a decimal string");
195
+ try {
196
+ return Decimal.from(raw);
197
+ }
198
+ catch {
199
+ return fail("expected a decimal string");
200
+ }
201
+ case "timestamp": {
202
+ if (typeof raw !== "string")
203
+ return fail("expected an RFC 3339 timestamp");
204
+ const d = new Date(raw);
205
+ return Number.isNaN(d.getTime()) ? fail("expected an RFC 3339 timestamp") : d;
206
+ }
207
+ case "date":
208
+ return typeof raw === "string" && validDate(raw) ? raw : fail("expected a date (YYYY-MM-DD)");
209
+ case "bytes":
210
+ return typeof raw === "string" && BASE64.test(raw) ? Buffer.from(raw, "base64") : fail("expected base64");
211
+ case "json":
212
+ return raw;
213
+ }
214
+ }
215
+ function validDate(s) {
216
+ const m = DATE.exec(s);
217
+ if (!m)
218
+ return false;
219
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
220
+ return d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]);
221
+ }
222
+ /** A handler answered something that does not fit its output type: a 500 for the caller, logged with the path. */
223
+ export class OutputError extends Error {
224
+ path;
225
+ constructor(path, message) {
226
+ super(`output ${path}: ${message}`);
227
+ this.path = path;
228
+ this.name = "OutputError";
229
+ }
230
+ }
231
+ /** Encodes a handler's output value as a JSON object. */
232
+ export function encodeMessage(source, value, path = "") {
233
+ if (!isObject(value))
234
+ throw new OutputError(path || "$", "expected an object");
235
+ const out = {};
236
+ // `omitDefaults`: a field at its protobuf default is left out (an optional one is written whenever it has a value)
237
+ const trim = source instanceof MessageDef && source.omitDefaults;
238
+ for (const f of messageFields(source)) {
239
+ const v = value[f.key];
240
+ const p = join(path, f.key);
241
+ if (f.field.spec.kind === "array") {
242
+ if (v === undefined || v === null) {
243
+ if (!trim)
244
+ out[f.json] = [];
245
+ }
246
+ else if (!Array.isArray(v))
247
+ throw new OutputError(p, "expected an array");
248
+ else if (!(trim && v.length === 0))
249
+ out[f.json] = v.map((item, i) => encodeValue(f.field.spec.inner, item, `${p}[${i}]`));
250
+ continue;
251
+ }
252
+ if (v === null && f.field.spec.scalar === "json") {
253
+ out[f.json] = null;
254
+ continue;
255
+ }
256
+ if (v === undefined || v === null) {
257
+ if (f.field.isOptional)
258
+ continue;
259
+ throw new OutputError(p, "a required field is missing");
260
+ }
261
+ const encoded = encodeValue(f.field, v, p);
262
+ if (trim && !f.field.isOptional && isDefault(f.field, encoded))
263
+ continue;
264
+ out[f.json] = encoded;
265
+ }
266
+ return out;
267
+ }
268
+ /**
269
+ * The protobuf default of a field's JSON that an `omitDefaults` message leaves out: `""` of a string, `0` of a number,
270
+ * `false`, empty bytes, a message whose JSON is `{}`. Never an enum (its first value is written), a uuid, a timestamp,
271
+ * a date, a decimal, a json value or a ref.
272
+ */
273
+ function isDefault(field, json) {
274
+ const { spec } = field;
275
+ if (spec.kind === "message")
276
+ return isObject(json) && Object.keys(json).length === 0;
277
+ if (spec.kind !== "scalar")
278
+ return false;
279
+ switch (spec.scalar) {
280
+ case "string":
281
+ case "bytes":
282
+ return json === "";
283
+ case "bool":
284
+ return json === false;
285
+ case "int32":
286
+ case "double":
287
+ return json === 0;
288
+ case "int64":
289
+ return json === "0" || json === "-0";
290
+ default:
291
+ return false;
292
+ }
293
+ }
294
+ function encodeValue(field, v, path) {
295
+ const { spec } = field;
296
+ const fail = (message) => {
297
+ throw new OutputError(path, message);
298
+ };
299
+ switch (spec.kind) {
300
+ case "array":
301
+ return fail("nested arrays are not supported");
302
+ case "message":
303
+ return encodeMessage(spec.message, v, path);
304
+ case "enum":
305
+ return typeof v === "string" && spec.enumDef.values.includes(v) ? v : fail(`not a value of ${spec.enumDef.name}`);
306
+ case "ref":
307
+ if (typeof v === "string")
308
+ return v;
309
+ if (typeof v === "bigint" || (typeof v === "number" && Number.isSafeInteger(v)))
310
+ return String(v);
311
+ return fail("expected an id");
312
+ case "scalar":
313
+ break;
314
+ }
315
+ switch (spec.scalar) {
316
+ case "string":
317
+ case "uuid":
318
+ return typeof v === "string" ? v : fail("expected a string");
319
+ case "bool":
320
+ return typeof v === "boolean" ? v : fail("expected a boolean");
321
+ case "int32":
322
+ return typeof v === "number" && Number.isInteger(v) ? v : fail("expected an integer");
323
+ case "int64":
324
+ if (typeof v === "bigint")
325
+ return v.toString();
326
+ if (typeof v === "number" && Number.isSafeInteger(v))
327
+ return String(v);
328
+ return typeof v === "string" && INT.test(v) ? v : fail("expected a bigint");
329
+ case "double":
330
+ if (typeof v !== "number")
331
+ return fail("expected a number");
332
+ return Number.isFinite(v) ? v : Number.isNaN(v) ? "NaN" : v > 0 ? "Infinity" : "-Infinity";
333
+ case "decimal":
334
+ try {
335
+ return Decimal.from(v).toString();
336
+ }
337
+ catch {
338
+ return fail("expected a Decimal");
339
+ }
340
+ case "timestamp": {
341
+ const d = v instanceof Date ? v : typeof v === "string" ? new Date(v) : undefined;
342
+ return d && !Number.isNaN(d.getTime()) ? d.toISOString() : fail("expected a Date");
343
+ }
344
+ case "date":
345
+ if (v instanceof Date && !Number.isNaN(v.getTime()))
346
+ return v.toISOString().slice(0, 10);
347
+ return typeof v === "string" && validDate(v) ? v : fail("expected a YYYY-MM-DD date");
348
+ case "bytes":
349
+ return v instanceof Uint8Array ? Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") : fail("expected a Uint8Array");
350
+ case "json":
351
+ return v;
352
+ }
353
+ }
354
+ /** @internal One value of a field in the protobuf JSON mapping (for filters and patches). */
355
+ export function encodeFieldValue(field, v, path) {
356
+ return encodeValue(field, v, path);
357
+ }
358
+ /** JSON.stringify that writes a bigint as a string (for raw calls and logs). */
359
+ export function stringify(value) {
360
+ return JSON.stringify(value, (_k, v) => (typeof v === "bigint" ? v.toString() : v));
361
+ }
package/dist/cron.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** @internal What is wrong with a cron expression, in words; `undefined` when it parses. */
2
+ export declare function cronError(s: string): string | undefined;
package/dist/cron.js ADDED
@@ -0,0 +1,113 @@
1
+ // The schedule of a job: a cron expression of five fields, in UTC, checked as the platform checks it.
2
+ //
3
+ // `minute hour day-of-month month day-of-week`, each a `*`, a number, a range `a-b`, a step `*/n`, `a-b/n` or `a/n`
4
+ // (from `a` to the field's end), or a comma-separated list of these. Months may be named (`jan`–`dec`) and weekdays
5
+ // too (`sun`–`sat`; `0` and `7` are Sunday), in any case. When both the day of the month and the day of the week are
6
+ // restricted (neither starts with `*`), a day matches either of them, as in the classic cron; otherwise both must
7
+ // match. There are no seconds, no years, no `L`, `W`, `#`, `?` and no `@daily` shorthands.
8
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
9
+ const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
10
+ const SPECS = [
11
+ { what: "minute", min: 0, max: 59, names: [], namesFrom: 0 },
12
+ { what: "hour", min: 0, max: 23, names: [], namesFrom: 0 },
13
+ { what: "day of the month", min: 1, max: 31, names: [], namesFrom: 0 },
14
+ { what: "month", min: 1, max: 12, names: MONTHS, namesFrom: 1 },
15
+ { what: "day of the week", min: 0, max: 7, names: WEEKDAYS, namesFrom: 0 },
16
+ ];
17
+ class CronError extends Error {
18
+ }
19
+ const UNSIGNED = /^\+?\d+$/;
20
+ function value(s, spec) {
21
+ const i = spec.names.indexOf(s.toLowerCase());
22
+ if (i >= 0)
23
+ return spec.namesFrom + i;
24
+ if (!UNSIGNED.test(s))
25
+ throw new CronError(`${JSON.stringify(s)} is not a ${spec.what}`);
26
+ const n = Number(s);
27
+ if (n < spec.min || n > spec.max)
28
+ throw new CronError(`${n} is out of ${spec.min}..=${spec.max} for the ${spec.what}`);
29
+ return n;
30
+ }
31
+ function itemSet(item, spec) {
32
+ let range = item;
33
+ let step;
34
+ const slash = item.indexOf("/");
35
+ if (slash >= 0) {
36
+ range = item.slice(0, slash);
37
+ const st = item.slice(slash + 1);
38
+ if (!UNSIGNED.test(st) || !Number.isSafeInteger(Number(st)))
39
+ throw new CronError(`${JSON.stringify(st)} is not a step`);
40
+ step = Number(st);
41
+ if (step === 0)
42
+ throw new CronError("a step of 0");
43
+ }
44
+ let lo;
45
+ let hi;
46
+ const dash = range.indexOf("-");
47
+ if (range === "*") {
48
+ [lo, hi] = [spec.min, spec.max];
49
+ }
50
+ else if (dash >= 0) {
51
+ [lo, hi] = [value(range.slice(0, dash), spec), value(range.slice(dash + 1), spec)];
52
+ if (lo > hi)
53
+ throw new CronError(`the range ${JSON.stringify(range)} runs backwards`);
54
+ }
55
+ else {
56
+ lo = value(range, spec);
57
+ // `a/n` runs from `a` to the field's end
58
+ hi = step !== undefined ? spec.max : lo;
59
+ }
60
+ const out = new Set();
61
+ for (let v = lo; v <= hi; v += step ?? 1)
62
+ out.add(v);
63
+ return out;
64
+ }
65
+ function fieldSet(s, spec) {
66
+ if (s === "")
67
+ throw new CronError(`the ${spec.what} field is empty`);
68
+ const out = new Set();
69
+ for (const item of s.split(",")) {
70
+ try {
71
+ for (const v of itemSet(item, spec))
72
+ out.add(v);
73
+ }
74
+ catch (e) {
75
+ throw new CronError(`${e.message} in the ${spec.what} field (${JSON.stringify(s)})`);
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ /** The most days a month has (29 for February). */
81
+ function maxDay(month) {
82
+ return month === 2 ? 29 : [4, 6, 9, 11].includes(month) ? 30 : 31;
83
+ }
84
+ /** @internal What is wrong with a cron expression, in words; `undefined` when it parses. */
85
+ export function cronError(s) {
86
+ const parts = s.split(/\s+/).filter(Boolean);
87
+ if (parts.length !== 5) {
88
+ return `a cron has 5 fields (minute hour day-of-month month day-of-week), this one has ${parts.length}`;
89
+ }
90
+ try {
91
+ const sets = parts.map((p, i) => fieldSet(p, SPECS[i]));
92
+ const [, , days, months] = sets;
93
+ // a day of the month alone that no chosen month has (`0 0 30 2 *`) never fires
94
+ if (parts[4].startsWith("*") || parts[2].startsWith("*")) {
95
+ let possible = false;
96
+ for (let m = 1; m <= 12 && !possible; m++) {
97
+ if (!months.has(m))
98
+ continue;
99
+ for (let d = 1; d <= maxDay(m); d++)
100
+ if (days.has(d))
101
+ possible = true;
102
+ }
103
+ if (!possible)
104
+ return "no chosen month has the chosen day of the month";
105
+ }
106
+ return undefined;
107
+ }
108
+ catch (e) {
109
+ if (e instanceof CronError)
110
+ return e.message;
111
+ throw e;
112
+ }
113
+ }