payload 3.68.0-internal-debug.591ab42 → 3.68.0-internal.2b8df4a
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/auth/strategies/local/incrementLoginAttempts.js +1 -2
- package/dist/auth/strategies/local/incrementLoginAttempts.js.map +1 -1
- package/dist/bin/generateImportMap/iterateFields.js +1 -2
- package/dist/bin/generateImportMap/iterateFields.js.map +1 -1
- package/dist/bin/index.js +2 -4
- package/dist/bin/index.js.map +1 -1
- package/dist/bin/migrate.js +1 -2
- package/dist/bin/migrate.js.map +1 -1
- package/dist/collections/config/defaults.js +1 -2
- package/dist/collections/config/defaults.js.map +1 -1
- package/dist/config/find.js +1 -2
- package/dist/config/find.js.map +1 -1
- package/dist/errors/APIError.js +1 -2
- package/dist/errors/APIError.js.map +1 -1
- package/dist/errors/AuthenticationError.js.map +1 -1
- package/dist/errors/DuplicateCollection.js.map +1 -1
- package/dist/errors/DuplicateFieldName.js.map +1 -1
- package/dist/errors/DuplicateGlobal.js.map +1 -1
- package/dist/errors/ErrorDeletingFile.js.map +1 -1
- package/dist/errors/FileRetrievalError.js.map +1 -1
- package/dist/errors/FileUploadError.js.map +1 -1
- package/dist/errors/Forbidden.js.map +1 -1
- package/dist/errors/InvalidConfiguration.js.map +1 -1
- package/dist/errors/InvalidFieldJoin.js.map +1 -1
- package/dist/errors/InvalidFieldName.js.map +1 -1
- package/dist/errors/InvalidFieldRelationship.js.map +1 -1
- package/dist/errors/InvalidSchema.js.map +1 -1
- package/dist/errors/Locked.js.map +1 -1
- package/dist/errors/LockedAuth.js.map +1 -1
- package/dist/errors/MissingCollectionLabel.js.map +1 -1
- package/dist/errors/MissingEditorProp.js.map +1 -1
- package/dist/errors/MissingFieldInputOptions.js.map +1 -1
- package/dist/errors/MissingFieldType.js.map +1 -1
- package/dist/errors/MissingFile.js.map +1 -1
- package/dist/errors/NotFound.js.map +1 -1
- package/dist/errors/QueryError.js.map +1 -1
- package/dist/errors/ReservedFieldName.js.map +1 -1
- package/dist/errors/TimestampsRequired.js.map +1 -1
- package/dist/errors/UnauthorizedError.js.map +1 -1
- package/dist/errors/UnverifiedEmail.js.map +1 -1
- package/dist/errors/ValidationError.js.map +1 -1
- package/dist/fields/config/client.js +1 -2
- package/dist/fields/config/client.js.map +1 -1
- package/dist/kv/adapters/DatabaseKVAdapter.js.map +1 -1
- package/dist/queues/errors/index.js.map +1 -1
- package/dist/queues/operations/runJobs/index.js +1 -2
- package/dist/queues/operations/runJobs/index.js.map +1 -1
- package/dist/uploads/fetchAPI-multipart/utilities.js +1 -2
- package/dist/uploads/fetchAPI-multipart/utilities.js.map +1 -1
- package/dist/uploads/generateFileData.js +4 -8
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/utilities/createLocalReq.js.map +1 -1
- package/dist/utilities/deepCopyObject.js.map +1 -1
- package/dist/utilities/findUp.js +4 -8
- package/dist/utilities/findUp.js.map +1 -1
- package/dist/utilities/formatErrors.js.map +1 -1
- package/dist/utilities/getFieldPermissions.spec.js +2 -4
- package/dist/utilities/getFieldPermissions.spec.js.map +1 -1
- package/dist/utilities/parseParams/index.spec.js +5 -10
- package/dist/utilities/parseParams/index.spec.js.map +1 -1
- package/dist/utilities/telemetry/conf/index.js.map +1 -1
- package/dist/utilities/transformColumnPreferences.js +1 -2
- package/dist/utilities/transformColumnPreferences.js.map +1 -1
- package/dist/utilities/unflatten.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors/UnauthorizedError.ts"],"sourcesContent":["import type { TFunction } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\nimport { status as httpStatus } from 'http-status'\n\nimport { APIError } from './APIError.js'\n\nexport class UnauthorizedError extends APIError {\n constructor(t?: TFunction) {\n super(t ? t('error:unauthorized') : en.translations.error.unauthorized, httpStatus.UNAUTHORIZED)\n }\n}\n"],"names":["en","status","httpStatus","APIError","UnauthorizedError","
|
|
1
|
+
{"version":3,"sources":["../../src/errors/UnauthorizedError.ts"],"sourcesContent":["import type { TFunction } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\nimport { status as httpStatus } from 'http-status'\n\nimport { APIError } from './APIError.js'\n\nexport class UnauthorizedError extends APIError {\n constructor(t?: TFunction) {\n super(t ? t('error:unauthorized') : en.translations.error.unauthorized, httpStatus.UNAUTHORIZED)\n }\n}\n"],"names":["en","status","httpStatus","APIError","UnauthorizedError","t","translations","error","unauthorized","UNAUTHORIZED"],"mappings":"AAEA,SAASA,EAAE,QAAQ,wCAAuC;AAC1D,SAASC,UAAUC,UAAU,QAAQ,cAAa;AAElD,SAASC,QAAQ,QAAQ,gBAAe;AAExC,OAAO,MAAMC,0BAA0BD;IACrC,YAAYE,CAAa,CAAE;QACzB,KAAK,CAACA,IAAIA,EAAE,wBAAwBL,GAAGM,YAAY,CAACC,KAAK,CAACC,YAAY,EAAEN,WAAWO,YAAY;IACjG;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors/UnverifiedEmail.ts"],"sourcesContent":["import type { TFunction } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\nimport { status as httpStatus } from 'http-status'\n\nimport { APIError } from './APIError.js'\n\nexport class UnverifiedEmail extends APIError {\n constructor({ t }: { t?: TFunction }) {\n super(\n t ? t('error:unverifiedEmail') : en.translations.error.unverifiedEmail,\n httpStatus.FORBIDDEN,\n )\n }\n}\n"],"names":["en","status","httpStatus","APIError","UnverifiedEmail","
|
|
1
|
+
{"version":3,"sources":["../../src/errors/UnverifiedEmail.ts"],"sourcesContent":["import type { TFunction } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\nimport { status as httpStatus } from 'http-status'\n\nimport { APIError } from './APIError.js'\n\nexport class UnverifiedEmail extends APIError {\n constructor({ t }: { t?: TFunction }) {\n super(\n t ? t('error:unverifiedEmail') : en.translations.error.unverifiedEmail,\n httpStatus.FORBIDDEN,\n )\n }\n}\n"],"names":["en","status","httpStatus","APIError","UnverifiedEmail","t","translations","error","unverifiedEmail","FORBIDDEN"],"mappings":"AAEA,SAASA,EAAE,QAAQ,wCAAuC;AAC1D,SAASC,UAAUC,UAAU,QAAQ,cAAa;AAElD,SAASC,QAAQ,QAAQ,gBAAe;AAExC,OAAO,MAAMC,wBAAwBD;IACnC,YAAY,EAAEE,CAAC,EAAqB,CAAE;QACpC,KAAK,CACHA,IAAIA,EAAE,2BAA2BL,GAAGM,YAAY,CAACC,KAAK,CAACC,eAAe,EACtEN,WAAWO,SAAS;IAExB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors/ValidationError.ts"],"sourcesContent":["import type { TFunction } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\nimport { status as httpStatus } from 'http-status'\n\nimport type { LabelFunction, StaticLabel } from '../config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { APIError } from './APIError.js'\n\n// This gets dynamically reassigned during compilation\nexport let ValidationErrorName = 'ValidationError'\n\nexport type ValidationFieldError = {\n label?: LabelFunction | StaticLabel\n // The error message to display for this field\n message: string\n path: string\n}\n\nexport class ValidationError extends APIError<{\n collection?: string\n errors: ValidationFieldError[]\n global?: string\n}> {\n constructor(\n results: {\n collection?: string\n errors: ValidationFieldError[]\n global?: string\n id?: number | string\n /**\n * req needs to be passed through (if you have one) in order to resolve label functions that may be part of the errors array\n */\n req?: Partial<PayloadRequest>\n },\n t?: TFunction,\n ) {\n const message = t\n ? t('error:followingFieldsInvalid', { count: results.errors.length })\n : results.errors.length === 1\n ? en.translations.error.followingFieldsInvalid_one\n : en.translations.error.followingFieldsInvalid_other\n\n const req = results.req\n // delete to avoid logging the whole req\n delete results['req']\n\n super(\n `${message} ${results.errors\n .map((f) => {\n if (f.label) {\n if (typeof f.label === 'function') {\n if (!req || !req.i18n || !req.t) {\n return f.path\n }\n\n return f.label({ i18n: req.i18n, t: req.t })\n }\n\n if (typeof f.label === 'object') {\n if (req?.i18n?.language) {\n return f.label[req.i18n.language]\n }\n\n return f.label[Object.keys(f.label)[0]!]\n }\n\n return f.label\n }\n\n return f.path\n })\n .join(', ')}`,\n httpStatus.BAD_REQUEST,\n results,\n )\n\n ValidationErrorName = this.constructor.name\n }\n}\n"],"names":["en","status","httpStatus","APIError","ValidationErrorName","ValidationError","
|
|
1
|
+
{"version":3,"sources":["../../src/errors/ValidationError.ts"],"sourcesContent":["import type { TFunction } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\nimport { status as httpStatus } from 'http-status'\n\nimport type { LabelFunction, StaticLabel } from '../config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { APIError } from './APIError.js'\n\n// This gets dynamically reassigned during compilation\nexport let ValidationErrorName = 'ValidationError'\n\nexport type ValidationFieldError = {\n label?: LabelFunction | StaticLabel\n // The error message to display for this field\n message: string\n path: string\n}\n\nexport class ValidationError extends APIError<{\n collection?: string\n errors: ValidationFieldError[]\n global?: string\n}> {\n constructor(\n results: {\n collection?: string\n errors: ValidationFieldError[]\n global?: string\n id?: number | string\n /**\n * req needs to be passed through (if you have one) in order to resolve label functions that may be part of the errors array\n */\n req?: Partial<PayloadRequest>\n },\n t?: TFunction,\n ) {\n const message = t\n ? t('error:followingFieldsInvalid', { count: results.errors.length })\n : results.errors.length === 1\n ? en.translations.error.followingFieldsInvalid_one\n : en.translations.error.followingFieldsInvalid_other\n\n const req = results.req\n // delete to avoid logging the whole req\n delete results['req']\n\n super(\n `${message} ${results.errors\n .map((f) => {\n if (f.label) {\n if (typeof f.label === 'function') {\n if (!req || !req.i18n || !req.t) {\n return f.path\n }\n\n return f.label({ i18n: req.i18n, t: req.t })\n }\n\n if (typeof f.label === 'object') {\n if (req?.i18n?.language) {\n return f.label[req.i18n.language]\n }\n\n return f.label[Object.keys(f.label)[0]!]\n }\n\n return f.label\n }\n\n return f.path\n })\n .join(', ')}`,\n httpStatus.BAD_REQUEST,\n results,\n )\n\n ValidationErrorName = this.constructor.name\n }\n}\n"],"names":["en","status","httpStatus","APIError","ValidationErrorName","ValidationError","results","t","message","count","errors","length","translations","error","followingFieldsInvalid_one","followingFieldsInvalid_other","req","map","f","label","i18n","path","language","Object","keys","join","BAD_REQUEST","name"],"mappings":"AAEA,SAASA,EAAE,QAAQ,wCAAuC;AAC1D,SAASC,UAAUC,UAAU,QAAQ,cAAa;AAKlD,SAASC,QAAQ,QAAQ,gBAAe;AAExC,sDAAsD;AACtD,OAAO,IAAIC,sBAAsB,kBAAiB;AASlD,OAAO,MAAMC,wBAAwBF;IAKnC,YACEG,OASC,EACDC,CAAa,CACb;QACA,MAAMC,UAAUD,IACZA,EAAE,gCAAgC;YAAEE,OAAOH,QAAQI,MAAM,CAACC,MAAM;QAAC,KACjEL,QAAQI,MAAM,CAACC,MAAM,KAAK,IACxBX,GAAGY,YAAY,CAACC,KAAK,CAACC,0BAA0B,GAChDd,GAAGY,YAAY,CAACC,KAAK,CAACE,4BAA4B;QAExD,MAAMC,MAAMV,QAAQU,GAAG;QACvB,wCAAwC;QACxC,OAAOV,OAAO,CAAC,MAAM;QAErB,KAAK,CACH,GAAGE,QAAQ,CAAC,EAAEF,QAAQI,MAAM,CACzBO,GAAG,CAAC,CAACC;YACJ,IAAIA,EAAEC,KAAK,EAAE;gBACX,IAAI,OAAOD,EAAEC,KAAK,KAAK,YAAY;oBACjC,IAAI,CAACH,OAAO,CAACA,IAAII,IAAI,IAAI,CAACJ,IAAIT,CAAC,EAAE;wBAC/B,OAAOW,EAAEG,IAAI;oBACf;oBAEA,OAAOH,EAAEC,KAAK,CAAC;wBAAEC,MAAMJ,IAAII,IAAI;wBAAEb,GAAGS,IAAIT,CAAC;oBAAC;gBAC5C;gBAEA,IAAI,OAAOW,EAAEC,KAAK,KAAK,UAAU;oBAC/B,IAAIH,KAAKI,MAAME,UAAU;wBACvB,OAAOJ,EAAEC,KAAK,CAACH,IAAII,IAAI,CAACE,QAAQ,CAAC;oBACnC;oBAEA,OAAOJ,EAAEC,KAAK,CAACI,OAAOC,IAAI,CAACN,EAAEC,KAAK,CAAC,CAAC,EAAE,CAAE;gBAC1C;gBAEA,OAAOD,EAAEC,KAAK;YAChB;YAEA,OAAOD,EAAEG,IAAI;QACf,GACCI,IAAI,CAAC,OAAO,EACfvB,WAAWwB,WAAW,EACtBpB;QAGFF,sBAAsB,IAAI,CAAC,WAAW,CAACuB,IAAI;IAC7C;AACF"}
|
|
@@ -255,8 +255,7 @@ export const createClientField = ({ defaultIDType, field: incomingField, i18n, i
|
|
|
255
255
|
{
|
|
256
256
|
const field = clientField;
|
|
257
257
|
if (incomingField.options?.length) {
|
|
258
|
-
field.options = [] // Create new array to avoid mutating global config
|
|
259
|
-
;
|
|
258
|
+
field.options = []; // Create new array to avoid mutating global config
|
|
260
259
|
for(let i = 0; i < incomingField.options.length; i++){
|
|
261
260
|
const option = incomingField.options[i];
|
|
262
261
|
if (typeof option === 'object' && typeof option.label === 'function') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/fields/config/client.ts"],"sourcesContent":["// @ts-strict-ignore\n/* eslint-disable perfectionist/sort-switch-case */\n// Keep perfectionist/sort-switch-case disabled - it incorrectly messes up the ordering of the switch cases, causing it to break\nimport type { I18nClient, TFunction } from '@payloadcms/translations'\n\nimport type {\n AdminClient,\n ArrayFieldClient,\n Block,\n BlockJSX,\n BlocksFieldClient,\n ClientBlock,\n ClientField,\n Field,\n FieldBase,\n JoinFieldClient,\n LabelsClient,\n RadioFieldClient,\n RowFieldClient,\n SelectFieldClient,\n TabsFieldClient,\n} from '../../fields/config/types.js'\nimport type { Payload } from '../../types/index.js'\n\nimport { getFromImportMap } from '../../bin/generateImportMap/utilities/getFromImportMap.js'\nimport { MissingEditorProp } from '../../errors/MissingEditorProp.js'\nimport { fieldAffectsData } from '../../fields/config/types.js'\nimport { flattenTopLevelFields, type ImportMap } from '../../index.js'\n\n// Should not be used - ClientField should be used instead. This is why we don't export ClientField, we don't want people\n// to accidentally use it instead of ClientField and get confused\n\nexport { ClientField }\n\nexport type ServerOnlyFieldProperties =\n | 'dbName' // can be a function\n | 'editor' // This is a `richText` only property\n | 'enumName' // can be a function\n | 'filterOptions' // This is a `relationship`, `upload`, and `select` only property\n | 'graphQL'\n | 'label'\n | 'typescriptSchema'\n | 'validate'\n | keyof Pick<FieldBase, 'access' | 'custom' | 'defaultValue' | 'hooks'>\n\nexport type ServerOnlyFieldAdminProperties = keyof Pick<\n FieldBase['admin'],\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n 'components' | 'condition'\n>\n\nconst serverOnlyFieldProperties: Partial<ServerOnlyFieldProperties>[] = [\n 'hooks',\n 'access',\n 'validate',\n 'defaultValue',\n 'filterOptions', // This is a `relationship`, `upload`, and `select` only property\n 'editor', // This is a `richText` only property\n 'custom',\n 'typescriptSchema',\n 'dbName', // can be a function\n 'enumName', // can be a function\n 'graphQL', // client does not need graphQL\n // the following props are handled separately (see below):\n // `label`\n // `fields`\n // `blocks`\n // `tabs`\n // `admin`\n]\n\nconst serverOnlyFieldAdminProperties: Partial<ServerOnlyFieldAdminProperties>[] = [\n 'condition',\n 'components',\n]\n\ntype FieldWithDescription = {\n admin: AdminClient\n} & ClientField\n\nexport const createClientBlocks = ({\n blocks,\n defaultIDType,\n i18n,\n importMap,\n}: {\n blocks: (Block | string)[]\n defaultIDType: Payload['config']['db']['defaultIDType']\n i18n: I18nClient\n importMap: ImportMap\n}): (ClientBlock | string)[] | ClientBlock[] => {\n const clientBlocks: (ClientBlock | string)[] = []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]!\n\n if (typeof block === 'string') {\n // Do not process blocks that are just strings - they are processed once in the client config\n clientBlocks.push(block)\n continue\n }\n\n const clientBlock: ClientBlock = {\n slug: block.slug,\n fields: [],\n }\n if (block.imageAltText) {\n clientBlock.imageAltText = block.imageAltText\n }\n if (block.imageURL) {\n clientBlock.imageURL = block.imageURL\n }\n\n if (block.admin?.custom || block.admin?.group) {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n clientBlock.admin = {}\n if (block.admin.custom) {\n clientBlock.admin!.custom = block.admin.custom\n }\n if (block.admin.group) {\n clientBlock.admin!.group = block.admin.group\n }\n }\n\n if (block?.admin?.jsx) {\n const jsxResolved = getFromImportMap<BlockJSX>({\n importMap,\n PayloadComponent: block.admin.jsx,\n schemaPath: '',\n })\n clientBlock.jsx = jsxResolved\n }\n\n if (block?.admin?.disableBlockName) {\n // Check for existing admin object, this way we don't have to spread it in\n if (clientBlock.admin) {\n clientBlock.admin.disableBlockName = block.admin.disableBlockName\n } else {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n clientBlock.admin = { disableBlockName: block.admin.disableBlockName }\n }\n }\n\n if (block.labels) {\n clientBlock.labels = {} as unknown as LabelsClient\n\n if (block.labels.singular) {\n if (typeof block.labels.singular === 'function') {\n clientBlock.labels.singular = block.labels.singular({ i18n, t: i18n.t as TFunction })\n } else {\n clientBlock.labels.singular = block.labels.singular\n }\n if (typeof block.labels.plural === 'function') {\n clientBlock.labels.plural = block.labels.plural({ i18n, t: i18n.t as TFunction })\n } else {\n clientBlock.labels.plural = block.labels.plural\n }\n }\n }\n\n clientBlock.fields = createClientFields({\n defaultIDType,\n fields: block.fields,\n i18n,\n importMap,\n })\n\n clientBlocks.push(clientBlock)\n }\n\n return clientBlocks\n}\n\nexport const createClientField = ({\n defaultIDType,\n field: incomingField,\n i18n,\n importMap,\n}: {\n defaultIDType: Payload['config']['db']['defaultIDType']\n field: Field\n i18n: I18nClient\n importMap: ImportMap\n}): ClientField => {\n const clientField: ClientField = {} as ClientField\n\n for (const key in incomingField) {\n if (serverOnlyFieldProperties.includes(key as any)) {\n continue\n }\n\n switch (key) {\n case 'admin':\n if (!incomingField.admin) {\n break\n }\n\n clientField.admin = {} as AdminClient\n\n for (const adminKey in incomingField.admin) {\n if (serverOnlyFieldAdminProperties.includes(adminKey as any)) {\n continue\n }\n\n switch (adminKey) {\n case 'description':\n if ('description' in incomingField.admin) {\n if (typeof incomingField.admin?.description !== 'function') {\n ;(clientField as FieldWithDescription).admin.description =\n incomingField.admin.description\n }\n }\n\n break\n\n default:\n ;(clientField.admin as any)[adminKey] =\n incomingField.admin[adminKey as keyof typeof incomingField.admin]\n }\n }\n\n break\n\n case 'blocks':\n case 'fields':\n case 'tabs':\n // Skip - we handle sub-fields in the switch below\n break\n\n case 'options':\n // Skip - we handle options in the radio/select switch below to avoid mutating the global config\n break\n\n case 'label':\n //@ts-expect-error - would need to type narrow\n if (typeof incomingField.label === 'function') {\n //@ts-expect-error - would need to type narrow\n clientField.label = incomingField.label({ i18n, t: i18n.t })\n } else {\n //@ts-expect-error - would need to type narrow\n clientField.label = incomingField.label\n }\n\n break\n\n default:\n ;(clientField as any)[key] = incomingField[key as keyof Field]\n }\n }\n\n switch (incomingField.type) {\n case 'array': {\n if (incomingField.labels) {\n const field = clientField as unknown as ArrayFieldClient\n\n field.labels = {} as unknown as LabelsClient\n\n if (incomingField.labels.singular) {\n if (typeof incomingField.labels.singular === 'function') {\n field.labels.singular = incomingField.labels.singular({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.singular = incomingField.labels.singular\n }\n if (typeof incomingField.labels.plural === 'function') {\n field.labels.plural = incomingField.labels.plural({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.plural = incomingField.labels.plural\n }\n }\n }\n }\n // falls through\n case 'collapsible':\n case 'group':\n case 'row': {\n const field = clientField as unknown as RowFieldClient\n\n if (!field.fields) {\n field.fields = []\n }\n\n field.fields = createClientFields({\n defaultIDType,\n disableAddingID: incomingField.type !== 'array',\n fields: incomingField.fields,\n i18n,\n importMap,\n })\n\n break\n }\n\n case 'blocks': {\n const field = clientField as unknown as BlocksFieldClient\n\n if (incomingField.labels) {\n field.labels = {} as unknown as LabelsClient\n\n if (incomingField.labels.singular) {\n if (typeof incomingField.labels.singular === 'function') {\n field.labels.singular = incomingField.labels.singular({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.singular = incomingField.labels.singular\n }\n if (typeof incomingField.labels.plural === 'function') {\n field.labels.plural = incomingField.labels.plural({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.plural = incomingField.labels.plural\n }\n }\n }\n\n if (incomingField.blockReferences?.length) {\n field.blockReferences = createClientBlocks({\n blocks: incomingField.blockReferences,\n defaultIDType,\n i18n,\n importMap,\n })\n }\n\n if (incomingField.blocks?.length) {\n field.blocks = createClientBlocks({\n blocks: incomingField.blocks,\n defaultIDType,\n i18n,\n importMap,\n }) as ClientBlock[]\n }\n\n break\n }\n\n case 'join': {\n const field = clientField as JoinFieldClient\n\n field.targetField = {\n relationTo: field.targetField?.relationTo,\n }\n\n break\n }\n\n case 'radio':\n // falls through\n case 'select': {\n const field = clientField as RadioFieldClient | SelectFieldClient\n\n if (incomingField.options?.length) {\n field.options = [] // Create new array to avoid mutating global config\n\n for (let i = 0; i < incomingField.options.length; i++) {\n const option = incomingField.options[i]\n\n if (typeof option === 'object' && typeof option.label === 'function') {\n field.options[i] = {\n label: option.label({ i18n, t: i18n.t as TFunction }),\n value: option.value,\n }\n } else if (typeof option === 'object') {\n field.options[i] = {\n label: option.label,\n value: option.value,\n }\n } else if (typeof option === 'string') {\n field.options[i] = option\n }\n }\n }\n\n break\n }\n\n case 'richText': {\n if (!incomingField?.editor) {\n throw new MissingEditorProp(incomingField) // while we allow disabling editor functionality, you should not have any richText fields defined if you do not have an editor\n }\n\n if (typeof incomingField?.editor === 'function') {\n throw new Error('Attempted to access unsanitized rich text editor.')\n }\n\n break\n }\n\n case 'tabs': {\n const field = clientField as unknown as TabsFieldClient\n\n if (incomingField.tabs?.length) {\n field.tabs = []\n\n for (let i = 0; i < incomingField.tabs.length; i++) {\n const tab = incomingField.tabs[i]\n const clientTab = {} as unknown as TabsFieldClient['tabs'][0]\n\n for (const key in tab) {\n if (serverOnlyFieldProperties.includes(key as any)) {\n continue\n }\n\n const tabProp = tab[key as keyof typeof tab]\n\n if (key === 'fields') {\n clientTab.fields = createClientFields({\n defaultIDType,\n disableAddingID: true,\n fields: tab.fields,\n i18n,\n importMap,\n })\n } else if (\n (key === 'label' || key === 'description') &&\n typeof tabProp === 'function'\n ) {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n clientTab[key] = tabProp({ t: i18n.t })\n } else if (key === 'admin') {\n clientTab.admin = {} as AdminClient\n\n for (const adminKey in tab.admin) {\n if (serverOnlyFieldAdminProperties.includes(adminKey as any)) {\n continue\n }\n\n switch (adminKey) {\n case 'description':\n if ('description' in tab.admin) {\n if (typeof tab.admin?.description === 'function') {\n clientTab.admin.description = tab.admin.description({\n i18n,\n t: i18n.t as TFunction,\n })\n } else {\n clientTab.admin.description = tab.admin.description\n }\n }\n\n break\n\n default:\n ;(clientTab.admin as any)[adminKey] =\n tab.admin[adminKey as keyof typeof tab.admin]\n }\n }\n } else {\n ;(clientTab as any)[key] = tabProp\n }\n }\n field.tabs[i] = clientTab\n }\n }\n\n break\n }\n\n default:\n break\n }\n\n return clientField\n}\n\nexport const createClientFields = ({\n defaultIDType,\n disableAddingID,\n fields,\n i18n,\n importMap,\n}: {\n defaultIDType: Payload['config']['db']['defaultIDType']\n disableAddingID?: boolean\n fields: Field[]\n i18n: I18nClient\n importMap: ImportMap\n}): ClientField[] => {\n const clientFields: ClientField[] = []\n\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i]!\n\n const clientField = createClientField({\n defaultIDType,\n field,\n i18n,\n importMap,\n })\n\n clientFields.push(clientField)\n }\n\n const hasID = flattenTopLevelFields(fields).some((f) => fieldAffectsData(f) && f.name === 'id')\n\n if (!disableAddingID && !hasID) {\n clientFields.push({\n name: 'id',\n type: defaultIDType,\n admin: {\n description: 'The unique identifier for this document',\n disableBulkEdit: true,\n disabled: true,\n hidden: true,\n },\n hidden: true,\n label: 'ID',\n } as ClientField)\n }\n\n return clientFields\n}\n"],"names":["getFromImportMap","MissingEditorProp","fieldAffectsData","flattenTopLevelFields","serverOnlyFieldProperties","serverOnlyFieldAdminProperties","createClientBlocks","blocks","defaultIDType","i18n","importMap","clientBlocks","i","length","block","push","clientBlock","slug","fields","imageAltText","imageURL","admin","custom","group","jsx","jsxResolved","PayloadComponent","schemaPath","disableBlockName","labels","singular","t","plural","createClientFields","createClientField","field","incomingField","clientField","key","includes","adminKey","description","label","type","disableAddingID","blockReferences","targetField","relationTo","options","option","value","editor","Error","tabs","tab","clientTab","tabProp","clientFields","hasID","some","f","name","disableBulkEdit","disabled","hidden"],"mappings":"AAAA,oBAAoB;AACpB,iDAAiD,GACjD,gIAAgI;AAsBhI,SAASA,gBAAgB,QAAQ,4DAA2D;AAC5F,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,qBAAqB,QAAwB,iBAAgB;AAwBtE,MAAMC,4BAAkE;IACtE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CAOD;AAED,MAAMC,iCAA4E;IAChF;IACA;CACD;AAMD,OAAO,MAAMC,qBAAqB,CAAC,EACjCC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJC,SAAS,EAMV;IACC,MAAMC,eAAyC,EAAE;IACjD,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAOM,MAAM,EAAED,IAAK;QACtC,MAAME,QAAQP,MAAM,CAACK,EAAE;QAEvB,IAAI,OAAOE,UAAU,UAAU;YAC7B,6FAA6F;YAC7FH,aAAaI,IAAI,CAACD;YAClB;QACF;QAEA,MAAME,cAA2B;YAC/BC,MAAMH,MAAMG,IAAI;YAChBC,QAAQ,EAAE;QACZ;QACA,IAAIJ,MAAMK,YAAY,EAAE;YACtBH,YAAYG,YAAY,GAAGL,MAAMK,YAAY;QAC/C;QACA,IAAIL,MAAMM,QAAQ,EAAE;YAClBJ,YAAYI,QAAQ,GAAGN,MAAMM,QA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7B;wBACF;wBACArB,MAAMkB,IAAI,CAACzC,EAAE,GAAG2C;oBAClB;gBACF;gBAEA;YACF;QAEA;YACE;IACJ;IAEA,OAAOlB;AACT,EAAC;AAED,OAAO,MAAMJ,qBAAqB,CAAC,EACjCzB,aAAa,EACboC,eAAe,EACf1B,MAAM,EACNT,IAAI,EACJC,SAAS,EAOV;IACC,MAAM+C,eAA8B,EAAE;IAEtC,IAAK,IAAI7C,IAAI,GAAGA,IAAIM,OAAOL,MAAM,EAAED,IAAK;QACtC,MAAMuB,QAAQjB,MAAM,CAACN,EAAE;QAEvB,MAAMyB,cAAcH,kBAAkB;YACpC1B;YACA2B;YACA1B;YACAC;QACF;QAEA+C,aAAa1C,IAAI,CAACsB;IACpB;IAEA,MAAMqB,QAAQvD,sBAAsBe,QAAQyC,IAAI,CAAC,CAACC,IAAM1D,iBAAiB0D,MAAMA,EAAEC,IAAI,KAAK;IAE1F,IAAI,CAACjB,mBAAmB,CAACc,OAAO;QAC9BD,aAAa1C,IAAI,CAAC;YAChB8C,MAAM;YACNlB,MAAMnC;YACNa,OAAO;gBACLoB,aAAa;gBACbqB,iBAAiB;gBACjBC,UAAU;gBACVC,QAAQ;YACV;YACAA,QAAQ;YACRtB,OAAO;QACT;IACF;IAEA,OAAOe;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/fields/config/client.ts"],"sourcesContent":["// @ts-strict-ignore\n/* eslint-disable perfectionist/sort-switch-case */\n// Keep perfectionist/sort-switch-case disabled - it incorrectly messes up the ordering of the switch cases, causing it to break\nimport type { I18nClient, TFunction } from '@payloadcms/translations'\n\nimport type {\n AdminClient,\n ArrayFieldClient,\n Block,\n BlockJSX,\n BlocksFieldClient,\n ClientBlock,\n ClientField,\n Field,\n FieldBase,\n JoinFieldClient,\n LabelsClient,\n RadioFieldClient,\n RowFieldClient,\n SelectFieldClient,\n TabsFieldClient,\n} from '../../fields/config/types.js'\nimport type { Payload } from '../../types/index.js'\n\nimport { getFromImportMap } from '../../bin/generateImportMap/utilities/getFromImportMap.js'\nimport { MissingEditorProp } from '../../errors/MissingEditorProp.js'\nimport { fieldAffectsData } from '../../fields/config/types.js'\nimport { flattenTopLevelFields, type ImportMap } from '../../index.js'\n\n// Should not be used - ClientField should be used instead. This is why we don't export ClientField, we don't want people\n// to accidentally use it instead of ClientField and get confused\n\nexport { ClientField }\n\nexport type ServerOnlyFieldProperties =\n | 'dbName' // can be a function\n | 'editor' // This is a `richText` only property\n | 'enumName' // can be a function\n | 'filterOptions' // This is a `relationship`, `upload`, and `select` only property\n | 'graphQL'\n | 'label'\n | 'typescriptSchema'\n | 'validate'\n | keyof Pick<FieldBase, 'access' | 'custom' | 'defaultValue' | 'hooks'>\n\nexport type ServerOnlyFieldAdminProperties = keyof Pick<\n FieldBase['admin'],\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n 'components' | 'condition'\n>\n\nconst serverOnlyFieldProperties: Partial<ServerOnlyFieldProperties>[] = [\n 'hooks',\n 'access',\n 'validate',\n 'defaultValue',\n 'filterOptions', // This is a `relationship`, `upload`, and `select` only property\n 'editor', // This is a `richText` only property\n 'custom',\n 'typescriptSchema',\n 'dbName', // can be a function\n 'enumName', // can be a function\n 'graphQL', // client does not need graphQL\n // the following props are handled separately (see below):\n // `label`\n // `fields`\n // `blocks`\n // `tabs`\n // `admin`\n]\n\nconst serverOnlyFieldAdminProperties: Partial<ServerOnlyFieldAdminProperties>[] = [\n 'condition',\n 'components',\n]\n\ntype FieldWithDescription = {\n admin: AdminClient\n} & ClientField\n\nexport const createClientBlocks = ({\n blocks,\n defaultIDType,\n i18n,\n importMap,\n}: {\n blocks: (Block | string)[]\n defaultIDType: Payload['config']['db']['defaultIDType']\n i18n: I18nClient\n importMap: ImportMap\n}): (ClientBlock | string)[] | ClientBlock[] => {\n const clientBlocks: (ClientBlock | string)[] = []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]!\n\n if (typeof block === 'string') {\n // Do not process blocks that are just strings - they are processed once in the client config\n clientBlocks.push(block)\n continue\n }\n\n const clientBlock: ClientBlock = {\n slug: block.slug,\n fields: [],\n }\n if (block.imageAltText) {\n clientBlock.imageAltText = block.imageAltText\n }\n if (block.imageURL) {\n clientBlock.imageURL = block.imageURL\n }\n\n if (block.admin?.custom || block.admin?.group) {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n clientBlock.admin = {}\n if (block.admin.custom) {\n clientBlock.admin!.custom = block.admin.custom\n }\n if (block.admin.group) {\n clientBlock.admin!.group = block.admin.group\n }\n }\n\n if (block?.admin?.jsx) {\n const jsxResolved = getFromImportMap<BlockJSX>({\n importMap,\n PayloadComponent: block.admin.jsx,\n schemaPath: '',\n })\n clientBlock.jsx = jsxResolved\n }\n\n if (block?.admin?.disableBlockName) {\n // Check for existing admin object, this way we don't have to spread it in\n if (clientBlock.admin) {\n clientBlock.admin.disableBlockName = block.admin.disableBlockName\n } else {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n clientBlock.admin = { disableBlockName: block.admin.disableBlockName }\n }\n }\n\n if (block.labels) {\n clientBlock.labels = {} as unknown as LabelsClient\n\n if (block.labels.singular) {\n if (typeof block.labels.singular === 'function') {\n clientBlock.labels.singular = block.labels.singular({ i18n, t: i18n.t as TFunction })\n } else {\n clientBlock.labels.singular = block.labels.singular\n }\n if (typeof block.labels.plural === 'function') {\n clientBlock.labels.plural = block.labels.plural({ i18n, t: i18n.t as TFunction })\n } else {\n clientBlock.labels.plural = block.labels.plural\n }\n }\n }\n\n clientBlock.fields = createClientFields({\n defaultIDType,\n fields: block.fields,\n i18n,\n importMap,\n })\n\n clientBlocks.push(clientBlock)\n }\n\n return clientBlocks\n}\n\nexport const createClientField = ({\n defaultIDType,\n field: incomingField,\n i18n,\n importMap,\n}: {\n defaultIDType: Payload['config']['db']['defaultIDType']\n field: Field\n i18n: I18nClient\n importMap: ImportMap\n}): ClientField => {\n const clientField: ClientField = {} as ClientField\n\n for (const key in incomingField) {\n if (serverOnlyFieldProperties.includes(key as any)) {\n continue\n }\n\n switch (key) {\n case 'admin':\n if (!incomingField.admin) {\n break\n }\n\n clientField.admin = {} as AdminClient\n\n for (const adminKey in incomingField.admin) {\n if (serverOnlyFieldAdminProperties.includes(adminKey as any)) {\n continue\n }\n\n switch (adminKey) {\n case 'description':\n if ('description' in incomingField.admin) {\n if (typeof incomingField.admin?.description !== 'function') {\n ;(clientField as FieldWithDescription).admin.description =\n incomingField.admin.description\n }\n }\n\n break\n\n default:\n ;(clientField.admin as any)[adminKey] =\n incomingField.admin[adminKey as keyof typeof incomingField.admin]\n }\n }\n\n break\n\n case 'blocks':\n case 'fields':\n case 'tabs':\n // Skip - we handle sub-fields in the switch below\n break\n\n case 'options':\n // Skip - we handle options in the radio/select switch below to avoid mutating the global config\n break\n\n case 'label':\n //@ts-expect-error - would need to type narrow\n if (typeof incomingField.label === 'function') {\n //@ts-expect-error - would need to type narrow\n clientField.label = incomingField.label({ i18n, t: i18n.t })\n } else {\n //@ts-expect-error - would need to type narrow\n clientField.label = incomingField.label\n }\n\n break\n\n default:\n ;(clientField as any)[key] = incomingField[key as keyof Field]\n }\n }\n\n switch (incomingField.type) {\n case 'array': {\n if (incomingField.labels) {\n const field = clientField as unknown as ArrayFieldClient\n\n field.labels = {} as unknown as LabelsClient\n\n if (incomingField.labels.singular) {\n if (typeof incomingField.labels.singular === 'function') {\n field.labels.singular = incomingField.labels.singular({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.singular = incomingField.labels.singular\n }\n if (typeof incomingField.labels.plural === 'function') {\n field.labels.plural = incomingField.labels.plural({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.plural = incomingField.labels.plural\n }\n }\n }\n }\n // falls through\n case 'collapsible':\n case 'group':\n case 'row': {\n const field = clientField as unknown as RowFieldClient\n\n if (!field.fields) {\n field.fields = []\n }\n\n field.fields = createClientFields({\n defaultIDType,\n disableAddingID: incomingField.type !== 'array',\n fields: incomingField.fields,\n i18n,\n importMap,\n })\n\n break\n }\n\n case 'blocks': {\n const field = clientField as unknown as BlocksFieldClient\n\n if (incomingField.labels) {\n field.labels = {} as unknown as LabelsClient\n\n if (incomingField.labels.singular) {\n if (typeof incomingField.labels.singular === 'function') {\n field.labels.singular = incomingField.labels.singular({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.singular = incomingField.labels.singular\n }\n if (typeof incomingField.labels.plural === 'function') {\n field.labels.plural = incomingField.labels.plural({ i18n, t: i18n.t as TFunction })\n } else {\n field.labels.plural = incomingField.labels.plural\n }\n }\n }\n\n if (incomingField.blockReferences?.length) {\n field.blockReferences = createClientBlocks({\n blocks: incomingField.blockReferences,\n defaultIDType,\n i18n,\n importMap,\n })\n }\n\n if (incomingField.blocks?.length) {\n field.blocks = createClientBlocks({\n blocks: incomingField.blocks,\n defaultIDType,\n i18n,\n importMap,\n }) as ClientBlock[]\n }\n\n break\n }\n\n case 'join': {\n const field = clientField as JoinFieldClient\n\n field.targetField = {\n relationTo: field.targetField?.relationTo,\n }\n\n break\n }\n\n case 'radio':\n // falls through\n case 'select': {\n const field = clientField as RadioFieldClient | SelectFieldClient\n\n if (incomingField.options?.length) {\n field.options = [] // Create new array to avoid mutating global config\n\n for (let i = 0; i < incomingField.options.length; i++) {\n const option = incomingField.options[i]\n\n if (typeof option === 'object' && typeof option.label === 'function') {\n field.options[i] = {\n label: option.label({ i18n, t: i18n.t as TFunction }),\n value: option.value,\n }\n } else if (typeof option === 'object') {\n field.options[i] = {\n label: option.label,\n value: option.value,\n }\n } else if (typeof option === 'string') {\n field.options[i] = option\n }\n }\n }\n\n break\n }\n\n case 'richText': {\n if (!incomingField?.editor) {\n throw new MissingEditorProp(incomingField) // while we allow disabling editor functionality, you should not have any richText fields defined if you do not have an editor\n }\n\n if (typeof incomingField?.editor === 'function') {\n throw new Error('Attempted to access unsanitized rich text editor.')\n }\n\n break\n }\n\n case 'tabs': {\n const field = clientField as unknown as TabsFieldClient\n\n if (incomingField.tabs?.length) {\n field.tabs = []\n\n for (let i = 0; i < incomingField.tabs.length; i++) {\n const tab = incomingField.tabs[i]\n const clientTab = {} as unknown as TabsFieldClient['tabs'][0]\n\n for (const key in tab) {\n if (serverOnlyFieldProperties.includes(key as any)) {\n continue\n }\n\n const tabProp = tab[key as keyof typeof tab]\n\n if (key === 'fields') {\n clientTab.fields = createClientFields({\n defaultIDType,\n disableAddingID: true,\n fields: tab.fields,\n i18n,\n importMap,\n })\n } else if (\n (key === 'label' || key === 'description') &&\n typeof tabProp === 'function'\n ) {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n clientTab[key] = tabProp({ t: i18n.t })\n } else if (key === 'admin') {\n clientTab.admin = {} as AdminClient\n\n for (const adminKey in tab.admin) {\n if (serverOnlyFieldAdminProperties.includes(adminKey as any)) {\n continue\n }\n\n switch (adminKey) {\n case 'description':\n if ('description' in tab.admin) {\n if (typeof tab.admin?.description === 'function') {\n clientTab.admin.description = tab.admin.description({\n i18n,\n t: i18n.t as TFunction,\n })\n } else {\n clientTab.admin.description = tab.admin.description\n }\n }\n\n break\n\n default:\n ;(clientTab.admin as any)[adminKey] =\n tab.admin[adminKey as keyof typeof tab.admin]\n }\n }\n } else {\n ;(clientTab as any)[key] = tabProp\n }\n }\n field.tabs[i] = clientTab\n }\n }\n\n break\n }\n\n default:\n break\n }\n\n return clientField\n}\n\nexport const createClientFields = ({\n defaultIDType,\n disableAddingID,\n fields,\n i18n,\n importMap,\n}: {\n defaultIDType: Payload['config']['db']['defaultIDType']\n disableAddingID?: boolean\n fields: Field[]\n i18n: I18nClient\n importMap: ImportMap\n}): ClientField[] => {\n const clientFields: ClientField[] = []\n\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i]!\n\n const clientField = createClientField({\n defaultIDType,\n field,\n i18n,\n importMap,\n })\n\n clientFields.push(clientField)\n }\n\n const hasID = flattenTopLevelFields(fields).some((f) => fieldAffectsData(f) && f.name === 'id')\n\n if (!disableAddingID && !hasID) {\n clientFields.push({\n name: 'id',\n type: defaultIDType,\n admin: {\n description: 'The unique identifier for this document',\n disableBulkEdit: true,\n disabled: true,\n hidden: true,\n },\n hidden: true,\n label: 'ID',\n } as ClientField)\n }\n\n return clientFields\n}\n"],"names":["getFromImportMap","MissingEditorProp","fieldAffectsData","flattenTopLevelFields","serverOnlyFieldProperties","serverOnlyFieldAdminProperties","createClientBlocks","blocks","defaultIDType","i18n","importMap","clientBlocks","i","length","block","push","clientBlock","slug","fields","imageAltText","imageURL","admin","custom","group","jsx","jsxResolved","PayloadComponent","schemaPath","disableBlockName","labels","singular","t","plural","createClientFields","createClientField","field","incomingField","clientField","key","includes","adminKey","description","label","type","disableAddingID","blockReferences","targetField","relationTo","options","option","value","editor","Error","tabs","tab","clientTab","tabProp","clientFields","hasID","some","f","name","disableBulkEdit","disabled","hidden"],"mappings":"AAAA,oBAAoB;AACpB,iDAAiD,GACjD,gIAAgI;AAsBhI,SAASA,gBAAgB,QAAQ,4DAA2D;AAC5F,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,qBAAqB,QAAwB,iBAAgB;AAwBtE,MAAMC,4BAAkE;IACtE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CAOD;AAED,MAAMC,iCAA4E;IAChF;IACA;CACD;AAMD,OAAO,MAAMC,qBAAqB,CAAC,EACjCC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJC,SAAS,EAMV;IACC,MAAMC,eAAyC,EAAE;IACjD,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAOM,MAAM,EAAED,IAAK;QACtC,MAAME,QAAQP,MAAM,CAACK,EAAE;QAEvB,IAAI,OAAOE,UAAU,UAAU;YAC7B,6FAA6F;YAC7FH,aAAaI,IAAI,CAACD;YAClB;QACF;QAEA,MAAME,cAA2B;YAC/BC,MAAMH,MAAMG,IAAI;YAChBC,QAAQ,EAAE;QACZ;QACA,IAAIJ,MAAMK,YAA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AK,AAAQ,CAACmB,SAAS,GACjCc,IAAIjC,KAAK,CAACmB,SAAmC;oCACnD;gCACF;4BACF,OAAO;;gCACHe,SAAiB,CAACjB,IAAI,GAAGkB;4BAC7B;wBACF;wBACArB,MAAMkB,IAAI,CAACzC,EAAE,GAAG2C;oBAClB;gBACF;gBAEA;YACF;QAEA;YACE;IACJ;IAEA,OAAOlB;AACT,EAAC;AAED,OAAO,MAAMJ,qBAAqB,CAAC,EACjCzB,aAAa,EACboC,eAAe,EACf1B,MAAM,EACNT,IAAI,EACJC,SAAS,EAOV;IACC,MAAM+C,eAA8B,EAAE;IAEtC,IAAK,IAAI7C,IAAI,GAAGA,IAAIM,OAAOL,MAAM,EAAED,IAAK;QACtC,MAAMuB,QAAQjB,MAAM,CAACN,EAAE;QAEvB,MAAMyB,cAAcH,kBAAkB;YACpC1B;YACA2B;YACA1B;YACAC;QACF;QAEA+C,aAAa1C,IAAI,CAACsB;IACpB;IAEA,MAAMqB,QAAQvD,sBAAsBe,QAAQyC,IAAI,CAAC,CAACC,IAAM1D,iBAAiB0D,MAAMA,EAAEC,IAAI,KAAK;IAE1F,IAAI,CAACjB,mBAAmB,CAACc,OAAO;QAC9BD,aAAa1C,IAAI,CAAC;YAChB8C,MAAM;YACNlB,MAAMnC;YACNa,OAAO;gBACLoB,aAAa;gBACbqB,iBAAiB;gBACjBC,UAAU;gBACVC,QAAQ;YACV;YACAA,QAAQ;YACRtB,OAAO;QACT;IACF;IAEA,OAAOe;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/kv/adapters/DatabaseKVAdapter.ts"],"sourcesContent":["import type { CollectionConfig } from '../../index.js'\nimport type { Payload, PayloadRequest } from '../../types/index.js'\nimport type { KVAdapter, KVAdapterResult, KVStoreValue } from '../index.js'\n\n/** Mocked `req`, we don't need to use transactions, neither we want `createLocalReq` overhead. */\nconst req = {} as PayloadRequest\n\nexport class DatabaseKVAdapter implements KVAdapter {\n constructor(\n readonly payload: Payload,\n readonly collectionSlug: string,\n ) {}\n\n async clear(): Promise<void> {\n await this.payload.db.deleteMany({\n collection: this.collectionSlug,\n req,\n where: {},\n })\n }\n\n async delete(key: string): Promise<void> {\n await this.payload.db.deleteOne({\n collection: this.collectionSlug,\n req,\n where: { key: { equals: key } },\n })\n }\n\n async get<T extends KVStoreValue>(key: string): Promise<null | T> {\n const doc = await this.payload.db.findOne<{\n data: T\n id: number | string\n }>({\n collection: this.collectionSlug,\n joins: false,\n req,\n select: {\n data: true,\n key: true,\n },\n where: { key: { equals: key } },\n })\n\n if (doc === null) {\n return null\n }\n\n return doc.data\n }\n\n async has(key: string): Promise<boolean> {\n const { totalDocs } = await this.payload.db.count({\n collection: this.collectionSlug,\n req,\n where: { key: { equals: key } },\n })\n\n return totalDocs > 0\n }\n\n async keys(): Promise<string[]> {\n const result = await this.payload.db.find<{ key: string }>({\n collection: this.collectionSlug,\n limit: 0,\n pagination: false,\n req,\n select: {\n key: true,\n },\n })\n\n return result.docs.map((each) => each.key)\n }\n\n async set(key: string, data: KVStoreValue): Promise<void> {\n await this.payload.db.upsert({\n collection: this.collectionSlug,\n data: {\n data,\n key,\n },\n joins: false,\n req,\n select: {},\n where: { key: { equals: key } },\n })\n }\n}\n\nexport type DatabaseKVAdapterOptions = {\n /** Override options for the generated collection */\n kvCollectionOverrides?: Partial<CollectionConfig>\n}\n\nexport const databaseKVAdapter = (options: DatabaseKVAdapterOptions = {}): KVAdapterResult => {\n const collectionSlug = options.kvCollectionOverrides?.slug ?? 'payload-kv'\n return {\n init: ({ payload }) => new DatabaseKVAdapter(payload, collectionSlug),\n kvCollection: {\n slug: collectionSlug,\n access: {\n create: () => false,\n delete: () => false,\n read: () => false,\n update: () => false,\n },\n admin: {\n hidden: true,\n },\n fields: [\n {\n name: 'key',\n type: 'text',\n index: true,\n required: true,\n unique: true,\n },\n {\n name: 'data',\n type: 'json',\n required: true,\n },\n ],\n lockDocuments: false,\n timestamps: false,\n ...options.kvCollectionOverrides,\n },\n }\n}\n"],"names":["req","DatabaseKVAdapter","
|
|
1
|
+
{"version":3,"sources":["../../../src/kv/adapters/DatabaseKVAdapter.ts"],"sourcesContent":["import type { CollectionConfig } from '../../index.js'\nimport type { Payload, PayloadRequest } from '../../types/index.js'\nimport type { KVAdapter, KVAdapterResult, KVStoreValue } from '../index.js'\n\n/** Mocked `req`, we don't need to use transactions, neither we want `createLocalReq` overhead. */\nconst req = {} as PayloadRequest\n\nexport class DatabaseKVAdapter implements KVAdapter {\n constructor(\n readonly payload: Payload,\n readonly collectionSlug: string,\n ) {}\n\n async clear(): Promise<void> {\n await this.payload.db.deleteMany({\n collection: this.collectionSlug,\n req,\n where: {},\n })\n }\n\n async delete(key: string): Promise<void> {\n await this.payload.db.deleteOne({\n collection: this.collectionSlug,\n req,\n where: { key: { equals: key } },\n })\n }\n\n async get<T extends KVStoreValue>(key: string): Promise<null | T> {\n const doc = await this.payload.db.findOne<{\n data: T\n id: number | string\n }>({\n collection: this.collectionSlug,\n joins: false,\n req,\n select: {\n data: true,\n key: true,\n },\n where: { key: { equals: key } },\n })\n\n if (doc === null) {\n return null\n }\n\n return doc.data\n }\n\n async has(key: string): Promise<boolean> {\n const { totalDocs } = await this.payload.db.count({\n collection: this.collectionSlug,\n req,\n where: { key: { equals: key } },\n })\n\n return totalDocs > 0\n }\n\n async keys(): Promise<string[]> {\n const result = await this.payload.db.find<{ key: string }>({\n collection: this.collectionSlug,\n limit: 0,\n pagination: false,\n req,\n select: {\n key: true,\n },\n })\n\n return result.docs.map((each) => each.key)\n }\n\n async set(key: string, data: KVStoreValue): Promise<void> {\n await this.payload.db.upsert({\n collection: this.collectionSlug,\n data: {\n data,\n key,\n },\n joins: false,\n req,\n select: {},\n where: { key: { equals: key } },\n })\n }\n}\n\nexport type DatabaseKVAdapterOptions = {\n /** Override options for the generated collection */\n kvCollectionOverrides?: Partial<CollectionConfig>\n}\n\nexport const databaseKVAdapter = (options: DatabaseKVAdapterOptions = {}): KVAdapterResult => {\n const collectionSlug = options.kvCollectionOverrides?.slug ?? 'payload-kv'\n return {\n init: ({ payload }) => new DatabaseKVAdapter(payload, collectionSlug),\n kvCollection: {\n slug: collectionSlug,\n access: {\n create: () => false,\n delete: () => false,\n read: () => false,\n update: () => false,\n },\n admin: {\n hidden: true,\n },\n fields: [\n {\n name: 'key',\n type: 'text',\n index: true,\n required: true,\n unique: true,\n },\n {\n name: 'data',\n type: 'json',\n required: true,\n },\n ],\n lockDocuments: false,\n timestamps: false,\n ...options.kvCollectionOverrides,\n },\n }\n}\n"],"names":["req","DatabaseKVAdapter","payload","collectionSlug","clear","db","deleteMany","collection","where","delete","key","deleteOne","equals","get","doc","findOne","joins","select","data","has","totalDocs","count","keys","result","find","limit","pagination","docs","map","each","set","upsert","databaseKVAdapter","options","kvCollectionOverrides","slug","init","kvCollection","access","create","read","update","admin","hidden","fields","name","type","index","required","unique","lockDocuments","timestamps"],"mappings":"AAIA,gGAAgG,GAChG,MAAMA,MAAM,CAAC;AAEb,OAAO,MAAMC;;;IACX,YACE,AAASC,OAAgB,EACzB,AAASC,cAAsB,CAC/B;aAFSD,UAAAA;aACAC,iBAAAA;IACR;IAEH,MAAMC,QAAuB;QAC3B,MAAM,IAAI,CAACF,OAAO,CAACG,EAAE,CAACC,UAAU,CAAC;YAC/BC,YAAY,IAAI,CAACJ,cAAc;YAC/BH;YACAQ,OAAO,CAAC;QACV;IACF;IAEA,MAAMC,OAAOC,GAAW,EAAiB;QACvC,MAAM,IAAI,CAACR,OAAO,CAACG,EAAE,CAACM,SAAS,CAAC;YAC9BJ,YAAY,IAAI,CAACJ,cAAc;YAC/BH;YACAQ,OAAO;gBAAEE,KAAK;oBAAEE,QAAQF;gBAAI;YAAE;QAChC;IACF;IAEA,MAAMG,IAA4BH,GAAW,EAAqB;QAChE,MAAMI,MAAM,MAAM,IAAI,CAACZ,OAAO,CAACG,EAAE,CAACU,OAAO,CAGtC;YACDR,YAAY,IAAI,CAACJ,cAAc;YAC/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;YACZF,MAAMhC;YACNmC,QAAQ;gBACNC,QAAQ,IAAM;gBACd9B,QAAQ,IAAM;gBACd+B,MAAM,IAAM;gBACZC,QAAQ,IAAM;YAChB;YACAC,OAAO;gBACLC,QAAQ;YACV;YACAC,QAAQ;gBACN;oBACEC,MAAM;oBACNC,MAAM;oBACNC,OAAO;oBACPC,UAAU;oBACVC,QAAQ;gBACV;gBACA;oBACEJ,MAAM;oBACNC,MAAM;oBACNE,UAAU;gBACZ;aACD;YACDE,eAAe;YACfC,YAAY;YACZ,GAAGlB,QAAQC,qBAAqB;QAClC;IACF;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/queues/errors/index.ts"],"sourcesContent":["import type { Job, SingleTaskStatus, WorkflowConfig } from '../../index.js'\nimport type { RetryConfig, TaskConfig } from '../config/types/taskTypes.js'\nimport type { TaskParent } from '../operations/runJobs/runJob/getRunTaskFunction.js'\n\nexport type TaskErrorArgs = {\n executedAt: Date\n input?: object\n job: Job\n message: string\n output?: object\n parent?: TaskParent\n retriesConfig: RetryConfig\n taskConfig?: TaskConfig<string>\n taskID: string\n taskSlug: string\n taskStatus: null | SingleTaskStatus<string>\n workflowConfig: WorkflowConfig\n}\n\nexport type WorkflowErrorArgs = {\n job: Job\n message: string\n workflowConfig: WorkflowConfig\n}\n\nexport class TaskError extends Error {\n args: TaskErrorArgs\n constructor(args: TaskErrorArgs) {\n super(args.message)\n this.args = args\n }\n}\nexport class WorkflowError extends Error {\n args: WorkflowErrorArgs\n\n constructor(args: WorkflowErrorArgs) {\n super(args.message)\n this.args = args\n }\n}\n\nexport class JobCancelledError extends Error {\n args: {\n job: Job\n }\n\n constructor(args: { job: Job }) {\n super(`Job ${args.job.id} was cancelled`)\n this.args = args\n }\n}\n"],"names":["TaskError","Error","args","
|
|
1
|
+
{"version":3,"sources":["../../../src/queues/errors/index.ts"],"sourcesContent":["import type { Job, SingleTaskStatus, WorkflowConfig } from '../../index.js'\nimport type { RetryConfig, TaskConfig } from '../config/types/taskTypes.js'\nimport type { TaskParent } from '../operations/runJobs/runJob/getRunTaskFunction.js'\n\nexport type TaskErrorArgs = {\n executedAt: Date\n input?: object\n job: Job\n message: string\n output?: object\n parent?: TaskParent\n retriesConfig: RetryConfig\n taskConfig?: TaskConfig<string>\n taskID: string\n taskSlug: string\n taskStatus: null | SingleTaskStatus<string>\n workflowConfig: WorkflowConfig\n}\n\nexport type WorkflowErrorArgs = {\n job: Job\n message: string\n workflowConfig: WorkflowConfig\n}\n\nexport class TaskError extends Error {\n args: TaskErrorArgs\n constructor(args: TaskErrorArgs) {\n super(args.message)\n this.args = args\n }\n}\nexport class WorkflowError extends Error {\n args: WorkflowErrorArgs\n\n constructor(args: WorkflowErrorArgs) {\n super(args.message)\n this.args = args\n }\n}\n\nexport class JobCancelledError extends Error {\n args: {\n job: Job\n }\n\n constructor(args: { job: Job }) {\n super(`Job ${args.job.id} was cancelled`)\n this.args = args\n }\n}\n"],"names":["TaskError","Error","args","message","WorkflowError","JobCancelledError","job","id"],"mappings":"AAyBA,OAAO,MAAMA,kBAAkBC;IAC7BC,KAAmB;IACnB,YAAYA,IAAmB,CAAE;QAC/B,KAAK,CAACA,KAAKC,OAAO;QAClB,IAAI,CAACD,IAAI,GAAGA;IACd;AACF;AACA,OAAO,MAAME,sBAAsBH;IACjCC,KAAuB;IAEvB,YAAYA,IAAuB,CAAE;QACnC,KAAK,CAACA,KAAKC,OAAO;QAClB,IAAI,CAACD,IAAI,GAAGA;IACd;AACF;AAEA,OAAO,MAAMG,0BAA0BJ;IACrCC,KAEC;IAED,YAAYA,IAAkB,CAAE;QAC9B,KAAK,CAAC,CAAC,IAAI,EAAEA,KAAKI,GAAG,CAACC,EAAE,CAAC,cAAc,CAAC;QACxC,IAAI,CAACL,IAAI,GAAGA;IACd;AACF"}
|
|
@@ -295,8 +295,7 @@ export const runJobs = async (args)=>{
|
|
|
295
295
|
for(const jobID in resultsObject){
|
|
296
296
|
const jobResult = resultsObject[jobID];
|
|
297
297
|
if (jobResult?.status === 'error') {
|
|
298
|
-
remainingJobsFromQueried
|
|
299
|
-
;
|
|
298
|
+
remainingJobsFromQueried++; // Can be retried
|
|
300
299
|
}
|
|
301
300
|
}
|
|
302
301
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/queues/operations/runJobs/index.ts"],"sourcesContent":["import type { Job } from '../../../index.js'\nimport type { PayloadRequest, Sort, Where } from '../../../types/index.js'\nimport type { WorkflowJSON } from '../../config/types/workflowJSONTypes.js'\nimport type { WorkflowConfig, WorkflowHandler } from '../../config/types/workflowTypes.js'\nimport type { RunJobsSilent } from '../../localAPI.js'\nimport type { RunJobResult } from './runJob/index.js'\n\nimport { Forbidden } from '../../../errors/Forbidden.js'\nimport { isolateObjectProperty } from '../../../utilities/isolateObjectProperty.js'\nimport { jobsCollectionSlug } from '../../config/collection.js'\nimport { JobCancelledError } from '../../errors/index.js'\nimport { getCurrentDate } from '../../utilities/getCurrentDate.js'\nimport { updateJob, updateJobs } from '../../utilities/updateJob.js'\nimport { getUpdateJobFunction } from './runJob/getUpdateJobFunction.js'\nimport { importHandlerPath } from './runJob/importHandlerPath.js'\nimport { runJob } from './runJob/index.js'\nimport { runJSONJob } from './runJSONJob/index.js'\n\nexport type RunJobsArgs = {\n /**\n * If you want to run jobs from all queues, set this to true.\n * If you set this to true, the `queue` property will be ignored.\n *\n * @default false\n */\n allQueues?: boolean\n /**\n * ID of the job to run\n */\n id?: number | string\n /**\n * The maximum number of jobs to run in this invocation\n *\n * @default 10\n */\n limit?: number\n overrideAccess?: boolean\n /**\n * Adjust the job processing order\n *\n * FIFO would equal `createdAt` and LIFO would equal `-createdAt`.\n *\n * @default all jobs for all queues will be executed in FIFO order.\n */\n processingOrder?: Sort\n /**\n * If you want to run jobs from a specific queue, set this to the queue name.\n *\n * @default jobs from the `default` queue will be executed.\n */\n queue?: string\n req: PayloadRequest\n /**\n * By default, jobs are run in parallel.\n * If you want to run them in sequence, set this to true.\n */\n sequential?: boolean\n /**\n * If set to true, the job system will not log any output to the console (for both info and error logs).\n * Can be an option for more granular control over logging.\n *\n * This will not automatically affect user-configured logs (e.g. if you call `console.log` or `payload.logger.info` in your job code).\n *\n * @default false\n */\n silent?: RunJobsSilent\n where?: Where\n}\n\nexport type RunJobsResult = {\n jobStatus?: Record<string, RunJobResult>\n /**\n * If this is false, there for sure are no jobs remaining, regardless of the limit\n */\n noJobsRemaining?: boolean\n /**\n * Out of the jobs that were queried & processed (within the set limit), how many are remaining and retryable?\n */\n remainingJobsFromQueried: number\n}\n\nexport const runJobs = async (args: RunJobsArgs): Promise<RunJobsResult> => {\n const {\n id,\n allQueues = false,\n limit = 10,\n overrideAccess,\n processingOrder,\n queue = 'default',\n req,\n req: {\n payload,\n payload: {\n config: { jobs: jobsConfig },\n },\n },\n sequential,\n silent = false,\n where: whereFromProps,\n } = args\n\n if (!overrideAccess) {\n /**\n * By default, jobsConfig.access.run will be `defaultAccess` which is a function that returns `true` if the user is logged in.\n */\n const accessFn = jobsConfig?.access?.run ?? (() => true)\n const hasAccess = await accessFn({ req })\n if (!hasAccess) {\n throw new Forbidden(req.t)\n }\n }\n const and: Where[] = [\n {\n completedAt: {\n exists: false,\n },\n },\n {\n hasError: {\n not_equals: true,\n },\n },\n {\n processing: {\n equals: false,\n },\n },\n {\n or: [\n {\n waitUntil: {\n exists: false,\n },\n },\n {\n waitUntil: {\n less_than: getCurrentDate().toISOString(),\n },\n },\n ],\n },\n ]\n\n if (allQueues !== true) {\n and.push({\n queue: {\n equals: queue ?? 'default',\n },\n })\n }\n\n if (whereFromProps) {\n and.push(whereFromProps)\n }\n\n // Find all jobs and ensure we set job to processing: true as early as possible to reduce the chance of\n // the same job being picked up by another worker\n let jobs: Job[] = []\n\n if (id) {\n // Only one job to run\n const job = await updateJob({\n id,\n data: {\n processing: true,\n },\n depth: jobsConfig.depth,\n disableTransaction: true,\n req,\n returning: true,\n })\n if (job) {\n jobs = [job]\n }\n } else {\n let defaultProcessingOrder: Sort =\n payload.collections[jobsCollectionSlug]?.config.defaultSort ?? 'createdAt'\n\n const processingOrderConfig = jobsConfig.processingOrder\n if (typeof processingOrderConfig === 'function') {\n defaultProcessingOrder = await processingOrderConfig(args)\n } else if (typeof processingOrderConfig === 'object' && !Array.isArray(processingOrderConfig)) {\n if (\n !allQueues &&\n queue &&\n processingOrderConfig.queues &&\n processingOrderConfig.queues[queue]\n ) {\n defaultProcessingOrder = processingOrderConfig.queues[queue]\n } else if (processingOrderConfig.default) {\n defaultProcessingOrder = processingOrderConfig.default\n }\n } else if (typeof processingOrderConfig === 'string') {\n defaultProcessingOrder = processingOrderConfig\n }\n const updatedDocs = await updateJobs({\n data: {\n processing: true,\n },\n depth: jobsConfig.depth,\n disableTransaction: true,\n limit,\n req,\n returning: true,\n sort: processingOrder ?? defaultProcessingOrder,\n where: { and },\n })\n\n if (updatedDocs) {\n jobs = updatedDocs\n }\n }\n\n /**\n * Just for logging purposes, we want to know how many jobs are new and how many are existing (= already been tried).\n * This is only for logs - in the end we still want to run all jobs, regardless of whether they are new or existing.\n */\n const { existingJobs, newJobs } = jobs.reduce(\n (acc, job) => {\n if (job.totalTried > 0) {\n acc.existingJobs.push(job)\n } else {\n acc.newJobs.push(job)\n }\n return acc\n },\n { existingJobs: [] as Job[], newJobs: [] as Job[] },\n )\n\n if (!jobs.length) {\n return {\n noJobsRemaining: true,\n remainingJobsFromQueried: 0,\n }\n }\n\n if (!silent || (typeof silent === 'object' && !silent.info)) {\n payload.logger.info({\n msg: `Running ${jobs.length} jobs.`,\n new: newJobs?.length,\n retrying: existingJobs?.length,\n })\n }\n\n const successfullyCompletedJobs: (number | string)[] = []\n\n const runSingleJob = async (\n job: Job,\n ): Promise<{\n id: number | string\n result: RunJobResult\n }> => {\n if (!job.workflowSlug && !job.taskSlug) {\n throw new Error('Job must have either a workflowSlug or a taskSlug')\n }\n const jobReq = isolateObjectProperty(req, 'transactionID')\n\n const workflowConfig: WorkflowConfig =\n job.workflowSlug && jobsConfig.workflows?.length\n ? jobsConfig.workflows.find(({ slug }) => slug === job.workflowSlug)!\n : {\n slug: 'singleTask',\n handler: async ({ job, tasks }) => {\n await tasks[job.taskSlug as string]!('1', {\n input: job.input,\n })\n },\n }\n\n if (!workflowConfig) {\n return {\n id: job.id,\n result: {\n status: 'error',\n },\n } // Skip jobs with no workflow configuration\n }\n\n try {\n const updateJob = getUpdateJobFunction(job, jobReq)\n\n // the runner will either be passed to the config\n // OR it will be a path, which we will need to import via eval to avoid\n // Next.js compiler dynamic import expression errors\n let workflowHandler: WorkflowHandler | WorkflowJSON\n if (\n typeof workflowConfig.handler === 'function' ||\n (typeof workflowConfig.handler === 'object' && Array.isArray(workflowConfig.handler))\n ) {\n workflowHandler = workflowConfig.handler\n } else {\n workflowHandler = await importHandlerPath<typeof workflowHandler>(workflowConfig.handler)\n\n if (!workflowHandler) {\n const jobLabel = job.workflowSlug || `Task: ${job.taskSlug}`\n const errorMessage = `Can't find runner while importing with the path ${workflowConfig.handler} in job type ${jobLabel}.`\n if (!silent || (typeof silent === 'object' && !silent.error)) {\n payload.logger.error(errorMessage)\n }\n\n await updateJob({\n error: {\n error: errorMessage,\n },\n hasError: true,\n processing: false,\n })\n\n return {\n id: job.id,\n result: {\n status: 'error-reached-max-retries',\n },\n }\n }\n }\n\n if (typeof workflowHandler === 'function') {\n const result = await runJob({\n job,\n req: jobReq,\n silent,\n updateJob,\n workflowConfig,\n workflowHandler,\n })\n\n if (result.status === 'success') {\n successfullyCompletedJobs.push(job.id)\n }\n\n return { id: job.id, result }\n } else {\n const result = await runJSONJob({\n job,\n req: jobReq,\n silent,\n updateJob,\n workflowConfig,\n workflowHandler,\n })\n\n if (result.status === 'success') {\n successfullyCompletedJobs.push(job.id)\n }\n\n return { id: job.id, result }\n }\n } catch (error) {\n if (error instanceof JobCancelledError) {\n return {\n id: job.id,\n result: {\n status: 'error-reached-max-retries',\n },\n }\n }\n throw error\n }\n }\n\n let resultsArray: { id: number | string; result: RunJobResult }[] = []\n if (sequential) {\n for (const job of jobs) {\n const result = await runSingleJob(job)\n if (result) {\n resultsArray.push(result)\n }\n }\n } else {\n const jobPromises = jobs.map(runSingleJob)\n resultsArray = (await Promise.all(jobPromises)) as {\n id: number | string\n result: RunJobResult\n }[]\n }\n\n if (jobsConfig.deleteJobOnComplete && successfullyCompletedJobs.length) {\n try {\n if (jobsConfig.runHooks) {\n await payload.delete({\n collection: jobsCollectionSlug,\n depth: 0, // can be 0 since we're not returning anything\n disableTransaction: true,\n where: { id: { in: successfullyCompletedJobs } },\n })\n } else {\n await payload.db.deleteMany({\n collection: jobsCollectionSlug,\n where: { id: { in: successfullyCompletedJobs } },\n })\n }\n } catch (err) {\n if (!silent || (typeof silent === 'object' && !silent.error)) {\n payload.logger.error({\n err,\n msg: `Failed to delete jobs ${successfullyCompletedJobs.join(', ')} on complete`,\n })\n }\n }\n }\n\n const resultsObject: RunJobsResult['jobStatus'] = resultsArray.reduce(\n (acc, cur) => {\n if (cur !== null) {\n // Check if there's a valid result to include\n acc[cur.id] = cur.result\n }\n return acc\n },\n {} as Record<string, RunJobResult>,\n )\n\n let remainingJobsFromQueried = 0\n for (const jobID in resultsObject) {\n const jobResult = resultsObject[jobID]\n if (jobResult?.status === 'error') {\n remainingJobsFromQueried++ // Can be retried\n }\n }\n\n return {\n jobStatus: resultsObject,\n remainingJobsFromQueried,\n }\n}\n"],"names":["Forbidden","isolateObjectProperty","jobsCollectionSlug","JobCancelledError","getCurrentDate","updateJob","updateJobs","getUpdateJobFunction","importHandlerPath","runJob","runJSONJob","runJobs","args","id","allQueues","limit","overrideAccess","processingOrder","queue","req","payload","config","jobs","jobsConfig","sequential","silent","where","whereFromProps","accessFn","access","run","hasAccess","t","and","completedAt","exists","hasError","not_equals","processing","equals","or","waitUntil","less_than","toISOString","push","job","data","depth","disableTransaction","returning","defaultProcessingOrder","collections","defaultSort","processingOrderConfig","Array","isArray","queues","default","updatedDocs","sort","existingJobs","newJobs","reduce","acc","totalTried","length","noJobsRemaining","remainingJobsFromQueried","info","logger","msg","new","retrying","successfullyCompletedJobs","runSingleJob","workflowSlug","taskSlug","Error","jobReq","workflowConfig","workflows","find","slug","handler","tasks","input","result","status","workflowHandler","jobLabel","errorMessage","error","resultsArray","jobPromises","map","Promise","all","deleteJobOnComplete","runHooks","delete","collection","in","db","deleteMany","err","join","resultsObject","cur","jobID","jobResult","jobStatus"],"mappings":"AAOA,SAASA,SAAS,QAAQ,+BAA8B;AACxD,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,kBAAkB,QAAQ,6BAA4B;AAC/D,SAASC,iBAAiB,QAAQ,wBAAuB;AACzD,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,SAAS,EAAEC,UAAU,QAAQ,+BAA8B;AACpE,SAASC,oBAAoB,QAAQ,mCAAkC;AACvE,SAASC,iBAAiB,QAAQ,gCAA+B;AACjE,SAASC,MAAM,QAAQ,oBAAmB;AAC1C,SAASC,UAAU,QAAQ,wBAAuB;AAiElD,OAAO,MAAMC,UAAU,OAAOC;IAC5B,MAAM,EACJC,EAAE,EACFC,YAAY,KAAK,EACjBC,QAAQ,EAAE,EACVC,cAAc,EACdC,eAAe,EACfC,QAAQ,SAAS,EACjBC,GAAG,EACHA,KAAK,EACHC,OAAO,EACPA,SAAS,EACPC,QAAQ,EAAEC,MAAMC,UAAU,EAAE,EAC7B,EACF,EACDC,UAAU,EACVC,SAAS,KAAK,EACdC,OAAOC,cAAc,EACtB,GAAGf;IAEJ,IAAI,CAACI,gBAAgB;QACnB;;KAEC,GACD,MAAMY,WAAWL,YAAYM,QAAQC,OAAQ,CAAA,IAAM,IAAG;QACtD,MAAMC,YAAY,MAAMH,SAAS;YAAET;QAAI;QACvC,IAAI,CAACY,WAAW;YACd,MAAM,IAAI/B,UAAUmB,IAAIa,CAAC;QAC3B;IACF;IACA,MAAMC,MAAe;QACnB;YACEC,aAAa;gBACXC,QAAQ;YACV;QACF;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,CAACC,UAAU,CAAC;oBAC1BH,YAAYlG;oBACZwB,OAAO;wBAAEb,IAAI;4BAAEwF,IAAI5B;wBAA0B;oBAAE;gBACjD;YACF;QACF,EAAE,OAAO+B,KAAK;YACZ,IAAI,CAAC/E,UAAW,OAAOA,WAAW,YAAY,CAACA,OAAOkE,KAAK,EAAG;gBAC5DvE,QAAQiD,MAAM,CAACsB,KAAK,CAAC;oBACnBa;oBACAlC,KAAK,CAAC,sBAAsB,EAAEG,0BAA0BgC,IAAI,CAAC,MAAM,YAAY,CAAC;gBAClF;YACF;QACF;IACF;IAEA,MAAMC,gBAA4Cd,aAAa9B,MAAM,CACnE,CAACC,KAAK4C;QACJ,IAAIA,QAAQ,MAAM;YAChB,6CAA6C;YAC7C5C,GAAG,CAAC4C,IAAI9F,EAAE,CAAC,GAAG8F,IAAIrB,MAAM;QAC1B;QACA,OAAOvB;IACT,GACA,CAAC;IAGH,IAAII,2BAA2B;IAC/B,IAAK,MAAMyC,SAASF,cAAe;QACjC,MAAMG,YAAYH,aAAa,CAACE,MAAM;QACtC,IAAIC,WAAWtB,WAAW,SAAS;YACjCpB,2BAA2B,iBAAiB;;QAC9C;IACF;IAEA,OAAO;QACL2C,WAAWJ;QACXvC;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/queues/operations/runJobs/index.ts"],"sourcesContent":["import type { Job } from '../../../index.js'\nimport type { PayloadRequest, Sort, Where } from '../../../types/index.js'\nimport type { WorkflowJSON } from '../../config/types/workflowJSONTypes.js'\nimport type { WorkflowConfig, WorkflowHandler } from '../../config/types/workflowTypes.js'\nimport type { RunJobsSilent } from '../../localAPI.js'\nimport type { RunJobResult } from './runJob/index.js'\n\nimport { Forbidden } from '../../../errors/Forbidden.js'\nimport { isolateObjectProperty } from '../../../utilities/isolateObjectProperty.js'\nimport { jobsCollectionSlug } from '../../config/collection.js'\nimport { JobCancelledError } from '../../errors/index.js'\nimport { getCurrentDate } from '../../utilities/getCurrentDate.js'\nimport { updateJob, updateJobs } from '../../utilities/updateJob.js'\nimport { getUpdateJobFunction } from './runJob/getUpdateJobFunction.js'\nimport { importHandlerPath } from './runJob/importHandlerPath.js'\nimport { runJob } from './runJob/index.js'\nimport { runJSONJob } from './runJSONJob/index.js'\n\nexport type RunJobsArgs = {\n /**\n * If you want to run jobs from all queues, set this to true.\n * If you set this to true, the `queue` property will be ignored.\n *\n * @default false\n */\n allQueues?: boolean\n /**\n * ID of the job to run\n */\n id?: number | string\n /**\n * The maximum number of jobs to run in this invocation\n *\n * @default 10\n */\n limit?: number\n overrideAccess?: boolean\n /**\n * Adjust the job processing order\n *\n * FIFO would equal `createdAt` and LIFO would equal `-createdAt`.\n *\n * @default all jobs for all queues will be executed in FIFO order.\n */\n processingOrder?: Sort\n /**\n * If you want to run jobs from a specific queue, set this to the queue name.\n *\n * @default jobs from the `default` queue will be executed.\n */\n queue?: string\n req: PayloadRequest\n /**\n * By default, jobs are run in parallel.\n * If you want to run them in sequence, set this to true.\n */\n sequential?: boolean\n /**\n * If set to true, the job system will not log any output to the console (for both info and error logs).\n * Can be an option for more granular control over logging.\n *\n * This will not automatically affect user-configured logs (e.g. if you call `console.log` or `payload.logger.info` in your job code).\n *\n * @default false\n */\n silent?: RunJobsSilent\n where?: Where\n}\n\nexport type RunJobsResult = {\n jobStatus?: Record<string, RunJobResult>\n /**\n * If this is false, there for sure are no jobs remaining, regardless of the limit\n */\n noJobsRemaining?: boolean\n /**\n * Out of the jobs that were queried & processed (within the set limit), how many are remaining and retryable?\n */\n remainingJobsFromQueried: number\n}\n\nexport const runJobs = async (args: RunJobsArgs): Promise<RunJobsResult> => {\n const {\n id,\n allQueues = false,\n limit = 10,\n overrideAccess,\n processingOrder,\n queue = 'default',\n req,\n req: {\n payload,\n payload: {\n config: { jobs: jobsConfig },\n },\n },\n sequential,\n silent = false,\n where: whereFromProps,\n } = args\n\n if (!overrideAccess) {\n /**\n * By default, jobsConfig.access.run will be `defaultAccess` which is a function that returns `true` if the user is logged in.\n */\n const accessFn = jobsConfig?.access?.run ?? (() => true)\n const hasAccess = await accessFn({ req })\n if (!hasAccess) {\n throw new Forbidden(req.t)\n }\n }\n const and: Where[] = [\n {\n completedAt: {\n exists: false,\n },\n },\n {\n hasError: {\n not_equals: true,\n },\n },\n {\n processing: {\n equals: false,\n },\n },\n {\n or: [\n {\n waitUntil: {\n exists: false,\n },\n },\n {\n waitUntil: {\n less_than: getCurrentDate().toISOString(),\n },\n },\n ],\n },\n ]\n\n if (allQueues !== true) {\n and.push({\n queue: {\n equals: queue ?? 'default',\n },\n })\n }\n\n if (whereFromProps) {\n and.push(whereFromProps)\n }\n\n // Find all jobs and ensure we set job to processing: true as early as possible to reduce the chance of\n // the same job being picked up by another worker\n let jobs: Job[] = []\n\n if (id) {\n // Only one job to run\n const job = await updateJob({\n id,\n data: {\n processing: true,\n },\n depth: jobsConfig.depth,\n disableTransaction: true,\n req,\n returning: true,\n })\n if (job) {\n jobs = [job]\n }\n } else {\n let defaultProcessingOrder: Sort =\n payload.collections[jobsCollectionSlug]?.config.defaultSort ?? 'createdAt'\n\n const processingOrderConfig = jobsConfig.processingOrder\n if (typeof processingOrderConfig === 'function') {\n defaultProcessingOrder = await processingOrderConfig(args)\n } else if (typeof processingOrderConfig === 'object' && !Array.isArray(processingOrderConfig)) {\n if (\n !allQueues &&\n queue &&\n processingOrderConfig.queues &&\n processingOrderConfig.queues[queue]\n ) {\n defaultProcessingOrder = processingOrderConfig.queues[queue]\n } else if (processingOrderConfig.default) {\n defaultProcessingOrder = processingOrderConfig.default\n }\n } else if (typeof processingOrderConfig === 'string') {\n defaultProcessingOrder = processingOrderConfig\n }\n const updatedDocs = await updateJobs({\n data: {\n processing: true,\n },\n depth: jobsConfig.depth,\n disableTransaction: true,\n limit,\n req,\n returning: true,\n sort: processingOrder ?? defaultProcessingOrder,\n where: { and },\n })\n\n if (updatedDocs) {\n jobs = updatedDocs\n }\n }\n\n /**\n * Just for logging purposes, we want to know how many jobs are new and how many are existing (= already been tried).\n * This is only for logs - in the end we still want to run all jobs, regardless of whether they are new or existing.\n */\n const { existingJobs, newJobs } = jobs.reduce(\n (acc, job) => {\n if (job.totalTried > 0) {\n acc.existingJobs.push(job)\n } else {\n acc.newJobs.push(job)\n }\n return acc\n },\n { existingJobs: [] as Job[], newJobs: [] as Job[] },\n )\n\n if (!jobs.length) {\n return {\n noJobsRemaining: true,\n remainingJobsFromQueried: 0,\n }\n }\n\n if (!silent || (typeof silent === 'object' && !silent.info)) {\n payload.logger.info({\n msg: `Running ${jobs.length} jobs.`,\n new: newJobs?.length,\n retrying: existingJobs?.length,\n })\n }\n\n const successfullyCompletedJobs: (number | string)[] = []\n\n const runSingleJob = async (\n job: Job,\n ): Promise<{\n id: number | string\n result: RunJobResult\n }> => {\n if (!job.workflowSlug && !job.taskSlug) {\n throw new Error('Job must have either a workflowSlug or a taskSlug')\n }\n const jobReq = isolateObjectProperty(req, 'transactionID')\n\n const workflowConfig: WorkflowConfig =\n job.workflowSlug && jobsConfig.workflows?.length\n ? jobsConfig.workflows.find(({ slug }) => slug === job.workflowSlug)!\n : {\n slug: 'singleTask',\n handler: async ({ job, tasks }) => {\n await tasks[job.taskSlug as string]!('1', {\n input: job.input,\n })\n },\n }\n\n if (!workflowConfig) {\n return {\n id: job.id,\n result: {\n status: 'error',\n },\n } // Skip jobs with no workflow configuration\n }\n\n try {\n const updateJob = getUpdateJobFunction(job, jobReq)\n\n // the runner will either be passed to the config\n // OR it will be a path, which we will need to import via eval to avoid\n // Next.js compiler dynamic import expression errors\n let workflowHandler: WorkflowHandler | WorkflowJSON\n if (\n typeof workflowConfig.handler === 'function' ||\n (typeof workflowConfig.handler === 'object' && Array.isArray(workflowConfig.handler))\n ) {\n workflowHandler = workflowConfig.handler\n } else {\n workflowHandler = await importHandlerPath<typeof workflowHandler>(workflowConfig.handler)\n\n if (!workflowHandler) {\n const jobLabel = job.workflowSlug || `Task: ${job.taskSlug}`\n const errorMessage = `Can't find runner while importing with the path ${workflowConfig.handler} in job type ${jobLabel}.`\n if (!silent || (typeof silent === 'object' && !silent.error)) {\n payload.logger.error(errorMessage)\n }\n\n await updateJob({\n error: {\n error: errorMessage,\n },\n hasError: true,\n processing: false,\n })\n\n return {\n id: job.id,\n result: {\n status: 'error-reached-max-retries',\n },\n }\n }\n }\n\n if (typeof workflowHandler === 'function') {\n const result = await runJob({\n job,\n req: jobReq,\n silent,\n updateJob,\n workflowConfig,\n workflowHandler,\n })\n\n if (result.status === 'success') {\n successfullyCompletedJobs.push(job.id)\n }\n\n return { id: job.id, result }\n } else {\n const result = await runJSONJob({\n job,\n req: jobReq,\n silent,\n updateJob,\n workflowConfig,\n workflowHandler,\n })\n\n if (result.status === 'success') {\n successfullyCompletedJobs.push(job.id)\n }\n\n return { id: job.id, result }\n }\n } catch (error) {\n if (error instanceof JobCancelledError) {\n return {\n id: job.id,\n result: {\n status: 'error-reached-max-retries',\n },\n }\n }\n throw error\n }\n }\n\n let resultsArray: { id: number | string; result: RunJobResult }[] = []\n if (sequential) {\n for (const job of jobs) {\n const result = await runSingleJob(job)\n if (result) {\n resultsArray.push(result)\n }\n }\n } else {\n const jobPromises = jobs.map(runSingleJob)\n resultsArray = (await Promise.all(jobPromises)) as {\n id: number | string\n result: RunJobResult\n }[]\n }\n\n if (jobsConfig.deleteJobOnComplete && successfullyCompletedJobs.length) {\n try {\n if (jobsConfig.runHooks) {\n await payload.delete({\n collection: jobsCollectionSlug,\n depth: 0, // can be 0 since we're not returning anything\n disableTransaction: true,\n where: { id: { in: successfullyCompletedJobs } },\n })\n } else {\n await payload.db.deleteMany({\n collection: jobsCollectionSlug,\n where: { id: { in: successfullyCompletedJobs } },\n })\n }\n } catch (err) {\n if (!silent || (typeof silent === 'object' && !silent.error)) {\n payload.logger.error({\n err,\n msg: `Failed to delete jobs ${successfullyCompletedJobs.join(', ')} on complete`,\n })\n }\n }\n }\n\n const resultsObject: RunJobsResult['jobStatus'] = resultsArray.reduce(\n (acc, cur) => {\n if (cur !== null) {\n // Check if there's a valid result to include\n acc[cur.id] = cur.result\n }\n return acc\n },\n {} as Record<string, RunJobResult>,\n )\n\n let remainingJobsFromQueried = 0\n for (const jobID in resultsObject) {\n const jobResult = resultsObject[jobID]\n if (jobResult?.status === 'error') {\n remainingJobsFromQueried++ // Can be retried\n }\n }\n\n return {\n jobStatus: resultsObject,\n remainingJobsFromQueried,\n }\n}\n"],"names":["Forbidden","isolateObjectProperty","jobsCollectionSlug","JobCancelledError","getCurrentDate","updateJob","updateJobs","getUpdateJobFunction","importHandlerPath","runJob","runJSONJob","runJobs","args","id","allQueues","limit","overrideAccess","processingOrder","queue","req","payload","config","jobs","jobsConfig","sequential","silent","where","whereFromProps","accessFn","access","run","hasAccess","t","and","completedAt","exists","hasError","not_equals","processing","equals","or","waitUntil","less_than","toISOString","push","job","data","depth","disableTransaction","returning","defaultProcessingOrder","collections","defaultSort","processingOrderConfig","Array","isArray","queues","default","updatedDocs","sort","existingJobs","newJobs","reduce","acc","totalTried","length","noJobsRemaining","remainingJobsFromQueried","info","logger","msg","new","retrying","successfullyCompletedJobs","runSingleJob","workflowSlug","taskSlug","Error","jobReq","workflowConfig","workflows","find","slug","handler","tasks","input","result","status","workflowHandler","jobLabel","errorMessage","error","resultsArray","jobPromises","map","Promise","all","deleteJobOnComplete","runHooks","delete","collection","in","db","deleteMany","err","join","resultsObject","cur","jobID","jobResult","jobStatus"],"mappings":"AAOA,SAASA,SAAS,QAAQ,+BAA8B;AACxD,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,kBAAkB,QAAQ,6BAA4B;AAC/D,SAASC,iBAAiB,QAAQ,wBAAuB;AACzD,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,SAAS,EAAEC,UAAU,QAAQ,+BAA8B;AACpE,SAASC,oBAAoB,QAAQ,mCAAkC;AACvE,SAASC,iBAAiB,QAAQ,gCAA+B;AACjE,SAASC,MAAM,QAAQ,oBAAmB;AAC1C,SAASC,UAAU,QAAQ,w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aAAa,CAACE,MAAM;QACtC,IAAIC,WAAWtB,WAAW,SAAS;YACjCpB,4BAA2B,iBAAiB;QAC9C;IACF;IAEA,OAAO;QACL2C,WAAWJ;QACXvC;IACF;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/uploads/fetchAPI-multipart/utilities.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport { Readable } from 'stream'\n\nimport type { FetchAPIFileUploadOptions } from '../../config/types.js'\n\n// Parameters for safe file name parsing.\nconst SAFE_FILE_NAME_REGEX = /[^\\w-]/g\nconst MAX_EXTENSION_LENGTH = 3\n\n// Parameters to generate unique temporary file names:\nconst TEMP_COUNTER_MAX = 65536\nconst TEMP_PREFIX = 'tmp'\nlet tempCounter = 0\n\n/**\n * Logs message to console if options.debug option set to true.\n */\nexport const debugLog = (options: FetchAPIFileUploadOptions, msg: string) => {\n const opts = options || {}\n if (!opts.debug) {\n return false\n }\n console.log(`Next-file-upload: ${msg}`) // eslint-disable-line\n return true\n}\n\n/**\n * Generates unique temporary file name. e.g. tmp-5000-156788789789.\n */\nexport const getTempFilename = (prefix: string = TEMP_PREFIX) => {\n tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1\n return `${prefix}-${tempCounter}-${Date.now()}`\n}\n\ntype FuncType = (...args: any[]) => any\nexport const isFunc = (value: any): value is FuncType => {\n return typeof value === 'function'\n}\n\n/**\n * Set errorFunc to the same value as successFunc for callback mode.\n */\ntype ErrorFunc = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nconst errorFunc: ErrorFunc = (resolve, reject) => (isFunc(reject) ? reject : resolve)\n\n/**\n * Return a callback function for promise resole/reject args.\n * Ensures that callback is called only once.\n */\ntype PromiseCallback = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nexport const promiseCallback: PromiseCallback = (resolve, reject) => {\n let hasFired = false\n return (err: Error) => {\n if (hasFired) {\n return\n }\n\n hasFired = true\n return err ? errorFunc(resolve, reject)(err) : resolve()\n }\n}\n\n// The default prototypes for both objects and arrays.\n// Used by isSafeFromPollution\nconst OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype)\nconst ARRAY_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Array.prototype)\n\n/**\n * Determines whether a key insertion into an object could result in a prototype pollution\n */\ntype IsSafeFromPollution = (base: any, key: string) => boolean\nexport const isSafeFromPollution: IsSafeFromPollution = (base, key) => {\n // We perform an instanceof check instead of Array.isArray as the former is more\n // permissive for cases in which the object as an Array prototype but was not constructed\n // via an Array constructor or literal.\n const TOUCHES_ARRAY_PROTOTYPE = base instanceof Array && ARRAY_PROTOTYPE_KEYS.includes(key)\n const TOUCHES_OBJECT_PROTOTYPE = OBJECT_PROTOTYPE_KEYS.includes(key)\n\n return !TOUCHES_ARRAY_PROTOTYPE && !TOUCHES_OBJECT_PROTOTYPE\n}\n\n/**\n * Build request field/file objects to return\n */\ntype BuildFields = (instance: any, field: string, value: any) => any\nexport const buildFields: BuildFields = (instance, field, value) => {\n // Do nothing if value is not set.\n if (value === null || value === undefined) {\n return instance\n }\n instance = instance || Object.create(null)\n\n if (!isSafeFromPollution(instance, field)) {\n return instance\n }\n // Non-array fields\n if (!instance[field]) {\n instance[field] = value\n return instance\n }\n // Array fields\n if (instance[field] instanceof Array) {\n instance[field].push(value)\n } else {\n instance[field] = [instance[field], value]\n }\n return instance\n}\n\n/**\n * Creates a folder if it does not exist\n * for file specified in the path variable\n */\ntype CheckAndMakeDir = (fileUploadOptions: FetchAPIFileUploadOptions, filePath: string) => boolean\nexport const checkAndMakeDir: CheckAndMakeDir = (fileUploadOptions, filePath) => {\n if (!fileUploadOptions.createParentPath) {\n return false\n }\n // Check whether folder for the file exists.\n const parentPath = path.dirname(filePath)\n // Create folder if it doesn't exist.\n if (!fs.existsSync(parentPath)) {\n fs.mkdirSync(parentPath, { recursive: true })\n }\n // Checks folder again and return a results.\n return fs.existsSync(parentPath)\n}\n\n/**\n * Delete a file.\n */\ntype DeleteFile = (filePath: string, callback: (args: any) => void) => void\nexport const deleteFile: DeleteFile = (filePath, callback) => fs.unlink(filePath, callback)\n\n/**\n * Copy file via streams\n */\ntype CopyFile = (src: string, dst: string, callback: (err: Error) => void) => void\nconst copyFile: CopyFile = (src, dst, callback) => {\n // cbCalled flag and runCb helps to run cb only once.\n let cbCalled = false\n const runCb = (err?: Error) => {\n if (cbCalled) {\n return\n }\n cbCalled = true\n callback(err!)\n }\n // Create read stream\n const readable = fs.createReadStream(src)\n readable.on('error', runCb)\n // Create write stream\n const writable = fs.createWriteStream(dst)\n writable.on('error', (err: Error) => {\n readable.destroy()\n runCb(err)\n })\n writable.on('close', () => runCb())\n // Copy file via piping streams.\n readable.pipe(writable)\n}\n\n/**\n * moveFile: moves the file from src to dst.\n * Firstly trying to rename the file if no luck copying it to dst and then deleting src.\n */\ntype MoveFile = (\n src: string,\n dst: string,\n callback: (err: Error, renamed?: boolean) => void,\n) => void\nexport const moveFile: MoveFile = (src, dst, callback) =>\n fs.rename(src, dst, (err) => {\n if (err) {\n // Try to copy file if rename didn't work.\n copyFile(src, dst, (cpErr) => (cpErr ? callback(cpErr) : deleteFile(src, callback)))\n return\n }\n // File was renamed successfully: Add true to the callback to indicate that.\n callback(null!, true)\n })\n\n/**\n * Save buffer data to a file.\n * @param {Buffer} buffer - buffer to save to a file.\n * @param {string} filePath - path to a file.\n */\nexport const saveBufferToFile = (\n buffer: Buffer,\n filePath: string,\n callback: (err?: Error) => void,\n) => {\n if (!Buffer.isBuffer(buffer)) {\n return callback(new Error('buffer variable should be type of Buffer!'))\n }\n // Setup readable stream from buffer.\n let streamData = buffer\n const readStream = new Readable()\n readStream._read = () => {\n readStream.push(streamData)\n streamData = null!\n }\n // Setup file system writable stream.\n const fstream = fs.createWriteStream(filePath)\n // console.log(\"Calling saveBuffer\");\n fstream.on('error', (err) => {\n // console.log(\"err cb\")\n callback(err)\n })\n fstream.on('close', () => {\n // console.log(\"close cb\");\n callback()\n })\n // Copy file via piping streams.\n readStream.pipe(fstream)\n}\n\n/**\n * Decodes uriEncoded file names.\n * @param {Object} opts - middleware options.\n * @param fileName {String} - file name to decode.\n * @returns {String}\n */\nconst uriDecodeFileName = (opts: FetchAPIFileUploadOptions, fileName: string) => {\n if (!opts || !opts.uriDecodeFileNames) {\n return fileName\n }\n // Decode file name from URI with checking URI malformed errors.\n // See Issue https://github.com/richardgirges/express-fileupload/issues/342.\n try {\n return decodeURIComponent(fileName)\n } catch (ignore) {\n const matcher = /(%[a-f\\d]{2})/gi\n return fileName\n .split(matcher)\n .map((str) => {\n try {\n return decodeURIComponent(str)\n } catch (ignore) {\n return ''\n }\n })\n .join('')\n }\n}\n\n/**\n * Parses filename and extension and returns object {name, extension}.\n */\ntype ParseFileNameExtension = (\n preserveExtension: boolean | number,\n fileName: string,\n) => {\n extension: string\n name: string\n}\nexport const parseFileNameExtension: ParseFileNameExtension = (preserveExtension, fileName) => {\n const defaultResult = {\n name: fileName,\n extension: '',\n }\n if (!preserveExtension) {\n return defaultResult\n }\n\n // Define maximum extension length\n const maxExtLength =\n typeof preserveExtension === 'boolean' ? MAX_EXTENSION_LENGTH : preserveExtension\n\n const nameParts = fileName.split('.')\n if (nameParts.length < 2) {\n return defaultResult\n }\n\n let extension = nameParts.pop()\n if (extension!.length > maxExtLength && maxExtLength > 0) {\n nameParts[nameParts.length - 1] += '.' + extension!.substr(0, extension!.length - maxExtLength)\n extension = extension!.substr(-maxExtLength)\n }\n\n return {\n name: nameParts.join('.'),\n extension: maxExtLength ? extension! : '',\n }\n}\n\n/**\n * Parse file name and extension.\n */\ntype ParseFileName = (opts: FetchAPIFileUploadOptions, fileName: string) => string\nexport const parseFileName: ParseFileName = (opts, fileName) => {\n // Check fileName argument\n if (!fileName || typeof fileName !== 'string') {\n return getTempFilename()\n }\n // Cut off file name if it's length more then 255.\n let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255)\n // Decode file name if uriDecodeFileNames option set true.\n parsedName = uriDecodeFileName(opts, parsedName)\n // Stop parsing file name if safeFileNames options hasn't been set.\n if (!opts.safeFileNames) {\n return parsedName\n }\n // Set regular expression for the file name.\n const nameRegex =\n typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp\n ? opts.safeFileNames\n : SAFE_FILE_NAME_REGEX\n // Parse file name extension.\n const parsedFileName = parseFileNameExtension(opts.preserveExtension!, parsedName)\n if (parsedFileName.extension.length) {\n parsedFileName.extension = '.' + parsedFileName.extension.replace(nameRegex, '')\n }\n\n return parsedFileName.name.replace(nameRegex, '').concat(parsedFileName.extension)\n}\n"],"names":["fs","path","Readable","SAFE_FILE_NAME_REGEX","MAX_EXTENSION_LENGTH","TEMP_COUNTER_MAX","TEMP_PREFIX","tempCounter","debugLog","options","msg","opts","debug","console","log","getTempFilename","prefix","Date","now","isFunc","value","errorFunc","resolve","reject","promiseCallback","hasFired","err","OBJECT_PROTOTYPE_KEYS","Object","getOwnPropertyNames","prototype","ARRAY_PROTOTYPE_KEYS","Array","isSafeFromPollution","base","key","TOUCHES_ARRAY_PROTOTYPE","includes","TOUCHES_OBJECT_PROTOTYPE","buildFields","instance","field","undefined","create","push","checkAndMakeDir","fileUploadOptions","filePath","createParentPath","parentPath","dirname","existsSync","mkdirSync","recursive","deleteFile","callback","unlink","copyFile","src","dst","cbCalled","runCb","readable","createReadStream","on","writable","createWriteStream","destroy","pipe","moveFile","rename","cpErr","saveBufferToFile","buffer","Buffer","isBuffer","Error","streamData","readStream","_read","fstream","uriDecodeFileName","fileName","uriDecodeFileNames","decodeURIComponent","ignore","matcher","split","map","str","join","parseFileNameExtension","preserveExtension","defaultResult","name","extension","maxExtLength","nameParts","length","pop","substr","parseFileName","parsedName","safeFileNames","nameRegex","RegExp","parsedFileName","replace","concat"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,QAAQ,QAAQ,SAAQ;AAIjC,yCAAyC;AACzC,MA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,OAAO7F,KAAK4F,aAAa,KAAK,YAAY5F,KAAK4F,aAAa,YAAYE,SACpE9F,KAAK4F,aAAa,GAClBpG;IACN,6BAA6B;IAC7B,MAAMuG,iBAAiBf,uBAAuBhF,KAAKiF,iBAAiB,EAAGU;IACvE,IAAII,eAAeX,SAAS,CAACG,MAAM,EAAE;QACnCQ,eAAeX,SAAS,GAAG,MAAMW,eAAeX,SAAS,CAACY,OAAO,CAACH,WAAW;IAC/E;IAEA,OAAOE,eAAeZ,IAAI,CAACa,OAAO,CAACH,WAAW,IAAII,MAAM,CAACF,eAAeX,SAAS;AACnF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/uploads/fetchAPI-multipart/utilities.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport { Readable } from 'stream'\n\nimport type { FetchAPIFileUploadOptions } from '../../config/types.js'\n\n// Parameters for safe file name parsing.\nconst SAFE_FILE_NAME_REGEX = /[^\\w-]/g\nconst MAX_EXTENSION_LENGTH = 3\n\n// Parameters to generate unique temporary file names:\nconst TEMP_COUNTER_MAX = 65536\nconst TEMP_PREFIX = 'tmp'\nlet tempCounter = 0\n\n/**\n * Logs message to console if options.debug option set to true.\n */\nexport const debugLog = (options: FetchAPIFileUploadOptions, msg: string) => {\n const opts = options || {}\n if (!opts.debug) {\n return false\n }\n console.log(`Next-file-upload: ${msg}`) // eslint-disable-line\n return true\n}\n\n/**\n * Generates unique temporary file name. e.g. tmp-5000-156788789789.\n */\nexport const getTempFilename = (prefix: string = TEMP_PREFIX) => {\n tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1\n return `${prefix}-${tempCounter}-${Date.now()}`\n}\n\ntype FuncType = (...args: any[]) => any\nexport const isFunc = (value: any): value is FuncType => {\n return typeof value === 'function'\n}\n\n/**\n * Set errorFunc to the same value as successFunc for callback mode.\n */\ntype ErrorFunc = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nconst errorFunc: ErrorFunc = (resolve, reject) => (isFunc(reject) ? reject : resolve)\n\n/**\n * Return a callback function for promise resole/reject args.\n * Ensures that callback is called only once.\n */\ntype PromiseCallback = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nexport const promiseCallback: PromiseCallback = (resolve, reject) => {\n let hasFired = false\n return (err: Error) => {\n if (hasFired) {\n return\n }\n\n hasFired = true\n return err ? errorFunc(resolve, reject)(err) : resolve()\n }\n}\n\n// The default prototypes for both objects and arrays.\n// Used by isSafeFromPollution\nconst OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype)\nconst ARRAY_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Array.prototype)\n\n/**\n * Determines whether a key insertion into an object could result in a prototype pollution\n */\ntype IsSafeFromPollution = (base: any, key: string) => boolean\nexport const isSafeFromPollution: IsSafeFromPollution = (base, key) => {\n // We perform an instanceof check instead of Array.isArray as the former is more\n // permissive for cases in which the object as an Array prototype but was not constructed\n // via an Array constructor or literal.\n const TOUCHES_ARRAY_PROTOTYPE = base instanceof Array && ARRAY_PROTOTYPE_KEYS.includes(key)\n const TOUCHES_OBJECT_PROTOTYPE = OBJECT_PROTOTYPE_KEYS.includes(key)\n\n return !TOUCHES_ARRAY_PROTOTYPE && !TOUCHES_OBJECT_PROTOTYPE\n}\n\n/**\n * Build request field/file objects to return\n */\ntype BuildFields = (instance: any, field: string, value: any) => any\nexport const buildFields: BuildFields = (instance, field, value) => {\n // Do nothing if value is not set.\n if (value === null || value === undefined) {\n return instance\n }\n instance = instance || Object.create(null)\n\n if (!isSafeFromPollution(instance, field)) {\n return instance\n }\n // Non-array fields\n if (!instance[field]) {\n instance[field] = value\n return instance\n }\n // Array fields\n if (instance[field] instanceof Array) {\n instance[field].push(value)\n } else {\n instance[field] = [instance[field], value]\n }\n return instance\n}\n\n/**\n * Creates a folder if it does not exist\n * for file specified in the path variable\n */\ntype CheckAndMakeDir = (fileUploadOptions: FetchAPIFileUploadOptions, filePath: string) => boolean\nexport const checkAndMakeDir: CheckAndMakeDir = (fileUploadOptions, filePath) => {\n if (!fileUploadOptions.createParentPath) {\n return false\n }\n // Check whether folder for the file exists.\n const parentPath = path.dirname(filePath)\n // Create folder if it doesn't exist.\n if (!fs.existsSync(parentPath)) {\n fs.mkdirSync(parentPath, { recursive: true })\n }\n // Checks folder again and return a results.\n return fs.existsSync(parentPath)\n}\n\n/**\n * Delete a file.\n */\ntype DeleteFile = (filePath: string, callback: (args: any) => void) => void\nexport const deleteFile: DeleteFile = (filePath, callback) => fs.unlink(filePath, callback)\n\n/**\n * Copy file via streams\n */\ntype CopyFile = (src: string, dst: string, callback: (err: Error) => void) => void\nconst copyFile: CopyFile = (src, dst, callback) => {\n // cbCalled flag and runCb helps to run cb only once.\n let cbCalled = false\n const runCb = (err?: Error) => {\n if (cbCalled) {\n return\n }\n cbCalled = true\n callback(err!)\n }\n // Create read stream\n const readable = fs.createReadStream(src)\n readable.on('error', runCb)\n // Create write stream\n const writable = fs.createWriteStream(dst)\n writable.on('error', (err: Error) => {\n readable.destroy()\n runCb(err)\n })\n writable.on('close', () => runCb())\n // Copy file via piping streams.\n readable.pipe(writable)\n}\n\n/**\n * moveFile: moves the file from src to dst.\n * Firstly trying to rename the file if no luck copying it to dst and then deleting src.\n */\ntype MoveFile = (\n src: string,\n dst: string,\n callback: (err: Error, renamed?: boolean) => void,\n) => void\nexport const moveFile: MoveFile = (src, dst, callback) =>\n fs.rename(src, dst, (err) => {\n if (err) {\n // Try to copy file if rename didn't work.\n copyFile(src, dst, (cpErr) => (cpErr ? callback(cpErr) : deleteFile(src, callback)))\n return\n }\n // File was renamed successfully: Add true to the callback to indicate that.\n callback(null!, true)\n })\n\n/**\n * Save buffer data to a file.\n * @param {Buffer} buffer - buffer to save to a file.\n * @param {string} filePath - path to a file.\n */\nexport const saveBufferToFile = (\n buffer: Buffer,\n filePath: string,\n callback: (err?: Error) => void,\n) => {\n if (!Buffer.isBuffer(buffer)) {\n return callback(new Error('buffer variable should be type of Buffer!'))\n }\n // Setup readable stream from buffer.\n let streamData = buffer\n const readStream = new Readable()\n readStream._read = () => {\n readStream.push(streamData)\n streamData = null!\n }\n // Setup file system writable stream.\n const fstream = fs.createWriteStream(filePath)\n // console.log(\"Calling saveBuffer\");\n fstream.on('error', (err) => {\n // console.log(\"err cb\")\n callback(err)\n })\n fstream.on('close', () => {\n // console.log(\"close cb\");\n callback()\n })\n // Copy file via piping streams.\n readStream.pipe(fstream)\n}\n\n/**\n * Decodes uriEncoded file names.\n * @param {Object} opts - middleware options.\n * @param fileName {String} - file name to decode.\n * @returns {String}\n */\nconst uriDecodeFileName = (opts: FetchAPIFileUploadOptions, fileName: string) => {\n if (!opts || !opts.uriDecodeFileNames) {\n return fileName\n }\n // Decode file name from URI with checking URI malformed errors.\n // See Issue https://github.com/richardgirges/express-fileupload/issues/342.\n try {\n return decodeURIComponent(fileName)\n } catch (ignore) {\n const matcher = /(%[a-f\\d]{2})/gi\n return fileName\n .split(matcher)\n .map((str) => {\n try {\n return decodeURIComponent(str)\n } catch (ignore) {\n return ''\n }\n })\n .join('')\n }\n}\n\n/**\n * Parses filename and extension and returns object {name, extension}.\n */\ntype ParseFileNameExtension = (\n preserveExtension: boolean | number,\n fileName: string,\n) => {\n extension: string\n name: string\n}\nexport const parseFileNameExtension: ParseFileNameExtension = (preserveExtension, fileName) => {\n const defaultResult = {\n name: fileName,\n extension: '',\n }\n if (!preserveExtension) {\n return defaultResult\n }\n\n // Define maximum extension length\n const maxExtLength =\n typeof preserveExtension === 'boolean' ? MAX_EXTENSION_LENGTH : preserveExtension\n\n const nameParts = fileName.split('.')\n if (nameParts.length < 2) {\n return defaultResult\n }\n\n let extension = nameParts.pop()\n if (extension!.length > maxExtLength && maxExtLength > 0) {\n nameParts[nameParts.length - 1] += '.' + extension!.substr(0, extension!.length - maxExtLength)\n extension = extension!.substr(-maxExtLength)\n }\n\n return {\n name: nameParts.join('.'),\n extension: maxExtLength ? extension! : '',\n }\n}\n\n/**\n * Parse file name and extension.\n */\ntype ParseFileName = (opts: FetchAPIFileUploadOptions, fileName: string) => string\nexport const parseFileName: ParseFileName = (opts, fileName) => {\n // Check fileName argument\n if (!fileName || typeof fileName !== 'string') {\n return getTempFilename()\n }\n // Cut off file name if it's length more then 255.\n let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255)\n // Decode file name if uriDecodeFileNames option set true.\n parsedName = uriDecodeFileName(opts, parsedName)\n // Stop parsing file name if safeFileNames options hasn't been set.\n if (!opts.safeFileNames) {\n return parsedName\n }\n // Set regular expression for the file name.\n const nameRegex =\n typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp\n ? opts.safeFileNames\n : SAFE_FILE_NAME_REGEX\n // Parse file name extension.\n const parsedFileName = parseFileNameExtension(opts.preserveExtension!, parsedName)\n if (parsedFileName.extension.length) {\n parsedFileName.extension = '.' + parsedFileName.extension.replace(nameRegex, '')\n }\n\n return parsedFileName.name.replace(nameRegex, '').concat(parsedFileName.extension)\n}\n"],"names":["fs","path","Readable","SAFE_FILE_NAME_REGEX","MAX_EXTENSION_LENGTH","TEMP_COUNTER_MAX","TEMP_PREFIX","tempCounter","debugLog","options","msg","opts","debug","console","log","getTempFilename","prefix","Date","now","isFunc","value","errorFunc","resolve","reject","promiseCallback","hasFired","err","OBJECT_PROTOTYPE_KEYS","Object","getOwnPropertyNames","prototype","ARRAY_PROTOTYPE_KEYS","Array","isSafeFromPollution","base","key","TOUCHES_ARRAY_PROTOTYPE","includes","TOUCHES_OBJECT_PROTOTYPE","buildFields","instance","field","undefined","create","push","checkAndMakeDir","fileUploadOptions","filePath","createParentPath","parentPath","dirname","existsSync","mkdirSync","recursive","deleteFile","callback","unlink","copyFile","src","dst","cbCalled","runCb","readable","createReadStream","on","writable","createWriteStream","destroy","pipe","moveFile","rename","cpErr","saveBufferToFile","buffer","Buffer","isBuffer","Error","streamData","readStream","_read","fstream","uriDecodeFileName","fileName","uriDecodeFileNames","decodeURIComponent","ignore","matcher","split","map","str","join","parseFileNameExtension","preserveExtension","defaultResult","name","extension","maxExtLength","nameParts","length","pop","substr","parseFileName","parsedName","safeFileNames","nameRegex","RegExp","parsedFileName","replace","concat"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,QAAQ,QAAQ,SAAQ;AAIjC,yCAAyC;AACzC,MAAMC,uBAAuB;AAC7B,MAAMC,uBAAuB;AAE7B,sDAAsD;AACtD,MAAMC,mBAAmB;AACzB,MAAMC,cAAc;AACpB,IAAIC,cAAc;AAElB;;CAEC,GACD,OAAO,MAAMC,WAAW,CAACC,SAAoCC;IAC3D,MAAMC,OAAOF,WAAW,CAAC;IACzB,IAAI,CAACE,KAAKC,KAAK,EAAE;QACf,OAAO;IACT;IACAC,QAAQC,GAAG,CAAC,CAAC,kBAAkB,EAAEJ,KAAK,GAAE,sBAAsB;IAC9D,OAAO;AACT,EAAC;AAED;;CAEC,GACD,OAAO,MAAMK,kBAAkB,CAACC,SAAiBV,WAAW;IAC1DC,cAAcA,eAAeF,mBAAmB,IAAIE,cAAc;IAClE,OAAO,GAAGS,OAAO,CAAC,EAAET,YAAY,CAAC,EAAEU,KAAKC,GAAG,IAAI;AACjD,EAAC;AAGD,OAAO,MAAMC,SAAS,CAACC;IACrB,OAAO,OAAOA,UAAU;AAC1B,EAAC;AAMD,MAAMC,YAAuB,CAACC,SAASC,SAAYJ,OAAOI,UAAUA,SAASD;AAO7E,OAAO,MAAME,kBAAmC,CAACF,SAASC;IACxD,IAAIE,WAAW;IACf,OAAO,CAACC;QACN,IAAID,UAAU;YACZ;QACF;QAEAA,WAAW;QACX,OAAOC,MAAML,UAAUC,SAASC,QAAQG,OAAOJ;IACjD;AACF,EAAC;AAED,sDAAsD;AACtD,8BAA8B;AAC9B,MAAMK,wBAAwBC,OAAOC,mBAAmB,CAACD,OAAOE,SAAS;AACzE,MAAMC,uBAAuBH,OAAOC,mBAAmB,CAACG,MAAMF,SAAS;AAMvE,OAAO,MAAMG,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AAapB,SAASgB,MAAM,IAAI,MAAMhB,WAAWA,SAASkB,MAAM,CAAC,GAAG;IACxE,0DAA0D;IAC1DE,aAAarB,kBAAkBtE,MAAM2F;IACrC,mEAAmE;IACnE,IAAI,CAAC3F,KAAK4F,aAAa,EAAE;QACvB,OAAOD;IACT;IACA,4CAA4C;IAC5C,MAAME,YACJ,OAAO7F,KAAK4F,aAAa,KAAK,YAAY5F,KAAK4F,aAAa,YAAYE,SACpE9F,KAAK4F,aAAa,GAClBpG;IACN,6BAA6B;IAC7B,MAAMuG,iBAAiBf,uBAAuBhF,KAAKiF,iBAAiB,EAAGU;IACvE,IAAII,eAAeX,SAAS,CAACG,MAAM,EAAE;QACnCQ,eAAeX,SAAS,GAAG,MAAMW,eAAeX,SAAS,CAACY,OAAO,CAACH,WAAW;IAC/E;IAEA,OAAOE,eAAeZ,IAAI,CAACa,OAAO,CAACH,WAAW,IAAII,MAAM,CAACF,eAAeX,SAAS;AACnF,EAAC"}
|
|
@@ -120,11 +120,9 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
120
120
|
}
|
|
121
121
|
if (sharp && (fileIsAnimatedType || fileHasAdjustments)) {
|
|
122
122
|
if (file.tempFilePath) {
|
|
123
|
-
sharpFile = sharp(file.tempFilePath, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081
|
|
124
|
-
;
|
|
123
|
+
sharpFile = sharp(file.tempFilePath, sharpOptions).rotate(); // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081
|
|
125
124
|
} else {
|
|
126
|
-
sharpFile = sharp(file.data, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081
|
|
127
|
-
;
|
|
125
|
+
sharpFile = sharp(file.data, sharpOptions).rotate(); // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081
|
|
128
126
|
}
|
|
129
127
|
if (fileHasAdjustments) {
|
|
130
128
|
if (resizeOptions) {
|
|
@@ -246,8 +244,7 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
246
244
|
fileData.filesize = info.size;
|
|
247
245
|
}
|
|
248
246
|
if (file.tempFilePath) {
|
|
249
|
-
await fs.writeFile(file.tempFilePath, croppedImage) // write fileBuffer to the temp path
|
|
250
|
-
;
|
|
247
|
+
await fs.writeFile(file.tempFilePath, croppedImage); // write fileBuffer to the temp path
|
|
251
248
|
} else {
|
|
252
249
|
req.file = fileForResize;
|
|
253
250
|
}
|
|
@@ -259,8 +256,7 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
259
256
|
// If using temp files and the image is being resized, write the file to the temp path
|
|
260
257
|
if (fileBuffer?.data || file.data.length > 0) {
|
|
261
258
|
if (file.tempFilePath) {
|
|
262
|
-
await fs.writeFile(file.tempFilePath, fileBuffer?.data || file.data) // write fileBuffer to the temp path
|
|
263
|
-
;
|
|
259
|
+
await fs.writeFile(file.tempFilePath, fileBuffer?.data || file.data); // write fileBuffer to the temp path
|
|
264
260
|
} else {
|
|
265
261
|
// Assign the _possibly modified_ file to the request object
|
|
266
262
|
req.file = {
|