@shopify/hydrogen-react 2024.4.2 → 2024.4.3

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.
Files changed (85) hide show
  1. package/README.md +2 -2
  2. package/dist/browser-dev/RichText.components.mjs +57 -0
  3. package/dist/browser-dev/RichText.components.mjs.map +1 -0
  4. package/dist/browser-dev/RichText.mjs +160 -0
  5. package/dist/browser-dev/RichText.mjs.map +1 -0
  6. package/dist/browser-dev/index.mjs +2 -0
  7. package/dist/browser-dev/index.mjs.map +1 -1
  8. package/dist/browser-dev/parse-metafield.mjs +1 -0
  9. package/dist/browser-dev/parse-metafield.mjs.map +1 -1
  10. package/dist/browser-dev/storefront-client.mjs +1 -1
  11. package/dist/browser-dev/storefront-client.mjs.map +1 -1
  12. package/dist/browser-dev/useShopifyCookies.mjs +8 -4
  13. package/dist/browser-dev/useShopifyCookies.mjs.map +1 -1
  14. package/dist/browser-prod/RichText.components.mjs +57 -0
  15. package/dist/browser-prod/RichText.components.mjs.map +1 -0
  16. package/dist/browser-prod/RichText.mjs +160 -0
  17. package/dist/browser-prod/RichText.mjs.map +1 -0
  18. package/dist/browser-prod/index.mjs +2 -0
  19. package/dist/browser-prod/index.mjs.map +1 -1
  20. package/dist/browser-prod/parse-metafield.mjs +1 -0
  21. package/dist/browser-prod/parse-metafield.mjs.map +1 -1
  22. package/dist/browser-prod/storefront-client.mjs +1 -1
  23. package/dist/browser-prod/storefront-client.mjs.map +1 -1
  24. package/dist/browser-prod/useShopifyCookies.mjs +8 -4
  25. package/dist/browser-prod/useShopifyCookies.mjs.map +1 -1
  26. package/dist/node-dev/RichText.components.js +57 -0
  27. package/dist/node-dev/RichText.components.js.map +1 -0
  28. package/dist/node-dev/RichText.components.mjs +57 -0
  29. package/dist/node-dev/RichText.components.mjs.map +1 -0
  30. package/dist/node-dev/RichText.js +160 -0
  31. package/dist/node-dev/RichText.js.map +1 -0
  32. package/dist/node-dev/RichText.mjs +160 -0
  33. package/dist/node-dev/RichText.mjs.map +1 -0
  34. package/dist/node-dev/index.js +2 -0
  35. package/dist/node-dev/index.js.map +1 -1
  36. package/dist/node-dev/index.mjs +2 -0
  37. package/dist/node-dev/index.mjs.map +1 -1
  38. package/dist/node-dev/parse-metafield.js +1 -0
  39. package/dist/node-dev/parse-metafield.js.map +1 -1
  40. package/dist/node-dev/parse-metafield.mjs +1 -0
  41. package/dist/node-dev/parse-metafield.mjs.map +1 -1
  42. package/dist/node-dev/storefront-client.js +1 -1
  43. package/dist/node-dev/storefront-client.js.map +1 -1
  44. package/dist/node-dev/storefront-client.mjs +1 -1
  45. package/dist/node-dev/storefront-client.mjs.map +1 -1
  46. package/dist/node-dev/useShopifyCookies.js +8 -4
  47. package/dist/node-dev/useShopifyCookies.js.map +1 -1
  48. package/dist/node-dev/useShopifyCookies.mjs +8 -4
  49. package/dist/node-dev/useShopifyCookies.mjs.map +1 -1
  50. package/dist/node-prod/RichText.components.js +57 -0
  51. package/dist/node-prod/RichText.components.js.map +1 -0
  52. package/dist/node-prod/RichText.components.mjs +57 -0
  53. package/dist/node-prod/RichText.components.mjs.map +1 -0
  54. package/dist/node-prod/RichText.js +160 -0
  55. package/dist/node-prod/RichText.js.map +1 -0
  56. package/dist/node-prod/RichText.mjs +160 -0
  57. package/dist/node-prod/RichText.mjs.map +1 -0
  58. package/dist/node-prod/index.js +2 -0
  59. package/dist/node-prod/index.js.map +1 -1
  60. package/dist/node-prod/index.mjs +2 -0
  61. package/dist/node-prod/index.mjs.map +1 -1
  62. package/dist/node-prod/parse-metafield.js +1 -0
  63. package/dist/node-prod/parse-metafield.js.map +1 -1
  64. package/dist/node-prod/parse-metafield.mjs +1 -0
  65. package/dist/node-prod/parse-metafield.mjs.map +1 -1
  66. package/dist/node-prod/storefront-client.js +1 -1
  67. package/dist/node-prod/storefront-client.js.map +1 -1
  68. package/dist/node-prod/storefront-client.mjs +1 -1
  69. package/dist/node-prod/storefront-client.mjs.map +1 -1
  70. package/dist/node-prod/useShopifyCookies.js +8 -4
  71. package/dist/node-prod/useShopifyCookies.js.map +1 -1
  72. package/dist/node-prod/useShopifyCookies.mjs +8 -4
  73. package/dist/node-prod/useShopifyCookies.mjs.map +1 -1
  74. package/dist/types/RichText.components.d.ts +76 -0
  75. package/dist/types/RichText.d.ts +14 -0
  76. package/dist/types/RichText.test.helpers.d.ts +9 -0
  77. package/dist/types/RichText.types.d.ts +36 -0
  78. package/dist/types/index.d.cts +1 -0
  79. package/dist/types/index.d.ts +1 -0
  80. package/dist/types/parse-metafield.d.ts +8 -1
  81. package/dist/umd/hydrogen-react.dev.js +215 -5
  82. package/dist/umd/hydrogen-react.dev.js.map +1 -1
  83. package/dist/umd/hydrogen-react.prod.js +18 -17
  84. package/dist/umd/hydrogen-react.prod.js.map +1 -1
  85. package/package.json +2 -3
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  Hydrogen React is an unopinionated and performant library of Shopify-specific commerce components, hooks, and utilities. Bring the best parts of Hydrogen to more React frameworks, like Next.js and Gatsby, and accelerate headless development using Shopify’s pre-built React components including Cart, Shop Pay, and Shopify Analytics.
6
6
 
