simetra 0.3.0-next.1 → 0.3.0-next.3

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.
@@ -2889,8 +2889,24 @@ const MESSAGES = {
2889
2889
  en: (p) => `Open self sign-up lets anyone from the Internet become a signed-in user: objects open to every signed-in user (${p.objects || "none"}) and the grants of everyUser roles (${p.roles || "none"}) are exposed to them`,
2890
2890
  uk: (p) => `Відкрита самореєстрація дає змогу будь-кому з Інтернету стати дійсним користувачем: йому відкрито об'єкти для кожного користувача (${p.objects || "немає"}) і гранти ролей everyUser (${p.roles || "немає"})`,
2891
2891
  hint: {
2892
- en: "Check that these objects and grants are meant for anyone, or set selfSignUp to false.",
2893
- uk: "Переконайтеся, що ці об'єкти й гранти призначено для будь-кого, або вимкніть selfSignUp."
2892
+ en: "Check that these objects and grants are meant for anyone and list them in selfSignUpAccepted, or set selfSignUp to false.",
2893
+ uk: "Переконайтеся, що ці об'єкти й гранти призначено для будь-кого, і перелічіть їх у selfSignUpAccepted, або вимкніть selfSignUp."
2894
+ }
2895
+ },
2896
+ "project.self-sign-up-role": {
2897
+ en: (p) => `selfSignUpAccepted names ${p.kind} "${p.name}" as the role of a grant, but only a role of the everyUser level gives grants to anyone`,
2898
+ uk: (p) => `selfSignUpAccepted називає ${p.kind} "${p.name}" роллю гранту, але гранти будь-кому дає лише роль рівня everyUser`,
2899
+ hint: {
2900
+ en: "Name a Role with assignedOn everyUser, or remove the entry.",
2901
+ uk: "Назвіть Role з assignedOn everyUser або приберіть запис."
2902
+ }
2903
+ },
2904
+ "project.self-sign-up-stale": {
2905
+ en: (p) => `selfSignUpAccepted accepts ${p.entry}, but nothing open to every signed-in user matches it: the entry would silently accept such openness when it appears`,
2906
+ uk: (p) => `selfSignUpAccepted приймає ${p.entry}, але нічого відкритого кожному користувачу йому не відповідає: запис мовчки прийняв би таку відкритість, коли вона з'явиться`,
2907
+ hint: {
2908
+ en: "Remove the entry (or the actions it no longer matches); accept the openness again when it returns.",
2909
+ uk: "Приберіть запис (чи дії, яким уже нічого не відповідає); прийміть відкритість знову, коли вона повернеться."
2894
2910
  }
2895
2911
  },
2896
2912
  "rights.ownership-target": {
@@ -3282,11 +3298,11 @@ const MESSAGES = {
3282
3298
  }
3283
3299
  },
3284
3300
  "operation.input-invalid": {
3285
- en: (p) => p.scopes !== void 0 ? `The scopes input ${p.scopes === "target" ? "is allowed only with the scopeKinds collection of Project" : p.scopes === "table-unknown" ? `names ${p.table}, which is not a CustomTable of the project` : `names ${p.table}, which already declares its scope: changing a scope is another operation`} (at ${p.at}); nothing was changed` : p.at === void 0 ? "The operation needs metadata that compiles without errors; nothing was changed" : `The operation input must not carry "id" (at ${p.at}): ids are assigned by the operation; nothing was changed`,
3286
- uk: (p) => p.scopes !== void 0 ? `Вхід scopes ${p.scopes === "target" ? "дозволено лише з колекцією scopeKinds проєкту" : p.scopes === "table-unknown" ? `називає ${p.table}, якої немає серед CustomTable проєкту` : `називає ${p.table}, що вже оголошує скоуп: зміна скоупу — інша операція`} (у ${p.at}); нічого не змінено` : p.at === void 0 ? "Операція потребує метаданих, що компілюються без помилок; нічого не змінено" : `Вхід операції не повинен містити "id" (у ${p.at}): id призначає операція; нічого не змінено`,
3301
+ en: (p) => p.objects !== void 0 ? `The objects input is allowed only with the scopeKinds collection of Project (at ${p.at}); nothing was changed` : p.scopes !== void 0 ? `The scopes input ${p.scopes === "target" ? "is allowed only with the scopeKinds collection of Project" : p.scopes === "table-unknown" ? `names ${p.table}, which is not a CustomTable of the project` : `names ${p.table}, which already declares its scope: changing a scope is another operation`} (at ${p.at}); nothing was changed` : p.at === void 0 ? "The operation needs metadata that compiles without errors; nothing was changed" : `The operation input must not carry "id" (at ${p.at}): ids are assigned by the operation; nothing was changed`,
3302
+ uk: (p) => p.objects !== void 0 ? `Вхід objects дозволено лише з колекцією scopeKinds проєкту (у ${p.at}); нічого не змінено` : p.scopes !== void 0 ? `Вхід scopes ${p.scopes === "target" ? "дозволено лише з колекцією scopeKinds проєкту" : p.scopes === "table-unknown" ? `називає ${p.table}, якої немає серед CustomTable проєкту` : `називає ${p.table}, що вже оголошує скоуп: зміна скоупу — інша операція`} (у ${p.at}); нічого не змінено` : p.at === void 0 ? "Операція потребує метаданих, що компілюються без помилок; нічого не змінено" : `Вхід операції не повинен містити "id" (у ${p.at}): id призначає операція; нічого не змінено`,
3287
3303
  hint: {
3288
- en: (p) => p.scopes !== void 0 ? "Use scopes only when adding a scope kind to Project, and name only CustomTables that have no scope yet." : p.at === void 0 ? "Fix the errors reported with this diagnostic (simetra fix handles missing ids and physical names), then repeat the operation." : "Remove the id from the input; a new element gets a fresh id that is never reused.",
3289
- uk: (p) => p.scopes !== void 0 ? "Використовуйте scopes лише при додаванні виду скоупу в проєкт і називайте лише CustomTable без скоупу." : p.at === void 0 ? "Виправте помилки, наведені поряд із цією діагностикою (відсутні id і фізичні імена лагодить simetra fix), і повторіть операцію." : "Приберіть id із входу; новий елемент отримує свіжий id, який ніколи не перевикористовується."
3304
+ en: (p) => p.objects !== void 0 ? "Use objects only when adding a scope kind to Project; create other objects with create." : p.scopes !== void 0 ? "Use scopes only when adding a scope kind to Project, and name only CustomTables that have no scope yet." : p.at === void 0 ? "Fix the errors reported with this diagnostic (simetra fix handles missing ids and physical names), then repeat the operation." : "Remove the id from the input; a new element gets a fresh id that is never reused.",
3305
+ uk: (p) => p.objects !== void 0 ? "Використовуйте objects лише при додаванні виду скоупу в проєкт; інші об'єкти створюйте через create." : p.scopes !== void 0 ? "Використовуйте scopes лише при додаванні виду скоупу в проєкт і називайте лише CustomTable без скоупу." : p.at === void 0 ? "Виправте помилки, наведені поряд із цією діагностикою (відсутні id і фізичні імена лагодить simetra fix), і повторіть операцію." : "Приберіть id із входу; новий елемент отримує свіжий id, який ніколи не перевикористовується."
3290
3306
  }
3291
3307
  },
