shutro 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.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +60 -0
- package/dist/core/money/fx.js +109 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { IncompatibleUomCategoryError, InvalidUomError, UomMismatchError } from '../errors.js';
|
|
2
|
+
import { normalizeZero, toDecimal } from './decimal.js';
|
|
3
|
+
import { roundToUnit } from './rounding.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates a {@link Uom}.
|
|
6
|
+
* @throws {InvalidUomError} for an empty name or category, or a non-positive ratio or rounding.
|
|
7
|
+
*/
|
|
8
|
+
export function defineUom(input) {
|
|
9
|
+
const ratio = toDecimal(input.ratio);
|
|
10
|
+
const rounding = toDecimal(input.rounding);
|
|
11
|
+
if (input.name.trim() === '' || input.category.trim() === '') {
|
|
12
|
+
throw new InvalidUomError('A unit of measure needs a name and a category.', "Pass e.g. { name: 'kg', category: 'Weight', ... }.");
|
|
13
|
+
}
|
|
14
|
+
for (const [label, value] of [
|
|
15
|
+
['ratio', ratio],
|
|
16
|
+
['rounding', rounding],
|
|
17
|
+
]) {
|
|
18
|
+
if (value.isZero() || value.isNegative()) {
|
|
19
|
+
throw new InvalidUomError(`Unit ${input.name} has ${label} ${value.toFixed()}.`, `The ${label} must be positive (ratio: reference units per ${input.name}; rounding: smallest quantity).`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return Object.freeze({
|
|
23
|
+
name: input.name,
|
|
24
|
+
category: input.category,
|
|
25
|
+
ratio,
|
|
26
|
+
rounding,
|
|
27
|
+
id: input.id,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function sameUom(a, b) {
|
|
31
|
+
return a === b || (a.name === b.name && a.category === b.category && a.ratio.eq(b.ratio));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* An immutable quantity in one unit of measure. Mixing units requires an explicit {@link Quantity.to}, and
|
|
35
|
+
* conversion is only possible within a category.
|
|
36
|
+
*/
|
|
37
|
+
export class Quantity {
|
|
38
|
+
/** The exact value. */
|
|
39
|
+
value;
|
|
40
|
+
/** The unit. */
|
|
41
|
+
uom;
|
|
42
|
+
constructor(value, uom) {
|
|
43
|
+
this.value = value;
|
|
44
|
+
this.uom = uom;
|
|
45
|
+
Object.freeze(this);
|
|
46
|
+
}
|
|
47
|
+
/** A quantity of `value` in `uom`. */
|
|
48
|
+
static of(value, uom) {
|
|
49
|
+
return new Quantity(toDecimal(value), uom);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The same quantity in `target` (exact, unrounded): `Quantity.of(3, dozen).to(unit)` → 36 units.
|
|
53
|
+
* @throws {IncompatibleUomCategoryError} when the categories differ.
|
|
54
|
+
*/
|
|
55
|
+
to(target) {
|
|
56
|
+
if (this.uom.category !== target.category) {
|
|
57
|
+
throw new IncompatibleUomCategoryError(`Cannot convert ${this.uom.name} (${this.uom.category}) to ${target.name} (${target.category}).`, 'Units convert only within one category; check the product unit and the unit used on the document.');
|
|
58
|
+
}
|
|
59
|
+
if (sameUom(this.uom, target))
|
|
60
|
+
return this;
|
|
61
|
+
return new Quantity(normalizeZero(this.value.times(this.uom.ratio).dividedBy(target.ratio)), target);
|
|
62
|
+
}
|
|
63
|
+
/** `this + other`, same unit. @throws {UomMismatchError} */
|
|
64
|
+
plus(other) {
|
|
65
|
+
this.assertSameUom(other, 'add');
|
|
66
|
+
return new Quantity(this.value.plus(other.value), this.uom);
|
|
67
|
+
}
|
|
68
|
+
/** `this - other`, same unit. @throws {UomMismatchError} */
|
|
69
|
+
minus(other) {
|
|
70
|
+
this.assertSameUom(other, 'subtract');
|
|
71
|
+
return new Quantity(this.value.minus(other.value), this.uom);
|
|
72
|
+
}
|
|
73
|
+
/** `this × factor`, unrounded. */
|
|
74
|
+
times(factor) {
|
|
75
|
+
return new Quantity(this.value.times(toDecimal(factor)), this.uom);
|
|
76
|
+
}
|
|
77
|
+
/** Rounded to the unit's rounding (`half-up` unless given; procurement typically uses `up`). */
|
|
78
|
+
round(method = 'half-up') {
|
|
79
|
+
return new Quantity(roundToUnit(this.value, this.uom.rounding, method), this.uom);
|
|
80
|
+
}
|
|
81
|
+
/** True when the quantity rounds to zero in its unit. */
|
|
82
|
+
isZero() {
|
|
83
|
+
return this.round().value.isZero();
|
|
84
|
+
}
|
|
85
|
+
/** -1, 0 or 1 at the unit's precision. @throws {UomMismatchError} */
|
|
86
|
+
compare(other) {
|
|
87
|
+
this.assertSameUom(other, 'compare');
|
|
88
|
+
const c = this.round().value.cmp(other.round().value);
|
|
89
|
+
return c < 0 ? -1 : c > 0 ? 1 : 0;
|
|
90
|
+
}
|
|
91
|
+
/** Equal at the unit's precision. @throws {UomMismatchError} */
|
|
92
|
+
equals(other) {
|
|
93
|
+
return this.compare(other) === 0;
|
|
94
|
+
}
|
|
95
|
+
/** `{ value: '2.5', uom: 'kg' }`. */
|
|
96
|
+
toJSON() {
|
|
97
|
+
return { value: normalizeZero(this.value).toFixed(), uom: this.uom.name };
|
|
98
|
+
}
|
|
99
|
+
/** `'2.5 kg'`. */
|
|
100
|
+
toString() {
|
|
101
|
+
return `${normalizeZero(this.value).toFixed()} ${this.uom.name}`;
|
|
102
|
+
}
|
|
103
|
+
assertSameUom(other, operation) {
|
|
104
|
+
if (!sameUom(this.uom, other.uom)) {
|
|
105
|
+
throw new UomMismatchError(`Cannot ${operation} ${this.toString()} and ${other.toString()}: they are in different units.`, `Convert first, e.g. other.to(${this.uom.name}) with Quantity.to(uom).`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Decimal } from './decimal.js';
|
|
2
|
+
/**
|
|
3
|
+
* How to round to a currency's or unit's rounding unit:
|
|
4
|
+
* - `half-up`: halves away from zero (1.005 → 1.01, -1.005 → -1.01). Common accounting practice, Odoo's default.
|
|
5
|
+
* - `half-even`: banker's rounding (1.005 → 1.00, 1.015 → 1.02).
|
|
6
|
+
* - `up`: away from zero (1.001 → 1.01). For procurement quantities.
|
|
7
|
+
* - `down`: towards zero (1.009 → 1.00).
|
|
8
|
+
*/
|
|
9
|
+
export type RoundingMethod = 'half-up' | 'half-even' | 'up' | 'down';
|
|
10
|
+
/** Rounds `value` to a multiple of `unit` (e.g. 0.01, 0.05 for cash rounding, 1). */
|
|
11
|
+
export declare function roundToUnit(value: Decimal, unit: Decimal, method: RoundingMethod): Decimal;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
2
|
+
import { normalizeZero } from './decimal.js';
|
|
3
|
+
const MODES = {
|
|
4
|
+
'half-up': DecimalJs.ROUND_HALF_UP,
|
|
5
|
+
'half-even': DecimalJs.ROUND_HALF_EVEN,
|
|
6
|
+
up: DecimalJs.ROUND_UP,
|
|
7
|
+
down: DecimalJs.ROUND_DOWN,
|
|
8
|
+
};
|
|
9
|
+
/** Rounds `value` to a multiple of `unit` (e.g. 0.01, 0.05 for cash rounding, 1). */
|
|
10
|
+
export function roundToUnit(value, unit, method) {
|
|
11
|
+
return normalizeZero(value.dividedBy(unit).toDecimalPlaces(0, MODES[method]).times(unit));
|
|
12
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collecting the audit trail (RFC 0013 §7.2–7.3): rows of tracked changes are gathered per transaction attempt,
|
|
3
|
+
* coalesced per (record, field) and written at flush points in one statement, in the same transaction as the data.
|
|
4
|
+
*/
|
|
5
|
+
import { type AuditEntry, type AuditRowInput, type TrailFilter } from '../../audit/index.js';
|
|
6
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
7
|
+
import type { AnyModel } from '../model/model.js';
|
|
8
|
+
/** True when the model's `tracking` list or the field's `tracking` option names the field. */
|
|
9
|
+
export declare function isTracked(model: AnyModel, key: string): boolean;
|
|
10
|
+
/** Tracked field keys of a model (with the sibling currency / unit fields needed to render money). */
|
|
11
|
+
export declare function trackedKeys(model: AnyModel): Set<string>;
|
|
12
|
+
/** The JSON form of a cached value, as `read()` would return it (RFC 0013 §7.3). */
|
|
13
|
+
export declare function auditValue(internals: ScopeInternals, model: AnyModel, key: string, raw: unknown, siblings: (key: string) => unknown): unknown;
|
|
14
|
+
/** Records a change of a tracked field (no-op for untracked fields or with `flags.tracking` off). */
|
|
15
|
+
export declare function trackChange(internals: ScopeInternals, model: AnyModel, id: number, key: string, prev: unknown, next: unknown, siblings: (key: string) => unknown): void;
|
|
16
|
+
/** Records a creation or deletion with a snapshot of the tracked fields. */
|
|
17
|
+
export declare function trackSnapshot(internals: ScopeInternals, model: AnyModel, id: number, action: 'create' | 'unlink', values: ReadonlyMap<string, unknown>): void;
|
|
18
|
+
/** Records a superuser scope (RFC 0003 §7.6). */
|
|
19
|
+
export declare function trackSuperuser(internals: ScopeInternals, reason: string): void;
|
|
20
|
+
/** Coalesces `write` rows per (model, record, field): the first old, the last new; unchanged values are dropped. */
|
|
21
|
+
export declare function coalesceAudit(rows: readonly AuditRowInput[]): AuditRowInput[];
|
|
22
|
+
/** Writes the pending rows of `model` (or every row) in one statement. */
|
|
23
|
+
export declare function flushAudit(internals: ScopeInternals, model?: string): Promise<void>;
|
|
24
|
+
/** `records.trail()`: the rows of these records, newest first, after a flush. */
|
|
25
|
+
export declare function trailOf(internals: ScopeInternals, model: AnyModel, ids: readonly number[], filter: Omit<TrailFilter, 'model' | 'recordIds'>): Promise<AuditEntry[]>;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collecting the audit trail (RFC 0013 §7.2–7.3): rows of tracked changes are gathered per transaction attempt,
|
|
3
|
+
* coalesced per (record, field) and written at flush points in one statement, in the same transaction as the data.
|
|
4
|
+
*/
|
|
5
|
+
import { AUDIT_TABLE, auditTableStatements, insertAuditStatement, readTrail, } from '../../audit/index.js';
|
|
6
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
7
|
+
import { Money } from '../money/money.js';
|
|
8
|
+
const ensured = new WeakSet();
|
|
9
|
+
async function ensureTable(driver) {
|
|
10
|
+
if (ensured.has(driver))
|
|
11
|
+
return;
|
|
12
|
+
// Created by migrations in production (the application role may not own the schema); on first use otherwise.
|
|
13
|
+
const [row] = await driver.query({
|
|
14
|
+
text: `SELECT to_regclass('${AUDIT_TABLE}') IS NOT NULL AS present`,
|
|
15
|
+
params: [],
|
|
16
|
+
});
|
|
17
|
+
if (row?.present !== true)
|
|
18
|
+
for (const statement of auditTableStatements())
|
|
19
|
+
await driver.query(statement);
|
|
20
|
+
ensured.add(driver);
|
|
21
|
+
}
|
|
22
|
+
/** True when the model's `tracking` list or the field's `tracking` option names the field. */
|
|
23
|
+
export function isTracked(model, key) {
|
|
24
|
+
const field = model.fields[key];
|
|
25
|
+
if (field === undefined || field.kind === 'one2many' || field.kind === 'many2many')
|
|
26
|
+
return false;
|
|
27
|
+
return field.tracking || model.tracking.includes(key);
|
|
28
|
+
}
|
|
29
|
+
/** Tracked field keys of a model (with the sibling currency / unit fields needed to render money). */
|
|
30
|
+
export function trackedKeys(model) {
|
|
31
|
+
const keys = new Set();
|
|
32
|
+
for (const key of Object.keys(model.fields)) {
|
|
33
|
+
if (!isTracked(model, key))
|
|
34
|
+
continue;
|
|
35
|
+
keys.add(key);
|
|
36
|
+
const field = model.fields[key];
|
|
37
|
+
if (field?.currencyField !== undefined)
|
|
38
|
+
keys.add(field.currencyField);
|
|
39
|
+
if (field?.uomField !== undefined)
|
|
40
|
+
keys.add(field.uomField);
|
|
41
|
+
}
|
|
42
|
+
return keys;
|
|
43
|
+
}
|
|
44
|
+
/** The JSON form of a cached value, as `read()` would return it (RFC 0013 §7.3). */
|
|
45
|
+
export function auditValue(internals, model, key, raw, siblings) {
|
|
46
|
+
if (raw === undefined || raw === null)
|
|
47
|
+
return null;
|
|
48
|
+
if (model.fields[key]?.encrypted)
|
|
49
|
+
return '[encrypted]';
|
|
50
|
+
const field = model.fields[key];
|
|
51
|
+
if (field?.kind === 'monetary' && DecimalJs.isDecimal(raw)) {
|
|
52
|
+
const currencyId = siblings(field.currencyField ?? '');
|
|
53
|
+
const currency = typeof currencyId === 'number' ? internals.cache.currencies.get(currencyId) : undefined;
|
|
54
|
+
if (currency !== undefined)
|
|
55
|
+
return Money.of(raw, currency).toJSON(); // rounded like read()
|
|
56
|
+
return { amount: raw.toFixed(), currency: null };
|
|
57
|
+
}
|
|
58
|
+
if (field?.kind === 'quantity' && DecimalJs.isDecimal(raw)) {
|
|
59
|
+
const uomId = siblings(field.uomField ?? '');
|
|
60
|
+
const uom = typeof uomId === 'number' ? internals.cache.uoms.get(uomId) : undefined;
|
|
61
|
+
return { value: raw.toFixed(), uom: uom?.name ?? null };
|
|
62
|
+
}
|
|
63
|
+
if (DecimalJs.isDecimal(raw))
|
|
64
|
+
return raw.toFixed();
|
|
65
|
+
if (raw instanceof Date)
|
|
66
|
+
return raw.toISOString();
|
|
67
|
+
if (typeof raw === 'bigint')
|
|
68
|
+
return raw.toString();
|
|
69
|
+
return raw;
|
|
70
|
+
}
|
|
71
|
+
function base(internals) {
|
|
72
|
+
const { env } = internals;
|
|
73
|
+
return {
|
|
74
|
+
at: env.now(),
|
|
75
|
+
tx: internals.tx,
|
|
76
|
+
uid: env.uid,
|
|
77
|
+
companyId: env.companyId,
|
|
78
|
+
su: env.su,
|
|
79
|
+
reason: env.reason ?? null,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Records a change of a tracked field (no-op for untracked fields or with `flags.tracking` off). */
|
|
83
|
+
export function trackChange(internals, model, id, key, prev, next, siblings) {
|
|
84
|
+
if (!internals.env.flags.tracking || !isTracked(model, key) || id < 0)
|
|
85
|
+
return;
|
|
86
|
+
internals.auditRows.push({
|
|
87
|
+
...base(internals),
|
|
88
|
+
action: 'write',
|
|
89
|
+
model: model.name,
|
|
90
|
+
recordId: id,
|
|
91
|
+
field: key,
|
|
92
|
+
old: auditValue(internals, model, key, prev, siblings),
|
|
93
|
+
new: auditValue(internals, model, key, next, siblings),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/** Records a creation or deletion with a snapshot of the tracked fields. */
|
|
97
|
+
export function trackSnapshot(internals, model, id, action, values) {
|
|
98
|
+
if (!internals.env.flags.tracking || id < 0)
|
|
99
|
+
return;
|
|
100
|
+
const snapshot = {};
|
|
101
|
+
let any = false;
|
|
102
|
+
for (const key of Object.keys(model.fields)) {
|
|
103
|
+
if (!isTracked(model, key))
|
|
104
|
+
continue;
|
|
105
|
+
any = true;
|
|
106
|
+
snapshot[key] = values.has(key)
|
|
107
|
+
? auditValue(internals, model, key, values.get(key), (k) => values.get(k))
|
|
108
|
+
: null;
|
|
109
|
+
}
|
|
110
|
+
if (!any)
|
|
111
|
+
return;
|
|
112
|
+
internals.auditRows.push({
|
|
113
|
+
...base(internals),
|
|
114
|
+
action,
|
|
115
|
+
model: model.name,
|
|
116
|
+
recordId: id,
|
|
117
|
+
field: null,
|
|
118
|
+
old: action === 'unlink' ? snapshot : null,
|
|
119
|
+
new: action === 'create' ? snapshot : null,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** Records a superuser scope (RFC 0003 §7.6). */
|
|
123
|
+
export function trackSuperuser(internals, reason) {
|
|
124
|
+
if (!internals.env.flags.tracking)
|
|
125
|
+
return;
|
|
126
|
+
internals.auditRows.push({
|
|
127
|
+
...base(internals),
|
|
128
|
+
su: true,
|
|
129
|
+
reason,
|
|
130
|
+
action: 'su',
|
|
131
|
+
model: null,
|
|
132
|
+
recordId: null,
|
|
133
|
+
field: null,
|
|
134
|
+
old: null,
|
|
135
|
+
new: null,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
function same(a, b) {
|
|
139
|
+
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
140
|
+
}
|
|
141
|
+
/** Coalesces `write` rows per (model, record, field): the first old, the last new; unchanged values are dropped. */
|
|
142
|
+
export function coalesceAudit(rows) {
|
|
143
|
+
const out = [];
|
|
144
|
+
const writes = new Map();
|
|
145
|
+
const creates = new Map();
|
|
146
|
+
for (const row of rows) {
|
|
147
|
+
if (row.action !== 'write') {
|
|
148
|
+
if (row.action === 'create')
|
|
149
|
+
creates.set(`${row.model}|${row.recordId}`, out.length);
|
|
150
|
+
out.push(row);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
// A value first computed or numbered in the transaction that created the record belongs to its creation.
|
|
154
|
+
const created = creates.get(`${row.model}|${row.recordId}`);
|
|
155
|
+
if (created !== undefined && row.field !== null && (row.old ?? null) === null) {
|
|
156
|
+
const createRow = out[created];
|
|
157
|
+
const snapshot = { ...createRow.new };
|
|
158
|
+
if ((snapshot[row.field] ?? null) === null) {
|
|
159
|
+
snapshot[row.field] = row.new;
|
|
160
|
+
out[created] = { ...createRow, new: snapshot };
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const key = `${row.model}|${row.recordId}|${row.field}`;
|
|
165
|
+
const at = writes.get(key);
|
|
166
|
+
if (at === undefined) {
|
|
167
|
+
writes.set(key, out.length);
|
|
168
|
+
out.push(row);
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
const first = out[at];
|
|
172
|
+
out[at] = {
|
|
173
|
+
...first,
|
|
174
|
+
new: row.new,
|
|
175
|
+
uid: row.uid,
|
|
176
|
+
su: first.su || row.su,
|
|
177
|
+
reason: first.reason ?? row.reason,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return out.filter((row) => row.action !== 'write' || !same(row.old, row.new));
|
|
182
|
+
}
|
|
183
|
+
/** Writes the pending rows of `model` (or every row) in one statement. */
|
|
184
|
+
export async function flushAudit(internals, model) {
|
|
185
|
+
const rows = internals.auditRows;
|
|
186
|
+
if (rows.length === 0)
|
|
187
|
+
return;
|
|
188
|
+
const take = model === undefined ? rows.splice(0) : [];
|
|
189
|
+
if (model !== undefined) {
|
|
190
|
+
for (let i = rows.length - 1; i >= 0; i--) {
|
|
191
|
+
if (rows[i]?.model === model)
|
|
192
|
+
take.unshift(...rows.splice(i, 1));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const coalesced = coalesceAudit(take);
|
|
196
|
+
if (coalesced.length === 0)
|
|
197
|
+
return;
|
|
198
|
+
await ensureTable(internals.driver);
|
|
199
|
+
await internals.query(insertAuditStatement(coalesced));
|
|
200
|
+
}
|
|
201
|
+
/** `records.trail()`: the rows of these records, newest first, after a flush. */
|
|
202
|
+
export async function trailOf(internals, model, ids, filter) {
|
|
203
|
+
await internals.flush();
|
|
204
|
+
return readTrail({ query: (q) => internals.query(q) }, { ...filter, model: model.name, recordIds: ids });
|
|
205
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The compute engine at runtime (RFC 0008): trigger invalidation through the cache, resolution of triggers into the
|
|
3
|
+
* affected records (database + cache), batched recompute in rank order before flushes, computation of non-stored
|
|
4
|
+
* fields on load, and the assignment protocol inside computes.
|
|
5
|
+
*/
|
|
6
|
+
import type { ComputedField } from '../compute/graph.js';
|
|
7
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
8
|
+
import { type AnyModel } from '../model/model.js';
|
|
9
|
+
/** A load spec as the loader understands it (same shape as its normalized specs). */
|
|
10
|
+
export interface ComputeSpec {
|
|
11
|
+
readonly fields: ReadonlySet<string>;
|
|
12
|
+
readonly relations: ReadonlyMap<string, ComputeSpec>;
|
|
13
|
+
}
|
|
14
|
+
/** What the engine needs from the recordset runtime (passed in to avoid a module cycle). */
|
|
15
|
+
export interface ComputeHost {
|
|
16
|
+
readonly internals: ScopeInternals;
|
|
17
|
+
load(model: AnyModel, ids: readonly number[], spec: ComputeSpec): Promise<void>;
|
|
18
|
+
values(model: string, id: number, create?: boolean): Map<string, unknown> | undefined;
|
|
19
|
+
/** A recordset of `ids` (one prefetch group) to pass to compute functions. */
|
|
20
|
+
recordset(model: AnyModel, ids: readonly number[]): unknown;
|
|
21
|
+
}
|
|
22
|
+
/** Drops the cached values of the dependents of `(model, key)` that are in the cache (RFC 0008 §7.2). Cache only. */
|
|
23
|
+
export declare function invalidateCached(internals: ScopeInternals, model: string, key: string, ids: readonly number[]): void;
|
|
24
|
+
/** The load spec covering the `depends` of `fields` (RFC 0004 §7.5), plus the sibling currency / unit fields. */
|
|
25
|
+
export declare function dependsSpec(internals: ScopeInternals, model: AnyModel, fields: readonly ComputedField[]): ComputeSpec;
|
|
26
|
+
/** Assigns a computed value from inside its compute (the record accessors' setter). */
|
|
27
|
+
export declare function assignComputed(host: ComputeHost, model: AnyModel, id: number, key: string, value: unknown): void;
|
|
28
|
+
/**
|
|
29
|
+
* Computes `fields` of `model` for `ids`: loads their `depends` for the whole batch, runs each compute once, then
|
|
30
|
+
* checks required fields. Fields sharing a compute are computed together.
|
|
31
|
+
*/
|
|
32
|
+
export declare function computeFields(host: ComputeHost, model: AnyModel, ids: readonly number[], fields: readonly ComputedField[]): Promise<void>;
|
|
33
|
+
/** Recomputes every stored computed field with pending triggers, in rank order, until nothing is pending (RFC 0008 §7.3). */
|
|
34
|
+
export declare function recompute(host: ComputeHost): Promise<void>;
|