suppa-mcp-2 1.21.2 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Suppa MCP Server — unified gateway to the Suppa platform.
3
3
  *
4
- * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires all 87 tools,
4
+ * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires every tool,
5
5
  * mirrors the tool-behavior annotations (_READ/_ADD/_MUT), reproduces the
6
6
  * server `instructions` string verbatim, and OWNS all confirm-gating (the tool
7
7
  * modules mutate unconditionally, exactly like the Python tool functions).
@@ -29,6 +29,22 @@ export { PACKAGE_VERSION };
29
29
  // existing data (and is additionally approval-gated via confirm=true).
30
30
  // ---------------------------------------------------------------------------
31
31
  const _READ = { readOnlyHint: true };
32
+ /**
33
+ * A download reads on the platform but WRITES to the user's disk, so it is not
34
+ * read-only: readOnlyHint means "does not modify its environment", and a host
35
+ * that auto-approves read-only tools would let a model drop files anywhere the
36
+ * process can write.
37
+ *
38
+ * destructiveHint stays false deliberately. In this server that flag means "may
39
+ * destroy data on the platform" and carries the confirm gate with it (see
40
+ * destructiveToolsAreGated). A download destroys nothing remotely, and its own
41
+ * guard is `overwrite`, which defaults to false and refuses an existing file.
42
+ */
43
+ const _DOWNLOAD = {
44
+ readOnlyHint: false,
45
+ destructiveHint: false,
46
+ idempotentHint: true,
47
+ };
32
48
  const _ADD = {
33
49
  readOnlyHint: false,
34
50
  destructiveHint: false,
@@ -768,7 +784,10 @@ export function buildServer() {
768
784
  return text(await docs.deleteBlock(a.block_id));
769
785
  });
