suppa-mcp-2 1.46.1 → 1.47.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/README.md CHANGED
@@ -30,7 +30,7 @@ No API key needed to start — the server authenticates interactively via the `s
30
30
 
31
31
  ## The `suppa` command
32
32
 
33
- The same 110 operations the MCP server exposes are available as a command, for
33
+ The same 118 operations the MCP server exposes are available as a command, for
34
34
  shells, scripts and CI:
35
35
 
36
36
  ```bash
@@ -419,7 +419,7 @@ extension table is created outside that check and is not subject to it.
419
419
 
420
420
  ## Available tools
421
421
 
422
- 110 tools across the areas below.
422
+ 118 tools across the areas below.
423
423
 
424
424
  ### Session & identity
425
425
 
@@ -538,6 +538,25 @@ extension table is created outside that check and is not subject to it.
538
538
  Designing, laying out or optimizing an automation before writing it: the bundled
539
539
  `skills/building-suppa-automations` skill (see below).
540
540
 
541
+ ### Registers
542
+
543
+ 1C-style accumulation registers (stock: movements, balances, turnovers) and information registers
544
+ (prices by period) built into entity-builder — `REGISTERS_ENABLED` on the platform.
545
+
546
+ | Tool | Description |
547
+ |---|---|
548
+ | `suppa_registers_kb` | The bundled `skills/suppa-registers` skill, offline: the cycle, concepts, rules, reads, operations, errors |
549
+ | `suppa_create_register` | Create a register with its fields and roles; frozen options are checked before the request, `timezone` is required, and it asks first (`confirm`) — a register cannot be removed |
550
+ | `suppa_save_posting_rule` | Create or update a posting rule by names; the confirmation request previews it on a document (confirm-gated) |
551
+ | `suppa_read_register` | Balance, turnovers, balance and turnovers, movements, slices — under the caller's rights, paged |
552
+ | `suppa_register_document` | A document's posting state, movements, violations and preview; or the state of up to 1000 documents |
553
+ | `suppa_repost_documents` | Repost one document, or history as a job; the confirmation request carries the dry run (confirm-gated) |
554
+ | `suppa_register_status` | The operations panel, one register's state with held documents and open violations, a job |
555
+ | `suppa_operate_register` | Totals suspend / resume / rebuild / check, the closed date, release held, resolve a violation, jobs (confirm-gated) |
556
+
557
+ A document is an entity with the `document` option (`suppa_update_entity_options`); your own SQL over
558
+ register reads is `suppa_query` with `virtual_tables_json`.
559
+
541
560
  ### Forms
542
561
 
543
562
  | Tool | Description |
@@ -591,6 +610,7 @@ Guided workflows clients can expose as slash commands:
591
610
  | `build_entity` | `entity_purpose` | Guided design + creation of a new entity, fields, enums, and a form |
592
611
  | `migrate_from_v1` | `entity_names?` | Guided Suppa 1.0 → 2.0 schema migration (dry-run, review, execute) |
593
612
  | `write_entity_code` | `entity_purpose` | Guided: write v2 application schema code (entities, seeds, registration) instead of API calls |
613
+ | `build_register` | `register_purpose` | Guided: a stock register from zero — register, document, posting rule previewed on a real document, repost of history |
594
614
 
595
615
  ---
596
616
 
@@ -846,7 +866,7 @@ At run time a read is checked the same way before it is sent, so no tool learns
846
866
  suppa-mcp-node/
847
867
  ├── src/
848
868
  │ ├── bin.ts # Entry point — stdio transport
849
- │ ├── server.ts # McpServer + all 95 tool + 4 prompt registrations
869
+ │ ├── server.ts # McpServer + all 118 tool + 5 prompt registrations
850
870
  │ ├── config.ts # Env / .env config surface
851
871
  │ ├── store.ts # Credentials in the OS keychain (@napi-rs/keyring)
852
872
  │ ├── registry.ts # Non-secret tenant registry (~/.suppa-mcp/tenants.json)
