@object-ui/core 16.1.0 → 17.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +1355 -4
  2. package/dist/actions/ActionRunner.d.ts +82 -14
  3. package/dist/actions/ActionRunner.js +164 -81
  4. package/dist/actions/actionKeys.d.ts +118 -0
  5. package/dist/actions/actionKeys.js +243 -0
  6. package/dist/actions/index.d.ts +1 -0
  7. package/dist/actions/index.js +1 -0
  8. package/dist/adapters/ApiDataSource.js +10 -1
  9. package/dist/adapters/ValueDataSource.d.ts +2 -2
  10. package/dist/evaluator/fieldRules.d.ts +0 -2
  11. package/dist/evaluator/fieldRules.js +3 -2
  12. package/dist/evaluator/optionLint.js +5 -2
  13. package/dist/evaluator/optionRules.d.ts +13 -6
  14. package/dist/evaluator/optionRules.js +0 -23
  15. package/dist/index.d.ts +4 -0
  16. package/dist/index.js +7 -0
  17. package/dist/registry/Registry.d.ts +81 -2
  18. package/dist/registry/Registry.js +102 -2
  19. package/dist/registry/public-blocks.js +52 -1
  20. package/dist/theme/ThemeEngine.js +0 -12
  21. package/dist/utils/chart-series.d.ts +28 -0
  22. package/dist/utils/chart-series.js +55 -0
  23. package/dist/utils/column-identity.d.ts +110 -0
  24. package/dist/utils/column-identity.js +210 -0
  25. package/dist/utils/dashboard-filters.d.ts +2 -2
  26. package/dist/utils/expand-fields.js +8 -8
  27. package/dist/utils/filter-converter.d.ts +47 -0
  28. package/dist/utils/filter-converter.js +94 -7
  29. package/dist/utils/filter-tokens.d.ts +101 -0
  30. package/dist/utils/filter-tokens.js +173 -0
  31. package/dist/utils/managedBy.d.ts +21 -3
  32. package/dist/utils/managedBy.js +45 -4
  33. package/dist/utils/normalize-list-view.d.ts +99 -0
  34. package/dist/utils/normalize-list-view.js +255 -0
  35. package/dist/utils/sort-values.d.ts +52 -0
  36. package/dist/utils/sort-values.js +125 -0
  37. package/dist/validation/index.d.ts +9 -1
  38. package/dist/validation/index.js +9 -1
  39. package/dist/validation/validators/index.d.ts +7 -1
  40. package/dist/validation/validators/index.js +7 -1
  41. package/dist/validation/validators/object-validation-engine.d.ts +151 -31
  42. package/dist/validation/validators/object-validation-engine.js +275 -142
  43. package/package.json +4 -4
