@prismicio/client 7.21.0-alpha.2 → 7.21.0-canary.147e3f2

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 (697) hide show
  1. package/dist/Client.cjs +926 -0
  2. package/dist/Client.cjs.map +1 -0
  3. package/dist/Client.d.cts +704 -0
  4. package/dist/Client.d.cts.map +1 -0
  5. package/dist/Client.d.ts +704 -0
  6. package/dist/Client.d.ts.map +1 -0
  7. package/dist/Client.js +926 -0
  8. package/dist/Client.js.map +1 -0
  9. package/dist/Migration.cjs +284 -0
  10. package/dist/Migration.cjs.map +1 -0
  11. package/dist/Migration.d.cts +216 -0
  12. package/dist/Migration.d.cts.map +1 -0
  13. package/dist/Migration.d.ts +216 -0
  14. package/dist/Migration.d.ts.map +1 -0
  15. package/dist/Migration.js +284 -0
  16. package/dist/Migration.js.map +1 -0
  17. package/dist/WriteClient.cjs +488 -0
  18. package/dist/WriteClient.cjs.map +1 -0
  19. package/dist/WriteClient.d.cts +262 -0
  20. package/dist/WriteClient.d.cts.map +1 -0
  21. package/dist/WriteClient.d.ts +262 -0
  22. package/dist/WriteClient.d.ts.map +1 -0
  23. package/dist/WriteClient.js +488 -0
  24. package/dist/WriteClient.js.map +1 -0
  25. package/dist/_virtual/rolldown_runtime.cjs +14 -0
  26. package/dist/_virtual/rolldown_runtime.js +13 -0
  27. package/dist/buildQueryURL.cjs +96 -0
  28. package/dist/buildQueryURL.cjs.map +1 -0
  29. package/dist/buildQueryURL.d.cts +212 -0
  30. package/dist/buildQueryURL.d.cts.map +1 -0
  31. package/dist/buildQueryURL.d.ts +212 -0
  32. package/dist/buildQueryURL.d.ts.map +1 -0
  33. package/dist/buildQueryURL.js +96 -0
  34. package/dist/buildQueryURL.js.map +1 -0
  35. package/dist/cookie.cjs +19 -0
  36. package/dist/cookie.cjs.map +1 -0
  37. package/dist/cookie.d.cts +11 -0
  38. package/dist/cookie.d.cts.map +1 -0
  39. package/dist/cookie.d.ts +11 -0
  40. package/dist/cookie.d.ts.map +1 -0
  41. package/dist/cookie.js +13 -0
  42. package/dist/cookie.js.map +1 -0
  43. package/dist/createClient.cjs +33 -0
  44. package/dist/createClient.cjs.map +1 -0
  45. package/dist/createClient.d.cts +41 -0
  46. package/dist/createClient.d.cts.map +1 -0
  47. package/dist/createClient.d.ts +41 -0
  48. package/dist/createClient.d.ts.map +1 -0
  49. package/dist/createClient.js +33 -0
  50. package/dist/createClient.js.map +1 -0
  51. package/dist/createMigration.cjs +22 -0
  52. package/dist/createMigration.cjs.map +1 -0
  53. package/dist/createMigration.d.cts +30 -0
  54. package/dist/createMigration.d.cts.map +1 -0
  55. package/dist/createMigration.d.ts +30 -0
  56. package/dist/createMigration.d.ts.map +1 -0
  57. package/dist/createMigration.js +22 -0
  58. package/dist/createMigration.js.map +1 -0
  59. package/dist/createWriteClient.cjs +30 -0
  60. package/dist/createWriteClient.cjs.map +1 -0
  61. package/dist/createWriteClient.d.cts +38 -0
  62. package/dist/createWriteClient.d.cts.map +1 -0
  63. package/dist/createWriteClient.d.ts +38 -0
  64. package/dist/createWriteClient.d.ts.map +1 -0
  65. package/dist/createWriteClient.js +30 -0
  66. package/dist/createWriteClient.js.map +1 -0
  67. package/dist/errors.cjs +31 -0
  68. package/dist/errors.cjs.map +1 -0
  69. package/dist/errors.d.cts +46 -0
  70. package/dist/errors.d.cts.map +1 -0
  71. package/dist/errors.d.ts +46 -0
  72. package/dist/errors.d.ts.map +1 -0
  73. package/dist/errors.js +22 -0
  74. package/dist/errors.js.map +1 -0
  75. package/dist/filter.cjs +104 -0
  76. package/dist/filter.cjs.map +1 -0
  77. package/dist/filter.d.cts +213 -0
  78. package/dist/filter.d.cts.map +1 -0
  79. package/dist/filter.d.ts +213 -0
  80. package/dist/filter.d.ts.map +1 -0
  81. package/dist/filter.js +103 -0
  82. package/dist/filter.js.map +1 -0
  83. package/dist/getGraphQLEndpoint.cjs +21 -0
  84. package/dist/getGraphQLEndpoint.cjs.map +1 -0
  85. package/dist/getGraphQLEndpoint.d.cts +14 -0
  86. package/dist/getGraphQLEndpoint.d.cts.map +1 -0
  87. package/dist/getGraphQLEndpoint.d.ts +14 -0
  88. package/dist/getGraphQLEndpoint.d.ts.map +1 -0
  89. package/dist/getGraphQLEndpoint.js +21 -0
  90. package/dist/getGraphQLEndpoint.js.map +1 -0
  91. package/dist/getRepositoryEndpoint.cjs +30 -0
  92. package/dist/getRepositoryEndpoint.cjs.map +1 -0
  93. package/dist/getRepositoryEndpoint.d.cts +23 -0
  94. package/dist/getRepositoryEndpoint.d.cts.map +1 -0
  95. package/dist/getRepositoryEndpoint.d.ts +23 -0
  96. package/dist/getRepositoryEndpoint.d.ts.map +1 -0
  97. package/dist/getRepositoryEndpoint.js +30 -0
  98. package/dist/getRepositoryEndpoint.js.map +1 -0
  99. package/dist/getRepositoryName.cjs +25 -0
  100. package/dist/getRepositoryName.cjs.map +1 -0
  101. package/dist/getRepositoryName.d.cts +16 -0
  102. package/dist/getRepositoryName.d.cts.map +1 -0
  103. package/dist/getRepositoryName.d.ts +16 -0
  104. package/dist/getRepositoryName.d.ts.map +1 -0
  105. package/dist/getRepositoryName.js +25 -0
  106. package/dist/getRepositoryName.js.map +1 -0
  107. package/dist/getToolbarSrc.cjs +45 -0
  108. package/dist/getToolbarSrc.cjs.map +1 -0
  109. package/dist/getToolbarSrc.d.cts +38 -0
  110. package/dist/getToolbarSrc.d.cts.map +1 -0
  111. package/dist/getToolbarSrc.d.ts +38 -0
  112. package/dist/getToolbarSrc.d.ts.map +1 -0
  113. package/dist/getToolbarSrc.js +45 -0
  114. package/dist/getToolbarSrc.js.map +1 -0
  115. package/dist/helpers/asDate.cjs +39 -0
  116. package/dist/helpers/asDate.cjs.map +1 -0
  117. package/dist/helpers/asDate.d.cts +29 -0
  118. package/dist/helpers/asDate.d.cts.map +1 -0
  119. package/dist/helpers/asDate.d.ts +29 -0
  120. package/dist/helpers/asDate.d.ts.map +1 -0
  121. package/dist/helpers/asDate.js +38 -0
  122. package/dist/helpers/asDate.js.map +1 -0
  123. package/dist/helpers/asHTML.cjs +83 -0
  124. package/dist/helpers/asHTML.cjs.map +1 -0
  125. package/dist/helpers/asHTML.d.cts +147 -0
  126. package/dist/helpers/asHTML.d.cts.map +1 -0
  127. package/dist/helpers/asHTML.d.ts +147 -0
  128. package/dist/helpers/asHTML.d.ts.map +1 -0
  129. package/dist/helpers/asHTML.js +83 -0
  130. package/dist/helpers/asHTML.js.map +1 -0
  131. package/dist/helpers/asImagePixelDensitySrcSet.cjs +60 -0
  132. package/dist/helpers/asImagePixelDensitySrcSet.cjs.map +1 -0
  133. package/dist/helpers/asImagePixelDensitySrcSet.d.cts +59 -0
  134. package/dist/helpers/asImagePixelDensitySrcSet.d.cts.map +1 -0
  135. package/dist/helpers/asImagePixelDensitySrcSet.d.ts +59 -0
  136. package/dist/helpers/asImagePixelDensitySrcSet.d.ts.map +1 -0
  137. package/dist/helpers/asImagePixelDensitySrcSet.js +60 -0
  138. package/dist/helpers/asImagePixelDensitySrcSet.js.map +1 -0
  139. package/dist/helpers/asImageSrc.cjs +33 -0
  140. package/dist/helpers/asImageSrc.cjs.map +1 -0
  141. package/dist/helpers/asImageSrc.d.cts +34 -0
  142. package/dist/helpers/asImageSrc.d.cts.map +1 -0
  143. package/dist/helpers/asImageSrc.d.ts +34 -0
  144. package/dist/helpers/asImageSrc.d.ts.map +1 -0
  145. package/dist/helpers/asImageSrc.js +33 -0
  146. package/dist/helpers/asImageSrc.js.map +1 -0
  147. package/dist/helpers/asImageWidthSrcSet.cjs +79 -0
  148. package/dist/helpers/asImageWidthSrcSet.cjs.map +1 -0
  149. package/dist/helpers/asImageWidthSrcSet.d.cts +67 -0
  150. package/dist/helpers/asImageWidthSrcSet.d.cts.map +1 -0
  151. package/dist/helpers/asImageWidthSrcSet.d.ts +67 -0
  152. package/dist/helpers/asImageWidthSrcSet.d.ts.map +1 -0
  153. package/dist/helpers/asImageWidthSrcSet.js +79 -0
  154. package/dist/helpers/asImageWidthSrcSet.js.map +1 -0
  155. package/dist/helpers/asLink.cjs +29 -0
  156. package/dist/helpers/asLink.cjs.map +1 -0
  157. package/dist/helpers/asLink.d.cts +83 -0
  158. package/dist/helpers/asLink.d.cts.map +1 -0
  159. package/dist/helpers/asLink.d.ts +83 -0
  160. package/dist/helpers/asLink.d.ts.map +1 -0
  161. package/dist/helpers/asLink.js +29 -0
  162. package/dist/helpers/asLink.js.map +1 -0
  163. package/dist/helpers/asLinkAttrs.cjs +47 -0
  164. package/dist/helpers/asLinkAttrs.cjs.map +1 -0
  165. package/dist/helpers/asLinkAttrs.d.cts +51 -0
  166. package/dist/helpers/asLinkAttrs.d.cts.map +1 -0
  167. package/dist/helpers/asLinkAttrs.d.ts +51 -0
  168. package/dist/helpers/asLinkAttrs.d.ts.map +1 -0
  169. package/dist/helpers/asLinkAttrs.js +47 -0
  170. package/dist/helpers/asLinkAttrs.js.map +1 -0
  171. package/dist/helpers/asText.cjs +16 -0
  172. package/dist/helpers/asText.cjs.map +1 -0
  173. package/dist/helpers/asText.d.cts +62 -0
  174. package/dist/helpers/asText.d.cts.map +1 -0
  175. package/dist/helpers/asText.d.ts +62 -0
  176. package/dist/helpers/asText.d.ts.map +1 -0
  177. package/dist/helpers/asText.js +16 -0
  178. package/dist/helpers/asText.js.map +1 -0
  179. package/dist/helpers/documentToLinkField.cjs +33 -0
  180. package/dist/helpers/documentToLinkField.cjs.map +1 -0
  181. package/dist/helpers/documentToLinkField.d.cts +21 -0
  182. package/dist/helpers/documentToLinkField.d.cts.map +1 -0
  183. package/dist/helpers/documentToLinkField.d.ts +21 -0
  184. package/dist/helpers/documentToLinkField.d.ts.map +1 -0
  185. package/dist/helpers/documentToLinkField.js +33 -0
  186. package/dist/helpers/documentToLinkField.js.map +1 -0
  187. package/dist/helpers/isFilled.cjs +250 -0
  188. package/dist/helpers/isFilled.cjs.map +1 -0
  189. package/dist/helpers/isFilled.d.cts +199 -0
  190. package/dist/helpers/isFilled.d.cts.map +1 -0
  191. package/dist/helpers/isFilled.d.ts +199 -0
  192. package/dist/helpers/isFilled.d.ts.map +1 -0
  193. package/dist/helpers/isFilled.js +243 -0
  194. package/dist/helpers/isFilled.js.map +1 -0
  195. package/dist/helpers/mapSliceZone.cjs +53 -0
  196. package/dist/helpers/mapSliceZone.cjs.map +1 -0
  197. package/dist/helpers/mapSliceZone.d.cts +139 -0
  198. package/dist/helpers/mapSliceZone.d.cts.map +1 -0
  199. package/dist/helpers/mapSliceZone.d.ts +139 -0
  200. package/dist/helpers/mapSliceZone.d.ts.map +1 -0
  201. package/dist/helpers/mapSliceZone.js +52 -0
  202. package/dist/helpers/mapSliceZone.js.map +1 -0
  203. package/dist/index.cjs +109 -3882
  204. package/dist/index.cjs.map +1 -1
  205. package/dist/index.d.cts +143 -4394
  206. package/dist/index.d.cts.map +1 -0
  207. package/dist/index.d.ts +143 -4394
  208. package/dist/index.d.ts.map +1 -0
  209. package/dist/index.js +55 -0
  210. package/dist/index.js.map +1 -0
  211. package/dist/isRepositoryEndpoint.cjs +23 -0
  212. package/dist/isRepositoryEndpoint.cjs.map +1 -0
  213. package/dist/isRepositoryEndpoint.d.cts +14 -0
  214. package/dist/isRepositoryEndpoint.d.cts.map +1 -0
  215. package/dist/isRepositoryEndpoint.d.ts +14 -0
  216. package/dist/isRepositoryEndpoint.d.ts.map +1 -0
  217. package/dist/isRepositoryEndpoint.js +22 -0
  218. package/dist/isRepositoryEndpoint.js.map +1 -0
  219. package/dist/isRepositoryName.cjs +17 -0
  220. package/dist/isRepositoryName.cjs.map +1 -0
  221. package/dist/isRepositoryName.d.cts +13 -0
  222. package/dist/isRepositoryName.d.cts.map +1 -0
  223. package/dist/isRepositoryName.d.ts +13 -0
  224. package/dist/isRepositoryName.d.ts.map +1 -0
  225. package/dist/isRepositoryName.js +16 -0
  226. package/dist/isRepositoryName.js.map +1 -0
  227. package/dist/lib/devMsg.cjs +25 -0
  228. package/dist/lib/devMsg.cjs.map +1 -0
  229. package/dist/lib/devMsg.js +25 -0
  230. package/dist/lib/devMsg.js.map +1 -0
  231. package/dist/lib/escapeHTML.cjs +40 -0
  232. package/dist/lib/escapeHTML.cjs.map +1 -0
  233. package/dist/lib/escapeHTML.js +39 -0
  234. package/dist/lib/escapeHTML.js.map +1 -0
  235. package/dist/lib/getOptionalLinkProperties.cjs +22 -0
  236. package/dist/lib/getOptionalLinkProperties.cjs.map +1 -0
  237. package/dist/lib/getOptionalLinkProperties.js +21 -0
  238. package/dist/lib/getOptionalLinkProperties.js.map +1 -0
  239. package/dist/lib/getPreviewCookie.cjs +30 -0
  240. package/dist/lib/getPreviewCookie.cjs.map +1 -0
  241. package/dist/lib/getPreviewCookie.js +30 -0
  242. package/dist/lib/getPreviewCookie.js.map +1 -0
  243. package/dist/lib/isInternalURL.cjs +18 -0
  244. package/dist/lib/isInternalURL.cjs.map +1 -0
  245. package/dist/lib/isInternalURL.js +17 -0
  246. package/dist/lib/isInternalURL.js.map +1 -0
  247. package/dist/lib/isMigrationValue.cjs +77 -0
  248. package/dist/lib/isMigrationValue.cjs.map +1 -0
  249. package/dist/lib/isMigrationValue.js +74 -0
  250. package/dist/lib/isMigrationValue.js.map +1 -0
  251. package/dist/lib/isValue.cjs +110 -0
  252. package/dist/lib/isValue.cjs.map +1 -0
  253. package/dist/lib/isValue.js +106 -0
  254. package/dist/lib/isValue.js.map +1 -0
  255. package/dist/lib/pLimit.cjs +55 -0
  256. package/dist/lib/pLimit.cjs.map +1 -0
  257. package/dist/lib/pLimit.js +54 -0
  258. package/dist/lib/pLimit.js.map +1 -0
  259. package/dist/lib/request.cjs +60 -0
  260. package/dist/lib/request.cjs.map +1 -0
  261. package/dist/lib/request.d.cts +61 -0
  262. package/dist/lib/request.d.cts.map +1 -0
  263. package/dist/lib/request.d.ts +61 -0
  264. package/dist/lib/request.d.ts.map +1 -0
  265. package/dist/lib/request.js +60 -0
  266. package/dist/lib/request.js.map +1 -0
  267. package/dist/lib/resolveMigrationDocumentData.cjs +156 -0
  268. package/dist/lib/resolveMigrationDocumentData.cjs.map +1 -0
  269. package/dist/lib/resolveMigrationDocumentData.js +155 -0
  270. package/dist/lib/resolveMigrationDocumentData.js.map +1 -0
  271. package/dist/lib/serializerHelpers.cjs +95 -0
  272. package/dist/lib/serializerHelpers.cjs.map +1 -0
  273. package/dist/lib/serializerHelpers.js +90 -0
  274. package/dist/lib/serializerHelpers.js.map +1 -0
  275. package/dist/lib/throttledWarn.cjs +27 -0
  276. package/dist/lib/throttledWarn.cjs.map +1 -0
  277. package/dist/lib/throttledWarn.js +26 -0
  278. package/dist/lib/throttledWarn.js.map +1 -0
  279. package/dist/lib/validateAssetMetadata.cjs +48 -0
  280. package/dist/lib/validateAssetMetadata.cjs.map +1 -0
  281. package/dist/lib/validateAssetMetadata.js +48 -0
  282. package/dist/lib/validateAssetMetadata.js.map +1 -0
  283. package/dist/package.cjs +19 -0
  284. package/dist/package.cjs.map +1 -0
  285. package/dist/package.js +7 -0
  286. package/dist/package.js.map +1 -0
  287. package/dist/richtext/asText.cjs +21 -0
  288. package/dist/richtext/asText.cjs.map +1 -0
  289. package/dist/richtext/asText.d.cts +18 -0
  290. package/dist/richtext/asText.d.cts.map +1 -0
  291. package/dist/richtext/asText.d.ts +18 -0
  292. package/dist/richtext/asText.d.ts.map +1 -0
  293. package/dist/richtext/asText.js +20 -0
  294. package/dist/richtext/asText.js.map +1 -0
  295. package/dist/richtext/asTree.cjs +122 -0
  296. package/dist/richtext/asTree.cjs.map +1 -0
  297. package/dist/richtext/asTree.d.cts +20 -0
  298. package/dist/richtext/asTree.d.cts.map +1 -0
  299. package/dist/richtext/asTree.d.ts +20 -0
  300. package/dist/richtext/asTree.d.ts.map +1 -0
  301. package/dist/richtext/asTree.js +122 -0
  302. package/dist/richtext/asTree.js.map +1 -0
  303. package/dist/richtext/composeSerializers.cjs +31 -0
  304. package/dist/richtext/composeSerializers.cjs.map +1 -0
  305. package/dist/richtext/composeSerializers.d.cts +22 -0
  306. package/dist/richtext/composeSerializers.d.cts.map +1 -0
  307. package/dist/richtext/composeSerializers.d.ts +22 -0
  308. package/dist/richtext/composeSerializers.d.ts.map +1 -0
  309. package/dist/richtext/composeSerializers.js +30 -0
  310. package/dist/richtext/composeSerializers.js.map +1 -0
  311. package/dist/richtext/serialize.cjs +35 -0
  312. package/dist/richtext/serialize.cjs.map +1 -0
  313. package/dist/richtext/serialize.d.cts +25 -0
  314. package/dist/richtext/serialize.d.cts.map +1 -0
  315. package/dist/richtext/serialize.d.ts +25 -0
  316. package/dist/richtext/serialize.d.ts.map +1 -0
  317. package/dist/richtext/serialize.js +35 -0
  318. package/dist/richtext/serialize.js.map +1 -0
  319. package/dist/richtext/types.cjs +13 -0
  320. package/dist/richtext/types.cjs.map +1 -0
  321. package/dist/richtext/types.d.cts +71 -0
  322. package/dist/richtext/types.d.cts.map +1 -0
  323. package/dist/richtext/types.d.ts +71 -0
  324. package/dist/richtext/types.d.ts.map +1 -0
  325. package/dist/richtext/types.js +13 -0
  326. package/dist/richtext/types.js.map +1 -0
  327. package/dist/richtext/wrapMapSerializer.cjs +32 -0
  328. package/dist/richtext/wrapMapSerializer.cjs.map +1 -0
  329. package/dist/richtext/wrapMapSerializer.d.cts +21 -0
  330. package/dist/richtext/wrapMapSerializer.d.cts.map +1 -0
  331. package/dist/richtext/wrapMapSerializer.d.ts +21 -0
  332. package/dist/richtext/wrapMapSerializer.d.ts.map +1 -0
  333. package/dist/richtext/wrapMapSerializer.js +32 -0
  334. package/dist/richtext/wrapMapSerializer.js.map +1 -0
  335. package/dist/richtext.cjs +13 -0
  336. package/dist/richtext.d.cts +8 -0
  337. package/dist/richtext.d.ts +8 -0
  338. package/dist/richtext.js +8 -0
  339. package/dist/types/api/asset/asset.d.cts +97 -0
  340. package/dist/types/api/asset/asset.d.cts.map +1 -0
  341. package/dist/types/api/asset/asset.d.ts +97 -0
  342. package/dist/types/api/asset/asset.d.ts.map +1 -0
  343. package/dist/types/api/asset/tag.d.cts +35 -0
  344. package/dist/types/api/asset/tag.d.cts.map +1 -0
  345. package/dist/types/api/asset/tag.d.ts +35 -0
  346. package/dist/types/api/asset/tag.d.ts.map +1 -0
  347. package/dist/types/api/integration.d.cts +34 -0
  348. package/dist/types/api/integration.d.cts.map +1 -0
  349. package/dist/types/api/integration.d.ts +34 -0
  350. package/dist/types/api/integration.d.ts.map +1 -0
  351. package/dist/types/api/query.d.cts +49 -0
  352. package/dist/types/api/query.d.cts.map +1 -0
  353. package/dist/types/api/query.d.ts +49 -0
  354. package/dist/types/api/query.d.ts.map +1 -0
  355. package/dist/types/api/ref.d.cts +36 -0
  356. package/dist/types/api/ref.d.cts.map +1 -0
  357. package/dist/types/api/ref.d.ts +36 -0
  358. package/dist/types/api/ref.d.ts.map +1 -0
  359. package/dist/types/api/release.d.cts +17 -0
  360. package/dist/types/api/release.d.cts.map +1 -0
  361. package/dist/types/api/release.d.ts +17 -0
  362. package/dist/types/api/release.d.ts.map +1 -0
  363. package/dist/types/api/repository.d.cts +115 -0
  364. package/dist/types/api/repository.d.cts.map +1 -0
  365. package/dist/types/api/repository.d.ts +115 -0
  366. package/dist/types/api/repository.d.ts.map +1 -0
  367. package/dist/types/api/tags.d.cts +13 -0
  368. package/dist/types/api/tags.d.cts.map +1 -0
  369. package/dist/types/api/tags.d.ts +13 -0
  370. package/dist/types/api/tags.d.ts.map +1 -0
  371. package/dist/types/migration/Asset.cjs +35 -0
  372. package/dist/types/migration/Asset.cjs.map +1 -0
  373. package/dist/types/migration/Asset.d.cts +109 -0
  374. package/dist/types/migration/Asset.d.cts.map +1 -0
  375. package/dist/types/migration/Asset.d.ts +109 -0
  376. package/dist/types/migration/Asset.d.ts.map +1 -0
  377. package/dist/types/migration/Asset.js +34 -0
  378. package/dist/types/migration/Asset.js.map +1 -0
  379. package/dist/types/migration/ContentRelationship.d.cts +15 -0
  380. package/dist/types/migration/ContentRelationship.d.cts.map +1 -0
  381. package/dist/types/migration/ContentRelationship.d.ts +15 -0
  382. package/dist/types/migration/ContentRelationship.d.ts.map +1 -0
  383. package/dist/types/migration/Document.cjs +51 -0
  384. package/dist/types/migration/Document.cjs.map +1 -0
  385. package/dist/types/migration/Document.d.cts +97 -0
  386. package/dist/types/migration/Document.d.cts.map +1 -0
  387. package/dist/types/migration/Document.d.ts +97 -0
  388. package/dist/types/migration/Document.d.ts.map +1 -0
  389. package/dist/types/migration/Document.js +50 -0
  390. package/dist/types/migration/Document.js.map +1 -0
  391. package/dist/types/model/boolean.d.cts +21 -0
  392. package/dist/types/model/boolean.d.cts.map +1 -0
  393. package/dist/types/model/boolean.d.ts +21 -0
  394. package/dist/types/model/boolean.d.ts.map +1 -0
  395. package/dist/types/model/color.d.cts +19 -0
  396. package/dist/types/model/color.d.cts.map +1 -0
  397. package/dist/types/model/color.d.ts +19 -0
  398. package/dist/types/model/color.d.ts.map +1 -0
  399. package/dist/types/model/contentRelationship.d.cts +59 -0
  400. package/dist/types/model/contentRelationship.d.cts.map +1 -0
  401. package/dist/types/model/contentRelationship.d.ts +59 -0
  402. package/dist/types/model/contentRelationship.d.ts.map +1 -0
  403. package/dist/types/model/customType.d.cts +54 -0
  404. package/dist/types/model/customType.d.cts.map +1 -0
  405. package/dist/types/model/customType.d.ts +54 -0
  406. package/dist/types/model/customType.d.ts.map +1 -0
  407. package/dist/types/model/date.d.cts +20 -0
  408. package/dist/types/model/date.d.cts.map +1 -0
  409. package/dist/types/model/date.d.ts +20 -0
  410. package/dist/types/model/date.d.ts.map +1 -0
  411. package/dist/types/model/embed.d.cts +19 -0
  412. package/dist/types/model/embed.d.cts.map +1 -0
  413. package/dist/types/model/embed.d.ts +19 -0
  414. package/dist/types/model/embed.d.ts.map +1 -0
  415. package/dist/types/model/geoPoint.d.cts +18 -0
  416. package/dist/types/model/geoPoint.d.cts.map +1 -0
  417. package/dist/types/model/geoPoint.d.ts +18 -0
  418. package/dist/types/model/geoPoint.d.ts.map +1 -0
  419. package/dist/types/model/group.d.cts +29 -0
  420. package/dist/types/model/group.d.cts.map +1 -0
  421. package/dist/types/model/group.d.ts +29 -0
  422. package/dist/types/model/group.d.ts.map +1 -0
  423. package/dist/types/model/image.d.cts +37 -0
  424. package/dist/types/model/image.d.cts.map +1 -0
  425. package/dist/types/model/image.d.ts +37 -0
  426. package/dist/types/model/image.d.ts.map +1 -0
  427. package/dist/types/model/integration.d.cts +20 -0
  428. package/dist/types/model/integration.d.cts.map +1 -0
  429. package/dist/types/model/integration.d.ts +20 -0
  430. package/dist/types/model/integration.d.ts.map +1 -0
  431. package/dist/types/model/keyText.d.cts +19 -0
  432. package/dist/types/model/keyText.d.cts.map +1 -0
  433. package/dist/types/model/keyText.d.ts +19 -0
  434. package/dist/types/model/keyText.d.ts.map +1 -0
  435. package/dist/types/model/link.cjs +16 -0
  436. package/dist/types/model/link.cjs.map +1 -0
  437. package/dist/types/model/link.d.cts +34 -0
  438. package/dist/types/model/link.d.cts.map +1 -0
  439. package/dist/types/model/link.d.ts +34 -0
  440. package/dist/types/model/link.d.ts.map +1 -0
  441. package/dist/types/model/link.js +15 -0
  442. package/dist/types/model/link.js.map +1 -0
  443. package/dist/types/model/linkToMedia.d.cts +23 -0
  444. package/dist/types/model/linkToMedia.d.cts.map +1 -0
  445. package/dist/types/model/linkToMedia.d.ts +23 -0
  446. package/dist/types/model/linkToMedia.d.ts.map +1 -0
  447. package/dist/types/model/number.d.cts +21 -0
  448. package/dist/types/model/number.d.cts.map +1 -0
  449. package/dist/types/model/number.d.ts +21 -0
  450. package/dist/types/model/number.d.ts.map +1 -0
  451. package/dist/types/model/range.d.cts +20 -0
  452. package/dist/types/model/range.d.cts.map +1 -0
  453. package/dist/types/model/range.d.ts +20 -0
  454. package/dist/types/model/range.d.ts.map +1 -0
  455. package/dist/types/model/richText.d.cts +43 -0
  456. package/dist/types/model/richText.d.cts.map +1 -0
  457. package/dist/types/model/richText.d.ts +43 -0
  458. package/dist/types/model/richText.d.ts.map +1 -0
  459. package/dist/types/model/select.d.cts +24 -0
  460. package/dist/types/model/select.d.cts.map +1 -0
  461. package/dist/types/model/select.d.ts +24 -0
  462. package/dist/types/model/select.d.ts.map +1 -0
  463. package/dist/types/model/separator.d.cts +16 -0
  464. package/dist/types/model/separator.d.cts.map +1 -0
  465. package/dist/types/model/separator.d.ts +16 -0
  466. package/dist/types/model/separator.d.ts.map +1 -0
  467. package/dist/types/model/sharedSlice.d.cts +22 -0
  468. package/dist/types/model/sharedSlice.d.cts.map +1 -0
  469. package/dist/types/model/sharedSlice.d.ts +22 -0
  470. package/dist/types/model/sharedSlice.d.ts.map +1 -0
  471. package/dist/types/model/sharedSliceVariation.d.cts +25 -0
  472. package/dist/types/model/sharedSliceVariation.d.cts.map +1 -0
  473. package/dist/types/model/sharedSliceVariation.d.ts +25 -0
  474. package/dist/types/model/sharedSliceVariation.d.ts.map +1 -0
  475. package/dist/types/model/slice.cjs +15 -0
  476. package/dist/types/model/slice.cjs.map +1 -0
  477. package/dist/types/model/slice.d.cts +39 -0
  478. package/dist/types/model/slice.d.cts.map +1 -0
  479. package/dist/types/model/slice.d.ts +39 -0
  480. package/dist/types/model/slice.d.ts.map +1 -0
  481. package/dist/types/model/slice.js +14 -0
  482. package/dist/types/model/slice.js.map +1 -0
  483. package/dist/types/model/sliceZone.cjs +15 -0
  484. package/dist/types/model/sliceZone.cjs.map +1 -0
  485. package/dist/types/model/sliceZone.d.cts +47 -0
  486. package/dist/types/model/sliceZone.d.cts.map +1 -0
  487. package/dist/types/model/sliceZone.d.ts +47 -0
  488. package/dist/types/model/sliceZone.d.ts.map +1 -0
  489. package/dist/types/model/sliceZone.js +14 -0
  490. package/dist/types/model/sliceZone.js.map +1 -0
  491. package/dist/types/model/table.d.cts +18 -0
  492. package/dist/types/model/table.d.cts.map +1 -0
  493. package/dist/types/model/table.d.ts +18 -0
  494. package/dist/types/model/table.d.ts.map +1 -0
  495. package/dist/types/model/timestamp.d.cts +20 -0
  496. package/dist/types/model/timestamp.d.cts.map +1 -0
  497. package/dist/types/model/timestamp.d.ts +20 -0
  498. package/dist/types/model/timestamp.d.ts.map +1 -0
  499. package/dist/types/model/title.d.cts +13 -0
  500. package/dist/types/model/title.d.cts.map +1 -0
  501. package/dist/types/model/title.d.ts +13 -0
  502. package/dist/types/model/title.d.ts.map +1 -0
  503. package/dist/types/model/types.cjs +32 -0
  504. package/dist/types/model/types.cjs.map +1 -0
  505. package/dist/types/model/types.d.cts +82 -0
  506. package/dist/types/model/types.d.cts.map +1 -0
  507. package/dist/types/model/types.d.ts +82 -0
  508. package/dist/types/model/types.d.ts.map +1 -0
  509. package/dist/types/model/types.js +31 -0
  510. package/dist/types/model/types.js.map +1 -0
  511. package/dist/types/model/uid.d.cts +19 -0
  512. package/dist/types/model/uid.d.cts.map +1 -0
  513. package/dist/types/model/uid.d.ts +19 -0
  514. package/dist/types/model/uid.d.ts.map +1 -0
  515. package/dist/types/value/boolean.d.cts +10 -0
  516. package/dist/types/value/boolean.d.cts.map +1 -0
  517. package/dist/types/value/boolean.d.ts +10 -0
  518. package/dist/types/value/boolean.d.ts.map +1 -0
  519. package/dist/types/value/color.d.cts +15 -0
  520. package/dist/types/value/color.d.cts.map +1 -0
  521. package/dist/types/value/color.d.ts +15 -0
  522. package/dist/types/value/color.d.ts.map +1 -0
  523. package/dist/types/value/contentRelationship.d.cts +37 -0
  524. package/dist/types/value/contentRelationship.d.cts.map +1 -0
  525. package/dist/types/value/contentRelationship.d.ts +37 -0
  526. package/dist/types/value/contentRelationship.d.ts.map +1 -0
  527. package/dist/types/value/date.d.cts +15 -0
  528. package/dist/types/value/date.d.cts.map +1 -0
  529. package/dist/types/value/date.d.ts +15 -0
  530. package/dist/types/value/date.d.ts.map +1 -0
  531. package/dist/types/value/document.d.cts +120 -0
  532. package/dist/types/value/document.d.cts.map +1 -0
  533. package/dist/types/value/document.d.ts +120 -0
  534. package/dist/types/value/document.d.ts.map +1 -0
  535. package/dist/types/value/embed.cjs +17 -0
  536. package/dist/types/value/embed.cjs.map +1 -0
  537. package/dist/types/value/embed.d.cts +173 -0
  538. package/dist/types/value/embed.d.cts.map +1 -0
  539. package/dist/types/value/embed.d.ts +173 -0
  540. package/dist/types/value/embed.d.ts.map +1 -0
  541. package/dist/types/value/embed.js +16 -0
  542. package/dist/types/value/embed.js.map +1 -0
  543. package/dist/types/value/geoPoint.d.cts +18 -0
  544. package/dist/types/value/geoPoint.d.cts.map +1 -0
  545. package/dist/types/value/geoPoint.d.ts +18 -0
  546. package/dist/types/value/geoPoint.d.ts.map +1 -0
  547. package/dist/types/value/group.d.cts +19 -0
  548. package/dist/types/value/group.d.cts.map +1 -0
  549. package/dist/types/value/group.d.ts +19 -0
  550. package/dist/types/value/group.d.ts.map +1 -0
  551. package/dist/types/value/image.d.cts +53 -0
  552. package/dist/types/value/image.d.cts.map +1 -0
  553. package/dist/types/value/image.d.ts +53 -0
  554. package/dist/types/value/image.d.ts.map +1 -0
  555. package/dist/types/value/integration.d.cts +22 -0
  556. package/dist/types/value/integration.d.cts.map +1 -0
  557. package/dist/types/value/integration.d.ts +22 -0
  558. package/dist/types/value/integration.d.ts.map +1 -0
  559. package/dist/types/value/keyText.d.cts +15 -0
  560. package/dist/types/value/keyText.d.cts.map +1 -0
  561. package/dist/types/value/keyText.d.ts +15 -0
  562. package/dist/types/value/keyText.d.ts.map +1 -0
  563. package/dist/types/value/link.cjs +15 -0
  564. package/dist/types/value/link.cjs.map +1 -0
  565. package/dist/types/value/link.d.cts +74 -0
  566. package/dist/types/value/link.d.cts.map +1 -0
  567. package/dist/types/value/link.d.ts +74 -0
  568. package/dist/types/value/link.d.ts.map +1 -0
  569. package/dist/types/value/link.js +14 -0
  570. package/dist/types/value/link.js.map +1 -0
  571. package/dist/types/value/linkToMedia.d.cts +33 -0
  572. package/dist/types/value/linkToMedia.d.cts.map +1 -0
  573. package/dist/types/value/linkToMedia.d.ts +33 -0
  574. package/dist/types/value/linkToMedia.d.ts.map +1 -0
  575. package/dist/types/value/number.d.cts +15 -0
  576. package/dist/types/value/number.d.cts.map +1 -0
  577. package/dist/types/value/number.d.ts +15 -0
  578. package/dist/types/value/number.d.ts.map +1 -0
  579. package/dist/types/value/richText.cjs +32 -0
  580. package/dist/types/value/richText.cjs.map +1 -0
  581. package/dist/types/value/richText.d.cts +221 -0
  582. package/dist/types/value/richText.d.cts.map +1 -0
  583. package/dist/types/value/richText.d.ts +221 -0
  584. package/dist/types/value/richText.d.ts.map +1 -0
  585. package/dist/types/value/richText.js +31 -0
  586. package/dist/types/value/richText.js.map +1 -0
  587. package/dist/types/value/select.d.cts +16 -0
  588. package/dist/types/value/select.d.cts.map +1 -0
  589. package/dist/types/value/select.d.ts +16 -0
  590. package/dist/types/value/select.d.ts.map +1 -0
  591. package/dist/types/value/sharedSlice.d.cts +17 -0
  592. package/dist/types/value/sharedSlice.d.cts.map +1 -0
  593. package/dist/types/value/sharedSlice.d.ts +17 -0
  594. package/dist/types/value/sharedSlice.d.ts.map +1 -0
  595. package/dist/types/value/sharedSliceVariation.d.cts +16 -0
  596. package/dist/types/value/sharedSliceVariation.d.cts.map +1 -0
  597. package/dist/types/value/sharedSliceVariation.d.ts +16 -0
  598. package/dist/types/value/sharedSliceVariation.d.ts.map +1 -0
  599. package/dist/types/value/slice.d.cts +19 -0
  600. package/dist/types/value/slice.d.cts.map +1 -0
  601. package/dist/types/value/slice.d.ts +19 -0
  602. package/dist/types/value/slice.d.ts.map +1 -0
  603. package/dist/types/value/sliceZone.d.cts +18 -0
  604. package/dist/types/value/sliceZone.d.cts.map +1 -0
  605. package/dist/types/value/sliceZone.d.ts +18 -0
  606. package/dist/types/value/sliceZone.d.ts.map +1 -0
  607. package/dist/types/value/table.d.cts +97 -0
  608. package/dist/types/value/table.d.cts.map +1 -0
  609. package/dist/types/value/table.d.ts +97 -0
  610. package/dist/types/value/table.d.ts.map +1 -0
  611. package/dist/types/value/timestamp.d.cts +13 -0
  612. package/dist/types/value/timestamp.d.cts.map +1 -0
  613. package/dist/types/value/timestamp.d.ts +13 -0
  614. package/dist/types/value/timestamp.d.ts.map +1 -0
  615. package/dist/types/value/title.d.cts +16 -0
  616. package/dist/types/value/title.d.cts.map +1 -0
  617. package/dist/types/value/title.d.ts +16 -0
  618. package/dist/types/value/title.d.ts.map +1 -0
  619. package/dist/types/value/types.d.cts +61 -0
  620. package/dist/types/value/types.d.cts.map +1 -0
  621. package/dist/types/value/types.d.ts +61 -0
  622. package/dist/types/value/types.d.ts.map +1 -0
  623. package/dist/types/webhook/apiUpdate.d.cts +57 -0
  624. package/dist/types/webhook/apiUpdate.d.cts.map +1 -0
  625. package/dist/types/webhook/apiUpdate.d.ts +57 -0
  626. package/dist/types/webhook/apiUpdate.d.ts.map +1 -0
  627. package/dist/types/webhook/testTrigger.d.cts +15 -0
  628. package/dist/types/webhook/testTrigger.d.cts.map +1 -0
  629. package/dist/types/webhook/testTrigger.d.ts +15 -0
  630. package/dist/types/webhook/testTrigger.d.ts.map +1 -0
  631. package/dist/types/webhook/types.cjs +15 -0
  632. package/dist/types/webhook/types.cjs.map +1 -0
  633. package/dist/types/webhook/types.d.cts +23 -0
  634. package/dist/types/webhook/types.d.cts.map +1 -0
  635. package/dist/types/webhook/types.d.ts +23 -0
  636. package/dist/types/webhook/types.d.ts.map +1 -0
  637. package/dist/types/webhook/types.js +14 -0
  638. package/dist/types/webhook/types.js.map +1 -0
  639. package/package.json +29 -35
  640. package/src/Client.ts +682 -1028
  641. package/src/WriteClient.ts +44 -46
  642. package/src/buildQueryURL.ts +14 -20
  643. package/src/createClient.ts +1 -1
  644. package/src/errors.ts +94 -0
  645. package/src/getGraphQLEndpoint.ts +1 -1
  646. package/src/getRepositoryEndpoint.ts +1 -1
  647. package/src/getRepositoryName.ts +1 -1
  648. package/src/getToolbarSrc.ts +1 -1
  649. package/src/helpers/asHTML.ts +4 -4
  650. package/src/helpers/asImageWidthSrcSet.ts +1 -5
  651. package/src/helpers/asLink.ts +0 -3
  652. package/src/helpers/asLinkAttrs.ts +0 -4
  653. package/src/helpers/mapSliceZone.ts +5 -5
  654. package/src/index.ts +11 -8
  655. package/src/lib/isValue.ts +0 -6
  656. package/src/lib/pLimit.ts +1 -1
  657. package/src/lib/request.ts +3 -3
  658. package/src/lib/{throttledLog.ts → throttledWarn.ts} +3 -14
  659. package/src/lib/validateAssetMetadata.ts +1 -1
  660. package/src/types/migration/Document.ts +1 -1
  661. package/src/types/model/contentRelationship.ts +1 -0
  662. package/src/types/value/date.ts +1 -1
  663. package/src/types/value/document.ts +3 -3
  664. package/src/types/value/timestamp.ts +1 -5
  665. package/dist/index.d.mts +0 -4424
  666. package/dist/index.mjs +0 -3837
  667. package/dist/index.mjs.map +0 -1
  668. package/dist/richtext/index.cjs +0 -244
  669. package/dist/richtext/index.cjs.map +0 -1
  670. package/dist/richtext/index.d.cts +0 -78
  671. package/dist/richtext/index.d.mts +0 -78
  672. package/dist/richtext/index.d.ts +0 -78
  673. package/dist/richtext/index.mjs +0 -237
  674. package/dist/richtext/index.mjs.map +0 -1
  675. package/dist/shared/client.TSGr56lO.d.cts +0 -899
  676. package/dist/shared/client.TSGr56lO.d.mts +0 -899
  677. package/dist/shared/client.TSGr56lO.d.ts +0 -899
  678. package/src/errors/ForbiddenError.ts +0 -16
  679. package/src/errors/InvalidDataError.ts +0 -5
  680. package/src/errors/NotFoundError.ts +0 -5
  681. package/src/errors/ParsingError.ts +0 -16
  682. package/src/errors/PreviewTokenExpired.ts +0 -12
  683. package/src/errors/PrismicError.ts +0 -15
  684. package/src/errors/RefExpiredError.ts +0 -14
  685. package/src/errors/RefNotFoundError.ts +0 -14
  686. package/src/errors/RepositoryNotFoundError.ts +0 -5
  687. package/src/lib/appendFilters.ts +0 -26
  688. package/src/lib/castArray.ts +0 -14
  689. package/src/lib/castThunk.ts +0 -13
  690. package/src/lib/everyTagFilter.ts +0 -15
  691. package/src/lib/findMasterRef.ts +0 -16
  692. package/src/lib/findRef.ts +0 -25
  693. package/src/lib/findRefByID.ts +0 -17
  694. package/src/lib/findRefByLabel.ts +0 -17
  695. package/src/lib/minifyGraphQLQuery.ts +0 -13
  696. package/src/lib/someTagsFilter.ts +0 -15
  697. package/src/lib/typeFilter.ts +0 -12
