@payloadcms/plugin-stripe 3.89.0-internal.95c9cba → 3.90.0

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 (43) hide show
  1. package/dist/admin.d.ts.map +1 -1
  2. package/dist/admin.js +4 -2
  3. package/dist/admin.js.map +1 -1
  4. package/dist/exports/types.d.ts +1 -1
  5. package/dist/exports/types.d.ts.map +1 -1
  6. package/dist/exports/types.js.map +1 -1
  7. package/dist/fields/getFields.d.ts.map +1 -1
  8. package/dist/fields/getFields.js +8 -0
  9. package/dist/fields/getFields.js.map +1 -1
  10. package/dist/hooks/createNewInStripe.d.ts.map +1 -1
  11. package/dist/hooks/createNewInStripe.js +6 -7
  12. package/dist/hooks/createNewInStripe.js.map +1 -1
  13. package/dist/hooks/syncExistingWithStripe.d.ts.map +1 -1
  14. package/dist/hooks/syncExistingWithStripe.js +6 -7
  15. package/dist/hooks/syncExistingWithStripe.js.map +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +5 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.spec.js +115 -0
  20. package/dist/index.spec.js.map +1 -0
  21. package/dist/routes/rest.d.ts +3 -3
  22. package/dist/routes/rest.d.ts.map +1 -1
  23. package/dist/routes/rest.js +110 -27
  24. package/dist/routes/rest.js.map +1 -1
  25. package/dist/routes/rest.spec.js +282 -0
  26. package/dist/routes/rest.spec.js.map +1 -0
  27. package/dist/types.d.ts +10 -3
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/types.js.map +1 -1
  30. package/dist/utilities/deepen.d.ts +6 -0
  31. package/dist/utilities/deepen.d.ts.map +1 -1
  32. package/dist/utilities/deepen.js +33 -3
  33. package/dist/utilities/deepen.js.map +1 -1
  34. package/dist/utilities/deepen.spec.js +110 -0
  35. package/dist/utilities/deepen.spec.js.map +1 -0
  36. package/dist/utilities/sanitizeStripeRESTConfig.d.ts +5 -0
  37. package/dist/utilities/sanitizeStripeRESTConfig.d.ts.map +1 -0
  38. package/dist/utilities/sanitizeStripeRESTConfig.js +25 -0
  39. package/dist/utilities/sanitizeStripeRESTConfig.js.map +1 -0
  40. package/dist/webhooks/handleCreatedOrUpdated.d.ts.map +1 -1
  41. package/dist/webhooks/handleCreatedOrUpdated.js +6 -6
  42. package/dist/webhooks/handleCreatedOrUpdated.js.map +1 -1
  43. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"admin.d.ts","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAIjF,eAAO,MAAM,YAAY,yBACA,kBAAkB,cAChC,MAAM,KAAG,MAmCjB,CAAA"}
