@amplifyup/sdk 0.1.1 → 0.1.3

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