@ecomweb/storefront-kit 0.14.1 → 0.15.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 +25 -1
- package/bin/check-client-bundle-lib.d.mts +16 -0
- package/bin/check-client-bundle-lib.mjs +58 -0
- package/bin/check-client-bundle.d.mts +11 -0
- package/bin/check-client-bundle.mjs +8 -0
- package/dist/api/client.js +39 -0
- package/dist/api/client.js.map +1 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/proxy-guard.js +29 -0
- package/dist/api/proxy-guard.js.map +1 -0
- package/dist/api/proxy-routes.js +126 -0
- package/dist/api/proxy-routes.js.map +1 -0
- package/dist/api/proxy.js +17 -4
- package/dist/api/proxy.js.map +1 -1
- package/dist/api/server-sdk.js +41 -0
- package/dist/api/server-sdk.js.map +1 -0
- package/dist/api/store-preview-header.js.map +1 -1
- package/dist/auth/sdk.js +15 -5
- package/dist/auth/sdk.js.map +1 -1
- package/dist/auth/session-refresh.js +7 -4
- package/dist/auth/session-refresh.js.map +1 -1
- package/dist/cart/api.js.map +1 -1
- package/dist/checkout/get-payment-state.js +4 -8
- package/dist/checkout/get-payment-state.js.map +1 -1
- package/dist/checkout/initiate-gateway-payment.js +5 -7
- package/dist/checkout/initiate-gateway-payment.js.map +1 -1
- package/dist/checkout/order-handoff.js.map +1 -1
- package/dist/checkout/payment-redirect.js.map +1 -1
- package/dist/client-info.js +1 -1
- package/dist/config/public.js +2 -0
- package/dist/config/public.js.map +1 -1
- package/dist/config/schema.js +16 -4
- package/dist/config/schema.js.map +1 -1
- package/dist/config/secret-guard.js +20 -0
- package/dist/config/secret-guard.js.map +1 -0
- package/dist/config/server.js +15 -8
- package/dist/config/server.js.map +1 -1
- package/dist/config.d.ts +14 -4
- package/dist/config.js +2 -0
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +25 -68
- package/dist/index.js.map +1 -1
- package/dist/middleware/create-storefront-middleware.js +14 -3
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/{mode-DXo-EhTJ.d.ts → mode-oVZCQxrc.d.ts} +1 -1
- package/dist/orders/api-client.js +3 -3
- package/dist/orders/api-client.js.map +1 -1
- package/dist/orders/bank-transfer.js +1 -1
- package/dist/orders/bank-transfer.js.map +1 -1
- package/dist/orders/use-order-status.js +2 -2
- package/dist/orders/use-order-status.js.map +1 -1
- package/dist/promotions/use-promotion-validation.js +2 -2
- package/dist/promotions/use-promotion-validation.js.map +1 -1
- package/dist/request/served-store.js +5 -0
- package/dist/request/served-store.js.map +1 -0
- package/dist/{schema-DIF0CZNV.d.ts → schema-B3nAYiwT.d.ts} +1 -1
- package/dist/sdk.js +3 -3
- package/dist/sdk.js.map +1 -1
- package/dist/server/routes.js +16 -9
- package/dist/server/routes.js.map +1 -1
- package/dist/server.d.ts +38 -5
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/shipping/use-shipping-calculation.js +2 -2
- package/dist/shipping/use-shipping-calculation.js.map +1 -1
- package/package.json +6 -2
- package/dist/api/server-client.js +0 -162
- package/dist/api/server-client.js.map +0 -1
package/dist/middleware.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
-
import { S as StorefrontMode } from './mode-
|
|
3
|
-
import './schema-
|
|
2
|
+
import { S as StorefrontMode } from './mode-oVZCQxrc.js';
|
|
3
|
+
import './schema-B3nAYiwT.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createStoreSdk
|
|
1
|
+
import { createStoreSdk } from "../sdk.js";
|
|
2
2
|
const publicOrdersApi = {
|
|
3
3
|
async getPublicOrderStatus(storeRef, orderNumber, contactInfo) {
|
|
4
|
-
const result = await
|
|
4
|
+
const result = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {
|
|
5
5
|
order_number: orderNumber,
|
|
6
6
|
customer_email: contactInfo.email,
|
|
7
7
|
customer_phone: contactInfo.phone
|
|
@@ -12,7 +12,7 @@ const publicOrdersApi = {
|
|
|
12
12
|
* `isAuth` comes from the caller's auth context — this module is not a
|
|
13
13
|
* component and must not read context or an httpOnly cookie itself.
|
|
14
14
|
*
|
|
15
|
-
* When true the SDK posts to `/
|
|
15
|
+
* When true the SDK posts to `/storefront/stores/:ref/customers/orders`, which
|
|
16
16
|
* derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`
|
|
17
17
|
* (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no
|
|
18
18
|
* such fields to carry them in. The request reaches that guarded route
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk
|
|
1
|
+
{"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/storefront/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,sBAAsB;AAGxB,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,eAAe,QAAQ,EAAE,OAAO,YAAY,UAAU;AAAA,MACzE,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -29,7 +29,7 @@ function useBankTransferDetails(enabled) {
|
|
|
29
29
|
(async () => {
|
|
30
30
|
try {
|
|
31
31
|
const res = await publicApiClient.get(
|
|
32
|
-
`/
|
|
32
|
+
`/storefront/stores/${encodeURIComponent(storeRef)}/payment-methods`
|
|
33
33
|
);
|
|
34
34
|
const picked = pickBankTransfer(unwrap(res));
|
|
35
35
|
if (cancelled) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/orders/bank-transfer.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport { useStoreId } from \"../store/store-context\";\n\n/** The bank_transfer slice of the public payment-methods projection. */\nexport interface BankAccountView {\n id: number;\n bank_name: string;\n bank_code: string;\n account_number: string;\n account_holder: string;\n}\n\ninterface PublicPaymentMethod {\n payment_method: string;\n transfer_instruction?: string | null;\n bank_accounts?: BankAccountView[];\n}\n\n/** What a shopper needs to pay a bank transfer order. */\nexport interface BankTransferDetails {\n accounts: BankAccountView[];\n /** The merchant's transfer instruction, if they wrote one. */\n note: string | null;\n isLoading: boolean;\n}\n\n/**\n * Whether an order page should tell the shopper how to pay by transfer: a\n * bank_transfer order the merchant has not marked paid yet, and that is\n * still live. Order pages read this from the order itself, so they work for\n * any order, long after the checkout handoff has expired.\n */\nexport function shouldShowBankTransferDetails(\n order:\n | {\n payment_method?: string | null;\n payment_status?: string | null;\n order_status?: string | null;\n }\n | null\n | undefined\n): boolean {\n if (!order) return false;\n return (\n order.payment_method === \"bank_transfer\" &&\n order.payment_status === \"pending\" &&\n order.order_status !== \"cancelled\"\n );\n}\n\n/**\n * The bank_transfer method's accounts and instruction out of the public\n * payment-methods response. A store without the method, or a malformed\n * response, yields no accounts.\n */\nexport function pickBankTransfer(methods: unknown): {\n accounts: BankAccountView[];\n note: string | null;\n} {\n const list = Array.isArray(methods) ? (methods as PublicPaymentMethod[]) : [];\n const transfer = list.find(m => m?.payment_method === \"bank_transfer\");\n return {\n accounts: Array.isArray(transfer?.bank_accounts)\n ? transfer.bank_accounts\n : [],\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n note: transfer?.transfer_instruction || null,\n };\n}\n\n/**\n * The store's bank accounts and transfer instruction, fetched from the\n * public payment-methods endpoint while `enabled`. Used by the order-success\n * page and by the order lookup and account order pages.\n */\nexport function useBankTransferDetails(enabled: boolean): BankTransferDetails {\n const storeRef = useStoreId();\n const [accounts, setAccounts] = useState<BankAccountView[]>([]);\n const [note, setNote] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n if (!enabled || !storeRef) return;\n let cancelled = false;\n setIsLoading(true);\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/
|
|
1
|
+
{"version":3,"sources":["../../src/orders/bank-transfer.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport { useStoreId } from \"../store/store-context\";\n\n/** The bank_transfer slice of the public payment-methods projection. */\nexport interface BankAccountView {\n id: number;\n bank_name: string;\n bank_code: string;\n account_number: string;\n account_holder: string;\n}\n\ninterface PublicPaymentMethod {\n payment_method: string;\n transfer_instruction?: string | null;\n bank_accounts?: BankAccountView[];\n}\n\n/** What a shopper needs to pay a bank transfer order. */\nexport interface BankTransferDetails {\n accounts: BankAccountView[];\n /** The merchant's transfer instruction, if they wrote one. */\n note: string | null;\n isLoading: boolean;\n}\n\n/**\n * Whether an order page should tell the shopper how to pay by transfer: a\n * bank_transfer order the merchant has not marked paid yet, and that is\n * still live. Order pages read this from the order itself, so they work for\n * any order, long after the checkout handoff has expired.\n */\nexport function shouldShowBankTransferDetails(\n order:\n | {\n payment_method?: string | null;\n payment_status?: string | null;\n order_status?: string | null;\n }\n | null\n | undefined\n): boolean {\n if (!order) return false;\n return (\n order.payment_method === \"bank_transfer\" &&\n order.payment_status === \"pending\" &&\n order.order_status !== \"cancelled\"\n );\n}\n\n/**\n * The bank_transfer method's accounts and instruction out of the public\n * payment-methods response. A store without the method, or a malformed\n * response, yields no accounts.\n */\nexport function pickBankTransfer(methods: unknown): {\n accounts: BankAccountView[];\n note: string | null;\n} {\n const list = Array.isArray(methods) ? (methods as PublicPaymentMethod[]) : [];\n const transfer = list.find(m => m?.payment_method === \"bank_transfer\");\n return {\n accounts: Array.isArray(transfer?.bank_accounts)\n ? transfer.bank_accounts\n : [],\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n note: transfer?.transfer_instruction || null,\n };\n}\n\n/**\n * The store's bank accounts and transfer instruction, fetched from the\n * public payment-methods endpoint while `enabled`. Used by the order-success\n * page and by the order lookup and account order pages.\n */\nexport function useBankTransferDetails(enabled: boolean): BankTransferDetails {\n const storeRef = useStoreId();\n const [accounts, setAccounts] = useState<BankAccountView[]>([]);\n const [note, setNote] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n if (!enabled || !storeRef) return;\n let cancelled = false;\n setIsLoading(true);\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/storefront/stores/${encodeURIComponent(storeRef)}/payment-methods`\n );\n const picked = pickBankTransfer(unwrap(res));\n if (cancelled) return;\n setAccounts(picked.accounts);\n setNote(picked.note);\n } catch {\n // The order exists either way; no accounts renders a \"contact the\n // shop\" fallback rather than an error.\n if (!cancelled) {\n setAccounts([]);\n setNote(null);\n }\n } finally {\n if (!cancelled) setIsLoading(false);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [enabled, storeRef]);\n\n return { accounts, note, isLoading };\n}\n"],"mappings":";AAEA,SAAS,WAAW,gBAAgB;AACpC,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,kBAAkB;AA+BpB,SAAS,8BACd,OAQS;AACT,MAAI,CAAC,MAAO,QAAO;AACnB,SACE,MAAM,mBAAmB,mBACzB,MAAM,mBAAmB,aACzB,MAAM,iBAAiB;AAE3B;AAOO,SAAS,iBAAiB,SAG/B;AACA,QAAM,OAAO,MAAM,QAAQ,OAAO,IAAK,UAAoC,CAAC;AAC5E,QAAM,WAAW,KAAK,KAAK,OAAK,GAAG,mBAAmB,eAAe;AACrE,SAAO;AAAA,IACL,UAAU,MAAM,QAAQ,UAAU,aAAa,IAC3C,SAAS,gBACT,CAAC;AAAA;AAAA;AAAA,IAGL,MAAM,UAAU,wBAAwB;AAAA,EAC1C;AACF;AAOO,SAAS,uBAAuB,SAAuC;AAC5E,QAAM,WAAW,WAAW;AAC5B,QAAM,CAAC,UAAU,WAAW,IAAI,SAA4B,CAAC,CAAC;AAC9D,QAAM,CAAC,MAAM,OAAO,IAAI,SAAwB,IAAI;AACpD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,QAAI,CAAC,WAAW,CAAC,SAAU;AAC3B,QAAI,YAAY;AAChB,iBAAa,IAAI;AACjB,KAAC,YAAY;AACX,UAAI;AACF,cAAM,MAAM,MAAM,gBAAgB;AAAA,UAChC,sBAAsB,mBAAmB,QAAQ,CAAC;AAAA,QACpD;AACA,cAAM,SAAS,iBAAiB,OAAO,GAAG,CAAC;AAC3C,YAAI,UAAW;AACf,oBAAY,OAAO,QAAQ;AAC3B,gBAAQ,OAAO,IAAI;AAAA,MACrB,QAAQ;AAGN,YAAI,CAAC,WAAW;AACd,sBAAY,CAAC,CAAC;AACd,kBAAQ,IAAI;AAAA,QACd;AAAA,MACF,UAAE;AACA,YAAI,CAAC,UAAW,cAAa,KAAK;AAAA,MACpC;AAAA,IACF,GAAG;AACH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,SAAS,QAAQ,CAAC;AAEtB,SAAO,EAAE,UAAU,MAAM,UAAU;AACrC;","names":[]}
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveInitialState,
|
|
8
8
|
shouldPollForConfirmation
|
|
9
9
|
} from "../checkout/success-state.js";
|
|
10
|
-
import {
|
|
10
|
+
import { createStoreSdk } from "../sdk.js";
|
|
11
11
|
import { useStoreId } from "../store/store-context.js";
|
|
12
12
|
import { useBankTransferDetails } from "./bank-transfer.js";
|
|
13
13
|
const CANCELLED = new Error("order status: unmounted");
|
|
@@ -83,7 +83,7 @@ function useOrderLookup({
|
|
|
83
83
|
try {
|
|
84
84
|
setIsLoading(true);
|
|
85
85
|
setError(null);
|
|
86
|
-
const found = await
|
|
86
|
+
const found = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {
|
|
87
87
|
order_code: orderCode,
|
|
88
88
|
customer_email: email || void 0,
|
|
89
89
|
customer_phone: phone || void 0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { createStoreSdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\nimport { useBankTransferDetails } from \"./bank-transfer\";\n\nexport type { BankAccountView } from \"./bank-transfer\";\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n const bankTransfer = useBankTransferDetails(state === \"awaiting-transfer\");\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,sBAAsB;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AAIvC,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,MAAM,cAAc,CAAC,OACnB,IAAI,QAAc,aAAW,WAAW,SAAS,EAAE,CAAC;AAW/C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA,OAAO;AACT,GAIG;AACD,QAAM,WAAW,WAAW;AAI5B,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8B,IAAI;AAChE,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAS,KAAK;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IAAmC,MAC3D,oBAAoB,WAAW,IAAI;AAAA,EACrC;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,UAAM,SAAS,iBAAiB,SAAS;AACzC,eAAW,MAAM;AACjB,aAAS,oBAAoB,WAAW,MAAM,CAAC;AAC/C,qBAAiB,IAAI;AAAA,EACvB,GAAG,CAAC,SAAS,CAAC;AAId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M,eAAe,QAAQ,EAAE,OAAO,YAAY,UAAU;AAAA,QACxE,YAAY;AAAA,QACZ,gBAAgB,SAAS;AAAA,QACzB,gBAAgB,SAAS;AAAA,MAC3B,CAAC;AACD,UAAI,CAAC,OAAO;AACV,iBAAS,gGAAmD;AAC5D;AAAA,MACF;AACA,eAAS,KAAK;AAAA,IAChB,SAAS,KAAK;AAEZ,cAAQ,MAAM,yBAAyB,GAAG;AAC1C,eAAS,mEAAoC;AAAA,IAC/C,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,UAAU,WAAW,OAAO,KAAK,CAAC;AAEtC,YAAU,MAAM;AACd,eAAW;AAAA,EACb,GAAG,CAAC,UAAU,CAAC;AAEf,SAAO,EAAE,OAAO,WAAW,OAAO,OAAO,WAAW;AACtD;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createStoreSdk } from "../sdk.js";
|
|
2
2
|
import { useState, useCallback, useEffect, useRef } from "react";
|
|
3
3
|
import { useNotify } from "../notices.js";
|
|
4
4
|
class PromotionRejected extends Error {
|
|
@@ -25,7 +25,7 @@ function usePromotionValidation({
|
|
|
25
25
|
setIsValidatingPromo(true);
|
|
26
26
|
setPromoError("");
|
|
27
27
|
try {
|
|
28
|
-
const result = await
|
|
28
|
+
const result = await createStoreSdk(storeRef).promotions.validate(storeRef, {
|
|
29
29
|
code: codeToValidate.trim(),
|
|
30
30
|
items: items.map((item) => ({
|
|
31
31
|
product_id: item.productId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useNotify } from \"../notices\";\n\ninterface CartItem {\n productId: number;\n variantId: number | null;\n quantity: number;\n price: number;\n}\n\ninterface UsePromotionValidationProps {\n storeRef: string;\n items: CartItem[];\n subtotal: number;\n shippingFee: number;\n}\n\n/** The API answered: this code does not apply (unknown, expired, not eligible). */\nclass PromotionRejected extends Error {}\n\nexport function usePromotionValidation({\n storeRef,\n items,\n subtotal,\n shippingFee,\n}: UsePromotionValidationProps) {\n const [promoCode, setPromoCode] = useState<string>(\"\");\n const [appliedPromotion, setAppliedPromotion] = useState<any>(null);\n // Computed by the API against the shipping fee we sent; the same number the\n // server uses when the order is placed, so we never derive it ourselves.\n const [shippingDiscount, setShippingDiscount] = useState<number>(0);\n const [isValidatingPromo, setIsValidatingPromo] = useState(false);\n const [promoError, setPromoError] = useState<string>(\"\");\n const notify = useNotify();\n\n // Validate promotion code with specific code\n const validatePromoCodeWithCode = useCallback(\n async (code?: string) => {\n const codeToValidate = code || promoCode;\n\n if (!codeToValidate.trim()) {\n setPromoError(\"Vui lòng nhập mã khuyến mãi\");\n return;\n }\n\n setIsValidatingPromo(true);\n setPromoError(\"\");\n\n try {\n const result = await createStoreSdk(storeRef).promotions.validate(storeRef, {\n code: codeToValidate.trim(),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId ?? undefined,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal: subtotal,\n shipping_fee: shippingFee,\n });\n\n if (!result.success) {\n throw new PromotionRejected(\n result.message || \"Mã khuyến mãi không hợp lệ\"\n );\n }\n\n // Add code to promotion object for tracking\n const promotionWithCode = {\n ...result.promotion,\n code: codeToValidate.trim(),\n };\n setAppliedPromotion(promotionWithCode);\n setShippingDiscount(result.shipping_discount ?? 0);\n notify({\n kind: \"success\",\n code: \"promotion.applied\",\n title: \"Áp dụng mã khuyến mãi thành công\",\n description: `${result.promotion?.name || \"\"} đã được áp dụng`,\n });\n } catch (error) {\n // A rejected code is an ordinary answer, shown to the shopper; only\n // unexpected failures (network, server) are worth logging.\n if (!(error instanceof PromotionRejected)) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to validate promotion code:\", error);\n }\n setPromoError(\n error instanceof Error ? error.message : \"Mã khuyến mãi không hợp lệ\"\n );\n setAppliedPromotion(null);\n setShippingDiscount(0);\n } finally {\n setIsValidatingPromo(false);\n }\n },\n [storeRef, items, subtotal, shippingFee, promoCode, notify]\n );\n\n // The server computes the shipping discount against the shipping fee we sent\n // it, so the number goes stale the moment the fee changes (new address, new\n // method). Re-ask rather than recomputing locally — a local recomputation is\n // exactly the duplicated money logic this hook exists to avoid.\n const revalidateRef = useRef(validatePromoCodeWithCode);\n revalidateRef.current = validatePromoCodeWithCode;\n\n useEffect(() => {\n const code = appliedPromotion?.code;\n if (!code) return;\n void revalidateRef.current(code);\n // Intentionally keyed on the fee alone: including the callback would\n // re-run this on every render, and including appliedPromotion would loop\n // on the state this very effect writes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shippingFee]);\n\n // Validate promotion code\n const validatePromoCode = useCallback(async () => {\n await validatePromoCodeWithCode();\n }, [validatePromoCodeWithCode]);\n\n // Remove applied promotion\n const removePromoCode = useCallback(() => {\n setPromoCode(\"\");\n setAppliedPromotion(null);\n setShippingDiscount(0);\n setPromoError(\"\");\n }, []);\n\n // Apply promotion from suggestion\n const applyPromotionFromSuggestion = useCallback(\n async (code: string) => {\n setPromoCode(code);\n // Use the code directly instead of relying on state\n await validatePromoCodeWithCode(code);\n },\n [validatePromoCodeWithCode]\n );\n\n return {\n promoCode,\n appliedPromotion,\n shippingDiscount,\n isValidatingPromo,\n promoError,\n setPromoCode,\n validatePromoCode,\n removePromoCode,\n applyPromotionFromSuggestion,\n };\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAC/B,SAAS,UAAU,aAAa,WAAW,cAAc;AACzD,SAAS,iBAAiB;AAiB1B,MAAM,0BAA0B,MAAM;AAAC;AAEhC,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,CAAC,WAAW,YAAY,IAAI,SAAiB,EAA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B,QAAQ,MAAM,UAAU;AAAA,QAC3C;AACA,4BAAoB,IAAI;AACxB,4BAAoB,CAAC;AAAA,MACvB,UAAE;AACA,6BAAqB,KAAK;AAAA,MAC5B;AAAA,IACF;AAAA,IACA,CAAC,UAAU,OAAO,UAAU,aAAa,WAAW,MAAM;AAAA,EAC5D;AAMA,QAAM,gBAAgB,OAAO,yBAAyB;AACtD,gBAAc,UAAU;AAExB,YAAU,MAAM;AACd,UAAM,OAAO,kBAAkB;AAC/B,QAAI,CAAC,KAAM;AACX,SAAK,cAAc,QAAQ,IAAI;AAAA,EAKjC,GAAG,CAAC,WAAW,CAAC;AAGhB,QAAM,oBAAoB,YAAY,YAAY;AAChD,UAAM,0BAA0B;AAAA,EAClC,GAAG,CAAC,yBAAyB,CAAC;AAG9B,QAAM,kBAAkB,YAAY,MAAM;AACxC,iBAAa,EAAE;AACf,wBAAoB,IAAI;AACxB,wBAAoB,CAAC;AACrB,kBAAc,EAAE;AAAA,EAClB,GAAG,CAAC,CAAC;AAGL,QAAM,+BAA+B;AAAA,IACnC,OAAO,SAAiB;AACtB,mBAAa,IAAI;AAEjB,YAAM,0BAA0B,IAAI;AAAA,IACtC;AAAA,IACA,CAAC,yBAAyB;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/request/served-store.ts"],"sourcesContent":["/**\n * The store this request serves, stamped by the middleware (the host's store\n * on a store host, the path's store on localhost, the configured one in single\n * mode). The middleware always deletes any client copy first, so a server-side\n * reader can trust it. Absent when no store was resolved. No `server-only`:\n * the middleware imports it.\n */\nexport const SERVED_STORE_HEADER = \"x-ecomweb-served-store\";\n"],"mappings":"AAOO,MAAM,sBAAsB;","names":[]}
|
|
@@ -27,7 +27,7 @@ declare const publicConfigSchema: z.ZodObject<{
|
|
|
27
27
|
}, z.core.$strip>;
|
|
28
28
|
type PublicConfig = z.infer<typeof publicConfigSchema>;
|
|
29
29
|
declare const serverConfigSchema: z.ZodObject<{
|
|
30
|
-
|
|
30
|
+
secretKey: z.ZodString;
|
|
31
31
|
clientIpForwarderSecret: z.ZodOptional<z.ZodString>;
|
|
32
32
|
appBaseUrl: z.ZodString;
|
|
33
33
|
appEnv: z.ZodString;
|
package/dist/sdk.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEcomwebSdk } from "@ecomweb/sdk";
|
|
1
|
+
import { createEcomwebProxiedSdk, createEcomwebSdk } from "@ecomweb/sdk";
|
|
2
2
|
import { createStoreApiClient, publicApiClient } from "./api/client.js";
|
|
3
3
|
import { KIT_CLIENT_TOKEN } from "./client-info.js";
|
|
4
4
|
function requireStoreScopedSdk() {
|
|
@@ -21,9 +21,9 @@ const storeSdks = /* @__PURE__ */ new Map();
|
|
|
21
21
|
function createStoreSdk(storeRef) {
|
|
22
22
|
const cached = storeSdks.get(storeRef);
|
|
23
23
|
if (cached) return cached;
|
|
24
|
-
const created =
|
|
24
|
+
const created = createEcomwebProxiedSdk({
|
|
25
25
|
publicHttp: publicApiClient,
|
|
26
|
-
|
|
26
|
+
proxyHttp: createStoreApiClient(storeRef),
|
|
27
27
|
clientInfo: KIT_CLIENT_TOKEN
|
|
28
28
|
});
|
|
29
29
|
storeSdks.set(storeRef, created);
|
package/dist/sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type {
|
|
1
|
+
{"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebProxiedSdk, createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type {\n ApiResponse,\n EcomwebSdk,\n EcomwebServerSdk,\n IHttpClient,\n} from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\nimport { KIT_CLIENT_TOKEN } from \"./client-info\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk: EcomwebSdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n clientInfo: KIT_CLIENT_TOKEN,\n});\n\nconst storeSdks = new Map<string, EcomwebServerSdk>();\n\n/**\n * SDK bound to one store, for the browser. Public calls go straight to the\n * API with the publishable key; every private call (cart, orders, payments,\n * customers, addresses, shopper-side blog, review and metaobject calls, rate\n * calculation, promotion validation) goes to the same-origin proxy at\n * `/store/<ref>/api/backend` (`/api/backend` on a single-store site), which\n * adds the storefront secret key and turns the httpOnly session cookie into a\n * bearer token. The secret key never reaches the browser.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string): EcomwebServerSdk {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebProxiedSdk({\n publicHttp: publicApiClient as any,\n proxyHttp: createStoreApiClient(storeRef) as any,\n clientInfo: KIT_CLIENT_TOKEN,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,yBAAyB,wBAAwB;AAO1D,SAAS,sBAAsB,uBAAuB;AACtD,SAAS,wBAAwB;AAQjC,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAkB,iBAAiB;AAAA,EAC9C,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAAA,EAChC,YAAY;AACd,CAAC;AAED,MAAM,YAAY,oBAAI,IAA8B;AAc7C,SAAS,eAAe,UAAoC;AACjE,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,wBAAwB;AAAA,IACtC,YAAY;AAAA,IACZ,WAAW,qBAAqB,QAAQ;AAAA,IACxC,YAAY;AAAA,EACd,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
|
package/dist/server/routes.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import "server-only";
|
|
2
|
-
import { NextResponse } from "next/server";
|
|
3
2
|
import { redirect } from "next/navigation";
|
|
4
3
|
import { handleBackendProxy } from "../api/proxy.js";
|
|
4
|
+
import {
|
|
5
|
+
isSameOriginRequest,
|
|
6
|
+
proxyNotFound,
|
|
7
|
+
servedStoreRef
|
|
8
|
+
} from "../api/proxy-guard.js";
|
|
5
9
|
import { handleAuthRoute } from "../auth/route-handlers.js";
|
|
6
10
|
import { getServerIdentity } from "../auth/session.js";
|
|
7
11
|
import { resolveStoreRef } from "../store-scope/index.js";
|
|
@@ -12,18 +16,20 @@ async function storeRefFor(params) {
|
|
|
12
16
|
}
|
|
13
17
|
return resolveRootStoreRef();
|
|
14
18
|
}
|
|
15
|
-
function storeNotFound() {
|
|
16
|
-
return NextResponse.json(
|
|
17
|
-
{ error: { message: "Store not found for host" } },
|
|
18
|
-
{ status: 404 }
|
|
19
|
-
);
|
|
20
|
-
}
|
|
21
19
|
const segments = (v) => Array.isArray(v) ? v : v ? [v] : [];
|
|
20
|
+
function servesRouteStore(req, params) {
|
|
21
|
+
if (params.storeRef === void 0) return true;
|
|
22
|
+
return servedStoreRef(req) === params.storeRef;
|
|
23
|
+
}
|
|
22
24
|
function createAuthRoutes() {
|
|
23
25
|
const handle = async (req, { params }) => {
|
|
24
26
|
const p = await params;
|
|
27
|
+
if (!servesRouteStore(req, p)) return proxyNotFound();
|
|
28
|
+
if (req.method !== "GET" && !isSameOriginRequest(req)) {
|
|
29
|
+
return proxyNotFound();
|
|
30
|
+
}
|
|
25
31
|
const storeRef = await storeRefFor(p);
|
|
26
|
-
if (!storeRef) return
|
|
32
|
+
if (!storeRef) return proxyNotFound();
|
|
27
33
|
return handleAuthRoute(req, storeRef, segments(p.route));
|
|
28
34
|
};
|
|
29
35
|
return { GET: handle, POST: handle };
|
|
@@ -31,8 +37,9 @@ function createAuthRoutes() {
|
|
|
31
37
|
function createBackendProxy() {
|
|
32
38
|
const handle = async (req, { params }) => {
|
|
33
39
|
const p = await params;
|
|
40
|
+
if (!servesRouteStore(req, p)) return proxyNotFound();
|
|
34
41
|
const storeRef = await storeRefFor(p);
|
|
35
|
-
if (!storeRef) return
|
|
42
|
+
if (!storeRef) return proxyNotFound();
|
|
36
43
|
return handleBackendProxy(req, storeRef, segments(p.path));
|
|
37
44
|
};
|
|
38
45
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport type { NextRequest } from \"next/server\";\nimport { redirect } from \"next/navigation\";\nimport { handleBackendProxy } from \"../api/proxy\";\nimport {\n isSameOriginRequest,\n proxyNotFound,\n servedStoreRef,\n} from \"../api/proxy-guard\";\nimport { handleAuthRoute } from \"../auth/route-handlers\";\nimport { getServerIdentity } from \"../auth/session\";\nimport { resolveStoreRef } from \"../store-scope\";\nimport { resolveRootStoreRef } from \"../store-scope/root\";\n\ntype Params = Record<string, string | string[] | undefined>;\nexport type RouteContext = { params: Promise<Params> };\nexport type RouteHandler = (\n req: NextRequest,\n ctx: RouteContext\n) => Promise<Response>;\n\n/**\n * The store a route serves: the /store/<ref> segment when the route has one,\n * otherwise whatever the host (or, single-store, the config) names.\n */\nasync function storeRefFor(params: Params): Promise<string | null> {\n if (typeof params.storeRef === \"string\") {\n return resolveStoreRef(Promise.resolve({ storeRef: params.storeRef }));\n }\n return resolveRootStoreRef();\n}\n\nconst segments = (v: Params[string]): string[] =>\n Array.isArray(v) ? v : v ? [v] : [];\n\n/**\n * False when the route names a store (`/store/<ref>/...`) other than the one\n * the middleware stamped for this request, or when it stamped none. Routes\n * without the param take the store from the host or config instead.\n */\nfunction servesRouteStore(req: NextRequest, params: Params): boolean {\n if (params.storeRef === undefined) return true;\n return servedStoreRef(req) === params.storeRef;\n}\n\n/**\n * `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route].\n * These routes sign every shopper-auth call with the storefront secret key,\n * so they answer 404 for a `/store/<ref>` other than the one this request\n * serves, and for any non-GET request that is not same-origin (GETs stay\n * open: Google's OAuth callback arrives cross-site).\n */\nexport function createAuthRoutes(): { GET: RouteHandler; POST: RouteHandler } {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n if (!servesRouteStore(req, p)) return proxyNotFound();\n if (req.method !== \"GET\" && !isSameOriginRequest(req)) {\n return proxyNotFound();\n }\n const storeRef = await storeRefFor(p);\n if (!storeRef) return proxyNotFound();\n return handleAuthRoute(req, storeRef, segments(p.route));\n };\n return { GET: handle, POST: handle };\n}\n\n/**\n * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`\n * in api/backend/[...path]. It carries every private browser call under the\n * storefront secret key, so it forwards only same-origin calls to routes in\n * `PROXIED_STOREFRONT_ROUTES`, for the store this request serves, and answers\n * every other request 404 `NOT_FOUND`.\n */\nexport function createBackendProxy(): Record<\n \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n RouteHandler\n> {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n if (!servesRouteStore(req, p)) return proxyNotFound();\n const storeRef = await storeRefFor(p);\n if (!storeRef) return proxyNotFound();\n return handleBackendProxy(req, storeRef, segments(p.path));\n };\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n };\n}\n\nexport type CustomerIdentity = NonNullable<\n Awaited<ReturnType<typeof getServerIdentity>>\n>;\n\n/**\n * The signed-in customer, or a redirect to `redirectTo`. An anonymous\n * identity holds a valid token but no customer profile, so it redirects too.\n */\nexport async function requireSession(\n storeRef: string,\n redirectTo: string\n): Promise<CustomerIdentity> {\n const identity = await getServerIdentity(storeRef);\n if (!identity || identity.is_anonymous) redirect(redirectTo);\n return identity;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAapC,eAAe,YAAY,QAAwC;AACjE,MAAI,OAAO,OAAO,aAAa,UAAU;AACvC,WAAO,gBAAgB,QAAQ,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC,CAAC;AAAA,EACvE;AACA,SAAO,oBAAoB;AAC7B;AAEA,MAAM,WAAW,CAAC,MAChB,MAAM,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC;AAOpC,SAAS,iBAAiB,KAAkB,QAAyB;AACnE,MAAI,OAAO,aAAa,OAAW,QAAO;AAC1C,SAAO,eAAe,GAAG,MAAM,OAAO;AACxC;AASO,SAAS,mBAA8D;AAC5E,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,QAAI,CAAC,iBAAiB,KAAK,CAAC,EAAG,QAAO,cAAc;AACpD,QAAI,IAAI,WAAW,SAAS,CAAC,oBAAoB,GAAG,GAAG;AACrD,aAAO,cAAc;AAAA,IACvB;AACA,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,gBAAgB,KAAK,UAAU,SAAS,EAAE,KAAK,CAAC;AAAA,EACzD;AACA,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;AASO,SAAS,qBAGd;AACA,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,QAAI,CAAC,iBAAiB,KAAK,CAAC,EAAG,QAAO,cAAc;AACpD,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,mBAAmB,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC;AAAA,EAC3D;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAUA,eAAsB,eACpB,UACA,YAC2B;AAC3B,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,MAAI,CAAC,YAAY,SAAS,aAAc,UAAS,UAAU;AAC3D,SAAO;AACT;","names":[]}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NextRequest } from 'next/server';
|
|
2
|
-
import { CurrentIdentity } from '@ecomweb/sdk';
|
|
3
|
-
|
|
2
|
+
import { CurrentIdentity, EcomwebServerSdk } from '@ecomweb/sdk';
|
|
3
|
+
export { EcomwebSdk, EcomwebServerSdk } from '@ecomweb/sdk';
|
|
4
|
+
import { E as EnvSource, S as ServerConfig } from './schema-B3nAYiwT.js';
|
|
4
5
|
import 'zod';
|
|
5
6
|
|
|
6
7
|
/**
|
|
@@ -27,14 +28,23 @@ type RouteContext = {
|
|
|
27
28
|
params: Promise<Params>;
|
|
28
29
|
};
|
|
29
30
|
type RouteHandler = (req: NextRequest, ctx: RouteContext) => Promise<Response>;
|
|
30
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route].
|
|
33
|
+
* These routes sign every shopper-auth call with the storefront secret key,
|
|
34
|
+
* so they answer 404 for a `/store/<ref>` other than the one this request
|
|
35
|
+
* serves, and for any non-GET request that is not same-origin (GETs stay
|
|
36
|
+
* open: Google's OAuth callback arrives cross-site).
|
|
37
|
+
*/
|
|
31
38
|
declare function createAuthRoutes(): {
|
|
32
39
|
GET: RouteHandler;
|
|
33
40
|
POST: RouteHandler;
|
|
34
41
|
};
|
|
35
42
|
/**
|
|
36
43
|
* `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`
|
|
37
|
-
* in api/backend/[...path].
|
|
44
|
+
* in api/backend/[...path]. It carries every private browser call under the
|
|
45
|
+
* storefront secret key, so it forwards only same-origin calls to routes in
|
|
46
|
+
* `PROXIED_STOREFRONT_ROUTES`, for the store this request serves, and answers
|
|
47
|
+
* every other request 404 `NOT_FOUND`.
|
|
38
48
|
*/
|
|
39
49
|
declare function createBackendProxy(): Record<"GET" | "POST" | "PUT" | "PATCH" | "DELETE", RouteHandler>;
|
|
40
50
|
type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>>>;
|
|
@@ -44,6 +54,29 @@ type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>
|
|
|
44
54
|
*/
|
|
45
55
|
declare function requireSession(storeRef: string, redirectTo: string): Promise<CustomerIdentity>;
|
|
46
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The server SDK for the current request, signed with the storefront secret
|
|
59
|
+
* key, for private reads in server components and route handlers (for example
|
|
60
|
+
* a review invitation by token). The shopper's IP and the store preview token
|
|
61
|
+
* are taken from the request.
|
|
62
|
+
*
|
|
63
|
+
* Shopper-side methods (cart, orders, addresses and the like) do not work
|
|
64
|
+
* here: a server has no shopper session, so they reject with
|
|
65
|
+
* `SDK_SHOPPER_CALL_ON_SERVER`. Use `createStoreSdk(storeRef)` in the browser.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* import { getServerSdk } from "@ecomweb/storefront-kit/server";
|
|
70
|
+
*
|
|
71
|
+
* const sdk = await getServerSdk();
|
|
72
|
+
* const invitation = await sdk.reviews.getReviewInvitation(storeRef, token);
|
|
73
|
+
* ```
|
|
74
|
+
*
|
|
75
|
+
* @returns The server SDK for this request
|
|
76
|
+
* @throws Error when the storefront secret key is not set
|
|
77
|
+
*/
|
|
78
|
+
declare function getServerSdk(): Promise<EcomwebServerSdk>;
|
|
79
|
+
|
|
47
80
|
/** Parses the variables of the mode `env` selects (see resolveMode). */
|
|
48
81
|
declare function parseServerConfig(env: EnvSource): ServerConfig;
|
|
49
82
|
/**
|
|
@@ -109,4 +142,4 @@ declare function resolveComingSoonStore(): Promise<{
|
|
|
109
142
|
name: string | null;
|
|
110
143
|
} | null>;
|
|
111
144
|
|
|
112
|
-
export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
|
|
145
|
+
export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, getServerSdk, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
|
package/dist/server.js
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
createBackendProxy,
|
|
5
5
|
requireSession
|
|
6
6
|
} from "./server/routes.js";
|
|
7
|
+
import { getServerSdk } from "./api/server-sdk.js";
|
|
7
8
|
import { hasCustomerSession } from "./auth/session.js";
|
|
8
9
|
import { parseServerConfig, serverConfig } from "./config/server.js";
|
|
9
10
|
import { resolveRootStoreRef } from "./store-scope/root.js";
|
|
@@ -16,6 +17,7 @@ export {
|
|
|
16
17
|
createAuthRoutes,
|
|
17
18
|
createBackendProxy,
|
|
18
19
|
externalThemeRedirectFor,
|
|
20
|
+
getServerSdk,
|
|
19
21
|
hasCustomerSession,
|
|
20
22
|
parseServerConfig,
|
|
21
23
|
readPreviewHostSlug,
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only route handlers and helpers: the auth routes, the backend proxy,\n * session checks and the server config.\n *\n * Import from `@ecomweb/storefront-kit/server` in route handlers and server\n * components only; the entry imports `server-only` and fails in a client\n * bundle.\n *\n * @packageDocumentation\n */\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 { readStorePreviewToken } from \"./stores/read-store-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\nexport { resolveComingSoonStore } from \"./stores/resolve-coming-soon\";\n"],"mappings":"AAUA,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,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only route handlers and helpers: the auth routes, the backend proxy,\n * session checks and the server config.\n *\n * Import from `@ecomweb/storefront-kit/server` in route handlers and server\n * components only; the entry imports `server-only` and fails in a client\n * bundle.\n *\n * @packageDocumentation\n */\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 { getServerSdk } from \"./api/server-sdk\";\nexport type { EcomwebSdk, EcomwebServerSdk } from \"@ecomweb/sdk\";\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 { readStorePreviewToken } from \"./stores/read-store-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\nexport { resolveComingSoonStore } from \"./stores/resolve-coming-soon\";\n"],"mappings":"AAUA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,oBAAoB;AAE7B,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createStoreSdk } from "../sdk.js";
|
|
2
2
|
import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
|
|
3
3
|
import { SHIPPING_MESSAGES } from "./messages.js";
|
|
4
4
|
import { useNotify } from "../notices.js";
|
|
@@ -42,7 +42,7 @@ function useShippingCalculation({
|
|
|
42
42
|
const next = stateRef.current.requestId + 1;
|
|
43
43
|
dispatch({ type: "CALCULATION_STARTED" });
|
|
44
44
|
try {
|
|
45
|
-
const options = await
|
|
45
|
+
const options = await createStoreSdk(storeRef).shipping.calculate(storeRef, {
|
|
46
46
|
province_id: city,
|
|
47
47
|
ward_id: ward,
|
|
48
48
|
subtotal,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { isStoreComingSoonError } from \"../stores/store-coming-soon\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // A store preview is read-only and the API refuses this POST with\n // STORE_COMING_SOON, which would show as a shipping error. Say it is a\n // preview instead, like the cart and checkout writes do.\n if (isBrowserStorePreview()) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await createStoreSdk(storeRef).shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n if (isStoreComingSoonError(error)) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAC/B,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;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AA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecomweb/storefront-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -39,7 +39,11 @@
|
|
|
39
39
|
"publishConfig": {
|
|
40
40
|
"access": "public"
|
|
41
41
|
},
|
|
42
|
+
"bin": {
|
|
43
|
+
"ecomweb-check-client-bundle": "./bin/check-client-bundle.mjs"
|
|
44
|
+
},
|
|
42
45
|
"files": [
|
|
46
|
+
"bin",
|
|
43
47
|
"dist",
|
|
44
48
|
"README.md",
|
|
45
49
|
"LICENSE"
|
|
@@ -49,7 +53,7 @@
|
|
|
49
53
|
"currency.js": "^2.0.4",
|
|
50
54
|
"server-only": "^0.0.1",
|
|
51
55
|
"zod": "^4.1.12",
|
|
52
|
-
"@ecomweb/sdk": "^0.
|
|
56
|
+
"@ecomweb/sdk": "^0.15.0"
|
|
53
57
|
},
|
|
54
58
|
"peerDependencies": {
|
|
55
59
|
"next": ">=16",
|