suppa-mcp-2 1.6.1 → 1.7.1

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/README.md CHANGED
@@ -339,8 +339,20 @@ when resolvable, falling back to the doc tables otherwise
339
339
  spread or by reference can't be statically checked and fire a W606 warning
340
340
  instead. An entity or seed left out of `EntityModule.forFeature()` fires
341
341
  E301/E302, naming the module file to edit so the fix is a find-and-add, not a
342
- search. Exit code 1 on any error. Use the `write_entity_code` MCP prompt to
343
- drive it from any client.
342
+ search. Use the `write_entity_code` MCP prompt to drive it from any client.
343
+
344
+ It also enforces the four **authoring rules** the platform doc does not: a
345
+ relation property must carry a TypeScript type that agrees with its decorator
346
+ (E114/E115/W610; a type naming no class, such as `any`, is the advisory W615),
347
+ enum member keys are PascalCase (W611), no field option
348
+ may be written at its platform default (W612), and `@Enum`/`@MultiEnum` take a
349
+ global name only when the enum is actually shared (W613). Those four, plus
350
+ `owner` first in a tabular part's `importKeyFields` (W607) and no `inverse` on
351
+ `@ManyToOne`/`@ManyToMany` (W609), are **rule violations**: like errors, they
352
+ exit 1, because a rule that only warns is a rule that gets ignored.
353
+ `--no-strict` demotes them to warnings for a legacy repo.
354
+ Advisory warnings — W601-W606, W608, W614, W615 — never block; they report what
355
+ the checker could not see.
344
356
 
345
357
  Tabular parts (owned child sub-tables like checklist items or order lines)
346
358
  and the remove-and-re-add-a-field semantics — a re-added field restores its
package/dist/server.js CHANGED
@@ -6,6 +6,9 @@
6
6
  * server `instructions` string verbatim, and OWNS all confirm-gating (the tool
7
7
  * modules mutate unconditionally, exactly like the Python tool functions).
8
8
  */
