@waniwani/sdk 0.12.2 → 0.12.4-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -656,22 +656,13 @@ interface AutoCaptureToggles {
656
656
  formSubmit?: boolean;
657
657
  }
658
658
 
659
- /**
660
- * Options for the useWaniwani hook.
661
- */
662
- interface UseWaniwaniOptions {
659
+ interface BaseUseWaniwaniOptions {
663
660
  /**
664
661
  * JWT widget token for authenticating directly with the WaniWani backend.
665
662
  * If omitted, the hook resolves from tool response metadata
666
663
  * (`toolResponseMetadata.waniwani` or `toolResponseMetadata._meta.waniwani`).
667
664
  */
668
665
  token?: string;
669
- /**
670
- * The V2 batch endpoint URL to POST tracking events to.
671
- * If omitted, the hook resolves from tool response metadata
672
- * (`toolResponseMetadata.waniwani` or `toolResponseMetadata._meta.waniwani`).
673
- */
674
- endpoint?: string;
675
666
  /**
676
667
  * Session ID to use for event correlation.
677
668
  * If omitted, the hook resolves from tool response metadata
@@ -692,6 +683,31 @@ interface UseWaniwaniOptions {
692
683
  */
693
684
  capture?: AutoCaptureToggles;
694
685
  }
686
+ /**
687
+ * Context-driven options: `endpoint` and `source` are resolved from
688
+ * `WidgetProvider`'s `toolResponseMetadata.waniwani`. `source` may be
689
+ * overridden explicitly.
690
+ */
691
+ interface ContextDrivenOptions extends BaseUseWaniwaniOptions {
692
+ endpoint?: undefined;
693
+ /** Optional override; otherwise resolved from context. */
694
+ source?: string;
695
+ }
696
+ /**
697
+ * Explicit-endpoint options: when `endpoint` is passed directly, `source`
698
+ * is required so events never get stamped with a placeholder.
699
+ */
700
+ interface ExplicitEndpointOptions extends BaseUseWaniwaniOptions {
701
+ /** V2 batch endpoint URL to POST tracking events to. */
702
+ endpoint: string;
703
+ /** Required when `endpoint` is explicit (e.g. `"chatgpt"`, `"chatbar"`). */
704
+ source: string;
705
+ }
706
+ /**
707
+ * Options for the useWaniwani hook. Either rely on `WidgetProvider`
708
+ * context (omit `endpoint`) or pass `endpoint` + `source` explicitly.
709
+ */
710
+ type UseWaniwaniOptions = ContextDrivenOptions | ExplicitEndpointOptions;
695
711
  /**
696
712
  * The tracking API returned by `useWaniwani()`.
697
713
  */
@@ -713,9 +729,9 @@ interface WaniwaniWidget {
713
729
  * instance shared across all consumers.
714
730
  *
715
731
  * Config resolution order:
716
- * 1. Explicit `endpoint` (+ optional `token` / `sessionId`) options
732
+ * 1. Explicit `endpoint` / `token` / `sessionId` / `source` options
717
733
  * 2. `toolResponseMetadata.waniwani` from WidgetProvider context
718
- * 3. No-op if neither is available
734
+ * 3. No-op if `endpoint` cannot be resolved or `source` is unknown
719
735
  *
720
736
  * @example
721
737
  * ```tsx
package/dist/mcp/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import{a as V,b as Me,c as Se}from"../chunk-DP6SAQTK.js";import{b as H,c as Te}from"../chunk-RZKVTH7F.js";import{Fragment as nt,jsx as B,jsxs as ot}from"react/jsx-runtime";function et(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(p=>{p.forEach(g=>{if(g.type==="attributes"&&g.target===n){let c=g.attributeName;c&&c!=="suppresshydrationwarning"&&c!=="lang"&&c!=="class"&&c!=="style"&&n.removeAttribute(c)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let r=history.replaceState.bind(history);history.replaceState=(p,g,c)=>{try{let s=new URL(String(c??""),window.location.href);r(null,g,s.pathname+s.search+s.hash)}catch{}};let u=history.pushState.bind(history);history.pushState=(p,g,c)=>{try{let s=new URL(String(c??""),window.location.href);u(null,g,s.pathname+s.search+s.hash)}catch{}};let f=new URL(e).origin,w=window.self!==window.top;if(window.addEventListener("click",p=>{let g=p?.target?.closest("a");if(!g||!g.href)return;let c=new URL(g.href,window.location.href);if(c.origin!==window.location.origin&&c.origin!==f)try{window.openai&&(window.openai?.openExternal({href:g.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),w&&window.location.origin!==f){let p=window.fetch;window.fetch=((o,l)=>{let m=typeof o=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(o)&&!o.startsWith("//"),d;if(typeof o=="string"||o instanceof URL?d=new URL(o,window.location.href):d=new URL(o.url,window.location.href),d.origin===f)return typeof o=="string"||o instanceof URL?o=d.toString():o=new Request(d.toString(),o),p.call(window,o,{...l,mode:"cors"});if(t.indexOf(d.origin)!==-1)return p.call(window,o,l);if(m&&d.origin===window.location.origin){let x=new URL(e);return x.pathname=d.pathname,x.search=d.search,x.hash=d.hash,d=x,o=d.toString(),p.call(window,o,{...l,mode:"cors"})}return p.call(window,o,l)});let g=f.replace(/^http/,"ws"),c=window.WebSocket,s=((o,l)=>{let m=new URL(String(o),window.location.href);if(m.origin===window.location.origin||m.origin===window.location.origin.replace(/^http/,"ws")){let d=new URL(g);return d.pathname=m.pathname,d.search=m.search,d.hash=m.hash,new c(d.toString(),l)}return new c(o,l)});s.prototype=c.prototype,Object.assign(s,{CONNECTING:c.CONNECTING,OPEN:c.OPEN,CLOSING:c.CLOSING,CLOSED:c.CLOSED}),window.WebSocket=s}}var tt=`(${et.toString()})()`;function Ee({baseUrl:e,passthroughOrigins:t}){return ot(nt,{children:[B("base",{href:e}),B("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),B("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),B("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),B("script",{children:tt})]})}import{useCallback as T,useEffect as F,useRef as Z,useState as C}from"react";var Re={theme:"dark",userAgent:{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:"en",maxHeight:800,displayMode:"inline",safeArea:{insets:{top:0,bottom:0,left:0,right:0}},toolInput:{},toolOutput:null,toolResponseMetadata:null,widgetState:null},G={...Re};function U(e){typeof window>"u"||window.openai||(G={...Re,toolOutput:e??null},window.openai={...G,requestDisplayMode:async({mode:t})=>(R("displayMode",t),{mode:t}),callTool:async(t,n)=>(console.log(`[DevMode] callTool: ${t}`,n),{result:JSON.stringify({mock:!0,tool:t,args:n})}),sendFollowUpMessage:async({prompt:t})=>{console.log(`[DevMode] sendFollowUpMessage: ${t}`)},openExternal:({href:t})=>{console.log(`[DevMode] openExternal: ${t}`),window.open(t,"_blank")},setWidgetState:async t=>{R("widgetState",t)}},window.dispatchEvent(new H({globals:G})))}function R(e,t){typeof window>"u"||!window.openai||(G[e]=t,window.openai[e]=t,window.dispatchEvent(new H({globals:{[e]:t}})))}function j(){return{...G}}function N(e){R("toolOutput",e)}function L(e){R("displayMode",e)}function D(e){R("theme",e)}import{Fragment as Q,jsx as a,jsxs as y}from"react/jsx-runtime";var $=150;function We({className:e}){return y("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[a("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),a("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function rt({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:a("path",{d:"M18 6L6 18M6 6l12 12"})})}function it({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function st({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),a("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function at({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("path",{d:"M2 5.5V3.5C2 2.95 2.45 2.5 3 2.5H5.5M10.5 2.5H13C13.55 2.5 14 2.95 14 3.5V5.5M14 10.5V12.5C14 13.05 13.55 13.5 13 13.5H10.5M5.5 13.5H3C2.45 13.5 2 13.05 2 12.5V10.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function lt({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),a("path",{d:"M8 2v1.5M8 12.5V14M2 8h1.5M12.5 8H14M4.11 4.11l1.06 1.06M10.83 10.83l1.06 1.06M4.11 11.89l1.06-1.06M10.83 5.17l1.06-1.06",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]})}function dt({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("path",{d:"M13.5 9.5a5.5 5.5 0 01-7-7 5.5 5.5 0 107 7z",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function ut({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("path",{d:"M2.5 8a5.5 5.5 0 019.37-3.9M13.5 8a5.5 5.5 0 01-9.37 3.9",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"}),a("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var ct=`
2
+ import{a as V,b as ke,c as Ce}from"../chunk-DP6SAQTK.js";import{b as H,c as Me}from"../chunk-RZKVTH7F.js";import{Fragment as nt,jsx as B,jsxs as ot}from"react/jsx-runtime";function et(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(p=>{p.forEach(g=>{if(g.type==="attributes"&&g.target===n){let c=g.attributeName;c&&c!=="suppresshydrationwarning"&&c!=="lang"&&c!=="class"&&c!=="style"&&n.removeAttribute(c)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let r=history.replaceState.bind(history);history.replaceState=(p,g,c)=>{try{let s=new URL(String(c??""),window.location.href);r(null,g,s.pathname+s.search+s.hash)}catch{}};let u=history.pushState.bind(history);history.pushState=(p,g,c)=>{try{let s=new URL(String(c??""),window.location.href);u(null,g,s.pathname+s.search+s.hash)}catch{}};let f=new URL(e).origin,h=window.self!==window.top;if(window.addEventListener("click",p=>{let g=p?.target?.closest("a");if(!g||!g.href)return;let c=new URL(g.href,window.location.href);if(c.origin!==window.location.origin&&c.origin!==f)try{window.openai&&(window.openai?.openExternal({href:g.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),h&&window.location.origin!==f){let p=window.fetch;window.fetch=((o,a)=>{let m=typeof o=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(o)&&!o.startsWith("//"),d;if(typeof o=="string"||o instanceof URL?d=new URL(o,window.location.href):d=new URL(o.url,window.location.href),d.origin===f)return typeof o=="string"||o instanceof URL?o=d.toString():o=new Request(d.toString(),o),p.call(window,o,{...a,mode:"cors"});if(t.indexOf(d.origin)!==-1)return p.call(window,o,a);if(m&&d.origin===window.location.origin){let x=new URL(e);return x.pathname=d.pathname,x.search=d.search,x.hash=d.hash,d=x,o=d.toString(),p.call(window,o,{...a,mode:"cors"})}return p.call(window,o,a)});let g=f.replace(/^http/,"ws"),c=window.WebSocket,s=((o,a)=>{let m=new URL(String(o),window.location.href);if(m.origin===window.location.origin||m.origin===window.location.origin.replace(/^http/,"ws")){let d=new URL(g);return d.pathname=m.pathname,d.search=m.search,d.hash=m.hash,new c(d.toString(),a)}return new c(o,a)});s.prototype=c.prototype,Object.assign(s,{CONNECTING:c.CONNECTING,OPEN:c.OPEN,CLOSING:c.CLOSING,CLOSED:c.CLOSED}),window.WebSocket=s}}var tt=`(${et.toString()})()`;function Se({baseUrl:e,passthroughOrigins:t}){return ot(nt,{children:[B("base",{href:e}),B("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),B("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),B("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),B("script",{children:tt})]})}import{useCallback as S,useEffect as F,useRef as Z,useState as C}from"react";var Te={theme:"dark",userAgent:{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:"en",maxHeight:800,displayMode:"inline",safeArea:{insets:{top:0,bottom:0,left:0,right:0}},toolInput:{},toolOutput:null,toolResponseMetadata:null,widgetState:null},G={...Te};function U(e){typeof window>"u"||window.openai||(G={...Te,toolOutput:e??null},window.openai={...G,requestDisplayMode:async({mode:t})=>(E("displayMode",t),{mode:t}),callTool:async(t,n)=>(console.log(`[DevMode] callTool: ${t}`,n),{result:JSON.stringify({mock:!0,tool:t,args:n})}),sendFollowUpMessage:async({prompt:t})=>{console.log(`[DevMode] sendFollowUpMessage: ${t}`)},openExternal:({href:t})=>{console.log(`[DevMode] openExternal: ${t}`),window.open(t,"_blank")},setWidgetState:async t=>{E("widgetState",t)}},window.dispatchEvent(new H({globals:G})))}function E(e,t){typeof window>"u"||!window.openai||(G[e]=t,window.openai[e]=t,window.dispatchEvent(new H({globals:{[e]:t}})))}function j(){return{...G}}function N(e){E("toolOutput",e)}function L(e){E("displayMode",e)}function D(e){E("theme",e)}import{Fragment as Q,jsx as l,jsxs as y}from"react/jsx-runtime";var $=150;function Ee({className:e}){return y("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[l("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),l("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function rt({className:e}){return l("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M18 6L6 18M6 6l12 12"})})}function it({className:e}){return l("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:l("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function st({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[l("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),l("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function at({className:e}){return l("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:l("path",{d:"M2 5.5V3.5C2 2.95 2.45 2.5 3 2.5H5.5M10.5 2.5H13C13.55 2.5 14 2.95 14 3.5V5.5M14 10.5V12.5C14 13.05 13.55 13.5 13 13.5H10.5M5.5 13.5H3C2.45 13.5 2 13.05 2 12.5V10.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function lt({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[l("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),l("path",{d:"M8 2v1.5M8 12.5V14M2 8h1.5M12.5 8H14M4.11 4.11l1.06 1.06M10.83 10.83l1.06 1.06M4.11 11.89l1.06-1.06M10.83 5.17l1.06-1.06",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]})}function dt({className:e}){return l("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:l("path",{d:"M13.5 9.5a5.5 5.5 0 01-7-7 5.5 5.5 0 107 7z",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function ut({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[l("path",{d:"M2.5 8a5.5 5.5 0 019.37-3.9M13.5 8a5.5 5.5 0 01-9.37 3.9",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"}),l("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var ct=`
3
3
  @keyframes devPanelSlideIn {
4
4
  0% {
5
5
  opacity: 0;
@@ -47,22 +47,22 @@ import{a as V,b as Me,c as Se}from"../chunk-DP6SAQTK.js";import{b as H,c as Te}f
47
47
  .dev-json-editor::-webkit-scrollbar-thumb:hover {
48
48
  background: rgba(255, 255, 255, 0.15);
49
49
  }
50
- `;function ee({defaultProps:e,widgetPaths:t,children:n}){let[i,r]=C(!1),[u,f]=C(!1);return F(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){r(!0);return}if(t&&t.length>0){let p=window.location.pathname,g=t.some(c=>p===c||p.startsWith(`${c}/`));f(g),g&&U(e)}else U(e),f(!0);r(!0)},[e,t]),i?u?y(Q,{children:[a(pt,{children:n}),a(gt,{defaultProps:e})]}):a(Q,{children:n}):null}function pt({children:e}){return a("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:a("div",{className:"relative w-full max-w-md overflow-hidden rounded-2xl sm:rounded-3xl border border-[#414141]",style:{boxShadow:"0px 0px 0px 1px #414141, 0px 4px 14px rgba(0,0,0,0.24)"},children:e})})}function _e({options:e,value:t,onChange:n}){let i=e.findIndex(r=>r.value===t);return y("div",{className:"relative flex p-0.5 rounded-lg",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:[a("div",{className:"absolute top-0.5 bottom-0.5 rounded-md transition-transform duration-150 ease-out",style:{width:`calc(${100/e.length}% - 2px)`,left:"2px",transform:`translateX(calc(${i*100}% + ${i*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(r=>y("button",{type:"button",onClick:()=>n(r.value),className:`
50
+ `;function ee({defaultProps:e,widgetPaths:t,children:n}){let[i,r]=C(!1),[u,f]=C(!1);return F(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){r(!0);return}if(t&&t.length>0){let p=window.location.pathname,g=t.some(c=>p===c||p.startsWith(`${c}/`));f(g),g&&U(e)}else U(e),f(!0);r(!0)},[e,t]),i?u?y(Q,{children:[l(pt,{children:n}),l(gt,{defaultProps:e})]}):l(Q,{children:n}):null}function pt({children:e}){return l("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:l("div",{className:"relative w-full max-w-md overflow-hidden rounded-2xl sm:rounded-3xl border border-[#414141]",style:{boxShadow:"0px 0px 0px 1px #414141, 0px 4px 14px rgba(0,0,0,0.24)"},children:e})})}function Re({options:e,value:t,onChange:n}){let i=e.findIndex(r=>r.value===t);return y("div",{className:"relative flex p-0.5 rounded-lg",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:[l("div",{className:"absolute top-0.5 bottom-0.5 rounded-md transition-transform duration-150 ease-out",style:{width:`calc(${100/e.length}% - 2px)`,left:"2px",transform:`translateX(calc(${i*100}% + ${i*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(r=>y("button",{type:"button",onClick:()=>n(r.value),className:`
51
51
  relative z-10 flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5
52
52
  text-xs font-medium rounded-md transition-colors duration-150
53
53
  ${t===r.value?"text-white":"text-gray-400 hover:text-gray-300"}
54
- `,children:[r.icon,a("span",{className:"capitalize",children:r.label})]},r.value))]})}function gt({defaultProps:e}){let[t,n]=C(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[i,r]=C(!1),[u,f]=C(t),[w,p]=C("inline"),[g,c]=C("dark"),[s,o]=C(!1),[l,m]=C(()=>JSON.stringify(e??{},null,2)),[d,x]=C(null),b=Z(null),E=Z(null),P=Z(null);F(()=>{let h=j();p(h.displayMode),c(h.theme)},[]),F(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:s?$:0,left:0,right:0}},window.dispatchEvent(new H({globals:{safeArea:window.openai.safeArea}})))},[s]),F(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let O=T(()=>{f(!0),requestAnimationFrame(()=>{n(!0)})},[]),W=T(()=>{r(!0),n(!1),setTimeout(()=>{f(!1),r(!1)},150)},[]),q=T(()=>{t?W():O()},[t,O,W]);F(()=>{let h=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="d"&&(k.preventDefault(),q()),k.key==="Escape"&&t&&W()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,q,W]),F(()=>{if(!t)return;let h=k=>{P.current&&!P.current.contains(k.target)&&W()};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[t,W]);let Ve=T(h=>{p(h),L(h)},[]),$e=T(h=>{c(h),D(h)},[]),J=T(h=>{try{let k=JSON.parse(h);x(null),N(k)}catch{x("Invalid JSON")}},[]),Xe=T(h=>{m(h),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{J(h)},500)},[J]),Ye=T(()=>{b.current&&clearTimeout(b.current),J(l)},[J,l]),qe=T(()=>{let h=JSON.stringify(e??{},null,2);m(h),x(null),N(e??{}),p("inline"),L("inline"),c("dark"),D("dark")},[e]),Ze=[{value:"inline",label:"inline",icon:a(it,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:a(st,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:a(at,{className:"w-3.5 h-3.5"})}],Qe=[{value:"light",label:"light",icon:a(lt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:a(dt,{className:"w-3.5 h-3.5"})}];return y(Q,{children:[a("style",{dangerouslySetInnerHTML:{__html:ct}}),y("div",{ref:P,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[y("button",{type:"button",onClick:q,className:"group relative flex items-center justify-center w-11 h-11 rounded-xl transition-all duration-200 ease-out hover:scale-105 active:scale-95",style:{background:"rgba(14, 14, 16, 0.95)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(255, 255, 255, 0.08)",boxShadow:`
54
+ `,children:[r.icon,l("span",{className:"capitalize",children:r.label})]},r.value))]})}function gt({defaultProps:e}){let[t,n]=C(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[i,r]=C(!1),[u,f]=C(t),[h,p]=C("inline"),[g,c]=C("dark"),[s,o]=C(!1),[a,m]=C(()=>JSON.stringify(e??{},null,2)),[d,x]=C(null),b=Z(null),T=Z(null),P=Z(null);F(()=>{let w=j();p(w.displayMode),c(w.theme)},[]),F(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:s?$:0,left:0,right:0}},window.dispatchEvent(new H({globals:{safeArea:window.openai.safeArea}})))},[s]),F(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let I=S(()=>{f(!0),requestAnimationFrame(()=>{n(!0)})},[]),W=S(()=>{r(!0),n(!1),setTimeout(()=>{f(!1),r(!1)},150)},[]),q=S(()=>{t?W():I()},[t,I,W]);F(()=>{let w=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="d"&&(k.preventDefault(),q()),k.key==="Escape"&&t&&W()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[t,q,W]),F(()=>{if(!t)return;let w=k=>{P.current&&!P.current.contains(k.target)&&W()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[t,W]);let Ve=S(w=>{p(w),L(w)},[]),$e=S(w=>{c(w),D(w)},[]),J=S(w=>{try{let k=JSON.parse(w);x(null),N(k)}catch{x("Invalid JSON")}},[]),Xe=S(w=>{m(w),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{J(w)},500)},[J]),Ye=S(()=>{b.current&&clearTimeout(b.current),J(a)},[J,a]),qe=S(()=>{let w=JSON.stringify(e??{},null,2);m(w),x(null),N(e??{}),p("inline"),L("inline"),c("dark"),D("dark")},[e]),Ze=[{value:"inline",label:"inline",icon:l(it,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:l(st,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:l(at,{className:"w-3.5 h-3.5"})}],Qe=[{value:"light",label:"light",icon:l(lt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:l(dt,{className:"w-3.5 h-3.5"})}];return y(Q,{children:[l("style",{dangerouslySetInnerHTML:{__html:ct}}),y("div",{ref:P,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[y("button",{type:"button",onClick:q,className:"group relative flex items-center justify-center w-11 h-11 rounded-xl transition-all duration-200 ease-out hover:scale-105 active:scale-95",style:{background:"rgba(14, 14, 16, 0.95)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(255, 255, 255, 0.08)",boxShadow:`
55
55
  0 4px 12px rgba(0, 0, 0, 0.4),
56
56
  0 0 0 1px rgba(255, 255, 255, 0.05),
57
57
  inset 0 1px 0 rgba(255, 255, 255, 0.04)
58
- `},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[a(We,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),a("div",{className:"absolute inset-0 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",style:{background:"radial-gradient(circle at center, rgba(99, 102, 241, 0.15) 0%, transparent 70%)"}})]}),u&&y("div",{ref:E,className:`absolute bottom-14 right-0 w-80 ${t&&!i?"dev-panel-enter":"dev-panel-exit"}`,style:{maxHeight:"calc(100vh - 120px)",background:"rgba(14, 14, 16, 0.92)",backdropFilter:"blur(24px)",WebkitBackdropFilter:"blur(24px)",border:"1px solid rgba(255, 255, 255, 0.06)",borderRadius:"16px",boxShadow:`
58
+ `},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[l(Ee,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),l("div",{className:"absolute inset-0 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",style:{background:"radial-gradient(circle at center, rgba(99, 102, 241, 0.15) 0%, transparent 70%)"}})]}),u&&y("div",{ref:T,className:`absolute bottom-14 right-0 w-80 ${t&&!i?"dev-panel-enter":"dev-panel-exit"}`,style:{maxHeight:"calc(100vh - 120px)",background:"rgba(14, 14, 16, 0.92)",backdropFilter:"blur(24px)",WebkitBackdropFilter:"blur(24px)",border:"1px solid rgba(255, 255, 255, 0.06)",borderRadius:"16px",boxShadow:`
59
59
  0 25px 50px -12px rgba(0, 0, 0, 0.6),
60
60
  0 0 0 1px rgba(255, 255, 255, 0.05),
61
61
  inset 0 1px 0 rgba(255, 255, 255, 0.04)
62
- `},children:[y("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[y("div",{className:"flex items-center gap-2",children:[a(We,{className:"w-4 h-4 text-gray-400"}),a("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),y("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-[10px] font-medium text-gray-500 px-1.5 py-0.5 rounded",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:typeof navigator<"u"&&navigator.platform?.includes("Mac")?"\u2318\u21E7D":"Ctrl+Shift+D"}),a("button",{type:"button",onClick:W,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:a(rt,{className:"w-4 h-4"})})]})]}),y("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[y("div",{children:[a("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),a(_e,{options:Ze,value:w,onChange:Ve})]}),y("div",{children:[a("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),a(_e,{options:Qe,value:g,onChange:$e})]}),y("div",{children:[a("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),y("button",{type:"button",onClick:()=>o(!s),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${s?"text-emerald-400":"text-gray-400"}`,style:{background:s?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:s?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[a("span",{children:"Mock ChatGPT Input Bar"}),a("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${s?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:s?"ON":"OFF"})]}),s&&y("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",$,"px"]})]}),y("div",{children:[a("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),a("textarea",{value:l,onChange:h=>Xe(h.target.value),onBlur:Ye,className:"dev-json-editor w-full min-h-[160px] text-xs text-gray-200 p-3 rounded-lg resize-none focus:outline-none transition-colors",style:{background:"rgba(0, 0, 0, 0.3)",border:d?"1px solid rgba(239, 68, 68, 0.5)":"1px solid rgba(255, 255, 255, 0.06)",fontFamily:"'JetBrains Mono', 'SF Mono', 'Fira Code', monospace",lineHeight:1.6},onFocus:h=>{d||(h.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:h=>{d||(h.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),d&&y("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[a("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:a("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),d]})]}),y("button",{type:"button",onClick:qe,className:"w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-gray-400 transition-all duration-150 hover:text-gray-200",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},onMouseEnter:h=>{h.currentTarget.style.background="rgba(255, 255, 255, 0.08)",h.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:h=>{h.currentTarget.style.background="rgba(255, 255, 255, 0.04)",h.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[a(ut,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),s&&y("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${$}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[y("div",{className:"w-full max-w-2xl mx-4 px-4 py-3 rounded-2xl bg-[#2f2f2f] border border-[#424242] flex items-center gap-3",children:[a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),a("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})})})]}),y("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",$,"px"]})]})]})}import{useCallback as ft,useContext as ht,useLayoutEffect as wt,useMemo as vt,useRef as Ae}from"react";import{createContext as mt}from"react";var _=mt(null);import{Fragment as Ie,jsx as te}from"react/jsx-runtime";var yt="waniwani:send-follow-up:advanced:",xt=1e4;function Oe(e){return`${yt}${e??"default"}`}function bt(e){try{let t=globalThis.localStorage?.getItem(Oe(e));if(!t)return null;let n=JSON.parse(t);return typeof n?.at!="number"||typeof n?.byMountId!="string"?null:n}catch{return null}}function kt(e,t){try{globalThis.localStorage?.setItem(Oe(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Ct(){return ne()?window.openai:null}function Mt(){return wt(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),i=t.getAttribute("style"),r="margin:0!important;padding:0!important;border:0!important;background:transparent!important;background-color:transparent!important;height:0!important;min-height:0!important;max-height:0!important;overflow:hidden!important;";return e.setAttribute("style",r),t.setAttribute("style",r),()=>{n===null?e.removeAttribute("style"):e.setAttribute("style",n),i===null?t.removeAttribute("style"):t.setAttribute("style",i)}},[]),null}function oe(e){let t=ht(_),n=Ae(e);n.current=e;let i=t?.getToolResponseMetadata?.()??null,r=Ct()?.toolResponseMetadata??null,u=i??r,f=u&&typeof u.viewUUID=="string"?u.viewUUID:void 0,w=Ae("");w.current===""&&(w.current=crypto.randomUUID());let p=ft((c,s)=>{ne()&&kt(f,w.current);try{Promise.resolve(n.current(c)).catch(o=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",o)})}catch(o){console.error("[unstable_useSendFollowUpWithGhostGuard]",o)}},[f]),g=vt(()=>{let c=w.current;return function({children:o}){if(!ne())return te(Ie,{children:o});let l=bt(f);return l&&l.byMountId!==c&&Date.now()-l.at<xt?te(Mt,{}):te(Ie,{children:o})}},[f]);return{sendFollowUp:p,Guard:g}}import{useCallback as Et}from"react";import K,{useCallback as Ne,useContext as St,useEffect as Le,useState as re,useSyncExternalStore as Tt}from"react";async function Ue(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-TZIOCMXP.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-OFYMQOI3.js");return new n}}function ie({children:e,loading:t=null,onError:n}){let[i,r]=re(null),[u,f]=re(null),[w,p]=re(!0);return Le(()=>{let g=!0,c=null;async function s(){try{let o=await Ue();await o.connect(),g?(c=o,r(o),p(!1)):o.close()}catch(o){g&&(console.error("error",o),f(o instanceof Error?o:new Error(String(o))),p(!1))}}return s(),()=>{g=!1,c?.close()}},[]),Le(()=>{if(!i)return;let g=c=>{document.documentElement.classList.toggle("dark",c==="dark"),document.documentElement.style.colorScheme=c==="dark"?"dark":"auto"};return g(i.getTheme()),i.onThemeChange(g)},[i]),u&&n?K.createElement(K.Fragment,null,n(u)):w||!i?K.createElement(K.Fragment,null,t):K.createElement(_.Provider,{value:i},e)}function v(e){let t=St(_);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Ne(u=>e==="toolOutput"?t.onToolResult(()=>u()):e==="theme"?t.onThemeChange(()=>u()):e==="displayMode"?t.onDisplayModeChange(()=>u()):e==="safeArea"?t.onSafeAreaChange(()=>u()):e==="maxHeight"?t.onMaxHeightChange(()=>u()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>u()):e==="widgetState"?t.onWidgetStateChange(()=>u()):()=>{},[t,e]),i=Ne(()=>e==="toolOutput"?t.getToolOutput():e==="theme"?t.getTheme():e==="displayMode"?t.getDisplayMode():e==="locale"?t.getLocale():e==="safeArea"?t.getSafeArea():e==="maxHeight"?t.getMaxHeight():e==="toolResponseMetadata"?t.getToolResponseMetadata():e==="widgetState"?t.getWidgetState():null,[t,e]),r=Tt(n,i,i);return e?r:t}function se(){let e=v();return Et((t,n)=>e.callTool(t,n),[e])}function ae(){return v("displayMode")}function z(){return v("toolOutput")}function le(){return{data:z()}}import{useSyncExternalStore as Rt}from"react";function de(){return Rt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return v("locale")}function ce(){return v("maxHeight")}import{useCallback as Wt}from"react";function pe(){let e=v();return Wt(t=>e.openExternal(t),[e])}import{useCallback as _t}from"react";function ge(){let e=v();return _t(t=>e.requestDisplayMode(t),[e])}function me(){return v("safeArea")}import{useCallback as At}from"react";function fe(){let e=v();return At((t,n)=>{(async()=>{Te(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(i=>{console.error("Failed to send follow-up message:",i)})},[e])}function he(){return v("theme")}function we(){return v("toolResponseMetadata")}import{useCallback as It}from"react";function ve(){let e=v();return It(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as Ot,useEffect as Ut,useState as Nt}from"react";function ye(e){let t=v("widgetState"),[n,i]=Nt(()=>t??(typeof e=="function"?e():e??null));Ut(()=>{i(t)},[t]);let r=Ot(u=>{i(f=>{let w=typeof u=="function"?u(f):u;return V()==="openai"&&w!=null&&window.openai?.setWidgetState(w),w})},[]);return[n,r]}import{jsx as A,jsxs as De}from"react/jsx-runtime";var Fe=()=>De("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[De("div",{className:"flex gap-2",children:[A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),A("p",{className:"text-sm font-medium text-transparent bg-clip-text bg-gradient-to-r from-slate-400 via-slate-200 to-slate-400 bg-[length:200%_100%] animate-[shimmer_1.5s_ease-in-out_infinite]",children:"Loading widget..."}),A("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:A("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),A("style",{children:`
62
+ `},children:[y("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[y("div",{className:"flex items-center gap-2",children:[l(Ee,{className:"w-4 h-4 text-gray-400"}),l("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),y("div",{className:"flex items-center gap-2",children:[l("span",{className:"text-[10px] font-medium text-gray-500 px-1.5 py-0.5 rounded",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:typeof navigator<"u"&&navigator.platform?.includes("Mac")?"\u2318\u21E7D":"Ctrl+Shift+D"}),l("button",{type:"button",onClick:W,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:l(rt,{className:"w-4 h-4"})})]})]}),y("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[y("div",{children:[l("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),l(Re,{options:Ze,value:h,onChange:Ve})]}),y("div",{children:[l("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),l(Re,{options:Qe,value:g,onChange:$e})]}),y("div",{children:[l("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),y("button",{type:"button",onClick:()=>o(!s),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${s?"text-emerald-400":"text-gray-400"}`,style:{background:s?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:s?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[l("span",{children:"Mock ChatGPT Input Bar"}),l("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${s?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:s?"ON":"OFF"})]}),s&&y("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",$,"px"]})]}),y("div",{children:[l("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),l("textarea",{value:a,onChange:w=>Xe(w.target.value),onBlur:Ye,className:"dev-json-editor w-full min-h-[160px] text-xs text-gray-200 p-3 rounded-lg resize-none focus:outline-none transition-colors",style:{background:"rgba(0, 0, 0, 0.3)",border:d?"1px solid rgba(239, 68, 68, 0.5)":"1px solid rgba(255, 255, 255, 0.06)",fontFamily:"'JetBrains Mono', 'SF Mono', 'Fira Code', monospace",lineHeight:1.6},onFocus:w=>{d||(w.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:w=>{d||(w.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),d&&y("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[l("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:l("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),d]})]}),y("button",{type:"button",onClick:qe,className:"w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-gray-400 transition-all duration-150 hover:text-gray-200",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},onMouseEnter:w=>{w.currentTarget.style.background="rgba(255, 255, 255, 0.08)",w.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:w=>{w.currentTarget.style.background="rgba(255, 255, 255, 0.04)",w.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[l(ut,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),s&&y("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${$}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[y("div",{className:"w-full max-w-2xl mx-4 px-4 py-3 rounded-2xl bg-[#2f2f2f] border border-[#424242] flex items-center gap-3",children:[l("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:l("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),l("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),l("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:l("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})})})]}),y("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",$,"px"]})]})]})}import{useCallback as ft,useContext as ht,useLayoutEffect as wt,useMemo as vt,useRef as We}from"react";import{createContext as mt}from"react";var _=mt(null);import{Fragment as _e,jsx as te}from"react/jsx-runtime";var yt="waniwani:send-follow-up:advanced:",xt=1e4;function Ae(e){return`${yt}${e??"default"}`}function bt(e){try{let t=globalThis.localStorage?.getItem(Ae(e));if(!t)return null;let n=JSON.parse(t);return typeof n?.at!="number"||typeof n?.byMountId!="string"?null:n}catch{return null}}function kt(e,t){try{globalThis.localStorage?.setItem(Ae(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Ct(){return ne()?window.openai:null}function Mt(){return wt(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),i=t.getAttribute("style"),r="margin:0!important;padding:0!important;border:0!important;background:transparent!important;background-color:transparent!important;height:0!important;min-height:0!important;max-height:0!important;overflow:hidden!important;";return e.setAttribute("style",r),t.setAttribute("style",r),()=>{n===null?e.removeAttribute("style"):e.setAttribute("style",n),i===null?t.removeAttribute("style"):t.setAttribute("style",i)}},[]),null}function oe(e){let t=ht(_),n=We(e);n.current=e;let i=t?.getToolResponseMetadata?.()??null,r=Ct()?.toolResponseMetadata??null,u=i??r,f=u&&typeof u.viewUUID=="string"?u.viewUUID:void 0,h=We("");h.current===""&&(h.current=crypto.randomUUID());let p=ft((c,s)=>{ne()&&kt(f,h.current);try{Promise.resolve(n.current(c)).catch(o=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",o)})}catch(o){console.error("[unstable_useSendFollowUpWithGhostGuard]",o)}},[f]),g=vt(()=>{let c=h.current;return function({children:o}){if(!ne())return te(_e,{children:o});let a=bt(f);return a&&a.byMountId!==c&&Date.now()-a.at<xt?te(Mt,{}):te(_e,{children:o})}},[f]);return{sendFollowUp:p,Guard:g}}import{useCallback as Et}from"react";import K,{useCallback as Ie,useContext as St,useEffect as Ue,useState as re,useSyncExternalStore as Tt}from"react";async function Oe(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-TZIOCMXP.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-OFYMQOI3.js");return new n}}function ie({children:e,loading:t=null,onError:n}){let[i,r]=re(null),[u,f]=re(null),[h,p]=re(!0);return Ue(()=>{let g=!0,c=null;async function s(){try{let o=await Oe();await o.connect(),g?(c=o,r(o),p(!1)):o.close()}catch(o){g&&(console.error("error",o),f(o instanceof Error?o:new Error(String(o))),p(!1))}}return s(),()=>{g=!1,c?.close()}},[]),Ue(()=>{if(!i)return;let g=c=>{document.documentElement.classList.toggle("dark",c==="dark"),document.documentElement.style.colorScheme=c==="dark"?"dark":"auto"};return g(i.getTheme()),i.onThemeChange(g)},[i]),u&&n?K.createElement(K.Fragment,null,n(u)):h||!i?K.createElement(K.Fragment,null,t):K.createElement(_.Provider,{value:i},e)}function v(e){let t=St(_);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Ie(u=>e==="toolOutput"?t.onToolResult(()=>u()):e==="theme"?t.onThemeChange(()=>u()):e==="displayMode"?t.onDisplayModeChange(()=>u()):e==="safeArea"?t.onSafeAreaChange(()=>u()):e==="maxHeight"?t.onMaxHeightChange(()=>u()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>u()):e==="widgetState"?t.onWidgetStateChange(()=>u()):()=>{},[t,e]),i=Ie(()=>e==="toolOutput"?t.getToolOutput():e==="theme"?t.getTheme():e==="displayMode"?t.getDisplayMode():e==="locale"?t.getLocale():e==="safeArea"?t.getSafeArea():e==="maxHeight"?t.getMaxHeight():e==="toolResponseMetadata"?t.getToolResponseMetadata():e==="widgetState"?t.getWidgetState():null,[t,e]),r=Tt(n,i,i);return e?r:t}function se(){let e=v();return Et((t,n)=>e.callTool(t,n),[e])}function ae(){return v("displayMode")}function z(){return v("toolOutput")}function le(){return{data:z()}}import{useSyncExternalStore as Rt}from"react";function de(){return Rt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return v("locale")}function ce(){return v("maxHeight")}import{useCallback as Wt}from"react";function pe(){let e=v();return Wt(t=>e.openExternal(t),[e])}import{useCallback as _t}from"react";function ge(){let e=v();return _t(t=>e.requestDisplayMode(t),[e])}function me(){return v("safeArea")}import{useCallback as At}from"react";function fe(){let e=v();return At((t,n)=>{(async()=>{Me(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(i=>{console.error("Failed to send follow-up message:",i)})},[e])}function he(){return v("theme")}function we(){return v("toolResponseMetadata")}import{useCallback as Ot}from"react";function ve(){let e=v();return Ot(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as It,useEffect as Ut,useState as Nt}from"react";function ye(e){let t=v("widgetState"),[n,i]=Nt(()=>t??(typeof e=="function"?e():e??null));Ut(()=>{i(t)},[t]);let r=It(u=>{i(f=>{let h=typeof u=="function"?u(f):u;return V()==="openai"&&h!=null&&window.openai?.setWidgetState(h),h})},[]);return[n,r]}import{jsx as A,jsxs as Ne}from"react/jsx-runtime";var Le=()=>Ne("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Ne("div",{className:"flex gap-2",children:[A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),A("p",{className:"text-sm font-medium text-transparent bg-clip-text bg-gradient-to-r from-slate-400 via-slate-200 to-slate-400 bg-[length:200%_100%] animate-[shimmer_1.5s_ease-in-out_infinite]",children:"Loading widget..."}),A("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:A("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),A("style",{children:`
63
63
  @keyframes shimmer {
64
64
  0% { background-position: 200% 0; }
65
65
  100% { background-position: -200% 0; }
66
66
  }
67
- `})]});import{useContext as Pt,useEffect as ke,useMemo as Ht,useRef as Be,useState as je}from"react";function Lt(){return crypto.randomUUID()}function M(e,t,n){return{event_id:Lt(),event_type:t,timestamp:new Date().toISOString(),source:e.source??"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function xe(e){let t=e.trim().split(/\s+/),n=t[0]||"",i={};for(let r=1;r<t.length;r++){let u=t[r].indexOf(":");if(u===-1)continue;let f=t[r].slice(0,u),w=t[r].slice(u+1),p=Number(w);i[f]=Number.isFinite(p)&&w!==""?p:w}return{name:n,props:i}}function Pe(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function He(e,t){let n=[],i=typeof navigator<"u"?navigator:void 0,r=i&&"connection"in i?i.connection:void 0;t([M(e,"widget_render",{metadata:{viewport_width:window.innerWidth,viewport_height:window.innerHeight,device_pixel_ratio:window.devicePixelRatio??1,touch_support:"ontouchstart"in window?1:0,connection_type:r?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let u=s=>{t([M(e,"widget_error",{metadata:{error_message:s.message,error_stack:(s.error?.stack??"").slice(0,1024),error_source:s.filename??"unknown"}})])};window.addEventListener("error",u),n.push(()=>window.removeEventListener("error",u));let f=s=>{let o=s.reason,l=o instanceof Error?o.message:String(o),m=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:l,error_stack:m,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",f),n.push(()=>window.removeEventListener("unhandledrejection",f)),e.capture?.click){let s=o=>{let l=o.target,m=l?.closest?.("[data-ww-conversion],[data-ww-step]");if(m){let d=m.getAttribute("data-ww-conversion")??m.getAttribute("data-ww-step")??"";if(xe(d).name)return}t([M(e,"widget_click",{metadata:{target_tag:l?.tagName?.toLowerCase()??"unknown",target_id:l?.id||void 0,target_class:l?.className||void 0,click_x:o.clientX,click_y:o.clientY}})])};document.addEventListener("click",s,{capture:!0}),n.push(()=>document.removeEventListener("click",s,{capture:!0}))}let w=s=>{let l=s.target?.closest?.("[data-ww-conversion]");if(!l)return;let{name:m,props:d}=xe(l.getAttribute("data-ww-conversion")||"");m&&t([M(e,"conversion",{event_name:m,metadata:Object.keys(d).length>0?d:void 0})])};document.addEventListener("click",w,{capture:!0}),n.push(()=>document.removeEventListener("click",w,{capture:!0}));let p=0,g=s=>{let l=s.target?.closest?.("[data-ww-step]");if(!l)return;let{name:m,props:d}=xe(l.getAttribute("data-ww-step")||"");m&&(p++,t([M(e,"step",{event_name:m,step_sequence:p,metadata:Object.keys(d).length>0?d:void 0})]))};document.addEventListener("click",g,{capture:!0}),n.push(()=>document.removeEventListener("click",g,{capture:!0}));let c=s=>{let o=s.target?.closest?.("a");if(!o)return;let l=o.getAttribute("href")??"",m=l.startsWith("http")&&!l.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:l,link_text:(o.textContent??"").slice(0,200),is_external:m}})])};if(document.addEventListener("click",c,{capture:!0}),n.push(()=>document.removeEventListener("click",c,{capture:!0})),e.capture?.scroll){let s=null,o=window.scrollY||0,l=()=>{s||(s=setTimeout(()=>{s=null;let m=window.scrollY||document.documentElement.scrollTop,d=document.documentElement.scrollHeight-document.documentElement.clientHeight,x=d>0?Math.round(m/d*100):0,b=m>=o?"down":"up";o=m,t([M(e,"widget_scroll",{metadata:{scroll_depth_pct:x,scroll_direction:b,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",l,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",l),s&&clearTimeout(s)})}if(e.capture?.formField){let s=new WeakMap,o=m=>{let d=m.target;!d||!Pe(d)||s.set(d,Date.now())},l=m=>{let d=m.target;if(!d||!Pe(d))return;let x=s.get(d),b=x?Date.now()-x:0,E=d;t([M(e,"widget_form_field",{metadata:{field_name:E.name||E.id||void 0,field_type:E.type||d.tagName.toLowerCase(),time_in_field_ms:b,filled:!!E.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",l,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",l,{capture:!0})})}if(e.capture?.formSubmit){let s=new WeakMap,o=m=>{let x=m.target?.closest?.("form");x&&!s.has(x)&&s.set(x,Date.now())};document.addEventListener("focusin",o,{capture:!0}),n.push(()=>document.removeEventListener("focusin",o,{capture:!0}));let l=m=>{let d=m.target,x=d?s.get(d):void 0,b=0;if(d){let E=d.querySelectorAll("input, textarea, select");for(let P of E){let O=P;(O.validity&&!O.validity.valid||O.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:d?.id||void 0,time_to_submit_ms:x?Date.now()-x:void 0,validation_errors:b}})])};document.addEventListener("submit",l,{capture:!0}),n.push(()=>document.removeEventListener("submit",l,{capture:!0}))}return()=>{for(let s of n)s()}}var Dt="@waniwani/sdk";function Ft(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,i={};e.session_id&&(i.sessionId=e.session_id),e.trace_id&&(i.traceId=e.trace_id),e.user_id&&(i.externalUserId=e.user_id);let r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:i,properties:r,metadata:{}}}function be(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:Dt,version:"0.1.0"},events:e.map(Ft)})}var X=class{buffer=[];timer=null;flushing=!1;pendingFlush=!1;stopped=!1;config;teardownVisibility=null;teardownPagehide=null;constructor(t){this.config=t,this.start(),this.registerTeardown()}send(t){if(!this.stopped){if(this.buffer.push(...t),this.buffer.length>200){let n=this.buffer.length-200;this.buffer.splice(0,n)}this.buffer.length>=20&&this.flush().catch(()=>{})}}async flush(){if(!(this.stopped||this.buffer.length===0)){if(this.flushing){this.pendingFlush=!0;return}this.flushing=!0;try{let t=this.buffer.splice(0,20);await this.sendBatch(t)}finally{this.flushing=!1,this.pendingFlush&&this.buffer.length>0&&!this.stopped&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null),typeof document<"u"&&this.teardownVisibility&&(document.removeEventListener("visibilitychange",this.teardownVisibility),this.teardownVisibility=null),typeof window<"u"&&this.teardownPagehide&&(window.removeEventListener("pagehide",this.teardownPagehide),this.teardownPagehide=null)}beaconFlush(){if(this.buffer.length===0)return;let t=[...this.buffer];this.buffer.length=0;let n={"Content-Type":"application/json"};if(this.config.token&&(n.Authorization=`Bearer ${this.config.token}`),typeof fetch<"u"){this.sendKeepAliveChunked(this.config.endpoint,t,n);return}typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendBeaconChunked(this.config.endpoint,t)}sendKeepAliveChunked(t,n,i){let r=be(n);if(r.length<=6e4){fetch(t,{method:"POST",headers:i,body:r,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let u=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,u),i),this.sendKeepAliveChunked(t,n.slice(u),i)}sendBeaconChunked(t,n){let i=be(n);if(i.length<=6e4){navigator.sendBeacon(t,new Blob([i],{type:"application/json"}));return}if(n.length<=1)return;let r=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,r)),this.sendBeaconChunked(t,n.slice(r))}start(){this.timer||(this.timer=setInterval(()=>{this.flush().catch(()=>{})},5e3))}registerTeardown(){typeof document>"u"||(this.teardownVisibility=()=>{document.visibilityState==="hidden"&&this.beaconFlush()},this.teardownPagehide=()=>{this.beaconFlush()},document.addEventListener("visibilitychange",this.teardownVisibility),window.addEventListener("pagehide",this.teardownPagehide))}async sendBatch(t){let n=be(t),i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);for(let r=0;r<=3;r++)try{let u=await fetch(this.config.endpoint,{method:"POST",headers:i,body:n});if(u.status===200||u.status===207)return;if(u.status===401){this.stopped=!0;return}if(u.status>=500&&r<3){await this.delay(1e3*2**r);continue}if(u.status===429&&r<3){let f=u.headers.get("Retry-After"),w=f?Number(f):NaN,p=Number.isFinite(w)?w*1e3:1e3*2**r;await this.delay(p);continue}return}catch{if(r<3){await this.delay(1e3*2**r);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var Ce={identify(){},step(){},track(){},conversion(){}},S=null,Y=0;function Bt(){return crypto.randomUUID()}function I(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Gt(){return{widget:Ce,cleanup:()=>{},config:null,captureKey:""}}function Ke(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Ge(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,r=I(i?.endpoint);return r?{endpoint:r,token:I(i?.token),sessionId:I(i?.sessionId),source:I(i?.source)}:null}function ze(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function jt(e){let[t,n]=je(()=>Ge(e));return ke(()=>{if(!e){n(r=>r===null?r:null);return}let i=()=>{let r=Ge(e);n(u=>ze(u,r)?u:r)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function Kt(e,t,n){let i=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),u=new X({endpoint:e.endpoint,token:e.token,metadata:t}),f,w=0,p=o=>{u.send(o)},g=e.source??"widget",c=He({sessionId:i,traceId:r,metadata:t,source:g,capture:n},p);function s(o,l){return{event_id:Bt(),event_type:o,timestamp:new Date().toISOString(),source:g,session_id:i,trace_id:r,user_id:f,...l}}return{captureKey:Ke(n),widget:{identify(o,l){f=o,p([s("identify",{user_id:o,user_traits:l})])},step(o,l){w++,p([s("step",{event_name:o,step_sequence:w,metadata:l})])},track(o,l){p([s("track",{event_name:o,metadata:l})])},conversion(o,l){p([s("conversion",{event_name:o,metadata:l})])}},cleanup:()=>{c(),u.stop()},config:e}}function Je(e={}){let t=Pt(_),n=jt(t),i=I(e.endpoint),r=I(e.token),u=I(e.sessionId),f=Ht(()=>i?{endpoint:i,token:r??n?.token,sessionId:u??n?.sessionId,source:n?.source}:n,[i,r,u,n]),[w,p]=je(Ce),g=Be(e.metadata);g.current=e.metadata;let c=Be(e.capture);c.current=e.capture;let s=Ke(e.capture);return ke(()=>(Y++,()=>{Y=Math.max(Y-1,0),Y===0&&(S?.cleanup(),S=null)}),[]),ke(()=>{if(!(typeof window>"u")){if(!f){S?.config&&(S.cleanup(),S=Gt(),p(Ce));return}(!ze(S?.config,f)||S?.captureKey!==s)&&(S?.cleanup(),S=Kt(f,g.current,c.current),p(S.widget))}},[f,s]),w}export{ee as DevModeProvider,Ee as InitializeNextJsInIframe,Fe as LoadingWidget,ie as WidgetProvider,V as detectPlatform,j as getMockState,U as initializeMockOpenAI,Se as isMCPApps,Me as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,L as updateMockDisplayMode,R as updateMockGlobal,D as updateMockTheme,N as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,ge as useRequestDisplayMode,me as useSafeArea,fe as useSendFollowUp,he as useTheme,z as useToolOutput,we as useToolResponseMetadata,ve as useUpdateModelContext,Je as useWaniwani,v as useWidgetClient,ye as useWidgetState};
67
+ `})]});import{useContext as Pt,useEffect as Ge,useMemo as Ht,useRef as Pe,useState as je}from"react";function Lt(){return crypto.randomUUID()}function M(e,t,n){return{event_id:Lt(),event_type:t,timestamp:new Date().toISOString(),source:e.source,session_id:e.sessionId,trace_id:e.traceId,...n}}function xe(e){let t=e.trim().split(/\s+/),n=t[0]||"",i={};for(let r=1;r<t.length;r++){let u=t[r].indexOf(":");if(u===-1)continue;let f=t[r].slice(0,u),h=t[r].slice(u+1),p=Number(h);i[f]=Number.isFinite(p)&&h!==""?p:h}return{name:n,props:i}}function De(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function Fe(e,t){let n=[],i=typeof navigator<"u"?navigator:void 0,r=i&&"connection"in i?i.connection:void 0;t([M(e,"widget_render",{metadata:{viewport_width:window.innerWidth,viewport_height:window.innerHeight,device_pixel_ratio:window.devicePixelRatio??1,touch_support:"ontouchstart"in window?1:0,connection_type:r?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let u=s=>{t([M(e,"widget_error",{metadata:{error_message:s.message,error_stack:(s.error?.stack??"").slice(0,1024),error_source:s.filename??"unknown"}})])};window.addEventListener("error",u),n.push(()=>window.removeEventListener("error",u));let f=s=>{let o=s.reason,a=o instanceof Error?o.message:String(o),m=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:a,error_stack:m,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",f),n.push(()=>window.removeEventListener("unhandledrejection",f)),e.capture?.click){let s=o=>{let a=o.target,m=a?.closest?.("[data-ww-conversion],[data-ww-step]");if(m){let d=m.getAttribute("data-ww-conversion")??m.getAttribute("data-ww-step")??"";if(xe(d).name)return}t([M(e,"widget_click",{metadata:{target_tag:a?.tagName?.toLowerCase()??"unknown",target_id:a?.id||void 0,target_class:a?.className||void 0,click_x:o.clientX,click_y:o.clientY}})])};document.addEventListener("click",s,{capture:!0}),n.push(()=>document.removeEventListener("click",s,{capture:!0}))}let h=s=>{let a=s.target?.closest?.("[data-ww-conversion]");if(!a)return;let{name:m,props:d}=xe(a.getAttribute("data-ww-conversion")||"");m&&t([M(e,"conversion",{event_name:m,metadata:Object.keys(d).length>0?d:void 0})])};document.addEventListener("click",h,{capture:!0}),n.push(()=>document.removeEventListener("click",h,{capture:!0}));let p=0,g=s=>{let a=s.target?.closest?.("[data-ww-step]");if(!a)return;let{name:m,props:d}=xe(a.getAttribute("data-ww-step")||"");m&&(p++,t([M(e,"step",{event_name:m,step_sequence:p,metadata:Object.keys(d).length>0?d:void 0})]))};document.addEventListener("click",g,{capture:!0}),n.push(()=>document.removeEventListener("click",g,{capture:!0}));let c=s=>{let o=s.target?.closest?.("a");if(!o)return;let a=o.getAttribute("href")??"",m=a.startsWith("http")&&!a.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:a,link_text:(o.textContent??"").slice(0,200),is_external:m}})])};if(document.addEventListener("click",c,{capture:!0}),n.push(()=>document.removeEventListener("click",c,{capture:!0})),e.capture?.scroll){let s=null,o=window.scrollY||0,a=()=>{s||(s=setTimeout(()=>{s=null;let m=window.scrollY||document.documentElement.scrollTop,d=document.documentElement.scrollHeight-document.documentElement.clientHeight,x=d>0?Math.round(m/d*100):0,b=m>=o?"down":"up";o=m,t([M(e,"widget_scroll",{metadata:{scroll_depth_pct:x,scroll_direction:b,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",a,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",a),s&&clearTimeout(s)})}if(e.capture?.formField){let s=new WeakMap,o=m=>{let d=m.target;!d||!De(d)||s.set(d,Date.now())},a=m=>{let d=m.target;if(!d||!De(d))return;let x=s.get(d),b=x?Date.now()-x:0,T=d;t([M(e,"widget_form_field",{metadata:{field_name:T.name||T.id||void 0,field_type:T.type||d.tagName.toLowerCase(),time_in_field_ms:b,filled:!!T.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",a,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",a,{capture:!0})})}if(e.capture?.formSubmit){let s=new WeakMap,o=m=>{let x=m.target?.closest?.("form");x&&!s.has(x)&&s.set(x,Date.now())};document.addEventListener("focusin",o,{capture:!0}),n.push(()=>document.removeEventListener("focusin",o,{capture:!0}));let a=m=>{let d=m.target,x=d?s.get(d):void 0,b=0;if(d){let T=d.querySelectorAll("input, textarea, select");for(let P of T){let I=P;(I.validity&&!I.validity.valid||I.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:d?.id||void 0,time_to_submit_ms:x?Date.now()-x:void 0,validation_errors:b}})])};document.addEventListener("submit",a,{capture:!0}),n.push(()=>document.removeEventListener("submit",a,{capture:!0}))}return()=>{for(let s of n)s()}}var Dt="@waniwani/sdk";function Ft(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,i={};e.session_id&&(i.sessionId=e.session_id),e.trace_id&&(i.traceId=e.trace_id),e.user_id&&(i.externalUserId=e.user_id);let r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source,timestamp:e.timestamp,correlation:i,properties:r,metadata:{}}}function be(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:Dt,version:"0.1.0"},events:e.map(Ft)})}var X=class{buffer=[];timer=null;flushing=!1;pendingFlush=!1;stopped=!1;config;teardownVisibility=null;teardownPagehide=null;constructor(t){this.config=t,this.start(),this.registerTeardown()}send(t){if(!this.stopped){if(this.buffer.push(...t),this.buffer.length>200){let n=this.buffer.length-200;this.buffer.splice(0,n)}this.buffer.length>=20&&this.flush().catch(()=>{})}}async flush(){if(!(this.stopped||this.buffer.length===0)){if(this.flushing){this.pendingFlush=!0;return}this.flushing=!0;try{let t=this.buffer.splice(0,20);await this.sendBatch(t)}finally{this.flushing=!1,this.pendingFlush&&this.buffer.length>0&&!this.stopped&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null),typeof document<"u"&&this.teardownVisibility&&(document.removeEventListener("visibilitychange",this.teardownVisibility),this.teardownVisibility=null),typeof window<"u"&&this.teardownPagehide&&(window.removeEventListener("pagehide",this.teardownPagehide),this.teardownPagehide=null)}beaconFlush(){if(this.buffer.length===0)return;let t=[...this.buffer];this.buffer.length=0;let n={"Content-Type":"application/json"};if(this.config.token&&(n.Authorization=`Bearer ${this.config.token}`),typeof fetch<"u"){this.sendKeepAliveChunked(this.config.endpoint,t,n);return}typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendBeaconChunked(this.config.endpoint,t)}sendKeepAliveChunked(t,n,i){let r=be(n);if(r.length<=6e4){fetch(t,{method:"POST",headers:i,body:r,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let u=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,u),i),this.sendKeepAliveChunked(t,n.slice(u),i)}sendBeaconChunked(t,n){let i=be(n);if(i.length<=6e4){navigator.sendBeacon(t,new Blob([i],{type:"application/json"}));return}if(n.length<=1)return;let r=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,r)),this.sendBeaconChunked(t,n.slice(r))}start(){this.timer||(this.timer=setInterval(()=>{this.flush().catch(()=>{})},5e3))}registerTeardown(){typeof document>"u"||(this.teardownVisibility=()=>{document.visibilityState==="hidden"&&this.beaconFlush()},this.teardownPagehide=()=>{this.beaconFlush()},document.addEventListener("visibilitychange",this.teardownVisibility),window.addEventListener("pagehide",this.teardownPagehide))}async sendBatch(t){let n=be(t),i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);for(let r=0;r<=3;r++)try{let u=await fetch(this.config.endpoint,{method:"POST",headers:i,body:n});if(u.status===200||u.status===207)return;if(u.status===401){this.stopped=!0;return}if(u.status>=500&&r<3){await this.delay(1e3*2**r);continue}if(u.status===429&&r<3){let f=u.headers.get("Retry-After"),h=f?Number(f):NaN,p=Number.isFinite(h)?h*1e3:1e3*2**r;await this.delay(p);continue}return}catch{if(r<3){await this.delay(1e3*2**r);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var He={identify(){},step(){},track(){},conversion(){}},O=null,Y=0;function Bt(){return crypto.randomUUID()}function R(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Ke(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Be(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,r=R(i?.endpoint);return r?{endpoint:r,token:R(i?.token),sessionId:R(i?.sessionId),source:R(i?.source)}:null}function ze(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function Gt(e){let[t,n]=je(()=>Be(e));return Ge(()=>{if(!e){n(r=>r===null?r:null);return}let i=()=>{let r=Be(e);n(u=>ze(u,r)?u:r)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function jt(e,t,n){let i=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),u=new X({endpoint:e.endpoint,token:e.token,metadata:t}),f,h=0,p=o=>{u.send(o)},g=e.source,c=Fe({sessionId:i,traceId:r,metadata:t,source:g,capture:n},p);function s(o,a){return{event_id:Bt(),event_type:o,timestamp:new Date().toISOString(),source:g,session_id:i,trace_id:r,user_id:f,...a}}return{captureKey:Ke(n),widget:{identify(o,a){f=o,p([s("identify",{user_id:o,user_traits:a})])},step(o,a){h++,p([s("step",{event_name:o,step_sequence:h,metadata:a})])},track(o,a){p([s("track",{event_name:o,metadata:a})])},conversion(o,a){p([s("conversion",{event_name:o,metadata:a})])}},cleanup:()=>{c(),u.stop()},config:e}}function Je(e={}){let t=Pt(_),n=Gt(t),i=R(e.endpoint),r=R(e.token),u=R(e.sessionId),f=R(e.source),h=Ht(()=>{let a=f??n?.source;return a?i?{endpoint:i,token:r??n?.token,sessionId:u??n?.sessionId,source:a}:n?{...n,source:a}:null:null},[i,r,u,f,n]),[p,g]=je(He),c=Pe(e.metadata);c.current=e.metadata;let s=Pe(e.capture);s.current=e.capture;let o=Ke(e.capture);return Ge(()=>{if(!(typeof window>"u")){if(!h){g(He);return}return(!ze(O?.config,h)||O?.captureKey!==o)&&(O?.cleanup(),O=jt(h,c.current,s.current)),g(O.widget),Y++,()=>{Y=Math.max(Y-1,0),Y===0&&(O?.cleanup(),O=null)}}},[h,o]),p}export{ee as DevModeProvider,Se as InitializeNextJsInIframe,Le as LoadingWidget,ie as WidgetProvider,V as detectPlatform,j as getMockState,U as initializeMockOpenAI,Ce as isMCPApps,ke as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,L as updateMockDisplayMode,E as updateMockGlobal,D as updateMockTheme,N as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,ge as useRequestDisplayMode,me as useSafeArea,fe as useSendFollowUp,he as useTheme,z as useToolOutput,we as useToolResponseMetadata,ve as useUpdateModelContext,Je as useWaniwani,v as useWidgetClient,ye as useWidgetState};
68
68
  //# sourceMappingURL=react.js.map