suppa-mcp-2 1.2.4 → 1.3.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.
@@ -15,8 +15,8 @@ import { existsSync, statSync } from "node:fs";
15
15
  import { basename } from "node:path";
16
16
  import { config } from "../config.js";
17
17
  import * as tenants from "../tenants.js";
18
- import { makeRequest, makeRequestRawBytes, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
19
- import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListProblems, } from "../utils.js";
18
+ import { makeRequest, makeRequestRawBytes, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, restoreEntity, copyEntity, validateSelect, DELETED_SCOPES, DEFAULT_DELETED_SCOPE, DEFAULT_INCLUDE_DELETED_RELATIONS, } from "../httpClient.js";
19
+ import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListProblems, normalizeConditionNodes, } from "../utils.js";
20
20
  // Builder field types that accept file uploads.
21
21
  export const FILE_FIELD_TYPES = ["file", "multi-file"];
22
22
  export const RELATION_FIELD_TYPES = [
@@ -27,6 +27,14 @@ export const RELATION_FIELD_TYPES = [
27
27
  ];
28
28
  // Every type the 2.0 builder accepts — used to reject typos client-side with a
29
29
  // clear message instead of an opaque server 400.
30
+ // The scalar list is builder.txt:62 verbatim
31
+ // (docs/superpowers/specs/captures/api-entity-builder-builder.txt:62 — "Scalar
32
+ // types: text, numeric, integer, serial, boolean, timestamp, json, uuid,
33
+ // multi-language, bytea, tsvector, multi-type, icon."); the relation list is
34
+ // builder.txt:63. bytea / tsvector / multi-type were missing here, so this server
35
+ // REFUSED three types the platform accepts and the bundled suppa-entity-code
36
+ // skill documents (skills/suppa-entity-code/references/entities.md:157-159) —
37
+ // MCP and skill disagreed and the agent was told the type did not exist.
30
38
  export const VALID_FIELD_TYPES = [
31
39
  "text",
32
40
  "numeric",
@@ -37,6 +45,9 @@ export const VALID_FIELD_TYPES = [
37
45
  "json",
38
46
  "uuid",
39
47
  "multi-language",
48
+ "bytea", // builder.txt:62
49
+ "tsvector", // builder.txt:62
50
+ "multi-type", // builder.txt:62
40
51
  "icon",
41
52
  "enum",
42
53
  "multi-enum",
@@ -59,9 +70,17 @@ export const RELATION_LIKE_FIELD_TYPES = [
59
70
  // Where `defaultValue` does NOT apply. builder.txt:43 — "defaultValue | string |
60
71
  // false | Default value. Not applicable to relations, enums, or unique fields."
61
72
  // So: every relation-like type above, plus ANY type when unique is set.
62
- // (`notNull` has its own, narrower exclusion — builder.txt:41: "Not applicable to
63
- // many-to-many / multi-enum" — and is still sent for the rest.)
64
73
  export const NO_DEFAULT_VALUE_FIELD_TYPES = RELATION_LIKE_FIELD_TYPES;
74
+ // Where `notNull` does NOT apply — its own, narrower exclusion. builder.txt:41 —
75
+ // "notNull | boolean | false | Field is required. Not applicable to many-to-many
76
+ // / multi-enum." The comment above used to claim this exclusion was honoured
77
+ // while the wire body set `notNull` unconditionally, so a required=true on these
78
+ // two types was sent to the builder and reported back as applied.
79
+ export const NO_NOT_NULL_FIELD_TYPES = ["many-to-many", "multi-enum"];
80
+ /** True when `notNull` is applicable to this field type (builder.txt:41). */
81
+ export function notNullApplies(fieldType) {
82
+ return !NO_NOT_NULL_FIELD_TYPES.includes(fieldType);
83
+ }
65
84
  /**
66
85
  * True when `defaultValue` is applicable to this field — and therefore when
67
86
  * `notNull` on it also demands one. Recorded evidence for that demand, on the
@@ -74,6 +93,261 @@ export function defaultValueApplies(fieldType, unique = false) {
74
93
  return !unique && !RELATION_LIKE_FIELD_TYPES.includes(fieldType);
75
94
  }
76
95
  // ---------------------------------------------------------------------------
96
+ // Field options (the `options` object of a field body)
97
+ // ---------------------------------------------------------------------------
98
+ //
99
+ // builder.txt:60 — "options | object | false | Field options configuration."
100
+ // Its keys are builder.txt:66-73. A field created without them is invisible in
101
+ // table views and unsearchable until a human fixes it in the UI: the free-text
102
+ // search of suppa_search_records only covers fields carrying `searchable`
103
+ // (data.txt:218 — "Only fields with the searchable option participate.").
104
+ /** Boolean members of the Field Options object. */
105
+ export const FIELD_OPTION_BOOLEAN_KEYS = [
106
+ "searchable", // builder.txt:66 — "Available for search."
107
+ "readOnly", // builder.txt:68 — "Field is read-only (UI level)."
108
+ "canGroup", // builder.txt:69 — "Allow grouping by field."
109
+ "canSort", // builder.txt:70 — "Allow sorting by field."
110
+ "showInTable", // builder.txt:71 — "Show field in table view."
111
+ "editFromTable", // builder.txt:72 — "Allow editing from table view."
112
+ "canFilter", // builder.txt:73 — "Allow filtering by field."
113
+ ];
114
+ // builder.txt:67 — "searchPriority | number | false | Search priority, 1–4
115
+ // (higher = stronger weight)." The only non-boolean option.
116
+ export const FIELD_OPTION_SEARCH_PRIORITY = "searchPriority";
117
+ export const FIELD_OPTION_KEYS = [
118
+ ...FIELD_OPTION_BOOLEAN_KEYS,
119
+ FIELD_OPTION_SEARCH_PRIORITY,
120
+ ];
121
+ /**
122
+ * Validate an `options_json` parameter into the builder's Field Options object.
123
+ *
124
+ * Strict on purpose: the builder drops an unknown key without complaint, so a
125
+ * typo ("searchible", "sortable") would be reported as applied and silently do
126
+ * nothing — the same failure mode that made every field this server created come
127
+ * out nullable. Throws with the valid key list instead; returns null when there
128
+ * is nothing to send (so no empty `options: {}` is emitted).
129
+ */
130
+ export function normalizeFieldOptions(raw, param = "options_json") {
131
+ if (raw === null || raw === undefined || raw === "") {
132
+ return null;
133
+ }
134
+ const parsed = parseJsonParam(raw, param, "object");
135
+ const unknownKeys = Object.keys(parsed).filter((k) => !FIELD_OPTION_KEYS.includes(k));
136
+ if (unknownKeys.length > 0) {
137
+ throw new Error(`Parameter '${param}' has unknown option(s): ${unknownKeys.join(", ")}. The builder ` +
138
+ `accepts only ${FIELD_OPTION_KEYS.join(", ")} (builder.txt:66-73) and drops anything ` +
139
+ "else without complaint — which would look like success and change nothing.");
140
+ }
141
+ const out = {};
142
+ for (const [key, value] of Object.entries(parsed)) {
143
+ if (key === FIELD_OPTION_SEARCH_PRIORITY) {
144
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 4) {
145
+ throw new Error(`Parameter '${param}': searchPriority must be an integer 1-4 (builder.txt:67 — ` +
146
+ `"Search priority, 1–4 (higher = stronger weight)"), got ${JSON.stringify(value)}.`);
147
+ }
148
+ }
149
+ else if (typeof value !== "boolean") {
150
+ throw new Error(`Parameter '${param}': '${key}' must be true or false (builder.txt:66-73 type it as ` +
151
+ `boolean), got ${JSON.stringify(value)}.`);
152
+ }
153
+ out[key] = value;
154
+ }
155
+ return Object.keys(out).length > 0 ? out : null;
156
+ }
157
+ // ---------------------------------------------------------------------------
158
+ // Entity options (the `options` object of an entity body)
159
+ // ---------------------------------------------------------------------------
160
+ //
161
+ // builder.txt:74-90 — the platform's 15 per-entity features. Sent on
162
+ // create-entity (builder.txt:113 — "options | object | false | See Entity
163
+ // Options.") and edited on their own through /update-options (builder.txt:267).
164
+ //
165
+ // builder.txt:91-92 (TIP): "Enabling an option creates the side table that backs
166
+ // it. Turning on recurrence, reminders, notificationMutes, timeTracking or pinned
167
+ // also refreshes the cache of the corresponding system entity." A toggle here is
168
+ // therefore a schema change, not a preference.
169
+ /** Options typed `boolean` by builder.txt:76-90. */
170
+ export const ENTITY_OPTION_BOOLEAN_KEYS = [
171
+ "comments", // builder.txt:76 — "Enable comments."
172
+ "reactions", // builder.txt:77 — "Enable reactions."
173
+ "trackChangeHistory", // builder.txt:80 — "Enable change tracking."
174
+ "globalSearch", // builder.txt:82 — "Enable global search."
175
+ "timeTracking", // builder.txt:83 — "Enable time tracking."
176
+ "favorites", // builder.txt:84 — "Enable favorites."
177
+ "pinned", // builder.txt:85 — "Enable pinned instances."
178
+ "approvals", // builder.txt:86 — "Enable approvals."
179
+ "checklists", // builder.txt:87 — "Enable checklists."
180
+ "recurrence", // builder.txt:88 — "Enable recurrence."
181
+ "reminders", // builder.txt:89 — "Enable reminders."
182
+ "notificationMutes", // builder.txt:90 — "Enable notification mutes."
183
+ ];
184
+ /** The two mode options, both `"single" | "multi"`. */
185
+ export const ENTITY_OPTION_MODE_KEYS = [
186
+ "hierarchy", // builder.txt:78 — "Hierarchy mode."
187
+ "folders", // builder.txt:79 — "Folders mode."
188
+ ];
189
+ /** builder.txt:78-79 — the closed value set of hierarchy / folders. */
190
+ export const ENTITY_OPTION_MODES = ["single", "multi"];
191
+ // builder.txt:81 — "browsingHistory | boolean | number | false | Enable browsing
192
+ // history." The one option that takes either.
193
+ export const ENTITY_OPTION_BROWSING_HISTORY = "browsingHistory";
194
+ /** All 15, in the order builder.txt:76-90 lists them. */
195
+ export const ENTITY_OPTION_KEYS = [
196
+ "comments",
197
+ "reactions",
198
+ "hierarchy",
199
+ "folders",
200
+ "trackChangeHistory",
201
+ "browsingHistory",
202
+ "globalSearch",
203
+ "timeTracking",
204
+ "favorites",
205
+ "pinned",
206
+ "approvals",
207
+ "checklists",
208
+ "recurrence",
209
+ "reminders",
210
+ "notificationMutes",
211
+ ];
212
+ /**
213
+ * builder.txt:251-256 — on an entity created by the system (initiator = system)
214
+ * the ONLY option key accepted is globalSearch; everything else is dropped, and a
215
+ * body carrying none of the accepted keys fails with
216
+ * `Cannot update system entity: <name>`.
217
+ */
218
+ export const SYSTEM_ENTITY_OPTION_KEYS = ["globalSearch"];
219
+ /**
220
+ * builder.txt:258-264 — on a system-GENERATED entity (reserved suffixes) enabling
221
+ * any of these fails with `Modifying options of system-generated entity "<name>"
222
+ * is forbidden.` The doc does not list the reserved suffixes, so this server
223
+ * cannot tell which names are system-generated: it warns instead of guessing.
224
+ */
225
+ export const SYSTEM_GENERATED_FORBIDDEN_OPTIONS = [
226
+ "comments", // builder.txt:259
227
+ "timeTracking", // builder.txt:260
228
+ "pinned", // builder.txt:261
229
+ "favorites", // builder.txt:262
230
+ "approvals", // builder.txt:263
231
+ "checklists", // builder.txt:264
232
+ ];
233
+ /** builder.txt:91-92 — what a toggle actually costs, quoted back to the caller. */
234
+ export const ENTITY_OPTION_SIDE_EFFECT_NOTE = "Enabling an option creates the side table that backs it; recurrence, reminders, " +
235
+ "notificationMutes, timeTracking and pinned also refresh the cache of the corresponding " +
236
+ "system entity (builder.txt:91-92). This is a schema change, not a preference.";
237
+ /**
238
+ * Validate an options parameter into the builder's Entity Options object.
239
+ *
240
+ * Strict for the same reason as normalizeFieldOptions: the builder drops an
241
+ * unknown key without complaint, so a typo ("comment", "folder") would be
242
+ * reported as applied and change nothing. Each key is checked against the type
243
+ * builder.txt:76-90 gives it — hierarchy/folders are the "single" | "multi"
244
+ * enums, browsingHistory is boolean-or-number, the other twelve are booleans.
245
+ * Returns null when there is nothing to send (so no empty `options: {}`).
246
+ */
247
+ export function normalizeEntityOptions(raw, param = "options_json") {
248
+ if (raw === null || raw === undefined || raw === "") {
249
+ return null;
250
+ }
251
+ const parsed = parseJsonParam(raw, param, "object");
252
+ const unknownKeys = Object.keys(parsed).filter((k) => !ENTITY_OPTION_KEYS.includes(k));
253
+ if (unknownKeys.length > 0) {
254
+ throw new Error(`Parameter '${param}' has unknown option(s): ${unknownKeys.join(", ")}. The builder ` +
255
+ `accepts only ${ENTITY_OPTION_KEYS.join(", ")} (builder.txt:76-90) and drops anything ` +
256
+ "else without complaint — which would look like success and change nothing.");
257
+ }
258
+ const out = {};
259
+ for (const [key, value] of Object.entries(parsed)) {
260
+ if (ENTITY_OPTION_MODE_KEYS.includes(key)) {
261
+ if (typeof value !== "string" || !ENTITY_OPTION_MODES.includes(value)) {
262
+ throw new Error(`Parameter '${param}': '${key}' must be "single" or "multi" (builder.txt:78-79 types ` +
263
+ `it as '"single" | "multi"', not a boolean), got ${JSON.stringify(value)}.`);
264
+ }
265
+ }
266
+ else if (key === ENTITY_OPTION_BROWSING_HISTORY) {
267
+ const ok = typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
268
+ if (!ok) {
269
+ throw new Error(`Parameter '${param}': 'browsingHistory' must be a boolean or a number ` +
270
+ `(builder.txt:81 — "boolean | number"), got ${JSON.stringify(value)}.`);
271
+ }
272
+ }
273
+ else if (typeof value !== "boolean") {
274
+ throw new Error(`Parameter '${param}': '${key}' must be true or false (builder.txt:76-90 type it as ` +
275
+ `boolean), got ${JSON.stringify(value)}.`);
276
+ }
277
+ out[key] = value;
278
+ }
279
+ return Object.keys(out).length > 0 ? out : null;
280
+ }
281
+ // ---------------------------------------------------------------------------
282
+ // subType matrix
283
+ // ---------------------------------------------------------------------------
284
+ //
285
+ // migrations.txt:211-216 (docs/superpowers/specs/captures/migrations.txt) —
286
+ // "subType is a second, narrower classification on top of type ... it means three
287
+ // unrelated things depending on the base type": Timestamp → 'date' | 'time' |
288
+ // 'timestamp'; Text → 'encrypted'; Enum / MultiEnum → the enum's global name,
289
+ // "Set by the decorator — never by hand". Everything else takes none.
290
+ /** The documented matrix, echoed in refusals so the caller sees the rule itself. */
291
+ export const SUB_TYPE_MATRIX = {
292
+ timestamp: "'date' | 'time' | 'timestamp' — chooses the physical column type; omitted = timestamp (migrations.txt:213)",
293
+ text: "'encrypted' — value stored as an AES-GCM envelope (migrations.txt:214)",
294
+ "enum / multi-enum": "the enum's global name — set by the platform, NEVER by hand (migrations.txt:215, :256)",
295
+ "every other type": "no sub_type is documented (migrations.txt:212-216)",
296
+ };
297
+ /** sub_type values each base type accepts. migrations.txt:213-214. */
298
+ export const SUB_TYPES_BY_FIELD_TYPE = {
299
+ timestamp: ["date", "time", "timestamp"], // migrations.txt:213
300
+ text: ["encrypted"], // migrations.txt:214
301
+ };
302
+ /**
303
+ * Why this (type, sub_type) pair is refused — or null when the matrix allows it.
304
+ *
305
+ * Pure and request-free: the point is to refuse BEFORE anything is sent.
306
+ * 'encrypted' used to be forwarded raw on a numeric field, where the platform
307
+ * answers "Encrypted subtype is only allowed on text fields" (migrations.txt:241).
308
+ */
309
+ export function subTypeProblem(fieldType, subType) {
310
+ if (subType === null || subType === undefined) {
311
+ return null;
312
+ }
313
+ if (typeof subType !== "string") {
314
+ return `Refused: sub_type must be a string, got ${JSON.stringify(subType)}.`;
315
+ }
316
+ const st = subType.trim();
317
+ if (st === "") {
318
+ return null;
319
+ }
320
+ if (fieldType === "enum" || fieldType === "multi-enum") {
321
+ return (`Refused: sub_type is not yours to set on a '${fieldType}' field. There it holds the ` +
322
+ "ENUM'S GLOBAL NAME and the platform fills it in (migrations.txt:215 \"Enum, MultiEnum | " +
323
+ "The global enum name | Identifies which enum the field draws from. Set by the decorator " +
324
+ "— never by hand\"; :256 \"do not pass subType yourself on an enum field\"). Pass enum_name " +
325
+ "instead and leave sub_type unset.");
326
+ }
327
+ const allowed = SUB_TYPES_BY_FIELD_TYPE[fieldType];
328
+ if (!allowed) {
329
+ let extra = "";
330
+ if (st === "encrypted") {
331
+ extra =
332
+ ' The platform\'s own rule: "Encrypted subtype is only allowed on text fields" ' +
333
+ "(migrations.txt:241)";
334
+ extra +=
335
+ fieldType === "multi-type"
336
+ ? ', and "Encrypted subtype is not allowed inside a multi-type field" (migrations.txt:242).'
337
+ : ".";
338
+ }
339
+ return (`Refused: field type '${fieldType}' takes no sub_type. The subType matrix ` +
340
+ `(migrations.txt:212-216) documents exactly two combinations — timestamp → 'date' | ` +
341
+ `'time' | 'timestamp', text → 'encrypted' — plus enum / multi-enum, where the platform ` +
342
+ `sets it itself.${extra}`);
343
+ }
344
+ if (!allowed.includes(st)) {
345
+ return (`Refused: sub_type '${st}' is not valid on a '${fieldType}' field. The subType matrix ` +
346
+ `(migrations.txt:212-216) allows ${allowed.map((v) => `'${v}'`).join(" | ")} there.`);
347
+ }
348
+ return null;
349
+ }
350
+ // ---------------------------------------------------------------------------
77
351
  // Multi-language titles
78
352
  // ---------------------------------------------------------------------------
79
353
  //
@@ -222,16 +496,40 @@ export async function describeEntity(entityName) {
222
496
  const result = await makeRequest("GET", `/api/core/schema/${entityName}`);
223
497
  return jsonResponse(result);
224
498
  }
499
+ /**
500
+ * Normalise a deleted_scope argument. Returns the scope, or an error string for
501
+ * anything the platform would reject — the enum is closed (data.txt:76).
502
+ */
503
+ function _parseDeletedScope(raw) {
504
+ const value = (raw ?? DEFAULT_DELETED_SCOPE).trim().toLowerCase();
505
+ if (!DELETED_SCOPES.includes(value)) {
506
+ return {
507
+ scope: DEFAULT_DELETED_SCOPE,
508
+ error: jsonResponse({
509
+ error: `deleted_scope must be one of ${DELETED_SCOPES.join(", ")} — got '${raw}'. ` +
510
+ "'active' hides soft-deleted rows (the platform default), 'deleted' returns " +
511
+ "ONLY the soft-deleted ones (use it to find a record to restore), 'all' returns both.",
512
+ }),
513
+ };
514
+ }
515
+ return { scope: value };
516
+ }
225
517
  /**
226
518
  * Search records of any entity with filters.
227
519
  * filters_json: JSON array of filter objects [{field, value, comparator}].
228
520
  * fields_json: JSON object specifying which fields to return.
229
521
  * order_by: 'field:direction' (e.g. 'createdAt:desc').
230
522
  * match_any: when True, filters are combined with OR instead of AND.
523
+ * deleted_scope: 'active' | 'deleted' | 'all' (data.txt:76).
524
+ * include_deleted_relations: keep soft-deleted RELATED records (data.txt:75).
231
525
  *
232
526
  * Returns {"records": [...], "returned": N, "has_more": bool, "next_offset": int|null}.
233
527
  */
234
- export async function searchRecords(entityName, filtersJson = "[]", fieldsJson = '{"id": true}', limit = 20, offset = 0, search = "", orderBy = "createdAt:desc", matchAny = false) {
528
+ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson = '{"id": true}', limit = 20, offset = 0, search = "", orderBy = "createdAt:desc", matchAny = false, deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
529
+ const scope = _parseDeletedScope(deletedScope);
530
+ if (scope.error) {
531
+ return scope.error;
532
+ }
235
533
  let filters;
236
534
  let fields;
237
535
  try {
@@ -243,8 +541,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
243
541
  }
244
542
  // Tolerate common near-miss shapes instead of erroring:
245
543
  // a single filter object -> one-element list; a list of field names -> projection.
246
- if (filters !== null && typeof filters === "object" && !Array.isArray(filters)) {
247
- filters = [filters];
544
+ // Nested condition GROUPS are accepted here too — normalizeConditionNodes
545
+ // validates both leaf filters and {"operator": "and"|"or", "filters": [...]}
546
+ // groups (data.txt:33-42), so (a AND b) OR c is one call.
547
+ try {
548
+ filters = normalizeConditionNodes(filters, "filters_json");
549
+ }
550
+ catch (e) {
551
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
248
552
  }
249
553
  if (Array.isArray(fields)) {
250
554
  const proj = {};
@@ -266,17 +570,162 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
266
570
  // Fetch one extra row so the agent learns whether another page exists.
267
571
  // Cap at 500/page: larger responses blow the model's context — page instead.
268
572
  limit = Math.max(1, Math.min(limit, 500));
269
- const rows = await searchEntity(entityName, filters, fields, limit + 1, offset, order, search, matchAny ? "or" : "and");
573
+ const conditions = {
574
+ operator: matchAny ? "or" : "and",
575
+ filters: filters,
576
+ };
577
+ let rows;
578
+ try {
579
+ rows = await searchEntity(entityName, filters, fields, limit + 1, offset, order, search, matchAny ? "or" : "and", scope.scope, includeDeletedRelations);
580
+ }
581
+ catch (e) {
582
+ // A 400 is the platform refusing the payload. Ask select/validate WHY
583
+ // instead of handing the caller back an opaque status line.
584
+ const msg = e instanceof Error ? e.message : String(e);
585
+ if (!/HTTP 400/.test(msg)) {
586
+ throw e;
587
+ }
588
+ const diag = await _selectDiagnostic(entityName, {
589
+ fields: fields,
590
+ conditions,
591
+ orderBy: order,
592
+ });
593
+ if (!diag) {
594
+ throw e;
595
+ }
596
+ return jsonResponse({ error: msg, ...diag, records: [], returned: 0 });
597
+ }
270
598
  const hasMore = rows.length > limit;
271
- return jsonResponse({
599
+ const out = {
272
600
  records: rows.slice(0, limit),
273
601
  returned: Math.min(rows.length, limit),
274
602
  has_more: hasMore,
275
603
  next_offset: hasMore ? offset + limit : null,
604
+ deleted_scope: scope.scope,
605
+ };
606
+ // Zero rows is ambiguous: no matches, or a typo'd field that the platform
607
+ // resolved to nothing. ONE extra call — only on the empty result, never after
608
+ // a successful non-empty read — turns that into a real answer.
609
+ if (rows.length === 0) {
610
+ const diag = await _selectDiagnostic(entityName, {
611
+ fields: fields,
612
+ conditions,
613
+ orderBy: order,
614
+ });
615
+ if (diag) {
616
+ Object.assign(out, diag);
617
+ }
618
+ }
619
+ return jsonResponse(out);
620
+ }
621
+ /**
622
+ * Ask POST /core/data/:entityName/select/validate why a select produced nothing
623
+ * (data.txt:126-129 — "Use it to tell a malformed query from an empty result").
624
+ *
625
+ * Returns null when the payload validates (nothing useful to add) or when the
626
+ * check itself fails — a diagnostic must never turn a legitimate empty result
627
+ * into an error.
628
+ */
629
+ async function _selectDiagnostic(entityName, payload) {
630
+ let result;
631
+ try {
632
+ result = await validateSelect(entityName, payload);
633
+ }
634
+ catch {
635
+ return null;
636
+ }
637
+ if (!result || result.valid !== false) {
638
+ return null;
639
+ }
640
+ const invalid = Array.isArray(result.invalidFields) ? result.invalidFields : [];
641
+ // data.txt:145-148 — path / location / kind / reason.
642
+ const reasons = invalid
643
+ .map((f) => f?.reason || (f?.path ? `Unresolved reference '${f.path}'.` : ""))
644
+ .filter(Boolean);
645
+ return {
646
+ validation: {
647
+ valid: false,
648
+ invalidFields: invalid,
649
+ message: reasons.join(" ") ||
650
+ `The platform rejected this query against '${entityName}'.`,
651
+ },
652
+ hint: "This result is EMPTY because the query is malformed, not because nothing " +
653
+ "matched: the references above do not resolve on this entity. Check the " +
654
+ "names with suppa_describe_entity and re-run.",
655
+ };
656
+ }
657
+ /**
658
+ * Standalone query check: validate a select payload WITHOUT running it
659
+ * (POST /core/data/:entityName/select/validate, data.txt:126).
660
+ *
661
+ * Use it before an expensive read, or to explain an empty one: a typo'd field
662
+ * name silently returns no records, while this returns
663
+ * {"valid": false, "invalidFields": [{path, location, kind, reason}]}.
664
+ */
665
+ export async function validateSelectQuery(entityName, filtersJson = "[]", fieldsJson = '{"id": true}', orderBy = "", matchAny = false) {
666
+ let filters;
667
+ let fields;
668
+ try {
669
+ fields = parseJsonParam(fieldsJson, "fields_json");
670
+ filters = normalizeConditionNodes(parseJsonParam(filtersJson, "filters_json"), "filters_json");
671
+ }
672
+ catch (e) {
673
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
674
+ }
675
+ if (Array.isArray(fields)) {
676
+ const proj = {};
677
+ for (const f of fields) {
678
+ proj[String(f)] = true;
679
+ }
680
+ fields = proj;
681
+ }
682
+ let order = null;
683
+ if (orderBy.trim()) {
684
+ const idx = orderBy.indexOf(":");
685
+ const field = (idx === -1 ? orderBy : orderBy.slice(0, idx)).trim();
686
+ const direction = (idx === -1 ? "desc" : orderBy.slice(idx + 1)).trim().toLowerCase() || "desc";
687
+ order = [{ field, order: direction }];
688
+ }
689
+ let result;
690
+ try {
691
+ result = await validateSelect(entityName, {
692
+ fields: fields,
693
+ conditions: { operator: matchAny ? "or" : "and", filters },
694
+ orderBy: order,
695
+ });
696
+ }
697
+ catch (e) {
698
+ return jsonResponse({
699
+ error: e instanceof Error ? e.message : String(e),
700
+ entity: entityName,
701
+ });
702
+ }
703
+ const invalid = Array.isArray(result?.invalidFields) ? result.invalidFields : [];
704
+ const valid = result?.valid !== false;
705
+ return jsonResponse({
706
+ entity: entityName,
707
+ valid, // data.txt:143
708
+ invalidFields: invalid, // data.txt:144-148
709
+ message: valid
710
+ ? "Every referenced field, comparator and operator resolves on this entity — " +
711
+ "an empty result from this query means nothing matched."
712
+ : invalid
713
+ .map((f) => f?.reason || `Unresolved reference '${f?.path}'.`)
714
+ .filter(Boolean)
715
+ .join(" ") || "The platform rejected this payload.",
276
716
  });
277
717
  }
278
- /** Get a single record of any entity by its numeric id. */
279
- export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}') {
718
+ /**
719
+ * Get a single record of any entity by its numeric id.
720
+ *
721
+ * deleted_scope='deleted' (or 'all') reads a soft-deleted record — the only way
722
+ * to inspect one before restoring it with restoreRecord.
723
+ */
724
+ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}', deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
725
+ const scope = _parseDeletedScope(deletedScope);
726
+ if (scope.error) {
727
+ return scope.error;
728
+ }
280
729
  let fields;
281
730
  try {
282
731
  fields = parseJsonParam(fieldsJson, "fields_json", "object");
@@ -284,10 +733,14 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
284
733
  catch (e) {
285
734
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
286
735
  }
287
- const result = await selectEntity(entityName, [makeFilter("id", recordId)], fields);
736
+ const result = await selectEntity(entityName, [makeFilter("id", recordId)], fields, scope.scope, includeDeletedRelations);
288
737
  if (result === null) {
289
738
  return jsonResponse({
290
- error: `No record ${recordId} in '${entityName}' (wrong id, deleted, or no access).`,
739
+ error: `No record ${recordId} in '${entityName}' (wrong id, deleted, or no access).` +
740
+ (scope.scope === "active"
741
+ ? " If it was deleted, re-read it with deleted_scope='deleted' — a soft delete " +
742
+ "is reversible with suppa_restore_record."
743
+ : ""),
291
744
  });
292
745
  }
293
746
  return jsonResponse(result);
@@ -300,8 +753,24 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
300
753
  * and the entity's titleFieldName resolves to a real field. Pass
301
754
  * auto_title_field=False when the caller adds its own fields (e.g. migration),
302
755
  * to avoid a type clash with a field of the same name added later.
756
+ *
757
+ * `options` carries the Entity Options object (builder.txt:113 — "options |
758
+ * object | false | See Entity Options."). Setting them at creation is the cheap
759
+ * moment: each one enabled later still creates its side table (builder.txt:91-92).
303
760
  */
304
- export async function createEntity(name, title, titleFieldName = "title", autoTitleField = true, titleFieldType = "multi-language") {
761
+ export async function createEntity(name, title, titleFieldName = "title", autoTitleField = true, titleFieldType = "multi-language", options) {
762
+ let entityOptions;
763
+ try {
764
+ entityOptions = normalizeEntityOptions(options, "options_json");
765
+ }
766
+ catch (e) {
767
+ // Refused BEFORE the request: a bad options object must not create the
768
+ // entity with the rest of the body silently applied.
769
+ return jsonResponse({
770
+ error: e instanceof Error ? e.message : String(e),
771
+ valid_option_keys: [...ENTITY_OPTION_KEYS],
772
+ });
773
+ }
305
774
  const titleObj = await _expandTitle(title, name);
306
775
  const body = {
307
776
  name,
@@ -309,6 +778,9 @@ export async function createEntity(name, title, titleFieldName = "title", autoTi
309
778
  titleFieldName,
310
779
  fields: [],
311
780
  };
781
+ if (entityOptions) {
782
+ body.options = entityOptions; // builder.txt:113
783
+ }
312
784
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
313
785
  let titleFieldResult = null;
314
786
  let representative = null;
@@ -548,6 +1020,105 @@ export async function setTitleField(entityName, fieldName) {
548
1020
  note,
549
1021
  });
550
1022
  }
1023
+ /**
1024
+ * Edit ONLY an entity's options: POST /api/core/builder/{entity}/update-options
1025
+ * (builder.txt:267 — "A narrower alternative to Edit Entity that touches only
1026
+ * options. The same Restrictions apply."). The body IS the Entity Options object
1027
+ * (builder.txt:275 — "Same shape as Entity Options."), not `{options: {...}}`.
1028
+ *
1029
+ * The Restrictions it points at (builder.txt:250-264) are enforced here, before
1030
+ * the request, as far as they are checkable:
1031
+ * - an entity created by the system (initiator = "system") accepts only
1032
+ * options.globalSearch; everything else is dropped and a body with none of the
1033
+ * accepted keys fails with "Cannot update system entity: <name>" (:251-256).
1034
+ * The live entity metadata is read once to check this; a failed read SKIPS the
1035
+ * check rather than blocking a legitimate edit (same rule as updateField).
1036
+ * - a system-GENERATED entity (reserved suffixes) refuses comments, timeTracking,
1037
+ * pinned, favorites, approvals, checklists (:258-264). The doc never lists the
1038
+ * reserved suffixes, so which names those are is unknowable client-side: the
1039
+ * result carries the warning instead of a guess that would block real entities.
1040
+ *
1041
+ * The response is "the applied entity options — which may be a subset of the
1042
+ * request when the entity is a system one" (:282), so what came back is compared
1043
+ * against what was sent and the difference is reported.
1044
+ */
1045
+ export async function updateEntityOptions(entityName, options) {
1046
+ let body;
1047
+ try {
1048
+ body = normalizeEntityOptions(options, "options_json");
1049
+ }
1050
+ catch (e) {
1051
+ return jsonResponse({
1052
+ error: e instanceof Error ? e.message : String(e),
1053
+ valid_option_keys: [...ENTITY_OPTION_KEYS],
1054
+ });
1055
+ }
1056
+ if (!body) {
1057
+ return jsonResponse({
1058
+ error: `Refused: no options to apply to '${entityName}' — no request was sent. Pass an ` +
1059
+ `options object with at least one of: ${ENTITY_OPTION_KEYS.join(", ")} ` +
1060
+ "(builder.txt:76-90).",
1061
+ });
1062
+ }
1063
+ // --- Restriction: a system entity accepts options.globalSearch only. ------
1064
+ let meta = null;
1065
+ try {
1066
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
1067
+ if (isPlainObject(schema)) {
1068
+ meta = schema;
1069
+ }
1070
+ }
1071
+ catch {
1072
+ // Can't verify → proceed rather than block on a transient read.
1073
+ }
1074
+ if (meta && (meta.initiator === "system" || meta.system === true)) {
1075
+ const rejected = Object.keys(body).filter((k) => !SYSTEM_ENTITY_OPTION_KEYS.includes(k));
1076
+ if (rejected.length > 0) {
1077
+ return jsonResponse({
1078
+ error: `Refused: '${entityName}' is a SYSTEM entity (initiator="system"). On one of those the ` +
1079
+ "builder accepts only representativeFieldId, representativeTemplate, title, " +
1080
+ "importKeyFields and options.globalSearch — anything else is DROPPED without " +
1081
+ `complaint, and a body carrying none of them fails with "Cannot update system entity: ` +
1082
+ `${entityName}" (builder.txt:251-256). Nothing was sent, so nothing was reported as ` +
1083
+ "applied that the platform would have thrown away.",
1084
+ rejected_keys: rejected.map((k) => `options.${k}`),
1085
+ accepted_on_system_entities: SYSTEM_ENTITY_OPTION_KEYS.map((k) => `options.${k}`),
1086
+ });
1087
+ }
1088
+ }
1089
+ const result = await makeRequest("POST", `/api/core/builder/${entityName}/update-options`, // builder.txt:267
1090
+ body);
1091
+ const out = {
1092
+ entity: entityName,
1093
+ sent: body,
1094
+ applied: result,
1095
+ note: ENTITY_OPTION_SIDE_EFFECT_NOTE,
1096
+ };
1097
+ // builder.txt:282 — the response "may be a subset of the request when the
1098
+ // entity is a system one". Say so instead of implying everything landed.
1099
+ if (isPlainObject(result)) {
1100
+ const applied = result;
1101
+ const notApplied = Object.keys(body).filter((k) => !Object.prototype.hasOwnProperty.call(applied, k));
1102
+ if (notApplied.length > 0) {
1103
+ out.not_applied = notApplied;
1104
+ out.not_applied_note =
1105
+ "The platform returns the APPLIED options and may drop keys it does not accept on this " +
1106
+ `entity (builder.txt:282). These were sent but are missing from the response: ` +
1107
+ `${notApplied.join(", ")}. Read the entity back with suppa_describe_entity before ` +
1108
+ "assuming they took effect.";
1109
+ }
1110
+ }
1111
+ const forbiddenEnabled = Object.keys(body).filter((k) => body[k] !== false &&
1112
+ SYSTEM_GENERATED_FORBIDDEN_OPTIONS.includes(k));
1113
+ if (forbiddenEnabled.length > 0) {
1114
+ out.system_generated_warning =
1115
+ `If '${entityName}' is a system-GENERATED entity (reserved suffix), enabling ` +
1116
+ `${forbiddenEnabled.join(", ")} fails with 'Modifying options of system-generated entity ` +
1117
+ `"${entityName}" is forbidden.' (builder.txt:258-264). The doc does not list the reserved ` +
1118
+ "suffixes, so this cannot be checked before the call.";
1119
+ }
1120
+ return jsonResponse(out);
1121
+ }
551
1122
  /**
552
1123
  * Pre-flight a relation field against the LIVE schema so we never create a
553
1124
  * broken or duplicate relation — either of which corrupts the entity:
@@ -624,8 +1195,9 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
624
1195
  * Add a field to an existing entity.
625
1196
  *
626
1197
  * field_type: a real Suppa 2.0 type — text, numeric, integer, serial, boolean,
627
- * timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file,
628
- * many-to-one, many-to-many, many-to-many-backref.
1198
+ * timestamp, json, uuid, multi-language, bytea, tsvector, multi-type, icon, enum,
1199
+ * multi-enum, file, multi-file, many-to-one, many-to-many, many-to-many-backref
1200
+ * (builder.txt:62-63).
629
1201
  * There is NO date/datetime/richtext/email/url/phone/string type:
630
1202
  * - date-only → field_type='timestamp' with sub_type='date'
631
1203
  * - localized → field_type='multi-language'
@@ -643,9 +1215,17 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
643
1215
  * enum and multi-enum, file and multi-file, and any unique field. The call is
644
1216
  * refused before any request if an applicable default is missing; no default is
645
1217
  * ever invented.
1218
+ * options: the builder's Field Options object (builder.txt:60, keys :66-73) —
1219
+ * searchable / searchPriority / readOnly / canGroup / canSort / showInTable /
1220
+ * editFromTable / canFilter. Omitting it leaves the field out of table views and
1221
+ * out of free-text search (data.txt:218).
1222
+ * sub_type is checked against the documented matrix (migrations.txt:212-216)
1223
+ * before the request: timestamp takes 'date' | 'time' | 'timestamp', text takes
1224
+ * 'encrypted', enum/multi-enum have it set by the platform, and no other type
1225
+ * takes one.
646
1226
  */
647
1227
  export async function addField(entityName, fieldName, fieldType, title, opts = {}) {
648
- const { required = false, defaultValue = null, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, } = opts;
1228
+ const { required = false, defaultValue = null, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, options = null, } = opts;
649
1229
  // The platform has no relation type literally called "relation"; a foreign
650
1230
  // key is "many-to-one" with the target entity in `relationTarget`.
651
1231
  let resolvedType = fieldType === "relation" ? "many-to-one" : fieldType;
@@ -693,6 +1273,24 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
693
1273
  "with suppa_add_enum_values.",
694
1274
  });
695
1275
  }
1276
+ // sub_type pre-flight: refuse a combination the matrix does not document,
1277
+ // BEFORE any request. 'encrypted' on a numeric field used to be forwarded raw.
1278
+ const subProblem = subTypeProblem(resolvedType, subType);
1279
+ if (subProblem) {
1280
+ return jsonResponse({ error: subProblem, sub_type_matrix: SUB_TYPE_MATRIX });
1281
+ }
1282
+ // Field options (builder.txt:60 / :66-73) — validated before anything is sent;
1283
+ // an unknown key here would be dropped by the builder and reported as applied.
1284
+ let fieldOptions;
1285
+ try {
1286
+ fieldOptions = normalizeFieldOptions(options, "options_json");
1287
+ }
1288
+ catch (e) {
1289
+ return jsonResponse({
1290
+ error: e instanceof Error ? e.message : String(e),
1291
+ valid_option_keys: [...FIELD_OPTION_KEYS],
1292
+ });
1293
+ }
696
1294
  // NOT NULL needs a default — but ONLY where a default is applicable at all.
697
1295
  // builder.txt:43 (docs/superpowers/specs/captures/api-entity-builder-builder.txt)
698
1296
  // rules defaultValue out for relations, enums and unique fields; on everything
@@ -746,9 +1344,30 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
746
1344
  name: fieldName,
747
1345
  type: resolvedType,
748
1346
  title: await _expandTitle(title, fieldName),
749
- notNull: required,
750
- unique,
751
1347
  };
1348
+ // Applicability is per the builder's own table, and a constraint that does not
1349
+ // apply is DROPPED by the builder without complaint — so sending it would be
1350
+ // reported back to the agent as applied while nothing changed. Each of these
1351
+ // is instead withheld and named in `not_applicable`, so the caller learns the
1352
+ // constraint is not in force.
1353
+ const notApplicable = [];
1354
+ if (notNullApplies(resolvedType)) {
1355
+ fieldDef.notNull = required;
1356
+ }
1357
+ else if (required) {
1358
+ notApplicable.push(`notNull was NOT set: builder.txt:41 — "Not applicable to many-to-many / multi-enum" ` +
1359
+ `(this field is '${resolvedType}'). The field was created WITHOUT the required ` +
1360
+ "constraint; enforce it in application logic if you need it.");
1361
+ }
1362
+ // builder.txt:42 — "unique | boolean | false | Field must be unique. Not
1363
+ // applicable to relations and enums."
1364
+ if (!RELATION_LIKE_FIELD_TYPES.includes(resolvedType)) {
1365
+ fieldDef.unique = unique;
1366
+ }
1367
+ else if (unique) {
1368
+ notApplicable.push(`unique was NOT set: builder.txt:42 — "Not applicable to relations and enums" ` +
1369
+ `(this field is '${resolvedType}'). The field was created WITHOUT the unique constraint.`);
1370
+ }
752
1371
  // builder.txt:43 — "Not applicable to relations, enums, or unique fields":
753
1372
  // sending it there is at best ignored, so it is never emitted.
754
1373
  if (defaultText.trim() !== "" && typeNeedsDefault) {
@@ -782,13 +1401,234 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
782
1401
  if (enumName) {
783
1402
  fieldDef.enumName = enumName;
784
1403
  }
1404
+ // builder.txt:60 — "options | object | false | Field options configuration."
1405
+ // (example body: builder.txt:127-132).
1406
+ if (fieldOptions) {
1407
+ fieldDef.options = fieldOptions;
1408
+ }
785
1409
  // Correct endpoint is /builder/{Entity}/add-fields and the body is the bare
786
1410
  // array of field defs (the old /builder/add-fields with an {entityName,fields}
787
1411
  // wrapper 404s).
788
1412
  const result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, [
789
1413
  fieldDef,
790
1414
  ]);
791
- return jsonResponse(result);
1415
+ // Plain result when everything asked for was applied — the shape callers and
1416
+ // tests already read. The wrapper appears only when something was withheld,
1417
+ // because that is the case a bare success would misreport.
1418
+ return notApplicable.length > 0
1419
+ ? jsonResponse({ result, not_applicable: notApplicable })
1420
+ : jsonResponse(result);
1421
+ }
1422
+ // builder.txt:391-398 — on a field created by the system (initiator = system)
1423
+ // these are the only accepted keys. Note searchPriority is NOT among them.
1424
+ const _SYSTEM_FIELD_TOP_KEYS = ["title", "options"];
1425
+ const _SYSTEM_FIELD_OPTION_KEYS = [
1426
+ "canGroup", // builder.txt:392
1427
+ "canSort", // builder.txt:393
1428
+ "showInTable", // builder.txt:394
1429
+ "editFromTable", // builder.txt:395
1430
+ "canFilter", // builder.txt:396
1431
+ "readOnly", // builder.txt:397
1432
+ "searchable", // builder.txt:398
1433
+ ];
1434
+ /**
1435
+ * Edit an existing field: POST /api/core/builder/{entity}/{field}/update-field
1436
+ * (builder.txt:344). Every body key is optional — only what changes is sent.
1437
+ *
1438
+ * This replaces the old "field edits are UI-only" policy of this server, which
1439
+ * predated the endpoint. What the endpoint itself refuses is enforced HERE,
1440
+ * before the request (builder.txt:388-398, migrations.txt:257-263):
1441
+ * - `type` is never changeable — "Field type cannot be changed." (:389). No
1442
+ * type key is ever sent, and a caller asking for one is told why.
1443
+ * - `subType` is not changeable either — "Field subType cannot be changed."
1444
+ * (:390) — EXCEPT toggling 'encrypted' on or off (migrations.txt:261). A
1445
+ * date↔timestamp change is a physical column-type change under existing data:
1446
+ * add a new field instead.
1447
+ * - 'encrypted' only on a text field (migrations.txt:241), and never together
1448
+ * with searchable/canFilter/canSort/canGroup, which encryption forces off
1449
+ * (migrations.txt:245).
1450
+ * - a system field (initiator = "system") accepts only title + seven options
1451
+ * keys (:391-398).
1452
+ * The field's live metadata is read once to check those; a failed read SKIPS the
1453
+ * checks rather than blocking a legitimate edit (same rule as _relationPreflight).
1454
+ */
1455
+ export async function updateField(entityName, fieldName, opts = {}) {
1456
+ // --- Restriction: type is never changeable (builder.txt:389). -------------
1457
+ if (opts.type !== undefined && opts.type !== null && String(opts.type).trim() !== "") {
1458
+ return jsonResponse({
1459
+ error: 'Refused: "Field type cannot be changed." (builder.txt:389). The builder rejects a ' +
1460
+ `type change on an existing field, so '${fieldName}' keeps the type it was created ` +
1461
+ "with. To store a different type, add a NEW field with suppa_add_field and move the " +
1462
+ "data across; the old column would otherwise have to be rewritten under existing rows.",
1463
+ });
1464
+ }
1465
+ // --- Restriction: subType only toggles 'encrypted' (builder.txt:390). -----
1466
+ const wantsEncryptToggle = opts.encrypt !== undefined && opts.encrypt !== null;
1467
+ const wantsRawSubType = Object.prototype.hasOwnProperty.call(opts, "subType");
1468
+ let subTypeValue;
1469
+ if (wantsEncryptToggle) {
1470
+ subTypeValue = opts.encrypt ? "encrypted" : null;
1471
+ }
1472
+ if (wantsRawSubType) {
1473
+ const raw = opts.subType === undefined || opts.subType === null ? null : String(opts.subType).trim();
1474
+ const normalized = raw === "" ? null : raw;
1475
+ if (wantsEncryptToggle && normalized !== subTypeValue) {
1476
+ return jsonResponse({
1477
+ error: `Refused: encrypt=${opts.encrypt} and sub_type=${JSON.stringify(opts.subType)} ask for ` +
1478
+ "different subtypes. Pass one of them.",
1479
+ });
1480
+ }
1481
+ subTypeValue = normalized;
1482
+ }
1483
+ const changesSubType = wantsEncryptToggle || wantsRawSubType;
1484
+ if (changesSubType && subTypeValue !== null && subTypeValue !== "encrypted") {
1485
+ return jsonResponse({
1486
+ error: `Refused: "Field subType cannot be changed." (builder.txt:390; migrations.txt:258-259). ` +
1487
+ "The one permitted transition is the encryption toggle — setting 'encrypted' or clearing " +
1488
+ `it (migrations.txt:261) — not '${subTypeValue}'. A date/time choice is fixed at creation: ` +
1489
+ "the physical column type would have to change under existing data, so add a new field " +
1490
+ "with suppa_add_field instead of converting this one.",
1491
+ sub_type_matrix: SUB_TYPE_MATRIX,
1492
+ });
1493
+ }
1494
+ // --- Field options (builder.txt:364 — same shape as Field Options). -------
1495
+ let fieldOptions;
1496
+ try {
1497
+ fieldOptions = normalizeFieldOptions(opts.options, "options_json");
1498
+ }
1499
+ catch (e) {
1500
+ return jsonResponse({
1501
+ error: e instanceof Error ? e.message : String(e),
1502
+ valid_option_keys: [...FIELD_OPTION_KEYS],
1503
+ });
1504
+ }
1505
+ // Encryption forces the read-the-plaintext capabilities off whatever was
1506
+ // declared (migrations.txt:245), so asking for both in one call would report an
1507
+ // option the platform immediately discards.
1508
+ if (subTypeValue === "encrypted" && fieldOptions) {
1509
+ const clash = ["searchable", "canFilter", "canSort", "canGroup"].filter((k) => fieldOptions[k] === true);
1510
+ if (clash.length > 0) {
1511
+ return jsonResponse({
1512
+ error: `Refused: encrypting '${fieldName}' turns ${clash.join(", ")} off by itself — ` +
1513
+ '"the searchable, canFilter, canSort and canGroup options become false" ' +
1514
+ "(migrations.txt:245), because an encrypted column cannot be read as plaintext. " +
1515
+ "Asking for both in one call would report options the platform discards. Keep the " +
1516
+ "searchable part in a separate plaintext field (migrations.txt:249).",
1517
+ });
1518
+ }
1519
+ }
1520
+ // --- Build the body. Keys and their doc lines: builder.txt:352-364. -------
1521
+ const body = {};
1522
+ if (opts.newName !== undefined && opts.newName !== null && String(opts.newName).trim() !== "") {
1523
+ body.name = String(opts.newName).trim(); // builder.txt:353
1524
+ }
1525
+ if (changesSubType) {
1526
+ body.subType = subTypeValue; // builder.txt:355 (explicit null clears it — migrations.txt:263)
1527
+ }
1528
+ if (opts.required !== undefined && opts.required !== null) {
1529
+ body.notNull = opts.required; // builder.txt:356
1530
+ }
1531
+ if (opts.unique !== undefined && opts.unique !== null) {
1532
+ body.unique = opts.unique; // builder.txt:357
1533
+ }
1534
+ if (opts.defaultValue !== undefined && opts.defaultValue !== null) {
1535
+ body.defaultValue = String(opts.defaultValue); // builder.txt:358
1536
+ }
1537
+ if (opts.relationEntity !== undefined && opts.relationEntity !== null && String(opts.relationEntity).trim() !== "") {
1538
+ body.relationTarget = String(opts.relationEntity).trim(); // builder.txt:359
1539
+ }
1540
+ if (opts.backReference !== undefined && opts.backReference !== null && String(opts.backReference).trim() !== "") {
1541
+ body.backReference = String(opts.backReference).trim(); // builder.txt:360
1542
+ }
1543
+ if (opts.isPrimary !== undefined && opts.isPrimary !== null) {
1544
+ body.isPrimary = opts.isPrimary; // builder.txt:361
1545
+ }
1546
+ if (opts.isArray !== undefined && opts.isArray !== null) {
1547
+ body.isArray = opts.isArray; // builder.txt:362
1548
+ }
1549
+ if (fieldOptions) {
1550
+ body.options = fieldOptions; // builder.txt:364
1551
+ }
1552
+ const wantsTitle = opts.title !== undefined && opts.title !== null && (isPlainObject(opts.title) || String(opts.title).trim() !== "");
1553
+ if (Object.keys(body).length === 0 && !wantsTitle) {
1554
+ return jsonResponse({
1555
+ error: `Refused: nothing to update on '${entityName}.${fieldName}' — no request was sent. Pass ` +
1556
+ "at least one change: new_name, title, required, unique, default_value, relation_entity, " +
1557
+ "back_reference, is_primary, is_array, encrypt, or options_json. (type is never " +
1558
+ "changeable — builder.txt:389.)",
1559
+ });
1560
+ }
1561
+ // --- Live metadata, for the checks that need to know the field. -----------
1562
+ let meta = null;
1563
+ let metaRead = false;
1564
+ try {
1565
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
1566
+ const fields = _extractFields(schema);
1567
+ if (fields.length > 0) {
1568
+ metaRead = true;
1569
+ meta = fields.find((f) => f.name === fieldName) ?? null;
1570
+ }
1571
+ }
1572
+ catch {
1573
+ // Can't verify → proceed rather than block on a transient read.
1574
+ }
1575
+ if (metaRead && !meta) {
1576
+ return jsonResponse({
1577
+ error: `Refused: field '${fieldName}' does not exist on '${entityName}' — nothing was sent. ` +
1578
+ "Check the name with suppa_describe_entity (field names are case-sensitive); if you " +
1579
+ "just created it, retry in a moment — the schema read is eventually consistent.",
1580
+ });
1581
+ }
1582
+ if (subTypeValue === "encrypted" && meta) {
1583
+ const liveType = String(meta.type ?? "");
1584
+ if (liveType !== "text") {
1585
+ return jsonResponse({
1586
+ error: `Refused: "Encrypted subtype is only allowed on text fields" (migrations.txt:241) — ` +
1587
+ `'${fieldName}' is '${liveType}'.` +
1588
+ (liveType === "multi-type"
1589
+ ? ' Also: "Encrypted subtype is not allowed inside a multi-type field" (migrations.txt:242).'
1590
+ : ""),
1591
+ });
1592
+ }
1593
+ }
1594
+ if (wantsTitle) {
1595
+ body.title = await _expandTitle(opts.title, String(body.name ?? fieldName)); // builder.txt:363
1596
+ }
1597
+ // System fields accept a much narrower body (builder.txt:391-398).
1598
+ if (meta && (meta.initiator === "system" || meta.system === true)) {
1599
+ const badTop = Object.keys(body).filter((k) => !_SYSTEM_FIELD_TOP_KEYS.includes(k));
1600
+ const badOptions = Object.keys(fieldOptions ?? {}).filter((k) => !_SYSTEM_FIELD_OPTION_KEYS.includes(k));
1601
+ if (badTop.length > 0 || badOptions.length > 0) {
1602
+ return jsonResponse({
1603
+ error: `Refused: '${fieldName}' is a SYSTEM field (initiator="system"). The builder accepts ` +
1604
+ "only title and options.{canGroup, canSort, showInTable, editFromTable, canFilter, " +
1605
+ "readOnly, searchable} on one (builder.txt:391-398) — note searchPriority is not in " +
1606
+ `that list — and a body carrying none of them fails with "Cannot update system field: ` +
1607
+ `${fieldName}". Nothing was sent.`,
1608
+ rejected_keys: [...badTop, ...badOptions.map((k) => `options.${k}`)],
1609
+ accepted_on_system_fields: [
1610
+ "title",
1611
+ ..._SYSTEM_FIELD_OPTION_KEYS.map((k) => `options.${k}`),
1612
+ ],
1613
+ });
1614
+ }
1615
+ }
1616
+ const result = await makeRequest("POST", `/api/core/builder/${entityName}/${fieldName}/update-field`, body);
1617
+ const out = {
1618
+ entity: entityName,
1619
+ field: fieldName,
1620
+ sent: body,
1621
+ result,
1622
+ };
1623
+ if (subTypeValue === "encrypted") {
1624
+ // migrations.txt:244-247 — what the platform does to the field and its rows.
1625
+ out.encryption_note =
1626
+ "Encrypting this field forces unique=false and searchable/canFilter/canSort/canGroup to " +
1627
+ "false, and clears maxLength/minLength/mask (migrations.txt:244-246). The rows already in " +
1628
+ "the table are encrypted in place; a row that fails to decrypt on the way back aborts the " +
1629
+ "backfill rather than overwriting ciphertext (migrations.txt:247).";
1630
+ }
1631
+ return jsonResponse(out);
792
1632
  }
793
1633
  /**
794
1634
  * Add values to an enum (lookup table). values: comma-separated list of values to add.
@@ -839,10 +1679,21 @@ export async function listFieldTypes() {
839
1679
  },
840
1680
  { type: "serial", description: "Auto-incrementing integer" },
841
1681
  { type: "boolean", description: "True/false" },
842
- { type: "timestamp", description: "Date+time; for date-only set sub_type='date'" },
1682
+ {
1683
+ type: "timestamp",
1684
+ description: "Date+time; sub_type='date' for date-only, 'time' for time-only (migrations.txt:213)",
1685
+ },
843
1686
  { type: "multi-language", description: "Localized text object ({en, uk, ...})" },
844
1687
  { type: "json", description: "JSON object/array" },
845
1688
  { type: "uuid", description: "UUID value" },
1689
+ // builder.txt:62 — scalar types this server used to refuse client-side.
1690
+ { type: "bytea", description: "Raw binary (builder.txt:62); prefer 'file' for attachments" },
1691
+ { type: "tsvector", description: "Full-text search vector column (builder.txt:62)" },
1692
+ {
1693
+ type: "multi-type",
1694
+ description: "Composite field built from sub-fields (builder.txt:62). This tool creates the parent " +
1695
+ "field only — its subFields / multiTypeName wiring (builder.txt:58-59) is not exposed here.",
1696
+ },
846
1697
  { type: "icon", description: "Icon reference" },
847
1698
  { type: "enum", description: "Single lookup value (requires enum_name)" },
848
1699
  { type: "multi-enum", description: "Multiple lookup values" },
@@ -981,6 +1832,15 @@ async function _resolveEntity(name) {
981
1832
  * (possibly case-corrected) entity name and an error string when refused.
982
1833
  */
983
1834
  async function _validateRecordWrite(entityName, fields) {
1835
+ return _validateRecordWrites(entityName, [fields]);
1836
+ }
1837
+ /**
1838
+ * The batch form of `_validateRecordWrite`: validates EVERY record in one
1839
+ * insert against a SINGLE schema read, so a batch costs the same one GET a
1840
+ * single record does. With one record the refusals are byte-identical to the
1841
+ * single-record path; with several, each problem carries its record index.
1842
+ */
1843
+ async function _validateRecordWrites(entityName, records) {
984
1844
  const ent = await _resolveEntity(entityName);
985
1845
  if (ent.error) {
986
1846
  return { entityName, error: ent.error };
@@ -995,32 +1855,40 @@ async function _validateRecordWrite(entityName, fields) {
995
1855
  defs = null; // unreadable → can't validate fields; proceed
996
1856
  }
997
1857
  if (defs && defs.length > 0) {
1858
+ const many = records.length > 1;
998
1859
  const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
999
- const unknown = Object.keys(fields).filter((k) => !fieldNames.has(k));
1860
+ const unknown = [
1861
+ ...new Set(records.flatMap((r) => Object.keys(r).filter((k) => !fieldNames.has(k)))),
1862
+ ];
1000
1863
  if (unknown.length > 0) {
1001
- return {
1002
- entityName,
1003
- error: jsonResponse({
1004
- error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
1005
- "The platform silently drops unknown keys, so this would create a record missing " +
1006
- "that data (a 'broken' entity). Use only real fields (see valid_fields), or add " +
1007
- "the field first with suppa_add_field.",
1008
- unknown_fields: unknown,
1009
- valid_fields: [...fieldNames].sort(),
1010
- }),
1864
+ const body = {
1865
+ error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
1866
+ "The platform silently drops unknown keys, so this would create a record missing " +
1867
+ "that data (a 'broken' entity). Use only real fields (see valid_fields), or add " +
1868
+ "the field first with suppa_add_field.",
1869
+ unknown_fields: unknown,
1870
+ valid_fields: [...fieldNames].sort(),
1011
1871
  };
1872
+ if (many) {
1873
+ body.offending_records = records
1874
+ .map((r, i) => (Object.keys(r).some((k) => !fieldNames.has(k)) ? i : -1))
1875
+ .filter((i) => i >= 0);
1876
+ body.note = "NOTHING was inserted — the whole batch is refused as one unit.";
1877
+ }
1878
+ return { entityName, error: jsonResponse(body) };
1012
1879
  }
1013
- const problems = _shapeProblemsFromDefs(defs, fields);
1880
+ const problems = records.flatMap((r, i) => _shapeProblemsFromDefs(defs, r).map((p) => many ? `record[${i}]: ${p}` : p));
1014
1881
  if (problems.length > 0) {
1015
- return {
1016
- entityName,
1017
- error: jsonResponse({
1018
- error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
1019
- problems,
1020
- hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
1021
- 'target entity for relations), then re-send as {"id": N}.',
1022
- }),
1882
+ const body = {
1883
+ error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
1884
+ problems,
1885
+ hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
1886
+ 'target entity for relations), then re-send as {"id": N}.',
1023
1887
  };
1888
+ if (many) {
1889
+ body.note = "NOTHING was inserted — the whole batch is refused as one unit.";
1890
+ }
1891
+ return { entityName, error: jsonResponse(body) };
1024
1892
  }
1025
1893
  }
1026
1894
  // The defs travel back so the caller does not re-read the schema to decide
@@ -1082,26 +1950,62 @@ export async function previewReplacedLists(entityName, fields, merge = [], unmer
1082
1950
  return _replacedListNames(defs, fields, merge, unmerge);
1083
1951
  }
1084
1952
  /**
1085
- * Create a new record in any entity. fields_json: JSON object of field values.
1953
+ * Create one record — or a whole BATCH — in any entity.
1954
+ *
1955
+ * fields_json is either a JSON object (one record; response and refusals are
1956
+ * unchanged) or a JSON ARRAY of such objects. The array is the platform's own
1957
+ * batch shape: POST /core/data/:entityName/insert takes "fields | object[] |
1958
+ * true | Array of records to insert" (data.txt:323), so N records are ONE
1959
+ * request — and one schema read validates them all, instead of N of each.
1086
1960
  *
1087
1961
  * Relation/enum values are shape-checked against the schema first — a bare
1088
1962
  * number/string for those fields is refused with guidance, because the
1089
- * platform would return 201 and silently store NULL.
1963
+ * platform would return 201 and silently store NULL. A batch is refused as a
1964
+ * unit: if any record is malformed, nothing is inserted.
1090
1965
  */
1091
1966
  export async function createRecord(entityName, fieldsJson) {
1092
- let fields;
1967
+ // Which shape the caller MEANT is decided before parsing, so a single record
1968
+ // is still refused with the exact wording it has always used.
1969
+ const raw = fieldsJson;
1970
+ const looksBatch = typeof raw === "string" ? raw.trimStart().startsWith("[") : Array.isArray(raw);
1971
+ let parsed;
1093
1972
  try {
1094
- fields = parseJsonParam(fieldsJson, "fields_json", "object");
1973
+ parsed = parseJsonParam(fieldsJson, "fields_json", looksBatch ? "array" : "object");
1095
1974
  }
1096
1975
  catch (e) {
1097
1976
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
1098
1977
  }
1099
- const v = await _validateRecordWrite(entityName, fields);
1978
+ const many = Array.isArray(parsed);
1979
+ const records = (many ? parsed : [parsed]);
1980
+ if (many && records.length === 0) {
1981
+ return jsonResponse({
1982
+ error: "fields_json is an empty array — nothing to create. Pass one record object, " +
1983
+ 'or an array of them: [{"title": "A"}, {"title": "B"}].',
1984
+ });
1985
+ }
1986
+ const badIndex = records.findIndex((r) => r === null || typeof r !== "object" || Array.isArray(r));
1987
+ if (badIndex !== -1) {
1988
+ return jsonResponse({
1989
+ error: `fields_json[${badIndex}] must be a JSON object of field values — got ` +
1990
+ `${JSON.stringify(records[badIndex] ?? null)}. A batch is an array of record objects.`,
1991
+ });
1992
+ }
1993
+ const rows = records;
1994
+ const v = await _validateRecordWrites(entityName, rows);
1100
1995
  if (v.error) {
1101
1996
  return v.error;
1102
1997
  }
1103
- const result = await insertEntity(v.entityName, [fields]);
1104
- return jsonResponse(result && result.length ? result[0] : null);
1998
+ // One request for the whole batch (data.txt:323 — `fields` is the array).
1999
+ const result = await insertEntity(v.entityName, rows);
2000
+ if (!many) {
2001
+ return jsonResponse(result && result.length ? result[0] : null);
2002
+ }
2003
+ return jsonResponse({
2004
+ created: result.length,
2005
+ requested: rows.length,
2006
+ entity: v.entityName,
2007
+ records: result,
2008
+ });
1105
2009
  }
1106
2010
  /** Parse a merge_json/unmerge_json parameter into a list of field names. */
1107
2011
  function _parseNameList(raw, param) {
@@ -1357,13 +2261,18 @@ export async function attachFileToRecord(entityName, recordId, filePath, fieldNa
1357
2261
  }
1358
2262
  /**
1359
2263
  * SOFT-delete a record (instance) from any entity: the platform sets deletedAt
1360
- * and keeps the row, so this is reversible (restore is UI-only until 1.3.0) —
1361
- * it is not a permanent purge. The record does vanish from normal reads.
2264
+ * and keeps the row, so this is reversible with restoreRecord — it is not a
2265
+ * permanent purge. The record does vanish from normal reads.
2266
+ *
2267
+ * The platform's PERMANENT delete (/core/data/:entityName/delete, data.txt:507
2268
+ * — "the rows leave the table and cannot be restored") is deliberately not
2269
+ * wired up here; there is no undo for it. Do not add one.
1362
2270
  *
1363
- * Removes a single instance, NOT the entity/schema. By design this module is
1364
- * add-only at the schema level (create_entity / add_field / add_enum_values) —
1365
- * there is no update-entity or remove-field operation, so fields can only be
1366
- * removed manually via the Suppa UI. Do not add one here.
2271
+ * Removes a single instance, NOT the entity/schema. At the schema level this
2272
+ * module creates (create_entity / add_field / add_enum_values) and edits fields
2273
+ * (update_field — builder.txt:344, within the endpoint's own restrictions), but
2274
+ * REMOVES nothing: there is no remove-fields or remove-entity call here, so a
2275
+ * field can only be dropped via the Suppa UI. Do not add one.
1367
2276
  */
1368
2277
  export async function deleteRecord(entityName, recordId) {
1369
2278
  // Verify the entity exists (best-effort) so a typo'd name gives a clear error
@@ -1375,6 +2284,63 @@ export async function deleteRecord(entityName, recordId) {
1375
2284
  const result = await removeEntity(ent.name, [makeFilter("id", recordId)]);
1376
2285
  return jsonResponse(result);
1377
2286
  }
2287
+ /**
2288
+ * UNDO a soft delete: clears deletedAt on one record so it returns to every
2289
+ * normal read. The counterpart of deleteRecord (/remove).
2290
+ *
2291
+ * The platform scopes the operation to soft-deleted rows itself (it adds
2292
+ * `deletedAt IS NOT NULL` to the conditions, data.txt:538), so restoring a
2293
+ * record that was never removed is a no-op rather than a mutation — an empty
2294
+ * result therefore means "nothing was deleted under that id", not a failure.
2295
+ */
2296
+ export async function restoreRecord(entityName, recordId) {
2297
+ const ent = await _resolveEntity(entityName);
2298
+ if (ent.error) {
2299
+ return ent.error;
2300
+ }
2301
+ const result = await restoreEntity(ent.name, [makeFilter("id", recordId)]);
2302
+ const rows = Array.isArray(result) ? result : result ? [result] : [];
2303
+ const out = {
2304
+ restored: rows.length > 0,
2305
+ entity: ent.name,
2306
+ record_id: Math.trunc(recordId),
2307
+ records: rows,
2308
+ };
2309
+ if (rows.length === 0) {
2310
+ out.note =
2311
+ `Nothing to restore: no SOFT-DELETED record ${Math.trunc(recordId)} in ` +
2312
+ `'${ent.name}'. Restore only touches rows with deletedAt set, so either the ` +
2313
+ "record is already active, it never existed, or it was purged. Check with " +
2314
+ "suppa_search_records(deleted_scope='deleted').";
2315
+ }
2316
+ return jsonResponse(out);
2317
+ }
2318
+ /**
2319
+ * Duplicate a record server-side, optionally with its attachments.
2320
+ *
2321
+ * fields_json overrides values on the copy (data.txt:454 — "fields is applied on
2322
+ * top of the copied values"), and is schema-validated exactly like createRecord
2323
+ * so an override the platform would silently drop is refused first.
2324
+ *
2325
+ * copy_files is the only way this server can duplicate a record's attachments:
2326
+ * attachFileToRecord uploads from a LOCAL path, which an agent holding only the
2327
+ * platform copy does not have.
2328
+ */
2329
+ export async function copyRecord(entityName, recordId, fieldsJson = "{}", copyFiles = false, copyRelatedEntities = false) {
2330
+ let fields;
2331
+ try {
2332
+ fields = parseJsonParam(fieldsJson, "fields_json", "object");
2333
+ }
2334
+ catch (e) {
2335
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
2336
+ }
2337
+ const v = await _validateRecordWrite(entityName, fields);
2338
+ if (v.error) {
2339
+ return v.error;
2340
+ }
2341
+ const result = await copyEntity(v.entityName, Math.trunc(recordId), fields, copyFiles, copyRelatedEntities);
2342
+ return jsonResponse(result);
2343
+ }
1378
2344
  // ---------------------------------------------------------------------------
1379
2345
  // helpers
1380
2346
  // ---------------------------------------------------------------------------