payload 4.0.0-beta.4 → 4.0.0-beta.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,kBAAkB,EAAqB,MAAM,gBAAgB,CAAA;AAC3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAkB1D,MAAM,MAAM,MAAM,GAAG;IACnB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC9B,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE;QACJ,QAAQ,EAAE,MAAM,CAAA;QAChB,KAAK,EAAE,MAAM,CAAA;KACd,CAAA;IACD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAU,KAAK,SAAS,kBAAkB,QACrE,SAAS,KACd,OAAO,CAAC,MAAM,CAyOhB,CAAA"}
1
+ {"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAGX,MAAM,mCAAmC,CAAA;AAE1C,OAAO,KAAK,EAAE,kBAAkB,EAAqB,MAAM,gBAAgB,CAAA;AAC3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAkB1D,MAAM,MAAM,MAAM,GAAG;IACnB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC9B,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE;QACJ,QAAQ,EAAE,MAAM,CAAA;QAChB,KAAK,EAAE,MAAM,CAAA;KACd,CAAA;IACD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAU,KAAK,SAAS,kBAAkB,QACrE,SAAS,KACd,OAAO,CAAC,MAAM,CAiPhB,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
2
2
  import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
3
- import { APIError, Forbidden } from '../../errors/index.js';
3
+ import { APIError, Forbidden, ValidationError } from '../../errors/index.js';
4
4
  import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js';
5
5
  import { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js';
6
6
  import { commitTransaction } from '../../utilities/commitTransaction.js';
@@ -55,6 +55,13 @@ export const resetPasswordOperation = async (args)=>{
55
55
  if (!user) {
56
56
  throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN);
57
57
  }
58
+ await validatePasswordField({
59
+ collectionConfig,
60
+ overrideAccess,
61
+ password: data.password,
62
+ req,
63
+ user
64
+ });
58
65
  // TODO: replace this method
59
66
  const { hash, salt } = await generatePasswordSaltHash({
60
67
  collection: collectionConfig,
@@ -198,5 +205,47 @@ export const resetPasswordOperation = async (args)=>{
198
205
  throw error;
199
206
  }
200
207
  };
208
+ /**
209
+ * Runs the `password` field override's validation, which `payload.db.updateOne` skips.
210
+ */ async function validatePasswordField({ collectionConfig, overrideAccess, password, req, user }) {
211
+ const passwordField = collectionConfig.flattenedFields.find((field)=>field.name === 'password');
212
+ if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {
213
+ return;
214
+ }
215
+ const validate = passwordField.validate;
216
+ const dataToValidate = {
217
+ ...user,
218
+ password
219
+ };
220
+ const validationResult = await validate(password, {
221
+ ...passwordField,
222
+ id: user.id,
223
+ blockData: {},
224
+ collectionSlug: collectionConfig.slug,
225
+ data: dataToValidate,
226
+ event: 'submit',
227
+ operation: 'update',
228
+ overrideAccess,
229
+ path: [
230
+ 'password'
231
+ ],
232
+ preferences: {
233
+ fields: {}
234
+ },
235
+ req,
236
+ siblingData: dataToValidate
237
+ });
238
+ if (typeof validationResult === 'string') {
239
+ throw new ValidationError({
240
+ collection: collectionConfig.slug,
241
+ errors: [
242
+ {
243
+ message: validationResult,
244
+ path: 'password'
245
+ }
246
+ ]
247
+ });
248
+ }
249
+ }
201
250
 
202
251
  //# sourceMappingURL=resetPassword.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js'\nimport type { AuthCollectionSlug, AuthenticatedUser } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError, Forbidden } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser, revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\n\nexport type Result = {\n token?: string\n user: Record<string, unknown>\n}\n\nexport type Arguments = {\n collection: Collection\n data: {\n password: string\n token: string\n }\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const resetPasswordOperation = async <TSlug extends AuthCollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req: {\n payload: { secret },\n payload,\n },\n req,\n } = args\n\n assertNoValidationWrite(req)\n\n if (\n !Object.prototype.hasOwnProperty.call(data, 'token') ||\n !Object.prototype.hasOwnProperty.call(data, 'password')\n ) {\n throw new APIError('Missing required data.', httpStatus.BAD_REQUEST)\n }\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n\n let sid: string | undefined\n let sessionUser: AuthenticatedUser | null = null\n\n try {\n const shouldCommit = await initTransaction(req)\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'resetPassword',\n overrideAccess,\n })\n\n // /////////////////////////////////////\n // Reset Password\n // /////////////////////////////////////\n\n const where = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: {\n resetPasswordExpiration: { greater_than: new Date().toISOString() },\n resetPasswordToken: { equals: data.token },\n },\n })\n\n let user = await payload.db.findOne<AuthenticatedUser>({\n collection: collectionConfig.slug,\n req,\n where,\n })\n\n if (!user) {\n throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)\n }\n\n // TODO: replace this method\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password: data.password,\n req,\n })\n\n user.salt = salt\n user.hash = hash\n\n user.resetPasswordExpiration = new Date().toISOString()\n\n if (collectionConfig.auth.maxLoginAttempts > 0) {\n user.lockUntil = null\n user.loginAttempts = 0\n }\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n await hook({\n collection: args.collection?.config,\n context: req.context,\n data: user,\n operation: 'update',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Update new password\n // /////////////////////////////////////\n\n // Ensure updatedAt date is always updated\n user.updatedAt = new Date().toISOString()\n\n if (collectionConfig.auth.useSessions) {\n user.sessions = []\n }\n\n const doc = await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n await authenticateLocalStrategy({ doc, password: data.password })\n\n user = doc as AuthenticatedUser\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: user.email!,\n user,\n }\n\n const session = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n sessionUser = user\n sid = session.sid\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }\n }\n\n const { token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user\n }\n }\n\n user!.collection = collectionConfig.slug\n user!._strategy = 'local-jwt'\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: false,\n user: user!,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n overrideAccess,\n result,\n })\n\n return result\n } catch (error: unknown) {\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user: sessionUser,\n })\n }\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","APIError","Forbidden","appendNonTrashedFilter","assertNoValidationWrite","commitTransaction","httpStatus","initTransaction","killTransaction","applyUserReadAccess","getFieldsToSign","jwtSign","addSessionToUser","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","secret","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","sid","sessionUser","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","hash","salt","password","maxLoginAttempts","lockUntil","loginAttempts","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","useSessions","sessions","doc","updateOne","id","_strategy","fieldsToSignArgs","email","session","fieldsToSign","beforeLogin","tokenExpiration","afterLogin","userWithReadAccess","showHiddenFields","result","error"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,QAAQ,wBAAuB;AAC3D,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AAC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9C,iBAAiB2C,KAAK,CAACkB,UAAU,CAAE;gBACpD/B,OACE,AAAC,MAAMgB,KAAK;oBACVhD,YAAYD,KAAKC,UAAU,EAAEC;oBAC7BgD,SAASlD,KAAKO,GAAG,CAAC2C,OAAO;oBACzB3C,KAAKP,KAAKO,GAAG;oBACbyB;oBACAC;gBACF,MAAOA;YACX;QACF;QAEAA,KAAMhC,UAAU,GAAGE,iBAAiBiC,IAAI;QACxCH,KAAMwB,SAAS,GAAG;QAElB,MAAMQ,qBAAqB,MAAMzE,oBAAoB;YACnDS,YAAYE;YACZE,OAAOA;YACPC;YACAC;YACA2D,kBAAkB;YAClBjC,MAAMA;QACR;QAEA,IAAIb,cAAc;YAChB,MAAMhC,kBAAkBmB;QAC1B;QAEA,IAAI4D,SAA2D;YAC7DnC;YACAC,MAAMgC;QACR;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCE,SAAS,MAAMrF,oBAAoB;YACjCkB;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BmB,WAAW;YACXf;YACA6D;QACF;QAEA,OAAOA;IACT,EAAE,OAAOC,OAAgB;QACvB,IAAIlD,KAAK;YACP,MAAMtB,cAAc;gBAClBO;gBACAK;gBACAD;gBACAW;gBACAe,MAAMd;YACR;QACF;QACA,MAAM5B,gBAAgBgB;QACtB,MAAM6D;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import type {\n Collection,\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n} from '../../collections/config/types.js'\nimport type { Validate } from '../../fields/config/types.js'\nimport type { AuthCollectionSlug, AuthenticatedUser } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError, Forbidden, ValidationError } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser, revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\n\nexport type Result = {\n token?: string\n user: Record<string, unknown>\n}\n\nexport type Arguments = {\n collection: Collection\n data: {\n password: string\n token: string\n }\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const resetPasswordOperation = async <TSlug extends AuthCollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req: {\n payload: { secret },\n payload,\n },\n req,\n } = args\n\n assertNoValidationWrite(req)\n\n if (\n !Object.prototype.hasOwnProperty.call(data, 'token') ||\n !Object.prototype.hasOwnProperty.call(data, 'password')\n ) {\n throw new APIError('Missing required data.', httpStatus.BAD_REQUEST)\n }\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n\n let sid: string | undefined\n let sessionUser: AuthenticatedUser | null = null\n\n try {\n const shouldCommit = await initTransaction(req)\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'resetPassword',\n overrideAccess,\n })\n\n // /////////////////////////////////////\n // Reset Password\n // /////////////////////////////////////\n\n const where = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: {\n resetPasswordExpiration: { greater_than: new Date().toISOString() },\n resetPasswordToken: { equals: data.token },\n },\n })\n\n let user = await payload.db.findOne<AuthenticatedUser>({\n collection: collectionConfig.slug,\n req,\n where,\n })\n\n if (!user) {\n throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)\n }\n\n await validatePasswordField({\n collectionConfig,\n overrideAccess,\n password: data.password,\n req,\n user,\n })\n\n // TODO: replace this method\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password: data.password,\n req,\n })\n\n user.salt = salt\n user.hash = hash\n\n user.resetPasswordExpiration = new Date().toISOString()\n\n if (collectionConfig.auth.maxLoginAttempts > 0) {\n user.lockUntil = null\n user.loginAttempts = 0\n }\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n await hook({\n collection: args.collection?.config,\n context: req.context,\n data: user,\n operation: 'update',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Update new password\n // /////////////////////////////////////\n\n // Ensure updatedAt date is always updated\n user.updatedAt = new Date().toISOString()\n\n if (collectionConfig.auth.useSessions) {\n user.sessions = []\n }\n\n const doc = await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n await authenticateLocalStrategy({ doc, password: data.password })\n\n user = doc as AuthenticatedUser\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: user.email!,\n user,\n }\n\n const session = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n sessionUser = user\n sid = session.sid\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }\n }\n\n const { token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user\n }\n }\n\n user!.collection = collectionConfig.slug\n user!._strategy = 'local-jwt'\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: false,\n user: user!,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n overrideAccess,\n result,\n })\n\n return result\n } catch (error: unknown) {\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user: sessionUser,\n })\n }\n await killTransaction(req)\n throw error\n }\n}\n\n/**\n * Runs the `password` field override's validation, which `payload.db.updateOne` skips.\n */\nasync function validatePasswordField({\n collectionConfig,\n overrideAccess,\n password,\n req,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n overrideAccess: boolean\n password: string\n req: PayloadRequest\n user: AuthenticatedUser\n}): Promise<void> {\n const passwordField = collectionConfig.flattenedFields.find((field) => field.name === 'password')\n\n if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {\n return\n }\n\n const validate = passwordField.validate as Validate<string>\n const dataToValidate = { ...user, password }\n\n const validationResult = await validate(password, {\n ...passwordField,\n id: user.id,\n blockData: {},\n collectionSlug: collectionConfig.slug,\n data: dataToValidate,\n event: 'submit',\n operation: 'update',\n overrideAccess,\n path: ['password'],\n preferences: { fields: {} },\n req,\n siblingData: dataToValidate,\n })\n\n if (typeof validationResult === 'string') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: validationResult, path: 'password' }],\n })\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","APIError","Forbidden","ValidationError","appendNonTrashedFilter","assertNoValidationWrite","commitTransaction","httpStatus","initTransaction","killTransaction","applyUserReadAccess","getFieldsToSign","jwtSign","addSessionToUser","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","secret","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","sid","sessionUser","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","validatePasswordField","password","hash","salt","maxLoginAttempts","lockUntil","loginAttempts","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","useSessions","sessions","doc","updateOne","id","_strategy","fieldsToSignArgs","email","session","fieldsToSign","beforeLogin","tokenExpiration","afterLogin","userWithReadAccess","showHiddenFields","result","error","passwordField","flattenedFields","find","field","name","validate","dataToValidate","validationResult","blockData","collectionSlug","event","path","preferences","fields","siblingData","errors","message"],"mappings":"AASA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,EAAEC,eAAe,QAAQ,wBAAuB;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,UAAU,QAAQ,gCAA+B;AAC1D,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,4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MAAMF,SAASpC,UAAU;QAChD,GAAG+B,aAAa;QAChBb,IAAIxB,KAAKwB,EAAE;QACXqB,WAAW,CAAC;QACZC,gBAAgB5E,iBAAiBiC,IAAI;QACrChC,MAAMwE;QACNI,OAAO;QACP3D,WAAW;QACXf;QACA2E,MAAM;YAAC;SAAW;QAClBC,aAAa;YAAEC,QAAQ,CAAC;QAAE;QAC1B5E;QACA6E,aAAaR;IACf;IAEA,IAAI,OAAOC,qBAAqB,UAAU;QACxC,MAAM,IAAI5F,gBAAgB;YACxBgB,YAAYE,iBAAiBiC,IAAI;YACjCiD,QAAQ;gBAAC;oBAAEC,SAAST;oBAAkBI,MAAM;gBAAW;aAAE;QAC3D;IACF;AACF"}
@@ -11,9 +11,11 @@ function buildPluginsMap(plugins) {
11
11
  }
12
12
  export function definePlugin(descriptor) {
13
13
  return (options)=>{
14
+ // Read `pluginFn.options` when the plugin runs, so other plugins can edit or replace it, even
15
+ // when the plugin was registered without options
14
16
  const pluginFn = (config)=>descriptor.plugin({
15
17
  config,
16
- options: options,
18
+ options: pluginFn.options,
17
19
  plugins: buildPluginsMap(config.plugins)
18
20
  });
19
21
  if (options !== undefined) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map\n}\n\n/**\n * Helper for authoring plugins with order, slug, and typed options.\n * Eliminates boilerplate and ensures metadata is always set consistently.\n *\n * The `plugin` function receives `config`, `plugins` (a slug-keyed map of other\n * plugins), and the user-provided `options`.\n *\n * @experimental\n *\n * @example\n * // With options:\n * export const seoPlugin = definePlugin<SEOPluginConfig>({\n * slug: 'plugin-seo',\n * plugin: ({ config, options }) => ({ ...config }),\n * })\n *\n * // Without options:\n * export const myPlugin = definePlugin({\n * slug: 'my-plugin',\n * plugin: ({ config }) => ({ ...config }),\n * })\n */\nexport function definePlugin(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap }) => Config | Promise<Config>\n slug: string\n}): () => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): undefined extends TOptions ? (options?: TOptions) => Plugin : (options: TOptions) => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): (options: TOptions) => Plugin {\n return (options?: TOptions): Plugin => {\n const pluginFn: Plugin = (config) =>\n descriptor.plugin({\n config,\n options: options as TOptions,\n plugins: buildPluginsMap(config.plugins),\n })\n\n if (options !== undefined) {\n pluginFn.options = options as Record<string, unknown>\n }\n pluginFn.slug = descriptor.slug\n if (descriptor.order !== undefined) {\n pluginFn.order = descriptor.order\n }\n\n return pluginFn\n }\n}\n"],"names":["buildPluginsMap","plugins","map","p","slug","definePlugin","descriptor","options","pluginFn","config","plugin","undefined","order"],"mappings":"AAEA,SAASA,gBAAgBC,OAA6B;IACpD,MAAMC,MAA0C,CAAC;IACjD,IAAID,SAAS;QACX,KAAK,MAAME,KAAKF,QAAS;YACvB,IAAIE,EAAEC,IAAI,EAAE;gBACVF,GAAG,CAACC,EAAEC,IAAI,CAAC,GAAGD;YAChB;QACF;IACF;IACA,OAAOD;AACT;AAsCA,OAAO,SAASG,aAAuBC,UAQtC;IACC,OAAO,CAACC;QACN,MAAMC,WAAmB,CAACC,SACxBH,WAAWI,MAAM,CAAC;gBAChBD;gBACAF,SAASA;gBACTN,SAASD,gBAAgBS,OAAOR,OAAO;YACzC;QAEF,IAAIM,YAAYI,WAAW;YACzBH,SAASD,OAAO,GAAGA;QACrB;QACAC,SAASJ,IAAI,GAAGE,WAAWF,IAAI;QAC/B,IAAIE,WAAWM,KAAK,KAAKD,WAAW;YAClCH,SAASI,KAAK,GAAGN,WAAWM,KAAK;QACnC;QAEA,OAAOJ;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map\n}\n\n/**\n * Helper for authoring plugins with order, slug, and typed options.\n * Eliminates boilerplate and ensures metadata is always set consistently.\n *\n * The `plugin` function receives `config`, `plugins` (a slug-keyed map of other\n * plugins), and the user-provided `options`.\n *\n * @experimental\n *\n * @example\n * // With options:\n * export const seoPlugin = definePlugin<SEOPluginConfig>({\n * slug: 'plugin-seo',\n * plugin: ({ config, options }) => ({ ...config }),\n * })\n *\n * // Without options:\n * export const myPlugin = definePlugin({\n * slug: 'my-plugin',\n * plugin: ({ config }) => ({ ...config }),\n * })\n */\nexport function definePlugin(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap }) => Config | Promise<Config>\n slug: string\n}): () => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): undefined extends TOptions ? (options?: TOptions) => Plugin : (options: TOptions) => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): (options: TOptions) => Plugin {\n return (options?: TOptions): Plugin => {\n // Read `pluginFn.options` when the plugin runs, so other plugins can edit or replace it, even\n // when the plugin was registered without options\n const pluginFn: Plugin = (config) =>\n descriptor.plugin({\n config,\n options: pluginFn.options as TOptions,\n plugins: buildPluginsMap(config.plugins),\n })\n\n if (options !== undefined) {\n pluginFn.options = options as Record<string, unknown>\n }\n pluginFn.slug = descriptor.slug\n if (descriptor.order !== undefined) {\n pluginFn.order = descriptor.order\n }\n\n return pluginFn\n }\n}\n"],"names":["buildPluginsMap","plugins","map","p","slug","definePlugin","descriptor","options","pluginFn","config","plugin","undefined","order"],"mappings":"AAEA,SAASA,gBAAgBC,OAA6B;IACpD,MAAMC,MAA0C,CAAC;IACjD,IAAID,SAAS;QACX,KAAK,MAAME,KAAKF,QAAS;YACvB,IAAIE,EAAEC,IAAI,EAAE;gBACVF,GAAG,CAACC,EAAEC,IAAI,CAAC,GAAGD;YAChB;QACF;IACF;IACA,OAAOD;AACT;AAsCA,OAAO,SAASG,aAAuBC,UAQtC;IACC,OAAO,CAACC;QACN,8FAA8F;QAC9F,iDAAiD;QACjD,MAAMC,WAAmB,CAACC,SACxBH,WAAWI,MAAM,CAAC;gBAChBD;gBACAF,SAASC,SAASD,OAAO;gBACzBN,SAASD,gBAAgBS,OAAOR,OAAO;YACzC;QAEF,IAAIM,YAAYI,WAAW;YACzBH,SAASD,OAAO,GAAGA;QACrB;QACAC,SAASJ,IAAI,GAAGE,WAAWF,IAAI;QAC/B,IAAIE,WAAWM,KAAK,KAAKD,WAAW;YAClCH,SAASI,KAAK,GAAGN,WAAWM,KAAK;QACnC;QAEA,OAAOJ;IACT;AACF"}
@@ -10,7 +10,7 @@ export type { SchemaBuildContext } from '../database/createSchemaBuildContext.js
10
10
  export { getLLMInstructions } from '../llm-instructions/getInstructions.js';
11
11
  export { assertClientUploadAccess } from '../uploads/assertClientUploadAccess.js';
12
12
  export { assertClientUploadAllowed } from '../uploads/assertClientUploadAllowed.js';
13
- export { createClientUploadReceipt, verifyClientUploadReceipt, } from '../uploads/clientUploadReceipt.js';
13
+ export { createClientUploadReceipt, resignClientUploadReceipt, verifyClientUploadReceipt, } from '../uploads/clientUploadReceipt.js';
14
14
  export { downloadFileToBuffer } from '../uploads/downloadFileToBuffer.js';
15
15
  export { getUploadInstructions } from '../uploads/endpoints/uploadInstructions.js';
16
16
  export { getOriginalFilename } from '../uploads/fileVersioning/naming.js';
@@ -1 +1 @@
1
- {"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../../src/exports/internal.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,KAAK,iBAAiB,EACtB,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACzB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAA;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAA;AAClF,YAAY,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAA;AACjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAA;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAA;AACjF,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAA;AACnF,OAAO,EACL,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,mCAAmC,CAAA;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAA;AACzE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAA;AAClF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAA;AACzE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6CAA6C,CAAA;AAC3F,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAA;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAA;AACvE,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AACjE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAA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AAE,MAAM,qCAAqC,CAAA;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAA"}
@@ -8,7 +8,7 @@ export { createSchemaBuildContext } from '../database/createSchemaBuildContext.j
8
8
  export { getLLMInstructions } from '../llm-instructions/getInstructions.js';
9
9
  export { assertClientUploadAccess } from '../uploads/assertClientUploadAccess.js';
10
10
  export { assertClientUploadAllowed } from '../uploads/assertClientUploadAllowed.js';
11
- export { createClientUploadReceipt, verifyClientUploadReceipt } from '../uploads/clientUploadReceipt.js';
11
+ export { createClientUploadReceipt, resignClientUploadReceipt, verifyClientUploadReceipt } from '../uploads/clientUploadReceipt.js';
12
12
  export { downloadFileToBuffer } from '../uploads/downloadFileToBuffer.js';
13
13
  export { getUploadInstructions } from '../uploads/endpoints/uploadInstructions.js';
14
14
  export { getOriginalFilename } from '../uploads/fileVersioning/naming.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/internal.ts"],"sourcesContent":["/**\n * Modules exported here are not part of the public API and are subject to change without notice and without a major version bump.\n */\n\nexport {\n type AdminContextCache,\n initAdminContext,\n type InitAdminContextArgs,\n type PartialAdminContext,\n} from '../admin/initAdminContext.js'\nexport { applyUserReadAccess } from '../auth/applyUserReadAccess.js'\nexport { createCLI } from '../cli/index.js'\nexport { getCommandInput } from '../cli/runtime/getCommandInput.js'\nexport { createSchemaBuildContext } from '../database/createSchemaBuildContext.js'\nexport type { SchemaBuildContext } from '../database/createSchemaBuildContext.js'\nexport { getLLMInstructions } from '../llm-instructions/getInstructions.js'\nexport { assertClientUploadAccess } from '../uploads/assertClientUploadAccess.js'\nexport { assertClientUploadAllowed } from '../uploads/assertClientUploadAllowed.js'\nexport {\n createClientUploadReceipt,\n verifyClientUploadReceipt,\n} from '../uploads/clientUploadReceipt.js'\nexport { downloadFileToBuffer } from '../uploads/downloadFileToBuffer.js'\nexport { getUploadInstructions } from '../uploads/endpoints/uploadInstructions.js'\nexport { getOriginalFilename } from '../uploads/fileVersioning/naming.js'\nexport { getFileFromUploadInstructions } from '../uploads/getFileFromUploadInstructions.js'\nexport { isXmlMimeType } from '../uploads/getFileTypeIdentity.js'\nexport { getRangeRequestInfo } from '../uploads/getRangeRequestInfo.js'\nexport { getSafeFileName, incrementName } from '../uploads/getSafeFilename.js'\nexport { parseRangeHeader } from '../uploads/parseRangeHeader.js'\nexport { externalURLInputSchema, resolveURLUploadInput } from '../uploads/resolveURLUploadInput.js'\nexport type { ExternalURLInput } from '../uploads/resolveURLUploadInput.js'\nexport {\n getUploadFilePath,\n getUploadTransformerInternal,\n setUploadFilePath,\n uploadTransformerInternal,\n} from '../uploads/transformers/uploadTransformerBridge.js'\nexport type {\n PreparedUploadTransformation,\n TransformerWithInternalBridge,\n UploadTransformerInternal,\n UploadTransformTask,\n} from '../uploads/transformers/uploadTransformerBridge.js'\nexport { uploadContentSecurityPolicy } from '../uploads/uploadContentSecurityPolicy.js'\nexport {\n batchProcessing,\n type BatchProcessingOptions,\n type BatchProcessorResult,\n} from '../utilities/batchProcessing.js'\nexport { getEntityPermissions } from '../utilities/getEntityPermissions/getEntityPermissions.js'\nexport { httpStatus } from '../utilities/httpStatus.js'\nexport { isURLAllowed } from '../utilities/isURLAllowed.js'\nexport { sanitizePermissions } from '../utilities/sanitizePermissions.js'\nexport { sendTelemetryEvent } from '../utilities/telemetry/index.js'\n"],"names":["initAdminContext","applyUserReadAccess","createCLI","getCommandInput","createSchemaBuildContext","getLLMInstructions","assertClientUploadAccess","assertClientUploadAllowed","createClientUploadReceipt","verifyClientUploadReceipt","downloadFileToBuffer","getUploadInstructions","getOriginalFilename","getFileFromUploadInstructions","isXmlMimeType","getRangeRequestInfo","getSafeFileName","incrementName","parseRangeHeader","externalURLInputSchema","resolveURLUploadInput","getUploadFilePath","getUploadTransformerInternal","setUploadFilePath","uploadTransformerInternal","uploadContentSecurityPolicy","batchProcessing","getEntityPermissions","httpStatus","isURLAllowed","sanitizePermissions","sendTelemetryEvent"],"mappings":"AAAA;;CAEC,GAED,SAEEA,gBAAgB,QAGX,+BAA8B;AACrC,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,eAAe,QAAQ,oCAAmC;AACnE,SAASC,wBAAwB,QAAQ,0CAAyC;AAElF,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,wBAAwB,QAAQ,yCAAwC;AACjF,SAASC,yBAAyB,QAAQ,0CAAyC;AACnF,SACEC,yBAAyB,EACzBC,yBAAyB,QACpB,oCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,qCAAoC;AACzE,SAASC,qBAAqB,QAAQ,6CAA4C;AAClF,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,6BAA6B,QAAQ,8CAA6C;AAC3F,SAASC,aAAa,QAAQ,oCAAmC;AACjE,SAASC,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,eAAe,EAAEC,aAAa,QAAQ,gCAA+B;AAC9E,SAASC,gBAAgB,QAAQ,iCAAgC;AACjE,SAASC,sBAAsB,EAAEC,qBAAqB,QAAQ,sCAAqC;AAEnG,SACEC,iBAAiB,EACjBC,4BAA4B,EAC5BC,iBAAiB,EACjBC,yBAAyB,QACpB,qDAAoD;AAO3D,SAASC,2BAA2B,QAAQ,4CAA2C;AACvF,SACEC,eAAe,QAGV,kCAAiC;AACxC,SAASC,oBAAoB,QAAQ,4DAA2D;AAChG,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,kBAAkB,QAAQ,kCAAiC"}
1
+ {"version":3,"sources":["../../src/exports/internal.ts"],"sourcesContent":["/**\n * Modules exported here are not part of the public API and are subject to change without notice and without a major version bump.\n */\n\nexport {\n type AdminContextCache,\n initAdminContext,\n type InitAdminContextArgs,\n type PartialAdminContext,\n} from '../admin/initAdminContext.js'\nexport { applyUserReadAccess } from '../auth/applyUserReadAccess.js'\nexport { createCLI } from '../cli/index.js'\nexport { getCommandInput } from '../cli/runtime/getCommandInput.js'\nexport { createSchemaBuildContext } from '../database/createSchemaBuildContext.js'\nexport type { SchemaBuildContext } from '../database/createSchemaBuildContext.js'\nexport { getLLMInstructions } from '../llm-instructions/getInstructions.js'\nexport { assertClientUploadAccess } from '../uploads/assertClientUploadAccess.js'\nexport { assertClientUploadAllowed } from '../uploads/assertClientUploadAllowed.js'\nexport {\n createClientUploadReceipt,\n resignClientUploadReceipt,\n verifyClientUploadReceipt,\n} from '../uploads/clientUploadReceipt.js'\nexport { downloadFileToBuffer } from '../uploads/downloadFileToBuffer.js'\nexport { getUploadInstructions } from '../uploads/endpoints/uploadInstructions.js'\nexport { getOriginalFilename } from '../uploads/fileVersioning/naming.js'\nexport { getFileFromUploadInstructions } from '../uploads/getFileFromUploadInstructions.js'\nexport { isXmlMimeType } from '../uploads/getFileTypeIdentity.js'\nexport { getRangeRequestInfo } from '../uploads/getRangeRequestInfo.js'\nexport { getSafeFileName, incrementName } from '../uploads/getSafeFilename.js'\nexport { parseRangeHeader } from '../uploads/parseRangeHeader.js'\nexport { externalURLInputSchema, resolveURLUploadInput } from '../uploads/resolveURLUploadInput.js'\nexport type { ExternalURLInput } from '../uploads/resolveURLUploadInput.js'\nexport {\n getUploadFilePath,\n getUploadTransformerInternal,\n setUploadFilePath,\n uploadTransformerInternal,\n} from '../uploads/transformers/uploadTransformerBridge.js'\nexport type {\n PreparedUploadTransformation,\n TransformerWithInternalBridge,\n UploadTransformerInternal,\n UploadTransformTask,\n} from '../uploads/transformers/uploadTransformerBridge.js'\nexport { uploadContentSecurityPolicy } from '../uploads/uploadContentSecurityPolicy.js'\nexport {\n batchProcessing,\n type BatchProcessingOptions,\n type BatchProcessorResult,\n} from '../utilities/batchProcessing.js'\nexport { getEntityPermissions } from '../utilities/getEntityPermissions/getEntityPermissions.js'\nexport { httpStatus } from '../utilities/httpStatus.js'\nexport { isURLAllowed } from '../utilities/isURLAllowed.js'\nexport { sanitizePermissions } from '../utilities/sanitizePermissions.js'\nexport { sendTelemetryEvent } from '../utilities/telemetry/index.js'\n"],"names":["initAdminContext","applyUserReadAccess","createCLI","getCommandInput","createSchemaBuildContext","getLLMInstructions","assertClientUploadAccess","assertClientUploadAllowed","createClientUploadReceipt","resignClientUploadReceipt","verifyClientUploadReceipt","downloadFileToBuffer","getUploadInstructions","getOriginalFilename","getFileFromUploadInstructions","isXmlMimeType","getRangeRequestInfo","getSafeFileName","incrementName","parseRangeHeader","externalURLInputSchema","resolveURLUploadInput","getUploadFilePath","getUploadTransformerInternal","setUploadFilePath","uploadTransformerInternal","uploadContentSecurityPolicy","batchProcessing","getEntityPermissions","httpStatus","isURLAllowed","sanitizePermissions","sendTelemetryEvent"],"mappings":"AAAA;;CAEC,GAED,SAEEA,gBAAgB,QAGX,+BAA8B;AACrC,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,eAAe,QAAQ,oCAAmC;AACnE,SAASC,wBAAwB,QAAQ,0CAAyC;AAElF,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,wBAAwB,QAAQ,yCAAwC;AACjF,SAASC,yBAAyB,QAAQ,0CAAyC;AACnF,SACEC,yBAAyB,EACzBC,yBAAyB,EACzBC,yBAAyB,QACpB,oCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,qCAAoC;AACzE,SAASC,qBAAqB,QAAQ,6CAA4C;AAClF,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,6BAA6B,QAAQ,8CAA6C;AAC3F,SAASC,aAAa,QAAQ,oCAAmC;AACjE,SAASC,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,eAAe,EAAEC,aAAa,QAAQ,gCAA+B;AAC9E,SAASC,gBAAgB,QAAQ,iCAAgC;AACjE,SAASC,sBAAsB,EAAEC,qBAAqB,QAAQ,sCAAqC;AAEnG,SACEC,iBAAiB,EACjBC,4BAA4B,EAC5BC,iBAAiB,EACjBC,yBAAyB,QACpB,qDAAoD;AAO3D,SAASC,2BAA2B,QAAQ,4CAA2C;AACvF,SACEC,eAAe,QAGV,kCAAiC;AACxC,SAASC,oBAAoB,QAAQ,4DAA2D;AAChG,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,kBAAkB,QAAQ,kCAAiC"}
@@ -21,7 +21,7 @@ export { default as deepMerge } from 'deepmerge';
21
21
  import { PinoPretty } from 'pino-pretty';
22
22
  import { DatePickerProps } from 'react-datepicker';
23
23
 
24
- declare const clientTranslationKeys: ("error:autosaving" | "error:correctInvalidFields" | "error:deletingTitle" | "error:documentNotFound" | "error:emailOrPasswordIncorrect" | "error:failedToResetLayout" | "error:failedToSaveLayout" | "error:fileFetchFailed" | "error:insufficientClipboardPermissions" | "error:invalidClipboardData" | "error:invalidFileType" | "error:invalidRequestArgs" | "error:loadingDocument" | "error:logoutFailed" | "error:noFileFoundInClipboard" | "error:noMatchedField" | "error:notAllowedToAccessPage" | "error:notAllowedToPerformAction" | "error:previewing" | "error:problemUploadingFile" | "error:restoringTitle" | "error:revertingDocument" | "error:tokenNotProvided" | "error:unableToCopy" | "error:unableToDeleteCount" | "error:unableToReadClipboard" | "error:unableToReindexCollection" | "error:unableToUpdateCount" | "error:unauthorized" | "error:unauthorizedAdmin" | "error:unknown" | "error:unPublishingDocument" | "error:unspecific" | "error:unverifiedEmail" | "error:urlNotAllowed" | "error:userEmailAlreadyRegistered" | "error:usernameAlreadyRegistered" | "error:usernameOrPasswordIncorrect" | "error:followingFieldsInvalid" | "fields:blocks" | "fields:addLabel" | "fields:addLink" | "fields:addNew" | "fields:addNewLabel" | "fields:addRelationship" | "fields:addUpload" | "fields:block" | "fields:blockName" | "fields:blockType" | "fields:chooseBetweenCustomTextOrDocument" | "fields:chooseDocumentToLink" | "fields:chooseFromExisting" | "fields:collapseAll" | "fields:customURL" | "fields:editLink" | "fields:editRelationship" | "fields:enterURL" | "fields:hidePassword" | "fields:internalLink" | "fields:itemsAndMore" | "fields:labelRelationship" | "fields:latitude" | "fields:linkedTo" | "fields:linkType" | "fields:longitude" | "fields:openInNewTab" | "fields:passwordsDoNotMatch" | "fields:removeRelationship" | "fields:removeUpload" | "fields:saveChanges" | "fields:searchForBlock" | "fields:searchForLanguage" | "fields:selectFieldsToEdit" | "fields:showAll" | "fields:showPassword" | "fields:swapRelationship" | "fields:swapUpload" | "fields:textToDisplay" | "fields:toggleBlock" | "fields:uploadNewLabel" | "localization:cannotCopySameLocale" | "localization:copyFrom" | "localization:copyFromTo" | "localization:copyTo" | "localization:copyToLocale" | "localization:localeToPublish" | "localization:selectedLocales" | "localization:selectLocaleToCopy" | "localization:selectLocaleToDuplicate" | "upload:addFile" | "upload:addFiles" | "upload:bulkUpload" | "upload:copyLinkToFile" | "upload:copyURL" | "upload:crop" | "upload:cropBottom" | "upload:cropBottomLeft" | "upload:cropBottomRight" | "upload:cropLeft" | "upload:cropRight" | "upload:cropToolDescription" | "upload:cropTop" | "upload:cropTopLeft" | "upload:cropTopRight" | "upload:download" | "upload:dragAndDrop" | "upload:editImage" | "upload:fileName" | "upload:fileSize" | "upload:filesToUpload" | "upload:fileToUpload" | "upload:focalPoint" | "upload:focalPointDescription" | "upload:fromURL" | "upload:height" | "upload:linkToFile" | "upload:noFile" | "upload:pasteFromClipboard" | "upload:pasteURL" | "upload:previewSizes" | "upload:renameFile" | "upload:replaceFile" | "upload:selectCollectionToBrowse" | "upload:selectFile" | "upload:setCropArea" | "upload:setFocalPoint" | "upload:sizes" | "upload:sizesFor" | "upload:width" | "llmInstructions:additionalInstructions" | "llmInstructions:collectionDescription" | "llmInstructions:collectionSystemDescription" | "llmInstructions:editInstructions" | "llmInstructions:global" | "llmInstructions:globalDescription" | "llmInstructions:globalSystemDescription" | "llmInstructions:instructions" | "llmInstructions:systemInstructions" | "llmInstructions:title" | "authentication:forgotPassword" | "authentication:verify" | "authentication:account" | "authentication:accountOfCurrentUser" | "authentication:accountVerified" | "authentication:alreadyActivated" | "authentication:alreadyLoggedIn" | "authentication:apiKey" | "authentication:authenticated" | "authentication:backToLogin" | "authentication:beginCreateFirstUser" | "authentication:changePassword" | "authentication:checkYourEmailForPasswordReset" | "authentication:confirmGeneration" | "authentication:confirmPassword" | "authentication:createFirstUser" | "authentication:createUser" | "authentication:emailNotValid" | "authentication:emailOrUsername" | "authentication:emailSent" | "authentication:emailVerified" | "authentication:emailVerifiedRedirecting" | "authentication:enableAPIKey" | "authentication:failedToUnlock" | "authentication:forceUnlock" | "authentication:forgotPasswordEmailInstructions" | "authentication:forgotPasswordUsernameInstructions" | "authentication:usernameNotValid" | "authentication:forgotPasswordQuestion" | "authentication:generate" | "authentication:generateNewAPIKey" | "authentication:generatingNewAPIKeyWillInvalidate" | "authentication:logBackIn" | "authentication:loggedIn" | "authentication:loggedInChangePassword" | "authentication:loggedOutInactivity" | "authentication:loggedOutSuccessfully" | "authentication:loggingOut" | "authentication:login" | "authentication:logOut" | "authentication:logout" | "authentication:logoutSuccessful" | "authentication:logoutUser" | "authentication:newAPIKeyGenerated" | "authentication:newPassword" | "authentication:notRedirected" | "authentication:passed" | "authentication:passwordResetSuccessfully" | "authentication:resend" | "authentication:resetPassword" | "authentication:stayLoggedIn" | "authentication:successfullyRegisteredFirstUser" | "authentication:successfullyUnlocked" | "authentication:tokenRefreshSuccessful" | "authentication:unableToVerify" | "authentication:username" | "authentication:verified" | "authentication:verifiedSuccessfully" | "authentication:verifyUser" | "authentication:youAreInactive" | "commandPalette:title" | "commandPalette:createNew" | "commandPalette:hintClose" | "commandPalette:hintCreate" | "commandPalette:hintNavigate" | "commandPalette:hintSelect" | "commandPalette:noResults" | "commandPalette:placeholder" | "dashboard:addButton" | "dashboard:addWidget" | "dashboard:deleteWidget" | "dashboard:discardConfirmLabel" | "dashboard:discardMessage" | "dashboard:discardTitle" | "dashboard:editDashboard" | "dashboard:editingDashboard" | "dashboard:noItems" | "dashboard:resetLayout" | "dashboard:resizeWidget" | "dashboard:searchWidgets" | "dashboard:widgetAddPin" | "dashboard:widgetCollectionRequired" | "dashboard:widgetConfigurationError" | "dashboard:widgetDropFilesToUpload" | "dashboard:widgetInvalidCollection" | "dashboard:widgetInvalidFilterField" | "dashboard:widgetInvalidSortField" | "dashboard:widgetLimitLabel" | "dashboard:widgetNonSortableSortField" | "dashboard:widgetPageCount" | "dashboard:widgetPagination" | "dashboard:widgetPinned" | "dashboard:widgetPinnedEmpty" | "dashboard:widgetPinnedEmptyDescription" | "dashboard:widgetPinnedSaveError" | "dashboard:widgetQueryError" | "dashboard:widgetRecentlyViewedEmpty" | "dashboard:widgetRecentlyViewedEmptyDescription" | "dashboard:widgetRecentlyViewedFilterDescription" | "dashboard:widgetRecentlyViewedTitle" | "dashboard:widgetRecentsAndPinned" | "dashboard:widgetRemovePin" | "dashboard:widgetSelectCollectionFirst" | "dashboard:widgetSelectSortField" | "dashboard:widgetSortDirectionLabel" | "dashboard:widgetSortFieldLabel" | "dashboard:widgetTitleFallback" | "dashboard:widgetTitleLabel" | "dashboard:widgetUploadDropzoneDescription" | "dashboard:widgetUploadFiles" | "general:collections" | "general:globals" | "general:false" | "general:none" | "general:locale" | "general:select" | "general:user" | "general:createdAt" | "general:error" | "general:updatedAt" | "general:access" | "general:custom" | "general:name" | "general:depth" | "general:collection" | "general:email" | "general:items" | "general:of" | "general:dashboard" | "general:notFound" | "general:unauthorized" | "general:newLabel" | "general:saveChanges" | "general:username" | "general:createNew" | "general:noResults" | "general:aboutToDelete" | "general:aboutToPermanentlyDelete" | "general:aboutToPermanentlyDeleteTrash" | "general:aboutToRestore" | "general:aboutToRestoreAsDraft" | "general:aboutToRestoreAsDraftCount" | "general:aboutToRestoreCount" | "general:aboutToTrash" | "general:aboutToTrashCount" | "general:accepts" | "general:addBelow" | "general:addFilter" | "general:adminTheme" | "general:all" | "general:allCollections" | "general:allLocales" | "general:allowedTypes" | "general:and" | "general:anotherUser" | "general:anotherUserTakenOver" | "general:apiResponse" | "general:applyChanges" | "general:ascending" | "general:auto" | "general:automatic" | "general:backToDashboard" | "general:breadcrumb" | "general:by" | "general:cancel" | "general:changesNotSaved" | "general:checked" | "general:clear" | "general:clearAll" | "general:clearSearch" | "general:close" | "general:collapse" | "general:columns" | "general:columnToSort" | "general:confirm" | "general:confirmCopy" | "general:confirmDeletion" | "general:confirmDuplication" | "general:confirmMove" | "general:confirmReindex" | "general:confirmReindexAll" | "general:confirmReindexDescription" | "general:confirmReindexDescriptionAll" | "general:confirmRestoration" | "general:copied" | "general:copy" | "general:copyField" | "general:copying" | "general:copyRow" | "general:copyWarning" | "general:create" | "general:created" | "general:createdBy" | "general:createNewLabel" | "general:creating" | "general:creatingNewLabel" | "general:currentlyEditing" | "general:dark" | "general:decrement" | "general:delete" | "general:deleted" | "general:deletedAgo" | "general:deletedAt" | "general:deletedCountSuccessfully" | "general:deletedSuccessfully" | "general:deleteLabel" | "general:deletePermanently" | "general:deleting" | "general:descending" | "general:deselectAllRows" | "general:document" | "general:documentIsTrashed" | "general:documentLocked" | "general:documentModified" | "general:documentOutOfDate" | "general:documents" | "general:dragCancelled" | "general:dragDropped" | "general:dragInstructions" | "general:dragMoved" | "general:dragPickedUp" | "general:dragToMove" | "general:dragToReorder" | "general:duplicate" | "general:duplicateWithoutSaving" | "general:edit" | "general:editAll" | "general:editColumns" | "general:editedSince" | "general:editing" | "general:editingTakenOver" | "general:editLabel" | "general:emailAddress" | "general:emptyTrash" | "general:emptyTrashLabel" | "general:enhancedContrastMode" | "general:enterANumber" | "general:enterAValue" | "general:errors" | "general:exitLivePreview" | "general:expand" | "general:export" | "general:fallbackToDefaultLocale" | "general:field" | "general:filter" | "general:filters" | "general:filterWhere" | "general:goBack" | "general:goToPage" | "general:gridLayout" | "general:groupByLabel" | "general:hideSidebar" | "general:import" | "general:increment" | "general:isEditing" | "general:item" | "general:language" | "general:lastModified" | "general:layout" | "general:leaveAnyway" | "general:leaveWithoutSaving" | "general:light" | "general:livePreview" | "general:loading" | "general:loadMore" | "general:locales" | "general:lock" | "general:manageLabel" | "general:menu" | "general:moreOptions" | "general:move" | "general:moveConfirm" | "general:moveCount" | "general:moveDown" | "general:moveUp" | "general:moving" | "general:movingCount" | "general:next" | "general:nextPage" | "general:no" | "general:noDateSelected" | "general:noFiltersSet" | "general:noLabel" | "general:noMatchesFound" | "general:noOptions" | "general:noResultsDescription" | "general:noResultsFound" | "general:nothingFound" | "general:noTrashResults" | "general:notSelectedDocument" | "general:notShownInTable" | "general:noUpcomingEventsScheduled" | "general:noValue" | "general:only" | "general:open" | "general:openInNewWindow" | "general:or" | "general:order" | "general:original" | "general:overwriteExistingData" | "general:pageNotFound" | "general:pageNumberRange" | "general:password" | "general:pasteBelow" | "general:pasteField" | "general:pasteRow" | "general:payloadSettings" | "general:permanentlyDelete" | "general:permanentlyDeletedCountSuccessfully" | "general:perPage" | "general:perPageLabel" | "general:presets" | "general:previous" | "general:previousPage" | "general:reindex" | "general:reindexingAll" | "general:reloadDocument" | "general:remove" | "general:removeFilter" | "general:rename" | "general:replaceRow" | "general:requiredFields" | "general:reset" | "general:resetPreferences" | "general:resetPreferencesDescription" | "general:resettingPreferences" | "general:restore" | "general:restoreAsPublished" | "general:restoredCountSuccessfully" | "general:restoring" | "general:retry" | "general:row" | "general:rows" | "general:save" | "general:saving" | "general:schedulePublishFor" | "general:searchAutomatically" | "general:searchBy" | "general:searchCleared" | "general:searchColumns" | "general:searchGroups" | "general:searchResults" | "general:selectAll" | "general:selectAllRows" | "general:selectedCount" | "general:selectedDocument" | "general:selectLabel" | "general:selectValue" | "general:settings" | "general:showAllLabel" | "general:shownInTable" | "general:showSidebar" | "general:skipToContent" | "general:sorryNotFound" | "general:sort" | "general:sortByLabelDirection" | "general:sortByOrderToReorder" | "general:stayOnThisPage" | "general:submissionSuccessful" | "general:submit" | "general:submitting" | "general:success" | "general:successfullyCreated" | "general:successfullyDuplicated" | "general:successfullyReindexed" | "general:tableLayout" | "general:takeOver" | "general:theme" | "general:thisLanguage" | "general:time" | "general:timezone" | "general:titleDeleted" | "general:titleRestored" | "general:titleTrashed" | "general:toggle" | "general:trash" | "general:trashedCountSuccessfully" | "general:true" | "general:unchecked" | "general:unlock" | "general:unsavedChanges" | "general:unsavedChangesDuplicate" | "general:untitled" | "general:upcomingEvents" | "general:updatedAgo" | "general:updatedBy" | "general:updatedCountSuccessfully" | "general:updatedLabelSuccessfully" | "general:updatedSuccessfully" | "general:updateForEveryone" | "general:updating" | "general:uploading" | "general:uploadingBulk" | "general:users" | "general:value" | "general:viewing" | "general:viewReadOnly" | "general:welcome" | "general:where" | "general:yes" | "general:aboutToDeleteCount" | "general:editingLabel" | "hierarchy:noResults" | "hierarchy:searchResults" | "hierarchy:folderLocation" | "hierarchy:goTo" | "hierarchy:itemsMovedTo" | "hierarchy:itemsMovedToRoot" | "hierarchy:moveTo" | "hierarchy:moveToRoot" | "hierarchy:noParent" | "hierarchy:removeFrom" | "hierarchy:searchLabel" | "operators:contains" | "operators:equals" | "operators:exists" | "operators:intersects" | "operators:near" | "operators:within" | "operators:isGreaterThan" | "operators:isGreaterThanOrEqualTo" | "operators:isIn" | "operators:isLessThan" | "operators:isLessThanOrEqualTo" | "operators:isLike" | "operators:isNotEqualTo" | "operators:isNotIn" | "operators:isNotLike" | "validation:required" | "validation:username" | "validation:emailAddress" | "validation:enterNumber" | "validation:fieldHasNo" | "validation:greaterThanMax" | "validation:invalidBlock" | "validation:invalidBlocks" | "validation:invalidInput" | "validation:invalidSelection" | "validation:invalidSelections" | "validation:latitudeOutOfBounds" | "validation:lessThanMin" | "validation:limitReached" | "validation:longerThanMin" | "validation:longitudeOutOfBounds" | "validation:notValidDate" | "validation:requiresAtLeast" | "validation:requiresNoMoreThan" | "validation:requiresTwoNumbers" | "validation:shorterThanMax" | "validation:timezoneRequired" | "validation:trueOrFalse" | "validation:validUploadID" | "version:type" | "version:version" | "version:aboutToRestore" | "version:restoring" | "version:aboutToPublishSelection" | "version:aboutToRestoreGlobal" | "version:aboutToRevertToPublished" | "version:aboutToUnpublish" | "version:aboutToUnpublishIn" | "version:aboutToUnpublishSelection" | "version:autosave" | "version:autosavedSuccessfully" | "version:autosavedVersion" | "version:changed" | "version:compareVersions" | "version:comparingAgainst" | "version:confirmPublish" | "version:confirmRevertToSaved" | "version:confirmUnpublish" | "version:confirmVersionRestoration" | "version:currentDraft" | "version:currentlyPublished" | "version:currentlyViewing" | "version:currentPublishedVersion" | "version:draft" | "version:draftHasPublishedVersion" | "version:draftSavedSuccessfully" | "version:lastSavedAgo" | "version:modifiedOnly" | "version:moreVersions" | "version:noFurtherVersionsFound" | "version:noLabelGroup" | "version:noRowsFound" | "version:noRowsSelected" | "version:preview" | "version:previouslyDraft" | "version:previouslyPublished" | "version:previousVersion" | "version:problemRestoringVersion" | "version:publish" | "version:publishAllLocales" | "version:publishChanges" | "version:published" | "version:publishIn" | "version:publishing" | "version:restoreAsDraft" | "version:restoredSuccessfully" | "version:restoreThisVersion" | "version:reverting" | "version:revertToPublished" | "version:revertUnsuccessful" | "version:saveDraft" | "version:scheduledSuccessfully" | "version:schedulePublish" | "version:selectLocales" | "version:selectVersionToCompare" | "version:showLocales" | "version:specificVersion" | "version:status" | "version:unpublish" | "version:unpublished" | "version:unpublishedSuccessfully" | "version:unpublishIn" | "version:unpublishing" | "version:versionAgo" | "version:versionID" | "version:versions" | "version:viewingVersion" | "version:viewingVersionGlobal" | "version:viewingVersions" | "version:viewingVersionsGlobal" | "version:changedFieldsCount")[];
24
+ declare const clientTranslationKeys: ("error:autosaving" | "error:correctInvalidFields" | "error:deletingTitle" | "error:documentNotFound" | "error:emailOrPasswordIncorrect" | "error:failedToResetLayout" | "error:failedToSaveLayout" | "error:fileFetchFailed" | "error:insufficientClipboardPermissions" | "error:invalidClipboardData" | "error:invalidFileType" | "error:invalidRequestArgs" | "error:loadingDocument" | "error:logoutFailed" | "error:noFileFoundInClipboard" | "error:noMatchedField" | "error:notAllowedToAccessPage" | "error:notAllowedToPerformAction" | "error:previewing" | "error:problemUploadingFile" | "error:restoringTitle" | "error:revertingDocument" | "error:tokenNotProvided" | "error:unableToCopy" | "error:unableToDeleteCount" | "error:unableToReadClipboard" | "error:unableToReindexCollection" | "error:unableToUpdateCount" | "error:unauthorized" | "error:unauthorizedAdmin" | "error:unknown" | "error:unPublishingDocument" | "error:unspecific" | "error:unverifiedEmail" | "error:urlNotAllowed" | "error:userEmailAlreadyRegistered" | "error:usernameAlreadyRegistered" | "error:usernameOrPasswordIncorrect" | "error:followingFieldsInvalid" | "fields:blocks" | "fields:addLabel" | "fields:addLink" | "fields:addNew" | "fields:addNewLabel" | "fields:addRelationship" | "fields:addUpload" | "fields:block" | "fields:blockName" | "fields:blockType" | "fields:chooseBetweenCustomTextOrDocument" | "fields:chooseDocumentToLink" | "fields:chooseFromExisting" | "fields:collapseAll" | "fields:customURL" | "fields:editLink" | "fields:editRelationship" | "fields:enterURL" | "fields:hidePassword" | "fields:internalLink" | "fields:itemsAndMore" | "fields:labelRelationship" | "fields:latitude" | "fields:linkedTo" | "fields:linkType" | "fields:longitude" | "fields:openInNewTab" | "fields:passwordsDoNotMatch" | "fields:removeRelationship" | "fields:removeUpload" | "fields:saveChanges" | "fields:searchForBlock" | "fields:searchForLanguage" | "fields:selectFieldsToEdit" | "fields:showAll" | "fields:showPassword" | "fields:swapRelationship" | "fields:swapUpload" | "fields:textToDisplay" | "fields:toggleBlock" | "fields:uploadNewLabel" | "localization:cannotCopySameLocale" | "localization:copyFrom" | "localization:copyFromTo" | "localization:copyTo" | "localization:copyToLocale" | "localization:localeToPublish" | "localization:selectedLocales" | "localization:selectLocaleToCopy" | "localization:selectLocaleToDuplicate" | "upload:addFile" | "upload:addFiles" | "upload:bulkUpload" | "upload:copyLinkToFile" | "upload:copyURL" | "upload:crop" | "upload:cropBottom" | "upload:cropBottomLeft" | "upload:cropBottomRight" | "upload:cropLeft" | "upload:cropRight" | "upload:cropToolDescription" | "upload:cropTop" | "upload:cropTopLeft" | "upload:cropTopRight" | "upload:download" | "upload:dragAndDrop" | "upload:editImage" | "upload:fileName" | "upload:fileSize" | "upload:filesToUpload" | "upload:fileToUpload" | "upload:focalPoint" | "upload:focalPointDescription" | "upload:fromURL" | "upload:height" | "upload:linkToFile" | "upload:noFile" | "upload:pasteFromClipboard" | "upload:pasteURL" | "upload:previewSizes" | "upload:renameFile" | "upload:replaceFile" | "upload:selectCollectionToBrowse" | "upload:selectFile" | "upload:setCropArea" | "upload:setFocalPoint" | "upload:sizes" | "upload:sizesFor" | "upload:width" | "llmInstructions:additionalInstructions" | "llmInstructions:collectionDescription" | "llmInstructions:collectionSystemDescription" | "llmInstructions:editInstructions" | "llmInstructions:global" | "llmInstructions:globalDescription" | "llmInstructions:globalSystemDescription" | "llmInstructions:instructions" | "llmInstructions:systemInstructions" | "llmInstructions:title" | "authentication:forgotPassword" | "authentication:verify" | "authentication:account" | "authentication:accountOfCurrentUser" | "authentication:accountVerified" | "authentication:alreadyActivated" | "authentication:alreadyLoggedIn" | "authentication:apiKey" | "authentication:authenticated" | "authentication:backToLogin" | "authentication:beginCreateFirstUser" | "authentication:changePassword" | "authentication:checkYourEmailForPasswordReset" | "authentication:confirmGeneration" | "authentication:confirmPassword" | "authentication:createFirstUser" | "authentication:createUser" | "authentication:emailNotValid" | "authentication:emailOrUsername" | "authentication:emailSent" | "authentication:emailVerified" | "authentication:emailVerifiedRedirecting" | "authentication:enableAPIKey" | "authentication:failedToUnlock" | "authentication:forceUnlock" | "authentication:forgotPasswordEmailInstructions" | "authentication:forgotPasswordUsernameInstructions" | "authentication:usernameNotValid" | "authentication:forgotPasswordQuestion" | "authentication:generate" | "authentication:generateNewAPIKey" | "authentication:generatingNewAPIKeyWillInvalidate" | "authentication:logBackIn" | "authentication:loggedIn" | "authentication:loggedInChangePassword" | "authentication:loggedOutInactivity" | "authentication:loggedOutSuccessfully" | "authentication:loggingOut" | "authentication:login" | "authentication:logOut" | "authentication:logout" | "authentication:logoutSuccessful" | "authentication:logoutUser" | "authentication:newAPIKeyGenerated" | "authentication:newPassword" | "authentication:notRedirected" | "authentication:passed" | "authentication:passwordResetSuccessfully" | "authentication:resend" | "authentication:resetPassword" | "authentication:stayLoggedIn" | "authentication:successfullyRegisteredFirstUser" | "authentication:successfullyUnlocked" | "authentication:tokenRefreshSuccessful" | "authentication:unableToVerify" | "authentication:username" | "authentication:verified" | "authentication:verifiedSuccessfully" | "authentication:verifyUser" | "authentication:youAreInactive" | "commandPalette:title" | "commandPalette:createNew" | "commandPalette:hintClose" | "commandPalette:hintCreate" | "commandPalette:hintNavigate" | "commandPalette:hintSelect" | "commandPalette:noResults" | "commandPalette:placeholder" | "dashboard:addButton" | "dashboard:addWidget" | "dashboard:deleteWidget" | "dashboard:discardConfirmLabel" | "dashboard:discardMessage" | "dashboard:discardTitle" | "dashboard:editDashboard" | "dashboard:editingDashboard" | "dashboard:noItems" | "dashboard:resetLayout" | "dashboard:resizeWidget" | "dashboard:searchWidgets" | "dashboard:widgetAddPin" | "dashboard:widgetCollectionRequired" | "dashboard:widgetConfigurationError" | "dashboard:widgetDropFilesToUpload" | "dashboard:widgetInvalidCollection" | "dashboard:widgetInvalidFilterField" | "dashboard:widgetInvalidSortField" | "dashboard:widgetLimitLabel" | "dashboard:widgetNonSortableSortField" | "dashboard:widgetPageCount" | "dashboard:widgetPagination" | "dashboard:widgetPinned" | "dashboard:widgetPinnedEmpty" | "dashboard:widgetPinnedEmptyDescription" | "dashboard:widgetPinnedSaveError" | "dashboard:widgetQueryError" | "dashboard:widgetRecentlyViewedEmpty" | "dashboard:widgetRecentlyViewedEmptyDescription" | "dashboard:widgetRecentlyViewedFilterDescription" | "dashboard:widgetRecentlyViewedTitle" | "dashboard:widgetRecentsAndPinned" | "dashboard:widgetRemovePin" | "dashboard:widgetSelectCollectionFirst" | "dashboard:widgetSelectSortField" | "dashboard:widgetSortDirectionLabel" | "dashboard:widgetSortFieldLabel" | "dashboard:widgetTitleFallback" | "dashboard:widgetTitleLabel" | "dashboard:widgetUploadDropzoneDescription" | "dashboard:widgetUploadFiles" | "general:collections" | "general:globals" | "general:false" | "general:none" | "general:locale" | "general:select" | "general:user" | "general:createdAt" | "general:error" | "general:updatedAt" | "general:access" | "general:custom" | "general:name" | "general:depth" | "general:collection" | "general:email" | "general:items" | "general:of" | "general:dashboard" | "general:notFound" | "general:unauthorized" | "general:newLabel" | "general:saveChanges" | "general:username" | "general:createNew" | "general:noResults" | "general:aboutToDelete" | "general:aboutToPermanentlyDelete" | "general:aboutToPermanentlyDeleteTrash" | "general:aboutToRestore" | "general:aboutToRestoreAsDraft" | "general:aboutToRestoreAsDraftCount" | "general:aboutToRestoreCount" | "general:aboutToTrash" | "general:aboutToTrashCount" | "general:accepts" | "general:addBelow" | "general:addFilter" | "general:adminTheme" | "general:all" | "general:allCollections" | "general:allLocales" | "general:allowedTypes" | "general:and" | "general:anotherUser" | "general:anotherUserTakenOver" | "general:apiResponse" | "general:applyChanges" | "general:ascending" | "general:auto" | "general:automatic" | "general:backToDashboard" | "general:breadcrumb" | "general:by" | "general:cancel" | "general:changesNotSaved" | "general:checked" | "general:clear" | "general:clearAll" | "general:clearSearch" | "general:close" | "general:collapse" | "general:columns" | "general:columnToSort" | "general:confirm" | "general:confirmCopy" | "general:confirmDeletion" | "general:confirmDuplication" | "general:confirmMove" | "general:confirmReindex" | "general:confirmReindexAll" | "general:confirmReindexDescription" | "general:confirmReindexDescriptionAll" | "general:confirmRestoration" | "general:copied" | "general:copy" | "general:copyField" | "general:copying" | "general:copyRow" | "general:copyWarning" | "general:create" | "general:created" | "general:createdBy" | "general:createNewLabel" | "general:creating" | "general:creatingNewLabel" | "general:currentlyEditing" | "general:dark" | "general:decrement" | "general:delete" | "general:deleted" | "general:deletedAgo" | "general:deletedAt" | "general:deletedCountSuccessfully" | "general:deletedSuccessfully" | "general:deleteLabel" | "general:deletePermanently" | "general:deleting" | "general:descending" | "general:deselectAllRows" | "general:document" | "general:documentIsTrashed" | "general:documentLocked" | "general:documentModified" | "general:documentOutOfDate" | "general:documents" | "general:dragCancelled" | "general:dragDropped" | "general:dragInstructions" | "general:dragMoved" | "general:dragPickedUp" | "general:dragToMove" | "general:dragToReorder" | "general:duplicate" | "general:duplicateWithoutSaving" | "general:edit" | "general:editAll" | "general:editColumns" | "general:editedSince" | "general:editing" | "general:editingTakenOver" | "general:editLabel" | "general:emailAddress" | "general:emptyTrash" | "general:emptyTrashLabel" | "general:enhancedContrastMode" | "general:enterANumber" | "general:enterAValue" | "general:errors" | "general:exitLivePreview" | "general:expand" | "general:export" | "general:fallbackToDefaultLocale" | "general:field" | "general:filter" | "general:filters" | "general:filterWhere" | "general:goBack" | "general:goToPage" | "general:gridLayout" | "general:groupByLabel" | "general:hideSidebar" | "general:import" | "general:increment" | "general:isEditing" | "general:item" | "general:language" | "general:lastModified" | "general:layout" | "general:leaveAnyway" | "general:leaveWithoutSaving" | "general:light" | "general:livePreview" | "general:loading" | "general:loadMore" | "general:locales" | "general:lock" | "general:manageLabel" | "general:menu" | "general:moreOptions" | "general:move" | "general:moveConfirm" | "general:moveCount" | "general:moveDown" | "general:moveUp" | "general:moving" | "general:movingCount" | "general:next" | "general:nextPage" | "general:no" | "general:noDateSelected" | "general:noFiltersSet" | "general:noLabel" | "general:noMatchesFound" | "general:noOptions" | "general:noResultsDescription" | "general:noResultsFound" | "general:nothingFound" | "general:noTrashResults" | "general:notSelectedDocument" | "general:notShownInTable" | "general:noUpcomingEventsScheduled" | "general:noValue" | "general:only" | "general:open" | "general:openInNewWindow" | "general:or" | "general:order" | "general:original" | "general:overwriteExistingData" | "general:pageNotFound" | "general:pageNumberRange" | "general:password" | "general:pasteBelow" | "general:pasteField" | "general:pasteRow" | "general:payloadSettings" | "general:permanentlyDelete" | "general:permanentlyDeletedCountSuccessfully" | "general:perPage" | "general:perPageLabel" | "general:presets" | "general:previous" | "general:previousPage" | "general:reindex" | "general:reindexingAll" | "general:reloadDocument" | "general:remove" | "general:removeFilter" | "general:rename" | "general:replaceRow" | "general:requiredFields" | "general:reset" | "general:resetPreferences" | "general:resetPreferencesDescription" | "general:resettingPreferences" | "general:restore" | "general:restoreAsPublished" | "general:restoredCountSuccessfully" | "general:restoring" | "general:retry" | "general:row" | "general:rows" | "general:save" | "general:saving" | "general:schedulePublishFor" | "general:searchAutomatically" | "general:searchBy" | "general:searchCleared" | "general:searchColumns" | "general:searchGroups" | "general:searchResults" | "general:selectAll" | "general:selectAllRows" | "general:selectedCount" | "general:selectedDocument" | "general:selectLabel" | "general:selectValue" | "general:settings" | "general:showAllLabel" | "general:shownInTable" | "general:showSidebar" | "general:skipToContent" | "general:sorryNotFound" | "general:sort" | "general:sortByLabelDirection" | "general:sortByOrderToReorder" | "general:stayOnThisPage" | "general:submissionSuccessful" | "general:submit" | "general:submitting" | "general:success" | "general:successfullyCreated" | "general:successfullyDuplicated" | "general:successfullyReindexed" | "general:tableLayout" | "general:takeOver" | "general:theme" | "general:thisLanguage" | "general:time" | "general:timezone" | "general:titleDeleted" | "general:titleRestored" | "general:titleTrashed" | "general:toggle" | "general:trash" | "general:trashedCountSuccessfully" | "general:true" | "general:unchecked" | "general:unlock" | "general:unsavedChanges" | "general:unsavedChangesDuplicate" | "general:untitled" | "general:upcomingEvents" | "general:updatedAgo" | "general:updatedBy" | "general:updatedCountSuccessfully" | "general:updatedLabelSuccessfully" | "general:updatedSuccessfully" | "general:updateForEveryone" | "general:updating" | "general:uploading" | "general:uploadingBulk" | "general:users" | "general:value" | "general:viewing" | "general:viewReadOnly" | "general:welcome" | "general:where" | "general:yes" | "general:aboutToDeleteCount" | "general:editingLabel" | "hierarchy:noResults" | "hierarchy:searchResults" | "hierarchy:folderLocation" | "hierarchy:goTo" | "hierarchy:itemsMovedTo" | "hierarchy:itemsMovedToRoot" | "hierarchy:moveTo" | "hierarchy:moveToRoot" | "hierarchy:noParent" | "hierarchy:removeFrom" | "hierarchy:searchLabel" | "operators:contains" | "operators:equals" | "operators:exists" | "operators:intersects" | "operators:near" | "operators:within" | "operators:isGreaterThan" | "operators:isGreaterThanOrEqualTo" | "operators:isIn" | "operators:isLessThan" | "operators:isLessThanOrEqualTo" | "operators:isLike" | "operators:isNotEqualTo" | "operators:isNotIn" | "operators:isNotLike" | "validation:required" | "validation:username" | "validation:emailAddress" | "validation:enterNumber" | "validation:fieldHasNo" | "validation:greaterThanMax" | "validation:invalidBlock" | "validation:invalidBlocks" | "validation:invalidInput" | "validation:invalidSelection" | "validation:invalidSelections" | "validation:latitudeOutOfBounds" | "validation:lessThanMin" | "validation:limitReached" | "validation:longerThanMin" | "validation:longitudeOutOfBounds" | "validation:notValidDate" | "validation:requiresAtLeast" | "validation:requiresNoMoreThan" | "validation:requiresTwoNumbers" | "validation:shorterThanMax" | "validation:timezoneRequired" | "validation:trueOrFalse" | "validation:validUploadID" | "version:type" | "version:draft" | "version:version" | "version:aboutToRestore" | "version:restoring" | "version:aboutToPublishSelection" | "version:aboutToRestoreGlobal" | "version:aboutToRevertToPublished" | "version:aboutToUnpublish" | "version:aboutToUnpublishIn" | "version:aboutToUnpublishSelection" | "version:autosave" | "version:autosavedSuccessfully" | "version:autosavedVersion" | "version:changed" | "version:compareVersions" | "version:comparingAgainst" | "version:confirmPublish" | "version:confirmRevertToSaved" | "version:confirmUnpublish" | "version:confirmVersionRestoration" | "version:currentDraft" | "version:currentlyPublished" | "version:currentlyViewing" | "version:currentPublishedVersion" | "version:draftHasPublishedVersion" | "version:draftSavedSuccessfully" | "version:lastSavedAgo" | "version:modifiedOnly" | "version:moreVersions" | "version:noFurtherVersionsFound" | "version:noLabelGroup" | "version:noRowsFound" | "version:noRowsSelected" | "version:preview" | "version:previouslyDraft" | "version:previouslyPublished" | "version:previousVersion" | "version:problemRestoringVersion" | "version:publish" | "version:publishAllLocales" | "version:publishChanges" | "version:published" | "version:publishIn" | "version:publishing" | "version:restoreAsDraft" | "version:restoredSuccessfully" | "version:restoreThisVersion" | "version:reverting" | "version:revertToPublished" | "version:revertUnsuccessful" | "version:saveDraft" | "version:scheduledSuccessfully" | "version:schedulePublish" | "version:selectLocales" | "version:selectVersionToCompare" | "version:showLocales" | "version:specificVersion" | "version:status" | "version:unpublish" | "version:unpublished" | "version:unpublishedSuccessfully" | "version:unpublishIn" | "version:unpublishing" | "version:versionAgo" | "version:versionID" | "version:versions" | "version:viewingVersion" | "version:viewingVersionGlobal" | "version:viewingVersions" | "version:viewingVersionsGlobal" | "version:changedFieldsCount")[];
25
25
 
26
26
  declare const enTranslations: {
27
27
  authentication: {
@@ -4981,7 +4981,11 @@ type GenerateUploadInstructions = (args: {
4981
4981
  type UploadInstructionsCapability = {
4982
4982
  /** Generates upload instructions. The generator or supporting endpoint must check access. */
4983
4983
  generate: GenerateUploadInstructions;
4984
- /** Require a signed server-issued reference before invoking upload handlers. @internal */
4984
+ /**
4985
+ * Require a receipt signed by `resolveSignedURLKey` before invoking upload handlers. Client
4986
+ * uploads keep an `original` and file history only when a receipt is verified.
4987
+ * @see https://payloadcms.com/docs/upload/storage-adapters#custom-upload-receipts
4988
+ */
4985
4989
  requiresUploadReceipt?: boolean;
4986
4990
  /**
4987
4991
  * Whether the Admin panel should use these instructions before saving a document.
@@ -1,6 +1,8 @@
1
1
  import type { PayloadRequest } from '../types/index.js';
2
2
  type ClientUploadReceipt = {
3
3
  _objectKey?: string;
4
+ /** Signed data the storage adapter needs back after upload, such as a provider upload ID. */
5
+ adapterData?: Record<string, unknown>;
4
6
  allowOverwrite?: boolean;
5
7
  collectionSlug: string;
6
8
  expiresAt: number;
@@ -10,8 +12,9 @@ type ClientUploadReceipt = {
10
12
  userCollection: null | string;
11
13
  userID: null | number | string;
12
14
  };
13
- export declare const createClientUploadReceipt: ({ _objectKey, allowOverwrite, collectionSlug, filename, filePrefix, req, storageFilePath, }: {
15
+ export declare const createClientUploadReceipt: ({ _objectKey, adapterData, allowOverwrite, collectionSlug, filename, filePrefix, req, storageFilePath, }: {
14
16
  _objectKey?: string;
17
+ adapterData?: Record<string, unknown>;
15
18
  allowOverwrite?: boolean;
16
19
  collectionSlug: string;
17
20
  filename: string;
@@ -19,6 +22,17 @@ export declare const createClientUploadReceipt: ({ _objectKey, allowOverwrite, c
19
22
  req: PayloadRequest;
20
23
  storageFilePath: string;
21
24
  }) => `${string}.${string}`;
25
+ /**
26
+ * Signs a copy of a receipt with more `adapterData`, such as a provider ID that exists only after
27
+ * the upload. Every other field, including the user and expiry, is kept from the original receipt.
28
+ */
29
+ export declare const resignClientUploadReceipt: ({ adapterData, collectionSlug, req, signedReceipt, }: {
30
+ adapterData: Record<string, unknown>;
31
+ /** Rejects a receipt issued for another collection. */
32
+ collectionSlug?: string;
33
+ req: PayloadRequest;
34
+ signedReceipt: unknown;
35
+ }) => `${string}.${string}`;
22
36
  export declare const verifyClientUploadReceipt: ({ collectionSlug, filename, req, signedReceipt, }: {
23
37
  collectionSlug?: string;
24
38
  filename?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"clientUploadReceipt.d.ts","sourceRoot":"","sources":["../../src/uploads/clientUploadReceipt.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAIvD,KAAK,mBAAmB,GAAG;IACzB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,MAAM,CAAA;IAClB,eAAe,EAAE,MAAM,CAAA;IACvB,cAAc,EAAE,IAAI,GAAG,MAAM,CAAA;IAC7B,MAAM,EAAE,IAAI,GAAG,MAAM,GAAG,MAAM,CAAA;CAC/B,CAAA;AAOD,eAAO,MAAM,yBAAyB,gGAQnC;IACD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,cAAc,EAAE,MAAM,CAAA;IACtB,Q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,CAAA;IACnB,eAAe,EAAE,MAAM,CAAA;CACxB,KAAG,GAAG,MAAM,IAAI,MAAM,EActB,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,yBAAyB,yDAKnC;IACD,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACpC,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;IACnB,aAAa,EAAE,OAAO,CAAA;CACvB,KAAG,GAAG,MAAM,IAAI,MAAM,EAOtB,CAAA;AAED,eAAO,MAAM,yBAAyB,sDAKnC;IACD,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;IACnB,aAAa,EAAE,OAAO,CAAA;CACvB,KAAG,mBA+BH,CAAA"}
@@ -4,11 +4,14 @@ import { APIError } from '../errors/APIError.js';
4
4
  const LIFETIME_MS = 6 * 60 * 60 * 1000;
5
5
  // Separates these signatures from any future receipt format.
6
6
  const DOMAIN = 'payload-client-upload-receipt-v1';
7
- export const createClientUploadReceipt = ({ _objectKey, allowOverwrite, collectionSlug, filename, filePrefix, req, storageFilePath })=>{
7
+ export const createClientUploadReceipt = ({ _objectKey, adapterData, allowOverwrite, collectionSlug, filename, filePrefix, req, storageFilePath })=>{
8
8
  const data = {
9
9
  ..._objectKey !== undefined && {
10
10
  _objectKey
11
11
  },
12
+ ...adapterData !== undefined && {
13
+ adapterData
14
+ },
12
15
  ...allowOverwrite && {
13
16
  allowOverwrite: true
14
17
  },
@@ -19,11 +22,30 @@ export const createClientUploadReceipt = ({ _objectKey, allowOverwrite, collecti
19
22
  storageFilePath,
20
23
  ...getUser(req)
21
24
  };
22
- const encodedReceipt = Buffer.from(JSON.stringify(data)).toString('base64url');
23
- return `${encodedReceipt}.${sign({
24
- encodedReceipt,
25
+ return encodeReceipt({
26
+ data,
25
27
  secret: req.payload.secret
26
- })}`;
28
+ });
29
+ };
30
+ /**
31
+ * Signs a copy of a receipt with more `adapterData`, such as a provider ID that exists only after
32
+ * the upload. Every other field, including the user and expiry, is kept from the original receipt.
33
+ */ export const resignClientUploadReceipt = ({ adapterData, collectionSlug, req, signedReceipt })=>{
34
+ const receipt = verifyClientUploadReceipt({
35
+ collectionSlug,
36
+ req,
37
+ signedReceipt
38
+ });
39
+ return encodeReceipt({
40
+ data: {
41
+ ...receipt,
42
+ adapterData: {
43
+ ...receipt.adapterData,
44
+ ...adapterData
45
+ }
46
+ },
47
+ secret: req.payload.secret
48
+ });
27
49
  };
28
50
  export const verifyClientUploadReceipt = ({ collectionSlug, filename, req, signedReceipt })=>{
29
51
  if (typeof signedReceipt !== 'string') {
@@ -59,6 +81,13 @@ const getUser = (req)=>({
59
81
  userCollection: req.user?.collection ?? null,
60
82
  userID: req.user?.id ?? null
61
83
  });
84
+ const encodeReceipt = ({ data, secret })=>{
85
+ const encodedReceipt = Buffer.from(JSON.stringify(data)).toString('base64url');
86
+ return `${encodedReceipt}.${sign({
87
+ encodedReceipt,
88
+ secret
89
+ })}`;
90
+ };
62
91
  const sign = ({ encodedReceipt, secret })=>crypto.createHmac('sha256', `${DOMAIN}:${secret}`).update(encodedReceipt).digest('base64url');
63
92
  const equal = ({ actual, expected })=>{
64
93
  const actualBuffer = Buffer.from(actual);
@@ -70,7 +99,7 @@ const isReceipt = (value)=>{
70
99
  return false;
71
100
  }
72
101
  const data = value;
73
- return (data._objectKey === undefined || typeof data._objectKey === 'string') && (data.allowOverwrite === undefined || typeof data.allowOverwrite === 'boolean') && typeof data.collectionSlug === 'string' && typeof data.expiresAt === 'number' && Number.isFinite(data.expiresAt) && typeof data.storageFilePath === 'string' && typeof data.filePrefix === 'string' && typeof data.filename === 'string' && (data.userCollection === null || typeof data.userCollection === 'string') && (data.userID === null || typeof data.userID === 'string' || typeof data.userID === 'number' && Number.isFinite(data.userID));
102
+ return (data._objectKey === undefined || typeof data._objectKey === 'string') && (data.adapterData === undefined || typeof data.adapterData === 'object' && data.adapterData !== null && !Array.isArray(data.adapterData)) && (data.allowOverwrite === undefined || typeof data.allowOverwrite === 'boolean') && typeof data.collectionSlug === 'string' && typeof data.expiresAt === 'number' && Number.isFinite(data.expiresAt) && typeof data.storageFilePath === 'string' && typeof data.filePrefix === 'string' && typeof data.filename === 'string' && (data.userCollection === null || typeof data.userCollection === 'string') && (data.userID === null || typeof data.userID === 'string' || typeof data.userID === 'number' && Number.isFinite(data.userID));
74
103
  };
75
104
 
76
105
  //# sourceMappingURL=clientUploadReceipt.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/clientUploadReceipt.ts"],"sourcesContent":["import crypto from 'node:crypto'\n\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { APIError } from '../errors/APIError.js'\n\ntype ClientUploadReceipt = {\n _objectKey?: string\n allowOverwrite?: boolean\n collectionSlug: string\n expiresAt: number\n filename: string\n filePrefix: string\n storageFilePath: string\n userCollection: null | string\n userID: null | number | string\n}\n\n// Longer than the longest provider upload URL (GCS: five hours).\nconst LIFETIME_MS = 6 * 60 * 60 * 1000\n// Separates these signatures from any future receipt format.\nconst DOMAIN = 'payload-client-upload-receipt-v1'\n\nexport const createClientUploadReceipt = ({\n _objectKey,\n allowOverwrite,\n collectionSlug,\n filename,\n filePrefix,\n req,\n storageFilePath,\n}: {\n _objectKey?: string\n allowOverwrite?: boolean\n collectionSlug: string\n filename: string\n filePrefix: string\n req: PayloadRequest\n storageFilePath: string\n}): `${string}.${string}` => {\n const data: ClientUploadReceipt = {\n ...(_objectKey !== undefined && { _objectKey }),\n ...(allowOverwrite && { allowOverwrite: true }),\n collectionSlug,\n expiresAt: Date.now() + LIFETIME_MS,\n filename,\n filePrefix,\n storageFilePath,\n ...getUser(req),\n }\n const encodedReceipt = Buffer.from(JSON.stringify(data)).toString('base64url')\n\n return `${encodedReceipt}.${sign({ encodedReceipt, secret: req.payload.secret })}`\n}\n\nexport const verifyClientUploadReceipt = ({\n collectionSlug,\n filename,\n req,\n signedReceipt,\n}: {\n collectionSlug?: string\n filename?: string\n req: PayloadRequest\n signedReceipt: unknown\n}): ClientUploadReceipt => {\n if (typeof signedReceipt !== 'string') {\n throwInvalidReference()\n }\n const [encodedReceipt, signature, extra] = signedReceipt.split('.')\n const expected = encodedReceipt ? sign({ encodedReceipt, secret: req.payload.secret }) : ''\n\n if (!encodedReceipt || !signature || extra || !equal({ actual: signature, expected })) {\n throwInvalidReference()\n }\n\n let decodedReceipt: unknown\n try {\n decodedReceipt = JSON.parse(Buffer.from(encodedReceipt, 'base64url').toString())\n } catch {\n throwInvalidReference()\n }\n\n const user = getUser(req)\n if (\n !isReceipt(decodedReceipt) ||\n decodedReceipt.expiresAt <= Date.now() ||\n decodedReceipt.userCollection !== user.userCollection ||\n decodedReceipt.userID !== user.userID ||\n (collectionSlug !== undefined && decodedReceipt.collectionSlug !== collectionSlug) ||\n (filename !== undefined && decodedReceipt.filename !== filename)\n ) {\n throwInvalidReference()\n }\n\n return decodedReceipt\n}\n\nfunction throwInvalidReference(): never {\n throw new APIError('Invalid upload reference.', 400)\n}\n\nconst getUser = (req: PayloadRequest) => ({\n userCollection: req.user?.collection ?? null,\n userID: req.user?.id ?? null,\n})\n\nconst sign = ({ encodedReceipt, secret }: { encodedReceipt: string; secret: string }) =>\n crypto.createHmac('sha256', `${DOMAIN}:${secret}`).update(encodedReceipt).digest('base64url')\n\nconst equal = ({ actual, expected }: { actual: string; expected: string }) => {\n const actualBuffer = Buffer.from(actual)\n const expectedBuffer = Buffer.from(expected)\n return (\n actualBuffer.length === expectedBuffer.length &&\n crypto.timingSafeEqual(actualBuffer, expectedBuffer)\n )\n}\n\nconst isReceipt = (value: unknown): value is ClientUploadReceipt => {\n if (!value || typeof value !== 'object') {\n return false\n }\n const data = value as Partial<ClientUploadReceipt>\n return (\n (data._objectKey === undefined || typeof data._objectKey === 'string') &&\n (data.allowOverwrite === undefined || typeof data.allowOverwrite === 'boolean') &&\n typeof data.collectionSlug === 'string' &&\n typeof data.expiresAt === 'number' &&\n Number.isFinite(data.expiresAt) &&\n typeof data.storageFilePath === 'string' &&\n typeof data.filePrefix === 'string' &&\n typeof data.filename === 'string' &&\n (data.userCollection === null || typeof data.userCollection === 'string') &&\n (data.userID === null ||\n typeof data.userID === 'string' ||\n (typeof data.userID === 'number' && Number.isFinite(data.userID)))\n )\n}\n"],"names":["crypto","APIError","LIFETIME_MS","DOMAIN","createClientUploadReceipt","_objectKey","allowOverwrite","collectionSlug","filename","filePrefix","req","storageFilePath","data","undefined","expiresAt","Date","now","getUser","encodedReceipt","Buffer","from","JSON","stringify","toString","sign","secret","payload","verifyClientUploadReceipt","signedReceipt","throwInvalidReference","signature","extra","split","expected","equal","actual","decodedReceipt","parse","user","isReceipt","userCollection","userID","collection","id","createHmac","update","digest","actualBuffer","expectedBuffer","length","timingSafeEqual","value","Number","isFinite"],"mappings":"AAAA,OAAOA,YAAY,cAAa;AAIhC,SAASC,QAAQ,QAAQ,wBAAuB;AAchD,iEAAiE;AACjE,MAAMC,cAAc,IAAI,KAAK,KAAK;AAClC,6DAA6D;AAC7D,MAAMC,SAAS;AAEf,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,UAAU,EACVC,cAAc,EACdC,cAAc,EACdC,QAAQ,EACRC,UAAU,EACVC,GAAG,EACHC,eAAe,EAShB;IACC,MAAMC,OAA4B;QAChC,GAAIP,eAAeQ,aAAa;YAAER;QAAW,CAAC;QAC9C,GAAIC,kBAAkB;YAAEA,gBAAgB;QAAK,CAAC;QAC9CC;QACAO,WAAWC,KAAKC,GAAG,KAAKd;QACxBM;QACAC;QACAE;QACA,GAAGM,QAAQP,IAAI;IACjB;IACA,MAAMQ,iBAAiBC,OAAOC,IAAI,CAACC,KAAKC,SAAS,CAACV,OAAOW,QAAQ,CAAC;IAElE,OAAO,GAAGL,eAAe,CAAC,EAAEM,KAAK;QAAEN;QAAgBO,QAAQf,IAAIgB,OAAO,CAACD,MAAM;IAAC,IAAI;A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AAC;AAEnF,MAAMZ,QAAQ,CAAC,EAAEC,MAAM,EAAEF,QAAQ,EAAwC;IACvE,MAAMc,eAAe5B,OAAOC,IAAI,CAACe;IACjC,MAAMa,iBAAiB7B,OAAOC,IAAI,CAACa;IACnC,OACEc,aAAaE,MAAM,KAAKD,eAAeC,MAAM,IAC7CjD,OAAOkD,eAAe,CAACH,cAAcC;AAEzC;AAEA,MAAMT,YAAY,CAACY;IACjB,IAAI,CAACA,SAAS,OAAOA,UAAU,UAAU;QACvC,OAAO;IACT;IACA,MAAMvC,OAAOuC;IACb,OACE,AAACvC,CAAAA,KAAKP,UAAU,KAAKQ,aAAa,OAAOD,KAAKP,UAAU,KAAK,QAAO,KACnEO,CAAAA,KAAKN,cAAc,KAAKO,aAAa,OAAOD,KAAKN,cAAc,KAAK,SAAQ,KAC7E,OAAOM,KAAKL,cAAc,KAAK,YAC/B,OAAOK,KAAKE,SAAS,KAAK,YAC1BsC,OAAOC,QAAQ,CAACzC,KAAKE,SAAS,KAC9B,OAAOF,KAAKD,eAAe,KAAK,YAChC,OAAOC,KAAKH,UAAU,KAAK,YAC3B,OAAOG,KAAKJ,QAAQ,KAAK,YACxBI,CAAAA,KAAK4B,cAAc,KAAK,QAAQ,OAAO5B,KAAK4B,cAAc,KAAK,QAAO,KACtE5B,CAAAA,KAAK6B,MAAM,KAAK,QACf,OAAO7B,KAAK6B,MAAM,KAAK,YACtB,OAAO7B,KAAK6B,MAAM,KAAK,YAAYW,OAAOC,QAAQ,CAACzC,KAAK6B,MAAM,CAAC;AAEtE"}
1
+ {"version":3,"sources":["../../src/uploads/clientUploadReceipt.ts"],"sourcesContent":["import crypto from 'node:crypto'\n\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { APIError } from '../errors/APIError.js'\n\ntype ClientUploadReceipt = {\n _objectKey?: string\n /** Signed data the storage adapter needs back after upload, such as a provider upload ID. */\n adapterData?: Record<string, unknown>\n allowOverwrite?: boolean\n collectionSlug: string\n expiresAt: number\n filename: string\n filePrefix: string\n storageFilePath: string\n userCollection: null | string\n userID: null | number | string\n}\n\n// Longer than the longest provider upload URL (GCS: five hours).\nconst LIFETIME_MS = 6 * 60 * 60 * 1000\n// Separates these signatures from any future receipt format.\nconst DOMAIN = 'payload-client-upload-receipt-v1'\n\nexport const createClientUploadReceipt = ({\n _objectKey,\n adapterData,\n allowOverwrite,\n collectionSlug,\n filename,\n filePrefix,\n req,\n storageFilePath,\n}: {\n _objectKey?: string\n adapterData?: Record<string, unknown>\n allowOverwrite?: boolean\n collectionSlug: string\n filename: string\n filePrefix: string\n req: PayloadRequest\n storageFilePath: string\n}): `${string}.${string}` => {\n const data: ClientUploadReceipt = {\n ...(_objectKey !== undefined && { _objectKey }),\n ...(adapterData !== undefined && { adapterData }),\n ...(allowOverwrite && { allowOverwrite: true }),\n collectionSlug,\n expiresAt: Date.now() + LIFETIME_MS,\n filename,\n filePrefix,\n storageFilePath,\n ...getUser(req),\n }\n\n return encodeReceipt({ data, secret: req.payload.secret })\n}\n\n/**\n * Signs a copy of a receipt with more `adapterData`, such as a provider ID that exists only after\n * the upload. Every other field, including the user and expiry, is kept from the original receipt.\n */\nexport const resignClientUploadReceipt = ({\n adapterData,\n collectionSlug,\n req,\n signedReceipt,\n}: {\n adapterData: Record<string, unknown>\n /** Rejects a receipt issued for another collection. */\n collectionSlug?: string\n req: PayloadRequest\n signedReceipt: unknown\n}): `${string}.${string}` => {\n const receipt = verifyClientUploadReceipt({ collectionSlug, req, signedReceipt })\n\n return encodeReceipt({\n data: { ...receipt, adapterData: { ...receipt.adapterData, ...adapterData } },\n secret: req.payload.secret,\n })\n}\n\nexport const verifyClientUploadReceipt = ({\n collectionSlug,\n filename,\n req,\n signedReceipt,\n}: {\n collectionSlug?: string\n filename?: string\n req: PayloadRequest\n signedReceipt: unknown\n}): ClientUploadReceipt => {\n if (typeof signedReceipt !== 'string') {\n throwInvalidReference()\n }\n const [encodedReceipt, signature, extra] = signedReceipt.split('.')\n const expected = encodedReceipt ? sign({ encodedReceipt, secret: req.payload.secret }) : ''\n\n if (!encodedReceipt || !signature || extra || !equal({ actual: signature, expected })) {\n throwInvalidReference()\n }\n\n let decodedReceipt: unknown\n try {\n decodedReceipt = JSON.parse(Buffer.from(encodedReceipt, 'base64url').toString())\n } catch {\n throwInvalidReference()\n }\n\n const user = getUser(req)\n if (\n !isReceipt(decodedReceipt) ||\n decodedReceipt.expiresAt <= Date.now() ||\n decodedReceipt.userCollection !== user.userCollection ||\n decodedReceipt.userID !== user.userID ||\n (collectionSlug !== undefined && decodedReceipt.collectionSlug !== collectionSlug) ||\n (filename !== undefined && decodedReceipt.filename !== filename)\n ) {\n throwInvalidReference()\n }\n\n return decodedReceipt\n}\n\nfunction throwInvalidReference(): never {\n throw new APIError('Invalid upload reference.', 400)\n}\n\nconst getUser = (req: PayloadRequest) => ({\n userCollection: req.user?.collection ?? null,\n userID: req.user?.id ?? null,\n})\n\nconst encodeReceipt = ({\n data,\n secret,\n}: {\n data: ClientUploadReceipt\n secret: string\n}): `${string}.${string}` => {\n const encodedReceipt = Buffer.from(JSON.stringify(data)).toString('base64url')\n\n return `${encodedReceipt}.${sign({ encodedReceipt, secret })}`\n}\n\nconst sign = ({ encodedReceipt, secret }: { encodedReceipt: string; secret: string }) =>\n crypto.createHmac('sha256', `${DOMAIN}:${secret}`).update(encodedReceipt).digest('base64url')\n\nconst equal = ({ actual, expected }: { actual: string; expected: string }) => {\n const actualBuffer = Buffer.from(actual)\n const expectedBuffer = Buffer.from(expected)\n return (\n actualBuffer.length === expectedBuffer.length &&\n crypto.timingSafeEqual(actualBuffer, expectedBuffer)\n )\n}\n\nconst isReceipt = (value: unknown): value is ClientUploadReceipt => {\n if (!value || typeof value !== 'object') {\n return false\n }\n const data = value as Partial<ClientUploadReceipt>\n return (\n (data._objectKey === undefined || typeof data._objectKey === 'string') &&\n (data.adapterData === undefined ||\n (typeof data.adapterData === 'object' &&\n data.adapterData !== null &&\n !Array.isArray(data.adapterData))) &&\n (data.allowOverwrite === undefined || typeof data.allowOverwrite === 'boolean') &&\n typeof data.collectionSlug === 'string' &&\n typeof data.expiresAt === 'number' &&\n Number.isFinite(data.expiresAt) &&\n typeof data.storageFilePath === 'string' &&\n typeof data.filePrefix === 'string' &&\n typeof data.filename === 'string' &&\n (data.userCollection === null || typeof data.userCollection === 'string') &&\n (data.userID === null ||\n typeof data.userID === 'string' ||\n (typeof data.userID === 'number' && Number.isFinite(data.userID)))\n )\n}\n"],"names":["crypto","APIError","LIFETIME_MS","DOMAIN","createClientUploadReceipt","_objectKey","adapterData","allowOverwrite","collectionSlug","filename","filePrefix","req","storageFilePath","data","undefined","expiresAt","Date","now","getUser","encodeReceipt","secret","payload","resignClientUploadReceipt","signedReceipt","receipt","verifyClientUploadReceipt","throwInvalidReference","encodedReceipt","signature","extra","split","expected","sign","equal","actual","decodedReceipt","JSON","parse","Buffer","from","toString","user","isReceipt","userCollection","userID","collection","id","stringify","createHmac","update","digest","actualBuffer","expectedBuffer","length","timingSafeEqual","value","Array","isArray","Number","isFinite"],"mappings":"AAAA,OAAOA,YAAY,cAAa;AAIhC,SAASC,QAAQ,QAAQ,wBAAuB;AAgBhD,iEAAiE;AACjE,MAAMC,cAAc,IAAI,KAAK,KAAK;AAClC,6DAA6D;AAC7D,MAAMC,SAAS;AAEf,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,UAAU,EACVC,WAAW,EACXC,cAAc,EACdC,cAAc,EACdC,QAAQ,EACRC,UAAU,EACVC,GAAG,EACHC,eAAe,EAUhB;IACC,MAAMC,OAA4B;QAChC,GAAIR,eAAeS,aAAa;YAAET;QAAW,CAAC;QAC9C,GAAIC,gBAAgBQ,aAAa;YAAER;QAAY,CAAC;QAChD,GAAIC,kBAAkB;YAAEA,gBAAgB;QAAK,CAAC;QAC9CC;QACAO,WAAWC,KAAKC,GAAG,KAAKf;QACxBO;QACAC;QACAE;QACA,GAAGM,QAAQP,IAAI;IACjB;IAEA,OAAOQ,cAAc;QAAEN;QAAMO,Q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a,OAAOD,KAAKN,cAAc,KAAK,SAAQ,KAC7E,OAAOM,KAAKL,cAAc,KAAK,YAC/B,OAAOK,KAAKE,SAAS,KAAK,YAC1B2C,OAAOC,QAAQ,CAAC9C,KAAKE,SAAS,KAC9B,OAAOF,KAAKD,eAAe,KAAK,YAChC,OAAOC,KAAKH,UAAU,KAAK,YAC3B,OAAOG,KAAKJ,QAAQ,KAAK,YACxBI,CAAAA,KAAK8B,cAAc,KAAK,QAAQ,OAAO9B,KAAK8B,cAAc,KAAK,QAAO,KACtE9B,CAAAA,KAAK+B,MAAM,KAAK,QACf,OAAO/B,KAAK+B,MAAM,KAAK,YACtB,OAAO/B,KAAK+B,MAAM,KAAK,YAAYc,OAAOC,QAAQ,CAAC9C,KAAK+B,MAAM,CAAC;AAEtE"}
@@ -1 +1 @@
1
- {"version":3,"file":"getFileFromUploadInstructions.d.ts","sourceRoot":"","sources":["../../src/uploads/getFileFromUploadInstructions.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,KAAK,EAAsC,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAexF,eAAO,MAAM,6BAA6B,mCAIvC;IACD,cAAc,EAAE,MAAM,CAAA;IACtB,IAAI,EAAE,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAChC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,WAAW,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CA4N9C,CAAA"}
1
+ {"version":3,"file":"getFileFromUploadInstructions.d.ts","sourceRoot":"","sources":["../../src/uploads/getFileFromUploadInstructions.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,KAAK,EAAsC,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAexF,eAAO,MAAM,6BAA6B,mCAIvC;IACD,cAAc,EAAE,MAAM,CAAA;IACtB,IAAI,EAAE,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAChC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,WAAW,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CA0O9C,CAAA"}
@@ -35,6 +35,9 @@ export const getFileFromUploadInstructions = async ({ collectionSlug, file, req
35
35
  });
36
36
  }
37
37
  const uploadConfig = req.payload.collections[collectionSlug].config.upload;
38
+ const clientData = getClientData({
39
+ uploadReference: file.uploadReference
40
+ });
38
41
  let allowOverwrite = false;
39
42
  let providerFilename = file.filename;
40
43
  let verifiedOriginal;
@@ -81,10 +84,35 @@ export const getFileFromUploadInstructions = async ({ collectionSlug, file, req
81
84
  ...file,
82
85
  uploadReference: {
83
86
  _objectKey: receipt._objectKey,
87
+ ...receipt.adapterData && {
88
+ adapterData: receipt.adapterData
89
+ },
90
+ ...clientData && {
91
+ clientData
92
+ },
84
93
  prefix: receipt.filePrefix,
85
94
  signedReceipt
86
95
  }
87
96
  };
97
+ } else {
98
+ const { _objectKey, prefix, signedReceipt } = file.uploadReference;
99
+ file = {
100
+ ...file,
101
+ uploadReference: {
102
+ ..._objectKey !== undefined && {
103
+ _objectKey
104
+ },
105
+ ...clientData && {
106
+ clientData
107
+ },
108
+ ...prefix !== undefined && {
109
+ prefix
110
+ },
111
+ ...signedReceipt !== undefined && {
112
+ signedReceipt
113
+ }
114
+ }
115
+ };
88
116
  }
89
117
  const prefix = 'prefix' in file.uploadReference && typeof file.uploadReference.prefix === 'string' ? file.uploadReference.prefix : undefined;
90
118
  let sanitizedFilename;
@@ -204,6 +232,20 @@ export const getFileFromUploadInstructions = async ({ collectionSlug, file, req
204
232
  uploadReference: file.uploadReference
205
233
  };
206
234
  };
235
+ const reservedUploadReferenceKeys = new Set([
236
+ '_objectKey',
237
+ 'adapterData',
238
+ 'clientData',
239
+ 'prefix',
240
+ 'signedReceipt'
241
+ ]);
242
+ /**
243
+ * Collects the fields the client added to `uploadReference`. Payload never reads them, so
244
+ * adapters must verify them before use.
245
+ */ const getClientData = ({ uploadReference })=>{
246
+ const entries = Object.entries(uploadReference).filter(([key])=>!reservedUploadReferenceKeys.has(key));
247
+ return entries.length ? Object.fromEntries(entries) : undefined;
248
+ };
207
249
  /**
208
250
  * Whether the request's `uploadEdits` query param carries a crop or resize edit - reads the raw
209
251
  * `req.query.uploadEdits`, since a full parse (with its `data`/`originalDoc` focal-point
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/getFileFromUploadInstructions.ts"],"sourcesContent":["import type { ReadableStream } from 'node:stream/web'\n\nimport { randomUUID } from 'node:crypto'\nimport fs from 'node:fs'\nimport { mkdir, rm, stat } from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\nimport type { PayloadRequest } from '../types/index.js'\nimport type { SanitizedUploadConfig, UploadEdits, UploadInstructions } from './types.js'\n\nimport { APIError } from '../errors/APIError.js'\nimport { sanitizeFilename } from '../utilities/sanitizeFilename.js'\nimport { sanitizeUploadPrefix } from '../utilities/sanitizeUploadPrefix.js'\nimport { verifyClientUploadReceipt } from './clientUploadReceipt.js'\nimport { docWithFilenameExists } from './docWithFilenameExists.js'\nimport { getOriginalFilename, normalizeStorageKey } from './fileVersioning/naming.js'\nimport { getFileContentRequirement, HEADER_PROBE_BYTE_LENGTH } from './getFileContentRequirement.js'\nimport { getImageSize } from './getImageSize.js'\nimport { hasCropOrResizeEdit } from './hasCropOrResizeEdit.js'\nimport { getStagedFile } from './stagedUpload.js'\nimport { planTransformerPipeline } from './transformers/planTransformerPipeline.js'\nimport { getUploadTransformerInternal } from './transformers/uploadTransformerBridge.js'\n\nexport const getFileFromUploadInstructions = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> => {\n if (req.context) {\n delete req.context._payloadVerifiedProviderOriginal\n }\n\n if (\n !file ||\n typeof file !== 'object' ||\n typeof file.filename !== 'string' ||\n typeof file.mimeType !== 'string' ||\n !Number.isSafeInteger(file.size) ||\n file.size < 0 ||\n !file.uploadReference ||\n typeof file.uploadReference !== 'object' ||\n Array.isArray(file.uploadReference)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n /**\n * Handlers fetch files uploaded to a storage provider. An uploadId points to a temporary file\n * already stored by Payload, so no handler is needed.\n */\n if ('uploadId' in file.uploadReference) {\n return getStagedFile({ collectionSlug, req, uploadReference: file.uploadReference })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]!.config.upload\n let allowOverwrite = false\n let providerFilename = file.filename\n let verifiedOriginal:\n | {\n _objectKey?: string\n filename: string\n key: string\n prefix?: string\n signedReceipt: string\n }\n | undefined\n\n if (uploadConfig?.uploadInstructions?.requiresUploadReceipt) {\n const signedReceipt =\n 'signedReceipt' in file.uploadReference ? file.uploadReference.signedReceipt : undefined\n const receipt = verifyClientUploadReceipt({\n collectionSlug,\n filename: file.filename,\n req,\n signedReceipt,\n })\n allowOverwrite = receipt.allowOverwrite === true\n let originalFilename: string\n let storageFilePath: string\n\n try {\n originalFilename = getOriginalFilename({ filename: file.filename })\n storageFilePath = normalizeStorageKey({ key: receipt.storageFilePath })\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n const expectedKeySuffix = [receipt.filePrefix, receipt._objectKey, originalFilename]\n .filter(Boolean)\n .join('/')\n\n if (\n (!allowOverwrite &&\n (!receipt._objectKey ||\n path.posix.basename(storageFilePath) !== originalFilename ||\n !`/${storageFilePath}`.endsWith(`/${expectedKeySuffix}`))) ||\n ('prefix' in file.uploadReference && file.uploadReference.prefix !== receipt.filePrefix) ||\n ('_objectKey' in file.uploadReference &&\n file.uploadReference._objectKey !== receipt._objectKey)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n providerFilename = allowOverwrite ? file.filename : originalFilename\n if (!allowOverwrite) {\n verifiedOriginal = {\n _objectKey: receipt._objectKey,\n filename: originalFilename,\n key: storageFilePath,\n prefix: receipt.filePrefix,\n signedReceipt: signedReceipt as string,\n }\n }\n file = {\n ...file,\n uploadReference: {\n _objectKey: receipt._objectKey,\n prefix: receipt.filePrefix,\n signedReceipt,\n },\n }\n }\n\n const prefix =\n 'prefix' in file.uploadReference && typeof file.uploadReference.prefix === 'string'\n ? file.uploadReference.prefix\n : undefined\n\n let sanitizedFilename: string\n\n try {\n sanitizedFilename = sanitizeFilename(file.filename)\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (\n sanitizedFilename !== file.filename ||\n (typeof prefix === 'string' && sanitizeUploadPrefix(prefix) !== prefix)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n // Provider-backed references are submitted with the document request. They may only claim a\n // new object identity; existing top-level and generated filenames already belong to another\n // document and must continue through that document's read access checks.\n if (\n !allowOverwrite &&\n (await docWithFilenameExists({\n collectionSlug,\n filename: file.filename,\n matchAnyPrefix: true,\n path: '',\n prefix,\n req,\n }))\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (!uploadConfig || !uploadConfig.handlers) {\n throw new APIError('uploadConfig.handlers is not present for ' + collectionSlug)\n }\n\n const contentRequirement = getFileContentRequirement({\n hasSizeEdits: requestHasSizeEdits(req),\n hasTransformFileStages: await hasTransformFileStages({\n collectionSlug,\n mimeType: file.mimeType,\n req,\n }),\n mimeType: file.mimeType,\n uploadConfig,\n })\n const providerFile = { ...file, filename: providerFilename }\n const rememberVerifiedOriginal = () => {\n if (verifiedOriginal) {\n req.context ??= {}\n req.context._payloadVerifiedProviderOriginal = verifiedOriginal\n }\n }\n\n // Nothing downstream reads this file's content - use the client-reported metadata directly\n // instead of re-downloading a file that, for a chunked upload, can be far larger than\n // the server's available memory or disk.\n if (contentRequirement === 'none') {\n const response = await fetchUploadResponse({\n collectionSlug,\n file: providerFile,\n rangeHeader: file.size > 0 ? 'bytes=0-0' : undefined,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n const prefix = await readBoundedPrefix(response, 1)\n if (file.size > 0 && prefix.length === 0) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n }\n\n if (contentRequirement === 'header') {\n const headerFile = await fetchHeaderOnly({\n collectionSlug,\n file: providerFile,\n req,\n uploadConfig,\n })\n if (headerFile) {\n rememberVerifiedOriginal()\n return { ...headerFile, name: file.filename }\n }\n // The header wasn't enough to determine the image's dimensions - fall through to a full fetch.\n }\n\n const response = await fetchUploadResponse({\n collectionSlug,\n file: providerFile,\n req,\n uploadConfig,\n })\n\n const tempFilePath = await streamResponseToTempFile({ req, response })\n if ((await stat(tempFilePath)).size !== file.size) {\n await rm(tempFilePath, { force: true })\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n req.context ??= {}\n req.context._payloadClientUploadTempFile = true\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: response.headers.get('Content-Type') || file.mimeType,\n size: file.size,\n tempFilePath,\n uploadReference: file.uploadReference,\n }\n}\n\n/**\n * Whether the request's `uploadEdits` query param carries a crop or resize edit - reads the raw\n * `req.query.uploadEdits`, since a full parse (with its `data`/`originalDoc` focal-point\n * fallback, done in generateFileData.ts) isn't available yet at this point in the request\n * lifecycle.\n */\nconst requestHasSizeEdits = (req: PayloadRequest): boolean => {\n const uploadEdits = req.query?.uploadEdits\n if (typeof uploadEdits !== 'object' || uploadEdits === null) {\n return false\n }\n\n return hasCropOrResizeEdit(uploadEdits)\n}\n\n/**\n * Whether a transformer that reads the whole file will run `transformFile` on this upload. A\n * bridge transformer (e.g. `sharpTransformer`) is excluded: it projects what it needs onto the\n * sanitized upload config (`hasImageAdjustments`, `variants`) at startup instead.\n */\nconst hasTransformFileStages = async ({\n collectionSlug,\n mimeType,\n req,\n}: {\n collectionSlug: string\n mimeType: string\n req: PayloadRequest\n}): Promise<boolean> => {\n const transformers = req.payload.config.upload?.transformers ?? []\n\n if (transformers.length === 0) {\n return false\n }\n\n const pipeline = await planTransformerPipeline({\n args: { collectionSlug, mimeType, operation: 'upload', req },\n capability: 'transformFile',\n transformers,\n })\n\n return pipeline.some((transformer) => !getUploadTransformerInternal(transformer)?.prepareUpload)\n}\n\n/**\n * Fetches only the first `HEADER_PROBE_BYTE_LENGTH` bytes of the upload (via a best-effort byte\n * range request) and uses them to probe an image's dimensions, without downloading the rest of\n * the file. Returns null if that isn't enough to determine the dimensions, so the caller can\n * fall back to a full fetch.\n */\nconst fetchHeaderOnly = async ({\n collectionSlug,\n file,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<NonNullable<PayloadRequest['file']> | null> => {\n const response = await fetchUploadResponse({\n collectionSlug,\n file,\n rangeHeader: `bytes=0-${HEADER_PROBE_BYTE_LENGTH - 1}`,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n\n const headerBuffer = await readBoundedPrefix(response, HEADER_PROBE_BYTE_LENGTH)\n\n try {\n await getImageSize({\n file: {\n name: file.filename,\n data: headerBuffer,\n mimetype: file.mimeType,\n size: file.size,\n },\n })\n } catch {\n return null\n }\n\n return {\n name: file.filename,\n data: headerBuffer,\n mimetype: response.headers.get('Content-Type') || file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n}\n\nconst assertProviderFileSize = ({\n expectedSize,\n response,\n}: {\n expectedSize: number\n response: Response\n}): void => {\n const contentRange = response.headers.get('Content-Range')\n const reportedSize =\n response.status === 206\n ? contentRange?.match(/^bytes \\d+-\\d+\\/(\\d+)$/)?.[1]\n : response.headers.get('Content-Length')\n\n if (\n reportedSize === undefined ||\n reportedSize === null ||\n Number(reportedSize) !== expectedSize\n ) {\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n}\n\n/**\n * Runs the collection's upload handlers, following a single redirect if one is returned.\n * `rangeHeader`, when passed, is a best-effort hint - handlers that ignore it simply return the\n * full file, which callers must still bound their own reads against.\n */\nconst fetchUploadResponse = async ({\n collectionSlug,\n file,\n rangeHeader,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n rangeHeader?: string\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<Response> => {\n const scopedReq = rangeHeader ? withRangeHeader(req, rangeHeader) : req\n\n let response: null | Response = null\n let error: unknown\n\n for (const handler of uploadConfig.handlers!) {\n try {\n const result = await handler(scopedReq, {\n doc: null!,\n params: {\n collection: collectionSlug,\n filename: file.filename,\n uploadReference: file.uploadReference,\n },\n })\n if (result) {\n response = result\n /**\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n *\n * @see packages/payload/src/uploads/types.ts\n */\n break\n }\n } catch (err) {\n error = err\n }\n }\n\n if (!response) {\n if (error) {\n req.payload.logger.error(error)\n }\n\n throw new APIError('Expected response from the upload handler.')\n }\n\n if (response.status >= 300 && response.status < 400) {\n const redirectUrl = response.headers.get('Location')\n if (redirectUrl) {\n response = await fetch(redirectUrl, {\n ...(rangeHeader && { headers: { Range: rangeHeader } }),\n })\n }\n }\n\n if (!response.ok) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n\n return response\n}\n\n/**\n * Overrides `req.headers` with a `Range` header while leaving the real incoming request\n * untouched. Uses a Proxy, rather than cloning `req`, because `req` is a native `Request`\n * instance at runtime - accessors like `.signal` are brand-checked against `req`'s internal\n * slots, so a plain clone (e.g. `Object.create(req)`) throws once a handler reads one of them.\n * Forwarding reads through `Reflect.get(req, prop, req)` keeps `this` bound to the real `req`\n * so those accessors keep working.\n */\nconst withRangeHeader = (req: PayloadRequest, rangeHeader: string): PayloadRequest => {\n const headers = new Headers(req.headers)\n headers.set('range', rangeHeader)\n\n return new Proxy(req, {\n get(target, prop) {\n return prop === 'headers' ? headers : Reflect.get(target, prop, target)\n },\n })\n}\n\n/**\n * Reads at most `maxBytes` from the response body, then cancels the reader - so a handler that\n * ignores the range hint and starts streaming the whole file is still cut short on our end.\n */\nconst readBoundedPrefix = async (response: Response, maxBytes: number): Promise<Buffer> => {\n if (!response.body) {\n return Buffer.alloc(0)\n }\n\n const reader = response.body.getReader()\n const chunks: Buffer[] = []\n let total = 0\n\n try {\n while (total < maxBytes) {\n const { done, value } = await reader.read()\n if (done || !value) {\n break\n }\n\n const remaining = maxBytes - total\n const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value\n chunks.push(Buffer.from(chunk))\n total += chunk.byteLength\n }\n } finally {\n await reader.cancel().catch(() => {})\n }\n\n return Buffer.concat(chunks, total)\n}\n\n/**\n * Streams the fetched upload straight to disk instead of buffering it in memory. A client upload\n * (e.g. Azure's chunkLargeFiles) can be far larger than the server's available memory, so this\n * avoids re-downloading the whole file into a single in-memory buffer just to read it back out.\n */\nconst streamResponseToTempFile = async ({\n req,\n response,\n}: {\n req: PayloadRequest\n response: Response\n}): Promise<string> => {\n if (!response.body) {\n throw new APIError('Expected a response body from the upload handler.')\n }\n\n const tempFileDir = req.payload.config.upload?.tempFileDir || os.tmpdir()\n await mkdir(tempFileDir, { recursive: true })\n const tempFilePath = path.join(tempFileDir, `payload-client-upload-${randomUUID()}`)\n\n try {\n await pipeline(\n Readable.fromWeb(response.body as ReadableStream<Uint8Array>),\n fs.createWriteStream(tempFilePath),\n )\n } catch (error) {\n await rm(tempFilePath, { force: true })\n throw error\n }\n\n return tempFilePath\n}\n"],"names":["randomUUID","fs","mkdir","rm","stat","os","path","Readable","pipeline","APIError","sanitizeFilename","sanitizeUploadPrefix","verifyClientUploadReceipt","docWithFilenameExists","getOriginalFilename","normalizeStorageKey","getFileContentRequirement","HEADER_PROBE_BYTE_LENGTH","getImageSize","hasCropOrResizeEdit","getStagedFile","planTransformerPipeline","getUploadTransformerInternal","getFileFromUploadInstructions","collectionSlug","file","req","context","_payloadVerifiedProviderOriginal","filename","mimeType","Number","isSafeInteger","size","uploadReference","Array","isArray","uploadConfig","payload","collections","config","upload","allowOverwrite","providerFilename","verifiedOriginal","uploadInstructions","requiresUploadReceipt","signedReceipt","undefined","receipt","originalFilename","storageFilePath","key","expectedKeySuffix","filePrefix","_objectKey","filter","Boolean","join","posix","basename","endsWith","prefix","sanitizedFilename","matchAnyPrefix","handlers","contentRequirement","hasSizeEdits","requestHasSizeEdits","hasTransformFileStages","providerFile","rememberVerifiedOriginal","response","fetchUploadResponse","rangeHeader","assertProviderFileSize","expectedSize","readBoundedPrefix","length","name","data","Buffer","alloc","mimetype","headerFile","fetchHeaderOnly","tempFilePath","streamResponseToTempFile","force","_payloadClientUploadTempFile","headers","get","uploadEdits","query","transformers","args","operation","capability","some","transformer","prepareUpload","headerBuffer","contentRange","reportedSize","status","match","scopedReq","withRangeHeader","error","handler","result","doc","params","collection","err","logger","redirectUrl","fetch","Range","ok","Headers","set","Proxy","target","prop","Reflect","maxBytes","body","reader","getReader","chunks","total","done","value","read","remaining","chunk","byteLength","subarray","push","from","cancel","catch","concat","tempFileDir","tmpdir","recursive","fromWeb","createWriteStream"],"mappings":"AAEA,SAASA,UAAU,QAAQ,cAAa;AACxC,OAAOC,QAAQ,UAAS;AACxB,SAASC,KAAK,EAAEC,EAAE,EAAEC,IAAI,QAAQ,mBAAkB;AAClD,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,cAAa;AACtC,SAASC,QAAQ,QAAQ,uBAAsB;AAK/C,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,yBAAyB,QAAQ,2BAA0B;AACpE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,6BAA4B;AACrF,S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5C,2BAA2B,OAAO,EACtC7D,GAAG,EACH8C,QAAQ,EAIT;IACC,IAAI,CAACA,SAASuD,IAAI,EAAE;QAClB,MAAM,IAAItH,SAAS;IACrB;IAEA,MAAMuI,cAActH,IAAIY,OAAO,CAACE,MAAM,CAACC,MAAM,EAAEuG,eAAe3I,GAAG4I,MAAM;IACvE,MAAM/I,MAAM8I,aAAa;QAAEE,WAAW;IAAK;IAC3C,MAAM5D,eAAehF,KAAKoD,IAAI,CAACsF,aAAa,CAAC,sBAAsB,EAAEhJ,cAAc;IAEnF,IAAI;QACF,MAAMQ,SACJD,SAAS4I,OAAO,CAAC3E,SAASuD,IAAI,GAC9B9H,GAAGmJ,iBAAiB,CAAC9D;IAEzB,EAAE,OAAOsB,OAAO;QACd,MAAMzG,GAAGmF,cAAc;YAAEE,OAAO;QAAK;QACrC,MAAMoB;IACR;IAEA,OAAOtB;AACT"}
1
+ {"version":3,"sources":["../../src/uploads/getFileFromUploadInstructions.ts"],"sourcesContent":["import type { ReadableStream } from 'node:stream/web'\n\nimport { randomUUID } from 'node:crypto'\nimport fs from 'node:fs'\nimport { mkdir, rm, stat } from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\nimport type { PayloadRequest } from '../types/index.js'\nimport type { SanitizedUploadConfig, UploadEdits, UploadInstructions } from './types.js'\n\nimport { APIError } from '../errors/APIError.js'\nimport { sanitizeFilename } from '../utilities/sanitizeFilename.js'\nimport { sanitizeUploadPrefix } from '../utilities/sanitizeUploadPrefix.js'\nimport { verifyClientUploadReceipt } from './clientUploadReceipt.js'\nimport { docWithFilenameExists } from './docWithFilenameExists.js'\nimport { getOriginalFilename, normalizeStorageKey } from './fileVersioning/naming.js'\nimport { getFileContentRequirement, HEADER_PROBE_BYTE_LENGTH } from './getFileContentRequirement.js'\nimport { getImageSize } from './getImageSize.js'\nimport { hasCropOrResizeEdit } from './hasCropOrResizeEdit.js'\nimport { getStagedFile } from './stagedUpload.js'\nimport { planTransformerPipeline } from './transformers/planTransformerPipeline.js'\nimport { getUploadTransformerInternal } from './transformers/uploadTransformerBridge.js'\n\nexport const getFileFromUploadInstructions = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> => {\n if (req.context) {\n delete req.context._payloadVerifiedProviderOriginal\n }\n\n if (\n !file ||\n typeof file !== 'object' ||\n typeof file.filename !== 'string' ||\n typeof file.mimeType !== 'string' ||\n !Number.isSafeInteger(file.size) ||\n file.size < 0 ||\n !file.uploadReference ||\n typeof file.uploadReference !== 'object' ||\n Array.isArray(file.uploadReference)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n /**\n * Handlers fetch files uploaded to a storage provider. An uploadId points to a temporary file\n * already stored by Payload, so no handler is needed.\n */\n if ('uploadId' in file.uploadReference) {\n return getStagedFile({ collectionSlug, req, uploadReference: file.uploadReference })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]!.config.upload\n const clientData = getClientData({ uploadReference: file.uploadReference })\n let allowOverwrite = false\n let providerFilename = file.filename\n let verifiedOriginal:\n | {\n _objectKey?: string\n filename: string\n key: string\n prefix?: string\n signedReceipt: string\n }\n | undefined\n\n if (uploadConfig?.uploadInstructions?.requiresUploadReceipt) {\n const signedReceipt =\n 'signedReceipt' in file.uploadReference ? file.uploadReference.signedReceipt : undefined\n const receipt = verifyClientUploadReceipt({\n collectionSlug,\n filename: file.filename,\n req,\n signedReceipt,\n })\n allowOverwrite = receipt.allowOverwrite === true\n let originalFilename: string\n let storageFilePath: string\n\n try {\n originalFilename = getOriginalFilename({ filename: file.filename })\n storageFilePath = normalizeStorageKey({ key: receipt.storageFilePath })\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n const expectedKeySuffix = [receipt.filePrefix, receipt._objectKey, originalFilename]\n .filter(Boolean)\n .join('/')\n\n if (\n (!allowOverwrite &&\n (!receipt._objectKey ||\n path.posix.basename(storageFilePath) !== originalFilename ||\n !`/${storageFilePath}`.endsWith(`/${expectedKeySuffix}`))) ||\n ('prefix' in file.uploadReference && file.uploadReference.prefix !== receipt.filePrefix) ||\n ('_objectKey' in file.uploadReference &&\n file.uploadReference._objectKey !== receipt._objectKey)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n providerFilename = allowOverwrite ? file.filename : originalFilename\n if (!allowOverwrite) {\n verifiedOriginal = {\n _objectKey: receipt._objectKey,\n filename: originalFilename,\n key: storageFilePath,\n prefix: receipt.filePrefix,\n signedReceipt: signedReceipt as string,\n }\n }\n file = {\n ...file,\n uploadReference: {\n _objectKey: receipt._objectKey,\n ...(receipt.adapterData && { adapterData: receipt.adapterData }),\n ...(clientData && { clientData }),\n prefix: receipt.filePrefix,\n signedReceipt,\n },\n }\n } else {\n const { _objectKey, prefix, signedReceipt } = file.uploadReference\n file = {\n ...file,\n uploadReference: {\n ...(_objectKey !== undefined && { _objectKey }),\n ...(clientData && { clientData }),\n ...(prefix !== undefined && { prefix }),\n ...(signedReceipt !== undefined && { signedReceipt }),\n },\n }\n }\n\n const prefix =\n 'prefix' in file.uploadReference && typeof file.uploadReference.prefix === 'string'\n ? file.uploadReference.prefix\n : undefined\n\n let sanitizedFilename: string\n\n try {\n sanitizedFilename = sanitizeFilename(file.filename)\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (\n sanitizedFilename !== file.filename ||\n (typeof prefix === 'string' && sanitizeUploadPrefix(prefix) !== prefix)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n // Provider-backed references are submitted with the document request. They may only claim a\n // new object identity; existing top-level and generated filenames already belong to another\n // document and must continue through that document's read access checks.\n if (\n !allowOverwrite &&\n (await docWithFilenameExists({\n collectionSlug,\n filename: file.filename,\n matchAnyPrefix: true,\n path: '',\n prefix,\n req,\n }))\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (!uploadConfig || !uploadConfig.handlers) {\n throw new APIError('uploadConfig.handlers is not present for ' + collectionSlug)\n }\n\n const contentRequirement = getFileContentRequirement({\n hasSizeEdits: requestHasSizeEdits(req),\n hasTransformFileStages: await hasTransformFileStages({\n collectionSlug,\n mimeType: file.mimeType,\n req,\n }),\n mimeType: file.mimeType,\n uploadConfig,\n })\n const providerFile = { ...file, filename: providerFilename }\n const rememberVerifiedOriginal = () => {\n if (verifiedOriginal) {\n req.context ??= {}\n req.context._payloadVerifiedProviderOriginal = verifiedOriginal\n }\n }\n\n // Nothing downstream reads this file's content - use the client-reported metadata directly\n // instead of re-downloading a file that, for a chunked upload, can be far larger than\n // the server's available memory or disk.\n if (contentRequirement === 'none') {\n const response = await fetchUploadResponse({\n collectionSlug,\n file: providerFile,\n rangeHeader: file.size > 0 ? 'bytes=0-0' : undefined,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n const prefix = await readBoundedPrefix(response, 1)\n if (file.size > 0 && prefix.length === 0) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n }\n\n if (contentRequirement === 'header') {\n const headerFile = await fetchHeaderOnly({\n collectionSlug,\n file: providerFile,\n req,\n uploadConfig,\n })\n if (headerFile) {\n rememberVerifiedOriginal()\n return { ...headerFile, name: file.filename }\n }\n // The header wasn't enough to determine the image's dimensions - fall through to a full fetch.\n }\n\n const response = await fetchUploadResponse({\n collectionSlug,\n file: providerFile,\n req,\n uploadConfig,\n })\n\n const tempFilePath = await streamResponseToTempFile({ req, response })\n if ((await stat(tempFilePath)).size !== file.size) {\n await rm(tempFilePath, { force: true })\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n req.context ??= {}\n req.context._payloadClientUploadTempFile = true\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: response.headers.get('Content-Type') || file.mimeType,\n size: file.size,\n tempFilePath,\n uploadReference: file.uploadReference,\n }\n}\n\nconst reservedUploadReferenceKeys = new Set([\n '_objectKey',\n 'adapterData',\n 'clientData',\n 'prefix',\n 'signedReceipt',\n])\n\n/**\n * Collects the fields the client added to `uploadReference`. Payload never reads them, so\n * adapters must verify them before use.\n */\nconst getClientData = ({\n uploadReference,\n}: {\n uploadReference: Record<string, unknown>\n}): Record<string, unknown> | undefined => {\n const entries = Object.entries(uploadReference).filter(\n ([key]) => !reservedUploadReferenceKeys.has(key),\n )\n\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/**\n * Whether the request's `uploadEdits` query param carries a crop or resize edit - reads the raw\n * `req.query.uploadEdits`, since a full parse (with its `data`/`originalDoc` focal-point\n * fallback, done in generateFileData.ts) isn't available yet at this point in the request\n * lifecycle.\n */\nconst requestHasSizeEdits = (req: PayloadRequest): boolean => {\n const uploadEdits = req.query?.uploadEdits\n if (typeof uploadEdits !== 'object' || uploadEdits === null) {\n return false\n }\n\n return hasCropOrResizeEdit(uploadEdits)\n}\n\n/**\n * Whether a transformer that reads the whole file will run `transformFile` on this upload. A\n * bridge transformer (e.g. `sharpTransformer`) is excluded: it projects what it needs onto the\n * sanitized upload config (`hasImageAdjustments`, `variants`) at startup instead.\n */\nconst hasTransformFileStages = async ({\n collectionSlug,\n mimeType,\n req,\n}: {\n collectionSlug: string\n mimeType: string\n req: PayloadRequest\n}): Promise<boolean> => {\n const transformers = req.payload.config.upload?.transformers ?? []\n\n if (transformers.length === 0) {\n return false\n }\n\n const pipeline = await planTransformerPipeline({\n args: { collectionSlug, mimeType, operation: 'upload', req },\n capability: 'transformFile',\n transformers,\n })\n\n return pipeline.some((transformer) => !getUploadTransformerInternal(transformer)?.prepareUpload)\n}\n\n/**\n * Fetches only the first `HEADER_PROBE_BYTE_LENGTH` bytes of the upload (via a best-effort byte\n * range request) and uses them to probe an image's dimensions, without downloading the rest of\n * the file. Returns null if that isn't enough to determine the dimensions, so the caller can\n * fall back to a full fetch.\n */\nconst fetchHeaderOnly = async ({\n collectionSlug,\n file,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<NonNullable<PayloadRequest['file']> | null> => {\n const response = await fetchUploadResponse({\n collectionSlug,\n file,\n rangeHeader: `bytes=0-${HEADER_PROBE_BYTE_LENGTH - 1}`,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n\n const headerBuffer = await readBoundedPrefix(response, HEADER_PROBE_BYTE_LENGTH)\n\n try {\n await getImageSize({\n file: {\n name: file.filename,\n data: headerBuffer,\n mimetype: file.mimeType,\n size: file.size,\n },\n })\n } catch {\n return null\n }\n\n return {\n name: file.filename,\n data: headerBuffer,\n mimetype: response.headers.get('Content-Type') || file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n}\n\nconst assertProviderFileSize = ({\n expectedSize,\n response,\n}: {\n expectedSize: number\n response: Response\n}): void => {\n const contentRange = response.headers.get('Content-Range')\n const reportedSize =\n response.status === 206\n ? contentRange?.match(/^bytes \\d+-\\d+\\/(\\d+)$/)?.[1]\n : response.headers.get('Content-Length')\n\n if (\n reportedSize === undefined ||\n reportedSize === null ||\n Number(reportedSize) !== expectedSize\n ) {\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n}\n\n/**\n * Runs the collection's upload handlers, following a single redirect if one is returned.\n * `rangeHeader`, when passed, is a best-effort hint - handlers that ignore it simply return the\n * full file, which callers must still bound their own reads against.\n */\nconst fetchUploadResponse = async ({\n collectionSlug,\n file,\n rangeHeader,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n rangeHeader?: string\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<Response> => {\n const scopedReq = rangeHeader ? withRangeHeader(req, rangeHeader) : req\n\n let response: null | Response = null\n let error: unknown\n\n for (const handler of uploadConfig.handlers!) {\n try {\n const result = await handler(scopedReq, {\n doc: null!,\n params: {\n collection: collectionSlug,\n filename: file.filename,\n uploadReference: file.uploadReference,\n },\n })\n if (result) {\n response = result\n /**\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n *\n * @see packages/payload/src/uploads/types.ts\n */\n break\n }\n } catch (err) {\n error = err\n }\n }\n\n if (!response) {\n if (error) {\n req.payload.logger.error(error)\n }\n\n throw new APIError('Expected response from the upload handler.')\n }\n\n if (response.status >= 300 && response.status < 400) {\n const redirectUrl = response.headers.get('Location')\n if (redirectUrl) {\n response = await fetch(redirectUrl, {\n ...(rangeHeader && { headers: { Range: rangeHeader } }),\n })\n }\n }\n\n if (!response.ok) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n\n return response\n}\n\n/**\n * Overrides `req.headers` with a `Range` header while leaving the real incoming request\n * untouched. Uses a Proxy, rather than cloning `req`, because `req` is a native `Request`\n * instance at runtime - accessors like `.signal` are brand-checked against `req`'s internal\n * slots, so a plain clone (e.g. `Object.create(req)`) throws once a handler reads one of them.\n * Forwarding reads through `Reflect.get(req, prop, req)` keeps `this` bound to the real `req`\n * so those accessors keep working.\n */\nconst withRangeHeader = (req: PayloadRequest, rangeHeader: string): PayloadRequest => {\n const headers = new Headers(req.headers)\n headers.set('range', rangeHeader)\n\n return new Proxy(req, {\n get(target, prop) {\n return prop === 'headers' ? headers : Reflect.get(target, prop, target)\n },\n })\n}\n\n/**\n * Reads at most `maxBytes` from the response body, then cancels the reader - so a handler that\n * ignores the range hint and starts streaming the whole file is still cut short on our end.\n */\nconst readBoundedPrefix = async (response: Response, maxBytes: number): Promise<Buffer> => {\n if (!response.body) {\n return Buffer.alloc(0)\n }\n\n const reader = response.body.getReader()\n const chunks: Buffer[] = []\n let total = 0\n\n try {\n while (total < maxBytes) {\n const { done, value } = await reader.read()\n if (done || !value) {\n break\n }\n\n const remaining = maxBytes - total\n const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value\n chunks.push(Buffer.from(chunk))\n total += chunk.byteLength\n }\n } finally {\n await reader.cancel().catch(() => {})\n }\n\n return Buffer.concat(chunks, total)\n}\n\n/**\n * Streams the fetched upload straight to disk instead of buffering it in memory. A client upload\n * (e.g. Azure's chunkLargeFiles) can be far larger than the server's available memory, so this\n * avoids re-downloading the whole file into a single in-memory buffer just to read it back out.\n */\nconst streamResponseToTempFile = async ({\n req,\n response,\n}: {\n req: PayloadRequest\n response: Response\n}): Promise<string> => {\n if (!response.body) {\n throw new APIError('Expected a response body from the upload handler.')\n }\n\n const tempFileDir = req.payload.config.upload?.tempFileDir || os.tmpdir()\n await mkdir(tempFileDir, { recursive: true })\n const tempFilePath = path.join(tempFileDir, `payload-client-upload-${randomUUID()}`)\n\n try {\n await pipeline(\n Readable.fromWeb(response.body as ReadableStream<Uint8Array>),\n fs.createWriteStream(tempFilePath),\n )\n } catch (error) {\n await rm(tempFilePath, { force: true })\n throw error\n }\n\n return tempFilePath\n}\n"],"names":["randomUUID","fs","mkdir","rm","stat","os","path","Readable","pipeline","APIError","sanitizeFilename","sanitizeUploadPrefix","verifyClientUploadReceipt","docWithFilenameExists","getOriginalFilename","normalizeStorageKey","getFileContentRequirement","HEADER_PROBE_BYTE_LENGTH","getImageSize","hasCropOrResizeEdit","getStagedFile","planTransformerPipeline","getUploadTransformerInternal","getFileFromUploadInstructions","collectionSlug","file","req","context","_payloadVerifiedProviderOriginal","filename","mimeType","Number","isSafeInteger","size","uploadReference","Array","isArray","uploadConfig","payload","collections","config","upload","clientData","getClientData","allowOverwrite","providerFilename","verifiedOriginal","uploadInstructions","requiresUploadReceipt","signedReceipt","undefined","receipt","originalFilename","storageFilePath","key","expectedKeySuffix","filePrefix","_objectKey","filter","Boolean","join","posix","basename","endsWith","prefix","adapterData","sanitizedFilename","matchAnyPrefix","handlers","contentRequirement","hasSizeEdits","requestHasSizeEdits","hasTransformFileStages","providerFile","rememberVerifiedOriginal","response","fetchUploadResponse","rangeHeader","assertProviderFileSize","expectedSize","readBoundedPrefix","length","name","data","Buffer","alloc","mimetype","headerFile","fetchHeaderOnly","tempFilePath","streamResponseToTempFile","force","_payloadClientUploadTempFile","headers","get","reservedUploadReferenceKeys","Set","entries","Object","has","fromEntries","uploadEdits","query","transformers","args","operation","capability","some","transformer","prepareUpload","headerBuffer","contentRange","reportedSize","status","match","scopedReq","withRangeHeader","error","handler","result","doc","params","collection","err","logger","redirectUrl","fetch","Range","ok","Headers","set","Proxy","target","prop","Reflect","maxBytes","body","reader","getReader","chunks","total","done","value","read","remaining","chunk","byteLength","subarray","push","from","cancel","catch","concat","tempFileDir","tmpdir","recursive","fromWeb","createWriteStream"],"mappings":"AAEA,SAASA,UAAU,QAAQ,cAAa;AACxC,OAAOC,QAAQ,UAAS;AACxB,SAASC,KAAK,EAAEC,EAAE,EAAEC,IAAI,QAAQ,mBAAkB;AAClD,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,cAAa;AACtC,SAASC,QAAQ,QAAQ,uBAAsB;AAK/C,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,yBAAyB,QAAQ,2BAA0B;AACpE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,6BAA4B;AACrF,SAASC,yBAAyB,EAAEC,wBAAwB,QAAQ,iCAAgC;AACpG,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,aAAa,QAAQ,oBAAmB;AACjD,SAASC,uBAAuB,QAAQ,4CAA2C;AACnF,SAASC,4BAA4B,QAAQ,4CAA2C;AAExF,OAAO,MAAMC,gCAAgC,OAAO,EAClDC,cAAc,EACdC,IAAI,EACJC,GAAG,EAKJ;IACC,IAA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C,MAAMC,SAAmB,EAAE;IAC3B,IAAIC,QAAQ;IAEZ,IAAI;QACF,MAAOA,QAAQL,SAAU;YACvB,MAAM,EAAEM,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAML,OAAOM,IAAI;YACzC,IAAIF,QAAQ,CAACC,OAAO;gBAClB;YACF;YAEA,MAAME,YAAYT,WAAWK;YAC7B,MAAMK,QAAQH,MAAMI,UAAU,GAAGF,YAAYF,MAAMK,QAAQ,CAAC,GAAGH,aAAaF;YAC5EH,OAAOS,IAAI,CAAChE,OAAOiE,IAAI,CAACJ;YACxBL,SAASK,MAAMC,UAAU;QAC3B;IACF,SAAU;QACR,MAAMT,OAAOa,MAAM,GAAGC,KAAK,CAAC,KAAO;IACrC;IAEA,OAAOnE,OAAOoE,MAAM,CAACb,QAAQC;AAC/B;AAEA;;;;CAIC,GACD,MAAMlD,2BAA2B,OAAO,EACtChE,GAAG,EACHiD,QAAQ,EAIT;IACC,IAAI,CAACA,SAAS6D,IAAI,EAAE;QAClB,MAAM,IAAI/H,SAAS;IACrB;IAEA,MAAMgJ,cAAc/H,IAAIY,OAAO,CAACE,MAAM,CAACC,MAAM,EAAEgH,eAAepJ,GAAGqJ,MAAM;IACvE,MAAMxJ,MAAMuJ,aAAa;QAAEE,WAAW;IAAK;IAC3C,MAAMlE,eAAenF,KAAKsD,IAAI,CAAC6F,aAAa,CAAC,sBAAsB,EAAEzJ,cAAc;IAEnF,IAAI;QACF,MAAMQ,SACJD,SAASqJ,OAAO,CAACjF,SAAS6D,IAAI,GAC9BvI,GAAG4J,iBAAiB,CAACpE;IAEzB,EAAE,OAAO4B,OAAO;QACd,MAAMlH,GAAGsF,cAAc;YAAEE,OAAO;QAAK;QACrC,MAAM0B;IACR;IAEA,OAAO5B;AACT"}
@@ -378,7 +378,11 @@ export type GenerateUploadInstructions = (args: {
378
378
  export type UploadInstructionsCapability = {
379
379
  /** Generates upload instructions. The generator or supporting endpoint must check access. */
380
380
  generate: GenerateUploadInstructions;
381
- /** Require a signed server-issued reference before invoking upload handlers. @internal */
381
+ /**
382
+ * Require a receipt signed by `resolveSignedURLKey` before invoking upload handlers. Client
383
+ * uploads keep an `original` and file history only when a receipt is verified.
384
+ * @see https://payloadcms.com/docs/upload/storage-adapters#custom-upload-receipts
385
+ */
382
386
  requiresUploadReceipt?: boolean;
383
387
  /**
384
388
  * Whether the Admin panel should use these instructions before saving a document.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/uploads/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAA;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAA;AAE5E,MAAM,MAAM,gBAAgB,GAAG;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;IACtB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,QAAQ,GAAG;IACrB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,MAAM,EAAE,IAAI,GAAG,MAAM,CAAA;IACrB,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,MAAM,CAAC,EA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AAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,MAAM,MAAM,qBAAqB,GAAG;IAClC,SAAS,EAAE,YAAY,CAAC,WAAW,CAAC,CAAA;IACpC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,SAAS,EAAE,CAAA;CACvB,GAAG,YAAY,CAAA;AAEhB,MAAM,MAAM,IAAI,GAAG;IACjB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ;;OAEG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,UAAU,GAClB;IACE;;OAEG;IACH,MAAM,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,IAAI,EAAE,MAAM,CAAA;CACb,GACD;IACE;;OAEG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAA;CACnB,CAAA;AAEL,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,GAAG,GAAG,IAAI,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;CACV,CAAA;AAED,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;CACV,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,UAAU,CAAC,EAAE,UAAU,CAAA;IACvB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/types.ts"],"sourcesContent":["import type { CollectionConfig, TypeWithID } from '../collections/config/types.js'\nimport type { PayloadComponent } from '../config/types.js'\nimport type { UploadCollectionSlug } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { StagedObject } from './fileVersioning/fileOperationManager.js'\n\nexport type OriginalFileData = {\n _objectKey?: string\n filename: string\n filesize: number\n height?: null | number\n mimeType: string\n prefix?: string\n url: string\n width?: null | number\n}\n\nexport type FileSize = {\n _objectKey?: string\n filename: null | string\n filesize: null | number\n height: null | number\n mimeType: null | string\n prefix?: string\n url: null | string\n width: null | number\n}\n\nexport type FileSizes = {\n [size: string]: FileSize\n}\n\nexport type FileData = {\n _objectKey?: string\n filename: string\n filesize: number\n focalX?: number\n focalY?: number\n height: number\n mimeType: string\n original?: null | OriginalFileData\n prefix?: string\n tempFilePath?: string\n url?: string\n variants: FileSizes\n width: number\n}\n\nexport type ProbedImageSize = {\n height: number\n width: number\n}\n\nexport type GenerateImageName = (args: {\n extension: string\n height: number\n originalName: string\n sizeName: string\n width: number\n}) => string\n\ntype ImageSizeBase = {\n /**\n * Admin UI options that control how this image size appears in list views.\n */\n admin?: {\n /**\n * Controls visibility of this image size in the collection list view.\n * Defaults to hiding the image size from columns, filters, and group-by to reduce noise.\n *\n * - `column` — whether to hide this size from selectable list columns. @default false\n * - `filter` — whether to hide this size from filter options. @default false\n * - `groupBy` — whether to hide this size from group-by options. @default false\n */\n disabled?: {\n column?: boolean\n filter?: boolean\n groupBy?: boolean\n }\n }\n /**\n * Generate a custom name for the file of this image size.\n */\n generateImageName?: GenerateImageName\n name: string\n}\n\n/**\n * Interface to be module-augmented by image processing providers.\n *\n * When no provider is registered, ImageSize carries no processor-specific options.\n * When one or more providers are registered (e.g. `@payloadcms/transformer-sharp`),\n * ImageSize uses the union of their registered options instead.\n *\n * @example\n * declare module 'payload' {\n * interface RegisteredImageSizeOptions {\n * myProvider: MyProviderImageSizeOptions\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Intentionally empty so image processing providers can augment it.\nexport interface RegisteredImageSizeOptions {}\n\ntype ImageSizeOptions = keyof RegisteredImageSizeOptions extends never\n ? unknown\n : RegisteredImageSizeOptions[keyof RegisteredImageSizeOptions]\n\nexport type ImageSize = ImageSizeBase & ImageSizeOptions\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type AllowList = Array<{\n hostname: string\n pathname?: string\n port?: string\n protocol?: 'http' | 'https'\n search?: string\n}>\n\nexport type FileAllowList = Array<{\n extensions: string[]\n mimeType: string\n}>\n\nexport type UploadFilePreviewClientProps = {\n filename: string\n filesize: number\n /** Resolved URL of the file (data.url). */\n fileSrc: string\n height?: number\n mimeType: string\n width?: number\n}\n\ntype UploadFilePreviewMap = {\n [mimeTypePattern: string]: PayloadComponent\n}\n\n/**\n * Distinguishes an ordinary public file request (`read`) from Payload's internal\n * retrieval of a stored file's bytes for a dynamic transformation (`transform`).\n * Defaults to `read` when omitted, for third-party handler compatibility.\n */\nexport type FileHandlerOperation = 'read' | 'transform'\n\ntype Admin = {\n components?: {\n /**\n * The Controls component to extend the upload controls in the admin panel.\n */\n controls?: PayloadComponent[]\n /**\n * A custom component to render in place of the default Thumbnail in the upload side panel.\n *\n * Can be a single PayloadComponent (renders for all MIME types) or a Record keyed by\n * MIME type patterns. Pattern resolution priority: exact match → category wildcard\n * (e.g. `video/*`) → universal fallback (`*`). Falls back to the default Thumbnail\n * when nothing matches.\n */\n filePreview?: PayloadComponent | UploadFilePreviewMap\n }\n}\n\nexport type ExternalFileHeaderFilterContext = {\n isSameOrigin: boolean\n url: string\n}\n\nexport type UploadConfig = {\n /**\n * The adapter name to use for uploads. Used for storage adapter telemetry.\n * @default undefined\n */\n adapter?: string\n /**\n * The admin configuration for the upload field.\n */\n admin?: Admin\n /**\n * Represents an admin thumbnail, which can be either a React component or a string.\n * - If a string, it should be one of the image size names.\n * - A function that generates a fully qualified URL for the thumbnail, receives the doc as the only argument.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n /**\n * Allow restricted file types known to be problematic.\n * - If set to `true`, it will allow all file types.\n * - If set to `false`, it will not allow file types and extensions known to be problematic.\n * - This setting is overriden by the `mimeTypes` option.\n * @default false\n */\n allowRestrictedFileTypes?: boolean\n /**\n * Enables bulk upload of files from the list view.\n * @default true\n */\n bulkUpload?: boolean\n /**\n * Appends a cache tag to the image URL when fetching the thumbnail in the admin panel. It may be desirable to disable this when hosting via CDNs with strict parameters.\n *\n * @default true\n */\n cacheTags?: boolean\n /**\n * Enables cropping of images.\n * @default true\n */\n crop?: boolean\n /**\n * Disable the ability to save files to disk.\n * @default false\n */\n disableLocalStorage?: boolean\n /**\n * Enable displaying preview of the uploaded file in Upload fields related to this Collection.\n * Can be locally overridden by `displayPreview` option in Upload field.\n * @default false\n */\n displayPreview?: boolean\n /**\n * Accepts existing headers and returns the headers after filtering or modifying. The optional\n * context identifies the destination for the current request, including each redirect hop.\n * `isSameOrigin` is true only when that destination matches a trusted origin established for a\n * relative file URL.\n * If using this option, you should handle the removal of any sensitive cookies\n * (like payload-prefixed cookies) to prevent leaking session information to external\n * services. By default, Payload automatically filters out payload-prefixed cookies\n * when this option is NOT defined.\n *\n * Useful for adding custom headers to fetch from external providers.\n * @default undefined\n */\n externalFileHeaderFilter?: (\n headers: Record<string, string>,\n context?: ExternalFileHeaderFilterContext,\n ) => Record<string, string>\n /**\n * Field slugs to use for a compound index instead of the default filename index.\n */\n filenameCompoundIndex?: string[]\n /** @internal Set by cloudStoragePlugin for versioned uploads; adapters do not implement this. */\n fileOperations?: {\n /** Copy before the document changes. Must preserve object metadata and reject an occupied key. */\n copy: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n delete: (args: { key: string; req: PayloadRequest }) => Promise<void>\n hasLegacyFile?: (args: {\n doc: Record<string, unknown>\n req: PayloadRequest\n }) => Promise<boolean>\n move?: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n resolveStorageKey: (args: { _objectKey?: string; filename: string; prefix?: string }) => string\n stage: (args: {\n data: Record<string, unknown>\n files: FileToSave[]\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<{ metadata: Record<string, unknown> }>\n }\n /**\n * Require files to be uploaded when creating a document.\n * @default true\n */\n filesRequiredOnCreate?: boolean\n /**\n * Enables focal point positioning for image manipulation.\n * @default true\n */\n focalPoint?: boolean\n /**\n * Custom handlers to run when a file is fetched.\n *\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n * - If no handlers return a response the file will be returned by default.\n *\n * @default undefined\n */\n handlers?: ((\n req: PayloadRequest,\n args: {\n doc: TypeWithID\n headers?: Headers\n params: {\n collection: string\n filename: string\n /** @default 'read' */\n operation?: FileHandlerOperation\n prefix?: string\n uploadReference?: unknown\n }\n },\n ) => Promise<Response> | Promise<void> | Response | void)[]\n /**\n * Whether a registered transformer performs additional processing on the main\n * uploaded file beyond simple pass-through (e.g. resizing, format conversion,\n * trimming). Written by a transformer's `init()`; not intended to be set\n * directly in collection config. Used by the Admin UI to decide whether to\n * show focal-point controls when no image sizes are configured.\n * @internal\n */\n hasImageAdjustments?: boolean\n /**\n * Set to `true` to prevent the admin UI from showing file inputs during document creation, useful for programmatic file generation.\n */\n hideFileInputOnCreate?: boolean\n /**\n * Set to `true` to prevent the admin UI having a way to remove an existing file while editing.\n */\n hideRemoveFile?: boolean\n /**\n * Restrict mimeTypes in the file picker. Array of valid mime types or mimetype wildcards\n * @example ['image/*', 'application/pdf']\n * @default undefined\n */\n mimeTypes?: string[]\n /**\n * Ability to modify the response headers fetching a file.\n * @default undefined\n */\n modifyResponseHeaders?: ({ headers }: { headers: Headers }) => Headers | void\n /**\n * Controls the behavior of pasting/uploading files from URLs.\n * If set to `false`, fetching from remote URLs is disabled.\n * If an `allowList` is provided, server-side fetching will be enabled for specified URLs.\n *\n * @default true (client-side fetching enabled)\n */\n pasteURL?:\n | {\n allowList: AllowList\n }\n | false\n /**\n * Skip safe fetch when using server-side fetching for external files from these URLs.\n * @default false\n */\n skipSafeFetch?: AllowList | boolean\n /**\n * The directory to serve static files from. Defaults to collection slug.\n * @default undefined\n */\n staticDir?: string\n /**\n * Adapter-provided upload instructions.\n * @internal\n */\n uploadInstructions?: UploadInstructionsCapability\n}\n\nexport type UploadInstructionsAccess = (args: {\n collectionSlug: UploadCollectionSlug\n req: PayloadRequest\n}) => boolean | Promise<boolean>\n\nexport type UploadInstructionsRequest = {\n collectionSlug: UploadCollectionSlug\n docPrefix?: string\n filename: string\n filesize: number\n mimeType: string\n}\n\nexport type UploadInstructions = {\n file: {\n filename: string\n mimeType: string\n size: number\n uploadReference: Record<string, unknown>\n }\n} & (\n | {\n data?: unknown\n name: string\n type: 'dispatch'\n }\n | {\n request: {\n headers?: Record<string, string>\n method: 'POST' | 'PUT'\n url: string\n }\n type: 'http'\n }\n)\n\nexport type GenerateUploadInstructions = (\n args: { overrideAccess?: boolean; req: PayloadRequest } & UploadInstructionsRequest,\n) => Promise<UploadInstructions> | UploadInstructions\n\nexport type UploadInstructionsCapability = {\n /** Generates upload instructions. The generator or supporting endpoint must check access. */\n generate: GenerateUploadInstructions\n /** Require a signed server-issued reference before invoking upload handlers. @internal */\n requiresUploadReceipt?: boolean\n /**\n * Whether the Admin panel should use these instructions before saving a document.\n * This can still be useful when upload chunks pass through Payload.\n */\n useInAdmin: boolean\n}\nexport type checkFileRestrictionsParams = {\n /** Set to false when the file bytes have not been uploaded yet. */\n checkFileContents?: boolean\n collection: CollectionConfig\n file: File\n req: PayloadRequest\n}\n\nexport type SanitizedUploadConfig = {\n staticDir: UploadConfig['staticDir']\n /**\n * The collection's image sizes, as written at startup by a registered transformer such as\n * `sharpTransformer({ collections: { <slug>: { variants } } })`. Names and admin options\n * only — not authored on the collection.\n */\n variants?: ImageSize[]\n} & UploadConfig\n\nexport type File = {\n /**\n * The buffer of the file.\n */\n data: Buffer\n /**\n * The mimetype of the file.\n */\n mimetype: string\n /**\n * The name of the file.\n */\n name: string\n /**\n * The size of the file in bytes.\n */\n size: number\n /**\n * Path to the temp file on disk when useTempFiles is enabled. In this case file.data will be an empty buffer.\n */\n tempFilePath?: string\n}\n\nexport type FileToSave =\n | {\n /**\n * The buffer of the file.\n */\n buffer: Buffer\n /**\n * The path to save the file.\n */\n path: string\n }\n | {\n /**\n * The path to save the file.\n */\n path: string\n /**\n * An existing file on disk to copy to `path`, instead of `buffer` - avoids loading a file\n * that's already on disk (e.g. a temp file) fully into memory just to write it back out.\n */\n sourcePath: string\n }\n\ntype Crop = {\n height: number\n unit: '%' | 'px'\n width: number\n x: number\n y: number\n}\n\nexport type FocalPoint = {\n x: number\n y: number\n}\n\nexport type UploadEdits = {\n crop?: Crop\n focalPoint?: FocalPoint\n heightInPixels?: number\n widthInPixels?: number\n}\n"],"names":[],"mappings":"AAweA,WAKC"}
1
+ {"version":3,"sources":["../../src/uploads/types.ts"],"sourcesContent":["import type { CollectionConfig, TypeWithID } from '../collections/config/types.js'\nimport type { PayloadComponent } from '../config/types.js'\nimport type { UploadCollectionSlug } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { StagedObject } from './fileVersioning/fileOperationManager.js'\n\nexport type OriginalFileData = {\n _objectKey?: string\n filename: string\n filesize: number\n height?: null | number\n mimeType: string\n prefix?: string\n url: string\n width?: null | number\n}\n\nexport type FileSize = {\n _objectKey?: string\n filename: null | string\n filesize: null | number\n height: null | number\n mimeType: null | string\n prefix?: string\n url: null | string\n width: null | number\n}\n\nexport type FileSizes = {\n [size: string]: FileSize\n}\n\nexport type FileData = {\n _objectKey?: string\n filename: string\n filesize: number\n focalX?: number\n focalY?: number\n height: number\n mimeType: string\n original?: null | OriginalFileData\n prefix?: string\n tempFilePath?: string\n url?: string\n variants: FileSizes\n width: number\n}\n\nexport type ProbedImageSize = {\n height: number\n width: number\n}\n\nexport type GenerateImageName = (args: {\n extension: string\n height: number\n originalName: string\n sizeName: string\n width: number\n}) => string\n\ntype ImageSizeBase = {\n /**\n * Admin UI options that control how this image size appears in list views.\n */\n admin?: {\n /**\n * Controls visibility of this image size in the collection list view.\n * Defaults to hiding the image size from columns, filters, and group-by to reduce noise.\n *\n * - `column` — whether to hide this size from selectable list columns. @default false\n * - `filter` — whether to hide this size from filter options. @default false\n * - `groupBy` — whether to hide this size from group-by options. @default false\n */\n disabled?: {\n column?: boolean\n filter?: boolean\n groupBy?: boolean\n }\n }\n /**\n * Generate a custom name for the file of this image size.\n */\n generateImageName?: GenerateImageName\n name: string\n}\n\n/**\n * Interface to be module-augmented by image processing providers.\n *\n * When no provider is registered, ImageSize carries no processor-specific options.\n * When one or more providers are registered (e.g. `@payloadcms/transformer-sharp`),\n * ImageSize uses the union of their registered options instead.\n *\n * @example\n * declare module 'payload' {\n * interface RegisteredImageSizeOptions {\n * myProvider: MyProviderImageSizeOptions\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Intentionally empty so image processing providers can augment it.\nexport interface RegisteredImageSizeOptions {}\n\ntype ImageSizeOptions = keyof RegisteredImageSizeOptions extends never\n ? unknown\n : RegisteredImageSizeOptions[keyof RegisteredImageSizeOptions]\n\nexport type ImageSize = ImageSizeBase & ImageSizeOptions\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type AllowList = Array<{\n hostname: string\n pathname?: string\n port?: string\n protocol?: 'http' | 'https'\n search?: string\n}>\n\nexport type FileAllowList = Array<{\n extensions: string[]\n mimeType: string\n}>\n\nexport type UploadFilePreviewClientProps = {\n filename: string\n filesize: number\n /** Resolved URL of the file (data.url). */\n fileSrc: string\n height?: number\n mimeType: string\n width?: number\n}\n\ntype UploadFilePreviewMap = {\n [mimeTypePattern: string]: PayloadComponent\n}\n\n/**\n * Distinguishes an ordinary public file request (`read`) from Payload's internal\n * retrieval of a stored file's bytes for a dynamic transformation (`transform`).\n * Defaults to `read` when omitted, for third-party handler compatibility.\n */\nexport type FileHandlerOperation = 'read' | 'transform'\n\ntype Admin = {\n components?: {\n /**\n * The Controls component to extend the upload controls in the admin panel.\n */\n controls?: PayloadComponent[]\n /**\n * A custom component to render in place of the default Thumbnail in the upload side panel.\n *\n * Can be a single PayloadComponent (renders for all MIME types) or a Record keyed by\n * MIME type patterns. Pattern resolution priority: exact match → category wildcard\n * (e.g. `video/*`) → universal fallback (`*`). Falls back to the default Thumbnail\n * when nothing matches.\n */\n filePreview?: PayloadComponent | UploadFilePreviewMap\n }\n}\n\nexport type ExternalFileHeaderFilterContext = {\n isSameOrigin: boolean\n url: string\n}\n\nexport type UploadConfig = {\n /**\n * The adapter name to use for uploads. Used for storage adapter telemetry.\n * @default undefined\n */\n adapter?: string\n /**\n * The admin configuration for the upload field.\n */\n admin?: Admin\n /**\n * Represents an admin thumbnail, which can be either a React component or a string.\n * - If a string, it should be one of the image size names.\n * - A function that generates a fully qualified URL for the thumbnail, receives the doc as the only argument.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n /**\n * Allow restricted file types known to be problematic.\n * - If set to `true`, it will allow all file types.\n * - If set to `false`, it will not allow file types and extensions known to be problematic.\n * - This setting is overriden by the `mimeTypes` option.\n * @default false\n */\n allowRestrictedFileTypes?: boolean\n /**\n * Enables bulk upload of files from the list view.\n * @default true\n */\n bulkUpload?: boolean\n /**\n * Appends a cache tag to the image URL when fetching the thumbnail in the admin panel. It may be desirable to disable this when hosting via CDNs with strict parameters.\n *\n * @default true\n */\n cacheTags?: boolean\n /**\n * Enables cropping of images.\n * @default true\n */\n crop?: boolean\n /**\n * Disable the ability to save files to disk.\n * @default false\n */\n disableLocalStorage?: boolean\n /**\n * Enable displaying preview of the uploaded file in Upload fields related to this Collection.\n * Can be locally overridden by `displayPreview` option in Upload field.\n * @default false\n */\n displayPreview?: boolean\n /**\n * Accepts existing headers and returns the headers after filtering or modifying. The optional\n * context identifies the destination for the current request, including each redirect hop.\n * `isSameOrigin` is true only when that destination matches a trusted origin established for a\n * relative file URL.\n * If using this option, you should handle the removal of any sensitive cookies\n * (like payload-prefixed cookies) to prevent leaking session information to external\n * services. By default, Payload automatically filters out payload-prefixed cookies\n * when this option is NOT defined.\n *\n * Useful for adding custom headers to fetch from external providers.\n * @default undefined\n */\n externalFileHeaderFilter?: (\n headers: Record<string, string>,\n context?: ExternalFileHeaderFilterContext,\n ) => Record<string, string>\n /**\n * Field slugs to use for a compound index instead of the default filename index.\n */\n filenameCompoundIndex?: string[]\n /** @internal Set by cloudStoragePlugin for versioned uploads; adapters do not implement this. */\n fileOperations?: {\n /** Copy before the document changes. Must preserve object metadata and reject an occupied key. */\n copy: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n delete: (args: { key: string; req: PayloadRequest }) => Promise<void>\n hasLegacyFile?: (args: {\n doc: Record<string, unknown>\n req: PayloadRequest\n }) => Promise<boolean>\n move?: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n resolveStorageKey: (args: { _objectKey?: string; filename: string; prefix?: string }) => string\n stage: (args: {\n data: Record<string, unknown>\n files: FileToSave[]\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<{ metadata: Record<string, unknown> }>\n }\n /**\n * Require files to be uploaded when creating a document.\n * @default true\n */\n filesRequiredOnCreate?: boolean\n /**\n * Enables focal point positioning for image manipulation.\n * @default true\n */\n focalPoint?: boolean\n /**\n * Custom handlers to run when a file is fetched.\n *\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n * - If no handlers return a response the file will be returned by default.\n *\n * @default undefined\n */\n handlers?: ((\n req: PayloadRequest,\n args: {\n doc: TypeWithID\n headers?: Headers\n params: {\n collection: string\n filename: string\n /** @default 'read' */\n operation?: FileHandlerOperation\n prefix?: string\n uploadReference?: unknown\n }\n },\n ) => Promise<Response> | Promise<void> | Response | void)[]\n /**\n * Whether a registered transformer performs additional processing on the main\n * uploaded file beyond simple pass-through (e.g. resizing, format conversion,\n * trimming). Written by a transformer's `init()`; not intended to be set\n * directly in collection config. Used by the Admin UI to decide whether to\n * show focal-point controls when no image sizes are configured.\n * @internal\n */\n hasImageAdjustments?: boolean\n /**\n * Set to `true` to prevent the admin UI from showing file inputs during document creation, useful for programmatic file generation.\n */\n hideFileInputOnCreate?: boolean\n /**\n * Set to `true` to prevent the admin UI having a way to remove an existing file while editing.\n */\n hideRemoveFile?: boolean\n /**\n * Restrict mimeTypes in the file picker. Array of valid mime types or mimetype wildcards\n * @example ['image/*', 'application/pdf']\n * @default undefined\n */\n mimeTypes?: string[]\n /**\n * Ability to modify the response headers fetching a file.\n * @default undefined\n */\n modifyResponseHeaders?: ({ headers }: { headers: Headers }) => Headers | void\n /**\n * Controls the behavior of pasting/uploading files from URLs.\n * If set to `false`, fetching from remote URLs is disabled.\n * If an `allowList` is provided, server-side fetching will be enabled for specified URLs.\n *\n * @default true (client-side fetching enabled)\n */\n pasteURL?:\n | {\n allowList: AllowList\n }\n | false\n /**\n * Skip safe fetch when using server-side fetching for external files from these URLs.\n * @default false\n */\n skipSafeFetch?: AllowList | boolean\n /**\n * The directory to serve static files from. Defaults to collection slug.\n * @default undefined\n */\n staticDir?: string\n /**\n * Adapter-provided upload instructions.\n * @internal\n */\n uploadInstructions?: UploadInstructionsCapability\n}\n\nexport type UploadInstructionsAccess = (args: {\n collectionSlug: UploadCollectionSlug\n req: PayloadRequest\n}) => boolean | Promise<boolean>\n\nexport type UploadInstructionsRequest = {\n collectionSlug: UploadCollectionSlug\n docPrefix?: string\n filename: string\n filesize: number\n mimeType: string\n}\n\nexport type UploadInstructions = {\n file: {\n filename: string\n mimeType: string\n size: number\n uploadReference: Record<string, unknown>\n }\n} & (\n | {\n data?: unknown\n name: string\n type: 'dispatch'\n }\n | {\n request: {\n headers?: Record<string, string>\n method: 'POST' | 'PUT'\n url: string\n }\n type: 'http'\n }\n)\n\nexport type GenerateUploadInstructions = (\n args: { overrideAccess?: boolean; req: PayloadRequest } & UploadInstructionsRequest,\n) => Promise<UploadInstructions> | UploadInstructions\n\nexport type UploadInstructionsCapability = {\n /** Generates upload instructions. The generator or supporting endpoint must check access. */\n generate: GenerateUploadInstructions\n /**\n * Require a receipt signed by `resolveSignedURLKey` before invoking upload handlers. Client\n * uploads keep an `original` and file history only when a receipt is verified.\n * @see https://payloadcms.com/docs/upload/storage-adapters#custom-upload-receipts\n */\n requiresUploadReceipt?: boolean\n /**\n * Whether the Admin panel should use these instructions before saving a document.\n * This can still be useful when upload chunks pass through Payload.\n */\n useInAdmin: boolean\n}\nexport type checkFileRestrictionsParams = {\n /** Set to false when the file bytes have not been uploaded yet. */\n checkFileContents?: boolean\n collection: CollectionConfig\n file: File\n req: PayloadRequest\n}\n\nexport type SanitizedUploadConfig = {\n staticDir: UploadConfig['staticDir']\n /**\n * The collection's image sizes, as written at startup by a registered transformer such as\n * `sharpTransformer({ collections: { <slug>: { variants } } })`. Names and admin options\n * only — not authored on the collection.\n */\n variants?: ImageSize[]\n} & UploadConfig\n\nexport type File = {\n /**\n * The buffer of the file.\n */\n data: Buffer\n /**\n * The mimetype of the file.\n */\n mimetype: string\n /**\n * The name of the file.\n */\n name: string\n /**\n * The size of the file in bytes.\n */\n size: number\n /**\n * Path to the temp file on disk when useTempFiles is enabled. In this case file.data will be an empty buffer.\n */\n tempFilePath?: string\n}\n\nexport type FileToSave =\n | {\n /**\n * The buffer of the file.\n */\n buffer: Buffer\n /**\n * The path to save the file.\n */\n path: string\n }\n | {\n /**\n * The path to save the file.\n */\n path: string\n /**\n * An existing file on disk to copy to `path`, instead of `buffer` - avoids loading a file\n * that's already on disk (e.g. a temp file) fully into memory just to write it back out.\n */\n sourcePath: string\n }\n\ntype Crop = {\n height: number\n unit: '%' | 'px'\n width: number\n x: number\n y: number\n}\n\nexport type FocalPoint = {\n x: number\n y: number\n}\n\nexport type UploadEdits = {\n crop?: Crop\n focalPoint?: FocalPoint\n heightInPixels?: number\n widthInPixels?: number\n}\n"],"names":[],"mappings":"AA4eA,WAKC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payload",
3
- "version": "4.0.0-beta.4",
3
+ "version": "4.0.0-beta.5",
4
4
  "description": "Node, React, Headless CMS and Application Framework built on Next.js",
5
5
  "keywords": [
6
6
  "admin panel",
@@ -118,7 +118,7 @@
118
118
  },
119
119
  "dependencies": {
120
120
  "@next/env": "16.4.2",
121
- "@payloadcms/translations": "4.0.0-beta.4",
121
+ "@payloadcms/translations": "4.0.0-beta.5",
122
122
  "@standard-schema/spec": "1.1.0",
123
123
  "@types/busboy": "1.5.4",
124
124
  "bson-objectid": "2.0.4",