suppa-mcp-2 1.31.1 → 1.34.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/tools/customFieldsAsCode.js +28 -10
- package/dist/tools/entity.js +192 -2
- package/package.json +1 -1
- package/skills/suppa-entity-code/SKILL.md +33 -0
- package/skills/suppa-entity-code/references/custom-fields.md +236 -0
- package/skills/suppa-entity-code/scripts/house-rules.mjs +5 -2
- package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +208 -2
|
@@ -2,17 +2,35 @@
|
|
|
2
2
|
* Custom fields, declared in the repository instead of typed into a chat.
|
|
3
3
|
*
|
|
4
4
|
* THE PROBLEM THIS FIXES. Every other part of a Suppa application is code: an
|
|
5
|
-
* entity class IS its migration, and a seed is a file. Custom fields
|
|
6
|
-
* exception —
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
5
|
+
* entity class IS its migration, and a seed is a file. Custom fields used to be
|
|
6
|
+
* the exception — they exist only as runtime rows (CustomFieldSets +
|
|
7
|
+
* CustomFieldSetFields + values under the reserved `customFields` key), so the
|
|
8
|
+
* one part of a schema that varies per context was also the one part that lived
|
|
9
|
+
* nowhere in git: not reviewable, not diffable, not reproducible on a second
|
|
10
|
+
* tenant. Nothing forces the DECLARATION to be a chat message; a declaration
|
|
11
|
+
* file in the repo is the source of truth, and this converges a tenant to it.
|
|
12
12
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* PREFER THE SDK WHEN YOU SHIP AN APPLICATION. @suppa/sdk 1.38.0 added a
|
|
14
|
+
* decorator that says all of this in the entity class itself — a nested class
|
|
15
|
+
* of columns reached through a `customFields` property, with the contexts on
|
|
16
|
+
* each column under `options.customFieldSets` (migrations.html#custom-fields,
|
|
17
|
+
* transcribed in docs/.../captures/migrations-custom-fields.txt):
|
|
18
|
+
*
|
|
19
|
+
* @CustomFields(() => TasksCustomFields)
|
|
20
|
+
* customFields?: TasksCustomFields;
|
|
21
|
+
*
|
|
22
|
+
* That route is strictly better where it applies: the platform converges every
|
|
23
|
+
* tenant on start, the property is TYPED, and `@CustomFields` implies the
|
|
24
|
+
* entity option rather than needing it switched on. Reach for THIS tool when it
|
|
25
|
+
* does not apply — an SDK below 1.38.0, a tenant nobody deploys an application
|
|
26
|
+
* to, or an entity another application owns (extension mode ignores the entity
|
|
27
|
+
* option, so the feature still has to be enabled once through
|
|
28
|
+
* suppa_update_entity_options).
|
|
29
|
+
*
|
|
30
|
+
* The two are not rivals: the declaration below is the same
|
|
31
|
+
* `{ entity, context_field, fields[] }` shape the platform's own
|
|
32
|
+
* `custom-fields-json-to-class.ts` turns into that class, so a file written for
|
|
33
|
+
* this tool ports to the decorator without being retyped.
|
|
16
34
|
*
|
|
17
35
|
* { "entity": "ServiceRequests",
|
|
18
36
|
* "context_field": "country",
|
package/dist/tools/entity.js
CHANGED
|
@@ -2460,6 +2460,147 @@ function _shapeProblemsFromDefs(defs, fields, customDefs = []) {
|
|
|
2460
2460
|
}
|
|
2461
2461
|
return problems;
|
|
2462
2462
|
}
|
|
2463
|
+
/**
|
|
2464
|
+
* The Enums group each enum field is bound to, keyed by field name.
|
|
2465
|
+
*
|
|
2466
|
+
* A field whose subType and relationTarget are both empty is bound to NOTHING
|
|
2467
|
+
* (verified live: such a field reads back with no group and owns no values), so
|
|
2468
|
+
* it is left out — there is no group against which to judge a value.
|
|
2469
|
+
*/
|
|
2470
|
+
function _enumGroups(defs) {
|
|
2471
|
+
const groups = Object.create(null); // see `types` above
|
|
2472
|
+
for (const f of defs) {
|
|
2473
|
+
if (!f.name) {
|
|
2474
|
+
continue;
|
|
2475
|
+
}
|
|
2476
|
+
const type = String(f.type ?? "").trim().toLowerCase().replace(/_/g, "-");
|
|
2477
|
+
if (type !== "enum" && type !== "multi-enum") {
|
|
2478
|
+
continue;
|
|
2479
|
+
}
|
|
2480
|
+
const raw = f.subType ?? f.relationTarget;
|
|
2481
|
+
const group = typeof raw === "string" ? raw.trim() : "";
|
|
2482
|
+
if (group) {
|
|
2483
|
+
groups[f.name] = group;
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
return groups;
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* Every enum id a batch writes, paired with the group its field is bound to.
|
|
2490
|
+
*
|
|
2491
|
+
* Pure: the caller does the reading, so every branch is testable without a
|
|
2492
|
+
* network. Only well-shaped references are collected — a value of the wrong
|
|
2493
|
+
* SHAPE is already refused before this runs, and reporting it again here would
|
|
2494
|
+
* say the same thing twice in one refusal.
|
|
2495
|
+
*/
|
|
2496
|
+
export function _enumRefsInRecords(records, defs, customDefs = []) {
|
|
2497
|
+
const core = _enumGroups(defs);
|
|
2498
|
+
const custom = _enumGroups(customDefs);
|
|
2499
|
+
const refs = [];
|
|
2500
|
+
const take = (record, field, group, val) => {
|
|
2501
|
+
for (const one of Array.isArray(val) ? val : [val]) {
|
|
2502
|
+
if (!isPlainObject(one)) {
|
|
2503
|
+
continue;
|
|
2504
|
+
}
|
|
2505
|
+
const raw = one.id;
|
|
2506
|
+
// A numeric string is what a caller who built the id from text sends; the
|
|
2507
|
+
// platform resolves it the same way, so it is the same reference.
|
|
2508
|
+
const id = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() ? Number(raw) : NaN;
|
|
2509
|
+
if (Number.isFinite(id)) {
|
|
2510
|
+
refs.push({ record, field, group, id });
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
};
|
|
2514
|
+
for (const [i, r] of records.entries()) {
|
|
2515
|
+
for (const [key, val] of Object.entries(r)) {
|
|
2516
|
+
if (val === null || val === undefined) {
|
|
2517
|
+
continue;
|
|
2518
|
+
}
|
|
2519
|
+
if (key === CUSTOM_FIELDS_KEY && isPlainObject(val)) {
|
|
2520
|
+
for (const [cname, cval] of Object.entries(val)) {
|
|
2521
|
+
// `id` addresses the values ROW, not a custom field — same exemption
|
|
2522
|
+
// the shape check makes one screen up.
|
|
2523
|
+
if (cname === "id" || cval === null || cval === undefined) {
|
|
2524
|
+
continue;
|
|
2525
|
+
}
|
|
2526
|
+
const group = custom[cname];
|
|
2527
|
+
if (group) {
|
|
2528
|
+
take(i, `${CUSTOM_FIELDS_KEY}.${cname}`, group, cval);
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
continue;
|
|
2532
|
+
}
|
|
2533
|
+
const group = core[key];
|
|
2534
|
+
if (group) {
|
|
2535
|
+
take(i, key, group, val);
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
return refs;
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Refs whose Enums row belongs to a different group — pure, and deliberately
|
|
2543
|
+
* conservative in the same way the shape check is.
|
|
2544
|
+
*
|
|
2545
|
+
* An id the read did not answer with is NOT judged. It may be a row this
|
|
2546
|
+
* account cannot see, or one the read simply missed; refusing a write over a
|
|
2547
|
+
* row we could not read would turn a platform bug into an outage. Only a row
|
|
2548
|
+
* we positively read, carrying a group that is positively different, is a
|
|
2549
|
+
* problem.
|
|
2550
|
+
*/
|
|
2551
|
+
export function _membershipProblems(refs, rows, many) {
|
|
2552
|
+
const problems = [];
|
|
2553
|
+
const seen = new Set();
|
|
2554
|
+
for (const ref of refs) {
|
|
2555
|
+
const row = rows.get(ref.id);
|
|
2556
|
+
if (!row || !row.name || row.name === ref.group) {
|
|
2557
|
+
continue;
|
|
2558
|
+
}
|
|
2559
|
+
const at = many ? `record[${ref.record}]: ` : "";
|
|
2560
|
+
// The same wrong id written to the same field twice is one problem.
|
|
2561
|
+
const key = `${at}${ref.field}:${ref.id}`;
|
|
2562
|
+
if (seen.has(key)) {
|
|
2563
|
+
continue;
|
|
2564
|
+
}
|
|
2565
|
+
seen.add(key);
|
|
2566
|
+
problems.push(`${at}'${ref.field}' is bound to the enum group '${ref.group}', but {"id": ${ref.id}} is a ` +
|
|
2567
|
+
`value of '${row.name}'${row.value ? ` (${row.value})` : ""}. The platform accepts this ` +
|
|
2568
|
+
"and stores it — the record then holds a value its own picker cannot show.");
|
|
2569
|
+
}
|
|
2570
|
+
return problems;
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* The Enums rows behind a set of ids, or null if they cannot be read.
|
|
2574
|
+
*
|
|
2575
|
+
* deletedScope 'all': a soft-deleted row from the RIGHT group is still the
|
|
2576
|
+
* right group, and treating it as missing would leave a legitimate write
|
|
2577
|
+
* unjudged — while a soft-deleted row from the wrong group is still wrong.
|
|
2578
|
+
*/
|
|
2579
|
+
async function _readEnumRows(ids) {
|
|
2580
|
+
try {
|
|
2581
|
+
const rows = await searchEntity("Enums",
|
|
2582
|
+
// One request for the whole batch: an AND of a single OR-group. Nested
|
|
2583
|
+
// conditions are the documented shape (data.txt:36).
|
|
2584
|
+
[{ operator: "or", filters: ids.map((id) => makeFilter("id", id)) }], { id: true, name: true, value: true }, Math.min(Math.max(ids.length, 1), 1000), 0, null, "", "and", "all");
|
|
2585
|
+
const byId = new Map();
|
|
2586
|
+
for (const row of rows) {
|
|
2587
|
+
if (!isPlainObject(row)) {
|
|
2588
|
+
continue;
|
|
2589
|
+
}
|
|
2590
|
+
const r = row;
|
|
2591
|
+
const id = Number(r.id);
|
|
2592
|
+
if (!Number.isFinite(id) || typeof r.name !== "string") {
|
|
2593
|
+
continue;
|
|
2594
|
+
}
|
|
2595
|
+
byId.set(id, { name: r.name, value: typeof r.value === "string" ? r.value : undefined });
|
|
2596
|
+
}
|
|
2597
|
+
return byId;
|
|
2598
|
+
}
|
|
2599
|
+
catch {
|
|
2600
|
+
// Unreadable → say nothing, exactly as an unreadable schema does above.
|
|
2601
|
+
return null;
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2463
2604
|
/**
|
|
2464
2605
|
* A platform refusal this server can say something useful about — or null,
|
|
2465
2606
|
* leaving the error to propagate exactly as before.
|
|
@@ -2562,6 +2703,9 @@ async function _validateRecordWrites(entityName, records) {
|
|
|
2562
2703
|
}
|
|
2563
2704
|
entityName = ent.name;
|
|
2564
2705
|
let defs;
|
|
2706
|
+
// Filled in below when a written enum value turns out to belong to another
|
|
2707
|
+
// group. It rides back to the caller, which attaches it to the RESULT.
|
|
2708
|
+
let enumWarning;
|
|
2565
2709
|
// The SAME schema read carries the entity's custom field definitions in its
|
|
2566
2710
|
// own `customFields` array (name, type, options, setIds) — so validating the
|
|
2567
2711
|
// inline custom values costs no extra request.
|
|
@@ -2619,10 +2763,45 @@ async function _validateRecordWrites(entityName, records) {
|
|
|
2619
2763
|
}
|
|
2620
2764
|
return { entityName, error: jsonResponse(body) };
|
|
2621
2765
|
}
|
|
2766
|
+
// The shape is right; membership is the half the platform does not check.
|
|
2767
|
+
// Costs one read, and only on a write that actually carries an enum value
|
|
2768
|
+
// bound to a group.
|
|
2769
|
+
//
|
|
2770
|
+
// REPORTED, NEVER REFUSED — and that was decided by looking. A sweep of the
|
|
2771
|
+
// dev tenant on 2026-09-11 found 1,111 of 4,504 stored enum values already
|
|
2772
|
+
// sitting in a group other than their field's subType, across 30 entities:
|
|
2773
|
+
// ServiceInstallationChecklist.equipmentType is bound to a group holding one
|
|
2774
|
+
// row with an empty value, while every record stores rows of 'equipment_type'.
|
|
2775
|
+
// A refusal would therefore block a quarter of this tenant's enum writes —
|
|
2776
|
+
// read-modify-write re-sends the field, so ordinary edits to untouched
|
|
2777
|
+
// columns would start failing. The check is worth making and is not worth an
|
|
2778
|
+
// outage: say so on the way past.
|
|
2779
|
+
const refs = _enumRefsInRecords(records, defs, customDefs);
|
|
2780
|
+
if (refs.length > 0) {
|
|
2781
|
+
const rows = await _readEnumRows([...new Set(refs.map((r) => r.id))]);
|
|
2782
|
+
if (rows) {
|
|
2783
|
+
const wrongGroup = _membershipProblems(refs, rows, many);
|
|
2784
|
+
if (wrongGroup.length > 0) {
|
|
2785
|
+
enumWarning = {
|
|
2786
|
+
warning: "These enum values belong to a DIFFERENT group than the field they were written " +
|
|
2787
|
+
"to. The platform does not check this, so the write went through and the value is " +
|
|
2788
|
+
"stored.",
|
|
2789
|
+
problems: wrongGroup,
|
|
2790
|
+
note: "NOT blocked, on purpose: on the dev tenant 1,111 of 4,504 stored enum values were " +
|
|
2791
|
+
"already in this state, so refusing would break ordinary updates to existing " +
|
|
2792
|
+
"records. Treat it as something to check, not as a failure.",
|
|
2793
|
+
hint: "An enum field is bound to the group named by its subType (suppa_describe_entity " +
|
|
2794
|
+
"shows it). To see that group's real values, search Enums by that name: " +
|
|
2795
|
+
'suppa_search_records(entity_name="Enums", filters_json=' +
|
|
2796
|
+
'[{"field": "name", "value": "<group>", "comparator": "="}]).',
|
|
2797
|
+
};
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2800
|
+
}
|
|
2622
2801
|
}
|
|
2623
2802
|
// The defs travel back so the caller does not re-read the schema to decide
|
|
2624
2803
|
// which written fields are actually list-valued (see `_replacedListNames`).
|
|
2625
|
-
return { entityName, defs: defs && defs.length > 0 ? defs : null };
|
|
2804
|
+
return { entityName, defs: defs && defs.length > 0 ? defs : null, enumWarning };
|
|
2626
2805
|
}
|
|
2627
2806
|
// The only field types whose stored value IS a list, so the only ones an update
|
|
2628
2807
|
// can replace wholesale and the only ones merge/unmerge applies to. Types from
|
|
@@ -2747,13 +2926,17 @@ export async function createRecord(entityName, fieldsJson) {
|
|
|
2747
2926
|
reason: "Platform returned no row — nothing was inserted or the response was empty",
|
|
2748
2927
|
});
|
|
2749
2928
|
}
|
|
2750
|
-
|
|
2929
|
+
// Namespaced with a leading underscore so it cannot collide with a field:
|
|
2930
|
+
// the bare record IS the documented shape here, and this key only appears
|
|
2931
|
+
// when there is something to say.
|
|
2932
|
+
return jsonResponse(v.enumWarning ? { ...returned[0], _enum_group_warning: v.enumWarning } : returned[0]);
|
|
2751
2933
|
}
|
|
2752
2934
|
return jsonResponse({
|
|
2753
2935
|
created: returned.length,
|
|
2754
2936
|
requested: rows.length,
|
|
2755
2937
|
entity: v.entityName,
|
|
2756
2938
|
records: returned,
|
|
2939
|
+
...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
|
|
2757
2940
|
});
|
|
2758
2941
|
}
|
|
2759
2942
|
/** Parse a merge_json/unmerge_json parameter into a list of field names. */
|
|
@@ -2837,6 +3020,10 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
|
|
|
2837
3020
|
entity: entityName,
|
|
2838
3021
|
reason: "Platform returned no row — record id may not exist, be " +
|
|
2839
3022
|
"deleted, or the values matched the stored ones (no-op).",
|
|
3023
|
+
// A write that matched nothing still CARRIED the value, and the caller
|
|
3024
|
+
// still chose it. Dropping the warning here hid it from every probe that
|
|
3025
|
+
// targets a missing row — which is how this omission was found.
|
|
3026
|
+
...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
|
|
2840
3027
|
result,
|
|
2841
3028
|
});
|
|
2842
3029
|
}
|
|
@@ -2860,6 +3047,9 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
|
|
|
2860
3047
|
"To add items instead, re-send with merge_json; to remove only the listed " +
|
|
2861
3048
|
"items, use unmerge_json.";
|
|
2862
3049
|
}
|
|
3050
|
+
if (v.enumWarning) {
|
|
3051
|
+
out.enum_group_warning = v.enumWarning;
|
|
3052
|
+
}
|
|
2863
3053
|
out.result = Array.isArray(result) && result.length ? result[0] : result;
|
|
2864
3054
|
return jsonResponse(out);
|
|
2865
3055
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "suppa-mcp-2",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.34.0",
|
|
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": {
|
|
@@ -98,6 +98,39 @@ Confirm all 5 before writing anything:
|
|
|
98
98
|
**Prefer an entity-scoped enum in an extension.** A global enum name has no owning entity, so two applications using the same name write to the same rows — which is rule 18's default anyway: pass no name.
|
|
99
99
|
21. **`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.
|
|
100
100
|
|
|
101
|
+
22. **Custom fields are declared in code too — and the nested class that holds them is NOT an entity.** A field every record of the entity shows is an ordinary column and belongs in the entity class; only a field whose presence depends on another field's VALUE is a custom field. Declare those as a plain class of columns, reached through a property on the owner (`references/custom-fields.md`). **Needs `@suppa/sdk` 1.38.0** — "older SDKs have no way to describe custom fields from an application", so below that floor there is no code route and the API tools (`suppa_add_custom_field`, `suppa_apply_custom_fields`) are the answer.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
export class TasksCustomFields {
|
|
105
|
+
@Column({
|
|
106
|
+
type: FieldTypeEnum.Numeric,
|
|
107
|
+
nullable: true,
|
|
108
|
+
title: { en: 'Budget', uk: 'Бюджет' },
|
|
109
|
+
options: { customFieldSets: [{ contextField: 'category', contextValue: 'design' }] },
|
|
110
|
+
})
|
|
111
|
+
cfBudget?: number;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@Entity({ name: 'Tasks' })
|
|
115
|
+
export class Tasks extends SystemBaseEntity {
|
|
116
|
+
@Column({ name: 'category', type: FieldTypeEnum.Text })
|
|
117
|
+
category?: string;
|
|
118
|
+
|
|
119
|
+
@CustomFields(() => TasksCustomFields)
|
|
120
|
+
customFields?: TasksCustomFields;
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Five things bind, and the first is the one this skill's own reflexes get wrong:
|
|
125
|
+
|
|
126
|
+
- **The nested class has no `@Entity()`, does not extend `SystemBaseEntity`, and is NEVER passed to `forFeature()`** — register only the owner. Rules 19 and 21 do not reach it: it names no table of its own, and registering it makes the platform build a plain table where the generated `{Entity}CustomFields` belongs, which "would break every custom-field read and write". The table is named after the OWNER, never after the class.
|
|
127
|
+
- **The property must be named `customFields`**, and one class serves one owner — "that is the name the platform gives the back reference; both rules fail the build loudly".
|
|
128
|
+
- **`@CustomFields` implies `options: { customFields: true }`.** Writing that option beside it repeats what the decorator already says (rule 16).
|
|
129
|
+
- **Every column needs `options.customFieldSets`** — `{ contextField, contextValue, required?, readOnly?, defaultValue? }`, one field and one value per set, no compound conditions. `contextValue` is a business key (an enum's stored value, a relation's import key), not an id, which is what makes the declaration portable between workspaces. A column with no set "exists in the metadata but no record shows it" — valid, and almost never what you meant.
|
|
130
|
+
- **Inside the nested class the extension-mode restrictions apply:** `nullable: false` needs a `default`; `primary`, `@OneToMany()` and `@ManyToManyBackRef()` are rejected. Every other house rule still binds there too — relation typing (14), no option at its default (16), local enums unnamed (17), stubs for existing targets (19).
|
|
131
|
+
|
|
132
|
+
On an entity you do **not** own, the columns still come from your file — only the switch is out of reach: extension mode ignores entity options, so enable the feature once with `suppa_update_entity_options(entity_name, '{"customFields": true}')` (`POST /core/builder/<Entity>/update-options`). That is what W618 means when it fires on `options`.
|
|
133
|
+
|
|
101
134
|
## Decorator decision table
|
|
102
135
|
|
|
103
136
|
| You need | Decorator |
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# Custom fields in code — verbatim rules
|
|
2
|
+
|
|
3
|
+
Transcribed from docs.modern-expo.com/backend/application-developing/migrations.html, section "Custom Fields" (captured 2026-09-11). The full capture is `docs/superpowers/specs/captures/migrations-custom-fields.txt` in the suppa-mcp-2 repository. If a rule is not here, it does not exist — stop and ask.
|
|
4
|
+
|
|
5
|
+
**Requires `@suppa/sdk` 1.38.0.** The doc is explicit: "`@CustomFields` and the declarative sets land in 1.38.0. Older SDKs have no way to describe custom fields from an application." Below that floor there is no code route at all — use the API tools (`suppa_add_custom_field`, `suppa_apply_custom_fields`) against the tenant instead. Check the floor before you write the class; a decorator that does not exist in the installed SDK fails at import, not at migration time.
|
|
6
|
+
|
|
7
|
+
## What they are
|
|
8
|
+
|
|
9
|
+
> Custom fields are the extra fields a workspace shows **per context** — the fields a task of category `design` has and a task of category `support` does not. The platform keeps them in a generated extension table `{Entity}CustomFields`: one row per owner record, one real typed column per field. **Field sets** describe where each field applies.
|
|
10
|
+
|
|
11
|
+
This is the distinction that decides whether a field belongs here at all: **a field every record of the entity shows is an ordinary column** and belongs in the entity class. Only a field whose presence depends on another field's value is a custom field.
|
|
12
|
+
|
|
13
|
+
## The declaration
|
|
14
|
+
|
|
15
|
+
> An application declares them the way a Nest controller declares a nested body: a class holds the fields, and the owner entity carries that class on a `customFields` property.
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import {
|
|
19
|
+
Column,
|
|
20
|
+
CustomFields,
|
|
21
|
+
Entity,
|
|
22
|
+
FieldTypeEnum,
|
|
23
|
+
SystemBaseEntity,
|
|
24
|
+
} from '@suppa/sdk';
|
|
25
|
+
|
|
26
|
+
export class TasksCustomFields {
|
|
27
|
+
@Column({
|
|
28
|
+
type: FieldTypeEnum.Numeric,
|
|
29
|
+
nullable: true,
|
|
30
|
+
title: { en: 'Budget', uk: 'Бюджет' },
|
|
31
|
+
options: {
|
|
32
|
+
customFieldSets: [
|
|
33
|
+
{ contextField: 'category', contextValue: 'design' },
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
cfBudget?: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
@Entity({ name: 'Tasks', importKeyFields: ['shortUID'] })
|
|
41
|
+
export class Tasks extends SystemBaseEntity {
|
|
42
|
+
@Column({ name: 'title', type: FieldTypeEnum.Text, nullable: false })
|
|
43
|
+
title: string;
|
|
44
|
+
|
|
45
|
+
@Column({ name: 'category', type: FieldTypeEnum.Text })
|
|
46
|
+
category?: string;
|
|
47
|
+
|
|
48
|
+
@CustomFields(() => TasksCustomFields)
|
|
49
|
+
customFields?: TasksCustomFields;
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Three things follow from that one declaration:
|
|
54
|
+
|
|
55
|
+
| What | How |
|
|
56
|
+
|---|---|
|
|
57
|
+
| The feature is switched on for `Tasks` | "The `@CustomFields` property implies `options: { customFields: true }`" |
|
|
58
|
+
| `TasksCustomFields` becomes the columns of the `TasksCustomFields` table | The nested class is applied to the platform-generated extension table |
|
|
59
|
+
| Where each field applies | `options.customFieldSets` on the column |
|
|
60
|
+
|
|
61
|
+
> And because the property is typed, `customFields.cfBudget` is a real type everywhere the record is read or written.
|
|
62
|
+
|
|
63
|
+
**Do not write `options: { customFields: true }` next to `@CustomFields`.** The decorator implies it, and an option written at a value something else already sets is the same mistake as writing one at its default (rule 16).
|
|
64
|
+
|
|
65
|
+
## The nested class is NOT an entity
|
|
66
|
+
|
|
67
|
+
> Register **only the owner** in `EntityModule.forFeature()`. The nested class is not an entity, has no `@Entity()`, does not extend `SystemBaseEntity` and is never registered — it is reached through the owner's property.
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
EntityModule.forFeature([Tasks], { seeds: [] });
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
This is the one place where the skill's usual reflex is wrong. Rule 19 says a class that names a table gets `@Entity()` and registration; rule 21 says a class that never reaches `forFeature()` does not exist. **Neither applies to the nested class** — it names no table of its own, and registering it would make the platform build a plain table where the generated extension table belongs:
|
|
74
|
+
|
|
75
|
+
> Only the **columns** are applied — no entity row is ever written for `{Entity}CustomFields`. The generated table carries the `owner` relation and the back reference; writing an entity row of your own would replace it with a plain table and break every custom-field read and write.
|
|
76
|
+
|
|
77
|
+
What the platform creates for you on start: "a unique `owner` relation back to `Tasks`, the standard columns, and a `customFields` back reference on the owner. Re-running is a no-op, and disabling the option later never drops the table or the values in it."
|
|
78
|
+
|
|
79
|
+
## Two names that are not yours to choose
|
|
80
|
+
|
|
81
|
+
| Rule | Why |
|
|
82
|
+
|---|---|
|
|
83
|
+
| "The table is named after the **owner**, never after the class." | `@CustomFields(() => Whatever)` on `Tasks` always applies to `TasksCustomFields`. |
|
|
84
|
+
| "The property must be named `customFields`, and one class serves one owner." | "That is the name the platform gives the back reference; both rules fail the build loudly." |
|
|
85
|
+
|
|
86
|
+
## The fields
|
|
87
|
+
|
|
88
|
+
> Every property of the nested class is one custom field, declared with the same decorators as any other field — `@Column()`, `@ManyToOne()`, `@ManyToMany()`, `@Enum()`, `@MultiEnum()`, `@File()`, `@MultiFile()`
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
export class ServiceProductsCustomFields {
|
|
92
|
+
@Column({
|
|
93
|
+
name: 'articleCode',
|
|
94
|
+
type: FieldTypeEnum.Text,
|
|
95
|
+
nullable: true,
|
|
96
|
+
title: { en: 'Article code' },
|
|
97
|
+
})
|
|
98
|
+
articleCode?: string;
|
|
99
|
+
|
|
100
|
+
@ManyToOne(() => Compressors, {
|
|
101
|
+
name: 'compressor',
|
|
102
|
+
nullable: true,
|
|
103
|
+
title: { en: 'Compressor', uk: 'Компресор' },
|
|
104
|
+
})
|
|
105
|
+
compressor?: Compressors;
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Restrictions, and they are the **extension-mode restrictions** — the generated table is not this application's to reshape:
|
|
110
|
+
|
|
111
|
+
> `nullable: false` needs a `default`; `primary`, `@OneToMany()` and `@ManyToManyBackRef()` are rejected.
|
|
112
|
+
|
|
113
|
+
Every other house rule still binds inside the nested class: relation properties carry their type (rule 14), no option at its default (rule 16), a local enum takes no global name (rule 17), a relation target that already exists gets a stub (rule 19).
|
|
114
|
+
|
|
115
|
+
One default worth knowing rather than writing: "Columns default to `initiator: 'client'` — the marker of a *custom* field. Only a client field is reported as `isCustom` by the schema API and offered as a custom field by forms. Pass `initiator` explicitly only to opt out."
|
|
116
|
+
|
|
117
|
+
## Where each field applies
|
|
118
|
+
|
|
119
|
+
> A set binds the owner entity to **one context value** — one field, one value, no compound conditions.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
@Column({
|
|
123
|
+
name: 'cfBudget',
|
|
124
|
+
type: FieldTypeEnum.Numeric,
|
|
125
|
+
nullable: true,
|
|
126
|
+
options: {
|
|
127
|
+
customFieldSets: [
|
|
128
|
+
{ contextField: 'category', contextValue: 'design', required: true },
|
|
129
|
+
{ contextField: 'category', contextValue: 'support' },
|
|
130
|
+
],
|
|
131
|
+
},
|
|
132
|
+
})
|
|
133
|
+
cfBudget?: number;
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
| Key | Meaning |
|
|
137
|
+
|---|---|
|
|
138
|
+
| `contextField` | "Name of the field **on the owner** whose value decides the context. It must exist on the owner." |
|
|
139
|
+
| `contextValue` | "The value that turns the set on" — resolved, see below |
|
|
140
|
+
| `required` | "The field must be filled on a record of this context. Default `false`." |
|
|
141
|
+
| `readOnly` | "Per-set override of the field's own `readOnly`. `null` (default) defers to the field." |
|
|
142
|
+
| `defaultValue` | "Per-set default. `null` (default) defers to the field." |
|
|
143
|
+
|
|
144
|
+
`contextValue` is written as a business key, not an id:
|
|
145
|
+
|
|
146
|
+
| Context field type | What `contextValue` may say | Resolved to |
|
|
147
|
+
|---|---|---|
|
|
148
|
+
| text / numeric / boolean | the value itself (`'design'`) | the value itself |
|
|
149
|
+
| `@Enum` / `@MultiEnum` | the stored enum value (`'Refrigeration equipment'`) | the id of that `Enums` row |
|
|
150
|
+
| `@ManyToOne` / `@ManyToMany` | the target's import key, its representative value, or the row id | the id of that row |
|
|
151
|
+
|
|
152
|
+
> That resolution is what makes a declaration portable: ids differ from workspace to workspace, business keys do not. A relation target with neither `importKeyFields` nor a representative field cannot be matched by name — declare the row id there, or give the entity an import key.
|
|
153
|
+
|
|
154
|
+
Sets are shared: "two fields declaring the same `(contextField, contextValue)` land in the same set, and a set a workspace administrator already created by hand is reused, not duplicated."
|
|
155
|
+
|
|
156
|
+
**A field with no set never shows up.** A column declared without `customFieldSets` "exists in the metadata (and in `GET /core/schema/Tasks` with an empty `setIds`) but no record shows it. That is a valid intermediate state — an administrator can create the sets in the workspace — but it is rarely what a migration wants."
|
|
157
|
+
|
|
158
|
+
## An entity you do not own
|
|
159
|
+
|
|
160
|
+
> [Extension mode](./extensions.md) ignores entity-level options, so an application cannot switch the feature on for an entity that belongs to the platform, to another application, or to the workspace itself — the `@CustomFields` property still applies its columns, but the extension table has to exist. Enable the feature once per workspace through the API (or ask an administrator to):
|
|
161
|
+
|
|
162
|
+
```http
|
|
163
|
+
POST /core/builder/ServiceProducts/update-options
|
|
164
|
+
{ "customFields": true }
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Read that carefully, because half of it is easy to miss: **the columns still come from your file.** Only the switch is out of reach. With the Suppa MCP server the same call is `suppa_update_entity_options(entity_name, options_json)`; it is a schema change (it creates the `{Entity}CustomFields` side table), so record it in the plan beside the code that depends on it. This is what W618 is telling you when it fires on `options` in an extension.
|
|
168
|
+
|
|
169
|
+
## What happens on start
|
|
170
|
+
|
|
171
|
+
1. "The owner entity converges — and the `customFields` option implied by the property creates `{Entity}CustomFields` with the `owner` relation if it does not exist yet."
|
|
172
|
+
2. "The columns of the nested class are created on that table as client fields, with their titles."
|
|
173
|
+
3. "`options.customFieldSets` is materialized: each set is found or created, each link is created or brought in line with the declaration."
|
|
174
|
+
|
|
175
|
+
> All three steps are idempotent, so restarts and redeploys converge instead of duplicating. Steps 2 and 3 run inside the write transaction: a context that cannot be resolved fails the migration instead of leaving half a declaration behind.
|
|
176
|
+
|
|
177
|
+
**First boot of a brand-new owner.** "When the owner entity, the option and the custom fields all arrive in the very same first import, the column of a custom field can lose a race against the DDL that creates the extension table (`deadlock detected`). The next start applies it — nothing is lost and nothing needs fixing by hand, but do not read that first-boot error as a broken declaration."
|
|
178
|
+
|
|
179
|
+
## Reading and writing values
|
|
180
|
+
|
|
181
|
+
Values ride the owner record under the same `customFields` key:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
await manager.insertOne('Tasks', {
|
|
185
|
+
title: 'Landing page',
|
|
186
|
+
category: 'design',
|
|
187
|
+
customFields: { cfBudget: 500 },
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const [task] = await manager.select('Tasks', {
|
|
191
|
+
fields: { id: true, customFields: { cfBudget: true } },
|
|
192
|
+
conditions: {
|
|
193
|
+
operator: 'and',
|
|
194
|
+
filters: [
|
|
195
|
+
{ field: 'customFields.cfBudget', comparator: '>', value: 100 },
|
|
196
|
+
],
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
> Only the keys present in `customFields` are written; the write guard rejects a value whose field is not in a set active for that record, and enforces `required`.
|
|
202
|
+
|
|
203
|
+
## Limits worth knowing
|
|
204
|
+
|
|
205
|
+
- **"A link is never removed automatically."** Dropping a `customFieldSets` entry stops the platform re-creating it, "but the existing link stays — a workspace may have curated it. Remove it in the workspace (or through `CustomFieldSetFields`) when you mean it."
|
|
206
|
+
- **"Removing a property follows the normal rules."** It soft-deletes the field and renames the column; re-declaring restores the row with its data. "A field a workspace administrator removed is not resurrected by the next start."
|
|
207
|
+
- **"A field a user created through the UI is not a collision."** The declaration takes it over, keeping the column and the data.
|
|
208
|
+
- **"The per-table custom field cap guards the API, not migrations."** A declaration can push a table past it; watch the column count.
|
|
209
|
+
|
|
210
|
+
## Porting a list of existing custom fields
|
|
211
|
+
|
|
212
|
+
> Turn it into one nested class per owner entity, one property per field, with the contexts of that field in `options.customFieldSets` — and keep the source file in the repository next to it: the class is the migration, the dump is the provenance.
|
|
213
|
+
|
|
214
|
+
For a large port the platform ships a generator rather than asking you to type it: `scripts/custom-fields-json-to-class.ts` in the `modern-expo` application (git.modern-expo.com/suppa/applications/modern-expo) turns a `{ entity, context_field, fields[] }` dump into the class and "reports the fields that still need a decision (enum value lists, unresolved relation targets)".
|
|
215
|
+
|
|
216
|
+
That dump shape is exactly the declaration `suppa_apply_custom_fields` reads, so a file written for the MCP tool ports to the decorator without being retyped — and vice versa.
|
|
217
|
+
|
|
218
|
+
## What the API reference adds
|
|
219
|
+
|
|
220
|
+
The migrations page links to a separate [custom fields API reference](https://docs.modern-expo.com/backend/api/entity-builder/custom-fields.html) for "the full contract — projections, search, per-set attributes". Captured as `docs/superpowers/specs/captures/api-custom-fields.txt`. Six things there change how you write the class:
|
|
221
|
+
|
|
222
|
+
- **There is a per-table cap.** Active client fields per extension table are limited by `CUSTOM_FIELDS_LIMIT`, **default 200**; exceeding it answers 400 with the usage numbers. The migrations page says the cap "guards the API, not migrations" — a declaration can push a table past it, and then the API stops serving that table. Count the properties before porting a large list.
|
|
223
|
+
- **Sets are inherited down a hierarchy.** "When the context field relates to a hierarchical entity with `parents`, sets also apply to descendants of the `contextValue`." So a field declared for a parent context shows on records of its children; you do not declare one entry per descendant.
|
|
224
|
+
- **A field in several sets merges its per-set attributes**, and the rules are not "last wins": `required` — any set demanding it wins; `readOnly` — an explicit editable beats a read-only, `null` defers to the field; `defaultValue` — the first non-null in set id order.
|
|
225
|
+
- **The owner's schema already lists the sets.** `GET /core/schema/<E>` carries a `customFieldSets` array (`id`, `title`, `contextFieldName`, `contextValue`) beside `customFields` with their `setIds` — the cheap way to see every context at once. It is schema only; the ACTIVE set for a given record still comes from `/custom-fields/<E>/resolve`.
|
|
226
|
+
- **You can sort and filter through a relation custom field** — `customFields.reviewer.fullName` — because each step of the chain yields at most one row. A multi-row collection in the chain is `400 query.planner_unsupported`. Full-text search covers the extension table's own searchable TEXT fields only (not a relation's content), and the base entity must have at least one searchable field of its own.
|
|
227
|
+
- **Write values inline on the owner, not on the extension table.** Both paths validate against the active sets, but a direct extension-table write "bridges into an owner update after the values row is written" and is **not atomic** — the values commit first. Inline writes run inside the owner's transaction, bump `updatedAt`, and fire triggers, socket events and automations with `customFields` among the changed fields.
|
|
228
|
+
|
|
229
|
+
## Which route to take
|
|
230
|
+
|
|
231
|
+
| Situation | Route |
|
|
232
|
+
|---|---|
|
|
233
|
+
| You ship an application and the SDK is ≥ 1.38.0 | The decorator. The platform converges every tenant on start and the property is typed. |
|
|
234
|
+
| SDK below 1.38.0 | `suppa_add_custom_field` / `suppa_apply_custom_fields` against the tenant. |
|
|
235
|
+
| No application is deployed to this tenant | The API tools. |
|
|
236
|
+
| The owner belongs to another application | Both: the columns come from your file, but the option is enabled once through `suppa_update_entity_options`. |
|
|
@@ -30,5 +30,8 @@ export const BLOCKING_SUMMARY =
|
|
|
30
30
|
"(E116/E117/W616/W617), extension mode — ignored entity options, no reverse relations, no primary, " +
|
|
31
31
|
"no NOT NULL without a default, indexes over your own columns only (W618/E118/E119/E120/E121/E122/E123/W620), " +
|
|
32
32
|
"`owner` first in a tabular part's importKeyFields (W607), no second entity class of the same name — " +
|
|
33
|
-
"the other one is then analyzed by nothing (W619)
|
|
34
|
-
"`inverse` on @ManyToOne/@ManyToMany (W609)"
|
|
33
|
+
"the other one is then analyzed by nothing (W619), no " +
|
|
34
|
+
"`inverse` on @ManyToOne/@ManyToMany (W609) — and, on a @CustomFields class, never registering or " +
|
|
35
|
+
"decorating it, the `customFields` property name, a set on every column, no primary, no reverse " +
|
|
36
|
+
"relation, no NOT NULL without a default " +
|
|
37
|
+
"(E124/E125/E126/E127/E128/W621/W622/W623)";
|
|
@@ -71,6 +71,9 @@ export const RULE_WARNINGS = [
|
|
|
71
71
|
"W617", // field-less entity in a file not named <name>.stub.entity.ts
|
|
72
72
|
"W618", // extension declaring entity options extension mode ignores
|
|
73
73
|
"W620", // relation target named by string outside an extension
|
|
74
|
+
"W621", // custom-field column with no customFieldSets: no record shows it
|
|
75
|
+
"W622", // customFieldSets contextField names no field on the owner
|
|
76
|
+
"W623", // options: { customFields: true } written beside @CustomFields
|
|
74
77
|
];
|
|
75
78
|
/**
|
|
76
79
|
* W613 argues from ABSENCE — "nothing references this name". That only holds
|
|
@@ -702,6 +705,14 @@ function analyzeEntities(ts, sf, model, opts = {}) {
|
|
|
702
705
|
optionsNode: d.args[0] ?? null,
|
|
703
706
|
nameNode: objectMap(ts, d.args[0]).get("name") ?? null,
|
|
704
707
|
});
|
|
708
|
+
} else if (d.name === "CustomFields") {
|
|
709
|
+
// Not a field: it names the class that becomes the columns of the
|
|
710
|
+
// platform-generated {Owner}CustomFields table. Kept off
|
|
711
|
+
// info.properties so no field rule treats it as a column.
|
|
712
|
+
info.customFieldsProp = {
|
|
713
|
+
propName, node: member, decorator: d,
|
|
714
|
+
targetClass: thunkTarget(ts, sf, d.args[0]),
|
|
715
|
+
};
|
|
705
716
|
} else if (d.name in RELATION_KIND_BY_DECORATOR) {
|
|
706
717
|
// (target, options?) or (target, inverse, options?) — the options
|
|
707
718
|
// object is whichever trailing argument is an object literal; the
|
|
@@ -757,6 +768,198 @@ function analyzeEntities(ts, sf, model, opts = {}) {
|
|
|
757
768
|
});
|
|
758
769
|
}
|
|
759
770
|
|
|
771
|
+
// ── rules: custom fields declared in code (@suppa/sdk 1.38.0) ──
|
|
772
|
+
/**
|
|
773
|
+
* `@CustomFields(() => Cls)` on an owner entity, with Cls a PLAIN class of
|
|
774
|
+
* columns. Transcribed from migrations.html#custom-fields (captured in
|
|
775
|
+
* docs/superpowers/specs/captures/migrations-custom-fields.txt).
|
|
776
|
+
*
|
|
777
|
+
* This is the one place where this checker's own habits point at the wall.
|
|
778
|
+
* Rule 19 says a class naming a table gets @Entity() and registration; rule 21
|
|
779
|
+
* says a class never passed to forFeature() is invisible. Neither reaches the
|
|
780
|
+
* nested class: it names no table of its own, and registering it makes the
|
|
781
|
+
* platform build a plain table where the generated extension table belongs —
|
|
782
|
+
* "writing an entity row of your own would replace it with a plain table and
|
|
783
|
+
* break every custom-field read and write". Nothing else would catch that, and
|
|
784
|
+
* the damage is silent, so it is an error rather than a warning.
|
|
785
|
+
*/
|
|
786
|
+
function checkCustomFieldsClasses(ts, model, findings) {
|
|
787
|
+
const registered = new Set(model.modules.flatMap((m) => m.entities.names));
|
|
788
|
+
for (const info of model.entities.values()) {
|
|
789
|
+
if (info.outOfScope) continue;
|
|
790
|
+
const cf = info.customFieldsProp;
|
|
791
|
+
if (!cf) continue;
|
|
792
|
+
|
|
793
|
+
// "The property must be named `customFields`, and one class serves one
|
|
794
|
+
// owner. That is the name the platform gives the back reference; both rules
|
|
795
|
+
// fail the build loudly."
|
|
796
|
+
if (cf.propName !== "customFields") {
|
|
797
|
+
findings.push(finding(ts, info.sf, cf.node, "E125",
|
|
798
|
+
`@CustomFields is on a property called '${cf.propName}', but the platform names the back ` +
|
|
799
|
+
`reference 'customFields' and accepts no other — the build fails loudly on this. Rename the ` +
|
|
800
|
+
`property to customFields; the extension table is named after the OWNER either way ` +
|
|
801
|
+
`('${info.entityName}CustomFields'), never after the class.`));
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// "The `@CustomFields` property implies `options: { customFields: true }`."
|
|
805
|
+
const optNode = info.options.get("options");
|
|
806
|
+
if (optNode) {
|
|
807
|
+
const entityOpts = objectMap(ts, optNode);
|
|
808
|
+
if (entityOpts.get("customFields")) {
|
|
809
|
+
findings.push(finding(ts, info.sf, entityOpts.get("customFields"), "W623",
|
|
810
|
+
`options: { customFields: … } is written beside @CustomFields, which already implies it. ` +
|
|
811
|
+
`Delete the option and keep the decorator — two statements of one fact drift apart.`));
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const targetName = cf.targetClass;
|
|
816
|
+
if (!targetName) {
|
|
817
|
+
findings.push(finding(ts, info.sf, cf.node, "W624",
|
|
818
|
+
`@CustomFields target cannot be read as a thunk returning a class, so none of the ` +
|
|
819
|
+
`custom-field rules could run on it. Write it as @CustomFields(() => ${info.className}CustomFields).`));
|
|
820
|
+
continue;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// Registering it is the silent breaker.
|
|
824
|
+
if (registered.has(targetName)) {
|
|
825
|
+
findings.push(finding(ts, info.sf, cf.node, "E124",
|
|
826
|
+
`'${targetName}' is passed to EntityModule.forFeature(), but the class behind @CustomFields ` +
|
|
827
|
+
`is NOT an entity — "register only the owner". Registering it makes the platform build a ` +
|
|
828
|
+
`plain table where the generated '${info.entityName}CustomFields' belongs, which breaks every ` +
|
|
829
|
+
`custom-field read and write. Remove it from forFeature(); only '${info.className}' belongs there.`));
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
const binding = findLocalBinding(ts, info.sf, targetName);
|
|
833
|
+
if (!binding || binding.kind !== "class") {
|
|
834
|
+
// Declared elsewhere: the registration check above still applied, but the
|
|
835
|
+
// column rules need the class body. Say a check was skipped rather than
|
|
836
|
+
// implying the class is clean.
|
|
837
|
+
findings.push(finding(ts, info.sf, cf.node, "W624",
|
|
838
|
+
`the class '${targetName}' behind @CustomFields is not declared in this file, so its columns ` +
|
|
839
|
+
`were not checked (no-set columns, nullable without default, primary, reverse relations). ` +
|
|
840
|
+
`The doc keeps it beside the owner it serves.`));
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const cls = binding.node;
|
|
845
|
+
const clsDecs = decoratorsOf(ts, cls).map((d) => decoratorCall(ts, d, info.sf)).filter(Boolean);
|
|
846
|
+
if (clsDecs.some((d) => d.name === "Entity")) {
|
|
847
|
+
findings.push(finding(ts, info.sf, cls.name ?? cls, "E124",
|
|
848
|
+
`'${targetName}' carries @Entity(), but the class behind @CustomFields "is not an entity, has ` +
|
|
849
|
+
`no @Entity(), does not extend SystemBaseEntity and is never registered". With @Entity() the ` +
|
|
850
|
+
`platform builds a plain table instead of the generated extension table, breaking every ` +
|
|
851
|
+
`custom-field read and write. Delete the decorator.`));
|
|
852
|
+
}
|
|
853
|
+
const heritage = cls.heritageClauses ?? [];
|
|
854
|
+
const extendsSomething = heritage.some((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
|
|
855
|
+
if (extendsSomething) {
|
|
856
|
+
findings.push(finding(ts, info.sf, cls.name ?? cls, "E124",
|
|
857
|
+
`'${targetName}' extends a base class, but the class behind @CustomFields "does not extend ` +
|
|
858
|
+
`SystemBaseEntity" — the generated table already carries the owner relation and the standard ` +
|
|
859
|
+
`columns. Declare it as a plain class: export class ${targetName} { … }.`));
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
checkCustomFieldColumns(ts, info, cls, findings);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/** Every property of the nested class is one custom field. */
|
|
867
|
+
function checkCustomFieldColumns(ts, info, cls, findings) {
|
|
868
|
+
const ownerFields = new Set();
|
|
869
|
+
for (const [propName, prop] of info.properties) {
|
|
870
|
+
ownerFields.add(propName);
|
|
871
|
+
const colName = stringValue(ts, prop.nameNode);
|
|
872
|
+
if (colName) ownerFields.add(colName);
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
for (const member of cls.members ?? []) {
|
|
876
|
+
if (!member.name) continue;
|
|
877
|
+
const propName = ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
|
|
878
|
+
? member.name.text : member.name.getText(info.sf);
|
|
879
|
+
const decs = decoratorsOf(ts, member).map((d) => decoratorCall(ts, d, info.sf)).filter(Boolean);
|
|
880
|
+
if (!decs.length) continue;
|
|
881
|
+
|
|
882
|
+
// "`primary`, `@OneToMany()` and `@ManyToManyBackRef()` are rejected" —
|
|
883
|
+
// the same extension-mode restrictions as any table this app does not own.
|
|
884
|
+
let reverse = false;
|
|
885
|
+
for (const d of decs) {
|
|
886
|
+
if (d.name === "OneToMany" || d.name === "ManyToManyBackRef") {
|
|
887
|
+
reverse = true;
|
|
888
|
+
findings.push(finding(ts, info.sf, member, "E126",
|
|
889
|
+
`'${propName}' uses @${d.name}(), which the platform REJECTS on a custom-field class — a ` +
|
|
890
|
+
`reverse relation creates a field on the other entity, and the generated extension table ` +
|
|
891
|
+
`is not this application's to reshape. Declare the relation on the other side.`));
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// A reverse relation is not a column at all: reporting it again as a
|
|
896
|
+
// column with no set would say two things about one mistake.
|
|
897
|
+
if (reverse) continue;
|
|
898
|
+
const colDec = decs.find((d) => d.name === "Column") ??
|
|
899
|
+
decs.find((d) => d.name in RELATION_KIND_BY_DECORATOR);
|
|
900
|
+
if (!colDec) continue;
|
|
901
|
+
const opts = colDec.name === "Column"
|
|
902
|
+
? objectMap(ts, colDec.args[0])
|
|
903
|
+
: objectMap(ts, [...colDec.args].reverse().find((a) => ts.isObjectLiteralExpression(a)));
|
|
904
|
+
|
|
905
|
+
if (opts.get("primary")) {
|
|
906
|
+
findings.push(finding(ts, info.sf, opts.get("primary"), "E126",
|
|
907
|
+
`'${propName}' declares primary, which the platform REJECTS on a custom-field class: the ` +
|
|
908
|
+
`generated table's key is the owner relation, not yours to redefine.`));
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
const nullable = opts.get("nullable");
|
|
912
|
+
const nullableIsFalse = nullable && nullable.kind === ts.SyntaxKind.FalseKeyword;
|
|
913
|
+
if (nullableIsFalse && !opts.get("default")) {
|
|
914
|
+
findings.push(finding(ts, info.sf, nullable, "E127",
|
|
915
|
+
`'${propName}' is nullable: false with no default. On a custom-field class "nullable: false ` +
|
|
916
|
+
`needs a default" — the values row may already exist for records that have no value for this ` +
|
|
917
|
+
`column yet. Give it a default (a SQL expression STRING), or leave it nullable.`));
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// "A field with no set never shows up."
|
|
921
|
+
const inner = objectMap(ts, opts.get("options"));
|
|
922
|
+
const setsNode = inner.get("customFieldSets");
|
|
923
|
+
if (!setsNode) {
|
|
924
|
+
findings.push(finding(ts, info.sf, member, "W621",
|
|
925
|
+
`'${propName}' declares no options.customFieldSets, so no record will ever show it: a custom ` +
|
|
926
|
+
`field "exists in the metadata (and in GET /core/schema/${info.entityName} with an empty ` +
|
|
927
|
+
`setIds) but no record shows it". Declare where it applies — ` +
|
|
928
|
+
`options: { customFieldSets: [{ contextField: '<owner field>', contextValue: '<value>' }] } — ` +
|
|
929
|
+
`or, if it belongs on every record, it is an ordinary column of '${info.className}'.`));
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
if (!ts.isArrayLiteralExpression(setsNode)) {
|
|
933
|
+
findings.push(finding(ts, info.sf, setsNode, "W624",
|
|
934
|
+
`'${propName}' hands customFieldSets over by reference, so where it applies cannot be read ` +
|
|
935
|
+
`here and its contexts went unchecked. Write the array literally.`));
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
for (const entry of setsNode.elements) {
|
|
939
|
+
if (!ts.isObjectLiteralExpression(entry)) continue;
|
|
940
|
+
const set = objectMap(ts, entry);
|
|
941
|
+
const cfNode = set.get("contextField");
|
|
942
|
+
const cvNode = set.get("contextValue");
|
|
943
|
+
if (!cfNode || !cvNode) {
|
|
944
|
+
findings.push(finding(ts, info.sf, entry, "E128",
|
|
945
|
+
`'${propName}' has a customFieldSets entry without ` +
|
|
946
|
+
`${!cfNode ? "contextField" : "contextValue"} — a set binds the owner to ONE context value, ` +
|
|
947
|
+
`and both halves are required.`));
|
|
948
|
+
continue;
|
|
949
|
+
}
|
|
950
|
+
const cfName = stringValue(ts, cfNode);
|
|
951
|
+
// "contextField — Name of the field ON THE OWNER whose value decides the
|
|
952
|
+
// context. It must exist on the owner."
|
|
953
|
+
if (cfName && ownerFields.size > 0 && !ownerFields.has(cfName)) {
|
|
954
|
+
findings.push(finding(ts, info.sf, cfNode, "W622",
|
|
955
|
+
`'${propName}' keys its context on '${cfName}', which '${info.className}' does not declare — ` +
|
|
956
|
+
`contextField must name a field ON THE OWNER. The migration resolves the context inside the ` +
|
|
957
|
+
`write transaction, so an unresolvable one fails the whole start, not just this field.`));
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
760
963
|
// ── rules: tabular parts ──
|
|
761
964
|
/**
|
|
762
965
|
* Doc: "Three things make an entity a tabular part. All three are required,
|
|
@@ -1704,10 +1907,12 @@ function checkExtension(ts, info, findings) {
|
|
|
1704
1907
|
// gap in the tooling — say so here rather than leaving them to guess.
|
|
1705
1908
|
(opt === "options"
|
|
1706
1909
|
? `. If you need an option ENABLED on an entity you do not own — customFields, comments, ` +
|
|
1707
|
-
`trackChangeHistory —
|
|
1910
|
+
`trackChangeHistory — SWITCHING IT ON is an owner action and cannot come from a file: call ` +
|
|
1708
1911
|
`suppa_update_entity_options(entity_name, options_json) once. It is a schema change ` +
|
|
1709
1912
|
`(enabling customFields creates the {Entity}CustomFields side table), so record it in the ` +
|
|
1710
|
-
`plan beside the code that depends on it`
|
|
1913
|
+
`plan beside the code that depends on it. Note what does NOT move out of the file: with ` +
|
|
1914
|
+
`@suppa/sdk 1.38.0+ the custom-field COLUMNS still come from your @CustomFields class — ` +
|
|
1915
|
+
`extension mode applies them, it only ignores the option that switches the feature on`
|
|
1711
1916
|
: "")));
|
|
1712
1917
|
}
|
|
1713
1918
|
|
|
@@ -2776,6 +2981,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
|
|
|
2776
2981
|
if (info.outOfScope) continue;
|
|
2777
2982
|
checkEntity(ts, info, sdk, model, findings);
|
|
2778
2983
|
}
|
|
2984
|
+
checkCustomFieldsClasses(ts, model, findings);
|
|
2779
2985
|
for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
|
|
2780
2986
|
checkRegistration(ts, model, findings, rootDir, parsedByCanonical);
|
|
2781
2987
|
checkTsconfig(ts, rootDir, model, findings);
|