simetra 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.
Files changed (35) hide show
  1. package/dist/channel-grant-BATD6oQu.js +15 -0
  2. package/dist/compiler/index.d.ts +684 -77
  3. package/dist/compiler/index.js +24598 -13501
  4. package/dist/data/centrifugo/index.d.ts +24 -0
  5. package/dist/data/centrifugo/index.js +173 -0
  6. package/dist/data/index.d.ts +27 -0
  7. package/dist/data/index.js +9779 -0
  8. package/dist/data/react/index.d.ts +103 -0
  9. package/dist/data/react/index.js +214 -0
  10. package/dist/grant-Zg0hmqK7.d.ts +11 -0
  11. package/dist/handle-C6PFsnUX.js +44 -0
  12. package/dist/holder-CkR-qRYU.d.ts +585 -0
  13. package/dist/model/index.d.ts +4118 -476
  14. package/dist/model/index.js +4267 -380
  15. package/dist/schema/index.d.ts +1523 -572
  16. package/dist/schema/index.js +11698 -7402
  17. package/dist/server/index.d.ts +665 -21
  18. package/dist/server/index.js +4279 -426
  19. package/dist/server/signals/index.d.ts +92 -0
  20. package/dist/server/signals/index.js +140 -0
  21. package/dist/shell/index.d.ts +100 -0
  22. package/dist/shell/index.js +148 -0
  23. package/dist/ui/index.d.ts +213 -0
  24. package/dist/ui/index.js +1075 -0
  25. package/package.json +74 -3
  26. package/schemas/accumulation-registers.schema.json +46 -5
  27. package/schemas/catalogs.schema.json +110 -7
  28. package/schemas/constants.schema.json +31 -5
  29. package/schemas/custom-tables.schema.json +24 -0
  30. package/schemas/documents.schema.json +83 -5
  31. package/schemas/functions.schema.json +129 -0
  32. package/schemas/information-registers.schema.json +47 -5
  33. package/schemas/project.schema.json +11 -1
  34. package/schemas/rights-sets.schema.json +3 -1
  35. package/schemas/roles.schema.json +6 -2
@@ -1,9 +1,9 @@
1
1
  import { z } from "zod";
2
- import { AttributeCase, CatalogUnit, CustomTable, DatabaseProvider, Dml, GrantPurpose, KIND_REGISTRY, LocalizedString, LogicalType, MetadataKind, MetadataRef, NumberingSpec, PhysicalColumn, PhysicalOrigin, PhysicalSnapshot, PhysicalTable, Project, ReferenceRole, RequestRolePurpose, RightsSystemCatalog, RuntimeCatalog, SchemaRule, SqlUnitClass, StandardColumnDef, SubscriptionEvent, VirtualTableKind } from "simetra/model";
2
+ import { AttributeCase, CatalogTable, CatalogUnit, ClientCatalog, CustomTable, DatabaseProvider, Dml, GrantPurpose, IdentitySource, KIND_REGISTRY, LocalizedString, LogicalType, MetadataKind, MetadataRef, NumberingSpec, ObjectOrigin, ObjectTable, PhysicalColumn, PhysicalSnapshot, PhysicalTable, Project, ReferenceRole, RequestRolePurpose, RightsSystemCatalog, RuntimeCatalog, RuntimeObject, SchemaRule, SqlFunctionDeclaration, SqlUnitClass, StandardColumnDef, SubscriptionEvent, VirtualTableKind } from "simetra/model";
3
3
  import { Constraint, IndexElem, IndexStmt, Node, Node as Node$1, RangeVar } from "libpg-query";
4
4
  type Severity = "error" | "warning";
5
5
  /** Коди правил самого компілятора; коди перевірок схем T0 — `SCHEMA_RULES`. */
