payload 4.0.0-beta.3 → 4.0.0-beta.4
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/adapters/router.d.ts +1 -1
- package/dist/admin/adapters/router.d.ts.map +1 -1
- package/dist/admin/adapters/router.js.map +1 -1
- package/dist/admin/initAdminContext.js.map +1 -1
- package/dist/auth/getFieldsToSign.js.map +1 -1
- package/dist/auth/loginWithCookie.js.map +1 -1
- package/dist/auth/serverFunctions/cookies.js.map +1 -1
- package/dist/auth/serverFunctions/login.js.map +1 -1
- package/dist/cli/defineCLICommand.js +1 -1
- package/dist/cli/defineCLICommand.js.map +1 -1
- package/dist/collections/config/client.js.map +1 -1
- package/dist/collections/operations/findByID.js.map +1 -1
- package/dist/collections/operations/findVersionByID.js.map +1 -1
- package/dist/collections/operations/findVersions.js.map +1 -1
- package/dist/collections/operations/local/findDistinct.js.map +1 -1
- package/dist/collections/operations/renameFile.js +1 -1
- package/dist/collections/operations/renameFile.js.map +1 -1
- package/dist/collections/operations/utilities/update.js +1 -1
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/collections/operations/validate.js +4 -4
- package/dist/collections/operations/validate.js.map +1 -1
- package/dist/config/definePlugin.js.map +1 -1
- package/dist/config/sanitize.js +2 -2
- package/dist/config/sanitize.js.map +1 -1
- package/dist/exports/build-config.d.ts +9 -0
- package/dist/exports/build-config.d.ts.map +1 -0
- package/dist/exports/build-config.js +38 -0
- package/dist/exports/build-config.js.map +1 -0
- package/dist/fields/config/client.js.map +1 -1
- package/dist/fields/hooks/afterChange/promise.js.map +1 -1
- package/dist/fields/validations.d.ts.map +1 -1
- package/dist/fields/validations.js +4 -1
- package/dist/fields/validations.js.map +1 -1
- package/dist/globals/operations/local/findOne.js.map +1 -1
- package/dist/globals/operations/local/update.js.map +1 -1
- package/dist/globals/operations/restoreVersion.d.ts +2 -3
- package/dist/globals/operations/restoreVersion.d.ts.map +1 -1
- package/dist/globals/operations/restoreVersion.js +22 -15
- package/dist/globals/operations/restoreVersion.js.map +1 -1
- package/dist/globals/operations/validate.js +1 -1
- package/dist/globals/operations/validate.js.map +1 -1
- package/dist/hierarchy/createFolderField.js.map +1 -1
- package/dist/hierarchy/resolveHierarchyCollections.js +2 -2
- package/dist/hierarchy/resolveHierarchyCollections.js.map +1 -1
- package/dist/hierarchy/utils/computePaths.d.ts.map +1 -1
- package/dist/hierarchy/utils/computePaths.js.map +1 -1
- package/dist/index.bundled.d.ts +12 -3
- package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js +1 -1
- package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js.map +1 -1
- package/dist/uploads/fileVersioning/archive.js.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/getFileFromUploadInstructions.js.map +1 -1
- package/dist/uploads/safeFetch.js.map +1 -1
- package/dist/uploads/stagedUpload.js.map +1 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.js +11 -2
- package/dist/uploads/transformers/handleDynamicFileRequest.js.map +1 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.d.ts.map +1 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.js +0 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.js.map +1 -1
- package/dist/utilities/appendDateTimezoneSelectFields.js.map +1 -1
- package/dist/utilities/cloneValidationRequest.js.map +1 -1
- package/dist/utilities/createPayloadRequest.js.map +1 -1
- package/dist/utilities/deepCopyObject.js.map +1 -1
- package/dist/utilities/documentMatchingWhereExists.js +1 -1
- package/dist/utilities/documentMatchingWhereExists.js.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.js.map +1 -1
- package/dist/utilities/getEntityPermissions/getEntityPermissions.d.ts.map +1 -1
- package/dist/utilities/getEntityPermissions/getEntityPermissions.js +1 -0
- package/dist/utilities/getEntityPermissions/getEntityPermissions.js.map +1 -1
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.js.map +1 -1
- package/dist/utilities/parseParams/index.js.map +1 -1
- package/dist/utilities/parseValidationLocale.js.map +1 -1
- package/dist/utilities/sanitizePopulateParam.js.map +1 -1
- package/dist/utilities/telemetry/featureInfo/getFeatureInfo.js.map +1 -1
- package/dist/versions/allLocalesPublicationStatus.js.map +1 -1
- package/package.json +11 -9
- package/skills/payload/reference/PLUGIN-DEVELOPMENT.md +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/findVersions.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PaginatedDocs } from '../../database/types.js'\nimport type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'\nimport type { TypeWithVersion } from '../../versions/types.js'\nimport type { Collection } from '../config/types.js'\nimport type { FindOptions } from './local/find.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { checkFileAccess } from '../../uploads/checkFileAccess.js'\nimport { markHistoricalFileURLs } from '../../uploads/fileVersioning/markHistoricalFileURLs.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { hasVersionsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\n\nexport type Arguments = {\n collection: Collection\n depth?: number\n limit?: number\n overrideAccess?: boolean\n page?: number\n pagination?: boolean\n populate?: PopulateType\n req?: PayloadRequest\n showHiddenFields?: boolean\n sort?: Sort\n trash?: boolean\n where?: Where\n} & Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findVersionsOperation = async <TData extends TypeWithVersion<TData>>(\n args: Arguments,\n): Promise<PaginatedDocs<TData>> => {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'findVersions',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n depth,\n limit,\n overrideAccess,\n page,\n pagination = true,\n populate,\n select: incomingSelect,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = args\n\n const req = args.req!\n const { fallbackLocale, locale, payload } = req\n\n if (!hasVersionsEnabled(collectionConfig)) {\n throw new NotFound(req.t)\n }\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResults!: AccessResult\n\n if (!overrideAccess) {\n accessResults = await executeAccess(\n { slug: collectionConfig.slug, req },\n collectionConfig.access.readVersions,\n )\n }\n\n const versionFields = buildVersionCollectionFields(payload.config, collectionConfig, true)\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n versionFields,\n where: where!,\n })\n\n await validateSortQuery({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n sort,\n versionFields,\n })\n\n let fullWhere = combineQueries(where!, accessResults)\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n deletedAtPath: 'version.deletedAt',\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: versionFields, payload, where: fullWhere })\n\n const select = sanitizeSelect({\n fields: versionFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n versions: true,\n })\n\n // /////////////////////////////////////\n // Find\n // /////////////////////////////////////\n\n const usePagination = pagination && limit !== 0\n const sanitizedLimit = limit ?? (usePagination ? 10 : 0)\n const sanitizedPage = page || 1\n\n const paginatedDocs = await payload.db.findVersions<TData>({\n collection: collectionConfig.slug,\n limit: sanitizedLimit,\n locale: locale!,\n page: sanitizedPage,\n pagination,\n req,\n select,\n sort,\n where: fullWhere,\n })\n\n if (collectionConfig.upload && !overrideAccess) {\n for (const row of paginatedDocs.docs) {\n const filename = (row.version as Record<string, unknown>)?.filename\n\n await checkFileAccess({\n collection: args.collection,\n documentID: row.parent,\n filename: typeof filename === 'string' ? filename : '',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n let result: PaginatedDocs<TData> = paginatedDocs as unknown as PaginatedDocs<TData>\n result.docs = (await Promise.all(\n paginatedDocs.docs.map(async (doc) => {\n const docRef = doc\n // Fallback if not selected\n if (!docRef.version) {\n ;(docRef as any).version = {}\n }\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || docRef.version\n }\n }\n\n return docRef\n }),\n )) as TData[]\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result.docs = await Promise.all(\n result.docs.map(async (data) => {\n data.version = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: depth!,\n doc: data.version,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n findMany: true,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n populate,\n req,\n select: typeof select?.version === 'object' ? select.version : undefined,\n showHiddenFields: showHiddenFields!,\n })\n return data\n }),\n )\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks.afterRead?.length) {\n result.docs = await Promise.all(\n result.docs.map(async (doc) => {\n const docRef = doc\n\n for (const hook of collectionConfig.hooks.afterRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: doc.version,\n findMany: true,\n overrideAccess,\n query: fullWhere,\n req,\n })) || doc.version\n }\n\n return docRef\n }),\n )\n }\n\n if (collectionConfig.upload) {\n result.docs = result.docs.map((row) => ({\n ...row,\n version: markHistoricalFileURLs({\n collectionSlug: collectionConfig.slug,\n doc: row.version as Record<string, unknown>,\n req,\n versionID: row.id,\n }) as TData,\n }))\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n result.docs = result.docs.map((doc) => sanitizeInternalFields<TData>(doc))\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersions',\n overrideAccess,\n result,\n })\n\n return result\n}\n"],"names":["executeAccess","combineQueries","validateQueryPaths","validateSortQuery","sanitizeWhereQuery","NotFound","afterRead","checkFileAccess","markHistoricalFileURLs","appendNonTrashedFilter","hasVersionsEnabled","resolveSelect","sanitizeInternalFields","sanitizeSelect","buildVersionCollectionFields","buildAfterOperation","buildBeforeOperation","findVersionsOperation","args","collection","config","operation","overrideAccess","collectionConfig","depth","limit","page","pagination","populate","select","incomingSelect","showHiddenFields","sort","trash","where","req","fallbackLocale","locale","payload","t","accessResults","slug","access","readVersions","versionFields","fullWhere","deletedAtPath","enableTrash","fields","versions","usePagination","sanitizedLimit","sanitizedPage","paginatedDocs","db","findVersions","upload","row","docs","filename","version","documentID","parent","result","Promise","all","map","doc","docRef","hooks","beforeRead","length","hook","context","query","data","draft","undefined","findMany","global","collectionSlug","versionID","id"],"mappings":"AAOA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,iBAAiB,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AiB8C,KAAK,CAAC/D,SAAS,EAAEiE,QAAQ;QAC5CR,OAAOL,IAAI,GAAG,MAAMM,QAAQC,GAAG,CAC7BF,OAAOL,IAAI,CAACQ,GAAG,CAAC,OAAOC;YACrB,MAAMC,SAASD;YAEf,KAAK,MAAMK,QAAQjD,iBAAiB8C,KAAK,CAAC/D,SAAS,CAAE;gBACnD8D,OAAOR,OAAO,GACZ,AAAC,MAAMY,KAAK;oBACVrD,YAAYI;oBACZkD,SAAStC,IAAIsC,OAAO;oBACpBN,KAAKA,IAAIP,OAAO;oBAChBkB,UAAU;oBACVxD;oBACAoD,OAAO7B;oBACPV;gBACF,MAAOgC,IAAIP,OAAO;YACtB;YAEA,OAAOQ;QACT;IAEJ;IAEA,IAAI7C,iBAAiBiC,MAAM,EAAE;QAC3BO,OAAOL,IAAI,GAAGK,OAAOL,IAAI,CAACQ,GAAG,CAAC,CAACT,MAAS,CAAA;gBACtC,GAAGA,GAAG;gBACNG,SAASpD,uBAAuB;oBAC9BwE,gBAAgBzD,iBAAiBkB,IAAI;oBACrC0B,KAAKV,IAAIG,OAAO;oBAChBzB;oBACA8C,WAAWxB,IAAIyB,EAAE;gBACnB;YACF,CAAA;IACF;IAEA,wCAAwC;IACxC,iBAAiB;IACjB,wCAAwC;IACxCnB,OAAOL,IAAI,GAAGK,OAAOL,IAAI,CAACQ,GAAG,CAAC,CAACC,MAAQvD,uBAA8BuD;IAErE,wCAAwC;IACxC,8BAA8B;IAC9B,wCAAwC;IAExCJ,SAAS,MAAMhD,oBAAoB;QACjCG;QACAC,YAAYI;QACZF,WAAW;QACXC;QACAyC;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/findVersions.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PaginatedDocs } from '../../database/types.js'\nimport type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'\nimport type { TypeWithVersion } from '../../versions/types.js'\nimport type { Collection } from '../config/types.js'\nimport type { FindOptions } from './local/find.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { checkFileAccess } from '../../uploads/checkFileAccess.js'\nimport { markHistoricalFileURLs } from '../../uploads/fileVersioning/markHistoricalFileURLs.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { hasVersionsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\n\nexport type Arguments = {\n collection: Collection\n depth?: number\n limit?: number\n overrideAccess?: boolean\n page?: number\n pagination?: boolean\n populate?: PopulateType\n req?: PayloadRequest\n showHiddenFields?: boolean\n sort?: Sort\n trash?: boolean\n where?: Where\n} & Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findVersionsOperation = async <TData extends TypeWithVersion<TData>>(\n args: Arguments,\n): Promise<PaginatedDocs<TData>> => {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'findVersions',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n depth,\n limit,\n overrideAccess,\n page,\n pagination = true,\n populate,\n select: incomingSelect,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = args\n\n const req = args.req!\n const { fallbackLocale, locale, payload } = req\n\n if (!hasVersionsEnabled(collectionConfig)) {\n throw new NotFound(req.t)\n }\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResults!: AccessResult\n\n if (!overrideAccess) {\n accessResults = await executeAccess(\n { slug: collectionConfig.slug, req },\n collectionConfig.access.readVersions,\n )\n }\n\n const versionFields = buildVersionCollectionFields(payload.config, collectionConfig, true)\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n versionFields,\n where: where!,\n })\n\n await validateSortQuery({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n sort,\n versionFields,\n })\n\n let fullWhere = combineQueries(where!, accessResults)\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n deletedAtPath: 'version.deletedAt',\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: versionFields, payload, where: fullWhere })\n\n const select = sanitizeSelect({\n fields: versionFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n versions: true,\n })\n\n // /////////////////////////////////////\n // Find\n // /////////////////////////////////////\n\n const usePagination = pagination && limit !== 0\n const sanitizedLimit = limit ?? (usePagination ? 10 : 0)\n const sanitizedPage = page || 1\n\n const paginatedDocs = await payload.db.findVersions<TData>({\n collection: collectionConfig.slug,\n limit: sanitizedLimit,\n locale: locale!,\n page: sanitizedPage,\n pagination,\n req,\n select,\n sort,\n where: fullWhere,\n })\n\n if (collectionConfig.upload && !overrideAccess) {\n for (const row of paginatedDocs.docs) {\n const filename = (row.version as Record<string, unknown>)?.filename\n\n await checkFileAccess({\n collection: args.collection,\n documentID: row.parent,\n filename: typeof filename === 'string' ? filename : '',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n let result: PaginatedDocs<TData> = paginatedDocs as unknown as PaginatedDocs<TData>\n result.docs = (await Promise.all(\n paginatedDocs.docs.map(async (doc) => {\n const docRef = doc\n // Fallback if not selected\n if (!docRef.version) {\n ;(docRef as any).version = {}\n }\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || docRef.version\n }\n }\n\n return docRef\n }),\n )) as TData[]\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result.docs = await Promise.all(\n result.docs.map(async (data) => {\n data.version = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: depth!,\n doc: data.version,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n findMany: true,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n populate,\n req,\n select: typeof select?.version === 'object' ? select.version : undefined,\n showHiddenFields: showHiddenFields!,\n })\n return data\n }),\n )\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks.afterRead?.length) {\n result.docs = await Promise.all(\n result.docs.map(async (doc) => {\n const docRef = doc\n\n for (const hook of collectionConfig.hooks.afterRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: doc.version,\n findMany: true,\n overrideAccess,\n query: fullWhere,\n req,\n })) || doc.version\n }\n\n return docRef\n }),\n )\n }\n\n if (collectionConfig.upload) {\n result.docs = result.docs.map((row) => ({\n ...row,\n version: markHistoricalFileURLs({\n collectionSlug: collectionConfig.slug,\n doc: row.version,\n req,\n versionID: row.id,\n }),\n }))\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n result.docs = result.docs.map((doc) => sanitizeInternalFields<TData>(doc))\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersions',\n overrideAccess,\n result,\n })\n\n return result\n}\n"],"names":["executeAccess","combineQueries","validateQueryPaths","validateSortQuery","sanitizeWhereQuery","NotFound","afterRead","checkFileAccess","markHistoricalFileURLs","appendNonTrashedFilter","hasVersionsEnabled","resolveSelect","sanitizeInternalFields","sanitizeSelect","buildVersionCollectionFields","buildAfterOperation","buildBeforeOperation","findVersionsOperation","args","collection","config","operation","overrideAccess","collectionConfig","depth","limit","page","pagination","populate","select","incomingSelect","showHiddenFields","sort","trash","where","req","fallbackLocale","locale","payload","t","accessResults","slug","access","readVersions","versionFields","fullWhere","deletedAtPath","enableTrash","fields","versions","usePagination","sanitizedLimit","sanitizedPage","paginatedDocs","db","findVersions","upload","row","docs","filename","version","documentID","parent","result","Promise","all","map","doc","docRef","hooks","beforeRead","length","hook","context","query","data","draft","undefined","findMany","global","collectionSlug","versionID","id"],"mappings":"AAOA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,iBAAiB,QAAQ,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,sBAAsB,QAAQ,yDAAwD;AAC/F,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SAASC,mBAAmB,QAAQ,qCAAoC;AACxE,SAASC,oBAAoB,QAAQ,sCAAqC;AAiB1E,OAAO,MAAMC,wBAAwB,OACnCC;IAEA,wCAAwC;IACxC,+BAA+B;IAC/B,wCAAwC;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T,MAAS,CAAA;gBACtC,GAAGA,GAAG;gBACNG,SAASpD,uBAAuB;oBAC9BwE,gBAAgBzD,iBAAiBkB,IAAI;oBACrC0B,KAAKV,IAAIG,OAAO;oBAChBzB;oBACA8C,WAAWxB,IAAIyB,EAAE;gBACnB;YACF,CAAA;IACF;IAEA,wCAAwC;IACxC,iBAAiB;IACjB,wCAAwC;IACxCnB,OAAOL,IAAI,GAAGK,OAAOL,IAAI,CAACQ,GAAG,CAAC,CAACC,MAAQvD,uBAA8BuD;IAErE,wCAAwC;IACxC,8BAA8B;IAC9B,wCAAwC;IAExCJ,SAAS,MAAMhD,oBAAoB;QACjCG;QACAC,YAAYI;QACZF,WAAW;QACXC;QACAyC;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/operations/local/findDistinct.ts"],"sourcesContent":["import type {\n CollectionSlug,\n DataFromCollectionSlug,\n PaginatedDistinctDocs,\n Payload,\n PayloadRequest,\n PopulateType,\n RequestContext,\n Sort,\n TypedLocale,\n User,\n Where,\n} from '../../../index.js'\nimport type { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type { CreatePayloadRequestArgs } from '../../../utilities/createPayloadRequest.js'\n\nimport { APIError, createPayloadRequest } from '../../../index.js'\nimport { findDistinctOperation } from '../findDistinct.js'\n\nexport type Options<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug>,\n> = {\n /**\n * the Collection slug to operate against.\n */\n collection: TSlug\n /**\n * [Context](https://payloadcms.com/docs/hooks/context), which will then be passed to `context` and `req.context`,\n * which can be read by hooks. Useful if you want to pass additional information to the hooks which\n * shouldn't be necessarily part of the document, for example a `triggerBeforeChange` option which can be read by the BeforeChange hook\n * to determine if it should run or not.\n */\n context?: RequestContext\n /**\n * [Control auto-population](https://payloadcms.com/docs/queries/depth) of nested relationship and upload fields.\n */\n depth?: number\n /**\n * When set to `true`, errors will not be thrown.\n */\n disableErrors?: boolean\n /**\n * The field to get distinct values for\n */\n field: ({} & string) | TField\n /**\n * The maximum distinct field values to be returned.\n * By default the operation returns all the values.\n */\n limit?: number\n /**\n * Specify [locale](https://payloadcms.com/docs/configuration/localization) for any returned documents.\n */\n locale?: 'all' | TypedLocale\n /**\n * Get a specific page number (if limit is specified)\n * @default 1\n */\n page?: number\n /**\n * Specify [populate](https://payloadcms.com/docs/queries/select#populate) to control which fields to include to the result from populated documents.\n */\n populate?: PopulateType\n /**\n * The `PayloadRequest` object. You can pass it to thread the current [transaction](https://payloadcms.com/docs/database/transactions), user and locale to the operation.\n * Recommended to pass when using the Local API from hooks, as usually you want to execute the operation within the current transaction.\n */\n req?: Partial<PayloadRequest>\n /**\n * Opt-in to receiving hidden fields. By default, they are hidden from returned documents in accordance to your config.\n * @default false\n */\n showHiddenFields?: boolean\n /**\n * Sort the documents, can be a string or an array of strings\n * @example '-createdAt' // Sort DESC by createdAt\n * @example ['group', '-createdAt'] // sort by 2 fields, ASC group and DESC createdAt\n */\n sort?: Sort\n /**\n * When set to `true`, the query will include both normal and trashed documents.\n * To query only trashed documents, pass `trash: true` and combine with a `where` clause filtering by `deletedAt`.\n * By default (`false`), the query will only include normal documents and exclude those with a `deletedAt` field.\n *\n * This argument has no effect unless `trash` is enabled on the collection.\n * @default false\n */\n trash?: boolean\n /**\n * If you set `overrideAccess` to `false`, you can pass a user to use against the access control checks.\n */\n user?: null | User\n /**\n * A filter [query](https://payloadcms.com/docs/queries/overview)\n */\n where?: Where\n} & Pick<SharedLocalAPIOptions, 'overrideAccess'>\n\nexport async function findDistinct<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug> & string,\n>(\n payload: Payload,\n options: Options<TSlug, TField>,\n): Promise<PaginatedDistinctDocs<Record<TField, DataFromCollectionSlug<TSlug>[TField]>>> {\n const {\n collection: collectionSlug,\n depth = 0,\n disableErrors,\n field,\n limit,\n overrideAccess = false,\n page,\n populate,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = options\n const collection = payload.collections[collectionSlug]\n\n if (!collection) {\n throw new APIError(\n `The collection with slug ${String(collectionSlug)} can't be found. Find Operation.`,\n )\n }\n\n return findDistinctOperation({\n collection,\n depth,\n disableErrors,\n field,\n limit,\n overrideAccess,\n page,\n populate,\n req: await createPayloadRequest({\n ...(options as Omit<CreatePayloadRequestArgs, 'payload'>),\n payload,\n }),\n showHiddenFields,\n sort,\n trash,\n where,\n })
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/local/findDistinct.ts"],"sourcesContent":["import type {\n CollectionSlug,\n DataFromCollectionSlug,\n PaginatedDistinctDocs,\n Payload,\n PayloadRequest,\n PopulateType,\n RequestContext,\n Sort,\n TypedLocale,\n User,\n Where,\n} from '../../../index.js'\nimport type { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type { CreatePayloadRequestArgs } from '../../../utilities/createPayloadRequest.js'\n\nimport { APIError, createPayloadRequest } from '../../../index.js'\nimport { findDistinctOperation } from '../findDistinct.js'\n\nexport type Options<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug>,\n> = {\n /**\n * the Collection slug to operate against.\n */\n collection: TSlug\n /**\n * [Context](https://payloadcms.com/docs/hooks/context), which will then be passed to `context` and `req.context`,\n * which can be read by hooks. Useful if you want to pass additional information to the hooks which\n * shouldn't be necessarily part of the document, for example a `triggerBeforeChange` option which can be read by the BeforeChange hook\n * to determine if it should run or not.\n */\n context?: RequestContext\n /**\n * [Control auto-population](https://payloadcms.com/docs/queries/depth) of nested relationship and upload fields.\n */\n depth?: number\n /**\n * When set to `true`, errors will not be thrown.\n */\n disableErrors?: boolean\n /**\n * The field to get distinct values for\n */\n field: ({} & string) | TField\n /**\n * The maximum distinct field values to be returned.\n * By default the operation returns all the values.\n */\n limit?: number\n /**\n * Specify [locale](https://payloadcms.com/docs/configuration/localization) for any returned documents.\n */\n locale?: 'all' | TypedLocale\n /**\n * Get a specific page number (if limit is specified)\n * @default 1\n */\n page?: number\n /**\n * Specify [populate](https://payloadcms.com/docs/queries/select#populate) to control which fields to include to the result from populated documents.\n */\n populate?: PopulateType\n /**\n * The `PayloadRequest` object. You can pass it to thread the current [transaction](https://payloadcms.com/docs/database/transactions), user and locale to the operation.\n * Recommended to pass when using the Local API from hooks, as usually you want to execute the operation within the current transaction.\n */\n req?: Partial<PayloadRequest>\n /**\n * Opt-in to receiving hidden fields. By default, they are hidden from returned documents in accordance to your config.\n * @default false\n */\n showHiddenFields?: boolean\n /**\n * Sort the documents, can be a string or an array of strings\n * @example '-createdAt' // Sort DESC by createdAt\n * @example ['group', '-createdAt'] // sort by 2 fields, ASC group and DESC createdAt\n */\n sort?: Sort\n /**\n * When set to `true`, the query will include both normal and trashed documents.\n * To query only trashed documents, pass `trash: true` and combine with a `where` clause filtering by `deletedAt`.\n * By default (`false`), the query will only include normal documents and exclude those with a `deletedAt` field.\n *\n * This argument has no effect unless `trash` is enabled on the collection.\n * @default false\n */\n trash?: boolean\n /**\n * If you set `overrideAccess` to `false`, you can pass a user to use against the access control checks.\n */\n user?: null | User\n /**\n * A filter [query](https://payloadcms.com/docs/queries/overview)\n */\n where?: Where\n} & Pick<SharedLocalAPIOptions, 'overrideAccess'>\n\nexport async function findDistinct<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug> & string,\n>(\n payload: Payload,\n options: Options<TSlug, TField>,\n): Promise<PaginatedDistinctDocs<Record<TField, DataFromCollectionSlug<TSlug>[TField]>>> {\n const {\n collection: collectionSlug,\n depth = 0,\n disableErrors,\n field,\n limit,\n overrideAccess = false,\n page,\n populate,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = options\n const collection = payload.collections[collectionSlug]\n\n if (!collection) {\n throw new APIError(\n `The collection with slug ${String(collectionSlug)} can't be found. Find Operation.`,\n )\n }\n\n return findDistinctOperation({\n collection,\n depth,\n disableErrors,\n field,\n limit,\n overrideAccess,\n page,\n populate,\n req: await createPayloadRequest({\n ...(options as Omit<CreatePayloadRequestArgs, 'payload'>),\n payload,\n }),\n showHiddenFields,\n sort,\n trash,\n where,\n })\n}\n"],"names":["APIError","createPayloadRequest","findDistinctOperation","findDistinct","payload","options","collection","collectionSlug","depth","disableErrors","field","limit","overrideAccess","page","populate","showHiddenFields","sort","trash","where","collections","String","req"],"mappings":"AAgBA,SAASA,QAAQ,EAAEC,oBAAoB,QAAQ,oBAAmB;AAClE,SAASC,qBAAqB,QAAQ,qBAAoB;AAkF1D,OAAO,eAAeC,aAIpBC,OAAgB,EAChBC,OAA+B;IAE/B,MAAM,EACJC,YAAYC,cAAc,EAC1BC,QAAQ,CAAC,EACTC,aAAa,EACbC,KAAK,EACLC,KAAK,EACLC,iBAAiB,KAAK,EACtBC,IAAI,EACJC,QAAQ,EACRC,gBAAgB,EAChBC,IAAI,EACJC,QAAQ,KAAK,EACbC,KAAK,EACN,GAAGb;IACJ,MAAMC,aAAaF,QAAQe,WAAW,CAACZ,eAAe;IAEtD,IAAI,CAACD,YAAY;QACf,MAAM,IAAIN,SACR,CAAC,yBAAyB,EAAEoB,OAAOb,gBAAgB,gCAAgC,CAAC;IAExF;IAEA,OAAOL,sBAAsB;QAC3BI;QACAE;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAO,KAAK,MAAMpB,qBAAqB;YAC9B,GAAII,OAAO;YACXD;QACF;QACAW;QACAC;QACAC;QACAC;IACF;AACF"}
|
|
@@ -229,7 +229,7 @@ import { updateDocument } from './utilities/update.js';
|
|
|
229
229
|
autosave: false,
|
|
230
230
|
collectionConfig: collection.config,
|
|
231
231
|
config: req.payload.config,
|
|
232
|
-
data
|
|
232
|
+
data,
|
|
233
233
|
depth: args.depth ?? 0,
|
|
234
234
|
docWithLocales: stored,
|
|
235
235
|
draftArg: draft,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/renameFile.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { Collection } from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { hasWhereAccessResult } from '../../auth/types.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { APIError, Forbidden, NotFound } from '../../errors/index.js'\nimport { replaceStoredFileReferences } from '../../uploads/fileVersioning/archive.js'\nimport {\n removeUnreferencedStagedObjects,\n scheduleUnreferencedFileCleanup,\n} from '../../uploads/fileVersioning/cleanup.js'\nimport {\n abortFileOperationScope,\n beginFileOperationScope,\n completeFileOperationScope,\n runFileOperationPlan,\n} from '../../uploads/fileVersioning/fileOperationManager.js'\nimport { copyLocalFile } from '../../uploads/fileVersioning/localStorage.js'\nimport { getOriginalFilename, normalizeStorageKey } from '../../uploads/fileVersioning/naming.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n withLegacyCloudUploadFileData,\n} from '../../uploads/fileVersioning/storedFiles.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js'\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\nimport { updateDocument } from './utilities/update.js'\n\nexport type RenameFileArguments = {\n collection: Collection\n depth?: number\n disableTransaction?: boolean\n draft?: boolean\n filename: string\n id: number | string\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\n/** Renames the current managed file set without changing its bytes. */\nexport const renameFileOperation = async (\n incomingArgs: RenameFileArguments,\n): Promise<JsonObject> => {\n let args = { ...incomingArgs, data: { filename: incomingArgs.filename } }\n const { req } = args\n beginFileOperationScope({ req })\n\n try {\n const shouldCommit = !args.disableTransaction && (await initTransaction(req))\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'updateByID',\n overrideAccess: args.overrideAccess ?? false,\n })\n\n const { id, collection, draft = false, overrideAccess = false } = args\n const { filename } = args.data\n if (!collection.config.upload) {\n throw new APIError('This collection does not support file rename.', 400)\n }\n\n const access = overrideAccess\n ? true\n : await executeAccess(\n { id, slug: collection.config.slug, data: { filename }, req },\n collection.config.access.update,\n )\n const where = combineQueries({ id: { equals: id } }, access)\n const query = { collection: collection.config.slug, locale: 'all' as const, req, where }\n const current = draft\n ? await getLatestCollectionVersion({\n id,\n config: collection.config,\n payload: req.payload,\n query,\n req,\n })\n : await req.payload.db.findOne(query)\n\n if (!current) {\n throw hasWhereAccessResult(access) ? new Forbidden(req.t) : new NotFound(req.t)\n }\n const stored = await withLegacyCloudUploadFileData({\n collection: collection.config,\n doc: current as JsonObject,\n req,\n })\n const operations = collection.config.upload.fileOperations\n const storedFiles = collectStoredFiles({ collection: collection.config, doc: stored, req })\n const oldOriginal = (stored.original as { filename?: string } | undefined)?.filename\n const oldFilename = oldOriginal ?? (stored.filename as string | undefined)\n\n if (!oldFilename || !storedFiles.length) {\n throw new APIError('This upload has no managed files to rename.', 400)\n }\n\n const { newStem } = validateRename({ filename, oldFilename })\n const originalStem = path.posix.parse(oldFilename).name\n const originalMarkerIndex = originalStem.lastIndexOf('-original')\n const oldStem =\n originalMarkerIndex > 0\n ? originalStem.slice(0, originalMarkerIndex)\n : path.posix.parse(stored.filename as string).name\n if (filename === `${oldStem}${path.posix.extname(oldFilename)}`) {\n throw new APIError('The upload already has this filename.', 400)\n }\n\n const originalFilename = getOriginalFilename({ filename })\n const plannedKeys = new Set(\n storedFiles\n .filter(({ roles }) => roles.some(({ type }) => type === 'original'))\n .map(({ key }) =>\n getStoredFileIdentity({\n key: path.posix.join(path.posix.dirname(key), originalFilename),\n }),\n ),\n )\n const replacements = new Map<string, string>()\n for (const file of storedFiles) {\n const previousFilename = path.posix.basename(file.key)\n const hasOriginalRole = file.roles.some(({ type }) => type === 'original')\n const suffix = previousFilename.startsWith(oldStem)\n ? previousFilename.slice(oldStem.length)\n : `-${previousFilename}`\n let nextFilename = hasOriginalRole ? originalFilename : `${newStem}${suffix}`\n const directory = path.posix.dirname(file.key)\n let nextKey = path.posix.join(directory, nextFilename)\n let nextIdentity = getStoredFileIdentity({\n key: nextKey,\n })\n const extension = path.posix.extname(nextFilename)\n const stem = nextFilename.slice(0, -extension.length || undefined)\n let collisionNumber = 1\n while (!hasOriginalRole && plannedKeys.has(nextIdentity)) {\n nextFilename = `${stem}-${collisionNumber}${extension}`\n nextKey = path.posix.join(directory, nextFilename)\n nextIdentity = getStoredFileIdentity({\n key: nextKey,\n })\n collisionNumber++\n }\n plannedKeys.add(nextIdentity)\n const key = normalizeStorageKey({ key: nextKey })\n replacements.set(getStoredFileIdentity(file), key)\n }\n\n const renamed = replaceStoredFileReferences({\n files: storedFiles,\n replacements,\n version: stored,\n })\n if (!renamed) {\n throw new APIError('The upload has no files to rename.', 400)\n }\n\n const staticDir = collection.config.upload.staticDir\n const result = await runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection: collection.config, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n for (const file of storedFiles) {\n const to = replacements.get(getStoredFileIdentity(file))!\n if (!operations && staticDir) {\n try {\n await copyLocalFile({ from: file.key, staticDir, to })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new APIError(`A file named ${path.posix.basename(to)} already exists.`, 409)\n }\n throw err\n }\n trackStagedObject({\n key: to,\n remove: () => fs.rm(path.join(staticDir, to), { force: true }),\n })\n } else if (operations?.copy) {\n // Keep source files readable until the document update and its transaction succeed.\n try {\n await operations.copy({ from: file.key, req, to, trackStagedObject })\n } catch (err) {\n if (isStorageCollision({ err })) {\n throw new APIError(`A file named ${path.posix.basename(to)} already exists.`, 409)\n }\n throw err\n }\n } else {\n throw new APIError('No safe copy operation is available for this upload.', 400)\n }\n }\n },\n write: async () => {\n if (collection.config.versions) {\n const previousVersions = await req.payload.db.findVersions({\n collection: collection.config.slug,\n limit: 1,\n req,\n where: { parent: { equals: id } },\n })\n\n if (!previousVersions.docs.length) {\n await saveVersion({\n id,\n collection: collection.config,\n docWithLocales: stored,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n }\n }\n\n const data = {\n filename: renamed.filename,\n original: renamed.original,\n url: renamed.url,\n variants: renamed.variants,\n ...(draft ? { _status: 'draft' } : {}),\n }\n const updated = await updateDocument({\n id,\n autosave: false,\n collectionConfig: collection.config,\n config: req.payload.config,\n data: data as never,\n depth: args.depth ?? 0,\n docWithLocales: stored as never,\n draftArg: draft,\n fallbackLocale: req.fallbackLocale!,\n filesToUpload: [],\n locale: req.locale!,\n overrideAccess,\n overrideLock: false,\n payload: req.payload,\n req,\n select: undefined!,\n shouldManageLocalFiles: false,\n showHiddenFields: false,\n })\n\n await scheduleUnreferencedFileCleanup({\n candidates: storedFiles,\n collection: collection.config,\n req,\n })\n return updated as JsonObject\n },\n })\n\n const finalResult = await buildAfterOperation({\n args,\n collection: collection.config,\n operation: 'updateByID',\n overrideAccess,\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n await completeFileOperationScope({ req })\n return finalResult as JsonObject\n } catch (err) {\n await killTransaction(req)\n await abortFileOperationScope({ req })\n throw err\n }\n}\n\nconst validateRename = ({ filename, oldFilename }: { filename: string; oldFilename: string }) => {\n if (\n typeof filename !== 'string' ||\n !filename ||\n filename === '.' ||\n filename === '..' ||\n filename.includes('/') ||\n filename.includes('\\\\') ||\n filename.includes('\\0')\n ) {\n throw new APIError('Invalid filename.', 400)\n }\n\n const oldExtension = path.posix.extname(oldFilename)\n const newExtension = path.posix.extname(filename)\n if (oldExtension.toLowerCase() !== newExtension.toLowerCase()) {\n throw new APIError('The new filename must keep the original file extension.', 400)\n }\n\n return {\n newStem: filename.slice(0, -newExtension.length || undefined),\n }\n}\n\nconst isStorageCollision = ({ err }: { err: unknown }): boolean => {\n if (!err || typeof err !== 'object') {\n return false\n }\n\n const { name, code, message, statusCode } = err as {\n code?: number | string\n message?: string\n name?: string\n statusCode?: number\n }\n\n return (\n code === 'EEXIST' ||\n code === 'PreconditionFailed' ||\n code === 412 ||\n name === 'PreconditionFailed' ||\n statusCode === 409 ||\n statusCode === 412 ||\n Boolean(message?.includes('Storage destination already exists'))\n )\n}\n"],"names":["fs","path","executeAccess","hasWhereAccessResult","combineQueries","APIError","Forbidden","NotFound","replaceStoredFileReferences","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","abortFileOperationScope","beginFileOperationScope","completeFileOperationScope","runFileOperationPlan","copyLocalFile","getOriginalFilename","normalizeStorageKey","collectStoredFiles","getStoredFileIdentity","withLegacyCloudUploadFileData","commitTransaction","initTransaction","killTransaction","getLatestCollectionVersion","saveVersion","buildAfterOperation","buildBeforeOperation","updateDocument","renameFileOperation","incomingArgs","args","data","filename","req","shouldCommit","disableTransaction","collection","config","operation","overrideAccess","id","draft","upload","access","slug","update","where","equals","query","locale","current","payload","db","findOne","t","stored","doc","operations","fileOperations","storedFiles","oldOriginal","original","oldFilename","length","newStem","validateRename","originalStem","posix","parse","name","originalMarkerIndex","lastIndexOf","oldStem","slice","extname","originalFilename","plannedKeys","Set","filter","roles","some","type","map","key","join","dirname","replacements","Map","file","previousFilename","basename","hasOriginalRole","suffix","startsWith","nextFilename","directory","nextKey","nextIdentity","extension","stem","undefined","collisionNumber","has","add","set","renamed","files","version","staticDir","result","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","to","get","from","err","code","remove","rm","force","copy","isStorageCollision","write","versions","previousVersions","findVersions","limit","parent","docs","docWithLocales","url","variants","_status","updated","autosave","collectionConfig","depth","draftArg","fallbackLocale","filesToUpload","overrideLock","select","shouldManageLocalFiles","showHiddenFields","candidates","finalResult","includes","oldExtension","newExtension","toLowerCase","message","statusCode","Boolean"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAK5B,SAASC,aAAa,QAAQ,8BAA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,EAAC;AAED,MAAMpD,iBAAiB,CAAC,EAAEjC,QAAQ,EAAE8B,WAAW,EAA6C;IAC1F,IACE,OAAO9B,aAAa,YACpB,CAACA,YACDA,aAAa,OACbA,aAAa,QACbA,SAASoH,QAAQ,CAAC,QAClBpH,SAASoH,QAAQ,CAAC,SAClBpH,SAASoH,QAAQ,CAAC,OAClB;QACA,MAAM,IAAIhJ,SAAS,qBAAqB;IAC1C;IAEA,MAAMiJ,eAAerJ,KAAKmE,KAAK,CAACO,OAAO,CAACZ;IACxC,MAAMwF,eAAetJ,KAAKmE,KAAK,CAACO,OAAO,CAAC1C;IACxC,IAAIqH,aAAaE,WAAW,OAAOD,aAAaC,WAAW,IAAI;QAC7D,MAAM,IAAInJ,SAAS,2DAA2D;IAChF;IAEA,OAAO;QACL4D,SAAShC,SAASyC,KAAK,CAAC,GAAG,CAAC6E,aAAavF,MAAM,IAAIqC;IACrD;AACF;AAEA,MAAMuB,qBAAqB,CAAC,EAAEN,GAAG,EAAoB;IACnD,IAAI,CAACA,OAAO,OAAOA,QAAQ,UAAU;QACnC,OAAO;IACT;IAEA,MAAM,EAAEhD,IAAI,EAAEiD,IAAI,EAAEkC,OAAO,EAAEC,UAAU,EAAE,GAAGpC;IAO5C,OACEC,SAAS,YACTA,SAAS,wBACTA,SAAS,OACTjD,SAAS,wBACToF,eAAe,OACfA,eAAe,OACfC,QAAQF,SAASJ,SAAS;AAE9B"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/renameFile.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { Collection } from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { hasWhereAccessResult } from '../../auth/types.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { APIError, Forbidden, NotFound } from '../../errors/index.js'\nimport { replaceStoredFileReferences } from '../../uploads/fileVersioning/archive.js'\nimport {\n removeUnreferencedStagedObjects,\n scheduleUnreferencedFileCleanup,\n} from '../../uploads/fileVersioning/cleanup.js'\nimport {\n abortFileOperationScope,\n beginFileOperationScope,\n completeFileOperationScope,\n runFileOperationPlan,\n} from '../../uploads/fileVersioning/fileOperationManager.js'\nimport { copyLocalFile } from '../../uploads/fileVersioning/localStorage.js'\nimport { getOriginalFilename, normalizeStorageKey } from '../../uploads/fileVersioning/naming.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n withLegacyCloudUploadFileData,\n} from '../../uploads/fileVersioning/storedFiles.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js'\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\nimport { updateDocument } from './utilities/update.js'\n\nexport type RenameFileArguments = {\n collection: Collection\n depth?: number\n disableTransaction?: boolean\n draft?: boolean\n filename: string\n id: number | string\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\n/** Renames the current managed file set without changing its bytes. */\nexport const renameFileOperation = async (\n incomingArgs: RenameFileArguments,\n): Promise<JsonObject> => {\n let args = { ...incomingArgs, data: { filename: incomingArgs.filename } }\n const { req } = args\n beginFileOperationScope({ req })\n\n try {\n const shouldCommit = !args.disableTransaction && (await initTransaction(req))\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'updateByID',\n overrideAccess: args.overrideAccess ?? false,\n })\n\n const { id, collection, draft = false, overrideAccess = false } = args\n const { filename } = args.data\n if (!collection.config.upload) {\n throw new APIError('This collection does not support file rename.', 400)\n }\n\n const access = overrideAccess\n ? true\n : await executeAccess(\n { id, slug: collection.config.slug, data: { filename }, req },\n collection.config.access.update,\n )\n const where = combineQueries({ id: { equals: id } }, access)\n const query = { collection: collection.config.slug, locale: 'all' as const, req, where }\n const current = draft\n ? await getLatestCollectionVersion({\n id,\n config: collection.config,\n payload: req.payload,\n query,\n req,\n })\n : await req.payload.db.findOne(query)\n\n if (!current) {\n throw hasWhereAccessResult(access) ? new Forbidden(req.t) : new NotFound(req.t)\n }\n const stored = await withLegacyCloudUploadFileData({\n collection: collection.config,\n doc: current as JsonObject,\n req,\n })\n const operations = collection.config.upload.fileOperations\n const storedFiles = collectStoredFiles({ collection: collection.config, doc: stored, req })\n const oldOriginal = (stored.original as { filename?: string } | undefined)?.filename\n const oldFilename = oldOriginal ?? (stored.filename as string | undefined)\n\n if (!oldFilename || !storedFiles.length) {\n throw new APIError('This upload has no managed files to rename.', 400)\n }\n\n const { newStem } = validateRename({ filename, oldFilename })\n const originalStem = path.posix.parse(oldFilename).name\n const originalMarkerIndex = originalStem.lastIndexOf('-original')\n const oldStem =\n originalMarkerIndex > 0\n ? originalStem.slice(0, originalMarkerIndex)\n : path.posix.parse(stored.filename as string).name\n if (filename === `${oldStem}${path.posix.extname(oldFilename)}`) {\n throw new APIError('The upload already has this filename.', 400)\n }\n\n const originalFilename = getOriginalFilename({ filename })\n const plannedKeys = new Set(\n storedFiles\n .filter(({ roles }) => roles.some(({ type }) => type === 'original'))\n .map(({ key }) =>\n getStoredFileIdentity({\n key: path.posix.join(path.posix.dirname(key), originalFilename),\n }),\n ),\n )\n const replacements = new Map<string, string>()\n for (const file of storedFiles) {\n const previousFilename = path.posix.basename(file.key)\n const hasOriginalRole = file.roles.some(({ type }) => type === 'original')\n const suffix = previousFilename.startsWith(oldStem)\n ? previousFilename.slice(oldStem.length)\n : `-${previousFilename}`\n let nextFilename = hasOriginalRole ? originalFilename : `${newStem}${suffix}`\n const directory = path.posix.dirname(file.key)\n let nextKey = path.posix.join(directory, nextFilename)\n let nextIdentity = getStoredFileIdentity({\n key: nextKey,\n })\n const extension = path.posix.extname(nextFilename)\n const stem = nextFilename.slice(0, -extension.length || undefined)\n let collisionNumber = 1\n while (!hasOriginalRole && plannedKeys.has(nextIdentity)) {\n nextFilename = `${stem}-${collisionNumber}${extension}`\n nextKey = path.posix.join(directory, nextFilename)\n nextIdentity = getStoredFileIdentity({\n key: nextKey,\n })\n collisionNumber++\n }\n plannedKeys.add(nextIdentity)\n const key = normalizeStorageKey({ key: nextKey })\n replacements.set(getStoredFileIdentity(file), key)\n }\n\n const renamed = replaceStoredFileReferences({\n files: storedFiles,\n replacements,\n version: stored,\n })\n if (!renamed) {\n throw new APIError('The upload has no files to rename.', 400)\n }\n\n const staticDir = collection.config.upload.staticDir\n const result = await runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection: collection.config, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n for (const file of storedFiles) {\n const to = replacements.get(getStoredFileIdentity(file))!\n if (!operations && staticDir) {\n try {\n await copyLocalFile({ from: file.key, staticDir, to })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new APIError(`A file named ${path.posix.basename(to)} already exists.`, 409)\n }\n throw err\n }\n trackStagedObject({\n key: to,\n remove: () => fs.rm(path.join(staticDir, to), { force: true }),\n })\n } else if (operations?.copy) {\n // Keep source files readable until the document update and its transaction succeed.\n try {\n await operations.copy({ from: file.key, req, to, trackStagedObject })\n } catch (err) {\n if (isStorageCollision({ err })) {\n throw new APIError(`A file named ${path.posix.basename(to)} already exists.`, 409)\n }\n throw err\n }\n } else {\n throw new APIError('No safe copy operation is available for this upload.', 400)\n }\n }\n },\n write: async () => {\n if (collection.config.versions) {\n const previousVersions = await req.payload.db.findVersions({\n collection: collection.config.slug,\n limit: 1,\n req,\n where: { parent: { equals: id } },\n })\n\n if (!previousVersions.docs.length) {\n await saveVersion({\n id,\n collection: collection.config,\n docWithLocales: stored,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n }\n }\n\n const data = {\n filename: renamed.filename,\n original: renamed.original,\n url: renamed.url,\n variants: renamed.variants,\n ...(draft ? { _status: 'draft' } : {}),\n }\n const updated = await updateDocument({\n id,\n autosave: false,\n collectionConfig: collection.config,\n config: req.payload.config,\n data,\n depth: args.depth ?? 0,\n docWithLocales: stored as never,\n draftArg: draft,\n fallbackLocale: req.fallbackLocale!,\n filesToUpload: [],\n locale: req.locale!,\n overrideAccess,\n overrideLock: false,\n payload: req.payload,\n req,\n select: undefined!,\n shouldManageLocalFiles: false,\n showHiddenFields: false,\n })\n\n await scheduleUnreferencedFileCleanup({\n candidates: storedFiles,\n collection: collection.config,\n req,\n })\n return updated\n },\n })\n\n const finalResult = await buildAfterOperation({\n args,\n collection: collection.config,\n operation: 'updateByID',\n overrideAccess,\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n await completeFileOperationScope({ req })\n return finalResult as JsonObject\n } catch (err) {\n await killTransaction(req)\n await abortFileOperationScope({ req })\n throw err\n }\n}\n\nconst validateRename = ({ filename, oldFilename }: { filename: string; oldFilename: string }) => {\n if (\n typeof filename !== 'string' ||\n !filename ||\n filename === '.' ||\n filename === '..' ||\n filename.includes('/') ||\n filename.includes('\\\\') ||\n filename.includes('\\0')\n ) {\n throw new APIError('Invalid filename.', 400)\n }\n\n const oldExtension = path.posix.extname(oldFilename)\n const newExtension = path.posix.extname(filename)\n if (oldExtension.toLowerCase() !== newExtension.toLowerCase()) {\n throw new APIError('The new filename must keep the original file extension.', 400)\n }\n\n return {\n newStem: filename.slice(0, -newExtension.length || undefined),\n }\n}\n\nconst isStorageCollision = ({ err }: { err: unknown }): boolean => {\n if (!err || typeof err !== 'object') {\n return false\n }\n\n const { name, code, message, statusCode } = err as {\n code?: number | string\n message?: string\n name?: string\n statusCode?: number\n }\n\n return (\n code === 'EEXIST' ||\n code === 'PreconditionFailed' ||\n code === 412 ||\n name === 'PreconditionFailed' ||\n statusCode === 409 ||\n statusCode === 412 ||\n Boolean(message?.includes('Storage destination already exists'))\n )\n}\n"],"names":["fs","path","executeAccess","hasWhereAccessResult","combineQueries","APIError","Forbidden","NotFound","replaceStoredFileReferences","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","abortFileOperationScope","beginFileOperationScope","completeFileOperationScope","runFileOperationPlan","copyLocalFile","getOriginalFilename","normalizeStorageKey","collectStoredFiles","getStoredFileIdentity","withLegacyCloudUploadFileData","commitTransaction","initTransaction","killTransaction","getLatestCollectionVersion","saveVersion","buildAfterOperation","buildBeforeOperation","updateDocument","renameFileOperation","incomingArgs","args","data","filename","req","shouldCommit","disableTransaction","collection","config","operation","overrideAccess","id","draft","upload","access","slug","update","where","equals","query","locale","current","payload","db","findOne","t","stored","doc","operations","fileOperations","storedFiles","oldOriginal","original","oldFilename","length","newStem","validateRename","originalStem","posix","parse","name","originalMarkerIndex","lastIndexOf","oldStem","slice","extname","originalFilename","plannedKeys","Set","filter","roles","some","type","map","key","join","dirname","replacements","Map","file","previousFilename","basename","hasOriginalRole","suffix","startsWith","nextFilename","directory","nextKey","nextIdentity","extension","stem","undefined","collisionNumber","has","add","set","renamed","files","version","staticDir","result","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","to","get","from","err","code","remove","rm","force","copy","isStorageCollision","write","versions","previousVersions","findVersions","limit","parent","docs","docWithLocales","url","variants","_status","updated","autosave","collectionConfig","depth","draftArg","fallbackLocale","filesToUpload","overrideLock","select","shouldManageLocalFiles","showHiddenFields","candidates","finalResult","includes","oldExtension","newExtension","toLowerCase","message","statusCode","Boolean"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAK5B,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,sBAAqB;AAC1D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,QAAQ,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AACrE,SAASC,2BAA2B,QAAQ,0CAAyC;AACrF,SACEC,+BAA+B,EAC/BC,+BAA+B,QAC1B,0CAAyC;AAChD,SACEC,uBAAuB,EACv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;IAC1C;IAEA,MAAMiJ,eAAerJ,KAAKmE,KAAK,CAACO,OAAO,CAACZ;IACxC,MAAMwF,eAAetJ,KAAKmE,KAAK,CAACO,OAAO,CAAC1C;IACxC,IAAIqH,aAAaE,WAAW,OAAOD,aAAaC,WAAW,IAAI;QAC7D,MAAM,IAAInJ,SAAS,2DAA2D;IAChF;IAEA,OAAO;QACL4D,SAAShC,SAASyC,KAAK,CAAC,GAAG,CAAC6E,aAAavF,MAAM,IAAIqC;IACrD;AACF;AAEA,MAAMuB,qBAAqB,CAAC,EAAEN,GAAG,EAAoB;IACnD,IAAI,CAACA,OAAO,OAAOA,QAAQ,UAAU;QACnC,OAAO;IACT;IAEA,MAAM,EAAEhD,IAAI,EAAEiD,IAAI,EAAEkC,OAAO,EAAEC,UAAU,EAAE,GAAGpC;IAO5C,OACEC,SAAS,YACTA,SAAS,wBACTA,SAAS,OACTjD,SAAS,wBACToF,eAAe,OACfA,eAAe,OACfC,QAAQF,SAASJ,SAAS;AAE9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { UserSession } from '../../../auth/types.js'\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 { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { removeExpiredSessions } from '../../../auth/sessions.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { ValidationError } from '../../../errors/index.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 { runLocalFileUpdate } from '../../../uploads/fileVersioning/archive.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport { getTopLevelFieldNames } from '../../../utilities/getTopLevelFieldNames.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { resolvePublishAllLocales } from '../../../utilities/resolvePublishAllLocales.js'\nimport {\n buildAllLocalesPublicationHookDoc,\n getAllLocalesPublicationStatus,\n hasAuthorizedAllLocalesPublicationStatus,\n validateAllLocalesPublicationFlags,\n} from '../../../versions/allLocalesPublicationStatus.js'\nimport { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js'\nimport { validateLocalWithLocaleKeyedData } from '../local/validate.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 overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n select: SelectType\n shouldManageLocalFiles: boolean\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n} & Pick<Required<SharedLocalAPIOptions>, 'overrideAccess'>\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 shouldManageLocalFiles,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const nextFileData =\n collectionConfig.upload && shouldManageLocalFiles && !collectionConfig.upload.fileOperations\n ? deepCopyObjectSimple(data)\n : undefined\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: publishAllLocalesArg,\n unpublishAllLocales: unpublishAllLocalesArg,\n })\n\n const publishAllLocales = resolvePublishAllLocales({\n draft: draftArg,\n hasLocalizeStatusEnabled: hasLocalizeStatusEnabled(collectionConfig),\n locale,\n publishAllLocalesArg,\n })\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const allLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(config.localization && hasLocalizeStatusEnabled(collectionConfig)),\n publishAllLocales,\n unpublishAllLocales,\n })\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n if (allLocalesPublicationStatus || isSavingDraft) {\n data._status = allLocalesPublicationStatus ?? '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 const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n const shouldLimitValidationToSubmittedFields =\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n unpublishAllLocales\n const submittedTopLevelFieldNames = shouldLimitValidationToSubmittedFields\n ? getTopLevelFieldNames(data)\n : undefined\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 // 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 during the update 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 const hasManagedLocalUpload =\n filesToUpload.length > 0 &&\n Boolean(data.original) &&\n !collectionConfig.upload.disableLocalStorage\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n let statusFieldAccess = false\n const publicationFieldPolicyDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status: data._status === allLocalesPublicationStatus ? allLocalesPublicationStatus : undefined,\n })\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n docForHooks: publicationFieldPolicyDoc,\n global: null,\n onFieldAccess: ({ accessResult, path }) => {\n if (path === '_status') {\n statusFieldAccess = accessResult\n }\n },\n operation: 'update',\n overrideAccess,\n req,\n })\n\n const password = data?.password\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 const publicationHookDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status:\n statusFieldAccess && data._status === allLocalesPublicationStatus\n ? allLocalesPublicationStatus\n : undefined,\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: publicationHookDoc,\n req,\n })) || data\n }\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: publicationHookDoc,\n req,\n })) || data\n }\n }\n\n const publicationData = { ...data }\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: publicationHookDoc,\n docWithLocales,\n fieldsToValidate: submittedTopLevelFieldNames,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n // only skip validation for drafts when draft validation is false\n skipValidation: isSavingDraft && !hasDraftValidationEnabled(collectionConfig),\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let statusFieldValue: unknown\n\n let result: JsonObject = await beforeChange({\n ...beforeChangeArgs,\n onDataProcessed: (processedData) => {\n statusFieldValue = processedData._status\n },\n })\n\n const hasAuthorizedPublicationStatus = hasAuthorizedAllLocalesPublicationStatus({\n data: publicationData,\n fieldAccessDenied: !statusFieldAccess,\n fieldValue: statusFieldValue,\n status: allLocalesPublicationStatus,\n })\n\n if (\n allLocalesPublicationStatus &&\n !hasAuthorizedPublicationStatus &&\n typeof statusFieldValue === 'undefined' &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n }\n\n if (\n config.localization &&\n hasLocalizeStatusEnabled(collectionConfig) &&\n typeof result._status === 'string'\n ) {\n const statusStr = result._status\n\n if (\n hasAuthorizedPublicationStatus &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n } else {\n result._status = {}\n }\n\n if (!hasAuthorizedPublicationStatus) {\n for (const localeCode of config.localization.localeCodes) {\n ;(result._status as Record<string, unknown>)[localeCode] = statusStr\n }\n }\n }\n\n let localizedPublishData: JsonObject | null = null\n\n if (config.localization && collectionConfig.versions) {\n if (hasLocalizeStatusEnabled(collectionConfig)) {\n if (hasAuthorizedPublicationStatus) {\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 if (\n config.localization &&\n hasDraftsEnabled(collectionConfig) &&\n publishAllLocales &&\n !unpublishAllLocales &&\n (!hasLocalizeStatusEnabled(collectionConfig) || hasAuthorizedPublicationStatus)\n ) {\n const validationResult = await validateLocalWithLocaleKeyedData({\n operation: 'update',\n options: {\n id,\n collection: collectionConfig.slug,\n data: result,\n draft: true,\n locale: 'all',\n overrideAccess,\n req,\n },\n payload,\n sourceData: {\n docWithLocales,\n originalDoc: publicationHookDoc,\n originalLocale: locale,\n },\n trash: Boolean(originalDoc?.deletedAt),\n })\n\n if (!validationResult.valid) {\n throw new ValidationError(\n {\n id,\n collection: collectionConfig.slug,\n errors: validationResult.errors,\n req,\n },\n req.t,\n )\n }\n }\n\n // File deletion and writes must occur after the final publish validation. Validation failures\n // leave both the persisted upload and local files untouched.\n if (!isDraftOverPublished && !hasManagedLocalUpload) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n if (!collectionConfig.upload.disableLocalStorage && !hasManagedLocalUpload) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n const writeDocument = async (): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\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 if (collectionConfig.auth?.useSessions) {\n const currentSid =\n req.user?.collection === collectionConfig.slug && String(req.user.id) === String(id)\n ? req.user._sid\n : undefined\n const existingSessions = removeExpiredSessions(\n (docWithLocales.sessions as undefined | UserSession[]) ?? [],\n )\n\n dataToUpdate.sessions = currentSid\n ? existingSessions.filter((session) => session.id === currentSid)\n : []\n }\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 select,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n }\n\n if (!nextFileData) {\n return writeDocument()\n }\n\n return runLocalFileUpdate({\n id,\n collection: collectionConfig,\n current: docWithLocales,\n files: hasManagedLocalUpload ? filesToUpload : [],\n next: nextFileData as JsonObject,\n req,\n write: writeDocument,\n })\n}\n"],"names":["ensureUsernameOrEmail","removeExpiredSessions","generatePasswordSaltHash","ValidationError","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","saveVersion","deleteAssociatedFiles","runLocalFileUpdate","uploadFiles","checkDocumentLockStatus","getTopLevelFieldNames","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","resolvePublishAllLocales","buildAllLocalesPublicationHookDoc","getAllLocalesPublicationStatus","hasAuthorizedAllLocalesPublicationStatus","validateAllLocalesPublicationFlags","buildLocalizedPublishData","validateLocalWithLocaleKeyedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","req","select","shouldManageLocalFiles","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","nextFileData","upload","fileOperations","undefined","draft","allLocalesPublicationStatus","hasLocalizedStatus","Boolean","localization","isSavingDraft","_status","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","global","isRestoringDraftFromTrash","deletedAt","shouldLimitValidationToSubmittedFields","trash","submittedTopLevelFieldNames","auth","authOptions","operation","isDraftOverPublished","hasManagedLocalUpload","length","original","disableLocalStorage","statusFieldAccess","publicationFieldPolicyDoc","status","docForHooks","onFieldAccess","accessResult","path","password","shouldSavePassword","disableLocalStrategy","enableFields","publicationHookDoc","hooks","hook","publicationData","beforeChangeArgs","fieldsToValidate","skipValidation","statusFieldValue","result","onDataProcessed","processedData","hasAuthorizedPublicationStatus","fieldAccessDenied","fieldValue","statusStr","localeCode","localeCodes","localizedPublishData","versions","accessibleLocaleCodes","filterAvailableLocales","filteredLocales","locales","map","code","Array","isArray","currentDoc","db","findOne","where","equals","fields","validationResult","options","sourceData","originalLocale","valid","errors","t","files","overrideDelete","writeDocument","dataToUpdate","hash","salt","useSessions","currentSid","user","String","_sid","existingSessions","sessions","filter","session","resultWithLocales","updatedAt","Date","toISOString","updateOne","unpublish","previousDoc","current","next","write"],"mappings":"AA0BA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,qBAAqB,QAAQ,4BAA2B;AACjE,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,eAAe,QAAQ,2BAA0B;AAC1D,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,WAAW,QAAQ,oBAAmB;AACrE,SAASC,qBAAqB,QAAQ,4CAA2C;AACjF,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,uBAAuB,QAAQ,gDAA+C;AACvF,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SACEC,gBAAgB,EAChBC,yBAAyB,EACzBC,wBAAwB,QACnB,0CAAyC;AAChD,SAASC,wBAAwB,QAAQ,iDAAgD;AACzF,SACEC,iCAAiC,EACjCC,8BAA8B,EAC9BC,wCAAwC,EACxCC,kCAAkC,QAC7B,mDAAkD;AACzD,SAASC,yBAAyB,QAAQ,oDAAmD;AAC7F,SAASC,gCAAgC,QAAQ,uBAAsB;AAwBvE;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,iBAAiB,OAG5B,EACAC,EA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StB,IAAIsB,OAAO;YACpBlC;YACAmC,KAAKiF;YACL9F,OAAOpB;YACPC;YACAiC,QAAQ;YACR/B;YACAC;YACAG;YACAG;YACAC;YACAE;QACF;QAEA,wCAAwC;QACxC,yBAAyB;QACzB,wCAAwC;QAExC,IAAIlB,iBAAiBiE,KAAK,EAAExF,WAAWyE,QAAQ;YAC7C,KAAK,MAAMgB,QAAQlE,iBAAiBiE,KAAK,CAACxF,SAAS,CAAE;gBACnD+F,SACE,AAAC,MAAMN,KAAK;oBACV9B,YAAYpC;oBACZqC,SAAStB,IAAIsB,OAAO;oBACpBC,KAAKkC;oBACL/D;oBACAM;gBACF,MAAOyD;YACX;QACF;QAEA,wCAAwC;QACxC,uBAAuB;QACvB,wCAAwC;QAExCA,SAAS,MAAMhG,YAAY;YACzB4D,YAAYpC;YACZqC,SAAStB,IAAIsB,OAAO;YACpBnC;YACAoC,KAAKkC;YACLjC,QAAQ;YACRQ,WAAW;YACX8E,aAAa1F;YACbpB;QACF;QAEA,wCAAwC;QACxC,2BAA2B;QAC3B,wCAAwC;QAExC,IAAIf,iBAAiBiE,KAAK,EAAEzF,aAAa0E,QAAQ;YAC/C,KAAK,MAAMgB,QAAQlE,iBAAiBiE,KAAK,CAACzF,WAAW,CAAE;gBACrDgG,SACE,AAAC,MAAMN,KAAK;oBACV9B,YAAYpC;oBACZqC,SAAStB,IAAIsB,OAAO;oBACpBnC;oBACAoC,KAAKkC;oBACLzB,WAAW;oBACXtC;oBACAoH,aAAa1F;oBACbpB;oBACAC;gBACF,MAAOwD;YACX;QACF;QAEA,OAAOA;IACT;IAEA,IAAI,CAACnD,cAAc;QACjB,OAAOqF;IACT;IAEA,OAAO3H,mBAAmB;QACxBe;QACAsC,YAAYpC;QACZ8H,SAAS1H;QACToG,OAAOvD,wBAAwB1C,gBAAgB,EAAE;QACjDwH,MAAM1G;QACNN;QACAiH,OAAOtB;IACT;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { UserSession } from '../../../auth/types.js'\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 { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { removeExpiredSessions } from '../../../auth/sessions.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { ValidationError } from '../../../errors/index.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 { runLocalFileUpdate } from '../../../uploads/fileVersioning/archive.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport { getTopLevelFieldNames } from '../../../utilities/getTopLevelFieldNames.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { resolvePublishAllLocales } from '../../../utilities/resolvePublishAllLocales.js'\nimport {\n buildAllLocalesPublicationHookDoc,\n getAllLocalesPublicationStatus,\n hasAuthorizedAllLocalesPublicationStatus,\n validateAllLocalesPublicationFlags,\n} from '../../../versions/allLocalesPublicationStatus.js'\nimport { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js'\nimport { validateLocalWithLocaleKeyedData } from '../local/validate.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 overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n select: SelectType\n shouldManageLocalFiles: boolean\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n} & Pick<Required<SharedLocalAPIOptions>, 'overrideAccess'>\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 shouldManageLocalFiles,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const nextFileData =\n collectionConfig.upload && shouldManageLocalFiles && !collectionConfig.upload.fileOperations\n ? deepCopyObjectSimple(data)\n : undefined\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: publishAllLocalesArg,\n unpublishAllLocales: unpublishAllLocalesArg,\n })\n\n const publishAllLocales = resolvePublishAllLocales({\n draft: draftArg,\n hasLocalizeStatusEnabled: hasLocalizeStatusEnabled(collectionConfig),\n locale,\n publishAllLocalesArg,\n })\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const allLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(config.localization && hasLocalizeStatusEnabled(collectionConfig)),\n publishAllLocales,\n unpublishAllLocales,\n })\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n if (allLocalesPublicationStatus || isSavingDraft) {\n data._status = allLocalesPublicationStatus ?? '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 const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n const shouldLimitValidationToSubmittedFields =\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n unpublishAllLocales\n const submittedTopLevelFieldNames = shouldLimitValidationToSubmittedFields\n ? getTopLevelFieldNames(data)\n : undefined\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 // 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 during the update 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 const hasManagedLocalUpload =\n filesToUpload.length > 0 &&\n Boolean(data.original) &&\n !collectionConfig.upload.disableLocalStorage\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n let statusFieldAccess = false\n const publicationFieldPolicyDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status: data._status === allLocalesPublicationStatus ? allLocalesPublicationStatus : undefined,\n })\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n docForHooks: publicationFieldPolicyDoc,\n global: null,\n onFieldAccess: ({ accessResult, path }) => {\n if (path === '_status') {\n statusFieldAccess = accessResult\n }\n },\n operation: 'update',\n overrideAccess,\n req,\n })\n\n const password = data?.password\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 const publicationHookDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status:\n statusFieldAccess && data._status === allLocalesPublicationStatus\n ? allLocalesPublicationStatus\n : undefined,\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: publicationHookDoc,\n req,\n })) || data\n }\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: publicationHookDoc,\n req,\n })) || data\n }\n }\n\n const publicationData = { ...data }\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: publicationHookDoc,\n docWithLocales,\n fieldsToValidate: submittedTopLevelFieldNames,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n // only skip validation for drafts when draft validation is false\n skipValidation: isSavingDraft && !hasDraftValidationEnabled(collectionConfig),\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let statusFieldValue: unknown\n\n let result: JsonObject = await beforeChange({\n ...beforeChangeArgs,\n onDataProcessed: (processedData) => {\n statusFieldValue = processedData._status\n },\n })\n\n const hasAuthorizedPublicationStatus = hasAuthorizedAllLocalesPublicationStatus({\n data: publicationData,\n fieldAccessDenied: !statusFieldAccess,\n fieldValue: statusFieldValue,\n status: allLocalesPublicationStatus,\n })\n\n if (\n allLocalesPublicationStatus &&\n !hasAuthorizedPublicationStatus &&\n typeof statusFieldValue === 'undefined' &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n }\n\n if (\n config.localization &&\n hasLocalizeStatusEnabled(collectionConfig) &&\n typeof result._status === 'string'\n ) {\n const statusStr = result._status\n\n if (\n hasAuthorizedPublicationStatus &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n } else {\n result._status = {}\n }\n\n if (!hasAuthorizedPublicationStatus) {\n for (const localeCode of config.localization.localeCodes) {\n ;(result._status as Record<string, unknown>)[localeCode] = statusStr\n }\n }\n }\n\n let localizedPublishData: JsonObject | null = null\n\n if (config.localization && collectionConfig.versions) {\n if (hasLocalizeStatusEnabled(collectionConfig)) {\n if (hasAuthorizedPublicationStatus) {\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,\n fields: collectionConfig.fields,\n locale,\n result,\n })\n }\n }\n }\n\n if (\n config.localization &&\n hasDraftsEnabled(collectionConfig) &&\n publishAllLocales &&\n !unpublishAllLocales &&\n (!hasLocalizeStatusEnabled(collectionConfig) || hasAuthorizedPublicationStatus)\n ) {\n const validationResult = await validateLocalWithLocaleKeyedData({\n operation: 'update',\n options: {\n id,\n collection: collectionConfig.slug,\n data: result,\n draft: true,\n locale: 'all',\n overrideAccess,\n req,\n },\n payload,\n sourceData: {\n docWithLocales,\n originalDoc: publicationHookDoc,\n originalLocale: locale,\n },\n trash: Boolean(originalDoc?.deletedAt),\n })\n\n if (!validationResult.valid) {\n throw new ValidationError(\n {\n id,\n collection: collectionConfig.slug,\n errors: validationResult.errors,\n req,\n },\n req.t,\n )\n }\n }\n\n // File deletion and writes must occur after the final publish validation. Validation failures\n // leave both the persisted upload and local files untouched.\n if (!isDraftOverPublished && !hasManagedLocalUpload) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n if (!collectionConfig.upload.disableLocalStorage && !hasManagedLocalUpload) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n const writeDocument = async (): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\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 if (collectionConfig.auth?.useSessions) {\n const currentSid =\n req.user?.collection === collectionConfig.slug && String(req.user.id) === String(id)\n ? req.user._sid\n : undefined\n const existingSessions = removeExpiredSessions(\n (docWithLocales.sessions as undefined | UserSession[]) ?? [],\n )\n\n dataToUpdate.sessions = currentSid\n ? existingSessions.filter((session) => session.id === currentSid)\n : []\n }\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 select,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n }\n\n if (!nextFileData) {\n return writeDocument()\n }\n\n return runLocalFileUpdate({\n id,\n collection: collectionConfig,\n current: docWithLocales,\n files: hasManagedLocalUpload ? filesToUpload : [],\n next: nextFileData,\n req,\n write: writeDocument,\n })\n}\n"],"names":["ensureUsernameOrEmail","removeExpiredSessions","generatePasswordSaltHash","ValidationError","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","saveVersion","deleteAssociatedFiles","runLocalFileUpdate","uploadFiles","checkDocumentLockStatus","getTopLevelFieldNames","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","resolvePublishAllLocales","buildAllLocalesPublicationHookDoc","getAllLocalesPublicationStatus","hasAuthorizedAllLocalesPublicationStatus","validateAllLocalesPublicationFlags","buildLocalizedPublishData","validateLocalWithLocaleKeyedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","req","select","shouldManageLocalFiles","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","nextFileData","upload","fileOperations","undefined","draft","allLocalesPublicationStatus","hasLocalizedStatus","Boolean","localization","isSavingDraft","_status","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","global","isRestoringDraftFromTrash","deletedAt","shouldLimitValidationToSubmittedFields","trash","submittedTopLevelFieldNames","auth","authOptions","operation","isDraftOverPublished","hasManagedLocalUpload","length","original","disableLocalStorage","statusFieldAccess","publicationFieldPolicyDoc","status","docForHooks","onFieldAccess","accessResult","path","password","shouldSavePassword","disableLocalStrategy","enableFields","publicationHookDoc","hooks","hook","publicationData","beforeChangeArgs","fieldsToValidate","skipValidation","statusFieldValue","result","onDataProcessed","processedData","hasAuthorizedPublicationStatus","fieldAccessDenied","fieldValue","statusStr","localeCode","localeCodes","localizedPublishData","versions","accessibleLocaleCodes","filterAvailableLocales","filteredLocales","locales","map","code","Array","isArray","currentDoc","db","findOne","where","equals","fields","validationResult","options","sourceData","originalLocale","valid","errors","t","files","overrideDelete","writeDocument","dataToUpdate","hash","salt","useSessions","currentSid","user","String","_sid","existingSessions","sessions","filter","session","resultWithLocales","updatedAt","Date","toISOString","updateOne","unpublish","previousDoc","current","next","write"],"mappings":"AA0BA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,qBAAqB,QAAQ,4BAA2B;AACjE,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,eAAe,QAAQ,2BAA0B;AAC1D,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,WAAW,QAAQ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C/C,KAAK,MAAMgB,QAAQlE,iBAAiBiE,KAAK,CAACzF,WAAW,CAAE;gBACrDgG,SACE,AAAC,MAAMN,KAAK;oBACV9B,YAAYpC;oBACZqC,SAAStB,IAAIsB,OAAO;oBACpBnC;oBACAoC,KAAKkC;oBACLzB,WAAW;oBACXtC;oBACAoH,aAAa1F;oBACbpB;oBACAC;gBACF,MAAOwD;YACX;QACF;QAEA,OAAOA;IACT;IAEA,IAAI,CAACnD,cAAc;QACjB,OAAOqF;IACT;IAEA,OAAO3H,mBAAmB;QACxBe;QACAsC,YAAYpC;QACZ8H,SAAS1H;QACToG,OAAOvD,wBAAwB1C,gBAAgB,EAAE;QACjDwH,MAAM1G;QACNN;QACAiH,OAAOtB;IACT;AACF,EAAC"}
|
|
@@ -128,7 +128,7 @@ async function validateOperationWithScopedRequest({ id, collection, data: incomi
|
|
|
128
128
|
ensureUsernameOrEmail({
|
|
129
129
|
authOptions: collectionConfig.auth,
|
|
130
130
|
collectionSlug: collectionConfig.slug,
|
|
131
|
-
data
|
|
131
|
+
data,
|
|
132
132
|
operation: 'create',
|
|
133
133
|
req
|
|
134
134
|
});
|
|
@@ -136,9 +136,9 @@ async function validateOperationWithScopedRequest({ id, collection, data: incomi
|
|
|
136
136
|
ensureUsernameOrEmail({
|
|
137
137
|
authOptions: collectionConfig.auth,
|
|
138
138
|
collectionSlug: collectionConfig.slug,
|
|
139
|
-
data
|
|
139
|
+
data,
|
|
140
140
|
operation: 'update',
|
|
141
|
-
originalDoc
|
|
141
|
+
originalDoc,
|
|
142
142
|
req
|
|
143
143
|
});
|
|
144
144
|
}
|
|
@@ -146,7 +146,7 @@ async function validateOperationWithScopedRequest({ id, collection, data: incomi
|
|
|
146
146
|
collection: collectionConfig,
|
|
147
147
|
docWithLocales,
|
|
148
148
|
global: null,
|
|
149
|
-
incomingData
|
|
149
|
+
incomingData,
|
|
150
150
|
onValidationData,
|
|
151
151
|
originalDoc,
|
|
152
152
|
overrideAccess,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/validate.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, JsonObject } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { ValidationResult } from '../../types/validation.js'\nimport type { ValidationSourceData } from '../../utilities/runValidationLifecycle.js'\nimport type { Collection, RequiredDataFromCollectionSlug, TypeWithID } from '../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../auth/ensureUsernameOrEmail.js'\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { hasWhereAccessResult } from '../../auth/types.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { Forbidden, NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { deepCopyObjectSimple } from '../../utilities/deepCopyObject.js'\nimport { flattenDataByLocale } from '../../utilities/flattenDataByLocale.js'\nimport { runValidationLifecycle } from '../../utilities/runValidationLifecycle.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { validateUniqueConstraints } from './utilities/validateUniqueConstraints.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data?: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n draft: boolean\n id?: number | string\n onValidationData?: (data: JsonObject) => void\n overrideAccess: boolean\n req: PayloadRequest\n skipAccessControl?: boolean\n skipMutationHooks?: boolean\n sourceData?: ValidationSourceData\n trash?: boolean\n validationOperation?: 'create' | 'update' | 'validate'\n}\n\nexport async function validateOperation<TSlug extends CollectionSlug>(\n args: Arguments<TSlug>,\n): Promise<ValidationResult> {\n const previousOperation = args.req.operation\n args.req.operation = args.validationOperation ?? 'validate'\n\n try {\n return await validateOperationWithScopedRequest(args)\n } finally {\n args.req.operation = previousOperation\n }\n}\n\nasync function validateOperationWithScopedRequest<TSlug extends CollectionSlug>({\n id,\n collection,\n data: incomingData,\n draft,\n onValidationData,\n overrideAccess,\n req,\n skipAccessControl = false,\n skipMutationHooks = false,\n sourceData,\n trash = false,\n validationOperation = 'validate',\n}: Arguments<TSlug>): Promise<ValidationResult> {\n const collectionConfig = collection.config\n\n const accessResult =\n !skipAccessControl && !overrideAccess\n ? await executeAccess(\n { id, slug: collectionConfig.slug, data: incomingData, req },\n collectionConfig.access.validate,\n )\n : true\n const hasWherePolicy = hasWhereAccessResult(accessResult)\n\n if (id === undefined && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n\n let docWithLocales: JsonObject = sourceData ? deepCopyObjectSimple(sourceData.docWithLocales) : {}\n\n if (id !== undefined && !sourceData) {\n const idWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: { id: { equals: id } },\n })\n const where = combineQueries(idWhere, accessResult)\n const query: FindOneArgs = {\n collection: collectionConfig.slug,\n locale: req.locale!,\n req,\n where,\n }\n\n let storedDocument: (RequiredDataFromCollectionSlug<TSlug> & TypeWithID) | undefined\n\n if (draft && collectionConfig.versions?.drafts) {\n const { docs } = await req.payload.db.queryDrafts<\n RequiredDataFromCollectionSlug<TSlug> & TypeWithID\n >({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n where: appendVersionToQueryKey(where),\n })\n\n storedDocument = docs[0]\n\n if (!storedDocument && hasWherePolicy) {\n const { docs: existingVersions } = await req.payload.db.queryDrafts({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n select: { parent: true },\n where: appendVersionToQueryKey(idWhere),\n })\n\n if (existingVersions[0]) {\n throw new Forbidden(req.t)\n }\n }\n }\n\n if (!storedDocument) {\n storedDocument =\n (await req.payload.db.findOne<RequiredDataFromCollectionSlug<TSlug> & TypeWithID>({\n ...query,\n req,\n })) ?? undefined\n }\n\n if (!storedDocument && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n if (!storedDocument) {\n throw new NotFound(req.t)\n }\n\n docWithLocales = deepCopyObjectSimple(storedDocument)\n }\n\n let originalDoc: JsonObject\n\n if (id === undefined) {\n originalDoc = docWithLocales\n } else if (!sourceData) {\n originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft,\n fallbackLocale: null,\n global: null,\n locale: req.locale!,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n } else if (req.locale === sourceData.originalLocale) {\n originalDoc = deepCopyObjectSimple(sourceData.originalDoc)\n } else {\n originalDoc = flattenDataByLocale({\n configBlockReferences: req.payload.config.blocks,\n docWithLocales,\n fields: collectionConfig.fields,\n locale: req.locale!,\n })\n }\n\n return runValidationLifecycle({\n id,\n beforeValidation: ({ data }) => {\n if (!collectionConfig.auth) {\n return\n }\n\n if (id === undefined) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data: data as RequiredDataFromCollectionSlug<TSlug>,\n operation: 'create',\n req,\n })\n } else {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data: data as RequiredDataFromCollectionSlug<TSlug>,\n operation: 'update',\n originalDoc: originalDoc as RequiredDataFromCollectionSlug<TSlug>,\n req,\n })\n }\n },\n collection: collectionConfig,\n docWithLocales,\n global: null,\n incomingData: incomingData as JsonObject | undefined,\n onValidationData,\n originalDoc,\n overrideAccess,\n req,\n skipMutationHooks,\n validateData: ({ data }) =>\n validateUniqueConstraints({\n id,\n collection: collectionConfig,\n data,\n req,\n }),\n validationOperation,\n })\n}\n"],"names":["ensureUsernameOrEmail","executeAccess","hasWhereAccessResult","combineQueries","Forbidden","NotFound","afterRead","appendNonTrashedFilter","deepCopyObjectSimple","flattenDataByLocale","runValidationLifecycle","appendVersionToQueryKey","validateUniqueConstraints","validateOperation","args","previousOperation","req","operation","validationOperation","validateOperationWithScopedRequest","id","collection","data","incomingData","draft","onValidationData","overrideAccess","skipAccessControl","skipMutationHooks","sourceData","trash","collectionConfig","config","accessResult","slug","access","validate","hasWherePolicy","undefined","t","docWithLocales","idWhere","enableTrash","where","equals","query","locale","storedDocument","versions","drafts","docs","payload","db","queryDrafts","limit","pagination","existingVersions","select","parent","findOne","originalDoc","context","depth","doc","fallbackLocale","global","showHiddenFields","originalLocale","configBlockReferences","blocks","fields","beforeValidation","auth","authOptions","collectionSlug","validateData"],"mappings":"AASA,SAASA,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,sBAAqB;AAC1D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AAC3D,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,oBAAoB,QAAQ,oCAAmC;AACxE,SAASC,mBAAmB,QAAQ,yCAAwC;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,yBAAyB,QAAQ,2CAA0C;AAiBpF,OAAO,eAAeC,kBACpBC,IAAsB;IAEtB,MAAMC,oBAAoBD,KAAKE,GAAG,CAACC,SAAS;IAC5CH,KAAKE,GAAG,CAACC,SAAS,GAAGH,KAAKI,mBAAmB,IAAI;IAEjD,IAAI;QACF,OAAO,MAAMC,mCAAmCL;IAClD,SAAU;QACRA,KAAKE,GAAG,CAACC,SAAS,GAAGF;IACvB;AACF;AAEA,eAAeI,mCAAiE,EAC9EC,EAAE,EACFC,UAAU,EACVC,MAAMC,YAAY,EAClBC,KAAK,EACLC,gBAAgB,EAChBC,cAAc,EACdV,GAAG,EACHW,oBAAoB,KAAK,EACzBC,oBAAoB,KAAK,EACzBC,UAAU,EACVC,QAAQ,KAAK,EACbZ,sBAAsB,UAA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jD,IAAI,EAAE;YACzB,IAAI,CAACS,iBAAiByC,IAAI,EAAE;gBAC1B;YACF;YAEA,IAAIpD,OAAOkB,WAAW;gBACpBtC,sBAA6B;oBAC3ByE,aAAa1C,iBAAiByC,IAAI;oBAClCE,gBAAgB3C,iBAAiBG,IAAI;oBACrCZ,MAAMA;oBACNL,WAAW;oBACXD;gBACF;YACF,OAAO;gBACLhB,sBAA6B;oBAC3ByE,aAAa1C,iBAAiByC,IAAI;oBAClCE,gBAAgB3C,iBAAiBG,IAAI;oBACrCZ,MAAMA;oBACNL,WAAW;oBACX2C,aAAaA;oBACb5C;gBACF;YACF;QACF;QACAK,YAAYU;QACZS;QACAyB,QAAQ;QACR1C,cAAcA;QACdE;QACAmC;QACAlC;QACAV;QACAY;QACA+C,cAAc,CAAC,EAAErD,IAAI,EAAE,GACrBV,0BAA0B;gBACxBQ;gBACAC,YAAYU;gBACZT;gBACAN;YACF;QACFE;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/validate.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, JsonObject } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { ValidationResult } from '../../types/validation.js'\nimport type { ValidationSourceData } from '../../utilities/runValidationLifecycle.js'\nimport type { Collection, RequiredDataFromCollectionSlug, TypeWithID } from '../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../auth/ensureUsernameOrEmail.js'\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { hasWhereAccessResult } from '../../auth/types.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { Forbidden, NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { deepCopyObjectSimple } from '../../utilities/deepCopyObject.js'\nimport { flattenDataByLocale } from '../../utilities/flattenDataByLocale.js'\nimport { runValidationLifecycle } from '../../utilities/runValidationLifecycle.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { validateUniqueConstraints } from './utilities/validateUniqueConstraints.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data?: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n draft: boolean\n id?: number | string\n onValidationData?: (data: JsonObject) => void\n overrideAccess: boolean\n req: PayloadRequest\n skipAccessControl?: boolean\n skipMutationHooks?: boolean\n sourceData?: ValidationSourceData\n trash?: boolean\n validationOperation?: 'create' | 'update' | 'validate'\n}\n\nexport async function validateOperation<TSlug extends CollectionSlug>(\n args: Arguments<TSlug>,\n): Promise<ValidationResult> {\n const previousOperation = args.req.operation\n args.req.operation = args.validationOperation ?? 'validate'\n\n try {\n return await validateOperationWithScopedRequest(args)\n } finally {\n args.req.operation = previousOperation\n }\n}\n\nasync function validateOperationWithScopedRequest<TSlug extends CollectionSlug>({\n id,\n collection,\n data: incomingData,\n draft,\n onValidationData,\n overrideAccess,\n req,\n skipAccessControl = false,\n skipMutationHooks = false,\n sourceData,\n trash = false,\n validationOperation = 'validate',\n}: Arguments<TSlug>): Promise<ValidationResult> {\n const collectionConfig = collection.config\n\n const accessResult =\n !skipAccessControl && !overrideAccess\n ? await executeAccess(\n { id, slug: collectionConfig.slug, data: incomingData, req },\n collectionConfig.access.validate,\n )\n : true\n const hasWherePolicy = hasWhereAccessResult(accessResult)\n\n if (id === undefined && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n\n let docWithLocales: JsonObject = sourceData ? deepCopyObjectSimple(sourceData.docWithLocales) : {}\n\n if (id !== undefined && !sourceData) {\n const idWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: { id: { equals: id } },\n })\n const where = combineQueries(idWhere, accessResult)\n const query: FindOneArgs = {\n collection: collectionConfig.slug,\n locale: req.locale!,\n req,\n where,\n }\n\n let storedDocument: (RequiredDataFromCollectionSlug<TSlug> & TypeWithID) | undefined\n\n if (draft && collectionConfig.versions?.drafts) {\n const { docs } = await req.payload.db.queryDrafts<\n RequiredDataFromCollectionSlug<TSlug> & TypeWithID\n >({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n where: appendVersionToQueryKey(where),\n })\n\n storedDocument = docs[0]\n\n if (!storedDocument && hasWherePolicy) {\n const { docs: existingVersions } = await req.payload.db.queryDrafts({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n select: { parent: true },\n where: appendVersionToQueryKey(idWhere),\n })\n\n if (existingVersions[0]) {\n throw new Forbidden(req.t)\n }\n }\n }\n\n if (!storedDocument) {\n storedDocument =\n (await req.payload.db.findOne<RequiredDataFromCollectionSlug<TSlug> & TypeWithID>({\n ...query,\n req,\n })) ?? undefined\n }\n\n if (!storedDocument && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n if (!storedDocument) {\n throw new NotFound(req.t)\n }\n\n docWithLocales = deepCopyObjectSimple(storedDocument)\n }\n\n let originalDoc: JsonObject\n\n if (id === undefined) {\n originalDoc = docWithLocales\n } else if (!sourceData) {\n originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft,\n fallbackLocale: null,\n global: null,\n locale: req.locale!,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n } else if (req.locale === sourceData.originalLocale) {\n originalDoc = deepCopyObjectSimple(sourceData.originalDoc)\n } else {\n originalDoc = flattenDataByLocale({\n configBlockReferences: req.payload.config.blocks,\n docWithLocales,\n fields: collectionConfig.fields,\n locale: req.locale!,\n })\n }\n\n return runValidationLifecycle({\n id,\n beforeValidation: ({ data }) => {\n if (!collectionConfig.auth) {\n return\n }\n\n if (id === undefined) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'create',\n req,\n })\n } else {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n },\n collection: collectionConfig,\n docWithLocales,\n global: null,\n incomingData,\n onValidationData,\n originalDoc,\n overrideAccess,\n req,\n skipMutationHooks,\n validateData: ({ data }) =>\n validateUniqueConstraints({\n id,\n collection: collectionConfig,\n data,\n req,\n }),\n validationOperation,\n })\n}\n"],"names":["ensureUsernameOrEmail","executeAccess","hasWhereAccessResult","combineQueries","Forbidden","NotFound","afterRead","appendNonTrashedFilter","deepCopyObjectSimple","flattenDataByLocale","runValidationLifecycle","appendVersionToQueryKey","validateUniqueConstraints","validateOperation","args","previousOperation","req","operation","validationOperation","validateOperationWithScopedRequest","id","collection","data","incomingData","draft","onValidationData","overrideAccess","skipAccessControl","skipMutationHooks","sourceData","trash","collectionConfig","config","accessResult","slug","access","validate","hasWherePolicy","undefined","t","docWithLocales","idWhere","enableTrash","where","equals","query","locale","storedDocument","versions","drafts","docs","payload","db","queryDrafts","limit","pagination","existingVersions","select","parent","findOne","originalDoc","context","depth","doc","fallbackLocale","global","showHiddenFields","originalLocale","configBlockReferences","blocks","fields","beforeValidation","auth","authOptions","collectionSlug","validateData"],"mappings":"AASA,SAASA,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,sBAAqB;AAC1D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AAC3D,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,oBAAoB,QAAQ,oCAAmC;AACxE,SAASC,mBAAmB,QAAQ,yCAAwC;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,yBAAyB,QAAQ,2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vD,qBAAqBgC;YAC1BhB;YACAwC,gBAAgB;YAChBC,QAAQ;YACRnB,QAAQ9B,IAAI8B,MAAM;YAClBpB,gBAAgB;YAChBV;YACAkD,kBAAkB;QACpB;IACF,OAAO,IAAIlD,IAAI8B,MAAM,KAAKjB,WAAWsC,cAAc,EAAE;QACnDP,cAAcpD,qBAAqBqB,WAAW+B,WAAW;IAC3D,OAAO;QACLA,cAAcnD,oBAAoB;YAChC2D,uBAAuBpD,IAAImC,OAAO,CAACnB,MAAM,CAACqC,MAAM;YAChD7B;YACA8B,QAAQvC,iBAAiBuC,MAAM;YAC/BxB,QAAQ9B,IAAI8B,MAAM;QACpB;IACF;IAEA,OAAOpC,uBAAuB;QAC5BU;QACAmD,kBAAkB,CAAC,EAAEjD,IAAI,EAAE;YACzB,IAAI,CAACS,iBAAiByC,IAAI,EAAE;gBAC1B;YACF;YAEA,IAAIpD,OAAOkB,WAAW;gBACpBtC,sBAA6B;oBAC3ByE,aAAa1C,iBAAiByC,IAAI;oBAClCE,gBAAgB3C,iBAAiBG,IAAI;oBACrCZ;oBACAL,WAAW;oBACXD;gBACF;YACF,OAAO;gBACLhB,sBAA6B;oBAC3ByE,aAAa1C,iBAAiByC,IAAI;oBAClCE,gBAAgB3C,iBAAiBG,IAAI;oBACrCZ;oBACAL,WAAW;oBACX2C;oBACA5C;gBACF;YACF;QACF;QACAK,YAAYU;QACZS;QACAyB,QAAQ;QACR1C;QACAE;QACAmC;QACAlC;QACAV;QACAY;QACA+C,cAAc,CAAC,EAAErD,IAAI,EAAE,GACrBV,0BAA0B;gBACxBQ;gBACAC,YAAYU;gBACZT;gBACAN;YACF;QACFE;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map
|
|
1
|
+
{"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map\n}\n\n/**\n * Helper for authoring plugins with order, slug, and typed options.\n * Eliminates boilerplate and ensures metadata is always set consistently.\n *\n * The `plugin` function receives `config`, `plugins` (a slug-keyed map of other\n * plugins), and the user-provided `options`.\n *\n * @experimental\n *\n * @example\n * // With options:\n * export const seoPlugin = definePlugin<SEOPluginConfig>({\n * slug: 'plugin-seo',\n * plugin: ({ config, options }) => ({ ...config }),\n * })\n *\n * // Without options:\n * export const myPlugin = definePlugin({\n * slug: 'my-plugin',\n * plugin: ({ config }) => ({ ...config }),\n * })\n */\nexport function definePlugin(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap }) => Config | Promise<Config>\n slug: string\n}): () => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): undefined extends TOptions ? (options?: TOptions) => Plugin : (options: TOptions) => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): (options: TOptions) => Plugin {\n return (options?: TOptions): Plugin => {\n const pluginFn: Plugin = (config) =>\n descriptor.plugin({\n config,\n options: options as TOptions,\n plugins: buildPluginsMap(config.plugins),\n })\n\n if (options !== undefined) {\n pluginFn.options = options as Record<string, unknown>\n }\n pluginFn.slug = descriptor.slug\n if (descriptor.order !== undefined) {\n pluginFn.order = descriptor.order\n }\n\n return pluginFn\n }\n}\n"],"names":["buildPluginsMap","plugins","map","p","slug","definePlugin","descriptor","options","pluginFn","config","plugin","undefined","order"],"mappings":"AAEA,SAASA,gBAAgBC,OAA6B;IACpD,MAAMC,MAA0C,CAAC;IACjD,IAAID,SAAS;QACX,KAAK,MAAME,KAAKF,QAAS;YACvB,IAAIE,EAAEC,IAAI,EAAE;gBACVF,GAAG,CAACC,EAAEC,IAAI,CAAC,GAAGD;YAChB;QACF;IACF;IACA,OAAOD;AACT;AAsCA,OAAO,SAASG,aAAuBC,UAQtC;IACC,OAAO,CAACC;QACN,MAAMC,WAAmB,CAACC,SACxBH,WAAWI,MAAM,CAAC;gBAChBD;gBACAF,SAASA;gBACTN,SAASD,gBAAgBS,OAAOR,OAAO;YACzC;QAEF,IAAIM,YAAYI,WAAW;YACzBH,SAASD,OAAO,GAAGA;QACrB;QACAC,SAASJ,IAAI,GAAGE,WAAWF,IAAI;QAC/B,IAAIE,WAAWM,KAAK,KAAKD,WAAW;YAClCH,SAASI,KAAK,GAAGN,WAAWM,KAAK;QACnC;QAEA,OAAOJ;IACT;AACF"}
|
package/dist/config/sanitize.js
CHANGED
|
@@ -141,7 +141,7 @@ const addDefaultDashboardWidgets = ({ config, richTextSanitizers, validRelations
|
|
|
141
141
|
components: {
|
|
142
142
|
// Presents an inclusion filter (all collections checked by default) while persisting the
|
|
143
143
|
// inverse as an exclusion list, so collections added later stay visible by default.
|
|
144
|
-
Field: '@payloadcms/ui#
|
|
144
|
+
Field: '@payloadcms/ui#CollectionFilter'
|
|
145
145
|
},
|
|
146
146
|
description: ({ t })=>t('dashboard:widgetRecentlyViewedFilterDescription')
|
|
147
147
|
},
|
|
@@ -191,7 +191,7 @@ const addDefaultDashboardWidgets = ({ config, richTextSanitizers, validRelations
|
|
|
191
191
|
});
|
|
192
192
|
dashboard.widgets.push({
|
|
193
193
|
slug: 'activity',
|
|
194
|
-
Component: '@payloadcms/ui/rsc#
|
|
194
|
+
Component: '@payloadcms/ui/rsc#ActivityWidget',
|
|
195
195
|
fields: sanitizeFields({
|
|
196
196
|
config: config,
|
|
197
197
|
existingFieldNames: new Set(),
|