@payloadcms/drizzle 4.0.0-internal.b8e7c89 → 4.0.0-internal.bd1d413

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.
Files changed (207) hide show
  1. package/dist/exports/postgres.d.ts +4 -1
  2. package/dist/exports/postgres.d.ts.map +1 -1
  3. package/dist/exports/postgres.js +4 -1
  4. package/dist/exports/postgres.js.map +1 -1
  5. package/dist/exports/sqlite.d.ts +2 -1
  6. package/dist/exports/sqlite.d.ts.map +1 -1
  7. package/dist/exports/sqlite.js +2 -1
  8. package/dist/exports/sqlite.js.map +1 -1
  9. package/dist/find/buildPolymorphicJoinQuery.d.ts +39 -0
  10. package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -0
  11. package/dist/find/buildPolymorphicJoinQuery.js +146 -0
  12. package/dist/find/buildPolymorphicJoinQuery.js.map +1 -0
  13. package/dist/find/buildPolymorphicJoinWhere.d.ts +20 -0
  14. package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -0
  15. package/dist/find/buildPolymorphicJoinWhere.js +301 -0
  16. package/dist/find/buildPolymorphicJoinWhere.js.map +1 -0
  17. package/dist/find/createPolymorphicJoinWherePlan.d.ts +38 -0
  18. package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -0
  19. package/dist/find/createPolymorphicJoinWherePlan.js +200 -0
  20. package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -0
  21. package/dist/find/traverseFields.d.ts.map +1 -1
  22. package/dist/find/traverseFields.js +20 -191
  23. package/dist/find/traverseFields.js.map +1 -1
  24. package/dist/index.d.ts +1 -8
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +1 -8
  27. package/dist/index.js.map +1 -1
  28. package/dist/migrate.d.ts.map +1 -1
  29. package/dist/migrate.js +6 -2
  30. package/dist/migrate.js.map +1 -1
  31. package/dist/migrateDown.d.ts.map +1 -1
  32. package/dist/migrateDown.js +5 -2
  33. package/dist/migrateDown.js.map +1 -1
  34. package/dist/migrateFresh.d.ts.map +1 -1
  35. package/dist/migrateFresh.js +5 -2
  36. package/dist/migrateFresh.js.map +1 -1
  37. package/dist/migrateRefresh.d.ts.map +1 -1
  38. package/dist/migrateRefresh.js +6 -2
  39. package/dist/migrateRefresh.js.map +1 -1
  40. package/dist/migrateReset.d.ts.map +1 -1
  41. package/dist/migrateReset.js +6 -2
  42. package/dist/migrateReset.js.map +1 -1
  43. package/dist/postgres/createJSONQuery/index.js +3 -3
  44. package/dist/postgres/createJSONQuery/index.js.map +1 -1
  45. package/dist/postgres/findDocumentLocks.d.ts +4 -0
  46. package/dist/postgres/findDocumentLocks.d.ts.map +1 -0
  47. package/dist/postgres/findDocumentLocks.js +22 -0
  48. package/dist/postgres/findDocumentLocks.js.map +1 -0
  49. package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.d.ts +26 -0
  50. package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.d.ts.map +1 -0
  51. package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.js +61 -0
  52. package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.js.map +1 -0
  53. package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.d.ts +13 -0
  54. package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.d.ts.map +1 -0
  55. package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.js +17 -0
  56. package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.js.map +1 -0
  57. package/dist/postgres/predefinedMigrations/localize-status/index.d.ts.map +1 -1
  58. package/dist/postgres/predefinedMigrations/localize-status/index.js +73 -10
  59. package/dist/postgres/predefinedMigrations/localize-status/index.js.map +1 -1
  60. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts +35 -0
  61. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  62. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js +185 -0
  63. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  64. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -1
  65. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js +8 -4
  66. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -1
  67. package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
  68. package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
  69. package/dist/postgres/requireDrizzleKit.d.ts +4 -0
  70. package/dist/postgres/requireDrizzleKit.d.ts.map +1 -1
  71. package/dist/postgres/requireDrizzleKit.js +16 -10
  72. package/dist/postgres/requireDrizzleKit.js.map +1 -1
  73. package/dist/queries/buildOperatorConstraint.d.ts.map +1 -1
  74. package/dist/queries/buildOperatorConstraint.js +16 -0
  75. package/dist/queries/buildOperatorConstraint.js.map +1 -1
  76. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  77. package/dist/queries/getTableColumnFromPath.js +15 -1
  78. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  79. package/dist/queries/parseParams.d.ts.map +1 -1
  80. package/dist/queries/parseParams.js +59 -2
  81. package/dist/queries/parseParams.js.map +1 -1
  82. package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
  83. package/dist/queries/sanitizeQueryValue.js +6 -2
  84. package/dist/queries/sanitizeQueryValue.js.map +1 -1
  85. package/dist/schema/build.d.ts.map +1 -1
  86. package/dist/schema/build.js +54 -5
  87. package/dist/schema/build.js.map +1 -1
  88. package/dist/schema/traverseFields.d.ts.map +1 -1
  89. package/dist/schema/traverseFields.js +71 -14
  90. package/dist/schema/traverseFields.js.map +1 -1
  91. package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js +3 -2
  92. package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js.map +1 -1
  93. package/dist/sqlite/createJSONQuery/index.d.ts.map +1 -1
  94. package/dist/sqlite/createJSONQuery/index.js +6 -5
  95. package/dist/sqlite/createJSONQuery/index.js.map +1 -1
  96. package/dist/sqlite/createRequireDrizzleKit.d.ts +6 -0
  97. package/dist/sqlite/createRequireDrizzleKit.d.ts.map +1 -0
  98. package/dist/sqlite/createRequireDrizzleKit.js +15 -0
  99. package/dist/sqlite/createRequireDrizzleKit.js.map +1 -0
  100. package/dist/sqlite/execute.js.map +1 -1
  101. package/dist/sqlite/insert.d.ts.map +1 -1
  102. package/dist/sqlite/insert.js +4 -1
  103. package/dist/sqlite/insert.js.map +1 -1
  104. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts +15 -0
  105. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  106. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js +114 -0
  107. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  108. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  109. package/dist/transactions/beginTransaction.js +13 -5
  110. package/dist/transactions/beginTransaction.js.map +1 -1
  111. package/dist/transactions/commitTransaction.d.ts.map +1 -1
  112. package/dist/transactions/commitTransaction.js +2 -5
  113. package/dist/transactions/commitTransaction.js.map +1 -1
  114. package/dist/transform/read/traverseFields.d.ts.map +1 -1
  115. package/dist/transform/read/traverseFields.js +11 -3
  116. package/dist/transform/read/traverseFields.js.map +1 -1
  117. package/dist/transform/write/array.d.ts +3 -2
  118. package/dist/transform/write/array.d.ts.map +1 -1
  119. package/dist/transform/write/array.js +2 -1
  120. package/dist/transform/write/array.js.map +1 -1
  121. package/dist/transform/write/blocks.d.ts +3 -2
  122. package/dist/transform/write/blocks.d.ts.map +1 -1
  123. package/dist/transform/write/blocks.js +5 -2
  124. package/dist/transform/write/blocks.js.map +1 -1
  125. package/dist/transform/write/index.d.ts.map +1 -1
  126. package/dist/transform/write/index.js +5 -1
  127. package/dist/transform/write/index.js.map +1 -1
  128. package/dist/transform/write/traverseFields.d.ts +2 -1
  129. package/dist/transform/write/traverseFields.d.ts.map +1 -1
  130. package/dist/transform/write/traverseFields.js +36 -16
  131. package/dist/transform/write/traverseFields.js.map +1 -1
  132. package/dist/transform/write/types.d.ts +10 -0
  133. package/dist/transform/write/types.d.ts.map +1 -1
  134. package/dist/transform/write/types.js.map +1 -1
  135. package/dist/types.d.ts +2 -2
  136. package/dist/types.d.ts.map +1 -1
  137. package/dist/types.js.map +1 -1
  138. package/dist/updateOne.d.ts.map +1 -1
  139. package/dist/updateOne.js +54 -1
  140. package/dist/updateOne.js.map +1 -1
  141. package/dist/upsertRow/deleteExistingRowsByPath.d.ts +6 -1
  142. package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
  143. package/dist/upsertRow/deleteExistingRowsByPath.js +21 -3
  144. package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
  145. package/dist/upsertRow/index.d.ts +1 -1
  146. package/dist/upsertRow/index.d.ts.map +1 -1
  147. package/dist/upsertRow/index.js +57 -13
  148. package/dist/upsertRow/index.js.map +1 -1
  149. package/dist/upsertRow/insertArrays.d.ts.map +1 -1
  150. package/dist/upsertRow/insertArrays.js +2 -3
  151. package/dist/upsertRow/insertArrays.js.map +1 -1
  152. package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
  153. package/dist/utilities/blocksToJsonMigrator.js +7 -18
  154. package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
  155. package/dist/utilities/buildCreateMigration.js +1 -1
  156. package/dist/utilities/buildCreateMigration.js.map +1 -1
  157. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts +15 -0
  158. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts.map +1 -0
  159. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +110 -0
  160. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -0
  161. package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
  162. package/dist/utilities/createSchemaGenerator.js +24 -13
  163. package/dist/utilities/createSchemaGenerator.js.map +1 -1
  164. package/dist/utilities/executeSchemaHooks.js +1 -1
  165. package/dist/utilities/executeSchemaHooks.js.map +1 -1
  166. package/dist/utilities/fitIdentifierLength.d.ts +25 -0
  167. package/dist/utilities/fitIdentifierLength.d.ts.map +1 -0
  168. package/dist/utilities/fitIdentifierLength.js +35 -0
  169. package/dist/utilities/fitIdentifierLength.js.map +1 -0
  170. package/dist/utilities/formatGeneratedFile.d.ts +10 -0
  171. package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
  172. package/dist/utilities/formatGeneratedFile.js +58 -0
  173. package/dist/utilities/formatGeneratedFile.js.map +1 -0
  174. package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
  175. package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
  176. package/dist/utilities/getSizesToVariantsRenames.js +252 -0
  177. package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
  178. package/dist/utilities/getTransaction.js.map +1 -1
  179. package/dist/utilities/parseJSONPathSegment.d.ts +9 -0
  180. package/dist/utilities/parseJSONPathSegment.d.ts.map +1 -0
  181. package/dist/utilities/parseJSONPathSegment.js +17 -0
  182. package/dist/utilities/parseJSONPathSegment.js.map +1 -0
  183. package/dist/utilities/pushDevSchema.js +1 -1
  184. package/dist/utilities/pushDevSchema.js.map +1 -1
  185. package/package.json +17 -19
  186. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js +0 -91
  187. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js.map +0 -1
  188. package/dist/postgres/query/postgresUnaccent.spec.js +0 -71
  189. package/dist/postgres/query/postgresUnaccent.spec.js.map +0 -1
  190. package/dist/queries/buildOperatorConstraint.spec.js +0 -348
  191. package/dist/queries/buildOperatorConstraint.spec.js.map +0 -1
  192. package/dist/queries/validateOperatorHandlers.spec.js +0 -142
  193. package/dist/queries/validateOperatorHandlers.spec.js.map +0 -1
  194. package/dist/schema/buildRawSchema.spec.js +0 -290
  195. package/dist/schema/buildRawSchema.spec.js.map +0 -1
  196. package/dist/sqlite/requireDrizzleKit.d.ts +0 -3
  197. package/dist/sqlite/requireDrizzleKit.d.ts.map +0 -1
  198. package/dist/sqlite/requireDrizzleKit.js +0 -12
  199. package/dist/sqlite/requireDrizzleKit.js.map +0 -1
  200. package/dist/upsertRow/handleUpsertError.spec.js +0 -42
  201. package/dist/upsertRow/handleUpsertError.spec.js.map +0 -1
  202. package/dist/utilities/checkTruncatedIdentifiers.spec.js +0 -301
  203. package/dist/utilities/checkTruncatedIdentifiers.spec.js.map +0 -1
  204. package/dist/utilities/isValidStringID.spec.js +0 -15
  205. package/dist/utilities/isValidStringID.spec.js.map +0 -1
  206. package/dist/utilities/validateIdentifierLength.spec.js +0 -19
  207. package/dist/utilities/validateIdentifierLength.spec.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nexport const buildCreateMigration = ({\n executeMethod,\n filename,\n sanitizeStatements,\n}: {\n executeMethod: string\n filename: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): CreateMigration => {\n const dirname = path.dirname(filename)\n return async function createMigration(\n this: DrizzleAdapter,\n { file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty },\n ) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration, upSnapshot } = this.requireDrizzleKit()\n\n const drizzleJsonAfter = await generateDrizzleJson(this.schema)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n imports = predefinedMigration.imports\n downSQL = predefinedMigration.downSQL\n upSQL = predefinedMigration.upSQL\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n if (typeof predefinedMigration.dynamic === 'function') {\n const dynamicResult = await predefinedMigration.dynamic({ filePath, payload })\n\n if (dynamicResult.upSQL) {\n upSQL = dynamicResult.upSQL\n }\n\n if (dynamicResult.downSQL) {\n downSQL = dynamicResult.downSQL\n }\n\n if (dynamicResult.imports) {\n imports = dynamicResult.imports\n }\n }\n\n let drizzleJsonBefore = this.defaultDrizzleSnapshot as DrizzleSnapshotJSON\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upSnapshot(drizzleJsonBefore)\n }\n }\n\n payload.logger.info('Starting migration: generating UP statements...')\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n payload.logger.info('Migration UP complete. Generating DOWN statements...')\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n payload.logger.info('Migration DOWN statements generation complete.')\n\n const sqlExecute = `await db.${executeMethod}(` + 'sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsUp })\n }\n if (sqlStatementsDown?.length) {\n downSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsDown })\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty || !shouldPrompt) {\n return { created: false }\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts({\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n })\n\n if (!shouldCreateBlankMigration) {\n return { created: false }\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n const data = getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n })\n\n const fullPath = `${filePath}.ts`\n\n // write migration\n fs.writeFileSync(fullPath, data)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${fullPath}` })\n\n return { created: true, path: fullPath }\n }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","prompts","getMigrationTemplate","buildCreateMigration","executeMethod","filename","sanitizeStatements","dirname","createMigration","file","forceAcceptWarning","migrationName","payload","shouldPrompt","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upSnapshot","requireDrizzleKit","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","predefinedMigration","timestamp","name","slice","join","fileName","filePath","dynamic","dynamicResult","drizzleJsonBefore","defaultDrizzleSnapshot","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","logger","info","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","statements","created","confirm","shouldCreateBlankMigration","type","initial","message","writeFileSync","stringify","data","packageName","fullPath","migrationsDir","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,O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YAAMrE,MAAM+E;QAAS;IACzC;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nexport const buildCreateMigration = ({\n executeMethod,\n filename,\n sanitizeStatements,\n}: {\n executeMethod: string\n filename: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): CreateMigration => {\n const dirname = path.dirname(filename)\n return async function createMigration(\n this: DrizzleAdapter,\n { file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty },\n ) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration, upSnapshot } = await this.requireDrizzleKit()\n\n const drizzleJsonAfter = await generateDrizzleJson(this.schema)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n imports = predefinedMigration.imports\n downSQL = predefinedMigration.downSQL\n upSQL = predefinedMigration.upSQL\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n if (typeof predefinedMigration.dynamic === 'function') {\n const dynamicResult = await predefinedMigration.dynamic({ filePath, payload })\n\n if (dynamicResult.upSQL) {\n upSQL = dynamicResult.upSQL\n }\n\n if (dynamicResult.downSQL) {\n downSQL = dynamicResult.downSQL\n }\n\n if (dynamicResult.imports) {\n imports = dynamicResult.imports\n }\n }\n\n let drizzleJsonBefore = this.defaultDrizzleSnapshot as DrizzleSnapshotJSON\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upSnapshot(drizzleJsonBefore)\n }\n }\n\n payload.logger.info('Starting migration: generating UP statements...')\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n payload.logger.info('Migration UP complete. Generating DOWN statements...')\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n payload.logger.info('Migration DOWN statements generation complete.')\n\n const sqlExecute = `await db.${executeMethod}(` + 'sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsUp })\n }\n if (sqlStatementsDown?.length) {\n downSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsDown })\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty || !shouldPrompt) {\n return { created: false }\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts({\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n })\n\n if (!shouldCreateBlankMigration) {\n return { created: false }\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n const data = getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n })\n\n const fullPath = `${filePath}.ts`\n\n // write migration\n fs.writeFileSync(fullPath, data)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${fullPath}` })\n\n return { created: true, path: fullPath }\n }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","prompts","getMigrationTemplate","buildCreateMigration","executeMethod","filename","sanitizeStatements","dirname","createMigration","file","forceAcceptWarning","migrationName","payload","shouldPrompt","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upSnapshot","requireDrizzleKit","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","predefinedMigration","timestamp","name","slice","join","fileName","filePath","dynamic","dynamicResult","drizzleJsonBefore","defaultDrizzleSnapshot","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","logger","info","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","statements","created","confirm","shouldCreateBlankMigration","type","initial","message","writeFileSync","stringify","data","packageName","fullPath","migrationsDir","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,OAAOC,aAAa,UAAS;AAI7B,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,aAAa,EACbC,QAAQ,EACRC,kBAAkB,EAKnB;IACC,MAAMC,UAAUT,KAAKS,OAAO,CAACF;IAC7B,OAAO,eAAeG,gBAEpB,EAAEC,IAAI,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,OAAO,EAAEC,eAAe,IAAI,EAAEC,SAAS,EAAE;QAEpF,MAAMC,MAAMH,QAAQI,EAAE,CAACC,YAAY;QACnC,IAAI,CAACpB,GAAGqB,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,SAAS;oBAAM;gBAC1B;gBAEA,MAAM,EAAEC,SAASC,0BAA0B,EAAE,GAAG,MAAMpE,QAAQ;oBAC5DsC,MAAM;oBACN+B,MAAM;oBACNC,SAAS;oBACTC,SAAS;gBACX;gBAEA,IAAI,CAACH,4BAA4B;oBAC/B,OAAO;wBAAEF,SAAS;oBAAM;gBAC1B;YACF;YAEA,eAAe;YACftE,GAAG4E,aAAa,CAAC,GAAG9B,SAAS,KAAK,CAAC,EAAEa,KAAKkB,SAAS,CAAClD,kBAAkB,MAAM;QAC9E;QAEA,MAAMmD,OAAOzE,qBAAqB;YAChCiC,SAASA,WAAW,CAAC,mBAAmB,CAAC;YACzCD;YACA0C,aAAahE,QAAQI,EAAE,CAAC4D,WAAW;YACnCxC,OAAOA,SAAS,CAAC,mBAAmB,CAAC;QACvC;QAEA,MAAMyC,WAAW,GAAGlC,SAAS,GAAG,CAAC;QAEjC,kBAAkB;QAClB9C,GAAG4E,aAAa,CAACI,UAAUF;QAE3B3E,oBAAoB;YAAE8E,eAAelE,QAAQI,EAAE,CAACC,YAAY;QAAC;QAE7DL,QAAQgD,MAAM,CAACC,IAAI,CAAC;YAAEkB,KAAK,CAAC,qBAAqB,EAAEF,UAAU;QAAC;QAE9D,OAAO;YAAEV,SAAS;YAAMrE,MAAM+E;QAAS;IACzC;AACF,EAAC"}
