@depup/payload 3.81.0-depup.1 → 3.82.1-depup.0

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 (69) hide show
  1. package/README.md +5 -5
  2. package/changes.json +4 -4
  3. package/dist/bin/generateTypes.d.ts.map +1 -1
  4. package/dist/bin/generateTypes.js +8 -0
  5. package/dist/bin/generateTypes.js.map +1 -1
  6. package/dist/collections/config/sanitize.d.ts +2 -1
  7. package/dist/collections/config/sanitize.d.ts.map +1 -1
  8. package/dist/collections/config/sanitize.js +4 -1
  9. package/dist/collections/config/sanitize.js.map +1 -1
  10. package/dist/collections/operations/utilities/update.d.ts.map +1 -1
  11. package/dist/collections/operations/utilities/update.js +2 -1
  12. package/dist/collections/operations/utilities/update.js.map +1 -1
  13. package/dist/config/orderable/index.d.ts +2 -10
  14. package/dist/config/orderable/index.d.ts.map +1 -1
  15. package/dist/config/orderable/index.js +20 -67
  16. package/dist/config/orderable/index.js.map +1 -1
  17. package/dist/config/sanitize.d.ts.map +1 -1
  18. package/dist/config/sanitize.js +45 -5
  19. package/dist/config/sanitize.js.map +1 -1
  20. package/dist/config/types.d.ts +20 -0
  21. package/dist/config/types.d.ts.map +1 -1
  22. package/dist/config/types.js.map +1 -1
  23. package/dist/fields/config/sanitize.d.ts +54 -2
  24. package/dist/fields/config/sanitize.d.ts.map +1 -1
  25. package/dist/fields/config/sanitize.js +333 -285
  26. package/dist/fields/config/sanitize.js.map +1 -1
  27. package/dist/fields/config/sanitize.spec.js +82 -0
  28. package/dist/fields/config/sanitize.spec.js.map +1 -1
  29. package/dist/fields/config/sanitizeJoinField.d.ts +15 -1
  30. package/dist/fields/config/sanitizeJoinField.d.ts.map +1 -1
  31. package/dist/fields/config/sanitizeJoinField.js +17 -1
  32. package/dist/fields/config/sanitizeJoinField.js.map +1 -1
  33. package/dist/globals/operations/findOne.d.ts +1 -0
  34. package/dist/globals/operations/findOne.d.ts.map +1 -1
  35. package/dist/globals/operations/findOne.js +10 -3
  36. package/dist/globals/operations/findOne.js.map +1 -1
  37. package/dist/globals/operations/local/findOne.d.ts +8 -0
  38. package/dist/globals/operations/local/findOne.d.ts.map +1 -1
  39. package/dist/globals/operations/local/findOne.js +2 -1
  40. package/dist/globals/operations/local/findOne.js.map +1 -1
  41. package/dist/globals/operations/update.d.ts.map +1 -1
  42. package/dist/globals/operations/update.js +2 -1
  43. package/dist/globals/operations/update.js.map +1 -1
  44. package/dist/index.bundled.d.ts +112 -18
  45. package/dist/index.d.ts +3 -2
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/uploads/checkFileAccess.d.ts +2 -1
  50. package/dist/uploads/checkFileAccess.d.ts.map +1 -1
  51. package/dist/uploads/checkFileAccess.js +25 -14
  52. package/dist/uploads/checkFileAccess.js.map +1 -1
  53. package/dist/uploads/checkFileAccess.spec.js +109 -0
  54. package/dist/uploads/checkFileAccess.spec.js.map +1 -0
  55. package/dist/uploads/endpoints/getFile.d.ts.map +1 -1
  56. package/dist/uploads/endpoints/getFile.js +4 -1
  57. package/dist/uploads/endpoints/getFile.js.map +1 -1
  58. package/dist/uploads/types.d.ts +2 -1
  59. package/dist/uploads/types.d.ts.map +1 -1
  60. package/dist/uploads/types.js.map +1 -1
  61. package/dist/utilities/slugify.d.ts.map +1 -1
  62. package/dist/utilities/slugify.js +1 -1
  63. package/dist/utilities/slugify.js.map +1 -1
  64. package/dist/utilities/validateTimezones.d.ts.map +1 -1
  65. package/dist/utilities/validateTimezones.js +7 -0
  66. package/dist/utilities/validateTimezones.js.map +1 -1
  67. package/dist/versions/types.d.ts +1 -1
  68. package/dist/versions/types.js.map +1 -1
  69. package/package.json +10 -10
package/README.md CHANGED
@@ -13,8 +13,8 @@ npm install @depup/payload
13
13
 
14
14
  | Field | Value |
15
15
  |-------|-------|