6
- export declare const COMPILER_RULES: readonly ["project.missing", "project.timezone-unknown", "project.database-required", "file.unknown-path", "file.orphan", "file.invalid-json", "file.schema", "file.unknown-key", "file.kind-mismatch", "file.name-mismatch", "file.movements-block", "file.movements-marker-indented", "sql.parse", "sql.statement-not-allowed", "sql.unit-duplicate", "sql.namespace-conflict", "sql.generated-grant", "sql.kind-table-verbatim", "sql.function-body-statement", "sql.platform-function-call", "sql.expression-call-not-allowed", "sql.dependency-cycle", "sql.closed-shell", "sql.command-context-write", "sql.head-not-allowed", "sql.domain-check-not-allowed", "sql.function-settings-shell", "sql.function-overload", "sql.row-rule-grammar", "sql.row-rule-foreign-table", "sql.row-rule-outside-module", "sql.row-rule-name-taken", "sql.bare-current-user", "sql.debt-grows", "sql.debt-stale", "sql.debt-session-write", "sql.debt-extension-schema", "sql.definer-reads-rls", "rewrite.ambiguous-name", "rewrite.unqualified-table", "rewrite.unsupported", "rewrite.trigger-binding", "rewrite.label-literal", "rewrite.dynamic-sql", "rewrite.unresolved-type", "rewrite.body-quoting", "rewrite.verification-failed", "rewrite.contract-change", "rewrite.dynamic-sql-unscoped", "identity.id-missing", "identity.id-duplicate", "identity.physical-name-missing", "identity.kind-label-missing", "identity.kind-label-retained", "identity.kind-label-duplicate", "identity.assigned-once-changed", "identity.name-duplicate", "identity.name-case", "identity.name-reserved", "reference.unresolved", "reference.ambiguous", "customTable.column-unknown", "register.balance-control-resource", "register.balance-control-duplicate", "posting.field-unknown", "posting.register-field-unknown", "posting.tabular-section-unknown", "scope.declaration-missing", "scope.unknown-kind", "scope.attribute-name-collision", "scope.root-duplicate", "scope.root-key", "scope.root-hierarchy", "scope.root-declaration", "scope.root-self-reference", "scope.root-cascade-not-kind", "scope.global-to-scoped", "scope.cross-kind", "scope.recorder-mismatch", "scope.custom-table-column", "scope.cross-scope-redundant", "scope.custom-table-cross-tenant", "scope.set-function-missing", "scope.set-function-signature", "scope.membership-missing", "storage.bucket-duplicate", "storage.scope-kind-unknown", "subscription.source-not-table", "subscription.provider-table-unknown", "subscription.when-changed-unknown", "subscription.when-changed-duplicate", "subscription.source-duplicate", "subscription.name-duplicate", "subscription.when-changed-on-delete", "subscription.handler-missing", "subscription.handler-signature", "subscription.handler-not-closed", "subscription.handler-assigns-mechanics", "subscription.handler-assigns-carrier", "subscription.handler-reads-carrier", "subscription.trigger-name-taken", "subscription.when-changed-mechanics", "users.catalog-duplicate", "users.scope-not-none", "users.description-required", "users.provision-unsafe", "users.catalog-missing", "membership.not-scoped", "membership.user-not-users-ref", "membership.duplicate", "rights.action-unknown", "rights.custom-action-reserved", "rights.custom-action-effects", "rights.requires-cycle", "rights.attribute-unknown", "rights.carrier-not-ref", "rights.carrier-cross-tenant", "rights.carrier-column-taken", "rights.carrier-path-adopted", "rights.register-access-dimension", "rights.dimension-name-reserved", "rights.ownership-target", "rights.container-target", "rights.container-self", "rights.dimension-unknown", "rights.dimension-target", "rights.dimension-relation", "rights.access-target", "rights.access-duplicate", "rights.dimension-function-missing", "rights.dimension-function-signature", "rights.dimension-function-reads-rights", "rights.source-table", "rights.source-forced-rls", "rights.source-member-key", "rights.source-member-unique", "rights.source-column-type", "rights.source-where", "rights.source-role-key", "rights.source-scope-column", "rights.membership-source-duplicate", "rights.source-container-column", "rights.scope-kind-unknown", "rights.users-missing", "rights.public-read-forbidden", "rights.include-target", "rights.include-cycle", "rights.scope-without-membership", "rights.full-access-level", "rights.root-creator-level", "rights.root-creator-duplicate", "rights.root-creator-membership", "rights.root-creator-set-function", "rights.root-creator-assignments", "rights.root-creator-assignment-required", "rights.root-creator-subscription", "rights.root-create-author", "rights.root-creator-no-admin", "rights.root-creator-unreachable", "rights.source-unknown", "rights.source-key-level", "rights.source-key-duplicate", "rights.grant-level", "rights.extent-unsupported", "rights.requires-missing", "rights.custom-table-no-contract", "rights.object-without-rights", "rights.custom-action-multi-object", "rights.system-catalog-missing", "rights.system-catalog-duplicate", "rights.system-catalog-scope", "rights.system-catalog-description", "rights.system-catalog-parallel", "rights.system-catalog-custom-action", "rights.adopted-source-writes", "rights.scope-kind-unread", "rights.snapshot-source-unknown", "rights.snapshot-exempt-writer", "reference.not-referenceable", "reference.custom-table-key", "reference.custom-table-deferrable-key", "reference.default-to-table", "reference.default-unknown-value", "reference.polymorphic-target-kind", "attribute.unique-within-place", "index.attribute-unknown", "index.attribute-duplicate", "catalog.owner-kind", "register.recorder-kind", "posting.register-kind", "posting.register-independent", "posting.register-undeclared", "posting.source-missing", "posting.source-ambiguous", "posting.query-not-select", "posting.query-order-missing", "posting.recorder-not-allowed", "posting.fields-incomplete", "posting.row-in-document-source", "posting.aggregate-in-section-source", "posting.movement-type", "posting.period-not-allowed", "posting.type-mismatch", "physical.table-duplicate", "physical.relation-duplicate", "physical.column-duplicate", "physical.function-duplicate", "physical.reserved-word", "physical.name-too-long", "physical.constraint-name-required", "customTable.foreign-key-arity", "customTable.foreign-key-deferrable-target", "customTable.fk-action-on-kind-table", "customTable.fk-target-not-key", "customTable.generated-conflict", "customTable.key-column-nullable", "presentation.unknown-standard-attribute", "operation.physical-name-too-long", "operation.input-invalid", "operation.target-not-found", "operation.object-exists", "operation.collection-unknown", "operation.delete-referenced", "promote.column-unplaced", "promote.mapping-unknown", "promote.unit-unsupported", "promote.reference-not-promoted", "promote.retired-referenced", "promote.unclassified", "promote.write-path", "promote.debt-writes-table", "promote.cascade-to-restrict", "promote.provider-user-reference", "promote.enum-labels", "promote.type-unsupported", "promote.default-unplaced", "promote.fill-missing", "promote.expression-invalid", "promote.debt-text-reference", "promote.text-conflict", "promote.property-not-equivalent", "engine.diagnostic", "engine.unmodeled-drift", "engine.shadow-load-failed", "engine.desired-rejected", "engine.clone-failed", "engine.preamble-unknown", "engine.unrepresentable", "engine.unmodeled-class", "engine.census-mismatch", "engine.unmodeled-property", "engine.out-of-scope", "engine.owner-not-member", "apply.state-format", "apply.ledger-without-marker", "apply.cascade", "apply.non-transactional", "apply.commit-boundary", "apply.permission-required", "apply.permission-unknown", "apply.first-apply", "apply.drift", "apply.drift-partial", "apply.versions-changed", "apply.plan-versions", "apply.plan-format", "apply.plan-hash", "apply.plan-stale", "apply.busy", "apply.api-role", "apply.server-unsupported", "apply.role-mismatch", "apply.chain", "apply.target-changed", "apply.verify-failed", "apply.step-failed", "apply.lock-timeout", "apply.lock-privilege", "apply.lock-footprint-exceeded", "apply.connection-lost", "apply.type-narrowing", "apply.type-guard-failed", "apply.preservation-failed", "apply.preservation-measure-failed", "apply.function-check-failed", "apply.function-check-blind", "apply.deferred-constraint-failed", "apply.constraint-invalid", "apply.rehearsal-proof-failed", "apply.rehearsal-required", "apply.rehearsal-stale", "apply.rehearsal-copy-empty", "apply.rehearsal-fewer-rows", "apply.rehearsal-timeout-unbounded", "apply.temp-name-taken", "apply.plpgsql-check-unavailable", "apply.replication-role", "apply.data-step-failed", "apply.data-step-narrowing", "apply.data-write-mismatch", "plan.unparsable-step", "plan.clone-mismatch", "plan.proof-not-empty", "plan.fingerprint-disagrees", "plan.schema-only-proof", "plan.owner-mismatch", "plan.platform-role-missing", "plan.platform-role-shape", "plan.type-guard-unsupported", "plan.type-change-dependent", "plan.promotion-record-missing", "plan.promotion-record-invalid", "plan.promotion-base", "plan.promotion-record-mismatch", "plan.promotion-record-stale", "plan.promotion-needs-marker", "plan.promotion-multiple", "plan.promotion-unsupported", "plan.promotion-applied", "plan.promotion-not-applicable", "plan.rename-not-realized", "plan.removal-unclassified", "plan.platform-replacement-missing", "plan.property-not-reproduced", "plan.write-path", "plan.service-role-access-lost", "plan.update-of-narrowed", "plan.foreign-exclusive-lock", "plan.plpgsql-check-unavailable", "plan.temp-name-taken", "plan.data-step-volatile", "plan.data-step-function-changed", "plan.temp-privilege", "plan.replication-role", "plan.preservation-type", "plan.provider-trigger-taken", "plan.numbering-not-generated", "plan.rights-source-access", "plan.rights-source-unknown-keys", "plan.rights-full-access-lost", "plan.rights-orphans", "database.failed", "roles.create-role-denied", "roles.admin-option-missing", "maintenance.model-mismatch", "maintenance.unknown-role", "maintenance.role-level", "maintenance.role-ambiguous", "maintenance.unknown-scope-kind", "maintenance.no-catalog", "maintenance.scope-missing", "maintenance.unknown-user", "maintenance.busy", "maintenance.not-first", "maintenance.holder-exists", "maintenance.not-effective", "maintenance.invalid-member", "maintenance.member-required", "maintenance.refused", "maintenance.outcome-unknown", "introspect.unrepresentable", "introspect.identity-conflict", "introspect.project-mismatch", "introspect.path-collision"];
6
+ export declare const COMPILER_RULES: readonly ["project.missing", "project.timezone-unknown", "project.database-required", "file.unknown-path", "file.orphan", "file.invalid-json", "file.schema", "file.unknown-key", "file.kind-mismatch", "file.name-mismatch", "file.movements-block", "file.movements-marker-indented", "sql.parse", "sql.statement-not-allowed", "sql.unit-duplicate", "sql.namespace-conflict", "sql.generated-grant", "sql.kind-table-verbatim", "sql.function-body-statement", "sql.function-body-session-setting", "sql.function-body-temp-type", "sql.function-body-session-builtin", "sql.platform-function-call", "sql.expression-call-not-allowed", "sql.dependency-cycle", "sql.closed-shell", "sql.command-context-write", "sql.head-not-allowed", "sql.domain-check-not-allowed", "sql.function-settings-shell", "sql.head-settings", "sql.function-overload", "sql.row-rule-grammar", "sql.row-rule-foreign-table", "sql.row-rule-outside-module", "sql.row-rule-name-taken", "sql.bare-current-user", "sql.debt-grows", "sql.debt-stale", "sql.debt-session-write", "sql.debt-extension-schema", "sql.definer-reads-rls", "sql.definer-caller-unchecked", "sql.policy-helper-correlated", "sql.declaration-target-missing", "sql.declaration-overload", "sql.declaration-duplicate", "sql.declaration-platform-form", "sql.declaration-platform-form-widens", "sql.declaration-execute-widened", "sql.declaration-check-missing", "sql.declaration-check-form", "sql.declaration-check-not-applied", "sql.declaration-anonymous-definer", "sql.default-privileges-execute", "sql.function-argument-type-reference", "rewrite.ambiguous-name", "rewrite.unqualified-table", "rewrite.unsupported", "rewrite.trigger-binding", "rewrite.label-literal", "rewrite.dynamic-sql", "rewrite.unresolved-type", "rewrite.body-quoting", "rewrite.verification-failed", "rewrite.contract-change", "rewrite.dynamic-sql-unscoped", "identity.id-missing", "identity.id-duplicate", "identity.physical-name-missing", "identity.kind-label-missing", "identity.kind-label-retained", "identity.kind-label-duplicate", "identity.assigned-once-changed", "identity.name-duplicate", "identity.name-case", "identity.name-reserved", "identity.name-structural", "reference.unresolved", "reference.ambiguous", "customTable.column-unknown", "customTable.index-derived-column", "register.balance-control-resource", "register.balance-control-duplicate", "posting.field-unknown", "posting.register-field-unknown", "posting.tabular-section-unknown", "scope.declaration-missing", "scope.unknown-kind", "scope.attribute-name-collision", "scope.root-duplicate", "scope.root-key", "scope.root-hierarchy", "scope.root-declaration", "scope.root-self-reference", "scope.root-cascade-not-kind", "scope.global-to-scoped", "scope.cross-kind", "scope.recorder-mismatch", "scope.custom-table-column", "scope.cross-scope-redundant", "scope.custom-table-cross-tenant", "scope.set-function-missing", "scope.set-function-signature", "scope.membership-missing", "storage.bucket-duplicate", "storage.scope-kind-unknown", "subscription.source-not-table", "subscription.provider-table-unknown", "subscription.when-changed-unknown", "subscription.when-changed-duplicate", "subscription.source-duplicate", "subscription.name-duplicate", "subscription.when-changed-on-delete", "subscription.handler-missing", "subscription.handler-signature", "subscription.handler-not-closed", "subscription.handler-assigns-mechanics", "subscription.handler-assigns-carrier", "subscription.handler-reads-carrier", "subscription.trigger-name-taken", "subscription.when-changed-mechanics", "users.catalog-duplicate", "users.scope-not-none", "users.description-required", "users.provision-unsafe", "users.catalog-missing", "languages.catalog-duplicate", "languages.scope-not-none", "languages.code-form", "languages.description-required", "languages.public-read", "languages.predefined-items", "languages.seed-unsafe", "languages.primary-missing", "languages.primary-without-catalog", "membership.not-scoped", "membership.user-not-users-ref", "membership.duplicate", "rights.action-unknown", "rights.custom-action-reserved", "rights.custom-action-effects", "rights.requires-cycle", "rights.attribute-unknown", "rights.carrier-not-ref", "rights.carrier-cross-tenant", "rights.carrier-column-taken", "rights.carrier-path-adopted", "rights.carrier-lazy", "rights.register-access-dimension", "rights.dimension-name-reserved", "rights.ownership-target", "rights.container-target", "rights.container-self", "rights.dimension-unknown", "rights.dimension-target", "rights.dimension-relation", "rights.access-target", "rights.access-duplicate", "rights.dimension-function-missing", "rights.dimension-function-signature", "rights.dimension-function-reads-rights", "rights.source-table", "rights.source-forced-rls", "rights.source-member-key", "rights.source-member-unique", "rights.source-column-type", "rights.source-where", "rights.source-role-key", "rights.source-scope-column", "rights.membership-source-duplicate", "rights.source-container-column", "rights.scope-kind-unknown", "rights.users-missing", "rights.public-read-forbidden", "rights.public-read-published-kind", "rights.public-read-published-rights", "rights.public-read-published-read", "rights.include-target", "rights.include-cycle", "rights.scope-without-membership", "rights.full-access-level", "rights.root-creator-level", "rights.root-creator-duplicate", "rights.root-creator-membership", "rights.root-creator-set-function", "rights.root-creator-assignments", "rights.root-creator-assignment-required", "rights.root-creator-subscription", "rights.root-create-author", "rights.root-creator-no-admin", "rights.root-creator-unreachable", "rights.source-unknown", "rights.source-key-level", "rights.source-key-duplicate", "rights.grant-level", "rights.extent-unsupported", "rights.requires-missing", "rights.custom-table-no-contract", "rights.object-without-rights", "rights.custom-action-multi-object", "rights.system-catalog-missing", "rights.system-catalog-duplicate", "rights.system-catalog-scope", "rights.system-catalog-description", "rights.system-catalog-parallel", "rights.system-catalog-custom-action", "rights.adopted-source-writes", "rights.scope-kind-unread", "project.self-sign-up", "rights.snapshot-source-unknown", "rights.snapshot-exempt-writer", "rights.signal-source-unknown", "reference.not-referenceable", "reference.custom-table-key", "reference.custom-table-deferrable-key", "reference.default-to-table", "reference.default-unknown-value", "reference.polymorphic-target-kind", "attribute.unique-within-place", "attribute.row-over-budget", "attribute.lazy-over-budget", "index.attribute-unknown", "index.attribute-duplicate", "index.attribute-rich-text", "search.field-unknown", "search.field-duplicate", "search.field-tabular", "search.field-ref", "search.field-generated", "search.field-rich-text", "catalog.owner-kind", "register.recorder-kind", "posting.register-kind", "posting.register-independent", "posting.register-undeclared", "posting.source-missing", "posting.source-ambiguous", "posting.query-not-select", "posting.query-order-missing", "posting.recorder-not-allowed", "posting.fields-incomplete", "posting.row-in-document-source", "posting.aggregate-in-section-source", "posting.movement-type", "posting.period-not-allowed", "posting.type-mismatch", "physical.table-duplicate", "physical.relation-duplicate", "physical.column-duplicate", "physical.function-duplicate", "physical.reserved-word", "physical.name-too-long", "physical.constraint-name-required", "customTable.foreign-key-arity", "customTable.foreign-key-deferrable-target", "customTable.fk-action-on-kind-table", "customTable.fk-target-not-key", "customTable.generated-conflict", "customTable.key-column-nullable", "presentation.unknown-standard-attribute", "operation.physical-name-too-long", "operation.input-invalid", "operation.target-not-found", "operation.object-exists", "operation.collection-unknown", "operation.delete-referenced", "promote.column-unplaced", "promote.mapping-unknown", "promote.unit-unsupported", "promote.reference-not-promoted", "promote.retired-referenced", "promote.unclassified", "promote.write-path", "promote.debt-writes-table", "promote.cascade-to-restrict", "promote.provider-user-reference", "promote.enum-labels", "promote.type-unsupported", "promote.default-unplaced", "promote.fill-missing", "promote.expression-invalid", "promote.debt-text-reference", "promote.text-conflict", "promote.property-not-equivalent", "engine.diagnostic", "engine.unmodeled-drift", "engine.shadow-load-failed", "engine.shadow-drop-failed", "engine.desired-rejected", "engine.clone-failed", "engine.environment-failed", "engine.preamble-unknown", "engine.unrepresentable", "engine.unmodeled-class", "engine.census-mismatch", "engine.unmodeled-property", "engine.out-of-scope", "engine.owner-not-member", "apply.state-format", "apply.ledger-without-marker", "apply.cascade", "apply.non-transactional", "apply.commit-boundary", "apply.permission-required", "apply.permission-unknown", "apply.first-apply", "apply.drift", "apply.drift-partial", "apply.drift-unverifiable", "apply.versions-changed", "apply.primary-language-changed", "apply.plan-versions", "apply.plan-format", "apply.plan-hash", "apply.plan-stale", "apply.busy", "apply.api-role", "apply.server-unsupported", "apply.role-mismatch", "apply.chain", "apply.target-changed", "apply.verify-failed", "apply.step-failed", "apply.lock-timeout", "apply.lock-privilege", "apply.lock-footprint-exceeded", "apply.connection-lost", "apply.type-narrowing", "apply.type-guard-failed", "apply.preservation-failed", "apply.preservation-measure-failed", "apply.function-check-failed", "apply.function-check-blind", "apply.deferred-constraint-failed", "apply.constraint-invalid", "apply.rehearsal-proof-failed", "apply.rehearsal-required", "apply.rehearsal-stale", "apply.rehearsal-copy-empty", "apply.rehearsal-fewer-rows", "apply.rehearsal-timeout-unbounded", "apply.temp-name-taken", "apply.plpgsql-check-unavailable", "apply.replication-role", "apply.data-step-failed", "apply.data-step-narrowing", "apply.data-write-mismatch", "apply.not-null-violation", "apply.backfill-rows-changed", "apply.backfill-triggers-changed", "plan.unparsable-step", "plan.clone-mismatch", "plan.proof-not-empty", "plan.fingerprint-disagrees", "plan.schema-only-proof", "plan.owner-mismatch", "plan.platform-role-missing", "plan.platform-role-shape", "plan.owner-not-bypassrls", "plan.owner-provider-login", "plan.shadow-base-unsupported", "plan.identity-table-missing", "plan.identity-trigger-locked", "plan.storage-added", "plan.storage-removed", "plan.type-guard-unsupported", "plan.type-change-dependent", "plan.promotion-record-missing", "plan.promotion-record-invalid", "plan.promotion-base", "plan.promotion-record-mismatch", "plan.promotion-record-stale", "plan.promotion-needs-marker", "plan.promotion-multiple", "plan.promotion-unsupported", "plan.promotion-applied", "plan.promotion-not-applicable", "plan.rename-not-realized", "plan.removal-unclassified", "plan.platform-replacement-missing", "plan.property-not-reproduced", "plan.write-path", "plan.service-role-access-lost", "plan.update-of-narrowed", "plan.foreign-exclusive-lock", "plan.plpgsql-check-unavailable", "plan.temp-name-taken", "plan.data-step-volatile", "plan.data-step-function-changed", "plan.temp-privilege", "plan.replication-role", "plan.preservation-type", "plan.provider-trigger-taken", "plan.provider-trigger-undeclared", "plan.trigger-function-unseedable", "plan.row-version-first", "plan.numbering-not-generated", "plan.not-null-violation", "plan.backfill-order", "plan.backfill-unique", "plan.backfill-check", "plan.backfill-carrier-source", "plan.backfill-rights-guard", "plan.backfill-count-failed", "plan.rights-source-access", "plan.rights-source-unknown-keys", "plan.rights-full-access-lost", "plan.rights-orphans", "database.failed", "roles.create-role-denied", "roles.admin-option-missing", "roles.membership-grant-denied", "roles.superuser-required", "roles.unsafe-schema", "roles.unsafe-template", "roles.database-owner", "roles.database-locale", "roles.shared-cluster", "maintenance.model-mismatch", "maintenance.unknown-role", "maintenance.role-level", "maintenance.role-ambiguous", "maintenance.unknown-scope-kind", "maintenance.no-catalog", "maintenance.scope-missing", "maintenance.unknown-user", "maintenance.busy", "maintenance.not-first", "maintenance.holder-exists", "maintenance.not-effective", "maintenance.invalid-member", "maintenance.member-required", "maintenance.refused", "maintenance.outcome-unknown", "introspect.unrepresentable", "introspect.identity-conflict", "introspect.project-mismatch", "introspect.path-collision", "introspect.definer-check-unknown", "introspect.execute-narrowed", "introspect.definer-platform-form-candidate", "introspect.definer-foreign-grant", "introspect.definer-callers-drift", "introspect.definer-acl-changed"];
7
7
  type CompilerRule = (typeof COMPILER_RULES)[number];