@@ -858,10 +878,12 @@ suppa-mcp-node/
858
878
  │ └── tools/
859
879
  │ ├── tasks.ts docs.ts entity.ts forms.ts
860
880
  │ ├── automation.ts # read + write automation tools
881
+ │ ├── registers.ts # registers: create, rules, reads, documents, repost, operations
861
882
  │ ├── migrate.ts nameMap.ts v1Fields.ts
862
883
  │ └── workspace.ts
863
884
  ├── skills/suppa-entity-code/ # bundled agent skill: write v2 schema code + validator
864
885
  ├── skills/building-suppa-automations/ # bundled agent skill: design, lay out, lint and publish automations
886
+ ├── skills/suppa-registers/ # bundled agent skill: registers — served by suppa_registers_kb
865
887
  ├── test/ # vitest suite (ports the Python test suite)
866
888
  ├── scripts/ # live read-only / write verify scripts
867
889
  ├── package.json
package/dist/server.js CHANGED
@@ -30,6 +30,7 @@ import * as automation from "./tools/automation.js";
30
30
  import * as query from "./tools/query.js";
31
31
  import * as sqlKb from "./tools/sqlKb.js";
32
32
  import * as queryAnalyze from "./tools/queryAnalyze.js";
33
+ import * as registers from "./tools/registers.js";
33
34
  import * as auth from "./auth.js";
34
35
  import * as tenants from "./tenants.js";
35
36
  import { confirmRequired, jsonResponse } from "./utils.js";
@@ -1085,9 +1086,13 @@ export function buildToolTable() {
1085
1086
  .max(query.QUERY_MAX_LIMIT)
1086
1087
  .default(query.QUERY_DEFAULT_LIMIT)
1087
1088
  .describe("Rows to show (1-500)."),
1089
+ virtual_tables_json: z
1090
+ .string()
1091
+ .optional()
1092
+ .describe('Register reads to select FROM: {"b": {"register": "Stock", "kind": "balance"}}.'),
1088
1093
  },
1089
1094
  annotations: _READ,
1090
- }, async (a) => text(await query.runQuery(a.query, a.bind_params_json ?? null, a.limit)));
1095
+ }, async (a) => text(await query.runQuery(a.query, a.bind_params_json ?? null, a.limit, a.virtual_tables_json ?? null)));
1091
1096
  reg("suppa_sql_kb", {
1092
1097
  description: "The SuppaSQL skill (skills/writing-suppa-sql): write, check and tune a query for\n" +
1093
1098
  " suppa_query, a chart / table SQL source or an application. Offline; touches no tenant.\n\n" +
@@ -1206,7 +1211,8 @@ export function buildToolTable() {
1206
1211
  "globalSearch, timeTracking, favorites, pinned, approvals, checklists, " +
1207
1212
  "recurrence, reminders, notificationMutes, customFields, stateHistory (booleans), " +
1208
1213
  "hierarchyDepthLimit (integer 1-20), commentsPrivacy (object), externalSource " +
1209
- '({"sourceEntity": <id>}). Unknown keys are refused (the platform would ' +
1214
+ '({"sourceEntity": <id>}), document (true, or {"dateField", "postedField"}: a registers ' +
1215
+ "recorder; frozen once set). Unknown keys are refused (the platform would " +
1210
1216
  "drop them silently). Enabling an option creates the side table that backs it, " +
1211
1217
  "and recurrence/reminders/notificationMutes/timeTracking/pinned also refresh the " +
1212
1218
  "corresponding system entity's cache — so this is not a free toggle."),
@@ -3043,6 +3049,150 @@ export function buildToolTable() {
3043
3049
  },
3044
3050
  annotations: _READ,
3045
3051
  }, async (a) => text(await healthCheck(a.deep)));
