@amplifyup/sdk 0.1.54 → 0.1.55

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/react.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
- import React, { createContext, useState, useEffect, useContext, Fragment as Fragment$1, useSyncExternalStore, useRef, Component } from 'react';
2
+ import React, { createContext, memo, useState, useEffect, useContext, Fragment as Fragment$1, Component, useRef, useSyncExternalStore } from 'react';
3
3
  import { marked } from 'marked';
4
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
 
6
6
  /* @amplifyup/sdk - https://amplifyup.ai */
7
7
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -608,6 +608,49 @@ function getPageResourceFields() {
608
608
  return pageResourceFields;
609
609
  }
610
610
 
611
+ // src/debug.ts
612
+ function envFlag(value) {
613
+ if (!value) return false;
614
+ const v = value.trim().toLowerCase();
615
+ return v === "1" || v === "true" || v === "yes";
616
+ }
617
+ function readAmplifyUpDebugEnv() {
618
+ try {
619
+ if (typeof process === "undefined") return false;
620
+ return envFlag(process.env.NEXT_PUBLIC_AMPLIFYUP_DEBUG) || envFlag(process.env.AMPLIFYUP_DEBUG);
621
+ } catch {
622
+ return false;
623
+ }
624
+ }
625
+ var configDebug;
626
+ function setAmplifyUpDebug(enabled) {
627
+ configDebug = enabled;
628
+ }
629
+ function isAmplifyUpDebug() {
630
+ if (configDebug === true) return true;
631
+ if (configDebug === false) return false;
632
+ return readAmplifyUpDebugEnv();
633
+ }
634
+ var onceKeys = /* @__PURE__ */ new Set();
635
+ var onceRoute = "";
636
+ function resetOnceIfRouteChanged() {
637
+ const route = typeof window !== "undefined" ? window.location.pathname : "";
638
+ if (route === onceRoute) return;
639
+ onceKeys.clear();
640
+ onceRoute = route;
641
+ }
642
+ function sdkDebug(...args) {
643
+ if (!isAmplifyUpDebug()) return;
644
+ console.log(...args);
645
+ }
646
+ function sdkDebugOnce(key, ...args) {
647
+ if (!isAmplifyUpDebug()) return;
648
+ resetOnceIfRouteChanged();
649
+ if (onceKeys.has(key)) return;
650
+ onceKeys.add(key);
651
+ console.log(...args);
652
+ }
653
+
611
654
  // src/edge/normalizeRoute.ts
