@marktiderman/genesis-cli 1.13.2 → 1.15.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.
package/dist/vite.js CHANGED
@@ -1,28 +1,699 @@
1
- import * as path14 from 'path';
1
+ import * as path18 from 'path';
2
2
  import { spawnSync } from 'child_process';
3
- import { existsSync, readFileSync, statSync, readdirSync, realpathSync, lstatSync } from 'fs';
3
+ import { existsSync, readFileSync, statSync, realpathSync, readdirSync, lstatSync } from 'fs';
4
4
  import { builtinModules, createRequire } from 'module';
5
5
  import 'crypto';
6
6
  import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
7
7
  import { pathToFileURL } from 'url';
8
+ import 'jiti';
8
9
 
9
- // src/vite.ts
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __esm = (fn, res) => function __init() {
13
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+
20
+ // src/introspect/catalog-text.ts
21
+ function tokenize(tree) {
22
+ const tokens = [];
23
+ let i = 0;
24
+ while (i < tree.length) {
25
+ const ch = tree[i];
26
+ if (ch === " " || ch === "\n" || ch === " ") {
27
+ i++;
28
+ } else if (ch === "{" || ch === "(") {
29
+ tokens.push({ kind: "open", char: ch });
30
+ i++;
31
+ } else if (ch === "}" || ch === ")") {
32
+ tokens.push({ kind: "close", char: ch });
33
+ i++;
34
+ } else {
35
+ let text = "";
36
+ while (i < tree.length) {
37
+ const c = tree[i];
38
+ if (c === "\\" && i + 1 < tree.length) {
39
+ text += tree[i + 1];
40
+ i += 2;
41
+ continue;
42
+ }
43
+ if (c === " " || c === "\n" || c === " " || c === "{" || c === "}" || c === "(" || c === ")") break;
44
+ text += c;
45
+ i++;
46
+ }
47
+ tokens.push({ kind: "atom", text });
48
+ }
49
+ }
50
+ return tokens;
51
+ }
52
+ function viewColumnOrigins(evAction) {
53
+ const tokens = tokenize(evAction);
54
+ let depth = 0;
55
+ let start = -1;
56
+ for (let i = 0; i < tokens.length; i++) {
57
+ const t = tokens[i];
58
+ if (t.kind === "open") depth++;
59
+ else if (t.kind === "close") depth--;
60
+ else if (depth === 2 && t.text === ":targetList") {
61
+ start = i + 1;
62
+ break;
63
+ }
64
+ }
65
+ if (start < 0) return [];
66
+ const origins = [];
67
+ depth = 2;
68
+ let entry = null;
69
+ let lastKey = null;
70
+ for (let i = start; i < tokens.length; i++) {
71
+ const t = tokens[i];
72
+ if (t.kind === "open") {
73
+ depth++;
74
+ if (depth === 4 && t.char === "{") {
75
+ entry = /* @__PURE__ */ new Map();
76
+ lastKey = null;
77
+ }
78
+ continue;
79
+ }
80
+ if (t.kind === "close") {
81
+ if (depth === 4 && entry) {
82
+ const relation = Number(entry.get(":resorigtbl"));
83
+ const column = Number(entry.get(":resorigcol"));
84
+ const position = Number(entry.get(":resno"));
85
+ const name = entry.get(":resname") ?? "";
86
+ if (entry.get(":resjunk") !== "true" && position > 0 && relation > 0 && column > 0) {
87
+ origins.push({ position, name, relation, column });
88
+ }
89
+ entry = null;
90
+ }
91
+ depth--;
92
+ if (depth <= 2) break;
93
+ continue;
94
+ }
95
+ if (depth !== 4 || !entry) continue;
96
+ if (t.text === "TARGETENTRY") continue;
97
+ if (t.text.startsWith(":")) lastKey = t.text;
98
+ else if (lastKey) {
99
+ entry.set(lastKey, t.text);
100
+ lastKey = null;
101
+ }
102
+ }
103
+ return origins;
104
+ }
105
+ function unwrap(expr) {
106
+ let s = expr.trim();
107
+ for (; ; ) {
108
+ if (!s.startsWith("(") || !s.endsWith(")")) return s;
109
+ let depth = 0;
110
+ let inQuote = false;
111
+ let wrapsAll = true;
112
+ for (let i = 0; i < s.length; i++) {
113
+ const c = s[i];
114
+ if (c === "'") inQuote = !inQuote;
115
+ if (inQuote) continue;
116
+ if (c === "(") depth++;
117
+ else if (c === ")") {
118
+ depth--;
119
+ if (depth === 0 && i < s.length - 1) {
120
+ wrapsAll = false;
121
+ break;
122
+ }
123
+ }
124
+ }
125
+ if (!wrapsAll) return s;
126
+ s = s.slice(1, -1).trim();
127
+ }
128
+ }
129
+ function splitTopLevel(expr, separator) {
130
+ const parts = [];
131
+ let depth = 0;
132
+ let inQuote = false;
133
+ let from = 0;
134
+ for (let i = 0; i < expr.length; i++) {
135
+ const c = expr[i];
136
+ if (c === "'") inQuote = !inQuote;
137
+ if (inQuote) continue;
138
+ if (c === "(") depth++;
139
+ else if (c === ")") depth--;
140
+ else if (depth === 0 && expr.startsWith(separator, i)) {
141
+ parts.push(expr.slice(from, i));
142
+ from = i + separator.length;
143
+ i += separator.length - 1;
144
+ }
145
+ }
146
+ parts.push(expr.slice(from));
147
+ return parts;
148
+ }
149
+ function escapeRegExp(s) {
150
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151
+ }
152
+ function checkEnumValues(definition, column) {
153
+ const outer = /^CHECK \((.*)\)(?: NOT VALID)?$/s.exec(definition.trim());
154
+ if (!outer) return void 0;
155
+ const ident = `(?:${escapeRegExp(column)}|${escapeRegExp(`"${column.replace(/"/g, '""')}"`)})`;
156
+ const ref = String.raw`(?:${ident}|\(${ident}\)${CAST})`;
157
+ let body = unwrap(outer[1]);
158
+ const parts = splitTopLevel(body, " OR ");
159
+ if (parts.length === 2) {
160
+ const isNull = new RegExp(`^${ref} IS NULL$`);
161
+ const nullAt = parts.findIndex((p) => isNull.test(unwrap(p)));
162
+ if (nullAt < 0) return void 0;
163
+ body = unwrap(parts[1 - nullAt]);
164
+ } else if (parts.length !== 1) {
165
+ return void 0;
166
+ }
167
+ const single = new RegExp(`^${ref} = ${LITERAL}$`).exec(body);
168
+ if (single) return [single[1].replace(/''/g, "'")];
169
+ const any = new RegExp(String.raw`^${ref} = ANY \((.*)\)$`).exec(body);
170
+ if (!any) return void 0;
171
+ const list = /^\(?ARRAY\[(.*?)\](?:\)(?:::[a-z][a-z ]*(?:\(\d+\))?\[\]))?$/s.exec(unwrap(any[1]));
172
+ if (!list) return void 0;
173
+ const items = splitTopLevel(list[1], ", ");
174
+ const values = [];
175
+ const literal = new RegExp(`^${LITERAL}$`);
176
+ for (const item of items) {
177
+ const m = literal.exec(item.trim());
178
+ if (!m) return void 0;
179
+ values.push(m[1].replace(/''/g, "'"));
180
+ }
181
+ return values.length ? values : void 0;
182
+ }
183
+ var CAST, LITERAL;
184
+ var init_catalog_text = __esm({
185
+ "src/introspect/catalog-text.ts"() {
186
+ CAST = String.raw`::[a-z][a-z ]*(?:\(\d+(?:,\d+)?\))?`;
187
+ LITERAL = String.raw`'((?:[^']|'')*)'${CAST}`;
188
+ }
189
+ });
190
+
191
+ // src/introspect/comments.ts
192
+ function parse(comment, keys, where2) {
193
+ if (!comment) return {};
194
+ const at = comment.indexOf(MARKER);
195
+ if (at < 0) return { description: comment.trim() || void 0 };
196
+ const description = comment.slice(0, at).trim() || void 0;
197
+ const raw = comment.slice(at + MARKER.length).trim();
198
+ let value;
199
+ try {
200
+ value = JSON.parse(raw);
201
+ } catch {
202
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
203
+ }
204
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
205
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
206
+ }
207
+ const settings = {};
208
+ for (const [key2, v] of Object.entries(value)) {
209
+ const kind = keys[key2];
210
+ if (!kind) {
211
+ throw new CommentSettingsError(`${where2}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
212
+ }
213
+ if (typeof v !== kind) throw new CommentSettingsError(`${where2}: ${MARKER} "${key2}" must be a ${kind}.`);
214
+ settings[key2] = v;
215
+ }
216
+ return {
217
+ ...description ? { description } : {},
218
+ ...Object.keys(settings).length ? { settings } : {}
219
+ };
220
+ }
221
+ function parseTableComment(comment, table) {
222
+ return parse(comment, TABLE_KEYS, table);
223
+ }
224
+ function parseColumnComment(comment, column) {
225
+ return parse(comment, FIELD_KEYS, column);
226
+ }
227
+ var MARKER, TABLE_KEYS, FIELD_KEYS, CommentSettingsError;
228
+ var init_comments = __esm({
229
+ "src/introspect/comments.ts"() {
230
+ MARKER = "@genesis";
231
+ TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string" };
232
+ FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
233
+ CommentSettingsError = class extends Error {
234
+ };
235
+ }
236
+ });
237
+
238
+ // src/introspect/model.ts
239
+ function storageTypeOf(dbType) {
240
+ const t = dbType.toLowerCase().replace(/\[\]$/, "");
241
+ if (/^(smallint|integer|bigint|int2|int4|int8|real|double precision|float4|float8|numeric|decimal|money)\b/.test(t)) {
242
+ return "number";
243
+ }
244
+ if (t === "boolean" || t === "bool") return "boolean";
245
+ if (/^(date|timestamp|timestamptz|time|timetz|interval)\b/.test(t)) return "datetime";
246
+ if (t === "json" || t === "jsonb") return "json";
247
+ return "string";
248
+ }
249
+ function qualifiedName(schema, table) {
250
+ const part = (p) => /[."]/.test(p) ? `"${p.replace(/"/g, '""')}"` : p;
251
+ return `${part(schema)}.${part(table)}`;
252
+ }
253
+ var init_model = __esm({
254
+ "src/introspect/model.ts"() {
255
+ }
256
+ });
257
+
258
+ // src/introspect/postgres.ts
259
+ function where(sql, scope) {
260
+ return "schemas" in scope ? sql`n.nspname = any(${scope.schemas})` : sql`c.oid = any(${scope.oids}::oid[])`;
261
+ }
262
+ async function readRelations(sql, scope, into) {
263
+ const columns = await sql`
264
+ select c.oid::text as oid, c.relkind::text as relkind, n.nspname as schema, c.relname as table,
265
+ obj_description(c.oid, 'pg_class') as table_comment,
266
+ a.attnum::int as attnum,
267
+ a.attname as column,
268
+ format_type(a.atttypid, a.atttypmod) as db_type,
269
+ t.typcategory = 'A' as is_array,
270
+ a.attnotnull as not_null,
271
+ (a.atthasdef or a.attidentity <> '') as has_default,
272
+ (a.attgenerated <> '' or a.attidentity <> '') as generated,
273
+ (select array_agg(e.enumlabel::text order by e.enumsortorder)
274
+ from pg_enum e
275
+ where e.enumtypid = case when t.typcategory = 'A' then t.typelem else t.oid end) as enum_values,
276
+ col_description(c.oid, a.attnum) as column_comment
277
+ from pg_class c
278
+ join pg_namespace n on n.oid = c.relnamespace
279
+ join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
280
+ join pg_type t on t.oid = a.atttypid
281
+ where c.relkind in ('r', 'p', 'v', 'm', 'f')
282
+ and ${where(sql, scope)}
283
+ order by n.nspname, c.relname, a.attnum`;
284
+ const keys = await sql`
285
+ select c.oid::text as oid, array_agg(k.attnum::int order by k.ord) as columns
286
+ from pg_constraint con
287
+ join pg_class c on c.oid = con.conrelid
288
+ join pg_namespace n on n.oid = c.relnamespace
289
+ cross join lateral unnest(con.conkey) with ordinality as k(attnum, ord)
290
+ where con.contype = 'p' and ${where(sql, scope)}
291
+ group by c.oid`;
292
+ const links = await sql`
293
+ select c.oid::text as oid, con.conkey[1]::int as attnum,
294
+ rn.nspname as ref_schema, rc.relname as ref_table, ra.attname as ref_column
295
+ from pg_constraint con
296
+ join pg_class c on c.oid = con.conrelid
297
+ join pg_namespace n on n.oid = c.relnamespace
298
+ join pg_class rc on rc.oid = con.confrelid
299
+ join pg_namespace rn on rn.oid = rc.relnamespace
300
+ join pg_attribute ra on ra.attrelid = rc.oid and ra.attnum = con.confkey[1]
301
+ where con.contype = 'f' and array_length(con.conkey, 1) = 1
302
+ and ${where(sql, scope)}`;
303
+ const checks = await sql`
304
+ select c.oid::text as oid, con.conkey[1]::int as attnum, a.attname as column,
305
+ pg_get_constraintdef(con.oid) as definition
306
+ from pg_constraint con
307
+ join pg_class c on c.oid = con.conrelid
308
+ join pg_namespace n on n.oid = c.relnamespace
309
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
310
+ where con.contype = 'c' and array_length(con.conkey, 1) = 1
311
+ and ${where(sql, scope)}
312
+ order by con.conname`;
313
+ const views = await sql`
314
+ select c.oid::text as oid, r.ev_action::text as ev_action
315
+ from pg_class c
316
+ join pg_namespace n on n.oid = c.relnamespace
317
+ join pg_rewrite r on r.ev_class = c.oid and r.rulename = '_RETURN'
318
+ where c.relkind = 'v'
319
+ and (pg_relation_is_updatable(c.oid, false) & 20) = 20
320
+ and not exists (select 1 from pg_rewrite o where o.ev_class = c.oid and o.rulename <> '_RETURN')
321
+ and ${where(sql, scope)}`;
322
+ const added = [];
323
+ for (const row of columns) {
324
+ let relation = into.get(row.oid);
325
+ if (!relation) {
326
+ const name = qualifiedName(row.schema, row.table);
327
+ const comment2 = parseTableComment(row.table_comment, name);
328
+ relation = {
329
+ oid: row.oid,
330
+ table: {
331
+ name,
332
+ schema: row.schema,
333
+ table: row.table,
334
+ key: [],
335
+ columns: [],
336
+ ...comment2.description ? { description: comment2.description } : {},
337
+ ...comment2.settings ? { settings: comment2.settings } : {}
338
+ },
339
+ columns: /* @__PURE__ */ new Map(),
340
+ key: []
341
+ };
342
+ into.set(row.oid, relation);
343
+ added.push(row.oid);
344
+ }
345
+ const comment = parseColumnComment(row.column_comment, `${relation.table.name}.${row.column}`);
346
+ const column = {
347
+ name: row.column,
348
+ dbType: row.db_type,
349
+ type: storageTypeOf(row.db_type),
350
+ array: row.is_array,
351
+ nullable: !row.not_null,
352
+ // A view's columns always read as nullable: unknown until traced to a table.
353
+ ...row.relkind === "v" || row.relkind === "m" ? { nullableUnknown: true } : {},
354
+ hasDefault: row.has_default,
355
+ generated: row.generated,
356
+ ...row.enum_values ? { enumValues: row.enum_values } : {},
357
+ ...comment.description ? { description: comment.description } : {},
358
+ ...comment.settings ? { settings: comment.settings } : {}
359
+ };
360
+ relation.table.columns.push(column);
361
+ relation.columns.set(row.attnum, column);
362
+ }
363
+ for (const k of keys) {
364
+ const relation = into.get(k.oid);
365
+ if (relation) relation.key = k.columns;
366
+ }
367
+ for (const l of links) {
368
+ const column = into.get(l.oid)?.columns.get(l.attnum);
369
+ if (column) column.references = { resource: qualifiedName(l.ref_schema, l.ref_table), field: l.ref_column };
370
+ }
371
+ const listed = /* @__PURE__ */ new Map();
372
+ for (const check of checks) {
373
+ const column = into.get(check.oid)?.columns.get(check.attnum);
374
+ if (!column || column.array) continue;
375
+ const values = checkEnumValues(check.definition, check.column);
376
+ if (!values) continue;
377
+ const before = listed.get(column);
378
+ listed.set(column, before ? before.filter((v) => values.includes(v)) : values);
379
+ }
380
+ for (const [column, values] of listed) {
381
+ const allowed = column.enumValues ? column.enumValues.filter((v) => values.includes(v)) : values;
382
+ if (allowed.length > 0) column.enumValues = allowed;
383
+ }
384
+ for (const view of views) {
385
+ const relation = into.get(view.oid);
386
+ if (!relation) continue;
387
+ relation.origins = /* @__PURE__ */ new Map();
388
+ for (const origin of viewColumnOrigins(view.ev_action)) {
389
+ if (relation.columns.has(origin.position)) {
390
+ relation.origins.set(origin.position, { relation: String(origin.relation), column: origin.column });
391
+ }
392
+ }
393
+ }
394
+ return added;
395
+ }
396
+ function inherit(own, source) {
397
+ const settings = source.settings || own.settings ? { ...source.settings, ...own.settings } : void 0;
398
+ const description = own.description ?? source.description;
399
+ const both = own.enumValues && source.enumValues ? own.enumValues.filter((v) => source.enumValues.includes(v)) : void 0;
400
+ const enumValues = both?.length ? both : own.enumValues ?? source.enumValues;
401
+ return {
402
+ name: own.name,
403
+ dbType: own.dbType,
404
+ type: own.type,
405
+ array: own.array,
406
+ nullable: source.nullable,
407
+ ...source.nullableUnknown ? { nullableUnknown: true } : {},
408
+ hasDefault: own.hasDefault || source.hasDefault,
409
+ generated: source.generated,
410
+ ...enumValues ? { enumValues } : {},
411
+ ...source.references ? { references: source.references } : {},
412
+ ...description ? { description } : {},
413
+ ...settings ? { settings } : {}
414
+ };
415
+ }
416
+ function resolveViews(relations) {
417
+ const done = /* @__PURE__ */ new Set();
418
+ const resolve15 = (relation, depth) => {
419
+ if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
420
+ done.add(relation.oid);
421
+ const sources = new Set([...relation.origins.values()].map((o) => o.relation));
422
+ if (sources.size !== 1) return;
423
+ const source = relations.get([...sources][0]);
424
+ if (!source) return;
425
+ resolve15(source, depth + 1);
426
+ const viewAttnumOf = /* @__PURE__ */ new Map();
427
+ for (const [attnum, origin] of relation.origins) {
428
+ const own = relation.columns.get(attnum);
429
+ const from = source.columns.get(origin.column);
430
+ if (!own || !from) continue;
431
+ const merged = inherit(own, from);
432
+ relation.columns.set(attnum, merged);
433
+ relation.table.columns[relation.table.columns.indexOf(own)] = merged;
434
+ if (!viewAttnumOf.has(origin.column)) viewAttnumOf.set(origin.column, attnum);
435
+ }
436
+ if (relation.key.length === 0 && source.key.length > 0 && source.key.every((k) => viewAttnumOf.has(k))) {
437
+ relation.key = source.key.map((k) => viewAttnumOf.get(k));
438
+ }
439
+ const theirs = source.table.settings;
440
+ const viewColumns = new Set(relation.table.columns.map((c) => c.name));
441
+ const inherited = {
442
+ ...theirs?.noun ? { noun: theirs.noun } : {},
443
+ ...theirs?.nounPlural ? { nounPlural: theirs.nounPlural } : {},
444
+ ...theirs?.labelField && viewColumns.has(theirs.labelField) ? { labelField: theirs.labelField } : {}
445
+ };
446
+ if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
447
+ };
448
+ for (const relation of relations.values()) resolve15(relation, 0);
449
+ }
450
+ async function introspectPostgres(sql, schemas) {
451
+ const relations = /* @__PURE__ */ new Map();
452
+ const wanted = await readRelations(sql, { schemas: [...schemas] }, relations);
453
+ for (let depth = 0; depth < MAX_VIEW_DEPTH; depth++) {
454
+ const missing = /* @__PURE__ */ new Set();
455
+ for (const relation of relations.values()) {
456
+ for (const origin of relation.origins?.values() ?? []) {
457
+ if (!relations.has(origin.relation)) missing.add(origin.relation);
458
+ }
459
+ }
460
+ if (missing.size === 0) break;
461
+ const added = await readRelations(sql, { oids: [...missing].sort() }, relations);
462
+ if (added.length === 0) break;
463
+ }
464
+ resolveViews(relations);
465
+ return wanted.map((oid) => {
466
+ const relation = relations.get(oid);
467
+ return { ...relation.table, key: relation.key.map((attnum) => relation.columns.get(attnum).name) };
468
+ });
469
+ }
470
+ var MAX_VIEW_DEPTH;
471
+ var init_postgres = __esm({
472
+ "src/introspect/postgres.ts"() {
473
+ init_catalog_text();
474
+ init_comments();
475
+ init_model();
476
+ MAX_VIEW_DEPTH = 8;
477
+ }
478
+ });
479
+
480
+ // src/introspect/openapi.ts
481
+ function clean(description) {
482
+ if (!description) return void 0;
483
+ return description.replace(NOTES, "").trim() || void 0;
484
+ }
485
+ function introspectOpenApi(doc, schema = "public") {
486
+ const definitions = doc.definitions ?? doc.components?.schemas;
487
+ if (!definitions) throw new Error("This OpenAPI document has no definitions. Is it a PostgREST (Supabase /rest/v1/) spec?");
488
+ return Object.keys(definitions).sort().map((tableName) => {
489
+ const def = definitions[tableName];
490
+ const name = qualifiedName(schema, tableName);
491
+ const required = new Set(def.required ?? []);
492
+ const key2 = [];
493
+ const columns = Object.entries(def.properties ?? {}).map(([column, prop]) => {
494
+ if (PK.test(prop.description ?? "")) key2.push(column);
495
+ const fk = FK.exec(prop.description ?? "");
496
+ const isArray = prop.type === "array";
497
+ const format = (isArray ? prop.items?.format : prop.format) ?? prop.type ?? "text";
498
+ const dbType = isArray ? `${format}[]` : format;
499
+ const comment2 = parseColumnComment(clean(prop.description), `${name}.${column}`);
500
+ return {
501
+ name: column,
502
+ dbType,
503
+ type: storageTypeOf(format),
504
+ array: isArray,
505
+ // PostgREST (v9 on) lists every NOT NULL column as required, with or
506
+ // without a default (`filter (not . colNullable)` in its OpenAPI.hs).
507
+ nullable: !required.has(column),
508
+ hasDefault: prop.default !== void 0,
509
+ generated: false,
510
+ ...prop.enum ? { enumValues: prop.enum.map(String) } : {},
511
+ ...fk ? { references: { resource: qualifiedName(schema, fk[1]), field: fk[2] } } : {},
512
+ ...comment2.description ? { description: comment2.description } : {},
513
+ ...comment2.settings ? { settings: comment2.settings } : {}
514
+ };
515
+ });
516
+ const comment = parseTableComment(def.description, name);
517
+ return {
518
+ name,
519
+ schema,
520
+ table: tableName,
521
+ key: key2,
522
+ columns,
523
+ ...comment.description ? { description: comment.description } : {},
524
+ ...comment.settings ? { settings: comment.settings } : {}
525
+ };
526
+ });
527
+ }
528
+ var PK, FK, NOTES;
529
+ var init_openapi = __esm({
530
+ "src/introspect/openapi.ts"() {
531
+ init_comments();
532
+ init_model();
533
+ PK = /<pk\/>/;
534
+ FK = /<fk table='([^']+)' column='([^']+)'\/>/;
535
+ NOTES = /\s*Note:\s*This is a (?:Primary|Foreign) Key[^<]*<(?:pk|fk)[^>]*\/>/g;
536
+ }
537
+ });
538
+
539
+ // src/introspect/emit.ts
540
+ function quote(value) {
541
+ return JSON.stringify(value);
542
+ }
543
+ function propKey(name) {
544
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quote(name);
545
+ }
546
+ function typeName(table) {
547
+ const pascal = `${table.schema}_${table.table}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("");
548
+ return `${/^[0-9]/.test(pascal) ? "T" : ""}${pascal}Row`;
549
+ }
550
+ function constName(table) {
551
+ const row = typeName(table).replace(/Row$/, "");
552
+ return row[0].toLowerCase() + row.slice(1);
553
+ }
554
+ function tsType(column) {
555
+ const base = column.enumValues?.length ? column.enumValues.map(quote).join(" | ") : TS_TYPE[column.type];
556
+ const element = column.array ? base.includes("|") ? `(${base})[]` : `${base}[]` : base;
557
+ return column.nullable ? `${element} | null` : element;
558
+ }
559
+ function field(column, indent) {
560
+ const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
561
+ if (column.array) parts.push("array: true");
562
+ if (!column.nullableUnknown) parts.push(column.nullable ? "nullable: true" : "nullable: false");
563
+ if (column.nullable || column.hasDefault || column.generated) parts.push("optional: true");
564
+ if (column.hasDefault) parts.push("hasDefault: true");
565
+ if (column.generated) parts.push("generated: true");
566
+ if (column.enumValues) parts.push(`enumValues: [${column.enumValues.map(quote).join(", ")}]`);
567
+ if (column.references) {
568
+ parts.push(`references: { resource: ${quote(column.references.resource)}, field: ${quote(column.references.field)} }`);
569
+ }
570
+ const label = column.settings?.label;
571
+ const description = column.settings?.description ?? column.description;
572
+ if (label) parts.push(`label: ${quote(label)}`);
573
+ if (description) parts.push(`description: ${quote(description)}`);
574
+ if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
575
+ if (column.settings?.readonly) parts.push("readOnly: true");
576
+ if (column.settings?.sensitive) parts.push("sensitive: true");
577
+ return `${indent}{ ${parts.join(", ")} },`;
578
+ }
579
+ function emitContracts(tables, options) {
580
+ const sorted = [...tables].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
581
+ const seen = /* @__PURE__ */ new Map();
582
+ for (const table of sorted) {
583
+ const id = typeName(table);
584
+ const other = seen.get(id);
585
+ if (other) throw new EmitError(`${other} and ${table.name} would both be named ${id}; rename one, or introspect them separately.`);
586
+ seen.set(id, table.name);
587
+ const labelField = table.settings?.labelField;
588
+ if (labelField && !table.columns.some((c) => c.name === labelField)) {
589
+ throw new EmitError(`${table.name}: @genesis labelField "${labelField}" isn't one of its columns.`);
590
+ }
591
+ }
592
+ const out = [
593
+ "// Generated by `genesis introspect` \u2014 do not edit by hand.",
594
+ `// Source: ${options.source}`,
595
+ "//",
596
+ "// Re-run `genesis introspect` after a schema change and review the diff.",
597
+ "// Labels, widgets and descriptions come from `@genesis {...}` settings in",
598
+ "// table and column comments. Pass `contracts` to createStudioHandler: it",
599
+ "// wins over discovery for presentation, while types, keys and every",
600
+ "// permission still come from the live database. Each contract goes through",
601
+ "// defineResource, so a bad @genesis setting fails to compile and views read the",
602
+ "// row type with RowOf<typeof contract>.",
603
+ "",
604
+ 'import { defineResource } from "@marktiderman/genesis-core";',
605
+ ""
606
+ ];
607
+ for (const table of sorted) {
608
+ const row = typeName(table);
609
+ out.push(`/** \`${table.name}\`. */`);
610
+ out.push(`export const ${constName(table)} = defineResource<${row}>()({`);
611
+ out.push(` name: ${quote(table.name)},`);
612
+ out.push(` key: ${table.key.length === 1 ? quote(table.key[0]) : `[${table.key.map(quote).join(", ")}]`},`);
613
+ if (table.settings?.label) out.push(` label: ${quote(table.settings.label)},`);
614
+ if (table.settings?.labelField) out.push(` labelField: ${quote(table.settings.labelField)},`);
615
+ if (table.settings?.noun) out.push(` noun: ${quote(table.settings.noun)},`);
616
+ if (table.settings?.nounPlural) out.push(` nounPlural: ${quote(table.settings.nounPlural)},`);
617
+ const description = table.settings?.description ?? table.description;
618
+ if (description) out.push(` description: ${quote(description)},`);
619
+ out.push(" fields: [");
620
+ for (const column of table.columns) out.push(field(column, " "));
621
+ out.push(" ],");
622
+ out.push("});", "");
623
+ }
624
+ out.push("export const contracts = {");
625
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${constName(table)},`);
626
+ out.push("} as const;", "");
627
+ out.push("/** Every resource in this contract, `schema.table`. */");
628
+ out.push("export type GenesisResource = keyof typeof contracts;", "");
629
+ for (const table of sorted) {
630
+ out.push(`/** A row of \`${table.name}\`, as the studio handler returns it. */`);
631
+ out.push(`export type ${typeName(table)} = {`);
632
+ for (const column of table.columns) out.push(` ${propKey(column.name)}: ${tsType(column)};`);
633
+ out.push("};", "");
634
+ out.push(`/** The field names of \`${table.name}\`. */`);
635
+ out.push(`export type ${typeName(table).replace(/Row$/, "Field")} = keyof ${typeName(table)};`, "");
636
+ }
637
+ out.push("/** Row types by resource. */");
638
+ out.push("export interface GenesisRows {");
639
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${typeName(table)};`);
640
+ out.push("}", "");
641
+ return out.join("\n");
642
+ }
643
+ var TS_TYPE, EmitError;
644
+ var init_emit = __esm({
645
+ "src/introspect/emit.ts"() {
646
+ TS_TYPE = {
647
+ string: "string",
648
+ number: "number",
649
+ boolean: "boolean",
650
+ // The studio handler sends dates and timestamps as Postgres text, exactly.
651
+ datetime: "string",
652
+ json: "unknown"
653
+ };
654
+ EmitError = class extends Error {
655
+ name = "EmitError";
656
+ };
657
+ }
658
+ });
659
+
660
+ // src/introspect/index.ts
661
+ var introspect_exports = {};
662
+ __export(introspect_exports, {
663
+ CommentSettingsError: () => CommentSettingsError,
664
+ EmitError: () => EmitError,
665
+ emitContracts: () => emitContracts,
666
+ introspectOpenApi: () => introspectOpenApi,
667
+ introspectPostgres: () => introspectPostgres,
668
+ parseColumnComment: () => parseColumnComment,
669
+ parseTableComment: () => parseTableComment,
670
+ qualifiedName: () => qualifiedName
671
+ });
672
+ var init_introspect = __esm({
673
+ "src/introspect/index.ts"() {
674
+ init_postgres();
675
+ init_openapi();
676
+ init_emit();
677
+ init_comments();
678
+ init_model();
679
+ }
680
+ });
10
681
  var BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