9
+ import { readFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
9
12
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
13
  import { z } from "zod";
11
14
  import * as tasks from "./tools/tasks.js";
@@ -19,6 +22,24 @@ import * as automation from "./tools/automation.js";
19
22
  import * as auth from "./auth.js";
20
23
  import * as tenants from "./tenants.js";
21
24
  import { confirmRequired, jsonResponse } from "./utils.js";
25
+ /**
26
+ * The running package's version, read from its own package.json rather than
27
+ * typed in. A hand-maintained literal here reported 1.6.1 for every release
28
+ * after it, which is exactly the wrong answer to "which version is my client
29
+ * actually running?" — the question you ask when a fix appears not to have
30
+ * landed. Handshake-only, so a failure to read it must never take the server
31
+ * down.
32
+ */
33
+ export const PACKAGE_VERSION = (() => {
34
+ try {
35
+ const here = dirname(fileURLToPath(import.meta.url));
36
+ // dist/server.js -> ../package.json; src/server.ts (tests) -> ../package.json
37
+ return JSON.parse(readFileSync(join(here, "..", "package.json"), "utf-8")).version ?? "unknown";
38
+ }
39
+ catch {
40
+ return "unknown";
41
+ }
42
+ })();
22
43
  // ---------------------------------------------------------------------------
23
44
  // Tool-behavior hints (MCP spec): clients use these for auto-approval policies.
24
45
  // _READ touches nothing; _ADD only creates new data; _MUT changes or removes
@@ -265,6 +286,15 @@ ENTITY BUILDER (create + edit fields; removal is UI-only)
265
286
  - An enum value on a RECORD is a reference, not a string: write {"id": <Enums row id>} for enum and [{"id": ...}, ...] for multi-enum. A bare code like "red" is refused with 'field must contain id for many-to-one relationship'. Read the ids with suppa_search_records on 'Enums' filtered by name = the enum name.
266
287
  - Existing fields CAN be edited with suppa_update_field (name, title, notNull/unique/default, relation target, and the options above), within the platform's own limits: a field's TYPE can never be changed, its SUBTYPE only toggles 'encrypted' on/off (text fields only), and a system field takes just title + the options keys. Removing a field is still UI-only — this server has no remove-field call.
267
288
 
289
+ WRITING ENTITY CODE (*.entity.ts in an application repo — NOT the API tools above)
290
+ These four rules are house rules of this platform. They OVERRIDE the platform's own migrations doc, which contradicts two of them, and they override the style of the entities already in the repo you are editing — an existing file that breaks them is the habit these rules exist to stop, not a convention to match. The full skill is skills/suppa-entity-code/SKILL.md inside the installed suppa-mcp-2 package; these four bind whether or not you open it.
291
+ 1. TYPE EVERY RELATION PROPERTY to match its decorator: @ManyToOne -> \`owner: Target;\` (\`owner?: Target\` when the relation is nullable), @ManyToMany/@OneToMany/@ManyToManyBackRef -> \`peers: Target[];\`. Never \`any\`.
292
+ 2. ENUM MEMBER KEYS ARE PascalCase — \`NotFilled = 'Not filled'\`. The stored value is the string on the right and need not match the key.
293
+ 3. NEVER WRITE A FIELD OPTION AT ITS DEFAULT. canGroup, canSort, showInTable, editFromTable and canFilter are already true; readOnly and searchable are already false. Write one ONLY where the field departs from that (usually just \`searchable: true\`). A field with all seven spelled out is wrong even though it works.
294
+ 4. @Enum/@MultiEnum TAKE THE GLOBAL NAME ONLY WHEN THE ENUM IS GLOBAL — shared by another entity, or referenced from a seed record. Otherwise omit the first argument entirely: \`@Enum(StatusEnum, StatusTitles, { … })\`, and the decorator derives <ClassName>.<propertyName>. A field's own \`key: 'Entity.field'\` is the rename key, NOT a reference, and does not make the enum global.
295
+ Before reporting the file done, run the gate — it fails (exit 1) on every one of the four:
296
+ node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>
297
+
268
298
  ATTACHMENTS (files on a record)
269
299
  - A record can carry files only if its entity has a 'file' or 'multi-file' field; check with suppa_describe_entity and add one with suppa_add_field if it has none.
270
300
  - WRITE: suppa_attach_file_to_record(entity, record_id, absolute_path) uploads from the local disk and returns file_ids — keep them, they are the only handle that gets the bytes back.
@@ -305,7 +335,7 @@ export function buildServer() {
305
335
  // Reset so repeated buildServer() calls (e.g. in tests) do not double-count.
306
336
  TOOL_NAMES.length = 0;
307
337
  PROMPT_NAMES.length = 0;
308
- const server = new McpServer({ name: "suppa-2.0", version: "1.6.1" }, { instructions: INSTRUCTIONS });
338
+ const server = new McpServer({ name: "suppa-2.0", version: PACKAGE_VERSION }, { instructions: INSTRUCTIONS });
309
339
  const reg = (name, cfg, handler) => {
310
340
  server.registerTool(name, {
311
341
  description: cfg.description,
@@ -1108,13 +1138,17 @@ export function buildServer() {
1108
1138
  .string()
1109
1139
  .nullable()
1110
1140
  .default(null)
1111
- .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3, ' +
1112
- '"showInTable": true, "canSort": true}. Keys: searchable, searchPriority (1-4, ' +
1113
- "higher = stronger weight), readOnly, canGroup, canSort, showInTable, " +
1114
- "editFromTable, canFilter. WITHOUT these a new field does not appear in table " +
1115
- "views and free-text search (suppa_search_records search=...) cannot see it — " +
1116
- "only fields marked searchable participate. Unknown keys are refused here " +
1117
- "(the platform would silently drop them)."),
1141
+ .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3}. ' +
1142
+ "Keys: searchable, searchPriority (1-4, higher = stronger weight), readOnly, " +
1143
+ "canGroup, canSort, showInTable, editFromTable, canFilter. Pass ONLY the ones " +
1144
+ "that differ from the defaults the platform already applies — canGroup, canSort, " +
1145
+ "showInTable, editFromTable and canFilter are true; readOnly and searchable are " +
1146
+ "false (verified on a live tenant 2026-08-17; the Field Options table in " +
1147
+ "builder.txt:66-73 lists them as false, which the platform contradicts). So the " +
1148
+ "one usually worth passing is searchable (+searchPriority): free-text search " +
1149
+ "(suppa_search_records search=...) only covers fields marked searchable. " +
1150
+ "Restating a default changes nothing and buries the option that does. Unknown " +
1151
+ "keys are refused here (the platform would silently drop them)."),
1118
1152
  max_length: z
1119
1153
  .number()
1120
1154
  .int()
@@ -1167,11 +1201,12 @@ export function buildServer() {
1167
1201
  reg("suppa_update_field", {
1168
1202
  description: "Edit an EXISTING field of an entity (POST /core/builder/<entity>/<field>/update-field).\n" +
1169
1203
  " Send only what changes — everything is optional.\n\n" +
1170
- " Use it to fix a label, rename a field, flip required/unique, set a default, or —\n" +
1171
- " most often — turn on the field OPTIONS a field was created without:\n" +
1172
- " searchable / searchPriority (1-4) / readOnly / canGroup / canSort / showInTable /\n" +
1173
- " editFromTable / canFilter. A field with none of them is invisible in table views\n" +
1174
- " and cannot be found by free-text search.\n\n" +
1204
+ " Use it to fix a label, rename a field, flip required/unique, set a default, or\n" +
1205
+ " change the field OPTIONS: searchable / searchPriority (1-4) / readOnly / canGroup /\n" +
1206
+ " canSort / showInTable / editFromTable / canFilter. A field created without any of\n" +
1207
+ " them already has the platform defaults — visible, sortable, groupable, filterable,\n" +
1208
+ " editable, not read-only, NOT searchable — so the usual reason to come here is\n" +
1209
+ " searchable (+searchPriority), or turning one of the others OFF.\n\n" +
1175
1210
  " WHAT THE PLATFORM DOES NOT ALLOW (refused here BEFORE any request, so a rejected\n" +
1176
1211
  " call changes nothing):\n" +
1177
1212
  " - The TYPE of a field can never be changed ('Field type cannot be changed.') —\n" +
@@ -1240,10 +1275,13 @@ export function buildServer() {
1240
1275
  .string()
1241
1276
  .nullable()
1242
1277
  .default(null)
1243
- .describe('Field options as a JSON object, e.g. {"showInTable": true, "canFilter": true, ' +
1244
- '"searchable": true, "searchPriority": 3}. Keys: searchable, searchPriority ' +
1245
- "(1-4), readOnly, canGroup, canSort, showInTable, editFromTable, canFilter. " +
1246
- "Unknown keys are refused (the platform would drop them silently)."),
1278
+ .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3} ' +
1279
+ 'or {"showInTable": false}. Keys: searchable, searchPriority (1-4), readOnly, ' +
1280
+ "canGroup, canSort, showInTable, editFromTable, canFilter. Send only what " +
1281
+ "CHANGES — the platform already applies canGroup/canSort/showInTable/" +
1282
+ "editFromTable/canFilter true and readOnly/searchable false, so restating one " +
1283
+ "of those is a no-op. Unknown keys are refused (the platform would drop them " +
1284
+ "silently)."),
1247
1285
  confirm: Confirm,
1248
1286
  },
1249
1287
  annotations: _MUT,
@@ -2228,9 +2266,10 @@ export function buildServer() {
2228
2266
  "then suppa_add_field on the returned entity_name (the `owner` link is created for you).\n" +
2229
2267
  "4. Verify with suppa_describe_entity, and suppa_list_tabular_parts(parent) for any tabular parts.\n" +
2230
2268
  "5. Offer a form: suppa_create_form(generate_from_entity=true, entity_name=...). \n" +
2231
- "Pass options_json on each field the user should see or search — {\"showInTable\": true, \"canFilter\": true, " +
2232
- '"canSort": true} and {"searchable": true, "searchPriority": 3} on the ones worth finding by text; without ' +
2233
- "them the field is absent from table views and from free-text search.\n" +
2269
+ 'Pass options_json ONLY where a field departs from the defaults: {"searchable": true, "searchPriority": 3} ' +
2270
+ "on the ones worth finding by text (free-text search covers searchable fields only), or an option turned OFF. " +
2271
+ "A field created without options_json is already visible, sortable, groupable, filterable and editable — " +
2272
+ "restating those buries the one option that actually differs.\n" +
2234
2273
  "Fields cannot be REMOVED via this server (UI only) and a field's TYPE can never be changed — so get the types " +
2235
2274
  "right before creating; names, labels, flags and options can be corrected later with suppa_update_field.");
2236
2275
  regPrompt("migrate_from_v1", {
@@ -2269,7 +2308,14 @@ export function buildServer() {
2269
2308
  "representativeFieldName, and per-field nullable.\n" +
2270
2309
  "3. Write src/common/database/entities/*.entity.ts — @Entity class extending SystemBaseEntity; scalars via @Column({ type: FieldTypeEnum.X }); " +
2271
2310
  "relations via thunks (@ManyToOne(() => Target)) — pass the thunk and the options object only; do not add the optional inverse selector to @ManyToOne/@ManyToMany; " +
2272
- "fixed choices via @Enum('Entity.field', ...); attachments via @File/@MultiFile; " +
2311
+ "TYPE every relation property to match its decorator (@ManyToOne -> `owner: Target;`, or `owner?: Target` when the relation is nullable; " +
2312
+ "@ManyToMany/@OneToMany/@ManyToManyBackRef -> `peers: Target[];`) — an untyped relation is `any` to every caller. " +
2313
+ "Fixed choices via @Enum(StatusEnum, StatusTitles, { ... }) with PascalCase member keys (Active = 'active') and NO global name — " +
2314
+ "the decorator derives <ClassName>.<propertyName>; add the '<Entity>.<field>' first argument ONLY when the value set is shared across " +
2315
+ "entities or referenced from a seed record. Attachments via @File/@MultiFile; " +
2316
+ "NEVER write a field option that already holds its default — canGroup/canSort/showInTable/editFromTable/canFilter are true and " +
2317
+ "readOnly/searchable are false already, so declare one only where the field DEPARTS from that. If the repo's existing entities " +
2318
+ "restate those defaults on every field, do not copy that habit into the new file. " +
2273
2319
  "'default' is a SQL expression STRING ('false', \"'draft'\") — never a JS value. Repeating rows owned by one parent record " +
2274
2320
  "(checklist items, order lines) are a TABULAR PART, not a plain entity: type: 'tabular-part' + relationEntityName + a @ManyToOne " +
2275
2321
  "field named owner, with owner first in importKeyFields (see references/tabular-parts.md). " +
@@ -2280,6 +2326,7 @@ export function buildServer() {
2280
2326
  "5. Export the entity and seed from their barrels (entities/index.ts, seeds/index.ts), and add the seed to " +
2281
2327
  "EntityModule.forFeature()'s seeds array, positioned after the seeds of everything it references — dependencies first.\n" +
2282
2328
  "6. Gate before claiming done: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root> " +
2329
+ "(strict by default — restated default options and unreferenced enum global names fail it, exit 1) " +
2283
2330
  "(or the skills/ dir of a checkout) reports 0 errors; npx tsc --noEmit passes; " +
2284
2331
  "push, reload (POST /core/applications/:appId/reload), verify with suppa_describe_entity — " +
2285
2332
  "the gate fails with E301 if anything is unregistered — run it, do not assume.\n" +
@@ -1226,8 +1226,10 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
1226
1226
  * ever invented.
1227
1227
  * options: the builder's Field Options object (builder.txt:60, keys :66-73) —
1228
1228
  * searchable / searchPriority / readOnly / canGroup / canSort / showInTable /
1229
- * editFromTable / canFilter. Omitting it leaves the field out of table views and
1230
- * out of free-text search (data.txt:218).
1229
+ * editFromTable / canFilter. Omitting it leaves the platform defaults in place —
1230
+ * visible, sortable, groupable, filterable, editable, not read-only, and NOT
1231
+ * searchable, so only free-text search is actually lost (data.txt:218). Pass a
1232
+ * key only where it departs from that; restating a default says nothing.
1231
1233
  * sub_type is checked against the documented matrix (migrations.txt:212-216)
1232
1234
  * before the request: timestamp takes 'date' | 'time' | 'timestamp', text takes
1233
1235
  * 'encrypted', enum/multi-enum have it set by the platform, and no other type
@@ -549,7 +549,21 @@ export async function readV1Enum(enumInput) {
549
549
  // all primitives, localized text/json, custom fields, enums (single + multi),
550
550
  // relations (FK + many-to-many), file attachments (single + multi), and legacy
551
551
  // shapes (Number, polymorphic relations, TSVector/Object/List system columns).
552
- /** Stable enum bucket name for a migrated enum field (avoids cross-entity clashes). */
552
+ /**
553
+ * Stable enum bucket name for a migrated enum field (avoids cross-entity clashes).
554
+ *
555
+ * NOTE the separator: this is `Entity_field`, while everything on the CODE path
556
+ * uses `Entity.field` — the name @Enum()/@MultiEnum() derive from
557
+ * <ClassName>.<propertyName>, and the convention the tool descriptions teach.
558
+ * So an enum created by this migrator is NOT the one an entity class would bind
559
+ * to by default: code written later against a migrated tenant has to pass the
560
+ * underscore name explicitly as @Enum's first argument.
561
+ *
562
+ * Left as-is deliberately. Changing the separator would not rename the enums
563
+ * already created in migrated tenants — a re-run would create dot-named
564
+ * duplicates beside them and leave every previously migrated field bound to the
565
+ * old bucket. Aligning the two is a data-migration decision, not a rename.
566
+ */
553
567
  function _enumNameFor(entityName, fieldName) {
554
568
  return `${entityName}_${fieldName}`;
555
569
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.6.1",
3
+ "version": "1.7.1",
4
4
  "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -54,8 +54,11 @@ Confirm all 5 before writing anything:
54
54
  13. `subType` is **immutable after creation**, with one exception: toggling `'encrypted'` on or off. The Builder API answers `Field subType cannot be changed.` to anything else — so choosing `Timestamp` where you needed `subType: 'date'` is not a conversion you can ship later, it is a NEW field plus a removal of the old one (see `references/registration.md` for what removal leaves behind). Get date-vs-timestamp right the first time. To CLEAR a subtype you must write `subType: null` explicitly — deleting the line does nothing, because an omitted key is dropped from the sync payload and the stored subtype survives.
55
55
  14. **Every relation property carries its TypeScript type, and the type says what the decorator says.** `@ManyToOne` holds ONE row — `owner: ProductMatrixEntity;` — while `@ManyToMany`, `@OneToMany` and `@ManyToManyBackRef` hold many — `envs: ApplicationEnvsEntity[];`. Type it optional (`owner?: Target`) unless the relation is `nullable: false`. An untyped relation property is `any` to every consumer of the entity. E114/E115/W610.
56
56
  15. **Enum member keys are PascalCase** — `NotFilled = 'Not filled'`. The key is the identifier the code reads; the string on the right is what the platform stores, and the two need not match. W611.
57
- 16. **Never write an option that already holds its default value.** The platform applies `canGroup: true`, `canSort: true`, `showInTable: true`, `editFromTable: true`, `canFilter: true`, `readOnly: false`, `searchable: false` on its own. Declare one of these ONLY where the field departs from it; repeating defaults on every field buries the one option that actually differs. W612.
58
- 17. **`@Enum`/`@MultiEnum` take the global name only when the enum is global.** Default is local: `@Enum(StageStatusEnum, StageStatus, { nullable: false })` — the decorator derives `<ClassName>.<propertyName>`. Pass the name as the FIRST argument only when the value set is shared across entities or referenced from a seed: `@Enum('StageWorkflows.status', StageStatusEnum, StageStatus, { … })`. W613.
57
+ 16. **Never write an option that already holds its default value.** The platform applies `canGroup: true`, `canSort: true`, `showInTable: true`, `editFromTable: true`, `canFilter: true`, `readOnly: false`, `searchable: false` on its own. Declare one of these ONLY where the field departs from it; repeating defaults on every field buries the one option that actually differs. W612, and it fails the gate.
58
+ **This rule outranks the surrounding code.** An existing app repo very often has entities that restate all seven on every field — that is the habit this rule exists to stop, not a local convention to match. Write the new file clean; leave the old ones alone unless asked. The same goes for the platform's captured API docs: `api-entity-builder-builder.txt:66-73` lists these defaults as `false`, which live tenants contradict — a field created with no options comes back visible, sortable, groupable, filterable and editable.
59
+ 17. **`@Enum`/`@MultiEnum` take the global name only when the enum is global.** Default is local: `@Enum(StageStatusEnum, StageStatus, { nullable: false })` — the decorator derives `<ClassName>.<propertyName>`. Pass the name as the FIRST argument only when the value set is shared across entities or referenced from a seed: `@Enum('StageWorkflows.status', StageStatusEnum, StageStatus, { … })`. W613, and it fails the gate.
60
+ **This rule overrides the platform doc**, which says flatly "Give the enum a global name (first argument)" (migrations.html → `references/entities.md`) and passes one in every example. Follow the rule, not the example.
61
+ **A field's `key` is not a reference.** `key: '<Entity>.<field>'` on the same field is the rename key (rule 11) and is spelled exactly like a global enum name — it does not make the enum shared, and it is not what a seed resolves against.
59
62
  18. Repeating rows owned by one parent record are a **tabular part**, never a plain entity: `type: 'tabular-part'` + `relationEntityName` (the parent's `@Entity()` name) + a `@ManyToOne` field named exactly `owner` pointing at the parent class — all three required, the platform infers none of them. Put `owner` FIRST in `importKeyFields` — it scopes the business key to the parent, or rows collide across different parents.
60
63
  19. **`EntityModule.forFeature()` must be consumed by an `@Module`, and has exactly two shapes.** It RETURNS a module: put it in `@Module({ imports: [...] })` and export that class from `src/index.ts` as `AppModule` — a bare `EntityModule.forFeature(...);` statement discards the result and registers nothing (E307). The two shapes (`references/registration.md`) are `forFeature([A, B], { seeds: [...] })` — classes FIRST, options second — and `forFeature({ entitiesPath, seedsPath })` for autoloading. The options object accepts only `seeds`, `entitiesPath` and `seedsPath`. `forFeature({ entities: [...] })` looks reasonable and registers NOTHING: the classes are dropped with the unknown option and no table is created for any of them. E306.
61
64
 
@@ -218,7 +221,11 @@ If that prints nothing, the entity is not registered.
218
221
 
219
222
  Step 1 exists to catch exactly this: an unregistered class is E301 and the gate fails. Never report done on an unrun gate.
220
223
 
221
- `validate-suppa-schema.mjs` exits `0` on a clean run, `1` when errors are found, `2` on a usage error or a missing path. The gate requires exit `0` — warnings alone do not block.
224
+ `validate-suppa-schema.mjs` exits `0` on a clean run, `1` on violations, `2` on a usage error or a missing path. The gate requires exit `0`.
225
+
226
+ **Two classes of finding block it.** Errors (`E…`) always do. So do the *rule violations* — `W607`, `W609`, `W610`, `W611`, `W612`, `W613` — because each names one line that the hard rules above say must be written differently, and a rule that only warns is a rule that gets ignored (that is exactly how an entity shipped with seven restated defaults on every field). Advisory warnings — `W601`-`W606`, `W608`, `W614`, `W615` — describe what the checker could not see and never block.
227
+
228
+ `--no-strict` demotes the rule violations back to warnings. It exists for a legacy repo you are not cleaning up in this pass; it is not for making your own new file pass. `W613` argues from absence ("nothing references this name"), so it only blocks when the validator was pointed at a DIRECTORY and walked the whole repo — on an explicit file list the referencing seed may simply be outside the set.
222
229
 
223
230
  The validator parses with the TypeScript compiler API, read from the app repo you point it at (a Suppa application compiles with `tsc`, so it has one). If it reports `cannot resolve 'typescript'`, run `npm install` in that repo — or `npm i -D typescript@5` if it genuinely has none. Pin the major: plain `typescript` now installs 7.x, whose main entry exports only version info and carries no compiler API.
224
231
 
@@ -238,11 +245,13 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
238
245
  | `default` value is rejected | A JavaScript value was passed instead of a SQL expression string | E103 |
239
246
  | Generated relation has an inverse selector that fails to typecheck | An `inverse` was passed to `@ManyToOne`/`@ManyToMany`, where it's optional and usually omitted | W609/E111 — drop the selector, write `@ManyToOne(() => Target, { … })` |
240
247
  | A relation reads as `any`; nothing catches using it as the wrong shape | The property has no TypeScript type | E114 — write `owner: Target;` (`Target[]` for the to-many decorators) |
248
+ | A relation is typed `any` (or a union), so callers get nothing | An annotation that names no class — E114 does not fire, because there IS one | W615 — write the target class; platform entities such as `IconsEntity` are importable from `@suppa/sdk` |
241
249
  | A to-many relation is used as a single record (or the reverse) | The property's type contradicts the decorator's arity, or names a different class than the thunk | E115 — `@ManyToOne` → `Target`; `@ManyToMany`/`@OneToMany`/`@ManyToManyBackRef` → `Target[]` |
242
250
  | Callers never null-check a relation that can be empty | A nullable `@ManyToOne` is typed as always present (or a `nullable: false` one as optional) | W610 — `owner?: Target` when nullable, `owner: Target` when `nullable: false` |
243
251
  | Enum members read as data rather than identifiers | Member keys are not PascalCase | W611 — `NotFilled = 'Not filled'` |
244
- | Every field repeats the same five option lines | Options were written at their default values | W612 — delete them; declare an option only where it departs from the default |
245
- | An enum name is invented for a field nothing else references | The optional global name was passed to `@Enum`/`@MultiEnum` when the enum is local | W613 — omit the first argument; the decorator derives `<ClassName>.<propertyName>` |
252
+ | Every field repeats the same seven option lines | Options were written at their default values — often copied from the repo's older entities | W612 (blocks the gate) — delete them; declare an option only where it departs from the default |
253
+ | An enum name is invented for a field nothing else references | The optional global name was passed to `@Enum`/`@MultiEnum` when the enum is local | W613 (blocks the gate on a whole-repo run) — omit the first argument; the decorator derives `<ClassName>.<propertyName>` |
254
+ | An unreferenced enum global name passes the gate | The field also carries `key: '<Entity>.<field>'`; before 1.7.0 that identical literal counted as a reference and silenced W613 | fixed in 1.7.0 — a field's own `key`/`subType` is no longer a reference |
246
255
  | Migration rejects the column, or a date field ships as a full `timestamp` | The `(type, subType)` pair isn't one the doc allows — `Timestamp` takes `'date'`/`'time'`/`'timestamp'`, `Text` takes `'encrypted'`, nothing else | E112 |
247
256
  | `Encrypted subtype is only allowed on text fields` | `subType: 'encrypted'` on a non-Text column | E112 |
248
257
  | An enum field resolves to the wrong enum, or its values fail to insert | `subType` was written by hand on `@Enum`/`@MultiEnum` instead of being left to the decorator | E113 |
@@ -232,7 +232,7 @@ For an enum field, `subType` holds the enum's **global name** — the value that
232
232
  status: StageStatusEnum; // subType = 'StageWorkflows.status'
233
233
  ```
234
234
 
235
- Called without an explicit global name, the SDK derives `<ClassName>.<propertyName>`. Either way, do not pass `subType` yourself on an enum field.
235
+ Called without an explicit global name, the SDK derives `<ClassName>.<propertyName>` — so the field above, written `@Enum(StageStatusEnum, StageStatus, { nullable: false })` on class `StageWorkflows`, resolves to the same `subType`. That derived form is the one to write unless the enum is genuinely shared (see Enums below). Either way, do not pass `subType` yourself on an enum field.
236
236
 
237
237
  ### Changing a Subtype
238
238
 
@@ -272,6 +272,9 @@ export class StageWorkflows extends SystemBaseEntity {
272
272
  }
273
273
  ```
274
274
 
275
+ > **HOUSE RULE — the doc's `icon: any` is not the shape to copy (SKILL.md rule 14).**
276
+ > `any` names no class, so it tells callers nothing and the arity check cannot run (W615). `IconsEntity` is importable from the SDK, as the note below says — write `icon?: IconsEntity`. The `?` follows from the relation being nullable: this `@ManyToOne` sets no `nullable: false`, and the doc's `workflow: Workflows` above is right to omit it only because that one does.
277
+
275
278
  | Decorator | Signature | Use |
276
279
  |---|---|---|
277
280
  | @ManyToOne | (target, options?) or (target, inverse, options?) | Foreign key on this entity. |
@@ -285,7 +288,21 @@ Platform entities are importable from the SDK when you need to point at them —
285
288
 
286
289
  ## Enums
287
290
 
288
- @Enum and @MultiEnum accept a TypeScript enum with string values. Give the enum a global name (first argument) so it can be referenced from seeds and shared across entities:
291
+ @Enum and @MultiEnum accept a TypeScript enum with string values. The doc's own sentence here is *"Give the enum a global name (first argument) so it can be referenced from seeds and shared across entities"*, and every example in it passes one.
292
+
293
+ > **HOUSE RULE — overrides the sentence above (SKILL.md rule 17).**
294
+ > Pass the global name **only when the enum really is global**: shared by more than one entity, or referenced from a seed record (`{ name: 'StageWorkflows.status', value: 'active' }`). Otherwise omit the first argument and let the SDK derive `<ClassName>.<propertyName>`. A name that nothing references is a name that should not be there — W613, and it fails the close-out gate.
295
+ >
296
+ > Careful with `key`: a field conventionally carries `key: '<Entity>.<field>'`, spelled exactly like a global enum name. That is the **rename key**, an unrelated option — it is not a reference to the enum and does not make the enum global.
297
+
298
+ Local — the default, and what most enum fields should look like:
299
+
300
+ ```ts
301
+ @Enum(StageStatusEnum, StageStatus, { nullable: false })
302
+ status: StageStatusEnum; // subType resolves to 'StageWorkflows.status'
303
+ ```
304
+
305
+ Global — the same field, once a seed or a second entity refers to the value set by name:
289
306
 
290
307
  ```ts
291
308
  export enum StageStatusEnum {
@@ -15,7 +15,7 @@ The API migration path and this code path share one authority: `classifyV1Field(
15
15
  | `uuid` | `@Column({ type: FieldTypeEnum.UUID })` |
16
16
  | `multi-language` | `@Column({ type: FieldTypeEnum.MultiLang })` |
17
17
  | `icon` | `@Column({ type: FieldTypeEnum.Icon })` — scalar by default; use `@ManyToOne(() => IconsEntity)` only when v1 reports a relation |
18
- | `enum` | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles, { … })` + a TypeScript string enum built from `suppa_read_v1_enum` values + a seed is NOT needed (enum values live in the decorator maps) |
18
+ | `enum` | `@Enum(<Field>Enum, <Field>Titles, { … })` + a TypeScript string enum built from `suppa_read_v1_enum` values (member keys PascalCase) + a seed is NOT needed (enum values live in the decorator maps). A ported v1 enum belongs to one field, so **no global name**: add the `'<Entity>.<field>'` first argument only if a seed or a second entity references the value set by name (SKILL.md rule 17) |
19
19
  | `multi-enum` | `@MultiEnum(…)` — same signature as `@Enum` |
20
20
  | `file` | `@File({ title: … })` |
21
21
  | `multi-file` | `@MultiFile({ title: … })` |
@@ -91,10 +91,12 @@ export class Orders extends SystemBaseEntity {
91
91
  @Column({ name: 'name', type: FieldTypeEnum.Text })
92
92
  name: string;
93
93
 
94
- @Enum('Orders.status', StatusEnum, StatusTitles)
94
+ // No global name: nothing outside this field references the value set.
95
+ @Enum(StatusEnum, StatusTitles)
95
96
  status: StatusEnum;
96
97
 
98
+ // Nullable (no `nullable: false`), so the property is optional.
97
99
  @ManyToOne(() => Customers)
98
- customer: Customers;
100
+ customer?: Customers;
99
101
  }
100
102
  ```
@@ -7,8 +7,15 @@
7
7
  * (docs.modern-expo.com/backend/application-developing/migrations.html):
8
8
  * these mistakes compile under tsc and only fail at migration time.
9
9
  *
10
- * Usage: node validate-suppa-schema.mjs <app-root-or-files...>
10
+ * Usage: node validate-suppa-schema.mjs [--no-strict] <app-root-or-files...>
11
11
  * Import: import { validateSchema } from "./validate-suppa-schema.mjs"
12
+ *
13
+ * Exit codes: 0 clean, 1 violations found, 2 usage/toolchain problem.
14
+ * By DEFAULT the authoring-rule warnings in RULE_WARNINGS block the run too —
15
+ * they are the house rules, and a rule that only warns is a rule that gets
16
+ * ignored (which is exactly how a generated entity ended up restating seven
17
+ * default options on every field). `--no-strict` downgrades them back to
18
+ * advisory, for a legacy repo you are not cleaning up in this pass.
12
19
  */
13
20
  import { createRequire } from "node:module";
14
21
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -33,6 +40,34 @@ export const DEFAULT_FIELD_OPTIONS = {
33
40
  readOnly: false,
34
41
  searchable: false,
35
42
  };
43
+ /**
44
+ * Warnings that are DETERMINISTIC violations of a stated authoring rule, not
45
+ * heuristics: each one names a concrete line of code that the rules say must be
46
+ * written differently, and each has a mechanical fix. These block the gate by
47
+ * default (see `--no-strict`), because the four house rules kept being violated
48
+ * for exactly one reason — they were warnings, and the gate only failed on
49
+ * errors.
50
+ *
51
+ * Deliberately NOT in this set: W601-W606 (heuristics and "cannot verify from
52
+ * the AST"), W608 (no tsconfig at the given root — an input problem), W614
53
+ * (membership unknown, so a check was skipped). Those describe what the checker
54
+ * could not see; they do not name a line that is wrong.
55
+ */
56
+ export const RULE_WARNINGS = [
57
+ "W607", // tabular part: `owner` present in importKeyFields but not first
58
+ "W609", // inverse selector passed where it is optional (@ManyToOne/@ManyToMany)
59
+ "W610", // relation typed optional/non-optional against its own `nullable`
60
+ "W611", // enum member key is not PascalCase
61
+ "W612", // field option written at its platform default
62
+ "W613", // enum global name passed for an enum nothing references
63
+ "W615", // relation typed with a shape that names no class ('any', a union, …)
64
+ ];
65
+ /**
66
+ * W613 argues from ABSENCE — "nothing references this name". That only holds
67
+ * when the whole repo was analyzed; on an explicit file list the referencing
68
+ * seed may simply not be in the set, so it must not block.
69
+ */
70
+ export const RULE_WARNINGS_NEEDING_WHOLE_REPO = ["W613"];
36
71
  export const DOC_COLUMN_OPTIONS = ["type", "subType", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask",
37
72
  // Field options. The decorator tables do not list them, but migrations.txt:245
38
73
  // names four of them as options a column carries — encryption makes "the
@@ -184,8 +219,15 @@ function objectMap(ts, node) {
184
219
  if (!node || !ts.isObjectLiteralExpression(node)) return map;
185
220
  for (const p of node.properties) {
186
221
  if (ts.isPropertyAssignment(p)) {
187
- const name =
222
+ let name =
188
223
  ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : null;
224
+ // A computed key whose expression is a literal is the same key written
225
+ // differently — `{ ['canGroup']: true }`. Dropping it made a computed key
226
+ // a blanket opt-out of EVERY option rule (W612, E501/E502, E103, E112,
227
+ // E113 all read through this function), silently.
228
+ if (name === null && ts.isComputedPropertyName(p.name)) {
229
+ name = stringValue(ts, unwrapExpr(ts, p.name.expression));
230
+ }
189
231
  if (name !== null) map.set(name, p.initializer);
190
232
  } else if (ts.isShorthandPropertyAssignment(p)) {
191
233
  map.set(p.name.text, p.name);
@@ -193,6 +235,20 @@ function objectMap(ts, node) {
193
235
  }
194
236
  return map;
195
237
  }
238
+ /**
239
+ * Computed keys objectMap could NOT resolve — `{ [KEY]: true }`, where KEY is a
240
+ * const. The key exists but its name is unknowable here, so every option rule
241
+ * silently stops applying to it; callers report that rather than fall quiet.
242
+ */
243
+ function unreadableComputedKeys(ts, node) {
244
+ if (!node || !ts.isObjectLiteralExpression(node)) return [];
245
+ return node.properties.filter(
246
+ (p) =>
247
+ ts.isPropertyAssignment(p) &&
248
+ ts.isComputedPropertyName(p.name) &&
249
+ stringValue(ts, unwrapExpr(ts, p.name.expression)) === null,
250
+ );
251
+ }
196
252
  function stringValue(ts, node) {
197
253
  return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
198
254
  ? node.text
@@ -355,6 +411,17 @@ function analyzeImports(ts, sf) {
355
411
  }
356
412
  }
357
413
  }
414
+ // A local `type Customer = Customers;` names the same class as the thunk
415
+ // returns, so a property typed with it is correct — reading only the written
416
+ // identifier made E115 (an ERROR) fire on code that is right.
417
+ for (const st of sf.statements) {
418
+ if (!ts.isTypeAliasDeclaration(st)) continue;
419
+ let t = st.type;
420
+ while (t && ts.isParenthesizedTypeNode(t)) t = t.type;
421
+ if (t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && !t.typeArguments) {
422
+ alias.set(st.name.text, alias.get(t.typeName.text) ?? t.typeName.text);
423
+ }
424
+ }
358
425
  sf.suppaImports = { alias, namespaces };
359
426
  }
360
427
  function importsOf(sf) {
@@ -467,17 +534,36 @@ function analyzeEntities(ts, sf, model) {
467
534
  const last = d.args[d.args.length - 1];
468
535
  const enumOptionsNode =
469
536
  d.args.length >= 2 && last && ts.isObjectLiteralExpression(last) ? last : null;
537
+ // Argument 0 is EITHER the global name (a string) or the enum
538
+ // itself (an identifier / namespace access). Anything else — a
539
+ // concatenation, a substituting template — is a name being passed
540
+ // that this checker cannot read, and reading it as "no name given"
541
+ // turned one token into a bypass of W613 AND of E206's seed
542
+ // cross-check.
543
+ const first = d.args[0] ? unwrapExpr(ts, d.args[0]) : null;
544
+ const nameIsUnreadable =
545
+ !!first &&
546
+ stringValue(ts, first) === null &&
547
+ !ts.isIdentifier(first) &&
548
+ !ts.isPropertyAccessExpression(first);
470
549
  info.properties.set(propName, {
471
550
  kind: d.name === "Enum" ? "enum" : "multi-enum",
472
551
  node: member, decorator: d,
473
- enumGlobalName: stringValue(ts, d.args[0]),
552
+ enumGlobalName: stringValue(ts, first),
553
+ enumGlobalNameUnreadable: nameIsUnreadable,
554
+ enumGlobalNameNode: d.args[0] ?? null,
474
555
  optionsNode: enumOptionsNode,
475
556
  enumOptions: objectMap(ts, enumOptionsNode),
476
557
  });
477
558
  } else if (FILE_DECORATORS.has(d.name)) {
559
+ // @File/@MultiFile take an options object too (the template writes
560
+ // `@File({ title })`), and without optionsNode the default-option
561
+ // rule could never see an attachment field.
478
562
  info.properties.set(propName, {
479
563
  kind: d.name === "File" ? "file" : "multi-file",
480
564
  node: member, decorator: d,
565
+ optionsNode: d.args[0] ?? null,
566
+ nameNode: objectMap(ts, d.args[0]).get("name") ?? null,
481
567
  });
482
568
  } else if (d.name in RELATION_KIND_BY_DECORATOR) {
483
569
  // (target, options?) or (target, inverse, options?) — the options
@@ -496,6 +582,15 @@ function analyzeEntities(ts, sf, model) {
496
582
  inverseNode,
497
583
  relOptions,
498
584
  optionsNode: [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)) ?? null,
585
+ // The options SLOT, whatever sits in it — the last argument that
586
+ // is not the thunk and not an inverse selector. `optionsNode`
587
+ // above keeps only object literals, so on `@ManyToOne(() => T,
588
+ // OPTS)` it is null, which reads as "no options given" and is
589
+ // how an unreadable `nullable` was mistaken for `nullable: true`.
590
+ rawOptionsNode:
591
+ d.args.length > 1 && !isFunctionLike(ts, d.args[d.args.length - 1])
592
+ ? d.args[d.args.length - 1]
593
+ : null,
499
594
  typeInfo: propertyTypeInfo(ts, member),
500
595
  });
501
596
  }
