shutro 0.0.0-stage → 0.2.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
@@ -0,0 +1,789 @@
1
+ /**
2
+ * Recordset runtime (RFC 0004): identity map per transaction, prefetch groups, batched loads, typed access, and
3
+ * the entry points of writes (see writes.ts) and computes (see compute.ts).
4
+ */
5
+ import { resolveTranslation } from '../../i18n/index.js';
6
+ import { compile, sql } from '../../sql/index.js';
7
+ import { Decimal as DecimalJs } from 'decimal.js';
8
+ import { internalsOf } from '../env/env.js';
9
+ import { FieldNotLoadedError, InvalidFieldError, MissingRecordError, SingletonError, } from '../errors.js';
10
+ import { defineCurrency } from '../money/currency.js';
11
+ import { Money } from '../money/money.js';
12
+ import { defineUom, Quantity } from '../money/quantity.js';
13
+ import { targetOf } from '../registry/registry.js';
14
+ import { runAggregate } from './aggregate.js';
15
+ import { flushAudit, trailOf } from './audit.js';
16
+ import { assignComputed, computeFields, recompute, } from './compute.js';
17
+ import { checkConstraints } from './constraints.js';
18
+ import { compileDomain, compileOrder, scopingConditions } from './domain.js';
19
+ import { runOnchange, } from './onchange.js';
20
+ import { junctionTable } from './relations.js';
21
+ import { assertAccess, assertDomainFields, assertFields, explainDenied, fieldGroupsOf, loadedValue, readableKeys, ruleConditions, } from './security.js';
22
+ import { assignNumbers } from './sequences.js';
23
+ import { sourceOf } from './source.js';
24
+ import { availableTransitions, runTransition } from './transitions.js';
25
+ import { companyValue } from './values.js';
26
+ import { assertExpected, createRecords, flushDirty, unlinkRecords, writeRecords, } from './writes.js';
27
+ const CHUNK = 1000;
28
+ /** @internal */
29
+ export function createRecordCache() {
30
+ return { records: new Map(), currencies: new Map(), uoms: new Map() };
31
+ }
32
+ function valuesOf(cache, model, id, create = false) {
33
+ let byId = cache.records.get(model);
34
+ if (byId === undefined) {
35
+ if (!create)
36
+ return undefined;
37
+ byId = new Map();
38
+ cache.records.set(model, byId);
39
+ }
40
+ let values = byId.get(id);
41
+ if (values === undefined && create) {
42
+ values = new Map();
43
+ byId.set(id, values);
44
+ }
45
+ return values;
46
+ }
47
+ function isX2Many(field) {
48
+ return field.kind === 'one2many' || field.kind === 'many2many';
49
+ }
50
+ /** Stored, non-binary, not x2many (RFC 0004 §6.1). */
51
+ export function defaultKeys(model) {
52
+ return Object.entries(model.fields)
53
+ .filter(([, f]) => f.store && f.kind !== 'binary' && !isX2Many(f))
54
+ .map(([key]) => key);
55
+ }
56
+ /** Adds the sibling currency / uom fields that monetary / quantity values need. */
57
+ function withSiblings(model, keys) {
58
+ const out = new Set();
59
+ for (const key of keys) {
60
+ out.add(key);
61
+ const field = model.fields[key];
62
+ if (field?.currencyField !== undefined)
63
+ out.add(field.currencyField);
64
+ if (field?.uomField !== undefined)
65
+ out.add(field.uomField);
66
+ }
67
+ return out;
68
+ }
69
+ function normalizeSpec(loader, model, spec) {
70
+ // Default projections leave out fields the user may not read (RFC 0014 §7.4); explicit keys are checked instead.
71
+ const defaults = () => new Set(readableKeys(loader.internals, model, withSiblings(model, defaultKeys(model))));
72
+ if (spec === undefined || spec === true)
73
+ return { fields: defaults(), relations: new Map() };
74
+ if (Array.isArray(spec)) {
75
+ for (const key of spec) {
76
+ const field = model.fields[String(key)];
77
+ if (field === undefined || isX2Many(field)) {
78
+ throw new FieldNotLoadedError(model.name, String(key), `'${String(key)}' is not a loadable field of ${model.name}; list scalar or many2one fields, or use { ${String(key)}: true } for relations.`);
79
+ }
80
+ }
81
+ return { fields: withSiblings(model, ['id', ...spec.map(String)]), relations: new Map() };
82
+ }
83
+ const relations = new Map();
84
+ for (const [key, sub] of Object.entries(spec)) {
85
+ if (sub === undefined || sub === false)
86
+ continue;
87
+ const field = model.fields[key];
88
+ const target = field === undefined ? undefined : targetOf(field);
89
+ if (field === undefined || target === undefined) {
90
+ throw new FieldNotLoadedError(model.name, key, `'${key}' is not a relation of ${model.name}; nested load specs only take many2one, one2many and many2many fields.`);
91
+ }
92
+ relations.set(key, normalizeSpec(loader, loader.registry.get(target).model, sub));
93
+ }
94
+ return { fields: defaults(), relations };
95
+ }
96
+ function hydrate(loader, model, row, keys) {
97
+ const id = Number(row['id']);
98
+ const values = valuesOf(loader.internals.cache, model.name, id, true);
99
+ for (const key of keys) {
100
+ const column = model.columns[key];
101
+ if (column === undefined || key === 'id')
102
+ continue;
103
+ const field = model.fields[key];
104
+ // The cache is authoritative within the transaction: a value written or computed here (possibly not flushed
105
+ // yet) must not be replaced by the row's older value. Only fill keys that are not cached.
106
+ if (values.has(key))
107
+ continue;
108
+ values.set(key, loadedValue(loader.internals, field, row[column] ?? null));
109
+ }
110
+ return id;
111
+ }
112
+ /** Fetches the given fields for the records that don't have all of them cached. One query per 1,000 ids. */
113
+ async function fetchMissing(loader, model, ids, fields, user = false) {
114
+ const { cache } = loader.internals;
115
+ const wanted = [...fields].filter((k) => k !== 'id' && model.columns[k] !== undefined);
116
+ const missing = ids.filter((id) => {
117
+ const values = valuesOf(cache, model.name, id);
118
+ return values === undefined || wanted.some((k) => !values.has(k));
119
+ });
120
+ // User loads carry the read rules (RFC 0014 §7.3); engine loads do not.
121
+ const rules = user ? ruleConditions(loader.internals, model, 'read') : [];
122
+ const scope = rules.length === 0 ? sql.empty : sql ` AND ${sql.join(rules, sql ` AND `)}`;
123
+ if (missing.length > 0 && wanted.length === 0)
124
+ await assertExist(loader, model, missing, scope);
125
+ if (missing.length > 0 && wanted.length > 0) {
126
+ const columns = sql.join([sql.id('id'), ...wanted.map((k) => sql.id(model.columns[k] ?? ''))]);
127
+ const seen = new Set();
128
+ for (let i = 0; i < missing.length; i += CHUNK) {
129
+ const chunk = missing.slice(i, i + CHUNK);
130
+ const rows = await loader.internals.query(compile(sql `SELECT ${columns} FROM ${sourceOf(loader.internals, model)} WHERE ${sql.id('id')} = ANY(${chunk})${scope}`));
131
+ for (const row of rows)
132
+ seen.add(hydrate(loader, model, row, wanted));
133
+ }
134
+ const absent = missing.filter((id) => !seen.has(id));
135
+ if (absent.length > 0) {
136
+ if (rules.length > 0)
137
+ await explainDenied(loader.internals, model, absent, 'read');
138
+ throw new MissingRecordError(model.name, absent);
139
+ }
140
+ }
141
+ // Even when every column was cached, the value objects behind monetary / quantity fields may not be.
142
+ await ensureValueObjects(loader, model, ids, fields);
143
+ }
144
+ async function assertExist(loader, model, ids, scope = sql.empty) {
145
+ const rows = await loader.internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sourceOf(loader.internals, model)} WHERE ${sql.id('id')} = ANY(${[...ids]})${scope}`));
146
+ const found = new Set(rows.map((r) => Number(r.id)));
147
+ const absent = ids.filter((id) => !found.has(id));
148
+ if (absent.length > 0) {
149
+ if (scope !== sql.empty)
150
+ await explainDenied(loader.internals, model, absent, 'read');
151
+ throw new MissingRecordError(model.name, absent);
152
+ }
153
+ for (const id of ids)
154
+ valuesOf(loader.internals.cache, model.name, id, true);
155
+ }
156
+ /** Loads the currencies / units referenced by monetary / quantity fields, through the record cache. */
157
+ async function ensureValueObjects(loader, model, ids, fields) {
158
+ const { cache } = loader.internals;
159
+ const needed = { currency: new Set(), uom: new Set() };
160
+ for (const key of fields) {
161
+ const field = model.fields[key];
162
+ if (field === undefined)
163
+ continue;
164
+ const ref = field.currencyField !== undefined
165
+ ? { kind: 'currency', key: field.currencyField }
166
+ : field.uomField !== undefined
167
+ ? { kind: 'uom', key: field.uomField }
168
+ : undefined;
169
+ if (ref === undefined)
170
+ continue;
171
+ for (const id of ids) {
172
+ const value = valuesOf(cache, model.name, id)?.get(ref.key);
173
+ if (typeof value === 'number' &&
174
+ !(ref.kind === 'currency' ? cache.currencies : cache.uoms).has(value))
175
+ needed[ref.kind].add(value);
176
+ }
177
+ }
178
+ if (needed.currency.size > 0) {
179
+ const currency = loader.registry.get('res.currency').model;
180
+ const ids = [...needed.currency];
181
+ await fetchMissing(loader, currency, ids, new Set(defaultKeys(currency)));
182
+ for (const id of ids) {
183
+ const v = valuesOf(cache, currency.name, id);
184
+ const method = typeof v?.get('roundingMethod') === 'string'
185
+ ? String(v.get('roundingMethod')).replaceAll('_', '-')
186
+ : undefined;
187
+ const places = v?.get('decimalPlaces');
188
+ cache.currencies.set(id, defineCurrency({
189
+ code: String(v?.get('name')),
190
+ rounding: v?.get('rounding'),
191
+ ...(method === undefined ? {} : { roundingMethod: method }),
192
+ ...(typeof places === 'number' ? { decimalPlaces: places } : {}),
193
+ id,
194
+ }));
195
+ }
196
+ }
197
+ if (needed.uom.size > 0) {
198
+ const uom = loader.registry.get('uom.uom').model;
199
+ const ids = [...needed.uom];
200
+ await fetchMissing(loader, uom, ids, new Set(defaultKeys(uom)));
201
+ for (const id of ids) {
202
+ const v = valuesOf(cache, uom.name, id);
203
+ cache.uoms.set(id, defineUom({
204
+ name: String(v?.get('name')),
205
+ category: String(v?.get('category')),
206
+ ratio: v?.get('ratio'),
207
+ rounding: v?.get('rounding'),
208
+ id,
209
+ }));
210
+ }
211
+ }
212
+ }
213
+ /** Loads the relation `key` (x2many) of the parents whose child list isn't cached, with the sub-spec's fields, in one query. */
214
+ async function fetchX2Many(loader, model, key, parents, sub, user = false) {
215
+ const { cache } = loader.internals;
216
+ const field = model.fields[key];
217
+ const target = loader.registry.get(field.target).model;
218
+ const missing = parents.filter((id) => !valuesOf(cache, model.name, id)?.has(key));
219
+ if (missing.length > 0)
220
+ await loader.internals.flush(target.name); // re-pointed children must be visible
221
+ if (user) {
222
+ assertAccess(loader.internals, target, 'read');
223
+ assertFields(loader.internals, target, sub.fields, 'read');
224
+ }
225
+ const rules = user ? ruleConditions(loader.internals, target, 'read') : [];
226
+ const scope = rules.length === 0 ? sql.empty : sql ` AND ${sql.join(rules, sql ` AND `)}`;
227
+ const wanted = [...sub.fields].filter((k) => k !== 'id' && target.columns[k] !== undefined);
228
+ const children = new Map();
229
+ for (const id of missing)
230
+ children.set(id, []);
231
+ if (missing.length > 0) {
232
+ const t = sql.id('t');
233
+ const columns = sql.join([
234
+ sql `${t}.${sql.id('id')}`,
235
+ ...wanted.map((k) => sql `${t}.${sql.id(target.columns[k] ?? '')}`),
236
+ ]);
237
+ const order = compileOrder(target, undefined, translationScope(loader.internals));
238
+ for (let i = 0; i < missing.length; i += CHUNK) {
239
+ const chunk = missing.slice(i, i + CHUNK);
240
+ let rows;
241
+ if (field.kind === 'one2many') {
242
+ const inverse = sql.id(target.columns[field.inverseField ?? ''] ?? '');
243
+ rows = await loader.internals.query(compile(sql `SELECT ${t}.${inverse} AS ${sql.id('parent_id')}, ${columns} FROM ${sourceOf(loader.internals, target)} AS ${t} WHERE ${t}.${inverse} = ANY(${chunk})${scope} ORDER BY ${order}`));
244
+ }
245
+ else {
246
+ const j = junctionTable(model, field, target);
247
+ rows = await loader.internals.query(compile(sql `SELECT ${sql.id('rel', j.sourceColumn)} AS ${sql.id('parent_id')}, ${columns} FROM ${sql.id(j.table)} AS ${sql.id('rel')} INNER JOIN ${sql.id(target.table)} AS ${t} ON ${t}.${sql.id('id')} = ${sql.id('rel', j.targetColumn)} WHERE ${sql.id('rel', j.sourceColumn)} = ANY(${chunk})${scope} ORDER BY ${order}`));
248
+ }
249
+ for (const row of rows) {
250
+ const childId = hydrate(loader, target, row, wanted);
251
+ children.get(Number(row['parent_id']))?.push(childId);
252
+ }
253
+ }
254
+ for (const [parent, ids] of children)
255
+ valuesOf(cache, model.name, parent, true).set(key, ids);
256
+ }
257
+ const all = [];
258
+ for (const id of parents)
259
+ for (const child of valuesOf(cache, model.name, id)?.get(key) ?? [])
260
+ all.push(child);
261
+ const unique = [...new Set(all)];
262
+ // Lists cached by x2many commands hold ids whose fields were never fetched: load the sub-spec for every child.
263
+ await fetchMissing(loader, target, unique, sub.fields, user);
264
+ await computeNonStored(loader, target, unique, sub.fields);
265
+ return unique;
266
+ }
267
+ /** Computes the requested non-stored computed keys that are missing from the cache (RFC 0008 §7.4). */
268
+ async function computeNonStored(loader, model, ids, keys) {
269
+ const graph = loader.registry.compute;
270
+ const fields = [...keys]
271
+ .filter((k) => {
272
+ const f = model.fields[k];
273
+ return f?.computed === true && !f.store;
274
+ })
275
+ .map((k) => graph.field(model.name, k))
276
+ .filter((f) => f !== undefined);
277
+ if (fields.length === 0)
278
+ return;
279
+ const { cache } = loader.internals;
280
+ const missing = ids.filter((id) => {
281
+ const values = valuesOf(cache, model.name, id);
282
+ return values === undefined || fields.some((f) => !values.has(f.key));
283
+ });
284
+ await computeFields(computeHost(loader), model, missing, fields);
285
+ }
286
+ /** Loads `spec` for `ids` of `model`, recursively (RFC 0004 §7.1). */
287
+ async function loadInto(loader, model, ids, spec, user = false) {
288
+ if (ids.length === 0)
289
+ return;
290
+ if (user) {
291
+ assertAccess(loader.internals, model, 'read');
292
+ assertFields(loader.internals, model, spec.fields, 'read');
293
+ }
294
+ // Pending triggers first, so stored computes are fresh when they are read (RFC 0008 §7.3).
295
+ if (!loader.internals.compute.recomputing && loader.internals.hasPending())
296
+ await recompute(computeHost(loader));
297
+ await fetchMissing(loader, model, ids, spec.fields, user);
298
+ await computeNonStored(loader, model, ids, spec.fields);
299
+ for (const [key, sub] of spec.relations) {
300
+ const field = model.fields[key];
301
+ if (field.kind === 'many2one') {
302
+ const targetIds = new Set();
303
+ for (const id of ids) {
304
+ const value = valuesOf(loader.internals.cache, model.name, id)?.get(key);
305
+ if (typeof value === 'number')
306
+ targetIds.add(value);
307
+ }
308
+ await loadInto(loader, loader.registry.get(field.target).model, [...targetIds], sub, user);
309
+ }
310
+ else {
311
+ const children = await fetchX2Many(loader, model, key, ids, sub, user);
312
+ const target = loader.registry.get(field.target).model;
313
+ for (const [k, nested] of sub.relations) {
314
+ await loadInto(loader, target, children, { fields: new Set(), relations: new Map([[k, nested]]) }, user);
315
+ }
316
+ }
317
+ }
318
+ }
319
+ const prototypes = new WeakMap();
320
+ /** @internal Runtime recordset. Typed through `RecordSet` / `Rec` / `PendingSet` (types.ts). */
321
+ export class RecordSetImpl {
322
+ env;
323
+ registered;
324
+ modelName;
325
+ #ids;
326
+ #group;
327
+ #pending;
328
+ constructor(env, registered, ids, group, pending) {
329
+ this.env = env;
330
+ this.registered = registered;
331
+ this.modelName = registered.model.name;
332
+ this.#ids = ids;
333
+ this.#group = group;
334
+ this.#pending = pending;
335
+ }
336
+ get #loader() {
337
+ const internals = internalsOf(this.env);
338
+ return { env: this.env, internals, registry: internals.registry };
339
+ }
340
+ get model() {
341
+ return this.registered.model;
342
+ }
343
+ get ids() {
344
+ if (this.#ids === undefined) {
345
+ throw new FieldNotLoadedError(this.modelName, this.#pending?.key ?? 'ids', 'This x2many relation was not loaded yet: await set.load() (or load it with the parent: load({ lines: true })).');
346
+ }
347
+ return this.#ids;
348
+ }
349
+ get length() {
350
+ return this.ids.length;
351
+ }
352
+ isEmpty() {
353
+ return this.ids.length === 0;
354
+ }
355
+ #record(id) {
356
+ const Ctor = recordClass(this.model);
357
+ return new Ctor(this.env, this.registered, [id], this.#group ?? { ids: this.ids }, undefined);
358
+ }
359
+ *[Symbol.iterator]() {
360
+ for (const id of this.ids)
361
+ yield this.#record(id);
362
+ }
363
+ first() {
364
+ const id = this.ids[0];
365
+ if (id === undefined)
366
+ throw new SingletonError(this.modelName, 0, 'first');
367
+ return this.#record(id);
368
+ }
369
+ ensureOne() {
370
+ if (this.ids.length !== 1)
371
+ throw new SingletonError(this.modelName, this.ids.length, 'ensureOne');
372
+ return this.first();
373
+ }
374
+ /** The record's id (singletons only). */
375
+ get id() {
376
+ return this.ensureOne().ids[0];
377
+ }
378
+ map(fn) {
379
+ return [...this].map((r, i) => fn(r, i));
380
+ }
381
+ filter(fn) {
382
+ const kept = [...this].filter((r, i) => fn(r, i)).map((r) => r.ids[0]);
383
+ return new (recordClass(this.model))(this.env, this.registered, kept, this.#group, undefined);
384
+ }
385
+ /** A `Currency` from a currency, a record reference or an id (loaded with the records' monetary fields). */
386
+ #currencyOf(currency) {
387
+ if (currency === undefined)
388
+ return undefined;
389
+ if (typeof currency === 'object' && 'code' in currency)
390
+ return currency;
391
+ const id = typeof currency === 'number' ? currency : currency.id;
392
+ const found = this.#loader.internals.cache.currencies.get(id);
393
+ if (found === undefined)
394
+ throw new FieldNotLoadedError(this.model.name, 'currency', `Currency ${id} is not loaded: pass a Currency, or sum records whose monetary fields are loaded in it.`);
395
+ return found;
396
+ }
397
+ mapped(key) {
398
+ return [...this].map((r) => r[key]);
399
+ }
400
+ sum(key, currency) {
401
+ const kind = this.model.fields[key]?.kind;
402
+ const values = this.mapped(key).filter((v) => v !== null && v !== undefined);
403
+ if (kind === 'monetary')
404
+ return Money.sum(values, this.#currencyOf(currency));
405
+ if (kind === 'decimal')
406
+ return values.reduce((total, v) => total.plus(v), new DecimalJs(0));
407
+ if (kind === 'integer' || kind === 'float')
408
+ return values.reduce((total, v) => total + v, 0);
409
+ throw new InvalidFieldError(`${this.model.name}.sum() needs an integer, float, decimal or monetary field; '${key}' is ${kind ?? 'not a field'}.`, 'Sum a numeric field, or use mapped() and reduce the values yourself.');
410
+ }
411
+ async load(spec) {
412
+ const loader = this.#loader;
413
+ const normalized = normalizeSpec(loader, this.model, spec);
414
+ if (this.#pending !== undefined && this.#ids === undefined) {
415
+ const { parentModel, key, parents, own } = this.#pending;
416
+ await fetchX2Many(loader, parentModel, key, parents, normalized, true);
417
+ const childrenOf = (p) => valuesOf(loader.internals.cache, parentModel.name, p)?.get(key) ??
418
+ [];
419
+ const mine = own.flatMap(childrenOf);
420
+ const all = [...new Set(parents.flatMap(childrenOf))];
421
+ for (const [k, nested] of normalized.relations) {
422
+ await loadInto(loader, this.model, all, { fields: new Set(), relations: new Map([[k, nested]]) }, true);
423
+ }
424
+ return new (recordClass(this.model))(this.env, this.registered, mine, { ids: all }, undefined);
425
+ }
426
+ const group = this.#group?.ids ?? this.ids;
427
+ await loadInto(loader, this.model, group, normalized, true);
428
+ return new (recordClass(this.model))(this.env, this.registered, this.ids, this.#group, undefined);
429
+ }
430
+ #host() {
431
+ return writeHost(this.#loader);
432
+ }
433
+ /** Updates the records in the cache now; flushed at the next flush point. */
434
+ async write(values, options = {}) {
435
+ const ids = await this.resolveIds();
436
+ if (options.expect !== undefined)
437
+ await assertExpected(this.#loader.internals, this.model, ids, options.expect);
438
+ await writeRecords(this.#host(), this.model, ids, values);
439
+ }
440
+ /** Deletes the records now. */
441
+ async unlink() {
442
+ await unlinkRecords(this.#host(), this.model, await this.resolveIds());
443
+ }
444
+ /** Ids of a pending x2many set, loading them if needed. */
445
+ async resolveIds() {
446
+ if (this.#ids !== undefined)
447
+ return this.#ids;
448
+ return (await this.load([])).ids;
449
+ }
450
+ read(keys) {
451
+ return [...this].map((r) => {
452
+ const row = { id: r.ids[0] };
453
+ for (const key of keys)
454
+ if (key !== 'id')
455
+ row[key] = plain(r.fieldValue(key), this.model.fields[key]); // id is always there
456
+ return row;
457
+ });
458
+ }
459
+ toJSON() {
460
+ return this.ids;
461
+ }
462
+ /** The full translation map of a translatable field of a singleton (`null` when empty). */
463
+ translations(key) {
464
+ const field = this.model.fields[key];
465
+ if (field === undefined || !field.translate)
466
+ throw new FieldNotLoadedError(this.modelName, key, `'${key}' is not a translatable field.`);
467
+ const values = valuesOf(internalsOf(this.env).cache, this.modelName, this.id);
468
+ if (values === undefined || !values.has(key))
469
+ throw new FieldNotLoadedError(this.modelName, key, `Load it first: await records.load(['${key}']).`);
470
+ const raw = values.get(key);
471
+ return raw === null || raw === undefined ? null : raw;
472
+ }
473
+ /** The audit rows of these records, newest first (RFC 0013 §7.4). Pending changes are flushed first. */
474
+ async trail(options = {}) {
475
+ const internals = internalsOf(this.env);
476
+ assertAccess(internals, this.model, 'read');
477
+ return trailOf(internals, this.model, await this.resolveIds(), options);
478
+ }
479
+ /** Numbers unnumbered records of a manual sequence field (RFC 0012 §7.4). */
480
+ async assignNumber(key, options = {}) {
481
+ await assignNumbers(computeHost(this.#loader), this.model, await this.resolveIds(), key, options);
482
+ }
483
+ /** @internal Runs a transition of state field `key` on these records (RFC 0010 §7.2). */
484
+ async transition(key, name) {
485
+ await runTransition(computeHost(this.#loader), this.model, await this.resolveIds(), key, name);
486
+ }
487
+ /** Transition names the current state allows (singleton, state loaded). Defaults to the model's state field. */
488
+ transitions(key) {
489
+ const stateKey = key ??
490
+ Object.entries(this.model.fields)
491
+ .filter(([, f]) => f.kind === 'state')
492
+ .map(([k]) => k)[0];
493
+ if (stateKey === undefined)
494
+ return [];
495
+ return availableTransitions(this.model, stateKey, this.fieldValue(stateKey));
496
+ }
497
+ /** @internal Assigns a computed field of a singleton from inside its compute (RFC 0008 §7.5). */
498
+ assign(key, value) {
499
+ assignComputed(computeHost(this.#loader), this.model, this.id, key, value);
500
+ }
501
+ /** @internal Reads field `key` of a singleton from the cache. */
502
+ fieldValue(key) {
503
+ const id = this.ids[0];
504
+ const field = this.model.fields[key];
505
+ if (id === undefined || field === undefined)
506
+ throw new FieldNotLoadedError(this.modelName, key, `'${key}' is not a field of ${this.modelName}.`);
507
+ const internals = internalsOf(this.env);
508
+ if (fieldGroupsOf(internals, this.model, key).read.length > 0)
509
+ assertFields(internals, this.model, [key], 'read');
510
+ const { cache } = internals;
511
+ const values = valuesOf(cache, this.modelName, id);
512
+ if (field.kind === 'one2many' || field.kind === 'many2many') {
513
+ const target = this.#loader.registry.get(targetOf(field) ?? '');
514
+ const children = values?.get(key);
515
+ const group = this.#group?.ids ?? [id];
516
+ if (children === undefined) {
517
+ return new (recordClass(target.model))(this.env, target, undefined, undefined, {
518
+ parentModel: this.model,
519
+ key,
520
+ own: [id],
521
+ parents: group,
522
+ });
523
+ }
524
+ const groupChildren = group.flatMap((p) => valuesOf(cache, this.modelName, p)?.get(key) ?? []);
525
+ return new (recordClass(target.model))(this.env, target, children, { ids: groupChildren }, undefined);
526
+ }
527
+ if (values === undefined || !values.has(key)) {
528
+ const hint = field.computed
529
+ ? field.store
530
+ ? `It is computed and pending recompute (or not loaded): await records.load(['${key}']) or env.flush() first.`
531
+ : `It is computed on load: await records.load(['${key}']).`
532
+ : `Load it first: await records.load(['${key}'])${field.kind === 'many2one' ? ` or load({ ${key}: true }) for the related record` : ''}.`;
533
+ throw new FieldNotLoadedError(this.modelName, key, hint);
534
+ }
535
+ const raw = field.companyDependent
536
+ ? companyValue(field, values.get(key), this.env.companyId)
537
+ : values.get(key);
538
+ if (field.translate) {
539
+ return resolveTranslation(raw, this.env.lang, internalsOf(this.env).sourceLang);
540
+ }
541
+ if (field.kind === 'many2one') {
542
+ if (raw === null)
543
+ return null;
544
+ const target = this.#loader.registry.get(targetOf(field) ?? '');
545
+ const group = this.#group?.ids ?? [id];
546
+ const targetIds = [
547
+ ...new Set(group
548
+ .map((p) => valuesOf(cache, this.modelName, p)?.get(key))
549
+ .filter((v) => typeof v === 'number')),
550
+ ];
551
+ const Ctor = recordClass(target.model);
552
+ return new Ctor(this.env, target, [raw], { ids: targetIds }, undefined);
553
+ }
554
+ if (field.kind === 'monetary') {
555
+ if (raw === null)
556
+ return null;
557
+ const currencyId = values.get(field.currencyField);
558
+ if (currencyId === null)
559
+ return null; // no currency, no Money (e.g. a draft line without its order yet)
560
+ const currency = typeof currencyId === 'number' ? cache.currencies.get(currencyId) : undefined;
561
+ if (currency === undefined) {
562
+ throw new FieldNotLoadedError(this.modelName, key, 'The currency of this monetary field is not loaded; load the field through the ORM (search/load), which loads currencies with it.');
563
+ }
564
+ return Money.of(raw, currency);
565
+ }
566
+ if (field.kind === 'quantity') {
567
+ if (raw === null)
568
+ return null;
569
+ const uomId = values.get(field.uomField);
570
+ const uom = typeof uomId === 'number' ? cache.uoms.get(uomId) : undefined;
571
+ if (uom === undefined)
572
+ return null;
573
+ return Quantity.of(raw, uom);
574
+ }
575
+ return raw;
576
+ }
577
+ }
578
+ function plain(value, field) {
579
+ if (value instanceof RecordSetImpl)
580
+ return field?.kind === 'many2one' ? value.ids[0] : [...value.ids];
581
+ if (value instanceof Money || value instanceof Quantity)
582
+ return value.toJSON();
583
+ if (value instanceof Date)
584
+ return value.toISOString();
585
+ if (DecimalJs.isDecimal(value))
586
+ return value.toFixed();
587
+ return value;
588
+ }
589
+ /** One subclass per model with an accessor per field, created on first use. Computed fields get a setter. */
590
+ function recordClass(model) {
591
+ let Ctor = prototypes.get(model);
592
+ if (Ctor === undefined) {
593
+ Ctor = class extends RecordSetImpl {
594
+ };
595
+ for (const [key, field] of Object.entries(model.fields)) {
596
+ if (key === 'id')
597
+ continue;
598
+ Object.defineProperty(Ctor.prototype, key, {
599
+ get() {
600
+ return this.fieldValue(key);
601
+ },
602
+ ...(field.computed
603
+ ? {
604
+ set(value) {
605
+ this.assign(key, value);
606
+ },
607
+ }
608
+ : {}),
609
+ enumerable: true,
610
+ });
611
+ }
612
+ // Model methods (declared and generated transitions) are callable on every recordset of the model.
613
+ for (const [name, fn] of Object.entries(model.methods))
614
+ Object.defineProperty(Ctor.prototype, name, {
615
+ value: fn,
616
+ writable: true,
617
+ configurable: true,
618
+ enumerable: false,
619
+ });
620
+ prototypes.set(model, Ctor);
621
+ }
622
+ return Ctor;
623
+ }
624
+ function recordsetOf(loader, model, ids) {
625
+ const Ctor = recordClass(model);
626
+ return new Ctor(loader.env, loader.registry.get(model.name), [...ids], { ids: [...ids] }, undefined);
627
+ }
628
+ function computeHost(loader) {
629
+ return {
630
+ internals: loader.internals,
631
+ load: (model, ids, spec) => loadInto(loader, model, ids, spec),
632
+ valueObjects: (model, ids, fields) => ensureValueObjects(loader, model, ids, fields),
633
+ values: (model, id, create) => valuesOf(loader.internals.cache, model, id, create),
634
+ recordset: (model, ids) => recordsetOf(loader, model, ids),
635
+ };
636
+ }
637
+ function onchangeHost(loader) {
638
+ const write = writeHost(loader);
639
+ return {
640
+ ...computeHost(loader),
641
+ defaults: write.defaults,
642
+ children: write.children,
643
+ read: (model, ids, keys) => recordsetOf(loader, model, ids).read(keys),
644
+ };
645
+ }
646
+ function writeHost(loader) {
647
+ return {
648
+ internals: loader.internals,
649
+ fetch: (model, ids, fields) => fetchMissing(loader, model, ids, fields),
650
+ ensureValueObjects: (model, ids, fields) => ensureValueObjects(loader, model, ids, fields),
651
+ defaults: (model) => withSiblings(model, defaultKeys(model)),
652
+ values: (model, id, create) => valuesOf(loader.internals.cache, model, id, create),
653
+ children: async (model, id, key) => {
654
+ await fetchX2Many(loader, model, key, [id], {
655
+ fields: new Set(['id']),
656
+ relations: new Map(),
657
+ });
658
+ return [
659
+ ...(valuesOf(loader.internals.cache, model.name, id)?.get(key) ??
660
+ []),
661
+ ];
662
+ },
663
+ recordset: (model, ids) => recordsetOf(loader, model, ids),
664
+ };
665
+ }
666
+ /** True when the domain has a relation path or an x2many `any` / `none` (it reads other models' tables). */
667
+ function followsRelations(model, where) {
668
+ for (const [key, value] of Object.entries(where ?? {})) {
669
+ if (key === 'or' || key === 'and') {
670
+ if (Array.isArray(value) &&
671
+ value.some((d) => followsRelations(model, d)))
672
+ return true;
673
+ }
674
+ else if (key === 'not') {
675
+ if (followsRelations(model, value))
676
+ return true;
677
+ }
678
+ else if (key.includes('.'))
679
+ return true;
680
+ else {
681
+ const kind = model.fields[key]?.kind;
682
+ if (kind === 'one2many' || kind === 'many2many')
683
+ return true;
684
+ }
685
+ }
686
+ return false;
687
+ }
688
+ function translationScope(internals) {
689
+ return {
690
+ lang: internals.env.lang,
691
+ source: internals.sourceLang,
692
+ company: internals.env.companyId,
693
+ ...(internals.asOf === undefined ? {} : { from: (m) => sourceOf(internals, m) }),
694
+ };
695
+ }
696
+ /** @internal The currency value object of a `res.currency` id, loaded through the cache. */
697
+ export async function currencyById(internals, id) {
698
+ const cached = internals.cache.currencies.get(id);
699
+ if (cached !== undefined)
700
+ return cached;
701
+ const loader = { env: internals.env, internals, registry: internals.registry };
702
+ const currency = internals.registry.get('res.currency').model;
703
+ await fetchMissing(loader, currency, [id], new Set(defaultKeys(currency)));
704
+ const v = valuesOf(internals.cache, currency.name, id);
705
+ const method = typeof v?.get('roundingMethod') === 'string'
706
+ ? String(v.get('roundingMethod')).replaceAll('_', '-')
707
+ : undefined;
708
+ const places = v?.get('decimalPlaces');
709
+ const built = defineCurrency({
710
+ code: String(v?.get('name')),
711
+ rounding: v?.get('rounding'),
712
+ ...(method === undefined ? {} : { roundingMethod: method }),
713
+ ...(typeof places === 'number' ? { decimalPlaces: places } : {}),
714
+ id,
715
+ });
716
+ internals.cache.currencies.set(id, built);
717
+ return built;
718
+ }
719
+ /** @internal The currency id of a company (`res.company.currency`). */
720
+ export async function companyCurrencyId(internals, company) {
721
+ const loader = { env: internals.env, internals, registry: internals.registry };
722
+ const model = internals.registry.get('res.company').model;
723
+ await fetchMissing(loader, model, [company], new Set(['currency']));
724
+ const id = valuesOf(internals.cache, model.name, company)?.get('currency');
725
+ if (typeof id !== 'number')
726
+ throw new MissingRecordError(model.name, [company]);
727
+ return id;
728
+ }
729
+ /** @internal Flushes the unit of work (every model, or one): pending computes first, then the dirty records. */
730
+ export async function flushAll(internals, model) {
731
+ const loader = { env: internals.env, internals, registry: internals.registry };
732
+ await recompute(computeHost(loader));
733
+ await checkConstraints(computeHost(loader));
734
+ await flushDirty(writeHost(loader), model);
735
+ await flushAudit(internals, model);
736
+ }
737
+ /** @internal `env.model(name)`. */
738
+ export function modelRef(env, name) {
739
+ const internals = internalsOf(env);
740
+ const registered = internals.registry.get(name);
741
+ const model = registered.model;
742
+ const loader = { env, internals, registry: internals.registry };
743
+ return {
744
+ modelName: name,
745
+ async create(rows) {
746
+ const ids = await createRecords(writeHost(loader), model, rows);
747
+ return new (recordClass(model))(env, registered, ids, { ids }, undefined);
748
+ },
749
+ async search(query = {}) {
750
+ assertAccess(internals, model, 'read');
751
+ assertDomainFields(internals, model, query.where);
752
+ assertFields(internals, model, (query.order ?? []).map((o) => o.split(' ')[0] ?? ''), 'read');
753
+ // The search must see pending writes (and computes): of every model when a relation path reaches others.
754
+ await internals.flush(followsRelations(model, query.where) ? undefined : model.name);
755
+ const fields = new Set(readableKeys(internals, model, withSiblings(model, defaultKeys(model))));
756
+ const wanted = [...fields].filter((k) => k !== 'id' && model.columns[k] !== undefined);
757
+ const columns = sql.join([
758
+ sql.id('id'),
759
+ ...wanted.map((k) => sql.id(model.columns[k] ?? '')),
760
+ ]);
761
+ const translation = translationScope(internals);
762
+ const conditions = [
763
+ ...compileDomain(model, query.where, translation, (n) => internals.registry.get(n).model, (target) => ruleConditions(internals, target, 'read')),
764
+ ...scopingConditions(model, env),
765
+ ...ruleConditions(internals, model, 'read'),
766
+ ];
767
+ const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
768
+ const limit = query.limit === undefined ? sql.empty : sql ` LIMIT ${query.limit}`;
769
+ const offset = query.offset === undefined ? sql.empty : sql ` OFFSET ${query.offset}`;
770
+ const rows = await internals.query(compile(sql `SELECT ${columns} FROM ${sourceOf(internals, model)}${where} ORDER BY ${compileOrder(model, query.order, translation)}${limit}${offset}`));
771
+ const ids = rows.map((row) => hydrate(loader, model, row, wanted));
772
+ await ensureValueObjects(loader, model, ids, fields);
773
+ return new (recordClass(model))(env, registered, ids, { ids }, undefined);
774
+ },
775
+ browse(ids) {
776
+ return new (recordClass(model))(env, registered, [...ids], { ids: [...ids] }, undefined);
777
+ },
778
+ onchange: (input) => runOnchange(onchangeHost(loader), model, input),
779
+ async copy(rows) {
780
+ const ids = await createRecords(writeHost(loader), model, rows, { copy: true });
781
+ return new (recordClass(model))(env, registered, ids, { ids }, undefined);
782
+ },
783
+ aggregate: (query) => runAggregate({
784
+ internals,
785
+ translation: translationScope(internals),
786
+ currency: (id) => currencyById(internals, id),
787
+ }, model, query),
788
+ };
789
+ }