@simetrajs/designer 0.3.0-next.10 → 0.3.0-next.12

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,15 @@
1
1
  #!/usr/bin/env node
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-B6ljdX5t.js";
3
- import { i as DEFAULT_DATABASE_URL_ENV, n as trimSlash, p as UsageError, t as DEFAULT_DIR } from "./default-dir-DerxTbci.js";
2
+ import { a as toolByName, c as dataResource, i as structureOf, l as parseDataLaunch, o as formatDiagnostics, r as presentation, s as checkEnvName, t as invoke, u as databaseResource } from "./invoke-8HeorF7f.js";
3
+ import { r as writeChanges, t as isMetadataFile } from "./metadata-dir-DCZ_sYGI.js";
4
+ import { t as UsageError } from "./usage-error-BGPr8yRj.js";
5
+ import { n as DEFAULT_DATABASE_URL_ENV } from "./hints-C6wx_Gi6.js";
6
+ import { n as trimSlash, t as DEFAULT_DIR } from "./default-dir-DZz6mxP1.js";
4
7
  import { defineCommand } from "citty";
5
- import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
6
- import { basename, dirname, join, resolve } from "node:path";
7
- import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, METADATA_KINDS } from "simetra/model";
8
8
  import { DEFAULT_APPLY_TIMEOUTS, renderDesiredState } from "simetra/schema";
