@tapedb/tapedb 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.
@@ -0,0 +1,841 @@
1
+ import {
2
+ BASELINE_MIGRATION_ID,
3
+ ENGINE_MIGRATIONS,
4
+ WORKSPACE_ROLE_LEVELS,
5
+ assertDecisionShape,
6
+ toSnakeCase
7
+ } from "./chunk-3AL32Q4K.js";
8
+
9
+ // src/model/fields.ts
10
+ var Field = class _Field {
11
+ constructor(kind, isOptional, hasDefault, defaultValue = void 0, isIndexed = false, isUnique = false) {
12
+ this.kind = kind;
13
+ this.isOptional = isOptional;
14
+ this.hasDefault = hasDefault;
15
+ this.defaultValue = defaultValue;
16
+ this.isIndexed = isIndexed;
17
+ this.isUnique = isUnique;
18
+ }
19
+ kind;
20
+ isOptional;
21
+ hasDefault;
22
+ defaultValue;
23
+ isIndexed;
24
+ isUnique;
25
+ tag = "field";
26
+ /** Encrypt this value under the named subject's erasable key. */
27
+ personal(options) {
28
+ if (this.isIndexed || this.isUnique) throw new Error("Personal fields cannot be indexed or unique.");
29
+ if (!options.subject) throw new Error("A personal field needs its subject field, or self.");
30
+ return new PersonalField(this.kind, this.isOptional, this.hasDefault, options.subject, this.defaultValue);
31
+ }
32
+ /** The field may be null, and may be left out of `create`. */
33
+ optional() {
34
+ return new _Field(this.kind, true, this.hasDefault, this.defaultValue, this.isIndexed, this.isUnique);
35
+ }
36
+ /** Filled in by `create` when the field is left out. */
37
+ default(value) {
38
+ return new _Field(this.kind, this.isOptional, true, value, this.isIndexed, this.isUnique);
39
+ }
40
+ /** Adds an index, for filters and sorts on this field. */
41
+ index() {
42
+ return new _Field(this.kind, this.isOptional, this.hasDefault, this.defaultValue, true, this.isUnique);
43
+ }
44
+ /** Adds a unique index. */
45
+ unique() {
46
+ return new _Field(this.kind, this.isOptional, this.hasDefault, this.defaultValue, this.isIndexed, true);
47
+ }
48
+ };
49
+ var PersonalField = class _PersonalField extends Field {
50
+ constructor(kind, optional, hasDefault, personalSubject, defaultValue) {
51
+ super(kind, optional, hasDefault, defaultValue);
52
+ this.personalSubject = personalSubject;
53
+ }
54
+ personalSubject;
55
+ optional() {
56
+ return new _PersonalField(this.kind, true, this.hasDefault, this.personalSubject, this.defaultValue);
57
+ }
58
+ default(value) {
59
+ return new _PersonalField(this.kind, this.isOptional, true, this.personalSubject, value);
60
+ }
61
+ index() {
62
+ throw new Error("Personal fields cannot be indexed.");
63
+ }
64
+ unique() {
65
+ throw new Error("Personal fields cannot be unique.");
66
+ }
67
+ };
68
+ var BelongsTo = class _BelongsTo {
69
+ constructor(target, isOptional, onDelete = "setNull") {
70
+ this.target = target;
71
+ this.isOptional = isOptional;
72
+ this.onDelete = onDelete;
73
+ }
74
+ target;
75
+ isOptional;
76
+ onDelete;
77
+ tag = "belongsTo";
78
+ /** The key may be null: the row can exist without a parent. */
79
+ optional() {
80
+ return new _BelongsTo(this.target, true, this.onDelete);
81
+ }
82
+ };
83
+ var HasMany = class {
84
+ constructor(target, inverse) {
85
+ this.target = target;
86
+ this.inverse = inverse;
87
+ }
88
+ target;
89
+ inverse;
90
+ tag = "hasMany";
91
+ };
92
+ var t = {
93
+ string: () => new Field("string", false, false),
94
+ number: () => new Field("number", false, false),
95
+ boolean: () => new Field("boolean", false, false),
96
+ /** Stored as epoch milliseconds; accepts a `Date`, milliseconds or an ISO string. */
97
+ date: () => new Field("date", false, false),
98
+ /** Any JSON value. Not filterable or sortable. */
99
+ json: () => new Field("json", false, false),
100
+ belongsTo: (target, options = {}) => new BelongsTo(target, false, options.onDelete ?? "setNull"),
101
+ hasMany: (target, options = {}) => new HasMany(target, options.inverse)
102
+ };
103
+
104
+ // src/client/schema.ts
105
+ function createAttribute(type, flags = {}) {
106
+ return {
107
+ type,
108
+ isOptional: flags.optional ?? false,
109
+ isIndexed: flags.indexed ?? false,
110
+ isUnique: flags.unique ?? false,
111
+ optional() {
112
+ return createAttribute(type, { ...flags, optional: true });
113
+ },
114
+ indexed() {
115
+ return createAttribute(type, { ...flags, indexed: true });
116
+ },
117
+ unique() {
118
+ return createAttribute(type, { ...flags, unique: true });
119
+ }
120
+ };
121
+ }
122
+ function entity(attrs) {
123
+ return { type: "entity", attrs };
124
+ }
125
+ function schema(definition) {
126
+ return definition;
127
+ }
128
+ var i = {
129
+ schema,
130
+ entity,
131
+ string: () => createAttribute("string"),
132
+ number: () => createAttribute("number"),
133
+ boolean: () => createAttribute("boolean"),
134
+ date: () => createAttribute("date"),
135
+ json: () => createAttribute("json"),
136
+ any: () => createAttribute("any")
137
+ };
138
+ function findLinkByApiName(definition, apiName) {
139
+ return definition?.links[apiName];
140
+ }
141
+
142
+ // src/schema.ts
143
+ var ENGINE_TABLE_DDL = `
144
+ CREATE TABLE IF NOT EXISTS "_migrations" (
145
+ id TEXT PRIMARY KEY NOT NULL,
146
+ checksum TEXT NOT NULL,
147
+ applied_at INTEGER NOT NULL
148
+ );
149
+
150
+ CREATE TABLE IF NOT EXISTS "_tx_log" (
151
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
152
+ client_tx_id TEXT UNIQUE,
153
+ ops TEXT NOT NULL,
154
+ ops_hash TEXT NOT NULL,
155
+ user_id TEXT,
156
+ role INTEGER,
157
+ at INTEGER NOT NULL,
158
+ schema_version TEXT NOT NULL
159
+ );
160
+
161
+ CREATE TABLE IF NOT EXISTS "_tx_state" (
162
+ id INTEGER PRIMARY KEY CHECK (id = 1),
163
+ high_water_seq INTEGER NOT NULL DEFAULT 0
164
+ );
165
+
166
+ CREATE TABLE IF NOT EXISTS "_flush_state" (
167
+ id INTEGER PRIMARY KEY CHECK (id = 1),
168
+ last_seq INTEGER NOT NULL DEFAULT 0,
169
+ attempts INTEGER NOT NULL DEFAULT 0,
170
+ next_attempt_at INTEGER,
171
+ last_error TEXT,
172
+ last_flush_at INTEGER,
173
+ last_segment_from INTEGER,
174
+ updated_at INTEGER NOT NULL
175
+ );
176
+
177
+ CREATE TABLE IF NOT EXISTS "_snapshot_state" (
178
+ id INTEGER PRIMARY KEY CHECK (id = 1),
179
+ base_seq INTEGER NOT NULL DEFAULT 0,
180
+ status TEXT NOT NULL DEFAULT 'idle',
181
+ started_at INTEGER,
182
+ completed_at INTEGER,
183
+ manifest_key TEXT
184
+ );
185
+
186
+ CREATE TABLE IF NOT EXISTS "_engine_meta" (
187
+ "key" TEXT PRIMARY KEY NOT NULL,
188
+ value TEXT NOT NULL
189
+ );
190
+
191
+ CREATE TABLE IF NOT EXISTS "$files" (
192
+ id TEXT PRIMARY KEY NOT NULL,
193
+ path TEXT NOT NULL UNIQUE,
194
+ r2_key TEXT NOT NULL,
195
+ size INTEGER NOT NULL,
196
+ content_type TEXT,
197
+ created_at INTEGER NOT NULL,
198
+ updated_at INTEGER NOT NULL
199
+ );
200
+
201
+ INSERT OR IGNORE INTO "_tx_state" (id, high_water_seq) VALUES (1, 0);
202
+ INSERT OR IGNORE INTO "_flush_state" (id, last_seq, attempts, updated_at)
203
+ VALUES (1, 0, 0, 0);
204
+ INSERT OR IGNORE INTO "_snapshot_state" (id, base_seq, status)
205
+ VALUES (1, 0, 'idle');
206
+ INSERT OR IGNORE INTO "_engine_meta" ("key", value) VALUES
207
+ ('engine_version', '1'),
208
+ ('schema_version', '0001_baseline');
209
+ `;
210
+ var SQL_TYPE = {
211
+ string: "TEXT",
212
+ json: "TEXT",
213
+ date: "INTEGER",
214
+ any: "TEXT",
215
+ number: "REAL",
216
+ boolean: "INTEGER"
217
+ };
218
+ function sqlLiteral(value) {
219
+ if (value === null) return "NULL";
220
+ if (typeof value === "number") {
221
+ if (!Number.isFinite(value)) throw new Error(`Default ${value} is not a finite number.`);
222
+ return String(value);
223
+ }
224
+ return `'${value.replace(/'/g, "''")}'`;
225
+ }
226
+ function entityDdl(namespace, attributes) {
227
+ const columns = [
228
+ `"id" TEXT PRIMARY KEY NOT NULL`,
229
+ `"created_at" INTEGER NOT NULL`,
230
+ `"updated_at" INTEGER NOT NULL`,
231
+ `"updated_seq" INTEGER NOT NULL DEFAULT 0`
232
+ ];
233
+ for (const [name, attribute] of Object.entries(attributes)) {
234
+ const column = toSnakeCase(name);
235
+ let sql = `"${column}" ${SQL_TYPE[attribute.type] ?? "TEXT"}`;
236
+ if (attribute.default !== void 0) sql += ` DEFAULT ${sqlLiteral(attribute.default)}`;
237
+ if (attribute.references) {
238
+ const onDelete = attribute.references.onDelete ?? "SET NULL";
239
+ sql += ` REFERENCES "${attribute.references.table}"("${attribute.references.column}") ON DELETE ${onDelete}`;
240
+ }
241
+ columns.push(sql);
242
+ }
243
+ const statements = [
244
+ `CREATE TABLE IF NOT EXISTS "${namespace.table}" (
245
+ ${columns.join(",\n ")}
246
+ );`
247
+ ];
248
+ for (const [name, attribute] of Object.entries(attributes)) {
249
+ if (!attribute.indexed && !attribute.unique) continue;
250
+ const column = toSnakeCase(name);
251
+ const unique = attribute.unique ? "UNIQUE " : "";
252
+ statements.push(
253
+ `CREATE ${unique}INDEX IF NOT EXISTS "${namespace.table}_${column}_idx" ON "${namespace.table}" ("${column}");`
254
+ );
255
+ }
256
+ return statements;
257
+ }
258
+ function clientLink(link) {
259
+ return {
260
+ forward: {
261
+ on: link.foreignKey.attribute,
262
+ has: link.forward.has,
263
+ label: link.forward.label
264
+ },
265
+ reverse: {
266
+ on: link.foreignKey.attribute,
267
+ has: link.reverse.has,
268
+ label: link.reverse.label
269
+ }
270
+ };
271
+ }
272
+ function defineSchema(config) {
273
+ for (const [namespace, actions] of Object.entries(config.permissions ?? {})) {
274
+ if (!config.entities[namespace]) {
275
+ throw new Error(
276
+ `Permissions reference unknown namespace "${namespace}".`
277
+ );
278
+ }
279
+ for (const [action, decision] of Object.entries(actions ?? {})) {
280
+ assertDecisionShape(namespace, action, decision);
281
+ }
282
+ }
283
+ const namespaces = Object.entries(config.entities).map(
284
+ ([apiName, attributes]) => ({
285
+ apiName,
286
+ table: config.tables?.[apiName] ?? toSnakeCase(apiName),
287
+ attributes
288
+ })
289
+ );
290
+ const links = config.links ?? [];
291
+ for (const link of links) {
292
+ const owner = namespaces.find(
293
+ (namespace) => namespace.apiName === link.foreignKey.namespace
294
+ );
295
+ if (!owner) {
296
+ throw new Error(
297
+ `Link "${link.apiName}" points at unknown namespace "${link.foreignKey.namespace}".`
298
+ );
299
+ }
300
+ const attribute = owner.attributes[link.foreignKey.attribute];
301
+ if (!attribute) {
302
+ throw new Error(
303
+ `Link "${link.apiName}" needs "${link.foreignKey.namespace}.${link.foreignKey.attribute}", which the schema does not define.`
304
+ );
305
+ }
306
+ const target = link.forward.namespace === owner.apiName ? link.reverse.namespace : link.forward.namespace;
307
+ attribute.references = {
308
+ table: config.tables?.[target] ?? toSnakeCase(target),
309
+ column: "id",
310
+ onDelete: attribute.references?.onDelete ?? "SET NULL"
311
+ };
312
+ }
313
+ const entityStatements = [];
314
+ for (const namespace of namespaces) {
315
+ entityStatements.push(
316
+ ...entityDdl(namespace, config.entities[namespace.apiName] ?? {})
317
+ );
318
+ }
319
+ const migrations = [
320
+ { id: BASELINE_MIGRATION_ID, sql: ENGINE_TABLE_DDL.trim() },
321
+ ...ENGINE_MIGRATIONS,
322
+ {
323
+ id: "0002_entities",
324
+ sql: entityStatements.join("\n\n")
325
+ }
326
+ ];
327
+ const clientEntities = {};
328
+ for (const [apiName, attributes] of Object.entries(config.entities)) {
329
+ const mapped = {};
330
+ for (const [name, attribute] of Object.entries(attributes)) {
331
+ const builder = i[attribute.type] ?? i.any;
332
+ let value = builder();
333
+ const flags = value;
334
+ if (attribute.optional) value = flags.optional();
335
+ if (attribute.indexed) value = value.indexed();
336
+ if (attribute.unique) value = value.unique();
337
+ mapped[name] = value;
338
+ }
339
+ clientEntities[apiName] = i.entity(mapped);
340
+ }
341
+ const clientLinks = {};
342
+ for (const link of links) clientLinks[link.apiName] = clientLink(link);
343
+ return {
344
+ registry: { namespaces, links },
345
+ permissions: { overrides: config.permissions ?? {} },
346
+ migrations,
347
+ clientSchema: i.schema({ entities: clientEntities, links: clientLinks })
348
+ };
349
+ }
350
+
351
+ // src/model/where.ts
352
+ var OPERATORS = {
353
+ in: "$in",
354
+ notIn: "$nin",
355
+ gt: "$gt",
356
+ gte: "$gte",
357
+ lt: "$lt",
358
+ lte: "$lte"
359
+ };
360
+ function scalar(value) {
361
+ return value instanceof Date ? value.getTime() : value;
362
+ }
363
+ function isFilterObject(value) {
364
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
365
+ }
366
+ function asList(value) {
367
+ return Array.isArray(value) ? value : [value];
368
+ }
369
+ function fieldConditions(field, value) {
370
+ if (!isFilterObject(value)) return [{ [field]: scalar(value) }];
371
+ const comparison = {};
372
+ const extra = [];
373
+ for (const [operator, operand] of Object.entries(value)) {
374
+ if (operand === void 0) continue;
375
+ if (operator === "equals") {
376
+ extra.push({ [field]: scalar(operand) });
377
+ } else if (operator === "not") {
378
+ if (isFilterObject(operand)) {
379
+ const inner = fieldConditions(field, operand);
380
+ extra.push({ $not: inner.length === 1 ? inner[0] : { $and: inner } });
381
+ } else {
382
+ comparison.$ne = scalar(operand);
383
+ }
384
+ } else if (operator in OPERATORS) {
385
+ comparison[OPERATORS[operator]] = Array.isArray(operand) ? operand.map(scalar) : scalar(operand);
386
+ } else {
387
+ throw new Error(`Unknown filter "${operator}" on "${field}".`);
388
+ }
389
+ }
390
+ if (Object.keys(comparison).length > 0) extra.push({ [field]: comparison });
391
+ return extra;
392
+ }
393
+ function relationCondition(graph, model2, key, value) {
394
+ const relation = model2.relations[key];
395
+ const target = graph[relation.target];
396
+ if (relation.kind === "belongsTo") {
397
+ if (value === null) return { [relation.foreignKey]: null };
398
+ if (!isFilterObject(value)) {
399
+ throw new Error(`"${model2.key}.${key}" takes a filter object or null.`);
400
+ }
401
+ for (const mode of ["some", "every", "none"]) {
402
+ if (mode in value) {
403
+ throw new Error(
404
+ `"${model2.key}.${key}" is a to-one link: filter it directly, as { ${key}: { ... } }, not with ${mode}.`
405
+ );
406
+ }
407
+ }
408
+ return { $link: [{ label: key, mode: "parent", where: toEngineWhere(target, value, graph) }] };
409
+ }
410
+ if (!isFilterObject(value)) {
411
+ throw new Error(`"${model2.key}.${key}" takes { some }, { every } or { none }.`);
412
+ }
413
+ const entries = Object.entries(value).filter(([, filter2]) => filter2 !== void 0);
414
+ if (entries.length === 0) {
415
+ throw new Error(`"${model2.key}.${key}" needs one of some, every or none.`);
416
+ }
417
+ return {
418
+ $link: entries.map(([mode, filter2]) => {
419
+ if (mode !== "some" && mode !== "every" && mode !== "none") {
420
+ throw new Error(`"${model2.key}.${key}" takes some, every or none, not "${mode}".`);
421
+ }
422
+ if (!isFilterObject(filter2)) {
423
+ throw new Error(`"${model2.key}.${key}.${mode}" takes a filter object.`);
424
+ }
425
+ return { label: key, mode, where: toEngineWhere(target, filter2, graph) };
426
+ })
427
+ };
428
+ }
429
+ function toEngineWhere(model2, where, graph = {}) {
430
+ const conditions = [];
431
+ for (const [key, value] of Object.entries(where)) {
432
+ if (value === void 0) continue;
433
+ if (key === "AND") {
434
+ for (const branch of asList(value)) {
435
+ conditions.push(toEngineWhere(model2, branch, graph));
436
+ }
437
+ } else if (key === "OR") {
438
+ const branches = value;
439
+ if (!Array.isArray(branches) || branches.length === 0) {
440
+ throw new Error(`"OR" on "${model2.key}" needs a non-empty array.`);
441
+ }
442
+ conditions.push({ $or: branches.map((branch) => toEngineWhere(model2, branch, graph)) });
443
+ } else if (key === "NOT") {
444
+ for (const branch of asList(value)) {
445
+ conditions.push({ $not: toEngineWhere(model2, branch, graph) });
446
+ }
447
+ } else if (model2.filterable.has(key)) {
448
+ conditions.push(...fieldConditions(key, value));
449
+ } else if (key in model2.relations) {
450
+ conditions.push(relationCondition(graph, model2, key, value));
451
+ } else {
452
+ throw new Error(`"${model2.key}" has no filterable field "${key}".`);
453
+ }
454
+ }
455
+ const merged = {};
456
+ const rest = [];
457
+ for (const condition of conditions) {
458
+ const [entry] = Object.entries(condition);
459
+ if (entry[0] === "$link" && Object.keys(condition).length === 1) {
460
+ merged.$link = [
461
+ ...merged.$link ?? [],
462
+ ...entry[1]
463
+ ];
464
+ } else if (Object.keys(condition).length === 1 && !(entry[0] in merged) && entry[0] !== "$and") {
465
+ merged[entry[0]] = entry[1];
466
+ } else {
467
+ rest.push(condition);
468
+ }
469
+ }
470
+ if (rest.length > 0) merged.$and = rest;
471
+ return merged;
472
+ }
473
+ function toEngineOrder(model2, orderBy) {
474
+ if (orderBy === void 0) return void 0;
475
+ const order = {};
476
+ for (const entry of asList(orderBy)) {
477
+ for (const [field, direction] of Object.entries(entry)) {
478
+ if (!model2.filterable.has(field)) {
479
+ throw new Error(`"${model2.key}" cannot be ordered by "${field}".`);
480
+ }
481
+ if (direction !== "asc" && direction !== "desc") {
482
+ throw new Error(`Order for "${model2.key}.${field}" must be "asc" or "desc".`);
483
+ }
484
+ order[field] = direction;
485
+ }
486
+ }
487
+ return order;
488
+ }
489
+ function selectable(model2, name) {
490
+ return name === "id" || name === "createdAt" || name === "updatedAt" || name in model2.scalars || model2.filterable.has(name);
491
+ }
492
+ function splitSelect(model2, select) {
493
+ const fields = [];
494
+ const relations = {};
495
+ for (const [name, value] of Object.entries(select)) {
496
+ if (value === void 0 || value === false) continue;
497
+ if (name in model2.relations) {
498
+ relations[name] = value;
499
+ continue;
500
+ }
501
+ if (!selectable(model2, name)) {
502
+ throw new Error(`"${model2.key}" has no field "${name}" to select.`);
503
+ }
504
+ if (value !== true) {
505
+ throw new Error(`"${model2.key}.${name}" in select takes true or false.`);
506
+ }
507
+ fields.push(name);
508
+ }
509
+ return { fields, relations };
510
+ }
511
+ function relationsOf(model2, args, split) {
512
+ const merged = { ...args.include ?? {} };
513
+ for (const [name, value] of Object.entries(split?.relations ?? {})) {
514
+ const other = merged[name];
515
+ if (other === void 0 || other === false || other === true) {
516
+ merged[name] = value === true && typeof other === "object" ? other : value;
517
+ continue;
518
+ }
519
+ if (value === true || value === false || value === void 0) continue;
520
+ const a = other;
521
+ const b = value;
522
+ const combined = { ...a };
523
+ for (const [key, item] of Object.entries(b)) {
524
+ if (item === void 0) continue;
525
+ if (key === "select" || key === "include") {
526
+ combined[key] = { ...a[key] ?? {}, ...item };
527
+ } else if (a[key] !== void 0 && JSON.stringify(a[key]) !== JSON.stringify(item)) {
528
+ throw new Error(`"${model2.key}.${name}" has a different ${key} in select and in include.`);
529
+ } else {
530
+ combined[key] = item;
531
+ }
532
+ }
533
+ merged[name] = combined;
534
+ }
535
+ return merged;
536
+ }
537
+ function toEngineNode(graph, model2, args, extra = {}) {
538
+ const options = { ...extra };
539
+ if (args.where !== void 0) options.where = toEngineWhere(model2, args.where, graph);
540
+ const order = toEngineOrder(model2, args.orderBy);
541
+ if (order !== void 0) options.order = order;
542
+ if (args.take !== void 0) options.limit = args.take;
543
+ if (args.after !== void 0) options.after = args.after;
544
+ const split = args.select === void 0 ? null : splitSelect(model2, args.select);
545
+ if (split !== null) {
546
+ options.select = split.fields.length > 0 ? split.fields : ["id"];
547
+ }
548
+ const relations = relationsOf(model2, args, split);
549
+ const node = { $: options };
550
+ for (const [name, value] of Object.entries(relations)) {
551
+ if (value === void 0 || value === false) continue;
552
+ const relation = model2.relations[name];
553
+ if (!relation) {
554
+ throw new Error(`"${model2.key}" has no relation "${name}" to include.`);
555
+ }
556
+ node[name] = toEngineNode(
557
+ graph,
558
+ graph[relation.target],
559
+ value === true ? {} : value
560
+ );
561
+ }
562
+ return node;
563
+ }
564
+ function shapeFor(graph, model2, args) {
565
+ const split = args.select === void 0 ? null : splitSelect(model2, args.select);
566
+ const relations = relationsOf(model2, args, split);
567
+ const nested = [];
568
+ for (const [name, value] of Object.entries(relations)) {
569
+ if (value === void 0 || value === false) continue;
570
+ const relation = model2.relations[name];
571
+ if (!relation) continue;
572
+ nested.push([
573
+ name,
574
+ value === true ? null : shapeFor(graph, graph[relation.target], value)
575
+ ]);
576
+ }
577
+ if (split === null && nested.every(([, shape]) => shape === null)) return null;
578
+ const fields = split?.fields ?? null;
579
+ return (row) => {
580
+ let output;
581
+ if (fields === null) {
582
+ output = { ...row };
583
+ } else {
584
+ output = {};
585
+ for (const field of fields) if (field in row) output[field] = row[field];
586
+ }
587
+ for (const [name, shape] of nested) {
588
+ const value = row[name];
589
+ if (value === void 0) continue;
590
+ output[name] = shape === null || value === null ? value : Array.isArray(value) ? value.map((child) => shape(child)) : shape(value);
591
+ }
592
+ return output;
593
+ };
594
+ }
595
+
596
+ // src/model/schema.ts
597
+ var ROLE_LEVELS = {
598
+ guest: WORKSPACE_ROLE_LEVELS.GUEST,
599
+ user: WORKSPACE_ROLE_LEVELS.USER,
600
+ member: WORKSPACE_ROLE_LEVELS.MEMBER,
601
+ editor: WORKSPACE_ROLE_LEVELS.EDITOR,
602
+ moderator: WORKSPACE_ROLE_LEVELS.MODERATOR,
603
+ admin: WORKSPACE_ROLE_LEVELS.ADMIN,
604
+ owner: WORKSPACE_ROLE_LEVELS.OWNER
605
+ };
606
+ function role(name) {
607
+ const level = ROLE_LEVELS[name];
608
+ if (level === void 0) throw new Error(`Unknown role "${name}".`);
609
+ return { decision: "role", level };
610
+ }
611
+ function filter(build) {
612
+ return { decision: "filter", build };
613
+ }
614
+ function check(test) {
615
+ return { decision: "check", test };
616
+ }
617
+ function fileCheck(test) {
618
+ return { decision: "check", test };
619
+ }
620
+ function attachedTo(model2, locate) {
621
+ return { decision: "attachedTo", model: model2, locate };
622
+ }
623
+ var Model = class _Model {
624
+ constructor(fields, options = {}, rules = {}) {
625
+ this.fields = fields;
626
+ this.options = options;
627
+ this.rules = rules;
628
+ }
629
+ fields;
630
+ options;
631
+ rules;
632
+ /** Who may read, create, update and delete rows of this model. */
633
+ access(rules) {
634
+ return new _Model(this.fields, this.options, rules);
635
+ }
636
+ };
637
+ function model(fields, options = {}) {
638
+ return new Model(fields, options);
639
+ }
640
+ var DELETE_RULES = {
641
+ setNull: "SET NULL",
642
+ cascade: "CASCADE",
643
+ restrict: "RESTRICT"
644
+ };
645
+ function schema2(models, options = {}) {
646
+ const entities = {};
647
+ const links = [];
648
+ const graph = {};
649
+ const permissions = {};
650
+ for (const [key, definition] of Object.entries(models)) {
651
+ if (!/^[A-Za-z][A-Za-z0-9]*$/.test(key)) {
652
+ throw new Error(`Model name "${key}" must be letters and digits, starting with a letter.`);
653
+ }
654
+ if (!(definition instanceof Model)) {
655
+ throw new Error(`"${key}" is not a model(). Wrap its fields in model({ ... }).`);
656
+ }
657
+ const info = { key, scalars: {}, relations: {}, filterable: /* @__PURE__ */ new Set(["id"]) };
658
+ const attributes = {};
659
+ for (const [name, member] of Object.entries(definition.fields)) {
660
+ if (["id", "createdAt", "updatedAt", "updatedSeq"].includes(name)) {
661
+ throw new Error(`"${key}.${name}" is a system field and cannot be declared.`);
662
+ }
663
+ if (member instanceof Field) {
664
+ const subject = "personalSubject" in member ? String(member.personalSubject) : void 0;
665
+ if (subject && subject !== "self" && !(subject in definition.fields) && !Object.entries(definition.fields).some(([field, value]) => value instanceof BelongsTo && `${field}Id` === subject))
666
+ throw new Error(`Personal field ${key}.${name} refers to missing subject ${subject}.`);
667
+ if (subject && subject !== "self" && subject in definition.fields) {
668
+ const owner = definition.fields[subject];
669
+ if (!(owner instanceof Field) || owner.kind !== "string" || "personalSubject" in owner)
670
+ throw new Error(`Personal field ${key}.${name} requires a non-personal string subject.`);
671
+ }
672
+ attributes[name] = {
673
+ type: member.kind,
674
+ // A field with a default is filled in by create, so the engine never
675
+ // sees it missing; it stays required for writes that bypass create.
676
+ optional: subject ? true : member.isOptional,
677
+ ...subject ? { personal: { subject, required: !member.isOptional, ...member.hasDefault ? { defaultValue: storedDefault(member.kind, member.defaultValue) } : {} } } : {},
678
+ indexed: member.isIndexed || void 0,
679
+ unique: member.isUnique || void 0,
680
+ ...member.hasDefault && !subject ? { default: storedDefault(member.kind, member.defaultValue) } : {}
681
+ };
682
+ info.scalars[name] = {
683
+ kind: member.kind,
684
+ optional: member.isOptional,
685
+ hasDefault: member.hasDefault,
686
+ defaultValue: member.defaultValue
687
+ };
688
+ if (member.kind !== "json" && !subject) info.filterable.add(name);
689
+ } else if (member instanceof BelongsTo) {
690
+ if (!(member.target in models)) {
691
+ throw new Error(`"${key}.${name}" belongs to "${member.target}", which is not a model.`);
692
+ }
693
+ const foreignKey = `${name}Id`;
694
+ if (foreignKey in definition.fields) {
695
+ throw new Error(`"${key}.${foreignKey}" clashes with the key "${key}.${name}" stores.`);
696
+ }
697
+ attributes[foreignKey] = {
698
+ type: "string",
699
+ optional: member.isOptional,
700
+ indexed: true,
701
+ // defineSchema fills in the table; only the delete rule is ours.
702
+ references: { table: "", column: "id", onDelete: DELETE_RULES[member.onDelete] }
703
+ };
704
+ info.relations[name] = {
705
+ kind: "belongsTo",
706
+ target: member.target,
707
+ link: `${key}.${name}`,
708
+ foreignKey,
709
+ optional: member.isOptional
710
+ };
711
+ info.filterable.add(foreignKey);
712
+ } else if (member instanceof HasMany) {
713
+ if (!(member.target in models)) {
714
+ throw new Error(`"${key}.${name}" has many "${member.target}", which is not a model.`);
715
+ }
716
+ info.relations[name] = { kind: "hasMany", target: member.target, link: "" };
717
+ } else {
718
+ throw new Error(`"${key}.${name}" is not a field. Use t.string(), t.belongsTo(), ...`);
719
+ }
720
+ }
721
+ entities[key] = attributes;
722
+ graph[key] = info;
723
+ const overrides = accessOverrides(key, definition.rules, graph);
724
+ if (overrides) permissions[key] = overrides;
725
+ }
726
+ const pairedInverse = /* @__PURE__ */ new Map();
727
+ for (const info of Object.values(graph)) {
728
+ for (const [name, relation] of Object.entries(info.relations)) {
729
+ if (relation.kind !== "hasMany") continue;
730
+ const member = models[info.key].fields[name];
731
+ const candidates = Object.entries(graph[relation.target].relations).filter(
732
+ ([, other]) => other.kind === "belongsTo" && other.target === info.key
733
+ );
734
+ const chosen = member.inverse ? candidates.filter(([field]) => field === member.inverse) : candidates;
735
+ if (chosen.length !== 1) {
736
+ throw new Error(
737
+ chosen.length === 0 ? `"${info.key}.${name}" has no matching belongsTo("${info.key}") on "${relation.target}".` : `"${info.key}.${name}" matches several belongsTo fields on "${relation.target}"; name one with { inverse }.`
738
+ );
739
+ }
740
+ const [inverseField, inverse] = chosen[0];
741
+ if (pairedInverse.has(inverse.link)) {
742
+ throw new Error(`"${inverse.link}" is the inverse of two hasMany fields.`);
743
+ }
744
+ pairedInverse.set(inverse.link, name);
745
+ relation.link = inverse.link;
746
+ relation.foreignKey = `${inverseField}Id`;
747
+ }
748
+ }
749
+ for (const info of Object.values(graph)) {
750
+ for (const [name, relation] of Object.entries(info.relations)) {
751
+ if (relation.kind !== "belongsTo") continue;
752
+ links.push({
753
+ apiName: relation.link,
754
+ kind: "one-to-many",
755
+ forward: {
756
+ namespace: relation.target,
757
+ label: pairedInverse.get(relation.link) ?? `__${info.key}_${name}`,
758
+ has: "many"
759
+ },
760
+ reverse: { namespace: info.key, label: name, has: "one" },
761
+ foreignKey: { namespace: info.key, attribute: relation.foreignKey }
762
+ });
763
+ }
764
+ }
765
+ const tables = {};
766
+ for (const [key, definition] of Object.entries(models)) {
767
+ if (definition.options.table !== void 0) tables[key] = definition.options.table;
768
+ }
769
+ const files = options.files;
770
+ for (const [action, rule] of Object.entries(files ?? {})) {
771
+ if (!["read", "write", "delete"].includes(action)) {
772
+ throw new Error(`files.${action} is not a file action; use read, write or delete.`);
773
+ }
774
+ if (rule?.decision === "attachedTo" && !(rule.model in models)) {
775
+ throw new Error(`files.${action} is attached to "${rule.model}", which is not a model.`);
776
+ }
777
+ if (rule?.decision === "filter") {
778
+ throw new Error(`files.${action}: filter() is for model reads; use fileCheck() or attachedTo().`);
779
+ }
780
+ }
781
+ const compiled = defineSchema({ entities, links, permissions, tables });
782
+ return { ...compiled, ...files && Object.keys(files).length > 0 ? { files } : {}, models, graph };
783
+ }
784
+ function storedDefault(kind, value) {
785
+ if (value === null || value === void 0) return null;
786
+ switch (kind) {
787
+ case "boolean":
788
+ return value ? 1 : 0;
789
+ case "date":
790
+ return value instanceof Date ? value.getTime() : typeof value === "string" ? Date.parse(value) : Number(value);
791
+ case "json":
792
+ return JSON.stringify(value);
793
+ case "number":
794
+ return Number(value);
795
+ default:
796
+ return String(value);
797
+ }
798
+ }
799
+ function accessOverrides(key, rules, graph) {
800
+ const out = {};
801
+ for (const [action, decision] of Object.entries(rules)) {
802
+ if (decision === void 0) continue;
803
+ const engineAction = action === "read" ? "view" : action;
804
+ if (decision.decision === "role") {
805
+ out[engineAction] = decision.level;
806
+ } else if (decision.decision === "filter") {
807
+ if (action !== "read") throw new Error(`"${key}.${action}": filter() is only valid for read.`);
808
+ const build = decision.build;
809
+ out.view = {
810
+ where: (auth) => {
811
+ const result = build({ auth });
812
+ const branches = Array.isArray(result) ? result : [result];
813
+ return branches.map((branch) => toEngineWhere(graph[key], branch));
814
+ }
815
+ };
816
+ } else {
817
+ const test = decision.test;
818
+ out[engineAction] = (context) => test({ auth: context.auth, row: context.data, data: context.next, changed: context.changed });
819
+ }
820
+ }
821
+ return Object.keys(out).length > 0 ? out : void 0;
822
+ }
823
+
824
+ export {
825
+ findLinkByApiName,
826
+ toEngineWhere,
827
+ toEngineNode,
828
+ shapeFor,
829
+ t,
830
+ role,
831
+ filter,
832
+ check,
833
+ fileCheck,
834
+ attachedTo,
835
+ model,
836
+ schema2 as schema,
837
+ SQL_TYPE,
838
+ sqlLiteral,
839
+ entityDdl
840
+ };
841
+ //# sourceMappingURL=chunk-VWW5OS5B.js.map