16
- | Original | [payload](https://www.npmjs.com/package/payload) @ 3.81.0 |
17
- | Processed | 2026-04-02 |
16
+ | Original | [payload](https://www.npmjs.com/package/payload) @ 3.82.1 |
17
+ | Processed | 2026-04-09 |
18
18
  | Smoke test | passed |
19
19
  | Deps updated | 17 |
20
20
 
@@ -22,11 +22,11 @@ npm install @depup/payload
22
22
 
23
23
  | Dependency | From | To |
24
24
  |------------|------|-----|
25
- | @next/env | ^15.1.5 | ^16.2.2 |
25
+ | @next/env | ^15.1.5 | ^16.2.3 |
26
26
  | ci-info | ^4.1.0 | ^4.4.0 |
27
27
  | console-table-printer | 2.12.1 | ^2.15.0 |
28
28
  | croner | 9.1.0 | ^10.0.1 |
29
- | file-type | 21.3.4 | ^22.0.0 |
29
+ | file-type | 21.3.4 | ^22.0.1 |
30
30
  | get-tsconfig | 4.8.1 | ^4.13.7 |
31
31
  | ipaddr.js | 2.2.0 | ^2.3.0 |
32
32
  | jose | 5.10.0 | ^6.2.2 |
@@ -36,7 +36,7 @@ npm install @depup/payload
36
36
  | pino-pretty | 13.1.2 | ^13.1.3 |
37
37
  | sanitize-filename | 1.6.3 | ^1.6.4 |
38
38
  | ts-essentials | 10.0.3 | ^10.1.1 |
39
- | undici | 7.24.4 | ^8.0.0 |
39
+ | undici | 7.24.4 | ^8.0.2 |
40
40
  | uuid | 10.0.0 | ^13.0.0 |
41
41
  | ws | ^8.16.0 | ^8.20.0 |
42
42
 
package/changes.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "bumped": {
3
3
  "@next/env": {
4
4
  "from": "^15.1.5",
5
- "to": "^16.2.2"
5
+ "to": "^16.2.3"
6
6
  },
7
7
  "ci-info": {
8
8
  "from": "^4.1.0",
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "file-type": {
20
20
  "from": "21.3.4",
21
- "to": "^22.0.0"
21
+ "to": "^22.0.1"
22
22
  },
23
23
  "get-tsconfig": {
24
24
  "from": "4.8.1",
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "undici": {
60
60
  "from": "7.24.4",
61
- "to": "^8.0.0"
61
+ "to": "^8.0.2"
62
62
  },
63
63
  "uuid": {
64
64
  "from": "10.0.0",
@@ -69,6 +69,6 @@
69
69
  "to": "^8.20.0"
70
70
  }
71
71
  },
72
- "timestamp": "2026-04-02T12:28:47.456Z",
72
+ "timestamp": "2026-04-09T16:36:17.005Z",
73
73
  "totalUpdated": 17
74
74
  }
@@ -1 +1 @@
1
- {"version":3,"file":"generateTypes.d.ts","sourceRoot":"","sources":["../../src/bin/generateTypes.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAMzD,wBAAsB,aAAa,CACjC,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE;IAAE,GAAG,EAAE,OAAO,CAAA;CAAE,GACzB,OAAO,CAAC,IAAI,CAAC,CA4Df"}
1
+ {"version":3,"file":"generateTypes.d.ts","sourceRoot":"","sources":["../../src/bin/generateTypes.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAMzD,wBAAsB,aAAa,CACjC,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE;IAAE,GAAG,EAAE,OAAO,CAAA;CAAE,GACzB,OAAO,CAAC,IAAI,CAAC,CAkEf"}
@@ -36,6 +36,14 @@ export async function generateTypes(config, options) {
36
36
  compiled = addSelectGenericsToGeneratedTypes({
37
37
  compiledGeneratedTypes: compiled
38
38
  });
39
+ if (config.typescript.postProcess?.length) {
40
+ for (const fn of config.typescript.postProcess){
41
+ compiled = fn({
42
+ compiledTypes: compiled,
43
+ config
44
+ });
45
+ }
46
+ }
39
47
  if (config.typescript.declare !== false) {
40
48
  if (config.typescript.declare?.ignoreTSError) {
41
49
  compiled += `\n\n${declareWithTSIgnoreError}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/generateTypes.ts"],"sourcesContent":["import type { AcceptedLanguages } from '@payloadcms/translations'\n\nimport { initI18n } from '@payloadcms/translations'\nimport fs from 'fs/promises'\nimport { compile } from 'json-schema-to-typescript'\n\nimport type { SanitizedConfig } from '../config/types.js'\n\nimport { addSelectGenericsToGeneratedTypes } from '../utilities/addSelectGenericsToGeneretedTypes.js'\nimport { configToJSONSchema } from '../utilities/configToJSONSchema.js'\nimport { getLogger } from '../utilities/logger.js'\n\nexport async function generateTypes(\n config: SanitizedConfig,\n options?: { log: boolean },\n): Promise<void> {\n const logger = getLogger('payload', 'sync')\n const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile\n\n const shouldLog = options?.log ?? true\n\n if (shouldLog) {\n logger.info('Compiling TS types for Collections and Globals...')\n }\n\n const languages = Object.keys(config.i18n.supportedLanguages) as AcceptedLanguages[]\n\n const language = languages.includes('en') ? 'en' : config.i18n.fallbackLanguage\n\n const i18n = await initI18n({ config: config.i18n, context: 'api', language })\n\n const jsonSchema = configToJSONSchema(config, config.db.defaultIDType, i18n)\n\n const declare = `declare module 'payload' {\\n export interface GeneratedTypes extends Config {}\\n}`\n const declareWithTSIgnoreError = `declare module 'payload' {\\n // @ts-ignore \\n export interface GeneratedTypes extends Config {}\\n}`\n\n let compiled = await compile(jsonSchema, 'Config', {\n bannerComment:\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:types` to regenerate this file.\\n*/',\n style: {\n singleQuote: true,\n },\n // Generates code for $defs that aren't referenced by the schema. Reason:\n // If a field defines an interfaceName, it should be included in the generated types\n // even if it's not used by another type. Reason: the user might want to use it in their own code.\n unreachableDefinitions: true,\n // Allow resolving external file references in $ref pointers\n cwd: process.cwd(),\n })\n\n compiled = addSelectGenericsToGeneratedTypes({ compiledGeneratedTypes: compiled })\n\n if (config.typescript.declare !== false) {\n if (config.typescript.declare?.ignoreTSError) {\n compiled += `\\n\\n${declareWithTSIgnoreError}`\n } else {\n compiled += `\\n\\n${declare}`\n }\n }\n\n // Diff the compiled types against the existing types file\n try {\n const existingTypes = await fs.readFile(outputFile, 'utf-8')\n\n if (compiled === existingTypes) {\n return\n }\n } catch (_) {\n // swallow err\n }\n\n await fs.writeFile(outputFile, compiled)\n if (shouldLog) {\n logger.info(`Types written to ${outputFile}`)\n }\n}\n"],"names":["initI18n","fs","compile","addSelectGenericsToGeneratedTypes","configToJSONSchema","getLogger","generateTypes","config","options","logger","outputFile","process","env","PAYLOAD_TS_OUTPUT_PATH","typescript","shouldLog","log","info","languages","Object","keys","i18n","supportedLanguages","language","includes","fallbackLanguage","context","jsonSchema","db","defaultIDType","declare","declareWithTSIgnoreError","compiled","bannerComment","style","singleQuote","unreachableDefinitions","cwd","compiledGeneratedTypes","ignoreTSError","existingTypes","readFile","_","writeFile"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,2BAA0B;AACnD,OAAOC,QAAQ,cAAa;AAC5B,SAASC,OAAO,QAAQ,4BAA2B;AAInD,SAASC,iCAAiC,QAAQ,oDAAmD;AACrG,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,SAAS,QAAQ,yBAAwB;AAElD,OAAO,eAAeC,cACpBC,MAAuB,EACvBC,OAA0B;IAE1B,MAAMC,SAASJ,UAAU,WAAW;IACpC,MAAMK,aAAaC,QAAQC,GAAG,CAACC,sBAAsB,IAAIN,OAAOO,UAAU,CAACJ,UAAU;IAErF,MAAMK,YAAYP,SAASQ,OAAO;IAElC,IAAID,WAAW;QACbN,OAAOQ,IAAI,CAAC;IACd;IAEA,MAAMC,YAAYC,OAAOC,IAAI,CAACb,OAAOc,IAAI,CAACC,kBAAkB;IAE5D,MAAMC,WAAWL,UAAUM,QAAQ,CAAC,QAAQ,OAAOjB,OAAOc,IAAI,CAACI,gBAAgB;IAE/E,MAAMJ,OAAO,MAAMrB,SAAS;QAAEO,QAAQA,OAAOc,IAAI;QAAEK,SAAS;QAAOH;IAAS;IAE5E,MAAMI,aAAavB,mBAAmBG,QAAQA,OAAOqB,EAAE,CAACC,aAAa,EAAER;IAEvE,MAAMS,UAAU,CAAC,kFAAkF,CAAC;IACpG,MAAMC,2BAA2B,CAAC,oGAAoG,CAAC;IAEvI,IAAIC,WAAW,MAAM9B,QAAQyB,YAAY,UAAU;QACjDM,eACE;QACFC,OAAO;YACLC,aAAa;QACf;QACA,yEAAyE;QACzE,oFAAoF;QACpF,kGAAkG;QAClGC,wBAAwB;QACxB,4DAA4D;QAC5DC,KAAK1B,QAAQ0B,GAAG;IAClB;IAEAL,WAAW7B,kCAAkC;QAAEmC,wBAAwBN;IAAS;IAEhF,IAAIzB,OAAOO,UAAU,CAACgB,OAAO,KAAK,OAAO;QACvC,IAAIvB,OAAOO,UAAU,CAACgB,OAAO,EAAES,eAAe;YAC5CP,YAAY,CAAC,IAAI,EAAED,0BAA0B;QAC/C,OAAO;YACLC,YAAY,CAAC,IAAI,EAAEF,SAAS;QAC9B;IACF;IAEA,0DAA0D;IAC1D,IAAI;QACF,MAAMU,gBAAgB,MAAMvC,GAAGwC,QAAQ,CAAC/B,YAAY;QAEpD,IAAIsB,aAAaQ,eAAe;YAC9B;QACF;IACF,EAAE,OAAOE,GAAG;IACV,cAAc;IAChB;IAEA,MAAMzC,GAAG0C,SAAS,CAACjC,YAAYsB;IAC/B,IAAIjB,WAAW;QACbN,OAAOQ,IAAI,CAAC,CAAC,iBAAiB,EAAEP,YAAY;IAC9C;AACF"}
1
+ {"version":3,"sources":["../../src/bin/generateTypes.ts"],"sourcesContent":["import type { AcceptedLanguages } from '@payloadcms/translations'\n\nimport { initI18n } from '@payloadcms/translations'\nimport fs from 'fs/promises'\nimport { compile } from 'json-schema-to-typescript'\n\nimport type { SanitizedConfig } from '../config/types.js'\n\nimport { addSelectGenericsToGeneratedTypes } from '../utilities/addSelectGenericsToGeneretedTypes.js'\nimport { configToJSONSchema } from '../utilities/configToJSONSchema.js'\nimport { getLogger } from '../utilities/logger.js'\n\nexport async function generateTypes(\n config: SanitizedConfig,\n options?: { log: boolean },\n): Promise<void> {\n const logger = getLogger('payload', 'sync')\n const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile\n\n const shouldLog = options?.log ?? true\n\n if (shouldLog) {\n logger.info('Compiling TS types for Collections and Globals...')\n }\n\n const languages = Object.keys(config.i18n.supportedLanguages) as AcceptedLanguages[]\n\n const language = languages.includes('en') ? 'en' : config.i18n.fallbackLanguage\n\n const i18n = await initI18n({ config: config.i18n, context: 'api', language })\n\n const jsonSchema = configToJSONSchema(config, config.db.defaultIDType, i18n)\n\n const declare = `declare module 'payload' {\\n export interface GeneratedTypes extends Config {}\\n}`\n const declareWithTSIgnoreError = `declare module 'payload' {\\n // @ts-ignore \\n export interface GeneratedTypes extends Config {}\\n}`\n\n let compiled = await compile(jsonSchema, 'Config', {\n bannerComment:\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:types` to regenerate this file.\\n*/',\n style: {\n singleQuote: true,\n },\n // Generates code for $defs that aren't referenced by the schema. Reason:\n // If a field defines an interfaceName, it should be included in the generated types\n // even if it's not used by another type. Reason: the user might want to use it in their own code.\n unreachableDefinitions: true,\n // Allow resolving external file references in $ref pointers\n cwd: process.cwd(),\n })\n\n compiled = addSelectGenericsToGeneratedTypes({ compiledGeneratedTypes: compiled })\n\n if (config.typescript.postProcess?.length) {\n for (const fn of config.typescript.postProcess) {\n compiled = fn({ compiledTypes: compiled, config })\n }\n }\n\n if (config.typescript.declare !== false) {\n if (config.typescript.declare?.ignoreTSError) {\n compiled += `\\n\\n${declareWithTSIgnoreError}`\n } else {\n compiled += `\\n\\n${declare}`\n }\n }\n\n // Diff the compiled types against the existing types file\n try {\n const existingTypes = await fs.readFile(outputFile, 'utf-8')\n\n if (compiled === existingTypes) {\n return\n }\n } catch (_) {\n // swallow err\n }\n\n await fs.writeFile(outputFile, compiled)\n if (shouldLog) {\n logger.info(`Types written to ${outputFile}`)\n }\n}\n"],"names":["initI18n","fs","compile","addSelectGenericsToGeneratedTypes","configToJSONSchema","getLogger","generateTypes","config","options","logger","outputFile","process","env","PAYLOAD_TS_OUTPUT_PATH","typescript","shouldLog","log","info","languages","Object","keys","i18n","supportedLanguages","language","includes","fallbackLanguage","context","jsonSchema","db","defaultIDType","declare","declareWithTSIgnoreError","compiled","bannerComment","style","singleQuote","unreachableDefinitions","cwd","compiledGeneratedTypes","postProcess","length","fn","compiledTypes","ignoreTSError","existingTypes","readFile","_","writeFile"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,2BAA0B;AACnD,OAAOC,QAAQ,cAAa;AAC5B,SAASC,OAAO,QAAQ,4BAA2B;AAInD,SAASC,iCAAiC,QAAQ,oDAAmD;AACrG,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,SAAS,QAAQ,yBAAwB;AAElD,OAAO,eAAeC,cACpBC,MAAuB,EACvBC,OAA0B;IAE1B,MAAMC,SAASJ,UAAU,WAAW;IACpC,MAAMK,aAAaC,QAAQC,GAAG,CAACC,sBAAsB,IAAIN,OAAOO,UAAU,CAACJ,UAAU;IAErF,MAAMK,YAAYP,SAASQ,OAAO;IAElC,IAAID,WAAW;QACbN,OAAOQ,IAAI,CAAC;IACd;IAEA,MAAMC,YAAYC,OAAOC,IAAI,CAACb,OAAOc,IAAI,CAACC,kBAAkB;IAE5D,MAAMC,WAAWL,UAAUM,QAAQ,CAAC,QAAQ,OAAOjB,OAAOc,IAAI,CAACI,gBAAgB;IAE/E,MAAMJ,OAAO,MAAMrB,SAAS;QAAEO,QAAQA,OAAOc,IAAI;QAAEK,SAAS;QAAOH;IAAS;IAE5E,MAAMI,aAAavB,mBAAmBG,QAAQA,OAAOqB,EAAE,CAACC,aAAa,EAAER;IAEvE,MAAMS,UAAU,CAAC,kFAAkF,CAAC;IACpG,MAAMC,2BAA2B,CAAC,oGAAoG,CAAC;IAEvI,IAAIC,WAAW,MAAM9B,QAAQyB,YAAY,UAAU;QACjDM,eACE;QACFC,OAAO;YACLC,aAAa;QACf;QACA,yEAAyE;QACzE,oFAAoF;QACpF,kGAAkG;QAClGC,wBAAwB;QACxB,4DAA4D;QAC5DC,KAAK1B,QAAQ0B,GAAG;IAClB;IAEAL,WAAW7B,kCAAkC;QAAEmC,wBAAwBN;IAAS;IAEhF,IAAIzB,OAAOO,UAAU,CAACyB,WAAW,EAAEC,QAAQ;QACzC,KAAK,MAAMC,MAAMlC,OAAOO,UAAU,CAACyB,WAAW,CAAE;YAC9CP,WAAWS,GAAG;gBAAEC,eAAeV;gBAAUzB;YAAO;QAClD;IACF;IAEA,IAAIA,OAAOO,UAAU,CAACgB,OAAO,KAAK,OAAO;QACvC,IAAIvB,OAAOO,UAAU,CAACgB,OAAO,EAAEa,eAAe;YAC5CX,YAAY,CAAC,IAAI,EAAED,0BAA0B;QAC/C,OAAO;YACLC,YAAY,CAAC,IAAI,EAAEF,SAAS;QAC9B;IACF;IAEA,0DAA0D;IAC1D,IAAI;QACF,MAAMc,gBAAgB,MAAM3C,GAAG4C,QAAQ,CAACnC,YAAY;QAEpD,IAAIsB,aAAaY,eAAe;YAC9B;QACF;IACF,EAAE,OAAOE,GAAG;IACV,cAAc;IAChB;IAEA,MAAM7C,GAAG8C,SAAS,CAACrC,YAAYsB;IAC/B,IAAIjB,WAAW;QACbN,OAAOQ,IAAI,CAAC,CAAC,iBAAiB,EAAEP,YAAY;IAC9C;AACF"}
@@ -1,4 +1,5 @@
1
1
  import type { Config, SanitizedConfig } from '../../config/types.js';
2
+ import type { OrderableJoinInfo } from '../../fields/config/sanitizeJoinField.js';
2
3
  import type { CollectionConfig, SanitizedCollectionConfig } from './types.js';
3
- export declare const sanitizeCollection: (config: Config, collection: CollectionConfig, richTextSanitizationPromises?: Array<(config: SanitizedConfig) => Promise<void>>, _validRelationships?: string[]) => Promise<SanitizedCollectionConfig>;
4
+ export declare const sanitizeCollection: (config: Config, collection: CollectionConfig, richTextSanitizationPromises?: Array<(config: SanitizedConfig) => Promise<void>>, _validRelationships?: string[], orderableJoins?: OrderableJoinInfo[]) => Promise<SanitizedCollectionConfig>;
4
5
  //# sourceMappingURL=sanitize.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../../src/collections/config/sanitize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,KAAK,EACV,gBAAgB,EAChB,yBAAyB,EAG1B,MAAM,YAAY,CAAA;AAyBnB,eAAO,MAAM,kBAAkB,WACrB,MAAM,cACF,gBAAgB,iCAKG,KAAK,CAAC,CAAC,MAAM,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,wBAC1D,MAAM,EAAE,KAC7B,OAAO,CAAC,yBAAyB,CAgRnC,CAAA"}
1
+ {"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../../src/collections/config/sanitize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAA;AACjF,OAAO,KAAK,EACV,gBAAgB,EAChB,yBAAyB,EAG1B,MAAM,YAAY,CAAA;AAyBnB,eAAO,MAAM,kBAAkB,WACrB,MAAM,cACF,gBAAgB,iCAKG,KAAK,CAAC,CAAC,MAAM,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,wBAC1D,MAAM,EAAE,mBAIb,iBAAiB,EAAE,KACnC,OAAO,CAAC,yBAAyB,CAiRnC,CAAA"}
@@ -19,7 +19,9 @@ import { validateUseAsTitle } from './useAsTitle.js';
19
19
  export const sanitizeCollection = async (config, collection, /**
20
20
  * If this property is set, RichText fields won't be sanitized immediately. Instead, they will be added to this array as promises
21
21
  * so that you can sanitize them together, after the config has been sanitized.
22
- */ richTextSanitizationPromises, _validRelationships)=>{
22
+ */ richTextSanitizationPromises, _validRelationships, /**
23
+ * Tracker for orderable join fields - populated during sanitization
24
+ */ orderableJoins)=>{
23
25
  if (collection._sanitized) {
24
26
  return collection;
25
27
  }
@@ -40,6 +42,7 @@ export const sanitizeCollection = async (config, collection, /**
40
42
  fields: sanitized.fields,
41
43
  joinPath: '',
42
44
  joins,
45
+ orderableJoins,
43
46
  parentIsLocalized: false,
44
47
  polymorphicJoins,
45
48
  richTextSanitizationPromises,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/collections/config/sanitize.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from '../../config/types.js'\nimport type {\n CollectionConfig,\n SanitizedCollectionConfig,\n SanitizedJoin,\n SanitizedJoins,\n} from './types.js'\n\nimport { authCollectionEndpoints } from '../../auth/endpoints/index.js'\nimport { getBaseAuthFields } from '../../auth/getAuthFields.js'\nimport { TimestampsRequired } from '../../errors/TimestampsRequired.js'\nimport { sanitizeFields } from '../../fields/config/sanitize.js'\nimport { fieldAffectsData } from '../../fields/config/types.js'\nimport { mergeBaseFields } from '../../fields/mergeBaseFields.js'\nimport { uploadCollectionEndpoints } from '../../uploads/endpoints/index.js'\nimport { getBaseUploadFields } from '../../uploads/getBaseFields.js'\nimport { flattenAllFields } from '../../utilities/flattenAllFields.js'\nimport { formatLabels } from '../../utilities/formatLabels.js'\nimport { miniChalk } from '../../utilities/miniChalk.js'\nimport { traverseForLocalizedFields } from '../../utilities/traverseForLocalizedFields.js'\nimport { baseVersionFields } from '../../versions/baseFields.js'\nimport { versionDefaults } from '../../versions/defaults.js'\nimport { defaultCollectionEndpoints } from '../endpoints/index.js'\nimport {\n addDefaultsToAuthConfig,\n addDefaultsToCollectionConfig,\n addDefaultsToLoginWithUsernameConfig,\n} from './defaults.js'\nimport { sanitizeCompoundIndexes } from './sanitizeCompoundIndexes.js'\nimport { validateUseAsTitle } from './useAsTitle.js'\n\nexport const sanitizeCollection = async (\n config: Config,\n collection: CollectionConfig,\n /**\n * If this property is set, RichText fields won't be sanitized immediately. Instead, they will be added to this array as promises\n * so that you can sanitize them together, after the config has been sanitized.\n */\n richTextSanitizationPromises?: Array<(config: SanitizedConfig) => Promise<void>>,\n _validRelationships?: string[],\n): Promise<SanitizedCollectionConfig> => {\n if (collection._sanitized) {\n return collection as SanitizedCollectionConfig\n }\n\n collection._sanitized = true\n\n // /////////////////////////////////\n // Make copy of collection config\n // /////////////////////////////////\n\n const sanitized: CollectionConfig = addDefaultsToCollectionConfig(collection)\n\n // /////////////////////////////////\n // Sanitize fields\n // /////////////////////////////////\n\n const validRelationships = _validRelationships ?? config.collections!.map((c) => c.slug) ?? []\n\n const joins: SanitizedJoins = {}\n\n const polymorphicJoins: SanitizedJoin[] = []\n\n sanitized.fields = await sanitizeFields({\n collectionConfig: sanitized,\n config,\n fields: sanitized.fields,\n joinPath: '',\n joins,\n parentIsLocalized: false,\n polymorphicJoins,\n richTextSanitizationPromises,\n validRelationships,\n })\n\n if (sanitized.endpoints !== false) {\n if (!sanitized.endpoints) {\n sanitized.endpoints = []\n }\n\n if (sanitized.auth) {\n for (const endpoint of authCollectionEndpoints) {\n sanitized.endpoints.push(endpoint)\n }\n }\n\n if (sanitized.upload) {\n for (const endpoint of uploadCollectionEndpoints) {\n sanitized.endpoints.push(endpoint)\n }\n }\n\n for (const endpoint of defaultCollectionEndpoints) {\n sanitized.endpoints.push(endpoint)\n }\n }\n\n if (sanitized.timestamps !== false) {\n // add default timestamps fields only as needed\n let hasUpdatedAt: boolean | null = null\n let hasCreatedAt: boolean | null = null\n let hasDeletedAt: boolean | null = null\n\n sanitized.fields.some((field) => {\n if (fieldAffectsData(field)) {\n if (field.name === 'updatedAt') {\n hasUpdatedAt = true\n }\n\n if (field.name === 'createdAt') {\n hasCreatedAt = true\n }\n\n if (field.name === 'deletedAt') {\n hasDeletedAt = true\n }\n }\n\n return hasCreatedAt && hasUpdatedAt && (!sanitized.trash || hasDeletedAt)\n })\n\n if (!hasUpdatedAt) {\n sanitized.fields.push({\n name: 'updatedAt',\n type: 'date',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n },\n index: true,\n label: ({ t }) => t('general:updatedAt'),\n })\n }\n\n if (!hasCreatedAt) {\n sanitized.fields.push({\n name: 'createdAt',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n },\n // The default sort for list view is createdAt. Thus, enabling indexing by default, is a major performance improvement, especially for large or a large amount of collections.\n type: 'date',\n index: true,\n label: ({ t }) => t('general:createdAt'),\n })\n }\n\n if (sanitized.trash && !hasDeletedAt) {\n sanitized.fields.push({\n name: 'deletedAt',\n type: 'date',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n },\n index: true,\n label: ({ t }) => t('general:deletedAt'),\n })\n }\n }\n\n const defaultLabels = formatLabels(sanitized.slug)\n\n sanitized.labels = {\n plural: sanitized.labels?.plural || defaultLabels.plural,\n singular: sanitized.labels?.singular || defaultLabels.singular,\n }\n\n if (sanitized.versions) {\n if (sanitized.timestamps === false) {\n throw new TimestampsRequired(collection)\n }\n\n if (sanitized.versions === true) {\n sanitized.versions = {\n drafts: false,\n maxPerDoc: 100,\n }\n }\n\n sanitized.versions.maxPerDoc =\n typeof sanitized.versions.maxPerDoc === 'number' ? sanitized.versions.maxPerDoc : 100\n\n if (sanitized.versions.drafts) {\n if (sanitized.versions.drafts === true) {\n sanitized.versions.drafts = {\n autosave: false,\n validate: false,\n }\n }\n\n const hasLocalizedFields = traverseForLocalizedFields(sanitized.fields)\n\n if (config.localization) {\n if (hasLocalizedFields && sanitized.versions.drafts.localizeStatus === undefined) {\n sanitized.versions.drafts.localizeStatus = false\n }\n }\n\n // TODO v4: remove this sanitization check, should not need to enable the experimental flag\n if (sanitized.versions.drafts.localizeStatus && !config.experimental?.localizeStatus) {\n sanitized.versions.drafts.localizeStatus = false\n console.log(\n miniChalk.yellowBold(\n `Warning: \"localizeStatus\" for drafts is an experimental feature. To enable, set \"experimental.localizeStatus\" to true in your Payload config.`,\n ),\n )\n }\n\n if (sanitized.versions.drafts.autosave === true) {\n sanitized.versions.drafts.autosave = {\n interval: versionDefaults.autosaveInterval,\n }\n }\n\n if (sanitized.versions.drafts.validate === undefined) {\n sanitized.versions.drafts.validate = false\n }\n\n sanitized.fields = mergeBaseFields(\n sanitized.fields,\n baseVersionFields({\n localized: sanitized.versions.drafts.localizeStatus ?? false,\n }),\n )\n }\n } else {\n delete sanitized.versions\n }\n\n if (sanitized.folders === true) {\n sanitized.folders = {\n browseByFolder: true,\n }\n } else if (sanitized.folders) {\n sanitized.folders.browseByFolder = sanitized.folders.browseByFolder ?? true\n }\n\n if (sanitized.upload) {\n if (sanitized.upload === true) {\n sanitized.upload = {}\n }\n\n sanitized.upload.cacheTags = sanitized.upload?.cacheTags ?? true\n sanitized.upload.bulkUpload = sanitized.upload?.bulkUpload ?? true\n sanitized.upload.staticDir = sanitized.upload.staticDir || sanitized.slug\n sanitized.admin!.useAsTitle =\n sanitized.admin?.useAsTitle && sanitized.admin.useAsTitle !== 'id'\n ? sanitized.admin.useAsTitle\n : 'filename'\n\n const uploadFields = getBaseUploadFields({\n collection: sanitized,\n config,\n })\n\n sanitized.fields = mergeBaseFields(sanitized.fields, uploadFields)\n }\n\n if (sanitized.auth) {\n sanitized.auth = addDefaultsToAuthConfig(\n typeof sanitized.auth === 'boolean' ? {} : sanitized.auth,\n )\n\n // disable duplicate for auth enabled collections by default\n sanitized.disableDuplicate = sanitized.disableDuplicate ?? true\n\n if (sanitized.auth.loginWithUsername) {\n if (sanitized.auth.loginWithUsername === true) {\n sanitized.auth.loginWithUsername = addDefaultsToLoginWithUsernameConfig({})\n } else {\n const loginWithUsernameWithDefaults = addDefaultsToLoginWithUsernameConfig(\n sanitized.auth.loginWithUsername,\n )\n\n // if allowEmailLogin is false, requireUsername must be true\n if (loginWithUsernameWithDefaults.allowEmailLogin === false) {\n loginWithUsernameWithDefaults.requireUsername = true\n }\n sanitized.auth.loginWithUsername = loginWithUsernameWithDefaults\n }\n } else {\n sanitized.auth.loginWithUsername = false\n }\n\n if (!collection?.admin?.useAsTitle) {\n sanitized.admin!.useAsTitle = sanitized.auth.loginWithUsername ? 'username' : 'email'\n }\n\n sanitized.fields = mergeBaseFields(sanitized.fields, getBaseAuthFields(sanitized.auth))\n }\n\n if (collection?.admin?.pagination?.limits?.length) {\n sanitized.admin!.pagination!.limits = collection.admin.pagination.limits\n }\n\n validateUseAsTitle(sanitized)\n\n const sanitizedConfig = sanitized as SanitizedCollectionConfig\n\n sanitizedConfig.joins = joins\n sanitizedConfig.polymorphicJoins = polymorphicJoins\n\n sanitizedConfig.flattenedFields = flattenAllFields({ fields: sanitizedConfig.fields })\n\n sanitizedConfig.sanitizedIndexes = sanitizeCompoundIndexes({\n fields: sanitizedConfig.flattenedFields,\n indexes: sanitizedConfig.indexes,\n })\n\n return sanitizedConfig\n}\n"],"names":["authCollectionEndpoints","getBaseAuthFields","TimestampsRequired","sanitizeFields","fieldAffectsData","mergeBaseFields","uploadCollectionEndpoints","getBaseUploadFields","flattenAllFields","formatLabels","miniChalk","traverseForLocalizedFields","baseVersionFields","versionDefaults","defaultCollectionEndpoints","addDefaultsToAuthConfig","addDefaultsToCollectionConfig","addDefaultsToLoginWithUsernameConfig","sanitizeCompoundIndexes","validateUseAsTitle","sanitizeCollection","config","collection","richTextSanitizationPromises","_validRelationships","_sanitized","sanitized","validRelationships","collections","map","c","slug","joins","polymorphicJoins","fields","collectionConfig","joinPath","parentIsLocalized","endpoints","auth","endpoint","push","upload","timestamps","hasUpdatedAt","hasCreatedAt","hasDeletedAt","some","field","name","trash","type","admin","disableBulkEdit","hidden","index","label","t","defaultLabels","labels","plural","singular","versions","drafts","maxPerDoc","autosave","validate","hasLocalizedFields","localization","localizeStatus","undefined","experimental","console","log","yellowBold","interval","autosaveInterval","localized","folders","browseByFolder","cacheTags","bulkUpload","staticDir","useAsTitle","uploadFields","disableDuplicate","loginWithUsername","loginWithUsernameWithDefaults","allowEmailLogin","requireUsername","pagination","limits","length","sanitizedConfig","flattenedFields","sanitizedIndexes","index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,YAAY;YAClCzD,UAAU0B,KAAK,CAAE+B,UAAU,GAAGzD,UAAUa,IAAI,CAAC+C,iBAAiB,GAAG,aAAa;QAChF;QAEA5D,UAAUQ,MAAM,GAAG7B,gBAAgBqB,UAAUQ,MAAM,EAAEjC,kBAAkByB,UAAUa,IAAI;IACvF;IAEA,IAAIjB,YAAY8B,OAAOsC,YAAYC,QAAQC,QAAQ;QACjDlE,UAAU0B,KAAK,CAAEsC,UAAU,CAAEC,MAAM,GAAGrE,WAAW8B,KAAK,CAACsC,UAAU,CAACC,MAAM;IAC1E;IAEAxE,mBAAmBO;IAEnB,MAAMmE,kBAAkBnE;IAExBmE,gBAAgB7D,KAAK,GAAGA;IACxB6D,gBAAgB5D,gBAAgB,GAAGA;IAEnC4D,gBAAgBC,eAAe,GAAGtF,iBAAiB;QAAE0B,QAAQ2D,gBAAgB3D,MAAM;IAAC;IAEpF2D,gBAAgBE,gBAAgB,GAAG7E,wBAAwB;QACzDgB,QAAQ2D,gBAAgBC,eAAe;QACvCE,SAASH,gBAAgBG,OAAO;IAClC;IAEA,OAAOH;AACT,EAAC"}
1
+ {"version":3,"sources":["../../../src/collections/config/sanitize.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from '../../config/types.js'\nimport type { OrderableJoinInfo } from '../../fields/config/sanitizeJoinField.js'\nimport type {\n CollectionConfig,\n SanitizedCollectionConfig,\n SanitizedJoin,\n SanitizedJoins,\n} from './types.js'\n\nimport { authCollectionEndpoints } from '../../auth/endpoints/index.js'\nimport { getBaseAuthFields } from '../../auth/getAuthFields.js'\nimport { TimestampsRequired } from '../../errors/TimestampsRequired.js'\nimport { sanitizeFields } from '../../fields/config/sanitize.js'\nimport { fieldAffectsData } from '../../fields/config/types.js'\nimport { mergeBaseFields } from '../../fields/mergeBaseFields.js'\nimport { uploadCollectionEndpoints } from '../../uploads/endpoints/index.js'\nimport { getBaseUploadFields } from '../../uploads/getBaseFields.js'\nimport { flattenAllFields } from '../../utilities/flattenAllFields.js'\nimport { formatLabels } from '../../utilities/formatLabels.js'\nimport { miniChalk } from '../../utilities/miniChalk.js'\nimport { traverseForLocalizedFields } from '../../utilities/traverseForLocalizedFields.js'\nimport { baseVersionFields } from '../../versions/baseFields.js'\nimport { versionDefaults } from '../../versions/defaults.js'\nimport { defaultCollectionEndpoints } from '../endpoints/index.js'\nimport {\n addDefaultsToAuthConfig,\n addDefaultsToCollectionConfig,\n addDefaultsToLoginWithUsernameConfig,\n} from './defaults.js'\nimport { sanitizeCompoundIndexes } from './sanitizeCompoundIndexes.js'\nimport { validateUseAsTitle } from './useAsTitle.js'\n\nexport const sanitizeCollection = async (\n config: Config,\n collection: CollectionConfig,\n /**\n * If this property is set, RichText fields won't be sanitized immediately. Instead, they will be added to this array as promises\n * so that you can sanitize them together, after the config has been sanitized.\n */\n richTextSanitizationPromises?: Array<(config: SanitizedConfig) => Promise<void>>,\n _validRelationships?: string[],\n /**\n * Tracker for orderable join fields - populated during sanitization\n */\n orderableJoins?: OrderableJoinInfo[],\n): Promise<SanitizedCollectionConfig> => {\n if (collection._sanitized) {\n return collection as SanitizedCollectionConfig\n }\n\n collection._sanitized = true\n\n // /////////////////////////////////\n // Make copy of collection config\n // /////////////////////////////////\n\n const sanitized: CollectionConfig = addDefaultsToCollectionConfig(collection)\n\n // /////////////////////////////////\n // Sanitize fields\n // /////////////////////////////////\n\n const validRelationships = _validRelationships ?? config.collections!.map((c) => c.slug) ?? []\n\n const joins: SanitizedJoins = {}\n\n const polymorphicJoins: SanitizedJoin[] = []\n\n sanitized.fields = await sanitizeFields({\n collectionConfig: sanitized,\n config,\n fields: sanitized.fields,\n joinPath: '',\n joins,\n orderableJoins,\n parentIsLocalized: false,\n polymorphicJoins,\n richTextSanitizationPromises,\n validRelationships,\n })\n\n if (sanitized.endpoints !== false) {\n if (!sanitized.endpoints) {\n sanitized.endpoints = []\n }\n\n if (sanitized.auth) {\n for (const endpoint of authCollectionEndpoints) {\n sanitized.endpoints.push(endpoint)\n }\n }\n\n if (sanitized.upload) {\n for (const endpoint of uploadCollectionEndpoints) {\n sanitized.endpoints.push(endpoint)\n }\n }\n\n for (const endpoint of defaultCollectionEndpoints) {\n sanitized.endpoints.push(endpoint)\n }\n }\n\n if (sanitized.timestamps !== false) {\n // add default timestamps fields only as needed\n let hasUpdatedAt: boolean | null = null\n let hasCreatedAt: boolean | null = null\n let hasDeletedAt: boolean | null = null\n\n sanitized.fields.some((field) => {\n if (fieldAffectsData(field)) {\n if (field.name === 'updatedAt') {\n hasUpdatedAt = true\n }\n\n if (field.name === 'createdAt') {\n hasCreatedAt = true\n }\n\n if (field.name === 'deletedAt') {\n hasDeletedAt = true\n }\n }\n\n return hasCreatedAt && hasUpdatedAt && (!sanitized.trash || hasDeletedAt)\n })\n\n if (!hasUpdatedAt) {\n sanitized.fields.push({\n name: 'updatedAt',\n type: 'date',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n },\n index: true,\n label: ({ t }) => t('general:updatedAt'),\n })\n }\n\n if (!hasCreatedAt) {\n sanitized.fields.push({\n name: 'createdAt',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n },\n // The default sort for list view is createdAt. Thus, enabling indexing by default, is a major performance improvement, especially for large or a large amount of collections.\n type: 'date',\n index: true,\n label: ({ t }) => t('general:createdAt'),\n })\n }\n\n if (sanitized.trash && !hasDeletedAt) {\n sanitized.fields.push({\n name: 'deletedAt',\n type: 'date',\n admin: {\n disableBulkEdit: true,\n hidden: true,\n },\n index: true,\n label: ({ t }) => t('general:deletedAt'),\n })\n }\n }\n\n const defaultLabels = formatLabels(sanitized.slug)\n\n sanitized.labels = {\n plural: sanitized.labels?.plural || defaultLabels.plural,\n singular: sanitized.labels?.singular || defaultLabels.singular,\n }\n\n if (sanitized.versions) {\n if (sanitized.timestamps === false) {\n throw new TimestampsRequired(collection)\n }\n\n if (sanitized.versions === true) {\n sanitized.versions = {\n drafts: false,\n maxPerDoc: 100,\n }\n }\n\n sanitized.versions.maxPerDoc =\n typeof sanitized.versions.maxPerDoc === 'number' ? sanitized.versions.maxPerDoc : 100\n\n if (sanitized.versions.drafts) {\n if (sanitized.versions.drafts === true) {\n sanitized.versions.drafts = {\n autosave: false,\n validate: false,\n }\n }\n\n const hasLocalizedFields = traverseForLocalizedFields(sanitized.fields)\n\n if (config.localization) {\n if (hasLocalizedFields && sanitized.versions.drafts.localizeStatus === undefined) {\n sanitized.versions.drafts.localizeStatus = false\n }\n }\n\n // TODO v4: remove this sanitization check, should not need to enable the experimental flag\n if (sanitized.versions.drafts.localizeStatus && !config.experimental?.localizeStatus) {\n sanitized.versions.drafts.localizeStatus = false\n console.log(\n miniChalk.yellowBold(\n `Warning: \"localizeStatus\" for drafts is an experimental feature. To enable, set \"experimental.localizeStatus\" to true in your Payload config.`,\n ),\n )\n }\n\n if (sanitized.versions.drafts.autosave === true) {\n sanitized.versions.drafts.autosave = {\n interval: versionDefaults.autosaveInterval,\n }\n }\n\n if (sanitized.versions.drafts.validate === undefined) {\n sanitized.versions.drafts.validate = false\n }\n\n sanitized.fields = mergeBaseFields(\n sanitized.fields,\n baseVersionFields({\n localized: sanitized.versions.drafts.localizeStatus ?? false,\n }),\n )\n }\n } else {\n delete sanitized.versions\n }\n\n if (sanitized.folders === true) {\n sanitized.folders = {\n browseByFolder: true,\n }\n } else if (sanitized.folders) {\n sanitized.folders.browseByFolder = sanitized.folders.browseByFolder ?? true\n }\n\n if (sanitized.upload) {\n if (sanitized.upload === true) {\n sanitized.upload = {}\n }\n\n sanitized.upload.cacheTags = sanitized.upload?.cacheTags ?? true\n sanitized.upload.bulkUpload = sanitized.upload?.bulkUpload ?? true\n sanitized.upload.staticDir = sanitized.upload.staticDir || sanitized.slug\n sanitized.admin!.useAsTitle =\n sanitized.admin?.useAsTitle && sanitized.admin.useAsTitle !== 'id'\n ? sanitized.admin.useAsTitle\n : 'filename'\n\n const uploadFields = getBaseUploadFields({\n collection: sanitized,\n config,\n })\n\n sanitized.fields = mergeBaseFields(sanitized.fields, uploadFields)\n }\n\n if (sanitized.auth) {\n sanitized.auth = addDefaultsToAuthConfig(\n typeof sanitized.auth === 'boolean' ? {} : sanitized.auth,\n )\n\n // disable duplicate for auth enabled collections by default\n sanitized.disableDuplicate = sanitized.disableDuplicate ?? true\n\n if (sanitized.auth.loginWithUsername) {\n if (sanitized.auth.loginWithUsername === true) {\n sanitized.auth.loginWithUsername = addDefaultsToLoginWithUsernameConfig({})\n } else {\n const loginWithUsernameWithDefaults = addDefaultsToLoginWithUsernameConfig(\n sanitized.auth.loginWithUsername,\n )\n\n // if allowEmailLogin is false, requireUsername must be true\n if (loginWithUsernameWithDefaults.allowEmailLogin === false) {\n loginWithUsernameWithDefaults.requireUsername = true\n }\n sanitized.auth.loginWithUsername = loginWithUsernameWithDefaults\n }\n } else {\n sanitized.auth.loginWithUsername = false\n }\n\n if (!collection?.admin?.useAsTitle) {\n sanitized.admin!.useAsTitle = sanitized.auth.loginWithUsername ? 'username' : 'email'\n }\n\n sanitized.fields = mergeBaseFields(sanitized.fields, getBaseAuthFields(sanitized.auth))\n }\n\n if (collection?.admin?.pagination?.limits?.length) {\n sanitized.admin!.pagination!.limits = collection.admin.pagination.limits\n }\n\n validateUseAsTitle(sanitized)\n\n const sanitizedConfig = sanitized as SanitizedCollectionConfig\n\n sanitizedConfig.joins = joins\n sanitizedConfig.polymorphicJoins = polymorphicJoins\n\n sanitizedConfig.flattenedFields = flattenAllFields({ fields: sanitizedConfig.fields })\n\n sanitizedConfig.sanitizedIndexes = sanitizeCompoundIndexes({\n fields: sanitizedConfig.flattenedFields,\n indexes: sanitizedConfig.indexes,\n })\n\n return sanitizedConfig\n}\n"],"names":["authCollectionEndpoints","getBaseAuthFields","TimestampsRequired","sanitizeFields","fieldAffectsData","mergeBaseFields","uploadCollectionEndpoints","getBaseUploadFields","flattenAllFields","formatLabels","miniChalk","traverseForLocalizedFields","baseVersionFields","versionDefaults","defaultCollectionEndpoints","addDefaultsToAuthConfig","addDefaultsToCollectionConfig","addDefaultsToLoginWithUsernameConfig","sanitizeCompoundIndexes","validateUseAsTitle","sanitizeCollection","config","collection","richTextSanitizationPromises","_validRelationships","orderableJoins","_sanitized","sanitized","validRelationships","collections","map","c","slug","joins","polymorphicJoins","fields","collectionConfig","joinPath","parentIsLocalized","endpoints","auth","endpoint","push","upload","timestamps","hasUpdatedAt","hasCreatedAt","hasDeletedAt","some","field","name","trash","type","admin","disableBulkEdit","hidden","index","label","t","defaultLabels","labels","plural","singular","versions","drafts","maxPerDoc","autosave","validate","hasLocalizedFields","localization","localizeStatus","undefined","experimental","console","log","yellowBold","interval","autosaveInterval","localized","folders","browseByFolder","cacheTags","bulkUpload","staticDir","useAsTitle","uploadFields","disableDuplicate","loginWithUsername","loginWithUsernameWithDefaults","allowEmailLogin","requireUsername","pagination","limits","length","sanitizedConfig","flattenedFields","sanitizedIndexes","indexes"],"mappings":"AASA,SAASA,uBAAuB,QAAQ,gCAA+B;AACvE,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,cAAc,QAAQ,kCAAiC;AAChE,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,eAAe,QAAQ,kCAAiC;AACjE,SAASC,yBAAyB,QAAQ,mCAAkC;AAC5E,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,gBAAgB,QAAQ,sCAAqC;AACtE,SAASC,YAAY,QAAQ,kCAAiC;AAC9D,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SAASC,0BAA0B,QAAQ,gDAA+C;AAC1F,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,0BAA0B,QAAQ,wBAAuB;AAClE,SACEC,uBAAuB,EACvBC,6BAA6B,EAC7BC,oCAAoC,QAC/B,gBAAe;AACtB,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,kBAAiB;AAEpD,OAAO,MAAMC,qBAAqB,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
@@ -1 +1 @@
1
- {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/collections/operations/utilities/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAGhD,OAAO,KAAK,EACV,cAAc,EACd,UAAU,EACV,eAAe,EACf,mBAAmB,EACpB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,KAAK,EACV,UAAU,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,UAAU,EACV,6BAA6B,EAC9B,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,EACV,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,UAAU,EACX,MAAM,uBAAuB,CAAA;AAkB9B,MAAM,MAAM,wBAAwB,CAAC,KAAK,SAAS,cAAc,IAAI;IACnE,QAAQ,EAAE,OAAO,CAAA;IACjB,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,WAAW,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,KAAK,EAAE,MAAM,CAAA;IACb,cAAc,EAAE,UAAU,GAAG,UAAU,CAAA;IACvC,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,EAAE,mBAAmB,CAAA;IACnC,aAAa,EAAE,UAAU,EAAE,CAAA;IAC3B,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,EAAE,OAAO,CAAA;IACvB,YAAY,EAAE,OAAO,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,EAAE,UAAU,CAAA;IAClB,gBAAgB,EAAE,OAAO,CAAA;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,cAAc,GACzB,KAAK,SAAS,cAAc,EAC5B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,uUAuB9C,wBAAwB,CAAC,KAAK,CAAC,KAAG,OAAO,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,CA0WzF,CAAA"}
1
+ {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/collections/operations/utilities/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAGhD,OAAO,KAAK,EACV,cAAc,EACd,UAAU,EACV,eAAe,EACf,mBAAmB,EACpB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,KAAK,EACV,UAAU,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,UAAU,EACV,6BAA6B,EAC9B,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,EACV,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,UAAU,EACX,MAAM,uBAAuB,CAAA;AAkB9B,MAAM,MAAM,wBAAwB,CAAC,KAAK,SAAS,cAAc,IAAI;IACnE,QAAQ,EAAE,OAAO,CAAA;IACjB,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,WAAW,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,KAAK,EAAE,MAAM,CAAA;IACb,cAAc,EAAE,UAAU,GAAG,UAAU,CAAA;IACvC,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,EAAE,mBAAmB,CAAA;IACnC,aAAa,EAAE,UAAU,EAAE,CAAA;IAC3B,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,EAAE,OAAO,CAAA;IACvB,YAAY,EAAE,OAAO,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,EAAE,UAAU,CAAA;IAClB,gBAAgB,EAAE,OAAO,CAAA;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,cAAc,GACzB,KAAK,SAAS,cAAc,EAC5B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,uUAuB9C,wBAAwB,CAAC,KAAK,CAAC,KAAG,OAAO,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,CA4WzF,CAAA"}
@@ -145,7 +145,8 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
145
145
  req,
146
146
  skipValidation: // only skip validation for drafts when draft validation is false
147
147
  isSavingDraft && !hasDraftValidationEnabled(collectionConfig) || // Skip validation for trash operations since they're just metadata updates
148
- collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)
148
+ collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash) || // Skip validation for unpublish operations — they only change _status, not document data
149
+ unpublishAllLocales
149
150
  };
150
151
  // /////////////////////////////////////
151
152
  // Handle Localized Data Merging
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, getLatestCollectionVersion, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideAccess: boolean\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n publishSpecificLocale?: string\n req: PayloadRequest\n select: SelectType\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n}\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n publishSpecificLocale,\n req,\n select,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const password = data?.password\n const publishAllLocales =\n !draftArg &&\n (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true))\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n if (isSavingDraft) {\n data._status = 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Delete any associated files\n // /////////////////////////////////////\n\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // Write files to local storage\n // /////////////////////////////////////\n\n if (!collectionConfig.upload.disableLocalStorage) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: originalDoc,\n docWithLocales,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n skipValidation:\n // only skip validation for drafts when draft validation is false\n (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||\n // Skip validation for trash operations since they're just metadata updates\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)),\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let result: JsonObject = await beforeChange(beforeChangeArgs)\n let snapshotToSave: JsonObject | undefined\n\n if (config.localization && collectionConfig.versions) {\n let snapshotData: JsonObject | undefined\n let currentDoc\n\n if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {\n if (publishAllLocales || unpublishAllLocales) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (!isSavingDraft) {\n // publishing a single locale\n currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: id } },\n })\n snapshotData = result\n }\n } else if (publishSpecificLocale) {\n // previous way of publishing a single locale\n currentDoc = await getLatestCollectionVersion({\n id,\n config: collectionConfig,\n payload,\n published: true,\n query: {\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n snapshotData = {\n ...result,\n _status: 'draft',\n }\n }\n\n if (snapshotData) {\n snapshotToSave = deepCopyObjectSimple(snapshotData || {})\n\n result = mergeLocalizedData({\n configBlockReferences: config.blocks,\n dataWithLocales: result || {},\n docWithLocales: currentDoc || {},\n fields: collectionConfig.fields,\n selectedLocales: [locale],\n })\n }\n }\n\n const dataToUpdate: JsonObject = { ...result }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n result = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n result = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: result,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n publishSpecificLocale,\n req,\n snapshot: snapshotToSave,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: result,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n}\n"],"names":["ensureUsernameOrEmail","generatePasswordSaltHash","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","getLatestCollectionVersion","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","mergeLocalizedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","publishSpecificLocale","req","select","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","password","isSavingDraft","Boolean","_status","shouldSavePassword","auth","disableLocalStrategy","enableFields","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","draft","global","isRestoringDraftFromTrash","deletedAt","authOptions","operation","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","snapshotToSave","localization","versions","snapshotData","currentDoc","drafts","localizeStatus","accessibleLocaleCodes","localeCodes","filterAvailableLocales","filteredLocales","locales","map","code","localeCode","db","findOne","where","equals","published","query","configBlockReferences","blocks","dataWithLocales","fields","selectedLocales","dataToUpdate","hash","salt","updatedAt","Date","toISOString","updateOne","snapshot","unpublish","previousDoc"],"mappings":"AAwBA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,0BAA0B,EAAEC,WAAW,QAAQ,oBAAmB;AACjG,SAASC,qBAAqB,QAAQ,4CAA2C;AACjF,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,uBAAuB,QAAQ,gDAA+C;AACvF,SACEC,gBAAgB,EAChBC,yBAAyB,EACzBC,wBAAwB,QACnB,0CAAyC;AAChD,SAASC,kBAAkB,QAAQ,2CAA0C;AAyB7E;;;;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AOoC;QACX;IACF;IAEA,wCAAwC;IACxC,uBAAuB;IACvB,wCAAwC;IAExCA,SAAS,MAAMrE,YAAY;QACzBkD,YAAYjC;QACZkC,SAASlB,IAAIkB,OAAO;QACpBhC;QACAiC,KAAKiB;QACLf,QAAQ;QACRI,WAAW;QACX+C,aAAaxD;QACbhB;IACF;IAEA,wCAAwC;IACxC,2BAA2B;IAC3B,wCAAwC;IAExC,IAAIhB,iBAAiB4C,KAAK,EAAE7D,aAAa8D,QAAQ;QAC/C,KAAK,MAAMC,QAAQ9C,iBAAiB4C,KAAK,CAAC7D,WAAW,CAAE;YACrDqE,SACE,AAAC,MAAMN,KAAK;gBACVb,YAAYjC;gBACZkC,SAASlB,IAAIkB,OAAO;gBACpBhC;gBACAiC,KAAKiB;gBACLX,WAAW;gBACXhC;gBACA+E,aAAaxD;gBACbhB;YACF,MAAOoC;QACX;IACF;IAEA,OAAOA;AACT,EAAC"}
1
+ {"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, getLatestCollectionVersion, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideAccess: boolean\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n publishSpecificLocale?: string\n req: PayloadRequest\n select: SelectType\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n}\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n publishSpecificLocale,\n req,\n select,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const password = data?.password\n const publishAllLocales =\n !draftArg &&\n (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true))\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n if (isSavingDraft) {\n data._status = 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Delete any associated files\n // /////////////////////////////////////\n\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // Write files to local storage\n // /////////////////////////////////////\n\n if (!collectionConfig.upload.disableLocalStorage) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: originalDoc,\n docWithLocales,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n skipValidation:\n // only skip validation for drafts when draft validation is false\n (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||\n // Skip validation for trash operations since they're just metadata updates\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n // Skip validation for unpublish operations — they only change _status, not document data\n unpublishAllLocales,\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let result: JsonObject = await beforeChange(beforeChangeArgs)\n let snapshotToSave: JsonObject | undefined\n\n if (config.localization && collectionConfig.versions) {\n let snapshotData: JsonObject | undefined\n let currentDoc\n\n if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {\n if (publishAllLocales || unpublishAllLocales) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (!isSavingDraft) {\n // publishing a single locale\n currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: id } },\n })\n snapshotData = result\n }\n } else if (publishSpecificLocale) {\n // previous way of publishing a single locale\n currentDoc = await getLatestCollectionVersion({\n id,\n config: collectionConfig,\n payload,\n published: true,\n query: {\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n snapshotData = {\n ...result,\n _status: 'draft',\n }\n }\n\n if (snapshotData) {\n snapshotToSave = deepCopyObjectSimple(snapshotData || {})\n\n result = mergeLocalizedData({\n configBlockReferences: config.blocks,\n dataWithLocales: result || {},\n docWithLocales: currentDoc || {},\n fields: collectionConfig.fields,\n selectedLocales: [locale],\n })\n }\n }\n\n const dataToUpdate: JsonObject = { ...result }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n result = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n result = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: result,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n publishSpecificLocale,\n req,\n snapshot: snapshotToSave,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: result,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n}\n"],"names":["ensureUsernameOrEmail","generatePasswordSaltHash","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","getLatestCollectionVersion","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","mergeLocalizedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","publishSpecificLocale","req","select","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","password","isSavingDraft","Boolean","_status","shouldSavePassword","auth","disableLocalStrategy","enableFields","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","draft","global","isRestoringDraftFromTrash","deletedAt","authOptions","operation","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","snapshotToSave","localization","versions","snapshotData","currentDoc","drafts","localizeStatus","accessibleLocaleCodes","localeCodes","filterAvailableLocales","filteredLocales","locales","map","code","localeCode","db","findOne","where","equals","published","query","configBlockReferences","blocks","dataWithLocales","fields","selectedLocales","dataToUpdate","hash","salt","updatedAt","Date","toISOString","updateOne","snapshot","unpublish","previousDoc"],"mappings":"AAwBA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,0BAA0B,EAAEC,WAAW,QAAQ,oBAAmB;AACjG,SAASC,qBAAqB,QAAQ,4CAA2C;AACjF,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,uBAAuB,QAAQ,gDAA+C;AACvF,SACEC,gBAAgB,EAChBC,yBAAyB,EACzBC,wBAAwB,QACnB,0CAAyC;AAChD,SAASC,kBAAkB,QAAQ,2CAA0C;AAyB7E;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,iBAAiB,OAG5B,EACAC,EAAE,EACFC,QAAQ,EACRC,gBAAgB,EAChBC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,cAAc,EACdC,QAAQ,EACRC,cAAc,EACdC,aAAa,EACbC,MAAM,EACNC,cAAc,EACdC,YAAY,EACZC,OAAO,EACPC,QAAQ,EACRC,mBAAmBC,oBAAoB,EACvCC,qBAAqB,EACrBC,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IAAIhB,iBAAiB4C,KAAK,EAAE7D,aAAa8D,QAAQ;QAC/C,KAAK,MAAMC,QAAQ9C,iBAAiB4C,KAAK,CAAC7D,WAAW,CAAE;YACrDqE,SACE,AAAC,MAAMN,KAAK;gBACVb,YAAYjC;gBACZkC,SAASlB,IAAIkB,OAAO;gBACpBhC;gBACAiC,KAAKiB;gBACLX,WAAW;gBACXhC;gBACA+E,aAAaxD;gBACbhB;YACF,MAAOoC;QACX;IACF;IAEA,OAAOA;AACT,EAAC"}
@@ -1,15 +1,7 @@
1
1
  import type { CollectionConfig } from '../../collections/config/types.js';
2
+ import type { Config } from '../../config/types.js';
2
3
  import type { SanitizedConfig } from '../types.js';
3
- /**
4
- * This function creates:
5
- * - N fields per collection, named `_order` or `_<collection>_<joinField>_order`
6
- * - 1 hook per collection
7
- * - 1 endpoint per app
8
- *
9
- * Also, if collection.defaultSort or joinField.defaultSort is not set, it will be set to the orderable field.
10
- */
11
- export declare const setupOrderable: (config: SanitizedConfig) => void;
12
- export declare const addOrderableFieldsAndHook: (collection: CollectionConfig, orderableFieldNames: string[], joinFieldPathsByCollection?: Map<string, Map<string, string>>) => void;
4
+ export declare const addOrderableFieldsAndHook: (collection: CollectionConfig, config: Config, orderableFieldNames: string[], joinFieldPathsByCollection?: Map<string, Map<string, string>>) => Promise<void>;
13
5
  /**
14
6
  * The body of the reorder endpoint.
15
7
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/orderable/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAA;AAE3F,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;AAc5E;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,WAAY,eAAe,SA2DrD,CAAA;AAED,eAAO,MAAM,yBAAyB,eACxB,gBAAgB,uBACP,MAAM,EAAE,+BACA,GAAG,CAAC,MAAM,EAAE,GAAG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AAC,MAAM,EAAE,MAAM,CAAC,CAAC,SA4L7D,CAAA"}
@@ -1,80 +1,18 @@
1
1
  import { status as httpStatus } from 'http-status';
2
2
  import { executeAccess } from '../../auth/executeAccess.js';
3
3
  import { APIError } from '../../errors/index.js';
4
+ import { sanitizeField } from '../../fields/config/sanitize.js';
4
5
  import { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js';
5
6
  import { commitTransaction } from '../../utilities/commitTransaction.js';
6
7
  import { initTransaction } from '../../utilities/initTransaction.js';
7
8
  import { killTransaction } from '../../utilities/killTransaction.js';
8
- import { traverseFields } from '../../utilities/traverseFields.js';
9
9
  import { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js';
10
10
  import { getJoinScopeContext } from './utils/getJoinScopeContext.js';
11
11
  import { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js';
12
12
  import { resolvePendingTargetKey } from './utils/resolvePendingTargetKey.js';
13
- /**
14
- * This function creates:
15
- * - N fields per collection, named `_order` or `_<collection>_<joinField>_order`
16
- * - 1 hook per collection
17
- * - 1 endpoint per app
18
- *
19
- * Also, if collection.defaultSort or joinField.defaultSort is not set, it will be set to the orderable field.
20
- */ export const setupOrderable = (config)=>{
21
- const fieldsToAdd = new Map();
22
- const joinFieldPathsByCollection = new Map();
23
- config.collections.forEach((collection)=>{
24
- if (collection.orderable) {
25
- const currentFields = fieldsToAdd.get(collection) || [];
26
- fieldsToAdd.set(collection, [
27
- ...currentFields,
28
- '_order'
29
- ]);
30
- collection.defaultSort = collection.defaultSort ?? '_order';
31
- }
32
- traverseFields({
33
- callback: ({ field, parentRef, ref })=>{
34
- if (field.type === 'array' || field.type === 'blocks') {
35
- return false;
36
- }
37
- if (field.type === 'group' || field.type === 'tab') {
38
- // @ts-expect-error ref is untyped
39
- const parentPrefix = parentRef?.prefix ? `${parentRef.prefix}_` : '';
40
- // @ts-expect-error ref is untyped
41
- ref.prefix = `${parentPrefix}${field.name}`;
42
- }
43
- if (field.type === 'join' && field.orderable === true) {
44
- if (Array.isArray(field.collection)) {
45
- throw new APIError('Orderable joins must target a single collection', httpStatus.BAD_REQUEST, {}, true);
46
- }
47
- const relationshipCollection = config.collections.find((c)=>c.slug === field.collection);
48
- if (!relationshipCollection) {
49
- return false;
50
- }
51
- field.defaultSort = field.defaultSort ?? `_${field.collection}_${field.name}_order`;
52
- const currentFields = fieldsToAdd.get(relationshipCollection) || [];
53
- // @ts-expect-error ref is untyped
54
- const prefix = parentRef?.prefix ? `${parentRef.prefix}_` : '';
55
- const joinOrderableFieldName = `_${field.collection}_${prefix}${field.name}_order`;
56
- fieldsToAdd.set(relationshipCollection, [
57
- ...currentFields,
58
- joinOrderableFieldName
59
- ]);
60
- const currentJoinFieldPaths = joinFieldPathsByCollection.get(relationshipCollection.slug) || new Map();
61
- currentJoinFieldPaths.set(joinOrderableFieldName, field.on);
62
- joinFieldPathsByCollection.set(relationshipCollection.slug, currentJoinFieldPaths);
63
- }
64
- },
65
- fields: collection.fields
66
- });
67
- });
68
- Array.from(fieldsToAdd.entries()).forEach(([collection, orderableFields])=>{
69
- addOrderableFieldsAndHook(collection, orderableFields, joinFieldPathsByCollection);
70
- });
71
- if (fieldsToAdd.size > 0) {
72
- addOrderableEndpoint(config, joinFieldPathsByCollection);
73
- }
74
- };
75
- export const addOrderableFieldsAndHook = (collection, orderableFieldNames, joinFieldPathsByCollection)=>{
76
- // 1. Add field
77
- orderableFieldNames.forEach((orderableFieldName)=>{
13
+ export const addOrderableFieldsAndHook = async (collection, config, orderableFieldNames, joinFieldPathsByCollection)=>{
14
+ // 1. Add fields
15
+ for (const orderableFieldName of orderableFieldNames){
78
16
  const orderField = {
79
17
  name: orderableFieldName,
80
18
  type: 'text',
@@ -96,8 +34,23 @@ export const addOrderableFieldsAndHook = (collection, orderableFieldNames, joinF
96
34
  },
97
35
  index: true
98
36
  };
37
+ // Sanitize the field using the standard sanitization logic
38
+ await sanitizeField({
39
+ collectionConfig: collection,
40
+ config,
41
+ existingFieldNames: new Set(),
42
+ field: orderField,
43
+ index: 0,
44
+ isTopLevelField: true,
45
+ joinPath: '',
46
+ parentIndexPath: '',
47
+ parentIsLocalized: false,
48
+ parentSchemaPath: '',
49
+ requireFieldLevelRichTextEditor: false,
50
+ validRelationships: null
51
+ });
99
52
  collection.fields.unshift(orderField);
100
- });
53
+ }
101
54
  // 2. Add hook
102
55
  if (!collection.hooks) {
103
56
  collection.hooks = {};