@payloadcms/drizzle 4.0.0-beta.1 → 4.0.0-beta.10

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 (100) hide show
  1. package/dist/exports/postgres.d.ts +2 -1
  2. package/dist/exports/postgres.d.ts.map +1 -1
  3. package/dist/exports/postgres.js +2 -1
  4. package/dist/exports/postgres.js.map +1 -1
  5. package/dist/exports/sqlite.d.ts +1 -1
  6. package/dist/exports/sqlite.d.ts.map +1 -1
  7. package/dist/exports/sqlite.js +1 -1
  8. package/dist/exports/sqlite.js.map +1 -1
  9. package/dist/find/buildPolymorphicJoinQuery.d.ts +3 -2
  10. package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -1
  11. package/dist/find/buildPolymorphicJoinQuery.js +16 -5
  12. package/dist/find/buildPolymorphicJoinQuery.js.map +1 -1
  13. package/dist/find/buildPolymorphicJoinWhere.js +1 -1
  14. package/dist/find/buildPolymorphicJoinWhere.js.map +1 -1
  15. package/dist/find/createPolymorphicJoinWherePlan.d.ts +2 -1
  16. package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -1
  17. package/dist/find/createPolymorphicJoinWherePlan.js +14 -5
  18. package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -1
  19. package/dist/find/traverseFields.d.ts.map +1 -1
  20. package/dist/find/traverseFields.js +1 -0
  21. package/dist/find/traverseFields.js.map +1 -1
  22. package/dist/postgres/findDocumentLocks.d.ts +4 -0
  23. package/dist/postgres/findDocumentLocks.d.ts.map +1 -0
  24. package/dist/postgres/findDocumentLocks.js +22 -0
  25. package/dist/postgres/findDocumentLocks.js.map +1 -0
  26. package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
  27. package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
  28. package/dist/postgres/requireDrizzleKit.d.ts +4 -0
  29. package/dist/postgres/requireDrizzleKit.d.ts.map +1 -1
  30. package/dist/postgres/requireDrizzleKit.js +16 -10
  31. package/dist/postgres/requireDrizzleKit.js.map +1 -1
  32. package/dist/queries/buildOperatorConstraint.d.ts.map +1 -1
  33. package/dist/queries/buildOperatorConstraint.js +16 -0
  34. package/dist/queries/buildOperatorConstraint.js.map +1 -1
  35. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  36. package/dist/queries/getTableColumnFromPath.js +6 -1
  37. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  38. package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
  39. package/dist/queries/sanitizeQueryValue.js +6 -2
  40. package/dist/queries/sanitizeQueryValue.js.map +1 -1
  41. package/dist/schema/build.js +3 -3
  42. package/dist/schema/build.js.map +1 -1
  43. package/dist/sqlite/createRequireDrizzleKit.d.ts +6 -0
  44. package/dist/sqlite/createRequireDrizzleKit.d.ts.map +1 -0
  45. package/dist/sqlite/createRequireDrizzleKit.js +15 -0
  46. package/dist/sqlite/createRequireDrizzleKit.js.map +1 -0
  47. package/dist/sqlite/execute.js.map +1 -1
  48. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  49. package/dist/transactions/beginTransaction.js +13 -5
  50. package/dist/transactions/beginTransaction.js.map +1 -1
  51. package/dist/transactions/commitTransaction.d.ts.map +1 -1
  52. package/dist/transactions/commitTransaction.js +2 -5
  53. package/dist/transactions/commitTransaction.js.map +1 -1
  54. package/dist/transform/read/traverseFields.d.ts.map +1 -1
  55. package/dist/transform/read/traverseFields.js +11 -3
  56. package/dist/transform/read/traverseFields.js.map +1 -1
  57. package/dist/transform/write/blocks.d.ts.map +1 -1
  58. package/dist/transform/write/blocks.js +3 -1
  59. package/dist/transform/write/blocks.js.map +1 -1
  60. package/dist/transform/write/index.d.ts.map +1 -1
  61. package/dist/transform/write/index.js +3 -1
  62. package/dist/transform/write/index.js.map +1 -1
  63. package/dist/transform/write/traverseFields.js +1 -1
  64. package/dist/transform/write/traverseFields.js.map +1 -1
  65. package/dist/types.d.ts +2 -2
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js.map +1 -1
  68. package/dist/updateOne.d.ts.map +1 -1
  69. package/dist/updateOne.js +14 -1
  70. package/dist/updateOne.js.map +1 -1
  71. package/dist/upsertRow/index.d.ts.map +1 -1
  72. package/dist/upsertRow/index.js +31 -10
  73. package/dist/upsertRow/index.js.map +1 -1
  74. package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
  75. package/dist/utilities/blocksToJsonMigrator.js +7 -18
  76. package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
  77. package/dist/utilities/buildCreateMigration.js +1 -1
  78. package/dist/utilities/buildCreateMigration.js.map +1 -1
  79. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +1 -1
  80. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -1
  81. package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
  82. package/dist/utilities/createSchemaGenerator.js +7 -12
  83. package/dist/utilities/createSchemaGenerator.js.map +1 -1
  84. package/dist/utilities/executeSchemaHooks.js +1 -1
  85. package/dist/utilities/executeSchemaHooks.js.map +1 -1
  86. package/dist/utilities/formatGeneratedFile.d.ts +10 -0
  87. package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
  88. package/dist/utilities/formatGeneratedFile.js +58 -0
  89. package/dist/utilities/formatGeneratedFile.js.map +1 -0
  90. package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -1
  91. package/dist/utilities/getSizesToVariantsRenames.js +1 -0
  92. package/dist/utilities/getSizesToVariantsRenames.js.map +1 -1
  93. package/dist/utilities/getTransaction.js.map +1 -1
  94. package/dist/utilities/pushDevSchema.js +1 -1
  95. package/dist/utilities/pushDevSchema.js.map +1 -1
  96. package/package.json +17 -19
  97. package/dist/sqlite/requireDrizzleKit.d.ts +0 -3
  98. package/dist/sqlite/requireDrizzleKit.d.ts.map +0 -1
  99. package/dist/sqlite/requireDrizzleKit.js +0 -12
  100. package/dist/sqlite/requireDrizzleKit.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,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,UAAU,CAACH,MAAM;YACvBlB,GAAGsB,SA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AASC,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"}
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,UAAU,CAACH,MAAM;YACvBlB,GAAGsB,SAAS,CAACJ;QACf;QAEA,MAAM,EAAEK,mBAAmB,EAAEC,iBAAiB,EAAEC,UAAU,EAAE,GAAG,MAAM,IAAI,CAACC,iBAAiB;QAE3F,MAAMC,mBAAmB,MAAMJ,oBAAoB,IAAI,CAACK,MAAM;QAE9D,MAAM,CAACC,SAASC,OAAO,GAAG,IAAIC,OAAOC,WAAW,GAAGC,KAAK,CAAC;QACzD,MAAMC,gBAAgBL,QAAQM,OAAO,CAAC,OAAO;QAC7C,MAAMC,gBAAgBN,OAAOG,KAAK,CAAC,IAAI,CAAC,EAAE,CAACE,OAAO,CAAC,OAAO;QAC1D,IAAIE,UAAkB;QACtB,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,sBAAsB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AAC,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"}
@@ -39,7 +39,7 @@ import { findSizesToVariantsFieldCollision, getSizesToVariantsRenames } from './
39
39
  if (!latestSnapshotFile) {
40
40
  return undefined;
41
41
  }
