@starci/eslint-canon-be 3.6.8 → 3.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/app-composition.d.ts +1 -1
- package/dist/app-composition.js +18 -5
- package/dist/auth-passport.d.ts +14 -0
- package/dist/auth-passport.js +106 -0
- package/dist/index.js +4 -0
- package/dist/jwt-alg.js +1 -1
- package/dist/lib/hfs-view.d.ts +9 -0
- package/dist/module-layering.js +17 -4
- package/dist/no-raw-sql.d.ts +9 -0
- package/dist/no-raw-sql.js +78 -0
- package/package.json +1 -1
- package/runtime/knowledge/hfs/canon-pins.yaml +44 -24
- package/runtime/knowledge/hfs/fe-stack.yaml +4 -11
- package/runtime/knowledge/hfs/rules.yaml +179 -157
- package/runtime/knowledge/hfs/slots.yaml +185 -172
- package/runtime/scripts/hfs/architecture/canon-clones.mjs +1 -1
- package/runtime/scripts/hfs/architecture/entity-registry.mjs +53 -0
- package/runtime/scripts/hfs/architecture/{supabase-be.mjs → identity.mjs} +45 -15
- package/runtime/scripts/hfs/architecture/index.mjs +2 -3
- package/runtime/scripts/hfs/architecture/{supabase-ast.mjs → jwt-ast.mjs} +2 -103
- package/runtime/scripts/hfs/architecture/owners.mjs +11 -0
- package/runtime/scripts/hfs/architecture/register-once.mjs +1 -1
- package/runtime/scripts/hfs/architecture/schema-owner.mjs +29 -4
- package/runtime/scripts/hfs/architecture/server-action.mjs +3 -4
- package/runtime/scripts/hfs/architecture/side-boundary.mjs +1 -1
- package/runtime/scripts/hfs/architecture/{supabase-keys.mjs → sql-keys.mjs} +1 -1
- package/runtime/scripts/hfs/architecture/sql-owner.mjs +25 -27
- package/runtime/scripts/hfs/architecture/tiers.mjs +14 -3
- package/runtime/scripts/hfs/architecture/transport-owner.mjs +7 -3
- package/runtime/scripts/hfs/declaration-shape.mjs +15 -18
- package/runtime/scripts/hfs/manifest-shape.mjs +9 -5
- package/runtime/scripts/hfs/rule-params-shape.mjs +4 -1
- package/runtime/scripts/hfs/rules/database-constants.mjs +8 -10
- package/runtime/scripts/hfs/rules/database-migrations.mjs +3 -3
- package/runtime/scripts/hfs/slot-app-view.mjs +1 -1
- package/runtime/scripts/hfs/slots.mjs +8 -2
- package/runtime/scripts/lib/secret-patterns.mjs +2 -2
- package/runtime/scripts/hfs/architecture/supabase-tables.mjs +0 -50
- package/runtime/scripts/hfs/architecture/supabase.mjs +0 -226
|
@@ -2,8 +2,7 @@ import path from 'node:path';
|
|
|
2
2
|
import { analyzeSql, HOLE } from './sql-tokens.mjs';
|
|
3
3
|
import { machineKit } from './machine-ast.mjs';
|
|
4
4
|
import { contextModelOf } from './context-map.mjs';
|
|
5
|
-
import {
|
|
6
|
-
import { supabaseUniqueSetsOf } from './supabase-keys.mjs';
|
|
5
|
+
import { sqlUniqueSetsOf } from './sql-keys.mjs';
|
|
7
6
|
|
|
8
7
|
/**
|
|
9
8
|
* R86 `sql-owner` (BE_SQL_TABLE_OWNER). Every `sql` tagged template (the tag declared in platform/database) of a
|
|
@@ -14,7 +13,7 @@ import { supabaseUniqueSetsOf } from './supabase-keys.mjs';
|
|
|
14
13
|
* capability's, or those of a same-context capability its owner may import (the tier matrix, through `resolver.importAllowed`
|
|
15
14
|
* to the table owner's public entry); a table of another context is refused (cross-context data comes only by events);
|
|
16
15
|
* - every table it names is declared by some entity under TypeORM authority, or by the generated
|
|
17
|
-
*
|
|
16
|
+
* public tables the ordered db/migrations create under the SQL migration authority;
|
|
18
17
|
* - a SELECT carries LIMIT, or reads a single relation under a complete primary/unique-key equality to scalar values,
|
|
19
18
|
* or selects only proven scalar aggregates without GROUP BY. Inferred bounds reject multiplying projections and set operations.
|
|
20
19
|
* Table positions that hold a `${...}` substitution (SqlIdent) are dynamic; they are counted in the coverage and judged by
|
|
@@ -130,11 +129,10 @@ export function entitiesOf(kit, graph) {
|
|
|
130
129
|
|
|
131
130
|
const capabilityTable = root => path.posix.basename(root).replaceAll('-', '_').toLowerCase();
|
|
132
131
|
|
|
133
|
-
/**
|
|
134
|
-
function
|
|
135
|
-
const
|
|
136
|
-
const
|
|
137
|
-
const tables = new Map([...generated].map(table => [table, { table, owner: null, rel: null, uniqueSets: keys.get(table) ?? [] }]));
|
|
132
|
+
/** SQL-authority declarations (the public tables db/migrations create), with an owner when a table name matches a capability's persistence folder. */
|
|
133
|
+
function sqlDeclarations(graph, appRoot) {
|
|
134
|
+
const keys = sqlUniqueSetsOf(appRoot);
|
|
135
|
+
const tables = new Map([...keys.keys()].map(table => [table, { table, owner: null, rel: null, uniqueSets: keys.get(table) ?? [] }]));
|
|
138
136
|
for (const file of graph.files.values()) {
|
|
139
137
|
if (file.slot !== 'be.persistence' || !file.owner) continue;
|
|
140
138
|
const key = capabilityTable(file.owner.root);
|
|
@@ -150,16 +148,16 @@ const isOwnTable = (table, ownTable) => {
|
|
|
150
148
|
return name === ownTable || name.startsWith(`${ownTable}_`);
|
|
151
149
|
};
|
|
152
150
|
|
|
153
|
-
function reportSqlWrite({ tables,
|
|
151
|
+
function reportSqlWrite({ tables, sqlAuthority, file, ownTable, report }, write) {
|
|
154
152
|
const declaration = tables.get(write.table.toLowerCase());
|
|
155
153
|
if (!declaration) {
|
|
156
|
-
report(
|
|
157
|
-
? `SQL writes table ${write.table}, which
|
|
154
|
+
report(sqlAuthority
|
|
155
|
+
? `SQL writes table ${write.table}, which no db/migrations migration creates; add the table in a migration first.`
|
|
158
156
|
: `SQL writes table ${write.table}, which no @Entity declares; declare the entity in the owning capability's persistence/entities.`, { table: write.table });
|
|
159
|
-
} else if (
|
|
157
|
+
} else if (sqlAuthority) {
|
|
160
158
|
if (isOwnTable(write.table, ownTable) && (declaration.owner === null || declaration.owner === file.owner.root)) return;
|
|
161
159
|
const ownerNote = declaration.owner ? `, owned by ${declaration.owner}` : '';
|
|
162
|
-
report(`SQL in ${file.owner.root} writes table ${write.table}${ownerNote}; under
|
|
160
|
+
report(`SQL in ${file.owner.root} writes table ${write.table}${ownerNote}; under the SQL migration authority a capability writes only its own table (${ownTable}), named for that capability.`, { table: write.table, ...(declaration.owner ? { tableOwner: declaration.owner } : {}) });
|
|
163
161
|
} else if (declaration.owner !== file.owner.root) {
|
|
164
162
|
report(`SQL in ${file.owner.root} writes table ${write.table}, owned by ${declaration.owner}; a capability writes only the tables of its own entities, call the owner's public API instead.`, { table: write.table, tableOwner: declaration.owner });
|
|
165
163
|
}
|
|
@@ -169,11 +167,11 @@ function reportSqlWrites(input) {
|
|
|
169
167
|
for (const write of input.result.writes) reportSqlWrite(input, write);
|
|
170
168
|
}
|
|
171
169
|
|
|
172
|
-
function reportSqlRead(tables,
|
|
170
|
+
function reportSqlRead(tables, sqlAuthority, file, model, resolver, report, read) {
|
|
173
171
|
const declaration = tables.get(read.table.toLowerCase());
|
|
174
172
|
if (!declaration) {
|
|
175
|
-
report(
|
|
176
|
-
? `SQL reads table ${read.table}, which
|
|
173
|
+
report(sqlAuthority
|
|
174
|
+
? `SQL reads table ${read.table}, which no db/migrations migration creates; add the table in a migration first.`
|
|
177
175
|
: `SQL reads table ${read.table}, which no @Entity declares; declare the entity in the owning capability's persistence/entities.`, { table: read.table });
|
|
178
176
|
return;
|
|
179
177
|
}
|
|
@@ -188,8 +186,8 @@ function reportSqlRead(tables, supabase, file, model, resolver, report, read) {
|
|
|
188
186
|
if (!verdict.allowed) report(`SQL in ${file.owner.root} reads table ${read.table}, owned by ${declaration.owner}, which ${file.owner.root} may not import (${verdict.reason}); read it through the owner's public API.`, { table: read.table, tableOwner: declaration.owner, reason: verdict.reason });
|
|
189
187
|
}
|
|
190
188
|
|
|
191
|
-
function reportSqlReads({ result, tables,
|
|
192
|
-
for (const read of result.reads) reportSqlRead(tables,
|
|
189
|
+
function reportSqlReads({ result, tables, sqlAuthority, file, model, resolver, report }) {
|
|
190
|
+
for (const read of result.reads) reportSqlRead(tables, sqlAuthority, file, model, resolver, report, read);
|
|
193
191
|
}
|
|
194
192
|
|
|
195
193
|
function reportSqlSelects({ result, tables, report }) {
|
|
@@ -201,7 +199,7 @@ function reportSqlSelects({ result, tables, report }) {
|
|
|
201
199
|
}
|
|
202
200
|
|
|
203
201
|
function inspectSqlTag(input, state, file, checker, node) {
|
|
204
|
-
const { kit, ts, tables,
|
|
202
|
+
const { kit, ts, tables, sqlAuthority, model, resolver } = input;
|
|
205
203
|
if (!ts.isTaggedTemplateExpression(node)) return true;
|
|
206
204
|
const home = kit.declarationsOf(checker, node.tag).map(kit.ownerOfDeclaration).find(Boolean);
|
|
207
205
|
if (home?.tier !== 'platform' || home?.name !== 'database') { state.foreignTags += 1; return true; }
|
|
@@ -217,13 +215,13 @@ function inspectSqlTag(input, state, file, checker, node) {
|
|
|
217
215
|
state.violations.push({ ruleId: RULE, path: file.rel, ...kit.at(file.rel, file.sourceFile, node), message, ...extra });
|
|
218
216
|
};
|
|
219
217
|
const result = analyzeSql(text, { uniqueSetsOf: (table, schema) => {
|
|
220
|
-
if (
|
|
218
|
+
if (sqlAuthority && ((schema && schema !== 'public') || table !== table.toLowerCase())) return null;
|
|
221
219
|
return tables.get(table.toLowerCase())?.uniqueSets ?? null;
|
|
222
220
|
} });
|
|
223
221
|
state.dynamic += result.dynamic;
|
|
224
222
|
const ownTable = capabilityTable(file.owner.root);
|
|
225
|
-
reportSqlWrites({ result, tables,
|
|
226
|
-
reportSqlReads({ result, tables,
|
|
223
|
+
reportSqlWrites({ result, tables, sqlAuthority, file, ownTable, report });
|
|
224
|
+
reportSqlReads({ result, tables, sqlAuthority, file, model, resolver, report });
|
|
227
225
|
reportSqlSelects({ result, tables, report });
|
|
228
226
|
return true;
|
|
229
227
|
}
|
|
@@ -239,13 +237,13 @@ export function checkSqlOwner(input) {
|
|
|
239
237
|
const { config, graph } = input;
|
|
240
238
|
const kit = machineKit(input);
|
|
241
239
|
const { ts, resolver } = kit;
|
|
242
|
-
const
|
|
243
|
-
const entityDeclarations =
|
|
244
|
-
const tables =
|
|
240
|
+
const sqlAuthority = resolver.ruleParams().schemaAuthority === 'sql';
|
|
241
|
+
const entityDeclarations = sqlAuthority ? { tables: new Map(), unreadable: 0 } : entitiesOf(kit, graph);
|
|
242
|
+
const tables = sqlAuthority ? sqlDeclarations(graph, config.packageRoot) : entityDeclarations.tables;
|
|
245
243
|
const model = contextModelOf(kit, graph);
|
|
246
244
|
const state = { violations: [], templates: 0, dynamic: 0, foreignTags: 0 };
|
|
247
|
-
const inspection = { kit, ts, tables,
|
|
245
|
+
const inspection = { kit, ts, tables, sqlAuthority, model, resolver };
|
|
248
246
|
for (const file of graph.files.values()) inspectSqlFile(inspection, state, file);
|
|
249
247
|
return { violations: state.violations, coverage: { status: 'checked', entities: entityDeclarations.tables.size, unreadableEntities: entityDeclarations.unreadable,
|
|
250
|
-
...(
|
|
248
|
+
...(sqlAuthority ? { sqlTables: tables.size } : {}), templates: state.templates, dynamicIdentifiers: state.dynamic, foreignTags: state.foreignTags } };
|
|
251
249
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { byCodeUnit } from '../../lib/list.mjs';
|
|
2
|
+
import { registryListImport, registrySlot } from './entity-registry.mjs';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* HFS checks 1 and 2 (knowledge/hfs/slots.yaml `tiers`):
|
|
@@ -8,7 +9,9 @@ import { byCodeUnit } from '../../lib/list.mjs';
|
|
|
8
9
|
* kind (slot field `trigger`: api, webhooks, realtime, saga, reactors, jobs, cli) importing a feature of another is
|
|
9
10
|
* BE_KIND_ISOLATION, whose fix is the event bus,
|
|
10
11
|
* an app never imports another app (BE_SERVICE_ISOLATION / FE_APP_ISOLATION), and a component layer imports only the layers after it;
|
|
11
|
-
*
|
|
12
|
+
* the entity registry naming a capability's `<c>Entities` from its public entry is the one platform-to-domain edge (entity-registry.mjs);
|
|
13
|
+
* 2. owner cycles: a strongly connected component of the owner graph, type-only imports included (ARCH_OWNER_CYCLE), the entity
|
|
14
|
+
* registry counted as a unit of its own,
|
|
12
15
|
* reported with the cycle path and the import that closes each hop.
|
|
13
16
|
* Importing inside one owner is always allowed; the public-entry rule stays with owners.mjs (ARCH_OWNER_EXPORT_BYPASS).
|
|
14
17
|
*/
|
|
@@ -138,15 +141,23 @@ function inspectTierEdge(graph, edge, tierRule, counts, violations, coverage) {
|
|
|
138
141
|
return;
|
|
139
142
|
}
|
|
140
143
|
coverage.edgesChecked += 1;
|
|
144
|
+
if (verdict.reason === 'tierDirection' && registryListImport(graph.resolver, edge)) return;
|
|
141
145
|
reportReasonedTierViolation(graph, edge, verdict, tierRule, counts, violations);
|
|
142
146
|
}
|
|
143
147
|
|
|
148
|
+
/**
|
|
149
|
+
* The cycle unit of a file: its owner unit, except the entity registry (entity-registry.mjs), which is a unit of its own. It sits in
|
|
150
|
+
* platform/database but is composition-level by role (it imports every capability's `<c>Entities`), so it never closes a cycle
|
|
151
|
+
* among capabilities through the owner it lives in.
|
|
152
|
+
*/
|
|
153
|
+
const cycleUnit = (graph, resolver, rel) => (registrySlot(resolver, rel) ? `entity-registry:${rel}` : graph.unit(rel));
|
|
154
|
+
|
|
144
155
|
function ownerAdjacency(graph, resolver) {
|
|
145
156
|
const adjacency = new Map();
|
|
146
157
|
const witness = new Map();
|
|
147
158
|
for (const edge of graph.edges) {
|
|
148
|
-
const a = graph
|
|
149
|
-
const b = graph
|
|
159
|
+
const a = cycleUnit(graph, resolver, edge.from);
|
|
160
|
+
const b = cycleUnit(graph, resolver, edge.to);
|
|
150
161
|
if (!a || !b || a === b) continue;
|
|
151
162
|
if (resolver.tierOf(edge.from) === 'none' || resolver.tierOf(edge.to) === 'none') continue;
|
|
152
163
|
if (!adjacency.has(a)) adjacency.set(a, new Set());
|
|
@@ -18,7 +18,8 @@ import { propertyValue } from './function-spec-providers.mjs';
|
|
|
18
18
|
* - no file outside the client folder and the stream reader folder (`fe.transport.stream`, `modules/api/sse/clients/`) references the global `fetch`: a call, `globalThis.fetch`, `window.fetch`, or a
|
|
19
19
|
* reference passed as a value (`useSWR(key, fetch)`, `const send = fetch`), all of which a spelling-based rule misses; with no
|
|
20
20
|
* client at all every such reference is a finding that says the repository has no client;
|
|
21
|
-
* - axios is imported only by the api owner (modules/api, the api package) for its rest calls
|
|
21
|
+
* - axios is imported only by the api owner (modules/api, the api package) for its rest calls and by the auth door
|
|
22
|
+
* (modules/auth/auth-door.ts) for the app's own auth doors; every other HTTP library is a
|
|
22
23
|
* second transport wherever it is imported, by static import, `import()` or `require()`;
|
|
23
24
|
* - an `ApolloClient` is constructed only inside the client folder;
|
|
24
25
|
* - every GraphQL operation (`graphql/queries/query-*.ts`, `graphql/mutations/mutation-*.ts`, `graphql/subscriptions/subscription-*.ts`) imports the client (or the api
|
|
@@ -103,13 +104,16 @@ function isApolloClientConstruction(ts, kit, checker, node) {
|
|
|
103
104
|
return Boolean(binding?.name === 'ApolloClient' && binding.module.startsWith('@apollo/client'));
|
|
104
105
|
}
|
|
105
106
|
|
|
107
|
+
/** The one auth door of the session issuer's client (`modules/auth/auth-door.ts`, slot fe.modules.auth): it calls the app's own auth doors with axios. */
|
|
108
|
+
const isAuthDoor = (file) => file.slot === 'fe.modules.auth' && path.posix.basename(file.rel) === 'auth-door.ts';
|
|
109
|
+
|
|
106
110
|
function inspectLibraryImport({ ts, file, node, transport, report }) {
|
|
107
111
|
const specifier = moduleSpecifierOf(ts, node);
|
|
108
112
|
if (!specifier || !ts.isStringLiteralLike(specifier)) return;
|
|
109
113
|
const library = specifier.text.split('/')[0];
|
|
110
|
-
if (!HTTP_LIBRARIES.has(library) || (library === REST_LIBRARY && API_OWNER_SLOTS.has(file.slot))) return;
|
|
114
|
+
if (!HTTP_LIBRARIES.has(library) || (library === REST_LIBRARY && (API_OWNER_SLOTS.has(file.slot) || isAuthDoor(file)))) return;
|
|
111
115
|
const where = library === REST_LIBRARY
|
|
112
|
-
? 'axios belongs to the api owner
|
|
116
|
+
? 'axios belongs to the api owner (modules/api/rest, the api package) and the auth door (modules/auth/auth-door.ts) only: call their functions'
|
|
113
117
|
: `the transport is Apollo GraphQL (${transport}) with axios for the rest calls of modules/api/rest`;
|
|
114
118
|
report(file, node, `${specifier.text} is a second HTTP transport in ${file.rel}; ${where}.`, { library: specifier.text });
|
|
115
119
|
}
|
|
@@ -2,27 +2,23 @@
|
|
|
2
2
|
// against a loaded manifest remain in slots.mjs; this module mirrors modules/schemas/hfs-repo.schema.yaml only.
|
|
3
3
|
import { isPlainObject } from '../../engine/plain-object.mjs';
|
|
4
4
|
import { APP_KIND, connectionShapeProblems, NAME, PACKAGE_NAME, RUNTIME_KIND, SLOT_ID } from './manifest-shape.mjs';
|
|
5
|
+
import { dbFunctionsOk } from './rule-params-shape.mjs';
|
|
5
6
|
import { kindShapeProblems, patternShapeProblems } from './declaration-slots.mjs';
|
|
6
7
|
import { byCodeUnit } from '../lib/list.mjs';
|
|
7
8
|
|
|
8
|
-
/** Shape problems of the optional hfs.json `
|
|
9
|
-
const
|
|
9
|
+
/** Shape problems of the optional hfs.json `db` block of a lite app: the environment variable naming its database, its image, forced RLS and its application role. */
|
|
10
|
+
const isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === 'string' && entry.trim());
|
|
10
11
|
|
|
11
|
-
function
|
|
12
|
-
const bad = [];
|
|
13
|
-
if (block.enableSignup !== undefined && typeof block.enableSignup !== 'boolean') bad.push('supabase.enableSignup must be true or false');
|
|
14
|
-
if (block.jwtExpiry !== undefined && !(Number.isInteger(block.jwtExpiry) && block.jwtExpiry > 0 && block.jwtExpiry <= 3600)) bad.push('supabase.jwtExpiry must be an integer of seconds, 3600 at most');
|
|
15
|
-
if (block.siteUrl !== undefined && (typeof block.siteUrl !== 'string' || !block.siteUrl.trim())) bad.push('supabase.siteUrl must be a URL string');
|
|
16
|
-
for (const key of ['redirectUrls', 'forceRls']) if (block[key] !== undefined && !isSupabaseStringList(block[key])) bad.push(`supabase.${key} must be a list of strings`);
|
|
17
|
-
return bad;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function supabaseBlockProblems(block) {
|
|
12
|
+
function dbBlockProblems(block) {
|
|
21
13
|
if (block === undefined) return [];
|
|
22
|
-
if (!isPlainObject(block)) return ['
|
|
14
|
+
if (!isPlainObject(block)) return ['db must be an object'];
|
|
23
15
|
const bad = [];
|
|
24
|
-
for (const key of Object.keys(block)) if (!['
|
|
25
|
-
|
|
16
|
+
for (const key of Object.keys(block)) if (!['urlEnv', 'image', 'forceRls', 'forceRlsExemptions', 'appRole'].includes(key)) bad.push(`db has unknown key ${key}`);
|
|
17
|
+
if (block.urlEnv !== undefined && (typeof block.urlEnv !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(block.urlEnv))) bad.push('db.urlEnv must name an UPPER_CASE environment variable');
|
|
18
|
+
if (block.image !== undefined && (typeof block.image !== 'string' || !/@sha256:[0-9a-f]{64}$/.test(block.image))) bad.push('db.image must be a digest-pinned image reference');
|
|
19
|
+
if (block.forceRls !== undefined && !isStringList(block.forceRls)) bad.push('db.forceRls must be a list of strings');
|
|
20
|
+
if (block.appRole !== undefined && (typeof block.appRole !== 'string' || !/^[a-z][a-z0-9_]*$/.test(block.appRole))) bad.push('db.appRole must name a role');
|
|
21
|
+
if (block.forceRlsExemptions !== undefined && !Array.isArray(block.forceRlsExemptions)) bad.push('db.forceRlsExemptions must be a list of { table, reason }');
|
|
26
22
|
return bad;
|
|
27
23
|
}
|
|
28
24
|
|
|
@@ -95,7 +91,8 @@ function declarationSideProblems(side, value, names) {
|
|
|
95
91
|
const bad = [];
|
|
96
92
|
const at = `sides.${side}`;
|
|
97
93
|
if (!isPlainObject(value)) return [`${at} must be an object`];
|
|
98
|
-
for (const key of Object.keys(value)) if (!['apps', 'optionalSlots', 'patterns', 'kinds', 'connections', 'reads', 'extraPackages', 'grammar', 'backing', 'queueOutbox'].includes(key)) bad.push(`${at} has unknown key ${key}`);
|
|
94
|
+
for (const key of Object.keys(value)) if (!['apps', 'optionalSlots', 'patterns', 'kinds', 'connections', 'reads', 'extraPackages', 'grammar', 'backing', 'queueOutbox', 'dbFunctions'].includes(key)) bad.push(`${at} has unknown key ${key}`);
|
|
95
|
+
if (value.dbFunctions !== undefined && (side !== 'be' || !dbFunctionsOk(value.dbFunctions))) bad.push(`${at}.dbFunctions belongs to the be side and lists {name, reason} database functions with unique names`);
|
|
99
96
|
bad.push(...appShapeProblems(value.apps, at, side, names));
|
|
100
97
|
if (isBadUniqueList(value.optionalSlots, (slot) => SLOT_ID.test(String(slot)))) bad.push(`${at}.optionalSlots must be a unique list of slot ids`);
|
|
101
98
|
if (value.backing !== undefined && side !== 'be') bad.push('backing belongs to the be side');
|
|
@@ -127,13 +124,13 @@ function observeBlockProblems(observe) {
|
|
|
127
124
|
return bad;
|
|
128
125
|
}
|
|
129
126
|
|
|
130
|
-
const DECLARATION_KEYS = new Set(['hfs', 'kind', 'project', 'edition', '
|
|
127
|
+
const DECLARATION_KEYS = new Set(['hfs', 'kind', 'project', 'edition', 'db', 'sides', 'browser', 'lexicon', 'observe']);
|
|
131
128
|
const RUNTIME_DECLARATION_KEYS = new Set(['hfs', 'kind', 'project']);
|
|
132
129
|
|
|
133
130
|
function productDeclarationProblems(declaration, profiles) {
|
|
134
131
|
const bad = [];
|
|
135
132
|
for (const key of Object.keys(declaration)) if (!DECLARATION_KEYS.has(key)) bad.push(`unknown key ${key}`);
|
|
136
|
-
bad.push(...
|
|
133
|
+
bad.push(...dbBlockProblems(declaration.db), ...lexiconBlockProblems(declaration.lexicon), ...observeBlockProblems(declaration.observe));
|
|
137
134
|
if (declaration.browser !== undefined && declaration.browser !== true) bad.push('browser is `true` when the app has a browser journey (slot app.browser), and is left out otherwise');
|
|
138
135
|
if (declaration.kind !== APP_KIND) bad.push(`kind must be ${APP_KIND} (a product is one app repository with a be and an fe side) or ${RUNTIME_KIND} (the StarCi runtime repository)`);
|
|
139
136
|
if (!isPlainObject(declaration.sides) || Object.keys(declaration.sides).sort(byCodeUnit).join() !== profiles.join()) { bad.push('sides must declare exactly be and fe'); return bad; }
|
|
@@ -15,12 +15,12 @@ const ENV_PREFIX =/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$/;
|
|
|
15
15
|
const CONTEXT_ISOLATIONS = Object.freeze(["database", "schema"]);
|
|
16
16
|
/** The app kinds that may own a context: the services, never the migrate or cli apps that only run migrations. */
|
|
17
17
|
const CONTEXT_OWNER_KINDS = Object.freeze(["api", "worker"]);
|
|
18
|
-
/** The database
|
|
19
|
-
const CONNECTION_PROVIDERS = Object.freeze(["postgres"
|
|
18
|
+
/** The database engine a connection runs on. */
|
|
19
|
+
const CONNECTION_PROVIDERS = Object.freeze(["postgres"]);
|
|
20
20
|
/** The editions an app repository may declare in hfs.json (`full` when absent): the filter slots.mjs applies. */
|
|
21
21
|
export const EDITIONS = Object.freeze(["full", "lite"]);
|
|
22
|
-
/** What decides where schema changes live (ruleParams.<side>.schemaAuthority): TypeORM migrations under persistence/, or the
|
|
23
|
-
export const SCHEMA_AUTHORITIES = Object.freeze(["typeorm", "
|
|
22
|
+
/** What decides where schema changes live (ruleParams.<side>.schemaAuthority): TypeORM migrations under persistence/, or the SQL migration tree db/migrations. */
|
|
23
|
+
export const SCHEMA_AUTHORITIES = Object.freeze(["typeorm", "sql"]);
|
|
24
24
|
/**
|
|
25
25
|
* The shape problems of the `connections` of one side: a list of {name, envPrefix, owner, isolation}, the owner an api or worker app
|
|
26
26
|
* of the same side (a connection is a bounded context and one service owns it), isolation `database` or `schema`.
|
|
@@ -87,7 +87,9 @@ export const MANIFEST_KINDS = [APP_KIND, RUNTIME_KIND];
|
|
|
87
87
|
export const manifestKind = (m) => (isPlainObject(m) && m.kind !== undefined ? m.kind : APP_KIND);
|
|
88
88
|
const strList = (v) => stringList(v);
|
|
89
89
|
|
|
90
|
-
const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy'];
|
|
90
|
+
const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy', 'role', 'importedBy'];
|
|
91
|
+
/** The roles a file slot may play that a rule reads (`role`): the entity registry of persistence.md BE-PERSISTENCE-3 (architecture/entity-registry.mjs). */
|
|
92
|
+
const SLOT_ROLES = ['entity-registry'];
|
|
91
93
|
/** The fields a slot's `lite` overlay may hold: the same keys it would carry in the slot body, resolved under edition lite. */
|
|
92
94
|
const LITE_OVERLAY_KEYS = ['path', 'requires', 'allows', 'forbids', 'minInstances', 'requiredInstances', 'why'];
|
|
93
95
|
/** A runtime slot has no app kind, side composition, layer or managed template; it may name the generator of a generated copy. */
|
|
@@ -249,6 +251,8 @@ function slotEntryProblems(slot, at) {
|
|
|
249
251
|
else if (Array.isArray(slot.allows) && slot.entries.some((entry) => !slot.allows.includes(entry))) bad.push(`${at}: every entry must be one of the names the slot allows`);
|
|
250
252
|
}
|
|
251
253
|
if (slot.outcomeHome !== undefined && !(slot.outcomeHome === true && typeof slot.path === 'string' && slot.path && !slot.path.endsWith('/'))) bad.push(`${at}: outcomeHome is true and belongs to a file slot (the one file that declares the repository's Outcome union)`);
|
|
254
|
+
if (slot.role !== undefined && !(SLOT_ROLES.includes(slot.role) && typeof slot.path === 'string' && slot.path && !slot.path.endsWith('/'))) bad.push(`${at}: role is one of ${SLOT_ROLES.join(', ')} and belongs to a file slot`);
|
|
255
|
+
if (slot.importedBy !== undefined && !(slot.role !== undefined && strList(slot.importedBy) && slot.importedBy.length && new Set(slot.importedBy).size === slot.importedBy.length && slot.importedBy.every(relPath))) bad.push(`${at}: importedBy is a non-empty list of unique relative path patterns of the only files that import the slot's file by deep path, on a slot with a role`);
|
|
252
256
|
return bad;
|
|
253
257
|
}
|
|
254
258
|
|
|
@@ -62,6 +62,9 @@ function beSpecificProblems(be, manifest) {
|
|
|
62
62
|
return bad;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
/** True for an absent list or a list of {name, reason} database functions, names unique. */
|
|
66
|
+
export const dbFunctionsOk = (list) => list === undefined || (Array.isArray(list) && list.every((entry) => isPlainObject(entry) && Object.keys(entry).sort().join() === 'name,reason' && /^[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)?$/.test(entry.name) && typeof entry.reason === 'string' && entry.reason.trim().length > 0) && new Set(list.map((entry) => entry.name)).size === list.length);
|
|
67
|
+
|
|
65
68
|
/** The shape problems of `m.ruleParams`. */
|
|
66
69
|
export function ruleParamsProblems(m) {
|
|
67
70
|
const bad = [];
|
|
@@ -71,7 +74,7 @@ export function ruleParamsProblems(m) {
|
|
|
71
74
|
// common holds the parameters both sides share; a side may restate one of them (a valid value) as an override, nothing else.
|
|
72
75
|
// Edition lite: a side's optional `lite` map overrides keys of the same side (never `lite` itself) when the app declares edition lite.
|
|
73
76
|
if (!sideOk(rp.common, []) || !fileLinesOk(rp.common.fileLines) || !blockOk(rp.common.duplicateBlock)) bad.push('ruleParams.common needs fileLines {soft, hardGrowth} and duplicateBlock {lines >= 2, tokens >= 1}; optional functionLines and featureFiles must be positive integers');
|
|
74
|
-
if (!sideOk(rp.be, BE_OWN, ['schemaAuthority', 'lite']) || (rp.be.schemaAuthority !== undefined && !SCHEMA_AUTHORITIES.includes(rp.be.schemaAuthority)) || !liteOk(rp.be.lite, [...BE_OWN, ...SHARED_KEYS, 'schemaAuthority'])) bad.push('ruleParams.be needs infraOwners, eventBus, specDoubles, paramNames, suffixes, bannedSuffixes, contractShape {helper}, unitRoles, logicRoles, thinRoles, patternScenarios, kindPatterns, addKinds and backing (shared parameters live in ruleParams.common, a side may override them); optional: schemaAuthority (' + SCHEMA_AUTHORITIES.join(' | ') + ') and lite (overrides of the same keys)'); else bad.push(...unitRolesProblems(rp.be), ...roleListProblems(rp.be));
|
|
77
|
+
if (!sideOk(rp.be, BE_OWN, ['schemaAuthority', 'lite', 'dbFunctions']) || (rp.be.schemaAuthority !== undefined && !SCHEMA_AUTHORITIES.includes(rp.be.schemaAuthority)) || !dbFunctionsOk(rp.be.dbFunctions) || !liteOk(rp.be.lite, [...BE_OWN, ...SHARED_KEYS, 'schemaAuthority', 'dbFunctions'])) bad.push('ruleParams.be needs infraOwners, eventBus, specDoubles, paramNames, suffixes, bannedSuffixes, contractShape {helper}, unitRoles, logicRoles, thinRoles, patternScenarios, kindPatterns, addKinds and backing (shared parameters live in ruleParams.common, a side may override them); optional: schemaAuthority (' + SCHEMA_AUTHORITIES.join(' | ') + '), dbFunctions ([{name, reason}]) and lite (overrides of the same keys)'); else bad.push(...unitRolesProblems(rp.be), ...roleListProblems(rp.be));
|
|
75
78
|
bad.push(...beSpecificProblems(rp.be, m));
|
|
76
79
|
if (rp.fe !== undefined && (!sideOk(rp.fe, [], ['lite']) || !liteOk(rp.fe.lite, SHARED_KEYS))) bad.push('ruleParams.fe may only restate the shared parameters of ruleParams.common, and carry a lite override of them');
|
|
77
80
|
if (!dbParamsOk(rp.db)) bad.push('ruleParams.db may contain only extensions (a list of unique non-empty extension names) and queueOutbox ({table: <schema>.<table>, columns: [unique column names including queue]})');
|
|
@@ -1,26 +1,24 @@
|
|
|
1
|
-
// Single source of database-rule finding codes and owned
|
|
1
|
+
// Single source of database-rule finding codes and the owned db/ paths of a lite app (slot app.db).
|
|
2
2
|
export const DB_MIGRATION_SHAPE = 'DB_MIGRATION_SHAPE';
|
|
3
3
|
export const DB_RLS_REQUIRED = 'DB_RLS_REQUIRED';
|
|
4
4
|
export const DB_DYNAMIC_DDL = 'DB_DYNAMIC_DDL';
|
|
5
5
|
export const DB_POLICY_SHAPE = 'DB_POLICY_SHAPE';
|
|
6
6
|
export const DB_DEFINER_SAFE = 'DB_DEFINER_SAFE';
|
|
7
7
|
export const DB_STORAGE_POLICY = 'DB_STORAGE_POLICY';
|
|
8
|
-
export const
|
|
9
|
-
export const DB_TYPES_DRIFT = 'DB_TYPES_DRIFT';
|
|
8
|
+
export const LITE_DB_MIGRATION = 'LITE_DB_MIGRATION';
|
|
10
9
|
export const DB_BASELINE_SHAPE = 'DB_BASELINE_SHAPE';
|
|
11
10
|
export const DB_ARCHIVE_MUTATED = 'DB_ARCHIVE_MUTATED';
|
|
12
11
|
export const DB_PGMQ_DECLARED = 'DB_PGMQ_DECLARED';
|
|
13
12
|
export const DB_CRON_OWNED = 'DB_CRON_OWNED';
|
|
14
13
|
export const DB_EXTENSION_ALLOWED = 'DB_EXTENSION_ALLOWED';
|
|
15
|
-
export const DB_API_EXPOSED = 'DB_API_EXPOSED';
|
|
16
14
|
export const DB_MIGRATION_DESTRUCTIVE = 'DB_MIGRATION_DESTRUCTIVE';
|
|
17
15
|
export const HFS_SEED_PII = 'HFS_SEED_PII';
|
|
18
16
|
export const DB_VAULT_WRITE = 'DB_VAULT_WRITE';
|
|
19
17
|
|
|
20
|
-
export const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
18
|
+
export const DB_DIR = 'db';
|
|
19
|
+
export const MIGRATIONS_DIR = `${DB_DIR}/migrations`;
|
|
20
|
+
/** The migrations retired at a baseline cutover (slot app.db.migrations.archive): never applied, never judged by L02-L08. */
|
|
21
|
+
export const MIGRATIONS_ARCHIVE_DIR = `${MIGRATIONS_DIR}/archive`;
|
|
22
|
+
/** True for a migration `starci app db migrate` applies: a path under db/migrations/ outside the archive. */
|
|
24
23
|
export const isActiveMigration = (file) => file.startsWith(`${MIGRATIONS_DIR}/`) && !file.startsWith(`${MIGRATIONS_ARCHIVE_DIR}/`);
|
|
25
|
-
export const
|
|
26
|
-
export const TYPES_FILE = 'supabase/types/database.types.ts';
|
|
24
|
+
export const SEED_FILE = `${DB_DIR}/seed.sql`;
|
|
@@ -74,7 +74,7 @@ function localMigrationFindings(local) {
|
|
|
74
74
|
const stamps = new Map();
|
|
75
75
|
for (const entry of local) {
|
|
76
76
|
if (!entry.match) {
|
|
77
|
-
findings.push(found(DB_MIGRATION_SHAPE, entry.file, `${entry.file} is not named <ts14>_<kebab>.sql; a migration is created by \`npm run db:new\` (
|
|
77
|
+
findings.push(found(DB_MIGRATION_SHAPE, entry.file, `${entry.file} is not named <ts14>_<kebab>.sql; a migration is created by \`npm run db:new\` (starci app db new), never renamed by hand`, { expected: '<ts14>_<kebab>.sql' }));
|
|
78
78
|
continue;
|
|
79
79
|
}
|
|
80
80
|
const stamp = migrationStamp(entry.match[1]);
|
|
@@ -143,8 +143,8 @@ function removedMigrationFindings(local, retired, baseNames, baseSha) {
|
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
/**
|
|
146
|
-
* L02 findings for names, stamps, ordering and immutability of
|
|
147
|
-
*
|
|
146
|
+
* L02 findings for names, stamps, ordering and immutability of db/migrations/*.sql. `archived` are the files of
|
|
147
|
+
* db/migrations/archive/ (app.db.migrations.archive): never judged, and a migration moved there at a baseline
|
|
148
148
|
* cutover is retired from the ordering chain, not removed. New files append after HEAD's active migrations; timestamps
|
|
149
149
|
* on archived migrations, remote branches and the wall clock do not constrain a replacement baseline.
|
|
150
150
|
*/
|
|
@@ -49,7 +49,7 @@ function sideCrossing(repo, fromSide, toSide, toPath) {
|
|
|
49
49
|
function importAllowedApp({ repo, root, sides }, fromPath, toPath) {
|
|
50
50
|
const from = splitSide(fromPath);
|
|
51
51
|
const to = splitSide(toPath);
|
|
52
|
-
// A side file may read an app-root path (
|
|
52
|
+
// A side file may read an app-root path (db/types/) only through a declared read, exactly as it reads the other side.
|
|
53
53
|
if (from && from.side !== to?.side) return sideCrossing(repo, from.side, to?.side ?? null, toPath);
|
|
54
54
|
if (from && to) return sides[from.side].importAllowed(from.rest, to.rest);
|
|
55
55
|
return root.importAllowed(fromPath, toPath);
|
|
@@ -120,6 +120,7 @@ function sideDeclaration(manifest, declaration, name, edition, providers) {
|
|
|
120
120
|
connections: Object.freeze((s.connections ?? []).map(connectionView)),
|
|
121
121
|
providers,
|
|
122
122
|
reads: Object.freeze([...(s.reads ?? [])]),
|
|
123
|
+
dbFunctions: Object.freeze((s.dbFunctions ?? []).map((entry) => Object.freeze({ ...entry }))),
|
|
123
124
|
...(s.grammar === undefined ? {} : { grammar: s.grammar }),
|
|
124
125
|
...(s.extraPackages === undefined ? {} : { extraPackages: Object.freeze(s.extraPackages.map(entry => Object.freeze({ ...entry }))) }),
|
|
125
126
|
manifestVersion: manifest.version,
|
|
@@ -221,7 +222,8 @@ function createScopeResolver(manifest, repo) {
|
|
|
221
222
|
trackingOf,
|
|
222
223
|
/** True only for a path a slot owns and requires to be committed. */
|
|
223
224
|
isTracked: (p) => trackingOf(p) === 'tracked',
|
|
224
|
-
|
|
225
|
+
// The app's own database functions (hfs.json sides.be.dbFunctions) join the canon's list (R334).
|
|
226
|
+
ruleParams: () => withDeclaredDbFunctions(ruleParams(manifest, profile, edition), repo.dbFunctions),
|
|
225
227
|
allowedImports: (tier) => manifest.tiers[profile]?.[tier]?.mayImport ?? null,
|
|
226
228
|
});
|
|
227
229
|
}
|
|
@@ -235,13 +237,17 @@ function createScopeResolver(manifest, repo) {
|
|
|
235
237
|
*/
|
|
236
238
|
export function createSlotResolver(manifest, repo) {
|
|
237
239
|
if (repo.profile !== APP_SCOPE) return createScopeResolver(manifest, repo);
|
|
238
|
-
// The root declares no connection of its own, yet a provider slot of the app profile
|
|
240
|
+
// The root declares no connection of its own, yet a provider slot of the app profile is enabled by a
|
|
239
241
|
// side's connection with that provider: the root scope reads the union of the sides' connections.
|
|
240
242
|
const root = createScopeResolver(manifest, { ...repo, connections: SIDES.flatMap((side) => repo.sides[side].connections) });
|
|
241
243
|
const sides = Object.fromEntries(PROFILES.map((side) => [side, createScopeResolver(manifest, repo.sides[side])]));
|
|
242
244
|
return appResolver(repo, root, sides);
|
|
243
245
|
}
|
|
244
246
|
|
|
247
|
+
/** The rule parameters with the app's declared database functions appended to `dbFunctions` (be only), frozen. */
|
|
248
|
+
const withDeclaredDbFunctions = (params, declared = []) => (params.dbFunctions === undefined && !declared.length ? params
|
|
249
|
+
: Object.freeze({ ...params, dbFunctions: Object.freeze([...(params.dbFunctions ?? []), ...declared]) }));
|
|
250
|
+
|
|
245
251
|
/** The rule parameters of one profile (be: infraOwners, suffixes, bannedSuffixes and the rest over the shared ruleParams.common fileLines and duplicateBlock; fe: common alone or with its overrides; runtime: ruleParams.runtime of a runtime manifest), as a frozen deep copy. Under `edition` lite the `lite` overrides of ruleParams.<profile> merge over the base (the `lite` key itself is never returned). */
|
|
246
252
|
export function ruleParams(manifest, profile, edition = 'full') {
|
|
247
253
|
const profiles = manifestKind(manifest) === RUNTIME_KIND ? [RUNTIME_KIND] : PROFILES;
|
|
@@ -100,7 +100,7 @@ const SECRET_NAME_TEST = NAME_WORD(SECRET_WORD, String.raw`(?:[_\-.]|[A-Z]|[^A-Z
|
|
|
100
100
|
const BENIGN_TAIL_TEST = NAME_WORD(BENIGN_WORD, '$');
|
|
101
101
|
|
|
102
102
|
/** True when a bare variable `name` holds secret material as an identifier segment (DB_PASSWORD, dbPassword,
|
|
103
|
-
*
|
|
103
|
+
* STORAGE_SECRET_ACCESS_KEY) and does not end in a config suffix (PASSWORD_MIN_LENGTH, SECRET_FILE,
|
|
104
104
|
* tokenBudget). The same name judgement the `assigned-secret` patterns make, for callers that read keys. */
|
|
105
105
|
export const secretNameLike = (name) => SECRET_NAME_TEST.test(name) && !BENIGN_TAIL_TEST.test(name);
|
|
106
106
|
|
|
@@ -117,7 +117,7 @@ export const SECRET_PATTERNS = [
|
|
|
117
117
|
{ name: 'jwt', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
|
|
118
118
|
{ name: 'age-secret-key', re: /\bAGE-SECRET-KEY-1[0-9A-Z]{20,}\b/ },
|
|
119
119
|
{ name: 'password-connection-string', re: /\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis):\/\/[^:\s/@]+:[^@\s/${}]{8,}@/iu },
|
|
120
|
-
// A value written `env(NAME)` (
|
|
120
|
+
// A value written `env(NAME)` (a config reference form) names a variable, not a secret.
|
|
121
121
|
// A keyword-assigned value that names itself a stand-in (a test stub's `accessToken: "fixture-..."`) is no
|
|
122
122
|
// candidate; only this heuristic takes the exemption, never a provider-shaped token above.
|
|
123
123
|
// A spec file's keyword-assigned values are test inputs (a spec's sign-in
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
|
|
4
|
-
const CACHE = new Map();
|
|
5
|
-
|
|
6
|
-
/** A static TypeScript property name, as emitted by `supabase gen types typescript`. */
|
|
7
|
-
const propertyName = (typescript, name) => (typescript.isIdentifier(name) || typescript.isStringLiteralLike(name) ? name.text : null);
|
|
8
|
-
|
|
9
|
-
/** The type-literal members below property `name`, or null when the generated shape is not statically readable. */
|
|
10
|
-
const propertyMembers = (typescript, members, name) => {
|
|
11
|
-
const property = members.find(member => typescript.isPropertySignature(member) && propertyName(typescript, member.name) === name);
|
|
12
|
-
return property?.type && typescript.isTypeLiteralNode(property.type) ? property.type.members : null;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
function addTableNames(typescript, members, tables) {
|
|
16
|
-
if (!members) return;
|
|
17
|
-
for (const member of members) {
|
|
18
|
-
if (!typescript.isPropertySignature(member)) continue;
|
|
19
|
-
const name = propertyName(typescript, member.name);
|
|
20
|
-
if (name) tables.add(name.toLowerCase());
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function readTableNames(typescript, file, tables) {
|
|
25
|
-
const source = typescript.createSourceFile(file, fs.readFileSync(file, 'utf8'), typescript.ScriptTarget.Latest, true, typescript.ScriptKind.TS);
|
|
26
|
-
if (source.parseDiagnostics.length !== 0) return;
|
|
27
|
-
const database = source.statements.find(statement => typescript.isTypeAliasDeclaration(statement) && statement.name.text === 'Database');
|
|
28
|
-
const databaseMembers = database && typescript.isTypeLiteralNode(database.type) ? database.type.members : null;
|
|
29
|
-
const publicMembers = databaseMembers ? propertyMembers(typescript, databaseMembers, 'public') : null;
|
|
30
|
-
const tableMembers = publicMembers ? propertyMembers(typescript, publicMembers, 'Tables') : null;
|
|
31
|
-
addTableNames(typescript, tableMembers, tables);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* The lower-case keys of `Database['public']['Tables']`, parsed with the architecture context's target compiler.
|
|
36
|
-
* An absent, malformed or unreadable contract proves no table. The result is cached once per app root.
|
|
37
|
-
*/
|
|
38
|
-
export function supabaseTablesOf(appRoot, typescript) {
|
|
39
|
-
const root = path.resolve(appRoot);
|
|
40
|
-
if (CACHE.has(root)) return CACHE.get(root);
|
|
41
|
-
const tables = new Set();
|
|
42
|
-
const file = path.join(root, 'supabase', 'types', 'database.types.ts');
|
|
43
|
-
try {
|
|
44
|
-
readTableNames(typescript, file, tables);
|
|
45
|
-
} catch {
|
|
46
|
-
// Missing and unreadable generated contracts are fail-closed: no table is proven.
|
|
47
|
-
}
|
|
48
|
-
CACHE.set(root, tables);
|
|
49
|
-
return tables;
|
|
50
|
-
}
|