612
655
  function normalizeRoute(route) {
613
656
  let path = String(route || "").trim();
@@ -1181,13 +1224,13 @@ var AmplifyUpSDK = class {
1181
1224
  }
1182
1225
  this.config = {
1183
1226
  trackingId: previewOverrides.trackingId || config.trackingId,
1184
- debug: config.debug ?? true,
1185
- // Enable debug by default
1227
+ debug: config.debug ?? readAmplifyUpDebugEnv(),
1186
1228
  target: this.target,
1187
1229
  dev: config.dev,
1188
1230
  ...config.siteId ? { siteId: config.siteId } : {},
1189
1231
  ...config.pageContext ? { pageContext: config.pageContext } : {}
1190
1232
  };
1233
+ setAmplifyUpDebug(!!this.config.debug);
1191
1234
  if (config.pageContext) {
1192
1235
  this.pendingPageContext = config.pageContext;
1193
1236
  this.recomputeAttachedContext();
@@ -3519,23 +3562,12 @@ function Slot({
3519
3562
  className
3520
3563
  }) {
3521
3564
  const context = useContext(ComponentContext);
3522
- console.log(`[Slot:${name}] Rendering slot`, {
3523
- hasContext: !!context,
3524
- availableSlotKeys: context?.slots ? Object.keys(context.slots) : [],
3525
- slotContent: context?.slots?.[name] ? "EXISTS" : "MISSING",
3526
- contextSlots: context?.slots
3527
- });
3528
3565
  if (!context) {
3529
3566
  console.warn(`[AmplifyUp SDK] Slot "${name}" used outside ComponentContextProvider`);
3530
3567
  return null;
3531
3568
  }
3532
3569
  const slotContent = context.slots?.[name];
3533
3570
  const isEmpty = !slotContent;
3534
- console.log(`[Slot:${name}] Slot state`, {
3535
- isEmpty,
3536
- hasSlotContent: !!slotContent,
3537
- slotContentType: slotContent ? typeof slotContent : "null"
3538
- });
3539
3571
  const isEditorMode = typeof window !== "undefined" && // Check for preview mode flag set by proxy
3540
3572
  (window.__AMPLIFYUP_PREVIEW_MODE__ === true || // Check URL query params
3541
3573
  new URLSearchParams(window.location.search).get("preview") === "true" || new URLSearchParams(window.location.search).get("visualEditor") === "true" || // Check if in iframe from orchestrator (check referrer hostname/port)
@@ -3547,17 +3579,15 @@ function Slot({
3547
3579
  return false;
3548
3580
  }
3549
3581
  })());
3550
- console.log(`[Slot:${name}] Editor mode detection`, {
3551
- isEditorMode,
3552
- isWindowDefined: typeof window !== "undefined",
3553
- previewModeFlag: typeof window !== "undefined" ? window.__AMPLIFYUP_PREVIEW_MODE__ : void 0,
3554
- urlParams: typeof window !== "undefined" ? {
3555
- preview: new URLSearchParams(window.location.search).get("preview"),
3556
- visualEditor: new URLSearchParams(window.location.search).get("visualEditor")
3557
- } : void 0,
3558
- inIframe: typeof window !== "undefined" ? window.self !== window.top : false,
3559
- referrer: typeof window !== "undefined" && document.referrer ? document.referrer : void 0
3560
- });
3582
+ sdkDebugOnce(
3583
+ `slot:${context.layoutNodeId || ""}:${name}`,
3584
+ `[Slot:${name}]`,
3585
+ {
3586
+ isEmpty,
3587
+ isEditorMode,
3588
+ availableSlotKeys: context.slots ? Object.keys(context.slots) : []
3589
+ }
3590
+ );
3561
3591
  return /* @__PURE__ */ jsx(
3562
3592
  "div",
3563
3593
  {
@@ -4198,7 +4228,7 @@ function LiveNodeRender({
4198
4228
  layoutNodeId: nodeId
4199
4229
  }) });
4200
4230
  }
4201
- function AmplifyRenderer({
4231
+ function AmplifyRendererInner({
4202
4232
  renderComponent,
4203
4233
  pageConfig: serverPageConfig,
4204
4234
  loadingComponent,
@@ -4340,14 +4370,22 @@ function AmplifyRenderer({
4340
4370
  return `${indent}- ${n.id} (${n.componentId || "?"})${slotsDesc ? "\n" + slotsDesc : ""}`;
4341
4371
  }).join("\n");
4342
4372
  };
4343
- console.log("[AmplifyRenderer] layoutTree received:\n%s", describeLayoutTree(layoutTree2));
4373
+ sdkDebugOnce(
4374
+ `layoutTree:${pageConfig?.id || ""}:${pageConfig?.route || ""}`,
4375
+ "[AmplifyRenderer] layoutTree received:\n%s",
4376
+ describeLayoutTree(layoutTree2)
4377
+ );
4344
4378
  if (typeof window !== "undefined" && window.parent && window.parent !== window) {
4345
4379
  const message = {
4346
4380
  type: "COMPONENT_TREE",
4347
4381
  tree: componentTree
4348
4382
  };
4349
4383
  window.parent.postMessage(message, "*");
4350
- console.log("[AmplifyRenderer] Sent component tree from layoutTree:", componentTree.length, "root components");
4384
+ sdkDebug(
4385
+ "[AmplifyRenderer] Sent component tree from layoutTree:",
4386
+ componentTree.length,
4387
+ "root components"
4388
+ );
4351
4389
  }
4352
4390
  }, [pageConfig]);
4353
4391
  useEffect(() => {
@@ -4498,7 +4536,7 @@ function AmplifyRenderer({
4498
4536
  );
4499
4537
  }
4500
4538
  let slotChildren = {};
4501
- console.log(`[AmplifyRenderer] Rendering node ${node.id} (${node.componentId})`, {
4539
+ sdkDebugOnce(`node:${node.id}`, `[AmplifyRenderer] Rendering node ${node.id} (${node.componentId})`, {
4502
4540
  hasSlots: !!(node.slots && node.slots.length > 0),
4503
4541
  slotCount: node.slots?.length || 0,
4504
4542
  slots: node.slots?.map((s) => ({ slotId: s.slotId, zoneId: s.zoneId, childrenCount: s.children?.length || 0 }))
@@ -4507,30 +4545,13 @@ function AmplifyRenderer({
4507
4545
  for (const slot of node.slots) {
4508
4546
  const slotKey = `${node.id}-${slot.slotId}`;
4509
4547
  let childrenToRender = [];
4510
- console.log(`[AmplifyRenderer] Processing slot ${slot.slotId} for node ${node.id}`, {
4511
- slotKey,
4512
- hasZoneId: !!slot.zoneId,
4513
- hasVariants: !!slot.variants,
4514
- hasVariantCache: !!variantCache[slotKey],
4515
- directChildrenCount: slot.children?.length || 0
4516
- });
4517
4548
  if (slot.zoneId && slot.variants && variantCache[slotKey]) {
4518
4549
  childrenToRender = variantCache[slotKey].children;
4519
- console.log(`[AmplifyRenderer] Using cached variant for slot ${slot.slotId}`, {
4520
- variantId: variantCache[slotKey].variantId,
4521
- childrenCount: childrenToRender.length
4522
- });
4523
4550
  } else if (slot.zoneId && slot.variants) {
4524
4551
  const defaultVariant = slot.variants.find((v) => v.isDefault);
4525
4552
  childrenToRender = defaultVariant?.children || [];
4526
- console.log(`[AmplifyRenderer] Using default variant for slot ${slot.slotId}`, {
4527
- childrenCount: childrenToRender.length
4528
- });
4529
4553
  } else {
4530
4554
  childrenToRender = Array.isArray(slot.children) ? slot.children : [];
4531
- console.log(`[AmplifyRenderer] Using direct children for slot ${slot.slotId}`, {
4532
- childrenCount: childrenToRender.length
4533
- });
4534
4555
  }
4535
4556
  const safeChildren = Array.isArray(childrenToRender) ? childrenToRender : [];
4536
4557
  slotChildren[slot.slotId] = /* @__PURE__ */ jsx(
@@ -4545,10 +4566,6 @@ function AmplifyRenderer({
4545
4566
  },
4546
4567
  slot.slotId
4547
4568
  );
4548
- console.log(`[AmplifyRenderer] Created slot content for ${slot.slotId}`, {
4549
- slotId: slot.slotId,
4550
- renderedChildrenCount: childrenToRender.length
4551
- });
4552
4569
  }
4553
4570
  }
4554
4571
  const slotsToPass = Object.keys(slotChildren).length > 0 ? slotChildren : void 0;
@@ -4586,6 +4603,7 @@ function AmplifyRenderer({
4586
4603
  }
4587
4604
  ) : layoutTree.map((node) => /* @__PURE__ */ jsx("div", { children: renderNode(node) }, node.id)) });
4588
4605
  }
4606
+ var AmplifyRenderer = memo(AmplifyRendererInner);
4589
4607
  function defaultPreviewCanvas() {
4590
4608
  return /* @__PURE__ */ jsx(
4591
4609
  "div",
@@ -4689,6 +4707,12 @@ if (typeof window !== "undefined") {
4689
4707
  }
4690
4708
  }
4691
4709
  var AmplifyUpContext = createContext(null);
4710
+ function normalizeRoutePath2(route) {
4711
+ if (!route) return "";
4712
+ const path = route.split("?")[0] || "/";
4713
+ if (path.length > 1 && path.endsWith("/")) return path.replace(/\/+$/, "");
4714
+ return path || "/";
4715
+ }
4692
4716
  function AmplifyUpProvider({
4693
4717
  children,
4694
4718
  config,
@@ -4716,6 +4740,7 @@ function AmplifyUpProvider({
4716
4740
  }
4717
4741
  return currentPath;
4718
4742
  };
4743
+ const loadedRouteRef = useRef(null);
4719
4744
  const nextPathname = usePathname ? usePathname() : null;
4720
4745
  const [pathname, setPathname] = useState(() => {
4721
4746
  if (typeof window !== "undefined") {
@@ -4749,56 +4774,46 @@ function AmplifyUpProvider({
4749
4774
  };
4750
4775
  }
4751
4776
  }, [nextPathname]);
4752
- useEffect(() => {
4753
- let cancelled = false;
4754
- const sdk = getSDK();
4755
- sdk.init({
4756
- ...config,
4757
- ...pageContext ? { pageContext } : {}
4758
- }).then(() => {
4759
- if (!cancelled) {
4760
- setInitialized(true);
4761
- }
4762
- }).catch((err) => {
4763
- if (cancelled) return;
4764
- console.error("Failed to initialize AmplifyUp SDK:", err);
4765
- setError("Failed to initialize tracking");
4766
- setLoading(false);
4767
- });
4768
- return () => {
4769
- cancelled = true;
4770
- };
4771
- }, [config.trackingId, config.target, config.debug, config.dev, config.siteId, pageContext]);
4777
+ const pageContextKey = pageContext ? `${pageContext.resourceType}:${pageContext.key}` : "";
4772
4778
  useEffect(() => {
4773
4779
  if (!initialized || !pageContext) return;
4774
4780
  getSDK().setPageContext(pageContext);
4775
- }, [initialized, pageContext]);
4781
+ }, [initialized, pageContextKey]);
4776
4782
  useEffect(() => {
4777
- if (!initialized) return;
4778
4783
  let cancelled = false;
4779
- const load = async () => {
4784
+ const sdk = getSDK();
4785
+ const run = async () => {
4780
4786
  try {
4787
+ await sdk.init({
4788
+ ...config,
4789
+ ...pageContext ? { pageContext } : {}
4790
+ });
4791
+ if (cancelled) return;
4792
+ if (pageContext) sdk.setPageContext(pageContext);
4781
4793
  const actualRoute = getActualRoute();
4782
4794
  if (!actualRoute) {
4795
+ setInitialized(true);
4783
4796
  setLoading(false);
4784
4797
  return;
4785
4798
  }
4786
- const sdk = getSDK();
4787
4799
  sdk.routeChange(actualRoute);
4788
4800
  const preview = isComposerPreview();
4789
4801
  const overlay = preview || config.clientPersonalization !== false;
4790
4802
  if (!overlay) {
4803
+ setInitialized(true);
4791
4804
  setPageConfig(null);
4792
4805
  setLoading(false);
4793
4806
  return;
4794
4807
  }
4795
- setPageConfig(null);
4796
- setError(null);
4797
- setLoading(false);
4808
+ if (loadedRouteRef.current && loadedRouteRef.current !== actualRoute) {
4809
+ setPageConfig(null);
4810
+ setError(null);
4811
+ }
4798
4812
  const edgeUrl = sdk.getEdgeUrl();
4799
4813
  const orchestratorUrl = sdk.getOrchestratorUrl();
4800
4814
  const trackingId = sdk.getTrackingId();
4801
4815
  if (!trackingId || !orchestratorUrl || !edgeUrl) {
4816
+ setInitialized(true);
4802
4817
  setError("SDK not initialized");
4803
4818
  setLoading(false);
4804
4819
  return;
@@ -4834,28 +4849,37 @@ function AmplifyUpProvider({
4834
4849
  fetchOrchestratorPage: (route, isPreview) => sdk.fetchPageConfig(route, isPreview)
4835
4850
  });
4836
4851
  if (cancelled) return;
4837
- setSource(result.source);
4838
- setMeta(result.meta);
4839
- setError(result.error);
4840
- if (!result.pageConfig) {
4841
- setPageConfig({
4842
- id: "default",
4843
- route: actualRoute,
4844
- title: "Page Not Configured",
4845
- description: "This page has not been published yet.",
4846
- layoutTree: []
4847
- });
4848
- } else {
4849
- setPageConfig(result.pageConfig);
4852
+ const nextConfig = result.pageConfig || {
4853
+ id: "default",
4854
+ route: actualRoute,
4855
+ title: "Page Not Configured",
4856
+ description: "This page has not been published yet.",
4857
+ layoutTree: []
4858
+ };
4859
+ setInitialized(true);
4860
+ setSource((prev) => prev === result.source ? prev : result.source);
4861
+ setMeta(
4862
+ (prev) => prev === result.meta || JSON.stringify(prev) === JSON.stringify(result.meta) ? prev : result.meta
4863
+ );
4864
+ setError((prev) => prev === result.error ? prev : result.error);
4865
+ setPageConfig((prev) => {
4866
+ if (prev && prev.id === nextConfig.id && normalizeRoutePath2(prev.route) === normalizeRoutePath2(nextConfig.route) && JSON.stringify(prev.layoutTree) === JSON.stringify(nextConfig.layoutTree)) {
4867
+ return prev;
4868
+ }
4869
+ return nextConfig;
4870
+ });
4871
+ if (result.pageConfig) {
4850
4872
  sdk.applyResolvedPageData(
4851
4873
  result.pageConfig.pageData || null,
4852
4874
  result.pageConfig.route,
4853
4875
  extractRouteParams(result.pageConfig.route, actualRoute)
4854
4876
  );
4855
4877
  }
4878
+ loadedRouteRef.current = actualRoute;
4856
4879
  } catch (err) {
4857
4880
  if (cancelled) return;
4858
4881
  console.error("Error fetching page config:", err);
4882
+ setInitialized(true);
4859
4883
  setError(err instanceof Error ? err.message : "Unknown error");
4860
4884
  setSource(null);
4861
4885
  setMeta(null);
@@ -4863,11 +4887,20 @@ function AmplifyUpProvider({
4863
4887
  if (!cancelled) setLoading(false);
4864
4888
  }
4865
4889
  };
4866
- void load();
4890
+ void run();
4867
4891
  return () => {
4868
4892
  cancelled = true;
4869
4893
  };
4870
- }, [pathname, initialized, config.clientPersonalization]);
4894
+ }, [
4895
+ pathname,
4896
+ config.trackingId,
4897
+ config.target,
4898
+ config.debug,
4899
+ config.dev,
4900
+ config.siteId,
4901
+ config.clientPersonalization,
4902
+ pageContextKey
4903
+ ]);
4871
4904
  return /* @__PURE__ */ jsx(
4872
4905
  AmplifyUpContext.Provider,
4873
4906
  {