42
- const { generateDrizzleJson, upSnapshot } = adapter.requireDrizzleKit();
42
+ const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit();
43
43
  const currentVersion = (await generateDrizzleJson(adapter.schema)).version;
44
44
  const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8'));
45
45
  return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot;
@@ -1 +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 } = 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,CAAC,+CAA+C,CAAC;QAC1D;IACF;AACF,EAAC;AAED,+FAA+F,GAC/F,eA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2B,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
+ {"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,CAAC,+CAA+C,CAAC;QAC1D;IACF;AACF,EAAC;AAED,+FAA+F,GAC/F,eAAeV,mBAAmB,EAChCH,OAAO,EAGR;IACC,MAAMc,MAAMd,QAAQe,YAAY;IAChC,MAAMC,qBAAqBzB,YAAYuB,KACpCG,MAAM,CAAC,CAACC,OAASA,KA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AAMF,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,cA4SH,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
@@ -215,7 +216,7 @@ declare module '${this.packageName}' {
215
216
  */
216
217
  `;
217
218
  const importTypes = `import type {} from '${this.packageName}'`;
218
- let code = [
219
+ const code = [
219
220
  warning,
220
221
  importTypes,
221
222
  ...importDeclarationsSanitized,
@@ -235,19 +236,13 @@ declare module '${this.packageName}' {
235
236
  outputFile = path.resolve(cwd, 'payload-generated-schema.ts');
236
237
  }
237
238
  }
239
+ await writeFile(outputFile, code, 'utf-8');
238
240
  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 */ }
241
+ await formatGeneratedFile({
242
+ filePath: outputFile,
243
+ logger: this.payload.logger
244
+ });
249
245
  }
250
- await writeFile(outputFile, code, 'utf-8');
251
246
  if (log) {
252
247
  this.payload.logger.info(`Written ${outputFile}`);
253
248
  }
@@ -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,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,SAAiB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,EAAE,IAAI,CAAC9E,WAAW,CAAC;;;;;IAK/B,CAAC;QAED,MAAM+E,UAAU,CAAC;;;;;;;;AAQrB,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAAChF,WAAW,CAAC,CAAC,CAAC;QAE/D,IAAIiF,OAAO;YACTF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASlH,KAAKmH,OAAO,CAACH,KAAK;YAEjC,IAAIlH,WAAWoH,SAAS;gBACtBhG,aAAalB,KAAKmH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAalB,KAAKmH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAI7F,UAAU;YACZ,IAAI;gBACF,MAAMiG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM3E,SAAS0E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
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\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 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","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","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,kBAA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AAC;;;;;IAK/B,CAAC;QAED,MAAM+E,UAAU,CAAC;;;;;;;;AAQrB,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAAChF,WAAW,CAAC,CAAC,CAAC;QAE/D,MAAMiF,OAAO;YACXF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASnH,KAAKoH,OAAO,CAACH,KAAK;YAEjC,IAAInH,WAAWqH,SAAS;gBACtBhG,aAAanB,KAAKoH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAanB,KAAKoH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,MAAMlH,UAAUoB,YAAY6F,MAAM;QAElC,IAAI5F,UAAU;YACZ,MAAMnB,oBAAoB;gBAAEoH,UAAUlG;gBAAYmG,QAAQ,IAAI,CAAC1E,OAAO,CAAC0E,MAAM;YAAC;QAChF;QAEA,IAAIpG,KAAK;YACP,IAAI,CAAC0B,OAAO,CAAC0E,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAEpG,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,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,EAAE,OAAM;IACN,wBAAwB;IAC1B;IAEA,IAAIT,cAAc;QAChB,IAAI;YACF,MAAML,cACJQ,QAAQO,QAAQ,EAChB,8FAA8F;YAC9F;gBAAC;gBAA8BV;gBAAc;gBAAmCH;aAAS,EACzF;gBAAEO,KAAKD,QAAQC,GAAG;YAAG;YAEvB;QACF,EAAE,OAAOO,KAAK;YACZZ,cAAcY;QAChB;IACF;IAEA,IAAI;QACF,MAAMC,WAAW,MAAMnB,cAAwB;QAC/C,MAAMoB,aAAa,MAAMD,SAASE,iBAAiB;QACnD,MAAMC,SAASF,aAAa,MAAMD,SAASI,aAAa,CAACH,cAAc,CAAC;QACxE,MAAMI,OAAO,MAAM5B,SAASQ,UAAU;QACtC,MAAMP,UAAUO,UAAU,MAAMe,SAASM,MAAM,CAACD,MAAM;YAAE,GAAGF,MAAM;YAAEI,QAAQ;QAAa;QACxF;IACF,EAAE,OAAOR,KAAK;QACZZ,gBAAgBY;IAClB;IAEAb,OAAOsB,KAAK,CAAC;QAAET,KAAKZ;QAAasB,KAAK,CAAC,iBAAiB,EAAExB,SAAS,uBAAuB,CAAC;IAAC;AAC9F"}
@@ -1 +1 @@
1
- {"version":3,"file":"getSizesToVariantsRenames.d.ts","sourceRoot":"","sources":["../../src/utilities/getSizesToVariantsRenames.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAsB,MAAM,aAAa,CAAA;AAIrE,MAAM,MAAM,wBAAwB,GAAG,MAAM,GAAG,IAAI,CAAA;AAEpD,M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S,EAAE,MAAM,CAAA;IACjB,cAAc,EAAE,MAAM,CAAA;CACvB,GAAG,OAAO,CAQV;AAED,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,SAAI,GAAG,MAAM,CAO9E"}
1
+ {"version":3,"file":"getSizesToVariantsRenames.d.ts","sourceRoot":"","sources":["../../src/utilities/getSizesToVariantsRenames.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAsB,MAAM,aAAa,CAAA;AAIrE,MAAM,MAAM,wBAAwB,GAAG,MAAM,GAAG,IAAI,CAAA;AAEpD,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,MAAM,CAAA;CACX,CAAA;AAED,MAAM,MAAM,0BAA0B,GAAG;IACvC,4EAA4E;IAC5E,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,8FAA8F;IAC9F,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,8FAA8F;IAC9F,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,MAAM,CAAA;IACV,MAAM,EAAE,OAAO,CAAA;CAChB,CAAA;AAED,MAAM,MAAM,2BAA2B,GAAG;IACxC,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,OAAO,EAAE,0BAA0B,EAAE,CAAA;IACrC,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,wBAAgB,iCAAiC,CAAC,EAChD,OAAO,EACP,eAAe,GAChB,EAAE;IACD,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAC7B,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CA2B3C;AAED,wBAAgB,uCAAuC,CAAC,EACtD,OAAO,EACP,eAAe,EACf,SAAS,GACV,EAAE;IACD,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC5B,SAAS,EAAE,MAAM,CAAA;CAClB,GAAG,IAAI,CAgBP;AAkBD;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,EACxC,OAAO,EACP,SAAS,GACV,EAAE;IACD,OAAO,EAAE,cAAc,CAAA;IACvB,SAAS,EAAE,wBAAwB,CAAA;CACpC,GAAG,2BAA2B,EAAE,CAwEhC;AA6ID,+FAA+F;AAC/F,wBAAgB,0BAA0B,CAAC,EACzC,SAAS,EACT,cAAc,GACf,EAAE;IACD,SAAS,EAAE,MAAM,CAAA;IACjB,cAAc,EAAE,MAAM,CAAA;CACvB,GAAG,OAAO,CAQV;AAED,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,SAAI,GAAG,MAAM,CAO9E"}
@@ -58,6 +58,7 @@ const columnPrefixes = [
58
58
  ];
59
59
  const generatedVariantMetadataFieldNames = [
60
60
  '_objectKey',
61
+ '_stored',
61
62
  'filename',
62
63
  'filesize',
63
64
  'height',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/getSizesToVariantsRenames.ts"],"sourcesContent":["import toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, RawIndex, RawTable } from '../types.js'\n\nimport { maxGeneratedIdentifierLength } from './validateIdentifierLength.js'\n\nexport type SizesToVariantsDirection = 'down' | 'up'\n\nexport type SizesToVariantsColumnRename = {\n from: string\n to: string\n}\n\nexport type SizesToVariantsIndexRename = {\n /** Columns the index covers, named as they are after the column renames. */\n columns: string[]\n /** The index name to rename from on `down`. The generated legacy name is resolved on `up`. */\n from?: string\n /** Base used to verify a generated legacy index name, including a possible numeric suffix. */\n legacyNameBase?: string\n to: string\n unique: boolean\n}\n\nexport type SizesToVariantsTableRenames = {\n columns: SizesToVariantsColumnRename[]\n indexes: SizesToVariantsIndexRename[]\n tableName: string\n}\n\nexport function findSizesToVariantsFieldCollision({\n columns,\n existingColumns,\n}: {\n columns: SizesToVariantsColumnRename[]\n existingColumns: Set<string>\n}): { from: string; to: string } | undefined {\n const firstRename = columns[0]\n\n if (!firstRename) {\n return undefined\n }\n\n const fromField = getSizesToVariantsField({ columnName: firstRename.from })\n const toField = getSizesToVariantsField({ columnName: firstRename.to })\n\n if (!fromField || !toField) {\n return undefined\n }\n\n const hasSourceField = [...existingColumns].some((column) =>\n isSizesToVariantsFieldColumn({ column, field: fromField }),\n )\n const plannedDestinationColumns = new Set(columns.map(({ to }) => to))\n const hasUnexpectedDestinationField = [...existingColumns].some(\n (column) =>\n isSizesToVariantsFieldColumn({ column, field: toField }) &&\n !plannedDestinationColumns.has(column),\n )\n\n return hasSourceField && hasUnexpectedDestinationField\n ? { from: fromField.fieldPath, to: toField.fieldPath }\n : undefined\n}\n\nexport function assertNoSizesToVariantsColumnCollisions({\n columns,\n existingColumns,\n tableName,\n}: {\n columns: SizesToVariantsColumnRename[]\n existingColumns: Set<string>\n tableName: string\n}): void {\n for (const { from, to } of columns) {\n if (existingColumns.has(from) && existingColumns.has(to)) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before running this migration.`,\n )\n }\n }\n\n const fieldCollision = findSizesToVariantsFieldCollision({ columns, existingColumns })\n\n if (fieldCollision) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because table \"${tableName}\" contains both the \"${fieldCollision.from}\" and \"${fieldCollision.to}\" fields. Move or rename the existing destination data before running this migration.`,\n )\n }\n}\n\nconst columnPrefixes = [\n { current: 'variants_', legacy: 'sizes_' },\n { current: 'version_variants_', legacy: 'version_sizes_' },\n]\nconst generatedVariantMetadataFieldNames = [\n '_objectKey',\n 'filename',\n 'filesize',\n 'height',\n 'mimeType',\n 'prefix',\n 'url',\n 'width',\n]\n\n/**\n * Plans the column and index renames that move every upload collection's stored image sizes\n * between the legacy `sizes` group and `variants`. Reads the current (`variants`) schema the\n * adapter built from the config, so it covers each collection's main and versions tables without\n * re-deriving Payload's column naming.\n *\n * Index names come from the schema on `up`, and on `down` are rebuilt the way `buildIndexName`\n * named them before the rename. The runner still has to locate the verified generated legacy name\n * on `up`, since it may have a numeric suffix that keeps the name unique.\n */\nexport function getSizesToVariantsRenames({\n adapter,\n direction,\n}: {\n adapter: DrizzleAdapter\n direction: SizesToVariantsDirection\n}): SizesToVariantsTableRenames[] {\n const plan: SizesToVariantsTableRenames[] = []\n\n for (const collection of adapter.payload.config.collections) {\n if (!collection.upload) {\n continue\n }\n\n const upload = typeof collection.upload === 'object' ? collection.upload : undefined\n const generatedVariantColumnKeys = new Set(\n (upload?.variants ?? []).flatMap(({ name }) =>\n generatedVariantMetadataFieldNames.flatMap((metadataFieldName) => [\n `variants_${name}_${metadataFieldName}`,\n `version_variants_${name}_${metadataFieldName}`,\n ]),\n ),\n )\n\n if (generatedVariantColumnKeys.size === 0) {\n continue\n }\n\n const tableNames = [adapter.tableNameMap.get(toSnakeCase(collection.slug))]\n\n if (collection.versions) {\n tableNames.push(\n adapter.tableNameMap.get(`_${toSnakeCase(collection.slug)}${adapter.versionsSuffix}`),\n )\n }\n\n for (const tableName of tableNames) {\n const rawTable = tableName ? adapter.rawTables[tableName] : undefined\n\n if (!tableName || !rawTable) {\n continue\n }\n\n const columns: SizesToVariantsColumnRename[] = []\n\n for (const [columnKey, { name }] of Object.entries(rawTable.columns)) {\n if (!generatedVariantColumnKeys.has(columnKey)) {\n continue\n }\n\n const prefix = columnPrefixes.find(({ current }) => name.startsWith(current))\n\n if (!prefix) {\n continue\n }\n\n const legacyName = `${prefix.legacy}${name.slice(prefix.current.length)}`\n\n columns.push(\n direction === 'up' ? { from: legacyName, to: name } : { from: name, to: legacyName },\n )\n }\n\n if (columns.length === 0) {\n continue\n }\n\n const indexes = Object.values(rawTable.indexes ?? {})\n .map((index) =>\n planIndexRename({ columns, direction, index, rawColumns: rawTable.columns, tableName }),\n )\n .filter((index): index is SizesToVariantsIndexRename => Boolean(index))\n\n plan.push({ columns, indexes, tableName })\n }\n }\n\n return plan\n}\n\nfunction getSizesToVariantsField({\n columnName,\n}: {\n columnName: string\n}): { columnName: string; columnPrefix: string; fieldPath: string } | undefined {\n if (columnName === 'version_sizes' || columnName.startsWith('version_sizes_')) {\n return {\n columnName: 'version_sizes',\n columnPrefix: 'version_sizes_',\n fieldPath: 'version.sizes',\n }\n }\n\n if (columnName === 'version_variants' || columnName.startsWith('version_variants_')) {\n return {\n columnName: 'version_variants',\n columnPrefix: 'version_variants_',\n fieldPath: 'version.variants',\n }\n }\n\n if (columnName === 'sizes' || columnName.startsWith('sizes_')) {\n return { columnName: 'sizes', columnPrefix: 'sizes_', fieldPath: 'sizes' }\n }\n\n if (columnName === 'variants' || columnName.startsWith('variants_')) {\n return { columnName: 'variants', columnPrefix: 'variants_', fieldPath: 'variants' }\n }\n\n return undefined\n}\n\nfunction isSizesToVariantsFieldColumn({\n column,\n field,\n}: {\n column: string\n field: { columnName: string; columnPrefix: string }\n}): boolean {\n return column === field.columnName || column.startsWith(field.columnPrefix)\n}\n\nfunction planIndexRename({\n columns,\n direction,\n index,\n rawColumns,\n tableName,\n}: {\n columns: SizesToVariantsColumnRename[]\n direction: SizesToVariantsDirection\n index: RawIndex\n rawColumns: RawTable['columns']\n tableName: string\n}): SizesToVariantsIndexRename | undefined {\n // `on` holds the column's schema key (e.g. `variants_heroLarge_filename`), not its database name.\n const currentColumns = [index.on].flat().map((key) => rawColumns[key]?.name ?? key)\n const renamedColumns = currentColumns.map((column) =>\n columns.find((rename) => (direction === 'up' ? rename.to : rename.from) === column),\n )\n\n if (renamedColumns.every((rename) => !rename)) {\n return undefined\n }\n\n const unique = Boolean(index.unique)\n\n if (direction === 'up') {\n const legacyColumns = currentColumns.map((column, i) => renamedColumns[i]?.from ?? column)\n\n return {\n columns: currentColumns,\n legacyNameBase: getLegacyIndexNameBase({\n currentColumns,\n indexName: index.name,\n legacyColumns,\n tableName,\n }),\n to: index.name,\n unique,\n }\n }\n\n const legacyColumns = currentColumns.map((column, i) => renamedColumns[i]?.to ?? column)\n const legacyNameBase = getLegacyIndexNameBase({\n currentColumns,\n indexName: index.name,\n legacyColumns,\n tableName,\n })\n\n return {\n columns: legacyColumns,\n from: index.name,\n legacyNameBase,\n to: buildGeneratedLegacyIndexName(legacyNameBase),\n unique,\n }\n}\n\nfunction getLegacyIndexNameBase({\n currentColumns,\n indexName,\n legacyColumns,\n tableName,\n}: {\n currentColumns: string[]\n indexName: string\n legacyColumns: string[]\n tableName: string\n}): string {\n const currentColumn = currentColumns.length === 1 ? currentColumns[0] : undefined\n const legacyColumn = legacyColumns.length === 1 ? legacyColumns[0] : undefined\n const currentFieldPath = currentColumn ? getGeneratedVariantFieldPath(currentColumn) : undefined\n const legacyFieldPath = legacyColumn ? getGeneratedVariantFieldPath(legacyColumn) : undefined\n\n if (currentColumn && currentFieldPath && legacyColumn && legacyFieldPath) {\n const currentFieldIndexNameBase = `${tableName}_${currentFieldPath}_${currentColumn}`\n\n if (isGeneratedLegacyIndexName({ indexName, legacyNameBase: currentFieldIndexNameBase })) {\n return `${tableName}_${legacyFieldPath}_${legacyColumn}`\n }\n }\n\n return legacyColumns.join('_')\n}\n\nfunction getGeneratedVariantFieldPath(columnName: string): string | undefined {\n for (const metadataFieldName of generatedVariantMetadataFieldNames) {\n const metadataColumnSuffix = `_${toSnakeCase(metadataFieldName)}`\n\n if (columnName.endsWith(metadataColumnSuffix)) {\n return columnName.slice(0, -metadataColumnSuffix.length)\n }\n }\n\n return undefined\n}\n\n/** Mirrors `buildIndexName` for an index that didn't collide, without registering the name. */\nexport function isGeneratedLegacyIndexName({\n indexName,\n legacyNameBase,\n}: {\n indexName: string\n legacyNameBase: string\n}): boolean {\n const suffixMatch = indexName.match(/(?:_(\\d+))?_idx$/)\n\n if (!suffixMatch) {\n return false\n }\n\n return indexName === buildGeneratedLegacyIndexName(legacyNameBase, Number(suffixMatch[1] ?? 0))\n}\n\nexport function buildGeneratedLegacyIndexName(name: string, number = 0): string {\n const suffix = `${number ? `_${number}` : ''}_idx`\n const indexName = `${name}${suffix}`\n\n return indexName.length > maxGeneratedIdentifierLength\n ? `${name.slice(0, maxGeneratedIdentifierLength - suffix.length)}${suffix}`\n : indexName\n}\n"],"names":["toSnakeCase","maxGeneratedIdentifierLength","findSizesToVariantsFieldCollision","columns","existingColumns","firstRename","undefined","fromField","getSizesToVariantsField","columnName","from","toField","to","hasSourceField","some","column","isSizesToVariantsFieldColumn","field","plannedDestinationColumns","Set","map","hasUnexpectedDestinationField","has","fieldPath","assertNoSizesToVariantsColumnCollisions","tableName","Error","fieldCollision","columnPrefixes","current","legacy","generatedVariantMetadataFieldNames","getSizesToVariantsRenames","adapter","direction","plan","collection","payload","config","collections","upload","generatedVariantColumnKeys","variants","flatMap","name","metadataFieldName","size","tableNames","tableNameMap","get","slug","versions","push","versionsSuffix","rawTable","rawTables","columnKey","Object","entries","prefix","find","startsWith","legacyName","slice","length","indexes","values","index","planIndexRename","rawColumns","filter","Boolean","columnPrefix","currentColumns","on","flat","key","renamedColumns","rename","every","unique","legacyColumns","i","legacyNameBase","getLegacyIndexNameBase","indexName","buildGeneratedLegacyIndexName","currentColumn","legacyColumn","currentFieldPath","getGeneratedVariantFieldPath","legacyFieldPath","currentFieldIndexNameBase","isGeneratedLegacyIndexName","join","metadataColumnSuffix","endsWith","suffixMatch","match","Number","number","suffix"],"mappings":"AAAA,OAAOA,iBAAiB,gBAAe;AAIvC,SAASC,4BAA4B,QAAQ,gCAA+B;AA0B5E,OAAO,SAASC,kCAAkC,EAChDC,OAAO,EACPC,eAAe,EAIhB;IACC,MAAMC,cAAcF,OAAO,CAAC,EAAE;IAE9B,IAAI,CAACE,aAAa;QAChB,OAAOC;IACT;IAEA,MAAMC,YAAYC,wBAAwB;QAAEC,YAAYJ,YAAYK,IAAI;IAAC;IACzE,MAAMC,UAAUH,wBAAwB;QAAEC,YAAYJ,YAAYO,EAAE;IAAC;IAErE,IAAI,CAACL,aAAa,CA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,IAAY,EAAEwD,SAAS,CAAC;IACpE,MAAMC,SAAS,GAAGD,SAAS,CAAC,CAAC,EAAEA,QAAQ,GAAG,GAAG,IAAI,CAAC;IAClD,MAAMf,YAAY,GAAGzC,OAAOyD,QAAQ;IAEpC,OAAOhB,UAAUrB,MAAM,GAAG/D,+BACtB,GAAG2C,KAAKmB,KAAK,CAAC,GAAG9D,+BAA+BoG,OAAOrC,MAAM,IAAIqC,QAAQ,GACzEhB;AACN"}
