@kittl/sdk 0.0.8 → 0.0.9

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.
@@ -0,0 +1,1001 @@
1
+ // @ts-self-types="./sdk.d.ts"
2
+ /*! Kittl SDK - https://kittl.com - see license for terms */
3
+
4
+ var FROM_EXTENSION_COMMANDS = {
5
+ /** SDK API call */
6
+ SDK_CALL: "sdk-call",
7
+ /** AI handler registration */
8
+ AI_REGISTER_HANDLER: "ai-register-handler",
9
+ /** AI handler unregistration */
10
+ AI_UNREGISTER_HANDLER: "ai-unregister-handler",
11
+ /** File browser tab registration */
12
+ FILE_BROWSER_REGISTER: "file-browser-register",
13
+ /** File browser fetch content response */
14
+ FILE_BROWSER_FETCH_CONTENT_RESPONSE: "file-browser-fetch-content-response",
15
+ /** Stateless message send */
16
+ STATELESS_SEND: "stateless-send",
17
+ /** Stateless subscription */
18
+ STATELESS_SUBSCRIBE: "stateless-subscribe",
19
+ /** Stateless unsubscription */
20
+ STATELESS_UNSUBSCRIBE: "stateless-unsubscribe",
21
+ /** App state subscription */
22
+ APP_STATE_SUBSCRIBE: "app-state-subscribe",
23
+ /** App state unsubscription */
24
+ APP_STATE_UNSUBSCRIBE: "app-state-unsubscribe",
25
+ /** Batch creation */
26
+ BATCH_CREATE: "batch-create",
27
+ /** Batch commit */
28
+ BATCH_COMMIT: "batch-commit",
29
+ /** OAuth flow start */
30
+ AUTH_START: "auth-start",
31
+ /** OAuth token exchange */
32
+ AUTH_EXCHANGE: "auth-exchange",
33
+ /** Get OAuth token */
34
+ AUTH_GET_TOKEN: "auth-get-token",
35
+ /** Refresh OAuth token */
36
+ AUTH_REFRESH: "auth-refresh",
37
+ /** OAuth logout */
38
+ AUTH_LOGOUT: "auth-logout",
39
+ /** Get user token for authentication */
40
+ AUTH_GET_USER_TOKEN: "auth-get-user-token",
41
+ /** Context subscription */
42
+ CONTEXT_SUBSCRIBE: "context-subscribe",
43
+ /** Context unsubscription */
44
+ CONTEXT_UNSUBSCRIBE: "context-unsubscribe",
45
+ /** Design state subscription */
46
+ DESIGN_STATE_SUBSCRIBE: "design-state-subscribe",
47
+ /** Design state unsubscription */
48
+ DESIGN_STATE_UNSUBSCRIBE: "design-state-unsubscribe",
49
+ /** Extension loaded notification */
50
+ LOADED: "loaded"
51
+ };
52
+ var TO_EXTENSION_COMMANDS = {
53
+ /** SDK API response */
54
+ SDK_RESPONSE: "sdk-response",
55
+ /** File browser fetch content request */
56
+ FILE_BROWSER_FETCH_CONTENT_REQUEST: "file-browser-fetch-content-request",
57
+ /** Stateless message push */
58
+ STATELESS_MESSAGE: "stateless-message",
59
+ /** Context update push */
60
+ CONTEXT_UPDATE: "context-update",
61
+ /** AI generation update push */
62
+ AI_GENERATION_UPDATE: "ai-generation-update",
63
+ /** Design state update push */
64
+ DESIGN_STATE_UPDATE: "design-state-update",
65
+ /** App state update push */
66
+ APP_STATE_UPDATE: "app-state-update"
67
+ };
68
+
69
+ var isSDKResponseMessage = (data) => {
70
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.SDK_RESPONSE && "messageId" in data && typeof data.messageId === "string";
71
+ };
72
+ var isStatelessPushMessage = (data) => {
73
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.STATELESS_MESSAGE && "type" in data && typeof data.type === "string" && "payload" in data && typeof data.payload === "object" && data.payload !== null;
74
+ };
75
+ var isAIGenerationUpdatePushMessage = (data) => {
76
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.AI_GENERATION_UPDATE && "subscriptionId" in data && typeof data.subscriptionId === "string" && "update" in data && typeof data.update === "object" && data.update !== null;
77
+ };
78
+ var isDesignStateUpdatePushMessage = (data) => {
79
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.DESIGN_STATE_UPDATE && "updates" in data && Array.isArray(data.updates);
80
+ };
81
+ var isAppStateUpdatePushMessage = (data) => {
82
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.APP_STATE_UPDATE && "updates" in data && Array.isArray(data.updates);
83
+ };
84
+ var isContextUpdatePushMessage = (data) => {
85
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.CONTEXT_UPDATE && "subscriptionId" in data && typeof data.subscriptionId === "string" && "context" in data && typeof data.context === "object" && data.context !== null;
86
+ };
87
+ var isFileBrowserFetchContentRequestMessage = (data) => {
88
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_REQUEST && "requestId" in data && typeof data.requestId === "string" && "subscriptionId" in data && typeof data.subscriptionId === "string";
89
+ };
90
+
91
+ var generateMessageId = () => {
92
+ if (crypto?.randomUUID && typeof crypto.randomUUID === "function") {
93
+ return crypto.randomUUID();
94
+ }
95
+ return Math.random().toString(36).substring(7);
96
+ };
97
+
98
+ var buildMethodPath = (rootPrefix, pathSegments) => {
99
+ if (!rootPrefix) {
100
+ return pathSegments.join(".");
101
+ }
102
+ if (pathSegments.length === 0) {
103
+ return rootPrefix;
104
+ }
105
+ return `${rootPrefix}.${pathSegments.join(".")}`;
106
+ };
107
+ var createCallablePathProxy = (options) => {
108
+ const createNode = (pathSegments) => {
109
+ const target = () => {
110
+ };
111
+ const handler = {
112
+ get: (_target, prop) => {
113
+ if (typeof prop === "symbol") {
114
+ return Reflect.get(target, prop);
115
+ }
116
+ return createNode([...pathSegments, String(prop)]);
117
+ },
118
+ apply: (_target, _thisArg, args) => {
119
+ const context = {
120
+ pathSegments,
121
+ methodPath: buildMethodPath(options.rootPrefix ?? "", pathSegments),
122
+ args
123
+ };
124
+ options.beforeInvoke?.(context);
125
+ return options.onInvoke(context);
126
+ }
127
+ };
128
+ return new Proxy(target, handler);
129
+ };
130
+ return createNode([]);
131
+ };
132
+
133
+ var parentDomain;
134
+ var APPROVED_EXTENSION_COMMUNICATION_DOMAINS = [
135
+ "https://app.stagingdesigner.com",
136
+ "https://*.stagingdesigner.com",
137
+ "http://localhost:3000",
138
+ "https://app.kittl.com"
139
+ ];
140
+ var toOrigin = (value) => {
141
+ if (!value) {
142
+ return null;
143
+ }
144
+ try {
145
+ return new URL(value).origin;
146
+ } catch (_error) {
147
+ return null;
148
+ }
149
+ };
150
+ var escapeRegex = (value) => {
151
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
152
+ };
153
+ var matchesApprovedDomain = (origin, approvedDomain) => {
154
+ const normalized = approvedDomain.trim();
155
+ if (!normalized) {
156
+ return false;
157
+ }
158
+ if (normalized.includes("*")) {
159
+ const wildcardRegex = new RegExp(
160
+ // because we use wildcards only in the middle of the string
161
+ // we know that our list must start with the regex and end with the regex
162
+ // so we add the ^ and $ to the regex too
163
+ `^${escapeRegex(normalized).replace(/\\\*/g, ".*")}$`
164
+ );
165
+ return wildcardRegex.test(origin);
166
+ }
167
+ return origin === normalized;
168
+ };
169
+ var getParentDomain = () => {
170
+ if (parentDomain) {
171
+ return parentDomain;
172
+ }
173
+ const referrer = window.document.referrer;
174
+ const ancestorOrigins = window.location.ancestorOrigins;
175
+ const ancestorOrigin = ancestorOrigins && ancestorOrigins.length > 0 ? ancestorOrigins[ancestorOrigins.length - 1] : void 0;
176
+ const currentDomainOrigin = toOrigin(referrer) ?? toOrigin(ancestorOrigin);
177
+ if (!currentDomainOrigin) {
178
+ throw new Error("No current domain origin found");
179
+ }
180
+ const approvedParentDomain = APPROVED_EXTENSION_COMMUNICATION_DOMAINS.find(
181
+ (domain) => {
182
+ return matchesApprovedDomain(currentDomainOrigin, domain);
183
+ }
184
+ );
185
+ if (!approvedParentDomain) {
186
+ throw new Error("No approved parent domain found");
187
+ }
188
+ parentDomain = currentDomainOrigin;
189
+ return parentDomain;
190
+ };
191
+
192
+ var pendingRequests = /* @__PURE__ */ new Map();
193
+ var postMessageToParent = (message) => {
194
+ window.parent.postMessage(message, getParentDomain());
195
+ };
196
+ var sendMessage = (message) => {
197
+ postMessageToParent(message);
198
+ return new Promise((resolve, reject) => {
199
+ pendingRequests.set(message.messageId, {
200
+ resolve: (value) => {
201
+ resolve(value);
202
+ },
203
+ reject
204
+ });
205
+ });
206
+ };
207
+ var sendLoaded = () => {
208
+ const parent = window.parent;
209
+ if (!parent || parent === window) {
210
+ return;
211
+ }
212
+ const message = { command: FROM_EXTENSION_COMMANDS.LOADED };
213
+ postMessageToParent(message);
214
+ };
215
+
216
+ var createSDKCallMessage = {
217
+ ai: (dots, args, messageId) => ({
218
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
219
+ dots,
220
+ args,
221
+ messageId,
222
+ apiType: "ai"
223
+ }),
224
+ context: (dots, args, messageId) => ({
225
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
226
+ dots,
227
+ args,
228
+ messageId,
229
+ apiType: "context"
230
+ }),
231
+ design: (dots, args, messageId) => ({
232
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
233
+ dots,
234
+ args,
235
+ messageId,
236
+ apiType: "design"
237
+ }),
238
+ export: (dots, args, messageId) => ({
239
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
240
+ dots,
241
+ args,
242
+ messageId,
243
+ apiType: "export"
244
+ }),
245
+ font: (dots, args, messageId) => ({
246
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
247
+ dots,
248
+ args,
249
+ messageId,
250
+ apiType: "font"
251
+ }),
252
+ state: (dots, args, messageId) => ({
253
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
254
+ dots,
255
+ args,
256
+ messageId,
257
+ apiType: "state"
258
+ }),
259
+ upload: (dots, args, messageId) => ({
260
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
261
+ dots,
262
+ args,
263
+ messageId,
264
+ apiType: "upload"
265
+ }),
266
+ data: (dots, args, messageId) => ({
267
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
268
+ dots,
269
+ args,
270
+ messageId,
271
+ apiType: "data"
272
+ })
273
+ };
274
+ function createApiProxy(apiType) {
275
+ return createCallablePathProxy({
276
+ onInvoke: ({ pathSegments, args }) => {
277
+ return sendMessage(
278
+ createSDKCallMessage[apiType](
279
+ [...pathSegments],
280
+ [...args],
281
+ generateMessageId()
282
+ )
283
+ );
284
+ }
285
+ });
286
+ }
287
+
288
+ var generationHandlers = /* @__PURE__ */ new Map();
289
+ var generationSubscriptions = /* @__PURE__ */ new Map();
290
+ var dispatchAIGenerationUpdate = (subscriptionId, update) => {
291
+ const handler = generationHandlers.get(subscriptionId);
292
+ if (!handler) {
293
+ return;
294
+ }
295
+ void handler(update);
296
+ };
297
+ function createAIApiProxy() {
298
+ const unregisterGenerationHandler = (generatorId) => {
299
+ const subscriptionId = generationSubscriptions.get(generatorId);
300
+ if (!subscriptionId) {
301
+ return;
302
+ }
303
+ generationHandlers.delete(subscriptionId);
304
+ generationSubscriptions.delete(generatorId);
305
+ const unregisterMessage = {
306
+ command: FROM_EXTENSION_COMMANDS.AI_UNREGISTER_HANDLER,
307
+ generatorId,
308
+ subscriptionId
309
+ };
310
+ postMessageToParent(unregisterMessage);
311
+ };
312
+ return {
313
+ spendCredits: async (options) => {
314
+ const { onAccept, onDecline, ...serializable } = options;
315
+ const message = {
316
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
317
+ dots: ["spendCredits"],
318
+ args: [serializable],
319
+ messageId: generateMessageId(),
320
+ apiType: "ai"
321
+ };
322
+ const response = await sendMessage(message);
323
+ if (response.isOk && response.result.success) {
324
+ onAccept?.();
325
+ } else {
326
+ onDecline?.();
327
+ }
328
+ return response;
329
+ },
330
+ startGeneration: (generatorId, inputSettings, output) => {
331
+ const message = {
332
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
333
+ dots: ["startGeneration"],
334
+ args: [generatorId, inputSettings, output],
335
+ messageId: generateMessageId(),
336
+ apiType: "ai"
337
+ };
338
+ return sendMessage(message);
339
+ },
340
+ registerHandler: async (generatorId, onStatusUpdate) => {
341
+ if (generationSubscriptions.has(generatorId)) {
342
+ return {
343
+ isOk: false,
344
+ error: {
345
+ message: `AI handler for generator "${generatorId}" is already registered`,
346
+ name: "SdkInternalError"
347
+ }
348
+ };
349
+ }
350
+ const subscriptionId = generateMessageId();
351
+ generationHandlers.set(subscriptionId, onStatusUpdate);
352
+ generationSubscriptions.set(generatorId, subscriptionId);
353
+ const registerMessage = {
354
+ command: FROM_EXTENSION_COMMANDS.AI_REGISTER_HANDLER,
355
+ messageId: generateMessageId(),
356
+ generatorId,
357
+ subscriptionId
358
+ };
359
+ try {
360
+ const response = await sendMessage(registerMessage);
361
+ if (!response.isOk) {
362
+ generationHandlers.delete(subscriptionId);
363
+ generationSubscriptions.delete(generatorId);
364
+ return response;
365
+ }
366
+ return {
367
+ isOk: true,
368
+ result: () => unregisterGenerationHandler(generatorId)
369
+ };
370
+ } catch {
371
+ generationHandlers.delete(subscriptionId);
372
+ generationSubscriptions.delete(generatorId);
373
+ return {
374
+ isOk: false,
375
+ error: {
376
+ message: "Failed to register AI handler",
377
+ name: "SdkInternalError"
378
+ }
379
+ };
380
+ }
381
+ },
382
+ unregisterHandler: async (generatorId) => {
383
+ unregisterGenerationHandler(generatorId);
384
+ return { isOk: true, result: void 0 };
385
+ }
386
+ };
387
+ }
388
+
389
+ var fetchContentHandlers = /* @__PURE__ */ new Map();
390
+ var tabIdToSubscriptionId = /* @__PURE__ */ new Map();
391
+ var removeSubscriptionHandlers = (subscriptionId) => {
392
+ fetchContentHandlers.delete(subscriptionId);
393
+ };
394
+ var dispatchFileBrowserFetchContentRequest = (requestId, subscriptionId, params) => {
395
+ const handler = fetchContentHandlers.get(subscriptionId);
396
+ if (!handler) {
397
+ const responseMessage = {
398
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
399
+ requestId,
400
+ content: []
401
+ };
402
+ postMessageToParent(responseMessage);
403
+ return;
404
+ }
405
+ void handler(params).then((result) => {
406
+ const responseMessage = {
407
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
408
+ requestId,
409
+ content: result.content,
410
+ next: result.next
411
+ };
412
+ postMessageToParent(responseMessage);
413
+ }).catch((error) => {
414
+ const responseMessage = {
415
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
416
+ requestId,
417
+ content: [],
418
+ error: error instanceof Error ? error.message : "Unknown error"
419
+ };
420
+ postMessageToParent(responseMessage);
421
+ });
422
+ };
423
+ function createFileBrowserApiProxy() {
424
+ return {
425
+ registerUploadBrowser: async (tab) => {
426
+ const subscriptionId = generateMessageId();
427
+ const existingSubscriptionId = tabIdToSubscriptionId.get(tab.id);
428
+ if (existingSubscriptionId) {
429
+ removeSubscriptionHandlers(existingSubscriptionId);
430
+ }
431
+ fetchContentHandlers.set(subscriptionId, tab.fetchContent);
432
+ tabIdToSubscriptionId.set(tab.id, subscriptionId);
433
+ const registerMessage = {
434
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_REGISTER,
435
+ messageId: generateMessageId(),
436
+ tabId: tab.id,
437
+ label: tab.label,
438
+ order: tab.order,
439
+ emptyState: tab.emptyState,
440
+ subscriptionId
441
+ };
442
+ try {
443
+ const response = await sendMessage(registerMessage);
444
+ if (!response.isOk) {
445
+ removeSubscriptionHandlers(subscriptionId);
446
+ tabIdToSubscriptionId.delete(tab.id);
447
+ return {
448
+ isOk: false,
449
+ error: response.error
450
+ };
451
+ }
452
+ return {
453
+ isOk: true,
454
+ result: void 0
455
+ };
456
+ } catch {
457
+ removeSubscriptionHandlers(subscriptionId);
458
+ tabIdToSubscriptionId.delete(tab.id);
459
+ return {
460
+ isOk: false,
461
+ error: {
462
+ message: "Failed to register upload browser",
463
+ name: "SdkInternalError"
464
+ }
465
+ };
466
+ }
467
+ }
468
+ };
469
+ }
470
+
471
+ var sendUnsubscribe = (selectorIds) => {
472
+ const message = {
473
+ command: FROM_EXTENSION_COMMANDS.APP_STATE_UNSUBSCRIBE,
474
+ selectorIds
475
+ };
476
+ postMessageToParent(message);
477
+ };
478
+ var createAppStateBridgeApi = () => {
479
+ const localSubscriptions = /* @__PURE__ */ new Map();
480
+ async function subscribe(paths, callback) {
481
+ if (paths.length === 0) {
482
+ return () => {
483
+ };
484
+ }
485
+ const values = new Array(paths.length).fill(void 0);
486
+ const selectorIds = [];
487
+ const pathArrays = [];
488
+ for (const dotPath of paths) {
489
+ const segments = dotPath.split(".");
490
+ if (segments.some((s) => s === "")) {
491
+ throw new Error(
492
+ `Invalid app state path: '${dotPath}'. Path must be a non-empty dot-separated string.`
493
+ );
494
+ }
495
+ selectorIds.push(generateMessageId());
496
+ pathArrays.push(segments);
497
+ }
498
+ const messageId = generateMessageId();
499
+ const subscribeMessage = {
500
+ command: FROM_EXTENSION_COMMANDS.APP_STATE_SUBSCRIBE,
501
+ messageId,
502
+ selectorIds,
503
+ paths: pathArrays
504
+ };
505
+ const response = await sendMessage(subscribeMessage);
506
+ if (!response.isOk) {
507
+ throw new Error(`app-state-subscribe failed: ${response.error.message}`);
508
+ }
509
+ for (let i = 0; i < selectorIds.length; i++) {
510
+ localSubscriptions.set(selectorIds[i], {
511
+ callback: (value) => {
512
+ values[i] = value;
513
+ callback(...values);
514
+ }
515
+ });
516
+ }
517
+ return () => {
518
+ for (const selectorId of selectorIds) {
519
+ localSubscriptions.delete(selectorId);
520
+ }
521
+ sendUnsubscribe(selectorIds);
522
+ };
523
+ }
524
+ const dispatch = (updates) => {
525
+ for (const { selectorId, value } of updates) {
526
+ const entry = localSubscriptions.get(selectorId);
527
+ if (entry) {
528
+ entry.callback(value);
529
+ }
530
+ }
531
+ };
532
+ return { subscribe, dispatch };
533
+ };
534
+
535
+ var SandboxedAuthClient = class {
536
+ /**
537
+ * Binds the public start method because the exported SDK API may pass it
538
+ * around without its client object as the receiver.
539
+ */
540
+ constructor() {
541
+ this.startAuth = this.startAuth.bind(this);
542
+ }
543
+ /**
544
+ * Starts provider authentication and optionally adds an RFC 7636 PKCE
545
+ * challenge to the request. Successful responses include the verifier that
546
+ * the caller must pass to {@link exchangeCode}.
547
+ */
548
+ async startAuth(request) {
549
+ const state = generateMessageId();
550
+ let pkceCode = "";
551
+ let code_verifier = "";
552
+ if (request.generatePKCE) {
553
+ code_verifier = this.generatePKCECode();
554
+ pkceCode = await this.hashPKCECode(code_verifier);
555
+ }
556
+ const message = {
557
+ command: FROM_EXTENSION_COMMANDS.AUTH_START,
558
+ messageId: generateMessageId(),
559
+ state,
560
+ provider: request.provider,
561
+ params: {
562
+ ...request.params,
563
+ ...pkceCode ? {
564
+ code_challenge: pkceCode,
565
+ code_challenge_method: "S256"
566
+ } : {}
567
+ }
568
+ };
569
+ const response = await sendMessage(message);
570
+ if (!response.isOk) {
571
+ return response;
572
+ }
573
+ return {
574
+ ...response,
575
+ result: {
576
+ ...response.result,
577
+ code_verifier
578
+ }
579
+ };
580
+ }
581
+ /** Exchanges the provider authorization code for an auth token. */
582
+ exchangeCode(request) {
583
+ const message = {
584
+ command: FROM_EXTENSION_COMMANDS.AUTH_EXCHANGE,
585
+ messageId: generateMessageId(),
586
+ code: request.code,
587
+ code_verifier: request.code_verifier,
588
+ provider: request.provider,
589
+ params: request.params,
590
+ headers: request.headers
591
+ };
592
+ return sendMessage(message);
593
+ }
594
+ /** Requests the current auth token for a provider. */
595
+ getAuthToken(request) {
596
+ const message = {
597
+ command: FROM_EXTENSION_COMMANDS.AUTH_GET_TOKEN,
598
+ messageId: generateMessageId(),
599
+ provider: request.provider
600
+ };
601
+ return sendMessage(message);
602
+ }
603
+ /** Refreshes the auth token for a provider. */
604
+ refreshToken(request) {
605
+ const message = {
606
+ command: FROM_EXTENSION_COMMANDS.AUTH_REFRESH,
607
+ messageId: generateMessageId(),
608
+ provider: request.provider
609
+ };
610
+ return sendMessage(message);
611
+ }
612
+ /** Logs the current user out of a provider. */
613
+ logout(request) {
614
+ const message = {
615
+ command: FROM_EXTENSION_COMMANDS.AUTH_LOGOUT,
616
+ messageId: generateMessageId(),
617
+ provider: request.provider
618
+ };
619
+ return sendMessage(message);
620
+ }
621
+ /** Requests the authenticated user's user token from the parent window. */
622
+ getUserToken() {
623
+ const message = {
624
+ command: FROM_EXTENSION_COMMANDS.AUTH_GET_USER_TOKEN,
625
+ messageId: generateMessageId()
626
+ };
627
+ return sendMessage(message);
628
+ }
629
+ /** Hashes a PKCE verifier and encodes the SHA-256 digest as Base64URL. */
630
+ async hashPKCECode(input) {
631
+ const subtle = window.crypto?.subtle;
632
+ if (!subtle) {
633
+ throw new Error("Web Crypto SubtleCrypto API not available");
634
+ }
635
+ const textAsBuffer = new TextEncoder().encode(input);
636
+ const hashBuffer = await subtle.digest("SHA-256", textAsBuffer);
637
+ const hashArray = new Uint8Array(hashBuffer);
638
+ const binaryString = String.fromCharCode(...hashArray);
639
+ const base64 = btoa(binaryString);
640
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
641
+ }
642
+ /** Generates a high-entropy RFC 7636-compatible PKCE verifier. */
643
+ generatePKCECode() {
644
+ if (!window.crypto) {
645
+ throw new Error("Crypto API not available");
646
+ }
647
+ const array = new Uint32Array(56);
648
+ window.crypto.getRandomValues(array);
649
+ return Array.from(array, (dec) => `0${dec.toString(16)}`.slice(-2)).join(
650
+ ""
651
+ );
652
+ }
653
+ };
654
+
655
+ var createBatch = async () => {
656
+ const response = await sendMessage({
657
+ command: FROM_EXTENSION_COMMANDS.BATCH_CREATE,
658
+ messageId: generateMessageId()
659
+ });
660
+ if (!response.isOk) {
661
+ throw response.error;
662
+ }
663
+ const { batchKey } = response.result;
664
+ const sendDesignCall = (dots, args) => sendMessage({
665
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
666
+ dots,
667
+ args,
668
+ messageId: generateMessageId(),
669
+ apiType: "design",
670
+ batchKey
671
+ });
672
+ const commit = async () => {
673
+ const res = await sendMessage({
674
+ command: FROM_EXTENSION_COMMANDS.BATCH_COMMIT,
675
+ messageId: generateMessageId(),
676
+ batchKey
677
+ });
678
+ if (!res.isOk) {
679
+ throw res.error;
680
+ }
681
+ };
682
+ const buildNode = (pathSegments) => {
683
+ const target = () => {
684
+ };
685
+ return new Proxy(target, {
686
+ get: (_t, prop) => {
687
+ if (typeof prop === "symbol" || prop === "then") return void 0;
688
+ if (prop === "commit") return commit;
689
+ return buildNode([...pathSegments, prop]);
690
+ },
691
+ apply: (_t, _this, args) => {
692
+ return sendDesignCall(pathSegments, args);
693
+ }
694
+ });
695
+ };
696
+ return buildNode([]);
697
+ };
698
+
699
+ var createContextBridgeApi = () => {
700
+ const contextProxy = createApiProxy("context");
701
+ const subscriptionCallbacks = /* @__PURE__ */ new Map();
702
+ const dispatch = (message) => {
703
+ const cb = subscriptionCallbacks.get(message.subscriptionId);
704
+ cb?.(message.context);
705
+ };
706
+ const subscribeImpl = async (callback) => {
707
+ const subscriptionId = generateMessageId();
708
+ const messageId = generateMessageId();
709
+ subscriptionCallbacks.set(subscriptionId, callback);
710
+ let response;
711
+ try {
712
+ response = await sendMessage({
713
+ command: FROM_EXTENSION_COMMANDS.CONTEXT_SUBSCRIBE,
714
+ messageId,
715
+ subscriptionId
716
+ });
717
+ } catch (error) {
718
+ subscriptionCallbacks.delete(subscriptionId);
719
+ throw error;
720
+ }
721
+ if (!response.isOk) {
722
+ subscriptionCallbacks.delete(subscriptionId);
723
+ throw new Error(`context-subscribe failed: ${response.error.message}`);
724
+ }
725
+ return () => {
726
+ subscriptionCallbacks.delete(subscriptionId);
727
+ const message = {
728
+ command: FROM_EXTENSION_COMMANDS.CONTEXT_UNSUBSCRIBE,
729
+ subscriptionId
730
+ };
731
+ postMessageToParent(message);
732
+ };
733
+ };
734
+ const api = new Proxy(contextProxy, {
735
+ get(target, prop, receiver) {
736
+ if (prop === "subscribe") {
737
+ return subscribeImpl;
738
+ }
739
+ return Reflect.get(target, prop, receiver);
740
+ }
741
+ });
742
+ return { api, dispatch };
743
+ };
744
+
745
+ var sendUnsubscribe2 = (selectorIds) => {
746
+ const message = {
747
+ command: FROM_EXTENSION_COMMANDS.DESIGN_STATE_UNSUBSCRIBE,
748
+ selectorIds
749
+ };
750
+ postMessageToParent(message);
751
+ };
752
+ var createDesignStateBridgeApi = () => {
753
+ const localSubscriptions = /* @__PURE__ */ new Map();
754
+ async function subscribe(paths, callback) {
755
+ if (paths.length === 0) {
756
+ return () => {
757
+ };
758
+ }
759
+ const values = new Array(paths.length).fill(void 0);
760
+ const selectorIds = [];
761
+ const pathArrays = [];
762
+ for (const dotPath of paths) {
763
+ const segments = dotPath.split(".");
764
+ if (segments.some((s) => s === "")) {
765
+ throw new Error(
766
+ `Invalid design state path: '${dotPath}'. Path must be a non-empty dot-separated string.`
767
+ );
768
+ }
769
+ selectorIds.push(generateMessageId());
770
+ pathArrays.push(segments);
771
+ }
772
+ const messageId = generateMessageId();
773
+ const subscribeMessage = {
774
+ command: FROM_EXTENSION_COMMANDS.DESIGN_STATE_SUBSCRIBE,
775
+ messageId,
776
+ selectorIds,
777
+ paths: pathArrays
778
+ };
779
+ const response = await sendMessage(subscribeMessage);
780
+ if (!response.isOk) {
781
+ throw new Error(
782
+ `design-state-subscribe failed: ${response.error.message}`
783
+ );
784
+ }
785
+ for (let i = 0; i < selectorIds.length; i++) {
786
+ localSubscriptions.set(selectorIds[i], {
787
+ callback: (value) => {
788
+ values[i] = value;
789
+ callback(...values);
790
+ }
791
+ });
792
+ }
793
+ return () => {
794
+ for (const selectorId of selectorIds) {
795
+ localSubscriptions.delete(selectorId);
796
+ }
797
+ sendUnsubscribe2(selectorIds);
798
+ };
799
+ }
800
+ const dispatch = (updates) => {
801
+ for (const { selectorId, value } of updates) {
802
+ const entry = localSubscriptions.get(selectorId);
803
+ if (entry) {
804
+ entry.callback(value);
805
+ }
806
+ }
807
+ };
808
+ return { subscribe, dispatch };
809
+ };
810
+
811
+ var createStatelessBridgeApi = () => {
812
+ const subscribers = /* @__PURE__ */ new Map();
813
+ return {
814
+ send: (message) => {
815
+ const messageId = generateMessageId();
816
+ const bridgeMessage = {
817
+ command: FROM_EXTENSION_COMMANDS.STATELESS_SEND,
818
+ messageId,
819
+ type: message.type,
820
+ payload: message.payload
821
+ };
822
+ return sendMessage(bridgeMessage);
823
+ },
824
+ subscribe: async (key, handler) => {
825
+ let handlers = subscribers.get(key);
826
+ if (!handlers) {
827
+ handlers = /* @__PURE__ */ new Set();
828
+ subscribers.set(key, handlers);
829
+ }
830
+ handlers.add(handler);
831
+ const messageId = generateMessageId();
832
+ const subscribeMessage = {
833
+ command: FROM_EXTENSION_COMMANDS.STATELESS_SUBSCRIBE,
834
+ messageId,
835
+ key
836
+ };
837
+ return sendMessage(subscribeMessage);
838
+ },
839
+ unsubscribe: async (key) => {
840
+ subscribers.delete(key);
841
+ const messageId = generateMessageId();
842
+ const unsubscribeMessage = {
843
+ command: FROM_EXTENSION_COMMANDS.STATELESS_UNSUBSCRIBE,
844
+ messageId,
845
+ key
846
+ };
847
+ return sendMessage(unsubscribeMessage);
848
+ },
849
+ dispatch: (type, payload) => {
850
+ const handlers = subscribers.get(type);
851
+ if (handlers) {
852
+ for (const handler of handlers) {
853
+ handler(payload);
854
+ }
855
+ }
856
+ }
857
+ };
858
+ };
859
+
860
+ var statelessApi = createStatelessBridgeApi();
861
+ var designStateApi = createDesignStateBridgeApi();
862
+ var appStateApi = createAppStateBridgeApi();
863
+ var { api: contextApi, dispatch: dispatchContextUpdate } = createContextBridgeApi();
864
+ var authClient = new SandboxedAuthClient();
865
+ var handleIncomingMessage = (event) => {
866
+ const parent = window.parent;
867
+ if (!parent || parent === window) {
868
+ return;
869
+ }
870
+ if (event.source !== parent) {
871
+ return;
872
+ }
873
+ const { data } = event;
874
+ if (isSDKResponseMessage(data)) {
875
+ const resolver = pendingRequests.get(data.messageId);
876
+ if (resolver) {
877
+ pendingRequests.delete(data.messageId);
878
+ const response = data.response;
879
+ resolver.resolve(response);
880
+ }
881
+ return;
882
+ }
883
+ if (isStatelessPushMessage(data)) {
884
+ statelessApi.dispatch(data.type, data.payload);
885
+ return;
886
+ }
887
+ if (isAIGenerationUpdatePushMessage(data)) {
888
+ dispatchAIGenerationUpdate(data.subscriptionId, data.update);
889
+ return;
890
+ }
891
+ if (isDesignStateUpdatePushMessage(data)) {
892
+ designStateApi.dispatch(data.updates);
893
+ return;
894
+ }
895
+ if (isAppStateUpdatePushMessage(data)) {
896
+ appStateApi.dispatch(data.updates);
897
+ return;
898
+ }
899
+ if (isContextUpdatePushMessage(data)) {
900
+ dispatchContextUpdate(data);
901
+ return;
902
+ }
903
+ if (isFileBrowserFetchContentRequestMessage(data)) {
904
+ dispatchFileBrowserFetchContentRequest(
905
+ data.requestId,
906
+ data.subscriptionId,
907
+ data.params
908
+ );
909
+ }
910
+ };
911
+ var bridgeHandlers = {
912
+ ai: createAIApiProxy(),
913
+ context: contextApi,
914
+ data: createApiProxy("data"),
915
+ design: createApiProxy("design"),
916
+ designStore: designStateApi,
917
+ appStore: appStateApi,
918
+ export: createApiProxy("export"),
919
+ font: createApiProxy("font"),
920
+ state: createApiProxy("state"),
921
+ upload: createApiProxy("upload"),
922
+ fileBrowser: createFileBrowserApiProxy(),
923
+ auth: authClient,
924
+ stateless: statelessApi,
925
+ createBatch
926
+ };
927
+
928
+ // src/api/utils.ts
929
+ function unwrapResult(result) {
930
+ if (result.isOk) {
931
+ return result.result;
932
+ }
933
+ throw result.error;
934
+ }
935
+
936
+ // src/utils/syncHtmlDataThemeFromHostContext.ts
937
+ async function syncHtmlDataThemeFromHostContext(kittl2) {
938
+ if (typeof document === "undefined") {
939
+ return;
940
+ }
941
+ const parent = window.parent;
942
+ if (!parent || parent === window) {
943
+ return;
944
+ }
945
+ const contextResponse = await kittl2.context.get();
946
+ if (contextResponse.isOk) {
947
+ document.documentElement.dataset.theme = contextResponse.result.colorScheme;
948
+ }
949
+ await kittl2.context.subscribe((ctx) => {
950
+ document.documentElement.dataset.theme = ctx.colorScheme;
951
+ });
952
+ }
953
+
954
+ // src/createKittlSDK.ts
955
+ function createKittlSDK(apis) {
956
+ const kittl2 = {
957
+ onLoadedCallback: null,
958
+ loaded: false,
959
+ onReady: (callback) => {
960
+ if (kittl2.loaded) {
961
+ callback();
962
+ return;
963
+ }
964
+ kittl2.onLoadedCallback = callback;
965
+ },
966
+ ...apis
967
+ };
968
+ const initSdk = () => {
969
+ kittl2.loaded = true;
970
+ window.addEventListener(
971
+ "message",
972
+ (event) => {
973
+ handleIncomingMessage(event);
974
+ }
975
+ );
976
+ void syncHtmlDataThemeFromHostContext(kittl2).then(() => {
977
+ kittl2.onLoadedCallback?.();
978
+ sendLoaded();
979
+ });
980
+ };
981
+ if (typeof document !== "undefined" && typeof window !== "undefined") {
982
+ window.kittl = kittl2;
983
+ if (document.readyState === "loading") {
984
+ document.addEventListener("DOMContentLoaded", initSdk);
985
+ } else {
986
+ initSdk();
987
+ }
988
+ }
989
+ return kittl2;
990
+ }
991
+
992
+ // src/sharedFileBrowser.ts
993
+ var kittl = createKittlSDK({
994
+ auth: bridgeHandlers.auth,
995
+ context: bridgeHandlers.context,
996
+ fileBrowser: bridgeHandlers.fileBrowser
997
+ });
998
+ export {
999
+ kittl,
1000
+ unwrapResult
1001
+ };