8
8
  type RuleCode = SchemaRule | CompilerRule;
9
9
  type DiagnosticParams = Record<string, string | number>;
@@ -36,6 +36,8 @@ interface Diagnostic {
36
36
  /** Заповнює `locate` для файлів, що є в мапі; відображення pointer → рядок і колонка. */
37
37
  range?: Range;
38
38
  }
39
+ /** Помилка, яку режим `repair` пропускає повз гейт стадій. */
40
+ export declare function isRepairError(d: Diagnostic): boolean;
39
41
  /** Діагностика з каталогу повідомлень; серйозність — властивість правила. */
40
42
  export declare function diagnostic(code: RuleCode, file: string, pointer: string, params?: DiagnosticParams): Diagnostic;
41
43
  /** Значення за JSON Pointer; `""` — сам корінь. */
@@ -128,14 +130,17 @@ interface ResolvedReference {
128
130
  /** 1-базний рядок маркера в `.sql`: pointer на весь файл місця не вказує. */
129
131
  line?: number;
130
132
  }
131
- /** CHECK таблиці та єдина колонка його виразу. */
133
+ /**
134
+ * CHECK таблиці та колонки, які читає його вираз, у порядку колонок таблиці:
135
+ * одна — для CHECK реквізиту, кілька — для правила рядка.
136
+ */
132
137
  interface CheckColumn {
133
138
  table: {
134
139
  schema: string;
135
140
  name: string;
136
141
  };
137
142
  check: string;
138
- column: string;
143
+ columns: string[];
139
144
  }
140
145
  /** Форма ключа цілі FK на таблицю виду (спека прав §4.7). */
