@ecomweb/storefront-kit 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -1
- package/dist/index.d.ts +54 -3
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/metafields/metaobjects.js +29 -0
- package/dist/metafields/metaobjects.js.map +1 -0
- package/dist/metafields/readers.js +27 -0
- package/dist/metafields/readers.js.map +1 -0
- package/dist/metafields/rich-text.js +89 -0
- package/dist/metafields/rich-text.js.map +1 -0
- package/dist/middleware/create-storefront-middleware.js +63 -8
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/request/request-path.js +5 -0
- package/dist/request/request-path.js.map +1 -0
- package/dist/server.d.ts +19 -1
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/stores/get-store-by-host.js +5 -2
- package/dist/stores/get-store-by-host.js.map +1 -1
- package/dist/theme/external-storefront.js +52 -0
- package/dist/theme/external-storefront.js.map +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ pnpm add @ecomweb/storefront-kit @ecomweb/sdk
|
|
|
10
10
|
|
|
11
11
|
| Entry | Use it from | Main exports |
|
|
12
12
|
|---|---|---|
|
|
13
|
-
| `@ecomweb/storefront-kit` | client and server components | `StorefrontKitProvider`, `useAuth`, `useCart`, `useCheckout`, `useOrderStatus`, `useOrderLookup`, `storePath`, `storeApiPath` |
|
|
13
|
+
| `@ecomweb/storefront-kit` | client and server components | `StorefrontKitProvider`, `useAuth`, `useCart`, `useCheckout`, `useOrderStatus`, `useOrderLookup`, `storePath`, `storeApiPath`, `metafield`, `metaobjectField`, `getMetaobjects`, `getMetaobject`, `RichText` |
|
|
14
14
|
| `@ecomweb/storefront-kit/server` | route handlers, server components | `createAuthRoutes`, `createBackendProxy`, `requireSession`, `serverConfig`, `resolveRootStoreRef` |
|
|
15
15
|
| `@ecomweb/storefront-kit/middleware` | `proxy.ts` | `createStorefrontMiddleware`, `storefrontMiddlewareConfig` |
|
|
16
16
|
| `@ecomweb/storefront-kit/config` | anywhere | `publicConfig`, `parsePublicConfig`, `resolveMode` |
|
|
@@ -48,6 +48,37 @@ Wrap the store layout in `<StorefrontKitProvider store={store} onNotice={…}>`;
|
|
|
48
48
|
toasts. `useCheckout().placeOrder()` returns `redirect`, `redirect_failed`,
|
|
49
49
|
`success`, `stock_issues` or `error`, and your page decides what to show.
|
|
50
50
|
|
|
51
|
+
## Metafields and metaobjects
|
|
52
|
+
|
|
53
|
+
Merchants define typed custom data in the dashboard (Settings, Custom data).
|
|
54
|
+
Definitions with storefront access come back on public product, variant,
|
|
55
|
+
collection, page, blog post and store responses as `metafields`, already
|
|
56
|
+
resolved (references are summaries, files are URLs).
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
import { getMetaobjects, metafield, metaobjectField, RichText } from "@ecomweb/storefront-kit";
|
|
60
|
+
import type { ResolvedMetaobjectRef, RichTextRoot } from "@ecomweb/sdk";
|
|
61
|
+
|
|
62
|
+
const care = metafield<RichTextRoot>(product, "custom.care_guide");
|
|
63
|
+
const featured = metafield<ResolvedMetaobjectRef>(product, "custom.featured_feedback");
|
|
64
|
+
const { items, next_cursor } = await getMetaobjects(storeRef, "feedbacks", { limit: 10 });
|
|
65
|
+
|
|
66
|
+
<RichText value={care} />
|
|
67
|
+
<blockquote>{metaobjectField<string>(featured, "content")}</blockquote>
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`list.*` types return arrays, e.g.
|
|
71
|
+
`metafield<ResolvedMetaobjectRef[]>(product, "custom.related")`.
|
|
72
|
+
`getMetaobjects` and `getMetaobject` are uncached on the server: wrap them in
|
|
73
|
+
React's `cache()` when several components in one request need the same data.
|
|
74
|
+
|
|
75
|
+
`metafield` returns `undefined` when there is no value or the reference is
|
|
76
|
+
hidden from the storefront. `RichText` renders bare `h1`..`h6`, `p`, `ul`,
|
|
77
|
+
`ol`, `li`, `strong`, `em` and `a` elements and never sets raw HTML; links
|
|
78
|
+
other than http, https and mailto render as text. For a metaobject type with
|
|
79
|
+
customer-account access only, pass `{ as_customer: true }` from a client
|
|
80
|
+
component.
|
|
81
|
+
|
|
51
82
|
## Versioning
|
|
52
83
|
|
|
53
84
|
Semver. Within 1.x no export is removed and no required prop or parameter
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import * as react from 'react';
|
|
3
|
-
import { ReactNode } from 'react';
|
|
3
|
+
import { ReactNode, ReactElement } from 'react';
|
|
4
4
|
import * as _ecomweb_sdk from '@ecomweb/sdk';
|
|
5
|
-
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, OrderStatus, Order, CreateOrderRequest, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues } from '@ecomweb/sdk';
|
|
5
|
+
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, OrderStatus, Order, CreateOrderRequest, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
|
|
6
6
|
import currencyJs from 'currency.js';
|
|
7
7
|
import { AxiosRequestConfig, AxiosInstance } from 'axios';
|
|
8
8
|
export { AnyThemeDefinition, HomePageSlotProps, LayoutSlotProps, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
|
|
@@ -689,6 +689,7 @@ declare const sdk: {
|
|
|
689
689
|
blog: _ecomweb_sdk.BlogApi;
|
|
690
690
|
stores: _ecomweb_sdk.StoresApi;
|
|
691
691
|
themes: _ecomweb_sdk.ThemesApi;
|
|
692
|
+
metaobjects: _ecomweb_sdk.MetaobjectsApi;
|
|
692
693
|
search: _ecomweb_sdk.SearchApi;
|
|
693
694
|
banners: _ecomweb_sdk.BannersApi;
|
|
694
695
|
shipping: _ecomweb_sdk.ShippingApi;
|
|
@@ -719,6 +720,7 @@ declare function createStoreSdk(storeRef: string): {
|
|
|
719
720
|
blog: _ecomweb_sdk.BlogApi;
|
|
720
721
|
stores: _ecomweb_sdk.StoresApi;
|
|
721
722
|
themes: _ecomweb_sdk.ThemesApi;
|
|
723
|
+
metaobjects: _ecomweb_sdk.MetaobjectsApi;
|
|
722
724
|
search: _ecomweb_sdk.SearchApi;
|
|
723
725
|
banners: _ecomweb_sdk.BannersApi;
|
|
724
726
|
shipping: _ecomweb_sdk.ShippingApi;
|
|
@@ -911,6 +913,55 @@ declare function ThemeSettingsProvider({ themeId, settings, children, }: ThemeSe
|
|
|
911
913
|
declare function useThemeSettings<T = ThemeValues>(): T;
|
|
912
914
|
declare function useThemeId(): string;
|
|
913
915
|
|
|
916
|
+
/**
|
|
917
|
+
* A metafield's resolved value by identifier, e.g.
|
|
918
|
+
* `metafield<RichTextRoot>(product, "custom.care_guide")`.
|
|
919
|
+
*
|
|
920
|
+
* Works on any public resource that carries `metafields` (product, variant,
|
|
921
|
+
* collection, content page, blog post, store, customer order). Returns
|
|
922
|
+
* undefined when the definition has no storefront access, the owner has no
|
|
923
|
+
* value, or the value is a reference the storefront may not see. The generic
|
|
924
|
+
* is a cast, not a check: pick it from the definition's type.
|
|
925
|
+
*
|
|
926
|
+
* The first argument may also be a bare metafield map, as returned by
|
|
927
|
+
* `sdk.customers.getMetafields()`. A resource is told from a map by its own
|
|
928
|
+
* `metafields` key (identifiers always contain a dot, so none can collide).
|
|
929
|
+
*/
|
|
930
|
+
declare function metafield<V = unknown>(resource: WithMetafields | StorefrontMetafields | null | undefined, identifier: string): V | undefined;
|
|
931
|
+
/**
|
|
932
|
+
* A metaobject entry's field value by field key, e.g.
|
|
933
|
+
* `metaobjectField<string>(entry, "name")`. Undefined for a missing or hidden
|
|
934
|
+
* value, and for a reference deeper than the resolution depth (a
|
|
935
|
+
* `{ type, handle }` stub has no fields).
|
|
936
|
+
*/
|
|
937
|
+
declare function metaobjectField<V = unknown>(entry: ResolvedMetaobjectRef | ResolvedMetaobjectStub | null | undefined, key: string): V | undefined;
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* Active entries of a metaobject type, e.g.
|
|
941
|
+
* `getMetaobjects(storeRef, "feedbacks", { filter: { rating: 5 }, limit: 10 })`.
|
|
942
|
+
*
|
|
943
|
+
* `filter` accepts only the definition's filter keys, equality only; `limit`
|
|
944
|
+
* is at most 50. A type that does not exist, or has no storefront access,
|
|
945
|
+
* lists as empty: the API answers both the same way.
|
|
946
|
+
*/
|
|
947
|
+
declare function getMetaobjects(storeRef: string, type: string, options?: MetaobjectListParams): Promise<MetaobjectListResult>;
|
|
948
|
+
/** One active entry by handle; null when it, or its type, is missing or hidden. */
|
|
949
|
+
declare function getMetaobject(storeRef: string, type: string, handle: string, options?: {
|
|
950
|
+
as_customer?: boolean;
|
|
951
|
+
}): Promise<StorefrontMetaobjectEntry | null>;
|
|
952
|
+
|
|
953
|
+
interface RichTextProps {
|
|
954
|
+
/** A rich_text metafield value, e.g. `metafield<RichTextRoot>(product, "custom.care_guide")`. */
|
|
955
|
+
value: RichTextRoot | null | undefined;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Renders a rich-text metafield as React elements: headings, paragraphs,
|
|
959
|
+
* lists, bold, italic and links. Unknown nodes are skipped. Text is always a
|
|
960
|
+
* text child, so nothing a merchant or shopper typed is ever parsed as
|
|
961
|
+
* markup. Returns bare elements with no wrapper; style them from the parent.
|
|
962
|
+
*/
|
|
963
|
+
declare function RichText({ value }: RichTextProps): ReactElement | null;
|
|
964
|
+
|
|
914
965
|
/** A `:root{…}` rule from a theme's custom properties; null when empty. */
|
|
915
966
|
declare function themeStyleCss(vars: Record<string, string> | null | undefined): string | null;
|
|
916
967
|
declare function ThemeStyle({ vars, }: {
|
|
@@ -976,4 +1027,4 @@ declare function getLogLevel(): LogLevel;
|
|
|
976
1027
|
declare function shouldLog(currentLevel: LogLevel, messageLevel: LogLevel): boolean;
|
|
977
1028
|
declare function applyConsoleFilter(level?: LogLevel): void;
|
|
978
1029
|
|
|
979
|
-
export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
|
|
1030
|
+
export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
|
package/dist/index.js
CHANGED
|
@@ -71,6 +71,9 @@ import {
|
|
|
71
71
|
useThemeId,
|
|
72
72
|
useThemeSettings
|
|
73
73
|
} from "./theme/settings-context.js";
|
|
74
|
+
import { metafield, metaobjectField } from "./metafields/readers.js";
|
|
75
|
+
import { getMetaobject, getMetaobjects } from "./metafields/metaobjects.js";
|
|
76
|
+
import { RichText } from "./metafields/rich-text.js";
|
|
74
77
|
import { ThemeStyle, themeStyleCss } from "./theme/style.js";
|
|
75
78
|
import { getCachedStore } from "./stores/cached.js";
|
|
76
79
|
import {
|
|
@@ -83,6 +86,7 @@ import { applyConsoleFilter, getLogLevel, shouldLog } from "./logging.js";
|
|
|
83
86
|
export {
|
|
84
87
|
DEFAULT_REDIRECT,
|
|
85
88
|
ORDER_PROGRESS_STEPS,
|
|
89
|
+
RichText,
|
|
86
90
|
SHIPPING_MESSAGES,
|
|
87
91
|
STATUS_OPTIONS,
|
|
88
92
|
STOCK_ISSUE_TOAST_DESCRIPTION,
|
|
@@ -109,11 +113,15 @@ export {
|
|
|
109
113
|
getCachedStore,
|
|
110
114
|
getDefaultLocale,
|
|
111
115
|
getLogLevel,
|
|
116
|
+
getMetaobject,
|
|
117
|
+
getMetaobjects,
|
|
112
118
|
getPasswordPolicyHints,
|
|
113
119
|
getPaymentState,
|
|
114
120
|
getPromotionDescription,
|
|
115
121
|
isStoreSuspendedError,
|
|
116
122
|
loadWards,
|
|
123
|
+
metafield,
|
|
124
|
+
metaobjectField,
|
|
117
125
|
money,
|
|
118
126
|
pollPaymentState,
|
|
119
127
|
publicApiClient,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type { OrderHandoff } from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport { formatShippingAmount } from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAEjC,SAAS,wBAAwB;AACjC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAY1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,qBAAqB;AAC1C,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type { OrderHandoff } from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport { formatShippingAmount } from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAEjC,SAAS,wBAAwB;AACjC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAY1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createStoreSdk, sdk } from "../sdk.js";
|
|
2
|
+
function clientFor(storeRef, asCustomer) {
|
|
3
|
+
if (asCustomer && typeof window === "undefined") {
|
|
4
|
+
throw new Error(
|
|
5
|
+
"as_customer reads need the browser: call getMetaobjects with as_customer from a client component"
|
|
6
|
+
);
|
|
7
|
+
}
|
|
8
|
+
return asCustomer ? createStoreSdk(storeRef) : sdk;
|
|
9
|
+
}
|
|
10
|
+
async function getMetaobjects(storeRef, type, options = {}) {
|
|
11
|
+
return clientFor(storeRef, options.as_customer).metaobjects.list(
|
|
12
|
+
storeRef,
|
|
13
|
+
type,
|
|
14
|
+
options
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
async function getMetaobject(storeRef, type, handle, options = {}) {
|
|
18
|
+
return clientFor(storeRef, options.as_customer).metaobjects.get(
|
|
19
|
+
storeRef,
|
|
20
|
+
type,
|
|
21
|
+
handle,
|
|
22
|
+
options
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
getMetaobject,
|
|
27
|
+
getMetaobjects
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=metaobjects.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/metafields/metaobjects.ts"],"sourcesContent":["import type {\n MetaobjectListParams,\n MetaobjectListResult,\n StorefrontMetaobjectEntry,\n} from \"@ecomweb/sdk\";\nimport { createStoreSdk, sdk } from \"../sdk\";\n\n/**\n * The public sdk, or, for a definition with customer access, the store-scoped\n * one whose authenticated calls go through the same-origin session proxy.\n * That proxy is a relative URL, so `as_customer` works in client components\n * only.\n */\nfunction clientFor(storeRef: string, asCustomer: boolean | undefined) {\n if (asCustomer && typeof window === \"undefined\") {\n throw new Error(\n \"as_customer reads need the browser: call getMetaobjects with as_customer from a client component\"\n );\n }\n return asCustomer ? createStoreSdk(storeRef) : sdk;\n}\n\n/**\n * Active entries of a metaobject type, e.g.\n * `getMetaobjects(storeRef, \"feedbacks\", { filter: { rating: 5 }, limit: 10 })`.\n *\n * `filter` accepts only the definition's filter keys, equality only; `limit`\n * is at most 50. A type that does not exist, or has no storefront access,\n * lists as empty: the API answers both the same way.\n */\nexport async function getMetaobjects(\n storeRef: string,\n type: string,\n options: MetaobjectListParams = {}\n): Promise<MetaobjectListResult> {\n return clientFor(storeRef, options.as_customer).metaobjects.list(\n storeRef,\n type,\n options\n );\n}\n\n/** One active entry by handle; null when it, or its type, is missing or hidden. */\nexport async function getMetaobject(\n storeRef: string,\n type: string,\n handle: string,\n options: { as_customer?: boolean } = {}\n): Promise<StorefrontMetaobjectEntry | null> {\n return clientFor(storeRef, options.as_customer).metaobjects.get(\n storeRef,\n type,\n handle,\n options\n );\n}\n"],"mappings":"AAKA,SAAS,gBAAgB,WAAW;AAQpC,SAAS,UAAU,UAAkB,YAAiC;AACpE,MAAI,cAAc,OAAO,WAAW,aAAa;AAC/C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,aAAa,eAAe,QAAQ,IAAI;AACjD;AAUA,eAAsB,eACpB,UACA,MACA,UAAgC,CAAC,GACF;AAC/B,SAAO,UAAU,UAAU,QAAQ,WAAW,EAAE,YAAY;AAAA,IAC1D;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAGA,eAAsB,cACpB,UACA,MACA,QACA,UAAqC,CAAC,GACK;AAC3C,SAAO,UAAU,UAAU,QAAQ,WAAW,EAAE,YAAY;AAAA,IAC1D;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
function read(fields, name) {
|
|
2
|
+
if (!fields || !Object.prototype.hasOwnProperty.call(fields, name)) {
|
|
3
|
+
return void 0;
|
|
4
|
+
}
|
|
5
|
+
const value = fields[name]?.value;
|
|
6
|
+
return value === null || value === void 0 ? void 0 : value;
|
|
7
|
+
}
|
|
8
|
+
function metafield(resource, identifier) {
|
|
9
|
+
if (resource === null || typeof resource !== "object") return void 0;
|
|
10
|
+
const isResource = Object.prototype.hasOwnProperty.call(
|
|
11
|
+
resource,
|
|
12
|
+
"metafields"
|
|
13
|
+
);
|
|
14
|
+
return read(
|
|
15
|
+
isResource ? resource.metafields : resource,
|
|
16
|
+
identifier
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
function metaobjectField(entry, key) {
|
|
20
|
+
const fields = entry !== null && typeof entry === "object" && "fields" in entry ? entry.fields : void 0;
|
|
21
|
+
return read(fields, key);
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
metafield,
|
|
25
|
+
metaobjectField
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=readers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/metafields/readers.ts"],"sourcesContent":["import type {\n ResolvedMetaobjectRef,\n ResolvedMetaobjectStub,\n StorefrontMetafields,\n WithMetafields,\n} from \"@ecomweb/sdk\";\n\nfunction read<V>(\n fields: StorefrontMetafields | undefined,\n name: string\n): V | undefined {\n // Own properties only: \"__proto__\" or \"toString\" must not reach the prototype.\n if (!fields || !Object.prototype.hasOwnProperty.call(fields, name)) {\n return undefined;\n }\n const value = fields[name]?.value;\n // A hidden reference resolves to null (spec 6.5); \"no value\" is undefined.\n return value === null || value === undefined ? undefined : (value as V);\n}\n\n/**\n * A metafield's resolved value by identifier, e.g.\n * `metafield<RichTextRoot>(product, \"custom.care_guide\")`.\n *\n * Works on any public resource that carries `metafields` (product, variant,\n * collection, content page, blog post, store, customer order). Returns\n * undefined when the definition has no storefront access, the owner has no\n * value, or the value is a reference the storefront may not see. The generic\n * is a cast, not a check: pick it from the definition's type.\n *\n * The first argument may also be a bare metafield map, as returned by\n * `sdk.customers.getMetafields()`. A resource is told from a map by its own\n * `metafields` key (identifiers always contain a dot, so none can collide).\n */\nexport function metafield<V = unknown>(\n resource: WithMetafields | StorefrontMetafields | null | undefined,\n identifier: string\n): V | undefined {\n if (resource === null || typeof resource !== \"object\") return undefined;\n const isResource = Object.prototype.hasOwnProperty.call(\n resource,\n \"metafields\"\n );\n return read<V>(\n isResource\n ? (resource as WithMetafields).metafields\n : (resource as StorefrontMetafields),\n identifier\n );\n}\n\n/**\n * A metaobject entry's field value by field key, e.g.\n * `metaobjectField<string>(entry, \"name\")`. Undefined for a missing or hidden\n * value, and for a reference deeper than the resolution depth (a\n * `{ type, handle }` stub has no fields).\n */\nexport function metaobjectField<V = unknown>(\n entry: ResolvedMetaobjectRef | ResolvedMetaobjectStub | null | undefined,\n key: string\n): V | undefined {\n const fields =\n entry !== null && typeof entry === \"object\" && \"fields\" in entry\n ? (entry as ResolvedMetaobjectRef).fields\n : undefined;\n return read<V>(fields, key);\n}\n"],"mappings":"AAOA,SAAS,KACP,QACA,MACe;AAEf,MAAI,CAAC,UAAU,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,IAAI,GAAG;AAClE,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,OAAO,IAAI,GAAG;AAE5B,SAAO,UAAU,QAAQ,UAAU,SAAY,SAAa;AAC9D;AAgBO,SAAS,UACd,UACA,YACe;AACf,MAAI,aAAa,QAAQ,OAAO,aAAa,SAAU,QAAO;AAC9D,QAAM,aAAa,OAAO,UAAU,eAAe;AAAA,IACjD;AAAA,IACA;AAAA,EACF;AACA,SAAO;AAAA,IACL,aACK,SAA4B,aAC5B;AAAA,IACL;AAAA,EACF;AACF;AAQO,SAAS,gBACd,OACA,KACe;AACf,QAAM,SACJ,UAAU,QAAQ,OAAO,UAAU,YAAY,YAAY,QACtD,MAAgC,SACjC;AACN,SAAO,KAAQ,QAAQ,GAAG;AAC5B;","names":[]}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
2
|
+
import {
|
|
3
|
+
createElement,
|
|
4
|
+
Fragment as Fragment2
|
|
5
|
+
} from "react";
|
|
6
|
+
const MAX_URL_LENGTH = 2048;
|
|
7
|
+
const UNSAFE_URL_CHARS = /[\u0000-\u001f\u007f-\u009f"<>`\\]|\s/;
|
|
8
|
+
const MAILTO = /^mailto:[^\s@?&#,]+@[^\s@?&#,]+$/i;
|
|
9
|
+
function richTextHref(url) {
|
|
10
|
+
if (typeof url !== "string" || url.length === 0 || url.length > MAX_URL_LENGTH || UNSAFE_URL_CHARS.test(url)) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
if (MAILTO.test(url)) return { href: url, external: false };
|
|
14
|
+
let parsed;
|
|
15
|
+
try {
|
|
16
|
+
parsed = new URL(url);
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
return parsed.protocol === "http:" || parsed.protocol === "https:" ? { href: url, external: true } : null;
|
|
21
|
+
}
|
|
22
|
+
const isNode = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
23
|
+
const childrenOf = (node) => Array.isArray(node.children) ? node.children : [];
|
|
24
|
+
const HEADINGS = {
|
|
25
|
+
1: "h1",
|
|
26
|
+
2: "h2",
|
|
27
|
+
3: "h3",
|
|
28
|
+
4: "h4",
|
|
29
|
+
5: "h5",
|
|
30
|
+
6: "h6"
|
|
31
|
+
};
|
|
32
|
+
function renderText(node, key) {
|
|
33
|
+
if (typeof node.value !== "string") return null;
|
|
34
|
+
let out = node.value;
|
|
35
|
+
if (node.italic === true) out = /* @__PURE__ */ jsx("em", { children: out });
|
|
36
|
+
if (node.bold === true) out = /* @__PURE__ */ jsx("strong", { children: out });
|
|
37
|
+
return /* @__PURE__ */ jsx(Fragment2, { children: out }, key);
|
|
38
|
+
}
|
|
39
|
+
function renderInline(node, key) {
|
|
40
|
+
if (!isNode(node)) return null;
|
|
41
|
+
if (node.type === "text") return renderText(node, key);
|
|
42
|
+
if (node.type !== "link") return null;
|
|
43
|
+
const text = childrenOf(node).map(
|
|
44
|
+
(child, index) => isNode(child) && child.type === "text" ? renderText(child, index) : null
|
|
45
|
+
);
|
|
46
|
+
const link = richTextHref(node.url);
|
|
47
|
+
if (!link) return /* @__PURE__ */ jsx(Fragment2, { children: text }, key);
|
|
48
|
+
const title = typeof node.title === "string" && node.title !== "" ? node.title : void 0;
|
|
49
|
+
return /* @__PURE__ */ jsx(
|
|
50
|
+
"a",
|
|
51
|
+
{
|
|
52
|
+
href: link.href,
|
|
53
|
+
rel: link.external ? "noopener noreferrer" : void 0,
|
|
54
|
+
title,
|
|
55
|
+
children: text
|
|
56
|
+
},
|
|
57
|
+
key
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const inlines = (node) => childrenOf(node).map(renderInline);
|
|
61
|
+
function renderBlock(node, key) {
|
|
62
|
+
if (!isNode(node)) return null;
|
|
63
|
+
switch (node.type) {
|
|
64
|
+
case "paragraph":
|
|
65
|
+
return /* @__PURE__ */ jsx("p", { children: inlines(node) }, key);
|
|
66
|
+
case "heading": {
|
|
67
|
+
const level = node.level;
|
|
68
|
+
const tag = typeof level === "number" && Object.prototype.hasOwnProperty.call(HEADINGS, level) ? HEADINGS[level] : "p";
|
|
69
|
+
return createElement(tag, { key }, inlines(node));
|
|
70
|
+
}
|
|
71
|
+
case "list": {
|
|
72
|
+
const items = childrenOf(node).map(
|
|
73
|
+
(item, index) => isNode(item) && item.type === "list-item" ? /* @__PURE__ */ jsx("li", { children: inlines(item) }, index) : null
|
|
74
|
+
);
|
|
75
|
+
return node.listType === "ordered" ? /* @__PURE__ */ jsx("ol", { children: items }, key) : /* @__PURE__ */ jsx("ul", { children: items }, key);
|
|
76
|
+
}
|
|
77
|
+
default:
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function RichText({ value }) {
|
|
82
|
+
if (!isNode(value) || value.type !== "root") return null;
|
|
83
|
+
return /* @__PURE__ */ jsx(Fragment, { children: childrenOf(value).map(renderBlock) });
|
|
84
|
+
}
|
|
85
|
+
export {
|
|
86
|
+
RichText,
|
|
87
|
+
richTextHref
|
|
88
|
+
};
|
|
89
|
+
//# sourceMappingURL=rich-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/metafields/rich-text.tsx"],"sourcesContent":["import {\n createElement,\n Fragment,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport type { RichTextRoot } from \"@ecomweb/sdk\";\n\n/**\n * The engine's link rule (spec 5.3), re-checked at render: the tree was\n * validated on write, but a row written before a validation fix, or edited\n * in the database, must still never become a script URL here. At least as\n * strict as the SDK engine. Commas are legal in http(s) URLs; only the\n * mailto pattern refuses them.\n */\nconst MAX_URL_LENGTH = 2048;\nconst UNSAFE_URL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f\"<>`\\\\]|\\s/;\nconst MAILTO = /^mailto:[^\\s@?&#,]+@[^\\s@?&#,]+$/i;\n\nexport interface RichTextHref {\n href: string;\n /** http(s) links; they get rel=\"noopener noreferrer\". */\n external: boolean;\n}\n\nexport function richTextHref(url: unknown): RichTextHref | null {\n if (\n typeof url !== \"string\" ||\n url.length === 0 ||\n url.length > MAX_URL_LENGTH ||\n UNSAFE_URL_CHARS.test(url)\n ) {\n return null;\n }\n if (MAILTO.test(url)) return { href: url, external: false };\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\"\n ? { href: url, external: true }\n : null;\n}\n\ntype Node = Record<string, unknown>;\n\nconst isNode = (value: unknown): value is Node =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst childrenOf = (node: Node): unknown[] =>\n Array.isArray(node.children) ? node.children : [];\n\nconst HEADINGS: Record<number, \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\"> = {\n 1: \"h1\",\n 2: \"h2\",\n 3: \"h3\",\n 4: \"h4\",\n 5: \"h5\",\n 6: \"h6\",\n};\n\n/** Only the listed keys of a node are ever read; nothing is spread into props. */\nfunction renderText(node: Node, key: number): ReactNode {\n if (typeof node.value !== \"string\") return null;\n let out: ReactNode = node.value;\n if (node.italic === true) out = <em>{out}</em>;\n if (node.bold === true) out = <strong>{out}</strong>;\n return <Fragment key={key}>{out}</Fragment>;\n}\n\nfunction renderInline(node: unknown, key: number): ReactNode {\n if (!isNode(node)) return null;\n if (node.type === \"text\") return renderText(node, key);\n if (node.type !== \"link\") return null;\n const text = childrenOf(node).map((child, index) =>\n isNode(child) && child.type === \"text\" ? renderText(child, index) : null\n );\n const link = richTextHref(node.url);\n if (!link) return <Fragment key={key}>{text}</Fragment>;\n const title =\n typeof node.title === \"string\" && node.title !== \"\"\n ? node.title\n : undefined;\n return (\n <a\n key={key}\n href={link.href}\n rel={link.external ? \"noopener noreferrer\" : undefined}\n title={title}\n >\n {text}\n </a>\n );\n}\n\nconst inlines = (node: Node): ReactNode[] => childrenOf(node).map(renderInline);\n\nfunction renderBlock(node: unknown, key: number): ReactNode {\n if (!isNode(node)) return null;\n switch (node.type) {\n case \"paragraph\":\n return <p key={key}>{inlines(node)}</p>;\n case \"heading\": {\n const level = node.level;\n const tag =\n typeof level === \"number\" &&\n Object.prototype.hasOwnProperty.call(HEADINGS, level)\n ? HEADINGS[level]\n : \"p\";\n return createElement(tag, { key }, inlines(node));\n }\n case \"list\": {\n const items = childrenOf(node).map((item, index) =>\n isNode(item) && item.type === \"list-item\" ? (\n <li key={index}>{inlines(item)}</li>\n ) : null\n );\n return node.listType === \"ordered\" ? (\n <ol key={key}>{items}</ol>\n ) : (\n <ul key={key}>{items}</ul>\n );\n }\n default:\n return null;\n }\n}\n\nexport interface RichTextProps {\n /** A rich_text metafield value, e.g. `metafield<RichTextRoot>(product, \"custom.care_guide\")`. */\n value: RichTextRoot | null | undefined;\n}\n\n/**\n * Renders a rich-text metafield as React elements: headings, paragraphs,\n * lists, bold, italic and links. Unknown nodes are skipped. Text is always a\n * text child, so nothing a merchant or shopper typed is ever parsed as\n * markup. Returns bare elements with no wrapper; style them from the parent.\n */\nexport function RichText({ value }: RichTextProps): ReactElement | null {\n if (!isNode(value) || value.type !== \"root\") return null;\n return <>{childrenOf(value).map(renderBlock)}</>;\n}\n"],"mappings":"AAmEkC,SA4EzB,UA5EyB;AAnElC;AAAA,EACE;AAAA,EACA,YAAAA;AAAA,OAGK;AAUP,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,SAAS;AAQR,SAAS,aAAa,KAAmC;AAC9D,MACE,OAAO,QAAQ,YACf,IAAI,WAAW,KACf,IAAI,SAAS,kBACb,iBAAiB,KAAK,GAAG,GACzB;AACA,WAAO;AAAA,EACT;AACA,MAAI,OAAO,KAAK,GAAG,EAAG,QAAO,EAAE,MAAM,KAAK,UAAU,MAAM;AAC1D,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,OAAO,aAAa,WAAW,OAAO,aAAa,WACtD,EAAE,MAAM,KAAK,UAAU,KAAK,IAC5B;A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I,EAAE,IAAI,YAAY;AAE9E,SAAS,YAAY,MAAe,KAAwB;AAC1D,MAAI,CAAC,OAAO,IAAI,EAAG,QAAO;AAC1B,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,oBAAC,OAAa,kBAAQ,IAAI,KAAlB,GAAoB;AAAA,IACrC,KAAK,WAAW;AACd,YAAM,QAAQ,KAAK;AACnB,YAAM,MACJ,OAAO,UAAU,YACjB,OAAO,UAAU,eAAe,KAAK,UAAU,KAAK,IAChD,SAAS,KAAK,IACd;AACN,aAAO,cAAc,KAAK,EAAE,IAAI,GAAG,QAAQ,IAAI,CAAC;AAAA,IAClD;AAAA,IACA,KAAK,QAAQ;AACX,YAAM,QAAQ,WAAW,IAAI,EAAE;AAAA,QAAI,CAAC,MAAM,UACxC,OAAO,IAAI,KAAK,KAAK,SAAS,cAC5B,oBAAC,QAAgB,kBAAQ,IAAI,KAApB,KAAsB,IAC7B;AAAA,MACN;AACA,aAAO,KAAK,aAAa,YACvB,oBAAC,QAAc,mBAAN,GAAY,IAErB,oBAAC,QAAc,mBAAN,GAAY;AAAA,IAEzB;AAAA,IACA;AACE,aAAO;AAAA,EACX;AACF;AAaO,SAAS,SAAS,EAAE,MAAM,GAAuC;AACtE,MAAI,CAAC,OAAO,KAAK,KAAK,MAAM,SAAS,OAAQ,QAAO;AACpD,SAAO,gCAAG,qBAAW,KAAK,EAAE,IAAI,WAAW,GAAE;AAC/C;","names":["Fragment"]}
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { publicNextUrl } from "../request/public-url.js";
|
|
2
|
-
import {
|
|
2
|
+
import { REQUEST_PATH_HEADER } from "../request/request-path.js";
|
|
3
|
+
import {
|
|
4
|
+
applyThemePreview,
|
|
5
|
+
hasThemePreview,
|
|
6
|
+
THEME_PREVIEW_PARAM
|
|
7
|
+
} from "../theme/preview-cookie.js";
|
|
8
|
+
import {
|
|
9
|
+
externalStorefrontUrl,
|
|
10
|
+
isSameHost
|
|
11
|
+
} from "../theme/external-storefront.js";
|
|
3
12
|
import { NextResponse } from "next/server";
|
|
4
13
|
import { authCookiePath, writeAuthCookies } from "../auth/cookies.js";
|
|
5
14
|
import {
|
|
@@ -19,6 +28,33 @@ const METADATA_FILES = [
|
|
|
19
28
|
"/icon",
|
|
20
29
|
"/apple-icon"
|
|
21
30
|
];
|
|
31
|
+
const EXTERNAL_METADATA_FILES = ["/robots.txt", "/sitemap.xml"];
|
|
32
|
+
const DOMAIN_NOT_CONNECTED_PATH = "/domain-not-connected";
|
|
33
|
+
function externalThemeResponse(req, host, storeRef, externalUrl) {
|
|
34
|
+
if (!externalUrl) return null;
|
|
35
|
+
if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req))
|
|
36
|
+
return null;
|
|
37
|
+
const pathname = req.nextUrl.pathname;
|
|
38
|
+
const prefix = multiTenantStorePath(storeRef);
|
|
39
|
+
const logicalPath = pathname === prefix || pathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) || "/" : pathname;
|
|
40
|
+
const target = externalStorefrontUrl(
|
|
41
|
+
externalUrl,
|
|
42
|
+
logicalPath,
|
|
43
|
+
req.nextUrl.search
|
|
44
|
+
);
|
|
45
|
+
if (!target) return null;
|
|
46
|
+
if (isSameHost(host, target.hostname)) {
|
|
47
|
+
if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;
|
|
48
|
+
const url = req.nextUrl.clone();
|
|
49
|
+
url.pathname = DOMAIN_NOT_CONNECTED_PATH;
|
|
50
|
+
url.search = "";
|
|
51
|
+
const res = NextResponse.rewrite(url);
|
|
52
|
+
res.headers.set("x-robots-tag", "noindex");
|
|
53
|
+
return res;
|
|
54
|
+
}
|
|
55
|
+
const safe = req.method === "GET" || req.method === "HEAD";
|
|
56
|
+
return NextResponse.redirect(target, { status: safe ? 302 : 307 });
|
|
57
|
+
}
|
|
22
58
|
function storeRefFromPath(pathname) {
|
|
23
59
|
const match = /^\/store\/([^/]+)/.exec(pathname);
|
|
24
60
|
if (!match) return null;
|
|
@@ -36,7 +72,8 @@ function buildRedirectResponse(req, redirect, pathPrefix = "") {
|
|
|
36
72
|
async function multiTenant(req) {
|
|
37
73
|
const host = req.headers.get("host") || "";
|
|
38
74
|
const pathname = req.nextUrl.pathname;
|
|
39
|
-
|
|
75
|
+
const isMetadataFile = METADATA_FILES.includes(pathname);
|
|
76
|
+
if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {
|
|
40
77
|
return NextResponse.next();
|
|
41
78
|
}
|
|
42
79
|
const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
|
|
@@ -44,12 +81,23 @@ async function multiTenant(req) {
|
|
|
44
81
|
let hostStoreRef = null;
|
|
45
82
|
let hostResolved = false;
|
|
46
83
|
let hostStoreSuspended = false;
|
|
84
|
+
if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();
|
|
47
85
|
if (hostIdentifiesStore) {
|
|
48
86
|
try {
|
|
49
|
-
const { storeRef: storeRef2, domain, isSubDomain, suspended } = await getStoreByHost(host);
|
|
87
|
+
const { storeRef: storeRef2, domain, isSubDomain, suspended, externalUrl } = await getStoreByHost(host);
|
|
50
88
|
hostResolved = true;
|
|
51
89
|
hostStoreRef = storeRef2 || null;
|
|
52
90
|
hostStoreSuspended = suspended;
|
|
91
|
+
if (storeRef2) {
|
|
92
|
+
const external = externalThemeResponse(
|
|
93
|
+
req,
|
|
94
|
+
host,
|
|
95
|
+
storeRef2,
|
|
96
|
+
externalUrl
|
|
97
|
+
);
|
|
98
|
+
if (external) return external;
|
|
99
|
+
}
|
|
100
|
+
if (isMetadataFile) return NextResponse.next();
|
|
53
101
|
if (storeRef2) {
|
|
54
102
|
if (isSubDomain && domain && domain !== host) {
|
|
55
103
|
const url = publicNextUrl(req);
|
|
@@ -67,6 +115,7 @@ async function multiTenant(req) {
|
|
|
67
115
|
}
|
|
68
116
|
} catch (error) {
|
|
69
117
|
console.debug("Middleware error:", error);
|
|
118
|
+
if (isMetadataFile) return NextResponse.next();
|
|
70
119
|
hostResolved = false;
|
|
71
120
|
hostStoreRef = null;
|
|
72
121
|
}
|
|
@@ -94,11 +143,17 @@ async function multiTenant(req) {
|
|
|
94
143
|
}
|
|
95
144
|
}
|
|
96
145
|
const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
146
|
+
const downstream = downstreamRequestHeaders(
|
|
147
|
+
req,
|
|
148
|
+
!!hostStoreRef,
|
|
149
|
+
storeRef,
|
|
150
|
+
rotated
|
|
151
|
+
);
|
|
152
|
+
downstream.set(
|
|
153
|
+
REQUEST_PATH_HEADER,
|
|
154
|
+
`${req.nextUrl.pathname}${req.nextUrl.search}`
|
|
155
|
+
);
|
|
156
|
+
const init = { request: { headers: downstream } };
|
|
102
157
|
let response;
|
|
103
158
|
if (hostStoreRef) {
|
|
104
159
|
const url = req.nextUrl.clone();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { applyThemePreview, hasThemePreview } from \"../theme/preview-cookie\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level\n if (METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n\n if (hostIdentifiesStore) {\n try {\n const { storeRef, domain, isSubDomain, suspended } =\n await getStoreByHost(host);\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to custom domain\n if (isSubDomain && domain && domain !== host) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n if (storeRef) {\n const preview = applyThemePreview(\n req,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n if (preview) return preview;\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;\n const init = {\n request: {\n headers: downstreamRequestHeaders(req, !!hostStoreRef, storeRef, rotated),\n },\n };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n\n if (rotated && storeRef) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const preview = applyThemePreview(req, authCookiePath(storeRef, true));\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, true)\n );\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,uBAAuB;AACnD,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAG/B,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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S,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,GAAG,EAAG,UAAS,QAAQ,IAAI,gBAAgB,SAAS;AACxE,MAAI,SAAS;AACX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe,UAAU,IAAI;AAAA,IAC/B;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req))\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url);\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n\n if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();\n\n if (hostIdentifiesStore) {\n try {\n const { storeRef, domain, isSubDomain, suspended, externalUrl } =\n await getStoreByHost(host);\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next();\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to custom domain\n if (isSubDomain && domain && domain !== host) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next();\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n if (storeRef) {\n const preview = applyThemePreview(\n req,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n if (preview) return preview;\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n\n if (rotated && storeRef) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const preview = applyThemePreview(req, authCookiePath(storeRef, true));\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, true)\n );\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};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C,QAAM,UAAU,kBAAkB,KAAK,eAAe,UAAU,IAAI,CAAC;AACrE,MAAI,QAAS,QAAO;AAEpB,MAAI;AACF,UAAM,WAAW,MAAM,eAAe,UAAU,QAAQ;AACxD,QAAI,UAAU;AACZ,YAAM,MAAM,cAAc,GAAG;AAC7B,UAAI,WAAW,SAAS;AACxB,aAAO,aAAa,SAAS,KAAK,EAAE,QAAQ,SAAS,cAAc,CAAC;AAAA,IACtE;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,QAAQ;AACvD,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,GAAG,EAAG,UAAS,QAAQ,IAAI,gBAAgB,SAAS;AACxE,MAAI,SAAS;AACX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe,UAAU,IAAI;AAAA,IAC/B;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/request/request-path.ts"],"sourcesContent":["/**\n * The path and query the shopper asked for (`/store/<ref>/x?y` on the shared\n * host, `/x?y` on a store's own host), before the middleware's rewrite. Server\n * components cannot see the URL; this is how the store layout learns it.\n * The multi-tenant middleware always overwrites it, so a browser-supplied\n * value never survives.\n */\nexport const REQUEST_PATH_HEADER = \"x-ecomweb-request-path\";\n"],"mappings":"AAOO,MAAM,sBAAsB;","names":[]}
|
package/dist/server.d.ts
CHANGED
|
@@ -58,4 +58,22 @@ declare function resolveRootStoreRef(): Promise<string | null>;
|
|
|
58
58
|
/** The open theme preview's token, if any (server components only). */
|
|
59
59
|
declare function readThemePreviewToken(): Promise<string | null>;
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Where the store layout sends a request when the published theme is
|
|
63
|
+
* external, else null: the backstop for path-based access
|
|
64
|
+
* (`/store/<ref>/…` on the shared host), which the middleware cannot check
|
|
65
|
+
* because only the by-domain lookup carries `storefront_url`. Host-mapped
|
|
66
|
+
* requests are left to the middleware, which already decided them. Never
|
|
67
|
+
* while a preview is open, never to the request's own host, and null without
|
|
68
|
+
* a usable https URL (fail open).
|
|
69
|
+
*/
|
|
70
|
+
declare function externalThemeRedirectFor(request: {
|
|
71
|
+
headers: {
|
|
72
|
+
get(name: string): string | null;
|
|
73
|
+
};
|
|
74
|
+
}, storeRef: string, theme: {
|
|
75
|
+
kind: string;
|
|
76
|
+
external_url?: string | null;
|
|
77
|
+
} | null | undefined, previewOpen: boolean): string | null;
|
|
78
|
+
|
|
79
|
+
export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
|
package/dist/server.js
CHANGED
|
@@ -8,9 +8,11 @@ import { hasCustomerSession } from "./auth/session.js";
|
|
|
8
8
|
import { parseServerConfig, serverConfig } from "./config/server.js";
|
|
9
9
|
import { resolveRootStoreRef } from "./store-scope/root.js";
|
|
10
10
|
import { readThemePreviewToken } from "./theme/read-preview-token.js";
|
|
11
|
+
import { externalThemeRedirectFor } from "./theme/external-storefront.js";
|
|
11
12
|
export {
|
|
12
13
|
createAuthRoutes,
|
|
13
14
|
createBackendProxy,
|
|
15
|
+
externalThemeRedirectFor,
|
|
14
16
|
hasCustomerSession,
|
|
15
17
|
parseServerConfig,
|
|
16
18
|
readThemePreviewToken,
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,gCAAgC;","names":[]}
|
|
@@ -7,12 +7,14 @@ async function getStoreByHost(host) {
|
|
|
7
7
|
storeRef: null,
|
|
8
8
|
domain: null,
|
|
9
9
|
isSubDomain: false,
|
|
10
|
-
suspended: false
|
|
10
|
+
suspended: false,
|
|
11
|
+
externalUrl: null
|
|
11
12
|
};
|
|
12
13
|
}
|
|
13
14
|
let storeRef = null;
|
|
14
15
|
let domain = null;
|
|
15
16
|
let suspended = false;
|
|
17
|
+
let externalUrl = null;
|
|
16
18
|
const parts = host.split(".");
|
|
17
19
|
const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
|
|
18
20
|
const isSubDomain = host.indexOf(platformDomain) >= 0 && parts.length === 3;
|
|
@@ -22,6 +24,7 @@ async function getStoreByHost(host) {
|
|
|
22
24
|
if (foundStore?.ref) {
|
|
23
25
|
storeRef = foundStore.ref;
|
|
24
26
|
domain = foundStore.config?.custom_domain || null;
|
|
27
|
+
externalUrl = foundStore.storefront_url || null;
|
|
25
28
|
}
|
|
26
29
|
} catch (error) {
|
|
27
30
|
if (isStoreSuspendedError(error)) {
|
|
@@ -30,7 +33,7 @@ async function getStoreByHost(host) {
|
|
|
30
33
|
console.error("Store not found for host:", host);
|
|
31
34
|
}
|
|
32
35
|
}
|
|
33
|
-
return { storeRef, domain, isSubDomain, suspended };
|
|
36
|
+
return { storeRef, domain, isSubDomain, suspended, externalUrl };
|
|
34
37
|
}
|
|
35
38
|
export {
|
|
36
39
|
getStoreByHost
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport { publicConfig } from \"../config\";\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n */\nexport async function getStoreByHost(host: string): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n };\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n\n const parts = host.split(\".\");\n const platformDomain =\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const isSubDomain = host.indexOf(platformDomain) >= 0 && parts.length === 3;\n\n try {\n const lookupValue = isSubDomain ? parts[0] : host;\n const foundStore = await sdk.stores.getByDomain(lookupValue);\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else {\n console.error(\"Store not found for host:\", host);\n }\n }\n\n return { storeRef, domain, isSubDomain, suspended };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAM7B,eAAsB,eAAe,
|
|
1
|
+
{"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport { publicConfig } from \"../config\";\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n */\nexport async function getStoreByHost(host: string): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n };\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n\n const parts = host.split(\".\");\n const platformDomain =\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const isSubDomain = host.indexOf(platformDomain) >= 0 && parts.length === 3;\n\n try {\n const lookupValue = isSubDomain ? parts[0] : host;\n const foundStore = await sdk.stores.getByDomain(lookupValue);\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else {\n console.error(\"Store not found for host:\", host);\n }\n }\n\n return { storeRef, domain, isSubDomain, suspended, externalUrl };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAM7B,eAAsB,eAAe,MAalC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,IACf;AAAA,EACF;AAEA,MAAI,WAA0B;AAC9B,MAAI,SAAwB;AAC5B,MAAI,YAAY;AAChB,MAAI,cAA6B;AAEjC,QAAM,QAAQ,KAAK,MAAM,GAAG;AAC5B,QAAM,iBACJ,aAAa,EAAE,wBAAwB;AACzC,QAAM,cAAc,KAAK,QAAQ,cAAc,KAAK,KAAK,MAAM,WAAW;AAE1E,MAAI;AACF,UAAM,cAAc,cAAc,MAAM,CAAC,IAAI;AAC7C,UAAM,aAAa,MAAM,IAAI,OAAO,YAAY,WAAW;AAE3D,QAAI,YAAY,KAAK;AACnB,iBAAW,WAAW;AACtB,eAAS,WAAW,QAAQ,iBAAiB;AAC7C,oBAAc,WAAW,kBAAkB;AAAA,IAC7C;AAAA,EACF,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,GAAG;AAChC,kBAAY;AAAA,IACd,OAAO;AACL,cAAQ,MAAM,6BAA6B,IAAI;AAAA,IACjD;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,QAAQ,aAAa,WAAW,YAAY;AACjE;","names":[]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isHostMappedRequest } from "../auth/cookies.js";
|
|
2
|
+
import { REQUEST_PATH_HEADER } from "../request/request-path.js";
|
|
3
|
+
function externalStorefrontUrl(base, path, search) {
|
|
4
|
+
if (!base) return null;
|
|
5
|
+
let url;
|
|
6
|
+
try {
|
|
7
|
+
url = new URL(base);
|
|
8
|
+
} catch {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
if (url.protocol !== "https:") return null;
|
|
12
|
+
const basePath = url.pathname.replace(/\/+$/, "");
|
|
13
|
+
const rel = path.startsWith("/") ? path : `/${path}`;
|
|
14
|
+
url.pathname = rel === "/" ? basePath || "/" : `${basePath}${rel}`;
|
|
15
|
+
url.search = search;
|
|
16
|
+
url.hash = "";
|
|
17
|
+
return url;
|
|
18
|
+
}
|
|
19
|
+
function isSameHost(host, hostname) {
|
|
20
|
+
const name = host.split(":")[0]?.trim().toLowerCase();
|
|
21
|
+
return !!name && name === hostname.toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
function externalThemeRedirectFor(request, storeRef, theme, previewOpen) {
|
|
24
|
+
if (theme?.kind !== "external" || previewOpen) return null;
|
|
25
|
+
if (isHostMappedRequest(request)) return null;
|
|
26
|
+
const requested = request.headers.get(REQUEST_PATH_HEADER) || "/";
|
|
27
|
+
const queryAt = requested.indexOf("?");
|
|
28
|
+
const rawPath = queryAt < 0 ? requested : requested.slice(0, queryAt);
|
|
29
|
+
const search = queryAt < 0 ? "" : requested.slice(queryAt);
|
|
30
|
+
const path = rawPath.startsWith("/") ? rawPath : "/";
|
|
31
|
+
let logicalPath = path;
|
|
32
|
+
const match = /^\/store\/([^/]+)(\/.*)?$/.exec(path);
|
|
33
|
+
if (match) {
|
|
34
|
+
let segment = match[1] ?? "";
|
|
35
|
+
try {
|
|
36
|
+
segment = decodeURIComponent(segment);
|
|
37
|
+
} catch {
|
|
38
|
+
}
|
|
39
|
+
if (segment === storeRef) logicalPath = match[2] || "/";
|
|
40
|
+
}
|
|
41
|
+
const target = externalStorefrontUrl(theme.external_url, logicalPath, search);
|
|
42
|
+
if (!target) return null;
|
|
43
|
+
if (isSameHost(request.headers.get("host") || "", target.hostname))
|
|
44
|
+
return null;
|
|
45
|
+
return target.toString();
|
|
46
|
+
}
|
|
47
|
+
export {
|
|
48
|
+
externalStorefrontUrl,
|
|
49
|
+
externalThemeRedirectFor,
|
|
50
|
+
isSameHost
|
|
51
|
+
};
|
|
52
|
+
//# sourceMappingURL=external-storefront.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/theme/external-storefront.ts"],"sourcesContent":["import { isHostMappedRequest } from \"../auth/cookies\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\n\n/**\n * Where a shopper's request goes when the store's live theme is external\n * (theme anatomy spec, \"Storefront\"): the external site's URL with the\n * request's path under its own path, and the query kept.\n *\n * `path` is the store-root-relative path as the request carried it (already\n * percent-encoded); `search` is `\"\"` or starts with `?`. Null unless `base`\n * is an https URL, so a missing or bad value never redirects (fail open).\n */\nexport function externalStorefrontUrl(\n base: string | null | undefined,\n path: string,\n search: string\n): URL | null {\n if (!base) return null;\n let url: URL;\n try {\n url = new URL(base);\n } catch {\n return null;\n }\n if (url.protocol !== \"https:\") return null;\n const basePath = url.pathname.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n url.pathname = rel === \"/\" ? basePath || \"/\" : `${basePath}${rel}`;\n url.search = search;\n url.hash = \"\";\n return url;\n}\n\n/** True when `host` (a Host header, port allowed) is `hostname`. */\nexport function isSameHost(host: string, hostname: string): boolean {\n const name = host.split(\":\")[0]?.trim().toLowerCase();\n return !!name && name === hostname.toLowerCase();\n}\n\n/**\n * Where the store layout sends a request when the published theme is\n * external, else null: the backstop for path-based access\n * (`/store/<ref>/…` on the shared host), which the middleware cannot check\n * because only the by-domain lookup carries `storefront_url`. Host-mapped\n * requests are left to the middleware, which already decided them. Never\n * while a preview is open, never to the request's own host, and null without\n * a usable https URL (fail open).\n */\nexport function externalThemeRedirectFor(\n request: { headers: { get(name: string): string | null } },\n storeRef: string,\n // The store's published theme (`PublishedStoreTheme` from @ecomweb/sdk).\n theme: { kind: string; external_url?: string | null } | null | undefined,\n previewOpen: boolean\n): string | null {\n if (theme?.kind !== \"external\" || previewOpen) return null;\n if (isHostMappedRequest(request)) return null;\n\n const requested = request.headers.get(REQUEST_PATH_HEADER) || \"/\";\n const queryAt = requested.indexOf(\"?\");\n const rawPath = queryAt < 0 ? requested : requested.slice(0, queryAt);\n const search = queryAt < 0 ? \"\" : requested.slice(queryAt);\n const path = rawPath.startsWith(\"/\") ? rawPath : \"/\";\n\n let logicalPath = path;\n const match = /^\\/store\\/([^/]+)(\\/.*)?$/.exec(path);\n if (match) {\n let segment = match[1] ?? \"\";\n try {\n segment = decodeURIComponent(segment);\n } catch {\n // keep the raw segment\n }\n if (segment === storeRef) logicalPath = match[2] || \"/\";\n }\n\n const target = externalStorefrontUrl(theme.external_url, logicalPath, search);\n if (!target) return null;\n if (isSameHost(request.headers.get(\"host\") || \"\", target.hostname))\n return null;\n return target.toString();\n}\n"],"mappings":"AAAA,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AAW7B,SAAS,sBACd,MACA,MACA,QACY;AACZ,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI;AACJ,MAAI;AACF,UAAM,IAAI,IAAI,IAAI;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,IAAI,aAAa,SAAU,QAAO;AACtC,QAAM,WAAW,IAAI,SAAS,QAAQ,QAAQ,EAAE;AAChD,QAAM,MAAM,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI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.5.0",
|
|
4
4
|
"description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"currency.js": "^2.0.4",
|
|
48
48
|
"server-only": "^0.0.1",
|
|
49
49
|
"zod": "^4.1.12",
|
|
50
|
-
"@ecomweb/sdk": "^0.
|
|
50
|
+
"@ecomweb/sdk": "^0.5.0"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"next": ">=16",
|