@rangular-framework/cli 0.0.0-stage → 1.0.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 (36) hide show
  1. package/dist/cli/src/cli.js +1217 -0
  2. package/dist/compiler/src/catalog.js +198 -0
  3. package/dist/compiler/src/class/formInit.js +370 -0
  4. package/dist/compiler/src/class/parseComponent.js +430 -0
  5. package/dist/compiler/src/class/parseDirective.js +227 -0
  6. package/dist/compiler/src/class/parseRoutes.js +163 -0
  7. package/dist/compiler/src/codegen/generate.js +3466 -0
  8. package/dist/compiler/src/codegen/methods.js +975 -0
  9. package/dist/compiler/src/codegen/sourceMap.js +77 -0
  10. package/dist/compiler/src/compile.js +775 -0
  11. package/dist/compiler/src/diagnostics.js +113 -0
  12. package/dist/compiler/src/doctor.js +144 -0
  13. package/dist/compiler/src/fix.js +44 -0
  14. package/dist/compiler/src/index.js +38 -0
  15. package/dist/compiler/src/preview/renderPreview.js +7158 -0
  16. package/dist/compiler/src/preview/styleSnapshot.js +268 -0
  17. package/dist/compiler/src/propTable.js +107 -0
  18. package/dist/compiler/src/style/css.js +161 -0
  19. package/dist/compiler/src/template/ast.js +19 -0
  20. package/dist/compiler/src/template/evaluate.js +151 -0
  21. package/dist/compiler/src/template/expr.js +360 -0
  22. package/dist/compiler/src/template/forms.js +80 -0
  23. package/dist/compiler/src/template/literal.js +248 -0
  24. package/dist/compiler/src/template/parser.js +230 -0
  25. package/dist/compiler/src/template/pipes.js +225 -0
  26. package/dist/compiler/src/template/printAst.js +38 -0
  27. package/dist/compiler/src/template/structural.js +51 -0
  28. package/dist/runtime/src/index.js +1197 -0
  29. package/dist/ui/src/chart.js +196 -0
  30. package/dist/ui/src/datetime.js +240 -0
  31. package/dist/ui/src/icons.js +310 -0
  32. package/dist/ui/src/mask.js +103 -0
  33. package/dist/ui/src/palette.js +141 -0
  34. package/dist/ui/src/tokens.js +173 -0
  35. package/package.json +28 -4
  36. package/README.md +0 -3