@@ -0,0 +1,15 @@
1
+ import type { DynamicMigrationTemplate } from 'payload';
2
+ /**
3
+ * Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames
4
+ * columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,
5
+ * losing every stored image size).
6
+ *
7
+ * It also writes a schema snapshot: the project's previous snapshot with only these renames
8
+ * applied. The next generated migration then diffs from the renamed columns instead of dropping
9
+ * them, and still picks up every other schema change the upgrade brings. Without a previous
10
+ * snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.
11
+ */
12
+ export declare const buildDynamicPredefinedSizesToVariantsMigration: ({ packageName, }: {
13
+ packageName: string;
14
+ }) => DynamicMigrationTemplate;
15
+ //# sourceMappingURL=buildDynamicPredefinedSizesToVariantsMigration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildDynamicPredefinedSizesToVariantsMigration.d.ts","sourceRoot":"","sources":["../../src/utilities/buildDynamicPredefinedSizesToVariantsMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA;AA+BvD;;;;;;;;;GASG;AACH,eAAO,MAAM,8CAA8C,qBAExD;IACD,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,wBAoBH,CAAA"}
@@ -0,0 +1,110 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { readdirSync, readFileSync, writeFileSync } from 'fs';
3
+ import { findSizesToVariantsFieldCollision, getSizesToVariantsRenames } from './getSizesToVariantsRenames.js';
4
+ /**
5
+ * Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames
6
+ * columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,
7
+ * losing every stored image size).
8
+ *
9
+ * It also writes a schema snapshot: the project's previous snapshot with only these renames
10
+ * applied. The next generated migration then diffs from the renamed columns instead of dropping
11
+ * them, and still picks up every other schema change the upgrade brings. Without a previous
12
+ * snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.
13
+ */ export const buildDynamicPredefinedSizesToVariantsMigration = ({ packageName })=>{
14
+ return async ({ filePath, payload })=>{
15
+ const adapter = payload.db;
16
+ const previousSnapshot = await readLatestSnapshot({
17
+ adapter
18
+ });
19
+ if (previousSnapshot) {
20
+ const renamedSnapshot = applySizesToVariantsRenames({
21
+ plan: getSizesToVariantsRenames({
22
+ adapter,
23
+ direction: 'up'
24
+ }),
25
+ snapshot: previousSnapshot
26
+ });
27
+ writeFileSync(`${filePath}.json`, JSON.stringify(renamedSnapshot, null, 2));
28
+ }
29
+ return {
30
+ downSQL: ` await migrateSizesToVariants({ db, direction: 'down', payload })`,
31
+ imports: `import { migrateSizesToVariants } from '${packageName}/migration-utils'`,
32
+ upSQL: ` await migrateSizesToVariants({ db, payload })`
33
+ };
34
+ };
35
+ };
36
+ /** The latest snapshot in the migrations directory, upgraded to drizzle-kit's current format. */ async function readLatestSnapshot({ adapter }) {
37
+ const dir = adapter.migrationDir;
38
+ const latestSnapshotFile = readdirSync(dir).filter((file)=>file.endsWith('.json')).sort().reverse()[0];
39
+ if (!latestSnapshotFile) {
40
+ return undefined;
41
+ }
42
+ const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit();
43
+ const currentVersion = (await generateDrizzleJson(adapter.schema)).version;
44
+ const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8'));
45
+ return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot;
46
+ }
47
+ function applySizesToVariantsRenames({ plan, snapshot }) {
48
+ const renamed = structuredClone(snapshot);
49
+ for (const { columns, indexes, tableName } of plan){
50
+ const table = Object.values(renamed.tables).find(({ name })=>name === tableName);
51
+ if (!table) {
52
+ continue;
53
+ }
54
+ const existingColumns = new Set(Object.values(table.columns).map(({ name })=>name));
55
+ for (const { from, to } of columns){
56
+ if (existingColumns.has(from) && existingColumns.has(to)) {
57
+ throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both "${from}" and "${to}". Move or rename the existing destination data before creating this migration.`);
58
+ }
59
+ }
60
+ const fieldCollision = findSizesToVariantsFieldCollision({
61
+ columns,
62
+ existingColumns
63
+ });
64
+ if (fieldCollision) {
65
+ throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both the "${fieldCollision.from}" and "${fieldCollision.to}" fields. Move or rename the existing destination data before creating this migration.`);
66
+ }
67
+ for (const { from, to } of columns){
68
+ const column = table.columns[from];
69
+ if (column) {
70
+ if (table.columns[to]) {
71
+ throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both "${from}" and "${to}". Move or rename the existing destination data before creating this migration.`);
72
+ }
73
+ delete table.columns[from];
74
+ table.columns[to] = {
75
+ ...column,
76
+ name: to
77
+ };
78
+ }
79
+ }
80
+ for (const [key, index] of Object.entries(table.indexes ?? {})){
81
+ const indexColumns = index.columns.map((column)=>{
82
+ const name = typeof column === 'string' ? column : column.expression;
83
+ const renamedName = columns.find(({ from })=>from === name)?.to ?? name;
84
+ return typeof column === 'string' ? renamedName : {
85
+ ...column,
86
+ expression: renamedName
87
+ };
88
+ });
89
+ const indexColumnNames = indexColumns.map((column)=>typeof column === 'string' ? column : column.expression);
90
+ const target = indexes.find((planned)=>planned.columns.join(',') === indexColumnNames.join(','));
91
+ if (!target) {
92
+ continue;
93
+ }
94
+ if (key !== target.to && table.indexes?.[target.to]) {
95
+ throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both indexes "${key}" and "${target.to}". Move or rename the existing destination index before creating this migration.`);
96
+ }
97
+ delete table.indexes[key];
98
+ table.indexes[target.to] = {
99
+ ...index,
100
+ name: target.to,
101
+ columns: indexColumns
102
+ };
103
+ }
104
+ }
105
+ renamed.prevId = snapshot.id;
106
+ renamed.id = randomUUID();
107
+ return renamed;
108
+ }
109
+
110
+ //# sourceMappingURL=buildDynamicPredefinedSizesToVariantsMigration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/buildDynamicPredefinedSizesToVariantsMigration.ts"],"sourcesContent":["import type { DynamicMigrationTemplate } from 'payload'\n\nimport { randomUUID } from 'crypto'\nimport { readdirSync, readFileSync, writeFileSync } from 'fs'\n\nimport type { DrizzleAdapter } from '../types.js'\nimport type { SizesToVariantsTableRenames } from './getSizesToVariantsRenames.js'\n\nimport {\n findSizesToVariantsFieldCollision,\n getSizesToVariantsRenames,\n} from './getSizesToVariantsRenames.js'\n\ntype SnapshotIndex = {\n columns: ({ expression: string } | string)[]\n name: string\n}\n\ntype SnapshotTable = {\n columns: Record<string, { name: string }>\n indexes?: Record<string, SnapshotIndex>\n name: string\n}\n\ntype Snapshot = {\n id?: string\n prevId?: string\n tables: Record<string, SnapshotTable>\n version: string\n}\n\n/**\n * Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames\n * columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,\n * losing every stored image size).\n *\n * It also writes a schema snapshot: the project's previous snapshot with only these renames\n * applied. The next generated migration then diffs from the renamed columns instead of dropping\n * them, and still picks up every other schema change the upgrade brings. Without a previous\n * snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.\n */\nexport const buildDynamicPredefinedSizesToVariantsMigration = ({\n packageName,\n}: {\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const adapter = payload.db as unknown as DrizzleAdapter\n const previousSnapshot = await readLatestSnapshot({ adapter })\n\n if (previousSnapshot) {\n const renamedSnapshot = applySizesToVariantsRenames({\n plan: getSizesToVariantsRenames({ adapter, direction: 'up' }),\n snapshot: previousSnapshot,\n })\n\n writeFileSync(`${filePath}.json`, JSON.stringify(renamedSnapshot, null, 2))\n }\n\n return {\n downSQL: ` await migrateSizesToVariants({ db, direction: 'down', payload })`,\n imports: `import { migrateSizesToVariants } from '${packageName}/migration-utils'`,\n upSQL: ` await migrateSizesToVariants({ db, payload })`,\n }\n }\n}\n\n/** The latest snapshot in the migrations directory, upgraded to drizzle-kit's current format. */\nasync function readLatestSnapshot({\n adapter,\n}: {\n adapter: DrizzleAdapter\n}): Promise<Snapshot | undefined> {\n const dir = adapter.migrationDir\n const latestSnapshotFile = readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()[0]\n\n if (!latestSnapshotFile) {\n return undefined\n }\n\n const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit()\n const currentVersion = (await generateDrizzleJson(adapter.schema)).version\n const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8')) as Snapshot\n\n return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot\n}\n\nfunction applySizesToVariantsRenames({\n plan,\n snapshot,\n}: {\n plan: SizesToVariantsTableRenames[]\n snapshot: Snapshot\n}): Snapshot {\n const renamed: Snapshot = structuredClone(snapshot)\n\n for (const { columns, indexes, tableName } of plan) {\n const table = Object.values(renamed.tables).find(({ name }) => name === tableName)\n\n if (!table) {\n continue\n }\n\n const existingColumns = new Set(Object.values(table.columns).map(({ name }) => name))\n\n for (const { from, to } of columns) {\n if (existingColumns.has(from) && existingColumns.has(to)) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n }\n\n const fieldCollision = findSizesToVariantsFieldCollision({ columns, existingColumns })\n\n if (fieldCollision) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both the \"${fieldCollision.from}\" and \"${fieldCollision.to}\" fields. Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n for (const { from, to } of columns) {\n const column = table.columns[from]\n\n if (column) {\n if (table.columns[to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n delete table.columns[from]\n table.columns[to] = { ...column, name: to }\n }\n }\n\n for (const [key, index] of Object.entries(table.indexes ?? {})) {\n const indexColumns = index.columns.map((column) => {\n const name = typeof column === 'string' ? column : column.expression\n const renamedName = columns.find(({ from }) => from === name)?.to ?? name\n\n return typeof column === 'string' ? renamedName : { ...column, expression: renamedName }\n })\n const indexColumnNames = indexColumns.map((column) =>\n typeof column === 'string' ? column : column.expression,\n )\n const target = indexes.find(\n (planned) => planned.columns.join(',') === indexColumnNames.join(','),\n )\n\n if (!target) {\n continue\n }\n\n if (key !== target.to && table.indexes?.[target.to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both indexes \"${key}\" and \"${target.to}\". Move or rename the existing destination index before creating this migration.`,\n )\n }\n\n delete table.indexes[key]\n table.indexes[target.to] = { ...index, name: target.to, columns: indexColumns }\n }\n }\n\n renamed.prevId = snapshot.id\n renamed.id = randomUUID()\n\n return renamed\n}\n"],"names":["randomUUID","readdirSync","readFileSync","writeFileSync","findSizesToVariantsFieldCollision","getSizesToVariantsRenames","buildDynamicPredefinedSizesToVariantsMigration","packageName","filePath","payload","adapter","db","previousSnapshot","readLatestSnapshot","renamedSnapshot","applySizesToVariantsRenames","plan","direction","snapshot","JSON","stringify","downSQL","imports","upSQL","dir","migrationDir","latestSnapshotFile","filter","file","endsWith","sort","reverse","undefined","generateDrizzleJson","upSnapshot","requireDrizzleKit","currentVersion","schema","version","parse","renamed","structuredClone","columns","indexes","tableName","table","Object","values","tables","find","name","existingColumns","Set","map","from","to","has","Error","fieldCollision","column","key","index","entries","indexColumns","expression","renamedName","indexColumnNames","target","planned","join","prevId","id"],"mappings":"AAEA,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAK7D,SACEC,iCAAiC,EACjCC,yBAAyB,QACpB,iCAAgC;AAoBvC;;;;;;;;;CASC,GACD,OAAO,MAAMC,iDAAiD,CAAC,EAC7DC,WAAW,EAGZ;IACC,OAAO,OAAO,EAAEC,QAAQ,EAAEC,OAAO,EAAE;QACjC,MAAMC,UAAUD,QAAQE,EAAE;QAC1B,MAAMC,mBAAmB,MAAMC,mBAAmB;YAAEH;QAAQ;QAE5D,IAAIE,kBAAkB;YACpB,MAAME,kBAAkBC,4BAA4B;gBAClDC,MAAMX,0BAA0B;oBAAEK;oBAASO,WAAW;gBAAK;gBAC3DC,UAAUN;YACZ;YAEAT,cAAc,GAAGK,SAAS,KAAK,CAAC,EAAEW,KAAKC,SAAS,CAACN,iBAAiB,MAAM;QAC1E;QAEA,OAAO;YACLO,SAAS,CAAC,kEAAkE,CAAC;YAC7EC,SAAS,CAAC,wCAAwC,EAAEf,YAAY,iBAAiB,CAAC;YAClFgB,OAAO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AEzD,MAAMG,SAASxB,QAAQM,IAAI,CACzB,CAACmB,UAAYA,QAAQ1B,OAAO,CAAC2B,IAAI,CAAC,SAASH,iBAAiBG,IAAI,CAAC;YAGnE,IAAI,CAACF,QAAQ;gBACX;YACF;YAEA,IAAIP,QAAQO,OAAOZ,EAAE,IAAIV,MAAMF,OAAO,EAAE,CAACwB,OAAOZ,EAAE,CAAC,EAAE;gBACnD,MAAM,IAAIE,MACR,CAAC,sEAAsE,EAAEb,UAAU,yBAAyB,EAAEgB,IAAI,OAAO,EAAEO,OAAOZ,EAAE,CAAC,gFAAgF,CAAC;YAE1N;YAEA,OAAOV,MAAMF,OAAO,CAACiB,IAAI;YACzBf,MAAMF,OAAO,CAACwB,OAAOZ,EAAE,CAAC,GAAG;gBAAE,GAAGM,KAAK;gBAAEX,MAAMiB,OAAOZ,EAAE;gBAAEb,SAASqB;YAAa;QAChF;IACF;IAEAvB,QAAQ8B,MAAM,GAAGpD,SAASqD,EAAE;IAC5B/B,QAAQ+B,EAAE,GAAGvE;IAEb,OAAOwC;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cAmTH,CAAA"}
1
+ {"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAoCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cAwUH,CAAA"}
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'fs';
2
2
  import { writeFile } from 'fs/promises';
