@rebuy/hydrogen-sdk
Version:
The React/Hydrogen wrapper for the Rebuy Core SDK.
198 lines (194 loc) • 6.34 kB
JavaScript
// src/context.tsx
import { RebuySDK } from "@rebuy/core-sdk";
import { createContext, useContext, useMemo } from "react";
import { jsx } from "react/jsx-runtime";
var RebuyContext = createContext(null);
var RebuyProvider = ({
apiHost,
apiKey,
children,
nonce
}) => {
const sdk = useMemo(() => new RebuySDK({ apiHost, apiKey }), [apiKey, apiHost]);
return /* @__PURE__ */ jsx(RebuyContext.Provider, { value: sdk, children });
};
var useRebuy = () => {
const context = useContext(RebuyContext);
if (!context) {
throw new Error("useRebuy must be used within a RebuyProvider");
}
return context;
};
// src/components/RecentlyViewed.tsx
import { useEffect, useState } from "react";
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var RecentlyViewed = ({
className,
emptyComponent,
limit = 5,
loadingComponent,
onError
}) => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const rebuy = useRebuy();
useEffect(() => {
const fetchRecentlyViewed = async () => {
try {
setLoading(true);
setError(null);
const data = await rebuy.products.getRecentlyViewed({ limit });
setProducts(data || []);
} catch (err) {
const error2 = err instanceof Error ? err : new Error(String(err));
setError(error2);
onError?.(error2);
console.error("Failed to fetch recently viewed products:", error2);
} finally {
setLoading(false);
}
};
fetchRecentlyViewed();
}, [limit, rebuy, onError]);
if (loading) {
return loadingComponent || /* @__PURE__ */ jsx2("div", { className, children: /* @__PURE__ */ jsx2("div", { children: "Loading recently viewed products..." }) });
}
if (error) {
return null;
}
if (products.length === 0) {
return emptyComponent || null;
}
return /* @__PURE__ */ jsxs("div", { className, children: [
/* @__PURE__ */ jsx2("h2", { children: "Recently Viewed" }),
/* @__PURE__ */ jsx2("ul", { children: products.map((product) => /* @__PURE__ */ jsx2("li", { children: product.title }, product.id)) })
] });
};
// src/components/RebuyProductView.tsx
import { useEffect as useEffect2, useRef } from "react";
var RebuyProductView = ({ customerId, product, rebuy: customRebuy }) => {
const tracked = useRef(false);
const rebuyFromContext = useRebuy();
useEffect2(() => {
if (tracked.current)
return;
tracked.current = true;
const trackView = async () => {
try {
const rebuyInstance = customRebuy || rebuyFromContext;
if (!rebuyInstance) {
console.warn("[RebuyProductView] Rebuy SDK not available for product view tracking");
return;
}
let productId = product.id;
if (productId.includes("/")) {
const numericId = productId.split("/").pop();
if (numericId) {
productId = numericId;
}
}
if (rebuyInstance && rebuyInstance.tracking && rebuyInstance.tracking.productView) {
await rebuyInstance.tracking.productView(productId);
} else {
console.warn("[RebuyProductView] Rebuy SDK tracking.productView method not available");
}
} catch (error) {
console.error("[RebuyProductView] Rebuy product view tracking failed:", error);
}
};
trackView();
}, [product.id, product.handle, customerId, customRebuy, rebuyFromContext]);
return null;
};
// src/loader.ts
import { RebuySDK as RebuySDK2, RebuyContextBuilder } from "@rebuy/core-sdk";
import { RebuyContextBuilder as RebuyContextBuilder2 } from "@rebuy/core-sdk";
var getRebuyData = async (options) => {
const { apiHost, apiKey, context, request } = options;
if (!request) {
console.warn("[getRebuyData] Request object is required for full context enrichment");
}
const debug = !!context.env?.REBUY_SDK_DEBUG;
const logger = {
log: (...args) => {
if (debug) {
console.log("[Rebuy Hydrogen SDK]", ...args);
}
}
};
logger.log("getRebuyData Entry:", {
hasI18n: !!context.storefront?.i18n,
hasRequest: !!request,
i18nCountry: context.storefront?.i18n?.country,
i18nLanguage: context.storefront?.i18n?.language,
requestUrl: request?.url
});
const rebuyApiKey = apiKey || context.env?.REBUY_API_KEY || context.env?.PUBLIC_REBUY_API_KEY;
const rebuyApiHost = apiHost || context.env?.REBUY_API_HOST;
if (!rebuyApiKey) {
throw new Error(
"Rebuy API key is required. Provide it via options.apiKey or set REBUY_API_KEY or PUBLIC_REBUY_API_KEY in your environment."
);
}
logger.log("Initializing Rebuy SDK with context builder support");
const sdk = new RebuySDK2({
apiHost: rebuyApiHost,
apiKey: rebuyApiKey,
debug
});
const builder = new RebuyContextBuilder(sdk, debug);
try {
logger.log("Fetching cart from Hydrogen context...");
const cart = await context.cart.get();
if (cart) {
logger.log("Cart found, adding to context");
builder.withCart(cart);
} else {
logger.log("No cart found or cart is empty");
}
} catch (error) {
console.warn("[getRebuyData] Failed to fetch cart for context:", error);
}
if (request && request.url) {
try {
logger.log("Adding URL context from request:", request.url);
builder.withUrl(request.url);
} catch (error) {
console.warn("[getRebuyData] Failed to parse URL for context:", error);
}
}
const i18n = context.storefront?.i18n;
if (i18n) {
if (i18n.country) {
logger.log("Adding country context:", i18n.country);
builder.withLocation(i18n.country);
}
if (i18n.language) {
logger.log("Adding language context:", i18n.language);
builder.withLanguage(i18n.language);
}
}
const cartContext = builder.build();
logger.log("getRebuyData Result:", {
contextKeys: Object.keys(cartContext),
contextValues: debug ? cartContext : "(hidden in non-debug mode)",
sdkInitialized: !!sdk
});
return {
rebuy: {
cartContext,
sdk
}
};
};
export {
RebuyContext,
RebuyContextBuilder2 as RebuyContextBuilder,
RebuyProductView,
RebuyProvider,
RecentlyViewed,
getRebuyData,
useRebuy
};
//# sourceMappingURL=index.mjs.map