@@ -0,0 +1,1217 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ /**
38
+ * Rangular CLI:
39
+ * rg build <component.ts> --out <file.tsx> [--json] [--source-map] [--routes <file>]
40
+ * rg ast <template.html>
41
+ * rg preview <component.ts> --out <file.html> [--json] [--routes <file>]
42
+ * rg catalog [--out <dir>]
43
+ * rg watch <component.ts> --out <file.tsx> [--routes <file>]
44
+ * rg init <dir> [--app]
45
+ * rg doctor <component.ts> [--json] [--routes <file>]
46
+ * rg verify [<component.ts>] [--json] [--routes <file>] [--no-strict]
47
+ *
48
+ * --routes names the routes file (Stage 9); without it the compiler
49
+ * auto-discovers a sibling app.routes.ts next to the component.
50
+ *
51
+ * Run from the compiled output: node dist/packages/cli/src/cli.js ...
52
+ *
53
+ * --json prints ONE JSON object to stdout ({ ok, outFile?, diagnostics })
54
+ * and nothing else, so AI tools and scripts can consume diagnostics and
55
+ * self-correct. Human diagnostics (with `fix:` lines) go to stderr.
56
+ * Diagnostics carry a `file` when their origin differs from the entry
57
+ * file: template problems name the .html, style problems the file that
58
+ * holds the styles (Stage 5).
59
+ */
60
+ const fs = __importStar(require("node:fs"));
61
+ const node_child_process_1 = require("node:child_process");
62
+ const path = __importStar(require("node:path"));
63
+ const index_1 = require("../../compiler/src/index");
64
+ function fail(message) {
65
+ console.error(`rg: ${message}`);
66
+ process.exit(2);
67
+ }
68
+ function option(args, name) {
69
+ const idx = args.indexOf(name);
70
+ return idx >= 0 ? args[idx + 1] : undefined;
71
+ }
72
+ /**
73
+ * Project root boundary (security audit, 2026-11-12): the nearest
74
+ * ancestor of the entry file that holds a package.json, falling back to
75
+ * the entry file's own directory. The resolvers below refuse to read
76
+ * anything outside this tree, and the same root is passed to the
77
+ * compiler, which reports escapes as CMP_PATH_ESCAPE errors.
78
+ */
79
+ function projectRootFor(entryAbs) {
80
+ let dir = path.dirname(entryAbs);
81
+ for (;;) {
82
+ if (fs.existsSync(path.join(dir, 'package.json')))
83
+ return dir;
84
+ const parent = path.dirname(dir);
85
+ if (parent === dir)
86
+ return path.dirname(entryAbs);
87
+ dir = parent;
88
+ }
89
+ }
90
+ function withinRoot(root, candidate) {
91
+ const rel = path.relative(root, candidate);
92
+ return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel));
93
+ }
94
+ function readComponent(componentFile) {
95
+ const abs = path.resolve(componentFile);
96
+ if (!fs.existsSync(abs))
97
+ fail(`file not found: ${componentFile}`);
98
+ const tsSource = fs.readFileSync(abs, 'utf8');
99
+ const dir = path.dirname(abs);
100
+ const rootDir = projectRootFor(abs);
101
+ const resolveFile = (rel) => {
102
+ const p = path.resolve(dir, rel);
103
+ if (!withinRoot(rootDir, p))
104
+ return undefined;
105
+ return fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : undefined;
106
+ };
107
+ /**
108
+ * Stage 3 import resolution: a relative specifier resolves against the
109
+ * importing file's directory, trying the specifier as-is (templates),
110
+ * with a '.ts' extension, and as a directory index.
111
+ */
112
+ const resolveImport = (spec, importer) => {
113
+ const base = path.resolve(path.dirname(importer), spec);
114
+ for (const candidate of [base, `${base}.ts`, path.join(base, 'index.ts')]) {
115
+ if (!withinRoot(rootDir, candidate))
116
+ continue;
117
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
118
+ return { source: fs.readFileSync(candidate, 'utf8'), fileName: candidate };
119
+ }
120
+ }
121
+ return undefined;
122
+ };
123
+ return { tsSource, resolveFile, resolveImport, absPath: abs, rootDir };
124
+ }
125
+ function toJsonDiagnostic(d) {
126
+ const out = { severity: d.severity, code: d.code, message: d.message };
127
+ if (d.line !== undefined)
128
+ out.line = d.line;
129
+ if (d.column !== undefined)
130
+ out.column = d.column;
131
+ if (d.file !== undefined)
132
+ out.file = d.file;
133
+ if (d.fix !== undefined)
134
+ out.fix = d.fix;
135
+ return out;
136
+ }
137
+ function printJson(payload) {
138
+ console.log(JSON.stringify(payload, null, 2));
139
+ }
140
+ const USAGE = [
141
+ 'Usage:',
142
+ ' rg build [<component.ts>] [--out <file.tsx>] [--json] [--source-map] [--routes <file>] [--strict | --no-strict]',
143
+ ' rg ast <template.html>',
144
+ ' rg preview <component.ts> --out <file.html> [--json] [--routes <file>]',
145
+ ' rg catalog [--out <dir>]',
146
+ ' rg watch <component.ts> --out <file.tsx> [--routes <file>]',
147
+ ' rg init <dir> [--app]',
148
+ ' rg doctor <component.ts> [--json] [--routes <file>] [--strict | --no-strict]',
149
+ ' rg verify [<component.ts>] [--json] [--routes <file>] [--no-strict]',
150
+ ' rg fix [<component.ts>] [--json] [--routes <file>]',
151
+ ].join('\n');
152
+ /**
153
+ * The --routes flag (Stage 9) as a specifier the compiler can resolve
154
+ * from the entry file: a './'-style relative path from the component's
155
+ * directory to the routes file. The compiler's own project-root
156
+ * boundary still applies to the resolved file.
157
+ */
158
+ function routesSpecifierFor(entryAbs, routesArg) {
159
+ if (!routesArg)
160
+ return undefined;
161
+ const routesAbs = path.resolve(routesArg);
162
+ if (!fs.existsSync(routesAbs))
163
+ fail(`routes file not found: ${routesArg}`);
164
+ let rel = path.relative(path.dirname(entryAbs), routesAbs).split(path.sep).join('/');
165
+ if (!rel.startsWith('.'))
166
+ rel = `./${rel}`;
167
+ return rel;
168
+ }
169
+ /**
170
+ * The Rangular repo root as seen from this CLI (Stage 12): the CLI
171
+ * runs from <root>/dist/packages/cli/src, so the root is four levels
172
+ * up. The Expo scaffold needs it to compute the file: dependencies
173
+ * that point at the repo's packages, and to place a bare-named app
174
+ * under <root>/apps.
175
+ */
176
+ function rgRepoRoot() {
177
+ return path.resolve(__dirname, '..', '..', '..', '..');
178
+ }
179
+ /**
180
+ * True when this CLI runs from inside the Rangular checkout: the
181
+ * root resolved above is a real checkout when its packages/ui is
182
+ * the framework's own UI package. A CLI installed from npm resolves
183
+ * its would-be root inside node_modules, where that check fails;
184
+ * that is published mode. The Expo scaffold behaves differently in
185
+ * the two modes on purpose: a checkout app binds to its checkout
186
+ * through file: specifiers, a published-mode app depends on the
187
+ * released packages by version range.
188
+ */
189
+ function isCheckoutRoot(root) {
190
+ try {
191
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'packages', 'ui', 'package.json'), 'utf8'));
192
+ return !!pkg && pkg.name === '@rangular-framework/ui';
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ }
198
+ /** The CLI's own version, used as the published-mode dependency range. */
199
+ function cliVersion(root, checkout) {
200
+ const candidates = checkout
201
+ ? [path.join(root, 'packages', 'cli', 'package.json')]
202
+ : [path.resolve(__dirname, '..', '..', '..', 'package.json')];
203
+ for (const candidate of candidates) {
204
+ try {
205
+ const pkg = JSON.parse(fs.readFileSync(candidate, 'utf8'));
206
+ if (pkg && typeof pkg.version === 'string')
207
+ return pkg.version;
208
+ }
209
+ catch {
210
+ /* try the next candidate */
211
+ }
212
+ }
213
+ return '0.3.1';
214
+ }
215
+ const STARTER_TS = `import { Component } from \'@angular/core\';
216
+
217
+ @Component({
218
+ selector: \'app-root\',
219
+ templateUrl: \'./app.component.html\',
220
+ styles: [\`,
221
+ /* doctor: allow-hex (the starter band colours are the deliberate brand palette) */
222
+ .band-title { font-size: 20px; font-weight: 700; color: #ffffff; }
223
+ .band-sub { font-size: 14px; color: #d3e3fd; }
224
+ .row { flex-direction: row; align-items: center; gap: 12px; }
225
+ .ic { width: 44px; height: 44px; border-radius: 9999px; background-color: #e8f0fe; align-items: center; justify-content: center; }
226
+ .grow { flex: 1; }
227
+ .muted { font-size: 14px; color: #5f6368; }
228
+ .pill { background-color: #e8f0fe; border-radius: 9999px; padding: 8px; }
229
+ .pill-text { font-size: 12px; font-weight: 700; color: #0b57d0; }
230
+ \`],
231
+ })
232
+ export class AppComponent {
233
+ title = \'Welcome to Rangular\';
234
+ lightOn = true;
235
+ taps = 0;
236
+
237
+ onLight(value: boolean) {
238
+ this.lightOn = value;
239
+ }
240
+
241
+ start() {
242
+ this.taps++;
243
+ }
244
+ }
245
+ `;
246
+ const STARTER_HTML = `<screen>
247
+ <appbar title="Rangular"></appbar>
248
+ <gradient>
249
+ <p class="band-title">{{ title }}</p>
250
+ <p class="band-sub">You wrote Angular. This screen is React Native.</p>
251
+ </gradient>
252
+ <card>
253
+ <section class="row">
254
+ <section class="ic"><icon name="home" color="primary"></icon></section>
255
+ <section class="grow">
256
+ <h3>Your first screen</h3>
257
+ <p class="muted">It opens dressed. Make it yours.</p>
258
+ </section>
259
+ <section class="pill"><p class="pill-text">1 screen</p></section>
260
+ </section>
261
+ <section class="row">
262
+ <p class="grow">Ceiling light</p>
263
+ <switch color="success" [checked]="lightOn" (change)="onLight($event)"></switch>
264
+ </section>
265
+ <button (click)="start()">Get started</button>
266
+ <p *ngIf="taps > 0">Started {{ taps }} times</p>
267
+ </card>
268
+ </screen>
269
+ `;
270
+ /** A package.json name from a directory name: lowercase, npm-safe. */
271
+ function packageNameOf(dirName) {
272
+ const cleaned = dirName.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+/, '');
273
+ return cleaned || 'rg-app';
274
+ }
275
+ /** A path as a file: dependency specifier, relative and forward-slashed. */
276
+ function fileDepOf(fromDir, toDir) {
277
+ const rel = path.relative(fromDir, toDir).split(path.sep).join('/');
278
+ return `file:${rel.startsWith('.') ? rel : `./${rel}`}`;
279
+ }
280
+ /**
281
+ * `rg init <dir> --app`: scaffold a real Expo app (Stage 12).
282
+ *
283
+ * A bare name (no path separators) creates the app at
284
+ * <repoRoot>/apps/<name>; an explicit path (absolute, or containing a
285
+ * separator) is used as given. Either way the generated package.json
286
+ * depends on @rangular-framework/ui and @rangular-framework/runtime through file:
287
+ * specifiers computed relative from the app directory to this repo's
288
+ * packages, so the app always builds against the checkout it was
289
+ * scaffolded from. Every file is written under the app directory;
290
+ * the starter component is compiled at init time into src/AppRoot.tsx
291
+ * by the real compiler, so what App.tsx imports is genuine compiler
292
+ * output, not a stored sample.
293
+ *
294
+ * The dependency pins are the Expo SDK 58 set (expo ~58, react 19.3,
295
+ * react-native 0.88, react-native-svg 15.16, babel-preset-expo ~58),
296
+ * chosen for mutual compatibility per the SDK 58 release. The set
297
+ * also carries expo-image-picker ~58.0.10 and expo-document-picker
298
+ * ~58.0.5: RgFilePicker names both in literal requires, and Metro
299
+ * resolves every literal require when an app bundles, so both are
300
+ * required dependencies of any app built on @rangular-framework/ui, not an
301
+ * option an app picks per kind. The same holds for expo-haptics
302
+ * ~58.0.8, which RgSwitch requires lazily for its haptic answer. The set moved from SDK 54 to
303
+ * SDK 58 on 2026-11-12 because the store build of Expo Go supports
304
+ * SDK 58 only and refused an SDK 54 app. The pins come from the
305
+ * SDK's published compatibility set; they were not installed or
306
+ * device-verified from this environment, and the app README
307
+ * says so.
308
+ */
309
+ function initApp(dirArg) {
310
+ const repoRoot = rgRepoRoot();
311
+ const checkout = isCheckoutRoot(repoRoot);
312
+ const isBareName = !path.isAbsolute(dirArg) && !dirArg.includes('/') && !dirArg.includes('\\');
313
+ let appDir;
314
+ if (isBareName) {
315
+ if (!/^[A-Za-z0-9._-]+$/.test(dirArg) || dirArg === '.' || dirArg === '..') {
316
+ console.error((0, index_1.formatDiagnostic)({
317
+ severity: 'error',
318
+ code: 'CLI_INIT_UNSAFE',
319
+ message: `Cannot init an app named '${dirArg}': a bare app name may only use letters, digits, dot, underscore and hyphen, and may not be . or ..`,
320
+ fix: 'Use a simple name, e.g. rg init my-app --app, or pass an explicit path',
321
+ }));
322
+ process.exit(1);
323
+ }
324
+ appDir = checkout ? path.join(repoRoot, 'apps', dirArg) : path.resolve(dirArg);
325
+ }
326
+ else {
327
+ appDir = path.resolve(dirArg);
328
+ }
329
+ if (fs.existsSync(appDir) && fs.readdirSync(appDir).length > 0) {
330
+ console.error((0, index_1.formatDiagnostic)({
331
+ severity: 'error',
332
+ code: 'CLI_INIT_NOT_EMPTY',
333
+ message: `Cannot init an app into '${appDir}': the directory is not empty`,
334
+ fix: 'Pick a new directory name, or empty the directory first, e.g. rg init my-app --app',
335
+ }));
336
+ process.exit(1);
337
+ }
338
+ const appName = packageNameOf(path.basename(appDir));
339
+ const relToRepo = path.relative(appDir, repoRoot).split(path.sep).join('/') || '.';
340
+ const srcDir = path.join(appDir, 'src');
341
+ fs.mkdirSync(srcDir, { recursive: true });
342
+ const write = (rel, content) => {
343
+ const target = path.join(appDir, rel);
344
+ fs.mkdirSync(path.dirname(target), { recursive: true });
345
+ fs.writeFileSync(target, content);
346
+ };
347
+ write('package.json', JSON.stringify({
348
+ name: appName,
349
+ version: '1.0.0',
350
+ private: true,
351
+ main: 'node_modules/expo/AppEntry.js',
352
+ scripts: {
353
+ start: 'expo start',
354
+ android: 'expo start --android',
355
+ ios: 'expo start --ios',
356
+ web: 'expo start --web',
357
+ },
358
+ dependencies: {
359
+ '@rangular-framework/runtime': checkout
360
+ ? fileDepOf(appDir, path.join(repoRoot, 'packages', 'runtime'))
361
+ : `^${cliVersion(repoRoot, checkout)}`,
362
+ '@rangular-framework/ui': checkout
363
+ ? fileDepOf(appDir, path.join(repoRoot, 'packages', 'ui'))
364
+ : `^${cliVersion(repoRoot, checkout)}`,
365
+ expo: '~58.0.0',
366
+ 'expo-document-picker': '~58.0.5',
367
+ 'expo-haptics': '~58.0.8',
368
+ 'expo-image-picker': '~58.0.10',
369
+ react: '19.3.0',
370
+ 'react-native': '0.88.1',
371
+ 'react-native-safe-area-context': '~5.6.0',
372
+ 'react-native-svg': '15.16.0',
373
+ rxjs: '^7.8.2',
374
+ },
375
+ devDependencies: {
376
+ '@babel/core': '^7.25.2',
377
+ 'babel-preset-expo': '~58.0.0',
378
+ typescript: '~5.9.2',
379
+ },
380
+ }, null, 2) + '\n');
381
+ write('app.json', JSON.stringify({
382
+ expo: {
383
+ name: appName,
384
+ slug: appName,
385
+ version: '1.0.0',
386
+ scheme: appName,
387
+ orientation: 'portrait',
388
+ platforms: ['ios', 'android'],
389
+ },
390
+ }, null, 2) + '\n');
391
+ write('babel.config.js', `module.exports = function (api) {
392
+ api.cache(true);
393
+ return {
394
+ presets: ['babel-preset-expo'],
395
+ };
396
+ };
397
+ `);
398
+ write('metro.config.js', checkout ? `const path = require('path');
399
+ const { getDefaultConfig } = require('expo/metro-config');
400
+
401
+ // Monorepo layout: this app lives outside the Rangular repo's package
402
+ // directories but depends on them through file: specifiers, so Metro
403
+ // must watch the repo root and resolve modules from both node_modules.
404
+ const projectRoot = __dirname;
405
+ const workspaceRoot = path.resolve(projectRoot, '${relToRepo}');
406
+
407
+ const config = getDefaultConfig(projectRoot);
408
+ config.watchFolders = [workspaceRoot];
409
+ config.resolver.nodeModulesPaths = [
410
+ path.resolve(projectRoot, 'node_modules'),
411
+ path.resolve(workspaceRoot, 'node_modules'),
412
+ ];
413
+
414
+ module.exports = config;
415
+ ` : `const { getDefaultConfig } = require('expo/metro-config');
416
+
417
+ // Standard Expo config: the framework packages arrive through npm
418
+ // like every other dependency, so Metro needs no special layout.
419
+ const config = getDefaultConfig(__dirname);
420
+
421
+ module.exports = config;
422
+ `);
423
+ write('tsconfig.json', JSON.stringify({
424
+ extends: 'expo/tsconfig.base',
425
+ compilerOptions: { strict: true },
426
+ }, null, 2) + '\n');
427
+ write('App.tsx', `import React from 'react';
428
+ import AppRoot from './src/AppRoot';
429
+
430
+ // Hardware back (Android) and Rangular routing: the compiled root
431
+ // module keeps its navigator private, so App.tsx cannot call back()
432
+ // on it yet. In-app back navigation is a template concern today (a
433
+ // button that navigates where the user came from); the app README's
434
+ // "Back behaviour" section states exactly what works and what does
435
+ // not. Nothing is wired here that is not real.
436
+ export default function App() {
437
+ return <AppRoot />;
438
+ }
439
+ `);
440
+ write(path.join('src', 'app.component.ts'), STARTER_TS);
441
+ write(path.join('src', 'app.component.html'), STARTER_HTML);
442
+ write('.gitignore', 'node_modules\n.expo\ndist\n');
443
+ // Compile the starter now, with the real compiler, so src/AppRoot.tsx
444
+ // is genuine output for the starter source.
445
+ const entryAbs = path.join(srcDir, 'app.component.ts');
446
+ const { tsSource, resolveFile, resolveImport, rootDir } = readComponent(entryAbs);
447
+ const result = (0, index_1.compileComponent)({ tsSource, fileName: entryAbs, resolveFile, resolveImport, rootDir });
448
+ for (const d of result.diagnostics)
449
+ console.error((0, index_1.formatDiagnostic)(d, entryAbs));
450
+ if ((0, index_1.hasErrors)(result.diagnostics) || !result.code) {
451
+ console.error('rg: the starter component did not compile; the scaffold is incomplete');
452
+ process.exit(1);
453
+ }
454
+ write(path.join('src', 'AppRoot.tsx'), result.code);
455
+ const recompileSection = checkout ? `## Recompile after editing the component
456
+
457
+ Run this from the Rangular repo root (the folder you cloned; every
458
+ path in the command is relative to that folder):
459
+
460
+ node dist/packages/cli/src/cli.js build ${path.relative(repoRoot, entryAbs).split(path.sep).join('/')} --out ${path.relative(repoRoot, path.join(srcDir, 'AppRoot.tsx')).split(path.sep).join('/')}
461
+
462
+ If the CLI is on your PATH, the same compile from this app folder is
463
+ just \`rg build\`: with no arguments it compiles
464
+ \`src/app.component.ts\` into \`src/AppRoot.tsx\`.
465
+
466
+ Or run the same command with \`watch\` instead of \`build\` and it
467
+ recompiles on every save.
468
+
469
+ ## Preview in a browser, no phone needed
470
+
471
+ The dev preview renders any app component as a phone-width page you
472
+ can click through. From the Rangular repo root:
473
+
474
+ node dist/packages/cli/src/cli.js preview ${path.relative(repoRoot, entryAbs).split(path.sep).join('/')} --out ${path.relative(repoRoot, path.join(appDir, 'preview.html')).split(path.sep).join('/')}
475
+
476
+ Then open \`preview.html\` in this app folder in a browser. The
477
+ preview is interactive: handlers run and lists respond, exactly as
478
+ the generated app behaves.` : `## Recompile after editing the component
479
+
480
+ Run this from the app folder:
481
+
482
+ rg build
483
+
484
+ With no arguments, the build compiles \`src/app.component.ts\` and
485
+ writes \`src/AppRoot.tsx\`, the one shape every Rangular app follows.
486
+ The same compile spelled out is \`rg build src/app.component.ts
487
+ --out src/AppRoot.tsx\`; pass the entry and \`--out\` yourself only
488
+ when an app steps outside that shape.
489
+
490
+ Or run the same command with \`watch\` instead of \`build\` and it
491
+ recompiles on every save.
492
+
493
+ ## Preview in a browser, no phone needed
494
+
495
+ The dev preview renders any app component as a phone-width page you
496
+ can click through. From the app folder:
497
+
498
+ rg preview src/app.component.ts --out preview.html
499
+
500
+ Then open \`preview.html\` in this app folder in a browser. The
501
+ preview is interactive: handlers run and lists respond, exactly as
502
+ the generated app behaves.`;
503
+ const fitBullet = checkout ? `- \`package.json\` depends on \`@rangular-framework/ui\` and
504
+ \`@rangular-framework/runtime\` through \`file:\` specifiers that point at the
505
+ Rangular checkout this app was scaffolded from, so the app always
506
+ builds against that checkout. Move the app and those paths move
507
+ with it only if the relative layout is kept; edit them if you
508
+ relocate the app on its own.` : `- \`package.json\` depends on \`@rangular-framework/ui\` and
509
+ \`@rangular-framework/runtime\` by version range from npm, so the app
510
+ builds against the released framework packages. The CLI that
511
+ scaffolded this app stamps its own version as the range, so the
512
+ two move together.`;
513
+ const metroBullet = checkout ? `- \`metro.config.js\` is the standard monorepo config: it watches the
514
+ Rangular repo root (so the file: packages resolve) and looks for
515
+ node_modules in both the app and the repo root.` : `- \`metro.config.js\` is the standard Expo config. The framework
516
+ packages arrive through npm like every other dependency, so Metro
517
+ needs no special layout.`;
518
+ write('rangular.json', '{\n "strict": true\n}\n');
519
+ write('AGENTS.md', `# Building this app with an AI assistant
520
+
521
+ This is a Rangular app: Angular-style components in src/, compiled to
522
+ React Native by the Rangular compiler, run by Expo.
523
+
524
+ Rules the compiler enforces:
525
+
526
+ - One structural directive per element: *ngIf or *ngFor, never both.
527
+ - Methods hold only expression statements, returns, ifs and const
528
+ declarations. No loops; use map, forEach, filter and reduce.
529
+ No new Date() in methods; use Date.now() and civil date math.
530
+ - Styles use the supported subset and the design scales: spacing
531
+ 4 8 12 16 20 24 32, radius 8 12 16 20 full, font sizes
532
+ 12 14 16 20 24 32. Off-scale values snap with a warning.
533
+ - Every element and every prop must exist in the framework catalog.
534
+ When unsure, check the catalog before writing the code.
535
+ - A template event binding must name a method the component has.
536
+ - Nothing fails silently. An unsupported construct produces a coded
537
+ diagnostic with a fix. Read the fix and apply it; do not work
538
+ around a diagnostic.
539
+
540
+ The verify loop:
541
+
542
+ 1. Run: rg verify
543
+ One gate: strict build, doctor, the app tests and a render
544
+ check. Strict mode is on in this app (rangular.json), so
545
+ warnings fail. Nothing is dropped or snapped quietly.
546
+ 2. Fix every diagnostic it names. Read the fix and apply it.
547
+ 3. Run rg verify again. Only a clean run means the work is done.
548
+
549
+ The full guide lives in the framework repo at docs/AI_GUIDE.md.
550
+
551
+ Before writing code, read the guardrails in the framework repo
552
+ at GUARDRAILS_FOR_VIBECODING.md:
553
+ https://github.com/bigyanchap/rangular-framework/blob/main/GUARDRAILS_FOR_VIBECODING.md
554
+ They name the mistakes rapid coding makes, and the code that
555
+ catches each one.
556
+ `);
557
+ write('README.md', `# ${appName}
558
+
559
+ A real Expo app scaffolded by the Rangular framework (Stage 12). You write
560
+ Angular-style components in \`src/\`; the Rangular compiler turns them
561
+ into React Native code, and Expo runs the result.
562
+
563
+ ## Run it on a phone
564
+
565
+ npm install
566
+ npx expo start
567
+
568
+ Then scan the QR code with Expo Go. Your component is
569
+ \`src/app.component.ts\` (with its template
570
+ \`src/app.component.html\`); the compiled output Expo loads is
571
+ \`src/AppRoot.tsx\`, generated from it at scaffold time.
572
+
573
+ ${recompileSection}
574
+
575
+ ## How the pieces fit
576
+
577
+ ${fitBullet}
578
+ - The Expo pins (expo ~58, react 19.3, react-native 0.88,
579
+ react-native-svg 15.16, expo-image-picker ~58.0.10,
580
+ expo-document-picker ~58.0.5, babel-preset-expo ~58) are the Expo
581
+ SDK 58 set, chosen for mutual compatibility. The set moved from
582
+ SDK 54 to SDK 58 because the store build of Expo Go supports
583
+ SDK 58 only. They were selected from the SDK's published
584
+ compatibility, not installed or device-verified when this
585
+ scaffold was written.
586
+ - \`expo-image-picker\` and \`expo-document-picker\` are required
587
+ dependencies, not extras: \`RgFilePicker\` in \`@rangular-framework/ui\`
588
+ names both in literal requires, and Metro resolves every literal
589
+ require when the app bundles, so the bundle fails without either
590
+ one. Keep both even if this app never shows a file picker.
591
+ - \`expo-haptics\` is required the same way: \`RgSwitch\` requires
592
+ it lazily to answer a toggle with a haptic when a switch carries
593
+ the \`haptic\` attribute. Keep it even if no switch uses it.
594
+ - \`react-native-safe-area-context\` is required the same way:
595
+ \`RgScreen\` imports its provider and inset hook directly to
596
+ pad the screen by the phone's real safe-area insets on both
597
+ platforms. Keep it even though no template names it.
598
+ ${metroBullet}
599
+
600
+ ## Back behaviour
601
+
602
+ The starter has one screen, so there is nothing to go back to. When
603
+ an app grows a router (see the routing section of the repo's
604
+ docs/AI_GUIDE.md), navigation inside the app is complete:
605
+ routerLink and the Router service work. The Android hardware back
606
+ button is not wired to the Rangular navigator in this version: the
607
+ compiled root module keeps its navigator private, so App.tsx cannot
608
+ call back() on it honestly, and this scaffold does not pretend
609
+ otherwise. In-app back affordances (a Back button that navigates to
610
+ the previous screen explicitly) work today; exporting the navigator
611
+ for hardware back is future work.
612
+
613
+ ## What was verified
614
+
615
+ The scaffold's structure and the starter's compilation are covered
616
+ by the Rangular test suite. An actual Expo Go launch on a device was
617
+ not run in the environment that wrote this scaffold; your first
618
+ \`npx expo start\` is the device proof.
619
+ `);
620
+ console.log(`Created an Expo app in ${appDir}`);
621
+ if (checkout && isBareName && !process.cwd().startsWith(repoRoot)) {
622
+ console.log(`Note: a bare name places the app under the Rangular repo's apps folder (${appDir}), not the current directory.`);
623
+ }
624
+ console.log(`Run it: cd ${appDir} && npm install && npx expo start`);
625
+ }
626
+ /** `rg init <dir>`: scaffold a starter project (Stage 5). */
627
+ function initProject(dirArg) {
628
+ const dir = path.resolve(dirArg);
629
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length > 0) {
630
+ console.error((0, index_1.formatDiagnostic)({
631
+ severity: 'error',
632
+ code: 'CLI_INIT_NOT_EMPTY',
633
+ message: `Cannot init into '${dirArg}': the directory is not empty`,
634
+ fix: 'Pick a new directory name, or empty the directory first, e.g. rg init my-app',
635
+ }));
636
+ process.exit(1);
637
+ }
638
+ const srcDir = path.join(dir, 'src');
639
+ fs.mkdirSync(srcDir, { recursive: true });
640
+ fs.writeFileSync(path.join(srcDir, 'app.component.ts'), `import { Component } from '@angular/core';
641
+
642
+ @Component({
643
+ selector: 'app-root',
644
+ templateUrl: './app.component.html',
645
+ styles: [\`,
646
+ /* doctor: allow-hex (the starter band colours are the deliberate brand palette) */
647
+ .band-title { font-size: 20px; font-weight: 700; color: #ffffff; }
648
+ .band-sub { font-size: 14px; color: #d3e3fd; }
649
+ .row { flex-direction: row; align-items: center; gap: 12px; }
650
+ .ic { width: 44px; height: 44px; border-radius: 9999px; background-color: #e8f0fe; align-items: center; justify-content: center; }
651
+ .grow { flex: 1; }
652
+ .muted { font-size: 14px; color: #5f6368; }
653
+ .pill { background-color: #e8f0fe; border-radius: 9999px; padding: 8px; }
654
+ .pill-text { font-size: 12px; font-weight: 700; color: #0b57d0; }
655
+ \`],
656
+ })
657
+ export class AppComponent {
658
+ title = 'Welcome to Rangular';
659
+ lightOn = true;
660
+ taps = 0;
661
+
662
+ onLight(value: boolean) {
663
+ this.lightOn = value;
664
+ }
665
+
666
+ start() {
667
+ this.taps++;
668
+ }
669
+ }
670
+ `);
671
+ fs.writeFileSync(path.join(srcDir, 'app.component.html'), `<screen>
672
+ <appbar title=\"Rangular\"></appbar>
673
+ <gradient>
674
+ <p class=\"band-title\">{{ title }}</p>
675
+ <p class=\"band-sub\">You wrote Angular. This screen is React Native.</p>
676
+ </gradient>
677
+ <card>
678
+ <section class=\"row\">
679
+ <section class=\"ic\"><icon name=\"home\" color=\"primary\"></icon></section>
680
+ <section class=\"grow\">
681
+ <h3>Your first screen</h3>
682
+ <p class=\"muted\">It opens dressed. Make it yours.</p>
683
+ </section>
684
+ <section class=\"pill\"><p class=\"pill-text\">1 screen</p></section>
685
+ </section>
686
+ <section class=\"row\">
687
+ <p class=\"grow\">Ceiling light</p>
688
+ <switch color=\"success\" [checked]=\"lightOn\" (change)=\"onLight($event)\"></switch>
689
+ </section>
690
+ <button (click)=\"start()\">Get started</button>
691
+ <p *ngIf=\"taps > 0\">Started {{ taps }} times</p>
692
+ </card>
693
+ </screen>
694
+ `);
695
+ fs.writeFileSync(path.join(dir, 'README.md'), `# ${path.basename(dir)}
696
+
697
+ A starter Rangular project. You write Angular-style components in
698
+ \`src/\`, and the Rangular compiler turns them into React Native code.
699
+
700
+ ## Build the starter screen
701
+
702
+ From the Rangular repo root (the folder you cloned), run:
703
+
704
+ node dist/packages/cli/src/cli.js build ${dirArg}/src/app.component.ts --out ${dirArg}/src/app.component.tsx
705
+
706
+ ## Preview it in a browser
707
+
708
+ node dist/packages/cli/src/cli.js preview ${dirArg}/src/app.component.ts --out ${dirArg}/preview.html
709
+
710
+ Then open \`${dirArg}/preview.html\` in any browser. The preview is
711
+ interactive: the Get started button works, and the Light and Dark toggle
712
+ in the corner flips the whole screen between themes.
713
+
714
+ ## Keep it building while you edit
715
+
716
+ node dist/packages/cli/src/cli.js watch ${dirArg}/src/app.component.ts --out ${dirArg}/src/app.component.tsx
717
+
718
+ Watch recompiles on every save and prints OK or the diagnostics.
719
+ Press Ctrl+C to stop.
720
+
721
+ ## Check the polish
722
+
723
+ node dist/packages/cli/src/cli.js doctor ${dirArg}/src/app.component.ts
724
+
725
+ Doctor reports polish problems (raw hex colours, off-scale values,
726
+ loose text, small tap targets) with the fix for each.
727
+ `);
728
+ fs.writeFileSync(path.join(dir, '.gitignore'), 'node_modules\ndist\n');
729
+ console.log(`Created a starter Rangular project in ${dirArg}`);
730
+ console.log(`Build it: node dist/packages/cli/src/cli.js build ${dirArg}/src/app.component.ts --out ${dirArg}/src/app.component.tsx`);
731
+ }
732
+ /** `rg watch`: compile now, then recompile on every change (Stage 5). */
733
+ function startWatch(target, out, routesSpecifier) {
734
+ let watchers = [];
735
+ let timer;
736
+ let compiling = false;
737
+ let queued = false;
738
+ const closeWatchers = () => {
739
+ for (const w of watchers) {
740
+ try {
741
+ w.close();
742
+ }
743
+ catch { /* already closed */ }
744
+ }
745
+ watchers = [];
746
+ };
747
+ const arm = (files) => {
748
+ closeWatchers();
749
+ const dirs = new Set();
750
+ for (const f of files) {
751
+ const abs = path.resolve(f);
752
+ if (fs.existsSync(abs)) {
753
+ try {
754
+ watchers.push(fs.watch(abs, () => schedule()));
755
+ }
756
+ catch { /* unsupported fs */ }
757
+ }
758
+ else {
759
+ dirs.add(path.dirname(abs));
760
+ }
761
+ }
762
+ // A resolved file that does not exist yet (a template about to be
763
+ // created) is covered by watching its directory instead.
764
+ for (const d of dirs) {
765
+ if (fs.existsSync(d)) {
766
+ try {
767
+ watchers.push(fs.watch(d, () => schedule()));
768
+ }
769
+ catch { /* unsupported fs */ }
770
+ }
771
+ }
772
+ };
773
+ const compileOnce = () => {
774
+ if (compiling) {
775
+ queued = true;
776
+ return;
777
+ }
778
+ compiling = true;
779
+ try {
780
+ const stamp = new Date().toISOString();
781
+ const { tsSource, resolveFile, resolveImport, absPath, rootDir } = readComponent(target);
782
+ const result = (0, index_1.compileComponent)({ tsSource, fileName: absPath, resolveFile, resolveImport, rootDir, routesSpecifier });
783
+ for (const d of result.diagnostics)
784
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
785
+ if ((0, index_1.hasErrors)(result.diagnostics)) {
786
+ const errors = result.diagnostics.filter((d) => d.severity === 'error').length;
787
+ console.log(`[${stamp}] FAILED ${target} (${errors} error${errors === 1 ? '' : 's'})`);
788
+ }
789
+ else {
790
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
791
+ fs.writeFileSync(out, result.code);
792
+ console.log(`[${stamp}] OK ${out}`);
793
+ }
794
+ // The watch set is re-resolved after every compile, so imports or
795
+ // templates added by an edit start being watched immediately.
796
+ arm(result.files.length ? result.files : [absPath]);
797
+ }
798
+ finally {
799
+ compiling = false;
800
+ if (queued) {
801
+ queued = false;
802
+ schedule();
803
+ }
804
+ }
805
+ };
806
+ const schedule = () => {
807
+ if (timer)
808
+ clearTimeout(timer);
809
+ timer = setTimeout(compileOnce, 100);
810
+ };
811
+ compileOnce();
812
+ console.log(`Watching ${target} for changes, Ctrl+C to stop`);
813
+ process.on('SIGINT', () => {
814
+ closeWatchers();
815
+ console.log('\nWatch stopped');
816
+ process.exit(0);
817
+ });
818
+ }
819
+ function main() {
820
+ const args = process.argv.slice(2);
821
+ const command = args[0];
822
+ if (command === 'catalog') {
823
+ const outDir = option(args, '--out') ?? '.';
824
+ const catalog = (0, index_1.buildCatalog)();
825
+ fs.mkdirSync(path.resolve(outDir), { recursive: true });
826
+ const jsonPath = path.join(outDir, 'catalog.json');
827
+ const mdPath = path.join(outDir, 'catalog.md');
828
+ fs.writeFileSync(jsonPath, JSON.stringify(catalog, null, 2) + '\n');
829
+ fs.writeFileSync(mdPath, (0, index_1.renderCatalogMarkdown)(catalog));
830
+ console.log(`Wrote ${jsonPath} and ${mdPath} (${catalog.tags.length} tags, ${catalog.primitives.length} primitives, ${catalog.diagnostics.length} diagnostic codes)`);
831
+ return;
832
+ }
833
+ if (command === 'init') {
834
+ const dir = args.slice(1).find((a) => !a.startsWith('--'));
835
+ if (!dir)
836
+ fail('usage: rg init <dir> [--app]');
837
+ if (args.includes('--app'))
838
+ initApp(dir);
839
+ else
840
+ initProject(dir);
841
+ return;
842
+ }
843
+ let target = args[1];
844
+ let rest = args.slice(2);
845
+ // `rg build` on its own is the app-folder form (2026-11-21):
846
+ // no entry means src/app.component.ts, and the build branch
847
+ // defaults --out to AppRoot.tsx beside the entry. Every app
848
+ // follows that one shape, so the common case needs no
849
+ // arguments at all. An explicit entry and --out still win.
850
+ if (command === 'build' || command === 'verify' || command === 'fix') {
851
+ if (target && target.startsWith('--')) {
852
+ rest = args.slice(1);
853
+ target = '';
854
+ }
855
+ if (!target) {
856
+ const fallback = path.join('src', 'app.component.ts');
857
+ if (!fs.existsSync(path.resolve(fallback))) {
858
+ fail('no entry file given and src/app.component.ts was not found here. Run the build from your app folder, or pass the entry file: rg build <entry> --out <file>');
859
+ }
860
+ target = fallback;
861
+ }
862
+ }
863
+ if (!command || !target) {
864
+ console.log(USAGE);
865
+ process.exit(command ? 2 : 0);
866
+ }
867
+ const json = rest.includes('--json');
868
+ // Strict mode (verification fortification, 2026-11-26): warnings fail
869
+ // the run. On when --strict is passed, or when the app folder's
870
+ // rangular.json sets "strict": true (the scaffold writes it on);
871
+ // --no-strict turns a config's strict off for one run.
872
+ const strict = (() => {
873
+ if (rest.includes('--no-strict'))
874
+ return false;
875
+ if (rest.includes('--strict'))
876
+ return true;
877
+ try {
878
+ const cfg = JSON.parse(fs.readFileSync(path.resolve('rangular.json'), 'utf8'));
879
+ return cfg?.strict === true;
880
+ }
881
+ catch {
882
+ return false;
883
+ }
884
+ })();
885
+ if (command === 'ast') {
886
+ const abs = path.resolve(target);
887
+ if (!fs.existsSync(abs))
888
+ fail(`file not found: ${target}`);
889
+ const { root, diagnostics } = (0, index_1.parseTemplate)(fs.readFileSync(abs, 'utf8'));
890
+ for (const d of diagnostics)
891
+ console.error((0, index_1.formatDiagnostic)(d, abs));
892
+ console.log((0, index_1.printAst)(root));
893
+ process.exit((0, index_1.hasErrors)(diagnostics) ? 1 : 0);
894
+ }
895
+ if (command === 'watch') {
896
+ const out = option(rest, '--out');
897
+ if (!out)
898
+ fail(`--out <file> is required for 'watch'`);
899
+ const { absPath: watchAbs } = readComponent(target);
900
+ startWatch(target, out, routesSpecifierFor(watchAbs, option(rest, '--routes')));
901
+ return;
902
+ }
903
+ if (command === 'doctor') {
904
+ const { tsSource, resolveFile, resolveImport, absPath, rootDir } = readComponent(target);
905
+ const result = (0, index_1.compileComponent)({
906
+ tsSource, fileName: absPath, resolveFile, resolveImport, rootDir,
907
+ routesSpecifier: routesSpecifierFor(absPath, option(rest, '--routes')),
908
+ });
909
+ const styleTexts = (0, index_1.doctorStyleTexts)(result, absPath, (abs) => (withinRoot(rootDir, abs) && fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : undefined));
910
+ const findings = (0, index_1.runDoctor)({ result, entryFile: absPath, styleTexts });
911
+ const all = [...result.diagnostics, ...findings];
912
+ const dok = !(0, index_1.hasErrors)(all) && !(strict && all.some((d) => d.severity === 'warning'));
913
+ if (json) {
914
+ printJson({
915
+ ok: dok,
916
+ file: path.basename(target),
917
+ diagnostics: all.map(toJsonDiagnostic),
918
+ });
919
+ process.exit(dok ? 0 : 1);
920
+ }
921
+ for (const d of all)
922
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
923
+ if ((0, index_1.hasErrors)(result.diagnostics))
924
+ process.exit(1);
925
+ if (!dok) {
926
+ console.error('strict mode: warnings and doctor findings treated as errors (pass --no-strict for one run without strict)');
927
+ process.exit(1);
928
+ }
929
+ if (!findings.length) {
930
+ console.log(`doctor: clean, ${target} has no polish findings`);
931
+ }
932
+ else {
933
+ console.log(`doctor: ${findings.length} finding${findings.length === 1 ? '' : 's'} in ${target} (warnings do not fail the run)`);
934
+ }
935
+ process.exit((0, index_1.hasErrors)(findings) ? 1 : 0);
936
+ }
937
+ if (command === 'verify') {
938
+ // One gate for a whole app (verification fortification, 2026-11-26):
939
+ // strict build, doctor, the app's own tests when it has a test
940
+ // script, and a render of the root preview. Strict is the default
941
+ // here (warnings fail); --no-strict reports warnings without
942
+ // failing. The exit code is the verdict, and --json carries the
943
+ // whole result as data, so an AI loop or a CI pipeline consumes
944
+ // the gate without parsing prose.
945
+ const vStrict = !rest.includes('--no-strict');
946
+ const { tsSource, resolveFile, resolveImport, absPath, rootDir } = readComponent(target);
947
+ const result = (0, index_1.compileComponent)({
948
+ tsSource, fileName: absPath, resolveFile, resolveImport, rootDir,
949
+ routesSpecifier: routesSpecifierFor(absPath, option(rest, '--routes')),
950
+ });
951
+ const errors = result.diagnostics.filter((d) => d.severity === 'error').length;
952
+ const warnings = result.diagnostics.length - errors;
953
+ const buildOk = errors === 0 && !(vStrict && warnings > 0);
954
+ const styleTexts = (0, index_1.doctorStyleTexts)(result, absPath, (abs) => (withinRoot(rootDir, abs) && fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : undefined));
955
+ const findings = (0, index_1.runDoctor)({ result, entryFile: absPath, styleTexts });
956
+ const doctorOk = !vStrict || findings.length === 0;
957
+ let pkgDir;
958
+ for (let dir = path.dirname(absPath), i = 0; i < 4; i++, dir = path.dirname(dir)) {
959
+ if (fs.existsSync(path.join(dir, 'package.json'))) {
960
+ pkgDir = dir;
961
+ break;
962
+ }
963
+ }
964
+ let testsRan = false;
965
+ let testsOk = true;
966
+ if (pkgDir) {
967
+ try {
968
+ const pkg = JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8'));
969
+ if (pkg?.scripts?.test) {
970
+ testsRan = true;
971
+ const run = (0, node_child_process_1.spawnSync)('npm', ['test', '--silent'], { cwd: pkgDir, encoding: 'utf8', timeout: 300000 });
972
+ testsOk = run.status === 0;
973
+ }
974
+ }
975
+ catch {
976
+ testsRan = false;
977
+ }
978
+ }
979
+ let renderOk = false;
980
+ let renderSkipped = false;
981
+ let renderDetail = '';
982
+ if (result.component && result.ast && errors === 0) {
983
+ try {
984
+ const html = (0, index_1.renderPreview)(result.component, result.ast, {
985
+ children: result.children,
986
+ services: result.services,
987
+ routes: result.routes,
988
+ pipes: result.pipes,
989
+ directives: result.directives,
990
+ });
991
+ renderOk = html.length > 200;
992
+ renderDetail = `preview rendered, ${html.length} bytes`;
993
+ }
994
+ catch (e) {
995
+ renderDetail = e instanceof Error ? e.message : String(e);
996
+ }
997
+ }
998
+ else {
999
+ renderSkipped = true;
1000
+ renderDetail = 'skipped: the build has errors';
1001
+ }
1002
+ const ok = buildOk && doctorOk && testsOk && (renderOk || renderSkipped) && errors === 0;
1003
+ const all = [...result.diagnostics, ...findings];
1004
+ if (json) {
1005
+ printJson({
1006
+ ok,
1007
+ file: path.basename(target),
1008
+ strict: vStrict,
1009
+ stages: {
1010
+ build: { ok: buildOk, errors, warnings },
1011
+ doctor: { ok: doctorOk, findings: findings.length },
1012
+ tests: { ran: testsRan, ok: testsOk },
1013
+ render: { ok: renderOk, skipped: renderSkipped, detail: renderDetail },
1014
+ },
1015
+ diagnostics: all.map(toJsonDiagnostic),
1016
+ });
1017
+ process.exit(ok ? 0 : 1);
1018
+ }
1019
+ for (const d of all)
1020
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
1021
+ const line = (stage, state, detail) => `verify: ${stage.padEnd(7)} ${state.padEnd(4)} ${detail}`;
1022
+ console.log(line('build', buildOk ? 'PASS' : 'FAIL', `${errors} errors, ${warnings} warnings${vStrict ? ' (strict)' : ''}`));
1023
+ console.log(line('doctor', doctorOk ? 'PASS' : 'FAIL', `${findings.length} finding${findings.length === 1 ? '' : 's'}`));
1024
+ console.log(line('tests', testsRan ? (testsOk ? 'PASS' : 'FAIL') : 'SKIP', testsRan ? 'the app test script' : 'no test script in package.json'));
1025
+ console.log(line('render', renderSkipped ? 'SKIP' : renderOk ? 'PASS' : 'FAIL', renderDetail));
1026
+ console.log(ok ? `verify: OK, ${target} is clean` : `verify: FAIL, ${target} is not clean`);
1027
+ process.exit(ok ? 0 : 1);
1028
+ }
1029
+ if (command === 'fix') {
1030
+ // Apply the mechanical fixes (verification fortification,
1031
+ // 2026-11-26): the repairs whose outcome the compiler already
1032
+ // knows. Off-scale style values are written back snapped,
1033
+ // unsupported style properties are removed with a comment, and a
1034
+ // prop with exactly one near match in the catalog is renamed.
1035
+ // Everything else is reported, never touched. The command ends
1036
+ // with a fresh compile, and its exit code is that compile's
1037
+ // verdict, like build.
1038
+ const { tsSource, resolveFile, resolveImport, absPath, rootDir } = readComponent(target);
1039
+ const routesSpecifier = routesSpecifierFor(absPath, option(rest, '--routes'));
1040
+ const compileNow = () => (0, index_1.compileComponent)({
1041
+ tsSource: fs.readFileSync(absPath, 'utf8'), fileName: absPath, resolveFile, resolveImport, rootDir, routesSpecifier,
1042
+ });
1043
+ const applied = [];
1044
+ const first = compileNow();
1045
+ const styleTexts = (0, index_1.doctorStyleTexts)(first, absPath, (abs) => (withinRoot(rootDir, abs) && fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : undefined));
1046
+ for (const st of styleTexts) {
1047
+ const fixed = (0, index_1.fixStyleText)(st.text);
1048
+ if (!fixed.fixes.length)
1049
+ continue;
1050
+ if (st.file.endsWith('.css')) {
1051
+ fs.writeFileSync(st.file, fixed.text);
1052
+ for (const f of fixed.fixes)
1053
+ applied.push(`${f.code}: ${f.detail} [in ${path.basename(st.file)}]`);
1054
+ }
1055
+ else {
1056
+ const content = fs.readFileSync(st.file, 'utf8');
1057
+ if (content.split(st.text).length === 2) {
1058
+ fs.writeFileSync(st.file, content.replace(st.text, fixed.text));
1059
+ for (const f of fixed.fixes)
1060
+ applied.push(`${f.code}: ${f.detail} [in ${path.basename(st.file)}]`);
1061
+ }
1062
+ }
1063
+ }
1064
+ // The diagnostic's line counts lines of the template, while its
1065
+ // file names the class file, so the rename finds its line by
1066
+ // content: the first line holding both the tag and the attribute.
1067
+ const templateFile = first.component?.templateUrl
1068
+ ? path.resolve(path.dirname(absPath), first.component.templateUrl)
1069
+ : absPath;
1070
+ for (const d of first.diagnostics) {
1071
+ if (d.code !== 'GEN_UNKNOWN_PROP')
1072
+ continue;
1073
+ const near = /Did you mean '([^']+)'/.exec(d.fix ?? '');
1074
+ // The code carries two wordings: a built-in element says the
1075
+ // name "is not a prop of <tag>", a child component says it
1076
+ // "is not an @Input of <tag> (Class)". The first fix round
1077
+ // matched only the built-in wording, so a child rename was
1078
+ // named by its diagnostic and then skipped here (the 2026-11-29
1079
+ // guardrail test finding: [lable] on a child chip survived rg
1080
+ // fix while colour on a button was renamed). Both wordings
1081
+ // name the same repair, so both are read.
1082
+ const bad = /^'([^']+)' is not a prop of <([a-z-]+)>/.exec(d.message)
1083
+ ?? /^'([^']+)' is not an @Input of <([a-z-]+)>/.exec(d.message);
1084
+ if (!near || !bad || !fs.existsSync(templateFile))
1085
+ continue;
1086
+ const lines = fs.readFileSync(templateFile, 'utf8').split('\n');
1087
+ const patterns = [`[${bad[1]}]`, `[(${bad[1]})]`, `${bad[1]}=`, `${bad[1]} `, `${bad[1]}>`, `${bad[1]}/>`];
1088
+ const idx = lines.findIndex((l) => l.includes(`<${bad[2]}`) && patterns.some((p) => l.includes(p)));
1089
+ if (idx === -1)
1090
+ continue;
1091
+ // Never create a duplicate: when the element already carries
1092
+ // the suggested name in a binding form, renaming would leave
1093
+ // two bindings for one prop, so the file stays untouched and
1094
+ // the diagnostic stands. Event bindings are not props, so a
1095
+ // (name) handler on the element never counts as carrying it.
1096
+ const nearPatterns = [`[${near[1]}]`, `[(${near[1]})]`, `${near[1]}=`, `${near[1]} `, `${near[1]}>`, `${near[1]}/>`];
1097
+ if (nearPatterns.some((p) => lines[idx].includes(p)))
1098
+ continue;
1099
+ const hit = patterns.find((p) => lines[idx].includes(p));
1100
+ if (!hit)
1101
+ continue;
1102
+ lines[idx] = lines[idx].replace(hit, hit.replace(bad[1], near[1]));
1103
+ fs.writeFileSync(templateFile, lines.join('\n'));
1104
+ applied.push(`GEN_UNKNOWN_PROP: '${bad[1]}' -> '${near[1]}' [in ${path.basename(templateFile)}:${idx + 1}]`);
1105
+ }
1106
+ const after = compileNow();
1107
+ if (json) {
1108
+ printJson({
1109
+ ok: !(0, index_1.hasErrors)(after.diagnostics),
1110
+ file: path.basename(target),
1111
+ applied,
1112
+ diagnostics: after.diagnostics.map(toJsonDiagnostic),
1113
+ });
1114
+ process.exit((0, index_1.hasErrors)(after.diagnostics) ? 1 : 0);
1115
+ }
1116
+ for (const a of applied)
1117
+ console.log(`fixed: ${a}`);
1118
+ if (!applied.length)
1119
+ console.log('fix: nothing mechanical to apply');
1120
+ for (const d of after.diagnostics)
1121
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
1122
+ if ((0, index_1.hasErrors)(after.diagnostics))
1123
+ process.exit(1);
1124
+ console.log(`fix: done, ${applied.length} applied, the compile is clean`);
1125
+ return;
1126
+ }
1127
+ if (command === 'build' || command === 'preview') {
1128
+ let out = option(rest, '--out');
1129
+ if (!out && command === 'build') {
1130
+ out = path.join(path.dirname(path.resolve(target)), 'AppRoot.tsx');
1131
+ }
1132
+ if (!out)
1133
+ fail(`--out <file> is required for '${command}'`);
1134
+ const { tsSource, resolveFile, resolveImport, absPath, rootDir } = readComponent(target);
1135
+ const routesSpecifier = routesSpecifierFor(absPath, option(rest, '--routes'));
1136
+ if (command === 'build') {
1137
+ const sourceMap = rest.includes('--source-map');
1138
+ const result = (0, index_1.compileComponent)({ tsSource, fileName: absPath, resolveFile, resolveImport, sourceMap, rootDir, routesSpecifier });
1139
+ const warnCount = result.diagnostics.filter((d) => d.severity === 'warning').length;
1140
+ const ok = !(0, index_1.hasErrors)(result.diagnostics) && !(strict && warnCount > 0);
1141
+ const writeOut = () => {
1142
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
1143
+ if (sourceMap && result.sourceMap) {
1144
+ result.sourceMap.file = path.basename(out);
1145
+ const code = result.code.replace(/\n?$/, '\n') + `//# sourceMappingURL=${path.basename(out)}.map\n`;
1146
+ fs.writeFileSync(out, code);
1147
+ fs.writeFileSync(`${out}.map`, JSON.stringify(result.sourceMap, null, 2) + '\n');
1148
+ }
1149
+ else {
1150
+ fs.writeFileSync(out, result.code);
1151
+ }
1152
+ };
1153
+ if (json) {
1154
+ if (ok)
1155
+ writeOut();
1156
+ printJson({
1157
+ ok,
1158
+ file: path.basename(target),
1159
+ ...(ok ? { outFile: out } : {}),
1160
+ ...(ok && sourceMap ? { sourceMapFile: `${out}.map` } : {}),
1161
+ diagnostics: result.diagnostics.map(toJsonDiagnostic),
1162
+ });
1163
+ process.exit(ok ? 0 : 1);
1164
+ }
1165
+ for (const d of result.diagnostics)
1166
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
1167
+ if (!ok) {
1168
+ if (strict && warnCount > 0 && !(0, index_1.hasErrors)(result.diagnostics))
1169
+ console.error(`strict mode: ${warnCount} warning${warnCount === 1 ? '' : 's'} treated as errors (pass --no-strict for one run without strict)`);
1170
+ process.exit(1);
1171
+ }
1172
+ writeOut();
1173
+ console.log(`Wrote ${out} (${result.code.split('\n').length} lines)`);
1174
+ return;
1175
+ }
1176
+ // preview, through the full compiler so child components and services
1177
+ // resolved from imports render exactly as they compile (Stage 3).
1178
+ const compiled = (0, index_1.compileComponent)({ tsSource, fileName: absPath, resolveFile, resolveImport, rootDir, routesSpecifier });
1179
+ const allDiags = compiled.diagnostics;
1180
+ if (!compiled.component || !compiled.ast || (0, index_1.hasErrors)(allDiags)) {
1181
+ if (json) {
1182
+ printJson({ ok: false, file: path.basename(target), diagnostics: allDiags.map(toJsonDiagnostic) });
1183
+ process.exit(1);
1184
+ }
1185
+ for (const d of allDiags)
1186
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
1187
+ process.exit(1);
1188
+ }
1189
+ const component = compiled.component;
1190
+ const html = (0, index_1.renderPreview)(component, compiled.ast, {
1191
+ children: compiled.children,
1192
+ services: compiled.services,
1193
+ routes: compiled.routes,
1194
+ pipes: compiled.pipes,
1195
+ directives: compiled.directives,
1196
+ });
1197
+ if (json) {
1198
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
1199
+ fs.writeFileSync(out, html);
1200
+ printJson({
1201
+ ok: true,
1202
+ file: path.basename(target),
1203
+ outFile: out,
1204
+ diagnostics: allDiags.map(toJsonDiagnostic),
1205
+ });
1206
+ process.exit(0);
1207
+ }
1208
+ for (const d of allDiags)
1209
+ console.error((0, index_1.formatDiagnostic)(d, absPath));
1210
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
1211
+ fs.writeFileSync(out, html);
1212
+ console.log(`Wrote ${out} (preview for ${component.selector ?? component.className})`);
1213
+ return;
1214
+ }
1215
+ fail(`unknown command '${command}'`);
1216
+ }
1217
+ main();