@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/query.js ADDED
@@ -0,0 +1,794 @@
1
+ // Typed reads across entities (`ctx.query(entity)`): joins, filters, groups and aggregates over the plugin's own
2
+ // entities, its dependencies' exported entities and the workspace directory, typed end to end. The SDK sends a tree of
3
+ // entities and columns by their names, operators and values (`celobus.v1.Query`), never SQL; the platform checks it
4
+ // against the installed descriptors and reads it as the caller, every entity under its own rules.
5
+ //
6
+ // import { label, sum } from '@celobus/sdk/query';
7
+ // const top = await ctx.query(orderLine)
8
+ // .join(order, orderLine.f.orderId)
9
+ // .leftJoin(customers.customer, order.f.customerId)
10
+ // .where(order.f.status.eq('paid'))
11
+ // .groupBy(customers.customer.f.id)
12
+ // .select({ customer: customers.customer.f.name, revenue: sum(orderLine.f.lineTotal) })
13
+ // .orderBy({ revenue: 'desc' })
14
+ // .limit(20)
15
+ // .all(); // { customer: string | undefined; revenue: Decimal }[]
16
+ import { decodeFieldValue, decodeMessage, encodeFieldValue } from "./codec.js";
17
+ import { Decimal } from "./decimal.js";
18
+ import { ReadRepository } from "./db.js";
19
+ import { RpcError, internal } from "./errors.js";
20
+ import { ColCmp, EntityDef, FieldRef, Order, PlatformEntity, entityNames, foreignPlugin, } from "./schema.js";
21
+ /** The name of an entity in a query: `order`, `crm.customer`, `platform.user`. */
22
+ export function canonicalOf(e) {
23
+ if (e instanceof PlatformEntity)
24
+ return e.ref;
25
+ if (e instanceof EntityDef) {
26
+ const provider = foreignPlugin(e);
27
+ if (provider)
28
+ return `${provider}.${e.options.name}`;
29
+ const name = entityNames.get(e) ?? e.options.name;
30
+ if (!name)
31
+ throw internal(new Error("ctx.query(): the entity is not in plugin({ entities })"));
32
+ return name;
33
+ }
34
+ throw internal(new Error("ctx.query(): not an entity"));
35
+ }
36
+ /** The alias of an entity unless it is given one: its name with `_` for `.` (`crm_customer`). */
37
+ export function defaultAlias(e) {
38
+ return canonicalOf(e).replace(".", "_");
39
+ }
40
+ /** A filter parameter (`DbValue`), as the repository sends it. */
41
+ function dbValue(v) {
42
+ if (typeof v === "boolean")
43
+ return { boolValue: v };
44
+ if (typeof v === "number")
45
+ return Number.isInteger(v) ? { intValue: String(v) } : { doubleValue: v };
46
+ if (typeof v === "string")
47
+ return { stringValue: v };
48
+ return { stringValue: JSON.stringify(v) };
49
+ }
50
+ function wireColumn(c) {
51
+ if (c instanceof FieldRef) {
52
+ if (!c.owner)
53
+ throw internal(new Error(`query: the column ${c.name} is not an entity's`));
54
+ return { source: defaultAlias(c.owner), field: c.name };
55
+ }
56
+ return c.queryColumn();
57
+ }
58
+ function fromFilter(alias, f) {
59
+ if ("and" in f)
60
+ return { and: { items: f.and.items.map((i) => fromFilter(alias, i)) } };
61
+ if ("or" in f)
62
+ return { or: { items: f.or.items.map((i) => fromFilter(alias, i)) } };
63
+ if ("not" in f)
64
+ return { not: fromFilter(alias, f.not) };
65
+ const c = f.condition;
66
+ return { compare: { left: { column: { source: alias, field: c.field } }, op: c.op, values: c.values } };
67
+ }
68
+ // --- conditions ---------------------------------------------------------------------------------------------------
69
+ /** A condition of a query beyond one entity's filter: `exists`, a column against a column, an aggregate's comparison,
70
+ * and the `and`, `or`, `not` of conditions of any entities. */
71
+ export class QCond {
72
+ expr;
73
+ constructor(/** @internal */ expr) {
74
+ this.expr = expr;
75
+ }
76
+ }
77
+ /** @internal */
78
+ export function exprOf(c) {
79
+ if (c instanceof QCond)
80
+ return c.expr;
81
+ if (c instanceof ColCmp) {
82
+ return { compare: { left: { column: wireColumn(c.left) }, op: c.op, right: { column: wireColumn(c.right) } } };
83
+ }
84
+ if (c.node === undefined)
85
+ return undefined;
86
+ if (!c.source)
87
+ throw internal(new Error("query: a filter that is not of an entity's field handles"));
88
+ return fromFilter(defaultAlias(c.source), c.node);
89
+ }
90
+ /** All of the conditions (of any entities). */
91
+ export function and(...conds) {
92
+ const items = conds.map(exprOf).filter((e) => e !== undefined);
93
+ if (items.length === 0)
94
+ return new QCond(undefined);
95
+ return new QCond(items.length === 1 ? items[0] : { and: { items } });
96
+ }
97
+ /** Any of the conditions. */
98
+ export function or(...conds) {
99
+ const items = conds.map(exprOf);
100
+ if (items.some((e) => e === undefined))
101
+ return new QCond(undefined);
102
+ return new QCond(items.length === 1 ? items[0] : { or: { items: items } });
103
+ }
104
+ /** Not the condition. */
105
+ export function not(cond) {
106
+ const e = exprOf(cond);
107
+ return new QCond(e === undefined ? { or: { items: [] } } : { not: e });
108
+ }
109
+ /** A row of `entity` (or of an alias) for which the conditions hold exists; they may name the query's entities. */
110
+ export function exists(entity, ...conds) {
111
+ const [name, alias] = entity instanceof Alias ? [canonicalOf(entity.entity), entity.name] : [canonicalOf(entity), defaultAlias(entity)];
112
+ const filter = and(...conds).expr;
113
+ return new QCond({ exists: { source: { entity: name, alias }, ...(filter ? { filter } : {}) } });
114
+ }
115
+ /** No row of `entity` for which the conditions hold exists. */
116
+ export function notExists(entity, ...conds) {
117
+ return not(exists(entity, ...conds));
118
+ }
119
+ // --- aliases ------------------------------------------------------------------------------------------------------
120
+ /** A column of an aliased entity (`manager.f.displayName`): `T` its value, `O` whether it may be null. */
121
+ export class AliasCol {
122
+ alias;
123
+ name;
124
+ field;
125
+ constructor(
126
+ /** @internal */ alias,
127
+ /** @internal */ name,
128
+ /** @internal */ field) {
129
+ this.alias = alias;
130
+ this.name = name;
131
+ this.field = field;
132
+ }
133
+ /** @internal */
134
+ queryColumn = () => ({ source: this.alias, field: this.name });
135
+ compare(op, values) {
136
+ const inner = this.field.spec.kind === "array" ? this.field.spec.inner : this.field;
137
+ const encoded = values.map((v) => dbValue(encodeFieldValue(inner, v, this.name)));
138
+ return new QCond({ compare: { left: { column: this.queryColumn() }, op, values: encoded } });
139
+ }
140
+ eq(v) {
141
+ return this.compare("EQ", [v]);
142
+ }
143
+ ne(v) {
144
+ return this.compare("NE", [v]);
145
+ }
146
+ lt(v) {
147
+ return this.compare("LT", [v]);
148
+ }
149
+ le(v) {
150
+ return this.compare("LE", [v]);
151
+ }
152
+ gt(v) {
153
+ return this.compare("GT", [v]);
154
+ }
155
+ ge(v) {
156
+ return this.compare("GE", [v]);
157
+ }
158
+ in(values) {
159
+ return this.compare("IN", values);
160
+ }
161
+ isNull() {
162
+ return this.compare("IS_NULL", []);
163
+ }
164
+ isNotNull() {
165
+ return this.compare("IS_NOT_NULL", []);
166
+ }
167
+ eqCol(other) {
168
+ return new ColCmp(this, "EQ", other);
169
+ }
170
+ asc() {
171
+ return new QOrder({ term: { column: this.queryColumn() }, desc: false });
172
+ }
173
+ desc() {
174
+ return new QOrder({ term: { column: this.queryColumn() }, desc: true });
175
+ }
176
+ }
177
+ /** An entity under a name of its own, for an entity joined twice: `alias(platform.user, 'manager')` (inner) or
178
+ * `.left()`; join it with `joinAs`, name its columns with `f`. */
179
+ export class Alias {
180
+ entity;
181
+ name;
182
+ isLeft;
183
+ /** The alias's columns (`manager.f.displayName`). */
184
+ f;
185
+ constructor(
186
+ /** @internal */ entity, name,
187
+ /** @internal */ isLeft) {
188
+ this.entity = entity;
189
+ this.name = name;
190
+ this.isLeft = isLeft;
191
+ const out = {};
192
+ for (const [key, ref] of Object.entries(entity.f)) {
193
+ out[key] = new AliasCol(name, ref.name, ref.field);
194
+ }
195
+ this.f = out;
196
+ }
197
+ /** The alias joined left: its columns may be null. */
198
+ left() {
199
+ return new Alias(this.entity, this.name, true);
200
+ }
201
+ }
202
+ /** An alias of an entity (`[a-z][a-z0-9_]*`). */
203
+ export function alias(entity, name) {
204
+ return new Alias(entity, name, false);
205
+ }
206
+ // --- aggregates, labels, orders -----------------------------------------------------------------------------------
207
+ /** An order of a query: a field handle's (`order.f.total.desc()`), an alias column's, an aggregate's. */
208
+ export class QOrder {
209
+ wire;
210
+ constructor(/** @internal */ wire) {
211
+ this.wire = wire;
212
+ }
213
+ }
214
+ /** An aggregate whose value is an `O`: selected, ordered by, or compared in `having`. */
215
+ export class Agg {
216
+ wire;
217
+ read;
218
+ constructor(
219
+ /** @internal */ wire,
220
+ /** @internal */ read) {
221
+ this.wire = wire;
222
+ this.read = read;
223
+ }
224
+ compare(op, v) {
225
+ // an aggregate's value is compared as the text of its number (an int64, a decimal, a double), as the other SDKs do
226
+ return new QCond({ compare: { left: { aggregate: this.wire }, op, values: [{ stringValue: String(v) }] } });
227
+ }
228
+ eq(v) {
229
+ return this.compare("EQ", v);
230
+ }
231
+ ne(v) {
232
+ return this.compare("NE", v);
233
+ }
234
+ lt(v) {
235
+ return this.compare("LT", v);
236
+ }
237
+ le(v) {
238
+ return this.compare("LE", v);
239
+ }
240
+ gt(v) {
241
+ return this.compare("GT", v);
242
+ }
243
+ ge(v) {
244
+ return this.compare("GE", v);
245
+ }
246
+ asc() {
247
+ return new QOrder({ term: { aggregate: this.wire }, desc: false });
248
+ }
249
+ desc() {
250
+ return new QOrder({ term: { aggregate: this.wire }, desc: true });
251
+ }
252
+ }
253
+ function columnField(c) {
254
+ return c.field;
255
+ }
256
+ /** The rows (of a group). */
257
+ export function count() {
258
+ return new Agg({ fn: "COUNT" }, (v) => Number(v ?? 0));
259
+ }
260
+ /** The distinct values of a column (nulls not counted). */
261
+ export function countDistinct(c) {
262
+ return new Agg({ fn: "COUNT_DISTINCT", column: wireColumn(c) }, (v) => Number(v ?? 0));
263
+ }
264
+ function number(field, v) {
265
+ switch (field.spec.scalar) {
266
+ case "decimal":
267
+ return Decimal.parse(String(v));
268
+ case "double":
269
+ return Number(v);
270
+ default:
271
+ return BigInt(String(v));
272
+ }
273
+ }
274
+ /** The sum of a number column: int32 and int64 sum to a bigint, a decimal to a `Decimal`, a double to a number (0
275
+ * when there is none). */
276
+ export function sum(c) {
277
+ const f = columnField(c);
278
+ return new Agg({ fn: "SUM", column: wireColumn(c) }, (v) => number(f, v ?? "0"));
279
+ }
280
+ /** The average of a number column: a `Decimal` of integers and decimals, a number of doubles (`undefined` when every
281
+ * value is null). */
282
+ export function avg(c) {
283
+ const f = columnField(c);
284
+ return new Agg({ fn: "AVG", column: wireColumn(c) }, (v) => {
285
+ if (v === null || v === undefined)
286
+ return undefined;
287
+ return (f.spec.scalar === "double" ? Number(v) : Decimal.parse(String(v)));
288
+ });
289
+ }
290
+ function extreme(fn, c) {
291
+ const f = columnField(c);
292
+ return new Agg({ fn, column: wireColumn(c) }, (v) => readValue(f, v));
293
+ }
294
+ /** The smallest value of a column (`undefined` when there is none). */
295
+ export function min(c) {
296
+ return extreme("MIN", c);
297
+ }
298
+ /** The largest value of a column (`undefined` when there is none). */
299
+ export function max(c) {
300
+ return extreme("MAX", c);
301
+ }
302
+ /** A `label(..)` select item. */
303
+ export class LabelItem {
304
+ column;
305
+ constructor(/** @internal */ column) {
306
+ this.column = column;
307
+ }
308
+ }
309
+ /** The label of the row a ref names (or of the row of an `id`): for every reader of that row, a guest included;
310
+ * `undefined` when the ref is empty or names a row the caller may not read. */
311
+ export function label(ref) {
312
+ return new LabelItem(wireColumn(ref));
313
+ }
314
+ function readValue(field, raw) {
315
+ if (raw === null || raw === undefined)
316
+ return undefined;
317
+ const errors = {};
318
+ let value;
319
+ if (field.spec.kind === "array") {
320
+ value = Array.isArray(raw) ? raw.map((x, i) => decodeFieldValue(field.spec.inner, x, `[${i}]`, errors)) : undefined;
321
+ }
322
+ else {
323
+ value = decodeFieldValue(field, raw, "value", errors);
324
+ }
325
+ if (Object.keys(errors).length > 0)
326
+ throw internal(new Error(`the platform sent a value this plugin cannot read: ${JSON.stringify(errors)}`));
327
+ return value;
328
+ }
329
+ /** What the select items are on the wire, and how a row's values are read. */
330
+ function selection(items) {
331
+ const keys = Object.keys(items);
332
+ const wire = [];
333
+ const reads = [];
334
+ const terms = new Map();
335
+ for (const k of keys) {
336
+ const item = items[k];
337
+ if (item instanceof FieldRef || item instanceof AliasCol) {
338
+ const column = wireColumn(item);
339
+ wire.push({ column });
340
+ terms.set(k, { column });
341
+ reads.push((v) => readValue(item.field, v));
342
+ }
343
+ else if (item instanceof Agg) {
344
+ wire.push({ aggregate: item.wire });
345
+ terms.set(k, { aggregate: item.wire });
346
+ reads.push((v) => item.read(v));
347
+ }
348
+ else if (item instanceof LabelItem) {
349
+ wire.push({ label: item.column });
350
+ reads.push((v) => {
351
+ if (v === null || typeof v !== "object")
352
+ return undefined;
353
+ const o = v;
354
+ const out = { id: String(o.id ?? ""), text: String(o.text ?? "") };
355
+ if (typeof o.avatarUrl === "string")
356
+ out.avatarUrl = o.avatarUrl;
357
+ return out;
358
+ });
359
+ }
360
+ else {
361
+ throw internal(new Error(`query: select ${k} is not a column, an aggregate or a label`));
362
+ }
363
+ }
364
+ const read = (row) => {
365
+ const out = {};
366
+ keys.forEach((k, i) => {
367
+ out[k] = reads[i](row[i]);
368
+ });
369
+ return out;
370
+ };
371
+ return { wire, read, terms };
372
+ }
373
+ /** Where the query was composed: the first frame of the stack outside the SDK (`src/report.ts:52`). */
374
+ function callerSource() {
375
+ const sdk = new URL(".", import.meta.url).pathname;
376
+ const lines = (new Error().stack ?? "").split("\n").slice(1);
377
+ for (const line of lines) {
378
+ const m = /\(?((?:file:\/\/)?[^()\s]+):(\d+):\d+\)?\s*$/.exec(line.trim());
379
+ if (!m)
380
+ continue;
381
+ const file = m[1].replace(/^file:\/\//, "");
382
+ if (file.startsWith(sdk) || file.startsWith("node:"))
383
+ continue;
384
+ return `${file}:${m[2]}`;
385
+ }
386
+ return "";
387
+ }
388
+ class Sender {
389
+ link;
390
+ tree;
391
+ error;
392
+ source;
393
+ constructor(link, tree, error, source) {
394
+ this.link = link;
395
+ this.tree = tree;
396
+ this.error = error;
397
+ this.source = source;
398
+ }
399
+ async send(mode, token) {
400
+ if (this.error)
401
+ throw new RpcError(500, "query_invalid", this.error);
402
+ const query = { sources: this.tree.sources, groupBy: this.tree.groupBy, select: this.tree.select, order: this.tree.order, limit: this.tree.limit };
403
+ if (this.tree.filter)
404
+ query.filter = this.tree.filter;
405
+ if (this.tree.having)
406
+ query.having = this.tree.having;
407
+ return this.link.syscall({
408
+ query: {
409
+ requestId: this.link.requestId,
410
+ tx: this.link.tx,
411
+ query,
412
+ mode,
413
+ pageToken: token ?? "",
414
+ asSystem: this.link.asSystem,
415
+ source: this.source,
416
+ },
417
+ });
418
+ }
419
+ async rows(mode, token) {
420
+ const r = await this.send(mode, token);
421
+ if (!r.dbRows)
422
+ throw internal(new Error("the platform answered a query with something else"));
423
+ const rows = (r.dbRows.rows ?? []).map((b) => {
424
+ try {
425
+ return JSON.parse(Buffer.from(b).toString("utf8"));
426
+ }
427
+ catch (e) {
428
+ throw internal(e);
429
+ }
430
+ });
431
+ const next = r.dbRows.nextPageToken || undefined;
432
+ return next ? { rows, next } : { rows };
433
+ }
434
+ async count() {
435
+ const r = await this.send("COUNT");
436
+ if (!r.dbCount)
437
+ throw internal(new Error("the platform answered a count with something else"));
438
+ return Number(r.dbCount.count);
439
+ }
440
+ }
441
+ /**
442
+ * A query over the root `Root`, the entities `J` (joined inner, the root among them) and `L` (joined left). Joins,
443
+ * `where`, `groupBy`, `having`, `orderBy` and `limit` build it; `select` names its rows' values; `all`, `first`,
444
+ * `count` and `page` read it. A dependency's entity keeps the repository's reads too (`get`, `find`, `exists`,
445
+ * `aggregate`).
446
+ */
447
+ export class Query {
448
+ link;
449
+ root;
450
+ source;
451
+ repo;
452
+ /** @internal */ tree;
453
+ /** @internal */ error;
454
+ constructor(
455
+ /** @internal */ link,
456
+ /** @internal */ root,
457
+ /** @internal */ source,
458
+ /** @internal the repository of an entity root (its reads) */
459
+ repo) {
460
+ this.link = link;
461
+ this.root = root;
462
+ this.source = source;
463
+ this.repo = repo;
464
+ this.tree = { sources: [{ entity: canonicalOf(root), alias: defaultAlias(root) }], groupBy: [], select: [], order: [], limit: 0 };
465
+ }
466
+ fail(message) {
467
+ this.error ??= message;
468
+ }
469
+ /** The alias of the one source of `entity` (its default alias first). */
470
+ sourceOf(entity) {
471
+ const all = this.tree.sources.filter((s) => s.entity === entity);
472
+ const def = all.find((s) => s.alias === entity.replace(".", "_"));
473
+ if (def)
474
+ return String(def.alias);
475
+ return all.length === 1 ? String(all[0].alias) : undefined;
476
+ }
477
+ addJoin(entity, alias, left, ref) {
478
+ let name;
479
+ let owner;
480
+ let target;
481
+ try {
482
+ name = canonicalOf(entity);
483
+ if (!ref.owner)
484
+ throw new Error("the ref is not an entity's field");
485
+ owner = canonicalOf(ref.owner);
486
+ target = refTarget(ref);
487
+ }
488
+ catch (e) {
489
+ this.fail(`join: ${e.message}`);
490
+ return;
491
+ }
492
+ let l;
493
+ let r;
494
+ const from = this.sourceOf(owner);
495
+ if (target === name && from !== undefined) {
496
+ l = { source: from, field: ref.name };
497
+ r = { source: alias, field: "id" };
498
+ }
499
+ else if (owner === name) {
500
+ const to = this.sourceOf(target);
501
+ if (to === undefined) {
502
+ this.fail(`join of ${name}: the query has no ${target} (or more than one: join with joinOn)`);
503
+ return;
504
+ }
505
+ l = { source: to, field: "id" };
506
+ r = { source: alias, field: ref.name };
507
+ }
508
+ else {
509
+ this.fail(`join of ${name}: the query has no ${owner} (or more than one: join with joinOn)`);
510
+ return;
511
+ }
512
+ this.tree.sources.push({ entity: name, alias, join: left ? "LEFT" : "INNER", left: l, right: r });
513
+ }
514
+ addJoinOn(entity, alias, left, on) {
515
+ if (on.op !== "EQ")
516
+ return this.fail(`joinOn of ${alias}: the columns are compared with eqCol`);
517
+ const a = wireColumn(on.left);
518
+ const b = wireColumn(on.right);
519
+ const [l, r] = b.source === alias ? [a, b] : a.source === alias ? [b, a] : [undefined, undefined];
520
+ if (!l || !r)
521
+ return this.fail(`joinOn of ${alias}: neither column is one of ${alias}`);
522
+ this.tree.sources.push({ entity: canonicalOf(entity), alias, join: left ? "LEFT" : "INNER", left: l, right: r });
523
+ }
524
+ /** Joins `entity` along a ref between it and an entity of the query, either way. */
525
+ join(entity, ref) {
526
+ this.addJoin(entity, defaultAlias(entity), false, ref);
527
+ return this;
528
+ }
529
+ /** As `join`, keeping the rows that have no `entity` (or none the caller may read): its columns may be undefined. */
530
+ leftJoin(entity, ref) {
531
+ this.addJoin(entity, defaultAlias(entity), true, ref);
532
+ return this;
533
+ }
534
+ /** Joins `entity` on two columns of one entity's keys (`a.eqCol(b)`): one of `entity`, one of the query. */
535
+ joinOn(entity, on) {
536
+ this.addJoinOn(entity, defaultAlias(entity), false, on);
537
+ return this;
538
+ }
539
+ leftJoinOn(entity, on) {
540
+ this.addJoinOn(entity, defaultAlias(entity), true, on);
541
+ return this;
542
+ }
543
+ /** Joins an aliased entity (inner or left as the alias was made); its columns are the alias's (`a.f`). */
544
+ joinAs(a, ref) {
545
+ this.addJoin(a.entity, a.name, a.isLeft, ref);
546
+ return this;
547
+ }
548
+ joinOnAs(a, on) {
549
+ this.addJoinOn(a.entity, a.name, a.isLeft, on);
550
+ return this;
551
+ }
552
+ /** Keeps the rows for which every condition holds (several `where`s: all of them). */
553
+ where(...conds) {
554
+ this.tree.filter = combine(this.tree.filter, conds);
555
+ return this;
556
+ }
557
+ /** Groups the rows by these columns. */
558
+ groupBy(...columns) {
559
+ for (const c of columns)
560
+ this.tree.groupBy.push(wireColumn(c));
561
+ return this;
562
+ }
563
+ /** Keeps the groups for which every condition holds (aggregates and grouped columns). */
564
+ having(...conds) {
565
+ this.tree.having = combine(this.tree.having, conds);
566
+ return this;
567
+ }
568
+ /** Orders the rows (then by their keys). */
569
+ orderBy(...orders) {
570
+ for (const o of orders)
571
+ this.tree.order.push(orderWire(o));
572
+ return this;
573
+ }
574
+ /** At most `n` rows (a page: at most 100). */
575
+ limit(n) {
576
+ this.tree.limit = n;
577
+ return this;
578
+ }
579
+ /** The values of the rows, by name: columns, aggregates, labels. */
580
+ select(items) {
581
+ try {
582
+ const s = selection(items);
583
+ this.tree.select = s.wire;
584
+ return new Selected(this.sender(), s.read, s.terms);
585
+ }
586
+ catch (e) {
587
+ this.fail(e.message);
588
+ return new Selected(this.sender(), () => ({}), new Map());
589
+ }
590
+ }
591
+ /** @internal */
592
+ sender() {
593
+ return new Sender(this.link, this.tree, this.error, this.source);
594
+ }
595
+ plain() {
596
+ const t = this.tree;
597
+ return (this.repo !== undefined &&
598
+ !this.error &&
599
+ t.sources.length === 1 &&
600
+ !t.filter &&
601
+ t.groupBy.length === 0 &&
602
+ !t.having &&
603
+ t.order.length === 0 &&
604
+ t.limit === 0);
605
+ }
606
+ /** The root's rows (at most 1,000: `query_rows_limit` past them). */
607
+ async all() {
608
+ if (this.plain())
609
+ return (await this.repo.all());
610
+ const { rows } = await this.sender().rows("ALL");
611
+ return rows.map((r) => this.decodeRoot(r));
612
+ }
613
+ /** The root's first row. */
614
+ async first() {
615
+ const { rows } = await this.sender().rows("FIRST");
616
+ return rows[0] === undefined ? undefined : this.decodeRoot(rows[0]);
617
+ }
618
+ /** A page of the root's rows (`limit`, at most 100) after the token of the previous page. */
619
+ async page(token) {
620
+ const { rows, next } = await this.sender().rows("PAGE", token);
621
+ const out = { rows: rows.map((r) => this.decodeRoot(r)) };
622
+ if (next)
623
+ out.next = next;
624
+ return out;
625
+ }
626
+ /** How many rows (or groups) the query has; with a filter of the root, those it matches. */
627
+ async count(filter) {
628
+ if (this.plain())
629
+ return this.repo.count(filter);
630
+ if (!filter)
631
+ return this.sender().count();
632
+ // the filter counts these rows only: the query itself is not changed
633
+ const tree = { ...this.tree, filter: combine(this.tree.filter, [filter]) };
634
+ return new Sender(this.link, tree, this.error, this.source).count();
635
+ }
636
+ decodeRoot(raw) {
637
+ if (!(this.root instanceof EntityDef))
638
+ throw internal(new Error("query: a directory entity's rows are read with select"));
639
+ const json = raw;
640
+ const errors = {};
641
+ const row = decodeMessage(this.root, json, "", errors);
642
+ if (Object.keys(errors).length > 0)
643
+ throw internal(new Error(`the platform sent a row this plugin cannot read: ${JSON.stringify(errors)}`));
644
+ row.createdAt = new Date(String(json.createdAt));
645
+ row.updatedAt = new Date(String(json.updatedAt));
646
+ if (typeof json.deletedAt === "string")
647
+ row.deletedAt = new Date(json.deletedAt);
648
+ if (json.version !== undefined && json.version !== null)
649
+ row.version = BigInt(String(json.version));
650
+ return row;
651
+ }
652
+ repository() {
653
+ if (!this.repo)
654
+ throw internal(new Error("query: the directory has no repository reads"));
655
+ return this.repo;
656
+ }
657
+ /** A row by id (the repository's read). */
658
+ get(id, options = {}) {
659
+ return this.repository().get(id, options);
660
+ }
661
+ /** The rows matching `filter` (the repository's read): order, limit and page it. */
662
+ find(filter) {
663
+ return this.repository().find(filter);
664
+ }
665
+ async exists(filter) {
666
+ return this.repository().exists(filter);
667
+ }
668
+ /** Groups of the rows (the repository's `aggregate`). */
669
+ get aggregate() {
670
+ const repo = this.repository();
671
+ return repo.aggregate.bind(repo);
672
+ }
673
+ }
674
+ /** A query whose rows are `T` (`select`): `orderBy` (by a select item's name too) and `limit` still apply. */
675
+ export class Selected {
676
+ q;
677
+ read;
678
+ terms;
679
+ constructor(
680
+ /** @internal */ q,
681
+ /** @internal */ read,
682
+ /** @internal */ terms) {
683
+ this.q = q;
684
+ this.read = read;
685
+ this.terms = terms;
686
+ }
687
+ /** Orders the rows: by a select item (`{ revenue: 'desc' }`), a column or an aggregate; then by the keys. */
688
+ orderBy(...orders) {
689
+ for (const o of orders) {
690
+ if (o instanceof QOrder || o instanceof Order) {
691
+ this.q.tree.order.push(orderWire(o));
692
+ continue;
693
+ }
694
+ for (const [k, dir] of Object.entries(o)) {
695
+ const term = this.terms.get(k);
696
+ if (!term)
697
+ throw internal(new Error(`query: orderBy ${k}: not a column or an aggregate of the select`));
698
+ this.q.tree.order.push({ term, desc: dir === "desc" });
699
+ }
700
+ }
701
+ return this;
702
+ }
703
+ /** At most `n` rows (a page: at most 100). */
704
+ limit(n) {
705
+ this.q.tree.limit = n;
706
+ return this;
707
+ }
708
+ decode(rows) {
709
+ return rows.map((r) => {
710
+ if (!Array.isArray(r))
711
+ throw internal(new Error("the platform sent a query row that is not a list"));
712
+ return this.read(r);
713
+ });
714
+ }
715
+ /** Every row (at most 1,000, or `limit`: `query_rows_limit` past them). */
716
+ async all() {
717
+ return this.decode((await this.q.rows("ALL")).rows);
718
+ }
719
+ async first() {
720
+ return this.decode((await this.q.rows("FIRST")).rows)[0];
721
+ }
722
+ /** A page (`limit`, at most 100) after the token of the previous page: keyset over the order and the keys. */
723
+ async page(token) {
724
+ const { rows, next } = await this.q.rows("PAGE", token);
725
+ const out = { rows: this.decode(rows) };
726
+ if (next)
727
+ out.next = next;
728
+ return out;
729
+ }
730
+ /** How many rows (or groups). */
731
+ async count() {
732
+ return this.q.count();
733
+ }
734
+ /** The query tree the SDK sends (`celobus.v1.Query`), in the protobuf JSON mapping. */
735
+ tree() {
736
+ const t = this.q.tree;
737
+ const out = { sources: t.sources };
738
+ if (t.filter)
739
+ out.filter = t.filter;
740
+ if (t.groupBy.length)
741
+ out.groupBy = t.groupBy;
742
+ if (t.having)
743
+ out.having = t.having;
744
+ if (t.select.length)
745
+ out.select = t.select;
746
+ if (t.order.length)
747
+ out.order = t.order;
748
+ if (t.limit)
749
+ out.limit = t.limit;
750
+ return out;
751
+ }
752
+ }
753
+ function combine(prev, conds) {
754
+ const next = and(...conds).expr;
755
+ if (!prev)
756
+ return next;
757
+ if (!next)
758
+ return prev;
759
+ return { and: { items: [prev, next] } };
760
+ }
761
+ function orderWire(o) {
762
+ if (o instanceof QOrder)
763
+ return o.wire;
764
+ if (!o.source)
765
+ throw internal(new Error(`query: the order by ${o.field} is not of an entity's field handle`));
766
+ return { term: { column: { source: defaultAlias(o.source), field: o.field } }, desc: o.desc };
767
+ }
768
+ /** The entity a ref names, by its name in a query. */
769
+ function refTarget(ref) {
770
+ const spec = ref.field.spec;
771
+ if (spec.kind !== "ref" || !spec.ref)
772
+ throw new Error(`${ref.name} is not a ref`);
773
+ const t = spec.ref;
774
+ if (typeof t === "string")
775
+ return t;
776
+ if (t instanceof PlatformEntity || t instanceof EntityDef)
777
+ return canonicalOf(t);
778
+ return canonicalOf(t());
779
+ }
780
+ /** @internal The start of a query (`ctx.query`). */
781
+ export function startQuery(link, entity) {
782
+ let repo;
783
+ if (entity instanceof EntityDef) {
784
+ const provider = foreignPlugin(entity);
785
+ const name = provider ? entity.options.name : (entityNames.get(entity) ?? entity.options.name);
786
+ if (!name)
787
+ throw internal(new Error("ctx.query(): the entity is not in plugin({ entities })"));
788
+ repo = new ReadRepository(link, entity, name, provider ?? "");
789
+ }
790
+ else if (!(entity instanceof PlatformEntity)) {
791
+ throw internal(new Error("ctx.query(): not an entity"));
792
+ }
793
+ return new Query(link, entity, callerSource(), repo);
794
+ }