@payloadcms/plugin-stripe 4.0.0-internal.d1cc1d3 → 4.0.0-internal.d21c039

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 (37) 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/routes/rest.d.ts +3 -3
  20. package/dist/routes/rest.d.ts.map +1 -1
  21. package/dist/routes/rest.js +104 -27
  22. package/dist/routes/rest.js.map +1 -1
  23. package/dist/types.d.ts +10 -3
  24. package/dist/types.d.ts.map +1 -1
  25. package/dist/types.js.map +1 -1
  26. package/dist/utilities/deepen.d.ts +6 -0
  27. package/dist/utilities/deepen.d.ts.map +1 -1
  28. package/dist/utilities/deepen.js +33 -3
  29. package/dist/utilities/deepen.js.map +1 -1
  30. package/dist/utilities/sanitizeStripeRESTConfig.d.ts +5 -0
  31. package/dist/utilities/sanitizeStripeRESTConfig.d.ts.map +1 -0
  32. package/dist/utilities/sanitizeStripeRESTConfig.js +25 -0
  33. package/dist/utilities/sanitizeStripeRESTConfig.js.map +1 -0
  34. package/dist/webhooks/handleCreatedOrUpdated.d.ts.map +1 -1
  35. package/dist/webhooks/handleCreatedOrUpdated.js +6 -6
  36. package/dist/webhooks/handleCreatedOrUpdated.js.map +1 -1
  37. 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,MAAMkB,aAAaZ,MAAMa,KAAK,CAACC,OAASA,KAAKpB,UAAU,KAAKiB;YAE5D,IAAIC,YAAY;gBACd,0FAA0F;gBAC1F,IAAIG,eAAeH,WAAWI,MAAM,CAACC,MAAM,CACzC,CAACC,KAAKC;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;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,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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,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,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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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,EAAEI,OAAO,EAAE,GAAGH;IAEpB,MAAM,EAAEI,MAAMC,cAAc,EAAE,GAAGV,cAAc,CAAC;IAEhD,IAAIW,QAAQC,GAAG,CAACC,QAAQ,KAAK,UAAU,CAACZ,KAAKa,QAAQ,E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T,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AASjF,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAExD,eAAO,MAAM,YAAY,2DAoGvB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAUjF,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAExD,eAAO,MAAM,YAAY,2DAoGvB,CAAA"}
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { deleteFromStripe } from './hooks/deleteFromStripe.js';
5
5
  import { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js';
6
6
  import { stripeREST } from './routes/rest.js';
7
7
  import { stripeWebhooks } from './routes/webhooks.js';
8
+ import { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js';
8
9
  export { stripeProxy } from './utilities/stripeProxy.js';
9
10
  export const stripePlugin = definePlugin({
10
11
  slug: '@payloadcms/plugin-stripe',
@@ -13,7 +14,9 @@ export const stripePlugin = definePlugin({
13
14
  // set config defaults here
14
15
  const pluginConfig = {
15
16
  ...incomingStripeConfig,
16
- rest: incomingStripeConfig?.rest ?? false,
17
+ rest: sanitizeStripeRESTConfig({
18
+ rest: incomingStripeConfig?.rest
19
+ }),
17
20
  sync: incomingStripeConfig?.sync || []
18
21
  };
19
22
  // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key
@@ -34,7 +37,7 @@ export const stripePlugin = definePlugin({
34
37
  path: '/stripe/webhooks'
35
38
  }
36
39
  ];
37
- if (incomingStripeConfig?.rest) {
40
+ if (pluginConfig.rest) {
38
41
  endpoints.push({
39
42
  handler: async (req)=>{
40
43
  const res = await stripeREST({
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport { definePlugin } 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 = definePlugin<StripePluginConfig>({\n slug: '@payloadcms/plugin-stripe',\n plugin: ({ config, options: incomingStripeConfig }) => {\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})\n"],"names":["definePlugin","getFields","createNewInStripe","deleteFromStripe","syncExistingWithStripe","stripeREST","stripeWebhooks","stripeProxy","stripePlugin","slug","plugin","config","options","incomingStripeConfig","collections","pluginConfig","rest","sync","endpoints","handler","req","res","method","path","push","collection","hooks","existingHooks","syncConfig","find","fields","afterDelete","args","beforeChange","beforeValidate"],"mappings":"AAEA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,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,eAAeR,aAAiC;IAC3DS,MAAM;IACNC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,SAASC,oBAAoB,EAAE;QAChD,MAAM,EAAEC,WAAW,EAAE,GAAGH;QAExB,2BAA2B;QAC3B,MAAMI,eAA4C;YAChD,GAAGF,oBAAoB;YACvBG,MAAMH,sBAAsBG,QAAQ;YACpCC,MAAMJ,sBAAsBI,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,MAAMC,YAAwB;eACxBP,QAAQO,aAAa,EAAE;YAC3B;gBACEC,SAAS,OAAOC;oBACd,MAAMC,MAAM,MAAMf,eAAe;wBAC/BK;wBACAI;wBACAK;oBACF;oBAEA,OAAOC;gBACT;gBACAC,QAAQ;gBACRC,MAAM;YACR;SACD;QAED,IAAIV,sBAAsBG,MAAM;YAC9BE,UAAUM,IAAI,CAAC;gBACbL,SAAS,OAAOC;oBACd,MAAMC,MAAM,MAAMhB,WAAW;wBAC3BU;wBACAK;oBACF;oBAEA,OAAOC;gBACT;gBACAC,QAAQ;gBACRC,MAAM;YACR;QACF;QAEA,KAAK,MAAME,cAAcX,YAAc;YACrC,MAAM,EAAEY,OAAOC,aAAa,EAAE,GAAGF;YAEjC,MAAMG,aAAab,aAAaE,IAAI,EAAEY,KAAK,CAACZ,OAASA,KAAKQ,UAAU,KAAKA,WAAWhB,IAAI;YAExF,IAAI,CAACmB,YAAY;gBACf;YACF;YACA,MAAME,SAAS7B,UAAU;gBACvBwB;gBACAV;gBACAa;YACF;YACAH,WAAWK,MAAM,GAAGA;YAEpB,IAAI,CAACL,WAAWC,KAAK,EAAE;gBACrBD,WAAWC,KAAK,GAAG,CAAC;YACtB;YAEAD,WAAWC,KAAK,CAACK,WAAW,GAAG;mBACzBJ,eAAeI,eAAe,EAAE;gBACpC,CAACC,OACC7B,iBAAiB;wBACf,GAAG6B,IAAI;wBACPP;wBACAV;oBACF;aACH;YACDU,WAAWC,KAAK,CAACO,YAAY,GAAG;mBAC1BN,eAAeM,gBAAgB,EAAE;gBACrC,CAACD,OACC5B,uBAAuB;wBACrB,GAAG4B,IAAI;wBACPP;wBACAV;oBACF;aACH;YACDU,WAAWC,KAAK,CAACQ,cAAc,GAAG;mBAC5BP,eAAeO,kBAAkB,EAAE;gBACvC,CAACF,OACC9B,kBAAkB;wBAChB,GAAG8B,IAAI;wBACPP;wBACAV;oBACF;aACH;QACH;QAEAJ,OAAOO,SAAS,GAAGA;QAEnB,OAAOP;IACT;AACF,GAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport { definePlugin } 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 = definePlugin<StripePluginConfig>({\n slug: '@payloadcms/plugin-stripe',\n plugin: ({ config, options: incomingStripeConfig }) => {\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})\n"],"names":["definePlugin","getFields","createNewInStripe","deleteFromStripe","syncExistingWithStripe","stripeREST","stripeWebhooks","sanitizeStripeRESTConfig","stripeProxy","stripePlugin","slug","plugin","config","options","incomingStripeConfig","collections","pluginConfig","rest","sync","endpoints","handler","req","res","method","path","push","collection","hooks","existingHooks","syncConfig","find","fields","afterDelete","args","beforeChange","beforeValidate"],"mappings":"AAEA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,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,eAAeT,aAAiC;IAC3DU,MAAM;IACNC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,SAASC,oBAAoB,EAAE;QAChD,MAAM,EAAEC,WAAW,EAAE,GAAGH;QAExB,2BAA2B;QAC3B,MAAMI,eAA4C;YAChD,GAAGF,oBAAoB;YACvBG,MAAMV,yBAAyB;gBAAEU,MAAMH,sBAAsBG;YAAK;YAClEC,MAAMJ,sBAAsBI,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,MAAMC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,GAAE"}
@@ -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,112 @@
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
+ });
36
+ }
37
+ } else {
38
+ try {
39
+ hasAccess = await hasAdminAccess({
40
+ req
41
+ });
42
+ } catch (err) {
43
+ return unexpectedErrorResponse({
44
+ err,
45
+ req
46
+ });
15
47
  }
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
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 || !pluginConfig.rest.allowedMethods.includes(stripeMethod)) {
57
+ return errorResponse({
58
+ message: 'Invalid request',
59
+ status: 400
60
+ });
61
+ }
62
+ if (!Array.isArray(stripeArgs)) {
63
+ return errorResponse({
64
+ message: 'Invalid request',
65
+ status: 400
66
+ });
67
+ }
68
+ try {
69
+ const responseJSON = await stripeProxy({
70
+ stripeArgs,
71
+ stripeMethod,
72
+ stripeSecretKey: pluginConfig.stripeSecretKey
73
+ });
74
+ return Response.json(responseJSON, {
75
+ status: responseJSON.status
76
+ });
77
+ } catch (err) {
78
+ return unexpectedErrorResponse({
79
+ err,
80
+ req
81
+ });
82
+ }
83
+ };
84
+ const hasAdminAccess = async ({ req })=>{
85
+ try {
86
+ await canAccessAdmin({
87
+ req
88
+ });
89
+ return true;
90
+ } catch (err) {
91
+ if (err instanceof UnauthorizedError) {
92
+ return false;
93
+ }
94
+ throw err;
95
+ }
96
+ };
97
+ const errorResponse = ({ message, status })=>Response.json({
98
+ message
99
+ }, {
100
+ status
101
+ });
102
+ const unexpectedErrorResponse = ({ err, req })=>{
103
+ req.payload.logger.error({
104
+ err,
105
+ msg: 'An unexpected error occurred in the Stripe plugin REST handler.'
106
+ });
107
+ return errorResponse({
108
+ message: 'Internal server error',
109
+ status: 500
33
110
  });
34
111
  };
35
112
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/routes/rest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest, Forbidden } from 'payload'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { stripeProxy } from '../utilities/stripeProxy.js'\n\nexport const stripeREST = async (args: {\n pluginConfig: StripePluginConfig\n req: PayloadRequest\n}): Promise<any> => {\n let responseStatus = 200\n let responseJSON\n\n const { pluginConfig, req } = args\n\n await addDataAndFileToRequest(req)\n\n const requestWithData = req\n const { data, payload, user } = requestWithData\n\n const { stripeSecretKey } = pluginConfig\n\n try {\n if (!user) {\n // TODO: make this customizable from the config\n throw new Forbidden(req.t)\n }\n\n responseJSON = await stripeProxy({\n stripeArgs: data?.stripeArgs, // example: ['cus_MGgt3Tuj3D66f2'] or [{ limit: 100 }, { stripeAccount: 'acct_1J9Z4pKZ4Z4Z4Z4Z' }]\n stripeMethod: data?.stripeMethod, // example: 'subscriptions.list',\n stripeSecretKey,\n })\n\n const { status } = responseJSON\n responseStatus = status\n } catch (error: unknown) {\n const message = `An error has occurred in the Stripe plugin REST handler: '${JSON.stringify(\n error,\n )}'`\n payload.logger.error(message)\n responseStatus = 500\n responseJSON = {\n message,\n }\n }\n\n return Response.json(responseJSON, {\n status: responseStatus,\n })\n}\n"],"names":["addDataAndFileToRequest","Forbidden","stripeProxy","stripeREST","args","responseStatus","responseJSON","pluginConfig","req","requestWithData","data","payload","user","stripeSecretKey","t","stripeArgs","stripeMethod","status","error","message","JSON","stringify","logger","Response","json"],"mappings":"AAEA,SAASA,uBAAuB,EAAEC,SAAS,QAAQ,UAAS;AAI5D,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,OAAO,MAAMC,aAAa,OAAOC;IAI/B,IAAIC,iBAAiB;IACrB,IAAIC;IAEJ,MAAM,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGJ;IAE9B,MAAMJ,wBAAwBQ;IAE9B,MAAMC,kBAAkBD;IACxB,MAAM,EAAEE,IAAI,EAAEC,OAAO,EAAEC,IAAI,EAAE,GAAGH;IAEhC,MAAM,EAAEI,eAAe,EAAE,GAAGN;IAE5B,IAAI;QACF,IAAI,CAACK,MAAM;YACT,+CAA+C;YAC/C,MAAM,IAAIX,UAAUO,IAAIM,CAAC;QAC3B;QAEAR,eAAe,MAAMJ,YAAY;YAC/Ba,YAAYL,MAAMK;YAClBC,cAAcN,MAAMM;YACpBH;QACF;QAEA,MAAM,EAAEI,MAAM,EAAE,GAAGX;QACnBD,iBAAiBY;IACnB,EAAE,OAAOC,OAAgB;QACvB,MAAMC,UAAU,CAAC,0DAA0D,EAAEC,KAAKC,SAAS,CACzFH,OACA,CAAC,CAAC;QACJP,QAAQW,MAAM,CAACJ,KAAK,CAACC;QACrBd,iBAAiB;QACjBC,eAAe;YACba;QACF;IACF;IAEA,OAAOI,SAASC,IAAI,CAAClB,cAAc;QACjCW,QAAQZ;IACV;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/routes/rest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest, canAccessAdmin, UnauthorizedError } from 'payload'\n\nimport type { SanitizedStripePluginConfig } from '../types.js'\n\nimport { stripeProxy } from '../utilities/stripeProxy.js'\n\nexport const stripeREST = async (args: {\n pluginConfig: SanitizedStripePluginConfig\n req: PayloadRequest\n}): Promise<Response> => {\n const { pluginConfig, req } = args\n\n try {\n await addDataAndFileToRequest(req)\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n\n if (!req.user) {\n return errorResponse({ message: 'Unauthorized', status: 401 })\n }\n\n if (!pluginConfig.rest) {\n return unexpectedErrorResponse({\n err: new Error('Stripe REST handler called while disabled'),\n req,\n })\n }\n\n let hasAccess: boolean\n\n if (pluginConfig.rest.access) {\n try {\n hasAccess = await pluginConfig.rest.access({ req })\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n } else {\n try {\n hasAccess = await hasAdminAccess({ req })\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n }\n\n if (!hasAccess) {\n return errorResponse({ message: 'Forbidden', status: 403 })\n }\n\n const { stripeArgs, stripeMethod } = req.data ?? {}\n\n if (\n typeof stripeMethod !== 'string' ||\n stripeMethod.trim().length === 0 ||\n !pluginConfig.rest.allowedMethods.includes(stripeMethod)\n ) {\n return errorResponse({ message: 'Invalid request', status: 400 })\n }\n\n if (!Array.isArray(stripeArgs)) {\n return errorResponse({ message: 'Invalid request', status: 400 })\n }\n\n try {\n const responseJSON = await stripeProxy({\n stripeArgs,\n stripeMethod,\n stripeSecretKey: pluginConfig.stripeSecretKey,\n })\n\n return Response.json(responseJSON, { status: responseJSON.status })\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n}\n\nconst hasAdminAccess = async ({ req }: { req: PayloadRequest }): Promise<boolean> => {\n try {\n await canAccessAdmin({ req })\n return true\n } catch (err) {\n if (err instanceof UnauthorizedError) {\n return false\n }\n\n throw err\n }\n}\n\nconst errorResponse = ({ message, status }: { message: string; status: number }): Response =>\n Response.json({ message }, { status })\n\nconst unexpectedErrorResponse = ({ err, req }: { err: unknown; req: PayloadRequest }): Response => {\n req.payload.logger.error({\n err,\n msg: 'An unexpected error occurred in the Stripe plugin REST handler.',\n })\n\n return errorResponse({ message: 'Internal server error', status: 500 })\n}\n"],"names":["addDataAndFileToRequest","canAccessAdmin","UnauthorizedError","stripeProxy","stripeREST","args","pluginConfig","req","err","unexpectedErrorResponse","user","errorResponse","message","status","rest","Error","hasAccess","access","hasAdminAccess","stripeArgs","stripeMethod","data","trim","length","allowedMethods","includes","Array","isArray","responseJSON","stripeSecretKey","Response","json","payload","logger","error","msg"],"mappings":"AAEA,SAASA,uBAAuB,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,UAAS;AAIpF,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,OAAO,MAAMC,aAAa,OAAOC;IAI/B,MAAM,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGF;IAE9B,IAAI;QACF,MAAML,wBAAwBO;IAChC,EAAE,OAAOC,KAAK;QACZ,OAAOC,wBAAwB;YAAED;YAAKD;QAAI;IAC5C;IAEA,IAAI,CAACA,IAAIG,IAAI,EAAE;QACb,OAAOC,cAAc;YAAEC,SAAS;YAAgBC,QAAQ;QAAI;IAC9D;IAEA,IAAI,CAACP,aAAaQ,IAAI,EAAE;QACtB,OAAOL,wBAAwB;YAC7BD,KAAK,IAAIO,MAAM;YACfR;QACF;IACF;IAEA,IAAIS;IAEJ,IAAIV,aAAaQ,IAAI,CAACG,MAAM,EAAE;QAC5B,IAAI;YACFD,YAAY,MAAMV,aAAaQ,IAAI,CAACG,MAAM,CAAC;gBAAEV;YAAI;QACnD,EAAE,OAAOC,KAAK;YACZ,OAAOC,wBAAwB;gBAAED;gBAAKD;YAAI;QAC5C;IACF,OAAO;QACL,IAAI;YACFS,YAAY,MAAME,eAAe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,CAAC;QACvB1B;QACA2B,KAAK;IACP;IAEA,OAAOxB,cAAc;QAAEC,SAAS;QAAyBC,QAAQ;IAAI;AACvE"}
package/dist/types.d.ts CHANGED
@@ -21,19 +21,26 @@ export type SyncConfig = {
21
21
  stripeResourceType: 'customers' | 'products';
22
22
  stripeResourceTypeSingular: 'customer' | 'product';
23
23
  };
24
+ export type StripeRESTAccess = (args: {
25
+ req: PayloadRequest;
26
+ }) => boolean | Promise<boolean>;
27
+ export type StripeRESTConfig = {
28
+ access?: StripeRESTAccess;
29
+ allowedMethods: readonly string[];
30
+ };
24
31
  export type StripePluginConfig = {
25
32
  isTestKey?: boolean;
26
33
  logs?: boolean;
27
- /** @default false */
28
- rest?: boolean;
34
+ rest?: StripeRESTConfig;
29
35
  stripeSecretKey: string;
30
36
  stripeWebhooksEndpointSecret?: string;
31
37
  sync?: SyncConfig[];
32
38
  webhooks?: StripeWebhookHandler | StripeWebhookHandlers;
33
39
  };
34
40
  export type SanitizedStripePluginConfig = {
41
+ rest?: StripeRESTConfig;
35
42
  sync: SyncConfig[];
36
- } & StripePluginConfig;
43
+ } & Omit<StripePluginConfig, 'rest' | 'sync'>;
37
44
  export type StripeProxy = (args: {
38
45
  stripeArgs: any[];
39
46
  stripeMethod: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,IAAI,aAAa,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAC/F,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAA;AAEhC,MAAM,MAAM,oBAAoB,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,IAAI,EAAE;IACjD,MAAM,EAAE,aAAa,CAAA;IACrB,KAAK,EAAE,CAAC,CAAA;IACR,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,CAAC,EAAE,kBAAkB,CAAA;IACjC,GAAG,EAAE,cA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nB,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,IAAI,CAAC,EAAE,gBAAgB,CAAA;IACvB,eAAe,EAAE,MAAM,CAAA;IACvB,4BAA4B,CAAC,EAAE,MAAM,CAAA;IACrC,IAAI,CAAC,EAAE,UAAU,EAAE,CAAA;IACnB,QAAQ,CAAC,EAAE,oBAAoB,GAAG,qBAAqB,CAAA;CACxD,CAAA;AAED,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,CAAC,EAAE,gBAAgB,CAAA;IACvB,IAAI,EAAE,UAAU,EAAE,CAAA;CACnB,GAAG,IAAI,CAAC,kBAAkB,EAAE,MAAM,GAAG,MAAM,CAAC,CAAA;AAE7C,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE;IAC/B,UAAU,EAAE,GAAG,EAAE,CAAA;IACjB,YAAY,EAAE,MAAM,CAAA;IACpB,eAAe,EAAE,MAAM,CAAA;CACxB,KAAK,OAAO,CAAC;IACZ,IAAI,CAAC,EAAE,GAAG,CAAA;IACV,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;CACf,CAAC,CAAA"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug, Payload, Config as PayloadConfig, PayloadRequest } from 'payload'\nimport type Stripe from 'stripe'\n\nexport type StripeWebhookHandler<T = any> = (args: {\n config: PayloadConfig\n event: T\n payload: Payload\n pluginConfig?: StripePluginConfig\n req: PayloadRequest\n stripe: Stripe\n}) => Promise<void> | void\n\nexport type StripeWebhookHandlers = {\n [webhookName: string]: StripeWebhookHandler\n}\n\nexport type FieldSyncConfig = {\n fieldPath: string\n stripeProperty: string\n}\n\nexport type SyncConfig = {\n collection: CollectionSlug\n fields: FieldSyncConfig[]\n stripeResourceType: 'customers' | 'products' // TODO: get this from Stripe types\n stripeResourceTypeSingular: 'customer' | 'product' // TODO: there must be a better way to do this\n}\n\nexport type StripePluginConfig = {\n isTestKey?: boolean\n logs?: boolean\n /** @default false */\n rest?: boolean\n stripeSecretKey: string\n stripeWebhooksEndpointSecret?: string\n sync?: SyncConfig[]\n webhooks?: StripeWebhookHandler | StripeWebhookHandlers\n}\n\nexport type SanitizedStripePluginConfig = {\n sync: SyncConfig[] // convert to required\n} & StripePluginConfig\n\nexport type StripeProxy = (args: {\n stripeArgs: any[]\n stripeMethod: string\n stripeSecretKey: string\n}) => Promise<{\n data?: any\n message?: string\n status: number\n}>\n"],"names":[],"mappings":"AA2CA,WAQE"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug, Payload, Config as PayloadConfig, PayloadRequest } from 'payload'\nimport type Stripe from 'stripe'\n\nexport type StripeWebhookHandler<T = any> = (args: {\n config: PayloadConfig\n event: T\n payload: Payload\n pluginConfig?: StripePluginConfig\n req: PayloadRequest\n stripe: Stripe\n}) => Promise<void> | void\n\nexport type StripeWebhookHandlers = {\n [webhookName: string]: StripeWebhookHandler\n}\n\nexport type FieldSyncConfig = {\n fieldPath: string\n stripeProperty: string\n}\n\nexport type SyncConfig = {\n collection: CollectionSlug\n fields: FieldSyncConfig[]\n stripeResourceType: 'customers' | 'products' // TODO: get this from Stripe types\n stripeResourceTypeSingular: 'customer' | 'product' // TODO: there must be a better way to do this\n}\n\nexport type StripeRESTAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type StripeRESTConfig = {\n access?: StripeRESTAccess\n allowedMethods: readonly string[]\n}\n\nexport type StripePluginConfig = {\n isTestKey?: boolean\n logs?: boolean\n rest?: StripeRESTConfig\n stripeSecretKey: string\n stripeWebhooksEndpointSecret?: string\n sync?: SyncConfig[]\n webhooks?: StripeWebhookHandler | StripeWebhookHandlers\n}\n\nexport type SanitizedStripePluginConfig = {\n rest?: StripeRESTConfig\n sync: SyncConfig[]\n} & Omit<StripePluginConfig, 'rest' | 'sync'>\n\nexport type StripeProxy = (args: {\n stripeArgs: any[]\n stripeMethod: string\n stripeSecretKey: string\n}) => Promise<{\n data?: any\n message?: string\n status: number\n}>\n"],"names":[],"mappings":"AAkDA,WAQE"}
@@ -1,2 +1,8 @@
1
+ import type { FieldSyncConfig } from '../types.js';
1
2
  export declare const deepen: (obj: Record<string, any>) => Record<string, any>;
3
+ export declare const getSyncedFields: ({ data, fields, source, }: {
4
+ data: object;
5
+ fields: FieldSyncConfig[];
6
+ source: 'payload' | 'stripe';
7
+ }) => Record<string, unknown>;
2
8
  //# sourceMappingURL=deepen.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deepen.d.ts","sourceRoot":"","sources":["../../src/utilities/deepen.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,MAAM,QAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAiBnE,CAAA"}
1
+ {"version":3,"file":"deepen.d.ts","sourceRoot":"","sources":["../../src/utilities/deepen.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,eAAO,MAAM,MAAM,QAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAwBnE,CAAA;AAED,eAAO,MAAM,eAAe,8BAIzB;IACD,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,eAAe,EAAE,CAAA;IACzB,MAAM,EAAE,SAAS,GAAG,QAAQ,CAAA;CAC7B,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAczB,CAAA"}
@@ -1,21 +1,51 @@
1
1
  // converts an object of dot notation keys to a nested object
2
2
  // i.e. { 'price.stripePriceID': '123' } to { price: { stripePriceID: '123' } }
3
+ import { hasUnsupportedFieldPathSegment, setOwnProperty } from 'payload/shared';
3
4
  export const deepen = (obj)=>{
4
5
  const result = {};
5
- for(const key in obj){
6
+ for (const key of Object.keys(obj)){
6
7
  const value = obj[key];
7
8
  const keys = key.split('.');
9
+ if (hasUnsupportedFieldPathSegment({
10
+ segments: keys
11
+ })) {
12
+ throw new Error('Invalid field path.');
13
+ }
8
14
  let current = result;
9
15
  keys.forEach((k, index)=>{
10
16
  if (index === keys.length - 1) {
11
- current[k] = value;
17
+ setOwnProperty({
18
+ key: k,
19
+ target: current,
20
+ value
21
+ });
12
22
  } else {
13
- current[k] = current[k] || {};
23
+ if (!Object.hasOwn(current, k) || current[k] === null || typeof current[k] !== 'object') {
24
+ setOwnProperty({
25
+ key: k,
26
+ target: current,
27
+ value: {}
28
+ });
29
+ }
14
30
  current = current[k];
15
31
  }
16
32
  });
17
33
  }
18
34
  return result;
19
35
  };
36
+ export const getSyncedFields = ({ data, fields, source })=>{
37
+ const flattened = Object.create(null);
38
+ for (const { fieldPath, stripeProperty } of fields){
39
+ const sourceProperty = source === 'payload' ? fieldPath : stripeProperty;
40
+ const targetProperty = source === 'payload' ? stripeProperty : fieldPath;
41
+ const value = Object.hasOwn(data, sourceProperty) ? data[sourceProperty] : undefined;
42
+ setOwnProperty({
43
+ key: targetProperty,
44
+ target: flattened,
45
+ value
46
+ });
47
+ }
48
+ return deepen(flattened);
49
+ };
20
50
 
21
51
  //# sourceMappingURL=deepen.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/deepen.ts"],"sourcesContent":["// converts an object of dot notation keys to a nested object\n// i.e. { 'price.stripePriceID': '123' } to { price: { stripePriceID: '123' } }\n\nexport const deepen = (obj: Record<string, any>): Record<string, any> => {\n const result: Record<string, any> = {}\n\n for (const key in obj) {\n const value = obj[key]\n const keys = key.split('.')\n let current = result\n keys.forEach((k, index) => {\n if (index === keys.length - 1) {\n current[k] = value\n } else {\n current[k] = current[k] || {}\n current = current[k]\n }\n })\n }\n return result\n}\n"],"names":["deepen","obj","result","key","value","keys","split","current","forEach","k","index","length"],"mappings":"AAAA,6DAA6D;AAC7D,+EAA+E;AAE/E,OAAO,MAAMA,SAAS,CAACC;IACrB,MAAMC,SAA8B,CAAC;IAErC,IAAK,MAAMC,OAAOF,IAAK;QACrB,MAAMG,QAAQH,GAAG,CAACE,IAAI;QACtB,MAAME,OAAOF,IAAIG,KAAK,CAAC;QACvB,IAAIC,UAAUL;QACdG,KAAKG,OAAO,CAAC,CAACC,GAAGC;YACf,IAAIA,UAAUL,KAAKM,MAAM,GAAG,GAAG;gBAC7BJ,OAAO,CAACE,EAAE,GAAGL;YACf,OAAO;gBACLG,OAAO,CAACE,EAAE,GAAGF,OAAO,CAACE,EAAE,IAAI,CAAC;gBAC5BF,UAAUA,OAAO,CAACE,EAAE;YACtB;QACF;IACF;IACA,OAAOP;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/deepen.ts"],"sourcesContent":["// converts an object of dot notation keys to a nested object\n// i.e. { 'price.stripePriceID': '123' } to { price: { stripePriceID: '123' } }\n\nimport { hasUnsupportedFieldPathSegment, setOwnProperty } from 'payload/shared'\n\nimport type { FieldSyncConfig } from '../types.js'\n\nexport const deepen = (obj: Record<string, any>): Record<string, any> => {\n const result: Record<string, any> = {}\n\n for (const key of Object.keys(obj)) {\n const value = obj[key]\n const keys = key.split('.')\n\n if (hasUnsupportedFieldPathSegment({ segments: keys })) {\n throw new Error('Invalid field path.')\n }\n\n let current = result\n keys.forEach((k, index) => {\n if (index === keys.length - 1) {\n setOwnProperty({ key: k, target: current, value })\n } else {\n if (!Object.hasOwn(current, k) || current[k] === null || typeof current[k] !== 'object') {\n setOwnProperty({ key: k, target: current, value: {} })\n }\n current = current[k]\n }\n })\n }\n return result\n}\n\nexport const getSyncedFields = ({\n data,\n fields,\n source,\n}: {\n data: object\n fields: FieldSyncConfig[]\n source: 'payload' | 'stripe'\n}): Record<string, unknown> => {\n const flattened = Object.create(null) as Record<string, unknown>\n\n for (const { fieldPath, stripeProperty } of fields) {\n const sourceProperty = source === 'payload' ? fieldPath : stripeProperty\n const targetProperty = source === 'payload' ? stripeProperty : fieldPath\n const value = Object.hasOwn(data, sourceProperty)\n ? (data as Record<string, unknown>)[sourceProperty]\n : undefined\n\n setOwnProperty({ key: targetProperty, target: flattened, value })\n }\n\n return deepen(flattened)\n}\n"],"names":["hasUnsupportedFieldPathSegment","setOwnProperty","deepen","obj","result","key","Object","keys","value","split","segments","Error","current","forEach","k","index","length","target","hasOwn","getSyncedFields","data","fields","source","flattened","create","fieldPath","stripeProperty","sourceProperty","targetProperty","undefined"],"mappings":"AAAA,6DAA6D;AAC7D,+EAA+E;AAE/E,SAASA,8BAA8B,EAAEC,cAAc,QAAQ,iBAAgB;AAI/E,OAAO,MAAMC,SAAS,CAACC;IACrB,MAAMC,SAA8B,CAAC;IAErC,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACJ,KAAM;QAClC,MAAMK,QAAQL,GAAG,CAACE,IAAI;QACtB,MAAME,OAAOF,IAAII,KAAK,CAAC;QAEvB,IAAIT,+BAA+B;YAAEU,UAAUH;QAAK,IAAI;YACtD,MAAM,IAAII,MAAM;QAClB;QAEA,IAAIC,UAAUR;QACdG,KAAKM,OAAO,CAAC,CAACC,GAAGC;YACf,IAAIA,UAAUR,KAAKS,MAAM,GAAG,GAAG;gBAC7Bf,eAAe;oBAAEI,KAAKS;oBAAGG,QAAQL;oBAASJ;gBAAM;YAClD,OAAO;gBACL,IAAI,CAACF,OAAOY,MAAM,CAACN,SAASE,MAAMF,OAAO,CAACE,EAAE,KAAK,QAAQ,OAAOF,OAAO,CAACE,EAAE,KAAK,UAAU;oBACvFb,eAAe;wBAAEI,KAAKS;wBAAGG,QAAQL;wBAASJ,OAAO,CAAC;oBAAE;gBACtD;gBACAI,UAAUA,OAAO,CAACE,EAAE;YACtB;QACF;IACF;IACA,OAAOV;AACT,EAAC;AAED,OAAO,MAAMe,kBAAkB,CAAC,EAC9BC,IAAI,EACJC,MAAM,EACNC,MAAM,EAKP;IACC,MAAMC,YAAYjB,OAAOkB,MAAM,CAAC;IAEhC,KAAK,MAAM,EAAEC,SAAS,EAAEC,cAAc,EAAE,IAAIL,OAAQ;QAClD,MAAMM,iBAAiBL,WAAW,YAAYG,YAAYC;QAC1D,MAAME,iBAAiBN,WAAW,YAAYI,iBAAiBD;QAC/D,MAAMjB,QAAQF,OAAOY,MAAM,CAACE,MAAMO,kBAC9B,AAACP,IAAgC,CAACO,eAAe,GACjDE;QAEJ5B,eAAe;YAAEI,KAAKuB;YAAgBX,QAAQM;YAAWf;QAAM;IACjE;IAEA,OAAON,OAAOqB;AAChB,EAAC"}
@@ -0,0 +1,5 @@
1
+ import type { StripeRESTConfig } from '../types.js';
2
+ export declare const sanitizeStripeRESTConfig: ({ rest, }: {
3
+ rest: unknown;
4
+ }) => StripeRESTConfig | undefined;
5
+ //# sourceMappingURL=sanitizeStripeRESTConfig.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitizeStripeRESTConfig.d.ts","sourceRoot":"","sources":["../../src/utilities/sanitizeStripeRESTConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAKrE,eAAO,MAAM,wBAAwB,cAElC;IACD,IAAI,EAAE,OAAO,CAAA;CACd,KAAG,gBAAgB,GAAG,SA8BtB,CAAA"}
@@ -0,0 +1,25 @@
1
+ const migrationError = 'The Stripe REST endpoint now requires an object with a non-empty allowedMethods array of exact method names.';
2
+ export const sanitizeStripeRESTConfig = ({ rest })=>{
3
+ if (rest === undefined || rest === false) {
4
+ return undefined;
5
+ }
6
+ if (typeof rest !== 'object' || rest === null || Array.isArray(rest) || !('allowedMethods' in rest) || !Array.isArray(rest.allowedMethods)) {
7
+ throw new Error(migrationError);
8
+ }
9
+ const access = 'access' in rest ? rest.access : undefined;
10
+ if (rest.allowedMethods.length === 0 || rest.allowedMethods.some((method)=>typeof method !== 'string' || method.trim().length === 0 || method.includes('*')) || access !== undefined && !isStripeRESTAccess(access)) {
11
+ throw new Error(migrationError);
12
+ }
13
+ const allowedMethods = Object.freeze([
14
+ ...new Set(rest.allowedMethods)
15
+ ]);
16
+ return access === undefined ? {
17
+ allowedMethods
18
+ } : {
19
+ access,
20
+ allowedMethods
21
+ };
22
+ };
23
+ const isStripeRESTAccess = (access)=>typeof access === 'function';
24
+
25
+ //# sourceMappingURL=sanitizeStripeRESTConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/sanitizeStripeRESTConfig.ts"],"sourcesContent":["import type { StripeRESTAccess, StripeRESTConfig } from '../types.js'\n\nconst migrationError =\n 'The Stripe REST endpoint now requires an object with a non-empty allowedMethods array of exact method names.'\n\nexport const sanitizeStripeRESTConfig = ({\n rest,\n}: {\n rest: unknown\n}): StripeRESTConfig | undefined => {\n if (rest === undefined || rest === false) {\n return undefined\n }\n\n if (\n typeof rest !== 'object' ||\n rest === null ||\n Array.isArray(rest) ||\n !('allowedMethods' in rest) ||\n !Array.isArray(rest.allowedMethods)\n ) {\n throw new Error(migrationError)\n }\n\n const access = 'access' in rest ? rest.access : undefined\n\n if (\n rest.allowedMethods.length === 0 ||\n rest.allowedMethods.some(\n (method) => typeof method !== 'string' || method.trim().length === 0 || method.includes('*'),\n ) ||\n (access !== undefined && !isStripeRESTAccess(access))\n ) {\n throw new Error(migrationError)\n }\n\n const allowedMethods = Object.freeze([...new Set(rest.allowedMethods)])\n\n return access === undefined ? { allowedMethods } : { access, allowedMethods }\n}\n\nconst isStripeRESTAccess = (access: unknown): access is StripeRESTAccess =>\n typeof access === 'function'\n"],"names":["migrationError","sanitizeStripeRESTConfig","rest","undefined","Array","isArray","allowedMethods","Error","access","length","some","method","trim","includes","isStripeRESTAccess","Object","freeze","Set"],"mappings":"AAEA,MAAMA,iBACJ;AAEF,OAAO,MAAMC,2BAA2B,CAAC,EACvCC,IAAI,EAGL;IACC,IAAIA,SAASC,aAAaD,SAAS,OAAO;QACxC,OAAOC;IACT;IAEA,IACE,OAAOD,SAAS,YAChBA,SAAS,QACTE,MAAMC,OAAO,CAACH,SACd,CAAE,CAAA,oBAAoBA,IAAG,KACzB,CAACE,MAAMC,OAAO,CAACH,KAAKI,cAAc,GAClC;QACA,MAAM,IAAIC,MAAMP;IAClB;IAEA,MAAMQ,SAAS,YAAYN,OAAOA,KAAKM,MAAM,GAAGL;IAEhD,IACED,KAAKI,cAAc,CAACG,MAAM,KAAK,KAC/BP,KAAKI,cAAc,CAACI,IAAI,CACtB,CAACC,SAAW,OAAOA,WAAW,YAAYA,OAAOC,IAAI,GAAGH,MAAM,KAAK,KAAKE,OAAOE,QAAQ,CAAC,SAEzFL,WAAWL,aAAa,CAACW,mBAAmBN,SAC7C;QACA,MAAM,IAAID,MAAMP;IAClB;IAEA,MAAMM,iBAAiBS,OAAOC,MAAM,CAAC;WAAI,IAAIC,IAAIf,KAAKI,cAAc;KAAE;IAEtE,OAAOE,WAAWL,YAAY;QAAEG;IAAe,IAAI;QAAEE;QAAQF;IAAe;AAC9E,EAAC;AAED,MAAMQ,qBAAqB,CAACN,SAC1B,OAAOA,WAAW"}
@@ -1 +1 @@
1
- {"version":3,"file":"handleCreatedOrUpdated.d.ts","sourceRoot":"","sources":["../../src/webhooks/handleCreatedOrUpdated.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAIpF,KAAK,sBAAsB,GAAG,CAC5B,IAAI,EAAE;IACJ,YAAY,EAAE,MAAM,CAAA;IACpB,UAAU,EAAE,2BAA2B,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;CACnD,GAAG,UAAU,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,KACpC,OAAO,CAAC,IAAI,CAAC,CAAA;AAElB,eAAO,MAAM,sBAAsB,EAAE,sBAyMpC,CAAA"}
1
+ {"version":3,"file":"handleCreatedOrUpdated.d.ts","sourceRoot":"","sources":["../../src/webhooks/handleCreatedOrUpdated.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAIpF,KAAK,sBAAsB,GAAG,CAC5B,IAAI,EAAE;IACJ,YAAY,EAAE,MAAM,CAAA;IACpB,UAAU,EAAE,2BAA2B,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;CACnD,GAAG,UAAU,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,KACpC,OAAO,CAAC,IAAI,CAAC,CAAA;AAElB,eAAO,MAAM,sBAAsB,EAAE,sBAqMpC,CAAA"}
@@ -1,5 +1,5 @@
1
1
  import { v4 as uuid } from 'uuid';
2
- import { deepen } from '../utilities/deepen.js';
2
+ import { deepen, getSyncedFields } from '../utilities/deepen.js';
3
3
  export const handleCreatedOrUpdated = async (args)=>{
4
4
  const { config: payloadConfig, event, payload, pluginConfig, resourceType, syncConfig } = args;
5
5
  const { logs } = pluginConfig || {};
@@ -37,11 +37,11 @@ export const handleCreatedOrUpdated = async (args)=>{
37
37
  });
38
38
  const foundDoc = payloadQuery.docs[0];
39
39
  // combine all properties of the Stripe doc and match their respective fields within the document
40
- let syncedData = syncConfig.fields.reduce((acc, field)=>{
41
- const { fieldPath, stripeProperty } = field;
42
- acc[fieldPath] = stripeDoc[stripeProperty];
43
- return acc;
44
- }, {});
40
+ let syncedData = getSyncedFields({
41
+ data: stripeDoc,
42
+ fields: syncConfig.fields,
43
+ source: 'stripe'
44
+ });
45
45
  syncedData = deepen({
46
46
  ...syncedData,
47
47
  skipSync: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/webhooks/handleCreatedOrUpdated.ts"],"sourcesContent":["import { v4 as uuid } from 'uuid'\n\nimport type { SanitizedStripePluginConfig, StripeWebhookHandler } from '../types.js'\n\nimport { deepen } from '../utilities/deepen.js'\n\ntype HandleCreatedOrUpdated = (\n args: {\n resourceType: string\n syncConfig: SanitizedStripePluginConfig['sync'][0]\n } & Parameters<StripeWebhookHandler>[0],\n) => Promise<void>\n\nexport const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => {\n const { config: payloadConfig, event, payload, pluginConfig, resourceType, syncConfig } = args\n\n const { logs } = pluginConfig || {}\n\n const stripeDoc: any = event?.data?.object || {}\n\n const { id: stripeID, object: eventObject } = stripeDoc\n\n // NOTE: the Stripe API does not nest fields, everything is an object at the top level\n // if the event object and resource type don't match, this change was not top-level\n const isNestedChange = eventObject !== resourceType\n\n // let stripeID = docID;\n // if (isNestedChange) {\n // const parentResource = stripeDoc[resourceType];\n // stripeID = parentResource;\n // }\n\n if (isNestedChange) {\n if (logs) {\n payload.logger.info(\n `- This change occurred on a nested field of ${resourceType}. Nested fields are not yet supported in auto-sync but can be manually setup.`,\n )\n }\n }\n\n if (!isNestedChange) {\n if (logs) {\n payload.logger.info(\n `- A new document was created or updated in Stripe, now syncing to Payload...`,\n )\n }\n\n const collectionSlug = syncConfig?.collection\n\n const isAuthCollection = Boolean(\n payloadConfig?.collections?.find((collection) => collection.slug === collectionSlug)?.auth,\n )\n\n // First, search for an existing document in Payload\n const payloadQuery = await payload.find({\n collection: collectionSlug,\n limit: 1,\n pagination: false,\n where: {\n stripeID: {\n equals: stripeID,\n },\n },\n })\n\n const foundDoc = payloadQuery.docs[0] as any\n\n // combine all properties of the Stripe doc and match their respective fields within the document\n let syncedData = syncConfig.fields.reduce(\n (acc, field) => {\n const { fieldPath, stripeProperty } = field\n\n acc[fieldPath] = stripeDoc[stripeProperty]\n return acc\n },\n {} as Record<string, any>,\n )\n\n syncedData = deepen({\n ...syncedData,\n skipSync: true,\n stripeID,\n })\n\n if (!foundDoc) {\n if (logs) {\n payload.logger.info(\n `- No existing '${collectionSlug}' document found with Stripe ID: '${stripeID}', creating new...`,\n )\n }\n\n // auth docs must use unique emails\n let authDoc = null\n\n if (isAuthCollection) {\n try {\n if (stripeDoc?.email) {\n const authQuery = await payload.find({\n collection: collectionSlug,\n limit: 1,\n pagination: false,\n where: {\n email: {\n equals: stripeDoc.email,\n },\n },\n })\n\n authDoc = authQuery.docs[0] as any\n\n if (authDoc) {\n if (logs) {\n payload.logger.info(\n `- Account already exists with e-mail: ${stripeDoc.email}, updating now...`,\n )\n }\n\n // account exists by email, so update it instead\n try {\n await payload.update({\n id: authDoc.id,\n collection: collectionSlug,\n data: syncedData,\n })\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully updated '${collectionSlug}' document in Payload with ID: '${authDoc.id}.'`,\n )\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : err\n if (logs) {\n payload.logger.error(\n `- Error updating existing '${collectionSlug}' document: ${msg}`,\n )\n }\n }\n }\n } else {\n if (logs) {\n payload.logger.error(\n `No email was provided from Stripe, cannot create new '${collectionSlug}' document.`,\n )\n }\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`Error looking up '${collectionSlug}' document in Payload: ${msg}`)\n }\n }\n }\n\n if (!isAuthCollection || (isAuthCollection && !authDoc)) {\n try {\n if (logs) {\n payload.logger.info(\n `- Creating new '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'.`,\n )\n }\n\n // generate a strong, unique password for the new user\n const password: string = uuid()\n\n await payload.create({\n collection: collectionSlug,\n data: {\n ...syncedData,\n password,\n passwordConfirm: password,\n },\n disableVerificationEmail: isAuthCollection ? true : undefined,\n })\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`Error creating new document in Payload: ${msg}`)\n }\n }\n }\n } else {\n if (logs) {\n payload.logger.info(\n `- Existing '${collectionSlug}' document found in Payload with Stripe ID: '${stripeID}', updating now...`,\n )\n }\n\n try {\n await payload.update({\n id: foundDoc.id,\n collection: collectionSlug,\n data: syncedData,\n })\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully updated '${collectionSlug}' document in Payload from Stripe ID: '${stripeID}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`Error updating '${collectionSlug}' document in Payload: ${msg}`)\n }\n }\n }\n }\n}\n"],"names":["v4","uuid","deepen","handleCreatedOrUpdated","args","config","payloadConfig","event","payload","pluginConfig","resourceType","syncConfig","logs","stripeDoc","data","object","id","stripeID","eventObject","isNestedChange","logger","info","collectionSlug","collection","isAuthCollection","Boolean","collections","find","slug","auth","payloadQuery","limit","pagination","where","equals","foundDoc","docs","syncedData","fields","reduce","acc","field","fieldPath","stripeProperty","skipSync","authDoc","email","authQuery","update","err","msg","Error","message","error","password","create","passwordConfirm","disableVerificationEmail","undefined"],"mappings":"AAAA,SAASA,MAAMC,IAAI,QAAQ,OAAM;AAIjC,SAASC,MAAM,QAAQ,yBAAwB;AAS/C,OAAO,MAAMC,yBAAiD,OAAOC;IACnE,MAAM,EAAEC,QAAQC,aAAa,EAAEC,KAAK,EAAEC,OAAO,EAAEC,YAAY,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGP;IAE1F,MAAM,EAAEQ,IAAI,EAAE,GAAGH,gBAAgB,CAAC;IAElC,MAAMI,YAAiBN,OAAOO,MAAMC,UAAU,CAAC;IAE/C,MAAM,EAAEC,IAAIC,QAAQ,EAAEF,QAAQG,WAAW,EAAE,GAAGL;IAE9C,sFAAsF;IACtF,mFAAmF;IACnF,MAAMM,iBAAiBD,gBAAgBR;IAEvC,wBAAwB;IACxB,wBAAwB;IACxB,oDAAoD;IACpD,+BAA+B;IAC/B,IAAI;IAEJ,IAAIS,gBAAgB;QAClB,IAAIP,MAAM;YACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,4CAA4C,EAAEX,aAAa,6EAA6E,CAAC;QAE9I;IACF;IAEA,IAAI,CAACS,gBAAgB;QACnB,IAAIP,MAAM;YACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,4EAA4E,CAAC;QAElF;QAEA,MAAMC,iBAAiBX,YAAYY;QAEnC,MAAMC,mBAAmBC,QACvBnB,eAAeoB,aAAaC,KAAK,C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EC,eAAe,uCAAuC,EAAEL,SAAS,EAAE,CAAC;oBAEvG;gBACF,EAAE,OAAOoC,OAAgB;oBACvB,MAAMH,MAAMG,iBAAiBF,QAAQE,MAAMD,OAAO,GAAGC;oBACrD,IAAIzC,MAAM;wBACRJ,QAAQY,MAAM,CAACiC,KAAK,CAAC,CAAC,wCAAwC,EAAEH,KAAK;oBACvE;gBACF;YACF;QACF,OAAO;YACL,IAAItC,MAAM;gBACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,YAAY,EAAEC,eAAe,6CAA6C,EAAEL,SAAS,kBAAkB,CAAC;YAE7G;YAEA,IAAI;gBACF,MAAMT,QAAQwC,MAAM,CAAC;oBACnBhC,IAAImB,SAASnB,EAAE;oBACfO,YAAYD;oBACZR,MAAMuB;gBACR;gBAEA,IAAIzB,MAAM;oBACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,wBAAwB,EAAEC,eAAe,uCAAuC,EAAEL,SAAS,EAAE,CAAC;gBAEnG;YACF,EAAE,OAAOoC,OAAgB;gBACvB,MAAMH,MAAMG,iBAAiBF,QAAQE,MAAMD,OAAO,GAAGC;gBACrD,IAAIzC,MAAM;oBACRJ,QAAQY,MAAM,CAACiC,KAAK,CAAC,CAAC,gBAAgB,EAAE/B,eAAe,uBAAuB,EAAE4B,KAAK;gBACvF;YACF;QACF;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/webhooks/handleCreatedOrUpdated.ts"],"sourcesContent":["import { v4 as uuid } from 'uuid'\n\nimport type { SanitizedStripePluginConfig, StripeWebhookHandler } from '../types.js'\n\nimport { deepen, getSyncedFields } from '../utilities/deepen.js'\n\ntype HandleCreatedOrUpdated = (\n args: {\n resourceType: string\n syncConfig: SanitizedStripePluginConfig['sync'][0]\n } & Parameters<StripeWebhookHandler>[0],\n) => Promise<void>\n\nexport const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => {\n const { config: payloadConfig, event, payload, pluginConfig, resourceType, syncConfig } = args\n\n const { logs } = pluginConfig || {}\n\n const stripeDoc: any = event?.data?.object || {}\n\n const { id: stripeID, object: eventObject } = stripeDoc\n\n // NOTE: the Stripe API does not nest fields, everything is an object at the top level\n // if the event object and resource type don't match, this change was not top-level\n const isNestedChange = eventObject !== resourceType\n\n // let stripeID = docID;\n // if (isNestedChange) {\n // const parentResource = stripeDoc[resourceType];\n // stripeID = parentResource;\n // }\n\n if (isNestedChange) {\n if (logs) {\n payload.logger.info(\n `- This change occurred on a nested field of ${resourceType}. Nested fields are not yet supported in auto-sync but can be manually setup.`,\n )\n }\n }\n\n if (!isNestedChange) {\n if (logs) {\n payload.logger.info(\n `- A new document was created or updated in Stripe, now syncing to Payload...`,\n )\n }\n\n const collectionSlug = syncConfig?.collection\n\n const isAuthCollection = Boolean(\n payloadConfig?.collections?.find((collection) => collection.slug === collectionSlug)?.auth,\n )\n\n // First, search for an existing document in Payload\n const payloadQuery = await payload.find({\n collection: collectionSlug,\n limit: 1,\n pagination: false,\n where: {\n stripeID: {\n equals: stripeID,\n },\n },\n })\n\n const foundDoc = payloadQuery.docs[0] as any\n\n // combine all properties of the Stripe doc and match their respective fields within the document\n let syncedData = getSyncedFields({\n data: stripeDoc,\n fields: syncConfig.fields,\n source: 'stripe',\n })\n\n syncedData = deepen({\n ...syncedData,\n skipSync: true,\n stripeID,\n })\n\n if (!foundDoc) {\n if (logs) {\n payload.logger.info(\n `- No existing '${collectionSlug}' document found with Stripe ID: '${stripeID}', creating new...`,\n )\n }\n\n // auth docs must use unique emails\n let authDoc = null\n\n if (isAuthCollection) {\n try {\n if (stripeDoc?.email) {\n const authQuery = await payload.find({\n collection: collectionSlug,\n limit: 1,\n pagination: false,\n where: {\n email: {\n equals: stripeDoc.email,\n },\n },\n })\n\n authDoc = authQuery.docs[0] as any\n\n if (authDoc) {\n if (logs) {\n payload.logger.info(\n `- Account already exists with e-mail: ${stripeDoc.email}, updating now...`,\n )\n }\n\n // account exists by email, so update it instead\n try {\n await payload.update({\n id: authDoc.id,\n collection: collectionSlug,\n data: syncedData,\n })\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully updated '${collectionSlug}' document in Payload with ID: '${authDoc.id}.'`,\n )\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : err\n if (logs) {\n payload.logger.error(\n `- Error updating existing '${collectionSlug}' document: ${msg}`,\n )\n }\n }\n }\n } else {\n if (logs) {\n payload.logger.error(\n `No email was provided from Stripe, cannot create new '${collectionSlug}' document.`,\n )\n }\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`Error looking up '${collectionSlug}' document in Payload: ${msg}`)\n }\n }\n }\n\n if (!isAuthCollection || (isAuthCollection && !authDoc)) {\n try {\n if (logs) {\n payload.logger.info(\n `- Creating new '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'.`,\n )\n }\n\n // generate a strong, unique password for the new user\n const password: string = uuid()\n\n await payload.create({\n collection: collectionSlug,\n data: {\n ...syncedData,\n password,\n passwordConfirm: password,\n },\n disableVerificationEmail: isAuthCollection ? true : undefined,\n })\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`Error creating new document in Payload: ${msg}`)\n }\n }\n }\n } else {\n if (logs) {\n payload.logger.info(\n `- Existing '${collectionSlug}' document found in Payload with Stripe ID: '${stripeID}', updating now...`,\n )\n }\n\n try {\n await payload.update({\n id: foundDoc.id,\n collection: collectionSlug,\n data: syncedData,\n })\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully updated '${collectionSlug}' document in Payload from Stripe ID: '${stripeID}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`Error updating '${collectionSlug}' document in Payload: ${msg}`)\n }\n }\n }\n }\n}\n"],"names":["v4","uuid","deepen","getSyncedFields","handleCreatedOrUpdated","args","config","payloadConfig","event","payload","pluginConfig","resourceType","syncConfig","logs","stripeDoc","data","object","id","stripeID","eventObject","isNestedChange","logger","info","collectionSlug","collection","isAuthCollection","Boolean","collections","find","slug","auth","payloadQuery","limit","pagination","where","equals","foundDoc","docs","syncedData","fields","source","skipSync","authDoc","email","authQuery","update","err","msg","Error","message","error","password","create","passwordConfirm","disableVerificationEmail","undefined"],"mappings":"AAAA,SAASA,MAAMC,IAAI,QAAQ,OAAM;AAIjC,SAASC,MAAM,EAAEC,eAAe,QAAQ,yBAAwB;AAShE,OAAO,MAAMC,yBAAiD,OAAOC;IACnE,MAAM,EAAEC,QAAQC,aAAa,EAAEC,KAAK,EAAEC,OAAO,EAAEC,YAAY,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGP;IAE1F,MAAM,EAAEQ,IAAI,EAAE,GAAGH,gBAAgB,CAAC;IAElC,MAAMI,YAAiBN,OAAOO,MAAMC,UAAU,CAAC;IAE/C,MAAM,EAAEC,IAAIC,QAAQ,EAAEF,QAAQG,WAAW,EAAE,GAAGL;IAE9C,sFAAsF;IACtF,mFAAmF;IACnF,MAAMM,iBAAiBD,gBAAgBR;IAEvC,wBAAwB;IACxB,wBAAwB;IACxB,oDAAoD;IACpD,+BAA+B;IAC/B,IAAI;IAEJ,IAAIS,gBAAgB;QAClB,IAAIP,MAAM;YACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,4CAA4C,EAAEX,aAAa,6EAA6E,CAAC;QAE9I;IACF;IAEA,IAAI,CAACS,gBAAgB;QACnB,IAAIP,MAAM;YACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,4EAA4E,CAAC;QAElF;QAEA,MAAMC,iBAAiBX,YAAYY;QAEnC,MAAMC,mBAAmBC,QACvBnB,eAAeoB,aAAaC,KAAK,CAACJ,aAAeA,WAAWK,IAAI,KAAKN,iBAAiBO;QAGxF,oDAAoD;QACpD,MAAMC,eAAe,MAAM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K,CAAC,CAAC,wCAAwC,EAAEH,KAAK;oBACvE;gBACF;YACF;QACF,OAAO;YACL,IAAIlC,MAAM;gBACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,YAAY,EAAEC,eAAe,6CAA6C,EAAEL,SAAS,kBAAkB,CAAC;YAE7G;YAEA,IAAI;gBACF,MAAMT,QAAQoC,MAAM,CAAC;oBACnB5B,IAAImB,SAASnB,EAAE;oBACfO,YAAYD;oBACZR,MAAMuB;gBACR;gBAEA,IAAIzB,MAAM;oBACRJ,QAAQY,MAAM,CAACC,IAAI,CACjB,CAAC,wBAAwB,EAAEC,eAAe,uCAAuC,EAAEL,SAAS,EAAE,CAAC;gBAEnG;YACF,EAAE,OAAOgC,OAAgB;gBACvB,MAAMH,MAAMG,iBAAiBF,QAAQE,MAAMD,OAAO,GAAGC;gBACrD,IAAIrC,MAAM;oBACRJ,QAAQY,MAAM,CAAC6B,KAAK,CAAC,CAAC,gBAAgB,EAAE3B,eAAe,uBAAuB,EAAEwB,KAAK;gBACvF;YACF;QACF;IACF;AACF,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-stripe",
3
- "version": "4.0.0-internal.d1cc1d3",
3
+ "version": "4.0.0-internal.d21c039",
4
4
  "description": "Stripe plugin for Payload",
5
5
  "keywords": [
6
6
  "payload",
@@ -55,19 +55,19 @@
55
55
  "lodash.get": "^4.4.2",
56
56
  "stripe": "^10.2.0",
57
57
  "uuid": "14.0.0",
58
- "@payloadcms/translations": "4.0.0-internal.d1cc1d3",
59
- "@payloadcms/ui": "4.0.0-internal.d1cc1d3"
58
+ "@payloadcms/translations": "4.0.0-internal.d21c039",
59
+ "@payloadcms/ui": "4.0.0-internal.d21c039"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/lodash.get": "^4.4.7",
63
63
  "@types/react": "19.2.14",
64
64
  "@types/react-dom": "19.2.3",
65
65
  "@payloadcms/eslint-config": "3.28.0",
66
- "@payloadcms/next": "4.0.0-internal.d1cc1d3",
67
- "payload": "4.0.0-internal.d1cc1d3"
66
+ "@payloadcms/next": "4.0.0-internal.d21c039",
67
+ "payload": "4.0.0-internal.d21c039"
68
68
  },
69
69
  "peerDependencies": {
70
- "payload": "4.0.0-internal.d1cc1d3"
70
+ "payload": "4.0.0-internal.d21c039"
71
71
  },
72
72
  "publishConfig": {
73
73
  "registry": "https://registry.npmjs.org/"
@@ -79,7 +79,7 @@
79
79
  "build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
80
80
  "build:types": "tsc --emitDeclarationOnly --outDir dist",
81
81
  "clean": "rimraf -g {dist,*.tsbuildinfo}",
82
- "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
82
+ "copyfiles": "copyfiles -u 1 -e \"**/*.spec.*\" \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
83
83
  "lint": "eslint .",
84
84
  "lint:fix": "eslint . --fix"
85
85
  }