@waniwani/sdk 0.15.1 → 0.15.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.
@@ -712,6 +712,17 @@ type UseWaniwaniOptions = ContextDrivenOptions | ExplicitEndpointOptions;
712
712
  * The tracking API returned by `useWaniwani()`.
713
713
  */
714
714
  interface WaniwaniWidget {
715
+ /**
716
+ * The session ID stamped on every event this widget emits, so hosts can
717
+ * correlate widget activity with server-side tracking without reaching into
718
+ * the internal `_meta` shape.
719
+ *
720
+ * Resolved from (1) the explicit `sessionId` option, (2)
721
+ * `toolResponseMetadata.waniwani.sessionId`, else a random UUID generated
722
+ * on mount. `undefined` until the widget initializes (same lifecycle as the
723
+ * tracking methods) and when no config resolves (no-op widget).
724
+ */
725
+ readonly sessionId?: string;
715
726
  /** Tie all subsequent widget events to this user. */
716
727
  identify(userId: string, traits?: Record<string, unknown>): void;
717
728
  /** Record a funnel step. Auto-incrementing sequence per session. */
@@ -739,6 +750,7 @@ interface WaniwaniWidget {
739
750
  * const wani = useWaniwani();
740
751
  * // Auto-captures clicks, links, errors, scrolls, forms
741
752
  * // Optionally call wani.track("custom_event") for manual events
753
+ * // Read wani.sessionId to correlate with server-side tracking
742
754
  * return <a href="https://example.com">Visit</a>;
743
755
  * }
744
756
  * ```
package/dist/mcp/react.js CHANGED
@@ -51,7 +51,7 @@ import{a as V,b as ke,c as Ce}from"../chunk-DP6SAQTK.js";import{b as H,c as Me}f
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 I=S(()=>{f(!0),requestAnimationFrame(()=>{n(!0)})},[]),W=S(()=>{r(!0),n(!1),setTimeout(()=>{f(!1),r(!1)},150)},[]),q=S(()=>{t?W():I()},[t,I,W]);F(()=>{let w=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="d"&&(k.preventDefault(),q()),k.key==="Escape"&&t&&W()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[t,q,W]),F(()=>{if(!t)return;let w=k=>{P.current&&!P.current.contains(k.target)&&W()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[t,W]);let Ve=S(w=>{p(w),L(w)},[]),$e=S(w=>{c(w),D(w)},[]),J=S(w=>{try{let k=JSON.parse(w);x(null),N(k)}catch{x("Invalid JSON")}},[]),Xe=S(w=>{m(w),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{J(w)},500)},[J]),Ye=S(()=>{b.current&&clearTimeout(b.current),J(a)},[J,a]),qe=S(()=>{let w=JSON.stringify(e??{},null,2);m(w),x(null),N(e??{}),p("inline"),L("inline"),c("dark"),D("dark")},[e]),Ze=[{value:"inline",label:"inline",icon:l(it,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:l(st,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:l(at,{className:"w-3.5 h-3.5"})}],Qe=[{value:"light",label:"light",icon:l(lt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:l(dt,{className:"w-3.5 h-3.5"})}];return y(Q,{children:[l("style",{dangerouslySetInnerHTML:{__html:ct}}),y("div",{ref:P,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[y("button",{type:"button",onClick:q,className:"group relative flex items-center justify-center w-11 h-11 rounded-xl transition-all duration-200 ease-out hover:scale-105 active:scale-95",style:{background:"rgba(14, 14, 16, 0.95)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(255, 255, 255, 0.08)",boxShadow:`
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:`
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)
@@ -59,10 +59,10 @@ import{a as V,b as ke,c as Ce}from"../chunk-DP6SAQTK.js";import{b as H,c as Me}f
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 Ie,useContext as St,useEffect as Ue,useState as re,useSyncExternalStore as Tt}from"react";async function Oe(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-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 Oe();await o.connect(),g?(c=o,r(o),p(!1)):o.close()}catch(o){g&&(console.error("error",o),f(o instanceof Error?o:new Error(String(o))),p(!1))}}return s(),()=>{g=!1,c?.close()}},[]),Ue(()=>{if(!i)return;let g=c=>{document.documentElement.classList.toggle("dark",c==="dark"),document.documentElement.style.colorScheme=c==="dark"?"dark":"auto"};return g(i.getTheme()),i.onThemeChange(g)},[i]),u&&n?K.createElement(K.Fragment,null,n(u)):h||!i?K.createElement(K.Fragment,null,t):K.createElement(_.Provider,{value:i},e)}function v(e){let t=St(_);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Ie(u=>e==="toolOutput"?t.onToolResult(()=>u()):e==="theme"?t.onThemeChange(()=>u()):e==="displayMode"?t.onDisplayModeChange(()=>u()):e==="safeArea"?t.onSafeAreaChange(()=>u()):e==="maxHeight"?t.onMaxHeightChange(()=>u()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>u()):e==="widgetState"?t.onWidgetStateChange(()=>u()):()=>{},[t,e]),i=Ie(()=>e==="toolOutput"?t.getToolOutput():e==="theme"?t.getTheme():e==="displayMode"?t.getDisplayMode():e==="locale"?t.getLocale():e==="safeArea"?t.getSafeArea():e==="maxHeight"?t.getMaxHeight():e==="toolResponseMetadata"?t.getToolResponseMetadata():e==="widgetState"?t.getWidgetState():null,[t,e]),r=Tt(n,i,i);return e?r:t}function se(){let e=v();return Et((t,n)=>e.callTool(t,n),[e])}function ae(){return v("displayMode")}function z(){return v("toolOutput")}function le(){return{data:z()}}import{useSyncExternalStore as Rt}from"react";function de(){return Rt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return v("locale")}function ce(){return v("maxHeight")}import{useCallback as Wt}from"react";function pe(){let e=v();return Wt(t=>e.openExternal(t),[e])}import{useCallback as _t}from"react";function ge(){let e=v();return _t(t=>e.requestDisplayMode(t),[e])}function me(){return v("safeArea")}import{useCallback as At}from"react";function fe(){let e=v();return At((t,n)=>{(async()=>{Me(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(i=>{console.error("Failed to send follow-up message:",i)})},[e])}function he(){return v("theme")}function we(){return v("toolResponseMetadata")}import{useCallback as Ot}from"react";function ve(){let e=v();return Ot(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as It,useEffect as Ut,useState as Nt}from"react";function ye(e){let t=v("widgetState"),[n,i]=Nt(()=>t??(typeof e=="function"?e():e??null));Ut(()=>{i(t)},[t]);let r=It(u=>{i(f=>{let h=typeof u=="function"?u(f):u;return V()==="openai"&&h!=null&&window.openai?.setWidgetState(h),h})},[]);return[n,r]}import{jsx as A,jsxs as Ne}from"react/jsx-runtime";var Le=()=>Ne("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Ne("div",{className:"flex gap-2",children:[A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),A("p",{className:"text-sm font-medium text-transparent bg-clip-text bg-gradient-to-r from-slate-400 via-slate-200 to-slate-400 bg-[length:200%_100%] animate-[shimmer_1.5s_ease-in-out_infinite]",children:"Loading widget..."}),A("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:A("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),A("style",{children:`
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:`
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 I=P;(I.validity&&!I.validity.valid||I.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:d?.id||void 0,time_to_submit_ms:x?Date.now()-x:void 0,validation_errors:b}})])};document.addEventListener("submit",a,{capture:!0}),n.push(()=>document.removeEventListener("submit",a,{capture:!0}))}return()=>{for(let s of n)s()}}var Dt="@waniwani/sdk";function Ft(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,i={};e.session_id&&(i.sessionId=e.session_id),e.trace_id&&(i.traceId=e.trace_id),e.user_id&&(i.externalUserId=e.user_id);let r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source,timestamp:e.timestamp,correlation:i,properties:r,metadata:{}}}function be(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:Dt,version:"0.1.0"},events:e.map(Ft)})}var X=class{buffer=[];timer=null;flushing=!1;pendingFlush=!1;stopped=!1;config;teardownVisibility=null;teardownPagehide=null;constructor(t){this.config=t,this.start(),this.registerTeardown()}send(t){if(!this.stopped){if(this.buffer.push(...t),this.buffer.length>200){let n=this.buffer.length-200;this.buffer.splice(0,n)}this.buffer.length>=20&&this.flush().catch(()=>{})}}async flush(){if(!(this.stopped||this.buffer.length===0)){if(this.flushing){this.pendingFlush=!0;return}this.flushing=!0;try{let t=this.buffer.splice(0,20);await this.sendBatch(t)}finally{this.flushing=!1,this.pendingFlush&&this.buffer.length>0&&!this.stopped&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null),typeof document<"u"&&this.teardownVisibility&&(document.removeEventListener("visibilitychange",this.teardownVisibility),this.teardownVisibility=null),typeof window<"u"&&this.teardownPagehide&&(window.removeEventListener("pagehide",this.teardownPagehide),this.teardownPagehide=null)}beaconFlush(){if(this.buffer.length===0)return;let t=[...this.buffer];this.buffer.length=0;let n={"Content-Type":"application/json"};if(this.config.token&&(n.Authorization=`Bearer ${this.config.token}`),typeof fetch<"u"){this.sendKeepAliveChunked(this.config.endpoint,t,n);return}typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendBeaconChunked(this.config.endpoint,t)}sendKeepAliveChunked(t,n,i){let r=be(n);if(r.length<=6e4){fetch(t,{method:"POST",headers:i,body:r,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let u=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,u),i),this.sendKeepAliveChunked(t,n.slice(u),i)}sendBeaconChunked(t,n){let i=be(n);if(i.length<=6e4){navigator.sendBeacon(t,new Blob([i],{type:"application/json"}));return}if(n.length<=1)return;let r=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,r)),this.sendBeaconChunked(t,n.slice(r))}start(){this.timer||(this.timer=setInterval(()=>{this.flush().catch(()=>{})},5e3))}registerTeardown(){typeof document>"u"||(this.teardownVisibility=()=>{document.visibilityState==="hidden"&&this.beaconFlush()},this.teardownPagehide=()=>{this.beaconFlush()},document.addEventListener("visibilitychange",this.teardownVisibility),window.addEventListener("pagehide",this.teardownPagehide))}async sendBatch(t){let n=be(t),i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);for(let r=0;r<=3;r++)try{let u=await fetch(this.config.endpoint,{method:"POST",headers:i,body:n});if(u.status===200||u.status===207)return;if(u.status===401){this.stopped=!0;return}if(u.status>=500&&r<3){await this.delay(1e3*2**r);continue}if(u.status===429&&r<3){let f=u.headers.get("Retry-After"),h=f?Number(f):NaN,p=Number.isFinite(h)?h*1e3:1e3*2**r;await this.delay(p);continue}return}catch{if(r<3){await this.delay(1e3*2**r);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var He={identify(){},step(){},track(){},conversion(){}},O=null,Y=0;function Bt(){return crypto.randomUUID()}function R(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Ke(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Be(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,r=R(i?.endpoint);return r?{endpoint:r,token:R(i?.token),sessionId:R(i?.sessionId),source:R(i?.source)}:null}function ze(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function Gt(e){let[t,n]=je(()=>Be(e));return Ge(()=>{if(!e){n(r=>r===null?r:null);return}let i=()=>{let r=Be(e);n(u=>ze(u,r)?u:r)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function jt(e,t,n){let i=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),u=new X({endpoint:e.endpoint,token:e.token,metadata:t}),f,h=0,p=o=>{u.send(o)},g=e.source,c=Fe({sessionId:i,traceId:r,metadata:t,source:g,capture:n},p);function s(o,a){return{event_id:Bt(),event_type:o,timestamp:new Date().toISOString(),source:g,session_id:i,trace_id:r,user_id:f,...a}}return{captureKey:Ke(n),widget:{identify(o,a){f=o,p([s("identify",{user_id:o,user_traits:a})])},step(o,a){h++,p([s("step",{event_name:o,step_sequence:h,metadata:a})])},track(o,a){p([s("track",{event_name:o,metadata:a})])},conversion(o,a){p([s("conversion",{event_name:o,metadata:a})])}},cleanup:()=>{c(),u.stop()},config:e}}function Je(e={}){let t=Pt(_),n=Gt(t),i=R(e.endpoint),r=R(e.token),u=R(e.sessionId),f=R(e.source),h=Ht(()=>{let a=f??n?.source;return a?i?{endpoint:i,token:r??n?.token,sessionId:u??n?.sessionId,source:a}:n?{...n,source:a}:null:null},[i,r,u,f,n]),[p,g]=je(He),c=Pe(e.metadata);c.current=e.metadata;let s=Pe(e.capture);s.current=e.capture;let o=Ke(e.capture);return Ge(()=>{if(!(typeof window>"u")){if(!h){g(He);return}return(!ze(O?.config,h)||O?.captureKey!==o)&&(O?.cleanup(),O=jt(h,c.current,s.current)),g(O.widget),Y++,()=>{Y=Math.max(Y-1,0),Y===0&&(O?.cleanup(),O=null)}}},[h,o]),p}export{ee as DevModeProvider,Se as InitializeNextJsInIframe,Le as LoadingWidget,ie as WidgetProvider,V as detectPlatform,j as getMockState,U as initializeMockOpenAI,Ce as isMCPApps,ke as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,L as updateMockDisplayMode,E as updateMockGlobal,D as updateMockTheme,N as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,ge as useRequestDisplayMode,me as useSafeArea,fe as useSendFollowUp,he as useTheme,z as useToolOutput,we as useToolResponseMetadata,ve as useUpdateModelContext,Je as useWaniwani,v as useWidgetClient,ye as useWidgetState};
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};
68
68
  //# sourceMappingURL=react.js.map