@wix/cli-app 1.1.51 → 1.1.53

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 (100) hide show
  1. package/build/CreateVersionCommand-2W37YQW4.js +4 -0
  2. package/build/{CreateVersionCommand-6QSWW7PH.js.map → CreateVersionCommand-2W37YQW4.js.map} +1 -1
  3. package/build/DevCommand-JDHE7RQB.js +4 -0
  4. package/build/DevCommand-JDHE7RQB.js.map +1 -0
  5. package/build/GenerateCommand-3PPXF4B6.js +128 -0
  6. package/build/GenerateCommand-3PPXF4B6.js.map +1 -0
  7. package/build/LogsCommand-LQKTBY6D.js +4 -0
  8. package/build/LogsCommand-LQKTBY6D.js.map +1 -0
  9. package/build/PreviewCommand-H3HVD7DH.js +4 -0
  10. package/build/ServeCommand-RHONEHTF.js +4 -0
  11. package/build/{ServeCommand-BKLVSLW3.js.map → ServeCommand-RHONEHTF.js.map} +1 -1
  12. package/build/build-QN6TGE3Q.js +4 -0
  13. package/build/build-QN6TGE3Q.js.map +1 -0
  14. package/build/{chunk-GF6CV6CZ.js → chunk-2W2YJZP5.js} +29 -29
  15. package/build/chunk-2W2YJZP5.js.map +1 -0
  16. package/build/{chunk-5OKXHNO2.js → chunk-4CCKO52Z.js} +2 -2
  17. package/build/chunk-5OZZ7R6I.js +11 -0
  18. package/build/chunk-5OZZ7R6I.js.map +1 -0
  19. package/build/{chunk-NYC4UPCI.js → chunk-AXAJ7DJ4.js} +2 -2
  20. package/build/{chunk-MM7OD345.js → chunk-B5P4JHUW.js} +177 -128
  21. package/build/chunk-B5P4JHUW.js.map +1 -0
  22. package/build/{chunk-YXZSFVXG.js → chunk-C3O7WWDR.js} +2 -2
  23. package/build/{chunk-VOW75NWO.js → chunk-DLQYJEV6.js} +2 -2
  24. package/build/chunk-F6MVNSX2.js +4 -0
  25. package/build/chunk-F6MVNSX2.js.map +1 -0
  26. package/build/chunk-FVG3T57Z.js +4 -0
  27. package/build/{chunk-ZWY7YSYP.js → chunk-HILXNAWZ.js} +2 -2
  28. package/build/chunk-LDGXTJLC.js +4 -0
  29. package/build/chunk-LDGXTJLC.js.map +1 -0
  30. package/build/{chunk-7YIQAWRD.js → chunk-PSQ4AQFG.js} +2 -2
  31. package/build/{chunk-M7777RXR.js → chunk-QXIKCJLU.js} +3 -3
  32. package/build/{chunk-M7777RXR.js.map → chunk-QXIKCJLU.js.map} +1 -1
  33. package/build/{chunk-V3QQTT5C.js → chunk-SZ5JWJ4Q.js} +2 -2
  34. package/build/{chunk-IOW53RH7.js → chunk-TSAKYUDG.js} +2 -2
  35. package/build/{chunk-LYCV7HBR.js → chunk-WXOIL7LC.js} +2 -2
  36. package/build/chunk-YIGHU6O6.js +4 -0
  37. package/build/chunk-YIGHU6O6.js.map +1 -0
  38. package/build/chunk-YMRYABCG.js +115 -0
  39. package/build/chunk-YMRYABCG.js.map +1 -0
  40. package/build/cloudflare-runtime/entry.js +9 -2
  41. package/build/cloudflare-runtime/getRegisteredExtensions.js +9 -2
  42. package/build/index.js +2 -2
  43. package/build/index.js.map +1 -1
  44. package/build/platform-sdk/chunk-32RIHE6N.js +2 -0
  45. package/build/platform-sdk/{chunk-KEIVYRQX.js.map → chunk-32RIHE6N.js.map} +1 -1
  46. package/build/platform-sdk/dashboard.js +1 -1
  47. package/build/platform-sdk/editor.js +6 -6
  48. package/build/platform-sdk/editor.js.map +1 -1
  49. package/build/platform-sdk/site.js +1 -1
  50. package/build/preview-457BTAHF.js +4 -0
  51. package/build/preview-457BTAHF.js.map +1 -0
  52. package/build/render-command-W6CY3R4Q.js +4 -0
  53. package/build/render-command-W6CY3R4Q.js.map +1 -0
  54. package/internal/component-hmr-wrapper.tsx +9 -9
  55. package/package.json +5 -5
  56. package/templates/custom-element/dependencies.json +1 -1
  57. package/templates/dashboard-modal/files/modal.tsx.ejs +2 -2
  58. package/templates/dashboard-plugin/files/plugin.tsx.ejs +1 -1
  59. package/templates/site-plugin/dependencies.json +1 -1
  60. package/templates/site-plugin/files/plugin.tsx.ejs +1 -0
  61. package/build/CreateVersionCommand-6QSWW7PH.js +0 -4
  62. package/build/DevCommand-L3OC7OUZ.js +0 -4
  63. package/build/DevCommand-L3OC7OUZ.js.map +0 -1
  64. package/build/GenerateCommand-K5IS2QEG.js +0 -99
  65. package/build/GenerateCommand-K5IS2QEG.js.map +0 -1
  66. package/build/LogsCommand-5TTBMWFF.js +0 -4
  67. package/build/LogsCommand-5TTBMWFF.js.map +0 -1
  68. package/build/PreviewCommand-RCGDUERX.js +0 -4
  69. package/build/ServeCommand-BKLVSLW3.js +0 -4
  70. package/build/build-OSBBPACR.js +0 -4
  71. package/build/build-OSBBPACR.js.map +0 -1
  72. package/build/chunk-5UV5L6RZ.js +0 -4
  73. package/build/chunk-EUNKG7JY.js +0 -11
  74. package/build/chunk-EUNKG7JY.js.map +0 -1
  75. package/build/chunk-GF6CV6CZ.js.map +0 -1
  76. package/build/chunk-L2GYA6RW.js +0 -115
  77. package/build/chunk-L2GYA6RW.js.map +0 -1
  78. package/build/chunk-MM7OD345.js.map +0 -1
  79. package/build/chunk-VXMDSBPO.js +0 -4
  80. package/build/chunk-VXMDSBPO.js.map +0 -1
  81. package/build/chunk-YFYESJ2A.js +0 -4
  82. package/build/chunk-YFYESJ2A.js.map +0 -1
  83. package/build/chunk-YIQOAFCK.js +0 -4
  84. package/build/chunk-YIQOAFCK.js.map +0 -1
  85. package/build/platform-sdk/chunk-KEIVYRQX.js +0 -2
  86. package/build/preview-FY5YKH5Z.js +0 -4
  87. package/build/preview-FY5YKH5Z.js.map +0 -1
  88. package/build/render-command-4BGZ4KYD.js +0 -4
  89. package/build/render-command-4BGZ4KYD.js.map +0 -1
  90. /package/build/{PreviewCommand-RCGDUERX.js.map → PreviewCommand-H3HVD7DH.js.map} +0 -0
  91. /package/build/{chunk-5OKXHNO2.js.map → chunk-4CCKO52Z.js.map} +0 -0
  92. /package/build/{chunk-NYC4UPCI.js.map → chunk-AXAJ7DJ4.js.map} +0 -0
  93. /package/build/{chunk-YXZSFVXG.js.map → chunk-C3O7WWDR.js.map} +0 -0
  94. /package/build/{chunk-VOW75NWO.js.map → chunk-DLQYJEV6.js.map} +0 -0
  95. /package/build/{chunk-5UV5L6RZ.js.map → chunk-FVG3T57Z.js.map} +0 -0
  96. /package/build/{chunk-ZWY7YSYP.js.map → chunk-HILXNAWZ.js.map} +0 -0
  97. /package/build/{chunk-7YIQAWRD.js.map → chunk-PSQ4AQFG.js.map} +0 -0
  98. /package/build/{chunk-V3QQTT5C.js.map → chunk-SZ5JWJ4Q.js.map} +0 -0
  99. /package/build/{chunk-IOW53RH7.js.map → chunk-TSAKYUDG.js.map} +0 -0
  100. /package/build/{chunk-LYCV7HBR.js.map → chunk-WXOIL7LC.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{a as N,c as B,f as b}from"./chunk-SBZEOPXX.js";var G={};B(G,{EventDefinition:()=>E,SERVICE_PLUGIN_ERROR_TYPE:()=>C,ServicePluginDefinition:()=>z});function E(e,i=!1,r=a=>a){return()=>({__type:"event-definition",type:e,isDomainEvent:i,transformations:r})}function z(e,i){return{__type:"service-plugin-definition",componentType:e,methods:i}}var C,W=N(()=>{"use strict";C="wix_spi_error"});W();import{wixContext as J}from"@wix/sdk-context";var F=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}`)}},M=e=>i=>async r=>{let a,o=t=>{if(a=e(r)(t),a.url===void 0)throw new Error("Url was not successfully created for this request, please reach out to support channels for assistance.");let{method:l,url:s,params:c}=a;return{...a,method:F(l),url:s,data:a.data,params:c}};try{let t=await i.request(o);if(a===void 0)throw new Error("Request options were not created for this request, please reach out to support channels for assistance.");let l=Array.isArray(a.transformResponse)?a.transformResponse:[a.transformResponse],s=t.data;return l.forEach(c=>{c&&(s=c(t.data,t.headers))}),s}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}},A=e=>e.__isAmbassador?!0:!!e().__isAmbassador;var H="__metadata",w="www.wixapis.com";var T=class extends Error{constructor(r,a){super(r);b(this,"message");b(this,"response");this.message=r,this.response=a}async details(){let r=await this.response.json();return K(this.response.status,r?.message,r?.details,{requestId:this.response.headers.get("X-Wix-Request-Id"),details:r})}},K=(e,i,r,a)=>({details:{...!r?.validationError&&{applicationError:{description:i,code:e,data:a}},...r},message:i});var P=e=>e?.method&&["post","put","patch"].includes(e.method.toLocaleLowerCase())&&e.body?{"Content-Type":"application/json"}:{},S=e=>e&&typeof e=="object"&&!Array.isArray(e);var $=e=>e.__type==="host";function R(e,i){return e.create(i)}var V="x-wix-bi-gateway";function U(e,i,r){return{[V]:Y({environment:`js-sdk${r?`-${r}`:""}`,"package-name":e.packageName??i?.PACKAGE_NAME,"method-fqn":e.methodFqn,entity:e.entityFqdn})}}function Y(e){return Object.entries(e).filter(([i,r])=>!!r).map(([i,r])=>`${i}=${r}`).join(",")}import{wixContext as y}from"@wix/sdk-context";function v(e){let i=globalThis.__wix_context__,r={client:y.client,elevatedClient:y.elevatedClient},a;globalThis.__wix_context__=void 0,y.client=void 0,y.elevatedClient=void 0,typeof $wixContext<"u"&&(a={client:$wixContext?.client,elevatedClient:$wixContext?.elevatedClient},delete $wixContext.client,delete $wixContext.elevatedClient);try{return e()}finally{globalThis.__wix_context__=i,y.client=r.client,y.elevatedClient=r.elevatedClient,typeof $wixContext<"u"&&($wixContext.client=a.client,$wixContext.elevatedClient=a.elevatedClient)}}function j(e,i,r,a,o,t,l){return v(()=>e({request:async s=>{let c=s({host:t?.HTTPHost||w}),u=c;u.method==="GET"&&u.fallback?.length&&u.params.toString().length>4e3&&(u=c.fallback[0]);let x=`https://${t?.HTTPHost??w}${u.url}`;u.params&&u.params.toString()&&(x+=`?${u.params.toString()}`);try{let n=U(c,i,l),d=await r(x,{method:u.method,...u.data&&{body:JSON.stringify(u.data)},headers:{...n}});if(d.status!==200){let p=null;try{p=await d.json()}catch{}throw X(d.status,p?.message,p?.details,{requestId:d.headers.get("X-Wix-Request-Id"),details:p})}return{data:await d.json(),headers:d.headers,status:d.status,statusText:d.statusText}}catch(n){throw n.message?.includes("fetch is not defined")&&console.error("Node.js v18+ is required"),n}},fetchWithAuth:r,wixAPIFetch:a,getActiveToken:o}))}var X=(e,i,r,a)=>({response:{data:{details:{...!r?.validationError&&{applicationError:{description:i,code:e,data:a}},...r},message:i},status:e}});W();function g(){return{emit(e,...i){for(let r=0,a=this.events[e]||[],o=a.length;r<o;r++)a[r](...i)},events:{},on(e,i){return(this.events[e]||=[]).push(i),()=>{this.events[e]=this.events[e]?.filter(r=>i!==r)}}}}var k=e=>e.__type==="event-definition";function I(e,i,r,a){let o;if(e.isDomainEvent){let l=r,{deletedEvent:s,actionEvent:c,createdEvent:u,updatedEvent:h,...x}=l,n={...a,...x};s?s?.deletedEntity?o={entity:s?.deletedEntity,metadata:n}:o={metadata:n}:c?o={data:c.body,metadata:n}:o={entity:u?.entity??h?.currentEntity,metadata:n}}else o={data:r,metadata:a};let t=e.transformations??(l=>l);return i(t(o))}function q(e){let i=new Map,r=g(),a={...r,getRegisteredEvents:()=>i,async process(o,t={expectedEvents:[]}){let{eventType:l,identity:s,instanceId:c,payload:u}=await this.parseJWT(o),h=[...t.expectedEvents,...Array.from(i.keys()).map(n=>({type:n}))];if(h.length>0&&!h.some(({type:n})=>n===l))throw new Error(`Unexpected event type: ${l}. Expected one of: ${h.map(n=>n.type).join(", ")}`);let x=i.get(l)??[];return await Promise.all(x.map(({eventDefinition:n,handler:d})=>I(n,d,u,{instanceId:c,identity:s}))),{instanceId:c,eventType:l,payload:u,identity:s}},async processRequest(o,t){let l=await o.text();return this.process(l,t)},async parseJWT(o){if(!e.decodeJWT)throw new Error("decodeJWT is not supported by the authentication strategy");let{decoded:t,valid:l}=await e.decodeJWT(o);if(!l)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 s=JSON.parse(t.data),c=s.eventType,u=s.instanceId,h=s.identity?JSON.parse(s.identity):void 0,x=JSON.parse(s.data);return{instanceId:u,eventType:c,payload:x,identity:h}},async parseRequest(o){let t=await o.text();return this.parseJWT(t)},async executeHandlers(o){let t=Array.from(i.keys()).map(s=>({type:s}));if(t.length>0&&!t.some(({type:s})=>s===o.eventType))throw new Error(`Unexpected event type: ${o.eventType}. Expected one of: ${t.map(s=>s.type).join(", ")}`);let l=i.get(o.eventType)??[];await Promise.all(l.map(({eventDefinition:s,handler:c})=>I(s,c,o.payload,{instanceId:o.instanceId,identity:o.identity})))},apps:{AppInstalled:E("AppInstalled")(),AppRemoved:E("AppRemoved")()}};return{initModule(o){return t=>{let l=i.get(o.type)??[];l.push({eventDefinition:o,handler:t}),i.set(o.type,l),r.emit("registered",o)}},client:a}}var D=e=>e.__type==="service-plugin-definition";function L(e){let i=new Map,r=g(),a={...r,getRegisteredServicePlugins:()=>i,async parseJWT(o){if(!e.decodeJWT)throw new Error("decodeJWT is not supported by the authentication strategy");let{decoded:t,valid:l}=await e.decodeJWT(o,!0);if(!l)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(o){let t=await this.parseJWT(o.body);return this.executeHandler(t,o.url)},async parseRequest(o){let t=await o.text();return this.parseJWT(t)},async processRequest(o){let t=o.url,l=await o.text();try{let s=await this.process({url:t,body:l});return Response.json(s)}catch(s){if(s.errorType==="SPI"&&s.applicationCode&&s.httpCode)return Response.json({applicationError:{code:s.applicationCode,data:s.data}},{status:s.httpCode});throw s}},async executeHandler(o,t){let l=o.metadata.appExtensionType.toLowerCase(),s=i.get(l)??[];if(s.length===0)throw new Error(`No service plugin implementations found for component type ${l}`);if(s.length>1)throw new Error(`Multiple service plugin implementations found for component type ${l}. This is currently not supported`);let{implementation:c,servicePluginDefinition:u}=s[0],h=u.methods.find(n=>t.endsWith(n.primaryHttpMappingPath));if(!h)throw new Error("Unexpect request: request url did not match any method: "+t);let x=c[h.name];if(!x)throw new Error(`Got request for service plugin method ${h.name} but no implementation was provided. Available methods: ${Object.keys(c).join(", ")}`);return h.transformations.toREST(await x(h.transformations.fromREST(o)))}};return{initModule(o){return t=>{let l=i.get(o.componentType.toLowerCase())??[];l.push({servicePluginDefinition:o,implementation:t}),i.set(o.componentType.toLowerCase(),l),r.emit("registered",o)}},client:a}}function He(e){let i=e.headers||{Authorization:""},r=e.auth||{getAuthHeaders:n=>Promise.resolve({headers:{}})},a=r.getAuthHeaders.bind(void 0,e.host);r.getAuthHeaders=a;let{client:o,initModule:t}=L(r),{client:l,initModule:s}=q(r),c=async(n,d)=>{let f=await a(),p=P(d);return fetch(n,{...d,headers:{...p,...i,...f?.headers,...d?.headers,...e.host?.essentials?.passThroughHeaders}})},u=(n,d)=>{if(k(n))return s(n);if(D(n))return t(n);if($(n)&&e.host)return R(n,e.host);if(typeof n=="function"){if("__type"in n&&n.__type===C)return n;let f=e.host?.apiBaseUrl??w;return j(v(()=>A(n))?M(n):n,d??{},c,(p,m)=>{let _=new URL(p,`https://${f}`);return _.host=f,_.protocol="https",c(_.toString(),m)},r.getActiveToken,{HTTPHost:f},e.host?.name)}else return S(n)?Object.fromEntries(Object.entries(n).map(([f,p])=>[f,u(p,n[H])])):n},h=n=>{for(let d in n)i[d]=n[d]};return{...e.modules?u(e.modules):{},auth:r,setHeaders:h,use:u,enableContext(n,d={elevated:!1}){n==="global"?globalThis.__wix_context__!=null?d.elevated?globalThis.__wix_context__.elevatedClient=this:globalThis.__wix_context__.client=this:d.elevated?globalThis.__wix_context__={elevatedClient:this}:globalThis.__wix_context__={client:this}:d.elevated?J.elevatedClient=this:J.client=this},fetch:(n,d)=>{let f=e.host?.apiBaseUrl??w,p=new URL(n,`https://${f}`);return p.host=f,p.protocol="https",c(p.toString(),d)},fetchWithAuth:async(n,d)=>{if(typeof n=="string"||n instanceof URL)return fetch(n,{...d,headers:{...d?.headers,...(await a()).headers}});for(let[f,p]of Object.entries((await a()).headers))n.headers.set(f,p);return fetch(n,d)},async graphql(n,d,f={apiVersion:"alpha"}){let p=e?.host?.apiBaseUrl??w,m=await c(`https://${p}/graphql/${f.apiVersion}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:n,variables:d})});if(m.status!==200)throw new T(`GraphQL request failed with status ${m.status}`,m);let{data:_,errors:O}=await m.json();return{data:_??{},errors:O}},webhooks:l,servicePlugins:o}}export{G as a,W as b,He as c};
