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,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dependency graph of computed fields (RFC 0008 §7.1): every `depends` path becomes triggers that say which
|
|
3
|
+
* computed field a change reaches and how to walk back to its records; computed fields get a rank so chains compute
|
|
4
|
+
* in order.
|
|
5
|
+
*/
|
|
6
|
+
import { ComputeCycleError, InvalidDependsPathError } from '../errors.js';
|
|
7
|
+
import { defaultDisplayName } from '../model/model.js';
|
|
8
|
+
function targetOf(field) {
|
|
9
|
+
return field.target;
|
|
10
|
+
}
|
|
11
|
+
function parsePath(models, model, path) {
|
|
12
|
+
const steps = [];
|
|
13
|
+
let current = model;
|
|
14
|
+
for (const key of path.split('.')) {
|
|
15
|
+
const f = current.fields[key];
|
|
16
|
+
if (f === undefined)
|
|
17
|
+
throw new Error(`Unchecked depends path '${path}' on ${model.name}.`); // the registry validated paths
|
|
18
|
+
const target = targetOf(f);
|
|
19
|
+
steps.push({
|
|
20
|
+
model: current.name,
|
|
21
|
+
key,
|
|
22
|
+
kind: f.kind,
|
|
23
|
+
target,
|
|
24
|
+
inverse: f.kind === 'one2many' ? f.inverseField : undefined,
|
|
25
|
+
});
|
|
26
|
+
if (target !== undefined) {
|
|
27
|
+
const next = models.get(target);
|
|
28
|
+
if (next === undefined)
|
|
29
|
+
throw new Error(`Unchecked target '${target}' in '${path}'.`);
|
|
30
|
+
current = next.model;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return steps;
|
|
34
|
+
}
|
|
35
|
+
/** Builds the graph for the registry's models. @throws {ComputeCycleError} */
|
|
36
|
+
export function buildComputeGraph(models) {
|
|
37
|
+
const fields = [];
|
|
38
|
+
const byName = new Map();
|
|
39
|
+
const pending = [];
|
|
40
|
+
for (const { model } of models.values()) {
|
|
41
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
42
|
+
if (!field.computed || field.compute === undefined)
|
|
43
|
+
continue;
|
|
44
|
+
const paths = field.compute === defaultDisplayName
|
|
45
|
+
? [model.recName]
|
|
46
|
+
: field.depends;
|
|
47
|
+
const parsed = paths.map((p) => parsePath(models, model, p));
|
|
48
|
+
const deps = new Set();
|
|
49
|
+
for (const steps of parsed) {
|
|
50
|
+
for (const step of steps) {
|
|
51
|
+
const stepField = models.get(step.model)?.model.fields[step.key];
|
|
52
|
+
if (stepField?.computed)
|
|
53
|
+
deps.add(`${step.model}.${step.key}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
pending.push({
|
|
57
|
+
field: {
|
|
58
|
+
model: model.name,
|
|
59
|
+
key,
|
|
60
|
+
stored: field.store,
|
|
61
|
+
compute: field.compute,
|
|
62
|
+
paths: parsed,
|
|
63
|
+
},
|
|
64
|
+
deps,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// Ranks by depth-first search with cycle detection.
|
|
69
|
+
const ranks = new Map();
|
|
70
|
+
const visiting = [];
|
|
71
|
+
const byKey = new Map(pending.map((p) => [`${p.field.model}.${p.field.key}`, p]));
|
|
72
|
+
const rankOf = (name) => {
|
|
73
|
+
const known = ranks.get(name);
|
|
74
|
+
if (known !== undefined)
|
|
75
|
+
return known;
|
|
76
|
+
const entry = byKey.get(name);
|
|
77
|
+
if (entry === undefined)
|
|
78
|
+
return 0;
|
|
79
|
+
const at = visiting.indexOf(name);
|
|
80
|
+
if (at >= 0)
|
|
81
|
+
throw new ComputeCycleError([...visiting.slice(at), name]);
|
|
82
|
+
visiting.push(name);
|
|
83
|
+
let rank = 0;
|
|
84
|
+
for (const dep of entry.deps)
|
|
85
|
+
rank = Math.max(rank, rankOf(dep) + 1);
|
|
86
|
+
visiting.pop();
|
|
87
|
+
ranks.set(name, rank);
|
|
88
|
+
return rank;
|
|
89
|
+
};
|
|
90
|
+
for (const p of pending) {
|
|
91
|
+
const name = `${p.field.model}.${p.field.key}`;
|
|
92
|
+
const built = { ...p.field, rank: rankOf(name) };
|
|
93
|
+
fields.push(built);
|
|
94
|
+
byName.set(name, built);
|
|
95
|
+
}
|
|
96
|
+
const triggers = new Map();
|
|
97
|
+
const inverses = new Map();
|
|
98
|
+
const add = (model, key, trigger) => {
|
|
99
|
+
let byField = triggers.get(model);
|
|
100
|
+
if (byField === undefined) {
|
|
101
|
+
byField = new Map();
|
|
102
|
+
triggers.set(model, byField);
|
|
103
|
+
}
|
|
104
|
+
let list = byField.get(key);
|
|
105
|
+
if (list === undefined) {
|
|
106
|
+
list = [];
|
|
107
|
+
byField.set(key, list);
|
|
108
|
+
}
|
|
109
|
+
list.push(trigger);
|
|
110
|
+
};
|
|
111
|
+
for (const field of fields) {
|
|
112
|
+
for (const steps of field.paths) {
|
|
113
|
+
steps.forEach((step, i) => {
|
|
114
|
+
add(step.model, step.key, { field, reverse: steps.slice(0, i) });
|
|
115
|
+
if (step.kind === 'one2many' && step.target !== undefined && step.inverse !== undefined) {
|
|
116
|
+
let set = inverses.get(step.target);
|
|
117
|
+
if (set === undefined) {
|
|
118
|
+
set = new Set();
|
|
119
|
+
inverses.set(step.target, set);
|
|
120
|
+
}
|
|
121
|
+
set.add(step.inverse);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// Constraints: depends are same-model field keys (RFC 0009 §7.1).
|
|
127
|
+
const constraintIndex = new Map();
|
|
128
|
+
for (const { model } of models.values()) {
|
|
129
|
+
for (const c of model.constraints) {
|
|
130
|
+
for (const dep of c.depends) {
|
|
131
|
+
if (dep.includes('.') || model.fields[dep] === undefined) {
|
|
132
|
+
throw new InvalidDependsPathError(`The depends '${dep}' of constraint '${c.key}' on '${model.name}' is not a field of the model.`, 'Constraint depends are field keys of the model itself (no dotted paths); put the rule on the model that owns the data, or depend on a computed field.');
|
|
133
|
+
}
|
|
134
|
+
let byKey = constraintIndex.get(model.name);
|
|
135
|
+
if (byKey === undefined) {
|
|
136
|
+
byKey = new Map();
|
|
137
|
+
constraintIndex.set(model.name, byKey);
|
|
138
|
+
}
|
|
139
|
+
byKey.set(dep, [...(byKey.get(dep) ?? []), c]);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const noConstraints = Object.freeze([]);
|
|
144
|
+
const none = Object.freeze([]);
|
|
145
|
+
const empty = new Set();
|
|
146
|
+
const storedByModel = new Map();
|
|
147
|
+
for (const f of fields) {
|
|
148
|
+
if (!f.stored)
|
|
149
|
+
continue;
|
|
150
|
+
const list = storedByModel.get(f.model) ?? [];
|
|
151
|
+
list.push(f);
|
|
152
|
+
storedByModel.set(f.model, list);
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
fields: Object.freeze(fields),
|
|
156
|
+
triggers,
|
|
157
|
+
field: (model, key) => byName.get(`${model}.${key}`),
|
|
158
|
+
stored: (model) => storedByModel.get(model) ?? none,
|
|
159
|
+
inverseKeys: (model) => inverses.get(model) ?? empty,
|
|
160
|
+
constraints: (model, key) => constraintIndex.get(model)?.get(key) ?? noConstraints,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import type { AuditRowInput } from '../../audit/index.js';
|
|
3
|
+
import { type Driver, type DriverConnection, type DriverQuery, type Row } from '../../driver-pg/index.js';
|
|
4
|
+
import type { KeyRing, Perm } from '../../security/index.js';
|
|
5
|
+
import { type Fx } from '../money/fx.js';
|
|
6
|
+
import { type RecordCache } from '../recordset/recordset.js';
|
|
7
|
+
import type { ModelName, ModelRef } from '../recordset/types.js';
|
|
8
|
+
import type { Registry } from '../registry/registry.js';
|
|
9
|
+
import { type Identity, type ResolvedIdentity } from './identity.js';
|
|
10
|
+
import type { Inspector } from './inspector.js';
|
|
11
|
+
/** Typed context flags (RFC 0003 §7.4). Module-contributed flags arrive with the registry's second half. */
|
|
12
|
+
export interface Flags {
|
|
13
|
+
/** Searches hide archived records. Default `true`. */
|
|
14
|
+
readonly activeTest: boolean;
|
|
15
|
+
/** Audit / tracking messages are written. Default `true` (imports may turn it off). */
|
|
16
|
+
readonly tracking: boolean;
|
|
17
|
+
/** Multi-company consistency checks and scoping. Default `true`; only a superuser environment may disable it. */
|
|
18
|
+
readonly checkCompany: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** A function registered with {@link Env.afterCommit} or {@link Env.onRollback}. */
|
|
21
|
+
export type Hook = () => void | Promise<void>;
|
|
22
|
+
/** Options of {@link Shutro.run}: the identity plus per-run transaction settings. */
|
|
23
|
+
export interface RunOptions extends Identity {
|
|
24
|
+
/** `BEGIN … READ ONLY`. Reports and replica-safe work. */
|
|
25
|
+
readonly readOnly?: boolean;
|
|
26
|
+
/** `false` disables automatic retries, e.g. for handlers that stream a response (RFC 0003 Q1). */
|
|
27
|
+
readonly retry?: false;
|
|
28
|
+
}
|
|
29
|
+
/** Query statistics of the current attempt. */
|
|
30
|
+
export interface ScopeStats {
|
|
31
|
+
readonly queries: number;
|
|
32
|
+
}
|
|
33
|
+
/** An undo record for savepoint rollback (RFC 0004 §7.6). */
|
|
34
|
+
export type JournalEntry = {
|
|
35
|
+
readonly kind: 'value';
|
|
36
|
+
readonly model: string;
|
|
37
|
+
readonly id: number;
|
|
38
|
+
readonly key: string;
|
|
39
|
+
readonly had: boolean;
|
|
40
|
+
readonly prev: unknown;
|
|
41
|
+
readonly wasDirty: boolean;
|
|
42
|
+
} | {
|
|
43
|
+
readonly kind: 'created';
|
|
44
|
+
readonly model: string;
|
|
45
|
+
readonly id: number;
|
|
46
|
+
} | {
|
|
47
|
+
readonly kind: 'deleted';
|
|
48
|
+
readonly model: string;
|
|
49
|
+
readonly id: number;
|
|
50
|
+
readonly values: Map<string, unknown>;
|
|
51
|
+
readonly dirty: Set<string> | undefined;
|
|
52
|
+
};
|
|
53
|
+
/** A transaction or savepoint. */
|
|
54
|
+
interface Scope {
|
|
55
|
+
readonly root: RootScope;
|
|
56
|
+
readonly parent: Scope | undefined;
|
|
57
|
+
readonly conn: DriverConnection;
|
|
58
|
+
status: 'open' | 'committed' | 'rolled-back';
|
|
59
|
+
env: Env;
|
|
60
|
+
readonly afterCommit: Hook[];
|
|
61
|
+
readonly onRollback: Hook[];
|
|
62
|
+
/** Cache changes made in this savepoint, for undo; `undefined` for the root transaction. */
|
|
63
|
+
readonly journal: JournalEntry[] | undefined;
|
|
64
|
+
}
|
|
65
|
+
interface RootScope {
|
|
66
|
+
/** The innermost open scope: the only one whose env may run statements. */
|
|
67
|
+
top: Scope;
|
|
68
|
+
readonly attempt: number;
|
|
69
|
+
readonly now: Date;
|
|
70
|
+
queries: number;
|
|
71
|
+
/** Identity map and value-object caches (RFC 0004 §7.4), shared by the savepoints of this attempt. */
|
|
72
|
+
readonly cache: RecordCache;
|
|
73
|
+
/** Unit of work: model → id → dirty field keys. */
|
|
74
|
+
readonly dirty: Map<string, Map<number, Set<string>>>;
|
|
75
|
+
/** Raw compute triggers: model → key → changed ids (RFC 0008 §7.2). */
|
|
76
|
+
readonly triggers: Map<string, Map<string, Set<number>>>;
|
|
77
|
+
/** Records marked for computation directly (new records): model → key → ids. */
|
|
78
|
+
readonly toCompute: Map<string, Map<string, Set<number>>>;
|
|
79
|
+
/** Records to check: model → constraint key → ids (RFC 0009 §7.1). */
|
|
80
|
+
readonly toCheck: Map<string, Map<string, Set<number>>>;
|
|
81
|
+
readonly compute: ComputeState;
|
|
82
|
+
/** Pending audit rows of this attempt (RFC 0013 §7.2). */
|
|
83
|
+
readonly audit: AuditRowInput[];
|
|
84
|
+
/** Groups the audit rows of this attempt. */
|
|
85
|
+
readonly tx: string;
|
|
86
|
+
/** Next virtual id for drafts (negative, RFC 0009 §7.4). */
|
|
87
|
+
virtual: number;
|
|
88
|
+
readonly uid: number;
|
|
89
|
+
}
|
|
90
|
+
/** Compute-engine state of an attempt (RFC 0008 §7.3, §7.5). */
|
|
91
|
+
export interface ComputeState {
|
|
92
|
+
recomputing: boolean;
|
|
93
|
+
/** `model.key` names being computed right now (assignment is allowed for them). */
|
|
94
|
+
readonly computing: Set<string>;
|
|
95
|
+
/** `model.key` → ids computed in the current round: invalidation and re-triggering skip them. */
|
|
96
|
+
readonly protected: Map<string, Set<number>>;
|
|
97
|
+
/** `model.key` → id → the value invalidated by a trigger, for the audit row of the recompute (RFC 0013). */
|
|
98
|
+
readonly previous: Map<string, Map<number, unknown>>;
|
|
99
|
+
}
|
|
100
|
+
interface Runtime {
|
|
101
|
+
readonly als: AsyncLocalStorage<Scope>;
|
|
102
|
+
readonly onHookError: (error: unknown, phase: 'afterCommit' | 'onRollback') => void;
|
|
103
|
+
readonly registry: Registry | undefined;
|
|
104
|
+
/** Dev-mode query inspector, if any. */
|
|
105
|
+
readonly inspector: Inspector | undefined;
|
|
106
|
+
/** The pool, for autonomous transactions (standard sequences, RFC 0012 §7.2). */
|
|
107
|
+
readonly driver: Driver;
|
|
108
|
+
/** Encryption keys for `encrypted` fields (RFC 0014 §7.6), or none. */
|
|
109
|
+
readonly keys: KeyRing | undefined;
|
|
110
|
+
/** The language translations fall back to (RFC 0011). */
|
|
111
|
+
readonly sourceLang: string;
|
|
112
|
+
}
|
|
113
|
+
/** @internal What the recordset runtime needs from an environment. */
|
|
114
|
+
export interface ScopeInternals {
|
|
115
|
+
readonly env: Env;
|
|
116
|
+
readonly registry: Registry;
|
|
117
|
+
readonly cache: RecordCache;
|
|
118
|
+
readonly uid: number;
|
|
119
|
+
readonly now: Date;
|
|
120
|
+
query<R extends Row>(query: DriverQuery): Promise<readonly R[]>;
|
|
121
|
+
/** `COPY ... FROM STDIN` on the scope's connection (RFC 0015 §7.1); returns the row count. */
|
|
122
|
+
copyIn(query: DriverQuery, lines: Iterable<string>): Promise<number>;
|
|
123
|
+
/** Records an undo entry when a savepoint is active. */
|
|
124
|
+
journal(entry: JournalEntry): void;
|
|
125
|
+
markDirty(model: string, id: number, key: string): void;
|
|
126
|
+
isDirty(model: string, id: number, key: string): boolean;
|
|
127
|
+
dirtyFields(model: string, id: number): Set<string> | undefined;
|
|
128
|
+
dirtyModels(): string[];
|
|
129
|
+
/** Removes and returns the dirty map of a model. */
|
|
130
|
+
takeDirty(model: string): Map<number, Set<string>> | undefined;
|
|
131
|
+
/** Drops a record from the cache and the unit of work. */
|
|
132
|
+
forget(model: string, id: number): void;
|
|
133
|
+
cachedValues(model: string): Iterable<Map<string, unknown>>;
|
|
134
|
+
readonly sourceLang: string;
|
|
135
|
+
readonly driver: Driver;
|
|
136
|
+
readonly keys: KeyRing | undefined;
|
|
137
|
+
/** Pending audit rows (RFC 0013 §7.2). */
|
|
138
|
+
readonly auditRows: AuditRowInput[];
|
|
139
|
+
readonly tx: string;
|
|
140
|
+
flush(model?: string): Promise<void>;
|
|
141
|
+
/** Records that `(model, key)` changed for `ids` and invalidates cached dependents (RFC 0008 §7.2). */
|
|
142
|
+
trigger(model: string, key: string, ids: readonly number[]): void;
|
|
143
|
+
/** Marks `ids` for computation of the stored computed field `key` (new records). */
|
|
144
|
+
markToCompute(model: string, key: string, ids: readonly number[]): void;
|
|
145
|
+
takeTriggers(): Map<string, Map<string, Set<number>>>;
|
|
146
|
+
takeToCompute(): Map<string, Map<string, Set<number>>>;
|
|
147
|
+
hasPending(): boolean;
|
|
148
|
+
takeToCheck(): Map<string, Map<string, Set<number>>>;
|
|
149
|
+
hasChecks(): boolean;
|
|
150
|
+
/** A fresh negative id for a draft record (RFC 0009 §7.4). */
|
|
151
|
+
nextVirtualId(): number;
|
|
152
|
+
readonly compute: ComputeState;
|
|
153
|
+
}
|
|
154
|
+
/** @internal */
|
|
155
|
+
export declare function internalsOf(env: Env): ScopeInternals;
|
|
156
|
+
/**
|
|
157
|
+
* The environment (RFC 0003): who is acting, for which company, how, and in which transaction. Immutable; the
|
|
158
|
+
* `with*` methods return derived environments that share the transaction scope. `S` is the schema view of the
|
|
159
|
+
* registry (model name → model), which types `model()`.
|
|
160
|
+
*/
|
|
161
|
+
export declare class Env<S = unknown> {
|
|
162
|
+
#private;
|
|
163
|
+
/** Id of the acting user. */
|
|
164
|
+
readonly uid: number;
|
|
165
|
+
/** Current company id. */
|
|
166
|
+
readonly companyId: number;
|
|
167
|
+
/** Allowed company ids (record-rule scope). */
|
|
168
|
+
readonly companyIds: readonly number[];
|
|
169
|
+
readonly lang: string;
|
|
170
|
+
/** The language translatable fields fall back to when `lang` has no text (RFC 0011). */
|
|
171
|
+
readonly sourceLang: string;
|
|
172
|
+
readonly tz: string;
|
|
173
|
+
/** Superuser mode: only inside {@link asSuperuser}. */
|
|
174
|
+
readonly su: boolean;
|
|
175
|
+
/** Reason for a job or superuser scope, when given. */
|
|
176
|
+
readonly reason: string | undefined;
|
|
177
|
+
/** The user's security groups, closed over `implies` (RFC 0014 §7.1). */
|
|
178
|
+
readonly groups: ReadonlySet<string>;
|
|
179
|
+
/** @internal Encryption keys. */
|
|
180
|
+
readonly keys: KeyRing | undefined;
|
|
181
|
+
readonly flags: Flags;
|
|
182
|
+
/** 1 for the first attempt of `run()`, 2+ for retries after a serialization failure or deadlock. */
|
|
183
|
+
readonly attempt: number;
|
|
184
|
+
readonly readOnly: boolean;
|
|
185
|
+
/** @internal */
|
|
186
|
+
constructor(identity: ResolvedIdentity & {
|
|
187
|
+
readonly su: boolean;
|
|
188
|
+
readonly flags: Flags;
|
|
189
|
+
readonly readOnly: boolean;
|
|
190
|
+
}, scope: Scope, runtime: Runtime);
|
|
191
|
+
/** An empty recordset of `name`: `search()` / `browse()` / `create()` start here (RFC 0004). */
|
|
192
|
+
model<M extends ModelName<S>>(name: M): ModelRef<S, M>;
|
|
193
|
+
/** What this environment may do (RFC 0014): for Kosh menus, export / import buttons and API guards. */
|
|
194
|
+
get access(): {
|
|
195
|
+
can(model: ModelName<S>, perm: Perm): boolean;
|
|
196
|
+
/** @throws {AccessError} */
|
|
197
|
+
check(model: ModelName<S>, perm: Perm): void;
|
|
198
|
+
canField(model: ModelName<S>, field: string, kind: 'read' | 'write'): boolean;
|
|
199
|
+
};
|
|
200
|
+
/** Dated, per-company currency conversion (RFC 0006 §7.6). Needs a `res.currency.rate` model. */
|
|
201
|
+
get fx(): Fx;
|
|
202
|
+
/** The transaction timestamp (PostgreSQL `now()`), stable within an attempt. Returns a fresh `Date` each call. */
|
|
203
|
+
now(): Date;
|
|
204
|
+
/** Today's calendar date (`'YYYY-MM-DD'`) in the environment's time zone. */
|
|
205
|
+
today(): string;
|
|
206
|
+
/** Today's calendar date in another time zone. */
|
|
207
|
+
todayIn(tz: string): string;
|
|
208
|
+
/** Writes every pending change of the unit of work to the database now (RFC 0004 §7.6). */
|
|
209
|
+
flush(): Promise<void>;
|
|
210
|
+
/** Statistics of the current attempt (query counts for N+1 assertions, RFC 0004 §7.9). */
|
|
211
|
+
stats(): ScopeStats;
|
|
212
|
+
/**
|
|
213
|
+
* Raw SQL in this transaction (RFC 0005 §7.8): values become parameters, identifiers go through `sql.id()`.
|
|
214
|
+
* Pending writes are flushed first. Rejects with {@link TransactionScopeError} when the scope has ended or
|
|
215
|
+
* another scope is active.
|
|
216
|
+
*/
|
|
217
|
+
sql<R extends Row = Row>(strings: TemplateStringsArray, ...values: readonly unknown[]): Promise<readonly R[]>;
|
|
218
|
+
/**
|
|
219
|
+
* Runs `fn` in a savepoint: its database work and its cache changes are undone if it throws, kept otherwise.
|
|
220
|
+
* Pending writes are flushed before the savepoint is released.
|
|
221
|
+
*/
|
|
222
|
+
transaction<T>(fn: (env: Env<S>) => Promise<T>): Promise<T>;
|
|
223
|
+
/** Registers work to run only after the outermost transaction commits (emails, webhooks, queue messages). */
|
|
224
|
+
afterCommit(hook: Hook): void;
|
|
225
|
+
/** Registers work to run if this scope rolls back (cleanup of external resources). */
|
|
226
|
+
onRollback(hook: Hook): void;
|
|
227
|
+
/** The same scope with another current company. Must be allowed unless `su`. @throws {CompanyNotAllowedError} */
|
|
228
|
+
withCompany(company: number): Env<S>;
|
|
229
|
+
/** The same scope with another language. */
|
|
230
|
+
withLang(lang: string): Env<S>;
|
|
231
|
+
/** The same scope with another time zone. */
|
|
232
|
+
withTz(tz: string): Env<S>;
|
|
233
|
+
/** The same scope with some flags changed. `checkCompany: false` needs `su`. @throws {FlagNotAllowedError} */
|
|
234
|
+
withFlags(flags: Partial<Flags>): Env<S>;
|
|
235
|
+
/**
|
|
236
|
+
* Runs `fn` with a superuser environment in the same scope. The elevation never leaks: only `su` and values
|
|
237
|
+
* returned by `fn` leave the callback, and `reason` is recorded for the audit trail (RFC 0003 §7.6).
|
|
238
|
+
*/
|
|
239
|
+
asSuperuser<T>(options: {
|
|
240
|
+
readonly reason: string;
|
|
241
|
+
}, fn: (su: Env<S>) => Promise<T>): Promise<T>;
|
|
242
|
+
}
|
|
243
|
+
/** Options of {@link createShutro}. */
|
|
244
|
+
export interface ShutroOptions<S> {
|
|
245
|
+
readonly driver: Driver;
|
|
246
|
+
/** The registry built from the application's modules. Without it, `env.model()` is unavailable. */
|
|
247
|
+
readonly registry?: Registry<S>;
|
|
248
|
+
/** The source language of translatable fields: what readers of a language without text see. Default `en_US`. */
|
|
249
|
+
readonly sourceLang?: string;
|
|
250
|
+
/** Keys for `encrypted` fields (RFC 0014 §7.6): `createKeyRing({ current, keys })`. */
|
|
251
|
+
readonly keys?: KeyRing;
|
|
252
|
+
/** Dev-mode query inspector (`createInspector()`): SQL, timings, N+1 warnings. */
|
|
253
|
+
readonly inspector?: Inspector;
|
|
254
|
+
/**
|
|
255
|
+
* Verifies identities against the application's data (RFC 0014 §7.1, docs/feedback.md #6): returns the user's
|
|
256
|
+
* allowed companies and groups, or `null` for an unknown or disabled user. When set, `run()` refuses companies
|
|
257
|
+
* outside the allowed set and groups the user does not have, and uses the loaded groups when none are given.
|
|
258
|
+
*/
|
|
259
|
+
readonly identity?: (uid: number) => Promise<VerifiedIdentity | null>;
|
|
260
|
+
/** Retry policy for serialization failures and deadlocks. Default: 5 attempts with jittered exponential backoff. */
|
|
261
|
+
readonly retry?: {
|
|
262
|
+
readonly attempts?: number;
|
|
263
|
+
/** Delay before attempt `attempt` (2+), in milliseconds. */
|
|
264
|
+
readonly backoffMs?: (attempt: number) => number;
|
|
265
|
+
};
|
|
266
|
+
/**
|
|
267
|
+
* Called when an `afterCommit` / `onRollback` hook throws (the transaction outcome is already decided, so the
|
|
268
|
+
* error cannot be surfaced to the caller). Defaults to `process.emitWarning`.
|
|
269
|
+
*/
|
|
270
|
+
readonly onHookError?: (error: unknown, phase: 'afterCommit' | 'onRollback') => void;
|
|
271
|
+
}
|
|
272
|
+
/** What an identity loader returns for a user. */
|
|
273
|
+
export interface VerifiedIdentity {
|
|
274
|
+
readonly companies: readonly number[];
|
|
275
|
+
readonly groups: readonly string[];
|
|
276
|
+
}
|
|
277
|
+
/** A Shutro instance: one driver, one registry, one AsyncLocalStorage. No global state (`CLAUDE.md`). */
|
|
278
|
+
export interface Shutro<S = unknown> {
|
|
279
|
+
/**
|
|
280
|
+
* Runs `fn` in one transaction with the given identity (RFC 0003 §7.1): `REPEATABLE READ`, identity pushed as
|
|
281
|
+
* `SET LOCAL` settings (`shutro.user_id`, `shutro.company_ids`), `TimeZone = UTC`. Pending writes are flushed
|
|
282
|
+
* before commit. Commits when `fn` resolves, rolls back when it throws. Serialization failures and deadlocks
|
|
283
|
+
* re-run `fn` from scratch with a fresh scope (so `fn` must have no side effects outside the database; use
|
|
284
|
+
* `env.afterCommit`).
|
|
285
|
+
*
|
|
286
|
+
* @throws {InvalidIdentityError} before any transaction starts.
|
|
287
|
+
* @throws {ConcurrentUpdateError} when every attempt conflicted.
|
|
288
|
+
*/
|
|
289
|
+
run<T>(options: RunOptions, fn: (env: Env<S>) => Promise<T>): Promise<T>;
|
|
290
|
+
/** The environment of the innermost active scope. @throws {NoEnvironmentError} outside `run()`. */
|
|
291
|
+
currentEnv(): Env<S>;
|
|
292
|
+
}
|
|
293
|
+
/** Creates a {@link Shutro} instance on a driver (and a registry). */
|
|
294
|
+
export declare function createShutro<S = unknown>(options: ShutroOptions<S>): Shutro<S>;
|
|
295
|
+
export {};
|