3292
3308
  "operation.target-not-found": {
@@ -3981,6 +3997,14 @@ const MESSAGES = {
3981
3997
  uk: "Нічого не записано. Поверніть ролі застосування те, що план застав (право поставити plpgsql_check чи USAGE на схему встановленого розширення), або сплануйте знову."
3982
3998
  }
3983
3999
  },
4000
+ "apply.extension-unavailable": {
4001
+ en: (p) => `The plan checks function bodies with ${p.extension}, but the server has no such extension: it is neither installed in the database nor listed in pg_available_extensions. Nothing was written`,
4002
+ uk: (p) => `План перевіряє тіла функцій через ${p.extension}, але на сервері такого розширення немає: його немає ні в базі, ні в pg_available_extensions. Нічого не записано`,
4003
+ hint: {
4004
+ en: (p) => `Install the package of the extension ${p.extension} on the database server (for a Debian-based Postgres image from the PGDG repository it is postgresql-<major>-${String(p.extension).replaceAll("_", "-")}), then apply again. A rehearsal copy on another server needs the package there too. When the plan found the extension installed, put it back into the database as well (\`simetra roles\` on the postgres profile), or plan again.`,
4005
+ uk: (p) => `Поставте пакет розширення ${p.extension} на сервер бази (для образу Postgres на Debian з репозиторію PGDG це postgresql-<major>-${String(p.extension).replaceAll("_", "-")}) і застосуйте знову. Копії репетиції на іншому сервері пакет потрібен і там. Коли план застав розширення встановленим, поверніть його й у базу (\`simetra roles\` у профілі postgres) або сплануйте знову.`
4006
+ }
4007
+ },
3984
4008
  "apply.replication-role": {
3985
4009
  en: (p) => `The apply transaction runs with session_replication_role = ${p.value}, and the plan's data steps need origin: otherwise foreign key triggers do not fire and the written values bypass the reference checks. Nothing was written`,
3986
4010
  uk: (p) => `Транзакція застосування має session_replication_role = ${p.value}, а кроки даних плану потребують origin: інакше тригери зовнішніх ключів не спрацьовують, і записані значення обходять перевірку посилань. Нічого не записано`,
@@ -4481,6 +4505,14 @@ const MESSAGES = {
4481
4505
  uk: "Саме підключення вдалося; збій стався під час роботи з базою. Текст помилки драйвера приховано, бо він може нести облікові дані; знайдіть SQLSTATE або повторіть після виправлення бази."
4482
4506
  }
4483
4507
  },
