@amplifyup/sdk 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1445 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ /* @amplifyup/sdk - https://amplifyup.ai */
6
+
7
+ // src/adapters/aws.ts
8
+ var AWSAdapter = class {
9
+ constructor() {
10
+ this.initialized = false;
11
+ this.config = null;
12
+ this.apiGatewayUrl = "";
13
+ }
14
+ async init(config) {
15
+ if (typeof window === "undefined") {
16
+ console.warn("AmplifyUp SDK: Window object not available (SSR)");
17
+ return;
18
+ }
19
+ if (this.initialized) {
20
+ return;
21
+ }
22
+ this.config = {
23
+ trackingId: config.trackingId,
24
+ debug: config.debug,
25
+ dev: config.dev
26
+ };
27
+ this.apiGatewayUrl = config.apiGatewayUrl || "";
28
+ if (!this.apiGatewayUrl) {
29
+ console.warn("AmplifyUp SDK: AWS API Gateway URL not configured. Tracking disabled.");
30
+ return;
31
+ }
32
+ this.initialized = true;
33
+ if (config.debug) {
34
+ console.log("AmplifyUp SDK: AWS adapter initialized", {
35
+ apiGatewayUrl: this.apiGatewayUrl
36
+ });
37
+ }
38
+ }
39
+ isInitialized() {
40
+ return this.initialized;
41
+ }
42
+ async sendEvent(endpoint, eventData) {
43
+ if (!this.apiGatewayUrl) {
44
+ console.warn("AmplifyUp SDK: AWS configuration missing");
45
+ return;
46
+ }
47
+ const url = `${this.apiGatewayUrl}${endpoint}`;
48
+ try {
49
+ const response = await fetch(url, {
50
+ method: "POST",
51
+ headers: {
52
+ "Content-Type": "application/json"
53
+ },
54
+ body: JSON.stringify(eventData)
55
+ });
56
+ if (!response.ok) {
57
+ if (this.config.debug) {
58
+ console.warn(`AmplifyUp SDK: Event tracking failed: ${response.status} ${response.statusText}`);
59
+ }
60
+ } else if (this.config.debug) {
61
+ const result = await response.json().catch(() => ({}));
62
+ console.log("AmplifyUp SDK: Event tracked", result);
63
+ }
64
+ } catch (error) {
65
+ if (this.config.debug) {
66
+ console.error("AmplifyUp SDK: Event tracking error:", error);
67
+ }
68
+ }
69
+ }
70
+ page(properties) {
71
+ if (!this.initialized) {
72
+ return;
73
+ }
74
+ if (typeof window !== "undefined") {
75
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
76
+ return;
77
+ }
78
+ if (window.location.pathname.includes("/api/pages/proxy")) {
79
+ return;
80
+ }
81
+ const urlParams = new URLSearchParams(window.location.search);
82
+ if (urlParams.get("preview") === "true" || urlParams.get("visualEditor") === "true") {
83
+ return;
84
+ }
85
+ if (window.self !== window.top) {
86
+ return;
87
+ }
88
+ if (window.location.href.includes("preview=true") || window.location.href.includes("visualEditor=true")) {
89
+ return;
90
+ }
91
+ }
92
+ const eventData = {
93
+ type: "page",
94
+ anonymousId: properties.instanceId,
95
+ userId: properties.userId,
96
+ properties: {
97
+ path: properties.path || properties.url,
98
+ referrer: properties.referrer,
99
+ ...properties
100
+ },
101
+ context: {
102
+ page: {
103
+ path: properties.path || properties.url,
104
+ referrer: properties.referrer
105
+ }
106
+ },
107
+ timestamp: properties.timestamp || (/* @__PURE__ */ new Date()).toISOString()
108
+ };
109
+ this.sendEvent("/v1/page", eventData);
110
+ }
111
+ track(eventName, properties) {
112
+ if (!this.initialized) {
113
+ return;
114
+ }
115
+ if (typeof window !== "undefined") {
116
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
117
+ return;
118
+ }
119
+ if (window.location.pathname.includes("/api/pages/proxy")) {
120
+ return;
121
+ }
122
+ const urlParams = new URLSearchParams(window.location.search);
123
+ if (urlParams.get("preview") === "true" || urlParams.get("visualEditor") === "true") {
124
+ return;
125
+ }
126
+ if (window.self !== window.top) {
127
+ return;
128
+ }
129
+ if (window.location.href.includes("preview=true") || window.location.href.includes("visualEditor=true")) {
130
+ return;
131
+ }
132
+ }
133
+ const eventData = {
134
+ type: "track",
135
+ event: eventName,
136
+ anonymousId: properties.instanceId,
137
+ userId: properties.userId,
138
+ properties: {
139
+ ...properties
140
+ },
141
+ context: {
142
+ url: properties.url || (typeof window !== "undefined" ? window.location.href : "")
143
+ },
144
+ timestamp: properties.timestamp || (/* @__PURE__ */ new Date()).toISOString()
145
+ };
146
+ this.sendEvent("/v1/track", eventData);
147
+ }
148
+ identify(userId, traits) {
149
+ if (!this.initialized) {
150
+ console.warn("AmplifyUp SDK: Not initialized. Call init() first.");
151
+ return;
152
+ }
153
+ const eventData = {
154
+ type: "identify",
155
+ userId,
156
+ anonymousId: traits.instanceId,
157
+ traits: {
158
+ ...traits
159
+ },
160
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
161
+ };
162
+ this.sendEvent("/v1/track", eventData);
163
+ }
164
+ reset() {
165
+ if (this.config?.debug) {
166
+ console.log("AmplifyUp SDK: Reset called (identity cleared)");
167
+ }
168
+ }
169
+ };
170
+
171
+ // src/storage.ts
172
+ var INSTANCE_ID_KEY = "amplifyup_instance_id";
173
+ var USER_ID_KEY = "amplifyup_user_id";
174
+ function getInstanceId() {
175
+ if (typeof window === "undefined") {
176
+ return "";
177
+ }
178
+ const stored = localStorage.getItem(INSTANCE_ID_KEY);
179
+ if (stored) {
180
+ return stored;
181
+ }
182
+ const instanceId = `anon_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
183
+ localStorage.setItem(INSTANCE_ID_KEY, instanceId);
184
+ return instanceId;
185
+ }
186
+ function getUserId() {
187
+ if (typeof window === "undefined") {
188
+ return null;
189
+ }
190
+ return localStorage.getItem(USER_ID_KEY);
191
+ }
192
+ function setUserId(userId) {
193
+ if (typeof window === "undefined") {
194
+ return;
195
+ }
196
+ localStorage.setItem(USER_ID_KEY, userId);
197
+ }
198
+ function clearIds() {
199
+ if (typeof window === "undefined") {
200
+ return;
201
+ }
202
+ localStorage.removeItem(INSTANCE_ID_KEY);
203
+ localStorage.removeItem(USER_ID_KEY);
204
+ }
205
+
206
+ // src/index.ts
207
+ var PROD_API_URL = "https://api.amplifyup.ai" ;
208
+ var PROD_ORCHESTRATOR_URL = "https://amplifyup.ai" ;
209
+ var AmplifyUpSDK = class {
210
+ constructor(adapter) {
211
+ this.config = null;
212
+ // Internal URLs - set during init, not part of user config
213
+ this.apiGatewayUrl = "";
214
+ this.orchestratorUrl = "";
215
+ this.decisionApiUrl = "";
216
+ this.initialized = false;
217
+ this.highlightingEnabled = false;
218
+ this.componentRegistry = [];
219
+ this.messageListener = null;
220
+ this.mutationObserver = null;
221
+ this.isVisualEditorMode = false;
222
+ this.eventSelectionMode = false;
223
+ this.eventSelectionClickHandler = null;
224
+ this.eventTrackingConfig = [];
225
+ this.attachedEventListeners = [];
226
+ this.trackingIntervals = [];
227
+ this.trackingCleanup = null;
228
+ this.adapter = adapter || new AWSAdapter();
229
+ if (typeof window !== "undefined") {
230
+ this.isVisualEditorMode = this.detectVisualEditorMode();
231
+ if (this.isVisualEditorMode) {
232
+ this.setupHighlightingListener();
233
+ console.log("[AmplifyUp SDK] Visual editor mode detected - message listener enabled");
234
+ }
235
+ }
236
+ }
237
+ /**
238
+ * Detect if we're running in visual editor mode
239
+ * Returns true if:
240
+ * 1. Preview mode flag is set by proxy
241
+ * 2. We're in an iframe AND parent is from orchestrator domain
242
+ * 3. OR visualEditor/preview query parameter is present
243
+ */
244
+ detectVisualEditorMode() {
245
+ if (typeof window === "undefined") return false;
246
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
247
+ return true;
248
+ }
249
+ const urlParams = new URLSearchParams(window.location.search);
250
+ if (urlParams.get("visualEditor") === "true" || urlParams.get("preview") === "true") {
251
+ return true;
252
+ }
253
+ const inIframe = window.self !== window.top;
254
+ if (!inIframe) return false;
255
+ try {
256
+ if (document.referrer) {
257
+ const referrerUrl = new URL(document.referrer);
258
+ if (referrerUrl.hostname === "localhost" && referrerUrl.port === "5001" || referrerUrl.pathname.includes("/dashboard/composer") || referrerUrl.pathname.includes("/dashboard/routes/")) {
259
+ return true;
260
+ }
261
+ }
262
+ } catch (e) {
263
+ }
264
+ return false;
265
+ }
266
+ /**
267
+ * Check if we're in preview/composer mode (should disable tracking)
268
+ */
269
+ isPreviewMode() {
270
+ if (typeof window === "undefined") return false;
271
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
272
+ return true;
273
+ }
274
+ if (window.location.pathname.includes("/api/pages/proxy")) {
275
+ return true;
276
+ }
277
+ const urlParams = new URLSearchParams(window.location.search);
278
+ if (urlParams.get("preview") === "true" || urlParams.get("visualEditor") === "true") {
279
+ return true;
280
+ }
281
+ const fullUrl = window.location.href;
282
+ if (fullUrl.includes("preview=true") || fullUrl.includes("visualEditor=true")) {
283
+ return true;
284
+ }
285
+ if (window.self !== window.top) {
286
+ if (document.referrer) {
287
+ try {
288
+ const referrerUrl = new URL(document.referrer);
289
+ if (referrerUrl.hostname === "localhost" && referrerUrl.port === "5001" || referrerUrl.pathname.includes("/dashboard/composer") || referrerUrl.pathname.includes("/dashboard/routes/")) {
290
+ return true;
291
+ }
292
+ } catch {
293
+ }
294
+ }
295
+ return true;
296
+ }
297
+ return false;
298
+ }
299
+ /**
300
+ * Get production URLs
301
+ *
302
+ * URLs are baked in at build time via tsup.config.ts
303
+ *
304
+ * API Gateway endpoints:
305
+ * - /v1/track - Event tracking (ingestion)
306
+ * - /v1/page - Page view tracking (ingestion)
307
+ * - /v1/personalize - Decision engine (personalization)
308
+ */
309
+ getProductionUrls() {
310
+ return {
311
+ apiGatewayUrl: PROD_API_URL,
312
+ orchestratorUrl: PROD_ORCHESTRATOR_URL,
313
+ decisionApiUrl: `${PROD_API_URL}/v1/personalize`
314
+ };
315
+ }
316
+ /**
317
+ * Initialize the SDK
318
+ * Automatically reads env vars and sets up tracking
319
+ */
320
+ async init(config) {
321
+ if (!this.adapter) {
322
+ this.adapter = new AWSAdapter();
323
+ }
324
+ const isLocalhost = typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1");
325
+ if (isLocalhost || config.dev === true) {
326
+ this.apiGatewayUrl = "http://localhost:5001/api";
327
+ this.orchestratorUrl = "http://localhost:5001";
328
+ this.decisionApiUrl = "http://localhost:5001/api/v1/personalize";
329
+ } else {
330
+ const urls = this.getProductionUrls();
331
+ this.apiGatewayUrl = urls.apiGatewayUrl;
332
+ this.orchestratorUrl = urls.orchestratorUrl;
333
+ this.decisionApiUrl = urls.decisionApiUrl;
334
+ }
335
+ this.config = {
336
+ trackingId: config.trackingId,
337
+ debug: config.debug ?? true,
338
+ // Enable debug by default
339
+ dev: config.dev
340
+ };
341
+ try {
342
+ const adapterConfig = {
343
+ ...this.config,
344
+ apiGatewayUrl: this.apiGatewayUrl,
345
+ orchestratorUrl: this.orchestratorUrl,
346
+ decisionApiUrl: this.decisionApiUrl
347
+ };
348
+ await this.adapter.init(adapterConfig);
349
+ this.initialized = this.adapter.isInitialized();
350
+ if (typeof window !== "undefined") {
351
+ window.AmplifyUp = {
352
+ getInstanceId: () => this.getInstanceId(),
353
+ getUserId: () => this.getUserId(),
354
+ getTrackingId: () => this.getTrackingId(),
355
+ getDiagnostics: () => this.getDiagnostics(),
356
+ getStatus: () => {
357
+ console.log(this.getStatus());
358
+ return this.getDiagnostics();
359
+ },
360
+ testTracking: () => this.testTracking(),
361
+ verifyAWSConnection: () => {
362
+ const result = this.verifyAWSConnection();
363
+ console.log("AWS Connection Verification:", result.message);
364
+ console.log("Full details:", result);
365
+ return result;
366
+ },
367
+ isInitialized: () => this.isInitialized(),
368
+ // Re-export main tracking methods for convenience
369
+ page: (url, properties) => this.page(url, properties),
370
+ track: (eventName, properties) => this.track(eventName, properties),
371
+ identify: (userId, traits) => this.identify(userId, traits)
372
+ };
373
+ if (this.config?.debug) {
374
+ console.log("AmplifyUp SDK: Diagnostic methods available on window.AmplifyUp");
375
+ console.log("Try: AmplifyUp.getStatus() or AmplifyUp.verifyAWSConnection()");
376
+ }
377
+ }
378
+ this.clearTrackingIntervals();
379
+ if (this.isPreviewMode()) {
380
+ return;
381
+ }
382
+ if (typeof window !== "undefined" && this.initialized) {
383
+ await new Promise((resolve) => setTimeout(resolve, 200));
384
+ if (this.isPreviewMode()) {
385
+ return;
386
+ }
387
+ const url = window.location.pathname;
388
+ this.page(url);
389
+ }
390
+ if (this.config?.debug && this.initialized) {
391
+ console.log("AmplifyUp SDK: Initialized successfully", { trackingId: config.trackingId });
392
+ }
393
+ } catch (error) {
394
+ console.error("AmplifyUp SDK: Initialization failed", error);
395
+ throw error;
396
+ }
397
+ }
398
+ /**
399
+ * Check if SDK is initialized
400
+ */
401
+ isInitialized() {
402
+ return this.initialized && this.adapter.isInitialized();
403
+ }
404
+ /**
405
+ * Clear all tracking intervals and event listeners
406
+ */
407
+ clearTrackingIntervals() {
408
+ if (this.trackingCleanup) {
409
+ this.trackingCleanup();
410
+ this.trackingCleanup = null;
411
+ }
412
+ this.trackingIntervals.forEach((id) => clearInterval(id));
413
+ this.trackingIntervals = [];
414
+ }
415
+ /**
416
+ * Track a page view
417
+ */
418
+ page(url, properties) {
419
+ if (this.isPreviewMode()) {
420
+ return;
421
+ }
422
+ if (!this.isInitialized()) {
423
+ return;
424
+ }
425
+ const instanceId = getInstanceId();
426
+ const pageProperties = {
427
+ name: url,
428
+ path: url,
429
+ url: typeof window !== "undefined" ? window.location.href : url,
430
+ referrer: typeof document !== "undefined" ? document.referrer : void 0,
431
+ instanceId,
432
+ trackingId: this.config?.trackingId,
433
+ // Timestamp is included in event payload
434
+ ...properties
435
+ };
436
+ this.adapter.page(pageProperties);
437
+ }
438
+ /**
439
+ * Track an event
440
+ */
441
+ track(eventName, properties) {
442
+ if (this.isPreviewMode()) {
443
+ return;
444
+ }
445
+ if (!this.isInitialized()) {
446
+ return;
447
+ }
448
+ const instanceId = getInstanceId();
449
+ const trackProperties = {
450
+ instanceId,
451
+ trackingId: this.config?.trackingId,
452
+ url: typeof window !== "undefined" ? window.location.href : void 0,
453
+ // Timestamp is included in event payload
454
+ ...properties
455
+ };
456
+ this.adapter.track(eventName, trackProperties);
457
+ }
458
+ /**
459
+ * Track a button click or CTA interaction
460
+ */
461
+ trackClick(elementId, elementText, properties) {
462
+ this.track("Button Click", {
463
+ elementId,
464
+ elementText,
465
+ ...properties
466
+ });
467
+ }
468
+ /**
469
+ * Track form submission
470
+ */
471
+ trackFormSubmit(formId, formData) {
472
+ this.track("Form Submit", {
473
+ formId,
474
+ ...formData
475
+ });
476
+ }
477
+ /**
478
+ * Track form field interaction
479
+ */
480
+ trackFormFieldInteraction(fieldName, fieldValue) {
481
+ this.track("Form Field Interaction", {
482
+ fieldName,
483
+ fieldValue: fieldValue ? fieldValue.substring(0, 100) : void 0
484
+ // Truncate for privacy
485
+ });
486
+ }
487
+ /**
488
+ * Track product/content view
489
+ */
490
+ trackContentView(contentId, contentType, properties) {
491
+ this.track("Content View", {
492
+ contentId,
493
+ contentType,
494
+ ...properties
495
+ });
496
+ }
497
+ /**
498
+ * Identify user (when they sign up or log in)
499
+ */
500
+ identify(userId, traits) {
501
+ if (this.isPreviewMode()) {
502
+ if (this.config?.debug) {
503
+ console.log("AmplifyUp SDK: Identify tracking disabled in preview mode", { userId });
504
+ }
505
+ return;
506
+ }
507
+ if (!this.isInitialized()) {
508
+ if (this.config?.debug) {
509
+ console.warn("AmplifyUp SDK: Not initialized. Identify not called.");
510
+ }
511
+ return;
512
+ }
513
+ const instanceId = getInstanceId();
514
+ const identifyTraits = {
515
+ instanceId,
516
+ trackingId: this.config?.trackingId,
517
+ ...traits
518
+ };
519
+ this.adapter.identify(userId, identifyTraits);
520
+ setUserId(userId);
521
+ if (this.config?.debug) {
522
+ console.log("AmplifyUp SDK: User identified", { userId, instanceId });
523
+ }
524
+ }
525
+ /**
526
+ * Track content engagement (when user interacts with personalized content)
527
+ */
528
+ trackContentEngagement(contentId, engagementType) {
529
+ this.track("Content Engagement", {
530
+ contentId,
531
+ engagementType
532
+ });
533
+ if (this.orchestratorUrl) {
534
+ const instanceId = getInstanceId();
535
+ fetch(`${this.orchestratorUrl}/api/personalization/feedback`, {
536
+ method: "POST",
537
+ headers: { "Content-Type": "application/json" },
538
+ body: JSON.stringify({
539
+ instanceId,
540
+ trackingId: this.config?.trackingId,
541
+ contentId,
542
+ engagementType,
543
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
544
+ })
545
+ }).catch((err) => {
546
+ if (this.config?.debug) {
547
+ console.error("AmplifyUp SDK: Failed to send engagement feedback:", err);
548
+ }
549
+ });
550
+ }
551
+ }
552
+ /**
553
+ * Reset user identity (logout)
554
+ */
555
+ reset() {
556
+ this.adapter.reset();
557
+ clearIds();
558
+ if (this.config?.debug) {
559
+ console.log("AmplifyUp SDK: User identity reset");
560
+ }
561
+ }
562
+ /**
563
+ * Get instance ID (anonymous ID)
564
+ */
565
+ getInstanceId() {
566
+ return getInstanceId();
567
+ }
568
+ /**
569
+ * Get user ID
570
+ */
571
+ getUserId() {
572
+ return getUserId();
573
+ }
574
+ /**
575
+ * Get tracking ID
576
+ */
577
+ getTrackingId() {
578
+ return this.config?.trackingId;
579
+ }
580
+ /**
581
+ * Get diagnostic information
582
+ * Useful for debugging from browser console
583
+ */
584
+ getDiagnostics() {
585
+ const instanceId = getInstanceId();
586
+ const userId = getUserId();
587
+ return {
588
+ initialized: this.initialized,
589
+ instanceId,
590
+ userId,
591
+ trackingId: this.config?.trackingId,
592
+ config: {
593
+ apiGatewayUrl: this.apiGatewayUrl,
594
+ decisionApiUrl: this.decisionApiUrl,
595
+ orchestratorUrl: this.orchestratorUrl,
596
+ debug: this.config?.debug
597
+ }
598
+ };
599
+ }
600
+ /**
601
+ * Test tracking by sending a test event
602
+ */
603
+ testTracking() {
604
+ if (!this.initialized) {
605
+ console.warn("AmplifyUp SDK: Not initialized. Cannot test tracking.");
606
+ return;
607
+ }
608
+ const testEvent = {
609
+ eventName: "SDK Test Event",
610
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
611
+ test: true
612
+ };
613
+ console.log("AmplifyUp SDK: Sending test event...", testEvent);
614
+ this.track("SDK Test Event", {
615
+ ...testEvent,
616
+ instanceId: getInstanceId(),
617
+ trackingId: this.config?.trackingId
618
+ });
619
+ console.log("AmplifyUp SDK: Test event sent. Check AWS API Gateway to verify it was received.");
620
+ console.log("AmplifyUp SDK: Check Network tab for requests to:", this.apiGatewayUrl);
621
+ }
622
+ /**
623
+ * Verify AWS API Gateway connectivity
624
+ * Checks if AWS adapter is initialized and can send events
625
+ */
626
+ verifyAWSConnection() {
627
+ if (!this.apiGatewayUrl) {
628
+ return {
629
+ connected: false,
630
+ message: "AWS API Gateway URL not configured"
631
+ };
632
+ }
633
+ if (!this.initialized) {
634
+ return {
635
+ connected: false,
636
+ message: "SDK not initialized"
637
+ };
638
+ }
639
+ return {
640
+ connected: true,
641
+ message: "AWS adapter is connected and ready",
642
+ details: {
643
+ apiGatewayUrl: this.apiGatewayUrl,
644
+ decisionApiUrl: this.decisionApiUrl
645
+ }
646
+ };
647
+ }
648
+ /**
649
+ * Get status summary (for console debugging)
650
+ */
651
+ getStatus() {
652
+ const diag = this.getDiagnostics();
653
+ return `
654
+ AmplifyUp SDK Status:
655
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
656
+ Initialized: ${diag.initialized ? "\u2705 Yes" : "\u274C No"}
657
+ Instance ID: ${diag.instanceId}
658
+ User ID: ${diag.userId || "Not identified"}
659
+ Tracking ID: ${diag.trackingId || "Not set"}
660
+
661
+ Adapter:
662
+ Type: AWS (Pure AWS Architecture)
663
+
664
+ Config:
665
+ API Gateway: ${this.apiGatewayUrl || "Not set (required)"}
666
+ Decision API: ${this.decisionApiUrl || "Not set (using Orchestrator fallback)"}
667
+ Orchestrator: ${this.orchestratorUrl || "Not set"}
668
+ Debug: ${diag.config.debug ? "Enabled" : "Disabled"}
669
+
670
+ Available Console Commands:
671
+ AmplifyUp.getStatus() - Show this status
672
+ AmplifyUp.getDiagnostics() - Get full diagnostic object
673
+ AmplifyUp.getInstanceId() - Get instance ID (browser/session ID)
674
+ AmplifyUp.getUserId() - Get user ID if identified
675
+ AmplifyUp.testTracking() - Send a test event
676
+ AmplifyUp.verifyAWSConnection() - Verify AWS API Gateway connectivity
677
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
678
+ `.trim();
679
+ }
680
+ /**
681
+ * Get orchestrator URL
682
+ */
683
+ getOrchestratorUrl() {
684
+ return this.orchestratorUrl || void 0;
685
+ }
686
+ /**
687
+ * Get decision API URL
688
+ */
689
+ getDecisionApiUrl() {
690
+ return this.decisionApiUrl || void 0;
691
+ }
692
+ /**
693
+ * Build API URL for fetching page config from the Layout Provider
694
+ */
695
+ buildLayoutProviderUrl(route, preview = false) {
696
+ const orchestratorUrl = this.getOrchestratorUrl();
697
+ const trackingId = this.getTrackingId();
698
+ const instanceId = getInstanceId();
699
+ if (!orchestratorUrl || !trackingId) {
700
+ throw new Error("SDK not initialized. Call init() first.");
701
+ }
702
+ const isOnOrchestratorOrigin = typeof window !== "undefined" && window.location.origin === new URL(orchestratorUrl).origin;
703
+ const params = new URLSearchParams({
704
+ route,
705
+ trackingId,
706
+ instanceId
707
+ });
708
+ if (preview) {
709
+ params.set("preview", "true");
710
+ }
711
+ if (isOnOrchestratorOrigin) {
712
+ return `/api/layout/provider?${params.toString()}`;
713
+ }
714
+ return `${orchestratorUrl}/api/layout/provider?${params.toString()}`;
715
+ }
716
+ /**
717
+ * Fetch page configuration from orchestrator's Layout Provider
718
+ */
719
+ async fetchPageConfig(route, preview = false) {
720
+ const url = this.buildLayoutProviderUrl(route, preview);
721
+ const response = await fetch(url);
722
+ if (!response.ok) {
723
+ if (response.status === 404) {
724
+ return null;
725
+ }
726
+ throw new Error(`Failed to fetch page: ${response.statusText}`);
727
+ }
728
+ const data = await response.json();
729
+ const pageConfig = data.page;
730
+ if (pageConfig?.eventTracking) {
731
+ this.setupEventTracking(pageConfig.eventTracking);
732
+ }
733
+ return pageConfig;
734
+ }
735
+ /**
736
+ * Set up view-level event tracking based on configuration
737
+ */
738
+ setupEventTracking(eventConfig) {
739
+ if (typeof document === "undefined") return;
740
+ this.cleanupEventTracking();
741
+ this.eventTrackingConfig = eventConfig;
742
+ if (this.config?.debug) {
743
+ console.log("[AmplifyUp SDK] Setting up event tracking:", eventConfig.length, "events");
744
+ }
745
+ if (document.readyState === "loading") {
746
+ document.addEventListener("DOMContentLoaded", () => this.attachEventListeners());
747
+ } else {
748
+ setTimeout(() => this.attachEventListeners(), 100);
749
+ }
750
+ }
751
+ /**
752
+ * Attach event listeners to page elements based on view-level configuration
753
+ */
754
+ attachEventListeners() {
755
+ if (typeof document === "undefined") return;
756
+ this.eventTrackingConfig.forEach((eventConfig) => {
757
+ if (eventConfig.enabled === false) return;
758
+ let targetElements = [];
759
+ if (eventConfig.selector) {
760
+ try {
761
+ targetElements = document.querySelectorAll(eventConfig.selector);
762
+ } catch (e) {
763
+ if (this.config?.debug) {
764
+ console.warn(`[AmplifyUp SDK] Invalid selector: ${eventConfig.selector}`, e);
765
+ }
766
+ return;
767
+ }
768
+ } else {
769
+ if (this.config?.debug) {
770
+ console.warn(`[AmplifyUp SDK] Event ${eventConfig.eventName} has no selector, skipping`);
771
+ }
772
+ return;
773
+ }
774
+ if (targetElements.length === 0) {
775
+ if (this.config?.debug) {
776
+ console.log(`[AmplifyUp SDK] No elements found for selector: ${eventConfig.selector}`);
777
+ }
778
+ return;
779
+ }
780
+ targetElements.forEach((targetEl) => {
781
+ const htmlTargetEl = targetEl;
782
+ const domEventType = this.mapEventType(eventConfig.eventType);
783
+ const handler = (e) => {
784
+ this.handleTrackedEvent(e, eventConfig, htmlTargetEl);
785
+ };
786
+ if (eventConfig.eventType === "view") {
787
+ this.setupViewTracking(htmlTargetEl, eventConfig);
788
+ } else {
789
+ htmlTargetEl.addEventListener(domEventType, handler);
790
+ this.attachedEventListeners.push({
791
+ element: htmlTargetEl,
792
+ eventType: domEventType,
793
+ handler
794
+ });
795
+ }
796
+ if (this.config?.debug) {
797
+ console.log(`[AmplifyUp SDK] Attached ${eventConfig.eventType} listener for ${eventConfig.eventName} on selector: ${eventConfig.selector}`);
798
+ }
799
+ });
800
+ });
801
+ }
802
+ /**
803
+ * Map event type from config to DOM event type
804
+ */
805
+ mapEventType(eventType) {
806
+ const eventMap = {
807
+ "click": "click",
808
+ "submit": "submit",
809
+ "focus": "focus",
810
+ "blur": "blur",
811
+ "hover": "mouseenter",
812
+ "change": "change",
813
+ "scroll": "scroll",
814
+ "view": "view",
815
+ // Handled separately with IntersectionObserver
816
+ "custom": "custom"
817
+ };
818
+ return eventMap[eventType] || eventType;
819
+ }
820
+ /**
821
+ * Handle a tracked event and send to AWS API Gateway
822
+ */
823
+ handleTrackedEvent(event, config, element) {
824
+ const properties = {
825
+ eventType: config.eventType,
826
+ selector: config.selector
827
+ };
828
+ if (config.properties && config.properties.length > 0) {
829
+ config.properties.forEach((prop) => {
830
+ const dataAttrValue = element.getAttribute(`data-${prop}`);
831
+ if (dataAttrValue) {
832
+ properties[prop] = dataAttrValue;
833
+ return;
834
+ }
835
+ if (prop in element) {
836
+ const value = element[prop];
837
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
838
+ properties[prop] = value;
839
+ }
840
+ }
841
+ switch (prop) {
842
+ case "buttonText":
843
+ case "text":
844
+ properties[prop] = element.textContent?.trim().substring(0, 100);
845
+ break;
846
+ case "linkUrl":
847
+ case "href":
848
+ properties[prop] = element.getAttribute("href");
849
+ break;
850
+ case "formId":
851
+ case "id":
852
+ properties[prop] = element.id || element.getAttribute("name");
853
+ break;
854
+ case "value":
855
+ properties[prop] = element.value;
856
+ break;
857
+ case "tagName":
858
+ properties[prop] = element.tagName.toLowerCase();
859
+ break;
860
+ case "className":
861
+ properties[prop] = element.className;
862
+ break;
863
+ }
864
+ });
865
+ }
866
+ this.track(config.eventName, properties);
867
+ if (this.config?.debug) {
868
+ console.log(`[AmplifyUp SDK] Tracked event: ${config.eventName}`, properties);
869
+ }
870
+ }
871
+ /**
872
+ * Set up view tracking using IntersectionObserver
873
+ */
874
+ setupViewTracking(element, config) {
875
+ if (typeof IntersectionObserver === "undefined") return;
876
+ const observer = new IntersectionObserver(
877
+ (entries) => {
878
+ entries.forEach((entry) => {
879
+ if (entry.isIntersecting) {
880
+ this.handleTrackedEvent(
881
+ new CustomEvent("view"),
882
+ config,
883
+ element
884
+ );
885
+ observer.unobserve(element);
886
+ }
887
+ });
888
+ },
889
+ {
890
+ threshold: 0.5
891
+ // 50% visible
892
+ }
893
+ );
894
+ observer.observe(element);
895
+ element._amplifyupViewObserver = observer;
896
+ }
897
+ /**
898
+ * Clean up all attached event listeners
899
+ */
900
+ cleanupEventTracking() {
901
+ this.attachedEventListeners.forEach(({ element, eventType, handler }) => {
902
+ element.removeEventListener(eventType, handler);
903
+ });
904
+ this.attachedEventListeners = [];
905
+ if (typeof document !== "undefined") {
906
+ document.querySelectorAll("*").forEach((el) => {
907
+ const observer = el._amplifyupViewObserver;
908
+ if (observer) {
909
+ observer.disconnect();
910
+ delete el._amplifyupViewObserver;
911
+ }
912
+ });
913
+ }
914
+ this.eventTrackingConfig = [];
915
+ if (this.config?.debug) {
916
+ console.log("[AmplifyUp SDK] Cleaned up event tracking");
917
+ }
918
+ }
919
+ /**
920
+ * Manually trigger event tracking setup (useful after dynamic content loads)
921
+ */
922
+ refreshEventTracking() {
923
+ if (this.eventTrackingConfig.length > 0) {
924
+ this.cleanupEventTracking();
925
+ const config = [...this.eventTrackingConfig];
926
+ this.eventTrackingConfig = config;
927
+ this.attachEventListeners();
928
+ }
929
+ }
930
+ /**
931
+ * Set up postMessage listener for highlighting commands from orchestrator
932
+ */
933
+ setupHighlightingListener() {
934
+ if (this.messageListener) {
935
+ console.log("[AmplifyUp SDK] Message listener already set up");
936
+ return;
937
+ }
938
+ console.log("[AmplifyUp SDK] Setting up message listener...");
939
+ this.messageListener = (event) => {
940
+ console.log("[AmplifyUp SDK] Received message:", {
941
+ origin: event.origin,
942
+ currentOrigin: window.location.origin,
943
+ data: event.data
944
+ });
945
+ const allowedOrigins = [
946
+ "http://localhost:5001",
947
+ "http://localhost:3001",
948
+ "https://orchestrator.amplifyup.com"
949
+ ];
950
+ const isSameOrigin = event.origin === window.location.origin;
951
+ const isAllowedOrigin = allowedOrigins.some((origin) => event.origin.startsWith(origin));
952
+ if (!isSameOrigin && !isAllowedOrigin) {
953
+ console.warn("[AmplifyUp SDK] Rejected message from unauthorized origin:", {
954
+ eventOrigin: event.origin,
955
+ currentOrigin: window.location.origin,
956
+ allowedOrigins
957
+ });
958
+ return;
959
+ }
960
+ try {
961
+ if (event.data?.type === "COMPONENT_DELETABLE_STATUS") {
962
+ const { componentId, deletable, nodeId } = event.data;
963
+ const element = document.querySelector(`[data-component-id="${componentId}"]`);
964
+ if (element) {
965
+ const deleteButton = element._deleteButton;
966
+ if (deleteButton) {
967
+ if (deletable && nodeId) {
968
+ deleteButton.disabled = false;
969
+ deleteButton.style.opacity = "1";
970
+ deleteButton.style.cursor = "pointer";
971
+ element.setAttribute("data-node-id", nodeId);
972
+ } else {
973
+ deleteButton.disabled = true;
974
+ deleteButton.style.opacity = "0.5";
975
+ deleteButton.style.cursor = "not-allowed";
976
+ }
977
+ }
978
+ }
979
+ return;
980
+ }
981
+ if (event.data?.type === "DELETE_COMPONENT_REQUEST") {
982
+ if (window.parent && window.parent !== window) {
983
+ window.parent.postMessage(event.data, "*");
984
+ }
985
+ return;
986
+ }
987
+ if (event.data?.type === "GET_ELEMENT_POSITION") {
988
+ const { componentId, slotName } = event.data;
989
+ const selector = slotName ? `[data-amplifyup-slot="${slotName}"]` : `[data-amplifyup-component="${componentId}"], [data-component-id="${componentId}"]`;
990
+ console.log("[AmplifyUp SDK] Finding element position:", { selector, componentId, slotName });
991
+ const element = document.querySelector(selector);
992
+ if (element) {
993
+ const rect = element.getBoundingClientRect();
994
+ const position = {
995
+ x: rect.left + rect.width / 2,
996
+ // Center of element
997
+ y: rect.top - 50,
998
+ // Position above element
999
+ width: rect.width,
1000
+ height: rect.height
1001
+ };
1002
+ console.log("[AmplifyUp SDK] Element position calculated:", { rect, position });
1003
+ if (window.parent && window.parent !== window) {
1004
+ window.parent.postMessage({
1005
+ type: "ELEMENT_POSITION",
1006
+ componentId,
1007
+ slotName,
1008
+ position
1009
+ }, "*");
1010
+ console.log("[AmplifyUp SDK] Sent ELEMENT_POSITION message");
1011
+ }
1012
+ } else {
1013
+ console.warn("[AmplifyUp SDK] Element not found for selector:", selector);
1014
+ }
1015
+ return;
1016
+ }
1017
+ const message = event.data;
1018
+ if (!message || typeof message !== "object" || !message.type) {
1019
+ console.log("[AmplifyUp SDK] Message is not a highlighting message:", message);
1020
+ return;
1021
+ }
1022
+ console.log("[AmplifyUp SDK] Processing highlight message:", message.type);
1023
+ switch (message.type) {
1024
+ case "ENABLE_HIGHLIGHTING":
1025
+ case "UPDATE_HIGHLIGHTING":
1026
+ console.log("[AmplifyUp SDK] Enabling highlighting with registry:", message.componentRegistry?.length || 0, "components");
1027
+ this.enableHighlighting(
1028
+ message.componentRegistry || [],
1029
+ message.highlightComponents ?? true,
1030
+ message.showZones ?? false
1031
+ );
1032
+ break;
1033
+ case "DISABLE_HIGHLIGHTING":
1034
+ console.log("[AmplifyUp SDK] Disabling highlighting");
1035
+ this.disableHighlighting();
1036
+ break;
1037
+ case "SHOW_COMPONENT_TOOLTIP":
1038
+ case "HIDE_ALL_TOOLTIPS":
1039
+ break;
1040
+ case "ENABLE_EVENT_SELECTION":
1041
+ console.log("[AmplifyUp SDK] Enable event selection mode:", message.enabled);
1042
+ this.setEventSelectionMode(message.enabled || false);
1043
+ break;
1044
+ }
1045
+ } catch (error) {
1046
+ console.error("[AmplifyUp SDK] Error handling highlight message:", error);
1047
+ }
1048
+ };
1049
+ window.addEventListener("message", this.messageListener);
1050
+ console.log("[AmplifyUp SDK] Message listener attached to window");
1051
+ }
1052
+ /**
1053
+ * Enable/disable event selection mode
1054
+ * When enabled, clicks on elements send element info to parent for event configuration
1055
+ */
1056
+ setEventSelectionMode(enabled) {
1057
+ if (typeof document === "undefined") return;
1058
+ this.eventSelectionMode = enabled;
1059
+ if (this.eventSelectionClickHandler) {
1060
+ document.removeEventListener("click", this.eventSelectionClickHandler, true);
1061
+ this.eventSelectionClickHandler = null;
1062
+ }
1063
+ if (enabled) {
1064
+ this.eventSelectionClickHandler = (e) => {
1065
+ const target = e.target;
1066
+ if (!target) return;
1067
+ const selector = this.generateSelectorForElement(target);
1068
+ const tagName = target.tagName.toLowerCase();
1069
+ const text = target.textContent?.trim().substring(0, 50) || "";
1070
+ if (window.parent && window.parent !== window) {
1071
+ window.parent.postMessage({
1072
+ type: "ELEMENT_CLICKED_FOR_EVENT",
1073
+ selector,
1074
+ tagName,
1075
+ text
1076
+ }, "*");
1077
+ }
1078
+ if (tagName === "a") {
1079
+ e.preventDefault();
1080
+ }
1081
+ };
1082
+ document.addEventListener("click", this.eventSelectionClickHandler, true);
1083
+ if (this.config?.debug) {
1084
+ console.log("[AmplifyUp SDK] Event selection mode enabled - clicks will be captured");
1085
+ }
1086
+ } else {
1087
+ if (this.config?.debug) {
1088
+ console.log("[AmplifyUp SDK] Event selection mode disabled");
1089
+ }
1090
+ }
1091
+ }
1092
+ /**
1093
+ * Generate a CSS selector for an element
1094
+ */
1095
+ generateSelectorForElement(el) {
1096
+ if (el.id) {
1097
+ return "#" + el.id;
1098
+ }
1099
+ const dataAttrs = Array.from(el.attributes).filter((a) => a.name.startsWith("data-"));
1100
+ if (dataAttrs.length > 0) {
1101
+ const attr = dataAttrs[0];
1102
+ return "[" + attr.name + '="' + attr.value + '"]';
1103
+ }
1104
+ if (el.className && typeof el.className === "string") {
1105
+ const classes = el.className.split(" ").filter(
1106
+ (c) => c && !c.startsWith("has-") && !c.includes("selectable") && !c.includes("selected")
1107
+ );
1108
+ if (classes.length > 0) {
1109
+ return el.tagName.toLowerCase() + "." + classes[0];
1110
+ }
1111
+ }
1112
+ if (el.type) {
1113
+ return el.tagName.toLowerCase() + '[type="' + el.type + '"]';
1114
+ }
1115
+ if (el.name) {
1116
+ return el.tagName.toLowerCase() + '[name="' + el.name + '"]';
1117
+ }
1118
+ return el.tagName.toLowerCase();
1119
+ }
1120
+ /**
1121
+ * Enable component highlighting
1122
+ */
1123
+ enableHighlighting(componentRegistry, highlightComponents, showZones) {
1124
+ if (typeof document === "undefined") return;
1125
+ this.componentRegistry = componentRegistry;
1126
+ this.highlightingEnabled = true;
1127
+ this.disableHighlighting();
1128
+ if (highlightComponents) {
1129
+ this.applyComponentHighlights();
1130
+ this.setupMutationObserver();
1131
+ }
1132
+ }
1133
+ /**
1134
+ * Set up MutationObserver to watch for new components being added
1135
+ */
1136
+ setupMutationObserver() {
1137
+ if (typeof document === "undefined" || !window.MutationObserver) return;
1138
+ if (this.mutationObserver) {
1139
+ this.mutationObserver.disconnect();
1140
+ this.mutationObserver = null;
1141
+ }
1142
+ this.mutationObserver = new MutationObserver((mutations) => {
1143
+ let shouldReapply = false;
1144
+ mutations.forEach((mutation) => {
1145
+ mutation.addedNodes.forEach((node) => {
1146
+ if (node.nodeType === Node.ELEMENT_NODE) {
1147
+ const el = node;
1148
+ if (el.hasAttribute("data-amplifyup-component") || el.hasAttribute("data-component-id") || el.hasAttribute("data-amplifyup-slot") || el.querySelector("[data-amplifyup-component], [data-component-id], [data-amplifyup-slot]")) {
1149
+ shouldReapply = true;
1150
+ }
1151
+ }
1152
+ });
1153
+ if (mutation.type === "attributes") {
1154
+ const target = mutation.target;
1155
+ if (target.hasAttribute("data-amplifyup-slot") || target.hasAttribute("data-slot-empty")) {
1156
+ shouldReapply = true;
1157
+ }
1158
+ }
1159
+ });
1160
+ if (shouldReapply && this.highlightingEnabled) {
1161
+ setTimeout(() => {
1162
+ if (this.highlightingEnabled) {
1163
+ this.applyComponentHighlights();
1164
+ }
1165
+ }, 100);
1166
+ }
1167
+ });
1168
+ this.mutationObserver.observe(document.body, {
1169
+ childList: true,
1170
+ subtree: true,
1171
+ attributes: true,
1172
+ attributeFilter: ["data-amplifyup-component", "data-component-id", "data-amplifyup-slot", "data-slot-empty"]
1173
+ });
1174
+ }
1175
+ /**
1176
+ * Disable component highlighting
1177
+ */
1178
+ disableHighlighting() {
1179
+ if (typeof document === "undefined") return;
1180
+ this.highlightingEnabled = false;
1181
+ if (this.mutationObserver) {
1182
+ this.mutationObserver.disconnect();
1183
+ this.mutationObserver = null;
1184
+ }
1185
+ document.querySelectorAll(".amplifyup-component-highlight").forEach((el) => {
1186
+ const htmlEl = el;
1187
+ const handlers = htmlEl._amplifyupHandlers;
1188
+ if (handlers?.handleClick) {
1189
+ htmlEl.removeEventListener("click", handlers.handleClick);
1190
+ }
1191
+ delete htmlEl._amplifyupHandlers;
1192
+ htmlEl.classList.remove("amplifyup-component-highlight");
1193
+ });
1194
+ document.querySelectorAll(".amplifyup-slot-highlight").forEach((el) => {
1195
+ const htmlEl = el;
1196
+ const handlers = htmlEl._amplifyupSlotHandlers;
1197
+ if (handlers) {
1198
+ if (handlers.handleClick) htmlEl.removeEventListener("click", handlers.handleClick);
1199
+ if (handlers.handleDragOver) htmlEl.removeEventListener("dragover", handlers.handleDragOver);
1200
+ if (handlers.handleDrop) htmlEl.removeEventListener("drop", handlers.handleDrop);
1201
+ }
1202
+ delete htmlEl._amplifyupSlotHandlers;
1203
+ htmlEl.classList.remove("amplifyup-slot-highlight");
1204
+ });
1205
+ }
1206
+ /**
1207
+ * Build component hierarchy for ancestor selection
1208
+ */
1209
+ buildComponentHierarchy(element) {
1210
+ const hierarchy = [];
1211
+ let current = element;
1212
+ while (current) {
1213
+ if (current.hasAttribute("data-amplifyup-component") || current.hasAttribute("data-component-id") || current.hasAttribute("data-amplifyup-slot")) {
1214
+ hierarchy.push(current);
1215
+ }
1216
+ current = current.parentElement;
1217
+ }
1218
+ return hierarchy.reverse();
1219
+ }
1220
+ /**
1221
+ * Send selection message to orchestrator (includes element bounds for overlay positioning).
1222
+ */
1223
+ sendSelectionMessage(element, hierarchy, isEmpty) {
1224
+ if (!this.isVisualEditorMode) return;
1225
+ const componentId = element.getAttribute("data-amplifyup-component") || element.getAttribute("data-component-id");
1226
+ const slotName = element.getAttribute("data-amplifyup-slot");
1227
+ const componentName = element.getAttribute("data-component-name");
1228
+ const hierarchyInfo = hierarchy.map((el, index) => {
1229
+ const elComponentId = el.getAttribute("data-amplifyup-component") || el.getAttribute("data-component-id");
1230
+ const elSlotName = el.getAttribute("data-amplifyup-slot");
1231
+ const elComponentName = el.getAttribute("data-component-name");
1232
+ return {
1233
+ index,
1234
+ componentId: elComponentId,
1235
+ componentName: elComponentName,
1236
+ slotName: elSlotName,
1237
+ isSlot: !!elSlotName
1238
+ };
1239
+ });
1240
+ const rect = element.getBoundingClientRect ? element.getBoundingClientRect() : null;
1241
+ const bounds = rect ? { top: rect.top, left: rect.left, width: rect.width, height: rect.height } : void 0;
1242
+ const message = {
1243
+ type: "COMPONENT_SELECTED",
1244
+ componentId,
1245
+ componentName,
1246
+ slotName,
1247
+ hierarchy: hierarchyInfo,
1248
+ selectedIndex: hierarchy.length - 1,
1249
+ ...bounds && { bounds },
1250
+ ...isEmpty !== void 0 && { isEmpty }
1251
+ };
1252
+ if (window.parent && window.parent !== window) {
1253
+ window.parent.postMessage(message, "*");
1254
+ console.log("[AmplifyUp SDK] Sent selection message:", message);
1255
+ }
1256
+ }
1257
+ /**
1258
+ * Send component tree to orchestrator
1259
+ * Note: Component tree is now sent from AmplifyRenderer based on layoutTree from pageConfig
1260
+ * This method is kept for backwards compatibility but is no longer used
1261
+ */
1262
+ sendComponentTree() {
1263
+ console.log("[AmplifyUp SDK] sendComponentTree called but component tree is now sent from AmplifyRenderer");
1264
+ }
1265
+ /**
1266
+ * Apply component highlights
1267
+ */
1268
+ applyComponentHighlights() {
1269
+ if (typeof document === "undefined") return;
1270
+ if (!this.isVisualEditorMode) {
1271
+ return;
1272
+ }
1273
+ const doc = document;
1274
+ const win = window;
1275
+ const componentElements = doc.querySelectorAll("[data-amplifyup-component], [data-component-id]");
1276
+ console.log("[AmplifyUp SDK] Found", componentElements.length, "components to highlight");
1277
+ this.sendComponentTree();
1278
+ const slotElements = doc.querySelectorAll("[data-amplifyup-slot]");
1279
+ console.log("[AmplifyUp SDK] Found", slotElements.length, "slots to highlight");
1280
+ componentElements.forEach((el) => {
1281
+ const htmlEl = el;
1282
+ const componentId = htmlEl.getAttribute("data-amplifyup-component") || htmlEl.getAttribute("data-component-id");
1283
+ if (!componentId) return;
1284
+ if (htmlEl.classList.contains("amplifyup-component-highlight")) return;
1285
+ const component = this.componentRegistry.find((c) => c.component_id === componentId);
1286
+ htmlEl.classList.add("amplifyup-component-highlight");
1287
+ htmlEl.setAttribute("data-component-id", componentId);
1288
+ htmlEl.setAttribute("data-component-name", component?.component_name || componentId);
1289
+ const hierarchy = this.buildComponentHierarchy(htmlEl);
1290
+ const handleClick = (e) => {
1291
+ e.stopPropagation();
1292
+ this.sendSelectionMessage(htmlEl, hierarchy);
1293
+ if (window.parent && window.parent !== window) {
1294
+ window.parent.postMessage({ type: "CHECK_COMPONENT_DELETABLE", componentId }, "*");
1295
+ }
1296
+ };
1297
+ htmlEl.addEventListener("click", handleClick);
1298
+ htmlEl._amplifyupHandlers = { handleClick };
1299
+ });
1300
+ this.componentRegistry.forEach((component) => {
1301
+ if (!component.data_attribute) return;
1302
+ const elements = doc.querySelectorAll(`[${component.data_attribute}]`);
1303
+ elements.forEach((el) => {
1304
+ const htmlEl = el;
1305
+ if (htmlEl.classList.contains("amplifyup-component-highlight")) return;
1306
+ htmlEl.classList.add("amplifyup-component-highlight");
1307
+ htmlEl.setAttribute("data-component-id", component.component_id);
1308
+ htmlEl.setAttribute("data-component-name", component.component_name);
1309
+ const hierarchy = this.buildComponentHierarchy(htmlEl);
1310
+ const handleClick = (e) => {
1311
+ e.stopPropagation();
1312
+ this.sendSelectionMessage(htmlEl, hierarchy);
1313
+ if (window.parent && window.parent !== window) {
1314
+ window.parent.postMessage({ type: "CHECK_COMPONENT_DELETABLE", componentId: component.component_id }, "*");
1315
+ }
1316
+ };
1317
+ htmlEl.addEventListener("click", handleClick);
1318
+ htmlEl._amplifyupHandlers = { handleClick };
1319
+ });
1320
+ });
1321
+ slotElements.forEach((el) => {
1322
+ const htmlEl = el;
1323
+ const slotName = htmlEl.getAttribute("data-amplifyup-slot");
1324
+ const isEmpty = htmlEl.getAttribute("data-slot-empty") === "true";
1325
+ if (!slotName) return;
1326
+ if (htmlEl.classList.contains("amplifyup-slot-highlight")) return;
1327
+ htmlEl.classList.add("amplifyup-slot-highlight");
1328
+ const hierarchy = this.buildComponentHierarchy(htmlEl);
1329
+ const handleClick = (e) => {
1330
+ e.stopPropagation();
1331
+ this.sendSelectionMessage(htmlEl, hierarchy, isEmpty);
1332
+ };
1333
+ const handleDrop = (e) => {
1334
+ e.preventDefault();
1335
+ e.stopPropagation();
1336
+ try {
1337
+ const data = JSON.parse(e.dataTransfer.getData("application/json"));
1338
+ if (data.type === "component" && win.parent && win.parent !== win) {
1339
+ win.parent.postMessage({
1340
+ type: "COMPONENT_DROPPED",
1341
+ componentId: data.componentId,
1342
+ componentName: data.componentName,
1343
+ slotName,
1344
+ slotElement: { path: htmlEl.getAttribute("data-slot-path"), isEmpty }
1345
+ }, "*");
1346
+ }
1347
+ } catch (_err) {
1348
+ }
1349
+ };
1350
+ const handleDragOver = (e) => {
1351
+ e.preventDefault();
1352
+ e.stopPropagation();
1353
+ e.dataTransfer.dropEffect = "copy";
1354
+ };
1355
+ htmlEl.addEventListener("click", handleClick);
1356
+ htmlEl.addEventListener("dragover", handleDragOver);
1357
+ htmlEl.addEventListener("drop", handleDrop);
1358
+ htmlEl._amplifyupSlotHandlers = { handleClick, handleDragOver, handleDrop };
1359
+ });
1360
+ }
1361
+ /**
1362
+ * Cleanup: Remove message listener and observers
1363
+ */
1364
+ cleanup() {
1365
+ if (this.messageListener) {
1366
+ window.removeEventListener("message", this.messageListener);
1367
+ this.messageListener = null;
1368
+ }
1369
+ this.disableHighlighting();
1370
+ }
1371
+ };
1372
+ var sdkInstance = null;
1373
+ function getSDK(adapter) {
1374
+ if (!sdkInstance) {
1375
+ sdkInstance = new AmplifyUpSDK(adapter);
1376
+ }
1377
+ return sdkInstance;
1378
+ }
1379
+ async function init(config) {
1380
+ const sdk = getSDK();
1381
+ await sdk.init(config);
1382
+ }
1383
+ var page = (url, properties) => getSDK().page(url, properties);
1384
+ var track = (eventName, properties) => getSDK().track(eventName, properties);
1385
+ var trackClick = (elementId, elementText, properties) => getSDK().trackClick(elementId, elementText, properties);
1386
+ var trackFormSubmit = (formId, formData) => getSDK().trackFormSubmit(formId, formData);
1387
+ var trackFormFieldInteraction = (fieldName, fieldValue) => getSDK().trackFormFieldInteraction(fieldName, fieldValue);
1388
+ var trackContentView = (contentId, contentType, properties) => getSDK().trackContentView(contentId, contentType, properties);
1389
+ var identify = (userId, traits) => getSDK().identify(userId, traits);
1390
+ var trackContentEngagement = (contentId, engagementType) => getSDK().trackContentEngagement(contentId, engagementType);
1391
+ var reset = () => getSDK().reset();
1392
+ var getInstanceId2 = () => getSDK().getInstanceId();
1393
+ var getUserId2 = () => getSDK().getUserId();
1394
+ var getTrackingId = () => getSDK().getTrackingId();
1395
+ var getOrchestratorUrl = () => getSDK().getOrchestratorUrl();
1396
+ var buildLayoutProviderUrl = (route, preview) => getSDK().buildLayoutProviderUrl(route, preview);
1397
+ var buildPageRenderUrl = (route, preview) => getSDK().buildLayoutProviderUrl(route, preview);
1398
+ var fetchPageConfig = (route, preview) => getSDK().fetchPageConfig(route, preview);
1399
+ var setupEventTracking = (config) => getSDK().setupEventTracking(config);
1400
+ var cleanupEventTracking = () => getSDK().cleanupEventTracking();
1401
+ var refreshEventTracking = () => getSDK().refreshEventTracking();
1402
+ var getDiagnostics = () => getSDK().getDiagnostics();
1403
+ var getStatus = () => {
1404
+ const status = getSDK().getStatus();
1405
+ console.log(status);
1406
+ return getSDK().getDiagnostics();
1407
+ };
1408
+ var testTracking = () => getSDK().testTracking();
1409
+ var verifyAWSConnection = () => {
1410
+ const result = getSDK().verifyAWSConnection();
1411
+ console.log("AWS Connection Verification:", result.message);
1412
+ console.log("Full details:", result);
1413
+ return result;
1414
+ };
1415
+ var index_default = getSDK();
1416
+
1417
+ exports.AmplifyUpSDK = AmplifyUpSDK;
1418
+ exports.buildLayoutProviderUrl = buildLayoutProviderUrl;
1419
+ exports.buildPageRenderUrl = buildPageRenderUrl;
1420
+ exports.cleanupEventTracking = cleanupEventTracking;
1421
+ exports.default = index_default;
1422
+ exports.fetchPageConfig = fetchPageConfig;
1423
+ exports.getDiagnostics = getDiagnostics;
1424
+ exports.getInstanceId = getInstanceId2;
1425
+ exports.getOrchestratorUrl = getOrchestratorUrl;
1426
+ exports.getSDK = getSDK;
1427
+ exports.getStatus = getStatus;
1428
+ exports.getTrackingId = getTrackingId;
1429
+ exports.getUserId = getUserId2;
1430
+ exports.identify = identify;
1431
+ exports.init = init;
1432
+ exports.page = page;
1433
+ exports.refreshEventTracking = refreshEventTracking;
1434
+ exports.reset = reset;
1435
+ exports.setupEventTracking = setupEventTracking;
1436
+ exports.testTracking = testTracking;
1437
+ exports.track = track;
1438
+ exports.trackClick = trackClick;
1439
+ exports.trackContentEngagement = trackContentEngagement;
1440
+ exports.trackContentView = trackContentView;
1441
+ exports.trackFormFieldInteraction = trackFormFieldInteraction;
1442
+ exports.trackFormSubmit = trackFormSubmit;
1443
+ exports.verifyAWSConnection = verifyAWSConnection;
1444
+ //# sourceMappingURL=index.js.map
1445
+ //# sourceMappingURL=index.js.map