@webiny/website-builder-sdk 6.6.0-alpha.1 → 6.6.0-alpha.10

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 (198) hide show
  1. package/BindingsResolver.d.ts +4 -1
  2. package/BindingsResolver.js.map +1 -1
  3. package/ComponentInputTraverser.js +1 -0
  4. package/ComponentInputTraverser.js.map +1 -1
  5. package/ComponentManifestToAstConverter.d.ts +23 -1
  6. package/ComponentManifestToAstConverter.js +122 -2
  7. package/ComponentManifestToAstConverter.js.map +1 -1
  8. package/ComponentRegistry.d.ts +2 -1
  9. package/ComponentRegistry.js +7 -0
  10. package/ComponentRegistry.js.map +1 -1
  11. package/ComponentResolver.d.ts +6 -3
  12. package/ComponentResolver.js +9 -4
  13. package/ComponentResolver.js.map +1 -1
  14. package/ConstraintEvaluator.d.ts +5 -0
  15. package/ConstraintEvaluator.js +20 -4
  16. package/ConstraintEvaluator.js.map +1 -1
  17. package/ConstraintEvaluator.test.js +137 -0
  18. package/ConstraintEvaluator.test.js.map +1 -1
  19. package/ContentSdk.d.ts +64 -2
  20. package/ContentSdk.js +90 -12
  21. package/ContentSdk.js.map +1 -1
  22. package/DocumentStoreManager.d.ts +9 -2
  23. package/DocumentStoreManager.js +24 -5
  24. package/DocumentStoreManager.js.map +1 -1
  25. package/EditingSdk.d.ts +18 -2
  26. package/EditingSdk.js +30 -5
  27. package/EditingSdk.js.map +1 -1
  28. package/ElementBindings.d.ts +28 -0
  29. package/ElementBindings.js +88 -0
  30. package/ElementBindings.js.map +1 -0
  31. package/ElementBindings.test.d.ts +1 -0
  32. package/ElementBindings.test.js +127 -0
  33. package/ElementBindings.test.js.map +1 -0
  34. package/ElementFactory.d.ts +10 -1
  35. package/ElementFactory.js +38 -7
  36. package/ElementFactory.js.map +1 -1
  37. package/ElementFactory.test.js +260 -0
  38. package/ElementFactory.test.js.map +1 -1
  39. package/ElementSelection.d.ts +20 -0
  40. package/ElementSelection.js +32 -0
  41. package/ElementSelection.js.map +1 -0
  42. package/ElementSelection.test.d.ts +1 -0
  43. package/ElementSelection.test.js +73 -0
  44. package/ElementSelection.test.js.map +1 -0
  45. package/Environment.d.ts +7 -0
  46. package/Environment.js +2 -1
  47. package/Environment.js.map +1 -1
  48. package/Environment.test.d.ts +1 -0
  49. package/Environment.test.js +39 -0
  50. package/Environment.test.js.map +1 -0
  51. package/GlobalComponentLanguage.d.ts +31 -0
  52. package/GlobalComponentLanguage.js +37 -0
  53. package/GlobalComponentLanguage.js.map +1 -0
  54. package/InheritanceProcessor.test.js +8 -0
  55. package/InheritanceProcessor.test.js.map +1 -1
  56. package/InheritedValueResolver.d.ts +6 -0
  57. package/InheritedValueResolver.js +7 -0
  58. package/InheritedValueResolver.js.map +1 -1
  59. package/InputBindingsProcessor.js +6 -2
  60. package/InputBindingsProcessor.js.map +1 -1
  61. package/InputRenderer.test.d.ts +1 -0
  62. package/InputRenderer.test.js +186 -0
  63. package/InputRenderer.test.js.map +1 -0
  64. package/InputsBindingsProcessor.test.js +130 -0
  65. package/InputsBindingsProcessor.test.js.map +1 -1
  66. package/InputsUpdater.js +1 -0
  67. package/InputsUpdater.js.map +1 -1
  68. package/LayoutContentArea.d.ts +68 -0
  69. package/LayoutContentArea.js +78 -0
  70. package/LayoutContentArea.js.map +1 -0
  71. package/LayoutContentArea.test.d.ts +1 -0
  72. package/LayoutContentArea.test.js +111 -0
  73. package/LayoutContentArea.test.js.map +1 -0
  74. package/LiveSdk.d.ts +5 -2
  75. package/LiveSdk.js +6 -2
  76. package/LiveSdk.js.map +1 -1
  77. package/NullSdk.d.ts +2 -1
  78. package/NullSdk.js +3 -0
  79. package/NullSdk.js.map +1 -1
  80. package/PreviewDocument.d.ts +2 -1
  81. package/PreviewDocument.js +2 -2
  82. package/PreviewDocument.js.map +1 -1
  83. package/PreviewSdk.d.ts +5 -2
  84. package/PreviewSdk.js +6 -2
  85. package/PreviewSdk.js.map +1 -1
  86. package/PreviewViewport.d.ts +5 -0
  87. package/PreviewViewport.js +9 -0
  88. package/PreviewViewport.js.map +1 -1
  89. package/PreviewViewport.test.d.ts +1 -0
  90. package/PreviewViewport.test.js +27 -0
  91. package/PreviewViewport.test.js.map +1 -0
  92. package/RadioOptionInputs.test.d.ts +1 -0
  93. package/RadioOptionInputs.test.js +521 -0
  94. package/RadioOptionInputs.test.js.map +1 -0
  95. package/ResizeObserver.js +1 -1
  96. package/ResizeObserver.js.map +1 -1
  97. package/StylesUpdater.js +4 -1
  98. package/StylesUpdater.js.map +1 -1
  99. package/asset/deliveryUrl.test.js +1 -1
  100. package/asset/deliveryUrl.test.js.map +1 -1
  101. package/asset/imageSrcSet.test.js +1 -1
  102. package/asset/imageSrcSet.test.js.map +1 -1
  103. package/asset/normalize.d.ts +1 -1
  104. package/asset/normalize.js +18 -14
  105. package/asset/normalize.js.map +1 -1
  106. package/asset/normalize.test.js +15 -8
  107. package/asset/normalize.test.js.map +1 -1
  108. package/componentLoader/ComponentLoader.d.ts +16 -0
  109. package/componentLoader/ComponentLoader.js +0 -0
  110. package/componentLoader/RegistryOnlyComponentLoader.d.ts +9 -0
  111. package/componentLoader/RegistryOnlyComponentLoader.js +8 -0
  112. package/componentLoader/RegistryOnlyComponentLoader.js.map +1 -0
  113. package/componentLoader/createComponentLoader.d.ts +7 -0
  114. package/componentLoader/createComponentLoader.js +10 -0
  115. package/componentLoader/createComponentLoader.js.map +1 -0
  116. package/componentLoader/defaultComponentLoader.d.ts +7 -0
  117. package/componentLoader/defaultComponentLoader.js +8 -0
  118. package/componentLoader/defaultComponentLoader.js.map +1 -0
  119. package/componentLoader/index.d.ts +3 -0
  120. package/componentLoader/index.js +3 -0
  121. package/contentClientState.test.d.ts +1 -0
  122. package/contentClientState.test.js +404 -0
  123. package/contentClientState.test.js.map +1 -0
  124. package/contentEntry/ContentEntryBindingsResolver.d.ts +33 -0
  125. package/contentEntry/ContentEntryBindingsResolver.js +52 -0
  126. package/contentEntry/ContentEntryBindingsResolver.js.map +1 -0
  127. package/contentEntry/ContentEntryCache.d.ts +49 -0
  128. package/contentEntry/ContentEntryCache.js +51 -0
  129. package/contentEntry/ContentEntryCache.js.map +1 -0
  130. package/contentEntry/resolveContentEntry.d.ts +74 -0
  131. package/contentEntry/resolveContentEntry.js +53 -0
  132. package/contentEntry/resolveContentEntry.js.map +1 -0
  133. package/contentEntry/resolveContentEntry.test.d.ts +1 -0
  134. package/contentEntry/resolveContentEntry.test.js +213 -0
  135. package/contentEntry/resolveContentEntry.test.js.map +1 -0
  136. package/createContentClient.d.ts +17 -0
  137. package/createContentClient.js +16 -0
  138. package/createContentClient.js.map +1 -0
  139. package/createContentClient.test.d.ts +1 -0
  140. package/createContentClient.test.js +165 -0
  141. package/createContentClient.test.js.map +1 -0
  142. package/createGlobalElementDocument.d.ts +6 -0
  143. package/createGlobalElementDocument.js +23 -0
  144. package/createGlobalElementDocument.js.map +1 -0
  145. package/createInput.d.ts +10 -2
  146. package/createInput.js +8 -1
  147. package/createInput.js.map +1 -1
  148. package/dataProviders/ApiClient.d.ts +3 -0
  149. package/dataProviders/ApiClient.js +23 -5
  150. package/dataProviders/ApiClient.js.map +1 -1
  151. package/dataProviders/ApiClient.test.d.ts +1 -0
  152. package/dataProviders/ApiClient.test.js +116 -0
  153. package/dataProviders/ApiClient.test.js.map +1 -0
  154. package/dataProviders/DefaultDataProvider.d.ts +2 -1
  155. package/dataProviders/DefaultDataProvider.js +12 -0
  156. package/dataProviders/DefaultDataProvider.js.map +1 -1
  157. package/dataProviders/DefaultDataProvider.test.d.ts +1 -0
  158. package/dataProviders/DefaultDataProvider.test.js +81 -0
  159. package/dataProviders/DefaultDataProvider.test.js.map +1 -0
  160. package/dataProviders/GET_LAYOUT_BY_SLUG.d.ts +1 -0
  161. package/dataProviders/GET_LAYOUT_BY_SLUG.js +27 -0
  162. package/dataProviders/GET_LAYOUT_BY_SLUG.js.map +1 -0
  163. package/dataProviders/GET_PAGE_BY_ID.d.ts +1 -1
  164. package/dataProviders/GET_PAGE_BY_ID.js +7 -0
  165. package/dataProviders/GET_PAGE_BY_ID.js.map +1 -1
  166. package/dataProviders/GET_PAGE_BY_PATH.d.ts +1 -1
  167. package/dataProviders/GET_PAGE_BY_PATH.js +7 -0
  168. package/dataProviders/GET_PAGE_BY_PATH.js.map +1 -1
  169. package/dataProviders/NullDataProvider.d.ts +2 -1
  170. package/dataProviders/NullDataProvider.js +3 -0
  171. package/dataProviders/NullDataProvider.js.map +1 -1
  172. package/dataProviders/queries.test.d.ts +1 -0
  173. package/dataProviders/queries.test.js +53 -0
  174. package/dataProviders/queries.test.js.map +1 -0
  175. package/experiments/render.d.ts +3 -0
  176. package/experiments/render.js +1 -1
  177. package/experiments/render.js.map +1 -1
  178. package/globalElements.d.ts +43 -0
  179. package/globalElements.js +79 -0
  180. package/globalElements.js.map +1 -0
  181. package/globalElements.test.d.ts +1 -0
  182. package/globalElements.test.js +343 -0
  183. package/globalElements.test.js.map +1 -0
  184. package/headersProvider.d.ts +1 -2
  185. package/headersProvider.js.map +1 -1
  186. package/index.d.ts +14 -0
  187. package/index.js +14 -0
  188. package/messages.d.ts +3 -0
  189. package/messages.js +4 -1
  190. package/messages.js.map +1 -1
  191. package/package.json +10 -10
  192. package/radioOptionInputs.d.ts +24 -0
  193. package/radioOptionInputs.js +26 -0
  194. package/radioOptionInputs.js.map +1 -0
  195. package/types.d.ts +159 -7
  196. package/withGlobalElementDefaults.d.ts +8 -0
  197. package/withGlobalElementDefaults.js +60 -0
  198. package/withGlobalElementDefaults.js.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createContentClient.test.js","sources":["../src/createContentClient.test.ts"],"sourcesContent":["import { describe, it, expect, beforeEach, afterEach, vi } from \"vitest\";\nimport { createContentClient } from \"./createContentClient.js\";\nimport { contentSdk } from \"./ContentSdk.js\";\n\ninterface RecordedRequest {\n url: string;\n tenant: string;\n authorization: string;\n path: string;\n}\n\nconst pageResponse = (path: string) => {\n return {\n data: {\n websiteBuilder: {\n getPageByPath: {\n data: { id: `page:${path}`, properties: { id: `page:${path}`, path } },\n error: null\n }\n }\n }\n };\n};\n\ndescribe(\"createContentClient\", () => {\n let requests: RecordedRequest[];\n let delays: Record<string, number>;\n\n beforeEach(() => {\n requests = [];\n delays = {};\n\n const fetchMock = vi.fn(async (url: string, init: RequestInit) => {\n const headers = init.headers as Record<string, string>;\n const body = JSON.parse(init.body as string);\n const path: string = body.variables.path;\n requests.push({\n url,\n tenant: headers[\"X-Tenant\"],\n authorization: headers[\"Authorization\"],\n path\n });\n\n const delay = delays[path] ?? 0;\n await new Promise(resolve => setTimeout(resolve, delay));\n\n return { json: async () => pageResponse(path) };\n });\n\n vi.stubGlobal(\"fetch\", fetchMock);\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n });\n\n it(\"sends each client's own tenant, host and key\", async () => {\n const clientA = createContentClient({\n apiHost: \"https://a.example.com\",\n apiKey: \"key-a\",\n apiTenant: \"tenant-a\"\n });\n const clientB = createContentClient({\n apiHost: \"https://b.example.com\",\n apiKey: \"key-b\",\n apiTenant: \"tenant-b\"\n });\n\n await clientA.getPage(\"/a\");\n await clientB.getPage(\"/b\");\n\n expect(requests).toEqual([\n {\n url: \"https://a.example.com/graphql\",\n tenant: \"tenant-a\",\n authorization: \"Bearer key-a\",\n path: \"/a\"\n },\n {\n url: \"https://b.example.com/graphql\",\n tenant: \"tenant-b\",\n authorization: \"Bearer key-b\",\n path: \"/b\"\n }\n ]);\n });\n\n it(\"keeps clients isolated when their calls interleave\", async () => {\n const clientA = createContentClient({\n apiHost: \"https://a.example.com\",\n apiKey: \"key-a\",\n apiTenant: \"tenant-a\"\n });\n const clientB = createContentClient({\n apiHost: \"https://b.example.com\",\n apiKey: \"key-b\",\n apiTenant: \"tenant-b\"\n });\n\n // The first request to start is the last to finish.\n delays[\"/a\"] = 20;\n delays[\"/b\"] = 0;\n\n const [pageA, pageB] = await Promise.all([clientA.getPage(\"/a\"), clientB.getPage(\"/b\")]);\n\n expect(pageA?.properties.path).toBe(\"/a\");\n expect(pageB?.properties.path).toBe(\"/b\");\n\n const requestA = requests.find(request => request.path === \"/a\");\n const requestB = requests.find(request => request.path === \"/b\");\n\n expect(requestA).toMatchObject({\n url: \"https://a.example.com/graphql\",\n tenant: \"tenant-a\",\n authorization: \"Bearer key-a\"\n });\n expect(requestB).toMatchObject({\n url: \"https://b.example.com/graphql\",\n tenant: \"tenant-b\",\n authorization: \"Bearer key-b\"\n });\n });\n\n it(\"does not change what the contentSdk singleton sends, and init() does not change a client\", async () => {\n contentSdk.init({\n apiHost: \"https://singleton.example.com\",\n apiKey: \"key-singleton\",\n apiTenant: \"root\"\n });\n\n const client = createContentClient({\n apiHost: \"https://client.example.com\",\n apiKey: \"key-client\",\n apiTenant: \"tenant-client\"\n });\n\n await contentSdk.getPage(\"/singleton\");\n\n contentSdk.init({\n apiHost: \"https://singleton-2.example.com\",\n apiKey: \"key-singleton-2\",\n apiTenant: \"root-2\"\n });\n\n await client.getPage(\"/client\");\n await contentSdk.getPage(\"/singleton-2\");\n\n expect(requests).toEqual([\n {\n url: \"https://singleton.example.com/graphql\",\n tenant: \"root\",\n authorization: \"Bearer key-singleton\",\n path: \"/singleton\"\n },\n {\n url: \"https://client.example.com/graphql\",\n tenant: \"tenant-client\",\n authorization: \"Bearer key-client\",\n path: \"/client\"\n },\n {\n url: \"https://singleton-2.example.com/graphql\",\n tenant: \"root-2\",\n authorization: \"Bearer key-singleton-2\",\n path: \"/singleton-2\"\n }\n ]);\n });\n\n it(\"keeps the preview flag per client\", () => {\n const live = createContentClient({\n apiHost: \"https://a.example.com\",\n apiKey: \"key-a\",\n apiTenant: \"tenant-a\"\n });\n const preview = createContentClient({\n apiHost: \"https://a.example.com\",\n apiKey: \"key-a\",\n apiTenant: \"tenant-a\",\n preview: true,\n previewParams: \"wb.type=page&wb.path=/a&wb.id=page-1\"\n });\n\n expect(live.isPreviewing()).toBe(false);\n expect(preview.isPreviewing()).toBe(true);\n });\n});\n"],"names":["pageResponse","path","describe","requests","delays","beforeEach","fetchMock","vi","url","init","headers","body","JSON","delay","Promise","resolve","setTimeout","afterEach","it","clientA","createContentClient","clientB","expect","pageA","pageB","requestA","request","requestB","contentSdk","client","live","preview"],"mappings":";;;AAWA,MAAMA,eAAe,CAACC,OACX;QACH,MAAM;YACF,gBAAgB;gBACZ,eAAe;oBACX,MAAM;wBAAE,IAAI,CAAC,KAAK,EAAEA,MAAM;wBAAE,YAAY;4BAAE,IAAI,CAAC,KAAK,EAAEA,MAAM;4BAAEA;wBAAK;oBAAE;oBACrE,OAAO;gBACX;YACJ;QACJ;IACJ;AAGJC,SAAS,uBAAuB;IAC5B,IAAIC;IACJ,IAAIC;IAEJC,WAAW;QACPF,WAAW,EAAE;QACbC,SAAS,CAAC;QAEV,MAAME,YAAYC,GAAG,EAAE,CAAC,OAAOC,KAAaC;YACxC,MAAMC,UAAUD,KAAK,OAAO;YAC5B,MAAME,OAAOC,KAAK,KAAK,CAACH,KAAK,IAAI;YACjC,MAAMR,OAAeU,KAAK,SAAS,CAAC,IAAI;YACxCR,SAAS,IAAI,CAAC;gBACVK;gBACA,QAAQE,OAAO,CAAC,WAAW;gBAC3B,eAAeA,OAAO,CAAC,gBAAgB;gBACvCT;YACJ;YAEA,MAAMY,QAAQT,MAAM,CAACH,KAAK,IAAI;YAC9B,MAAM,IAAIa,QAAQC,CAAAA,UAAWC,WAAWD,SAASF;YAEjD,OAAO;gBAAE,MAAM,UAAYb,aAAaC;YAAM;QAClD;QAEAM,GAAG,UAAU,CAAC,SAASD;IAC3B;IAEAW,UAAU;QACNV,GAAG,gBAAgB;IACvB;IAEAW,GAAG,gDAAgD;QAC/C,MAAMC,UAAUC,oBAAoB;YAChC,SAAS;YACT,QAAQ;YACR,WAAW;QACf;QACA,MAAMC,UAAUD,oBAAoB;YAChC,SAAS;YACT,QAAQ;YACR,WAAW;QACf;QAEA,MAAMD,QAAQ,OAAO,CAAC;QACtB,MAAME,QAAQ,OAAO,CAAC;QAEtBC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;QAEzBN,OAAOnB,UAAU,OAAO,CAAC;YACrB;gBACI,KAAK;gBACL,QAAQ;gBACR,eAAe;gBACf,MAAM;YACV;YACA;gBACI,KAAK;gBACL,QAAQ;gBACR,eAAe;gBACf,MAAM;YACV;YACA;gBACI,KAAK;gBACL,QAAQ;gBACR,eAAe;gBACf,MAAM;YACV;SACH;IACL;IAEAe,GAAG,qCAAqC;QACpC,MAAMY,OAAOV,oBAAoB;YAC7B,SAAS;YACT,QAAQ;YACR,WAAW;QACf;QACA,MAAMW,UAAUX,oBAAoB;YAChC,SAAS;YACT,QAAQ;YACR,WAAW;YACX,SAAS;YACT,eAAe;QACnB;QAEAE,OAAOQ,KAAK,YAAY,IAAI,IAAI,CAAC;QACjCR,OAAOS,QAAQ,YAAY,IAAI,IAAI,CAAC;IACxC;AACJ"}
