@mistriwork/engine 1.0.0-rc.77 → 1.0.0-rc.79

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 (40) hide show
  1. package/dist/adapters/adapter.d.ts +6 -0
  2. package/dist/adapters/postgres.js +13 -7
  3. package/dist/adapters/scoped/scopedReads.js +5 -1
  4. package/dist/adapters/scoped/scopedTransaction.js +3 -1
  5. package/dist/adapters/sqlite.js +7 -5
  6. package/dist/server/columnGrants.d.ts +3 -0
  7. package/dist/server/columnGrants.js +29 -4
  8. package/dist/server/http/probes.d.ts +10 -1
  9. package/dist/server/http/probes.js +6 -2
  10. package/dist/server/http/recordWrites.js +7 -1
  11. package/dist/server/http/serverCore.d.ts +2 -1
  12. package/dist/server/migrate/cli.js +7 -0
  13. package/dist/server/resourceReadOperations.js +5 -1
  14. package/dist/shared/aggregate.js +7 -1
  15. package/dist/shared/computedParse.d.ts +2 -0
  16. package/dist/shared/computedParse.js +1 -1
  17. package/dist/shared/computedWhere.d.ts +47 -0
  18. package/dist/shared/computedWhere.js +159 -0
  19. package/dist/shared/filter.d.ts +5 -0
  20. package/dist/shared/filter.js +4 -0
  21. package/dist/shared/query.js +20 -22
  22. package/dist/shared/queryDates.d.ts +16 -0
  23. package/dist/shared/queryDates.js +29 -0
  24. package/dist/shared/queryOperands.d.ts +24 -0
  25. package/dist/shared/queryOperands.js +36 -0
  26. package/dist/shared/refusal.d.ts +8 -0
  27. package/dist/shared/refusal.js +15 -0
  28. package/dist/shared/resourceHttp.d.ts +1 -1
  29. package/dist/shared/rowCondition.d.ts +5 -0
  30. package/dist/shared/rowCondition.js +80 -0
  31. package/dist/shared/schema.d.ts +10 -0
  32. package/dist/shared/schema.js +8 -0
  33. package/dist/shared/scopeCatalog.d.ts +1 -1
  34. package/dist/shared/scopeCatalog.js +13 -1
  35. package/dist/shared/servedApp.d.ts +19 -0
  36. package/dist/shared/structuredFilter.d.ts +3 -0
  37. package/dist/shared/viewLabels.d.ts +6 -1
  38. package/dist/shared/viewLabels.js +1 -1
  39. package/package.json +2 -1
  40. package/schema/model.d.ts +12 -3
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Computed columns in a single-table read's filter: `db.tasks.where('is_overdue')` in a handler or a loader.
3
+ *
4
+ * A computed column is no column of the table (computed.ts), so a read that names one carries its expression on the
5
+ * filter (`Filter.computed`), and the adapter writes that expression where a condition names it, with the same
6
+ * compiler a view uses (`compileComputed`). The expression is what the reader's catalog served, its constants folded:
7
+ * the caller resolved it, never the person asking. It is still checked here, node by node, before a word of it reaches
8
+ * a statement, because `compileComputed` writes a function's name, an operator, a unit and a JSON key as text: anything
9
+ * the parser would never have produced is refused, and so is a read of anything but one of the table's own columns.
10
+ * What it reads is worked out from the expression (`computedReads`), never taken from the request, so a grant check
11
+ * of those reads (columnGrants.ts) is a check of what the statement reads.
12
+ */
13
+ import { COMPUTED_TYPES, compileComputed, computedKind, computedReads } from './computed.js';
14
+ import { COMPUTED_FUNCTIONS } from './computedParse.js';
15
+ import { asksAboutRows } from './filter.js';
16
+ import { RequestFault } from './refusal.js';
17
+ import { findTable } from './schema.js';
18
+ import { columnRead } from './viewLabels.js';
19
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
20
+ const OPS = new Set(['+', '-', '*', '/', '=', '!=', '<', '<=', '>', '>=', 'and', 'or']);
21
+ const UNITS = new Set(['minute', 'hour', 'day', 'week', 'month', 'year']);
22
+ const FUNCTIONS = new Set(COMPUTED_FUNCTIONS);
23
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
24
+ const INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z$/;
25
+ const refuse = (detail) => {
26
+ throw new RequestFault(`This read cannot use that computed column: ${detail}.`);
27
+ };
28
+ /** Whether a filter carries computed columns, so the adapter needs the table's columns to write them. */
29
+ export const asksComputed = (filter) => filter?.computed !== undefined &&
30
+ filter.computed !== null &&
31
+ typeof filter.computed === 'object' &&
32
+ Object.keys(filter.computed).length > 0;
33
+ /** Whether a single-table read's filter needs the catalog: it asks about other rows, or names a computed column. */
34
+ export const readsCatalog = (filter) => asksAboutRows(filter) || asksComputed(filter);
35
+ /** The table a computed column is written over; a catalog that cannot say it refuses the read, never drops the condition. */
36
+ export function computedTable(schema, id) {
37
+ const table = schema && findTable(schema, id);
38
+ if (!table)
39
+ throw new RequestFault('This read cannot use a computed column.');
40
+ return table;
41
+ }
42
+ /**
43
+ * The filter's computed columns, each checked against the table: a name that is no column of it, a type, and an
44
+ * expression of the parser's own shapes reading only the table's stored columns. Its constants are folded already:
45
+ * `today`, `now` and `me` are the request's, said by whoever resolved the column, so an unfolded one is refused.
46
+ */
47
+ export function checkedComputed(filter, table) {
48
+ const out = new Map();
49
+ const given = filter.computed;
50
+ if (given === undefined)
51
+ return out;
52
+ if (given === null || typeof given !== 'object' || Array.isArray(given))
53
+ refuse('not a map of columns');
54
+ const stored = new Set(table.columns.map((column) => column.name));
55
+ for (const [name, def] of Object.entries(given)) {
56
+ if (!IDENTIFIER.test(name) || stored.has(name))
57
+ refuse(`"${name}" is a column of ${table.name} or no name`);
58
+ if (def === null || typeof def !== 'object')
59
+ refuse(`"${name}" has no definition`);
60
+ if (!COMPUTED_TYPES.includes(def.type))
61
+ refuse(`"${name}" has no type`);
62
+ let size = 0;
63
+ const node = (n) => {
64
+ if (++size > 500)
65
+ refuse(`"${name}" is too large`);
66
+ if (n === null || typeof n !== 'object')
67
+ refuse(`"${name}" is not an expression`);
68
+ const at = n;
69
+ switch (at.k) {
70
+ case 'path':
71
+ if (typeof at.path !== 'string' || !stored.has(at.path))
72
+ refuse(`"${name}" reads what is not a column of ${table.name}`);
73
+ return;
74
+ case 'json':
75
+ if (typeof at.column !== 'string' || !stored.has(at.column))
76
+ refuse(`"${name}" reads what is not a column of ${table.name}`);
77
+ if (!Array.isArray(at.keys) || !at.keys.length || !at.keys.every((key) => typeof key === 'string' && IDENTIFIER.test(key)))
78
+ refuse(`"${name}" names a member that is no identifier`);
79
+ return;
80
+ case 'number':
81
+ if (typeof at.value !== 'number' || !Number.isFinite(at.value))
82
+ refuse(`"${name}" has a figure that is no number`);
83
+ return;
84
+ case 'text':
85
+ if (typeof at.value !== 'string')
86
+ refuse(`"${name}" has text that is no text`);
87
+ return;
88
+ case 'bool':
89
+ if (typeof at.value !== 'boolean')
90
+ refuse(`"${name}" has a yes-or-no that is neither`);
91
+ return;
92
+ case 'date':
93
+ if (typeof at.value !== 'string' || !DAY.test(at.value))
94
+ refuse(`"${name}" has a day that is no day`);
95
+ return;
96
+ case 'instant':
97
+ if (typeof at.value !== 'string' || !INSTANT.test(at.value))
98
+ refuse(`"${name}" has an instant that is no instant`);
99
+ return;
100
+ case 'nobody':
101
+ return;
102
+ case 'not':
103
+ case 'neg':
104
+ return node(at.of);
105
+ case 'empty':
106
+ if (typeof at.negate !== 'boolean')
107
+ refuse(`"${name}" is not an expression`);
108
+ return node(at.of);
109
+ case 'span':
110
+ if (typeof at.unit !== 'string' || !UNITS.has(at.unit))
111
+ refuse(`"${name}" moves by no unit`);
112
+ return node(at.of);
113
+ case 'call':
114
+ if (typeof at.fn !== 'string' || !FUNCTIONS.has(at.fn))
115
+ refuse(`"${name}" calls no function an expression knows`);
116
+ if (!Array.isArray(at.args) || !at.args.length)
117
+ refuse(`"${name}" calls a function with nothing`);
118
+ return at.args.forEach(node);
119
+ case 'op':
120
+ if (typeof at.op !== 'string' || !OPS.has(at.op))
121
+ refuse(`"${name}" has no operator an expression knows`);
122
+ node(at.left);
123
+ return node(at.right);
124
+ /* `today`, `now` and `me` are this request's: folded by whoever resolved the column, never left for the statement. */
125
+ default:
126
+ refuse(`"${name}" is not an expression with its constants said`);
127
+ }
128
+ };
129
+ node(def.expr);
130
+ const kindOf = (path) => columnRead(table.columns.find((column) => column.name === path))?.kind;
131
+ try {
132
+ computedKind(def.expr, kindOf);
133
+ }
134
+ catch {
135
+ refuse(`"${name}" does not type`);
136
+ }
137
+ out.set(name, { type: def.type, expr: def.expr, reads: computedReads(def.expr) });
138
+ }
139
+ return out;
140
+ }
141
+ /**
142
+ * The filter as buildWhere takes it, with its computed columns written where a condition names one: the filter
143
+ * without them, a column resolver that writes the expression in place of the name, and a types reader that says
144
+ * nothing of a computed name (it has no catalog type, so it compares by the operator as written). `column` is how
145
+ * the read writes its own columns; the expression's reads are written through it too.
146
+ */
147
+ export function withComputedWhere(filter, table, style, column = (name) => style.quote(name), types) {
148
+ const computed = checkedComputed(filter, table);
149
+ const { computed: _carried, ...rest } = filter;
150
+ if (!computed.size)
151
+ return { filter: rest, column, types };
152
+ const kindOf = (path) => columnRead(table.columns.find((c) => c.name === path));
153
+ const written = new Map([...computed].map(([name, def]) => [name, `(${compileComputed(def, style, (path) => column(path), kindOf)})`]));
154
+ return {
155
+ filter: rest,
156
+ column: (name, condition) => written.get(name) ?? column(name, condition),
157
+ types: types && ((name) => (written.has(name) ? undefined : types(name))),
158
+ };
159
+ }
@@ -1,3 +1,4 @@
1
+ import type { FilterComputed } from './computedWhere.js';
1
2
  /** One condition in a filter. Values are bound, never interpolated. */