3052
+ // =========================================================================
3053
+ // Registers — 1C-style accumulation / information registers (tools/registers.ts;
3054
+ // knowledge: skills/suppa-registers, served by suppa_registers_kb).
3055
+ // =========================================================================
3056
+ const RegisterName = z.string();
3057
+ const DocEntity = z.string().describe("The document entity.");
3058
+ reg("suppa_registers_kb", {
3059
+ description: "Registers (1C-style stock / price registers), offline: no topic — the cycle; concepts | rules | reads |\n" +
3060
+ "operations | errors. Read it before creating a register or a rule: kinds and roles freeze.",
3061
+ inputSchema: {
3062
+ topic: z.enum(registers.KB_TOPICS).optional(),
3063
+ },
3064
+ annotations: _READ,
3065
+ }, async (a) => text(await registers.registersKb(a.topic ?? null)));
3066
+ reg("suppa_create_register", {
3067
+ description: "Create a register with its fields and roles, checked first: kind, type, periodicity, write mode and timezone\n" +
3068
+ "FREEZE, and a register cannot be removed. dimension: many-to-one, text, integer, boolean, timestamp+sub_type\n" +
3069
+ "date (≤ 8); resource: numeric, integer (≤ 6 decimals); attribute. No platform fields (period, recorder…).\n" +
3070
+ "suppa_registers_kb concepts. APPROVAL GATE: confirm=true creates.",
3071
+ inputSchema: {
3072
+ name: z.string().describe("PascalCase, ≤ 24 chars: GoodsInWarehouses."),
3073
+ title: z.string(),
3074
+ kind: z.enum(registers.REGISTER_KINDS).describe("accumulation: stock, balances. information: prices by period."),
3075
+ accumulation_type: z.enum(registers.ACCUMULATION_TYPES).nullable().default(null).describe("accumulation; default balance."),
3076
+ periodicity: z.enum(registers.PERIODICITIES).nullable().default(null).describe("information: required."),
3077
+ write_mode: z.enum(registers.WRITE_MODES).nullable().default(null).describe("information; default independent."),
3078
+ timezone: z.string().describe("IANA zone (Europe/Kyiv). Ask, never assume."),
3079
+ fields_json: z
3080
+ .string()
3081
+ .describe('[{"name":"warehouse","type":"many-to-one","relation_entity":"Warehouses","role":"dimension"},{"name":"qty","type":"numeric","decimal_places":3,"role":"resource"}]; optional title, sub_type.'),
3082
+ confirm: Confirm,
3083
+ },
3084
+ annotations: _ADD,
3085
+ }, async (a) => text(await registers.createRegister(a.name, a.title, a.kind, a.accumulation_type, a.periodicity, a.write_mode, a.timezone, a.fields_json, a.confirm)));
3086
+ reg("suppa_save_posting_rule", {
3087
+ description: "Create or update a posting rule by names: how a document's rows become movements. Without confirm and with\n" +
3088
+ "preview_document_id the platform checks it and shows that document's movements (rolled back). Saving does\n" +
3089
+ "NOT repost existing documents. suppa_registers_kb rules. APPROVAL GATE: confirm=true writes.",
3090
+ inputSchema: {
3091
+ register: RegisterName,
3092
+ recorder: DocEntity,
3093
+ source: z.string().nullable().default(null).describe("The tabular part it reads; null = the document."),
3094
+ key: z.string().describe("sale, receipt…"),
3095
+ definition_json: z
3096
+ .string()
3097
+ .describe('{"link":"owner","movements":[{"recordKind":"expense","set":{"sku":"\\"sku\\"","qty":"\\"qty\\""}}]} (SuppaSQL values), or {"sql":…,"link":…}.'),
3098
+ preview_document_id: z.number().int().positive().nullable().default(null),
3099
+ confirm: Confirm,
3100
+ },
3101
+ annotations: _MUT,
3102
+ }, async (a) => text(await registers.savePostingRule(a.register, a.recorder, a.source, a.key, a.definition_json, a.preview_document_id, a.confirm)));
3103
+ reg("suppa_read_register", {
3104
+ description: "Read a register: balance (at), turnovers / balance_and_turnovers (from, to, grain), movements, slice_last /\n" +
3105
+ "slice_first. Moments: 'now', YYYY-MM-DD (as at/to: its end) or an instant WITH offset. Sums are text;\n" +
3106
+ "meta.pending > 0: still queued. Page until nextCursor is null. SQL over reads: suppa_query virtual_tables_json.",
3107
+ inputSchema: {
3108
+ register: RegisterName,
3109
+ kind: z.enum(registers.READ_KINDS),
3110
+ at: z.string().nullable().default(null).describe("Absent = now; a slice: 'latest'."),
3111
+ from: z.string().nullable().default(null),
3112
+ to: z.string().nullable().default(null),
3113
+ group_by: z.array(z.string()).nullable().default(null).describe("Dimensions; null = all; [] = a total."),
3114
+ filter_json: z.string().nullable().default(null).describe('Dimensions: {"warehouse": [3, 4]}.'),
3115
+ conditions_json: z.string().nullable().default(null).describe("Or a conditions tree on dimensions."),
3116
+ grain: z.enum(registers.GRAINS).nullable().default(null),
3117
+ limit: z.number().int().min(1).max(registers.READ_MAX_LIMIT).default(100),
3118
+ cursor: z.string().nullable().default(null),
3119
+ },
3120
+ annotations: _READ,
3121
+ }, async (a) => text(await registers.readRegister({
3122
+ register: a.register,
3123
+ kind: a.kind,
3124
+ at: a.at,
3125
+ from: a.from,
3126
+ to: a.to,
3127
+ groupBy: a.group_by,
3128
+ filterJson: a.filter_json,
3129
+ conditionsJson: a.conditions_json,
3130
+ grain: a.grain,
3131
+ limit: a.limit,
3132
+ cursor: a.cursor,
3133
+ })));
3134
+ reg("suppa_register_document", {
3135
+ description: "A document's posting: record_id — state (posted, queued, held + reason, unposted), movements, violations, and\n" +
3136
+ "with preview=true what its rules give now; record_ids — the state of up to 1000 documents.",
3137
+ inputSchema: {
3138
+ entity: DocEntity,
3139
+ record_id: z.number().int().positive().nullable().default(null),
3140
+ record_ids: z.array(z.number().int().positive()).nullable().default(null),
3141
+ preview: z.boolean().default(false),
3142
+ },
3143
+ annotations: _READ,
3144
+ }, async (a) => text(await registers.registerDocument(a.entity, a.record_id, a.record_ids, a.preview)));
3145
+ reg("suppa_repost_documents", {
3146
+ description: "Repost: record_id — one document now (control applies to you); from_date ('all', a day) — history as a job,\n" +
3147
+ "after a rule change. The confirmation request carries the dry run. Never repost by flipping posted.\n" +
3148
+ "APPROVAL GATE: confirm=true reposts.",
3149
+ inputSchema: {
3150
+ entity: DocEntity,
3151
+ record_id: z.number().int().positive().nullable().default(null),
3152
+ from_date: z.string().nullable().default(null),
3153
+ rate: z.number().int().min(1).max(500).default(50).describe("Documents a second."),
3154
+ confirm: Confirm,
3155
+ },
3156
+ annotations: _MUT,
3157
+ }, async (a) => text(await registers.repostDocuments(a.entity, a.record_id, a.from_date, a.rate, a.confirm)));
3158
+ reg("suppa_register_status", {
3159
+ description: "Registers' status: no args — every register (pending, held, violations); register — its state, held\n" +
3160
+ "documents, open violations; job_id — a job (part: a sheet part / check examples).",
3161
+ inputSchema: {
3162
+ register: z.string().nullable().default(null),
3163
+ job_id: z.number().int().positive().nullable().default(null),
3164
+ part: z.number().int().min(0).nullable().default(null),
3165
+ },
3166
+ annotations: _READ,
3167
+ }, async (a) => text(await registers.registerStatus(a.register, a.job_id, a.part)));
3168
+ reg("suppa_operate_register", {
3169
+ description: "Operate a register: totals (suspend, resume, rebuild from_month, check), close_period (closed_until\n" +
3170
+ "YYYY-MM-DD, or 'none' to open all), release_held, resolve_violation, pause / resume / cancel a job.\n" +
3171
+ "suppa_registers_kb operations. APPROVAL GATE: confirm=true acts.",
3172
+ inputSchema: {
3173
+ action: z.enum(registers.OPERATE_ACTIONS),
3174
+ register: z.string().nullable().default(null),
3175
+ closed_until: z.string().nullable().default(null),
3176
+ from_month: z.string().nullable().default(null),
3177
+ repair: z.boolean().default(false),
3178
+ derivation: z.boolean().default(false),
3179
+ from_date: z.string().nullable().default(null),
3180
+ violation_id: z.number().int().positive().nullable().default(null),
3181
+ job_id: z.number().int().positive().nullable().default(null),
3182
+ confirm: Confirm,
3183
+ },
3184
+ annotations: _MUT,
3185
+ }, async (a) => text(await registers.operateRegister({
3186
+ action: a.action,
3187
+ register: a.register,
3188
+ closedUntil: a.closed_until,
3189
+ fromMonth: a.from_month,
3190
+ repair: a.repair,
3191
+ derivation: a.derivation,
3192
+ fromDate: a.from_date,
3193
+ violationId: a.violation_id,
3194
+ jobId: a.job_id,
3195
+ }, a.confirm)));
3046
3196
  return table;