@@ -0,0 +1,6 @@
1
+ import type { ComponentManifest, GlobalDocument } from "./types.js";
2
+ /**
3
+ * Build the default instance of a global component (element + bindings) from its manifest defaults.
4
+ * Used when a global exists in code but has no stored instance yet.
5
+ */
6
+ export declare const createGlobalElementDocument: (componentName: string, components: Record<string, ComponentManifest>) => GlobalDocument;
@@ -0,0 +1,23 @@
1
+ import { ElementFactory } from "./ElementFactory.js";
2
+ const createDefaultIdGenerator = (componentName)=>{
3
+ const name = componentName.replace(/[^a-zA-Z0-9]/gu, (char)=>`_${char.codePointAt(0).toString(16)}_`);
4
+ const prefix = `global-${name}`;
5
+ let counter = 0;
6
+ return ()=>`${prefix}-${++counter}`;
7
+ };
8
+ const createGlobalElementDocument = (componentName, components)=>{
9
+ const factory = new ElementFactory(components, createDefaultIdGenerator(componentName));
10
+ const { operations } = factory.createGlobalElement(componentName);
11
+ const document = {
12
+ elements: {},
13
+ bindings: {}
14
+ };
15
+ operations.forEach((operation)=>operation.apply(document));
16
+ return {
17
+ elements: document.elements,
18
+ bindings: document.bindings
19
+ };
20
+ };
21
+ export { createGlobalElementDocument };
22
+
23
+ //# sourceMappingURL=createGlobalElementDocument.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createGlobalElementDocument.js","sources":["../src/createGlobalElementDocument.ts"],"sourcesContent":["import type { ComponentManifest, Document, GlobalDocument } from \"./types.js\";\nimport { ElementFactory } from \"./ElementFactory.js\";\n\n/**\n * Ids for the elements and bindings of a default global instance. They are derived from the component\n * name, so every build of the same defaults yields the same ids: the server render and the client\n * hydration agree, and re-renders don't remount the global's children. The hyphens keep them apart\n * from generated ids, which use only lowercase letters and digits.\n * Every other character of the name is escaped as `_<hex code point>_`, so two different names never\n * share a prefix (`Demo/Header` and `Demo-Header` would both collapse to `Demo-Header` otherwise).\n */\nconst createDefaultIdGenerator = (componentName: string) => {\n const name = componentName.replace(/[^a-zA-Z0-9]/gu, char => {\n return `_${char.codePointAt(0)!.toString(16)}_`;\n });\n const prefix = `global-${name}`;\n let counter = 0;\n return () => `${prefix}-${++counter}`;\n};\n\n/**\n * Build the default instance of a global component (element + bindings) from its manifest defaults.\n * Used when a global exists in code but has no stored instance yet.\n */\nexport const createGlobalElementDocument = (\n componentName: string,\n components: Record<string, ComponentManifest>\n): GlobalDocument => {\n const factory = new ElementFactory(components, createDefaultIdGenerator(componentName));\n const { operations } = factory.createGlobalElement(componentName);\n\n const document = { elements: {}, bindings: {} } as Document;\n operations.forEach(operation => operation.apply(document));\n\n return { elements: document.elements, bindings: document.bindings };\n};\n"],"names":["createDefaultIdGenerator","componentName","name","char","prefix","counter","createGlobalElementDocument","components","factory","ElementFactory","operations","document","operation"],"mappings":";AAWA,MAAMA,2BAA2B,CAACC;IAC9B,MAAMC,OAAOD,cAAc,OAAO,CAAC,kBAAkBE,CAAAA,OAC1C,CAAC,CAAC,EAAEA,KAAK,WAAW,CAAC,GAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;IAEnD,MAAMC,SAAS,CAAC,OAAO,EAAEF,MAAM;IAC/B,IAAIG,UAAU;IACd,OAAO,IAAM,GAAGD,OAAO,CAAC,EAAE,EAAEC,SAAS;AACzC;AAMO,MAAMC,8BAA8B,CACvCL,eACAM;IAEA,MAAMC,UAAU,IAAIC,eAAeF,YAAYP,yBAAyBC;IACxE,MAAM,EAAES,UAAU,EAAE,GAAGF,QAAQ,mBAAmB,CAACP;IAEnD,MAAMU,WAAW;QAAE,UAAU,CAAC;QAAG,UAAU,CAAC;IAAE;IAC9CD,WAAW,OAAO,CAACE,CAAAA,YAAaA,UAAU,KAAK,CAACD;IAEhD,OAAO;QAAE,UAAUA,SAAS,QAAQ;QAAE,UAAUA,SAAS,QAAQ;IAAC;AACtE"}
package/createInput.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { TextInput, LongTextInput, NumberInput, BooleanInput, ColorInput, FileInput, LexicalInput, SelectInput, RadioInput, ObjectInput, DateTimeInput, ComponentInput, TagsInput, SlotInput } from "./types.js";
2
- export type InputFactory<Name extends string> = ReturnType<typeof createTextInput<Name>> | ReturnType<typeof createLongTextInput<Name>> | ReturnType<typeof createNumberInput<Name>> | ReturnType<typeof createBooleanInput<Name>> | ReturnType<typeof createColorInput<Name>> | ReturnType<typeof createFileInput<Name>> | ReturnType<typeof createDateInput<Name>> | ReturnType<typeof createLexicalInput<Name>> | ReturnType<typeof createSelectInput<Name>> | ReturnType<typeof createRadioInput<Name>> | ReturnType<typeof createObjectInput<Name>> | ReturnType<typeof createTagsInput<Name>> | ReturnType<typeof createSlotInput<Name>>;
1
+ import type { TextInput, LongTextInput, NumberInput, BooleanInput, ColorInput, FileInput, LexicalInput, SelectInput, RadioInput, ObjectInput, DateTimeInput, ComponentInput, TagsInput, SlotInput, ContentEntryInput } from "./types.js";
2
+ export type InputFactory<Name extends string> = ReturnType<typeof createTextInput<Name>> | ReturnType<typeof createLongTextInput<Name>> | ReturnType<typeof createNumberInput<Name>> | ReturnType<typeof createBooleanInput<Name>> | ReturnType<typeof createColorInput<Name>> | ReturnType<typeof createFileInput<Name>> | ReturnType<typeof createDateInput<Name>> | ReturnType<typeof createLexicalInput<Name>> | ReturnType<typeof createSelectInput<Name>> | ReturnType<typeof createRadioInput<Name>> | ReturnType<typeof createObjectInput<Name>> | ReturnType<typeof createTagsInput<Name>> | ReturnType<typeof createSlotInput<Name>> | ReturnType<typeof createContentEntryInput<Name>>;
3
3
  /**
4
4
  * TypeScript Overload Resolution and Input Factory Design
5
5
  *
@@ -122,4 +122,12 @@ export declare function createSlotInput<TName extends string>(input: {
122
122
  export declare function createSlotInput<TName extends string>(input: Omit<SlotInput, "type" | "name">): SlotInput & {
123
123
  name: TName;
124
124
  };
125
+ export declare function createContentEntryInput<TName extends string>(input: {
126
+ name: TName;
127
+ } & Omit<ContentEntryInput, "type" | "name">): ContentEntryInput & {
128
+ name: TName;
129
+ };
130
+ export declare function createContentEntryInput<TName extends string>(input: Omit<ContentEntryInput, "type" | "name">): ContentEntryInput & {
131
+ name: TName;
132
+ };
125
133
  export declare function createInput(input: ComponentInput): ComponentInput;
package/createInput.js CHANGED
@@ -93,10 +93,17 @@ function createSlotInput(input) {
93
93
  ...input
94
94
  });
95
95
  }
96
+ function createContentEntryInput(input) {
97
+ return createInput({
98
+ type: "contentEntry",
99
+ renderer: "Webiny/ContentEntry",
100
+ ...input
101
+ });
102
+ }
96
103
  function createInput(input) {
97
104
  if (input.onChange) input.onChange = functionConverter.serialize(input.onChange);
98
105
  return input;
99
106
  }
100
- export { createBooleanInput, createColorInput, createDateInput, createFileInput, createInput, createLexicalInput, createLongTextInput, createNumberInput, createObjectInput, createRadioInput, createSelectInput, createSlotInput, createTagsInput, createTextInput };
107
+ export { createBooleanInput, createColorInput, createContentEntryInput, createDateInput, createFileInput, createInput, createLexicalInput, createLongTextInput, createNumberInput, createObjectInput, createRadioInput, createSelectInput, createSlotInput, createTagsInput, createTextInput };
101
108
 
102
109
  //# sourceMappingURL=createInput.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"createInput.js","sources":["../src/createInput.ts"],"sourcesContent":["import type {\n TextInput,\n LongTextInput,\n NumberInput,\n BooleanInput,\n ColorInput,\n FileInput,\n LexicalInput,\n SelectInput,\n RadioInput,\n ObjectInput,\n DateTimeInput,\n ComponentInput,\n TagsInput,\n SlotInput\n} from \"./types.js\";\nimport { functionConverter } from \"~/FunctionConverter.js\";\n\nexport type InputFactory<Name extends string> =\n | ReturnType<typeof createTextInput<Name>>\n | ReturnType<typeof createLongTextInput<Name>>\n | ReturnType<typeof createNumberInput<Name>>\n | ReturnType<typeof createBooleanInput<Name>>\n | ReturnType<typeof createColorInput<Name>>\n | ReturnType<typeof createFileInput<Name>>\n | ReturnType<typeof createDateInput<Name>>\n | ReturnType<typeof createLexicalInput<Name>>\n | ReturnType<typeof createSelectInput<Name>>\n | ReturnType<typeof createRadioInput<Name>>\n | ReturnType<typeof createObjectInput<Name>>\n | ReturnType<typeof createTagsInput<Name>>\n | ReturnType<typeof createSlotInput<Name>>;\n\n/**\n * TypeScript Overload Resolution and Input Factory Design\n *\n * Each input factory (e.g., createTextInput) is defined with two TypeScript overload signatures:\n * 1. One overload requires a `name` property in the input (used for array-based APIs, where inference is needed).\n * 2. The other overload omits the `name` property (used for object-based APIs, where the key provides the name).\n *\n * TypeScript resolves overloads by scanning from top to bottom and picking the first matching signature.\n * The implementation signature uses `any` for the argument, and the return type is unified to match all overloads.\n *\n * In array mode, the `name` must be explicitly provided in the input object, so inference for `TName` works.\n * In object mode, the input does not require a `name` property; instead, the key in the object (e.g., `{ foo: createTextInput({ ... }) }`)\n * provides the name via contextual typing from the consuming function (such as `createComponent`). TypeScript uses this context\n * to resolve the correct type for `TName` even when `name` is omitted from the input.\n *\n * This pattern ensures that all returned input objects are typed as `{ name: TName }`, whether `name` is provided explicitly or inferred,\n * so consumers of these factories do not need to worry about the presence of the `name` property in the result.\n */\n// Text\nexport function createTextInput<TName extends string>(\n input: { name: TName } & Omit<TextInput, \"type\" | \"name\">\n): TextInput & { name: TName };\nexport function createTextInput<TName extends string>(\n input: Omit<TextInput, \"type\" | \"name\">\n): TextInput & { name: TName };\nexport function createTextInput<TName extends string>(input: any): TextInput & { name: TName } {\n return createInput({\n type: \"text\",\n renderer: \"Webiny/Input\",\n ...input\n }) as TextInput & { name: TName };\n}\n\n// Long Text\nexport function createLongTextInput<TName extends string>(\n input: { name: TName } & Omit<LongTextInput, \"type\" | \"name\">\n): LongTextInput & { name: TName };\nexport function createLongTextInput<TName extends string>(\n input: Omit<LongTextInput, \"type\" | \"name\">\n): LongTextInput & { name: TName };\nexport function createLongTextInput<TName extends string>(\n input: any\n): LongTextInput & { name: TName } {\n return createInput({\n type: \"longText\",\n renderer: \"Webiny/Textarea\",\n ...input\n }) as LongTextInput & { name: TName };\n}\n\n// Number\nexport function createNumberInput<TName extends string>(\n input: { name: TName } & Omit<NumberInput, \"type\" | \"name\">\n): NumberInput & { name: TName };\nexport function createNumberInput<TName extends string>(\n input: Omit<NumberInput, \"type\" | \"name\">\n): NumberInput & { name: TName };\nexport function createNumberInput<TName extends string>(input: any): NumberInput & { name: TName } {\n return createInput({\n type: \"number\",\n renderer: \"Webiny/Number\",\n ...input\n }) as NumberInput & { name: TName };\n}\n\n// Boolean\nexport function createBooleanInput<TName extends string>(\n input: { name: TName } & Omit<BooleanInput, \"type\" | \"name\">\n): BooleanInput & { name: TName };\nexport function createBooleanInput<TName extends string>(\n input: Omit<BooleanInput, \"type\" | \"name\">\n): BooleanInput & { name: TName };\nexport function createBooleanInput<TName extends string>(\n input: any\n): BooleanInput & { name: TName } {\n return createInput({\n type: \"boolean\",\n renderer: \"Webiny/Switch\",\n ...input\n }) as BooleanInput & { name: TName };\n}\n\n// Color\nexport function createColorInput<TName extends string>(\n input: { name: TName } & Omit<ColorInput, \"type\" | \"name\">\n): ColorInput & { name: TName };\nexport function createColorInput<TName extends string>(\n input: Omit<ColorInput, \"type\" | \"name\">\n): ColorInput & { name: TName };\nexport function createColorInput<TName extends string>(input: any): ColorInput & { name: TName } {\n return createInput({\n type: \"color\",\n renderer: \"Webiny/ColorPicker\",\n ...input\n }) as ColorInput & { name: TName };\n}\n\n// File\nexport function createFileInput<TName extends string>(\n input: { name: TName } & Omit<FileInput, \"type\" | \"name\">\n): FileInput & { name: TName };\nexport function createFileInput<TName extends string>(\n input: Omit<FileInput, \"type\" | \"name\">\n): FileInput & { name: TName };\nexport function createFileInput<TName extends string>(input: any): FileInput & { name: TName } {\n return createInput({\n type: \"file\",\n renderer: \"Webiny/FileManager\",\n ...input\n }) as FileInput & { name: TName };\n}\n\n// Date\nexport function createDateInput<TName extends string>(\n input: { name: TName } & Omit<DateTimeInput, \"type\" | \"name\">\n): DateTimeInput & { name: TName };\nexport function createDateInput<TName extends string>(\n input: Omit<DateTimeInput, \"type\" | \"name\">\n): DateTimeInput & { name: TName };\nexport function createDateInput<TName extends string>(input: any): DateTimeInput & { name: TName } {\n return createInput({\n type: \"datetime\",\n renderer: \"Webiny/DateTime\",\n ...input\n }) as DateTimeInput & { name: TName };\n}\n\n// Rich Text\nexport function createLexicalInput<TName extends string>(\n input: { name: TName } & Omit<LexicalInput, \"type\" | \"name\">\n): LexicalInput & { name: TName };\nexport function createLexicalInput<TName extends string>(\n input: Omit<LexicalInput, \"type\" | \"name\">\n): LexicalInput & { name: TName };\nexport function createLexicalInput<TName extends string>(\n input: any\n): LexicalInput & { name: TName } {\n return createInput({\n type: \"lexical\",\n renderer: \"Webiny/Lexical\",\n ...input\n }) as LexicalInput & { name: TName };\n}\n\n// Select\nexport function createSelectInput<TName extends string>(\n input: { name: TName } & Omit<SelectInput, \"type\" | \"name\">\n): SelectInput & { name: TName };\nexport function createSelectInput<TName extends string>(\n input: Omit<SelectInput, \"type\" | \"name\">\n): SelectInput & { name: TName };\nexport function createSelectInput<TName extends string>(input: any): SelectInput & { name: TName } {\n return createInput({\n type: \"select\",\n renderer: \"Webiny/Select\",\n ...input\n }) as SelectInput & { name: TName };\n}\n\n// Radio\nexport function createRadioInput<TName extends string>(\n input: { name: TName } & Omit<RadioInput, \"type\" | \"name\">\n): RadioInput & { name: TName };\nexport function createRadioInput<TName extends string>(\n input: Omit<RadioInput, \"type\" | \"name\">\n): RadioInput & { name: TName };\nexport function createRadioInput<TName extends string>(input: any): RadioInput & { name: TName } {\n return createInput({\n type: \"radio\",\n renderer: \"Webiny/RadioGroup\",\n ...input\n }) as RadioInput & { name: TName };\n}\n\n// Object\nexport function createObjectInput<TName extends string>(\n input: { name: TName } & Omit<ObjectInput, \"type\" | \"name\">\n): ObjectInput & { name: TName };\nexport function createObjectInput<TName extends string>(\n input: Omit<ObjectInput, \"type\" | \"name\">\n): ObjectInput & { name: TName };\nexport function createObjectInput<TName extends string>(input: any): ObjectInput & { name: TName } {\n return createInput({\n type: \"object\",\n renderer: \"Webiny/Object\",\n ...input\n }) as ObjectInput & { name: TName };\n}\n\n// Tags\nexport function createTagsInput<TName extends string>(\n input: { name: TName } & Omit<TagsInput, \"type\" | \"name\">\n): TagsInput & { name: TName };\nexport function createTagsInput<TName extends string>(\n input: Omit<TagsInput, \"type\" | \"name\">\n): TagsInput & { name: TName };\nexport function createTagsInput<TName extends string>(input: any): TagsInput & { name: TName } {\n return createInput({\n type: \"text\",\n list: true,\n renderer: \"Webiny/Tags\",\n ...input\n }) as TagsInput & { name: TName };\n}\n\nexport function createSlotInput<TName extends string>(\n input: { name: TName } & Omit<SlotInput, \"type\" | \"name\">\n): SlotInput & { name: TName };\nexport function createSlotInput<TName extends string>(\n input: Omit<SlotInput, \"type\" | \"name\">\n): SlotInput & { name: TName };\nexport function createSlotInput<TName extends string>(input: any): SlotInput & { name: TName } {\n return createInput({\n type: \"slot\",\n list: true,\n renderer: \"Webiny/Slot\",\n defaultValue: [],\n ...input\n }) as SlotInput & { name: TName };\n}\n\n// Implementation\nexport function createInput(input: ComponentInput): ComponentInput {\n if (input.onChange) {\n // @ts-expect-error We don't use this function on the frontend, so this is ok.\n input.onChange = functionConverter.serialize(input.onChange!);\n }\n return input;\n}\n"],"names":["createTextInput","input","createInput","createLongTextInput","createNumberInput","createBooleanInput","createColorInput","createFileInput","createDateInput","createLexicalInput","createSelectInput","createRadioInput","createObjectInput","createT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gBAAsCb,KAAU;IAC5D,OAAOC,YAAY;QACf,MAAM;QACN,MAAM;QACN,UAAU;QACV,cAAc,EAAE;QAChB,GAAGD,KAAK;IACZ;AACJ;AAGO,SAASC,YAAYD,KAAqB;IAC7C,IAAIA,MAAM,QAAQ,EAEdA,MAAM,QAAQ,GAAGc,kBAAkB,SAAS,CAACd,MAAM,QAAQ;IAE/D,OAAOA;AACX"}