1
+ {"version":3,"sources":["../../src/utilities/getSizesToVariantsRenames.ts"],"sourcesContent":["import toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, RawIndex, RawTable } from '../types.js'\n\nimport { maxGeneratedIdentifierLength } from './validateIdentifierLength.js'\n\nexport type SizesToVariantsDirection = 'down' | 'up'\n\nexport type SizesToVariantsColumnRename = {\n from: string\n to: string\n}\n\nexport type SizesToVariantsIndexRename = {\n /** Columns the index covers, named as they are after the column renames. */\n columns: string[]\n /** The index name to rename from on `down`. The generated legacy name is resolved on `up`. */\n from?: string\n /** Base used to verify a generated legacy index name, including a possible numeric suffix. */\n legacyNameBase?: string\n to: string\n unique: boolean\n}\n\nexport type SizesToVariantsTableRenames = {\n columns: SizesToVariantsColumnRename[]\n indexes: SizesToVariantsIndexRename[]\n tableName: string\n}\n\nexport function findSizesToVariantsFieldCollision({\n columns,\n existingColumns,\n}: {\n columns: SizesToVariantsColumnRename[]\n existingColumns: Set<string>\n}): { from: string; to: string } | undefined {\n const firstRename = columns[0]\n\n if (!firstRename) {\n return undefined\n }\n\n const fromField = getSizesToVariantsField({ columnName: firstRename.from })\n const toField = getSizesToVariantsField({ columnName: firstRename.to })\n\n if (!fromField || !toField) {\n return undefined\n }\n\n const hasSourceField = [...existingColumns].some((column) =>\n isSizesToVariantsFieldColumn({ column, field: fromField }),\n )\n const plannedDestinationColumns = new Set(columns.map(({ to }) => to))\n const hasUnexpectedDestinationField = [...existingColumns].some(\n (column) =>\n isSizesToVariantsFieldColumn({ column, field: toField }) &&\n !plannedDestinationColumns.has(column),\n )\n\n return hasSourceField && hasUnexpectedDestinationField\n ? { from: fromField.fieldPath, to: toField.fieldPath }\n : undefined\n}\n\nexport function assertNoSizesToVariantsColumnCollisions({\n columns,\n existingColumns,\n tableName,\n}: {\n columns: SizesToVariantsColumnRename[]\n existingColumns: Set<string>\n tableName: string\n}): void {\n for (const { from, to } of columns) {\n if (existingColumns.has(from) && existingColumns.has(to)) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before running this migration.`,\n )\n }\n }\n\n const fieldCollision = findSizesToVariantsFieldCollision({ columns, existingColumns })\n\n if (fieldCollision) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because table \"${tableName}\" contains both the \"${fieldCollision.from}\" and \"${fieldCollision.to}\" fields. Move or rename the existing destination data before running this migration.`,\n )\n }\n}\n\nconst columnPrefixes = [\n { current: 'variants_', legacy: 'sizes_' },\n { current: 'version_variants_', legacy: 'version_sizes_' },\n]\nconst generatedVariantMetadataFieldNames = [\n '_objectKey',\n '_stored',\n 'filename',\n 'filesize',\n 'height',\n 'mimeType',\n 'prefix',\n 'url',\n 'width',\n]\n\n/**\n * Plans the column and index renames that move every upload collection's stored image sizes\n * between the legacy `sizes` group and `variants`. Reads the current (`variants`) schema the\n * adapter built from the config, so it covers each collection's main and versions tables without\n * re-deriving Payload's column naming.\n *\n * Index names come from the schema on `up`, and on `down` are rebuilt the way `buildIndexName`\n * named them before the rename. The runner still has to locate the verified generated legacy name\n * on `up`, since it may have a numeric suffix that keeps the name unique.\n */\nexport function getSizesToVariantsRenames({\n adapter,\n direction,\n}: {\n adapter: DrizzleAdapter\n direction: SizesToVariantsDirection\n}): SizesToVariantsTableRenames[] {\n const plan: SizesToVariantsTableRenames[] = []\n\n for (const collection of adapter.payload.config.collections) {\n if (!collection.upload) {\n continue\n }\n\n const upload = typeof collection.upload === 'object' ? collection.upload : undefined\n const generatedVariantColumnKeys = new Set(\n (upload?.variants ?? []).flatMap(({ name }) =>\n generatedVariantMetadataFieldNames.flatMap((metadataFieldName) => [\n `variants_${name}_${metadataFieldName}`,\n `version_variants_${name}_${metadataFieldName}`,\n ]),\n ),\n )\n\n if (generatedVariantColumnKeys.size === 0) {\n continue\n }\n\n const tableNames = [adapter.tableNameMap.get(toSnakeCase(collection.slug))]\n\n if (collection.versions) {\n tableNames.push(\n adapter.tableNameMap.get(`_${toSnakeCase(collection.slug)}${adapter.versionsSuffix}`),\n )\n }\n\n for (const tableName of tableNames) {\n const rawTable = tableName ? adapter.rawTables[tableName] : undefined\n\n if (!tableName || !rawTable) {\n continue\n }\n\n const columns: SizesToVariantsColumnRename[] = []\n\n for (const [columnKey, { name }] of Object.entries(rawTable.columns)) {\n if (!generatedVariantColumnKeys.has(columnKey)) {\n continue\n }\n\n const prefix = columnPrefixes.find(({ current }) => name.startsWith(current))\n\n if (!prefix) {\n continue\n }\n\n const legacyName = `${prefix.legacy}${name.slice(prefix.current.length)}`\n\n columns.push(\n direction === 'up' ? { from: legacyName, to: name } : { from: name, to: legacyName },\n )\n }\n\n if (columns.length === 0) {\n continue\n }\n\n const indexes = Object.values(rawTable.indexes ?? {})\n .map((index) =>\n planIndexRename({ columns, direction, index, rawColumns: rawTable.columns, tableName }),\n )\n .filter((index): index is SizesToVariantsIndexRename => Boolean(index))\n\n plan.push({ columns, indexes, tableName })\n }\n }\n\n return plan\n}\n\nfunction getSizesToVariantsField({\n columnName,\n}: {\n columnName: string\n}): { columnName: string; columnPrefix: string; fieldPath: string } | undefined {\n if (columnName === 'version_sizes' || columnName.startsWith('version_sizes_')) {\n return {\n columnName: 'version_sizes',\n columnPrefix: 'version_sizes_',\n fieldPath: 'version.sizes',\n }\n }\n\n if (columnName === 'version_variants' || columnName.startsWith('version_variants_')) {\n return {\n columnName: 'version_variants',\n columnPrefix: 'version_variants_',\n fieldPath: 'version.variants',\n }\n }\n\n if (columnName === 'sizes' || columnName.startsWith('sizes_')) {\n return { columnName: 'sizes', columnPrefix: 'sizes_', fieldPath: 'sizes' }\n }\n\n if (columnName === 'variants' || columnName.startsWith('variants_')) {\n return { columnName: 'variants', columnPrefix: 'variants_', fieldPath: 'variants' }\n }\n\n return undefined\n}\n\nfunction isSizesToVariantsFieldColumn({\n column,\n field,\n}: {\n column: string\n field: { columnName: string; columnPrefix: string }\n}): boolean {\n return column === field.columnName || column.startsWith(field.columnPrefix)\n}\n\nfunction planIndexRename({\n columns,\n direction,\n index,\n rawColumns,\n tableName,\n}: {\n columns: SizesToVariantsColumnRename[]\n direction: SizesToVariantsDirection\n index: RawIndex\n rawColumns: RawTable['columns']\n tableName: string\n}): SizesToVariantsIndexRename | undefined {\n // `on` holds the column's schema key (e.g. `variants_heroLarge_filename`), not its database name.\n const currentColumns = [index.on].flat().map((key) => rawColumns[key]?.name ?? key)\n const renamedColumns = currentColumns.map((column) =>\n columns.find((rename) => (direction === 'up' ? rename.to : rename.from) === column),\n )\n\n if (renamedColumns.every((rename) => !rename)) {\n return undefined\n }\n\n const unique = Boolean(index.unique)\n\n if (direction === 'up') {\n const legacyColumns = currentColumns.map((column, i) => renamedColumns[i]?.from ?? column)\n\n return {\n columns: currentColumns,\n legacyNameBase: getLegacyIndexNameBase({\n currentColumns,\n indexName: index.name,\n legacyColumns,\n tableName,\n }),\n to: index.name,\n unique,\n }\n }\n\n const legacyColumns = currentColumns.map((column, i) => renamedColumns[i]?.to ?? column)\n const legacyNameBase = getLegacyIndexNameBase({\n currentColumns,\n indexName: index.name,\n legacyColumns,\n tableName,\n })\n\n return {\n columns: legacyColumns,\n from: index.name,\n legacyNameBase,\n to: buildGeneratedLegacyIndexName(legacyNameBase),\n unique,\n }\n}\n\nfunction getLegacyIndexNameBase({\n currentColumns,\n indexName,\n legacyColumns,\n tableName,\n}: {\n currentColumns: string[]\n indexName: string\n legacyColumns: string[]\n tableName: string\n}): string {\n const currentColumn = currentColumns.length === 1 ? currentColumns[0] : undefined\n const legacyColumn = legacyColumns.length === 1 ? legacyColumns[0] : undefined\n const currentFieldPath = currentColumn ? getGeneratedVariantFieldPath(currentColumn) : undefined\n const legacyFieldPath = legacyColumn ? getGeneratedVariantFieldPath(legacyColumn) : undefined\n\n if (currentColumn && currentFieldPath && legacyColumn && legacyFieldPath) {\n const currentFieldIndexNameBase = `${tableName}_${currentFieldPath}_${currentColumn}`\n\n if (isGeneratedLegacyIndexName({ indexName, legacyNameBase: currentFieldIndexNameBase })) {\n return `${tableName}_${legacyFieldPath}_${legacyColumn}`\n }\n }\n\n return legacyColumns.join('_')\n}\n\nfunction getGeneratedVariantFieldPath(columnName: string): string | undefined {\n for (const metadataFieldName of generatedVariantMetadataFieldNames) {\n const metadataColumnSuffix = `_${toSnakeCase(metadataFieldName)}`\n\n if (columnName.endsWith(metadataColumnSuffix)) {\n return columnName.slice(0, -metadataColumnSuffix.length)\n }\n }\n\n return undefined\n}\n\n/** Mirrors `buildIndexName` for an index that didn't collide, without registering the name. */\nexport function isGeneratedLegacyIndexName({\n indexName,\n legacyNameBase,\n}: {\n indexName: string\n legacyNameBase: string\n}): boolean {\n const suffixMatch = indexName.match(/(?:_(\\d+))?_idx$/)\n\n if (!suffixMatch) {\n return false\n }\n\n return indexName === buildGeneratedLegacyIndexName(legacyNameBase, Number(suffixMatch[1] ?? 0))\n}\n\nexport function buildGeneratedLegacyIndexName(name: string, number = 0): string {\n const suffix = `${number ? `_${number}` : ''}_idx`\n const indexName = `${name}${suffix}`\n\n return indexName.length > maxGeneratedIdentifierLength\n ? `${name.slice(0, maxGeneratedIdentifierLength - suffix.length)}${suffix}`\n : indexName\n}\n"],"names":["toSnakeCase","maxGeneratedIdentifierLength","findSizesToVariantsFieldCollision","columns","existingColumns","firstRename","undefined","fromField","getSizesToVariantsField","columnName","from","toField","to","hasSourceField","some","column","isSizesToVariantsFieldColumn","field","plannedDestinationColumns","Set","map","hasUnexpectedDestinationField","has","fieldPath","assertNoSizesToVariantsColumnCollisions","tableName","Error","fieldCollision","columnPrefixes","current","legacy","generatedVariantMetadataFieldNames","getSizesToVariantsRenames","adapter","direction","plan","collection","payload","config","collections","upload","generatedVariantColumnKeys","variants","flatMap","name","metadataFieldName","size","tableNames","tableNameMap","get","slug","versions","push","versionsSuffix","rawTable","rawTables","columnKey","Object","entries","prefix","find","startsWith","legacyName","slice","length","indexes","values","index","planIndexRename","rawColumns","filter","Boolean","columnPrefix","currentColumns","on","flat","key","renamedColumns","rename","every","unique","legacyColumns","i","legacyNameBase","getLegacyIndexNameBase","indexName","buildGeneratedLegacyIndexName","currentColumn","legacyColumn","currentFieldPath","getGeneratedVariantFieldPath","legacyFieldPath","currentFieldIndexNameBase","isGeneratedLegacyIndexName","join","metadataColumnSuffix","endsWith","suffixMatch","match","Number","number","suffix"],"mappings":"AAAA,OAAOA,iBAAiB,gBAAe;AAIvC,SAASC,4BAA4B,QAAQ,gCAA+B;AA0B5E,OAAO,SAASC,kCAAkC,EAChDC,OAAO,EACPC,eAAe,EAIhB;IACC,MAAMC,cAAcF,OAAO,CAAC,EAAE;IAE9B,IAAI,CAACE,aAAa;QAChB,OAAOC;IACT;IAEA,MAAMC,YAAYC,wBAAwB;QAAEC,YAAYJ,YAAYK,IAAI;IAAC;IACzE,MAAMC,UAAUH,wBAAwB;QAAEC,YAAYJ,YAAYO,EAAE;IAAC;IAErE,IAAI,CAACL,aAAa,CAACI,SAAS;QAC1B,OAAOL;IACT;IAEA,MAAMO,iBAAiB;WAAIT;KAAgB,CAACU,IAAI,CAAC,CAACC,SAChDC,6BAA6B;YAAED;YAAQE,OAAOV;QAAU;IAE1D,MAAMW,4BAA4B,IAAIC,IAAIhB,QAAQiB,GAAG,CAAC,CAAC,EAAER,EAAE,EAAE,GAAKA;IAClE,MAAMS,gCAAgC;WAAIjB;KAAgB,CAACU,IAAI,CAC7D,CAACC,SACCC,6BAA6B;YAAED;YAAQE,OAAON;QAAQ,MACtD,CAACO,0BAA0BI,GAAG,CAACP;IAGnC,OAAOF,kBAAkBQ,g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\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { shouldReadFromPrimary } from './readAfterWrite.js'\n\n/**\n * Returns current db transaction instance from req or adapter.drizzle itself\n *\n * If a transaction session doesn't exist (e.g., it was already committed/rolled back),\n * falls back to the default adapter.drizzle instance to prevent errors.\n *\n * When read replicas are configured and a write happened recently, returns the\n * unwrapped primary to avoid replication-lag stale reads.\n */\nexport const getTransaction = async <T extends DrizzleAdapter = DrizzleAdapter>(\n adapter: T,\n req?: Partial<PayloadRequest>,\n): Promise<T['drizzle']> => {\n if (!req?.transactionID) {\n if (shouldReadFromPrimary(adapter)) {\n return adapter.primaryDrizzle as T['drizzle']\n }\n return adapter.drizzle\n }\n\n return (adapter.sessions[await req.transactionID]?.db as T['drizzle']) || adapter.drizzle\n}\n"],"names":["shouldReadFromPrimary","getTransaction","adapter","req","transactionID","primaryDrizzle","drizzle","sessions","db"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,sBAAqB;AAE3D;;;;;;;;CAQC,GACD,OAAO,MAAMC,iBAAiB,OAC5BC,SACAC;IAEA,IAAI,CAACA,KAAKC,eAAe;QACvB,IAAIJ,sBAAsBE,UAAU;YAClC,OAAOA,QAAQG,cAAc;QAC/B;QACA,OAAOH,QAAQI,OAAO;IACxB;IAEA,OAAO,AAACJ,QAAQK,QAAQ,CAAC,MAAMJ,IAAIC,aAAa,CAAC,EAAEI,MAAuBN,QAAQI,OAAO;AAC3F,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/getTransaction.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { shouldReadFromPrimary } from './readAfterWrite.js'\n\n/**\n * Returns current db transaction instance from req or adapter.drizzle itself\n *\n * If a transaction session doesn't exist (e.g., it was already committed/rolled back),\n * falls back to the default adapter.drizzle instance to prevent errors.\n *\n * When read replicas are configured and a write happened recently, returns the\n * unwrapped primary to avoid replication-lag stale reads.\n */\nexport const getTransaction = async <T extends DrizzleAdapter = DrizzleAdapter>(\n adapter: T,\n req?: Partial<PayloadRequest>,\n): Promise<T['drizzle']> => {\n if (!req?.transactionID) {\n if (shouldReadFromPrimary(adapter)) {\n return adapter.primaryDrizzle\n }\n return adapter.drizzle\n }\n\n return (adapter.sessions[await req.transactionID]?.db as T['drizzle']) || adapter.drizzle\n}\n"],"names":["shouldReadFromPrimary","getTransaction","adapter","req","transactionID","primaryDrizzle","drizzle","sessions","db"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,sBAAqB;AAE3D;;;;;;;;CAQC,GACD,OAAO,MAAMC,iBAAiB,OAC5BC,SACAC;IAEA,IAAI,CAACA,KAAKC,eAAe;QACvB,IAAIJ,sBAAsBE,UAAU;YAClC,OAAOA,QAAQG,cAAc;QAC/B;QACA,OAAOH,QAAQI,OAAO;IACxB;IAEA,OAAO,AAACJ,QAAQK,QAAQ,CAAC,MAAMJ,IAAIC,aAAa,CAAC,EAAEI,MAAuBN,QAAQI,OAAO;AAC3F,EAAC"}
@@ -26,7 +26,7 @@ const previousSchema = {
26
26
  previousSchema.rawTables = adapter.rawTables;
27
27
  }
