| 11 | type FormatSchemaParams = { schemas: MultipleSchemas } |
| 12 | |
| 13 | export async function formatSchema( |
| 14 | { schemas }: FormatSchemaParams, |
| 15 | inputFormattingOptions?: Partial<DocumentFormattingParams['options']>, |
| 16 | ): Promise<MultipleSchemas> { |
| 17 | if (process.env.FORCE_PANIC_PRISMA_SCHEMA) { |
| 18 | handleFormatPanic(() => { |
| 19 | prismaSchemaWasm.debug_panic() |
| 20 | }) |
| 21 | } |
| 22 | |
| 23 | const defaultFormattingOptions: DocumentFormattingParams['options'] = { |
| 24 | tabSize: 2, |
| 25 | insertSpaces: true, |
| 26 | } |
| 27 | |
| 28 | const documentFormattingParams = { |
| 29 | textDocument: { uri: 'file:/dev/null' }, |
| 30 | options: { |
| 31 | ...defaultFormattingOptions, |
| 32 | ...inputFormattingOptions, |
| 33 | }, |
| 34 | } as DocumentFormattingParams |
| 35 | |
| 36 | /** |
| 37 | * Note: |
| 38 | * - Given an invalid schema, `formatWasm` returns a formatted schema regardless (when it doesn't panic). |
| 39 | * - Given an invalid schema, `lintSchema` returns a list of warnings/errors regardless (when it doesn't panic). |
| 40 | * Warnings must be filtered out from the other diagnostics. |
| 41 | * - Validation errors aren't checked/shown here. |
| 42 | * They appear when calling `getDmmf` on the formatted schema in Format.ts. |
| 43 | * If we called `getConfig` instead, we wouldn't have any validation check. |
| 44 | */ |
| 45 | const { formattedMultipleSchemas, lintDiagnostics } = handleFormatPanic(() => { |
| 46 | // the only possible error here is a Rust panic |
| 47 | const formattedMultipleSchemasRaw = formatWasm(JSON.stringify(schemas), documentFormattingParams) |
| 48 | const formattedMultipleSchemas = JSON.parse(formattedMultipleSchemasRaw) as MultipleSchemas |
| 49 | |
| 50 | const lintDiagnostics = lintSchema({ schemas: formattedMultipleSchemas }) |
| 51 | return { formattedMultipleSchemas, lintDiagnostics } |
| 52 | }) |
| 53 | |
| 54 | const lintWarnings = getLintWarningsAsText(lintDiagnostics) |
| 55 | if (lintWarnings && logger.should.warn()) { |
| 56 | // Output warnings to stderr |
| 57 | console.warn(lintWarnings) |
| 58 | } |
| 59 | |
| 60 | return Promise.resolve(formattedMultipleSchemas) |
| 61 | } |
| 62 | |
| 63 | function handleFormatPanic<T>(tryCb: () => T) { |
| 64 | try { |