1
+ {"version":3,"file":"admin.d.ts","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAKjF,eAAO,MAAM,YAAY,yBACA,kBAAkB,cAChC,MAAM,KAAG,MAkCjB,CAAA"}
package/dist/admin.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { getFields } from './fields/getFields.js';
2
+ import { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js';
2
3
  export const stripePlugin = (incomingPluginConfig)=>(config)=>{
3
4
  const { collections } = config;
4
5
  // set config defaults here
5
6
  const pluginConfig = {
6
7
  ...incomingPluginConfig,
7
- // TODO: in the next major version, default this to `false`
8
- rest: incomingPluginConfig?.rest ?? true,
8
+ rest: sanitizeStripeRESTConfig({
9
+ rest: incomingPluginConfig?.rest
10
+ }),
9
11
  sync: incomingPluginConfig?.sync || []
10
12
  };
11
13
  // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key
package/dist/admin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/admin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\n\nexport const stripePlugin =\n (incomingPluginConfig: StripePluginConfig) =>\n (config: Config): Config => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingPluginConfig,\n // TODO: in the next major version, default this to `false`\n rest: incomingPluginConfig?.rest ?? true,\n sync: incomingPluginConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n return {\n ...config,\n collections: collections?.map((collection) => {\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (syncConfig) {\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n return {\n ...collection,\n fields,\n }\n }\n\n return collection\n }),\n }\n }\n"],"names":["getFields","stripePlugin","incomingPluginConfig","config","collections","pluginConfig","rest","sync","map","collection","syncConfig","find","slug","fields"],"mappings":"AAIA,SAASA,SAAS,QAAQ,wBAAuB;AAEjD,OAAO,MAAMC,eACX,CAACC,uBACD,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,2BAA2B;QAC3B,MAAME,eAA4C;YAChD,GAAGH,oBAAoB;YACvB,2DAA2D;YAC3DI,MAAMJ,sBAAsBI,QAAQ;YACpCC,MAAML,sBAAsBK,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,OAAO;YACL,GAAGJ,MAAM;YACTC,aAAaA,aAAaI,IAAI,CAACC;gBAC7B,MAAMC,aAAaL,aAAaE,IAAI,EAAEI,KAAK,CAACJ,OAASA,KAAKE,UAAU,KAAKA,WAAWG,IAAI;gBAExF,IAAIF,YAAY;oBACd,MAAMG,SAASb,UAAU;wBACvBS;wBACAJ;wBACAK;oBACF;oBACA,OAAO;wBACL,GAAGD,UAAU;wBACbI;oBACF;gBACF;gBAEA,OAAOJ;YACT;QACF;IACF,EAAC"}
1
+ {"version":3,"sources":["../src/admin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\nimport { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js'\n\nexport const stripePlugin =\n (incomingPluginConfig: StripePluginConfig) =>\n (config: Config): Config => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingPluginConfig,\n rest: sanitizeStripeRESTConfig({ rest: incomingPluginConfig?.rest }),\n sync: incomingPluginConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n return {\n ...config,\n collections: collections?.map((collection) => {\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (syncConfig) {\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n return {\n ...collection,\n fields,\n }\n }\n\n return collection\n }),\n }\n }\n"],"names":["getFields","sanitizeStripeRESTConfig","stripePlugin","incomingPluginConfig","config","collections","pluginConfig","rest","sync","map","collection","syncConfig","find","slug","fields"],"mappings":"AAIA,SAASA,SAAS,QAAQ,wBAAuB;AACjD,SAASC,wBAAwB,QAAQ,0CAAyC;AAElF,OAAO,MAAMC,eACX,CAACC,uBACD,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,2BAA2B;QAC3B,MAAME,eAA4C;YAChD,GAAGH,oBAAoB;YACvBI,MAAMN,yBAAyB;gBAAEM,MAAMJ,sBAAsBI;YAAK;YAClEC,MAAML,sBAAsBK,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,OAAO;YACL,GAAGJ,MAAM;YACTC,aAAaA,aAAaI,IAAI,CAACC;gBAC7B,MAAMC,aAAaL,aAAaE,IAAI,EAAEI,KAAK,CAACJ,OAASA,KAAKE,UAAU,KAAKA,WAAWG,IAAI;gBAExF,IAAIF,YAAY;oBACd,MAAMG,SAASd,UAAU;wBACvBU;wBACAJ;wBACAK;oBACF;oBACA,OAAO;wBACL,GAAGD,UAAU;wBACbI;oBACF;gBACF;gBAEA,OAAOJ;YACT;QACF;IACF,EAAC"}
@@ -1,2 +1,2 @@
1
- export type { FieldSyncConfig, SanitizedStripePluginConfig, StripePluginConfig, StripeProxy, StripeWebhookHandler, StripeWebhookHandlers, SyncConfig, } from '../types.js';
1
+ export type { FieldSyncConfig, SanitizedStripePluginConfig, StripePluginConfig, StripeProxy, StripeRESTAccess, StripeRESTConfig, StripeWebhookHandler, StripeWebhookHandlers, SyncConfig, } from '../types.js';
2
2
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/exports/types.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,qBAAqB,EACrB,UAAU,GACX,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/exports/types.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,EACrB,UAAU,GACX,MAAM,aAAa,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/types.ts"],"sourcesContent":["export type {\n FieldSyncConfig,\n SanitizedStripePluginConfig,\n StripePluginConfig,\n StripeProxy,\n StripeWebhookHandler,\n StripeWebhookHandlers,\n SyncConfig,\n} from '../types.js'\n"],"names":[],"mappings":"AAAA,WAQoB"}
1
+ {"version":3,"sources":["../../src/exports/types.ts"],"sourcesContent":["export type {\n FieldSyncConfig,\n SanitizedStripePluginConfig,\n StripePluginConfig,\n StripeProxy,\n StripeRESTAccess,\n StripeRESTConfig,\n StripeWebhookHandler,\n StripeWebhookHandlers,\n SyncConfig,\n} from '../types.js'\n"],"names":[],"mappings":"AAAA,WAUoB"}
@@ -1 +1 @@
1
- {"version":3,"file":"getFields.d.ts","sourceRoot":"","sources":["../../src/fields/getFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAE9D,UAAU,IAAI;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,YAAY,EAAE,2BAA2B,CAAA;IACzC,UAAU,EAAE;QACV,kBAAkB,EAAE,MAAM,CAAA;KAC3B,CAAA;CACF;AAED,eAAO,MAAM,SAAS,6CAA8C,IAAI,KAAG,KAAK,EAyC/E,CAAA"}
1
+ {"version":3,"file":"getFields.d.ts","sourceRoot":"","sources":["../../src/fields/getFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAE9D,UAAU,IAAI;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,YAAY,EAAE,2BAA2B,CAAA;IACzC,UAAU,EAAE;QACV,kBAAkB,EAAE,MAAM,CAAA;KAC3B,CAAA;CACF;AAED,eAAO,MAAM,SAAS,6CAA8C,IAAI,KAAG,KAAK,EAiD/E,CAAA"}
@@ -2,6 +2,10 @@ export const getFields = ({ collection, pluginConfig, syncConfig })=>{
2
2
  const stripeIDField = {
3
3
  name: 'stripeID',
4
4
  type: 'text',
5
+ access: {
6
+ create: ()=>false,
7
+ update: ()=>false
8
+ },
5
9
  admin: {
6
10
  position: 'sidebar',
7
11
  readOnly: true
@@ -12,6 +16,10 @@ export const getFields = ({ collection, pluginConfig, syncConfig })=>{
12
16
  const skipSyncField = {
13
17
  name: 'skipSync',
14
18
  type: 'checkbox',
19
+ access: {
20
+ create: ()=>false,
21
+ update: ()=>false
22
+ },
15
23
  admin: {
16
24
  position: 'sidebar',
17
25
  readOnly: true
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fields/getFields.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { SanitizedStripePluginConfig } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n pluginConfig: SanitizedStripePluginConfig\n syncConfig: {\n stripeResourceType: string\n }\n}\n\nexport const getFields = ({ collection, pluginConfig, syncConfig }: Args): Field[] => {\n const stripeIDField: Field = {\n name: 'stripeID',\n type: 'text',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Stripe ID',\n saveToJWT: true,\n }\n\n const skipSyncField: Field = {\n name: 'skipSync',\n type: 'checkbox',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Skip Sync',\n }\n\n const docUrlField: Field = {\n name: 'docUrl',\n type: 'ui',\n admin: {\n components: {\n Field: '@payloadcms/plugin-stripe/client#LinkToDoc',\n },\n custom: {\n isTestKey: pluginConfig.isTestKey,\n nameOfIDField: 'stripeID',\n stripeResourceType: syncConfig.stripeResourceType,\n },\n position: 'sidebar',\n },\n }\n\n const fields = [...collection.fields, stripeIDField, skipSyncField, docUrlField]\n\n return fields\n}\n"],"names":["getFields","collection","pluginConfig","syncConfig","stripeIDField","name","type","admin","position","readOnly","label","saveToJWT","skipSyncField","docUrlField","components","Field","custom","isTestKey","nameOfIDField","stripeResourceType","fields"],"mappings":"AAYA,OAAO,MAAMA,YAAY,CAAC,EAAEC,UAAU,EAAEC,YAAY,EAAEC,UAAU,EAAQ;IACtE,MAAMC,gBAAuB;QAC3BC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;QACPC,WAAW;IACb;IAEA,MAAMC,gBAAuB;QAC3BP,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;IACT;IAEA,MAAMG,cAAqB;QACzBR,MAAM;QACNC,MAAM;QACNC,OAAO;YACLO,YAAY;gBACVC,OAAO;YACT;YACAC,QAAQ;gBACNC,WAAWf,aAAae,SAAS;gBACjCC,eAAe;gBACfC,oBAAoBhB,WAAWgB,kBAAkB;YACnD;YACAX,UAAU;QACZ;IACF;IAEA,MAAMY,SAAS;WAAInB,WAAWmB,MAAM;QAAEhB;QAAeQ;QAAeC;KAAY;IAEhF,OAAOO;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/fields/getFields.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { SanitizedStripePluginConfig } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n pluginConfig: SanitizedStripePluginConfig\n syncConfig: {\n stripeResourceType: string\n }\n}\n\nexport const getFields = ({ collection, pluginConfig, syncConfig }: Args): Field[] => {\n const stripeIDField: Field = {\n name: 'stripeID',\n type: 'text',\n access: {\n create: () => false,\n update: () => false,\n },\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Stripe ID',\n saveToJWT: true,\n }\n\n const skipSyncField: Field = {\n name: 'skipSync',\n type: 'checkbox',\n access: {\n create: () => false,\n update: () => false,\n },\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Skip Sync',\n }\n\n const docUrlField: Field = {\n name: 'docUrl',\n type: 'ui',\n admin: {\n components: {\n Field: '@payloadcms/plugin-stripe/client#LinkToDoc',\n },\n custom: {\n isTestKey: pluginConfig.isTestKey,\n nameOfIDField: 'stripeID',\n stripeResourceType: syncConfig.stripeResourceType,\n },\n position: 'sidebar',\n },\n }\n\n const fields = [...collection.fields, stripeIDField, skipSyncField, docUrlField]\n\n return fields\n}\n"],"names":["getFields","collection","pluginConfig","syncConfig","stripeIDField","name","type","access","create","update","admin","position","readOnly","label","saveToJWT","skipSyncField","docUrlField","components","Field","custom","isTestKey","nameOfIDField","stripeResourceType","fields"],"mappings":"AAYA,OAAO,MAAMA,YAAY,CAAC,EAAEC,UAAU,EAAEC,YAAY,EAAEC,UAAU,EAAQ;IACtE,MAAMC,gBAAuB;QAC3BC,MAAM;QACNC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;YACdC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;QACPC,WAAW;IACb;IAEA,MAAMC,gBAAuB;QAC3BV,MAAM;QACNC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;YACdC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;IACT;IAEA,MAAMG,cAAqB;QACzBX,MAAM;QACNC,MAAM;QACNI,OAAO;YACLO,YAAY;gBACVC,OAAO;YACT;YACAC,QAAQ;gBACNC,WAAWlB,aAAakB,SAAS;gBACjCC,eAAe;gBACfC,oBAAoBnB,WAAWmB,kBAAkB;YACnD;YACAX,UAAU;QACZ;IACF;IAEA,MAAMY,SAAS;WAAItB,WAAWsB,MAAM;QAAEnB;QAAeW;QAAeC;KAAY;IAEhF,OAAOO;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"createNewInStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/createNewInStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,4BAA4B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEnE,MAAM,MAAM,oCAAoC,GAAG,CACjD,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,iBAAiB,EAAE,oCA0H/B,CAAA"}
1
+ {"version":3,"file":"createNewInStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/createNewInStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,4BAA4B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEnE,MAAM,MAAM,oCAAoC,GAAG,CACjD,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,iBAAiB,EAAE,oCAoH/B,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { APIError } from 'payload';
2
2
  import Stripe from 'stripe';
3
- import { deepen } from '../utilities/deepen.js';
3
+ import { getSyncedFields } from '../utilities/deepen.js';
4
4
  export const createNewInStripe = async (args)=>{
5
5
  const { collection, data, operation, pluginConfig, req } = args;
6
6
  const { logs, sync } = pluginConfig || {};
@@ -24,12 +24,11 @@ export const createNewInStripe = async (args)=>{
24
24
  const syncConfig = sync?.find((conf)=>conf.collection === collectionSlug);
25
25
  if (syncConfig) {
26
26
  // combine all fields of this object and match their respective values within the document
27
- let syncedFields = syncConfig.fields.reduce((acc, field)=>{
28
- const { fieldPath, stripeProperty } = field;
29
- acc[stripeProperty] = dataRef[fieldPath];
30
- return acc;
31
- }, {});
32
- syncedFields = deepen(syncedFields);
27
+ const syncedFields = getSyncedFields({
28
+ data: dataRef,
29
+ fields: syncConfig.fields,
30
+ source: 'payload'
31
+ });
33
32
  // api version can only be the latest, stripe recommends ts ignoring it
34
33
  const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', {
35
34
  apiVersion: '2022-08-01'
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/createNewInStripe.ts"],"sourcesContent":["import type { CollectionBeforeValidateHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { deepen } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeValidateHook>[0], 'collection'>\n\nexport type CollectionBeforeValidateHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (args) => {\n const { collection, data, operation, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const payload = req?.payload\n\n const dataRef = data || {}\n\n if (process.env.NODE_ENV === 'test') {\n dataRef.stripeID = 'test'\n return dataRef\n }\n\n if (payload) {\n if (data?.skipSync) {\n if (logs) {\n payload.logger.info(`Bypassing collection-level hooks.`)\n }\n } else {\n // initialize as 'false' so that all Payload admin events sync to Stripe\n // then conditionally set to 'true' to for events that originate from webhooks\n // this will prevent webhook events from triggering an unnecessary sync / infinite loop\n dataRef.skipSync = false\n\n const { slug: collectionSlug } = collection || {}\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n // combine all fields of this object and match their respective values within the document\n let syncedFields = syncConfig.fields.reduce(\n (acc, field) => {\n const { fieldPath, stripeProperty } = field\n\n acc[stripeProperty] = dataRef[fieldPath]\n return acc\n },\n {} as Record<string, any>,\n )\n\n syncedFields = deepen(syncedFields)\n\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', { apiVersion: '2022-08-01' })\n\n if (operation === 'update') {\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n // NOTE: the Stripe document will be created in the \"afterChange\" hook, so create a new stripe document here if no stripeID exists\n if (!dataRef.stripeID) {\n try {\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // NOTE: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`- Error creating Stripe document: ${msg}`)\n }\n }\n }\n }\n\n if (operation === 'create') {\n if (logs) {\n payload.logger.info(\n `A new '${collectionSlug}' document was created in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n try {\n if (logs) {\n payload.logger.info(\n `- Creating new '${syncConfig.stripeResourceType}' resource in Stripe...`,\n )\n }\n\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // IMPORTANT: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(\n `Failed to create new '${syncConfig.stripeResourceType}' resource in Stripe: ${msg}`,\n )\n }\n }\n }\n }\n }\n\n return dataRef\n}\n"],"names":["APIError","Stripe","deepen","createNewInStripe","args","collection","data","operation","pluginConfig","req","logs","sync","payload","dataRef","process","env","NODE_ENV","stripeID","skipSync","logger","info","slug","collectionSlug","syncConfig","find","conf","syncedFields","fields","reduce","acc","field","fieldPath","stripeProperty","stripe","stripeSecretKey","apiVersion","id","stripeResource","stripeResourceType","create","error","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,MAAM,QAAQ,yBAAwB;AAa/C,OAAO,MAAMC,oBAA0D,OAAOC;IAC5E,MAAM,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGL;IAE3D,MAAM,EAAEM,IAAI,EAAEC,IAAI,EAAE,GAAGH,gBAAgB,CAAC;IAExC,MAAMI,UAAUH,KAAKG;IAErB,MAAMC,UAAUP,QAAQ,CAAC;IAEzB,IAAIQ,QAAQC,GAAG,CAACC,QAAQ,KAAK,QAAQ;QACnCH,QAAQI,QAAQ,GAAG;QACnB,OAAOJ;IACT;IAEA,IAAID,SAAS;QACX,IAAIN,MAAMY,UAAU;YAClB,IAAIR,MAAM;gBACRE,QAAQO,MAAM,CAACC,IAAI,CAAC,CAAC,iCAAiC,CAAC;YACzD;QACF,OAAO;YACL,wEAAwE;YACxE,8EAA8E;YAC9E,uFAAuF;YACvFP,QAAQK,QAAQ,GAAG;YAEnB,MAAM,EAAEG,MAAMC,cAAc,EAAE,GAAGjB,cAAc,CAAC;YAChD,MAAM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EA,IAAIlC,cAAc,UAAU;oBAC1B,IAAIG,MAAM;wBACRE,QAAQO,MAAM,CAACC,IAAI,CACjB,CAAC,OAAO,EAAEE,eAAe,4CAA4C,EAAEhB,MAAM8B,GAAG,yBAAyB,CAAC;oBAE9G;oBAEA,IAAI;wBACF,IAAI1B,MAAM;4BACRE,QAAQO,MAAM,CAACC,IAAI,CACjB,CAAC,gBAAgB,EAAEG,WAAWe,kBAAkB,CAAC,uBAAuB,CAAC;wBAE7E;wBAEA,+FAA+F;wBAC/F,MAAMD,iBAAiB,MAAMJ,QAAQ,CAACV,WAAWe,kBAAkB,CAAC,EAAEC,OACpE,mBAAmB;wBACnBb;wBAGF,IAAIhB,MAAM;4BACRE,QAAQO,MAAM,CAACC,IAAI,CACjB,CAAC,4BAA4B,EAAEG,WAAWe,kBAAkB,CAAC,+BAA+B,EAAED,eAAeD,EAAE,CAAC,EAAE,CAAC;wBAEvH;wBAEAvB,QAAQI,QAAQ,GAAGoB,eAAeD,EAAE;wBAEpC,+DAA+D;wBAC/DvB,QAAQK,QAAQ,GAAG;oBACrB,EAAE,OAAOsB,OAAgB;wBACvB,MAAMC,MAAMD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAGH;wBACrD,MAAM,IAAIxC,SACR,CAAC,sBAAsB,EAAEuB,WAAWe,kBAAkB,CAAC,sBAAsB,EAAEG,KAAK;oBAExF;gBACF;YACF;QACF;IACF;IAEA,OAAO5B;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/createNewInStripe.ts"],"sourcesContent":["import type { CollectionBeforeValidateHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { getSyncedFields } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeValidateHook>[0], 'collection'>\n\nexport type CollectionBeforeValidateHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (args) => {\n const { collection, data, operation, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const payload = req?.payload\n\n const dataRef = data || {}\n\n if (process.env.NODE_ENV === 'test') {\n dataRef.stripeID = 'test'\n return dataRef\n }\n\n if (payload) {\n if (data?.skipSync) {\n if (logs) {\n payload.logger.info(`Bypassing collection-level hooks.`)\n }\n } else {\n // initialize as 'false' so that all Payload admin events sync to Stripe\n // then conditionally set to 'true' to for events that originate from webhooks\n // this will prevent webhook events from triggering an unnecessary sync / infinite loop\n dataRef.skipSync = false\n\n const { slug: collectionSlug } = collection || {}\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n // combine all fields of this object and match their respective values within the document\n const syncedFields = getSyncedFields({\n data: dataRef,\n fields: syncConfig.fields,\n source: 'payload',\n })\n\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', { apiVersion: '2022-08-01' })\n\n if (operation === 'update') {\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n // NOTE: the Stripe document will be created in the \"afterChange\" hook, so create a new stripe document here if no stripeID exists\n if (!dataRef.stripeID) {\n try {\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // NOTE: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`- Error creating Stripe document: ${msg}`)\n }\n }\n }\n }\n\n if (operation === 'create') {\n if (logs) {\n payload.logger.info(\n `A new '${collectionSlug}' document was created in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n try {\n if (logs) {\n payload.logger.info(\n `- Creating new '${syncConfig.stripeResourceType}' resource in Stripe...`,\n )\n }\n\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // IMPORTANT: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(\n `Failed to create new '${syncConfig.stripeResourceType}' resource in Stripe: ${msg}`,\n )\n }\n }\n }\n }\n }\n\n return dataRef\n}\n"],"names":["APIError","Stripe","getSyncedFields","createNewInStripe","args","collection","data","operation","pluginConfig","req","logs","sync","payload","dataRef","process","env","NODE_ENV","stripeID","skipSync","logger","info","slug","collectionSlug","syncConfig","find","conf","syncedFields","fields","source","stripe","stripeSecretKey","apiVersion","id","stripeResource","stripeResourceType","create","error","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,eAAe,QAAQ,yBAAwB;AAaxD,OAAO,MAAMC,oBAA0D,OAAOC;IAC5E,MAAM,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGL;IAE3D,MAAM,EAAEM,IAAI,EAAEC,IAAI,EAAE,GAAGH,gBAAgB,CAAC;IAExC,MAAMI,UAAUH,KAAKG;IAErB,MAAMC,UAAUP,QAAQ,CAAC;IAEzB,IAAIQ,QAAQC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"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEjE,MAAM,MAAM,kCAAkC,GAAG,CAC/C,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,sBAAsB,EAAE,kCAwEpC,CAAA"}
1
+ {"version":3,"file":"syncExistingWithStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/syncExistingWithStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEjE,MAAM,MAAM,kCAAkC,GAAG,CAC/C,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,sBAAsB,EAAE,kCAkEpC,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { APIError } from 'payload';
2
2
  import Stripe from 'stripe';
3
- import { deepen } from '../utilities/deepen.js';
3
+ import { getSyncedFields } from '../utilities/deepen.js';
4
4
  export const syncExistingWithStripe = async (args)=>{
5
5
  const { collection, data, operation, originalDoc, pluginConfig, req } = args;
6
6
  const { logs, sync } = pluginConfig || {};
@@ -11,12 +11,11 @@ export const syncExistingWithStripe = async (args)=>{
11
11
  if (syncConfig) {
12
12
  if (operation === 'update') {
13
13
  // combine all fields of this object and match their respective values within the document
14
- let syncedFields = syncConfig.fields.reduce((acc, field)=>{
15
- const { fieldPath, stripeProperty } = field;
16
- acc[stripeProperty] = data[fieldPath];
17
- return acc;
18
- }, {});
19
- syncedFields = deepen(syncedFields);
14
+ const syncedFields = getSyncedFields({
15
+ data,
16
+ fields: syncConfig.fields,
17
+ source: 'payload'
18
+ });
20
19
  if (logs) {
21
20
  payload.logger.info(`A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`);
22
21
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/syncExistingWithStripe.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { deepen } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeChangeHook>[0], 'collection'>\n\nexport type CollectionBeforeChangeHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async (args) => {\n const { collection, data, operation, originalDoc, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const { payload } = req\n\n const { slug: collectionSlug } = collection || {}\n\n if (process.env.NODE_ENV !== 'test' && !data.skipSync) {\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n if (operation === 'update') {\n // combine all fields of this object and match their respective values within the document\n let syncedFields = syncConfig.fields.reduce(\n (acc, field) => {\n const { fieldPath, stripeProperty } = field\n\n acc[stripeProperty] = data[fieldPath]\n return acc\n },\n {} as Record<string, any>,\n )\n\n syncedFields = deepen(syncedFields)\n\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`,\n )\n }\n\n if (!data.stripeID) {\n // NOTE: the \"beforeValidate\" hook populates this\n if (logs) {\n payload.logger.error(`- There is no Stripe ID for this document, skipping.`)\n }\n } else {\n if (logs) {\n payload.logger.info(`- Syncing to Stripe resource with ID: '${data.stripeID}'...`)\n }\n\n try {\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', {\n apiVersion: '2022-08-01',\n })\n\n const stripeResource = await stripe?.[syncConfig?.stripeResourceType]?.update(\n data.stripeID,\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully synced Stripe resource with ID: '${stripeResource.id}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(`Failed to sync document with ID: '${data.id}' to Stripe: ${msg}`)\n }\n }\n }\n }\n }\n\n // Set back to 'false' so that all changes continue to sync to Stripe, see note in './createNewInStripe.ts'\n data.skipSync = false\n\n return data\n}\n"],"names":["APIError","Stripe","deepen","syncExistingWithStripe","args","collection","data","operation","originalDoc","pluginConfig","req","logs","sync","payload","slug","collectionSlug","process","env","NODE_ENV","skipSync","syncConfig","find","conf","syncedFields","fields","reduce","acc","field","fieldPath","stripeProperty","logger","info","_id","stripeID","error","stripe","stripeSecretKey","apiVersion","stripeResource","stripeResourceType","update","id","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,MAAM,QAAQ,yBAAwB;AAa/C,OAAO,MAAMC,yBAA6D,O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7DC,YAAY;wBACd;wBAEA,MAAMC,iBAAiB,MAAMH,QAAQ,CAACf,YAAYmB,mBAAmB,EAAEC,OACrElC,KAAK2B,QAAQ,EACbV;wBAGF,IAAIZ,MAAM;4BACRE,QAAQiB,MAAM,CAACC,IAAI,CACjB,CAAC,gDAAgD,EAAEO,eAAeG,EAAE,CAAC,EAAE,CAAC;wBAE5E;oBACF,EAAE,OAAOP,OAAgB;wBACvB,MAAMQ,MAAMR,iBAAiBS,QAAQT,MAAMU,OAAO,GAAGV;wBACrD,MAAM,IAAIlC,SAAS,CAAC,kCAAkC,EAAEM,KAAKmC,EAAE,CAAC,aAAa,EAAEC,KAAK;oBACtF;gBACF;YACF;QACF;IACF;IAEA,2GAA2G;IAC3GpC,KAAKa,QAAQ,GAAG;IAEhB,OAAOb;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/syncExistingWithStripe.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { getSyncedFields } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeChangeHook>[0], 'collection'>\n\nexport type CollectionBeforeChangeHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async (args) => {\n const { collection, data, operation, originalDoc, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const { payload } = req\n\n const { slug: collectionSlug } = collection || {}\n\n if (process.env.NODE_ENV !== 'test' && !data.skipSync) {\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n if (operation === 'update') {\n // combine all fields of this object and match their respective values within the document\n const syncedFields = getSyncedFields({\n data,\n fields: syncConfig.fields,\n source: 'payload',\n })\n\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`,\n )\n }\n\n if (!data.stripeID) {\n // NOTE: the \"beforeValidate\" hook populates this\n if (logs) {\n payload.logger.error(`- There is no Stripe ID for this document, skipping.`)\n }\n } else {\n if (logs) {\n payload.logger.info(`- Syncing to Stripe resource with ID: '${data.stripeID}'...`)\n }\n\n try {\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', {\n apiVersion: '2022-08-01',\n })\n\n const stripeResource = await stripe?.[syncConfig?.stripeResourceType]?.update(\n data.stripeID,\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully synced Stripe resource with ID: '${stripeResource.id}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(`Failed to sync document with ID: '${data.id}' to Stripe: ${msg}`)\n }\n }\n }\n }\n }\n\n // Set back to 'false' so that all changes continue to sync to Stripe, see note in './createNewInStripe.ts'\n data.skipSync = false\n\n return data\n}\n"],"names":["APIError","Stripe","getSyncedFields","syncExistingWithStripe","args","collection","data","operation","originalDoc","pluginConfig","req","logs","sync","payload","slug","collectionSlug","process","env","NODE_ENV","skipSync","syncConfig","find","conf","syncedFields","fields","source","logger","info","_id","stripeID","error","stripe","stripeSecretKey","apiVersion","stripeResource","stripeResourceType","update","id","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,eAAe,QAAQ,yBAAwB;AAaxD,OAAO,MAAMC,yBAA6D,OAAOC;IAC/E,MAAM,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,WAAW,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGN;IAExE,MAAM,EAAEO,IAAI,EAAEC,IAAI,EAAE,GAAGH,gBAAgB,CAAC;IAExC,MAAM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AI9B,SAAS,CAAC,kCAAkC,EAAEM,KAAK+B,EAAE,CAAC,aAAa,EAAEC,KAAK;oBACtF;gBACF;YACF;QACF;IACF;IAEA,2GAA2G;IAC3GhC,KAAKa,QAAQ,GAAG;IAEhB,OAAOb;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAY,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AASjF,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAExD,eAAO,MAAM,YAAY,yBACA,kBAAkB,cAChC,MAAM,KAAG,MAiGjB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAY,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAUjF,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAExD,eAAO,MAAM,YAAY,yBACA,kBAAkB,cAChC,MAAM,KAAG,MAiGjB,CAAA"}
package/dist/index.js CHANGED
@@ -4,13 +4,16 @@ import { deleteFromStripe } from './hooks/deleteFromStripe.js';
4
4
  import { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js';
5
5
  import { stripeREST } from './routes/rest.js';
6
6
  import { stripeWebhooks } from './routes/webhooks.js';
7
+ import { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js';
7
8
  export { stripeProxy } from './utilities/stripeProxy.js';
8
9
  export const stripePlugin = (incomingStripeConfig)=>(config)=>{
9
10
  const { collections } = config;
10
11
  // set config defaults here
11
12
  const pluginConfig = {
12
13
  ...incomingStripeConfig,
13
- rest: incomingStripeConfig?.rest ?? false,
14
+ rest: sanitizeStripeRESTConfig({
15
+ rest: incomingStripeConfig?.rest
16
+ }),
14
17
  sync: incomingStripeConfig?.sync || []
15
18
  };
16
19
  // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key
@@ -31,7 +34,7 @@ export const stripePlugin = (incomingStripeConfig)=>(config)=>{
31
34
  path: '/stripe/webhooks'
32
35
  }
33
36
  ];
34
- if (incomingStripeConfig?.rest) {
37
+ if (pluginConfig.rest) {
35
38
  endpoints.push({
36
39
  handler: async (req)=>{
37
40
  const res = await stripeREST({
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config, Endpoint } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\nimport { createNewInStripe } from './hooks/createNewInStripe.js'\nimport { deleteFromStripe } from './hooks/deleteFromStripe.js'\nimport { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js'\nimport { stripeREST } from './routes/rest.js'\nimport { stripeWebhooks } from './routes/webhooks.js'\n\nexport { stripeProxy } from './utilities/stripeProxy.js'\n\nexport const stripePlugin =\n (incomingStripeConfig: StripePluginConfig) =>\n (config: Config): Config => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingStripeConfig,\n rest: incomingStripeConfig?.rest ?? false,\n sync: incomingStripeConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n const endpoints: Endpoint[] = [\n ...(config?.endpoints || []),\n {\n handler: async (req) => {\n const res = await stripeWebhooks({\n config,\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post',\n path: '/stripe/webhooks',\n },\n ]\n\n if (incomingStripeConfig?.rest) {\n endpoints.push({\n handler: async (req) => {\n const res = await stripeREST({\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post' as Endpoint['method'],\n path: '/stripe/rest',\n })\n }\n\n for (const collection of collections!) {\n const { hooks: existingHooks } = collection\n\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (!syncConfig) {\n continue\n }\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n collection.fields = fields\n\n if (!collection.hooks) {\n collection.hooks = {}\n }\n\n collection.hooks.afterDelete = [\n ...(existingHooks?.afterDelete || []),\n (args) =>\n deleteFromStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeChange = [\n ...(existingHooks?.beforeChange || []),\n (args) =>\n syncExistingWithStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeValidate = [\n ...(existingHooks?.beforeValidate || []),\n (args) =>\n createNewInStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n }\n\n config.endpoints = endpoints\n\n return config\n }\n"],"names":["getFields","createNewInStripe","deleteFromStripe","syncExistingWithStripe","stripeREST","stripeWebhooks","stripeProxy","stripePlugin","incomingStripeConfig","config","collections","pluginConfig","rest","sync","endpoints","handler","req","res","method","path","push","collection","hooks","existingHooks","syncConfig","find","slug","fields","afterDelete","args","beforeChange","beforeValidate"],"mappings":"AAIA,SAASA,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,gBAAgB,QAAQ,8BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAmC;AAC1E,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,cAAc,QAAQ,uBAAsB;AAErD,SAASC,WAAW,QAAQ,6BAA4B;AAExD,OAAO,MAAMC,eACX,CAACC,uBACD,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,2BAA2B;QAC3B,MAAME,eAA4C;YAChD,GAAGH,oBAAoB;YACvBI,MAAMJ,sBAAsBI,QAAQ;YACpCC,MAAML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I;wBACPR;wBACAV;oBACF;aACH;QACH;QAEAF,OAAOK,SAAS,GAAGA;QAEnB,OAAOL;IACT,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config, Endpoint } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\nimport { createNewInStripe } from './hooks/createNewInStripe.js'\nimport { deleteFromStripe } from './hooks/deleteFromStripe.js'\nimport { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js'\nimport { stripeREST } from './routes/rest.js'\nimport { stripeWebhooks } from './routes/webhooks.js'\nimport { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js'\n\nexport { stripeProxy } from './utilities/stripeProxy.js'\n\nexport const stripePlugin =\n (incomingStripeConfig: StripePluginConfig) =>\n (config: Config): Config => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingStripeConfig,\n rest: sanitizeStripeRESTConfig({ rest: incomingStripeConfig?.rest }),\n sync: incomingStripeConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n const endpoints: Endpoint[] = [\n ...(config?.endpoints || []),\n {\n handler: async (req) => {\n const res = await stripeWebhooks({\n config,\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post',\n path: '/stripe/webhooks',\n },\n ]\n\n if (pluginConfig.rest) {\n endpoints.push({\n handler: async (req) => {\n const res = await stripeREST({\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post' as Endpoint['method'],\n path: '/stripe/rest',\n })\n }\n\n for (const collection of collections!) {\n const { hooks: existingHooks } = collection\n\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (!syncConfig) {\n continue\n }\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n collection.fields = fields\n\n if (!collection.hooks) {\n collection.hooks = {}\n }\n\n collection.hooks.afterDelete = [\n ...(existingHooks?.afterDelete || []),\n (args) =>\n deleteFromStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeChange = [\n ...(existingHooks?.beforeChange || []),\n (args) =>\n syncExistingWithStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeValidate = [\n ...(existingHooks?.beforeValidate || []),\n (args) =>\n createNewInStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n }\n\n config.endpoints = endpoints\n\n return config\n }\n"],"names":["getFields","createNewInStripe","deleteFromStripe","syncExistingWithStripe","stripeREST","stripeWebhooks","sanitizeStripeRESTConfig","stripeProxy","stripePlugin","incomingStripeConfig","config","collections","pluginConfig","rest","sync","endpoints","handler","req","res","method","path","push","collection","hooks","existingHooks","syncConfig","find","slug","fields","afterDelete","args","beforeChange","beforeValidate"],"mappings":"AAIA,SAASA,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,gBAAgB,QAAQ,8BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAmC;AAC1E,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,wBAAwB,QAAQ,0CAAyC;AAElF,SAASC,WAAW,QAAQ,6BAA4B;AAExD,OAAO,MAAMC,eACX,CAACC,uBACD,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,2BAA2B;QAC3B,MAAME,eAA4C;YAChD,GAAGH,oBAAoB;YACvBI,MAAMP,yBAAyB;gBAAEO,MAAMJ,sBAAsBI;YAAK;YAClEC,MAAML,sBAAsBK,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,MAAMC,YAAwB;eACxBL,QAAQK,aAAa,EAAE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ach, describe, expect, it, vi } from 'vitest';
2
+ const mocks = vi.hoisted(()=>({
3
+ stripeREST: vi.fn()
4
+ }));
5
+ vi.mock('./routes/rest.js', ()=>({
6
+ stripeREST: mocks.stripeREST
7
+ }));
8
+ import { stripePlugin } from './index.js';
9
+ const createBaseConfig = ()=>({
10
+ collections: []
11
+ });
12
+ describe('stripePlugin REST endpoint registration', ()=>{
13
+ beforeEach(()=>{
14
+ vi.clearAllMocks();
15
+ mocks.stripeREST.mockResolvedValue(Response.json({}, {
16
+ status: 405
17
+ }));
18
+ });
19
+ // Mutation caught: restoring the legacy `rest: true` configuration without an explicit allowlist.
20
+ it('should reject the legacy true configuration', ()=>{
21
+ expect(()=>stripePlugin({
22
+ // @ts-expect-error -- `true` is intentionally rejected in every supported release line.
23
+ rest: true,
24
+ stripeSecretKey: 'sk_test_example'
25
+ })(createBaseConfig())).toThrow('non-empty allowedMethods');
26
+ expect(mocks.stripeREST).not.toHaveBeenCalled();
27
+ });
28
+ // Mutation caught: only registering the endpoint for the legacy boolean form.
29
+ it('should register an object-configured endpoint with its exact allowlist', async ()=>{
30
+ const transformedConfig = stripePlugin({
31
+ rest: {
32
+ allowedMethods: [
33
+ 'customers.list'
34
+ ]
35
+ },
36
+ stripeSecretKey: 'sk_test_example'
37
+ })(createBaseConfig());
38
+ const endpoint = transformedConfig.endpoints?.find(({ path })=>path === '/stripe/rest');
39
+ const req = {};
40
+ await endpoint?.handler(req);
41
+ expect(endpoint).toMatchObject({
42
+ method: 'post',
43
+ path: '/stripe/rest'
44
+ });
45
+ expect(mocks.stripeREST).toHaveBeenCalledWith({
46
+ pluginConfig: expect.objectContaining({
47
+ rest: {
48
+ allowedMethods: [
49
+ 'customers.list'
50
+ ]
51
+ }
52
+ }),
53
+ req
54
+ });
55
+ });
56
+ // Mutation caught: registering the REST endpoint when its configuration is omitted.
57
+ it('should not register the REST endpoint when the option is absent', ()=>{
58
+ const transformedConfig = stripePlugin({
59
+ stripeSecretKey: 'sk_test_example'
60
+ })(createBaseConfig());
61
+ expect(transformedConfig.endpoints?.filter(({ path })=>path === '/stripe/rest')).toEqual([]);
62
+ });
63
+ // Mutation caught: removing fail-closed runtime handling for untyped configurations.
64
+ it('should treat false from an untyped configuration as disabled', ()=>{
65
+ const transformedConfig = stripePlugin({
66
+ // @ts-expect-error -- omission is the supported way to disable the endpoint.
67
+ rest: false,
68
+ stripeSecretKey: 'sk_test_example'
69
+ })(createBaseConfig());
70
+ expect(transformedConfig.endpoints?.filter(({ path })=>path === '/stripe/rest')).toEqual([]);
71
+ });
72
+ });
73
+ describe('stripePlugin managed fields', ()=>{
74
+ it('should prevent API writes to Stripe-managed fields', ()=>{
75
+ const transformedConfig = stripePlugin({
76
+ stripeSecretKey: 'sk_test_example',
77
+ sync: [
78
+ {
79
+ collection: 'products',
80
+ fields: [],
81
+ stripeResourceType: 'products',
82
+ stripeResourceTypeSingular: 'product'
83
+ }
84
+ ]
85
+ })({
86
+ collections: [
87
+ {
88
+ fields: [],
89
+ slug: 'products'
90
+ }
91
+ ]
92
+ });
93
+ const fields = transformedConfig.collections?.[0]?.fields ?? [];
94
+ const stripeIDField = fields.find((field)=>'name' in field && field.name === 'stripeID');
95
+ const skipSyncField = fields.find((field)=>'name' in field && field.name === 'skipSync');
96
+ expect(stripeIDField).toMatchObject({
97
+ access: {
98
+ create: expect.any(Function),
99
+ update: expect.any(Function)
100
+ }
101
+ });
102
+ expect(skipSyncField).toMatchObject({
103
+ access: {
104
+ create: expect.any(Function),
105
+ update: expect.any(Function)
106
+ }
107
+ });
108
+ expect(stripeIDField?.access?.create?.({})).toBe(false);
109
+ expect(stripeIDField?.access?.update?.({})).toBe(false);
110
+ expect(skipSyncField?.access?.create?.({})).toBe(false);
111
+ expect(skipSyncField?.access?.update?.({})).toBe(false);
112
+ });
113
+ });
114
+
115
+ //# sourceMappingURL=index.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.spec.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { beforeEach, describe, expect, it, vi } from 'vitest'\n\nconst mocks = vi.hoisted(() => ({\n stripeREST: vi.fn(),\n}))\n\nvi.mock('./routes/rest.js', () => ({\n stripeREST: mocks.stripeREST,\n}))\n\nimport { stripePlugin } from './index.js'\n\nconst createBaseConfig = (): Config => ({ collections: [] })\n\ndescribe('stripePlugin REST endpoint registration', () => {\n beforeEach(() => {\n vi.clearAllMocks()\n mocks.stripeREST.mockResolvedValue(Response.json({}, { status: 405 }))\n })\n\n // Mutation caught: restoring the legacy `rest: true` configuration without an explicit allowlist.\n it('should reject the legacy true configuration', () => {\n expect(() =>\n stripePlugin({\n // @ts-expect-error -- `true` is intentionally rejected in every supported release line.\n rest: true,\n stripeSecretKey: 'sk_test_example',\n })(createBaseConfig()),\n ).toThrow('non-empty allowedMethods')\n\n expect(mocks.stripeREST).not.toHaveBeenCalled()\n })\n\n // Mutation caught: only registering the endpoint for the legacy boolean form.\n it('should register an object-configured endpoint with its exact allowlist', async () => {\n const transformedConfig = stripePlugin({\n rest: { allowedMethods: ['customers.list'] },\n stripeSecretKey: 'sk_test_example',\n })(createBaseConfig())\n const endpoint = transformedConfig.endpoints?.find(({ path }) => path === '/stripe/rest')\n const req = {} as Parameters<NonNullable<typeof endpoint>['handler']>[0]\n\n await endpoint?.handler(req)\n\n expect(endpoint).toMatchObject({ method: 'post', path: '/stripe/rest' })\n expect(mocks.stripeREST).toHaveBeenCalledWith({\n pluginConfig: expect.objectContaining({\n rest: { allowedMethods: ['customers.list'] },\n }),\n req,\n })\n })\n\n // Mutation caught: registering the REST endpoint when its configuration is omitted.\n it('should not register the REST endpoint when the option is absent', () => {\n const transformedConfig = stripePlugin({\n stripeSecretKey: 'sk_test_example',\n })(createBaseConfig())\n\n expect(transformedConfig.endpoints?.filter(({ path }) => path === '/stripe/rest')).toEqual([])\n })\n\n // Mutation caught: removing fail-closed runtime handling for untyped configurations.\n it('should treat false from an untyped configuration as disabled', () => {\n const transformedConfig = stripePlugin({\n // @ts-expect-error -- omission is the supported way to disable the endpoint.\n rest: false,\n stripeSecretKey: 'sk_test_example',\n })(createBaseConfig())\n\n expect(transformedConfig.endpoints?.filter(({ path }) => path === '/stripe/rest')).toEqual([])\n })\n})\n\ndescribe('stripePlugin managed fields', () => {\n it('should prevent API writes to Stripe-managed fields', () => {\n const transformedConfig = stripePlugin({\n stripeSecretKey: 'sk_test_example',\n sync: [\n {\n collection: 'products',\n fields: [],\n stripeResourceType: 'products',\n stripeResourceTypeSingular: 'product',\n },\n ],\n })({\n collections: [\n {\n fields: [],\n slug: 'products',\n },\n ],\n })\n const fields = transformedConfig.collections?.[0]?.fields ?? []\n const stripeIDField = fields.find((field) => 'name' in field && field.name === 'stripeID')\n const skipSyncField = fields.find((field) => 'name' in field && field.name === 'skipSync')\n\n expect(stripeIDField).toMatchObject({\n access: { create: expect.any(Function), update: expect.any(Function) },\n })\n expect(skipSyncField).toMatchObject({\n access: { create: expect.any(Function), update: expect.any(Function) },\n })\n expect(stripeIDField?.access?.create?.({} as never)).toBe(false)\n expect(stripeIDField?.access?.update?.({} as never)).toBe(false)\n expect(skipSyncField?.access?.create?.({} as never)).toBe(false)\n expect(skipSyncField?.access?.update?.({} as never)).toBe(false)\n })\n})\n"],"names":["beforeEach","describe","expect","it","vi","mocks","hoisted","stripeREST","fn","mock","stripePlugin","createBaseConfig","collections","clearAllMocks","mockResolvedValue","Response","json","status","rest","stripeSecretKey","toThrow","not","toHaveBeenCalled","transformedConfig","allowedMethods","endpoint","endpoints","find","path","req","handler","toMatchObject","method","toHaveBeenCalledWith","pluginConfig","objectContaining","filter","toEqual","sync","collection","fields","stripeResourceType","stripeResourceTypeSingular","slug","stripeIDField","field","name","skipSyncField","access","create","any","Function","update","toBe"],"mappings":"AAEA,SAASA,UAAU,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAE7D,MAAMC,QAAQD,GAAGE,OAAO,CAAC,IAAO,CAAA;QAC9BC,YAA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CAAC,IAAaC,IAAI,CAAC;QAC1DnD,OAAO6C,eAAeC,QAAQC,SAAS,CAAC,IAAaI,IAAI,CAAC;QAC1DnD,OAAO6C,eAAeC,QAAQI,SAAS,CAAC,IAAaC,IAAI,CAAC;IAC5D;AACF"}
@@ -1,7 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
- import type { StripePluginConfig } from '../types.js';
2
+ import type { SanitizedStripePluginConfig } from '../types.js';
3
3
  export declare const stripeREST: (args: {
4
- pluginConfig: StripePluginConfig;
4
+ pluginConfig: SanitizedStripePluginConfig;
5
5
  req: PayloadRequest;
6
- }) => Promise<any>;
6
+ }) => Promise<Response>;
7
7
  //# sourceMappingURL=rest.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../../src/routes/rest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,eAAO,MAAM,UAAU,SAAgB;IACrC,YAAY,EAAE,kBAAkB,CAAA;IAChC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,GAAG,CAyCd,CAAA"}
1
+ {"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../../src/routes/rest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAI9D,eAAO,MAAM,UAAU,SAAgB;IACrC,YAAY,EAAE,2BAA2B,CAAA;IACzC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,QAAQ,CAiEnB,CAAA"}
@@ -1,35 +1,118 @@
1
- import { addDataAndFileToRequest, Forbidden } from 'payload';
1
+ import { addDataAndFileToRequest, canAccessAdmin, UnauthorizedError } from 'payload';
2
2
  import { stripeProxy } from '../utilities/stripeProxy.js';
3
3
  export const stripeREST = async (args)=>{
4
- let responseStatus = 200;
5
- let responseJSON;
6
4
  const { pluginConfig, req } = args;
7
- await addDataAndFileToRequest(req);
8
- const requestWithData = req;
9
- const { data, payload, user } = requestWithData;
10
- const { stripeSecretKey } = pluginConfig;
11
5
  try {
12
- if (!user) {
13
- // TODO: make this customizable from the config
14
- throw new Forbidden(req.t);
6
+ await addDataAndFileToRequest(req);
7
+ } catch (err) {
8
+ return unexpectedErrorResponse({
9
+ err,
10
+ req
11
+ });
12
+ }
13
+ if (!req.user) {
14
+ return errorResponse({
15
+ message: 'Unauthorized',
16
+ status: 401
17
+ });
18
+ }
19
+ if (!pluginConfig.rest) {
20
+ return unexpectedErrorResponse({
21
+ err: new Error('Stripe REST handler called while disabled'),
22
+ req
23
+ });
24
+ }
25
+ let hasAccess;
26
+ if (pluginConfig.rest.access) {
27
+ try {
28
+ hasAccess = await pluginConfig.rest.access({
29
+ req
30
+ });
31
+ } catch (err) {
32
+ return unexpectedErrorResponse({
33
+ err,
34
+ req
35
+ });
15
36
  }
16
- responseJSON = await stripeProxy({
17
- stripeArgs: data?.stripeArgs,
18
- stripeMethod: data?.stripeMethod,
19
- stripeSecretKey
20
- });
21
- const { status } = responseJSON;
22
- responseStatus = status;
23
- } catch (error) {
24
- const message = `An error has occurred in the Stripe plugin REST handler: '${JSON.stringify(error)}'`;
25
- payload.logger.error(message);
26
- responseStatus = 500;
27
- responseJSON = {
28
- message
29
- };
30
- }
31
- return Response.json(responseJSON, {
32
- status: responseStatus
37
+ } else {
38
+ try {
39
+ hasAccess = await hasAdminAccess({
40
+ req
41
+ });
42
+ } catch (err) {
43
+ return unexpectedErrorResponse({
44
+ err,
45
+ req
46
+ });
47
+ }
48
+ }
49
+ if (!hasAccess) {
50
+ return errorResponse({
51
+ message: 'Forbidden',
52
+ status: 403
53
+ });
54
+ }
55
+ const { stripeArgs, stripeMethod } = req.data ?? {};
56
+ if (typeof stripeMethod !== 'string' || stripeMethod.trim().length === 0) {
57
+ return errorResponse({
58
+ message: 'Invalid request',
59
+ status: 400
60
+ });
61
+ }
62
+ if (!pluginConfig.rest.allowedMethods.includes(stripeMethod)) {
63
+ return errorResponse({
64
+ message: 'Invalid request',
65
+ status: 400
66
+ });
67
+ }
68
+ if (!Array.isArray(stripeArgs)) {
69
+ return errorResponse({
70
+ message: 'Invalid request',
71
+ status: 400
72
+ });
73
+ }
74
+ try {
75
+ const responseJSON = await stripeProxy({
76
+ stripeArgs,
77
+ stripeMethod,
78
+ stripeSecretKey: pluginConfig.stripeSecretKey
79
+ });
80
+ return Response.json(responseJSON, {
81
+ status: responseJSON.status
82
+ });
83
+ } catch (err) {
84
+ return unexpectedErrorResponse({
85
+ err,
86
+ req
87
+ });
88
+ }
89
+ };
90
+ const hasAdminAccess = async ({ req })=>{
91
+ try {
92
+ await canAccessAdmin({
93
+ req
94
+ });
95
+ return true;
96
+ } catch (err) {
97
+ if (err instanceof UnauthorizedError) {
98
+ return false;
99
+ }
100
+ throw err;
101
+ }
102
+ };
103
+ const errorResponse = ({ message, status })=>Response.json({
104
+ message
105
+ }, {
106
+ status
107
+ });
108
+ const unexpectedErrorResponse = ({ err, req })=>{
109
+ req.payload.logger.error({
110
+ err,
111
+ msg: 'An unexpected error occurred in the Stripe plugin REST handler.'
112
+ });
113
+ return errorResponse({
114
+ message: 'Internal server error',
115
+ status: 500
33
116
  });
34
117
  };
35
118