@simetrajs/designer 0.2.0 → 0.3.0-next.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.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { a as invoke, c as summarizeData, d as writeChanges, f as checkEnvName, h as databaseResource, i as renderPlan, m as parseDataLaunch, n as renderApply, p as dataResource, r as renderDiff, s as toolByName, t as formatDiagnostics, u as isMetadataFile } from "./report-DV4deFdu.js";
2
+ import { a as toolByName, c as writeChanges, d as parseDataLaunch, f as databaseResource, i as structureOf, l as checkEnvName, o as formatDiagnostics, r as presentation, s as isMetadataFile, t as invoke, u as dataResource } from "./invoke-BwP_5iN6.js";
3
3
  import { i as DEFAULT_DATABASE_URL_ENV, n as trimSlash, p as UsageError, t as DEFAULT_DIR } from "./default-dir-DerxTbci.js";
4
4
  import { defineCommand } from "citty";
5
5
  import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
7
  import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, METADATA_KINDS } from "simetra/model";
8
8
  import { DEFAULT_APPLY_TIMEOUTS, renderDesiredState } from "simetra/schema";
9
- import { buildRuntimeCatalog, canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
9
+ import { buildClientCatalog, buildRuntimeCatalog, canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
10
10
  import { spawn } from "node:child_process";
11
11
  import { tmpdir } from "node:os";
12
12
  // src/tools/artifacts.ts
@@ -15,6 +15,7 @@ import { tmpdir } from "node:os";
15
15
  * адаптер (`compile --out`), тут лише вміст.
16
16
  */
17
17
  function compileArtifacts(model) {
18
+ const runtime = buildRuntimeCatalog(model);
18
19
  return [
19
20
  {
20
21
  path: "snapshot.json",
@@ -30,7 +31,11 @@ function compileArtifacts(model) {
30
31
  },
31
32
  {
32
33
  path: "runtime-catalog.json",
33
- content: `${JSON.stringify(buildRuntimeCatalog(model), null, 2)}\n`
34
+ content: `${JSON.stringify(runtime, null, 2)}\n`
35
+ },
36
+ {
37
+ path: "client-catalog.json",
38
+ content: `${JSON.stringify(buildClientCatalog(runtime), null, 2)}\n`
34
39
  }
35
40
  ];
36
41
  }
@@ -246,12 +251,17 @@ async function cliInput(tool, args, stdin) {
246
251
  if (tool.name === "explain") {
247
252
  const target = positional[0] ?? "";
248
253
  const dot = target.indexOf(".");
249
- if (dot <= 0 || dot === target.length - 1) throw new UsageError(`Invalid target "${target}". Expected <Kind>.<Name>, e.g. Document.ServiceAccrual (kinds: ${METADATA_KINDS.join(", ")}).`);
254
+ if (dot <= 0 || dot === target.length - 1) throw new UsageError(`Invalid target "${target}". Expected <Kind>.<Name>, e.g. Document.ServiceAccrual (kinds: ${METADATA_KINDS.join(", ")}), or <schema>.<function>, e.g. public.post_order.`);
255
+ const head = target.slice(0, dot);
256
+ const tail = target.slice(dot + 1);
250
257
  return {
251
- input: {
252
- kind: target.slice(0, dot),
253
- name: target.slice(dot + 1)
254
- },
258
+ input: METADATA_KINDS.includes(head) ? {
259
+ kind: head,
260
+ name: tail
261
+ } : { function: {
262
+ schema: head,
263
+ name: tail
264
+ } },
255
265
  dirs: [trimSlash(positional[1] ?? "./metadata")]
256
266
  };
257
267
  }
@@ -318,135 +328,44 @@ async function cliInput(tool, args, stdin) {
318
328
  };
319
329
  }
320
330
  // src/cli/render.ts
321
- /** Текст пояснення об'єкта для терміналу; JSON-вигляд друкується як є. */
322
- function renderExplanation(e) {
323
- const lines = [`${e.object.kind} ${e.object.name} (${e.object.file})`];
324
- if (e.object.scopeKind !== void 0) lines.push(`scope: ${e.object.scopeKind}`);
325
- for (const t of e.tables) {
326
- lines.push("", `table ${t.schema}.${t.name}${t.part ? ` [${t.part}]` : ""}`);
327
- for (const c of t.columns) {
328
- const tags = [
329
- c.notNull ? "not null" : void 0,
330
- c.logical === void 0 ? void 0 : `logical: ${c.logical}`,
331
- c.standard === void 0 ? void 0 : `standard: ${c.standard}`,
332
- c.scope === true ? "scope" : void 0
333
- ].filter((x) => x !== void 0);
334
- lines.push(` ${c.name} ${c.type}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`);
335
- }
336
- if (t.primaryKey !== void 0) lines.push(` primary key (${t.primaryKey.join(", ")})`);
337
- for (const u of t.uniques) lines.push(` unique (${u.join(", ")})`);
338
- for (const f of t.foreignKeys) lines.push(` foreign key (${f.columns.join(", ")}) -> ${f.references}`);
339
- }
340
- for (const q of e.movementQueries) lines.push("", `movement query ${q.identity}`, q.sql);
341
- for (const u of e.generatedUnits) lines.push("", `generated ${u.identity}`, u.sql);
342
- if (e.contracts.length > 0) lines.push("", "contracts:", JSON.stringify(e.contracts, null, 2));
343
- if (e.referencedBy.length > 0) {
344
- lines.push("", "referenced by:");
345
- for (const r of e.referencedBy) lines.push(` ${r.file}#${r.pointer} (${r.role})`);
346
- }
347
- return `${lines.join("\n")}\n`;
348
- }
349
- /**
350
- * Підсумок запису промоції для терміналу: що на що перетворилось і що
351
- * лишається плану бази. Повний запис — у `--format json`.
352
- */
353
- function renderPromotion(r, written) {
354
- const lines = [`${written ? "promoted" : "would promote"} ${r.objectId} into ${r.kind}`];
355
- for (const t of r.tables) lines.push(` table ${t.schema}.${t.from} -> ${t.to}`);
356
- const counts = [
357
- ["columns renamed or moved", r.columns.length],
358
- ["type changes", r.typeChanges.length],
359
- ["data steps", r.dataSteps.length],
360
- ["columns retired", r.retired.length],
361
- ["constraints relaxed", r.relaxed.length],
362
- ["constraints tightened", r.tightened.length],
363
- ["row level security changes", r.rowLevelSecurity.length],
364
- ["delete semantics changes", r.deleteSemantics.length],
365
- ["conversions", r.conversions.length],
366
- ["units moved", r.movedUnits.length],
367
- ["units rewritten", r.rewrittenUnits.length],
368
- ["contract changes", r.contractChanges.length]
369
- ];
370
- for (const [label, n] of counts) if (n > 0) lines.push(` ${label}: ${n}`);
371
- return lines.join("\n");
372
- }
373
331
  /** Кінцевий результат одного виклику в тексті/JSON для терміналу. */
374
332
  function renderResult(tool, r, o) {
375
333
  const report = formatDiagnostics(r.diagnostics, o);
376
- if (tool.name === "compile") return o.format === "json" ? {
334
+ const present = tool.present;
335
+ if (present?.diagnosticsOnly === true) return o.format === "json" ? {
377
336
  stdout: "",
378
337
  json: JSON.parse(report)
379
338
  } : { stdout: report };
380
- if (tool.name === "explain" && r.ok && r.data !== void 0) {
381
- const explanation = r.data;
382
- return { stdout: o.format === "json" ? JSON.stringify(explanation, null, 2) : renderExplanation(explanation).trimEnd() };
383
- }
384
- if (tool.name === "diff" && r.data !== void 0) {
385
- const data = r.data;
386
- return { stdout: o.format === "json" ? JSON.stringify({
387
- ok: r.ok,
388
- empty: data.empty,
389
- plan: data.plan,
390
- differences: data.differences,
391
- diagnostics: JSON.parse(report)
392
- }, null, 2) : renderDiff(data, report) };
393
- }
394
- if (tool.name === "plan" || tool.name === "apply") {
395
- if (o.format === "json") return { stdout: JSON.stringify({
396
- ok: r.ok,
397
- written: r.written,
398
- artifacts: r.artifacts ?? [],
399
- ...r.data,
400
- diagnostics: JSON.parse(report)
401
- }, null, 2) };
402
- return { stdout: tool.name === "plan" ? renderPlan(r.data, report, {
403
- ok: r.ok,
404
- written: r.written
405
- }) : renderApply(r.data, r.diagnostics, report) };
406
- }
407
- if (tool.name === "roles" && r.data !== void 0) {
408
- const { roles, skipped } = r.data;
409
- return { stdout: o.format === "json" ? JSON.stringify({
410
- ok: r.ok,
411
- roles,
412
- skipped,
413
- diagnostics: JSON.parse(report)
414
- }, null, 2) : [
415
- ...roles.map((x) => `${x.server}: ${x.name} ${x.outcome}`),
416
- ...skipped.map((x) => `target: ${x.name} skipped: the directory has no project.meta.json, so database.provider is unknown; run roles in a metadata directory with a project file to create it`),
417
- ...r.diagnostics.length > 0 ? [report] : []
418
- ].join("\n") };
419
- }
420
- if (tool.name === "rights-maintenance" && r.data !== void 0) {
421
- const done = r.data;
422
- return { stdout: o.format === "json" ? JSON.stringify({
423
- ok: r.ok,
424
- ...done,
425
- diagnostics: JSON.parse(report)
426
- }, null, 2) : `assigned ${done.assignment}${done.member === void 0 ? "" : ` to member ${done.member}`}` };
427
- }
428
- if ((tool.name === "data-read" || tool.name === "data-command") && r.data !== void 0) {
429
- const data = r.data;
430
- return { stdout: o.format === "json" ? JSON.stringify({
431
- ok: r.ok,
432
- ...data
433
- }, null, 2) : summarizeData(tool.name, data) };
339
+ const view = {
340
+ channel: "cli",
341
+ ok: r.ok,
342
+ written: r.written,
343
+ diagnostics: r.diagnostics,
344
+ report
345
+ };
346
+ const { shown: shows, data } = presentation(tool, r);
347
+ if (shows && present?.bare === true && o.format === "json") return { stdout: JSON.stringify(r.data, null, 2) };
348
+ if (shows && o.format === "text") {
349
+ const text = present?.text?.(r.data, view);
350
+ if (text !== void 0) return { stdout: text };
434
351
  }
435
- if (tool.files === "read") return { stdout: report };
352
+ if (!shows && tool.files === "read") return { stdout: report };
436
353
  const changed = r.changes.map((c) => c.path);
437
354
  if (o.format === "json") return { stdout: JSON.stringify({
438
355
  ok: r.ok,
439
356
  written: r.written,
357
+ ...r.wouldWrite === true ? { wouldWrite: true } : {},
440
358
  changed,
441
- diagnostics: JSON.parse(report),
442
- ...tool.name === "promote" && r.data !== void 0 ? { record: r.data } : {}
359
+ ...tool.files === "artifact" ? { artifacts: r.artifacts ?? [] } : {},
360
+ ...data !== void 0 ? structureOf(tool, data) : {},
361
+ diagnostics: JSON.parse(report)
443
362
  }, null, 2) };
444
363
  const verb = (deleted) => r.written ? deleted ? "deleted" : "written" : deleted ? "would delete" : "would write";
445
364
  return { stdout: [
446
365
  ...r.changes.map((c) => `${verb(c.deleted)} ${o.dir}/${c.path}`),
447
- ...r.ok ? [] : ["nothing written: the result has errors"],
366
+ ...r.ok ? [] : r.written ? ["written: the result keeps only repair-class errors the directory already had"] : r.wouldWrite === true ? ["would write: the result keeps only repair-class errors the directory already had"] : ["nothing written: the result has errors"],
448
367
  report,
449
- ...tool.name === "promote" && r.data !== void 0 ? [renderPromotion(r.data, r.written)] : []
368
+ ...data !== void 0 && present?.appendix !== void 0 ? [present.appendix(data, view)] : []
450
369
  ].join("\n") };
451
370
  }
452
371
  // src/cli/command.ts
@@ -594,12 +513,12 @@ function argsFor(tool) {
594
513
  };
595
514
  args.out = {
596
515
  type: "string",
597
- description: "Write snapshot.json, desired-state.sql, entities.d.ts, runtime-catalog.json here"
516
+ description: "Write snapshot.json, desired-state.sql, entities.d.ts, runtime-catalog.json, client-catalog.json here"
598
517
  };
599
518
  } else if (tool.name === "explain") {
600
519
  args.target = {
601
520
  type: "positional",
602
- description: "<Kind>.<Name>, e.g. Document.ServiceAccrual",
521
+ description: "<Kind>.<Name>, e.g. Document.ServiceAccrual, or <schema>.<function>, e.g. public.post_order (a schema named like a kind, or containing a dot, needs the JSON input of MCP)",
603
522
  required: true
604
523
  };
605
524
  args.dir = {
@@ -655,7 +574,7 @@ function argsFor(tool) {
655
574
  args["database-provider"] = {
656
575
  type: "enum",
657
576
  options: [...DATABASE_PROVIDERS],
658
- description: "Database provider of a new project (default \"supabase\")"
577
+ description: "Database provider of a new project: supabase | postgres (default \"supabase\")"
659
578
  };
660
579
  }
661
580
  if (tool.name === "diff") args.tables = {
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // src/schema-engine/errors.ts
3
+ /** Тінь на сервері іншої мажорної версії: каталоги двох версій не порівнюються. */
4
+ var ShadowServerMismatchError = class extends Error {
5
+ name = "ShadowServerMismatchError";
6
+ };
7
+ /** Роль підключення не має `CREATEDB` на сервері, де мала б з'явитися тінь. */
8
+ var ShadowCreateRefusedError = class extends Error {
9
+ onShadowBase;
10
+ name = "ShadowCreateRefusedError";
11
+ constructor(onShadowBase) {
12
+ super("the connecting role lacks CREATEDB");
13
+ this.onShadowBase = onShadowBase;
14
+ }
15
+ };
16
+ /**
17
+ * Збій створення тіні чи підключення до неї з причиною, якої адаптер не
18
+ * розпізнав: причина — у `cause`. Межа описує її адресою сервера, де мала
19
+ * з'явитися тінь, і називає вимогу тіні до режиму з'єднання (спека designer
20
+ * §3.2).
21
+ */
22
+ var ShadowServerError = class extends Error {
23
+ onShadowBase;
24
+ shadowDrop;
25
+ name = "ShadowServerError";
26
+ constructor(cause, onShadowBase, shadowDrop) {
27
+ super("the shadow could not be created or reached", { cause });
28
+ this.onShadowBase = onShadowBase;
29
+ this.shadowDrop = shadowDrop;
30
+ }
31
+ };
32
+ /**
33
+ * Збій видалення тіні на шляху винятку: виняток лишається тим самим (його
34
+ * клас розпізнає межа), а попередження `engine.shadow-drop-failed` стає його
35
+ * полем `shadowDrop`. Значення, що не є `Error`, поля не несе.
36
+ */
37
+ function withShadowDrop(error, drop) {
38
+ if (error instanceof Error) Object.assign(error, { shadowDrop: drop });
39
+ return error;
40
+ }
41
+ /** Попередження про невидалену тінь, яке несе виняток, якщо несе. */
42
+ function shadowDropOf(error) {
43
+ if (!(error instanceof Error)) return void 0;
44
+ return error.shadowDrop;
45
+ }
46
+ /** Шаблон тіні профілю відсутній або не запечатаний суперкористувачем: його готує `simetra roles`. */
47
+ var ShadowTemplateMissingError = class extends Error {
48
+ template;
49
+ name = "ShadowTemplateMissingError";
50
+ constructor(template) {
51
+ super(`the shadow template database "${template}" is missing or not sealed`);
52
+ this.template = template;
53
+ }
54
+ };
55
+ /** Профіль `postgres` будує тіні з шаблону кластера цілі й окремого сервера тіней не має. */
56
+ var ShadowBaseUnsupportedError = class extends Error {
57
+ name = "ShadowBaseUnsupportedError";
58
+ constructor() {
59
+ super("a separate shadow server is not supported with the postgres profile");
60
+ }
61
+ };
62
+ export { ShadowTemplateMissingError as a, ShadowServerMismatchError as i, ShadowCreateRefusedError as n, shadowDropOf as o, ShadowServerError as r, withShadowDrop as s, ShadowBaseUnsupportedError as t };