suppa-mcp-2 1.45.0 → 1.46.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -8
- package/dist/bin.js +32 -1
- package/dist/cli/api.js +102 -21
- package/dist/cli/run.js +6 -3
- package/dist/server.js +103 -13
- package/dist/startupRepair.js +1 -1
- package/dist/toolTable.js +1 -1
- package/dist/tools/customOrder.js +307 -0
- package/dist/tools/docs.js +48 -27
- package/dist/tools/entity.js +82 -11
- package/dist/tools/recordOrder.js +266 -0
- package/dist/tools/tasks.js +82 -16
- package/package.json +1 -1
- package/skills/suppa-cli/SKILL.md +13 -7
- package/skills/suppa-form-v2/code-form/SOURCE.json +3 -3
- package/skills/suppa-form-v2/scripts/code-form/code-form-core.mjs +8 -8
- package/skills/suppa-form-v2/scripts/form-core.mjs +24 -24
- package/skills/suppa-form-v2/scripts/validate-form-schema.mjs +42 -15
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The platform's MANUAL order of records ("custom order") — for ANY entity.
|
|
3
|
+
*
|
|
4
|
+
* It is not a column. The platform keeps it in its own table, CustomOrders, one
|
|
5
|
+
* row per (entity, context field, context value, record), and exposes it two ways
|
|
6
|
+
* (entity-builder develop 1e8ea716d):
|
|
7
|
+
* - read: an orderBy entry {field, order, function: "custom_order", args: [value]}
|
|
8
|
+
* (core2 lower-custom-order.pass.ts; "#custom_order" is the same name —
|
|
9
|
+
* sql-safety.util.ts toSafeDslFunctionName strips the "#");
|
|
10
|
+
* - write: POST /api/core/data/custom-order/<Entity> with InstancesOrderDto
|
|
11
|
+
* (modules/entity/controllers/custom-order.controller.ts).
|
|
12
|
+
*
|
|
13
|
+
* The CONTEXT names the list: one parent's children are (parent, 40), a
|
|
14
|
+
* hierarchy's top level is (parent, null), a flat entity's own list is the global
|
|
15
|
+
* order (no field, no value). Reads express exactly these three; nothing reads a
|
|
16
|
+
* value without a field (assertReadableContext). A hierarchy that ALSO has an
|
|
17
|
+
* owner keeps its top level per owner: the top-level PageBlocks of page 12 are
|
|
18
|
+
* (page, 12) read with parent = null, the top-level Pages of doc 55 are (doc, 55)
|
|
19
|
+
* — the front reads and writes exactly these (pagesStore.ts loadDocPages, the
|
|
20
|
+
* page and block reorders), and nothing reads (parent, null) for them.
|
|
21
|
+
*
|
|
22
|
+
* Anchors are positions IN THE LIST THE READER SEES, read in `direction`, and the
|
|
23
|
+
* ids land as one block in the order given — InstancesOrderDto.direction ("relative
|
|
24
|
+
* to what the user sees … Absent ⇒ 'desc'") and
|
|
25
|
+
* test/integration/common/custom-order/custom-order-visible-order.e2e.spec.ts pin
|
|
26
|
+
* both. Nothing here inverts an anchor or reverses the ids.
|
|
27
|
+
*/
|
|
28
|
+
import { makeRequest, searchEntity } from "../httpClient.js";
|
|
29
|
+
/**
|
|
30
|
+
* contextFieldName for the global order. The DTO requires a name, and the
|
|
31
|
+
* controller's (no field, no value) branch IS the global order — the front sends
|
|
32
|
+
* 'parent' for a flat table and relies on exactly that (custom-order.controller.ts
|
|
33
|
+
* assertReadableContext). orderContextRefusal guarantees the entity has no `parent`.
|
|
34
|
+
*/
|
|
35
|
+
export const GLOBAL_CONTEXT_FIELD = "parent";
|
|
36
|
+
/** What the planner scopes a custom_order by (lower-custom-order.pass.ts: "must be an "enum" or "many-to-one" relation"). */
|
|
37
|
+
const CONTEXT_FIELD_TYPES = new Set(["many-to-one", "enum"]);
|
|
38
|
+
const ACCEPTED = "custom_order, custom_order(page, 12) or custom_order(parent), each optionally followed by :asc or :desc";
|
|
39
|
+
const CUSTOM_ORDER = /^custom_order\s*(?:\(\s*(?:"?([A-Za-z_][A-Za-z0-9_]*)"?\s*(?:,\s*(null|\d+)\s*)?)?\))?\s*(?::\s*([A-Za-z]+)\s*)?$/i;
|
|
40
|
+
/**
|
|
41
|
+
* An order_by that asks for the manual order, or null when it is a plain 'field:dir'.
|
|
42
|
+
* custom_order the entity's global order, desc
|
|
43
|
+
* custom_order(page, 2962) the list of page 2962
|
|
44
|
+
* custom_order(parent):asc a hierarchy's top level, read ascending
|
|
45
|
+
* Throws, naming the accepted forms, when it starts like one and is malformed.
|
|
46
|
+
*/
|
|
47
|
+
export function parseCustomOrderBy(orderBy) {
|
|
48
|
+
const text = String(orderBy ?? "").trim();
|
|
49
|
+
if (!/^custom_order(?![A-Za-z0-9_])/i.test(text))
|
|
50
|
+
return null;
|
|
51
|
+
const m = CUSTOM_ORDER.exec(text);
|
|
52
|
+
if (!m)
|
|
53
|
+
throw new Error(`order_by '${text}' is not a manual-order read. Accepted: ${ACCEPTED}.`);
|
|
54
|
+
const [, field, rawValue, rawDir] = m;
|
|
55
|
+
const direction = (rawDir ?? "desc").toLowerCase();
|
|
56
|
+
if (direction !== "asc" && direction !== "desc") {
|
|
57
|
+
throw new Error(`order_by direction must be 'asc' or 'desc', got '${rawDir}'. Accepted: ${ACCEPTED}.`);
|
|
58
|
+
}
|
|
59
|
+
const value = rawValue === undefined || rawValue.toLowerCase() === "null" ? null : Number(rawValue);
|
|
60
|
+
if (value !== null && !isRecordId(value)) {
|
|
61
|
+
throw new Error(`order_by's context value must be a positive record id, got '${rawValue}'. Accepted: ${ACCEPTED}.`);
|
|
62
|
+
}
|
|
63
|
+
return { context: { field: field ?? null, value }, direction };
|
|
64
|
+
}
|
|
65
|
+
/** A record id: a positive, safe integer (the platform once stored contextValue = 0 for a missing value). */
|
|
66
|
+
export function isRecordId(n) {
|
|
67
|
+
return Number.isSafeInteger(n) && n > 0;
|
|
68
|
+
}
|
|
69
|
+
export function flip(direction) {
|
|
70
|
+
return direction === "desc" ? "asc" : "desc";
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The orderBy of a read in that order. The custom-order entry goes FIRST:
|
|
74
|
+
* #expand_tree orders a row's children by their own parent's order only then
|
|
75
|
+
* (expand-tree.service.ts selectInParentOrder). The id entry breaks ties so offset
|
|
76
|
+
* paging is stable, and runs against the order so asc is exactly desc reversed.
|
|
77
|
+
*/
|
|
78
|
+
export function customOrderBy(context, direction) {
|
|
79
|
+
const entry = {};
|
|
80
|
+
if (context.field !== null)
|
|
81
|
+
entry.field = context.field;
|
|
82
|
+
entry.order = direction;
|
|
83
|
+
entry.function = "custom_order";
|
|
84
|
+
if (context.field !== null && context.value !== null)
|
|
85
|
+
entry.args = [context.value];
|
|
86
|
+
return [entry, { field: "id", order: flip(direction) }];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The filters that keep a read to the rows of its list (a row outside it has no
|
|
90
|
+
* place in it) — with `topLevelField`, an owner list's top level only.
|
|
91
|
+
*/
|
|
92
|
+
export function contextFilters(context, topLevelField = null) {
|
|
93
|
+
if (context.field === null)
|
|
94
|
+
return [];
|
|
95
|
+
const own = context.value === null
|
|
96
|
+
? { field: context.field, comparator: "=", value: null }
|
|
97
|
+
: { field: `${context.field}.id`, comparator: "=", value: context.value };
|
|
98
|
+
return topLevelField === null ? [own] : [own, { field: topLevelField, comparator: "=", value: null }];
|
|
99
|
+
}
|
|
100
|
+
/** The order_by that reads this list back with suppa_search_records. */
|
|
101
|
+
export function orderByText(context, direction) {
|
|
102
|
+
const head = context.field === null
|
|
103
|
+
? "custom_order"
|
|
104
|
+
: context.value === null
|
|
105
|
+
? `custom_order(${context.field})`
|
|
106
|
+
: `custom_order(${context.field}, ${context.value})`;
|
|
107
|
+
return direction === "asc" ? `${head}:asc` : head;
|
|
108
|
+
}
|
|
109
|
+
/** Why this placement cannot be sent, or null. `anchorArg` names the anchor's argument in the answer. */
|
|
110
|
+
export function placementProblem(where, anchorId, movedIds, anchorArg = "anchor_id") {
|
|
111
|
+
const noAnchor = anchorId === null || anchorId === undefined;
|
|
112
|
+
if (where === "before" || where === "after") {
|
|
113
|
+
if (noAnchor)
|
|
114
|
+
return `where='${where}' needs ${anchorArg} — the id of a record of the same list.`;
|
|
115
|
+
if (!isRecordId(anchorId)) {
|
|
116
|
+
return `${anchorArg} must be a positive record id, got ${String(anchorId)}.`;
|
|
117
|
+
}
|
|
118
|
+
if (movedIds.includes(anchorId)) {
|
|
119
|
+
return `${anchorArg} ${anchorId} is one of the records being placed — anchor on a record that stays put.`;
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (where === "first" || where === "last") {
|
|
124
|
+
return noAnchor ? null : `where='${where}' takes no ${anchorArg} — leave it null, or use where='before'/'after'.`;
|
|
125
|
+
}
|
|
126
|
+
return `where must be 'before', 'after', 'first' or 'last', got '${String(where)}'.`;
|
|
127
|
+
}
|
|
128
|
+
/** The body of POST /api/core/data/custom-order/<Entity>. `updates` stays empty: the platform applies it as sudo. */
|
|
129
|
+
export function reorderBody(ids, context, direction, anchor) {
|
|
130
|
+
return {
|
|
131
|
+
instanceIds: [...ids],
|
|
132
|
+
contextFieldName: context.field ?? GLOBAL_CONTEXT_FIELD,
|
|
133
|
+
contextValue: context.value,
|
|
134
|
+
direction,
|
|
135
|
+
updates: {},
|
|
136
|
+
...("beforeId" in anchor ? { beforeInstanceId: anchor.beforeId } : { afterInstanceId: anchor.afterId }),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function fieldsOf(schema) {
|
|
140
|
+
const fields = schema?.fields;
|
|
141
|
+
return Array.isArray(fields) ? fields.filter((f) => typeof f === "object" && f !== null) : [];
|
|
142
|
+
}
|
|
143
|
+
const carriesOrder = (f) => f.options?.customOrder === true;
|
|
144
|
+
/** The hierarchy field of an entity whose order is kept per parent. */
|
|
145
|
+
const HIERARCHY_FIELD = "parent";
|
|
146
|
+
/**
|
|
147
|
+
* The owners of a hierarchy kept per owner: the order-carrying many-to-one fields
|
|
148
|
+
* other than `parent` (Pages: doc, PageBlocks: page). Read from the schema, never
|
|
149
|
+
* from the entity's name; empty when the entity has no `parent` many-to-one.
|
|
150
|
+
*/
|
|
151
|
+
function ownersOf(fields) {
|
|
152
|
+
const isManyToOne = (f) => String(f.type) === "many-to-one";
|
|
153
|
+
if (!fields.some((f) => f.name === HIERARCHY_FIELD && isManyToOne(f)))
|
|
154
|
+
return [];
|
|
155
|
+
return fields
|
|
156
|
+
.filter((f) => carriesOrder(f) && isManyToOne(f) && f.name !== HIERARCHY_FIELD && f.name !== "id")
|
|
157
|
+
.map((f) => String(f.name));
|
|
158
|
+
}
|
|
159
|
+
function perOwnerRefusal(entityName, owners) {
|
|
160
|
+
const top = owners.map((o) => `context_field='${o}', context_value=<${o} id> (custom_order(${o}, <id>))`).join(" or ");
|
|
161
|
+
return (`'${entityName}' is a hierarchy kept per ${owners.join(" / ")}: no list reads its global order or parent = null. ` +
|
|
162
|
+
`The top level is kept per owner — ${top}; one parent's children: ` +
|
|
163
|
+
"context_field='parent', context_value=<parent id> (custom_order(parent, <id>)).");
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Why `context` cannot name a manual order of `entityName` — or, when it can, the
|
|
167
|
+
* list it names: an owner list of a hierarchy kept per owner carries its
|
|
168
|
+
* topLevelField, which contextFilters and listProblem apply. One GET
|
|
169
|
+
* /api/core/schema/<E>. Without it the platform answers a wrong context
|
|
170
|
+
* with "custom_order() expects a field name as its first argument, got a 'func'
|
|
171
|
+
* expression" (read live on Pages.title) — or, on a write, stores an order that
|
|
172
|
+
* no list ever reads.
|
|
173
|
+
*/
|
|
174
|
+
export async function orderContextRefusal(entityName, context) {
|
|
175
|
+
const refuse = (refusal) => ({ refusal });
|
|
176
|
+
if (context.field === null && context.value !== null) {
|
|
177
|
+
return refuse("context_value needs a context_field: the platform keeps no list under a value without a field, " +
|
|
178
|
+
"and nothing could read it back. Name the field that scopes the list (e.g. 'page').");
|
|
179
|
+
}
|
|
180
|
+
if (context.value !== null && !isRecordId(context.value)) {
|
|
181
|
+
return refuse(`context_value must be a positive record id (or null for the field's empty group), got ${String(context.value)}.`);
|
|
182
|
+
}
|
|
183
|
+
let schema;
|
|
184
|
+
try {
|
|
185
|
+
// One path segment: a name with a '/' must not reach another endpoint.
|
|
186
|
+
schema = await makeRequest("GET", `/api/core/schema/${encodeURIComponent(entityName)}`);
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
190
|
+
return refuse(`Refused: the schema of '${entityName}' could not be read (${msg}) — check the name with suppa_list_entities. Nothing was sent.`);
|
|
191
|
+
}
|
|
192
|
+
const fields = fieldsOf(schema);
|
|
193
|
+
if (!fields.some(carriesOrder)) {
|
|
194
|
+
return refuse(`'${entityName}' keeps no manual order: none of its fields carries options.customOrder.`);
|
|
195
|
+
}
|
|
196
|
+
const scoping = fields.filter((f) => carriesOrder(f) && f.name !== "id").map((f) => String(f.name));
|
|
197
|
+
const scopes = scoping.length ? scoping.join(", ") : "none — only its own list (no context)";
|
|
198
|
+
const owners = ownersOf(fields);
|
|
199
|
+
const list = (topLevelField = null) => ({ refusal: null, list: { context, topLevelField } });
|
|
200
|
+
if (context.field === null) {
|
|
201
|
+
const hierarchy = fields.find((f) => f.name === HIERARCHY_FIELD || f.name === "parents");
|
|
202
|
+
if (!hierarchy)
|
|
203
|
+
return list();
|
|
204
|
+
if (hierarchy.name === "parents") {
|
|
205
|
+
return refuse(`'${entityName}' is a multi-parent hierarchy: its manual order is kept per parent (parents), which this server does not read or write yet.`);
|
|
206
|
+
}
|
|
207
|
+
if (owners.length)
|
|
208
|
+
return refuse(perOwnerRefusal(entityName, owners));
|
|
209
|
+
return refuse(`'${entityName}' is a hierarchy: its manual order is kept per parent and no list reads a global one. ` +
|
|
210
|
+
"Name the field — context_field='parent' / custom_order(parent) for the top level, " +
|
|
211
|
+
"custom_order(parent, <id>) for one parent's children.");
|
|
212
|
+
}
|
|
213
|
+
const def = fields.find((f) => f.name === context.field);
|
|
214
|
+
if (!def)
|
|
215
|
+
return refuse(`'${entityName}' has no field '${context.field}'. Fields that scope its manual order: ${scopes}.`);
|
|
216
|
+
if (!CONTEXT_FIELD_TYPES.has(String(def.type))) {
|
|
217
|
+
return refuse(`'${context.field}' is a ${String(def.type)} field — a manual order is scoped only by a many-to-one ` +
|
|
218
|
+
`relation or an enum. Fields that scope it on '${entityName}': ${scopes}.`);
|
|
219
|
+
}
|
|
220
|
+
if (owners.length && context.field === HIERARCHY_FIELD && context.value === null) {
|
|
221
|
+
return refuse(perOwnerRefusal(entityName, owners));
|
|
222
|
+
}
|
|
223
|
+
return list(owners.includes(context.field) ? HIERARCHY_FIELD : null);
|
|
224
|
+
}
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
// Membership. The platform's custom-order write runs as sudo and checks no rights
|
|
227
|
+
// on the rows (custom-order.controller.ts updateRows), so every row a write moves,
|
|
228
|
+
// and every anchor, is read first WITH THE CALLER'S RIGHTS (active rows only).
|
|
229
|
+
// ---------------------------------------------------------------------------
|
|
230
|
+
/** One call moves or inserts at most this many records — one membership read covers them. */
|
|
231
|
+
export const MAX_ORDER_IDS = 200;
|
|
232
|
+
/** A record id from a bare id or a {id} reference; null for anything else. */
|
|
233
|
+
export function idOf(v) {
|
|
234
|
+
if (typeof v === "number" && Number.isInteger(v))
|
|
235
|
+
return v;
|
|
236
|
+
if (v !== null && typeof v === "object" && Number.isInteger(v.id))
|
|
237
|
+
return v.id;
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
/** Why `ids` cannot be the records of one move, or null. `arg` names the argument in the answer. */
|
|
241
|
+
export function idsProblem(ids, arg = "record_ids") {
|
|
242
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
243
|
+
return `${arg} is empty — pass the ids to move, in the order they should stand.`;
|
|
244
|
+
}
|
|
245
|
+
if (ids.length > MAX_ORDER_IDS)
|
|
246
|
+
return `${arg} has ${ids.length} ids; one call moves at most ${MAX_ORDER_IDS}.`;
|
|
247
|
+
const bad = ids.filter((n) => !isRecordId(n));
|
|
248
|
+
if (bad.length)
|
|
249
|
+
return `${arg} must be positive record ids; got ${JSON.stringify(bad)}.`;
|
|
250
|
+
if (new Set(ids).size !== ids.length)
|
|
251
|
+
return `${arg} names a record twice — each id once, in the order they should stand.`;
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
/** The fields a membership read of `list` projects: its context field, and the field its top level keeps empty. */
|
|
255
|
+
export function listFields(list) {
|
|
256
|
+
return [list.context.field, list.topLevelField].filter((f) => f !== null);
|
|
257
|
+
}
|
|
258
|
+
/** `ids` of `entity`, read with the caller's rights (active rows only), each of `fields` projected as {id}. */
|
|
259
|
+
export async function readOrderRows(entity, ids, fields) {
|
|
260
|
+
const projection = { id: true };
|
|
261
|
+
for (const f of fields)
|
|
262
|
+
projection[f] = { id: true };
|
|
263
|
+
const rows = (await searchEntity(entity, [{ field: "id", comparator: "in", value: ids }], projection, ids.length + 1, 0, [{ field: "id", order: "asc" }], "", "and", "active"));
|
|
264
|
+
return new Map(rows.map((r) => [r.id, r]));
|
|
265
|
+
}
|
|
266
|
+
/** Why the rows read (`byId`) do not all stand in `list`, or null. Pure; the reason only. */
|
|
267
|
+
export function listProblem(entity, list, ids, byId) {
|
|
268
|
+
const missing = ids.filter((id) => !byId.has(id));
|
|
269
|
+
if (missing.length) {
|
|
270
|
+
return `Records ${missing.join(", ")} of '${entity}' were not found — no such id, soft-deleted, or not visible to you.`;
|
|
271
|
+
}
|
|
272
|
+
const { field, value } = list.context;
|
|
273
|
+
if (field === null)
|
|
274
|
+
return null;
|
|
275
|
+
// An empty relation reads back as null. A field hidden by field permissions
|
|
276
|
+
// reads back ABSENT, and a related row the caller may not see comes back masked
|
|
277
|
+
// "*" (entity-builder lower-root-relations.pass.ts) — neither is "empty": never
|
|
278
|
+
// take them for standing in a list.
|
|
279
|
+
const readable = (row, f) => row !== undefined && Object.prototype.hasOwnProperty.call(row, f) && (row[f] === null || idOf(row[f]) !== null);
|
|
280
|
+
for (const f of listFields(list)) {
|
|
281
|
+
const unread = ids.filter((id) => !readable(byId.get(id), f));
|
|
282
|
+
if (unread.length) {
|
|
283
|
+
return `You cannot read '${f}' of records ${unread.join(", ")} of '${entity}' (hidden from you), so their list cannot be checked.`;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const foreign = ids.filter((id) => idOf(byId.get(id)?.[field] ?? null) !== value);
|
|
287
|
+
if (foreign.length) {
|
|
288
|
+
const where = value === null ? `${field} is empty` : `${field} = ${value}`;
|
|
289
|
+
return `Records ${foreign.join(", ")} do not stand in the list ${where} — a record is placed only among the records of its own list.`;
|
|
290
|
+
}
|
|
291
|
+
const top = list.topLevelField;
|
|
292
|
+
if (top === null)
|
|
293
|
+
return null;
|
|
294
|
+
const nested = ids
|
|
295
|
+
.map((id) => [id, idOf(byId.get(id)?.[top] ?? null)])
|
|
296
|
+
.filter((p) => p[1] !== null);
|
|
297
|
+
if (!nested.length)
|
|
298
|
+
return null;
|
|
299
|
+
return (`Records ${nested.map(([id, parent]) => `${id} (its list: custom_order(${top}, ${parent}))`).join(", ")} are nested: ` +
|
|
300
|
+
`the list ${field} = ${String(value)} holds the top level only; a nested record stands in its own parent's list — ` +
|
|
301
|
+
`context_field='${top}', context_value=<that parent's id>.`);
|
|
302
|
+
}
|
|
303
|
+
/** Why `ids` cannot be placed in `list`, or null. One read, with the caller's rights. */
|
|
304
|
+
export async function membershipRefusal(entity, list, ids) {
|
|
305
|
+
const why = listProblem(entity, list, ids, await readOrderRows(entity, ids, listFields(list)));
|
|
306
|
+
return why === null ? null : `${why} Nothing was sent.`;
|
|
307
|
+
}
|
package/dist/tools/docs.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { makeRequest, dataUrl, customOrderUrl, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
|
|
12
12
|
import { ownProjection, registerOwnProjections } from "../projection.js";
|
|
13
|
+
import { idOf, idsProblem, listProblem, membershipRefusal, placementProblem, readOrderRows, reorderBody, } from "./customOrder.js";
|
|
13
14
|
import { makeFilter, writeOutcome, stripHtml, jsonResponse, wrapHtml, unescapeUnicode, parseJsonParam, parseProjectionParam, notFoundAnswer, } from "../utils.js";
|
|
14
15
|
// ---------------------------------------------------------------------------
|
|
15
16
|
// Constants
|
|
@@ -245,6 +246,15 @@ export function _flattenBlockTree(rows, _seen = null) {
|
|
|
245
246
|
}
|
|
246
247
|
return out;
|
|
247
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* The list a page's top-level blocks stand in, as the front keeps it: (page, P)
|
|
251
|
+
* with parent empty. A block's children stand in (parent, X) — pagesStore.ts,
|
|
252
|
+
* the block reorders. The custom-order write is sudo and checks no rights, so the
|
|
253
|
+
* block tools read the rows they place, and the anchor, against this list first.
|
|
254
|
+
*/
|
|
255
|
+
function topLevelBlocks(pageId) {
|
|
256
|
+
return { context: { field: "page", value: pageId }, topLevelField: "parent" };
|
|
257
|
+
}
|
|
248
258
|
/** Fetch a page's blocks in custom (display) order (used by getBlocks/readPage). */
|
|
249
259
|
async function _fetchBlocks(pageId) {
|
|
250
260
|
const body = {
|
|
@@ -484,6 +494,18 @@ export async function insertBlock(pageId, blocksJson, afterId = null, beforeId =
|
|
|
484
494
|
catch (e) {
|
|
485
495
|
return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
|
|
486
496
|
}
|
|
497
|
+
// The new blocks stand at the page's top level (_blocksFromJson sets page, never
|
|
498
|
+
// parent), so the anchor must be a top-level block of this page — read with the
|
|
499
|
+
// caller's rights BEFORE the create, so a refusal leaves nothing behind.
|
|
500
|
+
const anchorId = (afterId || beforeId);
|
|
501
|
+
const anchorArg = afterId ? "after_id" : "before_id";
|
|
502
|
+
const notHere = placementProblem(afterId ? "after" : "before", anchorId, [], anchorArg) ??
|
|
503
|
+
(await membershipRefusal(ENTITY_PAGE_BLOCKS, topLevelBlocks(pageId), [anchorId]));
|
|
504
|
+
if (notHere) {
|
|
505
|
+
return jsonResponse({
|
|
506
|
+
error: `${notHere} suppa_insert_block creates top-level blocks of page ${pageId}: ${anchorArg} must be one of those.`,
|
|
507
|
+
});
|
|
508
|
+
}
|
|
487
509
|
const res = await makeRequest("POST", dataUrl(ENTITY_PAGE_BLOCKS, "insert"), {
|
|
488
510
|
fields: payload,
|
|
489
511
|
returning: { id: true, type: true },
|
|
@@ -498,24 +520,15 @@ export async function insertBlock(pageId, blocksJson, afterId = null, beforeId =
|
|
|
498
520
|
if (newIds.length === 0) {
|
|
499
521
|
return jsonResponse({ error: "Insert returned no block ids; nothing to position.", raw: res });
|
|
500
522
|
}
|
|
501
|
-
//
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
contextValue: pageId,
|
|
506
|
-
updates: {},
|
|
507
|
-
};
|
|
508
|
-
if (afterId) {
|
|
509
|
-
reorderBody.beforeInstanceId = afterId;
|
|
510
|
-
}
|
|
511
|
-
else if (beforeId) {
|
|
512
|
-
reorderBody.afterInstanceId = beforeId;
|
|
513
|
-
}
|
|
523
|
+
// Anchors as the editor sends them (front pageBlocksAdapter.ts): the side the
|
|
524
|
+
// reader sees, ids in the order given, read desc — customOrder.ts F3.
|
|
525
|
+
const anchor = afterId ? { afterId } : { beforeId: beforeId };
|
|
526
|
+
const orderBody = reorderBody(newIds, { field: "page", value: pageId }, "desc", anchor);
|
|
514
527
|
// The blocks already exist at this point. If only the positioning fails,
|
|
515
528
|
// report partial success with the ids — raising would hide the insert and
|
|
516
529
|
// bait the agent into retrying, which duplicates the blocks.
|
|
517
530
|
try {
|
|
518
|
-
await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS),
|
|
531
|
+
await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), orderBody);
|
|
519
532
|
}
|
|
520
533
|
catch (e) {
|
|
521
534
|
const msg = e instanceof Error ? e.message : String(e);
|
|
@@ -635,19 +648,27 @@ export async function reorderBlocks(pageId, blockIds, afterId = null, beforeId =
|
|
|
635
648
|
if (ids.length === 0) {
|
|
636
649
|
return jsonResponse({ error: "block_ids is empty — pass at least one block id." });
|
|
637
650
|
}
|
|
638
|
-
|
|
639
|
-
const
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
+
const anchorId = (afterId || beforeId);
|
|
652
|
+
const problem = idsProblem(ids, "block_ids") ??
|
|
653
|
+
placementProblem(afterId ? "after" : "before", anchorId, ids, afterId ? "after_id" : "before_id");
|
|
654
|
+
if (problem)
|
|
655
|
+
return jsonResponse({ error: problem });
|
|
656
|
+
// One read of the blocks and the anchor, with the caller's rights. The first
|
|
657
|
+
// block names the list — the page's top level, or one block's children — and
|
|
658
|
+
// every block and the anchor must stand in it, on this page.
|
|
659
|
+
const all = [...ids, anchorId];
|
|
660
|
+
const rows = await readOrderRows(ENTITY_PAGE_BLOCKS, all, ["page", "parent"]);
|
|
661
|
+
const parentId = idOf(rows.get(ids[0])?.parent ?? null);
|
|
662
|
+
const list = parentId === null ? topLevelBlocks(pageId) : { context: { field: "parent", value: parentId }, topLevelField: null };
|
|
663
|
+
const offPage = all.filter((id) => rows.has(id) && idOf(rows.get(id)?.page ?? null) !== pageId);
|
|
664
|
+
const why = listProblem(ENTITY_PAGE_BLOCKS, list, all, rows) ??
|
|
665
|
+
(offPage.length ? `Blocks ${offPage.join(", ")} are not on page ${pageId}.` : null);
|
|
666
|
+
if (why)
|
|
667
|
+
return jsonResponse({ error: `${why} Nothing was sent.` });
|
|
668
|
+
// Anchors as the editor sends them (front pageBlocksAdapter.ts): the side the
|
|
669
|
+
// reader sees, ids in the order given, read desc — customOrder.ts F3.
|
|
670
|
+
const anchor = afterId ? { afterId } : { beforeId: beforeId };
|
|
671
|
+
const body = reorderBody(ids, list.context, "desc", anchor);
|
|
651
672
|
await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), body);
|
|
652
673
|
return jsonResponse({
|
|
653
674
|
reordered: ids,
|
package/dist/tools/entity.js
CHANGED
|
@@ -21,6 +21,7 @@ import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListPro
|
|
|
21
21
|
import { compactEntitySchema, slimTitle, titleLanguages } from "../readEconomy.js";
|
|
22
22
|
import { customFieldsHint } from "../customFieldHints.js";
|
|
23
23
|
import { transliterationProblem, untranslatedTokens } from "./nameMap.js";
|
|
24
|
+
import { contextFilters, customOrderBy, orderByText, orderContextRefusal, parseCustomOrderBy, } from "./customOrder.js";
|
|
24
25
|
// Builder field types that accept file uploads.
|
|
25
26
|
export const FILE_FIELD_TYPES = ["file", "multi-file"];
|
|
26
27
|
export const RELATION_FIELD_TYPES = [
|
|
@@ -679,8 +680,41 @@ export async function listEntities(search = "", full = false) {
|
|
|
679
680
|
return e;
|
|
680
681
|
});
|
|
681
682
|
}
|
|
683
|
+
if (Array.isArray(result))
|
|
684
|
+
result = [...result, ...(await _tabularPartRows(result, search, full))];
|
|
682
685
|
return jsonResponse(result);
|
|
683
686
|
}
|
|
687
|
+
/**
|
|
688
|
+
* The tabular parts, for the end of the listing. GET /core/schema leaves them out by design — it lists
|
|
689
|
+
* only entities with no `relationEntity` (entity-builder schema.controller getEntities), so a tenant's
|
|
690
|
+
* `OrderItems` never showed in suppa_list_entities (reported 2026-11-16). The platform lists them apart:
|
|
691
|
+
* GET /core/schema/tabular-parts → `{ id, name, type: 'tabular-part', relationEntity: { id, name } }`.
|
|
692
|
+
* Each comes back as `{ id, name, type: "tabular-part", owner }`. A stand that does not answer that
|
|
693
|
+
* route lists as it did before; a part the main listing already has is not repeated.
|
|
694
|
+
*/
|
|
695
|
+
async function _tabularPartRows(listed, search, full) {
|
|
696
|
+
let parts;
|
|
697
|
+
try {
|
|
698
|
+
parts = await makeRequest("GET", "/api/core/schema/tabular-parts");
|
|
699
|
+
}
|
|
700
|
+
catch {
|
|
701
|
+
return [];
|
|
702
|
+
}
|
|
703
|
+
if (!Array.isArray(parts))
|
|
704
|
+
return [];
|
|
705
|
+
const have = new Set(listed.filter(isPlainObject).map((e) => String(e.name ?? "")));
|
|
706
|
+
const needle = search.toLowerCase();
|
|
707
|
+
return parts
|
|
708
|
+
.filter(isPlainObject)
|
|
709
|
+
.map((p) => {
|
|
710
|
+
const row = p;
|
|
711
|
+
const owner = isPlainObject(row.relationEntity) ? row.relationEntity.name ?? null : null;
|
|
712
|
+
return { row, owner: typeof owner === "string" ? owner : null };
|
|
713
|
+
})
|
|
714
|
+
.filter(({ row, owner }) => typeof row.name === "string" && !have.has(row.name))
|
|
715
|
+
.filter(({ row, owner }) => !needle || String(row.name).toLowerCase().includes(needle) || (owner ?? "").toLowerCase().includes(needle))
|
|
716
|
+
.map(({ row, owner }) => (full ? row : { id: row.id, name: row.name, type: "tabular-part", owner }));
|
|
717
|
+
}
|
|
684
718
|
/**
|
|
685
719
|
* The searchable text of a title. Titles are localized objects ({en, uk, ...});
|
|
686
720
|
* String() on one is "[object Object]", so no localized title ever matched and
|
|
@@ -861,16 +895,45 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
|
|
|
861
895
|
}
|
|
862
896
|
fields = proj.fields;
|
|
863
897
|
}
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
});
|
|
898
|
+
// order_by is either 'field:dir' or a read of the platform's MANUAL order,
|
|
899
|
+
// custom_order(<field>, <id>) — see customOrder.ts for what that list is.
|
|
900
|
+
let custom;
|
|
901
|
+
try {
|
|
902
|
+
custom = parseCustomOrderBy(orderBy);
|
|
903
|
+
}
|
|
904
|
+
catch (e) {
|
|
905
|
+
return jsonResponse({ error: e instanceof Error ? e.message : String(e), records: [], returned: 0 });
|
|
906
|
+
}
|
|
907
|
+
let order;
|
|
908
|
+
if (custom) {
|
|
909
|
+
const check = await orderContextRefusal(entityName, custom.context);
|
|
910
|
+
if (check.refusal !== null) {
|
|
911
|
+
return jsonResponse({ error: check.refusal, records: [], returned: 0 });
|
|
912
|
+
}
|
|
913
|
+
order = customOrderBy(custom.context, custom.direction);
|
|
914
|
+
// The read is the rows OF that list: one outside it has no place in it and
|
|
915
|
+
// would sort by its creation time among the rest — and an owner list of a
|
|
916
|
+
// hierarchy kept per owner holds its top level only (parent = null). ANDed
|
|
917
|
+
// with the caller's filters even under match_any, which keeps its OR among them.
|
|
918
|
+
const scoped = contextFilters(check.list.context, check.list.topLevelField);
|
|
919
|
+
if (scoped.length) {
|
|
920
|
+
const own = filters;
|
|
921
|
+
filters = matchAny && own.length > 0 ? [{ operator: "or", filters: own }, ...scoped] : [...own, ...scoped];
|
|
922
|
+
matchAny = false;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
else {
|
|
926
|
+
const idx = orderBy.indexOf(":");
|
|
927
|
+
const field = idx === -1 ? orderBy : orderBy.slice(0, idx);
|
|
928
|
+
const rawDir = idx === -1 ? "" : orderBy.slice(idx + 1);
|
|
929
|
+
const direction = rawDir.trim().toLowerCase() || "desc";
|
|
930
|
+
if (direction !== "asc" && direction !== "desc") {
|
|
931
|
+
return jsonResponse({
|
|
932
|
+
error: `order_by direction must be 'asc' or 'desc', got '${direction}'.`,
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
order = [{ field: field.trim() || "createdAt", order: direction }];
|
|
872
936
|
}
|
|
873
|
-
const order = [{ field: field.trim() || "createdAt", order: direction }];
|
|
874
937
|
// Fetch one extra row so the agent learns whether another page exists.
|
|
875
938
|
// Cap at 500/page: larger responses blow the model's context — page instead.
|
|
876
939
|
limit = Math.max(1, Math.min(limit, 500));
|
|
@@ -935,6 +998,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
|
|
|
935
998
|
Object.assign(out, diag);
|
|
936
999
|
}
|
|
937
1000
|
}
|
|
1001
|
+
if (custom) {
|
|
1002
|
+
out.custom_order = {
|
|
1003
|
+
context_field: custom.context.field,
|
|
1004
|
+
context_value: custom.context.value,
|
|
1005
|
+
direction: custom.direction,
|
|
1006
|
+
order_by: orderByText(custom.context, custom.direction),
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
938
1009
|
return jsonResponse(out);
|
|
939
1010
|
}
|
|
940
1011
|
/**
|
|
@@ -2433,8 +2504,8 @@ async function _updateField(entityName, fieldName, opts, checkOnly) {
|
|
|
2433
2504
|
notApplicable.push(`defaultValue was sent as the plain string ${JSON.stringify(body.defaultValue)} on ` +
|
|
2434
2505
|
`'${fieldName}', which is a '${liveType}' — a default on a relation/enum/file field is a ` +
|
|
2435
2506
|
"REFERENCE: `{ id }`, or `[{ id }, …]` for a multi (a Users relation also takes the " +
|
|
2436
|
-
"`$current-user` token).
|
|
2437
|
-
"Enums row id
|
|
2507
|
+
"`$current-user` token). An enum field holds the " +
|
|
2508
|
+
"Enums row id; a many-to-one to Users may hold `$current-user`. Read the field " +
|
|
2438
2509
|
"back to check what was stored.");
|
|
2439
2510
|
}
|
|
2440
2511
|
}
|