@mistriwork/engine 1.0.0-rc.10 → 1.0.0-rc.11

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 (73) hide show
  1. package/dist/adapters/adapter.d.ts +33 -0
  2. package/dist/adapters/postgres.d.ts +21 -16
  3. package/dist/adapters/postgres.js +174 -223
  4. package/dist/adapters/postgresCatalog.d.ts +12 -1
  5. package/dist/adapters/postgresCatalog.js +57 -23
  6. package/dist/adapters/postgresCatalogDigest.js +40 -34
  7. package/dist/adapters/postgresCatalogRows.d.ts +2 -0
  8. package/dist/adapters/postgresWriteAhead.d.ts +47 -0
  9. package/dist/adapters/postgresWriteAhead.js +209 -0
  10. package/dist/adapters/scoped/keyRows.js +9 -3
  11. package/dist/adapters/scoped/keyTypes.d.ts +34 -0
  12. package/dist/adapters/scoped/keyTypes.js +66 -0
  13. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +18 -0
  14. package/dist/adapters/scoped/postgresScopeCatalog.js +353 -13
  15. package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
  16. package/dist/adapters/scoped/postgresTriggers.js +1545 -0
  17. package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
  18. package/dist/adapters/scoped/scopeTriggers.js +131 -0
  19. package/dist/adapters/scoped/scopedReads.d.ts +3 -1
  20. package/dist/adapters/scoped/scopedReads.js +23 -5
  21. package/dist/adapters/scoped/scopedTransaction.d.ts +76 -6
  22. package/dist/adapters/scoped/scopedTransaction.js +278 -34
  23. package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +17 -1
  24. package/dist/adapters/scoped/sqliteScopeCatalog.js +197 -18
  25. package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
  26. package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
  27. package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
  28. package/dist/adapters/scoped/sqliteTriggers.js +822 -0
  29. package/dist/adapters/scoped/storedText.d.ts +45 -0
  30. package/dist/adapters/scoped/storedText.js +61 -0
  31. package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
  32. package/dist/adapters/scoped/triggerEffects.js +189 -0
  33. package/dist/adapters/scoped/triggerProof.d.ts +124 -0
  34. package/dist/adapters/scoped/triggerProof.js +366 -0
  35. package/dist/adapters/snapshotRead.d.ts +8 -0
  36. package/dist/adapters/snapshotRead.js +37 -0
  37. package/dist/adapters/sqlite.d.ts +13 -2
  38. package/dist/adapters/sqlite.js +139 -16
  39. package/dist/adapters/sqliteDecimals.d.ts +2 -2
  40. package/dist/adapters/sqliteDecimals.js +2 -8
  41. package/dist/adapters/storeHost.d.ts +4 -1
  42. package/dist/adapters/writeCapture.d.ts +7 -0
  43. package/dist/server/cli/args.d.ts +6 -0
  44. package/dist/server/cli/args.js +6 -0
  45. package/dist/server/columnGrants.d.ts +3 -0
  46. package/dist/server/columnGrants.js +12 -1
  47. package/dist/server/config/profile.d.ts +123 -0
  48. package/dist/server/config/profile.js +236 -0
  49. package/dist/server/connections.d.ts +5 -0
  50. package/dist/server/connections.js +11 -1
  51. package/dist/server/hiddenColumns.js +6 -0
  52. package/dist/server/http/refusalReport.js +16 -4
  53. package/dist/server/migrate/cli.d.ts +50 -3
  54. package/dist/server/migrate/cli.js +199 -14
  55. package/dist/server/migrate/runner.js +5 -1
  56. package/dist/server/shapeonly.js +5 -0
  57. package/dist/shared/aggregate.d.ts +49 -0
  58. package/dist/shared/aggregate.js +107 -0
  59. package/dist/shared/breakdown.js +17 -4
  60. package/dist/shared/decimals.d.ts +37 -0
  61. package/dist/shared/decimals.js +148 -0
  62. package/dist/shared/displayDefaults.js +15 -1
  63. package/dist/shared/filter.d.ts +22 -1
  64. package/dist/shared/filter.js +36 -9
  65. package/dist/shared/money.d.ts +9 -0
  66. package/dist/shared/money.js +17 -0
  67. package/dist/shared/pageModel.d.ts +1 -1
  68. package/dist/shared/refusal.d.ts +16 -0
  69. package/dist/shared/refusal.js +40 -0
  70. package/dist/shared/schema.d.ts +6 -0
  71. package/dist/shared/scopeCatalog.js +4 -0
  72. package/dist/shared/servedApp.d.ts +7 -2
  73. package/package.json +5 -1
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Decimal columns said exactly: the scale a declared type asks for, and an
3
+ * exact SQLite sum over one.
4
+ *
5
+ * PostgreSQL's `numeric` is exact and `SUM` over it is too, read as text by
6
+ * `pg`. SQLite stores `numeric(12,2)` as an integer or a REAL and sums it as
7
+ * a REAL, so 0.10 + 0.20 + 0.07 + 100,000,000,000,000.00 came back as
8
+ * `100000000000000.38`. Summed here as whole hundredths instead — each value
9
+ * times 10^scale, rounded once to an integer, added as integers — and said
10
+ * with the column's places, as PostgreSQL says it, the two engines agree to
11
+ * the cent. Exact while each REAL value times 10^scale is below 2^53 (SQLite
12
+ * keeps a number with a fraction as a REAL, whose whole units stop there), an
13
+ * integer value times 10^scale and the total fit 2^63. Past either, no answer
14
+ * is the right one, so none is given: the sum says it is beyond exact range
15
+ * (`ExactnessRefusal`), where it once answered 10.223372036854775808 for
16
+ * 10 + 0.5. SQLite's own `integer overflow` of a total is the same refusal.
17
+ */
18
+ import { RequestFault } from './refusal.js';
19
+ /** The sum of a decimal column SQLite cannot add exactly: a data or schema fault (a column declared with more
20
+ places than SQLite can hold), never worth a retry. */
21
+ class ExactnessRefusal extends RequestFault {
22
+ constructor(columns) {
23
+ const named = columns.length ? columns.map((column) => `"${column}"`).join(', ') : 'a decimal column';
24
+ super(`The sum of ${named} is beyond what SQLite adds exactly: a value times 10^places passes 2^53 (a REAL) or 2^63 (an integer), ` +
25
+ 'or the total passes 2^63. Declare fewer places, hold smaller values, or run the App on PostgreSQL.', { columns });
26
+ this.name = 'ExactnessRefusal';
27
+ }
28
+ }
29
+ /** What an exact sum says in place of a number when it cannot be exact; `refuseInexact` turns it into the refusal. */
30
+ const INEXACT = '\u001finexact\u001f';
31
+ const DECLARED_SCALE = /^\s*(?:decimal|numeric)\s*\(\s*\d+\s*,\s*(\d+)\s*\)\s*$/i;
32
+ /** The scale a declared type asks for, when it is a DECIMAL/NUMERIC with one above zero. */
33
+ export function declaredScale(type) {
34
+ if (!type)
35
+ return 0;
36
+ const scale = Number(DECLARED_SCALE.exec(type)?.[1] ?? 0);
37
+ return scale > 0 ? scale : 0;
38
+ }
39
+ /** The most places an exact sum says: 10^18 is the largest power of ten a SQLite integer holds. */
40
+ const MOST_PLACES = 18;
41
+ /** Whether a SQLite sum over a column of this declared type is summed exactly (`exactSqliteSum`). */
42
+ export const sumsExactly = (type) => {
43
+ const scale = declaredScale(type);
44
+ return scale > 0 && scale <= MOST_PLACES;
45
+ };
46
+ /**
47
+ * A SQLite column of `scale` places summed as an integer count of its
48
+ * smallest unit: `total` is that integer (for ordering by it), `text` the
49
+ * decimal it says, null over no rows as `SUM` is. `read` is the column's
50
+ * expression; the scale is a number read off the catalog, never a request's
51
+ * text.
52
+ */
53
+ export function exactSqliteSum(read, scale, label = '') {
54
+ if (!Number.isInteger(scale) || scale < 1 || scale > MOST_PLACES)
55
+ throw new RangeError(`An exact sum takes 1 to ${MOST_PLACES} places.`);
56
+ const unit = `1${'0'.repeat(scale)}`;
57
+ /* A value stored as an integer is multiplied as one, exactly; a REAL is
58
+ rounded once to the nearest unit, which is what the column meant. */
59
+ const total = `SUM(CASE WHEN typeof(${read}) = 'integer' THEN ${read} * ${unit} ELSE CAST(ROUND(${read} * ${unit}) AS INTEGER) END)`;
60
+ /* A REAL past 2^53 units is rounded to a neighbor before it is added, and a total that is no longer an integer
61
+ is an integer product that overflowed into a REAL: neither is the sum, so the cell says so instead. */
62
+ const beyond = `SUM(CASE WHEN typeof(${read}) = 'real' AND abs(${read} * ${unit}) >= 9007199254740992 THEN 1 ELSE 0 END) > 0`;
63
+ const text = `CASE WHEN ${total} IS NULL THEN NULL ` +
64
+ `WHEN ${beyond} OR typeof(${total}) <> 'integer' THEN '${INEXACT}' || '${label.replaceAll("'", "''")}' ELSE ` +
65
+ `(CASE WHEN ${total} < 0 THEN '-' ELSE '' END) || printf('%d.%0${scale}d', abs(${total}) / ${unit}, abs(${total}) % ${unit}) END`;
66
+ return { total, text };
67
+ }
68
+ /** The columns a list of measures sums, for the refusal to name. */
69
+ export const summed = (measures) => (measures ?? []).flatMap((measure) => measure.fn === 'sum' && (measure.path ?? measure.column) ? [(measure.path ?? measure.column)] : []);
70
+ /**
71
+ * Runs a SQLite read whose rows may hold exact sums: a cell that says it was beyond exact range, or SQLite's own
72
+ * `integer overflow` while adding, is the refusal, naming the columns summed (`columns`).
73
+ */
74
+ export async function readExactly(run, columns) {
75
+ let result;
76
+ try {
77
+ result = await run();
78
+ }
79
+ catch (error) {
80
+ if (columns.length && error instanceof Error && /integer overflow/i.test(error.message))
81
+ throw new ExactnessRefusal(columns);
82
+ throw error;
83
+ }
84
+ const found = new Set();
85
+ for (const row of result.rows)
86
+ for (const value of Object.values(row))
87
+ if (typeof value === 'string' && value.startsWith(INEXACT))
88
+ found.add(value.slice(INEXACT.length));
89
+ if (found.size)
90
+ throw new ExactnessRefusal([...found].filter(Boolean).length ? [...found].filter(Boolean) : columns);
91
+ return result;
92
+ }
93
+ /* ---------- exact decimal text in the server ---------- */
94
+ const DECIMAL_TEXT = /^(-)?(\d+)(?:\.(\d+))?$/;
95
+ /** A decimal as an integer count of units and its places, or undefined when the text is not a plain decimal. */
96
+ export function parseDecimal(value) {
97
+ if (typeof value === 'bigint')
98
+ return { units: value, scale: 0 };
99
+ if (typeof value === 'number') {
100
+ if (!Number.isFinite(value))
101
+ return undefined;
102
+ if (Number.isInteger(value))
103
+ return Number.isSafeInteger(value) ? { units: BigInt(value), scale: 0 } : undefined;
104
+ value = String(value);
105
+ if (/e/i.test(value))
106
+ return undefined;
107
+ }
108
+ const match = DECIMAL_TEXT.exec(value.trim());
109
+ if (!match)
110
+ return undefined;
111
+ const places = match[3] ?? '';
112
+ const units = BigInt(`${match[2]}${places}`);
113
+ return { units: match[1] ? -units : units, scale: places.length };
114
+ }
115
+ /** An integer count of units said with `scale` places: `formatDecimal(-5n, 2)` is `-0.05`. */
116
+ export function formatDecimal(units, scale) {
117
+ const negative = units < 0n;
118
+ const digits = (negative ? -units : units).toString().padStart(scale + 1, '0');
119
+ const whole = scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits;
120
+ return negative && /[1-9]/.test(digits) ? `-${whole}` : whole;
121
+ }
122
+ /** `units / divisor`, rounded half to even: the banker's rounding, so ties do not drift one way. */
123
+ function divideHalfEven(units, divisor) {
124
+ if (divisor === 0n)
125
+ throw new RangeError('Division by zero.');
126
+ if (divisor < 0n)
127
+ return divideHalfEven(-units, -divisor);
128
+ let quotient = units / divisor;
129
+ const remainder = units - quotient * divisor;
130
+ const twice = (remainder < 0n ? -remainder : remainder) * 2n;
131
+ if (twice > divisor || (twice === divisor && quotient % 2n !== 0n))
132
+ quotient += remainder < 0n ? -1n : 1n;
133
+ return quotient;
134
+ }
135
+ /** The mean of an exact sum over `count` values, said with `places` places, rounded half to even. */
136
+ export function exactAverage(sum, count, places) {
137
+ const parsed = parseDecimal(sum);
138
+ if (!parsed)
139
+ return undefined;
140
+ const n = BigInt(count);
141
+ if (n <= 0n)
142
+ return undefined;
143
+ /* sum / count at `places` places: units · 10^(places − scale) / count, with the shift folded into whichever side keeps it whole. */
144
+ const shift = places - parsed.scale;
145
+ const numerator = shift >= 0 ? parsed.units * 10n ** BigInt(shift) : parsed.units;
146
+ const denominator = shift >= 0 ? n : n * 10n ** BigInt(-shift);
147
+ return formatDecimal(divideHalfEven(numerator, denominator), places);
148
+ }
@@ -293,7 +293,21 @@ const CONCERNS = [
293
293
  {
294
294
  name: 'figure',
295
295
  owns: ['format', 'bar', 'unit', 'minor', 'currency'],
296
- displaces: ['format', 'bar', 'unit', 'ring', 'slider', 'outOf', 'max', 'minor', 'currency', 'currencyColumn', 'values', 'avatar'],
296
+ displaces: [
297
+ 'format',
298
+ 'bar',
299
+ 'unit',
300
+ 'ring',
301
+ 'slider',
302
+ 'outOf',
303
+ 'max',
304
+ 'minor',
305
+ 'whole',
306
+ 'currency',
307
+ 'currencyColumn',
308
+ 'values',
309
+ 'avatar',
310
+ ],
297
311
  },
298
312
  { name: 'words', owns: ['values'], displaces: ['values', 'format'] },
299
313
  { name: 'tone', owns: ['tone'], displaces: ['tone', 'colors'] },
@@ -32,6 +32,25 @@ export interface Condition {
32
32
  * `op` is `isNotNull` for `any`, `isNull` for `no`.
33
33
  */
34
34
  any?: AnyRows;
35
+ /**
36
+ * Compare as a PostgreSQL foreign key compares a reference with its parent's key: by its own operator, named with
37
+ * its schema, the value cast to the referencing column's type and each side to the operator's, as the database's
38
+ * own check is written (ri_triggers.c). Read from the catalog for a scoped write's parent check
39
+ * (scopedTransaction.ts); SQL text, so only a builder that asks for it (`buildWhere`'s `references`) compiles it,
40
+ * and everywhere else it is refused.
41
+ */
42
+ equality?: ConditionEquality;
43
+ }
44
+ /** A foreign key's comparison of one column (`Condition.equality`): each part SQL as the catalog gave it. */
45
+ export interface ConditionEquality {
46
+ /** `schema.operator`, the schema quoted where it needs it. */
47
+ readonly operator: string;
48
+ /** The type the value is read as: the referencing column's, typmod and all. */
49
+ readonly type: string;
50
+ /** The operator's left type, where the parent column's is another. */
51
+ readonly left?: string;
52
+ /** The operator's right type, where the referencing column's is another. */
53
+ readonly right?: string;
35
54
  }
36
55
  /**
37
56
  * The child rows an `any` condition asks about: the reference they point
@@ -213,5 +232,7 @@ other?: (name: string) => string,
213
232
  /** How `has` is written for a column naming a record's tags, given the bound labels' placeholders; absent, `has` is refused. */
214
233
  membership?: (name: string, holes: readonly string[]) => string,
215
234
  /** How an `any` condition is written: an EXISTS over the child's rows, binding nothing of its own; absent, one is refused. */
216
- exists?: (rows: AnyRows) => string): SqlFragment;
235
+ exists?: (rows: AnyRows) => string,
236
+ /** Whether a condition may compare as a foreign key does (`Condition.equality`): a scoped write's own reads only. */
237
+ references?: boolean): SqlFragment;
217
238
  export {};
