@agentic-kit/db-tools 0.12.46 → 0.13.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.
Files changed (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
@@ -0,0 +1,116 @@
1
+ import { type PlanAccessState, type PlanColumn, type PlanRule, type PlanTableAccess, type ToolCallSuggestion } from '@agentic-kit/harness';
2
+ import type { BlueprintPolicy } from 'node-type-registry';
3
+ import { type TableAccessInput, type TableField, type TablePolicy } from './access';
4
+ import type { ProjectContext } from './context';
5
+ import { type FailureMeaning, type Result } from './failure';
6
+ export type SchemaField = {
7
+ name: string;
8
+ type: string;
9
+ isRequired: boolean;
10
+ defaultValue: string | null;
11
+ };
12
+ /** One access rule of a table: the policy rows that differ only by privilege, as one. */
13
+ export type SchemaPolicy = {
14
+ type: string;
15
+ privileges: string[];
16
+ /** False for a restrictive rule, which every row must also pass. */
17
+ permissive: boolean;
18
+ role: string;
19
+ data: Record<string, unknown>;
20
+ disabled?: true;
21
+ /** UPDATE only: the rule a changed row must pass instead of this one, as the backend stores it. */
22
+ withCheck?: {
23
+ type: string;
24
+ data: Record<string, unknown>;
25
+ };
26
+ };
27
+ export type TableGrants = NonNullable<TableAccessInput['grants']>;
28
+ export type TableRecord = {
29
+ id: string;
30
+ name: string;
31
+ fields: SchemaField[];
32
+ policyRules: SchemaPolicy[];
33
+ /** The names of its policy rows: PostgreSQL keeps a policy name unique per table. */
34
+ policyNames: string[];
35
+ grants: TableGrants;
36
+ rlsEnabled: boolean;
37
+ };
38
+ /** A canonical JSON text, so two rules with the same data in another key order are one rule. */
39
+ export declare const canonical: (value: unknown) => string;
40
+ /** The application tables of the bound database (every one, or those named), with all their access parts. */
41
+ export declare function readTables(context: ProjectContext, names?: string[], schemaId?: string): Promise<Result<TableRecord[]>>;
42
+ /** One table of the bound database by name, or `not-found` naming the call that lists them. */
43
+ export declare function readTable(context: ProjectContext, name: string): Promise<Result<TableRecord>>;
44
+ /** A stored field default as the SQL it stands for (`now()`, `0`), or as stored when this tool cannot read it. */
45
+ export declare function defaultText(value: string | null): string;
46
+ /** A column as the registry reads it: its default decides, for example, whose team a new row names. */
47
+ export declare const tableField: (field: SchemaField) => TableField;
48
+ /**
49
+ * What the registry reads for one live table: every policy (a role of
50
+ * `public` counts for every role) with its WITH CHECK override, the grants,
51
+ * the row-security state and the columns. A disabled policy does not apply,
52
+ * so it is left out.
53
+ */
54
+ export declare function accessInputOf(table: TableRecord): TableAccessInput;
55
+ /** One rule in plain words, with the related columns the reader read; a rule the words cannot describe says so instead. */
56
+ export declare function ruleWords(type: string, data: Record<string, unknown>, related?: TableAccessInput['related']): string;
57
+ /** A stored rule in the shape a caller writes one, so a rule that is read can be written back. */
58
+ export type WrittenRule = Omit<BlueprintPolicy, 'policy_name'> & Required<Pick<BlueprintPolicy, 'privileges' | 'permissive' | 'policy_role' | 'data'>>;
59
+ /**
60
+ * A stored rule as every read returns it: the keys a caller writes (`$type`, `privileges`, `permissive`,
61
+ * `policy_role`, `data`, and `with_check` for an update rule with its own check), with each key the closed
62
+ * parameter_schema marks readOnly left out, so no read carries a part the closed world refuses.
63
+ */
64
+ export declare function asWritten(policy: TablePolicy): WrittenRule;
65
+ /** One rule as a plan names it, under the keys a caller writes: its own sentence, and for an update rule with its own check of the changed row, that one too. */
66
+ export declare function planRule(policy: TablePolicy, related?: TableAccessInput['related']): PlanRule;
67
+ /** A table's grants in words, one entry per role: "select, insert, update and delete to authenticated", "update (title) to editor". */
68
+ export declare function grantWords(grants: TableAccessInput['grants']): string[];
69
+ /** A table's access at one moment, as a plan names it. */
70
+ export declare const accessState: (input: TableAccessInput) => PlanAccessState;
71
+ /**
72
+ * The access of one table a plan creates (`before` absent) or changes: the rules, grants and row security now and
73
+ * after, one sentence per rule, and the findings the change brings and removes.
74
+ */
75
+ export declare function planTableAccess(table: string, before: TableAccessInput | undefined, after: TableAccessInput): PlanTableAccess;
76
+ /** One rule as the registry reads it: its policy type, its data, and the WITH CHECK override of an update. */
77
+ export type Rule = Pick<TablePolicy, 'type' | 'data' | 'with_check'>;
78
+ /** What a change does to the columns of one table. */
79
+ export type ColumnChange = {
80
+ /** The columns its nodes add that the table does not have. */
81
+ added: PlanColumn[];
82
+ /** The columns its nodes would add that the table has: a generator keeps each as it is, its own default too. */
83
+ reused: PlanColumn[];
84
+ /** The added columns the rows there now would get no value for: the change fails if the table has rows. */
85
+ failsIfRows: PlanColumn[];
86
+ /** The added columns as the registry reads them, for the access after the change. */
87
+ fields: TableField[];
88
+ /** What the plan says about columns the registry does not know. */
89
+ notes: string[];
90
+ };
91
+ /**
92
+ * The columns `nodes` add to a table that has `fields`, and the ones they
93
+ * reuse (a generator keeps a column of the same name as it is), refused when
94
+ * a rule reads a column the table has not and no node of the change adds: the
95
+ * backend cannot build that rule. Where a node's columns, or the columns a
96
+ * rule reads, are not known, the plan says what it cannot check instead.
97
+ */
98
+ export declare function columnChange(table: string, fields: ReadonlyArray<SchemaField | {
99
+ name: string;
100
+ }>, nodes: Array<string | {
101
+ $type: string;
102
+ data?: object;
103
+ }>, rules: readonly Rule[]): Result<ColumnChange>;
104
+ /** The plan's parts for a column change: the columns it adds and reuses, and the ones that fail on rows of an existing table. */
105
+ export declare const columnPlan: (change: ColumnChange, existing: boolean) => Pick<PlanTableAccess, "columnsAdded" | "columnsReused" | "failsIfRows">;
106
+ /** Why a change that adds `columns` cannot apply to `table` while it has rows, and the fix. */
107
+ export declare function rowsConflict(table: string, columns: PlanColumn[]): {
108
+ message: string;
109
+ hint: string;
110
+ calls: ToolCallSuggestion[];
111
+ };
112
+ /**
113
+ * What a refusal of a change to `table` means: a refused NOT NULL is the rows the added columns get no value for,
114
+ * and a refused rule is one of the caller's own `rules` (a preset's are the registry's, so they are left out).
115
+ */
116
+ export declare const changeMeaning: (table: string, change: ColumnChange, rules: readonly Rule[] | undefined) => FailureMeaning;
@@ -0,0 +1,418 @@
1
+ // The access of the tables of a bound database, read once from the control
2
+ // plane: their columns, policies, grants and row-security state, which is the
3
+ // whole input the words and the findings of a table need. A part that cannot
4
+ // be read fails the read, so no report leaves a part out.
5
+ import { listed } from '@agentic-kit/harness';
6
+ import { accessFindings, columnsReadByPolicies, defaultFills, explainPolicy, fieldsAddedByNodes, } from './access';
7
+ import { AUTHZ_NODES, isObject, part } from './access/policies';
8
+ import { fieldTypeToTypeName } from './blueprint/field-type';
9
+ import { DESCRIBE_SCHEMA, failureFromError, failureFromErrors, suggest } from './failure';
10
+ import { notFound, renamed } from './schema-resolve';
11
+ const PRIVILEGE_ORDER = ['all', 'select', 'insert', 'update', 'delete'];
12
+ const PRIVILEGES = new Set(['select', 'insert', 'update', 'delete']);
13
+ /** A canonical JSON text, so two rules with the same data in another key order are one rule. */
14
+ export const canonical = (value) => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
15
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)))
16
+ : item);
17
+ // The stored WITH CHECK override: {"$type": "Authz...", "data": {...}}, or none.
18
+ function withCheckOf(value) {
19
+ if (!value || typeof value !== 'object' || typeof value.$type !== 'string')
20
+ return undefined;
21
+ const { $type, data } = value;
22
+ return { type: $type, data: data && typeof data === 'object' ? data : {} };
23
+ }
24
+ function policyRules(rows) {
25
+ const rules = new Map();
26
+ for (const row of rows) {
27
+ const withCheck = withCheckOf(row.withCheck);
28
+ const rule = {
29
+ type: row.policyType ?? '',
30
+ privileges: [],
31
+ permissive: row.permissive !== false,
32
+ role: row.granteeName ?? '',
33
+ data: row.data && typeof row.data === 'object' ? row.data : {},
34
+ ...(row.disabled ? { disabled: true } : {}),
35
+ ...(withCheck ? { withCheck } : {}),
36
+ };
37
+ const key = canonical([rule.type, rule.permissive, rule.role, rule.disabled ?? false, rule.data, rule.withCheck ?? null]);
38
+ const kept = rules.get(key) ?? rule;
39
+ const privilege = (row.privilege ?? '').toLowerCase();
40
+ if (privilege && !kept.privileges.includes(privilege))
41
+ kept.privileges.push(privilege);
42
+ rules.set(key, kept);
43
+ }
44
+ for (const rule of rules.values()) {
45
+ rule.privileges.sort((a, b) => PRIVILEGE_ORDER.indexOf(a) - PRIVILEGE_ORDER.indexOf(b));
46
+ }
47
+ return [...rules.values()];
48
+ }
49
+ // The grants of one table in the blueprint shape the registry reads: per role, [privilege, columns or '*'].
50
+ function tableGrants(rows, fieldNames) {
51
+ const byRole = new Map();
52
+ for (const row of rows) {
53
+ if (row.isGrant === false || !row.granteeName || !row.privilege)
54
+ continue;
55
+ const columns = row.fieldIds?.length ? row.fieldIds.map((id) => fieldNames.get(id) ?? id) : '*';
56
+ byRole.set(row.granteeName, [...(byRole.get(row.granteeName) ?? []), [row.privilege.toLowerCase(), columns]]);
57
+ }
58
+ return [...byRole].map(([role, privileges]) => ({ roles: [role], privileges }));
59
+ }
60
+ function toDefaultValueString(value) {
61
+ if (value == null)
62
+ return null;
63
+ if (typeof value === 'string')
64
+ return value;
65
+ return JSON.stringify(value);
66
+ }
67
+ const groupBy = (rows) => {
68
+ const groups = new Map();
69
+ for (const row of rows)
70
+ groups.set(row.tableId, [...(groups.get(row.tableId) ?? []), row]);
71
+ return groups;
72
+ };
73
+ /** The application tables of the bound database (every one, or those named), with all their access parts. */
74
+ export async function readTables(context, names, schemaId) {
75
+ const { api, databaseId } = context;
76
+ try {
77
+ const tablesResult = await api.table
78
+ .findMany({
79
+ select: { id: true, name: true, category: true, useRls: true },
80
+ where: {
81
+ databaseId: { equalTo: databaseId },
82
+ ...(schemaId ? { schemaId: { equalTo: schemaId } } : {}),
83
+ or: [{ category: { equalTo: 'APP' } }, { name: { equalTo: 'users' } }],
84
+ ...(names ? { name: { in: names } } : {}),
85
+ },
86
+ orderBy: ['NAME_ASC'],
87
+ })
88
+ .execute();
89
+ if (!tablesResult.ok)
90
+ return { kind: 'failed', failure: failureFromErrors(tablesResult.errors, 'Failed to read schema') };
91
+ const tableNodes = tablesResult.data.tables?.nodes ?? [];
92
+ const tableIds = tableNodes.map((table) => table.id);
93
+ if (tableIds.length === 0)
94
+ return { kind: 'ok', value: [] };
95
+ const where = { tableId: { in: tableIds } };
96
+ const [fieldsResult, policiesResult, grantsResult] = await Promise.all([
97
+ api.field
98
+ .findMany({ select: { id: true, name: true, type: true, isRequired: true, defaultValue: true, tableId: true }, where })
99
+ .execute(),
100
+ api.policy
101
+ .findMany({
102
+ select: { tableId: true, name: true, policyType: true, privilege: true, permissive: true, granteeName: true, disabled: true, data: true, withCheck: true },
103
+ where,
104
+ })
105
+ .execute(),
106
+ api.tableGrant.findMany({ select: { tableId: true, privilege: true, granteeName: true, fieldIds: true, isGrant: true }, where }).execute(),
107
+ ]);
108
+ if (!fieldsResult.ok)
109
+ return { kind: 'failed', failure: failureFromErrors(fieldsResult.errors, 'Failed to read fields') };
110
+ if (!policiesResult.ok)
111
+ return { kind: 'failed', failure: failureFromErrors(policiesResult.errors, 'Failed to read policies') };
112
+ if (!grantsResult.ok)
113
+ return { kind: 'failed', failure: failureFromErrors(grantsResult.errors, 'Failed to read grants') };
114
+ const fieldRows = fieldsResult.data.fields?.nodes ?? [];
115
+ const fieldNames = new Map(fieldRows.map((field) => [field.id, field.name]));
116
+ const fields = groupBy(fieldRows);
117
+ const policies = groupBy((policiesResult.data.policies?.nodes ?? []));
118
+ const grants = groupBy((grantsResult.data.tableGrants?.nodes ?? []));
119
+ return {
120
+ kind: 'ok',
121
+ value: tableNodes.map((table) => ({
122
+ id: table.id,
123
+ name: table.name,
124
+ fields: (fields.get(table.id) ?? []).map((field) => ({
125
+ name: field.name,
126
+ type: fieldTypeToTypeName(field.type),
127
+ isRequired: Boolean(field.isRequired),
128
+ defaultValue: toDefaultValueString(field.defaultValue),
129
+ })),
130
+ policyRules: policyRules(policies.get(table.id) ?? []),
131
+ policyNames: (policies.get(table.id) ?? []).flatMap((row) => (row.name ? [row.name] : [])),
132
+ grants: tableGrants(grants.get(table.id) ?? [], fieldNames),
133
+ rlsEnabled: table.useRls === true,
134
+ })),
135
+ };
136
+ }
137
+ catch (err) {
138
+ return { kind: 'failed', failure: failureFromError(err, 'Failed to read schema') };
139
+ }
140
+ }
141
+ /** One table of the bound database by name, or `not-found` naming the call that lists them. */
142
+ export async function readTable(context, name) {
143
+ const stored = renamed(name);
144
+ const read = await readTables(context, stored ? [name, stored] : [name], context.schemaId);
145
+ if (read.kind === 'failed')
146
+ return read;
147
+ const table = read.value.find((candidate) => candidate.name === name);
148
+ if (table)
149
+ return { kind: 'ok', value: table };
150
+ const message = `Table "${name}" was not found in the project database.`;
151
+ return { kind: 'failed', failure: notFound('Table', name, message, read.value.map((candidate) => candidate.name)) };
152
+ }
153
+ // A stored field default: the JSON of a FieldDefault (as readTables keeps it), or SQL text this tool cannot read.
154
+ function storedDefault(value) {
155
+ if (value === null)
156
+ return null;
157
+ try {
158
+ const parsed = JSON.parse(value);
159
+ return parsed !== null && typeof parsed === 'object' ? parsed : 'unknown';
160
+ }
161
+ catch {
162
+ return 'unknown';
163
+ }
164
+ }
165
+ /** A stored field default as the SQL it stands for (`now()`, `0`), or as stored when this tool cannot read it. */
166
+ export function defaultText(value) {
167
+ const parsed = storedDefault(value);
168
+ if (parsed === null)
169
+ return '';
170
+ if (parsed === 'unknown')
171
+ return value;
172
+ return 'generated' in parsed ? `generated (${parsed.generated})` : defaultSql(parsed);
173
+ }
174
+ /** A column as the registry reads it: its default decides, for example, whose team a new row names. */
175
+ export const tableField = (field) => ({
176
+ name: field.name,
177
+ required: field.isRequired,
178
+ default: storedDefault(field.defaultValue),
179
+ type: field.type,
180
+ });
181
+ /** A column a Data node adds, as the registry reads it. */
182
+ const addedField = (column) => ({ name: column.name, required: !column.nullable, default: column.default, type: column.type });
183
+ /**
184
+ * What the registry reads for one live table: every policy (a role of
185
+ * `public` counts for every role) with its WITH CHECK override, the grants,
186
+ * the row-security state and the columns. A disabled policy does not apply,
187
+ * so it is left out.
188
+ */
189
+ export function accessInputOf(table) {
190
+ return {
191
+ policies: table.policyRules
192
+ .filter((rule) => !rule.disabled)
193
+ .map((rule) => ({
194
+ type: rule.type,
195
+ privileges: rule.privileges.filter((privilege) => PRIVILEGES.has(privilege)),
196
+ permissive: rule.permissive,
197
+ role: rule.role || 'authenticated',
198
+ data: rule.data,
199
+ ...(rule.withCheck ? { with_check: rule.withCheck } : {}),
200
+ })),
201
+ grants: table.grants,
202
+ rls_enabled: table.rlsEnabled,
203
+ fields: table.fields.map(tableField),
204
+ };
205
+ }
206
+ /** One rule in plain words, with the related columns the reader read; a rule the words cannot describe says so instead. */
207
+ export function ruleWords(type, data, related) {
208
+ if (!AUTHZ_NODES.has(type))
209
+ return `A rule of the type ${type}, which these words do not describe.`;
210
+ try {
211
+ return explainPolicy(type, data ?? {}, related);
212
+ }
213
+ catch {
214
+ return `A ${type} rule whose stored data these words cannot read.`;
215
+ }
216
+ }
217
+ const EXPRESSION = { format: 'authz-expression' };
218
+ // A part of an Authz expression: AND and OR hold a list of expressions, NOT holds one, and a node holds its own data.
219
+ function expressionPart(key) {
220
+ if (key === 'AND' || key === 'OR')
221
+ return { items: EXPRESSION };
222
+ if (key === 'NOT')
223
+ return EXPRESSION;
224
+ return AUTHZ_NODES.get(key)?.parameter_schema;
225
+ }
226
+ // `value` under `schema` without the keys the schema marks readOnly, which the backend or the platform sets, nested
227
+ // Authz nodes included: the parse trees, the member lists the backend resolves, and the table it records.
228
+ function withoutStoredOnly(schema, value) {
229
+ if (!schema)
230
+ return value;
231
+ if (Array.isArray(value)) {
232
+ const items = schema.items && !Array.isArray(schema.items) ? schema.items : undefined;
233
+ return items ? value.map((item) => withoutStoredOnly(items, item)) : value;
234
+ }
235
+ if (!isObject(value))
236
+ return value;
237
+ return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {
238
+ const part = schema.properties?.[key] ?? (schema.format === 'authz-expression' ? expressionPart(key) : undefined);
239
+ return part?.readOnly ? [] : [[key, withoutStoredOnly(part, item)]];
240
+ }));
241
+ }
242
+ const writtenData = (type, data) => withoutStoredOnly(AUTHZ_NODES.get(type)?.parameter_schema, data ?? {});
243
+ /**
244
+ * A stored rule as every read returns it: the keys a caller writes (`$type`, `privileges`, `permissive`,
245
+ * `policy_role`, `data`, and `with_check` for an update rule with its own check), with each key the closed
246
+ * parameter_schema marks readOnly left out, so no read carries a part the closed world refuses.
247
+ */
248
+ export function asWritten(policy) {
249
+ return {
250
+ $type: policy.type,
251
+ privileges: [...policy.privileges],
252
+ permissive: policy.permissive !== false,
253
+ policy_role: policy.role || 'authenticated',
254
+ data: writtenData(policy.type, policy.data),
255
+ ...(policy.with_check ? { with_check: { $type: policy.with_check.type, data: writtenData(policy.with_check.type, policy.with_check.data) } } : {}),
256
+ };
257
+ }
258
+ /** One rule as a plan names it, under the keys a caller writes: its own sentence, and for an update rule with its own check of the changed row, that one too. */
259
+ export function planRule(policy, related) {
260
+ const check = policy.with_check ? ` A changed row must pass instead: ${ruleWords(policy.with_check.type, policy.with_check.data ?? {}, related)}` : '';
261
+ const rule = {
262
+ $type: policy.type,
263
+ privileges: policy.privileges,
264
+ permissive: policy.permissive !== false,
265
+ policy_role: policy.role || 'authenticated',
266
+ words: `${ruleWords(policy.type, policy.data, related)}${check}`,
267
+ };
268
+ return Object.defineProperty(rule, 'comparisonKey', { value: part(policy).key });
269
+ }
270
+ /** A table's grants in words, one entry per role: "select, insert, update and delete to authenticated", "update (title) to editor". */
271
+ export function grantWords(grants) {
272
+ const byRole = new Map();
273
+ for (const grant of grants ?? []) {
274
+ for (const role of grant.roles) {
275
+ for (const entry of grant.privileges) {
276
+ const [privilege, columns] = Array.isArray(entry) ? entry : [entry, '*'];
277
+ const what = `${String(privilege).toLowerCase()}${Array.isArray(columns) && columns.length ? ` (${columns.join(', ')})` : ''}`;
278
+ const known = byRole.get(role) ?? [];
279
+ if (!known.includes(what))
280
+ byRole.set(role, [...known, what]);
281
+ }
282
+ }
283
+ }
284
+ return [...byRole].map(([role, privileges]) => {
285
+ const ordered = [...privileges].sort((a, b) => PRIVILEGE_ORDER.indexOf(a.split(' ')[0]) - PRIVILEGE_ORDER.indexOf(b.split(' ')[0]));
286
+ return `${listed(ordered)} to ${role}`;
287
+ });
288
+ }
289
+ /** A table's access at one moment, as a plan names it. */
290
+ export const accessState = (input) => ({
291
+ rules: input.policies.map((policy) => planRule(policy, input.related)),
292
+ grants: grantWords(input.grants),
293
+ rowSecurity: input.rls_enabled !== false,
294
+ });
295
+ /**
296
+ * The access of one table a plan creates (`before` absent) or changes: the rules, grants and row security now and
297
+ * after, one sentence per rule, and the findings the change brings and removes.
298
+ */
299
+ export function planTableAccess(table, before, after) {
300
+ const next = accessFindings(after);
301
+ const now = before ? accessFindings(before) : [];
302
+ const ids = (findings) => new Set(findings.map((finding) => finding.id));
303
+ const [wasIds, willIds] = [ids(now), ids(next)];
304
+ const short = ({ id, level, summary, columns, details }) => ({
305
+ id,
306
+ level,
307
+ summary,
308
+ ...(columns?.length ? { columns } : {}),
309
+ ...(details?.length ? { details } : {}),
310
+ });
311
+ return {
312
+ table,
313
+ ...(before ? { before: accessState(before) } : {}),
314
+ after: accessState(after),
315
+ findingsAdded: next.filter((finding) => !wasIds.has(finding.id)).map(short),
316
+ findingsRemoved: now.filter((finding) => !willIds.has(finding.id)).map(short),
317
+ };
318
+ }
319
+ const sqlLiteral = (value) => (typeof value === 'string' ? `'${value.replace(/'/g, "''")}'` : JSON.stringify(value));
320
+ // A default as the SQL it stands for: `false`, `jwt_public.current_user_id()`, `now()`.
321
+ function defaultSql(value) {
322
+ if (value.sql_keyword)
323
+ return value.sql_keyword;
324
+ if (value.operator && value.left && value.right)
325
+ return `${defaultSql(value.left)} ${value.operator} ${defaultSql(value.right)}`;
326
+ const base = value.function
327
+ ? `${value.schema ? `${value.schema}.` : ''}${value.function}(${(value.args ?? []).map((arg) => (arg !== null && typeof arg === 'object' ? defaultSql(arg) : sqlLiteral(arg))).join(', ')})`
328
+ : sqlLiteral(value.value ?? null);
329
+ return value.cast ? `${base}::${value.cast.name}` : base;
330
+ }
331
+ function planColumn(column) {
332
+ const base = { name: column.name, type: column.type, required: !column.nullable };
333
+ if (column.default === 'unknown')
334
+ return base;
335
+ if (column.default === null)
336
+ return { ...base, default: null };
337
+ if ('generated' in column.default)
338
+ return { ...base, default: `generated by PostgreSQL (${column.default.generated})` };
339
+ const fills = defaultFills(column.default);
340
+ return { ...base, default: defaultSql(column.default), ...(fills.existing_rows === false ? { computed: true } : {}) };
341
+ }
342
+ // A required column fails on the rows the table has when its default does not fill them (the registry's defaultFills).
343
+ const failsOnRows = (column) => !column.nullable && defaultFills(column.default).existing_rows === false;
344
+ function missingColumns(table, missing) {
345
+ const columns = [...new Set(missing.map((entry) => entry.column))];
346
+ const sentences = missing.map(({ type, column }) => `${type} reads the column "${column}", which table "${table}" does not have and this change does not add, so the backend cannot build the rule.`);
347
+ return {
348
+ code: 'invalid-input',
349
+ message: [...new Set(sentences)].join(' '),
350
+ hint: `Add ${listed(columns)} to the table first, or name a column the table has.`,
351
+ calls: [...columns.map((column) => suggest('create_field', { table_name: table, field_name: column }, `Add the column ${column} the rule reads`, ['type'])), DESCRIBE_SCHEMA],
352
+ };
353
+ }
354
+ // A column the table has, as the plan says it: its own type, NOT NULL and default (stored as the JSON of a FieldDefault).
355
+ function existingColumn(field) {
356
+ let stored = field.defaultValue;
357
+ try {
358
+ stored = field.defaultValue === null ? null : JSON.parse(field.defaultValue);
359
+ }
360
+ catch {
361
+ // A default the backend gave as text is the SQL itself.
362
+ }
363
+ const sql = stored === null ? null : typeof stored === 'object' ? defaultSql(stored) : String(stored);
364
+ return { name: field.name, type: field.type, required: field.isRequired, default: sql };
365
+ }
366
+ /**
367
+ * The columns `nodes` add to a table that has `fields`, and the ones they
368
+ * reuse (a generator keeps a column of the same name as it is), refused when
369
+ * a rule reads a column the table has not and no node of the change adds: the
370
+ * backend cannot build that rule. Where a node's columns, or the columns a
371
+ * rule reads, are not known, the plan says what it cannot check instead.
372
+ */
373
+ export function columnChange(table, fields, nodes, rules) {
374
+ const { fields: columns, unknown } = fieldsAddedByNodes(nodes);
375
+ const has = new Map(fields.map((field) => [field.name, field]));
376
+ const adds = columns.filter((column) => !has.has(column.name));
377
+ const reused = columns.flatMap((column) => {
378
+ const field = has.get(column.name);
379
+ return field && 'type' in field ? [existingColumn(field)] : [];
380
+ });
381
+ const known = new Set([...has.keys(), ...adds.map((column) => column.name)]);
382
+ const read = columnsReadByPolicies(rules.map((rule) => ({ ...rule, data: rule.data ?? {} })));
383
+ const missing = read.columns.filter((entry) => !known.has(entry.column));
384
+ const notes = unknown.length ? [`The columns ${unknown.join(', ')} add${unknown.length === 1 ? 's' : ''} are not known to the registry, so this plan cannot list them.`] : [];
385
+ if (read.unknown.length) {
386
+ notes.push(`The registry cannot tell which columns ${listed(read.unknown)} reads (a stored expression, or data it does not describe), so this plan cannot check that table "${table}" has them.`);
387
+ }
388
+ if (missing.length && !unknown.length)
389
+ return { kind: 'failed', failure: missingColumns(table, missing) };
390
+ for (const { type, column } of missing)
391
+ notes.push(`${type} reads the column "${column}", which table "${table}" does not have; this plan cannot tell whether ${listed(unknown)} adds it.`);
392
+ const added = adds.map(planColumn);
393
+ return { kind: 'ok', value: { added, reused, failsIfRows: added.filter((_column, index) => failsOnRows(adds[index])), fields: adds.map(addedField), notes } };
394
+ }
395
+ /** The plan's parts for a column change: the columns it adds and reuses, and the ones that fail on rows of an existing table. */
396
+ export const columnPlan = (change, existing) => ({
397
+ ...(change.added.length ? { columnsAdded: change.added } : {}),
398
+ ...(change.reused.length ? { columnsReused: change.reused } : {}),
399
+ ...(existing && change.failsIfRows.length ? { failsIfRows: change.failsIfRows.map((column) => column.name) } : {}),
400
+ });
401
+ /** Why a change that adds `columns` cannot apply to `table` while it has rows, and the fix. */
402
+ export function rowsConflict(table, columns) {
403
+ const names = listed(columns.map((column) => column.name));
404
+ const many = columns.length === 1 ? '' : 's';
405
+ return {
406
+ message: `table "${table}" has rows, and the change adds the required column${many} ${names} with no value for them.`,
407
+ hint: `Add ${names} first as ${columns.length === 1 ? 'an optional column' : 'optional columns'}, give the rows a value, then make the change again: it keeps a column that exists, as it is.`,
408
+ calls: columns.map((column) => suggest('create_field', { table_name: table, field_name: column.name, type: column.type, is_required: false }, `Add ${column.name} as an optional column first, so the rows can get a value`)),
409
+ };
410
+ }
411
+ /**
412
+ * What a refusal of a change to `table` means: a refused NOT NULL is the rows the added columns get no value for,
413
+ * and a refused rule is one of the caller's own `rules` (a preset's are the registry's, so they are left out).
414
+ */
415
+ export const changeMeaning = (table, change, rules) => ({
416
+ ...(change.failsIfRows.length ? { notNull: rowsConflict(table, change.failsIfRows) } : {}),
417
+ ...(rules ? { policyTypes: rules.map((rule) => rule.type) } : {}),
418
+ });