11
682
  function buildCommands(root, config) {
12
683
  if (config.build) return config.build;
13
- const pkgFile = path14.join(root, "package.json");
684
+ const pkgFile = path18.join(root, "package.json");
14
685
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
15
686
  const pm = packageManager(root);
16
687
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
17
688
  }
18
689
  function packageManager(root) {
19
- let dir = path14.resolve(root);
690
+ let dir = path18.resolve(root);
20
691
  for (; ; ) {
21
- if (existsSync(path14.join(dir, "pnpm-lock.yaml"))) return "pnpm";
22
- if (existsSync(path14.join(dir, "bun.lock")) || existsSync(path14.join(dir, "bun.lockb"))) return "bun";
23
- if (existsSync(path14.join(dir, "yarn.lock"))) return "yarn";
24
- if (existsSync(path14.join(dir, "package-lock.json"))) return "npm";
25
- const parent = path14.dirname(dir);
692
+ if (existsSync(path18.join(dir, "pnpm-lock.yaml"))) return "pnpm";
693
+ if (existsSync(path18.join(dir, "bun.lock")) || existsSync(path18.join(dir, "bun.lockb"))) return "bun";
694
+ if (existsSync(path18.join(dir, "yarn.lock"))) return "yarn";
695
+ if (existsSync(path18.join(dir, "package-lock.json"))) return "npm";
696
+ const parent = path18.dirname(dir);
26
697
  if (parent === dir) return "npm";
27
698
  dir = parent;
28
699
  }
@@ -118,44 +789,61 @@ var KNOWN = /* @__PURE__ */ new Set([
118
789
  "supabase",
119
790
  "packages",
120
791
  "routesDir",
792
+ "packageRules",
793
+ "ratchet",
794
+ "contracts",
121
795
  "$schema",
122
796
  "$comment"
123
797
  ]);
124
798
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
125
- var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
799
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
800
+ var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
801
+ var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
802
+ var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
126
803
  var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
127
804
  var PACK_KEYS = {
128
805
  native: { routerRoot: "path" },
129
806
  supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
130
807
  packages: { base: "string" }
131
808
  };
132
- function appPath(v, where, fail) {
133
- if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
134
- if (path14.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
135
- const norm = path14.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
136
- if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
809
+ function appPath(v, where2, fail) {
810
+ if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
811
+ if (path18.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
812
+ const norm = path18.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
813
+ if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
137
814
  return norm;
138
815
  }
139
816
  function loadConfig(root, configPath) {
140
817
  if (configPath) {
141
- const file = path14.resolve(root, configPath);
818
+ const file = path18.resolve(root, configPath);
142
819
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
143
820
  const json = readJson(file);
144
- const block = path14.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
145
- return { config: validateConfig(block ?? {}, file), file, dir: path14.dirname(file) };
821
+ const block = path18.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
822
+ return { config: validateConfig(block ?? {}, file), file, dir: path18.dirname(file) };
146
823
  }
147
- const own = path14.join(root, "genesis.config.json");
824
+ const own = path18.join(root, "genesis.config.json");
148
825
  if (existsSync(own)) {
149
826
  const block = readGenesisConfig(root)?.raw.doctor;
150
827
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
151
828
  }
152
- const pkg = path14.join(root, "package.json");
829
+ const pkg = path18.join(root, "package.json");
153
830
  if (existsSync(pkg)) {
154
831
  const block = readJson(pkg)?.genesis?.doctor;
155
- if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
832
+ if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
156
833
  }
157
834
  return { config: {}, file: null, dir: root };
158
835
  }
836
+ function doctorBlock(json, file, explicit) {
837
+ const j = json;
838
+ if (path18.basename(file) === "package.json") return j?.genesis?.doctor;
839
+ return explicit ? j?.doctor ?? j : j?.doctor;
840
+ }
841
+ function isPackageDeclaration(block) {
842
+ if (typeof block === "string") return true;
843
+ if (!isObject(block)) return false;
844
+ const keys = Object.keys(block).filter((k) => k !== "$comment");
845
+ return keys.some((k) => ["prefer", "primitives", "plugin", "enforce"].includes(k)) && !keys.some((k) => KNOWN.has(k));
846
+ }
159
847
  function readJson(file) {
160
848
  try {
161
849
  return JSON.parse(readFileSync(file, "utf8"));
@@ -164,7 +852,7 @@ function readJson(file) {
164
852
  }
165
853
  }
166
854
  function readGenesisConfig(root) {
167
- const file = path14.join(root, "genesis.config.json");
855
+ const file = path18.join(root, "genesis.config.json");
168
856
  if (!existsSync(file)) return null;
169
857
  const raw = readJson(file);
170
858
  if (!isObject(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -194,18 +882,18 @@ function validatePrivacy(raw, source = "config") {
194
882
  if (c.collects !== void 0) {
195
883
  if (!Array.isArray(c.collects)) fail(`privacy.collects must be a list`);
196
884
  out.collects = c.collects.map((entry, i) => {
197
- const where = `privacy.collects[${i}]`;
198
- if (!isObject(entry)) return fail(`${where} must be an object`);
199
- for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where}: unknown setting "${key2}"`);
885
+ const where2 = `privacy.collects[${i}]`;
886
+ if (!isObject(entry)) return fail(`${where2} must be an object`);
887
+ for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where2}: unknown setting "${key2}"`);
200
888
  if (typeof entry.type !== "string" || !privacyDataType(entry.type)) {
201
- fail(`${where}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
889
+ fail(`${where2}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
202
890
  }
203
- if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where}.purposes must be a non-empty list`);
891
+ if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where2}.purposes must be a non-empty list`);
204
892
  for (const p of entry.purposes) {
205
- if (!(p in PRIVACY_PURPOSES)) fail(`${where}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
893
+ if (!(p in PRIVACY_PURPOSES)) fail(`${where2}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
206
894
  }
207
- if (typeof entry.linked !== "boolean") fail(`${where}.linked must be true or false`);
208
- if (typeof entry.tracking !== "boolean") fail(`${where}.tracking must be true or false`);
895
+ if (typeof entry.linked !== "boolean") fail(`${where2}.linked must be true or false`);
896
+ if (typeof entry.tracking !== "boolean") fail(`${where2}.tracking must be true or false`);
209
897
  return { type: entry.type, purposes: [...new Set(entry.purposes)], linked: entry.linked, tracking: entry.tracking };
210
898
  });
211
899
  }
@@ -274,6 +962,7 @@ function validateConfig(raw, source = "config") {
274
962
  if (!isObject(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
275
963
  for (const [rule, level] of Object.entries(c.rules)) {
276
964
  if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn", "info" or "off"`);
965
+ if (META_RULES.has(rule)) fail(`rules can't set ${rule}: it guards the config itself`);
277
966
  }
278
967
  }
279
968
  if (c.allow !== void 0) {
@@ -283,6 +972,7 @@ function validateConfig(raw, source = "config") {
283
972
  const entry = e;
284
973
  if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
285
974
  if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
975
+ if (META_RULES.has(entry.rule)) fail(`allow[${i}] can't allow ${entry.rule}: it guards the allow list itself`);
286
976
  for (const k of ["file", "match"]) {
287
977
  if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
288
978
  }
@@ -298,13 +988,42 @@ function validateConfig(raw, source = "config") {
298
988
  for (const k of ["files", "exclude"]) {
299
989
  if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
300
990
  }
991
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") fail(`patterns[${i}].newOnly must be true or false`);
301
992
  });
302
993
  }
994
+ if (c.packageRules !== void 0) {
995
+ if (!isObject(c.packageRules)) fail(`"packageRules" must be an object of package rule id \u2192 { level?, files?, exclude?, reason }`);
996
+ for (const [id, v] of Object.entries(c.packageRules)) {
997
+ const where2 = `packageRules["${id}"]`;
998
+ if (!id.includes("/")) fail(`${where2}: package rule ids are namespaced by package, e.g. "ui/lists-use-resource-view"`);
999
+ if (!isObject(v)) fail(`${where2} must be an object`);
1000
+ const setting = v;
1001
+ for (const k of Object.keys(setting)) if (!PACKAGE_RULE_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: level, files, exclude, reason)`);
1002
+ if (typeof setting.reason !== "string" || !setting.reason.trim()) fail(`${where2} needs a "reason": a package rule is never changed silently`);
1003
+ if (setting.level !== void 0 && !LEVELS.has(setting.level)) fail(`${where2}.level must be "error", "warn", "info" or "off"`);
1004
+ for (const k of ["files", "exclude"]) if (setting[k] !== void 0 && !isStringList(setting[k])) fail(`${where2}.${k} must be a list of globs`);
1005
+ }
1006
+ }
1007
+ if (c.ratchet !== void 0 && typeof c.ratchet !== "boolean" && !isStringList(c.ratchet)) fail(`"ratchet" must be true, false or a list of rule ids`);
303
1008
  if (c.packs !== void 0) {
304
1009
  if (!isStringList(c.packs)) fail(`"packs" must be a list, e.g. ["native", "supabase"]`);
305
1010
  for (const p of c.packs) if (!PACKS.has(p)) fail(`packs: unknown pack "${p}" (known: ${[...PACKS].join(", ")})`);
306
1011
  if (new Set(c.packs).size !== c.packs.length) fail(`packs: lists a pack twice`);
307
1012
  }
1013
+ if (c.contracts !== void 0) {
1014
+ if (!isObject(c.contracts)) fail(`"contracts" must be an object: { out?, schemas?, databaseEnv? }`);
1015
+ const contracts = c.contracts;
1016
+ for (const k of Object.keys(contracts)) if (!CONTRACT_KEYS.has(k)) fail(`contracts: unknown setting "${k}" (known: out, schemas, databaseEnv)`);
1017
+ if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1018
+ if (contracts.out !== void 0) {
1019
+ if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1020
+ if (path18.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1021
+ }
1022
+ if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1023
+ if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
1024
+ fail(`contracts.databaseEnv must be an environment variable name`);
1025
+ }
1026
+ }
308
1027
  for (const [pack, keys] of Object.entries(PACK_KEYS)) {
309
1028
  const block = c[pack];
310
1029
  if (block === void 0) continue;
@@ -327,11 +1046,11 @@ function validateConfig(raw, source = "config") {
327
1046
  }
328
1047
  return c;
329
1048
  }
330
- function checkRegExp(source, where, fail) {
1049
+ function checkRegExp(source, where2, fail) {
331
1050
  try {
332
1051
  new RegExp(source);
333
1052
  } catch (err) {
334
- fail(`${where} is not a valid regular expression: ${err.message}`);
1053
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
335
1054
  }
336
1055
  }
337
1056
  function isObject(v) {
@@ -366,7 +1085,7 @@ function globToRegExp(glob) {
366
1085
  }
367
1086
  function globMatcher(globs) {
368
1087
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
369
- return (path21) => res.some((re) => re.test(path21));
1088
+ return (path29) => res.some((re) => re.test(path29));
370
1089
  }
371
1090
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
372
1091
  var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -406,11 +1125,11 @@ var TAILWIND_PALETTE = [
406
1125
  "olive"
407
1126
  ];
408
1127
  function findPackageDir(from, name) {
409
- let dir = path14.resolve(from);
1128
+ let dir = path18.resolve(from);
410
1129
  for (; ; ) {
411
- const candidate = path14.join(dir, "node_modules", name);
412
- if (existsSync(path14.join(candidate, "package.json"))) return candidate;
413
- const parent = path14.dirname(dir);
1130
+ const candidate = path18.join(dir, "node_modules", name);
1131
+ if (existsSync(path18.join(candidate, "package.json"))) return candidate;
1132
+ const parent = path18.dirname(dir);
414
1133
  if (parent === dir) return null;
415
1134
  dir = parent;
416
1135
  }
@@ -462,7 +1181,7 @@ function loadCompanions(root, config, uiPackage) {
462
1181
  function readPackageExports(root, uiPackage) {
463
1182
  const uiDir = findPackageDir(root, uiPackage);
464
1183
  if (!uiDir) return null;
465
- const uiPkg = JSON.parse(readFileSync(path14.join(uiDir, "package.json"), "utf8"));
1184
+ const uiPkg = JSON.parse(readFileSync(path18.join(uiDir, "package.json"), "utf8"));
466
1185
  const typeEntries = /* @__PURE__ */ new Set();
467
1186
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
468
1187
  if (typeof mainTypes === "string") typeEntries.add(mainTypes);
@@ -474,7 +1193,7 @@ function readPackageExports(root, uiPackage) {
474
1193
  const reexportedPackages = /* @__PURE__ */ new Set();
475
1194
  let readAny = false;
476
1195
  for (const entry of typeEntries) {
477
- const file = path14.join(uiDir, entry);
1196
+ const file = path18.join(uiDir, entry);
478
1197
  if (!existsSync(file)) continue;
479
1198
  readAny = true;
480
1199
  const dts = readFileSync(file, "utf8");
@@ -488,11 +1207,11 @@ function readPackageExports(root, uiPackage) {
488
1207
  }
489
1208
  const valueDecls = /* @__PURE__ */ new Set();
490
1209
  const typeDecls = /* @__PURE__ */ new Set();
491
- const declRoot = typeof mainTypes === "string" ? path14.dirname(path14.join(uiDir, mainTypes)) : uiDir;
1210
+ const declRoot = typeof mainTypes === "string" ? path18.dirname(path18.join(uiDir, mainTypes)) : uiDir;
492
1211
  const declFiles = walkDts(declRoot);
493
1212
  for (const pkg of reexportedPackages) {
494
1213
  const dir = findPackageDir(uiDir, pkg);
495
- if (dir) walkDts(path14.join(dir, "dist"), declFiles);
1214
+ if (dir) walkDts(path18.join(dir, "dist"), declFiles);
496
1215
  }
497
1216
  for (const file of declFiles) {
498
1217
  const text = readFileSync(file, "utf8");
@@ -538,7 +1257,7 @@ function walkDts(dir, out = []) {
538
1257
  if (!existsSync(dir)) return out;
539
1258
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
540
1259
  if (entry.name === "node_modules") continue;
541
- const p = path14.join(dir, entry.name);
1260
+ const p = path18.join(dir, entry.name);
542
1261
  if (entry.isDirectory()) walkDts(p, out);
543
1262
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
544
1263
  }
@@ -555,27 +1274,27 @@ function resolveThemeFiles(root, config, uiDir) {
555
1274
  }
556
1275
  const files = [];
557
1276
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
558
- const themes = ds && path14.join(ds, "dist", "themes");
1277
+ const themes = ds && path18.join(ds, "dist", "themes");
559
1278
  if (themes && existsSync(themes)) {
560
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path14.join(themes, name));
1279
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path18.join(themes, name));
561
1280
  }
562
1281
  if (files.length === 0) {
563
1282
  throw new DoctorConfigError(
564
1283
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
565
1284
  );
566
1285
  }
567
- const uiStyles = path14.join(uiDir, "dist", "styles.css");
1286
+ const uiStyles = path18.join(uiDir, "dist", "styles.css");
568
1287
  if (existsSync(uiStyles)) files.push(uiStyles);
569
1288
  return files;
570
1289
  }
571
1290
  function resolveSpec(root, spec) {
572
- const local = path14.resolve(root, spec);
573
- if (spec.startsWith(".") || path14.isAbsolute(spec)) return existsSync(local) ? local : null;
1291
+ const local = path18.resolve(root, spec);
1292
+ if (spec.startsWith(".") || path18.isAbsolute(spec)) return existsSync(local) ? local : null;
574
1293
  const parts = spec.split("/");
575
1294
  const nameLength = spec.startsWith("@") ? 2 : 1;
576
1295
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
577
1296
  if (dir) {
578
- const file = path14.join(dir, ...parts.slice(nameLength));
1297
+ const file = path18.join(dir, ...parts.slice(nameLength));
579
1298
  if (existsSync(file) && statSync(file).isFile()) return file;
580
1299
  }
581
1300
  return existsSync(local) ? local : null;
@@ -583,7 +1302,7 @@ function resolveSpec(root, spec) {
583
1302
  function loadPalette(root) {
584
1303
  const names = new Set(TAILWIND_PALETTE);
585
1304
  try {
586
- const req = createRequire(path14.join(root, "package.json"));
1305
+ const req = createRequire(path18.join(root, "package.json"));
587
1306
  const colors = req("tailwindcss/colors");
588
1307
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
589
1308
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -623,17 +1342,17 @@ function parseManifest(home, id, raw, version, options = {}) {
623
1342
  if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
624
1343
  if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
625
1344
  if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
626
- const pkgOf = (value, where) => {
1345
+ const pkgOf = (value, where2) => {
627
1346
  if (value === void 0) return home;
628
1347
  if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
629
- problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
1348
+ problems.push(`${where2}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
630
1349
  return home;
631
1350
  }
632
1351
  return value;
633
1352
  };
634
- const pathOf = (value, where) => {
1353
+ const pathOf = (value, where2) => {
635
1354
  const safe = safeRelative(value);
636
- if (!safe) problems.push(`${where}: ${JSON.stringify(value)} is not a plain path inside the package`);
1355
+ if (!safe) problems.push(`${where2}: ${JSON.stringify(value)} is not a plain path inside the package`);
637
1356
  return safe ?? "";
638
1357
  };
639
1358
  const list = (key2) => {
@@ -665,43 +1384,43 @@ function parseManifest(home, id, raw, version, options = {}) {
665
1384
  return ok;
666
1385
  });
667
1386
  const migrations = list("migrations").map((m, i) => {
668
- const where = `${at}.migrations[${i}]`;
1387
+ const where2 = `${at}.migrations[${i}]`;
669
1388
  if (!isObject2(m)) {
670
- problems.push(`${where}: must be an object`);
1389
+ problems.push(`${where2}: must be an object`);
671
1390
  return { package: home, file: "" };
672
1391
  }
673
- const file = pathOf(m["file"], `${where}.file`);
674
- if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
675
- const out = { package: pkgOf(m["package"], where), file };
1392
+ const file = pathOf(m["file"], `${where2}.file`);
1393
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1394
+ const out = { package: pkgOf(m["package"], where2), file };
676
1395
  if (m["test"] !== void 0) {
677
- out.test = pathOf(m["test"], `${where}.test`);
678
- if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
1396
+ out.test = pathOf(m["test"], `${where2}.test`);
1397
+ if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where2}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
679
1398
  }
680
1399
  return out;
681
1400
  });
682
1401
  const functions = list("functions").map((f, i) => {
683
- const where = `${at}.functions[${i}]`;
1402
+ const where2 = `${at}.functions[${i}]`;
684
1403
  if (!isObject2(f)) {
685
- problems.push(`${where}: must be an object`);
1404
+ problems.push(`${where2}: must be an object`);
686
1405
  return { package: home, dir: "" };
687
1406
  }
688
- const dir = pathOf(f["dir"], `${where}.dir`);
689
- if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
690
- const out = { package: pkgOf(f["package"], where), dir };
1407
+ const dir = pathOf(f["dir"], `${where2}.dir`);
1408
+ if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where2}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
1409
+ const out = { package: pkgOf(f["package"], where2), dir };
691
1410
  if (f["verifyJwt"] !== void 0) {
692
- if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where}.verifyJwt: must be true or false`);
1411
+ if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where2}.verifyJwt: must be true or false`);
693
1412
  else out.verifyJwt = f["verifyJwt"];
694
1413
  }
695
1414
  if (f["secrets"] !== void 0) {
696
- if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where}.secrets: must be a list of UPPER_CASE names`);
1415
+ if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where2}.secrets: must be a list of UPPER_CASE names`);
697
1416
  else out.secrets = f["secrets"];
698
1417
  }
699
1418
  return out;
700
1419
  });
701
1420
  const routes = list("routes").map((r, i) => {
702
- const where = `${at}.routes[${i}]`;
1421
+ const where2 = `${at}.routes[${i}]`;
703
1422
  if (!isObject2(r) || typeof r["path"] !== "string" || !ROUTE.test(r["path"]) || r["path"].split("/").includes("..")) {
704
- problems.push(`${where}: needs a path like /settings/notifications`);
1423
+ problems.push(`${where2}: needs a path like /settings/notifications`);
705
1424
  return { path: "/" };
706
1425
  }
707
1426
  const out = { path: r["path"] };
@@ -771,8 +1490,8 @@ function rawBlocksOf(packageJson) {
771
1490
 
772
1491
  // src/blocks/files.ts
773
1492
  function inside(parent, child) {
774
- const rel = path14.relative(parent, child);
775
- return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
1493
+ const rel = path18.relative(parent, child);
1494
+ return rel === "" || !rel.startsWith("..") && !path18.isAbsolute(rel);
776
1495
  }
777
1496
 
778
1497
  // src/blocks/local.ts
@@ -783,21 +1502,21 @@ var LocalPackagesError = class extends Error {
783
1502
  function validateLocalPackages(raw, source = "genesis.config.json") {
784
1503
  if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
785
1504
  return raw.map((entry, i) => {
786
- const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
787
- if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
788
- if (path14.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
789
- const norm = path14.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
790
- if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
1505
+ const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
1506
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
1507
+ if (path18.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
1508
+ const norm = path18.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
1509
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
791
1510
  const parts = norm.split("/");
792
1511
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
793
- throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
1512
+ throw new LocalPackagesError(`${where2}: only a final "/*" is supported ("${entry}")`);
794
1513
  }
795
- if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
1514
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where2} can't point into node_modules ("${entry}")`);
796
1515
  return norm;
797
1516
  });
798
1517
  }
799
1518
  function localPackageGlobs(root) {
800
- const file = path14.join(root, "genesis.config.json");
1519
+ const file = path18.join(root, "genesis.config.json");
801
1520
  if (!existsSync(file)) return [];
802
1521
  let raw;
803
1522
  try {
@@ -811,14 +1530,14 @@ function localPackageGlobs(root) {
811
1530
  var cache = /* @__PURE__ */ new Map();
812
1531
  function repositoryRoot(appRoot) {
813
1532
  for (let dir = appRoot; ; ) {
814
- if (existsSync(path14.join(dir, ".git"))) return dir;
815
- const parent = path14.dirname(dir);
1533
+ if (existsSync(path18.join(dir, ".git"))) return dir;
1534
+ const parent = path18.dirname(dir);
816
1535
  if (parent === dir) return appRoot;
817
1536
  dir = parent;
818
1537
  }
819
1538
  }
820
1539
  function localPackages(root) {
821
- const appRoot = path14.resolve(root);
1540
+ const appRoot = path18.resolve(root);
822
1541
  const globs = localPackageGlobs(appRoot);
823
1542
  const key2 = `${appRoot}
824
1543
  ${globs.join("\n")}`;
@@ -827,24 +1546,24 @@ ${globs.join("\n")}`;
827
1546
  const dirs = /* @__PURE__ */ new Set();
828
1547
  for (const glob of globs) {
829
1548
  if (glob.endsWith("/*") || glob === "*") {
830
- const parent = path14.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
1549
+ const parent = path18.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
831
1550
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
832
1551
  for (const entry of readdirSync(parent).sort()) {
833
1552
  if (entry.startsWith(".") || entry === "node_modules") continue;
834
- dirs.add(path14.join(parent, entry));
1553
+ dirs.add(path18.join(parent, entry));
835
1554
  }
836
1555
  } else {
837
- dirs.add(path14.join(appRoot, glob));
1556
+ dirs.add(path18.join(appRoot, glob));
838
1557
  }
839
1558
  }
840
1559
  const real2 = realpathSync(repositoryRoot(appRoot));
841
1560
  const out = [];
842
1561
  const byName = /* @__PURE__ */ new Map();
843
1562
  for (const dir of [...dirs].sort()) {
844
- const manifest = path14.join(dir, "package.json");
1563
+ const manifest = path18.join(dir, "package.json");
845
1564
  if (!existsSync(manifest)) continue;
846
1565
  if (!inside(real2, realpathSync(dir))) {
847
- throw new LocalPackagesError(`${path14.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
1566
+ throw new LocalPackagesError(`${path18.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
848
1567
  }
849
1568
  let pkg;
850
1569
  try {
@@ -853,7 +1572,7 @@ ${globs.join("\n")}`;
853
1572
  continue;
854
1573
  }
855
1574
  if (typeof pkg.name !== "string" || !pkg.name) continue;
856
- const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
1575
+ const rel = path18.relative(appRoot, dir).split(path18.sep).join("/");
857
1576
  const other = byName.get(pkg.name);
858
1577
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
859
1578
  byName.set(pkg.name, rel);
@@ -1038,16 +1757,16 @@ var DEFAULT_IGNORE = [
1038
1757
  ];
1039
1758
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
1040
1759
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
1041
- var toPosix = (p) => p.split(path14.sep).join("/");
1760
+ var toPosix = (p) => p.split(path18.sep).join("/");
1042
1761
  function scanFiles(root, config) {
1043
1762
  const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
1044
1763
  const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
1045
1764
  const files = [];
1046
1765
  const seen = /* @__PURE__ */ new Set();
1047
1766
  const visit = (abs) => {
1048
- const rel = toPosix(path14.relative(root, abs));
1767
+ const rel = toPosix(path18.relative(root, abs));
1049
1768
  if (seen.has(rel) || ignored(rel)) return;
1050
- const ext = path14.extname(abs);
1769
+ const ext = path18.extname(abs);
1051
1770
  if (!extensions.has(ext)) return;
1052
1771
  if (statSync(abs).size > MAX_FILE_BYTES) return;
1053
1772
  seen.add(rel);
@@ -1057,14 +1776,14 @@ function scanFiles(root, config) {
1057
1776
  const walk = (dir) => {
1058
1777
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1059
1778
  if (entry.isDirectory()) {
1060
- if (!SKIP_DIRS.has(entry.name)) walk(path14.join(dir, entry.name));
1779
+ if (!SKIP_DIRS.has(entry.name)) walk(path18.join(dir, entry.name));
1061
1780
  } else if (entry.isFile()) {
1062
- visit(path14.join(dir, entry.name));
1781
+ visit(path18.join(dir, entry.name));
1063
1782
  }
1064
1783
  }
1065
1784
  };
1066
1785
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
1067
- const abs = path14.resolve(root, src);
1786
+ const abs = path18.resolve(root, src);
1068
1787
  if (!existsSync(abs)) continue;
1069
1788
  if (statSync(abs).isDirectory()) walk(abs);
1070
1789
  else visit(abs);
@@ -1099,12 +1818,13 @@ function parseRulesMarkdown(markdown) {
1099
1818
  current = null;
1100
1819
  continue;
1101
1820
  }
1102
- const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
1821
+ const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message|newOnly):\s*(.*)$/);
1103
1822
  if (!current || !kv) continue;
1104
1823
  const [, key2, raw] = kv;
1105
1824
  const value = raw.trim();
1106
1825
  if (key2 === "files" || key2 === "exclude") current[key2] = value.split(",").map((s) => s.trim()).filter(Boolean);
1107
1826
  else if (key2 === "level") current.level = value;
1827
+ else if (key2 === "newOnly") current.newOnly = value === "true" ? true : value === "false" ? false : value;
1108
1828
  else current[key2] = value;
1109
1829
  }
1110
1830
  return rules;
@@ -1123,6 +1843,9 @@ function compilePatternRules(rules, source) {
1123
1843
  if (!["error", "warn", "info", "guide"].includes(level)) {
1124
1844
  throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn, info or guide)`);
1125
1845
  }
1846
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") {
1847
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has newOnly "${String(rule.newOnly)}" (use true or false)`);
1848
+ }
1126
1849
  if (level === "guide") continue;
1127
1850
  if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
1128
1851
  if (!rule.forbid && !rule.require && !rule.path) {
@@ -1148,7 +1871,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
1148
1871
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
1149
1872
  let all = compiled;
1150
1873
  if (rulesDoc) {
1151
- const file = path14.resolve(root, rulesDoc);
1874
+ const file = path18.resolve(root, rulesDoc);
1152
1875
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
1153
1876
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
1154
1877
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -1158,6 +1881,8 @@ function loadPatternRules(root, patterns, rulesDoc) {
1158
1881
  if (all.length === 0) return null;
1159
1882
  return {
1160
1883
  count: all.length,
1884
+ ids: all.map((r) => r.rule.id),
1885
+ newOnly: all.filter((r) => r.rule.newOnly).map((r) => r.rule.id),
1161
1886
  plugin: {
1162
1887
  name: "patterns",
1163
1888
  check(ctx) {
@@ -1204,14 +1929,14 @@ async function loadPlugins(specs, configDir) {
1204
1929
  }
1205
1930
  function resolvePlugin(id, configDir) {
1206
1931
  try {
1207
- if (id.startsWith(".") || path14.isAbsolute(id)) return resolveFrom(path14.resolve(configDir, id), configDir);
1932
+ if (id.startsWith(".") || path18.isAbsolute(id)) return resolveFrom(path18.resolve(configDir, id), configDir);
1208
1933
  return resolveFrom(id, configDir);
1209
1934
  } catch {
1210
1935
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
1211
1936
  }
1212
1937
  }
1213
1938
  function resolveFrom(id, from) {
1214
- return createRequire(path14.join(from, "noop.js")).resolve(id);
1939
+ return createRequire(path18.join(from, "noop.js")).resolve(id);
1215
1940
  }
1216
1941
  var BUILTIN_RULES = [
1217
1942
  "local-primitives",
@@ -1233,6 +1958,11 @@ var BUILTIN_RULES = [
1233
1958
  "page-layout",
1234
1959
  // dates
1235
1960
  "iso-date-slice",
1961
+ // Genesis API usage (api-usage.ts)
1962
+ "resource-view-tree",
1963
+ "studio-server-auth-import",
1964
+ "removed-scope-name",
1965
+ "scope-practice-id",
1236
1966
  // native pack
1237
1967
  "native-raw-primitive",
1238
1968
  "native-literal-color",
@@ -1256,7 +1986,19 @@ var BUILTIN_RULES = [
1256
1986
  "package-unversioned-change",
1257
1987
  "package-export-missing",
1258
1988
  "package-block-invalid",
1259
- "package-untagged-tests"
1989
+ "package-untagged-tests",
1990
+ "package-doctor-declaration",
1991
+ // package rules (package-rules.ts): the rules themselves are namespaced, e.g. ui/lists-use-resource-view
1992
+ "package-rules-invalid",
1993
+ "package-rule-override",
1994
+ // ratchet (ratchet.ts)
1995
+ "ratchet-skipped",
1996
+ "allow-grew",
1997
+ "rules-weakened",
1998
+ // agent guide (primitives.ts)
1999
+ "agent-guide-stale",
2000
+ // supabase pack: contracts (contracts.ts)
2001
+ "contracts-stale"
1260
2002
  ];
1261
2003
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1262
2004
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1274,7 +2016,7 @@ function importSpecifiers(file) {
1274
2016
  }
1275
2017
  function checkProjectLayout(ctx) {
1276
2018
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
1277
- if (existsSync(path14.join(ctx.root, dir))) {
2019
+ if (existsSync(path18.join(ctx.root, dir))) {
1278
2020
  ctx.report({
1279
2021
  rule: "local-primitives",
1280
2022
  file: dir,
@@ -1284,7 +2026,7 @@ function checkProjectLayout(ctx) {
1284
2026
  }
1285
2027
  }
1286
2028
  for (const file of STARTER_LEFTOVERS) {
1287
- if (existsSync(path14.join(ctx.root, file))) {
2029
+ if (existsSync(path18.join(ctx.root, file))) {
1288
2030
  ctx.report({
1289
2031
  rule: "starter-leftover",
1290
2032
  level: "warn",
@@ -1373,7 +2115,7 @@ function checkTokens(ctx) {
1373
2115
  }
1374
2116
  for (const pattern of ctx.config.tokenFiles ?? []) {
1375
2117
  if (/[*?]/.test(pattern)) continue;
1376
- const abs = path14.join(ctx.root, pattern);
2118
+ const abs = path18.join(ctx.root, pattern);
1377
2119
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
1378
2120
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
1379
2121
  }
@@ -1475,19 +2217,34 @@ function privacyApisFor(dependencies2) {
1475
2217
  var SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
1476
2218
  var JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
1477
2219
  var RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
2220
+ function resolveLocal(root, fromFile, spec) {
2221
+ const bases = spec.startsWith(".") ? [path18.resolve(path18.dirname(fromFile), spec)] : [path18.join(root, spec.slice(2)), path18.join(root, "src", spec.slice(2))];
2222
+ for (const base of bases) {
2223
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path18.join(base, `index${e}`))].find(
2224
+ (p) => SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p)
2225
+ );
2226
+ if (hit) return hit;
2227
+ }
2228
+ return null;
2229
+ }
1478
2230
  function localImports(root, file) {
1479
2231
  const out = [];
1480
2232
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
1481
- const spec = m[1];
1482
- const bases = spec.startsWith(".") ? [path14.resolve(path14.dirname(file.absolutePath), spec)] : [path14.join(root, spec.slice(2)), path14.join(root, "src", spec.slice(2))];
1483
- for (const base of bases) {
1484
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path14.join(base, `index${e}`))].find(
1485
- (p) => SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p)
1486
- );
1487
- if (hit) {
1488
- out.push(hit);
1489
- break;
1490
- }
2233
+ const hit = resolveLocal(root, file.absolutePath, m[1]);
2234
+ if (hit) out.push(hit);
2235
+ }
2236
+ return out;
2237
+ }
2238
+ function localImportedNames(root, file) {
2239
+ const out = /* @__PURE__ */ new Map();
2240
+ const re = /\bimport\s+(?:type\s+)?([\w$]+)?\s*,?\s*(?:\{([^}]*)\})?\s*from\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g;
2241
+ for (const m of file.code.matchAll(re)) {
2242
+ const target = resolveLocal(root, file.absolutePath, m[3]);
2243
+ if (!target) continue;
2244
+ if (m[1]) out.set(m[1], { file: target, name: "default" });
2245
+ for (const part of (m[2] ?? "").split(",")) {
2246
+ const [imported, local] = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/);
2247
+ if (imported) out.set(local ?? imported, { file: target, name: imported });
1491
2248
  }
1492
2249
  }
1493
2250
  return out;
@@ -1501,15 +2258,15 @@ function readSource(abs) {
1501
2258
  }
1502
2259
  function tagEnd(code, start) {
1503
2260
  let depth = 0;
1504
- let quote = null;
2261
+ let quote2 = null;
1505
2262
  for (let i = start + 1; i < code.length; i++) {
1506
2263
  const ch = code[i];
1507
- if (quote) {
2264
+ if (quote2) {
1508
2265
  if (ch === "\\") i++;
1509
- else if (ch === quote) quote = null;
2266
+ else if (ch === quote2) quote2 = null;
1510
2267
  continue;
1511
2268
  }
1512
- if (ch === '"' || ch === "'" || ch === "`") quote = ch;
2269
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
1513
2270
  else if (ch === "{") depth++;
1514
2271
  else if (ch === "}") depth--;
1515
2272
  else if (ch === ">" && depth === 0) {
@@ -1646,7 +2403,7 @@ function checkCustomHeaders(ctx, pkg) {
1646
2403
  if (!JSX_EXTS3.has(file.ext)) continue;
1647
2404
  const code = file.code;
1648
2405
  const hidden = HIDES_HEADER.exec(code);
1649
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path14.posix.dirname(file.path), file.path);
2406
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path18.posix.dirname(file.path), file.path);
1650
2407
  const own = hidden ? ownHeader(code, pkg) : null;
1651
2408
  if (hidden && own) {
1652
2409
  reported.add(file.path);
@@ -1674,7 +2431,7 @@ function checkCustomHeaders(ctx, pkg) {
1674
2431
  }
1675
2432
  for (const file of ctx.files) {
1676
2433
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
1677
- const layout = hidingLayouts.get(path14.posix.dirname(file.path));
2434
+ const layout = hidingLayouts.get(path18.posix.dirname(file.path));
1678
2435
  const own = layout ? ownHeader(file.code, pkg) : null;
1679
2436
  if (!layout || !own) continue;
1680
2437
  ctx.report({
@@ -1696,13 +2453,13 @@ function isLoadingOnlyRoute(code) {
1696
2453
  }
1697
2454
  function routerRoot(ctx) {
1698
2455
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
1699
- return existsSync(path14.join(ctx.root, "src", "app")) ? "src/app" : "app";
2456
+ return existsSync(path18.join(ctx.root, "src", "app")) ? "src/app" : "app";
1700
2457
  }
1701
2458
  function checkScreenLayouts(ctx, pkg) {
1702
2459
  const layouts = nativeLayouts(pkg);
1703
2460
  if (layouts.length === 0) return;
1704
2461
  const rootDir = routerRoot(ctx);
1705
- if (!existsSync(path14.join(ctx.root, rootDir))) {
2462
+ if (!existsSync(path18.join(ctx.root, rootDir))) {
1706
2463
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
1707
2464
  return;
1708
2465
  }
@@ -1758,7 +2515,7 @@ var GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\
1758
2515
  function readExpoConfigs(root) {
1759
2516
  const out = [];
1760
2517
  for (const name of EXPO_CONFIGS) {
1761
- const abs = path14.join(root, name);
2518
+ const abs = path18.join(root, name);
1762
2519
  if (!existsSync(abs)) continue;
1763
2520
  const text = readFileSync(abs, "utf8");
1764
2521
  let json = null;
@@ -1792,13 +2549,13 @@ function pluginOptions(json, module) {
1792
2549
  return null;
1793
2550
  }
1794
2551
  function dependencies(root) {
1795
- const file = path14.join(root, "package.json");
2552
+ const file = path18.join(root, "package.json");
1796
2553
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
1797
2554
  const pkg = JSON.parse(readFileSync(file, "utf8"));
1798
2555
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
1799
2556
  }
1800
2557
  function runtimeDependencies(root) {
1801
- const file = path14.join(root, "package.json");
2558
+ const file = path18.join(root, "package.json");
1802
2559
  if (!existsSync(file)) return {};
1803
2560
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
1804
2561
  }
@@ -2172,14 +2929,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2172
2929
  seen.add(file);
2173
2930
  const json = readJsonc(file);
2174
2931
  if (!json) return {};
2175
- const dir = path14.dirname(file);
2932
+ const dir = path18.dirname(file);
2176
2933
  let merged = {};
2177
2934
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
2178
2935
  for (const ext of parents) {
2179
2936
  if (typeof ext !== "string") continue;
2180
2937
  let target = null;
2181
- if (ext.startsWith(".") || path14.isAbsolute(ext)) {
2182
- const abs = path14.resolve(dir, ext);
2938
+ if (ext.startsWith(".") || path18.isAbsolute(ext)) {
2939
+ const abs = path18.resolve(dir, ext);
2183
2940
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2184
2941
  } else {
2185
2942
  const parts = ext.split("/");
@@ -2187,14 +2944,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2187
2944
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2188
2945
  if (pkgDir) {
2189
2946
  const sub = parts.slice(nameLength).join("/");
2190
- const abs = path14.join(pkgDir, sub || "tsconfig.json");
2947
+ const abs = path18.join(pkgDir, sub || "tsconfig.json");
2191
2948
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2192
2949
  }
2193
2950
  }
2194
2951
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2195
2952
  }
2196
2953
  const opts = json.compilerOptions ?? {};
2197
- if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
2954
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path18.resolve(dir, opts.baseUrl);
2198
2955
  if (opts.paths && typeof opts.paths === "object") {
2199
2956
  merged.paths = opts.paths;
2200
2957
  merged.pathsDir = dir;
@@ -2205,7 +2962,7 @@ function aliases(root) {
2205
2962
  const table = [];
2206
2963
  let baseUrl = null;
2207
2964
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
2208
- const file = path14.join(root, name);
2965
+ const file = path18.join(root, name);
2209
2966
  if (!existsSync(file)) continue;
2210
2967
  const config = readTsconfig(root, file);
2211
2968
  baseUrl ??= config.baseUrl ?? null;
@@ -2213,22 +2970,22 @@ function aliases(root) {
2213
2970
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
2214
2971
  if (!Array.isArray(targets)) continue;
2215
2972
  const exact = !pattern.endsWith("*");
2216
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
2973
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path18.join(base, String(t).replace(/\*$/, ""))) });
2217
2974
  }
2218
2975
  }
2219
- const pkg = readJsonc(path14.join(root, "package.json"));
2976
+ const pkg = readJsonc(path18.join(root, "package.json"));
2220
2977
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
2221
2978
  if (typeof target !== "string") continue;
2222
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
2979
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path18.join(root, target.replace(/\*.*$/, ""))] });
2223
2980
  }
2224
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2981
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path18.join(root, "src") + path18.sep, root + path18.sep] });
2225
2982
  return { table, baseUrl };
2226
2983
  }
2227
2984
  function resolveFile(base) {
2228
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
2985
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path18.join(base, `index${e}`))];
2229
2986
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
2230
2987
  for (const p of tries) {
2231
- if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2988
+ if (SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2232
2989
  }
2233
2990
  return null;
2234
2991
  }
@@ -2242,13 +2999,13 @@ function createTrail(ctx) {
2242
2999
  const { table, baseUrl } = aliases(ctx.root);
2243
3000
  let declared = null;
2244
3001
  try {
2245
- const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3002
+ const pkg = JSON.parse(readFileSync(path18.join(ctx.root, "package.json"), "utf8"));
2246
3003
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
2247
3004
  } catch {
2248
3005
  declared = null;
2249
3006
  }
2250
3007
  const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2251
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
3008
+ const read2 = (abs) => byPath.get(abs) ?? readSource(abs);
2252
3009
  const importsCache = /* @__PURE__ */ new Map();
2253
3010
  const importsOf = (file) => {
2254
3011
  const hit = importsCache.get(file.absolutePath);
@@ -2273,17 +3030,17 @@ function createTrail(ctx) {
2273
3030
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
2274
3031
  let resolved = null;
2275
3032
  if (spec.startsWith(".")) {
2276
- resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3033
+ resolved = resolveFile(path18.resolve(path18.dirname(file.absolutePath), spec));
2277
3034
  if (!resolved) lost = true;
2278
3035
  } else {
2279
3036
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
2280
3037
  if (alias) {
2281
3038
  for (const t of alias.targets) {
2282
- resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3039
+ resolved = resolveFile(alias.exact ? t : path18.join(t, spec.slice(alias.prefix.length)));
2283
3040
  if (resolved) break;
2284
3041
  }
2285
3042
  }
2286
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3043
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path18.join(baseUrl, spec));
2287
3044
  if (!resolved) {
2288
3045
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
2289
3046
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -2325,7 +3082,7 @@ function createTrail(ctx) {
2325
3082
  cut.add(abs);
2326
3083
  continue;
2327
3084
  }
2328
- const target = read(abs);
3085
+ const target = read2(abs);
2329
3086
  if (!target) {
2330
3087
  unknown = true;
2331
3088
  continue;
@@ -2355,83 +3112,587 @@ function createTrail(ctx) {
2355
3112
  return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
2356
3113
  }
2357
3114
 
2358
- // src/doctor/packages.ts
2359
- var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
2360
- var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
2361
- var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
2362
- var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
2363
- var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
2364
- function sourceFiles(dir, rel = "") {
2365
- const out = [];
2366
- for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
2367
- if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
2368
- const child = rel ? `${rel}/${entry}` : entry;
2369
- const stat = lstatSync(path14.join(dir, child));
2370
- if (stat.isSymbolicLink()) continue;
2371
- if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
2372
- else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3115
+ // src/blocks/discover.ts
3116
+ var INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
3117
+ function installedGenesis(root) {
3118
+ const found = /* @__PURE__ */ new Map();
3119
+ let dir = path18.resolve(root);
3120
+ for (; ; ) {
3121
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path18.join(dir, m)));
3122
+ const scope = path18.join(dir, "node_modules", "@marktiderman");
3123
+ if (existsSync(scope)) {
3124
+ for (const entry of readdirSync(scope)) {
3125
+ const name = `@marktiderman/${entry}`;
3126
+ if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
3127
+ if (existsSync(path18.join(scope, entry, "package.json"))) found.set(name, path18.join(scope, entry));
3128
+ }
3129
+ }
3130
+ const parent = path18.dirname(dir);
3131
+ if (atInstallRoot || parent === dir) return found;
3132
+ dir = parent;
2373
3133
  }
2374
- return out;
2375
3134
  }
2376
- function packageName2(specifier) {
2377
- const parts = specifier.split("/");
2378
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3135
+ var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3136
+ var STEMS = {
3137
+ tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3138
+ "next-app": {
3139
+ layout: /* @__PURE__ */ new Set(["layout"]),
3140
+ index: /* @__PURE__ */ new Set(["page"]),
3141
+ skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3142
+ },
3143
+ "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3144
+ };
3145
+ var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3146
+ var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3147
+ var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3148
+ var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3149
+ var OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
3150
+ function routesDir(ctx) {
3151
+ if (ctx.config.routesDir) return ctx.config.routesDir;
3152
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path18.join(ctx.root, d))) ?? null;
2379
3153
  }
2380
- function git(root, args) {
2381
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2382
- return r.status === 0 ? r.stdout : null;
3154
+ var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3155
+ function flavorOf(dir, rels) {
3156
+ const stems = rels.map((r) => r.split("/").pop());
3157
+ if (stems.includes("__root")) return "tanstack";
3158
+ if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3159
+ if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3160
+ return "tanstack";
2383
3161
  }
2384
- function matchPattern(pattern, spec) {
2385
- const star = pattern.indexOf("*");
2386
- if (star < 0) return pattern === spec ? "" : null;
2387
- const head = pattern.slice(0, star);
2388
- const tail = pattern.slice(star + 1);
2389
- return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3162
+ function renders(code) {
3163
+ const elements = renderedElements(code);
3164
+ if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3165
+ const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3166
+ const named = COMPONENT_OPTION.exec(code)?.[1];
3167
+ if (named && !definedHere(named)) return true;
3168
+ if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3169
+ const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3170
+ return exported !== void 0 && !definedHere(exported);
2390
3171
  }
2391
- function tsconfigPaths(dir) {
2392
- const file = path14.join(dir, "tsconfig.json");
2393
- if (!existsSync(file)) return [];
2394
- try {
2395
- const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
2396
- const options = JSON.parse(text).compilerOptions ?? {};
2397
- const base = path14.resolve(dir, options.baseUrl ?? ".");
2398
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
2399
- } catch {
2400
- return [];
3172
+ function webRoutes(ctx) {
3173
+ const dir = routesDir(ctx);
3174
+ if (!dir) return [];
3175
+ const candidates = ctx.files.filter((f) => JSX_EXTS2.has(f.ext) && f.path.startsWith(`${dir}/`)).map((file) => ({ file, rel: file.path.slice(dir.length + 1).replace(/\.[^.]+$/, "") }));
3176
+ const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3177
+ const stems = STEMS[flavor];
3178
+ const groups = /* @__PURE__ */ new Map();
3179
+ for (const { file, rel } of candidates) {
3180
+ const parts = rel.split("/");
3181
+ if (parts.some((p) => p.startsWith("-"))) continue;
3182
+ if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3183
+ if (flavor === "next-pages" && parts[0] === "api") continue;
3184
+ if (stems.skip.test(parts.at(-1))) continue;
3185
+ if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3186
+ const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3187
+ groups.set(id, [...groups.get(id) ?? [], file]);
2401
3188
  }
2402
- }
2403
- function checkImports2(ctx, pkg, json) {
2404
- const aliases2 = tsconfigPaths(pkg.dir);
2405
- const subpathImports = Object.keys(json.imports ?? {});
2406
- const viaAlias = (spec) => {
2407
- if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
2408
- for (const { pattern, targets } of aliases2) {
2409
- const hit = matchPattern(pattern, spec);
2410
- if (hit === null) continue;
2411
- return targets.some((t) => {
2412
- const rel = path14.relative(pkg.dir, t.replace("*", hit));
2413
- return !rel.startsWith("..") && !path14.isAbsolute(rel);
2414
- });
3189
+ const trail = trailFor(ctx);
3190
+ const routes = [];
3191
+ for (const [id, files] of groups) {
3192
+ const parts = id.split("/");
3193
+ const stem = parts.pop();
3194
+ const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3195
+ const named = stems.layout.has(stem) || stems.index.has(stem);
3196
+ const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3197
+ const segments = [...folders, ...own];
3198
+ const tree = [...parts, ...own];
3199
+ let index = stems.index.has(stem);
3200
+ if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3201
+ segments.pop();
3202
+ tree.pop();
3203
+ index = true;
2415
3204
  }
2416
- return null;
2417
- };
2418
- const declared = /* @__PURE__ */ new Set([
2419
- json.name,
2420
- ...Object.keys(json.dependencies ?? {}),
2421
- ...Object.keys(json.peerDependencies ?? {}),
2422
- ...Object.keys(json.devDependencies ?? {}),
2423
- ...Object.keys(json.optionalDependencies ?? {})
2424
- ]);
2425
- for (const file of sourceFiles(pkg.dir)) {
2426
- const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
2427
- if (code === null) continue;
2428
- const at = `${pkg.rel}/${file}`;
2429
- const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
2430
- let offset = 0;
2431
- code.split("\n").forEach((text, i) => {
2432
- const lineStart = offset;
2433
- offset += text.length + 1;
2434
- for (const m of text.matchAll(IMPORT)) {
3205
+ const code = files.map((f) => f.code).join("\n");
3206
+ const elements = renderedElements(code);
3207
+ const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3208
+ const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3209
+ const layout = stems.layout.has(stem) || pathless || outlet;
3210
+ const rendering = renders(code);
3211
+ const ownContent = new RegExp(OWN_CONTENT).test(code);
3212
+ const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3213
+ const page = !pure && !pathless && (!layout || ownContent);
3214
+ routes.push({
3215
+ file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3216
+ files,
3217
+ segments,
3218
+ tree,
3219
+ index,
3220
+ layout,
3221
+ page,
3222
+ detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3223
+ redirectOnly: !rendering,
3224
+ parents: []
3225
+ });
3226
+ }
3227
+ for (const r of routes) {
3228
+ const own = r.tree;
3229
+ for (const p of routes) {
3230
+ if (p === r || !p.layout) continue;
3231
+ const n = p.tree.length;
3232
+ if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3233
+ if (key(own.slice(0, n)) !== key(p.tree)) continue;
3234
+ if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3235
+ r.parents.push(p);
3236
+ }
3237
+ r.parents.sort((a, b) => b.tree.length - a.tree.length);
3238
+ }
3239
+ return routes;
3240
+ }
3241
+
3242
+ // src/doctor/package-rules.ts
3243
+ var PackageDeclarationError = class extends Error {
3244
+ name = "PackageDeclarationError";
3245
+ };
3246
+ var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3247
+ var ID = /^[a-z0-9][a-z0-9-]*$/;
3248
+ var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3249
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
3250
+ var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3251
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
3252
+ var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3253
+ var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "primitives", "plugin", "$comment"]);
3254
+ var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
3255
+ function ruleNamespace(packageName3) {
3256
+ const m = GENESIS.exec(packageName3);
3257
+ if (m) return m[1] ?? "genesis";
3258
+ return packageName3;
3259
+ }
3260
+ var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3261
+ var isStringList2 = (v) => Array.isArray(v) && v.every((x) => typeof x === "string" && x.trim() !== "");
3262
+ function toRegExp2(source, flags = "") {
3263
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
3264
+ return new RegExp(source, flags);
3265
+ }
3266
+ function validateDeclaration(raw, packageName3, packageDir, ignored) {
3267
+ const fail = (msg) => {
3268
+ throw new PackageDeclarationError(`${packageName3}: genesis.doctor ${msg}`);
3269
+ };
3270
+ const unknownKey = (where2, key2, known) => {
3271
+ const msg = `${where2 ? `${where2} ` : ""}has an unknown key "${key2}"${known ? ` (known: ${[...known].filter((k) => k !== "$comment").join(", ")})` : ""}`;
3272
+ if (!ignored) return fail(msg);
3273
+ ignored.push(`${packageName3}: genesis.doctor ${msg}; ignored`);
3274
+ };
3275
+ const each = (list, check) => list.flatMap((item, i) => {
3276
+ if (!ignored) return [check(item, i)];
3277
+ try {
3278
+ return [check(item, i)];
3279
+ } catch (err) {
3280
+ if (!(err instanceof PackageDeclarationError)) throw err;
3281
+ ignored.push(`${err.message}; that entry is skipped`);
3282
+ return [];
3283
+ }
3284
+ });
3285
+ if (typeof raw === "string") {
3286
+ if (!packageDir) fail(`points at ${raw}, but the package folder is unknown`);
3287
+ const file = path18.resolve(packageDir, raw);
3288
+ if (!inside(packageDir, file)) fail(`points outside the package (${raw})`);
3289
+ if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
3290
+ let parsed;
3291
+ try {
3292
+ parsed = JSON.parse(readFileSync(file, "utf8"));
3293
+ } catch (err) {
3294
+ return fail(`file ${raw} is not valid JSON: ${err.message}`);
3295
+ }
3296
+ return validateDeclaration(parsed, packageName3, packageDir, ignored);
3297
+ }
3298
+ if (raw === false) fail(`is false; say why with { "enforce": false, "reason": "\u2026" }`);
3299
+ if (!isObject3(raw)) fail(`must be an object (or a path to a JSON file in the package)`);
3300
+ const c = raw;
3301
+ for (const key2 of Object.keys(c)) if (!DECLARATION_KEYS.has(key2)) unknownKey("", key2, DECLARATION_KEYS);
3302
+ const enforce = c.enforce === void 0 ? true : c.enforce;
3303
+ if (typeof enforce !== "boolean") fail(`enforce must be true or false`);
3304
+ if (c.reason !== void 0 && (typeof c.reason !== "string" || !c.reason.trim())) fail(`reason must be a sentence`);
3305
+ const prefer = c.prefer === void 0 ? [] : c.prefer;
3306
+ if (!Array.isArray(prefer)) fail(`prefer must be a list`);
3307
+ const primitives = c.primitives === void 0 ? [] : c.primitives;
3308
+ if (!Array.isArray(primitives)) fail(`primitives must be a list`);
3309
+ if (c.plugin !== void 0 && (typeof c.plugin !== "string" || !c.plugin.trim())) fail(`plugin must be a module path inside the package`);
3310
+ if (!enforce) {
3311
+ if (typeof c.reason !== "string") fail(`turns enforcement off without a reason; add "reason"`);
3312
+ if (prefer.length || c.plugin) fail(`turns enforcement off but declares rules; drop "enforce": false or the rules`);
3313
+ } else if (!prefer.length && !c.plugin) {
3314
+ fail(`declares no rules; add "prefer" rules or a "plugin", or say { "enforce": false, "reason": "\u2026" }`);
3315
+ }
3316
+ const ids = /* @__PURE__ */ new Set();
3317
+ const rules = each(prefer, (r, i) => validatePrefer(r, `prefer[${i}]`, fail, unknownKey));
3318
+ for (const r of rules) {
3319
+ if (ids.has(r.id)) fail(`defines the rule "${r.id}" twice`);
3320
+ ids.add(r.id);
3321
+ }
3322
+ const entries = each(primitives, (p, i) => {
3323
+ const where2 = `primitives[${i}]`;
3324
+ if (!isObject3(p)) return fail(`${where2} must be an object`);
3325
+ for (const key2 of Object.keys(p)) if (!PRIMITIVE_KEYS.has(key2)) unknownKey(where2, key2);
3326
+ for (const key2 of ["need", "use"]) if (typeof p[key2] !== "string" || !p[key2].trim()) fail(`${where2} needs "${key2}"`);
3327
+ for (const key2 of ["import", "docs"]) if (p[key2] !== void 0 && typeof p[key2] !== "string") fail(`${where2}.${key2} must be a string`);
3328
+ return p;
3329
+ });
3330
+ let plugin;
3331
+ if (typeof c.plugin === "string") {
3332
+ if (!packageDir) plugin = c.plugin;
3333
+ else {
3334
+ plugin = path18.resolve(packageDir, c.plugin);
3335
+ if (!inside(packageDir, plugin)) fail(`plugin points outside the package (${c.plugin})`);
3336
+ }
3337
+ }
3338
+ return {
3339
+ enforce,
3340
+ ...typeof c.reason === "string" ? { reason: c.reason } : {},
3341
+ prefer: rules,
3342
+ primitives: entries,
3343
+ ...plugin ? { plugin } : {}
3344
+ };
3345
+ }
3346
+ function validatePrefer(raw, where2, fail, unknownKey) {
3347
+ if (!isObject3(raw)) return fail(`${where2} must be an object`);
3348
+ const narrowing = (at2, key2, known) => fail(`${at2} has an unknown key "${key2}" (known: ${[...known].join(", ")})`);
3349
+ for (const key2 of Object.keys(raw)) if (!PREFER_KEYS.has(key2)) narrowing(where2, key2, PREFER_KEYS);
3350
+ if (typeof raw.id !== "string" || !ID.test(raw.id)) fail(`${where2} needs an "id" of lower-case words and dashes`);
3351
+ const at = `${where2} (${raw.id})`;
3352
+ for (const key2 of ["use", "why"]) if (typeof raw[key2] !== "string" || !raw[key2].trim()) fail(`${at} needs "${key2}"`);
3353
+ for (const key2 of ["need", "import", "docs"]) if (raw[key2] !== void 0 && typeof raw[key2] !== "string") fail(`${at}.${key2} must be a string`);
3354
+ if (raw.level !== void 0 && !LEVELS2.has(raw.level)) fail(`${at}.level must be "error", "warn" or "info"`);
3355
+ if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
3356
+ if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
3357
+ for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
3358
+ if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
3359
+ const forbid = raw.forbid;
3360
+ for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
3361
+ if (!forbid.jsx && !forbid.imports && !forbid.pattern) fail(`${at}.forbid needs jsx, imports or pattern`);
3362
+ if (forbid.jsx !== void 0 && !(isStringList2(forbid.jsx) && forbid.jsx.every((n) => /^[A-Z][\w.]*$/.test(n)))) fail(`${at}.forbid.jsx must be a list of component names`);
3363
+ if (forbid.imports !== void 0 && !isStringList2(forbid.imports)) fail(`${at}.forbid.imports must be a list of import specifiers`);
3364
+ if (forbid.pattern !== void 0) checkPattern(forbid.pattern, `${at}.forbid.pattern`, fail);
3365
+ if (raw.unless !== void 0) {
3366
+ if (!isObject3(raw.unless)) fail(`${at}.unless must be an object`);
3367
+ const unless = raw.unless;
3368
+ for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
3369
+ if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
3370
+ if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
3371
+ }
3372
+ return raw;
3373
+ }
3374
+ function checkPattern(v, where2, fail) {
3375
+ if (typeof v !== "string" || !v) fail(`${where2} must be a regular expression`);
3376
+ try {
3377
+ toRegExp2(v, "g");
3378
+ } catch (err) {
3379
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
3380
+ }
3381
+ }
3382
+ var discoveryCache = /* @__PURE__ */ new Map();
3383
+ function readDeclaringPackage(dir, local) {
3384
+ const file = path18.join(dir, "package.json");
3385
+ let stamp;
3386
+ let real2;
3387
+ try {
3388
+ real2 = realpathSync(dir);
3389
+ stamp = `${real2}
3390
+ ${statSync(file).mtimeMs}
3391
+ ${local}`;
3392
+ } catch {
3393
+ return null;
3394
+ }
3395
+ const hit = discoveryCache.get(stamp);
3396
+ if (hit) return hit;
3397
+ let json;
3398
+ try {
3399
+ json = JSON.parse(readFileSync(file, "utf8"));
3400
+ } catch {
3401
+ return null;
3402
+ }
3403
+ if (typeof json.name !== "string" || !json.name) return null;
3404
+ const pkg = {
3405
+ name: json.name,
3406
+ version: typeof json.version === "string" ? json.version : "0.0.0",
3407
+ dir: path18.resolve(dir),
3408
+ namespace: ruleNamespace(json.name),
3409
+ local,
3410
+ private: json.private === true,
3411
+ declaration: null
3412
+ };
3413
+ const raw = json.genesis?.doctor;
3414
+ if (raw !== void 0) {
3415
+ const ignored = [];
3416
+ try {
3417
+ pkg.declaration = validateDeclaration(raw, json.name, path18.resolve(dir), ignored);
3418
+ if (ignored.length) pkg.ignored = ignored;
3419
+ } catch (err) {
3420
+ pkg.error = err.message;
3421
+ }
3422
+ }
3423
+ discoveryCache.set(stamp, pkg);
3424
+ return pkg;
3425
+ }
3426
+ function discoverPackages(root) {
3427
+ const byName = /* @__PURE__ */ new Map();
3428
+ const installed = [...installedGenesis(root).values()];
3429
+ for (const dir of installed) {
3430
+ const pkg = readDeclaringPackage(dir, false);
3431
+ if (pkg) byName.set(pkg.name, pkg);
3432
+ }
3433
+ for (const dir of installed) {
3434
+ let scope;
3435
+ try {
3436
+ scope = path18.dirname(realpathSync(dir));
3437
+ } catch {
3438
+ continue;
3439
+ }
3440
+ if (path18.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
3441
+ for (const entry of readdirSync(scope)) {
3442
+ if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
3443
+ const pkg = readDeclaringPackage(path18.join(scope, entry), false);
3444
+ if (pkg) byName.set(pkg.name, pkg);
3445
+ }
3446
+ }
3447
+ let local = [];
3448
+ try {
3449
+ local = localPackages(root);
3450
+ } catch {
3451
+ }
3452
+ for (const l of local) {
3453
+ const pkg = readDeclaringPackage(l.dir, true);
3454
+ if (pkg) byName.set(pkg.name, pkg);
3455
+ }
3456
+ return [...byName.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3457
+ }
3458
+ function preferRules(packages) {
3459
+ return packages.flatMap(
3460
+ (p) => (p.declaration?.prefer ?? []).map((r) => ({ ...r, ruleId: `${p.namespace}/${r.id}`, package: p.name, packageDir: p.dir }))
3461
+ );
3462
+ }
3463
+ var specMatcher = (s) => s.endsWith("*") ? (spec) => spec.startsWith(s.slice(0, -1)) : (spec) => spec === s;
3464
+ function compile(rule, setting, routes) {
3465
+ const expand = (globs) => globs.flatMap((g) => {
3466
+ if (!g.includes("{routes}")) return [g];
3467
+ return routes ? [g.replaceAll("{routes}", routes)] : [];
3468
+ });
3469
+ const files = expand(setting?.files ?? rule.files ?? SCRIPT_GLOBS);
3470
+ if (files.length === 0) return null;
3471
+ return {
3472
+ rule,
3473
+ level: rule.level ?? "warn",
3474
+ includes: globMatcher(files),
3475
+ excludes: globMatcher(expand(setting?.exclude ?? rule.exclude ?? [])),
3476
+ jsx: new Set(rule.forbid.jsx ?? []),
3477
+ imports: (rule.forbid.imports ?? []).map(specMatcher),
3478
+ ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
3479
+ unlessRenders: new Set(rule.unless?.renders ?? []),
3480
+ ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
3481
+ };
3482
+ }
3483
+ var JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
3484
+ var ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
3485
+ var SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
3486
+ function messageFor(rule, found) {
3487
+ const from = rule.import ? ` (${rule.import})` : "";
3488
+ const docs = rule.docs ? ` See ${rule.docs}` : "";
3489
+ return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
3490
+ }
3491
+ var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
3492
+ var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
3493
+ var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
3494
+ function wrappersIn(file, elements, c) {
3495
+ const out = /* @__PURE__ */ new Map();
3496
+ const decls = [...file.code.matchAll(TOP_LEVEL)];
3497
+ const listed = /* @__PURE__ */ new Map();
3498
+ for (const m of file.code.matchAll(EXPORT_LIST)) {
3499
+ for (const part of m[1].split(",")) {
3500
+ const [local, exported] = part.trim().split(/\s+as\s+/);
3501
+ if (local) listed.set(local, [...listed.get(local) ?? [], exported ?? local]);
3502
+ }
3503
+ }
3504
+ for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
3505
+ decls.forEach((d, i) => {
3506
+ const name = d[3];
3507
+ if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
3508
+ const end = decls[i + 1]?.index ?? file.code.length;
3509
+ const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
3510
+ if (!hit) return;
3511
+ const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
3512
+ for (const n of names) out.set(n, hit[1]);
3513
+ });
3514
+ return out;
3515
+ }
3516
+ function runPrefer(ctx, c) {
3517
+ const own = c.rule.packageDir;
3518
+ const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
3519
+ const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
3520
+ const wrappers = /* @__PURE__ */ new Map();
3521
+ const renderedBy = /* @__PURE__ */ new Map();
3522
+ for (const file of checked) {
3523
+ if (!JSX.has(file.ext)) continue;
3524
+ const elements = [...file.code.matchAll(ELEMENT)];
3525
+ renderedBy.set(file, elements);
3526
+ if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
3527
+ const found = wrappersIn(file, elements, c);
3528
+ if (found.size) wrappers.set(file.absolutePath, found);
3529
+ }
3530
+ for (const file of checked) {
3531
+ const elements = renderedBy.get(file) ?? [];
3532
+ if (exempt(file, elements.map((m) => m[1]))) continue;
3533
+ const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
3534
+ const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
3535
+ for (const m of elements) {
3536
+ const name = m[1];
3537
+ if (c.jsx.has(name)) {
3538
+ report(lineAt(file.code, m.index), name, `renders <${name}>`);
3539
+ continue;
3540
+ }
3541
+ const from = imported?.get(name.split(".")[0]);
3542
+ const around = from && !name.includes(".") ? wrappers.get(from.file)?.get(from.name) : void 0;
3543
+ if (around) report(lineAt(file.code, m.index), name, `renders <${name}>, an app wrapper around <${around}>`);
3544
+ }
3545
+ if (c.imports.length) {
3546
+ for (const { specifier, line } of importSpecifiers(file)) {
3547
+ if (c.imports.some((t) => t(specifier))) report(line, specifier, `imports ${specifier}`);
3548
+ }
3549
+ }
3550
+ if (c.pattern) {
3551
+ c.pattern.lastIndex = 0;
3552
+ for (const m of file.code.matchAll(c.pattern)) {
3553
+ const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
3554
+ report(lineAt(file.code, m.index), text, `has ${text}`);
3555
+ }
3556
+ }
3557
+ }
3558
+ }
3559
+ var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
3560
+ async function packageRulesPlugins(packages) {
3561
+ const out = [
3562
+ {
3563
+ name: "package-rules",
3564
+ check(ctx) {
3565
+ for (const p of packages) {
3566
+ const at = { rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name };
3567
+ if (p.error) ctx.report({ ...at, message: `${p.error}; its rules don't run` });
3568
+ for (const note of p.ignored ?? []) ctx.report({ ...at, message: `${note} (a newer @marktiderman/genesis-cli may read it)` });
3569
+ }
3570
+ const routes = routesDir(ctx);
3571
+ const settings = ctx.config.packageRules ?? {};
3572
+ for (const rule of preferRules(packages)) {
3573
+ if (rule.platform === "web" && isNative(ctx)) continue;
3574
+ if (rule.platform === "native" && !isNative(ctx)) continue;
3575
+ const compiled = compile(rule, settings[rule.ruleId], routes);
3576
+ if (compiled) runPrefer(ctx, compiled);
3577
+ }
3578
+ }
3579
+ }
3580
+ ];
3581
+ for (const p of packages) {
3582
+ const file = p.declaration?.plugin;
3583
+ if (!file) continue;
3584
+ let loaded;
3585
+ try {
3586
+ loaded = await loadPlugins([file], p.dir);
3587
+ } catch (err) {
3588
+ const message = err.message;
3589
+ out.push({ name: `${p.name} plugin`, check: (ctx) => ctx.report({ rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name, message }) });
3590
+ continue;
3591
+ }
3592
+ for (const plugin of loaded) {
3593
+ out.push({
3594
+ name: `${p.namespace}/${plugin.name}`,
3595
+ check: (ctx) => plugin.check({
3596
+ ...ctx,
3597
+ report: (f) => ctx.report({ ...f, rule: f.rule.startsWith(`${p.namespace}/`) ? f.rule : `${p.namespace}/${f.rule}` })
3598
+ })
3599
+ });
3600
+ }
3601
+ }
3602
+ return out;
3603
+ }
3604
+ function unknownPackageRuleSettings(config, packages, reported) {
3605
+ const known = /* @__PURE__ */ new Set([...packageRuleIds(packages), ...reported.map((f) => f.rule)]);
3606
+ const plugins = packages.filter((p) => p.declaration?.plugin).map((p) => `${p.namespace}/`);
3607
+ return Object.keys(config.packageRules ?? {}).filter((id) => !known.has(id) && !plugins.some((ns) => id.startsWith(ns))).map((id) => ({
3608
+ rule: "stale-exception",
3609
+ level: "warn",
3610
+ file: "genesis config",
3611
+ subject: id,
3612
+ message: `packageRules names ${id}, which no installed package declares; check the id (genesis primitives lists them) or remove it`
3613
+ }));
3614
+ }
3615
+ function packageRuleIds(packages) {
3616
+ return new Set(preferRules(packages).map((r) => r.ruleId));
3617
+ }
3618
+
3619
+ // src/doctor/packages.ts
3620
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3621
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3622
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3623
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3624
+ var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3625
+ function sourceFiles(dir, rel = "") {
3626
+ const out = [];
3627
+ for (const entry of readdirSync(path18.join(dir, rel)).sort()) {
3628
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3629
+ const child = rel ? `${rel}/${entry}` : entry;
3630
+ const stat = lstatSync(path18.join(dir, child));
3631
+ if (stat.isSymbolicLink()) continue;
3632
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3633
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3634
+ }
3635
+ return out;
3636
+ }
3637
+ function packageName2(specifier) {
3638
+ const parts = specifier.split("/");
3639
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3640
+ }
3641
+ function git(root, args) {
3642
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3643
+ return r.status === 0 ? r.stdout : null;
3644
+ }
3645
+ function matchPattern(pattern, spec) {
3646
+ const star = pattern.indexOf("*");
3647
+ if (star < 0) return pattern === spec ? "" : null;
3648
+ const head = pattern.slice(0, star);
3649
+ const tail = pattern.slice(star + 1);
3650
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3651
+ }
3652
+ function tsconfigPaths(dir) {
3653
+ const file = path18.join(dir, "tsconfig.json");
3654
+ if (!existsSync(file)) return [];
3655
+ try {
3656
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3657
+ const options = JSON.parse(text).compilerOptions ?? {};
3658
+ const base = path18.resolve(dir, options.baseUrl ?? ".");
3659
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path18.resolve(base, t)) }));
3660
+ } catch {
3661
+ return [];
3662
+ }
3663
+ }
3664
+ function checkImports2(ctx, pkg, json) {
3665
+ const aliases2 = tsconfigPaths(pkg.dir);
3666
+ const subpathImports = Object.keys(json.imports ?? {});
3667
+ const viaAlias = (spec) => {
3668
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3669
+ for (const { pattern, targets } of aliases2) {
3670
+ const hit = matchPattern(pattern, spec);
3671
+ if (hit === null) continue;
3672
+ return targets.some((t) => {
3673
+ const rel = path18.relative(pkg.dir, t.replace("*", hit));
3674
+ return !rel.startsWith("..") && !path18.isAbsolute(rel);
3675
+ });
3676
+ }
3677
+ return null;
3678
+ };
3679
+ const declared = /* @__PURE__ */ new Set([
3680
+ json.name,
3681
+ ...Object.keys(json.dependencies ?? {}),
3682
+ ...Object.keys(json.peerDependencies ?? {}),
3683
+ ...Object.keys(json.devDependencies ?? {}),
3684
+ ...Object.keys(json.optionalDependencies ?? {})
3685
+ ]);
3686
+ for (const file of sourceFiles(pkg.dir)) {
3687
+ const code = stripForImports(readFileSync(path18.join(pkg.dir, file), "utf8"));
3688
+ if (code === null) continue;
3689
+ const at = `${pkg.rel}/${file}`;
3690
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3691
+ let offset = 0;
3692
+ code.split("\n").forEach((text, i) => {
3693
+ const lineStart = offset;
3694
+ offset += text.length + 1;
3695
+ for (const m of text.matchAll(IMPORT)) {
2435
3696
  const spec = m[1];
2436
3697
  const line = i + 1;
2437
3698
  const at0 = lineStart + m.index;
@@ -2448,9 +3709,9 @@ function checkImports2(ctx, pkg, json) {
2448
3709
  continue;
2449
3710
  }
2450
3711
  if (spec.startsWith(".")) {
2451
- const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
2452
- const rel = path14.relative(pkg.dir, target);
2453
- if (rel.startsWith("..") || path14.isAbsolute(rel)) {
3712
+ const target = path18.resolve(pkg.dir, path18.dirname(file), spec);
3713
+ const rel = path18.relative(pkg.dir, target);
3714
+ if (rel.startsWith("..") || path18.isAbsolute(rel)) {
2454
3715
  ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} reaches outside its folder (${spec}); move what it needs into the package or a dependency` });
2455
3716
  }
2456
3717
  continue;
@@ -2472,12 +3733,12 @@ function checkMigrations(ctx, pkg, json) {
2472
3733
  if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
2473
3734
  if (typeof m.file === "string" && typeof m.test !== "string") {
2474
3735
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file} has no pgTAP test; declare one as "test" beside it` });
2475
- } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
3736
+ } else if (typeof m.test === "string" && !existsSync(path18.join(pkg.dir, m.test))) {
2476
3737
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test} doesn't exist` });
2477
3738
  }
2478
3739
  }
2479
3740
  }
2480
- const dir = path14.join(pkg.dir, "migrations");
3741
+ const dir = path18.join(pkg.dir, "migrations");
2481
3742
  if (!existsSync(dir)) return;
2482
3743
  const seen = /* @__PURE__ */ new Map();
2483
3744
  for (const name of readdirSync(dir).sort()) {
@@ -2486,7 +3747,7 @@ function checkMigrations(ctx, pkg, json) {
2486
3747
  const other = seen.get(m[1]);
2487
3748
  if (other) ctx.report({ rule: "package-migration-number", file: `${pkg.rel}/migrations/${name}`, subject: m[1], message: `${pkg.name}: ${name} and ${other} share the number ${m[1]}; give each migration its own` });
2488
3749
  else seen.set(m[1], name);
2489
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3750
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path18.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
2490
3751
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/migrations/${name}`, subject: name, message: `${pkg.name}: ${name} has no pgTAP test (migrations/tests/${name.replace(/\.sql$/, ".test.sql")})` });
2491
3752
  }
2492
3753
  }
@@ -2500,7 +3761,7 @@ function checkExports(ctx, pkg, json) {
2500
3761
  walk(json.exports);
2501
3762
  for (const t of targets) {
2502
3763
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
2503
- if (!existsSync(path14.join(pkg.dir, t))) {
3764
+ if (!existsSync(path18.join(pkg.dir, t))) {
2504
3765
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
2505
3766
  }
2506
3767
  }
@@ -2518,11 +3779,11 @@ function checkBlocks(ctx, pkg, json) {
2518
3779
  function checkTaggedTests(ctx, pkg) {
2519
3780
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
2520
3781
  if (!tests.length) return;
2521
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
3782
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path18.join(pkg.dir, f), "utf8")));
2522
3783
  if (!tagged) ctx.report({ rule: "package-untagged-tests", level: "warn", file: pkg.rel, message: `${pkg.name}'s tests name no feature; tag them with // @feat:<feature id>` });
2523
3784
  }
2524
3785
  function checkRegistered(ctx, pkg) {
2525
- const file = path14.join(ctx.root, "features.json");
3786
+ const file = path18.join(ctx.root, "features.json");
2526
3787
  if (!existsSync(file)) return;
2527
3788
  let doc;
2528
3789
  try {
@@ -2532,7 +3793,7 @@ function checkRegistered(ctx, pkg) {
2532
3793
  }
2533
3794
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2534
3795
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
2535
- if (top) forms.add(path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/"));
3796
+ if (top) forms.add(path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/"));
2536
3797
  const covered = (doc.features ?? []).some(
2537
3798
  (f) => (f.links?.code ?? []).some((c) => {
2538
3799
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -2562,9 +3823,9 @@ function mergeBaseOf(root, base) {
2562
3823
  function checkChanges(ctx, pkg, json, base, mergeBase) {
2563
3824
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2564
3825
  if (!top) return;
2565
- const appRelative = (fromTop) => path14.relative(realpathSync(ctx.root), path14.join(top, fromTop)).split(path14.sep).join("/");
2566
- const inRepo = path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/");
2567
- const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
3826
+ const appRelative = (fromTop) => path18.relative(realpathSync(ctx.root), path18.join(top, fromTop)).split(path18.sep).join("/");
3827
+ const inRepo = path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/");
3828
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell2, i) => i === 0 ? cell2 : appRelative(cell2)).join(" ")).join("\n");
2568
3829
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
2569
3830
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
2570
3831
  (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
@@ -2586,11 +3847,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2586
3847
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
2587
3848
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
2588
3849
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
2589
- const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path14.join(top, f)) : [];
3850
+ const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path18.join(top, f)) : [];
2590
3851
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
2591
3852
  const named = naming.length > 0;
2592
3853
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
2593
- ctx.report({ rule: "package-unversioned-change", level: "warn", file: path14.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
3854
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path18.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
2594
3855
  }
2595
3856
  let jsonBefore = null;
2596
3857
  try {
@@ -2600,7 +3861,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2600
3861
  }
2601
3862
  const raw = json;
2602
3863
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
2603
- const appInRepo = path14.relative(top, realpathSync(ctx.root)).split(path14.sep).join("/");
3864
+ const appInRepo = path18.relative(top, realpathSync(ctx.root)).split(path18.sep).join("/");
2604
3865
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
2605
3866
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
2606
3867
  if (!registry) ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s blocks or exports changed but features.ts didn't; update the features they belong to` });
@@ -2617,6 +3878,26 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2617
3878
  });
2618
3879
  }
2619
3880
  }
3881
+ var GENESIS_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
3882
+ function checkDoctorDeclaration(ctx, pkg, json) {
3883
+ if (json.private === true || !GENESIS_NAME.test(json.name)) return;
3884
+ const file = `${pkg.rel}/package.json`;
3885
+ const raw = json.genesis?.doctor;
3886
+ if (raw === void 0) {
3887
+ ctx.report({
3888
+ rule: "package-doctor-declaration",
3889
+ file,
3890
+ subject: json.name,
3891
+ message: `${json.name} declares no doctor rules; add genesis.doctor with the primitives it enforces ("prefer" rules), or { "enforce": false, "reason": "\u2026" }`
3892
+ });
3893
+ return;
3894
+ }
3895
+ try {
3896
+ validateDeclaration(raw, json.name, pkg.dir);
3897
+ } catch (err) {
3898
+ ctx.report({ rule: "package-doctor-declaration", file, subject: json.name, message: err.message });
3899
+ }
3900
+ }
2620
3901
  function checkPackagesPack(ctx) {
2621
3902
  let packages;
2622
3903
  try {
@@ -2632,13 +3913,14 @@ function checkPackagesPack(ctx) {
2632
3913
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
2633
3914
  }
2634
3915
  for (const pkg of packages) {
2635
- const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
3916
+ const json = JSON.parse(readFileSync(path18.join(pkg.dir, "package.json"), "utf8"));
2636
3917
  checkImports2(ctx, pkg, json);
2637
3918
  checkExports(ctx, pkg, json);
2638
3919
  checkBlocks(ctx, pkg, json);
2639
3920
  checkMigrations(ctx, pkg, json);
2640
3921
  checkTaggedTests(ctx, pkg);
2641
3922
  checkRegistered(ctx, pkg);
3923
+ checkDoctorDeclaration(ctx, pkg, json);
2642
3924
  if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
2643
3925
  }
2644
3926
  }
@@ -2803,30 +4085,30 @@ function gitView(root, dir, base) {
2803
4085
  const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2804
4086
  if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2805
4087
  const sql = (p) => p !== void 0 && p.endsWith(".sql");
2806
- const touched = new Set(untracked.split("\n").filter(sql));
4088
+ const touched2 = new Set(untracked.split("\n").filter(sql));
2807
4089
  const edited = [];
2808
4090
  for (const row of diff.split("\n").filter(Boolean)) {
2809
4091
  const [status, a, b] = row.split(" ");
2810
4092
  if (status.startsWith("R")) {
2811
- if (sql(b)) touched.add(b);
4093
+ if (sql(b)) touched2.add(b);
2812
4094
  if (sql(a)) edited.push({ file: a, status: "renamed" });
2813
4095
  continue;
2814
4096
  }
2815
4097
  if (!sql(a)) continue;
2816
- if (status.startsWith("A")) touched.add(a);
4098
+ if (status.startsWith("A")) touched2.add(a);
2817
4099
  else if (status.startsWith("M") || status.startsWith("T")) {
2818
- touched.add(a);
4100
+ touched2.add(a);
2819
4101
  edited.push({ file: a, status: "modified" });
2820
4102
  } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2821
4103
  }
2822
- return { touched, edited };
4104
+ return { touched: touched2, edited };
2823
4105
  }
2824
4106
  function checkSupabasePack(ctx) {
2825
4107
  const settings = ctx.config.supabase ?? {};
2826
4108
  const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2827
- const abs = path14.join(ctx.root, dir);
4109
+ const abs = path18.join(ctx.root, dir);
2828
4110
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2829
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
4111
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path18.join(abs, n), "utf8")) }));
2830
4112
  const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2831
4113
  const base = settings.base ?? DEFAULT_BASE;
2832
4114
  const view = gitView(ctx.root, dir, base);
@@ -2843,7 +4125,7 @@ function checkSupabasePack(ctx) {
2843
4125
  }
2844
4126
  }
2845
4127
  const since = settings.since;
2846
- const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
4128
+ const afterSince = (file) => since === void 0 || path18.posix.basename(file) >= since;
2847
4129
  if ("reason" in view && since === void 0) {
2848
4130
  ctx.report({
2849
4131
  rule: "migration-grants",
@@ -3095,7 +4377,7 @@ function checkDefinerSearchPath(ctx, migrations) {
3095
4377
  var UMBRELLA_PACKAGE = "@marktiderman/genesis";
3096
4378
  function readReleaseManifest(root) {
3097
4379
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
3098
- const file = dir && path14.join(dir, "dist", "versions.json");
4380
+ const file = dir && path18.join(dir, "dist", "versions.json");
3099
4381
  if (!file || !existsSync(file)) return null;
3100
4382
  return JSON.parse(readFileSync(file, "utf8"));
3101
4383
  }
@@ -3105,7 +4387,7 @@ function checkVersionSkew(ctx) {
3105
4387
  for (const [name, want] of Object.entries(manifest.packages)) {
3106
4388
  const dir = findPackageDir(ctx.root, name);
3107
4389
  if (!dir) continue;
3108
- const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
4390
+ const have = JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8")).version;
3109
4391
  if (have === want) continue;
3110
4392
  ctx.report({
3111
4393
  rule: "version-skew",
@@ -3116,12 +4398,12 @@ function checkVersionSkew(ctx) {
3116
4398
  });
3117
4399
  }
3118
4400
  }
3119
- var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4401
+ var GENESIS2 = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3120
4402
  var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3121
4403
  var NON_SHIPPING = /^(?:@marktiderman\/genesis-cli|vitest|@vitest\/.+|jest|jest-.+|@jest\/.+|ts-jest|babel-jest|mocha|ava|c8|nyc|@playwright\/test|playwright|cypress|@testing-library\/.+|happy-dom|jsdom|msw|@types\/.+|typescript|tsx|ts-node|eslint|eslint-.+|@eslint\/.+|@typescript-eslint\/.+|typescript-eslint|prettier|prettier-.+|@biomejs\/.+|oxlint|vite|@vitejs\/.+|vite-plugin-.+|webpack|webpack-.+|rollup|@rollup\/.+|esbuild|tsup|turbo|@storybook\/.+|storybook|@changesets\/.+|husky|lint-staged|wrangler|knip|concurrently|npm-run-all2?|rimraf|cross-env|dotenv-cli)$/;
3122
4404
  var readManifest = (dir) => {
3123
4405
  try {
3124
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
4406
+ return JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8"));
3125
4407
  } catch {
3126
4408
  return null;
3127
4409
  }
@@ -3135,18 +4417,18 @@ var real = (p) => {
3135
4417
  };
3136
4418
  var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
3137
4419
  function nodeModulesOf(dir) {
3138
- const parent = path14.dirname(dir);
3139
- return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
4420
+ const parent = path18.dirname(dir);
4421
+ return path18.basename(parent).startsWith("@") ? path18.dirname(parent) : parent;
3140
4422
  }
3141
4423
  function packagesIn(nodeModules) {
3142
4424
  if (!existsSync(nodeModules)) return [];
3143
4425
  const out = [];
3144
4426
  for (const entry of readdirSync(nodeModules)) {
3145
4427
  if (entry.startsWith(".")) continue;
3146
- const p = path14.join(nodeModules, entry);
4428
+ const p = path18.join(nodeModules, entry);
3147
4429
  if (entry.startsWith("@")) {
3148
4430
  try {
3149
- for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
4431
+ for (const sub of readdirSync(p)) out.push(path18.join(p, sub));
3150
4432
  } catch {
3151
4433
  }
3152
4434
  } else {
@@ -3158,7 +4440,7 @@ function packagesIn(nodeModules) {
3158
4440
  function genesisInstalls(root) {
3159
4441
  const copies = /* @__PURE__ */ new Map();
3160
4442
  const realRoot = real(root);
3161
- const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
4443
+ const rel = (abs) => path18.relative(realRoot, abs).split(path18.sep).join("/") || ".";
3162
4444
  const via = /* @__PURE__ */ new Map();
3163
4445
  const record = (real2, manifest, by, range, root2) => {
3164
4446
  let copy = copies.get(real2);
@@ -3178,7 +4460,7 @@ function genesisInstalls(root) {
3178
4460
  if (!manifest?.name) return;
3179
4461
  if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3180
4462
  const realDir = real(dir);
3181
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4463
+ if (GENESIS2.test(manifest.name)) record(realDir, manifest, by, range, kind);
3182
4464
  if (expanded.has(realDir)) return;
3183
4465
  expanded.add(realDir);
3184
4466
  queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
@@ -3203,7 +4485,7 @@ function genesisInstalls(root) {
3203
4485
  if (!dir) return null;
3204
4486
  if (!ownInstall || name in declared) return dir;
3205
4487
  const realDir = real(dir);
3206
- if (realDir.startsWith(realRoot + path14.sep)) return dir;
4488
+ if (realDir.startsWith(realRoot + path18.sep)) return dir;
3207
4489
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3208
4490
  };
3209
4491
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -3211,7 +4493,7 @@ function genesisInstalls(root) {
3211
4493
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3212
4494
  });
3213
4495
  const app = readManifest(root);
3214
- const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
4496
+ const ownInstall = LOCKFILES.some((f) => existsSync(path18.join(root, f)));
3215
4497
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3216
4498
  const declaredDev = Object.entries(app?.devDependencies ?? {});
3217
4499
  const runtimeDeps = {
@@ -3222,11 +4504,11 @@ function genesisInstalls(root) {
3222
4504
  };
3223
4505
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3224
4506
  walk("runtime", rootsOf(runtimeDeps, "the app"));
3225
- const top = path14.join(root, "node_modules");
4507
+ const top = path18.join(root, "node_modules");
3226
4508
  walk(
3227
4509
  "hoisted",
3228
4510
  packagesIn(top).filter((dir) => {
3229
- const name = path14.relative(top, dir).split(path14.sep).join("/");
4511
+ const name = path18.relative(top, dir).split(path18.sep).join("/");
3230
4512
  return !(name in runtimeDeps) && !(name in devDeps);
3231
4513
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3232
4514
  );
@@ -3268,13 +4550,13 @@ function checkDuplicatePackages(ctx) {
3268
4550
  }
3269
4551
  }
3270
4552
  function checkPeerRanges(ctx) {
3271
- const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
4553
+ const rel = (abs) => path18.relative(ctx.root, abs).split(path18.sep).join("/");
3272
4554
  for (const copies of genesisInstalls(ctx.root).values()) {
3273
4555
  for (const copy of copies) {
3274
4556
  const dir = copy.absolutePath;
3275
4557
  const peers = readManifest(dir)?.peerDependencies ?? {};
3276
4558
  for (const [peer, range] of Object.entries(peers)) {
3277
- if (!GENESIS.test(peer)) continue;
4559
+ if (!GENESIS2.test(peer)) continue;
3278
4560
  const peerDir = findPackageDir(dir, peer);
3279
4561
  const installed = peerDir && readManifest(peerDir)?.version;
3280
4562
  if (!peerDir || !installed) continue;
@@ -3291,126 +4573,20 @@ function checkPeerRanges(ctx) {
3291
4573
  }
3292
4574
  }
3293
4575
  }
3294
- var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3295
- var STEMS = {
3296
- tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3297
- "next-app": {
3298
- layout: /* @__PURE__ */ new Set(["layout"]),
3299
- index: /* @__PURE__ */ new Set(["page"]),
3300
- skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3301
- },
3302
- "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3303
- };
3304
- var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3305
- var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3306
- var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3307
- var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3308
- var OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
3309
- function routesDir(ctx) {
3310
- if (ctx.config.routesDir) return ctx.config.routesDir;
3311
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path14.join(ctx.root, d))) ?? null;
3312
- }
3313
- var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3314
- function flavorOf(dir, rels) {
3315
- const stems = rels.map((r) => r.split("/").pop());
3316
- if (stems.includes("__root")) return "tanstack";
3317
- if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3318
- if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3319
- return "tanstack";
3320
- }
3321
- function renders(code) {
3322
- const elements = renderedElements(code);
3323
- if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3324
- const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3325
- const named = COMPONENT_OPTION.exec(code)?.[1];
3326
- if (named && !definedHere(named)) return true;
3327
- if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3328
- const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3329
- return exported !== void 0 && !definedHere(exported);
3330
- }
3331
- function webRoutes(ctx) {
3332
- const dir = routesDir(ctx);
3333
- if (!dir) return [];
3334
- const candidates = ctx.files.filter((f) => JSX_EXTS2.has(f.ext) && f.path.startsWith(`${dir}/`)).map((file) => ({ file, rel: file.path.slice(dir.length + 1).replace(/\.[^.]+$/, "") }));
3335
- const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3336
- const stems = STEMS[flavor];
3337
- const groups = /* @__PURE__ */ new Map();
3338
- for (const { file, rel } of candidates) {
3339
- const parts = rel.split("/");
3340
- if (parts.some((p) => p.startsWith("-"))) continue;
3341
- if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3342
- if (flavor === "next-pages" && parts[0] === "api") continue;
3343
- if (stems.skip.test(parts.at(-1))) continue;
3344
- if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3345
- const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3346
- groups.set(id, [...groups.get(id) ?? [], file]);
3347
- }
3348
- const trail = trailFor(ctx);
3349
- const routes = [];
3350
- for (const [id, files] of groups) {
3351
- const parts = id.split("/");
3352
- const stem = parts.pop();
3353
- const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3354
- const named = stems.layout.has(stem) || stems.index.has(stem);
3355
- const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3356
- const segments = [...folders, ...own];
3357
- const tree = [...parts, ...own];
3358
- let index = stems.index.has(stem);
3359
- if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3360
- segments.pop();
3361
- tree.pop();
3362
- index = true;
3363
- }
3364
- const code = files.map((f) => f.code).join("\n");
3365
- const elements = renderedElements(code);
3366
- const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3367
- const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3368
- const layout = stems.layout.has(stem) || pathless || outlet;
3369
- const rendering = renders(code);
3370
- const ownContent = new RegExp(OWN_CONTENT).test(code);
3371
- const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3372
- const page = !pure && !pathless && (!layout || ownContent);
3373
- routes.push({
3374
- file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3375
- files,
3376
- segments,
3377
- tree,
3378
- index,
3379
- layout,
3380
- page,
3381
- detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3382
- redirectOnly: !rendering,
3383
- parents: []
3384
- });
3385
- }
3386
- for (const r of routes) {
3387
- const own = r.tree;
3388
- for (const p of routes) {
3389
- if (p === r || !p.layout) continue;
3390
- const n = p.tree.length;
3391
- if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3392
- if (key(own.slice(0, n)) !== key(p.tree)) continue;
3393
- if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3394
- r.parents.push(p);
3395
- }
3396
- r.parents.sort((a, b) => b.tree.length - a.tree.length);
3397
- }
3398
- return routes;
3399
- }
3400
-
3401
- // src/doctor/structure.ts
3402
- var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/ui/SKILL.md (Sub-navigation)";
3403
- var CONTAINER = /(?:Card|CardContent|Dialog|DialogContent|Sheet|SheetContent|Drawer|DrawerContent|Popover|PopoverContent|Modal|Accordion|AccordionContent|AccordionItem|Collapsible|CollapsibleContent|Tooltip|Menu|MenuContent|Panel|Table|TabsContent)$/;
3404
- var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
3405
- var SHELL = /<AppShell(?=[\s>/])/;
3406
- var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3407
- var PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
3408
- var EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
3409
- var PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
3410
- var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
3411
- var rendersRe = (names) => {
3412
- const list = [...names];
3413
- return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
4576
+
4577
+ // src/doctor/structure.ts
4578
+ var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/ui/SKILL.md (Sub-navigation)";
4579
+ var CONTAINER = /(?:Card|CardContent|Dialog|DialogContent|Sheet|SheetContent|Drawer|DrawerContent|Popover|PopoverContent|Modal|Accordion|AccordionContent|AccordionItem|Collapsible|CollapsibleContent|Tooltip|Menu|MenuContent|Panel|Table|TabsContent)$/;
4580
+ var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
4581
+ var SHELL = /<AppShell(?=[\s>/])/;
4582
+ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
4583
+ var PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
4584
+ var EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
4585
+ var PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
4586
+ var isNative2 = (ctx) => ctx.config.packs?.includes("native") ?? false;
4587
+ var rendersRe = (names) => {
4588
+ const list = [...names];
4589
+ return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
3414
4590
  };
3415
4591
  function routeReach(ctx, r, test2) {
3416
4592
  const trail = trailFor(ctx);
@@ -3429,7 +4605,7 @@ function insideShell(ctx, routes) {
3429
4605
  return (r) => !shell.has(r) && (anyShell || r.parents.some((p) => shell.has(p)));
3430
4606
  }
3431
4607
  function checkHandRolledSubNav(ctx) {
3432
- if (isNative(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
4608
+ if (isNative2(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
3433
4609
  const routes = webRoutes(ctx);
3434
4610
  if (routes.length === 0) return;
3435
4611
  const inShell = insideShell(ctx, routes);
@@ -3486,7 +4662,7 @@ function checkLocalGenesisCopies(ctx) {
3486
4662
  }
3487
4663
  }
3488
4664
  function checkResourceWorkspaces(ctx) {
3489
- if (isNative(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
4665
+ if (isNative2(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
3490
4666
  const header = /<AppShellPageHeader(?=[\s>/])/;
3491
4667
  const byFolder = /* @__PURE__ */ new Map();
3492
4668
  for (const r of webRoutes(ctx)) {
@@ -3511,7 +4687,7 @@ function checkResourceWorkspaces(ctx) {
3511
4687
  }
3512
4688
  }
3513
4689
  function checkPageLayouts(ctx) {
3514
- if (isNative(ctx)) return;
4690
+ if (isNative2(ctx)) return;
3515
4691
  const layouts = new Set(ctx.genesis.components.filter((n) => PAGE_LAYOUT.test(n)));
3516
4692
  for (const c of ctx.genesis.companions) for (const n of c.components) if (PAGE_LAYOUT.test(n)) layouts.add(n);
3517
4693
  if (layouts.size === 0) return;
@@ -3560,22 +4736,697 @@ function checkIsoDateSlices(ctx) {
3560
4736
  }
3561
4737
  }
3562
4738
 
3563
- // src/doctor/index.ts
4739
+ // src/upgrade/scope-names.ts
4740
+ var IMPORTS_GENESIS = /\bfrom\s*["']@marktiderman\/genesis[\w/-]*["']/;
4741
+ function maskComments(text) {
4742
+ const out = text.split("");
4743
+ let quote2 = null;
4744
+ for (let i = 0; i < text.length; i++) {
4745
+ const ch = text[i];
4746
+ if (quote2) {
4747
+ if (ch === "\\") i++;
4748
+ else if (ch === quote2) quote2 = null;
4749
+ continue;
4750
+ }
4751
+ if (ch === '"' || ch === "'" || ch === "`") {
4752
+ quote2 = ch;
4753
+ continue;
4754
+ }
4755
+ if (ch === "/" && (text[i + 1] === "/" || text[i + 1] === "*")) {
4756
+ const line = text[i + 1] === "/";
4757
+ const end = line ? text.indexOf("\n", i) === -1 ? text.length : text.indexOf("\n", i) : text.indexOf("*/", i + 2) === -1 ? text.length : text.indexOf("*/", i + 2) + 2;
4758
+ for (let k = i; k < end; k++) if (out[k] !== "\n") out[k] = " ";
4759
+ i = end - 1;
4760
+ }
4761
+ }
4762
+ return out.join("");
4763
+ }
4764
+ var within = (spans, at) => spans.some(([a, b]) => at >= a && at < b);
4765
+ function importedFromGenesis(text, name) {
4766
+ for (const m of text.matchAll(/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']@marktiderman\/genesis[\w/-]*["']/g)) {
4767
+ for (const part of m[1].split(",")) {
4768
+ const local = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
4769
+ if (local === name) return true;
4770
+ }
4771
+ }
4772
+ return false;
4773
+ }
4774
+ var OPEN = { "(": ")", "{": "}", "[": "]" };
4775
+ function matching(text, open) {
4776
+ const stack = [];
4777
+ let quote2 = null;
4778
+ for (let i = open; i < text.length; i++) {
4779
+ const ch = text[i];
4780
+ if (quote2) {
4781
+ if (ch === "\\") i++;
4782
+ else if (ch === quote2) quote2 = null;
4783
+ continue;
4784
+ }
4785
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
4786
+ else if (OPEN[ch]) stack.push(OPEN[ch]);
4787
+ else if (ch === ")" || ch === "}" || ch === "]") {
4788
+ stack.pop();
4789
+ if (stack.length === 0) return i + 1;
4790
+ }
4791
+ }
4792
+ return text.length;
4793
+ }
4794
+ function matchingBack(text, close) {
4795
+ let depth = 0;
4796
+ for (let i = close; i >= 0; i--) {
4797
+ const ch = text[i];
4798
+ if (ch === "}") depth++;
4799
+ else if (ch === "{") {
4800
+ depth--;
4801
+ if (depth === 0) return i;
4802
+ }
4803
+ }
4804
+ return 0;
4805
+ }
4806
+ function callSpans(text, name) {
4807
+ const out = [];
4808
+ for (const m of text.matchAll(new RegExp(`\\b${name}\\s*(?:<[^()]*?>)?\\s*\\(`, "g"))) {
4809
+ const open = m.index + m[0].length - 1;
4810
+ out.push([open, matching(text, open)]);
4811
+ }
4812
+ return out;
4813
+ }
4814
+ function typedObjectSpans(text, types) {
4815
+ const out = [];
4816
+ if (types.length === 0) return out;
4817
+ const names = `(?:(?:Partial|Readonly|Required|Pick|Omit)\\s*<\\s*)?(?:${types.join("|")})`;
4818
+ for (const m of text.matchAll(new RegExp(`:\\s*${names}\\b(?:<[^=]*?>)?[^=;{]*?=\\s*\\{`, "g"))) {
4819
+ const open = m.index + m[0].length - 1;
4820
+ out.push([open, matching(text, open)]);
4821
+ }
4822
+ for (const m of text.matchAll(new RegExp(`\\}\\s*(?:satisfies|as)\\s+${names}\\b`, "g"))) {
4823
+ const close = m.index;
4824
+ out.push([matchingBack(text, close), close + 1]);
4825
+ }
4826
+ return out;
4827
+ }
4828
+ function tagSpans(text, tag) {
4829
+ const out = [];
4830
+ for (const m of text.matchAll(new RegExp(`<${tag}\\b`, "g"))) {
4831
+ let depth = 0;
4832
+ let quote2 = null;
4833
+ let end = text.length;
4834
+ for (let i = m.index + 1; i < text.length; i++) {
4835
+ const ch = text[i];
4836
+ if (quote2) {
4837
+ if (ch === "\\") i++;
4838
+ else if (ch === quote2) quote2 = null;
4839
+ continue;
4840
+ }
4841
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
4842
+ else if (ch === "{") depth++;
4843
+ else if (ch === "}") depth--;
4844
+ else if (ch === ">" && depth === 0) {
4845
+ end = i + 1;
4846
+ break;
4847
+ }
4848
+ }
4849
+ out.push([m.index, end]);
4850
+ }
4851
+ return out;
4852
+ }
4853
+ function attributeObjectSpans(text, tag, attr) {
4854
+ const out = [];
4855
+ for (const [a, b] of tagSpans(text, tag)) {
4856
+ const inTag = text.slice(a, b);
4857
+ for (const m of inTag.matchAll(new RegExp(`\\s${attr}\\s*=\\s*\\{\\s*\\{`, "g"))) {
4858
+ const open = a + m.index + m[0].length - 1;
4859
+ out.push([open, matching(text, open)]);
4860
+ }
4861
+ }
4862
+ return out;
4863
+ }
4864
+ function zoneBindings(text, hook, type) {
4865
+ const names = /* @__PURE__ */ new Set();
4866
+ if (hook) {
4867
+ for (const m of text.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::\s*DisplayTimeZones\s*)?=\s*useDisplayTimeZones\(\)/g)) names.add(m[1]);
4868
+ }
4869
+ if (type) for (const m of text.matchAll(/\b([A-Za-z_$][\w$]*)\s*\??\s*:\s*DisplayTimeZones\b/g)) names.add(m[1]);
4870
+ return [...names];
4871
+ }
4872
+ var escape = (name) => name.replace(/\$/g, "\\$");
4873
+ function findRemovedScopeNames(source) {
4874
+ const text = maskComments(source);
4875
+ if (!IMPORTS_GENESIS.test(text)) return [];
4876
+ const out = [];
4877
+ const has = (name) => importedFromGenesis(text, name);
4878
+ const viewSpans = [
4879
+ ...has("defineView") ? callSpans(text, "defineView") : [],
4880
+ ...typedObjectSpans(text, ["ViewDefinition", "ViewField"].filter(has))
4881
+ ];
4882
+ for (const m of text.matchAll(/(\btimeZone\s*:\s*)(["'`])practice\2/g)) {
4883
+ const at = m.index + m[1].length;
4884
+ if (!within(viewSpans, at)) continue;
4885
+ out.push({ index: m.index, what: "timeZone-practice", instead: 'timeZone: "scope"', start: at + 1, end: at + 1 + "practice".length, replacement: "scope" });
4886
+ }
4887
+ if (has("resolveZone")) {
4888
+ for (const m of text.matchAll(/(\bresolveZone\(\s*)(["'`])practice\2/g)) {
4889
+ const at = m.index + m[1].length + 1;
4890
+ out.push({ index: m.index, what: "resolveZone-practice", instead: 'resolveZone("scope", \u2026)', start: at, end: at + "practice".length, replacement: "scope" });
4891
+ }
4892
+ }
4893
+ const propSpans = [
4894
+ ...has("NativeResourceView") ? tagSpans(text, "NativeResourceView") : [],
4895
+ ...typedObjectSpans(text, ["NativeResourceViewProps"].filter(has))
4896
+ ];
4897
+ for (const m of text.matchAll(/(^|[\s{,(])practiceTimeZone(\s*[=:])/gm)) {
4898
+ const at = m.index + m[1].length;
4899
+ if (!within(propSpans, at)) continue;
4900
+ out.push({ index: at, what: "practiceTimeZone", instead: "scopeTimeZone", start: at, end: at + "practiceTimeZone".length, replacement: "scopeTimeZone" });
4901
+ }
4902
+ const zoneSpans = [
4903
+ ...has("DisplayTimeZonesProvider") ? attributeObjectSpans(text, "DisplayTimeZonesProvider", "value") : [],
4904
+ ...typedObjectSpans(text, ["DisplayTimeZones"].filter(has))
4905
+ ];
4906
+ for (const m of text.matchAll(/(^|[\s{,])practice(\s*:)/gm)) {
4907
+ const at = m.index + m[1].length;
4908
+ if (!within(zoneSpans, at)) continue;
4909
+ out.push({ index: at, what: "DisplayTimeZones.practice", instead: "scope", start: at, end: at + "practice".length, replacement: "scope" });
4910
+ }
4911
+ for (const name of zoneBindings(text, has("useDisplayTimeZones"), has("DisplayTimeZones"))) {
4912
+ for (const m of text.matchAll(new RegExp(`(?<![\\w$])${escape(name)}\\s*\\??\\.\\s*(practice)(?![\\w$])`, "g"))) {
4913
+ const at = m.index + m[0].length - "practice".length;
4914
+ out.push({ index: m.index, what: "DisplayTimeZones.practice", instead: `${name}.scope`, start: at, end: at + "practice".length, replacement: "scope" });
4915
+ }
4916
+ }
4917
+ const seen = /* @__PURE__ */ new Set();
4918
+ return out.filter((f) => seen.has(f.start) ? false : (seen.add(f.start), true)).sort((a, b) => a.start - b.start);
4919
+ }
4920
+ function readsPracticeId(text) {
4921
+ if (!IMPORTS_GENESIS.test(text)) return [];
4922
+ return [...text.matchAll(/\bscope\s*\??\.\s*practiceId\b/g)].map((m) => m.index);
4923
+ }
4924
+ var augmentsResourceScope = (text) => /\binterface\s+ResourceScope\b/.test(text);
4925
+ var PRACTICE_ID_AUGMENTATION = 'declare module "@marktiderman/genesis-core" { interface ResourceScope { practiceId?: string } }';
4926
+
4927
+ // src/upgrade/codemods.ts
4928
+ var SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
4929
+ var SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
4930
+ var MAX_BYTES = 2 * 1024 * 1024;
4931
+ function appScripts(root) {
4932
+ const out = [];
4933
+ const walk = (dir) => {
4934
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
4935
+ const abs = path18.join(dir, entry.name);
4936
+ if (entry.isDirectory()) {
4937
+ if (!SKIP_DIRS3.has(entry.name)) walk(abs);
4938
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
4939
+ out.push(path18.relative(root, abs).split(path18.sep).join("/"));
4940
+ }
4941
+ }
4942
+ };
4943
+ walk(root);
4944
+ return out;
4945
+ }
4946
+
4947
+ // src/doctor/api-usage.ts
4948
+ var SCRIPT_EXTS5 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
4949
+ function openingTag(code, start) {
4950
+ let depth = 0;
4951
+ let quote2 = null;
4952
+ for (let i = start + 1; i < code.length; i++) {
4953
+ const ch = code[i];
4954
+ if (quote2) {
4955
+ if (ch === "\\") i++;
4956
+ else if (ch === quote2) quote2 = null;
4957
+ continue;
4958
+ }
4959
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
4960
+ else if (ch === "{") depth++;
4961
+ else if (ch === "}") depth--;
4962
+ else if (ch === ">" && depth === 0) return code.slice(start, i + 1);
4963
+ }
4964
+ return code.slice(start);
4965
+ }
4966
+ function ownAttributes(tag) {
4967
+ let depth = 0;
4968
+ let quote2 = null;
4969
+ let out = "";
4970
+ let inner = "";
4971
+ for (let i = 0; i < tag.length; i++) {
4972
+ const ch = tag[i];
4973
+ if (depth > 0) inner += ch;
4974
+ if (quote2) {
4975
+ if (ch === "\\") {
4976
+ i++;
4977
+ if (depth > 0) inner += tag[i] ?? "";
4978
+ else out += ch + (tag[i] ?? "");
4979
+ continue;
4980
+ }
4981
+ if (ch === quote2) quote2 = null;
4982
+ if (depth === 0) out += ch;
4983
+ continue;
4984
+ }
4985
+ if (ch === '"' || ch === "'" || ch === "`") {
4986
+ quote2 = ch;
4987
+ if (depth === 0) out += ch;
4988
+ } else if (ch === "{") {
4989
+ if (depth === 0) inner = "";
4990
+ depth++;
4991
+ } else if (ch === "}") {
4992
+ depth--;
4993
+ if (depth === 0) {
4994
+ const body = inner.slice(0, -1).trim();
4995
+ out += /^(["'`])[^"'`]*\1$/.test(body) ? `{${body}}` : "{}";
4996
+ }
4997
+ } else if (depth === 0) out += ch;
4998
+ }
4999
+ return out;
5000
+ }
5001
+ function checkTreeViews(ctx) {
5002
+ for (const file of ctx.files) {
5003
+ if (!SCRIPT_EXTS5.has(file.ext) || !/\btree\s*=/.test(file.code)) continue;
5004
+ for (const m of file.code.matchAll(/<(ResourceView|ResourcePage)\b(?:\s*<[^<>]*>)?/g)) {
5005
+ const tag = openingTag(file.code, (m.index ?? 0) + m[0].length - 1);
5006
+ const attrs = ownAttributes(tag);
5007
+ if (!/\stree\s*=/.test(attrs) || !/\spagination\s*=/.test(attrs)) continue;
5008
+ const paging = attrs.match(/\spagination\s*=\s*(?:\{\s*)?["'`](server|cursor)["'`]/);
5009
+ if (!paging) continue;
5010
+ ctx.report({
5011
+ rule: "resource-view-tree",
5012
+ level: "error",
5013
+ file: file.path,
5014
+ line: lineAt(file.code, m.index ?? 0),
5015
+ subject: m[1],
5016
+ message: `${m[1]} has \`tree\` with pagination="${paging[1]}", which throws when it renders: a tree is built from every row on the client. Leave pagination unset (docs/RESOURCE-VIEW.md, "Tree mode")`
5017
+ });
5018
+ }
5019
+ }
5020
+ }
5021
+ var STUDIO_SERVER = "@marktiderman/genesis-studio-server";
5022
+ var DEEP = /\b(?:from|import|require)\s*\(?\s*["']@marktiderman\/genesis-studio-server\/(dist|src|lib)\/[^"']*["']/g;
5023
+ var ROOT_REQUIRE = /\brequire\s*\(\s*["']@marktiderman\/genesis-studio-server["']\s*\)/g;
5024
+ function moduleFiles(ctx) {
5025
+ const scanned = new Set(ctx.files.map((f) => f.path));
5026
+ const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
5027
+ const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path18.join(ctx.root, rel), "utf8"), true) }));
5028
+ return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
5029
+ }
5030
+ function checkStudioServerImports(ctx) {
5031
+ for (const file of moduleFiles(ctx)) {
5032
+ if (!file.code.includes(STUDIO_SERVER)) continue;
5033
+ for (const m of file.code.matchAll(DEEP)) {
5034
+ ctx.report({
5035
+ rule: "studio-server-auth-import",
5036
+ level: "warn",
5037
+ file: file.path,
5038
+ line: lineAt(file.code, m.index ?? 0),
5039
+ subject: `${STUDIO_SERVER}/${m[1]}`,
5040
+ message: `imports a studio-server file the package doesn't export, which fails at run time; the token checks and switchToUser are in ${STUDIO_SERVER}/auth (import or require)`
5041
+ });
5042
+ }
5043
+ for (const m of file.code.matchAll(ROOT_REQUIRE)) {
5044
+ ctx.report({
5045
+ rule: "studio-server-auth-import",
5046
+ level: "warn",
5047
+ file: file.path,
5048
+ line: lineAt(file.code, m.index ?? 0),
5049
+ subject: STUDIO_SERVER,
5050
+ message: `requires ${STUDIO_SERVER}, which is ESM-only and fails under require(); ${STUDIO_SERVER}/auth (the token checks and switchToUser) ships for require too`
5051
+ });
5052
+ }
5053
+ }
5054
+ }
5055
+ var REMOVED_WORDS = {
5056
+ "timeZone-practice": 'timeZone "practice"',
5057
+ "resolveZone-practice": 'resolveZone("practice")',
5058
+ practiceTimeZone: "practiceTimeZone",
5059
+ "DisplayTimeZones.practice": "DisplayTimeZones.practice"
5060
+ };
5061
+ function checkRemovedScopeNames(ctx) {
5062
+ let augmentedMemo;
5063
+ const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path18.join(ctx.root, rel), "utf8")));
5064
+ for (const file of ctx.files) {
5065
+ if (!SCRIPT_EXTS5.has(file.ext)) continue;
5066
+ for (const hit of findRemovedScopeNames(file.code)) {
5067
+ ctx.report({
5068
+ rule: "removed-scope-name",
5069
+ level: "error",
5070
+ file: file.path,
5071
+ line: lineAt(file.code, hit.index),
5072
+ subject: REMOVED_WORDS[hit.what] ?? hit.what,
5073
+ message: `${REMOVED_WORDS[hit.what] ?? hit.what} was removed in genesis-core 2; use ${hit.instead}. \`genesis codemod genesis-core-2-scope-names\` rewrites every one`
5074
+ });
5075
+ }
5076
+ const reads = readsPracticeId(file.code);
5077
+ if (!reads.length || augmented()) continue;
5078
+ for (const index of reads) {
5079
+ ctx.report({
5080
+ rule: "scope-practice-id",
5081
+ level: "info",
5082
+ file: file.path,
5083
+ line: lineAt(file.code, index),
5084
+ subject: "practiceId",
5085
+ message: `scope.practiceId is the app's own scope key now, read as unknown; type it once: ${PRACTICE_ID_AUGMENTATION}`
5086
+ });
5087
+ }
5088
+ }
5089
+ }
5090
+ function git3(root, args) {
5091
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
5092
+ return r.status === 0 ? r.stdout : null;
5093
+ }
5094
+ function changedSince(root, base) {
5095
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5096
+ if (!mergeBase) return null;
5097
+ const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
5098
+ const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
5099
+ if (committed === null || untracked === null) return null;
5100
+ return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
5101
+ }
5102
+ var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
5103
+ function showAt(dir, rev, file) {
5104
+ const at = `${rev}:./${file}`;
5105
+ if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
5106
+ return git3(dir, ["show", at]);
5107
+ }
5108
+ function configAtBase(root, base, explicitFile) {
5109
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5110
+ if (!mergeBase) return null;
5111
+ const candidates = explicitFile ? [{ dir: path18.dirname(explicitFile), file: path18.basename(explicitFile), explicit: true }] : [
5112
+ { dir: root, file: "genesis.config.json", explicit: false },
5113
+ { dir: root, file: "package.json", explicit: false }
5114
+ ];
5115
+ for (const c of candidates) {
5116
+ const text = showAt(c.dir, mergeBase, c.file);
5117
+ if (text === null) return null;
5118
+ if (text === void 0) continue;
5119
+ let block;
5120
+ try {
5121
+ block = doctorBlock(JSON.parse(text), c.file, c.explicit);
5122
+ } catch {
5123
+ return null;
5124
+ }
5125
+ if (block === void 0 || c.file === "package.json" && !c.explicit && isPackageDeclaration(block)) {
5126
+ if (c.file === "genesis.config.json") return "absent";
5127
+ continue;
5128
+ }
5129
+ const b = objectOr(block);
5130
+ return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
5131
+ }
5132
+ return "absent";
5133
+ }
5134
+ var allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
5135
+ function allowGrew(allow, before, base) {
5136
+ const had = new Set(before.map(allowKey));
5137
+ return allow.filter((a) => !had.has(allowKey(a))).map((a) => ({
5138
+ rule: "allow-grew",
5139
+ file: a.file ?? "genesis config",
5140
+ subject: a.rule,
5141
+ message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
5142
+ }));
5143
+ }
5144
+ var RANK = { off: 0, info: 1, warn: 2, error: 3 };
5145
+ function rulesWeakened(config, before, base) {
5146
+ const out = [];
5147
+ const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
5148
+ const ids = /* @__PURE__ */ new Set([...Object.keys(config.rules ?? {}), ...Object.keys(config.packageRules ?? {})]);
5149
+ for (const rule of ids) {
5150
+ const set = levelIn(config, rule);
5151
+ if (set === void 0) continue;
5152
+ const was = levelIn(before, rule);
5153
+ if (was === void 0 ? set === "off" : RANK[set] < RANK[was]) {
5154
+ out.push({ rule: "rules-weakened", file: "genesis config", subject: rule, message: `${rule} is set to "${set}"${was ? `, lower than "${was}"` : ""} since ${base}; rules only tighten, so fix what it finds instead` });
5155
+ }
5156
+ }
5157
+ for (const [rule, setting] of Object.entries(config.packageRules ?? {})) {
5158
+ const had = new Set(before.packageRules[rule]?.exclude ?? []);
5159
+ const added = (setting.exclude ?? []).filter((g) => !had.has(g));
5160
+ if (added.length) {
5161
+ out.push({ rule: "rules-weakened", file: "genesis config", subject: rule, message: `packageRules excludes ${added.join(", ")} from ${rule} since ${base}; rules only tighten, so fix what it finds instead` });
5162
+ }
5163
+ }
5164
+ return out;
5165
+ }
5166
+ function touched(file, changed) {
5167
+ if (changed.has(file)) return true;
5168
+ const prefix = file.endsWith("/") ? file : `${file}/`;
5169
+ for (const c of changed) if (c.startsWith(prefix)) return true;
5170
+ return false;
5171
+ }
5172
+ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
5173
+ ...META_RULES,
5174
+ "stale-exception",
5175
+ "package-rule-override",
5176
+ "package-rules-invalid",
5177
+ "package-doctor-declaration",
5178
+ "plugin-error",
5179
+ "build",
5180
+ "agent-guide-stale",
5181
+ "contracts-stale"
5182
+ ]);
5183
+ function applyRatchet(findings, options) {
5184
+ const { config, newOnly, changed, base, isAppPath } = options;
5185
+ const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
5186
+ return findings.map((f) => {
5187
+ if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
5188
+ return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
5189
+ });
5190
+ }
5191
+ var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
5192
+ var DEFAULT_DATABASE_ENV = "DATABASE_URL";
5193
+ var shellArg = (s) => /^[\w./,@:+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
5194
+ var postgresSource = (schemas) => `Postgres (${schemas.join(", ")})`;
5195
+ async function postgresContract(url, schemas) {
5196
+ const { introspectPostgres: introspectPostgres2, emitContracts: emitContracts2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
5197
+ const { default: postgres } = await import('postgres');
5198
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {
5199
+ } });
5200
+ try {
5201
+ const tables = await introspectPostgres2(sql, schemas);
5202
+ return { content: emitContracts2(tables, { source: postgresSource(schemas) }), tables: tables.length };
5203
+ } finally {
5204
+ await sql.end();
5205
+ }
5206
+ }
5207
+ function contractSource(content) {
5208
+ return /^\/\/ Source: (.*)$/m.exec(content.slice(0, 2e3))?.[1]?.trim() ?? null;
5209
+ }
5210
+ function sourceSchemas(source) {
5211
+ const m = source === null ? null : /^Postgres \((.*)\)$/.exec(source);
5212
+ const schemas = m?.[1].split(",").map((s) => s.trim()).filter(Boolean);
5213
+ return schemas?.length ? schemas : null;
5214
+ }
5215
+ var lf = (text) => text.replace(/\r\n/g, "\n");
5216
+ async function checkContracts(ctx, read2 = postgresContract) {
5217
+ const settings = ctx.config.contracts;
5218
+ if (!settings) return;
5219
+ const out = settings.out ?? DEFAULT_CONTRACT_OUT;
5220
+ const env = settings.databaseEnv ?? DEFAULT_DATABASE_ENV;
5221
+ let current = null;
5222
+ try {
5223
+ current = lf(readFileSync(path18.join(ctx.root, out), "utf8"));
5224
+ } catch {
5225
+ current = null;
5226
+ }
5227
+ const source = current === null ? null : contractSource(current);
5228
+ if (source !== null && !source.startsWith("Postgres (")) {
5229
+ ctx.report({ rule: "contracts-stale", level: "info", file: out, message: `not checked: it was generated from ${source.split(" ")[0]}, and the doctor compares only contracts read from Postgres; check it with genesis introspect --check and the same source` });
5230
+ return;
5231
+ }
5232
+ const schemas = settings.schemas?.length ? settings.schemas : sourceSchemas(source) ?? ["public"];
5233
+ const url = process.env[env];
5234
+ if (!url) {
5235
+ ctx.report({ rule: "contracts-stale", level: "info", file: out, message: `not checked: set ${env} to the database URL to compare it with the database (as genesis introspect --check)` });
5236
+ return;
5237
+ }
5238
+ let expected;
5239
+ try {
5240
+ expected = lf((await read2(url, schemas)).content);
5241
+ } catch (err) {
5242
+ const generation = err.name === "EmitError";
5243
+ const message = err.message.split("\n")[0];
5244
+ ctx.report({ rule: "contracts-stale", level: generation ? "error" : "warn", file: out, message: generation ? `couldn't be generated: ${message}` : `couldn't read the database through ${env}: ${message}` });
5245
+ return;
5246
+ }
5247
+ const target = path18.relative(process.cwd(), path18.join(ctx.root, out)) || out;
5248
+ const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
5249
+ if (current !== expected) {
5250
+ ctx.report({
5251
+ rule: "contracts-stale",
5252
+ file: out,
5253
+ message: current === null ? `doesn't exist; run ${command} and commit it` : `is out of date with the database; run ${command} and commit the result`
5254
+ });
5255
+ }
5256
+ }
5257
+ var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
5258
+ var CORE = [
5259
+ {
5260
+ need: "anything, before building it",
5261
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
5262
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5263
+ from: "genesis-cli"
5264
+ },
5265
+ {
5266
+ need: "a page inside the app shell",
5267
+ use: "a Genesis page layout (`DashboardPage`, `SettingsPage`, `FormPage`, `DetailPage`, from `@marktiderman/genesis-ui`) or `ResourceView` (from `@marktiderman/genesis-ui/data`)",
5268
+ import: "@marktiderman/genesis-ui",
5269
+ rule: "page-layout",
5270
+ from: "genesis-cli"
5271
+ },
5272
+ {
5273
+ need: "a button, input, table, dialog or other component",
5274
+ use: "the Genesis component, never the raw tag or a local copy",
5275
+ import: "@marktiderman/genesis-ui/<component>",
5276
+ rule: "raw-tag",
5277
+ from: "genesis-cli"
5278
+ },
5279
+ {
5280
+ need: "colors and spacing",
5281
+ use: "semantic tokens (`bg-primary`, `text-muted-foreground`), never literal colors",
5282
+ import: "@marktiderman/genesis-design-system",
5283
+ rule: "raw-color",
5284
+ from: "genesis-cli"
5285
+ },
5286
+ {
5287
+ need: "something no primitive covers",
5288
+ use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
5289
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5290
+ from: "genesis-cli"
5291
+ }
5292
+ ];
5293
+ function primitivesCatalog(packages) {
5294
+ const rows = [...CORE];
5295
+ for (const rule of preferRules(packages)) {
5296
+ rows.push({
5297
+ need: rule.need ?? rule.id.replace(/-/g, " "),
5298
+ use: rule.use,
5299
+ ...rule.import ? { import: rule.import } : {},
5300
+ ...rule.docs ? { docs: rule.docs } : {},
5301
+ rule: rule.ruleId,
5302
+ from: rule.package
5303
+ });
5304
+ }
5305
+ for (const p of packages) {
5306
+ for (const e of p.declaration?.primitives ?? []) {
5307
+ rows.push({ need: e.need, use: e.use, ...e.import ? { import: e.import } : {}, ...e.docs ? { docs: e.docs } : {}, from: p.name });
5308
+ }
5309
+ }
5310
+ return rows;
5311
+ }
5312
+ function primitivesSummary(packages) {
5313
+ const rules = preferRules(packages);
5314
+ const withPlugin = packages.filter((p) => p.declaration?.plugin);
5315
+ return { rules: rules.length + withPlugin.length, packages: (/* @__PURE__ */ new Set([...rules.map((r) => r.package), ...withPlugin.map((p) => p.name)])).size };
5316
+ }
5317
+ var cell = (s) => (s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ").replace(/(`[^`]*`)|<([A-Za-z][\w.]*)>/g, (m, code, name) => code ?? `\`<${name}>\``);
5318
+ var importCell = (s) => `\`${s.replace(/`/g, "").replace(/\|/g, "\\|").replace(/\n/g, " ")}\``;
5319
+ function catalogTable(rows, options = {}) {
5320
+ const head = options.docs ? "| Need | Use | Import | Enforced by | Docs |\n| --- | --- | --- | --- | --- |" : "| Need | Use | Import |\n| --- | --- | --- |";
5321
+ const body = rows.map(
5322
+ (r) => options.docs ? `| ${cell(r.need)} | ${cell(r.use)} | ${r.import ? importCell(r.import) : ""} | ${r.rule ? `\`${r.rule}\`` : ""} | ${r.docs ? `[docs](${r.docs})` : ""} |` : `| ${cell(r.need)} | ${cell(r.use)} | ${r.import ? importCell(r.import) : ""} |`
5323
+ );
5324
+ return [head, ...body].join("\n");
5325
+ }
5326
+ var SKILL_PATH = ".claude/skills/genesis/SKILL.md";
5327
+ var AGENTS_START = "<!-- genesis-primitives:start -->";
5328
+ var AGENTS_END = "<!-- genesis-primitives:end -->";
5329
+ var RULES = [
5330
+ "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
5331
+ "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
5332
+ "A list screen is a view (`defineView`) rendered by `ResourceView`; a record page is `ResourceWorkspace`; on the phone, `NativeResourceView`.",
5333
+ "Screens never call the database client (`supabase.from`, `.rpc`) directly: reads go through a view or a named data function, writes through the resource's provider rules.",
5334
+ "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
5335
+ "Run `genesis doctor` before you finish; it enforces these rules."
5336
+ ];
5337
+ function renderSkill(rows) {
5338
+ return [
5339
+ "---",
5340
+ "name: genesis",
5341
+ "description: Which Genesis primitive to use for each need (list screens, record pages, forms, data access, dates and more), with its import and docs. Load before writing any screen, list, form or data access in a Genesis app.",
5342
+ "---",
5343
+ "",
5344
+ "<!-- Generated by `genesis agents` from the installed Genesis packages. Don't edit; run `genesis agents` after upgrading Genesis. -->",
5345
+ "",
5346
+ "# Genesis primitives",
5347
+ "",
5348
+ ...RULES.map((r) => `- ${r}`),
5349
+ "",
5350
+ "## What to use for each need",
5351
+ "",
5352
+ catalogTable(rows, { docs: true }),
5353
+ "",
5354
+ "`genesis primitives` prints the same list; `genesis doctor` enforces the rules named above.",
5355
+ ""
5356
+ ].join("\n");
5357
+ }
5358
+ function renderAgentsBlock(rows) {
5359
+ return [
5360
+ AGENTS_START,
5361
+ "## Building with Genesis",
5362
+ "",
5363
+ "Generated by `genesis agents` from the installed Genesis packages. Don't edit this block; run `genesis agents` after upgrading Genesis.",
5364
+ "",
5365
+ `Before writing a screen, read \`${SKILL_PATH}\` (or run \`genesis primitives\`).`,
5366
+ "",
5367
+ ...RULES.map((r) => `- ${r}`),
5368
+ "",
5369
+ catalogTable(rows),
5370
+ AGENTS_END
5371
+ ].join("\n");
5372
+ }
5373
+ function blockSpan(text) {
5374
+ const s = text.indexOf(AGENTS_START);
5375
+ const e = text.indexOf(AGENTS_END);
5376
+ if (s < 0 && e < 0) return "absent";
5377
+ if (s < 0 || e < 0 || e < s || text.indexOf(AGENTS_START, s + 1) >= 0 || text.indexOf(AGENTS_END, e + 1) >= 0) return "broken";
5378
+ return { start: s, end: e + AGENTS_END.length };
5379
+ }
5380
+ function currentAgentsBlock(agents) {
5381
+ if (!agents) return null;
5382
+ const span = blockSpan(agents);
5383
+ if (span === "absent") return null;
5384
+ if (span === "broken") return "broken";
5385
+ return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
5386
+ }
5387
+ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
5388
+ function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
5389
+ const rows = primitivesCatalog(packages);
5390
+ const skill = read(path18.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
5391
+ const block = currentAgentsBlock(read(path18.join(root, agentsFile)));
5392
+ return {
5393
+ skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
5394
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
5395
+ };
5396
+ }
5397
+ function checkAgentGuide(ctx) {
5398
+ const state = agentGuideState(ctx.root, ctx.packages);
5399
+ if (state.skill === "missing" && state.agents === "missing") return;
5400
+ const fix = "run genesis agents and commit the result";
5401
+ if (state.skill !== "ok") {
5402
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: SKILL_PATH, message: `${state.skill === "missing" ? "is missing" : "doesn't match the installed Genesis packages"}; ${fix}` });
5403
+ }
5404
+ if (state.agents !== "ok") {
5405
+ const message = {
5406
+ missing: `has no genesis-primitives block; ${fix}`,
5407
+ broken: `has a broken genesis-primitives block (a ${AGENTS_START} or ${AGENTS_END} marker is missing, repeated or out of order); fix the markers by hand, then ${fix}`,
5408
+ stale: `has a genesis-primitives block that doesn't match the installed Genesis packages; ${fix}`
5409
+ }[state.agents];
5410
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
5411
+ }
5412
+ }
3564
5413
  async function runDoctor(options = {}) {
3565
- const root = path14.resolve(options.root ?? process.cwd());
5414
+ const root = path18.resolve(options.root ?? process.cwd());
3566
5415
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
3567
5416
  const config = loaded.config;
3568
5417
  const genesis = options.genesis ?? loadGenesis(root, config);
3569
5418
  const files = scanFiles(root, config);
3570
5419
  const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
3571
5420
  const plugins = await loadPlugins(config.plugins, loaded.dir);
5421
+ const packages = discoverPackages(root);
5422
+ const packagePlugins = await packageRulesPlugins(packages);
3572
5423
  const builtinIds = new Set(BUILTIN_RULES);
3573
5424
  for (const p of config.patterns ?? []) {
3574
- if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
5425
+ if (builtinIds.has(p.id) || META_RULES.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
3575
5426
  }
3576
5427
  const raw = [];
3577
- const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3578
- for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
5428
+ const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
5429
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
3579
5430
  try {
3580
5431
  await plugin.check(ctx);
3581
5432
  } catch (err) {
@@ -3587,7 +5438,34 @@ async function runDoctor(options = {}) {
3587
5438
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
3588
5439
  if (failure) raw.push(failure);
3589
5440
  }
3590
- const findings = applyConfig(raw, config);
5441
+ raw.push(...unknownPackageRuleSettings(config, packages, raw));
5442
+ const newOnly = /* @__PURE__ */ new Set([...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
5443
+ let changed = null;
5444
+ let skipped = false;
5445
+ if (options.base && (newOnly.size > 0 || config.ratchet)) {
5446
+ changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
5447
+ skipped ||= !changed;
5448
+ }
5449
+ const configFile = "file" in loaded ? loaded.file : null;
5450
+ const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
5451
+ let configSkipped = false;
5452
+ if (options.base && configFile) {
5453
+ const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
5454
+ if (before && before !== "absent") {
5455
+ raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
5456
+ raw.push(...rulesWeakened(config, before, options.base));
5457
+ }
5458
+ configSkipped = !before && guarded;
5459
+ }
5460
+ if (skipped || configSkipped) {
5461
+ raw.push(
5462
+ configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
5463
+ );
5464
+ }
5465
+ let findings = applyConfig(raw, config, packageRuleIds(packages));
5466
+ if (options.base && changed) {
5467
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path18.join(root, f)) });
5468
+ }
3591
5469
  const errors = findings.filter((f) => f.level === "error").length;
3592
5470
  const warnings = findings.filter((f) => f.level === "warn").length;
3593
5471
  const infos = findings.length - errors - warnings;
@@ -3598,12 +5476,13 @@ async function runDoctor(options = {}) {
3598
5476
  findings,
3599
5477
  unused: unusedComponents(ctx),
3600
5478
  ruleCount: (patterns?.count ?? 0) + plugins.length,
5479
+ primitives: primitivesSummary(packages),
3601
5480
  errors,
3602
5481
  warnings,
3603
5482
  infos
3604
5483
  };
3605
5484
  }
3606
- function builtinChecks(config) {
5485
+ function builtinChecks(config, options = {}) {
3607
5486
  const packs = {
3608
5487
  native: { name: "native", check: checkNativePack },
3609
5488
  supabase: { name: "supabase", check: checkSupabasePack },
@@ -3624,14 +5503,31 @@ function builtinChecks(config) {
3624
5503
  { name: "resource-workspaces", check: checkResourceWorkspaces },
3625
5504
  { name: "page-layouts", check: checkPageLayouts },
3626
5505
  { name: "iso-date-slices", check: checkIsoDateSlices },
3627
- ...(config.packs ?? []).map((p) => packs[p])
5506
+ { name: "resource-view-trees", check: checkTreeViews },
5507
+ { name: "studio-server-imports", check: checkStudioServerImports },
5508
+ { name: "removed-scope-names", check: checkRemovedScopeNames },
5509
+ { name: "agent-guide", check: checkAgentGuide },
5510
+ ...(config.packs ?? []).map((p) => packs[p]),
5511
+ ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
3628
5512
  ];
3629
5513
  }
3630
- function applyConfig(raw, config) {
5514
+ function applyConfig(raw, config, packageIds) {
3631
5515
  const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
3632
5516
  const out = [];
5517
+ const levelOf = (rule) => META_RULES.has(rule) ? void 0 : config.rules?.[rule] ?? config.packageRules?.[rule]?.level;
5518
+ for (const [rule, level] of Object.entries(config.rules ?? {})) {
5519
+ if (!packageIds.has(rule) || config.packageRules?.[rule]?.reason) continue;
5520
+ out.push({
5521
+ rule: "package-rule-override",
5522
+ level: "warn",
5523
+ file: "genesis config",
5524
+ line: 0,
5525
+ subject: rule,
5526
+ message: `rules sets the package rule ${rule} to "${level}" without a reason; move it to doctor.packageRules["${rule}"] with { "level": "${level}", "reason": "\u2026" }`
5527
+ });
5528
+ }
3633
5529
  for (const input of raw) {
3634
- const setting = config.rules?.[input.rule];
5530
+ const setting = levelOf(input.rule);
3635
5531
  if (setting === "off") continue;
3636
5532
  const finding = {
3637
5533
  rule: input.rule,
@@ -3642,7 +5538,7 @@ function applyConfig(raw, config) {
3642
5538
  ...input.subject !== void 0 ? { subject: input.subject } : {}
3643
5539
  };
3644
5540
  const exception = allow.find(
3645
- (a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
5541
+ (a) => !META_RULES.has(finding.rule) && a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
3646
5542
  );
3647
5543
  if (exception) {
3648
5544
  exception.used = true;
@@ -3652,7 +5548,7 @@ function applyConfig(raw, config) {
3652
5548
  }
3653
5549
  const staleLevel = config.rules?.["stale-exception"];
3654
5550
  for (const a of allow) {
3655
- if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
5551
+ if (staleLevel === "off" || a.used || levelOf(a.entry.rule) === "off") continue;
3656
5552
  out.push({
3657
5553
  rule: "stale-exception",
3658
5554
  level: staleLevel ?? "warn",
@@ -3673,6 +5569,7 @@ function formatReport(result) {
3673
5569
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
3674
5570
  }
3675
5571
  lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
5572
+ lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis primitives`);
3676
5573
  const info = result.infos ? `, ${result.infos} info` : "";
3677
5574
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
3678
5575
  return lines.join("\n");
@@ -3690,7 +5587,7 @@ function genesisDoctor(options = {}) {
3690
5587
  root = options.root ?? config.root;
3691
5588
  },
3692
5589
  async buildStart() {
3693
- const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict });
5590
+ const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict, contracts: false });
3694
5591
  if (!result.ok) this.error(`Genesis doctor found problems:
3695
5592
  ${formatProblems(result, options.strict)}`);
3696
5593
  if (result.warnings > 0) this.warn(formatReport(result));
@@ -3723,7 +5620,7 @@ ${formatProblems(result, options.strict)}`);
3723
5620
  running = true;
3724
5621
  try {
3725
5622
  genesis ??= loadGenesis(root, loadConfig(root, options.configPath).config);
3726
- const result = await runDoctor({ root, configPath: options.configPath, genesis });
5623
+ const result = await runDoctor({ root, configPath: options.configPath, genesis, contracts: false });
3727
5624
  if (result.errors > 0) {
3728
5625
  showError(`Genesis doctor found problems:
3729
5626
  ${formatProblems(result)}`);
@@ -3743,15 +5640,15 @@ ${formatProblems(result)}`);
3743
5640
  }
3744
5641
  }
3745
5642
  };
3746
- const explicit = /* @__PURE__ */ new Set([path14.join(root, "genesis.config.json"), ...options.configPath ? [path14.resolve(root, options.configPath)] : []]);
5643
+ const explicit = /* @__PURE__ */ new Set([path18.join(root, "genesis.config.json"), ...options.configPath ? [path18.resolve(root, options.configPath)] : []]);
3747
5644
  try {
3748
5645
  const { config } = loadConfig(root, options.configPath);
3749
- if (config.rulesDoc) explicit.add(path14.resolve(root, config.rulesDoc));
5646
+ if (config.rulesDoc) explicit.add(path18.resolve(root, config.rulesDoc));
3750
5647
  } catch {
3751
5648
  }
3752
5649
  const schedule = (file) => {
3753
- if (!explicit.has(path14.resolve(file))) {
3754
- const rel = path14.relative(root, file).split(path14.sep).join("/");
5650
+ if (!explicit.has(path18.resolve(file))) {
5651
+ const rel = path18.relative(root, file).split(path18.sep).join("/");
3755
5652
  if (rel.startsWith("..") || rel.includes("node_modules/")) return;
3756
5653
  }
3757
5654
  clearTimeout(timer);