4508
+ "data.scope-unspecified": {
4509
+ en: (p) => `The create of ${p.object} names no ${p.attribute}, and the user is a member of ${p.scopes} scopes of kind "${p.scopeKind}": the scope of the new row is not specified. Nothing was written.`,
4510
+ uk: (p) => `Створення ${p.object} не називає ${p.attribute}, а користувач — учасник ${p.scopes} скоупів виду "${p.scopeKind}": скоуп нового рядка не вказано. Нічого не записано.`,
4511
+ hint: {
4512
+ en: (p) => `Pass values.${p.attribute} with the scope of the new row; it is taken by itself only when the user is a member of exactly one scope of the kind.`,
4513
+ uk: (p) => `Передайте values.${p.attribute} зі скоупом нового рядка; сам він береться лише тоді, коли користувач — учасник рівно одного скоупу виду.`
4514
+ }
4515
+ },
4484
4516
  "roles.create-role-denied": {
4485
4517
  en: (p) => `The connecting role cannot create the platform role ${p.role} on the ${p.server} server: it has neither CREATEROLE nor SUPERUSER`,
4486
4518
  uk: (p) => `Роль підключення не може створити платформну роль ${p.role} на сервері ${p.server === "shadow" ? "тіні" : "цілі"}: у неї немає ні CREATEROLE, ні SUPERUSER`,
@@ -4553,6 +4585,38 @@ const MESSAGES = {
4553
4585
  uk: "Нічого не створено. Ролі входу кластерні з фіксованими іменами, тож той самий логін мав би свої права в базі іншого застосунку. Використайте окремий кластер для кожного застосунку або відкличте явний CONNECT на ці бази, якщо вони не застосунки Simetra."
4554
4586
  }
4555
4587
  },
