This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerate-type-script.ts
471 lines (399 loc) · 14.5 KB
/
generate-type-script.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import { createSeedFunction } from '../lib/SeedFunction'
import { getTemplateInfos, TemplateInfo } from '~/src/templates'
import { File } from '~/src/types'
import { escapeBackticks, indentBlock, sourceCodeSectionHeader, sourceCodeSectionHeader2 } from '~/src/utils'
import endent from 'endent'
import glob from 'fast-glob'
import { log as rootLog } from 'floggy'
import * as FS from 'fs-jetpack'
import { upperFirst } from 'lodash'
import * as Path from 'path'
import * as Prettier from 'prettier'
const log = rootLog.child('generateTypeScript')
const handleKinds = [`kebab`, `pascal`, `camel`, `snake`, `upper`] as const
/**
* Generate TypeScript code for templates in given dir .
*/
const run = async (params: {
templatesRepoDir: string
outputDir: string
prettier: boolean
}): Promise<void> => {
const { templatesRepoDir, outputDir } = params
log.info(`generating type-script code to ${outputDir}`)
const templateInfos = getTemplateInfos({ templatesRepoDir })
log.info(`Found templates:`, { templates: templateInfos.map((t) => t.displayName) })
const fileOutputs: File[] = []
fileOutputs.push({
path: Path.join(outputDir, `index.ts`),
content: endent`
export * as Generated from './index_'
`,
})
fileOutputs.push({
path: Path.join(outputDir, `index_.ts`),
content: endent`
export * as Templates from './templates'
export * as Types from './types'
`,
})
fileOutputs.push({
path: Path.join(outputDir, `types.ts`),
content: endent`
import * as Templates from './templates'
export type TemplateByName = {
${templateInfos
.map((_) => {
return endent`
"${_.handles.pascal.value}": Templates.${_.handles.pascal.value}
`
})
.join('\n')}
}
export type TemplateParametersByName = {
${templateInfos
.map((_) => {
return endent`
"${_.handles.pascal.value}": Templates.${_.handles.pascal.value}.Parameters
`
})
.join('\n')}
}
export type TemplateClassByName = {
${templateInfos
.map((_) => {
return endent`
"${_.handles.pascal.value}": typeof Templates.${_.handles.pascal.value}
`
})
.join('\n')}
}
export type TemplateClass =
${templateInfos
.map((_) => {
return endent`
| typeof Templates.${_.handles.pascal.value}
`
})
.join('\n')}
export type Template =
${templateInfos
.map((_) => {
return endent`
| Templates.${_.handles.pascal.value}
`
})
.join('\n')}
export type TemplateTag =
${templateInfos
.map((_) => {
return endent`
| Templates.${_.handles.pascal.value}.Tag
`
})
.join('\n')}
export const TemplateTag = [
${templateInfos.map((_) => `Templates.${_.handles.pascal.value}._tag,`).join('\n')}
] as const
export namespace TemplateHandle {
${handleKinds
.map(
// prettier-ignore
(handleKind) => `export const ${upperFirst(handleKind)} = [${templateInfos.map((_) => `'${_.handles[handleKind].value}'`).join(`, `)}] as const`
)
.join(`\n`)}
${handleKinds
.map(
// prettier-ignore
(handleKind) => `export type ${upperFirst(handleKind)} = ${templateInfos.map((_) => `'${_.handles[handleKind].value}'`).join(` | `)}`
)
.join(`\n`)}
}
/**
* Convert between template metadata handle formats in a type-safe way.
*/
export const handleMap = {
${templateInfos
.map((templateInfo) => {
return Object.entries(templateInfo.handles)
.map(([k, item]) => {
if (k === 'kebab' && templateInfo.handles.kebab.value === templateInfo.handles.camel.value)
return null
if (k === 'snake' && templateInfo.handles.snake.value === templateInfo.handles.camel.value)
return null
return endent`
'${item.value}': {
/**
* ${templateInfo.handles.kebab.jsdoc}
*/
kebab: '${templateInfo.handles.kebab.value}',
/**
* ${templateInfo.handles.pascal.jsdoc}
*/
pascal: '${templateInfo.handles.pascal.value}',
/**
* ${templateInfo.handles.camel.jsdoc}
*/
camel: '${templateInfo.handles.camel.value}',
/**
* ${templateInfo.handles.upper.jsdoc}
*/
upper: '${templateInfo.handles.upper.value}',
/**
* ${templateInfo.handles.snake.jsdoc}
*/
snake: '${templateInfo.handles.snake.value}',
},
`
})
.filter((_) => _ !== null)
.join('\n')
})
.join('\n')}
} as const
`,
})
fileOutputs.push({
path: Path.join(outputDir, `templates/index.ts`),
content: endent`
${templateInfos
.map((_) => {
return `export { ${_.handles.pascal.value} } from './${_.handles.pascal.value}'`
})
.join('\n')}
`,
})
const prettierConfigPath = await Prettier.resolveConfigFile(process.cwd())
if (!prettierConfigPath) throw new Error(`Could not find prettier config file.`)
const prettierConfig = await Prettier.resolveConfig(prettierConfigPath)
if (!prettierConfig) throw new Error(`Could not read prettier config file.`)
fileOutputs.push(
...templateInfos.map((_) => {
const sourceCodePath = Path.join(outputDir, `templates/${_.handles.pascal.value}.ts`)
const sourceCodeUnformatted = createSourceCodeTemplate({ templateInfo: _, templatesRepoDir })
const sourceCode = params.prettier
? Prettier.format(sourceCodeUnformatted, {
...prettierConfig,
parser: 'typescript',
})
: sourceCodeUnformatted
return {
path: sourceCodePath,
content: sourceCode,
}
})
)
fileOutputs.forEach((output) => {
FS.write(output.path, output.content)
log.info(`Output file: ${output.path}`)
})
}
/**
* Create the module source code for a template.
*/
const createSourceCodeTemplate = (params: {
templateInfo: TemplateInfo
templatesRepoDir: string
}): string => {
const { templateInfo } = params
const filePaths = glob.sync(`${templateInfo.path}/**/*`, { dot: true })
const files = filePaths
.filter((filePath) => !(filePath.endsWith('.png') || filePath.endsWith('.jpeg')))
.map((filePath) => ({
path: Path.relative(templateInfo.path, filePath),
//eslint-disable-next-line
content: FS.read(filePath)!,
}))
const prismaSeedFile = files.find((_) => _.path === 'prisma/seed.ts')
const filesByPath = files
.map((f) => {
// cannot use endent here because it gets messed up by inner endent
return `'${f.path}': {
path: '${f.path}' as const,
content: endent\`
${indentBlock(4, escapeBackticks(f.content))}
\`
}`
})
.join(',\n')
const githubRepoUrl = `https://github.com/prisma/prisma-schema-examples`
const sourceCode = endent`
/**
* This module was generated.
*
* It contains data about the "${templateInfo.displayName}" template.
*/
// Disable TS type checking because the emitted seed function body otherwise has type errors.
// Once https://github.com/Microsoft/TypeScript/issues/19573 is shipped we can disable TS
// type checking on just the seed function.
// @ts-nocheck
import endent from 'endent'
import { FileTransformer } from '../../fileTransformer'
import { FileTransformers } from '../../fileTransformers'
import { MigrationScript } from '../../logic'
import { Reflector } from '~/src/lib/Reflector'
import { BaseTemplateParameters, AbstractTemplate } from '../../types'
import { merge } from 'lodash'
${sourceCodeSectionHeader('Metadata')}
const metadata = {
/**
* The template's handles in various forms.
*/
handles: {
/**
* ${templateInfo.handles.kebab.jsdoc}
*/
kebab: '${templateInfo.handles.kebab.value}',
/**
* ${templateInfo.handles.pascal.jsdoc}
*/
pascal: '${templateInfo.handles.pascal.value}',
/**
* ${templateInfo.handles.camel.jsdoc}
*/
camel: '${templateInfo.handles.camel.value}',
/**
* ${templateInfo.handles.upper.jsdoc}
*/
upper: '${templateInfo.handles.upper.value}',
/**
* ${templateInfo.handles.snake.jsdoc}
*/
snake: '${templateInfo.handles.snake.value}',
} as const,
/**
* The template's expressive name.
*/
displayName: '${templateInfo.displayName}' as const,
/**
* The GitHub repo URL that this template comes from.
*/
githubUrl: '${githubRepoUrl}/tree/main/${templateInfo.displayName}',
/**
* The template's description.
*/
description: '${templateInfo.description}',
}
${sourceCodeSectionHeader('Files')}
const files = {
${filesByPath}
}
${sourceCodeSectionHeader('Parameters')}
type TemplateParameters = BaseTemplateParameters
const templateParameterDefaults: Required<TemplateParameters> = {
datasourceProvider: Reflector.Schema.DatasourceProviderNormalized._def.values.postgres,
repositoryOwner: null,
repositoryHandle: null,
engineType: null,
dataproxy: true,
referentialIntegrity: Reflector.Schema.referentialIntegritySettingValueDefault,
}
/**
* Run the seed script for this template.
*
* @remarks This is a version of the seed script from the template that has been transformed into a runnable parameterized function.
*/
const seed = ${createSeedFunction({ content: prismaSeedFile?.content ?? '' })}
${sourceCodeSectionHeader('Class')}
/**
* The "${templateInfo.displayName}" Prisma template.
*
* ${templateInfo.description}
*/
class ${templateInfo.handles.pascal.value} implements AbstractTemplate<typeof files> {
/**
* Type brand for discriminant union use-cases.
*/
static _tag = '${templateInfo.handles.pascal.value}' as const
/**
* Template metadata like name, etc.
*/
static metadata = metadata
/**
* Template files indexed by their path on disk. Note that the files on a template class instance can
* have different contents than the files on template class constructor.
*/
static files = files
/**
* Metadata about the parameters accepted by this template.
*/
static parameters = {
defaults: templateParameterDefaults
}
static seed = seed
${sourceCodeSectionHeader2('Instance Properties')}
/**
* Type brand for discriminant union use-cases.
*/
public _tag = '${templateInfo.handles.pascal.value}' as const
/**
* Template metadata like name, etc.
*/
public metadata = metadata
public seed = seed
/**
* Template files indexed by their path on disk. Note that the files on a template class instance can
* have different contents than the files on template class constructor.
*/
public files = files
/**
* A SQL migration script that will put the database into a state reflecting the initial Prisma schema of this template.
*
* This is useful for running migrations in environments where the Prisma Migration engine cannot be used, such as with the Prisma Data Proxy.
*
* This SQL has been statically generated using the Prisma CLI [\`migrate diff\`](https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-diff) sub-command. The SQL here is equivalent to the
* SQL that shows up in _initial prisma migration file_ (e.g. \`./prisma/migrations/20210409125609_init/migration.sql\`) of this template.
*
* Note that the script is influenced by the arguments given to this template such as if referential integrity is enabled or not, and what datasource provider was chosen.
*/
public migrationScript: string
${sourceCodeSectionHeader2('Constructor')}
constructor(parameters?: TemplateParameters) {
const parameters_ = merge({}, templateParameterDefaults, parameters)
this.migrationScript = MigrationScript.select({
template: this._tag,
datasourceProvider: parameters_.datasourceProvider,
referentialIntegrity: parameters_.referentialIntegrity
})
this.files = FileTransformer.runStack({
template: this._tag,
transformers: Object.values(FileTransformers),
files,
parameters: parameters_
})
}
}
${sourceCodeSectionHeader('Namespace')}
// /**
// * Types belonging to the "${templateInfo.handles.pascal.value}" Prisma template.
// */
namespace ${templateInfo.handles.pascal.value} {
/**
* The template's tag.
*/
export type Tag = '${templateInfo.handles.pascal.value}'
/**
* The template's handles.
*/
export namespace Handles {
export type Pascal = typeof metadata.handles.pascal
export type Property = typeof metadata.handles.camel
export type Slug = typeof metadata.handles.kebab
}
/**
* Template files indexed by their path on disk.
*/
export type Files = typeof files
/**
* Parameters accepted by this template.
*/
export type Parameters = TemplateParameters
}
${sourceCodeSectionHeader('Exports')}
export {
${templateInfo.handles.pascal.value}
}
`
return sourceCode
}
export default run