@wix/cli-app 1.1.62 → 1.1.63

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 (91) hide show
  1. package/build/{CreateVersionCommand-IEF6U34E.js → CreateVersionCommand-HSZ5KOXI.js} +14 -14
  2. package/build/{DevCommand-SOODXUEP.js → DevCommand-U5VNLUWE.js} +17 -13
  3. package/build/DevCommand-U5VNLUWE.js.map +1 -0
  4. package/build/{GenerateCommand-ARNW73TM.js → GenerateCommand-EAOS2X3X.js} +7 -7
  5. package/build/{LogsCommand-7TW36YZX.js → LogsCommand-OW2ZNER5.js} +4 -4
  6. package/build/PreviewCommand-MMMYRI4Z.js +23 -0
  7. package/build/{ReleaseCommand-SB2WWSVP.js → ReleaseCommand-L4WZJXHC.js} +14 -14
  8. package/build/{ServeCommand-GZKF6AN3.js → ServeCommand-RR7E4CTH.js} +13 -13
  9. package/build/{build-LHCSCFBM.js → build-KQLNYCVG.js} +7 -7
  10. package/build/{chunk-YW2RBPPY.js → chunk-3I7X6TPV.js} +3 -3
  11. package/build/{chunk-4WKSS3PU.js → chunk-7I5LSGDI.js} +3 -3
  12. package/build/{chunk-6IX6CDWB.js → chunk-7XQDPLBO.js} +7 -7
  13. package/build/{chunk-PM4M3SGC.js → chunk-CQUQ6WJV.js} +2 -2
  14. package/build/chunk-CQUQ6WJV.js.map +1 -0
  15. package/build/{chunk-LMFNRK6X.js → chunk-DIA3AFPZ.js} +2 -2
  16. package/build/{chunk-KJR4P55M.js → chunk-EYB7PRAB.js} +2 -2
  17. package/build/{chunk-HKX5ODUN.js → chunk-FXVMZQC7.js} +3 -3
  18. package/build/{chunk-A3FHJ4EK.js → chunk-HAPDEIJZ.js} +3 -3
  19. package/build/{chunk-6US7335E.js → chunk-IB2EYESP.js} +3 -3
  20. package/build/{chunk-KCNEUOW2.js → chunk-NWRBK74T.js} +8 -8
  21. package/build/{chunk-UZXKDHQZ.js → chunk-OHPZ74IV.js} +5 -5
  22. package/build/{chunk-V75TFIXI.js → chunk-OV6Y7VX4.js} +4 -4
  23. package/build/{chunk-MTEB33GR.js → chunk-SFPBI2MM.js} +3 -3
  24. package/build/{chunk-KVM6MGID.js → chunk-SK3ICCEA.js} +3 -3
  25. package/build/{chunk-LULKQBSP.js → chunk-SXIV63HN.js} +425 -312
  26. package/build/chunk-SXIV63HN.js.map +1 -0
  27. package/build/{chunk-UE7LDQKD.js → chunk-VSQ4XHEB.js} +2 -2
  28. package/build/{chunk-5R5H3Y2D.js → chunk-XYNJZDSJ.js} +5 -5
  29. package/build/cloudflare-runtime/entry.js +1 -1
  30. package/build/cloudflare-runtime/getRegisteredExtensions.js +1 -1
  31. package/build/index.js +47 -32
  32. package/build/index.js.map +1 -1
  33. package/build/platform-sdk/chunk-7EYXEF6M.js +2 -0
  34. package/build/platform-sdk/chunk-7EYXEF6M.js.map +1 -0
  35. package/build/platform-sdk/chunk-BGTZ3RNN.js +2 -0
  36. package/build/platform-sdk/chunk-BGTZ3RNN.js.map +1 -0
  37. package/build/platform-sdk/chunk-DGX4CFXG.js +2 -0
  38. package/build/platform-sdk/chunk-DGX4CFXG.js.map +1 -0
  39. package/build/platform-sdk/chunk-XYIDODIB.js +2 -0
  40. package/build/platform-sdk/{chunk-VXQAZIAE.js.map → chunk-XYIDODIB.js.map} +1 -1
  41. package/build/platform-sdk/dashboard.js +1 -1
  42. package/build/platform-sdk/dashboard.js.map +1 -1
  43. package/build/platform-sdk/editor.js +5 -5
  44. package/build/platform-sdk/editor.js.map +1 -1
  45. package/build/platform-sdk/sdk-context.js +1 -1
  46. package/build/platform-sdk/sdk-context.js.map +1 -1
  47. package/build/platform-sdk/site.js +1 -1
  48. package/build/platform-sdk/site.js.map +1 -1
  49. package/build/platform-sdk/web-methods.js +1 -1
  50. package/build/platform-sdk/web-methods.js.map +1 -1
  51. package/build/{preview-ZAKEXAJH.js → preview-4UF7QRIS.js} +12 -12
  52. package/build/{render-command-XMQH723O.js → render-command-5DTSCPVY.js} +5 -5
  53. package/package.json +3 -3
  54. package/schemas/site-plugin.json +1 -1
  55. package/templates/web-method/dependencies.json +1 -1
  56. package/templates/web-method/files/placeholder.ts.ejs +1 -1
  57. package/build/DevCommand-SOODXUEP.js.map +0 -1
  58. package/build/PreviewCommand-ZZKRP2GF.js +0 -23
  59. package/build/chunk-LULKQBSP.js.map +0 -1
  60. package/build/chunk-PM4M3SGC.js.map +0 -1
  61. package/build/platform-sdk/chunk-3U6QUCP3.js +0 -2
  62. package/build/platform-sdk/chunk-3U6QUCP3.js.map +0 -1
  63. package/build/platform-sdk/chunk-FLUCZ5U6.js +0 -2
  64. package/build/platform-sdk/chunk-FLUCZ5U6.js.map +0 -1
  65. package/build/platform-sdk/chunk-VXQAZIAE.js +0 -2
  66. package/build/platform-sdk/chunk-ZM5O3GFB.js +0 -2
  67. package/build/platform-sdk/chunk-ZM5O3GFB.js.map +0 -1
  68. /package/build/{CreateVersionCommand-IEF6U34E.js.map → CreateVersionCommand-HSZ5KOXI.js.map} +0 -0
  69. /package/build/{GenerateCommand-ARNW73TM.js.map → GenerateCommand-EAOS2X3X.js.map} +0 -0
  70. /package/build/{LogsCommand-7TW36YZX.js.map → LogsCommand-OW2ZNER5.js.map} +0 -0
  71. /package/build/{PreviewCommand-ZZKRP2GF.js.map → PreviewCommand-MMMYRI4Z.js.map} +0 -0
  72. /package/build/{ReleaseCommand-SB2WWSVP.js.map → ReleaseCommand-L4WZJXHC.js.map} +0 -0
  73. /package/build/{ServeCommand-GZKF6AN3.js.map → ServeCommand-RR7E4CTH.js.map} +0 -0
  74. /package/build/{build-LHCSCFBM.js.map → build-KQLNYCVG.js.map} +0 -0
  75. /package/build/{chunk-YW2RBPPY.js.map → chunk-3I7X6TPV.js.map} +0 -0
  76. /package/build/{chunk-4WKSS3PU.js.map → chunk-7I5LSGDI.js.map} +0 -0
  77. /package/build/{chunk-6IX6CDWB.js.map → chunk-7XQDPLBO.js.map} +0 -0
  78. /package/build/{chunk-LMFNRK6X.js.map → chunk-DIA3AFPZ.js.map} +0 -0
  79. /package/build/{chunk-KJR4P55M.js.map → chunk-EYB7PRAB.js.map} +0 -0
  80. /package/build/{chunk-HKX5ODUN.js.map → chunk-FXVMZQC7.js.map} +0 -0
  81. /package/build/{chunk-A3FHJ4EK.js.map → chunk-HAPDEIJZ.js.map} +0 -0
  82. /package/build/{chunk-6US7335E.js.map → chunk-IB2EYESP.js.map} +0 -0
  83. /package/build/{chunk-KCNEUOW2.js.map → chunk-NWRBK74T.js.map} +0 -0
  84. /package/build/{chunk-UZXKDHQZ.js.map → chunk-OHPZ74IV.js.map} +0 -0
  85. /package/build/{chunk-V75TFIXI.js.map → chunk-OV6Y7VX4.js.map} +0 -0
  86. /package/build/{chunk-MTEB33GR.js.map → chunk-SFPBI2MM.js.map} +0 -0
  87. /package/build/{chunk-KVM6MGID.js.map → chunk-SK3ICCEA.js.map} +0 -0
  88. /package/build/{chunk-UE7LDQKD.js.map → chunk-VSQ4XHEB.js.map} +0 -0
  89. /package/build/{chunk-5R5H3Y2D.js.map → chunk-XYNJZDSJ.js.map} +0 -0
  90. /package/build/{preview-ZAKEXAJH.js.map → preview-4UF7QRIS.js.map} +0 -0
  91. /package/build/{render-command-XMQH723O.js.map → render-command-5DTSCPVY.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{a as r,c as _}from"./chunk-SBZEOPXX.js";var p={};_(p,{EventDefinition:()=>o,SERVICE_PLUGIN_ERROR_TYPE:()=>u,ServicePluginDefinition:()=>f});function o(i,e=!1,n=t=>t){return()=>({__type:"event-definition",type:i,isDomainEvent:e,transformations:n})}function f(i,e){return{__type:"service-plugin-definition",componentType:i,methods:e}}var u,v=r(()=>{"use strict";u="wix_spi_error"});export{o as a,u as b,p as c,v as d};
2
+ //# sourceMappingURL=chunk-7EYXEF6M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/@wix/sdk-types/build/browser/index.mjs"],"sourcesContent":["// src/event-handlers-modules.ts\nfunction EventDefinition(type, isDomainEvent = false, transformations = (x) => x) {\n return () => ({\n __type: \"event-definition\",\n type,\n isDomainEvent,\n transformations\n });\n}\n\n// src/service-plugins.ts\nfunction ServicePluginDefinition(componentType, methods) {\n return {\n __type: \"service-plugin-definition\",\n componentType,\n methods\n };\n}\nvar SERVICE_PLUGIN_ERROR_TYPE = \"wix_spi_error\";\nexport {\n EventDefinition,\n SERVICE_PLUGIN_ERROR_TYPE,\n ServicePluginDefinition\n};\n"],"mappings":"+CAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,8BAAAC,EAAA,4BAAAC,IACA,SAASF,EAAgBG,EAAMC,EAAgB,GAAOC,EAAmBC,GAAMA,EAAG,CAChF,MAAO,KAAO,CACZ,OAAQ,mBACR,KAAAH,EACA,cAAAC,EACA,gBAAAC,CACF,EACF,CAGA,SAASH,EAAwBK,EAAeC,EAAS,CACvD,MAAO,CACL,OAAQ,4BACR,cAAAD,EACA,QAAAC,CACF,CACF,CAjBA,IAkBIP,EAlBJQ,EAAAC,EAAA,kBAkBIT,EAA4B","names":["browser_exports","__export","EventDefinition","SERVICE_PLUGIN_ERROR_TYPE","ServicePluginDefinition","type","isDomainEvent","transformations","x","componentType","methods","init_browser","__esmMin"]}
@@ -0,0 +1,2 @@
1
+ import{wixContext as n}from"@wix/sdk-context";function d(o,t){return(...i)=>{let e=x();return e?e.initWixModules(o,t).apply(void 0,i):o.apply(void 0,i)}}function x(){let o=typeof $wixContext<"u"&&$wixContext.initWixModules?$wixContext.initWixModules:typeof globalThis.__wix_context__<"u"&&globalThis.__wix_context__.initWixModules?globalThis.__wix_context__.initWixModules:void 0;if(o)return{initWixModules(e,l){return r(()=>o(e,l))},fetchWithAuth(){throw new Error("fetchWithAuth is not available in this context")},graphql(){throw new Error("graphql is not available in this context")}};let t=typeof $wixContext<"u"?$wixContext.client:typeof n.client<"u"?n.client:typeof globalThis.__wix_context__<"u"?globalThis.__wix_context__.client:void 0,i=typeof $wixContext<"u"?$wixContext.elevatedClient:typeof n.elevatedClient<"u"?n.elevatedClient:typeof globalThis.__wix_context__<"u"?globalThis.__wix_context__.elevatedClient:void 0;if(!(!t&&!i))return{initWixModules(e,l){if(l){if(!i)throw new Error("An elevated client is required to use elevated modules. Make sure to initialize the Wix context with an elevated client before using elevated SDK modules");return r(()=>i.use(e))}if(!t)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return r(()=>t.use(e))},fetchWithAuth:(e,l)=>{if(!t)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return t.fetchWithAuth(e,l)},async graphql(e,l,u){if(!t)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return t.graphql(e,l,u)}}}function r(o){let t=globalThis.__wix_context__,i={client:n.client,elevatedClient:n.elevatedClient},e;globalThis.__wix_context__=void 0,n.client=void 0,n.elevatedClient=void 0,typeof $wixContext<"u"&&(e={client:$wixContext?.client,elevatedClient:$wixContext?.elevatedClient},delete $wixContext.client,delete $wixContext.elevatedClient);try{return o()}finally{globalThis.__wix_context__=t,n.client=i.client,n.elevatedClient=i.elevatedClient,typeof $wixContext<"u"&&($wixContext.client=e.client,$wixContext.elevatedClient=e.elevatedClient)}}export{d as a,r as b};
2
+ //# sourceMappingURL=chunk-BGTZ3RNN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/@wix/sdk/node_modules/@wix/sdk-runtime/build/context.js","../../../node_modules/@wix/sdk/node_modules/@wix/sdk-runtime/build/context-v2.js"],"sourcesContent":["import { wixContext } from '@wix/sdk-context';\nexport function resolveContext() {\n const oldContext = typeof $wixContext !== 'undefined' && $wixContext.initWixModules\n ? $wixContext.initWixModules\n : typeof globalThis.__wix_context__ !== 'undefined' &&\n globalThis.__wix_context__.initWixModules\n ? globalThis.__wix_context__.initWixModules\n : undefined;\n if (oldContext) {\n return {\n // @ts-expect-error\n initWixModules(modules, elevated) {\n return runWithoutContext(() => oldContext(modules, elevated));\n },\n fetchWithAuth() {\n throw new Error('fetchWithAuth is not available in this context');\n },\n graphql() {\n throw new Error('graphql is not available in this context');\n },\n };\n }\n const contextualClient = typeof $wixContext !== 'undefined'\n ? $wixContext.client\n : typeof wixContext.client !== 'undefined'\n ? wixContext.client\n : typeof globalThis.__wix_context__ !== 'undefined'\n ? globalThis.__wix_context__.client\n : undefined;\n const elevatedClient = typeof $wixContext !== 'undefined'\n ? $wixContext.elevatedClient\n : typeof wixContext.elevatedClient !== 'undefined'\n ? wixContext.elevatedClient\n : typeof globalThis.__wix_context__ !== 'undefined'\n ? globalThis.__wix_context__.elevatedClient\n : undefined;\n if (!contextualClient && !elevatedClient) {\n return;\n }\n return {\n initWixModules(wixModules, elevated) {\n if (elevated) {\n if (!elevatedClient) {\n throw new Error('An elevated client is required to use elevated modules. Make sure to initialize the Wix context with an elevated client before using elevated SDK modules');\n }\n return runWithoutContext(() => elevatedClient.use(wixModules));\n }\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return runWithoutContext(() => contextualClient.use(wixModules));\n },\n fetchWithAuth: (urlOrRequest, requestInit) => {\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return contextualClient.fetchWithAuth(urlOrRequest, requestInit);\n },\n async graphql(query, variables, opts) {\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return contextualClient.graphql(query, variables, opts);\n },\n };\n}\nexport function contextualizeHostModule(hostModule, prop) {\n return (...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(hostModule)[prop].apply(undefined, args);\n };\n}\nexport function contextualizeRESTModule(restModule, expectedArgsLength) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context\n .initWixModules(restModule, args[expectedArgsLength]?.suppressAuth ? true : false)\n .apply(undefined, args);\n });\n}\nexport function contextualizeEventDefinitionModule(eventDefinition) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(eventDefinition).apply(undefined, args);\n });\n}\nexport function contextualizeSerivcePluginModule(servicePlugin) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(servicePlugin).apply(undefined, args);\n });\n}\nexport * from './context-v2.js';\nexport function runWithoutContext(fn) {\n const globalContext = globalThis.__wix_context__;\n const moduleContext = {\n client: wixContext.client,\n elevatedClient: wixContext.elevatedClient,\n };\n let closureContext;\n globalThis.__wix_context__ = undefined;\n wixContext.client = undefined;\n wixContext.elevatedClient = undefined;\n if (typeof $wixContext !== 'undefined') {\n closureContext = {\n client: $wixContext?.client,\n elevatedClient: $wixContext?.elevatedClient,\n };\n delete $wixContext.client;\n delete $wixContext.elevatedClient;\n }\n try {\n return fn();\n }\n finally {\n globalThis.__wix_context__ = globalContext;\n wixContext.client = moduleContext.client;\n wixContext.elevatedClient = moduleContext.elevatedClient;\n if (typeof $wixContext !== 'undefined') {\n $wixContext.client = closureContext.client;\n $wixContext.elevatedClient = closureContext.elevatedClient;\n }\n }\n}\n","import { EventDefinition, ServicePluginDefinition, } from '@wix/sdk-types';\nimport { resolveContext } from './context.js';\nexport { EventDefinition, ServicePluginDefinition, };\nexport function contextualizeHostModuleV2(hostModule, props) {\n return {\n ...hostModule,\n ...Object.fromEntries(props.map((prop) => [\n prop,\n (...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context\n .initWixModules(hostModule)[prop].apply(undefined, args);\n },\n ])),\n };\n}\nexport function contextualizeRESTModuleV2(restModule, elevated) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n // @ts-expect-error - if there is no context, we want to behave like the original module\n return restModule.apply(undefined, args);\n }\n return (context\n .initWixModules(restModule, elevated)\n // @ts-expect-error - we know the args here are meant to be passed to the initalized module\n .apply(undefined, args));\n });\n}\nexport function contextualizeEventDefinitionModuleV2(eventDefinition) {\n const contextualMethod = ((...args) => {\n const context = resolveContext();\n if (!context) {\n // this line should throw, but this would be a breaking change for older SDK versions\n // this is because in wixClient there's code that calls any function it detects and checks\n // if it's an ambassador module (see isAmbassadorModule)\n return () => { };\n }\n return context.initWixModules(eventDefinition).apply(undefined, args);\n });\n contextualMethod.__type = eventDefinition.__type;\n contextualMethod.type = eventDefinition.type;\n contextualMethod.isDomainEvent = eventDefinition.isDomainEvent;\n contextualMethod.transformations = eventDefinition.transformations;\n return contextualMethod;\n}\nexport function contextualizeSerivcePluginModuleV2(servicePlugin) {\n const contextualMethod = ((...args) => {\n const context = resolveContext();\n if (!context) {\n // this line should throw, but this would be a breaking change for older SDK versions\n // this is because in wixClient there's code that calls any function it detects and checks\n // if it's an ambassador module (see isAmbassadorModule)\n return () => { };\n }\n return context.initWixModules(servicePlugin).apply(undefined, args);\n });\n contextualMethod.__type = servicePlugin.__type;\n contextualMethod.componentType = servicePlugin.componentType;\n contextualMethod.methods = servicePlugin.methods;\n return contextualMethod;\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,mBCmBpB,SAASC,EAA0BC,EAAYC,EAAU,CAC5D,MAAQ,IAAIC,IAAS,CACjB,IAAMC,EAAUC,EAAe,EAC/B,OAAKD,EAIGA,EACH,eAAeH,EAAYC,CAAQ,EAEnC,MAAM,OAAWC,CAAI,EALfF,EAAW,MAAM,OAAWE,CAAI,CAM/C,CACJ,CD9BO,SAASG,GAAiB,CAC7B,IAAMC,EAAa,OAAO,YAAgB,KAAe,YAAY,eAC/D,YAAY,eACZ,OAAO,WAAW,gBAAoB,KACpC,WAAW,gBAAgB,eACzB,WAAW,gBAAgB,eAC3B,OACV,GAAIA,EACA,MAAO,CAEH,eAA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xB,OAAO,YAAgB,MACvBC,EAAiB,CACb,OAAQ,aAAa,OACrB,eAAgB,aAAa,cACjC,EACA,OAAO,YAAY,OACnB,OAAO,YAAY,gBAEvB,GAAI,CACA,OAAOJ,EAAG,CACd,QACA,CACI,WAAW,gBAAkBC,EAC7BE,EAAW,OAASD,EAAc,OAClCC,EAAW,eAAiBD,EAAc,eACtC,OAAO,YAAgB,MACvB,YAAY,OAASE,EAAe,OACpC,YAAY,eAAiBA,EAAe,eAEpD,CACJ","names":["wixContext","contextualizeRESTModuleV2","restModule","elevated","args","context","resolveContext","resolveContext","oldContext","modules","elevated","runWithoutContext","contextualClient","wixContext","elevatedClient","wixModules","urlOrRequest","requestInit","query","variables","opts","runWithoutContext","fn","globalContext","moduleContext","wixContext","closureContext"]}
@@ -0,0 +1,2 @@
1
+ import{wixContext as l}from"@wix/sdk-context";function u(){let o=typeof $wixContext<"u"&&$wixContext.initWixModules?$wixContext.initWixModules:typeof globalThis.__wix_context__<"u"&&globalThis.__wix_context__.initWixModules?globalThis.__wix_context__.initWixModules:void 0;if(o)return{initWixModules(e,n){return r(()=>o(e,n))},fetchWithAuth(){throw new Error("fetchWithAuth is not available in this context")},graphql(){throw new Error("graphql is not available in this context")}};let t=typeof $wixContext<"u"?$wixContext.client:typeof l.client<"u"?l.client:typeof globalThis.__wix_context__<"u"?globalThis.__wix_context__.client:void 0,i=typeof $wixContext<"u"?$wixContext.elevatedClient:typeof l.elevatedClient<"u"?l.elevatedClient:typeof globalThis.__wix_context__<"u"?globalThis.__wix_context__.elevatedClient:void 0;if(!(!t&&!i))return{initWixModules(e,n){if(n){if(!i)throw new Error("An elevated client is required to use elevated modules. Make sure to initialize the Wix context with an elevated client before using elevated SDK modules");return r(()=>i.use(e))}if(!t)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return r(()=>t.use(e))},fetchWithAuth:(e,n)=>{if(!t)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return t.fetchWithAuth(e,n)},async graphql(e,n,a){if(!t)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return t.graphql(e,n,a)}}}function r(o){let t=globalThis.__wix_context__,i={client:l.client,elevatedClient:l.elevatedClient},e;globalThis.__wix_context__=void 0,l.client=void 0,l.elevatedClient=void 0,typeof $wixContext<"u"&&(e={client:$wixContext?.client,elevatedClient:$wixContext?.elevatedClient},delete $wixContext.client,delete $wixContext.elevatedClient);try{return o()}finally{globalThis.__wix_context__=t,l.client=i.client,l.elevatedClient=i.elevatedClient,typeof $wixContext<"u"&&($wixContext.client=e.client,$wixContext.elevatedClient=e.elevatedClient)}}function x(o,t){return{...o,...Object.fromEntries(t.map(i=>[i,(...e)=>{let n=u();if(!n)throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");return n.initWixModules(o)[i].apply(void 0,e)}]))}}function h(o){return x({__type:"host",create:t=>Object.entries(o).reduce((i,[e,n])=>({...i,[e]:n(t)}),{})},Object.keys(o))}export{h as a};
2
+ //# sourceMappingURL=chunk-DGX4CFXG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/@wix/sdk-runtime/build/context.js","../../../node_modules/@wix/sdk-runtime/build/context-v2.js","../../../node_modules/@wix/sdk-runtime/build/host-modules.js"],"sourcesContent":["import { wixContext } from '@wix/sdk-context';\nexport function resolveContext() {\n const oldContext = typeof $wixContext !== 'undefined' && $wixContext.initWixModules\n ? $wixContext.initWixModules\n : typeof globalThis.__wix_context__ !== 'undefined' &&\n globalThis.__wix_context__.initWixModules\n ? globalThis.__wix_context__.initWixModules\n : undefined;\n if (oldContext) {\n return {\n // @ts-expect-error\n initWixModules(modules, elevated) {\n return runWithoutContext(() => oldContext(modules, elevated));\n },\n fetchWithAuth() {\n throw new Error('fetchWithAuth is not available in this context');\n },\n graphql() {\n throw new Error('graphql is not available in this context');\n },\n };\n }\n const contextualClient = typeof $wixContext !== 'undefined'\n ? $wixContext.client\n : typeof wixContext.client !== 'undefined'\n ? wixContext.client\n : typeof globalThis.__wix_context__ !== 'undefined'\n ? globalThis.__wix_context__.client\n : undefined;\n const elevatedClient = typeof $wixContext !== 'undefined'\n ? $wixContext.elevatedClient\n : typeof wixContext.elevatedClient !== 'undefined'\n ? wixContext.elevatedClient\n : typeof globalThis.__wix_context__ !== 'undefined'\n ? globalThis.__wix_context__.elevatedClient\n : undefined;\n if (!contextualClient && !elevatedClient) {\n return;\n }\n return {\n initWixModules(wixModules, elevated) {\n if (elevated) {\n if (!elevatedClient) {\n throw new Error('An elevated client is required to use elevated modules. Make sure to initialize the Wix context with an elevated client before using elevated SDK modules');\n }\n return runWithoutContext(() => elevatedClient.use(wixModules));\n }\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return runWithoutContext(() => contextualClient.use(wixModules));\n },\n fetchWithAuth: (urlOrRequest, requestInit) => {\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return contextualClient.fetchWithAuth(urlOrRequest, requestInit);\n },\n async graphql(query, variables, opts) {\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return contextualClient.graphql(query, variables, opts);\n },\n };\n}\nexport function contextualizeHostModule(hostModule, prop) {\n return (...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(hostModule)[prop].apply(undefined, args);\n };\n}\nexport function contextualizeRESTModule(restModule, expectedArgsLength) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context\n .initWixModules(restModule, args[expectedArgsLength]?.suppressAuth ? true : false)\n .apply(undefined, args);\n });\n}\nexport function contextualizeEventDefinitionModule(eventDefinition) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(eventDefinition).apply(undefined, args);\n });\n}\nexport function contextualizeSerivcePluginModule(servicePlugin) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(servicePlugin).apply(undefined, args);\n });\n}\nexport * from './context-v2.js';\nexport function runWithoutContext(fn) {\n const globalContext = globalThis.__wix_context__;\n const moduleContext = {\n client: wixContext.client,\n elevatedClient: wixContext.elevatedClient,\n };\n let closureContext;\n globalThis.__wix_context__ = undefined;\n wixContext.client = undefined;\n wixContext.elevatedClient = undefined;\n if (typeof $wixContext !== 'undefined') {\n closureContext = {\n client: $wixContext?.client,\n elevatedClient: $wixContext?.elevatedClient,\n };\n delete $wixContext.client;\n delete $wixContext.elevatedClient;\n }\n try {\n return fn();\n }\n finally {\n globalThis.__wix_context__ = globalContext;\n wixContext.client = moduleContext.client;\n wixContext.elevatedClient = moduleContext.elevatedClient;\n if (typeof $wixContext !== 'undefined') {\n $wixContext.client = closureContext.client;\n $wixContext.elevatedClient = closureContext.elevatedClient;\n }\n }\n}\n","import { EventDefinition, ServicePluginDefinition, } from '@wix/sdk-types';\nimport { resolveContext } from './context.js';\nexport { EventDefinition, ServicePluginDefinition, };\nexport function contextualizeHostModuleV2(hostModule, props) {\n return {\n ...hostModule,\n ...Object.fromEntries(props.map((prop) => [\n prop,\n (...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context\n .initWixModules(hostModule)[prop].apply(undefined, args);\n },\n ])),\n };\n}\nexport function contextualizeRESTModuleV2(restModule, elevated) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n // @ts-expect-error - if there is no context, we want to behave like the original module\n return restModule.apply(undefined, args);\n }\n return (context\n .initWixModules(restModule, elevated)\n // @ts-expect-error - we know the args here are meant to be passed to the initalized module\n .apply(undefined, args));\n });\n}\nexport function contextualizeEventDefinitionModuleV2(eventDefinition) {\n const contextualMethod = ((...args) => {\n const context = resolveContext();\n if (!context) {\n // this line should throw, but this would be a breaking change for older SDK versions\n // this is because in wixClient there's code that calls any function it detects and checks\n // if it's an ambassador module (see isAmbassadorModule)\n return () => { };\n }\n return context.initWixModules(eventDefinition).apply(undefined, args);\n });\n contextualMethod.__type = eventDefinition.__type;\n contextualMethod.type = eventDefinition.type;\n contextualMethod.isDomainEvent = eventDefinition.isDomainEvent;\n contextualMethod.transformations = eventDefinition.transformations;\n return contextualMethod;\n}\nexport function contextualizeSerivcePluginModuleV2(servicePlugin) {\n const contextualMethod = ((...args) => {\n const context = resolveContext();\n if (!context) {\n // this line should throw, but this would be a breaking change for older SDK versions\n // this is because in wixClient there's code that calls any function it detects and checks\n // if it's an ambassador module (see isAmbassadorModule)\n return () => { };\n }\n return context.initWixModules(servicePlugin).apply(undefined, args);\n });\n contextualMethod.__type = servicePlugin.__type;\n contextualMethod.componentType = servicePlugin.componentType;\n contextualMethod.methods = servicePlugin.methods;\n return contextualMethod;\n}\n","import { contextualizeHostModuleV2 } from './context-v2.js';\nexport function createHostModule(hostModuleAPI) {\n return contextualizeHostModuleV2({\n __type: 'host',\n create: (host) => Object.entries(hostModuleAPI).reduce((acc, [key, fn]) => ({\n ...acc,\n [key]: fn(host),\n }), {}),\n }, Object.keys(hostModuleAPI));\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,mBACpB,SAASC,GAAiB,CAC7B,IAAMC,EAAa,OAAO,YAAgB,KAAe,YAAY,eAC/D,YAAY,eACZ,OAAO,WAAW,gBAAoB,KACpC,WAAW,gBAAgB,eACzB,WAAW,gBAAgB,eAC3B,OACV,GAAIA,EACA,MAAO,CAEH,eAAeC,EAASC,EAAU,CAC9B,OAAOC,EAAkB,IAAMH,EAAWC,EAASC,CAAQ,CAAC,CAChE,EACA,eAAgB,CACZ,MAAM,IAAI,MAAM,gDAAgD,CACpE,EACA,SAAU,CACN,MAAM,IAAI,MAAM,0CAA0C,CAC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EAC7BE,EAAW,OAASD,EAAc,OAClCC,EAAW,eAAiBD,EAAc,eACtC,OAAO,YAAgB,MACvB,YAAY,OAASE,EAAe,OACpC,YAAY,eAAiBA,EAAe,eAEpD,CACJ,CCpIO,SAASC,EAA0BC,EAAYC,EAAO,CACzD,MAAO,CACH,GAAGD,EACH,GAAG,OAAO,YAAYC,EAAM,IAAKC,GAAS,CACtCA,EACA,IAAIC,IAAS,CACT,IAAMC,EAAUC,EAAe,EAC/B,GAAI,CAACD,EACD,MAAM,IAAI,MAAM,gGAAgG,EAEpH,OAAOA,EACF,eAAeJ,CAAU,EAAEE,CAAI,EAAE,MAAM,OAAWC,CAAI,CAC/D,CACJ,CAAC,CAAC,CACN,CACJ,CCjBO,SAASG,EAAiBC,EAAe,CAC5C,OAAOC,EAA0B,CAC7B,OAAQ,OACR,OAASC,GAAS,OAAO,QAAQF,CAAa,EAAE,OAAO,CAACG,EAAK,CAACC,EAAKC,CAAE,KAAO,CACxE,GAAGF,EACH,CAACC,CAAG,EAAGC,EAAGH,CAAI,CAClB,GAAI,CAAC,CAAC,CACV,EAAG,OAAO,KAAKF,CAAa,CAAC,CACjC","names":["wixContext","resolveContext","oldContext","modules","elevated","runWithoutContext","contextualClient","elevatedClient","wixModules","urlOrRequest","requestInit","query","variables","opts","runWithoutContext","fn","globalContext","moduleContext","wixContext","closureContext","contextualizeHostModuleV2","hostModule","props","prop","args","context","resolveContext","createHostModule","hostModuleAPI","contextualizeHostModuleV2","host","acc","key","fn"]}
@@ -0,0 +1,2 @@
1
+ import{b as x}from"./chunk-BGTZ3RNN.js";import{a as b,b as A,d as H}from"./chunk-7EYXEF6M.js";import{f as v}from"./chunk-SBZEOPXX.js";H();import{wixContext as N}from"@wix/sdk-context";var B=e=>{switch(e){case"get":case"GET":return"GET";case"post":case"POST":return"POST";case"put":case"PUT":return"PUT";case"delete":case"DELETE":return"DELETE";case"patch":case"PATCH":return"PATCH";case"head":case"HEAD":return"HEAD";case"options":case"OPTIONS":return"OPTIONS";default:throw new Error(`Unknown method: ${e}`)}},P=e=>a=>async s=>{let d,r=t=>{if(d=e(s)(t),d.url===void 0)throw new Error("Url was not successfully created for this request, please reach out to support channels for assistance.");let{method:i,url:o,params:p}=d;return{...d,method:B(i),url:o,data:d.data,params:p}};try{let t=await a.request(r);if(d===void 0)throw new Error("Request options were not created for this request, please reach out to support channels for assistance.");let i=Array.isArray(d.transformResponse)?d.transformResponse:[d.transformResponse],o=t.data;return i.forEach(p=>{p&&(o=p(t.data,t.headers))}),o}catch(t){throw typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"&&t.response!==null&&"data"in t.response?t.response.data:t}},M=e=>e.__isAmbassador?!0:!!e().__isAmbassador;var R="__metadata",w="www.wixapis.com";var g=class extends Error{constructor(s,d){super(s);v(this,"message");v(this,"response");this.message=s,this.response=d}async details(){let s=await this.response.json();return D(this.response.status,s?.message,s?.details,{requestId:this.response.headers.get("X-Wix-Request-Id"),details:s})}},D=(e,a,s,d)=>({details:{...!s?.validationError&&{applicationError:{description:a,code:e,data:d}},...s},message:a});var C=e=>e?.method&&["post","put","patch"].includes(e.method.toLocaleLowerCase())&&e.body?{"Content-Type":"application/json"}:{},U=e=>e&&typeof e=="object"&&!Array.isArray(e);var j=e=>e.__type==="host";function S(e,a){return e.create(a)}var G="x-wix-bi-gateway";function W(e,a,s){return{[G]:F({environment:`js-sdk${s?`-${s}`:""}`,"package-name":e.packageName??a?.PACKAGE_NAME,"method-fqn":e.methodFqn,entity:e.entityFqdn})}}function F(e){return Object.entries(e).filter(([a,s])=>!!s).map(([a,s])=>`${a}=${s}`).join(",")}function I(e,a,s,d,r,t,i){return x(()=>e({request:async o=>{let p=o({host:t?.HTTPHost||w}),c=p;c.method==="GET"&&c.fallback?.length&&c.params.toString().length>4e3&&(c=p.fallback[0]);let y=`https://${t?.HTTPHost??w}${c.url}`;c.params&&c.params.toString()&&(y+=`?${c.params.toString()}`);try{let u=W(p,a,i),n=await s(y,{method:c.method,...c.data&&{body:JSON.stringify(c.data)},headers:{...u}});if(n.status!==200){let h=null;try{h=await n.json()}catch{}throw V(n.status,h?.message,h?.details,{requestId:n.headers.get("X-Wix-Request-Id"),details:h})}return{data:await n.json(),headers:n.headers,status:n.status,statusText:n.statusText}}catch(u){throw u.message?.includes("fetch is not defined")&&console.error("Node.js v18+ is required"),u}},fetchWithAuth:s,wixAPIFetch:d,getActiveToken:r}))}var V=(e,a,s,d)=>({response:{data:{details:{...!s?.validationError&&{applicationError:{description:a,code:e,data:d}},...s},message:a},status:e}});H();function _(){return{emit(e,...a){for(let s=0,d=this.events[e]||[],r=d.length;s<r;s++)d[s](...a)},events:{},on(e,a){return(this.events[e]||=[]).push(a),()=>{this.events[e]=this.events[e]?.filter(s=>a!==s)}}}}var J=e=>e.__type==="event-definition";function $(e,a,s,d){let r;if(e.isDomainEvent){let i=s,{deletedEvent:o,actionEvent:p,createdEvent:c,updatedEvent:f,...y}=i,u={...d,...y};o?o?.deletedEntity?r={entity:o?.deletedEntity,metadata:u}:r={metadata:u}:p?r={data:p.body,metadata:u}:r={entity:c?.entity??f?.currentEntity,metadata:u}}else r={data:s,metadata:d};let t=e.transformations??(i=>i);return a(t(r))}function L(e){let a=new Map,s=_(),d={...s,getRegisteredEvents:()=>a,async process(r,t={expectedEvents:[]}){let{eventType:i,identity:o,instanceId:p,payload:c}=await this.parseJWT(r),f=[...t.expectedEvents,...Array.from(a.keys()).map(u=>({type:u}))];if(f.length>0&&!f.some(({type:u})=>u===i))throw new Error(`Unexpected event type: ${i}. Expected one of: ${f.map(u=>u.type).join(", ")}`);let y=a.get(i)??[];return await Promise.all(y.map(({eventDefinition:u,handler:n})=>$(u,n,c,{instanceId:p,identity:o}))),{instanceId:p,eventType:i,payload:c,identity:o}},async processRequest(r,t){let i=await r.text();return this.process(i,t)},async parseJWT(r){if(!e.decodeJWT)throw new Error("decodeJWT is not supported by the authentication strategy");let{decoded:t,valid:i}=await e.decodeJWT(r);if(!i)throw new Error("JWT is not valid");if(typeof t.data!="string")throw new Error(`Unexpected type of JWT data: expected string, got ${typeof t.data}`);let o=JSON.parse(t.data),p=o.eventType,c=o.instanceId,f=o.identity?JSON.parse(o.identity):void 0,y=JSON.parse(o.data);return{instanceId:c,eventType:p,payload:y,identity:f}},async parseRequest(r){let t=await r.text();return this.parseJWT(t)},async executeHandlers(r){let t=Array.from(a.keys()).map(o=>({type:o}));if(t.length>0&&!t.some(({type:o})=>o===r.eventType))throw new Error(`Unexpected event type: ${r.eventType}. Expected one of: ${t.map(o=>o.type).join(", ")}`);let i=a.get(r.eventType)??[];await Promise.all(i.map(({eventDefinition:o,handler:p})=>$(o,p,r.payload,{instanceId:r.instanceId,identity:r.identity})))},apps:{AppInstalled:b("AppInstalled")(),AppRemoved:b("AppRemoved")()}};return{initModule(r){return t=>{let i=a.get(r.type)??[];i.push({eventDefinition:r,handler:t}),a.set(r.type,i),s.emit("registered",r)}},client:d}}var O=e=>e.__type==="service-plugin-definition";function q(e){let a=new Map,s=_(),d={...s,getRegisteredServicePlugins:()=>a,async parseJWT(r){if(!e.decodeJWT)throw new Error("decodeJWT is not supported by the authentication strategy");let{decoded:t,valid:i}=await e.decodeJWT(r,!0);if(!i)throw new Error("JWT is not valid");if(typeof t.data!="object"||t.data===null||!("metadata"in t.data)||typeof t.data.metadata!="object"||t.data.metadata===null||!("appExtensionType"in t.data.metadata)||typeof t.data.metadata.appExtensionType!="string")throw new Error("Unexpected JWT data: expected object with metadata.appExtensionType string");return t.data},async process(r){let t=await this.parseJWT(r.body);return this.executeHandler(t,r.url)},async parseRequest(r){let t=await r.text();return this.parseJWT(t)},async processRequest(r){let t=r.url,i=await r.text();try{let o=await this.process({url:t,body:i});return Response.json(o)}catch(o){if(o.errorType==="SPI"&&o.applicationCode&&o.httpCode)return Response.json({applicationError:{code:o.applicationCode,data:o.data}},{status:o.httpCode});throw o}},async executeHandler(r,t){let i=r.metadata.appExtensionType.toLowerCase(),o=a.get(i)??[];if(o.length===0)throw new Error(`No service plugin implementations found for component type ${i}`);if(o.length>1)throw new Error(`Multiple service plugin implementations found for component type ${i}. This is currently not supported`);let{implementation:p,servicePluginDefinition:c}=o[0],f=c.methods.find(u=>t.endsWith(u.primaryHttpMappingPath));if(!f)throw new Error("Unexpect request: request url did not match any method: "+t);let y=p[f.name];if(!y)throw new Error(`Got request for service plugin method ${f.name} but no implementation was provided. Available methods: ${Object.keys(p).join(", ")}`);return f.transformations.toREST(await y(f.transformations.fromREST(r)))}};return{initModule(r){return t=>{let i=a.get(r.componentType.toLowerCase())??[];i.push({servicePluginDefinition:r,implementation:t}),a.set(r.componentType.toLowerCase(),i),s.emit("registered",r)}},client:d}}function _e(e){let a=e.headers||{Authorization:""},s=e.auth||{getAuthHeaders:n=>Promise.resolve({headers:{}})},d=s.getAuthHeaders.bind(void 0,e.host);s.getAuthHeaders=d;let r=async(n,l)=>{if(typeof n=="string"||n instanceof URL)return fetch(n,{...l,headers:{...l?.headers,...(await d()).headers}});for(let[h,m]of Object.entries((await d()).headers))n.headers.set(h,m);return fetch(n,l)},{client:t,initModule:i}=q(s),{client:o,initModule:p}=L(s),c=async(n,l)=>{let h=await d(),m=C(l);return fetch(n,{...l,headers:{...m,...a,...h?.headers,...l?.headers,...e.host?.essentials?.passThroughHeaders}})},f=(n,l)=>{if(J(n))return p(n);if(O(n))return i(n);if(j(n)&&e.host)return S(n,e.host);if(typeof n=="function"){if("__type"in n&&n.__type===A)return n;let h=e.host?.apiBaseUrl??w;return I(x(()=>M(n))?P(n):n,l??{},c,(m,E)=>{let T=new URL(m,`https://${h}`);return T.host=h,T.protocol="https",c(T.toString(),E)},s.getActiveToken,{HTTPHost:h},e.host?.name)}else return U(n)?Object.fromEntries(Object.entries(n).map(([h,m])=>[h,f(m,n[R])])):n},y=n=>{for(let l in n)a[l]=n[l]};return{...e.modules?f(e.modules):{},auth:s,setHeaders:y,use:f,enableContext(n,l={elevated:!1}){n==="global"?globalThis.__wix_context__!=null?l.elevated?globalThis.__wix_context__.elevatedClient=this:globalThis.__wix_context__.client=this:l.elevated?globalThis.__wix_context__={elevatedClient:this}:globalThis.__wix_context__={client:this}:l.elevated?N.elevatedClient=this:N.client=this},fetch:(n,l)=>{let h=e.host?.apiBaseUrl??w,m=new URL(n,`https://${h}`);return m.host=h,m.protocol="https",c(m.toString(),l)},fetchWithAuth:r,async graphql(n,l,h={apiVersion:"alpha"}){let m=e?.host?.apiBaseUrl??w,E=await c(`https://${m}/graphql/${h.apiVersion}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:n,variables:l})});if(E.status!==200)throw new g(`GraphQL request failed with status ${E.status}`,E);let{data:T,errors:k}=await E.json();return{data:T??{},errors:k}},webhooks:o,servicePlugins:t}}export{_e as a};
2
+ //# sourceMappingURL=chunk-XYIDODIB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/@wix/sdk/build/wixClient.js","../../../node_modules/@wix/sdk/build/ambassador-modules.js","../../../node_modules/@wix/sdk/build/common.js","../../../node_modules/@wix/sdk/build/fetch-error.js","../../../node_modules/@wix/sdk/build/helpers.js","../../../node_modules/@wix/sdk/build/host-modules.js","../../../node_modules/@wix/sdk/build/bi/biHeaderGenerator.js","../../../node_modules/@wix/sdk/build/rest-modules.js","../../../node_modules/@wix/sdk/build/event-handlers-modules.js","../../../node_modules/@wix/sdk/build/nanoevents.js","../../../node_modules/@wix/sdk/build/service-plugin-modules.js"],"sourcesContent":["import { wixContext } from '@wix/sdk-context';\nimport { SERVICE_PLUGIN_ERROR_TYPE, } from '@wix/sdk-types';\nimport { isAmbassadorModule, toHTTPModule } from './ambassador-modules.js';\nimport { DEFAULT_API_URL, PUBLIC_METADATA_KEY } from './common.js';\nimport { FetchErrorResponse } from './fetch-error.js';\nimport { getDefaultContentHeader, isObject } from './helpers.js';\nimport { buildHostModule, isHostModule } from './host-modules.js';\nimport { buildRESTDescriptor } from './rest-modules.js';\nimport { eventHandlersModules, isEventHandlerModule, } from './event-handlers-modules.js';\nimport { isServicePluginModule, servicePluginsModules, } from './service-plugin-modules.js';\nimport { runWithoutContext } from '@wix/sdk-runtime/context';\nexport function createClient(config) {\n const _headers = config.headers || { Authorization: '' };\n const authStrategy = config.auth ||\n {\n getAuthHeaders: (_) => Promise.resolve({ headers: {} }),\n };\n const boundGetAuthHeaders = authStrategy.getAuthHeaders.bind(undefined, config.host);\n authStrategy.getAuthHeaders = boundGetAuthHeaders;\n const fetchWithAuth = async (urlOrRequest, requestInit) => {\n if (typeof urlOrRequest === 'string' || urlOrRequest instanceof URL) {\n return fetch(urlOrRequest, {\n ...requestInit,\n headers: {\n ...requestInit?.headers,\n ...(await boundGetAuthHeaders()).headers,\n },\n });\n }\n else {\n for (const [k, v] of Object.entries((await boundGetAuthHeaders()).headers)) {\n urlOrRequest.headers.set(k, v);\n }\n return fetch(urlOrRequest, requestInit);\n }\n };\n const { client: servicePluginsClient, initModule: initServicePluginModule } = servicePluginsModules(authStrategy);\n const { client: eventHandlersClient, initModule: initEventHandlerModule } = eventHandlersModules(authStrategy);\n const boundFetch = async (url, options) => {\n const authHeaders = await boundGetAuthHeaders();\n const defaultContentTypeHeader = getDefaultContentHeader(options);\n return fetch(url, {\n ...options,\n headers: {\n ...defaultContentTypeHeader,\n ..._headers,\n ...authHeaders?.headers,\n ...options?.headers,\n ...config.host?.essentials?.passThroughHeaders,\n },\n });\n };\n // This is typed as `any` because when trying to properly type it as defined\n // on the WixClient, typescript starts failing with `Type instantiation is\n // excessively deep and possibly infinite.`\n const use = (modules, metadata) => {\n if (isEventHandlerModule(modules)) {\n return initEventHandlerModule(modules);\n }\n else if (isServicePluginModule(modules)) {\n return initServicePluginModule(modules);\n }\n else if (isHostModule(modules) && config.host) {\n return buildHostModule(modules, config.host);\n }\n else if (typeof modules === 'function') {\n // The generated namespaces all have the error classes on them and\n // a class is also a function, so we need to explicitly ignore these\n // error classes using a static field that exists on them.\n if ('__type' in modules && modules.__type === SERVICE_PLUGIN_ERROR_TYPE) {\n return modules;\n }\n const apiBaseUrl = config.host?.apiBaseUrl ?? DEFAULT_API_URL;\n return buildRESTDescriptor(runWithoutContext(() => isAmbassadorModule(modules))\n ? toHTTPModule(modules)\n : modules, metadata ?? {}, boundFetch, (relativeUrl, fetchOptions) => {\n const finalUrl = new URL(relativeUrl, `https://${apiBaseUrl}`);\n finalUrl.host = apiBaseUrl;\n finalUrl.protocol = 'https';\n return boundFetch(finalUrl.toString(), fetchOptions);\n }, authStrategy.getActiveToken, { HTTPHost: apiBaseUrl }, config.host?.name);\n }\n else if (isObject(modules)) {\n return Object.fromEntries(Object.entries(modules).map(([key, value]) => {\n return [key, use(value, modules[PUBLIC_METADATA_KEY])];\n }));\n }\n else {\n return modules;\n }\n };\n const setHeaders = (headers) => {\n for (const k in headers) {\n _headers[k] = headers[k];\n }\n };\n const wrappedModules = config.modules\n ? use(config.modules)\n : {};\n return {\n ...wrappedModules,\n auth: authStrategy,\n setHeaders,\n use,\n enableContext(contextType, opts = { elevated: false }) {\n if (contextType === 'global') {\n if (globalThis.__wix_context__ != null) {\n if (opts.elevated) {\n globalThis.__wix_context__.elevatedClient = this;\n }\n else {\n globalThis.__wix_context__.client = this;\n }\n }\n else {\n if (opts.elevated) {\n globalThis.__wix_context__ = { elevatedClient: this };\n }\n else {\n globalThis.__wix_context__ = { client: this };\n }\n }\n }\n else {\n if (opts.elevated) {\n wixContext.elevatedClient = this;\n }\n else {\n wixContext.client = this;\n }\n }\n },\n /**\n * @param relativeUrl The URL to fetch relative to the API base URL\n * @param options The fetch options\n * @returns The fetch Response object\n * @deprecated Use `fetchWithAuth` instead\n */\n fetch: (relativeUrl, options) => {\n const apiBaseUrl = config.host?.apiBaseUrl ?? DEFAULT_API_URL;\n const finalUrl = new URL(relativeUrl, `https://${apiBaseUrl}`);\n finalUrl.host = apiBaseUrl;\n finalUrl.protocol = 'https';\n return boundFetch(finalUrl.toString(), options);\n },\n fetchWithAuth,\n async graphql(query, variables, opts = {\n apiVersion: 'alpha',\n }) {\n const apiBaseUrl = config?.host?.apiBaseUrl ?? DEFAULT_API_URL;\n const res = await boundFetch(`https://${apiBaseUrl}/graphql/${opts.apiVersion}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ query, variables }),\n });\n if (res.status !== 200) {\n throw new FetchErrorResponse(`GraphQL request failed with status ${res.status}`, res);\n }\n const { data, errors } = await res.json();\n return { data: data ?? {}, errors };\n },\n webhooks: eventHandlersClient,\n servicePlugins: servicePluginsClient,\n };\n}\n","const parseMethod = (method) => {\n switch (method) {\n case 'get':\n case 'GET':\n return 'GET';\n case 'post':\n case 'POST':\n return 'POST';\n case 'put':\n case 'PUT':\n return 'PUT';\n case 'delete':\n case 'DELETE':\n return 'DELETE';\n case 'patch':\n case 'PATCH':\n return 'PATCH';\n case 'head':\n case 'HEAD':\n return 'HEAD';\n case 'options':\n case 'OPTIONS':\n return 'OPTIONS';\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n};\nexport const toHTTPModule = (factory) => (httpClient) => async (payload) => {\n let requestOptions;\n const HTTPFactory = (context) => {\n requestOptions = factory(payload)(context);\n if (requestOptions.url === undefined) {\n throw new Error('Url was not successfully created for this request, please reach out to support channels for assistance.');\n }\n const { method, url, params } = requestOptions;\n return {\n ...requestOptions,\n method: parseMethod(method),\n url,\n data: requestOptions.data,\n params,\n };\n };\n try {\n const response = await httpClient.request(HTTPFactory);\n if (requestOptions === undefined) {\n throw new Error('Request options were not created for this request, please reach out to support channels for assistance.');\n }\n const transformations = Array.isArray(requestOptions.transformResponse)\n ? requestOptions.transformResponse\n : [requestOptions.transformResponse];\n /**\n * Based on Axios implementation:\n * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/lib/core/transformData.js#L22\n */\n let data = response.data;\n transformations.forEach((transform) => {\n if (transform) {\n data = transform(response.data, response.headers);\n }\n });\n return data;\n }\n catch (e) {\n if (typeof e === 'object' &&\n e !== null &&\n 'response' in e &&\n typeof e.response === 'object' &&\n e.response !== null &&\n 'data' in e.response) {\n throw e.response.data;\n }\n throw e;\n }\n};\n/*\n * Because of issues with tree-shaking, we cant really put static parameter on module.\n * We still have check for __isAmbassador for backward compatibility\n */\nexport const isAmbassadorModule = (module) => {\n if (module.__isAmbassador) {\n return true;\n }\n const fn = module();\n return Boolean(fn.__isAmbassador);\n};\n","export const PUBLIC_METADATA_KEY = '__metadata';\nexport const DEFAULT_API_URL = 'www.wixapis.com';\nexport const FORCE_WRITE_API_URLS = ['/ecom/v1/carts/current'];\n","export class FetchErrorResponse extends Error {\n message;\n response;\n constructor(message, response) {\n super(message);\n this.message = message;\n this.response = response;\n }\n async details() {\n const dataError = await this.response.json();\n return errorBuilder(this.response.status, dataError?.message, dataError?.details, {\n requestId: this.response.headers.get('X-Wix-Request-Id'),\n details: dataError,\n });\n }\n}\nconst errorBuilder = (code, description, details, data) => {\n return {\n details: {\n ...(!details?.validationError && {\n applicationError: {\n description,\n code,\n data,\n },\n }),\n ...details,\n },\n message: description,\n };\n};\n","// we follow a simplified version of the axios convention\n// https://github.com/axios/axios/blob/649d739288c8e2c55829ac60e2345a0f3439c730/lib/defaults/index.js#L65\nexport const getDefaultContentHeader = (options) => {\n if (options?.method &&\n ['post', 'put', 'patch'].includes(options.method.toLocaleLowerCase()) &&\n options.body) {\n return { 'Content-Type': 'application/json' };\n }\n return {};\n};\nexport const isObject = (val) => val && typeof val === 'object' && !Array.isArray(val);\nexport function parsePublicKeyIfEncoded(publicKey) {\n if (publicKey.includes('\\n') || publicKey.includes('\\r')) {\n // publicKey is multi-line string, can be used as is\n return publicKey.trim();\n }\n else {\n // publicKey is base64 encoded\n return typeof atob !== 'undefined'\n ? atob(publicKey)\n : Buffer.from(publicKey, 'base64').toString('utf-8');\n }\n}\n","export const isHostModule = (val) => val.__type === 'host';\nexport function buildHostModule(val, host) {\n return val.create(host);\n}\n","export const WixBIHeaderName = 'x-wix-bi-gateway';\nexport function biHeaderGenerator(apiMetadata, publicMetadata, environment) {\n return {\n [WixBIHeaderName]: objectToKeyValue({\n environment: `js-sdk${environment ? `-${environment}` : ``}`,\n 'package-name': apiMetadata.packageName ?? publicMetadata?.PACKAGE_NAME,\n 'method-fqn': apiMetadata.methodFqn,\n entity: apiMetadata.entityFqdn,\n }),\n };\n}\nfunction objectToKeyValue(input) {\n return Object.entries(input)\n .filter(([_, value]) => Boolean(value))\n .map(([key, value]) => `${key}=${value}`)\n .join(',');\n}\n","import { biHeaderGenerator } from './bi/biHeaderGenerator.js';\nimport { DEFAULT_API_URL } from './common.js';\nimport { runWithoutContext } from '@wix/sdk-runtime/context';\nexport function buildRESTDescriptor(origFunc, publicMetadata, boundFetch, wixAPIFetch, getActiveToken, options, hostName) {\n return runWithoutContext(() => origFunc({\n request: async (factory) => {\n const requestOptions = factory({\n host: options?.HTTPHost || DEFAULT_API_URL,\n });\n let request = requestOptions;\n if (request.method === 'GET' &&\n request.fallback?.length &&\n request.params.toString().length > 4000) {\n request = requestOptions.fallback[0];\n }\n const domain = options?.HTTPHost ?? DEFAULT_API_URL;\n let url = `https://${domain}${request.url}`;\n if (request.params && request.params.toString()) {\n url += `?${request.params.toString()}`;\n }\n try {\n const biHeader = biHeaderGenerator(requestOptions, publicMetadata, hostName);\n const res = await boundFetch(url, {\n method: request.method,\n ...(request.data && {\n body: JSON.stringify(request.data),\n }),\n headers: {\n ...biHeader,\n },\n });\n if (res.status !== 200) {\n let dataError = null;\n try {\n dataError = await res.json();\n }\n catch (e) {\n //\n }\n throw errorBuilder(res.status, dataError?.message, dataError?.details, {\n requestId: res.headers.get('X-Wix-Request-Id'),\n details: dataError,\n });\n }\n const data = await res.json();\n return {\n data,\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n };\n }\n catch (e) {\n if (e.message?.includes('fetch is not defined')) {\n console.error('Node.js v18+ is required');\n }\n throw e;\n }\n },\n fetchWithAuth: boundFetch,\n wixAPIFetch,\n getActiveToken,\n }));\n}\nconst errorBuilder = (code, description, details, data) => {\n return {\n response: {\n data: {\n details: {\n ...(!details?.validationError && {\n applicationError: {\n description,\n code,\n data,\n },\n }),\n ...details,\n },\n message: description,\n },\n status: code,\n },\n };\n};\n","import { EventDefinition, } from '@wix/sdk-types';\nimport { createNanoEvents } from './nanoevents.js';\nexport const isEventHandlerModule = (val) => val.__type === 'event-definition';\nexport function buildEventDefinition(eventDefinition, registerHandler) {\n return (handler) => {\n registerHandler(eventDefinition, handler);\n };\n}\nfunction runHandler(eventDefinition, handler, payload, baseEventMetadata) {\n let envelope;\n if (eventDefinition.isDomainEvent) {\n const domainEventPayload = payload;\n const { deletedEvent, actionEvent, createdEvent, updatedEvent, ...domainEventMetadata } = domainEventPayload;\n const metadata = {\n ...baseEventMetadata,\n ...domainEventMetadata,\n };\n if (deletedEvent) {\n if (deletedEvent?.deletedEntity) {\n envelope = {\n entity: deletedEvent?.deletedEntity,\n metadata,\n };\n }\n else {\n envelope = { metadata };\n }\n }\n else if (actionEvent) {\n envelope = {\n data: actionEvent.body,\n metadata,\n };\n }\n else {\n envelope = {\n entity: createdEvent?.entity ?? updatedEvent?.currentEntity,\n metadata,\n };\n }\n }\n else {\n envelope = {\n data: payload,\n metadata: baseEventMetadata,\n };\n }\n const transformFromRESTFn = eventDefinition.transformations ?? ((x) => x);\n return handler(transformFromRESTFn(envelope));\n}\nexport function eventHandlersModules(authStrategy) {\n const eventHandlers = new Map();\n const webhooksEmitter = createNanoEvents();\n const client = {\n ...webhooksEmitter,\n getRegisteredEvents: () => eventHandlers,\n async process(jwt, opts = {\n expectedEvents: [],\n }) {\n const { eventType, identity, instanceId, payload } = await this.parseJWT(jwt);\n const allExpectedEvents = [\n ...opts.expectedEvents,\n ...Array.from(eventHandlers.keys()).map((type) => ({ type })),\n ];\n if (allExpectedEvents.length > 0 &&\n !allExpectedEvents.some(({ type }) => type === eventType)) {\n throw new Error(`Unexpected event type: ${eventType}. Expected one of: ${allExpectedEvents\n .map((x) => x.type)\n .join(', ')}`);\n }\n const handlers = eventHandlers.get(eventType) ?? [];\n await Promise.all(handlers.map(({ eventDefinition, handler }) => runHandler(eventDefinition, handler, payload, {\n instanceId,\n identity,\n })));\n return {\n instanceId,\n eventType,\n payload,\n identity,\n };\n },\n async processRequest(request, opts) {\n const body = await request.text();\n return this.process(body, opts);\n },\n async parseJWT(jwt) {\n if (!authStrategy.decodeJWT) {\n throw new Error('decodeJWT is not supported by the authentication strategy');\n }\n const { decoded, valid } = await authStrategy.decodeJWT(jwt);\n if (!valid) {\n throw new Error('JWT is not valid');\n }\n if (typeof decoded.data !== 'string') {\n throw new Error(`Unexpected type of JWT data: expected string, got ${typeof decoded.data}`);\n }\n const parsedDecoded = JSON.parse(decoded.data);\n const eventType = parsedDecoded.eventType;\n const instanceId = parsedDecoded.instanceId;\n const identity = parsedDecoded.identity\n ? JSON.parse(parsedDecoded.identity)\n : undefined;\n const payload = JSON.parse(parsedDecoded.data);\n return {\n instanceId,\n eventType,\n payload,\n identity,\n };\n },\n async parseRequest(request) {\n const jwt = await request.text();\n return this.parseJWT(jwt);\n },\n async executeHandlers(event) {\n const allExpectedEvents = Array.from(eventHandlers.keys()).map((type) => ({ type }));\n if (allExpectedEvents.length > 0 &&\n !allExpectedEvents.some(({ type }) => type === event.eventType)) {\n throw new Error(`Unexpected event type: ${event.eventType}. Expected one of: ${allExpectedEvents\n .map((x) => x.type)\n .join(', ')}`);\n }\n const handlers = eventHandlers.get(event.eventType) ?? [];\n await Promise.all(handlers.map(({ eventDefinition, handler }) => runHandler(eventDefinition, handler, event.payload, {\n instanceId: event.instanceId,\n identity: event.identity,\n })));\n },\n apps: {\n AppInstalled: EventDefinition('AppInstalled')(),\n AppRemoved: EventDefinition('AppRemoved')(),\n },\n };\n return {\n initModule(eventDefinition) {\n return (handler) => {\n const handlers = eventHandlers.get(eventDefinition.type) ?? [];\n handlers.push({ eventDefinition, handler });\n eventHandlers.set(eventDefinition.type, handlers);\n webhooksEmitter.emit('registered', eventDefinition);\n };\n },\n client,\n };\n}\n","// Inlined from https://github.com/ai/nanoevents/blob/main/index.js\n/**\n * Create event emitter.\n *\n * ```js\n * import { createNanoEvents } from 'nanoevents'\n *\n * class Ticker {\n * constructor() {\n * this.emitter = createNanoEvents()\n * }\n * on(...args) {\n * return this.emitter.on(...args)\n * }\n * tick() {\n * this.emitter.emit('tick')\n * }\n * }\n * ```\n * @returns Event emitter.\n */\nexport function createNanoEvents() {\n return {\n emit(event, ...args) {\n for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {\n callbacks[i](...args);\n }\n },\n events: {},\n on(event, cb) {\n (this.events[event] ||= []).push(cb);\n return () => {\n this.events[event] = this.events[event]?.filter((i) => cb !== i);\n };\n },\n };\n}\n","import { createNanoEvents } from './nanoevents.js';\nexport const isServicePluginModule = (val) => val.__type === 'service-plugin-definition';\nexport function servicePluginsModules(authStrategy) {\n const servicePluginsImplementations = new Map();\n const servicePluginsEmitter = createNanoEvents();\n const client = {\n ...servicePluginsEmitter,\n getRegisteredServicePlugins: () => servicePluginsImplementations,\n async parseJWT(jwt) {\n if (!authStrategy.decodeJWT) {\n throw new Error('decodeJWT is not supported by the authentication strategy');\n }\n const { decoded, valid } = await authStrategy.decodeJWT(jwt, true);\n if (!valid) {\n throw new Error('JWT is not valid');\n }\n if (typeof decoded.data !== 'object' ||\n decoded.data === null ||\n !('metadata' in decoded.data) ||\n typeof decoded.data.metadata !== 'object' ||\n decoded.data.metadata === null ||\n !('appExtensionType' in decoded.data.metadata) ||\n typeof decoded.data.metadata.appExtensionType !== 'string') {\n throw new Error('Unexpected JWT data: expected object with metadata.appExtensionType string');\n }\n return decoded.data;\n },\n async process(request) {\n const servicePluginRequest = await this.parseJWT(request.body);\n return this.executeHandler(servicePluginRequest, request.url);\n },\n async parseRequest(request) {\n const body = await request.text();\n return this.parseJWT(body);\n },\n async processRequest(request) {\n const url = request.url;\n const body = await request.text();\n try {\n const implMethodResult = await this.process({ url, body });\n return Response.json(implMethodResult);\n }\n catch (err) {\n if (err.errorType === 'SPI' && err.applicationCode && err.httpCode) {\n return Response.json({ applicationError: { code: err.applicationCode, data: err.data } }, { status: err.httpCode });\n }\n throw err;\n }\n },\n async executeHandler(servicePluginRequest, url) {\n const componentType = servicePluginRequest.metadata.appExtensionType.toLowerCase();\n const implementations = servicePluginsImplementations.get(componentType) ?? [];\n if (implementations.length === 0) {\n throw new Error(`No service plugin implementations found for component type ${componentType}`);\n }\n else if (implementations.length > 1) {\n throw new Error(`Multiple service plugin implementations found for component type ${componentType}. This is currently not supported`);\n }\n const { implementation: impl, servicePluginDefinition } = implementations[0];\n const method = servicePluginDefinition.methods.find((m) => url.endsWith(m.primaryHttpMappingPath));\n if (!method) {\n throw new Error('Unexpect request: request url did not match any method: ' + url);\n }\n const implMethod = impl[method.name];\n if (!implMethod) {\n throw new Error(`Got request for service plugin method ${method.name} but no implementation was provided. Available methods: ${Object.keys(impl).join(', ')}`);\n }\n return method.transformations.toREST(await implMethod(method.transformations.fromREST(servicePluginRequest)));\n },\n };\n return {\n initModule(servicePluginDefinition) {\n return (implementation) => {\n const implementations = servicePluginsImplementations.get(servicePluginDefinition.componentType.toLowerCase()) ?? [];\n implementations.push({ servicePluginDefinition, implementation });\n servicePluginsImplementations.set(servicePluginDefinition.componentType.toLowerCase(), implementations);\n servicePluginsEmitter.emit('registered', servicePluginDefinition);\n };\n },\n client,\n };\n}\n"],"mappings":"qGACAA,IADA,OAAS,cAAAC,MAAkB,mBCA3B,IAAMC,EAAeC,GAAW,CAC5B,OAAQA,EAAQ,CACZ,IAAK,MACL,IAAK,MACD,MAAO,MACX,IAAK,OACL,IAAK,OACD,MAAO,OACX,IAAK,MACL,IAAK,MACD,MAAO,MACX,IAAK,SACL,IAAK,SACD,MAAO,SACX,IAAK,QACL,IAAK,QACD,MAAO,QACX,IAAK,OACL,IAAK,OACD,MAAO,OACX,IAAK,UACL,IAAK,UACD,MAAO,UACX,QACI,MAAM,IAAI,MAAM,mBAAmBA,CAAM,EAAE,CACnD,CACJ,EACaC,EAAgBC,GAAaC,GA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AalB,IAAY,CAC7B,IAAMY,EAAa9B,EAAO,MAAM,YAAc+B,EACxCO,EAAW,IAAI,IAAIF,EAAa,WAAWN,CAAU,EAAE,EAC7D,OAAAQ,EAAS,KAAOR,EAChBQ,EAAS,SAAW,QACbtB,EAAWsB,EAAS,SAAS,EAAGpB,CAAO,CAClD,EACA,cAAAb,EACA,MAAM,QAAQ2C,EAAOC,EAAWH,EAAO,CACnC,WAAY,OAChB,EAAG,CACC,IAAMhB,EAAa9B,GAAQ,MAAM,YAAc+B,EACzCmB,EAAM,MAAMlC,EAAW,WAAWc,CAAU,YAAYgB,EAAK,UAAU,GAAI,CAC7E,OAAQ,OACR,QAAS,CACL,eAAgB,kBACpB,EACA,KAAM,KAAK,UAAU,CAAE,MAAAE,EAAO,UAAAC,CAAU,CAAC,CAC7C,CAAC,EACD,GAAIC,EAAI,SAAW,IACf,MAAM,IAAIC,EAAmB,sCAAsCD,EAAI,MAAM,GAAIA,CAAG,EAExF,GAAM,CAAE,KAAAE,EAAM,OAAAC,CAAO,EAAI,MAAMH,EAAI,KAAK,EACxC,MAAO,CAAE,KAAME,GAAQ,CAAC,EAAG,OAAAC,CAAO,CACtC,EACA,SAAUxC,EACV,eAAgBH,CACpB,CACJ","names":["init_browser","wixContext","parseMethod","method","toHTTPModule","factory","httpClient","payload","requestOptions","HTTPFactory","context","url","params","response","transformations","data","transform","e","isAmbassadorModule","module","PUBLIC_METADATA_KEY","DEFAULT_API_URL","FetchErrorResponse","message","response","__publicField","dataError","errorBuilder","code","description","details","data","getDefaultContentHeader","options","isObject","val","isHostModule","val","buildHostModule","host","WixBIHeaderName","biHeaderGenerator","apiMetadata","publicMetadata","environment","objectToKeyValue","input","_","value","key","buildRESTDescriptor","origFunc","publicMetadata","boundFetch","wixAPIFetch","getActiveToken","options","hostName","runWithoutContext","factory","requestOptions","DEFAULT_API_URL","request","url","biHeader","biHeaderGenerator","res","dataError","errorBuilder","e","code","description","details","data","init_browser","createNanoEvents","event","args","i","callbacks","length","cb","isEventHandlerModule","val","runHandler","eventDefinition","handler","payload","baseEventMetadata","envelope","domainEventPayload","deletedEvent","actionEvent","createdEvent","updatedEvent","domainEventMetadata","metadata","transformFromRESTFn","x","eventHandlersModules","authStrategy","eventHandlers","webhooksEmitter","createNanoEvents","client","jwt","opts","eventType","identity","instanceId","allExpectedEvents","type","handlers","request","body","decoded","valid","parsedDecoded","event","EventDefinition","isServicePluginModule","val","servicePluginsModules","authStrategy","servicePluginsImplementations","servicePluginsEmitter","createNanoEvents","client","jwt","decoded","valid","request","servicePluginRequest","body","url","implMethodResult","err","componentType","implementations","impl","servicePluginDefinition","method","m","implMethod","implementation","createClient","config","_headers","authStrategy","_","boundGetAuthHeaders","fetchWithAuth","urlOrRequest","requestInit","k","v","servicePluginsClient","initServicePluginModule","servicePluginsModules","eventHandlersClient","initEventHandlerModule","eventHandlersModules","boundFetch","url","options","authHeaders","defaultContentTypeHeader","getDefaultContentHeader","use","modules","metadata","isEventHandlerModule","isServicePluginModule","isHostModule","buildHostModule","SERVICE_PLUGIN_ERROR_TYPE","apiBaseUrl","DEFAULT_API_URL","buildRESTDescriptor","runWithoutContext","isAmbassadorModule","toHTTPModule","relativeUrl","fetchOptions","finalUrl","isObject","key","value","PUBLIC_METADATA_KEY","setHeaders","headers","contextType","opts","wixContext","query","variables","res","FetchErrorResponse","data","errors"]}
1
+ {"version":3,"sources":["../../../node_modules/@wix/sdk/build/wixClient.js","../../../node_modules/@wix/sdk/build/ambassador-modules.js","../../../node_modules/@wix/sdk/build/common.js","../../../node_modules/@wix/sdk/build/fetch-error.js","../../../node_modules/@wix/sdk/build/helpers.js","../../../node_modules/@wix/sdk/build/host-modules.js","../../../node_modules/@wix/sdk/build/bi/biHeaderGenerator.js","../../../node_modules/@wix/sdk/build/rest-modules.js","../../../node_modules/@wix/sdk/build/event-handlers-modules.js","../../../node_modules/@wix/sdk/build/nanoevents.js","../../../node_modules/@wix/sdk/build/service-plugin-modules.js"],"sourcesContent":["import { wixContext } from '@wix/sdk-context';\nimport { SERVICE_PLUGIN_ERROR_TYPE, } from '@wix/sdk-types';\nimport { isAmbassadorModule, toHTTPModule } from './ambassador-modules.js';\nimport { DEFAULT_API_URL, PUBLIC_METADATA_KEY } from './common.js';\nimport { FetchErrorResponse } from './fetch-error.js';\nimport { getDefaultContentHeader, isObject } from './helpers.js';\nimport { buildHostModule, isHostModule } from './host-modules.js';\nimport { buildRESTDescriptor } from './rest-modules.js';\nimport { eventHandlersModules, isEventHandlerModule, } from './event-handlers-modules.js';\nimport { isServicePluginModule, servicePluginsModules, } from './service-plugin-modules.js';\nimport { runWithoutContext } from '@wix/sdk-runtime/context';\nexport function createClient(config) {\n const _headers = config.headers || { Authorization: '' };\n const authStrategy = config.auth ||\n {\n getAuthHeaders: (_) => Promise.resolve({ headers: {} }),\n };\n const boundGetAuthHeaders = authStrategy.getAuthHeaders.bind(undefined, config.host);\n authStrategy.getAuthHeaders = boundGetAuthHeaders;\n const fetchWithAuth = async (urlOrRequest, requestInit) => {\n if (typeof urlOrRequest === 'string' || urlOrRequest instanceof URL) {\n return fetch(urlOrRequest, {\n ...requestInit,\n headers: {\n ...requestInit?.headers,\n ...(await boundGetAuthHeaders()).headers,\n },\n });\n }\n else {\n for (const [k, v] of Object.entries((await boundGetAuthHeaders()).headers)) {\n urlOrRequest.headers.set(k, v);\n }\n return fetch(urlOrRequest, requestInit);\n }\n };\n const { client: servicePluginsClient, initModule: initServicePluginModule } = servicePluginsModules(authStrategy);\n const { client: eventHandlersClient, initModule: initEventHandlerModule } = eventHandlersModules(authStrategy);\n const boundFetch = async (url, options) => {\n const authHeaders = await boundGetAuthHeaders();\n const defaultContentTypeHeader = getDefaultContentHeader(options);\n return fetch(url, {\n ...options,\n headers: {\n ...defaultContentTypeHeader,\n ..._headers,\n ...authHeaders?.headers,\n ...options?.headers,\n ...config.host?.essentials?.passThroughHeaders,\n },\n });\n };\n // This is typed as `any` because when trying to properly type it as defined\n // on the WixClient, typescript starts failing with `Type instantiation is\n // excessively deep and possibly infinite.`\n const use = (modules, metadata) => {\n if (isEventHandlerModule(modules)) {\n return initEventHandlerModule(modules);\n }\n else if (isServicePluginModule(modules)) {\n return initServicePluginModule(modules);\n }\n else if (isHostModule(modules) && config.host) {\n return buildHostModule(modules, config.host);\n }\n else if (typeof modules === 'function') {\n // The generated namespaces all have the error classes on them and\n // a class is also a function, so we need to explicitly ignore these\n // error classes using a static field that exists on them.\n if ('__type' in modules && modules.__type === SERVICE_PLUGIN_ERROR_TYPE) {\n return modules;\n }\n const apiBaseUrl = config.host?.apiBaseUrl ?? DEFAULT_API_URL;\n return buildRESTDescriptor(runWithoutContext(() => isAmbassadorModule(modules))\n ? toHTTPModule(modules)\n : modules, metadata ?? {}, boundFetch, (relativeUrl, fetchOptions) => {\n const finalUrl = new URL(relativeUrl, `https://${apiBaseUrl}`);\n finalUrl.host = apiBaseUrl;\n finalUrl.protocol = 'https';\n return boundFetch(finalUrl.toString(), fetchOptions);\n }, authStrategy.getActiveToken, { HTTPHost: apiBaseUrl }, config.host?.name);\n }\n else if (isObject(modules)) {\n return Object.fromEntries(Object.entries(modules).map(([key, value]) => {\n return [key, use(value, modules[PUBLIC_METADATA_KEY])];\n }));\n }\n else {\n return modules;\n }\n };\n const setHeaders = (headers) => {\n for (const k in headers) {\n _headers[k] = headers[k];\n }\n };\n const wrappedModules = config.modules\n ? use(config.modules)\n : {};\n return {\n ...wrappedModules,\n auth: authStrategy,\n setHeaders,\n use,\n enableContext(contextType, opts = { elevated: false }) {\n if (contextType === 'global') {\n if (globalThis.__wix_context__ != null) {\n if (opts.elevated) {\n globalThis.__wix_context__.elevatedClient = this;\n }\n else {\n globalThis.__wix_context__.client = this;\n }\n }\n else {\n if (opts.elevated) {\n globalThis.__wix_context__ = { elevatedClient: this };\n }\n else {\n globalThis.__wix_context__ = { client: this };\n }\n }\n }\n else {\n if (opts.elevated) {\n wixContext.elevatedClient = this;\n }\n else {\n wixContext.client = this;\n }\n }\n },\n /**\n * @param relativeUrl The URL to fetch relative to the API base URL\n * @param options The fetch options\n * @returns The fetch Response object\n * @deprecated Use `fetchWithAuth` instead\n */\n fetch: (relativeUrl, options) => {\n const apiBaseUrl = config.host?.apiBaseUrl ?? DEFAULT_API_URL;\n const finalUrl = new URL(relativeUrl, `https://${apiBaseUrl}`);\n finalUrl.host = apiBaseUrl;\n finalUrl.protocol = 'https';\n return boundFetch(finalUrl.toString(), options);\n },\n fetchWithAuth,\n async graphql(query, variables, opts = {\n apiVersion: 'alpha',\n }) {\n const apiBaseUrl = config?.host?.apiBaseUrl ?? DEFAULT_API_URL;\n const res = await boundFetch(`https://${apiBaseUrl}/graphql/${opts.apiVersion}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ query, variables }),\n });\n if (res.status !== 200) {\n throw new FetchErrorResponse(`GraphQL request failed with status ${res.status}`, res);\n }\n const { data, errors } = await res.json();\n return { data: data ?? {}, errors };\n },\n webhooks: eventHandlersClient,\n servicePlugins: servicePluginsClient,\n };\n}\n","const parseMethod = (method) => {\n switch (method) {\n case 'get':\n case 'GET':\n return 'GET';\n case 'post':\n case 'POST':\n return 'POST';\n case 'put':\n case 'PUT':\n return 'PUT';\n case 'delete':\n case 'DELETE':\n return 'DELETE';\n case 'patch':\n case 'PATCH':\n return 'PATCH';\n case 'head':\n case 'HEAD':\n return 'HEAD';\n case 'options':\n case 'OPTIONS':\n return 'OPTIONS';\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n};\nexport const toHTTPModule = (factory) => (httpClient) => async (payload) => {\n let requestOptions;\n const HTTPFactory = (context) => {\n requestOptions = factory(payload)(context);\n if (requestOptions.url === undefined) {\n throw new Error('Url was not successfully created for this request, please reach out to support channels for assistance.');\n }\n const { method, url, params } = requestOptions;\n return {\n ...requestOptions,\n method: parseMethod(method),\n url,\n data: requestOptions.data,\n params,\n };\n };\n try {\n const response = await httpClient.request(HTTPFactory);\n if (requestOptions === undefined) {\n throw new Error('Request options were not created for this request, please reach out to support channels for assistance.');\n }\n const transformations = Array.isArray(requestOptions.transformResponse)\n ? requestOptions.transformResponse\n : [requestOptions.transformResponse];\n /**\n * Based on Axios implementation:\n * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/lib/core/transformData.js#L22\n */\n let data = response.data;\n transformations.forEach((transform) => {\n if (transform) {\n data = transform(response.data, response.headers);\n }\n });\n return data;\n }\n catch (e) {\n if (typeof e === 'object' &&\n e !== null &&\n 'response' in e &&\n typeof e.response === 'object' &&\n e.response !== null &&\n 'data' in e.response) {\n throw e.response.data;\n }\n throw e;\n }\n};\n/*\n * Because of issues with tree-shaking, we cant really put static parameter on module.\n * We still have check for __isAmbassador for backward compatibility\n */\nexport const isAmbassadorModule = (module) => {\n if (module.__isAmbassador) {\n return true;\n }\n const fn = module();\n return Boolean(fn.__isAmbassador);\n};\n","export const PUBLIC_METADATA_KEY = '__metadata';\nexport const DEFAULT_API_URL = 'www.wixapis.com';\nexport const FORCE_WRITE_API_URLS = ['/ecom/v1/carts/current'];\n","export class FetchErrorResponse extends Error {\n message;\n response;\n constructor(message, response) {\n super(message);\n this.message = message;\n this.response = response;\n }\n async details() {\n const dataError = await this.response.json();\n return errorBuilder(this.response.status, dataError?.message, dataError?.details, {\n requestId: this.response.headers.get('X-Wix-Request-Id'),\n details: dataError,\n });\n }\n}\nconst errorBuilder = (code, description, details, data) => {\n return {\n details: {\n ...(!details?.validationError && {\n applicationError: {\n description,\n code,\n data,\n },\n }),\n ...details,\n },\n message: description,\n };\n};\n","// we follow a simplified version of the axios convention\n// https://github.com/axios/axios/blob/649d739288c8e2c55829ac60e2345a0f3439c730/lib/defaults/index.js#L65\nexport const getDefaultContentHeader = (options) => {\n if (options?.method &&\n ['post', 'put', 'patch'].includes(options.method.toLocaleLowerCase()) &&\n options.body) {\n return { 'Content-Type': 'application/json' };\n }\n return {};\n};\nexport const isObject = (val) => val && typeof val === 'object' && !Array.isArray(val);\nexport function parsePublicKeyIfEncoded(publicKey) {\n if (publicKey.includes('\\n') || publicKey.includes('\\r')) {\n // publicKey is multi-line string, can be used as is\n return publicKey.trim();\n }\n else {\n // publicKey is base64 encoded\n return typeof atob !== 'undefined'\n ? atob(publicKey)\n : Buffer.from(publicKey, 'base64').toString('utf-8');\n }\n}\n","export const isHostModule = (val) => val.__type === 'host';\nexport function buildHostModule(val, host) {\n return val.create(host);\n}\n","export const WixBIHeaderName = 'x-wix-bi-gateway';\nexport function biHeaderGenerator(apiMetadata, publicMetadata, environment) {\n return {\n [WixBIHeaderName]: objectToKeyValue({\n environment: `js-sdk${environment ? `-${environment}` : ``}`,\n 'package-name': apiMetadata.packageName ?? publicMetadata?.PACKAGE_NAME,\n 'method-fqn': apiMetadata.methodFqn,\n entity: apiMetadata.entityFqdn,\n }),\n };\n}\nfunction objectToKeyValue(input) {\n return Object.entries(input)\n .filter(([_, value]) => Boolean(value))\n .map(([key, value]) => `${key}=${value}`)\n .join(',');\n}\n","import { biHeaderGenerator } from './bi/biHeaderGenerator.js';\nimport { DEFAULT_API_URL } from './common.js';\nimport { runWithoutContext } from '@wix/sdk-runtime/context';\nexport function buildRESTDescriptor(origFunc, publicMetadata, boundFetch, wixAPIFetch, getActiveToken, options, hostName) {\n return runWithoutContext(() => origFunc({\n request: async (factory) => {\n const requestOptions = factory({\n host: options?.HTTPHost || DEFAULT_API_URL,\n });\n let request = requestOptions;\n if (request.method === 'GET' &&\n request.fallback?.length &&\n request.params.toString().length > 4000) {\n request = requestOptions.fallback[0];\n }\n const domain = options?.HTTPHost ?? DEFAULT_API_URL;\n let url = `https://${domain}${request.url}`;\n if (request.params && request.params.toString()) {\n url += `?${request.params.toString()}`;\n }\n try {\n const biHeader = biHeaderGenerator(requestOptions, publicMetadata, hostName);\n const res = await boundFetch(url, {\n method: request.method,\n ...(request.data && {\n body: JSON.stringify(request.data),\n }),\n headers: {\n ...biHeader,\n },\n });\n if (res.status !== 200) {\n let dataError = null;\n try {\n dataError = await res.json();\n }\n catch (e) {\n //\n }\n throw errorBuilder(res.status, dataError?.message, dataError?.details, {\n requestId: res.headers.get('X-Wix-Request-Id'),\n details: dataError,\n });\n }\n const data = await res.json();\n return {\n data,\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n };\n }\n catch (e) {\n if (e.message?.includes('fetch is not defined')) {\n console.error('Node.js v18+ is required');\n }\n throw e;\n }\n },\n fetchWithAuth: boundFetch,\n wixAPIFetch,\n getActiveToken,\n }));\n}\nconst errorBuilder = (code, description, details, data) => {\n return {\n response: {\n data: {\n details: {\n ...(!details?.validationError && {\n applicationError: {\n description,\n code,\n data,\n },\n }),\n ...details,\n },\n message: description,\n },\n status: code,\n },\n };\n};\n","import { EventDefinition, } from '@wix/sdk-types';\nimport { createNanoEvents } from './nanoevents.js';\nexport const isEventHandlerModule = (val) => val.__type === 'event-definition';\nexport function buildEventDefinition(eventDefinition, registerHandler) {\n return (handler) => {\n registerHandler(eventDefinition, handler);\n };\n}\nfunction runHandler(eventDefinition, handler, payload, baseEventMetadata) {\n let envelope;\n if (eventDefinition.isDomainEvent) {\n const domainEventPayload = payload;\n const { deletedEvent, actionEvent, createdEvent, updatedEvent, ...domainEventMetadata } = domainEventPayload;\n const metadata = {\n ...baseEventMetadata,\n ...domainEventMetadata,\n };\n if (deletedEvent) {\n if (deletedEvent?.deletedEntity) {\n envelope = {\n entity: deletedEvent?.deletedEntity,\n metadata,\n };\n }\n else {\n envelope = { metadata };\n }\n }\n else if (actionEvent) {\n envelope = {\n data: actionEvent.body,\n metadata,\n };\n }\n else {\n envelope = {\n entity: createdEvent?.entity ?? updatedEvent?.currentEntity,\n metadata,\n };\n }\n }\n else {\n envelope = {\n data: payload,\n metadata: baseEventMetadata,\n };\n }\n const transformFromRESTFn = eventDefinition.transformations ?? ((x) => x);\n return handler(transformFromRESTFn(envelope));\n}\nexport function eventHandlersModules(authStrategy) {\n const eventHandlers = new Map();\n const webhooksEmitter = createNanoEvents();\n const client = {\n ...webhooksEmitter,\n getRegisteredEvents: () => eventHandlers,\n async process(jwt, opts = {\n expectedEvents: [],\n }) {\n const { eventType, identity, instanceId, payload } = await this.parseJWT(jwt);\n const allExpectedEvents = [\n ...opts.expectedEvents,\n ...Array.from(eventHandlers.keys()).map((type) => ({ type })),\n ];\n if (allExpectedEvents.length > 0 &&\n !allExpectedEvents.some(({ type }) => type === eventType)) {\n throw new Error(`Unexpected event type: ${eventType}. Expected one of: ${allExpectedEvents\n .map((x) => x.type)\n .join(', ')}`);\n }\n const handlers = eventHandlers.get(eventType) ?? [];\n await Promise.all(handlers.map(({ eventDefinition, handler }) => runHandler(eventDefinition, handler, payload, {\n instanceId,\n identity,\n })));\n return {\n instanceId,\n eventType,\n payload,\n identity,\n };\n },\n async processRequest(request, opts) {\n const body = await request.text();\n return this.process(body, opts);\n },\n async parseJWT(jwt) {\n if (!authStrategy.decodeJWT) {\n throw new Error('decodeJWT is not supported by the authentication strategy');\n }\n const { decoded, valid } = await authStrategy.decodeJWT(jwt);\n if (!valid) {\n throw new Error('JWT is not valid');\n }\n if (typeof decoded.data !== 'string') {\n throw new Error(`Unexpected type of JWT data: expected string, got ${typeof decoded.data}`);\n }\n const parsedDecoded = JSON.parse(decoded.data);\n const eventType = parsedDecoded.eventType;\n const instanceId = parsedDecoded.instanceId;\n const identity = parsedDecoded.identity\n ? JSON.parse(parsedDecoded.identity)\n : undefined;\n const payload = JSON.parse(parsedDecoded.data);\n return {\n instanceId,\n eventType,\n payload,\n identity,\n };\n },\n async parseRequest(request) {\n const jwt = await request.text();\n return this.parseJWT(jwt);\n },\n async executeHandlers(event) {\n const allExpectedEvents = Array.from(eventHandlers.keys()).map((type) => ({ type }));\n if (allExpectedEvents.length > 0 &&\n !allExpectedEvents.some(({ type }) => type === event.eventType)) {\n throw new Error(`Unexpected event type: ${event.eventType}. Expected one of: ${allExpectedEvents\n .map((x) => x.type)\n .join(', ')}`);\n }\n const handlers = eventHandlers.get(event.eventType) ?? [];\n await Promise.all(handlers.map(({ eventDefinition, handler }) => runHandler(eventDefinition, handler, event.payload, {\n instanceId: event.instanceId,\n identity: event.identity,\n })));\n },\n apps: {\n AppInstalled: EventDefinition('AppInstalled')(),\n AppRemoved: EventDefinition('AppRemoved')(),\n },\n };\n return {\n initModule(eventDefinition) {\n return (handler) => {\n const handlers = eventHandlers.get(eventDefinition.type) ?? [];\n handlers.push({ eventDefinition, handler });\n eventHandlers.set(eventDefinition.type, handlers);\n webhooksEmitter.emit('registered', eventDefinition);\n };\n },\n client,\n };\n}\n","// Inlined from https://github.com/ai/nanoevents/blob/main/index.js\n/**\n * Create event emitter.\n *\n * ```js\n * import { createNanoEvents } from 'nanoevents'\n *\n * class Ticker {\n * constructor() {\n * this.emitter = createNanoEvents()\n * }\n * on(...args) {\n * return this.emitter.on(...args)\n * }\n * tick() {\n * this.emitter.emit('tick')\n * }\n * }\n * ```\n * @returns Event emitter.\n */\nexport function createNanoEvents() {\n return {\n emit(event, ...args) {\n for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {\n callbacks[i](...args);\n }\n },\n events: {},\n on(event, cb) {\n (this.events[event] ||= []).push(cb);\n return () => {\n this.events[event] = this.events[event]?.filter((i) => cb !== i);\n };\n },\n };\n}\n","import { createNanoEvents } from './nanoevents.js';\nexport const isServicePluginModule = (val) => val.__type === 'service-plugin-definition';\nexport function servicePluginsModules(authStrategy) {\n const servicePluginsImplementations = new Map();\n const servicePluginsEmitter = createNanoEvents();\n const client = {\n ...servicePluginsEmitter,\n getRegisteredServicePlugins: () => servicePluginsImplementations,\n async parseJWT(jwt) {\n if (!authStrategy.decodeJWT) {\n throw new Error('decodeJWT is not supported by the authentication strategy');\n }\n const { decoded, valid } = await authStrategy.decodeJWT(jwt, true);\n if (!valid) {\n throw new Error('JWT is not valid');\n }\n if (typeof decoded.data !== 'object' ||\n decoded.data === null ||\n !('metadata' in decoded.data) ||\n typeof decoded.data.metadata !== 'object' ||\n decoded.data.metadata === null ||\n !('appExtensionType' in decoded.data.metadata) ||\n typeof decoded.data.metadata.appExtensionType !== 'string') {\n throw new Error('Unexpected JWT data: expected object with metadata.appExtensionType string');\n }\n return decoded.data;\n },\n async process(request) {\n const servicePluginRequest = await this.parseJWT(request.body);\n return this.executeHandler(servicePluginRequest, request.url);\n },\n async parseRequest(request) {\n const body = await request.text();\n return this.parseJWT(body);\n },\n async processRequest(request) {\n const url = request.url;\n const body = await request.text();\n try {\n const implMethodResult = await this.process({ url, body });\n return Response.json(implMethodResult);\n }\n catch (err) {\n if (err.errorType === 'SPI' && err.applicationCode && err.httpCode) {\n return Response.json({ applicationError: { code: err.applicationCode, data: err.data } }, { status: err.httpCode });\n }\n throw err;\n }\n },\n async executeHandler(servicePluginRequest, url) {\n const componentType = servicePluginRequest.metadata.appExtensionType.toLowerCase();\n const implementations = servicePluginsImplementations.get(componentType) ?? [];\n if (implementations.length === 0) {\n throw new Error(`No service plugin implementations found for component type ${componentType}`);\n }\n else if (implementations.length > 1) {\n throw new Error(`Multiple service plugin implementations found for component type ${componentType}. This is currently not supported`);\n }\n const { implementation: impl, servicePluginDefinition } = implementations[0];\n const method = servicePluginDefinition.methods.find((m) => url.endsWith(m.primaryHttpMappingPath));\n if (!method) {\n throw new Error('Unexpect request: request url did not match any method: ' + url);\n }\n const implMethod = impl[method.name];\n if (!implMethod) {\n throw new Error(`Got request for service plugin method ${method.name} but no implementation was provided. Available methods: ${Object.keys(impl).join(', ')}`);\n }\n return method.transformations.toREST(await implMethod(method.transformations.fromREST(servicePluginRequest)));\n },\n };\n return {\n initModule(servicePluginDefinition) {\n return (implementation) => {\n const implementations = servicePluginsImplementations.get(servicePluginDefinition.componentType.toLowerCase()) ?? [];\n implementations.push({ servicePluginDefinition, implementation });\n servicePluginsImplementations.set(servicePluginDefinition.componentType.toLowerCase(), implementations);\n servicePluginsEmitter.emit('registered', servicePluginDefinition);\n };\n },\n client,\n };\n}\n"],"mappings":"sIACAA,IADA,OAAS,cAAAC,MAAkB,mBCA3B,IAAMC,EAAeC,GAAW,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AArB,EACA,cAAcuB,EAAaC,EAAO,CAAE,SAAU,EAAM,EAAG,CAC/CD,IAAgB,SACZ,WAAW,iBAAmB,KAC1BC,EAAK,SACL,WAAW,gBAAgB,eAAiB,KAG5C,WAAW,gBAAgB,OAAS,KAIpCA,EAAK,SACL,WAAW,gBAAkB,CAAE,eAAgB,IAAK,EAGpD,WAAW,gBAAkB,CAAE,OAAQ,IAAK,EAKhDA,EAAK,SACLC,EAAW,eAAiB,KAG5BA,EAAW,OAAS,IAGhC,EAOA,MAAO,CAACX,EAAalB,IAAY,CAC7B,IAAMY,EAAa9B,EAAO,MAAM,YAAc+B,EACxCO,EAAW,IAAI,IAAIF,EAAa,WAAWN,CAAU,EAAE,EAC7D,OAAAQ,EAAS,KAAOR,EAChBQ,EAAS,SAAW,QACbtB,EAAWsB,EAAS,SAAS,EAAGpB,CAAO,CAClD,EACA,cAAAb,EACA,MAAM,QAAQ2C,EAAOC,EAAWH,EAAO,CACnC,WAAY,OAChB,EAAG,CACC,IAAMhB,EAAa9B,GAAQ,MAAM,YAAc+B,EACzCmB,EAAM,MAAMlC,EAAW,WAAWc,CAAU,YAAYgB,EAAK,UAAU,GAAI,CAC7E,OAAQ,OACR,QAAS,CACL,eAAgB,kBACpB,EACA,KAAM,KAAK,UAAU,CAAE,MAAAE,EAAO,UAAAC,CAAU,CAAC,CAC7C,CAAC,EACD,GAAIC,EAAI,SAAW,IACf,MAAM,IAAIC,EAAmB,sCAAsCD,EAAI,MAAM,GAAIA,CAAG,EAExF,GAAM,CAAE,KAAAE,EAAM,OAAAC,CAAO,EAAI,MAAMH,EAAI,KAAK,EACxC,MAAO,CAAE,KAAME,GAAQ,CAAC,EAAG,OAAAC,CAAO,CACtC,EACA,SAAUxC,EACV,eAAgBH,CACpB,CACJ","names":["init_browser","wixContext","parseMethod","method","toHTTPModule","factory","httpClient","payload","requestOptions","HTTPFactory","context","url","params","response","transformations","data","transform","e","isAmbassadorModule","module","PUBLIC_METADATA_KEY","DEFAULT_API_URL","FetchErrorResponse","message","response","__publicField","dataError","errorBuilder","code","description","details","data","getDefaultContentHeader","options","isObject","val","isHostModule","val","buildHostModule","host","WixBIHeaderName","biHeaderGenerator","apiMetadata","publicMetadata","environment","objectToKeyValue","input","_","value","key","buildRESTDescriptor","origFunc","publicMetadata","boundFetch","wixAPIFetch","getActiveToken","options","hostName","runWithoutContext","factory","requestOptions","DEFAULT_API_URL","request","url","biHeader","biHeaderGenerator","res","dataError","errorBuilder","e","code","description","details","data","init_browser","createNanoEvents","event","args","i","callbacks","length","cb","isEventHandlerModule","val","runHandler","eventDefinition","handler","payload","baseEventMetadata","envelope","domainEventPayload","deletedEvent","actionEvent","createdEvent","updatedEvent","domainEventMetadata","metadata","transformFromRESTFn","x","eventHandlersModules","authStrategy","eventHandlers","webhooksEmitter","createNanoEvents","client","jwt","opts","eventType","identity","instanceId","allExpectedEvents","type","handlers","request","body","decoded","valid","parsedDecoded","event","EventDefinition","isServicePluginModule","val","servicePluginsModules","authStrategy","servicePluginsImplementations","servicePluginsEmitter","createNanoEvents","client","jwt","decoded","valid","request","servicePluginRequest","body","url","implMethodResult","err","componentType","implementations","impl","servicePluginDefinition","method","m","implMethod","implementation","createClient","config","_headers","authStrategy","_","boundGetAuthHeaders","fetchWithAuth","urlOrRequest","requestInit","k","v","servicePluginsClient","initServicePluginModule","servicePluginsModules","eventHandlersClient","initEventHandlerModule","eventHandlersModules","boundFetch","url","options","authHeaders","defaultContentTypeHeader","getDefaultContentHeader","use","modules","metadata","isEventHandlerModule","isServicePluginModule","isHostModule","buildHostModule","SERVICE_PLUGIN_ERROR_TYPE","apiBaseUrl","DEFAULT_API_URL","buildRESTDescriptor","runWithoutContext","isAmbassadorModule","toHTTPModule","relativeUrl","fetchOptions","finalUrl","isObject","key","value","PUBLIC_METADATA_KEY","setHeaders","headers","contextType","opts","wixContext","query","variables","res","FetchErrorResponse","data","errors"]}
@@ -1,2 +1,2 @@
1
- import{a as V}from"./chunk-FLUCZ5U6.js";import{a as D}from"./chunk-VXQAZIAE.js";import"./chunk-ZM5O3GFB.js";import"./chunk-SBZEOPXX.js";function k(){return k=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},k.apply(null,arguments)}import Ee,{useEffect as le,useState as j}from"react";function w(e){"@babel/helpers - typeof";return w=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},w(e)}function N(e,t){if(w(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(w(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function K(e){var t=N(e,"string");return w(t)=="symbol"?t:t+""}function q(e,t,r){return(t=K(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var M=class extends Error{constructor(t){let{message:r,code:n}=t;super(r),q(this,"code",void 0),this.message=r,this.code=n}};var F=()=>{let e=u=>{let{channel:c}=u;return function(){let f=c.showToast(...arguments);return{remove:()=>Promise.resolve(f).then(g=>g.remove())}}},t=u=>{let{channel:c}=u;return function(){let f=c.observeState(...arguments);return{disconnect:()=>Promise.resolve(f).then(g=>g.disconnect())}}};return{showToast:e,observeState:t,navigate:u=>{let{channel:c}=u;return function(){return c.navigate(...arguments)}},navigateBack:u=>{let{channel:c}=u;return()=>c.navigateBack()},openModal:u=>{let{channel:c}=u;return(f,h)=>{let[g,E]=typeof f=="string"?[f,h]:[f.modalId,f.params],v=c.openModal(g,E);return{modalClosed:Promise.resolve(v).then(y=>y.modalClosed)}}},closeModal:u=>{let{channel:c}=u;return f=>{if(f===void 0)return c.closeModal();let h=JSON.parse(JSON.stringify(f));return c.closeModal(h)}},getAccessToken:u=>{let{channel:c}=u;return()=>c.getAccessToken()},getPageUrl:u=>{let{channel:c}=u;return function(){return c.getPageUrl(...arguments)}},openMediaManager:u=>{let{channel:c}=u;return function(){return c.openMediaManager(...arguments)}},addSitePlugin:u=>{let{channel:c}=u;return(f,h)=>{let g="802c76e4-b381-4bb3-9152-96acabbf3194",E=h?.placement||{},v=c.openModal(g,{...E,pluginId:f,action:"populate"});return Promise.resolve(v).then(y=>y.modalClosed).then(y=>{if(y?.type===void 0)throw new M({message:"Aborted by user",code:3006});if(y?.type==="ERROR")throw new M(y.data.error)})}},onBeforeUnload:u=>{let{channel:c}=u;return function(){return c.onBeforeUnload(...arguments)}},setPageTitle:u=>{let{channel:c}=u;return f=>c.setPageTitle(f)},getLanguage:u=>{let c=null;return async()=>{var f;if(c)return c;let h=null;return c=await new Promise(g=>{h=t(u)((E,v)=>{g(v.language)})}),(f=h)==null||f.disconnect(),c}},requestFeedback:u=>{let{channel:c}=u;return function(){return c.requestFeedback(...arguments)}},onLayerStateChange:u=>{let{channel:c}=u;return function(){let f=c.onLayerStateChange(...arguments);return{remove:()=>Promise.resolve(f).then(g=>g.remove())}}},installApp:u=>{let{channel:c}=u;return c.installApp}}};var G=e=>{let{createHost:t}=e,r=F();return{...V(r),host:t,auth:()=>({getAuthHeaders:async n=>({headers:{Authorization:await r.getAccessToken(n)()}})})}};var J=(e,t)=>{let r=()=>e.updateHeight(t.offsetHeight),n=new ResizeObserver(r);return n.observe(t),()=>n.disconnect()};var X=Symbol("Comlink.proxy"),de=Symbol("Comlink.endpoint"),L=Symbol("Comlink.releaseProxy"),C=Symbol("Comlink.thrown"),Q=e=>typeof e=="object"&&e!==null||typeof e=="function",fe={canHandle:e=>Q(e)&&e[X],serialize(e){let{port1:t,port2:r}=new MessageChannel;return R(e,t),[r,[r]]},deserialize(e){return e.start(),_(e)}},me={canHandle:e=>Q(e)&&C in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Y=new Map([["proxy",fe],["throw",me]]);function R(e,t=self){t.addEventListener("message",function r(n){if(!n||!n.data)return;let{id:s,type:a,path:o}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(x),l;try{let d=o.slice(0,-1).reduce((p,b)=>p[b],e),m=o.reduce((p,b)=>p[b],e);switch(a){case 0:l=m;break;case 1:d[o.slice(-1)[0]]=x(n.data.value),l=!0;break;case 2:l=m.apply(d,i);break;case 3:{let p=new m(...i);l=S(p)}break;case 4:{let{port1:p,port2:b}=new MessageChannel;R(e,b),l=ge(p,[p])}break;case 5:l=void 0;break}}catch(d){l={value:d,[C]:0}}Promise.resolve(l).catch(d=>({value:d,[C]:0})).then(d=>{let[m,p]=B(d);t.postMessage(Object.assign(Object.assign({},m),{id:s}),p),a===5&&(t.removeEventListener("message",r),Z(t))})}),t.start&&t.start()}function pe(e){return e.constructor.name==="MessagePort"}function Z(e){pe(e)&&e.close()}function _(e,t){return U(e,[],t)}function A(e){if(e)throw new Error("Proxy has been released and is not useable")}function U(e,t=[],r=function(){}){let n=!1,s=new Proxy(r,{get(a,o){if(A(n),o===L)return()=>P(e,{type:5,path:t.map(i=>i.toString())}).then(()=>{Z(e),n=!0});if(o==="then"){if(t.length===0)return{then:()=>s};let i=P(e,{type:0,path:t.map(l=>l.toString())}).then(x);return i.then.bind(i)}return U(e,[...t,o])},set(a,o,i){A(n);let[l,d]=B(i);return P(e,{type:1,path:[...t,o].map(m=>m.toString()),value:l},d).then(x)},apply(a,o,i){A(n);let l=t[t.length-1];if(l===de)return P(e,{type:4}).then(x);if(l==="bind")return U(e,t.slice(0,-1));let[d,m]=$(i);return P(e,{type:2,path:t.map(p=>p.toString()),argumentList:d},m).then(x)},construct(a,o){A(n);let[i,l]=$(o);return P(e,{type:3,path:t.map(d=>d.toString()),argumentList:i},l).then(x)}});return s}function he(e){return Array.prototype.concat.apply([],e)}function $(e){let t=e.map(B);return[t.map(r=>r[0]),he(t.map(r=>r[1]))]}var ee=new WeakMap;function ge(e,t){return ee.set(e,t),e}function S(e){return Object.assign(e,{[X]:!0})}function B(e){for(let[t,r]of Y)if(r.canHandle(e)){let[n,s]=r.serialize(e);return[{type:3,name:t,value:n},s]}return[{type:0,value:e},ee.get(e)||[]]}function x(e){switch(e.type){case 3:return Y.get(e.name).deserialize(e.value);case 0:return e.value}}function P(e,t,r){return new Promise(n=>{let s=ye();e.addEventListener("message",function a(o){!o.data||!o.data.id||o.data.id!==s||(e.removeEventListener("message",a),n(o.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:s},t),r)})}function ye(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var I="__proxyCallbackId__wixSDK__",W="__proxyPromiseId__wixSDK__",re=e=>we(e,t=>async function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let[a,o]=z(n),i=await t(S(a),o);return ne(i)});var be=async e=>{let[t,r]=z(await e);return S({proxies:t,clonables:r})},ne=async e=>O(e?.proxies,await e?.clonables),z=e=>{let t=(s,a)=>{if(oe(a)){let o=te();return s.promises[o]=a,{[W]:o}}if(xe(a)){let o=te();return s.callbacks[o]=(i,l)=>{let d=O(i,l),m=a(...d);return be(m)},{[I]:o}}return Array.isArray(a)?a.map(o=>t(s,o)):H(a)?se(a,o=>t(s,o)):a},r={promises:{},callbacks:{}},n=t(r,e);return[r,n]},O=(e,t)=>{if(Array.isArray(t))return t.map(r=>O(e,r));if(H(t)&&t.hasOwnProperty(W)){let r=t[W];return e.promises[r]}if(H(t)&&t.hasOwnProperty(I)){let r=t[I];return async function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let[o,i]=z(s),l=await e.callbacks[r](S(o),i);return ne(l)}}return H(t)?se(t,r=>O(e,r)):t},we=(e,t)=>new Proxy(e,{get(r,n){return r[n]?t(r[n]):()=>{throw new Error(`Serialization error occurred while accessing ${n} property of ${r}`)}}}),oe=e=>e instanceof Promise,H=e=>e&&typeof e=="object"&&!oe(e),xe=e=>typeof e=="function",se=(e,t)=>{let r=n=>{let[s,a]=n;return[s,t(a)]};return Object.fromEntries(Object.entries(e).map(r))},te=(()=>{let e=0;return()=>++e})();var Pe="wix-sdk-bo-hello-handshake",ae=e=>{let{postMessage:t,origin:r}=e,{port1:n,port2:s}=new MessageChannel;t({code:Pe,version:"1.0.0",port:s},r,[s]);let i=re(_(n));return{channel:i,close:()=>i[L]()}};var ve=["https://manage.wix.com","https://manage.editorx.com"],Me=new Set(ve),ie=e=>Me.has(e);var ce=e=>{let t=new EventTarget,r=typeof window>"u",n=i=>{t.dispatchEvent(new CustomEvent("beforeunload",{cancelable:!0}))||(i.preventDefault(),i.returnValue=!0)},s=e.onBeforeUnload(n),a=()=>{r||window.removeEventListener("beforeunload",n),s.then(i=>{let{remove:l}=i;return l()})};return r||(window.addEventListener("beforeunload",n),window.addEventListener("unload",a)),{onBeforeUnload:i=>(t.addEventListener("beforeunload",i),{remove:()=>{t.removeEventListener("beforeunload",i)}}),clearBeforeUnloadHandler:a}};var ue=function(e){e===void 0&&(e={});let t=new URLSearchParams(typeof window<"u"?window.location.search:"?"),r=e.origin||t.get("origin")||"",n=e.postMessage||window.parent.postMessage.bind(window.parent);if(!ie(r))throw new Error("Wix Dashboard SDK: Unable to establish a connection with the Wix dashboard. Please ensure that you are running your app within the Wix dashboard.");let{channel:s,close:a}=ae({postMessage:n,origin:r}),o=[a];if(e.autoHeightUpdate===void 0||e.autoHeightUpdate){let m=e.autoHeightElement||document.documentElement,p=J(s,m);o.push(()=>p())}let{onBeforeUnload:i,clearBeforeUnloadHandler:l}=ce(s);return o.push(l),{channel:new Proxy(s,{get(m,p,b){return p==="onBeforeUnload"?i:Reflect.get(m,p,b)}}),close:()=>o.forEach(m=>m()),essentials:t.has("essentials")?Se(t.get("essentials")):void 0}};function Se(e){if(e)try{return JSON.parse(decodeURIComponent(e))}catch(t){console.warn('Failed to parse "essentials" query parameter. Make sure to run the code inside a supported Wix App extension.',t);return}}var T=G({createHost:ue});var ke=e=>t=>{let{host:r,...n}=t,[s,a]=j(!1),{host:o,props:i}=Ae(r);return le(()=>{o&&(D({auth:T.auth(),host:o}).enableContext("module"),a(!0))},[o]),!o||!i||!s?null:Ee.createElement(e,k({host:o},i,n))},Ae=e=>{let[t,r]=j(),[n,s]=j();return le(()=>{if(e)return;let a=T.host();r(a);let o=a.channel.observeState,i=o(d=>{s(d)}),l=async()=>{r(void 0),s(void 0),(await i).disconnect(),a.close()};return()=>{l()}},[e]),e?{host:e,props:{}}:{host:t,props:n}};export{ke as withContextualWixClient};
1
+ import{a as V}from"./chunk-DGX4CFXG.js";import{a as D}from"./chunk-XYIDODIB.js";import"./chunk-BGTZ3RNN.js";import"./chunk-7EYXEF6M.js";import"./chunk-SBZEOPXX.js";function k(){return k=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},k.apply(null,arguments)}import Ee,{useEffect as le,useState as j}from"react";function w(e){"@babel/helpers - typeof";return w=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},w(e)}function N(e,t){if(w(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(w(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function K(e){var t=N(e,"string");return w(t)=="symbol"?t:t+""}function q(e,t,r){return(t=K(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var M=class extends Error{constructor(t){let{message:r,code:n}=t;super(r),q(this,"code",void 0),this.message=r,this.code=n}};var F=()=>{let e=u=>{let{channel:c}=u;return function(){let f=c.showToast(...arguments);return{remove:()=>Promise.resolve(f).then(g=>g.remove())}}},t=u=>{let{channel:c}=u;return function(){let f=c.observeState(...arguments);return{disconnect:()=>Promise.resolve(f).then(g=>g.disconnect())}}};return{showToast:e,observeState:t,navigate:u=>{let{channel:c}=u;return function(){return c.navigate(...arguments)}},navigateBack:u=>{let{channel:c}=u;return()=>c.navigateBack()},openModal:u=>{let{channel:c}=u;return(f,h)=>{let[g,E]=typeof f=="string"?[f,h]:[f.modalId,f.params],v=c.openModal(g,E);return{modalClosed:Promise.resolve(v).then(y=>y.modalClosed)}}},closeModal:u=>{let{channel:c}=u;return f=>{if(f===void 0)return c.closeModal();let h=JSON.parse(JSON.stringify(f));return c.closeModal(h)}},getAccessToken:u=>{let{channel:c}=u;return()=>c.getAccessToken()},getPageUrl:u=>{let{channel:c}=u;return function(){return c.getPageUrl(...arguments)}},openMediaManager:u=>{let{channel:c}=u;return function(){return c.openMediaManager(...arguments)}},addSitePlugin:u=>{let{channel:c}=u;return(f,h)=>{let g="802c76e4-b381-4bb3-9152-96acabbf3194",E=h?.placement||{},v=c.openModal(g,{...E,pluginId:f,action:"populate"});return Promise.resolve(v).then(y=>y.modalClosed).then(y=>{if(y?.type===void 0)throw new M({message:"Aborted by user",code:3006});if(y?.type==="ERROR")throw new M(y.data.error)})}},onBeforeUnload:u=>{let{channel:c}=u;return function(){return c.onBeforeUnload(...arguments)}},setPageTitle:u=>{let{channel:c}=u;return f=>c.setPageTitle(f)},getLanguage:u=>{let c=null;return async()=>{var f;if(c)return c;let h=null;return c=await new Promise(g=>{h=t(u)((E,v)=>{g(v.language)})}),(f=h)==null||f.disconnect(),c}},requestFeedback:u=>{let{channel:c}=u;return function(){return c.requestFeedback(...arguments)}},onLayerStateChange:u=>{let{channel:c}=u;return function(){let f=c.onLayerStateChange(...arguments);return{remove:()=>Promise.resolve(f).then(g=>g.remove())}}},installApp:u=>{let{channel:c}=u;return c.installApp}}};var G=e=>{let{createHost:t}=e,r=F();return{...V(r),host:t,auth:()=>({getAuthHeaders:async n=>({headers:{Authorization:await r.getAccessToken(n)()}})})}};var J=(e,t)=>{let r=()=>e.updateHeight(t.offsetHeight),n=new ResizeObserver(r);return n.observe(t),()=>n.disconnect()};var X=Symbol("Comlink.proxy"),de=Symbol("Comlink.endpoint"),L=Symbol("Comlink.releaseProxy"),C=Symbol("Comlink.thrown"),Q=e=>typeof e=="object"&&e!==null||typeof e=="function",fe={canHandle:e=>Q(e)&&e[X],serialize(e){let{port1:t,port2:r}=new MessageChannel;return R(e,t),[r,[r]]},deserialize(e){return e.start(),_(e)}},me={canHandle:e=>Q(e)&&C in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Y=new Map([["proxy",fe],["throw",me]]);function R(e,t=self){t.addEventListener("message",function r(n){if(!n||!n.data)return;let{id:s,type:a,path:o}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(x),l;try{let d=o.slice(0,-1).reduce((p,b)=>p[b],e),m=o.reduce((p,b)=>p[b],e);switch(a){case 0:l=m;break;case 1:d[o.slice(-1)[0]]=x(n.data.value),l=!0;break;case 2:l=m.apply(d,i);break;case 3:{let p=new m(...i);l=S(p)}break;case 4:{let{port1:p,port2:b}=new MessageChannel;R(e,b),l=ge(p,[p])}break;case 5:l=void 0;break}}catch(d){l={value:d,[C]:0}}Promise.resolve(l).catch(d=>({value:d,[C]:0})).then(d=>{let[m,p]=B(d);t.postMessage(Object.assign(Object.assign({},m),{id:s}),p),a===5&&(t.removeEventListener("message",r),Z(t))})}),t.start&&t.start()}function pe(e){return e.constructor.name==="MessagePort"}function Z(e){pe(e)&&e.close()}function _(e,t){return U(e,[],t)}function A(e){if(e)throw new Error("Proxy has been released and is not useable")}function U(e,t=[],r=function(){}){let n=!1,s=new Proxy(r,{get(a,o){if(A(n),o===L)return()=>P(e,{type:5,path:t.map(i=>i.toString())}).then(()=>{Z(e),n=!0});if(o==="then"){if(t.length===0)return{then:()=>s};let i=P(e,{type:0,path:t.map(l=>l.toString())}).then(x);return i.then.bind(i)}return U(e,[...t,o])},set(a,o,i){A(n);let[l,d]=B(i);return P(e,{type:1,path:[...t,o].map(m=>m.toString()),value:l},d).then(x)},apply(a,o,i){A(n);let l=t[t.length-1];if(l===de)return P(e,{type:4}).then(x);if(l==="bind")return U(e,t.slice(0,-1));let[d,m]=$(i);return P(e,{type:2,path:t.map(p=>p.toString()),argumentList:d},m).then(x)},construct(a,o){A(n);let[i,l]=$(o);return P(e,{type:3,path:t.map(d=>d.toString()),argumentList:i},l).then(x)}});return s}function he(e){return Array.prototype.concat.apply([],e)}function $(e){let t=e.map(B);return[t.map(r=>r[0]),he(t.map(r=>r[1]))]}var ee=new WeakMap;function ge(e,t){return ee.set(e,t),e}function S(e){return Object.assign(e,{[X]:!0})}function B(e){for(let[t,r]of Y)if(r.canHandle(e)){let[n,s]=r.serialize(e);return[{type:3,name:t,value:n},s]}return[{type:0,value:e},ee.get(e)||[]]}function x(e){switch(e.type){case 3:return Y.get(e.name).deserialize(e.value);case 0:return e.value}}function P(e,t,r){return new Promise(n=>{let s=ye();e.addEventListener("message",function a(o){!o.data||!o.data.id||o.data.id!==s||(e.removeEventListener("message",a),n(o.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:s},t),r)})}function ye(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var I="__proxyCallbackId__wixSDK__",W="__proxyPromiseId__wixSDK__",re=e=>we(e,t=>async function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let[a,o]=z(n),i=await t(S(a),o);return ne(i)});var be=async e=>{let[t,r]=z(await e);return S({proxies:t,clonables:r})},ne=async e=>O(e?.proxies,await e?.clonables),z=e=>{let t=(s,a)=>{if(oe(a)){let o=te();return s.promises[o]=a,{[W]:o}}if(xe(a)){let o=te();return s.callbacks[o]=(i,l)=>{let d=O(i,l),m=a(...d);return be(m)},{[I]:o}}return Array.isArray(a)?a.map(o=>t(s,o)):H(a)?se(a,o=>t(s,o)):a},r={promises:{},callbacks:{}},n=t(r,e);return[r,n]},O=(e,t)=>{if(Array.isArray(t))return t.map(r=>O(e,r));if(H(t)&&t.hasOwnProperty(W)){let r=t[W];return e.promises[r]}if(H(t)&&t.hasOwnProperty(I)){let r=t[I];return async function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let[o,i]=z(s),l=await e.callbacks[r](S(o),i);return ne(l)}}return H(t)?se(t,r=>O(e,r)):t},we=(e,t)=>new Proxy(e,{get(r,n){return r[n]?t(r[n]):()=>{throw new Error(`Serialization error occurred while accessing ${n} property of ${r}`)}}}),oe=e=>e instanceof Promise,H=e=>e&&typeof e=="object"&&!oe(e),xe=e=>typeof e=="function",se=(e,t)=>{let r=n=>{let[s,a]=n;return[s,t(a)]};return Object.fromEntries(Object.entries(e).map(r))},te=(()=>{let e=0;return()=>++e})();var Pe="wix-sdk-bo-hello-handshake",ae=e=>{let{postMessage:t,origin:r}=e,{port1:n,port2:s}=new MessageChannel;t({code:Pe,version:"1.0.0",port:s},r,[s]);let i=re(_(n));return{channel:i,close:()=>i[L]()}};var ve=["https://manage.wix.com","https://manage.editorx.com"],Me=new Set(ve),ie=e=>Me.has(e);var ce=e=>{let t=new EventTarget,r=typeof window>"u",n=i=>{t.dispatchEvent(new CustomEvent("beforeunload",{cancelable:!0}))||(i.preventDefault(),i.returnValue=!0)},s=e.onBeforeUnload(n),a=()=>{r||window.removeEventListener("beforeunload",n),s.then(i=>{let{remove:l}=i;return l()})};return r||(window.addEventListener("beforeunload",n),window.addEventListener("unload",a)),{onBeforeUnload:i=>(t.addEventListener("beforeunload",i),{remove:()=>{t.removeEventListener("beforeunload",i)}}),clearBeforeUnloadHandler:a}};var ue=function(e){e===void 0&&(e={});let t=new URLSearchParams(typeof window<"u"?window.location.search:"?"),r=e.origin||t.get("origin")||"",n=e.postMessage||window.parent.postMessage.bind(window.parent);if(!ie(r))throw new Error("Wix Dashboard SDK: Unable to establish a connection with the Wix dashboard. Please ensure that you are running your app within the Wix dashboard.");let{channel:s,close:a}=ae({postMessage:n,origin:r}),o=[a];if(e.autoHeightUpdate===void 0||e.autoHeightUpdate){let m=e.autoHeightElement||document.documentElement,p=J(s,m);o.push(()=>p())}let{onBeforeUnload:i,clearBeforeUnloadHandler:l}=ce(s);return o.push(l),{channel:new Proxy(s,{get(m,p,b){return p==="onBeforeUnload"?i:Reflect.get(m,p,b)}}),close:()=>o.forEach(m=>m()),essentials:t.has("essentials")?Se(t.get("essentials")):void 0}};function Se(e){if(e)try{return JSON.parse(decodeURIComponent(e))}catch(t){console.warn('Failed to parse "essentials" query parameter. Make sure to run the code inside a supported Wix App extension.',t);return}}var T=G({createHost:ue});var ke=e=>t=>{let{host:r,...n}=t,[s,a]=j(!1),{host:o,props:i}=Ae(r);return le(()=>{o&&(D({auth:T.auth(),host:o}).enableContext("module"),a(!0))},[o]),!o||!i||!s?null:Ee.createElement(e,k({host:o},i,n))},Ae=e=>{let[t,r]=j(),[n,s]=j();return le(()=>{if(e)return;let a=T.host();r(a);let o=a.channel.observeState,i=o(d=>{s(d)}),l=async()=>{r(void 0),s(void 0),(await i).disconnect(),a.close()};return()=>{l()}},[e]),e?{host:e,props:{}}:{host:t,props:n}};export{ke as withContextualWixClient};
2
2
  //# sourceMappingURL=dashboard.js.map