3047
3197
  }
3048
3198
  /**
@@ -3206,6 +3356,40 @@ export function buildServer() {
3206
3356
  "the gate fails with E301 if anything is unregistered — run it, do not assume.\n" +
3207
3357
  "Porting from Suppa 1.0? Read the schema with suppa_read_v1_entity_props / suppa_read_v1_enum and map per references/v1-mapping.md — " +
3208
3358
  "never invent a mapping; record data stays with suppa_migrate_entities_from_v1.");
3359
+ regPrompt("build_register", {
3360
+ description: "Guided: a stock (accumulation) register from zero — register, document, posting rule, preview on a real document, repost of history",
3361
+ argsSchema: {
3362
+ register_purpose: z
3363
+ .string()
3364
+ .describe("What the register keeps, e.g. 'goods in warehouses by warehouse and SKU, quantity', and which documents move it."),
3365
+ },
3366
+ }, (a) => `Build a Suppa accumulation register from zero for: ${a.register_purpose}\n\n` +
3367
+ "Follow the bundled 'suppa-registers' skill (suppa_registers_kb; topic concepts and rules). Kinds, roles, the timezone " +
3368
+ "and the document option FREEZE once created — design first, write second.\n" +
3369
+ "1. Check: suppa_register_status() — registers exist on the tenant (a 400 register.disabled means the platform has " +
3370
+ "them off: stop and say so) and none already keeps this; suppa_list_entities for the document entities and their " +
3371
+ "tabular parts.\n" +
3372
+ "2. Design and show me, then WAIT for my approval: the register name (≤ 24 characters), kind accumulation with " +
3373
+ "accumulation_type balance (stock) or turnover (sales sums), the timezone (an IANA zone — ask me, never assume " +
3374
+ "it), the dimensions (what a balance is kept " +
3375
+ "by — a warehouse many-to-one, a SKU; ≤ 8), the resources (quantity numeric ≤ 6 decimals, amount), the attributes; " +
3376
+ "the documents that move it and, for each, receipt or expense per line (a transfer: one expense and one receipt).\n" +
3377
+ "3. Register: suppa_create_register(...) without confirm — show me what it will store (the option with its " +
3378
+ "defaults written out, the fields and their roles); confirm=true only after my approval: a register cannot be " +
3379
+ "removed.\n" +
3380
+ "4. Documents: for each document entity, suppa_update_entity_options(entity_name, options_json='{\"document\": true}') " +
3381
+ "— or {\"document\": {\"dateField\": …, \"postedField\": …}} to bind fields it has (show me the call first; it freezes). " +
3382
+ "Its lines are a tabular part (suppa_create_tabular_part) if they are not one already.\n" +
3383
+ "5. Rules: for each document, suppa_save_posting_rule WITHOUT confirm and WITH preview_document_id = a real document " +
3384
+ "of that entity (find one with suppa_search_records). Show me the movements the preview gives; fix the definition " +
3385
+ "until every dimension is filled and the kinds are right; only then confirm=true.\n" +
3386
+ "6. History: existing documents are NOT posted by a new rule. suppa_repost_documents(entity, from_date='all') " +
3387
+ "without confirm — show me the dry run (documents, changed, refused); start the job only after my approval, and " +
3388
+ "follow it with suppa_register_status(job_id).\n" +
3389
+ "7. Verify: suppa_read_register(register, kind='balance', group_by=[…]) — meta.pending 0 means the queue is done; " +
3390
+ "suppa_register_status(register) for held documents and violations.\n" +
3391
+ "8. Tell me: balance control is OFF until an operator puts resources into RegisterSettings.controlResources " +
3392
+ "(suppa_update_record on RegisterSettings, a list that is REPLACED); offer to do it, do not do it unasked.");
3209
3393
  // Every tools/list goes out without the schema boilerplate no model reads —
3210
3394
  // see toolsListEconomy.ts. Installed last so it wraps the SDK's own handler.
3211
3395
  installToolsListEconomy(server);
package/dist/toolTable.js CHANGED
@@ -13,6 +13,8 @@ export const PROFILES = {
13
13
  forms: ["create_form", "get_form", "list_forms", "update_form", "add_field_to_form", "generate_form_schema", "list_form_field_types", "form_kb", "validate_form_schema",
14
14
  "write_form_draft", "create_form_v2", "form_versions", "form_lifecycle", "form_code", "push_form_code"],
15
15
  automation: ["create_automation", "get_automation", "update_automation", "delete_automation", "list_automations", "publish_automation", "unpublish_automation", "list_automation_runs", "get_automation_run", "get_automation_node_schema", "list_automation_node_types"],
16
+ // 1C-style accumulation / information registers: the knowledge, the register and its rules, reads, operations.
17
+ registers: ["registers_kb", "create_register", "save_posting_rule", "read_register", "register_document", "repost_documents", "register_status", "operate_register"],
16
18
  };
17
19
  const BY_NAME = new Map();
18
20
  for (const [profile, tools] of Object.entries(PROFILES)) {
@@ -254,6 +254,12 @@ export const HIERARCHY_DEPTH_LIMIT_MAX = 20;
254
254
  /** The two object-valued options (entity-metadata-schema.type.ts:18-51). */
