-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathvalidate.ts
More file actions
360 lines (329 loc) · 14.4 KB
/
Copy pathvalidate.ts
File metadata and controls
360 lines (329 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import { existsSync, readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { join } from 'node:path';
import chalk from 'chalk';
import { ZodError } from 'zod';
import { ObjectStackDefinitionSchema, normalizeStackInput } from '@objectstack/spec';
import { loadConfig } from '../utils/config.js';
import { validateStackExpressions } from '@objectstack/lint';
import { validateWidgetBindings } from '@objectstack/lint';
import { validateResponsiveStyles } from '@objectstack/lint';
import { validateJsxPages, validateReactPages, validateReactPageProps } from '@objectstack/lint';
import {
printHeader,
printKV,
printSuccess,
printError,
printStep,
createTimer,
formatZodErrors,
collectMetadataStats,
printMetadataStats,
} from '../utils/format.js';
export default class Validate extends Command {
static override description =
'Validate ObjectStack configuration against the protocol schema, CEL expressions, and widget bindings (no artifact emitted)';
static override args = {
config: Args.string({ description: 'Configuration file path', required: false }),
};
static override flags = {
strict: Flags.boolean({ description: 'Treat warnings as errors' }),
json: Flags.boolean({ description: 'Output results as JSON' }),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Validate);
const timer = createTimer();
if (!flags.json) {
printHeader('Validate');
}
try {
// 1. Load configuration
if (!flags.json) printStep('Loading configuration...');
const { config, absolutePath, duration } = await loadConfig(args.config);
if (!flags.json) {
printKV('Config', absolutePath);
printKV('Load time', `${duration}ms`);
}
// 2. Normalize map-formatted stack definition and validate against schema
if (!flags.json) printStep('Validating against ObjectStack Protocol...');
const normalized = normalizeStackInput(config as Record<string, unknown>);
const result = ObjectStackDefinitionSchema.safeParse(normalized);
if (!result.success) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: (result.error as unknown as ZodError).issues,
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError('Validation failed');
formatZodErrors(result.error as unknown as ZodError);
this.exit(1);
}
// 2b. Expression validation (ADR-0032 §1a/1b) — the same gate `os build`
// runs, brought to the read-only check so authors catch it without
// emitting an artifact. CEL predicates in actions/validations/flows/
// sharing/hooks are checked for syntax AND that `record.<field>`
// references resolve on the target object. This is what catches a
// BARE field ref (`done` instead of `record.done`) that would
// otherwise silently hide an action on every record (#2183/#2185).
if (!flags.json) printStep('Validating expressions (ADR-0032)...');
const exprIssues = validateStackExpressions(result.data as Record<string, unknown>);
const exprErrors = exprIssues.filter((i) => i.severity !== 'warning');
const exprWarnings = exprIssues.filter((i) => i.severity === 'warning');
if (exprErrors.length > 0) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: exprErrors,
warnings: exprWarnings,
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(`Expression validation failed (${exprErrors.length} issue${exprErrors.length > 1 ? 's' : ''})`);
for (const i of exprErrors.slice(0, 50)) {
console.log(` • ${i.where}: ${i.message}`);
console.log(chalk.dim(` source: \`${i.source}\``));
}
this.exit(1);
}
// 3. Dashboard widget reference integrity (issue #1721) — a semantic
// cross-reference pass the protocol schema cannot express: every
// widget's `dataset`/`dimensions`/`values` and chartConfig
// axis/series fields must resolve against the declared datasets
// (ADR-0021). Errors fail validation; warnings are advisory.
if (!flags.json) printStep('Checking dashboard widget bindings (ADR-0021)...');
const widgetFindings = validateWidgetBindings(result.data as Record<string, unknown>);
const widgetErrors = widgetFindings.filter((f) => f.severity === 'error');
const widgetWarnings = widgetFindings.filter((f) => f.severity === 'warning');
if (widgetErrors.length > 0) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: widgetErrors,
warnings: widgetWarnings,
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(`Dashboard widget integrity failed (${widgetErrors.length} issue${widgetErrors.length > 1 ? 's' : ''})`);
for (const f of widgetErrors.slice(0, 50)) {
console.log(` • ${f.where}: ${f.message}`);
console.log(chalk.dim(` ${f.hint}`));
console.log(chalk.dim(` rule: ${f.rule} at ${f.path}`));
}
this.exit(1);
}
// 3b. SDUI scoped-styling correctness (ADR-0065) — a styled node's
// responsiveStyles must be scopable (needs an `id`), reference real
// CSS properties + design tokens, and carry a `large` base;
// Tailwind-in-className silently does nothing. Same bar for
// hand-authored and AI-generated pages (ADR-0019).
if (!flags.json) printStep('Checking SDUI styling (ADR-0065)...');
const styleFindings = validateResponsiveStyles(result.data as Record<string, unknown>);
const styleErrors = styleFindings.filter((f) => f.severity === 'error');
const styleWarnings = styleFindings.filter((f) => f.severity === 'warning');
if (styleErrors.length > 0) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: styleErrors,
warnings: [...widgetWarnings, ...styleWarnings],
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(`SDUI styling check failed (${styleErrors.length} issue${styleErrors.length > 1 ? 's' : ''})`);
for (const f of styleErrors.slice(0, 50)) {
console.log(` • ${f.where}: ${f.message}`);
console.log(chalk.dim(` ${f.hint}`));
console.log(chalk.dim(` rule: ${f.rule} at ${f.path}`));
}
this.exit(1);
}
// 3b. JSX-source pages (ADR-0080) — a kind:'jsx' page's `source` is
// parsed (never executed) and compiled to the SDUI tree at save
// time. Parse it now so malformed source fails loudly (ADR-0078)
// instead of being stored and breaking only at render.
if (!flags.json) printStep('Checking JSX-source pages (ADR-0080)...');
// Optional component manifest (ADR-0080): if the project ships a
// `sdui.manifest.json` (generated from the registry's public tier), the
// gate does full component/prop validation; otherwise parse-level.
let sduiManifest: unknown;
try {
const mp = join(process.cwd(), 'sdui.manifest.json');
if (existsSync(mp)) sduiManifest = JSON.parse(readFileSync(mp, 'utf8'));
if (!sduiManifest) {
// Fall back to the manifest shipped inside @objectstack/console
// (built from objectui's public-tier registry; cli already deps it).
const cp = createRequire(import.meta.url).resolve('@objectstack/console/dist/sdui.manifest.json');
if (existsSync(cp)) sduiManifest = JSON.parse(readFileSync(cp, 'utf8'));
}
} catch { /* fall back to parse-level */ }
const jsxFindings = validateJsxPages(
result.data as Record<string, unknown>,
sduiManifest ? { manifest: sduiManifest as never } : {},
);
const jsxErrors = jsxFindings.filter((f) => f.severity === 'error');
const jsxWarnings = jsxFindings.filter((f) => f.severity === 'warning');
if (jsxErrors.length > 0) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: jsxErrors,
warnings: [...widgetWarnings, ...styleWarnings, ...jsxWarnings],
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(`JSX-source page check failed (${jsxErrors.length} issue${jsxErrors.length > 1 ? 's' : ''})`);
for (const f of jsxErrors.slice(0, 50)) {
console.log(` \u2022 ${f.where}: ${f.message}`);
console.log(chalk.dim(` ${f.hint}`));
console.log(chalk.dim(` rule: ${f.rule} at ${f.path}`));
}
this.exit(1);
}
// 3c. React-source pages (ADR-0081) — a kind:'react' page's `source` is
// real React executed at render. Transpile it now (Sucrase, never
// executed) so syntax errors fail loudly at build, not at render.
if (!flags.json) printStep('Checking React-source pages (ADR-0081)...');
const reactFindings = validateReactPages(result.data as Record<string, unknown>);
const reactErrors = reactFindings.filter((f) => f.severity === 'error');
if (reactErrors.length > 0) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: reactErrors,
warnings: [...widgetWarnings, ...styleWarnings, ...jsxWarnings],
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(`React-source page check failed (${reactErrors.length} issue${reactErrors.length > 1 ? 's' : ''})`);
for (const f of reactErrors.slice(0, 50)) {
console.log(` \u2022 ${f.where}: ${f.message}`);
console.log(chalk.dim(` ${f.hint}`));
console.log(chalk.dim(` rule: ${f.rule} at ${f.path}`));
}
this.exit(1);
}
// 3d. React-source pages — prop usage against the component contract
// (ADR-0081 Phase 2): missing required bindings (error) + likely
// prop typos (warning), parsed from the real JSX.
if (!flags.json) printStep('Checking React-source page props (ADR-0081)...');
const reactPropFindings = validateReactPageProps(result.data as Record<string, unknown>);
const reactPropErrors = reactPropFindings.filter((f) => f.severity === 'error');
const reactPropWarnings = reactPropFindings.filter((f) => f.severity === 'warning');
if (!flags.json) {
for (const w of reactPropWarnings.slice(0, 50)) {
console.log(chalk.yellow(` \u26a0 ${w.where}: ${w.message}`));
console.log(chalk.dim(` ${w.hint}`));
}
}
if (reactPropErrors.length > 0) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
errors: reactPropErrors,
warnings: [...widgetWarnings, ...styleWarnings, ...jsxWarnings, ...reactPropWarnings],
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(`React-source page prop check failed (${reactPropErrors.length} issue${reactPropErrors.length > 1 ? 's' : ''})`);
for (const f of reactPropErrors.slice(0, 50)) {
console.log(` \u2022 ${f.where}: ${f.message}`);
console.log(chalk.dim(` ${f.hint}`));
console.log(chalk.dim(` rule: ${f.rule} at ${f.path}`));
}
this.exit(1);
}
// 4. Collect and display stats
const stats = collectMetadataStats(config);
if (flags.json) {
console.log(JSON.stringify({
valid: true,
manifest: config.manifest,
stats,
warnings: [...exprWarnings, ...widgetWarnings, ...styleWarnings, ...jsxWarnings],
duration: timer.elapsed(),
}, null, 2));
return;
}
// 5. Warnings (non-blocking)
const warnings: string[] = [];
for (const i of exprWarnings) {
warnings.push(`${i.where}: ${i.message}`);
}
for (const f of widgetWarnings) {
warnings.push(`${f.where}: ${f.message}`);
}
for (const f of styleWarnings) {
warnings.push(`${f.where}: ${f.message}`);
}
for (const f of jsxWarnings) {
warnings.push(`${f.where}: ${f.message}`);
}
if (stats.objects === 0) {
warnings.push('No objects defined — this stack has no data model');
}
if (stats.apps === 0 && stats.plugins === 0) {
warnings.push('No apps or plugins defined — this stack may not do much');
}
if (!config.manifest?.id) {
warnings.push('Missing manifest.id — required for deployment');
}
if (!config.manifest?.namespace) {
warnings.push('Missing manifest.namespace — required for multi-app hosting');
}
// 6. Display results
console.log('');
printSuccess(`Validation passed ${chalk.dim(`(${timer.display()})`)}`);
console.log('');
if (config.manifest) {
console.log(` ${chalk.bold(config.manifest.name || config.manifest.id || 'Unnamed')} ${chalk.dim(`v${config.manifest.version || '0.0.0'}`)}`);
if (config.manifest.description) {
console.log(chalk.dim(` ${config.manifest.description}`));
}
console.log('');
}
printMetadataStats(stats);
if (warnings.length > 0) {
console.log('');
for (const w of warnings) {
console.log(chalk.yellow(` ⚠ ${w}`));
}
if (flags.strict) {
console.log('');
printError('Strict mode: warnings treated as errors');
this.exit(1);
}
}
console.log('');
} catch (error: any) {
if (flags.json) {
console.log(JSON.stringify({
valid: false,
error: error.message,
duration: timer.elapsed(),
}, null, 2));
this.exit(1);
}
console.log('');
printError(error.message || String(error));
this.exit(1);
}
}
}