@shopify/hydrogen-react 2026.4.3 → 2026.4.4
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/dist/browser-dev/ShopifyProvider.mjs.map +1 -1
- package/dist/browser-dev/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
- package/dist/browser-dev/load-script.mjs +1 -1
- package/dist/browser-dev/packages/hydrogen-react/package.mjs +1 -1
- package/dist/browser-dev/packages/hydrogen-react/package.mjs.map +1 -1
- package/dist/browser-dev/tracking-utils.mjs +17 -58
- package/dist/browser-dev/tracking-utils.mjs.map +1 -1
- package/dist/browser-dev/useShopifyCookies.mjs +34 -97
- package/dist/browser-dev/useShopifyCookies.mjs.map +1 -1
- package/dist/browser-prod/ShopifyProvider.mjs.map +1 -1
- package/dist/browser-prod/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
- package/dist/browser-prod/load-script.mjs +1 -1
- package/dist/browser-prod/packages/hydrogen-react/package.mjs +1 -1
- package/dist/browser-prod/packages/hydrogen-react/package.mjs.map +1 -1
- package/dist/browser-prod/tracking-utils.mjs +17 -58
- package/dist/browser-prod/tracking-utils.mjs.map +1 -1
- package/dist/browser-prod/useShopifyCookies.mjs +34 -97
- package/dist/browser-prod/useShopifyCookies.mjs.map +1 -1
- package/dist/node-dev/ShopifyProvider.js.map +1 -1
- package/dist/node-dev/ShopifyProvider.mjs.map +1 -1
- package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.js +1 -1
- package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
- package/dist/node-dev/load-script.js +2 -0
- package/dist/node-dev/load-script.js.map +1 -1
- package/dist/node-dev/load-script.mjs +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.js +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.js.map +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.mjs +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.mjs.map +1 -1
- package/dist/node-dev/tracking-utils.js +17 -58
- package/dist/node-dev/tracking-utils.js.map +1 -1
- package/dist/node-dev/tracking-utils.mjs +17 -58
- package/dist/node-dev/tracking-utils.mjs.map +1 -1
- package/dist/node-dev/useShopifyCookies.js +34 -97
- package/dist/node-dev/useShopifyCookies.js.map +1 -1
- package/dist/node-dev/useShopifyCookies.mjs +34 -97
- package/dist/node-dev/useShopifyCookies.mjs.map +1 -1
- package/dist/node-prod/ShopifyProvider.js.map +1 -1
- package/dist/node-prod/ShopifyProvider.mjs.map +1 -1
- package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.js +1 -1
- package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
- package/dist/node-prod/load-script.js +2 -0
- package/dist/node-prod/load-script.js.map +1 -1
- package/dist/node-prod/load-script.mjs +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.js +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.js.map +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.mjs +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.mjs.map +1 -1
- package/dist/node-prod/tracking-utils.js +17 -58
- package/dist/node-prod/tracking-utils.js.map +1 -1
- package/dist/node-prod/tracking-utils.mjs +17 -58
- package/dist/node-prod/tracking-utils.mjs.map +1 -1
- package/dist/node-prod/useShopifyCookies.js +34 -97
- package/dist/node-prod/useShopifyCookies.js.map +1 -1
- package/dist/node-prod/useShopifyCookies.mjs +34 -97
- package/dist/node-prod/useShopifyCookies.mjs.map +1 -1
- package/dist/types/ShopifyProvider.d.ts +3 -0
- package/dist/types/tracking-utils.d.ts +5 -4
- package/dist/types/useShopifyCookies.d.ts +14 -33
- package/dist/umd/hydrogen-react.dev.js +55 -162
- package/dist/umd/hydrogen-react.dev.js.map +1 -1
- package/dist/umd/hydrogen-react.prod.js +4 -4
- package/dist/umd/hydrogen-react.prod.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,84 +1,49 @@
|
|
|
1
|
-
import { SHOPIFY_S, SHOPIFY_Y } from "./cart-constants.mjs";
|
|
2
1
|
import { SHOPIFY_UNIQUE_TOKEN_HEADER, SHOPIFY_VISIT_TOKEN_HEADER, getTrackingValues } from "./tracking-utils.mjs";
|
|
3
|
-
import { buildUUID } from "./cookies-utils.mjs";
|
|
4
2
|
import { useEffect, useRef, useState } from "react";
|
|
5
|
-
import { stringify } from "worktop/cookie";
|
|
6
3
|
//#region src/useShopifyCookies.tsx
|
|
7
|
-
var
|
|
8
|
-
var shortTermLength = 1800;
|
|
4
|
+
var CONSENT_MANAGEMENT_MARKER_HEADER = "Shopify-Storefront-Consent-Management";
|
|
9
5
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
6
|
+
* Optionally refreshes backend-managed cookies for standalone integrations.
|
|
7
|
+
* The Customer Privacy API owns tracking values and legacy cookie expiration.
|
|
12
8
|
*
|
|
13
|
-
* If `fetchTrackingValues` is true,
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* For example, set it to `true` if you are using `hydrogen-react` only with
|
|
18
|
-
* a different framework and still need to make a same-domain request to
|
|
19
|
-
* Storefront API to set cookies.
|
|
9
|
+
* If `fetchTrackingValues` is true, this sends a consent request through the
|
|
10
|
+
* Storefront API proxy, retrying against `checkoutDomain` if provided. Hydrogen's
|
|
11
|
+
* built-in analytics already delegates consent initialization to the Customer
|
|
12
|
+
* Privacy API and does not use this hook.
|
|
20
13
|
*
|
|
21
|
-
*
|
|
22
|
-
* Useful when you only want to use the newer tracking values and not rely on the deprecated ones.
|
|
23
|
-
*
|
|
24
|
-
* @returns `true` when cookies are set and ready.
|
|
14
|
+
* @returns `true` when the consent request has settled and cookies are ready.
|
|
25
15
|
* @publicDocs
|
|
26
16
|
*/
|
|
27
17
|
function useShopifyCookies(options) {
|
|
28
|
-
const {
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
fetchTrackingValues,
|
|
32
|
-
checkoutDomain
|
|
33
|
-
});
|
|
18
|
+
const { checkoutDomain, storefrontAccessToken, fetchTrackingValues = false } = options ?? {};
|
|
19
|
+
const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);
|
|
20
|
+
const hasFetchedTrackingValues = useRef(false);
|
|
34
21
|
useEffect(() => {
|
|
35
|
-
if (
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
*
|
|
39
|
-
* If no domain is provided, the cookie will be set for the current host.
|
|
40
|
-
* For Shopify, we need to ensure this domain is set with a leading dot.
|
|
41
|
-
*/
|
|
42
|
-
let currentDomain = domain || window.location.host;
|
|
43
|
-
if (checkoutDomain) {
|
|
44
|
-
const checkoutDomainParts = checkoutDomain.split(".").reverse();
|
|
45
|
-
const currentDomainParts = currentDomain.split(".").reverse();
|
|
46
|
-
const sameDomainParts = [];
|
|
47
|
-
checkoutDomainParts.forEach((part, index) => {
|
|
48
|
-
if (part === currentDomainParts[index]) sameDomainParts.push(part);
|
|
49
|
-
});
|
|
50
|
-
currentDomain = sameDomainParts.reverse().join(".");
|
|
51
|
-
}
|
|
52
|
-
if (/^localhost/.test(currentDomain)) currentDomain = "";
|
|
53
|
-
const domainWithLeadingDot = currentDomain ? /^\./.test(currentDomain) ? currentDomain : `.${currentDomain}` : "";
|
|
54
|
-
/**
|
|
55
|
-
* Set user and session cookies and refresh the expiry time
|
|
56
|
-
*/
|
|
57
|
-
if (hasUserConsent) {
|
|
58
|
-
const trackingValues = getTrackingValues();
|
|
59
|
-
if ((trackingValues.uniqueToken || trackingValues.visitToken || "").startsWith("00000000-")) return;
|
|
60
|
-
setCookie(SHOPIFY_Y, trackingValues.uniqueToken || buildUUID(), longTermLength, domainWithLeadingDot);
|
|
61
|
-
setCookie(SHOPIFY_S, trackingValues.visitToken || buildUUID(), shortTermLength, domainWithLeadingDot);
|
|
62
|
-
} else {
|
|
63
|
-
setCookie(SHOPIFY_Y, "", 0, domainWithLeadingDot);
|
|
64
|
-
setCookie(SHOPIFY_S, "", 0, domainWithLeadingDot);
|
|
22
|
+
if (!fetchTrackingValues) {
|
|
23
|
+
setCookiesReady(true);
|
|
24
|
+
return;
|
|
65
25
|
}
|
|
26
|
+
if (hasFetchedTrackingValues.current) return;
|
|
27
|
+
hasFetchedTrackingValues.current = true;
|
|
28
|
+
const fetchConsentValues = async () => {
|
|
29
|
+
try {
|
|
30
|
+
return await fetchTrackingValuesFromBrowser(storefrontAccessToken);
|
|
31
|
+
} catch (sameOriginError) {
|
|
32
|
+
if (!checkoutDomain) throw sameOriginError;
|
|
33
|
+
return fetchTrackingValuesFromBrowser(storefrontAccessToken, checkoutDomain);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
fetchConsentValues().catch((error) => {
|
|
37
|
+
console.warn("[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: " + (error instanceof Error ? error.message : String(error)));
|
|
38
|
+
}).finally(() => {
|
|
39
|
+
setCookiesReady(true);
|
|
40
|
+
});
|
|
66
41
|
}, [
|
|
67
|
-
coreCookiesReady,
|
|
68
|
-
hasUserConsent,
|
|
69
|
-
domain,
|
|
70
42
|
checkoutDomain,
|
|
71
|
-
|
|
43
|
+
fetchTrackingValues,
|
|
44
|
+
storefrontAccessToken
|
|
72
45
|
]);
|
|
73
|
-
return
|
|
74
|
-
}
|
|
75
|
-
function setCookie(name, value, maxage, domain) {
|
|
76
|
-
document.cookie = stringify(name, value, {
|
|
77
|
-
maxage,
|
|
78
|
-
domain,
|
|
79
|
-
samesite: "Lax",
|
|
80
|
-
path: "/"
|
|
81
|
-
});
|
|
46
|
+
return cookiesReady;
|
|
82
47
|
}
|
|
83
48
|
async function fetchTrackingValuesFromBrowser(storefrontAccessToken, storefrontApiDomain = "") {
|
|
84
49
|
const { uniqueToken, visitToken } = getTrackingValues();
|
|
@@ -87,43 +52,15 @@ async function fetchTrackingValuesFromBrowser(storefrontAccessToken, storefrontA
|
|
|
87
52
|
headers: {
|
|
88
53
|
"Content-Type": "application/json",
|
|
89
54
|
...storefrontAccessToken && { "X-Shopify-Storefront-Access-Token": storefrontAccessToken },
|
|
55
|
+
...storefrontApiDomain ? void 0 : { [CONSENT_MANAGEMENT_MARKER_HEADER]: "1" },
|
|
90
56
|
...visitToken || uniqueToken ? {
|
|
91
57
|
[SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,
|
|
92
58
|
[SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken
|
|
93
59
|
} : void 0
|
|
94
60
|
},
|
|
95
|
-
body: JSON.stringify({ query: "query ensureCookies { consentManagement { cookies(visitorConsent:{}) { cookieDomain } } }" })
|
|
61
|
+
body: JSON.stringify({ query: "query ensureCookies { consentManagement { cookies(visitorConsent:{}) { trackingConsentCookie cookieDomain shopifyUnique shopifyVisit } } }" })
|
|
96
62
|
});
|
|
97
63
|
if (!response.ok) throw new Error(`Failed to fetch consent from browser: ${response.status} ${response.statusText}`);
|
|
98
|
-
await response.json();
|
|
99
|
-
getTrackingValues();
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Gets http-only cookies from Storefront API via same-origin fetch request.
|
|
103
|
-
* Falls back to checkout domain if provided to at least obtain the tracking
|
|
104
|
-
* values via server-timing headers.
|
|
105
|
-
*/
|
|
106
|
-
function useCoreShopifyCookies({ checkoutDomain, storefrontAccessToken, fetchTrackingValues = false }) {
|
|
107
|
-
const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);
|
|
108
|
-
const hasFetchedTrackingValues = useRef(false);
|
|
109
|
-
useEffect(() => {
|
|
110
|
-
if (!fetchTrackingValues) {
|
|
111
|
-
setCookiesReady(true);
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
if (hasFetchedTrackingValues.current) return;
|
|
115
|
-
hasFetchedTrackingValues.current = true;
|
|
116
|
-
fetchTrackingValuesFromBrowser(storefrontAccessToken).catch((error) => checkoutDomain ? fetchTrackingValuesFromBrowser(storefrontAccessToken, checkoutDomain) : Promise.reject(error)).catch((error) => {
|
|
117
|
-
console.warn("[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: " + (error instanceof Error ? error.message : String(error)));
|
|
118
|
-
}).finally(() => {
|
|
119
|
-
setCookiesReady(true);
|
|
120
|
-
});
|
|
121
|
-
}, [
|
|
122
|
-
checkoutDomain,
|
|
123
|
-
fetchTrackingValues,
|
|
124
|
-
storefrontAccessToken
|
|
125
|
-
]);
|
|
126
|
-
return cookiesReady;
|
|
127
64
|
}
|
|
128
65
|
//#endregion
|
|
129
66
|
export { useShopifyCookies };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useShopifyCookies.mjs","names":[],"sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect, useRef, useState} from 'react';\n// @ts-ignore - worktop/cookie types not properly exported\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID} from './cookies-utils.js';\nimport {\n getTrackingValues,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from './tracking-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = CoreShopifyCookiesOptions & {\n /**\n * If set to `false`, Shopify cookies will be removed.\n * If set to `true`, Shopify unique user token cookie will have cookie expiry of 1 year.\n * Defaults to false.\n **/\n hasUserConsent?: boolean;\n /**\n * The domain scope of the cookie. Defaults to empty string.\n **/\n domain?: string;\n /**\n * The checkout domain of the shop. Defaults to empty string. If set, the cookie domain will check if it can be set with the checkout domain.\n */\n checkoutDomain?: string;\n /**\n * If set to `true`, it skips modifying the deprecated shopify_y and shopify_s cookies.\n */\n ignoreDeprecatedCookies?: boolean;\n};\n\n/**\n * Sets the `shopify_y` and `shopify_s` cookies in the browser based on user consent\n * for backward compatibility support.\n *\n * If `fetchTrackingValues` is true, it makes a request to Storefront API\n * to fetch or refresh Shopiy analytics and marketing cookies and tracking values.\n * Generally speaking, this should only be needed if you're not using Hydrogen's\n * built-in analytics components and hooks that already handle this automatically.\n * For example, set it to `true` if you are using `hydrogen-react` only with\n * a different framework and still need to make a same-domain request to\n * Storefront API to set cookies.\n *\n * If `ignoreDeprecatedCookies` is true, it skips setting the deprecated cookies entirely.\n * Useful when you only want to use the newer tracking values and not rely on the deprecated ones.\n *\n * @returns `true` when cookies are set and ready.\n * @publicDocs\n */\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): boolean {\n const {\n hasUserConsent,\n domain = '',\n checkoutDomain = '',\n storefrontAccessToken,\n fetchTrackingValues,\n ignoreDeprecatedCookies = false,\n } = options || {};\n\n const coreCookiesReady = useCoreShopifyCookies({\n storefrontAccessToken,\n fetchTrackingValues,\n checkoutDomain,\n });\n\n useEffect(() => {\n // Skip setting JS cookies until http-only cookies and server-timing\n // are ready so that we have values synced in JS and http-only cookies.\n if (ignoreDeprecatedCookies || !coreCookiesReady) return;\n\n /**\n * Setting cookie with domain\n *\n * If no domain is provided, the cookie will be set for the current host.\n * For Shopify, we need to ensure this domain is set with a leading dot.\n */\n\n // Use override domain or current host\n let currentDomain = domain || window.location.host;\n\n if (checkoutDomain) {\n const checkoutDomainParts = checkoutDomain.split('.').reverse();\n const currentDomainParts = currentDomain.split('.').reverse();\n const sameDomainParts: Array<string> = [];\n checkoutDomainParts.forEach((part, index) => {\n if (part === currentDomainParts[index]) {\n sameDomainParts.push(part);\n }\n });\n\n currentDomain = sameDomainParts.reverse().join('.');\n }\n\n // Reset domain if localhost\n if (/^localhost/.test(currentDomain)) currentDomain = '';\n\n // Shopify checkout only consumes cookies set with leading dot domain\n const domainWithLeadingDot = currentDomain\n ? /^\\./.test(currentDomain)\n ? currentDomain\n : `.${currentDomain}`\n : '';\n\n /**\n * Set user and session cookies and refresh the expiry time\n */\n if (hasUserConsent) {\n const trackingValues = getTrackingValues();\n if (\n (\n trackingValues.uniqueToken ||\n trackingValues.visitToken ||\n ''\n ).startsWith('00000000-')\n ) {\n // Skip writing cookies when tracking values signal we don't have consent yet\n return;\n }\n\n setCookie(\n SHOPIFY_Y,\n trackingValues.uniqueToken || buildUUID(),\n longTermLength,\n domainWithLeadingDot,\n );\n setCookie(\n SHOPIFY_S,\n trackingValues.visitToken || buildUUID(),\n shortTermLength,\n domainWithLeadingDot,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domainWithLeadingDot);\n setCookie(SHOPIFY_S, '', 0, domainWithLeadingDot);\n }\n }, [\n coreCookiesReady,\n hasUserConsent,\n domain,\n checkoutDomain,\n ignoreDeprecatedCookies,\n ]);\n\n return coreCookiesReady;\n}\n\nfunction setCookie(\n name: string,\n value: string,\n maxage: number,\n domain: string,\n): void {\n document.cookie = stringify(name, value, {\n maxage,\n domain,\n samesite: 'Lax',\n path: '/',\n });\n}\n\nasync function fetchTrackingValuesFromBrowser(\n storefrontAccessToken?: string,\n storefrontApiDomain = '',\n): Promise<void> {\n // These values might come from server-timing or old cookies.\n // If consent cannot be initially assumed, these tokens\n // will be dropped in SFAPI and it will return a mock token\n // starting with '00000000-'.\n // However, if consent can be assumed initially, these tokens\n // will be used to create proper cookies and continue our flow.\n const {uniqueToken, visitToken} = getTrackingValues();\n\n const response = await fetch(\n // TODO: update this endpoint when it becomes stable\n `${storefrontApiDomain.replace(/\\/+$/, '')}/api/unstable/graphql.json`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(storefrontAccessToken && {\n 'X-Shopify-Storefront-Access-Token': storefrontAccessToken,\n }),\n ...(visitToken || uniqueToken\n ? {\n [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,\n [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken,\n }\n : undefined),\n },\n body: JSON.stringify({\n query:\n // This query ensures we get _cmp (consent) server-timing header, which is not available in other queries.\n // This value can be passed later to consent-tracking-api and privacy-banner scripts to avoid extra requests.\n 'query ensureCookies { consentManagement { cookies(visitorConsent:{}) { cookieDomain } } }',\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch consent from browser: ${response.status} ${response.statusText}`,\n );\n }\n\n // Consume the body to complete the request and\n // ensure server-timing is available in performance API\n await response.json();\n\n // Ensure we cache the latest tracking values from resources timing\n getTrackingValues();\n}\n\ntype CoreShopifyCookiesOptions = {\n storefrontAccessToken?: string;\n fetchTrackingValues?: boolean;\n checkoutDomain?: string;\n};\n\n/**\n * Gets http-only cookies from Storefront API via same-origin fetch request.\n * Falls back to checkout domain if provided to at least obtain the tracking\n * values via server-timing headers.\n */\nfunction useCoreShopifyCookies({\n checkoutDomain,\n storefrontAccessToken,\n fetchTrackingValues = false,\n}: CoreShopifyCookiesOptions) {\n const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);\n const hasFetchedTrackingValues = useRef(false);\n\n useEffect(() => {\n if (!fetchTrackingValues) {\n // Backend did the work, or proxy is disabled.\n setCookiesReady(true);\n return;\n }\n\n // React runs effects twice in dev mode, avoid double fetching\n if (hasFetchedTrackingValues.current) return;\n hasFetchedTrackingValues.current = true;\n\n // Fetch consent from browser via proxy\n fetchTrackingValuesFromBrowser(storefrontAccessToken)\n .catch((error) =>\n checkoutDomain\n ? // Retry with checkout domain if available to at least\n // get the server-timing values for tracking.\n fetchTrackingValuesFromBrowser(\n storefrontAccessToken,\n checkoutDomain,\n )\n : Promise.reject(error),\n )\n .catch((error) => {\n console.warn(\n '[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n })\n .finally(() => {\n // Proceed even on errors, degraded tracking is better than no app\n setCookiesReady(true);\n });\n }, [checkoutDomain, fetchTrackingValues, storefrontAccessToken]);\n\n return cookiesReady;\n}\n"],"mappings":";;;;;;AAWA,IAAM,iBAAiB,OAAU,KAAK,MAAM;AAC5C,IAAM,kBAAkB;;;;;;;;;;;;;;;;;;;AAyCxB,SAAgB,kBAAkB,SAA6C;CAC7E,MAAM,EACJ,gBACA,SAAS,IACT,iBAAiB,IACjB,uBACA,qBACA,0BAA0B,UACxB,WAAW,EAAE;CAEjB,MAAM,mBAAmB,sBAAsB;EAC7C;EACA;EACA;EACD,CAAC;AAEF,iBAAgB;AAGd,MAAI,2BAA2B,CAAC,iBAAkB;;;;;;;EAUlD,IAAI,gBAAgB,UAAU,OAAO,SAAS;AAE9C,MAAI,gBAAgB;GAClB,MAAM,sBAAsB,eAAe,MAAM,IAAI,CAAC,SAAS;GAC/D,MAAM,qBAAqB,cAAc,MAAM,IAAI,CAAC,SAAS;GAC7D,MAAM,kBAAiC,EAAE;AACzC,uBAAoB,SAAS,MAAM,UAAU;AAC3C,QAAI,SAAS,mBAAmB,OAC9B,iBAAgB,KAAK,KAAK;KAE5B;AAEF,mBAAgB,gBAAgB,SAAS,CAAC,KAAK,IAAI;;AAIrD,MAAI,aAAa,KAAK,cAAc,CAAE,iBAAgB;EAGtD,MAAM,uBAAuB,gBACzB,MAAM,KAAK,cAAc,GACvB,gBACA,IAAI,kBACN;;;;AAKJ,MAAI,gBAAgB;GAClB,MAAM,iBAAiB,mBAAmB;AAC1C,QAEI,eAAe,eACf,eAAe,cACf,IACA,WAAW,YAAY,CAGzB;AAGF,aACE,WACA,eAAe,eAAe,WAAW,EACzC,gBACA,qBACD;AACD,aACE,WACA,eAAe,cAAc,WAAW,EACxC,iBACA,qBACD;SACI;AACL,aAAU,WAAW,IAAI,GAAG,qBAAqB;AACjD,aAAU,WAAW,IAAI,GAAG,qBAAqB;;IAElD;EACD;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO;;AAGT,SAAS,UACP,MACA,OACA,QACA,QACM;AACN,UAAS,SAAS,UAAU,MAAM,OAAO;EACvC;EACA;EACA,UAAU;EACV,MAAM;EACP,CAAC;;AAGJ,eAAe,+BACb,uBACA,sBAAsB,IACP;CAOf,MAAM,EAAC,aAAa,eAAc,mBAAmB;CAErD,MAAM,WAAW,MAAM,MAErB,GAAG,oBAAoB,QAAQ,QAAQ,GAAG,CAAC,6BAC3C;EACE,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,GAAI,yBAAyB,EAC3B,qCAAqC,uBACtC;GACD,GAAI,cAAc,cACd;KACG,6BAA6B;KAC7B,8BAA8B;IAChC,GACD,KAAA;GACL;EACD,MAAM,KAAK,UAAU,EACnB,OAGE,6FACH,CAAC;EACH,CACF;AAED,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,yCAAyC,SAAS,OAAO,GAAG,SAAS,aACtE;AAKH,OAAM,SAAS,MAAM;AAGrB,oBAAmB;;;;;;;AAcrB,SAAS,sBAAsB,EAC7B,gBACA,uBACA,sBAAsB,SACM;CAC5B,MAAM,CAAC,cAAc,mBAAmB,SAAS,CAAC,oBAAoB;CACtE,MAAM,2BAA2B,OAAO,MAAM;AAE9C,iBAAgB;AACd,MAAI,CAAC,qBAAqB;AAExB,mBAAgB,KAAK;AACrB;;AAIF,MAAI,yBAAyB,QAAS;AACtC,2BAAyB,UAAU;AAGnC,iCAA+B,sBAAsB,CAClD,OAAO,UACN,iBAGI,+BACE,uBACA,eACD,GACD,QAAQ,OAAO,MAAM,CAC1B,CACA,OAAO,UAAU;AAChB,WAAQ,KACN,gFACG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC1D;IACD,CACD,cAAc;AAEb,mBAAgB,KAAK;IACrB;IACH;EAAC;EAAgB;EAAqB;EAAsB,CAAC;AAEhE,QAAO"}
|
|
1
|
+
{"version":3,"file":"useShopifyCookies.mjs","names":[],"sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect, useRef, useState} from 'react';\nimport {\n getTrackingValues,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from './tracking-utils.js';\n\n// Marks the same-origin consent request so the backend can identify\n// headless consent-management traffic. A custom header on the cross-origin\n// checkout retry would fail its CORS preflight, so it is never sent there.\n// NOTE: packages/hydrogen/src/constants.ts defines the same header name\n// (STOREFRONT_CONSENT_MANAGEMENT_HEADER) for the server-side proxy\n// forwarding; keep the two in sync.\nconst CONSENT_MANAGEMENT_MARKER_HEADER =\n 'Shopify-Storefront-Consent-Management';\n\ntype UseShopifyCookiesOptions = {\n storefrontAccessToken?: string;\n fetchTrackingValues?: boolean;\n /** @deprecated No longer used. The Customer Privacy API manages Shopify cookies. */\n hasUserConsent?: boolean;\n /** @deprecated No longer used. The Customer Privacy API manages cookie domains. */\n domain?: string;\n /** The checkout domain used if the same-origin consent request fails. */\n checkoutDomain?: string;\n /** @deprecated No longer used. The Customer Privacy API expires deprecated cookies. */\n ignoreDeprecatedCookies?: boolean;\n};\n\n/**\n * Optionally refreshes backend-managed cookies for standalone integrations.\n * The Customer Privacy API owns tracking values and legacy cookie expiration.\n *\n * If `fetchTrackingValues` is true, this sends a consent request through the\n * Storefront API proxy, retrying against `checkoutDomain` if provided. Hydrogen's\n * built-in analytics already delegates consent initialization to the Customer\n * Privacy API and does not use this hook.\n *\n * @returns `true` when the consent request has settled and cookies are ready.\n * @publicDocs\n */\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): boolean {\n const {\n checkoutDomain,\n storefrontAccessToken,\n fetchTrackingValues = false,\n } = options ?? {};\n const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);\n const hasFetchedTrackingValues = useRef(false);\n\n useEffect(() => {\n if (!fetchTrackingValues) {\n // Backend did the work, or proxy is disabled.\n setCookiesReady(true);\n return;\n }\n\n // React runs effects twice in dev mode, avoid double fetching\n if (hasFetchedTrackingValues.current) return;\n hasFetchedTrackingValues.current = true;\n\n const fetchConsentValues = async () => {\n try {\n return await fetchTrackingValuesFromBrowser(storefrontAccessToken);\n } catch (sameOriginError) {\n if (!checkoutDomain) throw sameOriginError;\n // Retry with checkout domain if the same-origin proxy failed.\n return fetchTrackingValuesFromBrowser(\n storefrontAccessToken,\n checkoutDomain,\n );\n }\n };\n\n fetchConsentValues()\n .catch((error) => {\n console.warn(\n '[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n })\n .finally(() => {\n // Proceed even on errors, degraded tracking is better than no app\n setCookiesReady(true);\n });\n }, [checkoutDomain, fetchTrackingValues, storefrontAccessToken]);\n\n return cookiesReady;\n}\n\nasync function fetchTrackingValuesFromBrowser(\n storefrontAccessToken?: string,\n storefrontApiDomain = '',\n): Promise<void> {\n // Forward the current CTA tokens or legacy cookies to preserve the session.\n // CTA suppresses token generation while its async consent is loading.\n const {uniqueToken, visitToken} = getTrackingValues();\n\n const response = await fetch(\n // TODO: update this endpoint when it becomes stable\n `${storefrontApiDomain.replace(/\\/+$/, '')}/api/unstable/graphql.json`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(storefrontAccessToken && {\n 'X-Shopify-Storefront-Access-Token': storefrontAccessToken,\n }),\n // The marker header goes on the same-origin request only, where the\n // Hydrogen server proxy can act on it.\n ...(storefrontApiDomain\n ? undefined\n : {[CONSENT_MANAGEMENT_MARKER_HEADER]: '1'}),\n ...(visitToken || uniqueToken\n ? {\n [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,\n [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken,\n }\n : undefined),\n },\n body: JSON.stringify({\n query:\n // The empty `visitorConsent` refreshes cookies without changing\n // the stored consent.\n 'query ensureCookies { consentManagement { cookies(visitorConsent:{}) { trackingConsentCookie cookieDomain shopifyUnique shopifyVisit } } }',\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch consent from browser: ${response.status} ${response.statusText}`,\n );\n }\n}\n"],"mappings":";;;AAaA,IAAM,mCACJ;;;;;;;;;;;;;AA2BF,SAAgB,kBAAkB,SAA6C;CAC7E,MAAM,EACJ,gBACA,uBACA,sBAAsB,UACpB,WAAW,EAAE;CACjB,MAAM,CAAC,cAAc,mBAAmB,SAAS,CAAC,oBAAoB;CACtE,MAAM,2BAA2B,OAAO,MAAM;AAE9C,iBAAgB;AACd,MAAI,CAAC,qBAAqB;AAExB,mBAAgB,KAAK;AACrB;;AAIF,MAAI,yBAAyB,QAAS;AACtC,2BAAyB,UAAU;EAEnC,MAAM,qBAAqB,YAAY;AACrC,OAAI;AACF,WAAO,MAAM,+BAA+B,sBAAsB;YAC3D,iBAAiB;AACxB,QAAI,CAAC,eAAgB,OAAM;AAE3B,WAAO,+BACL,uBACA,eACD;;;AAIL,sBAAoB,CACjB,OAAO,UAAU;AAChB,WAAQ,KACN,gFACG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC1D;IACD,CACD,cAAc;AAEb,mBAAgB,KAAK;IACrB;IACH;EAAC;EAAgB;EAAqB;EAAsB,CAAC;AAEhE,QAAO;;AAGT,eAAe,+BACb,uBACA,sBAAsB,IACP;CAGf,MAAM,EAAC,aAAa,eAAc,mBAAmB;CAErD,MAAM,WAAW,MAAM,MAErB,GAAG,oBAAoB,QAAQ,QAAQ,GAAG,CAAC,6BAC3C;EACE,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,GAAI,yBAAyB,EAC3B,qCAAqC,uBACtC;GAGD,GAAI,sBACA,KAAA,IACA,GAAE,mCAAmC,KAAI;GAC7C,GAAI,cAAc,cACd;KACG,6BAA6B;KAC7B,8BAA8B;IAChC,GACD,KAAA;GACL;EACD,MAAM,KAAK,UAAU,EACnB,OAGE,8IACH,CAAC;EACH,CACF;AAED,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,yCAAyC,SAAS,OAAO,GAAG,SAAS,aACtE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopifyProvider.js","names":[],"sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * Hydrogen server sets this server timing key when the SFAPI proxy is enabled.\n * Read it automatically in the browser for apps using frontend cart in full-stack Hydrogen,\n * but don't export this utility yet since we don't want to make this a public convention.\n */\nfunction isSfapiProxyEnabled() {\n if (typeof window === 'undefined') return false;\n\n try {\n const navigationEntry = window.performance?.getEntriesByType?.(\n 'navigation',\n )[0] as PerformanceNavigationTiming;\n\n return !!navigationEntry?.serverTiming?.some(\n (entry) => entry.name === '_sfapi_proxy',\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n * @publicDocs\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n const sameDomainForStorefrontApi =\n shopifyConfig.sameDomainForStorefrontApi ?? isSfapiProxyEnabled();\n\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n const domain = overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n }\n\n return {\n ...shopifyConfig,\n sameDomainForStorefrontApi,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl =\n sameDomainForStorefrontApi && typeof window !== 'undefined'\n ? window.location.origin\n : getShopifyDomain({\n storeDomain:\n overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n * @publicDocs\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n /**\n * Uses the current window.location.origin for Storefront API requests.\n * This requires setting up a proxy for Storefront API requests in your domain.\n */\n sameDomainForStorefrontApi?: boolean;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase, ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n"],"mappings":";;;;;;AAKA,IAAa,wBAA6C;CACxD,aAAa;CACb,iBAAiB;CACjB,sBAAsB,iCAAA;CACtB,gBAAgB;CAChB,iBAAiB;CACjB,sBAAsB;AACpB,SAAO;;CAET,wBAAwB;AACtB,SAAO,EAAE;;CAEX,mBAAmB;AACjB,SAAO;;CAEV;AAED,IAAM,kBAAA,GAAA,MAAA,eACJ,sBACD;;;;;;AAOD,SAAS,sBAAsB;AAC7B,KAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,KAAI;AAKF,SAAO,CAAC,EAJgB,OAAO,aAAa,mBAC1C,aACD,CAAC,KAEwB,cAAc,MACrC,UAAU,MAAM,SAAS,eAC3B;UACM,GAAG;AACV,SAAO;;;;;;;AAQX,SAAgB,gBAAgB,EAC9B,UACA,GAAG,iBACiC;AACpC,KACE,CAAC,cAAc,kBACf,CAAC,cAAc,mBACf,CAAC,cAAc,eACf,CAAC,cAAc,mBACf,CAAC,cAAc,qBAEf,OAAM,IAAI,MACR,6DACD;AAGH,KAAI,cAAc,yBAAA,UAChB,SAAQ,KACN,oGAAoG,iCAAA,cAAc,2CAA2C,cAAc,qBAAqB,yGACjM;CAGH,MAAM,eAAA,GAAA,MAAA,eAAiD;EACrD,MAAM,6BACJ,cAAc,8BAA8B,qBAAqB;EAEnE,SAAS,iBAAiB,eAAgD;GACxE,MAAM,SAAS,eAAe,eAAe,cAAc;AAC3D,UAAO,OAAO,SAAS,MAAM,GAAG,SAAS,WAAW;;AAGtD,SAAO;GACL,GAAG;GACH;GACA,sBAAsB,eAAuC;AAC3D,WAAO,0BAAA,yBACL,cAAc,aACd,cAAc,sBACd,cAAc,mBAAmB,cAAc,gBAChD;;GAEH;GACA,oBAAoB,eAAuB;IACzC,MAAM,iBACJ,8BAA8B,OAAO,WAAW,cAC5C,OAAO,SAAS,SAChB,iBAAiB,EACf,aACE,eAAe,eAAe,cAAc,aAC/C,CAAC;AAER,WAAO,GAAG,iBACR,eAAe,SAAS,IAAI,GAAG,KAAK,IACrC,MACC,eAAe,wBACf,cAAc,qBACf;;GAEJ;IACA,CAAC,cAAc,CAAC;AAEnB,QACE,iBAAA,GAAA,kBAAA,KAAC,eAAe,UAAhB;EAAyB,OAAO;EAC7B;EACuB,CAAA;;;;;;AAQ9B,SAAgB,UAA+B;CAC7C,MAAM,eAAA,GAAA,MAAA,YAAyB,eAAe;AAC9C,KAAI,CAAC,YACH,OAAM,IAAI,MAAM,yDAAyD;AAE3E,QAAO"}
|
|
1
|
+
{"version":3,"file":"ShopifyProvider.js","names":[],"sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * Hydrogen server sets this server timing key when the SFAPI proxy is enabled.\n * Read it automatically in the browser for apps using frontend cart in full-stack Hydrogen,\n * but don't export this utility yet since we don't want to make this a public convention.\n */\nfunction isSfapiProxyEnabled() {\n if (typeof window === 'undefined') return false;\n\n try {\n const navigationEntry = window.performance?.getEntriesByType?.(\n 'navigation',\n )[0] as PerformanceNavigationTiming;\n\n return !!navigationEntry?.serverTiming?.some(\n (entry) => entry.name === '_sfapi_proxy',\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n * @publicDocs\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n const sameDomainForStorefrontApi =\n shopifyConfig.sameDomainForStorefrontApi ?? isSfapiProxyEnabled();\n\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n const domain = overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n }\n\n return {\n ...shopifyConfig,\n sameDomainForStorefrontApi,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl =\n sameDomainForStorefrontApi && typeof window !== 'undefined'\n ? window.location.origin\n : getShopifyDomain({\n storeDomain:\n overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n * @publicDocs\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n /**\n * Uses the current window.location.origin for Storefront API requests.\n * This requires setting up a proxy for Storefront API requests in your domain.\n * Without the proxy, cart requests still work, but visitor analytics and\n * session attribution do not,\n * [notice](https://shopify.dev/changelog/posts/tracking-cookie-deprecation-hydrogen).\n */\n sameDomainForStorefrontApi?: boolean;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase, ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n"],"mappings":";;;;;;AAKA,IAAa,wBAA6C;CACxD,aAAa;CACb,iBAAiB;CACjB,sBAAsB,iCAAA;CACtB,gBAAgB;CAChB,iBAAiB;CACjB,sBAAsB;AACpB,SAAO;;CAET,wBAAwB;AACtB,SAAO,EAAE;;CAEX,mBAAmB;AACjB,SAAO;;CAEV;AAED,IAAM,kBAAA,GAAA,MAAA,eACJ,sBACD;;;;;;AAOD,SAAS,sBAAsB;AAC7B,KAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,KAAI;AAKF,SAAO,CAAC,EAJgB,OAAO,aAAa,mBAC1C,aACD,CAAC,KAEwB,cAAc,MACrC,UAAU,MAAM,SAAS,eAC3B;UACM,GAAG;AACV,SAAO;;;;;;;AAQX,SAAgB,gBAAgB,EAC9B,UACA,GAAG,iBACiC;AACpC,KACE,CAAC,cAAc,kBACf,CAAC,cAAc,mBACf,CAAC,cAAc,eACf,CAAC,cAAc,mBACf,CAAC,cAAc,qBAEf,OAAM,IAAI,MACR,6DACD;AAGH,KAAI,cAAc,yBAAA,UAChB,SAAQ,KACN,oGAAoG,iCAAA,cAAc,2CAA2C,cAAc,qBAAqB,yGACjM;CAGH,MAAM,eAAA,GAAA,MAAA,eAAiD;EACrD,MAAM,6BACJ,cAAc,8BAA8B,qBAAqB;EAEnE,SAAS,iBAAiB,eAAgD;GACxE,MAAM,SAAS,eAAe,eAAe,cAAc;AAC3D,UAAO,OAAO,SAAS,MAAM,GAAG,SAAS,WAAW;;AAGtD,SAAO;GACL,GAAG;GACH;GACA,sBAAsB,eAAuC;AAC3D,WAAO,0BAAA,yBACL,cAAc,aACd,cAAc,sBACd,cAAc,mBAAmB,cAAc,gBAChD;;GAEH;GACA,oBAAoB,eAAuB;IACzC,MAAM,iBACJ,8BAA8B,OAAO,WAAW,cAC5C,OAAO,SAAS,SAChB,iBAAiB,EACf,aACE,eAAe,eAAe,cAAc,aAC/C,CAAC;AAER,WAAO,GAAG,iBACR,eAAe,SAAS,IAAI,GAAG,KAAK,IACrC,MACC,eAAe,wBACf,cAAc,qBACf;;GAEJ;IACA,CAAC,cAAc,CAAC;AAEnB,QACE,iBAAA,GAAA,kBAAA,KAAC,eAAe,UAAhB;EAAyB,OAAO;EAC7B;EACuB,CAAA;;;;;;AAQ9B,SAAgB,UAA+B;CAC7C,MAAM,eAAA,GAAA,MAAA,YAAyB,eAAe;AAC9C,KAAI,CAAC,YACH,OAAM,IAAI,MAAM,yDAAyD;AAE3E,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopifyProvider.mjs","names":[],"sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * Hydrogen server sets this server timing key when the SFAPI proxy is enabled.\n * Read it automatically in the browser for apps using frontend cart in full-stack Hydrogen,\n * but don't export this utility yet since we don't want to make this a public convention.\n */\nfunction isSfapiProxyEnabled() {\n if (typeof window === 'undefined') return false;\n\n try {\n const navigationEntry = window.performance?.getEntriesByType?.(\n 'navigation',\n )[0] as PerformanceNavigationTiming;\n\n return !!navigationEntry?.serverTiming?.some(\n (entry) => entry.name === '_sfapi_proxy',\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n * @publicDocs\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n const sameDomainForStorefrontApi =\n shopifyConfig.sameDomainForStorefrontApi ?? isSfapiProxyEnabled();\n\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n const domain = overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n }\n\n return {\n ...shopifyConfig,\n sameDomainForStorefrontApi,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl =\n sameDomainForStorefrontApi && typeof window !== 'undefined'\n ? window.location.origin\n : getShopifyDomain({\n storeDomain:\n overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n * @publicDocs\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n /**\n * Uses the current window.location.origin for Storefront API requests.\n * This requires setting up a proxy for Storefront API requests in your domain.\n */\n sameDomainForStorefrontApi?: boolean;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase, ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n"],"mappings":";;;;;AAKA,IAAa,wBAA6C;CACxD,aAAa;CACb,iBAAiB;CACjB,sBAAsB;CACtB,gBAAgB;CAChB,iBAAiB;CACjB,sBAAsB;AACpB,SAAO;;CAET,wBAAwB;AACtB,SAAO,EAAE;;CAEX,mBAAmB;AACjB,SAAO;;CAEV;AAED,IAAM,iBAAiB,cACrB,sBACD;;;;;;AAOD,SAAS,sBAAsB;AAC7B,KAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,KAAI;AAKF,SAAO,CAAC,EAJgB,OAAO,aAAa,mBAC1C,aACD,CAAC,KAEwB,cAAc,MACrC,UAAU,MAAM,SAAS,eAC3B;UACM,GAAG;AACV,SAAO;;;;;;;AAQX,SAAgB,gBAAgB,EAC9B,UACA,GAAG,iBACiC;AACpC,KACE,CAAC,cAAc,kBACf,CAAC,cAAc,mBACf,CAAC,cAAc,eACf,CAAC,cAAc,mBACf,CAAC,cAAc,qBAEf,OAAM,IAAI,MACR,6DACD;AAGH,KAAI,cAAc,yBAAA,UAChB,SAAQ,KACN,oGAAoG,cAAc,2CAA2C,cAAc,qBAAqB,yGACjM;CAGH,MAAM,cAAc,cAAmC;EACrD,MAAM,6BACJ,cAAc,8BAA8B,qBAAqB;EAEnE,SAAS,iBAAiB,eAAgD;GACxE,MAAM,SAAS,eAAe,eAAe,cAAc;AAC3D,UAAO,OAAO,SAAS,MAAM,GAAG,SAAS,WAAW;;AAGtD,SAAO;GACL,GAAG;GACH;GACA,sBAAsB,eAAuC;AAC3D,WAAO,yBACL,cAAc,aACd,cAAc,sBACd,cAAc,mBAAmB,cAAc,gBAChD;;GAEH;GACA,oBAAoB,eAAuB;IACzC,MAAM,iBACJ,8BAA8B,OAAO,WAAW,cAC5C,OAAO,SAAS,SAChB,iBAAiB,EACf,aACE,eAAe,eAAe,cAAc,aAC/C,CAAC;AAER,WAAO,GAAG,iBACR,eAAe,SAAS,IAAI,GAAG,KAAK,IACrC,MACC,eAAe,wBACf,cAAc,qBACf;;GAEJ;IACA,CAAC,cAAc,CAAC;AAEnB,QACE,oBAAC,eAAe,UAAhB;EAAyB,OAAO;EAC7B;EACuB,CAAA;;;;;;AAQ9B,SAAgB,UAA+B;CAC7C,MAAM,cAAc,WAAW,eAAe;AAC9C,KAAI,CAAC,YACH,OAAM,IAAI,MAAM,yDAAyD;AAE3E,QAAO"}
|
|
1
|
+
{"version":3,"file":"ShopifyProvider.mjs","names":[],"sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * Hydrogen server sets this server timing key when the SFAPI proxy is enabled.\n * Read it automatically in the browser for apps using frontend cart in full-stack Hydrogen,\n * but don't export this utility yet since we don't want to make this a public convention.\n */\nfunction isSfapiProxyEnabled() {\n if (typeof window === 'undefined') return false;\n\n try {\n const navigationEntry = window.performance?.getEntriesByType?.(\n 'navigation',\n )[0] as PerformanceNavigationTiming;\n\n return !!navigationEntry?.serverTiming?.some(\n (entry) => entry.name === '_sfapi_proxy',\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n * @publicDocs\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n const sameDomainForStorefrontApi =\n shopifyConfig.sameDomainForStorefrontApi ?? isSfapiProxyEnabled();\n\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n const domain = overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n }\n\n return {\n ...shopifyConfig,\n sameDomainForStorefrontApi,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl =\n sameDomainForStorefrontApi && typeof window !== 'undefined'\n ? window.location.origin\n : getShopifyDomain({\n storeDomain:\n overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n * @publicDocs\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n /**\n * Uses the current window.location.origin for Storefront API requests.\n * This requires setting up a proxy for Storefront API requests in your domain.\n * Without the proxy, cart requests still work, but visitor analytics and\n * session attribution do not,\n * [notice](https://shopify.dev/changelog/posts/tracking-cookie-deprecation-hydrogen).\n */\n sameDomainForStorefrontApi?: boolean;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase, ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n"],"mappings":";;;;;AAKA,IAAa,wBAA6C;CACxD,aAAa;CACb,iBAAiB;CACjB,sBAAsB;CACtB,gBAAgB;CAChB,iBAAiB;CACjB,sBAAsB;AACpB,SAAO;;CAET,wBAAwB;AACtB,SAAO,EAAE;;CAEX,mBAAmB;AACjB,SAAO;;CAEV;AAED,IAAM,iBAAiB,cACrB,sBACD;;;;;;AAOD,SAAS,sBAAsB;AAC7B,KAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,KAAI;AAKF,SAAO,CAAC,EAJgB,OAAO,aAAa,mBAC1C,aACD,CAAC,KAEwB,cAAc,MACrC,UAAU,MAAM,SAAS,eAC3B;UACM,GAAG;AACV,SAAO;;;;;;;AAQX,SAAgB,gBAAgB,EAC9B,UACA,GAAG,iBACiC;AACpC,KACE,CAAC,cAAc,kBACf,CAAC,cAAc,mBACf,CAAC,cAAc,eACf,CAAC,cAAc,mBACf,CAAC,cAAc,qBAEf,OAAM,IAAI,MACR,6DACD;AAGH,KAAI,cAAc,yBAAA,UAChB,SAAQ,KACN,oGAAoG,cAAc,2CAA2C,cAAc,qBAAqB,yGACjM;CAGH,MAAM,cAAc,cAAmC;EACrD,MAAM,6BACJ,cAAc,8BAA8B,qBAAqB;EAEnE,SAAS,iBAAiB,eAAgD;GACxE,MAAM,SAAS,eAAe,eAAe,cAAc;AAC3D,UAAO,OAAO,SAAS,MAAM,GAAG,SAAS,WAAW;;AAGtD,SAAO;GACL,GAAG;GACH;GACA,sBAAsB,eAAuC;AAC3D,WAAO,yBACL,cAAc,aACd,cAAc,sBACd,cAAc,mBAAmB,cAAc,gBAChD;;GAEH;GACA,oBAAoB,eAAuB;IACzC,MAAM,iBACJ,8BAA8B,OAAO,WAAW,cAC5C,OAAO,SAAS,SAChB,iBAAiB,EACf,aACE,eAAe,eAAe,cAAc,aAC/C,CAAC;AAER,WAAO,GAAG,iBACR,eAAe,SAAS,IAAI,GAAG,KAAK,IACrC,MACC,eAAe,wBACf,cAAc,qBACf;;GAEJ;IACA,CAAC,cAAc,CAAC;AAEnB,QACE,oBAAC,eAAe,UAAhB;EAAyB,OAAO;EAC7B;EACuB,CAAA;;;;;;AAQ9B,SAAgB,UAA+B;CAC7C,MAAM,cAAc,WAAW,eAAe;AAC9C,KAAI,CAAC,YACH,OAAM,IAAI,MAAM,yDAAyD;AAE3E,QAAO"}
|
|
@@ -100,7 +100,7 @@ function formatPayload(payload) {
|
|
|
100
100
|
const payloadWithPrivacy = payload;
|
|
101
101
|
return {
|
|
102
102
|
source: payload.shopifySalesChannel || require_analytics_constants.ShopifySalesChannel.headless,
|
|
103
|
-
asset_version_id: payload.assetVersionId || "2026.4.
|
|
103
|
+
asset_version_id: payload.assetVersionId || "2026.4.4",
|
|
104
104
|
hydrogenSubchannelId: payload.storefrontId || payload.hydrogenSubchannelId || "0",
|
|
105
105
|
is_persistent_cookie: payload.hasUserConsent,
|
|
106
106
|
deprecated_visit_token: payload.visitToken,
|
|
@@ -100,7 +100,7 @@ function formatPayload(payload) {
|
|
|
100
100
|
const payloadWithPrivacy = payload;
|
|
101
101
|
return {
|
|
102
102
|
source: payload.shopifySalesChannel || ShopifySalesChannel.headless,
|
|
103
|
-
asset_version_id: payload.assetVersionId || "2026.4.
|
|
103
|
+
asset_version_id: payload.assetVersionId || "2026.4.4",
|
|
104
104
|
hydrogenSubchannelId: payload.storefrontId || payload.hydrogenSubchannelId || "0",
|
|
105
105
|
is_persistent_cookie: payload.hasUserConsent,
|
|
106
106
|
deprecated_visit_token: payload.visitToken,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
1
2
|
require("./_virtual/_rolldown/runtime.js");
|
|
2
3
|
let react = require("react");
|
|
3
4
|
//#region src/load-script.tsx
|
|
@@ -38,6 +39,7 @@ function useLoadScript(url, options) {
|
|
|
38
39
|
return status;
|
|
39
40
|
}
|
|
40
41
|
//#endregion
|
|
42
|
+
exports.loadScript = loadScript;
|
|
41
43
|
exports.useLoadScript = useLoadScript;
|
|
42
44
|
|
|
43
45
|
//# sourceMappingURL=load-script.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-script.js","names":[],"sources":["../../src/load-script.tsx"],"sourcesContent":["import {useState, useEffect} from 'react';\n\nconst SCRIPTS_LOADED: Record<string, Promise<boolean>> = {};\n\ntype LoadScriptOptions = {\n module?: boolean;\n in?: 'head' | 'body';\n attributes?: Record<string, string>;\n};\n\nexport function loadScript(\n src: string,\n options?: LoadScriptOptions,\n): Promise<boolean> {\n const isScriptLoaded = SCRIPTS_LOADED[src];\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n if (isScriptLoaded) {\n return isScriptLoaded;\n }\n\n const promise = new Promise<boolean>((resolve, reject) => {\n const script = document.createElement('script');\n if (options?.module) {\n script.type = 'module';\n } else {\n script.type = 'text/javascript';\n }\n script.src = src;\n script.onload = (): void => {\n resolve(true);\n };\n script.onerror = (): void => {\n reject(false);\n };\n if (options?.in === 'head') {\n document.head.appendChild(script);\n } else {\n document.body.appendChild(script);\n }\n\n const attributes = options?.attributes;\n if (attributes) {\n Object.keys(attributes).forEach((key) => {\n script.setAttribute(key, attributes[key]);\n });\n }\n });\n\n SCRIPTS_LOADED[src] = promise;\n\n return promise;\n}\n\n/** @publicDocs */\nexport type LoadScriptParams = Parameters<typeof loadScript>;\n\n/**\n * The `useLoadScript` hook loads an external script tag in the browser. It allows React components to lazy-load large third-party dependencies.\n * @publicDocs\n */\nexport function useLoadScript(\n url: LoadScriptParams[0],\n options?: LoadScriptParams[1],\n): ScriptState {\n const [status, setStatus] = useState<ScriptState>('loading');\n\n useEffect(\n () => {\n loadScript(url, options)\n .then(() => setStatus('done'))\n .catch(() => setStatus('error'));\n },\n // Ignore options changes since it won't trigger a new load.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [url],\n );\n\n return status;\n}\n\ntype ScriptState = 'loading' | 'done' | 'error';\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"load-script.js","names":[],"sources":["../../src/load-script.tsx"],"sourcesContent":["import {useState, useEffect} from 'react';\n\nconst SCRIPTS_LOADED: Record<string, Promise<boolean>> = {};\n\ntype LoadScriptOptions = {\n module?: boolean;\n in?: 'head' | 'body';\n attributes?: Record<string, string>;\n};\n\nexport function loadScript(\n src: string,\n options?: LoadScriptOptions,\n): Promise<boolean> {\n const isScriptLoaded = SCRIPTS_LOADED[src];\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n if (isScriptLoaded) {\n return isScriptLoaded;\n }\n\n const promise = new Promise<boolean>((resolve, reject) => {\n const script = document.createElement('script');\n if (options?.module) {\n script.type = 'module';\n } else {\n script.type = 'text/javascript';\n }\n script.src = src;\n script.onload = (): void => {\n resolve(true);\n };\n script.onerror = (): void => {\n reject(false);\n };\n if (options?.in === 'head') {\n document.head.appendChild(script);\n } else {\n document.body.appendChild(script);\n }\n\n const attributes = options?.attributes;\n if (attributes) {\n Object.keys(attributes).forEach((key) => {\n script.setAttribute(key, attributes[key]);\n });\n }\n });\n\n SCRIPTS_LOADED[src] = promise;\n\n return promise;\n}\n\n/** @publicDocs */\nexport type LoadScriptParams = Parameters<typeof loadScript>;\n\n/**\n * The `useLoadScript` hook loads an external script tag in the browser. It allows React components to lazy-load large third-party dependencies.\n * @publicDocs\n */\nexport function useLoadScript(\n url: LoadScriptParams[0],\n options?: LoadScriptParams[1],\n): ScriptState {\n const [status, setStatus] = useState<ScriptState>('loading');\n\n useEffect(\n () => {\n loadScript(url, options)\n .then(() => setStatus('done'))\n .catch(() => setStatus('error'));\n },\n // Ignore options changes since it won't trigger a new load.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [url],\n );\n\n return status;\n}\n\ntype ScriptState = 'loading' | 'done' | 'error';\n"],"mappings":";;;;AAEA,IAAM,iBAAmD,EAAE;AAQ3D,SAAgB,WACd,KACA,SACkB;CAClB,MAAM,iBAAiB,eAAe;AAGtC,KAAI,eACF,QAAO;CAGT,MAAM,UAAU,IAAI,SAAkB,SAAS,WAAW;EACxD,MAAM,SAAS,SAAS,cAAc,SAAS;AAC/C,MAAI,SAAS,OACX,QAAO,OAAO;MAEd,QAAO,OAAO;AAEhB,SAAO,MAAM;AACb,SAAO,eAAqB;AAC1B,WAAQ,KAAK;;AAEf,SAAO,gBAAsB;AAC3B,UAAO,MAAM;;AAEf,MAAI,SAAS,OAAO,OAClB,UAAS,KAAK,YAAY,OAAO;MAEjC,UAAS,KAAK,YAAY,OAAO;EAGnC,MAAM,aAAa,SAAS;AAC5B,MAAI,WACF,QAAO,KAAK,WAAW,CAAC,SAAS,QAAQ;AACvC,UAAO,aAAa,KAAK,WAAW,KAAK;IACzC;GAEJ;AAEF,gBAAe,OAAO;AAEtB,QAAO;;;;;;AAUT,SAAgB,cACd,KACA,SACa;CACb,MAAM,CAAC,QAAQ,cAAA,GAAA,MAAA,UAAmC,UAAU;AAE5D,EAAA,GAAA,MAAA,iBACQ;AACJ,aAAW,KAAK,QAAQ,CACrB,WAAW,UAAU,OAAO,CAAC,CAC7B,YAAY,UAAU,QAAQ,CAAC;IAIpC,CAAC,IAAI,CACN;AAED,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.js","names":[],"sources":["../../../../package.json"],"sourcesContent":["{\n \"name\": \"@shopify/hydrogen-react\",\n \"version\": \"2026.4.
|
|
1
|
+
{"version":3,"file":"package.js","names":[],"sources":["../../../../package.json"],"sourcesContent":["{\n \"name\": \"@shopify/hydrogen-react\",\n \"version\": \"2026.4.4\",\n \"description\": \"React components, hooks, and utilities for creating custom Shopify storefronts\",\n \"homepage\": \"https://github.com/Shopify/hydrogen/tree/main/packages/hydrogen-react\",\n \"license\": \"MIT\",\n \"publishConfig\": {\n \"access\": \"public\",\n \"@shopify:registry\": \"https://registry.npmjs.org\"\n },\n \"files\": [\n \"dist\",\n \"storefront.schema.json\",\n \"customer-account.schema.json\"\n ],\n \"type\": \"commonjs\",\n \"exports\": {\n \".\": {\n \"node\": {\n \"require\": {\n \"types\": \"./dist/types/index.d.cts\",\n \"development\": \"./dist/node-dev/index.js\",\n \"default\": \"./dist/node-prod/index.js\"\n },\n \"import\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"development\": \"./dist/node-dev/index.mjs\",\n \"default\": \"./dist/node-prod/index.mjs\"\n },\n \"default\": \"./dist/node-prod/index.js\"\n },\n \"module\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"development\": \"./dist/browser-dev/index.mjs\",\n \"default\": \"./dist/browser-prod/index.mjs\"\n },\n \"import\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"development\": \"./dist/browser-dev/index.mjs\",\n \"default\": \"./dist/browser-prod/index.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/types/index.d.cts\",\n \"development\": \"./dist/node-dev/index.js\",\n \"default\": \"./dist/node-prod/index.js\"\n },\n \"default\": \"./dist/browser-prod/index.mjs\"\n },\n \"./storefront-api-types\": \"./dist/types/storefront-api-types.d.ts\",\n \"./storefront.schema.json\": \"./storefront.schema.json\",\n \"./customer-account.schema.json\": \"./customer-account.schema.json\",\n \"./customer-account-api-types\": \"./dist/types/customer-account-api-types.d.ts\",\n \"./package.json\": \"./package.json\",\n \"./*\": {\n \"node\": {\n \"require\": {\n \"types\": \"./dist/types/*.d.cts\",\n \"development\": \"./dist/node-dev/*.js\",\n \"default\": \"./dist/node-prod/*.js\"\n },\n \"import\": {\n \"types\": \"./dist/types/*.d.ts\",\n \"development\": \"./dist/node-dev/*.mjs\",\n \"default\": \"./dist/node-prod/*.mjs\"\n },\n \"default\": \"./dist/node-prod/*.js\"\n },\n \"module\": {\n \"types\": \"./dist/types/*.d.ts\",\n \"development\": \"./dist/browser-dev/*.mjs\",\n \"default\": \"./dist/browser-prod/*.mjs\"\n },\n \"import\": {\n \"types\": \"./dist/types/*.d.ts\",\n \"development\": \"./dist/browser-dev/*.mjs\",\n \"default\": \"./dist/browser-prod/*.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/types/*.d.cts\",\n \"development\": \"./dist/node-dev/*.js\",\n \"default\": \"./dist/node-prod/*.js\"\n },\n \"default\": \"./dist/browser-prod/*.mjs\"\n }\n },\n \"typesVersions\": {\n \"*\": {\n \"storefront-api-types\": [\n \"./dist/types/storefront-api-types.d.ts\"\n ]\n }\n },\n \"main\": \"./dist/node-prod/index.js\",\n \"module\": \"./dist/node-prod/index.mjs\",\n \"browser\": \"./dist/browser-prod/index.mjs\",\n \"types\": \"./dist/types/index.d.ts\",\n \"unpkg\": \"./dist/umd/hydrogen-react.prod.js\",\n \"jsdelivr\": \"./dist/umd/hydrogen-react.prod.js\",\n \"sideEffects\": false,\n \"scripts\": {\n \"build-docs\": \"sh ./docs/build-docs.sh && pnpm run format\",\n \"clean-dist\": \"rimraf ./dist\",\n \"dev\": \"run-s dev:demo\",\n \"dev:story\": \"ladle serve\",\n \"dev:demo\": \"run-p dev:demo:* copy-api-types\",\n \"dev:demo:browser-dev\": \"vite build --watch --emptyOutDir false --clearScreen false --mode devbuild\",\n \"dev:demo:ts\": \"tsc --watch --emitDeclarationOnly\",\n \"build\": \"npm-run-all --sequential clean-dist --parallel build:vite:* build:tsc:es --parallel build:tsc:cjs copy-api-types\",\n \"build:vite:browser-dev\": \"vite build --mode devbuild\",\n \"build:vite:browser-prod\": \"vite build\",\n \"build:vite:node-dev\": \"vite build --mode devbuild --ssr\",\n \"build:vite:node-prod\": \"vite build --ssr\",\n \"build:vite:umddev\": \"vite build --mode umdbuilddev\",\n \"build:vite:umdprod\": \"vite build --mode umdbuild\",\n \"build:tsc:cjs\": \"cpy ./dist/types/index.d.ts ./dist/types/ --rename=index.d.cts --flat\",\n \"build:tsc:es\": \"tsc --emitDeclarationOnly --project tsconfig.typeoutput.json\",\n \"copy-api-types\": \"cpy ./src/storefront-api-types.d.ts ./src/customer-account-api-types.d.ts ./dist/types/ --flat\",\n \"format\": \"prettier --write \\\"{src,docs}/**/*\\\" --ignore-unknown\",\n \"graphql-types\": \"graphql-codegen --config codegen.ts && pnpm run format\",\n \"test\": \"vitest run --coverage\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"run-p typecheck:*\",\n \"typecheck:code\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc --noEmit --project tsconfig.examples.json\",\n \"preview-docs\": \"pnpm --dir ../../docs/preview run dev\"\n },\n \"devDependencies\": {\n \"@faker-js/faker\": \"^9.4.0\",\n \"@graphql-codegen/add\": \"^5.0.3\",\n \"@graphql-codegen/cli\": \"^5.0.4\",\n \"@graphql-codegen/introspection\": \"^4.0.3\",\n \"@graphql-codegen/typescript\": \"^4.1.3\",\n \"@ladle/react\": \"^5.0.1\",\n \"@shopify/generate-docs\": \"catalog:\",\n \"@testing-library/jest-dom\": \"^6.6.3\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@testing-library/user-event\": \"^14.6.1\",\n \"@types/react\": \"catalog:\",\n \"@types/react-dom\": \"catalog:\",\n \"@vitejs/plugin-react\": \"^6.0.1\",\n \"@vitest/coverage-v8\": \"^3.2.4\",\n \"cpy-cli\": \"^5.0.0\",\n \"eslint\": \"9.19.0\",\n \"eslint-config-prettier\": \"10.0.1\",\n \"eslint-import-resolver-typescript\": \"3.7.0\",\n \"eslint-plugin-eslint-comments\": \"3.2.0\",\n \"eslint-plugin-import\": \"2.31.0\",\n \"eslint-plugin-jest\": \"28.11.0\",\n \"eslint-plugin-jsx-a11y\": \"6.10.2\",\n \"eslint-plugin-node\": \"11.1.0\",\n \"eslint-plugin-prettier\": \"4.2.1\",\n \"eslint-plugin-react\": \"7.37.4\",\n \"eslint-plugin-react-hooks\": \"5.1.0\",\n \"eslint-plugin-simple-import-sort\": \"12.1.1\",\n \"eslint-plugin-tsdoc\": \"0.2.14\",\n \"happy-dom\": \"^20.8.9\",\n \"npm-run-all\": \"^4.1.5\",\n \"react\": \"catalog:\",\n \"react-dom\": \"catalog:\",\n \"rimraf\": \"^6.0.1\",\n \"ts-expect\": \"^1.3.0\",\n \"typescript\": \"5.9.2\",\n \"vite\": \"^8.0.1\",\n \"vitest\": \"^3.2.4\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.3.1 || ~19.0.3 || ~19.1.4 || ^19.2.3\",\n \"react-dom\": \"^18.3.1 || ~19.0.3 || ~19.1.4 || ^19.2.3\",\n \"vite\": \"^5.1.0 || ^6.2.1 || ^7.0.0 || ^8.0.0\"\n },\n \"dependencies\": {\n \"@google/model-viewer\": \"^4.0.0\",\n \"@xstate/fsm\": \"2.0.0\",\n \"ast-v8-to-istanbul\": \"^0.3.11\",\n \"graphql\": \"^16.10.0\",\n \"type-fest\": \"^4.33.0\",\n \"worktop\": \"^0.7.3\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Shopify/hydrogen.git\",\n \"directory\": \"packages/hydrogen-react\"\n },\n \"bugs\": \"https://github.com/shopify/hydrogen/issues\"\n}\n"],"mappings":""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.mjs","names":[],"sources":["../../../../package.json"],"sourcesContent":["{\n \"name\": \"@shopify/hydrogen-react\",\n \"version\": \"2026.4.
|
|
1
|
+
{"version":3,"file":"package.mjs","names":[],"sources":["../../../../package.json"],"sourcesContent":["{\n \"name\": \"@shopify/hydrogen-react\",\n \"version\": \"2026.4.4\",\n \"description\": \"React components, hooks, and utilities for creating custom Shopify storefronts\",\n \"homepage\": \"https://github.com/Shopify/hydrogen/tree/main/packages/hydrogen-react\",\n \"license\": \"MIT\",\n \"publishConfig\": {\n \"access\": \"public\",\n \"@shopify:registry\": \"https://registry.npmjs.org\"\n },\n \"files\": [\n \"dist\",\n \"storefront.schema.json\",\n \"customer-account.schema.json\"\n ],\n \"type\": \"commonjs\",\n \"exports\": {\n \".\": {\n \"node\": {\n \"require\": {\n \"types\": \"./dist/types/index.d.cts\",\n \"development\": \"./dist/node-dev/index.js\",\n \"default\": \"./dist/node-prod/index.js\"\n },\n \"import\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"development\": \"./dist/node-dev/index.mjs\",\n \"default\": \"./dist/node-prod/index.mjs\"\n },\n \"default\": \"./dist/node-prod/index.js\"\n },\n \"module\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"development\": \"./dist/browser-dev/index.mjs\",\n \"default\": \"./dist/browser-prod/index.mjs\"\n },\n \"import\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"development\": \"./dist/browser-dev/index.mjs\",\n \"default\": \"./dist/browser-prod/index.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/types/index.d.cts\",\n \"development\": \"./dist/node-dev/index.js\",\n \"default\": \"./dist/node-prod/index.js\"\n },\n \"default\": \"./dist/browser-prod/index.mjs\"\n },\n \"./storefront-api-types\": \"./dist/types/storefront-api-types.d.ts\",\n \"./storefront.schema.json\": \"./storefront.schema.json\",\n \"./customer-account.schema.json\": \"./customer-account.schema.json\",\n \"./customer-account-api-types\": \"./dist/types/customer-account-api-types.d.ts\",\n \"./package.json\": \"./package.json\",\n \"./*\": {\n \"node\": {\n \"require\": {\n \"types\": \"./dist/types/*.d.cts\",\n \"development\": \"./dist/node-dev/*.js\",\n \"default\": \"./dist/node-prod/*.js\"\n },\n \"import\": {\n \"types\": \"./dist/types/*.d.ts\",\n \"development\": \"./dist/node-dev/*.mjs\",\n \"default\": \"./dist/node-prod/*.mjs\"\n },\n \"default\": \"./dist/node-prod/*.js\"\n },\n \"module\": {\n \"types\": \"./dist/types/*.d.ts\",\n \"development\": \"./dist/browser-dev/*.mjs\",\n \"default\": \"./dist/browser-prod/*.mjs\"\n },\n \"import\": {\n \"types\": \"./dist/types/*.d.ts\",\n \"development\": \"./dist/browser-dev/*.mjs\",\n \"default\": \"./dist/browser-prod/*.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/types/*.d.cts\",\n \"development\": \"./dist/node-dev/*.js\",\n \"default\": \"./dist/node-prod/*.js\"\n },\n \"default\": \"./dist/browser-prod/*.mjs\"\n }\n },\n \"typesVersions\": {\n \"*\": {\n \"storefront-api-types\": [\n \"./dist/types/storefront-api-types.d.ts\"\n ]\n }\n },\n \"main\": \"./dist/node-prod/index.js\",\n \"module\": \"./dist/node-prod/index.mjs\",\n \"browser\": \"./dist/browser-prod/index.mjs\",\n \"types\": \"./dist/types/index.d.ts\",\n \"unpkg\": \"./dist/umd/hydrogen-react.prod.js\",\n \"jsdelivr\": \"./dist/umd/hydrogen-react.prod.js\",\n \"sideEffects\": false,\n \"scripts\": {\n \"build-docs\": \"sh ./docs/build-docs.sh && pnpm run format\",\n \"clean-dist\": \"rimraf ./dist\",\n \"dev\": \"run-s dev:demo\",\n \"dev:story\": \"ladle serve\",\n \"dev:demo\": \"run-p dev:demo:* copy-api-types\",\n \"dev:demo:browser-dev\": \"vite build --watch --emptyOutDir false --clearScreen false --mode devbuild\",\n \"dev:demo:ts\": \"tsc --watch --emitDeclarationOnly\",\n \"build\": \"npm-run-all --sequential clean-dist --parallel build:vite:* build:tsc:es --parallel build:tsc:cjs copy-api-types\",\n \"build:vite:browser-dev\": \"vite build --mode devbuild\",\n \"build:vite:browser-prod\": \"vite build\",\n \"build:vite:node-dev\": \"vite build --mode devbuild --ssr\",\n \"build:vite:node-prod\": \"vite build --ssr\",\n \"build:vite:umddev\": \"vite build --mode umdbuilddev\",\n \"build:vite:umdprod\": \"vite build --mode umdbuild\",\n \"build:tsc:cjs\": \"cpy ./dist/types/index.d.ts ./dist/types/ --rename=index.d.cts --flat\",\n \"build:tsc:es\": \"tsc --emitDeclarationOnly --project tsconfig.typeoutput.json\",\n \"copy-api-types\": \"cpy ./src/storefront-api-types.d.ts ./src/customer-account-api-types.d.ts ./dist/types/ --flat\",\n \"format\": \"prettier --write \\\"{src,docs}/**/*\\\" --ignore-unknown\",\n \"graphql-types\": \"graphql-codegen --config codegen.ts && pnpm run format\",\n \"test\": \"vitest run --coverage\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"run-p typecheck:*\",\n \"typecheck:code\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc --noEmit --project tsconfig.examples.json\",\n \"preview-docs\": \"pnpm --dir ../../docs/preview run dev\"\n },\n \"devDependencies\": {\n \"@faker-js/faker\": \"^9.4.0\",\n \"@graphql-codegen/add\": \"^5.0.3\",\n \"@graphql-codegen/cli\": \"^5.0.4\",\n \"@graphql-codegen/introspection\": \"^4.0.3\",\n \"@graphql-codegen/typescript\": \"^4.1.3\",\n \"@ladle/react\": \"^5.0.1\",\n \"@shopify/generate-docs\": \"catalog:\",\n \"@testing-library/jest-dom\": \"^6.6.3\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@testing-library/user-event\": \"^14.6.1\",\n \"@types/react\": \"catalog:\",\n \"@types/react-dom\": \"catalog:\",\n \"@vitejs/plugin-react\": \"^6.0.1\",\n \"@vitest/coverage-v8\": \"^3.2.4\",\n \"cpy-cli\": \"^5.0.0\",\n \"eslint\": \"9.19.0\",\n \"eslint-config-prettier\": \"10.0.1\",\n \"eslint-import-resolver-typescript\": \"3.7.0\",\n \"eslint-plugin-eslint-comments\": \"3.2.0\",\n \"eslint-plugin-import\": \"2.31.0\",\n \"eslint-plugin-jest\": \"28.11.0\",\n \"eslint-plugin-jsx-a11y\": \"6.10.2\",\n \"eslint-plugin-node\": \"11.1.0\",\n \"eslint-plugin-prettier\": \"4.2.1\",\n \"eslint-plugin-react\": \"7.37.4\",\n \"eslint-plugin-react-hooks\": \"5.1.0\",\n \"eslint-plugin-simple-import-sort\": \"12.1.1\",\n \"eslint-plugin-tsdoc\": \"0.2.14\",\n \"happy-dom\": \"^20.8.9\",\n \"npm-run-all\": \"^4.1.5\",\n \"react\": \"catalog:\",\n \"react-dom\": \"catalog:\",\n \"rimraf\": \"^6.0.1\",\n \"ts-expect\": \"^1.3.0\",\n \"typescript\": \"5.9.2\",\n \"vite\": \"^8.0.1\",\n \"vitest\": \"^3.2.4\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.3.1 || ~19.0.3 || ~19.1.4 || ^19.2.3\",\n \"react-dom\": \"^18.3.1 || ~19.0.3 || ~19.1.4 || ^19.2.3\",\n \"vite\": \"^5.1.0 || ^6.2.1 || ^7.0.0 || ^8.0.0\"\n },\n \"dependencies\": {\n \"@google/model-viewer\": \"^4.0.0\",\n \"@xstate/fsm\": \"2.0.0\",\n \"ast-v8-to-istanbul\": \"^0.3.11\",\n \"graphql\": \"^16.10.0\",\n \"type-fest\": \"^4.33.0\",\n \"worktop\": \"^0.7.3\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Shopify/hydrogen.git\",\n \"directory\": \"packages/hydrogen-react\"\n },\n \"bugs\": \"https://github.com/shopify/hydrogen/issues\"\n}\n"],"mappings":""}
|
|
@@ -3,68 +3,27 @@
|
|
|
3
3
|
var SHOPIFY_VISIT_TOKEN_HEADER = "X-Shopify-VisitToken";
|
|
4
4
|
/** Storefront API header for UniqueToken */
|
|
5
5
|
var SHOPIFY_UNIQUE_TOKEN_HEADER = "X-Shopify-UniqueToken";
|
|
6
|
-
var cachedTrackingValues = { current: null };
|
|
7
6
|
/**
|
|
8
|
-
* Retrieves user session tracking values for analytics and marketing from the
|
|
7
|
+
* Retrieves user session tracking values for analytics and marketing from the
|
|
8
|
+
* browser environment. Customer Privacy API token readers are authoritative
|
|
9
|
+
* when available, including when consent denies tracking. Deprecated
|
|
10
|
+
* `_shopify_y`/`_shopify_s` cookies are read only without an API token reader.
|
|
11
|
+
* Consent comes from CTA's cache or the legacy `_tracking_consent` cookie.
|
|
9
12
|
* @publicDocs
|
|
10
13
|
*/
|
|
11
14
|
function getTrackingValues() {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
if (matchedHost === currentHost || sfapiPath && matchedHost?.endsWith(`.${currentHost}`)) {
|
|
25
|
-
const values = extractFromPerformanceEntry(entry);
|
|
26
|
-
if (values) {
|
|
27
|
-
matchedValues = values;
|
|
28
|
-
break;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
if (matchedValues) trackingValues = matchedValues;
|
|
33
|
-
if (trackingValues) cachedTrackingValues.current = trackingValues;
|
|
34
|
-
else if (cachedTrackingValues.current) trackingValues = cachedTrackingValues.current;
|
|
35
|
-
if (!trackingValues) {
|
|
36
|
-
const navigationEntries = performance.getEntriesByType("navigation")[0];
|
|
37
|
-
trackingValues = extractFromPerformanceEntry(navigationEntries, false);
|
|
38
|
-
}
|
|
39
|
-
} catch {}
|
|
40
|
-
if (!trackingValues) {
|
|
41
|
-
const cookie = typeof arguments[0] === "string" ? arguments[0] : typeof document !== "undefined" ? document.cookie : "";
|
|
42
|
-
trackingValues = {
|
|
43
|
-
uniqueToken: cookie.match(/\b_shopify_y=([^;]+)/)?.[1] || "",
|
|
44
|
-
visitToken: cookie.match(/\b_shopify_s=([^;]+)/)?.[1] || "",
|
|
45
|
-
consent: cookie.match(/\b_tracking_consent=([^;]+)/)?.[1] || ""
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
return trackingValues;
|
|
49
|
-
}
|
|
50
|
-
function extractFromPerformanceEntry(entry, isConsentRequired = true) {
|
|
51
|
-
let uniqueToken = "";
|
|
52
|
-
let visitToken = "";
|
|
53
|
-
let consent = "";
|
|
54
|
-
const serverTiming = entry.serverTiming;
|
|
55
|
-
if (serverTiming && serverTiming.length >= 3) for (let i = serverTiming.length - 1; i >= 0; i--) {
|
|
56
|
-
const { name, description } = serverTiming[i];
|
|
57
|
-
if (!name || !description) continue;
|
|
58
|
-
if (name === "_y") uniqueToken = description;
|
|
59
|
-
else if (name === "_s") visitToken = description;
|
|
60
|
-
else if (name === "_cmp") consent = description;
|
|
61
|
-
if (uniqueToken && visitToken && consent) break;
|
|
62
|
-
}
|
|
63
|
-
return uniqueToken && visitToken && (isConsentRequired ? consent : true) ? {
|
|
64
|
-
uniqueToken,
|
|
65
|
-
visitToken,
|
|
66
|
-
consent
|
|
67
|
-
} : void 0;
|
|
15
|
+
const cookie = typeof arguments[0] === "string" ? arguments[0] : typeof document !== "undefined" ? document.cookie : "";
|
|
16
|
+
const customerPrivacy = typeof window === "undefined" ? void 0 : window.Shopify?.customerPrivacy;
|
|
17
|
+
const internal = customerPrivacy?.__internal;
|
|
18
|
+
const tokenOptions = {
|
|
19
|
+
generateFallback: customerPrivacy?.config?.asyncConsent === true,
|
|
20
|
+
tag: "hydrogen:classic"
|
|
21
|
+
};
|
|
22
|
+
return {
|
|
23
|
+
uniqueToken: internal?.uniqueToken ? internal.uniqueToken(tokenOptions) ?? "" : cookie.match(/\b_shopify_y=([^;]+)/)?.[1] ?? "",
|
|
24
|
+
visitToken: internal?.visitToken ? internal.visitToken(tokenOptions) ?? "" : cookie.match(/\b_shopify_s=([^;]+)/)?.[1] ?? "",
|
|
25
|
+
consent: customerPrivacy?.cachedConsent ?? cookie.match(/\b_tracking_consent=([^;]+)/)?.[1] ?? ""
|
|
26
|
+
};
|
|
68
27
|
}
|
|
69
28
|
//#endregion
|
|
70
29
|
exports.SHOPIFY_UNIQUE_TOKEN_HEADER = SHOPIFY_UNIQUE_TOKEN_HEADER;
|