255
255
  export const ENTITY_OPTION_COMMENTS_PRIVACY = "commentsPrivacy";
256
256
  export const ENTITY_OPTION_EXTERNAL_SOURCE = "externalSource";
257
+ /**
258
+ * The registers' document option (documents: architecture/entity-builder/registers.md "Documents"):
259
+ * `true` binds the platform fields `date` and `posted`, or `{ dateField, postedField }` binds fields
260
+ * the entity already has. Frozen once set — the platform refuses removing or rebinding it.
261
+ */
262
+ export const ENTITY_OPTION_DOCUMENT = "document";
257
263
  /** The two mode options, both `"single" | "multi"`. */
258
264
  export const ENTITY_OPTION_MODE_KEYS = [
259
265
  "hierarchy", // builder.txt:78 — "Hierarchy mode."
@@ -289,6 +295,7 @@ export const ENTITY_OPTION_KEYS = [
289
295
  ENTITY_OPTION_DEPTH_LIMIT,
290
296
  ENTITY_OPTION_COMMENTS_PRIVACY,
291
297
  ENTITY_OPTION_EXTERNAL_SOURCE,
298
+ ENTITY_OPTION_DOCUMENT,
292
299
  ];
293
300
  /**
294
301
  * On an entity the tenant does not own — initiator "system" or "application" — the options a
@@ -419,6 +426,17 @@ export function normalizeEntityOptions(raw, param = "options_json") {
419
426
  `(entity-metadata-schema.type.ts:49-51), got ${JSON.stringify(value)}.`);
420
427
  }
421
428
  }
429
+ else if (key === ENTITY_OPTION_DOCUMENT) {
430
+ const bound = isPlainObject(value) ? value : null;
431
+ // {} is true spelled as an object: both platform fields (document-option.util.ts normalizeDocumentOption).
432
+ const okBound = bound !== null &&
433
+ Object.entries(bound).every(([k, v]) => (k === "dateField" || k === "postedField") && typeof v === "string" && v.trim() !== "");
434
+ if (value !== true && !okBound) {
435
+ throw new Error(`Parameter '${param}': 'document' must be true (the platform fields date and posted) or ` +
436
+ '{"dateField": "<timestamp field>", "postedField": "<boolean field>"} binding fields the ' +
437
+ `entity already has; it cannot be turned off (registers.md "Documents"), got ${JSON.stringify(value)}.`);
438
+ }
439
+ }
422
440
  else if (key === ENTITY_OPTION_BROWSING_HISTORY) {
423
441
  const ok = typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
424
442
  if (!ok) {
@@ -627,7 +645,7 @@ export function toMultiLang(title, languages) {
627
645
  return out;
628
646
  }
629
647
  /** Resolve the tenant languages and expand `title` (falling back to `fallbackName`). */
630
- async function _expandTitle(title, fallbackName) {
648
+ export async function _expandTitle(title, fallbackName) {
631
649
  const langs = await resolvePlatformLanguages();
632
650
  const base = isPlainObject(title) ? title : (title || fallbackName);
633
651
  return toMultiLang(base, langs);
@@ -1705,7 +1723,7 @@ export async function updateEntityOptions(entityName, options) {
1705
1723
  * the corresponding check rather than blocking a legitimate write (mirrors
1706
1724
  * `_refShapeProblems`). Returns a refusal JSON string, or the resolved target.
1707
1725
  */
1708
- async function _relationPreflight(entityName, fieldName, relationType, relationEntity) {
1726
+ async function _relationPreflight(entityName, fieldName, relationType, relationEntity, entityIsNew = false) {
1709
1727
  // 1. Target existence (+ case correction).
1710
1728
  let listing;
1711
1729
  try {
@@ -1742,7 +1760,9 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
1742
1760
  }
1743
1761
  }
1744
1762
  }
1745
- // 2. The field must not already exist on this entity.
1763
+ // 2. The field must not already exist on this entity — nothing to read on one being created.
1764
+ if (entityIsNew)
1765
+ return { relationEntity };
1746
1766
  let schema;
1747
1767
  try {
1748
1768
  schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
@@ -1808,7 +1828,7 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1808
1828
  if (echo) {
1809
1829
  return refuse({ error: echo });
1810
1830
  }
1811
- 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;
1831
+ 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, entityIsNew = false, } = opts;
1812
1832
  // The platform has no relation type literally called "relation"; a foreign
1813
1833
  // key is "many-to-one" with the target entity in `relationTarget`. That alias
1814
1834
  // is the ONLY rewrite: relation_entity used to turn ANY type into many-to-one
@@ -1927,7 +1947,7 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1927
1947
  // case-only target-name mismatch.
1928
1948
  let relTarget = relationEntity;
1929
1949
  if (RELATION_FIELD_TYPES.includes(resolvedType) && relTarget) {
1930
- const pf = await _relationPreflight(entityName, fieldName, resolvedType, relTarget);
1950
+ const pf = await _relationPreflight(entityName, fieldName, resolvedType, relTarget, entityIsNew);
1931
1951
  if (pf.error) {
1932
1952
  return { error: pf.error };
1933
1953
  }
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { makeRequest } from "../httpClient.js";
20
20
  import { jsonResponse } from "../utils.js";
21
+ import { queryRegisters, registerRefusal } from "./registers.js";
21
22
  export const QUERY_DEFAULT_LIMIT = 50;
22
23
  export const QUERY_MAX_LIMIT = 500;
23
24
  /** Characters of `rows` in one answer. Past it rows are dropped from the end, and the answer says so. */
@@ -291,7 +292,7 @@ function rowsOf(answer) {
291
292
  }
292
293
  return null;
293
294
  }
294
- export async function runQuery(query, bindParamsJson = null, limit = QUERY_DEFAULT_LIMIT) {
295
+ export async function runQuery(query, bindParamsJson = null, limit = QUERY_DEFAULT_LIMIT, virtualTablesJson = null) {
295
296
  const prepared = prepareQuery(query, limit);
296
297
  if ("error" in prepared)
297
298
  return jsonResponse({ error: prepared.error });
@@ -311,14 +312,38 @@ export async function runQuery(query, bindParamsJson = null, limit = QUERY_DEFAU
311
312
  }
312
313
  bindParams = parsed;
313
314
  }
315
+ // Register virtual tables (documents: api/entity-builder/registers.md "Virtual Tables"): each alias
316
+ // is a register read that becomes a CTE in front of the statement, at /core/registers/query.
317
+ let virtualTables;
318
+ if (virtualTablesJson !== null && virtualTablesJson !== undefined && String(virtualTablesJson).trim()) {
319
+ let parsed;
320
+ try {
321
+ parsed = JSON.parse(String(virtualTablesJson));
322
+ }
323
+ catch (e) {
324
+ return jsonResponse({ error: `virtual_tables_json is not valid JSON (${e instanceof Error ? e.message : e}). ${NOTHING_SENT}` });
325
+ }
326
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.keys(parsed).length) {
327
+ return jsonResponse({
328
+ error: 'virtual_tables_json must be an object of aliases, e.g. {"b": {"register": "Stock", "kind": "balance", "groupBy": ["sku"]}} — ' +
329
+ `suppa_registers_kb(topic='reads'). ${NOTHING_SENT}`,
330
+ });
331
+ }
332
+ virtualTables = parsed;
333
+ }
314
334
  let answer;
315
335
  try {
316
- answer = await makeRequest("POST", "/api/core/data/query", {
317
- query: prepared.text,
318
- ...(bindParams ? { bindParams } : {}),
319
- });
336
+ answer = virtualTables
337
+ ? await queryRegisters(prepared.text, virtualTables, bindParams)
338
+ : await makeRequest("POST", "/api/core/data/query", {
339
+ query: prepared.text,
340
+ ...(bindParams ? { bindParams } : {}),
341
+ });
320
342
  }
321
343
  catch (e) {
344
+ const refusal = virtualTables ? registerRefusal(e) : null;
345
+ if (refusal)
346
+ return jsonResponse({ ...refusal, query_sent: prepared.text });
322
347
  return jsonResponse({
323
348
  error: e instanceof Error ? e.message : String(e),
324
349
  query_sent: prepared.text,
@@ -352,6 +377,9 @@ export async function runQuery(query, bindParamsJson = null, limit = QUERY_DEFAU
352
377
  `Rows cut from ${before} to ${rows.length} to stay within the ${QUERY_ROWS_BUDGET.toLocaleString("en-US")}-character ` +
353
378
  "answer budget. Select fewer or narrower columns to see more.";
354
379
  }
380
+ if (virtualTables && answer && typeof answer === "object" && !Array.isArray(answer) && "meta" in answer) {
381
+ out.meta = answer.meta;
382
+ }
355
383
  if (prepared.changed)
356
384
  out.query_sent = prepared.text;
357
385
  if (prepared.limitNote)