3
3
  import path from 'path';
4
+ import { formatGeneratedFile } from './formatGeneratedFile.js';
4
5
  /**
5
6
  * @example
6
7
  * console.log(sanitizeObjectKey("oneTwo")); // oneTwo
@@ -75,7 +76,15 @@ export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix
75
76
  fkGraph[tableName].add(col.reference.table);
76
77
  }
77
78
  }
79
+ for(const fkKey in table.foreignKeys ?? {}){
80
+ for (const foreignColumn of table.foreignKeys[fkKey].foreignColumns){
81
+ if (foreignColumn.table !== tableName) {
82
+ fkGraph[tableName].add(foreignColumn.table);
83
+ }
84
+ }
85
+ }
78
86
  }
87
+ const extraConfigType = corePackageSuffix === 'pg-core' ? 'PgTableExtraConfigValue' : 'SQLiteTableExtraConfigValue';
79
88
  const canReach = (from, target, visited)=>{
80
89
  if (from === target) {
81
90
  return true;
@@ -102,6 +111,14 @@ export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix
102
111
  for(const tableName in this.rawTables){
103
112
  const table = this.rawTables[tableName];
104
113
  const extrasDeclarations = [];
114
+ /**
115
+ * A table-level foreign key to its own table, or to a table that points back at it, makes
116
+ * TypeScript infer the table's type from its own initializer (TS7022). An explicit return
117
+ * type on the extras callback breaks that cycle, like `AnyPgColumn` does for `.references()`.
118
+ */ const extrasNeedReturnType = Object.values(table.foreignKeys ?? {}).some((foreignKey)=>foreignKey.foreignColumns.some((foreignColumn)=>foreignColumn.table === tableName || circularEdges.has(`${tableName}:${foreignColumn.table}`)));
119
+ if (extrasNeedReturnType) {
120
+ addImport(corePackage, `type ${extraConfigType}`);
121
+ }
105
122
  if (table.indexes) {
106
123
  for(const key in table.indexes){
107
124
  const index = table.indexes[key];
@@ -139,7 +156,7 @@ ${Object.entries(table.columns).map(([key, column])=>` ${sanitizeObjectKey(key)
139
156
  locales: this.payload.config.localization ? this.payload.config.localization.localeCodes : undefined,
140
157
  tableKey: tableName
141
158
  })},`).join('\n')}
142
- }${extrasDeclarations.length ? `, (columns) => [
159
+ }${extrasDeclarations.length ? `, (columns)${extrasNeedReturnType ? `: ${extraConfigType}[]` : ''} => [
143
160
  ${extrasDeclarations.join(' ')}
144
161
  ]` : ''}
145
162
  )
@@ -215,7 +232,7 @@ declare module '${this.packageName}' {
215
232
  */
216
233
  `;
217
234
  const importTypes = `import type {} from '${this.packageName}'`;
218
- let code = [
235
+ const code = [
219
236
  warning,
220
237
  importTypes,
221
238
  ...importDeclarationsSanitized,
@@ -235,19 +252,13 @@ declare module '${this.packageName}' {
235
252
  outputFile = path.resolve(cwd, 'payload-generated-schema.ts');
236
253
  }
237
254
  }
255
+ await writeFile(outputFile, code, 'utf-8');
238
256
  if (prettify) {
239
- try {
240
- const prettier = await eval('import("prettier")');
241
- const configPath = await prettier.resolveConfigFile();
242
- const config = configPath ? await prettier.resolveConfig(configPath) : {};
243
- code = await prettier.format(code, {
244
- ...config,
245
- parser: 'typescript'
246
- });
247
- } catch {
248
- /* empty */ }
257
+ await formatGeneratedFile({
258
+ filePath: outputFile,
259
+ logger: this.payload.logger
260
+ });
249
261
  }
250
- await writeFile(outputFile, code, 'utf-8');
251
262
  if (log) {
252
263
  this.payload.logger.info(`Written ${outputFile}`);
253
264
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4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1
+ {"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\nimport { formatGeneratedFile } from './formatGeneratedFile.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n\n for (const fkKey in table.foreignKeys ?? {}) {\n for (const foreignColumn of table.foreignKeys![fkKey].foreignColumns) {\n if (foreignColumn.table !== tableName) {\n fkGraph[tableName].add(foreignColumn.table)\n }\n }\n }\n }\n\n const extraConfigType =\n corePackageSuffix === 'pg-core' ? 'PgTableExtraConfigValue' : 'SQLiteTableExtraConfigValue'\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n /**\n * A table-level foreign key to its own table, or to a table that points back at it, makes\n * TypeScript infer the table's type from its own initializer (TS7022). An explicit return\n * type on the extras callback breaks that cycle, like `AnyPgColumn` does for `.references()`.\n */\n const extrasNeedReturnType = Object.values(table.foreignKeys ?? {}).some((foreignKey) =>\n foreignKey.foreignColumns.some(\n (foreignColumn) =>\n foreignColumn.table === tableName ||\n circularEdges.has(`${tableName}:${foreignColumn.table}`),\n ),\n )\n\n if (extrasNeedReturnType) {\n addImport(corePackage, `type ${extraConfigType}`)\n }\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns)${extrasNeedReturnType ? `: ${extraConfigType}[]` : ''} => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n const code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (prettify) {\n await formatGeneratedFile({ filePath: outputFile, logger: this.payload.logger })\n }\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","formatGeneratedFile","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","fkKey","foreignKeys","foreignColumn","foreignColumns","extraConfigType","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","extrasNeedReturnType","Object","values","foreignKey","indexes","index","indexDeclaration","unique","on","foreignKeyDeclaration","onDelete","onUpdate","tableCode","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","filePath","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ,KAAK;AAC5B;AAEA,OAAO,MAAMO,wBAAwB,CAAC,EACpCC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,WAAW,EAQZ;IACC,OAAO,eAAeC,eAEpB,EAAEC,MAAM,IAAI,EAAEC,aAAaN,iBAAiB,EAAEO,WAAW,IAAI,EAAE,GAAG,CAAC,CAAC;QAEpE,MAAMC,qBAAkD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C3D,SAAS;eAC1BqB,OAAOsC,IAAI,CAAC,IAAI,CAACnB,YAAY,EAAElD,GAAG,CAAC,CAACW,QAAU,CAAC,UAAU,EAAEA,OAAO;SACtE,CACE2D,MAAM,CAACC,SACPvE,GAAG,CAAC,CAACd,OAAS,GAAGA,KAAK,SAAS,EAAEA,MAAM,EACvCgB,IAAI,CAAC,QAAQ;;IAEd,CAAC;QAED,MAAMsE,mBAAmB,CAAC;gBACd,EAAE,IAAI,CAAClF,WAAW,CAAC;;;;;IAK/B,CAAC;QAED,MAAMmF,UAAU,CAAC;;;;;;;;AAQrB,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAACpF,WAAW,CAAC,CAAC,CAAC;QAE/D,MAAMqF,OAAO;YACXF;YACAC;eACGV;YACHzE;eACGT;eACAD;eACAE;YACHqF;YACAI;SACD,CACEF,MAAM,CAACC,SACPrE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAMkG,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASvH,KAAKwH,OAAO,CAACH,KAAK;YAEjC,IAAIvH,WAAWyH,SAAS;gBACtBpG,aAAanB,KAAKwH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLpG,aAAanB,KAAKwH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,MAAMtH,UAAUoB,YAAYiG,MAAM;QAElC,IAAIhG,UAAU;YACZ,MAAMnB,oBAAoB;gBAAEwH,UAAUtG;gBAAYuG,QAAQ,IAAI,CAAC9E,OAAO,CAAC8E,MAAM;YAAC;QAChF;QAEA,IAAIxG,KAAK;YACP,IAAI,CAAC0B,OAAO,CAAC8E,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAExG,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
@@ -2,7 +2,7 @@ import { extendDrizzleTable } from './extendDrizzleTable.js';
2
2
  export const executeSchemaHooks = async ({ type, adapter })=>{
3
3
  for (const hook of adapter[type]){
4
4
  const result = await hook({
5
- adapter: adapter,
5
+ adapter,
6
6
  extendTable: extendDrizzleTable,
7
7
  schema: {
8
8
  enums: adapter.enums,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of (adapter as unknown as Adapter)[type]) {\n const result = await hook({\n adapter: adapter as unknown as Adapter,\n extendTable: extendDrizzleTable,\n schema: {\n enums: adapter.enums,\n relations: adapter.relations,\n tables: adapter.tables,\n },\n })\n if (result.enums) {\n adapter.enums = result.enums\n }\n\n adapter.tables = result.tables\n adapter.relations = result.relations\n }\n}\n"],"names":["extendDrizzleTable","executeSchemaHooks","type","adapter","hook","result","extendTable","schema","enums","relations","tables"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAAyB;AA0B5D,OAAO,MAAMC,qBAAqB,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAQ;IAC9D,KAAK,MAAMC,QAAQ,AAACD,OAA8B,CAACD,KAAK,CAAE;QACxD,MAAMG,SAAS,MAAMD,KAAK;YACxBD,SAASA;YACTG,aAAaN;YACbO,QAAQ;gBACNC,OAAOL,QAAQK,KAAK;gBACpBC,WAAWN,QAAQM,SAAS;gBAC5BC,QAAQP,QAAQO,MAAM;YACxB;QACF;QACA,IAAIL,OAAOG,KAAK,EAAE;YAChBL,QAAQK,KAAK,GAAGH,OAAOG,KAAK;QAC9B;QAEAL,QAAQO,MAAM,GAAGL,OAAOK,MAAM;QAC9BP,QAAQM,SAAS,GAAGJ,OAAOI,SAAS;IACtC;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of adapter[type]) {\n const result = await hook({\n adapter,\n extendTable: extendDrizzleTable,\n schema: {\n enums: adapter.enums,\n relations: adapter.relations,\n tables: adapter.tables,\n },\n })\n if (result.enums) {\n adapter.enums = result.enums\n }\n\n adapter.tables = result.tables\n adapter.relations = result.relations\n }\n}\n"],"names":["extendDrizzleTable","executeSchemaHooks","type","adapter","hook","result","extendTable","schema","enums","relations","tables"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAAyB;AA0B5D,OAAO,MAAMC,qBAAqB,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAQ;IAC9D,KAAK,MAAMC,QAAQD,OAAO,CAACD,KAAK,CAAE;QAChC,MAAMG,SAAS,MAAMD,KAAK;YACxBD;YACAG,aAAaN;YACbO,QAAQ;gBACNC,OAAOL,QAAQK,KAAK;gBACpBC,WAAWN,QAAQM,SAAS;gBAC5BC,QAAQP,QAAQO,MAAM;YACxB;QACF;QACA,IAAIL,OAAOG,KAAK,EAAE;YAChBL,QAAQK,KAAK,GAAGH,OAAOG,KAAK;QAC9B;QAEAL,QAAQO,MAAM,GAAGL,OAAOK,MAAM;QAC9BP,QAAQM,SAAS,GAAGJ,OAAOI,SAAS;IACtC;AACF,EAAC"}
@@ -0,0 +1,25 @@
1
+ import type { DrizzleAdapter } from '../types.js';
2
+ /**
3
+ * Returns `<name><suffix>` for a generated index or foreign key name, shortened only when
4
+ * Postgres would otherwise truncate it.
5
+ *
6
+ * Postgres keeps at most 63 characters of an identifier, so a longer name never matches what
7
+ * push reads back from the database and the constraint is dropped and re-added on every run.
8
+ *
9
+ * - Other adapters (SQLite, D1) have no such limit and always get the name unchanged.
10
+ * - Names that already fit are unchanged, so existing databases keep their current names.
11
+ * - Longer names are cut and end with a hash of the full name. The result depends only on
12
+ * `name` and `suffix`, never on which other names exist in the config, so adding or
13
+ * reordering fields doesn't rename constraints on other tables.
14
+ */
15
+ export declare const fitIdentifierLength: ({ name, adapter, suffix, }: {
16
+ adapter: Pick<DrizzleAdapter, 'name'>;
17
+ name: string;
18
+ suffix: string;
19
+ }) => string;
20
+ /** Whether Postgres would truncate `identifier`. Always `false` for non-Postgres adapters. */
21
+ export declare const exceedsIdentifierLength: ({ adapter, identifier, }: {
22
+ adapter: Pick<DrizzleAdapter, 'name'>;
23
+ identifier: string;
24
+ }) => boolean;
25
+ //# sourceMappingURL=fitIdentifierLength.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fitIdentifierLength.d.ts","sourceRoot":"","sources":["../../src/utilities/fitIdentifierLength.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,mBAAmB,+BAI7B;IACD,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;IACrC,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;CACf,KAAG,MAUH,CAAA;AAED,8FAA8F;AAC9F,eAAO,MAAM,uBAAuB,6BAGjC;IACD,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;IACrC,UAAU,EAAE,MAAM,CAAA;CACnB,KAAG,OAAiF,CAAA"}
@@ -0,0 +1,35 @@
1
+ import { maxIdentifierLength } from './validateIdentifierLength.js';
2
+ /**
3
+ * Returns `<name><suffix>` for a generated index or foreign key name, shortened only when
4
+ * Postgres would otherwise truncate it.
5
+ *
6
+ * Postgres keeps at most 63 characters of an identifier, so a longer name never matches what
7
+ * push reads back from the database and the constraint is dropped and re-added on every run.
8
+ *
9
+ * - Other adapters (SQLite, D1) have no such limit and always get the name unchanged.
10
+ * - Names that already fit are unchanged, so existing databases keep their current names.
11
+ * - Longer names are cut and end with a hash of the full name. The result depends only on
12
+ * `name` and `suffix`, never on which other names exist in the config, so adding or
13
+ * reordering fields doesn't rename constraints on other tables.
14
+ */ export const fitIdentifierLength = ({ name, adapter, suffix })=>{
15
+ const identifier = `${name}${suffix}`;
16
+ if (!exceedsIdentifierLength({
17
+ adapter,
18
+ identifier
19
+ })) {
20
+ return identifier;
21
+ }
22
+ const tail = `_${hashIdentifier(identifier)}${suffix}`;
23
+ return `${name.slice(0, maxIdentifierLength - tail.length)}${tail}`;
24
+ };
25
+ /** Whether Postgres would truncate `identifier`. Always `false` for non-Postgres adapters. */ export const exceedsIdentifierLength = ({ adapter, identifier })=>adapter.name === 'postgres' && identifier.length > maxIdentifierLength;
26
+ /** 32-bit FNV-1a hash as 8 hex characters. Avoids `crypto` so it also runs on edge runtimes. */ const hashIdentifier = (value)=>{
27
+ let hash = 0x811c9dc5;
28
+ for(let i = 0; i < value.length; i++){
29
+ hash ^= value.charCodeAt(i);
30
+ hash = Math.imul(hash, 0x01000193);
31
+ }
32
+ return (hash >>> 0).toString(16).padStart(8, '0');
33
+ };
34
+
35
+ //# sourceMappingURL=fitIdentifierLength.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/fitIdentifierLength.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { maxIdentifierLength } from './validateIdentifierLength.js'\n\n/**\n * Returns `<name><suffix>` for a generated index or foreign key name, shortened only when\n * Postgres would otherwise truncate it.\n *\n * Postgres keeps at most 63 characters of an identifier, so a longer name never matches what\n * push reads back from the database and the constraint is dropped and re-added on every run.\n *\n * - Other adapters (SQLite, D1) have no such limit and always get the name unchanged.\n * - Names that already fit are unchanged, so existing databases keep their current names.\n * - Longer names are cut and end with a hash of the full name. The result depends only on\n * `name` and `suffix`, never on which other names exist in the config, so adding or\n * reordering fields doesn't rename constraints on other tables.\n */\nexport const fitIdentifierLength = ({\n name,\n adapter,\n suffix,\n}: {\n adapter: Pick<DrizzleAdapter, 'name'>\n name: string\n suffix: string\n}): string => {\n const identifier = `${name}${suffix}`\n\n if (!exceedsIdentifierLength({ adapter, identifier })) {\n return identifier\n }\n\n const tail = `_${hashIdentifier(identifier)}${suffix}`\n\n return `${name.slice(0, maxIdentifierLength - tail.length)}${tail}`\n}\n\n/** Whether Postgres would truncate `identifier`. Always `false` for non-Postgres adapters. */\nexport const exceedsIdentifierLength = ({\n adapter,\n identifier,\n}: {\n adapter: Pick<DrizzleAdapter, 'name'>\n identifier: string\n}): boolean => adapter.name === 'postgres' && identifier.length > maxIdentifierLength\n\n/** 32-bit FNV-1a hash as 8 hex characters. Avoids `crypto` so it also runs on edge runtimes. */\nconst hashIdentifier = (value: string): string => {\n let hash = 0x811c9dc5\n\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n"],"names":["maxIdentifierLength","fitIdentifierLength","name","adapter","suffix","identifier","exceedsIdentifierLength","tail","hashIdentifier","slice","length","value","hash","i","charCodeAt","Math","imul","toString","padStart"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,gCAA+B;AAEnE;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,sBAAsB,CAAC,EAClCC,IAAI,EACJC,OAAO,EACPC,MAAM,EAKP;IACC,MAAMC,aAAa,GAAGH,OAAOE,QAAQ;IAErC,IAAI,CAACE,wBAAwB;QAAEH;QAASE;IAAW,IAAI;QACrD,OAAOA;IACT;IAEA,MAAME,OAAO,CAAC,CAAC,EAAEC,eAAeH,cAAcD,QAAQ;IAEtD,OAAO,GAAGF,KAAKO,KAAK,CAAC,GAAGT,sBAAsBO,KAAKG,MAAM,IAAIH,MAAM;AACrE,EAAC;AAED,4FAA4F,GAC5F,OAAO,MAAMD,0BAA0B,CAAC,EACtCH,OAAO,EACPE,UAAU,EAIX,GAAcF,QAAQD,IAAI,KAAK,cAAcG,WAAWK,MAAM,GAAGV,oBAAmB;AAErF,8FAA8F,GAC9F,MAAMQ,iBAAiB,CAACG;IACtB,IAAIC,OAAO;IAEX,IAAK,IAAIC,IAAI,GAAGA,IAAIF,MAAMD,MAAM,EAAEG,IAAK;QACrCD,QAAQD,MAAMG,UAAU,CAACD;QACzBD,OAAOG,KAAKC,IAAI,CAACJ,MAAM;IACzB;IAEA,OAAO,AAACA,CAAAA,SAAS,CAAA,EAAGK,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG;AAC/C"}
@@ -0,0 +1,10 @@
1
+ import type { Payload } from 'payload';
2
+ /**
3
+ * Formats a generated file in place with the project's formatter and formatter config: oxfmt if
4
+ * it's installed, otherwise Prettier. Logs an error if neither can format the file.
5
+ */
6
+ export declare function formatGeneratedFile({ filePath, logger, }: {
7
+ filePath: string;
8
+ logger: Payload['logger'];
9
+ }): Promise<void>;
10
+ //# sourceMappingURL=formatGeneratedFile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatGeneratedFile.d.ts","sourceRoot":"","sources":["../../src/utilities/formatGeneratedFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAoBtC;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,QAAQ,EACR,MAAM,GACP,EAAE;IACD,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;CAC1B,GAAG,OAAO,CAAC,IAAI,CAAC,CAwChB"}
@@ -0,0 +1,58 @@
1
+ import { execFile } from 'child_process';
2
+ import { readFile, writeFile } from 'fs/promises';
3
+ import { createRequire } from 'module';
4
+ import path from 'path';
5
+ import { dynamicImport } from 'payload';
6
+ import { promisify } from 'util';
7
+ const execFileAsync = promisify(execFile);
8
+ /**
9
+ * Formats a generated file in place with the project's formatter and formatter config: oxfmt if
10
+ * it's installed, otherwise Prettier. Logs an error if neither can format the file.
11
+ */ export async function formatGeneratedFile({ filePath, logger }) {
12
+ let formatError;
13
+ // oxfmt's `format()` API doesn't discover config files, so run the project's oxfmt CLI instead
14
+ let oxfmtBinPath;
15
+ try {
16
+ const projectRequire = createRequire(path.join(process.cwd(), 'package.json'));
17
+ const packageJSONPath = projectRequire.resolve('oxfmt/package.json');
18
+ const { bin } = projectRequire(packageJSONPath);
19
+ oxfmtBinPath = path.join(path.dirname(packageJSONPath), bin.oxfmt);
20
+ } catch {
21
+ // oxfmt isn't installed
22
+ }
23
+ if (oxfmtBinPath) {
24
+ try {
25
+ await execFileAsync(process.execPath, // Loading `oxfmt.config.ts` relies on Node's type stripping, which `NODE_OPTIONS` may disable
26
+ [
27
+ '--experimental-strip-types',
28
+ oxfmtBinPath,
29
+ '--no-error-on-unmatched-pattern',
30
+ filePath
31
+ ], {
32
+ cwd: process.cwd()
33
+ });
34
+ return;
35
+ } catch (err) {
36
+ formatError = err;
37
+ }
38
+ }
39
+ try {
40
+ const prettier = await dynamicImport('prettier');
41
+ const configPath = await prettier.resolveConfigFile();
42
+ const config = configPath ? await prettier.resolveConfig(configPath) : {};
43
+ const code = await readFile(filePath, 'utf-8');
44
+ await writeFile(filePath, await prettier.format(code, {
45
+ ...config,
46
+ parser: 'typescript'
47
+ }));
48
+ return;
49
+ } catch (err) {
50
+ formatError ??= err;
51
+ }
52
+ logger.error({
53
+ err: formatError,
54
+ msg: `Could not format ${filePath} with oxfmt or Prettier`
55
+ });
56
+ }
57
+
58
+ //# sourceMappingURL=formatGeneratedFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/formatGeneratedFile.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { execFile } from 'child_process'\nimport { readFile, writeFile } from 'fs/promises'\nimport { createRequire } from 'module'\nimport path from 'path'\nimport { dynamicImport } from 'payload'\nimport { promisify } from 'util'\n\n/**\n * The subset of Prettier's API used here. Prettier isn't a dependency, so its types aren't available.\n */\ntype Prettier = {\n format: (source: string, options: Record<string, unknown>) => Promise<string>\n resolveConfig: (filePath: string) => Promise<null | Record<string, unknown>>\n resolveConfigFile: () => Promise<null | string>\n}\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * Formats a generated file in place with the project's formatter and formatter config: oxfmt if\n * it's installed, otherwise Prettier. Logs an error if neither can format the file.\n */\nexport async function formatGeneratedFile({\n filePath,\n logger,\n}: {\n filePath: string\n logger: Payload['logger']\n}): Promise<void> {\n let formatError: unknown\n\n // oxfmt's `format()` API doesn't discover config files, so run the project's oxfmt CLI instead\n let oxfmtBinPath: string | undefined\n try {\n const projectRequire = createRequire(path.join(process.cwd(), 'package.json'))\n const packageJSONPath = projectRequire.resolve('oxfmt/package.json')\n const { bin } = projectRequire(packageJSONPath) as { bin: { oxfmt: string } }\n oxfmtBinPath = path.join(path.dirname(packageJSONPath), bin.oxfmt)\n } catch {\n // oxfmt isn't installed\n }\n\n if (oxfmtBinPath) {\n try {\n await execFileAsync(\n process.execPath,\n // Loading `oxfmt.config.ts` relies on Node's type stripping, which `NODE_OPTIONS` may disable\n ['--experimental-strip-types', oxfmtBinPath, '--no-error-on-unmatched-pattern', filePath],\n { cwd: process.cwd() },\n )\n return\n } catch (err) {\n formatError = err\n }\n }\n\n try {\n const prettier = await dynamicImport<Prettier>('prettier')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n const code = await readFile(filePath, 'utf-8')\n await writeFile(filePath, await prettier.format(code, { ...config, parser: 'typescript' }))\n return\n } catch (err) {\n formatError ??= err\n }\n\n logger.error({ err: formatError, msg: `Could not format ${filePath} with oxfmt or Prettier` })\n}\n"],"names":["execFile","readFile","writeFile","createRequire","path","dynamicImport","promisify","execFileAsync","formatGeneratedFile","filePath","logger","formatError","oxfmtBinPath","projectRequire","join","process","cwd","packageJSONPath","resolve","bin","dirname","oxfmt","execPath","err","prettier","configPath","resolveConfigFile","config","resolveConfig","code","format","parser","error","msg"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,SAASC,QAAQ,EAAEC,SAAS,QAAQ,cAAa;AACjD,SAASC,aAAa,QAAQ,SAAQ;AACtC,OAAOC,UAAU,OAAM;AACvB,SAASC,aAAa,QAAQ,UAAS;AACvC,SAASC,SAAS,QAAQ,OAAM;AAWhC,MAAMC,gBAAgBD,UAAUN;AAEhC;;;CAGC,GACD,OAAO,eAAeQ,oBAAoB,EACxCC,QAAQ,EACRC,MAAM,EAIP;IACC,IAAIC;IAEJ,+FAA+F;IAC/F,IAAIC;IACJ,IAAI;QACF,MAAMC,iBAAiBV,cAAcC,KAAKU,IAAI,CAACC,QAAQC,GAAG,IAAI;QAC9D,MAAMC,kBAAkBJ,eAAeK,OAAO,CAAC;QAC/C,MAAM,EAAEC,GAAG,EAAE,GAAGN,eAAeI;QAC/BL,eAAeR,KAAKU,IAAI,CAACV,KAAKgB,OAAO,CAACH,kBAAkBE,IAAIE,KAAK;IACnE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