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,177 @@
1
+ /**
2
+ * Value normalization shared by writes and computes: validates one value against its field and converts it to what
3
+ * the cache holds (Decimal amounts, ids, ...), and converts cached values into what the driver binds.
4
+ */
5
+ import { isTranslations, mergeTranslation } from '../../i18n/index.js';
6
+ import { sql } from '../../sql/index.js';
7
+ import { Decimal as DecimalJs } from 'decimal.js';
8
+ /** The value of a company-dependent field for `company` (the default when the company has none). */
9
+ export function companyValue(field, stored, company) {
10
+ const map = (stored ?? {});
11
+ const raw = Object.hasOwn(map, String(company))
12
+ ? map[String(company)]
13
+ : typeof field.default === 'function'
14
+ ? null
15
+ : (field.default ?? null);
16
+ if (raw === null || raw === undefined)
17
+ return null;
18
+ if (field.kind === 'decimal')
19
+ return new DecimalJs(String(raw));
20
+ if (field.kind === 'many2one' || field.kind === 'integer' || field.kind === 'float')
21
+ return Number(raw);
22
+ return raw;
23
+ }
24
+ import { CurrencyMismatchError, UomMismatchError, ValidationError } from '../errors.js';
25
+ import { toDecimal } from '../money/decimal.js';
26
+ import { Money } from '../money/money.js';
27
+ import { Quantity } from '../money/quantity.js';
28
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
29
+ /** Throws a {@link ValidationError} for `model`. */
30
+ export function fail(model, fields, problem, hint) {
31
+ throw new ValidationError(model.name, fields, problem, hint);
32
+ }
33
+ /** The PostgreSQL array element type for a field (for `unnest($n::type[])`). */
34
+ export function arrayType(field) {
35
+ // JSON travels as text and is cast in SQL (columnCast): array parameters of jsonb would be re-encoded by the driver.
36
+ if (columnCast(field) !== undefined)
37
+ return 'text';
38
+ if (field.kind === 'many2one')
39
+ return 'bigint';
40
+ return field.pgType;
41
+ }
42
+ /** The SQL cast applied to a bound value before it reaches the column (`jsonb` for json and translatable fields). */
43
+ export function columnCast(field) {
44
+ return field.kind === 'json' || field.translate || field.companyDependent ? 'jsonb' : undefined;
45
+ }
46
+ /** A reference to the bound value of `column` in the `v` row alias, cast when needed. */
47
+ export function valueRef(field, column) {
48
+ const ref = sql.id('v', column);
49
+ return columnCast(field) === undefined ? ref : sql `${ref}::jsonb`;
50
+ }
51
+ /** Converts a cached value into what the driver binds. */
52
+ export function bindValue(field, value) {
53
+ if (value === null || value === undefined)
54
+ return null;
55
+ if (DecimalJs.isDecimal(value))
56
+ return value.toFixed();
57
+ // Inside arrays, postgres.js would type a Date as a scalar timestamptz; an ISO string lets the ::timestamptz[] cast apply.
58
+ if (value instanceof Date)
59
+ return value.toISOString();
60
+ if (field.kind === 'json' || field.translate || field.companyDependent)
61
+ return JSON.stringify(value);
62
+ return value;
63
+ }
64
+ /**
65
+ * Validates and normalizes one value for storage in the cache. `siblings` gives the record's current currency / unit
66
+ * id for `Money` / `Quantity` checks.
67
+ */
68
+ export function normalize(model, key, field, value, siblings, translation) {
69
+ if (field.companyDependent) {
70
+ const company = translation?.company;
71
+ if (company === undefined)
72
+ fail(model, [key], 'is company-dependent but no company is known.', 'Write it inside shutro.run({ company }).');
73
+ const plain = value === null
74
+ ? null
75
+ : normalize(model, key, { ...field, companyDependent: false }, value, siblings, translation);
76
+ const existing = siblings(key);
77
+ const map = typeof existing === 'object' && existing !== null ? existing : {};
78
+ return Object.freeze({
79
+ ...map,
80
+ [String(company)]: DecimalJs.isDecimal(plain) ? plain.toFixed() : plain,
81
+ });
82
+ }
83
+ const bad = (what, hint) => fail(model, [key], `field '${key}' ${what}.`, hint);
84
+ if (value === null) {
85
+ if (field.required)
86
+ bad('is required and cannot be null', 'Give the field a value.');
87
+ return null;
88
+ }
89
+ switch (field.kind) {
90
+ case 'many2one': {
91
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0)
92
+ return value;
93
+ const ids = value.ids;
94
+ if (Array.isArray(ids) && ids.length === 1)
95
+ return ids[0];
96
+ return bad(`expects a record id (got ${typeof value})`, 'Pass the id of the related record, or a single record.');
97
+ }
98
+ case 'monetary': {
99
+ if (value instanceof Money) {
100
+ const currencyId = siblings(field.currencyField);
101
+ if (typeof currencyId !== 'number') {
102
+ bad("is given as Money but the record's currency is not known", 'Load the currency field first, or write a Decimal / string amount.');
103
+ }
104
+ if (value.currency.id !== currencyId) {
105
+ throw new CurrencyMismatchError(`Cannot write ${value.toString()} to ${model.name}.${key}: the record's currency is a different one (id ${String(currencyId)}).`, "Convert the amount to the record's currency first (env.fx.convert with the document date), or write the record's currency field in the same write.");
106
+ }
107
+ return value.amount;
108
+ }
109
+ return decimalOf(model, key, value);
110
+ }
111
+ case 'quantity': {
112
+ if (value instanceof Quantity) {
113
+ const uomId = siblings(field.uomField);
114
+ if (value.uom.id !== uomId) {
115
+ throw new UomMismatchError(`Cannot write ${value.toString()} to ${model.name}.${key}: the record's unit is a different one (id ${String(uomId)}).`, "Convert the quantity with .to(uom) first, or write the record's unit field in the same write.");
116
+ }
117
+ return value.value;
118
+ }
119
+ return decimalOf(model, key, value);
120
+ }
121
+ case 'decimal':
122
+ return decimalOf(model, key, value);
123
+ case 'integer':
124
+ return typeof value === 'number' && Number.isSafeInteger(value)
125
+ ? value
126
+ : bad('expects an integer', 'Pass a safe integer number.');
127
+ case 'bigint':
128
+ return typeof value === 'bigint' || (typeof value === 'number' && Number.isSafeInteger(value))
129
+ ? value
130
+ : bad('expects an integer', 'Pass a bigint or a safe integer.');
131
+ case 'boolean':
132
+ return typeof value === 'boolean' ? value : bad('expects true or false', 'Pass a boolean.');
133
+ case 'char':
134
+ case 'text':
135
+ case 'html': {
136
+ if (field.translate) {
137
+ if (typeof value !== 'string' && !isTranslations(value))
138
+ return bad('expects a string or a { lang: text } map', "Pass 'text' (written in the environment language) or { en_US: 'text', bn_BD: '...' }.");
139
+ const ctx = translation ?? { lang: 'en_US', source: 'en_US' };
140
+ const existing = siblings(key);
141
+ return mergeTranslation(isTranslations(existing) ? existing : null, value, ctx.lang, ctx.source);
142
+ }
143
+ return typeof value === 'string' ? value : bad('expects a string', 'Pass a string.');
144
+ }
145
+ case 'date':
146
+ return typeof value === 'string' && DATE.test(value)
147
+ ? value
148
+ : bad("expects a 'YYYY-MM-DD' string", "Pass a calendar date such as '2026-10-15', never a JS Date.");
149
+ case 'datetime':
150
+ return value instanceof Date && !Number.isNaN(value.getTime())
151
+ ? value
152
+ : bad('expects a Date', 'Pass a valid JS Date (stored in UTC).');
153
+ case 'selection':
154
+ case 'state': {
155
+ const selection = field.selection;
156
+ const allowed = typeof selection === 'function' ? selection() : selection.map(([k]) => k);
157
+ return typeof value === 'string' && allowed.includes(value)
158
+ ? value
159
+ : bad(`expects one of ${allowed.join(', ')}`, `Got ${JSON.stringify(value)}.`);
160
+ }
161
+ case 'binary':
162
+ return value instanceof Uint8Array ? value : bad('expects bytes', 'Pass a Uint8Array.');
163
+ default:
164
+ return value;
165
+ }
166
+ }
167
+ function decimalOf(model, key, value) {
168
+ try {
169
+ return toDecimal(value);
170
+ }
171
+ catch (e) {
172
+ const hint = e instanceof Error && 'hint' in e
173
+ ? String(e.hint)
174
+ : 'Pass a decimal string or a Decimal.';
175
+ return fail(model, [key], `field '${key}' expects an exact decimal.`, hint);
176
+ }
177
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Writes (RFC 0004 §7.6): `create()` inserts immediately, `write()` goes through the unit of work and is flushed in
3
+ * set-based statements, `unlink()` deletes immediately. Every change is journaled for savepoint rollback and
4
+ * recorded as a compute trigger (RFC 0008 §7.2).
5
+ */
6
+ import type { ScopeInternals } from '../env/env.js';
7
+ import type { AnyModel } from '../model/model.js';
8
+ /**
9
+ * Compare-and-set (RFC 0018 §7.1): locks the records and checks their stored values against `expect` before a write.
10
+ * @throws {StaleRecordError} for records whose values differ (someone else saved first).
11
+ */
12
+ export declare function assertExpected(internals: ScopeInternals, model: AnyModel, ids: readonly number[], expect: Readonly<Record<string, unknown>>): Promise<void>;
13
+ /** What the write runtime needs from the recordset runtime (passed in to avoid a module cycle). */
14
+ export interface WriteHost {
15
+ readonly internals: ScopeInternals;
16
+ /** Loads the given fields for ids (through the identity map). */
17
+ fetch(model: AnyModel, ids: readonly number[], fields: ReadonlySet<string>): Promise<void>;
18
+ /** Loads currencies / units referenced by the given fields of the records. */
19
+ ensureValueObjects(model: AnyModel, ids: readonly number[], fields: ReadonlySet<string>): Promise<void>;
20
+ /** Default (stored, non-x2many) keys of a model, with sibling currency / uom fields. */
21
+ defaults(model: AnyModel): Set<string>;
22
+ /** Cached values of a record, created when `create` is true. */
23
+ values(model: string, id: number, create?: boolean): Map<string, unknown> | undefined;
24
+ /** Children of an x2many relation, loading them if needed. */
25
+ children(model: AnyModel, id: number, key: string): Promise<number[]>;
26
+ /** A recordset of `ids` (for inverse functions). */
27
+ recordset(model: AnyModel, ids: readonly number[]): unknown;
28
+ }
29
+ type Row = Readonly<Record<string, unknown>>;
30
+ /** Inserts `rows` and returns their ids in input order. Children and links are created too. */
31
+ export declare function createRecords(host: WriteHost, model: AnyModel, input: readonly Row[], options?: {
32
+ readonly copy?: boolean;
33
+ }): Promise<number[]>;
34
+ /** One value in COPY text format: \N for null, backslash escapes, bytea as hex (RFC 0015 §7.1). */
35
+ export declare function copyField(value: unknown): string;
36
+ /** Applies `values` to `ids` in the cache and marks them dirty; x2many commands run immediately. */
37
+ export declare function writeRecords(host: WriteHost, model: AnyModel, ids: readonly number[], values: Row): Promise<void>;
38
+ /** Deletes `ids` now and removes them from the cache (and from any cached x2many lists). */
39
+ export declare function unlinkRecords(host: WriteHost, model: AnyModel, ids: readonly number[]): Promise<void>;
40
+ /** Writes dirty records of `modelName` (or all models) in one `UPDATE … FROM unnest(...)` per (model, field set). */
41
+ export declare function flushDirty(host: WriteHost, modelName?: string): Promise<void>;
42
+ export {};