@ankhorage/infra 1.1.0 → 2.0.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 +12 -0
- package/README.md +4 -1
- package/dist/adapters/minikube/auth/oauthRuntime.js +6 -12
- package/dist/adapters/minikube/auth/oauthRuntime.js.map +1 -1
- package/dist/adapters/minikube/index.d.ts.map +1 -1
- package/dist/adapters/minikube/index.js +13 -5
- package/dist/adapters/minikube/index.js.map +1 -1
- package/dist/generatedApiDatabase.d.ts +20 -0
- package/dist/generatedApiDatabase.d.ts.map +1 -0
- package/dist/generatedApiDatabase.js +343 -0
- package/dist/generatedApiDatabase.js.map +1 -0
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/project.d.ts +1 -1
- package/dist/project.d.ts.map +1 -1
- package/dist/project.js +3 -0
- package/dist/project.js.map +1 -1
- package/dist/testSupport.d.ts.map +1 -1
- package/dist/testSupport.js +1 -0
- package/dist/testSupport.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 +2 -2
- package/src/adapters/minikube/auth/oauthRuntime.ts +6 -12
- package/src/adapters/minikube/auth/supabase/oauthRuntime.test.ts +17 -6
- package/src/adapters/minikube/index.ts +18 -5
- package/src/generatedApiDatabase.test.ts +355 -0
- package/src/generatedApiDatabase.ts +558 -0
- package/src/index.ts +6 -2
- package/src/project.ts +3 -1
- package/src/testSupport.ts +1 -0
- package/src/types.ts +1 -1
- package/dist/apiArtifacts.d.ts +0 -8
- package/dist/apiArtifacts.d.ts.map +0 -1
- package/dist/apiArtifacts.js +0 -35
- package/dist/apiArtifacts.js.map +0 -1
- package/dist/apis.d.ts +0 -11
- package/dist/apis.d.ts.map +0 -1
- package/dist/apis.js +0 -354
- package/dist/apis.js.map +0 -1
- package/src/apiArtifacts.test.ts +0 -54
- package/src/apiArtifacts.ts +0 -107
- package/src/apis.test.ts +0 -212
- package/src/apis.ts +0 -534
|
@@ -0,0 +1,558 @@
|
|
|
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
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,8 +6,6 @@ import type {
|
|
|
6
6
|
InfrastructureGenerationResult,
|
|
7
7
|
} from './types';
|
|
8
8
|
|
|
9
|
-
export type { ApiInfrastructureArtifacts } from './apiArtifacts';
|
|
10
|
-
export { generateApiInfrastructureArtifacts } from './apiArtifacts';
|
|
11
9
|
export {
|
|
12
10
|
type AuthRedirectConfiguration,
|
|
13
11
|
type AuthRedirectEnvironment,
|
|
@@ -16,6 +14,12 @@ export {
|
|
|
16
14
|
resolveAuthRedirectConfiguration,
|
|
17
15
|
type ResolveAuthRedirectConfigurationInput,
|
|
18
16
|
} from './authRedirects';
|
|
17
|
+
export {
|
|
18
|
+
type GeneratedApiDatabaseArtifacts,
|
|
19
|
+
type GeneratedApiDatabaseDiagnostic,
|
|
20
|
+
type GeneratedApiDatabaseDiagnosticCode,
|
|
21
|
+
generateGeneratedApiDatabaseArtifacts,
|
|
22
|
+
} from './generatedApiDatabase';
|
|
19
23
|
export {
|
|
20
24
|
createInfraSecretStoreAdapter,
|
|
21
25
|
type CreateInfraSecretStoreAdapterInput,
|
package/src/project.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { APP_CATEGORIES, type AppManifest, type NavigatorSpec } from '@ankhorage/contracts';
|
|
2
2
|
import { promises as fs } from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
|
|
@@ -70,6 +70,7 @@ function createFallbackManifest(projectId: string): AppManifest {
|
|
|
70
70
|
name: projectId,
|
|
71
71
|
slug: projectId,
|
|
72
72
|
version: '0.0.0',
|
|
73
|
+
category: 'developer_tools',
|
|
73
74
|
themeId: 'default',
|
|
74
75
|
},
|
|
75
76
|
themes: [],
|
|
@@ -187,6 +188,7 @@ function isAppManifestMetadata(value: unknown): value is AppManifest['metadata']
|
|
|
187
188
|
typeof value.name === 'string' &&
|
|
188
189
|
typeof value.slug === 'string' &&
|
|
189
190
|
typeof value.version === 'string' &&
|
|
191
|
+
APP_CATEGORIES.some((category) => category === value.category) &&
|
|
190
192
|
typeof value.themeId === 'string' &&
|
|
191
193
|
(value.created === undefined || typeof value.created === 'string') &&
|
|
192
194
|
(value.updated === undefined || typeof value.updated === 'string')
|
package/src/testSupport.ts
CHANGED
package/src/types.ts
CHANGED
|
@@ -37,7 +37,7 @@ export interface InfrastructureGenerationOptions {
|
|
|
37
37
|
*/
|
|
38
38
|
readonly appManifest?: Pick<
|
|
39
39
|
AppManifest,
|
|
40
|
-
'
|
|
40
|
+
'generatedApis' | 'infra' | 'metadata' | 'navigator' | 'screens' | 'settings'
|
|
41
41
|
>;
|
|
42
42
|
}
|
|
43
43
|
|
package/dist/apiArtifacts.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { AppDataManifest } from '@ankhorage/contracts';
|
|
2
|
-
import { type ApiInfrastructureArtifacts } from './apis';
|
|
3
|
-
export type { ApiInfrastructureArtifacts } from './apis';
|
|
4
|
-
export declare function generateApiInfrastructureArtifacts(args: {
|
|
5
|
-
readonly data: AppDataManifest | undefined;
|
|
6
|
-
readonly databaseProvider: string | undefined;
|
|
7
|
-
}): ApiInfrastructureArtifacts;
|
|
8
|
-
//# sourceMappingURL=apiArtifacts.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"apiArtifacts.d.ts","sourceRoot":"","sources":["../src/apiArtifacts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EACL,KAAK,0BAA0B,EAEhC,MAAM,QAAQ,CAAC;AAIhB,YAAY,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAEzD,wBAAgB,kCAAkC,CAAC,IAAI,EAAE;IACvD,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,SAAS,CAAC;IAC3C,QAAQ,CAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CAC/C,GAAG,0BAA0B,CAW7B"}
|
package/dist/apiArtifacts.js
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { generateApiInfrastructureArtifacts as generateRawApiInfrastructureArtifacts, } from './apis';
|
|
2
|
-
const GENERATED_API_HANDLERS_PATH = 'src/generated/apis/apiHandlers.ts';
|
|
3
|
-
export function generateApiInfrastructureArtifacts(args) {
|
|
4
|
-
const artifacts = generateRawApiInfrastructureArtifacts(args);
|
|
5
|
-
return {
|
|
6
|
-
...artifacts,
|
|
7
|
-
files: artifacts.files.map((file) => file.path === GENERATED_API_HANDLERS_PATH
|
|
8
|
-
? { ...file, content: makeGeneratedApiHandlersLintSafe(file.content) }
|
|
9
|
-
: file),
|
|
10
|
-
};
|
|
11
|
-
}
|
|
12
|
-
function makeGeneratedApiHandlersLintSafe(source) {
|
|
13
|
-
let result = source;
|
|
14
|
-
result = replaceGeneratedSnippet(result, ' async list(apiId: string): Promise<readonly GeneratedApiRecord[]> {', ' list(apiId: string): Promise<readonly GeneratedApiRecord[]> {');
|
|
15
|
-
result = replaceGeneratedSnippet(result, ' return getRows(records, apiId).map(cloneRecord);', ' return Promise.resolve(getRows(records, apiId).map(cloneRecord));');
|
|
16
|
-
result = replaceGeneratedSnippet(result, ' async read(apiId: string, id: string): Promise<GeneratedApiRecord | null> {', ' read(apiId: string, id: string): Promise<GeneratedApiRecord | null> {');
|
|
17
|
-
result = replaceGeneratedSnippet(result, ' if (primaryKey === null) return null;', ' if (primaryKey === null) return Promise.resolve(null);', 3);
|
|
18
|
-
result = replaceGeneratedSnippet(result, ' return record === undefined ? null : cloneRecord(record);', ' return Promise.resolve(record === undefined ? null : cloneRecord(record));');
|
|
19
|
-
result = replaceGeneratedSnippet(result, ' async create(apiId: string, values: GeneratedApiRecord): Promise<GeneratedApiRecord> {', ' create(apiId: string, values: GeneratedApiRecord): Promise<GeneratedApiRecord> {');
|
|
20
|
-
result = replaceGeneratedSnippet(result, ' return cloneRecord(nextRecord);', ' return Promise.resolve(cloneRecord(nextRecord));', 2);
|
|
21
|
-
result = replaceGeneratedSnippet(result, ' async update(\n', ' update(\n');
|
|
22
|
-
result = replaceGeneratedSnippet(result, ' if (index < 0) return null;', ' if (index < 0) return Promise.resolve(null);');
|
|
23
|
-
result = replaceGeneratedSnippet(result, ' async delete(apiId: string, id: string): Promise<GeneratedApiRecord | null> {', ' delete(apiId: string, id: string): Promise<GeneratedApiRecord | null> {');
|
|
24
|
-
result = replaceGeneratedSnippet(result, ' if (deleted === undefined) return null;', ' if (deleted === undefined) return Promise.resolve(null);');
|
|
25
|
-
result = replaceGeneratedSnippet(result, ' return cloneRecord(deleted);', ' return Promise.resolve(cloneRecord(deleted));');
|
|
26
|
-
return result;
|
|
27
|
-
}
|
|
28
|
-
function replaceGeneratedSnippet(source, snippet, replacement, expectedCount = 1) {
|
|
29
|
-
const count = source.split(snippet).length - 1;
|
|
30
|
-
if (count !== expectedCount) {
|
|
31
|
-
throw new Error(`Expected generated API handler snippet ${JSON.stringify(snippet)} ${expectedCount} time(s), found ${count}.`);
|
|
32
|
-
}
|
|
33
|
-
return source.replaceAll(snippet, replacement);
|
|
34
|
-
}
|
|
35
|
-
//# sourceMappingURL=apiArtifacts.js.map
|
package/dist/apiArtifacts.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"apiArtifacts.js","sourceRoot":"","sources":["../src/apiArtifacts.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,kCAAkC,IAAI,qCAAqC,GAC5E,MAAM,QAAQ,CAAC;AAEhB,MAAM,2BAA2B,GAAG,mCAAmC,CAAC;AAIxE,MAAM,UAAU,kCAAkC,CAAC,IAGlD;IACC,MAAM,SAAS,GAAG,qCAAqC,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO;QACL,GAAG,SAAS;QACZ,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAClC,IAAI,CAAC,IAAI,KAAK,2BAA2B;YACvC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,gCAAgC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;YACtE,CAAC,CAAC,IAAI,CACT;KACF,CAAC;AACJ,CAAC;AAED,SAAS,gCAAgC,CAAC,MAAc;IACtD,IAAI,MAAM,GAAG,MAAM,CAAC;IAEpB,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,yEAAyE,EACzE,mEAAmE,CACpE,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,wDAAwD,EACxD,yEAAyE,CAC1E,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,iFAAiF,EACjF,2EAA2E,CAC5E,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,6CAA6C,EAC7C,8DAA8D,EAC9D,CAAC,CACF,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,iEAAiE,EACjE,kFAAkF,CACnF,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,4FAA4F,EAC5F,sFAAsF,CACvF,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,uCAAuC,EACvC,wDAAwD,EACxD,CAAC,CACF,CAAC;IACF,MAAM,GAAG,uBAAuB,CAAC,MAAM,EAAE,qBAAqB,EAAE,eAAe,CAAC,CAAC;IACjF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,mCAAmC,EACnC,oDAAoD,CACrD,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,mFAAmF,EACnF,6EAA6E,CAC9E,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,+CAA+C,EAC/C,gEAAgE,CACjE,CAAC;IACF,MAAM,GAAG,uBAAuB,CAC9B,MAAM,EACN,oCAAoC,EACpC,qDAAqD,CACtD,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,uBAAuB,CAC9B,MAAc,EACd,OAAe,EACf,WAAmB,EACnB,aAAa,GAAG,CAAC;IAEjB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAC/C,IAAI,KAAK,KAAK,aAAa,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CACb,0CAA0C,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,aAAa,mBAAmB,KAAK,GAAG,CAC9G,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import type { AppDataManifest } from '@ankhorage/contracts';\n\nimport {\n type ApiInfrastructureArtifacts,\n generateApiInfrastructureArtifacts as generateRawApiInfrastructureArtifacts,\n} from './apis';\n\nconst GENERATED_API_HANDLERS_PATH = 'src/generated/apis/apiHandlers.ts';\n\nexport type { ApiInfrastructureArtifacts } from './apis';\n\nexport function generateApiInfrastructureArtifacts(args: {\n readonly data: AppDataManifest | undefined;\n readonly databaseProvider: string | undefined;\n}): ApiInfrastructureArtifacts {\n const artifacts = generateRawApiInfrastructureArtifacts(args);\n\n return {\n ...artifacts,\n files: artifacts.files.map((file) =>\n file.path === GENERATED_API_HANDLERS_PATH\n ? { ...file, content: makeGeneratedApiHandlersLintSafe(file.content) }\n : file,\n ),\n };\n}\n\nfunction makeGeneratedApiHandlersLintSafe(source: string): string {\n let result = source;\n\n result = replaceGeneratedSnippet(\n result,\n ' async list(apiId: string): Promise<readonly GeneratedApiRecord[]> {',\n ' list(apiId: string): Promise<readonly GeneratedApiRecord[]> {',\n );\n result = replaceGeneratedSnippet(\n result,\n ' return getRows(records, apiId).map(cloneRecord);',\n ' return Promise.resolve(getRows(records, apiId).map(cloneRecord));',\n );\n result = replaceGeneratedSnippet(\n result,\n ' async read(apiId: string, id: string): Promise<GeneratedApiRecord | null> {',\n ' read(apiId: string, id: string): Promise<GeneratedApiRecord | null> {',\n );\n result = replaceGeneratedSnippet(\n result,\n ' if (primaryKey === null) return null;',\n ' if (primaryKey === null) return Promise.resolve(null);',\n 3,\n );\n result = replaceGeneratedSnippet(\n result,\n ' return record === undefined ? null : cloneRecord(record);',\n ' return Promise.resolve(record === undefined ? null : cloneRecord(record));',\n );\n result = replaceGeneratedSnippet(\n result,\n ' async create(apiId: string, values: GeneratedApiRecord): Promise<GeneratedApiRecord> {',\n ' create(apiId: string, values: GeneratedApiRecord): Promise<GeneratedApiRecord> {',\n );\n result = replaceGeneratedSnippet(\n result,\n ' return cloneRecord(nextRecord);',\n ' return Promise.resolve(cloneRecord(nextRecord));',\n 2,\n );\n result = replaceGeneratedSnippet(result, ' async update(\\n', ' update(\\n');\n result = replaceGeneratedSnippet(\n result,\n ' if (index < 0) return null;',\n ' if (index < 0) return Promise.resolve(null);',\n );\n result = replaceGeneratedSnippet(\n result,\n ' async delete(apiId: string, id: string): Promise<GeneratedApiRecord | null> {',\n ' delete(apiId: string, id: string): Promise<GeneratedApiRecord | null> {',\n );\n result = replaceGeneratedSnippet(\n result,\n ' if (deleted === undefined) return null;',\n ' if (deleted === undefined) return Promise.resolve(null);',\n );\n result = replaceGeneratedSnippet(\n result,\n ' return cloneRecord(deleted);',\n ' return Promise.resolve(cloneRecord(deleted));',\n );\n\n return result;\n}\n\nfunction replaceGeneratedSnippet(\n source: string,\n snippet: string,\n replacement: string,\n expectedCount = 1,\n): string {\n const count = source.split(snippet).length - 1;\n if (count !== expectedCount) {\n throw new Error(\n `Expected generated API handler snippet ${JSON.stringify(snippet)} ${expectedCount} time(s), found ${count}.`,\n );\n }\n\n return source.replaceAll(snippet, replacement);\n}\n"]}
|