@ankhorage/infra 3.3.0 → 4.0.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.
- package/CHANGELOG.md +6 -0
- package/README.md +1 -7
- package/dist/adapters/minikube/index.d.ts.map +1 -1
- package/dist/adapters/minikube/index.js +2 -16
- package/dist/adapters/minikube/index.js.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/infraValidation.d.ts +1 -0
- package/dist/infraValidation.d.ts.map +1 -1
- package/dist/infraValidation.js +6 -1
- package/dist/infraValidation.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -7
- package/src/adapters/minikube/index.ts +2 -21
- package/src/apiInfrastructure.test.ts +69 -0
- package/src/generatedApiLedgerCleanup.test.ts +72 -0
- package/src/index.ts +0 -6
- package/src/infraApiValidation.test.ts +42 -0
- package/src/infraValidation.ts +10 -1
- package/src/types.ts +1 -1
- package/dist/generatedApiDatabase.d.ts +0 -20
- package/dist/generatedApiDatabase.d.ts.map +0 -1
- package/dist/generatedApiDatabase.js +0 -343
- package/dist/generatedApiDatabase.js.map +0 -1
- package/src/generatedApiDatabase.test.ts +0 -355
- package/src/generatedApiDatabase.ts +0 -558
|
@@ -1,558 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
DataContractValue,
|
|
3
|
-
DbCollectionDefinition,
|
|
4
|
-
DbFieldDefinition,
|
|
5
|
-
GeneratedApiDefinition,
|
|
6
|
-
GeneratedApiRegistry,
|
|
7
|
-
GeneratedApiResourceDefinition,
|
|
8
|
-
GeneratedApiSeedRecord,
|
|
9
|
-
} from '@ankhorage/contracts';
|
|
10
|
-
|
|
11
|
-
import type { GeneratedInfrastructureFile } from './types';
|
|
12
|
-
|
|
13
|
-
export type GeneratedApiDatabaseDiagnosticCode =
|
|
14
|
-
| 'duplicate-field'
|
|
15
|
-
| 'duplicate-resource-id'
|
|
16
|
-
| 'duplicate-target'
|
|
17
|
-
| 'invalid-default'
|
|
18
|
-
| 'invalid-identifier'
|
|
19
|
-
| 'invalid-primary-key'
|
|
20
|
-
| 'invalid-seed'
|
|
21
|
-
| 'registry-id-mismatch'
|
|
22
|
-
| 'unsupported-policy'
|
|
23
|
-
| 'unsupported-provider';
|
|
24
|
-
|
|
25
|
-
export interface GeneratedApiDatabaseDiagnostic {
|
|
26
|
-
readonly code: GeneratedApiDatabaseDiagnosticCode;
|
|
27
|
-
readonly severity: 'error' | 'warning';
|
|
28
|
-
readonly apiId: string;
|
|
29
|
-
readonly resourceId?: string;
|
|
30
|
-
readonly path?: string;
|
|
31
|
-
readonly message: string;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export interface GeneratedApiDatabaseArtifacts {
|
|
35
|
-
readonly files: readonly GeneratedInfrastructureFile[];
|
|
36
|
-
readonly diagnostics: readonly GeneratedApiDatabaseDiagnostic[];
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
interface GeneratedResourceContext {
|
|
40
|
-
readonly api: GeneratedApiDefinition;
|
|
41
|
-
readonly resource: GeneratedApiResourceDefinition;
|
|
42
|
-
readonly seed: readonly GeneratedApiSeedRecord[];
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
interface GeneratedSeedEntry {
|
|
46
|
-
readonly apiId: string;
|
|
47
|
-
readonly resourceId: string;
|
|
48
|
-
readonly collection: DbCollectionDefinition;
|
|
49
|
-
readonly records: readonly GeneratedApiSeedRecord[];
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const DEFAULT_DATABASE_SCHEMA = 'public';
|
|
53
|
-
const SQL_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
54
|
-
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
55
|
-
|
|
56
|
-
export function generateGeneratedApiDatabaseArtifacts(args: {
|
|
57
|
-
readonly generatedApis: GeneratedApiRegistry | undefined;
|
|
58
|
-
readonly databaseProvider: string | undefined;
|
|
59
|
-
}): GeneratedApiDatabaseArtifacts {
|
|
60
|
-
const contexts = listGeneratedResources(args.generatedApis);
|
|
61
|
-
if (contexts.length === 0) return { files: [], diagnostics: [] };
|
|
62
|
-
|
|
63
|
-
const diagnostics = validateGeneratedApiDatabaseState(
|
|
64
|
-
args.generatedApis ?? {},
|
|
65
|
-
contexts,
|
|
66
|
-
args.databaseProvider,
|
|
67
|
-
);
|
|
68
|
-
if (diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
|
|
69
|
-
return { files: [], diagnostics };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const seedEntries = contexts.map(createSeedEntry);
|
|
73
|
-
const metadata = contexts.map((context) => ({
|
|
74
|
-
apiId: context.api.id,
|
|
75
|
-
database: context.api.database,
|
|
76
|
-
auth: context.api.auth ?? null,
|
|
77
|
-
resourceId: context.resource.id,
|
|
78
|
-
operations: context.resource.operations,
|
|
79
|
-
collection: context.resource.collection,
|
|
80
|
-
policies: context.resource.policies ?? [],
|
|
81
|
-
}));
|
|
82
|
-
|
|
83
|
-
return {
|
|
84
|
-
files: [
|
|
85
|
-
jsonFile('infra/minikube/db/generated-api-resources.json', metadata),
|
|
86
|
-
jsonFile('infra/minikube/db/generated-api-seed.json', seedEntries),
|
|
87
|
-
{
|
|
88
|
-
path: 'infra/minikube/db/migrations/001_generated_api_resources.sql',
|
|
89
|
-
content: generateMigrationSql(contexts),
|
|
90
|
-
},
|
|
91
|
-
{
|
|
92
|
-
path: 'infra/minikube/db/seeds/001_generated_api_seed.sql',
|
|
93
|
-
content: generateSeedSql(seedEntries),
|
|
94
|
-
},
|
|
95
|
-
{
|
|
96
|
-
path: 'infra/minikube/db/README.md',
|
|
97
|
-
content: generateReadme(contexts),
|
|
98
|
-
},
|
|
99
|
-
],
|
|
100
|
-
diagnostics,
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function listGeneratedResources(
|
|
105
|
-
registry: GeneratedApiRegistry | undefined,
|
|
106
|
-
): readonly GeneratedResourceContext[] {
|
|
107
|
-
return Object.values(registry ?? {})
|
|
108
|
-
.sort((left, right) => left.id.localeCompare(right.id))
|
|
109
|
-
.flatMap((api) =>
|
|
110
|
-
[...api.resources]
|
|
111
|
-
.sort((left, right) => left.id.localeCompare(right.id))
|
|
112
|
-
.map((resource) => ({ api, resource, seed: resource.seed ?? [] })),
|
|
113
|
-
);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function validateGeneratedApiDatabaseState(
|
|
117
|
-
registry: GeneratedApiRegistry,
|
|
118
|
-
contexts: readonly GeneratedResourceContext[],
|
|
119
|
-
databaseProvider: string | undefined,
|
|
120
|
-
): readonly GeneratedApiDatabaseDiagnostic[] {
|
|
121
|
-
const diagnostics: GeneratedApiDatabaseDiagnostic[] = [];
|
|
122
|
-
const targets = new Map<string, GeneratedResourceContext>();
|
|
123
|
-
const resourceIdsByApi = new Map<string, Set<string>>();
|
|
124
|
-
|
|
125
|
-
if (databaseProvider !== 'supabase') {
|
|
126
|
-
diagnostics.push({
|
|
127
|
-
code: 'unsupported-provider',
|
|
128
|
-
severity: 'error',
|
|
129
|
-
apiId: contexts[0]?.api.id ?? 'generated-api',
|
|
130
|
-
path: 'infra.database.provider',
|
|
131
|
-
message: 'Generated API database resources currently require the supabase provider.',
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
for (const [registryId, api] of Object.entries(registry)) {
|
|
136
|
-
if (registryId !== api.id) {
|
|
137
|
-
diagnostics.push({
|
|
138
|
-
code: 'registry-id-mismatch',
|
|
139
|
-
severity: 'error',
|
|
140
|
-
apiId: api.id,
|
|
141
|
-
path: `generatedApis.${registryId}.id`,
|
|
142
|
-
message: `Generated API registry key '${registryId}' does not match definition id '${api.id}'.`,
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
for (const context of contexts) {
|
|
148
|
-
const { api, resource } = context;
|
|
149
|
-
const resourceIds = resourceIdsByApi.get(api.id) ?? new Set<string>();
|
|
150
|
-
if (resourceIds.has(resource.id)) {
|
|
151
|
-
diagnostics.push(
|
|
152
|
-
resourceDiagnostic(
|
|
153
|
-
context,
|
|
154
|
-
'duplicate-resource-id',
|
|
155
|
-
'id',
|
|
156
|
-
`Resource ID '${resource.id}' is duplicated.`,
|
|
157
|
-
),
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
resourceIds.add(resource.id);
|
|
161
|
-
resourceIdsByApi.set(api.id, resourceIds);
|
|
162
|
-
|
|
163
|
-
validateIdentifier(context, 'collection.name', resource.collection.name, diagnostics);
|
|
164
|
-
validateIdentifier(
|
|
165
|
-
context,
|
|
166
|
-
'collection.schema',
|
|
167
|
-
resource.collection.schema ?? DEFAULT_DATABASE_SCHEMA,
|
|
168
|
-
diagnostics,
|
|
169
|
-
);
|
|
170
|
-
validateFields(context, diagnostics);
|
|
171
|
-
validatePrimaryKey(context, diagnostics);
|
|
172
|
-
validateSeeds(context, diagnostics);
|
|
173
|
-
|
|
174
|
-
const target = `${resource.collection.schema ?? DEFAULT_DATABASE_SCHEMA}.${resource.collection.name}`;
|
|
175
|
-
const previous = targets.get(target);
|
|
176
|
-
if (previous !== undefined) {
|
|
177
|
-
diagnostics.push(
|
|
178
|
-
resourceDiagnostic(
|
|
179
|
-
context,
|
|
180
|
-
'duplicate-target',
|
|
181
|
-
'collection',
|
|
182
|
-
`Database target '${target}' is already owned by ${previous.api.id}/${previous.resource.id}.`,
|
|
183
|
-
),
|
|
184
|
-
);
|
|
185
|
-
} else {
|
|
186
|
-
targets.set(target, context);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if ((resource.policies?.length ?? 0) > 0) {
|
|
190
|
-
diagnostics.push(
|
|
191
|
-
resourceDiagnostic(
|
|
192
|
-
context,
|
|
193
|
-
'unsupported-policy',
|
|
194
|
-
'policies',
|
|
195
|
-
'Policy references enable RLS, but the canonical contract does not yet contain provider-owned SQL policy expressions; no CREATE POLICY statement is emitted.',
|
|
196
|
-
'warning',
|
|
197
|
-
),
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
return diagnostics;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function validateFields(
|
|
206
|
-
context: GeneratedResourceContext,
|
|
207
|
-
diagnostics: GeneratedApiDatabaseDiagnostic[],
|
|
208
|
-
): void {
|
|
209
|
-
const fieldNames = new Set<string>();
|
|
210
|
-
for (const field of context.resource.collection.fields) {
|
|
211
|
-
validateIdentifier(context, `collection.fields.${field.name}.name`, field.name, diagnostics);
|
|
212
|
-
if (fieldNames.has(field.name)) {
|
|
213
|
-
diagnostics.push(
|
|
214
|
-
resourceDiagnostic(
|
|
215
|
-
context,
|
|
216
|
-
'duplicate-field',
|
|
217
|
-
`collection.fields.${field.name}`,
|
|
218
|
-
`Field '${field.name}' is duplicated.`,
|
|
219
|
-
),
|
|
220
|
-
);
|
|
221
|
-
}
|
|
222
|
-
fieldNames.add(field.name);
|
|
223
|
-
|
|
224
|
-
if (!isCompatibleDefault(field)) {
|
|
225
|
-
diagnostics.push(
|
|
226
|
-
resourceDiagnostic(
|
|
227
|
-
context,
|
|
228
|
-
'invalid-default',
|
|
229
|
-
`collection.fields.${field.name}.defaultValue`,
|
|
230
|
-
`Default value for '${field.name}' is incompatible with field type '${field.type}'.`,
|
|
231
|
-
),
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
function validatePrimaryKey(
|
|
238
|
-
context: GeneratedResourceContext,
|
|
239
|
-
diagnostics: GeneratedApiDatabaseDiagnostic[],
|
|
240
|
-
): void {
|
|
241
|
-
const { primaryKey } = context.resource.collection;
|
|
242
|
-
if (primaryKey === undefined) return;
|
|
243
|
-
|
|
244
|
-
validateIdentifier(context, 'collection.primaryKey', primaryKey, diagnostics);
|
|
245
|
-
if (!context.resource.collection.fields.some((field) => field.name === primaryKey)) {
|
|
246
|
-
diagnostics.push(
|
|
247
|
-
resourceDiagnostic(
|
|
248
|
-
context,
|
|
249
|
-
'invalid-primary-key',
|
|
250
|
-
'collection.primaryKey',
|
|
251
|
-
`Primary key '${primaryKey}' must reference a declared field.`,
|
|
252
|
-
),
|
|
253
|
-
);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
function validateSeeds(
|
|
258
|
-
context: GeneratedResourceContext,
|
|
259
|
-
diagnostics: GeneratedApiDatabaseDiagnostic[],
|
|
260
|
-
): void {
|
|
261
|
-
const fields = new Map(context.resource.collection.fields.map((field) => [field.name, field]));
|
|
262
|
-
const { primaryKey } = context.resource.collection;
|
|
263
|
-
|
|
264
|
-
context.seed.forEach((record, index) => {
|
|
265
|
-
for (const key of Object.keys(record)) {
|
|
266
|
-
if (!fields.has(key)) {
|
|
267
|
-
diagnostics.push(
|
|
268
|
-
resourceDiagnostic(
|
|
269
|
-
context,
|
|
270
|
-
'invalid-seed',
|
|
271
|
-
`seed.${index}.${key}`,
|
|
272
|
-
`Seed field '${key}' is not declared by the collection.`,
|
|
273
|
-
),
|
|
274
|
-
);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
for (const field of fields.values()) {
|
|
279
|
-
const value = record[field.name];
|
|
280
|
-
const generatedUuidPrimaryKey =
|
|
281
|
-
field.name === primaryKey && field.type === 'uuid' && value === undefined;
|
|
282
|
-
const requiresNonNullValue = field.required === true || field.name === primaryKey;
|
|
283
|
-
|
|
284
|
-
if (value === undefined) {
|
|
285
|
-
if (requiresNonNullValue && field.defaultValue === undefined && !generatedUuidPrimaryKey) {
|
|
286
|
-
diagnostics.push(
|
|
287
|
-
resourceDiagnostic(
|
|
288
|
-
context,
|
|
289
|
-
'invalid-seed',
|
|
290
|
-
`seed.${index}.${field.name}`,
|
|
291
|
-
`Seed record is missing required field '${field.name}'.`,
|
|
292
|
-
),
|
|
293
|
-
);
|
|
294
|
-
}
|
|
295
|
-
continue;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
if (value === null) {
|
|
299
|
-
if (requiresNonNullValue) {
|
|
300
|
-
diagnostics.push(
|
|
301
|
-
resourceDiagnostic(
|
|
302
|
-
context,
|
|
303
|
-
'invalid-seed',
|
|
304
|
-
`seed.${index}.${field.name}`,
|
|
305
|
-
`Seed field '${field.name}' cannot be null.`,
|
|
306
|
-
),
|
|
307
|
-
);
|
|
308
|
-
}
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
if (!isCompatibleFieldValue(field, value)) {
|
|
313
|
-
diagnostics.push(
|
|
314
|
-
resourceDiagnostic(
|
|
315
|
-
context,
|
|
316
|
-
'invalid-seed',
|
|
317
|
-
`seed.${index}.${field.name}`,
|
|
318
|
-
`Seed value for '${field.name}' is incompatible with field type '${field.type}'.`,
|
|
319
|
-
),
|
|
320
|
-
);
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
function validateIdentifier(
|
|
327
|
-
context: GeneratedResourceContext,
|
|
328
|
-
path: string,
|
|
329
|
-
value: string,
|
|
330
|
-
diagnostics: GeneratedApiDatabaseDiagnostic[],
|
|
331
|
-
): void {
|
|
332
|
-
if (SQL_IDENTIFIER_RE.test(value)) return;
|
|
333
|
-
diagnostics.push(
|
|
334
|
-
resourceDiagnostic(
|
|
335
|
-
context,
|
|
336
|
-
'invalid-identifier',
|
|
337
|
-
path,
|
|
338
|
-
`Database identifier '${value}' must match ${SQL_IDENTIFIER_RE.source}.`,
|
|
339
|
-
),
|
|
340
|
-
);
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
function resourceDiagnostic(
|
|
344
|
-
context: GeneratedResourceContext,
|
|
345
|
-
code: GeneratedApiDatabaseDiagnosticCode,
|
|
346
|
-
path: string,
|
|
347
|
-
message: string,
|
|
348
|
-
severity: GeneratedApiDatabaseDiagnostic['severity'] = 'error',
|
|
349
|
-
): GeneratedApiDatabaseDiagnostic {
|
|
350
|
-
return {
|
|
351
|
-
code,
|
|
352
|
-
severity,
|
|
353
|
-
apiId: context.api.id,
|
|
354
|
-
resourceId: context.resource.id,
|
|
355
|
-
path: `generatedApis.${context.api.id}.resources.${context.resource.id}.${path}`,
|
|
356
|
-
message,
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
function isCompatibleDefault(field: DbFieldDefinition): boolean {
|
|
361
|
-
const value = field.defaultValue;
|
|
362
|
-
if (value === undefined || value === null) return true;
|
|
363
|
-
return isCompatibleFieldValue(field, value);
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
function isCompatibleFieldValue(field: DbFieldDefinition, value: DataContractValue): boolean {
|
|
367
|
-
switch (field.type) {
|
|
368
|
-
case 'boolean':
|
|
369
|
-
return typeof value === 'boolean';
|
|
370
|
-
case 'number':
|
|
371
|
-
return typeof value === 'number' && Number.isFinite(value);
|
|
372
|
-
case 'text':
|
|
373
|
-
return typeof value === 'string';
|
|
374
|
-
case 'datetime':
|
|
375
|
-
return typeof value === 'string' && Number.isFinite(Date.parse(value));
|
|
376
|
-
case 'uuid':
|
|
377
|
-
return typeof value === 'string' && UUID_RE.test(value);
|
|
378
|
-
case 'json':
|
|
379
|
-
return true;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
function createSeedEntry(context: GeneratedResourceContext): GeneratedSeedEntry {
|
|
384
|
-
return {
|
|
385
|
-
apiId: context.api.id,
|
|
386
|
-
resourceId: context.resource.id,
|
|
387
|
-
collection: context.resource.collection,
|
|
388
|
-
records: context.seed.map((record, index) => materializeSeedRecord(context, record, index)),
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
function materializeSeedRecord(
|
|
393
|
-
context: GeneratedResourceContext,
|
|
394
|
-
record: GeneratedApiSeedRecord,
|
|
395
|
-
index: number,
|
|
396
|
-
): GeneratedApiSeedRecord {
|
|
397
|
-
const { primaryKey } = context.resource.collection;
|
|
398
|
-
if (primaryKey === undefined || record[primaryKey] !== undefined) return record;
|
|
399
|
-
|
|
400
|
-
const primaryKeyField = context.resource.collection.fields.find(
|
|
401
|
-
(field) => field.name === primaryKey,
|
|
402
|
-
);
|
|
403
|
-
if (primaryKeyField?.type !== 'uuid') return record;
|
|
404
|
-
|
|
405
|
-
return {
|
|
406
|
-
...record,
|
|
407
|
-
[primaryKey]: createDeterministicSeedUuid(context.api.id, context.resource.id, index),
|
|
408
|
-
};
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
function generateMigrationSql(contexts: readonly GeneratedResourceContext[]): string {
|
|
412
|
-
const statements = contexts.flatMap((context) => {
|
|
413
|
-
const schema = quoteIdentifier(context.resource.collection.schema ?? DEFAULT_DATABASE_SCHEMA);
|
|
414
|
-
const table = quoteIdentifier(context.resource.collection.name);
|
|
415
|
-
const columns = context.resource.collection.fields.map((field) =>
|
|
416
|
-
formatColumn(field, field.name === context.resource.collection.primaryKey),
|
|
417
|
-
);
|
|
418
|
-
const rls =
|
|
419
|
-
(context.resource.policies?.length ?? 0) > 0
|
|
420
|
-
? [`alter table ${schema}.${table} enable row level security;`]
|
|
421
|
-
: [];
|
|
422
|
-
|
|
423
|
-
return [
|
|
424
|
-
`create schema if not exists ${schema};`,
|
|
425
|
-
`create table if not exists ${schema}.${table} (\n ${columns.join(',\n ')}\n);`,
|
|
426
|
-
...rls,
|
|
427
|
-
];
|
|
428
|
-
});
|
|
429
|
-
|
|
430
|
-
return [
|
|
431
|
-
'-- Generated from canonical GeneratedApiDefinition resources.',
|
|
432
|
-
'-- No HTTP/GraphQL service or Kubernetes API workload is generated here.',
|
|
433
|
-
'create extension if not exists pgcrypto;',
|
|
434
|
-
'',
|
|
435
|
-
...statements,
|
|
436
|
-
'',
|
|
437
|
-
].join('\n');
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
function generateSeedSql(entries: readonly GeneratedSeedEntry[]): string {
|
|
441
|
-
const statements = entries.flatMap((entry) => createSeedStatements(entry));
|
|
442
|
-
return [
|
|
443
|
-
'-- Generated from canonical generated API seed records.',
|
|
444
|
-
...(statements.length === 0 ? ['-- No generated API seed records configured.'] : statements),
|
|
445
|
-
'',
|
|
446
|
-
].join('\n');
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
function createSeedStatements(entry: GeneratedSeedEntry): readonly string[] {
|
|
450
|
-
if (entry.records.length === 0) return [];
|
|
451
|
-
|
|
452
|
-
const fields = entry.collection.fields.filter((field) =>
|
|
453
|
-
entry.records.some((record) => record[field.name] !== undefined),
|
|
454
|
-
);
|
|
455
|
-
if (fields.length === 0) return [];
|
|
456
|
-
|
|
457
|
-
const schema = quoteIdentifier(entry.collection.schema ?? DEFAULT_DATABASE_SCHEMA);
|
|
458
|
-
const table = quoteIdentifier(entry.collection.name);
|
|
459
|
-
const values = entry.records
|
|
460
|
-
.map(
|
|
461
|
-
(record) =>
|
|
462
|
-
`(${fields.map((field) => formatSeedValue(field, record[field.name])).join(', ')})`,
|
|
463
|
-
)
|
|
464
|
-
.join(',\n ');
|
|
465
|
-
const conflict =
|
|
466
|
-
entry.collection.primaryKey === undefined
|
|
467
|
-
? 'on conflict do nothing'
|
|
468
|
-
: `on conflict (${quoteIdentifier(entry.collection.primaryKey)}) do nothing`;
|
|
469
|
-
|
|
470
|
-
return [
|
|
471
|
-
`insert into ${schema}.${table} (${fields.map((field) => quoteIdentifier(field.name)).join(', ')}) values\n ${values}\n${conflict};`,
|
|
472
|
-
];
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
function formatSeedValue(field: DbFieldDefinition, value: DataContractValue | undefined): string {
|
|
476
|
-
if (value === undefined) return 'default';
|
|
477
|
-
return formatFieldValue(field, value);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
function formatColumn(field: DbFieldDefinition, primaryKey: boolean): string {
|
|
481
|
-
const defaultValue = formatDefault(field, primaryKey);
|
|
482
|
-
const primaryKeyClause = primaryKey ? ' primary key' : '';
|
|
483
|
-
const required = field.required === true && !primaryKey ? ' not null' : '';
|
|
484
|
-
const unique = field.unique === true && !primaryKey ? ' unique' : '';
|
|
485
|
-
return `${quoteIdentifier(field.name)} ${mapFieldType(field.type)}${defaultValue}${primaryKeyClause}${required}${unique}`;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
function mapFieldType(type: DbFieldDefinition['type']): string {
|
|
489
|
-
if (type === 'uuid') return 'uuid';
|
|
490
|
-
if (type === 'text') return 'text';
|
|
491
|
-
if (type === 'number') return 'numeric';
|
|
492
|
-
if (type === 'boolean') return 'boolean';
|
|
493
|
-
if (type === 'datetime') return 'timestamptz';
|
|
494
|
-
return 'jsonb';
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
function formatDefault(field: DbFieldDefinition, primaryKey: boolean): string {
|
|
498
|
-
if (primaryKey && field.type === 'uuid' && field.defaultValue === undefined) {
|
|
499
|
-
return ' default gen_random_uuid()';
|
|
500
|
-
}
|
|
501
|
-
if (field.defaultValue === undefined) return '';
|
|
502
|
-
return ` default ${formatFieldValue(field, field.defaultValue)}`;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
function formatFieldValue(field: DbFieldDefinition, value: DataContractValue): string {
|
|
506
|
-
if (value === null) return 'null';
|
|
507
|
-
if (field.type === 'json') {
|
|
508
|
-
return `'${escapeString(JSON.stringify(value))}'::jsonb`;
|
|
509
|
-
}
|
|
510
|
-
return formatValue(value);
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
function formatValue(value: DataContractValue): string {
|
|
514
|
-
if (value === null) return 'null';
|
|
515
|
-
if (typeof value === 'string') return `'${escapeString(value)}'`;
|
|
516
|
-
if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'null';
|
|
517
|
-
if (typeof value === 'boolean') return value ? 'true' : 'false';
|
|
518
|
-
return `'${escapeString(JSON.stringify(value))}'::jsonb`;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
function generateReadme(contexts: readonly GeneratedResourceContext[]): string {
|
|
522
|
-
const resources = contexts
|
|
523
|
-
.map((context) => {
|
|
524
|
-
const { collection } = context.resource;
|
|
525
|
-
return `- \`${context.api.id}/${context.resource.id}\` -> \`${collection.schema ?? DEFAULT_DATABASE_SCHEMA}.${collection.name}\``;
|
|
526
|
-
})
|
|
527
|
-
.join('\n');
|
|
528
|
-
|
|
529
|
-
return `# Generated API Database Artifacts\n\nThese files materialize canonical generated API resources into Supabase/Postgres database infrastructure.\n\n${resources}\n\nNo HTTP/GraphQL server, Docker image, application handler, OpenAPI document, Kubernetes Deployment or Service is generated by this bridge.\n`;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
function jsonFile(path: string, value: unknown): GeneratedInfrastructureFile {
|
|
533
|
-
return { path, content: `${JSON.stringify(value, null, 2)}\n` };
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
function quoteIdentifier(identifier: string): string {
|
|
537
|
-
return `"${identifier.replaceAll('"', '""')}"`;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
function escapeString(value: string): string {
|
|
541
|
-
return value.replaceAll("'", "''");
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
function createDeterministicSeedUuid(apiId: string, resourceId: string, index: number): string {
|
|
545
|
-
const input = `${apiId}:${resourceId}:${index}`;
|
|
546
|
-
const hex = `${hashHex(input, 0)}${hashHex(input, 1)}${hashHex(input, 2)}${hashHex(input, 3)}`;
|
|
547
|
-
const variant = ((Number.parseInt(hex.charAt(16), 16) & 0x3) | 0x8).toString(16);
|
|
548
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
function hashHex(input: string, salt: number): string {
|
|
552
|
-
let hash = 2166136261 ^ salt;
|
|
553
|
-
for (const char of input) {
|
|
554
|
-
hash ^= char.charCodeAt(0);
|
|
555
|
-
hash = Math.imul(hash, 16777619);
|
|
556
|
-
}
|
|
557
|
-
return (hash >>> 0).toString(16).padStart(8, '0');
|
|
558
|
-
}
|