payload 4.0.0-internal.5f0cd13 → 4.0.0-internal.688c4d0
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.
- package/dist/admin/RichText.d.ts +22 -2
- package/dist/admin/RichText.d.ts.map +1 -1
- package/dist/admin/RichText.js.map +1 -1
- package/dist/admin/adapters/devReload.d.ts +9 -0
- package/dist/admin/adapters/devReload.d.ts.map +1 -0
- package/dist/admin/adapters/devReload.js +6 -0
- package/dist/admin/adapters/devReload.js.map +1 -0
- package/dist/admin/adapters/index.d.ts +3 -0
- package/dist/admin/adapters/index.d.ts.map +1 -1
- package/dist/admin/adapters/index.js.map +1 -1
- package/dist/admin/adapters/render.d.ts +16 -0
- package/dist/admin/adapters/render.d.ts.map +1 -0
- package/dist/admin/adapters/render.js +7 -0
- package/dist/admin/adapters/render.js.map +1 -0
- package/dist/admin/adapters/views.d.ts +36 -0
- package/dist/admin/adapters/views.d.ts.map +1 -0
- package/dist/admin/adapters/views.js +7 -0
- package/dist/admin/adapters/views.js.map +1 -0
- package/dist/admin/fields/Row.d.ts +2 -2
- package/dist/admin/fields/Row.d.ts.map +1 -1
- package/dist/admin/fields/Row.js.map +1 -1
- package/dist/admin/forms/Description.d.ts +2 -2
- package/dist/admin/forms/Description.d.ts.map +1 -1
- package/dist/admin/forms/Description.js.map +1 -1
- package/dist/admin/forms/Field.d.ts +8 -3
- package/dist/admin/forms/Field.d.ts.map +1 -1
- package/dist/admin/forms/Field.js.map +1 -1
- package/dist/admin/forms/Form.d.ts +29 -0
- package/dist/admin/forms/Form.d.ts.map +1 -1
- package/dist/admin/forms/Form.js.map +1 -1
- package/dist/admin/functions/index.d.ts +9 -0
- package/dist/admin/functions/index.d.ts.map +1 -1
- package/dist/admin/functions/index.js.map +1 -1
- package/dist/admin/types.d.ts +2 -2
- package/dist/admin/types.d.ts.map +1 -1
- package/dist/admin/types.js.map +1 -1
- package/dist/admin/views/dashboard.d.ts +7 -0
- package/dist/admin/views/dashboard.d.ts.map +1 -1
- package/dist/admin/views/dashboard.js.map +1 -1
- package/dist/admin/views/document.d.ts +5 -3
- package/dist/admin/views/document.d.ts.map +1 -1
- package/dist/admin/views/document.js.map +1 -1
- package/dist/admin/views/list.d.ts +5 -0
- package/dist/admin/views/list.d.ts.map +1 -1
- package/dist/admin/views/list.js.map +1 -1
- package/dist/auth/baseFields/apiKey.d.ts +10 -2
- package/dist/auth/baseFields/apiKey.d.ts.map +1 -1
- package/dist/auth/baseFields/apiKey.js +35 -24
- package/dist/auth/baseFields/apiKey.js.map +1 -1
- package/dist/auth/defaultAccess.d.ts +1 -1
- package/dist/auth/defaultAccess.d.ts.map +1 -1
- package/dist/auth/defaultAccess.js +1 -1
- package/dist/auth/defaultAccess.js.map +1 -1
- package/dist/auth/defaultUser.d.ts.map +1 -1
- package/dist/auth/defaultUser.js +2 -1
- package/dist/auth/defaultUser.js.map +1 -1
- package/dist/auth/getAuthFields.js +2 -2
- package/dist/auth/getAuthFields.js.map +1 -1
- package/dist/bin/build.d.ts +25 -0
- package/dist/bin/build.d.ts.map +1 -0
- package/dist/bin/build.js +80 -0
- package/dist/bin/build.js.map +1 -0
- package/dist/bin/build.spec.js +170 -0
- package/dist/bin/build.spec.js.map +1 -0
- package/dist/bin/generateImportMap/index.d.ts.map +1 -1
- package/dist/bin/generateImportMap/index.js +8 -5
- package/dist/bin/generateImportMap/index.js.map +1 -1
- package/dist/bin/generateImportMap/iterateCollections.d.ts.map +1 -1
- package/dist/bin/generateImportMap/iterateCollections.js +1 -0
- package/dist/bin/generateImportMap/iterateCollections.js.map +1 -1
- package/dist/bin/generateImportMap/iterateConfig.d.ts.map +1 -1
- package/dist/bin/generateImportMap/iterateConfig.js +1 -0
- package/dist/bin/generateImportMap/iterateConfig.js.map +1 -1
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.d.ts +5 -1
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.d.ts.map +1 -1
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.js +24 -18
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.js.map +1 -1
- package/dist/bin/generateTypes.d.ts +3 -2
- package/dist/bin/generateTypes.d.ts.map +1 -1
- package/dist/bin/generateTypes.js +4 -0
- package/dist/bin/generateTypes.js.map +1 -1
- package/dist/bin/index.d.ts.map +1 -1
- package/dist/bin/index.js +9 -0
- package/dist/bin/index.js.map +1 -1
- package/dist/bin/loadEnv.d.ts +3 -1
- package/dist/bin/loadEnv.d.ts.map +1 -1
- package/dist/bin/loadEnv.js +40 -10
- package/dist/bin/loadEnv.js.map +1 -1
- package/dist/collections/config/defaults.js +2 -2
- package/dist/collections/config/defaults.js.map +1 -1
- package/dist/collections/config/defaults.spec.js +47 -0
- package/dist/collections/config/defaults.spec.js.map +1 -0
- package/dist/collections/config/sanitize.d.ts.map +1 -1
- package/dist/collections/config/sanitize.js +1 -11
- package/dist/collections/config/sanitize.js.map +1 -1
- package/dist/collections/config/types.d.ts +5 -7
- package/dist/collections/config/types.d.ts.map +1 -1
- package/dist/collections/config/types.js.map +1 -1
- package/dist/collections/endpoints/create.d.ts.map +1 -1
- package/dist/collections/endpoints/create.js +0 -2
- package/dist/collections/endpoints/create.js.map +1 -1
- package/dist/collections/endpoints/updateByID.d.ts.map +1 -1
- package/dist/collections/endpoints/updateByID.js +1 -2
- package/dist/collections/endpoints/updateByID.js.map +1 -1
- package/dist/collections/operations/count.d.ts.map +1 -1
- package/dist/collections/operations/count.js +1 -0
- package/dist/collections/operations/count.js.map +1 -1
- package/dist/collections/operations/create.d.ts +0 -1
- package/dist/collections/operations/create.d.ts.map +1 -1
- package/dist/collections/operations/create.js +15 -6
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/delete.d.ts.map +1 -1
- package/dist/collections/operations/delete.js +3 -0
- package/dist/collections/operations/delete.js.map +1 -1
- package/dist/collections/operations/local/duplicate.d.ts.map +1 -1
- package/dist/collections/operations/local/duplicate.js.map +1 -1
- package/dist/collections/operations/local/find.d.ts.map +1 -1
- package/dist/collections/operations/local/find.js.map +1 -1
- package/dist/collections/operations/local/findByID.d.ts.map +1 -1
- package/dist/collections/operations/local/findByID.js.map +1 -1
- package/dist/collections/operations/local/findVersionByID.d.ts.map +1 -1
- package/dist/collections/operations/local/findVersionByID.js.map +1 -1
- package/dist/collections/operations/local/findVersions.d.ts.map +1 -1
- package/dist/collections/operations/local/findVersions.js.map +1 -1
- package/dist/collections/operations/local/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/local/restoreVersion.js.map +1 -1
- package/dist/collections/operations/local/update.d.ts +4 -8
- package/dist/collections/operations/local/update.d.ts.map +1 -1
- package/dist/collections/operations/local/update.js +1 -2
- package/dist/collections/operations/local/update.js.map +1 -1
- package/dist/collections/operations/update.d.ts +0 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +1 -2
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.d.ts +0 -1
- package/dist/collections/operations/updateByID.d.ts.map +1 -1
- package/dist/collections/operations/updateByID.js +1 -5
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/collections/operations/utilities/update.d.ts +1 -2
- package/dist/collections/operations/utilities/update.d.ts.map +1 -1
- package/dist/collections/operations/utilities/update.js +64 -65
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/config/client.js.map +1 -1
- package/dist/config/orderable/index.d.ts.map +1 -1
- package/dist/config/orderable/index.js +23 -0
- package/dist/config/orderable/index.js.map +1 -1
- package/dist/config/types.d.ts +18 -18
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js +1 -0
- package/dist/config/types.js.map +1 -1
- package/dist/database/getLocalizedPaths.d.ts.map +1 -1
- package/dist/database/getLocalizedPaths.js +1 -1
- package/dist/database/getLocalizedPaths.js.map +1 -1
- package/dist/database/migrations/migrationsCollection.d.ts.map +1 -1
- package/dist/database/migrations/migrationsCollection.js +2 -1
- package/dist/database/migrations/migrationsCollection.js.map +1 -1
- package/dist/exports/migrations.d.ts +5 -13
- package/dist/exports/migrations.d.ts.map +1 -1
- package/dist/exports/migrations.js +5 -13
- package/dist/exports/migrations.js.map +1 -1
- package/dist/exports/shared.d.ts +20 -0
- package/dist/exports/shared.d.ts.map +1 -1
- package/dist/exports/shared.js +20 -0
- package/dist/exports/shared.js.map +1 -1
- package/dist/fields/config/client.d.ts +2 -2
- package/dist/fields/config/client.d.ts.map +1 -1
- package/dist/fields/config/client.js +11 -12
- package/dist/fields/config/client.js.map +1 -1
- package/dist/fields/config/sanitize.d.ts.map +1 -1
- package/dist/fields/config/sanitize.js +1 -4
- package/dist/fields/config/sanitize.js.map +1 -1
- package/dist/fields/config/types.d.ts +5 -20
- package/dist/fields/config/types.d.ts.map +1 -1
- package/dist/fields/config/types.js.map +1 -1
- package/dist/fields/hooks/afterChange/promise.js +1 -1
- package/dist/fields/hooks/afterChange/promise.js.map +1 -1
- package/dist/fields/hooks/afterRead/promise.js +2 -2
- package/dist/fields/hooks/afterRead/promise.js.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.js +3 -3
- package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
- package/dist/fields/hooks/beforeDuplicate/promise.js +2 -2
- package/dist/fields/hooks/beforeDuplicate/promise.js.map +1 -1
- package/dist/fields/hooks/beforeValidate/promise.js +1 -1
- package/dist/fields/hooks/beforeValidate/promise.js.map +1 -1
- package/dist/fields/validations.d.ts.map +1 -1
- package/dist/fields/validations.js +5 -4
- package/dist/fields/validations.js.map +1 -1
- package/dist/globals/config/sanitize.d.ts.map +1 -1
- package/dist/globals/config/sanitize.js +2 -6
- package/dist/globals/config/sanitize.js.map +1 -1
- package/dist/globals/config/sanitize.spec.js +43 -0
- package/dist/globals/config/sanitize.spec.js.map +1 -0
- package/dist/globals/endpoints/update.d.ts.map +1 -1
- package/dist/globals/endpoints/update.js +0 -2
- package/dist/globals/endpoints/update.js.map +1 -1
- package/dist/globals/operations/local/findOne.d.ts.map +1 -1
- package/dist/globals/operations/local/findOne.js.map +1 -1
- package/dist/globals/operations/local/update.d.ts +4 -6
- package/dist/globals/operations/local/update.d.ts.map +1 -1
- package/dist/globals/operations/local/update.js +1 -2
- package/dist/globals/operations/local/update.js.map +1 -1
- package/dist/globals/operations/update.d.ts +0 -1
- package/dist/globals/operations/update.d.ts.map +1 -1
- package/dist/globals/operations/update.js +52 -58
- package/dist/globals/operations/update.js.map +1 -1
- package/dist/index.bundled.d.ts +300 -147
- package/dist/index.d.ts +13 -12
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +53 -35
- package/dist/index.js.map +1 -1
- package/dist/kv/adapters/DatabaseKVAdapter.d.ts.map +1 -1
- package/dist/kv/adapters/DatabaseKVAdapter.js +1 -0
- package/dist/kv/adapters/DatabaseKVAdapter.js.map +1 -1
- package/dist/locked-documents/config.d.ts.map +1 -1
- package/dist/locked-documents/config.js +2 -1
- package/dist/locked-documents/config.js.map +1 -1
- package/dist/preferences/config.d.ts.map +1 -1
- package/dist/preferences/config.js +2 -1
- package/dist/preferences/config.js.map +1 -1
- package/dist/query-presets/config.d.ts.map +1 -1
- package/dist/query-presets/config.js +2 -1
- package/dist/query-presets/config.js.map +1 -1
- package/dist/queues/config/collection.d.ts.map +1 -1
- package/dist/queues/config/collection.js +2 -1
- package/dist/queues/config/collection.js.map +1 -1
- package/dist/queues/config/generateJobsJSONSchemas.js +2 -2
- package/dist/queues/config/generateJobsJSONSchemas.js.map +1 -1
- package/dist/queues/config/global.d.ts.map +1 -1
- package/dist/queues/config/global.js +2 -1
- package/dist/queues/config/global.js.map +1 -1
- package/dist/uploads/fetchAPI-multipart/processMultipart.d.ts.map +1 -1
- package/dist/uploads/fetchAPI-multipart/processMultipart.js +14 -1
- package/dist/uploads/fetchAPI-multipart/processMultipart.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts +2 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js +5 -2
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/safeFetch.d.ts.map +1 -1
- package/dist/uploads/safeFetch.js +11 -5
- package/dist/uploads/safeFetch.js.map +1 -1
- package/dist/utilities/appendDateTimezoneSelectFields.js +2 -2
- package/dist/utilities/appendDateTimezoneSelectFields.js.map +1 -1
- package/dist/utilities/configToJSONSchema.d.ts +25 -0
- package/dist/utilities/configToJSONSchema.d.ts.map +1 -1
- package/dist/utilities/configToJSONSchema.js +76 -34
- package/dist/utilities/configToJSONSchema.js.map +1 -1
- package/dist/utilities/configToJSONSchema.spec.js +215 -29
- package/dist/utilities/configToJSONSchema.spec.js.map +1 -1
- package/dist/utilities/deepCopyObject.d.ts.map +1 -1
- package/dist/utilities/deepCopyObject.js +8 -0
- package/dist/utilities/deepCopyObject.js.map +1 -1
- package/dist/utilities/dependencies/dependencyChecker.js +1 -1
- package/dist/utilities/dependencies/dependencyChecker.js.map +1 -1
- package/dist/utilities/dependencies/getDependencies.d.ts.map +1 -1
- package/dist/utilities/dependencies/getDependencies.js +5 -5
- package/dist/utilities/dependencies/getDependencies.js.map +1 -1
- package/dist/utilities/dynamicImport.js +1 -1
- package/dist/utilities/dynamicImport.js.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.d.ts.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.js +5 -12
- package/dist/utilities/filterDataToSelectedLocales.js.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.spec.js +1 -2
- package/dist/utilities/filterDataToSelectedLocales.spec.js.map +1 -1
- package/dist/utilities/flattenAllFields.d.ts.map +1 -1
- package/dist/utilities/flattenAllFields.js +7 -22
- package/dist/utilities/flattenAllFields.js.map +1 -1
- package/dist/utilities/formatErrors.d.ts.map +1 -1
- package/dist/utilities/formatErrors.js +3 -1
- package/dist/utilities/formatErrors.js.map +1 -1
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts.map +1 -1
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.js +5 -5
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.js.map +1 -1
- package/dist/utilities/getFieldByPath.d.ts.map +1 -1
- package/dist/utilities/getFieldByPath.js +1 -1
- package/dist/utilities/getFieldByPath.js.map +1 -1
- package/dist/utilities/getRequestLanguage.d.ts +2 -2
- package/dist/utilities/getRequestLanguage.d.ts.map +1 -1
- package/dist/utilities/getRequestLanguage.js.map +1 -1
- package/dist/utilities/getVersionsConfig.js.map +1 -1
- package/dist/utilities/handleEndpoints.d.ts.map +1 -1
- package/dist/utilities/handleEndpoints.js +7 -3
- package/dist/utilities/handleEndpoints.js.map +1 -1
- package/dist/utilities/isRSCEnabled.d.ts +12 -0
- package/dist/utilities/isRSCEnabled.d.ts.map +1 -0
- package/dist/utilities/isRSCEnabled.js +14 -0
- package/dist/utilities/isRSCEnabled.js.map +1 -0
- package/dist/utilities/mergeLocalizedData.d.ts +14 -4
- package/dist/utilities/mergeLocalizedData.d.ts.map +1 -1
- package/dist/utilities/mergeLocalizedData.js +54 -46
- package/dist/utilities/mergeLocalizedData.js.map +1 -1
- package/dist/utilities/mergeLocalizedData.spec.js +23 -23
- package/dist/utilities/mergeLocalizedData.spec.js.map +1 -1
- package/dist/utilities/parseParams/index.d.ts +2 -5
- package/dist/utilities/parseParams/index.d.ts.map +1 -1
- package/dist/utilities/parseParams/index.js.map +1 -1
- package/dist/utilities/parseParams/index.spec.js +0 -9
- package/dist/utilities/parseParams/index.spec.js.map +1 -1
- package/dist/utilities/telemetry/conf/envPaths.d.ts.map +1 -1
- package/dist/utilities/telemetry/conf/envPaths.js +31 -40
- package/dist/utilities/telemetry/conf/envPaths.js.map +1 -1
- package/dist/utilities/transformColumnPreferences.js +4 -2
- package/dist/utilities/transformColumnPreferences.js.map +1 -1
- package/dist/utilities/traverseFields.d.ts.map +1 -1
- package/dist/utilities/traverseFields.js +2 -4
- package/dist/utilities/traverseFields.js.map +1 -1
- package/dist/utilities/traverseForLocalizedFields.d.ts.map +1 -1
- package/dist/utilities/traverseForLocalizedFields.js +3 -0
- package/dist/utilities/traverseForLocalizedFields.js.map +1 -1
- package/dist/versions/baseFields.d.ts +1 -2
- package/dist/versions/baseFields.d.ts.map +1 -1
- package/dist/versions/baseFields.js +0 -13
- package/dist/versions/baseFields.js.map +1 -1
- package/dist/versions/buildCollectionFields.d.ts.map +1 -1
- package/dist/versions/buildCollectionFields.js +0 -2
- package/dist/versions/buildCollectionFields.js.map +1 -1
- package/dist/versions/buildGlobalFields.d.ts.map +1 -1
- package/dist/versions/buildGlobalFields.js +0 -2
- package/dist/versions/buildGlobalFields.js.map +1 -1
- package/dist/versions/buildSingleLocalePublishData.d.ts +32 -0
- package/dist/versions/buildSingleLocalePublishData.d.ts.map +1 -0
- package/dist/versions/buildSingleLocalePublishData.js +37 -0
- package/dist/versions/buildSingleLocalePublishData.js.map +1 -0
- package/dist/versions/saveVersion.d.ts +0 -2
- package/dist/versions/saveVersion.d.ts.map +1 -1
- package/dist/versions/saveVersion.js +12 -17
- package/dist/versions/saveVersion.js.map +1 -1
- package/dist/versions/schedule/job.d.ts.map +1 -1
- package/dist/versions/schedule/job.js +2 -9
- package/dist/versions/schedule/job.js.map +1 -1
- package/dist/versions/types.d.ts +2 -15
- package/dist/versions/types.d.ts.map +1 -1
- package/dist/versions/types.js.map +1 -1
- package/package.json +8 -5
- package/dist/database/migrations/templates/localizeStatus.d.ts +0 -10
- package/dist/database/migrations/templates/localizeStatus.d.ts.map +0 -1
- package/dist/database/migrations/templates/localizeStatus.js +0 -54
- package/dist/database/migrations/templates/localizeStatus.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/index.d.ts +0 -12
- package/dist/versions/migrations/localizeStatus/index.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/index.js +0 -33
- package/dist/versions/migrations/localizeStatus/index.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/down.d.ts +0 -9
- package/dist/versions/migrations/localizeStatus/mongo/down.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/down.js +0 -112
- package/dist/versions/migrations/localizeStatus/mongo/down.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/index.d.ts +0 -8
- package/dist/versions/migrations/localizeStatus/mongo/index.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/index.js +0 -8
- package/dist/versions/migrations/localizeStatus/mongo/index.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/up.d.ts +0 -9
- package/dist/versions/migrations/localizeStatus/mongo/up.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/up.js +0 -220
- package/dist/versions/migrations/localizeStatus/mongo/up.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/down.d.ts +0 -11
- package/dist/versions/migrations/localizeStatus/sql/down.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/down.js +0 -213
- package/dist/versions/migrations/localizeStatus/sql/down.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/index.d.ts +0 -8
- package/dist/versions/migrations/localizeStatus/sql/index.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/index.js +0 -8
- package/dist/versions/migrations/localizeStatus/sql/index.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.d.ts +0 -13
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.js +0 -51
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.d.ts +0 -13
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.js +0 -54
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/up.d.ts +0 -11
- package/dist/versions/migrations/localizeStatus/sql/up.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/up.js +0 -277
- package/dist/versions/migrations/localizeStatus/sql/up.js.map +0 -1
- package/dist/versions/saveSnapshot.d.ts +0 -18
- package/dist/versions/saveSnapshot.d.ts.map +0 -1
- package/dist/versions/saveSnapshot.js +0 -38
- package/dist/versions/saveSnapshot.js.map +0 -1
|
@@ -4,12 +4,12 @@ import { afterChange } from '../../../fields/hooks/afterChange/index.js';
|
|
|
4
4
|
import { afterRead } from '../../../fields/hooks/afterRead/index.js';
|
|
5
5
|
import { beforeChange } from '../../../fields/hooks/beforeChange/index.js';
|
|
6
6
|
import { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js';
|
|
7
|
-
import { deepCopyObjectSimple,
|
|
7
|
+
import { deepCopyObjectSimple, saveVersion } from '../../../index.js';
|
|
8
8
|
import { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js';
|
|
9
9
|
import { uploadFiles } from '../../../uploads/uploadFiles.js';
|
|
10
10
|
import { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js';
|
|
11
11
|
import { hasDraftsEnabled, hasDraftValidationEnabled, hasLocalizeStatusEnabled } from '../../../utilities/getVersionsConfig.js';
|
|
12
|
-
import {
|
|
12
|
+
import { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js';
|
|
13
13
|
/**
|
|
14
14
|
* This function is used to update a document in the DB and return the result.
|
|
15
15
|
*
|
|
@@ -22,9 +22,9 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
22
22
|
* - afterRead - Collection
|
|
23
23
|
* - afterChange - Fields
|
|
24
24
|
* - afterChange - Collection
|
|
25
|
-
*/ export const updateDocument = async ({ id, autosave, collectionConfig, config, data, depth, docWithLocales, draftArg, fallbackLocale, filesToUpload, locale, overrideAccess, overrideLock, payload, populate, publishAllLocales: publishAllLocalesArg,
|
|
25
|
+
*/ export const updateDocument = async ({ id, autosave, collectionConfig, config, data, depth, docWithLocales, draftArg, fallbackLocale, filesToUpload, locale, overrideAccess, overrideLock, payload, populate, publishAllLocales: publishAllLocalesArg, req, select, showHiddenFields, unpublishAllLocales: unpublishAllLocalesArg })=>{
|
|
26
26
|
const password = data?.password;
|
|
27
|
-
const publishAllLocales = !draftArg && (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true));
|
|
27
|
+
const publishAllLocales = !draftArg && (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) && locale !== 'all' ? false : true));
|
|
28
28
|
const unpublishAllLocales = typeof unpublishAllLocalesArg === 'string' ? unpublishAllLocalesArg === 'true' : !!unpublishAllLocalesArg;
|
|
29
29
|
const isSavingDraft = Boolean(draftArg && hasDraftsEnabled(collectionConfig)) && data._status !== 'published' && !publishAllLocales;
|
|
30
30
|
const shouldSavePassword = Boolean(password && collectionConfig.auth && (!collectionConfig.auth.disableLocalStrategy || typeof collectionConfig.auth.disableLocalStrategy === 'object' && collectionConfig.auth.disableLocalStrategy.enableFields) && !isSavingDraft);
|
|
@@ -68,14 +68,22 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
68
68
|
// /////////////////////////////////////
|
|
69
69
|
// Delete any associated files
|
|
70
70
|
// /////////////////////////////////////
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
71
|
+
// When saving a draft on a document whose latest version is published, the file
|
|
72
|
+
// referenced by docWithLocales is still actively used by the published main document.
|
|
73
|
+
// Deleting it here would break the published document's file even though no publish
|
|
74
|
+
// is happening. Only skip deletion in this case; when the latest version is already a
|
|
75
|
+
// draft, it is safe to delete the old draft file as it is being replaced.
|
|
76
|
+
const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published';
|
|
77
|
+
if (!isDraftOverPublished) {
|
|
78
|
+
await deleteAssociatedFiles({
|
|
79
|
+
collectionConfig,
|
|
80
|
+
config,
|
|
81
|
+
doc: docWithLocales,
|
|
82
|
+
files: filesToUpload,
|
|
83
|
+
overrideDelete: false,
|
|
84
|
+
req
|
|
85
|
+
});
|
|
86
|
+
}
|
|
79
87
|
// /////////////////////////////////////
|
|
80
88
|
// beforeValidate - Fields
|
|
81
89
|
// /////////////////////////////////////
|
|
@@ -152,11 +160,17 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
152
160
|
// Handle Localized Data Merging
|
|
153
161
|
// /////////////////////////////////////
|
|
154
162
|
let result = await beforeChange(beforeChangeArgs);
|
|
155
|
-
|
|
163
|
+
if (config.localization && hasLocalizeStatusEnabled(collectionConfig) && typeof result._status === 'string') {
|
|
164
|
+
const statusStr = result._status;
|
|
165
|
+
result._status = {};
|
|
166
|
+
for (const localeCode of config.localization.localeCodes){
|
|
167
|
+
;
|
|
168
|
+
result._status[localeCode] = statusStr;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
let localizedPublishData = null;
|
|
156
172
|
if (config.localization && collectionConfig.versions) {
|
|
157
|
-
|
|
158
|
-
let currentDoc;
|
|
159
|
-
if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {
|
|
173
|
+
if (hasLocalizeStatusEnabled(collectionConfig)) {
|
|
160
174
|
if (publishAllLocales || unpublishAllLocales) {
|
|
161
175
|
let accessibleLocaleCodes = config.localization.localeCodes;
|
|
162
176
|
if (config.localization.filterAvailableLocales) {
|
|
@@ -172,10 +186,10 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
172
186
|
for (const localeCode of accessibleLocaleCodes){
|
|
173
187
|
result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published';
|
|
174
188
|
}
|
|
175
|
-
} else if (!isSavingDraft) {
|
|
176
|
-
|
|
177
|
-
currentDoc = await payload.db.findOne({
|
|
189
|
+
} else if (!isSavingDraft && result._status && typeof result._status === 'object' && !Array.isArray(result._status) && result._status[locale] === 'published') {
|
|
190
|
+
const currentDoc = await payload.db.findOne({
|
|
178
191
|
collection: collectionConfig.slug,
|
|
192
|
+
locale: 'all',
|
|
179
193
|
req,
|
|
180
194
|
where: {
|
|
181
195
|
id: {
|
|
@@ -183,47 +197,18 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
183
197
|
}
|
|
184
198
|
}
|
|
185
199
|
});
|
|
186
|
-
|
|
200
|
+
localizedPublishData = buildLocalizedPublishData({
|
|
201
|
+
config,
|
|
202
|
+
currentDoc: currentDoc,
|
|
203
|
+
fields: collectionConfig.fields,
|
|
204
|
+
locale,
|
|
205
|
+
result
|
|
206
|
+
});
|
|
187
207
|
}
|
|
188
|
-
} else if (publishSpecificLocale) {
|
|
189
|
-
// previous way of publishing a single locale
|
|
190
|
-
currentDoc = await getLatestCollectionVersion({
|
|
191
|
-
id,
|
|
192
|
-
config: collectionConfig,
|
|
193
|
-
payload,
|
|
194
|
-
published: true,
|
|
195
|
-
query: {
|
|
196
|
-
collection: collectionConfig.slug,
|
|
197
|
-
locale: 'all',
|
|
198
|
-
req,
|
|
199
|
-
where: {
|
|
200
|
-
id: {
|
|
201
|
-
equals: id
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
},
|
|
205
|
-
req
|
|
206
|
-
});
|
|
207
|
-
snapshotData = {
|
|
208
|
-
...result,
|
|
209
|
-
_status: 'draft'
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
if (snapshotData) {
|
|
213
|
-
snapshotToSave = deepCopyObjectSimple(snapshotData || {});
|
|
214
|
-
result = mergeLocalizedData({
|
|
215
|
-
configBlockReferences: config.blocks,
|
|
216
|
-
dataWithLocales: result || {},
|
|
217
|
-
docWithLocales: currentDoc || {},
|
|
218
|
-
fields: collectionConfig.fields,
|
|
219
|
-
selectedLocales: [
|
|
220
|
-
locale
|
|
221
|
-
]
|
|
222
|
-
});
|
|
223
208
|
}
|
|
224
209
|
}
|
|
225
210
|
const dataToUpdate = {
|
|
226
|
-
...result
|
|
211
|
+
...localizedPublishData ?? result
|
|
227
212
|
};
|
|
228
213
|
// /////////////////////////////////////
|
|
229
214
|
// Handle potential password update
|
|
@@ -246,13 +231,29 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
246
231
|
if (!isSavingDraft) {
|
|
247
232
|
// Ensure updatedAt date is always updated
|
|
248
233
|
dataToUpdate.updatedAt = new Date().toISOString();
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
234
|
+
if (localizedPublishData) {
|
|
235
|
+
// Single-locale publish: save filtered data to main doc but keep full locale data for
|
|
236
|
+
// the version so draft fetches (replaceWithDraftIfAvailable) return complete data.
|
|
237
|
+
await req.payload.db.updateOne({
|
|
238
|
+
id,
|
|
239
|
+
collection: collectionConfig.slug,
|
|
240
|
+
data: dataToUpdate,
|
|
241
|
+
locale,
|
|
242
|
+
req
|
|
243
|
+
});
|
|
244
|
+
resultWithLocales = {
|
|
245
|
+
...result,
|
|
246
|
+
updatedAt: dataToUpdate.updatedAt
|
|
247
|
+
};
|
|
248
|
+
} else {
|
|
249
|
+
resultWithLocales = await req.payload.db.updateOne({
|
|
250
|
+
id,
|
|
251
|
+
collection: collectionConfig.slug,
|
|
252
|
+
data: dataToUpdate,
|
|
253
|
+
locale,
|
|
254
|
+
req
|
|
255
|
+
});
|
|
256
|
+
}
|
|
256
257
|
}
|
|
257
258
|
// /////////////////////////////////////
|
|
258
259
|
// Create version
|
|
@@ -266,9 +267,7 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
266
267
|
draft: isSavingDraft,
|
|
267
268
|
operation: 'update',
|
|
268
269
|
payload,
|
|
269
|
-
publishSpecificLocale,
|
|
270
270
|
req,
|
|
271
|
-
snapshot: snapshotToSave,
|
|
272
271
|
unpublish: unpublishAllLocales
|
|
273
272
|
});
|
|
274
273
|
}
|
|
@@ -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 // 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 let resultWithLocales: JsonObject = result\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n resultWithLocales = 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 resultWithLocales = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: resultWithLocales,\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: resultWithLocales,\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","resultWithLocales","updatedAt","Date","toISOString","updateOne","snapshot","unpublish","previousDoc"],"mappings":"AAwBA,SAASA,qBAAqB,QAAQ,yCAAwC;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WrE;QACb;IACF;IAEA,wCAAwC;IACxC,qBAAqB;IACrB,wCAAwC;IAExCiC,SAAS,MAAMpE,UAAU;QACvBiD,YAAYjC;QACZkC,SAASlB,IAAIkB,OAAO;QACpB/B;QACAgC,KAAK+C;QACL9C,OAAO/B;QACPC;QACA+B,QAAQ;QACR7B;QACAC;QACAG;QACAI;QACAC;QACAC;IACF;IAEA,wCAAwC;IACxC,yBAAyB;IACzB,wCAAwC;IAExC,IAAIlB,iBAAiB4C,KAAK,EAAE5D,WAAW6D,QAAQ;QAC7C,KAAK,MAAMC,QAAQ9C,iBAAiB4C,KAAK,CAAC5D,SAAS,CAAE;YACnDoE,SACE,AAAC,MAAMN,KAAK;gBACVb,YAAYjC;gBACZkC,SAASlB,IAAIkB,OAAO;gBACpBC,KAAKiB;gBACL3C;gBACAO;YACF,MAAOoC;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;QACXgD,aAAazD;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;gBACAgF,aAAazD;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, 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 { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.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 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 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 ??\n (hasLocalizeStatusEnabled(collectionConfig) && locale !== 'all' ? 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 // When saving a draft on a document whose latest version is published, the file\n // referenced by docWithLocales is still actively used by the published main document.\n // Deleting it here would break the published document's file even though no publish\n // is happening. Only skip deletion in this case; when the latest version is already a\n // draft, it is safe to delete the old draft file as it is being replaced.\n const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published'\n\n if (!isDraftOverPublished) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\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\n if (\n config.localization &&\n hasLocalizeStatusEnabled(collectionConfig) &&\n typeof result._status === 'string'\n ) {\n const statusStr = result._status\n result._status = {}\n for (const localeCode of config.localization.localeCodes) {\n ;(result._status as Record<string, unknown>)[localeCode] = statusStr\n }\n }\n\n let localizedPublishData: JsonObject | null = null\n\n if (config.localization && collectionConfig.versions) {\n if (hasLocalizeStatusEnabled(collectionConfig)) {\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 (\n !isSavingDraft &&\n result._status &&\n typeof result._status === 'object' &&\n !Array.isArray(result._status) &&\n (result._status as Record<string, unknown>)[locale] === 'published'\n ) {\n const currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n })\n\n localizedPublishData = buildLocalizedPublishData({\n config,\n currentDoc: currentDoc as JsonObject,\n fields: collectionConfig.fields,\n locale,\n result,\n })\n }\n }\n }\n\n const dataToUpdate: JsonObject = { ...(localizedPublishData ?? 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 let resultWithLocales: JsonObject = result\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n if (localizedPublishData) {\n // Single-locale publish: save filtered data to main doc but keep full locale data for\n // the version so draft fetches (replaceWithDraftIfAvailable) return complete data.\n await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n resultWithLocales = { ...result, updatedAt: dataToUpdate.updatedAt }\n } else {\n resultWithLocales = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n resultWithLocales = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: resultWithLocales,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n req,\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: resultWithLocales,\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","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","buildLocalizedPublishData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","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","isDraftOverPublished","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","localization","statusStr","localeCode","localeCodes","localizedPublishData","versions","accessibleLocaleCodes","filterAvailableLocales","filteredLocales","locales","map","code","Array","isArray","currentDoc","db","findOne","where","equals","fields","dataToUpdate","hash","salt","resultWithLocales","updatedAt","Date","toIS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AAC,MAAMN,KAAK;gBACVd,YAAYhC;gBACZiC,SAASlB,IAAIkB,OAAO;gBACpB/B;gBACAgC,KAAKkB;gBACLZ,WAAW;gBACX/B;gBACAyE,aAAanD;gBACbhB;YACF,MAAOqC;QACX;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/client.ts"],"sourcesContent":["import type { I18nClient, TFunction } from '@payloadcms/translations'\nimport type { DeepPartial } from 'ts-essentials'\n\nimport type { ImportMap } from '../bin/generateImportMap/index.js'\nimport type { ClientBlock } from '../fields/config/types.js'\nimport type { BlockSlug, TypedUser } from '../index.js'\nimport type {\n ClientWidget,\n RootLivePreviewConfig,\n SanitizedConfig,\n ServerOnlyLivePreviewProperties,\n} from './types.js'\n\nimport {\n type ClientCollectionConfig,\n createClientCollectionConfigs,\n} from '../collections/config/client.js'\nimport { createClientBlocks, createClientFields } from '../fields/config/client.js'\nimport { type ClientGlobalConfig, createClientGlobalConfigs } from '../globals/config/client.js'\n\nexport type ServerOnlyRootProperties = keyof Pick<\n SanitizedConfig,\n | 'bin'\n | 'cors'\n | 'csrf'\n | 'custom'\n | 'db'\n | 'editor'\n | 'email'\n | 'endpoints'\n | 'graphQL'\n | 'hooks'\n | 'i18n'\n | 'jobs'\n | 'kv'\n | 'logger'\n | 'onInit'\n | 'plugins'\n | 'queryPresets'\n | 'secret'\n | 'sharp'\n | 'storage'\n | 'typescript'\n>\n\nexport type ServerOnlyRootAdminProperties = keyof Pick<SanitizedConfig['admin'], 'components'>\n\nexport type ClientConfig = {\n admin: {\n dashboard?: {\n widgets: ClientWidget[]\n }\n livePreview?: Omit<RootLivePreviewConfig, ServerOnlyLivePreviewProperties>\n } & Omit<SanitizedConfig['admin'], 'components' | 'dashboard' | 'dependencies' | 'livePreview'>\n blocks: ClientBlock[]\n blocksMap: Record<BlockSlug, ClientBlock>\n collections: ClientCollectionConfig[]\n custom?: Record<string, any>\n globals: ClientGlobalConfig[]\n unauthenticated?: boolean\n} & Omit<SanitizedConfig, 'admin' | 'collections' | 'globals' | 'i18n' | ServerOnlyRootProperties>\n\nexport type UnauthenticatedClientConfig = {\n admin: {\n routes: ClientConfig['admin']['routes']\n user: ClientConfig['admin']['user']\n }\n collections: [\n {\n auth: ClientCollectionConfig['auth']\n slug: string\n },\n ]\n globals: []\n routes: ClientConfig['routes']\n serverURL: ClientConfig['serverURL']\n unauthenticated: true\n}\n\nexport const serverOnlyAdminConfigProperties: readonly Partial<ServerOnlyRootAdminProperties>[] = []\n\nexport const serverOnlyConfigProperties: readonly Partial<ServerOnlyRootProperties>[] = [\n 'endpoints',\n 'db',\n 'editor',\n 'plugins',\n 'sharp',\n 'onInit',\n 'secret',\n 'hooks',\n 'bin',\n 'i18n',\n 'typescript',\n 'cors',\n 'csrf',\n 'email',\n 'custom',\n 'graphQL',\n 'jobs',\n 'logger',\n 'kv',\n 'queryPresets',\n 'storage',\n // `admin`, `onInit`, `localization`, `collections`, and `globals` are all handled separately\n]\n\nexport type CreateClientConfigArgs = {\n config: SanitizedConfig\n i18n: I18nClient\n importMap: ImportMap\n /**\n * If unauthenticated, the client config will omit some sensitive properties\n * such as field schemas, etc. This is useful for login and error pages where\n * the page source should not contain this information.\n *\n * For example, allow `true` to generate a client config for the \"create first user\" page\n * where there is no user yet, but the config should still be complete.\n */\n user: true | TypedUser\n}\n\nexport const createUnauthenticatedClientConfig = ({\n clientConfig,\n}: {\n /**\n * Send the previously generated client config to share memory when applicable.\n * E.g. the admin-enabled collection config can reference the existing collection rather than creating a new object.\n */\n clientConfig: ClientConfig\n}): UnauthenticatedClientConfig => {\n /**\n * To share memory, find the admin user collection from the existing client config.\n */\n const adminUserCollection = clientConfig.collections.find(\n ({ slug }) => slug === clientConfig.admin.user,\n )!\n\n return {\n admin: {\n routes: clientConfig.admin.routes,\n user: clientConfig.admin.user,\n },\n collections: [\n {\n slug: adminUserCollection.slug,\n auth: adminUserCollection.auth,\n },\n ],\n globals: [],\n routes: clientConfig.routes,\n serverURL: clientConfig.serverURL,\n unauthenticated: true,\n }\n}\n\nexport const createClientConfig = ({\n config,\n i18n,\n importMap,\n}: CreateClientConfigArgs): ClientConfig => {\n const clientConfig = {} as DeepPartial<ClientConfig>\n\n for (const key in config) {\n if (serverOnlyConfigProperties.includes(key as any)) {\n continue\n }\n\n switch (key) {\n case 'admin':\n clientConfig.admin = {\n autoLogin: config.admin.autoLogin,\n autoRefresh: config.admin.autoRefresh,\n avatar: config.admin.avatar,\n custom: config.admin.custom,\n dateFormat: config.admin.dateFormat,\n importMap: config.admin.importMap,\n meta: config.admin.meta,\n routes: config.admin.routes,\n theme: config.admin.theme,\n timezones: config.admin.timezones,\n toast: config.admin.toast,\n user: config.admin.user,\n }\n\n if (config.admin.dashboard?.widgets) {\n ;(clientConfig.admin.dashboard ??= {}).widgets = config.admin.dashboard.widgets.map(\n (widget) => {\n const { Component: _, fields, label, ...rest } = widget\n return {\n ...rest,\n ...(fields?.length\n ? {\n fields: createClientFields({\n defaultIDType: config.db.defaultIDType,\n fields,\n i18n,\n importMap,\n }),\n }\n : {}),\n // Resolve label function to string for client\n label:\n typeof label === 'function' ? label({ i18n, t: i18n.t as TFunction }) : label,\n }\n },\n )\n }\n\n if (config.admin.livePreview) {\n clientConfig.admin.livePreview = {}\n\n if (config.admin.livePreview.breakpoints) {\n clientConfig.admin.livePreview.breakpoints = config.admin.livePreview.breakpoints\n }\n\n if (config.admin.livePreview.collections) {\n clientConfig.admin.livePreview.collections = config.admin.livePreview.collections\n }\n\n if (config.admin.livePreview.globals) {\n clientConfig.admin.livePreview.globals = config.admin.livePreview.globals\n }\n }\n\n break\n\n case 'blocks': {\n ;(clientConfig.blocks as ClientBlock[]) = createClientBlocks({\n blocks: config.blocks!,\n defaultIDType: config.db.defaultIDType,\n i18n,\n importMap,\n }).filter((block) => typeof block !== 'string') as ClientBlock[]\n\n clientConfig.blocksMap = {}\n if (clientConfig.blocks?.length) {\n for (const block of clientConfig.blocks) {\n if (!block?.slug) {\n continue\n }\n\n clientConfig.blocksMap[block.slug] = block as ClientBlock\n }\n }\n\n break\n }\n\n case 'collections':\n ;(clientConfig.collections as ClientCollectionConfig[]) = createClientCollectionConfigs({\n collections: config.collections,\n defaultIDType: config.db.defaultIDType,\n i18n,\n importMap,\n })\n\n break\n\n case 'globals':\n ;(clientConfig.globals as ClientGlobalConfig[]) = createClientGlobalConfigs({\n defaultIDType: config.db.defaultIDType,\n globals: config.globals,\n i18n,\n importMap,\n })\n\n break\n\n case 'localization':\n if (typeof config.localization === 'object' && config.localization) {\n clientConfig.localization = {}\n\n if (config.localization.defaultLocale) {\n clientConfig.localization.defaultLocale = config.localization.defaultLocale\n }\n\n if (config.localization.defaultLocalePublishOption) {\n clientConfig.localization.defaultLocalePublishOption =\n config.localization.defaultLocalePublishOption\n }\n\n if (config.localization.fallback) {\n clientConfig.localization.fallback = config.localization.fallback\n }\n\n if (config.localization.localeCodes) {\n clientConfig.localization.localeCodes = config.localization.localeCodes\n }\n\n if (config.localization.locales) {\n clientConfig.localization.locales = []\n\n for (const locale of config.localization.locales) {\n if (locale) {\n const clientLocale: Partial<(typeof config.localization.locales)[0]> = {}\n\n if (locale.code) {\n clientLocale.code = locale.code\n }\n\n if (locale.fallbackLocale) {\n clientLocale.fallbackLocale = locale.fallbackLocale\n }\n\n if (locale.label) {\n clientLocale.label = locale.label\n }\n\n if (locale.rtl) {\n clientLocale.rtl = locale.rtl\n }\n\n clientConfig.localization.locales.push(clientLocale)\n }\n }\n }\n }\n\n break\n\n default:\n ;(clientConfig as any)[key] = config[key as keyof SanitizedConfig]\n }\n }\n\n return clientConfig as ClientConfig\n}\n"],"names":["createClientCollectionConfigs","createClientBlocks","createClientFields","createClientGlobalConfigs","serverOnlyAdminConfigProperties","serverOnlyConfigProperties","createUnauthenticatedClientConfig","clientConfig","adminUserCollection","collections","find","slug","admin","user","routes","auth","globals","serverURL","unauthenticated","createClientConfig","config","i18n","importMap","key","includes","autoLogin","autoRefresh","avatar","custom","dateFormat","meta","theme","timezones","toast","dashboard","widgets","map","widget","Component","_","fields","label","rest","length","defaultIDType","db","t","livePreview","breakpoints","blocks","filter","block","blocksMap","localization","defaultLocale","defaultLocalePublishOption","fallback","localeCodes","locales","locale","clientLocale","code","fallbackLocale","rtl","push"],"mappings":"AAaA,SAEEA,6BAA6B,QACxB,kCAAiC;AACxC,SAASC,kBAAkB,EAAEC,kBAAkB,QAAQ,6BAA4B;AACnF,SAAkCC,yBAAyB,QAAQ,8BAA6B;AA6DhG,OAAO,MAAMC,kCAAqF,EAAE,CAAA;AAEpG,OAAO,MAAMC,6BAA2E;IACtF;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CAED,CAAA;AAiBD,OAAO,MAAMC,oCAAoC,CAAC,EAChDC,YAAY,EAOb;IACC;;GAEC,GACD,MAAMC,sBAAsBD,aAAaE,WAAW,CAACC,IAAI,CACvD,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASJ,aAAaK,KAAK,CAACC,IAAI;IAGhD,OAAO;QACLD,OAAO;YACLE,QAAQP,aAAaK,KAAK,CAACE,MAAM;YACjCD,MAAMN,aAAaK,KAAK,CAACC,IAAI;QAC/B;QACAJ,aAAa;YACX;gBACEE,MAAMH,oBAAoBG,IAAI;gBAC9BI,MAAMP,oBAAoBO,IAAI;YAChC;SACD;QACDC,SAAS,EAAE;QACXF,QAAQP,aAAaO,MAAM;QAC3BG,WAAWV,aAAaU,SAAS;QACjCC,iBAAiB;IACnB;AACF,EAAC;AAED,OAAO,MAAMC,qBAAqB,CAAC,EACjCC,MAAM,EACNC,IAAI,EACJC,SAAS,EACc;IACvB,MAAMf,eAAe,CAAC;IAEtB,IAAK,MAAMgB,OAAOH,OAAQ;QACxB,IAAIf,2BAA2BmB,QAAQ,CAACD,MAAa;YACnD;QACF;QAEA,OAAQA;YACN,KAAK;gBACHhB,aAAaK,KA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xD,aAAa8C,YAAY,CAACK,OAAO,CAACM,IAAI,CAACJ;4BACzC;wBACF;oBACF;gBACF;gBAEA;YAEF;;gBACIrD,YAAoB,CAACgB,IAAI,GAAGH,MAAM,CAACG,IAA6B;QACtE;IACF;IAEA,OAAOhB;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/config/client.ts"],"sourcesContent":["import type { I18nClient, TFunction } from '@payloadcms/translations'\nimport type { DeepPartial } from 'ts-essentials'\n\nimport type { ImportMap } from '../bin/generateImportMap/index.js'\nimport type { ClientBlock } from '../fields/config/types.js'\nimport type { BlockSlug, TypedUser } from '../index.js'\nimport type {\n ClientWidget,\n RootLivePreviewConfig,\n SanitizedConfig,\n ServerOnlyLivePreviewProperties,\n} from './types.js'\n\nimport {\n type ClientCollectionConfig,\n createClientCollectionConfigs,\n} from '../collections/config/client.js'\nimport { createClientBlocks, createClientFields } from '../fields/config/client.js'\nimport { type ClientGlobalConfig, createClientGlobalConfigs } from '../globals/config/client.js'\n\nexport type ServerOnlyRootProperties = keyof Pick<\n SanitizedConfig,\n | 'bin'\n | 'cors'\n | 'csrf'\n | 'custom'\n | 'db'\n | 'editor'\n | 'email'\n | 'endpoints'\n | 'graphQL'\n | 'hooks'\n | 'i18n'\n | 'jobs'\n | 'kv'\n | 'logger'\n | 'onInit'\n | 'plugins'\n | 'queryPresets'\n | 'secret'\n | 'sharp'\n | 'storage'\n | 'typescript'\n>\n\nexport type ServerOnlyRootAdminProperties = keyof Pick<SanitizedConfig['admin'], 'components'>\n\nexport type ClientConfig = {\n admin: {\n dashboard?: {\n widgets: ClientWidget[]\n }\n livePreview?: Omit<RootLivePreviewConfig, ServerOnlyLivePreviewProperties>\n } & Omit<SanitizedConfig['admin'], 'components' | 'dashboard' | 'dependencies' | 'livePreview'>\n blocks: ClientBlock[]\n blocksMap: Record<BlockSlug, ClientBlock>\n collections: ClientCollectionConfig[]\n custom?: Record<string, any>\n globals: ClientGlobalConfig[]\n unauthenticated?: boolean\n} & Omit<SanitizedConfig, 'admin' | 'collections' | 'globals' | 'i18n' | ServerOnlyRootProperties>\n\nexport type UnauthenticatedClientConfig = {\n admin: {\n routes: ClientConfig['admin']['routes']\n user: ClientConfig['admin']['user']\n }\n collections: [\n {\n auth: ClientCollectionConfig['auth']\n slug: string\n },\n ]\n globals: []\n routes: ClientConfig['routes']\n serverURL: ClientConfig['serverURL']\n unauthenticated: true\n}\n\nexport const serverOnlyAdminConfigProperties: readonly Partial<ServerOnlyRootAdminProperties>[] = []\n\nexport const serverOnlyConfigProperties: readonly Partial<ServerOnlyRootProperties>[] = [\n 'endpoints',\n 'db',\n 'editor',\n 'plugins',\n 'sharp',\n 'onInit',\n 'secret',\n 'hooks',\n 'bin',\n 'i18n',\n 'typescript',\n 'cors',\n 'csrf',\n 'email',\n 'custom',\n 'graphQL',\n 'jobs',\n 'logger',\n 'kv',\n 'queryPresets',\n 'storage',\n // `admin`, `onInit`, `localization`, `collections`, and `globals` are all handled separately\n]\n\nexport type CreateClientConfigArgs = {\n config: SanitizedConfig\n i18n: I18nClient\n importMap: ImportMap\n /**\n * If unauthenticated, the client config will omit some sensitive properties\n * such as field schemas, etc. This is useful for login and error pages where\n * the page source should not contain this information.\n *\n * For example, allow `true` to generate a client config for the \"create first user\" page\n * where there is no user yet, but the config should still be complete.\n */\n user: true | TypedUser\n}\n\nexport const createUnauthenticatedClientConfig = ({\n clientConfig,\n}: {\n /**\n * Send the previously generated client config to share memory when applicable.\n * E.g. the admin-enabled collection config can reference the existing collection rather than creating a new object.\n */\n clientConfig: ClientConfig\n}): UnauthenticatedClientConfig => {\n /**\n * To share memory, find the admin user collection from the existing client config.\n */\n const adminUserCollection = clientConfig.collections.find(\n ({ slug }) => slug === clientConfig.admin.user,\n )!\n\n return {\n admin: {\n routes: clientConfig.admin.routes,\n user: clientConfig.admin.user,\n },\n collections: [\n {\n slug: adminUserCollection.slug,\n auth: adminUserCollection.auth,\n },\n ],\n globals: [],\n routes: clientConfig.routes,\n serverURL: clientConfig.serverURL,\n unauthenticated: true,\n }\n}\n\nexport const createClientConfig = ({\n config,\n i18n,\n importMap,\n}: CreateClientConfigArgs): ClientConfig => {\n const clientConfig = {} as DeepPartial<ClientConfig>\n\n for (const key in config) {\n if (serverOnlyConfigProperties.includes(key as any)) {\n continue\n }\n\n switch (key) {\n case 'admin':\n clientConfig.admin = {\n autoLogin: config.admin.autoLogin,\n autoRefresh: config.admin.autoRefresh,\n avatar: config.admin.avatar,\n custom: config.admin.custom,\n dateFormat: config.admin.dateFormat,\n importMap: config.admin.importMap,\n meta: config.admin.meta,\n routes: config.admin.routes,\n theme: config.admin.theme,\n timezones: config.admin.timezones,\n toast: config.admin.toast,\n user: config.admin.user,\n }\n\n if (config.admin.dashboard?.widgets) {\n ;(clientConfig.admin.dashboard ??= {}).widgets = config.admin.dashboard.widgets.map(\n (widget) => {\n const { Component: _, fields, label, ...rest } = widget\n return {\n ...rest,\n ...(fields?.length\n ? {\n fields: createClientFields({\n defaultIDType: config.db.defaultIDType,\n fields,\n i18n,\n importMap,\n }),\n }\n : {}),\n // Resolve label function to string for client\n label:\n typeof label === 'function' ? label({ i18n, t: i18n.t as TFunction }) : label,\n }\n },\n )\n }\n\n if (config.admin.livePreview) {\n clientConfig.admin.livePreview = {}\n\n if (config.admin.livePreview.breakpoints) {\n clientConfig.admin.livePreview.breakpoints = config.admin.livePreview.breakpoints\n }\n\n if (config.admin.livePreview.collections) {\n clientConfig.admin.livePreview.collections = config.admin.livePreview.collections\n }\n\n if (config.admin.livePreview.globals) {\n clientConfig.admin.livePreview.globals = config.admin.livePreview.globals\n }\n }\n\n break\n\n case 'blocks': {\n ;(clientConfig.blocks as ClientBlock[]) = createClientBlocks({\n blocks: config.blocks!,\n defaultIDType: config.db.defaultIDType,\n i18n,\n importMap,\n }).filter((block) => typeof block !== 'string')\n\n clientConfig.blocksMap = {}\n if (clientConfig.blocks?.length) {\n for (const block of clientConfig.blocks) {\n if (!block?.slug) {\n continue\n }\n\n clientConfig.blocksMap[block.slug] = block as ClientBlock\n }\n }\n\n break\n }\n\n case 'collections':\n ;(clientConfig.collections as ClientCollectionConfig[]) = createClientCollectionConfigs({\n collections: config.collections,\n defaultIDType: config.db.defaultIDType,\n i18n,\n importMap,\n })\n\n break\n\n case 'globals':\n ;(clientConfig.globals as ClientGlobalConfig[]) = createClientGlobalConfigs({\n defaultIDType: config.db.defaultIDType,\n globals: config.globals,\n i18n,\n importMap,\n })\n\n break\n\n case 'localization':\n if (typeof config.localization === 'object' && config.localization) {\n clientConfig.localization = {}\n\n if (config.localization.defaultLocale) {\n clientConfig.localization.defaultLocale = config.localization.defaultLocale\n }\n\n if (config.localization.defaultLocalePublishOption) {\n clientConfig.localization.defaultLocalePublishOption =\n config.localization.defaultLocalePublishOption\n }\n\n if (config.localization.fallback) {\n clientConfig.localization.fallback = config.localization.fallback\n }\n\n if (config.localization.localeCodes) {\n clientConfig.localization.localeCodes = config.localization.localeCodes\n }\n\n if (config.localization.locales) {\n clientConfig.localization.locales = []\n\n for (const locale of config.localization.locales) {\n if (locale) {\n const clientLocale: Partial<(typeof config.localization.locales)[0]> = {}\n\n if (locale.code) {\n clientLocale.code = locale.code\n }\n\n if (locale.fallbackLocale) {\n clientLocale.fallbackLocale = locale.fallbackLocale\n }\n\n if (locale.label) {\n clientLocale.label = locale.label\n }\n\n if (locale.rtl) {\n clientLocale.rtl = locale.rtl\n }\n\n clientConfig.localization.locales.push(clientLocale)\n }\n }\n }\n }\n\n break\n\n default:\n ;(clientConfig as any)[key] = config[key as keyof SanitizedConfig]\n }\n }\n\n return clientConfig as ClientConfig\n}\n"],"names":["createClientCollectionConfigs","createClientBlocks","createClientFields","createClientGlobalConfigs","serverOnlyAdminConfigProperties","serverOnlyConfigProperties","createUnauthenticatedClientConfig","clientConfig","adminUserCollection","collections","find","slug","admin","user","routes","auth","globals","serverURL","unauthenticated","createClientConfig","config","i18n","importMap","key","includes","autoLogin","autoRefresh","avatar","custom","dateFormat","meta","theme","timezones","toast","dashboard","widgets","map","widget","Component","_","fields","label","rest","length","defaultIDType","db","t","livePreview","breakpoints","blocks","filter","block","blocksMap","localization","defaultLocale","defaultLocalePublishOption","fallback","localeCodes","locales","locale","clientLocale","code","fallbackLocale","rtl","push"],"mappings":"AAaA,SAEEA,6BAA6B,QACxB,kCAAiC;AACxC,SAASC,kBAAkB,EAAEC,kBAAkB,QAAQ,6BAA4B;AACnF,SAAkCC,yBAAyB,QAAQ,8BAA6B;AA6DhG,OAAO,MAAMC,kCAAqF,EAAE,CAAA;AAEpG,OAAO,MAAMC,6BAA2E;IACtF;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CAED,CAAA;AAiBD,OAAO,MAAMC,oCAAoC,CAAC,EAChDC,YAAY,EAOb;IACC;;GAEC,GACD,MAAMC,sBAAsBD,aAAaE,WAAW,CAACC,IAAI,CACvD,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASJ,aAAaK,KAAK,CAACC,IAAI;IAGhD,OAAO;QACLD,OAAO;YACLE,QAAQP,aAAaK,KAAK,CAACE,MAAM;YACjCD,MAAMN,aAAaK,KAAK,CAACC,IAAI;QAC/B;QACAJ,aAAa;YACX;gBACEE,MAAMH,oBAAoBG,IAAI;gBAC9BI,MAAMP,oBAAoBO,IAAI;YAChC;SACD;QACDC,SAAS,EAAE;QACXF,QAAQP,aAAaO,MAAM;QAC3BG,WAAWV,aAAaU,SAAS;QACjCC,iBAAiB;IACnB;AACF,EAAC;AAED,OAAO,MAAMC,qBAAqB,CAAC,EACjCC,MAAM,EACNC,IAAI,EACJC,SAAS,EACc;IACvB,MAAMf,eAAe,CAAC;IAEtB,IAAK,MAAMgB,OAAOH,OAAQ;QACxB,IAAIf,2BAA2BmB,QAAQ,CAACD,MAAa;YACnD;QACF;QAEA,OAAQA;YACN,KAAK;gBACHhB,aAAaK,KAAK,GAAG;oBACnBa,WAAWL,OAAOR,KAA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IAAI,CAACJ;4BACzC;wBACF;oBACF;gBACF;gBAEA;YAEF;;gBACIrD,YAAoB,CAACgB,IAAI,GAAGH,MAAM,CAACG,IAA6B;QACtE;IACF;IAEA,OAAOhB;AACT,EAAC"}
|
|
@@ -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;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;
|
|
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;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;AAgB5E,eAAO,MAAM,yBAAyB,GACpC,YAAY,gBAAgB,EAC5B,QAAQ,MAAM,EACd,qBAAqB,MAAM,EAAE,EAC7B,6BAA6B,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,kBAuF9D,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,cAAc,EAAE,MAAM,CAAA;IACtB,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,YAAY,EAAE,SAAS,GAAG,MAAM,CAAA;IAChC,kBAAkB,EAAE,MAAM,CAAA;IAC1B,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAA;QACV,GAAG,EAAE,MAAM,CAAA;KACZ,CAAA;CACF,CAAA;AAED,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,eAAe,EACvB,4BAA4B,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,SAiN7D,CAAA"}
|
|
@@ -4,8 +4,10 @@ import { APIError } from '../../errors/index.js';
|
|
|
4
4
|
import { sanitizeField } from '../../fields/config/sanitize.js';
|
|
5
5
|
import { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js';
|
|
6
6
|
import { commitTransaction } from '../../utilities/commitTransaction.js';
|
|
7
|
+
import { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js';
|
|
7
8
|
import { initTransaction } from '../../utilities/initTransaction.js';
|
|
8
9
|
import { killTransaction } from '../../utilities/killTransaction.js';
|
|
10
|
+
import { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js';
|
|
9
11
|
import { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js';
|
|
10
12
|
import { getJoinScopeContext } from './utils/getJoinScopeContext.js';
|
|
11
13
|
import { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js';
|
|
@@ -255,8 +257,28 @@ export const addOrderableEndpoint = (config, joinFieldPathsByCollection)=>{
|
|
|
255
257
|
// Currently N (= docsToMove.length) is always 1. Maybe in the future we will
|
|
256
258
|
// allow dragging and reordering multiple documents at once via the UI.
|
|
257
259
|
const orderValues = newKeyWillBe === 'greater' ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length) : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length);
|
|
260
|
+
const draftsEnabled = hasDraftsEnabled(collection);
|
|
258
261
|
// Update each document with its new order value
|
|
259
262
|
for (const [index, id] of docsToMove.entries()){
|
|
263
|
+
let draft;
|
|
264
|
+
if (draftsEnabled) {
|
|
265
|
+
const latestVersion = await getLatestCollectionVersion({
|
|
266
|
+
id,
|
|
267
|
+
config: collection,
|
|
268
|
+
payload: req.payload,
|
|
269
|
+
query: {
|
|
270
|
+
collection: collection.slug,
|
|
271
|
+
req,
|
|
272
|
+
where: {
|
|
273
|
+
id: {
|
|
274
|
+
equals: id
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
req
|
|
279
|
+
});
|
|
280
|
+
draft = latestVersion?._status === 'draft';
|
|
281
|
+
}
|
|
260
282
|
await req.payload.update({
|
|
261
283
|
id,
|
|
262
284
|
collection: collection.slug,
|
|
@@ -264,6 +286,7 @@ export const addOrderableEndpoint = (config, joinFieldPathsByCollection)=>{
|
|
|
264
286
|
[orderableFieldName]: orderValues[index]
|
|
265
287
|
},
|
|
266
288
|
depth: 0,
|
|
289
|
+
draft,
|
|
267
290
|
req
|
|
268
291
|
});
|
|
269
292
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/orderable/index.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { BeforeChangeHook, CollectionConfig } from '../../collections/config/types.js'\nimport type { Config } from '../../config/types.js'\nimport type { Field, TextField } from '../../fields/config/types.js'\nimport type { Endpoint, PayloadHandler, SanitizedConfig } from '../types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { APIError } from '../../errors/index.js'\nimport { sanitizeField } from '../../fields/config/sanitize.js'\nimport { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js'\nimport { getJoinScopeContext } from './utils/getJoinScopeContext.js'\nimport { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js'\nimport { resolvePendingTargetKey } from './utils/resolvePendingTargetKey.js'\n\nexport const addOrderableFieldsAndHook = async (\n collection: CollectionConfig,\n config: Config,\n orderableFieldNames: string[],\n joinFieldPathsByCollection?: Map<string, Map<string, string>>,\n) => {\n // 1. Add fields\n for (const orderableFieldName of orderableFieldNames) {\n const orderField: TextField = {\n name: orderableFieldName,\n type: 'text',\n admin: {\n disabled: true,\n hidden: true,\n readOnly: true,\n },\n hooks: {\n beforeDuplicate: [\n ({ siblingData }) => {\n delete siblingData[orderableFieldName]\n },\n ],\n },\n index: true,\n }\n\n // Sanitize the field using the standard sanitization logic\n await sanitizeField({\n collectionConfig: collection,\n config,\n existingFieldNames: new Set(),\n field: orderField,\n index: 0,\n isTopLevelField: true,\n joinPath: '',\n parentIndexPath: '',\n parentIsLocalized: false,\n parentSchemaPath: '',\n requireFieldLevelRichTextEditor: false,\n validRelationships: null,\n })\n\n collection.fields.unshift(orderField)\n }\n\n // 2. Add hook\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.beforeChange) {\n collection.hooks.beforeChange = []\n }\n\n const orderBeforeChangeHook: BeforeChangeHook = async ({ data, originalDoc, req }) => {\n for (const orderableFieldName of orderableFieldNames) {\n if (!data[orderableFieldName] && !originalDoc?.[orderableFieldName]) {\n const joinScopeWhere = getJoinScopeWhereFromDocData({\n collectionSlug: collection.slug,\n data,\n joinFieldPathsByCollection,\n orderableFieldName,\n originalDoc,\n })\n\n const lastDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n sort: `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: true,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n\n const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null\n data[orderableFieldName] = generateKeyBetween(lastOrderValue, null)\n }\n }\n\n return data\n }\n\n collection.hooks.beforeChange.push(orderBeforeChangeHook)\n}\n\n/**\n * The body of the reorder endpoint.\n * @internal\n */\nexport type OrderableEndpointBody = {\n collectionSlug: string\n docsToMove: string[]\n newKeyWillBe: 'greater' | 'less'\n orderableFieldName: string\n target: {\n id: string\n key: string\n }\n}\n\nexport const addOrderableEndpoint = (\n config: SanitizedConfig,\n joinFieldPathsByCollection: Map<string, Map<string, string>>,\n) => {\n // 3. Add endpoint\n const reorderHandler: PayloadHandler = async (req) => {\n const body = (await req.json?.()) as OrderableEndpointBody\n\n const { collectionSlug, docsToMove, newKeyWillBe, orderableFieldName, target } = body\n\n if (!Array.isArray(docsToMove) || docsToMove.length === 0) {\n return new Response(JSON.stringify({ error: 'docsToMove must be a non-empty array' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (newKeyWillBe !== 'greater' && newKeyWillBe !== 'less') {\n return new Response(JSON.stringify({ error: 'newKeyWillBe must be \"greater\" or \"less\"' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n const collection = config.collections.find((c) => c.slug === collectionSlug)\n if (!collection) {\n return new Response(JSON.stringify({ error: `Collection ${collectionSlug} not found` }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (typeof orderableFieldName !== 'string') {\n return new Response(JSON.stringify({ error: 'orderableFieldName must be a string' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const { joinScopeWhere, targetDoc } = await getJoinScopeContext({\n collectionSlug: collection.slug,\n joinFieldPathsByCollection,\n orderableFieldName,\n req,\n target,\n })\n\n // Prevent reordering if user doesn't have editing permissions\n if (collection.access?.update) {\n await executeAccess(\n {\n // Currently only one doc can be moved at a time. We should review this if we want to allow\n // multiple docs to be moved at once in the future.\n id: docsToMove[0],\n data: {},\n req,\n },\n collection.access.update,\n )\n }\n /**\n * If there is no target.key, we can assume the user enabled `orderable`\n * on a collection with existing documents, and that this is the first\n * time they tried to reorder them. Therefore, we perform a one-time\n * migration by setting the key value for all documents. We do this\n * instead of enforcing `required` and `unique` at the database schema\n * level, so that users don't have to run a migration when they enable\n * `orderable` on a collection with existing documents.\n */\n if (!target.key) {\n const { docs } = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 0,\n req,\n select: { [orderableFieldName]: true },\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: false,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n await initTransaction(req)\n // We cannot update all documents in a single operation with `payload.update`,\n // because they would all end up with the same order key (`a0`).\n try {\n for (const doc of docs) {\n await req.payload.update({\n id: doc.id,\n collection: collection.slug,\n data: {\n // no data needed since the order hooks will handle this\n },\n depth: 0,\n req,\n })\n await commitTransaction(req)\n }\n } catch (e) {\n await killTransaction(req)\n if (e instanceof Error) {\n throw new APIError(e.message, httpStatus.INTERNAL_SERVER_ERROR)\n }\n }\n\n return new Response(JSON.stringify({ message: 'initial migration', success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n if (\n typeof target !== 'object' ||\n typeof target.id === 'undefined' ||\n typeof target.key !== 'string'\n ) {\n return new Response(JSON.stringify({ error: 'target must be an object with id' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const targetId = target.id\n const targetKey = await resolvePendingTargetKey({\n collectionSlug: collection.slug,\n orderableFieldName,\n req,\n targetDoc,\n targetID: targetId,\n targetKey: target.key,\n })\n\n // The reason the endpoint does not receive this docId as an argument is that there\n // are situations where the user may not see or know what the next or previous one is. For\n // example, access control restrictions, if docBefore is the last one on the page, etc.\n const adjacentDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n select: { [orderableFieldName]: true },\n sort: newKeyWillBe === 'greater' ? orderableFieldName : `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n [newKeyWillBe === 'greater' ? 'greater_than' : 'less_than']: targetKey,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n const adjacentDocKey = adjacentDoc.docs?.[0]?.[orderableFieldName] || null\n\n // Currently N (= docsToMove.length) is always 1. Maybe in the future we will\n // allow dragging and reordering multiple documents at once via the UI.\n const orderValues =\n newKeyWillBe === 'greater'\n ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length)\n : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length)\n\n // Update each document with its new order value\n for (const [index, id] of docsToMove.entries()) {\n await req.payload.update({\n id,\n collection: collection.slug,\n data: {\n [orderableFieldName]: orderValues[index],\n },\n depth: 0,\n req,\n })\n }\n\n return new Response(JSON.stringify({ orderValues, success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n const reorderEndpoint: Endpoint = {\n handler: reorderHandler,\n method: 'post',\n path: '/reorder',\n }\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n config.endpoints.push(reorderEndpoint)\n}\n"],"names":["status","httpStatus","executeAccess","APIError","sanitizeField","combineWhereConstraints","commitTransaction","initTransaction","killTransaction","generateKeyBetween","generateNKeysBetween","getJoinScopeContext","getJoinScopeWhereFromDocData","resolvePendingTargetKey","addOrderableFieldsAndHook","collection","config","orderableFieldNames","joinFieldPathsByCollection","orderableFieldName","orderField","name","type","admin","disabled","hidden","readOnly","hooks","beforeDuplicate","siblingData","index","collectionConfig","existingFieldNames","Set","field","isTopLevelField","joinPath","parentIndexPath","parentIsLocalized","parentSchemaPath","requireFieldLevelRichTextEditor","validRelationships","fields","unshift","beforeChange","orderBeforeChangeHook","data","originalDoc","req","joinScopeWhere","collectionSlug","slug","lastDoc","payload","find","depth","limit","pagination","select","sort","where","exists","undefined","lastOrderValue","docs","push","addOrderableEndpoint","reorderHandler","body","json","docsToMove","newKeyWillBe","target","Array","isArray","length","Response","JSON","stringify","error","headers","collections","c","targetDoc","access","update","id","key","doc","e","Error","message","INTERNAL_SERVER_ERROR","success","targetId","targetKey","targetID","adjacentDoc","adjacentDocKey","orderValues","entries","reorderEndpoint","handler","method","path","endpoints"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAOlD,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,aAAa,QAAQ,kCAAiC;AAC/D,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ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YACZC,QAAQ;gBAAE,CAACvC,mBAAmB,EAAE;YAAK;YACrCwC,MAAMY,iBAAiB,YAAYpD,qBAAqB,CAAC,CAAC,EAAEA,oBAAoB;YAChFyC,OAAOvD,wBAAwB;gBAC7B;oBACE,CAACc,mBAAmB,EAAE;wBACpB,CAACoD,iBAAiB,YAAY,iBAAiB,YAAY,EAAEwB;oBAC/D;gBACF;gBACA9C,kBAAkBa;aACnB;QACH;QACA,MAAMoC,iBAAiBD,YAAYjC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC7C,mBAAmB,IAAI;QAEtE,6EAA6E;QAC7E,uEAAuE;QACvE,MAAMgF,cACJ5B,iBAAiB,YACb7D,qBAAqBqF,WAAWG,gBAAgB5B,WAAWK,MAAM,IACjEjE,qBAAqBwF,gBAAgBH,WAAWzB,WAAWK,MAAM;QAEvE,gDAAgD;QAChD,KAAK,MAAM,CAAC7C,OAAOwD,GAAG,IAAIhB,WAAW8B,OAAO,GAAI;YAC9C,MAAMpD,IAAIK,OAAO,CAACgC,MAAM,CAAC;gBACvBC;gBACAvE,YAAYA,WAAWoC,IAAI;gBAC3BL,MAAM;oBACJ,CAAC3B,mBAAmB,EAAEgF,WAAW,CAACrE,MAAM;gBAC1C;gBACAyB,OAAO;gBACPP;YACF;QACF;QAEA,OAAO,IAAI4B,SAASC,KAAKC,SAAS,CAAC;YAAEqB;YAAaN,SAAS;QAAK,IAAI;YAClEb,SAAS;gBAAE,gBAAgB;YAAmB;YAC9ChF,QAAQ;QACV;IACF;IAEA,MAAMqG,kBAA4B;QAChCC,SAASnC;QACToC,QAAQ;QACRC,MAAM;IACR;IAEA,IAAI,CAACxF,OAAOyF,SAAS,EAAE;QACrBzF,OAAOyF,SAAS,GAAG,EAAE;IACvB;IAEAzF,OAAOyF,SAAS,CAACxC,IAAI,CAACoC;AACxB,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/config/orderable/index.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { BeforeChangeHook, CollectionConfig } from '../../collections/config/types.js'\nimport type { Config } from '../../config/types.js'\nimport type { Field, TextField } from '../../fields/config/types.js'\nimport type { Endpoint, PayloadHandler, SanitizedConfig } from '../types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { APIError } from '../../errors/index.js'\nimport { sanitizeField } from '../../fields/config/sanitize.js'\nimport { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js'\nimport { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js'\nimport { getJoinScopeContext } from './utils/getJoinScopeContext.js'\nimport { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js'\nimport { resolvePendingTargetKey } from './utils/resolvePendingTargetKey.js'\n\nexport const addOrderableFieldsAndHook = async (\n collection: CollectionConfig,\n config: Config,\n orderableFieldNames: string[],\n joinFieldPathsByCollection?: Map<string, Map<string, string>>,\n) => {\n // 1. Add fields\n for (const orderableFieldName of orderableFieldNames) {\n const orderField: TextField = {\n name: orderableFieldName,\n type: 'text',\n admin: {\n disabled: true,\n hidden: true,\n readOnly: true,\n },\n hooks: {\n beforeDuplicate: [\n ({ siblingData }) => {\n delete siblingData[orderableFieldName]\n },\n ],\n },\n index: true,\n }\n\n // Sanitize the field using the standard sanitization logic\n await sanitizeField({\n collectionConfig: collection,\n config,\n existingFieldNames: new Set(),\n field: orderField,\n index: 0,\n isTopLevelField: true,\n joinPath: '',\n parentIndexPath: '',\n parentIsLocalized: false,\n parentSchemaPath: '',\n requireFieldLevelRichTextEditor: false,\n validRelationships: null,\n })\n\n collection.fields.unshift(orderField)\n }\n\n // 2. Add hook\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.beforeChange) {\n collection.hooks.beforeChange = []\n }\n\n const orderBeforeChangeHook: BeforeChangeHook = async ({ data, originalDoc, req }) => {\n for (const orderableFieldName of orderableFieldNames) {\n if (!data[orderableFieldName] && !originalDoc?.[orderableFieldName]) {\n const joinScopeWhere = getJoinScopeWhereFromDocData({\n collectionSlug: collection.slug,\n data,\n joinFieldPathsByCollection,\n orderableFieldName,\n originalDoc,\n })\n\n const lastDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n sort: `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: true,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n\n const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null\n data[orderableFieldName] = generateKeyBetween(lastOrderValue, null)\n }\n }\n\n return data\n }\n\n collection.hooks.beforeChange.push(orderBeforeChangeHook)\n}\n\n/**\n * The body of the reorder endpoint.\n * @internal\n */\nexport type OrderableEndpointBody = {\n collectionSlug: string\n docsToMove: string[]\n newKeyWillBe: 'greater' | 'less'\n orderableFieldName: string\n target: {\n id: string\n key: string\n }\n}\n\nexport const addOrderableEndpoint = (\n config: SanitizedConfig,\n joinFieldPathsByCollection: Map<string, Map<string, string>>,\n) => {\n // 3. Add endpoint\n const reorderHandler: PayloadHandler = async (req) => {\n const body = (await req.json?.()) as OrderableEndpointBody\n\n const { collectionSlug, docsToMove, newKeyWillBe, orderableFieldName, target } = body\n\n if (!Array.isArray(docsToMove) || docsToMove.length === 0) {\n return new Response(JSON.stringify({ error: 'docsToMove must be a non-empty array' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (newKeyWillBe !== 'greater' && newKeyWillBe !== 'less') {\n return new Response(JSON.stringify({ error: 'newKeyWillBe must be \"greater\" or \"less\"' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n const collection = config.collections.find((c) => c.slug === collectionSlug)\n if (!collection) {\n return new Response(JSON.stringify({ error: `Collection ${collectionSlug} not found` }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (typeof orderableFieldName !== 'string') {\n return new Response(JSON.stringify({ error: 'orderableFieldName must be a string' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const { joinScopeWhere, targetDoc } = await getJoinScopeContext({\n collectionSlug: collection.slug,\n joinFieldPathsByCollection,\n orderableFieldName,\n req,\n target,\n })\n\n // Prevent reordering if user doesn't have editing permissions\n if (collection.access?.update) {\n await executeAccess(\n {\n // Currently only one doc can be moved at a time. We should review this if we want to allow\n // multiple docs to be moved at once in the future.\n id: docsToMove[0],\n data: {},\n req,\n },\n collection.access.update,\n )\n }\n /**\n * If there is no target.key, we can assume the user enabled `orderable`\n * on a collection with existing documents, and that this is the first\n * time they tried to reorder them. Therefore, we perform a one-time\n * migration by setting the key value for all documents. We do this\n * instead of enforcing `required` and `unique` at the database schema\n * level, so that users don't have to run a migration when they enable\n * `orderable` on a collection with existing documents.\n */\n if (!target.key) {\n const { docs } = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 0,\n req,\n select: { [orderableFieldName]: true },\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: false,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n await initTransaction(req)\n // We cannot update all documents in a single operation with `payload.update`,\n // because they would all end up with the same order key (`a0`).\n try {\n for (const doc of docs) {\n await req.payload.update({\n id: doc.id,\n collection: collection.slug,\n data: {\n // no data needed since the order hooks will handle this\n },\n depth: 0,\n req,\n })\n await commitTransaction(req)\n }\n } catch (e) {\n await killTransaction(req)\n if (e instanceof Error) {\n throw new APIError(e.message, httpStatus.INTERNAL_SERVER_ERROR)\n }\n }\n\n return new Response(JSON.stringify({ message: 'initial migration', success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n if (\n typeof target !== 'object' ||\n typeof target.id === 'undefined' ||\n typeof target.key !== 'string'\n ) {\n return new Response(JSON.stringify({ error: 'target must be an object with id' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const targetId = target.id\n const targetKey = await resolvePendingTargetKey({\n collectionSlug: collection.slug,\n orderableFieldName,\n req,\n targetDoc,\n targetID: targetId,\n targetKey: target.key,\n })\n\n // The reason the endpoint does not receive this docId as an argument is that there\n // are situations where the user may not see or know what the next or previous one is. For\n // example, access control restrictions, if docBefore is the last one on the page, etc.\n const adjacentDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n select: { [orderableFieldName]: true },\n sort: newKeyWillBe === 'greater' ? orderableFieldName : `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n [newKeyWillBe === 'greater' ? 'greater_than' : 'less_than']: targetKey,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n const adjacentDocKey = adjacentDoc.docs?.[0]?.[orderableFieldName] || null\n\n // Currently N (= docsToMove.length) is always 1. Maybe in the future we will\n // allow dragging and reordering multiple documents at once via the UI.\n const orderValues =\n newKeyWillBe === 'greater'\n ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length)\n : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length)\n\n const draftsEnabled = hasDraftsEnabled(collection)\n\n // Update each document with its new order value\n for (const [index, id] of docsToMove.entries()) {\n let draft: boolean | undefined\n\n if (draftsEnabled) {\n const latestVersion = await getLatestCollectionVersion({\n id,\n config: collection,\n payload: req.payload,\n query: {\n collection: collection.slug,\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n\n draft = latestVersion?._status === 'draft'\n }\n\n await req.payload.update({\n id,\n collection: collection.slug,\n data: {\n [orderableFieldName]: orderValues[index],\n },\n depth: 0,\n draft,\n req,\n })\n }\n\n return new Response(JSON.stringify({ orderValues, success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n const reorderEndpoint: Endpoint = {\n handler: reorderHandler,\n method: 'post',\n path: '/reorder',\n }\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n config.endpoints.push(reorderEndpoint)\n}\n"],"names":["status","httpStatus","executeAccess","APIError","sanitizeField","combineWhereConstraints","commitTransaction","hasDraftsEnabled","initTransaction","killTransaction","getLatestCollectionVersion","generateKeyBetween","generateNKeysBetween","getJoinScopeContext","getJoinScopeWhereFromDocData","resolvePendingTargetKey","addOrderableFieldsAndHook","collection","config","orderableFieldNames","joinFieldPathsByCollection","orderableFieldName","orderField","name","type","admin","disabled","hidden","readOnly","hooks","beforeDuplicate","siblingData","index","collectionConfig","existingFieldNames","Set","field","isTopLevelField","joinPath","parentIndexPath","parentIsLocalized","parentSchemaPath","requireFieldLevelRichTextEditor","validRelationships","fields","unshift","beforeChange","orderBeforeChangeHook","data","originalDoc","req","joinScopeWhere","collectionSlug","slug","lastDoc","payload","find","depth","limit","pagination","select","sort","where","exists","undefined","lastOrderValue","docs","push","addOrderableEndpoint","reorderHandler","body","json","docsToMove","newKeyWillBe","target","Array","isArray","length","Response","JSON","stringify","error","headers","collections","c","targetDoc","access","update","id","key","doc","e","Error","message","INTERNAL_SERVER_ERROR","success","targetId","targetKey","targetID","adjacentDoc","adjacentDocKey","orderValues","draftsEnabled","entries","draft","latestVersion","query","equals","_status","reorderEndpoint","handler","method","path","endpoints"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAOlD,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,aAAa,QAAQ,kCAAiC;AAC/D,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,0BAA0B,QAAQ,+CAA8C;AACzF,SAASC,kBAAkB,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