9
+ import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, METADATA_KINDS } from "simetra/model";
9
10
  import { buildClientCatalog, buildRuntimeCatalog, canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
11
+ import { basename, dirname, join, resolve } from "node:path";
12
+ import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
10
13
  import { spawn } from "node:child_process";
11
14
  import { tmpdir } from "node:os";
12
15
  // src/tools/artifacts.ts
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import { t as UsageError } from "./usage-error-BGPr8yRj.js";
3
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
4
+ import { existsSync } from "node:fs";
5
+ // src/io/package-path.ts
6
+ /**
7
+ * Тека встановленого пакета: перший предок `fromDir` (включно) з
8
+ * `node_modules/<pkg>/package.json`. Шлях навмисно не проходить `realpath`:
9
+ * pnpm робить `node_modules/<pkg>` симлінком у сховище, а значення, що потрапляє
10
+ * у файли метаданих, мусить бути однаковим на кожній машині й переживати
11
+ * перенос репо.
12
+ */
13
+ function installedPackageDir(fromDir, pkg) {
14
+ const start = resolve(fromDir);
15
+ let current = start;
16
+ for (;;) {
17
+ const candidate = join(current, "node_modules", pkg);
18
+ if (existsSync(join(candidate, "package.json"))) return candidate;
19
+ const parent = dirname(current);
20
+ if (parent === current) throw new UsageError(`${pkg} is not installed in node_modules above ${start}`);
21
+ current = parent;
22
+ }
23
+ }
24
+ /**
25
+ * Відносний шлях із роздільниками `/`: він потрапляє у файли, які комітять і
26
+ * читають на будь-якій ОС (`$schema`, ціль лінка скіла, шлях до бінарника в
27
+ * MCP-конфігу), тож форма не може залежати від машини, де його пораховано.
28
+ */
29
+ function posixRelative(fromDir, to) {
30
+ return relative(fromDir, to).split(sep).join(posix.sep);
31
+ }
32
+ // src/io/default-dir.ts
33
+ /** Тека метаданих за замовчуванням — спільна для CLI і `simetra mcp`. */
34
+ const DEFAULT_DIR = "./metadata";
35
+ const trimSlash = (d) => d.replace(/(?<=.)[\\/]+$/, "");
36
+ export { posixRelative as i, trimSlash as n, installedPackageDir as r, DEFAULT_DIR as t };
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import { n as DEFAULT_DATABASE_URL_ENV } from "./hints-C6wx_Gi6.js";
3
+ import { a as TestingError, n as assertLocalHost, t as assertDevelopmentDatabase } from "./development-BbRCYFA3.js";
4
+ import { defineCommand } from "citty";
5
+ import pg from "pg";
6
+ // src/commands/dev-check.ts
7
+ var dev_check_default = defineCommand({
8
+ meta: {
9
+ name: "dev-check",
10
+ description: `Refuse unless ${DEFAULT_DATABASE_URL_ENV} points at a development database on this machine (loopback or a unix socket, and the database-level setting simetra.environment = 'development')`
11
+ },
12
+ args: { "host-only": {
13
+ type: "boolean",
14
+ description: "Check only the host, without connecting (the flag is not set yet)"
15
+ } },
16
+ async run({ args }) {
17
+ const result = await runDevCheck({ hostOnly: args["host-only"] === true }, process.env);
18
+ process.stdout.write(result.stdout);
19
+ process.stderr.write(result.stderr);
20
+ process.exitCode = result.exitCode;
21
+ }
22
+ });
23
+ /**
24
+ * Не викликає `process.exit`: тести проганяють команду в процесі. Відмова —
25
+ * код 1 і код `testing.*` у stderr; рядок підключення в текст не потрапляє.
26
+ */
27
+ async function runDevCheck(o, env) {
28
+ const fail = (exitCode, line) => ({
29
+ exitCode,
30
+ stdout: "",
31
+ stderr: `simetra dev-check: ${line}\n`
32
+ });
33
+ const dsn = env[DEFAULT_DATABASE_URL_ENV];
34
+ if (dsn === void 0 || dsn === "") return fail(2, `${DEFAULT_DATABASE_URL_ENV} is not set`);
35
+ try {
36
+ assertLocalHost(dsn);
37
+ if (!o.hostOnly) {
38
+ const client = new pg.Client({ connectionString: dsn });
39
+ client.on("error", () => {});
40
+ try {
41
+ await client.connect();
42
+ await assertDevelopmentDatabase(client);
43
+ } finally {
44
+ await client.end().catch(() => {});
45
+ }
46
+ }
47
+ } catch (error) {
48
+ if (error instanceof TestingError) return fail(1, `${error.code}: ${error.message}`);
49
+ return fail(1, `cannot check the database: ${error instanceof Error ? error.message : String(error)}`);
50
+ }
51
+ return {
52
+ exitCode: 0,
53
+ stdout: o.hostOnly ? "The database host is on this machine.\n" : "The database is a development database on this machine.\n",
54
+ stderr: ""
55
+ };
56
+ }
57
+ export { dev_check_default as default };
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import pg from "pg";
3
+ import { DEVELOPMENT_DATABASE_SQL } from "simetra/schema";
4
+ // src/testing/errors.ts
5
+ /**
6
+ * Error thrown by the `@simetrajs/designer/testing` entry. `code` is a stable
7
+ * `testing.*` identifier to branch on; the message is for humans.
8
+ */
9
+ var TestingError = class extends Error {
10
+ code;
11
+ constructor(code, message) {
12
+ super(message);
13
+ this.name = "TestingError";
14
+ this.code = code;
15
+ }
16
+ };
17
+ // src/testing/development.ts
18
+ const IPV4_LOOPBACK = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
19
+ /**
20
+ * Хост, який візьме `pg`, — машина розробника: `localhost`, петля IPv4
21
+ * `127.0.0.0/8`, `::1` чи шлях unix-сокета. DNS не розв'язується: ім'я, що
22
+ * лише вказує на петлю, — уже не «ця машина» за формою рядка.
23
+ */
24
+ function isLocalHost(host) {
25
+ if (host === void 0 || host === "") return false;
26
+ if (host.startsWith("/")) return true;
27
+ const h = host.toLowerCase();
28
+ if (h === "localhost" || h === "::1") return true;
29
+ const m = IPV4_LOOPBACK.exec(h);
30
+ return m !== null && m.slice(1).every((octet) => Number(octet) <= 255);
31
+ }
32
+ const notLocal = () => new TestingError("testing.not-local", "Refused: the database host is not loopback or a unix socket; only a development database on this machine is allowed. Nothing changed.");
33
+ /**
34
+ * Refuses a connection string whose host is not this machine (loopback or a
35
+ * unix socket), before any connection is opened. The host is the one `pg`
36
+ * would use (a `host` query parameter, a repeated one, `PGHOST`). Throws
37
+ * {@link TestingError} `testing.not-local`; an unparsable string is refused
38
+ * the same way, without quoting it.
39
+ */
40
+ function assertLocalHost(dsn) {
41
+ let host;
42
+ try {
43
+ host = new pg.Client({ connectionString: dsn }).host;
44
+ } catch {
45
+ throw notLocal();
46
+ }
47
+ if (!isLocalHost(host)) throw notLocal();
48
+ }
49
+ function assertFlagged(row) {
50
+ if (row?.development !== true) throw new TestingError("testing.not-development", "Refused: the database does not carry the database-level flag simetra.environment = 'development' (ALTER DATABASE … SET by a superuser of the development database). Nothing changed.");
51
+ }
52
+ /**
53
+ * Refuses unless `client` is connected to this machine and the database
54
+ * carries the database-level flag `simetra.environment = 'development'`. The
55
+ * flag is read from the catalog on the same connection, so a session option
56
+ * (`options=-c …`) or a role setting does not pass. Without `database` the
57
+ * current database of the connection is checked; with it, the named database
58
+ * of the same cluster (for a database one cannot connect to, such as a
59
+ * template). Throws {@link TestingError} `testing.not-local` before any query,
60
+ * or `testing.not-development`.
61
+ */
62
+ async function assertDevelopmentDatabase(client, options = {}) {
63
+ if (!isLocalHost(client.host)) throw notLocal();
64
+ const { rows } = await client.query(DEVELOPMENT_DATABASE_SQL, [options.database ?? null]);
65
+ assertFlagged(rows[0]);
66
+ }
67
+ /**
68
+ * Порт apply, що пише лише в базу розробника. Рушій apply і
69
+ * `runRightsMaintenance` відкривають власні з'єднання, тож перевірка — на
70
+ * `tx` тієї самої транзакції, першим запитом, і лише тоді тіло. Хост — до
71
+ * з'єднання. `statement` відмовляє: це DDL кластера поза транзакцією, і
72
+ * перевірити ознаку на тому самому з'єднанні він не дає; писач плану й
73
+ * обслуговування прав ним не користуються.
74
+ */
75
+ function developmentApplyDatabase(inner) {
76
+ return {
77
+ async transaction(db, end, fn) {
78
+ assertLocalHost(db.url);
79
+ return inner.transaction(db, end, async (tx) => {
80
+ assertFlagged((await tx.query(DEVELOPMENT_DATABASE_SQL, [null]))[0]);
81
+ return fn(tx);
82
+ });
83
+ },
84
+ statement() {
85
+ return Promise.reject(/* @__PURE__ */ new Error("The development apply port runs transactions only; a statement outside a transaction cannot be checked on its own connection."));
86
+ }
87
+ };
88
+ }
89
+ export { TestingError as a, isLocalHost as i, assertLocalHost as n, developmentApplyDatabase as r, assertDevelopmentDatabase as t };
@@ -1,42 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { dirname, join, posix, relative, resolve, sep } from "node:path";
3
- import { existsSync } from "node:fs";
4
- // src/io/usage-error.ts
5
- /**
6
- * Помилка використання (немає теки, шлях поза текою): викликач може виправити
7
- * її сам. Лише її `invoke` перетворює на відмову; будь-який інший виняток —
8
- * баг, і він не повинен маскуватися під відмову.
9
- */
10
- var UsageError = class extends Error {
11
- name = "UsageError";
12
- };
13
- // src/io/package-path.ts
14
- /**
15
- * Тека встановленого пакета: перший предок `fromDir` (включно) з
16
- * `node_modules/<pkg>/package.json`. Шлях навмисно не проходить `realpath`:
17
- * pnpm робить `node_modules/<pkg>` симлінком у сховище, а значення, що потрапляє
18
- * у файли метаданих, мусить бути однаковим на кожній машині й переживати
19
- * перенос репо.
20
- */
21
- function installedPackageDir(fromDir, pkg) {
22
- const start = resolve(fromDir);
23
- let current = start;
24
- for (;;) {
25
- const candidate = join(current, "node_modules", pkg);
26
- if (existsSync(join(candidate, "package.json"))) return candidate;
27
- const parent = dirname(current);
28
- if (parent === current) throw new UsageError(`${pkg} is not installed in node_modules above ${start}`);
29
- current = parent;
30
- }
31
- }
32
- /**
33
- * Відносний шлях із роздільниками `/`: він потрапляє у файли, які комітять і
34
- * читають на будь-якій ОС (`$schema`, ціль лінка скіла, шлях до бінарника в
35
- * MCP-конфігу), тож форма не може залежати від машини, де його пораховано.
36
- */
37
- function posixRelative(fromDir, to) {
38
- return relative(fromDir, to).split(sep).join(posix.sep);
39
- }
40
2
  // src/tools/hints.ts
41
3
  const READ_ONLY_FLAG = "--read-only";
42
4
  const ALLOW_DATABASE_WRITE_FLAG = "--allow-database-write";
@@ -151,8 +113,4 @@ function noDataHint(envName, channel) {
151
113
  "Nothing changed."
152
114
  ].join(" ");
153
115
  }