141
146
  type KindKey = Extract<CustomTable["foreignKeys"][number]["references"], {
@@ -252,7 +257,12 @@ interface SqlUnit {
252
257
  requires?: readonly CreationNode[];
253
258
  }
254
259
  /** Хто згенерував одиницю. */
255
- type UnitGenerator = "movementQuery" | "membership" | "platformLayer" | "access" | "functionExecute" | "mechanics" | "key" | "subscription" | "rights" | "rightsGuards" | "rightsExplain" | "carriers" | "command" | "effects" | "catalogCommand";
260
+ type UnitGenerator = "movementQuery" | "membership" | "platformLayer" | "access" | "functionExecute" | "mechanics" | "key" | "subscription" | "rights" | "rightsGuards" | "rightsRequire" | "rightsExplain" | "carriers" | "command" | "effects" | "catalogCommand" | "schemaUsage" | "signalOutbox" | "storage" | "signal" | "rightsClientSnapshot" | "rightsSignal";
261
+ /**
262
+ * Чи одиниця — тіло, фіксоване платформою (`FIXED_BODY`): одне джерело і для
263
+ * `plpgsql_check`, і для еталона теки в reverse.
264
+ */
265
+ export declare function hasFixedBody(unit: Pick<SqlUnit, "generator">): boolean;
256
266
  /**
257
267
  * Сигнатури функцій платформи (`<схема>.<ім'я>(<типи>)`, як у ідентичності)
258
268
  * — ознака за походженням одиниці, а не за схемою. Типи аргументів
@@ -260,6 +270,17 @@ type UnitGenerator = "movementQuery" | "membership" | "platformLayer" | "access"
260
270
  * `to_regprocedure` незалежно від шляху.
261
271
  */
262
272
  export declare function platformFunctionSignatures(units: readonly Pick<SqlUnit, "class" | "identity" | "file" | "generator">[]): string[];
273
+ /** Обгортка запиту рухів: поля рухів обов'язкові. */
274
+ interface MovementQueryUnit extends SqlUnit {
275
+ class: "movementQuery";
276
+ generator: "movementQuery";
277
+ ownerObjectId: string;
278
+ queryTree: unknown;
279
+ registerId: string;
280
+ documentId: string;
281
+ source: "query" | "constructor";
282
+ }
283
+ export declare function isMovementQuery(unit: SqlUnit): unit is MovementQueryUnit;
263
284
  /** Дослівна одиниця з місцем у файлі; власника-об'єкт резолвить компілятор. */
264
285
  interface VerbatimUnit {
265
286
  class: SqlUnitClass;
@@ -297,6 +318,8 @@ interface SqlSource {
297
318
  schema: string;
298
319
  ownerFile?: string;
299
320
  }
321
+ /** Класи, що живуть у просторі імен функцій Postgres (`pg_proc`). */
322
+ export declare const FUNCTION_CLASSES: ReadonlySet<SqlUnitClass>;
300
323
  /**
301
324
  * Розбирає дослівні `.sql` на одиниці (платформна спека §6.3): гейт дозволених
302
325
  * операторів та ідентичність за класом. Блоки запиту рухів вирізано
@@ -318,6 +341,11 @@ export declare function readSqlUnits(sources: readonly SqlSource[], parse: SqlPa
318
341
  * зокрема тіло `$$…$$`, лишається дослівно — спека §8.3.
319
342
  */
320
343
  export declare function withoutLocations(value: unknown): unknown;
344
+ /**
345
+ * Ролі частини ідентичності гранту (`grantParts`) іменами каталогу: ім'я в
346
+ * лапках — без лапок, ключове слово (`public`) — як є.
347
+ */
348
+ export declare function grantRoles(roles: string): string[];
321
349
  interface QualifiedName {
322
350
  schema: string;
323
351
  name: string;
@@ -470,6 +498,42 @@ interface PredefinedContract {
470
498
  label: string;
471
499
  }[];
472
500
  }
501
+ /**
502
+ * Передвизначений рядок до засіву (Р-B2-7): крок даних apply вставляє його після
503
+ * DDL `INSERT … ON CONFLICT (<мітка>) WHERE <предикат> DO NOTHING`. Apply читає
504
+ * лише цей факт, а не `project.meta.json`; факт входить у хеш моделі, тож зміна
505
+ * поля проєкту, з якого взято рядок, не дає плану `unchanged` в обхід звірки.
506
+ * Імена колонок — фізичні.
507
+ */
508
+ interface PredefinedSeedContract {
509
+ objectId: string;
510
+ table: QualifiedName;
511
+ /**
512
+ * Колонка мітки, мітка рядка й предикат часткового унікального індексу мітки —
513
+ * арбітр `ON CONFLICT`.
514
+ */
515
+ label: {
516
+ column: string;
517
+ value: string;
518
+ where: string;
519
+ };
520
+ /** Ключ рядка: значення дає `gen_random_uuid()` засіву (DEFAULT ключа немає). */
521
+ keyColumn: string;
522
+ /** Значення колонок рядка, у порядку колонок таблиці. */
523
+ values: {
524
+ column: string;
525
+ value: string | boolean;
526
+ }[];
527
+ /**
528
+ * Звірка цілі перед засівом (Р-B2-8). `unique` — колонки, значення яких з
529
+ * `values` не може мати рядок без мітки; рядок з міткою мусить мати значення
530
+ * з `values` у колонках `unique` і `fixed`.
531
+ */
532
+ unique: string[];
533
+ fixed: string[];
534
+ /** Значення, яким діагностика звірки називає рядок (код основної мови). */
535
+ subject: string;
536
+ }
473
537
  /**
474
538
  * Нумерація першим записом (спека П2, М21): номер призначає оболонка при
475
539
  * першому записі; лічильники й генерацію — П3. Префікса поки немає.
@@ -577,6 +641,15 @@ interface AccessContract {
577
641
  };
578
642
  /** Ролі запиту, яким відкрито всі рядки: `anon` → обидві, `authenticated` → `user`. */
579
643
  publicRead: RequestRolePurpose[];
644
+ /**
645
+ * Умовна форма `publicRead` (спека публічної частини §5.1): фізичні колонки
646
+ * умови публікації цієї таблиці — на шапці її `published` і `deletion_mark`,
647
+ * на ТЧ — їхні копії. Немає — `publicRead` відкриває всі рядки.
648
+ */
649
+ published?: {
650
+ column: string;
651
+ mark: string;
652
+ };
580
653
  /** Основна таблиця кореня виду скоупу: без межі тенанта на `INSERT` (спека прав §5.2). */
581
654
  root: boolean;
582
655
  /**
@@ -598,6 +671,17 @@ interface AccessContract {
598
671
  update: string[];
599
672
  delete: boolean;
600
673
  };
674
+ /**
675
+ * Читання опублікованих рядків (Р-B2-5) — лише основної таблиці довідника
676
+ * з фактом ролі: фізичні колонка стану й колонки, які бачить гість.
677
+ * Політика `<t>_published_read` незалежна від функцій прав і від
678
+ * `publicRead`, а політики прав читання лишаються.
679
+ */
680
+ publishedRead?: {
681
+ stateColumn: string;
682
+ publishedState: string;
683
+ guestColumns: string[];
684
+ };
601
685
  }
602
686
  /** Обсяг, яким грант може обмежити дію (спека прав §3). */
603
687
  type RightsExtent = {
@@ -635,6 +719,11 @@ interface RightsAction {
635
719
  from?: boolean;
636
720
  to?: boolean;
637
721
  };
722
+ /** Пов'язана колонка: фізична колонка й її значення після дії (факт реєстру). */
723
+ coupled?: {
724
+ column: string;
725
+ value: boolean;
726
+ };
638
727
  extents: RightsExtent[];
639
728
  }
640
729
  /** Носій прав у таблиці: власна колонка або крок шляху (Рх21). */
@@ -685,7 +774,7 @@ interface RightsContract {
685
774
  root?: true;
686
775
  /**
687
776
  * Корінь: колонка автора (`createdBy`), коли вона — власний носій
688
- * власності. Лише її судить `create@own` кореня (спека прав §5.2, Р-A6-11).
777
+ * власності. Лише її судить `create@own` кореня (спека прав §5.2).
689
778
  */
690
779
  rootAuthor?: string;
691
780
  /** Стандартні дії в порядку реєстру, далі кастомні за `id`. */
@@ -916,6 +1005,8 @@ interface Contracts {
916
1005
  predefined: PredefinedContract[];
917
1006
  /** За `objectId`. */
918
1007
  numbering: NumberingContract[];
1008
+ /** За `objectId`: передвизначені рядки, які засіває apply (Р-B2-7). */
1009
+ predefinedSeeds: PredefinedSeedContract[];
919
1010
  /** За `table.schema`, далі `table.name`: кожна таблиця виду з RLS. */
920
1011
  access: AccessContract[];
921
1012
  /** За `bucket`: вид скоупу вказано id, бо ім'я виду може змінитися. */
@@ -947,7 +1038,7 @@ interface Contracts {
947
1038
  rightsCatalogs: RightsCatalogContract[];
948
1039
  }
949
1040
  /** Основна таблиця об'єкта (не ТЧ і не підсумки). */
950
- export declare function mainTableOf(physical: PhysicalSnapshot, objectId: string): PhysicalTable | undefined;
1041
+ export declare function mainTableOf(physical: PhysicalSnapshot, objectId: string): ObjectTable | undefined;
951
1042
  /**
952
1043
  * Імена тригерів копій носіїв на таблиці: `derive` — на таблиці з копіями,
953
1044
  * обидва тригери поширення — на таблиці-джерелі. `derive` — рядковий
@@ -977,8 +1068,8 @@ export declare function carrierFunctionNames(table: QualifiedName): {
977
1068
  * скоупу не дублюється.
978
1069
  */
979
1070
  interface CarrierLink {
980
- table: PhysicalTable;
981
- source: PhysicalTable;
1071
+ table: ObjectTable;
1072
+ source: ObjectTable;
982
1073
  through: string;
983
1074
  pairs: {
984
1075
  local: string;
@@ -1052,6 +1143,22 @@ interface PlpgsqlFunction {
1052
1143
  * мовчки: споживач сам вирішує, що робити з непрочитаним.
1053
1144
  */
1054
1145
  readonly unreadLines: readonly number[];
1146
+ /**
1147
+ * Зовнішній блок автора. Плаский `statements` не відрізняє його від
1148
+ * вкладених блоків і від синтетичної обгортки секції `EXCEPTION`, а доказ
1149
+ * запобіжника судить саме перший оператор цього блоку.
1150
+ */
1151
+ readonly author: PlpgsqlAuthorBlock;
1152
+ }
1153
+ interface PlpgsqlAuthorBlock {
1154
+ /**
1155
+ * Перший оператор блоку автора без фіктивного `RETURN`, який парсер додає
1156
+ * в кінець; `undefined`, коли блок порожній. Вирази — лише прямі, як у
1157
+ * `statements`.
1158
+ */
1159
+ readonly firstStatement?: PlpgsqlStatement;
1160
+ /** Блок автора має секцію `EXCEPTION` (парсер загортає його в обгортку). */
1161
+ readonly hasExceptionBlock: boolean;
1055
1162
  }
1056
1163
  interface PlpgsqlVariable {
1057
1164
  /** Ім'я, на яке може послатися автор; безіменних службових рядків тут немає. */
@@ -1144,7 +1251,7 @@ export declare function memberCheckFunctionName(table: QualifiedName): Qualified
1144
1251
  interface CatalogCommandContract {
1145
1252
  objectId: string;
1146
1253
  kindLabel: string;
1147
- table: PhysicalTable;
1254
+ table: ObjectTable;
1148
1255
  /** Колонка з `origin.scopeKindId`; у кореня виду скоупу — сам ключ. */
1149
1256
  scopeColumn?: string;
1150
1257
  key: string;
@@ -1152,6 +1259,9 @@ interface CatalogCommandContract {
1152
1259
  save: QualifiedName;
1153
1260
  markDeletion?: QualifiedName;
1154
1261
  delete?: QualifiedName;
1262
+ /** Ядра публікації — лише умовного об'єкта (Р-D1-11). */
1263
+ publish?: QualifiedName;
1264
+ unpublish?: QualifiedName;
1155
1265
  /** Ядро `create` кореня виду скоупу (спека П4 §6.13) — лише на корені. */
1156
1266
  createRoot?: QualifiedName;
1157
1267
  };
@@ -1161,6 +1271,8 @@ interface CatalogCommandContract {
1161
1271
  update: string;
1162
1272
  markDeletion?: string;
1163
1273
  delete?: string;
1274
+ publish?: string;
1275
+ unpublish?: string;
1164
1276
  createRoot?: string;
1165
1277
  };
1166
1278
  /** Ключі `p_item` створення й зміни (спека П4 §6.6) — з гранту ролі команд. */
@@ -1181,7 +1293,7 @@ interface CatalogCommandContract {
1181
1293
  }
1182
1294
  /** ТЧ довідника в контракті ядра; ключ ТЧ у `p_item.tabular` — `table.name`. */
1183
1295
  interface CatalogCommandSection {
1184
- table: PhysicalTable;
1296
+ table: ObjectTable;
1185
1297
  key: string;
1186
1298
  parent: string;
1187
1299
  lineNumber: string;
@@ -1208,6 +1320,11 @@ type CommandReference = {
1208
1320
  array: boolean;
1209
1321
  /** Свідомо між тенантами: ядро не звіряє скоуп цілі. */
1210
1322
  crossScope?: true;
1323
+ /**
1324
+ * Ціль — довідник «Користувачі» (роль реєстру `users`): значення, що
1325
+ * дорівнює `current_user_id()`, видиме без права на них (спека П4 §6.6).
1326
+ */
1327
+ users?: true;
1211
1328
  } | {
1212
1329
  form: "pair";
1213
1330
  typeColumn: string;
@@ -1216,7 +1333,7 @@ type CommandReference = {
1216
1333
  crossScope?: true;
1217
1334
  targets: {
1218
1335
  label: string;
1219
- table: PhysicalTable;
1336
+ table: ObjectTable;
1220
1337
  key: string;
1221
1338
  scopeColumn?: string;
1222
1339
  }[];
@@ -1260,6 +1377,132 @@ interface Presentation {
1260
1377
  defaultLocale: string;
1261
1378
  objects: PresentationBlock[];
1262
1379
  }
1380
+ /**
1381
+ * Форма платформи: функція, призначення якої задають метадані чи, для
1382
+ * функції політики, політики-викликачі (спека декларацій функцій §5.8).
1383
+ */
1384
+ type PlatformForm = "setFunction" | "subscriptionHandler" | "dimension" | "policyFunction";
1385
+ /** Чим функція виходить за закриту оболонку (спека промоції §9.4). */
1386
+ type ClosedShellProblem = "language" | "volatility" | "searchPath" | "dynamicSql" | "body";
1387
+ /** Одиниця, чию оболонку судять: дерево `CREATE FUNCTION` і його текст. */
1388
+ interface ShellUnit {
1389
+ tree: Node$1;
1390
+ sql: string;
1391
+ }
1392
+ /**
1393
+ * Закрита оболонка функції (спека П2 §3, «Дослівний SQL»): мова `sql` чи
1394
+ * `plpgsql`, явна волатильність, `SECURITY DEFINER` лише з `SET search_path
1395
+ * = ''`. Оболонка — те, що компілятор може перевірити статично: тіло лишається
1396
+ * кодом застосунку, а мова C чи неявна `VOLATILE` ховали б від рамки те, що
1397
+ * функція робить. Тіло plpgsql має розбиратися і не виконувати динамічний
1398
+ * SQL: рядок, зібраний під час виконання, не бачить ні граф залежностей, ні
1399
+ * рамка. Парсер plpgsql кличеться лише для `LANGUAGE plpgsql`: на тілі
1400
+ * `LANGUAGE sql … BEGIN ATOMIC` він аварійно завершується, і кожне тіло
1401
+ * стандарту SQL хибно вважалося б нерозбірним. Не функція (процедура, інший
1402
+ * оператор) — `undefined`: оболонка описує лише `CREATE FUNCTION`.
1403
+ */
1404
+ export declare function closedShellProblem(unit: ShellUnit, plpgsql: PlpgsqlParser): ClosedShellProblem | undefined;
1405
+ /**
1406
+ * Схема, куди `CREATE EXTENSION` ставить свої об'єкти (опція `SCHEMA`);
1407
+ * без неї — `undefined`: розширення стає в першу схему `search_path` сесії,
1408
+ * яка статично не відома.
1409
+ */
1410
+ export declare function extensionSchema(tree: unknown): string | undefined;
1411
+ /** Функція політики: форма пройдена, призначення `EXECUTE` виведено. */
1412
+ interface PolicyFunction {
1413
+ function: {
1414
+ schema: string;
1415
+ name: string;
1416
+ };
1417
+ unit: VerbatimUnit;
1418
+ /** Таблиця T, на якій стоять усі політики-викликачі. */
1419
+ table: {
1420
+ schema: string;
1421
+ name: string;
1422
+ };
1423
+ callers: readonly VerbatimUnit[];
1424
+ /** Призначення ролей `TO` політик-викликачів `SELECT`/`ALL` з `USING`. */
1425
+ purposes: readonly GrantPurpose[];
1426
+ }
1427
+ interface PolicyFunctions {
1428
+ functions: PolicyFunction[];
1429
+ /** `sql.policy-helper-correlated`: одна на функцію поза формою. */
1430
+ diagnostics: Diagnostic[];
1431
+ /**
1432
+ * Ідентичності одиниць цих діагностик: поки функція має
1433
+ * `sql.policy-helper-correlated`, інші коди ремонту тієї самої функції
1434
+ * вона поглинає (одна функція — одна причина ремонту, §5.8).
1435
+ */
1436
+ refused: string[];
1437
+ }
1438
+ /** Function with an EXECUTE group the platform derives (one entry per target). */
1439
+ interface ExecuteEntry {
1440
+ identity: string;
1441
+ schema: string;
1442
+ name: string;
1443
+ purposes: readonly GrantPurpose[];
1444
+ /** Set when the function is a platform form (the form decides the group). */
1445
+ form?: PlatformForm;
1446
+ }
1447
+ /**
1448
+ * Об'єкти, ACL яких належить платформі (платформна спека §6.7). Ключ —
1449
+ * `function|<сигнатура>` чи `table|<схема.ім'я>`: `grantTargetKeys`.
1450
+ * Функція — ціль будь-якої згенерованої одиниці `grant` (`functionExecute`,
1451
+ * членство, платформний шар); таблиця — лише таблиця з контрактом доступу,
1452
+ * тобто ціль грантів генератора `access`.
1453
+ */
1454
+ export declare function platformGrantTargets(units: readonly Pick<SqlUnit, "class" | "name" | "sql" | "file" | "generator">[], parse: SqlParser): Set<string>;
1455
+ /**
1456
+ * Чи ціль гранту — об'єкт платформи. `ON FUNCTION f` без списку аргументів
1457
+ * Postgres резолвить у єдину функцію з цим ім'ям, тож вона збігається з
1458
+ * функцією платформи тієї самої схеми й імені.
1459
+ */
1460
+ export declare function ownsTarget(owned: ReadonlySet<string>, target: string): boolean;
1461
+ /**
1462
+ * Цілі гранту-функції чи гранту-таблиці; ціль іншого виду (схема, тип,
1463
+ * послідовність) платформі в цьому правилі не належить, тож ключа не має.
1464
+ */
1465
+ export declare function grantTargetKeys(unit: Pick<SqlUnit, "class" | "name" | "sql">, parse: SqlParser): string[];
1466
+ /** Причини `sql.declaration-check-not-applied` (спека декларацій функцій §5.2). */
1467
+ type GuardReason = "language" | "declareSection" | "firstStatement" | "arguments" | "exceptionBlock";
1468
+ /**
1469
+ * Verdict of the call guard of one declared function, for `explain`: derived
1470
+ * from the same declarations and the same judge as `checkDeclaredGuards`, and
1471
+ * kept outside the model hash.
1472
+ */
1473
+ interface DeclaredFunctionState {
1474
+ schema: string;
1475
+ name: string;
1476
+ /** Declared callers (what the file says; not necessarily what is granted). */
1477
+ callers: SqlFunctionDeclaration["callers"];
1478
+ /** Purposes that really get EXECUTE: a platform form wins over the declaration. */
1479
+ purposes: readonly GrantPurpose[];
1480
+ check?: NonNullable<SqlFunctionDeclaration["check"]>;
1481
+ /** `none`: no check declared, or an invoker function (RLS judges it). */
1482
+ state: "applied" | "not-applied" | "none";
1483
+ /** Only for `not-applied`. */
1484
+ reason?: GuardReason;
1485
+ }
1486
+ /** Аргументи запобіжника виклику першого оператора тіла (читає зворотна генерація). */
1487
+ interface GuardArgs {
1488
+ /** Яка функція запобіжника: ціль `row` (`require`) чи `scope` (`requireScope`). */
1489
+ form: "require" | "requireScope";
1490
+ /** Рядок дії: ім'я стандартної дії або UUID кастомної. */
1491
+ action: string;
1492
+ /** Мітка виду об'єкта. */
1493
+ kindLabel: string;
1494
+ /** Параметр цілі; `null` — `NULL` (дія без цілі). */
1495
+ target: string | null;
1496
+ }
1497
+ /**
1498
+ * Читач аргументів запобіжника поруч із `guardOf`: той самий розбір форми
1499
+ * (plpgsql, без `DECLARE`, `PERFORM` єдиного прямого виклику першим
1500
+ * оператором, без `EXCEPTION`), але без декларації — зворотна генерація з
1501
+ * аргументів пише `check`. Нічого не повертає для тіла без запобіжника чи з
1502
+ * аргументами іншої форми (дві рядкові константи й голе ім'я чи `NULL`):
1503
+ * вигаданого `check` не буде.
1504
+ */
1505
+ export declare function guardArgsOf(unit: VerbatimUnit, plpgsql: PlpgsqlParser, parse: SqlParser): GuardArgs | undefined;
1263
1506
  interface SourceObject {
1264
1507
  id: string;
1265
1508
  kind: MetadataKind;
@@ -1333,11 +1576,18 @@ interface CompiledModel {
1333
1576
  */
1334
1577
  catalogCommands: CatalogCommandContract[];
1335
1578
  /**
1336
- * Колонка CHECK з однією колонкою виразу за призначеним іменем — для
1337
- * мапінгу `23514` каталогом рантайму (Р-A3-21). Похідне від знімка, тож
1579
+ * Колонки CHECK за призначеним іменем — колонка CHECK реквізиту чи
1580
+ * колонки, які читає правило рядка, — для мапінгу `23514` каталогом рантайму. Похідне від знімка, тож
1338
1581
  * канонічний знімок його не читає і хеш від нього не залежить.
1339
1582
  */
1340
1583
  checkColumns: CheckColumn[];
1584
+ /**
1585
+ * Колонки з позначкою `copy` (`copyColumns`) за таблицею `schema.table`,
1586
+ * лише таблиці з такими колонками. Похідне від знімка й парсера, тож
1587
+ * канонічний знімок його не читає і хеш від нього не залежить: поле знімка
1588
+ * змінило б `snapshotHash` кожного проєкту.
1589
+ */
1590
+ copyColumns: ReadonlyMap<string, ReadonlySet<string>>;
1341
1591
  /**
1342
1592
  * Спільний порядок створення енам-типів, таблиць і одиниць: розширення
1343
1593
  * перші, далі топологічно з tie-break (тип вузла, схема, ім'я/ідентичність).
@@ -1355,8 +1605,23 @@ interface CompiledModel {
1355
1605
  interface CompileResult {
1356
1606
  ok: boolean;
1357
1607
  diagnostics: Diagnostic[];
1358
- /** Лише коли прогін без помилок: наступні шари не бачать напівмоделі. */
1608
+ /**
1609
+ * Лише коли прогін без помилок: наступні шари не бачать напівмоделі. Режим
1610
+ * `repair` — виняток: модель є й тоді, коли кожна помилка — класу ремонту.
1611
+ */
1359
1612
  model?: CompiledModel;
1613
+ /**
1614
+ * Declared functions with the call-guard verdict, for `explain`. Present
1615
+ * together with the model but not part of it: the model hash does not
1616
+ * depend on declarations.
1617
+ */
1618
+ declaredFunctions?: DeclaredFunctionState[];
1619
+ /**
1620
+ * Functions whose EXECUTE the platform derives (declared, platform forms,
1621
+ * module functions), from the same groups as the grant generator; for
1622
+ * `explain`. Outside the model hash, like `declaredFunctions`.
1623
+ */
1624
+ functionExecute?: ExecuteEntry[];
1360
1625
  }
1361
1626
  interface CompileOptions {
1362
1627
  /**
@@ -1364,6 +1629,13 @@ interface CompileOptions {
1364
1629
  * призначені раз, звіряються з нею; немає — перевірки немає.
1365
1630
  */
1366
1631
  baseline?: ReadonlyMap<string, string>;
1632
+ /**
1633
+ * Режим ремонту (спека декларацій функцій §5.1): модель повертається й
1634
+ * тоді, коли кожна помилка — класу ремонту (`REPAIR_CLASS`), а `ok`
1635
+ * лишається `false`. Передають лише мутації, що лагодять теку крок за
1636
+ * кроком (`create`, `add`); без поля модель — лише з чистого прогону.
1637
+ */
1638
+ repair?: true;
1367
1639
  }
1368
1640
  /**
1369
1641
  * Компілятор — чиста функція над мапою «шлях відносно `metadata/` → вміст»
@@ -1372,6 +1644,12 @@ interface CompileOptions {
1372
1644
  * Асинхронна, бо парсер Postgres — WASM, який вантажиться один раз на процес.
1373
1645
  */
1374
1646
  export declare function compile(files: ReadonlyMap<string, string>, options?: CompileOptions): Promise<CompileResult>;
1647
+ /**
1648
+ * Функції політик теки (спека декларацій функцій §5.8) — той самий результат
1649
+ * розпізнавача, що бачить компілятор: операції, які судять форми платформи
1650
+ * (`toPlatformForms`, `declare-function`), будують його з тих самих одиниць.
1651
+ */
1652
+ export declare function formPolicies(files: ReadonlyMap<string, string>): Promise<PolicyFunctions>;
1375
1653
  /**
1376
1654
  * Повний борг дослівного SQL теки (спека П2 §8.6) —
1377
1655
  * відсортовані ідентичності одиниць, які ратчет вимагає мати в
@@ -1382,6 +1660,94 @@ export declare function compile(files: ReadonlyMap<string, string>, options?: Co
1382
1660
  * мовчки прибрало б справжні записи.
1383
1661
  */
1384
1662
  export declare function currentDebt(files: ReadonlyMap<string, string>): Promise<string[] | undefined>;
1663
+ /**
1664
+ * Імена політик таблиці (платформна спека §6.8, спека прав §5.2): мітка після
1665
+ * імені таблиці, як у Postgres, тож довга назва скорочується, а не перевищує
1666
+ * 63 байти. `rights` бере мітку обсягу без `read_` (`any`, `own_<колонка>`,
1667
+ * `in_<контейнер>_<обсяг>`, вимір): мітку понад 40 байтів цілком замінюють її
1668
+ * перші 31 байт, `_` і 8 hex-знаків `sha256` повної мітки (спека прав §5.2) — інакше
1669
+ * довгі мітки однієї таблиці після обрізання таблиці до нуля збіглися б.
1670
+ * `command<Dml>` — запобіжник контексту команди, `write` — політика запису
1671
+ * родини `root` чи `rest` з тією самою межею мітки.
1672
+ */
1673
+ export declare function accessPolicyNames(table: {
1674
+ name: string;
1675
+ }): {
1676
+ scopeRead: string;
1677
+ scopeInsert: string;
1678
+ scopeUpdate: string;
1679
+ scopeDelete: string;
1680
+ publicRead: string;
1681
+ publishedRead: string;
1682
+ commandInsert: string;
1683
+ commandUpdate: string;
1684
+ commandDelete: string;
1685
+ rights(label: string): string;
1686
+ write(dml: Dml, family: WriteFamily, label: string): string;
1687
+ };
1688
+ /** Родина політики запису (спека прав §5.3): кореневий рядок команди чи решта рядків. */
1689
+ type WriteFamily = "root" | "rest";
1690
+ /**
1691
+ * Контракти прав лише з метаданих, без SQL-стадій: зворотна генерація
1692
+ * розв'язує за ними мітку виду й дію запобіжника. `undefined` — метадані
1693
+ * не доходять до моделі (помилка стадій 1–3) чи контракти не будуються.
1694
+ */
1695
+ export declare function metadataRights(files: ReadonlyMap<string, string>): {
1696
+ objects: readonly {
1697
+ id: string;
1698
+ kind: MetadataKind;
1699
+ name: string;
1700
+ }[];
1701
+ rights: RightsContract[];
1702
+ } | undefined;
1703
+ /**
1704
+ * Ідентичність SQL-одиниці (спека П2 §3, §8.3): `<клас>:<ключ>`, де кожна
1705
+ * частина імені — за `quoteIdent`, а роздільники `.` `,` `:` `(` `)` стоять
1706
+ * лише поза лапками. Тож різні об'єкти Postgres мають різні ідентичності
1707
+ * (`"a.b".c` ≠ `a."b.c"`), а ключ функції — валідний підпис SQL. Цей модуль —
1708
+ * єдине місце, що складає й розбирає рядок ідентичності: склеєна вручну
1709
+ * частина без лапок знову зробила б ідентичність неін'єктивною (#297).
1710
+ */
1711
+ /**
1712
+ * Клас ідентичності: клас SQL-одиниці або об'єкт моделі (таблиця, енам-тип),
1713
+ * що ділить із одиницями простір міток — у конфліктах імен і графі
1714
+ * створення.
1715
+ */
1716
+ type IdentityClass = SqlUnitClass | "table" | "enumType";
1717
+ /** Кваліфіковане ім'я: частини за `quoteIdent` через `.`. */
1718
+ export declare function qualifiedName(...parts: readonly string[]): string;
1719
+ /** Ідентичність з ключем із частин імені: `view:public."V"`. */
1720
+ export declare function unitIdentity(cls: IdentityClass, ...parts: readonly string[]): string;
1721
+ /**
1722
+ * Ідентичність із готовим ключем: підписом (`signatureKey`) чи складеним
1723
+ * ключем гранту, коментаря, публікації. Частини такого ключа вже зібрано
1724
+ * функціями цього модуля.
1725
+ */
1726
+ export declare function keyIdentity(cls: IdentityClass, key: string): string;
1727
+ /** Ключ ідентичності: усе після класу (клас двокрапки не містить). */
1728
+ export declare function identityKey(identity: string): string;
1729
+ /**
1730
+ * Частини імені ключа з крапками (в'юха, тригер, політика:
1731
+ * схема, таблиця, ім'я) — імена каталогу, без лапок.
1732
+ */
1733
+ export declare function identityParts(identity: string): string[];
1734
+ /** Частина імені з ключа як ім'я каталогу: обернення `quoteIdent`. */
1735
+ export declare function unquoteIdent(part: string): string;
1736
+ /**
1737
+ * Частини ідентичності між роздільниками `separator` поза лапками й дужками:
1738
+ * роль чи ціль у лапках може містити і кому, і двокрапку.
1739
+ */
1740
+ export declare function splitIdentity(text: string, separator: string): string[];
1741
+ /**
1742
+ * Ключ функції з уже відрендерених типів аргументів: `схема.ім'я(т1,т2)`.
1743
+ * Агрегат без списку аргументів — тип `*`.
1744
+ */
1745
+ export declare function functionKey(schema: string, name: string, types: readonly string[]): string;
1746
+ /**
1747
+ * Names of the platform triggers on the identity table of the provider; the
1748
+ * map `TRIGGERS` stays their source.
1749
+ */
1750
+ export declare const IDENTITY_TRIGGERS: readonly string[];
1385
1751
  /**
1386
1752
  * Безпека самої схеми `simetra` (спека користувачів §3): `REVOKE ALL` від
1387
1753
  * `PUBLIC` і `USAGE` ролям API й ролі команд. Одна функція на два
@@ -1391,6 +1757,60 @@ export declare function currentDebt(files: ReadonlyMap<string, string>): Promise
1391
1757
  * описані.
1392
1758
  */
1393
1759
  export declare function platformSchemaGrants(provider: DatabaseProvider): string[];
1760
+ /**
1761
+ * What the platform installs in every database of a provider: the snapshot
1762
+ * tables with a platform origin (no owner object) and the units the compiler
1763
+ * generates for a project without any object.
1764
+ */
1765
+ interface PlatformInstall {
1766
+ tables: readonly PhysicalTable[];
1767
+ units: readonly SqlUnit[];
1768
+ }
1769
+ /**
1770
+ * The platform install of `provider`, derived from the compiled empty project
1771
+ * — the same generators that put it into every project, not a list per
1772
+ * object: a new platform table or unit appears here without a second edit.
1773
+ * It is a reference of `platformRecogniser`, which tells platform content
1774
+ * from the application's by content, not by name.
1775
+ */
1776
+ export declare function platformInstall(provider: DatabaseProvider): Promise<PlatformInstall>;
1777
+ /**
1778
+ * Atoms `<grant|revoke>|<class>|<object>|<role>|<privilege>` of a grant unit,
1779
+ * read from its identity
1780
+ * `grant:<grant|revoke>:<class>:<objects>:<roles>:<privileges>`; a column
1781
+ * privilege is one atom per column (`insert(method)`), and the grant option
1782
+ * stays on each atom (`select*`, `insert(method)*`), so a grant with the
1783
+ * option never matches an atom of the install, which gives none. Only for
1784
+ * identities without SQL (the plan of `diff`); a catalog unit is judged by
1785
+ * `platformRecogniser`, which takes its atoms from the parse tree.
1786
+ */
1787
+ export declare function grantAtoms(identity: string): string[];
1788
+ /**
1789
+ * What the platform itself installs or renders, as the recogniser compares
1790
+ * it: tables of the platform (no owner object) and generated units.
1791
+ */
1792
+ interface PlatformReference {
1793
+ tables: readonly PhysicalTable[];
1794
+ units: readonly Pick<SqlUnit, "class" | "identity" | "sql">[];
1795
+ }
1796
+ /** A unit of a live catalog, as the recogniser reads it. */
1797
+ type RecognisedUnit = Pick<CatalogUnit, "class" | "identity" | "sql">;
1798
+ /**
1799
+ * Recogniser of platform content among the objects of a catalog: a table or
1800
+ * unit is the platform's only when its content matches the reference. A
1801
+ * grant is the platform's when every atom of its parse tree (action, object,
1802
+ * role, privilege with column, grant option, behaviour, grantor) is an atom
1803
+ * of a reference grant; any other unit when its normalised parse tree equals
1804
+ * the tree of the reference unit with the same identity; a table when the
1805
+ * catalog comparison with the reference table finds no difference. What does
1806
+ * not parse, has no reference or differs without a normalisation rule is not
1807
+ * the platform's: the folder gets it and the compiler judges it.
1808
+ */
1809
+ interface PlatformRecogniser {
1810
+ table(table: CatalogTable): boolean;
1811
+ unit(unit: RecognisedUnit): boolean;
1812
+ }
1813
+ export declare function platformRecogniser(reference: PlatformReference, parse: SqlParser): PlatformRecogniser;
1394
1814
  /**
1395
1815
  * Право виконання згенерованої функції — лише ролям названих призначень
1396
1816
  * (платформна спека §6.7: дефолт — `REVOKE ALL`). Postgres дає `EXECUTE`
@@ -1402,6 +1822,89 @@ export declare function platformSchemaGrants(provider: DatabaseProvider): string
1402
1822
  * `схема.ім'я(типи)`, як у `ON FUNCTION`.
1403
1823
  */
1404
1824
  export declare function executeGrants(signature: string, purposes: readonly GrantPurpose[], provider: DatabaseProvider): string[];
1825
+ /**
1826
+ * Обернення `grantRole`: роль бази → викликачі декларації (зворотна генерація,
1827
+ * спека декларацій функцій §5.5). Таблицю пар не дублює — обертає `grantRole`
1828
+ * по всіх призначеннях, тож нове призначення потрапляє сюди саме. `PUBLIC`
1829
+ * дає кожне призначення, що має роль у профілі (роль без сесії теж: її
1830
+ * відкидає і про це попереджає читач). Роль поза призначеннями профілю
1831
+ * (`signalConsumer`, `files`, власна роль застосунку) — `undefined`: викликача для неї
1832
+ * немає, і це не мовчазна згода, а підстава відмови читача.
1833
+ */
1834
+ export declare function callersOfRole(role: string, provider: DatabaseProvider): GrantPurpose[] | undefined;
1835
+ export declare const PUBLIC = "PUBLIC";
1836
+ /** Дослівний `GRANT`/`REVOKE` на функцію чи відношення. */
1837
+ interface GrantFact {
1838
+ keys: readonly string[];
1839
+ grant: boolean;
1840
+ /** `REVOKE GRANT OPTION FOR` — сам привілей лишається. */
1841
+ optionOnly: boolean;
1842
+ /** Отримувачі: `PUBLIC` чи ім'я ролі. */
1843
+ roles: ReadonlySet<string>;
1844
+ /** Привілеї; порожньо — `ALL`. `columns` — лише на колонки. */
1845
+ privileges: readonly {
1846
+ name: string;
1847
+ columns: boolean;
1848
+ }[];
1849
+ }
1850
+ export declare function grantFacts(units: readonly VerbatimUnit[], parse: SqlParser): GrantFact[];
1851
+ /** Одиниця шару, що не залежить від моделі: модуль додає той, хто її кладе. */
1852
+ type RenderedUnit = Omit<SqlUnit, "module">;
1853
+ /** Одна функція механіки на всі таблиці: тіло не залежить від таблиці. */
1854
+ export declare const MECHANICS_FUNCTION: QualifiedName;
1855
+ /**
1856
+ * Єдине джерело версій рядків бази: усі таблиці механіки беруть версію з неї,
1857
+ * тож ключ, видалений і створений знову, не повторює вже видану версію.
1858
+ */
1859
+ export declare const ROW_VERSION_SEQUENCE: {
1860
+ readonly schema: "simetra";
1861
+ readonly name: "row_version";
1862
+ };
1863
+ /**
1864
+ * Префікс налаштування транзакції, у яке `touch` кладе видану версію рядка
1865
+ * (`<префікс><OID таблиці>`): `currval` зсували б інші тригери, а це
1866
+ * налаштування пише лише `touch` (вставка й оновлення) тієї самої таблиці.
1867
+ */
1868
+ export declare const ROW_VERSION_SETTING = "simetra.row_version_";
1869
+ /**
1870
+ * Ім'я тригера механіки на таблиці. Спільний префікс рядкових `BEFORE`-тригерів
1871
+ * ставить механіку останньою на будь-якій довжині назви, а зворотна генерація
1872
+ * й промоція впізнають тригер за тим самим іменем.
1873
+ */
1874
+ export declare function mechanicsTriggerName(table: string): string;
1875
+ /**
1876
+ * Ім'я тригера механіки на `UPDATE` таблиці з копіями носіїв: там механіка
1877
+ * розділена на вставку й оновлення з умовою `contentChangeCondition`.
1878
+ */
1879
+ export declare function mechanicsUpdateTriggerName(table: string): string;
1880
+ /** Колонки авторства таблиці — за `origin.standard`, у порядку таблиці. */
1881
+ export declare function authorTableColumns(table: Pick<PhysicalTable, "columns">, attributeCase: AttributeCase): PhysicalColumn[];
1882
+ /**
1883
+ * Умова «змінився зміст рядка» таблиці з копіями носіїв (спека прав §5.2):
1884
+ * `(<зміст змінився>) OR NOT (<копії змінилися>)`. Поширення копій
1885
+ * платформою — не зміна змісту: воно пише лише копії, тож придушується, а
1886
+ * звичайне перезбереження без змін (нічого не змінилося) поводиться, як на
1887
+ * будь-якій таблиці. Умова `BEFORE`-тригера рахується з `NEW` після
1888
+ * попередніх тригерів, але поширення пише лише копії за будь-якого порядку
1889
+ * тригерів, тож результат від порядку імен не залежить. Зміст —
1890
+ * `contentColumns`. Таблиця без копій умови не має.
1891
+ *
1892
+ * `watched` (спека П4 §6.8) — колонки поза змістом, зміна яких теж має спрацювати:
1893
+ * авторство для тригерів механіки, авторства й ефектів. Копія носія може
1894
+ * виводитися з `createdBy`, тож зміна лише `created_by_id` змінює й копію, і
1895
+ * без `watched` умова була б хибною: ефекти не відмовили б незмінному
1896
+ * автору, а механіка не підвищила б версію. Підписки `watched` не беруть.
1897
+ */
1898
+ export declare function contentChangeCondition(table: Pick<PhysicalTable, "columns">, attributeCase: AttributeCase, watched?: readonly PhysicalColumn[]): string | undefined;
1899
+ /**
1900
+ * Таблиці механіки моделі: ті, чиї колонки реєстр дав як службові дату й
1901
+ * версію (за `origin.standard`, а не за іменем колонки). Єдине рішення, яке
1902
+ * читають і генератор тригерів, і засів послідовності версій у стані
1903
+ * застосування, тож вони не розходяться.
1904
+ */
1905
+ export declare function mechanicsTables(physical: Pick<PhysicalSnapshot, "tables">, attributeCase: AttributeCase): ObjectTable[];
1906
+ /** Фізичне ім'я колонки версії рядка таблиць механіки. */
1907
+ export declare const ROW_VERSION_COLUMN: string;
1405
1908
  /** Одна функція авторства на проєкт: тіло не залежить від таблиці. */
1406
1909
  export declare const AUTHOR_FUNCTION: QualifiedName;
1407
1910
  /**
@@ -1423,13 +1926,25 @@ export declare function hierarchyNames(table: QualifiedName): {
1423
1926
  update: string;
1424
1927
  fn: QualifiedName;
1425
1928
  };
1426
- type PlatformTriggerFamily = "mechanics" | "author" | "key" | "carriers" | "hierarchy" | "effects" | "rightsGuards";
1929
+ /**
1930
+ * Імена тригерів стану мови (Р-B2-4). Рядковий — `BEFORE` у групі платформи
1931
+ * перед `simetra_touch`: відмовлений запис не бере версії. Запобіжник
1932
+ * `TRUNCATE` — операторний, тож у групу не входить і лишається на алгоритмі
1933
+ * імен Postgres. Обидва кличуть одну функцію в схемі таблиці з іменем
1934
+ * рядкового тригера.
1935
+ */
1936
+ export declare function languageStateNames(table: QualifiedName): {
1937
+ row: string;
1938
+ truncate: string;
1939
+ fn: QualifiedName;
1940
+ };
1941
+ type PlatformTriggerFamily = "mechanics" | "author" | "key" | "carriers" | "hierarchy" | "languageState" | "effects" | "rightsGuards" | "rightsSignals" | "storage";
1427
1942
  interface PlatformTrigger {
1428
1943
  family: PlatformTriggerFamily;
1429
1944
  trigger: string;
1430
1945
  function: QualifiedName;
1431
1946
  /** Генератор одиниці тригера (`SqlUnit.generator`). */
1432
- generator: "mechanics" | "key" | "carriers" | "effects" | "rightsGuards";
1947
+ generator: "mechanics" | "key" | "carriers" | "effects" | "rightsGuards" | "rightsSignal" | "storage";
1433
1948
  /** Тригер оновлення, платформний лише з умовою змісту таблиці. */
1434
1949
  contentUpdate: boolean;
1435
1950
  }
@@ -1443,6 +1958,21 @@ export declare const SHARED_TRIGGER_FUNCTIONS: readonly QualifiedName[];
1443
1958
  * він лише впізнає їх за іменем і функцією.
1444
1959
  */
1445
1960
  export declare function platformTriggers(table: QualifiedName): PlatformTrigger[];
1961
+ /**
1962
+ * Шар, що не залежить від моделі, для таблиці: спільні функції механіки,
1963
+ * авторства й ключа з їхніми грантами та тригери цих родин у формі без
1964
+ * `WHEN` змісту (таблиця без копій носіїв). Той самий текст, що кладуть
1965
+ * `build*Units`, — еталон зворотної генерації не має другої копії.
1966
+ * Варіанти з `WHEN` залежать від копій носіїв моделі й сюди не входять.
1967
+ * Чи таблиця має колонки, яких вимагає тригер, вирішує споживач.
1968
+ */
1969
+ export declare function renderModelIndependentLayer(table: QualifiedName, provider: DatabaseProvider, parse: SqlParser): RenderedUnit[];
1970
+ /**
1971
+ * Спільні функції механіки, авторства й ключа з їхніми грантами: частина
1972
+ * шару, що не залежить ні від моделі, ні від таблиці, — еталон зворотної
1973
+ * генерації бере її й без жодного тригера.
1974
+ */
1975
+ export declare function renderSharedTriggerFunctions(provider: DatabaseProvider, parse: SqlParser): RenderedUnit[];
1446
1976
  /** Одна функція незмінності ключа на проєкт: тіло не залежить від таблиці. */
1447
1977
  export declare const KEY_FUNCTION: QualifiedName;
1448
1978
  /**
@@ -1456,45 +1986,13 @@ export declare function keyTriggerNames(table: string): {
1456
1986
  before: string;
1457
1987
  after: string;
1458
1988
  };
1459
- /** Одна функція механіки на всі таблиці: тіло не залежить від таблиці. */
1460
- export declare const MECHANICS_FUNCTION: QualifiedName;
1461
- /**
1462
- * Ім'я тригера механіки на таблиці. Спільний префікс рядкових `BEFORE`-тригерів
1463
- * ставить механіку останньою на будь-якій довжині назви, а зворотна генерація
1464
- * й промоція впізнають тригер за тим самим іменем.
1465
- */
1466
- export declare function mechanicsTriggerName(table: string): string;
1467
- /**
1468
- * Ім'я тригера механіки на `UPDATE` таблиці з копіями носіїв: там механіка
1469
- * розділена на вставку й оновлення з умовою `contentChangeCondition`.
1470
- */
1471
- export declare function mechanicsUpdateTriggerName(table: string): string;
1472
- /** Колонки авторства таблиці — за `origin.standard`, у порядку таблиці. */
1473
- export declare function authorTableColumns(table: Pick<PhysicalTable, "columns">, attributeCase: AttributeCase): PhysicalColumn[];
1474
- /**
1475
- * Умова «змінився зміст рядка» таблиці з копіями носіїв (спека прав §5.2):
1476
- * `(<зміст змінився>) OR NOT (<копії змінилися>)`. Поширення копій
1477
- * платформою — не зміна змісту: воно пише лише копії, тож придушується, а
1478
- * звичайне перезбереження без змін (нічого не змінилося) поводиться, як на
1479
- * будь-якій таблиці. Умова `BEFORE`-тригера рахується з `NEW` після
1480
- * попередніх тригерів, але поширення пише лише копії за будь-якого порядку
1481
- * тригерів, тож результат від порядку імен не залежить. Зміст —
1482
- * `contentColumns`. Таблиця без копій умови не має.
1483
- *
1484
- * `watched` (спека П4 §6.8) — колонки поза змістом, зміна яких теж має спрацювати:
1485
- * авторство для тригерів механіки, авторства й ефектів. Копія носія може
1486
- * виводитися з `createdBy`, тож зміна лише `created_by_id` змінює й копію, і
1487
- * без `watched` умова була б хибною: ефекти не відмовили б незмінному
1488
- * автору, а механіка не підвищила б версію. Підписки `watched` не беруть.
1489
- */
1490
- export declare function contentChangeCondition(table: Pick<PhysicalTable, "columns">, attributeCase: AttributeCase, watched?: readonly PhysicalColumn[]): string | undefined;
1491
1989
  /**
1492
1990
  * Мітки рядкових `BEFORE`-тригерів платформи в порядку спрацювання.
1493
1991
  * Postgres запускає тригери одного часу за іменем (порівняння байтів), тож
1494
- * порядок `author → carriers → key → touch` тримається, лише коли всі імена групи
1992
+ * порядок `author → carriers → key → language → touch` тримається, лише коли всі імена групи
1495
1993
  * мають один префікс, а мітки сортуються як цей масив.
1496
1994
  */
1497
- export declare const PLATFORM_BEFORE_ROW_LABELS: readonly ["simetra_author", "simetra_author_update", "simetra_carriers", "simetra_key", "simetra_touch", "simetra_touch_update"];
1995
+ export declare const PLATFORM_BEFORE_ROW_LABELS: readonly ["simetra_author", "simetra_author_update", "simetra_carriers", "simetra_key", "simetra_language", "simetra_touch", "simetra_touch_update"];
1498
1996
  type PlatformBeforeRowLabel = (typeof PLATFORM_BEFORE_ROW_LABELS)[number];
1499
1997
  /**
1500
1998
  * Ім'я рядкового `BEFORE`-тригера платформи. `makeObjectName` обрізав би назву
@@ -1517,24 +2015,14 @@ export declare function effectsTriggerNames(table: QualifiedName): {
1517
2015
  /** Функція ефектів у схемі таблиці — одна для обох її тригерів. */
1518
2016
  export declare function effectsFunctionName(table: QualifiedName): QualifiedName;
1519
2017
  /**
1520
- * Об'єкти, ACL яких належить платформі (платформна спека §6.7). Ключ —
1521
- * `function|<сигнатура>` чи `table|<схема.ім'я>`: `grantTargetKeys`.
1522
- * Функція — ціль будь-якої згенерованої одиниці `grant` (`functionExecute`,
1523
- * членство, платформний шар); таблиця — лише таблиця з контрактом доступу,
1524
- * тобто ціль грантів генератора `access`.
2018
+ * Чи функція чи процедура виконується від власника: `SECURITY DEFINER` у
2019
+ * `CREATE` чи в окремому `ALTER FUNCTION` (порядок не моделюється —
2020
+ * fail-closed).
1525
2021
  */
1526
- export declare function platformGrantTargets(units: readonly Pick<SqlUnit, "class" | "name" | "sql" | "file" | "generator">[], parse: SqlParser): Set<string>;
1527
- /**
1528
- * Чи ціль гранту — об'єкт платформи. `ON FUNCTION f` без списку аргументів
1529
- * Postgres резолвить у єдину функцію з цим ім'ям, тож вона збігається з
1530
- * функцією платформи тієї самої схеми й імені.
1531
- */
1532
- export declare function ownsTarget(owned: ReadonlySet<string>, target: string): boolean;
1533
- /**
1534
- * Цілі гранту-функції чи гранту-таблиці; ціль іншого виду (схема, тип,
1535
- * послідовність) платформі в цьому правилі не належить, тож ключа не має.
1536
- */
1537
- export declare function grantTargetKeys(unit: Pick<SqlUnit, "class" | "name" | "sql">, parse: SqlParser): string[];
2022
+ export declare function isSecurityDefiner(unit: VerbatimUnit, units: readonly VerbatimUnit[]): boolean;
2023
+ /** Чи функція — тригерна: її кличе лише тригер. */
2024
+ export declare function isTriggerFunction(unit: VerbatimUnit): boolean;
2025
+ export declare const FUNCTIONS_SCHEMA_FILE = "functions.schema.json";
1538
2026
  /**
1539
2027
  * Ціль одиниці — об'єкт, на який діє оператор без власного об'єкта в схемі
1540
2028
  * (грант, коментар, типові привілеї, членство в publication) чи з об'єктом,
@@ -1577,11 +2065,19 @@ export declare function unitTargets(unit: TargetUnit, parse: SqlParser): UnitTar
1577
2065
  * для межі керування й для діагностики межі, одним правилом.
1578
2066
  */
1579
2067
  export declare function unitPlacement(unit: TargetUnit, parse: SqlParser): UnitTarget[];
2068
+ /** Функція, яку кличе тригер: у `EXECUTE FUNCTION` чи в умові `WHEN`. */
2069
+ interface TriggerFunctionCall {
2070
+ where: "execute" | "when";
2071
+ schema: string;
2072
+ name: string;
2073
+ }
1580
2074
  /**
1581
- * Схема функції, яку викликає тригер; некваліфіковане ім'я — `undefined`:
1582
- * його резолвить `search_path` бази, а не текст одиниці.
2075
+ * Функції, які кличе тригер, — лише кваліфіковані імена: без схеми функцію
2076
+ * знаходить `search_path` бази чи тригера, тож у межу вона не потрапляє
2077
+ * залежністю схеми. Межу тригера на таблиці провайдера судять усі його
2078
+ * функції-залежності (`providerTriggerInBoundarySql`).
1583
2079
  */
1584
- export declare function triggerFunctionSchema(unit: TargetUnit, parse: SqlParser): string | undefined;
2080
+ export declare function triggerFunctionCalls(unit: TargetUnit, parse: SqlParser): TriggerFunctionCall[];
1585
2081
  /**
1586
2082
  * Ключ предмета класу конверсії промоції (спека промоції §8): об'єкт,
1587
2083
  * який клас покриває, коли одиниця зникає з бажаного стану. Будується з
@@ -1736,6 +2232,10 @@ interface ValueSource {
1736
2232
  interface ElementSource extends ValueSource {
1737
2233
  id?: string;
1738
2234
  name: string;
2235
+ /** `load` реквізиту з метаданих (Рд25); у колонки `CustomTable` немає. */
2236
+ load?: "eager" | "lazy";
2237
+ /** Явний `maxBytes` реквізиту (Рд26); типове за типом дає `effectiveMaxBytes`. */
2238
+ maxBytes?: number;
1739
2239
  }
1740
2240
  /** Стандартні колонки (за логічним ім'ям у стилі проєкту) й елементи таблиці. */
1741
2241
  interface EntityContext {
@@ -1765,7 +2265,8 @@ interface EntityField {
1765
2265
  * скоупу (ім'я поля — ім'я виду), колонка без походження в метаданих — за
1766
2266
  * фізичним іменем. Ключ-одинак пропускається: службовий ключ рядка-одинака
1767
2267
  * (завжди `true`, значення дає DEFAULT) у скоупленій формі не існує, тож і
1768
- * поля сутності не дає.
2268
+ * поля сутності не дає. Нормалізована колонка пошуку (`origin.searchOf`) —
2269
+ * теж не поле: її значення — функція поля, і клієнт її не бачить.
1769
2270
  */
1770
2271
  export declare function entityFields(model: CompiledModel, table: PhysicalTable, context: EntityContext): EntityField[];
1771
2272
  /**
@@ -1777,6 +2278,17 @@ export declare function entityFields(model: CompiledModel, table: PhysicalTable,
1777
2278
  * тобто з гранту ролі команд.
1778
2279
  */
1779
2280
  export declare function buildRuntimeCatalog(model: CompiledModel): RuntimeCatalog;
2281
+ /**
2282
+ * The kernel contract hash of a catalog entry (P4-B spec Рд12): SHA-256 of
2283
+ * the canonical form of its operations — command functions and contexts.
2284
+ * An entry without operations hashes the empty form.
2285
+ */
2286
+ export declare function kernelHashOf(operations: RuntimeObject["operations"]): string;
2287
+ /**
2288
+ * The client catalog of a runtime catalog: each entry projected onto the
2289
+ * shared part, in the runtime order (P4-B spec §3).
2290
+ */
2291
+ export declare function buildClientCatalog(runtime: RuntimeCatalog): ClientCatalog;
1780
2292
  /**
1781
2293
  * Канонічна JSON-форма за RFC 8785 (JCS). Власна реалізація: примітиви
1782
2294
  * серіалізує `JSON.stringify` — це саме ES Number::toString та екранування
@@ -1822,8 +2334,14 @@ interface FileChange {
1822
2334
  content: string | null;
1823
2335
  }
1824
2336
  interface OperationResult {
1825
- /** Компіляція результату без помилок; лише тоді обгортка пише зміни. */
2337
+ /** Компіляція результату без помилок; тоді обгортка пише зміни. */
1826
2338
  ok: boolean;
2339
+ /**
2340
+ * Лише в хвості режиму `repair` (спека декларацій функцій §5.1): результат
2341
+ * з помилками лише класу ремонту, жодна з яких не нова, прийнято — `ok`
2342
+ * лишається `false`, а обгортка пише зміни.
2343
+ */
2344
+ written?: true;
1827
2345
  changes: FileChange[];
1828
2346
  diagnostics: Diagnostic[];
1829
2347
  }
@@ -1883,6 +2401,13 @@ export declare function sqlDebtText(units: readonly string[], schemaPath: Schema
1883
2401
  * справа — лагодити саме вхід. `changes` — лише файли зі зміненим текстом.
1884
2402
  * Борг рахується над доповненою текою: типи рядків таблиць, від яких
1885
2403
  * залежать ідентичності функцій, з'являються лише з id і фізичними іменами.
2404
+ *
2405
+ * Режим ремонту (спека декларацій функцій §5.6, Р2): після механічного
2406
+ * доповнення (і `id` записам `.functions.json`) `fix` лагодить клас ремонту —
2407
+ * (г) декларація функції, що стала формою платформи, (д) вирізання ADP на
2408
+ * функції, (в) запобіжник виклику з `check`. Результат з помилками класу
2409
+ * ремонту несе `written`, якщо не додав нових, прибрав хоча б одну й не має
2410
+ * помилок поза класом.
1886
2411
  */
1887
2412
  export declare function fixFiles(files: ReadonlyMap<string, string>, o: CompletionOptions): Promise<OperationResult>;
1888
2413
  /**
@@ -1976,6 +2501,10 @@ export declare const addElementInput: z.ZodObject<{
1976
2501
  }, z.core.$strict>], "kind">;
1977
2502
  collection: z.ZodString;
1978
2503
  element: z.ZodRecord<z.ZodString, z.ZodUnknown>;
2504
+ scopes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
2505
+ scope: z.ZodString;
2506
+ scopeColumn: z.ZodOptional<z.ZodString>;
2507
+ }, z.core.$strict>>>;
1979
2508
  }, z.core.$strict>;
1980
2509
  type AddElementInput = z.infer<typeof addElementInput>;
1981
2510
  export declare const renameInput: z.ZodObject<{
@@ -2031,10 +2560,10 @@ type DeleteInput = z.infer<typeof deleteInput>;
2031
2560
  * файлів.
2032
2561
  */
2033
2562
  export declare const conversionClass: z.ZodEnum<{
2563
+ metadata: "metadata";
2034
2564
  platform: "platform";
2035
2565
  property: "property";
2036
2566
  rowRule: "rowRule";
2037
- metadata: "metadata";
2038
2567
  applicationCode: "applicationCode";
2039
2568
  removed: "removed";
2040
2569
  }>;
@@ -2101,10 +2630,10 @@ export declare const promoteInput: z.ZodObject<{
2101
2630
  expression: z.ZodString;
2102
2631
  }, z.core.$strict>>>;
2103
2632
  conversions: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodEnum<{
2633
+ metadata: "metadata";
2104
2634
  platform: "platform";
2105
2635
  property: "property";
2106
2636
  rowRule: "rowRule";
2107
- metadata: "metadata";
2108
2637
  applicationCode: "applicationCode";
2109
2638
  removed: "removed";
2110
2639
  }>>>;
@@ -2112,6 +2641,45 @@ export declare const promoteInput: z.ZodObject<{
2112
2641
  consumerLabels: z.ZodDefault<z.ZodArray<z.ZodString>>;
2113
2642
  }, z.core.$strict>;
2114
2643
  type PromoteInput = z.infer<typeof promoteInput>;
2644
+ /**
2645
+ * Запис декларації функції без `id`: його видає операція, а наявний зберігає.
2646
+ * Схема — із T0 (єдине джерело форми запису), тож нове поле запису стає
2647
+ * доступним без змін тут.
2648
+ */
2649
+ export declare const declareFunctionInput: z.ZodObject<{
2650
+ function: z.ZodObject<{
2651
+ schema: z.ZodOptional<z.ZodString>;
2652
+ name: z.ZodString;
2653
+ }, z.core.$strict>;
2654
+ check: z.ZodOptional<z.ZodObject<{
2655
+ action: z.ZodString;
2656
+ object: z.ZodObject<{
2657
+ kind: z.ZodEnum<{
2658
+ Catalog: "Catalog";
2659
+ Document: "Document";
2660
+ Enumeration: "Enumeration";
2661
+ InformationRegister: "InformationRegister";
2662
+ AccumulationRegister: "AccumulationRegister";
2663
+ Constant: "Constant";
2664
+ CustomTable: "CustomTable";
2665
+ PgEnum: "PgEnum";
2666
+ EventSubscription: "EventSubscription";
2667
+ RightsSet: "RightsSet";
2668
+ Role: "Role";
2669
+ }>;
2670
+ name: z.ZodString;
2671
+ }, z.core.$strict>;
2672
+ row: z.ZodOptional<z.ZodString>;
2673
+ scope: z.ZodOptional<z.ZodString>;
2674
+ }, z.core.$strict>>;
2675
+ callers: z.ZodArray<z.ZodEnum<{
2676
+ user: "user";
2677
+ anonymous: "anonymous";
2678
+ service: "service";
2679
+ command: "command";
2680
+ }>>;
2681
+ }, z.core.$strict>;
2682
+ type DeclareFunctionInput = z.infer<typeof declareFunctionInput>;
2115
2683
  /**
2116
2684
  * Створює об'єкт (спека П2 §8.6): файл `<тека виду>/<Name>/<Name>.meta.json`
2117
2685
  * з `kind`, `name` і полями `data`; id, `physicalName`, `$schema` і канонічну
@@ -2125,6 +2693,18 @@ export declare function createObject(files: ReadonlyMap<string, string>, input:
2125
2693
  * контейнера, тож нова колекція схеми стає доступною без змін тут.
2126
2694
  */
2127
2695
  export declare function addElement(files: ReadonlyMap<string, string>, input: AddElementInput, o: CompletionOptions): Promise<OperationResult>;
2696
+ /**
2697
+ * Створює чи замінює запис декларації однієї функції в `<основа>.functions.json`
2698
+ * поруч із `.sql`, що її створює (спека декларацій функцій §5.6, Р1): повна
2699
+ * заміна `callers` і `check`, `id` наявного зберігається, новому його
2700
+ * видає операція. Режим `repair`, як у `addElement`: тека з помилками класу
2701
+ * ремонту приймається, а хвіст не дає додати нову — крім самої цілі, яка може
2702
+ * перейти в `check-not-applied` з причиною `firstStatement`, коли `fix`
2703
+ * гарантовано вставить запобіжник (`guardInsertionPoint`): інакше ланцюжок
2704
+ * `declare-function` → `fix` неможливий, бо недекларована функція, ставши
2705
+ * задекларованою, дістає новий ключ помилки.
2706
+ */
2707
+ export declare function declareFunction(files: ReadonlyMap<string, string>, input: DeclareFunctionInput, o: CompletionOptions): Promise<OperationResult>;
2128
2708
  /**
2129
2709
  * Перейменовує об'єкт чи вкладений іменований елемент (спека П2 §3, §8.6):
2130
2710
  * поле `name` цілі плюс каскад — кожне посилання індексу з id цілі. Id і
@@ -2474,7 +3054,7 @@ interface Explanation {
2474
3054
  tables: {
2475
3055
  schema: string;
2476
3056
  name: string;
2477
- part?: "main" | "tabularSection" | PhysicalOrigin["part"];
3057
+ part?: "main" | "tabularSection" | ObjectOrigin["part"];
2478
3058
  columns: {
2479
3059
  name: string;
2480
3060
  type: string;
@@ -2529,4 +3109,31 @@ export declare function explainObject(model: CompiledModel, target: {
2529
3109
  kind: MetadataKind;
2530
3110
  name: string;
2531
3111
  }): Explanation | undefined;
2532
- export type { AddElementInput, AssignmentSourceContract, CarrierBackfillStatement, CompileOptions, CompileResult, CompiledModel, CompiledScopeKind, CompilerRule, CompletionOptions, Constraint, ContainerTarget, Contracts, ConversionClass, CreateObjectInput, CreationNode, DeleteInput, DerivedFacts, Diagnostic, DiagnosticParams, ElementSource, ElementTarget, EntityContext, EntityField, Explanation, FieldDifference, FileChange, IdSource, IndexElem, IndexStmt, KindKey, Locale, MembershipSourceContract, MessageEntry, ModelFunctions, Node, OperationResult, OutOfScopeReason, PlatformBeforeRowLabel, PlatformTrigger, PlatformTriggerFamily, PlpgsqlParser, Position, PostingContract, Presentation, PresentationBlock, PromoteInput, PromoteResult, PromotionFacts, PromotionMapping, PromotionObject, PromotionRecord, QualifiedName, Range, RangeVar, RegisterContract, RenameInput, ResolvedReference, ResolvedTarget, ResourceMeasure, RightsLevelKey, RuleCode, SchemaPathResolver, Severity, SourceObject, SqlParser, SqlSource, SqlUnit, UniqueShape, UnitSubjectKey, UnitTarget, VirtualTableColumn, VirtualTableContract };
3112
+ /** Explanation of one SQL function; see `explainFunction`. */
3113
+ interface FunctionExplanation {
3114
+ function: {
3115
+ schema: string;
3116
+ name: string;
3117
+ };
3118
+ /** Declared callers; absent when the function is not declared (verbatim grants are not guessed). */
3119
+ callers?: string[];
3120
+ /** Profile roles that get the derived EXECUTE, per provider (a platform form wins over the declared callers). */
3121
+ roles?: Record<DatabaseProvider, {
3122
+ caller: string;
3123
+ role: string;
3124
+ }[]>;
3125
+ /** The declared check in words. */
3126
+ check?: string;
3127
+ /** Whether the body applies the declared check; `none` when no check is declared; a platform form names its form. */
3128
+ state: "applied" | `not-applied (${string})` | `platform-form (${PlatformForm})` | "none";
3129
+ }
3130
+ /**
3131
+ * Explains a function by `schema.name` from the compile result (not the
3132
+ * model: it holds no declarations). `undefined` when the folder has no such
3133
+ * function.
3134
+ */
3135
+ export declare function explainFunction(compiled: Pick<CompileResult, "model" | "declaredFunctions" | "functionExecute">, target: {
3136
+ schema: string;
3137
+ name: string;
3138
+ }): FunctionExplanation | undefined;
3139
+ export type { AddElementInput, AssignmentSourceContract, CarrierBackfillStatement, CompileOptions, CompileResult, CompiledModel, CompiledScopeKind, CompilerRule, CompletionOptions, Constraint, ContainerTarget, Contracts, ConversionClass, CreateObjectInput, CreationNode, DeclareFunctionInput, DeleteInput, DerivedFacts, Diagnostic, DiagnosticParams, ElementSource, ElementTarget, EntityContext, EntityField, Explanation, FieldDifference, FileChange, FunctionExplanation, GrantFact, GuardArgs, IdSource, IndexElem, IndexStmt, KindKey, Locale, MembershipSourceContract, MessageEntry, ModelFunctions, Node, OperationResult, OutOfScopeReason, PlatformBeforeRowLabel, PlatformInstall, PlatformRecogniser, PlatformReference, PlatformTrigger, PlatformTriggerFamily, PlpgsqlParser, Position, PostingContract, PredefinedSeedContract, Presentation, PresentationBlock, PromoteInput, PromoteResult, PromotionFacts, PromotionMapping, PromotionObject, PromotionRecord, QualifiedName, Range, RangeVar, RecognisedUnit, RegisterContract, RenameInput, ResolvedReference, ResolvedTarget, ResourceMeasure, RightsLevelKey, RuleCode, SchemaPathResolver, Severity, SourceObject, SqlParser, SqlSource, SqlUnit, UniqueShape, UnitSubjectKey, UnitTarget, VerbatimUnit, VirtualTableColumn, VirtualTableContract };