Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/storefront/scripts/artifact-publish.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function artifactConfigFromEnvironment(environment = process.env) {
return {
mode,
delivery,
origin: origin.origin,
origin: origin.toString().replace(/\/+$/, ""),
siteKey,
signingSecret,
};
Expand Down
6 changes: 4 additions & 2 deletions apps/storefront/scripts/generate-seo-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export async function fetchDocument(path, {
}
attemptsMade = attempt;
try {
const response = await fetchImpl(new URL(path, backendOrigin), {
const response = await fetchImpl(new URL(path.replace(/^\/+/, ""), backendOrigin), {
headers: { "User-Agent": "FunkyCommerce-Static-SEO/1.0" },
redirect: "follow",
signal: signal
Expand Down Expand Up @@ -243,7 +243,9 @@ export async function generateSeoFiles({
return;
}

const backendOrigin = new URL(graphqlEndpoint).origin;
const backendUrl = new URL(graphqlEndpoint);
backendUrl.pathname = backendUrl.pathname.replace(/\/+$/, "");
const backendOrigin = new URL(".", backendUrl).toString();
const frontendOrigin = siteUrl ? new URL(siteUrl).origin : null;
const signal = AbortSignal.timeout(budgetMs);
const fetchFromBackend = (path) => fetchDocument(path, {
Expand Down
11 changes: 8 additions & 3 deletions apps/storefront/scripts/prerender.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ const hasInteractiveStaticChrome = [configuredSiteHostname, configuredBackendHos
);
const graphqlEndpoint = process.env.VITE_GRAPHQL_ENDPOINT?.trim()
|| "https://dev.superfunky.pro/graphql";
const backendBaseUrl = (() => {
const endpoint = new URL(graphqlEndpoint);
endpoint.pathname = endpoint.pathname.replace(/\/+$/, "");
return new URL(".", endpoint).toString();
})();
let defaultLanguage = process.env.VITE_DEFAULT_LANGUAGE?.trim().toLowerCase() || "en";
const configuredBackendProfile = process.env.VITE_BACKEND_PROFILE?.trim().toLowerCase() || "full";
const backendProfile = ["shell", "blog", "shop", "full"].includes(configuredBackendProfile)
Expand Down Expand Up @@ -1084,7 +1089,7 @@ async function discoverLanguages() {
}));
}
try {
const response = await fetch(new URL("/wp-json/pll/v1/languages", graphqlEndpoint));
const response = await fetch(new URL("wp-json/pll/v1/languages", backendBaseUrl));
if (response.ok) {
const restLanguages = await response.json();
if (!Array.isArray(restLanguages)) {
Expand Down Expand Up @@ -1141,7 +1146,7 @@ async function discoverLanguages() {
}
}
try {
const response = await fetch(new URL("/wp-json/pll/v1/languages", graphqlEndpoint), {
const response = await fetch(new URL("wp-json/pll/v1/languages", backendBaseUrl), {
signal: AbortSignal.timeout(10_000),
});
if (response.ok) {
Expand Down Expand Up @@ -1523,7 +1528,7 @@ async function discoverCmsRoutes({
}

async function discoverStoreApiProductRouteNodes() {
const endpoint = new URL("/wp-json/wc/store/v1/products?per_page=100", graphqlEndpoint);
const endpoint = new URL("wp-json/wc/store/v1/products?per_page=100", backendBaseUrl);
const response = await fetch(endpoint, { signal: AbortSignal.timeout(20_000) });
if (response.status === 404) return [];
if (!response.ok) {
Expand Down
2 changes: 2 additions & 0 deletions apps/storefront/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,8 @@ export function App() {
<Route path="/:language/product-brand" element={<ProductBrandDirectoryPage />} />
<Route path="/shop/:slug" element={<ProductMockupPage />} />
<Route path="/sklep/:slug" element={<ProductMockupPage />} />
<Route path="/produkt/:slug" element={<ProductMockupPage />} />
<Route path="/:language/produkt/:slug" element={<ProductMockupPage />} />
<Route path="/product/*" element={<ProductMockupPage />} />
<Route path="/product-category/*" element={<ProductCategoryMockupPage />} />
<Route path="/kategoria-produktu/*" element={<ProductCategoryMockupPage />} />
Expand Down
13 changes: 11 additions & 2 deletions apps/storefront/src/components/ChatAssistantShortcode.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BACKEND_ORIGIN } from "@funky/sdk";
import { BACKEND_BASE_URL } from "@funky/sdk";
import { Bot, MessageCircle, Send, Sparkles } from "lucide-react";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { chatAssistantEndpoints, resolveFlatAssistantIcon, type FlatAssistantIcon } from "../lib/chatAssistant";
Expand Down Expand Up @@ -33,7 +33,7 @@ function ConfiguredIcon({ config }: { config: AssistantConfig | null }) {
}

export function ChatAssistantShortcode() {
const endpoints = useMemo(() => chatAssistantEndpoints(BACKEND_ORIGIN), []);
const endpoints = useMemo(() => chatAssistantEndpoints(BACKEND_BASE_URL), []);
const clientId = useMemo(() => crypto.randomUUID(), []);
const [config, setConfig] = useState<AssistantConfig | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
Expand All @@ -42,6 +42,10 @@ export function ChatAssistantShortcode() {
const [error, setError] = useState("");

useEffect(() => {
if (!endpoints) {
setError("The assistant backend is not configured.");
return;
}
const controller = new AbortController();
fetch(endpoints.config, { signal: controller.signal })
.then((response) => response.ok ? response.json() : Promise.reject(new Error("Assistant configuration is unavailable.")))
Expand All @@ -61,6 +65,11 @@ export function ChatAssistantShortcode() {
setInput("");
setBusy(true);
setError("");
if (!endpoints) {
setError("The assistant backend is not configured.");
setBusy(false);
return;
}
try {
const response = await fetch(endpoints.chat, {
method: "POST",
Expand Down
2 changes: 1 addition & 1 deletion apps/storefront/src/components/CmsPageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ function NestedWordPressShortcodes({ html, slots }: { html: string; slots: Neste
setTargets(slots.map(({ marker }) =>
contentRef.current?.querySelector(`[data-funkycommerce-render-slot="${marker.slotId}"]`) || null,
));
}, [slots]);
}, [html, slots]);

return (
<>
Expand Down
3 changes: 2 additions & 1 deletion apps/storefront/src/components/SmartLinkNavigation.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useRef } from "react";
import { useLocation, useNavigate, useNavigationType } from "react-router-dom";
import { normalizeLanguagePath, useLanguage } from "@funky/ui";
import { BACKEND_ORIGIN } from "@funky/sdk";
import { BACKEND_BASE_PATH, BACKEND_ORIGIN } from "@funky/sdk";
import { mountHashAnchorScroll, mountSmartLinkNavigation } from "../lib/internalLinks";
import { prefetchStorefrontRoute } from "../lib/routePrefetch";
import { artifactRouteHydrationEnabled } from "../lib/storefrontDocumentWarmup";
Expand All @@ -24,6 +24,7 @@ export function SmartLinkNavigation() {
document,
window,
backendOrigin: BACKEND_ORIGIN,
backendBasePath: BACKEND_BASE_PATH,
normalizeTo: (to) => normalizeLanguagePath(to, languageCode, configuredLanguageCodes),
navigate: artifactRouteHydrationEnabled
? (to) => void prefetch(to).then(() => navigate(to), () => navigate(to))
Expand Down
4 changes: 2 additions & 2 deletions apps/storefront/src/lib/blikPayment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export type BlikReconciliationResponse = {
};

export function buildBlikReconciliationRequest(
backendOrigin: string,
backendBaseUrl: string,
order: Pick<StoreApiCheckoutResult, "order_id" | "order_key">,
billingEmail: string,
): { url: string; body: Record<string, string> } {
const url = new URL(`${backendOrigin}/index.php`);
const url = new URL("index.php", backendBaseUrl);
url.searchParams.set(
"rest_route",
`/funkycommerce/v1/orders/${order.order_id}/reconcile-blik`,
Expand Down
6 changes: 4 additions & 2 deletions apps/storefront/src/lib/blog.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { PostCardData } from "@funky/ui";
import {
BACKEND_BASE_URL,
BACKEND_ORIGIN,
backendPathFromUrl,
graphqlRequest,
STOREFRONT_BACKEND_PROFILE,
type GraphqlResponse,
Expand Down Expand Up @@ -464,7 +466,7 @@ async function getRestListingTerms(
if (!BACKEND_ORIGIN) {
throw new Error("The blog taxonomy endpoint is unavailable because no backend origin is configured");
}
const url = new URL(`/wp-json/wp/v2/${resource}`, BACKEND_ORIGIN);
const url = new URL(`wp-json/wp/v2/${resource}`, BACKEND_BASE_URL);
url.searchParams.set("per_page", "100");
url.searchParams.set("hide_empty", "true");
url.searchParams.set("lang", languageCode);
Expand All @@ -487,7 +489,7 @@ async function getRestListingTerms(
id: String(term.id),
name: htmlToPlainText(term.name),
slug: term.slug,
uri: new URL(term.link, BACKEND_ORIGIN).pathname,
uri: backendPathFromUrl(term.link, ""),
count: Number.isFinite(term.count) ? term.count : 0,
description: htmlToPlainText(description),
}];
Expand Down
11 changes: 6 additions & 5 deletions apps/storefront/src/lib/chatAssistant.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
export const CHAT_ASSISTANT_REST_NAMESPACE = "/wp-json/funkycommerce-ai-assistant/v1";
export const CHAT_ASSISTANT_REST_NAMESPACE = "wp-json/funkycommerce-ai-assistant/v1";

export function chatAssistantEndpoints(backendOrigin: string) {
const origin = backendOrigin.replace(/\/+$/, "");
export function chatAssistantEndpoints(backendBaseUrl: string | undefined) {
if (!backendBaseUrl) return null;
const baseUrl = backendBaseUrl.replace(/\/+$/, "") + "/";
return {
config: `${origin}${CHAT_ASSISTANT_REST_NAMESPACE}/config`,
chat: `${origin}${CHAT_ASSISTANT_REST_NAMESPACE}/chat`,
config: `${baseUrl}${CHAT_ASSISTANT_REST_NAMESPACE}/config`,
chat: `${baseUrl}${CHAT_ASSISTANT_REST_NAMESPACE}/chat`,
};
}

Expand Down
6 changes: 3 additions & 3 deletions apps/storefront/src/lib/checkoutAccount.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { normalizeBackendError } from "@funky/ui";
import { BACKEND_ORIGIN } from "@funky/sdk";
import { BACKEND_BASE_URL } from "@funky/sdk";
import type { StoreApiCheckoutResult } from "./wcStoreApi";
import { buildCheckoutOrderClaimRequest } from "./checkoutAccountRequest";

Expand All @@ -8,11 +8,11 @@ export async function claimCheckoutOrder(
billingEmail: string,
authToken: string,
): Promise<number> {
if (!BACKEND_ORIGIN || !order.order_key) {
if (!BACKEND_BASE_URL || !order.order_key) {
throw new Error("The store did not return the credentials needed to link this order.");
}

const request = buildCheckoutOrderClaimRequest(BACKEND_ORIGIN, order, billingEmail);
const request = buildCheckoutOrderClaimRequest(BACKEND_BASE_URL, order, billingEmail);
const response = await fetch(request.url, {
method: "POST",
cache: "no-store",
Expand Down
4 changes: 2 additions & 2 deletions apps/storefront/src/lib/checkoutAccountRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ type CheckoutOrderClaim = {
};

export function buildCheckoutOrderClaimRequest(
backendOrigin: string,
backendBaseUrl: string,
order: CheckoutOrderClaim,
billingEmail: string,
): { url: string; body: Record<string, string> } {
const url = new URL(`${backendOrigin}/index.php`);
const url = new URL("index.php", backendBaseUrl);
url.searchParams.set(
"rest_route",
`/funkycommerce/v1/orders/${order.order_id}/claim-customer`,
Expand Down
1 change: 1 addition & 0 deletions apps/storefront/src/lib/cmsBehaviors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,7 @@ export function mountCmsBehaviors(container: HTMLElement, showCodeControls = tru
pendingCleanup?.();
});
}

const requests = new Map<HTMLElement, Set<string>>();

const addRequest = (element: HTMLElement, id: string) => {
Expand Down
12 changes: 4 additions & 8 deletions apps/storefront/src/lib/commerce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { ProductReview, ProductVariationCombo, ProductVariationOption } fro
import {
graphqlRequest,
hasOnlyMissingGraphqlFields,
backendPathFromUrl,
restUrl,
STOREFRONT_BACKEND_PROFILE,
} from "@funky/sdk";
Expand Down Expand Up @@ -1267,12 +1268,7 @@ async function getOptionalStoreApiCatalogProducts(context: string): Promise<RawP
}

function storefrontPathFromUrl(value: string | undefined, fallback: string): string {
if (!value) return fallback;
try {
return new URL(value).pathname || fallback;
} catch {
return fallback;
}
return backendPathFromUrl(value, fallback);
}

export function matchesCommerceRouteLanguage(
Expand Down Expand Up @@ -1875,9 +1871,9 @@ export function mapProductCard(product: RawProductCard): CmsProductCard {
id: product.id,
databaseId: product.databaseId,
featured: product.featured === true,
href: product.uri || (product.slug ? `/product/${product.slug}/` : undefined),
href: backendPathFromUrl(product.uri || undefined, product.slug ? `/product/${product.slug}/` : ""),
slug: product.slug || "",
uri: product.uri || (product.slug ? `/product/${product.slug}/` : ""),
uri: backendPathFromUrl(product.uri || undefined, product.slug ? `/product/${product.slug}/` : ""),
categorySlugs: product.productCategories?.nodes.flatMap((term) => term.slug ? [term.slug] : []) || [],
tagSlugs: product.productTags?.nodes.flatMap((term) => term.slug ? [term.slug] : []) || [],
brandSlugs: product.productBrands?.nodes.flatMap((term) => term.slug ? [term.slug] : []) || [],
Expand Down
1 change: 1 addition & 0 deletions apps/storefront/src/lib/commerceCompatibility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const appSource = readFileSync(new URL("../App.tsx", import.meta.url), "utf8");

test("localized Woo product permalinks route to product details", () => {
assert.match(appSource, /path="\/sklep\/:slug" element=\{<ProductMockupPage \/>}/);
assert.match(appSource, /path="\/produkt\/:slug" element=\{<ProductMockupPage \/>}/);
assert.match(appSource, /path="\/kategoria-produktu\/\*" element=\{<ProductCategoryMockupPage \/>}/);
});

Expand Down
6 changes: 3 additions & 3 deletions apps/storefront/src/lib/downloads.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { normalizeBackendError } from "@funky/ui";
import { BACKEND_ORIGIN } from "@funky/sdk";
import { BACKEND_BASE_URL } from "@funky/sdk";
import { HttpRequestError } from "./requestRetry";

export type OrderDownload = {
Expand Down Expand Up @@ -67,9 +67,9 @@ export async function getOrderDownloadAccess(input: {
billingEmail?: string;
accessToken?: string;
}): Promise<OrderDownloadAccess> {
if (!BACKEND_ORIGIN) throw new Error("The download service is not configured.");
if (!BACKEND_BASE_URL) throw new Error("The download service is not configured.");

const url = new URL(`${BACKEND_ORIGIN}/index.php`);
const url = new URL("index.php", BACKEND_BASE_URL);
url.searchParams.set("rest_route", `/funkycommerce/v1/orders/${input.orderId}/downloads`);
if (input.orderKey) url.searchParams.set("key", input.orderKey);
if (input.billingEmail) url.searchParams.set("email", input.billingEmail);
Expand Down
12 changes: 10 additions & 2 deletions apps/storefront/src/lib/internalLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type LinkEnvironment = {
currentUrl: string;
storefrontOrigin: string;
backendOrigin?: string;
backendBasePath?: string;
};

const NATIVE_PROTOCOLS = new Set(["mailto:", "tel:", "javascript:", "data:", "blob:"]);
Expand All @@ -31,7 +32,7 @@ const NON_CONTENT_BACKEND_PATHS = [

export function normalizeContentHref(
href: string,
environment: Pick<LinkEnvironment, "storefrontOrigin" | "backendOrigin"> & { baseUrl?: string },
environment: Pick<LinkEnvironment, "storefrontOrigin" | "backendOrigin" | "backendBasePath"> & { baseUrl?: string },
): string {
const value = href.trim();
if (!value) return value;
Expand All @@ -43,7 +44,11 @@ export function normalizeContentHref(
url.origin === environment.storefrontOrigin
|| (url.origin === environment.backendOrigin && isBackendContentUrl(url))
) {
return `${url.pathname}${url.search}${url.hash}`;
const basePath = environment.backendBasePath?.replace(/\/+$/, "") || "";
const path = basePath && (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`))
? url.pathname.slice(basePath.length) || "/"
: url.pathname;
return `${path.startsWith("/") ? path : `/${path}`}${url.search}${url.hash}`;
}
return url.href;
} catch {
Expand Down Expand Up @@ -200,6 +205,7 @@ type SmartLinkControllerOptions = {
document: Document;
window: Window;
backendOrigin?: string;
backendBasePath?: string;
normalizeTo?: (to: string) => string;
navigate: (to: string) => void;
prefetch: (to: string) => Promise<unknown> | unknown;
Expand All @@ -213,6 +219,7 @@ export function mountSmartLinkNavigation({
document,
window,
backendOrigin,
backendBasePath,
normalizeTo = (to) => to,
navigate,
prefetch,
Expand Down Expand Up @@ -247,6 +254,7 @@ export function mountSmartLinkNavigation({
const mapped = normalizeContentHref(rawHref, {
storefrontOrigin: window.location.origin,
backendOrigin,
backendBasePath,
baseUrl: window.location.href,
});
if (!mapped.startsWith("/") || mapped.startsWith("//")) continue;
Expand Down
4 changes: 2 additions & 2 deletions apps/storefront/src/lib/navigation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ test("optional language discovery cannot invalidate layout configuration", () =>
assert.doesNotMatch(navigationQuery, /languages\s*\{/);
assert.match(navigationSource, /getStorefrontLanguages\(\)/);
assert.match(navigationSource, /getPolylangRestLanguages\(AbortSignal\.timeout\(3_000\)\)/);
assert.match(navigationSource, /new URL\("\/wp-json\/", BACKEND_ORIGIN\)/);
assert.match(navigationSource, /new URL\("wp-json\/", BACKEND_BASE_URL\)/);
assert.match(navigationSource, /restIndex\.namespaces\.some\(\(namespace\) => namespace === "pll\/v1"\)/);
assert.doesNotMatch(navigationSource, /const \[graphqlResponse, restLanguageResult\] = await Promise\.all\(/);
assert.match(
Expand Down Expand Up @@ -212,7 +212,7 @@ test("navigation compatibility fallback is explicit for minimal backends without
assert.match(navigationSource, /"promoHtml"/);
assert.match(navigationSource, /"headerIconMedia"/);
assert.match(navigationSource, /"aiAssistant"/);
assert.match(navigationSource, /\/wp-json\/pll\/v1\/languages/);
assert.match(navigationSource, /wp-json\/pll\/v1\/languages/);
assert.match(navigationSource, /getOptionalPolylangRestLanguages\(\)/);
assert.doesNotMatch(navigationSource, /query StorefrontNavigationCompatible \{\s*menus\(first: 100\) \{\s*nodes \{\s*id\s*databaseId\s*name\s*slug\s*locations/);
assert.match(navigationSource, /return \[];\n\s*\}/);
Expand Down
Loading
Loading