@waniwani/sdk 0.11.11 → 0.11.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -112
- package/dist/chat/embed.js +65 -65
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/express-js/index.d.ts +8 -1
- package/dist/chat/express-js/index.js.map +1 -1
- package/dist/chat/index.d.ts +9 -22
- package/dist/chat/index.js +7 -7
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/next-js/index.d.ts +5 -3
- package/dist/chat/next-js/index.js.map +1 -1
- package/dist/chat/server/index.js +1 -1
- package/dist/chat/server/index.js.map +1 -1
- package/dist/chat/styles.css +1 -1
- package/dist/{chunk-DGSC74SV.js → chunk-DP6SAQTK.js} +1 -1
- package/dist/chunk-DP6SAQTK.js.map +1 -0
- package/dist/{chunk-5OQXAEHG.js → chunk-RZKVTH7F.js} +1 -1
- package/dist/chunk-RZKVTH7F.js.map +1 -0
- package/dist/legacy/chat/express-js/index.d.ts +407 -0
- package/dist/legacy/chat/express-js/index.js +10 -0
- package/dist/legacy/chat/express-js/index.js.map +1 -0
- package/dist/legacy/chat/next-js/index.d.ts +368 -0
- package/dist/legacy/chat/next-js/index.js +10 -0
- package/dist/legacy/chat/next-js/index.js.map +1 -0
- package/dist/legacy/index.d.ts +335 -0
- package/dist/legacy/index.js +2 -0
- package/dist/legacy/index.js.map +1 -0
- package/dist/legacy/mcp/react.d.ts +573 -0
- package/dist/legacy/mcp/react.js +68 -0
- package/dist/legacy/mcp/react.js.map +1 -0
- package/dist/mcp/index.d.ts +1153 -1117
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react.d.ts +170 -74
- package/dist/mcp/react.js +7 -7
- package/dist/mcp/react.js.map +1 -1
- package/dist/{mcp-apps-client-PUL4H54S.js → mcp-apps-client-OFYMQOI3.js} +1 -1
- package/dist/mcp-apps-client-OFYMQOI3.js.map +1 -0
- package/dist/{openai-client-QAC3ZD5W.js → openai-client-TZIOCMXP.js} +2 -2
- package/dist/openai-client-TZIOCMXP.js.map +1 -0
- package/dist/platform-LKQFC3AJ.js +3 -0
- package/package.json +34 -21
- package/dist/chunk-5OQXAEHG.js.map +0 -1
- package/dist/chunk-DGSC74SV.js.map +0 -1
- package/dist/evals/index.d.ts +0 -156
- package/dist/evals/index.js +0 -2
- package/dist/evals/index.js.map +0 -1
- package/dist/evals/scorers.d.ts +0 -92
- package/dist/evals/scorers.js +0 -8
- package/dist/evals/scorers.js.map +0 -1
- package/dist/mcp-apps-client-PUL4H54S.js.map +0 -1
- package/dist/openai-client-QAC3ZD5W.js.map +0 -1
- package/dist/platform-GKYYQBCS.js +0 -3
- /package/dist/{platform-GKYYQBCS.js.map → platform-LKQFC3AJ.js.map} +0 -0
package/dist/mcp/react.d.ts
CHANGED
|
@@ -13,6 +13,10 @@ import React$1, { ReactNode, SetStateAction } from 'react';
|
|
|
13
13
|
*
|
|
14
14
|
* More background on the ChatGPT case:
|
|
15
15
|
* https://vercel.com/blog/running-next-js-inside-chatgpt-a-deep-dive-into-native-app-integration
|
|
16
|
+
*
|
|
17
|
+
* @deprecated Legacy MCP-widget-in-host stack (used with `createResource`/`createTool`).
|
|
18
|
+
* Preserved for back-compat; will move to `@waniwani/sdk/legacy/react` in a future minor
|
|
19
|
+
* release.
|
|
16
20
|
*/
|
|
17
21
|
declare function InitializeNextJsInIframe({ baseUrl, passthroughOrigins, }: {
|
|
18
22
|
baseUrl: string;
|
|
@@ -29,6 +33,10 @@ interface DevControlsProps {
|
|
|
29
33
|
defaultProps?: Record<string, unknown>;
|
|
30
34
|
widgetPaths?: string[];
|
|
31
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
38
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
39
|
+
*/
|
|
32
40
|
declare function DevModeProvider({ defaultProps, widgetPaths, children, }: DevControlsProps & {
|
|
33
41
|
children: React.ReactNode;
|
|
34
42
|
}): react_jsx_runtime.JSX.Element | null;
|
|
@@ -140,6 +148,19 @@ type ToolCallResult = CallToolResult;
|
|
|
140
148
|
* Tool result notification (what the host pushes to the widget)
|
|
141
149
|
*/
|
|
142
150
|
type ToolResult = CallToolResult;
|
|
151
|
+
/**
|
|
152
|
+
* Host context - all values available from the host.
|
|
153
|
+
*/
|
|
154
|
+
type HostContext = {
|
|
155
|
+
theme: Theme;
|
|
156
|
+
locale: string;
|
|
157
|
+
displayMode: DisplayMode;
|
|
158
|
+
maxHeight: number | null;
|
|
159
|
+
safeArea: SafeArea | null;
|
|
160
|
+
toolOutput: UnknownObject | null;
|
|
161
|
+
toolResponseMetadata: UnknownObject | null;
|
|
162
|
+
widgetState: UnknownObject | null;
|
|
163
|
+
};
|
|
143
164
|
/**
|
|
144
165
|
* Unified widget client interface that works on both OpenAI and MCP Apps.
|
|
145
166
|
*
|
|
@@ -277,6 +298,8 @@ interface UnifiedWidgetClient {
|
|
|
277
298
|
* Get a function to call other tools.
|
|
278
299
|
* Works on both OpenAI widgets and MCP Apps.
|
|
279
300
|
*
|
|
301
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
302
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
280
303
|
* @returns A function to call tools with their name and arguments
|
|
281
304
|
*/
|
|
282
305
|
declare function useCallTool(): (name: string, args: Record<string, unknown>) => Promise<ToolCallResult>;
|
|
@@ -285,6 +308,8 @@ declare function useCallTool(): (name: string, args: Record<string, unknown>) =>
|
|
|
285
308
|
* Get the current display mode.
|
|
286
309
|
* Works on both OpenAI widgets and MCP Apps.
|
|
287
310
|
*
|
|
311
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
312
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
288
313
|
* @returns The current display mode ("pip" | "inline" | "fullscreen")
|
|
289
314
|
*/
|
|
290
315
|
declare function useDisplayMode(): DisplayMode;
|
|
@@ -299,6 +324,9 @@ type FlowActionResult<T> = {
|
|
|
299
324
|
* Lightweight wrapper over `useToolOutput` — will be extended
|
|
300
325
|
* with flow-specific features in the future.
|
|
301
326
|
*
|
|
327
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
328
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
329
|
+
*
|
|
302
330
|
* @example
|
|
303
331
|
* ```tsx
|
|
304
332
|
* const { data } = useFlowAction<{ plans: string[] }>();
|
|
@@ -312,6 +340,8 @@ declare function useFlowAction<T extends Record<string, unknown>>(): FlowActionR
|
|
|
312
340
|
* Check if running in ChatGPT app (OpenAI-only).
|
|
313
341
|
* Returns false on MCP Apps.
|
|
314
342
|
*
|
|
343
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
344
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
315
345
|
* @returns Whether the widget is running in ChatGPT app
|
|
316
346
|
*/
|
|
317
347
|
declare function useIsChatGptApp(): boolean;
|
|
@@ -320,6 +350,8 @@ declare function useIsChatGptApp(): boolean;
|
|
|
320
350
|
* Get the current locale.
|
|
321
351
|
* Works on both OpenAI widgets and MCP Apps.
|
|
322
352
|
*
|
|
353
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
354
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
323
355
|
* @returns The current locale string (e.g., "en-US")
|
|
324
356
|
*/
|
|
325
357
|
declare function useLocale(): string;
|
|
@@ -329,6 +361,8 @@ declare function useLocale(): string;
|
|
|
329
361
|
* Useful for responsive layouts that need to adapt to container constraints.
|
|
330
362
|
* Returns null on MCP Apps.
|
|
331
363
|
*
|
|
364
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
365
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
332
366
|
* @returns The maximum height in pixels, or null if not available
|
|
333
367
|
*/
|
|
334
368
|
declare function useMaxHeight(): number | null;
|
|
@@ -337,6 +371,8 @@ declare function useMaxHeight(): number | null;
|
|
|
337
371
|
* Get a function to open external URLs.
|
|
338
372
|
* Works on both OpenAI widgets and MCP Apps.
|
|
339
373
|
*
|
|
374
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
375
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
340
376
|
* @returns A function that opens external URLs
|
|
341
377
|
*/
|
|
342
378
|
declare function useOpenExternal(): (url: string) => void;
|
|
@@ -345,6 +381,8 @@ declare function useOpenExternal(): (url: string) => void;
|
|
|
345
381
|
* Get a function to request display mode changes.
|
|
346
382
|
* On MCP Apps, this may be a no-op depending on host support.
|
|
347
383
|
*
|
|
384
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
385
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
348
386
|
* @returns A function to request a specific display mode
|
|
349
387
|
*/
|
|
350
388
|
declare function useRequestDisplayMode(): (mode: DisplayMode) => Promise<DisplayMode>;
|
|
@@ -354,6 +392,8 @@ declare function useRequestDisplayMode(): (mode: DisplayMode) => Promise<Display
|
|
|
354
392
|
* Useful for ensuring UI elements don't get hidden behind the chat input.
|
|
355
393
|
* Returns null on MCP Apps.
|
|
356
394
|
*
|
|
395
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
396
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
357
397
|
* @returns The safe area insets, or null if not available
|
|
358
398
|
*/
|
|
359
399
|
declare function useSafeArea(): SafeArea | null;
|
|
@@ -365,6 +405,8 @@ interface SendFollowUpOptions {
|
|
|
365
405
|
* Get a function to send follow-up messages to the AI.
|
|
366
406
|
* Works on both OpenAI widgets and MCP Apps.
|
|
367
407
|
*
|
|
408
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
409
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
368
410
|
* @returns A function that sends a follow-up message
|
|
369
411
|
*/
|
|
370
412
|
declare function useSendFollowUp(): (prompt: string, options?: SendFollowUpOptions) => void;
|
|
@@ -373,6 +415,8 @@ declare function useSendFollowUp(): (prompt: string, options?: SendFollowUpOptio
|
|
|
373
415
|
* Get the current theme.
|
|
374
416
|
* Works on both OpenAI widgets and MCP Apps.
|
|
375
417
|
*
|
|
418
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
419
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
376
420
|
* @returns The current theme ("light" | "dark")
|
|
377
421
|
*/
|
|
378
422
|
declare function useTheme(): Theme;
|
|
@@ -381,6 +425,8 @@ declare function useTheme(): Theme;
|
|
|
381
425
|
* Get the tool output (structured content returned by the tool handler).
|
|
382
426
|
* Works on both OpenAI widgets and MCP Apps.
|
|
383
427
|
*
|
|
428
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
429
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
384
430
|
* @returns The tool output or null
|
|
385
431
|
*/
|
|
386
432
|
declare function useToolOutput<T extends Record<string, unknown>>(): T | null;
|
|
@@ -391,6 +437,8 @@ declare function useToolOutput<T extends Record<string, unknown>>(): T | null;
|
|
|
391
437
|
* `openai/widgetSessionId` and custom tool `_meta` fields).
|
|
392
438
|
* Returns null when the host does not provide metadata.
|
|
393
439
|
*
|
|
440
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
441
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
394
442
|
* @returns The tool response metadata object or null if not available
|
|
395
443
|
*/
|
|
396
444
|
declare function useToolResponseMetadata(): UnknownObject | null;
|
|
@@ -398,9 +446,130 @@ declare function useToolResponseMetadata(): UnknownObject | null;
|
|
|
398
446
|
/**
|
|
399
447
|
* Get a function to update hidden model context for the next assistant turn.
|
|
400
448
|
* Uses the MCP Apps `ui/update-model-context` request when available.
|
|
449
|
+
*
|
|
450
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
451
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
401
452
|
*/
|
|
402
453
|
declare function useUpdateModelContext(): (context: ModelContextUpdate) => Promise<void>;
|
|
403
454
|
|
|
455
|
+
/**
|
|
456
|
+
* Provider props
|
|
457
|
+
*/
|
|
458
|
+
interface WidgetProviderProps {
|
|
459
|
+
children: ReactNode;
|
|
460
|
+
/** Optional loading component while connecting */
|
|
461
|
+
loading?: ReactNode;
|
|
462
|
+
/** Optional error component */
|
|
463
|
+
onError?: (error: Error) => ReactNode;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Provider component that initializes the correct widget client based on platform.
|
|
467
|
+
* Wrap your widget component with this provider.
|
|
468
|
+
*
|
|
469
|
+
* @deprecated Part of the legacy MCP-widget-in-host stack (used with `createResource` /
|
|
470
|
+
* `createTool`). Preserved for back-compat; will move to `@waniwani/sdk/legacy/react` in
|
|
471
|
+
* a future minor release. For new code, use `createFlow` from `@waniwani/sdk/mcp` and
|
|
472
|
+
* `useWaniwani` from `@waniwani/sdk/mcp/react`.
|
|
473
|
+
*
|
|
474
|
+
* @example
|
|
475
|
+
* ```tsx
|
|
476
|
+
* function App() {
|
|
477
|
+
* return (
|
|
478
|
+
* <WidgetProvider loading={<Spinner />}>
|
|
479
|
+
* <MyWidget />
|
|
480
|
+
* </WidgetProvider>
|
|
481
|
+
* );
|
|
482
|
+
* }
|
|
483
|
+
* ```
|
|
484
|
+
*/
|
|
485
|
+
declare function WidgetProvider({ children, loading, onError, }: WidgetProviderProps): React$1.FunctionComponentElement<React$1.FragmentProps> | React$1.FunctionComponentElement<React$1.ProviderProps<UnifiedWidgetClient | null>>;
|
|
486
|
+
/**
|
|
487
|
+
* Keys that can be selected from the widget client.
|
|
488
|
+
*/
|
|
489
|
+
type WidgetKey = "toolOutput" | "theme" | "displayMode" | "locale" | "safeArea" | "maxHeight" | "toolResponseMetadata" | "widgetState";
|
|
490
|
+
/**
|
|
491
|
+
* Value types for each widget key.
|
|
492
|
+
*/
|
|
493
|
+
type WidgetKeyValues = {
|
|
494
|
+
toolOutput: Record<string, unknown> | null;
|
|
495
|
+
theme: Theme;
|
|
496
|
+
displayMode: DisplayMode;
|
|
497
|
+
locale: string;
|
|
498
|
+
safeArea: SafeArea | null;
|
|
499
|
+
maxHeight: number | null;
|
|
500
|
+
toolResponseMetadata: UnknownObject | null;
|
|
501
|
+
widgetState: UnknownObject | null;
|
|
502
|
+
};
|
|
503
|
+
/**
|
|
504
|
+
* Get the unified widget client instance.
|
|
505
|
+
* Must be used within a WidgetProvider.
|
|
506
|
+
*
|
|
507
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
508
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
509
|
+
*
|
|
510
|
+
* @example
|
|
511
|
+
* ```tsx
|
|
512
|
+
* // Full client for actions
|
|
513
|
+
* const client = useWidgetClient();
|
|
514
|
+
* client.callTool("foo", {});
|
|
515
|
+
*
|
|
516
|
+
* // Key selector for reactive values
|
|
517
|
+
* const toolOutput = useWidgetClient("toolOutput");
|
|
518
|
+
* const theme = useWidgetClient("theme");
|
|
519
|
+
* ```
|
|
520
|
+
*/
|
|
521
|
+
declare function useWidgetClient(): UnifiedWidgetClient;
|
|
522
|
+
declare function useWidgetClient<K extends WidgetKey>(key: K): WidgetKeyValues[K];
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Widget state that persists across widget lifecycles (OpenAI-only).
|
|
526
|
+
* State is synchronized with the ChatGPT parent window and survives widget minimize/restore.
|
|
527
|
+
* On MCP Apps, returns [null, no-op].
|
|
528
|
+
*
|
|
529
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
530
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
531
|
+
* @param defaultState - Initial state value or function to compute it
|
|
532
|
+
* @returns A tuple of [state, setState] similar to useState
|
|
533
|
+
*/
|
|
534
|
+
declare function useWidgetState<T extends UnknownObject>(defaultState?: T | (() => T | null) | null): readonly [T | null, (state: SetStateAction<T | null>) => void];
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Default loading fallback for legacy MCP widgets.
|
|
538
|
+
*
|
|
539
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
540
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
541
|
+
*/
|
|
542
|
+
declare const LoadingWidget: () => react_jsx_runtime.JSX.Element;
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Widget platform types
|
|
546
|
+
*/
|
|
547
|
+
type WidgetPlatform = "openai" | "mcp-apps";
|
|
548
|
+
/**
|
|
549
|
+
* Detects which platform the widget is running on.
|
|
550
|
+
*
|
|
551
|
+
* OpenAI injects a global `window.openai` object.
|
|
552
|
+
* MCP Apps runs in a sandboxed iframe and uses postMessage.
|
|
553
|
+
*
|
|
554
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
555
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
556
|
+
*/
|
|
557
|
+
declare function detectPlatform(): WidgetPlatform;
|
|
558
|
+
/**
|
|
559
|
+
* Check if running on OpenAI platform.
|
|
560
|
+
*
|
|
561
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
562
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
563
|
+
*/
|
|
564
|
+
declare function isOpenAI(): boolean;
|
|
565
|
+
/**
|
|
566
|
+
* Check if running on MCP Apps platform.
|
|
567
|
+
*
|
|
568
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
569
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
570
|
+
*/
|
|
571
|
+
declare function isMCPApps(): boolean;
|
|
572
|
+
|
|
404
573
|
/**
|
|
405
574
|
* Opt-in toggles for the noisy auto-capture event types. Each defaults to
|
|
406
575
|
* `false` so widget owners declare intent before the SDK starts emitting
|
|
@@ -488,77 +657,4 @@ interface WaniwaniWidget {
|
|
|
488
657
|
*/
|
|
489
658
|
declare function useWaniwani(options?: UseWaniwaniOptions): WaniwaniWidget;
|
|
490
659
|
|
|
491
|
-
|
|
492
|
-
* Provider props
|
|
493
|
-
*/
|
|
494
|
-
interface WidgetProviderProps {
|
|
495
|
-
children: ReactNode;
|
|
496
|
-
/** Optional loading component while connecting */
|
|
497
|
-
loading?: ReactNode;
|
|
498
|
-
/** Optional error component */
|
|
499
|
-
onError?: (error: Error) => ReactNode;
|
|
500
|
-
}
|
|
501
|
-
/**
|
|
502
|
-
* Provider component that initializes the correct widget client based on platform.
|
|
503
|
-
* Wrap your widget component with this provider.
|
|
504
|
-
*
|
|
505
|
-
* @example
|
|
506
|
-
* ```tsx
|
|
507
|
-
* function App() {
|
|
508
|
-
* return (
|
|
509
|
-
* <WidgetProvider loading={<Spinner />}>
|
|
510
|
-
* <MyWidget />
|
|
511
|
-
* </WidgetProvider>
|
|
512
|
-
* );
|
|
513
|
-
* }
|
|
514
|
-
* ```
|
|
515
|
-
*/
|
|
516
|
-
declare function WidgetProvider({ children, loading, onError, }: WidgetProviderProps): React$1.FunctionComponentElement<React$1.FragmentProps> | React$1.FunctionComponentElement<React$1.ProviderProps<UnifiedWidgetClient | null>>;
|
|
517
|
-
/**
|
|
518
|
-
* Keys that can be selected from the widget client.
|
|
519
|
-
*/
|
|
520
|
-
type WidgetKey = "toolOutput" | "theme" | "displayMode" | "locale" | "safeArea" | "maxHeight" | "toolResponseMetadata" | "widgetState";
|
|
521
|
-
/**
|
|
522
|
-
* Value types for each widget key.
|
|
523
|
-
*/
|
|
524
|
-
type WidgetKeyValues = {
|
|
525
|
-
toolOutput: Record<string, unknown> | null;
|
|
526
|
-
theme: Theme;
|
|
527
|
-
displayMode: DisplayMode;
|
|
528
|
-
locale: string;
|
|
529
|
-
safeArea: SafeArea | null;
|
|
530
|
-
maxHeight: number | null;
|
|
531
|
-
toolResponseMetadata: UnknownObject | null;
|
|
532
|
-
widgetState: UnknownObject | null;
|
|
533
|
-
};
|
|
534
|
-
/**
|
|
535
|
-
* Get the unified widget client instance.
|
|
536
|
-
* Must be used within a WidgetProvider.
|
|
537
|
-
*
|
|
538
|
-
* @example
|
|
539
|
-
* ```tsx
|
|
540
|
-
* // Full client for actions
|
|
541
|
-
* const client = useWidgetClient();
|
|
542
|
-
* client.callTool("foo", {});
|
|
543
|
-
*
|
|
544
|
-
* // Key selector for reactive values
|
|
545
|
-
* const toolOutput = useWidgetClient("toolOutput");
|
|
546
|
-
* const theme = useWidgetClient("theme");
|
|
547
|
-
* ```
|
|
548
|
-
*/
|
|
549
|
-
declare function useWidgetClient(): UnifiedWidgetClient;
|
|
550
|
-
declare function useWidgetClient<K extends WidgetKey>(key: K): WidgetKeyValues[K];
|
|
551
|
-
|
|
552
|
-
/**
|
|
553
|
-
* Widget state that persists across widget lifecycles (OpenAI-only).
|
|
554
|
-
* State is synchronized with the ChatGPT parent window and survives widget minimize/restore.
|
|
555
|
-
* On MCP Apps, returns [null, no-op].
|
|
556
|
-
*
|
|
557
|
-
* @param defaultState - Initial state value or function to compute it
|
|
558
|
-
* @returns A tuple of [state, setState] similar to useState
|
|
559
|
-
*/
|
|
560
|
-
declare function useWidgetState<T extends UnknownObject>(defaultState?: T | (() => T | null) | null): readonly [T | null, (state: SetStateAction<T | null>) => void];
|
|
561
|
-
|
|
562
|
-
declare const LoadingWidget: () => react_jsx_runtime.JSX.Element;
|
|
563
|
-
|
|
564
|
-
export { DevModeProvider, type DeviceType, type DisplayMode, type FlowActionResult, InitializeNextJsInIframe, LoadingWidget, type ModelContextContentBlock, type ModelContextUpdate, type SafeArea, type SafeAreaInsets, type SendFollowUpOptions, type Theme, type UnknownObject, type UseWaniwaniOptions, type UserAgent, type WaniwaniWidget, WidgetProvider, getMockState, initializeMockOpenAI, updateMockDisplayMode, updateMockGlobal, updateMockTheme, updateMockToolOutput, useCallTool, useDisplayMode, useFlowAction, useIsChatGptApp, useLocale, useMaxHeight, useOpenExternal, useRequestDisplayMode, useSafeArea, useSendFollowUp, useTheme, useToolOutput, useToolResponseMetadata, useUpdateModelContext, useWaniwani, useWidgetClient, useWidgetState };
|
|
660
|
+
export { DevModeProvider, type DeviceType, type DisplayMode, type FlowActionResult, type HostContext, InitializeNextJsInIframe, LoadingWidget, type ModelContextContentBlock, type ModelContextUpdate, type SafeArea, type SafeAreaInsets, type SendFollowUpOptions, type Theme, type ToolCallResult, type ToolResult, type UnifiedWidgetClient, type UnknownObject, type UseWaniwaniOptions, type UserAgent, type WaniwaniWidget, type WidgetPlatform, WidgetProvider, detectPlatform, getMockState, initializeMockOpenAI, isMCPApps, isOpenAI, updateMockDisplayMode, updateMockGlobal, updateMockTheme, updateMockToolOutput, useCallTool, useDisplayMode, useFlowAction, useIsChatGptApp, useLocale, useMaxHeight, useOpenExternal, useRequestDisplayMode, useSafeArea, useSendFollowUp, useTheme, useToolOutput, useToolResponseMetadata, useUpdateModelContext, useWaniwani, useWidgetClient, useWidgetState };
|
package/dist/mcp/react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as Y,b as be,c as ke}from"../chunk-DP6SAQTK.js";import{b as P,c as Ce}from"../chunk-RZKVTH7F.js";import{Fragment as Xe,jsx as H,jsxs as qe}from"react/jsx-runtime";function $e(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(p=>{p.forEach(m=>{if(m.type==="attributes"&&m.target===n){let u=m.attributeName;u&&u!=="suppresshydrationwarning"&&u!=="lang"&&u!=="class"&&u!=="style"&&n.removeAttribute(u)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let i=history.replaceState.bind(history);history.replaceState=(p,m,u)=>{try{let r=new URL(String(u??""),window.location.href);i(null,m,r.pathname+r.search+r.hash)}catch{}};let c=history.pushState.bind(history);history.pushState=(p,m,u)=>{try{let r=new URL(String(u??""),window.location.href);c(null,m,r.pathname+r.search+r.hash)}catch{}};let h=new URL(e).origin,x=window.self!==window.top;if(window.addEventListener("click",p=>{let m=p?.target?.closest("a");if(!m||!m.href)return;let u=new URL(m.href,window.location.href);if(u.origin!==window.location.origin&&u.origin!==h)try{window.openai&&(window.openai?.openExternal({href:m.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),x&&window.location.origin!==h){let p=window.fetch;window.fetch=((o,d)=>{let g=typeof o=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(o)&&!o.startsWith("//"),l;if(typeof o=="string"||o instanceof URL?l=new URL(o,window.location.href):l=new URL(o.url,window.location.href),l.origin===h)return typeof o=="string"||o instanceof URL?o=l.toString():o=new Request(l.toString(),o),p.call(window,o,{...d,mode:"cors"});if(t.indexOf(l.origin)!==-1)return p.call(window,o,d);if(g&&l.origin===window.location.origin){let y=new URL(e);return y.pathname=l.pathname,y.search=l.search,y.hash=l.hash,l=y,o=l.toString(),p.call(window,o,{...d,mode:"cors"})}return p.call(window,o,d)});let m=h.replace(/^http/,"ws"),u=window.WebSocket,r=((o,d)=>{let g=new URL(String(o),window.location.href);if(g.origin===window.location.origin||g.origin===window.location.origin.replace(/^http/,"ws")){let l=new URL(m);return l.pathname=g.pathname,l.search=g.search,l.hash=g.hash,new u(l.toString(),d)}return new u(o,d)});r.prototype=u.prototype,Object.assign(r,{CONNECTING:u.CONNECTING,OPEN:u.OPEN,CLOSING:u.CLOSING,CLOSED:u.CLOSED}),window.WebSocket=r}}var Je=`(${$e.toString()})()`;function Me({baseUrl:e,passthroughOrigins:t}){return qe(Xe,{children:[H("base",{href:e}),H("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),H("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),H("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),H("script",{children:Je})]})}import{useCallback as T,useEffect as D,useRef as Z,useState as C}from"react";var Se={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={...Se};function I(e){typeof window>"u"||window.openai||(B={...Se,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 j(){return{...B}}function N(e){R("toolOutput",e)}function L(e){R("displayMode",e)}function U(e){R("theme",e)}import{Fragment as Q,jsx as a,jsxs as v}from"react/jsx-runtime";var $=150;function Te({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[a("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),a("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function Ze({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:a("path",{d:"M18 6L6 18M6 6l12 12"})})}function Qe({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function et({className:e}){return v("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),a("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function tt({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("path",{d:"M2 5.5V3.5C2 2.95 2.45 2.5 3 2.5H5.5M10.5 2.5H13C13.55 2.5 14 2.95 14 3.5V5.5M14 10.5V12.5C14 13.05 13.55 13.5 13 13.5H10.5M5.5 13.5H3C2.45 13.5 2 13.05 2 12.5V10.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function nt({className:e}){return v("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),a("path",{d:"M8 2v1.5M8 12.5V14M2 8h1.5M12.5 8H14M4.11 4.11l1.06 1.06M10.83 10.83l1.06 1.06M4.11 11.89l1.06-1.06M10.83 5.17l1.06-1.06",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]})}function ot({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("path",{d:"M13.5 9.5a5.5 5.5 0 01-7-7 5.5 5.5 0 107 7z",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function it({className:e}){return v("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("path",{d:"M2.5 8a5.5 5.5 0 019.37-3.9M13.5 8a5.5 5.5 0 01-9.37 3.9",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"}),a("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var rt=`
|
|
3
3
|
@keyframes devPanelSlideIn {
|
|
4
4
|
0% {
|
|
5
5
|
opacity: 0;
|
|
@@ -47,22 +47,22 @@ import{a as re}from"../chunk-DGSC74SV.js";import{b as L,c as ie}from"../chunk-5O
|
|
|
47
47
|
.dev-json-editor::-webkit-scrollbar-thumb:hover {
|
|
48
48
|
background: rgba(255, 255, 255, 0.15);
|
|
49
49
|
}
|
|
50
|
-
`;function
|
|
50
|
+
`;function ee({defaultProps:e,widgetPaths:t,children:n}){let[s,i]=C(!1),[c,h]=C(!1);return D(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){i(!0);return}if(t&&t.length>0){let p=window.location.pathname,m=t.some(u=>p===u||p.startsWith(`${u}/`));h(m),m&&I(e)}else I(e),h(!0);i(!0)},[e,t]),s?c?v(Q,{children:[a(st,{children:n}),a(at,{defaultProps:e})]}):a(Q,{children:n}):null}function st({children:e}){return a("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:a("div",{className:"relative w-full max-w-md overflow-hidden rounded-2xl sm:rounded-3xl border border-[#414141]",style:{boxShadow:"0px 0px 0px 1px #414141, 0px 4px 14px rgba(0,0,0,0.24)"},children:e})})}function Ee({options:e,value:t,onChange:n}){let s=e.findIndex(i=>i.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:[a("div",{className:"absolute top-0.5 bottom-0.5 rounded-md transition-transform duration-150 ease-out",style:{width:`calc(${100/e.length}% - 2px)`,left:"2px",transform:`translateX(calc(${s*100}% + ${s*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(i=>v("button",{type:"button",onClick:()=>n(i.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
|
-
${t===
|
|
54
|
-
`,children:[
|
|
53
|
+
${t===i.value?"text-white":"text-gray-400 hover:text-gray-300"}
|
|
54
|
+
`,children:[i.icon,a("span",{className:"capitalize",children:i.label})]},i.value))]})}function at({defaultProps:e}){let[t,n]=C(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[s,i]=C(!1),[c,h]=C(t),[x,p]=C("inline"),[m,u]=C("dark"),[r,o]=C(!1),[d,g]=C(()=>JSON.stringify(e??{},null,2)),[l,y]=C(null),b=Z(null),E=Z(null),F=Z(null);D(()=>{let f=j();p(f.displayMode),u(f.theme)},[]),D(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:r?$:0,left:0,right:0}},window.dispatchEvent(new P({globals:{safeArea:window.openai.safeArea}})))},[r]),D(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let O=T(()=>{h(!0),requestAnimationFrame(()=>{n(!0)})},[]),W=T(()=>{i(!0),n(!1),setTimeout(()=>{h(!1),i(!1)},150)},[]),q=T(()=>{t?W():O()},[t,O,W]);D(()=>{let f=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="d"&&(k.preventDefault(),q()),k.key==="Escape"&&t&&W()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t,q,W]),D(()=>{if(!t)return;let f=k=>{F.current&&!F.current.contains(k.target)&&W()};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[t,W]);let Be=T(f=>{p(f),L(f)},[]),je=T(f=>{u(f),U(f)},[]),V=T(f=>{try{let k=JSON.parse(f);y(null),N(k)}catch{y("Invalid JSON")}},[]),Ke=T(f=>{g(f),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{V(f)},500)},[V]),ze=T(()=>{b.current&&clearTimeout(b.current),V(d)},[V,d]),Ge=T(()=>{let f=JSON.stringify(e??{},null,2);g(f),y(null),N(e??{}),p("inline"),L("inline"),u("dark"),U("dark")},[e]),Ve=[{value:"inline",label:"inline",icon:a(Qe,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:a(et,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:a(tt,{className:"w-3.5 h-3.5"})}],Ye=[{value:"light",label:"light",icon:a(nt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:a(ot,{className:"w-3.5 h-3.5"})}];return v(Q,{children:[a("style",{dangerouslySetInnerHTML:{__html:rt}}),v("div",{ref:F,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[v("button",{type:"button",onClick:q,className:"group relative flex items-center justify-center w-11 h-11 rounded-xl transition-all duration-200 ease-out hover:scale-105 active:scale-95",style:{background:"rgba(14, 14, 16, 0.95)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(255, 255, 255, 0.08)",boxShadow:`
|
|
55
55
|
0 4px 12px rgba(0, 0, 0, 0.4),
|
|
56
56
|
0 0 0 1px rgba(255, 255, 255, 0.05),
|
|
57
57
|
inset 0 1px 0 rgba(255, 255, 255, 0.04)
|
|
58
|
-
`},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[a(
|
|
58
|
+
`},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[a(Te,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),a("div",{className:"absolute inset-0 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",style:{background:"radial-gradient(circle at center, rgba(99, 102, 241, 0.15) 0%, transparent 70%)"}})]}),c&&v("div",{ref:E,className:`absolute bottom-14 right-0 w-80 ${t&&!s?"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:[a(ae,{className:"w-4 h-4 text-gray-400"}),a("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),v("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-[10px] font-medium text-gray-500 px-1.5 py-0.5 rounded",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:typeof navigator<"u"&&navigator.platform?.includes("Mac")?"\u2318\u21E7D":"Ctrl+Shift+D"}),a("button",{type:"button",onClick:_,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:a(Xe,{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:[a("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),a(le,{options:je,value:x,onChange:De})]}),v("div",{children:[a("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),a(le,{options:Ke,value:m,onChange:Fe})]}),v("div",{children:[a("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),v("button",{type:"button",onClick:()=>o(!i),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${i?"text-emerald-400":"text-gray-400"}`,style:{background:i?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:i?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[a("span",{children:"Mock ChatGPT Input Bar"}),a("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${i?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:i?"ON":"OFF"})]}),i&&v("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",G,"px"]})]}),v("div",{children:[a("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),a("textarea",{value:d,onChange:f=>Pe(f.target.value),onBlur:He,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:l?"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:f=>{l||(f.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:f=>{l||(f.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),l&&v("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[a("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:a("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),l]})]}),v("button",{type:"button",onClick:Be,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:f=>{f.currentTarget.style.background="rgba(255, 255, 255, 0.08)",f.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:f=>{f.currentTarget.style.background="rgba(255, 255, 255, 0.04)",f.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[a(tt,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),i&&v("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${G}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:[a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),a("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})})})]}),v("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",G,"px"]})]})]})}import{useCallback as lt}from"react";import j,{createContext as it,useCallback as ue,useContext as st,useEffect as pe,useState as Q,useSyncExternalStore as at}from"react";async function ce(){let{detectPlatform:e}=await import("../platform-GKYYQBCS.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-QAC3ZD5W.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-PUL4H54S.js");return new n}}var V=it(null);function ge({children:e,loading:t=null,onError:n}){let[s,r]=Q(null),[c,h]=Q(null),[x,p]=Q(!0);return pe(()=>{let m=!0,u=null;async function i(){try{let o=await ce();await o.connect(),m?(u=o,r(o),p(!1)):o.close()}catch(o){m&&(console.error("error",o),h(o instanceof Error?o:new Error(String(o))),p(!1))}}return i(),()=>{m=!1,u?.close()}},[]),pe(()=>{if(!s)return;let m=u=>{document.documentElement.classList.toggle("dark",u==="dark"),document.documentElement.style.colorScheme=u==="dark"?"dark":"auto"};return m(s.getTheme()),s.onThemeChange(m)},[s]),c&&n?j.createElement(j.Fragment,null,n(c)):x||!s?j.createElement(j.Fragment,null,t):j.createElement(V.Provider,{value:s},e)}function w(e){let t=st(V);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=ue(c=>e==="toolOutput"?t.onToolResult(()=>c()):e==="theme"?t.onThemeChange(()=>c()):e==="displayMode"?t.onDisplayModeChange(()=>c()):e==="safeArea"?t.onSafeAreaChange(()=>c()):e==="maxHeight"?t.onMaxHeightChange(()=>c()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>c()):e==="widgetState"?t.onWidgetStateChange(()=>c()):()=>{},[t,e]),s=ue(()=>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=at(n,s,s);return e?r:t}function me(){let e=w();return lt((t,n)=>e.callTool(t,n),[e])}function fe(){return w("displayMode")}function Y(){return w("toolOutput")}function he(){return{data:Y()}}import{useSyncExternalStore as dt}from"react";function we(){return dt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ve(){return w("locale")}function xe(){return w("maxHeight")}import{useCallback as ct}from"react";function ye(){let e=w();return ct(t=>e.openExternal(t),[e])}import{useCallback as ut}from"react";function be(){let e=w();return ut(t=>e.requestDisplayMode(t),[e])}function ke(){return w("safeArea")}import{useCallback as pt}from"react";function Ce(){let e=w();return pt((t,n)=>{(async()=>{ie(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(s=>{console.error("Failed to send follow-up message:",s)})},[e])}function Me(){return w("theme")}function Se(){return w("toolResponseMetadata")}import{useCallback as gt}from"react";function Te(){let e=w();return gt(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useContext as wt,useEffect as ne,useMemo as vt,useRef as Re,useState as Ae}from"react";function mt(){return crypto.randomUUID()}function M(e,t,n){return{event_id:mt(),event_type:t,timestamp:new Date().toISOString(),source:e.source??"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function ee(e){let t=e.trim().split(/\s+/),n=t[0]||"",s={};for(let r=1;r<t.length;r++){let c=t[r].indexOf(":");if(c===-1)continue;let h=t[r].slice(0,c),x=t[r].slice(c+1),p=Number(x);s[h]=Number.isFinite(p)&&x!==""?p:x}return{name:n,props:s}}function Ee(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function _e(e,t){let n=[],s=typeof navigator<"u"?navigator:void 0,r=s&&"connection"in s?s.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 c=i=>{t([M(e,"widget_error",{metadata:{error_message:i.message,error_stack:(i.error?.stack??"").slice(0,1024),error_source:i.filename??"unknown"}})])};window.addEventListener("error",c),n.push(()=>window.removeEventListener("error",c));let h=i=>{let o=i.reason,d=o instanceof Error?o.message:String(o),g=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:d,error_stack:g,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",h),n.push(()=>window.removeEventListener("unhandledrejection",h)),e.capture?.click){let i=o=>{let d=o.target,g=d?.closest?.("[data-ww-conversion],[data-ww-step]");if(g){let l=g.getAttribute("data-ww-conversion")??g.getAttribute("data-ww-step")??"";if(ee(l).name)return}t([M(e,"widget_click",{metadata:{target_tag:d?.tagName?.toLowerCase()??"unknown",target_id:d?.id||void 0,target_class:d?.className||void 0,click_x:o.clientX,click_y:o.clientY}})])};document.addEventListener("click",i,{capture:!0}),n.push(()=>document.removeEventListener("click",i,{capture:!0}))}let x=i=>{let d=i.target?.closest?.("[data-ww-conversion]");if(!d)return;let{name:g,props:l}=ee(d.getAttribute("data-ww-conversion")||"");g&&t([M(e,"conversion",{event_name:g,metadata:Object.keys(l).length>0?l:void 0})])};document.addEventListener("click",x,{capture:!0}),n.push(()=>document.removeEventListener("click",x,{capture:!0}));let p=0,m=i=>{let d=i.target?.closest?.("[data-ww-step]");if(!d)return;let{name:g,props:l}=ee(d.getAttribute("data-ww-step")||"");g&&(p++,t([M(e,"step",{event_name:g,step_sequence:p,metadata:Object.keys(l).length>0?l:void 0})]))};document.addEventListener("click",m,{capture:!0}),n.push(()=>document.removeEventListener("click",m,{capture:!0}));let u=i=>{let o=i.target?.closest?.("a");if(!o)return;let d=o.getAttribute("href")??"",g=d.startsWith("http")&&!d.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:d,link_text:(o.textContent??"").slice(0,200),is_external:g}})])};if(document.addEventListener("click",u,{capture:!0}),n.push(()=>document.removeEventListener("click",u,{capture:!0})),e.capture?.scroll){let i=null,o=window.scrollY||0,d=()=>{i||(i=setTimeout(()=>{i=null;let g=window.scrollY||document.documentElement.scrollTop,l=document.documentElement.scrollHeight-document.documentElement.clientHeight,y=l>0?Math.round(g/l*100):0,b=g>=o?"down":"up";o=g,t([M(e,"widget_scroll",{metadata:{scroll_depth_pct:y,scroll_direction:b,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",d,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",d),i&&clearTimeout(i)})}if(e.capture?.formField){let i=new WeakMap,o=g=>{let l=g.target;!l||!Ee(l)||i.set(l,Date.now())},d=g=>{let l=g.target;if(!l||!Ee(l))return;let y=i.get(l),b=y?Date.now()-y:0,E=l;t([M(e,"widget_form_field",{metadata:{field_name:E.name||E.id||void 0,field_type:E.type||l.tagName.toLowerCase(),time_in_field_ms:b,filled:!!E.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",d,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",d,{capture:!0})})}if(e.capture?.formSubmit){let i=new WeakMap,o=g=>{let y=g.target?.closest?.("form");y&&!i.has(y)&&i.set(y,Date.now())};document.addEventListener("focusin",o,{capture:!0}),n.push(()=>document.removeEventListener("focusin",o,{capture:!0}));let d=g=>{let l=g.target,y=l?i.get(l):void 0,b=0;if(l){let E=l.querySelectorAll("input, textarea, select");for(let I of E){let O=I;(O.validity&&!O.validity.valid||O.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:l?.id||void 0,time_to_submit_ms:y?Date.now()-y:void 0,validation_errors:b}})])};document.addEventListener("submit",d,{capture:!0}),n.push(()=>document.removeEventListener("submit",d,{capture:!0}))}return()=>{for(let i of n)i()}}var ft="@waniwani/sdk";function ht(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,s={};e.session_id&&(s.sessionId=e.session_id),e.trace_id&&(s.traceId=e.trace_id),e.user_id&&(s.externalUserId=e.user_id);let r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:s,properties:r,metadata:{}}}function te(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:ft,version:"0.1.0"},events:e.map(ht)})}var $=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,s){let r=te(n);if(r.length<=6e4){fetch(t,{method:"POST",headers:s,body:r,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let c=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,c),s),this.sendKeepAliveChunked(t,n.slice(c),s)}sendBeaconChunked(t,n){let s=te(n);if(s.length<=6e4){navigator.sendBeacon(t,new Blob([s],{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=te(t),s={"Content-Type":"application/json"};this.config.token&&(s.Authorization=`Bearer ${this.config.token}`);for(let r=0;r<=3;r++)try{let c=await fetch(this.config.endpoint,{method:"POST",headers:s,body:n});if(c.status===200||c.status===207)return;if(c.status===401){this.stopped=!0;return}if(c.status>=500&&r<3){await this.delay(1e3*2**r);continue}if(c.status===429&&r<3){let h=c.headers.get("Retry-After"),x=h?Number(h):NaN,p=Number.isFinite(x)?x*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 oe={identify(){},step(){},track(){},conversion(){}},S=null,X=0;function xt(){return crypto.randomUUID()}function W(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function yt(){return{widget:oe,cleanup:()=>{},config:null,captureKey:""}}function Oe(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function We(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,s=t.waniwani??n?.waniwani,r=W(s?.endpoint);return r?{endpoint:r,token:W(s?.token),sessionId:W(s?.sessionId),source:W(s?.source)}:null}function Ne(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function bt(e){let[t,n]=Ae(()=>We(e));return ne(()=>{if(!e){n(r=>r===null?r:null);return}let s=()=>{let r=We(e);n(c=>Ne(c,r)?c:r)};return s(),e.onToolResponseMetadataChange(()=>{s()})},[e]),t}function kt(e,t,n){let s=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),c=new $({endpoint:e.endpoint,token:e.token,metadata:t}),h,x=0,p=o=>{c.send(o)},m=e.source??"widget",u=_e({sessionId:s,traceId:r,metadata:t,source:m,capture:n},p);function i(o,d){return{event_id:xt(),event_type:o,timestamp:new Date().toISOString(),source:m,session_id:s,trace_id:r,user_id:h,...d}}return{captureKey:Oe(n),widget:{identify(o,d){h=o,p([i("identify",{user_id:o,user_traits:d})])},step(o,d){x++,p([i("step",{event_name:o,step_sequence:x,metadata:d})])},track(o,d){p([i("track",{event_name:o,metadata:d})])},conversion(o,d){p([i("conversion",{event_name:o,metadata:d})])}},cleanup:()=>{u(),c.stop()},config:e}}function Ie(e={}){let t=wt(V),n=bt(t),s=W(e.endpoint),r=W(e.token),c=W(e.sessionId),h=vt(()=>s?{endpoint:s,token:r??n?.token,sessionId:c??n?.sessionId,source:n?.source}:n,[s,r,c,n]),[x,p]=Ae(oe),m=Re(e.metadata);m.current=e.metadata;let u=Re(e.capture);u.current=e.capture;let i=Oe(e.capture);return ne(()=>(X++,()=>{X=Math.max(X-1,0),X===0&&(S?.cleanup(),S=null)}),[]),ne(()=>{if(!(typeof window>"u")){if(!h){S?.config&&(S.cleanup(),S=yt(),p(oe));return}(!Ne(S?.config,h)||S?.captureKey!==i)&&(S?.cleanup(),S=kt(h,m.current,u.current),p(S.widget))}},[h,i]),x}import{useCallback as Ct,useEffect as Mt,useState as St}from"react";function Le(e){let t=w("widgetState"),[n,s]=St(()=>t??(typeof e=="function"?e():e??null));Mt(()=>{s(t)},[t]);let r=Ct(c=>{s(h=>{let x=typeof c=="function"?c(h):c;return re()==="openai"&&x!=null&&window.openai?.setWidgetState(x),x})},[]);return[n,r]}import{jsx as A,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:[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:[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:[a(Te,{className:"w-4 h-4 text-gray-400"}),a("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),v("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-[10px] font-medium text-gray-500 px-1.5 py-0.5 rounded",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:typeof navigator<"u"&&navigator.platform?.includes("Mac")?"\u2318\u21E7D":"Ctrl+Shift+D"}),a("button",{type:"button",onClick:W,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:a(Ze,{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:[a("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),a(Ee,{options:Ve,value:x,onChange:Be})]}),v("div",{children:[a("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),a(Ee,{options:Ye,value:m,onChange:je})]}),v("div",{children:[a("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),v("button",{type:"button",onClick:()=>o(!r),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${r?"text-emerald-400":"text-gray-400"}`,style:{background:r?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:r?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[a("span",{children:"Mock ChatGPT Input Bar"}),a("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${r?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:r?"ON":"OFF"})]}),r&&v("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",$,"px"]})]}),v("div",{children:[a("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),a("textarea",{value:d,onChange:f=>Ke(f.target.value),onBlur:ze,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:l?"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:f=>{l||(f.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:f=>{l||(f.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),l&&v("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[a("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:a("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),l]})]}),v("button",{type:"button",onClick:Ge,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:f=>{f.currentTarget.style.background="rgba(255, 255, 255, 0.08)",f.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:f=>{f.currentTarget.style.background="rgba(255, 255, 255, 0.04)",f.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[a(it,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),r&&v("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:[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:[a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),a("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})})})]}),v("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",$,"px"]})]})]})}import{useCallback as ut}from"react";import z,{useCallback as We,useContext as dt,useEffect as _e,useState as te,useSyncExternalStore as ct}from"react";import{createContext as lt}from"react";var K=lt(null);async function Re(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-TZIOCMXP.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-OFYMQOI3.js");return new n}}function ne({children:e,loading:t=null,onError:n}){let[s,i]=te(null),[c,h]=te(null),[x,p]=te(!0);return _e(()=>{let m=!0,u=null;async function r(){try{let o=await Re();await o.connect(),m?(u=o,i(o),p(!1)):o.close()}catch(o){m&&(console.error("error",o),h(o instanceof Error?o:new Error(String(o))),p(!1))}}return r(),()=>{m=!1,u?.close()}},[]),_e(()=>{if(!s)return;let m=u=>{document.documentElement.classList.toggle("dark",u==="dark"),document.documentElement.style.colorScheme=u==="dark"?"dark":"auto"};return m(s.getTheme()),s.onThemeChange(m)},[s]),c&&n?z.createElement(z.Fragment,null,n(c)):x||!s?z.createElement(z.Fragment,null,t):z.createElement(K.Provider,{value:s},e)}function w(e){let t=dt(K);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=We(c=>e==="toolOutput"?t.onToolResult(()=>c()):e==="theme"?t.onThemeChange(()=>c()):e==="displayMode"?t.onDisplayModeChange(()=>c()):e==="safeArea"?t.onSafeAreaChange(()=>c()):e==="maxHeight"?t.onMaxHeightChange(()=>c()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>c()):e==="widgetState"?t.onWidgetStateChange(()=>c()):()=>{},[t,e]),s=We(()=>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]),i=ct(n,s,s);return e?i:t}function oe(){let e=w();return ut((t,n)=>e.callTool(t,n),[e])}function ie(){return w("displayMode")}function G(){return w("toolOutput")}function re(){return{data:G()}}import{useSyncExternalStore as pt}from"react";function se(){return pt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ae(){return w("locale")}function le(){return w("maxHeight")}import{useCallback as gt}from"react";function de(){let e=w();return gt(t=>e.openExternal(t),[e])}import{useCallback as mt}from"react";function ce(){let e=w();return mt(t=>e.requestDisplayMode(t),[e])}function ue(){return w("safeArea")}import{useCallback as ft}from"react";function pe(){let e=w();return ft((t,n)=>{(async()=>{Ce(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(s=>{console.error("Failed to send follow-up message:",s)})},[e])}function ge(){return w("theme")}function me(){return w("toolResponseMetadata")}import{useCallback as ht}from"react";function fe(){let e=w();return ht(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as wt,useEffect as vt,useState as xt}from"react";function he(e){let t=w("widgetState"),[n,s]=xt(()=>t??(typeof e=="function"?e():e??null));vt(()=>{s(t)},[t]);let i=wt(c=>{s(h=>{let x=typeof c=="function"?c(h):c;return Y()==="openai"&&x!=null&&window.openai?.setWidgetState(x),x})},[]);return[n,i]}import{jsx as _,jsxs as Ae}from"react/jsx-runtime";var Oe=()=>Ae("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Ae("div",{className:"flex gap-2",children:[_("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),_("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),_("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),_("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..."}),_("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:_("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),_("style",{children:`
|
|
63
63
|
@keyframes shimmer {
|
|
64
64
|
0% { background-position: 200% 0; }
|
|
65
65
|
100% { background-position: -200% 0; }
|
|
66
66
|
}
|
|
67
|
-
`})]});export{de as DevModeProvider,Ve as InitializeNextJsInIframe,Tt as LoadingWidget,ge as WidgetProvider,z as getMockState,F as initializeMockOpenAI,H as updateMockDisplayMode,R as updateMockGlobal,B as updateMockTheme,P as updateMockToolOutput,me as useCallTool,fe as useDisplayMode,he as useFlowAction,we as useIsChatGptApp,ve as useLocale,xe as useMaxHeight,ye as useOpenExternal,be as useRequestDisplayMode,ke as useSafeArea,Ce as useSendFollowUp,Me as useTheme,Y as useToolOutput,Se as useToolResponseMetadata,Te as useUpdateModelContext,Ie as useWaniwani,w as useWidgetClient,Le as useWidgetState};
|
|
67
|
+
`})]});import{useContext as Ct,useEffect as xe,useMemo as Mt,useRef as Le,useState as De}from"react";function yt(){return crypto.randomUUID()}function M(e,t,n){return{event_id:yt(),event_type:t,timestamp:new Date().toISOString(),source:e.source??"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function we(e){let t=e.trim().split(/\s+/),n=t[0]||"",s={};for(let i=1;i<t.length;i++){let c=t[i].indexOf(":");if(c===-1)continue;let h=t[i].slice(0,c),x=t[i].slice(c+1),p=Number(x);s[h]=Number.isFinite(p)&&x!==""?p:x}return{name:n,props:s}}function Ie(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function Ne(e,t){let n=[],s=typeof navigator<"u"?navigator:void 0,i=s&&"connection"in s?s.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:i?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let c=r=>{t([M(e,"widget_error",{metadata:{error_message:r.message,error_stack:(r.error?.stack??"").slice(0,1024),error_source:r.filename??"unknown"}})])};window.addEventListener("error",c),n.push(()=>window.removeEventListener("error",c));let h=r=>{let o=r.reason,d=o instanceof Error?o.message:String(o),g=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:d,error_stack:g,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",h),n.push(()=>window.removeEventListener("unhandledrejection",h)),e.capture?.click){let r=o=>{let d=o.target,g=d?.closest?.("[data-ww-conversion],[data-ww-step]");if(g){let l=g.getAttribute("data-ww-conversion")??g.getAttribute("data-ww-step")??"";if(we(l).name)return}t([M(e,"widget_click",{metadata:{target_tag:d?.tagName?.toLowerCase()??"unknown",target_id:d?.id||void 0,target_class:d?.className||void 0,click_x:o.clientX,click_y:o.clientY}})])};document.addEventListener("click",r,{capture:!0}),n.push(()=>document.removeEventListener("click",r,{capture:!0}))}let x=r=>{let d=r.target?.closest?.("[data-ww-conversion]");if(!d)return;let{name:g,props:l}=we(d.getAttribute("data-ww-conversion")||"");g&&t([M(e,"conversion",{event_name:g,metadata:Object.keys(l).length>0?l:void 0})])};document.addEventListener("click",x,{capture:!0}),n.push(()=>document.removeEventListener("click",x,{capture:!0}));let p=0,m=r=>{let d=r.target?.closest?.("[data-ww-step]");if(!d)return;let{name:g,props:l}=we(d.getAttribute("data-ww-step")||"");g&&(p++,t([M(e,"step",{event_name:g,step_sequence:p,metadata:Object.keys(l).length>0?l:void 0})]))};document.addEventListener("click",m,{capture:!0}),n.push(()=>document.removeEventListener("click",m,{capture:!0}));let u=r=>{let o=r.target?.closest?.("a");if(!o)return;let d=o.getAttribute("href")??"",g=d.startsWith("http")&&!d.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:d,link_text:(o.textContent??"").slice(0,200),is_external:g}})])};if(document.addEventListener("click",u,{capture:!0}),n.push(()=>document.removeEventListener("click",u,{capture:!0})),e.capture?.scroll){let r=null,o=window.scrollY||0,d=()=>{r||(r=setTimeout(()=>{r=null;let g=window.scrollY||document.documentElement.scrollTop,l=document.documentElement.scrollHeight-document.documentElement.clientHeight,y=l>0?Math.round(g/l*100):0,b=g>=o?"down":"up";o=g,t([M(e,"widget_scroll",{metadata:{scroll_depth_pct:y,scroll_direction:b,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",d,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",d),r&&clearTimeout(r)})}if(e.capture?.formField){let r=new WeakMap,o=g=>{let l=g.target;!l||!Ie(l)||r.set(l,Date.now())},d=g=>{let l=g.target;if(!l||!Ie(l))return;let y=r.get(l),b=y?Date.now()-y:0,E=l;t([M(e,"widget_form_field",{metadata:{field_name:E.name||E.id||void 0,field_type:E.type||l.tagName.toLowerCase(),time_in_field_ms:b,filled:!!E.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",d,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",d,{capture:!0})})}if(e.capture?.formSubmit){let r=new WeakMap,o=g=>{let y=g.target?.closest?.("form");y&&!r.has(y)&&r.set(y,Date.now())};document.addEventListener("focusin",o,{capture:!0}),n.push(()=>document.removeEventListener("focusin",o,{capture:!0}));let d=g=>{let l=g.target,y=l?r.get(l):void 0,b=0;if(l){let E=l.querySelectorAll("input, textarea, select");for(let F of E){let O=F;(O.validity&&!O.validity.valid||O.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:l?.id||void 0,time_to_submit_ms:y?Date.now()-y:void 0,validation_errors:b}})])};document.addEventListener("submit",d,{capture:!0}),n.push(()=>document.removeEventListener("submit",d,{capture:!0}))}return()=>{for(let r of n)r()}}var bt="@waniwani/sdk";function kt(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,s={};e.session_id&&(s.sessionId=e.session_id),e.trace_id&&(s.traceId=e.trace_id),e.user_id&&(s.externalUserId=e.user_id);let i={...e.metadata??{}};return e.event_name&&(i.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:s,properties:i,metadata:{}}}function ve(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:bt,version:"0.1.0"},events:e.map(kt)})}var J=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,s){let i=ve(n);if(i.length<=6e4){fetch(t,{method:"POST",headers:s,body:i,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let c=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,c),s),this.sendKeepAliveChunked(t,n.slice(c),s)}sendBeaconChunked(t,n){let s=ve(n);if(s.length<=6e4){navigator.sendBeacon(t,new Blob([s],{type:"application/json"}));return}if(n.length<=1)return;let i=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,i)),this.sendBeaconChunked(t,n.slice(i))}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=ve(t),s={"Content-Type":"application/json"};this.config.token&&(s.Authorization=`Bearer ${this.config.token}`);for(let i=0;i<=3;i++)try{let c=await fetch(this.config.endpoint,{method:"POST",headers:s,body:n});if(c.status===200||c.status===207)return;if(c.status===401){this.stopped=!0;return}if(c.status>=500&&i<3){await this.delay(1e3*2**i);continue}if(c.status===429&&i<3){let h=c.headers.get("Retry-After"),x=h?Number(h):NaN,p=Number.isFinite(x)?x*1e3:1e3*2**i;await this.delay(p);continue}return}catch{if(i<3){await this.delay(1e3*2**i);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var ye={identify(){},step(){},track(){},conversion(){}},S=null,X=0;function St(){return crypto.randomUUID()}function A(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Tt(){return{widget:ye,cleanup:()=>{},config:null,captureKey:""}}function Fe(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Ue(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,s=t.waniwani??n?.waniwani,i=A(s?.endpoint);return i?{endpoint:i,token:A(s?.token),sessionId:A(s?.sessionId),source:A(s?.source)}:null}function Pe(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function Et(e){let[t,n]=De(()=>Ue(e));return xe(()=>{if(!e){n(i=>i===null?i:null);return}let s=()=>{let i=Ue(e);n(c=>Pe(c,i)?c:i)};return s(),e.onToolResponseMetadataChange(()=>{s()})},[e]),t}function Rt(e,t,n){let s=e.sessionId??crypto.randomUUID(),i=crypto.randomUUID(),c=new J({endpoint:e.endpoint,token:e.token,metadata:t}),h,x=0,p=o=>{c.send(o)},m=e.source??"widget",u=Ne({sessionId:s,traceId:i,metadata:t,source:m,capture:n},p);function r(o,d){return{event_id:St(),event_type:o,timestamp:new Date().toISOString(),source:m,session_id:s,trace_id:i,user_id:h,...d}}return{captureKey:Fe(n),widget:{identify(o,d){h=o,p([r("identify",{user_id:o,user_traits:d})])},step(o,d){x++,p([r("step",{event_name:o,step_sequence:x,metadata:d})])},track(o,d){p([r("track",{event_name:o,metadata:d})])},conversion(o,d){p([r("conversion",{event_name:o,metadata:d})])}},cleanup:()=>{u(),c.stop()},config:e}}function He(e={}){let t=Ct(K),n=Et(t),s=A(e.endpoint),i=A(e.token),c=A(e.sessionId),h=Mt(()=>s?{endpoint:s,token:i??n?.token,sessionId:c??n?.sessionId,source:n?.source}:n,[s,i,c,n]),[x,p]=De(ye),m=Le(e.metadata);m.current=e.metadata;let u=Le(e.capture);u.current=e.capture;let r=Fe(e.capture);return xe(()=>(X++,()=>{X=Math.max(X-1,0),X===0&&(S?.cleanup(),S=null)}),[]),xe(()=>{if(!(typeof window>"u")){if(!h){S?.config&&(S.cleanup(),S=Tt(),p(ye));return}(!Pe(S?.config,h)||S?.captureKey!==r)&&(S?.cleanup(),S=Rt(h,m.current,u.current),p(S.widget))}},[h,r]),x}export{ee as DevModeProvider,Me as InitializeNextJsInIframe,Oe as LoadingWidget,ne as WidgetProvider,Y as detectPlatform,j as getMockState,I as initializeMockOpenAI,ke as isMCPApps,be as isOpenAI,L as updateMockDisplayMode,R as updateMockGlobal,U as updateMockTheme,N as updateMockToolOutput,oe as useCallTool,ie as useDisplayMode,re as useFlowAction,se as useIsChatGptApp,ae as useLocale,le as useMaxHeight,de as useOpenExternal,ce as useRequestDisplayMode,ue as useSafeArea,pe as useSendFollowUp,ge as useTheme,G as useToolOutput,me as useToolResponseMetadata,fe as useUpdateModelContext,He as useWaniwani,w as useWidgetClient,he as useWidgetState};
|
|
68
68
|
//# sourceMappingURL=react.js.map
|