@maxaiagent/widget-sdk 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/index.d.mts +121 -14
- package/dist/index.d.ts +121 -14
- package/dist/index.global.js +28 -15
- package/dist/index.js +28 -15
- package/dist/index.mjs +28 -15
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -76,7 +76,8 @@ Rejestruje narzędzie po stronie klienta. Agent AI może je wywoływać w trakci
|
|
|
76
76
|
|
|
77
77
|
```typescript
|
|
78
78
|
const unregister = widget.registerTool({
|
|
79
|
-
|
|
79
|
+
slug: 'add_to_cart',
|
|
80
|
+
name: 'Dodaj do koszyka',
|
|
80
81
|
description: 'Dodaje produkt do koszyka użytkownika',
|
|
81
82
|
schema: {
|
|
82
83
|
type: 'object',
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal JSON Schema Draft-07 type — inlined to avoid adding @types/json-schema dependency.
|
|
3
|
+
* Covers the subset used by tool definitions (properties, required, type, enum, etc.).
|
|
4
|
+
*/
|
|
5
|
+
interface JSONSchema7 {
|
|
6
|
+
$id?: string;
|
|
7
|
+
$ref?: string;
|
|
8
|
+
$schema?: string;
|
|
9
|
+
$comment?: string;
|
|
10
|
+
type?: JSONSchema7TypeName | JSONSchema7TypeName[];
|
|
11
|
+
enum?: unknown[];
|
|
12
|
+
const?: unknown;
|
|
13
|
+
multipleOf?: number;
|
|
14
|
+
maximum?: number;
|
|
15
|
+
exclusiveMaximum?: number;
|
|
16
|
+
minimum?: number;
|
|
17
|
+
exclusiveMinimum?: number;
|
|
18
|
+
maxLength?: number;
|
|
19
|
+
minLength?: number;
|
|
20
|
+
pattern?: string;
|
|
21
|
+
format?: string;
|
|
22
|
+
items?: JSONSchema7 | JSONSchema7[];
|
|
23
|
+
additionalItems?: JSONSchema7 | boolean;
|
|
24
|
+
maxItems?: number;
|
|
25
|
+
minItems?: number;
|
|
26
|
+
uniqueItems?: boolean;
|
|
27
|
+
contains?: JSONSchema7;
|
|
28
|
+
maxProperties?: number;
|
|
29
|
+
minProperties?: number;
|
|
30
|
+
required?: string[];
|
|
31
|
+
properties?: Record<string, JSONSchema7>;
|
|
32
|
+
patternProperties?: Record<string, JSONSchema7>;
|
|
33
|
+
additionalProperties?: JSONSchema7 | boolean;
|
|
34
|
+
propertyNames?: JSONSchema7;
|
|
35
|
+
if?: JSONSchema7;
|
|
36
|
+
then?: JSONSchema7;
|
|
37
|
+
else?: JSONSchema7;
|
|
38
|
+
allOf?: JSONSchema7[];
|
|
39
|
+
anyOf?: JSONSchema7[];
|
|
40
|
+
oneOf?: JSONSchema7[];
|
|
41
|
+
not?: JSONSchema7;
|
|
42
|
+
title?: string;
|
|
43
|
+
description?: string;
|
|
44
|
+
default?: unknown;
|
|
45
|
+
readOnly?: boolean;
|
|
46
|
+
writeOnly?: boolean;
|
|
47
|
+
examples?: unknown[];
|
|
48
|
+
definitions?: Record<string, JSONSchema7>;
|
|
49
|
+
}
|
|
50
|
+
type JSONSchema7TypeName = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
|
|
51
|
+
|
|
1
52
|
interface MaxAIInitOptions {
|
|
2
53
|
/** Widget key from MaxAI dashboard */
|
|
3
54
|
key: string;
|
|
@@ -23,20 +74,37 @@ interface PageContext {
|
|
|
23
74
|
mainContent?: string;
|
|
24
75
|
lang?: string;
|
|
25
76
|
}
|
|
26
|
-
|
|
27
|
-
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Generic tool definition.
|
|
80
|
+
*
|
|
81
|
+
* @typeParam TArgs - Shape of arguments the handler receives (inferred from usage)
|
|
82
|
+
* @typeParam TResult - Return type of the handler
|
|
83
|
+
* @typeParam TSchema - JSON Schema type (defaults to JSONSchema7)
|
|
84
|
+
* @typeParam TContext - Extra context passed to the AI agent alongside the tool description
|
|
85
|
+
*/
|
|
86
|
+
interface ToolDefinition<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown, TSchema extends JSONSchema7 = JSONSchema7, TContext extends Record<string, unknown> = Record<string, unknown>> {
|
|
87
|
+
/** Machine identifier — stable, used in API/events/logic. Must match /^[a-z0-9_]+$/ */
|
|
88
|
+
slug: string;
|
|
89
|
+
/** Human-readable label shown to the user in the widget UI */
|
|
28
90
|
name: string;
|
|
29
|
-
/**
|
|
91
|
+
/** Description for the AI agent */
|
|
30
92
|
description: string;
|
|
31
|
-
/** JSON Schema
|
|
32
|
-
schema:
|
|
93
|
+
/** JSON Schema (draft-07) describing the tool's arguments */
|
|
94
|
+
schema: TSchema;
|
|
95
|
+
/**
|
|
96
|
+
* Extra context sent to the AI model alongside the tool description.
|
|
97
|
+
* Use for: UI constraints, domain rules, preferred data formats, agent hints.
|
|
98
|
+
*/
|
|
99
|
+
context?: TContext;
|
|
33
100
|
/** Function that executes when the agent calls this tool */
|
|
34
|
-
handler: (args:
|
|
101
|
+
handler: (args: TArgs) => TResult | Promise<TResult>;
|
|
35
102
|
/** If true, widget shows confirmation dialog before executing */
|
|
36
103
|
requiresConfirmation?: boolean;
|
|
37
|
-
/** Tool category for grouping */
|
|
104
|
+
/** Tool category for grouping in the UI */
|
|
38
105
|
category?: string;
|
|
39
106
|
}
|
|
107
|
+
|
|
40
108
|
interface ChatMessage {
|
|
41
109
|
role: "user" | "assistant";
|
|
42
110
|
content: string;
|
|
@@ -68,13 +136,47 @@ type WidgetEventMap = {
|
|
|
68
136
|
error: ErrorEvent;
|
|
69
137
|
};
|
|
70
138
|
type WidgetEvent = keyof WidgetEventMap;
|
|
139
|
+
/**
|
|
140
|
+
* Signed identity payload for widget-embedded platforms.
|
|
141
|
+
* Allows host platforms to pass their logged-in user's identity to the agent.
|
|
142
|
+
*/
|
|
143
|
+
interface IdentityPayload {
|
|
144
|
+
/** Unique slug identifying the host platform (e.g. "billing_app", "crm") */
|
|
145
|
+
platform_slug: string;
|
|
146
|
+
/** UID of the logged-in user on the host platform */
|
|
147
|
+
platform_user_uid: string;
|
|
148
|
+
/** Optional: UID of the organization/account on the host platform */
|
|
149
|
+
platform_account_uid?: string;
|
|
150
|
+
/** Display name of the user */
|
|
151
|
+
display_name?: string;
|
|
152
|
+
/** Verified email address */
|
|
153
|
+
email?: string;
|
|
154
|
+
/** Verified phone number (E.164 preferred) */
|
|
155
|
+
phone?: string;
|
|
156
|
+
/** User locale (e.g. "pl-PL") */
|
|
157
|
+
locale?: string;
|
|
158
|
+
/** Arbitrary traits (plan, role, etc.) */
|
|
159
|
+
traits?: Record<string, unknown>;
|
|
160
|
+
/** ISO 8601 timestamp when the signature was created */
|
|
161
|
+
signed_at?: string;
|
|
162
|
+
/** ISO 8601 timestamp when the signature expires (recommended: 5 min) */
|
|
163
|
+
expires_at?: string;
|
|
164
|
+
/** HMAC-SHA256 hex signature: HMAC(signing_secret, platform_user_uid + signed_at) */
|
|
165
|
+
signature?: string;
|
|
166
|
+
}
|
|
71
167
|
interface WidgetInstance {
|
|
72
168
|
/** Send explicit page context to the widget */
|
|
73
169
|
setPageContext(ctx: Partial<PageContext>): void;
|
|
170
|
+
/**
|
|
171
|
+
* Set the identity of the logged-in user on the host platform.
|
|
172
|
+
* When signing_secret is configured on the widget key, include a valid HMAC-SHA256 signature
|
|
173
|
+
* to get "confirmed" trust level. Without a signature the identity is treated as "likely".
|
|
174
|
+
*/
|
|
175
|
+
setIdentity(payload: IdentityPayload): void;
|
|
74
176
|
/** Register a client-side tool. Returns unregister function. */
|
|
75
|
-
registerTool(def: ToolDefinition): () => void;
|
|
76
|
-
/** Unregister a tool by
|
|
77
|
-
unregisterTool(
|
|
177
|
+
registerTool<TArgs extends Record<string, unknown>, TResult, TSchema extends JSONSchema7, TContext extends Record<string, unknown>>(def: ToolDefinition<TArgs, TResult, TSchema, TContext>): () => void;
|
|
178
|
+
/** Unregister a tool by slug */
|
|
179
|
+
unregisterTool(slug: string): void;
|
|
78
180
|
/** Subscribe to widget events. Returns unsubscribe function. */
|
|
79
181
|
on<E extends WidgetEvent>(event: E, callback: WidgetEventMap[E] extends void ? () => void : (data: WidgetEventMap[E]) => void): () => void;
|
|
80
182
|
/** Unsubscribe from widget events */
|
|
@@ -110,15 +212,20 @@ declare const MaxAI: {
|
|
|
110
212
|
* Set page context (shorthand — delegates to active instance).
|
|
111
213
|
*/
|
|
112
214
|
setPageContext(ctx: Partial<PageContext>): void;
|
|
215
|
+
/**
|
|
216
|
+
* Set the identity of the logged-in user on the host platform (shorthand).
|
|
217
|
+
* Pass a signed payload (HMAC-SHA256) to get confirmed trust level.
|
|
218
|
+
*/
|
|
219
|
+
setIdentity(payload: IdentityPayload): void;
|
|
113
220
|
/**
|
|
114
221
|
* Register a client-side tool (shorthand — delegates to active instance).
|
|
115
222
|
* Returns an unregister function.
|
|
116
223
|
*/
|
|
117
|
-
registerTool(def: ToolDefinition): () => void;
|
|
224
|
+
registerTool<TArgs extends Record<string, unknown>, TResult, TSchema extends JSONSchema7, TContext extends Record<string, unknown>>(def: ToolDefinition<TArgs, TResult, TSchema, TContext>): () => void;
|
|
118
225
|
/**
|
|
119
|
-
* Unregister a tool by
|
|
226
|
+
* Unregister a tool by slug.
|
|
120
227
|
*/
|
|
121
|
-
unregisterTool(
|
|
228
|
+
unregisterTool(slug: string): void;
|
|
122
229
|
/**
|
|
123
230
|
* Subscribe to events.
|
|
124
231
|
*/
|
|
@@ -139,4 +246,4 @@ declare const MaxAI: {
|
|
|
139
246
|
_initialized: boolean;
|
|
140
247
|
};
|
|
141
248
|
|
|
142
|
-
export { type ChatMessage, type ErrorEvent, MaxAI, type MaxAIInitOptions, type PageContext, type ToolCallEvent, type ToolDefinition, type ToolResultEvent, type WidgetEvent, type WidgetEventMap, type WidgetInstance };
|
|
249
|
+
export { type ChatMessage, type ErrorEvent, type IdentityPayload, type JSONSchema7, MaxAI, type MaxAIInitOptions, type PageContext, type ToolCallEvent, type ToolDefinition, type ToolResultEvent, type WidgetEvent, type WidgetEventMap, type WidgetInstance };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal JSON Schema Draft-07 type — inlined to avoid adding @types/json-schema dependency.
|
|
3
|
+
* Covers the subset used by tool definitions (properties, required, type, enum, etc.).
|
|
4
|
+
*/
|
|
5
|
+
interface JSONSchema7 {
|
|
6
|
+
$id?: string;
|
|
7
|
+
$ref?: string;
|
|
8
|
+
$schema?: string;
|
|
9
|
+
$comment?: string;
|
|
10
|
+
type?: JSONSchema7TypeName | JSONSchema7TypeName[];
|
|
11
|
+
enum?: unknown[];
|
|
12
|
+
const?: unknown;
|
|
13
|
+
multipleOf?: number;
|
|
14
|
+
maximum?: number;
|
|
15
|
+
exclusiveMaximum?: number;
|
|
16
|
+
minimum?: number;
|
|
17
|
+
exclusiveMinimum?: number;
|
|
18
|
+
maxLength?: number;
|
|
19
|
+
minLength?: number;
|
|
20
|
+
pattern?: string;
|
|
21
|
+
format?: string;
|
|
22
|
+
items?: JSONSchema7 | JSONSchema7[];
|
|
23
|
+
additionalItems?: JSONSchema7 | boolean;
|
|
24
|
+
maxItems?: number;
|
|
25
|
+
minItems?: number;
|
|
26
|
+
uniqueItems?: boolean;
|
|
27
|
+
contains?: JSONSchema7;
|
|
28
|
+
maxProperties?: number;
|
|
29
|
+
minProperties?: number;
|
|
30
|
+
required?: string[];
|
|
31
|
+
properties?: Record<string, JSONSchema7>;
|
|
32
|
+
patternProperties?: Record<string, JSONSchema7>;
|
|
33
|
+
additionalProperties?: JSONSchema7 | boolean;
|
|
34
|
+
propertyNames?: JSONSchema7;
|
|
35
|
+
if?: JSONSchema7;
|
|
36
|
+
then?: JSONSchema7;
|
|
37
|
+
else?: JSONSchema7;
|
|
38
|
+
allOf?: JSONSchema7[];
|
|
39
|
+
anyOf?: JSONSchema7[];
|
|
40
|
+
oneOf?: JSONSchema7[];
|
|
41
|
+
not?: JSONSchema7;
|
|
42
|
+
title?: string;
|
|
43
|
+
description?: string;
|
|
44
|
+
default?: unknown;
|
|
45
|
+
readOnly?: boolean;
|
|
46
|
+
writeOnly?: boolean;
|
|
47
|
+
examples?: unknown[];
|
|
48
|
+
definitions?: Record<string, JSONSchema7>;
|
|
49
|
+
}
|
|
50
|
+
type JSONSchema7TypeName = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
|
|
51
|
+
|
|
1
52
|
interface MaxAIInitOptions {
|
|
2
53
|
/** Widget key from MaxAI dashboard */
|
|
3
54
|
key: string;
|
|
@@ -23,20 +74,37 @@ interface PageContext {
|
|
|
23
74
|
mainContent?: string;
|
|
24
75
|
lang?: string;
|
|
25
76
|
}
|
|
26
|
-
|
|
27
|
-
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Generic tool definition.
|
|
80
|
+
*
|
|
81
|
+
* @typeParam TArgs - Shape of arguments the handler receives (inferred from usage)
|
|
82
|
+
* @typeParam TResult - Return type of the handler
|
|
83
|
+
* @typeParam TSchema - JSON Schema type (defaults to JSONSchema7)
|
|
84
|
+
* @typeParam TContext - Extra context passed to the AI agent alongside the tool description
|
|
85
|
+
*/
|
|
86
|
+
interface ToolDefinition<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown, TSchema extends JSONSchema7 = JSONSchema7, TContext extends Record<string, unknown> = Record<string, unknown>> {
|
|
87
|
+
/** Machine identifier — stable, used in API/events/logic. Must match /^[a-z0-9_]+$/ */
|
|
88
|
+
slug: string;
|
|
89
|
+
/** Human-readable label shown to the user in the widget UI */
|
|
28
90
|
name: string;
|
|
29
|
-
/**
|
|
91
|
+
/** Description for the AI agent */
|
|
30
92
|
description: string;
|
|
31
|
-
/** JSON Schema
|
|
32
|
-
schema:
|
|
93
|
+
/** JSON Schema (draft-07) describing the tool's arguments */
|
|
94
|
+
schema: TSchema;
|
|
95
|
+
/**
|
|
96
|
+
* Extra context sent to the AI model alongside the tool description.
|
|
97
|
+
* Use for: UI constraints, domain rules, preferred data formats, agent hints.
|
|
98
|
+
*/
|
|
99
|
+
context?: TContext;
|
|
33
100
|
/** Function that executes when the agent calls this tool */
|
|
34
|
-
handler: (args:
|
|
101
|
+
handler: (args: TArgs) => TResult | Promise<TResult>;
|
|
35
102
|
/** If true, widget shows confirmation dialog before executing */
|
|
36
103
|
requiresConfirmation?: boolean;
|
|
37
|
-
/** Tool category for grouping */
|
|
104
|
+
/** Tool category for grouping in the UI */
|
|
38
105
|
category?: string;
|
|
39
106
|
}
|
|
107
|
+
|
|
40
108
|
interface ChatMessage {
|
|
41
109
|
role: "user" | "assistant";
|
|
42
110
|
content: string;
|
|
@@ -68,13 +136,47 @@ type WidgetEventMap = {
|
|
|
68
136
|
error: ErrorEvent;
|
|
69
137
|
};
|
|
70
138
|
type WidgetEvent = keyof WidgetEventMap;
|
|
139
|
+
/**
|
|
140
|
+
* Signed identity payload for widget-embedded platforms.
|
|
141
|
+
* Allows host platforms to pass their logged-in user's identity to the agent.
|
|
142
|
+
*/
|
|
143
|
+
interface IdentityPayload {
|
|
144
|
+
/** Unique slug identifying the host platform (e.g. "billing_app", "crm") */
|
|
145
|
+
platform_slug: string;
|
|
146
|
+
/** UID of the logged-in user on the host platform */
|
|
147
|
+
platform_user_uid: string;
|
|
148
|
+
/** Optional: UID of the organization/account on the host platform */
|
|
149
|
+
platform_account_uid?: string;
|
|
150
|
+
/** Display name of the user */
|
|
151
|
+
display_name?: string;
|
|
152
|
+
/** Verified email address */
|
|
153
|
+
email?: string;
|
|
154
|
+
/** Verified phone number (E.164 preferred) */
|
|
155
|
+
phone?: string;
|
|
156
|
+
/** User locale (e.g. "pl-PL") */
|
|
157
|
+
locale?: string;
|
|
158
|
+
/** Arbitrary traits (plan, role, etc.) */
|
|
159
|
+
traits?: Record<string, unknown>;
|
|
160
|
+
/** ISO 8601 timestamp when the signature was created */
|
|
161
|
+
signed_at?: string;
|
|
162
|
+
/** ISO 8601 timestamp when the signature expires (recommended: 5 min) */
|
|
163
|
+
expires_at?: string;
|
|
164
|
+
/** HMAC-SHA256 hex signature: HMAC(signing_secret, platform_user_uid + signed_at) */
|
|
165
|
+
signature?: string;
|
|
166
|
+
}
|
|
71
167
|
interface WidgetInstance {
|
|
72
168
|
/** Send explicit page context to the widget */
|
|
73
169
|
setPageContext(ctx: Partial<PageContext>): void;
|
|
170
|
+
/**
|
|
171
|
+
* Set the identity of the logged-in user on the host platform.
|
|
172
|
+
* When signing_secret is configured on the widget key, include a valid HMAC-SHA256 signature
|
|
173
|
+
* to get "confirmed" trust level. Without a signature the identity is treated as "likely".
|
|
174
|
+
*/
|
|
175
|
+
setIdentity(payload: IdentityPayload): void;
|
|
74
176
|
/** Register a client-side tool. Returns unregister function. */
|
|
75
|
-
registerTool(def: ToolDefinition): () => void;
|
|
76
|
-
/** Unregister a tool by
|
|
77
|
-
unregisterTool(
|
|
177
|
+
registerTool<TArgs extends Record<string, unknown>, TResult, TSchema extends JSONSchema7, TContext extends Record<string, unknown>>(def: ToolDefinition<TArgs, TResult, TSchema, TContext>): () => void;
|
|
178
|
+
/** Unregister a tool by slug */
|
|
179
|
+
unregisterTool(slug: string): void;
|
|
78
180
|
/** Subscribe to widget events. Returns unsubscribe function. */
|
|
79
181
|
on<E extends WidgetEvent>(event: E, callback: WidgetEventMap[E] extends void ? () => void : (data: WidgetEventMap[E]) => void): () => void;
|
|
80
182
|
/** Unsubscribe from widget events */
|
|
@@ -110,15 +212,20 @@ declare const MaxAI: {
|
|
|
110
212
|
* Set page context (shorthand — delegates to active instance).
|
|
111
213
|
*/
|
|
112
214
|
setPageContext(ctx: Partial<PageContext>): void;
|
|
215
|
+
/**
|
|
216
|
+
* Set the identity of the logged-in user on the host platform (shorthand).
|
|
217
|
+
* Pass a signed payload (HMAC-SHA256) to get confirmed trust level.
|
|
218
|
+
*/
|
|
219
|
+
setIdentity(payload: IdentityPayload): void;
|
|
113
220
|
/**
|
|
114
221
|
* Register a client-side tool (shorthand — delegates to active instance).
|
|
115
222
|
* Returns an unregister function.
|
|
116
223
|
*/
|
|
117
|
-
registerTool(def: ToolDefinition): () => void;
|
|
224
|
+
registerTool<TArgs extends Record<string, unknown>, TResult, TSchema extends JSONSchema7, TContext extends Record<string, unknown>>(def: ToolDefinition<TArgs, TResult, TSchema, TContext>): () => void;
|
|
118
225
|
/**
|
|
119
|
-
* Unregister a tool by
|
|
226
|
+
* Unregister a tool by slug.
|
|
120
227
|
*/
|
|
121
|
-
unregisterTool(
|
|
228
|
+
unregisterTool(slug: string): void;
|
|
122
229
|
/**
|
|
123
230
|
* Subscribe to events.
|
|
124
231
|
*/
|
|
@@ -139,4 +246,4 @@ declare const MaxAI: {
|
|
|
139
246
|
_initialized: boolean;
|
|
140
247
|
};
|
|
141
248
|
|
|
142
|
-
export { type ChatMessage, type ErrorEvent, MaxAI, type MaxAIInitOptions, type PageContext, type ToolCallEvent, type ToolDefinition, type ToolResultEvent, type WidgetEvent, type WidgetEventMap, type WidgetInstance };
|
|
249
|
+
export { type ChatMessage, type ErrorEvent, type IdentityPayload, type JSONSchema7, MaxAI, type MaxAIInitOptions, type PageContext, type ToolCallEvent, type ToolDefinition, type ToolResultEvent, type WidgetEvent, type WidgetEventMap, type WidgetInstance };
|
package/dist/index.global.js
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
|
-
/* @maxaiagent/widget-sdk v1.0
|
|
2
|
-
"use strict";var MaxAISDK=(()=>{var u=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols;var H=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var k=(n,t,e)=>t in n?u(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))H.call(t,e)&&k(n,e,t[e]);if(G)for(var e of G(t))ct.call(t,e)&&k(n,e,t[e]);return n};var pt=(n,t)=>{for(var e in t)u(n,e,{get:t[e],enumerable:!0})},ht=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!H.call(n,s)&&s!==e&&u(n,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return n};var ut=n=>ht(u({},"__esModule",{value:!0}),n);var St={};pt(St,{MaxAI:()=>A});var g=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var m=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",P="max-widget:register-tools",I="max-widget:unregister-tool",f="max-widget:tool-result",U="max-widget:point-ask-result",v="max-widget:point-ask-cancel",x="max-widget:host-styles",N="max-widget:debug-snapshot",D="max-widget:config-features";var z="max-widget:expand",W="max-widget:hide",K="max-widget:request-page-context",j="max-widget:start-point-ask",q="max-widget:stop-point-ask",X="max-widget:execute-tool",F="max-widget:request-debug-snapshot",B="max-widget:request-host-styles",Y="max-widget:gdpr-consent",$="max-widget:navigate",Z="max-widget:message",Q="max-widget:error";var y=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(I,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(f,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(f,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(f,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(P,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function V(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var mt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function ft(n){let t=JSON.stringify(n);for(let e of mt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var b=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let i=e.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:t,message:V(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let i of t.getEntries()){let s=i,o=(e=s.responseStatus)!=null?e:0;this.networkLog.push(h({method:"GET",url:V(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return ft({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function _(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function vt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function xt(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var w=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(v),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||xt(e)){this.transport.send(v),this.cleanup();return}let i={};for(let d of["class","id","href","src","alt","title","data-id","data-name"]){let a=e.getAttribute(d);a&&(i[d]=_(a,200))}let s=e.parentElement?_(e.parentElement.innerText,300):"",o={elementText:_(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:vt(e)};this.transport.send(U,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(v),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function yt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function J(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=yt(o.innerText,2e3));let d=document.querySelector(`script[data-key="${n}"]`);return d&&Array.from(d.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=a.value}}),t}function tt(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var E=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function S(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let d=document.querySelectorAll(o);for(let a=0;a<Math.min(d.length,10);a++){let l=getComputedStyle(d[a]),c=l.color;c&&c!==t.textColor&&c!=="rgb(0, 0, 0)"&&c!=="rgba(0, 0, 0, 0)"&&(i[c]=(i[c]||0)+1);let p=l.backgroundColor;p&&p!=="rgba(0, 0, 0, 0)"&&p!=="transparent"&&p!==t.bgColor&&(i[p]=(i[p]||0)+1)}}let s=Object.keys(i).sort((o,d)=>i[d]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var bt=`
|
|
1
|
+
/* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
|
|
2
|
+
"use strict";var MaxAISDK=(()=>{var _=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,Kt=Object.prototype.propertyIsEnumerable;var Q=(n,t,e)=>t in n?_(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))Z.call(t,e)&&Q(n,e,t[e]);if(V)for(var e of V(t))Kt.call(t,e)&&Q(n,e,t[e]);return n};var Xt=(n,t)=>{for(var e in t)_(n,e,{get:t[e],enumerable:!0})},jt=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Wt(t))!Z.call(n,i)&&i!==e&&_(n,i,{get:()=>t[i],enumerable:!(s=qt(t,i))||s.enumerable});return n};var Ft=n=>jt(_({},"__esModule",{value:!0}),n);var oe={};Xt(oe,{MaxAI:()=>K});var C=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let s=y({type:t},e);this.ready&&this.iframe?this.sendRaw(s):this.queue.push(s)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,s;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(s=(e=this.iframe)==null?void 0:e.contentWindow)==null||s.postMessage(t,this.baseUrl)}catch(i){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(t){return this.baseUrl}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow||t.origin!==this.expectedOrigin())return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var k=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.listeners.get(t))==null||s.delete(e)}emit(t,...e){var s;(s=this.listeners.get(t))==null||s.forEach(i=>{try{i(...e)}catch(r){console.error("[MaxAI SDK]",r)}})}removeAll(){this.listeners.clear()}};var tt="max-widget:page-context",et="max-widget:register-tools",nt="max-widget:unregister-tool",L="max-widget:tool-result",st="max-widget:point-ask-result",I="max-widget:point-ask-cancel",T="max-widget:host-styles",it="max-widget:debug-snapshot",rt="max-widget:config-features";var ot="max-widget:expand",at="max-widget:hide",lt="max-widget:close",dt="max-widget:request-page-context",ct="max-widget:start-point-ask",pt="max-widget:stop-point-ask",ht="max-widget:execute-tool",gt="max-widget:request-debug-snapshot",ut="max-widget:request-host-styles",mt="max-widget:gdpr-consent",ft="max-widget:navigate",xt="max-widget:message",vt="max-widget:error";var yt="max-widget:session-update",St="max-widget:session-request",bt="max-widget:session-restore",wt="max-widget:session-clear",Et="max-widget:draft-save",Tt="max-widget:draft-request",Mt="max-widget:draft-restore",_t="max-widget:identity-set";var O=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.slug||!/^[a-z0-9_]+$/.test(t.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",t.slug),()=>{}):(this.tools.set(t.slug,{slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,handler:t.handler,requiresConfirmation:t.requiresConfirmation||!1,category:t.category||""}),this.sendList(),()=>this.unregister(t.slug))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(nt,{slug:t}),this.sendList())}async execute(t,e,s){let i=this.tools.get(e);if(!(i!=null&&i.handler)){let r=`Tool "${e}" not found or has no handler`;return this.transport.send(L,{toolCallId:t,ok:!1,error:r}),{ok:!1,error:r}}try{let r=await i.handler(s);return this.transport.send(L,{toolCallId:t,ok:!0,data:r}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:e,args:s}})),{ok:!0}}catch(r){let a=r instanceof Error?r.message:"Tool execution failed";return this.transport.send(L,{toolCallId:t,ok:!1,error:a}),{ok:!1,error:a}}}sendList(){let t=Array.from(this.tools.values()).map(e=>({slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,requiresConfirmation:e.requiresConfirmation,category:e.category}));this.transport.send(et,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ct(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var Yt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function Jt(n){let t=JSON.stringify(n);for(let e of Yt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var A=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let s=e.map(i=>{try{return typeof i=="string"?i:JSON.stringify(i)}catch(r){return String(i)}}).join(" ");this.consoleLogs.push({level:t,message:Ct(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let s of t.getEntries()){let i=s,r=(e=i.responseStatus)!=null?e:0;this.networkLog.push(y({method:"GET",url:Ct(i.name,200),status:r,duration:Math.round(i.duration),timestamp:Math.round(performance.timeOrigin+i.startTime)},r===0||r>=400?{error:r===0?"Network error or blocked":`HTTP ${r}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return Jt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function W(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Vt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let s=1,i=e.previousSibling;for(;i;)i.nodeType===1&&i.tagName===e.tagName&&s++,i=i.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+s+"]"),e=e.parentElement}return"/"+t.join("/")}function Qt(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var G=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(I),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||Qt(e)){this.transport.send(I),this.cleanup();return}let s={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let o=e.getAttribute(a);o&&(s[a]=W(o,200))}let i=e.parentElement?W(e.parentElement.innerText,300):"",r={elementText:W(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:s,surroundingText:i,xpath:Vt(e)};this.transport.send(st,r),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(I),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function Zt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function kt(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let s=document.querySelector('meta[property="og:title"]');s&&(t.ogTitle=s.getAttribute("content")||"");let i=document.querySelector('meta[property="og:description"]');i&&(t.ogDescription=i.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(u){}})}catch(o){}let r=document.querySelector("main, article, [role='main']");r&&(t.mainContent=Zt(r.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(o=>{if(o.name.startsWith("data-context-")){let l=o.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=o.value}}),t}function Lt(n,t){if(!t)return n;let e=y({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=y(y({},e.customContext),t.customContext)),e}var R=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this.origPush,e=this.origReplace,s=()=>this.checkChange();history.pushState=function(...r){t.apply(this,r),s()},history.replaceState=function(...r){e.apply(this,r),s()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let i=document.querySelector("title");i&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(i,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function It(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return!0;let[e,s,i]=[+t[1],+t[2],+t[3]],r=Math.max(e,s,i),a=Math.min(e,s,i);return(r===0?0:(r-a)/r)<.15}function w(){let n=getComputedStyle(document.documentElement),t=getComputedStyle(document.body),e=t.backgroundColor||"",r={bgColor:!e||e==="rgba(0, 0, 0, 0)"||e==="transparent"?n.backgroundColor||"":e,fontFamily:t.fontFamily||"",textColor:t.color||"",primaryColor:"",accentColors:[]};try{let a=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],o={};for(let u of a){let m=document.querySelectorAll(u);for(let h=0;h<Math.min(m.length,10);h++){let S=getComputedStyle(m[h]),g=S.color;g&&g!==r.textColor&&g!=="rgb(0, 0, 0)"&&g!=="rgba(0, 0, 0, 0)"&&!It(g)&&(o[g]=(o[g]||0)+1);let x=S.backgroundColor;x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"&&x!==r.bgColor&&!It(x)&&(o[x]=(o[x]||0)+1)}}let l=Object.keys(o).sort((u,m)=>o[m]-o[u]);r.primaryColor=l[0]||"",r.accentColors=l.slice(0,5)}catch(a){}return r}var te=`
|
|
3
3
|
.max-widget-container{position:fixed;bottom:20px;z-index:999999;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
|
4
4
|
.max-widget-container.right{right:20px}
|
|
5
5
|
.max-widget-container.left{left:20px}
|
|
6
|
-
.max-widget-btn{width:56px;height:56px;border-radius:50%;border:none;cursor:
|
|
6
|
+
.max-widget-btn{width:56px;height:56px;border-radius:50%;border:none;cursor:grab;position:relative;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(0,0,0,0.3);transition:transform 0.2s,box-shadow 0.2s,opacity 0.2s}
|
|
7
7
|
.max-widget-btn:hover{transform:scale(1.05);box-shadow:0 6px 16px rgba(0,0,0,0.4)}
|
|
8
|
+
.max-widget-btn::after{content:'';position:absolute;top:-6px;left:-6px;right:-6px;bottom:-6px;border-radius:50%;border:2px dashed rgba(255,255,255,0);transition:border-color 0.2s;pointer-events:none}
|
|
9
|
+
.max-widget-btn:hover::after{border-color:rgba(255,255,255,0.45)}
|
|
10
|
+
.max-widget-btn.dragging{cursor:grabbing!important;transform:scale(1.08)!important;box-shadow:0 8px 20px rgba(0,0,0,0.5)!important}
|
|
11
|
+
.max-widget-btn.dragging::after{border-color:rgba(255,255,255,0.65)}
|
|
8
12
|
.max-widget-btn svg{width:24px;height:24px;fill:white}
|
|
9
|
-
.max-widget-
|
|
10
|
-
.max-widget-
|
|
11
|
-
.max-widget-
|
|
12
|
-
.max-widget-
|
|
13
|
-
.max-widget-
|
|
14
|
-
.max-widget-
|
|
15
|
-
.max-widget-
|
|
16
|
-
.max-widget-
|
|
17
|
-
.max-widget-
|
|
13
|
+
.max-widget-shell{position:absolute;bottom:0;width:380px;height:600px;border-radius:16px;background:transparent;overflow:hidden;transition:opacity 0.2s,transform 0.2s;opacity:0;transform:translateY(10px) scale(0.95);pointer-events:none;box-shadow:0 8px 32px rgba(0,0,0,0.3)}
|
|
14
|
+
.max-widget-shell.open~.max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
15
|
+
.max-widget-shell.right{right:0}
|
|
16
|
+
.max-widget-shell.left{left:0}
|
|
17
|
+
.max-widget-shell.open{opacity:1;transform:translateY(0) scale(1);pointer-events:auto}
|
|
18
|
+
.max-widget-shell.expanded{position:fixed;top:0;bottom:0;width:440px;height:100vh;height:100dvh;border-radius:0;box-shadow:-4px 0 24px rgba(0,0,0,0.2);opacity:1;transform:translateX(0);pointer-events:auto;transition:transform 0.3s ease,width 0.3s ease,border-radius 0.3s ease,box-shadow 0.3s ease}
|
|
19
|
+
.max-widget-shell.expanded.right{right:0;left:auto}
|
|
20
|
+
.max-widget-shell.expanded.left{left:0;right:auto}
|
|
21
|
+
.max-widget-shell.expanded.panel-hidden.right{transform:translateX(100%)}
|
|
22
|
+
.max-widget-shell.expanded.panel-hidden.left{transform:translateX(-100%)}
|
|
23
|
+
.max-widget-shell.glassmorphism{background:linear-gradient(180deg,rgba(12,18,30,0.2),rgba(6,10,18,0.12));backdrop-filter:blur(28px) saturate(185%);-webkit-backdrop-filter:blur(28px) saturate(185%);border:1px solid rgba(255,255,255,0.16);box-shadow:0 18px 48px rgba(0,0,0,0.28)}
|
|
24
|
+
.max-widget-shell.auto-adaptive{background:rgba(8,12,24,0.12);backdrop-filter:blur(12px) saturate(150%);-webkit-backdrop-filter:blur(12px) saturate(150%);border:1px solid rgba(255,255,255,0.12)}
|
|
18
25
|
.max-widget-container.panel-expanded .max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
19
26
|
.max-widget-container.panel-hidden-state .max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
27
|
+
.max-widget-frame{display:block;width:100%;height:100%;border:none;background:transparent;border-radius:inherit}
|
|
20
28
|
.max-widget-tab{position:fixed;top:12px;z-index:999999;width:40px;height:40px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:-2px 2px 8px rgba(0,0,0,0.2);transition:opacity 0.2s,transform 0.2s;opacity:0;pointer-events:none;transform:translateX(8px)}
|
|
21
29
|
.max-widget-tab.right{right:0;border-radius:8px 0 0 8px}
|
|
22
30
|
.max-widget-tab.left{left:0;border-radius:0 8px 8px 0}
|
|
@@ -24,6 +32,11 @@
|
|
|
24
32
|
.max-widget-tab.visible{opacity:1;pointer-events:auto;transform:translateX(0)}
|
|
25
33
|
.max-widget-tab:hover{filter:brightness(1.1)}
|
|
26
34
|
.max-widget-tab svg{width:18px;height:18px;fill:white}
|
|
27
|
-
@media(max-width:420px){.max-widget-
|
|
28
|
-
@media(max-width:420px){.max-widget-
|
|
29
|
-
|
|
35
|
+
@media(max-width:420px){.max-widget-shell{width:calc(100vw - 40px);height:calc(100vh - 120px)}}
|
|
36
|
+
@media(max-width:420px){.max-widget-shell.expanded{width:100vw}}
|
|
37
|
+
.max-widget-drag-handle{height:18px;width:100%;cursor:grab;display:flex;align-items:center;justify-content:center;flex-shrink:0;border-radius:16px 16px 0 0}
|
|
38
|
+
.max-widget-drag-handle::after{content:'';display:block;width:32px;height:3px;border-radius:2px;background:rgba(255,255,255,0.18)}
|
|
39
|
+
.max-widget-drag-handle:hover::after{background:rgba(255,255,255,0.35)}
|
|
40
|
+
.max-widget-drag-handle.dragging{cursor:grabbing!important}
|
|
41
|
+
.max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
|
|
42
|
+
`,ee='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var ne='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',se='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function At(n){if(!n||n.charAt(0)!=="#")return null;let t=n.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),t.length!==6?null:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Ot(n,t){let e=At(n);if(!e)return n;let s=Math.max(0,Math.min(255,Math.round(e.r+255*t))),i=Math.max(0,Math.min(255,Math.round(e.g+255*t))),r=Math.max(0,Math.min(255,Math.round(e.b+255*t))),a=o=>{let l=o.toString(16);return l.length===1?"0"+l:l};return"#"+a(s)+a(i)+a(r)}function P(n,t){let e=At(n);return e?`rgba(${e.r},${e.g},${e.b},${t})`:`rgba(99,102,241,${t})`}function ie(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return"";let e=s=>{let i=s.toString(16);return i.length===1?"0"+i:i};return"#"+e(+t[1])+e(+t[2])+e(+t[3])}function Gt(n,t,e,s){let i=re(e)||s||"#6366f1",r=[n.btn,n.tab];for(let a of r)if(a)if(a.style.background="",a.style.backgroundColor="",a.style.border="none",a.style.backdropFilter="",a.style.webkitBackdropFilter="",a.style.boxShadow="",t==="glassmorphism")a.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",a.style.border="1px solid rgba(255, 255, 255, 0.18)",a.style.backdropFilter="blur(18px) saturate(180%)",a.style.webkitBackdropFilter="blur(18px) saturate(180%)",a.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(t==="auto-adaptive"){let o=Ot(i,.08),l=Ot(i,-.06);a.style.background=`linear-gradient(180deg, ${P(o,.96)}, ${P(l,.92)})`,a.style.border=`1px solid ${P(i,.24)}`,a.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${P(i,.22)}`}else a.style.backgroundColor=s||i,a.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),t==="glassmorphism"?n.shell.classList.add("glassmorphism"):t==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function re(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ie(n):"":""}function Rt(n,t,e,s,i,r){if(document.querySelector(".max-widget-container"))return null;let a=document.createElement("style");i&&(a.nonce=i),a.textContent=te,document.head.appendChild(a);let o=document.createElement("div");o.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(o);let l=document.createElement("div");l.className="max-widget-shell "+(e?"right":"left"),o.appendChild(l);let u=document.createElement("div");u.className="max-widget-drag-handle",l.appendChild(u);let m=document.createElement("iframe");m.className="max-widget-frame",m.src=n+"/widget/"+t,m.setAttribute("allow","clipboard-write"),m.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),m.setAttribute("allowtransparency","true"),l.appendChild(m);let h=document.createElement("button");h.className="max-widget-btn",h.style.backgroundColor=s,h.innerHTML=ee,o.appendChild(h);let S=!1,g=!1,x=!1,X=0,j=0,D=0,N=0;function E(d,p){let f=window.innerWidth-o.offsetWidth,q=window.innerHeight-o.offsetHeight;o.style.left=Math.max(0,Math.min(f,d))+"px",o.style.top=Math.max(0,Math.min(q,p))+"px",o.style.bottom="auto",o.style.right="auto"}function F(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(o.style.left),top:parseInt(o.style.top)}))}catch(d){}U()}function U(){let d=l.offsetHeight||600,p=o.getBoundingClientRect(),f=p.top,q=window.innerHeight-p.bottom;f<d+8&&q>=d+8?(l.style.bottom="auto",l.style.top=o.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function zt(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:p,top:f}=JSON.parse(d);typeof p=="number"&&typeof f=="number"&&E(p,f)}catch(d){}}zt(),U(),h.addEventListener("pointerdown",d=>{if(d.button!==0)return;S=!0,g=!1,X=d.clientX,j=d.clientY;let p=o.getBoundingClientRect();D=p.left,N=p.top,E(D,N),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!S)return;let p=d.clientX-X,f=d.clientY-j;!g&&(Math.abs(p)>4||Math.abs(f)>4)&&(g=!0,h.classList.add("dragging")),g&&E(D+p,N+f)}),h.addEventListener("pointerup",()=>{S&&(S=!1,h.classList.remove("dragging"),g&&(x=!0,F(),g=!1))});let M=!1,b=!1,B=0,Y=0,z=0,$=0;u.addEventListener("pointerdown",d=>{if(d.button!==0)return;M=!0,b=!1,B=d.clientX,Y=d.clientY;let p=o.getBoundingClientRect();z=p.left,$=p.top,E(z,$),u.setPointerCapture(d.pointerId),d.preventDefault()}),u.addEventListener("pointermove",d=>{if(!M)return;let p=d.clientX-B,f=d.clientY-Y;!b&&(Math.abs(p)>4||Math.abs(f)>4)&&(b=!0,u.classList.add("dragging")),b&&E(z+p,$+f)}),u.addEventListener("pointerup",()=>{M&&(M=!1,u.classList.remove("dragging"),b&&(F(),b=!1))});let v=document.createElement("button");v.className="max-widget-tab "+(e?"right":"left"),v.style.backgroundColor=s,v.innerHTML=e?ne:se,document.body.appendChild(v);let J=!1;function $t(){J=!1,l.classList.remove("expanded","panel-hidden"),o.classList.remove("panel-expanded","panel-hidden-state"),v.classList.remove("visible"),document.body.style.overflow=""}return h.addEventListener("click",()=>{if(x){x=!1;return}if(J){$t();return}l.classList.contains("open")?(l.classList.remove("open"),r.onClose()):(U(),l.classList.add("open"),r.onOpen())}),v.addEventListener("click",()=>{l.classList.remove("panel-hidden"),o.classList.remove("panel-hidden-state"),v.classList.remove("visible")}),{container:o,shell:l,iframe:m,btn:h,tab:v,style:a}}function Pt(n,t,e){let{container:s,shell:i,tab:r}=n;t?(i.classList.contains("open")||i.classList.add("open"),i.classList.add("expanded"),s.classList.add("panel-expanded"),i.classList.remove("panel-hidden"),s.classList.remove("panel-hidden-state"),r.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(i.classList.remove("expanded","panel-hidden"),s.classList.remove("panel-expanded","panel-hidden-state"),r.classList.remove("visible"),document.body.style.overflow="")}function Ht(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Dt(n){n.container.remove(),n.tab.remove(),n.style.remove()}function Nt(n){n.shell.classList.add("open")}function Ut(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var H=class{constructor(t){this.emitter=new k;this.debug=new A;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.storedSessionToken=null;this.storedIdentity=null;this.key=t.key,this.isRight=t.position!=="bottom-left",this.nonce=t.nonce||null;let e=document.querySelector(`script[data-key="${t.key}"]`);e&&e.src?this.baseUrl=e.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):t.baseUrl?this.baseUrl=t.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new C(this.baseUrl),this.tools=new O(this.transport),this.pointAndAsk=new G(this.transport),this.spaDetector=new R(()=>{var s;if(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.ui){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}}),this.init()}readOrCreateVisitorId(){let t=`maxai_vid_${this.key}`;try{let s=localStorage.getItem(t);if(s)return s}catch(s){}let e=this.getCookie(t);if(e){try{localStorage.setItem(t,e)}catch(s){}return e}return this.generateUUID()}persistVisitorId(t){let e=`maxai_vid_${this.key}`;try{localStorage.setItem(e,t)}catch(s){}this.setCookie(e,t,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(t){}return null}saveSessionToken(t){this.storedSessionToken=t;try{localStorage.setItem(`maxai_st_${this.key}`,t)}catch(e){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(t){}}readStoredIdentity(){try{let t=localStorage.getItem(`maxai_identity_${this.key}`);if(t)return JSON.parse(t)}catch(t){}return null}saveIdentity(t){this.storedIdentity=t;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(t))}catch(e){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}setCookie(t,e,s){try{let i=new Date;i.setTime(i.getTime()+s*864e5),document.cookie=`${t}=${e};expires=${i.toUTCString()};path=/;SameSite=Lax;Secure`}catch(i){}}getCookie(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?e[1]:null}catch(e){return null}}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(e){t={}}this.config={pageContext:t.enable_page_context||!1,pointAndAsk:t.enable_point_and_ask||!1,debugMode:t.enable_debug_mode||!1,bugReport:t.enable_bug_reports||!1,clientTools:t.enable_client_tools||!1,autoTheme:t.theme_mode!=="manual",themeMode:t.theme_mode||"manual",gdprRequired:t.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=t.primary_color||"#6366f1",this.ui=Rt(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.ui&&(this.applyTheme(this.config.autoTheme?w().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var e,s;if(this.transport.markReady(),this.config&&this.transport.send(rt,{features:this.config}),(!((e=this.config)!=null&&e.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme)){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers())}setupMessageHandlers(){this.transport.listen(ot,t=>{this.ui&&Pt(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(at,()=>{this.ui&&Ht(this.ui)}),this.transport.listen(lt,()=>{this.close()}),this.transport.listen(dt,()=>{this.sendPageContext()}),this.transport.listen(ct,()=>{this.pointAndAsk.start()}),this.transport.listen(pt,()=>{this.pointAndAsk.stop()}),this.transport.listen(ht,t=>{let e=t.toolCallId,s=t.slug||t.name,i=t.args;this.emitter.emit("tool:call",{id:e,name:s,args:i}),this.tools.execute(e,s,i).then(r=>{this.emitter.emit("tool:result",{id:e,name:s,ok:r.ok,error:r.error})})}),this.transport.listen(gt,()=>{this.transport.send(it,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(ut,()=>{let t=w();this.applyTheme(t.primaryColor),this.transport.send(T,{styles:t})}),this.transport.listen(mt,()=>{var t,e;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme){let s=w();this.applyTheme(s.primaryColor),this.transport.send(T,{styles:s})}}),this.transport.listen(ft,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(xt,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(vt,t=>{this.emitter.emit("error",{message:t.error})}),this.transport.listen(St,()=>{this.transport.send(bt,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(yt,t=>{t.sessionToken&&this.saveSessionToken(t.sessionToken)}),this.transport.listen(wt,()=>{this.clearSessionToken()}),this.transport.listen(Et,t=>{try{localStorage.setItem(`maxai_draft_${this.key}`,t.text||"")}catch(e){}}),this.transport.listen(Tt,()=>{let t="";try{t=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(e){}this.transport.send(Mt,{text:t})})}applyTheme(t){!this.ui||!this.config||Gt(this.ui,this.config.themeMode,t,this.primaryColor)}sendPageContext(){var s;if(!this.consentGiven&&((s=this.config)!=null&&s.gdprRequired))return;let t=kt(this.key),e=Lt(t,this.explicitContext);this.transport.send(tt,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}setIdentity(t){this.saveIdentity(t),this.transport.send(_t,{identityPayload:t})}registerTool(t){return this.tools.register(t)}unregisterTool(t){this.tools.unregister(t)}on(t,e){return this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}open(){this.ui&&(Nt(this.ui),this.emitter.emit("open"))}close(){this.ui&&(Ut(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&Dt(this.ui),this.ui=null}};var c=null,K={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new H(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,t){return c?c.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let t=n.getAttribute("data-key");t&&K.init({key:t,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=K);return Ft(oe);})();
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
|
-
/* @maxaiagent/widget-sdk v1.0
|
|
2
|
-
"use strict";var u=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols;var H=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var k=(n,t,e)=>t in n?u(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))H.call(t,e)&&k(n,e,t[e]);if(G)for(var e of G(t))ct.call(t,e)&&k(n,e,t[e]);return n};var pt=(n,t)=>{for(var e in t)u(n,e,{get:t[e],enumerable:!0})},ht=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!H.call(n,s)&&s!==e&&u(n,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return n};var ut=n=>ht(u({},"__esModule",{value:!0}),n);var St={};pt(St,{MaxAI:()=>A});module.exports=ut(St);var g=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var m=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",P="max-widget:register-tools",I="max-widget:unregister-tool",f="max-widget:tool-result",U="max-widget:point-ask-result",v="max-widget:point-ask-cancel",x="max-widget:host-styles",N="max-widget:debug-snapshot",D="max-widget:config-features";var z="max-widget:expand",W="max-widget:hide",K="max-widget:request-page-context",j="max-widget:start-point-ask",q="max-widget:stop-point-ask",X="max-widget:execute-tool",F="max-widget:request-debug-snapshot",B="max-widget:request-host-styles",Y="max-widget:gdpr-consent",$="max-widget:navigate",Z="max-widget:message",Q="max-widget:error";var y=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(I,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(f,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(f,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(f,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(P,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function V(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var mt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function ft(n){let t=JSON.stringify(n);for(let e of mt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var b=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let i=e.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:t,message:V(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let i of t.getEntries()){let s=i,o=(e=s.responseStatus)!=null?e:0;this.networkLog.push(h({method:"GET",url:V(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return ft({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function _(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function vt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function xt(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var w=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(v),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||xt(e)){this.transport.send(v),this.cleanup();return}let i={};for(let d of["class","id","href","src","alt","title","data-id","data-name"]){let a=e.getAttribute(d);a&&(i[d]=_(a,200))}let s=e.parentElement?_(e.parentElement.innerText,300):"",o={elementText:_(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:vt(e)};this.transport.send(U,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(v),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function yt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function J(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=yt(o.innerText,2e3));let d=document.querySelector(`script[data-key="${n}"]`);return d&&Array.from(d.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=a.value}}),t}function tt(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var E=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function S(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let d=document.querySelectorAll(o);for(let a=0;a<Math.min(d.length,10);a++){let l=getComputedStyle(d[a]),c=l.color;c&&c!==t.textColor&&c!=="rgb(0, 0, 0)"&&c!=="rgba(0, 0, 0, 0)"&&(i[c]=(i[c]||0)+1);let p=l.backgroundColor;p&&p!=="rgba(0, 0, 0, 0)"&&p!=="transparent"&&p!==t.bgColor&&(i[p]=(i[p]||0)+1)}}let s=Object.keys(i).sort((o,d)=>i[d]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var bt=`
|
|
1
|
+
/* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
|
|
2
|
+
"use strict";var _=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,Kt=Object.prototype.propertyIsEnumerable;var Q=(n,t,e)=>t in n?_(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))Z.call(t,e)&&Q(n,e,t[e]);if(V)for(var e of V(t))Kt.call(t,e)&&Q(n,e,t[e]);return n};var Xt=(n,t)=>{for(var e in t)_(n,e,{get:t[e],enumerable:!0})},jt=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Wt(t))!Z.call(n,i)&&i!==e&&_(n,i,{get:()=>t[i],enumerable:!(s=qt(t,i))||s.enumerable});return n};var Ft=n=>jt(_({},"__esModule",{value:!0}),n);var oe={};Xt(oe,{MaxAI:()=>K});module.exports=Ft(oe);var C=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let s=y({type:t},e);this.ready&&this.iframe?this.sendRaw(s):this.queue.push(s)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,s;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(s=(e=this.iframe)==null?void 0:e.contentWindow)==null||s.postMessage(t,this.baseUrl)}catch(i){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(t){return this.baseUrl}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow||t.origin!==this.expectedOrigin())return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var k=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.listeners.get(t))==null||s.delete(e)}emit(t,...e){var s;(s=this.listeners.get(t))==null||s.forEach(i=>{try{i(...e)}catch(r){console.error("[MaxAI SDK]",r)}})}removeAll(){this.listeners.clear()}};var tt="max-widget:page-context",et="max-widget:register-tools",nt="max-widget:unregister-tool",L="max-widget:tool-result",st="max-widget:point-ask-result",I="max-widget:point-ask-cancel",T="max-widget:host-styles",it="max-widget:debug-snapshot",rt="max-widget:config-features";var ot="max-widget:expand",at="max-widget:hide",lt="max-widget:close",dt="max-widget:request-page-context",ct="max-widget:start-point-ask",pt="max-widget:stop-point-ask",ht="max-widget:execute-tool",gt="max-widget:request-debug-snapshot",ut="max-widget:request-host-styles",mt="max-widget:gdpr-consent",ft="max-widget:navigate",xt="max-widget:message",vt="max-widget:error";var yt="max-widget:session-update",St="max-widget:session-request",bt="max-widget:session-restore",wt="max-widget:session-clear",Et="max-widget:draft-save",Tt="max-widget:draft-request",Mt="max-widget:draft-restore",_t="max-widget:identity-set";var O=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.slug||!/^[a-z0-9_]+$/.test(t.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",t.slug),()=>{}):(this.tools.set(t.slug,{slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,handler:t.handler,requiresConfirmation:t.requiresConfirmation||!1,category:t.category||""}),this.sendList(),()=>this.unregister(t.slug))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(nt,{slug:t}),this.sendList())}async execute(t,e,s){let i=this.tools.get(e);if(!(i!=null&&i.handler)){let r=`Tool "${e}" not found or has no handler`;return this.transport.send(L,{toolCallId:t,ok:!1,error:r}),{ok:!1,error:r}}try{let r=await i.handler(s);return this.transport.send(L,{toolCallId:t,ok:!0,data:r}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:e,args:s}})),{ok:!0}}catch(r){let a=r instanceof Error?r.message:"Tool execution failed";return this.transport.send(L,{toolCallId:t,ok:!1,error:a}),{ok:!1,error:a}}}sendList(){let t=Array.from(this.tools.values()).map(e=>({slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,requiresConfirmation:e.requiresConfirmation,category:e.category}));this.transport.send(et,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ct(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var Yt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function Jt(n){let t=JSON.stringify(n);for(let e of Yt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var A=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let s=e.map(i=>{try{return typeof i=="string"?i:JSON.stringify(i)}catch(r){return String(i)}}).join(" ");this.consoleLogs.push({level:t,message:Ct(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let s of t.getEntries()){let i=s,r=(e=i.responseStatus)!=null?e:0;this.networkLog.push(y({method:"GET",url:Ct(i.name,200),status:r,duration:Math.round(i.duration),timestamp:Math.round(performance.timeOrigin+i.startTime)},r===0||r>=400?{error:r===0?"Network error or blocked":`HTTP ${r}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return Jt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function W(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Vt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let s=1,i=e.previousSibling;for(;i;)i.nodeType===1&&i.tagName===e.tagName&&s++,i=i.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+s+"]"),e=e.parentElement}return"/"+t.join("/")}function Qt(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var G=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(I),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||Qt(e)){this.transport.send(I),this.cleanup();return}let s={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let o=e.getAttribute(a);o&&(s[a]=W(o,200))}let i=e.parentElement?W(e.parentElement.innerText,300):"",r={elementText:W(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:s,surroundingText:i,xpath:Vt(e)};this.transport.send(st,r),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(I),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function Zt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function kt(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let s=document.querySelector('meta[property="og:title"]');s&&(t.ogTitle=s.getAttribute("content")||"");let i=document.querySelector('meta[property="og:description"]');i&&(t.ogDescription=i.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(u){}})}catch(o){}let r=document.querySelector("main, article, [role='main']");r&&(t.mainContent=Zt(r.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(o=>{if(o.name.startsWith("data-context-")){let l=o.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=o.value}}),t}function Lt(n,t){if(!t)return n;let e=y({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=y(y({},e.customContext),t.customContext)),e}var R=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this.origPush,e=this.origReplace,s=()=>this.checkChange();history.pushState=function(...r){t.apply(this,r),s()},history.replaceState=function(...r){e.apply(this,r),s()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let i=document.querySelector("title");i&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(i,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function It(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return!0;let[e,s,i]=[+t[1],+t[2],+t[3]],r=Math.max(e,s,i),a=Math.min(e,s,i);return(r===0?0:(r-a)/r)<.15}function w(){let n=getComputedStyle(document.documentElement),t=getComputedStyle(document.body),e=t.backgroundColor||"",r={bgColor:!e||e==="rgba(0, 0, 0, 0)"||e==="transparent"?n.backgroundColor||"":e,fontFamily:t.fontFamily||"",textColor:t.color||"",primaryColor:"",accentColors:[]};try{let a=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],o={};for(let u of a){let m=document.querySelectorAll(u);for(let h=0;h<Math.min(m.length,10);h++){let S=getComputedStyle(m[h]),g=S.color;g&&g!==r.textColor&&g!=="rgb(0, 0, 0)"&&g!=="rgba(0, 0, 0, 0)"&&!It(g)&&(o[g]=(o[g]||0)+1);let x=S.backgroundColor;x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"&&x!==r.bgColor&&!It(x)&&(o[x]=(o[x]||0)+1)}}let l=Object.keys(o).sort((u,m)=>o[m]-o[u]);r.primaryColor=l[0]||"",r.accentColors=l.slice(0,5)}catch(a){}return r}var te=`
|
|
3
3
|
.max-widget-container{position:fixed;bottom:20px;z-index:999999;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
|
4
4
|
.max-widget-container.right{right:20px}
|
|
5
5
|
.max-widget-container.left{left:20px}
|
|
6
|
-
.max-widget-btn{width:56px;height:56px;border-radius:50%;border:none;cursor:
|
|
6
|
+
.max-widget-btn{width:56px;height:56px;border-radius:50%;border:none;cursor:grab;position:relative;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(0,0,0,0.3);transition:transform 0.2s,box-shadow 0.2s,opacity 0.2s}
|
|
7
7
|
.max-widget-btn:hover{transform:scale(1.05);box-shadow:0 6px 16px rgba(0,0,0,0.4)}
|
|
8
|
+
.max-widget-btn::after{content:'';position:absolute;top:-6px;left:-6px;right:-6px;bottom:-6px;border-radius:50%;border:2px dashed rgba(255,255,255,0);transition:border-color 0.2s;pointer-events:none}
|
|
9
|
+
.max-widget-btn:hover::after{border-color:rgba(255,255,255,0.45)}
|
|
10
|
+
.max-widget-btn.dragging{cursor:grabbing!important;transform:scale(1.08)!important;box-shadow:0 8px 20px rgba(0,0,0,0.5)!important}
|
|
11
|
+
.max-widget-btn.dragging::after{border-color:rgba(255,255,255,0.65)}
|
|
8
12
|
.max-widget-btn svg{width:24px;height:24px;fill:white}
|
|
9
|
-
.max-widget-
|
|
10
|
-
.max-widget-
|
|
11
|
-
.max-widget-
|
|
12
|
-
.max-widget-
|
|
13
|
-
.max-widget-
|
|
14
|
-
.max-widget-
|
|
15
|
-
.max-widget-
|
|
16
|
-
.max-widget-
|
|
17
|
-
.max-widget-
|
|
13
|
+
.max-widget-shell{position:absolute;bottom:0;width:380px;height:600px;border-radius:16px;background:transparent;overflow:hidden;transition:opacity 0.2s,transform 0.2s;opacity:0;transform:translateY(10px) scale(0.95);pointer-events:none;box-shadow:0 8px 32px rgba(0,0,0,0.3)}
|
|
14
|
+
.max-widget-shell.open~.max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
15
|
+
.max-widget-shell.right{right:0}
|
|
16
|
+
.max-widget-shell.left{left:0}
|
|
17
|
+
.max-widget-shell.open{opacity:1;transform:translateY(0) scale(1);pointer-events:auto}
|
|
18
|
+
.max-widget-shell.expanded{position:fixed;top:0;bottom:0;width:440px;height:100vh;height:100dvh;border-radius:0;box-shadow:-4px 0 24px rgba(0,0,0,0.2);opacity:1;transform:translateX(0);pointer-events:auto;transition:transform 0.3s ease,width 0.3s ease,border-radius 0.3s ease,box-shadow 0.3s ease}
|
|
19
|
+
.max-widget-shell.expanded.right{right:0;left:auto}
|
|
20
|
+
.max-widget-shell.expanded.left{left:0;right:auto}
|
|
21
|
+
.max-widget-shell.expanded.panel-hidden.right{transform:translateX(100%)}
|
|
22
|
+
.max-widget-shell.expanded.panel-hidden.left{transform:translateX(-100%)}
|
|
23
|
+
.max-widget-shell.glassmorphism{background:linear-gradient(180deg,rgba(12,18,30,0.2),rgba(6,10,18,0.12));backdrop-filter:blur(28px) saturate(185%);-webkit-backdrop-filter:blur(28px) saturate(185%);border:1px solid rgba(255,255,255,0.16);box-shadow:0 18px 48px rgba(0,0,0,0.28)}
|
|
24
|
+
.max-widget-shell.auto-adaptive{background:rgba(8,12,24,0.12);backdrop-filter:blur(12px) saturate(150%);-webkit-backdrop-filter:blur(12px) saturate(150%);border:1px solid rgba(255,255,255,0.12)}
|
|
18
25
|
.max-widget-container.panel-expanded .max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
19
26
|
.max-widget-container.panel-hidden-state .max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
27
|
+
.max-widget-frame{display:block;width:100%;height:100%;border:none;background:transparent;border-radius:inherit}
|
|
20
28
|
.max-widget-tab{position:fixed;top:12px;z-index:999999;width:40px;height:40px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:-2px 2px 8px rgba(0,0,0,0.2);transition:opacity 0.2s,transform 0.2s;opacity:0;pointer-events:none;transform:translateX(8px)}
|
|
21
29
|
.max-widget-tab.right{right:0;border-radius:8px 0 0 8px}
|
|
22
30
|
.max-widget-tab.left{left:0;border-radius:0 8px 8px 0}
|
|
@@ -24,6 +32,11 @@
|
|
|
24
32
|
.max-widget-tab.visible{opacity:1;pointer-events:auto;transform:translateX(0)}
|
|
25
33
|
.max-widget-tab:hover{filter:brightness(1.1)}
|
|
26
34
|
.max-widget-tab svg{width:18px;height:18px;fill:white}
|
|
27
|
-
@media(max-width:420px){.max-widget-
|
|
28
|
-
@media(max-width:420px){.max-widget-
|
|
29
|
-
|
|
35
|
+
@media(max-width:420px){.max-widget-shell{width:calc(100vw - 40px);height:calc(100vh - 120px)}}
|
|
36
|
+
@media(max-width:420px){.max-widget-shell.expanded{width:100vw}}
|
|
37
|
+
.max-widget-drag-handle{height:18px;width:100%;cursor:grab;display:flex;align-items:center;justify-content:center;flex-shrink:0;border-radius:16px 16px 0 0}
|
|
38
|
+
.max-widget-drag-handle::after{content:'';display:block;width:32px;height:3px;border-radius:2px;background:rgba(255,255,255,0.18)}
|
|
39
|
+
.max-widget-drag-handle:hover::after{background:rgba(255,255,255,0.35)}
|
|
40
|
+
.max-widget-drag-handle.dragging{cursor:grabbing!important}
|
|
41
|
+
.max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
|
|
42
|
+
`,ee='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var ne='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',se='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function At(n){if(!n||n.charAt(0)!=="#")return null;let t=n.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),t.length!==6?null:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Ot(n,t){let e=At(n);if(!e)return n;let s=Math.max(0,Math.min(255,Math.round(e.r+255*t))),i=Math.max(0,Math.min(255,Math.round(e.g+255*t))),r=Math.max(0,Math.min(255,Math.round(e.b+255*t))),a=o=>{let l=o.toString(16);return l.length===1?"0"+l:l};return"#"+a(s)+a(i)+a(r)}function P(n,t){let e=At(n);return e?`rgba(${e.r},${e.g},${e.b},${t})`:`rgba(99,102,241,${t})`}function ie(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return"";let e=s=>{let i=s.toString(16);return i.length===1?"0"+i:i};return"#"+e(+t[1])+e(+t[2])+e(+t[3])}function Gt(n,t,e,s){let i=re(e)||s||"#6366f1",r=[n.btn,n.tab];for(let a of r)if(a)if(a.style.background="",a.style.backgroundColor="",a.style.border="none",a.style.backdropFilter="",a.style.webkitBackdropFilter="",a.style.boxShadow="",t==="glassmorphism")a.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",a.style.border="1px solid rgba(255, 255, 255, 0.18)",a.style.backdropFilter="blur(18px) saturate(180%)",a.style.webkitBackdropFilter="blur(18px) saturate(180%)",a.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(t==="auto-adaptive"){let o=Ot(i,.08),l=Ot(i,-.06);a.style.background=`linear-gradient(180deg, ${P(o,.96)}, ${P(l,.92)})`,a.style.border=`1px solid ${P(i,.24)}`,a.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${P(i,.22)}`}else a.style.backgroundColor=s||i,a.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),t==="glassmorphism"?n.shell.classList.add("glassmorphism"):t==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function re(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ie(n):"":""}function Rt(n,t,e,s,i,r){if(document.querySelector(".max-widget-container"))return null;let a=document.createElement("style");i&&(a.nonce=i),a.textContent=te,document.head.appendChild(a);let o=document.createElement("div");o.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(o);let l=document.createElement("div");l.className="max-widget-shell "+(e?"right":"left"),o.appendChild(l);let u=document.createElement("div");u.className="max-widget-drag-handle",l.appendChild(u);let m=document.createElement("iframe");m.className="max-widget-frame",m.src=n+"/widget/"+t,m.setAttribute("allow","clipboard-write"),m.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),m.setAttribute("allowtransparency","true"),l.appendChild(m);let h=document.createElement("button");h.className="max-widget-btn",h.style.backgroundColor=s,h.innerHTML=ee,o.appendChild(h);let S=!1,g=!1,x=!1,X=0,j=0,D=0,N=0;function E(d,p){let f=window.innerWidth-o.offsetWidth,q=window.innerHeight-o.offsetHeight;o.style.left=Math.max(0,Math.min(f,d))+"px",o.style.top=Math.max(0,Math.min(q,p))+"px",o.style.bottom="auto",o.style.right="auto"}function F(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(o.style.left),top:parseInt(o.style.top)}))}catch(d){}U()}function U(){let d=l.offsetHeight||600,p=o.getBoundingClientRect(),f=p.top,q=window.innerHeight-p.bottom;f<d+8&&q>=d+8?(l.style.bottom="auto",l.style.top=o.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function zt(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:p,top:f}=JSON.parse(d);typeof p=="number"&&typeof f=="number"&&E(p,f)}catch(d){}}zt(),U(),h.addEventListener("pointerdown",d=>{if(d.button!==0)return;S=!0,g=!1,X=d.clientX,j=d.clientY;let p=o.getBoundingClientRect();D=p.left,N=p.top,E(D,N),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!S)return;let p=d.clientX-X,f=d.clientY-j;!g&&(Math.abs(p)>4||Math.abs(f)>4)&&(g=!0,h.classList.add("dragging")),g&&E(D+p,N+f)}),h.addEventListener("pointerup",()=>{S&&(S=!1,h.classList.remove("dragging"),g&&(x=!0,F(),g=!1))});let M=!1,b=!1,B=0,Y=0,z=0,$=0;u.addEventListener("pointerdown",d=>{if(d.button!==0)return;M=!0,b=!1,B=d.clientX,Y=d.clientY;let p=o.getBoundingClientRect();z=p.left,$=p.top,E(z,$),u.setPointerCapture(d.pointerId),d.preventDefault()}),u.addEventListener("pointermove",d=>{if(!M)return;let p=d.clientX-B,f=d.clientY-Y;!b&&(Math.abs(p)>4||Math.abs(f)>4)&&(b=!0,u.classList.add("dragging")),b&&E(z+p,$+f)}),u.addEventListener("pointerup",()=>{M&&(M=!1,u.classList.remove("dragging"),b&&(F(),b=!1))});let v=document.createElement("button");v.className="max-widget-tab "+(e?"right":"left"),v.style.backgroundColor=s,v.innerHTML=e?ne:se,document.body.appendChild(v);let J=!1;function $t(){J=!1,l.classList.remove("expanded","panel-hidden"),o.classList.remove("panel-expanded","panel-hidden-state"),v.classList.remove("visible"),document.body.style.overflow=""}return h.addEventListener("click",()=>{if(x){x=!1;return}if(J){$t();return}l.classList.contains("open")?(l.classList.remove("open"),r.onClose()):(U(),l.classList.add("open"),r.onOpen())}),v.addEventListener("click",()=>{l.classList.remove("panel-hidden"),o.classList.remove("panel-hidden-state"),v.classList.remove("visible")}),{container:o,shell:l,iframe:m,btn:h,tab:v,style:a}}function Pt(n,t,e){let{container:s,shell:i,tab:r}=n;t?(i.classList.contains("open")||i.classList.add("open"),i.classList.add("expanded"),s.classList.add("panel-expanded"),i.classList.remove("panel-hidden"),s.classList.remove("panel-hidden-state"),r.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(i.classList.remove("expanded","panel-hidden"),s.classList.remove("panel-expanded","panel-hidden-state"),r.classList.remove("visible"),document.body.style.overflow="")}function Ht(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Dt(n){n.container.remove(),n.tab.remove(),n.style.remove()}function Nt(n){n.shell.classList.add("open")}function Ut(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var H=class{constructor(t){this.emitter=new k;this.debug=new A;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.storedSessionToken=null;this.storedIdentity=null;this.key=t.key,this.isRight=t.position!=="bottom-left",this.nonce=t.nonce||null;let e=document.querySelector(`script[data-key="${t.key}"]`);e&&e.src?this.baseUrl=e.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):t.baseUrl?this.baseUrl=t.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new C(this.baseUrl),this.tools=new O(this.transport),this.pointAndAsk=new G(this.transport),this.spaDetector=new R(()=>{var s;if(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.ui){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}}),this.init()}readOrCreateVisitorId(){let t=`maxai_vid_${this.key}`;try{let s=localStorage.getItem(t);if(s)return s}catch(s){}let e=this.getCookie(t);if(e){try{localStorage.setItem(t,e)}catch(s){}return e}return this.generateUUID()}persistVisitorId(t){let e=`maxai_vid_${this.key}`;try{localStorage.setItem(e,t)}catch(s){}this.setCookie(e,t,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(t){}return null}saveSessionToken(t){this.storedSessionToken=t;try{localStorage.setItem(`maxai_st_${this.key}`,t)}catch(e){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(t){}}readStoredIdentity(){try{let t=localStorage.getItem(`maxai_identity_${this.key}`);if(t)return JSON.parse(t)}catch(t){}return null}saveIdentity(t){this.storedIdentity=t;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(t))}catch(e){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}setCookie(t,e,s){try{let i=new Date;i.setTime(i.getTime()+s*864e5),document.cookie=`${t}=${e};expires=${i.toUTCString()};path=/;SameSite=Lax;Secure`}catch(i){}}getCookie(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?e[1]:null}catch(e){return null}}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(e){t={}}this.config={pageContext:t.enable_page_context||!1,pointAndAsk:t.enable_point_and_ask||!1,debugMode:t.enable_debug_mode||!1,bugReport:t.enable_bug_reports||!1,clientTools:t.enable_client_tools||!1,autoTheme:t.theme_mode!=="manual",themeMode:t.theme_mode||"manual",gdprRequired:t.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=t.primary_color||"#6366f1",this.ui=Rt(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.ui&&(this.applyTheme(this.config.autoTheme?w().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var e,s;if(this.transport.markReady(),this.config&&this.transport.send(rt,{features:this.config}),(!((e=this.config)!=null&&e.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme)){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers())}setupMessageHandlers(){this.transport.listen(ot,t=>{this.ui&&Pt(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(at,()=>{this.ui&&Ht(this.ui)}),this.transport.listen(lt,()=>{this.close()}),this.transport.listen(dt,()=>{this.sendPageContext()}),this.transport.listen(ct,()=>{this.pointAndAsk.start()}),this.transport.listen(pt,()=>{this.pointAndAsk.stop()}),this.transport.listen(ht,t=>{let e=t.toolCallId,s=t.slug||t.name,i=t.args;this.emitter.emit("tool:call",{id:e,name:s,args:i}),this.tools.execute(e,s,i).then(r=>{this.emitter.emit("tool:result",{id:e,name:s,ok:r.ok,error:r.error})})}),this.transport.listen(gt,()=>{this.transport.send(it,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(ut,()=>{let t=w();this.applyTheme(t.primaryColor),this.transport.send(T,{styles:t})}),this.transport.listen(mt,()=>{var t,e;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme){let s=w();this.applyTheme(s.primaryColor),this.transport.send(T,{styles:s})}}),this.transport.listen(ft,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(xt,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(vt,t=>{this.emitter.emit("error",{message:t.error})}),this.transport.listen(St,()=>{this.transport.send(bt,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(yt,t=>{t.sessionToken&&this.saveSessionToken(t.sessionToken)}),this.transport.listen(wt,()=>{this.clearSessionToken()}),this.transport.listen(Et,t=>{try{localStorage.setItem(`maxai_draft_${this.key}`,t.text||"")}catch(e){}}),this.transport.listen(Tt,()=>{let t="";try{t=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(e){}this.transport.send(Mt,{text:t})})}applyTheme(t){!this.ui||!this.config||Gt(this.ui,this.config.themeMode,t,this.primaryColor)}sendPageContext(){var s;if(!this.consentGiven&&((s=this.config)!=null&&s.gdprRequired))return;let t=kt(this.key),e=Lt(t,this.explicitContext);this.transport.send(tt,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}setIdentity(t){this.saveIdentity(t),this.transport.send(_t,{identityPayload:t})}registerTool(t){return this.tools.register(t)}unregisterTool(t){this.tools.unregister(t)}on(t,e){return this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}open(){this.ui&&(Nt(this.ui),this.emitter.emit("open"))}close(){this.ui&&(Ut(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&Dt(this.ui),this.ui=null}};var c=null,K={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new H(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,t){return c?c.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let t=n.getAttribute("data-key");t&&K.init({key:t,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=K);
|
package/dist/index.mjs
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
|
-
/* @maxaiagent/widget-sdk v1.0
|
|
2
|
-
var rt=Object.defineProperty;var A=Object.getOwnPropertySymbols;var at=Object.prototype.hasOwnProperty,lt=Object.prototype.propertyIsEnumerable;var O=(n,t,e)=>t in n?rt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))at.call(t,e)&&O(n,e,t[e]);if(A)for(var e of A(t))lt.call(t,e)&&O(n,e,t[e]);return n};var u=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var g=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var G="max-widget:page-context",k="max-widget:register-tools",H="max-widget:unregister-tool",m="max-widget:tool-result",R="max-widget:point-ask-result",f="max-widget:point-ask-cancel",v="max-widget:host-styles",P="max-widget:debug-snapshot",I="max-widget:config-features";var U="max-widget:expand",N="max-widget:hide",D="max-widget:request-page-context",z="max-widget:start-point-ask",W="max-widget:stop-point-ask",K="max-widget:execute-tool",j="max-widget:request-debug-snapshot",q="max-widget:request-host-styles",X="max-widget:gdpr-consent",F="max-widget:navigate",B="max-widget:message",Y="max-widget:error";var x=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(H,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(m,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(m,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(m,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(k,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function $(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var ct=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function pt(n){let t=JSON.stringify(n);for(let e of ct)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var y=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let i=e.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:t,message:$(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let i of t.getEntries()){let s=i,o=(e=s.responseStatus)!=null?e:0;this.networkLog.push(h({method:"GET",url:$(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return pt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function T(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function ht(n){let t=[],e=n;for(;e&&e.nodeType===1;){let i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function ut(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var b=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(f),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||ut(e)){this.transport.send(f),this.cleanup();return}let i={};for(let d of["class","id","href","src","alt","title","data-id","data-name"]){let a=e.getAttribute(d);a&&(i[d]=T(a,200))}let s=e.parentElement?T(e.parentElement.innerText,300):"",o={elementText:T(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:ht(e)};this.transport.send(R,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(f),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function gt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Z(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=gt(o.innerText,2e3));let d=document.querySelector(`script[data-key="${n}"]`);return d&&Array.from(d.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=a.value}}),t}function Q(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var w=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function E(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let d=document.querySelectorAll(o);for(let a=0;a<Math.min(d.length,10);a++){let l=getComputedStyle(d[a]),c=l.color;c&&c!==t.textColor&&c!=="rgb(0, 0, 0)"&&c!=="rgba(0, 0, 0, 0)"&&(i[c]=(i[c]||0)+1);let p=l.backgroundColor;p&&p!=="rgba(0, 0, 0, 0)"&&p!=="transparent"&&p!==t.bgColor&&(i[p]=(i[p]||0)+1)}}let s=Object.keys(i).sort((o,d)=>i[d]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var mt=`
|
|
1
|
+
/* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
|
|
2
|
+
var zt=Object.defineProperty;var Y=Object.getOwnPropertySymbols;var $t=Object.prototype.hasOwnProperty,qt=Object.prototype.propertyIsEnumerable;var J=(n,t,e)=>t in n?zt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))$t.call(t,e)&&J(n,e,t[e]);if(Y)for(var e of Y(t))qt.call(t,e)&&J(n,e,t[e]);return n};var _=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let s=y({type:t},e);this.ready&&this.iframe?this.sendRaw(s):this.queue.push(s)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,s;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(s=(e=this.iframe)==null?void 0:e.contentWindow)==null||s.postMessage(t,this.baseUrl)}catch(i){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(t){return this.baseUrl}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow||t.origin!==this.expectedOrigin())return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var C=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.listeners.get(t))==null||s.delete(e)}emit(t,...e){var s;(s=this.listeners.get(t))==null||s.forEach(i=>{try{i(...e)}catch(r){console.error("[MaxAI SDK]",r)}})}removeAll(){this.listeners.clear()}};var V="max-widget:page-context",Q="max-widget:register-tools",Z="max-widget:unregister-tool",k="max-widget:tool-result",tt="max-widget:point-ask-result",L="max-widget:point-ask-cancel",T="max-widget:host-styles",et="max-widget:debug-snapshot",nt="max-widget:config-features";var st="max-widget:expand",it="max-widget:hide",rt="max-widget:close",ot="max-widget:request-page-context",at="max-widget:start-point-ask",lt="max-widget:stop-point-ask",dt="max-widget:execute-tool",ct="max-widget:request-debug-snapshot",pt="max-widget:request-host-styles",ht="max-widget:gdpr-consent",gt="max-widget:navigate",ut="max-widget:message",mt="max-widget:error";var ft="max-widget:session-update",xt="max-widget:session-request",vt="max-widget:session-restore",yt="max-widget:session-clear",St="max-widget:draft-save",bt="max-widget:draft-request",wt="max-widget:draft-restore",Et="max-widget:identity-set";var I=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.slug||!/^[a-z0-9_]+$/.test(t.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",t.slug),()=>{}):(this.tools.set(t.slug,{slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,handler:t.handler,requiresConfirmation:t.requiresConfirmation||!1,category:t.category||""}),this.sendList(),()=>this.unregister(t.slug))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(Z,{slug:t}),this.sendList())}async execute(t,e,s){let i=this.tools.get(e);if(!(i!=null&&i.handler)){let r=`Tool "${e}" not found or has no handler`;return this.transport.send(k,{toolCallId:t,ok:!1,error:r}),{ok:!1,error:r}}try{let r=await i.handler(s);return this.transport.send(k,{toolCallId:t,ok:!0,data:r}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:e,args:s}})),{ok:!0}}catch(r){let a=r instanceof Error?r.message:"Tool execution failed";return this.transport.send(k,{toolCallId:t,ok:!1,error:a}),{ok:!1,error:a}}}sendList(){let t=Array.from(this.tools.values()).map(e=>({slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,requiresConfirmation:e.requiresConfirmation,category:e.category}));this.transport.send(Q,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Tt(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var Kt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function Xt(n){let t=JSON.stringify(n);for(let e of Kt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var O=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let s=e.map(i=>{try{return typeof i=="string"?i:JSON.stringify(i)}catch(r){return String(i)}}).join(" ");this.consoleLogs.push({level:t,message:Tt(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let s of t.getEntries()){let i=s,r=(e=i.responseStatus)!=null?e:0;this.networkLog.push(y({method:"GET",url:Tt(i.name,200),status:r,duration:Math.round(i.duration),timestamp:Math.round(performance.timeOrigin+i.startTime)},r===0||r>=400?{error:r===0?"Network error or blocked":`HTTP ${r}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return Xt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function q(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function jt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let s=1,i=e.previousSibling;for(;i;)i.nodeType===1&&i.tagName===e.tagName&&s++,i=i.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+s+"]"),e=e.parentElement}return"/"+t.join("/")}function Ft(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var A=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(L),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||Ft(e)){this.transport.send(L),this.cleanup();return}let s={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let o=e.getAttribute(a);o&&(s[a]=q(o,200))}let i=e.parentElement?q(e.parentElement.innerText,300):"",r={elementText:q(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:s,surroundingText:i,xpath:jt(e)};this.transport.send(tt,r),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(L),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function Bt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Mt(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let s=document.querySelector('meta[property="og:title"]');s&&(t.ogTitle=s.getAttribute("content")||"");let i=document.querySelector('meta[property="og:description"]');i&&(t.ogDescription=i.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(u){}})}catch(o){}let r=document.querySelector("main, article, [role='main']");r&&(t.mainContent=Bt(r.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(o=>{if(o.name.startsWith("data-context-")){let l=o.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=o.value}}),t}function _t(n,t){if(!t)return n;let e=y({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=y(y({},e.customContext),t.customContext)),e}var G=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this.origPush,e=this.origReplace,s=()=>this.checkChange();history.pushState=function(...r){t.apply(this,r),s()},history.replaceState=function(...r){e.apply(this,r),s()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let i=document.querySelector("title");i&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(i,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function Ct(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return!0;let[e,s,i]=[+t[1],+t[2],+t[3]],r=Math.max(e,s,i),a=Math.min(e,s,i);return(r===0?0:(r-a)/r)<.15}function w(){let n=getComputedStyle(document.documentElement),t=getComputedStyle(document.body),e=t.backgroundColor||"",r={bgColor:!e||e==="rgba(0, 0, 0, 0)"||e==="transparent"?n.backgroundColor||"":e,fontFamily:t.fontFamily||"",textColor:t.color||"",primaryColor:"",accentColors:[]};try{let a=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],o={};for(let u of a){let m=document.querySelectorAll(u);for(let h=0;h<Math.min(m.length,10);h++){let S=getComputedStyle(m[h]),g=S.color;g&&g!==r.textColor&&g!=="rgb(0, 0, 0)"&&g!=="rgba(0, 0, 0, 0)"&&!Ct(g)&&(o[g]=(o[g]||0)+1);let x=S.backgroundColor;x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"&&x!==r.bgColor&&!Ct(x)&&(o[x]=(o[x]||0)+1)}}let l=Object.keys(o).sort((u,m)=>o[m]-o[u]);r.primaryColor=l[0]||"",r.accentColors=l.slice(0,5)}catch(a){}return r}var Yt=`
|
|
3
3
|
.max-widget-container{position:fixed;bottom:20px;z-index:999999;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
|
4
4
|
.max-widget-container.right{right:20px}
|
|
5
5
|
.max-widget-container.left{left:20px}
|
|
6
|
-
.max-widget-btn{width:56px;height:56px;border-radius:50%;border:none;cursor:
|
|
6
|
+
.max-widget-btn{width:56px;height:56px;border-radius:50%;border:none;cursor:grab;position:relative;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(0,0,0,0.3);transition:transform 0.2s,box-shadow 0.2s,opacity 0.2s}
|
|
7
7
|
.max-widget-btn:hover{transform:scale(1.05);box-shadow:0 6px 16px rgba(0,0,0,0.4)}
|
|
8
|
+
.max-widget-btn::after{content:'';position:absolute;top:-6px;left:-6px;right:-6px;bottom:-6px;border-radius:50%;border:2px dashed rgba(255,255,255,0);transition:border-color 0.2s;pointer-events:none}
|
|
9
|
+
.max-widget-btn:hover::after{border-color:rgba(255,255,255,0.45)}
|
|
10
|
+
.max-widget-btn.dragging{cursor:grabbing!important;transform:scale(1.08)!important;box-shadow:0 8px 20px rgba(0,0,0,0.5)!important}
|
|
11
|
+
.max-widget-btn.dragging::after{border-color:rgba(255,255,255,0.65)}
|
|
8
12
|
.max-widget-btn svg{width:24px;height:24px;fill:white}
|
|
9
|
-
.max-widget-
|
|
10
|
-
.max-widget-
|
|
11
|
-
.max-widget-
|
|
12
|
-
.max-widget-
|
|
13
|
-
.max-widget-
|
|
14
|
-
.max-widget-
|
|
15
|
-
.max-widget-
|
|
16
|
-
.max-widget-
|
|
17
|
-
.max-widget-
|
|
13
|
+
.max-widget-shell{position:absolute;bottom:0;width:380px;height:600px;border-radius:16px;background:transparent;overflow:hidden;transition:opacity 0.2s,transform 0.2s;opacity:0;transform:translateY(10px) scale(0.95);pointer-events:none;box-shadow:0 8px 32px rgba(0,0,0,0.3)}
|
|
14
|
+
.max-widget-shell.open~.max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
15
|
+
.max-widget-shell.right{right:0}
|
|
16
|
+
.max-widget-shell.left{left:0}
|
|
17
|
+
.max-widget-shell.open{opacity:1;transform:translateY(0) scale(1);pointer-events:auto}
|
|
18
|
+
.max-widget-shell.expanded{position:fixed;top:0;bottom:0;width:440px;height:100vh;height:100dvh;border-radius:0;box-shadow:-4px 0 24px rgba(0,0,0,0.2);opacity:1;transform:translateX(0);pointer-events:auto;transition:transform 0.3s ease,width 0.3s ease,border-radius 0.3s ease,box-shadow 0.3s ease}
|
|
19
|
+
.max-widget-shell.expanded.right{right:0;left:auto}
|
|
20
|
+
.max-widget-shell.expanded.left{left:0;right:auto}
|
|
21
|
+
.max-widget-shell.expanded.panel-hidden.right{transform:translateX(100%)}
|
|
22
|
+
.max-widget-shell.expanded.panel-hidden.left{transform:translateX(-100%)}
|
|
23
|
+
.max-widget-shell.glassmorphism{background:linear-gradient(180deg,rgba(12,18,30,0.2),rgba(6,10,18,0.12));backdrop-filter:blur(28px) saturate(185%);-webkit-backdrop-filter:blur(28px) saturate(185%);border:1px solid rgba(255,255,255,0.16);box-shadow:0 18px 48px rgba(0,0,0,0.28)}
|
|
24
|
+
.max-widget-shell.auto-adaptive{background:rgba(8,12,24,0.12);backdrop-filter:blur(12px) saturate(150%);-webkit-backdrop-filter:blur(12px) saturate(150%);border:1px solid rgba(255,255,255,0.12)}
|
|
18
25
|
.max-widget-container.panel-expanded .max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
19
26
|
.max-widget-container.panel-hidden-state .max-widget-btn{opacity:0;pointer-events:none;transform:scale(0.8)}
|
|
27
|
+
.max-widget-frame{display:block;width:100%;height:100%;border:none;background:transparent;border-radius:inherit}
|
|
20
28
|
.max-widget-tab{position:fixed;top:12px;z-index:999999;width:40px;height:40px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:-2px 2px 8px rgba(0,0,0,0.2);transition:opacity 0.2s,transform 0.2s;opacity:0;pointer-events:none;transform:translateX(8px)}
|
|
21
29
|
.max-widget-tab.right{right:0;border-radius:8px 0 0 8px}
|
|
22
30
|
.max-widget-tab.left{left:0;border-radius:0 8px 8px 0}
|
|
@@ -24,6 +32,11 @@ var rt=Object.defineProperty;var A=Object.getOwnPropertySymbols;var at=Object.pr
|
|
|
24
32
|
.max-widget-tab.visible{opacity:1;pointer-events:auto;transform:translateX(0)}
|
|
25
33
|
.max-widget-tab:hover{filter:brightness(1.1)}
|
|
26
34
|
.max-widget-tab svg{width:18px;height:18px;fill:white}
|
|
27
|
-
@media(max-width:420px){.max-widget-
|
|
28
|
-
@media(max-width:420px){.max-widget-
|
|
29
|
-
|
|
35
|
+
@media(max-width:420px){.max-widget-shell{width:calc(100vw - 40px);height:calc(100vh - 120px)}}
|
|
36
|
+
@media(max-width:420px){.max-widget-shell.expanded{width:100vw}}
|
|
37
|
+
.max-widget-drag-handle{height:18px;width:100%;cursor:grab;display:flex;align-items:center;justify-content:center;flex-shrink:0;border-radius:16px 16px 0 0}
|
|
38
|
+
.max-widget-drag-handle::after{content:'';display:block;width:32px;height:3px;border-radius:2px;background:rgba(255,255,255,0.18)}
|
|
39
|
+
.max-widget-drag-handle:hover::after{background:rgba(255,255,255,0.35)}
|
|
40
|
+
.max-widget-drag-handle.dragging{cursor:grabbing!important}
|
|
41
|
+
.max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
|
|
42
|
+
`,Jt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var Vt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',Qt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Lt(n){if(!n||n.charAt(0)!=="#")return null;let t=n.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),t.length!==6?null:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function kt(n,t){let e=Lt(n);if(!e)return n;let s=Math.max(0,Math.min(255,Math.round(e.r+255*t))),i=Math.max(0,Math.min(255,Math.round(e.g+255*t))),r=Math.max(0,Math.min(255,Math.round(e.b+255*t))),a=o=>{let l=o.toString(16);return l.length===1?"0"+l:l};return"#"+a(s)+a(i)+a(r)}function R(n,t){let e=Lt(n);return e?`rgba(${e.r},${e.g},${e.b},${t})`:`rgba(99,102,241,${t})`}function Zt(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return"";let e=s=>{let i=s.toString(16);return i.length===1?"0"+i:i};return"#"+e(+t[1])+e(+t[2])+e(+t[3])}function It(n,t,e,s){let i=te(e)||s||"#6366f1",r=[n.btn,n.tab];for(let a of r)if(a)if(a.style.background="",a.style.backgroundColor="",a.style.border="none",a.style.backdropFilter="",a.style.webkitBackdropFilter="",a.style.boxShadow="",t==="glassmorphism")a.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",a.style.border="1px solid rgba(255, 255, 255, 0.18)",a.style.backdropFilter="blur(18px) saturate(180%)",a.style.webkitBackdropFilter="blur(18px) saturate(180%)",a.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(t==="auto-adaptive"){let o=kt(i,.08),l=kt(i,-.06);a.style.background=`linear-gradient(180deg, ${R(o,.96)}, ${R(l,.92)})`,a.style.border=`1px solid ${R(i,.24)}`,a.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${R(i,.22)}`}else a.style.backgroundColor=s||i,a.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),t==="glassmorphism"?n.shell.classList.add("glassmorphism"):t==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function te(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?Zt(n):"":""}function Ot(n,t,e,s,i,r){if(document.querySelector(".max-widget-container"))return null;let a=document.createElement("style");i&&(a.nonce=i),a.textContent=Yt,document.head.appendChild(a);let o=document.createElement("div");o.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(o);let l=document.createElement("div");l.className="max-widget-shell "+(e?"right":"left"),o.appendChild(l);let u=document.createElement("div");u.className="max-widget-drag-handle",l.appendChild(u);let m=document.createElement("iframe");m.className="max-widget-frame",m.src=n+"/widget/"+t,m.setAttribute("allow","clipboard-write"),m.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),m.setAttribute("allowtransparency","true"),l.appendChild(m);let h=document.createElement("button");h.className="max-widget-btn",h.style.backgroundColor=s,h.innerHTML=Jt,o.appendChild(h);let S=!1,g=!1,x=!1,W=0,K=0,H=0,D=0;function E(d,p){let f=window.innerWidth-o.offsetWidth,$=window.innerHeight-o.offsetHeight;o.style.left=Math.max(0,Math.min(f,d))+"px",o.style.top=Math.max(0,Math.min($,p))+"px",o.style.bottom="auto",o.style.right="auto"}function X(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(o.style.left),top:parseInt(o.style.top)}))}catch(d){}N()}function N(){let d=l.offsetHeight||600,p=o.getBoundingClientRect(),f=p.top,$=window.innerHeight-p.bottom;f<d+8&&$>=d+8?(l.style.bottom="auto",l.style.top=o.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Nt(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:p,top:f}=JSON.parse(d);typeof p=="number"&&typeof f=="number"&&E(p,f)}catch(d){}}Nt(),N(),h.addEventListener("pointerdown",d=>{if(d.button!==0)return;S=!0,g=!1,W=d.clientX,K=d.clientY;let p=o.getBoundingClientRect();H=p.left,D=p.top,E(H,D),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!S)return;let p=d.clientX-W,f=d.clientY-K;!g&&(Math.abs(p)>4||Math.abs(f)>4)&&(g=!0,h.classList.add("dragging")),g&&E(H+p,D+f)}),h.addEventListener("pointerup",()=>{S&&(S=!1,h.classList.remove("dragging"),g&&(x=!0,X(),g=!1))});let M=!1,b=!1,j=0,F=0,U=0,z=0;u.addEventListener("pointerdown",d=>{if(d.button!==0)return;M=!0,b=!1,j=d.clientX,F=d.clientY;let p=o.getBoundingClientRect();U=p.left,z=p.top,E(U,z),u.setPointerCapture(d.pointerId),d.preventDefault()}),u.addEventListener("pointermove",d=>{if(!M)return;let p=d.clientX-j,f=d.clientY-F;!b&&(Math.abs(p)>4||Math.abs(f)>4)&&(b=!0,u.classList.add("dragging")),b&&E(U+p,z+f)}),u.addEventListener("pointerup",()=>{M&&(M=!1,u.classList.remove("dragging"),b&&(X(),b=!1))});let v=document.createElement("button");v.className="max-widget-tab "+(e?"right":"left"),v.style.backgroundColor=s,v.innerHTML=e?Vt:Qt,document.body.appendChild(v);let B=!1;function Ut(){B=!1,l.classList.remove("expanded","panel-hidden"),o.classList.remove("panel-expanded","panel-hidden-state"),v.classList.remove("visible"),document.body.style.overflow=""}return h.addEventListener("click",()=>{if(x){x=!1;return}if(B){Ut();return}l.classList.contains("open")?(l.classList.remove("open"),r.onClose()):(N(),l.classList.add("open"),r.onOpen())}),v.addEventListener("click",()=>{l.classList.remove("panel-hidden"),o.classList.remove("panel-hidden-state"),v.classList.remove("visible")}),{container:o,shell:l,iframe:m,btn:h,tab:v,style:a}}function At(n,t,e){let{container:s,shell:i,tab:r}=n;t?(i.classList.contains("open")||i.classList.add("open"),i.classList.add("expanded"),s.classList.add("panel-expanded"),i.classList.remove("panel-hidden"),s.classList.remove("panel-hidden-state"),r.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(i.classList.remove("expanded","panel-hidden"),s.classList.remove("panel-expanded","panel-hidden-state"),r.classList.remove("visible"),document.body.style.overflow="")}function Gt(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Rt(n){n.container.remove(),n.tab.remove(),n.style.remove()}function Pt(n){n.shell.classList.add("open")}function Ht(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var P=class{constructor(t){this.emitter=new C;this.debug=new O;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.storedSessionToken=null;this.storedIdentity=null;this.key=t.key,this.isRight=t.position!=="bottom-left",this.nonce=t.nonce||null;let e=document.querySelector(`script[data-key="${t.key}"]`);e&&e.src?this.baseUrl=e.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):t.baseUrl?this.baseUrl=t.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new _(this.baseUrl),this.tools=new I(this.transport),this.pointAndAsk=new A(this.transport),this.spaDetector=new G(()=>{var s;if(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.ui){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}}),this.init()}readOrCreateVisitorId(){let t=`maxai_vid_${this.key}`;try{let s=localStorage.getItem(t);if(s)return s}catch(s){}let e=this.getCookie(t);if(e){try{localStorage.setItem(t,e)}catch(s){}return e}return this.generateUUID()}persistVisitorId(t){let e=`maxai_vid_${this.key}`;try{localStorage.setItem(e,t)}catch(s){}this.setCookie(e,t,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(t){}return null}saveSessionToken(t){this.storedSessionToken=t;try{localStorage.setItem(`maxai_st_${this.key}`,t)}catch(e){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(t){}}readStoredIdentity(){try{let t=localStorage.getItem(`maxai_identity_${this.key}`);if(t)return JSON.parse(t)}catch(t){}return null}saveIdentity(t){this.storedIdentity=t;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(t))}catch(e){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}setCookie(t,e,s){try{let i=new Date;i.setTime(i.getTime()+s*864e5),document.cookie=`${t}=${e};expires=${i.toUTCString()};path=/;SameSite=Lax;Secure`}catch(i){}}getCookie(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?e[1]:null}catch(e){return null}}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(e){t={}}this.config={pageContext:t.enable_page_context||!1,pointAndAsk:t.enable_point_and_ask||!1,debugMode:t.enable_debug_mode||!1,bugReport:t.enable_bug_reports||!1,clientTools:t.enable_client_tools||!1,autoTheme:t.theme_mode!=="manual",themeMode:t.theme_mode||"manual",gdprRequired:t.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=t.primary_color||"#6366f1",this.ui=Ot(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.ui&&(this.applyTheme(this.config.autoTheme?w().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var e,s;if(this.transport.markReady(),this.config&&this.transport.send(nt,{features:this.config}),(!((e=this.config)!=null&&e.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme)){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers())}setupMessageHandlers(){this.transport.listen(st,t=>{this.ui&&At(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(it,()=>{this.ui&&Gt(this.ui)}),this.transport.listen(rt,()=>{this.close()}),this.transport.listen(ot,()=>{this.sendPageContext()}),this.transport.listen(at,()=>{this.pointAndAsk.start()}),this.transport.listen(lt,()=>{this.pointAndAsk.stop()}),this.transport.listen(dt,t=>{let e=t.toolCallId,s=t.slug||t.name,i=t.args;this.emitter.emit("tool:call",{id:e,name:s,args:i}),this.tools.execute(e,s,i).then(r=>{this.emitter.emit("tool:result",{id:e,name:s,ok:r.ok,error:r.error})})}),this.transport.listen(ct,()=>{this.transport.send(et,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(pt,()=>{let t=w();this.applyTheme(t.primaryColor),this.transport.send(T,{styles:t})}),this.transport.listen(ht,()=>{var t,e;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme){let s=w();this.applyTheme(s.primaryColor),this.transport.send(T,{styles:s})}}),this.transport.listen(gt,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(ut,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(mt,t=>{this.emitter.emit("error",{message:t.error})}),this.transport.listen(xt,()=>{this.transport.send(vt,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(ft,t=>{t.sessionToken&&this.saveSessionToken(t.sessionToken)}),this.transport.listen(yt,()=>{this.clearSessionToken()}),this.transport.listen(St,t=>{try{localStorage.setItem(`maxai_draft_${this.key}`,t.text||"")}catch(e){}}),this.transport.listen(bt,()=>{let t="";try{t=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(e){}this.transport.send(wt,{text:t})})}applyTheme(t){!this.ui||!this.config||It(this.ui,this.config.themeMode,t,this.primaryColor)}sendPageContext(){var s;if(!this.consentGiven&&((s=this.config)!=null&&s.gdprRequired))return;let t=Mt(this.key),e=_t(t,this.explicitContext);this.transport.send(V,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}setIdentity(t){this.saveIdentity(t),this.transport.send(Et,{identityPayload:t})}registerTool(t){return this.tools.register(t)}unregisterTool(t){this.tools.unregister(t)}on(t,e){return this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}open(){this.ui&&(Pt(this.ui),this.emitter.emit("open"))}close(){this.ui&&(Ht(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&Rt(this.ui),this.ui=null}};var c=null,Dt={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new P(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,t){return c?c.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let t=n.getAttribute("data-key");t&&Dt.init({key:t,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=Dt);export{Dt as MaxAI};
|
package/package.json
CHANGED