2
+ //# sourceMappingURL=chunk-32RIHE6N.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/@wix/sdk-types/build/browser/index.mjs","../../../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/node_modules/@wix/sdk-runtime/build/context.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":["// 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","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 { 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: 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 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 { 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 { 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 const implMethodResult = await this.process({ url, body });\n return Response.json(implMethodResult);\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":"sDAAA,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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I,CAC7E,OAAQ,OACR,QAAS,CACL,eAAgB,kBACpB,EACA,KAAM,KAAK,UAAU,CAAE,MAAAK,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,SAAU5C,EACV,eAAgBH,CACpB,CACJ","names":["browser_exports","__export","EventDefinition","SERVICE_PLUGIN_ERROR_TYPE","ServicePluginDefinition","type","isDomainEvent","transformations","x","componentType","methods","init_browser","__esmMin","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","wixContext","runWithoutContext","fn","globalContext","moduleContext","wixContext","closureContext","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","componentType","implementations","impl","servicePluginDefinition","method","m","implMethod","implementation","createClient","config","_headers","authStrategy","_","boundGetAuthHeaders","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","k","contextType","opts","wixContext","urlOrRequest","requestInit","v","query","variables","res","FetchErrorResponse","data","errors"]}
1
+ {"version":3,"sources":["../../../node_modules/@wix/sdk-types/build/browser/index.mjs","../../../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/node_modules/@wix/sdk-runtime/build/context.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":["// 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","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 { 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: 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 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 { 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 { 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":"sDAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA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AGA,GAAa,QAChB,IAAI,MAAMzC,EAAoB,GAAG,OACrC,CACJ,CAAC,EAGD,OAAW,CAACoC,EAAGM,CAAC,IAAK,OAAO,SAAS,MAAM1C,EAAoB,GAAG,OAAO,EACrEwC,EAAa,QAAQ,IAAIJ,EAAGM,CAAC,EAEjC,OAAO,MAAMF,EAAcC,CAAW,CAE9C,EACA,MAAM,QAAQE,EAAOC,EAAWN,EAAO,CACnC,WAAY,OAChB,EAAG,CACC,IAAMjB,EAAazB,GAAQ,MAAM,YAAc0B,EACzCuB,EAAM,MAAMtC,EAAW,WAAWc,CAAU,YAAYiB,EAAK,UAAU,GAAI,CAC7E,OAAQ,OACR,QAAS,CACL,eAAgB,kBACpB,EACA,KAAM,KAAK,UAAU,CAAE,MAAAK,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,SAAU5C,EACV,eAAgBH,CACpB,CACJ","names":["browser_exports","__export","EventDefinition","SERVICE_PLUGIN_ERROR_TYPE","ServicePluginDefinition","type","isDomainEvent","transformations","x","componentType","methods","init_browser","__esmMin","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","wixContext","runWithoutContext","fn","globalContext","moduleContext","wixContext","closureContext","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","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","k","contextType","opts","wixContext","urlOrRequest","requestInit","v","query","variables","res","FetchErrorResponse","data","errors"]}
@@ -1,2 +1,2 @@
1
- import{a as V}from"./chunk-DGX4CFXG.js";import{c as D}from"./chunk-KEIVYRQX.js";import"./chunk-SBZEOPXX.js";function S(){return S=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},S.apply(null,arguments)}import ke,{useEffect as le,useState as z}from"react";function y(e){"@babel/helpers - typeof";return y=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},y(e)}function q(e,t){if(y(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(y(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function F(e){var t=q(e,"string");return y(t)=="symbol"?t:t+""}function N(e,t,r){return(t=F(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var v=class extends Error{constructor(t){let{message:r,code:n}=t;super(r),N(this,"code",void 0),this.message=r,this.code=n}};var K=()=>{let e=l=>{let{channel:c}=l;return function(){let f=c.showToast(...arguments);return{remove:()=>Promise.resolve(f).then(h=>h.remove())}}},t=l=>{let{channel:c}=l;return function(){let f=c.observeState(...arguments);return{disconnect:()=>Promise.resolve(f).then(h=>h.disconnect())}}};return{showToast:e,observeState:t,navigate:l=>{let{channel:c}=l;return function(){return c.navigate(...arguments)}},navigateBack:l=>{let{channel:c}=l;return()=>c.navigateBack()},openModal:l=>{let{channel:c}=l;return function(){let f=c.openModal(...arguments);return{modalClosed:Promise.resolve(f).then(g=>g.modalClosed)}}},closeModal:l=>{let{channel:c}=l;return f=>{if(f===void 0)return c.closeModal();let g=JSON.parse(JSON.stringify(f));return c.closeModal(g)}},getAccessToken:l=>{let{channel:c}=l;return()=>c.getAccessToken()},getPageUrl:l=>{let{channel:c}=l;return function(){return c.getPageUrl(...arguments)}},openMediaManager:l=>{let{channel:c}=l;return function(){return c.openMediaManager(...arguments)}},addSitePlugin:l=>{let{channel:c}=l;return(f,g)=>{let h="802c76e4-b381-4bb3-9152-96acabbf3194",j=g?.placement||{},H=c.openModal(h,{...j,pluginId:f,action:"populate"});return Promise.resolve(H).then(b=>b.modalClosed).then(b=>{if(b?.type===void 0)throw new v({message:"Aborted by user",code:3006});if(b?.type==="ERROR")throw new v(b.data.error)})}},onBeforeUnload:l=>{let{channel:c}=l;return function(){return c.onBeforeUnload(...arguments)}},setPageTitle:l=>{let{channel:c}=l;return f=>c.setPageTitle(f)},getLanguage:l=>{let c=null;return async()=>{var f;if(c)return c;let g=null;return c=await new Promise(h=>{g=t(l)((j,H)=>{h(H.language)})}),(f=g)==null||f.disconnect(),c}},requestFeedback:l=>{let{channel:c}=l;return function(){return c.requestFeedback(...arguments)}}}};var G=e=>{let{createHost:t}=e,r=K();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"),C=Symbol("Comlink.releaseProxy"),O=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)&&O 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:o,type:a,path:s}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(w),u;try{let d=s.slice(0,-1).reduce((p,x)=>p[x],e),m=s.reduce((p,x)=>p[x],e);switch(a){case 0:u=m;break;case 1:d[s.slice(-1)[0]]=w(n.data.value),u=!0;break;case 2:u=m.apply(d,i);break;case 3:{let p=new m(...i);u=M(p)}break;case 4:{let{port1:p,port2:x}=new MessageChannel;R(e,x),u=he(p,[p])}break;case 5:u=void 0;break}}catch(d){u={value:d,[O]:0}}Promise.resolve(u).catch(d=>({value:d,[O]:0})).then(d=>{let[m,p]=T(d);t.postMessage(Object.assign(Object.assign({},m),{id:o}),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 k(e){if(e)throw new Error("Proxy has been released and is not useable")}function U(e,t=[],r=function(){}){let n=!1,o=new Proxy(r,{get(a,s){if(k(n),s===C)return()=>P(e,{type:5,path:t.map(i=>i.toString())}).then(()=>{Z(e),n=!0});if(s==="then"){if(t.length===0)return{then:()=>o};let i=P(e,{type:0,path:t.map(u=>u.toString())}).then(w);return i.then.bind(i)}return U(e,[...t,s])},set(a,s,i){k(n);let[u,d]=T(i);return P(e,{type:1,path:[...t,s].map(m=>m.toString()),value:u},d).then(w)},apply(a,s,i){k(n);let u=t[t.length-1];if(u===de)return P(e,{type:4}).then(w);if(u==="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(w)},construct(a,s){k(n);let[i,u]=$(s);return P(e,{type:3,path:t.map(d=>d.toString()),argumentList:i},u).then(w)}});return o}function ge(e){return Array.prototype.concat.apply([],e)}function $(e){let t=e.map(T);return[t.map(r=>r[0]),ge(t.map(r=>r[1]))]}var ee=new WeakMap;function he(e,t){return ee.set(e,t),e}function M(e){return Object.assign(e,{[X]:!0})}function T(e){for(let[t,r]of Y)if(r.canHandle(e)){let[n,o]=r.serialize(e);return[{type:3,name:t,value:n},o]}return[{type:0,value:e},ee.get(e)||[]]}function w(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 o=be();e.addEventListener("message",function a(s){!s.data||!s.data.id||s.data.id!==o||(e.removeEventListener("message",a),n(s.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),r)})}function be(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var B="__proxyCallbackId__wixSDK__",L="__proxyPromiseId__wixSDK__",re=e=>we(e,t=>async function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let[a,s]=I(n),i=await t(M(a),s);return ne(i)});var ye=async e=>{let[t,r]=I(await e);return M({proxies:t,clonables:r})},ne=async e=>A(e?.proxies,await e?.clonables),I=e=>{let t=(o,a)=>{if(oe(a)){let s=te();return o.promises[s]=a,{[L]:s}}if(xe(a)){let s=te();return o.callbacks[s]=(i,u)=>{let d=A(i,u),m=a(...d);return ye(m)},{[B]:s}}return Array.isArray(a)?a.map(s=>t(o,s)):E(a)?se(a,s=>t(o,s)):a},r={promises:{},callbacks:{}},n=t(r,e);return[r,n]},A=(e,t)=>{if(Array.isArray(t))return t.map(r=>A(e,r));if(E(t)&&t.hasOwnProperty(L)){let r=t[L];return e.promises[r]}if(E(t)&&t.hasOwnProperty(B)){let r=t[B];return async function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let[s,i]=I(o),u=await e.callbacks[r](M(s),i);return ne(u)}}return E(t)?se(t,r=>A(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,E=e=>e&&typeof e=="object"&&!oe(e),xe=e=>typeof e=="function",se=(e,t)=>{let r=n=>{let[o,a]=n;return[o,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:o}=new MessageChannel;t({code:Pe,version:"1.0.0",port:o},r,[o]);let i=re(_(n));return{channel:i,close:()=>i[C]()}};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)},o=e.onBeforeUnload(n),a=()=>{r||window.removeEventListener("beforeunload",n),o.then(i=>{let{remove:u}=i;return u()})};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:o,close:a}=ae({postMessage:n,origin:r}),s=[a];if(e.autoHeightUpdate===void 0||e.autoHeightUpdate){let d=e.autoHeightElement||document.documentElement,m=J(o,d);s.push(()=>m())}let{onBeforeUnload:i,clearBeforeUnloadHandler:u}=ce(o);return s.push(u),{channel:{...o,showToast:o.showToast,navigate:o.navigate,navigateBack:o.navigateBack,updateHeight:o.updateHeight,observeState:o.observeState,closeModal:o.closeModal,openModal:o.openModal,getAccessToken:o.getAccessToken,getPageUrl:o.getPageUrl,setPageTitle:o.setPageTitle,openMediaManager:o.openMediaManager,onBeforeUnload:i,requestFeedback:o.requestFeedback},close:()=>s.forEach(d=>d()),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 W=G({createHost:ue});var Ee=e=>t=>{let{host:r,...n}=t,[o,a]=z(!1),{host:s,props:i}=Ae(r);return le(()=>{s&&(D({auth:W.auth(),host:s}).enableContext("module"),a(!0))},[s]),!s||!i||!o?null:ke.createElement(e,S({host:s},i,n))},Ae=e=>{let[t,r]=z(),[n,o]=z();return le(()=>{if(e)return;let a=W.host();r(a);let s=a.channel.observeState,i=s(d=>{o(d)}),u=async()=>{r(void 0),o(void 0),(await i).disconnect(),a.close()};return()=>{u()}},[e]),e?{host:e,props:{}}:{host:t,props:n}};export{Ee as withContextualWixClient};
1
+ import{a as V}from"./chunk-DGX4CFXG.js";import{c as D}from"./chunk-32RIHE6N.js";import"./chunk-SBZEOPXX.js";function S(){return S=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},S.apply(null,arguments)}import ke,{useEffect as le,useState as z}from"react";function y(e){"@babel/helpers - typeof";return y=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},y(e)}function q(e,t){if(y(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(y(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function F(e){var t=q(e,"string");return y(t)=="symbol"?t:t+""}function N(e,t,r){return(t=F(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var v=class extends Error{constructor(t){let{message:r,code:n}=t;super(r),N(this,"code",void 0),this.message=r,this.code=n}};var K=()=>{let e=l=>{let{channel:c}=l;return function(){let f=c.showToast(...arguments);return{remove:()=>Promise.resolve(f).then(h=>h.remove())}}},t=l=>{let{channel:c}=l;return function(){let f=c.observeState(...arguments);return{disconnect:()=>Promise.resolve(f).then(h=>h.disconnect())}}};return{showToast:e,observeState:t,navigate:l=>{let{channel:c}=l;return function(){return c.navigate(...arguments)}},navigateBack:l=>{let{channel:c}=l;return()=>c.navigateBack()},openModal:l=>{let{channel:c}=l;return function(){let f=c.openModal(...arguments);return{modalClosed:Promise.resolve(f).then(g=>g.modalClosed)}}},closeModal:l=>{let{channel:c}=l;return f=>{if(f===void 0)return c.closeModal();let g=JSON.parse(JSON.stringify(f));return c.closeModal(g)}},getAccessToken:l=>{let{channel:c}=l;return()=>c.getAccessToken()},getPageUrl:l=>{let{channel:c}=l;return function(){return c.getPageUrl(...arguments)}},openMediaManager:l=>{let{channel:c}=l;return function(){return c.openMediaManager(...arguments)}},addSitePlugin:l=>{let{channel:c}=l;return(f,g)=>{let h="802c76e4-b381-4bb3-9152-96acabbf3194",j=g?.placement||{},H=c.openModal(h,{...j,pluginId:f,action:"populate"});return Promise.resolve(H).then(b=>b.modalClosed).then(b=>{if(b?.type===void 0)throw new v({message:"Aborted by user",code:3006});if(b?.type==="ERROR")throw new v(b.data.error)})}},onBeforeUnload:l=>{let{channel:c}=l;return function(){return c.onBeforeUnload(...arguments)}},setPageTitle:l=>{let{channel:c}=l;return f=>c.setPageTitle(f)},getLanguage:l=>{let c=null;return async()=>{var f;if(c)return c;let g=null;return c=await new Promise(h=>{g=t(l)((j,H)=>{h(H.language)})}),(f=g)==null||f.disconnect(),c}},requestFeedback:l=>{let{channel:c}=l;return function(){return c.requestFeedback(...arguments)}}}};var G=e=>{let{createHost:t}=e,r=K();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"),C=Symbol("Comlink.releaseProxy"),O=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)&&O 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:o,type:a,path:s}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(w),u;try{let d=s.slice(0,-1).reduce((p,x)=>p[x],e),m=s.reduce((p,x)=>p[x],e);switch(a){case 0:u=m;break;case 1:d[s.slice(-1)[0]]=w(n.data.value),u=!0;break;case 2:u=m.apply(d,i);break;case 3:{let p=new m(...i);u=M(p)}break;case 4:{let{port1:p,port2:x}=new MessageChannel;R(e,x),u=he(p,[p])}break;case 5:u=void 0;break}}catch(d){u={value:d,[O]:0}}Promise.resolve(u).catch(d=>({value:d,[O]:0})).then(d=>{let[m,p]=T(d);t.postMessage(Object.assign(Object.assign({},m),{id:o}),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 k(e){if(e)throw new Error("Proxy has been released and is not useable")}function U(e,t=[],r=function(){}){let n=!1,o=new Proxy(r,{get(a,s){if(k(n),s===C)return()=>P(e,{type:5,path:t.map(i=>i.toString())}).then(()=>{Z(e),n=!0});if(s==="then"){if(t.length===0)return{then:()=>o};let i=P(e,{type:0,path:t.map(u=>u.toString())}).then(w);return i.then.bind(i)}return U(e,[...t,s])},set(a,s,i){k(n);let[u,d]=T(i);return P(e,{type:1,path:[...t,s].map(m=>m.toString()),value:u},d).then(w)},apply(a,s,i){k(n);let u=t[t.length-1];if(u===de)return P(e,{type:4}).then(w);if(u==="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(w)},construct(a,s){k(n);let[i,u]=$(s);return P(e,{type:3,path:t.map(d=>d.toString()),argumentList:i},u).then(w)}});return o}function ge(e){return Array.prototype.concat.apply([],e)}function $(e){let t=e.map(T);return[t.map(r=>r[0]),ge(t.map(r=>r[1]))]}var ee=new WeakMap;function he(e,t){return ee.set(e,t),e}function M(e){return Object.assign(e,{[X]:!0})}function T(e){for(let[t,r]of Y)if(r.canHandle(e)){let[n,o]=r.serialize(e);return[{type:3,name:t,value:n},o]}return[{type:0,value:e},ee.get(e)||[]]}function w(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 o=be();e.addEventListener("message",function a(s){!s.data||!s.data.id||s.data.id!==o||(e.removeEventListener("message",a),n(s.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),r)})}function be(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var B="__proxyCallbackId__wixSDK__",L="__proxyPromiseId__wixSDK__",re=e=>we(e,t=>async function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let[a,s]=I(n),i=await t(M(a),s);return ne(i)});var ye=async e=>{let[t,r]=I(await e);return M({proxies:t,clonables:r})},ne=async e=>A(e?.proxies,await e?.clonables),I=e=>{let t=(o,a)=>{if(oe(a)){let s=te();return o.promises[s]=a,{[L]:s}}if(xe(a)){let s=te();return o.callbacks[s]=(i,u)=>{let d=A(i,u),m=a(...d);return ye(m)},{[B]:s}}return Array.isArray(a)?a.map(s=>t(o,s)):E(a)?se(a,s=>t(o,s)):a},r={promises:{},callbacks:{}},n=t(r,e);return[r,n]},A=(e,t)=>{if(Array.isArray(t))return t.map(r=>A(e,r));if(E(t)&&t.hasOwnProperty(L)){let r=t[L];return e.promises[r]}if(E(t)&&t.hasOwnProperty(B)){let r=t[B];return async function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let[s,i]=I(o),u=await e.callbacks[r](M(s),i);return ne(u)}}return E(t)?se(t,r=>A(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,E=e=>e&&typeof e=="object"&&!oe(e),xe=e=>typeof e=="function",se=(e,t)=>{let r=n=>{let[o,a]=n;return[o,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:o}=new MessageChannel;t({code:Pe,version:"1.0.0",port:o},r,[o]);let i=re(_(n));return{channel:i,close:()=>i[C]()}};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)},o=e.onBeforeUnload(n),a=()=>{r||window.removeEventListener("beforeunload",n),o.then(i=>{let{remove:u}=i;return u()})};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:o,close:a}=ae({postMessage:n,origin:r}),s=[a];if(e.autoHeightUpdate===void 0||e.autoHeightUpdate){let d=e.autoHeightElement||document.documentElement,m=J(o,d);s.push(()=>m())}let{onBeforeUnload:i,clearBeforeUnloadHandler:u}=ce(o);return s.push(u),{channel:{...o,showToast:o.showToast,navigate:o.navigate,navigateBack:o.navigateBack,updateHeight:o.updateHeight,observeState:o.observeState,closeModal:o.closeModal,openModal:o.openModal,getAccessToken:o.getAccessToken,getPageUrl:o.getPageUrl,setPageTitle:o.setPageTitle,openMediaManager:o.openMediaManager,onBeforeUnload:i,requestFeedback:o.requestFeedback},close:()=>s.forEach(d=>d()),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 W=G({createHost:ue});var Ee=e=>t=>{let{host:r,...n}=t,[o,a]=z(!1),{host:s,props:i}=Ae(r);return le(()=>{s&&(D({auth:W.auth(),host:s}).enableContext("module"),a(!0))},[s]),!s||!i||!o?null:ke.createElement(e,S({host:s},i,n))},Ae=e=>{let[t,r]=z(),[n,o]=z();return le(()=>{if(e)return;let a=W.host();r(a);let s=a.channel.observeState,i=s(d=>{o(d)}),u=async()=>{r(void 0),o(void 0),(await i).disconnect(),a.close()};return()=>{u()}},[e]),e?{host:e,props:{}}:{host:t,props:n}};export{Ee as withContextualWixClient};
2
2
  //# sourceMappingURL=dashboard.js.map
@@ -1,8 +1,8 @@
1
- import{a as _e}from"./chunk-DGX4CFXG.js";import{a as Xe,b as Be,c as Te}from"./chunk-KEIVYRQX.js";import{b as be,d as Pe,e as ze,f as a,g as p,h as u,i as I,j as q}from"./chunk-SBZEOPXX.js";var Re=be(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.EventType=void 0;var Ce;(function(n){n.removeAppCompleted="removeAppCompleted",n.componentSelectionChanged="componentSelectionChanged",n.appInstalled="appInstalled",n.appUpdateCompleted="appUpdateCompleted"})(Ce||(ct.EventType=Ce={}))});var kt=be(A=>{"use strict";var Je=A&&A.__createBinding||(Object.create?function(n,t,e,i){i===void 0&&(i=e);var s=Object.getOwnPropertyDescriptor(t,e);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,i,s)}:function(n,t,e,i){i===void 0&&(i=e),n[i]=t[e]}),Ge=A&&A.__setModuleDefault||(Object.create?function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}:function(n,t){n.default=t}),He=A&&A.__importStar||function(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&Je(t,n,e);return Ge(t,n),t};Object.defineProperty(A,"__esModule",{value:!0});A.EventType=A.WixSDKTypes=void 0;var qe=He((Be(),ze(Xe)));A.WixSDKTypes=qe;var Ve=Re();Object.defineProperty(A,"EventType",{enumerable:!0,get:function(){return Ve.EventType}})});var y=class n extends Error{constructor(e,i,s){let r=e?` ${e}`:"",o=`[${s}]#${i}`;super(`${o}.${r}`);a(this,"state",{});a(this,"displayName");a(this,"prefix");a(this,"errorMessage");a(this,"parent");a(this,"messages",[]);a(this,"code");this.displayName=o,this.errorMessage=e,this.prefix=s,this.code=i,this.name=o,Object.defineProperty(this,"message",{get:()=>this.getDisplayMessage()}),Error.captureStackTrace&&Error.captureStackTrace(this,n)}get parentError(){let e=this.parent;if(!e)return null;if(this.parent instanceof n)return this.parent;let i=e.name??"[Unknown Error]";return{getBreadcrumbs(){return[i]},getMessage(){return[i,e.message??"unknown error message"].join(`
1
+ import{a as be}from"./chunk-DGX4CFXG.js";import{a as Be,b as Je,c as we}from"./chunk-32RIHE6N.js";import{b as ve,d as Pe,e as Xe,f as a,g as c,h as u,i as I,j as H}from"./chunk-SBZEOPXX.js";var _e=ve(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.EventType=void 0;var Te;(function(n){n.removeAppCompleted="removeAppCompleted",n.componentSelectionChanged="componentSelectionChanged",n.appInstalled="appInstalled",n.appUpdateCompleted="appUpdateCompleted"})(Te||(at.EventType=Te={}))});var jt=ve(A=>{"use strict";var Ge=A&&A.__createBinding||(Object.create?function(n,t,e,i){i===void 0&&(i=e);var r=Object.getOwnPropertyDescriptor(t,e);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,i,r)}:function(n,t,e,i){i===void 0&&(i=e),n[i]=t[e]}),He=A&&A.__setModuleDefault||(Object.create?function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}:function(n,t){n.default=t}),Ve=A&&A.__importStar||function(){var n=function(t){return n=Object.getOwnPropertyNames||function(e){var i=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[i.length]=r);return i},n(t)};return function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var i=n(t),r=0;r<i.length;r++)i[r]!=="default"&&Ge(e,t,i[r]);return He(e,t),e}}();Object.defineProperty(A,"__esModule",{value:!0});A.EventType=A.WixSDKTypes=void 0;var qe=Ve((Je(),Xe(Be)));A.WixSDKTypes=qe;var Qe=_e();Object.defineProperty(A,"EventType",{enumerable:!0,get:function(){return Qe.EventType}})});var y=class n extends Error{constructor(e,i,r){let s=e?` ${e}`:"",o=`[${r}]#${i}`;super(`${o}.${s}`);a(this,"state",{});a(this,"displayName");a(this,"prefix");a(this,"errorMessage");a(this,"parent");a(this,"messages",[]);a(this,"code");this.displayName=o,this.errorMessage=e,this.prefix=r,this.code=i,this.name=o,Object.defineProperty(this,"message",{get:()=>this.getDisplayMessage()}),Error.captureStackTrace&&Error.captureStackTrace(this,n)}get parentError(){let e=this.parent;if(!e)return null;if(this.parent instanceof n)return this.parent;let i=e.name??"[Unknown Error]";return{getBreadcrumbs(){return[i]},getMessage(){return[i,e.message??"unknown error message"].join(`
2
2
  `)}}}getDisplayMessage(){return[(this.parentError?this.getBreadcrumbs():[]).join(" -> "),this.getMessage()].filter(i=>i.trim().length).join(`
3
- `)}getMessage(){let e=Object.entries(this.state).reduce((c,[l,h])=>(h&&c.push(` \u2013 ${l}: ${h}`),c),[]).join(`
4
- `),i=this.messages.reduce((c,l)=>(c.push(` - ${l.join(" ")}`),c),[]).join(`
5
- `),s=this.parentError,r=s?["",s.getMessage(),""].join(`
6
- `):"",o=this.errorMessage?`${this.displayName}: ${this.errorMessage}`:this.displayName;return[r,o,e,i].filter(c=>c.trim().length).join(`
7
- `)}getBreadcrumbs(){let e=this.parentError;return e?[...e.getBreadcrumbs(),this.displayName]:[this.displayName]}withParentError(e){return this.parent=e,this}withMessage(...e){return this.messages.push(e),this}};function E(n){return function t(e,i=""){let s=new n(i,e);return Error.captureStackTrace&&Error.captureStackTrace(s,t),s}}var jt=class extends y{constructor(e,i){super(e,i,"Editor Platform Internal Error");a(this,"state",{})}withHost(e){return this.state={...this.state,host:e},this}},Dn=E(jt);var V=Pe(kt(),1);var O=class O{constructor(){a(this,"uid",0);a(this,"callbacks",new Map);a(this,"inTransaction",!1);a(this,"isSilent",!1);a(this,"queue",[])}silent(t=!0){this.isSilent=t}startTransaction(){this.inTransaction=!0}commit(){this.inTransaction=!1;let t=this.queue;this.queue=[],this.isSilent||t.forEach(e=>{this.notify(e)})}notify(t){this.isSilent||(this.inTransaction?this.queue.push(t):this.callbacks.forEach(e=>{e(t)}))}subscribe(t){let e=this.uid++;return this.callbacks.set(e,t),()=>{this.callbacks.delete(e)}}notifyWithStep(t,e){this.notify({...t,meta:{...t.meta,step:e}})}async withEvent(t,e){let i=e();if(i&&i.hasOwnProperty("then"))try{return this.notifyWithStep(t,O.EventSteps.Start),i=await i,this.notifyWithStep(t,O.EventSteps.End),i}catch(s){throw this.notifyWithStep({...t,meta:{...t.meta,error:s}},O.EventSteps.Error),s}else return this.notify(t),i}};a(O,"biEvents",{PLATFORM_WORKER_SPAWN:123,PLATFORM_APP_RUNNER_INIT_APP_API:124,PLATFORM_APP_RUNNER_RUN_APP:125,PLATFORM_APP_RUNNER_REMOVE_APP:126,PLATFORM_WORKER_APP_BUNDLE_LOAD:127,PLATFORM_WORKER_APP_BUNDLE_EXECUTE:128,PLATFORM_IFRAME_INIT:129,PLATFORM_APP_API_INIT:130,PLATFORM_APP_API_GET:131}),a(O,"EventSteps",{Start:"start",End:"end",Error:"error"});var Lt=O,U=(n=>(n.WorkerSpawn="WorkerSpawn",n.HostEvent="HostEvent",n.ApplicationsSpecsReceived="ApplicationsSpecsReceived",n.InitApplicationApi="InitApplicationApi",n.RunApplication="RunApplication",n.getApplicationApi="getApplicationApi",n.IframeInit="IframeInit",n))(U||{}),Q=(n=>(n.EditorReady="EditorReady",n))(Q||{});var d=(n=>(n.ApplicationInit="ApplicationInit",n.ApplicationExecute="ApplicationExecute",n.ApplicationRemoved="ApplicationRemoved",n.ApplicationLoad="ApplicationLoad",n.ApplicationApiInit="ApplicationApiInit",n.CustomEvent="CustomEvent",n.HostEvent="HostEvent",n.EditorReady="EditorReady",n))(d||{}),Ft=class{createApplicationRemovedEvent(t){return{type:"ApplicationRemoved",payload:{appDefinitionId:t},meta:{bi:{evid:g.biEvents.PLATFORM_WORKER_SPAWN,appDefId:t}}}}createApplicationLoadEvent(t,e){return{type:"ApplicationLoad",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:g.biEvents.PLATFORM_WORKER_APP_BUNDLE_LOAD,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationExecuteEvent(t,e){return{type:"ApplicationExecute",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:g.biEvents.PLATFORM_WORKER_APP_BUNDLE_EXECUTE,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationApiInitEvent(t,e){return{type:"ApplicationApiInit",payload:{appDefinitionId:t},meta:{bi:{evid:g.biEvents.PLATFORM_APP_API_INIT,appDefId:t,scope:e}}}}},g=class extends Lt{constructor(){super(...arguments);a(this,"factories",new Ft)}},pt=class pt{constructor(t){this.events=t}mapToPlatformHostEvent(t){if(typeof t=="string")try{t=JSON.parse(t)}catch{}return{type:U.HostEvent,payload:{type:t.args.eventType,...t.args.eventPayload},meta:{appDefinitionId:t.appDefinitionId??null,intent:t.intent}}}notify(t){let e=this.mapToPlatformHostEvent(t);pt.allowedEvents.includes(e.payload.type)&&this.events.notify(e)}};a(pt,"allowedEvents",[V.EventType.componentSelectionChanged,V.EventType.appInstalled,V.EventType.appUpdateCompleted,V.EventType.removeAppCompleted]);var xe=pt;var tt=n=>`"editor-platform-transport": ${n}`,lt=n=>tt(`[Internal Error] ${n}`),Ne="\u0192",De="\u2202",Se="_get_",je="_set_",ut="+",Oe="-",Gt="\xB7",Ht="\xD7",qt="\xB0",ke=n=>n[0]===Ht?"":n,Me=n=>n===null||typeof n>"u"||typeof n=="symbol"||typeof n=="number"||typeof n=="boolean"||typeof n=="function"||typeof n=="string",Qe=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof Set)&&!(n instanceof Map),Ze=n=>W(n.split(Gt)),W=n=>n.map(ke).filter(Boolean).join(".");function Et(n,t){return{marker:n,...t}}var tn=Et("A",{shouldUse:n=>Array.isArray(n),serialize:(n,t)=>{n.length?n.forEach((e,i)=>{t(`${i}`,e)}):t("",qt)},deserialize:{create:()=>[],has:(n,t)=>!(typeof n[t]>"u"),append:(n,t,e)=>{n.push(e)}}}),en=Et("M",{shouldUse:n=>n instanceof Map,serialize:(n,t)=>{n.forEach((e,i)=>{t(i,e)})},deserialize:{create:()=>new Map,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.set(t,e)}}}),nn=Et("S",{shouldUse:n=>n instanceof Set,serialize:(n,t)=>{let e=0;n.forEach(i=>{t(`${e++}`,i)})},deserialize:{create:()=>new Set,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.add(e)}}}),Wt=Et("O",{shouldUse:n=>typeof n=="object",serialize:(n,t)=>{let e=i=>{let r=Reflect.ownKeys(i).filter(c=>c!=="constructor").filter(c=>typeof c!="symbol");r.length?r.filter(c=>c!=="constructor").filter(c=>typeof c!="symbol").forEach(c=>{let l=Reflect.get(n,c);t(c,l)}):t("",qt);let o=Reflect.getPrototypeOf(i);!o||o?.hasOwnProperty("__proto__")||e(o)};e(n)},deserialize:{create:()=>({}),has:(n,t)=>!!n[t],append:(n,t,e)=>{n[t]=e}}}),Le=[tn,nn,en];function sn(n,t){let e=n;for(;e;){let i=Object.getOwnPropertyDescriptor(e,t);if(i)return i;e=Reflect.getPrototypeOf(e)}return null}function rn(n,t){let e=new WeakMap,i=r=>{let o=r.slice(1).map(ke).filter(Boolean);return o.slice(1).reduce((c,l)=>({context:c.context[c.pointer],pointer:l}),{context:n,pointer:o[0]})},s=(r,o=[])=>{if(e.has(r)&&e.get(r)?.some(h=>o.join(".").startsWith(h))){t(o,{...i(o),value:"[Circular]"});return}if(r&&!Me(r)&&(e.has(r)&&e.set(r,[]),e.set(r,[...e.get(r)??[],o.join(".")])),Me(r)){t(o,{...i(o),value:r});return}let c=Le.find(l=>l.shouldUse(r))??Wt;if(c){c.serialize(r,(l,h)=>{s(h,[...o,`${Ht}${c.marker}`,l])});return}};return s(n)}var on=(n,t)=>{if(!Qe(n))throw new Error(tt("only objects are serializable at the root level"));let e={data:[]},i=(r,o)=>{e.data.push([r,o])},s=(r,o)=>{t(Ze(r),(...c)=>o.context[o.pointer](...c)),i(r,Ne)};return rn(n,(r,{value:o,context:c,pointer:l})=>{let h=r.slice(1).join(Gt),f=sn(c,l);if(f?.get||f?.set){f?.get&&t(W([...r,Se]),()=>c[l]),f?.set&&t(W([...r,je]),H=>{c[l]=H});let x=[f?.get?ut:Oe,f?.set?ut:Oe];i(h,`${De}${x.join("")}`)}else typeof o=="function"?s(h,{context:c,pointer:l}):i(h,o)}),e},an=(n,t)=>typeof n!="object"||n===null?n:n.data.reduce((e,[i,s])=>{let r=e,o=i.split(Gt),c=Wt,l=null;for(let h=0;h<o.length;h++){let f=o[h];if(f[0]===Ht){let x=c.deserialize.has(r,l);if(c=[Wt,...Le].find(H=>H.marker===f[1]),!c)throw new Error(tt(`unknown marker "${f[1]}"`));x||(r[l]=c.deserialize.create()),r=r[l]}else l=f}if(s?.toString()===qt)return e;if(s?.toString()===Ne)c.deserialize.append(r,l,t(W(o)));else if(s?.toString()[0]===De){let h=s?.toString()[1]===ut,f=s?.toString()[2]===ut,x={};if(h){let H=t(W([...o,Se]));x.get=()=>H()}f&&(x.set=t(W([...o,je]))),Object.defineProperty(r,l,x)}else c.deserialize.append(r,l,s);return e},{[Symbol("transferred object")]:`${(JSON.stringify(n.data).length/1024).toFixed(2)}Kb`}),Z=(n=>(n.ExposeAPI="ExposeAPI",n.Call="Call",n.Response="Response",n.Cleanup="Cleanup",n))(Z||{}),T=class n{constructor(t,e){a(this,"correlationId",`M-${performance.now()}`);a(this,"parentCorrelationId");this.type=t,this.payload=e}withParentCorrelationId(t){return this.parentCorrelationId=t,this}serialize(t){return JSON.stringify({parentCorrelationId:this.parentCorrelationId,correlationId:this.correlationId,type:this.type,payload:on(this.payload,(e,i)=>{t(this.correlationId,e,i)})})}static fromEvent(t,e){let i=JSON.parse(t);return new n(i.type,an(i.payload,s=>e(i.correlationId,s))).withParentCorrelationId(i.correlationId)}},Kt=class extends T{constructor(t){super("Cleanup",t)}},$t=class extends T{constructor(t){super("Response",t)}},ht=class extends T{constructor(t){super("Response",t)}},Yt=class extends T{constructor(t){super("Call",t)}},Ut=(n,t)=>`${n}_${t}`,yt,At,K,w,zt=class{constructor(t){u(this,yt,new FinalizationRegistry(t=>{this.postMessage(new Kt(t))}));u(this,At,{[Z.Cleanup]:t=>{let e=t.payload.functionMarkerKey,i=t.payload.callId;delete p(this,K)[e],i&&delete p(this,w)[i]},[Z.Response]:async t=>{let e=t.payload.callId,i=t.payload.errorMessage;if(i)if(t.payload.errorStack){let r=new Error(i);r.stack=t.payload.errorStack,p(this,w)[e]?.reject(r)}else p(this,w)[e]?.reject(i);else{let s=t.payload.response;p(this,w)[e]?.resolve(s)}delete p(this,w)[e]},[Z.Call]:async t=>{let e=t.payload.functionMarkerKey,i=p(this,K)[e];if(!i){this.postMessage(new ht({callId:t.payload.callId,errorMessage:tt("function is not available")}));return}try{let s=await i.value(...t.payload.props??[]);this.postMessage(new $t({callId:t.payload.callId,response:s}))}catch(s){this.postMessage(new ht({callId:t.payload.callId,errorMessage:s.message,errorStack:s.stack}))}}});u(this,K,{});u(this,w,{});a(this,"queue",[]);a(this,"isConnected",!1);this.handshake=t}async run(t){return this.handshake.run(t)}registerMessageListener(){if(!this.port)throw new Error(lt("it is not possible to listen on port events because port is not defined"));this.port.onmessage=t=>{this.onMessage(t)}}onMessage(t){let e=T.fromEvent(t.data,(i,s)=>{let r=this.replaceTransferredFunction(i,s);return p(this,yt).register(r,{functionMarkerKey:Ut(i,s)}),r});p(this,At)[e.type]?.(e),this.messageEvents[e.type]?.(e)}postMessage(t){if(!this.port)throw new Error(lt("it is not possible to post message on port because port is not defined"));this.port.postMessage(t.serialize(this.registerTransferredFunction.bind(this)))}registerTransferredFunction(t,e,i){let s=Ut(t,e);p(this,K)[s]={path:e,value:i}}replaceTransferredFunction(t,e){return(...i)=>{let s=`CALL-${crypto.randomUUID()}`;return this.postMessage(new Yt({callId:s,functionMarkerKey:Ut(t,e),props:i})),new Promise((r,o)=>{p(this,w)[s]={resolve:r,reject:o}})}}flush(){this.port&&(this.queue.forEach(t=>{this.postMessage(t)}),this.queue=[])}};yt=new WeakMap,At=new WeakMap,K=new WeakMap,w=new WeakMap;var dt=class extends zt{constructor(e){super(e);a(this,"port");a(this,"messageEvents",{});this.init()}async init(){let e=await this.run();e?(this.port=e,this.registerMessageListener(),this.flush()):console.error(lt("consumer did not receive message port from the host"))}expose(e){if(!e.type)throw new Error(tt('wrong exposed API instance, "type" property is required'));this.queue.push(new T(Z.ExposeAPI,e)),this.flush()}};var Xt=class{constructor(t){this.communicationAPI=t}},M,v,Jt,b,Fe,Ue,Bt,P=class P extends Xt{constructor(){super(...arguments);u(this,b);u(this,M);u(this,v,!1);u(this,Jt,null)}run(e){return new Promise(i=>{e?q(this,b,Fe).call(this,e,()=>i(void 0)):q(this,b,Ue).call(this,i)})}};M=new WeakMap,v=new WeakMap,Jt=new WeakMap,b=new WeakSet,Fe=function(e,i){if(p(this,v))return;if(!e)throw new Error(lt("port should exists on host handshake"));let s=`Host-${performance.now()}`;this.communicationAPI.postMessage(JSON.stringify({memberId:s,type:"Greeting"}),[]),q(this,b,Bt).call(this,s,r=>{var o;if(!p(this,v))switch(r.type){case"Greeting":{this.communicationAPI.postMessage(JSON.stringify({memberId:s,type:"Greeting"}),[]);break}case"RequestPort":{I(this,v,!0),this.communicationAPI.postMessage(JSON.stringify({memberId:s,targetMemberId:r.memberId,type:"Port"}),[e]),(o=p(this,M))==null||o.call(this),i();break}}})},Ue=function(e){if(p(this,v))return;let i=`Consumer-${performance.now()}`;this.communicationAPI.postMessage(JSON.stringify({memberId:i,type:"Greeting"}),[]),q(this,b,Bt).call(this,i,(s,r)=>{var o;if(!p(this,v))switch(s.type){case"Greeting":{this.communicationAPI.postMessage(JSON.stringify({memberId:i,type:"RequestPort"}),[]);break}case"Port":{if(s.targetMemberId!==i)return;I(this,v,!0),(o=p(this,M))==null||o.call(this),e(r);break}}})},Bt=function(e,i){var s;(s=p(this,M))==null||s.call(this),I(this,M,this.communicationAPI.onMessage(r=>{try{let o=typeof r.data=="string"?JSON.parse(r.data):{};if(!o.memberId||o.memberId===e)return;i(o,r.ports[0])}catch(o){console.error(o)}}))},a(P,"iframe",{host:e=>new P({postMessage:(i,s)=>{let r=e.contentWindow;r&&r.postMessage(i,"*",s)},onMessage:i=>{let s=r=>{r.origin!==new URL(e.src).origin||e.contentWindow!==r.source||i(r)};return globalThis.addEventListener("message",s),()=>globalThis.removeEventListener("message",s)}}),consumer:()=>new P({postMessage:e=>{globalThis.parent.postMessage(e,"*")},onMessage:e=>(globalThis.addEventListener("message",e),()=>{globalThis.removeEventListener("message",e)})})}),a(P,"worker",{host:e=>new P({postMessage:(i,s)=>{e.postMessage(i,s)},onMessage:i=>(e.addEventListener("message",i),()=>e.removeEventListener("message",i))}),consumer:()=>new P({postMessage:e=>{globalThis.postMessage(e)},onMessage:e=>(globalThis.addEventListener("message",e),()=>{globalThis.removeEventListener("message",e)})})});var ft=P,mt=class extends dt{constructor(){super(ft.iframe.consumer())}};var It=class extends dt{constructor(){super(ft.worker.consumer())}};var Zt=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case Q.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case U.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},te=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(te||{}),ee=class{constructor(t){this.env=t,this.create()}},N=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(N||{}),ne=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},$=E(ne);async function cn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(s=>t.components.getComponent(s)));return{type:n.type,components:i};default:return n}}var ie=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let s=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,r=()=>cn(i.payload,this.privateAPI);t==="*"?e(await r()):i.type===d.CustomEvent?t===i.payload?.type&&!s&&e(await r()):i.type===d.HostEvent&&t===i.payload?.type&&s&&e(await r())})}},pn=200,ln=50,gt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,s,r=0,o=()=>{i||(s=setTimeout(()=>{if(r++,r<ln){r%10===0&&console.log($(N.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${r}`).message),o();return}if(!i){let l=$(N.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},pn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(s),t()})})}},Vt="__ENVIRONMENT_CONTEXT_KEY",wt=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(wt||{}),bt=class bt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[Vt])throw $(N.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[Vt]=new bt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[Vt]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(bt,"status",new gt("environment"));var Y=bt,Qt="__APPLICATION_CONTEXT_KEY",Pt=class Pt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new ie(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await Y.getInstance()).getEnvironment()!==wt.Frame)throw $(N.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[Qt])throw $(N.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[Qt]=new Pt(t,await Y.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await Y.getInstance()).getEnvironment()===wt.Frame?(await this.status.waitInjected(),globalThis[Qt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw $(N.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(Pt,"status",new gt("application"));var se=Pt,un={classic:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-default.global.css",studio:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-studio.global.css"},et,nt,Tt,it,vt=class extends ee{constructor(){super(te.Frame);a(this,"type",te.Frame);u(this,et,new g);u(this,nt,new Zt(p(this,et)));u(this,Tt);u(this,it)}create(){if(typeof globalThis?.document?.head?.prepend=="function"){let i=new URL(globalThis.location.href).searchParams.get("editorType")==="CLASSIC"?"classic":"studio",s=un[i],r=s&&!!document.querySelectorAll(`link[type="text/css"][href="${s}"]`)?.length;if(s&&!r){let o=document.createElement("link");o.setAttribute("rel","stylesheet"),o.setAttribute("type","text/css"),o.setAttribute("href",s),globalThis.document.head.prepend(o)}}}async initEnvironment(e){let{applicationPrivateAPI:i,privateAPI:s,appDefinitionId:r}=e;I(this,it,i),I(this,Tt,s),await Y.inject({environment:wt.Frame,privateApi:s,events:p(this,et),applicationAPIs:{[r]:p(this,it)}}),await se.inject({appDefinitionId:r,appDefinitionName:""})}notify(e){p(this,nt).notify(e)}subscribe(e){p(this,nt).subscribe(e)}};et=new WeakMap,nt=new WeakMap,Tt=new WeakMap,it=new WeakMap;var We=Pe(kt());var oe=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case Q.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case U.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},k=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(k||{}),ae=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},z=E(ae);async function hn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(s=>t.components.getComponent(s)));return{type:n.type,components:i};default:return n}}var ce=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let s=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,r=()=>hn(i.payload,this.privateAPI);t==="*"?e(await r()):i.type===d.CustomEvent?t===i.payload?.type&&!s&&e(await r()):i.type===d.HostEvent&&t===i.payload?.type&&s&&e(await r())})}},dn=200,fn=50,Ct=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,s,r=0,o=()=>{i||(s=setTimeout(()=>{if(r++,r<fn){r%10===0&&console.log(z(k.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${r}`).message),o();return}if(!i){let l=z(k.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},dn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(s),t()})})}},re="__ENVIRONMENT_CONTEXT_KEY",Rt=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Rt||{}),Ot=class Ot{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[re])throw z(k.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[re]=new Ot(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[re]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Ot,"status",new Ct("environment"));var L=Ot,_t="__APPLICATION_CONTEXT_KEY",Mt=class Mt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new ce(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await L.getInstance()).getEnvironment()!==Rt.Frame)throw z(k.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[_t])throw z(k.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[_t]=new Mt(t,await L.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await L.getInstance()).getEnvironment()===Rt.Frame?(await this.status.waitInjected(),globalThis[_t]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw z(k.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(Mt,"status",new Ct("application"));var pe=Mt,_=(n=>(n.ApplicationRuntimeError="ApplicationRuntimeError",n.ApplicationCreationError="ApplicationCreationError",n.ApplicationLoadError="ApplicationLoadError",n.ApplicationFetchError="ApplicationFetchError",n.ApplicationExecuteError="ApplicationExecuteError",n.ApplicationWasRemoved="ApplicationWasRemoved",n.UndefinedApiMethod="UndefinedApiMethod",n.ApplicationIsNotMutable="ApplicationIsNotMutable",n.FailedToGetPrivateAPI="FailedToGetPrivateAPI",n.ClientAuthError="ClientAuthError",n))(_||{}),le=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}withApiMethod(e){return this.state={...this.state,apiMethod:e},this}withApiType(e){return this.state={...this.state,apiType:e},this}},D=E(le),mn="__APPLICATION_REGISTRY_KEY";async function In(n,t,e){let i=new Function(_t,mn,e),s,r=o=>{if(s)throw D(_.ApplicationExecuteError,"Application registry called more than once").withAppDefinitionId(t.appDefinitionId);if(o.type!==t.type)throw D(_.ApplicationExecuteError,"Application has different type").withMessage("expected type",t.type).withMessage("received type",o.type);s=o};try{let o={...t};i.call(null,new pe(o,await L.getInstance()),r)}catch(o){throw D(_.ApplicationExecuteError,o.message).withAppDefinitionId(t.appDefinitionId).withParentError(o)}return new Promise((o,c)=>{let l=n.subscribe(h=>{let f=setTimeout(()=>{clearTimeout(f),l(),s||c(D(_.ApplicationExecuteError,"Application registry was not called, threw by timeout").withAppDefinitionId(t.appDefinitionId))},5e3);h.type===d.ApplicationInit&&h.meta.appDefinitionId===t.appDefinitionId&&(clearTimeout(f),l(),s||c(D(_.ApplicationExecuteError,"Application registry was not called").withAppDefinitionId(t.appDefinitionId)),o({instance:s}))})})}var S,st,m,ue=class{constructor(t,e){u(this,S,{});u(this,st);u(this,m);I(this,st,t),I(this,m,e),p(this,m).subscribe(i=>{switch(i.type){case d.HostEvent:{i.payload.type===We.EventType.removeAppCompleted&&p(this,m).withEvent(p(this,m).factories.createApplicationRemovedEvent(i.payload.appDefinitionId),()=>this.removeApplication(i.payload.appDefinitionId));break}}})}async runApplication(t){let e=await this.loadApplication(t),i=await this.executeApplication(t,e);return this.setApplication(t.appDefinitionId,i),i}setApplication(t,e){p(this,S)[t]=e,p(this,m).withEvent(p(this,m).factories.createApplicationApiInitEvent(t,e?.api?.private?"private":"public"),()=>{p(this,st).applicationManager.setApplication(e)})}getApplication(t){return p(this,S)[t]}getAppDefinitionIds(){return Object.keys(p(this,S))}removeApplication(t){delete p(this,S)[t]}async loadApplication(t){let e=t.url;return p(this,m).withEvent(p(this,m).factories.createApplicationLoadEvent(t,e),async()=>{try{return await this.loadApplicationBundle(e)}catch(i){throw D(_.ApplicationLoadError).withUrl(e).withAppDefinitionId(t.appDefinitionId).withParentError(i)}})}async loadApplicationBundle(t){let e=await fetch(t,{method:"GET"});if(!(e.status>=200&&e.status<=299))throw D(_.ApplicationFetchError).withUrl(t);return e.text()}async executeApplication(t,e){return p(this,m).withEvent(p(this,m).factories.createApplicationExecuteEvent(t,t.url),async()=>{let{instance:i}=await In(p(this,m),t,e);return i})}};S=new WeakMap,st=new WeakMap,m=new WeakMap;var he=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(he||{}),de=class{constructor(t){this.env=t,this.create()}},X,rt,ot,j,at,xt=class extends de{constructor(){super(he.Worker);a(this,"type",he.Worker);u(this,X,new g);u(this,rt,new oe(p(this,X)));u(this,ot,null);u(this,j);u(this,at,[])}create(){}async initEnvironment(e){let{buildPrivateAPI:i}=e;I(this,j,await i({type:"EDITOR_ADDON"})),await L.inject({environment:Rt.Worker,events:p(this,X),privateApi:p(this,j),applicationAPIs:{}}),I(this,ot,new ue(p(this,j),p(this,X))),p(this,at).forEach(s=>s(this))}async notify(e){await this.waitReady(),p(this,rt).notify(e)}subscribe(e){p(this,rt).subscribe(e)}async runApplication(e){await this.waitReady(),await p(this,ot).runApplication(e)}waitReady(){return new Promise(e=>{if(p(this,j))return e(this);p(this,at).push(e)})}};X=new WeakMap,rt=new WeakMap,ot=new WeakMap,j=new WeakMap,at=new WeakMap;var F=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(F||{}),ye=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},J=E(ye);async function yn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(s=>t.components.getComponent(s)));return{type:n.type,components:i};default:return n}}var Ae=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let s=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,r=()=>yn(i.payload,this.privateAPI);t==="*"?e(await r()):i.type===d.CustomEvent?t===i.payload?.type&&!s&&e(await r()):i.type===d.HostEvent&&t===i.payload?.type&&s&&e(await r())})}},An=200,En=50,Nt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,s,r=0,o=()=>{i||(s=setTimeout(()=>{if(r++,r<En){r%10===0&&console.log(J(F.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${r}`).message),o();return}if(!i){let l=J(F.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},An))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(s),t()})})}},fe="__ENVIRONMENT_CONTEXT_KEY",Ee=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Ee||{}),Dt=class Dt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[fe])throw J(F.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[fe]=new Dt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[fe]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Dt,"status",new Nt("environment"));var C=Dt,me="__APPLICATION_CONTEXT_KEY",St=class St{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new Ae(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await C.getInstance()).getEnvironment()!==Ee.Frame)throw J(F.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[me])throw J(F.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[me]=new St(t,await C.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await C.getInstance()).getEnvironment()===Ee.Frame?(await this.status.waitInjected(),globalThis[me]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw J(F.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(St,"status",new Nt("application"));var G=St,ge=class extends y{constructor(e,i){super(e,i,"Auth Strategy Error");a(this,"state",{})}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},Ie=E(ge);function gn(n,t){let e=Date.now(),i=n?new Date(n).getTime():null;return i&&i-e>t}var wn=30*60*1e3,vn=()=>{let n;return{getAuthHeaders:async()=>{let t=await G.getInstance(),e=t.getBindings(),i=t.getPrivateAPI();if(!e.appDefinitionId)throw Ie("EmptyAppDefinitionId");let s;try{s=await i.experiments.enabled("platform2.0_sdk_auth")}catch{s=!1}if(s){if((!n||gn(n.expires,wn))&&(n=await i.auth.getAccessToken(e.appDefinitionId,await i.info.getMetaSiteId())),!n?.token)throw Ie("EmptyAppAuthInstance").withAppDefinitionId(e.appDefinitionId);return{headers:{Authorization:n.token}}}else{let r=await i.info.getAppInstance(e.appDefinitionId);if(r===void 0)throw Ie("EmptyAppAuthInstance").withAppDefinitionId(e.appDefinitionId);return{headers:{Authorization:r}}}}}},Ke="_EP_TRANSPORT_INIT_KEY";globalThis[Ke]||(typeof importScripts=="function"?new It().expose(new xt):new mt().expose(new vt),globalThis[Ke]=!0);var R=class{constructor(t,e){this.namespace=t,this.shape=e}build(){return _e(Object.fromEntries(Object.entries(this.shape).map(([t,e])=>[t,i=>i?.environmentContext&&i?.applicationContext?async(...s)=>{let[r,o]=await Promise.all([i.environmentContext,i.applicationContext]);return e({environmentContext:r,applicationContext:o})(...s)}:async(...s)=>{let[r,o]=await Promise.all([C.getInstance(),G.getInstance()]);return e({environmentContext:r,applicationContext:o})(...s)}])))}},bn=new R("application",{getPrivateAPI({applicationContext:n}){return async()=>n.getPrivateApplicationAPI()},getPublicAPI({applicationContext:n}){return async t=>n.getPrivateAPI().applicationManager.getPublicApplicationAPI(t)},getAppInstance({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=n.getBindings();return t.info.getAppInstance(e.appDefinitionId)}}}),ni=bn.build(),Pn=new R("components",{getSelectedComponents({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=await t.components.getSelectedComponents();return Promise.all(e.map(i=>t.components.getComponent(i)))}}}),Tn=Pn.build(),_n=new R("events",{addEventListener({applicationContext:n}){return async(t,e)=>n.getEvents().addEventListener(t,e)}}),ii=_n.build(),Cn=new R("info",{getViewMode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getViewMode()},getLanguageCode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getLanguageCode()}}),si=Cn.build(),Ye=(n=>(n.UndefinedCompRef="UndefinedCompRef",n))(Ye||{}),we=class extends y{constructor(t,e){super(t,e,"Widget Error")}},Rn=E(we),$e=async()=>{let t=(await Tn.getSelectedComponents())[0]?.compRef;if(!t)throw Rn(Ye.UndefinedCompRef);return t},xn=new R("widget",{getProp({applicationContext:n}){return async t=>{let e=n.getPrivateAPI(),i=await $e();return e.customElement.getAttribute(i,t)}},setProp({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),s=await $e();await i.customElement.setAttribute(s,t,e)}}}),ri=xn.build(),B={transformFontInternalValue:n=>{if(n){let{theme:t,...e}=B.normalize(n);return{...e,editorKey:t}}else return{editorKey:"font_7",family:"helvetica-w01-roman",size:16,style:{}}},transformFontPublicValue:n=>n?{...B.normalize(n),theme:n.editorKey}:null,normalize:({theme:n,editorKey:t,preset:e,...i})=>({...i,theme:n??t})},On=new R("inputs",{selectColor({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),s=t?{color:t.color,theme:t?.theme}:null;return await i.inputs.openColorPicker({color:t?.theme?t.theme:t?.color},({color:r,theme:o})=>{let c={color:r,theme:o};s=c,e?.(c)}),s}},selectFont({applicationContext:n}){return async(t,e,i)=>{let s=n.getPrivateAPI(),r=B.transformFontPublicValue(t),o=(...c)=>{switch(r||(r=B.transformFontPublicValue(B.transformFontInternalValue(t))),c[0]){case"theme":Object.assign(r,{theme:c[1]});break;case"size":Object.assign(r,{size:c[1]});break;case"bold":Object.assign(r,{style:{...r.style,bold:c[1]}});break;case"italic":Object.assign(r,{style:{...r.style,italic:c[1]}});break;case"underline":Object.assign(r,{style:{...r.style,underline:c[1]}});break;case"family":Object.assign(r,{family:c[1]});break}};return await s.inputs.openFontPicker({...e,componentStyle:B.transformFontInternalValue(t)},(...c)=>{o(...c),i?.(r)}),r}}}),oi=On.build(),Mn=()=>{let n=new URLSearchParams(window.location.search);return{environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:C.getInstance(),applicationContext:G.getInstance(),essentials:n.has("essentials")?JSON.parse(n.get("essentials")):{}}},Nn=()=>({environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:C.getInstance(),applicationContext:G.getInstance()}),ve={host:()=>typeof importScripts=="function"?Nn():Mn(),auth:vn};var ui=()=>{let n=ve.host(),t=ve.auth();Te({auth:t,host:n}).enableContext("module")};export{ui as enableClient};
3
+ `)}getMessage(){let e=Object.entries(this.state).reduce((p,[l,h])=>(h&&p.push(` \u2013 ${l}: ${h}`),p),[]).join(`
4
+ `),i=this.messages.reduce((p,l)=>(p.push(` - ${l.join(" ")}`),p),[]).join(`
5
+ `),r=this.parentError,s=r?["",r.getMessage(),""].join(`
6
+ `):"",o=this.errorMessage?`${this.displayName}: ${this.errorMessage}`:this.displayName;return[s,o,e,i].filter(p=>p.trim().length).join(`
7
+ `)}getBreadcrumbs(){let e=this.parentError;return e?[...e.getBreadcrumbs(),this.displayName]:[this.displayName]}withParentError(e){return this.parent=e,this}withMessage(...e){return this.messages.push(e),this}};function g(n){return function t(e,i=""){let r=new n(i,e);return Error.captureStackTrace&&Error.captureStackTrace(r,t),r}}var Dt=class extends y{constructor(e,i){super(e,i,"Editor Platform Internal Error");a(this,"state",{})}withHost(e){return this.state={...this.state,host:e},this}},Wn=g(Dt);var V=Pe(jt(),1);var N=class N{constructor(){a(this,"uid",0);a(this,"callbacks",new Map);a(this,"inTransaction",!1);a(this,"isSilent",!1);a(this,"queue",[])}silent(t=!0){this.isSilent=t}startTransaction(){this.inTransaction=!0}commit(){this.inTransaction=!1;let t=this.queue;this.queue=[],this.isSilent||t.forEach(e=>{this.notify(e)})}notify(t){this.isSilent||(this.inTransaction?this.queue.push(t):this.callbacks.forEach(e=>{e(t)}))}subscribe(t){let e=this.uid++;return this.callbacks.set(e,t),()=>{this.callbacks.delete(e)}}notifyWithStep(t,e){this.notify({...t,meta:{...t.meta,step:e}})}async withEvent(t,e){let i=e();if(i&&i.hasOwnProperty("then"))try{return this.notifyWithStep(t,N.EventSteps.Start),i=await i,this.notifyWithStep(t,N.EventSteps.End),i}catch(r){throw this.notifyWithStep({...t,meta:{...t.meta,error:r}},N.EventSteps.Error),r}else return this.notify(t),i}};a(N,"biEvents",{PLATFORM_WORKER_SPAWN:123,PLATFORM_APP_RUNNER_INIT_APP_API:124,PLATFORM_APP_RUNNER_RUN_APP:125,PLATFORM_APP_RUNNER_REMOVE_APP:126,PLATFORM_WORKER_APP_BUNDLE_LOAD:127,PLATFORM_WORKER_APP_BUNDLE_EXECUTE:128,PLATFORM_IFRAME_INIT:129,PLATFORM_APP_API_INIT:130,PLATFORM_APP_API_GET:131}),a(N,"EventSteps",{Start:"start",End:"end",Error:"error"});var kt=N,U=(n=>(n.WorkerSpawn="WorkerSpawn",n.HostEvent="HostEvent",n.ApplicationsSpecsReceived="ApplicationsSpecsReceived",n.InitApplicationApi="InitApplicationApi",n.RunApplication="RunApplication",n.getApplicationApi="getApplicationApi",n.IframeInit="IframeInit",n))(U||{}),q=(n=>(n.EditorReady="EditorReady",n))(q||{});var d=(n=>(n.ApplicationInit="ApplicationInit",n.ApplicationExecute="ApplicationExecute",n.ApplicationRemoved="ApplicationRemoved",n.ApplicationLoad="ApplicationLoad",n.ApplicationApiInit="ApplicationApiInit",n.CustomEvent="CustomEvent",n.HostEvent="HostEvent",n.EditorReady="EditorReady",n))(d||{}),Lt=class{createApplicationRemovedEvent(t){return{type:"ApplicationRemoved",payload:{appDefinitionId:t},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_SPAWN,appDefId:t}}}}createApplicationLoadEvent(t,e){return{type:"ApplicationLoad",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_APP_BUNDLE_LOAD,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationExecuteEvent(t,e){return{type:"ApplicationExecute",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_APP_BUNDLE_EXECUTE,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationApiInitEvent(t,e){return{type:"ApplicationApiInit",payload:{appDefinitionId:t},meta:{bi:{evid:E.biEvents.PLATFORM_APP_API_INIT,appDefId:t,scope:e}}}}},E=class extends kt{constructor(){super(...arguments);a(this,"factories",new Lt)}},ct=class ct{constructor(t){this.events=t}mapToPlatformHostEvent(t){if(typeof t=="string")try{t=JSON.parse(t)}catch{}return{type:U.HostEvent,payload:{type:t.args.eventType,...t.args.eventPayload},meta:{appDefinitionId:t.appDefinitionId??null,intent:t.intent}}}notify(t){let e=this.mapToPlatformHostEvent(t);ct.allowedEvents.includes(e.payload.type)&&this.events.notify(e)}};a(ct,"allowedEvents",[V.EventType.componentSelectionChanged,V.EventType.appInstalled,V.EventType.appUpdateCompleted,V.EventType.removeAppCompleted]);var Ce=ct;var Z=n=>`"editor-platform-transport": ${n}`,pt=n=>Z(`[Internal Error] ${n}`),Ne="\u0192",Oe="\u2202",Me="_get_",Se="_set_",lt="+",xe="-",Jt="\xB7",Gt="\xD7",Ht="\xB0",De=n=>n[0]===Gt?"":n,Re=n=>n===null||typeof n>"u"||typeof n=="symbol"||typeof n=="number"||typeof n=="boolean"||typeof n=="function"||typeof n=="string",Ze=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof Set)&&!(n instanceof Map),tn=n=>W(n.split(Jt)),W=n=>n.map(De).filter(Boolean).join(".");function At(n,t){return{marker:n,...t}}var en=At("A",{shouldUse:n=>Array.isArray(n),serialize:(n,t)=>{n.length?n.forEach((e,i)=>{t(`${i}`,e)}):t("",Ht)},deserialize:{create:()=>[],has:(n,t)=>!(typeof n[t]>"u"),append:(n,t,e)=>{n.push(e)}}}),nn=At("M",{shouldUse:n=>n instanceof Map,serialize:(n,t)=>{n.forEach((e,i)=>{t(i,e)})},deserialize:{create:()=>new Map,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.set(t,e)}}}),rn=At("S",{shouldUse:n=>n instanceof Set,serialize:(n,t)=>{let e=0;n.forEach(i=>{t(`${e++}`,i)})},deserialize:{create:()=>new Set,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.add(e)}}}),Ut=At("O",{shouldUse:n=>typeof n=="object",serialize:(n,t)=>{let e=i=>{let s=Reflect.ownKeys(i).filter(p=>p!=="constructor").filter(p=>typeof p!="symbol");s.length?s.filter(p=>p!=="constructor").filter(p=>typeof p!="symbol").forEach(p=>{let l=Reflect.get(n,p);t(p,l)}):t("",Ht);let o=Reflect.getPrototypeOf(i);!o||o?.hasOwnProperty("__proto__")||e(o)};e(n)},deserialize:{create:()=>({}),has:(n,t)=>!!n[t],append:(n,t,e)=>{n[t]=e}}}),je=[en,rn,nn];function sn(n,t){let e=n;for(;e;){let i=Object.getOwnPropertyDescriptor(e,t);if(i)return i;e=Reflect.getPrototypeOf(e)}return null}function on(n,t){let e=new WeakMap,i=s=>{let o=s.slice(1).map(De).filter(Boolean);return o.slice(1).reduce((p,l)=>({context:p.context[p.pointer],pointer:l}),{context:n,pointer:o[0]})},r=(s,o=[])=>{if(e.has(s)&&e.get(s)?.some(h=>o.join(".").startsWith(h))){t(o,{...i(o),value:"[Circular]"});return}if(s&&!Re(s)&&(e.has(s)&&e.set(s,[]),e.set(s,[...e.get(s)??[],o.join(".")])),Re(s)){t(o,{...i(o),value:s});return}let p=je.find(l=>l.shouldUse(s))??Ut;if(p){p.serialize(s,(l,h)=>{r(h,[...o,`${Gt}${p.marker}`,l])});return}};return r(n)}var an=(n,t)=>{if(!Ze(n))throw new Error(Z("only objects are serializable at the root level"));let e={data:[]},i=(s,o)=>{e.data.push([s,o])},r=(s,o)=>{t(tn(s),(...p)=>o.context[o.pointer](...p)),i(s,Ne)};return on(n,(s,{value:o,context:p,pointer:l})=>{let h=s.slice(1).join(Jt),f=sn(p,l);if(f?.get||f?.set){f?.get&&t(W([...s,Me]),()=>p[l]),f?.set&&t(W([...s,Se]),G=>{p[l]=G});let R=[f?.get?lt:xe,f?.set?lt:xe];i(h,`${Oe}${R.join("")}`)}else typeof o=="function"?r(h,{context:p,pointer:l}):i(h,o)}),e},cn=(n,t)=>typeof n!="object"||n===null?n:n.data.reduce((e,[i,r])=>{let s=e,o=i.split(Jt),p=Ut,l=null;for(let h=0;h<o.length;h++){let f=o[h];if(f[0]===Gt){let R=p.deserialize.has(s,l);if(p=[Ut,...je].find(G=>G.marker===f[1]),!p)throw new Error(Z(`unknown marker "${f[1]}"`));R||(s[l]=p.deserialize.create()),s=s[l]}else l=f}if(r?.toString()===Ht)return e;if(r?.toString()===Ne)p.deserialize.append(s,l,t(W(o)));else if(r?.toString()[0]===Oe){let h=r?.toString()[1]===lt,f=r?.toString()[2]===lt,R={};if(h){let G=t(W([...o,Me]));R.get=()=>G()}f&&(R.set=t(W([...o,Se]))),Object.defineProperty(s,l,R)}else p.deserialize.append(s,l,r);return e},{[Symbol("transferred object")]:`${(JSON.stringify(n.data).length/1024).toFixed(2)}Kb`}),Q=(n=>(n.ExposeAPI="ExposeAPI",n.Call="Call",n.Response="Response",n.Cleanup="Cleanup",n))(Q||{}),_=class n{constructor(t,e){a(this,"correlationId",`M-${performance.now()}`);a(this,"parentCorrelationId");this.type=t,this.payload=e}withParentCorrelationId(t){return this.parentCorrelationId=t,this}serialize(t){return JSON.stringify({parentCorrelationId:this.parentCorrelationId,correlationId:this.correlationId,type:this.type,payload:an(this.payload,(e,i)=>{t(this.correlationId,e,i)})})}static fromEvent(t,e){let i=JSON.parse(t);return new n(i.type,cn(i.payload,r=>e(i.correlationId,r))).withParentCorrelationId(i.correlationId)}},Wt=class extends _{constructor(t){super("Cleanup",t)}},Kt=class extends _{constructor(t){super("Response",t)}},ut=class extends _{constructor(t){super("Response",t)}},$t=class extends _{constructor(t){super("Call",t)}},Ft=(n,t)=>`${n}_${t}`,It,yt,K,v,Yt=class{constructor(t){u(this,It,new FinalizationRegistry(t=>{this.postMessage(new Wt(t))}));u(this,yt,{[Q.Cleanup]:t=>{let e=t.payload.functionMarkerKey,i=t.payload.callId;delete c(this,K)[e],i&&delete c(this,v)[i]},[Q.Response]:async t=>{let e=t.payload.callId,i=t.payload.errorMessage;if(i)if(t.payload.errorStack){let s=new Error(i);s.stack=t.payload.errorStack,c(this,v)[e]?.reject(s)}else c(this,v)[e]?.reject(i);else{let r=t.payload.response;c(this,v)[e]?.resolve(r)}delete c(this,v)[e]},[Q.Call]:async t=>{let e=t.payload.functionMarkerKey,i=c(this,K)[e];if(!i){this.postMessage(new ut({callId:t.payload.callId,errorMessage:Z("function is not available")}));return}try{let r=await i.value(...t.payload.props??[]);this.postMessage(new Kt({callId:t.payload.callId,response:r}))}catch(r){this.postMessage(new ut({callId:t.payload.callId,errorMessage:r.message,errorStack:r.stack}))}}});u(this,K,{});u(this,v,{});a(this,"queue",[]);a(this,"isConnected",!1);this.handshake=t}async run(t){return this.handshake.run(t)}registerMessageListener(){if(!this.port)throw new Error(pt("it is not possible to listen on port events because port is not defined"));this.port.onmessage=t=>{this.onMessage(t)}}onMessage(t){let e=_.fromEvent(t.data,(i,r)=>{let s=this.replaceTransferredFunction(i,r);return c(this,It).register(s,{functionMarkerKey:Ft(i,r)}),s});c(this,yt)[e.type]?.(e),this.messageEvents[e.type]?.(e)}postMessage(t){if(!this.port)throw new Error(pt("it is not possible to post message on port because port is not defined"));this.port.postMessage(t.serialize(this.registerTransferredFunction.bind(this)))}registerTransferredFunction(t,e,i){let r=Ft(t,e);c(this,K)[r]={path:e,value:i}}replaceTransferredFunction(t,e){return(...i)=>{let r=`CALL-${crypto.randomUUID()}`;return this.postMessage(new $t({callId:r,functionMarkerKey:Ft(t,e),props:i})),new Promise((s,o)=>{c(this,v)[r]={resolve:s,reject:o}})}}flush(){this.port&&(this.queue.forEach(t=>{this.postMessage(t)}),this.queue=[])}};It=new WeakMap,yt=new WeakMap,K=new WeakMap,v=new WeakMap;var ht=class extends Yt{constructor(e){super(e);a(this,"port");a(this,"messageEvents",{});this.init()}async init(){let e=await this.run();e?(this.port=e,this.registerMessageListener(),this.flush()):console.error(pt("consumer did not receive message port from the host"))}expose(e){if(!e.type)throw new Error(Z('wrong exposed API instance, "type" property is required'));this.queue.push(new _(Q.ExposeAPI,e)),this.flush()}};var zt=class{constructor(t){this.communicationAPI=t}},O,P,Bt,w,ke,Le,Xt,T=class T extends zt{constructor(){super(...arguments);u(this,w);u(this,O);u(this,P,!1);u(this,Bt,null)}run(e){return new Promise(i=>{e?H(this,w,ke).call(this,e,()=>i(void 0)):H(this,w,Le).call(this,i)})}};O=new WeakMap,P=new WeakMap,Bt=new WeakMap,w=new WeakSet,ke=function(e,i){if(c(this,P))return;if(!e)throw new Error(pt("port should exists on host handshake"));let r=`Host-${performance.now()}`;this.communicationAPI.postMessage(JSON.stringify({memberId:r,type:"Greeting"}),[]),H(this,w,Xt).call(this,r,s=>{var o;if(!c(this,P))switch(s.type){case"Greeting":{this.communicationAPI.postMessage(JSON.stringify({memberId:r,type:"Greeting"}),[]);break}case"RequestPort":{I(this,P,!0),this.communicationAPI.postMessage(JSON.stringify({memberId:r,targetMemberId:s.memberId,type:"Port"}),[e]),(o=c(this,O))==null||o.call(this),i();break}}})},Le=function(e){if(c(this,P))return;let i=`Consumer-${performance.now()}`;this.communicationAPI.postMessage(JSON.stringify({memberId:i,type:"Greeting"}),[]),H(this,w,Xt).call(this,i,(r,s)=>{var o;if(!c(this,P))switch(r.type){case"Greeting":{this.communicationAPI.postMessage(JSON.stringify({memberId:i,type:"RequestPort"}),[]);break}case"Port":{if(r.targetMemberId!==i)return;I(this,P,!0),(o=c(this,O))==null||o.call(this),e(s);break}}})},Xt=function(e,i){var r;(r=c(this,O))==null||r.call(this),I(this,O,this.communicationAPI.onMessage(s=>{try{let o=typeof s.data=="string"?JSON.parse(s.data):{};if(!o.memberId||o.memberId===e)return;i(o,s.ports[0])}catch(o){console.error(o)}}))},a(T,"iframe",{host:e=>new T({postMessage:(i,r)=>{let s=e.contentWindow;s&&s.postMessage(i,"*",r)},onMessage:i=>{let r=s=>{s.origin!==new URL(e.src).origin||e.contentWindow!==s.source||i(s)};return globalThis.addEventListener("message",r),()=>globalThis.removeEventListener("message",r)}}),consumer:()=>new T({postMessage:e=>{globalThis.parent.postMessage(e,"*")},onMessage:e=>(globalThis.addEventListener("message",e),()=>{globalThis.removeEventListener("message",e)})})}),a(T,"worker",{host:e=>new T({postMessage:(i,r)=>{e.postMessage(i,r)},onMessage:i=>(e.addEventListener("message",i),()=>e.removeEventListener("message",i))}),consumer:()=>new T({postMessage:e=>{globalThis.postMessage(e)},onMessage:e=>(globalThis.addEventListener("message",e),()=>{globalThis.removeEventListener("message",e)})})});var dt=T,ft=class extends ht{constructor(){super(dt.iframe.consumer())}};var mt=class extends ht{constructor(){super(dt.worker.consumer())}};var Qt=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case q.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case U.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},Zt=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(Zt||{}),te=class{constructor(t){this.env=t,this.create()}},M=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(M||{}),ee=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},$=g(ee);async function pn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var ne=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>pn(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},ln=200,un=50,gt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<un){s%10===0&&console.log($(M.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=$(M.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},ln))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},Vt="__ENVIRONMENT_CONTEXT_KEY",Et=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Et||{}),Pt=class Pt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[Vt])throw $(M.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[Vt]=new Pt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[Vt]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Pt,"status",new gt("environment"));var Y=Pt,qt="__APPLICATION_CONTEXT_KEY",wt=class wt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new ne(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await Y.getInstance()).getEnvironment()!==Et.Frame)throw $(M.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[qt])throw $(M.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[qt]=new wt(t,await Y.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await Y.getInstance()).getEnvironment()===Et.Frame?(await this.status.waitInjected(),globalThis[qt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw $(M.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(wt,"status",new gt("application"));var ie=wt,hn={classic:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-default.global.css",studio:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-studio.global.css"},tt,et,bt,nt,vt=class extends te{constructor(){super(Zt.Frame);a(this,"type",Zt.Frame);u(this,tt,new E);u(this,et,new Qt(c(this,tt)));u(this,bt);u(this,nt)}create(){if(typeof globalThis?.document?.head?.prepend=="function"){let i=new URL(globalThis.location.href).searchParams.get("editorType")==="CLASSIC"?"classic":"studio",r=hn[i],s=r&&!!document.querySelectorAll(`link[type="text/css"][href="${r}"]`)?.length;if(r&&!s){let o=document.createElement("link");o.setAttribute("rel","stylesheet"),o.setAttribute("type","text/css"),o.setAttribute("href",r),globalThis.document.head.prepend(o)}}}async initEnvironment(e){let{applicationPrivateAPI:i,privateAPI:r,appDefinitionId:s}=e;I(this,nt,i),I(this,bt,r),await Y.inject({environment:Et.Frame,privateApi:r,events:c(this,tt),applicationAPIs:{[s]:c(this,nt)}}),await ie.inject({appDefinitionId:s,appDefinitionName:""})}notify(e){c(this,et).notify(e)}subscribe(e){c(this,et).subscribe(e)}};tt=new WeakMap,et=new WeakMap,bt=new WeakMap,nt=new WeakMap;var Fe=Pe(jt());var se=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case q.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case U.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},k=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(k||{}),oe=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},z=g(oe);async function dn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var ae=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>dn(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},fn=200,mn=50,_t=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<mn){s%10===0&&console.log(z(k.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=z(k.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},fn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},re="__ENVIRONMENT_CONTEXT_KEY",Ct=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Ct||{}),Rt=class Rt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[re])throw z(k.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[re]=new Rt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[re]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Rt,"status",new _t("environment"));var L=Rt,Tt="__APPLICATION_CONTEXT_KEY",Nt=class Nt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new ae(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await L.getInstance()).getEnvironment()!==Ct.Frame)throw z(k.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[Tt])throw z(k.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[Tt]=new Nt(t,await L.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await L.getInstance()).getEnvironment()===Ct.Frame?(await this.status.waitInjected(),globalThis[Tt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw z(k.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(Nt,"status",new _t("application"));var ce=Nt,C=(n=>(n.ApplicationRuntimeError="ApplicationRuntimeError",n.ApplicationCreationError="ApplicationCreationError",n.ApplicationLoadError="ApplicationLoadError",n.ApplicationFetchError="ApplicationFetchError",n.ApplicationExecuteError="ApplicationExecuteError",n.ApplicationWasRemoved="ApplicationWasRemoved",n.UndefinedApiMethod="UndefinedApiMethod",n.ApplicationIsNotMutable="ApplicationIsNotMutable",n.FailedToGetPrivateAPI="FailedToGetPrivateAPI",n.ClientAuthError="ClientAuthError",n))(C||{}),pe=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}withApiMethod(e){return this.state={...this.state,apiMethod:e},this}withApiType(e){return this.state={...this.state,apiType:e},this}},S=g(pe),In="__APPLICATION_REGISTRY_KEY";async function yn(n,t,e){let i=new Function(Tt,In,e),r,s=o=>{if(r)throw S(C.ApplicationExecuteError,"Application registry called more than once").withAppDefinitionId(t.appDefinitionId);if(o.type!==t.type)throw S(C.ApplicationExecuteError,"Application has different type").withMessage("expected type",t.type).withMessage("received type",o.type);r=o};try{let o={...t};i.call(null,new ce(o,await L.getInstance()),s)}catch(o){throw S(C.ApplicationExecuteError,o.message).withAppDefinitionId(t.appDefinitionId).withParentError(o)}return new Promise((o,p)=>{let l=n.subscribe(h=>{let f=setTimeout(()=>{clearTimeout(f),l(),r||p(S(C.ApplicationExecuteError,"Application registry was not called, threw by timeout").withAppDefinitionId(t.appDefinitionId))},5e3);h.type===d.ApplicationInit&&h.meta.appDefinitionId===t.appDefinitionId&&(clearTimeout(f),l(),r||p(S(C.ApplicationExecuteError,"Application registry was not called").withAppDefinitionId(t.appDefinitionId)),o({instance:r}))})})}var D,it,m,le=class{constructor(t,e){u(this,D,{});u(this,it);u(this,m);I(this,it,t),I(this,m,e),c(this,m).subscribe(i=>{switch(i.type){case d.HostEvent:{i.payload.type===Fe.EventType.removeAppCompleted&&c(this,m).withEvent(c(this,m).factories.createApplicationRemovedEvent(i.payload.appDefinitionId),()=>this.removeApplication(i.payload.appDefinitionId));break}}})}async runApplication(t){let e=await this.loadApplication(t),i=await this.executeApplication(t,e);return this.setApplication(t.appDefinitionId,i),i}setApplication(t,e){c(this,D)[t]=e,c(this,m).withEvent(c(this,m).factories.createApplicationApiInitEvent(t,e?.api?.private?"private":"public"),()=>{c(this,it).applicationManager.setApplication(e)})}getApplication(t){return c(this,D)[t]}getAppDefinitionIds(){return Object.keys(c(this,D))}removeApplication(t){delete c(this,D)[t]}async loadApplication(t){let e=t.url;return c(this,m).withEvent(c(this,m).factories.createApplicationLoadEvent(t,e),async()=>{try{return await this.loadApplicationBundle(e)}catch(i){throw S(C.ApplicationLoadError).withUrl(e).withAppDefinitionId(t.appDefinitionId).withParentError(i)}})}async loadApplicationBundle(t){let e=await fetch(t,{method:"GET"});if(!(e.status>=200&&e.status<=299))throw S(C.ApplicationFetchError).withUrl(t);return e.text()}async executeApplication(t,e){return c(this,m).withEvent(c(this,m).factories.createApplicationExecuteEvent(t,t.url),async()=>{let{instance:i}=await yn(c(this,m),t,e);return i})}};D=new WeakMap,it=new WeakMap,m=new WeakMap;var ue=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(ue||{}),he=class{constructor(t){this.env=t,this.create()}},X,rt,st,j,ot,xt=class extends he{constructor(){super(ue.Worker);a(this,"type",ue.Worker);u(this,X,new E);u(this,rt,new se(c(this,X)));u(this,st,null);u(this,j);u(this,ot,[])}create(){}async initEnvironment(e){let{buildPrivateAPI:i}=e;I(this,j,await i({type:"EDITOR_ADDON"})),await L.inject({environment:Ct.Worker,events:c(this,X),privateApi:c(this,j),applicationAPIs:{}}),I(this,st,new le(c(this,j),c(this,X))),c(this,ot).forEach(r=>r(this))}async notify(e){await this.waitReady(),c(this,rt).notify(e)}subscribe(e){c(this,rt).subscribe(e)}async runApplication(e){await this.waitReady(),await c(this,st).runApplication(e)}waitReady(){return new Promise(e=>{if(c(this,j))return e(this);c(this,ot).push(e)})}};X=new WeakMap,rt=new WeakMap,st=new WeakMap,j=new WeakMap,ot=new WeakMap;var F=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(F||{}),me=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},B=g(me);async function An(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var Ie=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>An(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},gn=200,En=50,Ot=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<En){s%10===0&&console.log(B(F.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=B(F.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},gn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},de="__ENVIRONMENT_CONTEXT_KEY",ye=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(ye||{}),Mt=class Mt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[de])throw B(F.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[de]=new Mt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[de]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Mt,"status",new Ot("environment"));var x=Mt,fe="__APPLICATION_CONTEXT_KEY",St=class St{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new Ie(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await x.getInstance()).getEnvironment()!==ye.Frame)throw B(F.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[fe])throw B(F.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[fe]=new St(t,await x.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await x.getInstance()).getEnvironment()===ye.Frame?(await this.status.waitInjected(),globalThis[fe]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw B(F.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(St,"status",new Ot("application"));var J=St,Ae=class extends y{constructor(e,i){super(e,i,"Auth Strategy Error");a(this,"state",{})}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},Ue=g(Ae);function vn(n,t){let e=Date.now(),i=n?new Date(n).getTime():null;return i&&i-e>t}var Pn=30*60*1e3,wn=()=>{let n;return{getAuthHeaders:async()=>{let t=await J.getInstance(),e=t.getBindings(),i=t.getPrivateAPI();if(!e.appDefinitionId)throw Ue("EmptyAppDefinitionId");return(!n||vn(n.expires,Pn))&&(n=await i.auth.getAccessToken(e.appDefinitionId,await i.info.getMetaSiteId())),n?.token?{headers:{Authorization:n.token}}:(console.error(Ue("EmptyAppAuthInstance").withAppDefinitionId(e.appDefinitionId)),{headers:{Authorization:""}})}}},We="_EP_TRANSPORT_INIT_KEY";globalThis[We]||(typeof importScripts=="function"?new mt().expose(new xt):new ft().expose(new vt),globalThis[We]=!0);var b=class{constructor(t,e){this.namespace=t,this.shape=e}build(){return be(Object.fromEntries(Object.entries(this.shape).map(([t,e])=>[t,i=>i?.environmentContext&&i?.applicationContext?async(...r)=>{let[s,o]=await Promise.all([i.environmentContext,i.applicationContext]);return e({environmentContext:s,applicationContext:o})(...r)}:async(...r)=>{let[s,o]=await Promise.all([x.getInstance(),J.getInstance()]);return e({environmentContext:s,applicationContext:o})(...r)}])))}},bn=new b("application",{getPrivateAPI({applicationContext:n}){return async()=>n.getPrivateApplicationAPI()},getPublicAPI({applicationContext:n}){return async t=>n.getPrivateAPI().applicationManager.getPublicApplicationAPI(t)},getAppInstance({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=n.getBindings();return t.info.getAppInstance(e.appDefinitionId)}}}),pi=bn.build(),Tn=new b("components",{getSelectedComponents({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=await t.components.getSelectedComponents();return Promise.all(e.map(i=>t.components.getComponent(i)))}}}),_n=Tn.build(),Cn=new b("events",{addEventListener({applicationContext:n}){return async(t,e)=>n.getEvents().addEventListener(t,e)}}),li=Cn.build(),xn=new b("info",{getViewMode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getViewMode()},getLanguageCode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getLanguageCode()}}),ui=xn.build(),Ye=(n=>(n.UndefinedCompRef="UndefinedCompRef",n))(Ye||{}),ge=class extends y{constructor(t,e){super(t,e,"Widget Error")}},Rn=g(ge),Ke=async()=>{let t=(await _n.getSelectedComponents())[0]?.compRef;if(!t)throw Rn(Ye.UndefinedCompRef);return t},Nn=new b("widget",{getProp({applicationContext:n}){return async t=>{let e=n.getPrivateAPI(),i=await Ke();return e.customElement.getAttribute(i,t)}},setProp({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=await Ke();await i.customElement.setAttribute(r,t,e)}}}),hi=Nn.build(),ze="underline";function On(n){let t=n.trim(),e=t.match(/var\((--[\w-]+),\s*(.+)\)/);return e?{variableName:e[1],fallbackValue:e[2]?.trim()??""}:{variableName:void 0,fallbackValue:t}}function Mn(n){let t={family:void 0,size:void 0};if(n?.font){let{variableName:e,fallbackValue:i}=On(n.font);t.cssVariableName=e;let r=i.match(/(?:(["']).*?\1|\S)+/g)||[];for(let s=0;s<r.length;s++){let o=r[s];switch(o){case"bold":t.bold=!0;break;case"italic":t.italic=!0;break;default:o?.endsWith("px")?t.size=parseInt(o,10):s===r.length-1?t.family=o:t.family=(t.family||"")+" "+o}}}return n?.textDecoration&&(t.underline=n.textDecoration===ze),t.family=t.family?.trim().replace(/['"]+/g,""),t}function Sn(n){return`${n.cssVariableName?`var(${n.cssVariableName}, `:""}${n.italic?"italic ":""}${n.bold?"bold ":""}${n.size||16}px ${n.family?.split(",").map(t=>`"${t.replace(/['"]+/g,"")}"`).join(",")||"serif"}${n.cssVariableName?")":""}`}function Dn(n){if(!n)return null;let t=n,e=t.match(/var\((--[\w-]+),\s*(.+)\)/);return e?{cssVariableName:e[1],color:e[2]}:{color:t}}function $e(n){return n?n.cssVariableName?`var(${n.cssVariableName}, ${n.color})`:n.color:""}var jn={transformFontInternalValue:n=>{if(n){let{theme:t,cssVariableName:e,bold:i,italic:r,underline:s,...o}=n;return{...o,style:{bold:i,italic:r,underline:s},editorKey:e||t||""}}else return{editorKey:"font_7",family:"helvetica-w01-roman",size:16,style:{}}}},kn=new b("inputs",{selectColor({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=Dn(t),s=$e(r);return await i.inputs.openColorPicker({color:r?.cssVariableName||r?.theme||r?.color},({color:o,theme:p,cssVariableTheme:l})=>{r={color:o,theme:p,cssVariableName:l},s=$e(r),e?.onChange?.(s)}),s}},selectFont({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=Mn(t),s=t;return await i.inputs.openFontPickerV2({...e,panelSectionsDefinition:{...e?.panelSectionsDefinition,htmlTag:"hidden"},componentStyle:jn.transformFontInternalValue(r)},(o,p)=>{s={font:Sn(o),textDecoration:o.underline?ze:void 0},e?.onChange?.(s)}),s}}}),di=kn.build(),Ln=new b("externalPanels",{getData({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getData()},setData({applicationContext:n}){return async t=>n.getPrivateAPI().externalPanels.setData(t)},getStyle({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getStyle()},setStyle({applicationContext:n}){return async t=>n.getPrivateAPI().externalPanels.setStyle(t)},getTheme({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getTheme()},selectMedia({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectMedia()},selectLink({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectLink()},selectColor({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectColor()},translate({applicationContext:n}){return async(t,e)=>n.getPrivateAPI().externalPanels.translate(t,e)}}),fi=Ln.build(),Fn=()=>{let n=new URLSearchParams(window.location.search);return{environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:x.getInstance(),applicationContext:J.getInstance(),essentials:n.has("essentials")?JSON.parse(n.get("essentials")):{}}},Un=()=>({environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:x.getInstance(),applicationContext:J.getInstance()}),Ee={host:()=>typeof importScripts=="function"?Un():Fn(),auth:wn};var gi=()=>{let n=Ee.host(),t=Ee.auth();we({auth:t,host:n}).enableContext("module")};export{gi as enableClient};
8
8
  //# sourceMappingURL=editor.js.map