@ecomweb/storefront-kit 0.2.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/LICENSE +21 -0
- package/README.md +55 -0
- package/dist/api/client.js +162 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/index.js +7 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/proxy.js +145 -0
- package/dist/api/proxy.js.map +1 -0
- package/dist/api/response.js +55 -0
- package/dist/api/response.js.map +1 -0
- package/dist/api/server-client.js +159 -0
- package/dist/api/server-client.js.map +1 -0
- package/dist/auth/client-ip.js +44 -0
- package/dist/auth/client-ip.js.map +1 -0
- package/dist/auth/context.js +125 -0
- package/dist/auth/context.js.map +1 -0
- package/dist/auth/cookies.js +97 -0
- package/dist/auth/cookies.js.map +1 -0
- package/dist/auth/error-copy.js +49 -0
- package/dist/auth/error-copy.js.map +1 -0
- package/dist/auth/password-policy.js +29 -0
- package/dist/auth/password-policy.js.map +1 -0
- package/dist/auth/route-handlers.js +337 -0
- package/dist/auth/route-handlers.js.map +1 -0
- package/dist/auth/safe-redirect.js +20 -0
- package/dist/auth/safe-redirect.js.map +1 -0
- package/dist/auth/sdk.js +76 -0
- package/dist/auth/sdk.js.map +1 -0
- package/dist/auth/session-refresh.js +81 -0
- package/dist/auth/session-refresh.js.map +1 -0
- package/dist/auth/session.js +26 -0
- package/dist/auth/session.js.map +1 -0
- package/dist/auth/use-public-auth-config.js +29 -0
- package/dist/auth/use-public-auth-config.js.map +1 -0
- package/dist/cart/api.js +60 -0
- package/dist/cart/api.js.map +1 -0
- package/dist/cart/server-context.js +279 -0
- package/dist/cart/server-context.js.map +1 -0
- package/dist/cart/types.js +1 -0
- package/dist/cart/types.js.map +1 -0
- package/dist/cart/utils.js +49 -0
- package/dist/cart/utils.js.map +1 -0
- package/dist/checkout/get-payment-state.js +15 -0
- package/dist/checkout/get-payment-state.js.map +1 -0
- package/dist/checkout/initiate-gateway-payment.js +13 -0
- package/dist/checkout/initiate-gateway-payment.js.map +1 -0
- package/dist/checkout/order-handoff.js +61 -0
- package/dist/checkout/order-handoff.js.map +1 -0
- package/dist/checkout/payment-redirect.js +11 -0
- package/dist/checkout/payment-redirect.js.map +1 -0
- package/dist/checkout/payment-state-poll.js +45 -0
- package/dist/checkout/payment-state-poll.js.map +1 -0
- package/dist/checkout/start-gateway-redirect.js +16 -0
- package/dist/checkout/start-gateway-redirect.js.map +1 -0
- package/dist/checkout/stock-issues.js +35 -0
- package/dist/checkout/stock-issues.js.map +1 -0
- package/dist/checkout/success-state.js +15 -0
- package/dist/checkout/success-state.js.map +1 -0
- package/dist/checkout/types.js +1 -0
- package/dist/checkout/types.js.map +1 -0
- package/dist/checkout/use-checkout.js +256 -0
- package/dist/checkout/use-checkout.js.map +1 -0
- package/dist/checkout/utils.js +7 -0
- package/dist/checkout/utils.js.map +1 -0
- package/dist/config/index.js +7 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/log-level.js +8 -0
- package/dist/config/log-level.js.map +1 -0
- package/dist/config/mode.js +18 -0
- package/dist/config/mode.js.map +1 -0
- package/dist/config/public.js +115 -0
- package/dist/config/public.js.map +1 -0
- package/dist/config/schema.js +70 -0
- package/dist/config/schema.js.map +1 -0
- package/dist/config/server.js +68 -0
- package/dist/config/server.js.map +1 -0
- package/dist/config.d.ts +16 -0
- package/dist/config.js +15 -0
- package/dist/config.js.map +1 -0
- package/dist/currency.js +68 -0
- package/dist/currency.js.map +1 -0
- package/dist/index.d.ts +968 -0
- package/dist/index.js +146 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces/api.types.js +1 -0
- package/dist/interfaces/api.types.js.map +1 -0
- package/dist/interfaces/index.js +2 -0
- package/dist/interfaces/index.js.map +1 -0
- package/dist/logging.js +42 -0
- package/dist/logging.js.map +1 -0
- package/dist/middleware/create-storefront-middleware.js +175 -0
- package/dist/middleware/create-storefront-middleware.js.map +1 -0
- package/dist/middleware.d.ts +24 -0
- package/dist/middleware.js +9 -0
- package/dist/middleware.js.map +1 -0
- package/dist/mode-1ZKDELPZ.d.ts +16 -0
- package/dist/notices.js +31 -0
- package/dist/notices.js.map +1 -0
- package/dist/orders/api-client.js +32 -0
- package/dist/orders/api-client.js.map +1 -0
- package/dist/orders/derive-progress.js +36 -0
- package/dist/orders/derive-progress.js.map +1 -0
- package/dist/orders/index.js +6 -0
- package/dist/orders/index.js.map +1 -0
- package/dist/orders/types.js +13 -0
- package/dist/orders/types.js.map +1 -0
- package/dist/orders/use-order-status.js +137 -0
- package/dist/orders/use-order-status.js.map +1 -0
- package/dist/promotions/use-promotion-validation.js +106 -0
- package/dist/promotions/use-promotion-validation.js.map +1 -0
- package/dist/promotions/utils.js +40 -0
- package/dist/promotions/utils.js.map +1 -0
- package/dist/provider.js +25 -0
- package/dist/provider.js.map +1 -0
- package/dist/redirects/index.js +2 -0
- package/dist/redirects/index.js.map +1 -0
- package/dist/redirects/lookup-redirect.js +13 -0
- package/dist/redirects/lookup-redirect.js.map +1 -0
- package/dist/request/public-url.js +20 -0
- package/dist/request/public-url.js.map +1 -0
- package/dist/schema-CEMKsCwh.d.ts +52 -0
- package/dist/sdk.js +33 -0
- package/dist/sdk.js.map +1 -0
- package/dist/server/routes.js +56 -0
- package/dist/server/routes.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +19 -0
- package/dist/server.js.map +1 -0
- package/dist/shipping/format-shipping-option.js +12 -0
- package/dist/shipping/format-shipping-option.js.map +1 -0
- package/dist/shipping/location-areas.js +104 -0
- package/dist/shipping/location-areas.js.map +1 -0
- package/dist/shipping/messages.js +19 -0
- package/dist/shipping/messages.js.map +1 -0
- package/dist/shipping/shipping-calculation-reducer.js +75 -0
- package/dist/shipping/shipping-calculation-reducer.js.map +1 -0
- package/dist/shipping/use-shipping-calculation.js +84 -0
- package/dist/shipping/use-shipping-calculation.js.map +1 -0
- package/dist/shipping/utils.js +18 -0
- package/dist/shipping/utils.js.map +1 -0
- package/dist/storage.js +116 -0
- package/dist/storage.js.map +1 -0
- package/dist/store/store-context.js +72 -0
- package/dist/store/store-context.js.map +1 -0
- package/dist/store-scope/index.js +33 -0
- package/dist/store-scope/index.js.map +1 -0
- package/dist/store-scope/root.js +15 -0
- package/dist/store-scope/root.js.map +1 -0
- package/dist/store-scope/store-url.js +45 -0
- package/dist/store-scope/store-url.js.map +1 -0
- package/dist/stores/basic-settings.js +67 -0
- package/dist/stores/basic-settings.js.map +1 -0
- package/dist/stores/cached.js +20 -0
- package/dist/stores/cached.js.map +1 -0
- package/dist/stores/get-store-by-host.js +38 -0
- package/dist/stores/get-store-by-host.js.map +1 -0
- package/dist/stores/index.js +7 -0
- package/dist/stores/index.js.map +1 -0
- package/dist/stores/metadata.js +19 -0
- package/dist/stores/metadata.js.map +1 -0
- package/dist/stores/store-path.js +9 -0
- package/dist/stores/store-path.js.map +1 -0
- package/dist/stores/store-suspension.js +14 -0
- package/dist/stores/store-suspension.js.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useCallback, useEffect, useState } from "react";
|
|
3
|
+
import { publicApiClient } from "../api/client.js";
|
|
4
|
+
import { unwrap } from "../api/response.js";
|
|
5
|
+
import { getPaymentState } from "../checkout/get-payment-state.js";
|
|
6
|
+
import { readOrderHandoff } from "../checkout/order-handoff.js";
|
|
7
|
+
import { pollPaymentState } from "../checkout/payment-state-poll.js";
|
|
8
|
+
import {
|
|
9
|
+
resolveInitialState,
|
|
10
|
+
shouldPollForConfirmation
|
|
11
|
+
} from "../checkout/success-state.js";
|
|
12
|
+
import { sdk } from "../sdk.js";
|
|
13
|
+
import { useStoreId } from "../store/store-context.js";
|
|
14
|
+
const CANCELLED = new Error("order status: unmounted");
|
|
15
|
+
const timeoutWait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
16
|
+
function useOrderStatus({
|
|
17
|
+
orderCode,
|
|
18
|
+
wait = timeoutWait
|
|
19
|
+
}) {
|
|
20
|
+
const storeRef = useStoreId();
|
|
21
|
+
const [handoff, setHandoff] = useState(null);
|
|
22
|
+
const [handoffLoaded, setHandoffLoaded] = useState(false);
|
|
23
|
+
const [state, setState] = useState(
|
|
24
|
+
() => resolveInitialState(orderCode, null)
|
|
25
|
+
);
|
|
26
|
+
const [isPolling, setIsPolling] = useState(false);
|
|
27
|
+
const [bankAccounts, setBankAccounts] = useState([]);
|
|
28
|
+
const [transferNote, setTransferNote] = useState(null);
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
const stored = readOrderHandoff(orderCode);
|
|
31
|
+
setHandoff(stored);
|
|
32
|
+
setState(resolveInitialState(orderCode, stored));
|
|
33
|
+
setHandoffLoaded(true);
|
|
34
|
+
}, [orderCode]);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (state !== "awaiting-transfer" || !storeRef) return;
|
|
37
|
+
let cancelled = false;
|
|
38
|
+
(async () => {
|
|
39
|
+
try {
|
|
40
|
+
const res = await publicApiClient.get(
|
|
41
|
+
`/public/stores/${encodeURIComponent(storeRef)}/payment-methods`
|
|
42
|
+
);
|
|
43
|
+
const methods = unwrap(res);
|
|
44
|
+
const transfer = (Array.isArray(methods) ? methods : []).find(
|
|
45
|
+
(m) => m.payment_method === "bank_transfer"
|
|
46
|
+
);
|
|
47
|
+
if (cancelled) return;
|
|
48
|
+
setBankAccounts(transfer?.bank_accounts ?? []);
|
|
49
|
+
setTransferNote(transfer?.transfer_instruction ?? null);
|
|
50
|
+
} catch {
|
|
51
|
+
if (!cancelled) setBankAccounts([]);
|
|
52
|
+
}
|
|
53
|
+
})();
|
|
54
|
+
return () => {
|
|
55
|
+
cancelled = true;
|
|
56
|
+
};
|
|
57
|
+
}, [state, storeRef]);
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
if (!orderCode) return;
|
|
60
|
+
if (!handoffLoaded) return;
|
|
61
|
+
if (!shouldPollForConfirmation(state)) return;
|
|
62
|
+
let cancelled = false;
|
|
63
|
+
setIsPolling(true);
|
|
64
|
+
pollPaymentState({
|
|
65
|
+
poll: () => getPaymentState(storeRef, orderCode),
|
|
66
|
+
// Rejecting once unmounted ends the poll loop, not just its result.
|
|
67
|
+
wait: async (ms) => {
|
|
68
|
+
if (cancelled) throw CANCELLED;
|
|
69
|
+
await wait(ms);
|
|
70
|
+
if (cancelled) throw CANCELLED;
|
|
71
|
+
}
|
|
72
|
+
}).then(
|
|
73
|
+
(outcome) => {
|
|
74
|
+
if (cancelled) return;
|
|
75
|
+
setState(
|
|
76
|
+
outcome.status === "paid" ? "paid" : outcome.status === "failed" ? "failed" : "still-confirming"
|
|
77
|
+
);
|
|
78
|
+
setIsPolling(false);
|
|
79
|
+
},
|
|
80
|
+
() => {
|
|
81
|
+
}
|
|
82
|
+
);
|
|
83
|
+
return () => {
|
|
84
|
+
cancelled = true;
|
|
85
|
+
};
|
|
86
|
+
}, [orderCode, storeRef, handoffLoaded]);
|
|
87
|
+
return {
|
|
88
|
+
handoff,
|
|
89
|
+
payment: { state, isPolling },
|
|
90
|
+
bankTransfer: { accounts: bankAccounts, note: transferNote }
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function useOrderLookup({
|
|
94
|
+
orderCode,
|
|
95
|
+
email,
|
|
96
|
+
phone
|
|
97
|
+
}) {
|
|
98
|
+
const storeRef = useStoreId();
|
|
99
|
+
const [order, setOrder] = useState(null);
|
|
100
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
101
|
+
const [error, setError] = useState(null);
|
|
102
|
+
const fetchOrder = useCallback(async () => {
|
|
103
|
+
if (!orderCode || !email && !phone) {
|
|
104
|
+
setError("Thi\u1EBFu th\xF4ng tin c\u1EA7n thi\u1EBFt \u0111\u1EC3 tra c\u1EE9u \u0111\u01A1n h\xE0ng");
|
|
105
|
+
setIsLoading(false);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
setIsLoading(true);
|
|
110
|
+
setError(null);
|
|
111
|
+
const found = await sdk.orders.lookupGuest(storeRef, {
|
|
112
|
+
order_code: orderCode,
|
|
113
|
+
customer_email: email || void 0,
|
|
114
|
+
customer_phone: phone || void 0
|
|
115
|
+
});
|
|
116
|
+
if (!found) {
|
|
117
|
+
setError("Kh\xF4ng t\xECm th\u1EA5y \u0111\u01A1n h\xE0ng v\u1EDBi th\xF4ng tin \u0111\xE3 cung c\u1EA5p");
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
setOrder(found);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
console.error("Error fetching order:", err);
|
|
123
|
+
setError("C\xF3 l\u1ED7i x\u1EA3y ra khi tra c\u1EE9u \u0111\u01A1n h\xE0ng");
|
|
124
|
+
} finally {
|
|
125
|
+
setIsLoading(false);
|
|
126
|
+
}
|
|
127
|
+
}, [storeRef, orderCode, email, phone]);
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
fetchOrder();
|
|
130
|
+
}, [fetchOrder]);
|
|
131
|
+
return { order, isLoading, error, retry: fetchOrder };
|
|
132
|
+
}
|
|
133
|
+
export {
|
|
134
|
+
useOrderLookup,
|
|
135
|
+
useOrderStatus
|
|
136
|
+
};
|
|
137
|
+
//# sourceMappingURL=use-order-status.js.map
|
|
@@ -0,0 +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 { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\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 { sdk } from \"../sdk\";\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\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 const [bankAccounts, setBankAccounts] = useState<BankAccountView[]>([]);\n const [transferNote, setTransferNote] = useState<string | null>(null);\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 useEffect(() => {\n if (state !== \"awaiting-transfer\" || !storeRef) return;\n let cancelled = false;\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`\n );\n const methods = unwrap(res) as unknown as PublicPaymentMethod[];\n const transfer = (Array.isArray(methods) ? methods : []).find(\n m => m.payment_method === \"bank_transfer\"\n );\n if (cancelled) return;\n setBankAccounts(transfer?.bank_accounts ?? []);\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n setTransferNote(transfer?.transfer_instruction ?? null);\n } catch {\n // The order is placed either way; no accounts renders a \"contact the\n // shop\" fallback rather than an error.\n if (!cancelled) setBankAccounts([]);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [state, storeRef]);\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: bankAccounts, note: transferNote },\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 sdk.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 as unknown as OrderWithItems);\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":"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","names":[]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { sdk } from "../sdk.js";
|
|
2
|
+
import { useState, useCallback, useEffect, useRef } from "react";
|
|
3
|
+
import { useNotify } from "../notices.js";
|
|
4
|
+
function usePromotionValidation({
|
|
5
|
+
storeRef,
|
|
6
|
+
items,
|
|
7
|
+
subtotal,
|
|
8
|
+
shippingFee
|
|
9
|
+
}) {
|
|
10
|
+
const [promoCode, setPromoCode] = useState("");
|
|
11
|
+
const [appliedPromotion, setAppliedPromotion] = useState(null);
|
|
12
|
+
const [shippingDiscount, setShippingDiscount] = useState(0);
|
|
13
|
+
const [isValidatingPromo, setIsValidatingPromo] = useState(false);
|
|
14
|
+
const [promoError, setPromoError] = useState("");
|
|
15
|
+
const notify = useNotify();
|
|
16
|
+
const validatePromoCodeWithCode = useCallback(
|
|
17
|
+
async (code) => {
|
|
18
|
+
const codeToValidate = code || promoCode;
|
|
19
|
+
if (!codeToValidate.trim()) {
|
|
20
|
+
setPromoError("Vui l\xF2ng nh\u1EADp m\xE3 khuy\u1EBFn m\xE3i");
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
setIsValidatingPromo(true);
|
|
24
|
+
setPromoError("");
|
|
25
|
+
try {
|
|
26
|
+
const result = await sdk.promotions.validate(
|
|
27
|
+
storeRef,
|
|
28
|
+
{
|
|
29
|
+
code: codeToValidate.trim(),
|
|
30
|
+
items: items.map((item) => ({
|
|
31
|
+
product_id: item.productId,
|
|
32
|
+
variant_id: item.variantId ?? void 0,
|
|
33
|
+
quantity: item.quantity,
|
|
34
|
+
price: item.price
|
|
35
|
+
})),
|
|
36
|
+
subtotal,
|
|
37
|
+
shipping_fee: shippingFee
|
|
38
|
+
}
|
|
39
|
+
);
|
|
40
|
+
if (!result.success) {
|
|
41
|
+
throw new Error(result.message || "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7");
|
|
42
|
+
}
|
|
43
|
+
const promotionWithCode = {
|
|
44
|
+
...result.promotion,
|
|
45
|
+
code: codeToValidate.trim()
|
|
46
|
+
};
|
|
47
|
+
setAppliedPromotion(promotionWithCode);
|
|
48
|
+
setShippingDiscount(result.shipping_discount ?? 0);
|
|
49
|
+
notify({
|
|
50
|
+
kind: "success",
|
|
51
|
+
code: "promotion.applied",
|
|
52
|
+
title: "\xC1p d\u1EE5ng m\xE3 khuy\u1EBFn m\xE3i th\xE0nh c\xF4ng",
|
|
53
|
+
description: `${result.promotion?.name || ""} \u0111\xE3 \u0111\u01B0\u1EE3c \xE1p d\u1EE5ng`
|
|
54
|
+
});
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error("Failed to validate promotion code:", error);
|
|
57
|
+
setPromoError(
|
|
58
|
+
error instanceof Error ? error.message : "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7"
|
|
59
|
+
);
|
|
60
|
+
setAppliedPromotion(null);
|
|
61
|
+
setShippingDiscount(0);
|
|
62
|
+
} finally {
|
|
63
|
+
setIsValidatingPromo(false);
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
[storeRef, items, subtotal, shippingFee, promoCode, notify]
|
|
67
|
+
);
|
|
68
|
+
const revalidateRef = useRef(validatePromoCodeWithCode);
|
|
69
|
+
revalidateRef.current = validatePromoCodeWithCode;
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
const code = appliedPromotion?.code;
|
|
72
|
+
if (!code) return;
|
|
73
|
+
void revalidateRef.current(code);
|
|
74
|
+
}, [shippingFee]);
|
|
75
|
+
const validatePromoCode = useCallback(async () => {
|
|
76
|
+
await validatePromoCodeWithCode();
|
|
77
|
+
}, [validatePromoCodeWithCode]);
|
|
78
|
+
const removePromoCode = useCallback(() => {
|
|
79
|
+
setPromoCode("");
|
|
80
|
+
setAppliedPromotion(null);
|
|
81
|
+
setShippingDiscount(0);
|
|
82
|
+
setPromoError("");
|
|
83
|
+
}, []);
|
|
84
|
+
const applyPromotionFromSuggestion = useCallback(
|
|
85
|
+
async (code) => {
|
|
86
|
+
setPromoCode(code);
|
|
87
|
+
await validatePromoCodeWithCode(code);
|
|
88
|
+
},
|
|
89
|
+
[validatePromoCodeWithCode]
|
|
90
|
+
);
|
|
91
|
+
return {
|
|
92
|
+
promoCode,
|
|
93
|
+
appliedPromotion,
|
|
94
|
+
shippingDiscount,
|
|
95
|
+
isValidatingPromo,
|
|
96
|
+
promoError,
|
|
97
|
+
setPromoCode,
|
|
98
|
+
validatePromoCode,
|
|
99
|
+
removePromoCode,
|
|
100
|
+
applyPromotionFromSuggestion
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
export {
|
|
104
|
+
usePromotionValidation
|
|
105
|
+
};
|
|
106
|
+
//# sourceMappingURL=use-promotion-validation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { sdk } 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\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 sdk.promotions.validate(\n storeRef,\n {\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\n if (!result.success) {\n throw new Error(result.message || \"Mã khuyến mãi không hợp lệ\");\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 // eslint-disable-next-line no-console\n console.error(\"Failed to validate promotion code:\", error);\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,WAAW;AACpB,SAAS,UAAU,aAAa,WAAW,cAAc;AACzD,SAAS,iBAAiB;AAgBnB,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,CAAC,WAAW,YAAY,IAAI,SAAiB,EAAE;AACrD,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAc,IAAI;AAGlE,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAiB,CAAC;AAClE,QAAM,CAAC,mBAAmB,oBAAoB,IAAI,SAAS,KAAK;AAChE,QAAM,CAAC,YAAY,aAAa,IAAI,SAAiB,EAAE;AACvD,QAAM,SAAS,UAAU;AAGzB,QAAM,4BAA4B;AAAA,IAChC,OAAO,SAAkB;AACvB,YAAM,iBAAiB,QAAQ;AAE/B,UAAI,CAAC,eAAe,KAAK,GAAG;AAC1B,sBAAc,gDAA6B;AAC3C;AAAA,MACF;AAEA,2BAAqB,IAAI;AACzB,oBAAc,EAAE;AAEhB,UAAI;AACF,cAAM,SAAS,MAAM,IAAI,WAAW;AAAA,UAClC;AAAA,UACA;AAAA,YACE,MAAM,eAAe,KAAK;AAAA,YAC1B,OAAO,MAAM,IAAI,WAAS;AAAA,cACxB,YAAY,KAAK;AAAA,cACjB,YAAY,KAAK,aAAa;AAAA,cAC9B,UAAU,KAAK;AAAA,cACf,OAAO,KAAK;AAAA,YACd,EAAE;AAAA,YACF;AAAA,YACA,cAAc;AAAA,UAChB;AAAA,QACF;AAEA,YAAI,CAAC,OAAO,SAAS;AACnB,gBAAM,IAAI,MAAM,OAAO,WAAW,oDAA4B;AAAA,QAChE;AAGA,cAAM,oBAAoB;AAAA,UACxB,GAAG,OAAO;AAAA,UACV,MAAM,eAAe,KAAK;AAAA,QAC5B;AACA,4BAAoB,iBAAiB;AACrC,4BAAoB,OAAO,qBAAqB,CAAC;AACjD,eAAO;AAAA,UACL,MAAM;AAAA,UACN,MAAM;AAAA,UACN,OAAO;AAAA,UACP,aAAa,GAAG,OAAO,WAAW,QAAQ,EAAE;AAAA,QAC9C,CAAC;AAAA,MACH,SAAS,OAAO;AAEd,gBAAQ,MAAM,sCAAsC,KAAK;AACzD;AAAA,UACE,iBAAiB,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,40 @@
|
|
|
1
|
+
import { formatPrice } from "../currency.js";
|
|
2
|
+
import { PromotionType, DiscountMethod } from "@ecomweb/sdk";
|
|
3
|
+
function getPromotionDescription(promotion, locale = "vi-VN", currency = "VND") {
|
|
4
|
+
if (promotion.type === PromotionType.FREE_SHIPPING) {
|
|
5
|
+
if (promotion.discount_method === DiscountMethod.PERCENTAGE && promotion.discount_value) {
|
|
6
|
+
return `Gi\u1EA3m ph\xED v\u1EADn chuy\u1EC3n ${promotion.discount_value}%`;
|
|
7
|
+
}
|
|
8
|
+
if (promotion.discount_method === DiscountMethod.FIXED_AMOUNT && promotion.discount_value) {
|
|
9
|
+
return `Gi\u1EA3m ph\xED v\u1EADn chuy\u1EC3n ${formatPrice(promotion.discount_value, locale, currency)}`;
|
|
10
|
+
}
|
|
11
|
+
return "Mi\u1EC5n ph\xED v\u1EADn chuy\u1EC3n";
|
|
12
|
+
}
|
|
13
|
+
if (promotion.discount_method === DiscountMethod.PERCENTAGE && promotion.discount_value) {
|
|
14
|
+
return `Gi\u1EA3m ${promotion.discount_value}%`;
|
|
15
|
+
}
|
|
16
|
+
if (promotion.discount_method === DiscountMethod.FIXED_AMOUNT && promotion.discount_value) {
|
|
17
|
+
return `Gi\u1EA3m ${formatPrice(promotion.discount_value, locale, currency)}`;
|
|
18
|
+
}
|
|
19
|
+
if (promotion.type === PromotionType.CART_DISCOUNT) {
|
|
20
|
+
if (promotion.discount_method === DiscountMethod.PERCENTAGE && promotion.discount_value) {
|
|
21
|
+
return `Gi\u1EA3m ${promotion.discount_value}%`;
|
|
22
|
+
}
|
|
23
|
+
if (promotion.discount_method === DiscountMethod.FIXED_AMOUNT && promotion.discount_value) {
|
|
24
|
+
return `Gi\u1EA3m ${formatPrice(promotion.discount_value, locale, currency)}`;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (promotion.type === PromotionType.PRODUCT_DISCOUNT) {
|
|
28
|
+
if (promotion.discount_method === DiscountMethod.PERCENTAGE && promotion.discount_value) {
|
|
29
|
+
return `Gi\u1EA3m ${promotion.discount_value}%`;
|
|
30
|
+
}
|
|
31
|
+
if (promotion.discount_method === DiscountMethod.FIXED_AMOUNT && promotion.discount_value) {
|
|
32
|
+
return `Gi\u1EA3m ${formatPrice(promotion.discount_value, locale, currency)}`;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return promotion.description || "Khuy\u1EBFn m\xE3i \u0111\u1EB7c bi\u1EC7t";
|
|
36
|
+
}
|
|
37
|
+
export {
|
|
38
|
+
getPromotionDescription
|
|
39
|
+
};
|
|
40
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/promotions/utils.ts"],"sourcesContent":["import { formatPrice } from \"../currency\";\nimport { PromotionType, DiscountMethod } from \"@ecomweb/sdk\";\n\nexport interface PromotionDescriptionData {\n type: string;\n discount_method?: string;\n discount_value?: number;\n description?: string;\n}\n\n/**\n * Generate promotion description based on promotion type and discount method\n * @param promotion - Promotion data containing type, discount_method, discount_value, description\n * @param locale - Locale for formatting (e.g., \"vi-VN\", \"en-US\")\n * @param currency - Currency code (e.g., \"VND\", \"USD\")\n * @returns Formatted promotion description string\n */\nexport function getPromotionDescription(\n promotion: PromotionDescriptionData,\n locale: string = \"vi-VN\",\n currency: string = \"VND\"\n): string {\n if (promotion.type === PromotionType.FREE_SHIPPING) {\n if (\n promotion.discount_method === DiscountMethod.PERCENTAGE &&\n promotion.discount_value\n ) {\n return `Giảm phí vận chuyển ${promotion.discount_value}%`;\n }\n if (\n promotion.discount_method === DiscountMethod.FIXED_AMOUNT &&\n promotion.discount_value\n ) {\n return `Giảm phí vận chuyển ${formatPrice(promotion.discount_value, locale, currency)}`;\n }\n return \"Miễn phí vận chuyển\";\n }\n\n if (\n promotion.discount_method === DiscountMethod.PERCENTAGE &&\n promotion.discount_value\n ) {\n return `Giảm ${promotion.discount_value}%`;\n }\n\n if (\n promotion.discount_method === DiscountMethod.FIXED_AMOUNT &&\n promotion.discount_value\n ) {\n return `Giảm ${formatPrice(promotion.discount_value, locale, currency)}`;\n }\n\n if (promotion.type === PromotionType.CART_DISCOUNT) {\n if (\n promotion.discount_method === DiscountMethod.PERCENTAGE &&\n promotion.discount_value\n ) {\n return `Giảm ${promotion.discount_value}%`;\n }\n if (\n promotion.discount_method === DiscountMethod.FIXED_AMOUNT &&\n promotion.discount_value\n ) {\n return `Giảm ${formatPrice(promotion.discount_value, locale, currency)}`;\n }\n }\n\n if (promotion.type === PromotionType.PRODUCT_DISCOUNT) {\n if (\n promotion.discount_method === DiscountMethod.PERCENTAGE &&\n promotion.discount_value\n ) {\n return `Giảm ${promotion.discount_value}%`;\n }\n if (\n promotion.discount_method === DiscountMethod.FIXED_AMOUNT &&\n promotion.discount_value\n ) {\n return `Giảm ${formatPrice(promotion.discount_value, locale, currency)}`;\n }\n }\n\n return promotion.description || \"Khuyến mãi đặc biệt\";\n}\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B,SAAS,eAAe,sBAAsB;AAgBvC,SAAS,wBACd,WACA,SAAiB,SACjB,WAAmB,OACX;AACR,MAAI,UAAU,SAAS,cAAc,eAAe;AAClD,QACE,UAAU,oBAAoB,eAAe,cAC7C,UAAU,gBACV;AACA,aAAO,yCAAuB,UAAU,cAAc;AAAA,IACxD;AACA,QACE,UAAU,oBAAoB,eAAe,gBAC7C,UAAU,gBACV;AACA,aAAO,yCAAuB,YAAY,UAAU,gBAAgB,QAAQ,QAAQ,CAAC;AAAA,IACvF;AACA,WAAO;AAAA,EACT;AAEA,MACE,UAAU,oBAAoB,eAAe,cAC7C,UAAU,gBACV;AACA,WAAO,aAAQ,UAAU,cAAc;AAAA,EACzC;AAEA,MACE,UAAU,oBAAoB,eAAe,gBAC7C,UAAU,gBACV;AACA,WAAO,aAAQ,YAAY,UAAU,gBAAgB,QAAQ,QAAQ,CAAC;AAAA,EACxE;AAEA,MAAI,UAAU,SAAS,cAAc,eAAe;AAClD,QACE,UAAU,oBAAoB,eAAe,cAC7C,UAAU,gBACV;AACA,aAAO,aAAQ,UAAU,cAAc;AAAA,IACzC;AACA,QACE,UAAU,oBAAoB,eAAe,gBAC7C,UAAU,gBACV;AACA,aAAO,aAAQ,YAAY,UAAU,gBAAgB,QAAQ,QAAQ,CAAC;AAAA,IACxE;AAAA,EACF;AAEA,MAAI,UAAU,SAAS,cAAc,kBAAkB;AACrD,QACE,UAAU,oBAAoB,eAAe,cAC7C,UAAU,gBACV;AACA,aAAO,aAAQ,UAAU,cAAc;AAAA,IACzC;AACA,QACE,UAAU,oBAAoB,eAAe,gBAC7C,UAAU,gBACV;AACA,aAAO,aAAQ,YAAY,UAAU,gBAAgB,QAAQ,QAAQ,CAAC;AAAA,IACxE;AAAA,EACF;AAEA,SAAO,UAAU,eAAe;AAClC;","names":[]}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx } from "react/jsx-runtime";
|
|
3
|
+
import { AuthProvider, useAuth } from "./auth/context.js";
|
|
4
|
+
import { CartProvider } from "./cart/server-context.js";
|
|
5
|
+
import { NoticeProvider } from "./notices.js";
|
|
6
|
+
import { StoreProvider } from "./store/store-context.js";
|
|
7
|
+
function IdentityCart({
|
|
8
|
+
storeRef,
|
|
9
|
+
children
|
|
10
|
+
}) {
|
|
11
|
+
const { user } = useAuth();
|
|
12
|
+
return /* @__PURE__ */ jsx(CartProvider, { storeRef, userId: user?.id, children });
|
|
13
|
+
}
|
|
14
|
+
function StorefrontKitProvider({
|
|
15
|
+
store,
|
|
16
|
+
storeRef,
|
|
17
|
+
onNotice,
|
|
18
|
+
children
|
|
19
|
+
}) {
|
|
20
|
+
return /* @__PURE__ */ jsx(StoreProvider, { store, children: /* @__PURE__ */ jsx(NoticeProvider, { onNotice, children: /* @__PURE__ */ jsx(AuthProvider, { children: /* @__PURE__ */ jsx(IdentityCart, { storeRef: storeRef ?? store.ref, children }) }) }) });
|
|
21
|
+
}
|
|
22
|
+
export {
|
|
23
|
+
StorefrontKitProvider
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n children,\n}: StorefrontKitProviderProps) {\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA2BI;AAvBJ,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAW9B,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAC7B,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/redirects/index.ts"],"sourcesContent":["export * from \"./lookup-redirect\";\n"],"mappings":"AAAA,cAAc;","names":[]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { sdk } from "../sdk.js";
|
|
2
|
+
async function lookupRedirect(storeId, path) {
|
|
3
|
+
try {
|
|
4
|
+
return await sdk.redirects.lookup(storeId, path);
|
|
5
|
+
} catch (error) {
|
|
6
|
+
console.error("Error looking up redirect:", error);
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
lookupRedirect
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=lookup-redirect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/redirects/lookup-redirect.ts"],"sourcesContent":["import type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\n\n/**\n * Lookup URL redirect for a given store and path\n * Used by middleware to check if a path should be redirected\n */\nexport async function lookupRedirect(\n storeId: string,\n path: string\n): Promise<UrlRedirect | null> {\n try {\n return await sdk.redirects.lookup(storeId, path);\n } catch (error) {\n console.error(\"Error looking up redirect:\", error);\n return null;\n }\n}\n"],"mappings":"AACA,SAAS,WAAW;AAMpB,eAAsB,eACpB,SACA,MAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,IAAI,UAAU,OAAO,SAAS,IAAI;AAAA,EACjD,SAAS,OAAO;AACd,YAAQ,MAAM,8BAA8B,KAAK;AACjD,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const HOST = /^[a-z0-9.-]+(:\d{1,5})?$/i;
|
|
2
|
+
const first = (value) => value?.split(",")[0]?.trim() || null;
|
|
3
|
+
function publicNextUrl(request) {
|
|
4
|
+
const url = new URL(request.nextUrl.toString());
|
|
5
|
+
const host = [first(request.headers.get("x-forwarded-host")), first(request.headers.get("host"))].find(
|
|
6
|
+
(h) => !!h && HOST.test(h)
|
|
7
|
+
);
|
|
8
|
+
const proto = first(request.headers.get("x-forwarded-proto"));
|
|
9
|
+
if (proto === "https" || proto === "http") url.protocol = `${proto}:`;
|
|
10
|
+
if (host) {
|
|
11
|
+
const [hostname, port = ""] = host.split(":");
|
|
12
|
+
url.hostname = hostname;
|
|
13
|
+
url.port = port;
|
|
14
|
+
}
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
publicNextUrl
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=public-url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/request/public-url.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\n\nconst HOST = /^[a-z0-9.-]+(:\\d{1,5})?$/i;\nconst first = (value: string | null) => value?.split(\",\")[0]?.trim() || null;\n\n/**\n * The request's URL as the shopper sees it. Behind a proxy (Kong in front of\n * ecomweb hosting, or any load balancer) a standalone Next server's\n * request.url carries its own bind address, e.g. http://0.0.0.0:3000, so a\n * redirect built from it sends the browser nowhere. The proxy's Host and\n * X-Forwarded-* headers carry the store's real host and scheme; values that\n * aren't a plain host or http(s) are ignored.\n */\nexport function publicNextUrl(request: Pick<NextRequest, \"headers\" | \"nextUrl\">): URL {\n const url = new URL(request.nextUrl.toString());\n const host = [first(request.headers.get(\"x-forwarded-host\")), first(request.headers.get(\"host\"))].find(\n (h): h is string => !!h && HOST.test(h),\n );\n const proto = first(request.headers.get(\"x-forwarded-proto\"));\n if (proto === \"https\" || proto === \"http\") url.protocol = `${proto}:`;\n if (host) {\n // Assigning host alone would keep the bind address's port.\n const [hostname, port = \"\"] = host.split(\":\");\n url.hostname = hostname!;\n url.port = port;\n }\n return url;\n}\n"],"mappings":"AAEA,MAAM,OAAO;AACb,MAAM,QAAQ,CAAC,UAAyB,OAAO,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAUjE,SAAS,cAAc,SAAwD;AACpF,QAAM,MAAM,IAAI,IAAI,QAAQ,QAAQ,SAAS,CAAC;AAC9C,QAAM,OAAO,CAAC,MAAM,QAAQ,QAAQ,IAAI,kBAAkB,CAAC,GAAG,MAAM,QAAQ,QAAQ,IAAI,MAAM,CAAC,CAAC,EAAE;AAAA,IAChG,CAAC,MAAmB,CAAC,CAAC,KAAK,KAAK,KAAK,CAAC;AAAA,EACxC;AACA,QAAM,QAAQ,MAAM,QAAQ,QAAQ,IAAI,mBAAmB,CAAC;AAC5D,MAAI,UAAU,WAAW,UAAU,OAAQ,KAAI,WAAW,GAAG,KAAK;AAClE,MAAI,MAAM;AAER,UAAM,CAAC,UAAU,OAAO,EAAE,IAAI,KAAK,MAAM,GAAG;AAC5C,QAAI,WAAW;AACf,QAAI,OAAO;AAAA,EACb;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
|
|
4
|
+
type EnvSource = Record<string, string | undefined>;
|
|
5
|
+
declare const publicConfigSchema: z.ZodObject<{
|
|
6
|
+
mode: z.ZodEnum<{
|
|
7
|
+
multi: "multi";
|
|
8
|
+
single: "single";
|
|
9
|
+
}>;
|
|
10
|
+
storeRef: z.ZodNullable<z.ZodString>;
|
|
11
|
+
apiUrl: z.ZodURL;
|
|
12
|
+
assetBaseUrl: z.ZodString;
|
|
13
|
+
appUrl: z.ZodURL;
|
|
14
|
+
storefrontApiKey: z.ZodString;
|
|
15
|
+
platformDomainSuffix: z.ZodNullable<z.ZodString>;
|
|
16
|
+
appBaseUrlFlag: z.ZodOptional<z.ZodString>;
|
|
17
|
+
imageTransformationsFlag: z.ZodOptional<z.ZodString>;
|
|
18
|
+
primaryMenuRef: z.ZodString;
|
|
19
|
+
logLevel: z.ZodOptional<z.ZodEnum<{
|
|
20
|
+
error: "error";
|
|
21
|
+
silent: "silent";
|
|
22
|
+
warn: "warn";
|
|
23
|
+
info: "info";
|
|
24
|
+
debug: "debug";
|
|
25
|
+
}>>;
|
|
26
|
+
webVitalsSampleRate: z.ZodNumber;
|
|
27
|
+
}, z.core.$strip>;
|
|
28
|
+
type PublicConfig = z.infer<typeof publicConfigSchema>;
|
|
29
|
+
declare const serverConfigSchema: z.ZodObject<{
|
|
30
|
+
platformApiKey: z.ZodString;
|
|
31
|
+
clientIpForwarderSecret: z.ZodOptional<z.ZodString>;
|
|
32
|
+
appBaseUrl: z.ZodString;
|
|
33
|
+
appEnv: z.ZodString;
|
|
34
|
+
googleVerification: z.ZodOptional<z.ZodString>;
|
|
35
|
+
logLevel: z.ZodOptional<z.ZodEnum<{
|
|
36
|
+
error: "error";
|
|
37
|
+
silent: "silent";
|
|
38
|
+
warn: "warn";
|
|
39
|
+
info: "info";
|
|
40
|
+
debug: "debug";
|
|
41
|
+
}>>;
|
|
42
|
+
clientIpHeader: z.ZodEnum<{
|
|
43
|
+
"x-forwarded-for": "x-forwarded-for";
|
|
44
|
+
"cf-connecting-ip": "cf-connecting-ip";
|
|
45
|
+
}>;
|
|
46
|
+
}, z.core.$strip>;
|
|
47
|
+
type ServerConfig = z.infer<typeof serverConfigSchema>;
|
|
48
|
+
declare class ConfigError extends Error {
|
|
49
|
+
constructor(message: string);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export { ConfigError as C, type EnvSource as E, type LogLevel as L, type PublicConfig as P, type ServerConfig as S };
|
package/dist/sdk.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createEcomwebSdk } from "@ecomweb/sdk";
|
|
2
|
+
import { createStoreApiClient, publicApiClient } from "./api/client.js";
|
|
3
|
+
function requireStoreScopedSdk() {
|
|
4
|
+
const fail = async () => ({
|
|
5
|
+
success: false,
|
|
6
|
+
error: {
|
|
7
|
+
message: "This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.",
|
|
8
|
+
statusCode: 401,
|
|
9
|
+
error: "SDK_STORE_SCOPE_REQUIRED"
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
return { get: fail, post: fail, put: fail, patch: fail, delete: fail };
|
|
13
|
+
}
|
|
14
|
+
const sdk = createEcomwebSdk({
|
|
15
|
+
publicHttp: publicApiClient,
|
|
16
|
+
authHttp: requireStoreScopedSdk()
|
|
17
|
+
});
|
|
18
|
+
const storeSdks = /* @__PURE__ */ new Map();
|
|
19
|
+
function createStoreSdk(storeRef) {
|
|
20
|
+
const cached = storeSdks.get(storeRef);
|
|
21
|
+
if (cached) return cached;
|
|
22
|
+
const created = createEcomwebSdk({
|
|
23
|
+
publicHttp: publicApiClient,
|
|
24
|
+
authHttp: createStoreApiClient(storeRef)
|
|
25
|
+
});
|
|
26
|
+
storeSdks.set(storeRef, created);
|
|
27
|
+
return created;
|
|
28
|
+
}
|
|
29
|
+
export {
|
|
30
|
+
createStoreSdk,
|
|
31
|
+
sdk
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=sdk.js.map
|
package/dist/sdk.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient } from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\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 = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n});\n\nconst storeSdks = new Map<string, ReturnType<typeof createEcomwebSdk>>();\n\n/**\n * SDK bound to one store, whose authenticated modules (cart, orders, blog\n * comments, customers, addresses) go through the same-origin proxy route so the\n * httpOnly session cookie can be turned into a bearer token server-side.\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) {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: createStoreApiClient(storeRef) as any,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB,uBAAuB;AAQtD,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,MAAM,iBAAiB;AAAA,EAClC,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAClC,CAAC;AAED,MAAM,YAAY,oBAAI,IAAiD;AAUhE,SAAS,eAAe,UAAkB;AAC/C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,iBAAiB;AAAA,IAC/B,YAAY;AAAA,IACZ,UAAU,qBAAqB,QAAQ;AAAA,EACzC,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { NextResponse } from "next/server";
|
|
3
|
+
import { redirect } from "next/navigation";
|
|
4
|
+
import { handleBackendProxy } from "../api/proxy.js";
|
|
5
|
+
import { handleAuthRoute } from "../auth/route-handlers.js";
|
|
6
|
+
import { getServerIdentity } from "../auth/session.js";
|
|
7
|
+
import { resolveStoreRef } from "../store-scope/index.js";
|
|
8
|
+
import { resolveRootStoreRef } from "../store-scope/root.js";
|
|
9
|
+
async function storeRefFor(params) {
|
|
10
|
+
if (typeof params.storeRef === "string") {
|
|
11
|
+
return resolveStoreRef(Promise.resolve({ storeRef: params.storeRef }));
|
|
12
|
+
}
|
|
13
|
+
return resolveRootStoreRef();
|
|
14
|
+
}
|
|
15
|
+
function storeNotFound() {
|
|
16
|
+
return NextResponse.json(
|
|
17
|
+
{ error: { message: "Store not found for host" } },
|
|
18
|
+
{ status: 404 }
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
const segments = (v) => Array.isArray(v) ? v : v ? [v] : [];
|
|
22
|
+
function createAuthRoutes() {
|
|
23
|
+
const handle = async (req, { params }) => {
|
|
24
|
+
const p = await params;
|
|
25
|
+
const storeRef = await storeRefFor(p);
|
|
26
|
+
if (!storeRef) return storeNotFound();
|
|
27
|
+
return handleAuthRoute(req, storeRef, segments(p.route));
|
|
28
|
+
};
|
|
29
|
+
return { GET: handle, POST: handle };
|
|
30
|
+
}
|
|
31
|
+
function createBackendProxy() {
|
|
32
|
+
const handle = async (req, { params }) => {
|
|
33
|
+
const p = await params;
|
|
34
|
+
const storeRef = await storeRefFor(p);
|
|
35
|
+
if (!storeRef) return storeNotFound();
|
|
36
|
+
return handleBackendProxy(req, storeRef, segments(p.path));
|
|
37
|
+
};
|
|
38
|
+
return {
|
|
39
|
+
GET: handle,
|
|
40
|
+
POST: handle,
|
|
41
|
+
PUT: handle,
|
|
42
|
+
PATCH: handle,
|
|
43
|
+
DELETE: handle
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
async function requireSession(storeRef, redirectTo) {
|
|
47
|
+
const identity = await getServerIdentity(storeRef);
|
|
48
|
+
if (!identity || identity.is_anonymous) redirect(redirectTo);
|
|
49
|
+
return identity;
|
|
50
|
+
}
|
|
51
|
+
export {
|
|
52
|
+
createAuthRoutes,
|
|
53
|
+
createBackendProxy,
|
|
54
|
+
requireSession
|
|
55
|
+
};
|
|
56
|
+
//# sourceMappingURL=routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { redirect } from \"next/navigation\";\nimport { handleBackendProxy } from \"../api/proxy\";\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\nfunction storeNotFound(): Response {\n return NextResponse.json(\n { error: { message: \"Store not found for host\" } },\n { status: 404 }\n );\n}\n\nconst segments = (v: Params[string]): string[] =>\n Array.isArray(v) ? v : v ? [v] : [];\n\n/** `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route]. */\nexport function createAuthRoutes(): { GET: RouteHandler; POST: RouteHandler } {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n const storeRef = await storeRefFor(p);\n if (!storeRef) return storeNotFound();\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].\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 const storeRef = await storeRefFor(p);\n if (!storeRef) return storeNotFound();\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;AACP,SAAS,oBAAsC;AAC/C,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,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,SAAS,gBAA0B;AACjC,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,2BAA2B,EAAE;AAAA,IACjD,EAAE,QAAQ,IAAI;AAAA,EAChB;AACF;AAEA,MAAM,WAAW,CAAC,MAChB,MAAM,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC;AAG7B,SAAS,mBAA8D;AAC5E,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,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;AAMO,SAAS,qBAGd;AACA,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,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
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { NextRequest } from 'next/server';
|
|
2
|
+
import { CurrentIdentity } from '@ecomweb/sdk';
|
|
3
|
+
import { E as EnvSource, S as ServerConfig } from './schema-CEMKsCwh.js';
|
|
4
|
+
import 'zod';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The one server-side "who is this request?" read.
|
|
8
|
+
*
|
|
9
|
+
* Wrapped in React `cache()` so several server components in the same render
|
|
10
|
+
* share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: "no-store"`,
|
|
11
|
+
* so without this every layout and page would issue its own.
|
|
12
|
+
*/
|
|
13
|
+
declare const getServerIdentity: (storeRef: string) => Promise<CurrentIdentity | null>;
|
|
14
|
+
/**
|
|
15
|
+
* Whether the request carries a real, logged-in shopper session.
|
|
16
|
+
*
|
|
17
|
+
* An **anonymous** identity (the guest-cart session the backend issues) has a
|
|
18
|
+
* perfectly valid token but is not a logged-in shopper: it has no
|
|
19
|
+
* `customer_id`, no name and no email. Treating it as authenticated admits it
|
|
20
|
+
* to `/account/*` — where every page is empty or errors — and, worse, bounces
|
|
21
|
+
* it away from `/login`, so a guest with a cart could never sign in.
|
|
22
|
+
*/
|
|
23
|
+
declare function hasCustomerSession(storeRef: string): Promise<boolean>;
|
|
24
|
+
|
|
25
|
+
type Params = Record<string, string | string[] | undefined>;
|
|
26
|
+
type RouteContext = {
|
|
27
|
+
params: Promise<Params>;
|
|
28
|
+
};
|
|
29
|
+
type RouteHandler = (req: NextRequest, ctx: RouteContext) => Promise<Response>;
|
|
30
|
+
/** `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route]. */
|
|
31
|
+
declare function createAuthRoutes(): {
|
|
32
|
+
GET: RouteHandler;
|
|
33
|
+
POST: RouteHandler;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`
|
|
37
|
+
* in api/backend/[...path].
|
|
38
|
+
*/
|
|
39
|
+
declare function createBackendProxy(): Record<"GET" | "POST" | "PUT" | "PATCH" | "DELETE", RouteHandler>;
|
|
40
|
+
type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>>>;
|
|
41
|
+
/**
|
|
42
|
+
* The signed-in customer, or a redirect to `redirectTo`. An anonymous
|
|
43
|
+
* identity holds a valid token but no customer profile, so it redirects too.
|
|
44
|
+
*/
|
|
45
|
+
declare function requireSession(storeRef: string, redirectTo: string): Promise<CustomerIdentity>;
|
|
46
|
+
|
|
47
|
+
/** Parses the variables of the mode `env` selects (see resolveMode). */
|
|
48
|
+
declare function parseServerConfig(env: EnvSource): ServerConfig;
|
|
49
|
+
declare function serverConfig(): ServerConfig;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The store for routes outside /store/<ref> (robots, sitemap, icons, manifest,
|
|
53
|
+
* root /api/auth). Single-store: the configured store. Multi-tenant: only the
|
|
54
|
+
* Host can name it.
|
|
55
|
+
*/
|
|
56
|
+
declare function resolveRootStoreRef(): Promise<string | null>;
|
|
57
|
+
|
|
58
|
+
export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, hasCustomerSession, parseServerConfig, requireSession, resolveRootStoreRef, serverConfig };
|