770
786
  reg("suppa_reorder_blocks", {
771
- description: "Reorder blocks on a page. block_ids: comma-separated IDs to move. Provide after_id or before_id as anchor.",
787
+ description: "Reorder blocks on a page. block_ids: comma-separated IDs to move. Provide after_id or before_id as anchor.\n" +
788
+ "\n" +
789
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
790
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
772
791
  inputSchema: {
773
792
  page_id: z.number().int(),
774
793
  block_ids: z
@@ -1314,15 +1333,29 @@ export function buildServer() {
1314
1333
  annotations: _ADD,
1315
1334
  }, async (a) => text(await entity.addEnumValues(a.enum_name, a.values)));
1316
1335
  reg("suppa_set_title_field", {
1317
- description: "Set an entity's display-title (representative) field; creates it if missing.",
1336
+ description: "Set an entity's display-title (representative) field; creates it if missing.\n" +
1337
+ "\n" +
1338
+ " This CHANGES what every existing record of the entity displays as its label,\n" +
1339
+ " so it is confirm-gated like any other edit to live data.\n" +
1340
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
1341
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
1318
1342
  inputSchema: {
1319
1343
  entity_name: EntityName,
1320
1344
  field_name: z
1321
1345
  .string()
1322
1346
  .describe("Field to use as the record display title; created (multi-language) if missing."),
1347
+ confirm: Confirm,
1323
1348
  },
1324
- annotations: _ADD,
1325
- }, async (a) => text(await entity.setTitleField(a.entity_name, a.field_name)));
1349
+ annotations: _MUT,
1350
+ }, async (a) => {
1351
+ if (!a.confirm) {
1352
+ return text(confirmRequired("set title field", {
1353
+ entity: a.entity_name,
1354
+ field: a.field_name,
1355
+ }));
1356
+ }
1357
+ return text(await entity.setTitleField(a.entity_name, a.field_name));
1358
+ });
1326
1359
  reg("suppa_list_field_types", {
1327
1360
  description: "List all available field types for entity/form creation.",
1328
1361
  annotations: _READ,
@@ -1483,10 +1516,10 @@ export function buildServer() {
1483
1516
  reg("suppa_list_record_files", {
1484
1517
  description: "List the files attached to one record of any entity.\n" +
1485
1518
  "\n" +
1486
- " Returns fileName, filePath, pdfPath, previewPath, size, mimeType and type\n" +
1487
- " for each attachment. It does NOT return the file id, and\n" +
1488
- " suppa_download_file needs one — read ids from the 'Files' entity with\n" +
1489
- " suppa_search_records, or keep the id suppa_attach_file_to_record returns.\n" +
1519
+ " Returns file_ids ready for suppa_download_file / suppa_download_files_zip,\n" +
1520
+ " plus fileName, filePath, pdfPath, previewPath, size, mimeType and type for\n" +
1521
+ " each attachment. A row that carries no id can be looked up on the 'Files'\n" +
1522
+ " entity with suppa_search_records.\n" +
1490
1523
  " An empty list can also mean the entity has no file field at all; check it\n" +
1491
1524
  " with suppa_describe_entity.\n",
1492
1525
  inputSchema: {
@@ -1522,7 +1555,7 @@ export function buildServer() {
1522
1555
  .default(false)
1523
1556
  .describe("Allow replacing an existing file at dest_path."),
1524
1557
  },
1525
- annotations: _READ,
1558
+ annotations: _DOWNLOAD,
1526
1559
  }, async (a) => text(await files.downloadFile(a.file_id, a.dest_path, a.file_type, a.overwrite)));
1527
1560
  reg("suppa_download_files_zip", {
1528
1561
  description: "Download several attachments at once as one ZIP archive.\n" +
@@ -1560,7 +1593,7 @@ export function buildServer() {
1560
1593
  .default(false)
1561
1594
  .describe("Allow replacing an existing archive at dest_path."),
1562
1595
  },
1563
- annotations: _READ,
1596
+ annotations: _DOWNLOAD,
1564
1597
  }, async (a) => text(await files.downloadFilesZip(a.file_ids, a.dest_path, a.overwrite, a.entity_name, a.record_ids)));
1565
1598
  reg("suppa_attach_file_to_record", {
1566
1599
  description: "Attach a local file to a record (instance) of any entity.\n\n" +
@@ -1571,8 +1604,7 @@ export function buildServer() {
1571
1604
  " field — check with suppa_describe_entity and add one with suppa_add_field if it\n" +
1572
1605
  " has none. KEEP THE RETURNED file_ids: they are the only handle that gets the bytes\n" +
1573
1606
  " back (suppa_download_file / suppa_download_files_zip). suppa_list_record_files\n" +
1574
- " lists what a record carries but does NOT return ids; the other source for them is\n" +
1575
- " suppa_search_records on the 'Files' entity. To put a record's attachments on a\n" +
1607
+ " returns them too, for files already attached. To put a record's attachments on a\n" +
1576
1608
  " copy, use suppa_copy_record(copy_files=true) — a file already on the platform has\n" +
1577
1609
  " no local path to re-upload from.",
1578
1610
  inputSchema: {
@@ -1830,9 +1862,13 @@ export function buildServer() {
1830
1862
  .boolean()
1831
1863
  .default(true)
1832
1864
  .describe("Exclude relation fields with no populated instances in v1 (create:false). Probe errors keep the field; set false to keep every relation."),
1865
+ overwrite: z
1866
+ .boolean()
1867
+ .default(false)
1868
+ .describe("Allow output_file to replace a file that already exists. Off by default so a second dry run cannot quietly destroy a plan you edited by hand."),
1833
1869
  },
1834
1870
  annotations: _ADD,
1835
- }, async (a) => text(await migrate.migrateEntities(a.dry_run, a.entity_names, a.include_builtin, a.skip_relations, a.output_file, a.plan_file, a.mode, a.check_relation_instances, a.skip_empty_relations)));
1871
+ }, async (a) => text(await migrate.migrateEntities(a.dry_run, a.entity_names, a.include_builtin, a.skip_relations, a.output_file, a.plan_file, a.mode, a.check_relation_instances, a.skip_empty_relations, a.overwrite)));
1836
1872
  reg("suppa_read_v1_entities", {
1837
1873
  description: "List entities on the configured Suppa 1.0 backend (read-only).",
1838
1874
  inputSchema: {
@@ -1990,7 +2026,8 @@ export function buildServer() {
1990
2026
  }, async (a) => text(await forms.getForm(a.form_id)));
1991
2027
  reg("suppa_create_form", {
1992
2028
  description: "Create a new form. Provide schema_json (array of fields or {formShema}), or set\n" +
1993
- " generate_from_entity=True with entity_name to auto-build fields from the entity.\n" +
2029
+ " generate_from_entity=true WITH entity_name to auto-build fields from the entity\n" +
2030
+ " (without entity_name it is refused, rather than creating an empty form).\n" +
1994
2031
  " Form names are UNIQUE platform-wide — a duplicate name fails; pick a distinct one.",
1995
2032
  inputSchema: {
1996
2033
  name: z.string(),
package/dist/store.js CHANGED
@@ -106,6 +106,12 @@ export function available() {
106
106
  }
107
107
  /** Load credentials for `host`, or `null` if absent / unavailable / corrupt. */
108
108
  export function load(host) {
109
+ // A pair this process rotated but could not persist is the freshest thing
110
+ // there is — the keychain still holds the token the platform has revoked.
111
+ const inMemory = memoryFallback.get(host);
112
+ if (inMemory) {
113
+ return { ...inMemory };
114
+ }
109
115
  const entry = entryFor(host);
110
116
  if (entry === null) {
111
117
  return null;
@@ -165,6 +171,26 @@ export function load(host) {
165
171
  return null;
166
172
  }
167
173
  }
174
+ /**
175
+ * Credentials this PROCESS rotated but could not persist.
176
+ *
177
+ * A keychain whose reads work while its writes fail (a locked Secret Service
178
+ * collection, a policy-restricted Credential Manager) used to burn the session:
179
+ * the platform rotated the pair, the write threw, the new tokens were dropped,
180
+ * and the next request went out with the old access token — which the platform
181
+ * had already invalidated. The session then died with "run suppa_login",
182
+ * blaming the session for a storage problem.
183
+ *
184
+ * Holding the rotated pair in memory degrades that to "this session keeps
185
+ * working, the next one logs in again", which is the honest outcome.
186
+ */
187
+ const memoryFallback = new Map();
188
+ /** Why the last persist for this host failed, for a message that names it. */
189
+ const persistErrors = new Map();
190
+ /** The persist error for `host`, if its credentials live only in memory. */
191
+ export function persistError(host) {
192
+ return persistErrors.get(host) ?? null;
193
+ }
168
194
  /** Persist credentials for `host`. Throws if no keychain backend exists. */
169
195
  export function save(host, creds) {
170
196
  const entry = entryFor(host);
@@ -185,11 +211,17 @@ export function save(host, creds) {
185
211
  entry.setPassword(blob);
186
212
  // Success — make sure no stale chunks linger from a prior chunked write.
187
213
  clearChunks(host);
214
+ memoryFallback.delete(host);
215
+ persistErrors.delete(host);
188
216
  return;
189
217
  }
190
218
  catch (err) {
191
219
  if (!isBlobSizeError(err)) {
192
- throw err;
220
+ // Readable-but-unwritable keychain: keep the pair for this process rather
221
+ // than losing a rotation that already happened on the platform.
222
+ memoryFallback.set(host, { ...creds });
223
+ persistErrors.set(host, err instanceof Error ? err.message : String(err));
224
+ return;
193
225
  }
194
226
  }
195
227
  // Chunked path: split the blob across sibling entries, then write a manifest.
@@ -211,9 +243,11 @@ export function save(host, creds) {
211
243
  * Exported as `del` because `delete` is a reserved word.
212
244
  */
213
245
  export function del(host) {
246
+ const hadMemory = memoryFallback.delete(host);
247
+ persistErrors.delete(host);
214
248
  const entry = entryFor(host);
215
249
  if (entry === null) {
216
- return false;
250
+ return hadMemory;
217
251
  }
218
252
  try {
219
253
  let raw;
@@ -221,10 +255,10 @@ export function del(host) {
221
255
  raw = entry.getPassword();
222
256
  }
223
257
  catch {
224
- return false;
258
+ return hadMemory;
225
259
  }
226
260
  if (raw === null) {
227
- return false;
261
+ return hadMemory;
228
262
  }
229
263
  // If this is a chunked entry, remove its chunk siblings too.
230
264
  try {
package/dist/tenants.js CHANGED
@@ -65,10 +65,23 @@ export function aliasOf(host) {
65
65
  const dot = host.indexOf(".");
66
66
  return dot === -1 ? host : host.slice(0, dot);
67
67
  }
68
+ /** True when stored credentials can no longer be refreshed into a live session. */
69
+ function storedSessionIsDead(creds) {
70
+ const exp = creds.refreshExp || 0;
71
+ return !creds.refreshToken || (exp > 0 && Date.now() / 1000 >= exp);
72
+ }
68
73
  function tokenProviderFor(host, envFallback = "") {
69
74
  return function provider() {
70
75
  const creds = store.load(host);
71
76
  if (creds && creds.accessToken) {
77
+ // A stored session whose refresh token has expired can never come back,
78
+ // and it used to SHADOW a perfectly good SUPPA_API_KEY: the documented
79
+ // CI path stopped working on any machine that had once logged in, and
80
+ // the 401 said "run suppa_login" — the wrong action, since the fix is a
81
+ // new key or suppa_logout.
82
+ if (envFallback && storedSessionIsDead(creds)) {
83
+ return envFallback;
84
+ }
72
85
  return creds.accessToken;
73
86
  }
74
87
  return envFallback;
@@ -103,7 +116,15 @@ function bootstrapKeychainFromEnv() {
103
116
  const host = defaultHost();
104
117
  const existing = store.load(host);
105
118
  if (existing && existing.accessToken) {
106
- return; // Keychain already has credentials; don't overwrite
119
+ // Keep what is stored UNLESS it is a dead session or a different pair —
120
+ // an expired keychain entry used to make a fresh env key unusable, with no
121
+ // way out but suppa_logout.
122
+ if (!storedSessionIsDead(existing) && existing.accessToken === config.API_KEY) {
123
+ return;
124
+ }
125
+ if (!storedSessionIsDead(existing)) {
126
+ return;
127
+ }
107
128
  }
108
129
  try {
109
130
  const creds = {
@@ -190,11 +211,17 @@ export function resolve(name) {
190
211
  // or "Testing.Modern.Me". Match case-insensitively so we re-use the stored
191
212
  // tenant instead of registering a mixed-case duplicate with no credentials.
192
213
  const key = name.toLowerCase();
193
- // Known host (exact, then case-insensitive).
194
- if (name in reg) {
214
+ // Known host (exact, then case-insensitive). OWN properties only: the
215
+ // registry is a JSON-parsed object, so `"toString" in reg` was true and
216
+ // suppa_use_tenant("toString") activated a tenant with no base URL — every
217
+ // later call then said "not signed in" for a tenant that does not exist.
218
+ const known = (host) => Object.prototype.hasOwnProperty.call(reg, host) && Boolean(reg[host]?.base_url);
219
+ if (known(name)) {
195
220
  return [reg[name].base_url, name, reg[name].alias];
196
221
  }
197
222
  for (const [host, info] of Object.entries(reg)) {
223
+ if (!known(host))
224
+ continue;
198
225
  if (host.toLowerCase() === key || String(info.alias).toLowerCase() === key) {
199
226
  return [info.base_url, host, info.alias];
200
227
  }
@@ -9,7 +9,7 @@
9
9
  * present, and is otherwise DERIVED from the `nodes` JSON of live workflows.
10
10
  */
11
11
  import { makeRequest, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
12
- import { makeFilter, jsonResponse, parseJsonParam } from "../utils.js";
12
+ import { makeFilter, jsonResponse, parseJsonParam, ACCESS_METADATA_KEYS } from "../utils.js";
13
13
  export const WORKFLOW_ENTITY = "AutomationWorkflow";
14
14
  export const EXECUTE_ENTITY = "AutomationWorkflowExecute";
15
15
  export const EXECUTE_DATA_ENTITY = "AutomationWorkflowExecuteData";
@@ -69,24 +69,25 @@ function _envelope(rows, limit, offset, key) {
69
69
  };
70
70
  }
71
71
  /**
72
- * Recursively drop ACL keys (any key starting with '$', i.e.
73
- * $readAccess/$updateAccess/$instanceAccess). Returns a new structure; all
74
- * real values — including legitimate nested nulls — are preserved verbatim.
72
+ * Drop the platform's ACL metadata ($readAccess/$updateAccess/$instanceAccess)
73
+ * from ONE row — shallow, named keys only. Everything below row level is
74
+ * returned verbatim: a workflow's `nodes`/`settings` and a run's
75
+ * `runData`/`executionState` are caller data (n8n-style `$set`, `$schema`,
76
+ * `$json`, header names …) and a deep walk that deleted every '$'-prefixed key
77
+ * silently truncated them — the documented read -> edit -> update round trip
78
+ * then WROTE the truncated graph back to the tenant. Never recurse here.
75
79
  */
76
80
  export function _clean(obj) {
77
- if (isPlainObject(obj)) {
78
- const out = {};
79
- for (const [k, v] of Object.entries(obj)) {
80
- if (!String(k).startsWith("$")) {
81
- out[k] = _clean(v);
82
- }
83
- }
84
- return out;
81
+ if (!isPlainObject(obj)) {
82
+ return obj;
85
83
  }
86
- if (Array.isArray(obj)) {
87
- return obj.map((v) => _clean(v));
84
+ const out = {};
85
+ for (const [k, v] of Object.entries(obj)) {
86
+ if (!ACCESS_METADATA_KEYS.includes(k)) {
87
+ out[k] = v;
88
+ }
88
89
  }
89
- return obj;
90
+ return out;
90
91
  }
91
92
  /**
92
93
  * Drop keys whose value is None (structural-null omission). SHALLOW — only
@@ -147,10 +148,18 @@ export function _paramType(value) {
147
148
  function _nodeType(n) {
148
149
  return n.type ?? n.nodeType ?? n.kind ?? null;
149
150
  }
151
+ // `parameters` FIRST: live graphs store the node config there and ALSO carry a
152
+ // react-flow `data` ({label}) — reading data first hid the real config behind
153
+ // the label (get_automation showed {label} as config; the validator refused a
154
+ // node whose parameters.entityName was present).
150
155
  function _nodeConfig(n) {
151
- const cfg = n.config ?? n.data ?? n.parameters ?? {};
156
+ const cfg = n.parameters ?? n.config ?? n.data ?? {};
152
157
  return isPlainObject(cfg) ? cfg : {};
153
158
  }
159
+ /** The `parameters` object the platform actually executes — no fallbacks. */
160
+ function _nodeParameters(n) {
161
+ return isPlainObject(n.parameters) ? n.parameters : {};
162
+ }
154
163
  /**
155
164
  * The `nodes` column may be a list or an id-keyed dict — flatten to a list
156
165
  * of node dicts.
@@ -166,7 +175,7 @@ function _normalizeNodes(nodes) {
166
175
  }
167
176
  /** Raw node -> {id, type, name?, config, position?}. config = parameters verbatim. */
168
177
  function _normalizeNode(raw) {
169
- const node = { id: raw.id ?? null, type: _nodeType(raw), config: _clean(_nodeConfig(raw)) };
178
+ const node = { id: raw.id ?? null, type: _nodeType(raw), config: _nodeConfig(raw) };
170
179
  if (raw.name !== null && raw.name !== undefined) {
171
180
  node.name = raw.name;
172
181
  }
@@ -236,6 +245,7 @@ function _stepsFromRunData(runData) {
236
245
  /** List automation workflows with `nodeCount`. ACL stripped, null fields omitted. */
237
246
  export async function listAutomations(search = "", isActive = null, limit = 20, offset = 0) {
238
247
  limit = Math.max(1, Math.min(limit, 500));
248
+ offset = Math.max(0, offset);
239
249
  const filters = [];
240
250
  if (isActive !== null && isActive !== undefined) {
241
251
  filters.push(makeFilter("isActive", isActive));
@@ -320,6 +330,7 @@ function isTruthy(v) {
320
330
  /** List runs of one automation, newest first. ACL stripped, null fields omitted. */
321
331
  export async function listAutomationRuns(automationId, status = null, limit = 20, offset = 0) {
322
332
  limit = Math.max(1, Math.min(limit, 500));
333
+ offset = Math.max(0, offset);
323
334
  const filters = [makeFilter("workflow.id", automationId)];
324
335
  if (status) {
325
336
  filters.push(makeFilter("status", status));
@@ -596,7 +607,7 @@ async function _nodeSchemaDerived(nodeType) {
596
607
  name: k,
597
608
  type: _collapseParamType(v.types),
598
609
  required: count > 0 && v.seen === count,
599
- sample: _clean(v.sample),
610
+ sample: v.sample,
600
611
  }));
601
612
  }
602
613
  return {
@@ -685,7 +696,7 @@ export async function getAutomationNodeSchema(nodeType) {
685
696
  type: meta.type ?? null,
686
697
  required: Boolean(meta.required),
687
698
  description: meta.description ?? null,
688
- sample: name in samples ? _clean(samples[name]) : null,
699
+ sample: name in samples ? samples[name] : null,
689
700
  }));
690
701
  }
691
702
  return jsonResponse(_compact({
@@ -899,8 +910,9 @@ export function _validateWorkflow(nodes, connections) {
899
910
  if (!isPlainObject(n) || typeof n.type !== "string") {
900
911
  continue;
901
912
  }
902
- // Tolerant config read (parameters||config||data), matching the read path.
903
- const params = _nodeConfig(n);
913
+ // Strictly `parameters` — that is the object the platform executes, so a
914
+ // requirement satisfied only by `config`/`data` would still fail live.
915
+ const params = _nodeParameters(n);
904
916
  const idLabel = typeof n.id === "string" ? n.id : "?";
905
917
  if (n.type === "triggerEntity" && !params.entityName) {
906
918
  errors.push(`trigger node '${idLabel}' (triggerEntity) requires parameters.entityName`);
@@ -990,8 +1002,9 @@ export async function createAutomation(name, nodesJson, connectionsJson, setting
990
1002
  }
991
1003
  const fields = { name, nodes, connections, settings, isActive: false };
992
1004
  const rows = await insertEntity(WORKFLOW_ENTITY, [fields]);
993
- const id = rows.length && isPlainObject(rows[0]) ? rows[0].id ?? null : null;
994
- return jsonResponse({ created: true, id, name });
1005
+ const id = Array.isArray(rows) && rows.length && isPlainObject(rows[0]) ? rows[0].id ?? null : null;
1006
+ // An insert that returns no row created nothing we can address — say so.
1007
+ return jsonResponse({ created: id !== null, id, name, result: rows });
995
1008
  }
996
1009
  /**
997
1010
  * Partial update of a draft workflow (read-modify-write). Only the fields the
@@ -1062,8 +1075,11 @@ export async function updateAutomation(automationId, name = null, nodesJson, con
1062
1075
  }
1063
1076
  /** Soft-delete a workflow via the entity API. */
1064
1077
  export async function deleteAutomation(automationId) {
1065
- await removeEntity(WORKFLOW_ENTITY, [makeFilter("id", automationId)]);
1066
- return jsonResponse({ deleted: true, id: automationId });
1078
+ const res = await removeEntity(WORKFLOW_ENTITY, [makeFilter("id", automationId)]);
1079
+ // /remove with a filter that matched nothing returns an empty list — an id
1080
+ // that never existed must not be reported as deleted.
1081
+ const deleted = Array.isArray(res) ? res.length > 0 : Boolean(res);
1082
+ return jsonResponse({ deleted, id: automationId, result: res });
1067
1083
  }
1068
1084
  /**
1069
1085
  * Parse the JSON error body out of an "HTTP <code> <reason>: <body>" Error
@@ -39,6 +39,27 @@ export const PAGE_FIELDS = {
39
39
  icon: true,
40
40
  createdBy: { id: true, fullName: true },
41
41
  };
42
+ /**
43
+ * The block types suppa_create_blocks documents (server.ts, tool description).
44
+ * Anything else is refused before it reaches the platform: an unknown type
45
+ * would either be rejected there with a less useful message or, worse, stored
46
+ * and rendered as an empty block.
47
+ */
48
+ export const BLOCK_TYPES = [
49
+ "text",
50
+ "head1",
51
+ "head2",
52
+ "head3",
53
+ "bulletList",
54
+ "numberedList",
55
+ "checkList",
56
+ "quote",
57
+ "callout",
58
+ "divider",
59
+ "code",
60
+ "table",
61
+ "toggle",
62
+ ];
42
63
  export const BLOCK_FIELDS = {
43
64
  id: true,
44
65
  type: true,
@@ -139,6 +160,9 @@ function typeName(value) {
139
160
  */
140
161
  export function _blocksFromJson(pageId, blocksJson) {
141
162
  const parsed = parseJsonParam(blocksJson, "blocks_json", "array");
163
+ if (parsed.length === 0) {
164
+ throw new Error("blocks_json is an empty array — pass at least one block.");
165
+ }
142
166
  const insertFields = [];
143
167
  for (const bd of parsed) {
144
168
  if (!isPlainObject(bd)) {
@@ -146,6 +170,9 @@ export function _blocksFromJson(pageId, blocksJson) {
146
170
  `got ${typeName(bd)}.`);
147
171
  }
148
172
  const btype = bd.type ?? "text";
173
+ if (typeof btype !== "string" || !BLOCK_TYPES.includes(btype)) {
174
+ throw new Error(`Unknown block type ${JSON.stringify(btype)}. Supported types: ${BLOCK_TYPES.join(", ")}.`);
175
+ }
149
176
  let props;
150
177
  if (isPlainObject(bd.properties)) {
151
178
  props = bd.properties;
@@ -375,6 +402,9 @@ export async function createBlocks(pageId, blocksJson) {
375
402
  * blocks_json: JSON array of {type, title, properties?, format?}.
376
403
  */
377
404
  export async function insertBlock(pageId, blocksJson, afterId = null, beforeId = null) {
405
+ if (afterId && beforeId) {
406
+ return jsonResponse({ error: "Provide only one of after_id / before_id" });
407
+ }
378
408
  if (!afterId && !beforeId) {
379
409
  return jsonResponse({ error: "Provide after_id or before_id to specify position" });
380
410
  }
@@ -459,12 +489,20 @@ export async function updateBlock(blockId, title = null, propertiesJson = null)
459
489
  else if (title !== null && title !== undefined) {
460
490
  // The title path heals \uXXXX escapes — but not for code blocks, where the
461
491
  // escapes may be genuine source. updateBlock has no type arg, so look it up.
492
+ // The read also brings the current properties: `properties` is written as a
493
+ // whole, so sending {title} alone would wipe a code block's `language` and a
494
+ // checkList item's `checked`.
462
495
  const existing = await selectEntity(ENTITY_PAGE_BLOCKS, [makeFilter("id", blockId)], {
463
496
  id: true,
464
497
  type: true,
498
+ properties: true,
465
499
  });
466
- const isCode = isPlainObject(existing) && existing.type === "code";
467
- fields.properties = { title: wrapHtml(title, !isCode) };
500
+ if (!isPlainObject(existing)) {
501
+ return jsonResponse({ error: `Block ${blockId} not found — nothing updated.` });
502
+ }
503
+ const isCode = existing.type === "code";
504
+ const current = isPlainObject(existing.properties) ? existing.properties : {};
505
+ fields.properties = { ...current, title: wrapHtml(title, !isCode) };
468
506
  }
469
507
  else {
470
508
  return jsonResponse({ error: "Provide title or properties_json" });
@@ -485,6 +523,9 @@ export async function deleteBlock(blockId) {
485
523
  * Provide after_id to place them after that block, or before_id to place before it.
486
524
  */
487
525
  export async function reorderBlocks(pageId, blockIds, afterId = null, beforeId = null) {
526
+ if (afterId && beforeId) {
527
+ return jsonResponse({ error: "Provide only one of after_id / before_id" });
528
+ }
488
529
  if (!afterId && !beforeId) {
489
530
  return jsonResponse({ error: "Provide after_id or before_id" });
490
531
  }