154
- // src/io/default-dir.ts
155
- /** Тека метаданих за замовчуванням — спільна для CLI і `simetra mcp`. */
156
- const DEFAULT_DIR = "./metadata";
157
- const trimSlash = (d) => d.replace(/(?<=.)[\\/]+$/, "");
158
- export { dataWriteHint as a, noDatabaseHint as c, installedPackageDir as d, posixRelative as f, DEFAULT_DATABASE_URL_ENV as i, readOnlyHint as l, trimSlash as n, databaseWriteHint as o, UsageError as p, ALLOW_RIGHTS_WRITE_FLAG as r, noDataHint as s, DEFAULT_DIR as t, rightsWriteHint as u };
116
+ export { noDataHint as a, rightsWriteHint as c, databaseWriteHint as i, DEFAULT_DATABASE_URL_ENV as n, noDatabaseHint as o, dataWriteHint as r, readOnlyHint as s, ALLOW_RIGHTS_WRITE_FLAG as t };
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { d as installedPackageDir, f as posixRelative, p as UsageError, t as DEFAULT_DIR } from "./default-dir-DerxTbci.js";
3
- import { t as mcpArgs } from "./mcp-args-D63akJ97.js";
2
+ import { i as posixRelative, r as installedPackageDir, t as DEFAULT_DIR } from "./default-dir-DZz6mxP1.js";
3
+ import { t as UsageError } from "./usage-error-BGPr8yRj.js";
4
+ import { t as mcpArgs } from "./mcp-args-CEn6uN4R.js";
4
5
  import { defineCommand, parseArgs } from "citty";
