@waniwani/sdk 0.2.2-beta.3 → 0.2.2

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.
@@ -272,32 +272,27 @@ declare function useDisplayMode(): DisplayMode;
272
272
 
273
273
  /** Return type of the useFlowAction hook */
274
274
  type FlowActionResult<T> = {
275
- /** Current widget data. Initially from useToolOutput, then updated inline on same-widget transitions. */
275
+ /** Sub-widget identifier only set in container mode (from __widgetId in structuredContent). */
276
+ widgetId: string | null;
277
+ /** Current widget data. */
276
278
  data: T | null;
277
- /** Advance the flow with the user's answer. Optionally include `stateUpdates` to update any flow field at this step. */
278
- advance: (value: string, followUpText?: string, stateUpdates?: Record<string, unknown>) => void;
279
- /** True while a callTool request is in flight. */
280
- isAdvancing: boolean;
281
279
  };
282
280
  /**
283
- * Hook for advancing a flow directly from a widget, bypassing the chat
284
- * composer on MCP Apps (Claude). On OpenAI, delegates to sendFollowUp.
285
- *
286
- * Replaces the combination of `useToolOutput` + `useSendFollowUp` in flow widgets.
287
- *
288
- * @param resourceId - The resource ID of the current widget (e.g., "option_picker").
289
- * Used to detect same-widget transitions for inline re-rendering.
281
+ * Hook for reading flow widget data. Extracts `__widgetId` from
282
+ * structuredContent when using the container widget pattern.
290
283
  *
291
284
  * @example
292
285
  * ```tsx
293
- * const { data, advance, isAdvancing } = useFlowAction<OptionPickerProps>("option_picker");
294
- * // On click:
295
- * advance(option.id, option.label);
296
- * // With extra cross-field updates:
297
- * // advance(option.id, option.label, { role: "CTO" });
286
+ * const { widgetId, data } = useFlowAction<MyData>();
287
+ * if (!widgetId || !data) return null;
288
+ *
289
+ * switch (widgetId) {
290
+ * case "pricing_table": return <PricingTable {...data} />;
291
+ * default: return null;
292
+ * }
298
293
  * ```
299
294
  */
300
- declare function useFlowAction<T extends Record<string, unknown>>(resourceId: string): FlowActionResult<T>;
295
+ declare function useFlowAction<T extends Record<string, unknown>>(): FlowActionResult<T>;
301
296
 
