payload 3.0.0-canary.a5aaf21 → 3.0.0-canary.a7293f6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/admin/forms/Label.d.ts +2 -2
  2. package/dist/admin/forms/Label.d.ts.map +1 -1
  3. package/dist/admin/forms/Label.js.map +1 -1
  4. package/dist/auth/operations/forgotPassword.js +1 -1
  5. package/dist/auth/operations/forgotPassword.js.map +1 -1
  6. package/dist/auth/operations/login.d.ts.map +1 -1
  7. package/dist/auth/operations/login.js +2 -2
  8. package/dist/auth/operations/login.js.map +1 -1
  9. package/dist/auth/operations/me.d.ts.map +1 -1
  10. package/dist/auth/operations/me.js +3 -1
  11. package/dist/auth/operations/me.js.map +1 -1
  12. package/dist/auth/operations/refresh.d.ts.map +1 -1
  13. package/dist/auth/operations/refresh.js +3 -1
  14. package/dist/auth/operations/refresh.js.map +1 -1
  15. package/dist/bin/generateTypes.d.ts.map +1 -1
  16. package/dist/bin/generateTypes.js +52 -1
  17. package/dist/bin/generateTypes.js.map +1 -1
  18. package/dist/bin/index.d.ts +1 -1
  19. package/dist/bin/index.d.ts.map +1 -1
  20. package/dist/bin/index.js +25 -0
  21. package/dist/bin/index.js.map +1 -1
  22. package/dist/collections/config/types.d.ts +5 -8
  23. package/dist/collections/config/types.d.ts.map +1 -1
  24. package/dist/collections/config/types.js.map +1 -1
  25. package/dist/config/client.d.ts +1 -1
  26. package/dist/config/client.d.ts.map +1 -1
  27. package/dist/config/client.js +3 -1
  28. package/dist/config/client.js.map +1 -1
  29. package/dist/config/defaults.d.ts.map +1 -1
  30. package/dist/config/defaults.js +10 -1
  31. package/dist/config/defaults.js.map +1 -1
  32. package/dist/config/sanitize.d.ts.map +1 -1
  33. package/dist/config/sanitize.js +21 -0
  34. package/dist/config/sanitize.js.map +1 -1
  35. package/dist/config/types.d.ts +41 -4
  36. package/dist/config/types.d.ts.map +1 -1
  37. package/dist/config/types.js.map +1 -1
  38. package/dist/database/defaultBeginTransaction.d.ts +6 -0
  39. package/dist/database/defaultBeginTransaction.d.ts.map +1 -0
  40. package/dist/database/defaultBeginTransaction.js +8 -0
  41. package/dist/database/defaultBeginTransaction.js.map +1 -0
  42. package/dist/database/types.d.ts +17 -3
  43. package/dist/database/types.d.ts.map +1 -1
  44. package/dist/database/types.js.map +1 -1
  45. package/dist/exports/i18n/da.d.ts +2 -0
  46. package/dist/exports/i18n/da.d.ts.map +1 -0
  47. package/dist/exports/i18n/da.js +3 -0
  48. package/dist/exports/i18n/da.js.map +1 -0
  49. package/dist/fields/config/sanitize.d.ts.map +1 -1
  50. package/dist/fields/config/sanitize.js +3 -0
  51. package/dist/fields/config/sanitize.js.map +1 -1
  52. package/dist/fields/config/sanitizeJoinField.d.ts.map +1 -1
  53. package/dist/fields/config/sanitizeJoinField.js +4 -1
  54. package/dist/fields/config/sanitizeJoinField.js.map +1 -1
  55. package/dist/fields/config/types.d.ts +8 -3
  56. package/dist/fields/config/types.d.ts.map +1 -1
  57. package/dist/fields/config/types.js.map +1 -1
  58. package/dist/index.d.ts +46 -5
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +4 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/preferences/operations/update.d.ts.map +1 -1
  63. package/dist/preferences/operations/update.js +6 -17
  64. package/dist/preferences/operations/update.js.map +1 -1
  65. package/dist/queues/config/generateJobsJSONSchemas.d.ts +18 -0
  66. package/dist/queues/config/generateJobsJSONSchemas.d.ts.map +1 -0
  67. package/dist/queues/config/generateJobsJSONSchemas.js +118 -0
  68. package/dist/queues/config/generateJobsJSONSchemas.js.map +1 -0
  69. package/dist/queues/config/jobsCollection.d.ts +4 -0
  70. package/dist/queues/config/jobsCollection.d.ts.map +1 -0
  71. package/dist/queues/config/jobsCollection.js +264 -0
  72. package/dist/queues/config/jobsCollection.js.map +1 -0
  73. package/dist/queues/config/types/index.d.ts +45 -0
  74. package/dist/queues/config/types/index.d.ts.map +1 -0
  75. package/dist/queues/config/types/index.js +3 -0
  76. package/dist/queues/config/types/index.js.map +1 -0
  77. package/dist/queues/config/types/taskTypes.d.ts +131 -0
  78. package/dist/queues/config/types/taskTypes.d.ts.map +1 -0
  79. package/dist/queues/config/types/taskTypes.js +3 -0
  80. package/dist/queues/config/types/taskTypes.js.map +1 -0
  81. package/dist/queues/config/types/workflowTypes.d.ts +90 -0
  82. package/dist/queues/config/types/workflowTypes.d.ts.map +1 -0
  83. package/dist/queues/config/types/workflowTypes.js +3 -0
  84. package/dist/queues/config/types/workflowTypes.js.map +1 -0
  85. package/dist/queues/operations/local/index.d.ts +21 -0
  86. package/dist/queues/operations/local/index.d.ts.map +1 -0
  87. package/dist/queues/operations/local/index.js +27 -0
  88. package/dist/queues/operations/local/index.js.map +1 -0
  89. package/dist/queues/operations/rest/run.d.ts +3 -0
  90. package/dist/queues/operations/rest/run.d.ts.map +1 -0
  91. package/dist/queues/operations/rest/run.js +62 -0
  92. package/dist/queues/operations/rest/run.js.map +1 -0
  93. package/dist/queues/operations/runAllJobs/index.d.ts +14 -0
  94. package/dist/queues/operations/runAllJobs/index.d.ts.map +1 -0
  95. package/dist/queues/operations/runAllJobs/index.js +143 -0
  96. package/dist/queues/operations/runAllJobs/index.js.map +1 -0
  97. package/dist/queues/operations/runJob/calculateBackoffWaitUntil.d.ts +6 -0
  98. package/dist/queues/operations/runJob/calculateBackoffWaitUntil.d.ts.map +1 -0
  99. package/dist/queues/operations/runJob/calculateBackoffWaitUntil.js +26 -0
  100. package/dist/queues/operations/runJob/calculateBackoffWaitUntil.js.map +1 -0
  101. package/dist/queues/operations/runJob/getRunTaskFunction.d.ts +25 -0
  102. package/dist/queues/operations/runJob/getRunTaskFunction.d.ts.map +1 -0
  103. package/dist/queues/operations/runJob/getRunTaskFunction.js +197 -0
  104. package/dist/queues/operations/runJob/getRunTaskFunction.js.map +1 -0
  105. package/dist/queues/operations/runJob/getUpdateJobFunction.d.ts +5 -0
  106. package/dist/queues/operations/runJob/getUpdateJobFunction.d.ts.map +1 -0
  107. package/dist/queues/operations/runJob/getUpdateJobFunction.js +18 -0
  108. package/dist/queues/operations/runJob/getUpdateJobFunction.js.map +1 -0
  109. package/dist/queues/operations/runJob/importHandlerPath.d.ts +2 -0
  110. package/dist/queues/operations/runJob/importHandlerPath.d.ts.map +1 -0
  111. package/dist/queues/operations/runJob/importHandlerPath.js +21 -0
  112. package/dist/queues/operations/runJob/importHandlerPath.js.map +1 -0
  113. package/dist/queues/operations/runJob/index.d.ts +14 -0
  114. package/dist/queues/operations/runJob/index.d.ts.map +1 -0
  115. package/dist/queues/operations/runJob/index.js +110 -0
  116. package/dist/queues/operations/runJob/index.js.map +1 -0
  117. package/dist/queues/operations/todo_json_defined_jobs/findStepToRun.d.ts +2 -0
  118. package/dist/queues/operations/todo_json_defined_jobs/findStepToRun.d.ts.map +1 -0
  119. package/dist/queues/operations/todo_json_defined_jobs/findStepToRun.js +18 -0
  120. package/dist/queues/operations/todo_json_defined_jobs/findStepToRun.js.map +1 -0
  121. package/dist/queues/operations/todo_json_defined_jobs/runStep.d.ts +2 -0
  122. package/dist/queues/operations/todo_json_defined_jobs/runStep.d.ts.map +1 -0
  123. package/dist/queues/operations/todo_json_defined_jobs/runStep.js +228 -0
  124. package/dist/queues/operations/todo_json_defined_jobs/runStep.js.map +1 -0
  125. package/dist/queues/utilities/getJobTaskStatus.d.ts +9 -0
  126. package/dist/queues/utilities/getJobTaskStatus.d.ts.map +1 -0
  127. package/dist/queues/utilities/getJobTaskStatus.js +29 -0
  128. package/dist/queues/utilities/getJobTaskStatus.js.map +1 -0
  129. package/dist/utilities/configToJSONSchema.d.ts +8 -1
  130. package/dist/utilities/configToJSONSchema.d.ts.map +1 -1
  131. package/dist/utilities/configToJSONSchema.js +44 -11
  132. package/dist/utilities/configToJSONSchema.js.map +1 -1
  133. package/dist/utilities/initTransaction.d.ts.map +1 -1
  134. package/dist/utilities/initTransaction.js +1 -2
  135. package/dist/utilities/initTransaction.js.map +1 -1
  136. package/dist/versions/drafts/getQueryDraftsSort.d.ts.map +1 -1
  137. package/dist/versions/drafts/getQueryDraftsSort.js +3 -0
  138. package/dist/versions/drafts/getQueryDraftsSort.js.map +1 -1
  139. package/dist/versions/types.d.ts +1 -0
  140. package/dist/versions/types.d.ts.map +1 -1
  141. package/dist/versions/types.js.map +1 -1
  142. package/package.json +4 -3
@@ -10,8 +10,8 @@ export type GenericLabelProps = {
10
10
  readonly required?: boolean;
11
11
  readonly unstyled?: boolean;
12
12
  };