5
- import { lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
6
+ import { randomUUID } from "node:crypto";
6
7
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, win32 } from "node:path";
8
+ import { lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
7
9
  import { parse } from "smol-toml";
8
- import { randomUUID } from "node:crypto";
9
10
  // src/init/fs-probe.ts
10
11
  /**
11
12
  * Що лежить за шляхом, без переходу за симлінком: `init` судить про власні
@@ -1,16 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { r as defineTool, t as PLANS_DIR } from "./types-CMcZhIci.js";
3
- import { a as dataWriteHint, c as noDatabaseHint, d as installedPackageDir, f as posixRelative, l as readOnlyHint, o as databaseWriteHint, p as UsageError, s as noDataHint, u as rightsWriteHint } from "./default-dir-DerxTbci.js";
3
+ import { a as TestingError, i as isLocalHost, n as assertLocalHost, t as assertDevelopmentDatabase } from "./development-BbRCYFA3.js";
4
4
  import { a as ShadowTemplateMissingError, i as ShadowServerMismatchError, n as ShadowCreateRefusedError, o as shadowDropOf, r as ShadowServerError, t as ShadowBaseUnsupportedError } from "./errors-D1P2kKbL.js";
5
- import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
6
- import { dirname, join, relative, resolve, sep } from "node:path";
7
- import { ATTRIBUTE_CASES, CENTRIFUGO_CHANNEL_MAX, CommandFailure, DATABASE_PROVIDERS, FUNCTIONS_FILE_SUFFIX, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, PROVIDER_SCHEMAS, SIGNAL_MERGE_THRESHOLD, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, SQL_DEBT_FILE, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
8
- import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, applyStateOf, buildPlan, checkOwnerAttributes, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, copiesShadowFromTemplate, desiredForApply, engineScope, ensurePlatformRoles, ensurePostgresCluster, executePlan, folderReference, parsePlan, parseRehearsal, planFileName, platformRoleSet, postgresClusterSet, readShadowEnvironment, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
5
+ import { t as UsageError } from "./usage-error-BGPr8yRj.js";
6
+ import { n as readMetadataDir, r as writeChanges } from "./metadata-dir-DCZ_sYGI.js";
7
+ import { i as posixRelative, r as installedPackageDir } from "./default-dir-DZz6mxP1.js";
8
+ import { a as noDataHint, c as rightsWriteHint, i as databaseWriteHint, o as noDatabaseHint, r as dataWriteHint, s as readOnlyHint } from "./hints-C6wx_Gi6.js";
9
9
  import pg from "pg";
10
+ import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, applyStateOf, buildPlan, checkOwnerAttributes, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, copiesShadowFromTemplate, desiredForApply, engineScope, ensurePlatformRoles, ensurePostgresCluster, executePlan, folderReference, parsePlan, parseRehearsal, planFileName, platformRoleSet, postgresClusterSet, readShadowEnvironment, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
11
+ import { parse } from "pg-connection-string";
12
+ import { ATTRIBUTE_CASES, CENTRIFUGO_CHANNEL_MAX, CommandFailure, DATABASE_PROVIDERS, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, PROVIDER_SCHEMAS, SIGNAL_MERGE_THRESHOLD, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
13
+ import { addElement, addElementInput, buildRuntimeCatalog, canonicalSnapshot, compile, createObject, createObjectInput, declareFunction, declareFunctionInput, deleteElement, deleteInput, diagnostic, explainFunction, explainObject, fixFiles, identityParts, isRepairError, loadSqlParser, localize, promoteInput, promoteObject, promotionFileName, promotionRecordSchema, readProjectFile, renameElement, renameInput, serializeCanonical, unitIdentity } from "simetra/compiler";
14
+ import { dirname, join, resolve, sep } from "node:path";
15
+ import { readFile, readdir, stat } from "node:fs/promises";
10
16
  import { agentWriteRefusal, createAgentCore, createCommandRuntime, fromPgPool, readRoleOf, toJson } from "simetra/server";
11
17
  import { ZodError, z } from "zod";
12
- import { addElement, addElementInput, buildRuntimeCatalog, canonicalSnapshot, compile, createObject, createObjectInput, declareFunction, declareFunctionInput, deleteElement, deleteInput, diagnostic, explainFunction, explainObject, fixFiles, identityParts, isRepairError, loadSqlParser, localize, promoteInput, promoteObject, promotionFileName, promotionRecordSchema, readProjectFile, renameElement, renameInput, serializeCanonical, unitIdentity } from "simetra/compiler";
13
- import { parse } from "pg-connection-string";
14
18
  import { existsSync } from "node:fs";
15
19
  // src/io/data-guard-refusal.ts
16
20
  /**
@@ -270,30 +274,7 @@ async function withDatabase(resource, tool, fn) {
270
274
  }
271
275
  // src/io/data.ts
272
276
  /**
273
- * Ознака бази розробника — налаштування рівня бази, яке ставить оператор
274
- * (`ALTER DATABASE … SET` від суперкористувача). Сесійне `options=-c …` чи
275
- * налаштування ролі її не дають: їх може задати сам рядок підключення.
276
- */
277
- const DEVELOPMENT_ENVIRONMENT = {
278
- setting: "simetra.environment",
279
- value: "development"
280
- };
281
- const IPV4_LOOPBACK = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
282
- /**
283
- * Хост, який візьме `pg`, — машина розробника: `localhost`, петля IPv4
284
- * `127.0.0.0/8`, `::1` чи шлях unix-сокета. DNS не розв'язується: ім'я, що
285
- * лише вказує на петлю, — уже не «ця машина» за формою рядка.
286
- */
287
- function isLocalHost(host) {
288
- if (host === void 0 || host === "") return false;
289
- if (host.startsWith("/")) return true;
290
- const h = host.toLowerCase();
291
- if (h === "localhost" || h === "::1") return true;
292
- const m = IPV4_LOOPBACK.exec(h);
293
- return m !== null && m.slice(1).every((octet) => Number(octet) <= 255);
294
- }
295
- /**
296
- * Факти ролі входу й ознаки бази одним оператором. Роль перевіряється
277
+ * Факти ролі входу одним оператором. Роль перевіряється
297
278
  * фактами, не іменем: ім'я `simetra_runtime` не доводить, що роль не
298
279
  * суперкористувач і не мігратор. Відсутня в кластері роль команд дає
299
280
  * `false`, а не `42704`, — підзапит з `COALESCE`.
@@ -303,20 +284,15 @@ const DATA_GUARD_FACTS_SQL = `SELECT r.rolsuper, r.rolbypassrls,
303
284
  FROM pg_catalog.pg_roles c WHERE c.rolname = $1), false) AS command,
304
285
  COALESCE(pg_catalog.pg_has_role(session_user, n.nspowner, 'MEMBER'), false) AS migrator,
305
286
  COALESCE((SELECT pg_catalog.pg_has_role(session_user, s.oid, 'MEMBER')
306
- FROM pg_catalog.pg_roles s WHERE s.rolname = $2), false) AS service,
307
- EXISTS (SELECT FROM pg_catalog.pg_db_role_setting d
308
- JOIN pg_catalog.pg_database b ON b.oid = d.setdatabase
309
- WHERE b.datname = pg_catalog.current_database() AND d.setrole = 0
310
- AND $3 = ANY (d.setconfig)) AS development
287
+ FROM pg_catalog.pg_roles s WHERE s.rolname = $2), false) AS service
311
288
  FROM pg_catalog.pg_roles r
312
- LEFT JOIN pg_catalog.pg_namespace n ON n.nspname = $4
289
+ LEFT JOIN pg_catalog.pg_namespace n ON n.nspname = $3
313
290
  WHERE r.rolname = session_user`;
314
291
  /** Параметри {@link DATA_GUARD_FACTS_SQL} для профілю провайдера. */
315
292
  function dataGuardFactsParams(provider) {
316
293
  return [
317
294
  PLATFORM_ROLES.command,
318
295
  PROVIDER_API_ROLES[provider].service,
319
- `${DEVELOPMENT_ENVIRONMENT.setting}=${DEVELOPMENT_ENVIRONMENT.value}`,
320
296
  PLATFORM_SCHEMA
321
297
  ];
322
298
  }
@@ -337,27 +313,36 @@ function dataSession(provider, o) {
337
313
  }
338
314
  /**
339
315
  * Запит фактів сирим клієнтом пулу (булеві — `boolean`, а не текст порту
340
- * рантайму) у транзакції лише читання. Клієнт звільняється до повернення:
341
- * за `max: 1` незвільнений клієнт заблокував би рантайм.
316
+ * рантайму) у транзакції лише читання, потім ознака бази — на тому самому
317
+ * клієнті, яким далі піде рантайм (`max: 1`). Клієнт звільняється до
318
+ * повернення: за `max: 1` незвільнений клієнт заблокував би рантайм.
342
319
  */
343
320
  async function checkGuards(pool, provider) {
344
321
  const client = await pool.connect();
345
322
  client.on("error", () => {});
346
- let facts;
347
323
  let broken = false;
348
324
  try {
349
325
  await client.query("BEGIN READ ONLY");
350
326
  const { rows } = await client.query(DATA_GUARD_FACTS_SQL, dataGuardFactsParams(provider));
351
327
  await client.query("COMMIT");
352
- facts = rows[0];
328
+ const facts = rows[0];
329
+ if (facts === void 0 || facts.rolsuper || facts.rolbypassrls || facts.migrator || facts.service || !facts.command) throw new DataGuardRefusal("login-refused");
330
+ await assertDevelopmentDatabase(client).catch((error) => {
331
+ throw guardRefusal(error);
332
+ });
353
333
  } catch (error) {
354
- broken = true;
334
+ if (!(error instanceof DataGuardRefusal)) broken = true;
355
335
  throw error;
356
336
  } finally {
357
337
  client.release(broken);
358
338
  }
359
- if (facts === void 0 || facts.rolsuper || facts.rolbypassrls || facts.migrator || facts.service || !facts.command) throw new DataGuardRefusal("login-refused");
360
- if (!facts.development) throw new DataGuardRefusal("not-development");
339
+ }
340
+ /** Відмова перевірки бази розробника — у код запобіжника даних. */
341
+ function guardRefusal(error) {
342
+ if (!(error instanceof TestingError)) return error;
343
+ if (error.code === "testing.not-local") return new DataGuardRefusal("not-local");
344
+ if (error.code === "testing.not-development") return new DataGuardRefusal("not-development");
345
+ return error;
361
346
  }
362
347
  /**
363
348
  * Ресурс даних з імені змінної, зафіксованого при запуску. Порожня змінна —
@@ -372,13 +357,16 @@ function dataResource(env, o) {
372
357
  as: o.as,
373
358
  ...o.agent === void 0 ? {} : { agent: o.agent },
374
359
  async open(provider) {
375
- let host;
376
360
  try {
377
- host = new pg.Client({ connectionString: url }).host;
361
+ new pg.Client({ connectionString: url });
378
362
  } catch {
379
363
  throw new DatabaseRefusal(`The connection string in ${o.urlEnv} is not a valid URL. Nothing changed.`);
380
364
  }
381
- if (!isLocalHost(host)) throw new DataGuardRefusal("not-local");
365
+ try {
366
+ assertLocalHost(url);
367
+ } catch (error) {
368
+ throw guardRefusal(error);
369
+ }
382
370
  const pool = new pg.Pool({
383
371
  connectionString: url,
384
372
  max: 1
@@ -485,87 +473,6 @@ function parseDataLaunch(flags) {
485
473
  ...agent === void 0 ? {} : { agent }
486
474
  };
487
475
  }
488
- // src/io/metadata-dir.ts
489
- /**
490
- * Файли, які читає компілятор; усе інше в теці його не стосується. Перелік
491
- * боргу — один файл у корені теки: без нього ратчет бачив би порожній перелік
492
- * і звітував кожну одиницю боргу.
493
- */
494
- const METADATA_SUFFIXES = [
495
- ".meta.json",
496
- ".sql",
497
- ".module.ts",
498
- FUNCTIONS_FILE_SUFFIX
499
- ];
500
- const isMetadataFile = (key) => key === SQL_DEBT_FILE || METADATA_SUFFIXES.some((suffix) => key.endsWith(suffix));
501
- /**
502
- * Єдине місце читання диска для дверей CLI: компілятор (T1) працює над мапою
503
- * «шлях → текст» і не знає про файлову систему.
504
- */
505
- async function readMetadataDir(dir) {
506
- let isDirectory;
507
- try {
508
- isDirectory = (await stat(dir)).isDirectory();
509
- } catch (error) {
510
- const code = error.code;
511
- if (code === "ENOENT" || code === "ENOTDIR") throw new UsageError(`metadata directory not found: ${dir}`);
512
- throw error;
513
- }
514
- if (!isDirectory) throw new UsageError(`Not a directory: ${dir}`);
515
- const entries = await readdir(dir, {
516
- recursive: true,
517
- withFileTypes: true
518
- });
519
- const files = /* @__PURE__ */ new Map();
520
- for (const entry of entries) {
521
- if (!entry.isFile()) continue;
522
- const full = join(entry.parentPath, entry.name);
523
- const key = relative(dir, full).split(sep).join("/");
524
- if (!isMetadataFile(key)) continue;
525
- files.set(key, await readFile(full, "utf8"));
526
- }
527
- return files;
528
- }
529
- /**
530
- * Єдине місце запису; `content: null` видаляє файл і прибирає порожні теки.
531
- * Видалення йдуть першими: на регістронезалежній ФС перейменування лише
532
- * регістру — це видалення старого шляху й запис нового, що вказують на той
533
- * самий файл, і зворотний порядок стер би щойно записане.
534
- */
535
- async function writeChanges(dir, changes) {
536
- const root = resolve(dir);
537
- const targets = /* @__PURE__ */ new Map();
538
- for (const change of changes) {
539
- const target = resolve(root, change.path);
540
- if (!target.startsWith(root + sep)) throw new UsageError(`Path escapes the target directory: ${change.path}`);
541
- targets.set(change, target);
542
- }
543
- const ordered = [...changes.filter((c) => c.content === null), ...changes.filter((c) => c.content !== null)];
544
- for (const change of ordered) {
545
- const target = targets.get(change);
546
- if (change.content === null) {
547
- await rm(target, { force: true });
548
- await pruneEmptyDirs(dirname(target), root);
549
- } else {
550
- await mkdir(dirname(target), { recursive: true });
551
- await writeFile(target, change.content, "utf8");
552
- }
553
- }
554
- }
555
- async function pruneEmptyDirs(from, root) {
556
- let current = from;
557
- while (current !== root && current.startsWith(root + sep)) {
558
- let entries;
559
- try {
560
- entries = await readdir(current);
561
- } catch {
562
- return;
563
- }
564
- if (entries.length > 0) return;
565
- await rm(current, { recursive: true });
566
- current = dirname(current);
567
- }
568
- }
569
476
  // src/io/report.ts
570
477
  /** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
571
478
  function localized(d, locale) {
@@ -811,7 +718,7 @@ const PROJECT_FILE$2 = "project.meta.json";
811
718
  * MCP-сервер без бази не тягнуть pg-delta.
812
719
  */
813
720
  async function loadEngine() {
814
- const { createPgDeltaEngine } = await import("./schema-engine-8rVHcVYO.js");
721
+ const { createPgDeltaEngine } = await import("./schema-engine-Bc9PeNLz.js");
815
722
  return createPgDeltaEngine();
816
723
  }
817
724
  /** Резолвер `invoke` гарантує ресурс для інструмента з віссю бази. */
@@ -901,7 +808,7 @@ const introspectTool = defineTool({
901
808
  };
902
809
  }
903
810
  const engine = await loadEngine();
904
- const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
811
+ const { createApplyDatabase } = await import("./schema-engine-Bc9PeNLz.js");
905
812
  const read = await withDatabase(required$1(database), "introspect", async (db) => ({
906
813
  ...await engine.extractWithExecuteFacts(db.target, scope),
907
814
  reference: await folderReference(engine, createApplyDatabase({ readOnly: true }), {
@@ -1108,7 +1015,7 @@ const diffTool = defineTool({
1108
1015
  };
1109
1016
  const desired = await desiredForApply(model);
1110
1017
  const engine = await loadEngine();
1111
- const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
1018
+ const { createApplyDatabase } = await import("./schema-engine-Bc9PeNLz.js");
1112
1019
  const compared = await withDatabase(required$1(database), "diff", async (db) => {
1113
1020
  const reader = createApplyDatabase({ readOnly: true });
1114
1021
  const membership = await checkOwnerMembership(reader, db.target, desired.scope, "engine.owner-not-member");
@@ -1180,7 +1087,7 @@ const diffTool = defineTool({
1180
1087
  * двигун у `loadEngine`.
1181
1088
  */
1182
1089
  async function applyDatabase(o) {
1183
- const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
1090
+ const { createApplyDatabase } = await import("./schema-engine-Bc9PeNLz.js");
1184
1091
  return createApplyDatabase(o);
1185
1092
  }
1186
1093
  const refusedWith = (diagnostics) => ({
@@ -2112,7 +2019,7 @@ const rightsMaintenanceTool = defineTool({
2112
2019
  changes: [],
2113
2020
  diagnostics: compiled.diagnostics
2114
2021
  };
2115
- const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
2022
+ const { createApplyDatabase } = await import("./schema-engine-Bc9PeNLz.js");
2116
2023
  const ran = await withDatabase(required$1(database), "rights-maintenance", (db) => runRightsMaintenance(createApplyDatabase({ readOnly: false }), db.target, model, request));
2117
2024
  if (!ran.ok) return {
2118
2025
  ok: false,
@@ -2333,7 +2240,7 @@ const rolesTool = defineTool({
2333
2240
  changes: [],
2334
2241
  diagnostics: set.diagnostics
2335
2242
  };
2336
- const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
2243
+ const { createApplyDatabase } = await import("./schema-engine-Bc9PeNLz.js");
2337
2244
  const ran = await withDatabase(required$1(database), "roles", (db) => runRoles(createApplyDatabase({ readOnly: false }), db, set, input.devPasswords === true ? { devPasswords: env ?? {} } : {}));
2338
2245
  if (!ran.ok) return {
2339
2246
  ok: false,
@@ -2825,4 +2732,4 @@ async function invoke(tool, input, o) {
2825
2732
  }
2826
2733
  });
2827
2734
  }
2828
- export { toolByName as a, writeChanges as c, parseDataLaunch as d, databaseResource as f, structureOf as i, checkEnvName as l, TOOLS as n, formatDiagnostics as o, presentation as r, isMetadataFile as s, invoke as t, dataResource as u };
2735
+ export { toolByName as a, dataResource as c, structureOf as i, parseDataLaunch as l, TOOLS as n, formatDiagnostics as o, presentation as r, checkEnvName as s, invoke as t, databaseResource as u };
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-CJuyaMGH.js";
2
+ import { t as version } from "./package-BxFYuhZ0.js";
3
3
  import { n as TOOL_NAMES } from "./types-CMcZhIci.js";
4
4
  import { defineCommand, runCommand, runMain, showUsage } from "citty";
5
5
  // src/main.ts
@@ -10,9 +10,10 @@ const main = defineCommand({
10
10
  description: "Simetra metadata tooling"
11
11
  },
12
12
  subCommands: {
13
- ...Object.fromEntries(TOOL_NAMES.map((name) => [name, () => import("./command-BUIz4QxS.js").then((m) => m.commandByName(name))])),
14
- mcp: () => import("./mcp-CLc4ByOi.js").then((m) => m.default),
15
- init: () => import("./init-BS7fCOls.js").then((m) => m.default)
13
+ ...Object.fromEntries(TOOL_NAMES.map((name) => [name, () => import("./command-B5wu4cHE.js").then((m) => m.commandByName(name))])),
14
+ mcp: () => import("./mcp-YQqUWktB.js").then((m) => m.default),
15
+ init: () => import("./init-DFsWagyh.js").then((m) => m.default),
16
+ "dev-check": () => import("./dev-check-CX7nvtJO.js").then((m) => m.default)
16
17
  }
17
18
  });
18
19
  const rawArgs = process.argv.slice(2);
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { d as parseDataLaunch, f as databaseResource, i as structureOf, l as checkEnvName, n as TOOLS, o as formatDiagnostics, r as presentation, t as invoke, u as dataResource } from "./invoke-B6ljdX5t.js";
3
- import { a as dataWriteHint, l as readOnlyHint, n as trimSlash, o as databaseWriteHint, p as UsageError, r as ALLOW_RIGHTS_WRITE_FLAG } from "./default-dir-DerxTbci.js";
4
- import { t as version } from "./package-CJuyaMGH.js";
5
- import { t as mcpArgs } from "./mcp-args-D63akJ97.js";
2
+ import { c as dataResource, i as structureOf, l as parseDataLaunch, n as TOOLS, o as formatDiagnostics, r as presentation, s as checkEnvName, t as invoke, u as databaseResource } from "./invoke-8HeorF7f.js";
3
+ import { n as trimSlash } from "./default-dir-DZz6mxP1.js";
4
+ import { t as UsageError } from "./usage-error-BGPr8yRj.js";
5
+ import { t as version } from "./package-BxFYuhZ0.js";
6
+ import { i as databaseWriteHint, r as dataWriteHint, s as readOnlyHint, t as ALLOW_RIGHTS_WRITE_FLAG } from "./hints-C6wx_Gi6.js";
7
+ import { t as mcpArgs } from "./mcp-args-CEn6uN4R.js";
6
8
  import { defineCommand } from "citty";
7
9
  import { z } from "zod";
8
10
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { i as DEFAULT_DATABASE_URL_ENV } from "./default-dir-DerxTbci.js";
2
+ import { n as DEFAULT_DATABASE_URL_ENV } from "./hints-C6wx_Gi6.js";
3
3
  // src/commands/mcp-args.ts
4
4
  /**
5
5
  * Аргументи `simetra mcp` окремим легким модулем: за цим же описом `init`