1
+ {"version":3,"file":"createInput.js","sources":["../src/createInput.ts"],"sourcesContent":["import type {\n TextInput,\n LongTextInput,\n NumberInput,\n BooleanInput,\n ColorInput,\n FileInput,\n LexicalInput,\n SelectInput,\n RadioInput,\n ObjectInput,\n DateTimeInput,\n ComponentInput,\n TagsInput,\n SlotInput,\n ContentEntryInput\n} from \"./types.js\";\nimport { functionConverter } from \"~/FunctionConverter.js\";\n\nexport type InputFactory<Name extends string> =\n | ReturnType<typeof createTextInput<Name>>\n | ReturnType<typeof createLongTextInput<Name>>\n | ReturnType<typeof createNumberInput<Name>>\n | ReturnType<typeof createBooleanInput<Name>>\n | ReturnType<typeof createColorInput<Name>>\n | ReturnType<typeof createFileInput<Name>>\n | ReturnType<typeof createDateInput<Name>>\n | ReturnType<typeof createLexicalInput<Name>>\n | ReturnType<typeof createSelectInput<Name>>\n | ReturnType<typeof createRadioInput<Name>>\n | ReturnType<typeof createObjectInput<Name>>\n | ReturnType<typeof createTagsInput<Name>>\n | ReturnType<typeof createSlotInput<Name>>\n | ReturnType<typeof createContentEntryInput<Name>>;\n\n/**\n * TypeScript Overload Resolution and Input Factory Design\n *\n * Each input factory (e.g., createTextInput) is defined with two TypeScript overload signatures:\n * 1. One overload requires a `name` property in the input (used for array-based APIs, where inference is needed).\n * 2. The other overload omits the `name` property (used for object-based APIs, where the key provides the name).\n *\n * TypeScript resolves overloads by scanning from top to bottom and picking the first matching signature.\n * The implementation signature uses `any` for the argument, and the return type is unified to match all overloads.\n *\n * In array mode, the `name` must be explicitly provided in the input object, so inference for `TName` works.\n * In object mode, the input does not require a `name` property; instead, the key in the object (e.g., `{ foo: createTextInput({ ... }) }`)\n * provides the name via contextual typing from the consuming function (such as `createComponent`). TypeScript uses this context\n * to resolve the correct type for `TName` even when `name` is omitted from the input.\n *\n * This pattern ensures that all returned input objects are typed as `{ name: TName }`, whether `name` is provided explicitly or inferred,\n * so consumers of these factories do not need to worry about the presence of the `name` property in the result.\n */\n// Text\nexport function createTextInput<TName extends string>(\n input: { name: TName } & Omit<TextInput, \"type\" | \"name\">\n): TextInput & { name: TName };\nexport function createTextInput<TName extends string>(\n input: Omit<TextInput, \"type\" | \"name\">\n): TextInput & { name: TName };\nexport function createTextInput<TName extends string>(input: any): TextInput & { name: TName } {\n return createInput({\n type: \"text\",\n renderer: \"Webiny/Input\",\n ...input\n }) as TextInput & { name: TName };\n}\n\n// Long Text\nexport function createLongTextInput<TName extends string>(\n input: { name: TName } & Omit<LongTextInput, \"type\" | \"name\">\n): LongTextInput & { name: TName };\nexport function createLongTextInput<TName extends string>(\n input: Omit<LongTextInput, \"type\" | \"name\">\n): LongTextInput & { name: TName };\nexport function createLongTextInput<TName extends string>(\n input: any\n): LongTextInput & { name: TName } {\n return createInput({\n type: \"longText\",\n renderer: \"Webiny/Textarea\",\n ...input\n }) as LongTextInput & { name: TName };\n}\n\n// Number\nexport function createNumberInput<TName extends string>(\n input: { name: TName } & Omit<NumberInput, \"type\" | \"name\">\n): NumberInput & { name: TName };\nexport function createNumberInput<TName extends string>(\n input: Omit<NumberInput, \"type\" | \"name\">\n): NumberInput & { name: TName };\nexport function createNumberInput<TName extends string>(input: any): NumberInput & { name: TName } {\n return createInput({\n type: \"number\",\n renderer: \"Webiny/Number\",\n ...input\n }) as NumberInput & { name: TName };\n}\n\n// Boolean\nexport function createBooleanInput<TName extends string>(\n input: { name: TName } & Omit<BooleanInput, \"type\" | \"name\">\n): BooleanInput & { name: TName };\nexport function createBooleanInput<TName extends string>(\n input: Omit<BooleanInput, \"type\" | \"name\">\n): BooleanInput & { name: TName };\nexport function createBooleanInput<TName extends string>(\n input: any\n): BooleanInput & { name: TName } {\n return createInput({\n type: \"boolean\",\n renderer: \"Webiny/Switch\",\n ...input\n }) as BooleanInput & { name: TName };\n}\n\n// Color\nexport function createColorInput<TName extends string>(\n input: { name: TName } & Omit<ColorInput, \"type\" | \"name\">\n): ColorInput & { name: TName };\nexport function createColorInput<TName extends string>(\n input: Omit<ColorInput, \"type\" | \"name\">\n): ColorInput & { name: TName };\nexport function createColorInput<TName extends string>(input: any): ColorInput & { name: TName } {\n return createInput({\n type: \"color\",\n renderer: \"Webiny/ColorPicker\",\n ...input\n }) as ColorInput & { name: TName };\n}\n\n// File\nexport function createFileInput<TName extends string>(\n input: { name: TName } & Omit<FileInput, \"type\" | \"name\">\n): FileInput & { name: TName };\nexport function createFileInput<TName extends string>(\n input: Omit<FileInput, \"type\" | \"name\">\n): FileInput & { name: TName };\nexport function createFileInput<TName extends string>(input: any): FileInput & { name: TName } {\n return createInput({\n type: \"file\",\n renderer: \"Webiny/FileManager\",\n ...input\n }) as FileInput & { name: TName };\n}\n\n// Date\nexport function createDateInput<TName extends string>(\n input: { name: TName } & Omit<DateTimeInput, \"type\" | \"name\">\n): DateTimeInput & { name: TName };\nexport function createDateInput<TName extends string>(\n input: Omit<DateTimeInput, \"type\" | \"name\">\n): DateTimeInput & { name: TName };\nexport function createDateInput<TName extends string>(input: any): DateTimeInput & { name: TName } {\n return createInput({\n type: \"datetime\",\n renderer: \"Webiny/DateTime\",\n ...input\n }) as DateTimeInput & { name: TName };\n}\n\n// Rich Text\nexport function createLexicalInput<TName extends string>(\n input: { name: TName } & Omit<LexicalInput, \"type\" | \"name\">\n): LexicalInput & { name: TName };\nexport function createLexicalInput<TName extends string>(\n input: Omit<LexicalInput, \"type\" | \"name\">\n): LexicalInput & { name: TName };\nexport function createLexicalInput<TName extends string>(\n input: any\n): LexicalInput & { name: TName } {\n return createInput({\n type: \"lexical\",\n renderer: \"Webiny/Lexical\",\n ...input\n }) as LexicalInput & { name: TName };\n}\n\n// Select\nexport function createSelectInput<TName extends string>(\n input: { name: TName } & Omit<SelectInput, \"type\" | \"name\">\n): SelectInput & { name: TName };\nexport function createSelectInput<TName extends string>(\n input: Omit<SelectInput, \"type\" | \"name\">\n): SelectInput & { name: TName };\nexport function createSelectInput<TName extends string>(input: any): SelectInput & { name: TName } {\n return createInput({\n type: \"select\",\n renderer: \"Webiny/Select\",\n ...input\n }) as SelectInput & { name: TName };\n}\n\n// Radio\nexport function createRadioInput<TName extends string>(\n input: { name: TName } & Omit<RadioInput, \"type\" | \"name\">\n): RadioInput & { name: TName };\nexport function createRadioInput<TName extends string>(\n input: Omit<RadioInput, \"type\" | \"name\">\n): RadioInput & { name: TName };\nexport function createRadioInput<TName extends string>(input: any): RadioInput & { name: TName } {\n return createInput({\n type: \"radio\",\n renderer: \"Webiny/RadioGroup\",\n ...input\n }) as RadioInput & { name: TName };\n}\n\n// Object\nexport function createObjectInput<TName extends string>(\n input: { name: TName } & Omit<ObjectInput, \"type\" | \"name\">\n): ObjectInput & { name: TName };\nexport function createObjectInput<TName extends string>(\n input: Omit<ObjectInput, \"type\" | \"name\">\n): ObjectInput & { name: TName };\nexport function createObjectInput<TName extends string>(input: any): ObjectInput & { name: TName } {\n return createInput({\n type: \"object\",\n renderer: \"Webiny/Object\",\n ...input\n }) as ObjectInput & { name: TName };\n}\n\n// Tags\nexport function createTagsInput<TName extends string>(\n input: { name: TName } & Omit<TagsInput, \"type\" | \"name\">\n): TagsInput & { name: TName };\nexport function createTagsInput<TName extends string>(\n input: Omit<TagsInput, \"type\" | \"name\">\n): TagsInput & { name: TName };\nexport function createTagsInput<TName extends string>(input: any): TagsInput & { name: TName } {\n return createInput({\n type: \"text\",\n list: true,\n renderer: \"Webiny/Tags\",\n ...input\n }) as TagsInput & { name: TName };\n}\n\nexport function createSlotInput<TName extends string>(\n input: { name: TName } & Omit<SlotInput, \"type\" | \"name\">\n): SlotInput & { name: TName };\nexport function createSlotInput<TName extends string>(\n input: Omit<SlotInput, \"type\" | \"name\">\n): SlotInput & { name: TName };\nexport function createSlotInput<TName extends string>(input: any): SlotInput & { name: TName } {\n return createInput({\n type: \"slot\",\n list: true,\n renderer: \"Webiny/Slot\",\n defaultValue: [],\n ...input\n }) as SlotInput & { name: TName };\n}\n\n// Content Entry\nexport function createContentEntryInput<TName extends string>(\n input: { name: TName } & Omit<ContentEntryInput, \"type\" | \"name\">\n): ContentEntryInput & { name: TName };\nexport function createContentEntryInput<TName extends string>(\n input: Omit<ContentEntryInput, \"type\" | \"name\">\n): ContentEntryInput & { name: TName };\nexport function createContentEntryInput<TName extends string>(\n input: any\n): ContentEntryInput & { name: TName } {\n return createInput({\n type: \"contentEntry\",\n renderer: \"Webiny/ContentEntry\",\n ...input\n }) as ContentEntryInput & { name: TName };\n}\n\n// Implementation\nexport function createInput(input: ComponentInput): ComponentInput {\n if (input.onChange) {\n // @ts-expect-error We don't use this function on the frontend, so this is ok.\n input.onChange = functionConverter.serialize(input.onChange!);\n }\n return input;\n}\n"],"names":["createTextInput","input","createInput","createLongTextInput","createNumberInput","createBooleanInput","createColorInput","createFileInput","createDateInput","createLexicalInput","createSelectInput","createRadioInput","createObjectInput","createTagsInput","createSlotInput","createContentEntryInput","functionConverter"],"mappings":";AA4DO,SAASA,gBAAsCC,KAAU;IAC5D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASE,oBACZF,KAAU;IAEV,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASG,kBAAwCH,KAAU;IAC9D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASI,mBACZJ,KAAU;IAEV,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASK,iBAAuCL,KAAU;IAC7D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASM,gBAAsCN,KAAU;IAC5D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASO,gBAAsCP,KAAU;IAC5D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASQ,mBACZR,KAAU;IAEV,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASS,kBAAwCT,KAAU;IAC9D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASU,iBAAuCV,KAAU;IAC7D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASW,kBAAwCX,KAAU;IAC9D,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AASO,SAASY,gBAAsCZ,KAAU;IAC5D,OAAOC,YAAY;QACf,MAAM;QACN,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AAQO,SAASa,gBAAsCb,KAAU;IAC5D,OAAOC,YAAY;QACf,MAAM;QACN,MAAM;QACN,UAAU;QACV,cAAc,EAAE;QAChB,GAAGD,KAAK;IACZ;AACJ;AASO,SAASc,wBACZd,KAAU;IAEV,OAAOC,YAAY;QACf,MAAM;QACN,UAAU;QACV,GAAGD,KAAK;IACZ;AACJ;AAGO,SAASC,YAAYD,KAAqB;IAC7C,IAAIA,MAAM,QAAQ,EAEdA,MAAM,QAAQ,GAAGe,kBAAkB,SAAS,CAACf,MAAM,QAAQ;IAE/D,OAAOA;AACX"}
@@ -1,3 +1,4 @@
1
+ import { type HeadersConfig } from "@webiny/sdk";
1
2
  interface QueryParams {
2
3
  query: string;
3
4
  variables: Record<string, any>;
@@ -6,6 +7,8 @@ export interface ApiClientConfig {
6
7
  apiHost: string;
7
8
  apiKey: string;
8
9
  apiTenant: string;
10
+ /** Extra headers sent with every request; a function is called before each request. */
11
+ headers?: HeadersConfig;
9
12
  preview?: boolean;
10
13
  }
11
14
  type WithPath<T> = T & {
@@ -1,3 +1,21 @@
1
+ import { resolveHeaders } from "@webiny/sdk";
2
+ const PROTECTED_HEADERS = [
3
+ "x-tenant",
4
+ "authorization"
5
+ ];
6
+ function headerEntries(headers) {
7
+ if (!headers) return [];
8
+ if (headers instanceof Headers) return Array.from(headers.entries());
9
+ return Array.isArray(headers) ? headers : Object.entries(headers);
10
+ }
11
+ function mergeHeaders(...sources) {
12
+ const merged = new Map();
13
+ for (const source of sources)for (const [name, value] of headerEntries(source))merged.set(name.toLowerCase(), [
14
+ name,
15
+ value
16
+ ]);
17
+ return Object.fromEntries(merged.values());
18
+ }
1
19
  class ApiClient {
2
20
  constructor(config){
3
21
  this.config = config;
@@ -5,12 +23,12 @@ class ApiClient {
5
23
  async fetch({ headers, path, ...params }) {
6
24
  return fetch(`${this.config.apiHost}${path}`, {
7
25
  method: "GET",
8
- headers: {
9
- "Content-Type": "application/json",
26
+ headers: mergeHeaders({
27
+ "Content-Type": "application/json"
28
+ }, headerEntries(await resolveHeaders(this.config.headers)).filter(([name])=>!PROTECTED_HEADERS.includes(name.toLowerCase())), {
10
29
  "X-Tenant": this.config.apiTenant,
11
- Authorization: "Bearer " + this.config.apiKey,
12
- ...headers
13
- },
30
+ Authorization: "Bearer " + this.config.apiKey
31
+ }, headers),
14
32
  ...params
15
33
  }).then((res)=>res.json());
16
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"dataProviders/ApiClient.js","sources":["../../src/dataProviders/ApiClient.ts"],"sourcesContent":["interface QueryParams {\n query: string;\n variables: Record<string, any>;\n}\n\nexport interface ApiClientConfig {\n apiHost: string;\n apiKey: string;\n apiTenant: string;\n preview?: boolean;\n}\n\ntype WithPath<T> = T & {\n path?: string;\n next?: Record<string, any>;\n};\n\nexport class ApiClient {\n private readonly config: ApiClientConfig;\n\n constructor(config: ApiClientConfig) {\n this.config = config;\n }\n\n async fetch({ headers, path, ...params }: WithPath<RequestInit>): Promise<any> {\n return fetch(`${this.config.apiHost}${path}`, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Tenant\": this.config.apiTenant,\n Authorization: \"Bearer \" + this.config.apiKey,\n ...headers\n },\n ...params\n }).then(res => res.json());\n }\n\n async query({ query, variables }: QueryParams, options?: { noStore?: boolean }) {\n // Runtime reads (e.g. the experiment kill-switch) must bypass the cache so they take\n // effect immediately; everything else caches and revalidates on an interval.\n const fetchOptions: Pick<WithPath<RequestInit>, \"cache\" | \"next\"> = options?.noStore\n ? { cache: \"no-store\" }\n : { next: { revalidate: this.config.preview ? 0 : 60 } };\n\n const request: WithPath<RequestInit> = {\n ...fetchOptions,\n path: \"/graphql\",\n method: \"POST\",\n body: JSON.stringify({\n query,\n variables\n })\n };\n\n const json = await this.fetch(request);\n\n if (json.message) {\n throw new Error(json.message);\n }\n\n if (json.errors) {\n console.error(json.errors);\n throw new Error(\"Failed to fetch API\");\n }\n\n return json.data;\n }\n}\n"],"names":["ApiClient","config","headers","path","params","fetch","res","query","variables","options","fetchOptions","request","JSON","json","Error","console"],"mappings":"AAiBO,MAAMA;IAGT,YAAYC,MAAuB,CAAE;QACjC,IAAI,CAAC,MAAM,GAAGA;IAClB;IAEA,MAAM,MAAM,EAAEC,OAAO,EAAEC,IAAI,EAAE,GAAGC,QAA+B,EAAgB;QAC3E,OAAOC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,GAAGF,MAAM,EAAE;YAC1C,QAAQ;YACR,SAAS;gBACL,gBAAgB;gBAChB,YAAY,IAAI,CAAC,MAAM,CAAC,SAAS;gBACjC,eAAe,YAAY,IAAI,CAAC,MAAM,CAAC,MAAM;gBAC7C,GAAGD,OAAO;YACd;YACA,GAAGE,MAAM;QACb,GAAG,IAAI,CAACE,CAAAA,MAAOA,IAAI,IAAI;IAC3B;IAEA,MAAM,MAAM,EAAEC,KAAK,EAAEC,SAAS,EAAe,EAAEC,OAA+B,EAAE;QAG5E,MAAMC,eAA8DD,SAAS,UACvE;YAAE,OAAO;QAAW,IACpB;YAAE,MAAM;gBAAE,YAAY,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,IAAI;YAAG;QAAE;QAE3D,MAAME,UAAiC;YACnC,GAAGD,YAAY;YACf,MAAM;YACN,QAAQ;YACR,MAAME,KAAK,SAAS,CAAC;gBACjBL;gBACAC;YACJ;QACJ;QAEA,MAAMK,OAAO,MAAM,IAAI,CAAC,KAAK,CAACF;QAE9B,IAAIE,KAAK,OAAO,EACZ,MAAM,IAAIC,MAAMD,KAAK,OAAO;QAGhC,IAAIA,KAAK,MAAM,EAAE;YACbE,QAAQ,KAAK,CAACF,KAAK,MAAM;YACzB,MAAM,IAAIC,MAAM;QACpB;QAEA,OAAOD,KAAK,IAAI;IACpB;AACJ"}
1
+ {"version":3,"file":"dataProviders/ApiClient.js","sources":["../../src/dataProviders/ApiClient.ts"],"sourcesContent":["import { resolveHeaders, type HeadersConfig } from \"@webiny/sdk\";\n\ninterface QueryParams {\n query: string;\n variables: Record<string, any>;\n}\n\nexport interface ApiClientConfig {\n apiHost: string;\n apiKey: string;\n apiTenant: string;\n /** Extra headers sent with every request; a function is called before each request. */\n headers?: HeadersConfig;\n preview?: boolean;\n}\n\ntype WithPath<T> = T & {\n path?: string;\n next?: Record<string, any>;\n};\n\n// Set by the client itself: configured extra headers can't replace them.\nconst PROTECTED_HEADERS = [\"x-tenant\", \"authorization\"];\n\nfunction headerEntries(headers: HeadersInit | undefined): [string, string][] {\n if (!headers) {\n return [];\n }\n if (headers instanceof Headers) {\n return Array.from(headers.entries());\n }\n return Array.isArray(headers) ? (headers as [string, string][]) : Object.entries(headers);\n}\n\n/**\n * The headers of several sources, a later one's value replacing an earlier one's whatever the case of the\n * name (header names are case-insensitive; `fetch` would otherwise send both values, joined).\n */\nfunction mergeHeaders(...sources: Array<HeadersInit | undefined>): Record<string, string> {\n const merged = new Map<string, [string, string]>();\n for (const source of sources) {\n for (const [name, value] of headerEntries(source)) {\n merged.set(name.toLowerCase(), [name, value]);\n }\n }\n return Object.fromEntries(merged.values());\n}\n\nexport class ApiClient {\n private readonly config: ApiClientConfig;\n\n constructor(config: ApiClientConfig) {\n this.config = config;\n }\n\n async fetch({ headers, path, ...params }: WithPath<RequestInit>): Promise<any> {\n return fetch(`${this.config.apiHost}${path}`, {\n method: \"GET\",\n headers: mergeHeaders(\n { \"Content-Type\": \"application/json\" },\n // Under the tenant and the API key: extra headers can't replace either.\n headerEntries(await resolveHeaders(this.config.headers)).filter(\n ([name]) => !PROTECTED_HEADERS.includes(name.toLowerCase())\n ),\n {\n \"X-Tenant\": this.config.apiTenant,\n Authorization: \"Bearer \" + this.config.apiKey\n },\n headers\n ),\n ...params\n }).then(res => res.json());\n }\n\n async query({ query, variables }: QueryParams, options?: { noStore?: boolean }) {\n // Runtime reads (e.g. the experiment kill-switch) must bypass the cache so they take\n // effect immediately; everything else caches and revalidates on an interval.\n const fetchOptions: Pick<WithPath<RequestInit>, \"cache\" | \"next\"> = options?.noStore\n ? { cache: \"no-store\" }\n : { next: { revalidate: this.config.preview ? 0 : 60 } };\n\n const request: WithPath<RequestInit> = {\n ...fetchOptions,\n path: \"/graphql\",\n method: \"POST\",\n body: JSON.stringify({\n query,\n variables\n })\n };\n\n const json = await this.fetch(request);\n\n if (json.message) {\n throw new Error(json.message);\n }\n\n if (json.errors) {\n console.error(json.errors);\n throw new Error(\"Failed to fetch API\");\n }\n\n return json.data;\n }\n}\n"],"names":["PROTECTED_HEADERS","headerEntries","headers","Headers","Array","Object","mergeHeaders","sources","merged","Map","source","name","value","ApiClient","config","path","params","fetch","resolveHeaders","res","query","variables","options","fetchOptions","request","JSON","json","Error","console"],"mappings":";AAsBA,MAAMA,oBAAoB;IAAC;IAAY;CAAgB;AAEvD,SAASC,cAAcC,OAAgC;IACnD,IAAI,CA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3D,MAAME,UAAiC;YACnC,GAAGD,YAAY;YACf,MAAM;YACN,QAAQ;YACR,MAAME,KAAK,SAAS,CAAC;gBACjBL;gBACAC;YACJ;QACJ;QAEA,MAAMK,OAAO,MAAM,IAAI,CAAC,KAAK,CAACF;QAE9B,IAAIE,KAAK,OAAO,EACZ,MAAM,IAAIC,MAAMD,KAAK,OAAO;QAGhC,IAAIA,KAAK,MAAM,EAAE;YACbE,QAAQ,KAAK,CAACF,KAAK,MAAM;YACzB,MAAM,IAAIC,MAAM;QACpB;QAEA,OAAOD,KAAK,IAAI;IACpB;AACJ"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,116 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { ApiClient } from "./ApiClient.js";
3
+ const mockFetch = ()=>{
4
+ const fetchMock = vi.fn().mockResolvedValue({
5
+ json: async ()=>({
6
+ data: {}
7
+ })
8
+ });
9
+ vi.stubGlobal("fetch", fetchMock);
10
+ return fetchMock;
11
+ };
12
+ const sentHeaders = (fetchMock, call = 0)=>fetchMock.mock.calls[call][1].headers;
13
+ const config = {
14
+ apiHost: "https://api.test",
15
+ apiKey: "key",
16
+ apiTenant: "root"
17
+ };
18
+ describe("ApiClient headers", ()=>{
19
+ afterEach(()=>{
20
+ vi.unstubAllGlobals();
21
+ });
22
+ it("sends the configured headers with every request", async ()=>{
23
+ const fetchMock = mockFetch();
24
+ const client = new ApiClient({
25
+ ...config,
26
+ headers: {
27
+ "x-extra": "a"
28
+ }
29
+ });
30
+ await client.query({
31
+ query: "{ a }",
32
+ variables: {}
33
+ });
34
+ await client.fetch({
35
+ path: "/wb/redirects"
36
+ });
37
+ expect(sentHeaders(fetchMock, 0)["x-extra"]).toBe("a");
38
+ expect(sentHeaders(fetchMock, 1)["x-extra"]).toBe("a");
39
+ });
40
+ it("calls a headers function before each request", async ()=>{
41
+ const fetchMock = mockFetch();
42
+ let value = "first";
43
+ const client = new ApiClient({
44
+ ...config,
45
+ headers: async ()=>({
46
+ "x-extra": value
47
+ })
48
+ });
49
+ await client.query({
50
+ query: "{ a }",
51
+ variables: {}
52
+ });
53
+ value = "second";
54
+ await client.query({
55
+ query: "{ a }",
56
+ variables: {}
57
+ });
58
+ expect(sentHeaders(fetchMock, 0)["x-extra"]).toBe("first");
59
+ expect(sentHeaders(fetchMock, 1)["x-extra"]).toBe("second");
60
+ });
61
+ it("doesn't let extra headers replace the tenant or the API key", async ()=>{
62
+ const fetchMock = mockFetch();
63
+ const client = new ApiClient({
64
+ ...config,
65
+ headers: {
66
+ "X-Tenant": "other",
67
+ Authorization: "Bearer other"
68
+ }
69
+ });
70
+ await client.query({
71
+ query: "{ a }",
72
+ variables: {}
73
+ });
74
+ expect(sentHeaders(fetchMock)["X-Tenant"]).toBe("root");
75
+ expect(sentHeaders(fetchMock).Authorization).toBe("Bearer key");
76
+ });
77
+ it("doesn't send a configured tenant or API key in another case either", async ()=>{
78
+ const fetchMock = mockFetch();
79
+ const client = new ApiClient({
80
+ ...config,
81
+ headers: {
82
+ "x-tenant": "other",
83
+ authorization: "Bearer other",
84
+ "x-extra": "a"
85
+ }
86
+ });
87
+ await client.query({
88
+ query: "{ a }",
89
+ variables: {}
90
+ });
91
+ expect(sentHeaders(fetchMock)).toMatchObject({
92
+ "X-Tenant": "root",
93
+ Authorization: "Bearer key",
94
+ "x-extra": "a"
95
+ });
96
+ expect(sentHeaders(fetchMock)).not.toHaveProperty("x-tenant");
97
+ expect(sentHeaders(fetchMock)).not.toHaveProperty("authorization");
98
+ });
99
+ it("lets a configured header replace the content type, whatever the case", async ()=>{
100
+ const fetchMock = mockFetch();
101
+ const client = new ApiClient({
102
+ ...config,
103
+ headers: {
104
+ "content-type": "application/graphql+json"
105
+ }
106
+ });
107
+ await client.query({
108
+ query: "{ a }",
109
+ variables: {}
110
+ });
111
+ expect(sentHeaders(fetchMock)["content-type"]).toBe("application/graphql+json");
112
+ expect(sentHeaders(fetchMock)).not.toHaveProperty("Content-Type");
113
+ });
114
+ });
115
+
116
+ //# sourceMappingURL=ApiClient.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataProviders/ApiClient.test.js","sources":["../../src/dataProviders/ApiClient.test.ts"],"sourcesContent":["import { afterEach, describe, expect, it, vi } from \"vitest\";\nimport { ApiClient } from \"./ApiClient.js\";\n\nconst mockFetch = () => {\n const fetchMock = vi.fn().mockResolvedValue({ json: async () => ({ data: {} }) });\n vi.stubGlobal(\"fetch\", fetchMock);\n return fetchMock;\n};\n\nconst sentHeaders = (fetchMock: ReturnType<typeof mockFetch>, call = 0) => {\n return fetchMock.mock.calls[call][1].headers as Record<string, string>;\n};\n\nconst config = {\n apiHost: \"https://api.test\",\n apiKey: \"key\",\n apiTenant: \"root\"\n};\n\ndescribe(\"ApiClient headers\", () => {\n afterEach(() => {\n vi.unstubAllGlobals();\n });\n\n it(\"sends the configured headers with every request\", async () => {\n const fetchMock = mockFetch();\n const client = new ApiClient({ ...config, headers: { \"x-extra\": \"a\" } });\n\n await client.query({ query: \"{ a }\", variables: {} });\n await client.fetch({ path: \"/wb/redirects\" });\n\n expect(sentHeaders(fetchMock, 0)[\"x-extra\"]).toBe(\"a\");\n expect(sentHeaders(fetchMock, 1)[\"x-extra\"]).toBe(\"a\");\n });\n\n it(\"calls a headers function before each request\", async () => {\n const fetchMock = mockFetch();\n let value = \"first\";\n const client = new ApiClient({\n ...config,\n headers: async () => ({ \"x-extra\": value })\n });\n\n await client.query({ query: \"{ a }\", variables: {} });\n value = \"second\";\n await client.query({ query: \"{ a }\", variables: {} });\n\n expect(sentHeaders(fetchMock, 0)[\"x-extra\"]).toBe(\"first\");\n expect(sentHeaders(fetchMock, 1)[\"x-extra\"]).toBe(\"second\");\n });\n\n it(\"doesn't let extra headers replace the tenant or the API key\", async () => {\n const fetchMock = mockFetch();\n const client = new ApiClient({\n ...config,\n headers: { \"X-Tenant\": \"other\", Authorization: \"Bearer other\" }\n });\n\n await client.query({ query: \"{ a }\", variables: {} });\n\n expect(sentHeaders(fetchMock)[\"X-Tenant\"]).toBe(\"root\");\n expect(sentHeaders(fetchMock).Authorization).toBe(\"Bearer key\");\n });\n\n it(\"doesn't send a configured tenant or API key in another case either\", async () => {\n const fetchMock = mockFetch();\n const client = new ApiClient({\n ...config,\n headers: {\n \"x-tenant\": \"other\",\n authorization: \"Bearer other\",\n \"x-extra\": \"a\"\n }\n });\n\n await client.query({ query: \"{ a }\", variables: {} });\n\n expect(sentHeaders(fetchMock)).toMatchObject({\n \"X-Tenant\": \"root\",\n Authorization: \"Bearer key\",\n \"x-extra\": \"a\"\n });\n expect(sentHeaders(fetchMock)).not.toHaveProperty(\"x-tenant\");\n expect(sentHeaders(fetchMock)).not.toHaveProperty(\"authorization\");\n });\n\n it(\"lets a configured header replace the content type, whatever the case\", async () => {\n const fetchMock = mockFetch();\n const client = new ApiClient({\n ...config,\n headers: { \"content-type\": \"application/graphql+json\" }\n });\n\n await client.query({ query: \"{ a }\", variables: {} });\n\n expect(sentHeaders(fetchMock)[\"content-type\"]).toBe(\"application/graphql+json\");\n expect(sentHeaders(fetchMock)).not.toHaveProperty(\"Content-Type\");\n });\n});\n"],"names":["mockFetch","fetchMock","vi","sentHeaders","call","config","describe","afterEach","it","client","ApiClient","expect","value"],"mappings":";;AAGA,MAAMA,YAAY;IACd,MAAMC,YAAYC,GAAG,EAAE,GAAG,iBAAiB,CAAC;QAAE,MAAM,UAAa;gBAAE,MAAM,CAAC;YAAE;IAAG;IAC/EA,GAAG,UAAU,CAAC,SAASD;IACvB,OAAOA;AACX;AAEA,MAAME,cAAc,CAACF,WAAyCG,OAAO,CAAC,GAC3DH,UAAU,IAAI,CAAC,KAAK,CAACG,KAAK,CAAC,EAAE,CAAC,OAAO;AAGhD,MAAMC,SAAS;IACX,SAAS;IACT,QAAQ;IACR,WAAW;AACf;AAEAC,SAAS,qBAAqB;IAC1BC,UAAU;QACNL,GAAG,gBAAgB;IACvB;IAEAM,GAAG,mDAAmD;QAClD,MAAMP,YAAYD;Q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BACZ,eAAe;gBACf,WAAW;YACf;QACJ;QAEA,MAAMI,OAAO,KAAK,CAAC;YAAE,OAAO;YAAS,WAAW,CAAC;QAAE;QAEnDE,OAAOR,YAAYF,YAAY,aAAa,CAAC;YACzC,YAAY;YACZ,eAAe;YACf,WAAW;QACf;QACAU,OAAOR,YAAYF,YAAY,GAAG,CAAC,cAAc,CAAC;QAClDU,OAAOR,YAAYF,YAAY,GAAG,CAAC,cAAc,CAAC;IACtD;IAEAO,GAAG,wEAAwE;QACvE,MAAMP,YAAYD;QAClB,MAAMS,SAAS,IAAIC,UAAU;YACzB,GAAGL,MAAM;YACT,SAAS;gBAAE,gBAAgB;YAA2B;QAC1D;QAEA,MAAMI,OAAO,KAAK,CAAC;YAAE,OAAO;YAAS,WAAW,CAAC;QAAE;QAEnDE,OAAOR,YAAYF,UAAU,CAAC,eAAe,EAAE,IAAI,CAAC;QACpDU,OAAOR,YAAYF,YAAY,GAAG,CAAC,cAAc,CAAC;IACtD;AACJ"}
@@ -1,4 +1,4 @@
1
- import type { IDataProvider, ListPagesOptions, ListPagesResult, PublicPage } from "../types.js";
1
+ import type { GetLayoutParams, IDataProvider, ListPagesOptions, ListPagesResult, PublicLayout, PublicPage } from "../types.js";
2
2
  import type { ActiveExperiment, VariantContent } from "../experiments/types.js";
3
3
  import type { ApiClient } from "../dataProviders/ApiClient.js";
4
4
  interface DefaultDataProviderConfig {
@@ -9,6 +9,7 @@ export declare class DefaultDataProvider implements IDataProvider {
9
9
  constructor(config: DefaultDataProviderConfig);
10
10
  getPageByPath(path: string): Promise<PublicPage | null>;
11
11
  getPageById(id: string): Promise<PublicPage | null>;
12
+ getLayoutBySlug(params: GetLayoutParams): Promise<PublicLayout | null>;
12
13
  listPages(options?: ListPagesOptions): Promise<ListPagesResult>;
13
14
  getPageExperiment(path: string): Promise<ActiveExperiment | null>;
14
15
  getVariantContent(variantId: string): Promise<VariantContent | null>;
@@ -1,5 +1,6 @@
1
1
  import { GET_PAGE_BY_PATH } from "./GET_PAGE_BY_PATH.js";
2
2
  import { GET_PAGE_BY_ID } from "./GET_PAGE_BY_ID.js";
3
+ import { GET_LAYOUT_BY_SLUG } from "./GET_LAYOUT_BY_SLUG.js";
3
4
  import { LIST_PUBLISHED_PAGES } from "./LIST_PUBLISHED_PAGES.js";
4
5
  import { GET_PAGE_EXPERIMENT } from "./GET_PAGE_EXPERIMENT.js";
5
6
  import { GET_VARIANT_CONTENT } from "./GET_VARIANT_CONTENT.js";
@@ -32,6 +33,17 @@ class DefaultDataProvider {
32
33
  this.checkForErrors("getPageById", result.websiteBuilder.getPageById);
33
34
  return result.websiteBuilder.getPageById.data;
34
35
  }
36
+ async getLayoutBySlug(params) {
37
+ const result = await this.config.apiClient.query({
38
+ query: GET_LAYOUT_BY_SLUG,
39
+ variables: {
40
+ slug: params.slug,
41
+ language: params.language ?? null
42
+ }
43
+ });
44
+ this.checkForErrors(`getLayoutBySlug:${params.slug}`, result.websiteBuilder.getLayoutBySlug);
45
+ return result.websiteBuilder.getLayoutBySlug.data ?? null;
46
+ }
35
47
  async listPages(options) {
36
48
  const { where, ...rest } = options ?? {};
37
49
  const result = await this.config.apiClient.query({
@@ -1 +1 @@
1
- {"version":3,"file":"dataProviders/DefaultDataProvider.js","sources":["../../src/dataProviders/DefaultDataProvider.ts"],"sourcesContent":["import type { IDataProvider, ListPagesOptions, ListPagesResult, PublicPage } from \"~/types.js\";\nimport type { ActiveExperiment, VariantContent } from \"~/experiments/types.js\";\nimport type { ApiClient } from \"~/dataProviders/ApiClient.js\";\nimport { GET_PAGE_BY_PATH } from \"./GET_PAGE_BY_PATH.js\";\nimport { GET_PAGE_BY_ID } from \"./GET_PAGE_BY_ID.js\";\nimport { LIST_PUBLISHED_PAGES } from \"./LIST_PUBLISHED_PAGES.js\";\nimport { GET_PAGE_EXPERIMENT } from \"./GET_PAGE_EXPERIMENT.js\";\nimport { GET_VARIANT_CONTENT } from \"./GET_VARIANT_CONTENT.js\";\nimport { GET_EXPERIMENT_PAUSED } from \"./GET_EXPERIMENT_PAUSED.js\";\n\ninterface DefaultDataProviderConfig {\n apiClient: ApiClient;\n}\n\nconst ignoreActions = [\".well-known\", \"_next\"];\n\nexport class DefaultDataProvider implements IDataProvider {\n private config: DefaultDataProviderConfig;\n\n constructor(config: DefaultDataProviderConfig) {\n this.config = config;\n }\n\n public async getPageByPath(path: string): Promise<PublicPage | null> {\n const result = await this.config.apiClient.query({\n query: GET_PAGE_BY_PATH,\n variables: {\n path\n }\n });\n\n this.checkForErrors(`getPageByPath:${path}`, result.websiteBuilder.getPageByPath);\n\n return result.websiteBuilder.getPageByPath.data;\n }\n\n public async getPageById(id: string): Promise<PublicPage | null> {\n const result = await this.config.apiClient.query({\n query: GET_PAGE_BY_ID,\n variables: {\n id\n }\n });\n\n this.checkForErrors(\"getPageById\", result.websiteBuilder.getPageById);\n\n return result.websiteBuilder.getPageById.data;\n }\n\n public async listPages(options?: ListPagesOptions): Promise<ListPagesResult> {\n const { where, ...rest } = options ?? {};\n\n const result = await this.config.apiClient.query({\n query: LIST_PUBLISHED_PAGES,\n variables: {\n where: {\n ...where,\n published: true\n },\n ...rest\n }\n });\n\n this.checkForErrors(\"listPages\", result.websiteBuilder.listPages);\n\n return {\n data: result.websiteBuilder.listPages.data ?? [],\n meta: result.websiteBuilder.listPages.meta ?? {\n hasMoreItems: false,\n totalCount: 0,\n cursor: null\n }\n };\n }\n\n public async getPageExperiment(path: string): Promise<ActiveExperiment | null> {\n const result = await this.config.apiClient.query({\n query: GET_PAGE_EXPERIMENT,\n variables: {\n path\n }\n });\n\n this.checkForErrors(`getPageExperiment:${path}`, result.websiteBuilder.getPageExperiment);\n\n return result.websiteBuilder.getPageExperiment.data ?? null;\n }\n\n public async getVariantContent(variantId: string): Promise<VariantContent | null> {\n const result = await this.config.apiClient.query({\n query: GET_VARIANT_CONTENT,\n variables: {\n id: variantId\n }\n });\n\n this.checkForErrors(\n `getVariantContent:${variantId}`,\n result.websiteBuilder.getVariantContent\n );\n\n return result.websiteBuilder.getVariantContent.data ?? null;\n }\n\n public async getExperimentPaused(experimentId: string): Promise<boolean> {\n // Uncached: the kill-switch must take effect immediately, even while page/variant content\n // stays cached.\n const result = await this.config.apiClient.query(\n {\n query: GET_EXPERIMENT_PAUSED,\n variables: { experimentId }\n },\n { noStore: true }\n );\n\n this.checkForErrors(\n `getExperimentPaused:${experimentId}`,\n result.websiteBuilder.getExperimentPaused\n );\n\n return result.websiteBuilder.getExperimentPaused.data === true;\n }\n\n private checkForErrors(action: string, data: any) {\n if (data.error) {\n // TODO: investigate how these ignored actions make their way to the SDK.\n if (ignoreActions.some(item => action.includes(item))) {\n return;\n }\n console.error(`Could not execute \"${action}\". Reason: ${data.error.message}`);\n }\n }\n}\n"],"names":["ignoreActions","DefaultDataProvider","config","path","result","GET_PAGE_BY_PATH","id","GET_PAGE_BY_ID","options","where","rest","LIST_PUBLISHED_PAGES","GET_PAGE_EXPERIMENT","variantId","GET_VARIANT_CONTENT","experimentId","GET_EXPERIMENT_PAUSED","action","data","item","console"],"mappings":";;;;;;AAcA,MAAMA,gBAAgB;IAAC;IAAe;CAAQ;AAEvC,MAAMC;IAGT,YAAYC,MAAiC,CAAE;QAC3C,IAAI,CAAC,MAAM,GAAGA;IAClB;IAEA,MAAa,cAAcC,IAAY,EAA8B;QACjE,MAAMC,SAAS,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC;YAC7C,OAAOC;YACP,WAAW;gBACPF;YACJ;QACJ;QAEA,IAAI,CAAC,cAAc,CAAC,CAAC,cAAc,EAAEA,MAAM,EAAEC,OAAO,cAAc,CAAC,aAAa;QAEhF,OAAOA,OAAO,cAAc,CAAC,aAAa,CAAC,IAAI;IACnD;IAEA,MAAa,YAAYE,EAAU,EAA8B;QAC7D,MAAMF,SAAS,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC;YAC7C,OAAOG;YACP,WAAW;gBACPD;YACJ;QACJ;QAEA,IAA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AiB,CAAC,IAAI,IAAI;IAC3D;IAEA,MAAa,oBAAoBW,YAAoB,EAAoB;QAGrE,MAAMX,SAAS,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAC5C;YACI,OAAOY;YACP,WAAW;gBAAED;YAAa;QAC9B,GACA;YAAE,SAAS;QAAK;QAGpB,IAAI,CAAC,cAAc,CACf,CAAC,oBAAoB,EAAEA,cAAc,EACrCX,OAAO,cAAc,CAAC,mBAAmB;QAG7C,OAAOA,AAAmD,SAAnDA,OAAO,cAAc,CAAC,mBAAmB,CAAC,IAAI;IACzD;IAEQ,eAAea,MAAc,EAAEC,IAAS,EAAE;QAC9C,IAAIA,KAAK,KAAK,EAAE;YAEZ,IAAIlB,cAAc,IAAI,CAACmB,CAAAA,OAAQF,OAAO,QAAQ,CAACE,QAC3C;YAEJC,QAAQ,KAAK,CAAC,CAAC,mBAAmB,EAAEH,OAAO,WAAW,EAAEC,KAAK,KAAK,CAAC,OAAO,EAAE;QAChF;IACJ;AACJ"}
1
+ {"version":3,"file":"dataProviders/DefaultDataProvider.js","sources":["../../src/dataProviders/DefaultDataProvider.ts"],"sourcesContent":["import type {\n GetLayoutParams,\n IDataProvider,\n ListPagesOptions,\n ListPagesResult,\n PublicLayout,\n PublicPage\n} from \"~/types.js\";\nimport type { ActiveExperiment, VariantContent } from \"~/experiments/types.js\";\nimport type { ApiClient } from \"~/dataProviders/ApiClient.js\";\nimport { GET_PAGE_BY_PATH } from \"./GET_PAGE_BY_PATH.js\";\nimport { GET_PAGE_BY_ID } from \"./GET_PAGE_BY_ID.js\";\nimport { GET_LAYOUT_BY_SLUG } from \"./GET_LAYOUT_BY_SLUG.js\";\nimport { LIST_PUBLISHED_PAGES } from \"./LIST_PUBLISHED_PAGES.js\";\nimport { GET_PAGE_EXPERIMENT } from \"./GET_PAGE_EXPERIMENT.js\";\nimport { GET_VARIANT_CONTENT } from \"./GET_VARIANT_CONTENT.js\";\nimport { GET_EXPERIMENT_PAUSED } from \"./GET_EXPERIMENT_PAUSED.js\";\n\ninterface DefaultDataProviderConfig {\n apiClient: ApiClient;\n}\n\nconst ignoreActions = [\".well-known\", \"_next\"];\n\nexport class DefaultDataProvider implements IDataProvider {\n private config: DefaultDataProviderConfig;\n\n constructor(config: DefaultDataProviderConfig) {\n this.config = config;\n }\n\n public async getPageByPath(path: string): Promise<PublicPage | null> {\n const result = await this.config.apiClient.query({\n query: GET_PAGE_BY_PATH,\n variables: {\n path\n }\n });\n\n this.checkForErrors(`getPageByPath:${path}`, result.websiteBuilder.getPageByPath);\n\n return result.websiteBuilder.getPageByPath.data;\n }\n\n public async getPageById(id: string): Promise<PublicPage | null> {\n const result = await this.config.apiClient.query({\n query: GET_PAGE_BY_ID,\n variables: {\n id\n }\n });\n\n this.checkForErrors(\"getPageById\", result.websiteBuilder.getPageById);\n\n return result.websiteBuilder.getPageById.data;\n }\n\n public async getLayoutBySlug(params: GetLayoutParams): Promise<PublicLayout | null> {\n const result = await this.config.apiClient.query({\n query: GET_LAYOUT_BY_SLUG,\n variables: {\n slug: params.slug,\n language: params.language ?? null\n }\n });\n\n this.checkForErrors(\n `getLayoutBySlug:${params.slug}`,\n result.websiteBuilder.getLayoutBySlug\n );\n\n return result.websiteBuilder.getLayoutBySlug.data ?? null;\n }\n\n public async listPages(options?: ListPagesOptions): Promise<ListPagesResult> {\n const { where, ...rest } = options ?? {};\n\n const result = await this.config.apiClient.query({\n query: LIST_PUBLISHED_PAGES,\n variables: {\n where: {\n ...where,\n published: true\n },\n ...rest\n }\n });\n\n this.checkForErrors(\"listPages\", result.websiteBuilder.listPages);\n\n return {\n data: result.websiteBuilder.listPages.data ?? [],\n meta: result.websiteBuilder.listPages.meta ?? {\n hasMoreItems: false,\n totalCount: 0,\n cursor: null\n }\n };\n }\n\n public async getPageExperiment(path: string): Promise<ActiveExperiment | null> {\n const result = await this.config.apiClient.query({\n query: GET_PAGE_EXPERIMENT,\n variables: {\n path\n }\n });\n\n this.checkForErrors(`getPageExperiment:${path}`, result.websiteBuilder.getPageExperiment);\n\n return result.websiteBuilder.getPageExperiment.data ?? null;\n }\n\n public async getVariantContent(variantId: string): Promise<VariantContent | null> {\n const result = await this.config.apiClient.query({\n query: GET_VARIANT_CONTENT,\n variables: {\n id: variantId\n }\n });\n\n this.checkForErrors(\n `getVariantContent:${variantId}`,\n result.websiteBuilder.getVariantContent\n );\n\n return result.websiteBuilder.getVariantContent.data ?? null;\n }\n\n public async getExperimentPaused(experimentId: string): Promise<boolean> {\n // Uncached: the kill-switch must take effect immediately, even while page/variant content\n // stays cached.\n const result = await this.config.apiClient.query(\n {\n query: GET_EXPERIMENT_PAUSED,\n variables: { experimentId }\n },\n { noStore: true }\n );\n\n this.checkForErrors(\n `getExperimentPaused:${experimentId}`,\n result.websiteBuilder.getExperimentPaused\n );\n\n return result.websiteBuilder.getExperimentPaused.data === true;\n }\n\n private checkForErrors(action: string, data: any) {\n if (data.error) {\n // TODO: investigate how these ignored actions make their way to the SDK.\n if (ignoreActions.some(item => action.includes(item))) {\n return;\n }\n console.error(`Could not execute \"${action}\". Reason: ${data.error.message}`);\n }\n }\n}\n"],"names":["ignoreActions","DefaultDataProvider","config","path","result","GET_PAGE_BY_PATH","id","GET_PAGE_BY_ID","params","GET_LAYOUT_BY_SLUG","options","where","rest","LIST_PUBLISHED_PAGES","GET_PAGE_EXPERIMENT","variantId","GET_VARIANT_CONTENT","experimentId","GET_EXPERIMENT_PAUSED","action","data","item","console"],"mappings":";;;;;;;AAsBA,MAAMA,gBAAgB;IAAC;IAAe;CAAQ;AAEvC,MAAMC;IAGT,YAAYC,MAAiC,CAAE;QAC3C,IAAI,CAAC,MAAM,GAAGA;IAClB;IAEA,MAAa,cAAcC,IAAY,EAA8B;QACjE,MAAMC,SAAS,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC;YAC7C,OAAOC;YACP,WAAW;gBACPF;YACJ;QACJ;QAEA,IAAI,CAAC,cAAc,CAAC,CAAC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KAAK,CAAC,OAAO,EAAE;QAChF;IACJ;AACJ"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,81 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { DefaultDataProvider } from "./DefaultDataProvider.js";
3
+ import { GET_LAYOUT_BY_SLUG } from "./GET_LAYOUT_BY_SLUG.js";
4
+ const createProvider = (envelope)=>{
5
+ const query = vi.fn().mockResolvedValue({
6
+ websiteBuilder: {
7
+ getLayoutBySlug: envelope
8
+ }
9
+ });
10
+ const provider = new DefaultDataProvider({
11
+ apiClient: {
12
+ query
13
+ }
14
+ });
15
+ return {
16
+ provider,
17
+ query
18
+ };
19
+ };
20
+ describe("DefaultDataProvider.getLayoutBySlug", ()=>{
21
+ it("asks for the layout by slug and language, and returns it composed", async ()=>{
22
+ const layout = {
23
+ elements: {
24
+ "$global:Demo/Header": {
25
+ id: "$global:Demo/Header"
26
+ }
27
+ },
28
+ bindings: {},
29
+ layout: {
30
+ id: "abc#0001",
31
+ entryId: "abc",
32
+ properties: {},
33
+ elements: {},
34
+ bindings: {}
35
+ }
36
+ };
37
+ const { provider, query } = createProvider({
38
+ data: layout,
39
+ error: null
40
+ });
41
+ expect(await provider.getLayoutBySlug({
42
+ slug: "blog",
43
+ language: "de"
44
+ })).toEqual(layout);
45
+ expect(query).toHaveBeenCalledWith({
46
+ query: GET_LAYOUT_BY_SLUG,
47
+ variables: {
48
+ slug: "blog",
49
+ language: "de"
50
+ }
51
+ });
52
+ });
53
+ it("returns null when no layout is published, or the API fails", async ()=>{
54
+ const { provider, query } = createProvider({
55
+ data: null,
56
+ error: null
57
+ });
58
+ expect(await provider.getLayoutBySlug({
59
+ slug: "blog"
60
+ })).toBeNull();
61
+ expect(query.mock.calls[0][0].variables).toEqual({
62
+ slug: "blog",
63
+ language: null
64
+ });
65
+ const consoleError = vi.spyOn(console, "error").mockImplementation(()=>{});
66
+ const failing = createProvider({
67
+ data: null,
68
+ error: {
69
+ code: "WebsiteBuilder/Layout/NotAuthorized",
70
+ message: "Not authorized!"
71
+ }
72
+ });
73
+ expect(await failing.provider.getLayoutBySlug({
74
+ slug: "blog"
75
+ })).toBeNull();
76
+ expect(consoleError).toHaveBeenCalled();
77
+ consoleError.mockRestore();
78
+ });
79
+ });
80
+
81
+ //# sourceMappingURL=DefaultDataProvider.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataProviders/DefaultDataProvider.test.js","sources":["../../src/dataProviders/DefaultDataProvider.test.ts"],"sourcesContent":["import { describe, expect, it, vi } from \"vitest\";\nimport { DefaultDataProvider } from \"./DefaultDataProvider.js\";\nimport { GET_LAYOUT_BY_SLUG } from \"./GET_LAYOUT_BY_SLUG.js\";\nimport type { ApiClient } from \"./ApiClient.js\";\n\nconst createProvider = (envelope: Record<string, any>) => {\n const query = vi.fn().mockResolvedValue({ websiteBuilder: { getLayoutBySlug: envelope } });\n const provider = new DefaultDataProvider({ apiClient: { query } as unknown as ApiClient });\n return { provider, query };\n};\n\ndescribe(\"DefaultDataProvider.getLayoutBySlug\", () => {\n it(\"asks for the layout by slug and language, and returns it composed\", async () => {\n const layout = {\n elements: { \"$global:Demo/Header\": { id: \"$global:Demo/Header\" } },\n bindings: {},\n layout: { id: \"abc#0001\", entryId: \"abc\", properties: {}, elements: {}, bindings: {} }\n };\n const { provider, query } = createProvider({ data: layout, error: null });\n\n expect(await provider.getLayoutBySlug({ slug: \"blog\", language: \"de\" })).toEqual(layout);\n expect(query).toHaveBeenCalledWith({\n query: GET_LAYOUT_BY_SLUG,\n variables: { slug: \"blog\", language: \"de\" }\n });\n });\n\n it(\"returns null when no layout is published, or the API fails\", async () => {\n const { provider, query } = createProvider({ data: null, error: null });\n expect(await provider.getLayoutBySlug({ slug: \"blog\" })).toBeNull();\n expect(query.mock.calls[0][0].variables).toEqual({ slug: \"blog\", language: null });\n\n const consoleError = vi.spyOn(console, \"error\").mockImplementation(() => {});\n const failing = createProvider({\n data: null,\n error: { code: \"WebsiteBuilder/Layout/NotAuthorized\", message: \"Not authorized!\" }\n });\n expect(await failing.provider.getLayoutBySlug({ slug: \"blog\" })).toBeNull();\n expect(consoleError).toHaveBeenCalled();\n consoleError.mockRestore();\n });\n});\n"],"names":["createProvider","envelope","query","vi","provider","DefaultDataProvider","describe","it","layout","expect","GET_LAYOUT_BY_SLUG","consoleError","console","failing"],"mappings":";;;AAKA,MAAMA,iBAAiB,CAACC;IACpB,MAAMC,QAAQC,GAAG,EAAE,GAAG,iBAAiB,CAAC;QAAE,gBAAgB;YAAE,iBAAiBF;QAAS;IAAE;IACxF,MAAMG,WAAW,IAAIC,oBAAoB;QAAE,WAAW;YAAEH;QAAM;IAA0B;IACxF,OAAO;QAAEE;QAAUF;IAAM;AAC7B;AAEAI,SAAS,uCAAuC;IAC5CC,GAAG,qEAAqE;QACpE,MAAMC,SAAS;YACX,UAAU;gBAAE,uBAAuB;oBAAE,IAAI;gBAAsB;YAAE;YACjE,UAAU,CAAC;YACX,QAAQ;gBAAE,IAAI;gBAAY,SAAS;gBAAO,YAAY,CAAC;gBAAG,UAAU,CAAC;gBAAG,UAAU,CAAC;YAAE;QACzF;QACA,MAAM,EAAEJ,QAAQ,EAAEF,KAAK,EAAE,GAAGF,eAAe;YAAE,MAAMQ;YAAQ,OAAO;QAAK;QAEvEC,OAAO,MAAML,SAAS,eAAe,CAAC;YAAE,MAAM;YAAQ,UAAU;QAAK,IAAI,OAAO,CAACI;QACjFC,OAAOP,OAAO,oBAAoB,CAAC;YAC/B,OAAOQ;YACP,WAAW;gBAAE,MAAM;gBAAQ,UAAU;YAAK;QAC9C;IACJ;IAEAH,GAAG,8DAA8D;QAC7D,MAAM,EAAEH,QAAQ,EAAEF,KAAK,EAAE,GAAGF,eAAe;YAAE,MAAM;YAAM,OAAO;QAAK;QACrES,OAAO,MAAML,SAAS,eAAe,CAAC;YAAE,MAAM;QAAO,IAAI,QAAQ;QACjEK,OAAOP,MAAM,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC;YAAE,MAAM;YAAQ,UAAU;QAAK;QAEhF,MAAMS,eAAeR,GAAG,KAAK,CAACS,SAAS,SAAS,kBAAkB,CAAC,KAAO;QAC1E,MAAMC,UAAUb,eAAe;YAC3B,MAAM;YACN,OAAO;gBAAE,MAAM;gBAAuC,SAAS;YAAkB;QACrF;QACAS,OAAO,MAAMI,QAAQ,QAAQ,CAAC,eAAe,CAAC;YAAE,MAAM;QAAO,IAAI,QAAQ;QACzEJ,OAAOE,cAAc,gBAAgB;QACrCA,aAAa,WAAW;IAC5B;AACJ"}
@@ -0,0 +1 @@
1
+ export declare const GET_LAYOUT_BY_SLUG = "\n query GetLayoutBySlug($slug: String!, $language: String) {\n websiteBuilder {\n getLayoutBySlug(slug: $slug, language: $language) {\n data {\n elements\n bindings\n layout {\n id\n entryId\n properties\n elements\n bindings\n }\n }\n error {\n code\n message\n data\n }\n }\n }\n }\n";
@@ -0,0 +1,27 @@
1
+ const GET_LAYOUT_BY_SLUG = `
2
+ query GetLayoutBySlug($slug: String!, $language: String) {
3
+ websiteBuilder {
4
+ getLayoutBySlug(slug: $slug, language: $language) {
5
+ data {
6
+ elements
7
+ bindings
8
+ layout {
9
+ id
10
+ entryId
11
+ properties
12
+ elements
13
+ bindings
14
+ }
15
+ }
16
+ error {
17
+ code
18
+ message
19
+ data
20
+ }
21
+ }
22
+ }
23
+ }
24
+ `;
25
+ export { GET_LAYOUT_BY_SLUG };
26
+
27
+ //# sourceMappingURL=GET_LAYOUT_BY_SLUG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataProviders/GET_LAYOUT_BY_SLUG.js","sources":["../../src/dataProviders/GET_LAYOUT_BY_SLUG.ts"],"sourcesContent":["export const GET_LAYOUT_BY_SLUG = /* GraphQL*/ `\n query GetLayoutBySlug($slug: String!, $language: String) {\n websiteBuilder {\n getLayoutBySlug(slug: $slug, language: $language) {\n data {\n elements\n bindings\n layout {\n id\n entryId\n properties\n elements\n bindings\n }\n }\n error {\n code\n message\n data\n }\n }\n }\n }\n`;\n"],"names":["GET_LAYOUT_BY_SLUG"],"mappings":"AAAO,MAAMA,qBAAkC,CAAC;;;;;;;;;;;;;;;;;;;;;;;AAuBhD,CAAC"}
@@ -1 +1 @@
1
- export declare const GET_PAGE_BY_ID = "\n query GetPageById($id: ID!) {\n websiteBuilder {\n getPageById(id: $id) {\n data {\n id\n properties\n elements\n bindings\n extensions\n languagePaths\n }\n error {\n code\n message\n data\n }\n }\n }\n }\n";
1
+ export declare const GET_PAGE_BY_ID = "\n query GetPageById($id: ID!) {\n websiteBuilder {\n getPageById(id: $id) {\n data {\n id\n version\n properties\n metadata\n elements\n bindings\n extensions\n languagePaths\n layout {\n id\n elements\n bindings\n }\n }\n error {\n code\n message\n data\n }\n }\n }\n }\n";