7
- 📚 [Overview](https://shopify.dev/custom-storefronts/hydrogen-react) | 🛠️ [Docs](https://shopify.dev/docs/api/hydrogen-react) | 🛍️ [Custom Storefronts at Shopify](https://shopify.dev/custom-storefronts) | 🗣 [Discord](https://discord.gg/Hefq6w5c5d) | 📝 [Changelog](https://github.com/Shopify/hydrogen/blob/main/packages/hydrogen-react/CHANGELOG.md)
7
+ 📚 [Overview](https://shopify.dev/custom-storefronts/hydrogen-react) | 🛠️ [Docs](https://shopify.dev/docs/api/hydrogen-react) | 🛍️ [Custom Storefronts at Shopify](https://shopify.dev/custom-storefronts) | 🗣 [Discussions](https://github.com/Shopify/hydrogen/discussions) | 📝 [Changelog](https://github.com/Shopify/hydrogen/blob/main/packages/hydrogen-react/CHANGELOG.md)
8
8
 
9
9
  **IMPORTANT:** Refer to how this package is [versioned](../../README.md#versioning).
10
10
 
@@ -78,6 +78,6 @@ For example, in VSCode do the following:
78
78
 
79
79
  ## Contributing
80
80
 
81
- We love contributions! Contributing works best when you first confirm that something needs to be changed or fixed; please open an issue, start a discussion, or talk to us in Discord!
81
+ We love contributions! Contributing works best when you first confirm that something needs to be changed or fixed; please open an issue or start a discussion!
82
82
 
83
83
  PRs are welcome! Be sure to read the [CONTRIBUTING.md](../../CONTRIBUTING.md) for an overview and guidelines to help your PR succeed.
@@ -0,0 +1,57 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { createElement } from "react";
3
+ const RichTextComponents = {
4
+ root: Root,
5
+ heading: Heading,
6
+ paragraph: Paragraph,
7
+ text: Text,
8
+ link: RichTextLink,
9
+ list: List,
10
+ "list-item": ListItem
11
+ };
12
+ function Root({
13
+ node
14
+ }) {
15
+ return /* @__PURE__ */ jsx("div", { children: node.children });
16
+ }
17
+ function Heading({
18
+ node
19
+ }) {
20
+ return createElement(`h${node.level ?? "1"}`, null, node.children);
21
+ }
22
+ function Paragraph({
23
+ node
24
+ }) {
25
+ return /* @__PURE__ */ jsx("p", { children: node.children });
26
+ }
27
+ function Text({
28
+ node
29
+ }) {
30
+ if (node.bold && node.italic)
31
+ return /* @__PURE__ */ jsx("em", { children: /* @__PURE__ */ jsx("strong", { children: node.value }) });
32
+ if (node.bold)
33
+ return /* @__PURE__ */ jsx("strong", { children: node.value });
34
+ if (node.italic)
35
+ return /* @__PURE__ */ jsx("em", { children: node.value });
36
+ return node.value;
37
+ }
38
+ function RichTextLink({
39
+ node
40
+ }) {
41
+ return /* @__PURE__ */ jsx("a", { href: node.url, title: node.title, target: node.target, children: node.children });
42
+ }
43
+ function List({
44
+ node
45
+ }) {
46
+ const List2 = node.listType === "unordered" ? "ul" : "ol";
47
+ return /* @__PURE__ */ jsx(List2, { children: node.children });
48
+ }
49
+ function ListItem({
50
+ node
51
+ }) {
52
+ return /* @__PURE__ */ jsx("li", { children: node.children });
53
+ }
54
+ export {
55
+ RichTextComponents
56
+ };
57
+ //# sourceMappingURL=RichText.components.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RichText.components.mjs","sources":["../../src/RichText.components.tsx"],"sourcesContent":["import {createElement, type ReactNode} from 'react';\n\nexport type CustomComponents = {\n /** The root node of the rich text. Defaults to `<div>` */\n root?: typeof Root;\n /** Customize the headings. Each heading has a `level` property from 1-6. Defaults to `<h1>` to `<h6>` */\n heading?: typeof Heading;\n /** Customize paragraphs. Defaults to `<p>` */\n paragraph?: typeof Paragraph;\n /** Customize how text nodes. They can either be bold or italic. Defaults to `<em>`, `<strong>` or text. */\n text?: typeof Text;\n /** Customize links. Defaults to a React Router `<Link>` component in Hydrogen and a `<a>` in Hydrogen React. */\n link?: typeof RichTextLink;\n /** Customize lists. They can be either ordered or unordered. Defaults to `<ol>` or `<ul>` */\n list?: typeof List;\n /** Customize list items. Defaults to `<li>`. */\n listItem?: typeof ListItem;\n};\n\nexport const RichTextComponents = {\n root: Root,\n heading: Heading,\n paragraph: Paragraph,\n text: Text,\n link: RichTextLink,\n list: List,\n 'list-item': ListItem,\n};\n\nfunction Root({\n node,\n}: {\n node: {\n type: 'root';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <div>{node.children}</div>;\n}\n\nfunction Heading({\n node,\n}: {\n node: {\n type: 'heading';\n level: number;\n children?: ReactNode[];\n };\n}): ReactNode {\n return createElement(`h${node.level ?? '1'}`, null, node.children);\n}\n\nfunction Paragraph({\n node,\n}: {\n node: {\n type: 'paragraph';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <p>{node.children}</p>;\n}\n\nfunction Text({\n node,\n}: {\n node: {\n type: 'text';\n italic?: boolean;\n bold?: boolean;\n value?: string;\n };\n}): ReactNode {\n if (node.bold && node.italic)\n return (\n <em>\n <strong>{node.value}</strong>\n </em>\n );\n\n if (node.bold) return <strong>{node.value}</strong>;\n if (node.italic) return <em>{node.value}</em>;\n\n return node.value;\n}\n\nfunction RichTextLink({\n node,\n}: {\n node: {\n type: 'link';\n url: string;\n title?: string;\n target?: string;\n children?: ReactNode[];\n };\n}): ReactNode {\n return (\n <a href={node.url} title={node.title} target={node.target}>\n {node.children}\n </a>\n );\n}\n\nfunction List({\n node,\n}: {\n node: {\n type: 'list';\n listType: 'unordered' | 'ordered';\n children?: ReactNode[];\n };\n}): ReactNode {\n const List = node.listType === 'unordered' ? 'ul' : 'ol';\n return <List>{node.children}</List>;\n}\n\nfunction ListItem({\n node,\n}: {\n node: {\n type: 'list-item';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <li>{node.children}</li>;\n}\n"],"names":["List"],"mappings":";;AAmBO,MAAM,qBAAqB;AAAA,EAChC,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,aAAa;AACf;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAKc;AACL,SAAA,oBAAC,OAAK,EAAA,UAAA,KAAK,SAAS,CAAA;AAC7B;AAEA,SAAS,QAAQ;AAAA,EACf;AACF,GAMc;AACL,SAAA,cAAc,IAAI,KAAK,SAAS,GAAG,IAAI,MAAM,KAAK,QAAQ;AACnE;AAEA,SAAS,UAAU;AAAA,EACjB;AACF,GAKc;AACL,SAAA,oBAAC,KAAG,EAAA,UAAA,KAAK,SAAS,CAAA;AAC3B;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAOc;AACR,MAAA,KAAK,QAAQ,KAAK;AACpB,+BACG,MACC,EAAA,UAAA,oBAAC,UAAQ,EAAA,UAAA,KAAK,MAAM,CAAA,EACtB,CAAA;AAGJ,MAAI,KAAK;AAAa,WAAA,oBAAC,UAAQ,EAAA,UAAA,KAAK,MAAM,CAAA;AAC1C,MAAI,KAAK;AAAe,WAAA,oBAAC,MAAI,EAAA,UAAA,KAAK,MAAM,CAAA;AAExC,SAAO,KAAK;AACd;AAEA,SAAS,aAAa;AAAA,EACpB;AACF,GAQc;AACZ,SACG,oBAAA,KAAA,EAAE,MAAM,KAAK,KAAK,OAAO,KAAK,OAAO,QAAQ,KAAK,QAChD,UAAA,KAAK,SACR,CAAA;AAEJ;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAMc;AACZ,QAAMA,QAAO,KAAK,aAAa,cAAc,OAAO;AACpD,SAAQA,oBAAAA,OAAA,EAAM,UAAA,KAAK,SAAS,CAAA;AAC9B;AAEA,SAAS,SAAS;AAAA,EAChB;AACF,GAKc;AACL,SAAA,oBAAC,MAAI,EAAA,UAAA,KAAK,SAAS,CAAA;AAC5B;"}
@@ -0,0 +1,160 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { useMemo, createElement, Fragment } from "react";
3
+ import { RichTextComponents } from "./RichText.components.mjs";
4
+ function RichText({
5
+ as,
6
+ data,
7
+ plain,
8
+ components,
9
+ ...passthroughProps
10
+ }) {
11
+ try {
12
+ const Wrapper = as ?? "div";
13
+ const parsedData = useMemo(
14
+ () => JSON.parse(data),
15
+ [data]
16
+ );
17
+ return /* @__PURE__ */ jsx(Wrapper, { ...passthroughProps, children: plain ? richTextToString(parsedData) : serializeRichTextASTNode(components, parsedData) });
18
+ } catch (e) {
19
+ throw new Error(
20
+ "[h2:error:RichText] Parsing error. Make sure to pass a JSON string of rich text metafield",
21
+ {
22
+ cause: e
23
+ }
24
+ );
25
+ }
26
+ }
27
+ function serializeRichTextASTNode(components = {}, node, index = 0) {
28
+ let children;
29
+ if ("children" in node) {
30
+ children = node.children.map(
31
+ (child, childIndex) => serializeRichTextASTNode(components, child, childIndex)
32
+ );
33
+ }
34
+ const Component = components[node.type === "list-item" ? "listItem" : node.type] ?? RichTextComponents[node.type];
35
+ switch (node.type) {
36
+ case "root":
37
+ return createElement(
38
+ Component,
39
+ {
40
+ key: index,
41
+ node: {
42
+ type: "root",
43
+ children
44
+ }
45
+ }
46
+ );
47
+ case "heading":
48
+ return createElement(
49
+ Component,
50
+ {
51
+ key: index,
52
+ node: {
53
+ type: "heading",
54
+ level: node.level,
55
+ children
56
+ }
57
+ }
58
+ );
59
+ case "paragraph":
60
+ return createElement(
61
+ Component,
62
+ {
63
+ key: index,
64
+ node: {
65
+ type: "paragraph",
66
+ children
67
+ }
68
+ }
69
+ );
70
+ case "text": {
71
+ const elements = (node.value ?? "").split("\n").flatMap((value, subindex) => {
72
+ const key = `${index}-${value}-${subindex}`;
73
+ const textElement = createElement(
74
+ Component,
75
+ {
76
+ key,
77
+ node: {
78
+ type: "text",
79
+ italic: node.italic,
80
+ bold: node.bold,
81
+ value
82
+ }
83
+ }
84
+ );
85
+ return subindex === 0 ? textElement : [createElement("br", { key: `${key}-br` }), textElement];
86
+ });
87
+ return elements.length > 1 ? createElement(Fragment, { key: index }, elements) : elements[0];
88
+ }
89
+ case "link":
90
+ return createElement(
91
+ Component,
92
+ {
93
+ key: index,
94
+ node: {
95
+ type: "link",
96
+ url: node.url,
97
+ title: node.title,
98
+ target: node.target,
99
+ children
100
+ }
101
+ }
102
+ );
103
+ case "list":
104
+ return createElement(
105
+ Component,
106
+ {
107
+ key: index,
108
+ node: {
109
+ type: "list",
110
+ listType: node.listType,
111
+ children
112
+ }
113
+ }
114
+ );
115
+ case "list-item":
116
+ return createElement(
117
+ Component,
118
+ {
119
+ key: index,
120
+ node: {
121
+ type: "list-item",
122
+ children
123
+ }
124
+ }
125
+ );
126
+ }
127
+ }
128
+ function richTextToString(node, result = []) {
129
+ switch (node.type) {
130
+ case "root":
131
+ node.children.forEach((child) => richTextToString(child, result));
132
+ break;
133
+ case "heading":
134
+ case "paragraph":
135
+ node.children.forEach((child) => richTextToString(child, result));
136
+ result.push(" ");
137
+ break;
138
+ case "text":
139
+ result.push(node.value || "");
140
+ break;
141
+ case "link":
142
+ node.children.forEach((child) => richTextToString(child, result));
143
+ break;
144
+ case "list":
145
+ node.children.forEach((item) => {
146
+ if (item.children) {
147
+ item.children.forEach((child) => richTextToString(child, result));
148
+ }
149
+ result.push(" ");
150
+ });
151
+ break;
152
+ default:
153
+ throw new Error(`Unknown node encountered ${node.type}`);
154
+ }
155
+ return result.join("").trim();
156
+ }
157
+ export {
158
+ RichText
159
+ };
160
+ //# sourceMappingURL=RichText.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RichText.mjs","sources":["../../src/RichText.tsx"],"sourcesContent":["import {createElement, Fragment, type ReactNode, useMemo} from 'react';\nimport type {RichTextASTNode} from './RichText.types.js';\nimport {\n type CustomComponents,\n RichTextComponents,\n} from './RichText.components.js';\n\nexport interface RichTextPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** The JSON string that correspond to the Storefront API's [RichText format](https://shopify.dev/docs/apps/custom-data/metafields/types#rich-text-formatting). */\n data: string;\n /** Customize how rich text components are rendered */\n components?: CustomComponents;\n /** Remove rich text formatting and render plain text */\n plain?: boolean;\n}\n\nexport function RichText<ComponentGeneric extends React.ElementType = 'div'>({\n as,\n data,\n plain,\n components,\n ...passthroughProps\n}: RichTextProps<ComponentGeneric>): JSX.Element {\n try {\n const Wrapper = as ?? 'div';\n const parsedData = useMemo(\n () => JSON.parse(data) as RichTextASTNode,\n [data],\n );\n\n return (\n <Wrapper {...passthroughProps}>\n {plain\n ? richTextToString(parsedData)\n : serializeRichTextASTNode(components, parsedData)}\n </Wrapper>\n );\n } catch (e) {\n throw new Error(\n '[h2:error:RichText] Parsing error. Make sure to pass a JSON string of rich text metafield',\n {\n cause: e,\n },\n );\n }\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type RichTextProps<ComponentGeneric extends React.ElementType> =\n RichTextPropsBase<ComponentGeneric> &\n Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof RichTextPropsBase<ComponentGeneric>\n >;\n\nfunction serializeRichTextASTNode(\n components: CustomComponents = {},\n node: RichTextASTNode,\n index = 0,\n): ReactNode {\n let children;\n if ('children' in node) {\n children = node.children.map((child, childIndex) =>\n serializeRichTextASTNode(components, child, childIndex),\n );\n }\n\n const Component =\n components[node.type === 'list-item' ? 'listItem' : node.type] ??\n RichTextComponents[node.type];\n\n switch (node.type) {\n case 'root':\n return createElement(\n Component as Exclude<CustomComponents['root'], undefined>,\n {\n key: index,\n node: {\n type: 'root',\n children,\n },\n },\n );\n case 'heading':\n return createElement(\n Component as Exclude<CustomComponents['heading'], undefined>,\n {\n key: index,\n node: {\n type: 'heading',\n level: node.level,\n children,\n },\n },\n );\n case 'paragraph':\n return createElement(\n Component as Exclude<CustomComponents['paragraph'], undefined>,\n {\n key: index,\n node: {\n type: 'paragraph',\n children,\n },\n },\n );\n case 'text': {\n const elements = (node.value ?? '')\n .split('\\n')\n .flatMap((value, subindex) => {\n const key = `${index}-${value}-${subindex}`;\n const textElement = createElement(\n Component as Exclude<CustomComponents['text'], undefined>,\n {\n key,\n node: {\n type: 'text',\n italic: node.italic,\n bold: node.bold,\n value,\n },\n },\n );\n\n // Add a `<br>` before each substring except the first one\n return subindex === 0\n ? textElement\n : [createElement('br', {key: `${key}-br`}), textElement];\n });\n\n return elements.length > 1\n ? createElement(Fragment, {key: index}, elements)\n : elements[0];\n }\n case 'link':\n return createElement(\n Component as Exclude<CustomComponents['link'], undefined>,\n {\n key: index,\n node: {\n type: 'link',\n url: node.url,\n title: node.title,\n target: node.target,\n children,\n },\n },\n );\n case 'list':\n return createElement(\n Component as Exclude<CustomComponents['list'], undefined>,\n {\n key: index,\n node: {\n type: 'list',\n listType: node.listType,\n children,\n },\n },\n );\n case 'list-item':\n return createElement(\n Component as Exclude<CustomComponents['listItem'], undefined>,\n {\n key: index,\n node: {\n type: 'list-item',\n children,\n },\n },\n );\n }\n}\n\nfunction richTextToString(\n node: RichTextASTNode,\n result: string[] = [],\n): string {\n switch (node.type) {\n case 'root':\n node.children.forEach((child) => richTextToString(child, result));\n break;\n case 'heading':\n case 'paragraph':\n node.children.forEach((child) => richTextToString(child, result));\n result.push(' ');\n break;\n case 'text':\n result.push(node.value || '');\n break;\n case 'link':\n node.children.forEach((child) => richTextToString(child, result));\n break;\n case 'list':\n node.children.forEach((item) => {\n if (item.children) {\n item.children.forEach((child) => richTextToString(child, result));\n }\n result.push(' ');\n });\n break;\n default:\n throw new Error(`Unknown node encountered ${node.type}`);\n }\n\n return result.join('').trim();\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport type RichTextPropsForDocs<AsType extends React.ElementType = 'div'> =\n RichTextPropsBase<AsType>;\n"],"names":[],"mappings":";;;AAkBO,SAAS,SAA6D;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAiD;AAC3C,MAAA;AACF,UAAM,UAAU,MAAM;AACtB,UAAM,aAAa;AAAA,MACjB,MAAM,KAAK,MAAM,IAAI;AAAA,MACrB,CAAC,IAAI;AAAA,IAAA;AAIL,WAAA,oBAAC,SAAS,EAAA,GAAG,kBACV,UAAA,QACG,iBAAiB,UAAU,IAC3B,yBAAyB,YAAY,UAAU,EACrD,CAAA;AAAA,WAEK,GAAG;AACV,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,QACE,OAAO;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AACF;AAUA,SAAS,yBACP,aAA+B,CAAA,GAC/B,MACA,QAAQ,GACG;AACP,MAAA;AACJ,MAAI,cAAc,MAAM;AACtB,eAAW,KAAK,SAAS;AAAA,MAAI,CAAC,OAAO,eACnC,yBAAyB,YAAY,OAAO,UAAU;AAAA,IAAA;AAAA,EAE1D;AAEM,QAAA,YACJ,WAAW,KAAK,SAAS,cAAc,aAAa,KAAK,IAAI,KAC7D,mBAAmB,KAAK,IAAI;AAE9B,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,IAEJ,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN,OAAO,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,IAEJ,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,IAEJ,KAAK,QAAQ;AACL,YAAA,YAAY,KAAK,SAAS,IAC7B,MAAM,IAAI,EACV,QAAQ,CAAC,OAAO,aAAa;AAC5B,cAAM,MAAM,GAAG,KAAK,IAAI,KAAK,IAAI,QAAQ;AACzC,cAAM,cAAc;AAAA,UAClB;AAAA,UACA;AAAA,YACE;AAAA,YACA,MAAM;AAAA,cACJ,MAAM;AAAA,cACN,QAAQ,KAAK;AAAA,cACb,MAAM,KAAK;AAAA,cACX;AAAA,YACF;AAAA,UACF;AAAA,QAAA;AAIF,eAAO,aAAa,IAChB,cACA,CAAC,cAAc,MAAM,EAAC,KAAK,GAAG,GAAG,MAAK,CAAC,GAAG,WAAW;AAAA,MAAA,CAC1D;AAEH,aAAO,SAAS,SAAS,IACrB,cAAc,UAAU,EAAC,KAAK,MAAQ,GAAA,QAAQ,IAC9C,SAAS,CAAC;AAAA,IAChB;AAAA,IACA,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN,KAAK,KAAK;AAAA,YACV,OAAO,KAAK;AAAA,YACZ,QAAQ,KAAK;AAAA,YACb;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,IAEJ,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN,UAAU,KAAK;AAAA,YACf;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,IAEJ,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,EAEN;AACF;AAEA,SAAS,iBACP,MACA,SAAmB,IACX;AACR,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,WAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAChE;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,WAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAChE,aAAO,KAAK,GAAG;AACf;AAAA,IACF,KAAK;AACI,aAAA,KAAK,KAAK,SAAS,EAAE;AAC5B;AAAA,IACF,KAAK;AACH,WAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAChE;AAAA,IACF,KAAK;AACE,WAAA,SAAS,QAAQ,CAAC,SAAS;AAC9B,YAAI,KAAK,UAAU;AACjB,eAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAAA,QAClE;AACA,eAAO,KAAK,GAAG;AAAA,MAAA,CAChB;AACD;AAAA,IACF;AACE,YAAM,IAAI,MAAM,4BAA4B,KAAK,IAAI,EAAE;AAAA,EAC3D;AAEA,SAAO,OAAO,KAAK,EAAE,EAAE,KAAK;AAC9B;"}
@@ -22,6 +22,7 @@ import { Money } from "./Money.mjs";
22
22
  import { parseMetafield } from "./parse-metafield.mjs";
23
23
  import { ProductPrice } from "./ProductPrice.mjs";
24
24
  import { ProductProvider, useProduct } from "./ProductProvider.mjs";
25
+ import { RichText } from "./RichText.mjs";
25
26
  import { ShopifyProvider, useShop } from "./ShopifyProvider.mjs";
26
27
  import { ShopPayButton } from "./ShopPayButton.mjs";
27
28
  import { createStorefrontClient } from "./storefront-client.mjs";
@@ -47,6 +48,7 @@ export {
47
48
  Money,
48
49
  ProductPrice,
49
50
  ProductProvider,
51
+ RichText,
50
52
  SHOPIFY_S,
51
53
  SHOPIFY_STOREFRONT_ID_HEADER,
52
54
  SHOPIFY_STOREFRONT_S_HEADER,
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -35,6 +35,7 @@ function parseMetafield(metafield) {
35
35
  case "rating":
36
36
  case "volume":
37
37
  case "weight":
38
+ case "rich_text_field":
38
39
  case "list.color":
39
40
  case "list.dimension":
40
41
  case "list.number_integer":
@@ -1 +1 @@
1
- {"version":3,"file":"parse-metafield.mjs","sources":["../../src/parse-metafield.ts"],"sourcesContent":["import type {\n Collection,\n GenericFile,\n Metafield as MetafieldBaseType,\n MoneyV2,\n Page,\n Product,\n ProductVariant,\n} from './storefront-api-types.js';\nimport type {PartialDeep, Simplify} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\n/**\n * A function that uses `metafield.type` to parse the Metafield's `value` or `reference` or `references` (depending on the `metafield.type`) and places the result in `metafield.parsedValue`\n *\n * TypeScript developers can use the type `ParsedMetafields` from this package to get the returned object's type correct. For example:\n *\n * ```\n * parseMetafield<ParsedMetafields['boolean']>({type: 'boolean', value: 'false'}\n * ```\n */\nexport function parseMetafield<ReturnGeneric>(\n metafield: PartialDeep<MetafieldBaseType, {recurseIntoArrays: true}>,\n): ReturnGeneric {\n if (!metafield.type) {\n const noTypeError = `parseMetafield(): The 'type' field is required in order to parse the Metafield.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noTypeError);\n } else {\n console.error(`${noTypeError} Returning 'parsedValue' of 'null'`);\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n\n switch (metafield.type) {\n case 'boolean':\n return {\n ...metafield,\n parsedValue: metafield.value === 'true',\n } as ReturnGeneric;\n\n case 'collection_reference':\n case 'file_reference':\n case 'page_reference':\n case 'product_reference':\n case 'variant_reference':\n return {\n ...metafield,\n parsedValue: metafield.reference,\n } as ReturnGeneric;\n\n case 'color':\n case 'multi_line_text_field':\n case 'single_line_text_field':\n case 'url':\n return {\n ...metafield,\n parsedValue: metafield.value,\n } as ReturnGeneric;\n\n // TODO: 'money' should probably be parsed even further to like `useMoney()`, but that logic needs to be extracted first so it's not a hook\n case 'dimension':\n case 'money':\n case 'json':\n case 'rating':\n case 'volume':\n case 'weight':\n case 'list.color':\n case 'list.dimension':\n case 'list.number_integer':\n case 'list.number_decimal':\n case 'list.rating':\n case 'list.single_line_text_field':\n case 'list.url':\n case 'list.volume':\n case 'list.weight': {\n let parsedValue = null;\n try {\n parsedValue = parseJSON(metafield.value ?? '');\n } catch (err) {\n const parseError = `parseMetafield(): attempted to JSON.parse the 'metafield.value' property, but failed.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(parseError);\n } else {\n console.error(`${parseError} Returning 'null' for 'parsedValue'`);\n }\n parsedValue = null;\n }\n return {\n ...metafield,\n parsedValue,\n } as ReturnGeneric;\n }\n\n case 'date':\n case 'date_time':\n return {\n ...metafield,\n parsedValue: new Date(metafield.value ?? ''),\n } as ReturnGeneric;\n\n case 'list.date':\n case 'list.date_time': {\n const jsonParseValue = parseJSON(metafield?.value ?? '') as string[];\n return {\n ...metafield,\n parsedValue: jsonParseValue.map((dateString) => new Date(dateString)),\n } as ReturnGeneric;\n }\n\n case 'number_decimal':\n case 'number_integer':\n return {\n ...metafield,\n parsedValue: Number(metafield.value),\n } as ReturnGeneric;\n\n case 'list.collection_reference':\n case 'list.file_reference':\n case 'list.page_reference':\n case 'list.product_reference':\n case 'list.variant_reference':\n return {\n ...metafield,\n parsedValue: flattenConnection(metafield.references ?? undefined),\n } as ReturnGeneric;\n\n default: {\n const typeNotFoundError = `parseMetafield(): the 'metafield.type' you passed in is not supported. Your type: \"${metafield.type}\". If you believe this is an error, please open an issue on GitHub.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typeNotFoundError);\n } else {\n console.error(\n `${typeNotFoundError} Returning 'parsedValue' of 'null'`,\n );\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n }\n}\n\n/**\n * Parses a JSON string while preventing prototype injection attacks.\n */\nexport function parseJSON(json: string): unknown {\n if (String(json).includes('__proto__')) {\n return JSON.parse(json, (k, v) => {\n if (k !== '__proto__') return v as unknown;\n }) as unknown;\n }\n return JSON.parse(json) as unknown;\n}\n\n// taken from https://shopify.dev/apps/metafields/types\nexport const allMetafieldTypesArray = [\n 'boolean',\n 'collection_reference',\n 'color',\n 'date',\n 'date_time',\n 'dimension',\n 'file_reference',\n 'json',\n 'money',\n 'multi_line_text_field',\n 'number_decimal',\n 'number_integer',\n 'page_reference',\n 'product_reference',\n 'rating',\n 'single_line_text_field',\n 'url',\n 'variant_reference',\n 'volume',\n 'weight',\n // list metafields\n 'list.collection_reference',\n 'list.color',\n 'list.date',\n 'list.date_time',\n 'list.dimension',\n 'list.file_reference',\n 'list.number_integer',\n 'list.number_decimal',\n 'list.page_reference',\n 'list.product_reference',\n 'list.rating',\n 'list.single_line_text_field',\n 'list.url',\n 'list.variant_reference',\n 'list.volume',\n 'list.weight',\n] as const;\n\n/** A union of all the supported `metafield.type`s */\nexport type MetafieldTypeTypes = (typeof allMetafieldTypesArray)[number];\n\n/**\n * A mapping of a Metafield's `type` to the TypeScript type that is returned from `parseMetafield()`\n * For example, when using `parseMetafield()`, the type will be correctly returned when used like the following:\n *\n * ```\n * const parsedMetafield = parseMetafield<ParsedMetafields['boolean']>(metafield);`\n * ```\n * `parsedMetafield.parsedValue`'s type is now `boolean`\n */\nexport type ParsedMetafields<ExtraTypeGeneric = void> = {\n /** A Metafield that's been parsed, with a `parsedValue` of `boolean` */\n boolean: Simplify<BooleanParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Collection` object (as defined by the Storefront API) */\n collection_reference: Simplify<CollectionParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n color: Simplify<ColorParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date_time: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n dimension: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `GenericFile` object (as defined by the Storefront API) */\n file_reference: Simplify<FileRefParsedMetafield>;\n /**\n * A Metafield that's been parsed, with a `parsedValue` of type `unknown`, unless you pass in the type as a generic. For example:\n *\n * ```\n * ParsedMetafields<MyJsonType>['json']\n * ```\n */\n json: Simplify<JsonParsedMetafield<ExtraTypeGeneric>>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Money` */\n money: Simplify<MoneyParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n multi_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_decimal: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_integer: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Page` object (as defined by the Storefront API) */\n page_reference: Simplify<PageParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Product` object (as defined by the Storefront API) */\n product_reference: Simplify<ProductParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rating: Simplify<RatingParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n single_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n url: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `ProductVariant` object (as defined by the Storefront API) */\n variant_reference: Simplify<VariantParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n volume: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n weight: Simplify<MeasurementParsedMetafield>;\n // list metafields\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Collection` objects (as defined by the Storefront API) */\n 'list.collection_reference': Simplify<CollectionListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.color': Simplify<ColorListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date_time': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement` objects */\n 'list.dimension': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `GenericFile` objects (as defined by the Storefront API) */\n 'list.file_reference': Simplify<FileListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_integer': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_decimal': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Page` objects (as defined by the Storefront API) */\n 'list.page_reference': Simplify<PageListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Product` objects (as defined by the Storefront API) */\n 'list.product_reference': Simplify<ProductListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Rating`s */\n 'list.rating': Simplify<RatingListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.single_line_text_field': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.url': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `ProductVariant` objects (as defined by the Storefront API) */\n 'list.variant_reference': Simplify<VariantListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.volume': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.weight': Simplify<MeasurementListParsedMetafield>;\n};\n\ninterface ParsedBase extends MetafieldBaseType {\n type: MetafieldTypeTypes;\n parsedValue: unknown;\n}\n\ninterface BooleanParsedMetafield extends ParsedBase {\n type: 'boolean';\n parsedValue: boolean | null;\n}\ntype CollectionParsedRefMetafield = MetafieldBaseType & {\n type: 'collection_reference';\n parsedValue: Collection | null;\n};\ntype ColorParsedMetafield = MetafieldBaseType & {\n type: 'color';\n parsedValue: string | null;\n};\ntype DatesParsedMetafield = MetafieldBaseType & {\n type: 'date' | 'date_time';\n parsedValue: Date | null;\n};\n\ntype MeasurementParsedMetafield = MetafieldBaseType & {\n type: 'dimension' | 'weight' | 'volume';\n parsedValue: Measurement | null;\n};\n\ntype FileRefParsedMetafield = MetafieldBaseType & {\n type: 'file_reference';\n parsedValue: GenericFile | null;\n};\n\ntype JsonParsedMetafield<JsonTypeGeneric = void> = MetafieldBaseType & {\n type: 'json';\n parsedValue: JsonTypeGeneric extends void ? unknown : JsonTypeGeneric | null;\n};\n\ntype MoneyParsedMetafield = MetafieldBaseType & {\n type: 'money';\n parsedValue: MoneyV2 | null;\n};\n\ntype TextParsedMetafield = MetafieldBaseType & {\n type: 'single_line_text_field' | 'multi_line_text_field' | 'url';\n parsedValue: string | null;\n};\n\ntype NumberParsedMetafield = MetafieldBaseType & {\n type: 'number_decimal' | 'number_integer';\n parsedValue: number | null;\n};\n\ntype PageParsedRefMetafield = MetafieldBaseType & {\n type: 'page_reference';\n parsedValue: Page | null;\n};\n\ntype ProductParsedRefMetafield = MetafieldBaseType & {\n type: 'product_reference';\n parsedValue: Product | null;\n};\n\ntype RatingParsedMetafield = MetafieldBaseType & {\n type: 'rating';\n parsedValue: Rating | null;\n};\n\ntype VariantParsedRefMetafield = MetafieldBaseType & {\n type: 'variant_reference';\n parsedValue: ProductVariant | null;\n};\n\ntype CollectionListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.collection_reference';\n parsedValue: Array<Collection> | null;\n};\n\ntype ColorListParsedMetafield = MetafieldBaseType & {\n type: 'list.color';\n parsedValue: Array<string> | null;\n};\n\ntype DatesListParsedMetafield = MetafieldBaseType & {\n type: 'list.date' | 'list.date_time';\n parsedValue: Array<Date> | null;\n};\n\ntype MeasurementListParsedMetafield = MetafieldBaseType & {\n type: 'list.dimension' | 'list.weight' | 'list.volume';\n parsedValue: Array<Measurement> | null;\n};\n\ntype FileListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.file_reference';\n parsedValue: Array<GenericFile> | null;\n};\n\ntype TextListParsedMetafield = MetafieldBaseType & {\n type: 'list.single_line_text_field' | 'list.url';\n parsedValue: Array<string> | null;\n};\n\ntype NumberListParsedMetafield = MetafieldBaseType & {\n type: 'list.number_decimal' | 'list.number_integer';\n parsedValue: Array<number> | null;\n};\n\ntype PageListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.page_reference';\n parsedValue: Array<Page> | null;\n};\n\ntype ProductListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.product_reference';\n parsedValue: Array<Product> | null;\n};\n\ntype RatingListParsedMetafield = MetafieldBaseType & {\n type: 'list.rating';\n parsedValue: Array<Rating> | null;\n};\n\ntype VariantListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.variant_reference';\n parsedValue: Array<ProductVariant> | null;\n};\n\nexport type Measurement = {\n unit: string;\n value: number;\n};\n\nexport interface Rating {\n value: number;\n scale_min: number;\n scale_max: number;\n}\n"],"names":[],"mappings":";AAqBO,SAAS,eACd,WACe;AACX,MAAA,CAAC,UAAU,MAAM;AACnB,UAAM,cAAc;AACE;AACd,YAAA,IAAI,MAAM,WAAW;AAAA,IAO7B;AAAA,EACF;AAEA,UAAQ,UAAU,MAAM;AAAA,IACtB,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU,UAAU;AAAA,MAAA;AAAA,IAGrC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAG3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAI3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,eAAe;AAClB,UAAI,cAAc;AACd,UAAA;AACY,sBAAA,UAAU,UAAU,SAAS,EAAE;AAAA,eACtC,KAAK;AACZ,cAAM,aAAa;AACG;AACd,gBAAA,IAAI,MAAM,UAAU;AAAA,QAG5B;AAAA,MAEF;AACO,aAAA;AAAA,QACL,GAAG;AAAA,QACH;AAAA,MAAA;AAAA,IAEJ;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,IAAI,KAAK,UAAU,SAAS,EAAE;AAAA,MAAA;AAAA,IAG/C,KAAK;AAAA,IACL,KAAK,kBAAkB;AACrB,YAAM,iBAAiB,WAAU,uCAAW,UAAS,EAAE;AAChD,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,eAAe,IAAI,CAAC,eAAe,IAAI,KAAK,UAAU,CAAC;AAAA,MAAA;AAAA,IAExE;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,OAAO,UAAU,KAAK;AAAA,MAAA;AAAA,IAGvC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,kBAAkB,UAAU,cAAc,MAAS;AAAA,MAAA;AAAA,IAGpE,SAAS;AACD,YAAA,oBAAoB,sFAAsF,UAAU,IAAI;AACxG;AACd,cAAA,IAAI,MAAM,iBAAiB;AAAA,MASnC;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,UAAU,MAAuB;AAC/C,MAAI,OAAO,IAAI,EAAE,SAAS,WAAW,GAAG;AACtC,WAAO,KAAK,MAAM,MAAM,CAAC,GAAG,MAAM;AAChC,UAAI,MAAM;AAAoB,eAAA;AAAA,IAAA,CAC/B;AAAA,EACH;AACO,SAAA,KAAK,MAAM,IAAI;AACxB;"}
1
+ {"version":3,"file":"parse-metafield.mjs","sources":["../../src/parse-metafield.ts"],"sourcesContent":["import type {\n Collection,\n GenericFile,\n Metafield as MetafieldBaseType,\n MoneyV2,\n Page,\n Product,\n ProductVariant,\n} from './storefront-api-types.js';\nimport type {PartialDeep, Simplify} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\nimport {RootASTNode as RichTextRootASTNode} from './RichText.types.js';\n\n/**\n * A function that uses `metafield.type` to parse the Metafield's `value` or `reference` or `references` (depending on the `metafield.type`) and places the result in `metafield.parsedValue`\n *\n * TypeScript developers can use the type `ParsedMetafields` from this package to get the returned object's type correct. For example:\n *\n * ```\n * parseMetafield<ParsedMetafields['boolean']>({type: 'boolean', value: 'false'}\n * ```\n */\nexport function parseMetafield<ReturnGeneric>(\n metafield: PartialDeep<MetafieldBaseType, {recurseIntoArrays: true}>,\n): ReturnGeneric {\n if (!metafield.type) {\n const noTypeError = `parseMetafield(): The 'type' field is required in order to parse the Metafield.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noTypeError);\n } else {\n console.error(`${noTypeError} Returning 'parsedValue' of 'null'`);\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n\n switch (metafield.type) {\n case 'boolean':\n return {\n ...metafield,\n parsedValue: metafield.value === 'true',\n } as ReturnGeneric;\n\n case 'collection_reference':\n case 'file_reference':\n case 'page_reference':\n case 'product_reference':\n case 'variant_reference':\n return {\n ...metafield,\n parsedValue: metafield.reference,\n } as ReturnGeneric;\n\n case 'color':\n case 'multi_line_text_field':\n case 'single_line_text_field':\n case 'url':\n return {\n ...metafield,\n parsedValue: metafield.value,\n } as ReturnGeneric;\n\n // TODO: 'money' should probably be parsed even further to like `useMoney()`, but that logic needs to be extracted first so it's not a hook\n case 'dimension':\n case 'money':\n case 'json':\n case 'rating':\n case 'volume':\n case 'weight':\n case 'rich_text_field':\n case 'list.color':\n case 'list.dimension':\n case 'list.number_integer':\n case 'list.number_decimal':\n case 'list.rating':\n case 'list.single_line_text_field':\n case 'list.url':\n case 'list.volume':\n case 'list.weight': {\n let parsedValue = null;\n try {\n parsedValue = parseJSON(metafield.value ?? '');\n } catch (err) {\n const parseError = `parseMetafield(): attempted to JSON.parse the 'metafield.value' property, but failed.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(parseError);\n } else {\n console.error(`${parseError} Returning 'null' for 'parsedValue'`);\n }\n parsedValue = null;\n }\n return {\n ...metafield,\n parsedValue,\n } as ReturnGeneric;\n }\n\n case 'date':\n case 'date_time':\n return {\n ...metafield,\n parsedValue: new Date(metafield.value ?? ''),\n } as ReturnGeneric;\n\n case 'list.date':\n case 'list.date_time': {\n const jsonParseValue = parseJSON(metafield?.value ?? '') as string[];\n return {\n ...metafield,\n parsedValue: jsonParseValue.map((dateString) => new Date(dateString)),\n } as ReturnGeneric;\n }\n\n case 'number_decimal':\n case 'number_integer':\n return {\n ...metafield,\n parsedValue: Number(metafield.value),\n } as ReturnGeneric;\n\n case 'list.collection_reference':\n case 'list.file_reference':\n case 'list.page_reference':\n case 'list.product_reference':\n case 'list.variant_reference':\n return {\n ...metafield,\n parsedValue: flattenConnection(metafield.references ?? undefined),\n } as ReturnGeneric;\n\n default: {\n const typeNotFoundError = `parseMetafield(): the 'metafield.type' you passed in is not supported. Your type: \"${metafield.type}\". If you believe this is an error, please open an issue on GitHub.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typeNotFoundError);\n } else {\n console.error(\n `${typeNotFoundError} Returning 'parsedValue' of 'null'`,\n );\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n }\n}\n\n/**\n * Parses a JSON string while preventing prototype injection attacks.\n */\nexport function parseJSON(json: string): unknown {\n if (String(json).includes('__proto__')) {\n return JSON.parse(json, (k, v) => {\n if (k !== '__proto__') return v as unknown;\n }) as unknown;\n }\n return JSON.parse(json) as unknown;\n}\n\n// taken from https://shopify.dev/apps/metafields/types\nexport const allMetafieldTypesArray = [\n 'boolean',\n 'collection_reference',\n 'color',\n 'date',\n 'date_time',\n 'dimension',\n 'file_reference',\n 'json',\n 'money',\n 'rich_text_field',\n 'multi_line_text_field',\n 'number_decimal',\n 'number_integer',\n 'page_reference',\n 'product_reference',\n 'rating',\n 'single_line_text_field',\n 'url',\n 'variant_reference',\n 'volume',\n 'weight',\n // list metafields\n 'list.collection_reference',\n 'list.color',\n 'list.date',\n 'list.date_time',\n 'list.dimension',\n 'list.file_reference',\n 'list.number_integer',\n 'list.number_decimal',\n 'list.page_reference',\n 'list.product_reference',\n 'list.rating',\n 'list.single_line_text_field',\n 'list.url',\n 'list.variant_reference',\n 'list.volume',\n 'list.weight',\n] as const;\n\n/** A union of all the supported `metafield.type`s */\nexport type MetafieldTypeTypes = (typeof allMetafieldTypesArray)[number];\n\n/**\n * A mapping of a Metafield's `type` to the TypeScript type that is returned from `parseMetafield()`\n * For example, when using `parseMetafield()`, the type will be correctly returned when used like the following:\n *\n * ```\n * const parsedMetafield = parseMetafield<ParsedMetafields['boolean']>(metafield);`\n * ```\n * `parsedMetafield.parsedValue`'s type is now `boolean`\n */\nexport type ParsedMetafields<ExtraTypeGeneric = void> = {\n /** A Metafield that's been parsed, with a `parsedValue` of `boolean` */\n boolean: Simplify<BooleanParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Collection` object (as defined by the Storefront API) */\n collection_reference: Simplify<CollectionParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n color: Simplify<ColorParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date_time: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n dimension: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `GenericFile` object (as defined by the Storefront API) */\n file_reference: Simplify<FileRefParsedMetafield>;\n /**\n * A Metafield that's been parsed, with a `parsedValue` of type `unknown`, unless you pass in the type as a generic. For example:\n *\n * ```\n * ParsedMetafields<MyJsonType>['json']\n * ```\n */\n json: Simplify<JsonParsedMetafield<ExtraTypeGeneric>>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Money` */\n money: Simplify<MoneyParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n multi_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_decimal: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_integer: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Page` object (as defined by the Storefront API) */\n page_reference: Simplify<PageParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Product` object (as defined by the Storefront API) */\n product_reference: Simplify<ProductParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rating: Simplify<RatingParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rich_text_field: Simplify<RichTextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n single_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n url: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `ProductVariant` object (as defined by the Storefront API) */\n variant_reference: Simplify<VariantParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n volume: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n weight: Simplify<MeasurementParsedMetafield>;\n // list metafields\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Collection` objects (as defined by the Storefront API) */\n 'list.collection_reference': Simplify<CollectionListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.color': Simplify<ColorListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date_time': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement` objects */\n 'list.dimension': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `GenericFile` objects (as defined by the Storefront API) */\n 'list.file_reference': Simplify<FileListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_integer': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_decimal': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Page` objects (as defined by the Storefront API) */\n 'list.page_reference': Simplify<PageListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Product` objects (as defined by the Storefront API) */\n 'list.product_reference': Simplify<ProductListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Rating`s */\n 'list.rating': Simplify<RatingListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.single_line_text_field': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.url': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `ProductVariant` objects (as defined by the Storefront API) */\n 'list.variant_reference': Simplify<VariantListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.volume': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.weight': Simplify<MeasurementListParsedMetafield>;\n};\n\ninterface ParsedBase extends MetafieldBaseType {\n type: MetafieldTypeTypes;\n parsedValue: unknown;\n}\n\ninterface BooleanParsedMetafield extends ParsedBase {\n type: 'boolean';\n parsedValue: boolean | null;\n}\ntype CollectionParsedRefMetafield = MetafieldBaseType & {\n type: 'collection_reference';\n parsedValue: Collection | null;\n};\ntype ColorParsedMetafield = MetafieldBaseType & {\n type: 'color';\n parsedValue: string | null;\n};\ntype DatesParsedMetafield = MetafieldBaseType & {\n type: 'date' | 'date_time';\n parsedValue: Date | null;\n};\n\ntype MeasurementParsedMetafield = MetafieldBaseType & {\n type: 'dimension' | 'weight' | 'volume';\n parsedValue: Measurement | null;\n};\n\ntype FileRefParsedMetafield = MetafieldBaseType & {\n type: 'file_reference';\n parsedValue: GenericFile | null;\n};\n\ntype JsonParsedMetafield<JsonTypeGeneric = void> = MetafieldBaseType & {\n type: 'json';\n parsedValue: JsonTypeGeneric extends void ? unknown : JsonTypeGeneric | null;\n};\n\ntype MoneyParsedMetafield = MetafieldBaseType & {\n type: 'money';\n parsedValue: MoneyV2 | null;\n};\n\ntype TextParsedMetafield = MetafieldBaseType & {\n type: 'single_line_text_field' | 'multi_line_text_field' | 'url';\n parsedValue: string | null;\n};\n\ntype NumberParsedMetafield = MetafieldBaseType & {\n type: 'number_decimal' | 'number_integer';\n parsedValue: number | null;\n};\n\ntype PageParsedRefMetafield = MetafieldBaseType & {\n type: 'page_reference';\n parsedValue: Page | null;\n};\n\ntype ProductParsedRefMetafield = MetafieldBaseType & {\n type: 'product_reference';\n parsedValue: Product | null;\n};\n\ntype RatingParsedMetafield = MetafieldBaseType & {\n type: 'rating';\n parsedValue: Rating | null;\n};\n\ntype RichTextParsedMetafield = MetafieldBaseType & {\n type: 'rich_text_field';\n parsedValue: RichTextRootASTNode | null;\n};\n\ntype VariantParsedRefMetafield = MetafieldBaseType & {\n type: 'variant_reference';\n parsedValue: ProductVariant | null;\n};\n\ntype CollectionListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.collection_reference';\n parsedValue: Array<Collection> | null;\n};\n\ntype ColorListParsedMetafield = MetafieldBaseType & {\n type: 'list.color';\n parsedValue: Array<string> | null;\n};\n\ntype DatesListParsedMetafield = MetafieldBaseType & {\n type: 'list.date' | 'list.date_time';\n parsedValue: Array<Date> | null;\n};\n\ntype MeasurementListParsedMetafield = MetafieldBaseType & {\n type: 'list.dimension' | 'list.weight' | 'list.volume';\n parsedValue: Array<Measurement> | null;\n};\n\ntype FileListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.file_reference';\n parsedValue: Array<GenericFile> | null;\n};\n\ntype TextListParsedMetafield = MetafieldBaseType & {\n type: 'list.single_line_text_field' | 'list.url';\n parsedValue: Array<string> | null;\n};\n\ntype NumberListParsedMetafield = MetafieldBaseType & {\n type: 'list.number_decimal' | 'list.number_integer';\n parsedValue: Array<number> | null;\n};\n\ntype PageListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.page_reference';\n parsedValue: Array<Page> | null;\n};\n\ntype ProductListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.product_reference';\n parsedValue: Array<Product> | null;\n};\n\ntype RatingListParsedMetafield = MetafieldBaseType & {\n type: 'list.rating';\n parsedValue: Array<Rating> | null;\n};\n\ntype VariantListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.variant_reference';\n parsedValue: Array<ProductVariant> | null;\n};\n\nexport type Measurement = {\n unit: string;\n value: number;\n};\n\nexport interface Rating {\n value: number;\n scale_min: number;\n scale_max: number;\n}\n"],"names":[],"mappings":";AAsBO,SAAS,eACd,WACe;AACX,MAAA,CAAC,UAAU,MAAM;AACnB,UAAM,cAAc;AACE;AACd,YAAA,IAAI,MAAM,WAAW;AAAA,IAO7B;AAAA,EACF;AAEA,UAAQ,UAAU,MAAM;AAAA,IACtB,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU,UAAU;AAAA,MAAA;AAAA,IAGrC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAG3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAI3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,eAAe;AAClB,UAAI,cAAc;AACd,UAAA;AACY,sBAAA,UAAU,UAAU,SAAS,EAAE;AAAA,eACtC,KAAK;AACZ,cAAM,aAAa;AACG;AACd,gBAAA,IAAI,MAAM,UAAU;AAAA,QAG5B;AAAA,MAEF;AACO,aAAA;AAAA,QACL,GAAG;AAAA,QACH;AAAA,MAAA;AAAA,IAEJ;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,IAAI,KAAK,UAAU,SAAS,EAAE;AAAA,MAAA;AAAA,IAG/C,KAAK;AAAA,IACL,KAAK,kBAAkB;AACrB,YAAM,iBAAiB,WAAU,uCAAW,UAAS,EAAE;AAChD,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,eAAe,IAAI,CAAC,eAAe,IAAI,KAAK,UAAU,CAAC;AAAA,MAAA;AAAA,IAExE;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,OAAO,UAAU,KAAK;AAAA,MAAA;AAAA,IAGvC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,kBAAkB,UAAU,cAAc,MAAS;AAAA,MAAA;AAAA,IAGpE,SAAS;AACD,YAAA,oBAAoB,sFAAsF,UAAU,IAAI;AACxG;AACd,cAAA,IAAI,MAAM,iBAAiB;AAAA,MASnC;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,UAAU,MAAuB;AAC/C,MAAI,OAAO,IAAI,EAAE,SAAS,WAAW,GAAG;AACtC,WAAO,KAAK,MAAM,MAAM,CAAC,GAAG,MAAM;AAChC,UAAI,MAAM;AAAoB,eAAA;AAAA,IAAA,CAC/B;AAAA,EACH;AACO,SAAA,KAAK,MAAM,IAAI;AACxB;"}
@@ -20,7 +20,7 @@ function createStorefrontClient({
20
20
  if (storefrontApiVersion !== SFAPI_VERSION) {
21
21
  warnOnce(
22
22
  `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.
23
- You may run into unexpected errors if these versions don't match. Received verion: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`
23
+ You may run into unexpected errors if these versions don't match. Received version: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`
24
24
  );
25
25
  }
26
26
  if (!privateStorefrontToken && !globalThis.document && !isMockShop(storeDomain)) {
@@ -1 +1 @@
1
- {"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: 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 * 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 * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\nconst MOCK_SHOP_DOMAIN = 'mock.shop';\nconst isMockShop = (domain: string): boolean =>\n domain.includes(MOCK_SHOP_DOMAIN);\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient({\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n}: StorefrontClientProps): StorefrontClientReturn {\n if (!storeDomain) {\n if (__HYDROGEN_DEV__) {\n storeDomain = MOCK_SHOP_DOMAIN;\n warnOnce(\n `storeDomain missing, defaulting to ${MOCK_SHOP_DOMAIN}`,\n 'info',\n );\n } else {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client in production.`,\n );\n }\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (\n __HYDROGEN_DEV__ &&\n !privateStorefrontToken &&\n !globalThis.document &&\n !isMockShop(storeDomain)\n ) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst warnOnce = (string: string, type: 'warn' | 'info' = 'warn'): void => {\n if (!warnings.has(string)) {\n console[type](`[h2:${type}:createStorefrontClient] ` + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\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 `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\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 calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAmBA,MAAM,mBAAmB;AACzB,MAAM,aAAa,CAAC,WAClB,OAAO,SAAS,gBAAgB;AAO3B,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB;AACF,GAAkD;AAChD,MAAI,CAAC,aAAa;AACM;AACN,oBAAA;AACd;AAAA,QACE,sCAAsC,gBAAgB;AAAA,QACtD;AAAA,MAAA;AAAA,IAOJ;AAAA,EACF;AAEA,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE;AAAA,sFAC2F,oBAAoB,wBAAwB,aAAa;AAAA,IAAA;AAAA,EAExJ;AAKE,MAAA,CAAC,0BACD,CAAC,WAAW,YACZ,CAAC,WAAW,WAAW,GACvB;AACA;AAAA,MACE;AAAA;AAAA,IAAA;AAAA,EAGJ;AAGwB,MAAA,0BAA0B,WAAW,UAAU;AACrE;AAAA,MACE;AAAA,IAAA;AAAA,EAGJ;AAEM,QAAA,mBAA+D,CACnE,kBACG;AACG,UAAA,UAAS,+CAAe,gBAAe;AAC7C,WAAO,OAAO,SAAS,KAAK,IAAI,SAAS,WAAW,MAAM;AAAA,EAAA;AAGrD,SAAA;AAAA,IACL;AAAA,IACA,oBAAoB,eAAuB;AACnC,YAAA,SAAS,iBAAiB,aAAa;AAC7C,YAAM,SAAS,UAAU,OAAO,SAAS,GAAG,IAAI,QAAQ;AAExD,UAAI,WAAW,MAAM;AAAU,eAAA;AAE/B,aAAO,GAAG,MAAM,KACd,+CAAe,yBAAwB,oBACzC;AAAA,IACF;AAAA,IACA,uBAAuB,eAAuC;AAE1D,UAAA,CAAC,0BACD,EAAC,+CAAe,2BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEwB,UAAA,EAAC,+CAAe,UAAS;AAC/C;AAAA,UACE;AAAA,QAAA;AAAA,MAEJ;AAEM,YAAA,oBAAmB,+CAAe,gBAAe;AAEhD,aAAA;AAAA;AAAA,QAEL,gBACE,qBAAqB,YACjB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAEzD,UAAA,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,WAAW,CAAC,QAAgB,OAAwB,WAAiB;AACzE,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,IAAI,EAAE,OAAO,IAAI,8BAA8B,MAAM;AAC7D,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
1
+ {"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: 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 * 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 * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\nconst MOCK_SHOP_DOMAIN = 'mock.shop';\nconst isMockShop = (domain: string): boolean =>\n domain.includes(MOCK_SHOP_DOMAIN);\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient({\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n}: StorefrontClientProps): StorefrontClientReturn {\n if (!storeDomain) {\n if (__HYDROGEN_DEV__) {\n storeDomain = MOCK_SHOP_DOMAIN;\n warnOnce(\n `storeDomain missing, defaulting to ${MOCK_SHOP_DOMAIN}`,\n 'info',\n );\n } else {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client in production.`,\n );\n }\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received version: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (\n __HYDROGEN_DEV__ &&\n !privateStorefrontToken &&\n !globalThis.document &&\n !isMockShop(storeDomain)\n ) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst warnOnce = (string: string, type: 'warn' | 'info' = 'warn'): void => {\n if (!warnings.has(string)) {\n console[type](`[h2:${type}:createStorefrontClient] ` + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\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 `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\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 calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAmBA,MAAM,mBAAmB;AACzB,MAAM,aAAa,CAAC,WAClB,OAAO,SAAS,gBAAgB;AAO3B,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB;AACF,GAAkD;AAChD,MAAI,CAAC,aAAa;AACM;AACN,oBAAA;AACd;AAAA,QACE,sCAAsC,gBAAgB;AAAA,QACtD;AAAA,MAAA;AAAA,IAOJ;AAAA,EACF;AAEA,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE;AAAA,uFAC4F,oBAAoB,wBAAwB,aAAa;AAAA,IAAA;AAAA,EAEzJ;AAKE,MAAA,CAAC,0BACD,CAAC,WAAW,YACZ,CAAC,WAAW,WAAW,GACvB;AACA;AAAA,MACE;AAAA;AAAA,IAAA;AAAA,EAGJ;AAGwB,MAAA,0BAA0B,WAAW,UAAU;AACrE;AAAA,MACE;AAAA,IAAA;AAAA,EAGJ;AAEM,QAAA,mBAA+D,CACnE,kBACG;AACG,UAAA,UAAS,+CAAe,gBAAe;AAC7C,WAAO,OAAO,SAAS,KAAK,IAAI,SAAS,WAAW,MAAM;AAAA,EAAA;AAGrD,SAAA;AAAA,IACL;AAAA,IACA,oBAAoB,eAAuB;AACnC,YAAA,SAAS,iBAAiB,aAAa;AAC7C,YAAM,SAAS,UAAU,OAAO,SAAS,GAAG,IAAI,QAAQ;AAExD,UAAI,WAAW,MAAM;AAAU,eAAA;AAE/B,aAAO,GAAG,MAAM,KACd,+CAAe,yBAAwB,oBACzC;AAAA,IACF;AAAA,IACA,uBAAuB,eAAuC;AAE1D,UAAA,CAAC,0BACD,EAAC,+CAAe,2BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEwB,UAAA,EAAC,+CAAe,UAAS;AAC/C;AAAA,UACE;AAAA,QAAA;AAAA,MAEJ;AAEM,YAAA,oBAAmB,+CAAe,gBAAe;AAEhD,aAAA;AAAA;AAAA,QAEL,gBACE,qBAAqB,YACjB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAEzD,UAAA,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,WAAW,CAAC,QAAgB,OAAwB,WAAiB;AACzE,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,IAAI,EAAE,OAAO,IAAI,8BAA8B,MAAM;AAC7D,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
@@ -8,22 +8,26 @@ function useShopifyCookies(options) {
8
8
  const { hasUserConsent = false, domain = "" } = options || {};
9
9
  useEffect(() => {
10
10
  const cookies = getShopifyCookies(document.cookie);
11
+ let currentDomain = domain || window.document.location.host;
12
+ if (/^localhost/.test(currentDomain))
13
+ currentDomain = "";
14
+ const domainWithLeadingDot = currentDomain ? /^\./.test(currentDomain) ? currentDomain : `.${currentDomain}` : "";
11
15
  if (hasUserConsent) {
12
16
  setCookie(
13
17
  SHOPIFY_Y,
14
18
  cookies[SHOPIFY_Y] || buildUUID(),
15
19
  longTermLength,
16
- domain
20
+ domainWithLeadingDot
17
21
  );
18
22
  setCookie(
19
23
  SHOPIFY_S,
20
24
  cookies[SHOPIFY_S] || buildUUID(),
21
25
  shortTermLength,
22
- domain
26
+ domainWithLeadingDot
23
27
  );
24
28
  } else {
25
- setCookie(SHOPIFY_Y, "", 0, domain);
26
- setCookie(SHOPIFY_S, "", 0, domain);
29
+ setCookie(SHOPIFY_Y, "", 0, domainWithLeadingDot);
30
+ setCookie(SHOPIFY_S, "", 0, domainWithLeadingDot);
27
31
  }
28
32
  }, [options, hasUserConsent, domain]);
29
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useShopifyCookies.mjs","sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect} from 'react';\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID, getShopifyCookies} from './cookies-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = {\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\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): void {\n const {hasUserConsent = false, domain = ''} = options || {};\n useEffect(() => {\n const cookies = getShopifyCookies(document.cookie);\n\n /**\n * Set user and session cookies and refresh the expiry time\n */\n if (hasUserConsent) {\n setCookie(\n SHOPIFY_Y,\n cookies[SHOPIFY_Y] || buildUUID(),\n longTermLength,\n domain,\n );\n setCookie(\n SHOPIFY_S,\n cookies[SHOPIFY_S] || buildUUID(),\n shortTermLength,\n domain,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domain);\n setCookie(SHOPIFY_S, '', 0, domain);\n }\n }, [options, hasUserConsent, domain]);\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"],"names":[],"mappings":";;;;AAKA,MAAM,iBAAiB,KAAK,KAAK,KAAK,MAAM;AAC5C,MAAM,kBAAkB,KAAK;AAetB,SAAS,kBAAkB,SAA0C;AAC1E,QAAM,EAAC,iBAAiB,OAAO,SAAS,GAAE,IAAI,WAAW;AACzD,YAAU,MAAM;AACR,UAAA,UAAU,kBAAkB,SAAS,MAAM;AAKjD,QAAI,gBAAgB;AAClB;AAAA,QACE;AAAA,QACA,QAAQ,SAAS,KAAK,UAAU;AAAA,QAChC;AAAA,QACA;AAAA,MAAA;AAEF;AAAA,QACE;AAAA,QACA,QAAQ,SAAS,KAAK,UAAU;AAAA,QAChC;AAAA,QACA;AAAA,MAAA;AAAA,IACF,OACK;AACK,gBAAA,WAAW,IAAI,GAAG,MAAM;AACxB,gBAAA,WAAW,IAAI,GAAG,MAAM;AAAA,IACpC;AAAA,EACC,GAAA,CAAC,SAAS,gBAAgB,MAAM,CAAC;AACtC;AAEA,SAAS,UACP,MACA,OACA,QACA,QACM;AACG,WAAA,SAAS,UAAU,MAAM,OAAO;AAAA,IACvC;AAAA,IACA;AAAA,IACA,UAAU;AAAA,IACV,MAAM;AAAA,EAAA,CACP;AACH;"}
1
+ {"version":3,"file":"useShopifyCookies.mjs","sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect} from 'react';\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID, getShopifyCookies} from './cookies-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = {\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\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): void {\n const {hasUserConsent = false, domain = ''} = options || {};\n useEffect(() => {\n const cookies = getShopifyCookies(document.cookie);\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.document.location.host;\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 setCookie(\n SHOPIFY_Y,\n cookies[SHOPIFY_Y] || buildUUID(),\n longTermLength,\n domainWithLeadingDot,\n );\n setCookie(\n SHOPIFY_S,\n cookies[SHOPIFY_S] || buildUUID(),\n shortTermLength,\n domainWithLeadingDot,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domainWithLeadingDot);\n setCookie(SHOPIFY_S, '', 0, domainWithLeadingDot);\n }\n }, [options, hasUserConsent, domain]);\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"],"names":[],"mappings":";;;;AAKA,MAAM,iBAAiB,KAAK,KAAK,KAAK,MAAM;AAC5C,MAAM,kBAAkB,KAAK;AAetB,SAAS,kBAAkB,SAA0C;AAC1E,QAAM,EAAC,iBAAiB,OAAO,SAAS,GAAE,IAAI,WAAW;AACzD,YAAU,MAAM;AACR,UAAA,UAAU,kBAAkB,SAAS,MAAM;AAUjD,QAAI,gBAAgB,UAAU,OAAO,SAAS,SAAS;AAGnD,QAAA,aAAa,KAAK,aAAa;AAAmB,sBAAA;AAGhD,UAAA,uBAAuB,gBACzB,MAAM,KAAK,aAAa,IACtB,gBACA,IAAI,aAAa,KACnB;AAKJ,QAAI,gBAAgB;AAClB;AAAA,QACE;AAAA,QACA,QAAQ,SAAS,KAAK,UAAU;AAAA,QAChC;AAAA,QACA;AAAA,MAAA;AAEF;AAAA,QACE;AAAA,QACA,QAAQ,SAAS,KAAK,UAAU;AAAA,QAChC;AAAA,QACA;AAAA,MAAA;AAAA,IACF,OACK;AACK,gBAAA,WAAW,IAAI,GAAG,oBAAoB;AACtC,gBAAA,WAAW,IAAI,GAAG,oBAAoB;AAAA,IAClD;AAAA,EACC,GAAA,CAAC,SAAS,gBAAgB,MAAM,CAAC;AACtC;AAEA,SAAS,UACP,MACA,OACA,QACA,QACM;AACG,WAAA,SAAS,UAAU,MAAM,OAAO;AAAA,IACvC;AAAA,IACA;AAAA,IACA,UAAU;AAAA,IACV,MAAM;AAAA,EAAA,CACP;AACH;"}
@@ -0,0 +1,57 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { createElement } from "react";
3
+ const RichTextComponents = {
4
+ root: Root,
5
+ heading: Heading,
6
+ paragraph: Paragraph,
7
+ text: Text,
8
+ link: RichTextLink,
9
+ list: List,
10
+ "list-item": ListItem
11
+ };
12
+ function Root({
13
+ node
14
+ }) {
15
+ return /* @__PURE__ */ jsx("div", { children: node.children });
16
+ }
17
+ function Heading({
18
+ node
19
+ }) {
20
+ return createElement(`h${node.level ?? "1"}`, null, node.children);
21
+ }
22
+ function Paragraph({
23
+ node
24
+ }) {
25
+ return /* @__PURE__ */ jsx("p", { children: node.children });
26
+ }
27
+ function Text({
28
+ node
29
+ }) {
30
+ if (node.bold && node.italic)
31
+ return /* @__PURE__ */ jsx("em", { children: /* @__PURE__ */ jsx("strong", { children: node.value }) });
32
+ if (node.bold)
33
+ return /* @__PURE__ */ jsx("strong", { children: node.value });
34
+ if (node.italic)
35
+ return /* @__PURE__ */ jsx("em", { children: node.value });
36
+ return node.value;
37
+ }
38
+ function RichTextLink({
39
+ node
40
+ }) {
41
+ return /* @__PURE__ */ jsx("a", { href: node.url, title: node.title, target: node.target, children: node.children });
42
+ }
43
+ function List({
44
+ node
45
+ }) {
46
+ const List2 = node.listType === "unordered" ? "ul" : "ol";
47
+ return /* @__PURE__ */ jsx(List2, { children: node.children });
48
+ }
49
+ function ListItem({
50
+ node
51
+ }) {
52
+ return /* @__PURE__ */ jsx("li", { children: node.children });
53
+ }
54
+ export {
55
+ RichTextComponents
56
+ };
57
+ //# sourceMappingURL=RichText.components.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RichText.components.mjs","sources":["../../src/RichText.components.tsx"],"sourcesContent":["import {createElement, type ReactNode} from 'react';\n\nexport type CustomComponents = {\n /** The root node of the rich text. Defaults to `<div>` */\n root?: typeof Root;\n /** Customize the headings. Each heading has a `level` property from 1-6. Defaults to `<h1>` to `<h6>` */\n heading?: typeof Heading;\n /** Customize paragraphs. Defaults to `<p>` */\n paragraph?: typeof Paragraph;\n /** Customize how text nodes. They can either be bold or italic. Defaults to `<em>`, `<strong>` or text. */\n text?: typeof Text;\n /** Customize links. Defaults to a React Router `<Link>` component in Hydrogen and a `<a>` in Hydrogen React. */\n link?: typeof RichTextLink;\n /** Customize lists. They can be either ordered or unordered. Defaults to `<ol>` or `<ul>` */\n list?: typeof List;\n /** Customize list items. Defaults to `<li>`. */\n listItem?: typeof ListItem;\n};\n\nexport const RichTextComponents = {\n root: Root,\n heading: Heading,\n paragraph: Paragraph,\n text: Text,\n link: RichTextLink,\n list: List,\n 'list-item': ListItem,\n};\n\nfunction Root({\n node,\n}: {\n node: {\n type: 'root';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <div>{node.children}</div>;\n}\n\nfunction Heading({\n node,\n}: {\n node: {\n type: 'heading';\n level: number;\n children?: ReactNode[];\n };\n}): ReactNode {\n return createElement(`h${node.level ?? '1'}`, null, node.children);\n}\n\nfunction Paragraph({\n node,\n}: {\n node: {\n type: 'paragraph';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <p>{node.children}</p>;\n}\n\nfunction Text({\n node,\n}: {\n node: {\n type: 'text';\n italic?: boolean;\n bold?: boolean;\n value?: string;\n };\n}): ReactNode {\n if (node.bold && node.italic)\n return (\n <em>\n <strong>{node.value}</strong>\n </em>\n );\n\n if (node.bold) return <strong>{node.value}</strong>;\n if (node.italic) return <em>{node.value}</em>;\n\n return node.value;\n}\n\nfunction RichTextLink({\n node,\n}: {\n node: {\n type: 'link';\n url: string;\n title?: string;\n target?: string;\n children?: ReactNode[];\n };\n}): ReactNode {\n return (\n <a href={node.url} title={node.title} target={node.target}>\n {node.children}\n </a>\n );\n}\n\nfunction List({\n node,\n}: {\n node: {\n type: 'list';\n listType: 'unordered' | 'ordered';\n children?: ReactNode[];\n };\n}): ReactNode {\n const List = node.listType === 'unordered' ? 'ul' : 'ol';\n return <List>{node.children}</List>;\n}\n\nfunction ListItem({\n node,\n}: {\n node: {\n type: 'list-item';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <li>{node.children}</li>;\n}\n"],"names":["List"],"mappings":";;AAmBO,MAAM,qBAAqB;AAAA,EAChC,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,aAAa;AACf;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAKc;AACL,SAAA,oBAAC,OAAK,EAAA,UAAA,KAAK,SAAS,CAAA;AAC7B;AAEA,SAAS,QAAQ;AAAA,EACf;AACF,GAMc;AACL,SAAA,cAAc,IAAI,KAAK,SAAS,GAAG,IAAI,MAAM,KAAK,QAAQ;AACnE;AAEA,SAAS,UAAU;AAAA,EACjB;AACF,GAKc;AACL,SAAA,oBAAC,KAAG,EAAA,UAAA,KAAK,SAAS,CAAA;AAC3B;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAOc;AACR,MAAA,KAAK,QAAQ,KAAK;AACpB,+BACG,MACC,EAAA,UAAA,oBAAC,UAAQ,EAAA,UAAA,KAAK,MAAM,CAAA,EACtB,CAAA;AAGJ,MAAI,KAAK;AAAa,WAAA,oBAAC,UAAQ,EAAA,UAAA,KAAK,MAAM,CAAA;AAC1C,MAAI,KAAK;AAAe,WAAA,oBAAC,MAAI,EAAA,UAAA,KAAK,MAAM,CAAA;AAExC,SAAO,KAAK;AACd;AAEA,SAAS,aAAa;AAAA,EACpB;AACF,GAQc;AACZ,SACG,oBAAA,KAAA,EAAE,MAAM,KAAK,KAAK,OAAO,KAAK,OAAO,QAAQ,KAAK,QAChD,UAAA,KAAK,SACR,CAAA;AAEJ;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAMc;AACZ,QAAMA,QAAO,KAAK,aAAa,cAAc,OAAO;AACpD,SAAQA,oBAAAA,OAAA,EAAM,UAAA,KAAK,SAAS,CAAA;AAC9B;AAEA,SAAS,SAAS;AAAA,EAChB;AACF,GAKc;AACL,SAAA,oBAAC,MAAI,EAAA,UAAA,KAAK,SAAS,CAAA;AAC5B;"}