28
28
  }
29
- const { pushSchema } = adapter.requireDrizzleKit();
29
+ const { pushSchema } = await adapter.requireDrizzleKit();
30
30
  const { extensions = {}, tablesFilter } = adapter;
31
31
  // This will prompt if clarifications are needed for Drizzle to push new schema
32
32
  const { apply, hasDataLoss, warnings } = await pushSchema(adapter.schema, adapter.drizzle, adapter.schemaName ? [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/pushDevSchema.ts"],"sourcesContent":["import { dequal } from 'dequal'\nimport prompts from 'prompts'\n\nimport type { BasePostgresAdapter } from '../postgres/types.js'\nimport type { DrizzleAdapter, PostgresDB, RawTable } from '../types.js'\n\nconst previousSchema: {\n localeCodes: null | string[]\n rawTables: null | Record<string, RawTable>\n} = {\n localeCodes: null,\n rawTables: null,\n}\n\n/**\n * Pushes the development schema to the database using Drizzle.\n *\n * @param {DrizzleAdapter} adapter - The PostgresAdapter instance connected to the database.\n * @returns {Promise<void>} - A promise that resolves once the schema push is complete.\n */\nexport const pushDevSchema = async (adapter: DrizzleAdapter) => {\n if (process.env.PAYLOAD_FORCE_DRIZZLE_PUSH !== 'true') {\n const localeCodes =\n adapter.payload.config.localization && adapter.payload.config.localization.localeCodes\n\n const equal = dequal(previousSchema, {\n localeCodes,\n rawTables: adapter.rawTables,\n })\n\n if (equal) {\n if (adapter.logger) {\n adapter.payload.logger.info('No changes detected in schema, skipping schema push.')\n }\n\n return\n } else {\n previousSchema.localeCodes = localeCodes\n previousSchema.rawTables = adapter.rawTables\n }\n }\n\n const { pushSchema } = adapter.requireDrizzleKit()\n\n const { extensions = {}, tablesFilter } = adapter as BasePostgresAdapter\n\n // This will prompt if clarifications are needed for Drizzle to push new schema\n const { apply, hasDataLoss, warnings } = await pushSchema(\n adapter.schema,\n adapter.drizzle,\n adapter.schemaName ? [adapter.schemaName] : undefined,\n tablesFilter,\n // Drizzle extensionsFilter supports only postgis for now\n // https://github.com/drizzle-team/drizzle-orm/blob/83daf2d5cf023112de878bc2249ee2c41a2a5b1b/drizzle-kit/src/cli/validations/cli.ts#L26\n extensions.postgis ? ['postgis'] : undefined,\n )\n\n if (warnings.length) {\n let message = `Warnings detected during schema push: \\n\\n${warnings.join('\\n')}\\n\\n`\n\n if (hasDataLoss) {\n message += `DATA LOSS WARNING: Possible data loss detected if schema is pushed.\\n\\n`\n }\n\n message += `Accept warnings and push schema to database?`\n\n const { confirm: acceptWarnings } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message,\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n // Exit if user does not accept warnings.\n // Q: Is this the right type of exit for this interaction?\n if (!acceptWarnings) {\n process.exit(0)\n }\n }\n\n await apply()\n const migrationsTable = adapter.schemaName\n ? `\"${adapter.schemaName}\".\"payload_migrations\"`\n : '\"payload_migrations\"'\n\n const drizzle = adapter.drizzle as PostgresDB\n\n const result = await adapter.execute({\n drizzle,\n raw: `SELECT * FROM ${migrationsTable} WHERE batch = '-1'`,\n })\n\n const devPush = result.rows\n\n if (!devPush.length) {\n // Use drizzle for insert so $defaultFn's are called\n await drizzle.insert(adapter.tables.payload_migrations).values({\n name: 'dev',\n batch: -1,\n })\n } else {\n await adapter.execute({\n drizzle,\n raw: `UPDATE ${migrationsTable} SET updated_at = CURRENT_TIMESTAMP WHERE batch = '-1'`,\n })\n }\n}\n"],"names":["dequal","prompts","previousSchema","localeCodes","rawTables","pushDevSchema","adapter","process","env","PAYLOAD_FORCE_DRIZZLE_PUSH","payload","config","localization","equal","logger","info","pushSchema","requireDrizzleKit","extensions","tablesFilter","apply","hasDataLoss","warnings","schema","drizzle","schemaName","undefined","postgis","length","message","join","confirm","acceptWarnings","name","type","initial","onCancel","exit","migrationsTable","result","execute","raw","devPush","rows","insert","tables","payload_migrations","values","batch"],"mappings":"AAAA,SAASA,MAAM,QAAQ,SAAQ;AAC/B,OAAOC,aAAa,UAAS;AAK7B,MAAMC,iBAGF;IACFC,aAAa;IACbC,WAAW;AACb;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,gBAAgB,OAAOC;IAClC,IAAIC,QAAQC,GAAG,CAACC,0BAA0B,KAAK,QAAQ;QACrD,MAAMN,cACJG,QAAQI,OAAO,CAACC,MAAM,CAACC,YAAY,IAAIN,QAAQI,OAAO,CAACC,MAAM,CAACC,YAAY,CAACT,WAAW;QAExF,MAAMU,QAAQb,OAAOE,gBAAgB;YACnCC;YACAC,WAAWE,QAAQF,SAAS;QAC9B;QAEA,IAAIS,OAAO;YACT,IAAIP,QAAQQ,MAAM,EAAE;gBAClBR,QAAQI,OAAO,CAACI,MAAM,CAACC,IAAI,CAAC;YAC9B;YAEA;QACF,OAAO;YACLb,eAAeC,WAAW,GAAGA;YAC7BD,eAAeE,SAAS,GAAGE,QAAQF,SAAS;QAC9C;IACF;IAEA,MAAM,EAAEY,UAAU,EAAE,GAAGV,QAAQW,iBAAiB;IAEhD,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EC,MAAM,CAAC;YAC7Dd,MAAM;YACNe,OAAO,CAAC;QACV;IACF,OAAO;QACL,MAAM1C,QAAQkC,OAAO,CAAC;YACpBhB;YACAiB,KAAK,CAAC,OAAO,EAAEH,gBAAgB,sDAAsD,CAAC;QACxF;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/pushDevSchema.ts"],"sourcesContent":["import { dequal } from 'dequal'\nimport prompts from 'prompts'\n\nimport type { BasePostgresAdapter } from '../postgres/types.js'\nimport type { DrizzleAdapter, PostgresDB, RawTable } from '../types.js'\n\nconst previousSchema: {\n localeCodes: null | string[]\n rawTables: null | Record<string, RawTable>\n} = {\n localeCodes: null,\n rawTables: null,\n}\n\n/**\n * Pushes the development schema to the database using Drizzle.\n *\n * @param {DrizzleAdapter} adapter - The PostgresAdapter instance connected to the database.\n * @returns {Promise<void>} - A promise that resolves once the schema push is complete.\n */\nexport const pushDevSchema = async (adapter: DrizzleAdapter) => {\n if (process.env.PAYLOAD_FORCE_DRIZZLE_PUSH !== 'true') {\n const localeCodes =\n adapter.payload.config.localization && adapter.payload.config.localization.localeCodes\n\n const equal = dequal(previousSchema, {\n localeCodes,\n rawTables: adapter.rawTables,\n })\n\n if (equal) {\n if (adapter.logger) {\n adapter.payload.logger.info('No changes detected in schema, skipping schema push.')\n }\n\n return\n } else {\n previousSchema.localeCodes = localeCodes\n previousSchema.rawTables = adapter.rawTables\n }\n }\n\n const { pushSchema } = await adapter.requireDrizzleKit()\n\n const { extensions = {}, tablesFilter } = adapter as BasePostgresAdapter\n\n // This will prompt if clarifications are needed for Drizzle to push new schema\n const { apply, hasDataLoss, warnings } = await pushSchema(\n adapter.schema,\n adapter.drizzle,\n adapter.schemaName ? [adapter.schemaName] : undefined,\n tablesFilter,\n // Drizzle extensionsFilter supports only postgis for now\n // https://github.com/drizzle-team/drizzle-orm/blob/83daf2d5cf023112de878bc2249ee2c41a2a5b1b/drizzle-kit/src/cli/validations/cli.ts#L26\n extensions.postgis ? ['postgis'] : undefined,\n )\n\n if (warnings.length) {\n let message = `Warnings detected during schema push: \\n\\n${warnings.join('\\n')}\\n\\n`\n\n if (hasDataLoss) {\n message += `DATA LOSS WARNING: Possible data loss detected if schema is pushed.\\n\\n`\n }\n\n message += `Accept warnings and push schema to database?`\n\n const { confirm: acceptWarnings } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message,\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n // Exit if user does not accept warnings.\n // Q: Is this the right type of exit for this interaction?\n if (!acceptWarnings) {\n process.exit(0)\n }\n }\n\n await apply()\n const migrationsTable = adapter.schemaName\n ? `\"${adapter.schemaName}\".\"payload_migrations\"`\n : '\"payload_migrations\"'\n\n const drizzle = adapter.drizzle as PostgresDB\n\n const result = await adapter.execute({\n drizzle,\n raw: `SELECT * FROM ${migrationsTable} WHERE batch = '-1'`,\n })\n\n const devPush = result.rows\n\n if (!devPush.length) {\n // Use drizzle for insert so $defaultFn's are called\n await drizzle.insert(adapter.tables.payload_migrations).values({\n name: 'dev',\n batch: -1,\n })\n } else {\n await adapter.execute({\n drizzle,\n raw: `UPDATE ${migrationsTable} SET updated_at = CURRENT_TIMESTAMP WHERE batch = '-1'`,\n })\n }\n}\n"],"names":["dequal","prompts","previousSchema","localeCodes","rawTables","pushDevSchema","adapter","process","env","PAYLOAD_FORCE_DRIZZLE_PUSH","payload","config","localization","equal","logger","info","pushSchema","requireDrizzleKit","extensions","tablesFilter","apply","hasDataLoss","warnings","schema","drizzle","schemaName","undefined","postgis","length","message","join","confirm","acceptWarnings","name","type","initial","onCancel","exit","migrationsTable","result","execute","raw","devPush","rows","insert","tables","payload_migrations","values","batch"],"mappings":"AAAA,SAASA,MAAM,QAAQ,SAAQ;AAC/B,OAAOC,aAAa,UAAS;AAK7B,MAAMC,iBAGF;IACFC,aAAa;IACbC,WAAW;AACb;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,gBAAgB,OAAOC;IAClC,IAAIC,Q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