@prismicio/client 7.21.0-alpha.2 → 7.21.0

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