@waniwani/sdk 0.15.2 → 0.17.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.
package/dist/mcp/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
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=`
2
+ import{a as K,b as Te,c as Me}from"../chunk-DP6SAQTK.js";import{b as _,c as Ie}from"../chunk-RZKVTH7F.js";import{Fragment as dt,jsx as P,jsxs as ut}from"react/jsx-runtime";function at(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(u=>{u.forEach(p=>{if(p.type==="attributes"&&p.target===n){let a=p.attributeName;a&&a!=="suppresshydrationwarning"&&a!=="lang"&&a!=="class"&&a!=="style"&&n.removeAttribute(a)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let r=history.replaceState.bind(history);history.replaceState=(u,p,a)=>{try{let f=new URL(String(a??""),window.location.href);r(null,p,f.pathname+f.search+f.hash)}catch{}};let i=history.pushState.bind(history);history.pushState=(u,p,a)=>{try{let f=new URL(String(a??""),window.location.href);i(null,p,f.pathname+f.search+f.hash)}catch{}};let d=new URL(e).origin,c=window.self!==window.top;if(window.addEventListener("click",u=>{let p=u?.target?.closest("a");if(!p||!p.href)return;let a=new URL(p.href,window.location.href);if(a.origin!==window.location.origin&&a.origin!==d)try{window.openai&&(window.openai?.openExternal({href:p.href}),u.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),c&&window.location.origin!==d){let u=window.fetch;window.fetch=((l,v)=>{let y=typeof l=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(l)&&!l.startsWith("//"),w;if(typeof l=="string"||l instanceof URL?w=new URL(l,window.location.href):w=new URL(l.url,window.location.href),w.origin===d)return typeof l=="string"||l instanceof URL?l=w.toString():l=new Request(w.toString(),l),u.call(window,l,{...v,mode:"cors"});if(t.indexOf(w.origin)!==-1)return u.call(window,l,v);if(y&&w.origin===window.location.origin){let T=new URL(e);return T.pathname=w.pathname,T.search=w.search,T.hash=w.hash,w=T,l=w.toString(),u.call(window,l,{...v,mode:"cors"})}return u.call(window,l,v)});let p=d.replace(/^http/,"ws"),a=window.WebSocket,f=((l,v)=>{let y=new URL(String(l),window.location.href);if(y.origin===window.location.origin||y.origin===window.location.origin.replace(/^http/,"ws")){let w=new URL(p);return w.pathname=y.pathname,w.search=y.search,w.hash=y.hash,new a(w.toString(),v)}return new a(l,v)});f.prototype=a.prototype,Object.assign(f,{CONNECTING:a.CONNECTING,OPEN:a.OPEN,CLOSING:a.CLOSING,CLOSED:a.CLOSED}),window.WebSocket=f}}var lt=`(${at.toString()})()`;function Ce({baseUrl:e,passthroughOrigins:t}){return ut(dt,{children:[P("base",{href:e}),P("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),P("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),P("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),P("script",{children:lt})]})}import{useCallback as S,useEffect as D,useRef as Z,useState as k}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},L={...Re};function U(e){typeof window>"u"||window.openai||(L={...Re,toolOutput:e??null},window.openai={...L,requestDisplayMode:async({mode:t})=>(M("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=>{M("widgetState",t)}},window.dispatchEvent(new _({globals:L})))}function M(e,t){typeof window>"u"||!window.openai||(L[e]=t,window.openai[e]=t,window.dispatchEvent(new _({globals:{[e]:t}})))}function B(){return{...L}}function O(e){M("toolOutput",e)}function A(e){M("displayMode",e)}function W(e){M("theme",e)}import{Fragment as Q,jsx as s,jsxs as h}from"react/jsx-runtime";var q=150;function Ee({className:e}){return h("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[s("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),s("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function ct({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s("path",{d:"M18 6L6 18M6 6l12 12"})})}function pt({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:s("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function ft({className:e}){return h("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[s("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),s("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function gt({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:s("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 mt({className:e}){return h("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[s("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),s("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 ht({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:s("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 wt({className:e}){return h("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[s("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"}),s("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var yt=`
3
3
  @keyframes devPanelSlideIn {
4
4
  0% {
5
5
  opacity: 0;
@@ -47,22 +47,22 @@ import{a as V,b as ke,c as Ce}from"../chunk-DP6SAQTK.js";import{b as H,c as Me}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:[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:`
50
+ `;function ee({defaultProps:e,widgetPaths:t,children:n}){let[o,r]=k(!1),[i,d]=k(!1);return D(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){r(!0);return}if(t&&t.length>0){let u=window.location.pathname,p=t.some(a=>u===a||u.startsWith(`${a}/`));d(p),p&&U(e)}else U(e),d(!0);r(!0)},[e,t]),o?i?h(Q,{children:[s(vt,{children:n}),s(xt,{defaultProps:e})]}):s(Q,{children:n}):null}function vt({children:e}){return s("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:s("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 Ue({options:e,value:t,onChange:n}){let o=e.findIndex(r=>r.value===t);return h("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:[s("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(${o*100}% + ${o*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(r=>h("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,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 O=S(()=>{f(!0),requestAnimationFrame(()=>{n(!0)})},[]),W=S(()=>{r(!0),n(!1),setTimeout(()=>{f(!1),r(!1)},150)},[]),q=S(()=>{t?W():O()},[t,O,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:`
54
+ `,children:[r.icon,s("span",{className:"capitalize",children:r.label})]},r.value))]})}function xt({defaultProps:e}){let[t,n]=k(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[o,r]=k(!1),[i,d]=k(t),[c,u]=k("inline"),[p,a]=k("dark"),[f,l]=k(!1),[v,y]=k(()=>JSON.stringify(e??{},null,2)),[w,T]=k(null),N=Z(null),Qe=Z(null),J=Z(null);D(()=>{let g=B();u(g.displayMode),a(g.theme)},[]),D(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:f?q:0,left:0,right:0}},window.dispatchEvent(new _({globals:{safeArea:window.openai.safeArea}})))},[f]),D(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let Se=S(()=>{d(!0),requestAnimationFrame(()=>{n(!0)})},[]),C=S(()=>{r(!0),n(!1),setTimeout(()=>{d(!1),r(!1)},150)},[]),X=S(()=>{t?C():Se()},[t,Se,C]);D(()=>{let g=b=>{(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key==="d"&&(b.preventDefault(),X()),b.key==="Escape"&&t&&C()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,X,C]),D(()=>{if(!t)return;let g=b=>{J.current&&!J.current.contains(b.target)&&C()};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[t,C]);let et=S(g=>{u(g),A(g)},[]),tt=S(g=>{a(g),W(g)},[]),V=S(g=>{try{let b=JSON.parse(g);T(null),O(b)}catch{T("Invalid JSON")}},[]),nt=S(g=>{y(g),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{V(g)},500)},[V]),ot=S(()=>{N.current&&clearTimeout(N.current),V(v)},[V,v]),rt=S(()=>{let g=JSON.stringify(e??{},null,2);y(g),T(null),O(e??{}),u("inline"),A("inline"),a("dark"),W("dark")},[e]),it=[{value:"inline",label:"inline",icon:s(pt,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:s(ft,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:s(gt,{className:"w-3.5 h-3.5"})}],st=[{value:"light",label:"light",icon:s(mt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:s(ht,{className:"w-3.5 h-3.5"})}];return h(Q,{children:[s("style",{dangerouslySetInnerHTML:{__html:yt}}),h("div",{ref:J,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[h("button",{type:"button",onClick:X,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:[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:`
58
+ `},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[s(Ee,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),s("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%)"}})]}),i&&h("div",{ref:Qe,className:`absolute bottom-14 right-0 w-80 ${t&&!o?"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:[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 Oe,useContext as St,useEffect as Ue,useState as re,useSyncExternalStore as Tt}from"react";async function Ie(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-PUBKF5TI.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-WEXKWHUI.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 Ie();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=Oe(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=Oe(()=>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 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 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:`
62
+ `},children:[h("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[h("div",{className:"flex items-center gap-2",children:[s(Ee,{className:"w-4 h-4 text-gray-400"}),s("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),h("div",{className:"flex items-center gap-2",children:[s("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"}),s("button",{type:"button",onClick:C,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:s(ct,{className:"w-4 h-4"})})]})]}),h("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[h("div",{children:[s("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),s(Ue,{options:it,value:c,onChange:et})]}),h("div",{children:[s("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),s(Ue,{options:st,value:p,onChange:tt})]}),h("div",{children:[s("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),h("button",{type:"button",onClick:()=>l(!f),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${f?"text-emerald-400":"text-gray-400"}`,style:{background:f?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:f?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[s("span",{children:"Mock ChatGPT Input Bar"}),s("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${f?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:f?"ON":"OFF"})]}),f&&h("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",q,"px"]})]}),h("div",{children:[s("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),s("textarea",{value:v,onChange:g=>nt(g.target.value),onBlur:ot,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:w?"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:g=>{w||(g.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:g=>{w||(g.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),w&&h("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[s("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:s("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),w]})]}),h("button",{type:"button",onClick:rt,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:g=>{g.currentTarget.style.background="rgba(255, 255, 255, 0.08)",g.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:g=>{g.currentTarget.style.background="rgba(255, 255, 255, 0.04)",g.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[s(wt,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),f&&h("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${q}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[h("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:[s("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:s("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),s("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),s("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:s("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s("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"})})})]}),h("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",q,"px"]})]})]})}import{useCallback as kt,useContext as St,useLayoutEffect as Tt,useMemo as Mt,useRef as Oe}from"react";import{createContext as bt}from"react";var H=bt(null);import{Fragment as Ae,jsx as te}from"react/jsx-runtime";var It="waniwani:send-follow-up:advanced:",Ct=1e4;function We(e){return`${It}${e??"default"}`}function Rt(e){try{let t=globalThis.localStorage?.getItem(We(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 Et(e,t){try{globalThis.localStorage?.setItem(We(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Ut(){return ne()?window.openai:null}function Ot(){return Tt(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),o=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),o===null?t.removeAttribute("style"):t.setAttribute("style",o)}},[]),null}function oe(e){let t=St(H),n=Oe(e);n.current=e;let o=t?.getToolResponseMetadata?.()??null,r=Ut()?.toolResponseMetadata??null,i=o??r,d=i&&typeof i.viewUUID=="string"?i.viewUUID:void 0,c=Oe("");c.current===""&&(c.current=crypto.randomUUID());let u=kt((a,f)=>{ne()&&Et(d,c.current);try{Promise.resolve(n.current(a)).catch(l=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",l)})}catch(l){console.error("[unstable_useSendFollowUpWithGhostGuard]",l)}},[d]),p=Mt(()=>{let a=c.current;return function({children:l}){if(!ne())return te(Ae,{children:l});let v=Rt(d);return v&&v.byMountId!==a&&Date.now()-v.at<Ct?te(Ot,{}):te(Ae,{children:l})}},[d]);return{sendFollowUp:u,Guard:p}}import{useCallback as Dt}from"react";import j,{useCallback as Fe,useContext as At,useEffect as Ne,useState as re,useSyncExternalStore as Wt}from"react";async function De(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-PUBKF5TI.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-WEXKWHUI.js");return new n}}function ie({children:e,loading:t=null,onError:n}){let[o,r]=re(null),[i,d]=re(null),[c,u]=re(!0);return Ne(()=>{let p=!0,a=null;async function f(){try{let l=await De();await l.connect(),p?(a=l,r(l),u(!1)):l.close()}catch(l){p&&(console.error("error",l),d(l instanceof Error?l:new Error(String(l))),u(!1))}}return f(),()=>{p=!1,a?.close()}},[]),Ne(()=>{if(!o)return;let p=a=>{document.documentElement.classList.toggle("dark",a==="dark"),document.documentElement.style.colorScheme=a==="dark"?"dark":"auto"};return p(o.getTheme()),o.onThemeChange(p)},[o]),i&&n?j.createElement(j.Fragment,null,n(i)):c||!o?j.createElement(j.Fragment,null,t):j.createElement(H.Provider,{value:o},e)}function m(e){let t=At(H);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Fe(i=>e==="toolOutput"?t.onToolResult(()=>i()):e==="theme"?t.onThemeChange(()=>i()):e==="displayMode"?t.onDisplayModeChange(()=>i()):e==="safeArea"?t.onSafeAreaChange(()=>i()):e==="maxHeight"?t.onMaxHeightChange(()=>i()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>i()):e==="widgetState"?t.onWidgetStateChange(()=>i()):()=>{},[t,e]),o=Fe(()=>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=Wt(n,o,o);return e?r:t}function se(){let e=m();return Dt((t,n)=>e.callTool(t,n),[e])}function ae(){return m("displayMode")}function G(){return m("toolOutput")}function le(){return{data:G()}}import{useSyncExternalStore as Ft}from"react";function de(){return Ft(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return m("locale")}function ce(){return m("maxHeight")}import{useCallback as Nt}from"react";function pe(){let e=m();return Nt(t=>e.openExternal(t),[e])}import{useCallback as _t}from"react";function fe(){let e=m();return _t(t=>e.requestDisplayMode(t),[e])}function ge(){return m("safeArea")}import{useCallback as Pt}from"react";function me(){let e=m();return Pt((t,n)=>{(async()=>{Ie(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(o=>{console.error("Failed to send follow-up message:",o)})},[e])}function he(){return m("theme")}function we(){return m("toolResponseMetadata")}import{useCallback as Lt}from"react";function ye(){let e=m();return Lt(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as Bt,useEffect as Ht,useState as jt}from"react";function ve(e){let t=m("widgetState"),[n,o]=jt(()=>t??(typeof e=="function"?e():e??null));Ht(()=>{o(t)},[t]);let r=Bt(i=>{o(d=>{let c=typeof i=="function"?i(d):i;return K()==="openai"&&c!=null&&window.openai?.setWidgetState(c),c})},[]);return[n,r]}import{jsx as R,jsxs as _e}from"react/jsx-runtime";var Pe=()=>_e("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[_e("div",{className:"flex gap-2",children:[R("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),R("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),R("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),R("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..."}),R("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:R("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),R("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 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 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",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={sessionId:void 0,identify(){},step(){},track(){},conversion(){}},I=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:{sessionId:i,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(I?.config,h)||I?.captureKey!==o)&&(I?.cleanup(),I=jt(h,c.current,s.current)),g(I.widget),Y++,()=>{Y=Math.max(Y-1,0),Y===0&&(I?.cleanup(),I=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};
67
+ `})]});import{useEffect as fn,useMemo as gn,useRef as mn,useState as hn}from"react";function F(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.length>0)return o}}var Gt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Vt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Kt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],qt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],zt=["waniwani/visitorId","visitorId"],Yt=["correlationId","openai/requestId"];var xe="waniwani/widget";function Le(e){return e?F(e,Gt):void 0}function Be(e){return e?F(e,Vt):void 0}function He(e){return e?F(e,Kt):void 0}function je(e){return e?F(e,qt):void 0}function Ge(e){return e?F(e,zt):void 0}function Ve(e){return e?F(e,Yt):void 0}var $t=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Jt=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function Ke(e,t){if(e){let o=e["waniwani/source"];if(typeof o=="string"&&o.length>0)return o;for(let{key:r,source:i}of $t){let d=e[r];if(typeof d=="string"&&d.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let o=n.toLowerCase();for(let{needle:r,source:i}of Jt)if(o.includes(r))return i}}var Xt="@waniwani/sdk";function qe(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??Zt,r=tn(e),i=z(e.meta),d=z(e.metadata),c=nn(e,i),u=x(e.eventId)??o(),p=on(e.timestamp,n),a=x(e.source)??Ke(i)??t.source??Xt,f=be(e)?{...e}:void 0,l={...d};return Object.keys(i).length>0&&(l.meta=i),f&&(l.rawLegacy=f),{id:u,type:"mcp.event",name:r,source:a,timestamp:p,correlation:c,properties:Qt(e,r),metadata:l,rawLegacy:f}}function Zt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Qt(e,t){if(!be(e))return z(e.properties);let n=en(e,t),o=z(e.properties);return{...n,...o}}function en(e,t){switch(t){case"tool.called":{let n={};return x(e.toolName)&&(n.name=e.toolName),x(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),x(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return x(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),x(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function tn(e){return be(e)?e.eventType:e.event}function nn(e,t){let n=x(e.requestId)??Be(t),o=x(e.sessionId)??Le(t),r=x(e.traceId)??He(t),i=x(e.externalUserId)??je(t),d=x(e.visitorId)??Ge(t),c=x(e.correlationId)??Ve(t)??n,u={};return o&&(u.sessionId=o),r&&(u.traceId=r),n&&(u.requestId=n),c&&(u.correlationId=c),i&&(u.externalUserId=i),d&&(u.visitorId=d),u}function on(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function z(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function x(e){if(typeof e=="string"&&e.trim().length!==0)return e}function be(e){return"eventType"in e}function ze(e){return{priceShown:({amount:t,currency:n,itemId:o,label:r,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:o,label:r},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:o,...r})=>e({event:"option_selected",properties:{id:t,amount:n,currency:o},...r}),leadQualified:t=>{let{externalId:n,email:o,name:r,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:o,name:r},...i})},converted:({amount:t,currency:n,occurredAt:o,...r})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:o},...r})}}var rn="/api/mcp/events/v2/batch";var Ye="@waniwani/sdk";var sn=new Set([401,403]),an=new Set([408,425,429,500,502,503,504]);function $e(e){return new ke(e)}var ke=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=un(t.apiUrl,t.endpointPath??rn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(o=>setTimeout(o,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let o=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,o)),this.sendKeepaliveChunk(t.slice(o));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":Ye};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:cn(i)}}if(sn.has(n.status))return{kind:"auth",status:n.status};if(an.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await dn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:Ye,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(d=>[d.id,d])),r=[],i=[];for(let d of n){let c=o.get(d.eventId);if(c){if(ln(d)){r.push(c);continue}i.push(c)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function ln(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function dn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function un(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function cn(e){return e instanceof Error?e.message:String(e)}function Je(e){let{apiUrl:t,endpointPath:n}=pn(e.endpoint),o=$e({apiUrl:t,apiKey:e.token,endpointPath:n,flushIntervalMs:e.flushIntervalMs}),r,i=c=>typeof c=="function"?c():c,d=async c=>{let u=e.identity?.()??{},p=i(e.channelId),a=p===void 0?c.properties:{channelId:p,...c.properties},f=qe({sessionId:u.sessionId,visitorId:u.visitorId,externalUserId:u.externalUserId??r,traceId:u.traceId,...c,properties:a,metadata:{...e.metadata,...c.metadata}},{source:i(e.source)});return o.enqueue(f),{eventId:f.id}};return{track:Object.assign(d,ze(d)),identify(c,u){return r=c,d({event:"user.identified",externalUserId:c,properties:u})},flush:()=>o.flush(),shutdown:c=>o.shutdown(c)}}function pn(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}var E=async()=>({eventId:""});function wn(){return Object.assign(E,{priceShown:E,pricesCompared:E,optionSelected:E,leadQualified:E,converted:E})}var Xe={sessionId:void 0,track:wn(),identify:E,flush:async()=>{}},Y=null,$=0;function I(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function yn(e){if(!e)return null;let t=e._meta,n=e[xe]??t?.[xe],o=I(n?.endpoint);return o?{endpoint:o,token:I(n?.token),sessionId:I(n?.sessionId),source:I(n?.source)}:null}function vn(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function xn(e,t){let n=e.sessionId??crypto.randomUUID(),o=crypto.randomUUID(),r=Je({endpoint:e.endpoint,token:e.token,source:e.source,identity:()=>({sessionId:n,traceId:o}),metadata:t});return r.track({event:"widget_render"}),{config:e,widget:{sessionId:n,track:r.track,identify:(i,d)=>r.identify(i,d),flush:()=>r.flush()},cleanup:()=>{r.shutdown()}}}function Ze(e={}){let t=I(e.endpoint),n=I(e.token),o=I(e.sessionId),r=I(e.source),i=t?null:yn(e.toolResponseMetadata??null),d=i?.endpoint,c=i?.token,u=i?.sessionId,p=i?.source,a=gn(()=>{let y=r??p;return y?t?{endpoint:t,token:n,sessionId:o,source:y}:d?{endpoint:d,token:n??c,sessionId:o??u,source:y}:null:null},[t,n,o,r,d,c,u,p]),[f,l]=hn(Xe),v=mn(e.metadata);return v.current=e.metadata,fn(()=>{if(typeof window>"u")return;if(!a){l(Xe);return}let y=Y;return(!y||!vn(y.config,a))&&(y?.cleanup(),y=xn(a,v.current),Y=y),l(y.widget),$++,()=>{$=Math.max($-1,0),$===0&&(Y?.cleanup(),Y=null)}},[a]),f}export{ee as DevModeProvider,Ce as InitializeNextJsInIframe,Pe as LoadingWidget,ie as WidgetProvider,K as detectPlatform,B as getMockState,U as initializeMockOpenAI,Me as isMCPApps,Te as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,A as updateMockDisplayMode,M as updateMockGlobal,W as updateMockTheme,O as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,fe as useRequestDisplayMode,ge as useSafeArea,me as useSendFollowUp,he as useTheme,G as useToolOutput,we as useToolResponseMetadata,ye as useUpdateModelContext,Ze as useWaniwani,m as useWidgetClient,ve as useWidgetState};
68
68
  //# sourceMappingURL=react.js.map