package/dist/index.mjs DELETED
@@ -1,3837 +0,0 @@
1
- import { Element as RichTextNodeType, asText as asText$1, composeSerializers, serialize, wrapMapSerializer } from './richtext/index.mjs';
2
- import { buildURL, buildWidthSrcSet, buildPixelDensitySrcSet } from 'imgix-url-builder';
3
-
4
- function mapSliceZone(sliceZone, mappers, context) {
5
- return Promise.all(
6
- sliceZone.map(async (slice, index, slices) => {
7
- const isRestSliceType = "slice_type" in slice;
8
- const sliceType = isRestSliceType ? slice.slice_type : slice.type;
9
- const mapper = mappers[sliceType];
10
- if (!mapper) {
11
- return slice;
12
- }
13
- const mapperArgs = { slice, slices, index, context };
14
- let result = await mapper(
15
- // @ts-expect-error - I don't know how to fix this type
16
- mapperArgs
17
- );
18
- if (
19
- // `mapper.length < 1` ensures the given
20
- // function is something of the form:
21
- // `() => import(...)`
22
- mapper.length < 1 && (typeof result === "function" || typeof result === "object" && "default" in result)
23
- ) {
24
- result = "default" in result ? result.default : result;
25
- result = await result(mapperArgs);
26
- }
27
- if (isRestSliceType) {
28
- return {
29
- __mapped: true,
30
- id: slice.id,
31
- slice_type: sliceType,
32
- ...result
33
- };
34
- } else {
35
- return {
36
- __mapped: true,
37
- type: sliceType,
38
- ...result
39
- };
40
- }
41
- })
42
- );
43
- }
44
-
45
- const formatValue = (value) => {
46
- if (Array.isArray(value)) {
47
- return `[${value.map(formatValue).join(", ")}]`;
48
- }
49
- if (typeof value === "string") {
50
- return `"${value}"`;
51
- }
52
- if (value instanceof Date) {
53
- return `${value.getTime()}`;
54
- }
55
- return `${value}`;
56
- };
57
- const pathWithArgsFilter = (name) => {
58
- const fn = (path, ...args) => {
59
- const formattedArgs = args.map(formatValue).join(", ");
60
- const joiner = path && args.length ? ", " : "";
61
- return `[${name}(${path}${joiner}${formattedArgs})]`;
62
- };
63
- return fn;
64
- };
65
- const pathFilter = (name) => {
66
- const filterFn = pathWithArgsFilter(name);
67
- const fn = (path) => {
68
- return filterFn(path);
69
- };
70
- return fn;
71
- };
72
- const argsFilter = (name) => {
73
- const filterFn = pathWithArgsFilter(name);
74
- const fn = (...args) => {
75
- return filterFn("", ...args);
76
- };
77
- return fn;
78
- };
79
- const filter = {
80
- /**
81
- * The `at` filter checks that the path matches the described value exactly.
82
- * It takes a single value for a field or an array (only for tags).
83
- *
84
- * {@link https://prismic.io/docs/rest-api-technical-reference#at}
85
- */
86
- at: pathWithArgsFilter(
87
- "at"
88
- ),
89
- /**
90
- * The `not` filter checks that the path doesn't match the provided value
91
- * exactly. It takes a single value for a field or an array (only for tags).
92
- *
93
- * {@link https://prismic.io/docs/rest-api-technical-reference#not}
94
- */
95
- not: pathWithArgsFilter(
96
- "not"
97
- ),
98
- /**
99
- * The `any` filter takes an array of values. It works exactly the same way as
100
- * the `at` operator, but checks whether the fragment matches any of the
101
- * values in the array.
102
- *
103
- * {@link https://prismic.io/docs/rest-api-technical-reference#any}
104
- */
105
- any: pathWithArgsFilter(
106
- "any"
107
- ),
108
- /**
109
- * The `in` filter is used specifically to retrieve an array of documents by
110
- * their IDs or UIDs. This filter is much more efficient at this than the any
111
- * filter.
112
- *
113
- * {@link https://prismic.io/docs/rest-api-technical-reference#in}
114
- */
115
- in: pathWithArgsFilter("in"),
116
- /**
117
- * The `fulltext` filter provides two capabilities:
118
- *
119
- * 1. Checking if a certain string is anywhere inside a document (this is what
120
- * you should use to make your project's search engine feature)
121
- * 2. Checking if the string is contained inside a specific custom type’s Rich
122
- * Text or Key Text fragment.
123
- *
124
- * {@link https://prismic.io/docs/rest-api-technical-reference#fulltext}
125
- */
126
- fulltext: pathWithArgsFilter("fulltext"),
127
- /**
128
- * The `has` filter checks whether a fragment has a value. It will return all
129
- * the documents of the specified type that contain a value for the specified
130
- * field.
131
- *
132
- * {@link https://prismic.io/docs/rest-api-technical-reference#has}
133
- */
134
- has: pathFilter("has"),
135
- /**
136
- * The `missing` filter checks if a fragment doesn't have a value. It will
137
- * return all the documents of the specified type that do not contain a value
138
- * for the specified field.
139
- *
140
- * {@link https://prismic.io/docs/rest-api-technical-reference#missing}
141
- */
142
- missing: pathFilter("missing"),
143
- /**
144
- * The `similar` filter takes the ID of a document, and returns a list of
145
- * documents with similar content. This allows you to build an automated
146
- * content discovery feature (for example, a "Related posts" section).
147
- *
148
- * {@link https://prismic.io/docs/rest-api-technical-reference#similar}
149
- */
150
- similar: argsFilter("similar"),
151
- /**
152
- * The `geopoint.near` filter checks that the value in the path is within the
153
- * radius of the given coordinates.
154
- *
155
- * This filter will only work for a geopoint field.
156
- *
157
- * {@link https://prismic.io/docs/rest-api-technical-reference#geopointnear}
158
- */
159
- geopointNear: pathWithArgsFilter(
160
- "geopoint.near"
161
- ),
162
- /**
163
- * The `number.lt` filter checks that the value in the number field is less
164
- * than the value passed into the filter.
165
- *
166
- * {@link https://prismic.io/docs/rest-api-technical-reference#numberlessthan}
167
- */
168
- numberLessThan: pathWithArgsFilter("number.lt"),
169
- /**
170
- * The `number.gt` filter checks that the value in the number field is greater
171
- * than the value passed into the filter.
172
- *
173
- * {@link https://prismic.io/docs/rest-api-technical-reference#numbergreaterthan}
174
- */
175
- numberGreaterThan: pathWithArgsFilter("number.gt"),
176
- /**
177
- * The `number.inRange` filter checks that the value in the path is within the
178
- * two values passed into the filter.
179
- *
180
- * {@link https://prismic.io/docs/rest-api-technical-reference#numberinrange}
181
- */
182
- numberInRange: pathWithArgsFilter(
183
- "number.inRange"
184
- ),
185
- /**
186
- * The `date.after` filter checks that the value in the path is after the date
187
- * value passed into the filter.
188
- *
189
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
190
- */
191
- dateAfter: pathWithArgsFilter("date.after"),
192
- /**
193
- * The `date.before` filter checks that the value in the path is before the
194
- * date value passed into the filter.
195
- *
196
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
197
- */
198
- dateBefore: pathWithArgsFilter("date.before"),
199
- /**
200
- * The `date.between` filter checks that the value in the path is within the
201
- * date values passed into the filter.
202
- *
203
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
204
- */
205
- dateBetween: pathWithArgsFilter("date.between"),
206
- /**
207
- * The `date.day-of-month` filter checks that the value in the path is equal
208
- * to the day of the month passed into the filter.
209
- *
210
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
211
- */
212
- dateDayOfMonth: pathWithArgsFilter("date.day-of-month"),
213
- /**
214
- * The `date.day-of-month-after` filter checks that the value in the path is
215
- * after the day of the month passed into the filter.
216
- *
217
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
218
- */
219
- dateDayOfMonthAfter: pathWithArgsFilter(
220
- "date.day-of-month-after"
221
- ),
222
- /**
223
- * The `date.day-of-month-before` filter checks that the value in the path is
224
- * before the day of the month passed into the filter.
225
- *
226
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
227
- */
228
- dateDayOfMonthBefore: pathWithArgsFilter(
229
- "date.day-of-month-before"
230
- ),
231
- /**
232
- * The `date.day-of-week` filter checks that the value in the path is equal to
233
- * the day of the week passed into the filter.
234
- *
235
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
236
- */
237
- dateDayOfWeek: pathWithArgsFilter("date.day-of-week"),
238
- /**
239
- * The `date.day-of-week-after` filter checks that the value in the path is
240
- * after the day of the week passed into the filter.
241
- *
242
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
243
- */
244
- dateDayOfWeekAfter: pathWithArgsFilter(
245
- "date.day-of-week-after"
246
- ),
247
- /**
248
- * The date.day-of-week-before filter checks that the value in the path is
249
- * before the day of the week passed into the filter.
250
- *
251
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
252
- */
253
- dateDayOfWeekBefore: pathWithArgsFilter(
254
- "date.day-of-week-before"
255
- ),
256
- /**
257
- * The `date.month` filter checks that the value in the path occurs in the
258
- * month value passed into the filter.
259
- *
260
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
261
- */
262
- dateMonth: pathWithArgsFilter("date.month"),
263
- /**
264
- * The `date.month-after` filter checks that the value in the path occurs in
265
- * any month after the value passed into the filter.
266
- *
267
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
268
- */
269
- dateMonthAfter: pathWithArgsFilter("date.month-after"),
270
- /**
271
- * The `date.month-before` filter checks that the value in the path occurs in
272
- * any month before the value passed into the filter.
273
- *
274
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
275
- */
276
- dateMonthBefore: pathWithArgsFilter("date.month-before"),
277
- /**
278
- * The `date.year` filter checks that the value in the path occurs in the year
279
- * value passed into the filter.
280
- *
281
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
282
- */
283
- dateYear: pathWithArgsFilter("date.year"),
284
- /**
285
- * The `date.hour` filter checks that the value in the path occurs within the
286
- * hour value passed into the filter.
287
- *
288
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
289
- */
290
- dateHour: pathWithArgsFilter("date.hour"),
291
- /**
292
- * The `date.hour-after` filter checks that the value in the path occurs after
293
- * the hour value passed into the filter.
294
- *
295
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
296
- */
297
- dateHourAfter: pathWithArgsFilter("date.hour-after"),
298
- /**
299
- * The `date.hour-before` filter checks that the value in the path occurs
300
- * before the hour value passed into the filter.
301
- *
302
- * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters}
303
- */
304
- dateHourBefore: pathWithArgsFilter("date.hour-before")
305
- };
306
-
307
- const castArray = (a) => {
308
- return Array.isArray(a) ? a : [a];
309
- };
310
-
311
- const appendFilters = (objWithFilters = {}, filters) => {
312
- return {
313
- ...objWithFilters,
314
- filters: [...objWithFilters.filters || [], ...castArray(filters)]
315
- };
316
- };
317
-
318
- const castThunk = (a) => {
319
- return typeof a === "function" ? a : () => a;
320
- };
321
-
322
- const name = "@prismicio/client";
323
- const version = "7.21.0-alpha.2";
324
-
325
- const devMsg = (slug) => {
326
- return `https://prismic.dev/msg/client/v${version}/${slug}`;
327
- };
328
-
329
- const everyTagFilter = (tags) => {
330
- return filter.at("document.tags", castArray(tags));
331
- };
332
-
333
- class PrismicError extends Error {
334
- url;
335
- response;
336
- constructor(message = "An invalid API response was returned", url, response) {
337
- super(message);
338
- this.url = url;
339
- this.response = response;
340
- }
341
- }
342
-
343
- const findRef = (refs, filter) => {
344
- const ref = refs.find((ref2) => filter(ref2));
345
- if (!ref) {
346
- throw new PrismicError("Ref could not be found.", void 0, void 0);
347
- }
348
- return ref;
349
- };
350
-
351
- const findMasterRef = (refs) => {
352
- return findRef(refs, (ref) => ref.isMasterRef);
353
- };
354
-
355
- const findRefByID = (refs, id) => {
356
- return findRef(refs, (ref) => ref.id === id);
357
- };
358
-
359
- const findRefByLabel = (refs, label) => {
360
- return findRef(refs, (ref) => ref.label === label);
361
- };
362
-
363
- const preview = "io.prismic.preview";
364
-
365
- const cookie = {
366
- __proto__: null,
367
- preview: preview
368
- };
369
-
370
- const readValue = (value) => {
371
- return value.replace(/%3B/g, ";");
372
- };
373
- const getPreviewCookie = (cookieJar) => {
374
- const cookies = cookieJar.split("; ");
375
- let value;
376
- for (const cookie of cookies) {
377
- const parts = cookie.split("=");
378
- const name = readValue(parts[0]).replace(/%3D/g, "=");
379
- if (name === preview) {
380
- value = readValue(parts.slice(1).join("="));
381
- break;
382
- }
383
- }
384
- return value;
385
- };
386
-
387
- const minifyGraphQLQuery = (query) => {
388
- return query.replace(
389
- /(\n| )*( |{|})(\n| )*/gm,
390
- (_chars, _spaces, brackets) => brackets
391
- );
392
- };
393
-
394
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
395
- const pLimit = ({
396
- interval
397
- } = {}) => {
398
- const queue = [];
399
- let busy = false;
400
- let lastCompletion = 0;
401
- const resumeNext = () => {
402
- if (!busy && queue.length > 0) {
403
- queue.shift()?.();
404
- busy = true;
405
- }
406
- };
407
- const next = () => {
408
- busy = false;
409
- resumeNext();
410
- };
411
- const run = async (function_, resolve, arguments_) => {
412
- const timeSinceLastCompletion = Date.now() - lastCompletion;
413
- if (interval && timeSinceLastCompletion < interval) {
414
- await sleep(interval - timeSinceLastCompletion);
415
- }
416
- const result = (async () => function_(...arguments_))();
417
- resolve(result);
418
- try {
419
- await result;
420
- } catch {
421
- }
422
- lastCompletion = Date.now();
423
- next();
424
- };
425
- const enqueue = (function_, resolve, arguments_) => {
426
- new Promise((internalResolve) => {
427
- queue.push(internalResolve);
428
- }).then(run.bind(void 0, function_, resolve, arguments_));
429
- (async () => {
430
- await Promise.resolve();
431
- if (!busy) {
432
- resumeNext();
433
- }
434
- })();
435
- };
436
- return ((function_, ...arguments_) => new Promise((resolve) => {
437
- enqueue(function_, resolve, arguments_);
438
- }));
439
- };
440
-
441
- const DEFAULT_RETRY_AFTER = 1500;
442
- const THROTTLED_RUNNERS = {};
443
- const DEDUPLICATED_JOBS = {};
444
- async function request(url, init, fetchFn) {
445
- const stringURL = url.toString();
446
- let job;
447
- if (init?.body) {
448
- const runner = THROTTLED_RUNNERS[url.hostname] ||= pLimit({
449
- interval: DEFAULT_RETRY_AFTER
450
- });
451
- job = runner(() => fetchFn(stringURL, init));
452
- } else {
453
- const existingJob = DEDUPLICATED_JOBS[stringURL]?.get(init?.signal);
454
- if (existingJob) {
455
- job = existingJob;
456
- } else {
457
- job = fetchFn(stringURL, init).finally(() => {
458
- DEDUPLICATED_JOBS[stringURL]?.delete(init?.signal);
459
- if (DEDUPLICATED_JOBS[stringURL]?.size === 0) {
460
- delete DEDUPLICATED_JOBS[stringURL];
461
- }
462
- });
463
- const map = DEDUPLICATED_JOBS[stringURL] ||= /* @__PURE__ */ new Map();
464
- map.set(init?.signal, job);
465
- }
466
- }
467
- const response = await job;
468
- if (response.status === 429) {
469
- const retryAfter = Number(response.headers.get("retry-after"));
470
- const resolvedRetryAfter = Number.isNaN(retryAfter) ? DEFAULT_RETRY_AFTER : retryAfter * 1e3;
471
- await new Promise((resolve) => setTimeout(resolve, resolvedRetryAfter));
472
- return request(url, init, fetchFn);
473
- }
474
- return response.clone();
475
- }
476
-
477
- const someTagsFilter = (tags) => {
478
- return filter.any("document.tags", castArray(tags));
479
- };
480
-
481
- const THROTTLE_THRESHOLD_MS = 5e3;
482
- let lastMessage;
483
- let lastCalledAt = 0;
484
- const throttledLog = (message, config = {}) => {
485
- const { level = "log" } = config;
486
- if (message === lastMessage && Date.now() - lastCalledAt < THROTTLE_THRESHOLD_MS) {
487
- lastCalledAt = Date.now();
488
- return;
489
- }
490
- lastCalledAt = Date.now();
491
- lastMessage = message;
492
- console[level](message);
493
- };
494
-
495
- const typeFilter = (documentType) => {
496
- return filter.at("document.type", documentType);
497
- };
498
-
499
- class ForbiddenError extends PrismicError {
500
- }
501
-
502
- class NotFoundError extends PrismicError {
503
- }
504
-
505
- class ParsingError extends PrismicError {
506
- }
507
-
508
- class PreviewTokenExpiredError extends ForbiddenError {
509
- }
510
-
511
- class RefExpiredError extends ForbiddenError {
512
- }
513
-
514
- class RefNotFoundError extends ForbiddenError {
515
- }
516
-
517
- class RepositoryNotFoundError extends NotFoundError {
518
- }
519
-
520
- const LinkType = {
521
- Any: "Any",
522
- Document: "Document",
523
- Media: "Media",
524
- Web: "Web"
525
- };
526
-
527
- const documentToLinkField = (prismicDocument) => {
528
- return {
529
- link_type: LinkType.Document,
530
- id: prismicDocument.id,
531
- uid: prismicDocument.uid || void 0,
532
- type: prismicDocument.type,
533
- tags: prismicDocument.tags,
534
- lang: prismicDocument.lang,
535
- url: prismicDocument.url == null ? void 0 : prismicDocument.url,
536
- slug: prismicDocument.slugs?.[0],
537
- // Slug field is not available with GraphQL
538
- // The REST API does not include a `data` property if the data
539
- // object is empty.
540
- //
541
- // A presence check for `prismicDocument.data` is done to
542
- // support partial documents. While `documentToLinkField` is
543
- // not typed to accept partial documents, passing a partial
544
- // document can happen in untyped projects.
545
- ...prismicDocument.data && Object.keys(prismicDocument.data).length > 0 ? { data: prismicDocument.data } : {}
546
- };
547
- };
548
-
549
- const asLink = (linkFieldOrDocument, ...configObjectOrTuple) => {
550
- if (!linkFieldOrDocument) {
551
- return null;
552
- }
553
- const linkField = (
554
- // prettier-ignore
555
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
556
- // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501
557
- // TODO: Remove the `prettier-ignore` comment when this bug is fixed.
558
- "link_type" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument)
559
- );
560
- const [configObjectOrLinkResolver] = configObjectOrTuple;
561
- let config;
562
- if (typeof configObjectOrLinkResolver === "function" || configObjectOrLinkResolver == null) {
563
- config = {
564
- linkResolver: configObjectOrLinkResolver
565
- };
566
- } else {
567
- config = { ...configObjectOrLinkResolver };
568
- }
569
- switch (linkField.link_type) {
570
- case LinkType.Media:
571
- case LinkType.Web:
572
- return "url" in linkField ? linkField.url : null;
573
- case LinkType.Document: {
574
- if ("id" in linkField && config.linkResolver) {
575
- const resolvedURL = config.linkResolver(linkField);
576
- if (resolvedURL != null) {
577
- return resolvedURL;
578
- }
579
- }
580
- if ("url" in linkField && linkField.url) {
581
- return linkField.url;
582
- }
583
- return null;
584
- }
585
- case LinkType.Any:
586
- default:
587
- return null;
588
- }
589
- };
590
-
591
- const PRISMIC_DEV_PARAM = "x-d";
592
- const PRISMIC_CLIENT_VERSION_PARAM = "x-c";
593
- const RENAMED_PARAMS = {
594
- accessToken: "access_token"
595
- };
596
- const castOrderingToString = (ordering) => {
597
- if (typeof ordering === "string") {
598
- if (process.env.NODE_ENV === "development") {
599
- const [field, direction] = ordering.split(" ");
600
- const objectForm = direction === "desc" ? `{ field: "${field}", direction: "desc" }` : `{ field: "${field}" }`;
601
- console.warn(
602
- `[@prismicio/client] A string value was provided to the \`orderings\` query parameter. Strings are deprecated. Please convert it to the object form: ${objectForm}. For more details, see ${devMsg(
603
- "orderings-must-be-an-array-of-objects"
604
- )}`
605
- );
606
- }
607
- return ordering;
608
- }
609
- return ordering.direction === "desc" ? `${ordering.field} desc` : ordering.field;
610
- };
611
- const buildQueryURL = (endpoint, args) => {
612
- const { filters, predicates, ...params } = args;
613
- const url = new URL(`documents/search`, `${endpoint}/`);
614
- if (filters) {
615
- if (process.env.NODE_ENV === "development" && !Array.isArray(filters)) {
616
- console.warn(
617
- `[@prismicio/client] A non-array value was provided to the \`filters\` query parameter (\`${filters}\`). Non-array values are deprecated. Please convert it to an array. For more details, see ${devMsg(
618
- "filters-must-be-an-array"
619
- )}`
620
- );
621
- }
622
- for (const filter of castArray(filters)) {
623
- url.searchParams.append("q", `[${filter}]`);
624
- }
625
- }
626
- if (predicates) {
627
- for (const predicate of castArray(predicates)) {
628
- url.searchParams.append("q", `[${predicate}]`);
629
- }
630
- }
631
- for (const k in params) {
632
- const name = RENAMED_PARAMS[k] || k;
633
- let value = params[k];
634
- if (name === "orderings") {
635
- const scopedValue = params[name];
636
- if (scopedValue != null) {
637
- if (process.env.NODE_ENV === "development" && typeof scopedValue === "string") {
638
- console.warn(
639
- `[@prismicio/client] A string value was provided to the \`orderings\` query parameter. Strings are deprecated. Please convert it to an array of objects. For more details, see ${devMsg(
640
- "orderings-must-be-an-array-of-objects"
641
- )}`
642
- );
643
- }
644
- const v = castArray(scopedValue).map((ordering) => castOrderingToString(ordering)).join(",");
645
- value = `[${v}]`;
646
- }
647
- } else if (name === "routes") {
648
- if (typeof params[name] === "object") {
649
- value = JSON.stringify(castArray(params[name]));
650
- }
651
- }
652
- if (value != null) {
653
- url.searchParams.set(
654
- name,
655
- castArray(value).join(",")
656
- );
657
- }
658
- }
659
- url.searchParams.set(PRISMIC_CLIENT_VERSION_PARAM, `js-${version}`);
660
- if (process.env.NODE_ENV === "development") {
661
- url.searchParams.set(PRISMIC_DEV_PARAM, "1");
662
- }
663
- return url.toString();
664
- };
665
-
666
- const isRepositoryName = (input) => {
667
- return /^[a-zA-Z0-9][-a-zA-Z0-9]{2,}[a-zA-Z0-9]$/.test(input);
668
- };
669
-
670
- const getRepositoryEndpoint = (repositoryName) => {
671
- if (isRepositoryName(repositoryName)) {
672
- return `https://${repositoryName}.cdn.prismic.io/api/v2`;
673
- } else {
674
- throw new PrismicError(
675
- `An invalid Prismic repository name was given: ${repositoryName}`,
676
- void 0,
677
- void 0
678
- );
679
- }
680
- };
681
-
682
- const getRepositoryName = (repositoryEndpoint) => {
683
- try {
684
- const hostname = new URL(repositoryEndpoint).hostname;
685
- if (hostname.endsWith("prismic.io") || // Production
686
- hostname.endsWith("wroom.io") || // Staging
687
- hostname.endsWith("wroom.test")) {
688
- return hostname.split(".")[0];
689
- }
690
- } catch {
691
- }
692
- throw new PrismicError(
693
- `An invalid Prismic Document API endpoint was provided: ${repositoryEndpoint}`,
694
- void 0,
695
- void 0
696
- );
697
- };
698
-
699
- const isRepositoryEndpoint = (input) => {
700
- try {
701
- new URL(input);
702
- return true;
703
- } catch {
704
- return false;
705
- }
706
- };
707
-
708
- const MAX_PAGE_SIZE = 100;
709
- const REPOSITORY_CACHE_TTL = 5e3;
710
- const GET_ALL_QUERY_DELAY = 500;
711
- const MAX_INVALID_REF_RETRY_ATTEMPTS = 3;
712
- class Client {
713
- /**
714
- * The function used to make network requests to the Prismic REST API. In
715
- * environments where a global `fetch` function does not exist, such as
716
- * Node.js, this function must be provided.
717
- */
718
- fetchFn;
719
- fetchOptions;
720
- #repositoryName;
721
- /**
722
- * The Prismic repository's name.
723
- */
724
- set repositoryName(value) {
725
- this.#repositoryName = value;
726
- }
727
- /**
728
- * The Prismic repository's name.
729
- */
730
- get repositoryName() {
731
- if (!this.#repositoryName) {
732
- throw new PrismicError(
733
- `A repository name is required for this method but one could not be inferred from the provided API endpoint (\`${this.documentAPIEndpoint}\`). To fix this error, provide a repository name when creating the client. For more details, see ${devMsg("prefer-repository-name")}`,
734
- void 0,
735
- void 0
736
- );
737
- }
738
- return this.#repositoryName;
739
- }
740
- /**
741
- * The Prismic REST API V2 endpoint for the repository (use
742
- * `prismic.getRepositoryEndpoint` for the default endpoint).
743
- */
744
- documentAPIEndpoint;
745
- /**
746
- * The Prismic REST API V2 endpoint for the repository (use
747
- * `prismic.getRepositoryEndpoint` for the default endpoint).
748
- *
749
- * @deprecated Use `documentAPIEndpoint` instead.
750
- */
751
- // TODO: Remove in v8.
752
- set endpoint(value) {
753
- this.documentAPIEndpoint = value;
754
- }
755
- /**
756
- * The Prismic REST API V2 endpoint for the repository (use
757
- * `prismic.getRepositoryEndpoint` for the default endpoint).
758
- *
759
- * @deprecated Use `documentAPIEndpoint` instead.
760
- */
761
- // TODO: Remove in v8.
762
- get endpoint() {
763
- return this.documentAPIEndpoint;
764
- }
765
- /**
766
- * The secure token for accessing the API (only needed if your repository is
767
- * set to private).
768
- *
769
- * {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token}
770
- */
771
- accessToken;
772
- /**
773
- * A list of route resolver objects that define how a document's `url` field
774
- * is resolved.
775
- *
776
- * {@link https://prismic.io/docs/route-resolver}
777
- */
778
- routes;
779
- /**
780
- * The `brokenRoute` option allows you to define the route populated in the
781
- * `url` property for broken link or content relationship fields. A broken
782
- * link is a link or content relationship field whose linked document has been
783
- * unpublished or deleted.
784
- *
785
- * {@link https://prismic.io/docs/route-resolver}
786
- */
787
- brokenRoute;
788
- /**
789
- * Default parameters that will be sent with each query. These parameters can
790
- * be overridden on each query if needed.
791
- */
792
- defaultParams;
793
- /**
794
- * The client's ref mode state. This determines which ref is used during
795
- * queries.
796
- */
797
- refState = {
798
- mode: "Master" /* Master */,
799
- autoPreviewsEnabled: true
800
- };
801
- /**
802
- * Cached repository value.
803
- */
804
- cachedRepository;
805
- /**
806
- * Timestamp at which the cached repository data is considered stale.
807
- */
808
- cachedRepositoryExpiration = 0;
809
- /**
810
- * Creates a Prismic client that can be used to query a repository.
811
- *
812
- * If used in an environment where a global `fetch` function is unavailable,
813
- * such as in some Node.js versions, the `fetch` option must be provided as
814
- * part of the `options` parameter.
815
- *
816
- * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
817
- * API V2 endpoint for the repository.
818
- * @param options - Configuration that determines how content will be queried
819
- * from the Prismic repository.
820
- *
821
- * @returns A client that can query content from the repository.
822
- */
823
- constructor(repositoryNameOrEndpoint, options = {}) {
824
- this.fetchOptions = options.fetchOptions;
825
- if (typeof options.fetch === "function") {
826
- this.fetchFn = options.fetch;
827
- } else if (typeof globalThis.fetch === "function") {
828
- this.fetchFn = globalThis.fetch;
829
- } else {
830
- throw new PrismicError(
831
- "A valid fetch implementation was not provided. In environments where fetch is not available (including Node.js), a fetch implementation must be provided via a polyfill or the `fetch` option.",
832
- void 0,
833
- void 0
834
- );
835
- }
836
- if (this.fetchFn === globalThis.fetch) {
837
- this.fetchFn = this.fetchFn.bind(globalThis);
838
- }
839
- if ((options.documentAPIEndpoint || isRepositoryEndpoint(repositoryNameOrEndpoint)) && process.env.NODE_ENV === "development") {
840
- const documentAPIEndpoint = options.documentAPIEndpoint || repositoryNameOrEndpoint;
841
- if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(documentAPIEndpoint)) {
842
- throw new PrismicError(
843
- "@prismicio/client only supports Prismic Rest API V2. Please provide only the repository name to the first createClient() parameter or use the getRepositoryEndpoint() helper to generate a valid Rest API V2 endpoint URL.",
844
- void 0,
845
- void 0
846
- );
847
- }
848
- const hostname = new URL(documentAPIEndpoint).hostname.toLowerCase();
849
- if (hostname.endsWith(".prismic.io") && !hostname.endsWith(".cdn.prismic.io")) {
850
- console.warn(
851
- `[@prismicio/client] The client was created with a non-CDN endpoint. Convert it to the CDN endpoint for better performance. For more details, see ${devMsg("endpoint-must-use-cdn")}`
852
- );
853
- }
854
- if (options.documentAPIEndpoint && isRepositoryEndpoint(repositoryNameOrEndpoint) && repositoryNameOrEndpoint !== options.documentAPIEndpoint) {
855
- console.warn(
856
- `[@prismicio/client] Multiple incompatible endpoints were provided. Create the client using a repository name to prevent this error. For more details, see ${devMsg("prefer-repository-name")}`
857
- );
858
- }
859
- }
860
- if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
861
- this.documentAPIEndpoint = repositoryNameOrEndpoint;
862
- try {
863
- this.repositoryName = getRepositoryName(repositoryNameOrEndpoint);
864
- } catch (error) {
865
- console.warn(
866
- `[@prismicio/client] A repository name could not be inferred from the provided endpoint (\`${repositoryNameOrEndpoint}\`). Some methods will be disabled. Create the client using a repository name to prevent this warning. For more details, see ${devMsg("prefer-repository-name")}`
867
- );
868
- }
869
- } else {
870
- this.documentAPIEndpoint = options.documentAPIEndpoint || getRepositoryEndpoint(repositoryNameOrEndpoint);
871
- this.repositoryName = repositoryNameOrEndpoint;
872
- }
873
- this.accessToken = options.accessToken;
874
- this.routes = options.routes;
875
- this.brokenRoute = options.brokenRoute;
876
- this.defaultParams = options.defaultParams;
877
- if (options.ref) {
878
- this.queryContentFromRef(options.ref);
879
- }
880
- this.graphQLFetch = this.graphQLFetch.bind(this);
881
- }
882
- /**
883
- * Enables the client to automatically query content from a preview session if
884
- * one is active in browser environments. This is enabled by default in the
885
- * browser.
886
- *
887
- * For server environments, use `enableAutoPreviewsFromReq`.
888
- *
889
- * @example
890
- *
891
- * ```ts
892
- * client.enableAutoPreviews()
893
- * ```
894
- *
895
- * @see enableAutoPreviewsFromReq
896
- */
897
- enableAutoPreviews() {
898
- this.refState.autoPreviewsEnabled = true;
899
- }
900
- /**
901
- * Enables the client to automatically query content from a preview session if
902
- * one is active in server environments. This is disabled by default on the
903
- * server.
904
- *
905
- * For browser environments, use `enableAutoPreviews`.
906
- *
907
- * @example
908
- *
909
- * ```ts
910
- * // In an express app
911
- * app.get("/", function (req, res) {
912
- * client.enableAutoPreviewsFromReq(req)
913
- * })
914
- * ```
915
- *
916
- * @param req - An HTTP server request object containing the request's
917
- * cookies.
918
- */
919
- enableAutoPreviewsFromReq(req) {
920
- this.refState.httpRequest = req;
921
- this.refState.autoPreviewsEnabled = true;
922
- }
923
- /**
924
- * Disables the client from automatically querying content from a preview
925
- * session if one is active.
926
- *
927
- * Automatic preview content querying is enabled by default unless this method
928
- * is called.
929
- *
930
- * @example
931
- *
932
- * ```ts
933
- * client.disableAutoPreviews()
934
- * ```
935
- */
936
- disableAutoPreviews() {
937
- this.refState.autoPreviewsEnabled = false;
938
- }
939
- /**
940
- * Queries content from the Prismic repository.
941
- *
942
- * @example
943
- *
944
- * ```ts
945
- * const response = await client.get()
946
- * ```
947
- *
948
- * @typeParam TDocument - Type of Prismic documents returned.
949
- *
950
- * @param params - Parameters to filter, sort, and paginate results.
951
- *
952
- * @returns A paginated response containing the result of the query.
953
- */
954
- async get(params) {
955
- const { data } = await this._get(params);
956
- return data;
957
- }
958
- /**
959
- * Queries content from the Prismic repository and returns only the first
960
- * result, if any.
961
- *
962
- * @example
963
- *
964
- * ```ts
965
- * const document = await client.getFirst()
966
- * ```
967
- *
968
- * @typeParam TDocument - Type of the Prismic document returned.
969
- *
970
- * @param params - Parameters to filter, sort, and paginate results.
971
- *
972
- * @returns The first result of the query, if any.
973
- */
974
- async getFirst(params) {
975
- const actualParams = { ...params };
976
- if (!(params && params.page) && !params?.pageSize) {
977
- actualParams.pageSize = this.defaultParams?.pageSize ?? 1;
978
- }
979
- const { data, url } = await this._get(actualParams);
980
- const firstResult = data.results[0];
981
- if (firstResult) {
982
- return firstResult;
983
- }
984
- throw new NotFoundError("No documents were returned", url, void 0);
985
- }
986
- /**
987
- * **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
988
- * require more resources than other methods. Prefer using other methods that
989
- * filter by filters such as `getAllByType`.
990
- *
991
- * Queries content from the Prismic repository and returns all matching
992
- * content. If no filters are provided, all documents will be fetched.
993
- *
994
- * This method may make multiple network requests to query all matching
995
- * content.
996
- *
997
- * @example
998
- *
999
- * ```ts
1000
- * const response = await client.dangerouslyGetAll()
1001
- * ```
1002
- *
1003
- * @typeParam TDocument - Type of Prismic documents returned.
1004
- *
1005
- * @param params - Parameters to filter, sort, and paginate results.
1006
- *
1007
- * @returns A list of documents matching the query.
1008
- */
1009
- async dangerouslyGetAll(params = {}) {
1010
- const { limit = Infinity, ...actualParams } = params;
1011
- const resolvedParams = {
1012
- ...actualParams,
1013
- pageSize: Math.min(
1014
- limit,
1015
- actualParams.pageSize || this.defaultParams?.pageSize || MAX_PAGE_SIZE
1016
- )
1017
- };
1018
- const documents = [];
1019
- let latestResult;
1020
- while ((!latestResult || latestResult.next_page) && documents.length < limit) {
1021
- const page = latestResult ? latestResult.page + 1 : void 0;
1022
- latestResult = await this.get({ ...resolvedParams, page });
1023
- documents.push(...latestResult.results);
1024
- if (latestResult.next_page) {
1025
- await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY));
1026
- }
1027
- }
1028
- return documents.slice(0, limit);
1029
- }
1030
- /**
1031
- * Queries a document from the Prismic repository with a specific ID.
1032
- *
1033
- * @remarks
1034
- * A document's UID is different from its ID. An ID is automatically generated
1035
- * for all documents and is made available on its `id` property. A UID is
1036
- * provided in the Prismic editor and is unique among all documents of its
1037
- * custom type.
1038
- *
1039
- * @example
1040
- *
1041
- * ```ts
1042
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1043
- * ```
1044
- *
1045
- * @typeParam TDocument- Type of the Prismic document returned.
1046
- *
1047
- * @param id - ID of the document.
1048
- * @param params - Parameters to filter, sort, and paginate the results.
1049
- *
1050
- * @returns The document with an ID matching the `id` parameter, if a matching
1051
- * document exists.
1052
- */
1053
- async getByID(id, params) {
1054
- return await this.getFirst(
1055
- appendFilters(params, filter.at("document.id", id))
1056
- );
1057
- }
1058
- /**
1059
- * Queries documents from the Prismic repository with specific IDs.
1060
- *
1061
- * @remarks
1062
- * A document's UID is different from its ID. An ID is automatically generated
1063
- * for all documents and is made available on its `id` property. A UID is
1064
- * provided in the Prismic editor and is unique among all documents of its
1065
- * custom type.
1066
- *
1067
- * @example
1068
- *
1069
- * ```ts
1070
- * const response = await client.getByIDs([
1071
- * "WW4bKScAAMAqmluX",
1072
- * "U1kTRgEAAC8A5ldS",
1073
- * ])
1074
- * ```
1075
- *
1076
- * @typeParam TDocument - Type of Prismic documents returned.
1077
- *
1078
- * @param ids - A list of document IDs.
1079
- * @param params - Parameters to filter, sort, and paginate the results.
1080
- *
1081
- * @returns A paginated response containing documents with IDs matching the
1082
- * `ids` parameter.
1083
- */
1084
- async getByIDs(ids, params) {
1085
- return await this.get(
1086
- appendFilters(params, filter.in("document.id", ids))
1087
- );
1088
- }
1089
- /**
1090
- * Queries all documents from the Prismic repository with specific IDs.
1091
- *
1092
- * This method may make multiple network requests to query all matching
1093
- * content.
1094
- *
1095
- * @remarks
1096
- * A document's UID is different from its ID. An ID is automatically generated
1097
- * for all documents and is made available on its `id` property. A UID is
1098
- * provided in the Prismic editor and is unique among all documents of its
1099
- * custom type.
1100
- *
1101
- * @example
1102
- *
1103
- * ```ts
1104
- * const response = await client.getAllByIDs([
1105
- * "WW4bKScAAMAqmluX",
1106
- * "U1kTRgEAAC8A5ldS",
1107
- * ])
1108
- * ```
1109
- *
1110
- * @typeParam TDocument - Type of Prismic documents returned.
1111
- *
1112
- * @param ids - A list of document IDs.
1113
- * @param params - Parameters to filter, sort, and paginate the results.
1114
- *
1115
- * @returns A list of documents with IDs matching the `ids` parameter.
1116
- */
1117
- async getAllByIDs(ids, params) {
1118
- return await this.dangerouslyGetAll(
1119
- appendFilters(params, filter.in("document.id", ids))
1120
- );
1121
- }
1122
- /**
1123
- * Queries a document from the Prismic repository with a specific UID and
1124
- * custom type.
1125
- *
1126
- * @remarks
1127
- * A document's UID is different from its ID. An ID is automatically generated
1128
- * for all documents and is made available on its `id` property. A UID is
1129
- * provided in the Prismic editor and is unique among all documents of its
1130
- * custom type.
1131
- *
1132
- * @example
1133
- *
1134
- * ```ts
1135
- * const document = await client.getByUID("blog_post", "my-first-post")
1136
- * ```
1137
- *
1138
- * @typeParam TDocument - Type of the Prismic document returned.
1139
- *
1140
- * @param documentType - The API ID of the document's custom type.
1141
- * @param uid - UID of the document.
1142
- * @param params - Parameters to filter, sort, and paginate the results.
1143
- *
1144
- * @returns The document with a UID matching the `uid` parameter, if a
1145
- * matching document exists.
1146
- */
1147
- async getByUID(documentType, uid, params) {
1148
- return await this.getFirst(
1149
- appendFilters(params, [
1150
- typeFilter(documentType),
1151
- filter.at(`my.${documentType}.uid`, uid)
1152
- ])
1153
- );
1154
- }
1155
- /**
1156
- * Queries document from the Prismic repository with specific UIDs and Custom
1157
- * Type.
1158
- *
1159
- * @remarks
1160
- * A document's UID is different from its ID. An ID is automatically generated
1161
- * for all documents and is made available on its `id` property. A UID is
1162
- * provided in the Prismic editor and is unique among all documents of its
1163
- * custom type.
1164
- *
1165
- * @example
1166
- *
1167
- * ```ts
1168
- * const document = await client.getByUIDs("blog_post", [
1169
- * "my-first-post",
1170
- * "my-second-post",
1171
- * ])
1172
- * ```
1173
- *
1174
- * @typeParam TDocument - Type of the Prismic document returned.
1175
- *
1176
- * @param documentType - The API ID of the document's custom type.
1177
- * @param uids - A list of document UIDs.
1178
- * @param params - Parameters to filter, sort, and paginate the results.
1179
- *
1180
- * @returns A paginated response containing documents with UIDs matching the
1181
- * `uids` parameter.
1182
- */
1183
- async getByUIDs(documentType, uids, params) {
1184
- return await this.get(
1185
- appendFilters(params, [
1186
- typeFilter(documentType),
1187
- filter.in(`my.${documentType}.uid`, uids)
1188
- ])
1189
- );
1190
- }
1191
- /**
1192
- * Queries all documents from the Prismic repository with specific UIDs and
1193
- * custom type.
1194
- *
1195
- * This method may make multiple network requests to query all matching
1196
- * content.
1197
- *
1198
- * @remarks
1199
- * A document's UID is different from its ID. An ID is automatically generated
1200
- * for all documents and is made available on its `id` property. A UID is
1201
- * provided in the Prismic editor and is unique among all documents of its
1202
- * custom type.
1203
- *
1204
- * @example
1205
- *
1206
- * ```ts
1207
- * const response = await client.getAllByUIDs([
1208
- * "my-first-post",
1209
- * "my-second-post",
1210
- * ])
1211
- * ```
1212
- *
1213
- * @typeParam TDocument - Type of Prismic documents returned.
1214
- *
1215
- * @param documentType - The API ID of the document's custom type.
1216
- * @param uids - A list of document UIDs.
1217
- * @param params - Parameters to filter, sort, and paginate the results.
1218
- *
1219
- * @returns A list of documents with UIDs matching the `uids` parameter.
1220
- */
1221
- async getAllByUIDs(documentType, uids, params) {
1222
- return await this.dangerouslyGetAll(
1223
- appendFilters(params, [
1224
- typeFilter(documentType),
1225
- filter.in(`my.${documentType}.uid`, uids)
1226
- ])
1227
- );
1228
- }
1229
- /**
1230
- * Queries a singleton document from the Prismic repository for a specific
1231
- * custom type.
1232
- *
1233
- * @remarks
1234
- * A singleton document is one that is configured in Prismic to only allow one
1235
- * instance. For example, a repository may be configured to contain just one
1236
- * Settings document. This is in contrast to a repeatable custom type which
1237
- * allows multiple instances of itself.
1238
- *
1239
- * @example
1240
- *
1241
- * ```ts
1242
- * const document = await client.getSingle("settings")
1243
- * ```
1244
- *
1245
- * @typeParam TDocument - Type of the Prismic document returned.
1246
- *
1247
- * @param documentType - The API ID of the singleton custom type.
1248
- * @param params - Parameters to filter, sort, and paginate the results.
1249
- *
1250
- * @returns The singleton document for the custom type, if a matching document
1251
- * exists.
1252
- */
1253
- async getSingle(documentType, params) {
1254
- return await this.getFirst(
1255
- appendFilters(params, typeFilter(documentType))
1256
- );
1257
- }
1258
- /**
1259
- * Queries documents from the Prismic repository for a specific custom type.
1260
- *
1261
- * Use `getAllByType` instead if you need to query all documents for a
1262
- * specific custom type.
1263
- *
1264
- * @example
1265
- *
1266
- * ```ts
1267
- * const response = await client.getByType("blog_post")
1268
- * ```
1269
- *
1270
- * @typeParam TDocument - Type of Prismic documents returned.
1271
- *
1272
- * @param documentType - The API ID of the custom type.
1273
- * @param params - Parameters to filter, sort, and paginate the results.
1274
- *
1275
- * @returns A paginated response containing documents of the custom type.
1276
- */
1277
- async getByType(documentType, params) {
1278
- return await this.get(
1279
- appendFilters(params, typeFilter(documentType))
1280
- );
1281
- }
1282
- /**
1283
- * Queries all documents from the Prismic repository for a specific Custom
1284
- * Type.
1285
- *
1286
- * This method may make multiple network requests to query all matching
1287
- * content.
1288
- *
1289
- * @example
1290
- *
1291
- * ```ts
1292
- * const response = await client.getByType("blog_post")
1293
- * ```
1294
- *
1295
- * @typeParam TDocument - Type of Prismic documents returned.
1296
- *
1297
- * @param documentType - The API ID of the custom type.
1298
- * @param params - Parameters to filter, sort, and paginate the results.
1299
- *
1300
- * @returns A list of all documents of the custom type.
1301
- */
1302
- async getAllByType(documentType, params) {
1303
- return await this.dangerouslyGetAll(appendFilters(params, typeFilter(documentType)));
1304
- }
1305
- /**
1306
- * Queries documents from the Prismic repository with a specific tag.
1307
- *
1308
- * Use `getAllByTag` instead if you need to query all documents with a
1309
- * specific tag.
1310
- *
1311
- * @example
1312
- *
1313
- * ```ts
1314
- * const response = await client.getByTag("food")
1315
- * ```
1316
- *
1317
- * @typeParam TDocument - Type of Prismic documents returned.
1318
- *
1319
- * @param tag - The tag that must be included on a document.
1320
- * @param params - Parameters to filter, sort, and paginate the results.
1321
- *
1322
- * @returns A paginated response containing documents with the tag.
1323
- */
1324
- async getByTag(tag, params) {
1325
- return await this.get(appendFilters(params, someTagsFilter(tag)));
1326
- }
1327
- /**
1328
- * Queries all documents from the Prismic repository with a specific tag.
1329
- *
1330
- * This method may make multiple network requests to query all matching
1331
- * content.
1332
- *
1333
- * @example
1334
- *
1335
- * ```ts
1336
- * const response = await client.getAllByTag("food")
1337
- * ```
1338
- *
1339
- * @typeParam TDocument - Type of Prismic documents returned.
1340
- *
1341
- * @param tag - The tag that must be included on a document.
1342
- * @param params - Parameters to filter, sort, and paginate the results.
1343
- *
1344
- * @returns A list of all documents with the tag.
1345
- */
1346
- async getAllByTag(tag, params) {
1347
- return await this.dangerouslyGetAll(
1348
- appendFilters(params, someTagsFilter(tag))
1349
- );
1350
- }
1351
- /**
1352
- * Queries documents from the Prismic repository with specific tags. A
1353
- * document must be tagged with all of the queried tags to be included.
1354
- *
1355
- * @example
1356
- *
1357
- * ```ts
1358
- * const response = await client.getByEveryTag(["food", "fruit"])
1359
- * ```
1360
- *
1361
- * @typeParam TDocument - Type of Prismic documents returned.
1362
- *
1363
- * @param tags - A list of tags that must be included on a document.
1364
- * @param params - Parameters to filter, sort, and paginate the results.
1365
- *
1366
- * @returns A paginated response containing documents with the tags.
1367
- */
1368
- async getByEveryTag(tags, params) {
1369
- return await this.get(
1370
- appendFilters(params, everyTagFilter(tags))
1371
- );
1372
- }
1373
- /**
1374
- * Queries documents from the Prismic repository with specific tags. A
1375
- * document must be tagged with all of the queried tags to be included.
1376
- *
1377
- * This method may make multiple network requests to query all matching
1378
- * content.
1379
- *
1380
- * @example
1381
- *
1382
- * ```ts
1383
- * const response = await client.getAllByEveryTag(["food", "fruit"])
1384
- * ```
1385
- *
1386
- * @typeParam TDocument - Type of Prismic documents returned.
1387
- *
1388
- * @param tags - A list of tags that must be included on a document.
1389
- * @param params - Parameters to filter, sort, and paginate the results.
1390
- *
1391
- * @returns A list of all documents with the tags.
1392
- */
1393
- async getAllByEveryTag(tags, params) {
1394
- return await this.dangerouslyGetAll(
1395
- appendFilters(params, everyTagFilter(tags))
1396
- );
1397
- }
1398
- /**
1399
- * Queries documents from the Prismic repository with specific tags. A
1400
- * document must be tagged with at least one of the queried tags to be
1401
- * included.
1402
- *
1403
- * @example
1404
- *
1405
- * ```ts
1406
- * const response = await client.getByEveryTag(["food", "fruit"])
1407
- * ```
1408
- *
1409
- * @typeParam TDocument - Type of Prismic documents returned.
1410
- *
1411
- * @param tags - A list of tags that must be included on a document.
1412
- * @param params - Parameters to filter, sort, and paginate the results.
1413
- *
1414
- * @returns A paginated response containing documents with at least one of the
1415
- * tags.
1416
- */
1417
- async getBySomeTags(tags, params) {
1418
- return await this.get(
1419
- appendFilters(params, someTagsFilter(tags))
1420
- );
1421
- }
1422
- /**
1423
- * Queries documents from the Prismic repository with specific tags. A
1424
- * document must be tagged with at least one of the queried tags to be
1425
- * included.
1426
- *
1427
- * This method may make multiple network requests to query all matching
1428
- * content.
1429
- *
1430
- * @example
1431
- *
1432
- * ```ts
1433
- * const response = await client.getAllBySomeTags(["food", "fruit"])
1434
- * ```
1435
- *
1436
- * @typeParam TDocument - Type of Prismic documents returned.
1437
- *
1438
- * @param tags - A list of tags that must be included on a document.
1439
- * @param params - Parameters to filter, sort, and paginate the results.
1440
- *
1441
- * @returns A list of all documents with at least one of the tags.
1442
- */
1443
- async getAllBySomeTags(tags, params) {
1444
- return await this.dangerouslyGetAll(
1445
- appendFilters(params, someTagsFilter(tags))
1446
- );
1447
- }
1448
- /**
1449
- * Returns metadata about the Prismic repository, such as its refs, releases,
1450
- * and custom types.
1451
- *
1452
- * @returns Repository metadata.
1453
- */
1454
- async getRepository(params) {
1455
- const url = new URL(this.documentAPIEndpoint);
1456
- if (this.accessToken) {
1457
- url.searchParams.set("access_token", this.accessToken);
1458
- }
1459
- const response = await this.#request(url, params);
1460
- switch (response.status) {
1461
- case 200: {
1462
- return await response.json();
1463
- }
1464
- case 401: {
1465
- const json = await response.json();
1466
- throw new ForbiddenError(json.error, url.toString(), json);
1467
- }
1468
- case 404: {
1469
- throw new RepositoryNotFoundError(
1470
- `Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`,
1471
- url.toString(),
1472
- void 0
1473
- );
1474
- }
1475
- default: {
1476
- throw new PrismicError(void 0, url.toString(), await response.text());
1477
- }
1478
- }
1479
- }
1480
- /**
1481
- * Returns a list of all refs for the Prismic repository.
1482
- *
1483
- * Refs are used to identify which version of the repository's content should
1484
- * be queried. All repositories will have at least one ref pointing to the
1485
- * latest published content called the "master ref".
1486
- *
1487
- * @returns A list of all refs for the Prismic repository.
1488
- */
1489
- async getRefs(params) {
1490
- const repository = await this.getRepository(params);
1491
- return repository.refs;
1492
- }
1493
- /**
1494
- * Returns a ref for the Prismic repository with a matching ID.
1495
- *
1496
- * @param id - ID of the ref.
1497
- *
1498
- * @returns The ref with a matching ID, if it exists.
1499
- */
1500
- async getRefByID(id, params) {
1501
- const refs = await this.getRefs(params);
1502
- return findRefByID(refs, id);
1503
- }
1504
- /**
1505
- * Returns a ref for the Prismic repository with a matching label.
1506
- *
1507
- * @param label - Label of the ref.
1508
- *
1509
- * @returns The ref with a matching label, if it exists.
1510
- */
1511
- async getRefByLabel(label, params) {
1512
- const refs = await this.getRefs(params);
1513
- return findRefByLabel(refs, label);
1514
- }
1515
- /**
1516
- * Returns the master ref for the Prismic repository. The master ref points to
1517
- * the repository's latest published content.
1518
- *
1519
- * @returns The repository's master ref.
1520
- */
1521
- async getMasterRef(params) {
1522
- const refs = await this.getRefs(params);
1523
- return findMasterRef(refs);
1524
- }
1525
- /**
1526
- * Returns a list of all Releases for the Prismic repository. Releases are
1527
- * used to group content changes before publishing.
1528
- *
1529
- * @returns A list of all Releases for the Prismic repository.
1530
- */
1531
- async getReleases(params) {
1532
- const refs = await this.getRefs(params);
1533
- return refs.filter((ref) => !ref.isMasterRef);
1534
- }
1535
- /**
1536
- * Returns a Release for the Prismic repository with a matching ID.
1537
- *
1538
- * @param id - ID of the Release.
1539
- *
1540
- * @returns The Release with a matching ID, if it exists.
1541
- */
1542
- async getReleaseByID(id, params) {
1543
- const releases = await this.getReleases(params);
1544
- return findRefByID(releases, id);
1545
- }
1546
- /**
1547
- * Returns a Release for the Prismic repository with a matching label.
1548
- *
1549
- * @param label - Label of the ref.
1550
- *
1551
- * @returns The ref with a matching label, if it exists.
1552
- */
1553
- async getReleaseByLabel(label, params) {
1554
- const releases = await this.getReleases(params);
1555
- return findRefByLabel(releases, label);
1556
- }
1557
- /**
1558
- * Returns a list of all tags used in the Prismic repository.
1559
- *
1560
- * @returns A list of all tags used in the repository.
1561
- */
1562
- async getTags(params) {
1563
- const cachedRepository = await this.getCachedRepository(params);
1564
- const form = cachedRepository.forms.tags;
1565
- if (form) {
1566
- const url = new URL(form.action);
1567
- if (this.accessToken) {
1568
- url.searchParams.set("access_token", this.accessToken);
1569
- }
1570
- const response = await this.#request(url, params);
1571
- if (response.ok) {
1572
- return await response.json();
1573
- }
1574
- }
1575
- const repository = await this.getRepository(params);
1576
- return repository.tags;
1577
- }
1578
- /**
1579
- * Builds a URL used to query content from the Prismic repository.
1580
- *
1581
- * @param params - Parameters to filter, sort, and paginate the results.
1582
- *
1583
- * @returns A URL string that can be requested to query content.
1584
- */
1585
- async buildQueryURL({
1586
- signal,
1587
- fetchOptions,
1588
- ...params
1589
- } = {}) {
1590
- const ref = params.ref || await this.getResolvedRefString({ signal, fetchOptions });
1591
- const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({ signal, fetchOptions })).integrationFieldsRef || void 0;
1592
- return buildQueryURL(this.documentAPIEndpoint, {
1593
- ...this.defaultParams,
1594
- ...params,
1595
- ref,
1596
- integrationFieldsRef,
1597
- routes: params.routes || this.routes,
1598
- brokenRoute: params.brokenRoute || this.brokenRoute,
1599
- accessToken: params.accessToken || this.accessToken
1600
- });
1601
- }
1602
- /**
1603
- * Determines the URL for a previewed document during an active preview
1604
- * session. The result of this method should be used to redirect the user to
1605
- * the document's URL.
1606
- *
1607
- * @example
1608
- *
1609
- * ```ts
1610
- * const url = client.resolvePreviewURL({
1611
- * linkResolver: (document) => `/${document.uid}`
1612
- * defaultURL: '/'
1613
- * })
1614
- * ```
1615
- *
1616
- * @param args - Arguments to configure the URL resolving.
1617
- *
1618
- * @returns The URL for the previewed document during an active preview
1619
- * session. The user should be redirected to this URL.
1620
- */
1621
- async resolvePreviewURL(args) {
1622
- let documentID = args.documentID;
1623
- let previewToken = args.previewToken;
1624
- if (typeof globalThis.location !== "undefined") {
1625
- const searchParams = new URLSearchParams(globalThis.location.search);
1626
- documentID = documentID || searchParams.get("documentId");
1627
- previewToken = previewToken || searchParams.get("token");
1628
- } else if (this.refState.httpRequest) {
1629
- if ("query" in this.refState.httpRequest) {
1630
- documentID = documentID || this.refState.httpRequest.query?.documentId;
1631
- previewToken = previewToken || this.refState.httpRequest.query?.token;
1632
- } else if ("url" in this.refState.httpRequest && this.refState.httpRequest.url) {
1633
- const searchParams = new URL(
1634
- this.refState.httpRequest.url,
1635
- "missing-host://"
1636
- ).searchParams;
1637
- documentID = documentID || searchParams.get("documentId");
1638
- previewToken = previewToken || searchParams.get("token");
1639
- }
1640
- }
1641
- if (documentID != null && previewToken != null) {
1642
- const document = await this.getByID(documentID, {
1643
- ref: previewToken,
1644
- lang: "*",
1645
- signal: args.signal,
1646
- fetchOptions: args.fetchOptions
1647
- });
1648
- const url = asLink(document, { linkResolver: args.linkResolver });
1649
- if (typeof url === "string") {
1650
- return url;
1651
- }
1652
- }
1653
- return args.defaultURL;
1654
- }
1655
- /**
1656
- * Configures the client to query the latest published content for all future
1657
- * queries.
1658
- *
1659
- * If the `ref` parameter is provided during a query, it takes priority for
1660
- * that query.
1661
- *
1662
- * @example
1663
- *
1664
- * ```ts
1665
- * await client.queryLatestContent()
1666
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1667
- * ```
1668
- */
1669
- queryLatestContent() {
1670
- this.refState.mode = "Master" /* Master */;
1671
- }
1672
- /**
1673
- * Configures the client to query content from a specific Release identified
1674
- * by its ID for all future queries.
1675
- *
1676
- * If the `ref` parameter is provided during a query, it takes priority for
1677
- * that query.
1678
- *
1679
- * @example
1680
- *
1681
- * ```ts
1682
- * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa")
1683
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1684
- * ```
1685
- *
1686
- * @param releaseID - The ID of the Release.
1687
- */
1688
- queryContentFromReleaseByID(releaseID) {
1689
- this.refState = {
1690
- ...this.refState,
1691
- mode: "ReleaseID" /* ReleaseID */,
1692
- releaseID
1693
- };
1694
- }
1695
- /**
1696
- * Configures the client to query content from a specific Release identified
1697
- * by its label for all future queries.
1698
- *
1699
- * If the `ref` parameter is provided during a query, it takes priority for
1700
- * that query.
1701
- *
1702
- * @example
1703
- *
1704
- * ```ts
1705
- * await client.queryContentFromReleaseByLabel("My Release")
1706
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1707
- * ```
1708
- *
1709
- * @param releaseLabel - The label of the Release.
1710
- */
1711
- queryContentFromReleaseByLabel(releaseLabel) {
1712
- this.refState = {
1713
- ...this.refState,
1714
- mode: "ReleaseLabel" /* ReleaseLabel */,
1715
- releaseLabel
1716
- };
1717
- }
1718
- /**
1719
- * Configures the client to query content from a specific ref. The ref can be
1720
- * provided as a string or a function.
1721
- *
1722
- * If a function is provided, the ref is fetched lazily before each query. The
1723
- * function may also be asynchronous.
1724
- *
1725
- * @example
1726
- *
1727
- * ```ts
1728
- * await client.queryContentFromRef("my-ref")
1729
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1730
- * ```
1731
- *
1732
- * @param ref - The ref or a function that returns the ref from which to query
1733
- * content.
1734
- */
1735
- queryContentFromRef(ref) {
1736
- this.refState = {
1737
- ...this.refState,
1738
- mode: "Manual" /* Manual */,
1739
- ref
1740
- };
1741
- }
1742
- /**
1743
- * A `fetch()` function to be used with GraphQL clients configured for
1744
- * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
1745
- * and Authorization headers. Queries will automatically be minified by
1746
- * removing whitespace where possible.
1747
- *
1748
- * @example
1749
- *
1750
- * ```ts
1751
- * const graphQLClient = new ApolloClient({
1752
- * link: new HttpLink({
1753
- * uri: prismic.getGraphQLEndpoint(repositoryName),
1754
- * // Provide `client.graphQLFetch` as the fetch implementation.
1755
- * fetch: client.graphQLFetch,
1756
- * // Using GET is required.
1757
- * useGETForQueries: true,
1758
- * }),
1759
- * cache: new InMemoryCache(),
1760
- * })
1761
- * ```
1762
- *
1763
- * @param input - The `fetch()` `input` parameter. Only strings are supported.
1764
- * @param init - The `fetch()` `init` parameter. Only plain objects are
1765
- * supported.
1766
- *
1767
- * @returns The `fetch()` Response for the request.
1768
- *
1769
- * @experimental
1770
- */
1771
- async graphQLFetch(input, init) {
1772
- const cachedRepository = await this.getCachedRepository();
1773
- const ref = await this.getResolvedRefString();
1774
- const unsanitizedHeaders = {
1775
- "Prismic-ref": ref,
1776
- Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
1777
- // Asserting `init.headers` is a Record since popular GraphQL
1778
- // libraries pass this as a Record. Header objects as input
1779
- // are unsupported.
1780
- ...init ? init.headers : {}
1781
- };
1782
- if (cachedRepository.integrationFieldsRef) {
1783
- unsanitizedHeaders["Prismic-integration-field-ref"] = cachedRepository.integrationFieldsRef;
1784
- }
1785
- const headers = {};
1786
- for (const key in unsanitizedHeaders) {
1787
- if (unsanitizedHeaders[key]) {
1788
- headers[key.toLowerCase()] = unsanitizedHeaders[key];
1789
- }
1790
- }
1791
- const url = new URL(
1792
- // Asserting `input` is a string since popular GraphQL
1793
- // libraries pass this as a string. Request objects as
1794
- // input are unsupported.
1795
- input
1796
- );
1797
- url.searchParams.set("ref", ref);
1798
- const query = url.searchParams.get("query");
1799
- if (query) {
1800
- url.searchParams.set(
1801
- "query",
1802
- // Compress the GraphQL query (if it exists) by
1803
- // removing whitespace. This is done to
1804
- // optimize the query size and avoid
1805
- // hitting the upper limit of GET requests
1806
- // (2048 characters).
1807
- minifyGraphQLQuery(query)
1808
- );
1809
- }
1810
- return await this.fetchFn(url.toString(), {
1811
- ...init,
1812
- headers
1813
- });
1814
- }
1815
- /**
1816
- * Returns a cached version of `getRepository` with a TTL.
1817
- *
1818
- * @returns Cached repository metadata.
1819
- */
1820
- async getCachedRepository(params) {
1821
- if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
1822
- this.cachedRepository = await this.getRepository(params);
1823
- this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1824
- }
1825
- return this.cachedRepository;
1826
- }
1827
- /**
1828
- * Returns the ref needed to query based on the client's current state. This
1829
- * method may make a network request to fetch a ref or resolve the user's ref
1830
- * thunk.
1831
- *
1832
- * If auto previews are enabled, the preview ref takes priority if available.
1833
- *
1834
- * The following strategies are used depending on the client's state:
1835
- *
1836
- * - If the user called `queryLatestContent`: Use the repository's master ref.
1837
- * The ref is cached for 5 seconds. After 5 seconds, a new master ref is
1838
- * fetched.
1839
- * - If the user called `queryContentFromReleaseByID`: Use the release's ref.
1840
- * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1841
- * release is fetched.
1842
- * - If the user called `queryContentFromReleaseByLabel`: Use the release's ref.
1843
- * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1844
- * release is fetched.
1845
- * - If the user called `queryContentFromRef`: Use the provided ref. Fall back
1846
- * to the master ref if the ref is not a string.
1847
- *
1848
- * @returns The ref to use during a query.
1849
- */
1850
- async getResolvedRefString(params) {
1851
- if (this.refState.autoPreviewsEnabled) {
1852
- let previewRef;
1853
- let cookieJar;
1854
- if (this.refState.httpRequest?.headers) {
1855
- if ("get" in this.refState.httpRequest.headers && typeof this.refState.httpRequest.headers.get === "function") {
1856
- cookieJar = this.refState.httpRequest.headers.get("cookie");
1857
- } else if ("cookie" in this.refState.httpRequest.headers) {
1858
- cookieJar = this.refState.httpRequest.headers.cookie;
1859
- }
1860
- } else if (globalThis.document?.cookie) {
1861
- cookieJar = globalThis.document.cookie;
1862
- }
1863
- if (cookieJar) {
1864
- previewRef = getPreviewCookie(cookieJar);
1865
- }
1866
- if (previewRef) {
1867
- return previewRef;
1868
- }
1869
- }
1870
- const cachedRepository = await this.getCachedRepository(params);
1871
- const refModeType = this.refState.mode;
1872
- if (refModeType === "ReleaseID" /* ReleaseID */) {
1873
- return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
1874
- } else if (refModeType === "ReleaseLabel" /* ReleaseLabel */) {
1875
- return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
1876
- } else if (refModeType === "Manual" /* Manual */) {
1877
- const res = await castThunk(this.refState.ref)();
1878
- if (typeof res === "string") {
1879
- return res;
1880
- }
1881
- }
1882
- return findMasterRef(cachedRepository.refs).ref;
1883
- }
1884
- /**
1885
- * The private implementation of `this.get`. It returns the API response and
1886
- * the URL used to make the request. The URL is sometimes used in the public
1887
- * method to include in thrown errors.
1888
- *
1889
- * This method retries requests that throw `RefNotFoundError` or
1890
- * `RefExpiredError`. It contains special logic to retry with the latest
1891
- * master ref, provided in the API's error message.
1892
- *
1893
- * @typeParam TDocument - Type of Prismic documents returned.
1894
- *
1895
- * @param params - Parameters to filter, sort, and paginate results.
1896
- *
1897
- * @returns An object containing the paginated response containing the result
1898
- * of the query and the URL used to make the API request.
1899
- */
1900
- async _get(params, attemptCount = 0) {
1901
- const url = await this.buildQueryURL(params);
1902
- try {
1903
- const response = await this.#request(new URL(url), params);
1904
- switch (response.status) {
1905
- case 200: {
1906
- try {
1907
- return {
1908
- data: await response.clone().json(),
1909
- url
1910
- };
1911
- } catch {
1912
- throw new PrismicError(void 0, url, await response.text());
1913
- }
1914
- }
1915
- case 400: {
1916
- const json = await response.json();
1917
- throw new ParsingError(json.message, url, json);
1918
- }
1919
- case 401: {
1920
- const json = await response.json();
1921
- throw new ForbiddenError(json.message, url, json);
1922
- }
1923
- case 404: {
1924
- const json = await response.json();
1925
- switch (json.type) {
1926
- case "api_notfound_error": {
1927
- throw new RefNotFoundError(json.message, url, json);
1928
- }
1929
- case "api_security_error": {
1930
- if (/preview token.*expired/i.test(json.message)) {
1931
- throw new PreviewTokenExpiredError(json.message, url, json);
1932
- }
1933
- }
1934
- default: {
1935
- throw new NotFoundError(json.message, url, json);
1936
- }
1937
- }
1938
- }
1939
- case 410: {
1940
- const json = await response.json();
1941
- throw new RefExpiredError(json.message, url, json);
1942
- }
1943
- default: {
1944
- throw new PrismicError(void 0, url, await response.text());
1945
- }
1946
- }
1947
- } catch (error) {
1948
- if (!(error instanceof RefNotFoundError || error instanceof RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPTS - 1) {
1949
- throw error;
1950
- }
1951
- if (!params?.ref) {
1952
- this.cachedRepository = void 0;
1953
- }
1954
- const masterRef = error.message.match(/Master ref is: (?<ref>.*)$/)?.groups?.ref;
1955
- if (!masterRef) {
1956
- throw error;
1957
- }
1958
- const badRef = new URL(url).searchParams.get("ref");
1959
- const issue = error instanceof RefNotFoundError ? "invalid" : "expired";
1960
- throttledLog(
1961
- `[@prismicio/client] The ref (${badRef}) was ${issue}. Now retrying with the latest master ref (${masterRef}). If you were previewing content, the response will not include draft content.`,
1962
- { level: "warn" }
1963
- );
1964
- return await this._get({ ...params, ref: masterRef }, attemptCount + 1);
1965
- }
1966
- }
1967
- /**
1968
- * Makes an HTTP request using the client's configured fetch function and
1969
- * options.
1970
- *
1971
- * @param url - The URL to request.
1972
- * @param params - Fetch options.
1973
- *
1974
- * @returns The response from the fetch request.
1975
- */
1976
- async #request(url, params) {
1977
- return await request(url, this._buildRequestInit(params), this.fetchFn);
1978
- }
1979
- _buildRequestInit(params) {
1980
- return {
1981
- ...this.fetchOptions,
1982
- ...params?.fetchOptions,
1983
- headers: {
1984
- ...this.fetchOptions?.headers,
1985
- ...params?.fetchOptions?.headers
1986
- },
1987
- signal: params?.fetchOptions?.signal || params?.signal || this.fetchOptions?.signal
1988
- };
1989
- }
1990
- }
1991
-
1992
- const createClient = (repositoryNameOrEndpoint, options) => new Client(repositoryNameOrEndpoint, options);
1993
-
1994
- class PrismicMigrationAsset {
1995
- /**
1996
- * Asset object from Prismic, available once created.
1997
- */
1998
- asset;
1999
- /**
2000
- * Configuration of the asset.
2001
- */
2002
- config;
2003
- /**
2004
- * The initial field value this migration field was created with.
2005
- */
2006
- originalField;
2007
- /**
2008
- * Creates a migration asset used with the Prismic Migration API.
2009
- *
2010
- * @param config - Configuration of the asset.
2011
- * @param initialField - The initial field value if any.
2012
- *
2013
- * @returns A migration asset instance.
2014
- */
2015
- constructor(config, initialField) {
2016
- this.config = config;
2017
- this.originalField = initialField;
2018
- }
2019
- }
2020
-
2021
- class PrismicMigrationDocument {
2022
- /**
2023
- * The document to be sent to the Migration API.
2024
- */
2025
- document;
2026
- /**
2027
- * The name of the document displayed in the editor.
2028
- */
2029
- title;
2030
- /**
2031
- * The link to the master language document to relate the document to if any.
2032
- */
2033
- masterLanguageDocument;
2034
- /**
2035
- * Original Prismic document when the migration document came from another
2036
- * Prismic repository.
2037
- *
2038
- * @remarks
2039
- * When migrating a document from another repository, one might want to alter
2040
- * it with migration specific types, hence accepting an
2041
- * `ExistingPrismicDocument` instead of a regular `PrismicDocument`.
2042
- */
2043
- originalPrismicDocument;
2044
- /**
2045
- * Creates a Prismic migration document instance.
2046
- *
2047
- * @param document - The document to be sent to the Migration API.
2048
- * @param title - The name of the document displayed in the editor.
2049
- * @param params - Parameters to create/update the document with on the
2050
- * Migration API.
2051
- *
2052
- * @returns A Prismic migration document instance.
2053
- */
2054
- constructor(document, title, params) {
2055
- this.document = document;
2056
- this.title = title;
2057
- this.masterLanguageDocument = params?.masterLanguageDocument;
2058
- this.originalPrismicDocument = params?.originalPrismicDocument;
2059
- }
2060
- }
2061
-
2062
- const isNonNullish = (input) => {
2063
- return input != null;
2064
- };
2065
- const isNonEmptyArray = (input) => {
2066
- return !!input.length;
2067
- };
2068
- const richText = (field) => {
2069
- if (!isNonNullish(field)) {
2070
- return false;
2071
- } else if (field.length === 1 && "text" in field[0]) {
2072
- return !!field[0].text;
2073
- } else {
2074
- return !!field.length;
2075
- }
2076
- };
2077
- const title = richText;
2078
- const imageThumbnail = (thumbnail) => {
2079
- return isNonNullish(thumbnail) && !!thumbnail.url;
2080
- };
2081
- const image$1 = imageThumbnail;
2082
- const link = (field) => {
2083
- return isNonNullish(field) && ("id" in field || "url" in field);
2084
- };
2085
- const linkToMedia$1 = link;
2086
- const contentRelationship$1 = link;
2087
- const date = isNonNullish;
2088
- const timestamp = isNonNullish;
2089
- const color = isNonNullish;
2090
- const number = isNonNullish;
2091
- const keyText = (field) => {
2092
- return !!field;
2093
- };
2094
- const select = isNonNullish;
2095
- const embed = (field) => {
2096
- return isNonNullish(field) && !!field.embed_url;
2097
- };
2098
- const geoPoint = (field) => {
2099
- return isNonNullish(field) && "longitude" in field;
2100
- };
2101
- const table = isNonNullish;
2102
- const integration = isNonNullish;
2103
- const integrationField = integration;
2104
- const integrationFields = integration;
2105
- const repeatable = (repeatable2) => {
2106
- return isNonNullish(repeatable2) && isNonEmptyArray(repeatable2);
2107
- };
2108
- const group = (group2) => {
2109
- return isNonNullish(group2) && isNonEmptyArray(group2);
2110
- };
2111
- const sliceZone = (slices) => {
2112
- return isNonNullish(slices) && isNonEmptyArray(slices);
2113
- };
2114
-
2115
- const isFilled = {
2116
- __proto__: null,
2117
- color: color,
2118
- contentRelationship: contentRelationship$1,
2119
- date: date,
2120
- embed: embed,
2121
- geoPoint: geoPoint,
2122
- group: group,
2123
- image: image$1,
2124
- imageThumbnail: imageThumbnail,
2125
- integration: integration,
2126
- integrationField: integrationField,
2127
- integrationFields: integrationFields,
2128
- keyText: keyText,
2129
- link: link,
2130
- linkToMedia: linkToMedia$1,
2131
- number: number,
2132
- repeatable: repeatable,
2133
- richText: richText,
2134
- select: select,
2135
- sliceZone: sliceZone,
2136
- table: table,
2137
- timestamp: timestamp,
2138
- title: title
2139
- };
2140
-
2141
- const filledLinkToMedia = (value) => {
2142
- if (value && typeof value === "object" && !("version" in value)) {
2143
- if ("link_type" in value && value.link_type === LinkType.Media && "id" in value && "name" in value && "kind" in value && "url" in value && "size" in value) {
2144
- return true;
2145
- }
2146
- }
2147
- return false;
2148
- };
2149
- const imageLike = (value) => {
2150
- if (value && typeof value === "object" && (!("version" in value) || typeof value.version === "object")) {
2151
- if ("id" in value && "url" in value && typeof value.url === "string" && "dimensions" in value && "edit" in value && "alt" in value && "copyright" in value) {
2152
- return true;
2153
- }
2154
- }
2155
- return false;
2156
- };
2157
- const filledImage = (value) => {
2158
- if (imageLike(value) && (!("type" in value) || value.type !== RichTextNodeType.image)) {
2159
- return true;
2160
- }
2161
- return false;
2162
- };
2163
- const rtImageNode$1 = (value) => {
2164
- if (imageLike(value) && "type" in value && value.type === RichTextNodeType.image) {
2165
- return true;
2166
- }
2167
- return false;
2168
- };
2169
- const filledContentRelationship = (value) => {
2170
- if (value && typeof value === "object" && !("version" in value)) {
2171
- if ("link_type" in value && value.link_type === LinkType.Document && "id" in value && "type" in value && "tags" in value && "lang" in value) {
2172
- return true;
2173
- }
2174
- }
2175
- return false;
2176
- };
2177
- const prismicDocument = (value) => {
2178
- try {
2179
- return typeof value === "object" && value !== null && "id" in value && "href" in value && typeof value.href === "string" && new URL(value.href) && "type" in value && "lang" in value && "tags" in value && Array.isArray(value.tags);
2180
- } catch {
2181
- return false;
2182
- }
2183
- };
2184
-
2185
- const contentRelationship = (value) => {
2186
- return value instanceof PrismicMigrationDocument || prismicDocument(value) || typeof value === "object" && value !== null && "link_type" in value && value.link_type === LinkType.Document && "id" in value && (contentRelationship(value.id) || typeof value.id === "function");
2187
- };
2188
- const image = (value) => {
2189
- return value instanceof PrismicMigrationAsset || typeof value === "object" && value !== null && "id" in value && Object.values(value).every(
2190
- (maybeThumbnail) => maybeThumbnail instanceof PrismicMigrationAsset
2191
- );
2192
- };
2193
- const linkToMedia = (value) => {
2194
- return typeof value === "object" && value !== null && "id" in value && value.id instanceof PrismicMigrationAsset && "link_type" in value && value.link_type === LinkType.Media;
2195
- };
2196
- const rtImageNode = (value) => {
2197
- return typeof value === "object" && value !== null && "id" in value && value.id instanceof PrismicMigrationAsset && "type" in value && value.type === RichTextNodeType.image;
2198
- };
2199
-
2200
- const getOptionalLinkProperties = (input) => {
2201
- const res = {};
2202
- if ("text" in input) {
2203
- res.text = input.text;
2204
- }
2205
- if ("variant" in input) {
2206
- res.variant = input.variant;
2207
- }
2208
- return res;
2209
- };
2210
-
2211
- async function resolveMigrationContentRelationship(relation) {
2212
- if (typeof relation === "function") {
2213
- return resolveMigrationContentRelationship(await relation());
2214
- }
2215
- if (relation instanceof PrismicMigrationDocument) {
2216
- return relation.document.id ? { link_type: LinkType.Document, id: relation.document.id } : { link_type: LinkType.Any };
2217
- }
2218
- const optionalLinkProperties = relation && "link_type" in relation ? getOptionalLinkProperties(relation) : void 0;
2219
- if (relation) {
2220
- if (contentRelationship(relation.id) || typeof relation.id !== "string") {
2221
- return {
2222
- ...optionalLinkProperties,
2223
- ...await resolveMigrationContentRelationship(relation.id)
2224
- };
2225
- }
2226
- return {
2227
- ...optionalLinkProperties,
2228
- link_type: LinkType.Document,
2229
- id: relation.id
2230
- };
2231
- }
2232
- return {
2233
- ...optionalLinkProperties,
2234
- link_type: LinkType.Any
2235
- };
2236
- }
2237
- const resolveMigrationImage = (image, migration, withThumbnails) => {
2238
- const { id: master, ...thumbnails } = image instanceof PrismicMigrationAsset ? { id: image } : image;
2239
- const asset = migration._assets.get(master.config.id)?.asset;
2240
- const maybeInitialField = master.originalField;
2241
- if (asset) {
2242
- const parameters = (maybeInitialField?.url || asset.url).split("?")[1];
2243
- const url = `${asset.url.split("?")[0]}${parameters ? `?${parameters}` : ""}`;
2244
- const dimensions = {
2245
- width: asset.width,
2246
- height: asset.height
2247
- };
2248
- const edit = maybeInitialField && "edit" in maybeInitialField ? maybeInitialField?.edit : { x: 0, y: 0, zoom: 1, background: "transparent" };
2249
- const alt = master.config.alt || asset.alt || null;
2250
- const resolvedThumbnails = {};
2251
- if (withThumbnails) {
2252
- for (const [name, thumbnail] of Object.entries(thumbnails)) {
2253
- const resolvedThumbnail = resolveMigrationImage(thumbnail, migration);
2254
- if (resolvedThumbnail) {
2255
- resolvedThumbnails[name] = resolvedThumbnail;
2256
- }
2257
- }
2258
- }
2259
- return {
2260
- id: asset.id,
2261
- url,
2262
- dimensions,
2263
- edit,
2264
- alt,
2265
- copyright: asset.credits || null,
2266
- ...resolvedThumbnails
2267
- };
2268
- }
2269
- };
2270
- const resolveMigrationRTImageNode = async (rtImageNode, migration) => {
2271
- const image = resolveMigrationImage(rtImageNode.id, migration);
2272
- if (image) {
2273
- const linkTo = await resolveMigrationDocumentData(
2274
- rtImageNode.linkTo,
2275
- migration
2276
- );
2277
- return {
2278
- ...image,
2279
- type: RichTextNodeType.image,
2280
- linkTo: link(linkTo) ? linkTo : void 0
2281
- };
2282
- }
2283
- };
2284
- const resolveMigrationLinkToMedia = (linkToMedia, migration) => {
2285
- const asset = migration._assets.get(linkToMedia.id.config.id)?.asset;
2286
- const optionalLinkProperties = getOptionalLinkProperties(linkToMedia);
2287
- if (asset) {
2288
- return {
2289
- ...optionalLinkProperties,
2290
- id: asset.id,
2291
- link_type: LinkType.Media
2292
- };
2293
- }
2294
- return {
2295
- ...optionalLinkProperties,
2296
- link_type: LinkType.Any
2297
- };
2298
- };
2299
- async function resolveMigrationDocumentData(input, migration) {
2300
- if (contentRelationship(input)) {
2301
- return resolveMigrationContentRelationship(input);
2302
- }
2303
- if (image(input)) {
2304
- return resolveMigrationImage(input, migration, true);
2305
- }
2306
- if (linkToMedia(input)) {
2307
- return resolveMigrationLinkToMedia(input, migration);
2308
- }
2309
- if (rtImageNode(input)) {
2310
- return resolveMigrationRTImageNode(input, migration);
2311
- }
2312
- if (typeof input === "function") {
2313
- return await resolveMigrationDocumentData(await input(), migration);
2314
- }
2315
- if (Array.isArray(input)) {
2316
- const res = [];
2317
- for (const element of input) {
2318
- res.push(await resolveMigrationDocumentData(element, migration));
2319
- }
2320
- return res.filter(Boolean);
2321
- }
2322
- if (input && typeof input === "object") {
2323
- const res = {};
2324
- for (const key in input) {
2325
- res[key] = await resolveMigrationDocumentData(
2326
- input[key],
2327
- migration
2328
- );
2329
- }
2330
- return res;
2331
- }
2332
- return input;
2333
- }
2334
-
2335
- class InvalidDataError extends PrismicError {
2336
- }
2337
-
2338
- const CLIENT_IDENTIFIER = `${name.replace("@", "").replace("/", "-")}/${version}`;
2339
- class WriteClient extends Client {
2340
- writeToken;
2341
- assetAPIEndpoint = "https://asset-api.prismic.io/";
2342
- migrationAPIEndpoint = "https://migration.prismic.io/";
2343
- /**
2344
- * Creates a Prismic client that can be used to query and write content to a
2345
- * repository.
2346
- *
2347
- * If used in an environment where a global `fetch` function is unavailable,
2348
- * such as in some Node.js versions, the `fetch` option must be provided as
2349
- * part of the `options` parameter.
2350
- *
2351
- * @param repositoryName - The Prismic repository name for the repository.
2352
- * @param options - Configuration that determines how content will be queried
2353
- * from and written to the Prismic repository.
2354
- *
2355
- * @returns A client that can query and write content to the repository.
2356
- */
2357
- constructor(repositoryName, options) {
2358
- super(repositoryName, options);
2359
- if (typeof globalThis.window !== "undefined") {
2360
- console.warn(
2361
- `[@prismicio/client] Prismic write client appears to be running in a browser environment. This is not recommended as it exposes your write token. Consider using Prismic write client in a server environment only, preferring the regular client for browser environment. For more details, see ${devMsg("avoid-write-client-in-browser")}`
2362
- );
2363
- }
2364
- this.writeToken = options.writeToken;
2365
- if (options.assetAPIEndpoint) {
2366
- this.assetAPIEndpoint = `${options.assetAPIEndpoint}/`;
2367
- }
2368
- if (options.migrationAPIEndpoint) {
2369
- this.migrationAPIEndpoint = `${options.migrationAPIEndpoint}/`;
2370
- }
2371
- }
2372
- /**
2373
- * Creates a migration release on the Prismic repository based on the provided
2374
- * prepared migration.
2375
- *
2376
- * @param migration - A migration prepared with {@link createMigration}.
2377
- * @param params - An event listener and additional fetch parameters.
2378
- *
2379
- * @see Prismic Migration API technical reference: {@link https://prismic.io/docs/migration-api-technical-reference}
2380
- */
2381
- async migrate(migration, params = {}) {
2382
- params.reporter?.({
2383
- type: "start",
2384
- data: {
2385
- pending: {
2386
- documents: migration._documents.length,
2387
- assets: migration._assets.size
2388
- }
2389
- }
2390
- });
2391
- await this.migrateCreateAssets(migration, params);
2392
- await this.migrateCreateDocuments(migration, params);
2393
- await this.migrateUpdateDocuments(migration, params);
2394
- params.reporter?.({
2395
- type: "end",
2396
- data: {
2397
- migrated: {
2398
- documents: migration._documents.length,
2399
- assets: migration._assets.size
2400
- }
2401
- }
2402
- });
2403
- }
2404
- /**
2405
- * Creates assets in the Prismic repository's media library.
2406
- *
2407
- * @param migration - A migration prepared with {@link createMigration}.
2408
- * @param params - An event listener and additional fetch parameters.
2409
- *
2410
- * @internal This method is one of the step performed by the {@link migrate} method.
2411
- */
2412
- async migrateCreateAssets(migration, {
2413
- reporter,
2414
- ...fetchParams
2415
- } = {}) {
2416
- let created = 0;
2417
- for (const [_, migrationAsset] of migration._assets) {
2418
- reporter?.({
2419
- type: "assets:creating",
2420
- data: {
2421
- current: ++created,
2422
- remaining: migration._assets.size - created,
2423
- total: migration._assets.size,
2424
- asset: migrationAsset
2425
- }
2426
- });
2427
- const { file, filename, notes, credits, alt, tags } = migrationAsset.config;
2428
- let resolvedFile;
2429
- if (typeof file === "string") {
2430
- let url;
2431
- try {
2432
- url = new URL(file);
2433
- } catch (error) {
2434
- }
2435
- if (url) {
2436
- resolvedFile = await this.fetchForeignAsset(
2437
- url.toString(),
2438
- fetchParams
2439
- );
2440
- } else {
2441
- resolvedFile = file;
2442
- }
2443
- } else if (file instanceof URL) {
2444
- resolvedFile = await this.fetchForeignAsset(
2445
- file.toString(),
2446
- fetchParams
2447
- );
2448
- } else {
2449
- resolvedFile = file;
2450
- }
2451
- const asset = await this.createAsset(resolvedFile, filename, {
2452
- ...{ notes, credits, alt, tags },
2453
- ...fetchParams
2454
- });
2455
- migrationAsset.asset = asset;
2456
- }
2457
- reporter?.({
2458
- type: "assets:created",
2459
- data: {
2460
- created
2461
- }
2462
- });
2463
- }
2464
- /**
2465
- * Creates documents in the Prismic repository's migration release.
2466
- *
2467
- * @param migration - A migration prepared with {@link createMigration}.
2468
- * @param params - An event listener and additional fetch parameters.
2469
- *
2470
- * @internal This method is one of the step performed by the {@link migrate} method.
2471
- */
2472
- async migrateCreateDocuments(migration, {
2473
- reporter,
2474
- ...fetchParams
2475
- } = {}) {
2476
- const repository = await this.getRepository(fetchParams);
2477
- const masterLocale = repository.languages.find((lang) => lang.is_master).id;
2478
- reporter?.({
2479
- type: "documents:masterLocale",
2480
- data: {
2481
- masterLocale
2482
- }
2483
- });
2484
- const documentsToCreate = [];
2485
- for (const doc of migration._documents) {
2486
- if (!doc.document.id) {
2487
- if (doc.document.lang === masterLocale) {
2488
- documentsToCreate.unshift(doc);
2489
- } else {
2490
- documentsToCreate.push(doc);
2491
- }
2492
- }
2493
- }
2494
- let created = 0;
2495
- for (const doc of documentsToCreate) {
2496
- reporter?.({
2497
- type: "documents:creating",
2498
- data: {
2499
- current: ++created,
2500
- remaining: documentsToCreate.length - created,
2501
- total: documentsToCreate.length,
2502
- document: doc
2503
- }
2504
- });
2505
- let masterLanguageDocumentID;
2506
- if (doc.masterLanguageDocument) {
2507
- const masterLanguageDocument = await resolveMigrationContentRelationship(doc.masterLanguageDocument);
2508
- masterLanguageDocumentID = "id" in masterLanguageDocument ? masterLanguageDocument.id : void 0;
2509
- } else if (doc.originalPrismicDocument) {
2510
- const maybeOriginalID = doc.originalPrismicDocument.alternate_languages.find(
2511
- ({ lang }) => lang === masterLocale
2512
- )?.id;
2513
- if (maybeOriginalID) {
2514
- masterLanguageDocumentID = migration._getByOriginalID(maybeOriginalID)?.document.id;
2515
- }
2516
- }
2517
- const { id } = await this.createDocument(
2518
- // We'll upload documents data later on.
2519
- { ...doc.document, data: {} },
2520
- doc.title,
2521
- {
2522
- masterLanguageDocumentID,
2523
- ...fetchParams
2524
- }
2525
- );
2526
- doc.document.id = id;
2527
- }
2528
- reporter?.({
2529
- type: "documents:created",
2530
- data: { created }
2531
- });
2532
- }
2533
- /**
2534
- * Updates documents in the Prismic repository's migration release with their
2535
- * patched data.
2536
- *
2537
- * @param migration - A migration prepared with {@link createMigration}.
2538
- * @param params - An event listener and additional fetch parameters.
2539
- *
2540
- * @internal This method is one of the step performed by the {@link migrate} method.
2541
- */
2542
- async migrateUpdateDocuments(migration, {
2543
- reporter,
2544
- ...fetchParams
2545
- } = {}) {
2546
- let i = 0;
2547
- for (const doc of migration._documents) {
2548
- reporter?.({
2549
- type: "documents:updating",
2550
- data: {
2551
- current: ++i,
2552
- remaining: migration._documents.length - i,
2553
- total: migration._documents.length,
2554
- document: doc
2555
- }
2556
- });
2557
- await this.updateDocument(
2558
- doc.document.id,
2559
- // We need to forward again document name and tags to update them
2560
- // in case the document already existed during the previous step.
2561
- {
2562
- ...doc.document,
2563
- documentTitle: doc.title,
2564
- data: await resolveMigrationDocumentData(
2565
- doc.document.data,
2566
- migration
2567
- )
2568
- },
2569
- fetchParams
2570
- );
2571
- }
2572
- reporter?.({
2573
- type: "documents:updated",
2574
- data: {
2575
- updated: migration._documents.length
2576
- }
2577
- });
2578
- }
2579
- /**
2580
- * Creates an asset in the Prismic media library.
2581
- *
2582
- * @param file - The file to upload as an asset.
2583
- * @param filename - The filename of the asset.
2584
- * @param params - Additional asset data and fetch parameters.
2585
- *
2586
- * @returns The created asset.
2587
- */
2588
- async createAsset(file, filename, {
2589
- notes,
2590
- credits,
2591
- alt,
2592
- tags,
2593
- ...params
2594
- } = {}) {
2595
- const url = new URL("assets", this.assetAPIEndpoint);
2596
- const formData = new FormData();
2597
- formData.append(
2598
- "file",
2599
- new File([file], filename, {
2600
- type: file instanceof File ? file.type : void 0
2601
- })
2602
- );
2603
- if (notes) {
2604
- formData.append("notes", notes);
2605
- }
2606
- if (credits) {
2607
- formData.append("credits", credits);
2608
- }
2609
- if (alt) {
2610
- formData.append("alt", alt);
2611
- }
2612
- const response = await this.#request(url, params, {
2613
- method: "POST",
2614
- body: formData
2615
- });
2616
- switch (response.status) {
2617
- case 200: {
2618
- const asset = await response.json();
2619
- if (tags && tags.length) {
2620
- return this.updateAsset(asset.id, { tags });
2621
- }
2622
- return asset;
2623
- }
2624
- default: {
2625
- return await this.#handleAssetAPIError(response);
2626
- }
2627
- }
2628
- }
2629
- /**
2630
- * Updates an asset in the Prismic media library.
2631
- *
2632
- * @param id - The ID of the asset to update.
2633
- * @param params - The asset data to update and additional fetch parameters.
2634
- *
2635
- * @returns The updated asset.
2636
- */
2637
- async updateAsset(id, {
2638
- notes,
2639
- credits,
2640
- alt,
2641
- filename,
2642
- tags,
2643
- ...params
2644
- } = {}) {
2645
- const url = new URL(`assets/${id}`, this.assetAPIEndpoint);
2646
- if (tags && tags.length) {
2647
- tags = await this.resolveAssetTagIDs(tags, {
2648
- createTags: true,
2649
- ...params
2650
- });
2651
- }
2652
- const response = await this.#request(url, params, {
2653
- method: "PATCH",
2654
- body: JSON.stringify({
2655
- notes,
2656
- credits,
2657
- alt,
2658
- filename,
2659
- tags
2660
- }),
2661
- headers: {
2662
- "content-type": "application/json"
2663
- }
2664
- });
2665
- switch (response.status) {
2666
- case 200: {
2667
- return await response.json();
2668
- }
2669
- default: {
2670
- return await this.#handleAssetAPIError(response);
2671
- }
2672
- }
2673
- }
2674
- /**
2675
- * Fetches a foreign asset from a URL.
2676
- *
2677
- * @param url - The URL of the asset to fetch.
2678
- * @param params - Additional fetch parameters.
2679
- *
2680
- * @returns A file representing the fetched asset.
2681
- */
2682
- async fetchForeignAsset(url, params = {}) {
2683
- const res = await this.fetchFn(url, this._buildRequestInit(params));
2684
- if (!res.ok) {
2685
- throw new PrismicError("Could not fetch foreign asset", url, void 0);
2686
- }
2687
- const blob = await res.blob();
2688
- return new File([blob], "", {
2689
- type: res.headers.get("content-type") || void 0
2690
- });
2691
- }
2692
- /**
2693
- * {@link resolveAssetTagIDs} rate limiter.
2694
- */
2695
- _resolveAssetTagIDsLimit = pLimit();
2696
- /**
2697
- * Resolves asset tag IDs from tag names.
2698
- *
2699
- * @param tagNames - An array of tag names to resolve.
2700
- * @param params - Whether or not missing tags should be created and
2701
- * additional fetch parameters.
2702
- *
2703
- * @returns An array of resolved tag IDs.
2704
- */
2705
- async resolveAssetTagIDs(tagNames = [], { createTags, ...params } = {}) {
2706
- return this._resolveAssetTagIDsLimit(async () => {
2707
- const existingTags = await this.getAssetTags(params);
2708
- const existingTagMap = {};
2709
- for (const tag of existingTags) {
2710
- existingTagMap[tag.name] = tag;
2711
- }
2712
- const resolvedTagIDs = [];
2713
- for (const tagName of tagNames) {
2714
- if (!existingTagMap[tagName] && createTags) {
2715
- existingTagMap[tagName] = await this.createAssetTag(tagName, params);
2716
- }
2717
- if (existingTagMap[tagName]) {
2718
- resolvedTagIDs.push(existingTagMap[tagName].id);
2719
- }
2720
- }
2721
- return resolvedTagIDs;
2722
- });
2723
- }
2724
- /**
2725
- * Creates a tag in the Asset API.
2726
- *
2727
- * @remarks
2728
- * Tags should be at least 3 characters long and 20 characters at most.
2729
- *
2730
- * @param name - The name of the tag to create.
2731
- * @param params - Additional fetch parameters.
2732
- *
2733
- * @returns The created tag.
2734
- */
2735
- async createAssetTag(name2, params) {
2736
- const url = new URL("tags", this.assetAPIEndpoint);
2737
- const response = await this.#request(url, params, {
2738
- method: "POST",
2739
- body: JSON.stringify({ name: name2 }),
2740
- headers: {
2741
- "content-type": "application/json"
2742
- }
2743
- });
2744
- switch (response.status) {
2745
- case 201: {
2746
- return await response.json();
2747
- }
2748
- default: {
2749
- return await this.#handleAssetAPIError(response);
2750
- }
2751
- }
2752
- }
2753
- /**
2754
- * Queries existing tags from the Asset API.
2755
- *
2756
- * @param params - Additional fetch parameters.
2757
- *
2758
- * @returns An array of existing tags.
2759
- */
2760
- async getAssetTags(params) {
2761
- const url = new URL("tags", this.assetAPIEndpoint);
2762
- const response = await this.#request(url, params);
2763
- switch (response.status) {
2764
- case 200: {
2765
- const json = await response.json();
2766
- return json.items;
2767
- }
2768
- default: {
2769
- return await this.#handleAssetAPIError(response);
2770
- }
2771
- }
2772
- }
2773
- /**
2774
- * Creates a document in the repository's migration release.
2775
- *
2776
- * @typeParam TType - Type of Prismic documents to create.
2777
- *
2778
- * @param document - The document to create.
2779
- * @param documentTitle - The title of the document to create which will be
2780
- * displayed in the editor.
2781
- * @param params - Document master language document ID and additional fetch
2782
- * parameters.
2783
- *
2784
- * @returns The ID of the created document.
2785
- *
2786
- * @see Prismic Migration API technical reference: {@link https://prismic.io/docs/migration-api-technical-reference}
2787
- */
2788
- async createDocument(document, documentTitle, {
2789
- masterLanguageDocumentID,
2790
- ...params
2791
- } = {}) {
2792
- const url = new URL("documents", this.migrationAPIEndpoint);
2793
- const response = await this.#request(url, params, {
2794
- method: "POST",
2795
- body: JSON.stringify({
2796
- title: documentTitle,
2797
- type: document.type,
2798
- uid: document.uid || void 0,
2799
- lang: document.lang,
2800
- alternate_language_id: masterLanguageDocumentID,
2801
- tags: document.tags,
2802
- data: document.data
2803
- }),
2804
- headers: {
2805
- "content-type": "application/json",
2806
- "x-client": CLIENT_IDENTIFIER
2807
- }
2808
- });
2809
- switch (response.status) {
2810
- case 201: {
2811
- const json = await response.json();
2812
- return { id: json.id };
2813
- }
2814
- default: {
2815
- return await this.#handleMigrationAPIError(response);
2816
- }
2817
- }
2818
- }
2819
- /**
2820
- * Updates an existing document in the repository's migration release.
2821
- *
2822
- * @typeParam TType - Type of Prismic documents to update.
2823
- *
2824
- * @param id - The ID of the document to update.
2825
- * @param document - The document content to update.
2826
- * @param params - Additional fetch parameters.
2827
- *
2828
- * @see Prismic Migration API technical reference: {@link https://prismic.io/docs/migration-api-technical-reference}
2829
- */
2830
- async updateDocument(id, document, params) {
2831
- const url = new URL(`documents/${id}`, this.migrationAPIEndpoint);
2832
- const response = await this.#request(url, params, {
2833
- method: "PUT",
2834
- body: JSON.stringify({
2835
- title: document.documentTitle,
2836
- uid: document.uid || void 0,
2837
- tags: document.tags,
2838
- data: document.data
2839
- }),
2840
- headers: {
2841
- "content-type": "application/json",
2842
- "x-client": CLIENT_IDENTIFIER
2843
- }
2844
- });
2845
- switch (response.status) {
2846
- case 200: {
2847
- return;
2848
- }
2849
- default: {
2850
- await this.#handleMigrationAPIError(response);
2851
- }
2852
- }
2853
- }
2854
- /**
2855
- * Makes an authenticated HTTP request for write operations using the client's
2856
- * configured fetch function and options.
2857
- *
2858
- * @param url - The URL to request.
2859
- * @param params - Fetch options from the user.
2860
- * @param init - Additional fetch options to merge with the user-provided
2861
- * options.
2862
- *
2863
- * @returns The response from the fetch request.
2864
- */
2865
- async #request(url, params, init) {
2866
- const baseInit = this._buildRequestInit(params);
2867
- return await request(
2868
- url,
2869
- {
2870
- ...baseInit,
2871
- ...init,
2872
- headers: {
2873
- ...baseInit.headers,
2874
- ...init?.headers,
2875
- repository: this.repositoryName,
2876
- authorization: `Bearer ${this.writeToken}`
2877
- }
2878
- },
2879
- this.fetchFn
2880
- );
2881
- }
2882
- /**
2883
- * Handles error responses from the Asset API with comprehensive error
2884
- * parsing.
2885
- *
2886
- * @param response - The HTTP response from the Asset API.
2887
- *
2888
- * @throws {@link InvalidDataError} For 400 errors.
2889
- * @throws {@link ForbiddenError} For 401 and 403 errors.
2890
- * @throws {@link NotFoundError} For 404 errors.
2891
- * @throws {@link PrismicError} For 500, 503, and other unexpected errors.
2892
- */
2893
- async #handleAssetAPIError(response) {
2894
- const json = await response.json();
2895
- switch (response.status) {
2896
- case 401:
2897
- case 403:
2898
- throw new ForbiddenError(json.error, response.url, json);
2899
- case 404:
2900
- throw new NotFoundError(json.error, response.url, json);
2901
- case 400:
2902
- throw new InvalidDataError(json.error, response.url, json);
2903
- case 500:
2904
- case 503:
2905
- default:
2906
- throw new PrismicError(json.error, response.url, json);
2907
- }
2908
- }
2909
- /**
2910
- * Handles error responses from the Migration API with comprehensive error
2911
- * parsing.
2912
- *
2913
- * @param response - The HTTP response from the Migration API.
2914
- *
2915
- * @throws {@link InvalidDataError} For 400 errors.
2916
- * @throws {@link ForbiddenError} For 401 and 403 errors.
2917
- * @throws {@link NotFoundError} For 404 errors.
2918
- * @throws {@link PrismicError} For 500, and other unexpected errors.
2919
- */
2920
- async #handleMigrationAPIError(response) {
2921
- const text = await response.text();
2922
- let json;
2923
- try {
2924
- json = JSON.parse(text);
2925
- } catch {
2926
- }
2927
- switch (response.status) {
2928
- case 400:
2929
- if (json) {
2930
- throw new InvalidDataError(
2931
- "Validation failed, check the response property of the error for details",
2932
- response.url,
2933
- json
2934
- // `json` has the shape Array<{ property: string, value: unknown, error: string }>
2935
- );
2936
- }
2937
- throw new InvalidDataError(text, response.url, text);
2938
- case 401:
2939
- throw new ForbiddenError(text, response.url, text);
2940
- case 403:
2941
- if (json) {
2942
- throw new ForbiddenError(
2943
- json.Message,
2944
- response.url,
2945
- json
2946
- );
2947
- }
2948
- throw new ForbiddenError(text, response.url, text);
2949
- case 404:
2950
- throw new NotFoundError(text, response.url, text);
2951
- case 500:
2952
- default:
2953
- throw new PrismicError(text, response.url, text);
2954
- }
2955
- }
2956
- }
2957
-
2958
- const createWriteClient = (repositoryName, options) => new WriteClient(repositoryName, options);
2959
-
2960
- const ASSET_NOTES_MAX_LENGTH = 500;
2961
- const ASSET_CREDITS_MAX_LENGTH = 500;
2962
- const ASSET_ALT_MAX_LENGTH = 500;
2963
- const ASSET_TAG_MIN_LENGTH = 3;
2964
- const ASSET_TAG_MAX_LENGTH = 20;
2965
- const validateAssetMetadata = ({
2966
- notes,
2967
- credits,
2968
- alt,
2969
- tags
2970
- }) => {
2971
- const errors = [];
2972
- if (notes && notes.length > ASSET_NOTES_MAX_LENGTH) {
2973
- errors.push(
2974
- `\`notes\` must be at most ${ASSET_NOTES_MAX_LENGTH} characters`
2975
- );
2976
- }
2977
- if (credits && credits.length > ASSET_CREDITS_MAX_LENGTH) {
2978
- errors.push(
2979
- `\`credits\` must be at most ${ASSET_CREDITS_MAX_LENGTH} characters`
2980
- );
2981
- }
2982
- if (alt && alt.length > ASSET_ALT_MAX_LENGTH) {
2983
- errors.push(`\`alt\` must be at most ${ASSET_ALT_MAX_LENGTH} characters`);
2984
- }
2985
- if (tags && tags.length && tags.some(
2986
- (tag) => tag.length < ASSET_TAG_MIN_LENGTH || tag.length > ASSET_TAG_MAX_LENGTH
2987
- )) {
2988
- errors.push(
2989
- `tags must be at least 3 characters long and 20 characters at most`
2990
- );
2991
- }
2992
- if (errors.length) {
2993
- throw new PrismicError(
2994
- `Errors validating asset metadata: ${errors.join(", ")}`,
2995
- void 0,
2996
- { notes, credits, alt, tags }
2997
- );
2998
- }
2999
- };
3000
-
3001
- class Migration {
3002
- /**
3003
- * Assets registered in the migration.
3004
- *
3005
- * @internal
3006
- */
3007
- _assets = /* @__PURE__ */ new Map();
3008
- /**
3009
- * Documents registered in the migration.
3010
- *
3011
- * @internal
3012
- */
3013
- _documents = [];
3014
- /**
3015
- * Registers an asset to be created in the migration from a file, an asset
3016
- * object, or an image or link to media field.
3017
- *
3018
- * @remarks
3019
- * This method does not create the asset in Prismic media library right away.
3020
- * Instead, it registers it in your migration. The asset will be created when
3021
- * the migration is executed through the `writeClient.migrate()` method.
3022
- *
3023
- * @returns A migration asset field instance.
3024
- */
3025
- createAsset(fileOrAssetOrField, filename, {
3026
- notes,
3027
- credits,
3028
- alt,
3029
- tags
3030
- } = {}) {
3031
- let config;
3032
- let maybeInitialField;
3033
- if (typeof fileOrAssetOrField === "object" && "url" in fileOrAssetOrField) {
3034
- if ("dimensions" in fileOrAssetOrField || "link_type" in fileOrAssetOrField) {
3035
- const url = fileOrAssetOrField.url.split("?")[0];
3036
- const filename2 = "name" in fileOrAssetOrField ? fileOrAssetOrField.name : url.split("/").pop().split("_").pop();
3037
- const credits2 = "copyright" in fileOrAssetOrField && fileOrAssetOrField.copyright ? fileOrAssetOrField.copyright : void 0;
3038
- const alt2 = "alt" in fileOrAssetOrField && fileOrAssetOrField.alt ? fileOrAssetOrField.alt : void 0;
3039
- if ("dimensions" in fileOrAssetOrField) {
3040
- maybeInitialField = fileOrAssetOrField;
3041
- }
3042
- config = {
3043
- id: fileOrAssetOrField.id,
3044
- file: url,
3045
- filename: filename2,
3046
- notes: void 0,
3047
- credits: credits2,
3048
- alt: alt2,
3049
- tags: void 0
3050
- };
3051
- } else {
3052
- config = {
3053
- id: fileOrAssetOrField.id,
3054
- file: fileOrAssetOrField.url,
3055
- filename: fileOrAssetOrField.filename,
3056
- notes: fileOrAssetOrField.notes,
3057
- credits: fileOrAssetOrField.credits,
3058
- alt: fileOrAssetOrField.alt,
3059
- tags: fileOrAssetOrField.tags?.map(({ name }) => name)
3060
- };
3061
- }
3062
- } else {
3063
- config = {
3064
- id: fileOrAssetOrField,
3065
- file: fileOrAssetOrField,
3066
- filename,
3067
- notes,
3068
- credits,
3069
- alt,
3070
- tags
3071
- };
3072
- }
3073
- validateAssetMetadata(config);
3074
- const migrationAsset = new PrismicMigrationAsset(config, maybeInitialField);
3075
- const maybeAsset = this._assets.get(config.id);
3076
- if (maybeAsset) {
3077
- maybeAsset.config.notes = maybeAsset.config.notes || config.notes;
3078
- maybeAsset.config.credits = maybeAsset.config.credits || config.credits;
3079
- maybeAsset.config.alt = maybeAsset.config.alt || config.alt;
3080
- maybeAsset.config.tags = Array.from(
3081
- /* @__PURE__ */ new Set([...maybeAsset.config.tags || [], ...config.tags || []])
3082
- );
3083
- } else {
3084
- this._assets.set(config.id, migrationAsset);
3085
- }
3086
- return migrationAsset;
3087
- }
3088
- /**
3089
- * Registers a document to be created in the migration.
3090
- *
3091
- * @remarks
3092
- * This method does not create the document in Prismic right away. Instead, it
3093
- * registers it in your migration. The document will be created when the
3094
- * migration is executed through the `writeClient.migrate()` method.
3095
- *
3096
- * @typeParam TType - Type of the Prismic document to create.
3097
- *
3098
- * @param document - The document to create.
3099
- * @param title - The title of the document to create which will be displayed
3100
- * in the editor.
3101
- * @param params - Document master language document ID.
3102
- *
3103
- * @returns A migration document instance.
3104
- */
3105
- createDocument(document, title, params) {
3106
- const doc = new PrismicMigrationDocument(document, title, params);
3107
- this._documents.push(doc);
3108
- return doc;
3109
- }
3110
- /**
3111
- * Registers an existing document to be updated in the migration.
3112
- *
3113
- * @remarks
3114
- * This method does not update the document in Prismic right away. Instead, it
3115
- * registers it in your migration. The document will be updated when the
3116
- * migration is executed through the `writeClient.migrate()` method.
3117
- *
3118
- * @typeParam TType - Type of Prismic documents to update.
3119
- *
3120
- * @param document - The document to update.
3121
- * @param title - The title of the document to update which will be displayed
3122
- * in the editor.
3123
- *
3124
- * @returns A migration document instance.
3125
- */
3126
- updateDocument(document, title) {
3127
- const doc = new PrismicMigrationDocument(document, title);
3128
- this._documents.push(doc);
3129
- return doc;
3130
- }
3131
- /**
3132
- * Registers a document from another Prismic repository to be created in the
3133
- * migration.
3134
- *
3135
- * @remarks
3136
- * This method does not create the document in Prismic right away. Instead, it
3137
- * registers it in your migration. The document will be created when the
3138
- * migration is executed through the `writeClient.migrate()` method.
3139
- *
3140
- * @param document - The document from Prismic to create.
3141
- * @param title - The title of the document to create which will be displayed
3142
- * in the editor.
3143
- *
3144
- * @returns A migration document instance.
3145
- */
3146
- createDocumentFromPrismic(document, title) {
3147
- const doc = new PrismicMigrationDocument(
3148
- this.#migratePrismicDocumentData({
3149
- type: document.type,
3150
- lang: document.lang,
3151
- uid: document.uid,
3152
- tags: document.tags,
3153
- data: document.data
3154
- }),
3155
- title,
3156
- { originalPrismicDocument: document }
3157
- );
3158
- this._documents.push(doc);
3159
- return doc;
3160
- }
3161
- /**
3162
- * Queries a document from the migration instance with a specific UID and
3163
- * custom type.
3164
- *
3165
- * @example
3166
- *
3167
- * ```ts
3168
- * const contentRelationship = migration.createContentRelationship(() =>
3169
- * migration.getByUID("blog_post", "my-first-post"),
3170
- * )
3171
- * ```
3172
- *
3173
- * @typeParam TType - Type of the Prismic document returned.
3174
- *
3175
- * @param type - The API ID of the document's custom type.
3176
- * @param uid - The UID of the document.
3177
- *
3178
- * @returns The migration document instance with a UID matching the `uid`
3179
- * parameter, if a matching document is found.
3180
- */
3181
- getByUID(type, uid) {
3182
- return this._documents.find(
3183
- (doc) => doc.document.type === type && doc.document.uid === uid
3184
- );
3185
- }
3186
- /**
3187
- * Queries a singleton document from the migration instance for a specific
3188
- * custom type.
3189
- *
3190
- * @example
3191
- *
3192
- * ```ts
3193
- * const contentRelationship = migration.createContentRelationship(() =>
3194
- * migration.getSingle("settings"),
3195
- * )
3196
- * ```
3197
- *
3198
- * @typeParam TType - Type of the Prismic document returned.
3199
- *
3200
- * @param type - The API ID of the singleton custom type.
3201
- *
3202
- * @returns The migration document instance for the custom type, if a matching
3203
- * document is found.
3204
- */
3205
- getSingle(type) {
3206
- return this._documents.find(
3207
- (doc) => doc.document.type === type
3208
- );
3209
- }
3210
- /**
3211
- * Migrates a Prismic document data from another repository so that it can be
3212
- * created through the current repository's Migration API.
3213
- *
3214
- * @param input - The Prismic document data to migrate.
3215
- *
3216
- * @returns The migrated Prismic document data.
3217
- */
3218
- #migratePrismicDocumentData(input) {
3219
- if (filledContentRelationship(input)) {
3220
- const optionalLinkProperties = getOptionalLinkProperties(input);
3221
- if (input.isBroken) {
3222
- return {
3223
- ...optionalLinkProperties,
3224
- link_type: LinkType.Document,
3225
- // ID needs to be 16 characters long to be considered valid by the API
3226
- id: "_____broken_____",
3227
- isBroken: true
3228
- };
3229
- }
3230
- return {
3231
- ...optionalLinkProperties,
3232
- link_type: LinkType.Document,
3233
- id: () => this._getByOriginalID(input.id)
3234
- };
3235
- }
3236
- if (filledLinkToMedia(input)) {
3237
- const optionalLinkProperties = getOptionalLinkProperties(input);
3238
- return {
3239
- ...optionalLinkProperties,
3240
- link_type: LinkType.Media,
3241
- id: this.createAsset(input)
3242
- };
3243
- }
3244
- if (rtImageNode$1(input)) {
3245
- const rtImageNode = {
3246
- type: RichTextNodeType.image,
3247
- id: this.createAsset(input)
3248
- };
3249
- if (input.linkTo) {
3250
- rtImageNode.linkTo = this.#migratePrismicDocumentData(input.linkTo);
3251
- }
3252
- return rtImageNode;
3253
- }
3254
- if (filledImage(input)) {
3255
- const image = {
3256
- id: this.createAsset(input)
3257
- };
3258
- const {
3259
- id: _id,
3260
- url: _url,
3261
- dimensions: _dimensions,
3262
- edit: _edit,
3263
- alt: _alt,
3264
- copyright: _copyright,
3265
- ...thumbnails
3266
- } = input;
3267
- for (const name in thumbnails) {
3268
- if (filledImage(thumbnails[name])) {
3269
- image[name] = this.createAsset(thumbnails[name]);
3270
- }
3271
- }
3272
- return image;
3273
- }
3274
- if (Array.isArray(input)) {
3275
- return input.map((element) => this.#migratePrismicDocumentData(element));
3276
- }
3277
- if (input && typeof input === "object") {
3278
- const res = {};
3279
- for (const key in input) {
3280
- res[key] = this.#migratePrismicDocumentData(
3281
- input[key]
3282
- );
3283
- }
3284
- return res;
3285
- }
3286
- return input;
3287
- }
3288
- /**
3289
- * Queries a document from the migration instance for a specific original ID.
3290
- *
3291
- * @example
3292
- *
3293
- * ```ts
3294
- * const contentRelationship = migration.createContentRelationship(() =>
3295
- * migration._getByOriginalID("YhdrDxIAACgAcp_b"),
3296
- * )
3297
- * ```
3298
- *
3299
- * @typeParam TType - Type of the Prismic document returned.
3300
- *
3301
- * @param id - The original ID of the Prismic document.
3302
- *
3303
- * @returns The migration document instance for the original ID, if a matching
3304
- * document is found.
3305
- *
3306
- * @internal
3307
- */
3308
- _getByOriginalID(id) {
3309
- return this._documents.find(
3310
- (doc) => doc.originalPrismicDocument?.id === id
3311
- );
3312
- }
3313
- }
3314
-
3315
- const createMigration = () => new Migration();
3316
-
3317
- const getGraphQLEndpoint = (repositoryName) => {
3318
- if (isRepositoryName(repositoryName)) {
3319
- return `https://${repositoryName}.cdn.prismic.io/graphql`;
3320
- } else {
3321
- throw new PrismicError(
3322
- `An invalid Prismic repository name was given: ${repositoryName}`,
3323
- void 0,
3324
- void 0
3325
- );
3326
- }
3327
- };
3328
-
3329
- const getToolbarSrc = (repositoryName) => {
3330
- if (isRepositoryName(repositoryName)) {
3331
- return `https://static.cdn.prismic.io/prismic.js?new=true&repo=${repositoryName}`;
3332
- } else {
3333
- throw new PrismicError(
3334
- `An invalid Prismic repository name was given: ${repositoryName}`,
3335
- void 0,
3336
- void 0
3337
- );
3338
- }
3339
- };
3340
-
3341
- const asDate = (dateOrTimestampField) => {
3342
- if (!dateOrTimestampField) {
3343
- return null;
3344
- }
3345
- if (dateOrTimestampField.length === 24) {
3346
- return new Date(
3347
- dateOrTimestampField.replace(/(\+|-)(\d{2})(\d{2})$/, ".000$1$2:$3")
3348
- );
3349
- } else {
3350
- return new Date(dateOrTimestampField);
3351
- }
3352
- };
3353
-
3354
- const isInternalURL = (url) => {
3355
- const isInternal = /^(\/(?!\/)|#)/.test(url);
3356
- const isSpecialLink = !isInternal && !/^https?:\/\//.test(url);
3357
- return isInternal && !isSpecialLink;
3358
- };
3359
-
3360
- const asLinkAttrs = (linkFieldOrDocument, config = {}) => {
3361
- if (linkFieldOrDocument && // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3362
- // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501
3363
- ("link_type" in linkFieldOrDocument ? link(linkFieldOrDocument) : linkFieldOrDocument)) {
3364
- const target = (
3365
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3366
- // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501
3367
- "target" in linkFieldOrDocument ? linkFieldOrDocument.target : void 0
3368
- );
3369
- const rawHref = asLink(linkFieldOrDocument, config.linkResolver);
3370
- const href = rawHref == null ? void 0 : rawHref;
3371
- const isExternal = typeof href === "string" ? !isInternalURL(href) : false;
3372
- const rel = config.rel ? config.rel({ href, isExternal, target }) : isExternal ? "noreferrer" : void 0;
3373
- return {
3374
- href,
3375
- target,
3376
- rel: rel == null ? void 0 : rel
3377
- };
3378
- }
3379
- return {};
3380
- };
3381
-
3382
- const asText = (richTextField, ...configObjectOrTuple) => {
3383
- if (richTextField) {
3384
- const [configObjectOrSeparator] = configObjectOrTuple;
3385
- let config;
3386
- if (typeof configObjectOrSeparator === "string") {
3387
- config = {
3388
- separator: configObjectOrSeparator
3389
- };
3390
- } else {
3391
- config = { ...configObjectOrSeparator };
3392
- }
3393
- return asText$1(
3394
- richTextField,
3395
- config.separator
3396
- );
3397
- } else {
3398
- return null;
3399
- }
3400
- };
3401
-
3402
- const matchHtmlRegExp = /["'&<>]/;
3403
- const escapeHTML = (string) => {
3404
- const str = "" + string;
3405
- const match = matchHtmlRegExp.exec(str);
3406
- if (!match) {
3407
- return str;
3408
- }
3409
- let escape;
3410
- let html = "";
3411
- let index = 0;
3412
- let lastIndex = 0;
3413
- for (index = match.index; index < str.length; index++) {
3414
- switch (str.charCodeAt(index)) {
3415
- case 34:
3416
- escape = "&quot;";
3417
- break;
3418
- case 38:
3419
- escape = "&amp;";
3420
- break;
3421
- case 39:
3422
- escape = "&#39;";
3423
- break;
3424
- case 60:
3425
- escape = "&lt;";
3426
- break;
3427
- case 62:
3428
- escape = "&gt;";
3429
- break;
3430
- default:
3431
- continue;
3432
- }
3433
- if (lastIndex !== index) {
3434
- html += str.substring(lastIndex, index);
3435
- }
3436
- lastIndex = index + 1;
3437
- html += escape;
3438
- }
3439
- return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
3440
- };
3441
-
3442
- const formatAttributes = (node, attributes) => {
3443
- const _attributes = { ...attributes };
3444
- if ("direction" in node && node.direction === "rtl") {
3445
- _attributes.dir = node.direction;
3446
- }
3447
- if ("data" in node && "label" in node.data && node.data.label) {
3448
- _attributes.class = _attributes.class ? `${_attributes.class} ${node.data.label}` : node.data.label;
3449
- }
3450
- const result = [];
3451
- for (const key in _attributes) {
3452
- const value = _attributes[key];
3453
- if (value) {
3454
- if (typeof value === "boolean") {
3455
- result.push(key);
3456
- } else {
3457
- result.push(`${key}="${escapeHTML(value)}"`);
3458
- }
3459
- }
3460
- }
3461
- if (result.length) {
3462
- result.unshift("");
3463
- }
3464
- return result.join(" ");
3465
- };
3466
- const getGeneralAttributes = (serializerOrShorthand) => {
3467
- return serializerOrShorthand && typeof serializerOrShorthand !== "function" ? serializerOrShorthand : {};
3468
- };
3469
- const serializeStandardTag = (tag, serializerOrShorthand) => {
3470
- const generalAttributes = getGeneralAttributes(serializerOrShorthand);
3471
- return (({ node, children }) => {
3472
- return `<${tag}${formatAttributes(
3473
- node,
3474
- generalAttributes
3475
- )}>${children}</${tag}>`;
3476
- });
3477
- };
3478
- const serializePreFormatted = (serializerOrShorthand) => {
3479
- const generalAttributes = getGeneralAttributes(serializerOrShorthand);
3480
- return ({ node }) => {
3481
- return `<pre${formatAttributes(node, generalAttributes)}>${escapeHTML(
3482
- node.text
3483
- )}</pre>`;
3484
- };
3485
- };
3486
- const serializeImage = (linkResolver, serializerOrShorthand) => {
3487
- const generalAttributes = getGeneralAttributes(serializerOrShorthand);
3488
- return ({ node }) => {
3489
- const attributes = {
3490
- ...generalAttributes,
3491
- src: node.url,
3492
- alt: node.alt,
3493
- copyright: node.copyright
3494
- };
3495
- let imageTag = `<img${formatAttributes(node, attributes)} />`;
3496
- if (node.linkTo) {
3497
- imageTag = serializeHyperlink(linkResolver)({
3498
- type: "hyperlink",
3499
- node: {
3500
- type: "hyperlink",
3501
- data: node.linkTo,
3502
- start: 0,
3503
- end: 0
3504
- },
3505
- text: "",
3506
- children: imageTag,
3507
- key: ""
3508
- });
3509
- }
3510
- return `<p class="block-img">${imageTag}</p>`;
3511
- };
3512
- };
3513
- const serializeEmbed = (serializerOrShorthand) => {
3514
- const generalAttributes = getGeneralAttributes(serializerOrShorthand);
3515
- return ({ node }) => {
3516
- const attributes = {
3517
- ...generalAttributes,
3518
- ["data-oembed"]: node.oembed.embed_url,
3519
- ["data-oembed-type"]: node.oembed.type,
3520
- ["data-oembed-provider"]: node.oembed.provider_name
3521
- };
3522
- return `<div${formatAttributes(node, attributes)}>${node.oembed.html}</div>`;
3523
- };
3524
- };
3525
- const serializeHyperlink = (linkResolver, serializerOrShorthand) => {
3526
- const generalAttributes = getGeneralAttributes(serializerOrShorthand);
3527
- return ({ node, children }) => {
3528
- const attributes = {
3529
- ...generalAttributes
3530
- };
3531
- if (node.data.link_type === LinkType.Web) {
3532
- attributes.href = node.data.url;
3533
- attributes.target = node.data.target;
3534
- attributes.rel = "noopener noreferrer";
3535
- } else if (node.data.link_type === LinkType.Document) {
3536
- attributes.href = asLink(node.data, { linkResolver });
3537
- } else if (node.data.link_type === LinkType.Media) {
3538
- attributes.href = node.data.url;
3539
- }
3540
- return `<a${formatAttributes(node, attributes)}>${children}</a>`;
3541
- };
3542
- };
3543
- const serializeSpan = () => {
3544
- return ({ text }) => {
3545
- return text ? escapeHTML(text).replace(/\n/g, "<br />") : "";
3546
- };
3547
- };
3548
-
3549
- const createHTMLRichTextSerializer = (linkResolver, serializer) => {
3550
- const useSerializerOrDefault = (nodeSerializerOrShorthand, defaultWithShorthand) => {
3551
- if (typeof nodeSerializerOrShorthand === "function") {
3552
- return ((payload) => {
3553
- return nodeSerializerOrShorthand?.(payload) || defaultWithShorthand(payload);
3554
- });
3555
- }
3556
- return defaultWithShorthand;
3557
- };
3558
- const mapSerializer = {
3559
- heading1: useSerializerOrDefault(
3560
- serializer?.heading1,
3561
- serializeStandardTag("h1", serializer?.heading1)
3562
- ),
3563
- heading2: useSerializerOrDefault(
3564
- serializer?.heading2,
3565
- serializeStandardTag("h2", serializer?.heading2)
3566
- ),
3567
- heading3: useSerializerOrDefault(
3568
- serializer?.heading3,
3569
- serializeStandardTag("h3", serializer?.heading3)
3570
- ),
3571
- heading4: useSerializerOrDefault(
3572
- serializer?.heading4,
3573
- serializeStandardTag("h4", serializer?.heading4)
3574
- ),
3575
- heading5: useSerializerOrDefault(
3576
- serializer?.heading5,
3577
- serializeStandardTag("h5", serializer?.heading5)
3578
- ),
3579
- heading6: useSerializerOrDefault(
3580
- serializer?.heading6,
3581
- serializeStandardTag("h6", serializer?.heading6)
3582
- ),
3583
- paragraph: useSerializerOrDefault(
3584
- serializer?.paragraph,
3585
- serializeStandardTag("p", serializer?.paragraph)
3586
- ),
3587
- preformatted: useSerializerOrDefault(
3588
- serializer?.preformatted,
3589
- serializePreFormatted(serializer?.preformatted)
3590
- ),
3591
- strong: useSerializerOrDefault(
3592
- serializer?.strong,
3593
- serializeStandardTag("strong", serializer?.strong)
3594
- ),
3595
- em: useSerializerOrDefault(
3596
- serializer?.em,
3597
- serializeStandardTag("em", serializer?.em)
3598
- ),
3599
- listItem: useSerializerOrDefault(
3600
- serializer?.listItem,
3601
- serializeStandardTag("li", serializer?.listItem)
3602
- ),
3603
- oListItem: useSerializerOrDefault(
3604
- serializer?.oListItem,
3605
- serializeStandardTag("li", serializer?.oListItem)
3606
- ),
3607
- list: useSerializerOrDefault(
3608
- serializer?.list,
3609
- serializeStandardTag("ul", serializer?.list)
3610
- ),
3611
- oList: useSerializerOrDefault(
3612
- serializer?.oList,
3613
- serializeStandardTag("ol", serializer?.oList)
3614
- ),
3615
- image: useSerializerOrDefault(
3616
- serializer?.image,
3617
- serializeImage(linkResolver, serializer?.image)
3618
- ),
3619
- embed: useSerializerOrDefault(
3620
- serializer?.embed,
3621
- serializeEmbed(serializer?.embed)
3622
- ),
3623
- hyperlink: useSerializerOrDefault(
3624
- serializer?.hyperlink,
3625
- serializeHyperlink(linkResolver, serializer?.hyperlink)
3626
- ),
3627
- label: useSerializerOrDefault(
3628
- serializer?.label,
3629
- serializeStandardTag("span", serializer?.label)
3630
- ),
3631
- span: useSerializerOrDefault(serializer?.span, serializeSpan())
3632
- };
3633
- return wrapMapSerializerWithStringChildren(mapSerializer);
3634
- };
3635
- const wrapMapSerializerWithStringChildren = (mapSerializer) => {
3636
- const modifiedMapSerializer = {};
3637
- for (const tag in mapSerializer) {
3638
- const tagSerializer = mapSerializer[tag];
3639
- if (tagSerializer) {
3640
- modifiedMapSerializer[tag] = (payload) => {
3641
- return tagSerializer({
3642
- ...payload,
3643
- // @ts-expect-error - merging blockSerializer types causes TS to bail to a never type
3644
- children: payload.children.join("")
3645
- });
3646
- };
3647
- }
3648
- }
3649
- return wrapMapSerializer(modifiedMapSerializer);
3650
- };
3651
- const asHTML = (richTextField, ...configObjectOrTuple) => {
3652
- if (richTextField) {
3653
- const [configObjectOrLinkResolver, maybeSerializer] = configObjectOrTuple;
3654
- let config;
3655
- if (typeof configObjectOrLinkResolver === "function" || configObjectOrLinkResolver == null) {
3656
- config = {
3657
- linkResolver: configObjectOrLinkResolver,
3658
- serializer: maybeSerializer
3659
- };
3660
- } else {
3661
- config = { ...configObjectOrLinkResolver };
3662
- }
3663
- let serializer;
3664
- if (config.serializer) {
3665
- if (typeof config.serializer === "function") {
3666
- serializer = composeSerializers(
3667
- (type, node, text, children, key) => (
3668
- // TypeScript doesn't narrow the type correctly here since it is now in a callback function, so we have to cast it here.
3669
- config.serializer(
3670
- type,
3671
- node,
3672
- text,
3673
- children.join(""),
3674
- key
3675
- )
3676
- ),
3677
- createHTMLRichTextSerializer(config.linkResolver)
3678
- );
3679
- } else {
3680
- serializer = createHTMLRichTextSerializer(
3681
- config.linkResolver,
3682
- config.serializer
3683
- );
3684
- }
3685
- } else {
3686
- serializer = createHTMLRichTextSerializer(config.linkResolver);
3687
- }
3688
- return serialize(richTextField, serializer).join(
3689
- ""
3690
- );
3691
- } else {
3692
- return null;
3693
- }
3694
- };
3695
-
3696
- const asImageSrc = (field, config = {}) => {
3697
- if (field && imageThumbnail(field)) {
3698
- return buildURL(field.url, config);
3699
- } else {
3700
- return null;
3701
- }
3702
- };
3703
-
3704
- const DEFAULT_WIDTHS = [640, 828, 1200, 2048, 3840];
3705
- const asImageWidthSrcSet = (field, config = {}) => {
3706
- if (field && imageThumbnail(field)) {
3707
- let {
3708
- widths = DEFAULT_WIDTHS,
3709
- // eslint-disable-next-line prefer-const
3710
- ...imgixParams
3711
- } = config;
3712
- const {
3713
- url,
3714
- dimensions,
3715
- id: _id,
3716
- alt: _alt,
3717
- copyright: _copyright,
3718
- edit: _edit,
3719
- ...responsiveViews
3720
- } = field;
3721
- const responsiveViewObjects = Object.values(responsiveViews);
3722
- if (widths === "thumbnails" && responsiveViewObjects.length < 1) {
3723
- widths = DEFAULT_WIDTHS;
3724
- }
3725
- return {
3726
- src: buildURL(url, imgixParams),
3727
- srcset: (
3728
- // By this point, we know `widths` can only be
3729
- // `"thubmanils"` if the field has thumbnails.
3730
- widths === "thumbnails" ? [
3731
- buildWidthSrcSet(url, {
3732
- ...imgixParams,
3733
- widths: [dimensions.width]
3734
- }),
3735
- ...responsiveViewObjects.map((thumbnail) => {
3736
- return buildWidthSrcSet(thumbnail.url, {
3737
- ...imgixParams,
3738
- widths: [thumbnail.dimensions.width]
3739
- });
3740
- })
3741
- ].join(", ") : buildWidthSrcSet(field.url, {
3742
- ...imgixParams,
3743
- widths
3744
- })
3745
- )
3746
- };
3747
- } else {
3748
- return null;
3749
- }
3750
- };
3751
-
3752
- const DEFAULT_PIXEL_DENSITIES = [1, 2, 3];
3753
- const asImagePixelDensitySrcSet = (field, config = {}) => {
3754
- if (field && imageThumbnail(field)) {
3755
- const { pixelDensities = DEFAULT_PIXEL_DENSITIES, ...imgixParams } = config;
3756
- return {
3757
- src: buildURL(field.url, imgixParams),
3758
- srcset: buildPixelDensitySrcSet(field.url, {
3759
- ...imgixParams,
3760
- pixelDensities
3761
- })
3762
- };
3763
- } else {
3764
- return null;
3765
- }
3766
- };
3767
-
3768
- const OEmbedType = {
3769
- Photo: "photo",
3770
- Video: "video",
3771
- Link: "link",
3772
- Rich: "rich"
3773
- };
3774
-
3775
- const CustomTypeModelFieldType = {
3776
- Boolean: "Boolean",
3777
- Color: "Color",
3778
- Date: "Date",
3779
- Embed: "Embed",
3780
- GeoPoint: "GeoPoint",
3781
- Group: "Group",
3782
- Image: "Image",
3783
- Integration: "IntegrationFields",
3784
- Link: "Link",
3785
- Number: "Number",
3786
- Select: "Select",
3787
- Slices: "Slices",
3788
- StructuredText: "StructuredText",
3789
- Table: "Table",
3790
- Text: "Text",
3791
- Timestamp: "Timestamp",
3792
- UID: "UID",
3793
- /**
3794
- * @deprecated - Renamed to `Integration`.
3795
- */
3796
- IntegrationFields: "IntegrationFields",
3797
- /**
3798
- * @deprecated - Legacy field type. Use `Number` instead.
3799
- */
3800
- Range: "Range",
3801
- /**
3802
- * @deprecated - Legacy field type. Do not use.
3803
- */
3804
- Separator: "Separator",
3805
- /**
3806
- * @deprecated - Legacy field type. Use `Slices` instead.
3807
- */
3808
- LegacySlices: "Choice"
3809
- };
3810
-
3811
- const CustomTypeModelLinkSelectType = {
3812
- Document: "document",
3813
- Media: "media",
3814
- Web: "web"
3815
- };
3816
-
3817
- const CustomTypeModelSliceType = {
3818
- Slice: "Slice",
3819
- SharedSlice: "SharedSlice"
3820
- };
3821
-
3822
- const CustomTypeModelSliceDisplay = {
3823
- List: "list",
3824
- Grid: "grid"
3825
- };
3826
-
3827
- const WebhookType = {
3828
- APIUpdate: "api-update",
3829
- TestTrigger: "test-trigger"
3830
- };
3831
-
3832
- const predicate = filter;
3833
- const unstable_mapSliceZone = mapSliceZone;
3834
- const Element = RichTextNodeType;
3835
-
3836
- export { Client, CustomTypeModelFieldType, CustomTypeModelLinkSelectType, CustomTypeModelSliceDisplay, CustomTypeModelSliceType, Element, ForbiddenError, LinkType, Migration, NotFoundError, OEmbedType, ParsingError, PreviewTokenExpiredError, PrismicError, PrismicMigrationAsset, PrismicMigrationDocument, RefExpiredError, RefNotFoundError, RepositoryNotFoundError, RichTextNodeType, WebhookType, WriteClient, asDate, asHTML, asImagePixelDensitySrcSet, asImageSrc, asImageWidthSrcSet, asLink, asLinkAttrs, asText, buildQueryURL, cookie, createClient, createMigration, createWriteClient, documentToLinkField, filter, getGraphQLEndpoint, getRepositoryEndpoint, getRepositoryName, getToolbarSrc, isFilled, isRepositoryEndpoint, isRepositoryName, mapSliceZone, predicate, unstable_mapSliceZone };
3837
- //# sourceMappingURL=index.mjs.map