simetra 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3951 @@
1
+ import { z } from "zod";
2
+ //#region src/model/schemas/localized-string.ts
3
+ /**
4
+ * Localized string: at least one locale required.
5
+ * BRD: {uk, en} — Ukrainian first, English second.
6
+ */
7
+ const localizedStringSchema = z.strictObject({
8
+ uk: z.string().optional().meta({ description: "Ukrainian text." }),
9
+ en: z.string().optional().meta({ description: "English text." })
10
+ }).refine((val) => val.uk !== void 0 || val.en !== void 0, { message: "At least one locale (uk or en) must be provided" }).meta({ description: "Text per locale; at least one of uk or en is required." });
11
+ //#endregion
12
+ //#region src/model/schemas/metadata-kind.ts
13
+ /**
14
+ * Перелік видів метаданих — частина форми посилання `MetadataRef`. Поведінка
15
+ * видів живе поруч у T0, у реєстрі видів (`model/kinds`), а не тут: схема
16
+ * посилання не залежить від знань про види.
17
+ */
18
+ const METADATA_KINDS = [
19
+ "Catalog",
20
+ "Document",
21
+ "Enumeration",
22
+ "InformationRegister",
23
+ "AccumulationRegister",
24
+ "Constant",
25
+ "CustomTable",
26
+ "PgEnum",
27
+ "EventSubscription",
28
+ "RightsSet",
29
+ "Role"
30
+ ];
31
+ const metadataKindSchema = z.enum(METADATA_KINDS).meta({ description: "Kind of the referenced metadata object." });
32
+ //#endregion
33
+ //#region src/model/schemas/identity.ts
34
+ /**
35
+ * Стабільна ідентичність об'єкта чи реквізиту: ім'я можна змінювати, id — ні.
36
+ * Лише нижній регістр (так генерує crypto.randomUUID): id порівнюються як
37
+ * рядки, тож той самий UUID у іншому регістрі обійшов би перевірку дублів.
38
+ */
39
+ const metadataIdSchema = z.uuid({ version: "v4" }).refine((id) => id === id.toLowerCase(), { message: "UUID must be lowercase" }).meta({ description: "Stable lowercase UUID v4 identity of the element. Assigned by tooling at creation and never reused; a rename keeps it." });
40
+ /** Логічне ім'я об'єкта — PascalCase. */
41
+ const objectNameSchema = z.string().regex(/^[A-Z][A-Za-z0-9]*$/).meta({ description: "Logical object name in PascalCase." });
42
+ /**
43
+ * Логічне ім'я елемента (реквізиту тощо). Шаблон навмисно ширший за обидва
44
+ * стилі: який саме стиль діє, залежить від налаштування застосунку, тож стиль
45
+ * перевіряє окрема стадія (matchesAttributeCase), а не схема.
46
+ */
47
+ const elementNameSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/).meta({ description: "Logical element name (attribute, section, column). The casing style is checked against the project naming setting." });
48
+ /** Ліміт ідентифікатора PostgreSQL — 63 байти, а не символи. */
49
+ const MAX_PHYSICAL_NAME_BYTES = 63;
50
+ const physicalNameSchema = z.string().min(1).refine((s) => new TextEncoder().encode(s).length <= 63, { message: "Physical name must be at most 63 bytes in UTF-8" }).meta({ description: "Physical database name. Assigned once at creation and never changed, so a rename emits no DDL. At most 63 bytes in UTF-8." });
51
+ const ATTRIBUTE_CASES = ["camelCase", "snake_case"];
52
+ const ATTRIBUTE_CASE_PATTERNS = {
53
+ camelCase: /^[a-z][A-Za-z0-9]*$/,
54
+ snake_case: /^[a-z][a-z0-9_]*$/
55
+ };
56
+ function matchesAttributeCase(name, style) {
57
+ return ATTRIBUTE_CASE_PATTERNS[style].test(name);
58
+ }
59
+ /**
60
+ * Перетворює PascalCase або camelCase ім'я у snake_case.
61
+ * Приклади: SalesOrder → sales_order, CurrencyExchangeRates → currency_exchange_rates.
62
+ */
63
+ function toSnakeCase(name) {
64
+ return name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").toLowerCase();
65
+ }
66
+ function capitalize(segment) {
67
+ return segment.charAt(0).toUpperCase() + segment.slice(1);
68
+ }
69
+ /**
70
+ * Inverse of `toSnakeCase` for object names: `service_accrual` becomes
71
+ * `ServiceAccrual`. Collisions between distinct physical names are not
72
+ * resolved here — the caller sees the whole set and does that.
73
+ */
74
+ function logicalObjectName(physical) {
75
+ return physical.split("_").filter(Boolean).map(capitalize).join("");
76
+ }
77
+ /**
78
+ * Logical name of an element (attribute, section, column) from its physical
79
+ * name, in the project's `naming.attributeCase` style.
80
+ */
81
+ function logicalElementName(physical, style) {
82
+ if (style === "snake_case") return physical;
83
+ const [head = "", ...rest] = physical.split("_").filter(Boolean);
84
+ return head + rest.map(capitalize).join("");
85
+ }
86
+ //#endregion
87
+ //#region src/model/schemas/metadata-ref.ts
88
+ /**
89
+ * Посилання на інший об'єкт метаданих. Чи можна на цей вид посилатися —
90
+ * факт реєстру видів і перевірка стадії 4, а не схеми.
91
+ */
92
+ const metadataRefSchema = z.strictObject({
93
+ kind: metadataKindSchema,
94
+ name: objectNameSchema.meta({ description: "Logical name of the referenced object." })
95
+ }).meta({ description: "Reference to a metadata object by kind and logical name; the compiler resolves it to an id." });
96
+ //#endregion
97
+ //#region src/model/schemas/value-type.ts
98
+ const LOGICAL_TYPES = [
99
+ "UUID",
100
+ "String",
101
+ "Text",
102
+ "Integer",
103
+ "SmallInt",
104
+ "BigInt",
105
+ "Numeric",
106
+ "Boolean",
107
+ "Date",
108
+ "DateTime",
109
+ "Bytes",
110
+ "Json",
111
+ "Ref"
112
+ ];
113
+ /** Поля типу, спільні для реквізиту, константи й колонки. */
114
+ const valueTypeShape = {
115
+ type: z.enum(LOGICAL_TYPES).meta({ description: "Logical value type." }),
116
+ length: z.number().int().positive().optional().meta({ description: "Maximum length; required for String and allowed only there." }),
117
+ precision: z.number().int().positive().optional().meta({ description: "Total number of digits; allowed only for Numeric." }),
118
+ scale: z.number().int().nonnegative().optional().meta({ description: "Digits after the decimal point; requires precision." }),
119
+ ref: metadataRefSchema.optional().meta({ description: "Single reference target of a Ref value; mutually exclusive with allowedTypes." }),
120
+ allowedTypes: z.array(metadataRefSchema).min(1).optional().meta({ description: "Polymorphic reference targets of a Ref value; mutually exclusive with ref." }),
121
+ array: z.boolean().optional().meta({ description: "Whether the value is an array of the type." }),
122
+ /** Свідомо міжскоуповий Ref: FK без скоупної частини ключа. */
123
+ crossScope: z.literal(true).optional().meta({ description: "Marks a deliberately cross-scope Ref: the FK has no scope part in its key." })
124
+ };
125
+ /** Значення заповнення: вираз, який рахує сама БД на вставці (спека промоції §9.2). */
126
+ const FILL_VALUES = [
127
+ "now",
128
+ "today",
129
+ "newUuid"
130
+ ];
131
+ const FILL_TYPES = {
132
+ now: "DateTime",
133
+ today: "Date",
134
+ newUuid: "UUID"
135
+ };
136
+ /**
137
+ * Чи заповнення дає кожному рядку власне значення. `today` однакове для рядків
138
+ * одного дня, `now` — для рядків однієї транзакції, тож унікальна колонка з
139
+ * ними, як і зі скаляром чи порожнім значенням, може отримати дубль від другої
140
+ * вставки без значення; `newUuid` — ні. `Record` змушує нове заповнення назвати
141
+ * цей факт.
142
+ */
143
+ const FILL_DISTINCT_PER_ROW = {
144
+ now: false,
145
+ today: false,
146
+ newUuid: true
147
+ };
148
+ /** Схема `defaultValue`; суворі об'єкти, щоб зайвий ключ не пройшов мовчки. */
149
+ const defaultValueSchema = z.union([
150
+ z.string(),
151
+ z.number(),
152
+ z.boolean(),
153
+ z.strictObject({ fill: z.enum(FILL_VALUES).meta({ description: "Fill expression computed by the database: now (DateTime), today (Date), newUuid (UUID)." }) }),
154
+ z.strictObject({ empty: z.union([z.literal(true), z.enum(["object", "array"])]).meta({ description: "Empty value: true for an array of any type, object or array for a scalar Json." }) })
155
+ ]);
156
+ /** Скаляр відрізняється від об'єктної форми заповнення. */
157
+ function isScalarDefault(value) {
158
+ return typeof value !== "object";
159
+ }
160
+ /**
161
+ * Чи типове значення може збігтися у двох рядків, вставлених без значення:
162
+ * скаляр, порожнє значення й заповнення, однакове для різних рядків.
163
+ */
164
+ function defaultMayRepeat(value) {
165
+ return !(typeof value === "object" && "fill" in value && FILL_DISTINCT_PER_ROW[value.fill]);
166
+ }
167
+ /** Межі цілих типів Postgres; `BigInt`-число — у межах точного числа JSON. */
168
+ const INTEGER_RANGES = {
169
+ SmallInt: [-(2 ** 15), 2 ** 15 - 1],
170
+ Integer: [-(2 ** 31), 2 ** 31 - 1],
171
+ BigInt: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]
172
+ };
173
+ /** Межі `int8`: за межею точного числа JSON `BigInt` береться рядком. */
174
+ const INT8_RANGE = [-(2n ** 63n), 2n ** 63n - 1n];
175
+ const DECIMAL = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
176
+ const INTEGER_TEXT = /^[+-]?\d+$/;
177
+ const UUID_TEXT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
178
+ const DATE_TEXT = /^(\d{4})-(\d{2})-(\d{2})$/;
179
+ /**
180
+ * ISO 8601 з поясом (`Z`, `±hh`, `±hh:mm`, `±hhmm`): момент без поясу Postgres
181
+ * прочитав би в поясі сесії.
182
+ */
183
+ const DATE_TIME_TEXT = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-](\d{2})(?::?(\d{2}))?)$/;
184
+ /**
185
+ * JSON-форма скаляра для типу (спека П2 §5): булеве, число чи рядок. Чи
186
+ * значення в межах типу — окреме питання (`isWithinType`).
187
+ */
188
+ function fitsType(type, value) {
189
+ switch (type) {
190
+ case "Boolean": return typeof value === "boolean";
191
+ case "SmallInt":
192
+ case "Integer": return typeof value === "number";
193
+ case "BigInt":
194
+ case "Numeric": return typeof value === "number" || typeof value === "string";
195
+ default: return typeof value === "string";
196
+ }
197
+ }
198
+ /**
199
+ * Чи значення правильної форми лежить у множині значень типу: інакше знімок
200
+ * містив би `DEFAULT`, який Postgres відхилить або мовчки округлить.
201
+ * Одиночний `Ref` бере логічне ім'я значення перерахування — його існування
202
+ * перевіряє стадія 4.
203
+ */
204
+ function isWithinType(value, raw) {
205
+ if (typeof raw === "number" && INTEGER_RANGES[value.type] !== void 0) {
206
+ const [min, max] = INTEGER_RANGES[value.type];
207
+ return Number.isInteger(raw) && raw >= min && raw <= max;
208
+ }
209
+ const text = String(raw);
210
+ switch (value.type) {
211
+ case "BigInt": return INTEGER_TEXT.test(text) && BigInt(text) >= INT8_RANGE[0] && BigInt(text) <= INT8_RANGE[1];
212
+ case "Numeric": return (typeof raw === "number" || DECIMAL.test(text)) && fitsNumeric(text, value.precision, value.scale);
213
+ case "UUID": return UUID_TEXT.test(text);
214
+ case "String": return value.length === void 0 || [...text].length <= value.length;
215
+ case "Date": return isDate(text);
216
+ case "DateTime": return isDateTime(text);
217
+ default: return true;
218
+ }
219
+ }
220
+ /**
221
+ * `numeric(p, s)`: цілих цифр не більше `p - s`, дробових — не більше `s`
222
+ * (зайві дробові Postgres мовчки округлив би). Число JSON читається через
223
+ * десятковий запис, зокрема експоненційний.
224
+ */
225
+ function fitsNumeric(text, precision, scale) {
226
+ const exponent = /^([^eE]*)[eE]([+-]?\d+)$/.exec(text);
227
+ const mantissa = exponent?.[1] ?? text;
228
+ if (!DECIMAL.test(mantissa)) return false;
229
+ if (precision === void 0) return true;
230
+ const [whole = "", fraction = ""] = mantissa.replace(/^[+-]/, "").split(".");
231
+ const digits = whole + fraction;
232
+ const point = whole.length + Number(exponent?.[2] ?? 0);
233
+ const significant = digits.replace(/^0+/, "");
234
+ const leading = digits.length - significant.length;
235
+ const trimmed = significant.replace(/0+$/, "");
236
+ if (trimmed === "") return true;
237
+ const integerDigits = Math.max(0, point - leading);
238
+ const fractionDigits = Math.max(0, leading + trimmed.length - point);
239
+ const allowedScale = scale ?? 0;
240
+ return integerDigits <= precision - allowedScale && fractionDigits <= allowedScale;
241
+ }
242
+ /** Календарний день `YYYY-MM-DD`: `2026-02-30` Postgres відхилить. */
243
+ function isDate(text) {
244
+ const match = DATE_TEXT.exec(text);
245
+ if (match === null) return false;
246
+ const [year, month, day] = [
247
+ match[1],
248
+ match[2],
249
+ match[3]
250
+ ].map(Number);
251
+ if (year < 1) return false;
252
+ const date = /* @__PURE__ */ new Date(0);
253
+ date.setUTCFullYear(year, month - 1, day);
254
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
255
+ }
256
+ function isDateTime(text) {
257
+ const match = DATE_TIME_TEXT.exec(text);
258
+ if (match === null || !isDate(match[1])) return false;
259
+ const [hours, minutes, seconds, zoneHours, zoneMinutes] = [
260
+ match[2],
261
+ match[3],
262
+ match[4] ?? "0",
263
+ match[5] ?? "0",
264
+ match[6] ?? "0"
265
+ ].map(Number);
266
+ return hours < 24 && minutes < 60 && seconds < 60 && zoneHours <= 15 && zoneMinutes < 60;
267
+ }
268
+ /**
269
+ * Об'єктні форми типового значення (спека промоції §9.2): `fill` — лише на
270
+ * скалярі свого типу, `empty` — лише на масиві або скалярному Json. Підказка
271
+ * називає форму, яку слід ужити.
272
+ */
273
+ function refineObjectDefault(value, defaultValue, issue) {
274
+ const path = ["defaultValue"];
275
+ if ("fill" in defaultValue) {
276
+ const wanted = FILL_TYPES[defaultValue.fill];
277
+ if (value.array === true || value.type !== wanted) {
278
+ const form = FILL_VALUES.find((f) => FILL_TYPES[f] === value.type);
279
+ issue("type.default-fill-mismatch", "fill does not match the logical type", path, value.array !== true && form !== void 0 ? `{ "fill": "${form}" }` : "");
280
+ }
281
+ return;
282
+ }
283
+ if (value.array === true ? defaultValue.empty === true : value.type === "Json" && defaultValue.empty !== true) return;
284
+ issue("type.default-empty-mismatch", "empty does not match the logical type", path, value.array === true ? "{ \"empty\": true }" : value.type === "Json" ? "{ \"empty\": \"object\" } or { \"empty\": \"array\" }" : "");
285
+ }
286
+ /**
287
+ * Перевірки унікальності реквізиту: порівняння без регістру має сенс лише для
288
+ * скалярного рядка, а звуження `uniqueWithin` — лише для вже унікального
289
+ * реквізиту. Місце (власник чи батько об'єкта) перевіряє стадія 4: схема не
290
+ * знає виду об'єкта.
291
+ */
292
+ function refineUnique(value, ctx) {
293
+ if (value.unique === "ignoreCase" && (value.array === true || value.type !== "String" && value.type !== "Text")) ctx.addIssue({
294
+ code: "custom",
295
+ message: "unique \"ignoreCase\" applies only to a scalar String or Text",
296
+ path: ["unique"],
297
+ params: { rule: "type.unique-ignore-case-type" }
298
+ });
299
+ }
300
+ /** `uniqueWithin` звужує вже наявну унікальність, тож без `unique` безглуздий. */
301
+ function refineUniqueWithin(value, ctx) {
302
+ if (value.uniqueWithin !== void 0 && (value.unique === void 0 || value.unique === false)) ctx.addIssue({
303
+ code: "custom",
304
+ message: "uniqueWithin requires unique",
305
+ path: ["uniqueWithin"],
306
+ params: { rule: "attribute.unique-within-requires-unique" }
307
+ });
308
+ }
309
+ /**
310
+ * Перевірки сумісності параметрів типу; кожне порушення несе код правила.
311
+ * Типове значення перевіряється тут же — для реквізиту й константи одним
312
+ * шляхом.
313
+ */
314
+ function refineValueType(value, ctx) {
315
+ const issue = (rule, message, path, expected) => ctx.addIssue({
316
+ code: "custom",
317
+ message,
318
+ path,
319
+ params: expected === void 0 ? { rule } : {
320
+ rule,
321
+ expected
322
+ }
323
+ });
324
+ if (value.type === "String" && value.length === void 0) issue("type.length-required", "String type requires length", ["length"]);
325
+ if (value.type !== "String" && value.length !== void 0) issue("type.length-not-allowed", "Only String type accepts length", ["length"]);
326
+ if (value.type !== "Numeric" && value.precision !== void 0) issue("type.precision-not-allowed", "Only Numeric type accepts precision", ["precision"]);
327
+ if (value.scale !== void 0 && value.precision === void 0) issue("type.scale-requires-precision", "Scale requires precision", ["scale"]);
328
+ if (value.crossScope !== void 0 && value.type !== "Ref") issue("type.cross-scope-not-allowed", "Only Ref type accepts crossScope", ["crossScope"]);
329
+ const hasRef = value.ref !== void 0;
330
+ const hasAllowed = value.allowedTypes !== void 0;
331
+ if (value.type === "Ref") {
332
+ if (!hasRef && !hasAllowed) issue("type.ref-target-required", "Ref type requires either ref or allowedTypes", ["ref"]);
333
+ else if (hasRef && hasAllowed) issue("type.ref-exclusive", "ref and allowedTypes are mutually exclusive", ["allowedTypes"]);
334
+ } else {
335
+ if (hasRef) issue("type.ref-not-allowed", "Only Ref type accepts ref", ["ref"]);
336
+ if (hasAllowed) issue("type.ref-not-allowed", "Only Ref type accepts allowedTypes", ["allowedTypes"]);
337
+ }
338
+ const { defaultValue } = value;
339
+ if (defaultValue === void 0) return;
340
+ if (!isScalarDefault(defaultValue)) {
341
+ refineObjectDefault(value, defaultValue, issue);
342
+ return;
343
+ }
344
+ if (value.array === true || hasAllowed || value.type === "Bytes" || value.type === "Json") issue("type.default-not-allowed", "defaultValue is not allowed for an array, allowedTypes, Bytes or Json value", ["defaultValue"]);
345
+ else if (!fitsType(value.type, defaultValue)) issue("type.default-mismatch", "defaultValue does not match the logical type", ["defaultValue"]);
346
+ else if (!isWithinType(value, defaultValue)) issue("type.default-invalid", "defaultValue is outside the type", ["defaultValue"]);
347
+ }
348
+ const NUMERIC_BOUND_TYPES = [
349
+ "Integer",
350
+ "SmallInt",
351
+ "BigInt",
352
+ "Numeric"
353
+ ];
354
+ /**
355
+ * Конструкції JS-виразу, яких регулярні вирази Postgres (POSIX ARE) не знають
356
+ * або читають інакше: іменовані групи, `\p{…}`/`\P{…}`, `\k<…>`, а також
357
+ * `\b`/`\B` (в ARE це символ повернення й синонім скісної риски, межа слова
358
+ * — `\y`), групи-модифікатори `(?i:…)`/`(?-i:…)` (ARE їх не знає),
359
+ * `\u{…}` (в ARE `\u` — рівно чотири цифри) і `\xHH` (ARE поглинає всі
360
+ * наступні шістнадцяткові цифри, тож `\x41B` там — інший символ, ніж у JS).
361
+ * Ці вирази `new RegExp` приймає, а CHECK на розгортанні впав би або
362
+ * перевіряв би інше. Розбір по символах, щоб екранована скісна риска й клас
363
+ * `[...]` не давали хибних спрацювань.
364
+ */
365
+ function usesJsOnlyRegexSyntax(pattern) {
366
+ let inClass = false;
367
+ for (let i = 0; i < pattern.length; i++) {
368
+ const char = pattern[i];
369
+ if (char === "\\") {
370
+ const next = pattern[i + 1];
371
+ if (next === "p" || next === "P" || next === "k" || next === "x") return true;
372
+ if (next === "u" && pattern[i + 2] === "{") return true;
373
+ if (!inClass && (next === "b" || next === "B")) return true;
374
+ i++;
375
+ } else if (inClass) {
376
+ if (char === "]") inClass = false;
377
+ } else if (char === "[") inClass = true;
378
+ else if (char === "(" && pattern[i + 1] === "?") {
379
+ const mark = pattern[i + 2];
380
+ if (mark === "<" && pattern[i + 3] !== "=" && pattern[i + 3] !== "!") return true;
381
+ if (mark !== void 0 && /[a-zA-Z-]/.test(mark)) return true;
382
+ }
383
+ }
384
+ return false;
385
+ }
386
+ /** Десятковий запис у вигляді `цілі × 10^степінь` — для точного порівняння меж. */
387
+ function decimalParts(value) {
388
+ const [, sign = "", whole = "", fraction = "", exponent = "0"] = /^([+-]?)(\d*)\.?(\d*)(?:[eE]([+-]?\d+))?$/.exec(String(value));
389
+ const int = BigInt(`${whole}${fraction}` || "0");
390
+ return {
391
+ int: sign === "-" ? -int : int,
392
+ exp: Number(exponent) - fraction.length
393
+ };
394
+ }
395
+ function compareDecimals(a, b) {
396
+ const left = decimalParts(a);
397
+ const right = decimalParts(b);
398
+ const exp = Math.min(left.exp, right.exp);
399
+ const x = left.int * 10n ** BigInt(left.exp - exp);
400
+ const y = right.int * 10n ** BigInt(right.exp - exp);
401
+ return x < y ? -1 : x > y ? 1 : 0;
402
+ }
403
+ /**
404
+ * Межі числа й формат рядка (спека промоції §9.3): властивість лише на
405
+ * скалярі свого типу, межі — у множині значень типу й упорядковані, вираз
406
+ * мусить бути придатним для Postgres. Схема пропускає лише те, що компілятор
407
+ * зможе виразити CHECK-ом колонки.
408
+ */
409
+ function refineValueChecks(value, ctx) {
410
+ const issue = (rule, message, path) => ctx.addIssue({
411
+ code: "custom",
412
+ message,
413
+ path: [path],
414
+ params: { rule }
415
+ });
416
+ const scalar = value.array !== true;
417
+ const numeric = scalar && NUMERIC_BOUND_TYPES.includes(value.type);
418
+ const textual = scalar && (value.type === "String" || value.type === "Text");
419
+ for (const key of [
420
+ "nonNegative",
421
+ "positive",
422
+ "minValue",
423
+ "maxValue"
424
+ ]) if (value[key] !== void 0 && !numeric) issue("type.bound-type", "Numeric bounds apply only to a scalar Integer, SmallInt, BigInt or Numeric", key);
425
+ for (const key of ["pattern", "minLength"]) if (value[key] !== void 0 && !textual) issue("type.format-type", "pattern and minLength apply only to a scalar String or Text", key);
426
+ if (numeric) {
427
+ if (value.positive !== void 0 && value.nonNegative !== void 0) issue("type.bound-conflict", "positive and nonNegative are mutually exclusive", "nonNegative");
428
+ let valid = true;
429
+ for (const key of ["minValue", "maxValue"]) {
430
+ const bound = value[key];
431
+ if (bound === void 0) continue;
432
+ if (!(fitsType(value.type, bound) && (typeof bound === "number" || DECIMAL.test(bound)) && isWithinType(value, bound))) {
433
+ valid = false;
434
+ issue("type.bound-invalid", `${key} is outside the type`, key);
435
+ }
436
+ }
437
+ if (valid && value.minValue !== void 0 && value.maxValue !== void 0 && compareDecimals(value.minValue, value.maxValue) > 0) issue("type.bound-order", "minValue must not exceed maxValue", "minValue");
438
+ }
439
+ if (textual && value.pattern !== void 0) {
440
+ let compiles = true;
441
+ try {
442
+ new RegExp(value.pattern, "u");
443
+ } catch {
444
+ compiles = false;
445
+ }
446
+ if (!compiles || usesJsOnlyRegexSyntax(value.pattern)) issue("type.pattern-invalid", "pattern is not a valid expression for both JavaScript and Postgres", "pattern");
447
+ }
448
+ }
449
+ /**
450
+ * Чи скалярне типове значення порушує власний CHECK реквізиту: непорожність
451
+ * обов'язкового рядка, формат і межі числа (ті самі умови, що стадія 3 кладе
452
+ * в CHECK колонки). Статично й лише над скаляром: вираз заповнення (`fill`,
453
+ * `empty`) обчислює БД, і такі значення тут не судяться.
454
+ */
455
+ function defaultViolatesValueChecks(value) {
456
+ const { defaultValue } = value;
457
+ if (defaultValue === void 0 || !isScalarDefault(defaultValue)) return false;
458
+ if (typeof defaultValue === "string" && value.array !== true) {
459
+ const textual = value.type === "String" || value.type === "Text";
460
+ if (textual && value.required === true && /^\s*$/.test(defaultValue)) return true;
461
+ if (textual && value.pattern !== void 0 && !new RegExp(value.pattern, "u").test(defaultValue)) return true;
462
+ if (textual && value.minLength !== void 0 && [...defaultValue].length < value.minLength) return true;
463
+ }
464
+ if (value.array !== true && NUMERIC_BOUND_TYPES.includes(value.type) && typeof defaultValue !== "boolean") {
465
+ const below = (bound) => compareDecimals(defaultValue, bound) < 0;
466
+ if (value.nonNegative === true && below(0)) return true;
467
+ if (value.positive === true && compareDecimals(defaultValue, 0) <= 0) return true;
468
+ if (value.minValue !== void 0 && below(value.minValue)) return true;
469
+ if (value.maxValue !== void 0 && compareDecimals(defaultValue, value.maxValue) > 0) return true;
470
+ }
471
+ return false;
472
+ }
473
+ //#endregion
474
+ //#region src/model/schemas/attribute.ts
475
+ /**
476
+ * Поле значення: реквізит, вимір чи ресурс регістра. Унікальність імен у
477
+ * масиві й стиль написання імені перевіряють пізніші стадії — схема лише
478
+ * описує форму.
479
+ */
480
+ const fieldShape = {
481
+ id: metadataIdSchema.optional(),
482
+ name: elementNameSchema,
483
+ physicalName: physicalNameSchema.optional(),
484
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the attribute." }),
485
+ description: localizedStringSchema.optional().meta({ description: "Description of the attribute." }),
486
+ ...valueTypeShape,
487
+ required: z.boolean().default(false).meta({ description: "Whether a value is mandatory (NOT NULL)." }),
488
+ indexed: z.boolean().default(false).meta({ description: "Whether the attribute is indexed." }),
489
+ unique: z.union([z.boolean(), z.literal("ignoreCase")]).default(false).meta({ description: "Whether values must be unique; \"ignoreCase\" compares a scalar String or Text value case-insensitively." }),
490
+ defaultValue: defaultValueSchema.optional().meta({ description: "Default value of the attribute." }),
491
+ nonNegative: z.literal(true).optional().meta({ description: "Value must be zero or greater (CHECK); scalar Integer, SmallInt, BigInt or Numeric; excludes positive." }),
492
+ positive: z.literal(true).optional().meta({ description: "Value must be greater than zero (CHECK); scalar Integer, SmallInt, BigInt or Numeric; excludes nonNegative." }),
493
+ minValue: z.union([z.number(), z.string()]).optional().meta({ description: "Lower bound of the value (CHECK): a number or a decimal-fraction string within the type's range; numeric types only." }),
494
+ maxValue: z.union([z.number(), z.string()]).optional().meta({ description: "Upper bound of the value (CHECK): a number or a decimal-fraction string within the type's range; must not be below minValue; numeric types only." }),
495
+ pattern: z.string().min(1).optional().meta({ description: "Regular expression the value must match (CHECK); valid for both JavaScript (u flag) and Postgres, so no named groups, \\p{...}, \\k<...>, \\b, \\B, \\x, \\u{...} or (?flags) groups; scalar String or Text only." }),
496
+ minLength: z.number().int().positive().optional().meta({ description: "Minimum number of characters (CHECK); scalar String or Text only." })
497
+ };
498
+ /** Реквізит: поле значення, яке може бути персональним. */
499
+ const attributeShape = {
500
+ ...fieldShape,
501
+ personalData: z.literal(true).optional().meta({ description: "Marks the attribute as personal data: anonymization sets its columns to NULL, so it cannot be required." })
502
+ };
503
+ /**
504
+ * Знеособлення ставить колонку в `NULL`, тож обов'язковий персональний
505
+ * реквізит зробив би його неможливим — відхиляємо на схемі.
506
+ */
507
+ function refinePersonalData(value, ctx) {
508
+ if (value.personalData === true && value.required) ctx.addIssue({
509
+ code: "custom",
510
+ message: "A personalData attribute cannot be required",
511
+ path: ["personalData"],
512
+ params: { rule: "attribute.personal-data-required" }
513
+ });
514
+ }
515
+ const attributeSchema = z.strictObject(attributeShape).superRefine((value, ctx) => {
516
+ refineValueType(value, ctx);
517
+ refineUnique(value, ctx);
518
+ refineValueChecks(value, ctx);
519
+ refinePersonalData(value, ctx);
520
+ });
521
+ /**
522
+ * Власний реквізит довідника: лише тут має сенс `uniqueWithin` (власник і
523
+ * батько — стандартні реквізити довідника). Місце за налаштуваннями довідника
524
+ * (є власники, є ієрархія) перевіряє стадія 4.
525
+ */
526
+ const catalogAttributeSchema = z.strictObject({
527
+ ...attributeShape,
528
+ uniqueWithin: z.enum(["owner", "parent"]).optional().meta({ description: "Narrows uniqueness to the owner or the parent of the object (needs unique; own attributes of an object whose kind has that standard attribute)." })
529
+ }).superRefine((value, ctx) => {
530
+ refineValueType(value, ctx);
531
+ refineUnique(value, ctx);
532
+ refineValueChecks(value, ctx);
533
+ refinePersonalData(value, ctx);
534
+ refineUniqueWithin(value, ctx);
535
+ });
536
+ /**
537
+ * Вимір регістра чи ресурс регістра відомостей: форма реквізиту без
538
+ * `personalData`. Персональне в розрізі обліку — посилання на довідник, і
539
+ * знеособлюється рядок довідника, а не ключ чи значення запису регістра;
540
+ * строга схема відкидає поле як невідомий ключ.
541
+ */
542
+ const registerFieldSchema = z.strictObject(fieldShape).superRefine((value, ctx) => {
543
+ refineValueType(value, ctx);
544
+ refineUnique(value, ctx);
545
+ refineValueChecks(value, ctx);
546
+ });
547
+ //#endregion
548
+ //#region src/model/schemas/pg-schema.ts
549
+ /**
550
+ * Схема, яку платформа резервує за собою: у ній живе системний шар
551
+ * (ідентичності, поточний користувач, довідник міток). Застосунок не може
552
+ * класти туди власні об'єкти, інакше його імена зіткнулися б із платформними.
553
+ */
554
+ const PLATFORM_SCHEMA = "simetra";
555
+ /**
556
+ * Ім'я PostgreSQL-схеми, яку обирає застосунок. Єдине місце перевірки
557
+ * резервування: поля схем, що несуть ім'я схеми застосунку, беруть цю схему,
558
+ * а не повторюють порівняння.
559
+ */
560
+ const appSchemaNameSchema = z.string().refine((schema) => schema !== PLATFORM_SCHEMA, {
561
+ message: `Schema ${PLATFORM_SCHEMA} belongs to the platform`,
562
+ params: { rule: "schema.reserved" }
563
+ });
564
+ //#endregion
565
+ //#region src/model/schemas/composite-index.ts
566
+ /**
567
+ * Складені індекси об'єкта чи його табличної частини. Назви — логічні імена
568
+ * реквізитів і стандартних реквізитів тієї самої таблиці; носій скоупу
569
+ * додає компілятор, тож у переліку його немає. Поле мають лише види з фактом
570
+ * реєстру `compositeIndexes`: схема не приймає того, чого компілятор не
571
+ * збудує.
572
+ */
573
+ const compositeIndexesSchema = z.array(z.strictObject({ attributes: z.array(z.union([z.string().min(1), z.strictObject({
574
+ name: z.string().min(1).meta({ description: "Logical name of the attribute." }),
575
+ order: z.literal("desc").meta({ description: "Descending order of this key part." })
576
+ })])).min(1).meta({ description: "Attributes and standard attributes of the same table in key order; a name, or { name, order: desc } for a descending part." }) }).meta({ description: "Non-unique btree index over attributes of the same table; the scope carrier is added first automatically." })).default([]);
577
+ //#endregion
578
+ //#region src/model/schemas/object-header.ts
579
+ /**
580
+ * Спільна «шапка» файлу об'єкта метаданих. `kind` кожен вид додає сам як
581
+ * літерал. `id` і `physicalName` опційні у файлі: їх призначає інструментарій
582
+ * при створенні, а не автор вручну.
583
+ */
584
+ const objectHeaderShape = {
585
+ $schema: z.string().optional().meta({ description: "Editor hint: path to the JSON Schema of this file." }),
586
+ id: metadataIdSchema.optional(),
587
+ name: objectNameSchema.meta({ description: "Logical object name in PascalCase." }),
588
+ physicalName: physicalNameSchema.optional(),
589
+ /** PG-схема об'єкта; за відсутності діє `defaultSchema` проєкту. */
590
+ schema: appSchemaNameSchema.optional().meta({ description: "PostgreSQL schema of the object; the project defaultSchema applies when absent." }),
591
+ /**
592
+ * Вид скоупу об'єкта або `none`. Обов'язковість за наявності видів скоупу
593
+ * в проєкті — правило стадії, а не схеми: лише вона бачить проєкт.
594
+ */
595
+ scope: z.string().optional().meta({ description: "Scope kind of the object, or none to keep it outside any scope. Required when the project declares scope kinds." }),
596
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the object." }),
597
+ description: localizedStringSchema.optional().meta({ description: "Description of the object." })
598
+ };
599
+ /** Користувацькі перевизначення заголовків і описів стандартних реквізитів. */
600
+ const standardAttributeOverridesSchema = z.record(z.string(), z.strictObject({
601
+ title: localizedStringSchema.optional().meta({ description: "Overridden title of the standard attribute." }),
602
+ description: localizedStringSchema.optional().meta({ description: "Overridden description of the standard attribute." })
603
+ })).optional().default({}).meta({ description: "Custom titles and descriptions of derived standard attributes, keyed by standard attribute name." });
604
+ //#endregion
605
+ //#region src/model/schemas/tabular-section.ts
606
+ /** Таблична частина об'єкта. */
607
+ const tabularSectionSchema = z.strictObject({
608
+ id: metadataIdSchema.optional(),
609
+ name: elementNameSchema,
610
+ physicalName: physicalNameSchema.optional(),
611
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the tabular section." }),
612
+ standardAttributeOverrides: standardAttributeOverridesSchema,
613
+ attributes: z.array(attributeSchema).default([]).meta({ description: "Attributes of the section rows." }),
614
+ indexes: compositeIndexesSchema.meta({ description: "Composite indexes over the section rows." })
615
+ }).meta({ description: "Tabular section: a list of rows owned by an object." });
616
+ //#endregion
617
+ //#region src/model/schemas/rules.ts
618
+ /**
619
+ * Коди власних перевірок T0. Кожна перевірка, що не виражається самою схемою
620
+ * Zod, додає issue з `params: { rule }` — так споживачі (стадії валідації,
621
+ * студія) розпізнають порушення за стабільним кодом, а не за текстом
622
+ * повідомлення. Нові коди дописують задачі, що додають перевірки.
623
+ */
624
+ const SCHEMA_RULES = [
625
+ "type.length-required",
626
+ "type.length-not-allowed",
627
+ "type.precision-not-allowed",
628
+ "type.scale-requires-precision",
629
+ "type.ref-target-required",
630
+ "type.ref-exclusive",
631
+ "type.ref-not-allowed",
632
+ "register.balance-control-type",
633
+ "customTable.column-type",
634
+ "customTable.identity-type",
635
+ "pgEnum.value-duplicate",
636
+ "scope.name-reserved",
637
+ "schema.reserved",
638
+ "scope.not-allowed",
639
+ "type.cross-scope-not-allowed",
640
+ "type.default-not-allowed",
641
+ "type.default-mismatch",
642
+ "type.default-invalid",
643
+ "type.default-fill-mismatch",
644
+ "type.default-empty-mismatch",
645
+ "type.unique-ignore-case-type",
646
+ "attribute.unique-within-requires-unique",
647
+ "attribute.personal-data-required",
648
+ "type.bound-type",
649
+ "type.bound-conflict",
650
+ "type.bound-order",
651
+ "type.bound-invalid",
652
+ "type.format-type",
653
+ "type.pattern-invalid",
654
+ "posting.parse",
655
+ "debt.not-canonical"
656
+ ];
657
+ //#endregion
658
+ //#region src/model/schemas/public-read.ts
659
+ /**
660
+ * Ролі API, яким об'єкт відкриває читання (спека промоції §9.3). Поле мають
661
+ * лише види з RLS (факт реєстру `rowLevelSecurity`): без RLS таблиця не має
662
+ * політик, і декларації нічим було б виконати. Політику генерує
663
+ * `buildAccessUnits` з контракту `Contracts.access`. Значення — слово файлу метаданих, а не ім'я ролі в базі:
664
+ * призначення дає `PUBLIC_READ_PURPOSES`, ім'я — `PROVIDER_API_ROLES`
665
+ * провайдера проєкту.
666
+ */
667
+ const PUBLIC_READ_ROLES = ["authenticated", "anon"];
668
+ /**
669
+ * Призначення ролі для кожного значення `publicRead` — лише роль запиту: тип
670
+ * не допускає сервісну роль, тож читання таблиці їй не відкривається
671
+ * (платформна спека §6.7).
672
+ */
673
+ const PUBLIC_READ_PURPOSES = {
674
+ authenticated: "user",
675
+ anon: "anonymous"
676
+ };
677
+ const publicReadSchema = z.enum(PUBLIC_READ_ROLES).optional().meta({ description: "API role that may read every row of the object: authenticated users or anonymous visitors. Absent means no public read." });
678
+ //#endregion
679
+ //#region src/model/kinds/actions.ts
680
+ /** The platform's standard action vocabulary. */
681
+ const STANDARD_ACTIONS = [
682
+ "read",
683
+ "create",
684
+ "update",
685
+ "markDeletion",
686
+ "delete",
687
+ "post",
688
+ "unpost",
689
+ "write"
690
+ ];
691
+ const readAction = {
692
+ name: "read",
693
+ requires: [],
694
+ effects: {
695
+ dml: [],
696
+ header: [],
697
+ tabularSections: false
698
+ }
699
+ };
700
+ const deleteAction = {
701
+ name: "delete",
702
+ requires: [],
703
+ effects: {
704
+ dml: ["delete"],
705
+ header: [],
706
+ tabularSections: false
707
+ }
708
+ };
709
+ const markDeletionAction = {
710
+ name: "markDeletion",
711
+ requires: [],
712
+ effects: {
713
+ dml: ["update"],
714
+ header: ["deletionMark"],
715
+ tabularSections: false
716
+ }
717
+ };
718
+ function createAction(tabularSections) {
719
+ return {
720
+ name: "create",
721
+ requires: [],
722
+ effects: {
723
+ dml: ["insert"],
724
+ header: "all",
725
+ tabularSections
726
+ }
727
+ };
728
+ }
729
+ function updateAction(tabularSections, dml = ["update"]) {
730
+ return {
731
+ name: "update",
732
+ requires: [],
733
+ effects: {
734
+ dml,
735
+ header: "all",
736
+ tabularSections
737
+ }
738
+ };
739
+ }
740
+ const postAction = {
741
+ name: "post",
742
+ requires: ["update"],
743
+ effects: {
744
+ dml: ["update"],
745
+ header: ["posted"],
746
+ tabularSections: false
747
+ }
748
+ };
749
+ const unpostAction = {
750
+ name: "unpost",
751
+ requires: ["post"],
752
+ effects: {
753
+ dml: ["update"],
754
+ header: ["posted"],
755
+ tabularSections: false
756
+ }
757
+ };
758
+ const writeAction = {
759
+ name: "write",
760
+ requires: [],
761
+ effects: {
762
+ dml: [
763
+ "insert",
764
+ "update",
765
+ "delete"
766
+ ],
767
+ header: "all",
768
+ tabularSections: false
769
+ }
770
+ };
771
+ /** The reference vocabulary of a record kind: read plus the four writes. */
772
+ function recordActions(tabularSections) {
773
+ return [
774
+ readAction,
775
+ createAction(tabularSections),
776
+ updateAction(tabularSections),
777
+ markDeletionAction,
778
+ deleteAction
779
+ ];
780
+ }
781
+ /**
782
+ * Direct requirements of an action plus the general edge: every action that
783
+ * writes something requires `read`.
784
+ */
785
+ function actionRequires(action) {
786
+ const edges = [...action.requires];
787
+ if (action.effects.dml.length > 0 && !edges.includes("read")) edges.push("read");
788
+ return edges;
789
+ }
790
+ /**
791
+ * Transitive closure of requirements: every action maps to the sorted set of
792
+ * actions it needs, without itself. Throws on a cycle; the compiler rejects
793
+ * cycles earlier with a diagnostic.
794
+ */
795
+ function closeRequires(actions) {
796
+ const direct = new Map(actions.map((a) => [a.name, a.requires]));
797
+ const closed = /* @__PURE__ */ new Map();
798
+ const visiting = /* @__PURE__ */ new Set();
799
+ const close = (name) => {
800
+ const known = closed.get(name);
801
+ if (known !== void 0) return known;
802
+ if (visiting.has(name)) throw new Error(`requires cycle at "${name}"`);
803
+ visiting.add(name);
804
+ const all = /* @__PURE__ */ new Set();
805
+ for (const edge of direct.get(name) ?? []) {
806
+ all.add(edge);
807
+ for (const deeper of close(edge)) all.add(deeper);
808
+ }
809
+ visiting.delete(name);
810
+ all.delete(name);
811
+ const sorted = [...all].sort();
812
+ closed.set(name, sorted);
813
+ return sorted;
814
+ };
815
+ for (const a of actions) close(a.name);
816
+ return closed;
817
+ }
818
+ //#endregion
819
+ //#region src/model/schemas/rights.ts
820
+ /**
821
+ * Кастомна дія об'єкта (спека прав §3): елемент з `id` і `name`, але без
822
+ * `physicalName` — у даних дію називає її UUID, а не ім'я. `dml` не
823
+ * оголошується: компілятор виводить його з того, чи є що писати, тож
824
+ * оголошення не може розійтися з ефектами. `title`/`description` відкладено
825
+ * до плану зі споживачем (Р1a-23).
826
+ */
827
+ const customActionSchema = z.strictObject({
828
+ id: metadataIdSchema.optional(),
829
+ name: elementNameSchema.meta({ description: "Logical name of the custom action, camelCase like the standard action words; must not repeat a standard action of the kind." }),
830
+ requires: z.array(elementNameSchema).default([]).meta({ description: "Actions a holder of this action must also hold: standard action words of the kind or names of custom actions of the same object." }),
831
+ effects: z.strictObject({
832
+ header: z.union([z.literal("all"), z.array(elementNameSchema)]).optional().meta({ description: "Header columns the action writes: all, or logical names of attributes and standard attributes of the object." }),
833
+ tabularSections: z.boolean().optional().meta({ description: "Whether the action writes the tabular section rows." })
834
+ }).default({}).meta({ description: "What the action writes itself; an action that writes anything is an update." })
835
+ });
836
+ /** Кастомні дії об'єкта — поле видів з контрактом прав. */
837
+ const customActionsSchema = z.array(customActionSchema).default([]).meta({ description: "Custom actions of the object beyond the standard actions of its kind." });
838
+ /**
839
+ * Носій прав (Рх21): реквізит самого об'єкта або шлях з двох кроків —
840
+ * посилання в межах скоупу й реквізит його цілі. Довших шляхів немає:
841
+ * кожен крок — це з'єднання в політиці рядка, а один крок покриває
842
+ * «коментар задачі належить виконавцю задачі».
843
+ */
844
+ const rightsCarrierSchema = z.union([elementNameSchema, z.tuple([elementNameSchema, elementNameSchema])]).meta({ description: "An attribute of this object, or a path [attribute, attribute of its target]" });
845
+ /** Власники рядка (спека прав §4.2): порожній перелік — це відсутність поля. */
846
+ const ownershipSchema = z.array(rightsCarrierSchema).min(1);
847
+ /**
848
+ * Вимір доступу проєкту (спека прав §4.4): скоуплений довідник значень і
849
+ * джерело значень користувача — таблиця зв'язку чи дослівна функція. Вимір —
850
+ * елемент проєкту з UUID, бо обсяг гранту називає його id, а ім'я може
851
+ * змінитися. `title`/`description` відкладено до плану зі споживачем (Р1a-23).
852
+ */
853
+ const accessDimensionSchema = z.strictObject({
854
+ id: metadataIdSchema.optional(),
855
+ name: elementNameSchema.meta({ description: "Logical name of the access dimension, unique among all named elements of the project." }),
856
+ target: metadataRefSchema.meta({ description: "Catalog of the dimension values; scoped when the project has scope kinds." }),
857
+ values: z.union([z.strictObject({ relation: z.strictObject({
858
+ object: metadataRefSchema.meta({ description: "Object whose rows link a user or a member to a value of the dimension." }),
859
+ subject: elementNameSchema.meta({ description: "Reference of the relation object to the users catalog or to the membership catalog." }),
860
+ value: elementNameSchema.meta({ description: "Reference of the relation object to the target catalog." })
861
+ }).meta({ description: "Values of a user read from a relation." }) }), z.strictObject({ function: z.strictObject({
862
+ schema: appSchemaNameSchema.min(1).optional().meta({ description: "PostgreSQL schema of the function; the project default schema when omitted." }),
863
+ name: z.string().min(1).meta({ description: "Name of a verbatim SQL function that returns the value ids of the current user." })
864
+ }).meta({ description: "Values of a user returned by a function." }) })]).meta({ description: "Where the values of the current user come from." })
865
+ });
866
+ /**
867
+ * Мапінг об'єкта на вимір: реквізит або шлях з двох кроків (як носій прав,
868
+ * Рх21), чий кінцевий `Ref` — на довідник значень виміру.
869
+ */
870
+ const accessMappingSchema = z.union([z.strictObject({
871
+ attribute: elementNameSchema.meta({ description: "Attribute of this object that references the dimension target." }),
872
+ dimension: elementNameSchema.meta({ description: "Name of a project access dimension." })
873
+ }), z.strictObject({
874
+ ref: z.tuple([elementNameSchema, elementNameSchema]).meta({ description: "Path [attribute, attribute of its target] whose last reference is to the dimension target." }),
875
+ dimension: elementNameSchema.meta({ description: "Name of a project access dimension." })
876
+ })]);
877
+ /** Мапінги `access` об'єкта: порожній перелік — це відсутність поля. */
878
+ const accessSchema = z.array(accessMappingSchema).min(1).meta({ description: "Access dimensions that restrict the rows of this object, each with its carrier." });
879
+ /**
880
+ * Рівень призначення (спека прав §4.1, §4.7): глобальний, вид скоупу чи
881
+ * об'єкт-контейнер. Одна форма для ролі й джерела призначень, тож рівень
882
+ * джерела порівнюється з рівнем ролі без перекладу.
883
+ */
884
+ const assignedOnSchema = z.union([
885
+ z.literal("global"),
886
+ z.strictObject({ scopeKind: elementNameSchema.meta({ description: "Name of the project scope kind of the level." }) }),
887
+ z.strictObject({ container: metadataRefSchema.meta({ description: "Rights container object of the level." }) })
888
+ ]).meta({ description: "Level of the assignment: global, a scope kind or a rights container." });
889
+ /**
890
+ * Прийняте джерело членства (спека прав §4.7): `CustomTable`, чиї рядки
891
+ * пов'язують користувача зі значенням виду скоупу. Колонки — логічні імена
892
+ * колонок таблиці, тож перейменування колонки переписує мапінг.
893
+ */
894
+ const membershipSourceSchema = z.strictObject({
895
+ id: metadataIdSchema.optional(),
896
+ name: elementNameSchema.meta({ description: "Logical name of the membership source, unique among all named elements of the project." }),
897
+ scopeKind: elementNameSchema.meta({ description: "Name of the project scope kind whose membership the table holds." }),
898
+ table: metadataRefSchema.meta({ description: "Adopted table (CustomTable) with the membership rows." }),
899
+ columns: z.strictObject({
900
+ scope: elementNameSchema.meta({ description: "Column with the scope value." }),
901
+ user: elementNameSchema.meta({ description: "Column with the user id." }),
902
+ active: elementNameSchema.optional().meta({ description: "Boolean column; only active rows count as membership." })
903
+ }).meta({ description: "Logical names of the table columns." })
904
+ });
905
+ /**
906
+ * Прийняте джерело призначень (спека прав §4.7): `CustomTable`, чиї рядки
907
+ * дають учаснику роль на одному рівні. Рівень — стала джерела (Р1a-16).
908
+ */
909
+ const assignmentSourceSchema = z.strictObject({
910
+ id: metadataIdSchema.optional(),
911
+ name: elementNameSchema.meta({ description: "Logical name of the assignment source, unique among all named elements of the project." }),
912
+ assignedOn: assignedOnSchema,
913
+ table: metadataRefSchema.meta({ description: "Adopted table (CustomTable) with the assignment rows." }),
914
+ columns: z.strictObject({
915
+ member: elementNameSchema.meta({ description: "Column with the member (a user for the global level)." }),
916
+ role: elementNameSchema.meta({ description: "Column with the role key declared by a role in sourceKeys." }),
917
+ container: elementNameSchema.optional().meta({ description: "Column with the container; required for the container level only." }),
918
+ active: elementNameSchema.optional().meta({ description: "Boolean column; only active rows count as assignments." })
919
+ }).meta({ description: "Logical names of the table columns." })
920
+ });
921
+ /**
922
+ * Рівень ролі (спека прав §4.1, Рх7): рівні джерела плюс «кожен дійсний
923
+ * користувач» — без рядків призначень, тож джерелам ця форма не потрібна
924
+ * (Р1b-3).
925
+ */
926
+ const roleAssignedOnSchema = z.union([assignedOnSchema, z.literal("everyUser").meta({ description: "Every authenticated user, with no assignment rows." })]).meta({ description: "Level of the role: global, every user, a scope kind or a rights container." });
927
+ /**
928
+ * Шапка декларацій прав: без PG-схеми, скоупу й фізичного імені — у базі
929
+ * набір і роль живуть лише в згенерованій проєкції, а в даних їх називає
930
+ * UUID (Р1b-9). `title`/`description` відкладено до плану зі споживачем
931
+ * (Р1b-14).
932
+ */
933
+ const rightsDeclarationHeader = z.object(objectHeaderShape).omit({
934
+ schema: true,
935
+ scope: true,
936
+ physicalName: true,
937
+ title: true,
938
+ description: true
939
+ }).shape;
940
+ const includeSchema = z.array(metadataRefSchema).default([]).meta({ description: "Rights sets whose grants this declaration includes." });
941
+ /**
942
+ * Обсяг гранту (спека прав §3): усі рядки, власні рядки чи рядки зі значенням
943
+ * виміру доступу користувача. Вимір названо іменем елемента проєкту, тож
944
+ * перейменування виміру переписує грант.
945
+ */
946
+ const extentSchema = z.union([
947
+ z.literal("any"),
948
+ z.literal("own"),
949
+ z.strictObject({ dimension: elementNameSchema.meta({ description: "Name of a project access dimension." }) })
950
+ ]).meta({ description: "Rows the grant opens: any row, own rows, or rows with a value of an access dimension of the user." });
951
+ /**
952
+ * Об'єкти гранту (Р1b-6): явний перелік або «усі об'єкти рівня ролі, чиї
953
+ * дії мають цю» — щоб роль не перелічувала кожен документ заради `post`.
954
+ */
955
+ const objectSelectorSchema = z.union([z.array(metadataRefSchema).min(1), z.strictObject({ withAction: z.enum(STANDARD_ACTIONS).meta({ description: "Standard action word; selects every object of the role level that has it." }) })]).meta({ description: "Objects of the grant: a list, or every object of the role level with an action." });
956
+ const grantActionsSchema = z.array(elementNameSchema).min(1).meta({ description: "Standard action words, or names of custom actions of the single object of the grant." });
957
+ const grantSchema = z.strictObject({
958
+ objects: objectSelectorSchema,
959
+ actions: grantActionsSchema,
960
+ extent: extentSchema
961
+ }).meta({ description: "Grant the actions on the objects within the extent." });
962
+ const grantAllSchema = z.strictObject({ extent: extentSchema }).meta({ description: "Grant every action the role level allows on every object of the level that supports the extent." });
963
+ const denySchema = z.strictObject({
964
+ objects: objectSelectorSchema,
965
+ actions: grantActionsSchema,
966
+ extent: extentSchema.optional().meta({ description: "Extent to remove; every extent of the actions when omitted." })
967
+ }).meta({ description: "Remove the actions from what the grants of the role and its sets give." });
968
+ /** Запис гранту набору: без `deny` — віднімання належить ролі (Р1b-5). */
969
+ const setGrantEntrySchema = z.union([z.strictObject({ grantAll: grantAllSchema }), z.strictObject({ grant: grantSchema })]);
970
+ /** Запис гранту ролі: `deny` віднімає з архетипу після розгортання (Р1b-5). */
971
+ const grantEntrySchema = z.union([
972
+ z.strictObject({ grantAll: grantAllSchema }),
973
+ z.strictObject({ grant: grantSchema }),
974
+ z.strictObject({ deny: denySchema })
975
+ ]);
976
+ /** Form of a grant entry (`grantAll`, `grant` or `deny`) and its body. */
977
+ function grantEntryForm(entry) {
978
+ if ("grantAll" in entry) return {
979
+ form: "grantAll",
980
+ body: entry.grantAll
981
+ };
982
+ if ("grant" in entry) return {
983
+ form: "grant",
984
+ body: entry.grant
985
+ };
986
+ return {
987
+ form: "deny",
988
+ body: entry.deny
989
+ };
990
+ }
991
+ /**
992
+ * Набір прав (спека прав §4.1, Рх16): іменована група грантів, яку
993
+ * включають ролі й інші набори. Цикл включень — помилка компілятора.
994
+ */
995
+ const rightsSetSchema = z.strictObject({
996
+ ...rightsDeclarationHeader,
997
+ kind: z.literal("RightsSet").meta({ description: "Metadata kind; always RightsSet." }),
998
+ include: includeSchema,
999
+ grants: z.array(setGrantEntrySchema).default([]).meta({ description: "Grants of the set; a set has no level and cannot deny." })
1000
+ });
1001
+ /**
1002
+ * Роль (спека прав §4.1): рівень призначення, повні права, включені набори.
1003
+ * `assignedOn` призначається раз (Рх20); `sourceKeys` — ключі ролі в даних
1004
+ * прийнятих джерел призначень (§4.7).
1005
+ */
1006
+ const roleSchema = z.strictObject({
1007
+ ...rightsDeclarationHeader,
1008
+ kind: z.literal("Role").meta({ description: "Metadata kind; always Role." }),
1009
+ assignedOn: roleAssignedOnSchema,
1010
+ fullAccess: z.boolean().default(false).meta({ description: "Bypass the rights checks on the objects of the role level; not on a container role or every user." }),
1011
+ order: z.number().int().nonnegative().optional().meta({ description: "Position of the role in the rights matrix." }),
1012
+ assignable: z.boolean().default(true).meta({ description: "Whether administrators assign the role; an owner role is handed over by its own command." }),
1013
+ maxHolders: z.number().int().positive().optional().meta({ description: "Most holders of the role on one level value." }),
1014
+ rootCreator: z.boolean().default(false).meta({ description: "Scope level only: the command that creates a scope root assigns this role to its creator." }),
1015
+ sourceKeys: z.array(z.strictObject({
1016
+ source: elementNameSchema.meta({ description: "Name of a project assignment source of the same level." }),
1017
+ key: z.string().min(1).meta({ description: "Role key in the role column of the source." })
1018
+ })).default([]).meta({ description: "Keys that name this role in adopted assignment sources." }),
1019
+ include: includeSchema,
1020
+ grants: z.array(grantEntrySchema).default([]).meta({ description: "Grants of the role; deny entries remove from what the grants and the included sets give." })
1021
+ });
1022
+ //#endregion
1023
+ //#region src/model/schemas/catalog.ts
1024
+ /** Довідник. */
1025
+ const catalogSchema = z.strictObject({
1026
+ ...objectHeaderShape,
1027
+ kind: z.literal("Catalog").meta({ description: "Metadata kind; always Catalog." }),
1028
+ kindLabel: physicalNameSchema.optional().meta({ description: "Physical kind label of the object. Assigned once at creation and never changed, so a rename keeps it." }),
1029
+ role: z.literal("users").optional().meta({ description: "System role of the catalog: users marks the users catalog that the platform layer provisions and references; at most one per project, unscoped." }),
1030
+ codeLength: z.number().int().nonnegative().default(9).meta({ description: "Length of the code attribute; 0 means the catalog has no code." }),
1031
+ codeType: z.enum(["String", "Number"]).default("String").meta({ description: "Value type of the code attribute." }),
1032
+ descriptionLength: z.number().int().nonnegative().default(150).meta({ description: "Length of the description attribute; 0 means the catalog has no description." }),
1033
+ hierarchyType: z.enum([
1034
+ "None",
1035
+ "FoldersAndItems",
1036
+ "ItemsOnly"
1037
+ ]).default("None").meta({ description: "Hierarchy mode: none, folders and items, or items nested under items." }),
1038
+ owners: z.array(metadataRefSchema).default([]).meta({ description: "Objects that own items of this catalog (subordination)." }),
1039
+ autonumber: z.boolean().default(true).meta({ description: "Whether the code is generated automatically." }),
1040
+ codeUnique: z.boolean().default(true).meta({ description: "Whether the code must be unique." }),
1041
+ mainPresentation: z.enum(["Code", "Description"]).default("Description").meta({ description: "Which standard attribute represents an item in lists and references." }),
1042
+ predefinedItems: z.array(z.strictObject({
1043
+ id: metadataIdSchema.optional(),
1044
+ name: objectNameSchema.meta({ description: "Logical name of the predefined item." }),
1045
+ physicalName: physicalNameSchema.optional().meta({ description: "Physical label of the item stored in predefined_name. Assigned once at creation and never changed, so a rename keeps it." }),
1046
+ description: localizedStringSchema.optional().meta({ description: "Description of the predefined item." })
1047
+ })).default([]).meta({ description: "Items that exist in every deployment and are referenced by name." }),
1048
+ trackAuthor: z.boolean().default(false).meta({ description: "Adds the standard createdBy and updatedBy attributes referencing the users catalog; requires a catalog with role users." }),
1049
+ membership: z.strictObject({ user: elementNameSchema.meta({ description: "Logical name of the scalar Ref attribute to the users catalog; nullable for an invited member without an account." }) }).optional().meta({ description: "Marks a scoped catalog as the membership of its scope kind: one member per user and scope value, a generated member lookup and an optional generated scope set function." }),
1050
+ publicRead: publicReadSchema,
1051
+ customActions: customActionsSchema,
1052
+ access: accessSchema.optional(),
1053
+ ownership: ownershipSchema.optional().meta({ description: "Owners of a row: users or members the own extent of a grant opens the row to." }),
1054
+ containerBinding: rightsCarrierSchema.optional().meta({ description: "Attribute (or a two-step path of attributes) that binds a row to its rights container: the catalog flagged rightsContainer." }),
1055
+ rightsContainer: z.boolean().optional().meta({ description: "Marks the catalog as a rights container: objects bind to its rows with containerBinding, and a grant on the container covers them." }),
1056
+ standardAttributeOverrides: standardAttributeOverridesSchema,
1057
+ attributes: z.array(catalogAttributeSchema).default([]).meta({ description: "Custom attributes of the catalog." }),
1058
+ tabularSections: z.array(tabularSectionSchema).default([]).meta({ description: "Tabular sections of the catalog." }),
1059
+ indexes: compositeIndexesSchema.meta({ description: "Composite indexes over the catalog attributes." })
1060
+ });
1061
+ //#endregion
1062
+ //#region src/model/posting/parse.ts
1063
+ var ParseError = class extends Error {
1064
+ offset;
1065
+ constructor(message, offset) {
1066
+ super(message);
1067
+ this.offset = offset;
1068
+ }
1069
+ };
1070
+ const COMPARISON_OPS = /* @__PURE__ */ new Set([
1071
+ "=",
1072
+ "!=",
1073
+ "<",
1074
+ "<=",
1075
+ ">",
1076
+ ">="
1077
+ ]);
1078
+ const IDENT_START = /[A-Za-z_]/;
1079
+ const IDENT_PART = /[A-Za-z0-9_]/;
1080
+ const DIGIT = /[0-9]/;
1081
+ function tokenize(text) {
1082
+ const tokens = [];
1083
+ let i = 0;
1084
+ while (i < text.length) {
1085
+ const ch = text.charAt(i);
1086
+ if (/\s/.test(ch)) {
1087
+ i++;
1088
+ continue;
1089
+ }
1090
+ const start = i;
1091
+ if (IDENT_START.test(ch)) {
1092
+ while (i < text.length && IDENT_PART.test(text.charAt(i))) i++;
1093
+ tokens.push({
1094
+ kind: "ident",
1095
+ text: text.slice(start, i),
1096
+ start,
1097
+ end: i
1098
+ });
1099
+ } else if (DIGIT.test(ch)) {
1100
+ while (i < text.length && DIGIT.test(text.charAt(i))) i++;
1101
+ if (text.charAt(i) === "." && DIGIT.test(text.charAt(i + 1))) {
1102
+ i++;
1103
+ while (i < text.length && DIGIT.test(text.charAt(i))) i++;
1104
+ }
1105
+ tokens.push({
1106
+ kind: "number",
1107
+ text: text.slice(start, i),
1108
+ start,
1109
+ end: i
1110
+ });
1111
+ } else if (ch === "'") {
1112
+ i++;
1113
+ let value = "";
1114
+ let closed = false;
1115
+ while (i < text.length) {
1116
+ if (text.charAt(i) === "'") {
1117
+ if (text.charAt(i + 1) === "'") {
1118
+ value += "'";
1119
+ i += 2;
1120
+ continue;
1121
+ }
1122
+ i++;
1123
+ closed = true;
1124
+ break;
1125
+ }
1126
+ value += text.charAt(i);
1127
+ i++;
1128
+ }
1129
+ if (!closed) throw new ParseError("Unterminated string literal", start);
1130
+ tokens.push({
1131
+ kind: "string",
1132
+ text: text.slice(start, i),
1133
+ value,
1134
+ start,
1135
+ end: i
1136
+ });
1137
+ } else {
1138
+ const two = text.slice(i, i + 2);
1139
+ if (two === "!=" || two === "<=" || two === ">=") i += 2;
1140
+ else if ("+-*/=<>().,".includes(ch)) i++;
1141
+ else throw new ParseError(`Unexpected character "${ch}"`, start);
1142
+ tokens.push({
1143
+ kind: "op",
1144
+ text: text.slice(start, i),
1145
+ start,
1146
+ end: i
1147
+ });
1148
+ }
1149
+ }
1150
+ tokens.push({
1151
+ kind: "eof",
1152
+ text: "",
1153
+ start: text.length,
1154
+ end: text.length
1155
+ });
1156
+ return tokens;
1157
+ }
1158
+ /**
1159
+ * Рекурсивний спуск. Пріоритет зростає: or < and < not < порівняння < + - <
1160
+ * * / < унарний - < первинні. Власний розбір, а не залежність: граматика
1161
+ * мала, а зміщення у вузлах потрібні діагностикам.
1162
+ */
1163
+ var Parser = class {
1164
+ tokens;
1165
+ pos = 0;
1166
+ constructor(tokens) {
1167
+ this.tokens = tokens;
1168
+ }
1169
+ get current() {
1170
+ return this.tokens[this.pos];
1171
+ }
1172
+ isKeyword(word) {
1173
+ const token = this.current;
1174
+ return token.kind === "ident" && token.text.toLowerCase() === word;
1175
+ }
1176
+ isOp(text) {
1177
+ const token = this.current;
1178
+ return token.kind === "op" && token.text === text;
1179
+ }
1180
+ advance() {
1181
+ const token = this.current;
1182
+ if (token.kind !== "eof") this.pos++;
1183
+ return token;
1184
+ }
1185
+ describe(token) {
1186
+ return token.kind === "eof" ? "end of expression" : `"${token.text}"`;
1187
+ }
1188
+ fail(expected) {
1189
+ const token = this.current;
1190
+ throw new ParseError(`Expected ${expected}, found ${this.describe(token)}`, token.start);
1191
+ }
1192
+ expectOp(text) {
1193
+ if (!this.isOp(text)) this.fail(`"${text}"`);
1194
+ return this.advance();
1195
+ }
1196
+ expectIdent(what) {
1197
+ if (this.current.kind !== "ident") this.fail(what);
1198
+ return this.advance();
1199
+ }
1200
+ parse() {
1201
+ const expr = this.parseOr();
1202
+ if (this.current.kind !== "eof") this.fail("end of expression");
1203
+ return expr;
1204
+ }
1205
+ binary(op, left, right) {
1206
+ return {
1207
+ type: "binary",
1208
+ op,
1209
+ left,
1210
+ right,
1211
+ start: left.start,
1212
+ end: right.end
1213
+ };
1214
+ }
1215
+ parseOr() {
1216
+ let left = this.parseAnd();
1217
+ while (this.isKeyword("or")) {
1218
+ this.advance();
1219
+ left = this.binary("or", left, this.parseAnd());
1220
+ }
1221
+ return left;
1222
+ }
1223
+ parseAnd() {
1224
+ let left = this.parseNot();
1225
+ while (this.isKeyword("and")) {
1226
+ this.advance();
1227
+ left = this.binary("and", left, this.parseNot());
1228
+ }
1229
+ return left;
1230
+ }
1231
+ parseNot() {
1232
+ if (this.isKeyword("not")) {
1233
+ const op = this.advance();
1234
+ const operand = this.parseNot();
1235
+ return {
1236
+ type: "unary",
1237
+ op: "not",
1238
+ operand,
1239
+ start: op.start,
1240
+ end: operand.end
1241
+ };
1242
+ }
1243
+ return this.parseComparison();
1244
+ }
1245
+ parseComparison() {
1246
+ const left = this.parseAdditive();
1247
+ const token = this.current;
1248
+ if (token.kind === "op" && COMPARISON_OPS.has(token.text)) {
1249
+ this.advance();
1250
+ return this.binary(token.text, left, this.parseAdditive());
1251
+ }
1252
+ return left;
1253
+ }
1254
+ parseAdditive() {
1255
+ let left = this.parseMultiplicative();
1256
+ while (this.isOp("+") || this.isOp("-")) {
1257
+ const op = this.advance().text;
1258
+ left = this.binary(op, left, this.parseMultiplicative());
1259
+ }
1260
+ return left;
1261
+ }
1262
+ parseMultiplicative() {
1263
+ let left = this.parseUnary();
1264
+ while (this.isOp("*") || this.isOp("/")) {
1265
+ const op = this.advance().text;
1266
+ left = this.binary(op, left, this.parseUnary());
1267
+ }
1268
+ return left;
1269
+ }
1270
+ parseUnary() {
1271
+ if (this.isOp("-")) {
1272
+ const op = this.advance();
1273
+ const operand = this.parseUnary();
1274
+ return {
1275
+ type: "unary",
1276
+ op: "-",
1277
+ operand,
1278
+ start: op.start,
1279
+ end: operand.end
1280
+ };
1281
+ }
1282
+ return this.parsePrimary();
1283
+ }
1284
+ parsePrimary() {
1285
+ const token = this.current;
1286
+ if (token.kind === "number") {
1287
+ this.advance();
1288
+ return {
1289
+ type: "number",
1290
+ value: token.text,
1291
+ start: token.start,
1292
+ end: token.end
1293
+ };
1294
+ }
1295
+ if (token.kind === "string") {
1296
+ this.advance();
1297
+ return {
1298
+ type: "string",
1299
+ value: token.value ?? "",
1300
+ start: token.start,
1301
+ end: token.end
1302
+ };
1303
+ }
1304
+ if (this.isOp("(")) {
1305
+ const open = this.advance();
1306
+ const inner = this.parseOr();
1307
+ const close = this.expectOp(")");
1308
+ return {
1309
+ ...inner,
1310
+ start: open.start,
1311
+ end: close.end
1312
+ };
1313
+ }
1314
+ if (token.kind === "ident") return this.parseWord(token);
1315
+ return this.fail("an expression");
1316
+ }
1317
+ parseWord(token) {
1318
+ const word = token.text.toLowerCase();
1319
+ if (word === "true" || word === "false") {
1320
+ this.advance();
1321
+ return {
1322
+ type: "boolean",
1323
+ value: word === "true",
1324
+ start: token.start,
1325
+ end: token.end
1326
+ };
1327
+ }
1328
+ if (word === "null") {
1329
+ this.advance();
1330
+ return {
1331
+ type: "null",
1332
+ start: token.start,
1333
+ end: token.end
1334
+ };
1335
+ }
1336
+ if (word === "sum") {
1337
+ this.advance();
1338
+ this.expectOp("(");
1339
+ const section = this.expectIdent("a tabular section name");
1340
+ this.expectOp(".");
1341
+ const field = this.expectIdent("a field name");
1342
+ const close = this.expectOp(")");
1343
+ return {
1344
+ type: "sum",
1345
+ section: section.text,
1346
+ field: field.text,
1347
+ sectionSpan: spanOf(section),
1348
+ fieldSpan: spanOf(field),
1349
+ start: token.start,
1350
+ end: close.end
1351
+ };
1352
+ }
1353
+ if (word === "count") {
1354
+ this.advance();
1355
+ this.expectOp("(");
1356
+ const section = this.expectIdent("a tabular section name");
1357
+ const close = this.expectOp(")");
1358
+ return {
1359
+ type: "count",
1360
+ section: section.text,
1361
+ sectionSpan: spanOf(section),
1362
+ start: token.start,
1363
+ end: close.end
1364
+ };
1365
+ }
1366
+ if (word === "doc" || word === "row") {
1367
+ this.advance();
1368
+ this.expectOp(".");
1369
+ const name = this.expectIdent("a field name");
1370
+ return {
1371
+ type: "field",
1372
+ base: word,
1373
+ name: name.text,
1374
+ fieldSpan: spanOf(name),
1375
+ start: token.start,
1376
+ end: name.end
1377
+ };
1378
+ }
1379
+ throw new ParseError(`Unknown identifier "${token.text}"; expected doc.<field>, row.<field>, sum(...) or count(...)`, token.start);
1380
+ }
1381
+ };
1382
+ function spanOf(token) {
1383
+ return {
1384
+ start: token.start,
1385
+ end: token.end
1386
+ };
1387
+ }
1388
+ /** Розбирає вираз конструктора рухів; помилка несе зміщення в `text`. */
1389
+ function parseExpression(text) {
1390
+ try {
1391
+ return {
1392
+ ok: true,
1393
+ expr: new Parser(tokenize(text)).parse()
1394
+ };
1395
+ } catch (error) {
1396
+ if (error instanceof ParseError) return {
1397
+ ok: false,
1398
+ message: error.message,
1399
+ offset: error.offset
1400
+ };
1401
+ throw error;
1402
+ }
1403
+ }
1404
+ //#endregion
1405
+ //#region src/model/posting/walk.ts
1406
+ /**
1407
+ * Обходить усі вузли виразу в порядку появи (спершу вузол, потім операнди).
1408
+ * Єдиний обхід AST: окремі рекурсії в стадіях компілятора розходилися б
1409
+ * при появі нового виду вузла.
1410
+ */
1411
+ function walkExpr(expr, visit) {
1412
+ visit(expr);
1413
+ switch (expr.type) {
1414
+ case "unary":
1415
+ walkExpr(expr.operand, visit);
1416
+ return;
1417
+ case "binary":
1418
+ walkExpr(expr.left, visit);
1419
+ walkExpr(expr.right, visit);
1420
+ return;
1421
+ default: return;
1422
+ }
1423
+ }
1424
+ //#endregion
1425
+ //#region src/model/schemas/document.ts
1426
+ /**
1427
+ * Один рух документа в регістр (конструктор рухів, спека П2 §7). `fields` —
1428
+ * плаский словник «поле регістра → вираз»: роль поля (вимір, ресурс,
1429
+ * реквізит) відома регістру, документу її дублювати не треба.
1430
+ */
1431
+ const movementDeclSchema = z.strictObject({
1432
+ register: metadataRefSchema.meta({ description: "Register that receives the movement." }),
1433
+ source: z.union([z.literal("document"), z.strictObject({ tabularSection: z.string().min(1).meta({ description: "Name of the tabular section that produces the rows." }) })]).meta({ description: "Where movement rows come from: the document itself or one of its tabular sections." }),
1434
+ condition: z.string().min(1).optional().meta({ description: "Expression; the movement is written only when it is true." }),
1435
+ movementType: z.string().min(1).optional().meta({ description: "Receipt or Expense literal for a balance register, otherwise an expression." }),
1436
+ period: z.string().min(1).optional().meta({ description: "Expression for the movement period." }),
1437
+ fields: z.record(z.string().min(1), z.string().min(1)).meta({ description: "Register field name to expression; the register defines each field role." })
1438
+ }).meta({ description: "One movement of the document into a register." }).superRefine((movement, ctx) => {
1439
+ const check = (text, path) => {
1440
+ if (text === void 0) return;
1441
+ const result = parseExpression(text);
1442
+ if (result.ok) return;
1443
+ ctx.addIssue({
1444
+ code: "custom",
1445
+ message: result.message,
1446
+ path,
1447
+ params: {
1448
+ rule: "posting.parse",
1449
+ offset: result.offset
1450
+ }
1451
+ });
1452
+ };
1453
+ check(movement.condition, ["condition"]);
1454
+ if (movement.movementType !== "Receipt" && movement.movementType !== "Expense") check(movement.movementType, ["movementType"]);
1455
+ check(movement.period, ["period"]);
1456
+ for (const [name, text] of Object.entries(movement.fields)) check(text, ["fields", name]);
1457
+ });
1458
+ /** Документ. */
1459
+ const documentSchema = z.strictObject({
1460
+ ...objectHeaderShape,
1461
+ kind: z.literal("Document").meta({ description: "Metadata kind; always Document." }),
1462
+ kindLabel: physicalNameSchema.optional().meta({ description: "Physical kind label of the object. Assigned once at creation and never changed, so a rename keeps it." }),
1463
+ numberLength: z.number().int().positive().default(11).meta({ description: "Length of the document number." }),
1464
+ numberType: z.enum(["String", "Number"]).default("String").meta({ description: "Value type of the document number." }),
1465
+ autonumber: z.boolean().default(true).meta({ description: "Whether the number is generated automatically." }),
1466
+ numberPeriodicity: z.enum([
1467
+ "None",
1468
+ "Year",
1469
+ "Quarter",
1470
+ "Month",
1471
+ "Day"
1472
+ ]).default("Year").meta({ description: "Period after which automatic numbering restarts." }),
1473
+ posting: z.strictObject({ movements: z.array(movementDeclSchema).default([]).meta({ description: "Declared movements written when the document is posted." }) }).optional().meta({ description: "Posting declaration of the document." }),
1474
+ registerMovements: z.array(metadataRefSchema).default([]).meta({ description: "Registers the document writes movements into." }),
1475
+ trackAuthor: z.boolean().default(false).meta({ description: "Adds the standard createdBy and updatedBy attributes referencing the users catalog; requires a catalog with role users." }),
1476
+ publicRead: publicReadSchema,
1477
+ customActions: customActionsSchema,
1478
+ access: accessSchema.optional(),
1479
+ ownership: ownershipSchema.optional().meta({ description: "Owners of a row: users or members the own extent of a grant opens the row to." }),
1480
+ containerBinding: rightsCarrierSchema.optional().meta({ description: "Attribute (or a two-step path of attributes) that binds a row to its rights container: the catalog flagged rightsContainer." }),
1481
+ standardAttributeOverrides: standardAttributeOverridesSchema,
1482
+ attributes: z.array(attributeSchema).default([]).meta({ description: "Custom attributes of the document." }),
1483
+ tabularSections: z.array(tabularSectionSchema).default([]).meta({ description: "Tabular sections of the document." }),
1484
+ indexes: compositeIndexesSchema.meta({ description: "Composite indexes over the document attributes." })
1485
+ });
1486
+ //#endregion
1487
+ //#region src/model/schemas/scope.ts
1488
+ /** Значення `setFunction` виду скоупу: функцію множини генерує компілятор з членства. */
1489
+ const MEMBERSHIP_SET_FUNCTION = "membership";
1490
+ /** Значення `scope` об'єкта, що явно виводить його зі скоупу. */
1491
+ const NO_SCOPE = "none";
1492
+ /**
1493
+ * Вид скоупу проєкту (спека П2 §6). Корінь — об'єкт метаданих або зовнішня
1494
+ * таблиця; колонка зовнішнього кореня — фізична, бо логічного імені в чужої
1495
+ * таблиці немає.
1496
+ */
1497
+ const scopeKindSchema = z.strictObject({
1498
+ id: metadataIdSchema.optional(),
1499
+ name: elementNameSchema,
1500
+ physicalName: physicalNameSchema.optional(),
1501
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the scope kind." }),
1502
+ root: z.union([z.strictObject({ object: metadataRefSchema.meta({ description: "Metadata object that is the scope root." }) }), z.strictObject({ external: z.strictObject({
1503
+ schema: appSchemaNameSchema.min(1).meta({ description: "PostgreSQL schema of the external root table." }),
1504
+ table: z.string().min(1).meta({ description: "Physical name of the external root table." }),
1505
+ column: z.string().min(1).meta({ description: "Physical key column of the external root table." })
1506
+ }).meta({ description: "Root table outside the metadata." }) })]).meta({ description: "Root of the scope: a metadata object or an external table." }),
1507
+ setFunction: z.union([z.strictObject({
1508
+ schema: appSchemaNameSchema.min(1).optional().meta({ description: "PostgreSQL schema of the function; defaultSchema when absent." }),
1509
+ name: z.string().min(1).meta({ description: "Physical name of the function." })
1510
+ }).meta({ description: "SQL function defined in a .sql file." }), z.literal(MEMBERSHIP_SET_FUNCTION).meta({ description: "Generated from the membership catalog of this scope kind: the scope values where the current user is a member." })]).meta({ description: "SQL function that returns the set of scope values visible to the current user." }),
1511
+ onRootDelete: z.enum(["restrict", "cascade"]).default("restrict").meta({ description: "What happens to scoped rows when the scope root is deleted." })
1512
+ }).meta({ description: "Scope kind of the application (tenant dimension)." });
1513
+ //#endregion
1514
+ //#region src/model/schemas/enumeration.ts
1515
+ const enumValueSchema = z.strictObject({
1516
+ id: metadataIdSchema.optional(),
1517
+ name: objectNameSchema.meta({ description: "Logical name of the enumeration value." }),
1518
+ /** Фізична мітка значення в БД. */
1519
+ physicalName: physicalNameSchema.optional(),
1520
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the value." })
1521
+ }).meta({ description: "One value of an enumeration." });
1522
+ /** Перелік. Порядок значень — порядок масиву, окремого поля порядку немає. */
1523
+ const enumerationSchema = z.strictObject({
1524
+ ...objectHeaderShape,
1525
+ kind: z.literal("Enumeration").meta({ description: "Metadata kind; always Enumeration." }),
1526
+ values: z.array(enumValueSchema).default([]).meta({ description: "Enumeration values; array order is the value order." })
1527
+ }).superRefine((value, ctx) => {
1528
+ if (value.scope !== void 0 && value.scope !== "none") ctx.addIssue({
1529
+ code: "custom",
1530
+ message: `Enumeration scope can only be "${NO_SCOPE}"`,
1531
+ path: ["scope"],
1532
+ params: { rule: "scope.not-allowed" }
1533
+ });
1534
+ });
1535
+ //#endregion
1536
+ //#region src/model/schemas/information-register.ts
1537
+ /** Регістр відомостей. */
1538
+ const informationRegisterSchema = z.strictObject({
1539
+ ...objectHeaderShape,
1540
+ kind: z.literal("InformationRegister").meta({ description: "Metadata kind; always InformationRegister." }),
1541
+ kindLabel: physicalNameSchema.optional().meta({ description: "Physical kind label of the object. Assigned once at creation and never changed, so a rename keeps it." }),
1542
+ periodicity: z.enum([
1543
+ "NonPeriodic",
1544
+ "Day",
1545
+ "Month",
1546
+ "Quarter",
1547
+ "Year"
1548
+ ]).default("NonPeriodic").meta({ description: "Period granularity of the register records." }),
1549
+ writeMode: z.enum(["Independent", "RecorderSubordinate"]).default("Independent").meta({ description: "Whether records are written independently or by a recorder document." }),
1550
+ recorderTypes: z.array(metadataRefSchema).default([]).meta({ description: "Document kinds allowed to write records of this register." }),
1551
+ publicRead: publicReadSchema,
1552
+ customActions: customActionsSchema,
1553
+ access: accessSchema.optional(),
1554
+ standardAttributeOverrides: standardAttributeOverridesSchema,
1555
+ dimensions: z.array(registerFieldSchema).default([]).meta({ description: "Dimensions: the key fields of a record." }),
1556
+ resources: z.array(registerFieldSchema).default([]).meta({ description: "Resources: the value fields of a record." }),
1557
+ attributes: z.array(attributeSchema).default([]).meta({ description: "Attributes: extra information of a record." })
1558
+ });
1559
+ //#endregion
1560
+ //#region src/model/schemas/accumulation-register.ts
1561
+ /**
1562
+ * Ресурс регістра накопичення. Ресурси сумуються в залишки й обороти, тож
1563
+ * форма вужча за реквізит: лише число з precision/scale — без length,
1564
+ * посилань, crossScope чи ознак індексу; строга схема відкидає їх як
1565
+ * невідомі ключі. Прапорця `required` немає: ресурс завжди NOT NULL, бо
1566
+ * значення дає кожен рух.
1567
+ */
1568
+ const resourceSchema = z.strictObject({
1569
+ id: metadataIdSchema.optional(),
1570
+ name: elementNameSchema,
1571
+ physicalName: physicalNameSchema.optional(),
1572
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the resource." }),
1573
+ description: localizedStringSchema.optional().meta({ description: "Description of the resource." }),
1574
+ type: z.enum(["Integer", "Numeric"]).meta({ description: "Logical value type; Integer or Numeric only." }),
1575
+ precision: valueTypeShape.precision,
1576
+ scale: valueTypeShape.scale
1577
+ }).superRefine(refineValueType).meta({ description: "Resource of an accumulation register: a summed number." });
1578
+ /** Регістр накопичення. */
1579
+ const accumulationRegisterSchema = z.strictObject({
1580
+ ...objectHeaderShape,
1581
+ kind: z.literal("AccumulationRegister").meta({ description: "Metadata kind; always AccumulationRegister." }),
1582
+ kindLabel: physicalNameSchema.optional().meta({ description: "Physical kind label of the object. Assigned once at creation and never changed, so a rename keeps it." }),
1583
+ registerType: z.enum(["Balance", "Turnover"]).default("Balance").meta({ description: "Balance keeps running totals; Turnover only accumulates." }),
1584
+ recorderTypes: z.array(metadataRefSchema).default([]).meta({ description: "Document kinds allowed to write records of this register." }),
1585
+ /**
1586
+ * Контроль залишків в оболонці проведення (спека П2 §7): ресурси — логічні
1587
+ * імена ресурсів цього регістра, їхнє існування перевіряє стадія 2.
1588
+ */
1589
+ balanceControl: z.strictObject({ resources: z.array(z.string()).meta({ description: "Logical names of resources whose balance is controlled." }) }).optional().meta({ description: "Negative-balance control at posting; allowed only on a Balance register." }),
1590
+ publicRead: publicReadSchema,
1591
+ customActions: customActionsSchema,
1592
+ access: accessSchema.optional(),
1593
+ standardAttributeOverrides: standardAttributeOverridesSchema,
1594
+ dimensions: z.array(registerFieldSchema).default([]).meta({ description: "Dimensions: the key fields of a record." }),
1595
+ resources: z.array(resourceSchema).default([]).meta({ description: "Resources: the summed value fields of a record; Integer or Numeric only." }),
1596
+ attributes: z.array(attributeSchema).default([]).meta({ description: "Attributes: extra information of a record." })
1597
+ }).superRefine((register, ctx) => {
1598
+ if (register.balanceControl !== void 0 && register.registerType !== "Balance") ctx.addIssue({
1599
+ code: "custom",
1600
+ message: "balanceControl is allowed only on a Balance register",
1601
+ path: ["balanceControl"],
1602
+ params: { rule: "register.balance-control-type" }
1603
+ });
1604
+ });
1605
+ //#endregion
1606
+ //#region src/model/schemas/constant.ts
1607
+ /** Константа — окремий об'єкт зі значенням довільного логічного типу. */
1608
+ const constantSchema = z.strictObject({
1609
+ ...objectHeaderShape,
1610
+ kind: z.literal("Constant").meta({ description: "Metadata kind; always Constant." }),
1611
+ kindLabel: physicalNameSchema.optional().meta({ description: "Physical kind label of the object. Assigned once at creation and never changed, so a rename keeps it." }),
1612
+ publicRead: publicReadSchema,
1613
+ customActions: customActionsSchema,
1614
+ ...valueTypeShape,
1615
+ defaultValue: defaultValueSchema.optional().meta({ description: "Initial value of the constant." })
1616
+ }).superRefine(refineValueType);
1617
+ //#endregion
1618
+ //#region src/model/schemas/custom-table.ts
1619
+ const IDENTITY_TYPES = [
1620
+ "SmallInt",
1621
+ "Integer",
1622
+ "BigInt"
1623
+ ];
1624
+ /**
1625
+ * Ім'я об'єкта каталогу Postgres (колляції, класу операторів) частинами, а
1626
+ * не рядком `schema.name`: крапка буває в самому імені (`en_US.utf8`), тож
1627
+ * рядок не відрізнив би його від колляції `utf8` схеми `en_US`. Метадані
1628
+ * лапок SQL не несуть — рендер бере кожну частину в лапки сам, а прийом
1629
+ * заповнює їх з каталогу. Схема `pg_catalog` не пишеться: один об'єкт — одна
1630
+ * форма знімка.
1631
+ */
1632
+ const pgQualifiedNameSchema = z.strictObject({
1633
+ schema: z.string().min(1).refine((schema) => schema !== "pg_catalog", { message: "Omit schema for objects in pg_catalog" }).optional().meta({ description: "Schema of the object, unquoted; omitted for objects in pg_catalog." }),
1634
+ name: z.string().min(1).meta({ description: "Name of the object, unquoted, as Postgres reports it." })
1635
+ }).meta({ description: "Postgres catalog object name split into parts." });
1636
+ /**
1637
+ * Колонка описується рівно однією з трьох форм типу: логічний тип, посилання
1638
+ * на `PgEnum` або сирий PG-тип (`Raw` — єдине місце, де допустимий сирий тип).
1639
+ * Форму розрізняє `type`; поля всіх форм оголошені разом, щоб невалідна
1640
+ * комбінація давала правило `customTable.column-type` зі шляхом до
1641
+ * конкретного поля, а не загальну помилку об'єднання.
1642
+ */
1643
+ const customTableColumnSchema = z.strictObject({
1644
+ id: objectHeaderShape.id,
1645
+ name: elementNameSchema,
1646
+ physicalName: physicalNameSchema.optional(),
1647
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the column." }),
1648
+ notNull: z.boolean().default(false).meta({ description: "Whether the column is NOT NULL." }),
1649
+ /** SQL-вираз значення за замовчуванням. */
1650
+ default: z.string().optional().meta({ description: "SQL expression used as the column default." }),
1651
+ identity: z.enum(["always", "byDefault"]).optional().meta({ description: "Identity generation mode; requires SmallInt, Integer or BigInt type." }),
1652
+ /**
1653
+ * `GENERATED ALWAYS AS (…) STORED`; вираз — у нормалізованій формі
1654
+ * Postgres (`pg_get_expr`). З `default` та `identity` несумісне — це
1655
+ * перевіряє стадія 4 (`customTable.generated-conflict`).
1656
+ */
1657
+ generated: z.strictObject({ expression: z.string().min(1).meta({ description: "SQL expression of the stored generated column." }) }).optional().meta({ description: "Stored generated column; incompatible with default and identity." }),
1658
+ collation: pgQualifiedNameSchema.optional().meta({ description: "Collation of the column (pg_collation); absent means the type default." }),
1659
+ comment: z.string().optional().meta({ description: "Comment on the column." }),
1660
+ type: z.enum([
1661
+ ...LOGICAL_TYPES,
1662
+ "PgEnum",
1663
+ "Raw"
1664
+ ]).meta({ description: "Logical type, PgEnum for an accepted enum, or Raw for a raw PostgreSQL type." }),
1665
+ ...z.object(valueTypeShape).omit({
1666
+ type: true,
1667
+ crossScope: true
1668
+ }).shape,
1669
+ enum: z.strictObject({
1670
+ kind: z.literal("PgEnum").meta({ description: "Always PgEnum." }),
1671
+ name: objectNameSchema.meta({ description: "Logical name of the PgEnum object." })
1672
+ }).optional().meta({ description: "Enum type of a PgEnum column." }),
1673
+ pgType: z.string().min(1).optional().meta({ description: "Raw PostgreSQL type of a Raw column." })
1674
+ }).superRefine((column, ctx) => {
1675
+ const issue = (rule, message, path) => ctx.addIssue({
1676
+ code: "custom",
1677
+ message,
1678
+ path,
1679
+ params: { rule }
1680
+ });
1681
+ const logicalFields = [
1682
+ "length",
1683
+ "precision",
1684
+ "scale",
1685
+ "ref",
1686
+ "allowedTypes"
1687
+ ];
1688
+ if (column.type === "PgEnum") {
1689
+ if (column.enum === void 0) issue("customTable.column-type", "PgEnum column requires enum", ["enum"]);
1690
+ if (column.pgType !== void 0) issue("customTable.column-type", "PgEnum column cannot have pgType", ["pgType"]);
1691
+ for (const field of logicalFields) if (column[field] !== void 0) issue("customTable.column-type", `PgEnum column cannot have ${field}`, [field]);
1692
+ } else if (column.type === "Raw") {
1693
+ if (column.pgType === void 0) issue("customTable.column-type", "Raw column requires pgType", ["pgType"]);
1694
+ if (column.enum !== void 0) issue("customTable.column-type", "Raw column cannot have enum", ["enum"]);
1695
+ for (const field of [...logicalFields, "array"]) if (column[field] !== void 0) issue("customTable.column-type", `Raw column cannot have ${field}`, [field]);
1696
+ } else {
1697
+ if (column.enum !== void 0) issue("customTable.column-type", "enum is only allowed for PgEnum columns", ["enum"]);
1698
+ if (column.pgType !== void 0) issue("customTable.column-type", "pgType is only allowed for Raw columns", ["pgType"]);
1699
+ refineValueType({
1700
+ ...column,
1701
+ type: column.type
1702
+ }, ctx);
1703
+ }
1704
+ if (column.identity !== void 0 && !IDENTITY_TYPES.includes(column.type)) issue("customTable.identity-type", "identity requires SmallInt, Integer or BigInt type", ["identity"]);
1705
+ });
1706
+ const constraintName = z.string().min(1).optional().meta({ description: "Constraint name; when absent the PostgreSQL default name is used." });
1707
+ const columnList = z.array(elementNameSchema).min(1).meta({ description: "Logical names of columns of this table." });
1708
+ /** `DEFERRABLE` / `INITIALLY DEFERRED` обмеження — спільне для FK, PK і UNIQUE. */
1709
+ const deferrableSchema = z.enum([
1710
+ "no",
1711
+ "deferrable",
1712
+ "initiallyDeferred"
1713
+ ]).default("no").meta({ description: "Whether the constraint check can be deferred." });
1714
+ const fkActionSchema = z.enum([
1715
+ "noAction",
1716
+ "restrict",
1717
+ "cascade",
1718
+ "setNull",
1719
+ "setDefault"
1720
+ ]).meta({ description: "Referential action of a foreign key." });
1721
+ /** `forced` — RLS діє і для власника таблиці (`FORCE ROW LEVEL SECURITY`). */
1722
+ const rowLevelSecuritySchema = z.enum([
1723
+ "off",
1724
+ "enabled",
1725
+ "forced"
1726
+ ]).meta({ description: "Row-level security of the table: off, enabled, or forced (applies to the table owner too)." });
1727
+ const foreignKeySchema = z.strictObject({
1728
+ name: constraintName,
1729
+ columns: columnList,
1730
+ references: z.union([z.strictObject({
1731
+ object: metadataRefSchema.meta({ description: "Referenced metadata object." }),
1732
+ columns: columnList.meta({ description: "Logical names of columns of the referenced object." })
1733
+ }), z.strictObject({ external: z.strictObject({
1734
+ schema: appSchemaNameSchema.min(1).meta({ description: "PostgreSQL schema of the external table." }),
1735
+ table: z.string().min(1).meta({ description: "Physical name of the external table." }),
1736
+ columns: z.array(z.string().min(1)).min(1).meta({ description: "Physical column names of the external table." })
1737
+ }).meta({ description: "Referenced table outside the metadata." }) })]).meta({ description: "Referenced target: a metadata object or an external table." }),
1738
+ onDelete: fkActionSchema.default("noAction").meta({ description: "Action on delete of the referenced row." }),
1739
+ onUpdate: fkActionSchema.default("noAction").meta({ description: "Action on update of the referenced key." }),
1740
+ deferrable: deferrableSchema
1741
+ }).meta({ description: "Foreign key of the table." });
1742
+ /**
1743
+ * Параметри елемента ключа індексу — однакові для колонки й виразу. Відсутнє
1744
+ * поле — значення Postgres за замовчуванням (`ASC`, розташування `NULL` за
1745
+ * порядком, клас операторів і колляція типу); прийом пише лише те, що є в
1746
+ * `pg_index`.
1747
+ */
1748
+ const indexKeyOptions = {
1749
+ order: z.enum(["asc", "desc"]).optional().meta({ description: "Sort order of the key; absent means ascending." }),
1750
+ nulls: z.enum(["first", "last"]).optional().meta({ description: "NULLS FIRST or NULLS LAST; absent means the order default." }),
1751
+ opclass: pgQualifiedNameSchema.optional().meta({ description: "Operator class of the key (pg_opclass); absent means the type default." }),
1752
+ collation: pgQualifiedNameSchema.optional().meta({ description: "Collation of the key (pg_collation); absent means the column default." })
1753
+ };
1754
+ const indexSchema = z.strictObject({
1755
+ name: constraintName,
1756
+ unique: z.boolean().default(false).meta({ description: "Whether the index is unique." }),
1757
+ method: z.string().min(1).default("btree").meta({ description: "Index access method." }),
1758
+ keys: z.array(z.union([z.strictObject({
1759
+ column: elementNameSchema.meta({ description: "Logical name of the indexed column." }),
1760
+ ...indexKeyOptions
1761
+ }), z.strictObject({
1762
+ expression: z.string().min(1).meta({ description: "SQL expression of the index key." }),
1763
+ ...indexKeyOptions
1764
+ })])).min(1).meta({ description: "Index keys: columns or expressions." }),
1765
+ include: z.array(elementNameSchema).default([]).meta({ description: "Logical names of non-key columns stored in the index." }),
1766
+ where: z.string().optional().meta({ description: "SQL predicate of a partial index." }),
1767
+ nullsNotDistinct: z.boolean().default(false).meta({ description: "Whether NULLs are treated as equal in a unique index." })
1768
+ }).meta({ description: "Index of the table." });
1769
+ /**
1770
+ * Довільна таблиця з повним фізичним описом. Колонки в обмеженнях і індексах
1771
+ * — логічні імена; ім'я обмеження необов'язкове (відсутнє — ім'я за
1772
+ * алгоритмом Postgres), зворотний генератор записує імена явно.
1773
+ */
1774
+ const customTableSchema = z.strictObject({
1775
+ ...objectHeaderShape,
1776
+ kind: z.literal("CustomTable").meta({ description: "Metadata kind; always CustomTable." }),
1777
+ kindLabel: physicalNameSchema.optional().meta({ description: "Physical kind label of the object. Assigned once at creation and never changed, so a rename keeps it." }),
1778
+ comment: z.string().optional().meta({ description: "Comment on the table." }),
1779
+ columns: z.array(customTableColumnSchema).min(1).meta({ description: "Columns of the table." }),
1780
+ primaryKey: z.strictObject({
1781
+ name: constraintName,
1782
+ columns: columnList,
1783
+ deferrable: deferrableSchema
1784
+ }).optional().meta({ description: "Primary key of the table." }),
1785
+ uniques: z.array(z.strictObject({
1786
+ name: constraintName,
1787
+ columns: columnList,
1788
+ nullsNotDistinct: z.boolean().default(false).meta({ description: "Whether NULLs are treated as equal." }),
1789
+ deferrable: deferrableSchema
1790
+ }).meta({ description: "Unique constraint." })).default([]).meta({ description: "Unique constraints of the table." }),
1791
+ checks: z.array(z.strictObject({
1792
+ name: constraintName,
1793
+ expression: z.string().min(1).meta({ description: "SQL boolean expression of the check." })
1794
+ }).meta({ description: "Check constraint." })).default([]).meta({ description: "Check constraints of the table." }),
1795
+ foreignKeys: z.array(foreignKeySchema).default([]).meta({ description: "Foreign keys of the table." }),
1796
+ indexes: z.array(indexSchema).default([]).meta({ description: "Indexes of the table." }),
1797
+ /** Логічне ім'я власної колонки таблиці, що несе скоуп. */
1798
+ scopeColumn: elementNameSchema.optional().meta({ description: "Logical name of the own column that carries the scope." }),
1799
+ /**
1800
+ * RLS таблиці — властивість метаданих, а не `ALTER TABLE` у `.sql`: стан
1801
+ * таблиці описує одне місце. Прийнята таблиця за замовчуванням без RLS.
1802
+ */
1803
+ rowLevelSecurity: rowLevelSecuritySchema.default("off").meta({ description: "Row-level security of the table: off, enabled, or forced (applies to the table owner too)." })
1804
+ });
1805
+ //#endregion
1806
+ //#region src/model/schemas/pg-enum.ts
1807
+ /**
1808
+ * Прийнятий PG-енам. Значення — фізичні мітки типу без власної ідентичності,
1809
+ * тому порядок значущий (порядок у PG-енамі), а дублікати заборонені.
1810
+ */
1811
+ const pgEnumSchema = z.strictObject({
1812
+ ...z.object(objectHeaderShape).omit({ scope: true }).shape,
1813
+ kind: z.literal("PgEnum").meta({ description: "Metadata kind; always PgEnum." }),
1814
+ values: z.array(z.string().min(1)).min(1).meta({ description: "Physical enum labels in database order; duplicates are not allowed." })
1815
+ }).superRefine((value, ctx) => {
1816
+ const seen = /* @__PURE__ */ new Set();
1817
+ value.values.forEach((label, index) => {
1818
+ if (seen.has(label)) ctx.addIssue({
1819
+ code: "custom",
1820
+ message: `Duplicate enum value "${label}"`,
1821
+ path: ["values", index],
1822
+ params: { rule: "pgEnum.value-duplicate" }
1823
+ });
1824
+ seen.add(label);
1825
+ });
1826
+ });
1827
+ //#endregion
1828
+ //#region src/model/schemas/event-subscription.ts
1829
+ /**
1830
+ * Події підписки (спека промоції §9.3): до чи після запису й видалення рядка
1831
+ * джерела. Тригер за подією генерує компілятор
1832
+ * (`compiler/subscription-units.ts`); тут — лише множина значень.
1833
+ */
1834
+ const SUBSCRIPTION_EVENTS = [
1835
+ "beforeWrite",
1836
+ "onWrite",
1837
+ "beforeDelete",
1838
+ "onDelete"
1839
+ ];
1840
+ /** Події видалення: змінених колонок у них немає, тож `whenChanged` — помилка. */
1841
+ const DELETE_EVENTS = /* @__PURE__ */ new Set(["beforeDelete", "onDelete"]);
1842
+ /**
1843
+ * Таблиця провайдера як джерело — `<схема>.<таблиця>` з пресету провайдера
1844
+ * (`PROVIDER_EVENT_SOURCES`). Наявність у пресеті перевіряє компілятор: лише
1845
+ * він бачить провайдера проєкту.
1846
+ */
1847
+ const providerTableSourceSchema = z.strictObject({ providerTable: z.string().regex(/^[^.\s]+\.[^.\s]+$/).meta({ description: "Provider table as <schema>.<table>; it must be in the provider event source preset." }) }).meta({ description: "A table of the database provider as the source." });
1848
+ /**
1849
+ * Підписка на подію — вид без сховища (як перерахування): файл на підписку,
1850
+ * `physicalName` — база імені згенерованого тригера, призначена раз. PG-схеми й скоупу в
1851
+ * неї немає: тригер живе на таблиці джерела, обробник називає схему сам.
1852
+ */
1853
+ const eventSubscriptionSchema = z.strictObject({
1854
+ ...z.object(objectHeaderShape).omit({
1855
+ schema: true,
1856
+ scope: true
1857
+ }).shape,
1858
+ kind: z.literal("EventSubscription").meta({ description: "Metadata kind; always EventSubscription." }),
1859
+ sources: z.array(z.union([metadataRefSchema, providerTableSourceSchema])).min(1).meta({ description: "Tables whose rows raise the event: application objects with a table or provider tables from the preset." }),
1860
+ event: z.enum(SUBSCRIPTION_EVENTS).meta({ description: "Row event the handler reacts to, before or after it." }),
1861
+ whenChanged: z.array(z.string().min(1)).min(1).optional().meta({ description: "Write events only: fire only when one of these attributes changes; logical names in every object source, preset columns for a provider table." }),
1862
+ handler: z.strictObject({
1863
+ schema: appSchemaNameSchema.optional().meta({ description: "PostgreSQL schema of the handler; the project defaultSchema applies when absent." }),
1864
+ name: z.string().min(1).meta({ description: "Name of a function without arguments that returns trigger, declared in the .sql files." })
1865
+ }).meta({ description: "Trigger function called for the event." })
1866
+ });
1867
+ //#endregion
1868
+ //#region src/model/schemas/sql-debt.ts
1869
+ /** Ім'я файлу переліку боргу в корені `metadata/`. */
1870
+ const SQL_DEBT_FILE = "sql-debt.json";
1871
+ /**
1872
+ * Перелік боргу дослівного SQL (план промоції 2b, рішення 12): ідентичності
1873
+ * одиниць поза закритою оболонкою, які тека вже мала, коли її розклав
1874
+ * `introspect`. Ратчет лише звужується: нова одиниця боргу, якої тут немає, —
1875
+ * помилка компіляції, а `fix` лише прибирає записи. Відсортований і без
1876
+ * дублів — тоді diff переліку показує саме зміну боргу, а не порядок запису.
1877
+ */
1878
+ const sqlDebtSchema = z.strictObject({
1879
+ $schema: z.string().optional().meta({ description: "Editor hint: path to the JSON Schema of this file." }),
1880
+ units: z.array(z.string()).meta({ description: "Identities of verbatim SQL units accepted as debt (outside the closed function shell), sorted and without duplicates. Written by introspect; fix only removes entries." })
1881
+ }).meta({ description: "Debt ratchet of verbatim SQL: a debt unit missing from this list is an error." }).superRefine((debt, ctx) => {
1882
+ debt.units.forEach((unit, index) => {
1883
+ const previous = debt.units[index - 1];
1884
+ if (index > 0 && !(previous < unit)) ctx.addIssue({
1885
+ code: "custom",
1886
+ message: previous === unit ? `Debt entry "${unit}" is listed twice` : `Debt entry "${unit}" is out of order`,
1887
+ path: ["units", index],
1888
+ params: { rule: "debt.not-canonical" }
1889
+ });
1890
+ });
1891
+ });
1892
+ //#endregion
1893
+ //#region src/model/schemas/project.ts
1894
+ /**
1895
+ * Пресети провайдера бази (платформна спека §6.9). Проєкт вибирає пресет
1896
+ * ключем, а його вміст — факти образу провайдера — лишається кодом платформи.
1897
+ */
1898
+ const DATABASE_PROVIDERS = ["supabase"];
1899
+ /**
1900
+ * Таблиці провайдера, які застосунок може слухати підпискою (спека промоції
1901
+ * §9.3): запис у них команд платформи не проходить (реєстрація користувача,
1902
+ * завантаження файлу). Колонки — факт образу провайдера; розходження з
1903
+ * локальним стеком ловить DB-тест, а лежання на поверхні тригерів пресету
1904
+ * схеми — тест T2 (T0 його не імпортує).
1905
+ */
1906
+ const PROVIDER_EVENT_SOURCES = { supabase: [{
1907
+ schema: "auth",
1908
+ table: "users",
1909
+ columns: [
1910
+ "instance_id",
1911
+ "id",
1912
+ "aud",
1913
+ "role",
1914
+ "email",
1915
+ "encrypted_password",
1916
+ "email_confirmed_at",
1917
+ "invited_at",
1918
+ "confirmation_token",
1919
+ "confirmation_sent_at",
1920
+ "recovery_token",
1921
+ "recovery_sent_at",
1922
+ "email_change_token_new",
1923
+ "email_change",
1924
+ "email_change_sent_at",
1925
+ "last_sign_in_at",
1926
+ "raw_app_meta_data",
1927
+ "raw_user_meta_data",
1928
+ "is_super_admin",
1929
+ "created_at",
1930
+ "updated_at",
1931
+ "phone",
1932
+ "phone_confirmed_at",
1933
+ "phone_change",
1934
+ "phone_change_token",
1935
+ "phone_change_sent_at",
1936
+ "confirmed_at",
1937
+ "email_change_token_current",
1938
+ "email_change_confirm_status",
1939
+ "banned_until",
1940
+ "reauthentication_token",
1941
+ "reauthentication_sent_at",
1942
+ "is_sso_user",
1943
+ "deleted_at",
1944
+ "is_anonymous"
1945
+ ]
1946
+ }, {
1947
+ schema: "storage",
1948
+ table: "objects",
1949
+ columns: [
1950
+ "id",
1951
+ "bucket_id",
1952
+ "name",
1953
+ "owner",
1954
+ "created_at",
1955
+ "updated_at",
1956
+ "last_accessed_at",
1957
+ "metadata",
1958
+ "path_tokens",
1959
+ "version",
1960
+ "owner_id",
1961
+ "user_metadata",
1962
+ "archived_at",
1963
+ "is_delete_marker",
1964
+ "is_versioned"
1965
+ ]
1966
+ }] };
1967
+ const PROVIDER_API_ROLES = { supabase: {
1968
+ user: "authenticated",
1969
+ anonymous: "anon",
1970
+ service: "service_role"
1971
+ } };
1972
+ /**
1973
+ * Факти провайдера ідентичності за пресетом бази. Колонки — факт образу
1974
+ * провайдера: їх наявність на стеку перевіряє DB-тест, а лежання таблиці на
1975
+ * поверхні тригерів пресету — тест T2 (T0 його не імпортує).
1976
+ *
1977
+ * Чого `IdentitySource` не виражає — межа, яку другий провайдер перевіряє
1978
+ * першою, бо платформний шар вважає це спільним для всіх:
1979
+ * - контракт сесії: `current_setting('request.jwt.claims')` і claim `sub`
1980
+ * у ньому (функція поточного користувача);
1981
+ * - правило С8: ключ облікового запису — uuid, він же `id` користувача, а
1982
+ * `subject` — цей ключ як `::text`;
1983
+ * - імена ролей API — окремий факт T0, `PROVIDER_API_ROLES` вище;
1984
+ * - фіксовані імена функцій і тригерів шару (`simetra.current_user_id`,
1985
+ * `simetra.provision_user`, `simetra_provision_user` тощо) — у генераторі
1986
+ * T1, не в даних провайдера.
1987
+ */
1988
+ const PROVIDER_IDENTITY_SOURCES = { supabase: {
1989
+ table: {
1990
+ schema: "auth",
1991
+ name: "users"
1992
+ },
1993
+ keyColumn: "id",
1994
+ nameSources: [
1995
+ {
1996
+ json: "raw_user_meta_data",
1997
+ key: "full_name"
1998
+ },
1999
+ {
2000
+ json: "raw_user_meta_data",
2001
+ key: "name"
2002
+ },
2003
+ { column: "email" }
2004
+ ],
2005
+ anonymousColumn: "is_anonymous",
2006
+ deletedAtColumn: "deleted_at",
2007
+ providerKey: "supabase"
2008
+ } };
2009
+ /** Файл проєкту: ідентичність, правила іменування й часовий пояс застосунку. */
2010
+ const projectSchema = z.strictObject({
2011
+ $schema: z.string().optional().meta({ description: "Editor hint: path to the JSON Schema of this file." }),
2012
+ name: z.string().meta({ description: "Application name." }),
2013
+ title: localizedStringSchema.optional().meta({ description: "Human-readable title of the application." }),
2014
+ defaultLocale: z.enum(["uk", "en"]).default("uk").meta({ description: "Locale used when none is requested." }),
2015
+ defaultSchema: appSchemaNameSchema.default("public").meta({ description: "PostgreSQL schema for objects that declare none." }),
2016
+ database: z.strictObject({ provider: z.enum(DATABASE_PROVIDERS).meta({ description: "Database provider preset that defines the management boundary." }) }).meta({ description: "Database of the application." }),
2017
+ naming: z.strictObject({ attributeCase: z.enum(ATTRIBUTE_CASES).default("camelCase").meta({ description: "Casing style of logical attribute names." }) }).default({ attributeCase: "camelCase" }).meta({ description: "Naming rules of the application." }),
2018
+ /**
2019
+ * IANA-пояс, у якому платформа визначає день, місяць, квартал і рік
2020
+ * моменту (спека П2 §3). Існування імені перевіряє компілятор
2021
+ * (`project.timezone-unknown`) за переліком поясів рушія.
2022
+ */
2023
+ timezone: z.string().min(1).default("UTC").meta({ description: "IANA time zone in which the platform determines day, month, quarter and year." }),
2024
+ scopeKinds: z.array(scopeKindSchema).default([]).meta({ description: "Scope kinds of the application; leave empty for a single-tenant application." }),
2025
+ accessDimensions: z.array(accessDimensionSchema).default([]).meta({ description: "Access dimensions of the application: value catalogs that grants may restrict rows by." }),
2026
+ membershipSources: z.array(membershipSourceSchema).default([]).meta({ description: "Adopted tables that hold the membership of a scope kind instead of a membership catalog." }),
2027
+ assignmentSources: z.array(assignmentSourceSchema).default([]).meta({ description: "Adopted tables that hold role assignments of one level." }),
2028
+ storageBuckets: z.array(z.strictObject({
2029
+ bucket: z.string().min(1).meta({ description: "Name of the provider storage bucket." }),
2030
+ scopeKind: elementNameSchema.meta({ description: "Name of the project scope kind that scopes access to the bucket." })
2031
+ })).default([]).meta({ description: "Provider storage buckets whose access policies follow a scope kind." })
2032
+ }).superRefine((project, ctx) => {
2033
+ project.scopeKinds.forEach((kind, index) => {
2034
+ if (kind.name === "none") ctx.addIssue({
2035
+ code: "custom",
2036
+ message: `Scope kind name "${NO_SCOPE}" is reserved`,
2037
+ path: [
2038
+ "scopeKinds",
2039
+ index,
2040
+ "name"
2041
+ ],
2042
+ params: { rule: "scope.name-reserved" }
2043
+ });
2044
+ });
2045
+ });
2046
+ //#endregion
2047
+ //#region src/model/physical/pg-keywords.ts
2048
+ /**
2049
+ * Ключові слова Postgres, які `quote_ident` бере в лапки: усі, що не
2050
+ * UNRESERVED_KEYWORD у `kwlist.h` (зарезервовані, col_name і
2051
+ * type_func_name). Один список для обох ролей: точна поведінка `quote_ident`
2052
+ * (від неї залежить збіг імен у знімку й у каталозі БД) і те, що платформа
2053
+ * вважає зарезервованим словом у фізичних іменах — інакше ім'я, яке БД не
2054
+ * потребує брати в лапки, отримувало б зайвий суфікс.
2055
+ */
2056
+ const PG_QUOTED_KEYWORDS = /* @__PURE__ */ new Set([
2057
+ ...`all analyse analyze and any array as asc asymmetric both case cast check
2058
+ collate column constraint create current_catalog current_date current_role
2059
+ current_time current_timestamp current_user default deferrable desc distinct
2060
+ do else end except false fetch for foreign from grant group having in
2061
+ initially intersect into lateral leading limit localtime localtimestamp not
2062
+ null offset on only or order placing primary references returning select
2063
+ session_user some symmetric system_user table then to trailing true union
2064
+ unique user using variadic when where window with`.split(/\s+/),
2065
+ ...`authorization binary collation concurrently cross current_schema freeze
2066
+ full ilike inner is isnull join left like natural notnull outer overlaps
2067
+ right similar tablesample verbose`.split(/\s+/),
2068
+ ...`between bigint bit boolean char character coalesce dec decimal exists
2069
+ extract float greatest grouping inout int integer interval json json_array
2070
+ json_arrayagg json_exists json_object json_objectagg json_query json_scalar
2071
+ json_serialize json_table json_value least merge_action national nchar none
2072
+ normalize nullif numeric out overlay position precision real row setof
2073
+ smallint substring time timestamp treat trim values varchar xmlattributes
2074
+ xmlconcat xmlelement xmlexists xmlforest xmlnamespaces xmlparse xmlpi
2075
+ xmlroot xmlserialize xmltable`.split(/\s+/)
2076
+ ]);
2077
+ /** Слово, яке `quote_ident` бере в лапки; регістр не важливий. */
2078
+ function isSqlReservedWord(name) {
2079
+ return PG_QUOTED_KEYWORDS.has(name.toLowerCase());
2080
+ }
2081
+ //#endregion
2082
+ //#region src/model/physical/pg-names.ts
2083
+ /** NAMEDATALEN у Postgres мінус завершальний нуль. */
2084
+ const MAX_IDENT_BYTES = 63;
2085
+ const encoder = new TextEncoder();
2086
+ const decoder = new TextDecoder();
2087
+ const PLAIN_IDENT = /^[a-z_][a-z0-9_$]*$/;
2088
+ /** Як `quote_ident` Postgres: лапки лише коли без них ім'я змінилося б. */
2089
+ function quoteIdent(name) {
2090
+ if (PLAIN_IDENT.test(name) && !PG_QUOTED_KEYWORDS.has(name)) return name;
2091
+ return `"${name.replaceAll("\"", "\"\"")}"`;
2092
+ }
2093
+ /**
2094
+ * Обрізає до `maxBytes` байтів UTF-8, не розриваючи символ (аналог
2095
+ * `pg_mbcliplen`): Postgres міряє ліміт у байтах, а розрізаний символ дав би
2096
+ * інше ім'я, ніж те, що збереже БД.
2097
+ */
2098
+ function clipBytes(bytes, maxBytes) {
2099
+ let end = Math.min(maxBytes, bytes.length);
2100
+ while (end > 0 && end < bytes.length && (bytes[end] & 192) === 128) end--;
2101
+ return bytes.subarray(0, end);
2102
+ }
2103
+ /**
2104
+ * Ім'я об'єкта за алгоритмом `makeObjectName` Postgres: `name1[_name2]_label`,
2105
+ * а коли не влізає в 63 байти — скорочуються частини (довша першою, за
2106
+ * рівності — друга), мітка лишається цілою.
2107
+ */
2108
+ function makeObjectName(name1, name2, label) {
2109
+ const n1 = encoder.encode(name1);
2110
+ const n2 = name2 === void 0 ? void 0 : encoder.encode(name2);
2111
+ let overhead = encoder.encode(label).length + 1;
2112
+ if (n2 !== void 0) overhead++;
2113
+ const avail = MAX_IDENT_BYTES - overhead;
2114
+ let len1 = n1.length;
2115
+ let len2 = n2?.length ?? 0;
2116
+ while (len1 + len2 > avail) if (len1 > len2) len1--;
2117
+ else len2--;
2118
+ let result = decoder.decode(clipBytes(n1, len1));
2119
+ if (n2 !== void 0) result += `_${decoder.decode(clipBytes(n2, len2))}`;
2120
+ return `${result}_${label}`;
2121
+ }
2122
+ /**
2123
+ * Як `ChooseConstraintName`: за колізії з уже зайнятим ім'ям до мітки
2124
+ * дописується лічильник (`key1`, `key2`, …) і ім'я будується заново, тож
2125
+ * обрізання враховує довшу мітку.
2126
+ */
2127
+ function chooseConstraintName(name1, name2, label, taken) {
2128
+ let candidate = makeObjectName(name1, name2, label);
2129
+ for (let pass = 1; taken.has(candidate); pass++) candidate = makeObjectName(name1, name2, `${label}${pass}`);
2130
+ return candidate;
2131
+ }
2132
+ //#endregion
2133
+ //#region src/model/physical/pg-types.ts
2134
+ /**
2135
+ * Логічний тип → рядок у формі `format_type()`: саме в такому вигляді
2136
+ * Postgres віддає тип із каталогу, тож знімок метаданих і знімок extract
2137
+ * порівнюються без нормалізації.
2138
+ */
2139
+ function pgTypeOf(value, refTargetKind) {
2140
+ const base = baseType(value, refTargetKind);
2141
+ return value.array === true ? `${base}[]` : base;
2142
+ }
2143
+ function baseType(value, refTargetKind) {
2144
+ switch (value.type) {
2145
+ case "UUID": return "uuid";
2146
+ case "String": return `character varying(${value.length})`;
2147
+ case "Text": return "text";
2148
+ case "SmallInt": return "smallint";
2149
+ case "Integer": return "integer";
2150
+ case "BigInt": return "bigint";
2151
+ case "Numeric": return value.precision === void 0 ? "numeric" : `numeric(${value.precision},${value.scale ?? 0})`;
2152
+ case "Boolean": return "boolean";
2153
+ case "Date": return "date";
2154
+ case "DateTime": return "timestamp with time zone";
2155
+ case "Bytes": return "bytea";
2156
+ case "Json": return "jsonb";
2157
+ case "Ref": return refTargetKind === "Enumeration" ? "text" : "uuid";
2158
+ }
2159
+ }
2160
+ function pgEnumTypeName(schema, physicalName) {
2161
+ return `${quoteIdent(schema)}.${quoteIdent(physicalName)}`;
2162
+ }
2163
+ const SCALAR_TYPES = {
2164
+ uuid: { type: "UUID" },
2165
+ text: { type: "Text" },
2166
+ smallint: { type: "SmallInt" },
2167
+ integer: { type: "Integer" },
2168
+ bigint: { type: "BigInt" },
2169
+ boolean: { type: "Boolean" },
2170
+ date: { type: "Date" },
2171
+ "timestamp with time zone": { type: "DateTime" },
2172
+ bytea: { type: "Bytes" },
2173
+ jsonb: { type: "Json" },
2174
+ numeric: { type: "Numeric" }
2175
+ };
2176
+ const VARCHAR = /^character varying\((\d+)\)$/;
2177
+ const NUMERIC = /^numeric\((\d+),(\d+)\)$/;
2178
+ /** Розбір `schema.name` / `name` з лапками `"…"` (подвоєна `""` — лапка). */
2179
+ function parseQualifiedName(text) {
2180
+ const parts = [];
2181
+ let i = 0;
2182
+ for (;;) {
2183
+ let part = "";
2184
+ if (text[i] === "\"") {
2185
+ i++;
2186
+ for (;;) {
2187
+ if (i >= text.length) return void 0;
2188
+ if (text[i] === "\"") {
2189
+ if (text[i + 1] === "\"") {
2190
+ part += "\"";
2191
+ i += 2;
2192
+ continue;
2193
+ }
2194
+ i++;
2195
+ break;
2196
+ }
2197
+ part += text[i++];
2198
+ }
2199
+ } else {
2200
+ const start = i;
2201
+ while (i < text.length && text[i] !== "." && text[i] !== "\"") i++;
2202
+ part = text.slice(start, i);
2203
+ }
2204
+ if (part === "") return void 0;
2205
+ parts.push(part);
2206
+ if (i === text.length) return parts;
2207
+ if (text[i] !== ".") return void 0;
2208
+ i++;
2209
+ }
2210
+ }
2211
+ function logicalBase(base) {
2212
+ const scalar = SCALAR_TYPES[base];
2213
+ if (scalar !== void 0) return { ...scalar };
2214
+ const varchar = VARCHAR.exec(base);
2215
+ if (varchar !== null) {
2216
+ const length = Number(varchar[1]);
2217
+ return length > 0 ? {
2218
+ type: "String",
2219
+ length
2220
+ } : void 0;
2221
+ }
2222
+ const numeric = NUMERIC.exec(base);
2223
+ if (numeric !== null) {
2224
+ const precision = Number(numeric[1]);
2225
+ const scale = Number(numeric[2]);
2226
+ if (precision <= 0) return void 0;
2227
+ return scale === 0 ? {
2228
+ type: "Numeric",
2229
+ precision
2230
+ } : {
2231
+ type: "Numeric",
2232
+ precision,
2233
+ scale
2234
+ };
2235
+ }
2236
+ }
2237
+ /**
2238
+ * Inverse of `pgTypeOf`: reads a `format_type()` text back into a logical type.
2239
+ * Only an exact image of a logical type becomes `logical`
2240
+ * (`pgTypeOf(result.value) === formatType`); a type that is an enum from
2241
+ * `enumTypes` (`"schema.name"` entries) becomes the physical pair; anything
2242
+ * else is `raw`. A bare `uuid` is always `UUID` — an FK is described separately.
2243
+ */
2244
+ function logicalTypeOf(formatType, enumTypes) {
2245
+ const array = formatType.endsWith("[]");
2246
+ const base = array ? formatType.slice(0, -2) : formatType;
2247
+ const value = logicalBase(base);
2248
+ if (value !== void 0) return {
2249
+ form: "logical",
2250
+ value: array ? {
2251
+ ...value,
2252
+ array: true
2253
+ } : value
2254
+ };
2255
+ const pair = array ? void 0 : enumPair(base, enumTypes);
2256
+ return pair === void 0 ? {
2257
+ form: "raw",
2258
+ pgType: formatType
2259
+ } : {
2260
+ form: "enum",
2261
+ ...pair
2262
+ };
2263
+ }
2264
+ /**
2265
+ * `format_type()` друкує тип без схеми, коли той у `search_path`, і з нею —
2266
+ * інакше; ім'я з лапками, якщо потребує. Тож приймаються обидві форми, а
2267
+ * неоднозначне нескваліфіковане ім'я (енам з однаковою назвою у кількох
2268
+ * схемах) не вгадується й лишається `raw`.
2269
+ */
2270
+ function enumPair(base, enumTypes) {
2271
+ const parts = parseQualifiedName(base);
2272
+ if (parts === void 0) return void 0;
2273
+ if (parts.length === 2) {
2274
+ const [schema, name] = parts;
2275
+ return enumTypes.has(`${schema}.${name}`) ? {
2276
+ schema,
2277
+ name
2278
+ } : void 0;
2279
+ }
2280
+ if (parts.length !== 1) return void 0;
2281
+ const name = parts[0];
2282
+ const matches = [...enumTypes].filter((q) => {
2283
+ const dot = q.indexOf(".");
2284
+ return q.slice(dot + 1) === name;
2285
+ });
2286
+ if (matches.length !== 1) return void 0;
2287
+ const dot = matches[0].indexOf(".");
2288
+ return {
2289
+ schema: matches[0].slice(0, dot),
2290
+ name
2291
+ };
2292
+ }
2293
+ //#endregion
2294
+ //#region src/model/physical/period.ts
2295
+ /**
2296
+ * Єдине джерело усічення моменту до дати в поясі проєкту (спека П2/C3):
2297
+ * `timestamptz::date` без `AT TIME ZONE` усікає за поясом сесії, тож межа
2298
+ * місяця «пливла» б залежно від клієнта. Вираз незмінний (`IMMUTABLE`) лише
2299
+ * з явним поясом-літералом, тому його однаково використовують індекси, ключі
2300
+ * похідних таблиць і SQL П3 — ніхто не збирає його вдруге.
2301
+ */
2302
+ function truncatedPeriodExpression(column, unit, timezone) {
2303
+ const zone = `'${timezone.replaceAll("'", "''")}'`;
2304
+ return `date_trunc('${unit}', (${quoteIdent(column)} AT TIME ZONE ${zone}))::date`;
2305
+ }
2306
+ //#endregion
2307
+ //#region src/model/physical/assign.ts
2308
+ function baseName(logicalName, role) {
2309
+ const snake = toSnakeCase(logicalName);
2310
+ switch (role.role) {
2311
+ case "tabularSection": return `${role.ownerPhysicalName}_${snake}`;
2312
+ case "scopeKind": return `${snake}_id`;
2313
+ case "field": return role.reference === "single" ? `${snake}_id` : snake;
2314
+ case "object":
2315
+ case "label":
2316
+ case "column": return snake;
2317
+ }
2318
+ }
2319
+ /**
2320
+ * Фізичне ім'я нового елемента — факт моделі, а не CLI. Призначається раз і
2321
+ * ніколи не змінюється, тож зарезервоване слово чи зайняте ім'я обходиться
2322
+ * суфіксом `_`, доки ім'я не стане вільним: квотування врятувало б SQL, але
2323
+ * не читача. Мітці суфікс дає лише зайнятість. `taken` — імена тієї ж області унікальності; їх збирає виклик.
2324
+ */
2325
+ function assignPhysicalName(logicalName, role, taken) {
2326
+ let name = baseName(logicalName, role);
2327
+ const reserved = (n) => role.role !== "label" && isSqlReservedWord(n);
2328
+ while (reserved(name) || taken.has(name)) name += "_";
2329
+ return name;
2330
+ }
2331
+ //#endregion
2332
+ //#region src/model/physical/catalog.ts
2333
+ /**
2334
+ * Класи SQL-одиниць (спека П2 §8.3); належать T0, бо їх читає й порт
2335
+ * каталогу. Масив, а не лише тип: строгі схеми файлів (запис промоції)
2336
+ * перевіряють клас тим самим переліком.
2337
+ */
2338
+ const SQL_UNIT_CLASSES = [
2339
+ "function",
2340
+ "procedure",
2341
+ "aggregate",
2342
+ "trigger",
2343
+ "policy",
2344
+ "view",
2345
+ "materializedView",
2346
+ "grant",
2347
+ "defaultPrivileges",
2348
+ "comment",
2349
+ "extension",
2350
+ "sequence",
2351
+ "sequenceOwnedBy",
2352
+ "domain",
2353
+ "publication",
2354
+ "replicaIdentity",
2355
+ "functionSettings",
2356
+ "movementQuery"
2357
+ ];
2358
+ function compare(a, b) {
2359
+ return a < b ? -1 : a > b ? 1 : 0;
2360
+ }
2361
+ /** Знімок без `origin`; порядок уже детермінований знімком. */
2362
+ function catalogFromSnapshot(snapshot) {
2363
+ return {
2364
+ tables: snapshot.tables.map((table) => {
2365
+ const copy = { ...table };
2366
+ delete copy.origin;
2367
+ return {
2368
+ ...copy,
2369
+ columns: table.columns.map((column) => {
2370
+ const c = { ...column };
2371
+ delete c.origin;
2372
+ return c;
2373
+ }),
2374
+ checks: table.checks.map(({ name, expression }) => ({
2375
+ name,
2376
+ expression
2377
+ }))
2378
+ };
2379
+ }),
2380
+ enumTypes: snapshot.enumTypes.map((e) => {
2381
+ const copy = { ...e };
2382
+ delete copy.origin;
2383
+ return copy;
2384
+ })
2385
+ };
2386
+ }
2387
+ /** Канонічна JSON-форма: ключі впорядковані, тож порядок полів не впливає. */
2388
+ function canon(value) {
2389
+ return JSON.stringify(value, (_k, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([x], [y]) => compare(x, y))) : v);
2390
+ }
2391
+ /** Порівнює словники за ключем: відсутній ліворуч — `extra`, праворуч — `missing`. */
2392
+ function diffKeyed(path, a, b, out, onBoth) {
2393
+ for (const [key, x] of a) {
2394
+ const y = b.get(key);
2395
+ if (y === void 0) out.push({
2396
+ path: `${path}.${key}`,
2397
+ kind: "missing",
2398
+ detail: "absent in second model"
2399
+ });
2400
+ else onBoth(`${path}.${key}`, x, y);
2401
+ }
2402
+ for (const key of b.keys()) if (!a.has(key)) out.push({
2403
+ path: `${path}.${key}`,
2404
+ kind: "extra",
2405
+ detail: "absent in first model"
2406
+ });
2407
+ }
2408
+ const byName = (items) => new Map(items.map((i) => [i.name, i]));
2409
+ function diffChanged(path, x, y, out) {
2410
+ if (canon(x) !== canon(y)) out.push({
2411
+ path,
2412
+ kind: "changed",
2413
+ detail: `${canon(x)} != ${canon(y)}`
2414
+ });
2415
+ }
2416
+ function diffTable(path, a, b, out, columnOrder) {
2417
+ const { columns: ca, primaryKey: pa, uniques: ua, checks: ka, foreignKeys: fa, indexes: ia, ...restA } = a;
2418
+ const { columns: cb, primaryKey: pb, uniques: ub, checks: kb, foreignKeys: fb, indexes: ib, ...restB } = b;
2419
+ diffChanged(path, restA, restB, out);
2420
+ diffKeyed(`${path}.columns`, byName(ca), byName(cb), out, (p, x, y) => diffChanged(p, x, y, out));
2421
+ const namesA = ca.map((c) => c.name);
2422
+ const namesB = cb.map((c) => c.name);
2423
+ const sameSet = namesA.length === namesB.length && namesA.every((n) => namesB.includes(n));
2424
+ if (columnOrder && sameSet && namesA.some((n, i) => n !== namesB[i])) out.push({
2425
+ path: `${path}.columns`,
2426
+ kind: "order",
2427
+ detail: `column order ${namesA.join(",")} != ${namesB.join(",")}`
2428
+ });
2429
+ diffChanged(`${path}.primaryKey`, pa ?? null, pb ?? null, out);
2430
+ diffKeyed(`${path}.uniques`, byName(ua), byName(ub), out, (p, x, y) => diffChanged(p, x, y, out));
2431
+ diffKeyed(`${path}.checks`, byName(ka), byName(kb), out, (p, x, y) => diffChanged(p, x, y, out));
2432
+ diffKeyed(`${path}.foreignKeys`, byName(fa), byName(fb), out, (p, x, y) => diffChanged(p, x, y, out));
2433
+ diffKeyed(`${path}.indexes`, byName(ia), byName(ib), out, (p, x, y) => diffChanged(p, x, y, out));
2434
+ }
2435
+ /** Структурне порівняння двох моделей каталогу; результат упорядкований за `path`. */
2436
+ function diffCatalogModels(a, b, { columnOrder }) {
2437
+ const out = [];
2438
+ const qualified = (items) => new Map(items.map((i) => [`${i.schema}.${i.name}`, i]));
2439
+ diffKeyed("tables", qualified(a.tables), qualified(b.tables), out, (p, x, y) => diffTable(p, x, y, out, columnOrder));
2440
+ diffKeyed("enumTypes", qualified(a.enumTypes), qualified(b.enumTypes), out, (p, x, y) => diffChanged(p, x, y, out));
2441
+ diffKeyed("units", new Map(a.units.map((u) => [u.identity, u])), new Map(b.units.map((u) => [u.identity, u])), out, (p, x, y) => diffChanged(p, x, y, out));
2442
+ return out.sort((x, y) => compare(x.path, y.path));
2443
+ }
2444
+ //#endregion
2445
+ //#region src/model/kinds/standard.ts
2446
+ /**
2447
+ * Логічне ім'я стандартного реквізиту в стилі проєкту (спека §3, М16). Ключ
2448
+ * `ref` однаковий в обох стилях, решта в snake_case — пряма зміна регістру.
2449
+ */
2450
+ function standardLogicalName(def, style) {
2451
+ if (style === "camelCase" || def.logicalName === "ref") return def.logicalName;
2452
+ return toSnakeCase(def.logicalName);
2453
+ }
2454
+ /** Спільна шапка файлу завжди йде першою, щоб файли всіх видів читалися однаково. */
2455
+ const HEADER_KEY_ORDER = [
2456
+ "$schema",
2457
+ "id",
2458
+ "kind",
2459
+ "name",
2460
+ "physicalName",
2461
+ "kindLabel",
2462
+ "schema",
2463
+ "scope",
2464
+ "title",
2465
+ "description"
2466
+ ];
2467
+ /**
2468
+ * Порядок ключів — шапка, далі решта полів у порядку оголошення в схемі виду:
2469
+ * так порядок форматера не може розійтися зі схемою.
2470
+ */
2471
+ function keyOrderOf(schema) {
2472
+ const header = HEADER_KEY_ORDER;
2473
+ const keys = Object.keys(schema.shape);
2474
+ return [...header.filter((key) => keys.includes(key)), ...keys.filter((key) => !header.includes(key))];
2475
+ }
2476
+ function keyColumn(withDefault) {
2477
+ return {
2478
+ logicalName: "ref",
2479
+ physicalName: "id",
2480
+ type: { type: "UUID" },
2481
+ notNull: true,
2482
+ primaryKey: true,
2483
+ ...withDefault ? { default: "gen_random_uuid()" } : {},
2484
+ title: {
2485
+ uk: "Посилання",
2486
+ en: "Reference"
2487
+ }
2488
+ };
2489
+ }
2490
+ function deletionMarkColumn() {
2491
+ return {
2492
+ logicalName: "deletionMark",
2493
+ physicalName: "deletion_mark",
2494
+ type: { type: "Boolean" },
2495
+ notNull: true,
2496
+ default: "false",
2497
+ title: {
2498
+ uk: "Позначка видалення",
2499
+ en: "Deletion mark"
2500
+ }
2501
+ };
2502
+ }
2503
+ /**
2504
+ * Версія рядка для оптимістичної конкурентності. Збільшує її разом зі
2505
+ * службовою датою оновлення тригер механіки (`compiler/mechanics-units.ts`).
2506
+ * Іде одразу перед службовими датами.
2507
+ */
2508
+ function versionColumn() {
2509
+ return {
2510
+ logicalName: "version",
2511
+ physicalName: "version",
2512
+ type: { type: "BigInt" },
2513
+ notNull: true,
2514
+ default: "1",
2515
+ title: {
2516
+ uk: "Версія",
2517
+ en: "Version"
2518
+ }
2519
+ };
2520
+ }
2521
+ function serviceDateColumns() {
2522
+ return [{
2523
+ logicalName: "createdAt",
2524
+ physicalName: "created_at",
2525
+ type: { type: "DateTime" },
2526
+ notNull: true,
2527
+ default: "now()",
2528
+ title: {
2529
+ uk: "Дата створення",
2530
+ en: "Created at"
2531
+ }
2532
+ }, {
2533
+ logicalName: "updatedAt",
2534
+ physicalName: "updated_at",
2535
+ type: { type: "DateTime" },
2536
+ notNull: true,
2537
+ default: "now()",
2538
+ title: {
2539
+ uk: "Дата оновлення",
2540
+ en: "Updated at"
2541
+ }
2542
+ }];
2543
+ }
2544
+ /**
2545
+ * Авторство (спека П2 §5): посилання на «Користувачі», а не на учасника —
2546
+ * автор лишається автором і після виходу з тенанта. Nullable, бо рядок може
2547
+ * записати й не користувач (міграція, провізія); заповнює їх `runCommand`.
2548
+ */
2549
+ function authorColumns() {
2550
+ return [{
2551
+ logicalName: "createdBy",
2552
+ physicalName: "created_by_id",
2553
+ type: { type: "UUID" },
2554
+ notNull: false,
2555
+ ref: "users",
2556
+ indexed: true,
2557
+ title: {
2558
+ uk: "Автор",
2559
+ en: "Created by"
2560
+ }
2561
+ }, {
2562
+ logicalName: "updatedBy",
2563
+ physicalName: "updated_by_id",
2564
+ type: { type: "UUID" },
2565
+ notNull: false,
2566
+ ref: "users",
2567
+ indexed: true,
2568
+ title: {
2569
+ uk: "Автор зміни",
2570
+ en: "Updated by"
2571
+ }
2572
+ }];
2573
+ }
2574
+ /**
2575
+ * Номер чи код: рядок заданої довжини або ціле число. Тип виду береться зі
2576
+ * схеми документа (у довідника `codeType` той самий), щоб значення не
2577
+ * дублювалися літералом.
2578
+ */
2579
+ function numberingType(kind, length) {
2580
+ return kind === "String" ? {
2581
+ type: "String",
2582
+ length
2583
+ } : { type: "Integer" };
2584
+ }
2585
+ /**
2586
+ * Окремого індексу на `period` немає: період входить в індекси рухів і в
2587
+ * ключ регістра (стадія 3 за `registerKeys`).
2588
+ */
2589
+ function periodColumn() {
2590
+ return {
2591
+ logicalName: "period",
2592
+ physicalName: "period",
2593
+ type: { type: "DateTime" },
2594
+ notNull: true,
2595
+ title: {
2596
+ uk: "Період",
2597
+ en: "Period"
2598
+ }
2599
+ };
2600
+ }
2601
+ /**
2602
+ * Місяць обороту в похідній таблиці регістра: перший день місяця за поясом
2603
+ * проєкту (`truncatedPeriodExpression`), тож тип — `date`, а не момент.
2604
+ */
2605
+ function monthColumn() {
2606
+ return {
2607
+ logicalName: "month",
2608
+ physicalName: "month",
2609
+ type: { type: "Date" },
2610
+ notNull: true,
2611
+ title: {
2612
+ uk: "Місяць",
2613
+ en: "Month"
2614
+ }
2615
+ };
2616
+ }
2617
+ /**
2618
+ * Ключ рядка-одинака: колонка, що може мати лише значення true. `unique` —
2619
+ * одинак як ключ запису поруч з іншим PK (підлеглий регістр відомостей).
2620
+ */
2621
+ function singletonColumn(role = "primaryKey") {
2622
+ return {
2623
+ logicalName: "singleton",
2624
+ physicalName: "singleton",
2625
+ type: { type: "Boolean" },
2626
+ notNull: true,
2627
+ ...role === "primaryKey" ? { primaryKey: true } : { unique: true },
2628
+ singleton: true,
2629
+ default: "true",
2630
+ check: "singleton",
2631
+ title: {
2632
+ uk: "Одинак",
2633
+ en: "Singleton"
2634
+ }
2635
+ };
2636
+ }
2637
+ /** Реєстратор, номер рядка й активність рухів — разом, як у 1С. */
2638
+ function recorderColumns() {
2639
+ return [
2640
+ {
2641
+ logicalName: "recorder",
2642
+ physicalName: "recorder",
2643
+ type: { type: "UUID" },
2644
+ notNull: true,
2645
+ ref: "recorders",
2646
+ polymorphic: "always",
2647
+ filledByShell: true,
2648
+ title: {
2649
+ uk: "Реєстратор",
2650
+ en: "Recorder"
2651
+ }
2652
+ },
2653
+ {
2654
+ ...lineNumberColumn(),
2655
+ filledByShell: true
2656
+ },
2657
+ {
2658
+ logicalName: "active",
2659
+ physicalName: "active",
2660
+ type: { type: "Boolean" },
2661
+ notNull: true,
2662
+ default: "true",
2663
+ filledByShell: true,
2664
+ title: {
2665
+ uk: "Активність",
2666
+ en: "Active"
2667
+ }
2668
+ }
2669
+ ];
2670
+ }
2671
+ function lineNumberColumn() {
2672
+ return {
2673
+ logicalName: "lineNumber",
2674
+ physicalName: "line_number",
2675
+ type: { type: "Integer" },
2676
+ notNull: true,
2677
+ title: {
2678
+ uk: "Номер рядка",
2679
+ en: "Line number"
2680
+ }
2681
+ };
2682
+ }
2683
+ /** Рядок ТЧ живе й помирає разом із власником — звідси каскад. */
2684
+ function tabularRowColumns(keyDefault) {
2685
+ return [
2686
+ keyColumn(keyDefault),
2687
+ {
2688
+ logicalName: "parent",
2689
+ physicalName: "parent_id",
2690
+ type: { type: "UUID" },
2691
+ notNull: true,
2692
+ ref: "owningObject",
2693
+ onDelete: "cascade",
2694
+ indexed: true,
2695
+ title: {
2696
+ uk: "Власник рядка",
2697
+ en: "Owning object"
2698
+ }
2699
+ },
2700
+ lineNumberColumn()
2701
+ ];
2702
+ }
2703
+ /**
2704
+ * Колонки шапки, які пишуть кастомні дії (`effects.header`): посилання на
2705
+ * власні колонки об'єкта, тож перейменування реквізиту бачить індекс.
2706
+ */
2707
+ function customActionReferences(obj) {
2708
+ return obj.customActions.flatMap((action, index) => {
2709
+ const { header } = action.effects;
2710
+ if (header === void 0 || header === "all") return [];
2711
+ return header.map((name, at) => ({
2712
+ pointer: `/customActions/${index}/effects/header/${at}`,
2713
+ name,
2714
+ role: "customAction.header"
2715
+ }));
2716
+ });
2717
+ }
2718
+ /**
2719
+ * Посилання носія прав (Рх21): рядок чи перший крок шляху — власна колонка,
2720
+ * другий крок — колонка цілі першого. Ціль першого кроку — `ref` реквізиту
2721
+ * або ціль стандартної колонки-посилання (`parent` — сам об'єкт, єдиний
2722
+ * власник, «Користувачі» авторства). Невідома ціль (поліморфне посилання,
2723
+ * не посилання) — другий крок в індекс не йде, а перший відхиляє правило
2724
+ * носія (`rights.carrier-not-ref`).
2725
+ */
2726
+ function carrierReferences(carrier, pointer, host, standard, head = "rights.carrier") {
2727
+ if (typeof carrier === "string") return [{
2728
+ pointer,
2729
+ name: carrier,
2730
+ role: head
2731
+ }];
2732
+ const [first, second] = carrier;
2733
+ const owner = carrierStepTarget(first, host, standard);
2734
+ return [{
2735
+ pointer: `${pointer}/0`,
2736
+ name: first,
2737
+ role: head
2738
+ }, ...owner === void 0 ? [] : [{
2739
+ pointer: `${pointer}/1`,
2740
+ name: second,
2741
+ owner,
2742
+ role: "rights.carrierPath"
2743
+ }]];
2744
+ }
2745
+ /**
2746
+ * Ціль одиночного посилання за логічним іменем. Стиль імен проєкту T0 не
2747
+ * знає, тож стандартну колонку впізнаємо в обох стилях: її ім'я
2748
+ * зарезервоване, і реквізит з таким самим іменем неможливий.
2749
+ */
2750
+ function carrierStepTarget(name, host, standard) {
2751
+ const attribute = host.attributes.find((a) => a.name === name);
2752
+ if (attribute !== void 0) return attribute.ref;
2753
+ const column = standard.find((c) => c.logicalName === name || toSnakeCase(c.logicalName) === name);
2754
+ if (column === void 0 || column.polymorphic === "always") return void 0;
2755
+ if (column.ref === "self") return {
2756
+ kind: host.kind,
2757
+ name: host.name
2758
+ };
2759
+ if (column.ref === "users") return "users";
2760
+ if (column.ref === "owners" && host.owners?.length === 1) return host.owners[0];
2761
+ }
2762
+ /** Носії `ownership` об'єкта. */
2763
+ function ownershipReferences(obj, standard) {
2764
+ return (obj.ownership ?? []).flatMap((carrier, index) => carrierReferences(carrier, `/ownership/${index}`, obj, standard));
2765
+ }
2766
+ /** Носій `containerBinding` об'єкта (прив'язка до контейнера прав). */
2767
+ function bindingReferences(obj, standard) {
2768
+ return obj.containerBinding === void 0 ? [] : carrierReferences(obj.containerBinding, "/containerBinding", obj, standard);
2769
+ }
2770
+ /**
2771
+ * Носії мапінгів `access` об'єкта: реквізит — на `/access/i/attribute`, шлях —
2772
+ * на `/access/i/ref`; роль першого кроку — `access.attribute`, другого — та
2773
+ * сама, що в будь-якого шляху носія.
2774
+ */
2775
+ function accessReferences(obj, standard) {
2776
+ return (obj.access ?? []).flatMap((mapping, index) => "attribute" in mapping ? carrierReferences(mapping.attribute, `/access/${index}/attribute`, obj, standard, "access.attribute") : carrierReferences(mapping.ref, `/access/${index}/ref`, obj, standard, "access.attribute"));
2777
+ }
2778
+ /**
2779
+ * Регістр як носій прав: колонки дають виміри, ресурси й реквізити, тож
2780
+ * перший крок шляху шукається серед усіх них.
2781
+ */
2782
+ function registerCarrierHost(register) {
2783
+ return {
2784
+ kind: register.kind,
2785
+ name: register.name,
2786
+ attributes: [
2787
+ ...register.dimensions,
2788
+ ...register.resources,
2789
+ ...register.attributes
2790
+ ],
2791
+ ...register.access === void 0 ? {} : { access: register.access }
2792
+ };
2793
+ }
2794
+ /** Виміри доступу проєкту, які називає `access` об'єкта. */
2795
+ function accessDimensionReferences(obj) {
2796
+ return (obj.access ?? []).map((mapping, index) => ({
2797
+ pointer: `/access/${index}/dimension`,
2798
+ name: mapping.dimension,
2799
+ collection: "accessDimensions",
2800
+ role: "access.dimension"
2801
+ }));
2802
+ }
2803
+ /**
2804
+ * Посилання одного поля з типом (реквізит, вимір, ресурс, колонка).
2805
+ * `allowedTypesPair` — чи будує перелік цілей фізичну пару: так у видів 1С,
2806
+ * а прийнята таблиця описує фізику як є, і її `Ref` — лише тип колонки.
2807
+ */
2808
+ function valueTypeReferences(field, pointer, roles, allowedTypesPair) {
2809
+ const found = [];
2810
+ if (field.ref !== void 0) found.push({
2811
+ pointer: `${pointer}/ref`,
2812
+ ref: field.ref,
2813
+ role: roles.ref,
2814
+ pair: false,
2815
+ polymorphic: false
2816
+ });
2817
+ field.allowedTypes?.forEach((ref, index) => {
2818
+ found.push({
2819
+ pointer: `${pointer}/allowedTypes/${index}`,
2820
+ ref,
2821
+ role: roles.allowedType,
2822
+ pair: allowedTypesPair,
2823
+ polymorphic: true
2824
+ });
2825
+ });
2826
+ return found;
2827
+ }
2828
+ const ATTRIBUTE_ROLES = {
2829
+ ref: "attribute.ref",
2830
+ allowedType: "attribute.allowedType"
2831
+ };
2832
+ function fieldListReferences(fields, pointer) {
2833
+ return fields.flatMap((field, index) => valueTypeReferences(field, `${pointer}/${index}`, ATTRIBUTE_ROLES, true));
2834
+ }
2835
+ /**
2836
+ * Перелік цілей поза типом поля: або цілі стандартної колонки, що стає парою
2837
+ * саме тоді, коли поліморфна (`standardRefReferences`), або зовсім не
2838
+ * значення-посилання (рухи документа), тож обидва факти тут збігаються.
2839
+ */
2840
+ function refListReferences(refs, pointer, role, pair) {
2841
+ return refs.map((ref, index) => ({
2842
+ pointer: `${pointer}/${index}`,
2843
+ ref,
2844
+ role,
2845
+ pair,
2846
+ polymorphic: pair
2847
+ }));
2848
+ }
2849
+ /**
2850
+ * Цілі стандартної колонки-посилання виду (власники, реєстратори): чи вони
2851
+ * в парі, каже `polymorphic` самої колонки, — те саме, з чого стадія 3 будує
2852
+ * пару, тож шар ідентичності й фізичний шар не розійдуться.
2853
+ */
2854
+ function standardRefReferences(columns, ref, refs, pointer, role) {
2855
+ return refListReferences(refs, pointer, role, columns.find((c) => c.ref === ref)?.polymorphic !== void 0);
2856
+ }
2857
+ /** Реквізити об'єкта й реквізити його табличних частин. */
2858
+ function objectFieldReferences(obj) {
2859
+ return [...fieldListReferences(obj.attributes, "/attributes"), ...obj.tabularSections.flatMap((section, index) => fieldListReferences(section.attributes, `/tabularSections/${index}/attributes`))];
2860
+ }
2861
+ //#endregion
2862
+ //#region src/model/kinds/accumulation-register.ts
2863
+ function standardColumns$4(obj) {
2864
+ const register = obj;
2865
+ const columns = [periodColumn(), ...recorderColumns()];
2866
+ if (register.registerType === "Balance") columns.push({
2867
+ logicalName: "movementType",
2868
+ physicalName: "movement_type",
2869
+ type: { type: "Text" },
2870
+ notNull: true,
2871
+ check: "movement_type IN ('Receipt', 'Expense')",
2872
+ title: {
2873
+ uk: "Вид руху",
2874
+ en: "Movement type"
2875
+ }
2876
+ });
2877
+ return columns;
2878
+ }
2879
+ const accumulationRegisterKind = {
2880
+ kind: "AccumulationRegister",
2881
+ dir: "accumulation-registers",
2882
+ schema: accumulationRegisterSchema,
2883
+ keyOrder: keyOrderOf(accumulationRegisterSchema),
2884
+ referenceable: false,
2885
+ writePattern: "server",
2886
+ actions: () => [readAction],
2887
+ rightsExtents: ["any", "dimension"],
2888
+ sqlModule: "closed",
2889
+ materializes: "table",
2890
+ rowLevelSecurity: "enabled",
2891
+ scope: "required",
2892
+ declared: false,
2893
+ kindLabel: true,
2894
+ columnFields: [
2895
+ "dimensions",
2896
+ "resources",
2897
+ "attributes"
2898
+ ],
2899
+ idElementFields: ["customActions"],
2900
+ valueElements: false,
2901
+ standardColumns: standardColumns$4,
2902
+ registerKeys: (obj) => ({
2903
+ movementsPrimaryKey: "recorder",
2904
+ recordKeyUnique: false,
2905
+ movementIndexes: true,
2906
+ totals: obj.registerType === "Balance",
2907
+ turnoversMonth: { split: obj.registerType === "Balance" },
2908
+ additiveResources: true,
2909
+ virtualTables: obj.registerType === "Balance" ? ["balance", "balanceAndTurnovers"] : ["turnovers"]
2910
+ }),
2911
+ elementReferences: (obj) => [...customActionReferences(obj), ...accessReferences(registerCarrierHost(obj), standardColumns$4(obj))],
2912
+ projectReferences: (obj) => accessDimensionReferences(obj),
2913
+ references(obj) {
2914
+ const register = obj;
2915
+ return [
2916
+ ...standardRefReferences(standardColumns$4(register), "recorders", register.recorderTypes, "/recorderTypes", "register.recorder"),
2917
+ ...fieldListReferences(register.dimensions, "/dimensions"),
2918
+ ...fieldListReferences(register.attributes, "/attributes")
2919
+ ];
2920
+ }
2921
+ };
2922
+ //#endregion
2923
+ //#region src/model/kinds/catalog.ts
2924
+ function standardColumns$3(obj) {
2925
+ const catalog = obj;
2926
+ const columns = [keyColumn(false)];
2927
+ if (catalog.codeLength > 0) columns.push({
2928
+ logicalName: "code",
2929
+ physicalName: "code",
2930
+ type: numberingType(catalog.codeType, catalog.codeLength),
2931
+ notNull: false,
2932
+ indexed: true,
2933
+ title: {
2934
+ uk: "Код",
2935
+ en: "Code"
2936
+ }
2937
+ });
2938
+ if (catalog.descriptionLength > 0) columns.push({
2939
+ logicalName: "description",
2940
+ physicalName: "description",
2941
+ type: {
2942
+ type: "String",
2943
+ length: catalog.descriptionLength
2944
+ },
2945
+ notNull: false,
2946
+ title: {
2947
+ uk: "Найменування",
2948
+ en: "Description"
2949
+ }
2950
+ });
2951
+ columns.push(deletionMarkColumn());
2952
+ if (catalog.role !== void 0) columns.push(...CATALOG_ROLES[catalog.role].columns?.() ?? []);
2953
+ if (catalog.hierarchyType !== "None") columns.push({
2954
+ logicalName: "parent",
2955
+ physicalName: "parent_id",
2956
+ type: { type: "UUID" },
2957
+ notNull: false,
2958
+ ref: "self",
2959
+ indexed: true,
2960
+ title: {
2961
+ uk: "Батьківський елемент",
2962
+ en: "Parent item"
2963
+ }
2964
+ });
2965
+ if (catalog.hierarchyType === "FoldersAndItems") columns.push({
2966
+ logicalName: "isFolder",
2967
+ physicalName: "is_folder",
2968
+ type: { type: "Boolean" },
2969
+ notNull: true,
2970
+ default: "false",
2971
+ title: {
2972
+ uk: "Це група",
2973
+ en: "Is folder"
2974
+ }
2975
+ });
2976
+ if (catalog.owners.length > 0) {
2977
+ const many = catalog.owners.length > 1;
2978
+ columns.push({
2979
+ logicalName: "owner",
2980
+ physicalName: many ? "owner" : "owner_id",
2981
+ type: { type: "UUID" },
2982
+ notNull: false,
2983
+ ref: "owners",
2984
+ ...many ? { polymorphic: "whenMany" } : {},
2985
+ indexed: true,
2986
+ title: {
2987
+ uk: "Власник",
2988
+ en: "Owner"
2989
+ }
2990
+ });
2991
+ }
2992
+ columns.push({
2993
+ logicalName: "predefinedName",
2994
+ physicalName: "predefined_name",
2995
+ type: { type: "Text" },
2996
+ notNull: false,
2997
+ partialUnique: "predefined_name IS NOT NULL",
2998
+ title: {
2999
+ uk: "Ім'я наперед визначеного елемента",
3000
+ en: "Predefined name"
3001
+ }
3002
+ }, versionColumn(), ...serviceDateColumns(), ...catalog.trackAuthor ? authorColumns() : []);
3003
+ return columns;
3004
+ }
3005
+ /**
3006
+ * Платформні реквізити «Користувачів» (спека користувачів §4): провізія
3007
+ * вставляє рядок лише з ключем і найменуванням, тож обидва мають DEFAULT.
3008
+ * Недійсність не видаляє рядок — на нього можуть посилатися дані застосунку.
3009
+ */
3010
+ function userColumns() {
3011
+ return [{
3012
+ logicalName: "userKind",
3013
+ physicalName: "user_kind",
3014
+ type: { type: "Text" },
3015
+ notNull: true,
3016
+ default: "'human'",
3017
+ check: "user_kind IN ('human', 'agent')",
3018
+ title: {
3019
+ uk: "Вид користувача",
3020
+ en: "User kind"
3021
+ }
3022
+ }, {
3023
+ logicalName: "invalid",
3024
+ physicalName: "invalid",
3025
+ type: { type: "Boolean" },
3026
+ notNull: true,
3027
+ default: "false",
3028
+ title: {
3029
+ uk: "Недійсний",
3030
+ en: "Invalid"
3031
+ }
3032
+ }];
3033
+ }
3034
+ /** Ролі довідника — одне місце, звідки компілятор бере їхні факти. */
3035
+ const CATALOG_ROLES = { users: {
3036
+ globalRoot: true,
3037
+ columns: userColumns
3038
+ } };
3039
+ function numbering$1(obj) {
3040
+ const catalog = obj;
3041
+ if (catalog.codeLength === 0) return void 0;
3042
+ return {
3043
+ column: "code",
3044
+ type: catalog.codeType,
3045
+ length: catalog.codeLength,
3046
+ autonumber: catalog.autonumber,
3047
+ periodicity: "None",
3048
+ unique: catalog.codeUnique
3049
+ };
3050
+ }
3051
+ const catalogKind = {
3052
+ kind: "Catalog",
3053
+ dir: "catalogs",
3054
+ schema: catalogSchema,
3055
+ keyOrder: keyOrderOf(catalogSchema),
3056
+ referenceable: true,
3057
+ compositeIndexes: true,
3058
+ writePattern: "optimistic",
3059
+ actions: () => recordActions(catalogKind.tabularSectionColumns !== void 0),
3060
+ rightsExtents: [
3061
+ "any",
3062
+ "own",
3063
+ "dimension"
3064
+ ],
3065
+ rightsContainer: true,
3066
+ rightsBinding: true,
3067
+ accessDimensionTarget: true,
3068
+ sqlModule: "closed",
3069
+ materializes: "table",
3070
+ rowLevelSecurity: "enabled",
3071
+ authorTracking: true,
3072
+ scope: "required",
3073
+ declared: false,
3074
+ kindLabel: true,
3075
+ columnFields: ["attributes"],
3076
+ idElementFields: ["customActions"],
3077
+ valueElements: false,
3078
+ namedElementFields: ["predefinedItems"],
3079
+ ownerKinds: ["Catalog"],
3080
+ standardColumns: standardColumns$3,
3081
+ globalRoot(obj) {
3082
+ const { role } = obj;
3083
+ return role !== void 0 && CATALOG_ROLES[role].globalRoot === true;
3084
+ },
3085
+ numbering: numbering$1,
3086
+ tabularSectionColumns: () => tabularRowColumns(false),
3087
+ elementReferences: (obj) => [
3088
+ ...customActionReferences(obj),
3089
+ ...ownershipReferences(obj, standardColumns$3(obj)),
3090
+ ...bindingReferences(obj, standardColumns$3(obj)),
3091
+ ...accessReferences(obj, standardColumns$3(obj))
3092
+ ],
3093
+ projectReferences: (obj) => accessDimensionReferences(obj),
3094
+ references(obj) {
3095
+ const catalog = obj;
3096
+ return [...objectFieldReferences(catalog), ...standardRefReferences(standardColumns$3(catalog), "owners", catalog.owners, "/owners", "catalog.owner")];
3097
+ }
3098
+ };
3099
+ //#endregion
3100
+ //#region src/model/kinds/constant.ts
3101
+ /** Лише поля типу: решта полів константи до колонки `value` не належить. */
3102
+ function valueTypeOf(constant) {
3103
+ const { type, length, precision, scale, ref, allowedTypes, array } = constant;
3104
+ const { crossScope } = constant;
3105
+ const value = { type };
3106
+ if (length !== void 0) value.length = length;
3107
+ if (precision !== void 0) value.precision = precision;
3108
+ if (scale !== void 0) value.scale = scale;
3109
+ if (ref !== void 0) value.ref = ref;
3110
+ if (allowedTypes !== void 0) value.allowedTypes = allowedTypes;
3111
+ if (array !== void 0) value.array = array;
3112
+ if (crossScope !== void 0) value.crossScope = crossScope;
3113
+ return value;
3114
+ }
3115
+ function standardColumns$2(obj) {
3116
+ const constant = obj;
3117
+ return [singletonColumn(), {
3118
+ logicalName: "value",
3119
+ physicalName: "value",
3120
+ type: valueTypeOf(constant),
3121
+ notNull: false,
3122
+ ...constant.defaultValue !== void 0 ? { defaultValue: constant.defaultValue } : {},
3123
+ title: {
3124
+ uk: "Значення",
3125
+ en: "Value"
3126
+ }
3127
+ }];
3128
+ }
3129
+ const constantKind = {
3130
+ kind: "Constant",
3131
+ dir: "constants",
3132
+ schema: constantSchema,
3133
+ keyOrder: keyOrderOf(constantSchema),
3134
+ referenceable: false,
3135
+ writePattern: "server",
3136
+ actions: () => [readAction, updateAction(false, ["insert", "update"])],
3137
+ rightsExtents: ["any"],
3138
+ sqlModule: "closed",
3139
+ materializes: "table",
3140
+ rowLevelSecurity: "enabled",
3141
+ scope: "required",
3142
+ declared: false,
3143
+ kindLabel: true,
3144
+ columnFields: [],
3145
+ idElementFields: ["customActions"],
3146
+ valueElements: false,
3147
+ standardColumns: standardColumns$2,
3148
+ elementReferences: (obj) => customActionReferences(obj),
3149
+ references: (obj) => valueTypeReferences(obj, "", {
3150
+ ref: "constant.ref",
3151
+ allowedType: "constant.allowedType"
3152
+ }, true)
3153
+ };
3154
+ //#endregion
3155
+ //#region src/model/kinds/custom-table.ts
3156
+ function references(obj) {
3157
+ const table = obj;
3158
+ const found = [];
3159
+ table.columns.forEach((column, index) => {
3160
+ if (column.enum !== void 0) found.push({
3161
+ pointer: `/columns/${index}/enum`,
3162
+ ref: column.enum,
3163
+ role: "customTable.pgEnum",
3164
+ pair: false,
3165
+ polymorphic: false
3166
+ });
3167
+ found.push(...valueTypeReferences(column, `/columns/${index}`, ATTRIBUTE_ROLES, false));
3168
+ });
3169
+ table.foreignKeys.forEach((foreignKey, index) => {
3170
+ if ("object" in foreignKey.references) found.push({
3171
+ pointer: `/foreignKeys/${index}/references/object`,
3172
+ ref: foreignKey.references.object,
3173
+ role: "customTable.foreignKey",
3174
+ pair: false,
3175
+ polymorphic: false
3176
+ });
3177
+ });
3178
+ return found;
3179
+ }
3180
+ /**
3181
+ * Кожне місце, де опис таблиці називає колонку логічним іменем. Ключі
3182
+ * індексу — за pointer на `column`: ключ-вираз колонки не називає, а pointer
3183
+ * поля лишає місце сусіднім властивостям ключа.
3184
+ */
3185
+ function elementReferences(obj) {
3186
+ const table = obj;
3187
+ const found = [];
3188
+ const own = (names, base) => {
3189
+ names.forEach((name, index) => {
3190
+ found.push({
3191
+ pointer: `${base}/${index}`,
3192
+ name,
3193
+ role: "customTable.column"
3194
+ });
3195
+ });
3196
+ };
3197
+ if (table.scopeColumn !== void 0) found.push({
3198
+ pointer: "/scopeColumn",
3199
+ name: table.scopeColumn,
3200
+ role: "customTable.scopeColumn"
3201
+ });
3202
+ if (table.primaryKey !== void 0) own(table.primaryKey.columns, "/primaryKey/columns");
3203
+ table.uniques.forEach((unique, i) => {
3204
+ own(unique.columns, `/uniques/${i}/columns`);
3205
+ });
3206
+ table.foreignKeys.forEach((foreignKey, i) => {
3207
+ const base = `/foreignKeys/${i}`;
3208
+ own(foreignKey.columns, `${base}/columns`);
3209
+ const { references } = foreignKey;
3210
+ if ("object" in references) references.columns.forEach((name, index) => {
3211
+ found.push({
3212
+ pointer: `${base}/references/columns/${index}`,
3213
+ name,
3214
+ owner: references.object,
3215
+ role: "customTable.foreignKeyTarget"
3216
+ });
3217
+ });
3218
+ });
3219
+ table.indexes.forEach((index, i) => {
3220
+ index.keys.forEach((key, k) => {
3221
+ if ("column" in key) found.push({
3222
+ pointer: `/indexes/${i}/keys/${k}/column`,
3223
+ name: key.column,
3224
+ role: "customTable.column"
3225
+ });
3226
+ });
3227
+ own(index.include, `/indexes/${i}/include`);
3228
+ });
3229
+ return found;
3230
+ }
3231
+ /** Скалярна колонка типу uuid: логічного `UUID` або `Raw` з `pgType` uuid. */
3232
+ function isUuidColumn(column) {
3233
+ return column.array !== true && (column.type === "UUID" || column.type === "Raw" && column.pgType?.toLowerCase() === "uuid");
3234
+ }
3235
+ /**
3236
+ * Колонка єдиного PK прийнятої таблиці, якщо вона скалярна uuid. Не залежить
3237
+ * від `physicalName`, тож придатна й до призначення фізичних імен.
3238
+ */
3239
+ function singleUuidKeyColumn(table) {
3240
+ const key = table.primaryKey?.columns;
3241
+ if (key?.length !== 1) return void 0;
3242
+ const column = table.columns.find((c) => c.name === key[0]);
3243
+ return column !== void 0 && isUuidColumn(column) ? column : void 0;
3244
+ }
3245
+ /**
3246
+ * Прийнята таблиця описана повністю фізично: нічого похідного, тож
3247
+ * стандартних колонок немає (спека §4).
3248
+ */
3249
+ const customTableKind = {
3250
+ kind: "CustomTable",
3251
+ dir: "custom-tables",
3252
+ schema: customTableSchema,
3253
+ keyOrder: keyOrderOf(customTableSchema),
3254
+ referenceable: true,
3255
+ writePattern: "optimistic",
3256
+ actions: () => [
3257
+ readAction,
3258
+ createAction(false),
3259
+ updateAction(false),
3260
+ deleteAction
3261
+ ],
3262
+ rightsExtents: [],
3263
+ sqlModule: "debt",
3264
+ materializes: "table",
3265
+ scope: "required",
3266
+ declared: true,
3267
+ kindLabel: true,
3268
+ columnFields: ["columns"],
3269
+ valueElements: false,
3270
+ standardColumns: () => [],
3271
+ references,
3272
+ elementReferences
3273
+ };
3274
+ //#endregion
3275
+ //#region src/model/kinds/document.ts
3276
+ const periodUnits = {
3277
+ Year: "year",
3278
+ Quarter: "quarter",
3279
+ Month: "month",
3280
+ Day: "day"
3281
+ };
3282
+ function numbering(obj) {
3283
+ const document = obj;
3284
+ return {
3285
+ column: "number",
3286
+ ...document.numberPeriodicity === "None" ? {} : { periodColumn: "numberPeriod" },
3287
+ type: document.numberType,
3288
+ length: document.numberLength,
3289
+ autonumber: document.autonumber,
3290
+ periodicity: document.numberPeriodicity,
3291
+ unique: true
3292
+ };
3293
+ }
3294
+ function standardColumns$1(obj) {
3295
+ const document = obj;
3296
+ return [
3297
+ keyColumn(true),
3298
+ {
3299
+ logicalName: "number",
3300
+ physicalName: "number",
3301
+ type: numberingType(document.numberType, document.numberLength),
3302
+ notNull: false,
3303
+ title: {
3304
+ uk: "Номер",
3305
+ en: "Number"
3306
+ }
3307
+ },
3308
+ {
3309
+ logicalName: "date",
3310
+ physicalName: "date",
3311
+ type: { type: "DateTime" },
3312
+ notNull: true,
3313
+ indexed: true,
3314
+ title: {
3315
+ uk: "Дата",
3316
+ en: "Date"
3317
+ }
3318
+ },
3319
+ ...document.numberPeriodicity === "None" ? [] : [{
3320
+ logicalName: "numberPeriod",
3321
+ physicalName: "number_period",
3322
+ type: { type: "Date" },
3323
+ notNull: true,
3324
+ generated: { truncate: {
3325
+ column: "date",
3326
+ unit: periodUnits[document.numberPeriodicity]
3327
+ } },
3328
+ title: {
3329
+ uk: "Період номера",
3330
+ en: "Number period"
3331
+ }
3332
+ }],
3333
+ {
3334
+ logicalName: "posted",
3335
+ physicalName: "posted",
3336
+ type: { type: "Boolean" },
3337
+ notNull: true,
3338
+ default: "false",
3339
+ title: {
3340
+ uk: "Проведений",
3341
+ en: "Posted"
3342
+ }
3343
+ },
3344
+ deletionMarkColumn(),
3345
+ versionColumn(),
3346
+ ...serviceDateColumns(),
3347
+ ...document.trackAuthor ? authorColumns() : []
3348
+ ];
3349
+ }
3350
+ function postingReferences(document) {
3351
+ if (document.posting === void 0) return [];
3352
+ return [...document.posting.movements.map((movement, index) => ({
3353
+ pointer: `/posting/movements/${index}/register`,
3354
+ ref: movement.register,
3355
+ role: "posting.register",
3356
+ pair: false,
3357
+ polymorphic: false
3358
+ }))];
3359
+ }
3360
+ const documentKind = {
3361
+ kind: "Document",
3362
+ dir: "documents",
3363
+ schema: documentSchema,
3364
+ keyOrder: keyOrderOf(documentSchema),
3365
+ referenceable: true,
3366
+ compositeIndexes: true,
3367
+ writePattern: "server",
3368
+ actions: () => [
3369
+ ...recordActions(documentKind.tabularSectionColumns !== void 0),
3370
+ postAction,
3371
+ unpostAction
3372
+ ],
3373
+ rightsExtents: [
3374
+ "any",
3375
+ "own",
3376
+ "dimension"
3377
+ ],
3378
+ rightsBinding: true,
3379
+ sqlModule: "closed",
3380
+ materializes: "table",
3381
+ rowLevelSecurity: "enabled",
3382
+ authorTracking: true,
3383
+ scope: "required",
3384
+ declared: false,
3385
+ kindLabel: true,
3386
+ requiredOnPost: true,
3387
+ columnFields: ["attributes"],
3388
+ idElementFields: ["customActions"],
3389
+ valueElements: false,
3390
+ standardColumns: standardColumns$1,
3391
+ numbering,
3392
+ tabularSectionColumns: () => tabularRowColumns(true),
3393
+ elementReferences: (obj) => [
3394
+ ...customActionReferences(obj),
3395
+ ...ownershipReferences(obj, standardColumns$1(obj)),
3396
+ ...bindingReferences(obj, standardColumns$1(obj)),
3397
+ ...accessReferences(obj, standardColumns$1(obj))
3398
+ ],
3399
+ projectReferences: (obj) => accessDimensionReferences(obj),
3400
+ references(obj) {
3401
+ const document = obj;
3402
+ return [
3403
+ ...objectFieldReferences(document),
3404
+ ...refListReferences(document.registerMovements, "/registerMovements", "document.registerMovement", false),
3405
+ ...postingReferences(document)
3406
+ ];
3407
+ }
3408
+ };
3409
+ //#endregion
3410
+ //#region src/model/kinds/enumeration.ts
3411
+ /**
3412
+ * Значення перерахування — метадані, а не рядки: таблиці немає, посилання на
3413
+ * нього фізично — text із CHECK за мітками (спека §5, М15).
3414
+ */
3415
+ const enumerationKind = {
3416
+ kind: "Enumeration",
3417
+ dir: "enumerations",
3418
+ schema: enumerationSchema,
3419
+ keyOrder: keyOrderOf(enumerationSchema),
3420
+ referenceable: true,
3421
+ writePattern: "none",
3422
+ actions: () => [],
3423
+ rightsExtents: [],
3424
+ sqlModule: "closed",
3425
+ materializes: "none",
3426
+ scope: "noneOnly",
3427
+ declared: false,
3428
+ columnFields: [],
3429
+ valueElements: true,
3430
+ standardColumns: () => [],
3431
+ references: () => []
3432
+ };
3433
+ //#endregion
3434
+ //#region src/model/kinds/event-subscription.ts
3435
+ function subscriptionOf(obj) {
3436
+ const data = obj;
3437
+ return {
3438
+ sources: data.sources.map((source, index) => {
3439
+ const pointer = `/sources/${index}`;
3440
+ if ("providerTable" in source) {
3441
+ const [schema, table] = source.providerTable.split(".");
3442
+ return {
3443
+ pointer,
3444
+ providerTable: {
3445
+ schema,
3446
+ table
3447
+ }
3448
+ };
3449
+ }
3450
+ return {
3451
+ pointer,
3452
+ ref: source
3453
+ };
3454
+ }),
3455
+ event: data.event,
3456
+ ...data.whenChanged === void 0 ? {} : { whenChanged: data.whenChanged },
3457
+ handler: {
3458
+ ...data.handler.schema === void 0 ? {} : { schema: data.handler.schema },
3459
+ name: data.handler.name
3460
+ }
3461
+ };
3462
+ }
3463
+ /**
3464
+ * Підписка на подію — вид без сховища, як перерахування (спека промоції
3465
+ * §9.3): таблиці й значень немає, на неї не посилаються. Джерела-об'єкти —
3466
+ * посилання індексу, тож перейменування й видалення джерела бачать її даром.
3467
+ */
3468
+ const eventSubscriptionKind = {
3469
+ kind: "EventSubscription",
3470
+ dir: "event-subscriptions",
3471
+ schema: eventSubscriptionSchema,
3472
+ keyOrder: keyOrderOf(eventSubscriptionSchema),
3473
+ referenceable: false,
3474
+ writePattern: "none",
3475
+ actions: () => [],
3476
+ rightsExtents: [],
3477
+ sqlModule: "closed",
3478
+ materializes: "none",
3479
+ scope: "absent",
3480
+ declared: false,
3481
+ columnFields: [],
3482
+ valueElements: false,
3483
+ standardColumns: () => [],
3484
+ references: (obj) => subscriptionOf(obj).sources.flatMap((source) => "ref" in source ? [{
3485
+ pointer: source.pointer,
3486
+ ref: source.ref,
3487
+ role: "eventSubscription.source",
3488
+ pair: false,
3489
+ polymorphic: false
3490
+ }] : []),
3491
+ subscription: subscriptionOf
3492
+ };
3493
+ //#endregion
3494
+ //#region src/model/kinds/information-register.ts
3495
+ function standardColumns(obj) {
3496
+ const register = obj;
3497
+ return [...register.periodicity !== "NonPeriodic" ? [periodColumn()] : [], ...register.writeMode === "RecorderSubordinate" ? recorderColumns() : []];
3498
+ }
3499
+ const informationRegisterKind = {
3500
+ kind: "InformationRegister",
3501
+ dir: "information-registers",
3502
+ schema: informationRegisterSchema,
3503
+ keyOrder: keyOrderOf(informationRegisterSchema),
3504
+ referenceable: false,
3505
+ writePattern: "server",
3506
+ actions: (obj) => obj.writeMode === "Independent" ? [readAction, writeAction] : [readAction],
3507
+ rightsExtents: ["any", "dimension"],
3508
+ sqlModule: "closed",
3509
+ materializes: "table",
3510
+ rowLevelSecurity: "enabled",
3511
+ scope: "required",
3512
+ declared: false,
3513
+ kindLabel: true,
3514
+ columnFields: [
3515
+ "dimensions",
3516
+ "resources",
3517
+ "attributes"
3518
+ ],
3519
+ idElementFields: ["customActions"],
3520
+ valueElements: false,
3521
+ standardColumns,
3522
+ registerKeys(obj) {
3523
+ return {
3524
+ movementsPrimaryKey: obj.writeMode === "RecorderSubordinate" ? "recorder" : "none",
3525
+ recordKeyUnique: true,
3526
+ movementIndexes: false,
3527
+ totals: false,
3528
+ additiveResources: false,
3529
+ virtualTables: obj.periodicity === "NonPeriodic" ? [] : ["sliceLast", "sliceFirst"]
3530
+ };
3531
+ },
3532
+ elementReferences: (obj) => [...customActionReferences(obj), ...accessReferences(registerCarrierHost(obj), standardColumns(obj))],
3533
+ projectReferences: (obj) => accessDimensionReferences(obj),
3534
+ references(obj) {
3535
+ const register = obj;
3536
+ return [
3537
+ ...standardRefReferences(standardColumns(register), "recorders", register.recorderTypes, "/recorderTypes", "register.recorder"),
3538
+ ...fieldListReferences(register.dimensions, "/dimensions"),
3539
+ ...fieldListReferences(register.resources, "/resources"),
3540
+ ...fieldListReferences(register.attributes, "/attributes")
3541
+ ];
3542
+ }
3543
+ };
3544
+ //#endregion
3545
+ //#region src/model/kinds/pg-enum.ts
3546
+ /**
3547
+ * Прийнятий енам-тип Postgres. На нього посилається лише колонка
3548
+ * `CustomTable`, тож загальним посиланням `Ref` він недоступний.
3549
+ */
3550
+ const pgEnumKind = {
3551
+ kind: "PgEnum",
3552
+ dir: "pg-enums",
3553
+ schema: pgEnumSchema,
3554
+ keyOrder: keyOrderOf(pgEnumSchema),
3555
+ referenceable: false,
3556
+ writePattern: "none",
3557
+ actions: () => [],
3558
+ rightsExtents: [],
3559
+ sqlModule: "debt",
3560
+ materializes: "enumType",
3561
+ scope: "absent",
3562
+ declared: true,
3563
+ columnFields: [],
3564
+ valueElements: false,
3565
+ standardColumns: () => [],
3566
+ references: () => []
3567
+ };
3568
+ //#endregion
3569
+ //#region src/model/kinds/rights-set.ts
3570
+ /**
3571
+ * Включені набори — посилання індексу: перейменування набору переписує
3572
+ * `include`, а видалення включеного набору бачить індекс.
3573
+ */
3574
+ function includeReferences(include) {
3575
+ return include.map((ref, index) => ({
3576
+ pointer: `/include/${index}`,
3577
+ ref,
3578
+ role: "rights.include",
3579
+ pair: false,
3580
+ polymorphic: false
3581
+ }));
3582
+ }
3583
+ /**
3584
+ * Об'єкти явного переліку гранту — посилання індексу: перейменування об'єкта
3585
+ * переписує грант, а видалення об'єкта, на який грант посилається, бачить
3586
+ * індекс. Селектор `withAction` об'єктів не називає.
3587
+ */
3588
+ function grantReferences(grants) {
3589
+ return grants.flatMap((entry, index) => {
3590
+ const { form, body } = grantEntryForm(entry);
3591
+ if (!("objects" in body) || !Array.isArray(body.objects)) return [];
3592
+ return body.objects.map((ref, at) => ({
3593
+ pointer: `/grants/${index}/${form}/objects/${at}`,
3594
+ ref,
3595
+ role: "grant.object",
3596
+ pair: false,
3597
+ polymorphic: false
3598
+ }));
3599
+ });
3600
+ }
3601
+ /** Вимір обсягу гранту — елемент проєкту: перейменування виміру переписує грант. */
3602
+ function grantProjectReferences(grants) {
3603
+ return grants.flatMap((entry, index) => {
3604
+ const { form, body } = grantEntryForm(entry);
3605
+ const { extent } = body;
3606
+ if (typeof extent !== "object") return [];
3607
+ return [{
3608
+ pointer: `/grants/${index}/${form}/extent/dimension`,
3609
+ name: extent.dimension,
3610
+ collection: "accessDimensions",
3611
+ role: "grant.dimension"
3612
+ }];
3613
+ });
3614
+ }
3615
+ /**
3616
+ * Спільні факти декларацій прав (спека прав §4.1): вид без сховища, як
3617
+ * підписка на подію, але й без фізичного імені (Р1b-9) — у базі їх видно лише
3618
+ * в згенерованій проєкції, а в даних — за UUID.
3619
+ */
3620
+ const rightsDeclarationFacts = {
3621
+ referenceable: false,
3622
+ writePattern: "none",
3623
+ actions: () => [],
3624
+ rightsExtents: [],
3625
+ sqlModule: "closed",
3626
+ materializes: "none",
3627
+ scope: "absent",
3628
+ declared: false,
3629
+ physicalName: false,
3630
+ columnFields: [],
3631
+ valueElements: false,
3632
+ standardColumns: () => []
3633
+ };
3634
+ //#endregion
3635
+ //#region src/model/kinds/registry.ts
3636
+ /**
3637
+ * Єдине місце знань про вид (спека П2 §8.1): кожне розгалуження за видом
3638
+ * читає цей запис, а новий вид — це новий запис плюс тести. Порядок ключів —
3639
+ * порядок METADATA_KINDS.
3640
+ */
3641
+ const KIND_REGISTRY = {
3642
+ Catalog: catalogKind,
3643
+ Document: documentKind,
3644
+ Enumeration: enumerationKind,
3645
+ InformationRegister: informationRegisterKind,
3646
+ AccumulationRegister: accumulationRegisterKind,
3647
+ Constant: constantKind,
3648
+ CustomTable: customTableKind,
3649
+ PgEnum: pgEnumKind,
3650
+ EventSubscription: eventSubscriptionKind,
3651
+ RightsSet: {
3652
+ ...rightsDeclarationFacts,
3653
+ kind: "RightsSet",
3654
+ dir: "rights-sets",
3655
+ schema: rightsSetSchema,
3656
+ keyOrder: keyOrderOf(rightsSetSchema),
3657
+ rightsDeclaration: "set",
3658
+ references: (obj) => {
3659
+ const set = obj;
3660
+ return [...includeReferences(set.include), ...grantReferences(set.grants)];
3661
+ },
3662
+ projectReferences: (obj) => grantProjectReferences(obj.grants)
3663
+ },
3664
+ Role: {
3665
+ ...rightsDeclarationFacts,
3666
+ kind: "Role",
3667
+ dir: "roles",
3668
+ schema: roleSchema,
3669
+ keyOrder: keyOrderOf(roleSchema),
3670
+ rightsDeclaration: "role",
3671
+ references: (obj) => {
3672
+ const role = obj;
3673
+ const level = role.assignedOn;
3674
+ const container = typeof level === "object" && "container" in level ? [{
3675
+ pointer: "/assignedOn/container",
3676
+ ref: level.container,
3677
+ role: "role.container",
3678
+ pair: false,
3679
+ polymorphic: false
3680
+ }] : [];
3681
+ return [
3682
+ ...includeReferences(role.include),
3683
+ ...container,
3684
+ ...grantReferences(role.grants)
3685
+ ];
3686
+ },
3687
+ projectReferences: (obj) => {
3688
+ const role = obj;
3689
+ const level = role.assignedOn;
3690
+ return [
3691
+ ...typeof level === "object" && "scopeKind" in level ? [{
3692
+ pointer: "/assignedOn/scopeKind",
3693
+ name: level.scopeKind,
3694
+ collection: "scopeKinds",
3695
+ role: "role.scopeKind"
3696
+ }] : [],
3697
+ ...role.sourceKeys.map((entry, index) => ({
3698
+ pointer: `/sourceKeys/${index}/source`,
3699
+ name: entry.source,
3700
+ collection: "assignmentSources",
3701
+ role: "role.sourceKey"
3702
+ })),
3703
+ ...grantProjectReferences(role.grants)
3704
+ ];
3705
+ }
3706
+ }
3707
+ };
3708
+ const KINDS_BY_DIR = new Map(Object.values(KIND_REGISTRY).map((def) => [def.dir, def]));
3709
+ /** Вид за текою `metadata/<тека>/`: тека задає очікуваний вид файлу. */
3710
+ function kindByDir(dir) {
3711
+ return KINDS_BY_DIR.get(dir);
3712
+ }
3713
+ /** Дія виду, що пише рухи: документ, який проводиться. */
3714
+ const POST_ACTION = "post";
3715
+ /**
3716
+ * Чи вид проводиться (пише рухи в регістри). Факт реєстру, що його читають і
3717
+ * перевірка реєстратора, і розбір `.sql`, тож назви дії ніхто не дублює.
3718
+ */
3719
+ function postsMovements(kind, obj) {
3720
+ return KIND_REGISTRY[kind].actions(obj).some((action) => action.name === POST_ACTION);
3721
+ }
3722
+ /**
3723
+ * Чи очікується в об'єкта мітка виду: вид її має (факт реєстру), а прийнята
3724
+ * таблиця — лише з єдиним uuid-ключем, бо без нього на неї не посилається
3725
+ * жодна `Ref`-пара й мітці нема що розрізняти.
3726
+ */
3727
+ function expectsKindLabel(kind, data) {
3728
+ const def = KIND_REGISTRY[kind];
3729
+ if (def.kindLabel !== true) return false;
3730
+ if (!def.declared) return true;
3731
+ const table = data;
3732
+ return Array.isArray(table.columns) && singleUuidKeyColumn(table) !== void 0;
3733
+ }
3734
+ //#endregion
3735
+ //#region src/model/format.ts
3736
+ /** Ключі project.meta.json — у порядку оголошення схеми проєкту. */
3737
+ const PROJECT_KEY_ORDER = Object.keys(projectSchema.shape);
3738
+ const defOf = (schema) => schema.def;
3739
+ /** Знімає обгортки, що не змінюють форму об'єкта (optional, default, pipe…). */
3740
+ function unwrap(schema) {
3741
+ let current = schema;
3742
+ for (;;) {
3743
+ const def = defOf(current);
3744
+ if (def.innerType !== void 0) current = def.innerType;
3745
+ else if (def.type === "pipe" && def.in !== void 0) current = def.in;
3746
+ else if (def.type === "lazy" && def.getter !== void 0) current = def.getter();
3747
+ else return current;
3748
+ }
3749
+ }
3750
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3751
+ /**
3752
+ * Варіант union, до якого належить об'єкт: за дискримінатором, інакше перший
3753
+ * варіант, чия схема приймає об'єкт. Файл із помилкою не приймає жоден
3754
+ * варіант — тоді береться варіант із найбільшим збігом ключів (за рівності —
3755
+ * перший), щоб порядок лишався детермінованим, а помилку показала валідація.
3756
+ */
3757
+ function pickVariant(options, discriminator, value) {
3758
+ const unwrapped = options.map(unwrap);
3759
+ if (discriminator !== void 0) {
3760
+ const byTag = unwrapped.find((option) => {
3761
+ const field = defOf(option).shape?.[discriminator];
3762
+ return field !== void 0 && field.safeParse(value[discriminator]).success;
3763
+ });
3764
+ if (byTag !== void 0) return byTag;
3765
+ }
3766
+ const accepting = options.find((option) => option.safeParse(value).success);
3767
+ if (accepting !== void 0) return unwrap(accepting);
3768
+ let best;
3769
+ let bestScore = -1;
3770
+ for (const option of unwrapped) {
3771
+ const shape = defOf(option).shape;
3772
+ const score = shape === void 0 ? 0 : Object.keys(value).filter((key) => Object.hasOwn(shape, key)).length;
3773
+ if (score > bestScore) {
3774
+ best = option;
3775
+ bestScore = score;
3776
+ }
3777
+ }
3778
+ return best;
3779
+ }
3780
+ /**
3781
+ * Канонічна форма значення на кожному рівні: ключі об'єкта — у порядку
3782
+ * оголошення його схеми, елементи масивів і значення `record` обходяться
3783
+ * тією ж схемою. Ключі `record` лишаються у вхідному порядку — це дані
3784
+ * автора (поля руху, перевизначення), а не частина схеми. Невідомі ключі не
3785
+ * губляться — вони йдуть після відомих у вхідному порядку, щоб форматер не
3786
+ * маскував помилку, яку покаже валідація. `topKeyOrder` — порядок верхнього
3787
+ * рівня з реєстру видів (шапка першою), решта виводиться зі схеми.
3788
+ */
3789
+ function canonicalize(value, schema, topKeyOrder) {
3790
+ if (schema === void 0) return value;
3791
+ const node = unwrap(schema);
3792
+ const def = defOf(node);
3793
+ if (Array.isArray(value)) {
3794
+ const element = def.type === "array" ? def.element : void 0;
3795
+ return value.map((item) => canonicalize(item, element));
3796
+ }
3797
+ if (!isPlainObject(value)) return value;
3798
+ if (def.type === "union") return canonicalize(value, pickVariant(def.options ?? [], def.discriminator, value), topKeyOrder);
3799
+ if (def.type === "record") {
3800
+ const result = {};
3801
+ for (const [key, item] of Object.entries(value)) result[key] = canonicalize(item, def.valueType);
3802
+ return result;
3803
+ }
3804
+ if (def.type !== "object" || def.shape === void 0) return value;
3805
+ const shape = def.shape;
3806
+ const keyOrder = topKeyOrder ?? Object.keys(shape);
3807
+ const ordered = {};
3808
+ for (const key of keyOrder) if (Object.hasOwn(value, key)) ordered[key] = canonicalize(value[key], shape[key]);
3809
+ for (const [key, item] of Object.entries(value)) if (!Object.hasOwn(ordered, key)) ordered[key] = item;
3810
+ return ordered;
3811
+ }
3812
+ function serialize(data) {
3813
+ return `${JSON.stringify(data, null, 2)}\n`;
3814
+ }
3815
+ function isKnownKind(kind) {
3816
+ return typeof kind === "string" && Object.hasOwn(KIND_REGISTRY, kind);
3817
+ }
3818
+ /**
3819
+ * Канонічна форма файлу `.meta.json` (спека П2 §3): порядок ключів за схемою
3820
+ * виду на всіх рівнях,
3821
+ * відступ у два пробіли, завершальний перевід рядка. Файл невідомого виду
3822
+ * лишається в порядку входу — вид відхилить стадія 1, а не форматер.
3823
+ */
3824
+ function formatMetaFile(data) {
3825
+ if (!isKnownKind(data.kind)) return serialize(data);
3826
+ const def = KIND_REGISTRY[data.kind];
3827
+ return serialize(canonicalize(data, def.schema, def.keyOrder));
3828
+ }
3829
+ /** Канонічна форма `project.meta.json`. */
3830
+ function formatProjectFile(data) {
3831
+ return serialize(canonicalize(data, projectSchema, PROJECT_KEY_ORDER));
3832
+ }
3833
+ /**
3834
+ * Канонічна форма `sql-debt.json`: `$schema` першим, перелік відсортований за
3835
+ * кодовими одиницями й без дублів — так його пишуть і `introspect`, і `fix`,
3836
+ * і diff переліку показує лише зміну боргу.
3837
+ */
3838
+ function formatSqlDebtFile(debt) {
3839
+ const units = [...new Set(debt.units)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3840
+ return serialize({
3841
+ ...debt.$schema === void 0 ? {} : { $schema: debt.$schema },
3842
+ units
3843
+ });
3844
+ }
3845
+ /** Сегменти JSON Pointer (RFC 6901) без екранування `~1`/`~0`. */
3846
+ function pointerSegments(pointer) {
3847
+ return pointer.split("/").slice(1).map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
3848
+ }
3849
+ /**
3850
+ * Чи останній крок pointer — ключ `record`, а не поле схеми чи індекс масиву.
3851
+ * Ключ `record` — дані автора (поля руху називають поля регістра), тож місце
3852
+ * за таким pointer — сам ключ: його перейменовують, а не значення під ним.
3853
+ * Варіант union обирається за даними, як і в канонічній формі.
3854
+ */
3855
+ function isRecordKeyAt(schema, data, pointer) {
3856
+ const segments = pointerSegments(pointer);
3857
+ let node = schema;
3858
+ let value = data;
3859
+ for (const [index, segment] of segments.entries()) {
3860
+ if (node === void 0) return false;
3861
+ let current = unwrap(node);
3862
+ while (defOf(current).type === "union") {
3863
+ const def = defOf(current);
3864
+ const options = def.options ?? [];
3865
+ const variant = isPlainObject(value) ? pickVariant(options, def.discriminator, value) : options.find((option) => option.safeParse(value).success);
3866
+ if (variant === void 0) return false;
3867
+ current = unwrap(variant);
3868
+ }
3869
+ const def = defOf(current);
3870
+ if (def.type === "record") {
3871
+ if (index === segments.length - 1) return true;
3872
+ node = def.valueType;
3873
+ } else if (def.type === "object") node = def.shape?.[segment];
3874
+ else if (def.type === "array") node = def.element;
3875
+ else return false;
3876
+ value = isPlainObject(value) || Array.isArray(value) ? value[segment] : void 0;
3877
+ }
3878
+ return false;
3879
+ }
3880
+ //#endregion
3881
+ //#region src/model/named-elements.ts
3882
+ /**
3883
+ * Масиви іменованих елементів схеми (спека П2 §3): елемент — об'єкт з `id` і
3884
+ * `name`. Ключ масиву → схема елемента, у порядку оголошення схеми. Факт
3885
+ * виводиться зі схеми, а не з переліку: новий вид чи нова колекція приходять
3886
+ * разом зі своєю схемою, а операції (додавання, адресація) бачать їх одразу.
3887
+ */
3888
+ function namedCollections(schema) {
3889
+ const result = /* @__PURE__ */ new Map();
3890
+ const node = unwrap(schema);
3891
+ if (node.def.type !== "object") return result;
3892
+ const shape = node.shape;
3893
+ for (const [key, field] of Object.entries(shape)) {
3894
+ const array = unwrap(field);
3895
+ if (array.def.type !== "array") continue;
3896
+ const element = unwrap(array.element);
3897
+ if (element.def.type !== "object") continue;
3898
+ const keys = element.shape;
3899
+ if (Object.hasOwn(keys, "id") && Object.hasOwn(keys, "name")) result.set(key, element);
3900
+ }
3901
+ return result;
3902
+ }
3903
+ const isRecord = (value) => typeof value === "object" && value !== null;
3904
+ /**
3905
+ * Рівень ролі як ефективне значення: `global`/`everyUser` як є, вид скоупу й
3906
+ * контейнер — за `id`, щоб перейменування не було зміною рівня. Нерозв'язане
3907
+ * ім'я лишається іменем (`scope?:`/`container?:`), тож його зміна видна.
3908
+ */
3909
+ function effectiveAssignedOn(raw, ctx) {
3910
+ const level = raw.assignedOn;
3911
+ if (typeof level === "string") return level;
3912
+ if (!isRecord(level)) return void 0;
3913
+ if (typeof level.scopeKind === "string") {
3914
+ const id = ctx.resolveScopeKind(level.scopeKind);
3915
+ return id === void 0 ? `scope?:${level.scopeKind}` : `scope:${id}`;
3916
+ }
3917
+ const target = level.container;
3918
+ if (isRecord(target) && typeof target.kind === "string" && typeof target.name === "string") {
3919
+ const id = ctx.resolveObject({
3920
+ kind: target.kind,
3921
+ name: target.name
3922
+ });
3923
+ return id === void 0 ? `container?:${target.kind}:${target.name}` : `container:${id}`;
3924
+ }
3925
+ }
3926
+ const ASSIGNED_ONCE = [
3927
+ {
3928
+ on: "object",
3929
+ field: "physicalName"
3930
+ },
3931
+ {
3932
+ on: "object",
3933
+ field: "kindLabel"
3934
+ },
3935
+ {
3936
+ on: "object",
3937
+ field: "schema",
3938
+ effective: (raw, ctx) => ctx.materializes ? raw.schema ?? ctx.defaultSchema : void 0
3939
+ },
3940
+ {
3941
+ on: "element",
3942
+ field: "physicalName"
3943
+ },
3944
+ {
3945
+ on: "object",
3946
+ field: "assignedOn",
3947
+ effective: effectiveAssignedOn
3948
+ }
3949
+ ];
3950
+ //#endregion
3951
+ export { ASSIGNED_ONCE, ATTRIBUTE_CASES, DATABASE_PROVIDERS, DELETE_EVENTS, KIND_REGISTRY, LOGICAL_TYPES, MAX_PHYSICAL_NAME_BYTES, MEMBERSHIP_SET_FUNCTION, METADATA_KINDS, NO_SCOPE, PLATFORM_SCHEMA, PROJECT_KEY_ORDER, PROVIDER_API_ROLES, PROVIDER_EVENT_SOURCES, PROVIDER_IDENTITY_SOURCES, PUBLIC_READ_PURPOSES, PUBLIC_READ_ROLES, SCHEMA_RULES, SQL_DEBT_FILE, SQL_UNIT_CLASSES, STANDARD_ACTIONS, SUBSCRIPTION_EVENTS, accessDimensionSchema, accessMappingSchema, accessSchema, accumulationRegisterSchema, actionRequires, appSchemaNameSchema, assignPhysicalName, assignedOnSchema, assignmentSourceSchema, attributeSchema, catalogAttributeSchema, catalogFromSnapshot, catalogSchema, chooseConstraintName, closeRequires, compositeIndexesSchema, constantSchema, customActionSchema, customActionsSchema, customTableColumnSchema, customTableSchema, defaultMayRepeat, defaultViolatesValueChecks, diffCatalogModels, documentSchema, elementNameSchema, enumValueSchema, enumerationSchema, eventSubscriptionSchema, expectsKindLabel, extentSchema, formatMetaFile, formatProjectFile, formatSqlDebtFile, grantEntryForm, grantEntrySchema, informationRegisterSchema, isRecordKeyAt, isScalarDefault, isSqlReservedWord, isUuidColumn, kindByDir, localizedStringSchema, logicalElementName, logicalObjectName, logicalTypeOf, makeObjectName, matchesAttributeCase, membershipSourceSchema, metadataIdSchema, metadataKindSchema, metadataRefSchema, monthColumn, namedCollections, objectHeaderShape, objectNameSchema, objectSelectorSchema, ownershipSchema, parseExpression, pgEnumSchema, pgEnumTypeName, pgTypeOf, physicalNameSchema, postsMovements, projectSchema, publicReadSchema, quoteIdent, refineValueType, resourceSchema, rightsCarrierSchema, rightsSetSchema, roleAssignedOnSchema, roleSchema, scopeKindSchema, serviceDateColumns, setGrantEntrySchema, singleUuidKeyColumn, singletonColumn, sqlDebtSchema, standardAttributeOverridesSchema, standardLogicalName, tabularSectionSchema, toSnakeCase, truncatedPeriodExpression, valueTypeShape, versionColumn, walkExpr };