2
3
  export interface Condition {
3
4
  column: string;
@@ -161,6 +162,10 @@ export declare const OPS: ReadonlySet<string>;
161
162
  */
162
163
  export interface Filter {
163
164
  groups: Condition[][];
165
+ /** The computed columns its conditions name, each its type and expression with the request's constants folded
166
+ (computedWhere.ts): a handler's or a loader's own read only, resolved from the reader's catalog by the server.
167
+ An adapter writes them through `withComputedWhere`; anywhere else one is refused, never dropped. */
168
+ computed?: FilterComputed;
164
169
  }
165
170
  export interface SqlFragment {
166
171
  text: string;
@@ -248,6 +248,10 @@ via = false,
248
248
  inline,
249
249
  /** How a `within` condition's subquery is read (`Condition.within`): its relation, scoped where the read is. Absent, one is refused. */
250
250
  within) {
251
+ /* Before anything: a computed column read where nobody wrote its expression would be a column by that name, or no
252
+ condition at all if the groups were empty. Refused, never dropped. */
253
+ if (filter?.computed !== undefined)
254
+ throw new RequestFault('This read cannot use a computed column.');
251
255
  if (!filter?.groups.length)
252
256
  return { text: '', params: [] };
253
257
  const params = [];
@@ -2,9 +2,9 @@ import { MAX_LIMIT } from './reads.js';
2
2
  import { LIKE_ESCAPE, likePattern } from './like.js';
3
3
  import { distance, nearest } from './suggest.js';
4
4
  import { columnKind, findTable } from './schema.js';
5
- import { dateWindow } from './queryDates.js';
5
+ import { bindDate, dateWindow } from './queryDates.js';
6
6
  import { maskQuoted } from './maskQuoted.js';
7
- import { ME_SET, TENANT_FIELD, columnOperand, meOperand, meSetOperand, tenantHolds, tenantOperand, } from './queryOperands.js';
7
+ import { ME_SET, TENANT_FIELD, chosenOperand, columnOperand, meOperand, meSetOperand, tenantHolds, tenantOperand, } from './queryOperands.js';
8
8
  import { CHOICES_TYPE, TAGS_TYPE } from './tagLists.js';
9
9
  import { DEFINED_PATH_TYPE } from './definedFields.js';
10
10
  const RANGE_OPS = new Set(['<', '<=', '>', '>=']);
@@ -503,26 +503,6 @@ function readsAsItself(text) {
503
503
  function unescapeValue(text) {
504
504
  return text.replace(/\\(["'\\])/g, '$1');
505
505
  }
506
- /**
507
- * Dates are bound as ISO strings because both target dialects compare them
508
- * correctly that way: Postgres casts on the way in, and SQLite's documented
509
- * text-date format is exactly ISO-8601. A `Date` object handed to a driver
510
- * is at the mercy of whatever it decides to do with the local timezone.
511
- */
512
- function bindDate(d) {
513
- const pad = (n) => String(n).padStart(2, '0');
514
- const day = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
515
- /* A midnight boundary is bound as the bare day. Text comparison sorts
516
- '2026-08-30' before '2026-08-30 00:00:00', so appending the zero time
517
- made every bare-DATE column compare wrong at the boundary — SQLite
518
- counted a task due *today* as `< today`, i.e. overdue. Bare, the bound
519
- is right for every storage shape at once: it sorts before any datetime
520
- of its day, and a driver casting for a real date/timestamp column reads
521
- it as midnight exactly as before. */
522
- if (!d.getHours() && !d.getMinutes() && !d.getSeconds())
523
- return day;
524
- return `${day} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
525
- }
526
506
  function coerce(column, value, quoted, op) {
527
507
  const kind = column ? columnKind(column.type) : 'other';
528
508
  if (quoted)
@@ -808,6 +788,15 @@ function compileClause(raw, ctx) {
808
788
  const groups = item.quoted ? undefined : (column?.states ?? ctx.states?.[name])?.groups;
809
789
  if (groups && Object.hasOwn(groups, item.value))
810
790
  return { error: `"${item.value}" is a group of ${name}'s states; ask it with is: ${name} is ${item.value}.` };
791
+ const fromChoice = chosenOperand(ctx, item.value, item.quoted);
792
+ if (fromChoice) {
793
+ if (fromChoice.error)
794
+ return { error: fromChoice.error };
795
+ /* Nothing chosen is in no list: left out, as a null profile value is. */
796
+ if (fromChoice.value !== undefined)
797
+ values.push(coerce(column, String(fromChoice.value), false));
798
+ continue;
799
+ }
811
800
  const fromTenant = tenantOperand(ctx, column, item.value, item.quoted);
812
801
  if (fromTenant) {
813
802
  if (fromTenant.error)
@@ -874,6 +863,15 @@ function compileClause(raw, ctx) {
874
863
  if (!quoted && value === 'me' && ctx.me === undefined)
875
864
  return { error: NO_ONE_HERE };
876
865
  /* The reader's tenant profile (`country = tenant.country`), read once for this request; a null value matches no row. */
866
+ /* The person's App choice (`site_id = chosen.site`), proven readable for this request; nothing chosen matches no row. */
867
+ const fromChoice = chosenOperand(ctx, value, quoted);
868
+ if (fromChoice) {
869
+ if (fromChoice.error)
870
+ return { error: fromChoice.error };
871
+ if (fromChoice.none)
872
+ return { conditions: [{ column: name, op: 'in', value: [] }] };
873
+ return { conditions: [{ column: name, op, value: coerce(column, String(fromChoice.value), false) }] };
874
+ }
877
875
  const fromTenant = tenantOperand(ctx, column, value, quoted);
878
876
  if (fromTenant) {
879
877
  if (fromTenant.error)
@@ -7,6 +7,22 @@ interface DateWindow {
7
7
  export declare const DATE_ARITHMETIC: RegExp;
8
8
  /** The day `today ± N units` names, from `today` (YYYY-MM-DD); a month or a year past the month's end lands on its last day. */
9
9
  export declare function shiftedDay(today: string, sign: string, count: number, unit: string): string;
10
+ /**
11
+ * Dates are bound as ISO strings because both target dialects compare them
12
+ * correctly that way: Postgres casts on the way in, and SQLite's documented
13
+ * text-date format is exactly ISO-8601. A `Date` object handed to a driver
14
+ * is at the mercy of whatever it decides to do with the local timezone.
15
+ */
16
+ export declare function bindDate(d: Date): string;
17
+ /**
18
+ * A window's bounds as a read compares against them (bindDate): `start` is in it, `end` is the first moment after it,
19
+ * so `last 30 days` on Nov 20 is 2026-10-21 to 2026-11-21. A custom dashboard section is handed these beside the
20
+ * phrase, to say or draw the span its rows were narrowed to without parsing the grammar itself.
21
+ */
22
+ export declare function windowBounds(phrase: string, now: Date): {
23
+ start: string;
24
+ end: string;
25
+ } | undefined;
10
26
  /**
11
27
  * `now` is a parameter rather than a call to the clock, so the compiler is a
12
28
  * pure function of its inputs. That is what makes the tests below able to
@@ -44,6 +44,35 @@ export function shiftedDay(today, sign, count, unit) {
44
44
  const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();
45
45
  return new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth(), Math.min(d, last))).toISOString().slice(0, 10);
46
46
  }
47
+ /**
48
+ * Dates are bound as ISO strings because both target dialects compare them
49
+ * correctly that way: Postgres casts on the way in, and SQLite's documented
50
+ * text-date format is exactly ISO-8601. A `Date` object handed to a driver
51
+ * is at the mercy of whatever it decides to do with the local timezone.
52
+ */
53
+ export function bindDate(d) {
54
+ const pad = (n) => String(n).padStart(2, '0');
55
+ const day = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
56
+ /* A midnight boundary is bound as the bare day. Text comparison sorts
57
+ '2026-08-30' before '2026-08-30 00:00:00', so appending the zero time
58
+ made every bare-DATE column compare wrong at the boundary — SQLite
59
+ counted a task due *today* as `< today`, i.e. overdue. Bare, the bound
60
+ is right for every storage shape at once: it sorts before any datetime
61
+ of its day, and a driver casting for a real date/timestamp column reads
62
+ it as midnight exactly as before. */
63
+ if (!d.getHours() && !d.getMinutes() && !d.getSeconds())
64
+ return day;
65
+ return `${day} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
66
+ }
67
+ /**
68
+ * A window's bounds as a read compares against them (bindDate): `start` is in it, `end` is the first moment after it,
69
+ * so `last 30 days` on Nov 20 is 2026-10-21 to 2026-11-21. A custom dashboard section is handed these beside the
70
+ * phrase, to say or draw the span its rows were narrowed to without parsing the grammar itself.
71
+ */
72
+ export function windowBounds(phrase, now) {
73
+ const window = dateWindow(phrase, now);
74
+ return window ? { start: bindDate(window.start), end: bindDate(window.end) } : undefined;
75
+ }
47
76
  /**
48
77
  * `now` is a parameter rather than a call to the clock, so the compiler is a
49
78
  * pure function of its inputs. That is what makes the tests below able to
@@ -54,9 +54,21 @@ export interface QueryPerson {
54
54
  * meant, and `tenant.<column>` is then refused rather than read as text.
55
55
  */
56
56
  tenant?: Readonly<Record<string, TenantValue>>;
57
+ /**
58
+ * `chosen.<name>`: the App-wide choices (an App's `choose`) by name, each the row key the person picked,
59
+ * re-read and proven readable under their own row policy for this request — null where nothing is chosen
60
+ * or the pick was not theirs to read. Absent where no App choice is meant, and `chosen.<name>` is then
61
+ * refused rather than read as text.
62
+ */
63
+ chosen?: Readonly<Record<string, string | number | null>>;
57
64
  }
58
65
  /** One column of a tenant's profile row, as a member may read it. */
59
66
  export type TenantValue = string | number | boolean | null;
67
+ /**
68
+ * The App-wide choices a query's text names (`site_id = chosen.site`), in the order they first appear, so a list can
69
+ * say which of them narrows it. Quoted text is a value and not a reference, as the compiler reads it.
70
+ */
71
+ export declare function choicesNamed(...texts: readonly string[]): string[];
60
72
  /** Nobody in particular (`anyone` above): what a check that runs before any request reads `me` as. */
61
73
  export declare const ANYONE: QueryPerson;
62
74
  /** ANYONE for a query kept as it is compiled and served to every request: `tenant.<column>` is refused, not held. */
@@ -110,6 +122,18 @@ export declare function tenantOperand(ctx: CompileContext, column: ColumnMeta |
110
122
  none?: true;
111
123
  error?: string;
112
124
  } | undefined;
125
+ /**
126
+ * What `chosen.<name>` stands for beside one column: the row key the person picked for this request.
127
+ * Undefined where the word is not one (quoted, or the table has a `chosen` column of its own, whose path it
128
+ * then is). Nothing chosen matches no row, as a null tenant value does: a list about the current site shows
129
+ * no site's rows rather than every site's. A check before any request (ANYONE) reads it as the word; a query
130
+ * kept for every request refuses it, as it refuses `tenant.<column>`.
131
+ */
132
+ export declare function chosenOperand(ctx: CompileContext, word: string, quoted: boolean): {
133
+ value?: string | number;
134
+ none?: true;
135
+ error?: string;
136
+ } | undefined;
113
137
  /**
114
138
  * The column an unquoted right-hand side names, when it names one.
115
139
  *
@@ -1,6 +1,19 @@
1
1
  import { columnKind } from './schema.js';
2
2
  /** `tenant.<column>`, unquoted, on the right of a comparison or in a value list. */
3
3
  const TENANT_VALUE = /^tenant\.([A-Za-z_]\w*)$/;
4
+ /** `chosen.<name>`, unquoted, on the right of a comparison or in a value list. */
5
+ const CHOSEN_VALUE = /^chosen\.([A-Za-z_]\w*)$/;
6
+ /**
7
+ * The App-wide choices a query's text names (`site_id = chosen.site`), in the order they first appear, so a list can
8
+ * say which of them narrows it. Quoted text is a value and not a reference, as the compiler reads it.
9
+ */
10
+ export function choicesNamed(...texts) {
11
+ const found = new Set();
12
+ for (const text of texts)
13
+ for (const [, name] of text.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""').matchAll(/(?<![\w.])chosen\.([A-Za-z_]\w*)/g))
14
+ found.add(name);
15
+ return [...found];
16
+ }
4
17
  /** Nobody in particular (`anyone` above): what a check that runs before any request reads `me` as. */
5
18
  export const ANYONE = Object.freeze({ email: null, anyone: true });
6
19
  /** ANYONE for a query kept as it is compiled and served to every request: `tenant.<column>` is refused, not held. */
@@ -84,6 +97,29 @@ export function tenantOperand(ctx, column, word, quoted) {
84
97
  return { error: `${word} is a flag, and ${column.name} is not.` };
85
98
  return { value };
86
99
  }
100
+ /**
101
+ * What `chosen.<name>` stands for beside one column: the row key the person picked for this request.
102
+ * Undefined where the word is not one (quoted, or the table has a `chosen` column of its own, whose path it
103
+ * then is). Nothing chosen matches no row, as a null tenant value does: a list about the current site shows
104
+ * no site's rows rather than every site's. A check before any request (ANYONE) reads it as the word; a query
105
+ * kept for every request refuses it, as it refuses `tenant.<column>`.
106
+ */
107
+ export function chosenOperand(ctx, word, quoted) {
108
+ const match = quoted ? null : CHOSEN_VALUE.exec(word);
109
+ if (!match || ctx.table?.columns.some((c) => c.name === 'chosen'))
110
+ return undefined;
111
+ const me = ctx.me;
112
+ if (me?.anyone && me.chosen === undefined)
113
+ return me.once
114
+ ? { error: `${word} is a choice of one request's person, and this query is read once for every request, so it cannot ask it.` }
115
+ : { value: word };
116
+ if (!me?.chosen)
117
+ return { error: `${word} is the person's App choice, and no App choice is meant here. Quote it ("${word}") to mean the text.` };
118
+ if (!Object.hasOwn(me.chosen, match[1]))
119
+ return { error: `${word} names no choice: the App's choose declares ${Object.keys(me.chosen).join(', ') || 'none'}.` };
120
+ const value = me.chosen[match[1]];
121
+ return value === null ? { none: true } : { value };
122
+ }
87
123
  const COMPARISON_OPS = new Set(['=', '!=', '<', '<=', '>', '>=']);
88
124
  const BARE_WORD = /^[A-Za-z_$][\w$]*$/;
89
125
  const PATH_WORD = /^[A-Za-z_$][\w$+]*(?:\.[A-Za-z_$][\w$+]*)+$/;
@@ -31,6 +31,14 @@ export declare class RequestFault extends Refusal {
31
31
  }
32
32
  /** Whether a refusal is a request that can never succeed as written (`RequestFault`), from any copy of the module. */
33
33
  export declare const isRequestFault: (error: unknown) => error is RequestFault;
34
+ declare const FROZEN_REFUSAL: unique symbol;
35
+ export declare class FrozenRefusal extends Refusal {
36
+ readonly [FROZEN_REFUSAL] = true;
37
+ /** The sentence the caller reads: it names the resource and the condition, never a value of the row. */
38
+ constructor(message: string);
39
+ }
40
+ /** Whether a refusal is a frozen record's (`FrozenRefusal`), from any copy of the module. */
41
+ export declare const isFrozenRefusal: (error: unknown) => error is FrozenRefusal;
34
42
  /** Record why a refusal happened on the refusal itself, for the trusted reader
35
43
  * only. Every opaque refusal takes its reason this way — a tenant denial, a
36
44
  * row policy that did not load, a command the database would not take — so
@@ -44,6 +44,21 @@ export class RequestFault extends Refusal {
44
44
  }
45
45
  /** Whether a refusal is a request that can never succeed as written (`RequestFault`), from any copy of the module. */
46
46
  export const isRequestFault = (error) => error instanceof Error && error[REQUEST_FAULT] === true;
47
+ /* A write to a record its resource declares frozen (`frozen: 'status = closed'`): the record's state, never the
48
+ caller's grants, so every door that says a refusal's status and code says this one 409 `frozen`. Branded as
49
+ RequestFault is, for a handler's second copy of this module. */
50
+ const FROZEN_REFUSAL = Symbol.for('mistri.frozenRefusal');
51
+ export class FrozenRefusal extends Refusal {
52
+ [FROZEN_REFUSAL] = true;
53
+ /** The sentence the caller reads: it names the resource and the condition, never a value of the row. */
54
+ constructor(message) {
55
+ super(message);
56
+ this.name = 'FrozenRefusal';
57
+ sayRefusal(this, message);
58
+ }
59
+ }
60
+ /** Whether a refusal is a frozen record's (`FrozenRefusal`), from any copy of the module. */
61
+ export const isFrozenRefusal = (error) => error instanceof Error && error[FROZEN_REFUSAL] === true;
47
62
  /* Why a refusal happened, kept for the trusted owner that has to diagnose it.
48
63
  A caller hears one fixed sentence and must: a driver's error text names
49
64
  columns, values and internal tables, and a clash on a hidden unique column
@@ -134,7 +134,7 @@ type ResourceHttpIdentity<Mode extends ResourceHttpMode> = Mode extends 'app' ?
134
134
  conn?: string;
135
135
  app?: never;
136
136
  };
137
- type HttpErrorCode = 'validation_failed' | 'consumes_refused' | 'record_conflict' | 'required_value' | 'duplicate_value' | 'reference_conflict' | 'constraint_failed' | 'data_unavailable' | 'write_unconfirmed' | 'forbidden' | 'undo_failed';
137
+ type HttpErrorCode = 'validation_failed' | 'consumes_refused' | 'frozen' | 'record_conflict' | 'required_value' | 'duplicate_value' | 'reference_conflict' | 'constraint_failed' | 'data_unavailable' | 'write_unconfirmed' | 'forbidden' | 'undo_failed';
138
138
  export interface HttpDiagnostic {
139
139
  message: string;
140
140
  at?: number;
@@ -0,0 +1,5 @@
1
+ import { type DatabaseSchema } from './schema.js';
2
+ type Cell = string | number | boolean | null | undefined;
3
+ /** True when `row` plainly meets the condition `text` over `tableId`; false wherever that cannot be said exactly. */
4
+ export declare function rowMeetsCondition(schema: DatabaseSchema | undefined, tableId: string, text: string, row: Readonly<Record<string, Cell>>): boolean;
5
+ export {};
@@ -0,0 +1,80 @@
1
+ import { ANYONE, parseQuery } from './query.js';
2
+ import { columnKind } from './schema.js';
3
+ const parsed = new WeakMap();
4
+ /** The condition's groups (ORed, each ANDed), or null where it does not parse over the table. */
5
+ function groupsOf(schema, table, text) {
6
+ let known = parsed.get(schema);
7
+ if (!known)
8
+ parsed.set(schema, (known = new Map()));
9
+ const at = `${table.id} ${text}`;
10
+ if (known.has(at))
11
+ return known.get(at);
12
+ const result = parseQuery(at, { schema, columnValues: true, me: ANYONE });
13
+ const groups = result.errors.length || !result.query ? null : result.query.filter.groups;
14
+ known.set(at, groups);
15
+ return groups;
16
+ }
17
+ const truthy = (value) => value === true || value === 1 || /^(1|true|t|yes|y)$/i.test(String(value));
18
+ function met(table, row, condition) {
19
+ if (condition.other !== undefined || condition.any !== undefined || condition.within !== undefined || condition.column.includes('.'))
20
+ return false;
21
+ if (!Object.hasOwn(row, condition.column))
22
+ return false;
23
+ const column = table.columns.find((candidate) => candidate.name === condition.column);
24
+ if (!column)
25
+ return false;
26
+ const value = row[condition.column];
27
+ const empty = value === null || value === undefined;
28
+ if (condition.op === 'isNull')
29
+ return empty;
30
+ if (condition.op === 'isNotNull')
31
+ return !empty;
32
+ if (empty)
33
+ return false;
34
+ const kind = columnKind(column.type);
35
+ const same = (given) => given !== null &&
36
+ given !== undefined &&
37
+ (kind === 'number'
38
+ ? Number(value) === Number(given)
39
+ : kind === 'boolean'
40
+ ? truthy(value) === truthy(given)
41
+ : String(value) === String(given));
42
+ const given = condition.value;
43
+ switch (condition.op) {
44
+ case '=':
45
+ return !Array.isArray(given) && same(given);
46
+ case '!=':
47
+ return !Array.isArray(given) && given !== null && given !== undefined && !same(given);
48
+ case 'in':
49
+ return Array.isArray(given) && given.some(same);
50
+ case '>':
51
+ case '>=':
52
+ case '<':
53
+ case '<=': {
54
+ if (Array.isArray(given) || given === null || given === undefined)
55
+ return false;
56
+ const [left, right] = kind === 'number' ? [Number(value), Number(given)] : [String(value), String(given)];
57
+ if (kind !== 'number' && kind !== 'date')
58
+ return false;
59
+ if (typeof left === 'number' && Number.isNaN(left))
60
+ return false;
61
+ return condition.op === '>'
62
+ ? left > right
63
+ : condition.op === '>='
64
+ ? left >= right
65
+ : condition.op === '<'
66
+ ? left < right
67
+ : left <= right;
68
+ }
69
+ default:
70
+ return false;
71
+ }
72
+ }
73
+ /** True when `row` plainly meets the condition `text` over `tableId`; false wherever that cannot be said exactly. */
74
+ export function rowMeetsCondition(schema, tableId, text, row) {
75
+ const table = schema?.tables.find((candidate) => candidate.id === tableId);
76
+ if (!schema || !table)
77
+ return false;
78
+ const groups = groupsOf(schema, table, text);
79
+ return groups !== null && groups.some((group) => group.length > 0 && group.every((condition) => met(table, row, condition)));
80
+ }
@@ -142,9 +142,19 @@ export declare function chooseColumnReference(candidates: readonly ColumnReferen
142
142
  * column the connection already hides, rather than be told it is no column.
143
143
  */
144
144
  export declare const CONNECTION_HIDDEN: unique symbol;
145
+ /**
146
+ * Of a table's declared rollups and computed columns, the ones a reader's
147
+ * field grant names (ColumnGrant.derived), set by pruning to that grant. They
148
+ * are added after pruning (the App's catalog), so pruning cannot cut them;
149
+ * this says which to keep. Absent, every one whose inputs the reader reads.
150
+ * A symbol, so it is never written into a JSON answer.
151
+ */
152
+ export declare const GRANTED_DERIVED: unique symbol;
145
153
  export interface TableMeta {
146
154
  /** What the connection hides of this table (CONNECTION_HIDDEN); never serialized. */
147
155
  readonly [CONNECTION_HIDDEN]?: readonly string[];
156
+ /** Of its rollups and computed columns, the ones the reader's field grant names (GRANTED_DERIVED); never serialized. */
157
+ readonly [GRANTED_DERIVED]?: readonly string[];
148
158
  name: string;
149
159
  /** Server-projected delete affordance, never authority; may account for hidden columns. */
150
160
  deletable?: boolean;
@@ -60,6 +60,14 @@ export function chooseColumnReference(candidates) {
60
60
  * column the connection already hides, rather than be told it is no column.
61
61
  */
62
62
  export const CONNECTION_HIDDEN = Symbol('mistri.connectionHidden');
63
+ /**
64
+ * Of a table's declared rollups and computed columns, the ones a reader's
65
+ * field grant names (ColumnGrant.derived), set by pruning to that grant. They
66
+ * are added after pruning (the App's catalog), so pruning cannot cut them;
67
+ * this says which to keep. Absent, every one whose inputs the reader reads.
68
+ * A symbol, so it is never written into a JSON answer.
69
+ */
70
+ export const GRANTED_DERIVED = Symbol('mistri.grantedDerived');
63
71
  /**
64
72
  * A dialect's spelling of an `ON DELETE` action, normalised.
65
73
  *
@@ -1,4 +1,4 @@
1
- import type { DatabaseSchema } from './schema.js';
1
+ import { type DatabaseSchema } from './schema.js';
2
2
  /** Test-only: how many catalogs were copied and checked in full. */
3
3
  export declare const scopeCatalogCounters: {
4
4
  captured: number;
@@ -1,4 +1,5 @@
1
1
  import { Refusal } from './refusal.js';
2
+ import { GRANTED_DERIVED } from './schema.js';
2
3
  const refuse = () => {
3
4
  throw new Refusal('The scoped catalog could not be verified. Refresh the catalog and permissions before continuing.');
4
5
  };
@@ -73,7 +74,18 @@ function copyData(input) {
73
74
  }
74
75
  return Object.fromEntries(keys.map((key) => {
75
76
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
76
- if (typeof key !== 'string' || !descriptor.enumerable || !('value' in descriptor))
77
+ if (!descriptor.enumerable || !('value' in descriptor))
78
+ return refuse();
79
+ /* The one symbol a catalog carries: which of a table's rollups and computed columns its reader's field
80
+ grant names (columnGrants.ts). It narrows what appRollups.ts serves and grants nothing, so it is
81
+ carried as a frozen list of names and left out of the fingerprint; any other symbol is refused. */
82
+ if (key === GRANTED_DERIVED) {
83
+ const names = descriptor.value;
84
+ if (!Array.isArray(names) || names.length > 4_096 || names.some((name) => !identifier(name)))
85
+ return refuse();
86
+ return [key, Object.freeze(names.map((name) => copy(name, depth + 1)))];
87
+ }
88
+ if (typeof key !== 'string')
77
89
  return refuse();
78
90
  if ((characters += key.length) > 16_777_216)
79
91
  return refuse();