@@ -4,7 +4,14 @@
4
4
  * it lives here rather than with the adapters that run the statements.
5
5
  */
6
6
  import { LIKE_ESCAPE, likePattern } from './like.js';
7
- import { Refusal } from './refusal.js';
7
+ import { RequestFault } from './refusal.js';
8
+ /* A type as the scope catalog names one (postgresScopeCatalog.ts sqlType): a chain of identifiers, each a word or
9
+ quoted, then at most a modifier of one or two integers and the brackets of an array — `pg_catalog."numeric"(10,2)`,
10
+ `"s"."my type"`, `pg_catalog."varchar"(3)[]`. Nothing else, so no text can end the cast and start an expression;
11
+ and an operator as `schema.=`. */
12
+ const IDENTIFIER = '(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)';
13
+ const SQL_TYPE = new RegExp(`^${IDENTIFIER}(?:\\.${IDENTIFIER})*(?:\\(\\d+(?:,-?\\d+)?\\))?(?:\\[\\])*$`);
14
+ const SQL_OPERATOR = /^(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)\.[+\-*<>=~!@#%^&|`?]{1,63}$/;
8
15
  /**
9
16
  * The operators, as a value rather than only as a type.
10
17
  *
@@ -146,7 +153,7 @@ export function collate(expression, collation, style) {
146
153
  if (collation === undefined)
147
154
  return expression;
148
155
  if (collation !== 'binary' || !style.binaryText)
149
- throw new Refusal('This comparison cannot be made by bytes on this database.');
156
+ throw new RequestFault('This comparison cannot be made by bytes on this database.');
150
157
  return `${expression}${style.binaryText}`;
151
158
  }
152
159
  const COMPARISONS = new Set(['=', '!=', '>', '>=', '<', '<=']);
@@ -172,7 +179,9 @@ other,
172
179
  /** How `has` is written for a column naming a record's tags, given the bound labels' placeholders; absent, `has` is refused. */
173
180
  membership,
174
181
  /** How an `any` condition is written: an EXISTS over the child's rows, binding nothing of its own; absent, one is refused. */
175
- exists) {
182
+ exists,
183
+ /** Whether a condition may compare as a foreign key does (`Condition.equality`): a scoped write's own reads only. */
184
+ references = false) {
176
185
  if (!filter?.groups.length)
177
186
  return { text: '', params: [] };
178
187
  const params = [];
@@ -193,21 +202,21 @@ exists) {
193
202
  const compile = (group) => group
194
203
  .map((c) => {
195
204
  if (c.collation !== undefined && !COMPARISONS.has(c.op)) {
196
- throw new Refusal('Only a comparison can compare text by bytes.');
205
+ throw new RequestFault('Only a comparison can compare text by bytes.');
197
206
  }
198
207
  /* Before the column is written: child rows are no column of this row. Their
199
208
  values are bound where their relation is planned (rowScope.ts `filtered`),
200
209
  so the EXISTS carries no parameter here and the numbering is untouched. */
201
210
  if (c.any !== undefined) {
202
211
  if (!exists || typeof c.any !== 'object' || c.any === null)
203
- throw new Refusal('This read cannot ask about the rows that point at it.');
212
+ throw new RequestFault('This read cannot ask about the rows that point at it.');
204
213
  /* `no task …` is the same rows asked the other way: none of them matches. */
205
214
  return c.op === 'isNull' ? `NOT ${exists(c.any)}` : exists(c.any);
206
215
  }
207
216
  /* Before the column is written: a record's tags are no column. */
208
217
  if (c.op === 'has') {
209
218
  if (!membership || c.other !== undefined)
210
- throw new Refusal("This read cannot ask a record's tags.");
219
+ throw new RequestFault("This read cannot ask a record's tags.");
211
220
  const labels = (Array.isArray(c.value) ? c.value : [c.value]).filter((v) => typeof v === 'string' || typeof v === 'number');
212
221
  if (!labels.length)
213
222
  return '1 = 0';
@@ -217,10 +226,23 @@ exists) {
217
226
  });
218
227
  return membership(c.column, holes);
219
228
  }
229
+ if (c.equality !== undefined) {
230
+ const { operator, type, left, right } = (c.equality ?? {});
231
+ if (!references ||
232
+ c.op !== '=' ||
233
+ c.collation !== undefined ||
234
+ c.other !== undefined ||
235
+ typeof operator !== 'string' ||
236
+ !SQL_OPERATOR.test(operator) ||
237
+ ![type, left, right].every((part, at) => (at > 0 && part === undefined) || (typeof part === 'string' && SQL_TYPE.test(part))))
238
+ throw new RequestFault('This read cannot compare as a foreign key does.');
239
+ params.push(c.value ?? null);
240
+ return `${column(c.column, c)}${left ? `::${left}` : ''} OPERATOR(${operator}) ${next()}::${type}${right ? `::${right}` : ''}`;
241
+ }
220
242
  const col = collate(column(c.column, c), c.collation, style);
221
243
  if (c.other !== undefined) {
222
244
  if (!other || typeof c.other !== 'string' || !COMPARISONS.has(c.op)) {
223
- throw new Refusal('This read cannot compare two columns.');
245
+ throw new RequestFault('This read cannot compare two columns.');
224
246
  }
225
247
  return `${col} ${c.op} ${collate(other(c.other), c.collation, style)}`;
226
248
  }
@@ -267,7 +289,7 @@ exists) {
267
289
  Checked here rather than at each caller: one choke point
268
290
  covers the four endpoints and anything added later. */
269
291
  if (!OPS.has(c.op)) {
270
- throw new Refusal(`"${String(c.op)}" is not an operator this tool knows.`);
292
+ throw new RequestFault(`"${String(c.op)}" is not an operator this tool knows.`);
271
293
  }
272
294
  params.push(c.value ?? null);
273
295
  return `${col} ${c.op} ${next()}`;
@@ -293,7 +315,12 @@ exists) {
293
315
  function sameCondition(a, b) {
294
316
  if (a === b)
295
317
  return true;
296
- if (a.column !== b.column || a.op !== b.op || a.collation !== b.collation || a.other !== b.other || a.any !== b.any)
318
+ if (a.column !== b.column ||
319
+ a.op !== b.op ||
320
+ a.collation !== b.collation ||
321
+ a.other !== b.other ||
322
+ a.any !== b.any ||
323
+ a.equality !== b.equality)
297
324
  return false;
298
325
  if (Array.isArray(a.value) || Array.isArray(b.value)) {
299
326
  return (Array.isArray(a.value) &&
@@ -22,6 +22,15 @@ export declare function currencyDigits(currency: string): number;
22
22
  * then divides as a number.
23
23
  */
24
24
  export declare function minorToMajor(value: unknown, currency: string): string | undefined;
25
+ /**
26
+ * A stored amount in the major unit as its exact decimal text, to the
27
+ * currency's minor digits: 5917 → "5917.00", "-12.5" → "-12.50", 1500 in JPY
28
+ * → "1500". Padded, never rounded: a figure with more places than its
29
+ * currency keeps them, as stored. A decimal string is read by its digits, so
30
+ * one past 2^53 is not the double Number() makes of it. Undefined for no
31
+ * decimal at all.
32
+ */
33
+ export declare function majorText(value: unknown, currency: string): string | undefined;
25
34
  /**
26
35
  * A minor-unit value as the figure a money format draws: the exact major text
27
36
  * where it is a whole number of minor units, else the number divided (a
@@ -49,6 +49,23 @@ export function minorToMajor(value, currency) {
49
49
  const whole = m[2].padStart(digits + 1, '0');
50
50
  return (/[1-9]/.test(whole) ? m[1] : '') + (digits ? `${whole.slice(0, -digits)}.${whole.slice(-digits)}` : whole);
51
51
  }
52
+ /**
53
+ * A stored amount in the major unit as its exact decimal text, to the
54
+ * currency's minor digits: 5917 → "5917.00", "-12.5" → "-12.50", 1500 in JPY
55
+ * → "1500". Padded, never rounded: a figure with more places than its
56
+ * currency keeps them, as stored. A decimal string is read by its digits, so
57
+ * one past 2^53 is not the double Number() makes of it. Undefined for no
58
+ * decimal at all.
59
+ */
60
+ export function majorText(value, currency) {
61
+ const text = typeof value === 'number' ? (Number.isFinite(value) ? String(value) : '') : typeof value === 'string' ? value.trim() : '';
62
+ const m = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(text);
63
+ if (!m)
64
+ return undefined;
65
+ const places = (m[3] ?? '').padEnd(currencyDigits(currency), '0');
66
+ const figure = `${m[2]}${places ? `.${places}` : ''}`;
67
+ return (m[1] === '-' && /[1-9]/.test(figure) ? '-' : '') + figure;
68
+ }
52
69
  /**
53
70
  * A minor-unit value as the figure a money format draws: the exact major text
54
71
  * where it is a whole number of minor units, else the number divided (a
@@ -408,7 +408,7 @@ interface PageNote {
408
408
  /** `quiet`: small print, no mark. `callout`: a ground of its own. Absent: the plain note. */
409
409
  variant?: 'quiet' | 'callout';
410
410
  icon?: import('./appIcons.js').AppIconName;
411
- /** One of the App's list or dashboard views to open. An App page only. */
411
+ /** One of the App's rooms to open: a list, a dashboard or a signed-in form view. An App page only. */
412
412
  action?: import('./appLinks.js').AppLinkAction;
413
413
  width?: SectionWidth;
414
414
  offsetLeft?: SectionOffset;
@@ -21,6 +21,16 @@ export declare class Refusal extends Error {
21
21
  cause?: unknown;
22
22
  });
23
23
  }
24
+ declare const REQUEST_FAULT: unique symbol;
25
+ export declare class RequestFault extends Refusal {
26
+ readonly [REQUEST_FAULT] = true;
27
+ constructor(message: string, options?: {
28
+ columns?: readonly string[];
29
+ cause?: unknown;
30
+ });
31
+ }
32
+ /** Whether a refusal is a request that can never succeed as written (`RequestFault`), from any copy of the module. */
33
+ export declare const isRequestFault: (error: unknown) => error is RequestFault;
24
34
  /** Record why a refusal happened on the refusal itself, for the trusted reader
25
35
  * only. Every opaque refusal takes its reason this way — a tenant denial, a
26
36
  * row policy that did not load, a command the database would not take — so
@@ -29,6 +39,11 @@ export declare class Refusal extends Error {
29
39
  export declare function recordRefusalCause<E extends object>(error: E, cause: unknown): E;
30
40
  /** The recorded reason behind a refusal, for a trusted diagnostic only. */
31
41
  export declare const refusalCause: (error: unknown) => unknown;
42
+ /** Mark a refusal as its App author's mistake, and record why: the operator is told the cause first. */
43
+ export declare function authorFault<E extends object>(error: E, cause: string): E;
44
+ /** Whether a refusal, or one it was rebuilt over (a command's refusals are re-issued with the outcome), was marked
45
+ as its App author's mistake (authorFault). */
46
+ export declare function isAuthorFault(error: unknown): boolean;
32
47
  /**
33
48
  * What the operator is told about a refusal: each reason under it, outermost
34
49
  * first — a recorded cause before `cause`, since the recorded one is the
@@ -62,3 +77,4 @@ export declare function faultFrames(error: unknown, most?: number): string[];
62
77
  export declare function sayRefusal<E extends object>(error: E, sentence: string): E;
63
78
  /** The sentence a refusal's caller may read about why, if the code that refused said one. */
64
79
  export declare const refusalSaid: (error: unknown) => string | undefined;
80
+ export {};
@@ -29,6 +29,21 @@ export class Refusal extends Error {
29
29
  this.columns = [...new Set(options.columns)];
30
30
  }
31
31
  }
32
+ /* A request that can never succeed as written: a malformed filter, an aggregate naming a column the table lacks, a
33
+ sum SQLite cannot add exactly. Whoever wrote the request fixes it, so nothing is worth retrying; a command that
34
+ meets one says invalid_result, where every other refusal it could not place was temporarily_unavailable and
35
+ sent a job or a workflow round a retry that could not end. Branded with a registered symbol, since a handler
36
+ may import a second copy of this module. */
37
+ const REQUEST_FAULT = Symbol.for('mistri.requestFault');
38
+ export class RequestFault extends Refusal {
39
+ [REQUEST_FAULT] = true;
40
+ constructor(message, options = {}) {
41
+ super(message, options);
42
+ this.name = 'RequestFault';
43
+ }
44
+ }
45
+ /** Whether a refusal is a request that can never succeed as written (`RequestFault`), from any copy of the module. */
46
+ export const isRequestFault = (error) => error instanceof Error && error[REQUEST_FAULT] === true;
32
47
  /* Why a refusal happened, kept for the trusted owner that has to diagnose it.
33
48
  A caller hears one fixed sentence and must: a driver's error text names
34
49
  columns, values and internal tables, and a clash on a hidden unique column
@@ -55,6 +70,31 @@ export function recordRefusalCause(error, cause) {
55
70
  }
56
71
  /** The recorded reason behind a refusal, for a trusted diagnostic only. */
57
72
  export const refusalCause = (error) => error !== null && typeof error === 'object' && CAUSE in error ? error[CAUSE] : undefined;
73
+ /* A refusal that is its App author's own mistake — a command handler that set a reference outside its footprint,
74
+ wrote bytes where no file resource keeps them — rather than the caller's or the platform's. Its caller still
75
+ hears the fixed sentence, but that sentence names nothing to fix, and leading with it put "The command did not
76
+ produce a valid result." over the one line that said what to change (a field report). Marked where the mistake
77
+ is found, so the operator's terminal leads with the recorded cause; who may hear that cause does not move
78
+ (refusalReport.ts). */
79
+ const AUTHOR_FAULT = Symbol.for('mistri.refusalAuthorFault');
80
+ /** Mark a refusal as its App author's mistake, and record why: the operator is told the cause first. */
81
+ export function authorFault(error, cause) {
82
+ if (!Object.hasOwn(error, AUTHOR_FAULT))
83
+ Object.defineProperty(error, AUTHOR_FAULT, { value: true, enumerable: false });
84
+ return recordRefusalCause(error, cause);
85
+ }
86
+ /** Whether a refusal, or one it was rebuilt over (a command's refusals are re-issued with the outcome), was marked
87
+ as its App author's mistake (authorFault). */
88
+ export function isAuthorFault(error) {
89
+ const seen = new Set();
90
+ for (let at = error, depth = 0; at !== null && typeof at === 'object' && !seen.has(at) && depth < 8; depth++) {
91
+ if (AUTHOR_FAULT in at)
92
+ return true;
93
+ seen.add(at);
94
+ at = refusalCause(at) ?? at.cause;
95
+ }
96
+ return false;
97
+ }
58
98
  /**
59
99
  * What the operator is told about a refusal: each reason under it, outermost
60
100
  * first — a recorded cause before `cause`, since the recorded one is the
@@ -35,6 +35,12 @@ export interface ColumnMeta {
35
35
  };
36
36
  /** Declared default, if any. */
37
37
  default?: string;
38
+ /**
39
+ * The places a `numeric(p, s)` column holds (s), where `type` cannot say them: PostgreSQL's catalog calls the
40
+ * type plain `numeric`. Absent for an unconstrained numeric and for every other type; SQLite's declared type
41
+ * string carries its own (`decimals.ts` declaredScale).
42
+ */
43
+ scale?: number;
38
44
  /** Public presence hint when a private schema projection omits the SQL default. */
39
45
  hasDefault?: boolean;
40
46
  /** Catalog-confirmed automatic identity assignment; absent is not a type-based guess. */
@@ -167,6 +167,7 @@ export function captureScopeCatalog(schema) {
167
167
  'references',
168
168
  'allowed',
169
169
  'flag',
170
+ 'scale',
170
171
  'text',
171
172
  'comment',
172
173
  'writable',
@@ -184,6 +185,9 @@ export function captureScopeCatalog(schema) {
184
185
  typeof column.primaryKey !== 'boolean' ||
185
186
  (column.default !== undefined && typeof column.default !== 'string') ||
186
187
  (column.flag !== undefined && column.flag !== true) ||
188
+ /* `scale` (a numeric's declared places, where the type string cannot say them) is evidence like `flag`:
189
+ how to say a sum, never a grant. */
190
+ (column.scale !== undefined && (typeof column.scale !== 'number' || !Number.isInteger(column.scale) || column.scale < 0)) ||
187
191
  (column.identity !== undefined && column.identity !== 'always' && column.identity !== 'by-default'))
188
192
  return refuse();
189
193
  if (column.references !== undefined) {
@@ -238,18 +238,21 @@ export interface AppDisplayRule {
238
238
  /** money: currency formatting. percent: the value is 0–100, shown with %.
239
239
  number: separators forced on a numeric-looking text column. relative:
240
240
  a date said from today — "in 3 days", "64 days ago" — with the date
241
- itself in the tooltip. email, phone, url: the value is a link — to write
241
+ itself in the tooltip. date, datetime: a day, or a moment with its time and zone, said absolutely — the same
242
+ words on any day, for any reader; a date alone never shifts. email, phone, url: the value is a link — to write
242
243
  to, to call, to open beside the App — where it has that shape. An App
243
244
  links a column named like one (`email`, `phone`, `website`) without a rule. richText: the value is
244
245
  sanitized HTML (shared/richText.ts), drawn formatted on a record, as an excerpt in a list, edited in the
245
246
  rich text editor; every write of the column is sanitized on the server, and Markdown is read into it. */
246
- format?: 'money' | 'percent' | 'number' | 'relative' | 'items' | 'duration' | 'email' | 'phone' | 'url' | 'richText' | 'avatars' | 'rating' | 'color' | 'time' | 'month' | 'year' | 'json' | 'qr';
247
+ format?: 'money' | 'percent' | 'number' | 'relative' | 'date' | 'datetime' | 'items' | 'duration' | 'email' | 'phone' | 'url' | 'richText' | 'avatars' | 'rating' | 'color' | 'time' | 'month' | 'year' | 'json' | 'qr';
247
248
  /** The face this column's values are set in, over the look's own: `data` (the look's data face, usually
248
249
  monospace), `sans` (the interface's reading face) or `code` (always monospace, for a VIN or a hash):
249
250
  `display: { vin: { face: 'code' } }`. Left out, an App sets a key, a reference, a code or a QR value in the
250
251
  data face and any other text in the reading face, because a name is not compared character by character.
251
252
  A rule with a `component` takes no face, the component sets its own; `masked: true` takes none either. */
252
253
  face?: 'data' | 'ui' | 'code';
254
+ /** With format "date" or "datetime": the IANA zone a moment is said in, over the App's `ui.timezone`. */
255
+ timezone?: string;
253
256
  /** With format "rating": how many stars the scale has, 3 to 10 (5 when unsaid). */
254
257
  outOf?: number;
255
258
  /** With format "percent": the value as a small ring, filled against 100, beside the figure. */
@@ -298,6 +301,8 @@ export interface AppDisplayRule {
298
301
  currencyColumn?: string;
299
302
  /** For "money": the column holds whole minor units (money.ts), drawn and edited as the major figure. */
300
303
  minor?: true;
304
+ /** For "money": the minor digits are left off a whole amount ("$24,495"); an amount with cents keeps them. */
305
+ whole?: true;
301
306
  /** With "number", "money" or no format on a numeric column: the unit said after the figure — "mi", "kg", "/mo" (a leading slash
302
307
  joins without a space: "$242/mo"). At most 12 characters. */
303
308
  unit?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/engine",
3
- "version": "1.0.0-rc.10",
3
+ "version": "1.0.0-rc.11",
4
4
  "description": "The engine both products stand on: the adapters (SQLite, Postgres), the catalog, the query language, keyset pages, the HTTP kit and the shared rules. No React.",
5
5
  "homepage": "https://mistriwork.dev",
6
6
  "bugs": {
@@ -61,6 +61,7 @@
61
61
  "./adapters/telemetry/trace.js": "./dist/adapters/telemetry/trace.js",
62
62
  "./adapters/writeAttribution.js": "./dist/adapters/writeAttribution.js",
63
63
  "./adapters/writeCapture.js": "./dist/adapters/writeCapture.js",
64
+ "./adapters/snapshotRead.js": "./dist/adapters/snapshotRead.js",
64
65
  "./adapters/writeAhead.js": "./dist/adapters/writeAhead.js",
65
66
  "./adapters/dbLatency.js": "./dist/adapters/dbLatency.js",
66
67
  "./adapters/writeLanes.js": "./dist/adapters/writeLanes.js",
@@ -81,6 +82,7 @@
81
82
  "./server/columnGrants.js": "./dist/server/columnGrants.js",
82
83
  "./server/compileCache.js": "./dist/server/compileCache.js",
83
84
  "./server/config/locations.js": "./dist/server/config/locations.js",
85
+ "./server/config/profile.js": "./dist/server/config/profile.js",
84
86
  "./server/configPaths.js": "./dist/server/configPaths.js",
85
87
  "./server/configSections.js": "./dist/server/configSections.js",
86
88
  "./server/connections.js": "./dist/server/connections.js",
@@ -148,11 +150,13 @@
148
150
  "./shared/appListColumns.js": "./dist/shared/appListColumns.js",
149
151
  "./shared/appLocale.js": "./dist/shared/appLocale.js",
150
152
  "./shared/appMessages.js": "./dist/shared/appMessages.js",
153
+ "./shared/aggregate.js": "./dist/shared/aggregate.js",
151
154
  "./shared/appNoun.js": "./dist/shared/appNoun.js",
152
155
  "./shared/autoBucket.js": "./dist/shared/autoBucket.js",
153
156
  "./shared/autoValues.js": "./dist/shared/autoValues.js",
154
157
  "./shared/breakdown.js": "./dist/shared/breakdown.js",
155
158
  "./shared/breakdowntext.js": "./dist/shared/breakdowntext.js",
159
+ "./shared/decimals.js": "./dist/shared/decimals.js",
156
160
  "./shared/clauses.js": "./dist/shared/clauses.js",
157
161
  "./shared/columnCaption.js": "./dist/shared/columnCaption.js",
158
162
  "./shared/commandFieldPath.js": "./dist/shared/commandFieldPath.js",