@salesforce/platform-sdk 3.0.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.
Files changed (122) hide show
  1. package/LICENSE.txt +82 -0
  2. package/README.md +62 -0
  3. package/dist/analytics/analytics.d.ts +21 -0
  4. package/dist/analytics/analytics.d.ts.map +1 -0
  5. package/dist/analytics/error-listener.d.ts +9 -0
  6. package/dist/analytics/error-listener.d.ts.map +1 -0
  7. package/dist/analytics/index.d.ts +8 -0
  8. package/dist/analytics/index.d.ts.map +1 -0
  9. package/dist/analytics/method-configs.d.ts +11 -0
  10. package/dist/analytics/method-configs.d.ts.map +1 -0
  11. package/dist/analytics/proxy.d.ts +14 -0
  12. package/dist/analytics/proxy.d.ts.map +1 -0
  13. package/dist/analytics/schemas.d.ts +7 -0
  14. package/dist/analytics/schemas.d.ts.map +1 -0
  15. package/dist/analytics/subscribe-wrapper.d.ts +7 -0
  16. package/dist/analytics/subscribe-wrapper.d.ts.map +1 -0
  17. package/dist/analytics/types.d.ts +90 -0
  18. package/dist/analytics/types.d.ts.map +1 -0
  19. package/dist/chat/index.d.ts +22 -0
  20. package/dist/chat/index.d.ts.map +1 -0
  21. package/dist/chat/mcpapps.d.ts +61 -0
  22. package/dist/chat/mcpapps.d.ts.map +1 -0
  23. package/dist/chat/openai.d.ts +25 -0
  24. package/dist/chat/openai.d.ts.map +1 -0
  25. package/dist/chat/salesforce-acc.d.ts +13 -0
  26. package/dist/chat/salesforce-acc.d.ts.map +1 -0
  27. package/dist/chat/singleton.d.ts +32 -0
  28. package/dist/chat/singleton.d.ts.map +1 -0
  29. package/dist/core/acc-types.d.ts +49 -0
  30. package/dist/core/acc-types.d.ts.map +1 -0
  31. package/dist/core/capabilities.d.ts +40 -0
  32. package/dist/core/capabilities.d.ts.map +1 -0
  33. package/dist/core/chat.d.ts +203 -0
  34. package/dist/core/chat.d.ts.map +1 -0
  35. package/dist/core/data.d.ts +38 -0
  36. package/dist/core/data.d.ts.map +1 -0
  37. package/dist/core/index.d.ts +24 -0
  38. package/dist/core/index.d.ts.map +1 -0
  39. package/dist/core/jsonrpc-client.d.ts +167 -0
  40. package/dist/core/jsonrpc-client.d.ts.map +1 -0
  41. package/dist/core/jsonrpc.d.ts +123 -0
  42. package/dist/core/jsonrpc.d.ts.map +1 -0
  43. package/dist/core/lightning.d.ts +42 -0
  44. package/dist/core/lightning.d.ts.map +1 -0
  45. package/dist/core/mcpapps-session.d.ts +107 -0
  46. package/dist/core/mcpapps-session.d.ts.map +1 -0
  47. package/dist/core/mfe-protocol/message-channel-transport.d.ts +79 -0
  48. package/dist/core/mfe-protocol/message-channel-transport.d.ts.map +1 -0
  49. package/dist/core/options.d.ts +16 -0
  50. package/dist/core/options.d.ts.map +1 -0
  51. package/dist/core/platforms.d.ts +229 -0
  52. package/dist/core/platforms.d.ts.map +1 -0
  53. package/dist/core/sdk-promise.d.ts +14 -0
  54. package/dist/core/sdk-promise.d.ts.map +1 -0
  55. package/dist/core/surface.d.ts +24 -0
  56. package/dist/core/surface.d.ts.map +1 -0
  57. package/dist/core/view.d.ts +308 -0
  58. package/dist/core/view.d.ts.map +1 -0
  59. package/dist/data/gql.d.ts +7 -0
  60. package/dist/data/gql.d.ts.map +1 -0
  61. package/dist/data/index.d.ts +34 -0
  62. package/dist/data/index.d.ts.map +1 -0
  63. package/dist/data/mosaic/fetch.d.ts +21 -0
  64. package/dist/data/mosaic/fetch.d.ts.map +1 -0
  65. package/dist/data/mosaic/index.d.ts +22 -0
  66. package/dist/data/mosaic/index.d.ts.map +1 -0
  67. package/dist/data/openai/index.d.ts +9 -0
  68. package/dist/data/openai/index.d.ts.map +1 -0
  69. package/dist/data/shared/graphql/cache/command.d.ts +93 -0
  70. package/dist/data/shared/graphql/cache/command.d.ts.map +1 -0
  71. package/dist/data/shared/graphql/cache/index.d.ts +7 -0
  72. package/dist/data/shared/graphql/cache/index.d.ts.map +1 -0
  73. package/dist/data/shared/graphql/headers.d.ts +13 -0
  74. package/dist/data/shared/graphql/headers.d.ts.map +1 -0
  75. package/dist/data/shared/url-utils.d.ts +9 -0
  76. package/dist/data/shared/url-utils.d.ts.map +1 -0
  77. package/dist/data/webapp/client-headers.interceptor.d.ts +12 -0
  78. package/dist/data/webapp/client-headers.interceptor.d.ts.map +1 -0
  79. package/dist/data/webapp/csrf/header.interceptor.d.ts +19 -0
  80. package/dist/data/webapp/csrf/header.interceptor.d.ts.map +1 -0
  81. package/dist/data/webapp/csrf/retry.interceptor.d.ts +8 -0
  82. package/dist/data/webapp/csrf/retry.interceptor.d.ts.map +1 -0
  83. package/dist/data/webapp/csrf/retry.policy.d.ts +31 -0
  84. package/dist/data/webapp/csrf/retry.policy.d.ts.map +1 -0
  85. package/dist/data/webapp/csrf/token-manager.d.ts +42 -0
  86. package/dist/data/webapp/csrf/token-manager.d.ts.map +1 -0
  87. package/dist/data/webapp/fetch.d.ts +27 -0
  88. package/dist/data/webapp/fetch.d.ts.map +1 -0
  89. package/dist/data/webapp/index.d.ts +19 -0
  90. package/dist/data/webapp/index.d.ts.map +1 -0
  91. package/dist/index.d.ts +13 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +1506 -0
  94. package/dist/lightning/index.d.ts +15 -0
  95. package/dist/lightning/index.d.ts.map +1 -0
  96. package/dist/telemetry/action-piggyback.d.ts +7 -0
  97. package/dist/telemetry/action-piggyback.d.ts.map +1 -0
  98. package/dist/telemetry/buffer.d.ts +22 -0
  99. package/dist/telemetry/buffer.d.ts.map +1 -0
  100. package/dist/telemetry/index.d.ts +10 -0
  101. package/dist/telemetry/index.d.ts.map +1 -0
  102. package/dist/telemetry/transport.d.ts +3 -0
  103. package/dist/telemetry/transport.d.ts.map +1 -0
  104. package/dist/telemetry/types.d.ts +32 -0
  105. package/dist/telemetry/types.d.ts.map +1 -0
  106. package/dist/telemetry/uploader/TelemetryUploader.d.ts +43 -0
  107. package/dist/telemetry/uploader/TelemetryUploader.d.ts.map +1 -0
  108. package/dist/telemetry/uploader/interfaces.d.ts +61 -0
  109. package/dist/telemetry/uploader/interfaces.d.ts.map +1 -0
  110. package/dist/telemetry/widget-state-flush.d.ts +14 -0
  111. package/dist/telemetry/widget-state-flush.d.ts.map +1 -0
  112. package/dist/view/index.d.ts +22 -0
  113. package/dist/view/index.d.ts.map +1 -0
  114. package/dist/view/mcpapps.d.ts +24 -0
  115. package/dist/view/mcpapps.d.ts.map +1 -0
  116. package/dist/view/openai.d.ts +11 -0
  117. package/dist/view/openai.d.ts.map +1 -0
  118. package/dist/view/singleton.d.ts +32 -0
  119. package/dist/view/singleton.d.ts.map +1 -0
  120. package/dist/view/utils.d.ts +59 -0
  121. package/dist/view/utils.d.ts.map +1 -0
  122. package/package.json +51 -0