4588
+ "roles.extension-unavailable": {
4589
+ en: (p) => `The server has no extension ${p.extension}: it is not listed in pg_available_extensions, so \`simetra roles\` cannot install it into the database or the template`,
4590
+ uk: (p) => `На сервері немає розширення ${p.extension}: його немає в pg_available_extensions, тож \`simetra roles\` не може поставити його в базу чи шаблон`,
4591
+ hint: {
4592
+ en: (p) => `Nothing was written. Install the package of the extension on the database server (for a Debian-based Postgres image from the PGDG repository it is postgresql-<major>-${String(p.extension).replaceAll("_", "-")}), then run \`simetra roles\` again.`,
4593
+ uk: (p) => `Нічого не записано. Поставте пакет розширення на сервер бази (для образу Postgres на Debian з репозиторію PGDG це postgresql-<major>-${String(p.extension).replaceAll("_", "-")}) і запустіть \`simetra roles\` знову.`
4594
+ }
4595
+ },
4596
+ "roles.dev-passwords-unsupported": {
4597
+ en: (p) => p.provider === void 0 ? "devPasswords needs the provider postgres, and the directory has no project.meta.json" : `devPasswords needs the provider postgres, and the project has ${p.provider}`,
4598
+ uk: (p) => p.provider === void 0 ? "devPasswords потребує провайдера postgres, а в теці немає project.meta.json" : `devPasswords потребує провайдера postgres, а проєкт має ${p.provider}`,
4599
+ hint: {
4600
+ en: "Nothing was written. Only the postgres profile creates its login roles in `simetra roles`; drop devPasswords, or run the command in a metadata directory whose project file selects postgres.",
4601
+ uk: "Нічого не записано. Лише профіль postgres створює свої ролі входу в `simetra roles`; приберіть devPasswords або запустіть команду в теці метаданих, файл проєкту якої обирає postgres."
4602
+ }
4603
+ },
4604
+ "roles.dev-password-missing": {
4605
+ en: (p) => `devPasswords reads the password of a login role from the environment variable ${p.variable}, and it is not set or empty`,
4606
+ uk: (p) => `devPasswords читає пароль ролі входу зі змінної середовища ${p.variable}, а вона не задана чи порожня`,
4607
+ hint: {
4608
+ en: "Nothing was written. Set every SIMETRA_*_DEV_PASSWORD variable the diagnostics name in the environment of the command, then run it again.",
4609
+ uk: "Нічого не записано. Задайте в середовищі команди кожну змінну SIMETRA_*_DEV_PASSWORD, яку називають діагностики, і запустіть її знову."
4610
+ }
4611
+ },
4612
+ "roles.dev-passwords-remote": {
4613
+ en: (p) => `devPasswords sets known passwords only on a database of this machine, and the database host is ${p.host}`,
4614
+ uk: (p) => `devPasswords ставить відомі паролі лише в базі цієї машини, а хост бази — ${p.host}`,
4615
+ hint: {
4616
+ en: "Nothing was written. Use devPasswords only with localhost, a 127.0.0.0/8 or ::1 address, or a unix socket; on any other server set the passwords of the login roles yourself.",
4617
+ uk: "Нічого не записано. Використовуйте devPasswords лише з localhost, адресою 127.0.0.0/8 чи ::1 або unix-сокетом; на іншому сервері паролі ролей входу ставте самі."
4618
+ }
4619
+ },
4556
4620
  "maintenance.model-mismatch": {
4557
4621
  en: (p) => `The applied model (${p.applied}) is not the compiled one (${p.compiled}): rights maintenance works only on the database state the project describes`,
4558
4622
  uk: (p) => `Застосована модель (${p.applied}) не збігається зі скомпільованою (${p.compiled}): обслуговування прав працює лише зі станом бази, який описує проєкт`,
@@ -5016,6 +5080,8 @@ const COMPILER_RULES = [
5016
5080
  "rights.adopted-source-writes",
5017
5081
  "rights.scope-kind-unread",
5018
5082
  "project.self-sign-up",
5083
+ "project.self-sign-up-role",
5084
+ "project.self-sign-up-stale",
5019
5085
  "rights.snapshot-source-unknown",
5020
5086
  "rights.snapshot-exempt-writer",
5021
5087
  "rights.signal-source-unknown",
@@ -5150,6 +5216,7 @@ const COMPILER_RULES = [
5150
5216
  "apply.rehearsal-timeout-unbounded",
5151
5217
  "apply.temp-name-taken",
5152
5218
  "apply.plpgsql-check-unavailable",
5219
+ "apply.extension-unavailable",
5153
5220
  "apply.replication-role",
5154
5221
  "apply.data-step-failed",
5155
5222
  "apply.data-step-narrowing",
@@ -5216,6 +5283,7 @@ const COMPILER_RULES = [
5216
5283
  "plan.rights-full-access-lost",
5217
5284
  "plan.rights-orphans",
5218
5285
  "database.failed",
5286
+ "data.scope-unspecified",
5219
5287
  "roles.create-role-denied",
5220
5288
  "roles.admin-option-missing",
5221
5289
  "roles.membership-grant-denied",
@@ -5225,6 +5293,10 @@ const COMPILER_RULES = [
5225
5293
  "roles.database-owner",
5226
5294
  "roles.database-locale",
5227
5295
  "roles.shared-cluster",
5296
+ "roles.extension-unavailable",
5297
+ "roles.dev-passwords-unsupported",
5298
+ "roles.dev-password-missing",
5299
+ "roles.dev-passwords-remote",
5228
5300
  "maintenance.model-mismatch",
5229
5301
  "maintenance.unknown-role",
5230
5302
  "maintenance.role-level",
@@ -5302,6 +5374,7 @@ const WARNING_RULES = /* @__PURE__ */ new Set([
5302
5374
  "rights.adopted-source-writes",
5303
5375
  "rights.scope-kind-unread",
5304
5376
  "project.self-sign-up",
5377
+ "project.self-sign-up-stale",
5305
5378
  "rights.root-creator-no-admin",
5306
5379
  "rights.root-creator-unreachable",
5307
5380
  "sql.debt-session-write",
@@ -6922,7 +6995,6 @@ function derivedSearchColumn(object, style, name) {
6922
6995
  };
6923
6996
  }
6924
6997
  }
6925
- // src/compiler/stages/identity.ts
6926
6998
  /**
6927
6999
  * Ролі, де рядок файлу — логічне ім'я колонки прийнятої таблиці чи цілі її FK.
6928
7000
  * Одна множина для знімка (ім'я → id елемента) і для стадії 3 (id → фізичне
@@ -7155,6 +7227,73 @@ function checkIdentity(objects, brokenNames, project, functionsFiles) {
7155
7227
  role: "storage.scopeKind"
7156
7228
  });
7157
7229
  });
7230
+ const accepted = project?.selfSignUpAccepted;
7231
+ const acceptedTo = (pointer, to) => {
7232
+ references.push({
7233
+ from: {
7234
+ file: PROJECT_FILE,
7235
+ pointer,
7236
+ objectId: ""
7237
+ },
7238
+ to,
7239
+ role: "selfSignUp.accepted"
7240
+ });
7241
+ };
7242
+ const resolveAccepted = (pointer, ref) => {
7243
+ const key = objectKey(ref.kind, ref.name);
7244
+ const target = objectsByName.get(key);
7245
+ if (target === void 0) {
7246
+ if (!brokenNames.has(key)) diagnostics.push(diagnostic("reference.unresolved", PROJECT_FILE, pointer, {
7247
+ kind: ref.kind,
7248
+ name: ref.name
7249
+ }));
7250
+ return;
7251
+ }
7252
+ if (target.id !== void 0) acceptedTo(pointer, {
7253
+ kind: target.kind,
7254
+ id: target.id
7255
+ });
7256
+ return target;
7257
+ };
7258
+ accepted?.objects.forEach((entry, index) => {
7259
+ resolveAccepted(`/selfSignUpAccepted/objects/${index}/object`, entry.object);
7260
+ });
7261
+ accepted?.grants.forEach((grant, index) => {
7262
+ const at = `/selfSignUpAccepted/grants/${index}`;
7263
+ const role = resolveAccepted(`${at}/role`, grant.role);
7264
+ if (role !== void 0 && (role.kind !== "Role" || role.data.assignedOn !== "everyUser")) diagnostics.push(diagnostic("project.self-sign-up-role", PROJECT_FILE, `${at}/role`, {
7265
+ kind: role.kind,
7266
+ name: role.name
7267
+ }));
7268
+ const object = resolveAccepted(`${at}/object`, grant.object);
7269
+ if (object !== void 0) {
7270
+ const standard = KIND_REGISTRY[object.kind].actions(object.data);
7271
+ const custom = customActionsOf(object);
7272
+ grant.actions.forEach((name, i) => {
7273
+ if (standard.some((a) => a.name === name)) return;
7274
+ const id = custom.find((a) => a.name === name)?.id;
7275
+ if (id !== void 0) {
7276
+ acceptedTo(`${at}/actions/${i}`, {
7277
+ kind: "Element",
7278
+ id
7279
+ });
7280
+ return;
7281
+ }
7282
+ diagnostics.push(diagnostic("rights.action-unknown", PROJECT_FILE, `${at}/actions/${i}`, {
7283
+ action: name,
7284
+ object: object.name
7285
+ }));
7286
+ });
7287
+ }
7288
+ if (typeof grant.extent === "object") {
7289
+ const id = projectElements.get("accessDimensions")?.get(grant.extent.dimension)?.id;
7290
+ if (id !== void 0) acceptedTo(`${at}/extent/dimension`, {
7291
+ kind: "Element",
7292
+ id
7293
+ });
7294
+ else diagnostics.push(diagnostic("rights.dimension-unknown", PROJECT_FILE, `${at}/extent/dimension`, { dimension: grant.extent.dimension }));
7295
+ }
7296
+ });
7158
7297
  dimensions.forEach((dimension, index) => {
7159
7298
  resolveDimension(dimension, `/accessDimensions/${index}`, resolveObjectRef, style, references);
7160
7299
  });
@@ -8130,7 +8269,8 @@ function canonicalSnapshot(model) {
8130
8269
  "storageBuckets",
8131
8270
  "accessDimensions",
8132
8271
  "membershipSources",
8133
- "assignmentSources"
8272
+ "assignmentSources",
8273
+ "selfSignUpAccepted"
8134
8274
  ]);
8135
8275
  return {
8136
8276
  project: Object.fromEntries(Object.entries(model.project).filter(([key]) => !unresolved.has(key))),
@@ -22247,7 +22387,7 @@ function systemOf(object) {
22247
22387
  return KIND_REGISTRY[object.kind].rightsSystem?.(object.data);
22248
22388
  }
22249
22389
  /** Рівень системного довідника — його власний скоуп (спека прав §4.6). */
22250
- function catalogLevel(object, references) {
22390
+ function catalogLevel$1(object, references) {
22251
22391
  const scopeKindId = scopeKindOf(object, references);
22252
22392
  return scopeKindId === void 0 ? GLOBAL : {
22253
22393
  level: "scope",
@@ -22328,7 +22468,7 @@ function checkSystemCatalogs(ctx) {
22328
22468
  const first = /* @__PURE__ */ new Map();
22329
22469
  for (const object of catalogs) {
22330
22470
  const system = must$9(systemOf(object));
22331
- const level = catalogLevel(object, ctx.references);
22471
+ const level = catalogLevel$1(object, ctx.references);
22332
22472
  const key = `${system}\u0000${storageKey(level)}`;
22333
22473
  const firstObject = first.get(key);
22334
22474
  if (firstObject === void 0) first.set(key, object);
@@ -22381,7 +22521,7 @@ function checkSystemCatalogs(ctx) {
22381
22521
  }
22382
22522
  }
22383
22523
  for (const object of catalogs) {
22384
- const level = catalogLevel(object, ctx.references);
22524
+ const level = catalogLevel$1(object, ctx.references);
22385
22525
  const source = sourced.get(storageKey(level));
22386
22526
  if (source === void 0 || uncovered.has(storageKey(level))) continue;
22387
22527
  diagnostics.push(diagnostic("rights.system-catalog-parallel", object.file, "/role", {
@@ -22415,7 +22555,7 @@ function rightsCatalogContracts(objects, references, physical) {
22415
22555
  for (const object of objects) {
22416
22556
  const system = systemOf(object);
22417
22557
  if (system === void 0) continue;
22418
- const level = catalogLevel(object, references);
22558
+ const level = catalogLevel$1(object, references);
22419
22559
  const key = storageKey(level);
22420
22560
  byLevel.set(key, {
22421
22561
  level,
@@ -33440,6 +33580,50 @@ function triggeredRelationTable(relation, physical, objects) {
33440
33580
  return table;
33441
33581
  }
33442
33582
  // src/compiler/runtime-catalog.ts
33583
+ /** Рівень ролі контракту як його бачить каталог (спека «Споживач поза монорепо» §5.4). */
33584
+ function catalogLevel(level) {
33585
+ switch (level.level) {
33586
+ case "global":
33587
+ case "everyUser": return level.level;
33588
+ case "scope": return { scopeKind: level.scopeKindId };
33589
+ case "container": return { container: level.containerId };
33590
+ }
33591
+ }
33592
+ /**
33593
+ * Розділи `roles` і `rightsSets` спільної частини каталогу: назви архетипів
33594
+ * для екрана призначення. Порядок — за `order`, далі за `name`; у проєкті без
33595
+ * ролей чи наборів поля немає. `title` береться з метаданих, а не з
33596
+ * контракту: контракт у знімок не змінюється.
33597
+ */
33598
+ function rightsDeclarationsOf(model) {
33599
+ const titleOf = (kind) => new Map(model.objects.filter((o) => o.kind === kind).map((o) => [o.id, o.data.title]));
33600
+ const roleTitles = titleOf("Role");
33601
+ const roles = model.contracts.roles.map((r) => {
33602
+ const title = roleTitles.get(r.roleId);
33603
+ return {
33604
+ id: r.roleId,
33605
+ name: r.name,
33606
+ ...title === void 0 ? {} : { title },
33607
+ level: catalogLevel(r.assignedOn),
33608
+ ...r.order === void 0 ? {} : { order: r.order },
33609
+ assignable: r.assignable,
33610
+ fullAccess: r.fullAccess
33611
+ };
33612
+ }).sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || compareStrings(a.name, b.name));
33613
+ const setTitles = titleOf("RightsSet");
33614
+ const rightsSets = model.objects.filter((o) => o.kind === "RightsSet").map((o) => {
33615
+ const title = setTitles.get(o.id);
33616
+ return {
33617
+ id: o.id,
33618
+ name: o.name,
33619
+ ...title === void 0 ? {} : { title }
33620
+ };
33621
+ }).sort((a, b) => compareStrings(a.name, b.name));
33622
+ return {
33623
+ ...roles.length === 0 ? {} : { roles },
33624
+ ...rightsSets.length === 0 ? {} : { rightsSets }
33625
+ };
33626
+ }
33443
33627
  /**
33444
33628
  * Каталог рантайму (спека П4 §6.3) — проєкція скомпільованої моделі: лише
33445
33629
  * довідники з контрактом ядра команд (`CompiledModel.catalogCommands`), у
@@ -33485,6 +33669,7 @@ function buildRuntimeCatalog(model) {
33485
33669
  ...adoptedFactsOf(model)
33486
33670
  } : {},
33487
33671
  ...model.project.selfSignUp ? { selfSignUp: true } : {},
33672
+ ...rightsDeclarationsOf(model),
33488
33673
  objects: model.objects.flatMap((object) => {
33489
33674
  const contract = contracts.get(object.id);
33490
33675
  if (contract === void 0) return [];
@@ -38388,21 +38573,84 @@ function scopeKindUnreadWarnings(contracts, project) {
38388
38573
  * Роль `publicRead` читається зі скомпільованого контракту доступу, а не з
38389
38574
  * рядкової форми метаданих: `anon` теж відкриває `user`, але його бачить і
38390
38575
  * гість, тож самореєстрація до нього нічого не додає.
38576
+ *
38577
+ * Прийняте в `selfSignUpAccepted` (спека публічної частини §5.5) попередження не називає; без
38578
+ * поля воно звучить завжди, з полем — лише коли відкрито щось неприйняте, і
38579
+ * називає тільки його. Ціль прийняття — id з індексу посилань: `rename`
38580
+ * переписує запис, а `delete` прийнятої цілі блокується. Відома межа —
38581
+ * об'єкт-однойменник, створений після ручного видалення теки (повз
38582
+ * `delete`): він резолвиться з того самого запису (спека публічної частини
38583
+ * §5.5). Об'єкт приймається з формою відкритості, грант — з обсягом.
38584
+ *
38585
+ * Запис прийняття, що не покриває жодної наявної відкритості (знятий грант,
38586
+ * об'єкт без `publicRead`), — попередження `project.self-sign-up-stale`:
38587
+ * інакше він мовчки прийняв би майбутню відкритість, якої автор не бачив.
38588
+ * Його звітує й проєкт без `selfSignUp`: прийняття переживає вимкнення.
38391
38589
  */
38392
- function selfSignUpWarnings(contracts, objects, project) {
38393
- if (project.selfSignUp !== true) return [];
38590
+ function selfSignUpWarnings(contracts, objects, project, references) {
38394
38591
  const names = new Map(objects.map(({ id, name }) => [id, name]));
38395
38592
  const nameOf = (objectId) => names.get(objectId) ?? objectId;
38396
- const exposed = [...new Set(contracts.access.filter((a) => publicReadRoleOf(a.publicRead) === "authenticated").map((a) => nameOf(a.objectId)))].sort(compareStrings);
38593
+ const actionNames = new Map(objects.flatMap((o) => customActionsOf(o).map((a) => [a.id, a.name])));
38594
+ const actionOf = (action) => actionNames.get(action) ?? action;
38595
+ const dimensionNames = new Map((project.accessDimensions ?? []).map((d) => [d.id, d.name]));
38596
+ const extentOf = (extent) => typeof extent === "string" ? extent : dimensionNames.get(extent.dimensionId) ?? extent.dimensionId;
38597
+ const accepted = project.selfSignUpAccepted;
38598
+ const target = new Map(references.filter((r) => r.role === "selfSignUp.accepted").map((r) => [r.from.pointer, r.to.id]));
38599
+ const acceptedObjects = new Set((accepted?.objects ?? []).map((entry, i) => `${target.get(`/selfSignUpAccepted/objects/${i}/object`) ?? ""}\0${entry.published === true ? "published" : "all"}`));
38600
+ const objectAccepted = (objectId, published) => acceptedObjects.has(`${objectId}\0all`) || published && acceptedObjects.has(`${objectId}\0published`);
38601
+ const grantKey = (roleId, objectId, action, extent) => JSON.stringify([
38602
+ roleId,
38603
+ objectId,
38604
+ action,
38605
+ typeof extent === "string" ? extent : extent.dimensionId
38606
+ ]);
38607
+ const acceptedGrants = new Set((accepted?.grants ?? []).flatMap((grant, i) => {
38608
+ const at = `/selfSignUpAccepted/grants/${i}`;
38609
+ const extent = typeof grant.extent === "string" ? grant.extent : { dimensionId: target.get(`${at}/extent/dimension`) ?? "" };
38610
+ return grant.actions.map((action, j) => grantKey(target.get(`${at}/role`) ?? "", target.get(`${at}/object`) ?? "", target.get(`${at}/actions/${j}`) ?? action, extent));
38611
+ }));
38612
+ const open = contracts.access.filter((a) => publicReadRoleOf(a.publicRead) === "authenticated");
38397
38613
  const projection = expandedProjection(contracts);
38398
- const roles = contracts.roles.filter((role) => role.assignedOn.level === "everyUser").map((role) => {
38399
- const grants = projection.filter((row) => row.roleId === role.roleId).map((row) => `${nameOf(row.objectId)}.${row.action}`).sort(compareStrings);
38400
- return `${role.name}: ${grants.join(", ")}`;
38401
- }).sort(compareStrings);
38614
+ const everyUser = contracts.roles.filter((role) => role.assignedOn.level === "everyUser");
38615
+ const exposedGrants = new Set(projection.filter((row) => everyUser.some((role) => role.roleId === row.roleId)).map((row) => grantKey(row.roleId, row.objectId, row.action, row.extent)));
38616
+ const stale = staleEntries();
38617
+ if (project.selfSignUp !== true) return stale;
38618
+ const exposed = [...new Set(open.filter((a) => !objectAccepted(a.objectId, a.published !== void 0)).map((a) => `${nameOf(a.objectId)}${a.published === void 0 ? "" : " (published)"}`))].sort(compareStrings);
38619
+ const roles = everyUser.map((role) => ({
38620
+ role,
38621
+ grants: projection.filter((row) => row.roleId === role.roleId).filter((row) => !acceptedGrants.has(grantKey(role.roleId, row.objectId, row.action, row.extent))).map((row) => `${nameOf(row.objectId)}.${actionOf(row.action)} (${extentOf(row.extent)})`).sort(compareStrings)
38622
+ })).filter(({ grants }) => accepted === void 0 || grants.length > 0).map(({ role, grants }) => `${role.name}: ${grants.join(", ")}`).sort(compareStrings);
38623
+ if (accepted !== void 0 && exposed.length === 0 && roles.length === 0) return stale;
38402
38624
  return [diagnostic("project.self-sign-up", PROJECT_FILE, "/selfSignUp", {
38403
38625
  objects: exposed.join(", "),
38404
38626
  roles: roles.join("; ")
38405
- })];
38627
+ }), ...stale];
38628
+ /**
38629
+ * Записи без жодної відкритості, яку вони покривають. Непрорезолвлений
38630
+ * запис уже має помилку стадії 2, тож тут мовчить.
38631
+ */
38632
+ function staleEntries() {
38633
+ const found = [];
38634
+ accepted?.objects.forEach((entry, i) => {
38635
+ const objectId = target.get(`/selfSignUpAccepted/objects/${i}/object`);
38636
+ if (objectId === void 0) return;
38637
+ const forms = open.filter((a) => a.objectId === objectId);
38638
+ if (entry.published === true ? forms.some((a) => a.published !== void 0) : forms.length > 0) return;
38639
+ found.push(diagnostic("project.self-sign-up-stale", PROJECT_FILE, `/selfSignUpAccepted/objects/${i}`, { entry: `${entry.object.name}${entry.published === true ? " (published)" : ""}` }));
38640
+ });
38641
+ accepted?.grants.forEach((grant, i) => {
38642
+ const at = `/selfSignUpAccepted/grants/${i}`;
38643
+ const roleId = target.get(`${at}/role`);
38644
+ const objectId = target.get(`${at}/object`);
38645
+ if (roleId === void 0 || objectId === void 0) return;
38646
+ if (typeof grant.extent === "object" && !target.has(`${at}/extent/dimension`)) return;
38647
+ const extent = typeof grant.extent === "string" ? grant.extent : { dimensionId: target.get(`${at}/extent/dimension`) };
38648
+ const unused = grant.actions.filter((action, j) => !exposedGrants.has(grantKey(roleId, objectId, target.get(`${at}/actions/${j}`) ?? action, extent)));
38649
+ if (unused.length === 0) return;
38650
+ found.push(diagnostic("project.self-sign-up-stale", PROJECT_FILE, at, { entry: `${grant.role.name}: ${unused.map((a) => `${grant.object.name}.${a}`).join(", ")} (${typeof grant.extent === "string" ? grant.extent : grant.extent.dimension})` }));
38651
+ });
38652
+ return found;
38653
+ }
38406
38654
  }
38407
38655
  // src/compiler/author-units.ts
38408
38656
  /** Одна функція авторства на проєкт: тіло не залежить від таблиці. */
@@ -41421,7 +41669,7 @@ async function runStages(stage1, options = {}) {
41421
41669
  rights,
41422
41670
  roles,
41423
41671
  rightsProjection: projection.rows
41424
- }, stage1.objects, stage1.project)
41672
+ }, stage1.objects, stage1.project, stage2.references)
41425
41673
  ]);
41426
41674
  return {
41427
41675
  ok: !hasErrors(final),
@@ -42413,6 +42661,8 @@ function buildClientCatalog(runtime) {
42413
42661
  provider: runtime.provider,
42414
42662
  ...present("rightsSnapshot", runtime.rightsSnapshot),
42415
42663
  ...present("adoptedFacts", runtime.adoptedFacts),
42664
+ ...present("roles", runtime.roles),
42665
+ ...present("rightsSets", runtime.rightsSets),
42416
42666
  objects: runtime.objects.map(entryOf)
42417
42667
  };
42418
42668
  }
@@ -43540,7 +43790,7 @@ function nodeAt$1(root, pointer) {
43540
43790
  * контейнера, тож нова колекція схеми стає доступною без змін тут.
43541
43791
  */
43542
43792
  async function addElement(files, input, o) {
43543
- const supplied = refuseSuppliedId(files, input.element, "element");
43793
+ const supplied = refuseSuppliedId(files, input.element, "element") ?? refuseSuppliedId(files, input.objects ?? [], "objects");
43544
43794
  if (supplied !== void 0) return supplied;
43545
43795
  const clean = await compileInput(files, { repair: true });
43546
43796
  if (!clean.ok) return clean.result;
@@ -43562,6 +43812,26 @@ async function addElement(files, input, o) {
43562
43812
  if (JSON.parse(files.get(object.file)).scope !== void 0) return scopesRefused("table-scoped", table);
43563
43813
  }
43564
43814
  }
43815
+ const created = /* @__PURE__ */ new Map();
43816
+ if (input.objects !== void 0) {
43817
+ if (input.target.kind !== "Project" || input.collection !== "scopeKinds") return refused(files, [diagnostic("operation.input-invalid", "", "", {
43818
+ objects: "target",
43819
+ at: "/objects"
43820
+ })]);
43821
+ for (const object of input.objects) {
43822
+ const path = `${KIND_REGISTRY[object.kind].dir}/${object.name}/${object.name}.meta.json`;
43823
+ const existing = clean.model.objects.find((o) => o.kind === object.kind && o.name === object.name);
43824
+ if (existing !== void 0 || files.has(path) || created.has(path)) return refused(files, [diagnostic("operation.object-exists", existing?.file ?? path, "", {
43825
+ kind: object.kind,
43826
+ name: object.name
43827
+ })]);
43828
+ created.set(path, {
43829
+ ...object.data,
43830
+ kind: object.kind,
43831
+ name: object.name
43832
+ });
43833
+ }
43834
+ }
43565
43835
  const collections = [...namedCollections(container.schema).keys()];
43566
43836
  if (!collections.includes(input.collection)) return refused(files, [diagnostic("operation.collection-unknown", container.file, container.pointer, {
43567
43837
  collection: input.collection,
@@ -43585,6 +43855,10 @@ async function addElement(files, input, o) {
43585
43855
  changed.set(object.file, JSON.stringify(tableRaw));
43586
43856
  only.add(object.file);
43587
43857
  }
43858
+ for (const [path, raw] of created) {
43859
+ changed.set(path, JSON.stringify(raw));
43860
+ only.add(path);
43861
+ }
43588
43862
  const after = await toPlatformFormsAfter(files, changed);
43589
43863
  return completeAndCompile(files, after.files, o, only, clean.accepted, after.diagnostics);
43590
43864
  }
@@ -43814,7 +44088,12 @@ const addElementInput = z.strictObject({
43814
44088
  scopes: z.record(z.string(), z.strictObject({
43815
44089
  scope: z.string().min(1),
43816
44090
  scopeColumn: elementNameSchema.optional()
43817
- })).optional().meta({ description: "Only for collection scopeKinds of Project: declares the scope of adopted CustomTables in the same change, keyed by table name, e.g. { Orders: { scope: \"org\", scopeColumn: \"org\" } }; a table that already has a scope is refused." })
44091
+ })).optional().meta({ description: "Only for collection scopeKinds of Project: declares the scope of adopted CustomTables in the same change, keyed by table name, e.g. { Orders: { scope: \"org\", scopeColumn: \"org\" } }; a table that already has a scope is refused." }),
44092
+ objects: z.array(z.strictObject({
44093
+ kind: metadataKindSchema.meta({ description: void 0 }),
44094
+ name: objectNameSchema.meta({ description: void 0 }),
44095
+ data: z.record(z.string(), z.unknown()).optional()
44096
+ })).optional().meta({ description: "Only for collection scopeKinds of Project: new objects created in the same change, as { kind, name, data } of create, e.g. the scope root and the membership catalog with scope set to the new kind." })
43818
44097
  });
43819
44098
  const renameInput = z.strictObject({
43820
44099
  target: elementTarget,