diff --git a/examples/app-showcase/src/ui/reports/index.ts b/examples/app-showcase/src/ui/reports/index.ts index 28b7ce4486c..2222c4c45cd 100644 --- a/examples/app-showcase/src/ui/reports/index.ts +++ b/examples/app-showcase/src/ui/reports/index.ts @@ -2,8 +2,6 @@ import { defineReport } from '@objectstack/spec/ui'; -const task = 'showcase_task'; - // ADR-0021 Phase 2: the former `TaskListReport` (showcase_task_list) — a flat // record list — was converted to the `tabular` ListView on showcase_task // (src/ui/views/task.view.ts). A flat list is an object-bound row lens (ADR-0017), diff --git a/scripts/analytics-reconcile/app-crm.ts b/scripts/analytics-reconcile/app-crm.ts deleted file mode 100644 index c668f7df090..00000000000 --- a/scripts/analytics-reconcile/app-crm.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// ADR-0021 Phase 2 — reconciliation runner for examples/app-crm. -// pnpm tsx scripts/analytics-reconcile/app-crm.ts - -import CrmApp from '../../examples/app-crm/objectstack.config.js'; -import { PipelineDashboard } from '../../examples/app-crm/src/dashboards/pipeline.dashboard.js'; -import { OpportunityDataset } from '../../examples/app-crm/src/datasets/opportunity.dataset.js'; -import { SalesByStageReport } from '../../examples/app-crm/src/reports/sales-by-stage.report.js'; -import { reconcileApp, runAsMain } from './boot.js'; - -runAsMain(() => reconcileApp({ - appName: 'app-crm', - config: CrmApp, - dashboards: [PipelineDashboard], - reports: [SalesByStageReport], - datasets: [OpportunityDataset], -})); diff --git a/scripts/analytics-reconcile/app-showcase.ts b/scripts/analytics-reconcile/app-showcase.ts deleted file mode 100644 index 65e1b881b20..00000000000 --- a/scripts/analytics-reconcile/app-showcase.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// ADR-0021 Phase 2 — reconciliation runner for examples/app-showcase. -// pnpm tsx scripts/analytics-reconcile/app-showcase.ts - -import ShowcaseApp from '../../examples/app-showcase/objectstack.config.js'; -import { ChartGalleryDashboard } from '../../examples/app-showcase/src/dashboards/chart-gallery.dashboard.js'; -import { ShowcaseTaskDataset, ShowcaseProjectDataset } from '../../examples/app-showcase/src/datasets/chart-gallery.dataset.js'; -import { allReports } from '../../examples/app-showcase/src/reports/index.js'; -import { reconcileApp, runAsMain } from './boot.js'; - -runAsMain(() => reconcileApp({ - appName: 'app-showcase', - config: ShowcaseApp, - dashboards: [ChartGalleryDashboard], - reports: allReports, - datasets: [ShowcaseTaskDataset, ShowcaseProjectDataset], -})); diff --git a/scripts/analytics-reconcile/app-todo.ts b/scripts/analytics-reconcile/app-todo.ts deleted file mode 100644 index b9573814789..00000000000 --- a/scripts/analytics-reconcile/app-todo.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// ADR-0021 Phase 2 — reconciliation runner for examples/app-todo. -// pnpm tsx scripts/analytics-reconcile/app-todo.ts - -import TodoApp from '../../examples/app-todo/objectstack.config.js'; -import { TaskDashboard } from '../../examples/app-todo/src/dashboards/task.dashboard.js'; -import { TaskDataset } from '../../examples/app-todo/src/datasets/task.dataset.js'; -import * as reports from '../../examples/app-todo/src/reports/index.js'; -import type { Report } from '@objectstack/spec/ui'; -import { reconcileApp, runAsMain } from './boot.js'; - -runAsMain(() => reconcileApp({ - appName: 'app-todo', - config: TodoApp, - dashboards: [TaskDashboard], - reports: Object.values(reports) as Report[], - datasets: [TaskDataset], -})); diff --git a/scripts/analytics-reconcile/boot.ts b/scripts/analytics-reconcile/boot.ts deleted file mode 100644 index 05c36f806e6..00000000000 --- a/scripts/analytics-reconcile/boot.ts +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// ADR-0021 Phase 2 — shared kernel-boot + reconciliation driver. -// -// Boots an example stack with a real in-memory engine + the analytics service -// (+ an explicit, open `security` service: see `openSecurity`), then reconciles -// every dual-form dashboard widget (legacy `aggregate()` vs dataset -// `queryDataset()`). Read-only: never writes metadata or data. - -import { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime'; -import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; -import { ObjectQLPlugin } from '@objectstack/objectql'; -import { AnalyticsServicePlugin } from '@objectstack/service-analytics'; -import { DatasetSchema } from '@objectstack/spec/ui'; -import type { Dataset, Dashboard, Report } from '@objectstack/spec/ui'; -import type { IAnalyticsService, DatasetSelection, ISecurityService } from '@objectstack/spec/contracts'; -import type { FilterCondition } from '@objectstack/spec/data'; -import { reconcileDashboard, reconcileReports, type ReconcileExecutors, type WidgetReconcileResult } from './reconcile.js'; -import { resolveDateMacros } from './macros.js'; - -/** - * The `security` service this reconciliation runs under: registered - * EXPLICITLY, and OPEN on purpose. - * - * [#22235] The analytics read bridges REFUSE, fail-closed, on a kernel that - * registers no security service: the kernel's lookup throws on the miss, the - * bridge reads that as a security service it cannot use, and every dataset - * query is refused `SERVICE_UNAVAILABLE` / 503 (#25561; it was - * `PERMISSION_DENIED` / 403 before) — which this runner would report as a - * mismatch on every widget. That is the declared behaviour, so a composition - * that wants analytics to answer registers a security service. - * - * This runner compares NUMBERS, not access. Its legacy path - * (`engine.aggregate()`) runs with no caller context on an engine that carries - * no security middleware, so the dataset path is given that same posture, by - * name: every object readable, no row restriction, no field answer. A real - * security plugin would put an access policy on the comparison, which is not - * what a reconciliation measures. - */ -const openSecurity = { - /** Object-level: every object is readable here. */ - canReadObject: async (_object: string): Promise => true, - /** Row-level: `undefined` is "no row restriction on this object". */ - getReadFilter: async (_object: string): Promise => undefined, - /** Field-level: `undefined` is "no answer", which judges no field. */ - getReadableFields: async (_object: string): Promise => undefined, -} satisfies Partial; - -interface DataEngineLike { - aggregate(object: string, options: { - where?: Record; - // Plain fields or structured date-bucket items ({ field, dateGranularity }). - groupBy?: Array; - aggregations?: Array<{ function: string; field: string; alias: string }>; - }): Promise[]>; -} - -export interface ReconcileAppOptions { - appName: string; - /** The defineStack() result for the example app. */ - config: unknown; - /** Dashboards to reconcile (each dual-form widget is checked). */ - dashboards: Dashboard[]; - /** Reports to reconcile (each dual-form report is checked). */ - reports?: Report[]; - /** Authored datasets (Dataset) the dashboards/reports reference by name. */ - datasets: Dataset[]; -} - -/** Boot, reconcile every dashboard, print a report, and return the mismatch count. */ -export async function reconcileApp(opts: ReconcileAppOptions): Promise { - process.env.OS_MULTI_ORG_ENABLED = 'false'; - - const kernel = new ObjectKernel(); - await kernel.use(new ObjectQLPlugin()); - await kernel.use(new DriverPlugin(new SqliteWasmDriver({ filename: ':memory:' }))); - await kernel.use(new AppPlugin(opts.config as ConstructorParameters[0])); - // The open `security` service above, mounted explicitly — without it every - // dataset query is refused (see `openSecurity`). - await kernel.use({ - name: 'analytics-reconcile.security-open', - init: async (ctx: { registerService(name: string, service: unknown): void }) => { - ctx.registerService('security', openSecurity); - }, - }); - // Force the ObjectQL aggregate path (no raw SQL) so legacy and dataset paths - // run through the identical engine.aggregate() — the cleanest apples-to-apples. - await kernel.use(new AnalyticsServicePlugin({ - queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }), - })); - await kernel.bootstrap(); - - const engine = - (kernel.getService('data') as DataEngineLike | undefined) ?? - (kernel.getService('objectql') as DataEngineLike | undefined); - if (!engine || typeof engine.aggregate !== 'function') { - throw new Error('No IDataEngine with aggregate() found (expected "data"/"objectql" service).'); - } - const analytics = kernel.getService('analytics') as IAnalyticsService | undefined; - if (!analytics || typeof analytics.queryDataset !== 'function') { - throw new Error('No analytics service with queryDataset() found.'); - } - - const datasets = new Map(); - for (const ds of opts.datasets) { - const parsed = DatasetSchema.parse(ds) as Dataset; - datasets.set(parsed.name, parsed); - } - - const exec: ReconcileExecutors = { - runAggregate: (spec) => engine.aggregate(spec.objectName, { - where: spec.filter as Record | undefined, - groupBy: spec.groupBy.length > 0 ? spec.groupBy : undefined, - aggregations: spec.aggregations.map((a) => ({ function: a.method, field: a.field, alias: a.alias })), - }), - runDataset: async (dataset: Dataset, selection: DatasetSelection) => { - const result = await analytics.queryDataset!(dataset, selection); - return result.rows as Record[]; - }, - resolveFilter: (filter?: FilterCondition) => (filter == null ? filter : resolveDateMacros(filter)), - }; - - let totalMismatch = 0; - for (const dashboard of opts.dashboards) { - const results = await reconcileDashboard(dashboard, datasets, exec); - totalMismatch += report(`${opts.appName} · ${dashboard.name}`, results); - } - if (opts.reports && opts.reports.length > 0) { - const results = await reconcileReports(opts.reports, datasets, exec); - totalMismatch += report(`${opts.appName} · reports`, results); - } - return totalMismatch; -} - -function report(surface: string, results: WidgetReconcileResult[]): number { - let mismatches = 0; - const icons: Record = { - ok: '✅', mismatch: '❌', skipped: '⏭️ ', pending: '🕗', - }; - console.log(`\n── Analytics reconciliation · ${surface} ──`); - for (const r of results) { - console.log(`${icons[r.status]} ${r.widgetId} [${r.status}]`); - if (r.status === 'mismatch') { - mismatches++; - for (const issue of r.issues) console.log(` · ${issue}`); - } else if ((r.status === 'skipped' || r.status === 'pending') && r.issues.length) { - console.log(` · ${r.issues[0]}`); - } - } - const count = (s: WidgetReconcileResult['status']) => results.filter((r) => r.status === s).length; - console.log( - `\n${mismatches === 0 ? '🎉' : '🔴'} ${count('ok')} ok · ${count('skipped')} skipped · ` + - `${count('pending')} pending · ${mismatches} mismatch`, - ); - return mismatches; -} - -/** Run a reconcileApp() and exit the process with a CI-friendly code. */ -export function runAsMain(run: () => Promise): void { - run() - .then((mismatches) => process.exit(mismatches === 0 ? 0 : 1)) - .catch((err) => { - console.error('❌ Reconciliation runner failed:', err); - process.exit(2); - }); -} diff --git a/scripts/analytics-reconcile/macros.ts b/scripts/analytics-reconcile/macros.ts deleted file mode 100644 index 45aa4bc0f15..00000000000 --- a/scripts/analytics-reconcile/macros.ts +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// ADR-0021 Phase 2 — date-macro resolver for the reconciliation harness. -// -// In production `{today}` / `{current_quarter_start}` / `{30_days_ago}` resolve -// to concrete dates BEFORE the query runs — in the renderer (@object-ui/core -// `resolveDateMacros()`) or, since framework#3582, server-side in -// `resolveFilterTokens()` (@objectstack/core). The harness pre-resolves them -// itself for a different reason: it must hand BOTH compared paths the byte-identical -// concrete filter, so any difference in the result is a semantic disagreement -// between the paths rather than a difference in when each resolved the clock. -// -// This is also why it does NOT call `resolveFilterTokens()`: that emits ISO -// strings (the driver then coerces per column), while the harness compares raw -// stored values and wants epoch-millis directly. The resolved VALUE is arbitrary -// here — only its identity across the two paths matters. -// -// Token grammar mirrors packages/spec/src/data/date-macros.zod.ts. - -import { DATE_MACRO_WRAPPED_RE, parseDateMacroParam } from '@objectstack/spec/data'; - -function startOfDay(d: Date): Date { - return new Date(d.getFullYear(), d.getMonth(), d.getDate()); -} -/** Monday-based week start (matches the spec's "Monday 00:00 of this week"). */ -function startOfWeek(d: Date): Date { - const s = startOfDay(d); - const dow = (s.getDay() + 6) % 7; // 0 = Monday - s.setDate(s.getDate() - dow); - return s; -} -function startOfMonth(d: Date): Date { return new Date(d.getFullYear(), d.getMonth(), 1); } -function startOfQuarter(d: Date): Date { return new Date(d.getFullYear(), Math.floor(d.getMonth() / 3) * 3, 1); } -function startOfYear(d: Date): Date { return new Date(d.getFullYear(), 0, 1); } - -// ObjectStack `date` fields are stored as epoch-millis (the seed loader writes -// `cel`daysFromNow(n)`` as a timestamp number), so resolve macros to epoch-millis -// — a number compares correctly against the stored column, where an ISO string -// would not. The exact value is arbitrary as long as BOTH paths get the same one. -const iso = (d: Date): number => d.getTime(); - -type PeriodKind = 'week' | 'month' | 'quarter' | 'year'; -const startOf: Record Date> = { - week: startOfWeek, month: startOfMonth, quarter: startOfQuarter, year: startOfYear, -}; -function addPeriod(kind: PeriodKind, d: Date, n: number): Date { - const r = new Date(d); - if (kind === 'week') r.setDate(r.getDate() + n * 7); - else if (kind === 'month') r.setMonth(r.getMonth() + n); - else if (kind === 'quarter') r.setMonth(r.getMonth() + n * 3); - else r.setFullYear(r.getFullYear() + n); - return r; -} - -/** Resolve a single token name (inside the braces) to an epoch-millis number, or null. */ -function resolveToken(name: string, now: Date): number | null { - switch (name) { - case 'today': return iso(startOfDay(now)); - case 'yesterday': { const d = startOfDay(now); d.setDate(d.getDate() - 1); return iso(d); } - case 'tomorrow': { const d = startOfDay(now); d.setDate(d.getDate() + 1); return iso(d); } - case 'now': return now.getTime(); - } - - // current/last/next × week/month/quarter/year × start/end (+ bare aliases). - const m = name.match(/^(current|last|next)?_?(week|month|quarter|year)_(start|end)$/); - if (m) { - const rel = (m[1] ?? 'current') as 'current' | 'last' | 'next'; - const kind = m[2] as PeriodKind; - const bound = m[3] as 'start' | 'end'; - const offset = rel === 'last' ? -1 : rel === 'next' ? 1 : 0; - const periodStart = startOf[kind](addPeriod(kind, now, offset)); - if (bound === 'start') return iso(periodStart); - // end = day before the next period's start. - const nextStart = addPeriod(kind, periodStart, 1); - nextStart.setDate(nextStart.getDate() - 1); - return iso(nextStart); - } - - // Parameterised: N__(ago|from_now). - const p = parseDateMacroParam(name); - if (p) { - const d = new Date(now); - const sign = p.direction === 'ago' ? -1 : 1; - switch (p.unit) { - case 'minute': d.setMinutes(d.getMinutes() + sign * p.n); break; - case 'hour': d.setHours(d.getHours() + sign * p.n); break; - case 'day': d.setDate(d.getDate() + sign * p.n); break; - case 'week': d.setDate(d.getDate() + sign * p.n * 7); break; - case 'month': d.setMonth(d.getMonth() + sign * p.n); break; - case 'year': d.setFullYear(d.getFullYear() + sign * p.n); break; - } - return p.unit === 'minute' || p.unit === 'hour' ? d.getTime() : iso(startOfDay(d)); - } - return null; -} - -/** Resolve a placeholder string like `'{today}'` / `'${30_days_ago}'`, else return it unchanged. */ -function resolveValue(value: unknown, now: Date): unknown { - if (typeof value !== 'string') return value; - const m = value.match(DATE_MACRO_WRAPPED_RE); - if (!m) return value; - return resolveToken(m[1], now) ?? value; -} - -/** - * Deep-clone a FilterCondition, replacing every `{date-macro}` placeholder with - * a concrete ISO date. `now` is fixed once per call so all tokens in one filter - * resolve against the same instant. - */ -export function resolveDateMacros(filter: T, now: Date = new Date()): T { - const walk = (node: unknown): unknown => { - if (Array.isArray(node)) return node.map(walk); - if (node && typeof node === 'object') { - const out: Record = {}; - for (const [k, v] of Object.entries(node as Record)) out[k] = walk(v); - return out; - } - return resolveValue(node, now); - }; - return walk(filter) as T; -} diff --git a/scripts/analytics-reconcile/reconcile.ts b/scripts/analytics-reconcile/reconcile.ts deleted file mode 100644 index d6bd69fd7d0..00000000000 --- a/scripts/analytics-reconcile/reconcile.ts +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// ADR-0021 Phase 2 — read-only analytics reconciliation (关键兜底 / hard gate). -// -// For every dual-form presentation (a report / dashboard widget that carries -// BOTH the legacy inline query AND the new `dataset` binding), run BOTH paths -// against the SAME engine and assert they return identical numbers. This is the -// safety net that catches an AI migration silently dropping a filter, flipping -// an aggregate口径 (count vs count_distinct), or pointing at the wrong field / -// relationship. It ONLY verifies — it never rewrites — and is the gate that -// must be green before the inline form is deleted (single-form convergence). -// -// Engine-agnostic on purpose: this module imports TYPES only. The caller injects -// the two executors (legacy `aggregate()` + dataset `queryDataset()`) bound to a -// real booted kernel — see app-todo.ts for the wiring. - -import type { Dashboard, DashboardWidget, Dataset, Report } from '@objectstack/spec/ui'; -import type { FilterCondition } from '@objectstack/spec/data'; -import type { DatasetSelection } from '@objectstack/spec/contracts'; - -/** A groupBy item — a plain field, or a date field bucketed by a granularity. */ -export type GroupByItem = string | { field: string; dateGranularity: string }; - -/** The legacy inline-query path, lowered to an ObjectQL `aggregate()` call. */ -export interface OldAggregateSpec { - objectName: string; - filter?: FilterCondition; - groupBy: GroupByItem[]; - aggregations: Array<{ field: string; method: string; alias: string }>; -} - -/** The field name a groupBy item groups on (the key the engine returns rows under). */ -function groupByField(g: GroupByItem): string { - return typeof g === 'string' ? g : g.field; -} - -/** The executors the caller binds to a booted kernel. */ -export interface ReconcileExecutors { - /** Legacy path — `engine.aggregate(object, { where, groupBy, aggregations })`. */ - runAggregate(spec: OldAggregateSpec): Promise[]>; - /** New path — `analytics.queryDataset(dataset, selection)`. */ - runDataset(dataset: Dataset, selection: DatasetSelection): Promise[]>; - /** - * Resolve `{date-macro}` placeholders in a filter to concrete values BEFORE - * both paths run — mirroring the renderer. Applied identically to both forms, - * so the resolved value is arbitrary; what matters is the two paths see the - * SAME concrete filter (no normalizer-drop artifact on unparseable strings). - */ - resolveFilter?: (filter: FilterCondition | undefined) => FilterCondition | undefined; -} - -export interface WidgetReconcileResult { - widgetId: string; - /** - * - `ok` — both forms returned identical numbers. - * - `mismatch` — numbers diverged (or a path threw). FAILS the gate. - * - `skipped` — dual-form but not numerically reconcilable here (e.g. a - * multi-dimension widget vs a single-categoryField legacy form). - * - `pending` — still inline-only; not yet dataset-bound (coverage gap, not a failure). - */ - status: 'ok' | 'mismatch' | 'skipped' | 'pending'; - issues: string[]; - /** Canonical {dimsKey → measureValues[]} maps for both paths (for diagnostics). */ - oldRows?: Record; - newRows?: Record; -} - -const NO_DIMS = '∅'; -const DIM_SEP = '∥'; -/** Relative tolerance for float measure comparison (counts are exact). */ -const EPSILON = 1e-9; - -/** - * A widget is reconcilable only when it carries BOTH forms: the legacy inline - * `object` query AND the new `dataset` binding with at least one measure name. - */ -export function isReconcilableWidget( - w: DashboardWidget, -): w is DashboardWidget & { object: string; dataset: string; values: string[] } { - return ( - typeof w.object === 'string' && - typeof w.dataset === 'string' && - Array.isArray(w.values) && - w.values.length > 0 - ); -} - -/** - * Lower a widget's LEGACY inline fields to an aggregate spec — derived purely - * from `object` / `categoryField` / `valueField` / `aggregate` / `measures` / - * `filter`, NOT from the dataset. That independence is the whole point: if the - * dataset was authored to mean something different, the numbers diverge here. - */ -export function deriveOldAggregate(w: DashboardWidget): OldAggregateSpec { - const groupBy: GroupByItem[] = w.categoryField - ? [w.categoryGranularity - ? { field: w.categoryField, dateGranularity: w.categoryGranularity } - : w.categoryField] - : []; - const aggregations: OldAggregateSpec['aggregations'] = []; - if (w.measures && w.measures.length > 0) { - w.measures.forEach((m, i) => { - aggregations.push({ method: m.aggregate ?? 'count', field: m.valueField ?? '*', alias: `m${i}` }); - }); - } else { - aggregations.push({ method: w.aggregate ?? 'count', field: w.valueField ?? '*', alias: 'm0' }); - } - return { objectName: w.object as string, filter: w.filter, groupBy, aggregations }; -} - -/** Build the dataset selection from the widget's `dimensions` / `values` / `filter`. */ -export function deriveSelection(w: DashboardWidget): DatasetSelection { - const dimensions = w.dimensions ?? []; - const selection: DatasetSelection = { - dimensions, - measures: w.values as string[], - runtimeFilter: w.filter, - }; - // Mirror the legacy `categoryGranularity` as a timeDimension so the dataset - // path buckets the date dimension identically (ObjectQLStrategy honours it). - if (w.categoryGranularity && dimensions.length === 1) { - selection.timeDimensions = [{ dimension: dimensions[0], granularity: w.categoryGranularity }]; - } - return selection; -} - -function toNum(v: unknown): number | null { - if (v == null) return null; - const n = typeof v === 'number' ? v : Number(v); - return Number.isFinite(n) ? n : null; -} - -/** Stable key for a row's dimension tuple, ordered by `dimKeys`. */ -function dimsKeyOf(row: Record, dimKeys: string[]): string { - if (dimKeys.length === 0) return NO_DIMS; - return dimKeys.map((k) => String(row[k] ?? '∄')).join(DIM_SEP); -} - -/** Canonicalize rows into {dimsKey → [measure values in `measureKeys` order]}. */ -function normalize( - rows: Record[], - dimKeys: string[], - measureKeys: string[], -): Record { - const out: Record = {}; - for (const row of rows) { - out[dimsKeyOf(row, dimKeys)] = measureKeys.map((m) => toNum(row[m])); - } - return out; -} - -function numbersEqual(a: number | null, b: number | null): boolean { - if (a === null || b === null) return a === b; - if (a === b) return true; - const scale = Math.max(Math.abs(a), Math.abs(b), 1); - return Math.abs(a - b) <= EPSILON * scale; -} - -/** Diff two canonical maps; returns human-readable issue strings (empty = match). */ -function diff( - oldMap: Record, - newMap: Record, -): string[] { - const issues: string[] = []; - const keys = new Set([...Object.keys(oldMap), ...Object.keys(newMap)]); - for (const key of keys) { - const o = oldMap[key]; - const n = newMap[key]; - const label = key === NO_DIMS ? '(scalar)' : key; - if (!o) { issues.push(`group "${label}": present in dataset path but missing from legacy path (new=${JSON.stringify(n)})`); continue; } - if (!n) { issues.push(`group "${label}": present in legacy path but missing from dataset path (old=${JSON.stringify(o)})`); continue; } - if (o.length !== n.length) { issues.push(`group "${label}": measure count differs (old=${o.length} new=${n.length})`); continue; } - for (let i = 0; i < o.length; i++) { - if (!numbersEqual(o[i], n[i])) issues.push(`group "${label}" measure[${i}]: legacy=${o[i]} dataset=${n[i]}`); - } - } - return issues; -} - -/** Reconcile a single dual-form widget against its dataset. */ -export async function reconcileWidget( - w: DashboardWidget, - dataset: Dataset | undefined, - exec: ReconcileExecutors, -): Promise { - if (!isReconcilableWidget(w)) { - return { widgetId: w.id, status: 'skipped', issues: ['not dual-form (missing object or dataset/values)'] }; - } - if (!dataset) { - return { widgetId: w.id, status: 'mismatch', issues: [`dataset "${w.dataset}" not found in registry`] }; - } - const dims = w.dimensions ?? []; - if (dims.length > 1 && w.categoryField) { - return { widgetId: w.id, status: 'skipped', issues: ['multi-dimension widget cannot reconcile against single categoryField legacy form'] }; - } - - // Resolve date macros once, then feed the identical filter to both paths. - const wResolved = exec.resolveFilter - ? ({ ...w, filter: exec.resolveFilter(w.filter) } as DashboardWidget) - : w; - const oldSpec = deriveOldAggregate(wResolved); - const selection = deriveSelection(wResolved); - - let oldRaw: Record[]; - let newRaw: Record[]; - try { - oldRaw = await exec.runAggregate(oldSpec); - } catch (e) { - return { widgetId: w.id, status: 'mismatch', issues: [`legacy aggregate threw: ${(e as Error).message}`] }; - } - try { - newRaw = await exec.runDataset(dataset, selection); - } catch (e) { - return { widgetId: w.id, status: 'mismatch', issues: [`dataset query threw: ${(e as Error).message}`] }; - } - - // Legacy rows key dimensions by the raw field name (categoryField); dataset - // rows key them by the dimension NAME. They share the same value domain, so - // canonicalize each by its own key set, then compare positionally. - const oldMap = normalize(oldRaw, oldSpec.groupBy.map(groupByField), oldSpec.aggregations.map((a) => a.alias)); - const newMap = normalize(newRaw, dims, w.values as string[]); - - const issues = diff(oldMap, newMap); - return { - widgetId: w.id, - status: issues.length === 0 ? 'ok' : 'mismatch', - issues, - oldRows: oldMap, - newRows: newMap, - }; -} - -// ───────────────────────── Reports ───────────────────────── -// -// Reports have NO server-side executor in this repo (the pivot is computed -// client-side). We reconcile the NUMBERS only: lower the legacy report's -// groupings + aggregate columns to the same `aggregate()` call, and compare to -// the dataset's `rows`/`values`. A matrix (`groupingsAcross`) flattens to a 2D -// groupBy — the cell values are identical to the rendered pivot. A detail/summary -// report with no aggregate columns reconciles its group COUNT (count(*)), which -// is what the legacy report's group headers show. - -/** A report is reconcilable when it carries BOTH the inline query and the dataset binding. */ -export function isReconcilableReport( - r: Report, -): r is Report & { objectName: string; dataset: string; values: string[] } { - return ( - typeof r.objectName === 'string' && - typeof r.dataset === 'string' && - Array.isArray(r.values) && - r.values.length > 0 - ); -} - -/** Lower a report's LEGACY inline fields (groupings + aggregate columns) to an aggregate spec. */ -export function deriveReportAggregate(r: Report): OldAggregateSpec { - const groupBy = [ - ...(r.groupingsDown ?? []).map((g) => g.field), - ...(r.groupingsAcross ?? []).map((g) => g.field), - ]; - const aggCols = (r.columns ?? []).filter((c) => c.aggregate); - const aggregations: OldAggregateSpec['aggregations'] = aggCols.length > 0 - ? aggCols.map((c, i) => ({ method: c.aggregate as string, field: c.field, alias: `m${i}` })) - : [{ method: 'count', field: '*', alias: 'm0' }]; // detail/summary → group count - return { objectName: r.objectName as string, filter: r.filter, groupBy, aggregations }; -} - -/** Reconcile a single dual-form report against its dataset. */ -export async function reconcileReport( - r: Report, - dataset: Dataset | undefined, - exec: ReconcileExecutors, -): Promise { - if (!isReconcilableReport(r)) { - return { widgetId: r.name, status: 'skipped', issues: ['not dual-form (missing objectName or dataset/values)'] }; - } - if (!dataset) { - return { widgetId: r.name, status: 'mismatch', issues: [`dataset "${r.dataset}" not found in registry`] }; - } - const rows = r.rows ?? []; - - // Resolve macros on the legacy filter and the dataset runtimeFilter identically. - const legacyFilter = exec.resolveFilter ? exec.resolveFilter(r.filter) : r.filter; - const runtimeFilter = exec.resolveFilter ? exec.resolveFilter(r.runtimeFilter ?? r.filter) : (r.runtimeFilter ?? r.filter); - - const oldSpec = { ...deriveReportAggregate(r), filter: legacyFilter }; - const selection: DatasetSelection = { dimensions: rows, measures: r.values as string[], runtimeFilter }; - - let oldRaw: Record[]; - let newRaw: Record[]; - try { - oldRaw = await exec.runAggregate(oldSpec); - } catch (e) { - return { widgetId: r.name, status: 'mismatch', issues: [`legacy aggregate threw: ${(e as Error).message}`] }; - } - try { - newRaw = await exec.runDataset(dataset, selection); - } catch (e) { - return { widgetId: r.name, status: 'mismatch', issues: [`dataset query threw: ${(e as Error).message}`] }; - } - - const oldMap = normalize(oldRaw, oldSpec.groupBy.map(groupByField), oldSpec.aggregations.map((a) => a.alias)); - const newMap = normalize(newRaw, rows, r.values as string[]); - const issues = diff(oldMap, newMap); - return { widgetId: r.name, status: issues.length === 0 ? 'ok' : 'mismatch', issues, oldRows: oldMap, newRows: newMap }; -} - -/** Reconcile every dual-form report. */ -export async function reconcileReports( - reports: Report[], - datasets: Map, - exec: ReconcileExecutors, -): Promise { - const results: WidgetReconcileResult[] = []; - for (const r of reports) { - // Joined reports have no single data binding — reconcile each block. - if (r.type === 'joined' && Array.isArray(r.blocks)) { - for (const block of r.blocks) { - const id = `${r.name}/${block.name}`; - if (typeof block.dataset !== 'string') { - results.push({ widgetId: id, status: 'pending', issues: ['joined block inline-only (record-list / embed)'] }); - continue; - } - // A block is shaped like a mini-report (objectName/columns/groupings/ - // filter + dataset/rows/values/runtimeFilter) — reconcile it as one. - const asReport = { ...block, name: id } as unknown as Report; - results.push(await reconcileReport(asReport, datasets.get(block.dataset), exec)); - } - continue; - } - if (typeof r.dataset !== 'string') { - results.push({ widgetId: r.name, status: 'pending', issues: ['inline-only — not yet dataset-bound'] }); - continue; - } - results.push(await reconcileReport(r, datasets.get(r.dataset), exec)); - } - return results; -} - -/** Reconcile every dual-form widget on a dashboard. */ -export async function reconcileDashboard( - dashboard: Dashboard, - datasets: Map, - exec: ReconcileExecutors, -): Promise { - const results: WidgetReconcileResult[] = []; - for (const w of dashboard.widgets) { - if (typeof w.dataset !== 'string') { - // Inline-only widget — surfaced as `pending` so migration coverage stays honest. - results.push({ widgetId: w.id, status: 'pending', issues: ['inline-only — not yet dataset-bound'] }); - continue; - } - results.push(await reconcileWidget(w, datasets.get(w.dataset), exec)); - } - return results; -} diff --git a/scripts/check-whole-set-label-write.mjs b/scripts/check-whole-set-label-write.mjs index bea00fe5fd4..ae80d7a6879 100644 --- a/scripts/check-whole-set-label-write.mjs +++ b/scripts/check-whole-set-label-write.mjs @@ -190,7 +190,7 @@ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'coverage']) * `check-watch-hint-literal.mjs` holds that rule fleet-wide; the self-test * below holds the own-source half. */ -const ROOT_DIR_WATCH_HINTS = ['scripts/**/*.mjs', 'scripts/**/*.ts', 'scripts/**/*.sh']; +const ROOT_DIR_WATCH_HINTS = ['scripts/**/*.mjs', 'scripts/**/*.sh']; /** * How far apart the method slot and the `/labels` path may sit and still be diff --git a/tsconfig.json b/tsconfig.json index e1595808911..e76492e7e31 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,10 @@ { "extends": "./tsconfig.base.json", "compilerOptions": { + // The scripts run on the Node that the root `engines` field pins (>=22), + // which ships all of ES2022 (`Object.hasOwn` among it). The shared base + // stays at ES2020. + "lib": ["ES2022"], "types": ["node"] }, "exclude": [