@@ -0,0 +1,210 @@
1
+ /**
2
+ * ObjectUI — column identity canonicalization
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ /**
9
+ * The spec's canonical key for "which object field this column shows".
10
+ * `ListColumnSchema` (`@objectstack/spec/view`) declares `field: z.ZodString`
11
+ * as its ONLY required key — there is no `name`, no `fieldName`, no
12
+ * `accessorKey` on it. So `field` is not one dialect among several: it is the
13
+ * contract, and everything else is objectui-side legacy (AGENTS.md #0).
14
+ *
15
+ * Note this is the exact opposite of the FORM layer, where the runtime key is
16
+ * `name` (objectui#3090). The two surfaces sit next to each other and mean the
17
+ * opposite thing by the same pair of key names, which is why copy-paste between
18
+ * them keeps producing the defect this module exists to close.
19
+ */
20
+ export const CANONICAL_COLUMN_IDENTITY_KEY = 'field';
21
+ /**
22
+ * Legacy identity spellings, in the order a canonicalizing read falls back
23
+ * through them. `field` wins over both, always.
24
+ *
25
+ * `fieldName` is here for defence, not because objectui emits it: as of
26
+ * objectui#3104 a repo-wide scan finds NO writer of a column-level `fieldName`
27
+ * — every `fieldName:` occurrence in the tree is a function parameter or an
28
+ * unrelated interface member (`AIFieldSuggestion.fieldName`). It survives
29
+ * purely in READERS that were written defensively, and stored host metadata
30
+ * could still carry it, so the fold accepts it and the ratchet counts it.
31
+ */
32
+ export const LEGACY_COLUMN_IDENTITY_KEYS = ['name', 'fieldName'];
33
+ /**
34
+ * NOT an identity key — deliberately excluded from everything in this module.
35
+ *
36
+ * `accessorKey` is TanStack Table's own column key (`TableColumn.accessorKey`,
37
+ * `packages/types/src/data-display.ts`, "Data accessor key"). It names a slot in
38
+ * the table LIBRARY's column model, not a field in ObjectStack metadata. Reads
39
+ * like `RelatedList`'s `accessorKey || field || name` therefore merge two
40
+ * different vocabularies in one expression; canonicalizing across that boundary
41
+ * would fossilize the merge, which is precisely the mistake this battle exists
42
+ * to undo. The fold neither reads nor writes it.
43
+ */
44
+ export const TABLE_ADAPTER_COLUMN_KEY = 'accessorKey';
45
+ const isRecord = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
46
+ const asIdentity = (v) => typeof v === 'string' && v.length > 0 ? v : undefined;
47
+ /**
48
+ * Read a column entry's field identity — the ONE reader every consumer should
49
+ * converge onto (objectui#3104 PR2).
50
+ *
51
+ * Accepts the three shapes a `columns` array actually holds: a bare string
52
+ * (`'stage'`), a spec column (`{ field: 'stage' }`), and the legacy objectui
53
+ * shapes (`{ name }` / `{ fieldName }`). Resolution is canonical-first, so it
54
+ * agrees with `buildExpandFields` and with the `$select` projection rather than
55
+ * with whichever half of a mixed-key column happened to be read.
56
+ *
57
+ * Returns `undefined` — not `''` — when nothing is resolvable, so callers can
58
+ * tell "no identity" from "identity is the empty string" and drop the entry
59
+ * instead of requesting a nameless column.
60
+ */
61
+ export function columnIdentity(entry) {
62
+ if (typeof entry === 'string')
63
+ return asIdentity(entry);
64
+ if (!isRecord(entry))
65
+ return undefined;
66
+ const canonical = asIdentity(entry[CANONICAL_COLUMN_IDENTITY_KEY]);
67
+ if (canonical)
68
+ return canonical;
69
+ for (const key of LEGACY_COLUMN_IDENTITY_KEYS) {
70
+ const legacy = asIdentity(entry[key]);
71
+ if (legacy)
72
+ return legacy;
73
+ }
74
+ return undefined;
75
+ }
76
+ /**
77
+ * True when a column entry carries more than one identity key AND they
78
+ * disagree — the shape that makes the renderer and the data request resolve
79
+ * two different fields. Exported for the "say who wins, loudly" step
80
+ * (objectui#3104 PR3) and used by the tests to name the defect precisely.
81
+ */
82
+ export function hasConflictingColumnIdentity(entry) {
83
+ if (!isRecord(entry))
84
+ return false;
85
+ const resolved = columnIdentity(entry);
86
+ if (!resolved)
87
+ return false;
88
+ for (const key of [CANONICAL_COLUMN_IDENTITY_KEY, ...LEGACY_COLUMN_IDENTITY_KEYS]) {
89
+ const present = asIdentity(entry[key]);
90
+ if (present && present !== resolved)
91
+ return true;
92
+ }
93
+ return false;
94
+ }
95
+ // Warn once per (identity, conflicting spelling), not once per fold: columns are
96
+ // re-normalized on every ListView render, and a warning that floods the console
97
+ // is a warning that gets muted. Keyed by the pair rather than by the identity
98
+ // alone so a column carrying two different stale spellings reports both — the
99
+ // author needs to fix every producer, not just the first one seen.
100
+ const warnedConflicts = new Set();
101
+ /** Reset the warn-once memo. Exported for tests. */
102
+ export function resetColumnIdentityWarnings() {
103
+ warnedConflicts.clear();
104
+ }
105
+ const isDev = () => globalThis.process?.env?.NODE_ENV !==
106
+ 'production';
107
+ /**
108
+ * Dev-mode only: say which key won, out loud, when a column carries two identity
109
+ * spellings that disagree.
110
+ *
111
+ * This is the audible half of objectui#3104. The fold below makes the two halves
112
+ * of such a column agree, which is what stops the bug — but silently rewriting
113
+ * `name` to match `field` also hides that the metadata producer is emitting a
114
+ * contradiction. The renderer recovering is not the same as the metadata being
115
+ * right, so the recovery says so.
116
+ *
117
+ * Non-breaking by construction: changes no types, rejects nothing, and is a
118
+ * no-op under `NODE_ENV=production`.
119
+ */
120
+ function warnOnConflictingIdentity(entry, identity, losing) {
121
+ if (!isDev() || losing.length === 0)
122
+ return;
123
+ for (const key of losing) {
124
+ const memo = `${identity}:${key}:${String(entry[key])}`;
125
+ if (warnedConflicts.has(memo))
126
+ continue;
127
+ warnedConflicts.add(memo);
128
+ // eslint-disable-next-line no-console
129
+ console.warn(`[ObjectUI] Column carries two identities: \`${CANONICAL_COLUMN_IDENTITY_KEY}: ` +
130
+ `'${identity}'\` and \`${key}: '${String(entry[key])}'\`. ` +
131
+ `\`${CANONICAL_COLUMN_IDENTITY_KEY}\` wins — it is the only key ` +
132
+ `\`ListColumnSchema\` declares — and \`${key}\` has been rewritten to match, ` +
133
+ `so the rendered column and the requested field agree. Fix the producer: ` +
134
+ `drop \`${key}\` and author \`${CANONICAL_COLUMN_IDENTITY_KEY}\` only. ` +
135
+ `(objectui#3104)`);
136
+ }
137
+ }
138
+ /**
139
+ * Stamp the canonical identity onto one column entry.
140
+ *
141
+ * The transitional strategy (objectui#3104 PR1) is **mirror, don't delete**:
142
+ *
143
+ * - `field` is written with the resolved identity, so the request path — which
144
+ * reads `field` and ONLY `field` in `ListView`'s `$expand`/`$select`
145
+ * builders and in `ObjectGrid.getSelectFields` — always finds one.
146
+ * - a legacy key that is ALREADY PRESENT is overwritten with that same
147
+ * identity, so the name-first read sites still standing (`ListView` ×8,
148
+ * `ObjectGrid`, `ObjectTree`, the detail renderers) resolve to exactly what
149
+ * the request asked for.
150
+ * - a legacy key that is ABSENT is never invented. A spec-clean
151
+ * `{ field: 'stage' }` comes back untouched, by reference; the fold does not
152
+ * manufacture the legacy vocabulary it is trying to retire.
153
+ *
154
+ * This differs on purpose from `normalizeListViewSchema`'s other folds, which
155
+ * DELETE the legacy key so a missed read-site fails loudly. Deleting works
156
+ * inside this repo — every name-first read here falls through to `field` — but
157
+ * `columns` entries cross the package boundary into host applications and
158
+ * third-party renderers, and dropping `name` from under them is a breaking
159
+ * change we have no inventory for. Mirroring is behaviour-preserving for every
160
+ * reader, in or out of the repo; the deletion is PR3's call to make once the
161
+ * in-repo consumers have converged onto {@link columnIdentity}.
162
+ *
163
+ * The result: for any single-key column the resolved identity is unchanged at
164
+ * every read site. The only entries whose behaviour moves are the ones where
165
+ * two sites already disagreed — which is the defect, not a regression.
166
+ */
167
+ export function normalizeColumnIdentity(entry) {
168
+ if (typeof entry === 'string' || !isRecord(entry))
169
+ return entry;
170
+ const identity = columnIdentity(entry);
171
+ if (!identity)
172
+ return entry;
173
+ const needsCanonical = entry[CANONICAL_COLUMN_IDENTITY_KEY] !== identity;
174
+ const staleLegacy = LEGACY_COLUMN_IDENTITY_KEYS.filter((key) => entry[key] !== undefined && entry[key] !== identity);
175
+ if (!needsCanonical && staleLegacy.length === 0)
176
+ return entry;
177
+ // Say who won before rewriting, while the losing spelling is still readable.
178
+ // Only genuine contradictions are reported: a column that merely lacks the
179
+ // canonical key (`{ name: 'stage' }`) is legacy, not conflicting, and gets
180
+ // stamped without noise.
181
+ warnOnConflictingIdentity(entry, identity, staleLegacy);
182
+ const next = { ...entry };
183
+ next[CANONICAL_COLUMN_IDENTITY_KEY] = identity;
184
+ for (const key of staleLegacy)
185
+ next[key] = identity;
186
+ return next;
187
+ }
188
+ /**
189
+ * Stamp the canonical identity across a `columns` array.
190
+ *
191
+ * Non-mutating and allocation-frugal in the same way as
192
+ * `normalizeListViewSchema`: when every entry is already canonical the INPUT
193
+ * array is returned by reference, so `ListView`'s downstream `useMemo`s keep a
194
+ * stable dependency identity on the common path and nothing re-renders.
195
+ *
196
+ * String entries pass through untouched — a bare `'stage'` is unambiguous and
197
+ * every consumer already special-cases it.
198
+ */
199
+ export function normalizeColumnIdentities(columns) {
200
+ if (!Array.isArray(columns))
201
+ return columns;
202
+ let changed = false;
203
+ const next = columns.map((entry) => {
204
+ const folded = normalizeColumnIdentity(entry);
205
+ if (folded !== entry)
206
+ changed = true;
207
+ return folded;
208
+ });
209
+ return (changed ? next : columns);
210
+ }
@@ -18,7 +18,7 @@
18
18
  * Everything in this module is pure and synchronous so the binding rules