13
- export type FieldLabelClientProps<TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType> = {
14
- field: TFieldClient;
13
+ export type FieldLabelClientProps<TFieldClient extends Partial<ClientFieldWithOptionalType> = Partial<ClientFieldWithOptionalType>> = {
14
+ field?: TFieldClient;
15
15
  } & GenericLabelProps;
16
16
  export type FieldLabelServerProps<TFieldServer extends Field, TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType> = {
17
17
  clientField: TFieldClient;
@@ -1 +1 @@
1
- {"version":3,"file":"Label.d.ts","sourceRoot":"","sources":["../../../src/admin/forms/Label.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACrE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAA;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAA;AAE7D,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,CAAC,EAAE,CAAC,EAAE,OAAO,GAAG,MAAM,CAAA;IAC9B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,eAAe,CAAA;IAChC,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,CAAA;IAC5B,QAAQ,CAAC,QAAQ,CAAC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":3,"sources":["../../../src/admin/forms/Label.ts"],"sourcesContent":["import type { ServerProps, StaticLabel } from '../../config/types.js'\nimport type { Field } from '../../fields/config/types.js'\nimport type { MappedComponent } from '../types.js'\nimport type { ClientFieldWithOptionalType } from './Field.js'\n\nexport type GenericLabelProps = {\n readonly as?: 'label' | 'span'\n readonly htmlFor?: string\n readonly Label?: MappedComponent\n readonly label?: StaticLabel\n readonly required?: boolean\n readonly unstyled?: boolean\n}\n\nexport type FieldLabelClientProps<\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = {\n field: TFieldClient\n} & GenericLabelProps\n\nexport type FieldLabelServerProps<\n TFieldServer extends Field,\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = {\n clientField: TFieldClient\n readonly field: TFieldServer\n} & GenericLabelProps &\n Partial<ServerProps>\n\nexport type SanitizedLabelProps<TFieldClient extends ClientFieldWithOptionalType> = Omit<\n FieldLabelClientProps<TFieldClient>,\n 'label' | 'required'\n>\n\nexport type FieldLabelClientComponent<\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = React.ComponentType<FieldLabelClientProps<TFieldClient>>\n\nexport type FieldLabelServerComponent<\n TFieldServer extends Field = Field,\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = React.ComponentType<FieldLabelServerProps<TFieldServer, TFieldClient>>\n"],"names":[],"mappings":"AAsCA,WAG0E"}
1
+ {"version":3,"sources":["../../../src/admin/forms/Label.ts"],"sourcesContent":["import type { ServerProps, StaticLabel } from '../../config/types.js'\nimport type { Field } from '../../fields/config/types.js'\nimport type { MappedComponent } from '../types.js'\nimport type { ClientFieldWithOptionalType } from './Field.js'\n\nexport type GenericLabelProps = {\n readonly as?: 'label' | 'span'\n readonly htmlFor?: string\n readonly Label?: MappedComponent\n readonly label?: StaticLabel\n readonly required?: boolean\n readonly unstyled?: boolean\n}\n\nexport type FieldLabelClientProps<\n TFieldClient extends Partial<ClientFieldWithOptionalType> = Partial<ClientFieldWithOptionalType>,\n> = {\n field?: TFieldClient\n} & GenericLabelProps\n\nexport type FieldLabelServerProps<\n TFieldServer extends Field,\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = {\n clientField: TFieldClient\n readonly field: TFieldServer\n} & GenericLabelProps &\n Partial<ServerProps>\n\nexport type SanitizedLabelProps<TFieldClient extends ClientFieldWithOptionalType> = Omit<\n FieldLabelClientProps<TFieldClient>,\n 'label' | 'required'\n>\n\nexport type FieldLabelClientComponent<\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = React.ComponentType<FieldLabelClientProps<TFieldClient>>\n\nexport type FieldLabelServerComponent<\n TFieldServer extends Field = Field,\n TFieldClient extends ClientFieldWithOptionalType = ClientFieldWithOptionalType,\n> = React.ComponentType<FieldLabelServerProps<TFieldServer, TFieldClient>>\n"],"names":[],"mappings":"AAsCA,WAG0E"}
@@ -79,7 +79,7 @@ export const forgotPasswordOperation = async (incomingArgs)=>{
79
79
  ;
80
80
  const serverURL = config.serverURL !== null && config.serverURL !== '' ? config.serverURL : `${protocol}//${req.headers.get('host')}`;
81
81
  let html = `${req.t('authentication:youAreReceivingResetPassword')}
82
- <a href="${serverURL}${config.routes.admin}/${config.admin.routes.reset}/${token}">${serverURL}${config.routes.admin}/${config.admin.routes.reset}/${token}</a>
82
+ <a href="${serverURL}${config.routes.admin}${config.admin.routes.reset}/${token}">${serverURL}${config.routes.admin}${config.admin.routes.reset}/${token}</a>
83
83
  ${req.t('authentication:youDidNotRequestPassword')}`;
84
84
  if (typeof collectionConfig.auth.forgotPassword.generateEmailHTML === 'function') {
85
85
  html = await collectionConfig.auth.forgotPassword.generateEmailHTML({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/forgotPassword.ts"],"sourcesContent":["import crypto from 'crypto'\nimport httpStatus from 'http-status'\nimport { URL } from 'url'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { APIError } from '../../errors/index.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: {\n [key: string]: unknown\n } & AuthOperationsFromCollectionSlug<TSlug>['forgotPassword']\n disableEmail?: boolean\n expiration?: number\n req: PayloadRequest\n}\n\nexport type Result = string\n\nexport const forgotPasswordOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<null | string> => {\n const loginWithUsername = incomingArgs.collection.config.auth.loginWithUsername\n const { data } = incomingArgs\n\n const canLoginWithUsername = Boolean(loginWithUsername)\n const canLoginWithEmail = !loginWithUsername || loginWithUsername.allowEmailLogin\n\n const sanitizedEmail =\n (canLoginWithEmail && (incomingArgs.data.email || '').toLowerCase().trim()) || null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n let args = incomingArgs\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'forgotPassword',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n collection: { config: collectionConfig },\n data,\n disableEmail,\n expiration,\n req: {\n payload: { config, email },\n payload,\n },\n req,\n } = args\n\n // /////////////////////////////////////\n // Forget password\n // /////////////////////////////////////\n\n let token: string = crypto.randomBytes(20).toString('hex')\n type UserDoc = {\n email?: string\n id: number | string\n resetPasswordExpiration?: string\n resetPasswordToken?: string\n }\n\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n let whereConstraint: Where = {}\n\n if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = {\n email: {\n equals: sanitizedEmail,\n },\n }\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = {\n username: {\n equals: sanitizedUsername,\n },\n }\n }\n\n let user = await payload.db.findOne<UserDoc>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })\n\n // We don't want to indicate specifically that an email was not found,\n // as doing so could lead to the exposure of registered emails.\n // Therefore, we prefer to fail silently.\n if (!user) {\n return null\n }\n\n user.resetPasswordToken = token\n user.resetPasswordExpiration = new Date(expiration || Date.now() + 3600000).toISOString() // 1 hour\n\n user = await payload.update({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n if (!disableEmail && user.email) {\n const protocol = new URL(req.url).protocol // includes the final :\n const serverURL =\n config.serverURL !== null && config.serverURL !== ''\n ? config.serverURL\n : `${protocol}//${req.headers.get('host')}`\n\n let html = `${req.t('authentication:youAreReceivingResetPassword')}\n <a href=\"${serverURL}${config.routes.admin}/${config.admin.routes.reset}/${token}\">${serverURL}${config.routes.admin}/${config.admin.routes.reset}/${token}</a>\n ${req.t('authentication:youDidNotRequestPassword')}`\n\n if (typeof collectionConfig.auth.forgotPassword.generateEmailHTML === 'function') {\n html = await collectionConfig.auth.forgotPassword.generateEmailHTML({\n req,\n token,\n user,\n })\n }\n\n let subject = req.t('authentication:resetYourPassword')\n\n if (typeof collectionConfig.auth.forgotPassword.generateEmailSubject === 'function') {\n subject = await collectionConfig.auth.forgotPassword.generateEmailSubject({\n req,\n token,\n user,\n })\n }\n\n await email.sendEmail({\n from: `\"${email.defaultFromName}\" <${email.defaultFromAddress}>`,\n html,\n subject,\n to: user.email,\n })\n }\n\n // /////////////////////////////////////\n // afterForgotPassword - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterForgotPassword.reduce(async (priorHook, hook) => {\n await priorHook\n await hook({ args, collection: args.collection?.config, context: req.context })\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n token = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'forgotPassword',\n result: token,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return token\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["crypto","httpStatus","URL","buildAfterOperation","APIError","commitTransaction","initTransaction","killTransaction","forgotPasswordOperation","incomingArgs","loginWithUsername","collection","config","auth","data","canLoginWithUsername","Boolean","canLoginWithEmail","allowEmailLogin","sanitizedEmail","email","toLowerCase","trim","sanitizedUsername","username","BAD_REQUEST","args","shouldCommit","req","hooks","beforeOperation","reduce","priorHook","hook","context","operation","Promise","resolve","collectionConfig","disableEmail","expiration","payload","token","randomBytes","toString","whereConstraint","equals","user","db","findOne","slug","where","resetPasswordToken","resetPasswordExpiration","Date","now","toISOString","update","id","protocol","url","serverURL","headers","get","html","t","routes","admin","reset","forgotPassword","generateEmailHTML","subject","generateEmailSubject","sendEmail","from","defaultFromName","defaultFromAddress","to","afterForgotPassword","result","error"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,OAAOC,gBAAgB,cAAa;AACpC,SAASC,GAAG,QAAQ,MAAK;AASzB,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AAcpE,OAAO,MAAMC,0BAA0B,OACrCC;IAEA,MAAMC,oBAAoBD,aAAaE,UAAU,CAAC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,OAAO;QAElB,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCK,QAAQ,MAAMvC,oBAAoB;YAChCuB;YACAf,YAAYe,KAAKf,UAAU,EAAEC;YAC7BuB,WAAW;YACX4C,QAAQrC;QACV;QAEA,IAAIf,cAAc;YAChB,MAAMtB,kBAAkBuB;QAC1B;QAEA,OAAOc;IACT,EAAE,OAAOsC,OAAgB;QACvB,MAAMzE,gBAAgBmB,KAAKE,GAAG;QAC9B,MAAMoD;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/forgotPassword.ts"],"sourcesContent":["import crypto from 'crypto'\nimport httpStatus from 'http-status'\nimport { URL } from 'url'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { APIError } from '../../errors/index.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: {\n [key: string]: unknown\n } & AuthOperationsFromCollectionSlug<TSlug>['forgotPassword']\n disableEmail?: boolean\n expiration?: number\n req: PayloadRequest\n}\n\nexport type Result = string\n\nexport const forgotPasswordOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<null | string> => {\n const loginWithUsername = incomingArgs.collection.config.auth.loginWithUsername\n const { data } = incomingArgs\n\n const canLoginWithUsername = Boolean(loginWithUsername)\n const canLoginWithEmail = !loginWithUsername || loginWithUsername.allowEmailLogin\n\n const sanitizedEmail =\n (canLoginWithEmail && (incomingArgs.data.email || '').toLowerCase().trim()) || null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n let args = incomingArgs\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'forgotPassword',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n collection: { config: collectionConfig },\n data,\n disableEmail,\n expiration,\n req: {\n payload: { config, email },\n payload,\n },\n req,\n } = args\n\n // /////////////////////////////////////\n // Forget password\n // /////////////////////////////////////\n\n let token: string = crypto.randomBytes(20).toString('hex')\n type UserDoc = {\n email?: string\n id: number | string\n resetPasswordExpiration?: string\n resetPasswordToken?: string\n }\n\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n let whereConstraint: Where = {}\n\n if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = {\n email: {\n equals: sanitizedEmail,\n },\n }\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = {\n username: {\n equals: sanitizedUsername,\n },\n }\n }\n\n let user = await payload.db.findOne<UserDoc>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })\n\n // We don't want to indicate specifically that an email was not found,\n // as doing so could lead to the exposure of registered emails.\n // Therefore, we prefer to fail silently.\n if (!user) {\n return null\n }\n\n user.resetPasswordToken = token\n user.resetPasswordExpiration = new Date(expiration || Date.now() + 3600000).toISOString() // 1 hour\n\n user = await payload.update({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n if (!disableEmail && user.email) {\n const protocol = new URL(req.url).protocol // includes the final :\n const serverURL =\n config.serverURL !== null && config.serverURL !== ''\n ? config.serverURL\n : `${protocol}//${req.headers.get('host')}`\n\n let html = `${req.t('authentication:youAreReceivingResetPassword')}\n <a href=\"${serverURL}${config.routes.admin}${config.admin.routes.reset}/${token}\">${serverURL}${config.routes.admin}${config.admin.routes.reset}/${token}</a>\n ${req.t('authentication:youDidNotRequestPassword')}`\n\n if (typeof collectionConfig.auth.forgotPassword.generateEmailHTML === 'function') {\n html = await collectionConfig.auth.forgotPassword.generateEmailHTML({\n req,\n token,\n user,\n })\n }\n\n let subject = req.t('authentication:resetYourPassword')\n\n if (typeof collectionConfig.auth.forgotPassword.generateEmailSubject === 'function') {\n subject = await collectionConfig.auth.forgotPassword.generateEmailSubject({\n req,\n token,\n user,\n })\n }\n\n await email.sendEmail({\n from: `\"${email.defaultFromName}\" <${email.defaultFromAddress}>`,\n html,\n subject,\n to: user.email,\n })\n }\n\n // /////////////////////////////////////\n // afterForgotPassword - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterForgotPassword.reduce(async (priorHook, hook) => {\n await priorHook\n await hook({ args, collection: args.collection?.config, context: req.context })\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n token = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'forgotPassword',\n result: token,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return token\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["crypto","httpStatus","URL","buildAfterOperation","APIError","commitTransaction","initTransaction","killTransaction","forgotPasswordOperation","incomingArgs","loginWithUsername","collection","config","auth","data","canLoginWithUsername","Boolean","canLoginWithEmail","allowEmailLogin","sanitizedEmail","email","toLowerCase","trim","sanitizedUsername","username","BAD_REQUEST","args","shouldCommit","req","hooks","beforeOperation","reduce","priorHook","hook","context","operation","Promise","resolve","collectionConfig","disableEmail","expiration","payload","token","randomBytes","toString","whereConstraint","equals","user","db","findOne","slug","where","resetPasswordToken","resetPasswordExpiration","Date","now","toISOString","update","id","protocol","url","serverURL","headers","get","html","t","routes","admin","reset","forgotPassword","generateEmailHTML","subject","generateEmailSubject","sendEmail","from","defaultFromName","defaultFromAddress","to","afterForgotPassword","result","error"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,OAAOC,gBAAgB,cAAa;AACpC,SAASC,GAAG,QAAQ,MAAK;AASzB,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AAcpE,OAAO,MAAMC,0BAA0B,OACrCC;IAEA,MAAMC,oBAAoBD,aAAaE,UAAU,CAACC,MAAM,CAACC,IAAI,CAACH,iBAAiB;IAC/E,MAAM,EAAEI,IAAI,EAAE,GAAGL;IAEjB,MAAMM,uBAAuBC,QAAQN;IACrC,MAAMO,oBAAoB,CAACP,qBAAqBA,kBAAkBQ,eAAe;IAEjF,MAAMC,iBACJ,AAACF,qBAAqB,AAACR,CAAAA,aAAaK,IAAI,CAACM,KAAK,IAAI,EAAC,EAAGC,WAAW,GAAGC,IAAI,MAAO;IACjF,MAAMC,oBACJ,cAAcT,QAAQ,OAAOA,MAAMU,aAAa,WAC5CV,KAAKU,QAAQ,CAACH,WAAW,GAAGC,IAAI,KAChC;IAEN,IAAI,CAACH,kBAAkB,CAACI,mBAAmB;QACzC,MAAM,IAAInB,SACR,CAAC,QAAQ,EAAEM,oBAAoB,aAAa,QAAQ,CAAC,CAAC,EACtDT,WAAWwB,WAAW;IAE1B;IAEA,IAAIC,OAAOjB;IAEX,IAAI;QACF,MAAMkB,eAAe,MAAMrB,gBAAgBoB,KAAKE,GAAG;QAEnD,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExC,MAAMF,KAAKf,UAAU,CAACC,MAAM,CAACiB,KAAK,CAACC,eAAe,CAACC,MAAM,CAAC,OAAOC,WAAWC;YAC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AAE,cAAc,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,cAAc,GAAU,KAAK,SAAS,cAAc,gBACjD,SAAS,CAAC,KAAK,CAAC,KAC7B,OAAO,CAAC;IAAE,IAAI,EAAE,sBAAsB,CAAC,KAAK,CAAC,CAAA;CAAE,GAAG,MAAM,CAwS1D,CAAA"}
@@ -133,11 +133,11 @@ export const loginOperation = async (incomingArgs)=>{
133
133
  req,
134
134
  where: whereConstraint
135
135
  });
136
- user.collection = collectionConfig.slug;
137
136
  if (!user || args.collection.config.auth.verify && user._verified === false) {
138
137
  throw new AuthenticationError(req.t, Boolean(canLoginWithUsername && sanitizedUsername));
139
138
  }
140
- if (user && isLocked(new Date(user.lockUntil).getTime())) {
139
+ user.collection = collectionConfig.slug;
140
+ if (isLocked(new Date(user.lockUntil).getTime())) {
141
141
  throw new LockedAuth(req.t);
142
142
  }
143
143
  const authResult = await authenticateLocalStrategy({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/login.ts"],"sourcesContent":["import jwt from 'jsonwebtoken'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n DataFromCollectionSlug,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\nimport type { User } from '../types.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { AuthenticationError, LockedAuth, ValidationError } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport sanitizeInternalFields from '../../utilities/sanitizeInternalFields.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport isLocked from '../isLocked.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type Result = {\n exp?: number\n token?: string\n user?: User\n}\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\nexport const loginOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<{ user: DataFromCollectionSlug<TSlug> } & Result> => {\n let args = incomingArgs\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'login',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess,\n req,\n req: {\n fallbackLocale,\n locale,\n payload,\n payload: { secret },\n },\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Login\n // /////////////////////////////////////\n\n let user\n const { email: unsanitizedEmail, password } = data\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const sanitizedEmail =\n typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n const canLoginWithUsername = Boolean(loginWithUsername)\n const canLoginWithEmail = !loginWithUsername || loginWithUsername.allowEmailLogin\n\n // cannot login with email, did not provide username\n if (!canLoginWithEmail && !sanitizedUsername) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ field: 'username', message: req.i18n.t('validation:required') }],\n })\n }\n\n // cannot login with username, did not provide email\n if (!canLoginWithUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ field: 'email', message: req.i18n.t('validation:required') }],\n })\n }\n\n // can login with either email or username, did not provide either\n if (!sanitizedUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [\n { field: 'email', message: req.i18n.t('validation:required') },\n { field: 'username', message: req.i18n.t('validation:required') },\n ],\n })\n }\n\n // did not provide password for login\n if (typeof password !== 'string' || password.trim() === '') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ field: 'password', message: req.i18n.t('validation:required') }],\n })\n }\n\n let whereConstraint: Where = {}\n const emailConstraint: Where = {\n email: {\n equals: sanitizedEmail,\n },\n }\n const usernameConstraint: Where = {\n username: {\n equals: sanitizedUsername,\n },\n }\n\n if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {\n if (sanitizedUsername) {\n whereConstraint = {\n or: [\n usernameConstraint,\n {\n email: {\n equals: sanitizedUsername,\n },\n },\n ],\n }\n } else {\n whereConstraint = {\n or: [\n emailConstraint,\n {\n username: {\n equals: sanitizedEmail,\n },\n },\n ],\n }\n }\n } else if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = emailConstraint\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = usernameConstraint\n }\n\n user = await payload.db.findOne<any>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })\n user.collection = collectionConfig.slug\n\n if (!user || (args.collection.config.auth.verify && user._verified === false)) {\n throw new AuthenticationError(req.t, Boolean(canLoginWithUsername && sanitizedUsername))\n }\n\n if (user && isLocked(new Date(user.lockUntil).getTime())) {\n throw new LockedAuth(req.t)\n }\n\n const authResult = await authenticateLocalStrategy({ doc: user, password })\n\n user = sanitizeInternalFields(user)\n\n const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0\n\n if (!authResult) {\n if (maxLoginAttemptsEnabled) {\n await incrementLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n throw new AuthenticationError(req.t)\n }\n\n if (maxLoginAttemptsEnabled) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: sanitizedEmail,\n user,\n })\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.beforeLogin.reduce(async (priorHook, hook) => {\n await priorHook\n\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }, Promise.resolve())\n\n const token = jwt.sign(fieldsToSign, secret, {\n expiresIn: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterLogin.reduce(async (priorHook, hook) => {\n await priorHook\n\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 }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n user = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: user,\n draft: undefined,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n req,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n user =\n (await hook({\n collection: args.collection?.config,\n context: req.context,\n doc: user,\n req,\n })) || user\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n user =\n (await hook({\n collection: args.collection?.config,\n context: req.context,\n doc: user,\n req,\n })) || user\n }, Promise.resolve())\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n exp: (jwt.decode(token) as jwt.JwtPayload).exp,\n token,\n user,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["jwt","buildAfterOperation","AuthenticationError","LockedAuth","ValidationError","afterRead","killTransaction","sanitizeInternalFields","getFieldsToSign","isLocked","authenticateLocalStrategy","incrementLoginAttempts","resetLoginAttempts","loginOperation","incomingArgs","args","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","req","operation","Promise","resolve","collectionConfig","data","depth","overrideAccess","fallbackLocale","locale","payload","secret","showHiddenFields","user","email","unsanitizedEmail","password","loginWithUsername","auth","sanitizedEmail","toLowerCase","trim","sanitizedUsername","username","canLoginWithUsername","Boolean","canLoginWithEmail","allowEmailLogin","slug","errors","field","message","i18n","t","whereConstraint","emailConstraint","equals","usernameConstraint","or","db","findOne","where","verify","_verified","Date","lockUntil","getTime","authResult","doc","maxLoginAttemptsEnabled","maxLoginAttempts","fieldsToSign","beforeLogin","token","sign","expiresIn","tokenExpiration","afterLogin","draft","undefined","global","result","exp","decode","error"],"mappings":"AAAA,OAAOA,SAAS,eAAc;AAW9B,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,mBAAmB,EAAEC,UAAU,EAAEC,eAAe,QAAQ,wBAAuB;AACxF,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,OAAOC,4BAA4B,4CAA2C;AAC9E,SAASC,eAAe,QAAQ,wBAAuB;AACvD,OAAOC,cAAc,iBAAgB;AACrC,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SAASC,sBAAsB,QAAQ,gDAA+C;AACtF,SAASC,kBAAkB,QAAQ,4CAA2C;AAiB9E,OAAO,MAAMC,iBAAiB,OAC5BC;IAEA,IAAIC,OAAOD;IAEX,IAAI;QACF,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExC,MAAMC,KAAKC,UAAU,CAACC,MAAM,CAACC,KAAK,CAACC,eAAe,CAACC,MAAM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AENgB,OACE,AAAC,MAAMf,KAAK;gBACVN,YAAYD,KAAKC,UAAU,EAAEC;gBAC7BM,SAASC,IAAID,OAAO;gBACpBiD,KAAKnC;gBACLb;YACF,MAAOa;QACX,GAAGX,QAAQC,OAAO;QAElB,IAAI0D,SAA2D;YAC7DC,KAAK,AAACtF,IAAIuF,MAAM,CAACV,OAA0BS,GAAG;YAC9CT;YACAxC;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCgD,SAAS,MAAMpF,oBAAoB;YACjCc;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BQ,WAAW;YACX4D;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IACT,EAAE,OAAOG,OAAgB;QACvB,MAAMlF,gBAAgBS,KAAKS,GAAG;QAC9B,MAAMgE;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/login.ts"],"sourcesContent":["import jwt from 'jsonwebtoken'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n DataFromCollectionSlug,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\nimport type { User } from '../types.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { AuthenticationError, LockedAuth, ValidationError } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport sanitizeInternalFields from '../../utilities/sanitizeInternalFields.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport isLocked from '../isLocked.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type Result = {\n exp?: number\n token?: string\n user?: User\n}\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\nexport const loginOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<{ user: DataFromCollectionSlug<TSlug> } & Result> => {\n let args = incomingArgs\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'login',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess,\n req,\n req: {\n fallbackLocale,\n locale,\n payload,\n payload: { secret },\n },\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Login\n // /////////////////////////////////////\n\n let user\n const { email: unsanitizedEmail, password } = data\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const sanitizedEmail =\n typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n const canLoginWithUsername = Boolean(loginWithUsername)\n const canLoginWithEmail = !loginWithUsername || loginWithUsername.allowEmailLogin\n\n // cannot login with email, did not provide username\n if (!canLoginWithEmail && !sanitizedUsername) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ field: 'username', message: req.i18n.t('validation:required') }],\n })\n }\n\n // cannot login with username, did not provide email\n if (!canLoginWithUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ field: 'email', message: req.i18n.t('validation:required') }],\n })\n }\n\n // can login with either email or username, did not provide either\n if (!sanitizedUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [\n { field: 'email', message: req.i18n.t('validation:required') },\n { field: 'username', message: req.i18n.t('validation:required') },\n ],\n })\n }\n\n // did not provide password for login\n if (typeof password !== 'string' || password.trim() === '') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ field: 'password', message: req.i18n.t('validation:required') }],\n })\n }\n\n let whereConstraint: Where = {}\n const emailConstraint: Where = {\n email: {\n equals: sanitizedEmail,\n },\n }\n const usernameConstraint: Where = {\n username: {\n equals: sanitizedUsername,\n },\n }\n\n if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {\n if (sanitizedUsername) {\n whereConstraint = {\n or: [\n usernameConstraint,\n {\n email: {\n equals: sanitizedUsername,\n },\n },\n ],\n }\n } else {\n whereConstraint = {\n or: [\n emailConstraint,\n {\n username: {\n equals: sanitizedEmail,\n },\n },\n ],\n }\n }\n } else if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = emailConstraint\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = usernameConstraint\n }\n\n user = await payload.db.findOne<any>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })\n\n if (!user || (args.collection.config.auth.verify && user._verified === false)) {\n throw new AuthenticationError(req.t, Boolean(canLoginWithUsername && sanitizedUsername))\n }\n\n user.collection = collectionConfig.slug\n\n if (isLocked(new Date(user.lockUntil).getTime())) {\n throw new LockedAuth(req.t)\n }\n\n const authResult = await authenticateLocalStrategy({ doc: user, password })\n\n user = sanitizeInternalFields(user)\n\n const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0\n\n if (!authResult) {\n if (maxLoginAttemptsEnabled) {\n await incrementLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n throw new AuthenticationError(req.t)\n }\n\n if (maxLoginAttemptsEnabled) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: sanitizedEmail,\n user,\n })\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.beforeLogin.reduce(async (priorHook, hook) => {\n await priorHook\n\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }, Promise.resolve())\n\n const token = jwt.sign(fieldsToSign, secret, {\n expiresIn: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterLogin.reduce(async (priorHook, hook) => {\n await priorHook\n\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 }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n user = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: user,\n draft: undefined,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n req,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n user =\n (await hook({\n collection: args.collection?.config,\n context: req.context,\n doc: user,\n req,\n })) || user\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n user =\n (await hook({\n collection: args.collection?.config,\n context: req.context,\n doc: user,\n req,\n })) || user\n }, Promise.resolve())\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n exp: (jwt.decode(token) as jwt.JwtPayload).exp,\n token,\n user,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["jwt","buildAfterOperation","AuthenticationError","LockedAuth","ValidationError","afterRead","killTransaction","sanitizeInternalFields","getFieldsToSign","isLocked","authenticateLocalStrategy","incrementLoginAttempts","resetLoginAttempts","loginOperation","incomingArgs","args","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","req","operation","Promise","resolve","collectionConfig","data","depth","overrideAccess","fallbackLocale","locale","payload","secret","showHiddenFields","user","email","unsanitizedEmail","password","loginWithUsername","auth","sanitizedEmail","toLowerCase","trim","sanitizedUsername","username","canLoginWithUsername","Boolean","canLoginWithEmail","allowEmailLogin","slug","errors","field","message","i18n","t","whereConstraint","emailConstraint","equals","usernameConstraint","or","db","findOne","where","verify","_verified","Date","lockUntil","getTime","authResult","doc","maxLoginAttemptsEnabled","maxLoginAttempts","fieldsToSign","beforeLogin","token","sign","expiresIn","tokenExpiration","afterLogin","draft","undefined","global","result","exp","decode","error"],"mappings":"AAAA,OAAOA,SAAS,eAAc;AAW9B,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,mBAAmB,EAAEC,UAAU,EAAEC,eAAe,QAAQ,wBAAuB;AACxF,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,OAAOC,4BAA4B,4CAA2C;AAC9E,SAASC,eAAe,QAAQ,wBAAuB;AACvD,OAAOC,cAAc,iBAAgB;AACrC,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SAASC,sBAAsB,QAAQ,gDAA+C;AACtF,SAASC,kBAAkB,QAAQ,4CAA2C;AAiB9E,OAAO,MAAMC,iBAAiB,OAC5BC;IAEA,IAAIC,OAAOD;IAEX,IAAI;QACF,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExC,MAAMC,KAAKC,UAAU,CAACC,MAAM,CAACC,KAAK,CAACC,eAAe,CAACC,MAAM,CAAC,OAAOC,WAAWC;YAC1E,MAAMD;YAENN,OACE,AAAC,MAAMO,KAAK;gBACVP;gB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AAID,OAAO;gBACpBiD,KAAKnC;gBACLb;YACF,MAAOa;QACX,GAAGX,QAAQC,OAAO;QAElB,IAAI0D,SAA2D;YAC7DC,KAAK,AAACtF,IAAIuF,MAAM,CAACV,OAA0BS,GAAG;YAC9CT;YACAxC;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCgD,SAAS,MAAMpF,oBAAoB;YACjCc;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BQ,WAAW;YACX4D;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IACT,EAAE,OAAOG,OAAgB;QACvB,MAAMlF,gBAAgBS,KAAKS,GAAG;QAC9B,MAAMgE;IACR;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"me.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/me.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAQ,MAAM,aAAa,CAAA;AAEnD,MAAM,MAAM,iBAAiB,GAAG;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,UAAU,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,WAAW,SAAgB,SAAS,KAAG,OAAO,CAAC,iBAAiB,CA6E5E,CAAA"}
1
+ {"version":3,"file":"me.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/me.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAQ,MAAM,aAAa,CAAA;AAEnD,MAAM,MAAM,iBAAiB,GAAG;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,UAAU,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,WAAW,SAAgB,SAAS,KAAG,OAAO,CAAC,iBAAiB,CAgF5E,CAAA"}
@@ -15,7 +15,9 @@ export const meOperation = async (args)=>{
15
15
  req,
16
16
  showHiddenFields: false
17
17
  });
18
- user.collection = collection.config.slug;
18
+ if (user) {
19
+ user.collection = collection.config.slug;
20
+ }
19
21
  if (req.user.collection !== collection.config.slug) {
20
22
  return {
21
23
  user: null
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/me.ts"],"sourcesContent":["import jwt from 'jsonwebtoken'\n\nimport type { Collection } from '../../collections/config/types.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { ClientUser, User } from '../types.js'\n\nexport type MeOperationResult = {\n collection?: string\n exp?: number\n strategy?: string\n token?: string\n user?: ClientUser\n}\n\nexport type Arguments = {\n collection: Collection\n currentToken?: string\n req: PayloadRequest\n}\n\nexport const meOperation = async (args: Arguments): Promise<MeOperationResult> => {\n const { collection, currentToken, req } = args\n\n let result: MeOperationResult = {\n user: null,\n }\n\n if (req.user) {\n const { pathname } = req\n const isGraphQL = pathname === `/api${req.payload.config.routes.graphQL}`\n\n const user = (await req.payload.findByID({\n id: req.user.id,\n collection: collection.config.slug,\n depth: isGraphQL ? 0 : collection.config.auth.depth,\n overrideAccess: false,\n req,\n showHiddenFields: false,\n })) as User\n user.collection = collection.config.slug\n\n if (req.user.collection !== collection.config.slug) {\n return {\n user: null,\n }\n }\n\n // /////////////////////////////////////\n // me hook - Collection\n // /////////////////////////////////////\n\n for (const meHook of collection.config.hooks.me) {\n const hookResult = await meHook({ args, user })\n\n if (hookResult) {\n result.user = hookResult.user\n result.exp = hookResult.exp\n\n break\n }\n }\n\n result.collection = req.user.collection\n result.strategy = req.user._strategy\n\n if (!result.user) {\n result.user = user\n\n if (currentToken) {\n const decoded = jwt.decode(currentToken) as jwt.JwtPayload\n if (decoded) {\n result.exp = decoded.exp\n }\n if (!collection.config.auth.removeTokenFromResponses) {\n result.token = currentToken\n }\n }\n }\n }\n\n // /////////////////////////////////////\n // After Me - Collection\n // /////////////////////////////////////\n\n await collection.config.hooks.afterMe.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: collection?.config,\n context: req.context,\n req,\n response: result,\n })) || result\n }, Promise.resolve())\n\n return result\n}\n"],"names":["jwt","meOperation","args","collection","currentToken","req","result","user","pathname","isGraphQL","payload","config","routes","graphQL","findByID","id","slug","depth","auth","overrideAccess","showHiddenFields","meHook","hooks","me","hookResult","exp","strategy","_strategy","decoded","decode","removeTokenFromResponses","token","afterMe","reduce","priorHook","hook","context","response","Promise","resolve"],"mappings":"AAAA,OAAOA,SAAS,eAAc;AAoB9B,OAAO,MAAMC,cAAc,OAAOC;IAChC,MAAM,EAAEC,UAAU,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGH;IAE1C,IAAII,SAA4B;QAC9BC,MAAM;IACR;IAEA,IAAIF,IAAIE,IAAI,EAAE;QACZ,MAAM,EAAEC,QAAQ,EAAE,GAAGH;QACrB,MAAMI,YAAYD,aAAa,CAAC,IAAI,EAAEH,IAA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wC;IACxC,wBAAwB;IACxB,wCAAwC;IAExC,MAAMD,WAAWQ,MAAM,CAACW,KAAK,CAACU,OAAO,CAACC,MAAM,CAAC,OAAOC,WAAWC;QAC7D,MAAMD;QAEN5B,SACE,AAAC,MAAM6B,KAAK;YACVhC,YAAYA,YAAYQ;YACxByB,SAAS/B,IAAI+B,OAAO;YACpB/B;YACAgC,UAAU/B;QACZ,MAAOA;IACX,GAAGgC,QAAQC,OAAO;IAElB,OAAOjC;AACT,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/me.ts"],"sourcesContent":["import jwt from 'jsonwebtoken'\n\nimport type { Collection } from '../../collections/config/types.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { ClientUser, User } from '../types.js'\n\nexport type MeOperationResult = {\n collection?: string\n exp?: number\n strategy?: string\n token?: string\n user?: ClientUser\n}\n\nexport type Arguments = {\n collection: Collection\n currentToken?: string\n req: PayloadRequest\n}\n\nexport const meOperation = async (args: Arguments): Promise<MeOperationResult> => {\n const { collection, currentToken, req } = args\n\n let result: MeOperationResult = {\n user: null,\n }\n\n if (req.user) {\n const { pathname } = req\n const isGraphQL = pathname === `/api${req.payload.config.routes.graphQL}`\n\n const user = (await req.payload.findByID({\n id: req.user.id,\n collection: collection.config.slug,\n depth: isGraphQL ? 0 : collection.config.auth.depth,\n overrideAccess: false,\n req,\n showHiddenFields: false,\n })) as User\n\n if (user) {\n user.collection = collection.config.slug\n }\n\n if (req.user.collection !== collection.config.slug) {\n return {\n user: null,\n }\n }\n\n // /////////////////////////////////////\n // me hook - Collection\n // /////////////////////////////////////\n\n for (const meHook of collection.config.hooks.me) {\n const hookResult = await meHook({ args, user })\n\n if (hookResult) {\n result.user = hookResult.user\n result.exp = hookResult.exp\n\n break\n }\n }\n\n result.collection = req.user.collection\n result.strategy = req.user._strategy\n\n if (!result.user) {\n result.user = user\n\n if (currentToken) {\n const decoded = jwt.decode(currentToken) as jwt.JwtPayload\n if (decoded) {\n result.exp = decoded.exp\n }\n if (!collection.config.auth.removeTokenFromResponses) {\n result.token = currentToken\n }\n }\n }\n }\n\n // /////////////////////////////////////\n // After Me - Collection\n // /////////////////////////////////////\n\n await collection.config.hooks.afterMe.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: collection?.config,\n context: req.context,\n req,\n response: result,\n })) || result\n }, Promise.resolve())\n\n return result\n}\n"],"names":["jwt","meOperation","args","collection","currentToken","req","result","user","pathname","isGraphQL","payload","config","routes","graphQL","findByID","id","slug","depth","auth","overrideAccess","showHiddenFields","meHook","hooks","me","hookResult","exp","strategy","_strategy","decoded","decode","removeTokenFromResponses","token","afterMe","reduce","priorHook","hook","context","response","Promise","resolve"],"mappings":"AAAA,OAAOA,SAAS,eAAc;AAoB9B,OAAO,MAAMC,cAAc,OAAOC;IAChC,MAAM,EAAEC,UAAU,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGH;IAE1C,IAAII,SAA4B;QAC9BC,MAAM;IACR;IAEA,IAAIF,IAAIE,IAAI,EAAE;QACZ,MAAM,EAAEC,QAAQ,EAAE,GAAGH;QACrB,MAAMI,YAAYD,aAAa,CAAC,IAAI,EAAEH,IAAIK,OAAO,CAACC,MAAM,CAACC,MAAM,CAACC,OAAO,CAAC,CAAC;QAEzE,MAAMN,OAAQ,MAAMF,IAAIK,OAAO,CAACI,QAAQ,CAAC;YACvCC,IAAIV,IAAIE,IAAI,CAACQ,EAAE;YACfZ,YAAYA,WAAWQ,MAAM,CAACK,IAAI;YAClCC,OAAOR,YAAY,IAAIN,WAAWQ,MAAM,CAACO,IAAI,CAACD,KAAK;YACnDE,gBAAgB;YAChBd;YACAe,kBAAkB;QACpB;QAEA,IAAIb,MAAM;YACRA,KAAKJ,UAAU,GAAGA,WAAWQ,MAAM,CAACK,IAAI;QAC1C;QAEA,IAAIX,IAAIE,IAAI,CAACJ,UAAU,KAAKA,WAAWQ,MAAM,CAACK,IAAI,EAAE;YAClD,OAAO;gBACLT,MAAM;YACR;QACF;QAEA,wCAAwC;QACxC,uBAAuB;QACvB,wCAAwC;QAExC,KAAK,MAAMc,UAAUlB,WAAWQ,MAAM,CAACW,KAAK,CAACC,EAAE,CAAE;YAC/C,MAAMC,aAAa,MAAMH,OAAO;gBAAEnB;gBAAMK;YAAK;YAE7C,IAAIiB,YAAY;gBACdlB,OAAOC,IAAI,GAAGiB,WAAWjB,IAAI;gBAC7BD,OAAOmB,GAAG,GAAGD,WAAWC,GAAG;gBAE3B;YACF;QACF;QAEAnB,OAAOH,UAAU,GAAGE,IAAIE,IAAI,CAACJ,UAAU;QACvCG,OAAOoB,QAAQ,GAAGrB,IAAIE,IAAI,CAACoB,SAAS;QAEpC,IAAI,CAACrB,OAAOC,IAAI,EAAE;YAChBD,OAAOC,IAAI,GAAGA;YAEd,IAAIH,cAAc;gBAChB,MAAMwB,UAAU5B,IAAI6B,MAAM,CAACzB;gBAC3B,IAAIwB,SAAS;oBACXtB,OAAOmB,GAAG,GAAGG,QAAQH,GAAG;gBAC1B;gBACA,IAAI,CAACtB,WAAWQ,MAAM,CAACO,IAAI,CAACY,wBAAwB,EAAE;oBACpDxB,OAAOyB,KAAK,GAAG3B;gBACjB;YACF;QACF;IACF;IAEA,wCAAwC;IACxC,wBAAwB;IACxB,wCAAwC;IAExC,MAAMD,WAAWQ,MAAM,CAACW,KAAK,CAACU,OAAO,CAACC,MAAM,CAAC,OAAOC,WAAWC;QAC7D,MAAMD;QAEN5B,SACE,AAAC,MAAM6B,KAAK;YACVhC,YAAYA,YAAYQ;YACxByB,SAAS/B,IAAI+B,OAAO;YACpB/B;YACAgC,UAAU/B;QACZ,MAAOA;IACX,GAAGgC,QAAQC,OAAO;IAElB,OAAOjC;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/refresh.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAuB,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACxF,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AASpE,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,EAAE,MAAM,CAAA;IACX,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,gBAAgB,iBAAwB,SAAS,KAAG,OAAO,CAAC,MAAM,CAmI9E,CAAA"}
1
+ {"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/refresh.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAuB,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACxF,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AASpE,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,EAAE,MAAM,CAAA;IACX,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,gBAAgB,iBAAwB,SAAS,KAAG,OAAO,CAAC,MAAM,CAsI9E,CAAA"}
@@ -38,7 +38,9 @@ export const refreshOperation = async (incomingArgs)=>{
38
38
  depth: isGraphQL ? 0 : args.collection.config.auth.depth,
39
39
  req: args.req
40
40
  });
41
- user.collection = args.req.user.collection;
41
+ if (user) {
42
+ user.collection = args.req.user.collection;
43
+ }
42
44
  let result;
43
45
  // /////////////////////////////////////
44
46
  // refresh hook - Collection
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/refresh.ts"],"sourcesContent":["import jwt from 'jsonwebtoken'\nimport url from 'url'\n\nimport type { BeforeOperationHook, Collection } from '../../collections/config/types.js'\nimport type { Document, PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { Forbidden } from '../../errors/index.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\n\nexport type Result = {\n exp: number\n refreshedToken: string\n setCookie?: boolean\n strategy?: string\n user: Document\n}\n\nexport type Arguments = {\n collection: Collection\n req: PayloadRequest\n}\n\nexport const refreshOperation = async (incomingArgs: Arguments): Promise<Result> => {\n let args = incomingArgs\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(\n async (priorHook: BeforeOperationHook | Promise<void>, hook: BeforeOperationHook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'refresh',\n req: args.req,\n })) || args\n },\n Promise.resolve(),\n )\n\n // /////////////////////////////////////\n // Refresh\n // /////////////////////////////////////\n\n const {\n collection: { config: collectionConfig },\n req,\n req: {\n payload: { config, secret },\n },\n } = args\n\n if (!args.req.user) {\n throw new Forbidden(args.req.t)\n }\n\n const parsedURL = url.parse(args.req.url)\n const isGraphQL = parsedURL.pathname === config.routes.graphQL\n\n const user = await args.req.payload.findByID({\n id: args.req.user.id,\n collection: args.req.user.collection,\n depth: isGraphQL ? 0 : args.collection.config.auth.depth,\n req: args.req,\n })\n user.collection = args.req.user.collection\n\n let result: Result\n\n // /////////////////////////////////////\n // refresh hook - Collection\n // /////////////////////////////////////\n\n for (const refreshHook of args.collection.config.hooks.refresh) {\n const hookResult = await refreshHook({ args, user })\n\n if (hookResult) {\n result = hookResult\n break\n }\n }\n\n if (!result) {\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: user?.email as string,\n user: args?.req?.user,\n })\n\n const refreshedToken = jwt.sign(fieldsToSign, secret, {\n expiresIn: collectionConfig.auth.tokenExpiration,\n })\n\n const exp = (jwt.decode(refreshedToken) as Record<string, unknown>).exp as number\n\n result = {\n exp,\n refreshedToken,\n setCookie: true,\n strategy: args.req.user._strategy,\n user,\n }\n }\n\n // /////////////////////////////////////\n // After Refresh - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRefresh.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n exp: result.exp,\n req: args.req,\n token: result.refreshedToken,\n })) || result\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'refresh',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["jwt","url","buildAfterOperation","Forbidden","commitTransaction","initTransaction","killTransaction","getFieldsToSign","refreshOperation","incomingArgs","args","shouldCommit","req","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","operation","Promise","resolve","collectionConfig","payload","secret","user","t","parsedURL","parse","isGraphQL","pathname","routes","graphQL","findByID","id","depth","auth","result","refreshHook","refresh","hookResult","fieldsToSign","email","refreshedToken","sign","expiresIn","tokenExpiration","exp","decode","setCookie","strategy","_strategy","afterRefresh","token","error"],"mappings":"AAAA,OAAOA,SAAS,eAAc;AAC9B,OAAOC,SAAS,MAAK;AAKrB,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,SAAS,QAAQ,wBAAuB;AACj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9B,wCAAwC;QAExCgB,SAAS,MAAMrC,oBAAoB;YACjCQ;YACAG,YAAYH,KAAKG,UAAU,EAAEC;YAC7BO,WAAW;YACXkB;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,IAAI5B,cAAc;YAChB,MAAMP,kBAAkBQ;QAC1B;QAEA,OAAO2B;IACT,EAAE,OAAOiB,OAAgB;QACvB,MAAMlD,gBAAgBI,KAAKE,GAAG;QAC9B,MAAM4C;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/refresh.ts"],"sourcesContent":["import jwt from 'jsonwebtoken'\nimport url from 'url'\n\nimport type { BeforeOperationHook, Collection } from '../../collections/config/types.js'\nimport type { Document, PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { Forbidden } from '../../errors/index.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\n\nexport type Result = {\n exp: number\n refreshedToken: string\n setCookie?: boolean\n strategy?: string\n user: Document\n}\n\nexport type Arguments = {\n collection: Collection\n req: PayloadRequest\n}\n\nexport const refreshOperation = async (incomingArgs: Arguments): Promise<Result> => {\n let args = incomingArgs\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(\n async (priorHook: BeforeOperationHook | Promise<void>, hook: BeforeOperationHook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'refresh',\n req: args.req,\n })) || args\n },\n Promise.resolve(),\n )\n\n // /////////////////////////////////////\n // Refresh\n // /////////////////////////////////////\n\n const {\n collection: { config: collectionConfig },\n req,\n req: {\n payload: { config, secret },\n },\n } = args\n\n if (!args.req.user) {\n throw new Forbidden(args.req.t)\n }\n\n const parsedURL = url.parse(args.req.url)\n const isGraphQL = parsedURL.pathname === config.routes.graphQL\n\n const user = await args.req.payload.findByID({\n id: args.req.user.id,\n collection: args.req.user.collection,\n depth: isGraphQL ? 0 : args.collection.config.auth.depth,\n req: args.req,\n })\n\n if (user) {\n user.collection = args.req.user.collection\n }\n\n let result: Result\n\n // /////////////////////////////////////\n // refresh hook - Collection\n // /////////////////////////////////////\n\n for (const refreshHook of args.collection.config.hooks.refresh) {\n const hookResult = await refreshHook({ args, user })\n\n if (hookResult) {\n result = hookResult\n break\n }\n }\n\n if (!result) {\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: user?.email as string,\n user: args?.req?.user,\n })\n\n const refreshedToken = jwt.sign(fieldsToSign, secret, {\n expiresIn: collectionConfig.auth.tokenExpiration,\n })\n\n const exp = (jwt.decode(refreshedToken) as Record<string, unknown>).exp as number\n\n result = {\n exp,\n refreshedToken,\n setCookie: true,\n strategy: args.req.user._strategy,\n user,\n }\n }\n\n // /////////////////////////////////////\n // After Refresh - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRefresh.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n exp: result.exp,\n req: args.req,\n token: result.refreshedToken,\n })) || result\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'refresh',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["jwt","url","buildAfterOperation","Forbidden","commitTransaction","initTransaction","killTransaction","getFieldsToSign","refreshOperation","incomingArgs","args","shouldCommit","req","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","operation","Promise","resolve","collectionConfig","payload","secret","user","t","parsedURL","parse","isGraphQL","pathname","routes","graphQL","findByID","id","depth","auth","result","refreshHook","refresh","hookResult","fieldsToSign","email","refreshedToken","sign","expiresIn","tokenExpiration","exp","decode","setCookie","strategy","_strategy","afterRefresh","token","error"],"mappings":"AAAA,OAAOA,SAAS,eAAc;AAC9B,OAAOC,SAAS,MAAK;AAKrB,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,wBAAuB;AAevD,OAAO,MAAMC,mBAAmB,OAAOC;IACrC,IAAIC,OAAOD;IAEX,IAAI;QACF,MAAME,eAAe,MAAMN,gBAAgBK,KAAKE,GAAG;QAEnD,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExC,MAAMF,KAAKG,UAAU,CAACC,MAAM,CAACC,KAAK,CAACC,eAAe,CAACC,MAAM,CACvD,OAAOC,WAAgDC;YACrD,MAAMD;YAENR,OACE,AAAC,MAAMS,KAAK;gBACVT;gBACAG,YAAYH,KAAKG,UAAU,EAAEC;gBAC7BM,SAASV,KAAKE,GAAG,CAACQ,OAAO;gBACzBC,WAAW;gBACXT,KAAKF,KAAKE,GAAG;YACf,MAAOF;QACX,GACAY,QAAQC,OAAO;QAGjB,wCAAwC;QACxC,UAAU;QACV,wCAAwC;QAExC,MAAM,EACJV,YAAY,EAAEC,QAAQU,gBAAgB,EAAE,EACxCZ,GAAG,EACHA,KAAK,EACHa,SAAS,EAAEX,MAAM,EAAEY,MAAM,EAAE,EAC5B,EACF,GAAGhB;QAEJ,IAAI,CAACA,KAAKE,GAAG,CAACe,IAAI,EAAE;YAClB,MAAM,IAAIxB,UAAUO,KAAKE,GAAG,CAACgB,CAAC;QAChC;QAEA,MAAMC,YAAY5B,IAAI6B,KAAK,CAACpB,K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AY,CAACrC,MAAM,CAAC,OAAOC,WAAWC;YACjE,MAAMD;YAENqB,SACE,AAAC,MAAMpB,KAAK;gBACVN,YAAYH,KAAKG,UAAU,EAAEC;gBAC7BM,SAASV,KAAKE,GAAG,CAACQ,OAAO;gBACzB6B,KAAKV,OAAOU,GAAG;gBACfrC,KAAKF,KAAKE,GAAG;gBACb2C,OAAOhB,OAAOM,cAAc;YAC9B,MAAON;QACX,GAAGjB,QAAQC,OAAO;QAElB,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCgB,SAAS,MAAMrC,oBAAoB;YACjCQ;YACAG,YAAYH,KAAKG,UAAU,EAAEC;YAC7BO,WAAW;YACXkB;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,IAAI5B,cAAc;YAChB,MAAMP,kBAAkBQ;QAC1B;QAEA,OAAO2B;IACT,EAAE,OAAOiB,OAAgB;QACvB,MAAMlD,gBAAgBI,KAAKE,GAAG;QAC9B,MAAM4C;IACR;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateTypes.d.ts","sourceRoot":"","sources":["../../src/bin/generateTypes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAKzD,wBAAsB,aAAa,CACjC,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE;IAAE,GAAG,EAAE,OAAO,CAAA;CAAE,GACzB,OAAO,CAAC,IAAI,CAAC,CAkDf"}
1
+ {"version":3,"file":"generateTypes.d.ts","sourceRoot":"","sources":["../../src/bin/generateTypes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAiCzD,wBAAsB,aAAa,CACjC,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE;IAAE,GAAG,EAAE,OAAO,CAAA;CAAE,GACzB,OAAO,CAAC,IAAI,CAAC,CAkGf"}
@@ -2,6 +2,19 @@ import fs from 'fs';
2
2
  import { compile } from 'json-schema-to-typescript';
3
3
  import { configToJSONSchema } from '../utilities/configToJSONSchema.js';
4
4
  import { getLogger } from '../utilities/logger.js';
5
+ function processExternalImports(fileContent, transformFunction) {
6
+ const regex = /'externalImport:([^']+)'/g;
7
+ const processedContent = fileContent.replace(regex, (match, captureGroup)=>{
8
+ const { generics, specifier } = transformFunction(captureGroup);
9
+ if (generics && generics.length > 0) {
10
+ return specifier + '<' + generics.join(',') + '>';
11
+ }
12
+ return specifier;
13
+ });
14
+ return {
15
+ processedContent
16
+ };
17
+ }
5
18
  export async function generateTypes(config, options) {
6
19
  const logger = getLogger('payload', 'sync');
7
20
  const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile;
@@ -12,7 +25,7 @@ export async function generateTypes(config, options) {
12
25
  const jsonSchema = configToJSONSchema(config, config.db.defaultIDType);
13
26
  const declare = `declare module 'payload' {\n export interface GeneratedTypes extends Config {}\n}`;
14
27
  const declareWithTSIgnoreError = `declare module 'payload' {\n // @ts-ignore \n export interface GeneratedTypes extends Config {}\n}`;
15
- let compiled = await compile(jsonSchema, 'Config', {
28
+ const _compiled = await compile(jsonSchema, 'Config', {
16
29
  bannerComment: '/* tslint:disable */\n/* eslint-disable */\n/**\n* This file was automatically generated by Payload.\n* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n* and re-run `payload generate:types` to regenerate this file.\n*/',
17
30
  style: {
18
31
  singleQuote: true
@@ -22,6 +35,44 @@ export async function generateTypes(config, options) {
22
35
  // even if it's not used by another type. Reason: the user might want to use it in their own code.
23
36
  unreachableDefinitions: true
24
37
  });
38
+ /*
39
+ * Process external imports
40
+ */ let importsFound = 0;
41
+ const importStrings = [];
42
+ const specifiers = [];
43
+ const rawImportStrings = [];
44
+ const { processedContent } = processExternalImports(_compiled, (captureGroup)=>{
45
+ const importString = captureGroup.split(':')[0];
46
+ let generics = [];
47
+ if (captureGroup.includes(':')) {
48
+ // Defines generics
49
+ generics = captureGroup.split(':')[1].split(',');
50
+ }
51
+ const importStringSplit = importString.split('#');
52
+ const importPath = importStringSplit[0];
53
+ const specifier = importStringSplit[1];
54
+ if (rawImportStrings.includes(importString)) {
55
+ const safeSpecifier = specifier + '_' + importsFound;
56
+ return {
57
+ generics,
58
+ specifier: safeSpecifier
59
+ };
60
+ }
61
+ importsFound++;
62
+ rawImportStrings.push(importString);
63
+ const safeSpecifier = specifier + '_' + importsFound;
64
+ const fullImportString = `import { ${specifier} as ${safeSpecifier} } from '${importPath}'`;
65
+ specifiers.push(safeSpecifier);
66
+ importStrings.push(fullImportString);
67
+ return {
68
+ generics,
69
+ specifier: safeSpecifier
70
+ };
71
+ });
72
+ /*
73
+ * Done processing external imports
74
+ */ let compiled = processedContent;
75
+ compiled = importStrings.join('\n') + '\n\n' + compiled;
25
76
  if (config.typescript.declare !== false) {
26
77
  if (config.typescript.declare?.ignoreTSError) {
27
78
  compiled += `\n\n${declareWithTSIgnoreError}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/generateTypes.ts"],"sourcesContent":["import fs from 'fs'\nimport { compile } from 'json-schema-to-typescript'\n\nimport type { SanitizedConfig } from '../config/types.js'\n\nimport { configToJSONSchema } from '../utilities/configToJSONSchema.js'\nimport { getLogger } from '../utilities/logger.js'\n\nexport async function generateTypes(\n config: SanitizedConfig,\n options?: { log: boolean },\n): Promise<void> {\n const logger = getLogger('payload', 'sync')\n const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile\n\n const shouldLog = options?.log ?? true\n\n if (shouldLog) {\n logger.info('Compiling TS types for Collections and Globals...')\n }\n\n const jsonSchema = configToJSONSchema(config, config.db.defaultIDType)\n\n const declare = `declare module 'payload' {\\n export interface GeneratedTypes extends Config {}\\n}`\n const declareWithTSIgnoreError = `declare module 'payload' {\\n // @ts-ignore \\n export interface GeneratedTypes extends Config {}\\n}`\n\n let compiled = await compile(jsonSchema, 'Config', {\n bannerComment:\n '/* tslint:disable */\\n/* eslint-disable */\\n/**\\n* This file was automatically generated by Payload.\\n* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\\n* and re-run `payload generate:types` to regenerate this file.\\n*/',\n style: {\n singleQuote: true,\n },\n // Generates code for $defs that aren't referenced by the schema. Reason:\n // If a field defines an interfaceName, it should be included in the generated types\n // even if it's not used by another type. Reason: the user might want to use it in their own code.\n unreachableDefinitions: true,\n })\n\n if (config.typescript.declare !== false) {\n if (config.typescript.declare?.ignoreTSError) {\n compiled += `\\n\\n${declareWithTSIgnoreError}`\n } else {\n compiled += `\\n\\n${declare}`\n }\n }\n\n // Diff the compiled types against the existing types file\n try {\n const existingTypes = fs.readFileSync(outputFile, 'utf-8')\n\n if (compiled === existingTypes) {\n return\n }\n } catch (_) {\n // swallow err\n }\n\n fs.writeFileSync(outputFile, compiled)\n if (shouldLog) {\n logger.info(`Types written to ${outputFile}`)\n }\n}\n"],"names":["fs","compile","configToJSONSchema","getLogger","generateTypes","config","options","logger","outputFile","process","env","PAYLOAD_TS_OUTPUT_PATH","typescript","shouldLog","log","info","jsonSchema","db","defaultIDType","declare","declareWithTSIgnoreError","compiled","bannerComment","style","singleQuote","unreachableDefinitions","ignoreTSError","existingTypes","readFileSync","_","writeFileSync"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,SAASC,OAAO,QAAQ,4BAA2B;AAInD,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,SAAS,QAAQ,yBAAwB;AAElD,OAAO,eAAeC,cACpBC,MAAuB,EACvBC,OAA0B;IAE1B,MAAMC,SAASJ,UAAU,WAAW;IACpC,MAAMK,aAAaC,QAAQC,GAAG,CAACC,sBAAsB,IAAIN,OAAOO,UAAU,CAACJ,UAAU;IAErF,MAAMK,YAAYP,SAASQ,OAAO;IAElC,IAAID,WAAW;QACbN,OAAOQ,IAAI,CAAC;IACd;IAEA,MAAMC,aAAad,mBAAmBG,QAAQA,OAAOY,EAAE,CAACC,aAAa;IAErE,MAAMC,UAAU,CAAC,kFAAkF,CAAC;IACpG,MAAMC,2BAA2B,CAAC,oGAAoG,CAAC;IAEvI,IAAIC,WAAW,MAAMpB,QAAQe,YAAY,UAAU;QACjDM,eACE;QACFC,OAAO;YACLC,aAAa;QACf;QACA,yEAAyE;QACzE,oFAAoF;QACpF,kGAAkG;QAClGC,wBAAwB;IAC1B;IAEA,IAAIpB,OAAOO,UAAU,CAACO,OAAO,KAAK,OAAO;QACvC,IAAId,OAAOO,UAAU,CAACO,OAAO,EAAEO,eAAe;YAC5CL,YAAY,CAAC,IAAI,EAAED,yBAAyB,CAAC;QAC/C,OAAO;YACLC,YAAY,CAAC,IAAI,EAAEF,QAAQ,CAAC;QAC9B;IACF;IAEA,0DAA0D;IAC1D,IAAI;QACF,MAAMQ,gBAAgB3B,GAAG4B,YAAY,CAACpB,YAAY;QAElD,IAAIa,aAAaM,eAAe;YAC9B;QACF;IACF,EAAE,OAAOE,GAAG;IACV,cAAc;IAChB;IAEA7B,GAAG8B,aAAa,CAACtB,YAAYa;IAC7B,IAAIR,WAAW;QACbN,OAAOQ,IAAI,CAAC,CAAC,iBAAiB,EAAEP,WAAW,CAAC;IAC9C;AACF"}
1
+ {"version":3,"sources":["../../src/bin/generateTypes.ts"],"sourcesContent":["import fs from 'fs'\nimport { compile } from 'json-schema-to-typescript'\n\nimport type { SanitizedConfig } from '../config/types.js'\n\nimport { configToJSONSchema } from '../utilities/configToJSONSchema.js'\nimport { getLogger } from '../utilities/logger.js'\n\ntype TransformFunction = (input: string) => {\n generics?: string[]\n specifier: string\n}\n\ninterface ProcessResult {\n processedContent: string\n}\n\nfunction processExternalImports(\n fileContent: string,\n transformFunction: TransformFunction,\n): ProcessResult {\n const regex = /'externalImport:([^']+)'/g\n\n const processedContent = fileContent.replace(regex, (match: string, captureGroup: string) => {\n const { generics, specifier } = transformFunction(captureGroup)\n if (generics && generics.length > 0) {\n return specifier + '<' + generics.join(',') + '>'\n }\n return specifier\n })\n\n return {\n processedContent,\n }\n}\n\nexport async function generateTypes(\n config: SanitizedConfig,\n options?: { log: boolean },\n): Promise<void> {\n const logger = getLogger('payload', 'sync')\n const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile\n\n const shouldLog = options?.log ?? true\n\n if (shouldLog) {\n logger.info('Compiling TS types for Collections and Globals...')\n }\n\n const jsonSchema = configToJSONSchema(config, config.db.defaultIDType)\n\n const declare = `declare module 'payload' {\\n export interface GeneratedTypes extends Config {}\\n}`\n const declareWithTSIgnoreError = `declare module 'payload' {\\n // @ts-ignore \\n export interface GeneratedTypes extends Config {}\\n}`\n\n const _compiled = await compile(jsonSchema, 'Config', {\n bannerComment:\n '/* tslint:disable */\\n/* eslint-disable */\\n/**\\n* This file was automatically generated by Payload.\\n* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\\n* and re-run `payload generate:types` to regenerate this file.\\n*/',\n style: {\n singleQuote: true,\n },\n // Generates code for $defs that aren't referenced by the schema. Reason:\n // If a field defines an interfaceName, it should be included in the generated types\n // even if it's not used by another type. Reason: the user might want to use it in their own code.\n unreachableDefinitions: true,\n })\n\n /*\n * Process external imports\n */\n let importsFound = 0\n const importStrings: string[] = []\n const specifiers: string[] = []\n const rawImportStrings: string[] = []\n\n const { processedContent } = processExternalImports(_compiled, (captureGroup) => {\n const importString = captureGroup.split(':')[0]\n let generics: string[] = []\n if (captureGroup.includes(':')) {\n // Defines generics\n generics = captureGroup.split(':')[1].split(',')\n }\n\n const importStringSplit = importString.split('#')\n\n const importPath = importStringSplit[0]\n const specifier = importStringSplit[1]\n\n if (rawImportStrings.includes(importString)) {\n const safeSpecifier = specifier + '_' + importsFound\n return {\n generics,\n specifier: safeSpecifier,\n }\n }\n importsFound++\n rawImportStrings.push(importString)\n const safeSpecifier = specifier + '_' + importsFound\n const fullImportString = `import { ${specifier} as ${safeSpecifier} } from '${importPath}'`\n specifiers.push(safeSpecifier)\n\n importStrings.push(fullImportString)\n return {\n generics,\n specifier: safeSpecifier,\n }\n })\n\n /*\n * Done processing external imports\n */\n\n let compiled = processedContent\n compiled = importStrings.join('\\n') + '\\n\\n' + compiled\n\n if (config.typescript.declare !== false) {\n if (config.typescript.declare?.ignoreTSError) {\n compiled += `\\n\\n${declareWithTSIgnoreError}`\n } else {\n compiled += `\\n\\n${declare}`\n }\n }\n\n // Diff the compiled types against the existing types file\n try {\n const existingTypes = fs.readFileSync(outputFile, 'utf-8')\n\n if (compiled === existingTypes) {\n return\n }\n } catch (_) {\n // swallow err\n }\n\n fs.writeFileSync(outputFile, compiled)\n if (shouldLog) {\n logger.info(`Types written to ${outputFile}`)\n }\n}\n"],"names":["fs","compile","configToJSONSchema","getLogger","processExternalImports","fileContent","transformFunction","regex","processedContent","replace","match","captureGroup","generics","specifier","length","join","generateTypes","config","options","logger","outputFile","process","env","PAYLOAD_TS_OUTPUT_PATH","typescript","shouldLog","log","info","jsonSchema","db","defaultIDType","declare","declareWithTSIgnoreError","_compiled","bannerComment","style","singleQuote","unreachableDefinitions","importsFound","importStrings","specifiers","rawImportStrings","importString","split","includes","importStringSplit","importPath","safeSpecifier","push","fullImportString","compiled","ignoreTSError","existingTypes","readFileSync","_","writeFileSync"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,SAASC,OAAO,QAAQ,4BAA2B;AAInD,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,SAAS,QAAQ,yBAAwB;AAWlD,SAASC,uBACPC,WAAmB,EACnBC,iBAAoC;IAEpC,MAAMC,QAAQ;IAEd,MAAMC,mBAAmBH,YAAYI,OAAO,CAACF,OAAO,CAACG,OAAeC;QAClE,MAAM,EAAEC,QAAQ,EAAEC,SAAS,EAAE,GAAGP,kBAAkBK;QAClD,IAAIC,YAAYA,SAASE,MAAM,GAAG,GAAG;YACnC,OAAOD,YAAY,MAAMD,SAASG,IAAI,CAAC,OAAO;QAChD;QACA,OAAOF;IACT;IAEA,OAAO;QACLL;IACF;AACF;AAEA,OAAO,eAAeQ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tB,MAAMK,gBAAgBlC,YAAY,MAAMyB;QACxC,MAAMW,mBAAmB,CAAC,SAAS,EAAEpC,UAAU,IAAI,EAAEkC,cAAc,SAAS,EAAED,WAAW,CAAC,CAAC;QAC3FN,WAAWQ,IAAI,CAACD;QAEhBR,cAAcS,IAAI,CAACC;QACnB,OAAO;YACLrC;YACAC,WAAWkC;QACb;IACF;IAEA;;GAEC,GAED,IAAIG,WAAW1C;IACf0C,WAAWX,cAAcxB,IAAI,CAAC,QAAQ,SAASmC;IAE/C,IAAIjC,OAAOO,UAAU,CAACO,OAAO,KAAK,OAAO;QACvC,IAAId,OAAOO,UAAU,CAACO,OAAO,EAAEoB,eAAe;YAC5CD,YAAY,CAAC,IAAI,EAAElB,yBAAyB,CAAC;QAC/C,OAAO;YACLkB,YAAY,CAAC,IAAI,EAAEnB,QAAQ,CAAC;QAC9B;IACF;IAEA,0DAA0D;IAC1D,IAAI;QACF,MAAMqB,gBAAgBpD,GAAGqD,YAAY,CAACjC,YAAY;QAElD,IAAI8B,aAAaE,eAAe;YAC9B;QACF;IACF,EAAE,OAAOE,GAAG;IACV,cAAc;IAChB;IAEAtD,GAAGuD,aAAa,CAACnC,YAAY8B;IAC7B,IAAIzB,WAAW;QACbN,OAAOQ,IAAI,CAAC,CAAC,iBAAiB,EAAEP,WAAW,CAAC;IAC9C;AACF"}
@@ -1,2 +1,2 @@
1
- export declare const bin: () => Promise<void>;
1
+ export declare const bin: () => Promise<void | import("../queues/operations/runAllJobs/index.js").RunAllJobsResult>;
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bin/index.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,GAAG,qBA0Ef,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bin/index.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,GAAG,2FAkGf,CAAA"}
package/dist/bin/index.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { Cron } from 'croner';
1
2
  import minimist from 'minimist';
2
3
  import { pathToFileURL } from 'node:url';
3
4
  import path from 'path';
4
5
  import { findConfig } from '../config/find.js';
6
+ import { getPayload } from '../index.js';
5
7
  import { generateImportMap } from './generateImportMap/index.js';
6
8
  import { generateTypes } from './generateTypes.js';
7
9
  import { info } from './info.js';
@@ -70,6 +72,29 @@ export const bin = async ()=>{
70
72
  if (script === 'generate:importmap') {
71
73
  return generateImportMap(config);
72
74
  }
75
+ if (script === 'jobs:run') {
76
+ const payload = await getPayload({
77
+ config
78
+ });
79
+ const limit = args.limit ? parseInt(args.limit, 10) : undefined;
80
+ const queue = args.queue ? args.queue : undefined;
81
+ if (args.cron) {
82
+ Cron(args.cron, async ()=>{
83
+ await payload.jobs.run({
84
+ limit,
85
+ queue
86
+ });
87
+ });
88
+ process.stdin.resume() // Keep the process alive
89
+ ;
90
+ return;
91
+ } else {
92
+ return await payload.jobs.run({
93
+ limit,
94
+ queue
95
+ });
96
+ }
97
+ }
73
98
  console.error(`Unknown script: "${script}".`);
74
99
  process.exit(1);
75
100
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/index.ts"],"sourcesContent":["import minimist from 'minimist'\nimport { pathToFileURL } from 'node:url'\nimport path from 'path'\n\nimport type { BinScript } from '../config/types.js'\n\nimport { findConfig } from '../config/find.js'\nimport { generateImportMap } from './generateImportMap/index.js'\nimport { generateTypes } from './generateTypes.js'\nimport { info } from './info.js'\nimport { loadEnv } from './loadEnv.js'\nimport { migrate } from './migrate.js'\n\nexport const bin = async () => {\n loadEnv()\n\n const args = minimist(process.argv.slice(2))\n const script = (typeof args._[0] === 'string' ? args._[0] : '').toLowerCase()\n\n if (script === 'info') {\n await info()\n return\n }\n\n if (script === 'run') {\n const scriptPath = args._[1]\n if (!scriptPath) {\n console.error('Please provide a script path to run.')\n process.exit(1)\n }\n\n const absoluteScriptPath = path.resolve(process.cwd(), scriptPath)\n\n // Modify process.argv to remove 'run' and the script path\n const originalArgv = process.argv\n process.argv = [process.argv[0], process.argv[1], ...args._.slice(2)]\n\n try {\n await import(pathToFileURL(absoluteScriptPath).toString())\n } catch (error) {\n console.error(`Error running script: ${absoluteScriptPath}`)\n console.error(error)\n process.exit(1)\n } finally {\n // Restore original process.argv\n process.argv = originalArgv\n }\n return\n }\n\n const configPath = findConfig()\n const configPromise = await import(pathToFileURL(configPath).toString())\n let config = await configPromise\n if (config.default) {\n config = await config.default\n }\n\n const userBinScript = Array.isArray(config.bin)\n ? config.bin.find(({ key }) => key === script)\n : false\n\n if (userBinScript) {\n try {\n const script: BinScript = await import(pathToFileURL(userBinScript.scriptPath).toString())\n await script(config)\n } catch (err) {\n console.log(`Could not find associated bin script for the ${userBinScript.key} command`)\n console.error(err)\n }\n\n return\n }\n\n if (script.startsWith('migrate')) {\n return migrate({ config, parsedArgs: args }).then(() => process.exit(0))\n }\n\n if (script === 'generate:types') {\n return generateTypes(config)\n }\n\n if (script === 'generate:importmap') {\n return generateImportMap(config)\n }\n\n console.error(`Unknown script: \"${script}\".`)\n process.exit(1)\n}\n"],"names":["minimist","pathToFileURL","path","findConfig","generateImportMap","generateTypes","info","loadEnv","migrate","bin","args","process","argv","slice","script","_","toLowerCase","scriptPath","console","error","exit","absoluteScriptPath","resolve","cwd","originalArgv","toString","configPath","configPromise","config","default","userBinScript","Array","isArray","find","key","err","log","startsWith","parsedArgs","then"],"mappings":"AAAA,OAAOA,cAAc,WAAU;AAC/B,SAASC,aAAa,QAAQ,WAAU;AACxC,OAAOC,UAAU,OAAM;AAIvB,SAASC,UAAU,QAAQ,oBAAmB;AAC9C,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,OAAO,QAAQ,eAAc;AAEtC,OAAO,MAAMC,MAAM;IACjBF;IAEA,MAAMG,OAAOV,SAASW,Q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;QACjB,IAAI;YACF,MAAMhB,SAAoB,MAAM,MAAM,CAACb,cAAc6B,cAAcb,UAAU,EAAEQ,QAAQ;YACvF,MAAMX,OAAOc;QACf,EAAE,OAAOO,KAAK;YACZjB,QAAQkB,GAAG,CAAC,CAAC,6CAA6C,EAAEN,cAAcI,GAAG,CAAC,QAAQ,CAAC;YACvFhB,QAAQC,KAAK,CAACgB;QAChB;QAEA;IACF;IAEA,IAAIrB,OAAOuB,UAAU,CAAC,YAAY;QAChC,OAAO7B,QAAQ;YAAEoB;YAAQU,YAAY5B;QAAK,GAAG6B,IAAI,CAAC,IAAM5B,QAAQS,IAAI,CAAC;IACvE;IAEA,IAAIN,WAAW,kBAAkB;QAC/B,OAAOT,cAAcuB;IACvB;IAEA,IAAId,WAAW,sBAAsB;QACnC,OAAOV,kBAAkBwB;IAC3B;IAEAV,QAAQC,KAAK,CAAC,CAAC,iBAAiB,EAAEL,OAAO,EAAE,CAAC;IAC5CH,QAAQS,IAAI,CAAC;AACf,EAAC"}
1
+ {"version":3,"sources":["../../src/bin/index.ts"],"sourcesContent":["import { Cron } from 'croner'\nimport minimist from 'minimist'\nimport { pathToFileURL } from 'node:url'\nimport path from 'path'\n\nimport type { BinScript } from '../config/types.js'\n\nimport { findConfig } from '../config/find.js'\nimport { getPayload } from '../index.js'\nimport { generateImportMap } from './generateImportMap/index.js'\nimport { generateTypes } from './generateTypes.js'\nimport { info } from './info.js'\nimport { loadEnv } from './loadEnv.js'\nimport { migrate } from './migrate.js'\n\nexport const bin = async () => {\n loadEnv()\n\n const args = minimist(process.argv.slice(2))\n const script = (typeof args._[0] === 'string' ? args._[0] : '').toLowerCase()\n\n if (script === 'info') {\n await info()\n return\n }\n\n if (script === 'run') {\n const scriptPath = args._[1]\n if (!scriptPath) {\n console.error('Please provide a script path to run.')\n process.exit(1)\n }\n\n const absoluteScriptPath = path.resolve(process.cwd(), scriptPath)\n\n // Modify process.argv to remove 'run' and the script path\n const originalArgv = process.argv\n process.argv = [process.argv[0], process.argv[1], ...args._.slice(2)]\n\n try {\n await import(pathToFileURL(absoluteScriptPath).toString())\n } catch (error) {\n console.error(`Error running script: ${absoluteScriptPath}`)\n console.error(error)\n process.exit(1)\n } finally {\n // Restore original process.argv\n process.argv = originalArgv\n }\n return\n }\n\n const configPath = findConfig()\n const configPromise = await import(pathToFileURL(configPath).toString())\n let config = await configPromise\n if (config.default) {\n config = await config.default\n }\n\n const userBinScript = Array.isArray(config.bin)\n ? config.bin.find(({ key }) => key === script)\n : false\n\n if (userBinScript) {\n try {\n const script: BinScript = await import(pathToFileURL(userBinScript.scriptPath).toString())\n await script(config)\n } catch (err) {\n console.log(`Could not find associated bin script for the ${userBinScript.key} command`)\n console.error(err)\n }\n\n return\n }\n\n if (script.startsWith('migrate')) {\n return migrate({ config, parsedArgs: args }).then(() => process.exit(0))\n }\n\n if (script === 'generate:types') {\n return generateTypes(config)\n }\n\n if (script === 'generate:importmap') {\n return generateImportMap(config)\n }\n\n if (script === 'jobs:run') {\n const payload = await getPayload({ config })\n const limit = args.limit ? parseInt(args.limit, 10) : undefined\n const queue = args.queue ? args.queue : undefined\n\n if (args.cron) {\n Cron(args.cron, async () => {\n await payload.jobs.run({\n limit,\n queue,\n })\n })\n\n process.stdin.resume() // Keep the process alive\n\n return\n } else {\n return await payload.jobs.run({\n limit,\n queue,\n })\n }\n }\n\n console.error(`Unknown script: \"${script}\".`)\n process.exit(1)\n}\n"],"names":["Cron","minimist","pathToFileURL","path","findConfig","getPayload","generateImportMap","generateTypes","info","loadEnv","migrate","bin","args","process","argv","slice","script","_","toLowerCase","scriptPath","console","error","exit","absoluteScriptPath","resolve","cwd","originalArgv","toString","configPath","configPromise","config","default","userBinScript","Array","isArray","find","key","err","log","startsWith","parsedArgs","then","payload","limit","parseInt","undefined","queue","cron","jobs","run","stdin","resume"],"mappings":"AAAA,SAASA,IAAI,QAAQ,SAAQ;AAC7B,OAAOC,cAAc,WAAU;AAC/B,SAASC,aAAa,QAAQ,WAAU;A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GAAG,yBAAyB;;YAEhD;QACF,OAAO;YACL,OAAO,MAAMT,QAAQM,IAAI,CAACC,GAAG,CAAC;gBAC5BN;gBACAG;YACF;QACF;IACF;IAEA1B,QAAQC,KAAK,CAAC,CAAC,iBAAiB,EAAEL,OAAO,EAAE,CAAC;IAC5CH,QAAQS,IAAI,CAAC;AACf,EAAC"}
@@ -4,7 +4,7 @@ import type { CustomPreviewButton, CustomPublishButton, CustomSaveButton, Custom
4
4
  import type { Arguments as MeArguments } from '../../auth/operations/me.js';
5
5
  import type { Arguments as RefreshArguments, Result as RefreshResult } from '../../auth/operations/refresh.js';
6
6
  import type { Auth, ClientUser, IncomingAuthType } from '../../auth/types.js';
7
- import type { Access, CustomComponent, EditConfig, Endpoint, EntityDescription, EntityDescriptionComponent, GeneratePreviewURL, LabelFunction, LivePreviewConfig, MetaConfig, PayloadComponent, StaticLabel } from '../../config/types.js';
7
+ import type { Access, AfterErrorHookArgs, AfterErrorResult, CustomComponent, EditConfig, Endpoint, EntityDescription, EntityDescriptionComponent, GeneratePreviewURL, LabelFunction, LivePreviewConfig, MetaConfig, PayloadComponent, StaticLabel } from '../../config/types.js';
8
8
  import type { DBIdentifierName } from '../../database/types.js';
9
9
  import type { Field, JoinField } from '../../fields/config/types.js';
10
10
  import type { CollectionSlug, JsonObject, TypedAuthOperations, TypedCollection } from '../../index.js';
@@ -112,12 +112,6 @@ export type AfterDeleteHook<T extends TypeWithID = any> = (args: {
112
112
  req: PayloadRequest;
113
113
  }) => any;
114
114
  export type AfterOperationHook<TOperationGeneric extends CollectionSlug = string> = (arg: AfterOperationArg<TOperationGeneric>) => Awaited<ReturnType<AfterOperationMap<TOperationGeneric>[keyof AfterOperationMap<TOperationGeneric>]>> | Promise<Awaited<ReturnType<AfterOperationMap<TOperationGeneric>[keyof AfterOperationMap<TOperationGeneric>]>>>;
115
- export type AfterErrorHook = (err: Error, res: unknown, context: RequestContext,
116
- /** The collection which this hook is being run on. This is null if the AfterError hook was be added to the payload-wide config */
117
- collection: null | SanitizedCollectionConfig) => {
118
- response: any;
119
- status: number;
120
- } | void;
121
115
  export type BeforeLoginHook<T extends TypeWithID = any> = (args: {
122
116
  /** The collection which this hook is being run on */
123
117
  collection: SanitizedCollectionConfig;
@@ -168,6 +162,9 @@ export type AfterRefreshHook<T extends TypeWithID = any> = (args: {
168
162
  req: PayloadRequest;
169
163
  token: string;
170
164
  }) => any;
165
+ export type AfterErrorHook = (args: {
166
+ collection: SanitizedCollectionConfig;
167
+ } & AfterErrorHookArgs) => AfterErrorResult | Promise<AfterErrorResult>;
171
168
  export type AfterForgotPasswordHook = (args: {
172
169
  args?: any;
173
170
  /** The collection which this hook is being run on */
@@ -333,7 +330,7 @@ export type CollectionConfig<TSlug extends CollectionSlug = any> = {
333
330
  hooks?: {
334
331
  afterChange?: AfterChangeHook[];
335
332
  afterDelete?: AfterDeleteHook[];
336
- afterError?: AfterErrorHook;
333
+ afterError?: AfterErrorHook[];
337
334
  afterForgotPassword?: AfterForgotPasswordHook[];
338
335
  afterLogin?: AfterLoginHook[];
339
336
  afterLogout?: AfterLogoutHook[];