payload 4.0.0-internal.cd69eef → 4.0.0-internal.d1cc1d3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/dist/admin/RichText.d.ts +1 -1
  2. package/dist/admin/RichText.d.ts.map +1 -1
  3. package/dist/admin/RichText.js.map +1 -1
  4. package/dist/admin/functions/index.d.ts +10 -8
  5. package/dist/admin/functions/index.d.ts.map +1 -1
  6. package/dist/admin/functions/index.js.map +1 -1
  7. package/dist/admin/types.d.ts +2 -2
  8. package/dist/admin/types.d.ts.map +1 -1
  9. package/dist/admin/types.js.map +1 -1
  10. package/dist/auth/endpoints/login.d.ts.map +1 -1
  11. package/dist/auth/endpoints/login.js +2 -11
  12. package/dist/auth/endpoints/login.js.map +1 -1
  13. package/dist/auth/loginWithCookie.d.ts +33 -0
  14. package/dist/auth/loginWithCookie.d.ts.map +1 -0
  15. package/dist/auth/loginWithCookie.js +34 -0
  16. package/dist/auth/loginWithCookie.js.map +1 -0
  17. package/dist/auth/serverFunctions/cookies.d.ts +47 -0
  18. package/dist/auth/serverFunctions/cookies.d.ts.map +1 -0
  19. package/dist/auth/serverFunctions/cookies.js +52 -0
  20. package/dist/auth/serverFunctions/cookies.js.map +1 -0
  21. package/dist/auth/serverFunctions/login.d.ts +29 -0
  22. package/dist/auth/serverFunctions/login.d.ts.map +1 -0
  23. package/dist/auth/serverFunctions/login.js +63 -0
  24. package/dist/auth/serverFunctions/login.js.map +1 -0
  25. package/dist/auth/serverFunctions/logout.d.ts +17 -0
  26. package/dist/auth/serverFunctions/logout.d.ts.map +1 -0
  27. package/dist/auth/serverFunctions/logout.js +58 -0
  28. package/dist/auth/serverFunctions/logout.js.map +1 -0
  29. package/dist/auth/serverFunctions/refresh.d.ts +17 -0
  30. package/dist/auth/serverFunctions/refresh.d.ts.map +1 -0
  31. package/dist/auth/serverFunctions/refresh.js +61 -0
  32. package/dist/auth/serverFunctions/refresh.js.map +1 -0
  33. package/dist/collections/config/client.d.ts +2 -3
  34. package/dist/collections/config/client.d.ts.map +1 -1
  35. package/dist/collections/config/client.js +5 -7
  36. package/dist/collections/config/client.js.map +1 -1
  37. package/dist/collections/config/defaults.d.ts.map +1 -1
  38. package/dist/collections/config/defaults.js +1 -0
  39. package/dist/collections/config/defaults.js.map +1 -1
  40. package/dist/collections/config/sanitize.d.ts +3 -8
  41. package/dist/collections/config/sanitize.d.ts.map +1 -1
  42. package/dist/collections/config/sanitize.js +2 -6
  43. package/dist/collections/config/sanitize.js.map +1 -1
  44. package/dist/collections/config/types.d.ts +1 -1
  45. package/dist/collections/config/types.d.ts.map +1 -1
  46. package/dist/collections/config/types.js.map +1 -1
  47. package/dist/collections/config/useAsTitle.spec.js +27 -27
  48. package/dist/collections/config/useAsTitle.spec.js.map +1 -1
  49. package/dist/collections/operations/create.d.ts.map +1 -1
  50. package/dist/collections/operations/create.js +10 -0
  51. package/dist/collections/operations/create.js.map +1 -1
  52. package/dist/collections/operations/restoreVersion.d.ts.map +1 -1
  53. package/dist/collections/operations/restoreVersion.js +7 -4
  54. package/dist/collections/operations/restoreVersion.js.map +1 -1
  55. package/dist/collections/operations/updateByID.js +1 -0
  56. package/dist/collections/operations/updateByID.js.map +1 -1
  57. package/dist/config/build.js +1 -1
  58. package/dist/config/build.js.map +1 -1
  59. package/dist/config/defaults.d.ts.map +1 -1
  60. package/dist/config/defaults.js +5 -2
  61. package/dist/config/defaults.js.map +1 -1
  62. package/dist/config/orderable/index.d.ts +1 -1
  63. package/dist/config/orderable/index.d.ts.map +1 -1
  64. package/dist/config/orderable/index.js +2 -2
  65. package/dist/config/orderable/index.js.map +1 -1
  66. package/dist/config/sanitize.d.ts +1 -1
  67. package/dist/config/sanitize.d.ts.map +1 -1
  68. package/dist/config/sanitize.js +33 -40
  69. package/dist/config/sanitize.js.map +1 -1
  70. package/dist/config/types.d.ts +1 -1
  71. package/dist/config/types.js.map +1 -1
  72. package/dist/database/createDatabaseAdapter.d.ts +1 -1
  73. package/dist/database/createDatabaseAdapter.d.ts.map +1 -1
  74. package/dist/database/createDatabaseAdapter.js +0 -2
  75. package/dist/database/createDatabaseAdapter.js.map +1 -1
  76. package/dist/database/types.d.ts +6 -0
  77. package/dist/database/types.d.ts.map +1 -1
  78. package/dist/database/types.js.map +1 -1
  79. package/dist/exports/auth.d.ts +5 -0
  80. package/dist/exports/auth.d.ts.map +1 -0
  81. package/dist/exports/auth.js +6 -0
  82. package/dist/exports/auth.js.map +1 -0
  83. package/dist/exports/internal.d.ts +2 -0
  84. package/dist/exports/internal.d.ts.map +1 -1
  85. package/dist/exports/internal.js +3 -1
  86. package/dist/exports/internal.js.map +1 -1
  87. package/dist/fields/baseFields/slug/duplicateContext.d.ts +11 -0
  88. package/dist/fields/baseFields/slug/duplicateContext.d.ts.map +1 -0
  89. package/dist/fields/baseFields/slug/duplicateContext.js +21 -0
  90. package/dist/fields/baseFields/slug/duplicateContext.js.map +1 -0
  91. package/dist/fields/baseFields/slug/fillEmptyLocalizedSlugs.d.ts +22 -0
  92. package/dist/fields/baseFields/slug/fillEmptyLocalizedSlugs.d.ts.map +1 -0
  93. package/dist/fields/baseFields/slug/fillEmptyLocalizedSlugs.js +63 -0
  94. package/dist/fields/baseFields/slug/fillEmptyLocalizedSlugs.js.map +1 -0
  95. package/dist/fields/baseFields/slug/generateSlug.d.ts +13 -8
  96. package/dist/fields/baseFields/slug/generateSlug.d.ts.map +1 -1
  97. package/dist/fields/baseFields/slug/generateSlug.js +98 -45
  98. package/dist/fields/baseFields/slug/generateSlug.js.map +1 -1
  99. package/dist/fields/baseFields/slug/generateSlugBeforeDuplicate.d.ts +18 -0
  100. package/dist/fields/baseFields/slug/generateSlugBeforeDuplicate.d.ts.map +1 -0
  101. package/dist/fields/baseFields/slug/generateSlugBeforeDuplicate.js +20 -0
  102. package/dist/fields/baseFields/slug/generateSlugBeforeDuplicate.js.map +1 -0
  103. package/dist/fields/baseFields/slug/getSlugFallbackValue.d.ts +22 -0
  104. package/dist/fields/baseFields/slug/getSlugFallbackValue.d.ts.map +1 -0
  105. package/dist/fields/baseFields/slug/getSlugFallbackValue.js +23 -0
  106. package/dist/fields/baseFields/slug/getSlugFallbackValue.js.map +1 -0
  107. package/dist/fields/baseFields/slug/hasValue.d.ts +3 -0
  108. package/dist/fields/baseFields/slug/hasValue.d.ts.map +1 -0
  109. package/dist/fields/baseFields/slug/hasValue.js +3 -0
  110. package/dist/fields/baseFields/slug/hasValue.js.map +1 -0
  111. package/dist/fields/config/reservedFieldNames.spec.js +18 -18
  112. package/dist/fields/config/reservedFieldNames.spec.js.map +1 -1
  113. package/dist/fields/config/sanitize.d.ts +3 -9
  114. package/dist/fields/config/sanitize.d.ts.map +1 -1
  115. package/dist/fields/config/sanitize.js +33 -34
  116. package/dist/fields/config/sanitize.js.map +1 -1
  117. package/dist/fields/config/sanitize.spec.js +128 -105
  118. package/dist/fields/config/sanitize.spec.js.map +1 -1
  119. package/dist/fields/config/types.d.ts +4 -3
  120. package/dist/fields/config/types.d.ts.map +1 -1
  121. package/dist/fields/config/types.js.map +1 -1
  122. package/dist/fields/hooks/beforeValidate/promise.d.ts.map +1 -1
  123. package/dist/fields/hooks/beforeValidate/promise.js +5 -3
  124. package/dist/fields/hooks/beforeValidate/promise.js.map +1 -1
  125. package/dist/fields/hooks/beforeValidate/stripNullRows.d.ts +10 -0
  126. package/dist/fields/hooks/beforeValidate/stripNullRows.d.ts.map +1 -0
  127. package/dist/fields/hooks/beforeValidate/stripNullRows.js +18 -0
  128. package/dist/fields/hooks/beforeValidate/stripNullRows.js.map +1 -0
  129. package/dist/fields/validations.d.ts.map +1 -1
  130. package/dist/fields/validations.js +7 -8
  131. package/dist/fields/validations.js.map +1 -1
  132. package/dist/fields/validations.spec.js +61 -37
  133. package/dist/fields/validations.spec.js.map +1 -1
  134. package/dist/globals/config/sanitize.d.ts +2 -7
  135. package/dist/globals/config/sanitize.d.ts.map +1 -1
  136. package/dist/globals/config/sanitize.js +2 -6
  137. package/dist/globals/config/sanitize.js.map +1 -1
  138. package/dist/globals/config/sanitize.spec.js +6 -6
  139. package/dist/globals/config/sanitize.spec.js.map +1 -1
  140. package/dist/globals/operations/countGlobalVersions.d.ts.map +1 -1
  141. package/dist/globals/operations/countGlobalVersions.js +1 -0
  142. package/dist/globals/operations/countGlobalVersions.js.map +1 -1
  143. package/dist/index.bundled.d.ts +247 -178
  144. package/dist/index.d.ts +49 -17
  145. package/dist/index.d.ts.map +1 -1
  146. package/dist/index.js +3 -0
  147. package/dist/index.js.map +1 -1
  148. package/dist/query-presets/constraints.js +1 -1
  149. package/dist/query-presets/constraints.js.map +1 -1
  150. package/dist/queues/config/collection.d.ts.map +1 -1
  151. package/dist/queues/config/collection.js +37 -43
  152. package/dist/queues/config/collection.js.map +1 -1
  153. package/dist/queues/config/global.d.ts +5 -6
  154. package/dist/queues/config/global.d.ts.map +1 -1
  155. package/dist/queues/config/global.js +1 -1
  156. package/dist/queues/config/global.js.map +1 -1
  157. package/dist/queues/config/types/index.d.ts +29 -24
  158. package/dist/queues/config/types/index.d.ts.map +1 -1
  159. package/dist/queues/config/types/index.js.map +1 -1
  160. package/dist/queues/config/types/taskTypes.d.ts +4 -7
  161. package/dist/queues/config/types/taskTypes.d.ts.map +1 -1
  162. package/dist/queues/config/types/taskTypes.js.map +1 -1
  163. package/dist/queues/config/types/workflowJSONTypes.d.ts +10 -9
  164. package/dist/queues/config/types/workflowJSONTypes.d.ts.map +1 -1
  165. package/dist/queues/config/types/workflowJSONTypes.js.map +1 -1
  166. package/dist/queues/config/types/workflowTypes.d.ts +11 -58
  167. package/dist/queues/config/types/workflowTypes.d.ts.map +1 -1
  168. package/dist/queues/config/types/workflowTypes.js.map +1 -1
  169. package/dist/queues/endpoints/handleSchedules.js +1 -1
  170. package/dist/queues/endpoints/handleSchedules.js.map +1 -1
  171. package/dist/queues/errors/handleTaskError.js +4 -4
  172. package/dist/queues/errors/handleTaskError.js.map +1 -1
  173. package/dist/queues/errors/handleWorkflowError.js +1 -1
  174. package/dist/queues/errors/handleWorkflowError.js.map +1 -1
  175. package/dist/queues/errors/index.d.ts +6 -0
  176. package/dist/queues/errors/index.d.ts.map +1 -1
  177. package/dist/queues/errors/index.js +5 -0
  178. package/dist/queues/errors/index.js.map +1 -1
  179. package/dist/queues/localAPI.d.ts +4 -4
  180. package/dist/queues/localAPI.d.ts.map +1 -1
  181. package/dist/queues/localAPI.js +63 -66
  182. package/dist/queues/localAPI.js.map +1 -1
  183. package/dist/queues/operations/handleSchedules/countRunnableOrActiveJobsForQueue.d.ts +4 -4
  184. package/dist/queues/operations/handleSchedules/countRunnableOrActiveJobsForQueue.d.ts.map +1 -1
  185. package/dist/queues/operations/handleSchedules/countRunnableOrActiveJobsForQueue.js.map +1 -1
  186. package/dist/queues/operations/handleSchedules/index.d.ts +1 -1
  187. package/dist/queues/operations/handleSchedules/index.d.ts.map +1 -1
  188. package/dist/queues/operations/handleSchedules/index.js +1 -1
  189. package/dist/queues/operations/handleSchedules/index.js.map +1 -1
  190. package/dist/queues/operations/runJobs/heartbeat.d.ts +13 -0
  191. package/dist/queues/operations/runJobs/heartbeat.d.ts.map +1 -0
  192. package/dist/queues/operations/runJobs/heartbeat.js +66 -0
  193. package/dist/queues/operations/runJobs/heartbeat.js.map +1 -0
  194. package/dist/queues/operations/runJobs/index.d.ts.map +1 -1
  195. package/dist/queues/operations/runJobs/index.js +133 -84
  196. package/dist/queues/operations/runJobs/index.js.map +1 -1
  197. package/dist/queues/operations/runJobs/runJSONJob/index.d.ts.map +1 -1
  198. package/dist/queues/operations/runJobs/runJSONJob/index.js +6 -3
  199. package/dist/queues/operations/runJobs/runJSONJob/index.js.map +1 -1
  200. package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js +5 -5
  201. package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js.map +1 -1
  202. package/dist/queues/operations/runJobs/runJob/getUpdateJobFunction.d.ts +2 -1
  203. package/dist/queues/operations/runJobs/runJob/getUpdateJobFunction.d.ts.map +1 -1
  204. package/dist/queues/operations/runJobs/runJob/getUpdateJobFunction.js +39 -8
  205. package/dist/queues/operations/runJobs/runJob/getUpdateJobFunction.js.map +1 -1
  206. package/dist/queues/operations/runJobs/runJob/importHandlerPath.js.map +1 -1
  207. package/dist/queues/operations/runJobs/runJob/index.d.ts.map +1 -1
  208. package/dist/queues/operations/runJobs/runJob/index.js +4 -4
  209. package/dist/queues/operations/runJobs/runJob/index.js.map +1 -1
  210. package/dist/queues/utilities/updateJob.d.ts.map +1 -1
  211. package/dist/queues/utilities/updateJob.js +3 -0
  212. package/dist/queues/utilities/updateJob.js.map +1 -1
  213. package/dist/types/index.d.ts +2 -2
  214. package/dist/types/index.d.ts.map +1 -1
  215. package/dist/types/index.js.map +1 -1
  216. package/dist/uploads/checkFileRestrictions.d.ts +1 -1
  217. package/dist/uploads/checkFileRestrictions.d.ts.map +1 -1
  218. package/dist/uploads/checkFileRestrictions.js +15 -1
  219. package/dist/uploads/checkFileRestrictions.js.map +1 -1
  220. package/dist/uploads/endpoints/uploadInstructions.d.ts +12 -0
  221. package/dist/uploads/endpoints/uploadInstructions.d.ts.map +1 -1
  222. package/dist/uploads/endpoints/uploadInstructions.js +66 -20
  223. package/dist/uploads/endpoints/uploadInstructions.js.map +1 -1
  224. package/dist/uploads/generateFileData.js +4 -1
  225. package/dist/uploads/generateFileData.js.map +1 -1
  226. package/dist/uploads/getFileFromUploadInstructions.d.ts +8 -0
  227. package/dist/uploads/getFileFromUploadInstructions.d.ts.map +1 -0
  228. package/dist/uploads/getFileFromUploadInstructions.js +62 -0
  229. package/dist/uploads/getFileFromUploadInstructions.js.map +1 -0
  230. package/dist/uploads/getImageSize.d.ts +12 -1
  231. package/dist/uploads/getImageSize.d.ts.map +1 -1
  232. package/dist/uploads/getImageSize.js +20 -18
  233. package/dist/uploads/getImageSize.js.map +1 -1
  234. package/dist/uploads/getImageSize.spec.js +298 -0
  235. package/dist/uploads/getImageSize.spec.js.map +1 -0
  236. package/dist/uploads/probeImageSize.d.ts +39 -0
  237. package/dist/uploads/probeImageSize.d.ts.map +1 -0
  238. package/dist/uploads/probeImageSize.js +374 -0
  239. package/dist/uploads/probeImageSize.js.map +1 -0
  240. package/dist/uploads/probeImageSize.spec.js +366 -0
  241. package/dist/uploads/probeImageSize.spec.js.map +1 -0
  242. package/dist/uploads/stagedUpload.d.ts +27 -0
  243. package/dist/uploads/stagedUpload.d.ts.map +1 -0
  244. package/dist/uploads/stagedUpload.js +197 -0
  245. package/dist/uploads/stagedUpload.js.map +1 -0
  246. package/dist/uploads/types.d.ts +41 -13
  247. package/dist/uploads/types.d.ts.map +1 -1
  248. package/dist/uploads/types.js.map +1 -1
  249. package/dist/utilities/addDataAndFileToRequest.d.ts.map +1 -1
  250. package/dist/utilities/addDataAndFileToRequest.js +12 -46
  251. package/dist/utilities/addDataAndFileToRequest.js.map +1 -1
  252. package/dist/utilities/configToJSONSchema.spec.js +33 -33
  253. package/dist/utilities/configToJSONSchema.spec.js.map +1 -1
  254. package/dist/utilities/fieldValueExists.d.ts +29 -0
  255. package/dist/utilities/fieldValueExists.d.ts.map +1 -0
  256. package/dist/utilities/fieldValueExists.js +27 -0
  257. package/dist/utilities/fieldValueExists.js.map +1 -0
  258. package/dist/utilities/getUniqueFieldValue.d.ts +27 -0
  259. package/dist/utilities/getUniqueFieldValue.d.ts.map +1 -0
  260. package/dist/utilities/getUniqueFieldValue.js +26 -0
  261. package/dist/utilities/getUniqueFieldValue.js.map +1 -0
  262. package/dist/versions/deleteScheduledPublishJobs.js +2 -2
  263. package/dist/versions/deleteScheduledPublishJobs.js.map +1 -1
  264. package/dist/versions/payloadPackageList.d.ts.map +1 -1
  265. package/dist/versions/payloadPackageList.js +0 -1
  266. package/dist/versions/payloadPackageList.js.map +1 -1
  267. package/package.json +8 -3
  268. package/dist/database/defaultUpdateJobs.d.ts +0 -3
  269. package/dist/database/defaultUpdateJobs.d.ts.map +0 -1
  270. package/dist/database/defaultUpdateJobs.js +0 -41
  271. package/dist/database/defaultUpdateJobs.js.map +0 -1
  272. package/dist/fields/baseFields/slug/countVersions.d.ts +0 -13
  273. package/dist/fields/baseFields/slug/countVersions.d.ts.map +0 -1
  274. package/dist/fields/baseFields/slug/countVersions.js +0 -27
  275. package/dist/fields/baseFields/slug/countVersions.js.map +0 -1
  276. package/dist/uploads/tempFile.d.ts +0 -7
  277. package/dist/uploads/tempFile.d.ts.map +0 -1
  278. package/dist/uploads/tempFile.js +0 -39
  279. package/dist/uploads/tempFile.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/getRunTaskFunction.ts"],"sourcesContent":["import ObjectIdImport from 'bson-objectid'\n\nimport type { Job } from '../../../../index.js'\nimport type { PayloadRequest } from '../../../../types/index.js'\nimport type {\n RetryConfig,\n RunInlineTaskFunction,\n RunTaskFunction,\n RunTaskFunctions,\n TaskConfig,\n TaskHandler,\n TaskHandlerResult,\n TaskType,\n} from '../../../config/types/taskTypes.js'\nimport type {\n JobLog,\n SingleTaskStatus,\n WorkflowConfig,\n WorkflowTypes,\n} from '../../../config/types/workflowTypes.js'\nimport type { UpdateJobFunction } from './getUpdateJobFunction.js'\n\nimport { JobCancelledError, TaskError } from '../../../errors/index.js'\nimport { getCurrentDate } from '../../../utilities/getCurrentDate.js'\nimport { getTaskHandlerFromConfig } from './importHandlerPath.js'\n\nconst ObjectId = 'default' in ObjectIdImport ? ObjectIdImport.default : ObjectIdImport\n\nexport type TaskParent = {\n taskID: string\n taskSlug: string\n}\n\nexport const getRunTaskFunction = <TIsInline extends boolean>(\n job: Job,\n workflowConfig: WorkflowConfig,\n req: PayloadRequest,\n isInline: TIsInline,\n updateJob: UpdateJobFunction,\n parent?: TaskParent,\n): TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions => {\n const jobConfig = req.payload.config.jobs\n\n const runTask: <TTaskSlug extends string>(\n taskSlug: TTaskSlug,\n ) => TTaskSlug extends 'inline' ? RunInlineTaskFunction : RunTaskFunction<TTaskSlug> = (\n taskSlug,\n ) =>\n (async (\n taskID: Parameters<RunInlineTaskFunction>[0],\n {\n input,\n retries,\n // Only available for inline tasks:\n task,\n }: Parameters<RunInlineTaskFunction>[1] & Parameters<RunTaskFunction<string>>[1],\n ) => {\n const executedAt = getCurrentDate()\n\n let taskConfig: TaskConfig | undefined\n if (!isInline) {\n taskConfig = (jobConfig.tasks?.length &&\n jobConfig.tasks.find((t) => t.slug === taskSlug)) as TaskConfig<string>\n\n if (!taskConfig) {\n throw new Error(`Task ${taskSlug} not found in workflow ${job.workflowSlug}`)\n }\n }\n\n const retriesConfigFromPropsNormalized =\n retries == undefined || retries == null\n ? {}\n : typeof retries === 'number'\n ? { attempts: retries }\n : retries\n const retriesConfigFromTaskConfigNormalized = taskConfig\n ? typeof taskConfig.retries === 'number'\n ? { attempts: taskConfig.retries }\n : taskConfig.retries\n : {}\n\n const finalRetriesConfig: RetryConfig = {\n ...retriesConfigFromTaskConfigNormalized,\n ...retriesConfigFromPropsNormalized, // Retry config from props takes precedence\n }\n\n const taskStatus: null | SingleTaskStatus<string> = job?.taskStatus?.[taskSlug]\n ? job.taskStatus[taskSlug][taskID]!\n : null\n\n // Handle restoration of task if it succeeded in a previous run\n if (taskStatus && taskStatus.complete === true) {\n let shouldRestore = true\n if (finalRetriesConfig?.shouldRestore === false) {\n shouldRestore = false\n } else if (typeof finalRetriesConfig?.shouldRestore === 'function') {\n shouldRestore = await finalRetriesConfig.shouldRestore({\n input,\n job,\n req,\n taskStatus,\n })\n }\n if (shouldRestore) {\n return taskStatus.output\n }\n }\n\n const runner = isInline\n ? (task as TaskHandler<TaskType>)\n : await getTaskHandlerFromConfig(taskConfig)\n\n if (!runner || typeof runner !== 'function') {\n throw new TaskError({\n executedAt,\n input,\n job,\n message: isInline\n ? `Inline task with ID ${taskID} does not have a valid handler.`\n : `Task with slug ${taskSlug} in workflow ${job.workflowSlug} does not have a valid handler.`,\n parent,\n retriesConfig: finalRetriesConfig,\n taskConfig,\n taskID,\n taskSlug,\n taskStatus,\n workflowConfig,\n })\n }\n\n let output: TaskHandlerResult<string>['output']\n\n try {\n output = (\n await runner({\n inlineTask: getRunTaskFunction(job, workflowConfig, req, true, updateJob, {\n taskID,\n taskSlug,\n }),\n input,\n job: job as unknown as Job<WorkflowTypes>,\n req,\n tasks: getRunTaskFunction(job, workflowConfig, req, false, updateJob, {\n taskID,\n taskSlug,\n }),\n })\n )?.output\n } catch (err: any) {\n if (err instanceof JobCancelledError) {\n // Re-throw JobCancelledError to be handled by the top-level error handler\n throw err\n }\n throw new TaskError({\n executedAt,\n input: input!,\n job,\n message: err.message || 'Task handler threw an error',\n output,\n parent,\n retriesConfig: finalRetriesConfig,\n taskConfig,\n taskID,\n taskSlug,\n taskStatus,\n workflowConfig,\n })\n }\n\n if (taskConfig?.onSuccess) {\n await taskConfig.onSuccess({\n input,\n job,\n req,\n taskStatus,\n })\n }\n\n const newLogItem: JobLog = {\n id: new ObjectId().toHexString(),\n completedAt: getCurrentDate().toISOString(),\n executedAt: executedAt.toISOString(),\n input,\n output,\n parent: jobConfig.addParentToTaskLog ? parent : undefined,\n state: 'succeeded',\n taskID,\n taskSlug,\n }\n\n await updateJob({\n log: {\n $push: newLogItem,\n } as any,\n // Set to null to skip main row update on postgres. 2 => 1 db round trips\n updatedAt: null as any,\n })\n\n return output\n }) as any\n\n if (isInline) {\n return runTask('inline') as TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions\n } else {\n const tasks: RunTaskFunctions = {}\n for (const task of jobConfig.tasks ?? []) {\n tasks[task.slug] = runTask(task.slug) as RunTaskFunction<string>\n }\n return tasks as TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions\n }\n}\n"],"names":["ObjectIdImport","JobCancelledError","TaskError","getCurrentDate","getTaskHandlerFromConfig","ObjectId","default","getRunTaskFunction","job","workflowConfig","req","isInline","updateJob","parent","jobConfig","payload","config","jobs","runTask","taskSlug","taskID","input","retries","task","executedAt","taskConfig","tasks","length","find","t","slug","Error","workflowSlug","retriesConfigFromPropsNormalized","undefined","attempts","retriesConfigFromTaskConfigNormalized","finalRetriesConfig","taskStatus","complete","shouldRestore","output","runner","message","retriesConfig","inlineTask","err","onSuccess","newLogItem","id","toHexString","completedAt","toISOString","addParentToTaskLog","state","log","$push","updatedAt"],"mappings":"AAAA,OAAOA,oBAAoB,gBAAe;AAsB1C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,cAAc,QAAQ,uCAAsC;AACrE,SAASC,wBAAwB,QAAQ,yBAAwB;AAEjE,MAAMC,WAAW,aAAaL,iBAAiBA,eAAeM,OAAO,GAAGN;AAOxE,OAAO,MAAMO,qBAAqB,CAChCC,KACAC,gBACAC,KACAC,UACAC,WACAC;IAEA,MAAMC,YAAYJ,IAAIK,OAAO,CAACC,MAAM,CAACC,IAAI;IAEzC,MAAMC,UAEiF,CACrFC,WAEC,OACCC,QACA,EACEC,KAAK,EACLC,OAAO,EACP,mCAAmC;QACnCC,IAAI,EAC0E;YAEhF,MAAMC,aAAarB;YAEnB,IAAIsB;YACJ,IAAI,CAACd,UAAU;gBACbc,aAAcX,UAAUY,KAAK,EAAEC,UAC7Bb,UAAUY,KAAK,CAACE,IAAI,CAAC,CAACC,IAAMA,EAAEC,IAAI,KAAKX;gBAEzC,IAAI,CAACM,YAAY;oBACf,MAAM,IAAIM,MAAM,CAAC,KAAK,EAAEZ,SAAS,uBAAuB,EAAEX,IAAIwB,YAAY,EAAE;gBAC9E;YACF;YAEA,MAAMC,mCACJX,WAAWY,aAAaZ,WAAW,OAC/B,CAAC,IACD,OAAOA,YAAY,WACjB;gBAAEa,UAAUb;YAAQ,IACpBA;YACR,MAAMc,wCAAwCX,aAC1C,OAAOA,WAAWH,OAAO,KAAK,WAC5B;gBAAEa,UAAUV,WAAWH,OAAO;YAAC,IAC/BG,WAAWH,OAAO,GACpB,CAAC;YAEL,MAAMe,qBAAkC;gBACtC,GAAGD,qCAAqC;gB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5C,UAAU;oBAClBsB;oBACAH,OAAOA;oBACPb;oBACAmC,SAASG,IAAIH,OAAO,IAAI;oBACxBF;oBACA5B;oBACA+B,eAAeP;oBACfZ;oBACAL;oBACAD;oBACAmB;oBACA7B;gBACF;YACF;YAEA,IAAIgB,YAAYsB,WAAW;gBACzB,MAAMtB,WAAWsB,SAAS,CAAC;oBACzB1B;oBACAb;oBACAE;oBACA4B;gBACF;YACF;YAEA,MAAMU,aAAqB;gBACzBC,IAAI,IAAI5C,WAAW6C,WAAW;gBAC9BC,aAAahD,iBAAiBiD,WAAW;gBACzC5B,YAAYA,WAAW4B,WAAW;gBAClC/B;gBACAoB;gBACA5B,QAAQC,UAAUuC,kBAAkB,GAAGxC,SAASqB;gBAChDoB,OAAO;gBACPlC;gBACAD;YACF;YAEA,MAAMP,UAAU;gBACd2C,KAAK;oBACHC,OAAOR;gBACT;gBACA,yEAAyE;gBACzES,WAAW;YACb;YAEA,OAAOhB;QACT;IAEF,IAAI9B,UAAU;QACZ,OAAOO,QAAQ;IACjB,OAAO;QACL,MAAMQ,QAA0B,CAAC;QACjC,KAAK,MAAMH,QAAQT,UAAUY,KAAK,IAAI,EAAE,CAAE;YACxCA,KAAK,CAACH,KAAKO,IAAI,CAAC,GAAGZ,QAAQK,KAAKO,IAAI;QACtC;QACA,OAAOJ;IACT;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/getRunTaskFunction.ts"],"sourcesContent":["import ObjectIdImport from 'bson-objectid'\n\nimport type { Job } from '../../../../index.js'\nimport type { PayloadRequest } from '../../../../types/index.js'\nimport type {\n RetryConfig,\n RunInlineTaskFunction,\n RunTaskFunction,\n RunTaskFunctions,\n TaskConfig,\n TaskHandler,\n TaskHandlerResult,\n TaskSlug,\n} from '../../../config/types/taskTypes.js'\nimport type {\n JobLog,\n SingleTaskStatus,\n WorkflowConfig,\n WorkflowSlug,\n} from '../../../config/types/workflowTypes.js'\nimport type { UpdateJobFunction } from './getUpdateJobFunction.js'\n\nimport { JobCancelledError, JobRunAbortedError, TaskError } from '../../../errors/index.js'\nimport { getCurrentDate } from '../../../utilities/getCurrentDate.js'\nimport { getTaskHandlerFromConfig } from './importHandlerPath.js'\n\nconst ObjectId = 'default' in ObjectIdImport ? ObjectIdImport.default : ObjectIdImport\n\nexport type TaskParent = {\n taskID: string\n taskSlug: string\n}\n\nexport const getRunTaskFunction = <TIsInline extends boolean>(\n job: Job,\n workflowConfig: WorkflowConfig,\n req: PayloadRequest,\n isInline: TIsInline,\n updateJob: UpdateJobFunction,\n parent?: TaskParent,\n): TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions => {\n const jobConfig = req.payload.config.jobs\n\n const runTask: <TTaskSlug extends string>(\n taskSlug: TTaskSlug,\n ) => TTaskSlug extends 'inline' ? RunInlineTaskFunction : RunTaskFunction<TTaskSlug> = (\n taskSlug,\n ) =>\n (async (\n taskID: Parameters<RunInlineTaskFunction>[0],\n {\n input,\n retries,\n // Only available for inline tasks:\n task,\n }: Parameters<RunInlineTaskFunction>[1] & Parameters<RunTaskFunction<string>>[1],\n ) => {\n const executedAt = getCurrentDate()\n\n let taskConfig: TaskConfig | undefined\n if (!isInline) {\n taskConfig = (jobConfig.tasks?.length &&\n jobConfig.tasks.find((t) => t.slug === taskSlug)) as TaskConfig<string>\n\n if (!taskConfig) {\n throw new Error(`Task ${taskSlug} not found in workflow ${job.workflowSlug}`)\n }\n }\n\n const retriesConfigFromPropsNormalized =\n retries == undefined || retries == null\n ? {}\n : typeof retries === 'number'\n ? { attempts: retries }\n : retries\n const retriesConfigFromTaskConfigNormalized = taskConfig\n ? typeof taskConfig.retries === 'number'\n ? { attempts: taskConfig.retries }\n : taskConfig.retries\n : {}\n\n const finalRetriesConfig: RetryConfig = {\n ...retriesConfigFromTaskConfigNormalized,\n ...retriesConfigFromPropsNormalized, // Retry config from props takes precedence\n }\n\n const taskStatus: null | SingleTaskStatus<string> = job?.taskStatus?.[taskSlug]\n ? job.taskStatus[taskSlug][taskID]!\n : null\n\n // Handle restoration of task if it succeeded in a previous run\n if (taskStatus && taskStatus.complete === true) {\n let shouldRestore = true\n if (finalRetriesConfig?.shouldRestore === false) {\n shouldRestore = false\n } else if (typeof finalRetriesConfig?.shouldRestore === 'function') {\n shouldRestore = await finalRetriesConfig.shouldRestore({\n input,\n job,\n req,\n taskStatus,\n })\n }\n if (shouldRestore) {\n return taskStatus.output\n }\n }\n\n const runner = isInline\n ? (task as TaskHandler<TaskSlug>)\n : await getTaskHandlerFromConfig(taskConfig)\n\n if (!runner || typeof runner !== 'function') {\n throw new TaskError({\n executedAt,\n input,\n job,\n message: isInline\n ? `Inline task with ID ${taskID} does not have a valid handler.`\n : `Task with slug ${taskSlug} in workflow ${job.workflowSlug} does not have a valid handler.`,\n parent,\n retriesConfig: finalRetriesConfig,\n taskConfig,\n taskID,\n taskSlug,\n taskStatus,\n workflowConfig,\n })\n }\n\n let output: TaskHandlerResult<string>['output']\n\n try {\n output = (\n await runner({\n inlineTask: getRunTaskFunction(job, workflowConfig, req, true, updateJob, {\n taskID,\n taskSlug,\n }),\n input,\n job: job as unknown as Job<WorkflowSlug>,\n req,\n tasks: getRunTaskFunction(job, workflowConfig, req, false, updateJob, {\n taskID,\n taskSlug,\n }),\n })\n )?.output\n } catch (err: any) {\n if (err instanceof JobCancelledError || err instanceof JobRunAbortedError) {\n // Job run aborts are handled by the top-level runner.\n throw err\n }\n throw new TaskError({\n executedAt,\n input: input!,\n job,\n message: err.message || 'Task handler threw an error',\n output,\n parent,\n retriesConfig: finalRetriesConfig,\n taskConfig,\n taskID,\n taskSlug,\n taskStatus,\n workflowConfig,\n })\n }\n\n if (taskConfig?.onSuccess) {\n await taskConfig.onSuccess({\n input,\n job,\n req,\n taskStatus,\n })\n }\n\n const newLogItem: JobLog = {\n id: new ObjectId().toHexString(),\n completedAt: getCurrentDate().toISOString(),\n executedAt: executedAt.toISOString(),\n input: input ?? {},\n output,\n parent,\n state: 'succeeded',\n taskID,\n taskSlug,\n }\n\n await updateJob({\n log: {\n $push: newLogItem,\n } as any,\n // Set to null to skip main row update on postgres. 2 => 1 db round trips\n updatedAt: null as any,\n })\n\n return output\n }) as any\n\n if (isInline) {\n return runTask('inline') as TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions\n } else {\n const tasks: RunTaskFunctions = {}\n for (const task of jobConfig.tasks ?? []) {\n tasks[task.slug] = runTask(task.slug) as RunTaskFunction<string>\n }\n return tasks as TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions\n }\n}\n"],"names":["ObjectIdImport","JobCancelledError","JobRunAbortedError","TaskError","getCurrentDate","getTaskHandlerFromConfig","ObjectId","default","getRunTaskFunction","job","workflowConfig","req","isInline","updateJob","parent","jobConfig","payload","config","jobs","runTask","taskSlug","taskID","input","retries","task","executedAt","taskConfig","tasks","length","find","t","slug","Error","workflowSlug","retriesConfigFromPropsNormalized","undefined","attempts","retriesConfigFromTaskConfigNormalized","finalRetriesConfig","taskStatus","complete","shouldRestore","output","runner","message","retriesConfig","inlineTask","err","onSuccess","newLogItem","id","toHexString","completedAt","toISOString","state","log","$push","updatedAt"],"mappings":"AAAA,OAAOA,oBAAoB,gBAAe;AAsB1C,SAASC,iBAAiB,EAAEC,kBAAkB,EAAEC,SAAS,QAAQ,2BAA0B;AAC3F,SAASC,cAAc,QAAQ,uCAAsC;AACrE,SAASC,wBAAwB,QAAQ,yBAAwB;AAEjE,MAAMC,WAAW,aAAaN,iBAAiBA,eAAeO,OAAO,GAAGP;AAOxE,OAAO,MAAMQ,qBAAqB,CAChCC,KACAC,gBACAC,KACAC,UACAC,WACAC;IAEA,MAAMC,YAAYJ,IAAIK,OAAO,CAACC,MAAM,CAACC,IAAI;IAEzC,MAAMC,UAEiF,CACrFC,WAEC,OACCC,QACA,EACEC,KAAK,EACLC,OAAO,EACP,mCAAmC;QACnCC,IAAI,EAC0E;YAEhF,MAAMC,aAAarB;YAEnB,IAAIsB;YACJ,IAAI,CAACd,UAAU;gBACbc,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IAAI,EAAE,CAAE;YACxCA,KAAK,CAACH,KAAKO,IAAI,CAAC,GAAGZ,QAAQK,KAAKO,IAAI;QACtC;QACA,OAAOJ;IACT;AACF,EAAC"}
@@ -4,7 +4,8 @@ export type UpdateJobFunction = (jobData: Partial<Job>) => Promise<Job>;
4
4
  /**
5
5
  * Helper for updating a job that does the following, additionally to updating the job:
6
6
  * - Merges incoming data from the updated job into the original job object
7
- * - Handles job cancellation by throwing a `JobCancelledError` if the job was cancelled.
7
+ * - Throws a `JobCancelledError` if another process cancelled the job.
8
+ * - Stops updates after this worker loses the job's lease.
8
9
  */
9
10
  export declare function getUpdateJobFunction(job: Job, req: PayloadRequest): UpdateJobFunction;
10
11
  //# sourceMappingURL=getUpdateJobFunction.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"getUpdateJobFunction.d.ts","sourceRoot":"","sources":["../../../../../src/queues/operations/runJobs/runJob/getUpdateJobFunction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAA;AAC/C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAKhE,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,CAAA;AAEvE;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,cAAc,GAAG,iBAAiB,CAiCrF"}
1
+ {"version":3,"file":"getUpdateJobFunction.d.ts","sourceRoot":"","sources":["../../../../../src/queues/operations/runJobs/runJob/getUpdateJobFunction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAA;AAC/C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAMhE,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,CAAA;AAEvE;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,cAAc,GAAG,iBAAiB,CAyDrF"}
@@ -1,18 +1,49 @@
1
- import { JobCancelledError } from '../../../errors/index.js';
2
- import { updateJob } from '../../../utilities/updateJob.js';
1
+ import { JobCancelledError, JobRunAbortedError } from '../../../errors/index.js';
2
+ import { getCurrentDate } from '../../../utilities/getCurrentDate.js';
3
+ import { updateJobs } from '../../../utilities/updateJob.js';
3
4
  /**
4
5
  * Helper for updating a job that does the following, additionally to updating the job:
5
6
  * - Merges incoming data from the updated job into the original job object
6
- * - Handles job cancellation by throwing a `JobCancelledError` if the job was cancelled.
7
+ * - Throws a `JobCancelledError` if another process cancelled the job.
8
+ * - Stops updates after this worker loses the job's lease.
7
9
  */ export function getUpdateJobFunction(job, req) {
8
10
  return async (jobData)=>{
9
- const updatedJob = await updateJob({
10
- id: job.id,
11
+ const processingToken = job.processingToken;
12
+ if (!processingToken) {
13
+ throw new JobRunAbortedError(`Job ${job.id} can no longer be updated by this runner`);
14
+ }
15
+ const minimumProcessingUntil = new Date(getCurrentDate().getTime() + req.payload.config.jobs.processingLease.safetyBuffer).toISOString();
16
+ const updatedJobs = await updateJobs({
11
17
  data: jobData,
12
- req
18
+ limit: 1,
19
+ req,
20
+ returning: true,
21
+ where: {
22
+ and: [
23
+ {
24
+ id: {
25
+ equals: job.id
26
+ }
27
+ },
28
+ {
29
+ processingToken: {
30
+ equals: processingToken
31
+ }
32
+ },
33
+ // Do not update this job if the lease expired.
34
+ // Append safety buffer, as, depending on the db adapter, the update itself
35
+ // may not be atomic, and another worker may have claimed the job before this update finishes.
36
+ {
37
+ processingUntil: {
38
+ greater_than: minimumProcessingUntil
39
+ }
40
+ }
41
+ ]
42
+ }
13
43
  });
44
+ const updatedJob = updatedJobs?.[0];
14
45
  if (!updatedJob) {
15
- return job;
46
+ throw new JobRunAbortedError(`Job ${job.id} can no longer be updated by this runner`);
16
47
  }
17
48
  // Update job object like this to modify the original object - that way, incoming changes (e.g. taskStatus field that will be re-generated through the hook) will be reflected in the calling function
18
49
  for(const key in updatedJob){
@@ -30,7 +61,7 @@ import { updateJob } from '../../../utilities/updateJob.js';
30
61
  job[key] = updatedJob[key];
31
62
  }
32
63
  }
33
- if (updatedJob?.error?.cancelled) {
64
+ if (updatedJob.error?.cancelled && !jobData.error?.cancelled) {
34
65
  throw new JobCancelledError(`Job ${job.id} was cancelled`);
35
66
  }
36
67
  return updatedJob;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/getUpdateJobFunction.ts"],"sourcesContent":["import type { Job } from '../../../../index.js'\nimport type { PayloadRequest } from '../../../../types/index.js'\n\nimport { JobCancelledError } from '../../../errors/index.js'\nimport { updateJob } from '../../../utilities/updateJob.js'\n\nexport type UpdateJobFunction = (jobData: Partial<Job>) => Promise<Job>\n\n/**\n * Helper for updating a job that does the following, additionally to updating the job:\n * - Merges incoming data from the updated job into the original job object\n * - Handles job cancellation by throwing a `JobCancelledError` if the job was cancelled.\n */\nexport function getUpdateJobFunction(job: Job, req: PayloadRequest): UpdateJobFunction {\n return async (jobData) => {\n const updatedJob = await updateJob({\n id: job.id,\n data: jobData,\n req,\n })\n\n if (!updatedJob) {\n return job\n }\n\n // Update job object like this to modify the original object - that way, incoming changes (e.g. taskStatus field that will be re-generated through the hook) will be reflected in the calling function\n for (const key in updatedJob) {\n if (key === 'log') {\n // Add all new log entries to the original job.log object. Do not delete any existing log entries.\n // Do not update existing log entries, as existing log entries should be immutable.\n for (const logEntry of updatedJob?.log ?? []) {\n if (!job.log || !job.log.some((entry) => entry.id === logEntry.id)) {\n ;(job.log ??= []).push(logEntry)\n }\n }\n } else {\n ;(job as any)[key] = updatedJob[key as keyof Job]\n }\n }\n\n if ((updatedJob?.error as Record<string, unknown>)?.cancelled) {\n throw new JobCancelledError(`Job ${job.id} was cancelled`)\n }\n\n return updatedJob\n }\n}\n"],"names":["JobCancelledError","updateJob","getUpdateJobFunction","job","req","jobData","updatedJob","id","data","key","logEntry","log","some","entry","push","error","cancelled"],"mappings":"AAGA,SAASA,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,SAAS,QAAQ,kCAAiC;AAI3D;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,GAAQ,EAAEC,GAAmB;IAChE,OAAO,OAAOC;QACZ,MAAMC,aAAa,MAAML,UAAU;YACjCM,IAAIJ,IAAII,EAAE;YACVC,MAAMH;YACND;QACF;QAEA,IAAI,CAACE,YAAY;YACf,OAAOH;QACT;QAEA,sMAAsM;QACtM,IAAK,MAAMM,OAAOH,WAAY;YAC5B,IAAIG,QAAQ,OAAO;gBACjB,kGAAkG;gBAClG,mFAAmF;gBACnF,KAAK,MAAMC,YAAYJ,YAAYK,OAAO,EAAE,CAAE;oBAC5C,IAAI,CAACR,IAAIQ,GAAG,IAAI,CAACR,IAAIQ,GAAG,CAACC,IAAI,CAAC,CAACC,QAAUA,MAAMN,EAAE,KAAKG,SAASH,EAAE,GAAG;;wBAChEJ,CAAAA,IAAIQ,GAAG,KAAK,EAAE,AAAD,EAAGG,IAAI,CAACJ;oBACzB;gBACF;YACF,OAAO;;gBACHP,GAAW,CAACM,IAAI,GAAGH,UAAU,CAACG,IAAiB;YACnD;QACF;QAEA,IAAKH,YAAYS,OAAmCC,WAAW;YAC7D,MAAM,IAAIhB,kBAAkB,CAAC,IAAI,EAAEG,IAAII,EAAE,CAAC,cAAc,CAAC;QAC3D;QAEA,OAAOD;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/getUpdateJobFunction.ts"],"sourcesContent":["import type { Job } from '../../../../index.js'\nimport type { PayloadRequest } from '../../../../types/index.js'\n\nimport { JobCancelledError, JobRunAbortedError } from '../../../errors/index.js'\nimport { getCurrentDate } from '../../../utilities/getCurrentDate.js'\nimport { updateJobs } from '../../../utilities/updateJob.js'\n\nexport type UpdateJobFunction = (jobData: Partial<Job>) => Promise<Job>\n\n/**\n * Helper for updating a job that does the following, additionally to updating the job:\n * - Merges incoming data from the updated job into the original job object\n * - Throws a `JobCancelledError` if another process cancelled the job.\n * - Stops updates after this worker loses the job's lease.\n */\nexport function getUpdateJobFunction(job: Job, req: PayloadRequest): UpdateJobFunction {\n return async (jobData) => {\n const processingToken = job.processingToken\n\n if (!processingToken) {\n throw new JobRunAbortedError(`Job ${job.id} can no longer be updated by this runner`)\n }\n\n const minimumProcessingUntil = new Date(\n getCurrentDate().getTime() + req.payload.config.jobs.processingLease.safetyBuffer,\n ).toISOString()\n const updatedJobs = await updateJobs({\n data: jobData,\n limit: 1,\n req,\n returning: true,\n where: {\n and: [\n { id: { equals: job.id } },\n { processingToken: { equals: processingToken } },\n // Do not update this job if the lease expired.\n // Append safety buffer, as, depending on the db adapter, the update itself\n // may not be atomic, and another worker may have claimed the job before this update finishes.\n { processingUntil: { greater_than: minimumProcessingUntil } },\n ],\n },\n })\n const updatedJob = updatedJobs?.[0]\n\n if (!updatedJob) {\n throw new JobRunAbortedError(`Job ${job.id} can no longer be updated by this runner`)\n }\n\n // Update job object like this to modify the original object - that way, incoming changes (e.g. taskStatus field that will be re-generated through the hook) will be reflected in the calling function\n for (const key in updatedJob) {\n if (key === 'log') {\n // Add all new log entries to the original job.log object. Do not delete any existing log entries.\n // Do not update existing log entries, as existing log entries should be immutable.\n for (const logEntry of updatedJob?.log ?? []) {\n if (!job.log || !job.log.some((entry) => entry.id === logEntry.id)) {\n ;(job.log ??= []).push(logEntry)\n }\n }\n } else {\n ;(job as any)[key] = updatedJob[key as keyof Job]\n }\n }\n\n if (\n (updatedJob.error as Record<string, unknown>)?.cancelled &&\n !(jobData.error as Record<string, unknown> | undefined)?.cancelled\n ) {\n throw new JobCancelledError(`Job ${job.id} was cancelled`)\n }\n\n return updatedJob\n }\n}\n"],"names":["JobCancelledError","JobRunAbortedError","getCurrentDate","updateJobs","getUpdateJobFunction","job","req","jobData","processingToken","id","minimumProcessingUntil","Date","getTime","payload","config","jobs","processingLease","safetyBuffer","toISOString","updatedJobs","data","limit","returning","where","and","equals","processingUntil","greater_than","updatedJob","key","logEntry","log","some","entry","push","error","cancelled"],"mappings":"AAGA,SAASA,iBAAiB,EAAEC,kBAAkB,QAAQ,2BAA0B;AAChF,SAASC,cAAc,QAAQ,uCAAsC;AACrE,SAASC,UAAU,QAAQ,kCAAiC;AAI5D;;;;;CAKC,GACD,OAAO,SAASC,qBAAqBC,GAAQ,EAAEC,GAAmB;IAChE,OAAO,OAAOC;QACZ,MAAMC,kBAAkBH,IAAIG,eAAe;QAE3C,IAAI,CAACA,iBAAiB;YACpB,MAAM,IAAIP,mBAAmB,CAAC,IAAI,EAAEI,IAAII,EAAE,CAAC,wCAAwC,CAAC;QACtF;QAEA,MAAMC,yBAAyB,IAAIC,KACjCT,iBAAiBU,OAAO,KAAKN,IAAIO,OAAO,CAACC,MAAM,CAACC,IAAI,CAACC,eAAe,CAACC,YAAY,EACjFC,WAAW;QACb,MAAMC,cAAc,MAAMhB,WAAW;YACnCiB,MAAMb;YACNc,OAAO;YACPf;YACAgB,WAAW;YACXC,OAAO;gBACLC,KAAK;oBACH;wBAAEf,IAAI;4BAAEgB,QAAQpB,IAAII,EAAE;wBAAC;oBAAE;oBACzB;wBAAED,iBAAiB;4BAAEiB,QAAQjB;wBAAgB;oBAAE;oBAC/C,+CAA+C;oBAC/C,2EAA2E;oBAC3E,8FAA8F;oBAC9F;wBAAEkB,iBAAiB;4BAAEC,cAAcjB;wBAAuB;oBAAE;iBAC7D;YACH;QACF;QACA,MAAMkB,aAAaT,aAAa,CAAC,EAAE;QAEnC,IAAI,CAACS,YAAY;YACf,MAAM,IAAI3B,mBAAmB,CAAC,IAAI,EAAEI,IAAII,EAAE,CAAC,wCAAwC,CAAC;QACtF;QAEA,sMAAsM;QACtM,IAAK,MAAMoB,OAAOD,WAAY;YAC5B,IAAIC,QAAQ,OAAO;gBACjB,kGAAkG;gBAClG,mFAAmF;gBACnF,KAAK,MAAMC,YAAYF,YAAYG,OAAO,EAAE,CAAE;oBAC5C,IAAI,CAAC1B,IAAI0B,GAAG,IAAI,CAAC1B,IAAI0B,GAAG,CAACC,IAAI,CAAC,CAACC,QAAUA,MAAMxB,EAAE,KAAKqB,SAASrB,EAAE,GAAG;;wBAChEJ,CAAAA,IAAI0B,GAAG,KAAK,EAAE,AAAD,EAAGG,IAAI,CAACJ;oBACzB;gBACF;YACF,OAAO;;gBACHzB,GAAW,CAACwB,IAAI,GAAGD,UAAU,CAACC,IAAiB;YACnD;QACF;QAEA,IACE,AAACD,WAAWO,KAAK,EAA8BC,aAC/C,CAAE7B,QAAQ4B,KAAK,EAA0CC,WACzD;YACA,MAAM,IAAIpC,kBAAkB,CAAC,IAAI,EAAEK,IAAII,EAAE,CAAC,cAAc,CAAC;QAC3D;QAEA,OAAOmB;IACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/importHandlerPath.ts"],"sourcesContent":["import type { TaskConfig, TaskHandler, TaskType } from '../../../config/types/taskTypes.js'\n\nimport { dynamicImport } from '../../../../utilities/dynamicImport.js'\n\n/**\n * Imports a handler function from a given path.\n */\nexport async function importHandlerPath<T>(path: string): Promise<T> {\n let runner!: T\n const [runnerPath, runnerImportName] = path.split('#')\n\n let runnerModule: Record<string, unknown>\n try {\n runnerModule = await dynamicImport<Record<string, unknown>>(runnerPath!)\n } catch (e) {\n throw new Error(\n `Error importing job queue handler module for path ${path}. This is an advanced feature that may require a sophisticated build pipeline, especially when using it in production or within Next.js, e.g. by calling opening the /api/payload-jobs/run endpoint. You will have to transpile the handler files separately and ensure they are available in the same location when the job is run. If you're using an endpoint to execute your jobs, it's recommended to define your handlers as functions directly in your Payload Config, or use import paths handlers outside of Next.js. Import Error: \\n${e instanceof Error ? e.message : 'Unknown error'}`,\n )\n }\n\n // If the path has indicated an #exportName, try to get it\n if (runnerImportName && runnerModule[runnerImportName]) {\n runner = runnerModule[runnerImportName] as T\n }\n\n // If there is a default export, use it\n if (!runner && runnerModule.default) {\n runner = runnerModule.default as T\n }\n\n // Finally, use whatever was imported\n if (!runner) {\n runner = runnerModule as T\n }\n\n return runner\n}\n\n/**\n * The `handler` property of a task config can either be a function or a path to a module that exports a function.\n * This function resolves the handler to a function, either by importing it from the path or returning the function directly\n * if it is already a function.\n */\nexport async function getTaskHandlerFromConfig(taskConfig?: TaskConfig) {\n if (!taskConfig) {\n throw new Error('Task config is required to get the task handler')\n }\n if (typeof taskConfig.handler === 'function') {\n return taskConfig.handler\n } else {\n return await importHandlerPath<TaskHandler<TaskType>>(taskConfig.handler)\n }\n}\n"],"names":["dynamicImport","importHandlerPath","path","runner","runnerPath","runnerImportName","split","runnerModule","e","Error","message","default","getTaskHandlerFromConfig","taskConfig","handler"],"mappings":"AAEA,SAASA,aAAa,QAAQ,yCAAwC;AAEtE;;CAEC,GACD,OAAO,eAAeC,kBAAqBC,IAAY;IACrD,IAAIC;IACJ,MAAM,CAACC,YAAYC,iBAAiB,GAAGH,KAAKI,KAAK,CAAC;IAElD,IAAIC;IACJ,IAAI;QACFA,eAAe,MAAMP,cAAuCI;IAC9D,EAAE,OAAOI,GAAG;QACV,MAAM,IAAIC,MACR,CAAC,kDAAkD,EAAEP,KAAK,+gBAA+gB,EAAEM,aAAaC,QAAQD,EAAEE,OAAO,GAAG,iBAAiB;IAEjoB;IAEA,0DAA0D;IAC1D,IAAIL,oBAAoBE,YAAY,CAACF,iBAAiB,EAAE;QACtDF,SAASI,YAAY,CAACF,iBAAiB;IACzC;IAEA,uCAAuC;IACvC,IAAI,CAACF,UAAUI,aAAaI,OAAO,EAAE;QACnCR,SAASI,aAAaI,OAAO;IAC/B;IAEA,qCAAqC;IACrC,IAAI,CAACR,QAAQ;QACXA,SAASI;IACX;IAEA,OAAOJ;AACT;AAEA;;;;CAIC,GACD,OAAO,eAAeS,yBAAyBC,UAAuB;IACpE,IAAI,CAACA,YAAY;QACf,MAAM,IAAIJ,MAAM;IAClB;IACA,IAAI,OAAOI,WAAWC,OAAO,KAAK,YAAY;QAC5C,OAAOD,WAAWC,OAAO;IAC3B,OAAO;QACL,OAAO,MAAMb,kBAAyCY,WAAWC,OAAO;IAC1E;AACF"}
1
+ {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/importHandlerPath.ts"],"sourcesContent":["import type { TaskConfig, TaskHandler, TaskSlug } from '../../../config/types/taskTypes.js'\n\nimport { dynamicImport } from '../../../../utilities/dynamicImport.js'\n\n/**\n * Imports a handler function from a given path.\n */\nexport async function importHandlerPath<T>(path: string): Promise<T> {\n let runner!: T\n const [runnerPath, runnerImportName] = path.split('#')\n\n let runnerModule: Record<string, unknown>\n try {\n runnerModule = await dynamicImport<Record<string, unknown>>(runnerPath!)\n } catch (e) {\n throw new Error(\n `Error importing job queue handler module for path ${path}. This is an advanced feature that may require a sophisticated build pipeline, especially when using it in production or within Next.js, e.g. by calling opening the /api/payload-jobs/run endpoint. You will have to transpile the handler files separately and ensure they are available in the same location when the job is run. If you're using an endpoint to execute your jobs, it's recommended to define your handlers as functions directly in your Payload Config, or use import paths handlers outside of Next.js. Import Error: \\n${e instanceof Error ? e.message : 'Unknown error'}`,\n )\n }\n\n // If the path has indicated an #exportName, try to get it\n if (runnerImportName && runnerModule[runnerImportName]) {\n runner = runnerModule[runnerImportName] as T\n }\n\n // If there is a default export, use it\n if (!runner && runnerModule.default) {\n runner = runnerModule.default as T\n }\n\n // Finally, use whatever was imported\n if (!runner) {\n runner = runnerModule as T\n }\n\n return runner\n}\n\n/**\n * The `handler` property of a task config can either be a function or a path to a module that exports a function.\n * This function resolves the handler to a function, either by importing it from the path or returning the function directly\n * if it is already a function.\n */\nexport async function getTaskHandlerFromConfig(taskConfig?: TaskConfig) {\n if (!taskConfig) {\n throw new Error('Task config is required to get the task handler')\n }\n if (typeof taskConfig.handler === 'function') {\n return taskConfig.handler\n } else {\n return await importHandlerPath<TaskHandler<TaskSlug>>(taskConfig.handler)\n }\n}\n"],"names":["dynamicImport","importHandlerPath","path","runner","runnerPath","runnerImportName","split","runnerModule","e","Error","message","default","getTaskHandlerFromConfig","taskConfig","handler"],"mappings":"AAEA,SAASA,aAAa,QAAQ,yCAAwC;AAEtE;;CAEC,GACD,OAAO,eAAeC,kBAAqBC,IAAY;IACrD,IAAIC;IACJ,MAAM,CAACC,YAAYC,iBAAiB,GAAGH,KAAKI,KAAK,CAAC;IAElD,IAAIC;IACJ,IAAI;QACFA,eAAe,MAAMP,cAAuCI;IAC9D,EAAE,OAAOI,GAAG;QACV,MAAM,IAAIC,MACR,CAAC,kDAAkD,EAAEP,KAAK,+gBAA+gB,EAAEM,aAAaC,QAAQD,EAAEE,OAAO,GAAG,iBAAiB;IAEjoB;IAEA,0DAA0D;IAC1D,IAAIL,oBAAoBE,YAAY,CAACF,iBAAiB,EAAE;QACtDF,SAASI,YAAY,CAACF,iBAAiB;IACzC;IAEA,uCAAuC;IACvC,IAAI,CAACF,UAAUI,aAAaI,OAAO,EAAE;QACnCR,SAASI,aAAaI,OAAO;IAC/B;IAEA,qCAAqC;IACrC,IAAI,CAACR,QAAQ;QACXA,SAASI;IACX;IAEA,OAAOJ;AACT;AAEA;;;;CAIC,GACD,OAAO,eAAeS,yBAAyBC,UAAuB;IACpE,IAAI,CAACA,YAAY;QACf,MAAM,IAAIJ,MAAM;IAClB;IACA,IAAI,OAAOI,WAAWC,OAAO,KAAK,YAAY;QAC5C,OAAOD,WAAWC,OAAO;IAC3B,OAAO;QACL,OAAO,MAAMb,kBAAyCY,WAAWC,OAAO;IAC1E;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/queues/operations/runJobs/runJob/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAA;AAC/C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAChE,OAAO,KA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e,EAAE,eAAe,CAAA;CACjC,CAAA;AAED,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,2BAA2B,GAAG,SAAS,CAAA;AAE5E,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM,EAAE,YAAY,CAAA;CACrB,CAAA;AAED,eAAO,MAAM,MAAM,sEAOhB,IAAI,KAAG,OAAO,CAAC,YAAY,CA6D7B,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { handleTaskError } from '../../../errors/handleTaskError.js';
2
2
  import { handleWorkflowError } from '../../../errors/handleWorkflowError.js';
3
- import { JobCancelledError, TaskError, WorkflowError } from '../../../errors/index.js';
3
+ import { JobCancelledError, JobRunAbortedError, TaskError, WorkflowError } from '../../../errors/index.js';
4
4
  import { getCurrentDate } from '../../../utilities/getCurrentDate.js';
5
5
  import { getRunTaskFunction } from './getRunTaskFunction.js';
6
6
  export const runJob = async ({ job, req, silent, updateJob, workflowConfig, workflowHandler })=>{
@@ -13,8 +13,8 @@ export const runJob = async ({ job, req, silent, updateJob, workflowConfig, work
13
13
  tasks: getRunTaskFunction(job, workflowConfig, req, false, updateJob)
14
14
  });
15
15
  } catch (error) {
16
- if (error instanceof JobCancelledError) {
17
- throw error // Job cancellation is handled in a top-level error handler, as higher up code may themselves throw this error
16
+ if (error instanceof JobCancelledError || error instanceof JobRunAbortedError) {
17
+ throw error // Job run aborts are handled by the top-level runner.
18
18
  ;
19
19
  }
20
20
  if (error instanceof TaskError) {
@@ -48,7 +48,7 @@ export const runJob = async ({ job, req, silent, updateJob, workflowConfig, work
48
48
  // Job log modifications are already updated at the end of the runTask function.
49
49
  await updateJob({
50
50
  completedAt: getCurrentDate().toISOString(),
51
- processing: false,
51
+ processingUntil: null,
52
52
  totalTried: (job.totalTried ?? 0) + 1
53
53
  });
54
54
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/index.ts"],"sourcesContent":["import type { Job } from '../../../../index.js'\nimport type { PayloadRequest } from '../../../../types/index.js'\nimport type { WorkflowConfig, WorkflowHandler } from '../../../config/types/workflowTypes.js'\nimport type { RunJobsSilent } from '../../../localAPI.js'\nimport type { UpdateJobFunction } from './getUpdateJobFunction.js'\n\nimport { handleTaskError } from '../../../errors/handleTaskError.js'\nimport { handleWorkflowError } from '../../../errors/handleWorkflowError.js'\nimport { JobCancelledError, TaskError, WorkflowError } from '../../../errors/index.js'\nimport { getCurrentDate } from '../../../utilities/getCurrentDate.js'\nimport { getRunTaskFunction } from './getRunTaskFunction.js'\n\ntype Args = {\n job: Job\n req: PayloadRequest\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 updateJob: UpdateJobFunction\n workflowConfig: WorkflowConfig\n workflowHandler: WorkflowHandler\n}\n\nexport type JobRunStatus = 'error' | 'error-reached-max-retries' | 'success'\n\nexport type RunJobResult = {\n status: JobRunStatus\n}\n\nexport const runJob = async ({\n job,\n req,\n silent,\n updateJob,\n workflowConfig,\n workflowHandler,\n}: Args): Promise<RunJobResult> => {\n // Run the job\n try {\n await workflowHandler({\n inlineTask: getRunTaskFunction(job, workflowConfig, req, true, updateJob),\n job,\n req,\n tasks: getRunTaskFunction(job, workflowConfig, req, false, updateJob),\n })\n } catch (error) {\n if (error instanceof JobCancelledError) {\n throw error // Job cancellation is handled in a top-level error handler, as higher up code may themselves throw this error\n }\n if (error instanceof TaskError) {\n const { hasFinalError } = await handleTaskError({\n error,\n req,\n silent,\n updateJob,\n })\n\n return {\n status: hasFinalError ? 'error-reached-max-retries' : 'error',\n }\n }\n\n const { hasFinalError } = await handleWorkflowError({\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowError({\n job,\n message:\n typeof error === 'object' && error && 'message' in error\n ? (error.message as string)\n : 'An unhandled error occurred',\n workflowConfig,\n }),\n req,\n silent,\n updateJob,\n })\n\n return {\n status: hasFinalError ? 'error-reached-max-retries' : 'error',\n }\n }\n\n // Workflow has completed successfully\n // Do not update the job log here, as that would result in unnecessary db calls when using postgres.\n // Solely updating simple fields here will result in optimized db calls.\n // Job log modifications are already updated at the end of the runTask function.\n await updateJob({\n completedAt: getCurrentDate().toISOString(),\n processing: false,\n totalTried: (job.totalTried ?? 0) + 1,\n })\n\n return {\n status: 'success',\n }\n}\n"],"names":["handleTaskError","handleWorkflowError","JobCancelledError","TaskError","WorkflowError","getCurrentDate","getRunTaskFunction","runJob","job","req","silent","updateJob","workflowConfig","workflowHandler","inlineTask","tasks","error","hasFinalError","status","message","completedAt","toISOString","processing","totalTried"],"mappings":"AAMA,SAASA,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,yCAAwC;AAC5E,SAASC,iBAAiB,EAAEC,SAAS,EAAEC,aAAa,QAAQ,2BAA0B;AACtF,SAASC,cAAc,QAAQ,uCAAsC;AACrE,SAASC,kBAAkB,QAAQ,0BAAyB;AAyB5D,OAAO,MAAMC,SAAS,OAAO,EAC3BC,GAAG,EACHC,GAAG,EACHC,MAAM,EACNC,SAAS,EACTC,cAAc,EACdC,eAAe,EACV;IACL,cAAc;IACd,IAAI;QACF,MAAMA,gBAAgB;YACpBC,YAAYR,mBAAmBE,KAAKI,gBAAgBH,KAAK,MAAME;YAC/DH;YACAC;YACAM,OAAOT,mBAAmBE,KAAKI,gBAAgBH,KAAK,OAAOE;QAC7D;IACF,EAAE,OAAOK,OAAO;QACd,IAAIA,iBAAiBd,mBAAmB;YACtC,MAAMc,MAAM,8GAA8G;;QAC5H;QACA,IAAIA,iBAAiBb,WAAW;YAC9B,MAAM,EAAEc,aAAa,EAAE,GAAG,MAAMjB,gBAAgB;gBAC9CgB;gBACAP;gBACAC;gBACAC;YACF;YAEA,OAAO;gBACLO,QAAQD,gBAAgB,8BAA8B;YACxD;QACF;QAEA,MAAM,EAAEA,aAAa,EAAE,GAAG,MAAMhB,oBAAoB;YAClDe,OACEA,iBAAiBZ,gBACbY,QACA,IAAIZ,cAAc;gBAChBI;gBACAW,SACE,OAAOH,UAAU,YAAYA,SAAS,aAAaA,QAC9CA,MAAMG,OAAO,GACd;gBACNP;YACF;YACNH;YACAC;YACAC;QACF;QAEA,OAAO;YACLO,QAAQD,gBAAgB,8BAA8B;QACxD;IACF;IAEA,sCAAsC;IACtC,oGAAoG;IACpG,wEAAwE;IACxE,gFAAgF;IAChF,MAAMN,UAAU;QACdS,aAAaf,iBAAiBgB,WAAW;QACzCC,YAAY;QACZC,YAAY,AAACf,CAAAA,IAAIe,UAAU,IAAI,CAAA,IAAK;IACtC;IAEA,OAAO;QACLL,QAAQ;IACV;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../src/queues/operations/runJobs/runJob/index.ts"],"sourcesContent":["import type { Job } from '../../../../index.js'\nimport type { PayloadRequest } from '../../../../types/index.js'\nimport type { WorkflowConfig, WorkflowHandler } from '../../../config/types/workflowTypes.js'\nimport type { RunJobsSilent } from '../../../localAPI.js'\nimport type { UpdateJobFunction } from './getUpdateJobFunction.js'\n\nimport { handleTaskError } from '../../../errors/handleTaskError.js'\nimport { handleWorkflowError } from '../../../errors/handleWorkflowError.js'\nimport {\n JobCancelledError,\n JobRunAbortedError,\n TaskError,\n WorkflowError,\n} from '../../../errors/index.js'\nimport { getCurrentDate } from '../../../utilities/getCurrentDate.js'\nimport { getRunTaskFunction } from './getRunTaskFunction.js'\n\ntype Args = {\n job: Job\n req: PayloadRequest\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 updateJob: UpdateJobFunction\n workflowConfig: WorkflowConfig\n workflowHandler: WorkflowHandler\n}\n\nexport type JobRunStatus = 'error' | 'error-reached-max-retries' | 'success'\n\nexport type RunJobResult = {\n status: JobRunStatus\n}\n\nexport const runJob = async ({\n job,\n req,\n silent,\n updateJob,\n workflowConfig,\n workflowHandler,\n}: Args): Promise<RunJobResult> => {\n // Run the job\n try {\n await workflowHandler({\n inlineTask: getRunTaskFunction(job, workflowConfig, req, true, updateJob),\n job,\n req,\n tasks: getRunTaskFunction(job, workflowConfig, req, false, updateJob),\n })\n } catch (error) {\n if (error instanceof JobCancelledError || error instanceof JobRunAbortedError) {\n throw error // Job run aborts are handled by the top-level runner.\n }\n if (error instanceof TaskError) {\n const { hasFinalError } = await handleTaskError({\n error,\n req,\n silent,\n updateJob,\n })\n\n return {\n status: hasFinalError ? 'error-reached-max-retries' : 'error',\n }\n }\n\n const { hasFinalError } = await handleWorkflowError({\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowError({\n job,\n message:\n typeof error === 'object' && error && 'message' in error\n ? (error.message as string)\n : 'An unhandled error occurred',\n workflowConfig,\n }),\n req,\n silent,\n updateJob,\n })\n\n return {\n status: hasFinalError ? 'error-reached-max-retries' : 'error',\n }\n }\n\n // Workflow has completed successfully\n // Do not update the job log here, as that would result in unnecessary db calls when using postgres.\n // Solely updating simple fields here will result in optimized db calls.\n // Job log modifications are already updated at the end of the runTask function.\n await updateJob({\n completedAt: getCurrentDate().toISOString(),\n processingUntil: null,\n totalTried: (job.totalTried ?? 0) + 1,\n })\n\n return {\n status: 'success',\n }\n}\n"],"names":["handleTaskError","handleWorkflowError","JobCancelledError","JobRunAbortedError","TaskError","WorkflowError","getCurrentDate","getRunTaskFunction","runJob","job","req","silent","updateJob","workflowConfig","workflowHandler","inlineTask","tasks","error","hasFinalError","status","message","completedAt","toISOString","processingUntil","totalTried"],"mappings":"AAMA,SAASA,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,yCAAwC;AAC5E,SACEC,iBAAiB,EACjBC,kBAAkB,EAClBC,SAAS,EACTC,aAAa,QACR,2BAA0B;AACjC,SAASC,cAAc,QAAQ,uCAAsC;AACrE,SAASC,kBAAkB,QAAQ,0BAAyB;AAyB5D,OAAO,MAAMC,SAAS,OAAO,EAC3BC,GAAG,EACHC,GAAG,EACHC,MAAM,EACNC,SAAS,EACTC,cAAc,EACdC,eAAe,EACV;IACL,cAAc;IACd,IAAI;QACF,MAAMA,gBAAgB;YACpBC,YAAYR,mBAAmBE,KAAKI,gBAAgBH,KAAK,MAAME;YAC/DH;YACAC;YACAM,OAAOT,mBAAmBE,KAAKI,gBAAgBH,KAAK,OAAOE;QAC7D;IACF,EAAE,OAAOK,OAAO;QACd,IAAIA,iBAAiBf,qBAAqBe,iBAAiBd,oBAAoB;YAC7E,MAAMc,MAAM,sDAAsD;;QACpE;QACA,IAAIA,iBAAiBb,WAAW;YAC9B,MAAM,EAAEc,aAAa,EAAE,GAAG,MAAMlB,gBAAgB;gBAC9CiB;gBACAP;gBACAC;gBACAC;YACF;YAEA,OAAO;gBACLO,QAAQD,gBAAgB,8BAA8B;YACxD;QACF;QAEA,MAAM,EAAEA,aAAa,EAAE,GAAG,MAAMjB,oBAAoB;YAClDgB,OACEA,iBAAiBZ,gBACbY,QACA,IAAIZ,cAAc;gBAChBI;gBACAW,SACE,OAAOH,UAAU,YAAYA,SAAS,aAAaA,QAC9CA,MAAMG,OAAO,GACd;gBACNP;YACF;YACNH;YACAC;YACAC;QACF;QAEA,OAAO;YACLO,QAAQD,gBAAgB,8BAA8B;QACxD;IACF;IAEA,sCAAsC;IACtC,oGAAoG;IACpG,wEAAwE;IACxE,gFAAgF;IAChF,MAAMN,UAAU;QACdS,aAAaf,iBAAiBgB,WAAW;QACzCC,iBAAiB;QACjBC,YAAY,AAACf,CAAAA,IAAIe,UAAU,IAAI,CAAA,IAAK;IACtC;IAEA,OAAO;QACLL,QAAQ;IACV;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"updateJob.d.ts","sourceRoot":"","sources":["../../../src/queues/utilities/updateJob.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AACzC,O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;IACd,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;IAClB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,GAAG,EAAE,cAAc,CAAA;IACnB,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB,CAAA;AAED,KAAK,QAAQ,GAAG;IACd,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,KAAK,CAAA;IACb,IAAI,CAAC,EAAE,KAAK,CAAA;IACZ,KAAK,CAAC,EAAE,KAAK,CAAA;CACd,CAAA;AAED,KAAK,SAAS,GAAG;IACf,EAAE,CAAC,EAAE,KAAK,CAAA;IACV,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,KAAK,EAAE,KAAK,CAAA;CACb,CAAA;AAED,KAAK,WAAW,GAAG,CAAC,QAAQ,GAAG,SAAS,CAAC,GAAG,QAAQ,CAAA;AAEpD;;GAEG;AACH,wBAAsB,SAAS,CAAC,IAAI,EAAE,QAAQ,GAAG,QAAQ,4BAKxD;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAAC,EAC/B,EAAE,EACF,IAAI,EACJ,KAAK,EAAE,QAAQ,EACf,GAAG,EACH,SAAS,EACT,IAAI,EACJ,KAAK,EAAE,QAAQ,GAChB,EAAE,WAAW,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAoDrC"}
@@ -22,6 +22,9 @@ import { getCurrentDate } from './getCurrentDate.js';
22
22
  const jobReq = {
23
23
  transactionID: req.payload.db.name !== 'mongoose' ? await req.payload.db.beginTransaction() : undefined
24
24
  };
25
+ if (data.processingUntil === null) {
26
+ data.processingToken = null;
27
+ }
25
28
  if (typeof data.updatedAt === 'undefined') {
26
29
  // Ensure updatedAt date is always updated
27
30
  data.updatedAt = getCurrentDate().toISOString();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/queues/utilities/updateJob.ts"],"sourcesContent":["import type { UpdateJobsArgs } from '../../database/types.js'\nimport type { Job } from '../../index.js'\nimport type { PayloadRequest, Sort, Where } from '../../types/index.js'\n\nimport { jobAfterRead } from '../config/collection.js'\nimport { getCurrentDate } from './getCurrentDate.js'\n\ntype BaseArgs = {\n data: Partial<Job>\n limit?: number\n req: PayloadRequest\n returning?: boolean\n}\n\ntype ArgsByID = {\n id: number | string\n limit?: never\n sort?: never\n where?: never\n}\n\ntype ArgsWhere = {\n id?: never\n limit?: number\n sort?: Sort\n where: Where\n}\n\ntype RunJobsArgs = (ArgsByID | ArgsWhere) & BaseArgs\n\n/**\n * Convenience method for updateJobs by id\n */\nexport async function updateJob(args: ArgsByID & BaseArgs) {\n const result = await updateJobs(args)\n if (result) {\n return result[0]\n }\n}\n\n/**\n * Helper for updating jobs in the most performant way possible.\n * Handles deciding whether it can used direct db methods or not, and if so,\n * manually runs the afterRead hook that populates the `taskStatus` property.\n */\nexport async function updateJobs({\n id,\n data,\n limit: limitArg,\n req,\n returning,\n sort,\n where: whereArg,\n}: RunJobsArgs): Promise<Job[] | null> {\n const limit = id ? 1 : limitArg\n const where = id ? { id: { equals: id } } : whereArg\n\n const jobReq = {\n transactionID:\n req.payload.db.name !== 'mongoose'\n ? ((await req.payload.db.beginTransaction()) as string)\n : undefined,\n }\n\n if (typeof data.updatedAt === 'undefined') {\n // Ensure updatedAt date is always updated\n data.updatedAt = getCurrentDate().toISOString()\n }\n\n const args: UpdateJobsArgs = id\n ? {\n id,\n data,\n req: jobReq,\n returning,\n }\n : {\n data,\n limit,\n req: jobReq,\n returning,\n sort,\n where: where as Where,\n }\n\n const updatedJobs: Job[] | null = await req.payload.db.updateJobs(args)\n\n if (req.payload.db.name !== 'mongoose' && jobReq.transactionID) {\n await req.payload.db.commitTransaction(jobReq.transactionID)\n }\n\n if (returning === false || !updatedJobs?.length) {\n return null\n }\n\n return updatedJobs.map((updatedJob) => {\n return jobAfterRead({\n config: req.payload.config,\n doc: updatedJob,\n })\n })\n}\n"],"names":["jobAfterRead","getCurrentDate","updateJob","args","result","updateJobs","id","data","limit","limitArg","req","returning","sort","where","whereArg","equals","jobReq","transactionID","payload","db","name","beginTransaction","undefined","updatedAt","toISOString","updatedJobs","commitTransaction","length","map","updatedJob","config","doc"],"mappings":"AAIA,SAASA,YAAY,QAAQ,0BAAyB;AACtD,SAASC,cAAc,QAAQ,sBAAqB;AAyBpD;;CAEC,GACD,OAAO,eAAeC,UAAUC,IAAyB;IACvD,MAAMC,SAAS,MAAMC,WAAWF;IAChC,IAAIC,QAAQ;QACV,OAAOA,MAAM,CAAC,EAAE;IAClB;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeC,WAAW,EAC/BC,EAAE,EACFC,IAAI,EACJC,OAAOC,QAAQ,EACfC,GAAG,EACHC,SAAS,EACTC,IAAI,EACJC,OAAOC,QAAQ,EACH;IACZ,MAAMN,QAAQF,KAAK,IAAIG;IACvB,MAAMI,QAAQP,KAAK;QAAEA,IAAI;YAAES,QAAQT;QAAG;IAAE,IAAIQ;IAE5C,MAAME,SAAS;QACbC,eACEP,IAAIQ,OAAO,CAACC,EAAE,CAACC,IAAI,KAAK,aAClB,MAAMV,IAAIQ,OAAO,CAACC,EAAE,CAACE,gBAAgB,KACvCC;IACR;IAEA,IAAI,OAAOf,KAAKgB,SAAS,KAAK,aAAa;QACzC,0CAA0C;QAC1ChB,KAAKgB,SAAS,GAAGtB,iBAAiBuB,WAAW;IAC/C;IAEA,MAAMrB,OAAuBG,KACzB;QACEA;QACAC;QACAG,KAAKM;QACLL;IACF,IACA;QACEJ;QACAC;QACAE,KAAKM;QACLL;QACAC;QACAC,OAAOA;IACT;IAEJ,MAAMY,cAA4B,MAAMf,IAAIQ,OAAO,CAACC,EAAE,CAACd,UAAU,CAACF;IAElE,IAAIO,IAAIQ,OAAO,CAACC,EAAE,CAACC,IAAI,KAAK,cAAcJ,OAAOC,aAAa,EAAE;QAC9D,MAAMP,IAAIQ,OAAO,CAACC,EAAE,CAACO,iBAAiB,CAACV,OAAOC,aAAa;IAC7D;IAEA,IAAIN,cAAc,SAAS,CAACc,aAAaE,QAAQ;QAC/C,OAAO;IACT;IAEA,OAAOF,YAAYG,GAAG,CAAC,CAACC;QACtB,OAAO7B,aAAa;YAClB8B,QAAQpB,IAAIQ,OAAO,CAACY,MAAM;YAC1BC,KAAKF;QACP;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/queues/utilities/updateJob.ts"],"sourcesContent":["import type { UpdateJobsArgs } from '../../database/types.js'\nimport type { Job } from '../../index.js'\nimport type { PayloadRequest, Sort, Where } from '../../types/index.js'\n\nimport { jobAfterRead } from '../config/collection.js'\nimport { getCurrentDate } from './getCurrentDate.js'\n\ntype BaseArgs = {\n data: Partial<Job>\n limit?: number\n req: PayloadRequest\n returning?: boolean\n}\n\ntype ArgsByID = {\n id: number | string\n limit?: never\n sort?: never\n where?: never\n}\n\ntype ArgsWhere = {\n id?: never\n limit?: number\n sort?: Sort\n where: Where\n}\n\ntype RunJobsArgs = (ArgsByID | ArgsWhere) & BaseArgs\n\n/**\n * Convenience method for updateJobs by id\n */\nexport async function updateJob(args: ArgsByID & BaseArgs) {\n const result = await updateJobs(args)\n if (result) {\n return result[0]\n }\n}\n\n/**\n * Helper for updating jobs in the most performant way possible.\n * Handles deciding whether it can used direct db methods or not, and if so,\n * manually runs the afterRead hook that populates the `taskStatus` property.\n */\nexport async function updateJobs({\n id,\n data,\n limit: limitArg,\n req,\n returning,\n sort,\n where: whereArg,\n}: RunJobsArgs): Promise<Job[] | null> {\n const limit = id ? 1 : limitArg\n const where = id ? { id: { equals: id } } : whereArg\n\n const jobReq = {\n transactionID:\n req.payload.db.name !== 'mongoose'\n ? ((await req.payload.db.beginTransaction()) as string)\n : undefined,\n }\n\n if (data.processingUntil === null) {\n data.processingToken = null\n }\n\n if (typeof data.updatedAt === 'undefined') {\n // Ensure updatedAt date is always updated\n data.updatedAt = getCurrentDate().toISOString()\n }\n\n const args: UpdateJobsArgs = id\n ? {\n id,\n data,\n req: jobReq,\n returning,\n }\n : {\n data,\n limit,\n req: jobReq,\n returning,\n sort,\n where: where as Where,\n }\n\n const updatedJobs: Job[] | null = await req.payload.db.updateJobs(args)\n\n if (req.payload.db.name !== 'mongoose' && jobReq.transactionID) {\n await req.payload.db.commitTransaction(jobReq.transactionID)\n }\n\n if (returning === false || !updatedJobs?.length) {\n return null\n }\n\n return updatedJobs.map((updatedJob) => {\n return jobAfterRead({\n config: req.payload.config,\n doc: updatedJob,\n })\n })\n}\n"],"names":["jobAfterRead","getCurrentDate","updateJob","args","result","updateJobs","id","data","limit","limitArg","req","returning","sort","where","whereArg","equals","jobReq","transactionID","payload","db","name","beginTransaction","undefined","processingUntil","processingToken","updatedAt","toISOString","updatedJobs","commitTransaction","length","map","updatedJob","config","doc"],"mappings":"AAIA,SAASA,YAAY,QAAQ,0BAAyB;AACtD,SAASC,cAAc,QAAQ,sBAAqB;AAyBpD;;CAEC,GACD,OAAO,eAAeC,UAAUC,IAAyB;IACvD,MAAMC,SAAS,MAAMC,WAAWF;IAChC,IAAIC,QAAQ;QACV,OAAOA,MAAM,CAAC,EAAE;IAClB;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeC,WAAW,EAC/BC,EAAE,EACFC,IAAI,EACJC,OAAOC,QAAQ,EACfC,GAAG,EACHC,SAAS,EACTC,IAAI,EACJC,OAAOC,QAAQ,EACH;IACZ,MAAMN,QAAQF,KAAK,IAAIG;IACvB,MAAMI,QAAQP,KAAK;QAAEA,IAAI;YAAES,QAAQT;QAAG;IAAE,IAAIQ;IAE5C,MAAME,SAAS;QACbC,eACEP,IAAIQ,OAAO,CAACC,EAAE,CAACC,IAAI,KAAK,aAClB,MAAMV,IAAIQ,OAAO,CAACC,EAAE,CAACE,gBAAgB,KACvCC;IACR;IAEA,IAAIf,KAAKgB,eAAe,KAAK,MAAM;QACjChB,KAAKiB,eAAe,GAAG;IACzB;IAEA,IAAI,OAAOjB,KAAKkB,SAAS,KAAK,aAAa;QACzC,0CAA0C;QAC1ClB,KAAKkB,SAAS,GAAGxB,iBAAiByB,WAAW;IAC/C;IAEA,MAAMvB,OAAuBG,KACzB;QACEA;QACAC;QACAG,KAAKM;QACLL;IACF,IACA;QACEJ;QACAC;QACAE,KAAKM;QACLL;QACAC;QACAC,OAAOA;IACT;IAEJ,MAAMc,cAA4B,MAAMjB,IAAIQ,OAAO,CAACC,EAAE,CAACd,UAAU,CAACF;IAElE,IAAIO,IAAIQ,OAAO,CAACC,EAAE,CAACC,IAAI,KAAK,cAAcJ,OAAOC,aAAa,EAAE;QAC9D,MAAMP,IAAIQ,OAAO,CAACC,EAAE,CAACS,iBAAiB,CAACZ,OAAOC,aAAa;IAC7D;IAEA,IAAIN,cAAc,SAAS,CAACgB,aAAaE,QAAQ;QAC/C,OAAO;IACT;IAEA,OAAOF,YAAYG,GAAG,CAAC,CAACC;QACtB,OAAO/B,aAAa;YAClBgC,QAAQtB,IAAIQ,OAAO,CAACc,MAAM;YAC1BC,KAAKF;QACP;IACF;AACF"}
@@ -97,7 +97,7 @@ type PayloadRequestData = {
97
97
  data?: JsonObject;
98
98
  /** The file on the request, same rules apply as the `data` property */
99
99
  file?: {
100
- directUpload?: unknown;
100
+ uploadReference?: unknown;
101
101
  } & File;
102
102
  /** All files from multipart form data, keyed by field name */
103
103
  files?: Record<string, File | File[]>;
@@ -125,7 +125,7 @@ export type DefaultValue = ((args: {
125
125
  locale?: TypedLocale;
126
126
  req: PayloadRequest;
127
127
  user: PayloadRequest['user'];
128
- }) => SerializableValue) | SerializableValue;
128
+ }) => Promise<SerializableValue> | SerializableValue) | SerializableValue;
129
129
  /**
130
130
  * Applies pagination for join fields for including collection relationships
131
131
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AAC/D,OAAO,KAAK,UAAU,MAAM,YAAY,CAAA;AACxC,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,OAAO,CAAC,qBAAqB,CAAC,CAAA;AAEzD,MAAM,MAAM,qBAAqB,GAAG;IAAE,CAAC,UAAU,EAAE,MAAM,GAAG,KAAK,CAAA;CAAE,CAAA;AAEnE,MAAM,MAAM,oBAAoB,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,IAAI,OAAO,CAC9D,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CACrC,GACC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAEtC,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\nimport type { OptionalKeys, RequiredKeys } from 'ts-essentials'\nimport type { URL } from 'url'\n\nimport type { ServerAdapter } from '../admin/adapters/server.js'\nimport type {\n DataFromCollectionSlug,\n QueryDraftDataFromCollectionSlug,\n TypeWithID,\n TypeWithTimestamps,\n} from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type {\n AuthenticatedUser,\n CollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n Payload,\n RequestContext,\n TypedCollectionJoins,\n TypedCollectionSelect,\n TypedFallbackLocale,\n TypedLocale,\n} from '../index.js'\nimport type { File } from '../uploads/types.js'\nimport type { Operator } from './constants.js'\nexport type { TypeWithID } from '../collections/config/types.js'\nexport type { Payload } from '../index.js'\n\nexport interface PayloadRequestAPI {\n GraphQL: true\n local: true\n REST: true\n}\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: TypedFallbackLocale\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n *\n * Suppressing warning below as it is a valid use case - won't be an issue if generated types exist\n */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n locale?: 'all' | TypedLocale\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: keyof PayloadRequestAPI\n /** Optimized document loader */\n payloadDataLoader: {\n /**\n * Wraps `payload.find` with a cache to deduplicate requests\n * @experimental This is may be replaced by a more robust cache strategy in future versions\n * By calling this method with the same arguments many times in one request, it will only be handled one time\n * const result = await req.payloadDataLoader.find({\n * collection,\n * req,\n * where: findWhere,\n * })\n */\n find: Payload['find']\n } & DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** Any response headers that are required to be set when a response is sent */\n responseHeaders?: Headers\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /**\n * Framework abstraction for server-only navigation, cookies, and headers APIs.\n * Populated by the framework adapter (e.g. `@payloadcms/next`). Plugins that\n * have access to `req` should call methods here (`req.server.unauthorized()`,\n * `req.server.redirect(...)`) instead of importing from `next/navigation` or\n * `next/headers` directly. Optional because non-framework contexts (jobs,\n * scripts, tests) construct requests without a server adapter.\n */\n server?: ServerAdapter\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n * Can also be used to ensure consistency when multiple operations try to create a transaction concurrently on the same request.\n */\n transactionID?: number | Promise<number | string> | string\n /** The signed-in user */\n user: AuthenticatedUser | null\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\ntype PayloadRequestData = {\n /**\n * Data from the request body\n *\n * Within Payload operations, i.e. hooks, data will be there\n * BUT in custom endpoints it will not be, you will need to\n * use either:\n * 1. `const data = await req.json()`\n *\n * 2. import { addDataAndFileToRequest } from 'payload'\n * `await addDataAndFileToRequest(req)`\n *\n * You should not expect this object to be the document data. It is the request data.\n * */\n data?: JsonObject\n /** The file on the request, same rules apply as the `data` property */\n file?: {\n directUpload?: unknown\n } & File\n /** All files from multipart form data, keyed by field name */\n files?: Record<string, File | File[]>\n}\nexport interface PayloadRequest\n extends CustomPayloadRequestProperties,\n Partial<Request>,\n PayloadRequestData {\n headers: Request['headers']\n}\n\nexport type { Operator }\n\n// Makes it so things like passing new Date() will error\nexport type JsonValue = JsonArray | JsonObject | unknown //Date | JsonArray | JsonObject | boolean | null | number | string // TODO: Evaluate proper, strong type for this\n\nexport type JsonArray = Array<JsonValue>\n\nexport interface JsonObject {\n [key: string]: any\n}\n\nexport type WhereField = {\n // any json-serializable value\n [key in Operator]?: JsonValue\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n and?: Where[]\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n or?: Where[]\n}\n\nexport type Sort = Array<string> | string\n\ntype SerializableValue = boolean | number | object | string\nexport type DefaultValue =\n | ((args: {\n locale?: TypedLocale\n req: PayloadRequest\n user: PayloadRequest['user']\n }) => SerializableValue)\n | SerializableValue\n\n/**\n * Applies pagination for join fields for including collection relationships\n */\nexport type JoinQuery<TSlug extends CollectionSlug = string> =\n TypedCollectionJoins[TSlug] extends Record<string, string>\n ?\n | false\n | Partial<{\n [K in keyof TypedCollectionJoins[TSlug]]:\n | {\n count?: boolean\n limit?: number\n page?: number\n sort?: string\n where?: Where\n }\n | false\n }>\n : never\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\nexport type Operation = 'create' | 'delete' | 'read' | 'update'\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n\nexport type SelectIncludeType = {\n [k: string]: SelectIncludeType | true\n}\n\nexport type SelectExcludeType = {\n [k: string]: false | SelectExcludeType\n}\n\nexport type SelectMode = 'exclude' | 'include'\n\nexport type SelectType = SelectExcludeType | SelectIncludeType\n\n/**\n * Operations that invoke an entity-level `select` function.\n *\n * Narrower than `HookOperationType`: `select` runs only for read- and\n * write-path operations that materialize a document (`create`, `delete`,\n * `read`, `restoreVersion`, `update`). Operations like `autosave`, `count`,\n * `countVersions`, `forgotPassword`, `login`, `readDistinct`, `refresh`, and\n * `resetPassword` do not invoke `select` and are intentionally excluded.\n */\nexport type SelectFnOperation = 'create' | 'delete' | 'read' | 'restoreVersion' | 'update'\n\nexport type SelectFnArgs = {\n operation: SelectFnOperation\n req: PayloadRequest\n /** The caller's `select` arg, or `undefined` if not provided. */\n select?: SelectType\n}\n\nexport type SelectFn<TSelect extends SelectType = SelectType> = (\n args: SelectFnArgs,\n) => TSelect | undefined\n\n/**\n * Shared shape for the entity-level `select` config used by Collections and Globals.\n * The JSDoc on the `select` property is the single source of truth — pick from this\n * type when defining the config:\n *\n * & Pick<WithSelectFn<...>, 'select'>\n */\nexport type WithSelectFn<TSelect extends SelectType = SelectType> = {\n /**\n * Entity-level Select API configuration.\n *\n * A function that receives the current request context (`operation`, `req`,\n * the caller's `select`) and returns the final `select` to apply, replacing\n * the caller's. Return `undefined` to leave the caller's `select` unchanged.\n *\n * Useful to dynamically modify the caller's selection based on the request context:\n * - Forcing a field to be populated for reference within hooks / access control.\n * - Differentiating between API requests and admin panel requests, to optimize\n * the amount of data being queried in each case.\n *\n * Note: per-document data is not available — this runs before the read.\n *\n * @see https://payloadcms.com/docs/queries/select\n */\n select?: SelectFn<TSelect>\n}\n\nexport type ApplyDisableErrors<T, DisableErrors = false> = false extends DisableErrors\n ? T\n : null | T\n\nexport type TransformDataWithSelect<\n Data extends Record<string, any>,\n Select extends SelectType,\n> = Select extends never\n ? Data\n : string extends keyof Select\n ? Data\n : // START Handle types when they aren't generated\n // For example in any package in this repository outside of tests / plugins\n // This stil gives us autocomplete when using include select mode, i.e select: {title :true} returns type {title: any, id: string | number}\n string extends keyof Omit<Data, 'id'>\n ? Select extends SelectIncludeType\n ? {\n [K in Data extends TypeWithID ? 'id' | keyof Select : keyof Select]: K extends 'id'\n ? number | string\n : unknown\n }\n : Data\n : // END Handle types when they aren't generated\n // Handle include mode\n Select extends SelectIncludeType\n ? {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | true\n ? K\n : never\n : // select 'id' always\n K extends 'id'\n ? K\n : never]: Data[K]\n }\n : // Handle exclude mode\n {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | undefined\n ? K\n : never\n : K]: Data[K]\n }\n\nexport type TransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromCollectionSlug<TSlug>, TSelect>\n : DataFromCollectionSlug<TSlug>\n\nexport type DraftTransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<QueryDraftDataFromCollectionSlug<TSlug>, TSelect>\n : QueryDraftDataFromCollectionSlug<TSlug>\n\nexport type TransformGlobalWithSelect<\n TSlug extends GlobalSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromGlobalSlug<TSlug>, TSelect>\n : DataFromGlobalSlug<TSlug>\n\nexport type PopulateType = Partial<TypedCollectionSelect>\n\nexport type ResolvedFilterOptions = { [collection: string]: Where }\n\nexport type PickPreserveOptional<T, K extends keyof T> = Partial<\n Pick<T, Extract<K, OptionalKeys<T>>>\n> &\n Pick<T, Extract<K, RequiredKeys<T>>>\n\nexport type MaybePromise<T> = Promise<T> | T\n"],"names":["docHasTimestamps","doc","createdAt","updatedAt"],"mappings":"AAqMA,OAAO,SAASA,iBAAiBC,GAAQ;IACvC,OAAOA,KAAKC,aAAaD,KAAKE;AAChC"}
1
+ {"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\nimport type { OptionalKeys, RequiredKeys } from 'ts-essentials'\nimport type { URL } from 'url'\n\nimport type { ServerAdapter } from '../admin/adapters/server.js'\nimport type {\n DataFromCollectionSlug,\n QueryDraftDataFromCollectionSlug,\n TypeWithID,\n TypeWithTimestamps,\n} from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type {\n AuthenticatedUser,\n CollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n Payload,\n RequestContext,\n TypedCollectionJoins,\n TypedCollectionSelect,\n TypedFallbackLocale,\n TypedLocale,\n} from '../index.js'\nimport type { File } from '../uploads/types.js'\nimport type { Operator } from './constants.js'\nexport type { TypeWithID } from '../collections/config/types.js'\nexport type { Payload } from '../index.js'\n\nexport interface PayloadRequestAPI {\n GraphQL: true\n local: true\n REST: true\n}\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: TypedFallbackLocale\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n *\n * Suppressing warning below as it is a valid use case - won't be an issue if generated types exist\n */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n locale?: 'all' | TypedLocale\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: keyof PayloadRequestAPI\n /** Optimized document loader */\n payloadDataLoader: {\n /**\n * Wraps `payload.find` with a cache to deduplicate requests\n * @experimental This is may be replaced by a more robust cache strategy in future versions\n * By calling this method with the same arguments many times in one request, it will only be handled one time\n * const result = await req.payloadDataLoader.find({\n * collection,\n * req,\n * where: findWhere,\n * })\n */\n find: Payload['find']\n } & DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** Any response headers that are required to be set when a response is sent */\n responseHeaders?: Headers\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /**\n * Framework abstraction for server-only navigation, cookies, and headers APIs.\n * Populated by the framework adapter (e.g. `@payloadcms/next`). Plugins that\n * have access to `req` should call methods here (`req.server.unauthorized()`,\n * `req.server.redirect(...)`) instead of importing from `next/navigation` or\n * `next/headers` directly. Optional because non-framework contexts (jobs,\n * scripts, tests) construct requests without a server adapter.\n */\n server?: ServerAdapter\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n * Can also be used to ensure consistency when multiple operations try to create a transaction concurrently on the same request.\n */\n transactionID?: number | Promise<number | string> | string\n /** The signed-in user */\n user: AuthenticatedUser | null\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\ntype PayloadRequestData = {\n /**\n * Data from the request body\n *\n * Within Payload operations, i.e. hooks, data will be there\n * BUT in custom endpoints it will not be, you will need to\n * use either:\n * 1. `const data = await req.json()`\n *\n * 2. import { addDataAndFileToRequest } from 'payload'\n * `await addDataAndFileToRequest(req)`\n *\n * You should not expect this object to be the document data. It is the request data.\n * */\n data?: JsonObject\n /** The file on the request, same rules apply as the `data` property */\n file?: {\n uploadReference?: unknown\n } & File\n /** All files from multipart form data, keyed by field name */\n files?: Record<string, File | File[]>\n}\nexport interface PayloadRequest\n extends CustomPayloadRequestProperties,\n Partial<Request>,\n PayloadRequestData {\n headers: Request['headers']\n}\n\nexport type { Operator }\n\n// Makes it so things like passing new Date() will error\nexport type JsonValue = JsonArray | JsonObject | unknown //Date | JsonArray | JsonObject | boolean | null | number | string // TODO: Evaluate proper, strong type for this\n\nexport type JsonArray = Array<JsonValue>\n\nexport interface JsonObject {\n [key: string]: any\n}\n\nexport type WhereField = {\n // any json-serializable value\n [key in Operator]?: JsonValue\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n and?: Where[]\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n or?: Where[]\n}\n\nexport type Sort = Array<string> | string\n\ntype SerializableValue = boolean | number | object | string\nexport type DefaultValue =\n | ((args: {\n locale?: TypedLocale\n req: PayloadRequest\n user: PayloadRequest['user']\n }) => Promise<SerializableValue> | SerializableValue)\n | SerializableValue\n\n/**\n * Applies pagination for join fields for including collection relationships\n */\nexport type JoinQuery<TSlug extends CollectionSlug = string> =\n TypedCollectionJoins[TSlug] extends Record<string, string>\n ?\n | false\n | Partial<{\n [K in keyof TypedCollectionJoins[TSlug]]:\n | {\n count?: boolean\n limit?: number\n page?: number\n sort?: string\n where?: Where\n }\n | false\n }>\n : never\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\nexport type Operation = 'create' | 'delete' | 'read' | 'update'\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n\nexport type SelectIncludeType = {\n [k: string]: SelectIncludeType | true\n}\n\nexport type SelectExcludeType = {\n [k: string]: false | SelectExcludeType\n}\n\nexport type SelectMode = 'exclude' | 'include'\n\nexport type SelectType = SelectExcludeType | SelectIncludeType\n\n/**\n * Operations that invoke an entity-level `select` function.\n *\n * Narrower than `HookOperationType`: `select` runs only for read- and\n * write-path operations that materialize a document (`create`, `delete`,\n * `read`, `restoreVersion`, `update`). Operations like `autosave`, `count`,\n * `countVersions`, `forgotPassword`, `login`, `readDistinct`, `refresh`, and\n * `resetPassword` do not invoke `select` and are intentionally excluded.\n */\nexport type SelectFnOperation = 'create' | 'delete' | 'read' | 'restoreVersion' | 'update'\n\nexport type SelectFnArgs = {\n operation: SelectFnOperation\n req: PayloadRequest\n /** The caller's `select` arg, or `undefined` if not provided. */\n select?: SelectType\n}\n\nexport type SelectFn<TSelect extends SelectType = SelectType> = (\n args: SelectFnArgs,\n) => TSelect | undefined\n\n/**\n * Shared shape for the entity-level `select` config used by Collections and Globals.\n * The JSDoc on the `select` property is the single source of truth — pick from this\n * type when defining the config:\n *\n * & Pick<WithSelectFn<...>, 'select'>\n */\nexport type WithSelectFn<TSelect extends SelectType = SelectType> = {\n /**\n * Entity-level Select API configuration.\n *\n * A function that receives the current request context (`operation`, `req`,\n * the caller's `select`) and returns the final `select` to apply, replacing\n * the caller's. Return `undefined` to leave the caller's `select` unchanged.\n *\n * Useful to dynamically modify the caller's selection based on the request context:\n * - Forcing a field to be populated for reference within hooks / access control.\n * - Differentiating between API requests and admin panel requests, to optimize\n * the amount of data being queried in each case.\n *\n * Note: per-document data is not available — this runs before the read.\n *\n * @see https://payloadcms.com/docs/queries/select\n */\n select?: SelectFn<TSelect>\n}\n\nexport type ApplyDisableErrors<T, DisableErrors = false> = false extends DisableErrors\n ? T\n : null | T\n\nexport type TransformDataWithSelect<\n Data extends Record<string, any>,\n Select extends SelectType,\n> = Select extends never\n ? Data\n : string extends keyof Select\n ? Data\n : // START Handle types when they aren't generated\n // For example in any package in this repository outside of tests / plugins\n // This stil gives us autocomplete when using include select mode, i.e select: {title :true} returns type {title: any, id: string | number}\n string extends keyof Omit<Data, 'id'>\n ? Select extends SelectIncludeType\n ? {\n [K in Data extends TypeWithID ? 'id' | keyof Select : keyof Select]: K extends 'id'\n ? number | string\n : unknown\n }\n : Data\n : // END Handle types when they aren't generated\n // Handle include mode\n Select extends SelectIncludeType\n ? {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | true\n ? K\n : never\n : // select 'id' always\n K extends 'id'\n ? K\n : never]: Data[K]\n }\n : // Handle exclude mode\n {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | undefined\n ? K\n : never\n : K]: Data[K]\n }\n\nexport type TransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromCollectionSlug<TSlug>, TSelect>\n : DataFromCollectionSlug<TSlug>\n\nexport type DraftTransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<QueryDraftDataFromCollectionSlug<TSlug>, TSelect>\n : QueryDraftDataFromCollectionSlug<TSlug>\n\nexport type TransformGlobalWithSelect<\n TSlug extends GlobalSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromGlobalSlug<TSlug>, TSelect>\n : DataFromGlobalSlug<TSlug>\n\nexport type PopulateType = Partial<TypedCollectionSelect>\n\nexport type ResolvedFilterOptions = { [collection: string]: Where }\n\nexport type PickPreserveOptional<T, K extends keyof T> = Partial<\n Pick<T, Extract<K, OptionalKeys<T>>>\n> &\n Pick<T, Extract<K, RequiredKeys<T>>>\n\nexport type MaybePromise<T> = Promise<T> | T\n"],"names":["docHasTimestamps","doc","createdAt","updatedAt"],"mappings":"AAqMA,OAAO,SAASA,iBAAiBC,GAAQ;IACvC,OAAOA,KAAKC,aAAaD,KAAKE;AAChC"}
@@ -3,5 +3,5 @@ import type { checkFileRestrictionsParams, FileAllowList } from './types.js';
3
3
  * Restricted file types and their extensions.
4
4
  */
5
5
  export declare const RESTRICTED_FILE_EXT_AND_TYPES: FileAllowList;
6
- export declare const checkFileRestrictions: ({ collection, file, req, }: checkFileRestrictionsParams) => Promise<void>;
6
+ export declare const checkFileRestrictions: ({ checkFileContents, collection, file, req, }: checkFileRestrictionsParams) => Promise<void>;
7
7
  //# sourceMappingURL=checkFileRestrictions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"checkFileRestrictions.d.ts","sourceRoot":"","sources":["../../src/uploads/checkFileRestrictions.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,2BAA2B,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAS5E;;GAEG;AACH,eAAO,MAAM,6BAA6B,EAAE,aAgC3C,CAAA;AAED,eAAO,MAAM,qBAAqB,+BAI/B,2BAA2B,KAAG,OAAO,CAAC,IAAI,CAyJ5C,CAAA"}
1
+ {"version":3,"file":"checkFileRestrictions.d.ts","sourceRoot":"","sources":["../../src/uploads/checkFileRestrictions.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,2BAA2B,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAS5E;;GAEG;AACH,eAAO,MAAM,6BAA6B,EAAE,aAgC3C,CAAA;AAED,eAAO,MAAM,qBAAqB,kDAK/B,2BAA2B,KAAG,OAAO,CAAC,IAAI,CA2K5C,CAAA"}
@@ -219,7 +219,7 @@ import { validateSvg } from './validateSvg.js';
219
219
  mimeType: 'application/x-command'
220
220
  }
221
221
  ];
222
- export const checkFileRestrictions = async ({ collection, file, req })=>{
222
+ export const checkFileRestrictions = async ({ checkFileContents = true, collection, file, req })=>{
223
223
  const errors = [];
224
224
  const { upload: uploadConfig } = collection;
225
225
  const configMimeTypes = uploadConfig && typeof uploadConfig === 'object' && 'mimeTypes' in uploadConfig && Array.isArray(uploadConfig.mimeTypes) ? uploadConfig.mimeTypes : [];
@@ -240,6 +240,20 @@ export const checkFileRestrictions = async ({ collection, file, req })=>{
240
240
  if (allowRestrictedFileTypes) {
241
241
  return;
242
242
  }
243
+ if (!checkFileContents) {
244
+ const isAllowed = configMimeTypes.length ? validateMimeType(file.mimetype, configMimeTypes) : !RESTRICTED_FILE_EXT_AND_TYPES.some(({ extensions, mimeType })=>mimeType === file.mimetype || extensions.some((extension)=>file.name.toLowerCase().endsWith(extension)));
245
+ if (!isAllowed) {
246
+ throw new ValidationError({
247
+ errors: [
248
+ {
249
+ message: `File type '${file.mimetype}' is not allowed.`,
250
+ path: 'file'
251
+ }
252
+ ]
253
+ });
254
+ }
255
+ return;
256
+ }
243
257
  // For temp files, use fileTypeFromFile so large files (e.g. video) are never loaded into memory
244
258
  // just for detection. For content validation (SVG safety, PDF integrity), the full buffer is
245
259
  // loaded lazily and only when the file type actually requires it.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/checkFileRestrictions.ts"],"sourcesContent":["import { fileTypeFromBuffer, fileTypeFromFile } from 'file-type'\nimport fs from 'fs/promises'\n\nimport type { checkFileRestrictionsParams, FileAllowList } from './types.js'\n\nimport { ValidationError } from '../errors/index.js'\nimport { validateMimeType } from '../utilities/validateMimeType.js'\nimport { validatePDF } from '../utilities/validatePDF.js'\nimport { detectSvgFromXml } from './detectSvgFromXml.js'\nimport { getFileTypeFallback } from './getFileTypeFallback.js'\nimport { validateSvg } from './validateSvg.js'\n\n/**\n * Restricted file types and their extensions.\n */\nexport const RESTRICTED_FILE_EXT_AND_TYPES: FileAllowList = [\n { extensions: ['exe', 'dll'], mimeType: 'application/x-msdownload' },\n { extensions: ['exe', 'com', 'app', 'action'], mimeType: 'application/x-executable' },\n { extensions: ['bat', 'cmd'], mimeType: 'application/x-msdos-program' },\n { extensions: ['exe', 'com'], mimeType: 'application/x-ms-dos-executable' },\n { extensions: ['dmg'], mimeType: 'application/x-apple-diskimage' },\n { extensions: ['deb'], mimeType: 'application/x-debian-package' },\n { extensions: ['rpm'], mimeType: 'application/x-redhat-package-manager' },\n { extensions: ['exe', 'dll'], mimeType: 'application/vnd.microsoft.portable-executable' },\n { extensions: ['msi'], mimeType: 'application/x-msi' },\n { extensions: ['jar', 'ear', 'war'], mimeType: 'application/java-archive' },\n { extensions: ['desktop'], mimeType: 'application/x-desktop' },\n { extensions: ['cpl'], mimeType: 'application/x-cpl' },\n { extensions: ['lnk'], mimeType: 'application/x-ms-shortcut' },\n { extensions: ['pkg'], mimeType: 'application/x-apple-installer' },\n { extensions: ['htm', 'html', 'shtml', 'xhtml'], mimeType: 'text/html' },\n { extensions: ['php', 'phtml'], mimeType: 'application/x-httpd-php' },\n { extensions: ['js', 'jse'], mimeType: 'text/javascript' },\n { extensions: ['jsp'], mimeType: 'application/x-jsp' },\n { extensions: ['py'], mimeType: 'text/x-python' },\n { extensions: ['rb'], mimeType: 'text/x-ruby' },\n { extensions: ['pl'], mimeType: 'text/x-perl' },\n { extensions: ['ps1', 'psc1', 'psd1', 'psh', 'psm1'], mimeType: 'application/x-powershell' },\n { extensions: ['vbe', 'vbs'], mimeType: 'application/x-vbscript' },\n { extensions: ['ws', 'wsc', 'wsf', 'wsh'], mimeType: 'application/x-ms-wsh' },\n { extensions: ['scr'], mimeType: 'application/x-msdownload' },\n { extensions: ['asp', 'aspx'], mimeType: 'application/x-asp' },\n { extensions: ['hta'], mimeType: 'application/x-hta' },\n { extensions: ['reg'], mimeType: 'application/x-registry' },\n { extensions: ['url'], mimeType: 'application/x-url' },\n { extensions: ['workflow'], mimeType: 'application/x-workflow' },\n { extensions: ['command'], mimeType: 'application/x-command' },\n]\n\nexport const checkFileRestrictions = async ({\n collection,\n file,\n req,\n}: checkFileRestrictionsParams): Promise<void> => {\n const errors: string[] = []\n const { upload: uploadConfig } = collection\n const configMimeTypes =\n uploadConfig &&\n typeof uploadConfig === 'object' &&\n 'mimeTypes' in uploadConfig &&\n Array.isArray(uploadConfig.mimeTypes)\n ? uploadConfig.mimeTypes\n : []\n\n const allowRestrictedFileTypes =\n uploadConfig && typeof uploadConfig === 'object' && 'allowRestrictedFileTypes' in uploadConfig\n ? (uploadConfig as { allowRestrictedFileTypes?: boolean }).allowRestrictedFileTypes\n : false\n\n const expectsDetectableType = (mimeType: string): boolean => {\n const textBasedTypes = ['/svg', 'image/svg+xml', 'image/x-xbitmap', 'image/x-xpixmap']\n\n if (textBasedTypes.includes(mimeType)) {\n return false\n }\n\n return (\n mimeType.startsWith('image/') ||\n mimeType.startsWith('video/') ||\n mimeType.startsWith('audio/') ||\n mimeType === 'application/pdf'\n )\n }\n\n // Skip validation if `allowRestrictedFileTypes` is true\n if (allowRestrictedFileTypes) {\n return\n }\n\n // For temp files, use fileTypeFromFile so large files (e.g. video) are never loaded into memory\n // just for detection. For content validation (SVG safety, PDF integrity), the full buffer is\n // loaded lazily and only when the file type actually requires it.\n const { tempFilePath } = file\n const isTempFile = !!tempFilePath && (!file.data || file.data.length === 0)\n\n // Lazily reads the full file — only reached for small text-based types (SVG, PDF).\n let _fileBuffer: Buffer | undefined\n const getFileBuffer = async (): Promise<Buffer> => {\n if (_fileBuffer) {\n return _fileBuffer\n }\n if (!isTempFile || !tempFilePath) {\n return (_fileBuffer = file.data)\n }\n try {\n _fileBuffer = await fs.readFile(tempFilePath)\n return _fileBuffer\n } catch {\n throw new ValidationError({\n errors: [{ message: 'Could not read uploaded file for validation.', path: 'file' }],\n })\n }\n }\n\n // Secondary mimetype check to assess file type from buffer\n if (configMimeTypes.length > 0) {\n let detected\n try {\n detected =\n isTempFile && tempFilePath\n ? await fileTypeFromFile(tempFilePath)\n : await fileTypeFromBuffer(file.data)\n } catch {\n throw new ValidationError({\n errors: [{ message: 'Could not read uploaded file for type detection.', path: 'file' }],\n })\n }\n const typeFromExtension = file.name.split('.').pop() || ''\n\n // Handle SVG files that are detected as XML due to <?xml declarations\n if (\n detected?.mime === 'application/xml' &&\n configMimeTypes.some(\n (type) => type.includes('image/') && (type.includes('svg') || type === 'image/*'),\n )\n ) {\n const isSvg = detectSvgFromXml(await getFileBuffer())\n if (isSvg) {\n detected = { ext: 'svg', mime: 'image/svg+xml' }\n }\n }\n\n if (!detected) {\n const mimeTypeFromExtension = getFileTypeFallback(file.name).mime\n const extIsValid = validateMimeType(mimeTypeFromExtension, configMimeTypes)\n\n if (!extIsValid) {\n errors.push(\n `File type ${mimeTypeFromExtension} (from extension ${typeFromExtension}) is not allowed.`,\n )\n } else {\n // SVG security check (text-based files not detectable by buffer)\n if (typeFromExtension.toLowerCase() === 'svg') {\n const isSafeSvg = validateSvg(await getFileBuffer())\n if (!isSafeSvg) {\n errors.push('SVG file contains potentially harmful content.')\n }\n }\n\n // PDF validation\n if (mimeTypeFromExtension === 'application/pdf') {\n const isValidPDF = validatePDF(await getFileBuffer())\n if (!isValidPDF) {\n errors.push('Invalid or corrupted PDF file.')\n }\n }\n }\n\n if (expectsDetectableType(mimeTypeFromExtension)) {\n req.payload.logger.warn(\n `File buffer returned no detectable MIME type for ${file.name}. Falling back to extension-based validation.`,\n )\n }\n }\n\n const passesMimeTypeCheck = detected?.mime && validateMimeType(detected.mime, configMimeTypes)\n\n if (passesMimeTypeCheck && detected?.mime === 'application/pdf') {\n const isValidPDF = validatePDF(await getFileBuffer())\n if (!isValidPDF) {\n errors.push('Invalid PDF file.')\n }\n }\n\n if (detected && !passesMimeTypeCheck) {\n errors.push(`Invalid MIME type: ${detected.mime}.`)\n }\n } else {\n const isRestricted = RESTRICTED_FILE_EXT_AND_TYPES.some((type) => {\n const hasRestrictedExt = type.extensions.some((ext) => file.name.toLowerCase().endsWith(ext))\n const hasRestrictedMime = type.mimeType === file.mimetype\n return hasRestrictedExt || hasRestrictedMime\n })\n if (isRestricted) {\n errors.push(\n `File type '${file.mimetype}' not allowed ${file.name}: Restricted file type detected -- set 'allowRestrictedFileTypes' to true to skip this check for this Collection.`,\n )\n }\n }\n\n if (errors.length > 0) {\n req.payload.logger.error(errors.join(', '))\n throw new ValidationError({\n errors: [{ message: errors.join(', '), path: 'file' }],\n })\n }\n}\n"],"names":["fileTypeFromBuffer","fileTypeFromFile","fs","ValidationError","validateMimeType","validatePDF","detectSvgFromXml","getFileTypeFallback","validateSvg","RESTRICTED_FILE_EXT_AND_TYPES","extensions","mimeType","checkFileRestrictions","collection","file","req","errors","upload","uploadConfig","configMimeTypes","Array","isArray","mimeTypes","allowRestrictedFileTypes","expectsDetectableType","textBasedTypes","includes","startsWith","tempFilePath","isTempFile","data","length","_fileBuffer","getFileBuffer","readFile","message","path","detected","typeFromExtension","name","split","pop","mime","some","type","isSvg","ext","mimeTypeFromExtension","extIsValid","push","toLowerCase","isSafeSvg","isValidPDF","payload","logger","warn","passesMimeTypeCheck","isRestricted","hasRestrictedExt","endsWith","hasRestrictedMime","mimetype","error","join"],"mappings":"AAAA,SAASA,kBAAkB,EAAEC,gBAAgB,QAAQ,YAAW;AAChE,OAAOC,QAAQ,cAAa;AAI5B,SAASC,eAAe,QAAQ,qBAAoB;AACpD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,WAAW,QAAQ,mBAAkB;AAE9C;;CAEC,GACD,OAAO,MAAMC,gCAA+C;IAC1D;QAAEC,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAA2B;IACnE;QAAED,YAAY;YAAC;YAAO;YAAO;YAAO;SAAS;QAAEC,UAAU;IAA2B;IACpF;QAAED,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAA8B;IACtE;QAAED,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAAkC;IAC1E;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAgC;IACjE;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAA+B;IAChE;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAuC;IACxE;QAAED,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAAgD;IACxF;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAoB;IACrD;QAAED,YAAY;YAAC;YAAO;YAAO;SAAM;QAAEC,UAAU;IAA2B;IAC1E;QAAED,YAAY;YAAC;SAAU;QAAE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iDAAiD,EAAEzC,KAAKyB,IAAI,CAAC,6CAA6C,CAAC;YAEhH;QACF;QAEA,MAAMiB,sBAAsBnB,UAAUK,QAAQtC,iBAAiBiC,SAASK,IAAI,EAAEvB;QAE9E,IAAIqC,uBAAuBnB,UAAUK,SAAS,mBAAmB;YAC/D,MAAMU,aAAa/C,YAAY,MAAM4B;YACrC,IAAI,CAACmB,YAAY;gBACfpC,OAAOiC,IAAI,CAAC;YACd;QACF;QAEA,IAAIZ,YAAY,CAACmB,qBAAqB;YACpCxC,OAAOiC,IAAI,CAAC,CAAC,mBAAmB,EAAEZ,SAASK,IAAI,CAAC,CAAC,CAAC;QACpD;IACF,OAAO;QACL,MAAMe,eAAehD,8BAA8BkC,IAAI,CAAC,CAACC;YACvD,MAAMc,mBAAmBd,KAAKlC,UAAU,CAACiC,IAAI,CAAC,CAACG,MAAQhC,KAAKyB,IAAI,CAACW,WAAW,GAAGS,QAAQ,CAACb;YACxF,MAAMc,oBAAoBhB,KAAKjC,QAAQ,KAAKG,KAAK+C,QAAQ;YACzD,OAAOH,oBAAoBE;QAC7B;QACA,IAAIH,cAAc;YAChBzC,OAAOiC,IAAI,CACT,CAAC,WAAW,EAAEnC,KAAK+C,QAAQ,CAAC,cAAc,EAAE/C,KAAKyB,IAAI,CAAC,iHAAiH,CAAC;QAE5K;IACF;IAEA,IAAIvB,OAAOe,MAAM,GAAG,GAAG;QACrBhB,IAAIsC,OAAO,CAACC,MAAM,CAACQ,KAAK,CAAC9C,OAAO+C,IAAI,CAAC;QACrC,MAAM,IAAI5D,gBAAgB;YACxBa,QAAQ;gBAAC;oBAAEmB,SAASnB,OAAO+C,IAAI,CAAC;oBAAO3B,MAAM;gBAAO;aAAE;QACxD;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/uploads/checkFileRestrictions.ts"],"sourcesContent":["import { fileTypeFromBuffer, fileTypeFromFile } from 'file-type'\nimport fs from 'fs/promises'\n\nimport type { checkFileRestrictionsParams, FileAllowList } from './types.js'\n\nimport { ValidationError } from '../errors/index.js'\nimport { validateMimeType } from '../utilities/validateMimeType.js'\nimport { validatePDF } from '../utilities/validatePDF.js'\nimport { detectSvgFromXml } from './detectSvgFromXml.js'\nimport { getFileTypeFallback } from './getFileTypeFallback.js'\nimport { validateSvg } from './validateSvg.js'\n\n/**\n * Restricted file types and their extensions.\n */\nexport const RESTRICTED_FILE_EXT_AND_TYPES: FileAllowList = [\n { extensions: ['exe', 'dll'], mimeType: 'application/x-msdownload' },\n { extensions: ['exe', 'com', 'app', 'action'], mimeType: 'application/x-executable' },\n { extensions: ['bat', 'cmd'], mimeType: 'application/x-msdos-program' },\n { extensions: ['exe', 'com'], mimeType: 'application/x-ms-dos-executable' },\n { extensions: ['dmg'], mimeType: 'application/x-apple-diskimage' },\n { extensions: ['deb'], mimeType: 'application/x-debian-package' },\n { extensions: ['rpm'], mimeType: 'application/x-redhat-package-manager' },\n { extensions: ['exe', 'dll'], mimeType: 'application/vnd.microsoft.portable-executable' },\n { extensions: ['msi'], mimeType: 'application/x-msi' },\n { extensions: ['jar', 'ear', 'war'], mimeType: 'application/java-archive' },\n { extensions: ['desktop'], mimeType: 'application/x-desktop' },\n { extensions: ['cpl'], mimeType: 'application/x-cpl' },\n { extensions: ['lnk'], mimeType: 'application/x-ms-shortcut' },\n { extensions: ['pkg'], mimeType: 'application/x-apple-installer' },\n { extensions: ['htm', 'html', 'shtml', 'xhtml'], mimeType: 'text/html' },\n { extensions: ['php', 'phtml'], mimeType: 'application/x-httpd-php' },\n { extensions: ['js', 'jse'], mimeType: 'text/javascript' },\n { extensions: ['jsp'], mimeType: 'application/x-jsp' },\n { extensions: ['py'], mimeType: 'text/x-python' },\n { extensions: ['rb'], mimeType: 'text/x-ruby' },\n { extensions: ['pl'], mimeType: 'text/x-perl' },\n { extensions: ['ps1', 'psc1', 'psd1', 'psh', 'psm1'], mimeType: 'application/x-powershell' },\n { extensions: ['vbe', 'vbs'], mimeType: 'application/x-vbscript' },\n { extensions: ['ws', 'wsc', 'wsf', 'wsh'], mimeType: 'application/x-ms-wsh' },\n { extensions: ['scr'], mimeType: 'application/x-msdownload' },\n { extensions: ['asp', 'aspx'], mimeType: 'application/x-asp' },\n { extensions: ['hta'], mimeType: 'application/x-hta' },\n { extensions: ['reg'], mimeType: 'application/x-registry' },\n { extensions: ['url'], mimeType: 'application/x-url' },\n { extensions: ['workflow'], mimeType: 'application/x-workflow' },\n { extensions: ['command'], mimeType: 'application/x-command' },\n]\n\nexport const checkFileRestrictions = async ({\n checkFileContents = true,\n collection,\n file,\n req,\n}: checkFileRestrictionsParams): Promise<void> => {\n const errors: string[] = []\n const { upload: uploadConfig } = collection\n const configMimeTypes =\n uploadConfig &&\n typeof uploadConfig === 'object' &&\n 'mimeTypes' in uploadConfig &&\n Array.isArray(uploadConfig.mimeTypes)\n ? uploadConfig.mimeTypes\n : []\n\n const allowRestrictedFileTypes =\n uploadConfig && typeof uploadConfig === 'object' && 'allowRestrictedFileTypes' in uploadConfig\n ? (uploadConfig as { allowRestrictedFileTypes?: boolean }).allowRestrictedFileTypes\n : false\n\n const expectsDetectableType = (mimeType: string): boolean => {\n const textBasedTypes = ['/svg', 'image/svg+xml', 'image/x-xbitmap', 'image/x-xpixmap']\n\n if (textBasedTypes.includes(mimeType)) {\n return false\n }\n\n return (\n mimeType.startsWith('image/') ||\n mimeType.startsWith('video/') ||\n mimeType.startsWith('audio/') ||\n mimeType === 'application/pdf'\n )\n }\n\n // Skip validation if `allowRestrictedFileTypes` is true\n if (allowRestrictedFileTypes) {\n return\n }\n\n if (!checkFileContents) {\n const isAllowed = configMimeTypes.length\n ? validateMimeType(file.mimetype, configMimeTypes)\n : !RESTRICTED_FILE_EXT_AND_TYPES.some(\n ({ extensions, mimeType }) =>\n mimeType === file.mimetype ||\n extensions.some((extension) => file.name.toLowerCase().endsWith(extension)),\n )\n\n if (!isAllowed) {\n throw new ValidationError({\n errors: [{ message: `File type '${file.mimetype}' is not allowed.`, path: 'file' }],\n })\n }\n\n return\n }\n\n // For temp files, use fileTypeFromFile so large files (e.g. video) are never loaded into memory\n // just for detection. For content validation (SVG safety, PDF integrity), the full buffer is\n // loaded lazily and only when the file type actually requires it.\n const { tempFilePath } = file\n const isTempFile = !!tempFilePath && (!file.data || file.data.length === 0)\n\n // Lazily reads the full file — only reached for small text-based types (SVG, PDF).\n let _fileBuffer: Buffer | undefined\n const getFileBuffer = async (): Promise<Buffer> => {\n if (_fileBuffer) {\n return _fileBuffer\n }\n if (!isTempFile || !tempFilePath) {\n return (_fileBuffer = file.data)\n }\n try {\n _fileBuffer = await fs.readFile(tempFilePath)\n return _fileBuffer\n } catch {\n throw new ValidationError({\n errors: [{ message: 'Could not read uploaded file for validation.', path: 'file' }],\n })\n }\n }\n\n // Secondary mimetype check to assess file type from buffer\n if (configMimeTypes.length > 0) {\n let detected\n try {\n detected =\n isTempFile && tempFilePath\n ? await fileTypeFromFile(tempFilePath)\n : await fileTypeFromBuffer(file.data)\n } catch {\n throw new ValidationError({\n errors: [{ message: 'Could not read uploaded file for type detection.', path: 'file' }],\n })\n }\n const typeFromExtension = file.name.split('.').pop() || ''\n\n // Handle SVG files that are detected as XML due to <?xml declarations\n if (\n detected?.mime === 'application/xml' &&\n configMimeTypes.some(\n (type) => type.includes('image/') && (type.includes('svg') || type === 'image/*'),\n )\n ) {\n const isSvg = detectSvgFromXml(await getFileBuffer())\n if (isSvg) {\n detected = { ext: 'svg', mime: 'image/svg+xml' }\n }\n }\n\n if (!detected) {\n const mimeTypeFromExtension = getFileTypeFallback(file.name).mime\n const extIsValid = validateMimeType(mimeTypeFromExtension, configMimeTypes)\n\n if (!extIsValid) {\n errors.push(\n `File type ${mimeTypeFromExtension} (from extension ${typeFromExtension}) is not allowed.`,\n )\n } else {\n // SVG security check (text-based files not detectable by buffer)\n if (typeFromExtension.toLowerCase() === 'svg') {\n const isSafeSvg = validateSvg(await getFileBuffer())\n if (!isSafeSvg) {\n errors.push('SVG file contains potentially harmful content.')\n }\n }\n\n // PDF validation\n if (mimeTypeFromExtension === 'application/pdf') {\n const isValidPDF = validatePDF(await getFileBuffer())\n if (!isValidPDF) {\n errors.push('Invalid or corrupted PDF file.')\n }\n }\n }\n\n if (expectsDetectableType(mimeTypeFromExtension)) {\n req.payload.logger.warn(\n `File buffer returned no detectable MIME type for ${file.name}. Falling back to extension-based validation.`,\n )\n }\n }\n\n const passesMimeTypeCheck = detected?.mime && validateMimeType(detected.mime, configMimeTypes)\n\n if (passesMimeTypeCheck && detected?.mime === 'application/pdf') {\n const isValidPDF = validatePDF(await getFileBuffer())\n if (!isValidPDF) {\n errors.push('Invalid PDF file.')\n }\n }\n\n if (detected && !passesMimeTypeCheck) {\n errors.push(`Invalid MIME type: ${detected.mime}.`)\n }\n } else {\n const isRestricted = RESTRICTED_FILE_EXT_AND_TYPES.some((type) => {\n const hasRestrictedExt = type.extensions.some((ext) => file.name.toLowerCase().endsWith(ext))\n const hasRestrictedMime = type.mimeType === file.mimetype\n return hasRestrictedExt || hasRestrictedMime\n })\n if (isRestricted) {\n errors.push(\n `File type '${file.mimetype}' not allowed ${file.name}: Restricted file type detected -- set 'allowRestrictedFileTypes' to true to skip this check for this Collection.`,\n )\n }\n }\n\n if (errors.length > 0) {\n req.payload.logger.error(errors.join(', '))\n throw new ValidationError({\n errors: [{ message: errors.join(', '), path: 'file' }],\n })\n }\n}\n"],"names":["fileTypeFromBuffer","fileTypeFromFile","fs","ValidationError","validateMimeType","validatePDF","detectSvgFromXml","getFileTypeFallback","validateSvg","RESTRICTED_FILE_EXT_AND_TYPES","extensions","mimeType","checkFileRestrictions","checkFileContents","collection","file","req","errors","upload","uploadConfig","configMimeTypes","Array","isArray","mimeTypes","allowRestrictedFileTypes","expectsDetectableType","textBasedTypes","includes","startsWith","isAllowed","length","mimetype","some","extension","name","toLowerCase","endsWith","message","path","tempFilePath","isTempFile","data","_fileBuffer","getFileBuffer","readFile","detected","typeFromExtension","split","pop","mime","type","isSvg","ext","mimeTypeFromExtension","extIsValid","push","isSafeSvg","isValidPDF","payload","logger","warn","passesMimeTypeCheck","isRestricted","hasRestrictedExt","hasRestrictedMime","error","join"],"mappings":"AAAA,SAASA,kBAAkB,EAAEC,gBAAgB,QAAQ,YAAW;AAChE,OAAOC,QAAQ,cAAa;AAI5B,SAASC,eAAe,QAAQ,qBAAoB;AACpD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,WAAW,QAAQ,mBAAkB;AAE9C;;CAEC,GACD,OAAO,MAAMC,gCAA+C;IAC1D;QAAEC,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAA2B;IACnE;QAAED,YAAY;YAAC;YAAO;YAAO;YAAO;SAAS;QAAEC,UAAU;IAA2B;IACpF;QAAED,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAA8B;IACtE;QAAED,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAAkC;IAC1E;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAgC;IACjE;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAA+B;IAChE;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAuC;IACxE;QAAED,YAAY;YAAC;YAAO;SAAM;QAAEC,UAAU;IAAgD;IACxF;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAoB;IACrD;QAAED,YAAY;YAAC;YAAO;YAAO;SAAM;QAAEC,UAAU;IAA2B;IAC1E;QAAED,YAAY;YAAC;SAAU;QAAEC,UAAU;IAAwB;IAC7D;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAoB;IACrD;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAA4B;IAC7D;QAAED,YAAY;YAAC;SAAM;QAAEC,UAAU;IAAgC;IACjE;QAAED,YAAY;YAAC;YAAO;YAAQ;YAAS;S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CAAChD,OAAOiD,IAAI,CAAC;QACrC,MAAM,IAAI/D,gBAAgB;YACxBc,QAAQ;gBAAC;oBAAEoB,SAASpB,OAAOiD,IAAI,CAAC;oBAAO5B,MAAM;gBAAO;aAAE;QACxD;IACF;AACF,EAAC"}
@@ -1,3 +1,15 @@
1
1
  import type { Endpoint } from '../../config/types.js';
2
+ import type { PayloadRequest } from '../../types/index.js';
3
+ import type { UploadInstructions, UploadInstructionsRequest } from '../types.js';
4
+ export declare const getUploadInstructions: ({ overrideAccess, req, ...upload }: {
5
+ overrideAccess?: boolean;
6
+ req: PayloadRequest;
7
+ } & UploadInstructionsRequest) => Promise<UploadInstructions>;
2
8
  export declare const uploadInstructionsEndpoint: Endpoint;
9
+ /**
10
+ * Stores or removes temporary files when no adapter-specific upload instructions are available.
11
+ * PUT keeps the file until it is used in a document request.
12
+ * DELETE removes a file the client no longer needs.
13
+ */
14
+ export declare const stagedUploadEndpoints: Endpoint[];
3
15
  //# sourceMappingURL=uploadInstructions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"uploadInstructions.d.ts","sourceRoot":"","sources":["../../../src/uploads/endpoints/uploadInstructions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAA;AAOrD,eAAO,MAAM,0BAA0B,EAAE,QAkDxC,CAAA"}
1
+ {"version":3,"file":"uploadInstructions.d.ts","sourceRoot":"","sources":["../../../src/uploads/endpoints/uploadInstructions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAA;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,KAAK,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAA;AA8BhF,eAAO,MAAM,qBAAqB,uCAI/B;IACD,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,yBAAyB,KAAG,OAAO,CAAC,kBAAkB,CA+CzD,CAAA;AAED,eAAO,MAAM,0BAA0B,EAAE,QAexC,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,EAAE,QAAQ,EAW3C,CAAA"}