19
19
  * are unit-testable in isolation from React and the data layer.
20
20
  */
21
- import type { DashboardSchema, DashboardWidgetSchema, PageVariable } from '@object-ui/types';
21
+ import type { DashboardComponentSchema, DashboardWidgetSchema, PageVariable } from '@object-ui/types';
22
22
  /** Reserved filter name for the dashboard's built-in date range. */
23
23
  export declare const DATE_RANGE_FILTER_NAME = "dateRange";
24
24
  export interface DashboardFilterDef {
@@ -66,7 +66,7 @@ export declare const DATE_RANGE_PRESETS: string[];
66
66
  * under the reserved name `"dateRange"`; each `globalFilters` entry follows,
67
67
  * named by its `name` (defaulting to `field`). Later duplicates win.
68
68
  */
69
- export declare function resolveDashboardFilterDefs(schema: Pick<DashboardSchema, 'globalFilters' | 'dateRange'>): DashboardFilterDef[];
69
+ export declare function resolveDashboardFilterDefs(schema: Pick<DashboardComponentSchema, 'globalFilters' | 'dateRange'>): DashboardFilterDef[];
70
70
  /**
71
71
  * Derive `PageVariable` definitions for a dashboard's filter values so the
72
72
  * dashboard can host them in a `PageVariablesProvider` (the page/dashboard
@@ -5,6 +5,7 @@
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
+ import { columnIdentity } from './column-identity.js';
8
9
  /**
9
10
  * Relational ("reference-bearing") field types whose stored value is a foreign
10
11
  * key into another object — and which therefore benefit from `$expand` so a
@@ -90,14 +91,13 @@ export function buildExpandFields(schemaFields, columns) {
90
91
  if (columns && Array.isArray(columns) && columns.length > 0) {
91
92
  const columnFieldNames = new Set();
92
93
  for (const col of columns) {
93
- if (typeof col === 'string') {
94
- columnFieldNames.add(col);
95
- }
96
- else if (col && typeof col === 'object') {
97
- const name = col.field ?? col.name ?? col.fieldName;
98
- if (name)
99
- columnFieldNames.add(name);
100
- }
94
+ // `columnIdentity` handles all three entry shapes (bare string, spec
95
+ // `{field}`, legacy `{name}`/`{fieldName}`) and resolves canonical-first
96
+ // — the same precedence every renderer now uses, so what gets expanded
97
+ // and what gets rendered can no longer name two different fields (#3104).
98
+ const name = columnIdentity(col);
99
+ if (name)
100
+ columnFieldNames.add(name);
101
101
  }
102
102
  return referenceFieldNames.filter((f) => columnFieldNames.has(f));
103
103
  }
@@ -29,6 +29,19 @@ export type FilterNode = [string, string, any] | [string, ...FilterNode[]];
29
29
  * @param operator - MongoDB-style operator (e.g., '$gte', '$in')
30
30
  * @returns ObjectStack operator or null if not recognized
31
31
  */
32
+ /**
33
+ * A filter operator this layer will not translate.
34
+ *
35
+ * Carries the data API's own code and status for the same refusal so a failed
36
+ * list renders "the filter is malformed" rather than "check your connection" —
37
+ * `classifyLoadError` reads these, and a bare `Error` classifies as a network
38
+ * fault, which is the one thing this is definitely not.
39
+ */
40
+ export declare class FilterOperatorError extends Error {
41
+ readonly code = "INVALID_FILTER";
42
+ readonly httpStatus = 400;
43
+ constructor(message: string);
44
+ }
32
45
  export declare function convertOperatorToAST(operator: string): string | null;
33
46
  /**
34
47
  * Convert object-based filters to ObjectStack FilterNode AST format.
@@ -55,3 +68,37 @@ export declare function convertOperatorToAST(operator: string): string | null;
55
68
  * @throws {Error} If an unknown operator is encountered
56
69
  */
57
70
  export declare function convertFiltersToAST(filter: Record<string, any>): FilterNode | Record<string, any>;
71
+ /**
72
+ * Normalize ONE filter source into a single filter node.
73
+ *
74
+ * A "source" is whatever a view hands a renderer, and there are three shapes in
75
+ * circulation, all legitimate:
76
+ *
77
+ * - `[{ field, operator, value }, ...]` a spec `ViewFilterRule[]`
78
+ * - `[['stage', '=', 'won'], ...]` an AST node / legacy flat array
79
+ * - `{ status: 'active' }` a MongoDB-style object
80
+ *
81
+ * The third is the one that kept getting lost. Renderers tested `source.length
82
+ * > 0` before using it, which is `undefined > 0` for an object — so a
83
+ * `table.defaultFilters` (declared `Record<string, any>`) was DROPPED and the
84
+ * view returned every record. Silently: no error, just a wider answer.
85
+ *
86
+ * Returns `undefined` for an absent or empty source, so callers can skip
87
+ * `$filter` rather than sending an empty array.
88
+ */
89
+ export declare function toFilterNode(source: unknown): FilterNode | Record<string, any> | undefined;
90
+ /**
91
+ * Combine filter sources under a single `and`, each as its OWN child.
92
+ *
93
+ * Wrapping rather than spreading, on purpose. `['and', ...rules]` looks
94
+ * equivalent and is not: spreading a `ViewFilterRule[]` puts bare rule OBJECTS
95
+ * where the AST expects nodes, and the server neither understands nor rejects
96
+ * that cleanly — `isFilterAST` says no (a 400 since objectstack#4121), while
97
+ * `parseFilterAST` reads the rule as a Mongo condition and filters on columns
98
+ * literally named `field` / `operator` / `value`. Spreading is only correct
99
+ * when the source happens to be an array of nodes, which is why it survived.
100
+ *
101
+ * Sources that normalize to nothing are skipped; one surviving source is
102
+ * returned as-is rather than wrapped in a pointless `and`.
103
+ */
104
+ export declare function mergeFilterNodes(...sources: unknown[]): FilterNode | Record<string, any> | undefined;
@@ -11,6 +11,32 @@
11
11
  * @param operator - MongoDB-style operator (e.g., '$gte', '$in')
12
12
  * @returns ObjectStack operator or null if not recognized
13
13
  */
14
+ /**
15
+ * A filter operator this layer will not translate.
16
+ *
17
+ * Carries the data API's own code and status for the same refusal so a failed
18
+ * list renders "the filter is malformed" rather than "check your connection" —
19
+ * `classifyLoadError` reads these, and a bare `Error` classifies as a network
20
+ * fault, which is the one thing this is definitely not.
21
+ */
22
+ export class FilterOperatorError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ Object.defineProperty(this, "code", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: 'INVALID_FILTER'
30
+ });
31
+ Object.defineProperty(this, "httpStatus", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: 400
36
+ });
37
+ this.name = 'FilterOperatorError';
38
+ }
39
+ }
14
40
  export function convertOperatorToAST(operator) {
15
41
  // Spec reference: framework/packages/spec/src/data/filter.zod.ts
16
42
  // Canonical MongoDB-style keys are camelCase ($startsWith, $endsWith, $notContains).
@@ -69,14 +95,22 @@ export function convertFiltersToAST(filter) {
69
95
  if (typeof value === 'object' && !Array.isArray(value)) {
70
96
  // Handle operator-based filters
71
97
  for (const [operator, operatorValue] of Object.entries(value)) {
72
- // Special handling for $regex - warn users about limited support
98
+ // `$regex` is refused, not downgraded. It used to become `contains`
99
+ // behind a `console.warn` — but substring matching is a DIFFERENT
100
+ // QUESTION, not a weaker version of the same one: `$regex: 'a.c'`
101
+ // matches "abc", `contains 'a.c'` does not, and neither result looks
102
+ // wrong on screen. A warning is not an error channel; nobody reads the
103
+ // console of a deployed app.
104
+ //
105
+ // The spec has no `$regex` (`FILTER_OPERATORS`, data/filter.zod.ts), so
106
+ // there is nothing to translate it INTO. Same treatment the unknown
107
+ // operator below already gets, and for the same stated reason.
73
108
  if (operator === '$regex') {
74
- console.warn(`[ObjectUI] Warning: $regex operator is not fully supported. ` +
75
- `Converting to 'contains' which only supports substring matching, not regex patterns. ` +
109
+ throw new FilterOperatorError(`[ObjectUI] The '$regex' filter operator is not supported. It used to be ` +
110
+ `converted to 'contains', which matches a literal substring rather than a ` +
111
+ `pattern — a different result, not a degraded one. ` +
76
112
  `Field: '${field}', Value: ${JSON.stringify(operatorValue)}. ` +
77
- `Consider using $contains or $startsWith instead.`);
78
- conditions.push([field, 'contains', operatorValue]);
79
- continue;
113
+ `Use $contains, $startsWith or $endsWith.`);
80
114
  }
81
115
  // $null / $exists translate based on their boolean value (per spec semantics).
82
116
  // $null: true → IS NULL | $null: false → IS NOT NULL
@@ -95,7 +129,7 @@ export function convertFiltersToAST(filter) {
95
129
  }
96
130
  else {
97
131
  // Unknown operator - throw error to avoid silent failure
98
- throw new Error(`[ObjectUI] Unknown filter operator '${operator}' for field '${field}'. ` +
132
+ throw new FilterOperatorError(`[ObjectUI] Unknown filter operator '${operator}' for field '${field}'. ` +
99
133
  `Supported operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $between, ` +
100
134
  `$contains, $notContains, $startsWith, $endsWith, $null, $exists. ` +
101
135
  `If you need exact object matching, use the value directly without an operator.`);
@@ -118,3 +152,56 @@ export function convertFiltersToAST(filter) {
118
152
  // Multiple conditions: combine with 'and'
119
153
  return ['and', ...conditions];
120
154
  }
155
+ /**
156
+ * Normalize ONE filter source into a single filter node.
157
+ *
158
+ * A "source" is whatever a view hands a renderer, and there are three shapes in
159
+ * circulation, all legitimate:
160
+ *
161
+ * - `[{ field, operator, value }, ...]` a spec `ViewFilterRule[]`
162
+ * - `[['stage', '=', 'won'], ...]` an AST node / legacy flat array
163
+ * - `{ status: 'active' }` a MongoDB-style object
164
+ *
165
+ * The third is the one that kept getting lost. Renderers tested `source.length
166
+ * > 0` before using it, which is `undefined > 0` for an object — so a
167
+ * `table.defaultFilters` (declared `Record<string, any>`) was DROPPED and the
168
+ * view returned every record. Silently: no error, just a wider answer.
169
+ *
170
+ * Returns `undefined` for an absent or empty source, so callers can skip
171
+ * `$filter` rather than sending an empty array.
172
+ */
173
+ export function toFilterNode(source) {
174
+ if (source === null || source === undefined)
175
+ return undefined;
176
+ if (Array.isArray(source))
177
+ return source.length > 0 ? source : undefined;
178
+ if (typeof source !== 'object')
179
+ return undefined;
180
+ const obj = source;
181
+ if (Object.keys(obj).length === 0)
182
+ return undefined;
183
+ // MongoDB-style → AST, so it can sit beside the other shapes under one `and`.
184
+ return convertFiltersToAST(obj);
185
+ }
186
+ /**
187
+ * Combine filter sources under a single `and`, each as its OWN child.
188
+ *
189
+ * Wrapping rather than spreading, on purpose. `['and', ...rules]` looks
190
+ * equivalent and is not: spreading a `ViewFilterRule[]` puts bare rule OBJECTS
191
+ * where the AST expects nodes, and the server neither understands nor rejects
192
+ * that cleanly — `isFilterAST` says no (a 400 since objectstack#4121), while
193
+ * `parseFilterAST` reads the rule as a Mongo condition and filters on columns
194
+ * literally named `field` / `operator` / `value`. Spreading is only correct
195
+ * when the source happens to be an array of nodes, which is why it survived.
196
+ *
197
+ * Sources that normalize to nothing are skipped; one surviving source is
198
+ * returned as-is rather than wrapped in a pointless `and`.
199
+ */
200
+ export function mergeFilterNodes(...sources) {
201
+ const nodes = sources.map(toFilterNode).filter((n) => n !== undefined);
202
+ if (nodes.length === 0)
203
+ return undefined;
204
+ if (nodes.length === 1)
205
+ return nodes[0];
206
+ return ['and', ...nodes];
207
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ /**
9
+ * Session-scoped filter placeholders — the sibling vocabulary to
10
+ * `{date-macros}`.
11
+ *
12
+ * Filter values travel as JSON, so a user-scoped slice cannot call
13
+ * `currentUser().id` inline; it writes a placeholder that this module expands
14
+ * immediately before the filter reaches the data source:
15
+ *
16
+ * { owner_id: '{current_user_id}' }
17
+ *
18
+ * ## Why this module exists (framework #3574)
19
+ *
20
+ * There used to be no shared resolver. Three ad-hoc implementations had grown
21
+ * up independently — one in `ObjectView` for list views, one in
22
+ * `ObjectDataPage` for URL filter triples, one in `NavigationRenderer` for
23
+ * hrefs — and each handled only the shape its own surface happened to use.
24
+ * Dashboard widgets never got one at all, so `{current_user_id}` in a widget
25
+ * filter reached SQL as a literal, matched no row, and the widget rendered
26
+ * `0` with no error in the console or the server log.
27
+ *
28
+ * The failure mode is the point: a metric reading `0` is indistinguishable
29
+ * from a metric that is legitimately zero, so the bug survived review and
30
+ * shipped. Any *new* surface that resolves placeholders itself will
31
+ * eventually reproduce it, which is why resolution lives here, once, and
32
+ * every surface calls {@link resolveFilterPlaceholders}.
33
+ *
34
+ * ## Presentation scope, NOT a security boundary
35
+ *
36
+ * These tokens scope what a surface *shows*. They do not decide what a caller
37
+ * is *allowed* to read — that is RLS, enforced server-side against a
38
+ * different vocabulary rooted at `current_user` (`owner_id = current_user.id`).
39
+ * Dropping a `{current_user_id}` filter widens a view; it must never widen
40
+ * access. Never use a context token as an access control.
41
+ *
42
+ * ## Contract source
43
+ *
44
+ * The canonical vocabulary is published as part of the platform contract at
45
+ * `@objectstack/spec` → `CONTEXT_TOKENS` / `classifyFilterToken`. It is
46
+ * mirrored here — exactly as `date-macros.ts` mirrors `DATE_MACRO_TOKENS` —
47
+ * because the installed `@objectstack/spec` predates that export. Keep the two
48
+ * in sync; the duplication is temporary until the next coordinated release.
49
+ */
50
+ /** The complete set of session-scoped filter tokens. */
51
+ export declare const CONTEXT_TOKENS: readonly ["current_user_id", "current_org_id"];
52
+ export type ContextTokenName = (typeof CONTEXT_TOKENS)[number];
53
+ /** Session values a filter placeholder can resolve against. */
54
+ export interface FilterTokenScope {
55
+ /** The signed-in user's id. */
56
+ currentUserId?: string | null;
57
+ /** The active organization id. */
58
+ currentOrgId?: string | null;
59
+ /**
60
+ * Called when a placeholder cannot be resolved — either a recognised token
61
+ * with no value in scope (signed out), or a near-miss spelling that resolves
62
+ * in no vocabulary. Defaults to a `console.warn`; pass `null` to silence.
63
+ */
64
+ onUnresolved?: ((message: string) => void) | null;
65
+ }
66
+ /**
67
+ * Expand `{current_user_id}` / `{current_org_id}` inside a filter.
68
+ *
69
+ * Walks arrays and plain objects recursively, which is what makes one
70
+ * resolver cover both platform filter shapes: the MongoDB-style object a
71
+ * dashboard widget carries (`{ owner_id: '{current_user_id}' }`) and the
72
+ * condition/triple arrays a list view carries (`[{ field, operator, value }]`
73
+ * / `[['owner','=','…']]`). The predecessor helper in `ObjectView` bailed on
74
+ * non-arrays (`if (!Array.isArray(filter)) return filter`), which is why
75
+ * lifting it into the dashboard would have been a silent no-op.
76
+ *
77
+ * Only whole-string placeholders are substituted — an id is an opaque value,
78
+ * so embedding it in a larger string (`'user-{current_user_id}'`) is never
79
+ * what an author means, and substituting there would silently produce a value
80
+ * that matches nothing. Unknown tokens are passed through untouched so that
81
+ * date macros and nav-only `AppContextSelector` ids survive this pass.
82
+ *
83
+ * An unresolvable *known* token is deliberately left as-is rather than
84
+ * dropped: leaving it yields an empty result, whereas dropping the clause
85
+ * would widen the result set — and a filter that silently widens is far worse
86
+ * than one that silently narrows.
87
+ */
88
+ export declare function resolveContextTokens<T = any>(filter: T, scope?: FilterTokenScope): T;
89
+ /**
90
+ * Resolve **every** placeholder vocabulary a filter value understands — date
91
+ * macros and context tokens — in one call.
92
+ *
93
+ * This is the function surfaces should call. Calling only one of the two
94
+ * resolvers is the defect behind framework #3574: dashboard widgets called
95
+ * `resolveDateMacros` alone, so `{today}` worked and `{current_user_id}`
96
+ * silently did not.
97
+ *
98
+ * Order is irrelevant (the vocabularies are disjoint) but fixed here so
99
+ * behaviour is identical everywhere.
100
+ */
101
+ export declare function resolveFilterPlaceholders<T = any>(filter: T, scope?: FilterTokenScope, now?: Date): T;