shutro 0.1.0 → 0.2.1

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 (76) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/index.d.ts +3 -1
  3. package/dist/audit/index.js +2 -0
  4. package/dist/cli/cli.js +17 -2
  5. package/dist/cli/config.js +2 -0
  6. package/dist/cli/generate/generate.js +2 -0
  7. package/dist/cli/generate/render.js +57 -8
  8. package/dist/cli/init.js +4 -4
  9. package/dist/cli/resolve.d.ts +2 -0
  10. package/dist/cli/resolve.js +28 -0
  11. package/dist/core/data/data.d.ts +59 -0
  12. package/dist/core/data/data.js +119 -0
  13. package/dist/core/data/load.d.ts +37 -0
  14. package/dist/core/data/load.js +236 -0
  15. package/dist/core/env/env.d.ts +175 -2
  16. package/dist/core/env/env.js +304 -19
  17. package/dist/core/env/identity.d.ts +10 -0
  18. package/dist/core/env/identity.js +16 -0
  19. package/dist/core/errors.d.ts +15 -1
  20. package/dist/core/errors.js +21 -0
  21. package/dist/core/events/events.d.ts +44 -0
  22. package/dist/core/events/events.js +58 -0
  23. package/dist/core/events/workers.d.ts +56 -0
  24. package/dist/core/events/workers.js +155 -0
  25. package/dist/core/index.d.ts +17 -9
  26. package/dist/core/index.js +11 -3
  27. package/dist/core/model/field.d.ts +33 -0
  28. package/dist/core/model/field.js +64 -1
  29. package/dist/core/model/generated.d.ts +4 -2
  30. package/dist/core/model/model.d.ts +40 -0
  31. package/dist/core/model/model.js +28 -0
  32. package/dist/core/model/related.d.ts +17 -0
  33. package/dist/core/model/related.js +60 -0
  34. package/dist/core/model/typed.d.ts +107 -0
  35. package/dist/core/model/typed.js +46 -0
  36. package/dist/core/money/fx.d.ts +10 -2
  37. package/dist/core/money/fx.js +17 -2
  38. package/dist/core/recordset/aggregate.d.ts +22 -0
  39. package/dist/core/recordset/aggregate.js +258 -0
  40. package/dist/core/recordset/audit.d.ts +9 -1
  41. package/dist/core/recordset/audit.js +59 -2
  42. package/dist/core/recordset/compute.d.ts +2 -0
  43. package/dist/core/recordset/compute.js +11 -2
  44. package/dist/core/recordset/domain.d.ts +4 -0
  45. package/dist/core/recordset/domain.js +74 -2
  46. package/dist/core/recordset/onchange.js +70 -37
  47. package/dist/core/recordset/recordset.d.ts +10 -1
  48. package/dist/core/recordset/recordset.js +80 -14
  49. package/dist/core/recordset/security.d.ts +15 -1
  50. package/dist/core/recordset/security.js +95 -10
  51. package/dist/core/recordset/source.d.ts +9 -0
  52. package/dist/core/recordset/source.js +19 -0
  53. package/dist/core/recordset/transitions.js +4 -1
  54. package/dist/core/recordset/types.d.ts +131 -12
  55. package/dist/core/recordset/values.d.ts +6 -0
  56. package/dist/core/recordset/values.js +34 -4
  57. package/dist/core/recordset/writes.d.ts +6 -1
  58. package/dist/core/recordset/writes.js +217 -12
  59. package/dist/core/registry/ddl.d.ts +9 -0
  60. package/dist/core/registry/ddl.js +49 -2
  61. package/dist/core/registry/module.d.ts +10 -1
  62. package/dist/core/registry/module.js +2 -0
  63. package/dist/core/registry/registry.d.ts +29 -4
  64. package/dist/core/registry/registry.js +100 -5
  65. package/dist/core/security/runtime.d.ts +102 -0
  66. package/dist/core/security/runtime.js +232 -0
  67. package/dist/driver-pg/driver.d.ts +2 -0
  68. package/dist/driver-pg/driver.js +1 -0
  69. package/dist/migrate/apply.d.ts +5 -1
  70. package/dist/migrate/apply.js +20 -2
  71. package/dist/migrate/schema.js +40 -2
  72. package/dist/security/index.d.ts +24 -0
  73. package/dist/security/index.js +16 -0
  74. package/dist/sql/tag.d.ts +5 -0
  75. package/dist/sql/tag.js +29 -1
  76. package/package.json +1 -1
@@ -4,15 +4,190 @@
4
4
  * recorded as a compute trigger (RFC 0008 §7.2).
5
5
  */
6
6
  import { compile, sql } from '../../sql/index.js';