@@ -710,7 +805,24 @@ function checkRelationTyping(ts, sf, propName, prop, findings) {
710
805
  ` an untyped relation property is 'any' to every consumer of this entity`));
711
806
  return;
712
807
  }
713
- if (info.name === null) return; // a shape this AST-only checker cannot read
808
+ // A type node exists but names no class: `any`, `unknown[]`, a union, a
809
+ // nested array. E114 does not cover it (there IS an annotation) and the arity
810
+ // checks below cannot run — which used to mean `owner: any` slipped through in
811
+ // total silence, the very hole E114 exists to close. Arity is still decidable
812
+ // from the brackets, so check that much, then say what could not be read.
813
+ if (info.name === null) {
814
+ if (arity === "many" && !info.isArray) {
815
+ findings.push(finding(ts, sf, info.node, "E115",
816
+ `'${propName}' (@${prop.decorator.name}) holds MANY rows but is not typed as an array — write '${expected ?? "Target[]"}'`));
817
+ } else if (arity === "one" && info.isArray) {
818
+ findings.push(finding(ts, sf, info.node, "E115",
819
+ `'${propName}' (@ManyToOne) holds ONE row but is typed as an array — write '${expected ?? "Target"}'. The many side is @OneToMany on the other class.`));
820
+ } else {
821
+ findings.push(finding(ts, sf, info.node, "W615",
822
+ `relation '${propName}' (@${prop.decorator.name}) is typed with a shape that names no class ('any', 'unknown', a union, …) — it tells callers nothing and the arity check cannot run. Write '${expected ?? (arity === "many" ? "Target[]" : "Target")}'. Platform entities are importable from @suppa/sdk (e.g. IconsEntity) when the target is one of theirs.`));
823
+ }
824
+ return;
825
+ }
714
826
 