package/dist/index.js ADDED
@@ -0,0 +1,1506 @@
1
+ import { buildServiceDescriptor as R, setHeader as S } from "@conduit-client/service-fetch-network/v1";
2
+ import { resolvedPromiseLike as C } from "@conduit-client/utils";
3
+ import { RetryPolicy as N, buildServiceDescriptor as U } from "@conduit-client/service-retry/v1";
4
+ import { encodeCoreEnvelopeContentsRaw as q } from "o11y/collectors";
5
+ import { SimpleCollector as W } from "o11y/simple_collector";
6
+ import { registerInstrumentedApp as V } from "o11y/client";
7
+ import { analyticsContextSchema as $, sessionSchema as B, pageViewSchema as K, errorContextSchema as j, interactionSchema as z, customEventSchema as J } from "o11y_schema/sf_mcpanalytics";
8
+ var o = /* @__PURE__ */ ((s) => (s.WebApp = "WebApp", s.MicroFrontend = "Micro-Frontend", s.OpenAI = "OpenAI", s.SalesforceACC = "Salesforce-ACC", s.MCPApps = "MCP-Apps", s.Mosaic = "Mosaic", s))(o || {});
9
+ const X = Y();
10
+ function Y() {
11
+ if (typeof window > "u")
12
+ return "Mosaic";
13
+ if (window.openai)
14
+ return "OpenAI";
15
+ try {
16
+ if (window.self !== window.top)
17
+ return "Micro-Frontend";
18
+ } catch {
19
+ return "Micro-Frontend";
20
+ }
21
+ const s = window;
22
+ return s.$A || s.Aura ? "Salesforce-ACC" : "WebApp";
23
+ }
24
+ function T(s) {
25
+ return s ?? X;
26
+ }
27
+ function _(s) {
28
+ return typeof s == "object" && s !== null && "jsonrpc" in s && s.jsonrpc === "2.0";
29
+ }
30
+ function G(s) {
31
+ return _(s) && "id" in s && typeof s.id == "number" && "result" in s;
32
+ }
33
+ function x(s) {
34
+ return _(s) && "id" in s && typeof s.id == "number" && "error" in s;
35
+ }
36
+ function Q(s) {
37
+ return G(s) || x(s);
38
+ }
39
+ function Z(s) {
40
+ return _(s) && "method" in s && typeof s.method == "string" && !("id" in s);
41
+ }
42
+ function yt(s) {
43
+ return _(s) && "id" in s && typeof s.id == "number" && "method" in s && typeof s.method == "string";
44
+ }
45
+ class ee {
46
+ targetOrigin;
47
+ /**
48
+ * @param targetOrigin - origin passed as the second argument to
49
+ * `window.parent.postMessage`. Defaults to `"*"` for backwards
50
+ * compatibility. Pin to the known parent origin when possible to
51
+ * prevent leaking messages to a cross-origin navigated parent.
52
+ */
53
+ constructor(e = "*") {
54
+ this.targetOrigin = e;
55
+ }
56
+ post(e) {
57
+ window.parent?.postMessage(e, this.targetOrigin);
58
+ }
59
+ onMessage(e) {
60
+ const t = (n) => {
61
+ e(n.data);
62
+ };
63
+ return window.addEventListener("message", t), () => window.removeEventListener("message", t);
64
+ }
65
+ }
66
+ class te {
67
+ nextRequestId = 1;
68
+ pending = /* @__PURE__ */ new Map();
69
+ notificationHandlers = /* @__PURE__ */ new Map();
70
+ transport;
71
+ /**
72
+ * Construct a JSON-RPC client bound to the given transport.
73
+ *
74
+ * @param transport - the transport to use; defaults to a
75
+ * `WindowPostMessageTransport`, which preserves the original
76
+ * `window.parent.postMessage` behaviour.
77
+ */
78
+ constructor(e = new ee()) {
79
+ this.transport = e, this.transport.onMessage(this.onMessage);
80
+ }
81
+ /**
82
+ * Register a handler for a specific JSON-RPC notification method
83
+ *
84
+ * Subclasses can register handlers to process specific notification types.
85
+ * When a notification with the registered method is received, the handler
86
+ * will be invoked with the notification params.
87
+ *
88
+ * @param method - The notification method to handle (e.g. "ui/notifications/host-context-changed")
89
+ * @param handler - Callback function to process the notification params
90
+ *
91
+ * @example
92
+ * this.registerNotificationHandler("ui/notifications/host-context-changed", (params) => {
93
+ * this.handleHostContextChanged(params);
94
+ * });
95
+ */
96
+ registerNotificationHandler(e, t) {
97
+ this.notificationHandlers.has(e) || this.notificationHandlers.set(e, /* @__PURE__ */ new Set()), this.notificationHandlers.get(e).add(t);
98
+ }
99
+ /**
100
+ * Handle inbound JSON-RPC messages from the transport.
101
+ *
102
+ * Processes both responses (for requests) and notifications. Non-JSON-RPC
103
+ * payloads are silently ignored so that a shared transport can be used for
104
+ * multiple protocols without cross-talk.
105
+ */
106
+ onMessage = (e) => {
107
+ if (Q(e)) {
108
+ const t = this.pending.get(e.id);
109
+ if (!t)
110
+ return;
111
+ this.pending.delete(e.id), x(e) ? t.reject(new Error(e.error.message || "Request failed")) : t.resolve(e.result);
112
+ return;
113
+ }
114
+ if (Z(e)) {
115
+ const t = this.notificationHandlers.get(e.method);
116
+ t && t.forEach((n) => n(e.params));
117
+ }
118
+ };
119
+ /**
120
+ * Send a JSON-RPC request to the peer.
121
+ *
122
+ * @param method - The JSON-RPC method name
123
+ * @param params - The method parameters
124
+ * @returns Promise that resolves with the result or rejects with error
125
+ *
126
+ * @example
127
+ * const result = await this.request("ui/message", {
128
+ * role: "user",
129
+ * content: { type: "text", text: "Hello" }
130
+ * });
131
+ */
132
+ request(e, t) {
133
+ const n = this.nextRequestId++, i = {
134
+ jsonrpc: "2.0",
135
+ id: n,
136
+ method: e,
137
+ params: t
138
+ };
139
+ return new Promise((r, a) => {
140
+ this.pending.set(n, {
141
+ resolve: r,
142
+ reject: a
143
+ }), this.transport.post(i);
144
+ });
145
+ }
146
+ /**
147
+ * Send a JSON-RPC notification to the peer.
148
+ *
149
+ * Notifications are one-way messages that do not expect a response.
150
+ * Use notifications for:
151
+ * - Informing the host of state changes
152
+ * - Fire-and-forget operations
153
+ * - Events that don't require confirmation
154
+ *
155
+ * Use request() instead when you need:
156
+ * - A response from the host
157
+ * - Confirmation of success/failure
158
+ * - Return values from the operation
159
+ *
160
+ * @param method - The JSON-RPC method name
161
+ * @param params - Optional method parameters
162
+ *
163
+ * @example
164
+ * this.sendNotification("ui/notifications/size-changed", {
165
+ * width: 800,
166
+ * height: 600
167
+ * });
168
+ */
169
+ sendNotification(e, t) {
170
+ const n = {
171
+ jsonrpc: "2.0",
172
+ method: e,
173
+ params: t
174
+ };
175
+ this.transport.post(n);
176
+ }
177
+ }
178
+ function se() {
179
+ }
180
+ class Ct {
181
+ #e;
182
+ #s = /* @__PURE__ */ new Set();
183
+ #i = !1;
184
+ #n = !1;
185
+ /** Messages queued before `port.start()` has been called. Flushed on first subscribe. */
186
+ #t = [];
187
+ constructor(e) {
188
+ this.#e = e;
189
+ }
190
+ /**
191
+ * Post a message to the peer.
192
+ *
193
+ * Never throws on transient failure — a closed / neutered / disposed
194
+ * port silently drops the message. If the transport has not yet
195
+ * started (no `onMessage` subscriber), the message is buffered and
196
+ * flushed on first subscription.
197
+ */
198
+ post(e) {
199
+ if (!this.#n) {
200
+ if (!this.#i) {
201
+ this.#t.push(e);
202
+ return;
203
+ }
204
+ try {
205
+ this.#e.postMessage(e);
206
+ } catch {
207
+ }
208
+ }
209
+ }
210
+ /**
211
+ * Subscribe to inbound messages from the peer. The callback receives
212
+ * the **unwrapped** payload (`MessageEvent.data`) — callers never see
213
+ * the `MessageEvent` wrapper.
214
+ *
215
+ * Starts the underlying port on first subscription and flushes any
216
+ * messages queued via `post` before the port was started.
217
+ *
218
+ * Returns an unsubscribe function. Calling it is idempotent.
219
+ */
220
+ onMessage(e) {
221
+ if (this.#n)
222
+ return se;
223
+ this.#s.add(e), this.#i || this.#o();
224
+ let t = !1;
225
+ return () => {
226
+ t || (t = !0, this.#s.delete(e));
227
+ };
228
+ }
229
+ /**
230
+ * Tear down the transport:
231
+ * - remove the internal `message` listener
232
+ * - call `port.close()`
233
+ * - clear subscriber set and outbound buffer
234
+ * - subsequent `post` calls silently no-op
235
+ * - subsequent `onMessage` calls return a no-op unsubscribe
236
+ */
237
+ dispose() {
238
+ if (!this.#n) {
239
+ this.#n = !0;
240
+ try {
241
+ this.#e.removeEventListener("message", this.#r);
242
+ } catch {
243
+ }
244
+ this.#s.clear(), this.#t.length = 0;
245
+ try {
246
+ this.#e.close();
247
+ } catch {
248
+ }
249
+ }
250
+ }
251
+ #o() {
252
+ this.#i = !0, this.#e.addEventListener("message", this.#r);
253
+ try {
254
+ this.#e.start();
255
+ } catch {
256
+ }
257
+ if (this.#t.length > 0) {
258
+ const e = this.#t;
259
+ this.#t = [];
260
+ for (const t of e)
261
+ try {
262
+ this.#e.postMessage(t);
263
+ } catch {
264
+ }
265
+ }
266
+ }
267
+ #r = (e) => {
268
+ const t = [...this.#s];
269
+ for (const n of t)
270
+ try {
271
+ n(e.data);
272
+ } catch {
273
+ }
274
+ };
275
+ }
276
+ const ne = 500, ie = "2026-01-26";
277
+ class g extends te {
278
+ static initPromise = null;
279
+ hostCtx = {};
280
+ _handshakeSucceeded = !1;
281
+ /**
282
+ * Get or create the shared session singleton.
283
+ *
284
+ * The first call performs the SEP-1865 handshake. Concurrent and subsequent
285
+ * calls reuse the same session and handshake result.
286
+ */
287
+ static async getInstance(e) {
288
+ return g.initPromise || (g.initPromise = (async () => {
289
+ const t = new g();
290
+ return await t.handshake(e), t;
291
+ })()), g.initPromise;
292
+ }
293
+ /**
294
+ * Reset the singleton (for testing only).
295
+ * @internal
296
+ */
297
+ static resetInstance() {
298
+ g.initPromise = null;
299
+ }
300
+ /**
301
+ * Perform the ui/initialize → hostContext → ui/notifications/initialized handshake.
302
+ *
303
+ * On success, stores the host context and sends the initialized notification.
304
+ * On timeout or error, falls back to an empty host context so the app can
305
+ * still render (graceful degradation for non-SEP-1865 hosts).
306
+ */
307
+ async handshake(e) {
308
+ const t = e?.handshakeTimeoutMs ?? ne, n = e?.appInfo ?? { name: "mcp-app", version: "1.0.0" };
309
+ try {
310
+ const i = /* @__PURE__ */ Symbol("timeout"), r = await Promise.race([
311
+ this.request("ui/initialize", {
312
+ protocolVersion: ie,
313
+ appInfo: n,
314
+ appCapabilities: {}
315
+ }),
316
+ new Promise((a) => setTimeout(() => a(i), t))
317
+ ]);
318
+ r !== i && (this.hostCtx = r.hostContext ?? {}, this._handshakeSucceeded = !0, this.registerNotificationHandler("ui/notifications/host-context-changed", (a) => {
319
+ this.hostCtx = {
320
+ ...this.hostCtx,
321
+ ...a
322
+ };
323
+ }), this.sendNotification("ui/notifications/initialized"));
324
+ } catch {
325
+ }
326
+ }
327
+ /** Returns the current host context (handshake + notification updates). */
328
+ getHostContext() {
329
+ return this.hostCtx;
330
+ }
331
+ /** Whether the ui/initialize handshake completed successfully (not timed out). */
332
+ get handshakeSucceeded() {
333
+ return this._handshakeSucceeded;
334
+ }
335
+ // ── Public wrappers ──────────────────────────────────────────────────
336
+ // Widen access from protected to public so SDK classes can use the
337
+ // shared transport without extending JsonRpcClient themselves.
338
+ request(e, t) {
339
+ return super.request(e, t);
340
+ }
341
+ sendNotification(e, t) {
342
+ super.sendNotification(e, t);
343
+ }
344
+ registerNotificationHandler(e, t) {
345
+ super.registerNotificationHandler(e, t);
346
+ }
347
+ }
348
+ const re = {
349
+ callTool: !0,
350
+ sendMessageToHost: !0,
351
+ readResource: !0,
352
+ openLink: !0,
353
+ accessToolInput: !0,
354
+ accessToolOutput: !0,
355
+ accessToolMetadata: !0,
356
+ getWidgetState: !0,
357
+ setWidgetState: !0,
358
+ onToolCanceled: !0,
359
+ setDisplayMode: !0,
360
+ getHostContext: !0,
361
+ subscribe: !0,
362
+ displayAlert: !0,
363
+ displayToast: !0,
364
+ displayModal: !1,
365
+ // TODO
366
+ getTheme: !0,
367
+ resize: !0
368
+ }, oe = {
369
+ callTool: !0,
370
+ sendMessageToHost: !0,
371
+ readResource: !1,
372
+ openLink: !0,
373
+ accessToolInput: !0,
374
+ accessToolOutput: !0,
375
+ accessToolMetadata: !0,
376
+ getWidgetState: !0,
377
+ setWidgetState: !0,
378
+ onToolCanceled: !1,
379
+ setDisplayMode: !0,
380
+ getHostContext: !1,
381
+ subscribe: !0,
382
+ displayAlert: !0,
383
+ displayToast: !0,
384
+ displayModal: !0,
385
+ getTheme: !0,
386
+ resize: !1
387
+ }, ae = {
388
+ callTool: !1,
389
+ sendMessageToHost: !0,
390
+ readResource: !1,
391
+ openLink: !0,
392
+ accessToolInput: !1,
393
+ accessToolOutput: !1,
394
+ accessToolMetadata: !1,
395
+ getWidgetState: !1,
396
+ setWidgetState: !1,
397
+ onToolCanceled: !1,
398
+ setDisplayMode: !1,
399
+ getHostContext: !1,
400
+ subscribe: !0,
401
+ displayAlert: !0,
402
+ displayToast: !0,
403
+ displayModal: !1,
404
+ getTheme: !0,
405
+ resize: !1
406
+ }, ce = {
407
+ callTool: !1,
408
+ sendMessageToHost: !1,
409
+ readResource: !1,
410
+ openLink: !1,
411
+ accessToolInput: !1,
412
+ accessToolOutput: !1,
413
+ accessToolMetadata: !1,
414
+ getWidgetState: !1,
415
+ setWidgetState: !1,
416
+ onToolCanceled: !1,
417
+ setDisplayMode: !1,
418
+ getHostContext: !1,
419
+ subscribe: !1,
420
+ displayAlert: !1,
421
+ displayToast: !1,
422
+ displayModal: !1,
423
+ getTheme: !1,
424
+ resize: !1
425
+ };
426
+ function Tt(s) {
427
+ switch (s) {
428
+ case o.MCPApps:
429
+ return { ...re };
430
+ case o.OpenAI:
431
+ return { ...oe };
432
+ case o.SalesforceACC:
433
+ return { ...ae };
434
+ case o.Mosaic:
435
+ case o.WebApp:
436
+ case o.MicroFrontend:
437
+ default:
438
+ return { ...ce };
439
+ }
440
+ }
441
+ const le = /* @__PURE__ */ new Set(["then", "catch", "finally"]);
442
+ function A(s, e) {
443
+ return new Proxy(s, {
444
+ get(t, n, i) {
445
+ if (typeof n == "symbol" || le.has(n)) {
446
+ const r = Reflect.get(t, n, i);
447
+ return typeof r == "function" ? r.bind(t) : r;
448
+ }
449
+ throw new TypeError(
450
+ `\`${e}()\` returns a Promise — did you forget to await it?
451
+ Use \`const sdk = await ${e}();\` before accessing SDK methods.`
452
+ );
453
+ }
454
+ });
455
+ }
456
+ class ue {
457
+ constructor(e) {
458
+ this.session = e;
459
+ const t = e.getHostContext();
460
+ t.toolOutput !== void 0 && (this.globals.toolOutput = t.toolOutput), t.toolStructuredContent !== void 0 && (this.globals.toolStructuredContent = t.toolStructuredContent), t.toolInput !== void 0 && (this.globals.toolInput = t.toolInput), t.toolResponseMetadata !== void 0 && (this.globals.toolResponseMetadata = t.toolResponseMetadata), t.widgetState !== void 0 && (this.globals.widgetState = t.widgetState), e.registerNotificationHandler(
461
+ "ui/notifications/host-context-changed",
462
+ () => this.notifySubscribers()
463
+ ), e.registerNotificationHandler(
464
+ "ui/notifications/tool-result",
465
+ (n) => this.handleToolResult(n)
466
+ ), e.registerNotificationHandler(
467
+ "ui/notifications/tool-input",
468
+ (n) => this.handleToolInput(n)
469
+ ), e.registerNotificationHandler(
470
+ "ui/notifications/tool-cancelled",
471
+ (n) => this.handleToolCancelled(n)
472
+ );
473
+ }
474
+ globals = {};
475
+ canceledCallbacks = /* @__PURE__ */ new Set();
476
+ subscriptions = /* @__PURE__ */ new Set();
477
+ /**
478
+ * Handle tool result notifications from the host
479
+ * @param params - Tool result data from the host
480
+ */
481
+ handleToolResult(e) {
482
+ const t = e;
483
+ let n = !1;
484
+ t.content !== void 0 && (this.globals.toolOutput = t.content, n = !0), t.structuredContent !== void 0 && (this.globals.toolStructuredContent = t.structuredContent, n = !0), t._meta !== void 0 && (this.globals.toolResponseMetadata = t._meta, n = !0), n && this.notifySubscribers();
485
+ }
486
+ /**
487
+ * Handle tool input notifications from the host
488
+ * @param params - Tool input data from the host
489
+ */
490
+ handleToolInput(e) {
491
+ const t = e;
492
+ t.arguments !== void 0 && Object.keys(t.arguments).length > 0 && (this.globals.toolInput = t.arguments, this.notifySubscribers());
493
+ }
494
+ /**
495
+ * Handle tool cancelled notifications from the host
496
+ * @param params - Tool cancellation data from the host
497
+ */
498
+ handleToolCancelled(e) {
499
+ const n = e.reason ?? "";
500
+ this.canceledCallbacks.forEach((i) => i(n));
501
+ }
502
+ /**
503
+ * Request display mode change from host
504
+ * @param mode - The requested display mode
505
+ * @returns Promise with the new display mode (confirmed by host)
506
+ */
507
+ async setDisplayMode(e) {
508
+ return await this.session.request("ui/request-display-mode", {
509
+ displayMode: e
510
+ });
511
+ }
512
+ async sendMessageToHost(e) {
513
+ await this.session.request("ui/message", {
514
+ role: "user",
515
+ content: [
516
+ {
517
+ type: "text",
518
+ text: e.content
519
+ }
520
+ ]
521
+ });
522
+ }
523
+ async callTool(e) {
524
+ return await this.session.request("tools/call", {
525
+ name: e.toolName,
526
+ arguments: e.params ?? {}
527
+ });
528
+ }
529
+ async readResource(e) {
530
+ return await this.session.request("resources/read", {
531
+ uri: e.uri
532
+ });
533
+ }
534
+ async openLink(e) {
535
+ await this.session.request("ui/open-link", { url: e });
536
+ }
537
+ accessToolInput() {
538
+ const e = this.globals.toolInput;
539
+ return e ? { data: e } : null;
540
+ }
541
+ accessToolOutput() {
542
+ const e = this.globals.toolStructuredContent;
543
+ if (e)
544
+ return { data: e };
545
+ const t = this.globals.toolOutput;
546
+ return t ? { data: t } : null;
547
+ }
548
+ accessToolMetadata() {
549
+ if (this.globals.toolResponseMetadata)
550
+ return this.globals.toolResponseMetadata;
551
+ const e = this.session.getHostContext().toolInfo;
552
+ return e || null;
553
+ }
554
+ getWidgetState() {
555
+ const e = this.globals.widgetState;
556
+ return e || null;
557
+ }
558
+ setWidgetState(e) {
559
+ this.globals.widgetState = e, this.session.request("ui/update-model-context", { state: e }).catch(() => {
560
+ }), this.notifySubscribers();
561
+ }
562
+ /**
563
+ * Get the current host context.
564
+ *
565
+ * Maps MCP Apps wire-format fields to the protocol-agnostic HostContext.
566
+ * Always returns an object (empty `{}` when no context has been received).
567
+ */
568
+ getHostContext() {
569
+ const e = this.session.getHostContext(), t = {};
570
+ if (e.theme !== void 0 && (t.theme = e.theme), e.displayMode !== void 0 && (t.displayMode = e.displayMode), e.containerDimensions !== void 0) {
571
+ const n = e.containerDimensions.maxHeight ?? e.containerDimensions.height;
572
+ n !== void 0 && (t.maxHeight = n);
573
+ }
574
+ return e.safeAreaInsets !== void 0 && (t.safeArea = e.safeAreaInsets), e.userAgent !== void 0 && (t.userAgent = e.userAgent), e.locale !== void 0 && (t.locale = e.locale), e.deviceCapabilities !== void 0 && (t.deviceCapabilities = e.deviceCapabilities), e.styles !== void 0 && (t.styles = e.styles), t;
575
+ }
576
+ onToolCanceled(e) {
577
+ return this.canceledCallbacks.add(e), () => {
578
+ this.canceledCallbacks.delete(e);
579
+ };
580
+ }
581
+ subscribe(e) {
582
+ return this.subscriptions.add(e), () => {
583
+ this.subscriptions.delete(e);
584
+ };
585
+ }
586
+ notifySubscribers() {
587
+ this.subscriptions.forEach((e) => e());
588
+ }
589
+ }
590
+ const k = "openai:set_globals";
591
+ class de {
592
+ sendMessageToHost(e) {
593
+ return window.openai.sendFollowUpMessage({ prompt: e.content });
594
+ }
595
+ callTool(e) {
596
+ return window.openai.callTool(e.toolName, e.params ?? {});
597
+ }
598
+ accessToolInput() {
599
+ const e = window.openai.toolInput;
600
+ return e ? { data: e } : null;
601
+ }
602
+ accessToolOutput() {
603
+ const e = window.openai.toolOutput;
604
+ return e ? { data: e } : null;
605
+ }
606
+ accessToolMetadata() {
607
+ const e = window.openai.toolResponseMetadata;
608
+ return e || null;
609
+ }
610
+ getWidgetState() {
611
+ const e = window.openai.widgetState;
612
+ return e || null;
613
+ }
614
+ setWidgetState(e) {
615
+ window.openai.setWidgetState(e);
616
+ }
617
+ async openLink(e) {
618
+ const t = window.openai;
619
+ typeof t?.openExternal == "function" ? await t.openExternal({ href: e }) : window.open(e, "_blank", "noopener,noreferrer");
620
+ }
621
+ async setDisplayMode(e) {
622
+ return window.openai.requestDisplayMode({ mode: e });
623
+ }
624
+ subscribe(e) {
625
+ const t = () => e();
626
+ return window.addEventListener(k, t), () => {
627
+ window.removeEventListener(k, t);
628
+ };
629
+ }
630
+ }
631
+ class he {
632
+ async sendMessageToHost(e) {
633
+ throw console.warn("SalesforceACCChatSDK.sendMessageToHost: stub implementation", e), new Error("SalesforceACCChatSDK.sendMessageToHost not yet implemented");
634
+ }
635
+ followUpActions() {
636
+ return console.warn("SalesforceACCChatSDK.followUpActions: stub implementation"), [];
637
+ }
638
+ }
639
+ let b = null, M = null;
640
+ function fe(s) {
641
+ return b || (b = pe(s).then((e) => (M = e, e))), b;
642
+ }
643
+ function bt() {
644
+ return M;
645
+ }
646
+ function vt() {
647
+ b = null, M = null;
648
+ }
649
+ function pe(s) {
650
+ return A(
651
+ (async () => {
652
+ switch (T(s?.surface)) {
653
+ case o.OpenAI:
654
+ return new de();
655
+ case o.WebApp:
656
+ case o.Mosaic:
657
+ return {};
658
+ case o.SalesforceACC:
659
+ return new he();
660
+ case o.MicroFrontend:
661
+ case o.MCPApps: {
662
+ const t = await g.getInstance(s?.mcpApps);
663
+ return t.handshakeSucceeded ? new ue(t) : {};
664
+ }
665
+ default:
666
+ return {};
667
+ }
668
+ })(),
669
+ "createChatSDK"
670
+ );
671
+ }
672
+ function ge(s) {
673
+ switch (s) {
674
+ case "info":
675
+ return "ℹ️";
676
+ case "success":
677
+ return "✅";
678
+ case "warning":
679
+ return "⚠️";
680
+ case "error":
681
+ return "❌";
682
+ default:
683
+ return "ℹ️";
684
+ }
685
+ }
686
+ function I(s, e) {
687
+ return `${ge(e)} ${s}`;
688
+ }
689
+ function D(s, e) {
690
+ const t = s.trim();
691
+ if (t === "")
692
+ return { success: !0, value: void 0 };
693
+ const n = t.match(/^(\d+(?:\.\d+)?)(px)?$/);
694
+ if (!n || !n[1])
695
+ return {
696
+ success: !1,
697
+ error: `Invalid ${e}: "${s}". Only pixel values are supported (e.g., "800px" or "800").`
698
+ };
699
+ const i = parseFloat(n[1]);
700
+ return i < 0 || !isFinite(i) ? {
701
+ success: !1,
702
+ error: `Invalid ${e}: "${s}". Value must be a positive number.`
703
+ } : { success: !0, value: i };
704
+ }
705
+ class me {
706
+ constructor(e) {
707
+ this.session = e;
708
+ }
709
+ /**
710
+ * Send a formatted message to the host via ui/message
711
+ * @param message - The message text
712
+ * @param level - The message severity level (defaults to "info")
713
+ */
714
+ async sendMessage(e, t = "info") {
715
+ const n = I(e, t);
716
+ await this.session.request("ui/message", {
717
+ role: "user",
718
+ content: [
719
+ {
720
+ type: "text",
721
+ text: n
722
+ }
723
+ ]
724
+ });
725
+ }
726
+ async displayAlert(e) {
727
+ await this.sendMessage(e.message, e.level);
728
+ }
729
+ async displayToast(e) {
730
+ await this.sendMessage(e.message, e.level);
731
+ }
732
+ async displayModal(e) {
733
+ return Promise.resolve();
734
+ }
735
+ getTheme() {
736
+ const e = this.session.getHostContext().theme;
737
+ return e ? { mode: e } : null;
738
+ }
739
+ async resize(e, t) {
740
+ const n = D(e, "width");
741
+ if (!n.success)
742
+ return Promise.reject(new Error(n.error));
743
+ const i = D(t, "height");
744
+ if (!i.success)
745
+ return Promise.reject(new Error(i.error));
746
+ const r = {};
747
+ return n.value !== void 0 && (r.width = n.value), i.value !== void 0 && (r.height = i.value), this.session.sendNotification("ui/notifications/size-changed", r), Promise.resolve();
748
+ }
749
+ }
750
+ class we {
751
+ async displayAlert(e) {
752
+ const t = e.level || "info", n = I(e.message, t);
753
+ await window.openai.sendFollowUpMessage({ prompt: n });
754
+ }
755
+ async displayToast(e) {
756
+ const t = e.level || "info", n = I(e.message, t);
757
+ await window.openai.sendFollowUpMessage({ prompt: n });
758
+ }
759
+ async displayModal(e) {
760
+ await window.openai.requestModal({
761
+ template: e.componentReference,
762
+ params: e.params
763
+ });
764
+ }
765
+ getTheme() {
766
+ const e = window.openai.theme;
767
+ return e ? { mode: e } : null;
768
+ }
769
+ }
770
+ let v = null, E = null;
771
+ function St(s) {
772
+ return v || (v = ye(s).then((e) => (E = e, e))), v;
773
+ }
774
+ function _t() {
775
+ return E;
776
+ }
777
+ function At() {
778
+ v = null, E = null;
779
+ }
780
+ function ye(s) {
781
+ return A(
782
+ (async () => {
783
+ switch (T(s?.surface)) {
784
+ case o.OpenAI:
785
+ return new we();
786
+ case o.WebApp:
787
+ case o.Mosaic:
788
+ return {};
789
+ case o.SalesforceACC:
790
+ return {};
791
+ case o.MicroFrontend:
792
+ case o.MCPApps: {
793
+ const t = await g.getInstance(s?.mcpApps);
794
+ return t.handshakeSucceeded ? new me(t) : {};
795
+ }
796
+ default:
797
+ return {};
798
+ }
799
+ })(),
800
+ "createViewSDK"
801
+ );
802
+ }
803
+ function Ce(s) {
804
+ return (e) => {
805
+ const [t, n] = e;
806
+ if (typeof t == "string" && !t.startsWith("http")) {
807
+ const i = t.startsWith("/") ? t : `/${t}`;
808
+ return C([`${s}${i}`, n]);
809
+ }
810
+ return C(e);
811
+ };
812
+ }
813
+ function Te(s) {
814
+ return (e) => C(S("Authorization", `Bearer ${s}`, e));
815
+ }
816
+ function be(s, e) {
817
+ const t = [];
818
+ return s && t.push(Ce(s)), e && t.push(Te(e)), R({
819
+ request: t
820
+ }).service;
821
+ }
822
+ const ve = typeof __SF_API_VERSION__ < "u" ? __SF_API_VERSION__ : "65.0";
823
+ function H(s = ve) {
824
+ return `/services/data/v${s}`;
825
+ }
826
+ class Se {
827
+ clientFetch;
828
+ pathData;
829
+ constructor(e) {
830
+ const t = _e(), n = Ae(e?.instanceUrl ?? t.instanceUrl), i = e?.accessToken ?? t.accessToken;
831
+ this.pathData = H(e?.apiVersion ?? t.apiVersion), this.clientFetch = be(n || void 0, i);
832
+ }
833
+ async graphql({
834
+ query: e,
835
+ variables: t,
836
+ operationName: n
837
+ }) {
838
+ return (await this.clientFetch(`${this.pathData}/graphql`, {
839
+ method: "POST",
840
+ body: JSON.stringify({ query: e, variables: t, operationName: n }),
841
+ headers: {
842
+ "Content-Type": "application/json",
843
+ Accept: "application/json"
844
+ }
845
+ })).json();
846
+ }
847
+ }
848
+ function _e() {
849
+ const s = globalThis.MOSAIC_ENV;
850
+ return {
851
+ instanceUrl: s?.instanceUrl,
852
+ accessToken: s?.accessToken,
853
+ apiVersion: s?.apiVersion
854
+ };
855
+ }
856
+ function Ae(s) {
857
+ if (!s || s === "/") return "";
858
+ let e = s;
859
+ return !e.startsWith("/") && !e.startsWith("http") && (e = `/${e}`), e.endsWith("/") && (e = e.slice(0, -1)), e;
860
+ }
861
+ const Ie = "graphqlQuery";
862
+ class Me {
863
+ async graphql({
864
+ query: e,
865
+ variables: t,
866
+ operationName: n
867
+ }) {
868
+ return (await window.openai.callTool(Ie, {
869
+ query: e,
870
+ ...t != null ? { variables: t } : {},
871
+ ...n != null ? { operationName: n } : {}
872
+ })).structuredContent;
873
+ }
874
+ }
875
+ const Ee = "X-SFDC-Client-Name", ke = "X-SFDC-Client-Version", De = "@salesforce/platform-sdk", Pe = "3.0.0", Le = (s) => {
876
+ let e = S(Ee, De, s);
877
+ return e = S(ke, Pe, e), C(e);
878
+ }, Re = "X-CSRF-Token";
879
+ function xe(s, e = {}) {
880
+ const { protectedUrls: t = [], alwaysProtectedUrls: n = [] } = e;
881
+ return async (i) => {
882
+ const [r, a] = i, c = new Request(r, a);
883
+ if (P(n, c.url) || He(c.method) && P(t, c.url)) {
884
+ const d = await s.getToken();
885
+ i = S(Re, d, i);
886
+ }
887
+ return C(i);
888
+ };
889
+ }
890
+ function He(s) {
891
+ const e = s.toLowerCase();
892
+ return e === "post" || e === "put" || e === "patch" || e === "delete";
893
+ }
894
+ function P(s, e) {
895
+ const t = new URL(e);
896
+ return s.some((n) => t.pathname.includes(n));
897
+ }
898
+ function Oe(s, e = {}) {
899
+ const t = xe(s, e);
900
+ async function n(i) {
901
+ const r = await t(i);
902
+ return fetch(r[0], r[1]);
903
+ }
904
+ return (i, r) => r ? r.applyRetry(async () => n(i)) : n(i);
905
+ }
906
+ const Fe = [400, 401, 403];
907
+ class Ne extends N {
908
+ constructor(e) {
909
+ super(e), this.csrfTokenManager = e;
910
+ }
911
+ /**
912
+ * Determines if a failed request should be retried due to CSRF token issues.
913
+ */
914
+ async shouldRetry(e, t) {
915
+ return t.attempt >= 1 ? !1 : Fe.includes(e.status);
916
+ }
917
+ /**
918
+ * CSRF token refresh should happen immediately with no delay.
919
+ */
920
+ async calculateDelay(e, t) {
921
+ return 0;
922
+ }
923
+ /**
924
+ * Called by retry service before each retry attempt.
925
+ *
926
+ * @param _result - The failed response that triggered the retry (unused, already validated)
927
+ * @param _context - Current retry context (unused but part of interface)
928
+ */
929
+ async prepareRetry(e, t) {
930
+ await this.csrfTokenManager.refreshToken();
931
+ }
932
+ }
933
+ class Ue {
934
+ constructor(e, t) {
935
+ this.endpoint = e, this.cacheName = t, this.tokenPromise = this.obtainToken();
936
+ }
937
+ tokenPromise;
938
+ refreshPromise;
939
+ /**
940
+ * Returns the current token value as a Promise.
941
+ * Lazy-loads the token on first call (from cache or by fetching).
942
+ */
943
+ async getToken() {
944
+ return this.tokenPromise;
945
+ }
946
+ /**
947
+ * Obtains and returns a new token value as a promise.
948
+ * This will clear the cached token and fetch a fresh one.
949
+ * If a refresh is already in progress, all callers share the same in-flight promise.
950
+ */
951
+ refreshToken() {
952
+ return this.refreshPromise || (this.refreshPromise = this.withCache((e) => e.delete(this.endpoint)).then(() => (this.tokenPromise = this.obtainToken(), this.tokenPromise)).finally(() => {
953
+ this.refreshPromise = void 0;
954
+ })), this.refreshPromise;
955
+ }
956
+ /**
957
+ * Obtains a CSRF token, using cache when available or fetching a new one.
958
+ *
959
+ * @returns Promise that resolves to the CSRF token string
960
+ */
961
+ async obtainToken() {
962
+ let e = await this.withCache((i) => i.match(this.endpoint)), t = !1;
963
+ e || (e = await fetch(this.endpoint, { method: "get" }), t = !0);
964
+ const n = (await e.clone().json()).csrfToken;
965
+ return t && await this.withCache((i) => i.put(this.endpoint, e)), n;
966
+ }
967
+ /**
968
+ * Provides a safe way to interact with the Cache API with fallback for unsupported environments.
969
+ *
970
+ * @param callback - Function that receives the cache instance and returns a promise
971
+ * @returns The result of the callback, or undefined if caches API is not available
972
+ */
973
+ async withCache(e) {
974
+ if (this.cacheName && caches) {
975
+ const t = await caches.open(this.cacheName);
976
+ return e(t);
977
+ } else
978
+ return;
979
+ }
980
+ }
981
+ const L = /* @__PURE__ */ new Map();
982
+ function qe(s) {
983
+ const { endpoint: e, cacheName: t, ...n } = s.csrf;
984
+ let i = L.get(e);
985
+ return i || (i = new Ue(e, t), L.set(e, i)), R(
986
+ {
987
+ retry: Oe(i, n),
988
+ request: [Le]
989
+ },
990
+ U(new Ne(i)).service
991
+ ).service;
992
+ }
993
+ function We() {
994
+ return {
995
+ "Content-Type": "application/json",
996
+ Accept: "application/json",
997
+ "X-Chatter-Entity-Encoding": "false"
998
+ };
999
+ }
1000
+ const Ve = 1, $e = `@salesforce/platform-sdk_v${Ve}`, O = H(), Be = `${O}/ui-api`;
1001
+ class Ke {
1002
+ baseUrl;
1003
+ clientFetch;
1004
+ onStatus;
1005
+ constructor(e) {
1006
+ const t = je();
1007
+ this.baseUrl = ze(e?.basePath ?? t.apiPath), this.onStatus = e?.onStatus ?? {}, this.clientFetch = qe({
1008
+ csrf: {
1009
+ endpoint: `${this.baseUrl}${Be}/session/csrf`,
1010
+ cacheName: $e,
1011
+ protectedUrls: ["services/data/v", "services/apexrest"],
1012
+ alwaysProtectedUrls: ["services/apexrest"]
1013
+ }
1014
+ });
1015
+ }
1016
+ async graphql({
1017
+ query: e,
1018
+ variables: t,
1019
+ operationName: n
1020
+ }) {
1021
+ return (await this.fetch(`${O}/graphql`, {
1022
+ method: "POST",
1023
+ body: JSON.stringify({ query: e, variables: t, operationName: n }),
1024
+ headers: We()
1025
+ })).json();
1026
+ }
1027
+ async fetch(e, t) {
1028
+ const n = this.applySalesforceBase(e), i = await this.clientFetch(n, t);
1029
+ return await this.onStatus[i.status]?.(), i;
1030
+ }
1031
+ /**
1032
+ * If the url is relative, convert to it to an absolute Salesforce URL. This is due to the way Code
1033
+ * Builder deployments structure the url for Salesforce
1034
+ */
1035
+ applySalesforceBase(e) {
1036
+ if (typeof e == "string") {
1037
+ if (e.startsWith("http"))
1038
+ return e;
1039
+ const t = e.startsWith("/") ? e : `/${e}`;
1040
+ return `${this.baseUrl}${t}`;
1041
+ }
1042
+ return e;
1043
+ }
1044
+ }
1045
+ function je() {
1046
+ return {
1047
+ apiPath: globalThis.SFDC_ENV?.apiPath
1048
+ };
1049
+ }
1050
+ function ze(s) {
1051
+ if (!s || s === "/") return "";
1052
+ let e = s;
1053
+ return e.startsWith("/") || (e = `/${e}`), e.endsWith("/") && (e = e.slice(0, -1)), e;
1054
+ }
1055
+ function It(s, ...e) {
1056
+ let t = s[0] ?? "";
1057
+ for (let n = 0; n < e.length; n += 1)
1058
+ t += String(e[n]) + (s[n + 1] ?? "");
1059
+ return t;
1060
+ }
1061
+ function Mt(s) {
1062
+ return A(
1063
+ (async () => {
1064
+ switch (T(s?.surface)) {
1065
+ case o.OpenAI:
1066
+ return new Me();
1067
+ case o.WebApp:
1068
+ case o.MicroFrontend:
1069
+ return new Ke(s?.webapp);
1070
+ case o.Mosaic:
1071
+ return new Se(s?.mosaic);
1072
+ case o.SalesforceACC:
1073
+ case o.MCPApps:
1074
+ return {};
1075
+ default:
1076
+ return {};
1077
+ }
1078
+ })(),
1079
+ "createDataSDK"
1080
+ );
1081
+ }
1082
+ function Et(s) {
1083
+ return A(
1084
+ (async () => {
1085
+ switch (T(s?.surface)) {
1086
+ case o.OpenAI:
1087
+ return {};
1088
+ case o.WebApp:
1089
+ return {};
1090
+ case o.MicroFrontend:
1091
+ return {};
1092
+ case o.SalesforceACC:
1093
+ return {};
1094
+ case o.MCPApps:
1095
+ return {};
1096
+ case o.Mosaic:
1097
+ return {};
1098
+ default:
1099
+ return {};
1100
+ }
1101
+ })(),
1102
+ "createLightningSDK"
1103
+ );
1104
+ }
1105
+ class Je {
1106
+ buffer;
1107
+ constructor(e) {
1108
+ this.buffer = e;
1109
+ }
1110
+ wrapAction(e) {
1111
+ if (this.buffer.isEmpty)
1112
+ return e;
1113
+ const t = { envelopes: this.buffer.drain() };
1114
+ return { ...e, _telemetry: t };
1115
+ }
1116
+ }
1117
+ function Xe(s) {
1118
+ let e = "";
1119
+ for (let n = 0; n < s.length; n += 8192)
1120
+ e += String.fromCharCode.apply(null, Array.from(s.subarray(n, n + 8192)));
1121
+ return btoa(e);
1122
+ }
1123
+ class Ye {
1124
+ entries = [];
1125
+ totalBytes = 0;
1126
+ maxBufferSize;
1127
+ onError;
1128
+ constructor(e) {
1129
+ this.maxBufferSize = e.maxBufferSize, this.onError = e.onError;
1130
+ }
1131
+ get size() {
1132
+ return this.totalBytes;
1133
+ }
1134
+ get isEmpty() {
1135
+ return this.entries.length === 0;
1136
+ }
1137
+ enqueue(e, t) {
1138
+ const n = Xe(e), i = {
1139
+ data: n,
1140
+ traceId: t?.traceId,
1141
+ instanceId: t?.instanceId,
1142
+ componentRef: t?.componentRef,
1143
+ timestamp: Date.now()
1144
+ }, r = n.length;
1145
+ this.entries.push(i), this.totalBytes += r, this.totalBytes > this.maxBufferSize && this.evict();
1146
+ }
1147
+ drain() {
1148
+ const e = this.entries;
1149
+ return this.entries = [], this.totalBytes = 0, e;
1150
+ }
1151
+ evict() {
1152
+ let e = 0;
1153
+ for (; this.totalBytes > this.maxBufferSize && this.entries.length > 1; ) {
1154
+ const t = this.entries.shift();
1155
+ this.totalBytes -= t.data.length, e++;
1156
+ }
1157
+ e > 0 && this.onError?.({ reason: "buffer_overflow", droppedCount: e });
1158
+ }
1159
+ }
1160
+ class Ge {
1161
+ buffer;
1162
+ sdk;
1163
+ timerId = null;
1164
+ disposed = !1;
1165
+ handleVisibilityChange = () => {
1166
+ document.visibilityState === "hidden" && this.flush();
1167
+ };
1168
+ handlePageHide = () => {
1169
+ this.flush();
1170
+ };
1171
+ constructor(e, t, n) {
1172
+ this.buffer = e, this.sdk = t, this.timerId = setInterval(() => this.flush(), n), document.addEventListener("visibilitychange", this.handleVisibilityChange), window.addEventListener("pagehide", this.handlePageHide);
1173
+ }
1174
+ flush() {
1175
+ if (this.buffer.isEmpty || !this.sdk.setWidgetState)
1176
+ return;
1177
+ const e = { envelopes: this.buffer.drain() }, t = this.sdk.getWidgetState?.() ?? {};
1178
+ this.sdk.setWidgetState({ ...t, _telemetry: e });
1179
+ }
1180
+ dispose() {
1181
+ this.disposed || (this.disposed = !0, this.timerId !== null && (clearInterval(this.timerId), this.timerId = null), document.removeEventListener("visibilitychange", this.handleVisibilityChange), window.removeEventListener("pagehide", this.handlePageHide), this.flush());
1182
+ }
1183
+ }
1184
+ const Qe = 65536, Ze = 3e4;
1185
+ function kt(s) {
1186
+ const {
1187
+ sdk: e,
1188
+ flushOnAction: t = !0,
1189
+ maxBufferSize: n = Qe,
1190
+ flushInterval: i = Ze,
1191
+ onError: r
1192
+ } = s, a = new Ye({ maxBufferSize: n, onError: r }), c = new Je(a), h = new Ge(a, e, i);
1193
+ return {
1194
+ enqueue(d, m) {
1195
+ a.enqueue(d, m);
1196
+ },
1197
+ wrapAction(d) {
1198
+ return t ? c.wrapAction(d) : d;
1199
+ },
1200
+ dispose() {
1201
+ h.dispose();
1202
+ }
1203
+ };
1204
+ }
1205
+ const et = 1e4, tt = 10, st = 10, nt = 250, it = 1e3;
1206
+ function y(s, e) {
1207
+ if (s !== void 0 && (typeof s != "number" || !Number.isFinite(s) || s <= 0))
1208
+ throw new Error(`${e}, if defined, must be a finite number greater than 0`);
1209
+ }
1210
+ function rt(s, e) {
1211
+ if (typeof s != "function")
1212
+ throw new Error(`${e} must be a function`);
1213
+ }
1214
+ class ot {
1215
+ _collector;
1216
+ _onEnvelope;
1217
+ _onError;
1218
+ _enableClickTrigger;
1219
+ _enableVisibilityTrigger;
1220
+ _messagesLimit;
1221
+ _metricsLimit;
1222
+ _uploadInterval;
1223
+ _clickUploadDelay;
1224
+ _clickTriggerCooldown;
1225
+ _boundClickListener = this._handleClick.bind(this);
1226
+ _boundVisibilityChangeListener = this._handleVisibilityChange.bind(this);
1227
+ _boundPageHideListener = this._handlePageHide.bind(this);
1228
+ _intervalHandle;
1229
+ _clickTimeoutHandle;
1230
+ _flushPromise;
1231
+ _pendingFlushReason;
1232
+ _lastClickTriggeredAt = 0;
1233
+ _isDisposed = !1;
1234
+ constructor(e) {
1235
+ rt(e?.onEnvelope, "options.onEnvelope"), y(e.uploadInterval, "options.uploadInterval"), y(e.messagesLimit, "options.messagesLimit"), y(e.metricsLimit, "options.metricsLimit"), y(e.maxUniqueSchemas, "options.maxUniqueSchemas"), y(e.clickUploadDelay, "options.clickUploadDelay"), y(e.clickTriggerCooldown, "options.clickTriggerCooldown"), this._onEnvelope = e.onEnvelope, this._onError = e.onError, this._messagesLimit = e.messagesLimit ?? tt, this._metricsLimit = e.metricsLimit ?? st, this._uploadInterval = e.uploadInterval ?? et, this._clickUploadDelay = e.clickUploadDelay ?? nt, this._clickTriggerCooldown = e.clickTriggerCooldown ?? it, this._enableClickTrigger = e.enableClickTrigger !== !1, this._enableVisibilityTrigger = e.enableVisibilityTrigger !== !1, this._collector = new W({
1236
+ environment: e.environment,
1237
+ maxUniqueSchemas: e.maxUniqueSchemas
1238
+ }), this._restartInterval(), this._attachWindowListeners();
1239
+ }
1240
+ get hasData() {
1241
+ return this._collector.hasData;
1242
+ }
1243
+ get estimatedByteSize() {
1244
+ return this._collector.estimatedByteSize;
1245
+ }
1246
+ get messagesCount() {
1247
+ return this._collector.messagesCount;
1248
+ }
1249
+ get metricsCount() {
1250
+ return this._collector.metricsCount;
1251
+ }
1252
+ getIsCollectDisabled() {
1253
+ return this._isDisposed;
1254
+ }
1255
+ collect(e, t, n) {
1256
+ this._collector.collect(e, t, n), this._shouldFlushForThreshold() && this.flush("threshold");
1257
+ }
1258
+ receiveMetricsExtractors(e) {
1259
+ this._collector.receiveMetricsExtractors(e);
1260
+ }
1261
+ async flush(e = "manual") {
1262
+ return this._flushPromise ? (this._pendingFlushReason = this._pendingFlushReason ?? e, this._flushPromise) : (this._flushPromise = this._flushInternal(e).then(() => {
1263
+ const t = this._pendingFlushReason;
1264
+ this._pendingFlushReason = void 0, t && this.hasData && !this._isDisposed && this.flush(t);
1265
+ }).finally(() => {
1266
+ this._flushPromise = void 0;
1267
+ }), this._flushPromise);
1268
+ }
1269
+ async dispose(e) {
1270
+ this._isDisposed = !0, this._detachWindowListeners(), this._stopInterval(), this._clickTimeoutHandle !== void 0 && (clearTimeout(this._clickTimeoutHandle), this._clickTimeoutHandle = void 0), e?.flush !== !1 && this.hasData && await this.flush("dispose");
1271
+ }
1272
+ _attachWindowListeners() {
1273
+ typeof document == "object" && this._enableClickTrigger && document.addEventListener("click", this._boundClickListener, !0), typeof window == "object" && this._enableVisibilityTrigger && (document.addEventListener("visibilitychange", this._boundVisibilityChangeListener, !0), window.addEventListener("pagehide", this._boundPageHideListener, !0));
1274
+ }
1275
+ _detachWindowListeners() {
1276
+ typeof document == "object" && (document.removeEventListener("click", this._boundClickListener, !0), document.removeEventListener("visibilitychange", this._boundVisibilityChangeListener, !0)), typeof window == "object" && window.removeEventListener("pagehide", this._boundPageHideListener, !0);
1277
+ }
1278
+ _handleClick() {
1279
+ !this.hasData || this._isDisposed || Date.now() - this._lastClickTriggeredAt < this._clickTriggerCooldown || (this._clickTimeoutHandle !== void 0 && clearTimeout(this._clickTimeoutHandle), this._clickTimeoutHandle = setTimeout(() => {
1280
+ this._clickTimeoutHandle = void 0, !(!this.hasData || this._isDisposed) && (this._lastClickTriggeredAt = Date.now(), this.flush("click"));
1281
+ }, this._clickUploadDelay));
1282
+ }
1283
+ _handleVisibilityChange() {
1284
+ typeof document != "object" || document.visibilityState !== "hidden" || !this.hasData || this.flush("visibilitychange");
1285
+ }
1286
+ _handlePageHide() {
1287
+ this.hasData && this.flush("pagehide");
1288
+ }
1289
+ _restartInterval() {
1290
+ this._stopInterval(), this._intervalHandle = setInterval(() => {
1291
+ this.hasData && !this._isDisposed && this.flush("interval");
1292
+ }, this._uploadInterval);
1293
+ }
1294
+ _stopInterval() {
1295
+ this._intervalHandle !== void 0 && (clearInterval(this._intervalHandle), this._intervalHandle = void 0);
1296
+ }
1297
+ _shouldFlushForThreshold() {
1298
+ return this.messagesCount >= this._messagesLimit || this.metricsCount >= this._metricsLimit;
1299
+ }
1300
+ async _flushInternal(e) {
1301
+ if (!this.hasData)
1302
+ return;
1303
+ const t = {
1304
+ reason: e,
1305
+ messagesCount: this.messagesCount,
1306
+ metricsCount: this.metricsCount,
1307
+ estimatedByteSize: this.estimatedByteSize,
1308
+ triggeredAt: Date.now()
1309
+ }, n = this._collector.getRawContentsOfCoreEnvelope(), i = q(n);
1310
+ this._restartInterval();
1311
+ try {
1312
+ await this._onEnvelope(i, t);
1313
+ } catch (r) {
1314
+ const a = {
1315
+ ...t,
1316
+ error: r
1317
+ };
1318
+ throw this._onError?.(a), r;
1319
+ }
1320
+ }
1321
+ }
1322
+ function at(s, e) {
1323
+ if (!s)
1324
+ throw new Error("instrumentedApp is required");
1325
+ const t = new ot(e);
1326
+ return s.registerLogCollector(t), s.registerMetricsCollector(t), e.enableClickTrigger !== !1 && s.activateClickTracker?.(), t;
1327
+ }
1328
+ function ct(s) {
1329
+ const e = (n, i, r, a, c) => {
1330
+ s.error(c ?? n);
1331
+ }, t = (n) => {
1332
+ s.error(n.reason);
1333
+ };
1334
+ return window.addEventListener("error", e), window.addEventListener("unhandledrejection", t), () => {
1335
+ window.removeEventListener("error", e), window.removeEventListener("unhandledrejection", t);
1336
+ };
1337
+ }
1338
+ function p(s, e) {
1339
+ return { surface: e };
1340
+ }
1341
+ const lt = {
1342
+ callTool: {
1343
+ isAsync: !0,
1344
+ extractTags: (s, e) => ({ toolName: s[0]?.toolName ?? "unknown", surface: e })
1345
+ },
1346
+ setWidgetState: {
1347
+ isAsync: !1,
1348
+ extractTags: p
1349
+ },
1350
+ getWidgetState: {
1351
+ isAsync: !1,
1352
+ extractTags: p
1353
+ },
1354
+ sendMessageToHost: {
1355
+ isAsync: !0,
1356
+ extractTags: p
1357
+ },
1358
+ openLink: {
1359
+ isAsync: !0,
1360
+ extractTags: p
1361
+ },
1362
+ subscribe: {
1363
+ isAsync: !1,
1364
+ extractTags: p,
1365
+ wrapArgs: (s, e) => {
1366
+ const t = s[0];
1367
+ return [
1368
+ () => {
1369
+ e.activity("sdk.subscribe_callback", () => t());
1370
+ }
1371
+ ];
1372
+ }
1373
+ },
1374
+ readResource: {
1375
+ isAsync: !0,
1376
+ extractTags: (s, e) => ({ uri: s[0]?.uri ?? "unknown", surface: e })
1377
+ },
1378
+ setDisplayMode: {
1379
+ isAsync: !0,
1380
+ extractTags: (s, e) => ({ mode: s[0] ?? "unknown", surface: e })
1381
+ },
1382
+ accessToolOutput: {
1383
+ isAsync: !1,
1384
+ extractTags: p
1385
+ },
1386
+ accessToolInput: {
1387
+ isAsync: !1,
1388
+ extractTags: p
1389
+ },
1390
+ accessToolMetadata: {
1391
+ isAsync: !1,
1392
+ extractTags: p
1393
+ }
1394
+ };
1395
+ function ut(s, e, t) {
1396
+ return new Proxy(s, {
1397
+ get(n, i, r) {
1398
+ const a = Reflect.get(n, i, r), c = lt[i];
1399
+ return !c || typeof a != "function" ? a : (...h) => {
1400
+ const d = c.extractTags(h, t), m = c.wrapArgs ? c.wrapArgs(h, e) : h, w = `sdk.${String(i)}`;
1401
+ return c.isAsync ? e.activityAsync(w, async () => {
1402
+ try {
1403
+ const f = await a.apply(
1404
+ n,
1405
+ m
1406
+ );
1407
+ return e.incrementCounter(w, 1, !1, d), f;
1408
+ } catch (f) {
1409
+ throw e.incrementCounter(w, 1, !0, d), f;
1410
+ }
1411
+ }) : (e.incrementCounter(w, 1, !1, d), a.apply(n, m));
1412
+ };
1413
+ }
1414
+ });
1415
+ }
1416
+ async function Dt(s) {
1417
+ const { appId: e, clientSessionId: t } = s, n = T(), i = Date.now(), r = s.sdk ?? await fe(), a = V("mcp-widget", {
1418
+ appPayloadProvider: {
1419
+ getPayload: () => ({
1420
+ schema: $,
1421
+ payload: { appId: e, surface: n }
1422
+ })
1423
+ },
1424
+ clientSessionId: t
1425
+ }), c = a, h = ut(r, c, n), d = ct(c);
1426
+ let m;
1427
+ if (s.transport) {
1428
+ m = at(a, {
1429
+ onEnvelope: (u) => {
1430
+ s.transport.enqueue(u);
1431
+ }
1432
+ });
1433
+ const l = h.callTool;
1434
+ l && (h.callTool = (u) => {
1435
+ const F = s.transport.wrapAction(u.params ?? {});
1436
+ return l.call(h, {
1437
+ ...u,
1438
+ params: F
1439
+ });
1440
+ });
1441
+ }
1442
+ let w, f = !1;
1443
+ return {
1444
+ instrumentedSDK: h,
1445
+ app: a,
1446
+ trackEvent(l, u) {
1447
+ f || c.log(J, {
1448
+ eventName: l,
1449
+ properties: u ? JSON.stringify(u) : ""
1450
+ });
1451
+ },
1452
+ trackInteraction(l, u) {
1453
+ f || c.log(z, {
1454
+ elementId: l,
1455
+ properties: u ? JSON.stringify(u) : ""
1456
+ });
1457
+ },
1458
+ trackError(l, u) {
1459
+ f || c.error(l, j, {
1460
+ properties: u ? JSON.stringify(u) : ""
1461
+ });
1462
+ },
1463
+ trackPageView(l) {
1464
+ f || l !== w && (w = l, c.log(K, { componentRef: l }));
1465
+ },
1466
+ dispose() {
1467
+ if (f) return;
1468
+ f = !0, d();
1469
+ const l = Date.now() - i;
1470
+ c.log(B, { durationMs: l }), m?.dispose();
1471
+ }
1472
+ };
1473
+ }
1474
+ export {
1475
+ te as JsonRpcClient,
1476
+ ue as MCPAppsChatSDK,
1477
+ me as MCPAppsViewSDK,
1478
+ g as McpAppsSession,
1479
+ Ct as MessageChannelTransport,
1480
+ o as Surface,
1481
+ ot as TelemetryUploader,
1482
+ ee as WindowPostMessageTransport,
1483
+ Dt as createAnalytics,
1484
+ pe as createChatSDK,
1485
+ Mt as createDataSDK,
1486
+ Et as createLightningSDK,
1487
+ kt as createTelemetryTransport,
1488
+ ye as createViewSDK,
1489
+ fe as getChatSDK,
1490
+ bt as getChatSDKSync,
1491
+ T as getSurface,
1492
+ Tt as getSurfaceCapabilities,
1493
+ St as getViewSDK,
1494
+ _t as getViewSDKSync,
1495
+ It as gql,
1496
+ _ as isJsonRpcBase,
1497
+ x as isJsonRpcErrorResponse,
1498
+ Z as isJsonRpcNotification,
1499
+ yt as isJsonRpcRequest,
1500
+ Q as isJsonRpcResponse,
1501
+ G as isJsonRpcSuccessResponse,
1502
+ at as registerTelemetryUploader,
1503
+ vt as resetChatSDK,
1504
+ At as resetViewSDK,
1505
+ A as wrapSDKPromise
1506
+ };