7
- import { MissingRecordError } from '../errors.js';
7
+ import { Decimal as DecimalJs } from 'decimal.js';
8
+ import { SYSTEM_UID } from '../env/identity.js';
9
+ import { MissingRecordError, StaleRecordError } from '../errors.js';
8
10
  import { targetOf } from '../registry/registry.js';
9
11
  import { trackChange, trackedKeys, trackSnapshot } from './audit.js';
10
12
  import { junctionTable } from './relations.js';
11
- import { assertAccess, assertFields, assertRecords, storedValue } from './security.js';
13
+ import { assertAccess, assertBackdate, assertFields, assertRecords, storedValue, } from './security.js';
12
14
  import { fillSequences, UNNUMBERED } from './sequences.js';
13
15
  import { arrayType, fail, normalize, valueRef } from './values.js';
16
+ /**
17
+ * Many2one fields without a database foreign key (`foreignKey: false`): the written ids must exist in the target
18
+ * (one query per field). @throws {MissingRecordError}
19
+ */
20
+ async function assertReferencesExist(internals, model, rows) {
21
+ for (const [key, field] of Object.entries(model.fields)) {
22
+ const keyless = field.foreignKey === false || field.companyDependent;
23
+ if (field.kind !== 'many2one' || !keyless)
24
+ continue;
25
+ const company = String(internals.env.companyId);
26
+ const ids = [
27
+ ...new Set(rows
28
+ .map((r) => field.companyDependent
29
+ ? (r.get(key) ?? {})[company]
30
+ : r.get(key))
31
+ .filter((v) => typeof v === 'number' && v > 0)),
32
+ ];
33
+ if (ids.length === 0)
34
+ continue;
35
+ const target = internals.registry.get(targetOf(field) ?? '').model;
36
+ const found = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(target.table)} WHERE ${sql.id('id')} = ANY(${sql.array(ids, 'bigint')})`));
37
+ const existing = new Set(found.map((r) => Number(r.id)));
38
+ const missing = ids.filter((id) => !existing.has(id));
39
+ if (missing.length > 0)
40
+ throw new MissingRecordError(target.name, missing);
41
+ }
42
+ }
43
+ /**
44
+ * Fills the materialized paths of new records of a hierarchical model, parents first (a batch may contain its own
45
+ * parents), and caches them. One statement per tree depth among the new records.
46
+ */
47
+ async function fillPaths(internals, model, ids) {
48
+ const spec = model.hierarchy;
49
+ if (spec === undefined || ids.length === 0)
50
+ return;
51
+ const t = sql.id(model.table);
52
+ const path = sql.id(model.columns[spec.path] ?? '');
53
+ const parent = sql.id(model.columns[spec.parent] ?? '');
54
+ const h = sql.id('h');
55
+ let pending = ids.length;
56
+ while (pending > 0) {
57
+ const rows = await internals.query(compile(sql `UPDATE ${t} SET ${path} = coalesce((SELECT ${h}.${path} FROM ${t} AS ${h} WHERE ${h}.${sql.id('id')} = ${t}.${parent}), '') || ${t}.${sql.id('id')}::text || '/'
58
+ WHERE ${t}.${sql.id('id')} = ANY(${sql.array([...ids], 'bigint')}) AND ${t}.${path} IS NULL
59
+ AND (${t}.${parent} IS NULL OR EXISTS (SELECT 1 FROM ${t} AS ${h} WHERE ${h}.${sql.id('id')} = ${t}.${parent} AND ${h}.${path} IS NOT NULL))
60
+ RETURNING ${t}.${sql.id('id')} AS ${sql.id('id')}, ${path} AS ${sql.id('path')}`));
61
+ if (rows.length === 0)
62
+ break;
63
+ for (const r of rows)
64
+ internals.cache.records.get(model.name)?.get(Number(r.id))?.set(spec.path, r.path);
65
+ pending -= rows.length;
66
+ }
67
+ }
68
+ /**
69
+ * A record of a hierarchy moved: refuses cycles, then rewrites the paths of its subtree in one statement each.
70
+ * @throws {ValidationError} when the new parent is the record or one of its descendants.
71
+ */
72
+ async function movePaths(host, model, ids, newParent) {
73
+ const spec = model.hierarchy;
74
+ if (spec === undefined)
75
+ return;
76
+ const { internals } = host;
77
+ const t = sql.id(model.table);
78
+ const path = sql.id(model.columns[spec.path] ?? '');
79
+ if (typeof newParent === 'number') {
80
+ const [p] = await internals.query(compile(sql `SELECT ${path} AS ${sql.id('path')} FROM ${t} WHERE ${sql.id('id')} = ${newParent}`));
81
+ const ancestors = new Set((p?.path ?? '')
82
+ .split('/')
83
+ .filter((x) => x !== '')
84
+ .map(Number));
85
+ const looping = ids.filter((id) => id === newParent || ancestors.has(id));
86
+ if (looping.length > 0)
87
+ fail(model, [spec.parent], `record(s) ${looping.join(', ')} cannot move under ${newParent}: it is the record itself or one of its descendants.`, 'A hierarchy cannot contain cycles; choose a parent outside the subtree.');
88
+ }
89
+ await internals.flush(model.name); // the new parent column reaches the database first
90
+ for (const id of ids) {
91
+ const rows = await internals.query(compile(sql `WITH ${sql.id('old')} AS (SELECT ${path} AS ${sql.id('p')} FROM ${t} WHERE ${sql.id('id')} = ${id}),
92
+ ${sql.id('new')} AS (SELECT coalesce((SELECT ${sql.id('h')}.${path} FROM ${t} AS ${sql.id('h')} WHERE ${sql.id('h')}.${sql.id('id')} = (SELECT ${sql.id(model.columns[spec.parent] ?? '')} FROM ${t} WHERE ${sql.id('id')} = ${id})), '') || ${String(id)} || '/' AS ${sql.id('p')})
93
+ UPDATE ${t} SET ${path} = (SELECT ${sql.id('p')} FROM ${sql.id('new')}) || substr(${t}.${path}, length((SELECT ${sql.id('p')} FROM ${sql.id('old')})) + 1)
94
+ WHERE ${t}.${path} LIKE (SELECT ${sql.id('p')} FROM ${sql.id('old')}) || '%'
95
+ RETURNING ${t}.${sql.id('id')} AS ${sql.id('id')}, ${path} AS ${sql.id('path')}`));
96
+ for (const r of rows)
97
+ internals.cache.records.get(model.name)?.get(Number(r.id))?.set(spec.path, r.path);
98
+ }
99
+ }
100
+ /**
101
+ * Delegation: values of the parents' fields go to the parent records. A row without its delegate many2one gets a new
102
+ * parent (one create per delegate for the whole batch); a row with one updates that parent.
103
+ */
104
+ async function createDelegates(host, model, rows) {
105
+ const out = rows.map((r) => ({ ...r }));
106
+ for (const key of model.delegates) {
107
+ const target = host.internals.registry.get(model.fields[key].target ?? '').model;
108
+ const own = Object.entries(model.fields)
109
+ .filter(([, f]) => f.delegated === key)
110
+ .map(([k]) => k);
111
+ const fresh = [];
112
+ for (const [index, row] of out.entries()) {
113
+ const values = {};
114
+ for (const k of own)
115
+ if (row[k] !== undefined) {
116
+ values[k] = row[k];
117
+ delete row[k];
118
+ }
119
+ if (row[key] === undefined || row[key] === null)
120
+ fresh.push({ index, values });
121
+ else if (Object.keys(values).length > 0)
122
+ await writeRecords(host, target, [row[key]], values);
123
+ }
124
+ if (fresh.length === 0)
125
+ continue;
126
+ const ids = await createRecords(host, target, fresh.map((f) => f.values));
127
+ fresh.forEach((f, i) => {
128
+ out[f.index][key] = ids[i];
129
+ });
130
+ }
131
+ return out;
132
+ }
133
+ function same(field, current, expected) {
134
+ if (expected === null || expected === undefined)
135
+ return current === null || current === undefined;
136
+ if (current === null || current === undefined)
137
+ return false;
138
+ if (expected instanceof Date || current instanceof Date)
139
+ return (new Date(current).getTime() === new Date(expected).getTime());
140
+ if (field.kind === 'many2one') {
141
+ const id = typeof expected === 'object' && 'id' in expected
142
+ ? expected.id
143
+ : expected;
144
+ return Number(current) === Number(id);
145
+ }
146
+ if (DecimalJs.isDecimal(current) || field.kind === 'decimal' || field.kind === 'monetary') {
147
+ const amount = typeof expected === 'object' && 'amount' in expected
148
+ ? expected.amount
149
+ : expected;
150
+ return new DecimalJs(String(current)).equals(new DecimalJs(String(amount)));
151
+ }
152
+ return JSON.stringify(current) === JSON.stringify(expected);
153
+ }
154
+ /**
155
+ * Compare-and-set (RFC 0018 §7.1): locks the records and checks their stored values against `expect` before a write.
156
+ * @throws {StaleRecordError} for records whose values differ (someone else saved first).
157
+ */
158
+ export async function assertExpected(internals, model, ids, expect) {
159
+ const keys = Object.keys(expect);
160
+ if (keys.length === 0 || ids.length === 0)
161
+ return;
162
+ for (const key of keys)
163
+ if (model.columns[key] === undefined || model.fields[key]?.companyDependent === true)
164
+ fail(model, [key], `'${key}' cannot be expected: it is not a stored column.`, 'Expect stored fields, e.g. { updatedAt }.');
165
+ assertFields(internals, model, keys, 'read');
166
+ await internals.flush(model.name); // this transaction's own pending writes count
167
+ const rows = await internals.query(compile(sql `SELECT ${sql.id('id')}, ${sql.join(keys.map((k) => sql.id(model.columns[k] ?? '')))} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array([...ids], 'bigint')}) FOR UPDATE`));
168
+ const stale = new Set();
169
+ const records = [];
170
+ for (const row of rows) {
171
+ const changed = keys.filter((k) => !same(model.fields[k], row[model.columns[k] ?? ''], expect[k]));
172
+ if (changed.length > 0) {
173
+ records.push(Number(row['id']));
174
+ for (const k of changed)
175
+ stale.add(k);
176
+ }
177
+ }
178
+ if (records.length > 0)
179
+ throw new StaleRecordError(model.name, records, [...stale]);
180
+ }
181
+ /** The `created_by` / `updated_by` value: `NULL` for the system ({@link SYSTEM_UID}, bootstrap scopes). */
182
+ function actor(internals) {
183
+ return internals.uid === SYSTEM_UID ? null : internals.uid;
184
+ }
14
185
  function translationOf(internals) {
15
- return { lang: internals.env.lang, source: internals.sourceLang };
186
+ return {
187
+ lang: internals.env.lang,
188
+ source: internals.sourceLang,
189
+ company: internals.env.companyId,
190
+ };
16
191
  }
17
192
  const CHUNK = 1000;
18
193
  function isX2Many(field) {
@@ -70,18 +245,22 @@ function splitRow(model, row, mode, host, id) {
70
245
  commands.set(key, value);
71
246
  continue;
72
247
  }
73
- if (model.columns[key] === undefined)
74
- fail(model, [key], `field '${key}' is not stored.`, 'Non-stored computed fields cannot be written.');
248
+ // A non-stored computed field is writable through its inverse (related fields with writable: true).
249
+ if (model.columns[key] === undefined && !(field.computed && field.inverse !== undefined))
250
+ fail(model, [key], `field '${key}' is not stored.`, 'Non-stored computed fields cannot be written unless they have an inverse.');
75
251
  stored.set(key, normalize(model, key, field, value, siblings, translationOf(host.internals)));
76
252
  }
77
253
  return { stored, commands };
78
254
  }
79
255
  // ------------------------------------------------------------------------------------------------- create
80
256
  /** Inserts `rows` and returns their ids in input order. Children and links are created too. */
81
- export async function createRecords(host, model, rows, options = {}) {
257
+ export async function createRecords(host, model, input, options = {}) {
82
258
  const { internals } = host;
83
- if (rows.length === 0)
259
+ if (input.length === 0)
84
260
  return [];
261
+ if (host.internals.asOf !== undefined)
262
+ fail(model, [], 'cannot be written in an asOf() scope.', 'The past is read-only: write outside env.asOf().');
263
+ const rows = model.delegates.length > 0 ? await createDelegates(host, model, input) : input;
85
264
  assertAccess(internals, model, 'create');
86
265
  if (options.copy === true)
87
266
  assertAccess(internals, model, 'import');
@@ -99,11 +278,15 @@ export async function createRecords(host, model, rows, options = {}) {
99
278
  const field = model.fields[key];
100
279
  if (field === undefined)
101
280
  continue;
281
+ if (field.companyDependent) {
282
+ stored.set(key, Object.freeze({})); // companies without a value read the default
283
+ continue;
284
+ }
102
285
  let value;
103
286
  if (key === 'createdAt' || key === 'updatedAt')
104
287
  value = internals.now;
105
288
  else if (key === 'createdBy' || key === 'updatedBy')
106
- value = internals.uid;
289
+ value = actor(internals);
107
290
  else
108
291
  value = defaultOf(field, internals.env) ?? null;
109
292
  // Stored computes are filled after the insert (RFC 0008 §7.6); sequences before it (RFC 0012 §7.4).
@@ -119,6 +302,9 @@ export async function createRecords(host, model, rows, options = {}) {
119
302
  fail(model, missing, `required field(s) ${missing.map((m) => `'${m}'`).join(', ')} are missing.`, 'Provide a value, or give the field a default in its definition.');
120
303
  return { stored, commands };
121
304
  });
305
+ await assertReferencesExist(internals, model, prepared.map((p) => p.stored));
306
+ if (model.backdate !== undefined)
307
+ assertBackdate(internals, model, prepared.map((p) => p.stored.get(model.backdate?.field ?? '')));
122
308
  await fillSequences(internals, model, prepared);
123
309
  const ids = [];
124
310
  if (options.copy === true)
@@ -132,6 +318,7 @@ export async function createRecords(host, model, rows, options = {}) {
132
318
  for (const r of rowsOut)
133
319
  ids.push(Number(r.id));
134
320
  }
321
+ await fillPaths(internals, model, ids);
135
322
  const parentsByKey = new Map();
136
323
  prepared.forEach((p, i) => {
137
324
  const id = ids[i];
@@ -181,7 +368,8 @@ export async function createRecords(host, model, rows, options = {}) {
181
368
  const target = internals.registry.get(field.target).model;
182
369
  const inverse = field.inverseField ?? '';
183
370
  const childRows = parents.flatMap(({ parent, rows: rs }) => rs.map((r) => ({ ...r, [inverse]: parent })));
184
- const childIds = await createRecords(host, target, childRows);
371
+ // COPY loads COPY their children too (feedback #20): one COPY per child model, ids in order.
372
+ const childIds = await createRecords(host, target, childRows, options);
185
373
  let at = 0;
186
374
  for (const { parent, rows: rs } of parents) {
187
375
  host.values(model.name, parent, true).set(key, childIds.slice(at, at + rs.length));
@@ -233,8 +421,13 @@ export async function writeRecords(host, model, ids, values) {
233
421
  const { internals } = host;
234
422
  if (ids.length === 0)
235
423
  return;
424
+ if (internals.asOf !== undefined)
425
+ fail(model, [], 'cannot be written in an asOf() scope.', 'The past is read-only: write outside env.asOf().');
236
426
  assertAccess(internals, model, 'write');
237
427
  assertFields(internals, model, Object.keys(values), 'write');
428
+ if (model.backdate !== undefined && model.backdate.field in values)
429
+ assertBackdate(internals, model, [values[model.backdate.field]]);
430
+ await assertReferencesExist(internals, model, [new Map(Object.entries(values))]);
238
431
  await assertRecords(internals, model, ids, 'write');
239
432
  // Money / Quantity checks need the sibling currency / uom values; a moved record needs its old parent.
240
433
  const needed = new Set();
@@ -246,6 +439,8 @@ export async function writeRecords(host, model, ids, values) {
246
439
  needed.add(field.uomField);
247
440
  if (field?.kind === 'many2one' && internals.registry.compute.inverseKeys(model.name).has(key))
248
441
  needed.add(key);
442
+ if (field?.companyDependent === true)
443
+ needed.add(key); // merged into the other companies' values
249
444
  }
250
445
  // The audit trail needs the exact old values of tracked fields (RFC 0013 §7.2).
251
446
  if (internals.env.flags.tracking) {
@@ -271,6 +466,12 @@ export async function writeRecords(host, model, ids, values) {
271
466
  const cached = host.values(model.name, id, true);
272
467
  for (const [key, value] of stored) {
273
468
  const field = model.fields[key];
469
+ if (model.columns[key] === undefined) {
470
+ // Non-stored with an inverse: the value lives in the cache for the inverse to read; nothing to flush.
471
+ cached.set(key, value);
472
+ inverses.add(key);
473
+ continue;
474
+ }
274
475
  if (field.kind === 'many2one') {
275
476
  invalidateInverseLists(host, model, key, cached.get(key), value);
276
477
  parentsByKey.set(key, [...(parentsByKey.get(key) ?? []), cached.get(key), value]);
@@ -298,9 +499,11 @@ export async function writeRecords(host, model, ids, values) {
298
499
  internals.trigger(model.name, key, changed);
299
500
  for (const [key, parents] of parentsByKey)
300
501
  triggerParents(internals, model, key, parents);
502
+ if (model.hierarchy !== undefined && model.hierarchy.parent in values)
503
+ await movePaths(host, model, ids, values[model.hierarchy.parent]);
301
504
  for (const key of inverses) {
302
505
  const inverse = model.fields[key].inverse;
303
- await inverse(host.recordset(model, ids));
506
+ await inverse(host.recordset(model, ids), key);
304
507
  }
305
508
  }
306
509
  /** A many2one changed: the cached child lists of the old and new parents are stale. */
@@ -326,6 +529,8 @@ export async function unlinkRecords(host, model, ids) {
326
529
  const { internals } = host;
327
530
  if (ids.length === 0)
328
531
  return;
532
+ if (internals.asOf !== undefined)
533
+ fail(model, [], 'cannot be deleted in an asOf() scope.', 'The past is read-only: delete outside env.asOf().');
329
534
  assertAccess(internals, model, 'unlink');
330
535
  await internals.flush(model.name);
331
536
  await assertRecords(internals, model, ids, 'unlink');
@@ -563,7 +768,7 @@ export async function flushDirty(host, modelName) {
563
768
  const sets = [
564
769
  ...fields.map((f) => sql `${sql.id(f.column)} = ${valueRef(f.field, f.column)}`),
565
770
  sql `${sql.id('updated_at')} = ${internals.now}`,
566
- sql `${sql.id('updated_by_id')} = ${internals.uid}`,
771
+ sql `${sql.id('updated_by_id')} = ${actor(internals)}`,
567
772
  ];
568
773
  const rows = await internals.query(compile(sql `UPDATE ${sql.id(model.table)} AS ${sql.id('x')} SET ${sql.join(sets)} FROM unnest(${sql.join(arrays)}) AS ${sql.id('v')}(${sql.join(names)}) WHERE ${sql.id('x', 'id')} = ${sql.id('v', 'id')} RETURNING ${sql.id('x', 'id')}`));
569
774
  const updated = new Set(rows.map((r) => Number(r.id)));
@@ -573,7 +778,7 @@ export async function flushDirty(host, modelName) {
573
778
  for (const id of chunk) {
574
779
  const values = host.values(name, id);
575
780
  values?.set('updatedAt', internals.now);
576
- values?.set('updatedBy', internals.uid);
781
+ values?.set('updatedBy', actor(internals));
577
782
  }
578
783
  }
579
784
  }
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { type CompiledSql } from '../../sql/index.js';
9
9
  import type { Field } from '../model/field.js';
10
+ import type { AnyModel } from '../model/model.js';
10
11
  import { type Registry } from './registry.js';
11
12
  /**
12
13
  * The database-level `DEFAULT` of a column (feedback #3), in the form PostgreSQL's catalog shows it once casts are
@@ -15,6 +16,14 @@ import { type Registry } from './registry.js';
15
16
  * computed, or a relation: those stay in the ORM.
16
17
  */
17
18
  export declare function columnDefault(key: string, field: Field): string | null;
19
+ /** The history table of a model with `history: true` (RFC 0018 §7.4). */
20
+ export declare function historyTable(model: AnyModel): string;
21
+ /**
22
+ * The history trigger of a model: archives the row as it was before its first change in each transaction (and before
23
+ * a delete) with its validity range, and keeps `updated_at` at the transaction time on every update, so raw SQL
24
+ * writes are versioned too. Idempotent: run after migrations.
25
+ */
26
+ export declare function historyStatements(registry: Registry): CompiledSql[];
18
27
  /**
19
28
  * `CREATE TABLE` statements for every model in the registry, then `ALTER TABLE … ADD FOREIGN KEY` for every
20
29
  * many2one, then junction tables for many2many fields. Execute them in order.
@@ -31,6 +31,8 @@ const NUMERIC_KINDS = new Set(['integer', 'float', 'decimal']);
31
31
  export function columnDefault(key, field) {
32
32
  if (key === 'createdAt' || key === 'updatedAt')
33
33
  return 'now()';
34
+ if (field.companyDependent)
35
+ return "'{}'"; // per-company values; the field default applies when reading
34
36
  const value = field.default;
35
37
  if (value === undefined || value === null || typeof value === 'function')
36
38
  return null;
@@ -68,6 +70,37 @@ function columnDdl(model, key, field, column) {
68
70
  parts.push(`DEFAULT ${dbDefault}`);
69
71
  return parts.join(' ');
70
72
  }
73
+ /** The history table of a model with `history: true` (RFC 0018 §7.4). */
74
+ export function historyTable(model) {
75
+ return `${model.table}_history`.slice(0, 63);
76
+ }
77
+ /**
78
+ * The history trigger of a model: archives the row as it was before its first change in each transaction (and before
79
+ * a delete) with its validity range, and keeps `updated_at` at the transaction time on every update, so raw SQL
80
+ * writes are versioned too. Idempotent: run after migrations.
81
+ */
82
+ export function historyStatements(registry) {
83
+ const out = [];
84
+ for (const { model } of registry.models.values()) {
85
+ if (!model.history)
86
+ continue;
87
+ const t = ident(model.table);
88
+ const h = ident(historyTable(model));
89
+ const fn = ident(`shutro_history_${model.table}`.slice(0, 63));
90
+ const trigger = ident(`${model.table}_history_trg`.slice(0, 63));
91
+ out.push(`CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS $fn$
92
+ BEGIN
93
+ IF TG_OP = 'UPDATE' THEN NEW.updated_at := now(); END IF;
94
+ -- Versions changed again in the same transaction were never visible to anyone: archive the first one only.
95
+ IF OLD.updated_at IS DISTINCT FROM now() THEN
96
+ INSERT INTO ${h} SELECT (jsonb_populate_record(NULL::${h}, to_jsonb(OLD) || jsonb_build_object('valid_from', OLD.updated_at, 'valid_to', now()))).* ON CONFLICT DO NOTHING;
97
+ END IF;
98
+ IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
99
+ RETURN NEW;
100
+ END $fn$`, `DROP TRIGGER IF EXISTS ${trigger} ON ${t}`, `CREATE TRIGGER ${trigger} BEFORE UPDATE OR DELETE ON ${t} FOR EACH ROW EXECUTE FUNCTION ${fn}()`);
101
+ }
102
+ return out.map((text) => ({ text, params: [] }));
103
+ }
71
104
  const ON_DELETE = {
72
105
  restrict: 'RESTRICT',
73
106
  cascade: 'CASCADE',
@@ -95,7 +128,9 @@ export function createTableStatements(registry) {
95
128
  continue;
96
129
  }
97
130
  columns.push(columnDdl(model, key, field, column));
98
- if (field.kind === 'many2one') {
131
+ if (field.kind === 'many2one' &&
132
+ field.foreignKey !== false &&
133
+ !field.companyDependent) {
99
134
  const target = registry.get(targetOf(field) ?? '').model;
100
135
  const onDelete = ON_DELETE[field.ondelete] ?? 'RESTRICT';
101
136
  foreignKeys.push(`ALTER TABLE ${ident(model.table)} ADD CONSTRAINT ${ident(`${model.table}_${column}_fkey`)} FOREIGN KEY (${ident(column)}) REFERENCES ${ident(target.table)} (${ident('id')}) ON DELETE ${onDelete}`);
@@ -123,5 +158,17 @@ export function createTableStatements(registry) {
123
158
  }
124
159
  }
125
160
  const junctionDdl = [...junctions.values()].map((j) => `CREATE TABLE ${ident(j.table)} (${ident(j.sourceColumn)} bigint NOT NULL REFERENCES ${ident(j.sourceTable)} (${ident('id')}) ON DELETE CASCADE, ${ident(j.targetColumn)} bigint NOT NULL REFERENCES ${ident(j.targetTable)} (${ident('id')}) ON DELETE CASCADE, PRIMARY KEY (${ident(j.sourceColumn)}, ${ident(j.targetColumn)}))`);
126
- return [...tables, ...foreignKeys, ...constraints, ...junctionDdl].map((text) => Object.freeze({ text, params: Object.freeze([]) }));
161
+ for (const { model } of registry.models.values()) {
162
+ if (!model.history)
163
+ continue;
164
+ const cols = Object.entries(model.columns)
165
+ .filter((entry) => entry[1] !== undefined)
166
+ .map(([key, column]) => {
167
+ const field = model.fields[key];
168
+ return `${ident(column)} ${key === 'id' ? 'bigint NOT NULL' : field.kind === 'many2one' && !field.companyDependent ? 'bigint' : typeName(field, model.name, key)}`;
169
+ });
170
+ tables.push(`CREATE TABLE ${ident(historyTable(model))} (${[...cols, '"valid_from" timestamp with time zone NOT NULL', '"valid_to" timestamp with time zone NOT NULL', 'PRIMARY KEY ("id", "valid_to")'].join(', ')})`);
171
+ }
172
+ const history = historyStatements(registry).map((c) => c.text);
173
+ return [...tables, ...foreignKeys, ...constraints, ...junctionDdl, ...history].map((text) => Object.freeze({ text, params: Object.freeze([]) }));
127
174
  }
@@ -4,8 +4,9 @@
4
4
  * carries its models, extensions and dependencies, so a registry built from modules knows every model it contains
5
5
  * (until `shutro generate` emits the same view).
6
6
  */
7
- import type { GroupDefinition } from '../../security/index.js';
7
+ import type { GroupDefinition, PermissionDefinition } from '../../security/index.js';
8
8
  import type { SequenceDefinition } from '../../sequence/index.js';
9
+ import type { DataRecord } from '../data/data.js';
9
10
  import { type AnyModel } from '../model/model.js';
10
11
  import { type AnyExtension } from './extension.js';
11
12
  import type { Registry } from './registry.js';
@@ -35,6 +36,10 @@ export interface ModuleBase {
35
36
  readonly sequences: readonly SequenceDefinition[];
36
37
  /** Security groups this module declares (RFC 0014 §7.1). */
37
38
  readonly groups: readonly GroupDefinition[];
39
+ /** Feature permissions this module declares (RFC 0014 §7.9). */
40
+ readonly permissions: readonly PermissionDefinition[];
41
+ /** Records the module ships (RFC 0017), in load order. */
42
+ readonly data: readonly DataRecord[];
38
43
  }
39
44
  /** A module as `defineModule` returns it; the type parameters carry the model types for the registry's schema view. */
40
45
  export interface Module<Ms extends readonly AnyModel[] = readonly AnyModel[], Deps extends readonly ModuleBase[] = readonly ModuleBase[], Exts extends readonly AnyExtension[] = readonly AnyExtension[]> extends ModuleBase {
@@ -62,6 +67,10 @@ export interface ModuleDefinition<Ms extends readonly AnyModel[], Deps extends r
62
67
  readonly sequences?: readonly SequenceDefinition[];
63
68
  /** Security groups (`defineGroup`). */
64
69
  readonly groups?: readonly GroupDefinition[];
70
+ /** Feature permissions (`definePermission`): apps, menus, buttons, approvals. */
71
+ readonly permissions?: readonly PermissionDefinition[];
72
+ /** Records the module ships (`record`, `override`; RFC 0017), loaded in this order by `shutro migrate apply`. */
73
+ readonly data?: readonly DataRecord[];
65
74
  }
66
75
  /** Numeric comparison of `major.minor.patch` versions. */
67
76
  export declare function compareVersions(a: string, b: string): number;
@@ -90,6 +90,8 @@ export function defineModule(definition) {
90
90
  migrations: Object.freeze(migrations),
91
91
  sequences: Object.freeze([...(definition.sequences ?? [])]),
92
92
  groups: Object.freeze([...(definition.groups ?? [])]),
93
+ permissions: Object.freeze([...(definition.permissions ?? [])]),
94
+ data: Object.freeze([...(definition.data ?? [])]),
93
95
  });
94
96
  modules.add(module);
95
97
  return module;
@@ -1,7 +1,7 @@
1
1
  import { type Field } from '../model/field.js';
2
2
  import { type AnyModel, type FieldDescription, type ModelDescription } from '../model/model.js';
3
3
  import { type Module, type ModuleBase } from './module.js';
4
- import { type GroupDefinition } from '../../security/index.js';
4
+ import { type GroupDefinition, type PermissionDefinition } from '../../security/index.js';
5
5
  import type { SequenceDefinition } from '../../sequence/index.js';
6
6
  import { type ComputeGraph } from '../compute/graph.js';
7
7
  type UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
@@ -64,12 +64,28 @@ export interface Registry<S = unknown> {
64
64
  readonly compute: ComputeGraph;
65
65
  /** Document sequences by code (RFC 0012 §7.1). */
66
66
  readonly sequences: ReadonlyMap<string, SequenceDefinition>;
67
+ /** External ids the modules' data declares → owning module and model (RFC 0017). */
68
+ readonly externalIds: ReadonlyMap<string, {
69
+ readonly module: string;
70
+ readonly model: string;
71
+ }>;
67
72
  /** Security groups and their closure (RFC 0014 §7.1). */
68
73
  readonly security: {
69
74
  readonly groups: ReadonlyMap<string, GroupDefinition>;
70
75
  closure(codes: Iterable<string>): Set<string>;
76
+ /** True when one of `groups` (a closure) is an administrator group (RFC 0014 §7.9). */
77
+ isAdministrator(groups: ReadonlySet<string>): boolean;
78
+ /** Feature permissions by code (RFC 0014 §7.9). */
79
+ readonly permissions: ReadonlyMap<string, PermissionDefinition>;
71
80
  /** False only when the registry was built with `security: { enforce: false }`. */
72
81
  readonly enforce: boolean;
82
+ /**
83
+ * `'warn'`: ACL and field-group denials are reported through {@link SecurityOptions.onDenied} and allowed
84
+ * (record rules still apply). `'enforce'` otherwise (or `'off'` with `enforce: false`).
85
+ */
86
+ readonly mode: 'enforce' | 'warn' | 'off';
87
+ /** Reports a denial `'warn'` mode let through; each distinct message once per registry. */
88
+ denied(message: string): void;
73
89
  };
74
90
  has(name: string): boolean;
75
91
  /** @throws {UnknownModelError} */
@@ -87,9 +103,18 @@ export interface RegistryOptions<Mods extends readonly ModuleBase[]> {
87
103
  * Access control (RFC 0014). Enforced by default; `enforce: false` makes every model, record and field accessible
88
104
  * to every environment, for prototypes and for tests of other features. Never ship it off.
89
105
  */
90
- readonly security?: {
91
- readonly enforce?: boolean;
92
- };
106
+ readonly security?: SecurityOptions;
107
+ }
108
+ /** Access-control options of {@link buildRegistry}. */
109
+ export interface SecurityOptions {
110
+ /**
111
+ * `true` (default) enforces ACL, rules and field groups. `'warn'` is for development: a missing grant is reported
112
+ * and allowed, so prototypes run before their `access` declarations are written; it is refused when
113
+ * `NODE_ENV=production`. `false` turns access control off (tests of other features).
114
+ */
115
+ readonly enforce?: boolean | 'warn';
116
+ /** Where `'warn'` reports go. Defaults to `process.emitWarning` (code `SHUTRO_ACCESS_WOULD_DENY`). */
117
+ readonly onDenied?: (message: string) => void;
93
118
  }
94
119
  /** The target model of a relation field, else `undefined`. */
95
120
  export declare function targetOf(field: Field): string | undefined;