302
297
  /**
303
298
  * Check if running in ChatGPT app (OpenAI-only).
package/dist/mcp/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import{a as Y}from"../chunk-DGSC74SV.js";import{b as P}from"../chunk-ZUGQBRJF.js";import{Fragment as Ke,jsx as $,jsxs as ze}from"react/jsx-runtime";function je({baseUrl:e}){return ze(Ke,{children:[$("base",{href:e}),$("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),$("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),$("script",{children:"("+(()=>{let t=window.innerBaseUrl,n=document.documentElement;new MutationObserver(p=>{p.forEach(s=>{if(s.type==="attributes"&&s.target===n){let d=s.attributeName;d&&d!=="suppresshydrationwarning"&&d!=="class"&&d!=="style"&&n.removeAttribute(d)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let o=history.replaceState;history.replaceState=(p,s,d)=>{let l=new URL(d??"",window.location.href),h=l.pathname+l.search+l.hash;o.call(history,s,h)};let a=history.pushState;history.pushState=(p,s,d)=>{let l=new URL(d??"",window.location.href),h=l.pathname+l.search+l.hash;a.call(history,s,h)};let f=new URL(t).origin,m=window.self!==window.top;if(window.addEventListener("click",p=>{let s=p?.target?.closest("a");if(!s||!s.href)return;let d=new URL(s.href,window.location.href);if(d.origin!==window.location.origin&&d.origin!==f)try{window.openai&&(window.openai?.openExternal({href:s.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),m&&window.location.origin!==f){let p=window.fetch;window.fetch=(s,d)=>{let l;if(typeof s=="string"||s instanceof URL?l=new URL(s,window.location.href):l=new URL(s.url,window.location.href),l.origin===f)return typeof s=="string"||s instanceof URL?s=l.toString():s=new Request(l.toString(),s),p.call(window,s,{...d,mode:"cors"});if(l.origin===window.location.origin){let h=new URL(t);return h.pathname=l.pathname,h.search=l.search,h.hash=l.hash,l=h,typeof s=="string"||s instanceof URL?s=l.toString():s=new Request(l.toString(),s),p.call(window,s,{...d,mode:"cors"})}return p.call(window,s,d)}}}).toString()+")()"})]})}import{useCallback as _,useEffect as O,useRef as ne,useState as S}from"react";var le={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},B={...le};function j(e){typeof window>"u"||window.openai||(B={...le,toolOutput:e??null},window.openai={...B,requestDisplayMode:async({mode:t})=>(I("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=>{I("widgetState",t)}},window.dispatchEvent(new P({globals:B})))}function I(e,t){typeof window>"u"||!window.openai||(B[e]=t,window.openai[e]=t,window.dispatchEvent(new P({globals:{[e]:t}})))}function X(){return{...B}}function K(e){I("toolOutput",e)}function z(e){I("displayMode",e)}function G(e){I("theme",e)}import{Fragment as oe,jsx as r,jsxs as v}from"react/jsx-runtime";var J=150;function de({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[r("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),r("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function Ge({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M18 6L6 18M6 6l12 12"})})}function Ve({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:r("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function Ye({className:e}){return v("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[r("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),r("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function $e({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:r("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 Xe({className:e}){return v("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[r("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),r("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 Je({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:r("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 qe({className:e}){return v("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[r("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"}),r("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var Ze=`
2
+ import{a as ae}from"../chunk-DGSC74SV.js";import{b as P}from"../chunk-ZUGQBRJF.js";import{Fragment as Be,jsx as Y,jsxs as je}from"react/jsx-runtime";function Pe({baseUrl:e}){return je(Be,{children:[Y("base",{href:e}),Y("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),Y("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),Y("script",{children:"("+(()=>{let t=window.innerBaseUrl,n=document.documentElement;new MutationObserver(p=>{p.forEach(s=>{if(s.type==="attributes"&&s.target===n){let d=s.attributeName;d&&d!=="suppresshydrationwarning"&&d!=="class"&&d!=="style"&&n.removeAttribute(d)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let o=history.replaceState;history.replaceState=(p,s,d)=>{let l=new URL(d??"",window.location.href),h=l.pathname+l.search+l.hash;o.call(history,s,h)};let a=history.pushState;history.pushState=(p,s,d)=>{let l=new URL(d??"",window.location.href),h=l.pathname+l.search+l.hash;a.call(history,s,h)};let m=new URL(t).origin,f=window.self!==window.top;if(window.addEventListener("click",p=>{let s=p?.target?.closest("a");if(!s||!s.href)return;let d=new URL(s.href,window.location.href);if(d.origin!==window.location.origin&&d.origin!==m)try{window.openai&&(window.openai?.openExternal({href:s.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),f&&window.location.origin!==m){let p=window.fetch;window.fetch=(s,d)=>{let l;if(typeof s=="string"||s instanceof URL?l=new URL(s,window.location.href):l=new URL(s.url,window.location.href),l.origin===m)return typeof s=="string"||s instanceof URL?s=l.toString():s=new Request(l.toString(),s),p.call(window,s,{...d,mode:"cors"});if(l.origin===window.location.origin){let h=new URL(t);return h.pathname=l.pathname,h.search=l.search,h.hash=l.hash,l=h,typeof s=="string"||s instanceof URL?s=l.toString():s=new Request(l.toString(),s),p.call(window,s,{...d,mode:"cors"})}return p.call(window,s,d)}}}).toString()+")()"})]})}import{useCallback as T,useEffect as L,useRef as te,useState as M}from"react";var le={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},B={...le};function j(e){typeof window>"u"||window.openai||(B={...le,toolOutput:e??null},window.openai={...B,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 P({globals:B})))}function R(e,t){typeof window>"u"||!window.openai||(B[e]=t,window.openai[e]=t,window.dispatchEvent(new P({globals:{[e]:t}})))}function $(){return{...B}}function K(e){R("toolOutput",e)}function z(e){R("displayMode",e)}function G(e){R("theme",e)}import{Fragment as ne,jsx as r,jsxs as w}from"react/jsx-runtime";var X=150;function de({className:e}){return w("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[r("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),r("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function Ke({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M18 6L6 18M6 6l12 12"})})}function ze({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:r("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function Ge({className:e}){return w("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[r("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),r("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function Ve({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:r("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 Ye({className:e}){return w("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[r("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),r("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 $e({className:e}){return r("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:r("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 Xe({className:e}){return w("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[r("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"}),r("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var Je=`
3
3
  @keyframes devPanelSlideIn {
4
4
  0% {
5
5
  opacity: 0;
@@ -47,22 +47,22 @@ import{a as Y}from"../chunk-DGSC74SV.js";import{b as P}from"../chunk-ZUGQBRJF.js
47
47
  .dev-json-editor::-webkit-scrollbar-thumb:hover {
48
48
  background: rgba(255, 255, 255, 0.15);
49
49
  }
50
- `;function ue({defaultProps:e,widgetPaths:t,children:n}){let[i,o]=S(!1),[a,f]=S(!1);return O(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){o(!0);return}if(t&&t.length>0){let p=window.location.pathname,s=t.some(d=>p===d||p.startsWith(`${d}/`));f(s),s&&j(e)}else j(e),f(!0);o(!0)},[e,t]),i?a?v(oe,{children:[r(Qe,{children:n}),r(et,{defaultProps:e})]}):r(oe,{children:n}):null}function Qe({children:e}){return r("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:r("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 ce({options:e,value:t,onChange:n}){let i=e.findIndex(o=>o.value===t);return v("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:[r("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(o=>v("button",{type:"button",onClick:()=>n(o.value),className:`
50
+ `;function ue({defaultProps:e,widgetPaths:t,children:n}){let[i,o]=M(!1),[a,m]=M(!1);return L(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){o(!0);return}if(t&&t.length>0){let p=window.location.pathname,s=t.some(d=>p===d||p.startsWith(`${d}/`));m(s),s&&j(e)}else j(e),m(!0);o(!0)},[e,t]),i?a?w(ne,{children:[r(qe,{children:n}),r(Ze,{defaultProps:e})]}):r(ne,{children:n}):null}function qe({children:e}){return r("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:r("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 ce({options:e,value:t,onChange:n}){let i=e.findIndex(o=>o.value===t);return w("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:[r("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(o=>w("button",{type:"button",onClick:()=>n(o.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===o.value?"text-white":"text-gray-400 hover:text-gray-300"}
54
- `,children:[o.icon,r("span",{className:"capitalize",children:o.label})]},o.value))]})}function et({defaultProps:e}){let[t,n]=S(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[i,o]=S(!1),[a,f]=S(t),[m,p]=S("inline"),[s,d]=S("dark"),[l,h]=S(!1),[A,R]=S(()=>JSON.stringify(e??{},null,2)),[k,C]=S(null),M=ne(null),F=ne(null),L=ne(null);O(()=>{let g=X();p(g.displayMode),d(g.theme)},[]),O(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:l?J:0,left:0,right:0}},window.dispatchEvent(new P({globals:{safeArea:window.openai.safeArea}})))},[l]),O(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let U=_(()=>{f(!0),requestAnimationFrame(()=>{n(!0)})},[]),u=_(()=>{o(!0),n(!1),setTimeout(()=>{f(!1),o(!1)},150)},[]),c=_(()=>{t?u():U()},[t,U,u]);O(()=>{let g=T=>{(T.metaKey||T.ctrlKey)&&T.shiftKey&&T.key==="d"&&(T.preventDefault(),c()),T.key==="Escape"&&t&&u()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,c,u]),O(()=>{if(!t)return;let g=T=>{L.current&&!L.current.contains(T.target)&&u()};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[t,u]);let x=_(g=>{p(g),z(g)},[]),y=_(g=>{d(g),G(g)},[]),b=_(g=>{try{let T=JSON.parse(g);C(null),K(T)}catch{C("Invalid JSON")}},[]),te=_(g=>{R(g),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{b(g)},500)},[b]),H=_(()=>{M.current&&clearTimeout(M.current),b(A)},[b,A]),He=_(()=>{let g=JSON.stringify(e??{},null,2);R(g),C(null),K(e??{}),p("inline"),z("inline"),d("dark"),G("dark")},[e]),Pe=[{value:"inline",label:"inline",icon:r(Ve,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:r(Ye,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:r($e,{className:"w-3.5 h-3.5"})}],Be=[{value:"light",label:"light",icon:r(Xe,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:r(Je,{className:"w-3.5 h-3.5"})}];return v(oe,{children:[r("style",{dangerouslySetInnerHTML:{__html:Ze}}),v("div",{ref:L,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[v("button",{type:"button",onClick:c,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:[o.icon,r("span",{className:"capitalize",children:o.label})]},o.value))]})}function Ze({defaultProps:e}){let[t,n]=M(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[i,o]=M(!1),[a,m]=M(t),[f,p]=M("inline"),[s,d]=M("dark"),[l,h]=M(!1),[A,D]=M(()=>JSON.stringify(e??{},null,2)),[E,I]=M(null),_=te(null),F=te(null),N=te(null);L(()=>{let g=$();p(g.displayMode),d(g.theme)},[]),L(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:l?X:0,left:0,right:0}},window.dispatchEvent(new P({globals:{safeArea:window.openai.safeArea}})))},[l]),L(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let U=T(()=>{m(!0),requestAnimationFrame(()=>{n(!0)})},[]),u=T(()=>{o(!0),n(!1),setTimeout(()=>{m(!1),o(!1)},150)},[]),c=T(()=>{t?u():U()},[t,U,u]);L(()=>{let g=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="d"&&(k.preventDefault(),c()),k.key==="Escape"&&t&&u()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,c,u]),L(()=>{if(!t)return;let g=k=>{N.current&&!N.current.contains(k.target)&&u()};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[t,u]);let x=T(g=>{p(g),z(g)},[]),y=T(g=>{d(g),G(g)},[]),b=T(g=>{try{let k=JSON.parse(g);I(null),K(k)}catch{I("Invalid JSON")}},[]),ee=T(g=>{D(g),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{b(g)},500)},[b]),H=T(()=>{_.current&&clearTimeout(_.current),b(A)},[b,A]),Fe=T(()=>{let g=JSON.stringify(e??{},null,2);D(g),I(null),K(e??{}),p("inline"),z("inline"),d("dark"),G("dark")},[e]),Ue=[{value:"inline",label:"inline",icon:r(ze,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:r(Ge,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:r(Ve,{className:"w-3.5 h-3.5"})}],He=[{value:"light",label:"light",icon:r(Ye,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:r($e,{className:"w-3.5 h-3.5"})}];return w(ne,{children:[r("style",{dangerouslySetInnerHTML:{__html:Je}}),w("div",{ref:N,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[w("button",{type:"button",onClick:c,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:[r(de,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),r("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%)"}})]}),a&&v("div",{ref:F,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:[r(de,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),r("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%)"}})]}),a&&w("div",{ref:F,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:[v("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[v("div",{className:"flex items-center gap-2",children:[r(de,{className:"w-4 h-4 text-gray-400"}),r("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),v("div",{className:"flex items-center gap-2",children:[r("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"}),r("button",{type:"button",onClick:u,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:r(Ge,{className:"w-4 h-4"})})]})]}),v("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[v("div",{children:[r("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),r(ce,{options:Pe,value:m,onChange:x})]}),v("div",{children:[r("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),r(ce,{options:Be,value:s,onChange:y})]}),v("div",{children:[r("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),v("button",{type:"button",onClick:()=>h(!l),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${l?"text-emerald-400":"text-gray-400"}`,style:{background:l?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:l?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[r("span",{children:"Mock ChatGPT Input Bar"}),r("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${l?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:l?"ON":"OFF"})]}),l&&v("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",J,"px"]})]}),v("div",{children:[r("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),r("textarea",{value:A,onChange:g=>te(g.target.value),onBlur:H,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:k?"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=>{k||(g.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:g=>{k||(g.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),k&&v("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[r("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:r("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),k]})]}),v("button",{type:"button",onClick:He,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:[r(qe,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),l&&v("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${J}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[v("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:[r("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:r("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),r("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),r("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:r("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r("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"})})})]}),v("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",J,"px"]})]})]})}import{useCallback as it}from"react";import V,{createContext as tt,useCallback as ge,useContext as nt,useEffect as fe,useState as ie,useSyncExternalStore as ot}from"react";async function pe(){let{detectPlatform:e}=await import("../platform-GKYYQBCS.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-HLQSYZJC.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-6WEBHSGH.js");return new n}}var q=tt(null);function me({children:e,loading:t=null,onError:n}){let[i,o]=ie(null),[a,f]=ie(null),[m,p]=ie(!0);return fe(()=>{let s=!0,d=null;async function l(){try{let h=await pe();await h.connect(),s?(d=h,o(h),p(!1)):h.close()}catch(h){s&&(console.error("error",h),f(h instanceof Error?h:new Error(String(h))),p(!1))}}return l(),()=>{s=!1,d?.close()}},[]),fe(()=>{if(!i)return;let s=d=>{document.documentElement.classList.toggle("dark",d==="dark"),document.documentElement.style.colorScheme=d==="dark"?"dark":"auto"};return s(i.getTheme()),i.onThemeChange(s)},[i]),a&&n?V.createElement(V.Fragment,null,n(a)):m||!i?V.createElement(V.Fragment,null,t):V.createElement(q.Provider,{value:i},e)}function w(e){let t=nt(q);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=ge(a=>e==="toolOutput"?t.onToolResult(()=>a()):e==="theme"?t.onThemeChange(()=>a()):e==="displayMode"?t.onDisplayModeChange(()=>a()):e==="safeArea"?t.onSafeAreaChange(()=>a()):e==="maxHeight"?t.onMaxHeightChange(()=>a()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>a()):e==="widgetState"?t.onWidgetStateChange(()=>a()):()=>{},[t,e]),i=ge(()=>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]),o=ot(n,i,i);return e?o:t}function he(){let e=w();return it((t,n)=>e.callTool(t,n),[e])}function we(){return w("displayMode")}import{useCallback as rt,useRef as st,useState as ve}from"react";function Z(){return w("toolOutput")}function at(e){let t=xe(e);return!t?.flowToken||!t?.flowId?null:{flowId:t.flowId,flowToken:t.flowToken}}function xe(e){let t=(e.content??[]).filter(n=>n.type==="text").map(n=>n.text).join("").trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}function ye(e){let t=w(),n=Z(),[i,o]=ve(null),[a,f]=ve(!1),m=st(null),p=rt(async(d,l,h)=>{if(Y()==="openai"){t.sendFollowUp(l??d);return}let R=m.current;if(R){f(!0);try{let k=await t.callTool(R.flowId,{action:"continue",flowToken:R.flowToken,stateUpdates:{...h??{}}}),C=xe(k);if(!C)return;let M=at(k);M&&(m.current=M),C.status==="widget"&&k.structuredContent&&(!C.widgetId||C.widgetId===e)&&o(k.structuredContent)}catch(k){console.error("useFlowAction: callTool failed",k)}finally{f(!1)}}},[t,e]);return{data:i??n,advance:p,isAdvancing:a}}import{useSyncExternalStore as lt}from"react";function be(){return lt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ke(){return w("locale")}function Ce(){return w("maxHeight")}import{useCallback as dt}from"react";function Me(){let e=w();return dt(t=>e.openExternal(t),[e])}import{useCallback as ct}from"react";function Te(){let e=w();return ct(t=>e.requestDisplayMode(t),[e])}function Se(){return w("safeArea")}import{useCallback as ut}from"react";function Ee(){let e=w();return ut(t=>e.sendFollowUp(t),[e])}function Re(){return w("theme")}function _e(){return w("toolResponseMetadata")}import{useContext as mt,useEffect as se,useMemo as ht,useRef as wt,useState as Le}from"react";function pt(){return crypto.randomUUID()}function E(e,t,n){return{event_id:pt(),event_type:t,timestamp:new Date().toISOString(),source:"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function We(e){let t=e.trim().split(/\s+/),n=t[0]||"",i={};for(let o=1;o<t.length;o++){let a=t[o].indexOf(":");if(a===-1)continue;let f=t[o].slice(0,a),m=t[o].slice(a+1),p=Number(m);i[f]=Number.isFinite(p)&&m!==""?p:m}return{name:n,props:i}}function Ae(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function Ie(e,t){let n=[],i=typeof navigator<"u"?navigator:void 0,o=i&&"connection"in i?i.connection:void 0;t([E(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:o?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let a=u=>{t([E(e,"widget_error",{metadata:{error_message:u.message,error_stack:(u.error?.stack??"").slice(0,1024),error_source:u.filename??"unknown"}})])};window.addEventListener("error",a),n.push(()=>window.removeEventListener("error",a));let f=u=>{let c=u.reason,x=c instanceof Error?c.message:String(c),y=c instanceof Error?(c.stack??"").slice(0,1024):"";t([E(e,"widget_error",{metadata:{error_message:x,error_stack:y,error_source:"unhandledrejection"}})])};window.addEventListener("unhandledrejection",f),n.push(()=>window.removeEventListener("unhandledrejection",f));let m=u=>{let c=u.target;t([E(e,"widget_click",{metadata:{target_tag:c?.tagName?.toLowerCase()??"unknown",target_id:c?.id||void 0,target_class:c?.className||void 0,click_x:u.clientX,click_y:u.clientY}})])};document.addEventListener("click",m,{capture:!0}),n.push(()=>document.removeEventListener("click",m,{capture:!0}));let p=u=>{let x=u.target?.closest?.("[data-ww-conversion]");if(!x)return;let{name:y,props:b}=We(x.getAttribute("data-ww-conversion")||"");y&&t([E(e,"conversion",{event_name:y,metadata:Object.keys(b).length>0?b:void 0})])};document.addEventListener("click",p,{capture:!0}),n.push(()=>document.removeEventListener("click",p,{capture:!0}));let s=0,d=u=>{let x=u.target?.closest?.("[data-ww-step]");if(!x)return;let{name:y,props:b}=We(x.getAttribute("data-ww-step")||"");y&&(s++,t([E(e,"step",{event_name:y,step_sequence:s,metadata:Object.keys(b).length>0?b:void 0})]))};document.addEventListener("click",d,{capture:!0}),n.push(()=>document.removeEventListener("click",d,{capture:!0}));let l=u=>{let c=u.target?.closest?.("a");if(!c)return;let x=c.getAttribute("href")??"",y=x.startsWith("http")&&!x.startsWith(window.location.origin);t([E(e,"widget_link_click",{metadata:{href:x,link_text:(c.textContent??"").slice(0,200),is_external:y}})])};document.addEventListener("click",l,{capture:!0}),n.push(()=>document.removeEventListener("click",l,{capture:!0}));let h=null,A=window.scrollY||0,R=()=>{h||(h=setTimeout(()=>{h=null;let u=window.scrollY||document.documentElement.scrollTop,c=document.documentElement.scrollHeight-document.documentElement.clientHeight,x=c>0?Math.round(u/c*100):0,y=u>=A?"down":"up";A=u,t([E(e,"widget_scroll",{metadata:{scroll_depth_pct:x,scroll_direction:y,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",R,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",R),h&&clearTimeout(h)});let k=new WeakMap,C=u=>{let c=u.target;!c||!Ae(c)||k.set(c,Date.now())},M=u=>{let c=u.target;if(!c||!Ae(c))return;let x=k.get(c),y=x?Date.now()-x:0,b=c;t([E(e,"widget_form_field",{metadata:{field_name:b.name||b.id||void 0,field_type:b.type||c.tagName.toLowerCase(),time_in_field_ms:y,filled:!!b.value}})])};document.addEventListener("focusin",C,{capture:!0}),document.addEventListener("focusout",M,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",C,{capture:!0}),document.removeEventListener("focusout",M,{capture:!0})});let F=new WeakMap,L=u=>{let x=u.target?.closest?.("form");x&&!F.has(x)&&F.set(x,Date.now())};document.addEventListener("focusin",L,{capture:!0}),n.push(()=>document.removeEventListener("focusin",L,{capture:!0}));let U=u=>{let c=u.target,x=c?F.get(c):void 0,y=0;if(c){let b=c.querySelectorAll("input, textarea, select");for(let te of b){let H=te;(H.validity&&!H.validity.valid||H.getAttribute("aria-invalid")==="true")&&y++}}t([E(e,"widget_form_submit",{metadata:{form_id:c?.id||void 0,time_to_submit_ms:x?Date.now()-x:void 0,validation_errors:y}})])};return document.addEventListener("submit",U,{capture:!0}),n.push(()=>document.removeEventListener("submit",U,{capture:!0})),()=>{for(let u of n)u()}}var gt="@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 o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:i,properties:o,metadata:{}}}function re(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:gt,version:"0.1.0"},events:e.map(ft)})}var Q=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 o=re(n);if(o.length<=6e4){fetch(t,{method:"POST",headers:i,body:o,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let a=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,a),i),this.sendKeepAliveChunked(t,n.slice(a),i)}sendBeaconChunked(t,n){let i=re(n);if(i.length<=6e4){navigator.sendBeacon(t,new Blob([i],{type:"application/json"}));return}if(n.length<=1)return;let o=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,o)),this.sendBeaconChunked(t,n.slice(o))}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=re(t),i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);for(let o=0;o<=3;o++)try{let a=await fetch(this.config.endpoint,{method:"POST",headers:i,body:n});if(a.status===200||a.status===207)return;if(a.status===401){this.stopped=!0;return}if(a.status>=500&&o<3){await this.delay(1e3*2**o);continue}if(a.status===429&&o<3){let f=a.headers.get("Retry-After"),m=f?Number(f):NaN,p=Number.isFinite(m)?m*1e3:1e3*2**o;await this.delay(p);continue}return}catch{if(o<3){await this.delay(1e3*2**o);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var ae={identify(){},step(){},track(){},conversion(){}},W=null,ee=0;function vt(){return crypto.randomUUID()}function D(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function xt(){return{widget:ae,cleanup:()=>{},config:null}}function Ne(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,o=D(i?.endpoint);return o?{endpoint:o,token:D(i?.token),sessionId:D(i?.sessionId)}:null}function Oe(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId}function yt(e){let[t,n]=Le(()=>Ne(e));return se(()=>{if(!e){n(o=>o===null?o:null);return}let i=()=>{let o=Ne(e);n(a=>Oe(a,o)?a:o)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function bt(e,t){let n=e.sessionId??crypto.randomUUID(),i=crypto.randomUUID(),o=new Q({endpoint:e.endpoint,token:e.token,metadata:t}),a,f=0,m=d=>{o.send(d)},p=Ie({sessionId:n,traceId:i,metadata:t},m);function s(d,l){return{event_id:vt(),event_type:d,timestamp:new Date().toISOString(),source:"widget",session_id:n,trace_id:i,user_id:a,...l}}return{widget:{identify(d,l){a=d,m([s("identify",{user_id:d,user_traits:l})])},step(d,l){f++,m([s("step",{event_name:d,step_sequence:f,metadata:l})])},track(d,l){m([s("track",{event_name:d,metadata:l})])},conversion(d,l){m([s("conversion",{event_name:d,metadata:l})])}},cleanup:()=>{p(),o.stop()},config:e}}function De(e={}){let t=mt(q),n=yt(t),i=D(e.endpoint),o=D(e.token),a=D(e.sessionId),f=ht(()=>i?{endpoint:i,token:o??n?.token,sessionId:a??n?.sessionId}:n,[i,o,a,n]),[m,p]=Le(ae),s=wt(e.metadata);return s.current=e.metadata,se(()=>(ee++,()=>{ee=Math.max(ee-1,0),ee===0&&(W?.cleanup(),W=null)}),[]),se(()=>{if(!(typeof window>"u")){if(!f){W?.config&&(W.cleanup(),W=xt(),p(ae));return}Oe(W?.config,f)||(W?.cleanup(),W=bt(f,s.current),p(W.widget))}},[f]),m}import{useCallback as kt,useEffect as Ct,useState as Mt}from"react";function Fe(e){let t=w("widgetState"),[n,i]=Mt(()=>t??(typeof e=="function"?e():e??null));Ct(()=>{i(t)},[t]);let o=kt(a=>{i(f=>{let m=typeof a=="function"?a(f):a;return Y()==="openai"&&m!=null&&window.openai?.setWidgetState(m),m})},[]);return[n,o]}import{jsx as N,jsxs as Ue}from"react/jsx-runtime";var Tt=()=>Ue("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Ue("div",{className:"flex gap-2",children:[N("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),N("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),N("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),N("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..."}),N("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:N("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),N("style",{children:`
62
+ `},children:[w("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[w("div",{className:"flex items-center gap-2",children:[r(de,{className:"w-4 h-4 text-gray-400"}),r("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),w("div",{className:"flex items-center gap-2",children:[r("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"}),r("button",{type:"button",onClick:u,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:r(Ke,{className:"w-4 h-4"})})]})]}),w("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[w("div",{children:[r("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),r(ce,{options:Ue,value:f,onChange:x})]}),w("div",{children:[r("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),r(ce,{options:He,value:s,onChange:y})]}),w("div",{children:[r("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),w("button",{type:"button",onClick:()=>h(!l),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${l?"text-emerald-400":"text-gray-400"}`,style:{background:l?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:l?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[r("span",{children:"Mock ChatGPT Input Bar"}),r("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${l?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:l?"ON":"OFF"})]}),l&&w("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",X,"px"]})]}),w("div",{children:[r("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),r("textarea",{value:A,onChange:g=>ee(g.target.value),onBlur:H,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:E?"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=>{E||(g.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:g=>{E||(g.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),E&&w("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[r("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:r("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),E]})]}),w("button",{type:"button",onClick:Fe,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:[r(Xe,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),l&&w("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${X}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[w("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:[r("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:r("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),r("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),r("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:r("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r("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"})})})]}),w("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",X,"px"]})]})]})}import{useCallback as nt}from"react";import V,{createContext as Qe,useCallback as ge,useContext as et,useEffect as me,useState as oe,useSyncExternalStore as tt}from"react";async function pe(){let{detectPlatform:e}=await import("../platform-GKYYQBCS.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-HLQSYZJC.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-6WEBHSGH.js");return new n}}var J=Qe(null);function fe({children:e,loading:t=null,onError:n}){let[i,o]=oe(null),[a,m]=oe(null),[f,p]=oe(!0);return me(()=>{let s=!0,d=null;async function l(){try{let h=await pe();await h.connect(),s?(d=h,o(h),p(!1)):h.close()}catch(h){s&&(console.error("error",h),m(h instanceof Error?h:new Error(String(h))),p(!1))}}return l(),()=>{s=!1,d?.close()}},[]),me(()=>{if(!i)return;let s=d=>{document.documentElement.classList.toggle("dark",d==="dark"),document.documentElement.style.colorScheme=d==="dark"?"dark":"auto"};return s(i.getTheme()),i.onThemeChange(s)},[i]),a&&n?V.createElement(V.Fragment,null,n(a)):f||!i?V.createElement(V.Fragment,null,t):V.createElement(J.Provider,{value:i},e)}function v(e){let t=et(J);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=ge(a=>e==="toolOutput"?t.onToolResult(()=>a()):e==="theme"?t.onThemeChange(()=>a()):e==="displayMode"?t.onDisplayModeChange(()=>a()):e==="safeArea"?t.onSafeAreaChange(()=>a()):e==="maxHeight"?t.onMaxHeightChange(()=>a()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>a()):e==="widgetState"?t.onWidgetStateChange(()=>a()):()=>{},[t,e]),i=ge(()=>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]),o=tt(n,i,i);return e?o:t}function he(){let e=v();return nt((t,n)=>e.callTool(t,n),[e])}function we(){return v("displayMode")}function q(){return v("toolOutput")}function ot(e){if(!e||!("__widgetId"in e))return{widgetId:null,cleanData:e};let{__widgetId:t,...n}=e;return{widgetId:t,cleanData:n}}function ve(){let e=q(),{widgetId:t,cleanData:n}=ot(e);return{widgetId:t,data:n}}import{useSyncExternalStore as it}from"react";function xe(){return it(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ye(){return v("locale")}function be(){return v("maxHeight")}import{useCallback as rt}from"react";function ke(){let e=v();return rt(t=>e.openExternal(t),[e])}import{useCallback as st}from"react";function Me(){let e=v();return st(t=>e.requestDisplayMode(t),[e])}function Ce(){return v("safeArea")}import{useCallback as at}from"react";function Te(){let e=v();return at(t=>e.sendFollowUp(t),[e])}function Se(){return v("theme")}function Ee(){return v("toolResponseMetadata")}import{useContext as ut,useEffect as re,useMemo as pt,useRef as gt,useState as Ie}from"react";function lt(){return crypto.randomUUID()}function C(e,t,n){return{event_id:lt(),event_type:t,timestamp:new Date().toISOString(),source:"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function _e(e){let t=e.trim().split(/\s+/),n=t[0]||"",i={};for(let o=1;o<t.length;o++){let a=t[o].indexOf(":");if(a===-1)continue;let m=t[o].slice(0,a),f=t[o].slice(a+1),p=Number(f);i[m]=Number.isFinite(p)&&f!==""?p:f}return{name:n,props:i}}function Re(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function We(e,t){let n=[],i=typeof navigator<"u"?navigator:void 0,o=i&&"connection"in i?i.connection:void 0;t([C(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:o?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let a=u=>{t([C(e,"widget_error",{metadata:{error_message:u.message,error_stack:(u.error?.stack??"").slice(0,1024),error_source:u.filename??"unknown"}})])};window.addEventListener("error",a),n.push(()=>window.removeEventListener("error",a));let m=u=>{let c=u.reason,x=c instanceof Error?c.message:String(c),y=c instanceof Error?(c.stack??"").slice(0,1024):"";t([C(e,"widget_error",{metadata:{error_message:x,error_stack:y,error_source:"unhandledrejection"}})])};window.addEventListener("unhandledrejection",m),n.push(()=>window.removeEventListener("unhandledrejection",m));let f=u=>{let c=u.target;t([C(e,"widget_click",{metadata:{target_tag:c?.tagName?.toLowerCase()??"unknown",target_id:c?.id||void 0,target_class:c?.className||void 0,click_x:u.clientX,click_y:u.clientY}})])};document.addEventListener("click",f,{capture:!0}),n.push(()=>document.removeEventListener("click",f,{capture:!0}));let p=u=>{let x=u.target?.closest?.("[data-ww-conversion]");if(!x)return;let{name:y,props:b}=_e(x.getAttribute("data-ww-conversion")||"");y&&t([C(e,"conversion",{event_name:y,metadata:Object.keys(b).length>0?b:void 0})])};document.addEventListener("click",p,{capture:!0}),n.push(()=>document.removeEventListener("click",p,{capture:!0}));let s=0,d=u=>{let x=u.target?.closest?.("[data-ww-step]");if(!x)return;let{name:y,props:b}=_e(x.getAttribute("data-ww-step")||"");y&&(s++,t([C(e,"step",{event_name:y,step_sequence:s,metadata:Object.keys(b).length>0?b:void 0})]))};document.addEventListener("click",d,{capture:!0}),n.push(()=>document.removeEventListener("click",d,{capture:!0}));let l=u=>{let c=u.target?.closest?.("a");if(!c)return;let x=c.getAttribute("href")??"",y=x.startsWith("http")&&!x.startsWith(window.location.origin);t([C(e,"widget_link_click",{metadata:{href:x,link_text:(c.textContent??"").slice(0,200),is_external:y}})])};document.addEventListener("click",l,{capture:!0}),n.push(()=>document.removeEventListener("click",l,{capture:!0}));let h=null,A=window.scrollY||0,D=()=>{h||(h=setTimeout(()=>{h=null;let u=window.scrollY||document.documentElement.scrollTop,c=document.documentElement.scrollHeight-document.documentElement.clientHeight,x=c>0?Math.round(u/c*100):0,y=u>=A?"down":"up";A=u,t([C(e,"widget_scroll",{metadata:{scroll_depth_pct:x,scroll_direction:y,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",D,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",D),h&&clearTimeout(h)});let E=new WeakMap,I=u=>{let c=u.target;!c||!Re(c)||E.set(c,Date.now())},_=u=>{let c=u.target;if(!c||!Re(c))return;let x=E.get(c),y=x?Date.now()-x:0,b=c;t([C(e,"widget_form_field",{metadata:{field_name:b.name||b.id||void 0,field_type:b.type||c.tagName.toLowerCase(),time_in_field_ms:y,filled:!!b.value}})])};document.addEventListener("focusin",I,{capture:!0}),document.addEventListener("focusout",_,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",I,{capture:!0}),document.removeEventListener("focusout",_,{capture:!0})});let F=new WeakMap,N=u=>{let x=u.target?.closest?.("form");x&&!F.has(x)&&F.set(x,Date.now())};document.addEventListener("focusin",N,{capture:!0}),n.push(()=>document.removeEventListener("focusin",N,{capture:!0}));let U=u=>{let c=u.target,x=c?F.get(c):void 0,y=0;if(c){let b=c.querySelectorAll("input, textarea, select");for(let ee of b){let H=ee;(H.validity&&!H.validity.valid||H.getAttribute("aria-invalid")==="true")&&y++}}t([C(e,"widget_form_submit",{metadata:{form_id:c?.id||void 0,time_to_submit_ms:x?Date.now()-x:void 0,validation_errors:y}})])};return document.addEventListener("submit",U,{capture:!0}),n.push(()=>document.removeEventListener("submit",U,{capture:!0})),()=>{for(let u of n)u()}}var dt="@waniwani/sdk";function ct(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 o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:i,properties:o,metadata:{}}}function ie(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:dt,version:"0.1.0"},events:e.map(ct)})}var Z=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 o=ie(n);if(o.length<=6e4){fetch(t,{method:"POST",headers:i,body:o,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let a=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,a),i),this.sendKeepAliveChunked(t,n.slice(a),i)}sendBeaconChunked(t,n){let i=ie(n);if(i.length<=6e4){navigator.sendBeacon(t,new Blob([i],{type:"application/json"}));return}if(n.length<=1)return;let o=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,o)),this.sendBeaconChunked(t,n.slice(o))}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=ie(t),i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);for(let o=0;o<=3;o++)try{let a=await fetch(this.config.endpoint,{method:"POST",headers:i,body:n});if(a.status===200||a.status===207)return;if(a.status===401){this.stopped=!0;return}if(a.status>=500&&o<3){await this.delay(1e3*2**o);continue}if(a.status===429&&o<3){let m=a.headers.get("Retry-After"),f=m?Number(m):NaN,p=Number.isFinite(f)?f*1e3:1e3*2**o;await this.delay(p);continue}return}catch{if(o<3){await this.delay(1e3*2**o);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var se={identify(){},step(){},track(){},conversion(){}},S=null,Q=0;function mt(){return crypto.randomUUID()}function O(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function ft(){return{widget:se,cleanup:()=>{},config:null}}function Ae(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,o=O(i?.endpoint);return o?{endpoint:o,token:O(i?.token),sessionId:O(i?.sessionId)}:null}function Ne(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId}function ht(e){let[t,n]=Ie(()=>Ae(e));return re(()=>{if(!e){n(o=>o===null?o:null);return}let i=()=>{let o=Ae(e);n(a=>Ne(a,o)?a:o)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function wt(e,t){let n=e.sessionId??crypto.randomUUID(),i=crypto.randomUUID(),o=new Z({endpoint:e.endpoint,token:e.token,metadata:t}),a,m=0,f=d=>{o.send(d)},p=We({sessionId:n,traceId:i,metadata:t},f);function s(d,l){return{event_id:mt(),event_type:d,timestamp:new Date().toISOString(),source:"widget",session_id:n,trace_id:i,user_id:a,...l}}return{widget:{identify(d,l){a=d,f([s("identify",{user_id:d,user_traits:l})])},step(d,l){m++,f([s("step",{event_name:d,step_sequence:m,metadata:l})])},track(d,l){f([s("track",{event_name:d,metadata:l})])},conversion(d,l){f([s("conversion",{event_name:d,metadata:l})])}},cleanup:()=>{p(),o.stop()},config:e}}function Le(e={}){let t=ut(J),n=ht(t),i=O(e.endpoint),o=O(e.token),a=O(e.sessionId),m=pt(()=>i?{endpoint:i,token:o??n?.token,sessionId:a??n?.sessionId}:n,[i,o,a,n]),[f,p]=Ie(se),s=gt(e.metadata);return s.current=e.metadata,re(()=>(Q++,()=>{Q=Math.max(Q-1,0),Q===0&&(S?.cleanup(),S=null)}),[]),re(()=>{if(!(typeof window>"u")){if(!m){S?.config&&(S.cleanup(),S=ft(),p(se));return}Ne(S?.config,m)||(S?.cleanup(),S=wt(m,s.current),p(S.widget))}},[m]),f}import{useCallback as vt,useEffect as xt,useState as yt}from"react";function Oe(e){let t=v("widgetState"),[n,i]=yt(()=>t??(typeof e=="function"?e():e??null));xt(()=>{i(t)},[t]);let o=vt(a=>{i(m=>{let f=typeof a=="function"?a(m):a;return ae()==="openai"&&f!=null&&window.openai?.setWidgetState(f),f})},[]);return[n,o]}import{jsx as W,jsxs as De}from"react/jsx-runtime";var bt=()=>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:[W("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),W("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),W("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),W("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..."}),W("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:W("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),W("style",{children:`
63
63
  @keyframes shimmer {
64
64
  0% { background-position: 200% 0; }
65
65
  100% { background-position: -200% 0; }
66
66
  }
67
- `})]});export{ue as DevModeProvider,je as InitializeNextJsInChatGpt,Tt as LoadingWidget,me as WidgetProvider,X as getMockState,j as initializeMockOpenAI,z as updateMockDisplayMode,I as updateMockGlobal,G as updateMockTheme,K as updateMockToolOutput,he as useCallTool,we as useDisplayMode,ye as useFlowAction,be as useIsChatGptApp,ke as useLocale,Ce as useMaxHeight,Me as useOpenExternal,Te as useRequestDisplayMode,Se as useSafeArea,Ee as useSendFollowUp,Re as useTheme,Z as useToolOutput,_e as useToolResponseMetadata,De as useWaniwani,w as useWidgetClient,Fe as useWidgetState};
67
+ `})]});export{ue as DevModeProvider,Pe as InitializeNextJsInChatGpt,bt as LoadingWidget,fe as WidgetProvider,$ as getMockState,j as initializeMockOpenAI,z as updateMockDisplayMode,R as updateMockGlobal,G as updateMockTheme,K as updateMockToolOutput,he as useCallTool,we as useDisplayMode,ve as useFlowAction,xe as useIsChatGptApp,ye as useLocale,be as useMaxHeight,ke as useOpenExternal,Me as useRequestDisplayMode,Ce as useSafeArea,Te as useSendFollowUp,Se as useTheme,q as useToolOutput,Ee as useToolResponseMetadata,Le as useWaniwani,v as useWidgetClient,Oe as useWidgetState};
68
68
  //# sourceMappingURL=react.js.map