715
827
  if (target && info.name !== target) {
716
828
  findings.push(finding(ts, sf, info.node, "E115",
@@ -728,9 +840,20 @@ function checkRelationTyping(ts, sf, propName, prop, findings) {
728
840
  }
729
841
 
730
842
  // Optionality should agree with the column: a NOT NULL relation always has a
731
- // value, anything else may be absent.
732
- if (arity === "one") {
733
- const notNull = booleanValue(ts, prop.relOptions?.get("nullable")) === false;
843
+ // value, anything else may be absent. This reads `nullable` off the options,
844
+ // so it can only run when the options are actually readable — with options
845
+ // passed by reference or carrying a spread, an absent `nullable` is UNKNOWN,
846
+ // not false, and treating it as false made the checker demand a '?' on a NOT
847
+ // NULL relation. W610 blocks the gate, so that was a rule violation the gate
848
+ // itself would have forced you to commit.
849
+ const slot = prop.rawOptionsNode ? unwrapExpr(ts, prop.rawOptionsNode) : null;
850
+ const optionsReadable =
851
+ !slot || (ts.isObjectLiteralExpression(slot) && spreadElements(ts, slot).length === 0);
852
+ if (arity === "one" && !optionsReadable) {
853
+ findings.push(finding(ts, sf, prop.rawOptionsNode, "W606",
854
+ `'${propName}' receives its relation options by reference or through a spread, so 'nullable' cannot be read — the optionality check (W610) is skipped. Inline the options object to restore it.`));
855
+ } else if (arity === "one") {
856
+ const notNull = booleanValue(ts, unwrapExpr(ts, prop.relOptions?.get("nullable"))) === false;
734
857
  if (notNull && info.nullable) {
735
858
  findings.push(finding(ts, sf, info.node, "W610",
736
859
  `'${propName}' is declared nullable: false but typed as optional — drop the '?' (and any '| null'): the column always has a value`));
@@ -746,17 +869,41 @@ function checkRelationTyping(ts, sf, propName, prop, findings) {
746
869
  * field is noise that hides the options that DO differ.
747
870
  */
748
871
  function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
872
+ // An options object delivered by reference reads as empty here, so every
873
+ // option rule silently stopped applying to that field — no W612, and no
874
+ // E501/E502 either. Say so instead of falling quiet: this file's convention
875
+ // is that content it cannot read is W606, not silence.
876
+ if (prop.optionsNode && !ts.isObjectLiteralExpression(unwrapExpr(ts, prop.optionsNode))) {
877
+ findings.push(finding(ts, sf, prop.optionsNode, "W606",
878
+ `'${propName}' receives its options by reference, so they cannot be read statically — the default-option check (W612) and the unknown-option checks (E501/E502) are skipped for this field. Inline the options object to restore them.`));
879
+ return;
880
+ }
749
881
  const scopes = [];
750
- if (prop.optionsNode) scopes.push(prop.optionsNode);
882
+ if (prop.optionsNode) scopes.push(unwrapExpr(ts, prop.optionsNode));
751
883
  // …and a nested `options: { … }` object, whichever shape the SDK takes.
752
884
  for (const scope of [...scopes]) {
753
885
  const nested = objectMap(ts, scope).get("options");
754
- if (nested && ts.isObjectLiteralExpression(nested)) scopes.push(nested);
886
+ const unwrapped = nested && unwrapExpr(ts, nested);
887
+ if (unwrapped && ts.isObjectLiteralExpression(unwrapped)) scopes.push(unwrapped);
888
+ }
889
+ // Not for @Enum/@MultiEnum: their options slot is ambiguous with an inline
890
+ // TITLES map (see the extractor), and a titles map is BUILT from computed
891
+ // keys — `{ [StatusEnum.Active]: { title } }`. Reporting those would be noise
892
+ // on correct code. Enum options are only ever read for `subType` (E113), so
893
+ // nothing is lost.
894
+ const enumKind = prop.kind === "enum" || prop.kind === "multi-enum";
895
+ for (const scope of enumKind ? [] : scopes) {
896
+ for (const keyNode of unreadableComputedKeys(ts, scope)) {
897
+ findings.push(finding(ts, sf, keyNode, "W606",
898
+ `'${propName}' has an option under a computed key whose name cannot be read statically — the default-option check (W612) and the unknown-option checks (E501/E502) are skipped for it. Write the key literally.`));
899
+ }
755
900
  }
756
901
  for (const scope of scopes) {
757
902
  for (const [key, valNode] of objectMap(ts, scope)) {
758
903
  if (!(key in DEFAULT_FIELD_OPTIONS)) continue;
759
- const value = booleanValue(ts, valNode);
904
+ // `(true)`, `true as boolean`, `true!` are the same literal; every other
905
+ // value read in this file unwraps first, and this one did not.
906
+ const value = booleanValue(ts, unwrapExpr(ts, valNode));
760
907
  if (value !== null && value === DEFAULT_FIELD_OPTIONS[key]) {
761
908
  findings.push(finding(ts, sf, valNode, "W612",
762
909
  `'${propName}' sets '${key}: ${value}', which is already the platform default — remove it; ` +
@@ -776,15 +923,36 @@ function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
776
923
  */
777
924
  function checkEnumGlobalName(ts, sf, propName, prop, model, findings) {
778
925
  const name = prop.enumGlobalName;
779
- if (!name) return; // local enum — the default, and nothing to check
780
- // The literal occurs once: here, in this decorator. Nothing — no seed record,
781
- // no other entity — refers to it, so the name buys nothing.
782
- const occurrences = model.stringLiteralCounts.get(name) ?? 0;
783
- if (occurrences <= 1) {
926
+ if (!name) {
927
+ if (prop.enumGlobalNameUnreadable) {
928
+ findings.push(finding(ts, sf, prop.enumGlobalNameNode, "W606",
929
+ `'${propName}' (@${prop.decorator.name}) passes a global enum name this checker cannot read (it is built at runtime, not written as a literal) — the local-vs-global rule (W613) and the seed cross-check (E206) are both skipped for this field. Write the name as a plain string, or omit it if the enum is local.`));
930
+ }
931
+ return; // local enum — the default, and nothing to check
932
+ }
933
+ // A REFERENCE is an occurrence of the name somewhere other than the property
934
+ // that declares it. Occurrences inside this property do not count, however
935
+ // they are spelled: `key: 'Entity.field'` (the rename key, which by convention
936
+ // is spelled exactly like a global enum name), a hand-written `subType`, a
937
+ // `name`. Counting those as references is what let the shipped violation
938
+ // through — the field's own key made the name look shared.
939
+ const declStart = prop.node.getStart(sf);
940
+ const declEnd = prop.node.getEnd();
941
+ const sites = model.stringLiteralSites.get(name) ?? [];
942
+ const references = sites.filter(
943
+ (s) => !(s.file === sf.fileName && s.start >= declStart && s.end <= declEnd),
944
+ ).length;
945
+ // …and application code outside the schema files counts too: a query that
946
+ // filters by { name: 'Orders.status', value: … } lives in a service, which is
947
+ // never parsed here.
948
+ const referencedElsewhere =
949
+ references === 0 && model.externalTexts.some((text) => text.includes(name));
950
+ if (references === 0 && !referencedElsewhere) {
784
951
  findings.push(finding(ts, sf, prop.decorator.args[0], "W613",
785
- `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing in the ` +
786
- `analyzed files references it. A global name is for enums shared across entities or referenced from ` +
787
- `seeds ({ name: '${name}', value: … }); for an enum used only by this field, omit the first argument ` +
952
+ `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing outside this ` +
953
+ `field references it (its own 'key'/'subType' option does not count as a reference). A global name is for ` +
954
+ `enums shared across entities or referenced from seeds ({ name: '${name}', value: … }); for an enum used ` +
955
+ `only by this field, omit the first argument ` +
788
956
  `— @${prop.decorator.name}(${prop.decorator.name === "Enum" ? "StatusEnum, StatusTitles, " : "…, "}{ … }) — and the decorator derives the name`));
789
957
  }
790
958
  }
@@ -936,11 +1104,17 @@ function checkSubType(ts, sf, propName, prop, typeValue, findings) {
936
1104
  // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
937
1105
  function analyzeEnums(ts, sf, model) {
938
1106
  sf.forEachChild(function walk(node) {
939
- // Every string literal in the analyzed set, counted. A global enum name that
940
- // occurs exactly once is written in its decorator and referenced nowhere —
941
- // which is what W613 is looking for.
1107
+ // Every string literal in the analyzed set, with WHERE it occurs. Counting
1108
+ // alone was not enough: a field conventionally carries `key: 'Entity.field'`
1109
+ // — the same shape as an enum's global name — so a purely local enum whose
1110
+ // decorator ALSO set that key scored two occurrences and W613 stayed silent.
1111
+ // That is the exact shape that shipped. The site lets the check discount
1112
+ // occurrences inside the very property that declares the name.
942
1113
  if (ts.isStringLiteral(node)) {
943
1114
  model.stringLiteralCounts.set(node.text, (model.stringLiteralCounts.get(node.text) ?? 0) + 1);
1115
+ const sites = model.stringLiteralSites.get(node.text) ?? [];
1116
+ sites.push({ file: sf.fileName, start: node.getStart(sf), end: node.getEnd() });
1117
+ model.stringLiteralSites.set(node.text, sites);
944
1118
  }
945
1119
  if (ts.isEnumDeclaration(node)) {
946
1120
  const members = new Map();
@@ -1509,7 +1683,8 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1509
1683
  const model = {
1510
1684
  entities: new Map(), entityByName: new Map(),
1511
1685
  seeds: [], modules: [], stringEnums: new Map(),
1512
- enumDeclarations: [], stringLiteralCounts: new Map(),
1686
+ enumDeclarations: [], stringLiteralCounts: new Map(), stringLiteralSites: new Map(),
1687
+ externalTexts: [],
1513
1688
  };
1514
1689
  const findings = [];
1515
1690
  // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
@@ -1517,6 +1692,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1517
1692
  const sources = uniqueFiles.map((f) =>
1518
1693
  ts.createSourceFile(f, readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
1519
1694
  );
1695
+ model.externalTexts = collectExternalTexts(rootDir, uniqueFiles);
1520
1696
  for (const sf of sources) analyzeImports(ts, sf);
1521
1697
  for (const sf of sources) analyzeEnums(ts, sf, model);
1522
1698
  for (const sf of sources) {
@@ -1543,10 +1719,65 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1543
1719
  findings,
1544
1720
  errors: findings.filter((f) => f.level === "error"),
1545
1721
  warnings: findings.filter((f) => f.level === "warning"),
1722
+ // Deterministic authoring-rule violations, split out so the gate can block
1723
+ // on them without promoting the advisory warnings alongside.
1724
+ ruleWarnings: findings.filter((f) => RULE_WARNINGS.includes(f.code)),
1546
1725
  sdkSource: sdk.source,
1547
1726
  };
1548
1727
  }
1549
1728
 
1729
+ /**
1730
+ * Raw text of every OTHER TypeScript file under the app root — the ones that
1731
+ * carry no schema and so are never parsed: services, controllers, DTOs.
1732
+ *
1733
+ * W613 argues that nothing references an enum's global name. The analyzed set is
1734
+ * entities, seeds and modules only, but an application legitimately names an
1735
+ * enum outside all three — `{ name: 'Orders.status', value: 'new' }` in a query
1736
+ * lives in a service. Without this the check called a genuinely global enum
1737
+ * unreferenced and, now that it blocks, stopped a correct repo from shipping.
1738
+ * A substring scan is enough: the question is only "does this name appear
1739
+ * anywhere else at all", so no parsing is needed.
1740
+ *
1741
+ * The trade is deliberate and one-sided. A mention inside a COMMENT counts as a
1742
+ * reference, so a name that only a comment uses escapes W613 — a false negative.
1743
+ * The alternative, parsing every file in the repo to be exact, buys precision in
1744
+ * a check that BLOCKS the gate, where a false positive costs far more than a
1745
+ * missed warning.
1746
+ */
1747
+ function collectExternalTexts(rootDir, analyzed) {
1748
+ if (!rootDir) return [];
1749
+ const skip = new Set(analyzed.map((f) => resolve(f)));
1750
+ const texts = [];
1751
+ (function walk(dir) {
1752
+ let entries;
1753
+ try {
1754
+ entries = readdirSync(dir);
1755
+ } catch {
1756
+ return; // unreadable directory: absence of evidence, not evidence of absence
1757
+ }
1758
+ for (const name of entries) {
1759
+ if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
1760
+ const p = join(dir, name);
1761
+ let st;
1762
+ try {
1763
+ st = statSync(p);
1764
+ } catch {
1765
+ continue;
1766
+ }
1767
+ if (st.isDirectory()) {
1768
+ walk(p);
1769
+ } else if ((name.endsWith(".ts") || name.endsWith(".tsx")) && !skip.has(resolve(p))) {
1770
+ try {
1771
+ texts.push(readFileSync(p, "utf-8"));
1772
+ } catch {
1773
+ /* unreadable file — skip */
1774
+ }
1775
+ }
1776
+ }
1777
+ })(resolve(rootDir));
1778
+ return texts;
1779
+ }
1780
+
1550
1781
  // ── discovery ──
1551
1782
  export function discoverFiles(rootDir) {
1552
1783
  const files = [];
@@ -1571,9 +1802,13 @@ export function discoverFiles(rootDir) {
1571
1802
  const isMain =
1572
1803
  process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
1573
1804
  if (isMain) {
1574
- const args = process.argv.slice(2);
1805
+ const argv = process.argv.slice(2);
1806
+ // Default is strict: the authoring rules block. --no-strict is the escape for
1807
+ // a legacy repo whose existing entities restate defaults everywhere.
1808
+ const strict = !argv.includes("--no-strict");
1809
+ const args = argv.filter((a) => a !== "--no-strict" && a !== "--strict");
1575
1810
  if (args.length === 0) {
1576
- console.error("usage: node validate-suppa-schema.mjs <app-root-or-files...>");
1811
+ console.error("usage: node validate-suppa-schema.mjs [--no-strict] <app-root-or-files...>");
1577
1812
  process.exit(2);
1578
1813
  }
1579
1814
  let rootDir = null;
@@ -1614,13 +1849,31 @@ if (isMain) {
1614
1849
  console.error(err.message);
1615
1850
  process.exit(2);
1616
1851
  }
1852
+ // W613 argues from absence, so it only blocks when the whole repo was walked:
1853
+ // on an explicit file list the seed that references the enum may simply be
1854
+ // outside the set.
1855
+ const wholeRepo = rootDir !== null;
1856
+ const blocks = (f) =>
1857
+ strict &&
1858
+ RULE_WARNINGS.includes(f.code) &&
1859
+ (wholeRepo || !RULE_WARNINGS_NEEDING_WHOLE_REPO.includes(f.code));
1617
1860
  for (const f of res.findings) {
1861
+ const level = blocks(f) ? "rule violation" : f.level;
1618
1862
  console.log(
1619
- `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1863
+ `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${level}] ${f.message}`,
1620
1864
  );
1621
1865
  }
1866
+ const blocked = res.findings.filter(blocks);
1867
+ const advisory = res.warnings.length - blocked.length;
1622
1868
  console.log(
1623
- `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1869
+ `\n${res.errors.length} error(s), ${blocked.length} rule violation(s), ${advisory} advisory warning(s) ` +
1870
+ `across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1624
1871
  );
1625
- process.exit(res.errors.length > 0 ? 1 : 0);
1872
+ if (blocked.length) {
1873
+ const codes = [...new Set(blocked.map((f) => f.code))].sort().join(", ");
1874
+ console.log(
1875
+ `Rule violations (${codes}) fail the gate. Fix them, or pass --no-strict to record them as warnings instead.`,
1876
+ );
1877
+ }
1878
+ process.exit(res.errors.length + blocked.length > 0 ? 1 : 0);
1626
1879
  }