From ed5a90e32927a761ee6497984dcc816b508b8639 Mon Sep 17 00:00:00 2001 From: Lucie <25330882+lihbr@users.noreply.github.com> Date: Wed, 24 Jul 2024 12:01:38 +0200 Subject: [PATCH] style: update eslint config (#343) * style: update eslint config * style: run prettier * style: run prettier * style: run prettier --------- Co-authored-by: lihbr --- .eslintrc.cjs | 3 +- .prettierrc | 2 +- .size-limit.cjs | 16 +- CONTRIBUTING.md | 3 + README.md | 6 +- examples/custom-query-caching/index.js | 28 +- examples/custom-query-timeout/index.js | 42 +- examples/query-multiple-languages/index.js | 22 +- examples/query-using-refs/index.js | 30 +- examples/query-using-releases/index.js | 32 +- examples/server-usage/index.js | 10 +- examples/with-express/index.js | 46 +- examples/with-typescript/index.ts | 36 +- examples/with-typescript/types.ts | 34 +- messages/filters-must-be-an-array.md | 10 +- .../orderings-must-be-an-array-of-objects.md | 12 +- src/buildQueryURL.ts | 102 +-- src/cookie.ts | 2 +- src/createClient.ts | 586 +++++++------- src/errors/ForbiddenError.ts | 12 +- src/errors/NotFoundError.ts | 2 +- src/errors/ParsingError.ts | 16 +- src/errors/PreviewTokenExpired.ts | 8 +- src/errors/PrismicError.ts | 10 +- src/errors/PrismicRichTextSerializerError.ts | 2 +- src/errors/RefExpiredError.ts | 8 +- src/errors/RefNotFoundError.ts | 8 +- src/errors/RepositoryNotFoundError.ts | 2 +- src/filter.ts | 44 +- src/getGraphQLEndpoint.ts | 10 +- src/getRepositoryEndpoint.ts | 10 +- src/getRepositoryName.ts | 8 +- src/getToolbarSrc.ts | 10 +- src/helpers/asDate.ts | 14 +- src/helpers/asHTML.ts | 110 ++- src/helpers/asImagePixelDensitySrcSet.ts | 31 +- src/helpers/asImageSrc.ts | 17 +- src/helpers/asImageWidthSrcSet.ts | 41 +- src/helpers/asLink.ts | 53 +- src/helpers/asLinkAttrs.ts | 59 +- src/helpers/asText.ts | 30 +- src/helpers/documentToLinkField.ts | 12 +- src/helpers/isFilled.ts | 106 +-- src/helpers/mapSliceZone.ts | 68 +- src/helpers/unstable_htmlAsRichText.ts | 45 +- src/helpers/unstable_markdownAsRichText.ts | 27 +- src/index.ts | 238 +++--- src/isRepositoryEndpoint.ts | 8 +- src/isRepositoryName.ts | 4 +- src/lib/RichTextFieldBuilder.ts | 77 +- src/lib/appendFilters.ts | 8 +- src/lib/castArray.ts | 4 +- src/lib/castThunk.ts | 4 +- src/lib/devMsg.ts | 8 +- src/lib/escapeHTML.ts | 48 +- src/lib/everyTagFilter.ts | 8 +- src/lib/filterRichTextField.ts | 62 +- src/lib/findMasterRef.ts | 8 +- src/lib/findRef.ts | 12 +- src/lib/findRefByID.ts | 8 +- src/lib/findRefByLabel.ts | 8 +- src/lib/getPreviewCookie.ts | 22 +- src/lib/hastSerializerHelpers.ts | 78 +- src/lib/hastToRichText.ts | 144 ++-- src/lib/isInternalURL.ts | 8 +- src/lib/minifyGraphQLQuery.ts | 4 +- src/lib/rehypeRichText.ts | 83 +- src/lib/serializerHelpers.ts | 107 ++- src/lib/someTagsFilter.ts | 8 +- src/lib/typeFilter.ts | 6 +- src/richtext/asText.ts | 10 +- src/richtext/asTree.ts | 106 +-- src/richtext/composeSerializers.ts | 12 +- src/richtext/index.ts | 14 +- src/richtext/serialize.ts | 22 +- src/richtext/types.ts | 76 +- src/richtext/wrapMapSerializer.ts | 15 +- src/types/api/query.ts | 18 +- src/types/api/ref.ts | 10 +- src/types/api/release.ts | 4 +- src/types/api/repository.ts | 48 +- src/types/api/tags.ts | 2 +- src/types/model/boolean.ts | 14 +- src/types/model/color.ts | 10 +- src/types/model/contentRelationship.ts | 18 +- src/types/model/customType.ts | 18 +- src/types/model/date.ts | 12 +- src/types/model/embed.ts | 10 +- src/types/model/geoPoint.ts | 8 +- src/types/model/group.ts | 12 +- src/types/model/image.ts | 18 +- src/types/model/integration.ts | 12 +- src/types/model/keyText.ts | 10 +- src/types/model/link.ts | 16 +- src/types/model/linkToMedia.ts | 14 +- src/types/model/number.ts | 14 +- src/types/model/range.ts | 16 +- src/types/model/richText.ts | 32 +- src/types/model/select.ts | 14 +- src/types/model/separator.ts | 8 +- src/types/model/sharedSlice.ts | 14 +- src/types/model/sharedSliceVariation.ts | 18 +- src/types/model/slice.ts | 24 +- src/types/model/sliceZone.ts | 22 +- src/types/model/timestamp.ts | 12 +- src/types/model/title.ts | 4 +- src/types/model/types.ts | 52 +- src/types/model/uid.ts | 10 +- src/types/value/boolean.ts | 2 +- src/types/value/color.ts | 4 +- src/types/value/contentRelationship.ts | 30 +- src/types/value/date.ts | 4 +- src/types/value/document.ts | 46 +- src/types/value/embed.ts | 66 +- src/types/value/geoPoint.ts | 8 +- src/types/value/group.ts | 6 +- src/types/value/image.ts | 42 +- src/types/value/integration.ts | 4 +- src/types/value/keyText.ts | 4 +- src/types/value/link.ts | 24 +- src/types/value/linkToMedia.ts | 22 +- src/types/value/number.ts | 4 +- src/types/value/richText.ts | 116 +-- src/types/value/select.ts | 4 +- src/types/value/sharedSlice.ts | 10 +- src/types/value/sharedSliceVariation.ts | 10 +- src/types/value/slice.ts | 12 +- src/types/value/sliceZone.ts | 8 +- src/types/value/timestamp.ts | 6 +- src/types/value/title.ts | 8 +- src/types/value/types.ts | 44 +- src/types/webhook/apiUpdate.ts | 36 +- src/types/webhook/testTrigger.ts | 4 +- src/types/webhook/types.ts | 16 +- test/__fixtures__/document.ts | 6 +- .../htmlRichTextFunctionSerializer.ts | 47 +- .../__fixtures__/htmlRichTextMapSerializer.ts | 12 +- test/__fixtures__/linkResolver.ts | 5 +- .../partialHTMLRichTextFunctionSerializer.ts | 8 +- .../partialHTMLRichTextMapSerializer.ts | 4 +- test/__fixtures__/richText.ts | 8 +- test/__setup__.ts | 36 +- .../createAuthorizationHeader.ts | 2 +- test/__testutils__/createClient.ts | 24 +- .../createPagedQueryResponses.ts | 24 +- test/__testutils__/createRepositoryName.ts | 12 +- test/__testutils__/createRichTextFixtures.ts | 22 +- test/__testutils__/getMasterRef.ts | 10 +- test/__testutils__/mockPrismicRestAPIV2.ts | 58 +- test/__testutils__/testAbortableMethod.ts | 42 +- test/__testutils__/testAnyGetMethod.ts | 64 +- test/__testutils__/testAsRichTextHelper.ts | 51 +- test/__testutils__/testConcurrentMethod.ts | 90 +-- test/__testutils__/testFetchOptions.ts | 72 +- test/__testutils__/testFilter.ts | 8 +- test/__testutils__/testGetTTL.ts | 96 +-- test/buildQueryURL.test.ts | 116 +-- test/client-buildQueryURL.test.ts | 118 +-- test/client-dangerouslyGetAll.test.ts | 90 +-- test/client-get.test.ts | 54 +- test/client-getAllByEveryTag.test.ts | 18 +- test/client-getAllByIDs.test.ts | 18 +- test/client-getAllBySomeTags.test.ts | 18 +- test/client-getAllByTag.test.ts | 18 +- test/client-getAllByType.test.ts | 18 +- test/client-getAllByUIDs.test.ts | 18 +- test/client-getByEveryTag.test.ts | 18 +- test/client-getByID.test.ts | 18 +- test/client-getByIDs.test.ts | 18 +- test/client-getBySomeTags.test.ts | 18 +- test/client-getByTag.test.ts | 18 +- test/client-getByType.test.ts | 18 +- test/client-getByUID.test.ts | 18 +- test/client-getByUIDs.test.ts | 18 +- test/client-getFirst.test.ts | 44 +- test/client-getMasterRef.test.ts | 36 +- test/client-getRefByID.test.ts | 48 +- test/client-getRefByLabel.test.ts | 48 +- test/client-getRefs.test.ts | 30 +- test/client-getReleaseById.test.ts | 48 +- test/client-getReleaseByLabel.test.ts | 48 +- test/client-getReleases.test.ts | 30 +- test/client-getRepository.test.ts | 42 +- test/client-getSingle.test.ts | 18 +- test/client-getTags.test.ts | 78 +- test/client-graphQLFetch.test.ts | 178 ++--- test/client-queryContentFromRef.test.ts | 40 +- ...client-queryContentFromReleaseById.test.ts | 43 +- ...ent-queryContentFromReleaseByLabel.test.ts | 43 +- test/client-queryLatestContent.test.ts | 11 +- test/client-resolvePreviewUrl.test.ts | 194 ++--- test/client.test.ts | 726 +++++++++--------- test/errors-ForbiddenError.test.ts | 20 +- test/errors-ParsingError.test.ts | 20 +- test/errors-PrismicError.test.ts | 32 +- test/filter-any.test.ts | 10 +- test/filter-at.test.ts | 14 +- test/filter-date.test.ts | 112 +-- test/filter-fulltext.test.ts | 10 +- test/filter-geopoint.test.ts | 6 +- test/filter-has.test.ts | 6 +- test/filter-in.test.ts | 8 +- test/filter-missing.test.ts | 6 +- test/filter-not.test.ts | 14 +- test/filter-number.test.ts | 16 +- test/filter-similar.test.ts | 6 +- test/getGraphQLEndpoint.test.ts | 20 +- test/getRepositoryEndpoint.test.ts | 20 +- test/getRepositoryName.test.ts | 20 +- test/getToolbarSrc.test.ts | 20 +- test/helpers-asDate.test.ts | 42 +- test/helpers-asHTML.test.ts | 67 +- .../helpers-asImagePixelDensitySrcSet.test.ts | 35 +- test/helpers-asImageSrc.test.ts | 33 +- test/helpers-asImageWidthSrcSet.test.ts | 53 +- test/helpers-asLink.test.ts | 82 +- test/helpers-asLinkAttrs.test.ts | 122 +-- test/helpers-asText.test.ts | 24 +- test/helpers-documentToLinkField.test.ts | 36 +- test/helpers-isFilled.test.ts | 187 ++--- test/helpers-mapSliceZone.test.ts | 101 +-- test/helpers-unstable_htmlAsRichText.test.ts | 178 ++--- ...elpers-unstable_markdownAsRichText.test.ts | 14 +- test/index.test.ts | 44 +- test/isRepositoryEndpoint.test.ts | 16 +- test/isRepositoryName.test.ts | 14 +- test/lib-filterRichTextField.test.ts | 91 +-- test/richtext/asText.test.ts | 18 +- test/richtext/asTree.test.ts | 24 +- test/richtext/composeSerializers.test.ts | 52 +- test/richtext/index.test-d.ts | 8 +- test/richtext/serialize.test.ts | 54 +- test/richtext/wrapMapSerializer.test.ts | 28 +- test/types/api-form.types.ts | 20 +- test/types/api-formField.types.ts | 22 +- test/types/api-language.types.ts | 16 +- test/types/api-query.types.ts | 22 +- test/types/api-ref.types.ts | 18 +- test/types/api-release.types.ts | 7 +- test/types/api-repository.types.ts | 16 +- test/types/api-tags.types.ts | 22 +- test/types/client.types.ts | 284 ++++--- test/types/customType-boolean.types.ts | 24 +- test/types/customType-color.types.ts | 24 +- .../customType-contentRelationship.types.ts | 34 +- test/types/customType-date.types.ts | 24 +- test/types/customType-embed.types.ts | 24 +- test/types/customType-geoPoint.types.ts | 24 +- test/types/customType-group.types.ts | 34 +- test/types/customType-image.types.ts | 38 +- test/types/customType-integration.types.ts | 24 +- test/types/customType-keyText.types.ts | 28 +- test/types/customType-link.types.ts | 28 +- test/types/customType-linkToMedia.types.ts | 26 +- test/types/customType-number.types.ts | 24 +- test/types/customType-richText.types.ts | 33 +- test/types/customType-select.types.ts | 34 +- test/types/customType-sharedSlice.types.ts | 22 +- .../customType-sharedSliceModel.types.ts | 28 +- ...tomType-sharedSliceModelVariation.types.ts | 38 +- test/types/customType-slice.types.ts | 26 +- test/types/customType-sliceZone.types.ts | 28 +- test/types/customType-timestamp.types.ts | 24 +- test/types/customType-title.types.ts | 24 +- test/types/customType-uid.types.ts | 24 +- test/types/customType.types.ts | 109 +-- .../document-alternativeLanguage.types.ts | 26 +- test/types/document-prismicDocument.types.ts | 34 +- .../document-prismicDocumentWithUID.types.ts | 36 +- ...ocument-prismicDocumentWithoutUID.types.ts | 36 +- test/types/fields-boolean.types.ts | 12 +- test/types/fields-color.types.ts | 30 +- .../types/fields-contentRelationship.types.ts | 36 +- test/types/fields-date.types.ts | 28 +- test/types/fields-embed.types.ts | 40 +- test/types/fields-geoPoint.types.ts | 26 +- test/types/fields-group.types.ts | 32 +- test/types/fields-image.types.ts | 81 +- test/types/fields-integration.types.ts | 30 +- test/types/fields-keyText.types.ts | 26 +- test/types/fields-link.types.ts | 46 +- test/types/fields-linkToMedia.types.ts | 26 +- test/types/fields-number.types.ts | 26 +- test/types/fields-richText.types.ts | 52 +- test/types/fields-select.types.ts | 34 +- test/types/fields-sharedSlice.types.ts | 24 +- .../fields-sharedSliceVariation.types.ts | 26 +- test/types/fields-slice.types.ts | 42 +- test/types/fields-sliceZone.types.ts | 30 +- test/types/fields-timestamp.types.ts | 28 +- test/types/fields-title.types.ts | 68 +- test/types/fields.types.ts | 59 +- test/types/helpers-isFilled.types.ts | 347 ++++----- test/types/webhook-apiUpdate.types.ts | 22 +- test/types/webhook-testTrigger.types.ts | 18 +- test/types/webhook.types.ts | 9 +- vite.config.ts | 6 +- 297 files changed, 5613 insertions(+), 5654 deletions(-) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 30166b79..6f36a89a 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -33,6 +33,7 @@ module.exports = { ], "@typescript-eslint/no-var-requires": "off", "@typescript-eslint/explicit-module-boundary-types": "error", + "@typescript-eslint/consistent-type-imports": "error", "tsdoc/syntax": "warn", }, -}; +} diff --git a/.prettierrc b/.prettierrc index b3942496..d0aea147 100644 --- a/.prettierrc +++ b/.prettierrc @@ -28,7 +28,7 @@ "importOrderGroupNamespaceSpecifiers": true, "printWidth": 80, "useTabs": true, - "semi": true, + "semi": false, "singleQuote": false, "quoteProps": "as-needed", "jsxSingleQuote": false, diff --git a/.size-limit.cjs b/.size-limit.cjs index d6567c8a..2460266d 100644 --- a/.size-limit.cjs +++ b/.size-limit.cjs @@ -1,13 +1,13 @@ -const pkg = require("./package.json"); +const pkg = require("./package.json") function getObjectValues(input, acc = []) { if (typeof input === "string") { - return input; + return input } else { return [ ...acc, ...Object.values(input).flatMap((value) => getObjectValues(value)), - ]; + ] } } @@ -16,15 +16,15 @@ module.exports = [ ] .sort() .filter((path) => { - return path && path !== "./package.json" && !path.endsWith(".d.ts"); + return path && path !== "./package.json" && !path.endsWith(".d.ts") }) .map((path) => { return { path, modifyEsbuildConfig(config) { - config.platform = "node"; + config.platform = "node" - return config; + return config }, - }; - }); + } + }) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7863739b..8f044447 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -132,6 +132,9 @@ npm run release:alpha ``` [^1]: This package is maintained by the DevX team. Prismic employees can ask for help or a review in the [#team-devx](https://prismic-team.slack.com/archives/C014VAACCQL) Slack channel. + [^2]: Prismic employees are highly encouraged to discuss changes with the DevX team in the [#team-devx](https://prismic-team.slack.com/archives/C014VAACCQL) Slack channel before starting. + [^3]: Code should be reviewed by the DevX team before merging. Prismic employees can request a review in the [#team-devx](https://prismic-team.slack.com/archives/CPG31MDL1) Slack channel. + [^4]: Prismic employees can ask the DevX team for [npm](https://www.npmjs.com) publish access. diff --git a/README.md b/README.md index 772c4842..b901da14 100644 --- a/README.md +++ b/README.md @@ -15,13 +15,13 @@ The official JavaScript + TypeScript client library for [Prismic][prismic]. - Built for browser and server usage. ```typescript -import * as prismic from "@prismicio/client"; +import * as prismic from "@prismicio/client" // Create a client -const client = prismic.createClient("my-repository"); +const client = prismic.createClient("my-repository") // Then query for your content -const blogPosts = await client.getAllByType("blog_post"); +const blogPosts = await client.getAllByType("blog_post") ``` ## Install diff --git a/examples/custom-query-caching/index.js b/examples/custom-query-caching/index.js index f34e6e8e..ffe0b5cc 100644 --- a/examples/custom-query-caching/index.js +++ b/examples/custom-query-caching/index.js @@ -1,37 +1,37 @@ -import * as prismic from "@prismicio/client"; -import fetch from "node-fetch"; -import QuickLRU from "quick-lru"; +import * as prismic from "@prismicio/client" +import fetch from "node-fetch" +import QuickLRU from "quick-lru" const cache = new QuickLRU({ maxSize: 1000, // 1000 entries -}); +}) const client = prismic.createClient("qwerty", { fetch: async (url, options) => { // The cache key contains the requested URL and headers - const key = JSON.stringify({ url, options }); + const key = JSON.stringify({ url, options }) if (cache.has(key)) { // If the cache contains a value for the key, return it - return cache.get(key).clone(); + return cache.get(key).clone() } else { // Otherwise, make the network request - const res = await fetch(url, options); + const res = await fetch(url, options) if (res.ok) { // If the request was successful, save it to the cache - cache.set(key, res.clone()); + cache.set(key, res.clone()) } - return res; + return res } }, -}); +}) -const homepage = await client.getByUID("page", "home"); -console.info("First uncached result: ", homepage); +const homepage = await client.getByUID("page", "home") +console.info("First uncached result: ", homepage) // => The `page` document with a UID of `home` -const homepageFetchedAgain = await client.getByUID("page", "home"); -console.info("Second cached result: ", homepageFetchedAgain); +const homepageFetchedAgain = await client.getByUID("page", "home") +console.info("Second cached result: ", homepageFetchedAgain) // => This call will use the cache rather than make another network request. diff --git a/examples/custom-query-timeout/index.js b/examples/custom-query-timeout/index.js index cf792d09..147e6f81 100644 --- a/examples/custom-query-timeout/index.js +++ b/examples/custom-query-timeout/index.js @@ -1,8 +1,8 @@ -import * as prismic from "@prismicio/client"; +import * as prismic from "@prismicio/client" // AbortController was added in node v14.17.0 globally. If you are using a node // version >=14.17.0, or are not in a node environment, remove this line. -import { AbortController } from "abort-controller"; -import fetch, { AbortError } from "node-fetch"; +import { AbortController } from "abort-controller" +import fetch, { AbortError } from "node-fetch" // A global timeout can be implemented like the following. This timeout will // apply to all network requests made by the client. @@ -11,12 +11,12 @@ const client = prismic.createClient("qwerty", { // Create an AbortController. This will be used to cancel the // `fetch()` request if it does not resolve within the given // timespan. - const controller = new AbortController(); + const controller = new AbortController() // After 1ms, cancel the `fetch()` request. // 1ms is used to force a timeout. In a real-world scenario, // something like 3000ms is more appropriate. - const timeoutId = setTimeout(() => controller.abort(), 1); + const timeoutId = setTimeout(() => controller.abort(), 1) // Fetch the requested URL with the AbortController. If // `controller.abort()` is called, the `fetch()` request will @@ -24,46 +24,46 @@ const client = prismic.createClient("qwerty", { const res = await fetch(url, { signal: controller.signal, ...options, - }); + }) // We must stop the timeout once the `fetch()` request is // complete. - clearTimeout(timeoutId); + clearTimeout(timeoutId) - return res; + return res }, -}); +}) // This query will throw if it does not resolve within the timeout duration. -const articles = await client.getAllByType("article"); -console.info(articles); +const articles = await client.getAllByType("article") +console.info(articles) // => A list of all `article` documents // If you want to handle timeouts, you can check the error's type. try { - const articles = await client.getAllByType("article"); - console.info(articles); + const articles = await client.getAllByType("article") + console.info(articles) } catch (error) { if (error instanceof AbortError) { - console.error("The request timed out."); + console.error("The request timed out.") } else { - throw error; + throw error } } // You can also set timeouts for individual client methods by passing an // AbortController signal to the method. try { - const controller = new AbortController(); - setTimeout(() => controller.abort(), 1); + const controller = new AbortController() + setTimeout(() => controller.abort(), 1) const articles = await client.getAllByType("article", { signal: controller.signal, - }); - console.info(articles); + }) + console.info(articles) } catch (error) { if (error instanceof AbortError) { - console.error("The request timed out."); + console.error("The request timed out.") } else { - throw error; + throw error } } diff --git a/examples/query-multiple-languages/index.js b/examples/query-multiple-languages/index.js index 8e684a49..6fc33e4d 100644 --- a/examples/query-multiple-languages/index.js +++ b/examples/query-multiple-languages/index.js @@ -1,5 +1,5 @@ -import * as prismic from "@prismicio/client"; -import fetch from "node-fetch"; +import * as prismic from "@prismicio/client" +import fetch from "node-fetch" const client = prismic.createClient("qwerty", { fetch, @@ -8,22 +8,22 @@ const client = prismic.createClient("qwerty", { defaultParams: { lang: "en-us", }, -}); +}) // This will fetch Article documents with the `en-us` lang. -const articlesDefaultLanguage = await client.getAllByType("article"); -console.info("articlesDefaultLanguage: ", articlesDefaultLanguage); +const articlesDefaultLanguage = await client.getAllByType("article") +console.info("articlesDefaultLanguage: ", articlesDefaultLanguage) // This will also fetch Article documents with the `en-us` lang. -const articlesEnglish = await client.getAllByType("article", { lang: "en-us" }); -console.info("articlesEnglish: ", articlesEnglish); +const articlesEnglish = await client.getAllByType("article", { lang: "en-us" }) +console.info("articlesEnglish: ", articlesEnglish) // This will fetch Article documents with the `fr-fr` lang. -const articlesFrench = await client.getAllByType("article", { lang: "fr-fr" }); -console.info("articlesFrench: ", articlesFrench); +const articlesFrench = await client.getAllByType("article", { lang: "fr-fr" }) +console.info("articlesFrench: ", articlesFrench) // This will fetch Article documents with any language. const articlesAllLanguages = await client.getAllByType("article", { lang: "*", -}); -console.info("articlesAllLanguages: ", articlesAllLanguages); +}) +console.info("articlesAllLanguages: ", articlesAllLanguages) diff --git a/examples/query-using-refs/index.js b/examples/query-using-refs/index.js index f277a951..a0156a34 100644 --- a/examples/query-using-refs/index.js +++ b/examples/query-using-refs/index.js @@ -1,37 +1,37 @@ -import * as prismic from "@prismicio/client"; -import fetch from "node-fetch"; +import * as prismic from "@prismicio/client" +import fetch from "node-fetch" const client = prismic.createClient("qwerty", { fetch, -}); +}) // By default, the client will fetch the latest published content from the repository. // This means content is fetched from the "master ref". -const homepage = await client.getByUID("page", "home"); -console.info(homepage); +const homepage = await client.getByUID("page", "home") +console.info(homepage) // We can get a list of all refs in a repository. -const refs = await client.getRefs(); -console.info(refs); +const refs = await client.getRefs() +console.info(refs) // Or we can get a specific ref by its label. // If we have an ID instead, `client.getRefByID` can be used. -const ref = await client.getRefByLabel("My Specific Ref"); +const ref = await client.getRefByLabel("My Specific Ref") // If we want to query content from a specific ref, we can tell the client to // make all future queries use that ref. -client.queryContentFromRef(ref.ref); +client.queryContentFromRef(ref.ref) // Now queries will fetch content from the "My Specific Ref" ref. -const aboutPage = await client.getByUID("page", "about"); -console.info(aboutPage); +const aboutPage = await client.getByUID("page", "about") +console.info(aboutPage) // We can also override the ref on a per-query basis. -const otherRef = await client.getRefByLabel("My Other Ref"); +const otherRef = await client.getRefByLabel("My Other Ref") const contactPage = await client.getByUID("page", "contact", { ref: otherRef.ref, -}); -console.info(contactPage); +}) +console.info(contactPage) // We can change back to fetching the latest content with the following function. -client.queryLatestContent(); +client.queryLatestContent() diff --git a/examples/query-using-releases/index.js b/examples/query-using-releases/index.js index f01fb57e..b6d83b43 100644 --- a/examples/query-using-releases/index.js +++ b/examples/query-using-releases/index.js @@ -1,38 +1,38 @@ -import * as prismic from "@prismicio/client"; -import fetch from "node-fetch"; +import * as prismic from "@prismicio/client" +import fetch from "node-fetch" const client = prismic.createClient("qwerty", { fetch, -}); +}) // By default, the client will fetch the latest published content from the repository. // This means content is fetched from the "master ref". -const homepage = await client.getByUID("page", "home"); -console.info(homepage); +const homepage = await client.getByUID("page", "home") +console.info(homepage) // We can get a list of all releases in a repository. -const releases = await client.getReleases(); -console.info(releases); +const releases = await client.getReleases() +console.info(releases) // Or we can get a specific release by its label. // If we have an ID instead, `client.getReleaseByID` can be used. -const release = await client.getReleaseByLabel("My Specific Release"); -console.info(release); +const release = await client.getReleaseByLabel("My Specific Release") +console.info(release) // We can tell the client to make all queries point to a released called "My Release". // We could also use `client.queryContentFromReleaseByID` if we have an ID instead. -client.queryContentFromReleaseByLabel("My Release"); +client.queryContentFromReleaseByLabel("My Release") // Now queries will fetch content from "My Release". -const aboutPage = await client.getByUID("page", "about"); -console.info(aboutPage); +const aboutPage = await client.getByUID("page", "about") +console.info(aboutPage) // We can also override the release on a per-query basis. -const otherRelease = await client.getReleaseByLabel("My Other Release"); +const otherRelease = await client.getReleaseByLabel("My Other Release") const contactPage = await client.getByUID("page", "contact", { ref: otherRelease.ref, -}); -console.info(contactPage); +}) +console.info(contactPage) // We can change back to fetching the latest content with the following function. -client.queryLatestContent(); +client.queryLatestContent() diff --git a/examples/server-usage/index.js b/examples/server-usage/index.js index 748a2b5d..9d35d2c6 100644 --- a/examples/server-usage/index.js +++ b/examples/server-usage/index.js @@ -1,12 +1,12 @@ -import * as prismic from "@prismicio/client"; -import fetch from "node-fetch"; +import * as prismic from "@prismicio/client" +import fetch from "node-fetch" const client = prismic.createClient("qwerty", { // Here, we provide a way for the client to make network requests. // `node-fetch` is a Node.js fetch-compatible package. fetch, -}); +}) -const homepage = await client.getByUID("page", "home"); -console.info(homepage); +const homepage = await client.getByUID("page", "home") +console.info(homepage) // => The `page` document with a UID of `home` diff --git a/examples/with-express/index.js b/examples/with-express/index.js index dcb10e60..a5f29369 100644 --- a/examples/with-express/index.js +++ b/examples/with-express/index.js @@ -1,11 +1,11 @@ -import * as prismic from "@prismicio/client"; -import express from "express"; -import fetch from "node-fetch"; -import QuickLRU from "quick-lru"; +import * as prismic from "@prismicio/client" +import express from "express" +import fetch from "node-fetch" +import QuickLRU from "quick-lru" const cache = new QuickLRU({ maxSize: 1000, // 1000 entries -}); +}) /** * This function returns a Prismic client for the repository. A new client @@ -18,52 +18,52 @@ const createClient = ({ req } = {}) => { const client = prismic.createClient("qwerty", { fetch: async (url, options) => { // The cache key contains the requested URL and headers - const key = JSON.stringify({ url, options }); + const key = JSON.stringify({ url, options }) if (cache.has(key)) { // If the cache contains a value for the key, return it - return cache.get(key).clone(); + return cache.get(key).clone() } else { // Otherwise, make the network request - const res = await fetch(url, options); + const res = await fetch(url, options) if (res.ok) { // If the request was successful, save it to the cache - cache.set(key, res.clone()); + cache.set(key, res.clone()) } - return res; + return res } }, - }); + }) if (req) { - client.enableAutoPreviewsFromReq(req); + client.enableAutoPreviewsFromReq(req) } - return client; -}; + return client +} -const app = express(); +const app = express() /** * This route will fetch all Article documents from the Prismic repository and * return a list of objects with formatted content. */ app.get("/articles", async (req, res) => { - const client = createClient({ req }); - const articles = await client.getAllByType("article"); + const client = createClient({ req }) + const articles = await client.getAllByType("article") const payload = articles.map((article) => ({ title: prismic.asText(article.data.title), description: prismic.asText(article.data.shortlede), content: prismic.asHTML(article.data.content), - })); + })) - res.json(payload); -}); + res.json(payload) +}) -app.listen(3000); +app.listen(3000) -console.info(`Open http://localhost:3000/articles to see the response`); -console.info("Press CTRL+C to stop the server"); +console.info(`Open http://localhost:3000/articles to see the response`) +console.info("Press CTRL+C to stop the server") diff --git a/examples/with-typescript/index.ts b/examples/with-typescript/index.ts index 8ecce3bf..dbb0b4ff 100644 --- a/examples/with-typescript/index.ts +++ b/examples/with-typescript/index.ts @@ -1,43 +1,43 @@ -import * as prismic from "@prismicio/client"; -import fetch from "node-fetch"; +import * as prismic from "@prismicio/client" +import fetch from "node-fetch" // See `./types.ts` for the document types. -import { AllDocumentTypes } from "./types"; +import type { AllDocumentTypes } from "./types" const main = async () => { // You can pass a union of document types to `createClient()`. // All query methods will now be typed appropriately. Methods that // accept a document type, for example, will return the correct type // for that document type. - const client = prismic.createClient("qwerty", { fetch }); + const client = prismic.createClient("qwerty", { fetch }) - const homepage = await client.getByUID("page", "home"); + const homepage = await client.getByUID("page", "home") // ^ Typed as PageDocument - const type = homepage.type; + const type = homepage.type // ^ Typed as "page" - console.info("title: ", type); + console.info("title: ", type) - const lang = homepage.lang; + const lang = homepage.lang // ^ Typed as `"en-us" | "fr-fr"` - console.info("lang: ", lang); + console.info("lang: ", lang) - const title = homepage.data.title; + const title = homepage.data.title // ^ Typed as `string | null` - console.info("title: ", title); + console.info("title: ", title) // @ts-expect-error - non_existent_field does not exist in `data` - const nonExistentField = homepage.data.non_existent_field; + const nonExistentField = homepage.data.non_existent_field // TypeScript Error: Property 'non_existent_field' does not exist on type 'PageDocument['data']'. - console.info("nonExistentField: ", nonExistentField); + console.info("nonExistentField: ", nonExistentField) - const blogPosts = await client.getAllByType("blog_post"); + const blogPosts = await client.getAllByType("blog_post") // ^ Typed as BlogPostDocument[] - console.info("blogPosts: ", blogPosts); + console.info("blogPosts: ", blogPosts) // @ts-expect-error - "settings" is a not a valid document type. - await client.getAllByType("settings"); + await client.getAllByType("settings") // TypeScript Error: Argument of type '"settings"' is not assignable to parameter of type '"page" | "blog_post"'. -}; +} -main(); +main() diff --git a/examples/with-typescript/types.ts b/examples/with-typescript/types.ts index f7c90d7f..67fbbeb4 100644 --- a/examples/with-typescript/types.ts +++ b/examples/with-typescript/types.ts @@ -1,57 +1,57 @@ -import * as prismic from "@prismicio/client"; +import type * as prismic from "@prismicio/client" /** * A union of all possible Prismic Document types. */ -export type AllDocumentTypes = PageDocument | BlogPostDocument; +export type AllDocumentTypes = PageDocument | BlogPostDocument /** * A Page document from Prismic. */ export type PageDocument = prismic.PrismicDocument< { - title: prismic.KeyTextField; - footnotes: prismic.RichTextField; + title: prismic.KeyTextField + footnotes: prismic.RichTextField }, "page", "en-us" | "fr-fr" ->; +> /** * A Blog Post document from Prismic. This example contains Slices. */ export type BlogPostDocument = prismic.PrismicDocument< { - title: prismic.KeyTextField; - description: prismic.RichTextField; + title: prismic.KeyTextField + description: prismic.RichTextField body: prismic.SliceZone< | PrismicSliceBlogPostBodyText | PrismicSliceBlogPostBodyImageGallery | PrismicSliceBlogPostBodyQuote - >; + > }, "blog_post", "en-us" | "fr-fr" ->; +> type PrismicSliceBlogPostBodyText = prismic.Slice< "text", never, { - text: prismic.RichTextField; + text: prismic.RichTextField } ->; +> type PrismicSliceBlogPostBodyImageGallery = prismic.Slice< "image_gallery", never, { - image: prismic.ImageField; - caption: prismic.KeyTextField; + image: prismic.ImageField + caption: prismic.KeyTextField } ->; +> type PrismicSliceBlogPostBodyQuote = prismic.Slice< "quote", { - quote: prismic.RichTextField; - quotee: prismic.KeyTextField; + quote: prismic.RichTextField + quotee: prismic.KeyTextField } ->; +> diff --git a/messages/filters-must-be-an-array.md b/messages/filters-must-be-an-array.md index 7339149f..a03a2710 100644 --- a/messages/filters-must-be-an-array.md +++ b/messages/filters-must-be-an-array.md @@ -5,9 +5,9 @@ Prismic queries can be filtered using the `filters` query parameter. The `filters` parameter accepts an array of filters like the following: ```typescript -import * as prismic from "@prismicio/client"; +import * as prismic from "@prismicio/client" -const client = prismic.createClient("my-repo-name"); +const client = prismic.createClient("my-repo-name") const blogPosts = await client.getAllByType("blog_post", { filters: [ @@ -17,7 +17,7 @@ const blogPosts = await client.getAllByType("blog_post", { new Date("1991-03-07"), ), ], -}); +}) ``` This query will fetch all `blog_post` documents _except_ those that: @@ -41,10 +41,10 @@ await client.getAllByType("blog_post", { new Date("1991-03-07"), ), ], -}); +}) // ❌ Incorrect await client.getAllByType("blog_post", { filters: prismic.filter.not("my.document.uid", "hidden"), -}); +}) ``` diff --git a/messages/orderings-must-be-an-array-of-objects.md b/messages/orderings-must-be-an-array-of-objects.md index eefd878b..481e0afe 100644 --- a/messages/orderings-must-be-an-array-of-objects.md +++ b/messages/orderings-must-be-an-array-of-objects.md @@ -5,9 +5,9 @@ Prismic's Rest API accepts an `orderings` parameter to determine the sort order The `orderings` parameter can be provided to `@prismicio/client` queries like the following: ```typescript -import * as prismic from "@prismicio/client"; +import * as prismic from "@prismicio/client" -const client = prismic.createClient("my-repo-name"); +const client = prismic.createClient("my-repo-name") const blogPosts = await client.getAllByType("blog_post", { orderings: [ @@ -15,7 +15,7 @@ const blogPosts = await client.getAllByType("blog_post", { { field: "blog_post.first_publication_date", direction: "desc" }, { field: "my.blog_post.title" }, ], -}); +}) ``` This query will fetch all `blog_post` documents sorted in the following order: @@ -38,7 +38,7 @@ await client.getAllByType("blog_post", { { field: "blog_post.first_publication_date", direction: "desc" }, { field: "my.blog_post.title" }, ], -}); +}) // ❌ Incorrect await client.getAllByType("blog_post", { @@ -47,11 +47,11 @@ await client.getAllByType("blog_post", { "blog_post.first_publication_date desc", "my.blog_post.title", ], -}); +}) // ❌ Incorrect await client.getAllByType("blog_post", { orderings: "my.blog_post.published_at desc,blog_post.first_publication_date desc,my.blog_post.title", -}); +}) ``` diff --git a/src/buildQueryURL.ts b/src/buildQueryURL.ts index 4958666d..fe862ef9 100644 --- a/src/buildQueryURL.ts +++ b/src/buildQueryURL.ts @@ -1,5 +1,5 @@ -import { castArray } from "./lib/castArray"; -import { devMsg } from "./lib/devMsg"; +import { castArray } from "./lib/castArray" +import { devMsg } from "./lib/devMsg" /** * Create a union of the given object's values, and optionally specify which @@ -13,7 +13,7 @@ import { devMsg } from "./lib/devMsg"; type ValueOf< ObjectType, ValueType extends keyof ObjectType = keyof ObjectType, -> = ObjectType[ValueType]; +> = ObjectType[ValueType] /** * An `orderings` parameter that orders the results by the specified field. @@ -21,8 +21,8 @@ type ValueOf< * {@link https://prismic.io/docs/rest-api-technical-reference#orderings} */ export interface Ordering { - field: string; - direction?: "asc" | "desc"; + field: string + direction?: "asc" | "desc" } /** @@ -55,29 +55,29 @@ export interface Route { /** * The custom type of the document. */ - type: string; + type: string /** * A specific UID to which this route definition is scoped. The route is only * defined for the document whose UID matches the given UID. */ - uid?: string; + uid?: string /** * A specific language to which this route definition is scoped. The route is * only defined for documents whose language matches the given language. */ - lang?: string; + lang?: string /** * The resolved path of the document with optional placeholders. */ - path: string; + path: string /** * An object that lists the API IDs of the Content Relationships in the route. */ - resolvers?: Record; + resolvers?: Record } /** @@ -92,7 +92,7 @@ export interface QueryParams { * * {@link https://prismic.io/docs/access-token} */ - accessToken?: string; + accessToken?: string /** * The `pageSize` parameter defines the maximum number of documents that the @@ -100,14 +100,14 @@ export interface QueryParams { * * {@link https://prismic.io/docs/rest-api-technical-reference#pagesize} */ - pageSize?: number; + pageSize?: number /** * The `page` parameter defines the pagination for the result of your query. * * {@link https://prismic.io/docs/rest-api-technical-reference#page} */ - page?: number; + page?: number /** * The `after` parameter can be used along with the orderings option. It will @@ -116,7 +116,7 @@ export interface QueryParams { * * {@link https://prismic.io/docs/rest-api-technical-reference#after} */ - after?: string; + after?: string /** * The `fetch` parameter is used to make queries faster by only retrieving the @@ -124,7 +124,7 @@ export interface QueryParams { * * {@link https://prismic.io/docs/rest-api-technical-reference#fetch} */ - fetch?: string | string[]; + fetch?: string | string[] /** * The `fetchLinks` parameter allows you to retrieve a specific content field @@ -132,7 +132,7 @@ export interface QueryParams { * * {@link https://prismic.io/docs/rest-api-technical-reference#fetchlinks} */ - fetchLinks?: string | string[]; + fetchLinks?: string | string[] /** * The `graphQuery` parameter allows you to specify which fields to retrieve @@ -141,14 +141,14 @@ export interface QueryParams { * * {@link https://prismic.io/docs/graphquery-rest-api} */ - graphQuery?: string; + graphQuery?: string /** * The `lang` option defines the language code for the results of your query. * * {@link https://prismic.io/docs/rest-api-technical-reference#lang} */ - lang?: string; + lang?: string /** * The `orderings` parameter orders the results by the specified field(s). You @@ -169,11 +169,11 @@ export interface QueryParams { * { field: "my.product.price", direction: "desc" }, * { field: "my.product.title" }, * ], - * }); + * }) * ``` */ // TODO: Update TSDoc with deprecated API removal in v8 - orderings?: string | Ordering | (string | Ordering)[]; + orderings?: string | Ordering | (string | Ordering)[] /** * The `routes` option allows you to define how a document's `url` field is @@ -181,7 +181,7 @@ export interface QueryParams { * * {@link https://prismic.io/docs/route-resolver} */ - routes?: Route | string | (Route | string)[]; + routes?: Route | string | (Route | string)[] /** * The `brokenRoute` option allows you to define the route populated in the @@ -191,7 +191,7 @@ export interface QueryParams { * * {@link https://prismic.io/docs/route-resolver} */ - brokenRoute?: string; + brokenRoute?: string } /** @@ -203,28 +203,28 @@ type BuildQueryURLParams = { * * {@link https://prismic.io/docs/api#refs-and-the-entry-api} */ - ref: string; + ref: string /** * Ref used to populate integration fields with the latest content. * * {@link https://prismic.io/docs/integration-fields} */ - integrationFieldsRef?: string; + integrationFieldsRef?: string /** * One or more filters to filter documents for the query. * * {@link https://prismic.io/docs/rest-api-technical-reference#q} */ - filters?: string | string[]; + filters?: string | string[] /** * @deprecated Renamed to `filters`. Ensure the value is an array of filters, * not a single, non-array filter. */ - predicates?: string | string[]; -}; + predicates?: string | string[] +} /** * Parameters in this map have been renamed from the official Prismic REST API @@ -234,7 +234,7 @@ type BuildQueryURLParams = { */ const RENAMED_PARAMS = { accessToken: "access_token", -} as const; +} as const /** * A valid parameter name for the Prismic REST API V2. @@ -244,7 +244,7 @@ type ValidParamName = keyof QueryParams, keyof typeof RENAMED_PARAMS | keyof BuildQueryURLParams > - | ValueOf; + | ValueOf /** * Converts an Ordering to a string that is compatible with Prismic's REST API. @@ -258,29 +258,29 @@ const castOrderingToString = (ordering: Ordering | string): string => { // TODO: Remove the following when `orderings` strings are no longer supported. if (typeof ordering === "string") { if (process.env.NODE_ENV === "development") { - const [field, direction] = ordering.split(" "); + const [field, direction] = ordering.split(" ") const objectForm = direction === "desc" ? `{ field: "${field}", direction: "desc" }` - : `{ field: "${field}" }`; + : `{ field: "${field}" }` console.warn( `[@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( "orderings-must-be-an-array-of-objects", )}`, - ); + ) } - return ordering; + return ordering } return ordering.direction === "desc" ? `${ordering.field} desc` - : ordering.field; -}; + : ordering.field +} -export type BuildQueryURLArgs = QueryParams & BuildQueryURLParams; +export type BuildQueryURLArgs = QueryParams & BuildQueryURLParams /** * Build a Prismic REST API V2 URL to request documents from a repository. The @@ -303,9 +303,9 @@ export const buildQueryURL = ( endpoint: string, args: BuildQueryURLArgs, ): string => { - const { filters, predicates, ...params } = args; + const { filters, predicates, ...params } = args - const url = new URL(`documents/search`, `${endpoint}/`); + const url = new URL(`documents/search`, `${endpoint}/`) if (filters) { // TODO: Remove warning when we remove support for string `filters` values. @@ -314,19 +314,19 @@ export const buildQueryURL = ( `[@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( "filters-must-be-an-array", )}`, - ); + ) } // TODO: Remove `castArray` when we remove support for string `filters` values. for (const filter of castArray(filters)) { - url.searchParams.append("q", `[${filter}]`); + url.searchParams.append("q", `[${filter}]`) } } // TODO: Remove when we remove support for deprecated `predicates` argument. if (predicates) { for (const predicate of castArray(predicates)) { - url.searchParams.append("q", `[${predicate}]`); + url.searchParams.append("q", `[${predicate}]`) } } @@ -334,12 +334,12 @@ export const buildQueryURL = ( // parameter value needs to be transformed to fit the REST API. for (const k in params) { const name = (RENAMED_PARAMS[k as keyof typeof RENAMED_PARAMS] || - k) as ValidParamName; + k) as ValidParamName - let value = params[k as keyof typeof params]; + let value = params[k as keyof typeof params] if (name === "orderings") { - const scopedValue = params[name]; + const scopedValue = params[name] if (scopedValue != null) { // TODO: Remove the following warning when `orderings` strings are no longer supported. @@ -351,18 +351,18 @@ export const buildQueryURL = ( `[@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( "orderings-must-be-an-array-of-objects", )}`, - ); + ) } const v = castArray(scopedValue) .map((ordering) => castOrderingToString(ordering)) - .join(","); + .join(",") - value = `[${v}]`; + value = `[${v}]` } } else if (name === "routes") { if (typeof params[name] === "object") { - value = JSON.stringify(castArray(params[name])); + value = JSON.stringify(castArray(params[name])) } } @@ -370,9 +370,9 @@ export const buildQueryURL = ( url.searchParams.set( name, castArray(value).join(","), - ); + ) } } - return url.toString(); -}; + return url.toString() +} diff --git a/src/cookie.ts b/src/cookie.ts index c3cec617..31e086c1 100644 --- a/src/cookie.ts +++ b/src/cookie.ts @@ -2,4 +2,4 @@ * The well-known name of the cookie used to store a Prismic preview session's * ref. */ -export const preview = "io.prismic.preview"; +export const preview = "io.prismic.preview" diff --git a/src/createClient.ts b/src/createClient.ts index bd814f15..070e134e 100644 --- a/src/createClient.ts +++ b/src/createClient.ts @@ -1,42 +1,44 @@ -import { appendFilters } from "./lib/appendFilters"; -import { castThunk } from "./lib/castThunk"; -import { devMsg } from "./lib/devMsg"; -import { everyTagFilter } from "./lib/everyTagFilter"; -import { findMasterRef } from "./lib/findMasterRef"; -import { findRefByID } from "./lib/findRefByID"; -import { findRefByLabel } from "./lib/findRefByLabel"; -import { getPreviewCookie } from "./lib/getPreviewCookie"; -import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery"; -import { someTagsFilter } from "./lib/someTagsFilter"; -import { typeFilter } from "./lib/typeFilter"; - -import type { Query } from "./types/api/query"; -import type { Ref } from "./types/api/ref"; -import type { Form, Repository } from "./types/api/repository"; -import type { PrismicDocument } from "./types/value/document"; - -import { ForbiddenError } from "./errors/ForbiddenError"; -import { NotFoundError } from "./errors/NotFoundError"; -import { ParsingError } from "./errors/ParsingError"; -import { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired"; -import { PrismicError } from "./errors/PrismicError"; -import { RefExpiredError } from "./errors/RefExpiredError"; -import { RefNotFoundError } from "./errors/RefNotFoundError"; -import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError"; - -import { LinkResolverFunction, asLink } from "./helpers/asLink"; - -import { BuildQueryURLArgs, buildQueryURL } from "./buildQueryURL"; -import { filter } from "./filter"; -import { getRepositoryEndpoint } from "./getRepositoryEndpoint"; -import { getRepositoryName } from "./getRepositoryName"; -import { isRepositoryEndpoint } from "./isRepositoryEndpoint"; +import { appendFilters } from "./lib/appendFilters" +import { castThunk } from "./lib/castThunk" +import { devMsg } from "./lib/devMsg" +import { everyTagFilter } from "./lib/everyTagFilter" +import { findMasterRef } from "./lib/findMasterRef" +import { findRefByID } from "./lib/findRefByID" +import { findRefByLabel } from "./lib/findRefByLabel" +import { getPreviewCookie } from "./lib/getPreviewCookie" +import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery" +import { someTagsFilter } from "./lib/someTagsFilter" +import { typeFilter } from "./lib/typeFilter" + +import type { Query } from "./types/api/query" +import type { Ref } from "./types/api/ref" +import type { Form, Repository } from "./types/api/repository" +import type { PrismicDocument } from "./types/value/document" + +import { ForbiddenError } from "./errors/ForbiddenError" +import { NotFoundError } from "./errors/NotFoundError" +import { ParsingError } from "./errors/ParsingError" +import { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired" +import { PrismicError } from "./errors/PrismicError" +import { RefExpiredError } from "./errors/RefExpiredError" +import { RefNotFoundError } from "./errors/RefNotFoundError" +import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError" + +import type { LinkResolverFunction } from "./helpers/asLink" +import { asLink } from "./helpers/asLink" + +import type { BuildQueryURLArgs } from "./buildQueryURL" +import { buildQueryURL } from "./buildQueryURL" +import { filter } from "./filter" +import { getRepositoryEndpoint } from "./getRepositoryEndpoint" +import { getRepositoryName } from "./getRepositoryName" +import { isRepositoryEndpoint } from "./isRepositoryEndpoint" /** * The largest page size allowed by the Prismic REST API V2. This value is used * to minimize the number of requests required to query content. */ -const MAX_PAGE_SIZE = 100; +const MAX_PAGE_SIZE = 100 /** * The number of milliseconds in which repository metadata is considered valid. @@ -44,7 +46,7 @@ const MAX_PAGE_SIZE = 100; * updated in the Prismic repository. As such, repository's metadata can only be * considered valid for a short amount of time. */ -export const REPOSITORY_CACHE_TTL = 5000; +export const REPOSITORY_CACHE_TTL = 5000 /** * The number of milliseconds in which a multi-page `getAll` (e.g. `getAll`, @@ -53,7 +55,7 @@ export const REPOSITORY_CACHE_TTL = 5000; * This is done to ensure API performance is sustainable and reduces the chance * of a failed API request due to overloading. */ -export const GET_ALL_QUERY_DELAY = 500; +export const GET_ALL_QUERY_DELAY = 500 /** * The default number of milliseconds to wait before retrying a rate-limited @@ -62,7 +64,7 @@ export const GET_ALL_QUERY_DELAY = 500; * * The API allows up to 200 requests per second. */ -const DEFUALT_RETRY_AFTER_MS = 1000; +const DEFUALT_RETRY_AFTER_MS = 1000 /** * Extracts one or more Prismic document types that match a given Prismic @@ -78,7 +80,7 @@ type ExtractDocumentType< > = Extract extends never ? TDocuments - : Extract; + : Extract /** * A universal API to make network requests. A subset of the `fetch()` API. @@ -88,7 +90,7 @@ type ExtractDocumentType< export type FetchLike = ( input: string, init?: RequestInitLike, -) => Promise; +) => Promise /** * An object that allows you to abort a `fetch()` request if needed via an @@ -101,7 +103,7 @@ export type FetchLike = ( // important to validate since it is blindly passed to a given `fetch()` // function. // eslint-disable-next-line @typescript-eslint/no-explicit-any -export type AbortSignalLike = any; +export type AbortSignalLike = any /** * A subset of RequestInit properties to configure a `fetch()` request. @@ -115,7 +117,7 @@ export interface RequestInitLike extends Pick { /** * An object literal to set the `fetch()` request's headers. */ - headers?: Record; + headers?: Record /** * An AbortSignal to set the `fetch()` request's signal. @@ -126,24 +128,24 @@ export interface RequestInitLike extends Pick { // NOTE: `AbortSignalLike` is `any`! It is left as `AbortSignalLike` // for backwards compatibility (the type is exported) and to signal to // other readers that this should be an AbortSignal-like object. - signal?: AbortSignalLike; + signal?: AbortSignalLike } /** * The minimum required properties from Response. */ export interface ResponseLike { - status: number; - headers: HeadersLike; + status: number + headers: HeadersLike // eslint-disable-next-line @typescript-eslint/no-explicit-any - json(): Promise; + json(): Promise } /** * The minimum required properties from Headers. */ export interface HeadersLike { - get(name: string): string | null; + get(name: string): string | null } /** @@ -158,9 +160,9 @@ export type HttpRequestLike = */ { headers?: { - get(name: string): string | null; - }; - url?: string; + get(name: string): string | null + } + url?: string } /** @@ -168,10 +170,10 @@ export type HttpRequestLike = */ | { headers?: { - cookie?: string; - }; - query?: Record; - }; + cookie?: string + } + query?: Record + } /** * Modes for client ref management. @@ -205,30 +207,30 @@ type RefState = { /** * Determines if automatic preview support is enabled. */ - autoPreviewsEnabled: boolean; + autoPreviewsEnabled: boolean /** * An optional HTTP server request object used during previews if automatic * previews are enabled. */ - httpRequest?: HttpRequestLike; + httpRequest?: HttpRequestLike } & ( | { - mode: RefStateMode.Master; + mode: RefStateMode.Master } | { - mode: RefStateMode.ReleaseID; - releaseID: string; + mode: RefStateMode.ReleaseID + releaseID: string } | { - mode: RefStateMode.ReleaseLabel; - releaseLabel: string; + mode: RefStateMode.ReleaseLabel + releaseLabel: string } | { - mode: RefStateMode.Manual; - ref: RefStringOrThunk; + mode: RefStateMode.Manual + ref: RefStringOrThunk } -); +) /** * A ref or a function that returns a ref. If a static ref is known, one can be @@ -237,7 +239,7 @@ type RefState = { */ type RefStringOrThunk = | string - | (() => string | undefined | Promise); + | (() => string | undefined | Promise) /** * Configuration for clients that determine how content is queried. @@ -247,14 +249,14 @@ export type ClientConfig = { * The secure token for accessing the Prismic repository. This is only * required if the repository is set to private. */ - accessToken?: string; + accessToken?: string /** * A string representing a version of the Prismic repository's content. This * may point to the latest version (called the "master ref"), or a preview * with draft content. */ - ref?: RefStringOrThunk; + ref?: RefStringOrThunk /** * A list of route resolver objects that define how a document's `url` @@ -262,7 +264,7 @@ export type ClientConfig = { * * {@link https://prismic.io/docs/route-resolver} */ - routes?: NonNullable; + routes?: NonNullable /** * The `brokenRoute` option allows you to define the route populated in the @@ -272,7 +274,7 @@ export type ClientConfig = { * * {@link https://prismic.io/docs/route-resolver} */ - brokenRoute?: NonNullable; + brokenRoute?: NonNullable /** * Default parameters that will be sent with each query. These parameters can @@ -281,22 +283,22 @@ export type ClientConfig = { defaultParams?: Omit< BuildQueryURLArgs, "ref" | "integrationFieldsRef" | "accessToken" | "routes" | "brokenRoute" - >; + > /** * The function used to make network requests to the Prismic REST API. In * environments where a global `fetch` function does not exist, such as * Node.js, this function must be provided. */ - fetch?: FetchLike; + fetch?: FetchLike /** * Options provided to the client's `fetch()` on all network requests. These * options will be merged with internally required options. They can also be * overriden on a per-query basis using the query's `fetchOptions` parameter. */ - fetchOptions?: RequestInitLike; -}; + fetchOptions?: RequestInitLike +} /** * Parameters for any client method that use `fetch()`. @@ -307,7 +309,7 @@ type FetchParams = { * options will be merged with internally required options. They can also be * overriden on a per-query basis using the query's `fetchOptions` parameter. */ - fetchOptions?: RequestInitLike; + fetchOptions?: RequestInitLike /** * An `AbortSignal` provided by an `AbortController`. This allows the network @@ -317,8 +319,8 @@ type FetchParams = { * * @see \ */ - signal?: AbortSignalLike; -}; + signal?: AbortSignalLike +} /** * Parameters specific to client methods that fetch all documents. These methods @@ -329,8 +331,8 @@ type GetAllParams = { * Limit the number of documents queried. If a number is not provided, there * will be no limit and all matching documents will be returned. */ - limit?: number; -}; + limit?: number +} /** * Arguments to determine how the URL for a preview session is resolved. @@ -339,34 +341,34 @@ type ResolvePreviewArgs = { /** * A function that maps a Prismic document to a URL within your app. */ - linkResolver?: LinkResolverFunction; + linkResolver?: LinkResolverFunction /** * A fallback URL if the link resolver does not return a value. */ - defaultURL: string; + defaultURL: string /** * The preview token (also known as a ref) that will be used to query preview * content from the Prismic repository. */ - previewToken?: string; + previewToken?: string /** * The previewed document that will be used to determine the destination URL. */ - documentID?: string; -}; + documentID?: string +} /** * The result of a `fetch()` job. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any type FetchJobResult = { - status: number; - headers: HeadersLike; - json: TJSON; -}; + status: number + headers: HeadersLike + json: TJSON +} /** * Type definitions for the `createClient()` function. May be augmented by @@ -375,7 +377,7 @@ type FetchJobResult = { export interface CreateClient { ( ...args: ConstructorParameters - ): Client; + ): Client } /** @@ -385,10 +387,10 @@ export interface CreateClient { * * ```ts * // With a repository name. - * createClient("qwerty"); + * createClient("qwerty") * * // Or with a full Prismic Rest API V2 endpoint. - * createClient("https://qwerty.cdn.prismic.io/api/v2"); + * createClient("https://qwerty.cdn.prismic.io/api/v2") * ``` * * @typeParam TDocuments - A map of Prismic document type IDs mapped to their @@ -404,7 +406,7 @@ export interface CreateClient { export const createClient: CreateClient = ( repositoryNameOrEndpoint: string, options?: ClientConfig, -) => new Client(repositoryNameOrEndpoint, options); +) => new Client(repositoryNameOrEndpoint, options) /** * A client that allows querying content from a Prismic repository. @@ -421,7 +423,7 @@ export class Client { * The Prismic REST API V2 endpoint for the repository (use * `prismic.getRepositoryEndpoint` for the default endpoint). */ - endpoint: string; + endpoint: string /** * The secure token for accessing the API (only needed if your repository is @@ -429,7 +431,7 @@ export class Client { * * {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token} */ - accessToken?: string; + accessToken?: string /** * A list of route resolver objects that define how a document's `url` field @@ -437,7 +439,7 @@ export class Client { * * {@link https://prismic.io/docs/route-resolver} */ - routes?: NonNullable; + routes?: NonNullable /** * The `brokenRoute` option allows you to define the route populated in the @@ -447,16 +449,16 @@ export class Client { * * {@link https://prismic.io/docs/route-resolver} */ - brokenRoute?: NonNullable; + brokenRoute?: NonNullable /** * The function used to make network requests to the Prismic REST API. In * environments where a global `fetch` function does not exist, such as * Node.js, this function must be provided. */ - fetchFn: FetchLike; + fetchFn: FetchLike - fetchOptions?: RequestInitLike; + fetchOptions?: RequestInitLike /** * Default parameters that will be sent with each query. These parameters can @@ -465,7 +467,7 @@ export class Client { defaultParams?: Omit< BuildQueryURLArgs, "ref" | "integrationFieldsRef" | "accessToken" | "routes" - >; + > /** * The client's ref mode state. This determines which ref is used during @@ -474,17 +476,17 @@ export class Client { private refState: RefState = { mode: RefStateMode.Master, autoPreviewsEnabled: true, - }; + } /** * Cached repository value. */ - private cachedRepository: Repository | undefined; + private cachedRepository: Repository | undefined /** * Timestamp at which the cached repository data is considered stale. */ - private cachedRepositoryExpiration = 0; + private cachedRepositoryExpiration = 0 /** * Active `fetch()` jobs keyed by URL and AbortSignal (if it exists). @@ -492,7 +494,7 @@ export class Client { private fetchJobs: Record< string, Map> - > = {}; + > = {} /** * Creates a Prismic client that can be used to query a repository. @@ -517,61 +519,61 @@ export class Client { "@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.", undefined, undefined, - ); + ) } const hostname = new URL( repositoryNameOrEndpoint, - ).hostname.toLowerCase(); + ).hostname.toLowerCase() // Matches non-.cdn `.prismic.io` endpoints if ( hostname.endsWith(".prismic.io") && !hostname.endsWith(".cdn.prismic.io") ) { - const repositoryName = getRepositoryName(repositoryNameOrEndpoint); - const dotCDNEndpoint = getRepositoryEndpoint(repositoryName); + const repositoryName = getRepositoryName(repositoryNameOrEndpoint) + const dotCDNEndpoint = getRepositoryEndpoint(repositoryName) console.warn( `[@prismicio/client] A non-.cdn endpoint was provided to create a client with (\`${repositoryNameOrEndpoint}\`). Non-.cdn endpoints can have unexpected side-effects and cause performance issues when querying Prismic. Please convert it to the \`.cdn\` alternative (\`${dotCDNEndpoint}\`) or use the repository name directly instead (\`${repositoryName}\`). For more details, see ${devMsg( "endpoint-must-use-cdn", )}`, - ); + ) } } - this.endpoint = repositoryNameOrEndpoint; + this.endpoint = repositoryNameOrEndpoint } else { - this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint); + this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint) } - this.accessToken = options.accessToken; - this.routes = options.routes; - this.brokenRoute = options.brokenRoute; - this.fetchOptions = options.fetchOptions; - this.defaultParams = options.defaultParams; + this.accessToken = options.accessToken + this.routes = options.routes + this.brokenRoute = options.brokenRoute + this.fetchOptions = options.fetchOptions + this.defaultParams = options.defaultParams if (options.ref) { - this.queryContentFromRef(options.ref); + this.queryContentFromRef(options.ref) } if (typeof options.fetch === "function") { - this.fetchFn = options.fetch; + this.fetchFn = options.fetch } else if (typeof globalThis.fetch === "function") { - this.fetchFn = globalThis.fetch as FetchLike; + this.fetchFn = globalThis.fetch as FetchLike } else { throw new PrismicError( "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.", undefined, undefined, - ); + ) } // If the global fetch function is used, we must bind it to the global scope. if (this.fetchFn === globalThis.fetch) { - this.fetchFn = this.fetchFn.bind(globalThis); + this.fetchFn = this.fetchFn.bind(globalThis) } - this.graphQLFetch = this.graphQLFetch.bind(this); + this.graphQLFetch = this.graphQLFetch.bind(this) } /** @@ -584,13 +586,13 @@ export class Client { * @example * * ```ts - * client.enableAutoPreviews(); + * client.enableAutoPreviews() * ``` * * @see enableAutoPreviewsFromReq */ enableAutoPreviews(): void { - this.refState.autoPreviewsEnabled = true; + this.refState.autoPreviewsEnabled = true } /** @@ -605,16 +607,16 @@ export class Client { * ```ts * // In an express app * app.get("/", function (req, res) { - * client.enableAutoPreviewsFromReq(req); - * }); + * client.enableAutoPreviewsFromReq(req) + * }) * ``` * * @param req - An HTTP server request object containing the request's * cookies. */ enableAutoPreviewsFromReq(req: R): void { - this.refState.httpRequest = req; - this.refState.autoPreviewsEnabled = true; + this.refState.httpRequest = req + this.refState.autoPreviewsEnabled = true } /** @@ -627,11 +629,11 @@ export class Client { * @example * * ```ts - * client.disableAutoPreviews(); + * client.disableAutoPreviews() * ``` */ disableAutoPreviews(): void { - this.refState.autoPreviewsEnabled = false; + this.refState.autoPreviewsEnabled = false } /** @@ -640,7 +642,7 @@ export class Client { * @example * * ```ts - * const response = await client.get(); + * const response = await client.get() * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -652,9 +654,9 @@ export class Client { async get( params?: Partial & FetchParams, ): Promise> { - const url = await this.buildQueryURL(params); + const url = await this.buildQueryURL(params) - return await this.fetch>(url, params); + return await this.fetch>(url, params) } /** @@ -664,7 +666,7 @@ export class Client { * @example * * ```ts - * const document = await client.getFirst(); + * const document = await client.getFirst() * ``` * * @typeParam TDocument - Type of the Prismic document returned. @@ -675,20 +677,20 @@ export class Client { async getFirst( params?: Partial & FetchParams, ): Promise { - const actualParams = { ...params }; + const actualParams = { ...params } if (!(params && params.page) && !params?.pageSize) { - actualParams.pageSize = this.defaultParams?.pageSize ?? 1; + actualParams.pageSize = this.defaultParams?.pageSize ?? 1 } - const url = await this.buildQueryURL(actualParams); - const result = await this.fetch>(url, params); + const url = await this.buildQueryURL(actualParams) + const result = await this.fetch>(url, params) - const firstResult = result.results[0]; + const firstResult = result.results[0] if (firstResult) { - return firstResult; + return firstResult } - throw new NotFoundError("No documents were returned", url, undefined); + throw new NotFoundError("No documents were returned", url, undefined) } /** @@ -705,7 +707,7 @@ export class Client { * @example * * ```ts - * const response = await client.dangerouslyGetAll(); + * const response = await client.dangerouslyGetAll() * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -719,33 +721,33 @@ export class Client { GetAllParams & FetchParams = {}, ): Promise { - const { limit = Infinity, ...actualParams } = params; + const { limit = Infinity, ...actualParams } = params const resolvedParams = { ...actualParams, pageSize: Math.min( limit, actualParams.pageSize || this.defaultParams?.pageSize || MAX_PAGE_SIZE, ), - }; + } - const documents: TDocument[] = []; - let latestResult: Query | undefined; + const documents: TDocument[] = [] + let latestResult: Query | undefined while ( (!latestResult || latestResult.next_page) && documents.length < limit ) { - const page = latestResult ? latestResult.page + 1 : undefined; + const page = latestResult ? latestResult.page + 1 : undefined - latestResult = await this.get({ ...resolvedParams, page }); - documents.push(...latestResult.results); + latestResult = await this.get({ ...resolvedParams, page }) + documents.push(...latestResult.results) if (latestResult.next_page) { - await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY)); + await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY)) } } - return documents.slice(0, limit); + return documents.slice(0, limit) } /** @@ -760,7 +762,7 @@ export class Client { * @example * * ```ts - * const document = await client.getByID("WW4bKScAAMAqmluX"); + * const document = await client.getByID("WW4bKScAAMAqmluX") * ``` * * @typeParam TDocument- Type of the Prismic document returned. @@ -777,7 +779,7 @@ export class Client { ): Promise { return await this.getFirst( appendFilters(params, filter.at("document.id", id)), - ); + ) } /** @@ -795,7 +797,7 @@ export class Client { * const response = await client.getByIDs([ * "WW4bKScAAMAqmluX", * "U1kTRgEAAC8A5ldS", - * ]); + * ]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -812,7 +814,7 @@ export class Client { ): Promise> { return await this.get( appendFilters(params, filter.in("document.id", ids)), - ); + ) } /** @@ -833,7 +835,7 @@ export class Client { * const response = await client.getAllByIDs([ * "WW4bKScAAMAqmluX", * "U1kTRgEAAC8A5ldS", - * ]); + * ]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -849,7 +851,7 @@ export class Client { ): Promise { return await this.dangerouslyGetAll( appendFilters(params, filter.in("document.id", ids)), - ); + ) } /** @@ -865,7 +867,7 @@ export class Client { * @example * * ```ts - * const document = await client.getByUID("blog_post", "my-first-post"); + * const document = await client.getByUID("blog_post", "my-first-post") * ``` * * @typeParam TDocument - Type of the Prismic document returned. @@ -890,7 +892,7 @@ export class Client { typeFilter(documentType), filter.at(`my.${documentType}.uid`, uid), ]), - ); + ) } /** @@ -909,7 +911,7 @@ export class Client { * const document = await client.getByUIDs("blog_post", [ * "my-first-post", * "my-second-post", - * ]); + * ]) * ``` * * @typeParam TDocument - Type of the Prismic document returned. @@ -934,7 +936,7 @@ export class Client { typeFilter(documentType), filter.in(`my.${documentType}.uid`, uids), ]), - ); + ) } /** @@ -956,7 +958,7 @@ export class Client { * const response = await client.getAllByUIDs([ * "my-first-post", * "my-second-post", - * ]); + * ]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -982,7 +984,7 @@ export class Client { typeFilter(documentType), filter.in(`my.${documentType}.uid`, uids), ]), - ); + ) } /** @@ -998,7 +1000,7 @@ export class Client { * @example * * ```ts - * const document = await client.getSingle("settings"); + * const document = await client.getSingle("settings") * ``` * * @typeParam TDocument - Type of the Prismic document returned. @@ -1018,7 +1020,7 @@ export class Client { ): Promise> { return await this.getFirst>( appendFilters(params, typeFilter(documentType)), - ); + ) } /** @@ -1030,7 +1032,7 @@ export class Client { * @example * * ```ts - * const response = await client.getByType("blog_post"); + * const response = await client.getByType("blog_post") * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1049,7 +1051,7 @@ export class Client { ): Promise>> { return await this.get>( appendFilters(params, typeFilter(documentType)), - ); + ) } /** @@ -1062,7 +1064,7 @@ export class Client { * @example * * ```ts - * const response = await client.getByType("blog_post"); + * const response = await client.getByType("blog_post") * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1083,7 +1085,7 @@ export class Client { ): Promise[]> { return await this.dangerouslyGetAll< ExtractDocumentType - >(appendFilters(params, typeFilter(documentType))); + >(appendFilters(params, typeFilter(documentType))) } /** @@ -1095,7 +1097,7 @@ export class Client { * @example * * ```ts - * const response = await client.getByTag("food"); + * const response = await client.getByTag("food") * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1109,9 +1111,7 @@ export class Client { tag: string, params?: Partial & FetchParams, ): Promise> { - return await this.get( - appendFilters(params, someTagsFilter(tag)), - ); + return await this.get(appendFilters(params, someTagsFilter(tag))) } /** @@ -1123,7 +1123,7 @@ export class Client { * @example * * ```ts - * const response = await client.getAllByTag("food"); + * const response = await client.getAllByTag("food") * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1141,7 +1141,7 @@ export class Client { ): Promise { return await this.dangerouslyGetAll( appendFilters(params, someTagsFilter(tag)), - ); + ) } /** @@ -1151,7 +1151,7 @@ export class Client { * @example * * ```ts - * const response = await client.getByEveryTag(["food", "fruit"]); + * const response = await client.getByEveryTag(["food", "fruit"]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1167,7 +1167,7 @@ export class Client { ): Promise> { return await this.get( appendFilters(params, everyTagFilter(tags)), - ); + ) } /** @@ -1180,7 +1180,7 @@ export class Client { * @example * * ```ts - * const response = await client.getAllByEveryTag(["food", "fruit"]); + * const response = await client.getAllByEveryTag(["food", "fruit"]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1198,7 +1198,7 @@ export class Client { ): Promise { return await this.dangerouslyGetAll( appendFilters(params, everyTagFilter(tags)), - ); + ) } /** @@ -1209,7 +1209,7 @@ export class Client { * @example * * ```ts - * const response = await client.getByEveryTag(["food", "fruit"]); + * const response = await client.getByEveryTag(["food", "fruit"]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1226,7 +1226,7 @@ export class Client { ): Promise> { return await this.get( appendFilters(params, someTagsFilter(tags)), - ); + ) } /** @@ -1240,7 +1240,7 @@ export class Client { * @example * * ```ts - * const response = await client.getAllBySomeTags(["food", "fruit"]); + * const response = await client.getAllBySomeTags(["food", "fruit"]) * ``` * * @typeParam TDocument - Type of Prismic documents returned. @@ -1258,7 +1258,7 @@ export class Client { ): Promise { return await this.dangerouslyGetAll( appendFilters(params, someTagsFilter(tags)), - ); + ) } /** @@ -1271,13 +1271,13 @@ export class Client { // TODO: Restore when Authorization header support works in browsers with CORS. // return await this.fetch(this.endpoint); - const url = new URL(this.endpoint); + const url = new URL(this.endpoint) if (this.accessToken) { - url.searchParams.set("access_token", this.accessToken); + url.searchParams.set("access_token", this.accessToken) } - return await this.fetch(url.toString(), params); + return await this.fetch(url.toString(), params) } /** @@ -1290,9 +1290,9 @@ export class Client { * @returns A list of all refs for the Prismic repository. */ async getRefs(params?: FetchParams): Promise { - const repository = await this.getRepository(params); + const repository = await this.getRepository(params) - return repository.refs; + return repository.refs } /** @@ -1303,9 +1303,9 @@ export class Client { * @returns The ref with a matching ID, if it exists. */ async getRefByID(id: string, params?: FetchParams): Promise { - const refs = await this.getRefs(params); + const refs = await this.getRefs(params) - return findRefByID(refs, id); + return findRefByID(refs, id) } /** @@ -1316,9 +1316,9 @@ export class Client { * @returns The ref with a matching label, if it exists. */ async getRefByLabel(label: string, params?: FetchParams): Promise { - const refs = await this.getRefs(params); + const refs = await this.getRefs(params) - return findRefByLabel(refs, label); + return findRefByLabel(refs, label) } /** @@ -1328,9 +1328,9 @@ export class Client { * @returns The repository's master ref. */ async getMasterRef(params?: FetchParams): Promise { - const refs = await this.getRefs(params); + const refs = await this.getRefs(params) - return findMasterRef(refs); + return findMasterRef(refs) } /** @@ -1340,9 +1340,9 @@ export class Client { * @returns A list of all Releases for the Prismic repository. */ async getReleases(params?: FetchParams): Promise { - const refs = await this.getRefs(params); + const refs = await this.getRefs(params) - return refs.filter((ref) => !ref.isMasterRef); + return refs.filter((ref) => !ref.isMasterRef) } /** @@ -1353,9 +1353,9 @@ export class Client { * @returns The Release with a matching ID, if it exists. */ async getReleaseByID(id: string, params?: FetchParams): Promise { - const releases = await this.getReleases(params); + const releases = await this.getReleases(params) - return findRefByID(releases, id); + return findRefByID(releases, id) } /** @@ -1366,9 +1366,9 @@ export class Client { * @returns The ref with a matching label, if it exists. */ async getReleaseByLabel(label: string, params?: FetchParams): Promise { - const releases = await this.getReleases(params); + const releases = await this.getReleases(params) - return findRefByLabel(releases, label); + return findRefByLabel(releases, label) } /** @@ -1378,19 +1378,19 @@ export class Client { */ async getTags(params?: FetchParams): Promise { try { - const tagsForm = await this.getCachedRepositoryForm("tags", params); + const tagsForm = await this.getCachedRepositoryForm("tags", params) - const url = new URL(tagsForm.action); + const url = new URL(tagsForm.action) if (this.accessToken) { - url.searchParams.set("access_token", this.accessToken); + url.searchParams.set("access_token", this.accessToken) } - return await this.fetch(url.toString(), params); + return await this.fetch(url.toString(), params) } catch { - const repository = await this.getRepository(params); + const repository = await this.getRepository(params) - return repository.tags; + return repository.tags } } @@ -1407,12 +1407,12 @@ export class Client { ...params }: Partial & FetchParams = {}): Promise { const ref = - params.ref || (await this.getResolvedRefString({ signal, fetchOptions })); + params.ref || (await this.getResolvedRefString({ signal, fetchOptions })) const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({ signal, fetchOptions })) .integrationFieldsRef || - undefined; + undefined return buildQueryURL(this.endpoint, { ...this.defaultParams, @@ -1422,7 +1422,7 @@ export class Client { routes: params.routes || this.routes, brokenRoute: params.brokenRoute || this.brokenRoute, accessToken: params.accessToken || this.accessToken, - }); + }) } /** @@ -1447,20 +1447,20 @@ export class Client { async resolvePreviewURL( args: ResolvePreviewArgs & FetchParams, ): Promise { - let documentID: string | undefined | null = args.documentID; - let previewToken: string | undefined | null = args.previewToken; + let documentID: string | undefined | null = args.documentID + let previewToken: string | undefined | null = args.previewToken if (typeof globalThis.location !== "undefined") { - const searchParams = new URLSearchParams(globalThis.location.search); + const searchParams = new URLSearchParams(globalThis.location.search) - documentID = documentID || searchParams.get("documentId"); - previewToken = previewToken || searchParams.get("token"); + documentID = documentID || searchParams.get("documentId") + previewToken = previewToken || searchParams.get("token") } else if (this.refState.httpRequest) { if ("query" in this.refState.httpRequest) { documentID = - documentID || (this.refState.httpRequest.query?.documentId as string); + documentID || (this.refState.httpRequest.query?.documentId as string) previewToken = - previewToken || (this.refState.httpRequest.query?.token as string); + previewToken || (this.refState.httpRequest.query?.token as string) } else if ( "url" in this.refState.httpRequest && this.refState.httpRequest.url @@ -1473,10 +1473,10 @@ export class Client { const searchParams = new URL( this.refState.httpRequest.url, "missing-host://", - ).searchParams; + ).searchParams - documentID = documentID || searchParams.get("documentId"); - previewToken = previewToken || searchParams.get("token"); + documentID = documentID || searchParams.get("documentId") + previewToken = previewToken || searchParams.get("token") } } @@ -1486,16 +1486,16 @@ export class Client { lang: "*", signal: args.signal, fetchOptions: args.fetchOptions, - }); + }) - const url = asLink(document, { linkResolver: args.linkResolver }); + const url = asLink(document, { linkResolver: args.linkResolver }) if (typeof url === "string") { - return url; + return url } } - return args.defaultURL; + return args.defaultURL } /** @@ -1508,12 +1508,12 @@ export class Client { * @example * * ```ts - * await client.queryLatestContent(); - * const document = await client.getByID("WW4bKScAAMAqmluX"); + * await client.queryLatestContent() + * const document = await client.getByID("WW4bKScAAMAqmluX") * ``` */ queryLatestContent(): void { - this.refState.mode = RefStateMode.Master; + this.refState.mode = RefStateMode.Master } /** @@ -1526,8 +1526,8 @@ export class Client { * @example * * ```ts - * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa"); - * const document = await client.getByID("WW4bKScAAMAqmluX"); + * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa") + * const document = await client.getByID("WW4bKScAAMAqmluX") * ``` * * @param releaseID - The ID of the Release. @@ -1537,7 +1537,7 @@ export class Client { ...this.refState, mode: RefStateMode.ReleaseID, releaseID, - }; + } } /** @@ -1550,8 +1550,8 @@ export class Client { * @example * * ```ts - * await client.queryContentFromReleaseByLabel("My Release"); - * const document = await client.getByID("WW4bKScAAMAqmluX"); + * await client.queryContentFromReleaseByLabel("My Release") + * const document = await client.getByID("WW4bKScAAMAqmluX") * ``` * * @param releaseLabel - The label of the Release. @@ -1561,7 +1561,7 @@ export class Client { ...this.refState, mode: RefStateMode.ReleaseLabel, releaseLabel, - }; + } } /** @@ -1574,8 +1574,8 @@ export class Client { * @example * * ```ts - * await client.queryContentFromRef("my-ref"); - * const document = await client.getByID("WW4bKScAAMAqmluX"); + * await client.queryContentFromRef("my-ref") + * const document = await client.getByID("WW4bKScAAMAqmluX") * ``` * * @param ref - The ref or a function that returns the ref from which to query @@ -1586,7 +1586,7 @@ export class Client { ...this.refState, mode: RefStateMode.Manual, ref, - }; + } } /** @@ -1607,7 +1607,7 @@ export class Client { * useGETForQueries: true, * }), * cache: new InMemoryCache(), - * }); + * }) * ``` * * @param input - The `fetch()` `input` parameter. Only strings are supported. @@ -1622,8 +1622,8 @@ export class Client { input: RequestInfo, init?: Omit & { signal?: AbortSignalLike }, ): Promise { - const cachedRepository = await this.getCachedRepository(); - const ref = await this.getResolvedRefString(); + const cachedRepository = await this.getCachedRepository() + const ref = await this.getResolvedRefString() const unsanitizedHeaders: Record = { "Prismic-ref": ref, @@ -1632,21 +1632,21 @@ export class Client { // libraries pass this as a Record. Header objects as input // are unsupported. ...(init ? (init.headers as Record) : {}), - }; + } if (cachedRepository.integrationFieldsRef) { unsanitizedHeaders["Prismic-integration-field-ref"] = - cachedRepository.integrationFieldsRef; + cachedRepository.integrationFieldsRef } // Normalize header keys to lowercase. This prevents header // conflicts between the Prismic client and the GraphQL // client. - const headers: Record = {}; + const headers: Record = {} for (const key in unsanitizedHeaders) { if (unsanitizedHeaders[key]) { headers[key.toLowerCase()] = - unsanitizedHeaders[key as keyof typeof unsanitizedHeaders]; + unsanitizedHeaders[key as keyof typeof unsanitizedHeaders] } } @@ -1655,7 +1655,7 @@ export class Client { // libraries pass this as a string. Request objects as // input are unsupported. input as string, - ); + ) // This prevents the request from being cached unnecessarily. // Without adding this `ref` param, re-running a query @@ -1665,9 +1665,9 @@ export class Client { // headers. // // The Prismic GraphQL API ignores the `ref` param. - url.searchParams.set("ref", ref); + url.searchParams.set("ref", ref) - const query = url.searchParams.get("query"); + const query = url.searchParams.get("query") if (query) { url.searchParams.set( "query", @@ -1677,13 +1677,13 @@ export class Client { // hitting the upper limit of GET requests // (2048 characters). minifyGraphQLQuery(query), - ); + ) } return (await this.fetchFn(url.toString(), { ...init, headers, - })) as Response; + })) as Response } /** @@ -1696,11 +1696,11 @@ export class Client { !this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration ) { - this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL; - this.cachedRepository = await this.getRepository(params); + this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL + this.cachedRepository = await this.getRepository(params) } - return this.cachedRepository; + return this.cachedRepository } /** @@ -1717,18 +1717,18 @@ export class Client { name: string, params?: FetchParams, ): Promise
{ - const cachedRepository = await this.getCachedRepository(params); - const form = cachedRepository.forms[name]; + const cachedRepository = await this.getCachedRepository(params) + const form = cachedRepository.forms[name] if (!form) { throw new PrismicError( `Form with name "${name}" could not be found`, undefined, undefined, - ); + ) } - return form; + return form } /** @@ -1756,9 +1756,9 @@ export class Client { */ private async getResolvedRefString(params?: FetchParams): Promise { if (this.refState.autoPreviewsEnabled) { - let previewRef: string | undefined; + let previewRef: string | undefined - let cookieJar: string | null | undefined; + let cookieJar: string | null | undefined if (this.refState.httpRequest?.headers) { if ( @@ -1766,41 +1766,41 @@ export class Client { typeof this.refState.httpRequest.headers.get === "function" ) { // Web API Headers - cookieJar = this.refState.httpRequest.headers.get("cookie"); + cookieJar = this.refState.httpRequest.headers.get("cookie") } else if ("cookie" in this.refState.httpRequest.headers) { // Express-style headers - cookieJar = this.refState.httpRequest.headers.cookie; + cookieJar = this.refState.httpRequest.headers.cookie } } else if (globalThis.document?.cookie) { - cookieJar = globalThis.document.cookie; + cookieJar = globalThis.document.cookie } if (cookieJar) { - previewRef = getPreviewCookie(cookieJar); + previewRef = getPreviewCookie(cookieJar) } if (previewRef) { - return previewRef; + return previewRef } } - const cachedRepository = await this.getCachedRepository(params); + const cachedRepository = await this.getCachedRepository(params) - const refModeType = this.refState.mode; + const refModeType = this.refState.mode if (refModeType === RefStateMode.ReleaseID) { - return findRefByID(cachedRepository.refs, this.refState.releaseID).ref; + return findRefByID(cachedRepository.refs, this.refState.releaseID).ref } else if (refModeType === RefStateMode.ReleaseLabel) { return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel) - .ref; + .ref } else if (refModeType === RefStateMode.Manual) { - const res = await castThunk(this.refState.ref)(); + const res = await castThunk(this.refState.ref)() if (typeof res === "string") { - return res; + return res } } - return findMasterRef(cachedRepository.refs).ref; + return findMasterRef(cachedRepository.refs).ref } /** @@ -1830,9 +1830,9 @@ export class Client { params.fetchOptions?.signal || params.signal || this.fetchOptions?.signal, - }; + } - let job: Promise; + let job: Promise // `fetchJobs` is keyed twice: first by the URL and again by is // signal, if one exists. @@ -1841,9 +1841,9 @@ export class Client { // equivalent URLs, but eject when we detect unique signals. if (this.fetchJobs[url] && this.fetchJobs[url].has(requestInit.signal)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - job = this.fetchJobs[url].get(requestInit.signal)!; + job = this.fetchJobs[url].get(requestInit.signal)! } else { - this.fetchJobs[url] = this.fetchJobs[url] || new Map(); + this.fetchJobs[url] = this.fetchJobs[url] || new Map() job = this.fetchFn(url, requestInit) .then(async (res) => { @@ -1853,9 +1853,9 @@ export class Client { // throw, signaling an invalid // response. // eslint-disable-next-line @typescript-eslint/no-explicit-any - let json: any = undefined; + let json: any = undefined try { - json = await res.json(); + json = await res.json() } catch { // noop } @@ -1864,36 +1864,36 @@ export class Client { status: res.status, headers: res.headers, json, - }; + } }) .finally(() => { - this.fetchJobs[url].delete(requestInit.signal); + this.fetchJobs[url].delete(requestInit.signal) if (this.fetchJobs[url].size === 0) { - delete this.fetchJobs[url]; + delete this.fetchJobs[url] } - }); + }) - this.fetchJobs[url].set(requestInit.signal, job); + this.fetchJobs[url].set(requestInit.signal, job) } - const res = await job; + const res = await job if (res.status !== 404 && res.json == null) { - throw new PrismicError(undefined, url, res.json); + throw new PrismicError(undefined, url, res.json) } switch (res.status) { // Successful case 200: { - return res.json; + return res.json } // Bad Request // - Invalid filter syntax // - Ref not provided (ignored) case 400: { - throw new ParsingError(res.json.message, url, res.json); + throw new ParsingError(res.json.message, url, res.json) } // Unauthorized @@ -1908,7 +1908,7 @@ export class Client { res.json.error || res.json.message, url, res.json, - ); + ) } // Not Found @@ -1921,49 +1921,49 @@ export class Client { `Prismic repository not found. Check that "${this.endpoint}" is pointing to the correct repository.`, url, undefined, - ); + ) } if (res.json.type === "api_notfound_error") { - throw new RefNotFoundError(res.json.message, url, res.json); + throw new RefNotFoundError(res.json.message, url, res.json) } if ( res.json.type === "api_security_error" && /preview token.*expired/i.test(res.json.message) ) { - throw new PreviewTokenExpiredError(res.json.message, url, res.json); + throw new PreviewTokenExpiredError(res.json.message, url, res.json) } - throw new NotFoundError(res.json.message, url, res.json); + throw new NotFoundError(res.json.message, url, res.json) } // Gone // - Ref is expired case 410: { - throw new RefExpiredError(res.json.message, url, res.json); + throw new RefExpiredError(res.json.message, url, res.json) } // Too Many Requests // - Exceeded the maximum number of requests per second case 429: { - const parsedRetryAfter = Number(res.headers.get("retry-after")); + const parsedRetryAfter = Number(res.headers.get("retry-after")) const delay = Number.isNaN(parsedRetryAfter) ? DEFUALT_RETRY_AFTER_MS - : parsedRetryAfter; + : parsedRetryAfter return await new Promise((resolve, reject) => { setTimeout(async () => { try { - resolve(await this.fetch(url, params)); + resolve(await this.fetch(url, params)) } catch (error) { - reject(error); + reject(error) } - }, delay); - }); + }, delay) + }) } } - throw new PrismicError(undefined, url, res.json); + throw new PrismicError(undefined, url, res.json) } } diff --git a/src/errors/ForbiddenError.ts b/src/errors/ForbiddenError.ts index ccb41c2c..b5d664c6 100644 --- a/src/errors/ForbiddenError.ts +++ b/src/errors/ForbiddenError.ts @@ -1,13 +1,13 @@ -import { PrismicError } from "./PrismicError"; +import { PrismicError } from "./PrismicError" type ForbiddenErrorRepositoryAPIResponse = { - type: string; - message: string; -}; + type: string + message: string +} type ForbiddenErrorQueryAPIResponse = { - error: string; -}; + error: string +} export class ForbiddenError< TResponse = diff --git a/src/errors/NotFoundError.ts b/src/errors/NotFoundError.ts index c1442f95..47aff6a9 100644 --- a/src/errors/NotFoundError.ts +++ b/src/errors/NotFoundError.ts @@ -1,4 +1,4 @@ -import { PrismicError } from "./PrismicError"; +import { PrismicError } from "./PrismicError" export class NotFoundError< TResponse = undefined, diff --git a/src/errors/ParsingError.ts b/src/errors/ParsingError.ts index 9e3cf5b4..818fc300 100644 --- a/src/errors/ParsingError.ts +++ b/src/errors/ParsingError.ts @@ -1,13 +1,13 @@ -import { PrismicError } from "./PrismicError"; +import { PrismicError } from "./PrismicError" type ParsingErrorAPIResponse = { - type: "parsing-error"; - message: string; - line: number; - column: number; - id: number; - location: string; -}; + type: "parsing-error" + message: string + line: number + column: number + id: number + location: string +} export class ParsingError< TResponse = ParsingErrorAPIResponse, diff --git a/src/errors/PreviewTokenExpired.ts b/src/errors/PreviewTokenExpired.ts index 799ed97b..6dd49973 100644 --- a/src/errors/PreviewTokenExpired.ts +++ b/src/errors/PreviewTokenExpired.ts @@ -1,9 +1,9 @@ -import { ForbiddenError } from "./ForbiddenError"; +import { ForbiddenError } from "./ForbiddenError" type PreviewTokenExpiredErrorAPIResponse = { - type: "api_security_error"; - message: string; -}; + type: "api_security_error" + message: string +} // This error extends `ForbiddenError` for backwards compatibility. // TODO: Extend this error from `PrismicError` in v8. diff --git a/src/errors/PrismicError.ts b/src/errors/PrismicError.ts index 0c31885a..402884d6 100644 --- a/src/errors/PrismicError.ts +++ b/src/errors/PrismicError.ts @@ -1,15 +1,15 @@ export class PrismicError extends Error { - url?: string; - response: Response; + url?: string + response: Response constructor( message = "An invalid API response was returned", url: string | undefined, response: Response, ) { - super(message); + super(message) - this.url = url; - this.response = response; + this.url = url + this.response = response } } diff --git a/src/errors/PrismicRichTextSerializerError.ts b/src/errors/PrismicRichTextSerializerError.ts index fc67c3a8..155fb648 100644 --- a/src/errors/PrismicRichTextSerializerError.ts +++ b/src/errors/PrismicRichTextSerializerError.ts @@ -1,3 +1,3 @@ -import { PrismicRichTextError } from "./PrismicRichTextError"; +import { PrismicRichTextError } from "./PrismicRichTextError" export class PrismicRichTextSerializerError extends PrismicRichTextError {} diff --git a/src/errors/RefExpiredError.ts b/src/errors/RefExpiredError.ts index b86f5a2f..2f456ddb 100644 --- a/src/errors/RefExpiredError.ts +++ b/src/errors/RefExpiredError.ts @@ -1,9 +1,9 @@ -import { ForbiddenError } from "./ForbiddenError"; +import { ForbiddenError } from "./ForbiddenError" type RefExpiredErrorAPIResponse = { - type: "api_validation_error"; - message: string; -}; + type: "api_validation_error" + message: string +} // This error extends `ForbiddenError` for backwards compatibility. Before the // API started returning 410 for expired refs, it returnd 403, which threw a diff --git a/src/errors/RefNotFoundError.ts b/src/errors/RefNotFoundError.ts index 2f0cce01..edfae12e 100644 --- a/src/errors/RefNotFoundError.ts +++ b/src/errors/RefNotFoundError.ts @@ -1,9 +1,9 @@ -import { ForbiddenError } from "./ForbiddenError"; +import { ForbiddenError } from "./ForbiddenError" type RefNotFoundErrorAPIResponse = { - type: "api_notfound_error"; - message: string; -}; + type: "api_notfound_error" + message: string +} // This error extends `ForbiddenError` for backwards compatibility. Before the // API started returning 404 for not found refs, it returnd 403, which threw a diff --git a/src/errors/RepositoryNotFoundError.ts b/src/errors/RepositoryNotFoundError.ts index 60d1af44..1318b34b 100644 --- a/src/errors/RepositoryNotFoundError.ts +++ b/src/errors/RepositoryNotFoundError.ts @@ -1,4 +1,4 @@ -import { NotFoundError } from "./NotFoundError"; +import { NotFoundError } from "./NotFoundError" export class RepositoryNotFoundError< TResponse = undefined, diff --git a/src/filter.ts b/src/filter.ts index 45916892..afa58eb1 100644 --- a/src/filter.ts +++ b/src/filter.ts @@ -15,19 +15,19 @@ const formatValue = ( | (string | number | Date | unknown)[], ): string => { if (Array.isArray(value)) { - return `[${value.map(formatValue).join(", ")}]`; + return `[${value.map(formatValue).join(", ")}]` } if (typeof value === "string") { - return `"${value}"`; + return `"${value}"` } if (value instanceof Date) { - return `${value.getTime()}`; + return `${value.getTime()}` } - return `${value}`; -}; + return `${value}` +} /** * Creates a filter builder function for filters with a path and arguments. @@ -43,14 +43,14 @@ const pathWithArgsFilter = (name: string) => { * @param path - Path to the value to be compared. */ const fn = (path: string, ...args: Args): string => { - const formattedArgs = args.map(formatValue).join(", "); - const joiner = path && args.length ? ", " : ""; + const formattedArgs = args.map(formatValue).join(", ") + const joiner = path && args.length ? ", " : "" - return `[${name}(${path}${joiner}${formattedArgs})]`; - }; + return `[${name}(${path}${joiner}${formattedArgs})]` + } - return fn; -}; + return fn +} /** * Creates a filter builder function for filters with only a path. @@ -60,17 +60,17 @@ const pathWithArgsFilter = (name: string) => { * @returns Filter builder function for the given name. */ const pathFilter = (name: string) => { - const filterFn = pathWithArgsFilter(name); + const filterFn = pathWithArgsFilter(name) /** * @param path - Path for the filter. */ const fn = (path: string): string => { - return filterFn(path); - }; + return filterFn(path) + } - return fn; -}; + return fn +} /** * Creates a filter builder function for filters with only arguments and no @@ -81,17 +81,17 @@ const pathFilter = (name: string) => { * @returns Filter builder function for the given name. */ const argsFilter = (name: string) => { - const filterFn = pathWithArgsFilter(name); + const filterFn = pathWithArgsFilter(name) /** * @param args - Arguments for the filter. */ const fn = (...args: Args): string => { - return filterFn("", ...args); - }; + return filterFn("", ...args) + } - return fn; -}; + return fn +} export const filter = { /** @@ -353,4 +353,4 @@ export const filter = { * {@link https://prismic.io/docs/rest-api-technical-reference#date-filters} */ dateHourBefore: pathWithArgsFilter<[hour: number]>("date.hour-before"), -}; +} diff --git a/src/getGraphQLEndpoint.ts b/src/getGraphQLEndpoint.ts index 3551e725..7396b4b8 100644 --- a/src/getGraphQLEndpoint.ts +++ b/src/getGraphQLEndpoint.ts @@ -1,6 +1,6 @@ -import { PrismicError } from "./errors/PrismicError"; +import { PrismicError } from "./errors/PrismicError" -import { isRepositoryName } from "./isRepositoryName"; +import { isRepositoryName } from "./isRepositoryName" /** * Get a repository's Prismic GraphQL endpoint. @@ -15,12 +15,12 @@ export const getGraphQLEndpoint = ( repositoryName: RepositoryName, ): `https://${RepositoryName}.cdn.prismic.io/graphql` => { if (isRepositoryName(repositoryName)) { - return `https://${repositoryName}.cdn.prismic.io/graphql` as const; + return `https://${repositoryName}.cdn.prismic.io/graphql` as const } else { throw new PrismicError( `An invalid Prismic repository name was given: ${repositoryName}`, undefined, undefined, - ); + ) } -}; +} diff --git a/src/getRepositoryEndpoint.ts b/src/getRepositoryEndpoint.ts index 4651b759..6109dc6c 100644 --- a/src/getRepositoryEndpoint.ts +++ b/src/getRepositoryEndpoint.ts @@ -1,6 +1,6 @@ -import { PrismicError } from "./errors/PrismicError"; +import { PrismicError } from "./errors/PrismicError" -import { isRepositoryName } from "./isRepositoryName"; +import { isRepositoryName } from "./isRepositoryName" /** * Get a repository's Prismic Rest API V2 endpoint. @@ -17,12 +17,12 @@ export const getRepositoryEndpoint = ( repositoryName: RepositoryName, ): `https://${RepositoryName}.cdn.prismic.io/api/v2` => { if (isRepositoryName(repositoryName)) { - return `https://${repositoryName}.cdn.prismic.io/api/v2` as const; + return `https://${repositoryName}.cdn.prismic.io/api/v2` as const } else { throw new PrismicError( `An invalid Prismic repository name was given: ${repositoryName}`, undefined, undefined, - ); + ) } -}; +} diff --git a/src/getRepositoryName.ts b/src/getRepositoryName.ts index 59305f4f..08f16998 100644 --- a/src/getRepositoryName.ts +++ b/src/getRepositoryName.ts @@ -1,4 +1,4 @@ -import { PrismicError } from "./errors/PrismicError"; +import { PrismicError } from "./errors/PrismicError" /** * Get a Prismic repository's name from its standard Prismic Rest API V2 or @@ -16,12 +16,12 @@ import { PrismicError } from "./errors/PrismicError"; */ export const getRepositoryName = (repositoryEndpoint: string): string => { try { - return new URL(repositoryEndpoint).hostname.split(".")[0]; + return new URL(repositoryEndpoint).hostname.split(".")[0] } catch { throw new PrismicError( `An invalid Prismic Rest API V2 endpoint was provided: ${repositoryEndpoint}`, undefined, undefined, - ); + ) } -}; +} diff --git a/src/getToolbarSrc.ts b/src/getToolbarSrc.ts index 5529b178..1200232f 100644 --- a/src/getToolbarSrc.ts +++ b/src/getToolbarSrc.ts @@ -1,6 +1,6 @@ -import { PrismicError } from "./errors/PrismicError"; +import { PrismicError } from "./errors/PrismicError" -import { isRepositoryName } from "./isRepositoryName"; +import { isRepositoryName } from "./isRepositoryName" /** * Returns the URL for a Prismic repository's Prismic Toolbar script. Use the @@ -39,12 +39,12 @@ export const getToolbarSrc = ( repositoryName: TRepositoryName, ): `https://static.cdn.prismic.io/prismic.js?new=true&repo=${TRepositoryName}` => { if (isRepositoryName(repositoryName)) { - return `https://static.cdn.prismic.io/prismic.js?new=true&repo=${repositoryName}` as const; + return `https://static.cdn.prismic.io/prismic.js?new=true&repo=${repositoryName}` as const } else { throw new PrismicError( `An invalid Prismic repository name was given: ${repositoryName}`, undefined, undefined, - ); + ) } -}; +} diff --git a/src/helpers/asDate.ts b/src/helpers/asDate.ts index f8bd7f1a..3666cd91 100644 --- a/src/helpers/asDate.ts +++ b/src/helpers/asDate.ts @@ -1,12 +1,12 @@ -import type { DateField } from "../types/value/date"; -import type { TimestampField } from "../types/value/timestamp"; +import type { DateField } from "../types/value/date" +import type { TimestampField } from "../types/value/timestamp" /** * The return type of `asDate()`. */ type AsDateReturnType< Field extends DateField | TimestampField | null | undefined, -> = Field extends DateField<"filled"> | TimestampField<"filled"> ? Date : null; +> = Field extends DateField<"filled"> | TimestampField<"filled"> ? Date : null /** * Transforms a date or timestamp field into a JavaScript Date object @@ -23,7 +23,7 @@ export const asDate = < dateOrTimestampField: Field, ): AsDateReturnType => { if (!dateOrTimestampField) { - return null as AsDateReturnType; + return null as AsDateReturnType } // If field is a timestamp field... @@ -41,9 +41,9 @@ export const asDate = < */ return new Date( dateOrTimestampField.replace(/(\+|-)(\d{2})(\d{2})$/, ".000$1$2:$3"), - ) as AsDateReturnType; + ) as AsDateReturnType } else { // ...else field is a date field - return new Date(dateOrTimestampField) as AsDateReturnType; + return new Date(dateOrTimestampField) as AsDateReturnType } -}; +} diff --git a/src/helpers/asHTML.ts b/src/helpers/asHTML.ts index 3369a994..becd441a 100644 --- a/src/helpers/asHTML.ts +++ b/src/helpers/asHTML.ts @@ -5,20 +5,18 @@ import { serializePreFormatted, serializeSpan, serializeStandardTag, -} from "../lib/serializerHelpers"; +} from "../lib/serializerHelpers" -import type { RichTextField } from "../types/value/richText"; +import type { RichTextField } from "../types/value/richText" -import { +import type { RichTextFunctionSerializer, RichTextMapSerializer, RichTextMapSerializerFunction, - composeSerializers, - serialize, - wrapMapSerializer, -} from "../richtext"; +} from "../richtext" +import { composeSerializers, serialize, wrapMapSerializer } from "../richtext" -import { LinkResolverFunction } from "./asLink"; +import type { LinkResolverFunction } from "./asLink" /** * Serializes a node from a rich text or title field with a function to HTML. @@ -35,7 +33,7 @@ export type HTMLRichTextFunctionSerializer = ( text: Parameters>[2], children: Parameters>[3][number], key: Parameters>[4], -) => string | null | undefined; +) => string | null | undefined /** * Serializes a node from a rich text or title field with a map to HTML @@ -49,8 +47,8 @@ export type HTMLRichTextFunctionSerializer = ( export type HTMLRichTextMapSerializer = { [P in keyof RichTextMapSerializer]: P extends RichTextMapSerializer["span"] ? HTMLStrictRichTextMapSerializer[P] - : HTMLStrictRichTextMapSerializer[P] | HTMLRichTextMapSerializerShorthand; -}; + : HTMLStrictRichTextMapSerializer[P] | HTMLRichTextMapSerializerShorthand +} /** * Serializes a node from a rich text or title field with a map to HTML @@ -63,15 +61,15 @@ export type HTMLRichTextMapSerializer = { */ export type HTMLStrictRichTextMapSerializer = { [P in keyof RichTextMapSerializer]: (payload: { - type: Parameters>[0]["type"]; - node: Parameters>[0]["node"]; - text: Parameters>[0]["text"]; + type: Parameters>[0]["type"] + node: Parameters>[0]["node"] + text: Parameters>[0]["text"] children: Parameters< HTMLRichTextMapSerializerFunction

- >[0]["children"][number]; - key: Parameters>[0]["key"]; - }) => string | null | undefined; -}; + >[0]["children"][number] + key: Parameters>[0]["key"] + }) => string | null | undefined +} /** * A {@link RichTextMapSerializerFunction} type specifically for @@ -85,7 +83,7 @@ type HTMLRichTextMapSerializerFunction< string, ExtractNodeGeneric[BlockType]>, ExtractTextTypeGeneric[BlockType]> ->; +> /** * Returns the `Node` generic from {@link RichTextMapSerializerFunction}. @@ -102,7 +100,7 @@ type ExtractNodeGeneric = any > ? U - : never; + : never /** * Returns the `TextType` generic from {@link RichTextMapSerializerFunction}. @@ -119,7 +117,7 @@ type ExtractTextTypeGeneric = infer U > ? U - : never; + : never /** * A shorthand definition for {@link HTMLRichTextMapSerializer} element types. @@ -128,13 +126,13 @@ export type HTMLRichTextMapSerializerShorthand = { /** * Classes to apply to the element type. */ - class?: string; + class?: string /** * Other attributes to apply to the element type. */ - [Attribute: string]: string | boolean | null | undefined; -}; + [Attribute: string]: string | boolean | null | undefined +} /** * Serializes a node from a rich text or title field with a map or a function to @@ -145,7 +143,7 @@ export type HTMLRichTextMapSerializerShorthand = { */ export type HTMLRichTextSerializer = | HTMLRichTextMapSerializer - | HTMLRichTextFunctionSerializer; + | HTMLRichTextFunctionSerializer /** * Creates a HTML rich text serializer with a given link resolver and provide @@ -171,12 +169,12 @@ const createHTMLRichTextSerializer = ( ( nodeSerializerOrShorthand as HTMLStrictRichTextMapSerializer[BlockType] )?.(payload) || defaultWithShorthand(payload) - ); - }) as NonNullable; + ) + }) as NonNullable } - return defaultWithShorthand; - }; + return defaultWithShorthand + } const mapSerializer: Required = { heading1: useSerializerOrDefault<"heading1">( @@ -252,10 +250,10 @@ const createHTMLRichTextSerializer = ( serializeStandardTag<"label">("span", serializer?.label), ), span: useSerializerOrDefault<"span">(serializer?.span, serializeSpan()), - }; + } - return wrapMapSerializerWithStringChildren(mapSerializer); -}; + return wrapMapSerializerWithStringChildren(mapSerializer) +} /** * Wraps a map serializer into a regular function serializer. The given map @@ -269,10 +267,10 @@ const createHTMLRichTextSerializer = ( const wrapMapSerializerWithStringChildren = ( mapSerializer: HTMLStrictRichTextMapSerializer, ): RichTextFunctionSerializer => { - const modifiedMapSerializer = {} as RichTextMapSerializer; + const modifiedMapSerializer = {} as RichTextMapSerializer for (const tag in mapSerializer) { - const tagSerializer = mapSerializer[tag as keyof typeof mapSerializer]; + const tagSerializer = mapSerializer[tag as keyof typeof mapSerializer] if (tagSerializer) { modifiedMapSerializer[tag as keyof typeof mapSerializer] = (payload) => { @@ -280,13 +278,13 @@ const wrapMapSerializerWithStringChildren = ( ...payload, // @ts-expect-error - merging blockSerializer types causes TS to bail to a never type children: payload.children.join(""), - }); - }; + }) + } } } - return wrapMapSerializer(modifiedMapSerializer); -}; + return wrapMapSerializer(modifiedMapSerializer) +} /** * Configuration that determines the output of `asHTML()`. @@ -296,14 +294,14 @@ type AsHTMLConfig = { * An optional link resolver function to resolve links. Without it you're * expected to use the `routes` options from the API. */ - linkResolver?: LinkResolverFunction | null; + linkResolver?: LinkResolverFunction | null /** * An optional rich text serializer, unhandled cases will fallback to the * default serializer */ - serializer?: HTMLRichTextSerializer | null; -}; + serializer?: HTMLRichTextSerializer | null +} // TODO: Remove when we remove support for deprecated tuple-style configuration. /** @@ -312,13 +310,13 @@ type AsHTMLConfig = { type AsHTMLDeprecatedTupleConfig = [ linkResolver?: LinkResolverFunction | null, serializer?: HTMLRichTextSerializer | null, -]; +] /** * The return type of `asHTML()`. */ type AsHTMLReturnType = - Field extends RichTextField ? string : null; + Field extends RichTextField ? string : null // TODO: Remove overload when we remove support for deprecated tuple-style configuration. export const asHTML: { @@ -335,7 +333,7 @@ export const asHTML: { ( richTextField: Field, config?: AsHTMLConfig, - ): AsHTMLReturnType; + ): AsHTMLReturnType /** * Serializes a rich text or title field to an HTML string. @@ -355,7 +353,7 @@ export const asHTML: { ( richTextField: Field, ...config: AsHTMLDeprecatedTupleConfig - ): AsHTMLReturnType; + ): AsHTMLReturnType } = ( richTextField: Field, // TODO: Rename to `config` when we remove support for deprecated tuple-style configuration. @@ -363,8 +361,8 @@ export const asHTML: { ): AsHTMLReturnType => { if (richTextField) { // TODO: Remove when we remove support for deprecated tuple-style configuration. - const [configObjectOrLinkResolver, maybeSerializer] = configObjectOrTuple; - let config: AsHTMLConfig; + const [configObjectOrLinkResolver, maybeSerializer] = configObjectOrTuple + let config: AsHTMLConfig if ( typeof configObjectOrLinkResolver === "function" || configObjectOrLinkResolver == null @@ -372,12 +370,12 @@ export const asHTML: { config = { linkResolver: configObjectOrLinkResolver, serializer: maybeSerializer, - }; + } } else { - config = { ...configObjectOrLinkResolver }; + config = { ...configObjectOrLinkResolver } } - let serializer: RichTextFunctionSerializer; + let serializer: RichTextFunctionSerializer if (config.serializer) { if (typeof config.serializer === "function") { serializer = composeSerializers( @@ -391,21 +389,21 @@ export const asHTML: { key, ), createHTMLRichTextSerializer(config.linkResolver), - ); + ) } else { serializer = createHTMLRichTextSerializer( config.linkResolver, config.serializer, - ); + ) } } else { - serializer = createHTMLRichTextSerializer(config.linkResolver); + serializer = createHTMLRichTextSerializer(config.linkResolver) } return serialize(richTextField, serializer).join( "", - ) as AsHTMLReturnType; + ) as AsHTMLReturnType } else { - return null as AsHTMLReturnType; + return null as AsHTMLReturnType } -}; +} diff --git a/src/helpers/asImagePixelDensitySrcSet.ts b/src/helpers/asImagePixelDensitySrcSet.ts index 56afbde2..fd8721a1 100644 --- a/src/helpers/asImagePixelDensitySrcSet.ts +++ b/src/helpers/asImagePixelDensitySrcSet.ts @@ -1,17 +1,14 @@ -import { - BuildPixelDensitySrcSetParams, - buildPixelDensitySrcSet, - buildURL, -} from "imgix-url-builder"; +import type { BuildPixelDensitySrcSetParams } from "imgix-url-builder" +import { buildPixelDensitySrcSet, buildURL } from "imgix-url-builder" -import type { ImageFieldImage } from "../types/value/image"; +import type { ImageFieldImage } from "../types/value/image" -import { imageThumbnail as isImageThumbnailFilled } from "./isFilled"; +import { imageThumbnail as isImageThumbnailFilled } from "./isFilled" /** * The default pixel densities used to generate a `srcset` value. */ -const DEFAULT_PIXEL_DENSITIES = [1, 2, 3]; +const DEFAULT_PIXEL_DENSITIES = [1, 2, 3] /** * Configuration for `asImagePixelDensitySrcSet()`. @@ -20,7 +17,7 @@ type AsImagePixelDensitySrcSetConfig = Omit< BuildPixelDensitySrcSetParams, "pixelDensities" > & - Partial>; + Partial> /** * The return type of `asImagePixelDensitySrcSet()`. @@ -33,15 +30,15 @@ type AsImagePixelDensitySrcSetReturnType< /** * The image field's image URL with Imgix URL parameters (if given). */ - src: string; + src: string /** * A pixel-densitye-based `srcset` attribute value for the image field's * image with Imgix URL parameters (if given). */ - srcset: string; + srcset: string } - : null; + : null /** * Creates a pixel-density-based `srcset` from an image field with optional @@ -56,7 +53,7 @@ type AsImagePixelDensitySrcSetReturnType< * const srcset = asImagePixelDensitySrcSet(document.data.imageField, { * pixelDensities: [1, 2], * sat: -100, - * }); + * }) * // => { * // src: 'https://images.prismic.io/repo/image.png?sat=-100', * // srcset: 'https://images.prismic.io/repo/image.png?sat=-100&dpr=1 1x, ' + @@ -83,7 +80,7 @@ export const asImagePixelDensitySrcSet = < if (field && isImageThumbnailFilled(field)) { // We are using destructuring to omit `pixelDensities` from the // object we will pass to `buildURL()`. - const { pixelDensities = DEFAULT_PIXEL_DENSITIES, ...imgixParams } = config; + const { pixelDensities = DEFAULT_PIXEL_DENSITIES, ...imgixParams } = config return { src: buildURL(field.url, imgixParams), @@ -91,8 +88,8 @@ export const asImagePixelDensitySrcSet = < ...imgixParams, pixelDensities, }), - } as AsImagePixelDensitySrcSetReturnType; + } as AsImagePixelDensitySrcSetReturnType } else { - return null as AsImagePixelDensitySrcSetReturnType; + return null as AsImagePixelDensitySrcSetReturnType } -}; +} diff --git a/src/helpers/asImageSrc.ts b/src/helpers/asImageSrc.ts index 25edaa53..9a074457 100644 --- a/src/helpers/asImageSrc.ts +++ b/src/helpers/asImageSrc.ts @@ -1,14 +1,15 @@ -import { ImgixURLParams, buildURL } from "imgix-url-builder"; +import type { ImgixURLParams } from "imgix-url-builder" +import { buildURL } from "imgix-url-builder" -import type { ImageFieldImage } from "../types/value/image"; +import type { ImageFieldImage } from "../types/value/image" -import { imageThumbnail as isImageThumbnailFilled } from "./isFilled"; +import { imageThumbnail as isImageThumbnailFilled } from "./isFilled" /** * The return type of `asImageSrc()`. */ type AsImageSrcReturnType = - Field extends ImageFieldImage<"filled"> ? string : null; + Field extends ImageFieldImage<"filled"> ? string : null /** * Returns the URL of an image field with optional image transformations (via @@ -17,7 +18,7 @@ type AsImageSrcReturnType = * @example * * ```ts - * const src = asImageSrc(document.data.imageField, { sat: -100 }); + * const src = asImageSrc(document.data.imageField, { sat: -100 }) * // => https://images.prismic.io/repo/image.png?sat=-100 * ``` * @@ -35,8 +36,8 @@ export const asImageSrc = ( config: ImgixURLParams = {}, ): AsImageSrcReturnType => { if (field && isImageThumbnailFilled(field)) { - return buildURL(field.url, config) as AsImageSrcReturnType; + return buildURL(field.url, config) as AsImageSrcReturnType } else { - return null as AsImageSrcReturnType; + return null as AsImageSrcReturnType } -}; +} diff --git a/src/helpers/asImageWidthSrcSet.ts b/src/helpers/asImageWidthSrcSet.ts index d591a32c..f59e1109 100644 --- a/src/helpers/asImageWidthSrcSet.ts +++ b/src/helpers/asImageWidthSrcSet.ts @@ -1,17 +1,14 @@ -import { - BuildWidthSrcSetParams, - buildURL, - buildWidthSrcSet, -} from "imgix-url-builder"; +import type { BuildWidthSrcSetParams } from "imgix-url-builder" +import { buildURL, buildWidthSrcSet } from "imgix-url-builder" -import type { ImageFieldImage } from "../types/value/image"; +import type { ImageFieldImage } from "../types/value/image" -import * as isFilled from "./isFilled"; +import * as isFilled from "./isFilled" /** * The default widths used to generate a `srcset` value. */ -const DEFAULT_WIDTHS = [640, 828, 1200, 2048, 3840]; +const DEFAULT_WIDTHS = [640, 828, 1200, 2048, 3840] /** * The return type of `asImageWidthSrcSet()`. @@ -24,22 +21,22 @@ type AsImageWidthSrcSetReturnType< /** * The image field's image URL with Imgix URL parameters (if given). */ - src: string; + src: string /** * A width-based `srcset` attribute value for the image field's image * with Imgix URL parameters (if given). */ - srcset: string; + srcset: string } - : null; + : null /** * Configuration for `asImageWidthSrcSet()`. */ type AsImageWidthSrcSetConfig = Omit & { - widths?: "thumbnails" | BuildWidthSrcSetParams["widths"]; -}; + widths?: "thumbnails" | BuildWidthSrcSetParams["widths"] +} /** * Creates a width-based `srcset` from an image field with optional image @@ -58,7 +55,7 @@ type AsImageWidthSrcSetConfig = Omit & { * const srcset = asImageWidthSrcSet(document.data.imageField, { * widths: [400, 800, 1600], * sat: -100, - * }); + * }) * // => { * // src: 'https://images.prismic.io/repo/image.png?sat=-100', * // srcset: 'https://images.prismic.io/repo/image.png?sat=-100&width=400 400w, ' + @@ -91,7 +88,7 @@ export const asImageWidthSrcSet = < widths = DEFAULT_WIDTHS, // eslint-disable-next-line prefer-const ...imgixParams - } = config; + } = config const { url, dimensions, @@ -100,18 +97,18 @@ export const asImageWidthSrcSet = < copyright: _copyright, edit: _edit, ...responsiveViews - } = field; + } = field // The Prismic Rest API will always return thumbnail values if // the base size is filled. const responsiveViewObjects: ImageFieldImage<"filled">[] = - Object.values(responsiveViews); + Object.values(responsiveViews) // If this `asImageWidthSrcSet()` call is configured to use // thumbnail widths, but the field does not have thumbnails, we // fall back to the default set of widths. if (widths === "thumbnails" && responsiveViewObjects.length < 1) { - widths = DEFAULT_WIDTHS; + widths = DEFAULT_WIDTHS } return { @@ -129,15 +126,15 @@ export const asImageWidthSrcSet = < return buildWidthSrcSet(thumbnail.url, { ...imgixParams, widths: [thumbnail.dimensions.width], - }); + }) }), ].join(", ") : buildWidthSrcSet(field.url, { ...imgixParams, widths, }), - } as AsImageWidthSrcSetReturnType; + } as AsImageWidthSrcSetReturnType } else { - return null as AsImageWidthSrcSetReturnType; + return null as AsImageWidthSrcSetReturnType } -}; +} diff --git a/src/helpers/asLink.ts b/src/helpers/asLink.ts index 7924218d..c16975a9 100644 --- a/src/helpers/asLink.ts +++ b/src/helpers/asLink.ts @@ -1,9 +1,10 @@ -import type { FilledContentRelationshipField } from "../types/value/contentRelationship"; -import type { PrismicDocument } from "../types/value/document"; -import { FilledLinkToWebField, LinkField, LinkType } from "../types/value/link"; -import type { FilledLinkToMediaField } from "../types/value/linkToMedia"; +import type { FilledContentRelationshipField } from "../types/value/contentRelationship" +import type { PrismicDocument } from "../types/value/document" +import type { FilledLinkToWebField, LinkField } from "../types/value/link" +import { LinkType } from "../types/value/link" +import type { FilledLinkToMediaField } from "../types/value/linkToMedia" -import { documentToLinkField } from "./documentToLinkField"; +import { documentToLinkField } from "./documentToLinkField" /** * Resolves a link to a Prismic document to a URL @@ -19,7 +20,7 @@ import { documentToLinkField } from "./documentToLinkField"; */ export type LinkResolverFunction = ( linkToDocumentField: FilledContentRelationshipField, -) => ReturnType; +) => ReturnType /** * Configuration that determines the output of `asLink()`. @@ -30,8 +31,8 @@ type AsLinkConfig = * An optional link resolver function. Without it, you are expected to use * the `routes` options from the API. */ - linkResolver?: LinkResolverFunction | null; - }; + linkResolver?: LinkResolverFunction | null + } // TODO: Remove when we remove support for deprecated tuple-style configuration. /** @@ -39,9 +40,7 @@ type AsLinkConfig = */ type AsLinkDeprecatedTupleConfig< LinkResolverFunctionReturnType = string | null | undefined, -> = [ - linkResolver?: LinkResolverFunction | null, -]; +> = [linkResolver?: LinkResolverFunction | null] /** * The return type of `asLink()`. @@ -59,7 +58,7 @@ export type AsLinkReturnType< | FilledContentRelationshipField | PrismicDocument ? LinkResolverFunctionReturnType | string | null - : null; + : null // TODO: Remove overload when we remove support for deprecated tuple-style configuration. export const asLink: { @@ -90,7 +89,7 @@ export const asLink: { >( linkFieldOrDocument: Field, config?: AsLinkConfig, - ): AsLinkReturnType; + ): AsLinkReturnType /** * Resolves any type of link field or Prismic document to a URL. @@ -122,7 +121,7 @@ export const asLink: { >( linkFieldOrDocument: Field, ...config: AsLinkDeprecatedTupleConfig - ): AsLinkReturnType; + ): AsLinkReturnType } = < LinkResolverFunctionReturnType = string | null | undefined, Field extends LinkField | PrismicDocument | null | undefined = @@ -138,7 +137,7 @@ export const asLink: { | AsLinkDeprecatedTupleConfig ): AsLinkReturnType => { if (!linkFieldOrDocument) { - return null as AsLinkReturnType; + return null as AsLinkReturnType } // Converts document to link field if needed @@ -151,20 +150,20 @@ export const asLink: { "link_type" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument) - ) as LinkField; + ) as LinkField // TODO: Remove when we remove support for deprecated tuple-style configuration. - const [configObjectOrLinkResolver] = configObjectOrTuple; - let config: AsLinkConfig; + const [configObjectOrLinkResolver] = configObjectOrTuple + let config: AsLinkConfig if ( typeof configObjectOrLinkResolver === "function" || configObjectOrLinkResolver == null ) { config = { linkResolver: configObjectOrLinkResolver, - }; + } } else { - config = { ...configObjectOrLinkResolver }; + config = { ...configObjectOrLinkResolver } } switch (linkField.link_type) { @@ -173,18 +172,18 @@ export const asLink: { return ("url" in linkField ? linkField.url : null) as AsLinkReturnType< LinkResolverFunctionReturnType, Field - >; + > case LinkType.Document: { if ("id" in linkField && config.linkResolver) { // When using link resolver... - const resolvedURL = config.linkResolver(linkField); + const resolvedURL = config.linkResolver(linkField) if (resolvedURL != null) { return resolvedURL as AsLinkReturnType< LinkResolverFunctionReturnType, Field - >; + > } } @@ -193,15 +192,15 @@ export const asLink: { return linkField.url as AsLinkReturnType< LinkResolverFunctionReturnType, Field - >; + > } // When empty or link resolver and route resolver are not used... - return null as AsLinkReturnType; + return null as AsLinkReturnType } case LinkType.Any: default: - return null as AsLinkReturnType; + return null as AsLinkReturnType } -}; +} diff --git a/src/helpers/asLinkAttrs.ts b/src/helpers/asLinkAttrs.ts index f61e3922..74d640eb 100644 --- a/src/helpers/asLinkAttrs.ts +++ b/src/helpers/asLinkAttrs.ts @@ -1,12 +1,13 @@ -import { isInternalURL } from "../lib/isInternalURL"; +import { isInternalURL } from "../lib/isInternalURL" -import type { FilledContentRelationshipField } from "../types/value/contentRelationship"; -import type { PrismicDocument } from "../types/value/document"; -import { FilledLinkToWebField, LinkField } from "../types/value/link"; -import type { FilledLinkToMediaField } from "../types/value/linkToMedia"; +import type { FilledContentRelationshipField } from "../types/value/contentRelationship" +import type { PrismicDocument } from "../types/value/document" +import type { FilledLinkToWebField, LinkField } from "../types/value/link" +import type { FilledLinkToMediaField } from "../types/value/linkToMedia" -import { AsLinkReturnType, LinkResolverFunction, asLink } from "./asLink"; -import { link as isFilledLink } from "./isFilled"; +import type { AsLinkReturnType, LinkResolverFunction } from "./asLink" +import { asLink } from "./asLink" +import { link as isFilledLink } from "./isFilled" type AsLinkAttrsConfigRelArgs< LinkResolverFunctionReturnType = ReturnType, @@ -18,10 +19,10 @@ type AsLinkAttrsConfigRelArgs< > = { href: | NonNullable> - | undefined; - isExternal: boolean; - target?: string; -}; + | undefined + isExternal: boolean + target?: string +} export type AsLinkAttrsConfig< LinkResolverFunctionReturnType = ReturnType, @@ -31,11 +32,11 @@ export type AsLinkAttrsConfig< | null | undefined, > = { - linkResolver?: LinkResolverFunction; + linkResolver?: LinkResolverFunction rel?: ( args: AsLinkAttrsConfigRelArgs, - ) => string | undefined | void; -}; + ) => string | undefined | void +} /** * The return type of `asLinkAttrs()`. @@ -55,15 +56,15 @@ type AsLinkAttrsReturnType< ? { href: | NonNullable> - | undefined; - target?: string; - rel?: string; + | undefined + target?: string + rel?: string } : { - href?: undefined; - target?: undefined; - rel?: undefined; - }; + href?: undefined + target?: undefined + rel?: undefined + } /** * Resolves any type of link field or Prismic document to a set of link @@ -109,26 +110,26 @@ export const asLinkAttrs = < const target = // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501 - "target" in linkFieldOrDocument ? linkFieldOrDocument.target : undefined; + "target" in linkFieldOrDocument ? linkFieldOrDocument.target : undefined - const rawHref = asLink(linkFieldOrDocument, config.linkResolver); + const rawHref = asLink(linkFieldOrDocument, config.linkResolver) const href = - rawHref == null ? undefined : (rawHref as NonNullable); + rawHref == null ? undefined : (rawHref as NonNullable) - const isExternal = typeof href === "string" ? !isInternalURL(href) : false; + const isExternal = typeof href === "string" ? !isInternalURL(href) : false const rel = config.rel ? config.rel({ href, isExternal, target }) : isExternal ? "noreferrer" - : undefined; + : undefined return { href, target, rel: rel == null ? undefined : rel, - }; + } } - return {}; -}; + return {} +} diff --git a/src/helpers/asText.ts b/src/helpers/asText.ts index d787fc81..f763cd67 100644 --- a/src/helpers/asText.ts +++ b/src/helpers/asText.ts @@ -1,6 +1,6 @@ -import { RichTextField } from "../types/value/richText"; +import type { RichTextField } from "../types/value/richText" -import { asText as baseAsText } from "../richtext/asText"; +import { asText as baseAsText } from "../richtext/asText" /** * Configuration that determines the output of `asText()`. @@ -11,20 +11,20 @@ type AsTextConfig = { * * @defaultValue ` ` (a space) */ - separator?: string; -}; + separator?: string +} // TODO: Remove when we remove support for deprecated tuple-style configuration. /** * @deprecated Use object-style configuration instead. */ -type AsTextDeprecatedTupleConfig = [separator?: string]; +type AsTextDeprecatedTupleConfig = [separator?: string] /** * The return type of `asText()`. */ type AsTextReturnType = - Field extends RichTextField ? string : null; + Field extends RichTextField ? string : null export const asText: { /** @@ -40,7 +40,7 @@ export const asText: { ( richTextField: Field, config?: AsTextConfig, - ): AsTextReturnType; + ): AsTextReturnType /** * Serializes a rich text or title field to a plain text string. @@ -57,7 +57,7 @@ export const asText: { ( richTextField: Field, ...config: AsTextDeprecatedTupleConfig - ): AsTextReturnType; + ): AsTextReturnType } = ( richTextField: Field, // TODO: Rename to `config` when we remove support for deprecated tuple-style configuration. @@ -65,21 +65,21 @@ export const asText: { ): AsTextReturnType => { if (richTextField) { // TODO: Remove when we remove support for deprecated tuple-style configuration. - const [configObjectOrSeparator] = configObjectOrTuple; - let config: AsTextConfig; + const [configObjectOrSeparator] = configObjectOrTuple + let config: AsTextConfig if (typeof configObjectOrSeparator === "string") { config = { separator: configObjectOrSeparator, - }; + } } else { - config = { ...configObjectOrSeparator }; + config = { ...configObjectOrSeparator } } return baseAsText( richTextField, config.separator, - ) as AsTextReturnType; + ) as AsTextReturnType } else { - return null as AsTextReturnType; + return null as AsTextReturnType } -}; +} diff --git a/src/helpers/documentToLinkField.ts b/src/helpers/documentToLinkField.ts index 6a65fbb1..518dba58 100644 --- a/src/helpers/documentToLinkField.ts +++ b/src/helpers/documentToLinkField.ts @@ -1,9 +1,9 @@ -import type { FilledContentRelationshipField } from "../types/value/contentRelationship"; -import type { PrismicDocument } from "../types/value/document"; -import { LinkType } from "../types/value/link"; +import type { FilledContentRelationshipField } from "../types/value/contentRelationship" +import type { PrismicDocument } from "../types/value/document" +import { LinkType } from "../types/value/link" type SetOptional = Omit & - Partial>; + Partial> /** * Converts a document into a link field, this is useful when crawling the API @@ -45,5 +45,5 @@ export const documentToLinkField = < ...(prismicDocument.data && Object.keys(prismicDocument.data).length > 0 ? { data: prismicDocument.data } : {}), - }; -}; + } +} diff --git a/src/helpers/isFilled.ts b/src/helpers/isFilled.ts index fc7b933b..e6c454ac 100644 --- a/src/helpers/isFilled.ts +++ b/src/helpers/isFilled.ts @@ -1,23 +1,23 @@ -import type { ColorField } from "../types/value/color"; -import type { ContentRelationshipField } from "../types/value/contentRelationship"; -import type { DateField } from "../types/value/date"; -import type { AnyOEmbed, EmbedField } from "../types/value/embed"; -import type { GeoPointField } from "../types/value/geoPoint"; -import type { GroupField, NestedGroupField } from "../types/value/group"; -import type { ImageField, ImageFieldImage } from "../types/value/image"; -import type { IntegrationField } from "../types/value/integration"; -import type { KeyTextField } from "../types/value/keyText"; -import type { LinkField } from "../types/value/link"; -import type { LinkToMediaField } from "../types/value/linkToMedia"; -import type { NumberField } from "../types/value/number"; -import type { RichTextField } from "../types/value/richText"; -import type { SelectField } from "../types/value/select"; -import type { SharedSlice } from "../types/value/sharedSlice"; -import type { Slice } from "../types/value/slice"; -import type { SliceZone } from "../types/value/sliceZone"; -import type { TimestampField } from "../types/value/timestamp"; -import type { TitleField } from "../types/value/title"; -import type { AnyRegularField } from "../types/value/types"; +import type { ColorField } from "../types/value/color" +import type { ContentRelationshipField } from "../types/value/contentRelationship" +import type { DateField } from "../types/value/date" +import type { AnyOEmbed, EmbedField } from "../types/value/embed" +import type { GeoPointField } from "../types/value/geoPoint" +import type { GroupField, NestedGroupField } from "../types/value/group" +import type { ImageField, ImageFieldImage } from "../types/value/image" +import type { IntegrationField } from "../types/value/integration" +import type { KeyTextField } from "../types/value/keyText" +import type { LinkField } from "../types/value/link" +import type { LinkToMediaField } from "../types/value/linkToMedia" +import type { NumberField } from "../types/value/number" +import type { RichTextField } from "../types/value/richText" +import type { SelectField } from "../types/value/select" +import type { SharedSlice } from "../types/value/sharedSlice" +import type { Slice } from "../types/value/slice" +import type { SliceZone } from "../types/value/sliceZone" +import type { TimestampField } from "../types/value/timestamp" +import type { TitleField } from "../types/value/title" +import type { AnyRegularField } from "../types/value/types" /** * Determines if a value is not nullish (i.e. not `null` or `undefined`). This @@ -28,8 +28,8 @@ import type { AnyRegularField } from "../types/value/types"; * @returns `true` if `input` is not nullish, `false` otherwise. */ const isNonNullish = (input: T): input is NonNullable => { - return input != null; -}; + return input != null +} /** * Determines if an array is not empty. This is used to check if array-based @@ -40,8 +40,8 @@ const isNonNullish = (input: T): input is NonNullable => { * @returns `true` if `input` has at least one element, `false` otherwise. */ const isNonEmptyArray = (input: T[]): input is [T, ...T[]] => { - return !!input.length; -}; + return !!input.length +} /** * Determines if a rich text field is filled. @@ -54,13 +54,13 @@ export const richText = ( field: RichTextField | null | undefined, ): field is RichTextField<"filled"> => { if (!isNonNullish(field)) { - return false; + return false } else if (field.length === 1 && "text" in field[0]) { - return !!field[0].text; + return !!field[0].text } else { - return !!field.length; + return !!field.length } -}; +} /** * Determines if a title field is filled. @@ -71,7 +71,7 @@ export const richText = ( */ export const title = richText as ( field: TitleField | null | undefined, -) => field is TitleField<"filled">; +) => field is TitleField<"filled"> /** * Determines if an Image thumbnail is filled. @@ -83,8 +83,8 @@ export const title = richText as ( export const imageThumbnail = ( thumbnail: ImageFieldImage | null | undefined, ): thumbnail is ImageFieldImage<"filled"> => { - return isNonNullish(thumbnail) && !!thumbnail.url; -}; + return isNonNullish(thumbnail) && !!thumbnail.url +} /** * Determines if an image field is filled. @@ -97,7 +97,7 @@ export const image = imageThumbnail as < ThumbnailNames extends string | null = never, >( field: ImageField | null | undefined, -) => field is ImageField; +) => field is ImageField /** * Determines if a link field is filled. @@ -115,8 +115,8 @@ export const link = < >( field: LinkField | null | undefined, ): field is LinkField => { - return isNonNullish(field) && ("id" in field || "url" in field); -}; + return isNonNullish(field) && ("id" in field || "url" in field) +} /** * Determines if a link to media field is filled. @@ -127,7 +127,7 @@ export const link = < */ export const linkToMedia = link as ( field: LinkToMediaField | null | undefined, -) => field is LinkToMediaField<"filled">; +) => field is LinkToMediaField<"filled"> /** * Determines if a content relationship field is filled. @@ -152,7 +152,7 @@ export const contentRelationship = link as < LangEnum, DataInterface, "filled" ->; +> /** * Determines if a date field is filled. @@ -163,7 +163,7 @@ export const contentRelationship = link as < */ export const date = isNonNullish as ( field: DateField | null | undefined, -) => field is DateField<"filled">; +) => field is DateField<"filled"> /** * Determines if a timestamp field is filled. @@ -174,7 +174,7 @@ export const date = isNonNullish as ( */ export const timestamp = isNonNullish as ( field: TimestampField | null | undefined, -) => field is TimestampField<"filled">; +) => field is TimestampField<"filled"> /** * Determines if a color field is filled. @@ -185,7 +185,7 @@ export const timestamp = isNonNullish as ( */ export const color = isNonNullish as ( field: ColorField | null | undefined, -) => field is ColorField<"filled">; +) => field is ColorField<"filled"> /** * Determines if a number field is filled. @@ -196,7 +196,7 @@ export const color = isNonNullish as ( */ export const number = isNonNullish as ( field: NumberField | null | undefined, -) => field is NumberField<"filled">; +) => field is NumberField<"filled"> /** * Determines if a key text field is filled. @@ -208,8 +208,8 @@ export const number = isNonNullish as ( export const keyText = ( field: KeyTextField | null | undefined, ): field is KeyTextField<"filled"> => { - return isNonNullish(keyText) && !!field; -}; + return isNonNullish(keyText) && !!field +} /** * Determines if a select field is filled. @@ -220,7 +220,7 @@ export const keyText = ( */ export const select = isNonNullish as ( field: SelectField | null | undefined, -) => field is SelectField; +) => field is SelectField /** * Determines if an embed field is filled. @@ -232,8 +232,8 @@ export const select = isNonNullish as ( export const embed = >( field: Field | null | undefined, ): field is Extract> => { - return isNonNullish(field) && !!field.embed_url; -}; + return isNonNullish(field) && !!field.embed_url +} /** * Determines if a geopoint field is filled. @@ -245,8 +245,8 @@ export const embed = >( export const geoPoint = ( field: GeoPointField | null | undefined, ): field is GeoPointField<"filled"> => { - return isNonNullish(field) && "longitude" in field; -}; + return isNonNullish(field) && "longitude" in field +} /** * Determines if an integration field is filled. @@ -259,12 +259,12 @@ export const integrationField = isNonNullish as < Data extends Record, >( field: IntegrationField | null | undefined, -) => field is IntegrationField; +) => field is IntegrationField /** * @deprecated Renamed to `integrationField`. */ // TODO: Remove when we remove support for deprecated `integrationFields` export. -export const integrationFields = integrationField; +export const integrationFields = integrationField /** * Determines if a Group has at least one item. @@ -278,8 +278,8 @@ export const group = < >( group: GroupField | null | undefined, ): group is GroupField => { - return isNonNullish(group) && isNonEmptyArray(group); -}; + return isNonNullish(group) && isNonEmptyArray(group) +} /** * Determines if a Slice Zone has at least one Slice. @@ -291,5 +291,5 @@ export const group = < export const sliceZone = ( slices: SliceZone | null | undefined, ): slices is SliceZone => { - return isNonNullish(slices) && isNonEmptyArray(slices); -}; + return isNonNullish(slices) && isNonEmptyArray(slices) +} diff --git a/src/helpers/mapSliceZone.ts b/src/helpers/mapSliceZone.ts index 282d7d4c..1906be59 100644 --- a/src/helpers/mapSliceZone.ts +++ b/src/helpers/mapSliceZone.ts @@ -1,18 +1,18 @@ -import { Slice } from "../types/value/slice"; +import type { Slice } from "../types/value/slice" /** * Convert a value to a lazyily loaded module. This is useful when using * functions like `() => import("...")`. */ -type LazyModule = () => Promise; +type LazyModule = () => Promise /** * Mark a type as potentially lazy-loaded via a module. */ -type MaybeLazyModule = T | LazyModule; +type MaybeLazyModule = T | LazyModule // eslint-disable-next-line @typescript-eslint/no-explicit-any -type AnyFunction = (...args: any[]) => any; +type AnyFunction = (...args: any[]) => any /** * Returns the type of a `SliceLike` type. @@ -23,7 +23,7 @@ type ExtractSliceType = TSlice extends SliceLikeRestV2 ? TSlice["slice_type"] : TSlice extends SliceLikeGraphQL ? TSlice["type"] - : never; + : never /** * The minimum required properties to represent a Prismic Slice from the Prismic @@ -34,7 +34,7 @@ type ExtractSliceType = TSlice extends SliceLikeRestV2 type SliceLikeRestV2 = Pick< Slice, "id" | "slice_type" ->; +> /** * The minimum required properties to represent a Prismic Slice from the Prismic @@ -43,8 +43,8 @@ type SliceLikeRestV2 = Pick< * @typeParam SliceType - Type name of the Slice. */ type SliceLikeGraphQL = { - type: Slice["slice_type"]; -}; + type: Slice["slice_type"] +} /** * The minimum required properties to represent a Prismic Slice for the @@ -57,7 +57,7 @@ type SliceLikeGraphQL = { */ type SliceLike = | SliceLikeRestV2 - | SliceLikeGraphQL; + | SliceLikeGraphQL /** * A looser version of the `SliceZone` type from `@prismicio/client` using @@ -68,7 +68,7 @@ type SliceLike = * * @typeParam TSlice - The type(s) of a Slice in the Slice Zone. */ -type SliceZoneLike = readonly TSlice[]; +type SliceZoneLike = readonly TSlice[] /** * A set of properties that identify a Slice as having been mapped. Consumers of @@ -82,8 +82,8 @@ type MappedSliceLike = { * * @internal */ - __mapped: true; -}; + __mapped: true +} /** * Arguments for a function mapping content from a Prismic Slice using the @@ -100,12 +100,12 @@ type SliceMapperArgs< /** * Slice data. */ - slice: TSlice; + slice: TSlice /** * The index of the Slice in the Slice Zone. */ - index: number; + index: number /** * All Slices from the Slice Zone to which the Slice belongs. @@ -116,14 +116,14 @@ type SliceMapperArgs< // throw a compilation error. slices: SliceZoneLike< TSlice extends SliceLikeGraphQL ? SliceLikeGraphQL : SliceLikeRestV2 - >; + > /** * Arbitrary data passed to `mapSliceZone()` and made available to all Slice * mappers. */ - context: TContext; -}; + context: TContext +} /** * A record of mappers. @@ -136,8 +136,8 @@ type SliceMappers = { any, TContext > - >; -}; + > +} /** * A function that maps a Slice and its metadata to a modified version. The @@ -152,7 +152,7 @@ export type SliceMapper< TContext = unknown, > = ( args: SliceMapperArgs, -) => TMappedSlice | Promise; +) => TMappedSlice | Promise /** * Unwraps a lazily loaded mapper module. @@ -163,11 +163,11 @@ type ResolveLazySliceMapperModule< > = TSliceMapper extends LazyModule ? Awaited> extends { - default: unknown; + default: unknown } ? Awaited>["default"] : Awaited> - : TSliceMapper; + : TSliceMapper /** * Transforms a Slice into its mapped version. @@ -206,7 +206,7 @@ type MapSliceLike< > : TSliceLike : TSliceLike - : never; + : never /** * Transforms a Slice Zone using a set of mapping functions, one for each type @@ -236,23 +236,23 @@ export function mapSliceZone< ): Promise[]> { return Promise.all( sliceZone.map(async (slice, index, slices) => { - const isRestSliceType = "slice_type" in slice; - const sliceType = isRestSliceType ? slice.slice_type : slice.type; + const isRestSliceType = "slice_type" in slice + const sliceType = isRestSliceType ? slice.slice_type : slice.type - const mapper = mappers[sliceType as keyof typeof mappers]; + const mapper = mappers[sliceType as keyof typeof mappers] if (!mapper) { - return slice; + return slice } - const mapperArgs = { slice, slices, index, context }; + const mapperArgs = { slice, slices, index, context } // `result` may be a mapper function OR a module // containing a mapper function. let result = await mapper( // @ts-expect-error - I don't know how to fix this type mapperArgs, - ); + ) // `result` is a module containing a mapper function, // we need to dig out the mapper function. `result` @@ -265,8 +265,8 @@ export function mapSliceZone< (typeof result === "function" || (typeof result === "object" && "default" in result)) ) { - result = "default" in result ? result.default : result; - result = await result(mapperArgs); + result = "default" in result ? result.default : result + result = await result(mapperArgs) } if (isRestSliceType) { @@ -275,14 +275,14 @@ export function mapSliceZone< id: slice.id, slice_type: sliceType, ...result, - }; + } } else { return { __mapped: true, type: sliceType, ...result, - }; + } } }), - ); + ) } diff --git a/src/helpers/unstable_htmlAsRichText.ts b/src/helpers/unstable_htmlAsRichText.ts index 019a7662..c2532c5f 100644 --- a/src/helpers/unstable_htmlAsRichText.ts +++ b/src/helpers/unstable_htmlAsRichText.ts @@ -1,20 +1,21 @@ -import { Element } from "hast"; -import rehypeParse from "rehype-parse"; -import { unified } from "unified"; +import type { Element } from "hast" +import rehypeParse from "rehype-parse" +import { unified } from "unified" -import { RTPartialInlineNode } from "../lib/RichTextFieldBuilder"; -import { RehypeRichTextConfig, rehypeRichText } from "../lib/rehypeRichText"; +import type { RTPartialInlineNode } from "../lib/RichTextFieldBuilder" +import type { RehypeRichTextConfig } from "../lib/rehypeRichText" +import { rehypeRichText } from "../lib/rehypeRichText" -import { +import type { RTInlineNode, RTNode, RichTextField, RichTextNodeTypes, -} from "../types/value/richText"; +} from "../types/value/richText" // Used for TSDocs only. // eslint-disable-next-line @typescript-eslint/no-unused-vars -import type { HTMLRichTextMapSerializer, asHTML } from "./asHTML"; +import type { HTMLRichTextMapSerializer, asHTML } from "./asHTML" /** * A shorthand definition for {@link RichTextHTMLMapSerializer} rich text node @@ -30,7 +31,7 @@ import type { HTMLRichTextMapSerializer, asHTML } from "./asHTML"; */ export type RichTextHTMLMapSerializerShorthand = | Exclude - | { label: string }; + | { label: string } /** * The payload provided to a {@link RichTextHTMLMapSerializerFunction}. @@ -39,7 +40,7 @@ type RichTextHTMLMapSerializerFunctionPayload = { /** * The hast {@link Element} node to serialize. */ - node: Element; + node: Element /** * Additional context information to help with the serialization. @@ -48,9 +49,9 @@ type RichTextHTMLMapSerializerFunctionPayload = { /** * The list type of the last list node encountered if any. */ - listType?: "group-list-item" | "group-o-list-item"; - }; -}; + listType?: "group-list-item" | "group-o-list-item" + } +} /** * Serializes a hast {@link Element} node to a @@ -68,7 +69,7 @@ export type RichTextHTMLMapSerializerFunction = ( | RTNode | RTInlineNode | RTPartialInlineNode - | undefined; + | undefined /** * Serializes a hast {@link Element} node matching the given HTML tag name or CSS @@ -82,20 +83,20 @@ export type RichTextHTMLMapSerializerFunction = ( export type RichTextHTMLMapSerializer = Record< string, RichTextHTMLMapSerializerShorthand | RichTextHTMLMapSerializerFunction ->; +> /** * Configuration that determines the output of {@link htmlAsRichText}. */ -export type HTMLAsRichTextConfig = RehypeRichTextConfig; +export type HTMLAsRichTextConfig = RehypeRichTextConfig /** * The return type of {@link htmlAsRichText}. */ type HTMLAsRichTextReturnType = { - result: RichTextField; - warnings: string[]; -}; + result: RichTextField + warnings: string[] +} /** * Converts an HTML string to a rich text field. @@ -115,7 +116,7 @@ export const unstable_htmlAsRichText = ( const { result, messages } = unified() .use(rehypeParse, { emitParseErrors: true, missingDoctype: 0 }) .use(rehypeRichText, config) - .processSync(html); + .processSync(html) - return { result, warnings: messages.map((message) => message.toString()) }; -}; + return { result, warnings: messages.map((message) => message.toString()) } +} diff --git a/src/helpers/unstable_markdownAsRichText.ts b/src/helpers/unstable_markdownAsRichText.ts index 66eff1ef..7c5016d7 100644 --- a/src/helpers/unstable_markdownAsRichText.ts +++ b/src/helpers/unstable_markdownAsRichText.ts @@ -1,27 +1,28 @@ -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { unified } from "unified"; +import remarkParse from "remark-parse" +import remarkRehype from "remark-rehype" +import { unified } from "unified" -import { RehypeRichTextConfig, rehypeRichText } from "../lib/rehypeRichText"; +import type { RehypeRichTextConfig } from "../lib/rehypeRichText" +import { rehypeRichText } from "../lib/rehypeRichText" -import { RichTextField } from "../types/value/richText"; +import type { RichTextField } from "../types/value/richText" // Used for TSDocs only. // eslint-disable-next-line @typescript-eslint/no-unused-vars -import type { unstable_htmlAsRichText } from "./unstable_htmlAsRichText"; +import type { unstable_htmlAsRichText } from "./unstable_htmlAsRichText" /** * Configuration that determines the output of {@link markdownAsRichText}. */ -export type MarkdownAsRichTextConfig = RehypeRichTextConfig; +export type MarkdownAsRichTextConfig = RehypeRichTextConfig /** * The return type of {@link markdownAsRichText}. */ type MarkdownAsRichTextReturnType = { - result: RichTextField; - warnings: string[]; -}; + result: RichTextField + warnings: string[] +} /** * Converts a markdown string to a rich text field. @@ -46,7 +47,7 @@ export const unstable_markdownAsRichText = ( .use(remarkParse) .use(remarkRehype) .use(rehypeRichText, config) - .processSync(markdown); + .processSync(markdown) - return { result, warnings: messages.map((message) => message.toString()) }; -}; + return { result, warnings: messages.map((message) => message.toString()) } +} diff --git a/src/index.ts b/src/index.ts index 6f622942..5e3a9393 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,44 +1,44 @@ // Imports are used for deprecations. -import type { CustomTypeModelIntegrationField } from "./types/model/integration"; -import type { IntegrationField } from "./types/value/integration"; -import { RichTextNodeType } from "./types/value/richText"; +import type { CustomTypeModelIntegrationField } from "./types/model/integration" +import type { IntegrationField } from "./types/value/integration" +import { RichTextNodeType } from "./types/value/richText" import type { HTMLRichTextFunctionSerializer, HTMLRichTextMapSerializer, -} from "./helpers/asHTML"; -import { mapSliceZone } from "./helpers/mapSliceZone"; +} from "./helpers/asHTML" +import { mapSliceZone } from "./helpers/mapSliceZone" -import { filter } from "./filter"; +import { filter } from "./filter" //============================================================================= // Client - Query content from Prismic. //============================================================================= // Primary Client API. -export { createClient, Client } from "./createClient"; +export { createClient, Client } from "./createClient" // API endpoint helpers. -export { getRepositoryEndpoint } from "./getRepositoryEndpoint"; -export { getRepositoryName } from "./getRepositoryName"; -export { getGraphQLEndpoint } from "./getGraphQLEndpoint"; -export { isRepositoryName } from "./isRepositoryName"; -export { isRepositoryEndpoint } from "./isRepositoryEndpoint"; -export { buildQueryURL } from "./buildQueryURL"; +export { getRepositoryEndpoint } from "./getRepositoryEndpoint" +export { getRepositoryName } from "./getRepositoryName" +export { getGraphQLEndpoint } from "./getGraphQLEndpoint" +export { isRepositoryName } from "./isRepositoryName" +export { isRepositoryEndpoint } from "./isRepositoryEndpoint" +export { buildQueryURL } from "./buildQueryURL" // Toolbar helpers. -export { getToolbarSrc } from "./getToolbarSrc"; +export { getToolbarSrc } from "./getToolbarSrc" // Query filters API. /** * @deprecated Renamed to `filter` */ // TODO: Remove when we remove support for deprecated `predicate` export. -const predicate = filter; -export { filter, predicate }; +const predicate = filter +export { filter, predicate } // A collection of well-known cookie names shared between Prismic libraries and systems. -export * as cookie from "./cookie"; +export * as cookie from "./cookie" // General types used to query content from Prismic. These are made public to allow users to better type their projects. export type { @@ -49,79 +49,79 @@ export type { HttpRequestLike, RequestInitLike, ResponseLike, -} from "./createClient"; +} from "./createClient" export type { BuildQueryURLArgs, Ordering, QueryParams, Route, -} from "./buildQueryURL"; +} from "./buildQueryURL" //============================================================================= // Helpers - Manipulate content from Prismic. //============================================================================= // Primary Helpers API. -export { asDate } from "./helpers/asDate"; -export { asLink } from "./helpers/asLink"; -export { asLinkAttrs } from "./helpers/asLinkAttrs"; -export { asText } from "./helpers/asText"; -export { asHTML } from "./helpers/asHTML"; -export { asImageSrc } from "./helpers/asImageSrc"; -export { asImageWidthSrcSet } from "./helpers/asImageWidthSrcSet"; -export { asImagePixelDensitySrcSet } from "./helpers/asImagePixelDensitySrcSet"; -export * as isFilled from "./helpers/isFilled"; +export { asDate } from "./helpers/asDate" +export { asLink } from "./helpers/asLink" +export { asLinkAttrs } from "./helpers/asLinkAttrs" +export { asText } from "./helpers/asText" +export { asHTML } from "./helpers/asHTML" +export { asImageSrc } from "./helpers/asImageSrc" +export { asImageWidthSrcSet } from "./helpers/asImageWidthSrcSet" +export { asImagePixelDensitySrcSet } from "./helpers/asImagePixelDensitySrcSet" +export * as isFilled from "./helpers/isFilled" /** * @deprecated Renamed to `mapSliceZone` */ -const unstable_mapSliceZone = mapSliceZone; -export { mapSliceZone, unstable_mapSliceZone }; +const unstable_mapSliceZone = mapSliceZone +export { mapSliceZone, unstable_mapSliceZone } // Conversion helper. -export { documentToLinkField } from "./helpers/documentToLinkField"; -export { unstable_htmlAsRichText } from "./helpers/unstable_htmlAsRichText"; -export { unstable_markdownAsRichText } from "./helpers/unstable_markdownAsRichText"; +export { documentToLinkField } from "./helpers/documentToLinkField" +export { unstable_htmlAsRichText } from "./helpers/unstable_htmlAsRichText" +export { unstable_markdownAsRichText } from "./helpers/unstable_markdownAsRichText" -export type { LinkResolverFunction } from "./helpers/asLink"; -export type { AsLinkAttrsConfig } from "./helpers/asLinkAttrs"; -export type { SliceMapper } from "./helpers/mapSliceZone"; +export type { LinkResolverFunction } from "./helpers/asLink" +export type { AsLinkAttrsConfig } from "./helpers/asLinkAttrs" +export type { SliceMapper } from "./helpers/mapSliceZone" /** * @deprecated Renamed to `HTMLRichTextMapSerializer` */ -type HTMLMapSerializer = HTMLRichTextMapSerializer; +type HTMLMapSerializer = HTMLRichTextMapSerializer /** * @deprecated Renamed to `HTMLRichTextFunctionSerializer` */ -type HTMLFunctionSerializer = HTMLRichTextFunctionSerializer; +type HTMLFunctionSerializer = HTMLRichTextFunctionSerializer export type { HTMLRichTextMapSerializer, HTMLRichTextFunctionSerializer, HTMLMapSerializer, HTMLFunctionSerializer, -}; -export type { HTMLRichTextSerializer } from "./helpers/asHTML"; +} +export type { HTMLRichTextSerializer } from "./helpers/asHTML" -export type { RichTextHTMLMapSerializer } from "./helpers/unstable_htmlAsRichText"; +export type { RichTextHTMLMapSerializer } from "./helpers/unstable_htmlAsRichText" //============================================================================= // Errors - Custom errors for Prismic APIs. //============================================================================= // Client Errors -export { PrismicError } from "./errors/PrismicError"; -export { ForbiddenError } from "./errors/ForbiddenError"; -export { NotFoundError } from "./errors/NotFoundError"; -export { RefNotFoundError } from "./errors/RefNotFoundError"; -export { RefExpiredError } from "./errors/RefExpiredError"; -export { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired"; -export { ParsingError } from "./errors/ParsingError"; -export { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError"; +export { PrismicError } from "./errors/PrismicError" +export { ForbiddenError } from "./errors/ForbiddenError" +export { NotFoundError } from "./errors/NotFoundError" +export { RefNotFoundError } from "./errors/RefNotFoundError" +export { RefExpiredError } from "./errors/RefExpiredError" +export { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired" +export { ParsingError } from "./errors/ParsingError" +export { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError" // Rich Text Errors -export { PrismicRichTextError } from "./errors/PrismicRichTextError"; -export { PrismicRichTextSerializerError } from "./errors/PrismicRichTextSerializerError"; +export { PrismicRichTextError } from "./errors/PrismicRichTextError" +export { PrismicRichTextSerializerError } from "./errors/PrismicRichTextSerializerError" //============================================================================= // Types - Types representing Prismic content, models, and API payloads. @@ -132,10 +132,10 @@ export { PrismicRichTextSerializerError } from "./errors/PrismicRichTextSerializ * @deprecated Use {@link RichTextNodeType} instead. */ // TODO: Remove in v8. -const Element = RichTextNodeType; -export { RichTextNodeType, Element }; -export { LinkType } from "./types/value/link"; -export { OEmbedType } from "./types/value/embed"; +const Element = RichTextNodeType +export { RichTextNodeType, Element } +export { LinkType } from "./types/value/link" +export { OEmbedType } from "./types/value/embed" export type { PrismicDocument, @@ -143,7 +143,7 @@ export type { PrismicDocumentWithoutUID, PrismicDocumentHeader, AlternateLanguage, -} from "./types/value/document"; +} from "./types/value/document" export type { // RichText & Title @@ -181,29 +181,29 @@ export type { RTInlineNode, RTAnyNode, RichTextNodeTypes, -} from "./types/value/richText"; -export type { TitleField } from "./types/value/title"; +} from "./types/value/richText" +export type { TitleField } from "./types/value/title" export type { ImageField, ImageFieldImage, FilledImageFieldImage, EmptyImageFieldImage, -} from "./types/value/image"; +} from "./types/value/image" export type { EmptyLinkField, LinkField, FilledLinkToWebField, -} from "./types/value/link"; +} from "./types/value/link" export type { ContentRelationshipField, FilledContentRelationshipField, -} from "./types/value/contentRelationship"; +} from "./types/value/contentRelationship" export type { LinkToMediaField, FilledLinkToMediaField, -} from "./types/value/linkToMedia"; +} from "./types/value/linkToMedia" export type { OEmbedExtra, @@ -213,135 +213,135 @@ export type { RichOEmbed, AnyOEmbed, EmbedField, -} from "./types/value/embed"; +} from "./types/value/embed" -export type { BooleanField } from "./types/value/boolean"; -export type { ColorField } from "./types/value/color"; -export type { DateField } from "./types/value/date"; -export type { KeyTextField } from "./types/value/keyText"; -export type { NumberField } from "./types/value/number"; -export type { SelectField } from "./types/value/select"; -export type { TimestampField } from "./types/value/timestamp"; -export type { GeoPointField } from "./types/value/geoPoint"; +export type { BooleanField } from "./types/value/boolean" +export type { ColorField } from "./types/value/color" +export type { DateField } from "./types/value/date" +export type { KeyTextField } from "./types/value/keyText" +export type { NumberField } from "./types/value/number" +export type { SelectField } from "./types/value/select" +export type { TimestampField } from "./types/value/timestamp" +export type { GeoPointField } from "./types/value/geoPoint" /** * @deprecated Renamed to `IntegrationField` */ // TODO: Remove when we remove support for deprecated `IntegrationFields` export. -type IntegrationFields = IntegrationField; -export { IntegrationField, IntegrationFields }; +type IntegrationFields = IntegrationField +export { IntegrationField, IntegrationFields } -export type { GroupField, NestedGroupField } from "./types/value/group"; +export type { GroupField, NestedGroupField } from "./types/value/group" -export type { SliceZone } from "./types/value/sliceZone"; -export type { Slice } from "./types/value/slice"; -export type { SharedSlice } from "./types/value/sharedSlice"; -export type { SharedSliceVariation } from "./types/value/sharedSliceVariation"; +export type { SliceZone } from "./types/value/sliceZone" +export type { Slice } from "./types/value/slice" +export type { SharedSlice } from "./types/value/sharedSlice" +export type { SharedSliceVariation } from "./types/value/sharedSliceVariation" export type { FieldState, AnyRegularField, AnySlicePrimaryField, -} from "./types/value/types"; +} from "./types/value/types" // Models - Types representing Prismic content models. -export { CustomTypeModelFieldType } from "./types/model/types"; -export { CustomTypeModelLinkSelectType } from "./types/model/link"; -export { CustomTypeModelSliceType } from "./types/model/sliceZone"; -export { CustomTypeModelSliceDisplay } from "./types/model/slice"; +export { CustomTypeModelFieldType } from "./types/model/types" +export { CustomTypeModelLinkSelectType } from "./types/model/link" +export { CustomTypeModelSliceType } from "./types/model/sliceZone" +export { CustomTypeModelSliceDisplay } from "./types/model/slice" export type { CustomTypeModel, CustomTypeModelDefinition, CustomTypeModelTab, -} from "./types/model/customType"; +} from "./types/model/customType" export type { CustomTypeModelRichTextField, CustomTypeModelRichTextMultiField, CustomTypeModelRichTextSingleField, -} from "./types/model/richText"; -export type { CustomTypeModelTitleField } from "./types/model/title"; +} from "./types/model/richText" +export type { CustomTypeModelTitleField } from "./types/model/title" export type { CustomTypeModelImageField, CustomTypeModelImageConstraint, CustomTypeModelImageThumbnail, -} from "./types/model/image"; +} from "./types/model/image" -export type { CustomTypeModelContentRelationshipField } from "./types/model/contentRelationship"; -export type { CustomTypeModelLinkField } from "./types/model/link"; -export type { CustomTypeModelLinkToMediaField } from "./types/model/linkToMedia"; +export type { CustomTypeModelContentRelationshipField } from "./types/model/contentRelationship" +export type { CustomTypeModelLinkField } from "./types/model/link" +export type { CustomTypeModelLinkToMediaField } from "./types/model/linkToMedia" -export type { CustomTypeModelEmbedField } from "./types/model/embed"; +export type { CustomTypeModelEmbedField } from "./types/model/embed" -export type { CustomTypeModelBooleanField } from "./types/model/boolean"; -export type { CustomTypeModelColorField } from "./types/model/color"; -export type { CustomTypeModelDateField } from "./types/model/date"; -export type { CustomTypeModelKeyTextField } from "./types/model/keyText"; -export type { CustomTypeModelNumberField } from "./types/model/number"; -export type { CustomTypeModelSelectField } from "./types/model/select"; -export type { CustomTypeModelTimestampField } from "./types/model/timestamp"; -export type { CustomTypeModelGeoPointField } from "./types/model/geoPoint"; +export type { CustomTypeModelBooleanField } from "./types/model/boolean" +export type { CustomTypeModelColorField } from "./types/model/color" +export type { CustomTypeModelDateField } from "./types/model/date" +export type { CustomTypeModelKeyTextField } from "./types/model/keyText" +export type { CustomTypeModelNumberField } from "./types/model/number" +export type { CustomTypeModelSelectField } from "./types/model/select" +export type { CustomTypeModelTimestampField } from "./types/model/timestamp" +export type { CustomTypeModelGeoPointField } from "./types/model/geoPoint" /** * @deprecated Renamed to `CustomTypeModelIntegrationField`. */ // TODO: Remove when we remove support for deprecated `CustomTypeModelIntegrationField` export. -type CustomTypeModelIntegrationFieldsField = CustomTypeModelIntegrationField; +type CustomTypeModelIntegrationFieldsField = CustomTypeModelIntegrationField export { CustomTypeModelIntegrationField, CustomTypeModelIntegrationFieldsField, -}; +} export type { CustomTypeModelGroupField, CustomTypeModelNestedGroupField, -} from "./types/model/group"; +} from "./types/model/group" export type { CustomTypeModelSliceZoneField, CustomTypeModelSliceLabel, CustomTypeModelSharedSlice, -} from "./types/model/sliceZone"; +} from "./types/model/sliceZone" export type { CustomTypeModelSlice, CustomTypeModelLegacySlice, -} from "./types/model/slice"; -export type { SharedSliceModel } from "./types/model/sharedSlice"; -export type { SharedSliceModelVariation } from "./types/model/sharedSliceVariation"; +} from "./types/model/slice" +export type { SharedSliceModel } from "./types/model/sharedSlice" +export type { SharedSliceModelVariation } from "./types/model/sharedSliceVariation" -export type { CustomTypeModelUIDField } from "./types/model/uid"; +export type { CustomTypeModelUIDField } from "./types/model/uid" -export type { CustomTypeModelRangeField } from "./types/model/range"; -export type { CustomTypeModelSeparatorField } from "./types/model/separator"; +export type { CustomTypeModelRangeField } from "./types/model/range" +export type { CustomTypeModelSeparatorField } from "./types/model/separator" export type { CustomTypeModelField, CustomTypeModelFieldForGroup, CustomTypeModelFieldForNestedGroup, CustomTypeModelFieldForSlicePrimary, -} from "./types/model/types"; +} from "./types/model/types" // API - Types representing Prismic Rest API V2 responses. -export type { Query } from "./types/api/query"; +export type { Query } from "./types/api/query" -export type { Ref } from "./types/api/ref"; +export type { Ref } from "./types/api/ref" -export type { Release } from "./types/api/release"; +export type { Release } from "./types/api/release" export type { Repository, Language, Form, FormField, -} from "./types/api/repository"; +} from "./types/api/repository" -export type { Tags } from "./types/api/tags"; +export type { Tags } from "./types/api/tags" // Webhook - Types representing Prismic webhooks. -export { WebhookType } from "./types/webhook/types"; +export { WebhookType } from "./types/webhook/types" -export type { WebhookBody } from "./types/webhook/types"; +export type { WebhookBody } from "./types/webhook/types" -export type { WebhookBodyAPIUpdate } from "./types/webhook/apiUpdate"; +export type { WebhookBodyAPIUpdate } from "./types/webhook/apiUpdate" -export type { WebhookBodyTestTrigger } from "./types/webhook/testTrigger"; +export type { WebhookBodyTestTrigger } from "./types/webhook/testTrigger" diff --git a/src/isRepositoryEndpoint.ts b/src/isRepositoryEndpoint.ts index bb9f44de..e07a38f9 100644 --- a/src/isRepositoryEndpoint.ts +++ b/src/isRepositoryEndpoint.ts @@ -9,10 +9,10 @@ */ export const isRepositoryEndpoint = (input: string): boolean => { try { - new URL(input); + new URL(input) - return true; + return true } catch { - return false; + return false } -}; +} diff --git a/src/isRepositoryName.ts b/src/isRepositoryName.ts index 4a840c32..01f91ff3 100644 --- a/src/isRepositoryName.ts +++ b/src/isRepositoryName.ts @@ -7,5 +7,5 @@ * otherwise. */ export const isRepositoryName = (input: string): boolean => { - return /^[a-zA-Z0-9][-a-zA-Z0-9]{2,}[a-zA-Z0-9]$/.test(input); -}; + return /^[a-zA-Z0-9][-a-zA-Z0-9]{2,}[a-zA-Z0-9]$/.test(input) +} diff --git a/src/lib/RichTextFieldBuilder.ts b/src/lib/RichTextFieldBuilder.ts index 77034d42..0e4aad75 100644 --- a/src/lib/RichTextFieldBuilder.ts +++ b/src/lib/RichTextFieldBuilder.ts @@ -1,12 +1,12 @@ -import { +import type { RTInlineNode, RTLinkNode, RTNode, RTTextNode, RichTextField, -} from "../types/value/richText"; +} from "../types/value/richText" -import { PrismicRichTextError } from "../errors/PrismicRichTextError"; +import { PrismicRichTextError } from "../errors/PrismicRichTextError" /** * Omits keys from a type, distributing the operation over a union. @@ -18,27 +18,24 @@ import { PrismicRichTextError } from "../errors/PrismicRichTextError"; type DistributedOmit< ObjectType, KeyType extends keyof ObjectType, -> = ObjectType extends unknown ? Omit : never; +> = ObjectType extends unknown ? Omit : never /** * An inline node without its `start` and `end` properties. */ -export type RTPartialInlineNode = DistributedOmit< - RTInlineNode, - "start" | "end" ->; +export type RTPartialInlineNode = DistributedOmit export class RichTextFieldBuilder { - #nodes: RTNode[] = []; + #nodes: RTNode[] = [] get #last(): RTNode | undefined { - return this.#nodes[this.#nodes.length - 1]; + return this.#nodes[this.#nodes.length - 1] } appendNode(node: RTNode): void { - this.cleanupLast(); + this.cleanupLast() - this.#nodes.push(node); + this.#nodes.push(node) } appendTextNode( @@ -50,48 +47,48 @@ export class RichTextFieldBuilder { text: "", spans: [], direction, - }); + }) } - appendSpan(span: RTInlineNode): void; - appendSpan(partialSpan: RTPartialInlineNode, length: number): void; + appendSpan(span: RTInlineNode): void + appendSpan(partialSpan: RTPartialInlineNode, length: number): void appendSpan( spanOrPartialSpan: RTInlineNode | RTPartialInlineNode, length?: number, ): void { if (!this.isTextNode(this.#last)) { - throw new PrismicRichTextError("Cannot add span to non-text last node"); + throw new PrismicRichTextError("Cannot add span to non-text last node") } - let span: RTInlineNode; + let span: RTInlineNode if ("start" in spanOrPartialSpan && "end" in spanOrPartialSpan) { - span = spanOrPartialSpan; + span = spanOrPartialSpan } else { - const lastLength = this.#last.text.length; + const lastLength = this.#last.text.length span = { ...spanOrPartialSpan, start: lastLength, end: lastLength + length!, - }; + } } - let lastIdenticalSpanIndex = -1; + let lastIdenticalSpanIndex = -1 for (let i = this.#last.spans.length - 1; i >= 0; i--) { - const lastSpan = this.#last.spans[i]; + const lastSpan = this.#last.spans[i] if (span.type === "strong" || span.type === "em") { if (lastSpan.type === span.type) { - lastIdenticalSpanIndex = i; - break; + lastIdenticalSpanIndex = i + break } } else if (span.type === "label") { if ( lastSpan.type === "label" && lastSpan.data.label === span.data.label ) { - lastIdenticalSpanIndex = i; - break; + lastIdenticalSpanIndex = i + break } } else if (span.type === "hyperlink") { if (lastSpan.type === "hyperlink") { @@ -100,11 +97,11 @@ export class RichTextFieldBuilder { // match with content relationship. const isSameLink = ( Object.entries(span.data) as [keyof RTLinkNode["data"], unknown][] - ).every(([key, value]) => lastSpan.data[key] === value); + ).every(([key, value]) => lastSpan.data[key] === value) if (isSameLink) { - lastIdenticalSpanIndex = i; - break; + lastIdenticalSpanIndex = i + break } } } @@ -112,39 +109,37 @@ export class RichTextFieldBuilder { // Ignore empty spans. if (span.start === span.end) { - return; + return } // Prefer to extend the last span of the same type end // position if it ends at the start of the new span. if (this.#last.spans[lastIdenticalSpanIndex]?.end === span.start) { - this.#last.spans[lastIdenticalSpanIndex].end = span.end; + this.#last.spans[lastIdenticalSpanIndex].end = span.end } else { - this.#last.spans.push(span); + this.#last.spans.push(span) } } appendText(text: string): void { if (!this.isTextNode(this.#last)) { - throw new PrismicRichTextError( - "Cannot append text to non-text last node", - ); + throw new PrismicRichTextError("Cannot append text to non-text last node") } if (this.#last.text) { - this.#last.text += text; + this.#last.text += text } else { - this.#last.text = text.trimStart(); + this.#last.text = text.trimStart() } } build(): RichTextField { // Ensure that the last text node is trimmed. - this.cleanupLast(); + this.cleanupLast() // Because `RichTextField` is defined as a non-empty // array, we have to cast `RTNode[]` to `RichTextField`. - return this.#nodes as RichTextField; + return this.#nodes as RichTextField } /** @@ -152,7 +147,7 @@ export class RichTextFieldBuilder { */ private cleanupLast(): void { if (this.isTextNode(this.#last)) { - this.#last.text = this.#last.text.trimEnd(); + this.#last.text = this.#last.text.trimEnd() } } @@ -164,6 +159,6 @@ export class RichTextFieldBuilder { * @returns `true` if `node` is a text node, `false` otherwise. */ private isTextNode(node?: RTNode): node is RTTextNode { - return !!node && node.type !== "image" && node.type !== "embed"; + return !!node && node.type !== "image" && node.type !== "embed" } } diff --git a/src/lib/appendFilters.ts b/src/lib/appendFilters.ts index 085d8bd1..5b21e772 100644 --- a/src/lib/appendFilters.ts +++ b/src/lib/appendFilters.ts @@ -1,7 +1,7 @@ -import { castArray } from "./castArray"; +import { castArray } from "./castArray" interface WithFilters { - filters?: string | string[]; + filters?: string | string[] } /** @@ -22,5 +22,5 @@ export const appendFilters = ( return { ...objWithFilters, filters: [...(objWithFilters.filters || []), ...castArray(filters)], - }; -}; + } +} diff --git a/src/lib/castArray.ts b/src/lib/castArray.ts index 0c8351a8..0c324abe 100644 --- a/src/lib/castArray.ts +++ b/src/lib/castArray.ts @@ -10,5 +10,5 @@ * @returns `a` as an array. */ export const castArray = (a: A | A[]): A[] => { - return Array.isArray(a) ? a : [a]; -}; + return Array.isArray(a) ? a : [a] +} diff --git a/src/lib/castThunk.ts b/src/lib/castThunk.ts index 8dd06333..ebca947a 100644 --- a/src/lib/castThunk.ts +++ b/src/lib/castThunk.ts @@ -9,5 +9,5 @@ * @returns `a` as a a thunk. */ export const castThunk = (a: A | (() => A)): (() => A) => { - return typeof a === "function" ? (a as () => A) : () => a; -}; + return typeof a === "function" ? (a as () => A) : () => a +} diff --git a/src/lib/devMsg.ts b/src/lib/devMsg.ts index 3dc280b0..bae8be5a 100644 --- a/src/lib/devMsg.ts +++ b/src/lib/devMsg.ts @@ -1,4 +1,4 @@ -import { version } from "../../package.json"; +import { version } from "../../package.json" /** * Returns a `prismic.dev/msg` URL for a given message slug. @@ -6,7 +6,7 @@ import { version } from "../../package.json"; * @example * * ```ts - * devMsg("missing-param"); + * devMsg("missing-param") * // => "https://prismic.dev/msg/client/v1.2.3/missing-param.md" * ``` * @@ -16,5 +16,5 @@ import { version } from "../../package.json"; * @returns The `prismic.dev/msg` URL for the given slug. */ export const devMsg = (slug: string): string => { - return `https://prismic.dev/msg/client/v${version}/${slug}`; -}; + return `https://prismic.dev/msg/client/v${version}/${slug}` +} diff --git a/src/lib/escapeHTML.ts b/src/lib/escapeHTML.ts index beba2dd2..895a8d30 100644 --- a/src/lib/escapeHTML.ts +++ b/src/lib/escapeHTML.ts @@ -3,49 +3,49 @@ ** Many thanks to @component */ -const matchHtmlRegExp = /["'&<>]/; +const matchHtmlRegExp = /["'&<>]/ export const escapeHTML = (string?: string | null): string => { - const str = "" + string; - const match = matchHtmlRegExp.exec(str); + const str = "" + string + const match = matchHtmlRegExp.exec(str) if (!match) { - return str; + return str } - let escape; - let html = ""; - let index = 0; - let lastIndex = 0; + let escape + let html = "" + let index = 0 + let lastIndex = 0 for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " - escape = """; - break; + escape = """ + break case 38: // & - escape = "&"; - break; + escape = "&" + break case 39: // ' - escape = "'"; - break; + escape = "'" + break case 60: // < - escape = "<"; - break; + escape = "<" + break case 62: // > - escape = ">"; - break; + escape = ">" + break default: - continue; + continue } if (lastIndex !== index) { - html += str.substring(lastIndex, index); + html += str.substring(lastIndex, index) } - lastIndex = index + 1; - html += escape; + lastIndex = index + 1 + html += escape } - return lastIndex !== index ? html + str.substring(lastIndex, index) : html; -}; + return lastIndex !== index ? html + str.substring(lastIndex, index) : html +} diff --git a/src/lib/everyTagFilter.ts b/src/lib/everyTagFilter.ts index e4599f0e..a5675d6b 100644 --- a/src/lib/everyTagFilter.ts +++ b/src/lib/everyTagFilter.ts @@ -1,6 +1,6 @@ -import { filter } from "../filter"; +import { filter } from "../filter" -import { castArray } from "./castArray"; +import { castArray } from "./castArray" /** * Creates a filter to filter content by document tags. All tags are required on @@ -11,5 +11,5 @@ import { castArray } from "./castArray"; * @returns A filter that can be used in a Prismic REST API V2 request. */ export const everyTagFilter = (tags: string | string[]): string => { - return filter.at("document.tags", castArray(tags)); -}; + return filter.at("document.tags", castArray(tags)) +} diff --git a/src/lib/filterRichTextField.ts b/src/lib/filterRichTextField.ts index 763cd464..8e71ea86 100644 --- a/src/lib/filterRichTextField.ts +++ b/src/lib/filterRichTextField.ts @@ -1,14 +1,14 @@ -import { CustomTypeModelRichTextField } from "../types/model/richText"; -import { LinkType } from "../types/value/link"; -import { +import type { CustomTypeModelRichTextField } from "../types/model/richText" +import { LinkType } from "../types/value/link" +import type { RTImageNode, RTNode, RTTextNode, RichTextField, - RichTextNodeType, RichTextNodeTypes, -} from "../types/value/richText"; -import { TitleField } from "../types/value/title"; +} from "../types/value/richText" +import { RichTextNodeType } from "../types/value/richText" +import type { TitleField } from "../types/value/title" /** * Get allowed nodes types from a rich text or title field custom type model. @@ -20,26 +20,26 @@ import { TitleField } from "../types/value/title"; const getAllowedNodeTypes = ( model: CustomTypeModelRichTextField, ): RichTextNodeTypes[] => { - const allowedNodeTypes: RichTextNodeTypes[] = []; // An empty array means no nodes are allowed by default. + const allowedNodeTypes: RichTextNodeTypes[] = [] // An empty array means no nodes are allowed by default. if (model.config) { if ("multi" in model.config && model.config.multi) { allowedNodeTypes.push( ...(model.config.multi.split(",") as RichTextNodeTypes[]), - ); + ) } else if ("single" in model.config && model.config.single) { allowedNodeTypes.push( ...(model.config.single.split(",") as RichTextNodeTypes[]), - ); + ) } if (model.config.labels?.length) { - allowedNodeTypes.push("label"); + allowedNodeTypes.push("label") } } - return allowedNodeTypes; -}; + return allowedNodeTypes +} /** * Filter an image node based on given model. @@ -63,11 +63,11 @@ const filterImageNode = ( ...node.linkTo, target: undefined, }, - }; + } } - return node; -}; + return node +} /** * Filter a text node based on given model. @@ -86,10 +86,10 @@ const filterTextNode = ( const filteredNode: RTTextNode = { ...node, spans: [], - }; + } for (let i = 0; i < node.spans.length; i++) { - const span = node.spans[i]; + const span = node.spans[i] if (allowedNodeTypes.includes(span.type)) { if (span.type === RichTextNodeType.hyperlink) { @@ -103,22 +103,22 @@ const filterTextNode = ( ...span.data, target: undefined, }, - }); + }) } else { - filteredNode.spans.push(span); + filteredNode.spans.push(span) } } else if (span.type === RichTextNodeType.label) { if (model.config?.labels?.includes(span.data.label)) { - filteredNode.spans.push(span); + filteredNode.spans.push(span) } } else { - filteredNode.spans.push(span); + filteredNode.spans.push(span) } } } - return filteredNode; -}; + return filteredNode +} /** * Filter a rich text field based on given model. @@ -132,9 +132,9 @@ export const filterRichTextField = ( richTextField: Field, model: CustomTypeModelRichTextField, ): Field => { - const nodes: RTNode[] = []; + const nodes: RTNode[] = [] - const allowedNodeTypes = getAllowedNodeTypes(model); + const allowedNodeTypes = getAllowedNodeTypes(model) for ( let i = 0; @@ -142,18 +142,18 @@ export const filterRichTextField = ( i < (model.config && "multi" in model.config ? richTextField.length : 1); i++ ) { - const node = richTextField[i]; + const node = richTextField[i] if (allowedNodeTypes.includes(node.type)) { if (node.type === RichTextNodeType.image) { - nodes.push(filterImageNode(node, model)); + nodes.push(filterImageNode(node, model)) } else if (node.type === RichTextNodeType.embed) { - nodes.push(node); + nodes.push(node) } else { - nodes.push(filterTextNode(node, model, allowedNodeTypes)); + nodes.push(filterTextNode(node, model, allowedNodeTypes)) } } } - return nodes as Field; -}; + return nodes as Field +} diff --git a/src/lib/findMasterRef.ts b/src/lib/findMasterRef.ts index c3157a5a..3219e6ba 100644 --- a/src/lib/findMasterRef.ts +++ b/src/lib/findMasterRef.ts @@ -1,6 +1,6 @@ -import { Ref } from "../types/api/ref"; +import type { Ref } from "../types/api/ref" -import { findRef } from "./findRef"; +import { findRef } from "./findRef" /** * Returns the master ref from a list of given refs. @@ -12,5 +12,5 @@ import { findRef } from "./findRef"; * @throws If a matching ref cannot be found. */ export const findMasterRef = (refs: Ref[]): Ref => { - return findRef(refs, (ref) => ref.isMasterRef); -}; + return findRef(refs, (ref) => ref.isMasterRef) +} diff --git a/src/lib/findRef.ts b/src/lib/findRef.ts index ac5e6a6c..b1f858df 100644 --- a/src/lib/findRef.ts +++ b/src/lib/findRef.ts @@ -1,6 +1,6 @@ -import { Ref } from "../types/api/ref"; +import type { Ref } from "../types/api/ref" -import { PrismicError } from "../errors/PrismicError"; +import { PrismicError } from "../errors/PrismicError" /** * Returns the first ref from a list that passes a filter (a function that @@ -15,11 +15,11 @@ import { PrismicError } from "../errors/PrismicError"; * @throws If a matching ref cannot be found. */ export const findRef = (refs: Ref[], filter: (ref: Ref) => boolean): Ref => { - const ref = refs.find((ref) => filter(ref)); + const ref = refs.find((ref) => filter(ref)) if (!ref) { - throw new PrismicError("Ref could not be found.", undefined, undefined); + throw new PrismicError("Ref could not be found.", undefined, undefined) } - return ref; -}; + return ref +} diff --git a/src/lib/findRefByID.ts b/src/lib/findRefByID.ts index 29552b8e..976f7d21 100644 --- a/src/lib/findRefByID.ts +++ b/src/lib/findRefByID.ts @@ -1,6 +1,6 @@ -import { Ref } from "../types/api/ref"; +import type { Ref } from "../types/api/ref" -import { findRef } from "./findRef"; +import { findRef } from "./findRef" /** * Returns the ref from a list of given refs with a matching ID. @@ -13,5 +13,5 @@ import { findRef } from "./findRef"; * @throws If a matching ref cannot be found. */ export const findRefByID = (refs: Ref[], id: string): Ref => { - return findRef(refs, (ref) => ref.id === id); -}; + return findRef(refs, (ref) => ref.id === id) +} diff --git a/src/lib/findRefByLabel.ts b/src/lib/findRefByLabel.ts index aefb3b40..ec8c7cb2 100644 --- a/src/lib/findRefByLabel.ts +++ b/src/lib/findRefByLabel.ts @@ -1,6 +1,6 @@ -import { Ref } from "../types/api/ref"; +import type { Ref } from "../types/api/ref" -import { findRef } from "./findRef"; +import { findRef } from "./findRef" /** * Returns the ref from a list of given refs with a matching label. @@ -13,5 +13,5 @@ import { findRef } from "./findRef"; * @throws If a matching ref cannot be found. */ export const findRefByLabel = (refs: Ref[], label: string): Ref => { - return findRef(refs, (ref) => ref.label === label); -}; + return findRef(refs, (ref) => ref.label === label) +} diff --git a/src/lib/getPreviewCookie.ts b/src/lib/getPreviewCookie.ts index eee6bcf7..19138bf3 100644 --- a/src/lib/getPreviewCookie.ts +++ b/src/lib/getPreviewCookie.ts @@ -1,8 +1,8 @@ -import { preview as previewCookieName } from "../cookie"; +import { preview as previewCookieName } from "../cookie" const readValue = (value: string): string => { - return value.replace(/%3B/g, ";"); -}; + return value.replace(/%3B/g, ";") +} /** * Returns the value of a cookie from a given cookie store. @@ -13,19 +13,19 @@ const readValue = (value: string): string => { * @returns The value of the cookie, if it exists. */ export const getPreviewCookie = (cookieJar: string): string | undefined => { - const cookies = cookieJar.split("; "); + const cookies = cookieJar.split("; ") - let value: string | undefined; + let value: string | undefined for (const cookie of cookies) { - const parts = cookie.split("="); - const name = readValue(parts[0]).replace(/%3D/g, "="); + const parts = cookie.split("=") + const name = readValue(parts[0]).replace(/%3D/g, "=") if (name === previewCookieName) { - value = readValue(parts.slice(1).join("=")); - break; + value = readValue(parts.slice(1).join("=")) + break } } - return value; -}; + return value +} diff --git a/src/lib/hastSerializerHelpers.ts b/src/lib/hastSerializerHelpers.ts index 3692aacc..1ab57fb4 100644 --- a/src/lib/hastSerializerHelpers.ts +++ b/src/lib/hastSerializerHelpers.ts @@ -1,13 +1,17 @@ -import { Element } from "hast"; -import { toHtml } from "hast-util-to-html"; +import type { Element } from "hast" +import { toHtml } from "hast-util-to-html" -import { OEmbedType } from "../types/value/embed"; -import { LinkType } from "../types/value/link"; -import { RTEmbedNode, RTImageNode, RTLinkNode } from "../types/value/richText"; +import { OEmbedType } from "../types/value/embed" +import { LinkType } from "../types/value/link" +import type { + RTEmbedNode, + RTImageNode, + RTLinkNode, +} from "../types/value/richText" -import { PrismicRichTextSerializerError } from "../errors/PrismicRichTextSerializerError"; +import { PrismicRichTextSerializerError } from "../errors/PrismicRichTextSerializerError" -import { RTPartialInlineNode } from "./RichTextFieldBuilder"; +import type { RTPartialInlineNode } from "./RichTextFieldBuilder" /** * Serializes a hast {@link Element} node to a {@link RTImageNode}. @@ -17,43 +21,43 @@ import { RTPartialInlineNode } from "./RichTextFieldBuilder"; * @returns Equivalent {@link RTImageNode}. */ export const serializeImage = (node: Element): RTImageNode => { - const src = node.properties?.src as string | undefined; + const src = node.properties?.src as string | undefined if (!src) { throw new PrismicRichTextSerializerError( "Element of type `img` is missing an `src` attribute", - ); + ) } - const url = new URL(src, "https://noop.com"); + const url = new URL(src, "https://noop.com") - let width = node.properties?.width as number | undefined; - let height = node.properties?.height as number | undefined; - let x = 0; - let y = 0; - let zoom = 1; + let width = node.properties?.width as number | undefined + let height = node.properties?.height as number | undefined + let x = 0 + let y = 0 + let zoom = 1 // Attempt to infer the image dimensions from the URL imgix parameters. if (url.hostname === "images.prismic.io") { if (url.searchParams.has("w")) { - width = Number(url.searchParams.get("w")); + width = Number(url.searchParams.get("w")) } if (url.searchParams.has("h")) { - height = Number(url.searchParams.get("h")); + height = Number(url.searchParams.get("h")) } if (url.searchParams.has("rect")) { const [rectX, rextY, rectW, _rectH] = url.searchParams .get("rect")! - .split(","); + .split(",") - x = Number(rectX); - y = Number(rextY); + x = Number(rectX) + y = Number(rextY) // This is not perfect but it's supposed to work on images without constraints. if (width) { - zoom = Math.max(1, width / Number(rectW)); + zoom = Math.max(1, width / Number(rectW)) } } } @@ -69,8 +73,8 @@ export const serializeImage = (node: Element): RTImageNode => { // See: https://github.com/prismicio/prismic-client/pull/342#discussion_r1683650185 dimensions: { width: width as number, height: height as number }, edit: { x, y, zoom, background: "transparent" }, - }; -}; + } +} /** * Serializes a hast {@link Element} node to a {@link RTEmbedNode}. @@ -80,12 +84,12 @@ export const serializeImage = (node: Element): RTImageNode => { * @returns Equivalent {@link RTEmbedNode}. */ export const serializeEmbed = (node: Element): RTEmbedNode => { - const src = node.properties?.src as string | undefined; + const src = node.properties?.src as string | undefined if (!src) { throw new PrismicRichTextSerializerError( "Element of type `embed` is missing an `src` attribute", - ); + ) } const oembedBase = { @@ -93,26 +97,26 @@ export const serializeEmbed = (node: Element): RTEmbedNode => { embed_url: src, html: toHtml(node), title: node.properties?.title as string | undefined, - }; + } - const width = node.properties?.width as number | undefined; - const height = node.properties?.height as number | undefined; + const width = node.properties?.width as number | undefined + const height = node.properties?.height as number | undefined // Remove the children of the embed node as we don't want to process them. - node.children = []; + node.children = [] if (width && height) { return { type: "embed", oembed: { ...oembedBase, type: OEmbedType.Rich, width, height }, - }; + } } else { return { type: "embed", oembed: { ...oembedBase, type: OEmbedType.Link }, - }; + } } -}; +} /** * Serializes a hast {@link Element} node to a {@link RTPartialInlineNode}. @@ -132,11 +136,11 @@ export const serializeSpan = ( rtPartialInlineNode.type === "hyperlink" && !("data" in rtPartialInlineNode) ) { - const url = node.properties?.href as string | undefined; + const url = node.properties?.href as string | undefined if (!url) { throw new PrismicRichTextSerializerError( "Element of type `hyperlink` is missing an `href` attribute", - ); + ) } return { @@ -146,8 +150,8 @@ export const serializeSpan = ( url, target: node.properties?.target as string | undefined, }, - }; + } } - return rtPartialInlineNode; -}; + return rtPartialInlineNode +} diff --git a/src/lib/hastToRichText.ts b/src/lib/hastToRichText.ts index 4c84b0fb..020594e7 100644 --- a/src/lib/hastToRichText.ts +++ b/src/lib/hastToRichText.ts @@ -1,32 +1,32 @@ -import { Element, Root } from "hast"; -import { whitespace } from "hast-util-whitespace"; -import { toString } from "mdast-util-to-string"; -import { visit } from "unist-util-visit"; -import { VFile } from "vfile"; +import type { Element, Root } from "hast" +import { whitespace } from "hast-util-whitespace" +import { toString } from "mdast-util-to-string" +import { visit } from "unist-util-visit" +import type { VFile } from "vfile" -import { +import type { RTBlockNode, RTInlineNode, RTLabelNode, RTTextNode, RichTextField, - RichTextNodeType, -} from "../types/value/richText"; +} from "../types/value/richText" +import { RichTextNodeType } from "../types/value/richText" -import { PrismicRichTextSerializerError } from "../errors/PrismicRichTextSerializerError"; +import { PrismicRichTextSerializerError } from "../errors/PrismicRichTextSerializerError" -import { +import type { RichTextHTMLMapSerializer, RichTextHTMLMapSerializerFunction, RichTextHTMLMapSerializerShorthand, -} from "../helpers/unstable_htmlAsRichText"; +} from "../helpers/unstable_htmlAsRichText" -import { RichTextFieldBuilder } from "./RichTextFieldBuilder"; +import { RichTextFieldBuilder } from "./RichTextFieldBuilder" import { serializeEmbed, serializeImage, serializeSpan, -} from "./hastSerializerHelpers"; +} from "./hastSerializerHelpers" /** * Pick keys from a type, distributing the operation over a union. @@ -38,7 +38,7 @@ import { type DistributedPick< ObjectType, KeyType extends keyof ObjectType, -> = ObjectType extends unknown ? Pick : never; +> = ObjectType extends unknown ? Pick : never const DEFAULT_SERIALIZER: RichTextHTMLMapSerializer = { h1: "heading1", @@ -58,10 +58,10 @@ const DEFAULT_SERIALIZER: RichTextHTMLMapSerializer = { img: "image", iframe: "embed", a: "hyperlink", -}; +} -const VFILE_RULE = "failed-to-serialize-node"; -const VFILE_SOURCE = "prismic"; +const VFILE_RULE = "failed-to-serialize-node" +const VFILE_SOURCE = "prismic" /** * Configuration that determines the output of `toRichText`. @@ -71,15 +71,15 @@ export type HASTToRichTextConfig = { * An optional HTML to rich text serializer. Will be merged with the default * HTML to rich text serializer. */ - serializer?: RichTextHTMLMapSerializer; + serializer?: RichTextHTMLMapSerializer /** * Whether or not the text processed should be marked as right-to-left. * * @defaultValue `false` */ - direction?: "ltr" | "rtl"; -}; + direction?: "ltr" | "rtl" +} /** * Transfor a hast tree to a rich text field. @@ -95,29 +95,29 @@ export const hastToRichText = ( file: VFile, config?: HASTToRichTextConfig, ): RichTextField => { - const builder = new RichTextFieldBuilder(); + const builder = new RichTextFieldBuilder() // Merge the default serializer with the user-provided one. const serializer = { ...DEFAULT_SERIALIZER, ...config?.serializer, - }; + } // Keep track of the last text node type to append text nodes to in // case of an image or an embed node is present inside a paragraph. - let lastRTTextNodeType: RTTextNode["type"] = RichTextNodeType.paragraph; + let lastRTTextNodeType: RTTextNode["type"] = RichTextNodeType.paragraph // Keep track of the last list type to know whether we need to append // `list-item` or `o-list-item` nodes. let lastListType: "group-list-item" | "group-o-list-item" | undefined = - undefined; + undefined visit(tree, (node) => { if (node.type === "element") { // Transforms line break elements to line breaks if (node.tagName === "br") { try { - builder.appendText("\n"); + builder.appendText("\n") } catch (error) { // noop } @@ -126,27 +126,27 @@ export const hastToRichText = ( // Resolves the serializer responsible for the current node. let serializerOrShorthand: | RichTextHTMLMapSerializerShorthand - | RichTextHTMLMapSerializerFunction; + | RichTextHTMLMapSerializerFunction // We give priority to CSS selectors over tag names. if (node.matchesSerializer && node.matchesSerializer in serializer) { - serializerOrShorthand = serializer[node.matchesSerializer]; + serializerOrShorthand = serializer[node.matchesSerializer] } else if (node.tagName in serializer) { - serializerOrShorthand = serializer[node.tagName]; + serializerOrShorthand = serializer[node.tagName] } else { - return; + return } - let shorthand: RichTextHTMLMapSerializerShorthand; + let shorthand: RichTextHTMLMapSerializerShorthand if (typeof serializerOrShorthand === "function") { const shorthandOrNode = serializerOrShorthand({ node, context: { listType: lastListType }, - }); + }) if (!shorthandOrNode) { // Exit on unhandled node. - return; + return } else if ( typeof shorthandOrNode === "object" && "type" in shorthandOrNode @@ -157,39 +157,39 @@ export const hastToRichText = ( case RichTextNodeType.em: case RichTextNodeType.label: case RichTextNodeType.hyperlink: { - const length = toString(node).trimEnd().length; + const length = toString(node).trimEnd().length try { - builder.appendSpan(shorthandOrNode, length); + builder.appendSpan(shorthandOrNode, length) } catch (error) { // Happens when we extract an image/embed node inside an RTTextNode and that // the next children is a span. The last RT node type is then an image/embed // node, so we need to resume a new RT text node. - builder.appendTextNode(lastRTTextNodeType, config?.direction); - builder.appendSpan(shorthandOrNode, length); + builder.appendTextNode(lastRTTextNodeType, config?.direction) + builder.appendSpan(shorthandOrNode, length) } - return; + return } case RichTextNodeType.image: case RichTextNodeType.embed: - builder.appendNode(shorthandOrNode); + builder.appendNode(shorthandOrNode) - return; + return default: - lastRTTextNodeType = shorthandOrNode.type; - builder.appendNode(shorthandOrNode); + lastRTTextNodeType = shorthandOrNode.type + builder.appendNode(shorthandOrNode) - return; + return } } // Else it's a shorthand. - shorthand = shorthandOrNode; + shorthand = shorthandOrNode } else { - shorthand = serializerOrShorthand; + shorthand = serializerOrShorthand } let match: @@ -197,11 +197,11 @@ export const hastToRichText = ( RTBlockNode | Exclude, "type" > - | { type: "label"; data: { label: string } }; + | { type: "label"; data: { label: string } } if (typeof shorthand === "string") { - match = { type: shorthand }; + match = { type: shorthand } } else { - match = { type: RichTextNodeType.label, data: shorthand }; + match = { type: RichTextNodeType.label, data: shorthand } } try { @@ -216,40 +216,40 @@ export const hastToRichText = ( case RichTextNodeType.preformatted: case RichTextNodeType.listItem: case RichTextNodeType.oListItem: - lastRTTextNodeType = match.type; - builder.appendTextNode(match.type, config?.direction); - break; + lastRTTextNodeType = match.type + builder.appendTextNode(match.type, config?.direction) + break case RichTextNodeType.list: case RichTextNodeType.oList: - lastListType = match.type; - break; + lastListType = match.type + break case RichTextNodeType.image: - builder.appendNode(serializeImage(node)); - break; + builder.appendNode(serializeImage(node)) + break case RichTextNodeType.embed: - builder.appendNode(serializeEmbed(node)); - break; + builder.appendNode(serializeEmbed(node)) + break case RichTextNodeType.strong: case RichTextNodeType.em: case RichTextNodeType.label: case RichTextNodeType.hyperlink: { - const span = serializeSpan(node, match); - const length = toString(node).trimEnd().length; + const span = serializeSpan(node, match) + const length = toString(node).trimEnd().length try { - builder.appendSpan(span, length); + builder.appendSpan(span, length) } catch (error) { // Happens when we extract an image/embed node inside an RTTextNode and that // the next children is a span. The last RT node type is then an image/embed // node, so we need to resume a new RT text node. - builder.appendTextNode(lastRTTextNodeType, config?.direction); - builder.appendSpan(span, length); + builder.appendTextNode(lastRTTextNodeType, config?.direction) + builder.appendSpan(span, length) } - break; + break } default: @@ -257,7 +257,7 @@ export const hastToRichText = ( `Unknown rich text node type: \`${ (match as { type: string }).type }\``, - ); + ) } } catch (error) { if (error instanceof PrismicRichTextSerializerError) { @@ -266,29 +266,29 @@ export const hastToRichText = ( place: node.position, ruleId: VFILE_RULE, source: VFILE_SOURCE, - }); + }) - return; + return } - throw error; + throw error } } else if (node.type === "text") { if (!whitespace(node)) { try { - builder.appendText(node.value); + builder.appendText(node.value) } catch (error) { // Happens when we extract an image/embed node inside an RTTextNode. The last RT // node type is then an image/embed node, so we need to resume a new RT text node. - builder.appendTextNode(lastRTTextNodeType, config?.direction); - builder.appendText(node.value); + builder.appendTextNode(lastRTTextNodeType, config?.direction) + builder.appendText(node.value) } } } // We ignore the following node types: // root, doctype, comment, raw - }); + }) - return builder.build(); -}; + return builder.build() +} diff --git a/src/lib/isInternalURL.ts b/src/lib/isInternalURL.ts index c1bb6fa8..6b9e8219 100644 --- a/src/lib/isInternalURL.ts +++ b/src/lib/isInternalURL.ts @@ -7,8 +7,8 @@ */ // TODO: This does not detect all relative URLs as internal such as `about` or `./about`. This function assumes relative URLs start with a "/" or "#"`. export const isInternalURL = (url: string): boolean => { - const isInternal = /^(\/(?!\/)|#)/.test(url); - const isSpecialLink = !isInternal && !/^https?:\/\//.test(url); + const isInternal = /^(\/(?!\/)|#)/.test(url) + const isSpecialLink = !isInternal && !/^https?:\/\//.test(url) - return isInternal && !isSpecialLink; -}; + return isInternal && !isSpecialLink +} diff --git a/src/lib/minifyGraphQLQuery.ts b/src/lib/minifyGraphQLQuery.ts index 67193872..5d8f2305 100644 --- a/src/lib/minifyGraphQLQuery.ts +++ b/src/lib/minifyGraphQLQuery.ts @@ -9,5 +9,5 @@ export const minifyGraphQLQuery = (query: string): string => { return query.replace( /(\n| )*( |{|})(\n| )*/gm, (_chars, _spaces, brackets) => brackets, - ); -}; + ) +} diff --git a/src/lib/rehypeRichText.ts b/src/lib/rehypeRichText.ts index 0f415c7c..a7b987cc 100644 --- a/src/lib/rehypeRichText.ts +++ b/src/lib/rehypeRichText.ts @@ -1,16 +1,17 @@ -import { Element, Root } from "hast"; -import { select, selectAll } from "hast-util-select"; -import rehypeMinifyWhitespace from "rehype-minify-whitespace"; -import { Plugin, Processor } from "unified"; -import { remove } from "unist-util-remove"; -import { SKIP, visit } from "unist-util-visit"; -import { VFile } from "vfile"; +import type { Element, Root } from "hast" +import { select, selectAll } from "hast-util-select" +import rehypeMinifyWhitespace from "rehype-minify-whitespace" +import type { Plugin, Processor } from "unified" +import { remove } from "unist-util-remove" +import { SKIP, visit } from "unist-util-visit" +import type { VFile } from "vfile" -import { CustomTypeModelRichTextField } from "../types/model/richText"; -import { RichTextField } from "../types/value/richText"; +import type { CustomTypeModelRichTextField } from "../types/model/richText" +import type { RichTextField } from "../types/value/richText" -import { filterRichTextField } from "./filterRichTextField"; -import { HASTToRichTextConfig, hastToRichText } from "./hastToRichText"; +import { filterRichTextField } from "./filterRichTextField" +import type { HASTToRichTextConfig } from "./hastToRichText" +import { hastToRichText } from "./hastToRichText" /** * Configuration options for {@link rehypeRichText}. @@ -24,7 +25,7 @@ export type RehypeRichTextConfig = { * * @defaultValue `":root"` - The top-level element of the document. */ - container?: string; + container?: string /** * A list of CSS selectors to exclude matching nodes from the document to @@ -34,7 +35,7 @@ export type RehypeRichTextConfig = { * * @defaultValue `[]` - No nodes are excluded. */ - exclude?: string[]; + exclude?: string[] /** * A list of CSS selectors to include only matching nodes from the document to @@ -44,7 +45,7 @@ export type RehypeRichTextConfig = { * * @defaultValue `[]` - All nodes are included. */ - include?: string[]; + include?: string[] /** * A rich text or title field model definition. When provided the serializer @@ -52,8 +53,8 @@ export type RehypeRichTextConfig = { * * @defaultValue `undefined` - No filtering is applied. */ - model?: CustomTypeModelRichTextField; -} & HASTToRichTextConfig; + model?: CustomTypeModelRichTextField +} & HASTToRichTextConfig /** * A unified plugin that compiles a hast tree to a Prismic rich text field. @@ -77,7 +78,7 @@ export const rehypeRichText: Plugin< undefined, Root, RichTextField - >; + > // We need to exclude nodes _before_ we minify the tree as excluding // nodes could end up in more whitespaces to trim. @@ -85,48 +86,48 @@ export const rehypeRichText: Plugin< return (tree: Root) => { // Extract container node if any is specified. if (config?.container) { - const element = select(config.container, tree); + const element = select(config.container, tree) if (!element) { throw new Error( `No container matching \`${config?.container}\` could be found in the input AST.`, - ); + ) } // We cannot reassign the tree itself, so we instead replace // its children with the found element. - tree.children = [element]; + tree.children = [element] } // Remove excluded nodes if any are specified if (config?.exclude) { // We join selector to only run one query - const nodesToExclude = selectAll(config.exclude.join(", "), tree); + const nodesToExclude = selectAll(config.exclude.join(", "), tree) - remove(tree, (node) => nodesToExclude.includes(node as Element)); + remove(tree, (node) => nodesToExclude.includes(node as Element)) } // Include only nodes to include if (config?.include) { - const nodesToInclude: Element[] = []; + const nodesToInclude: Element[] = [] // We join selector to only run one query - const selector = config.include.join(", "); - const rawNodesToInclude = selectAll(selector, tree); + const selector = config.include.join(", ") + const rawNodesToInclude = selectAll(selector, tree) // We walk the tree to exclude matching nodes that are children of other matching nodes. visit(tree, (node) => { if (rawNodesToInclude.includes(node as Element)) { - nodesToInclude.push(node as Element); + nodesToInclude.push(node as Element) // Stop traversing this part of the tree since we found its matching parent node. - return SKIP; + return SKIP } - }); + }) // We cannot reassign the tree itself, so we instead replace // its children with the found element. - tree.children = nodesToInclude; + tree.children = nodesToInclude } // Mark nodes matching CSS selectors @@ -136,38 +137,38 @@ export const rehypeRichText: Plugin< // Here we want to match anything that's not a valid HTML tag name and treat // it as a CSS selector. See: https://regex101.com/r/LILLWH/1 if (!/^[a-z]+[1-6]?$/.test(key)) { - const matches = selectAll(key, tree); + const matches = selectAll(key, tree) for (let i = 0; i < matches.length; i++) { - matches[i].matchesSerializer = key; + matches[i].matchesSerializer = key } } } } - }; - }); + } + }) // `rehypeRichText` _depends_ on `rehypeMinifyWhitespace`, that's why it's // registered within the plugin rather than on the processor directly. - self.use(rehypeMinifyWhitespace); + self.use(rehypeMinifyWhitespace) - self.compiler = compiler; + self.compiler = compiler function compiler(tree: Root, file: VFile): RichTextField { - const richTextField = hastToRichText(tree, file, config); + const richTextField = hastToRichText(tree, file, config) if (config?.model) { - return filterRichTextField(richTextField, config.model); + return filterRichTextField(richTextField, config.model) } - return richTextField; + return richTextField } -}; +} declare module "unified" { // Register unified processor the result type. interface CompileResultMap { - RichTextField: RichTextField; + RichTextField: RichTextField } } @@ -178,6 +179,6 @@ declare module "hast" { * A serializer this node matches to. Nodes are marked with this property * when they match a CSS selector from the serializer map. */ - matchesSerializer?: string; + matchesSerializer?: string } } diff --git a/src/lib/serializerHelpers.ts b/src/lib/serializerHelpers.ts index b1519e9a..5fa83c01 100644 --- a/src/lib/serializerHelpers.ts +++ b/src/lib/serializerHelpers.ts @@ -1,55 +1,56 @@ -import type { RichTextMapSerializer } from "../richtext/types"; -import { LinkType } from "../types/value/link"; -import { RTAnyNode } from "../types/value/richText"; +import type { RichTextMapSerializer } from "../richtext/types" +import { LinkType } from "../types/value/link" +import type { RTAnyNode } from "../types/value/richText" -import { +import type { HTMLRichTextMapSerializer, HTMLStrictRichTextMapSerializer, -} from "../helpers/asHTML"; -import { LinkResolverFunction, asLink } from "../helpers/asLink"; +} from "../helpers/asHTML" +import type { LinkResolverFunction } from "../helpers/asLink" +import { asLink } from "../helpers/asLink" -import { escapeHTML } from "./escapeHTML"; +import { escapeHTML } from "./escapeHTML" -type Attributes = Record; +type Attributes = Record const formatAttributes = (node: RTAnyNode, attributes: Attributes): string => { - const _attributes = { ...attributes }; + const _attributes = { ...attributes } // Add label to attributes if ("data" in node && "label" in node.data && node.data.label) { _attributes.class = _attributes.class ? `${_attributes.class} ${node.data.label}` - : node.data.label; + : node.data.label } - const result = []; + const result = [] for (const key in _attributes) { - const value = _attributes[key]; + const value = _attributes[key] if (value) { if (typeof value === "boolean") { - result.push(key); + result.push(key) } else { - result.push(`${key}="${escapeHTML(value)}"`); + result.push(`${key}="${escapeHTML(value)}"`) } } } // Add a space at the beginning if there's any result if (result.length) { - result.unshift(""); + result.unshift("") } - return result.join(" "); -}; + return result.join(" ") +} const getGeneralAttributes = ( serializerOrShorthand?: HTMLRichTextMapSerializer[keyof HTMLRichTextMapSerializer], ): Attributes => { return serializerOrShorthand && typeof serializerOrShorthand !== "function" ? serializerOrShorthand - : {}; -}; + : {} +} export const serializeStandardTag = < BlockType extends keyof RichTextMapSerializer, @@ -57,27 +58,27 @@ export const serializeStandardTag = < tag: string, serializerOrShorthand?: HTMLRichTextMapSerializer[BlockType], ): NonNullable => { - const generalAttributes = getGeneralAttributes(serializerOrShorthand); + const generalAttributes = getGeneralAttributes(serializerOrShorthand) return (({ node, children }) => { return `<${tag}${formatAttributes( node, generalAttributes, - )}>${children}`; - }) as NonNullable; -}; + )}>${children}` + }) as NonNullable +} export const serializePreFormatted = ( serializerOrShorthand?: HTMLRichTextMapSerializer["preformatted"], ): NonNullable => { - const generalAttributes = getGeneralAttributes(serializerOrShorthand); + const generalAttributes = getGeneralAttributes(serializerOrShorthand) return ({ node }) => { return `${escapeHTML( node.text, - )}`; - }; -}; + )}` + } +} export const serializeImage = ( linkResolver: @@ -86,7 +87,7 @@ export const serializeImage = ( | null, serializerOrShorthand?: HTMLRichTextMapSerializer["image"], ): NonNullable => { - const generalAttributes = getGeneralAttributes(serializerOrShorthand); + const generalAttributes = getGeneralAttributes(serializerOrShorthand) return ({ node }) => { const attributes = { @@ -94,9 +95,9 @@ export const serializeImage = ( src: node.url, alt: node.alt, copyright: node.copyright, - }; + } - let imageTag = ``; + let imageTag = `` // If the image has a link, we wrap it with an anchor tag if (node.linkTo) { @@ -111,17 +112,17 @@ export const serializeImage = ( text: "", children: imageTag, key: "", - })!; + })! } - return `

${imageTag}

`; - }; -}; + return `

${imageTag}

` + } +} export const serializeEmbed = ( serializerOrShorthand?: HTMLRichTextMapSerializer["embed"], ): NonNullable => { - const generalAttributes = getGeneralAttributes(serializerOrShorthand); + const generalAttributes = getGeneralAttributes(serializerOrShorthand) return ({ node }) => { const attributes = { @@ -129,13 +130,11 @@ export const serializeEmbed = ( ["data-oembed"]: node.oembed.embed_url, ["data-oembed-type"]: node.oembed.type, ["data-oembed-provider"]: node.oembed.provider_name, - }; + } - return `${ - node.oembed.html - }`; - }; -}; + return `${node.oembed.html}` + } +} export const serializeHyperlink = ( linkResolver: @@ -144,31 +143,31 @@ export const serializeHyperlink = ( | null, serializerOrShorthand?: HTMLRichTextMapSerializer["hyperlink"], ): NonNullable => { - const generalAttributes = getGeneralAttributes(serializerOrShorthand); + const generalAttributes = getGeneralAttributes(serializerOrShorthand) return ({ node, children }): string => { const attributes = { ...generalAttributes, - }; + } if (node.data.link_type === LinkType.Web) { - attributes.href = node.data.url; - attributes.target = node.data.target; - attributes.rel = "noopener noreferrer"; + attributes.href = node.data.url + attributes.target = node.data.target + attributes.rel = "noopener noreferrer" } else if (node.data.link_type === LinkType.Document) { - attributes.href = asLink(node.data, { linkResolver }); + attributes.href = asLink(node.data, { linkResolver }) } else if (node.data.link_type === LinkType.Media) { - attributes.href = node.data.url; + attributes.href = node.data.url } - return `${children}
`; - }; -}; + return `${children}` + } +} export const serializeSpan = (): NonNullable< HTMLStrictRichTextMapSerializer["span"] > => { return ({ text }): string => { - return text ? escapeHTML(text).replace(/\n/g, "
") : ""; - }; -}; + return text ? escapeHTML(text).replace(/\n/g, "
") : "" + } +} diff --git a/src/lib/someTagsFilter.ts b/src/lib/someTagsFilter.ts index cbfb0470..d17b2734 100644 --- a/src/lib/someTagsFilter.ts +++ b/src/lib/someTagsFilter.ts @@ -1,6 +1,6 @@ -import { filter } from "../filter"; +import { filter } from "../filter" -import { castArray } from "./castArray"; +import { castArray } from "./castArray" /** * Creates a filter to filter content by document tags. At least one matching @@ -11,5 +11,5 @@ import { castArray } from "./castArray"; * @returns A filter that can be used in a Prismic REST API V2 request. */ export const someTagsFilter = (tags: string | string[]): string => { - return filter.any("document.tags", castArray(tags)); -}; + return filter.any("document.tags", castArray(tags)) +} diff --git a/src/lib/typeFilter.ts b/src/lib/typeFilter.ts index f74548f6..25cb999e 100644 --- a/src/lib/typeFilter.ts +++ b/src/lib/typeFilter.ts @@ -1,4 +1,4 @@ -import { filter } from "../filter"; +import { filter } from "../filter" /** * Creates a filter to filter content by document type. @@ -8,5 +8,5 @@ import { filter } from "../filter"; * @returns A filter that can be used in a Prismic REST API V2 request. */ export const typeFilter = (documentType: string): string => { - return filter.at("document.type", documentType); -}; + return filter.at("document.type", documentType) +} diff --git a/src/richtext/asText.ts b/src/richtext/asText.ts index c82c277f..8e65c7db 100644 --- a/src/richtext/asText.ts +++ b/src/richtext/asText.ts @@ -1,4 +1,4 @@ -import { RTTextNode, RichTextField } from "../types/value/richText"; +import type { RTTextNode, RichTextField } from "../types/value/richText" /** * Serializes a rich text or title field to a plain text string @@ -14,14 +14,14 @@ export const asText = ( richTextField: RichTextField, separator = " ", ): string => { - let result = ""; + let result = "" for (let i = 0; i < richTextField.length; i++) { if ("text" in richTextField[i]) { result += - (result ? separator : "") + (richTextField[i] as RTTextNode).text; + (result ? separator : "") + (richTextField[i] as RTTextNode).text } } - return result; -}; + return result +} diff --git a/src/richtext/asTree.ts b/src/richtext/asTree.ts index 54b44b51..fddfef48 100644 --- a/src/richtext/asTree.ts +++ b/src/richtext/asTree.ts @@ -1,4 +1,4 @@ -import { +import type { RTAnyNode, RTBlockNode, RTInlineNode, @@ -6,14 +6,14 @@ import { RTNode, RTOListItemNode, RTTextNode, - RichTextNodeType, -} from "../types/value/richText"; -import { Tree, TreeNode } from "./types"; +} from "../types/value/richText" +import { RichTextNodeType } from "../types/value/richText" +import type { Tree, TreeNode } from "./types" const uuid = (): string => { - return (++uuid.i).toString(); -}; -uuid.i = 0; + return (++uuid.i).toString() +} +uuid.i = 0 /** * Parses a rich text or title field into a tree @@ -27,18 +27,18 @@ uuid.i = 0; * @returns Tree from given rich text or title field */ export const asTree = (nodes: RTNode[]): Tree => { - const preparedNodes = prepareNodes(nodes); + const preparedNodes = prepareNodes(nodes) - const children: TreeNode[] = []; + const children: TreeNode[] = [] for (let i = 0; i < preparedNodes.length; i++) { - children.push(nodeToTreeNode(preparedNodes[i])); + children.push(nodeToTreeNode(preparedNodes[i])) } return { key: uuid(), children, - }; -}; + } +} const createTreeNode = ( node: RTAnyNode, @@ -50,22 +50,22 @@ const createTreeNode = ( text: "text" in node ? node.text : undefined, node, children, - }; -}; + } +} const createTextTreeNode = (text: string): TreeNode => { return createTreeNode({ type: RichTextNodeType.span, text, spans: [], - }); -}; + }) +} const prepareNodes = (nodes: RTNode[]): RTBlockNode[] => { - const mutNodes: RTBlockNode[] = nodes.slice(0); + const mutNodes: RTBlockNode[] = nodes.slice(0) for (let i = 0; i < mutNodes.length; i++) { - const node = mutNodes[i]; + const node = mutNodes[i] if ( node.type === RichTextNodeType.listItem || @@ -73,49 +73,49 @@ const prepareNodes = (nodes: RTNode[]): RTBlockNode[] => { ) { const items: (RTListItemNode | RTOListItemNode)[] = [ node as RTListItemNode | RTOListItemNode, - ]; + ] while (mutNodes[i + 1] && mutNodes[i + 1].type === node.type) { - items.push(mutNodes[i + 1] as RTListItemNode | RTOListItemNode); - mutNodes.splice(i, 1); + items.push(mutNodes[i + 1] as RTListItemNode | RTOListItemNode) + mutNodes.splice(i, 1) } if (node.type === RichTextNodeType.listItem) { mutNodes[i] = { type: RichTextNodeType.list, items: items as RTListItemNode[], - }; + } } else { mutNodes[i] = { type: RichTextNodeType.oList, items: items as RTOListItemNode[], - }; + } } } } - return mutNodes; -}; + return mutNodes +} const nodeToTreeNode = (node: RTBlockNode): TreeNode => { if ("text" in node) { return createTreeNode( node, textNodeSpansToTreeNodeChildren(node.spans, node), - ); + ) } if ("items" in node) { - const children: TreeNode[] = []; + const children: TreeNode[] = [] for (let i = 0; i < node.items.length; i++) { - children.push(nodeToTreeNode(node.items[i])); + children.push(nodeToTreeNode(node.items[i])) } - return createTreeNode(node, children); + return createTreeNode(node, children) } - return createTreeNode(node); -}; + return createTreeNode(node) +} const textNodeSpansToTreeNodeChildren = ( spans: RTInlineNode[], @@ -123,10 +123,10 @@ const textNodeSpansToTreeNodeChildren = ( parentSpan?: RTInlineNode, ): TreeNode[] => { if (!spans.length) { - return [createTextTreeNode(node.text)]; + return [createTextTreeNode(node.text)] } - const mutSpans: RTInlineNode[] = spans.slice(0); + const mutSpans: RTInlineNode[] = spans.slice(0) // Sort spans using the following criteria: // @@ -138,26 +138,26 @@ const textNodeSpansToTreeNodeChildren = ( // // Sorting using this algorithm ensures proper detection of child // spans. - mutSpans.sort((a, b) => a.start - b.start || b.end - a.end); + mutSpans.sort((a, b) => a.start - b.start || b.end - a.end) - const children: TreeNode[] = []; + const children: TreeNode[] = [] for (let i = 0; i < mutSpans.length; i++) { - const span = mutSpans[i]; - const parentSpanStart = (parentSpan && parentSpan.start) || 0; - const spanStart = span.start - parentSpanStart; - const spanEnd = span.end - parentSpanStart; - const text = node.text.slice(spanStart, spanEnd); + const span = mutSpans[i] + const parentSpanStart = (parentSpan && parentSpan.start) || 0 + const spanStart = span.start - parentSpanStart + const spanEnd = span.end - parentSpanStart + const text = node.text.slice(spanStart, spanEnd) - const childSpans: RTInlineNode[] = []; + const childSpans: RTInlineNode[] = [] for (let j = i; j < mutSpans.length; j++) { - const siblingSpan = mutSpans[j]; + const siblingSpan = mutSpans[j] if (siblingSpan !== span) { if (siblingSpan.start >= span.start && siblingSpan.end <= span.end) { - childSpans.push(siblingSpan); - mutSpans.splice(j, 1); - j--; + childSpans.push(siblingSpan) + mutSpans.splice(j, 1) + j-- } else if ( siblingSpan.start < span.end && siblingSpan.end > span.start @@ -165,20 +165,20 @@ const textNodeSpansToTreeNodeChildren = ( childSpans.push({ ...siblingSpan, end: span.end, - }); + }) mutSpans[j] = { ...siblingSpan, start: span.end, - }; + } } } } if (i === 0 && spanStart > 0) { - children.push(createTextTreeNode(node.text.slice(0, spanStart))); + children.push(createTextTreeNode(node.text.slice(0, spanStart))) } - const spanWithText = { ...span, text }; + const spanWithText = { ...span, text } children.push( createTreeNode( spanWithText, @@ -191,7 +191,7 @@ const textNodeSpansToTreeNodeChildren = ( span, ), ), - ); + ) if (spanEnd < node.text.length) { children.push( @@ -203,9 +203,9 @@ const textNodeSpansToTreeNodeChildren = ( : undefined, ), ), - ); + ) } } - return children; -}; + return children +} diff --git a/src/richtext/composeSerializers.ts b/src/richtext/composeSerializers.ts index 9b632810..62ceb9cc 100644 --- a/src/richtext/composeSerializers.ts +++ b/src/richtext/composeSerializers.ts @@ -1,4 +1,4 @@ -import { RichTextFunctionSerializer } from "./types"; +import type { RichTextFunctionSerializer } from "./types" /** * Takes an array of serializers and returns a serializer applying provided @@ -22,15 +22,15 @@ export const composeSerializers = ( ): RichTextFunctionSerializer => { return (...args) => { for (let i = 0; i < serializers.length; i++) { - const serializer = serializers[i]; + const serializer = serializers[i] if (serializer) { - const res = serializer(...args); + const res = serializer(...args) if (res != null) { - return res; + return res } } } - }; -}; + } +} diff --git a/src/richtext/index.ts b/src/richtext/index.ts index 7085bb21..a388a088 100644 --- a/src/richtext/index.ts +++ b/src/richtext/index.ts @@ -1,14 +1,14 @@ -export { asTree } from "./asTree"; -export { asText } from "./asText"; +export { asTree } from "./asTree" +export { asText } from "./asText" -export { serialize } from "./serialize"; -export { wrapMapSerializer } from "./wrapMapSerializer"; -export { composeSerializers } from "./composeSerializers"; +export { serialize } from "./serialize" +export { wrapMapSerializer } from "./wrapMapSerializer" +export { composeSerializers } from "./composeSerializers" -export { RichTextNodeType as Element } from "../types/value/richText"; +export { RichTextNodeType as Element } from "../types/value/richText" export type { RichTextFunctionSerializer, RichTextMapSerializer, RichTextMapSerializerFunction, -} from "./types"; +} from "./types" diff --git a/src/richtext/serialize.ts b/src/richtext/serialize.ts index e5927c50..a1a1bf4a 100644 --- a/src/richtext/serialize.ts +++ b/src/richtext/serialize.ts @@ -1,7 +1,7 @@ -import type { RichTextField } from "../types/value/richText"; -import { RichTextFunctionSerializer, TreeNode } from "./types"; +import type { RichTextField } from "../types/value/richText" +import type { RichTextFunctionSerializer, TreeNode } from "./types" -import { asTree } from "./asTree"; +import { asTree } from "./asTree" /** * Serializes a rich text or title field with a given serializer @@ -26,29 +26,29 @@ export const serialize = ( return serializeTreeNodes( asTree(richTextField).children, serializer, - ); -}; + ) +} const serializeTreeNodes = ( nodes: TreeNode[], serializer: RichTextFunctionSerializer, ): T[] => { - const serializedTreeNodes: T[] = []; + const serializedTreeNodes: T[] = [] for (let i = 0; i < nodes.length; i++) { - const treeNode = nodes[i]; + const treeNode = nodes[i] const serializedTreeNode = serializer( treeNode.type, treeNode.node, treeNode.text, serializeTreeNodes(treeNode.children, serializer), treeNode.key, - ); + ) if (serializedTreeNode != null) { - serializedTreeNodes.push(serializedTreeNode); + serializedTreeNodes.push(serializedTreeNode) } } - return serializedTreeNodes; -}; + return serializedTreeNodes +} diff --git a/src/richtext/types.ts b/src/richtext/types.ts index 95aac55f..50c76fc7 100644 --- a/src/richtext/types.ts +++ b/src/richtext/types.ts @@ -1,4 +1,4 @@ -import { +import type { RTAnyNode, RTEmNode, RTEmbedNode, @@ -19,9 +19,9 @@ import { RTPreformattedNode, RTSpanNode, RTStrongNode, - RichTextNodeType, RichTextNodeTypes, -} from "../types/value/richText"; +} from "../types/value/richText" +import { RichTextNodeType } from "../types/value/richText" // Serializers @@ -38,7 +38,7 @@ export type RichTextFunctionSerializer = ( text: string | undefined, children: ReturnType[], key: string, -) => ReturnType | null | undefined; +) => ReturnType | null | undefined /** * Map serializer's tag function serializer, can be helpful for typing those @@ -51,12 +51,12 @@ export type RichTextMapSerializerFunction< Node extends RTAnyNode = RTAnyNode, TextType = string | undefined, > = (payload: { - type: Node["type"]; - node: Node; - text: TextType; - children: ReturnType[]; - key: string; -}) => ReturnType | null | undefined; + type: Node["type"] + node: Node + text: TextType + children: ReturnType[] + key: string +}) => ReturnType | null | undefined /** * Serializes a node from a rich text or title field with a map @@ -74,75 +74,75 @@ export type RichTextMapSerializer = { ReturnType, RTHeading1Node, undefined - >; + > heading2?: RichTextMapSerializerFunction< ReturnType, RTHeading2Node, undefined - >; + > heading3?: RichTextMapSerializerFunction< ReturnType, RTHeading3Node, undefined - >; + > heading4?: RichTextMapSerializerFunction< ReturnType, RTHeading4Node, undefined - >; + > heading5?: RichTextMapSerializerFunction< ReturnType, RTHeading5Node, undefined - >; + > heading6?: RichTextMapSerializerFunction< ReturnType, RTHeading6Node, undefined - >; + > paragraph?: RichTextMapSerializerFunction< ReturnType, RTParagraphNode, undefined - >; + > preformatted?: RichTextMapSerializerFunction< ReturnType, RTPreformattedNode, undefined - >; - strong?: RichTextMapSerializerFunction; - em?: RichTextMapSerializerFunction; + > + strong?: RichTextMapSerializerFunction + em?: RichTextMapSerializerFunction listItem?: RichTextMapSerializerFunction< ReturnType, RTListItemNode, undefined - >; + > oListItem?: RichTextMapSerializerFunction< ReturnType, RTOListItemNode, undefined - >; - list?: RichTextMapSerializerFunction; - oList?: RichTextMapSerializerFunction; - image?: RichTextMapSerializerFunction; - embed?: RichTextMapSerializerFunction; - hyperlink?: RichTextMapSerializerFunction; - label?: RichTextMapSerializerFunction; - span?: RichTextMapSerializerFunction; -}; + > + list?: RichTextMapSerializerFunction + oList?: RichTextMapSerializerFunction + image?: RichTextMapSerializerFunction + embed?: RichTextMapSerializerFunction + hyperlink?: RichTextMapSerializerFunction + label?: RichTextMapSerializerFunction + span?: RichTextMapSerializerFunction +} // Tree export interface Tree { - key: string; - children: TreeNode[]; + key: string + children: TreeNode[] } export interface TreeNode { - key: string; - type: RichTextNodeTypes; - text?: string; - node: RTAnyNode; - children: TreeNode[]; + key: string + type: RichTextNodeTypes + text?: string + node: RTAnyNode + children: TreeNode[] } // Helpers @@ -151,4 +151,4 @@ export const RichTextReversedNodeType = { [RichTextNodeType.oListItem]: "oListItem", [RichTextNodeType.list]: "list", [RichTextNodeType.oList]: "oList", -} as const; +} as const diff --git a/src/richtext/wrapMapSerializer.ts b/src/richtext/wrapMapSerializer.ts index ba4566da..42d2f8a2 100644 --- a/src/richtext/wrapMapSerializer.ts +++ b/src/richtext/wrapMapSerializer.ts @@ -1,8 +1,5 @@ -import { - RichTextFunctionSerializer, - RichTextMapSerializer, - RichTextReversedNodeType, -} from "./types"; +import type { RichTextFunctionSerializer, RichTextMapSerializer } from "./types" +import { RichTextReversedNodeType } from "./types" /** * Wraps a map serializer into a regular function serializer @@ -26,7 +23,7 @@ export const wrapMapSerializer = ( (RichTextReversedNodeType[ type as keyof typeof RichTextReversedNodeType ] || type) as keyof RichTextMapSerializer - ]; + ] if (tagSerializer) { return tagSerializer({ @@ -40,7 +37,7 @@ export const wrapMapSerializer = ( children, // @ts-expect-error cannot type check here key, - }); + }) } - }; -}; + } +} diff --git a/src/types/api/query.ts b/src/types/api/query.ts index b0171eb8..311549e7 100644 --- a/src/types/api/query.ts +++ b/src/types/api/query.ts @@ -1,4 +1,4 @@ -import { PrismicDocument } from "../value/document"; +import type { PrismicDocument } from "../value/document" /** * A query response from the Prismic REST API V2. The response contains @@ -12,40 +12,40 @@ export interface Query { /** * The page number for this page of results. */ - page: number; + page: number /** * Maximum number of results per page. */ - results_per_page: number; + results_per_page: number /** * Number of results in this page. */ - results_size: number; + results_size: number /** * Total number of results within all pages. */ - total_results_size: number; + total_results_size: number /** * Total number of pages. */ - total_pages: number; + total_pages: number /** * The Prismic REST API V2 URL to the next page, if one exists. */ - next_page: string | null; + next_page: string | null /** * The Prismic REST API V2 URL to the previous page, if one exists. */ - prev_page: string | null; + prev_page: string | null /** * A paginated list of documents matching the query. */ - results: Document[]; + results: Document[] } diff --git a/src/types/api/ref.ts b/src/types/api/ref.ts index ff3586a5..f0f923e1 100644 --- a/src/types/api/ref.ts +++ b/src/types/api/ref.ts @@ -7,24 +7,24 @@ export interface Ref { /** * The unique identifier for the ref. */ - id: string; + id: string /** * The identifier that should be provided to the API to select a content * version. */ - ref: string; + ref: string /** * A human-readable name for the ref. The master ref is always named "Master". */ - label: string; + label: string /** * Determines if the ref is the master ref. The master ref contains the latest * published content. */ - isMasterRef: boolean; + isMasterRef: boolean /** * If the ref is associated with a Release, this field contains the timestamp @@ -32,5 +32,5 @@ export interface Ref { * * @see More details on Releases: {@link https://prismic.io/docs/guides/draft-plan-and-schedule-content#releases} */ - scheduledAt?: string; + scheduledAt?: string } diff --git a/src/types/api/release.ts b/src/types/api/release.ts index e60b64f6..ef7f65c0 100644 --- a/src/types/api/release.ts +++ b/src/types/api/release.ts @@ -1,4 +1,4 @@ -import { Ref } from "./ref"; +import type { Ref } from "./ref" /** * Metadata for a Release. @@ -9,4 +9,4 @@ import { Ref } from "./ref"; * @see {@link Ref} * @see More details on Releases: {@link https://prismic.io/docs/guides/draft-plan-and-schedule-content#releases} */ -export type Release = Ref; +export type Release = Ref diff --git a/src/types/api/repository.ts b/src/types/api/repository.ts index 066e54f3..aeec2033 100644 --- a/src/types/api/repository.ts +++ b/src/types/api/repository.ts @@ -1,4 +1,4 @@ -import { Ref } from "./ref"; +import type { Ref } from "./ref" /** * Repository metadata returned from the Prismic REST API V2. This data can be @@ -12,70 +12,70 @@ export interface Repository { * * @see {@link Ref} */ - refs: Ref[]; + refs: Ref[] /** * An identifier used to query content with the latest integration fields * data. */ - integrationFieldsRef: string | null; + integrationFieldsRef: string | null /** * A list of languages for the repository. * * @see {@link Language} */ - languages: Language[]; + languages: Language[] /** * A list of the repository's custom type API IDs mapped to their * human-readable name. */ - types: Record; + types: Record /** * @deprecated Tags are only available in the forms object. * * @see More details in the blog post "A change to how the Prismic API handles tags": {@link https://prismic.io/blog/a-change-to-how-the-prismic-api-handles-tags} */ - tags: string[]; + tags: string[] /** * An internally-used list of REST API features for the repository. * * @internal */ - forms: Record; + forms: Record /** * The URL used to begin the OAuth process for the repository. */ - oauth_initiate: string; + oauth_initiate: string /** * The token used for the OAuth process for the repository. */ - oauth_token: string; + oauth_token: string /** * The version of the API. */ - version: string; + version: string /** * Licensing information for the repository content. */ - license: string; + license: string /** * @deprecated Experiments are no longer part of Prismic. */ - experiments: unknown; + experiments: unknown /** * @deprecated Bookmarks are not longer part of Prismic. */ - bookmarks: Record; + bookmarks: Record } /** @@ -85,12 +85,12 @@ export interface Language { /** * A unique identifier for the language. */ - id: string; + id: string /** * The name of the language. */ - name: string; + name: string } /** @@ -100,12 +100,12 @@ export interface Language { * @internal */ export interface Form { - method: "GET"; - enctype: string; - action: string; - name?: string; - rel?: string; - fields: Record; + method: "GET" + enctype: string + action: string + name?: string + rel?: string + fields: Record } /** @@ -115,7 +115,7 @@ export interface Form { * @internal */ export interface FormField { - type: "String" | "Integer"; - multiple: boolean; - default?: string; + type: "String" | "Integer" + multiple: boolean + default?: string } diff --git a/src/types/api/tags.ts b/src/types/api/tags.ts index e783ffaf..1619e598 100644 --- a/src/types/api/tags.ts +++ b/src/types/api/tags.ts @@ -6,4 +6,4 @@ * * @see More details on the Tags API: {@link https://prismic.io/docs/tags-api-technical-reference} */ -export type Tags = Tag[]; +export type Tags = Tag[] diff --git a/src/types/model/boolean.ts b/src/types/model/boolean.ts index bba71f9f..d35e2018 100644 --- a/src/types/model/boolean.ts +++ b/src/types/model/boolean.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A boolean custom type field. @@ -6,11 +6,11 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/boolean} */ export interface CustomTypeModelBooleanField { - type: typeof CustomTypeModelFieldType.Boolean; + type: typeof CustomTypeModelFieldType.Boolean config?: { - label?: string | null; - default_value?: boolean; - placeholder_true?: string; - placeholder_false?: string; - }; + label?: string | null + default_value?: boolean + placeholder_true?: string + placeholder_false?: string + } } diff --git a/src/types/model/color.ts b/src/types/model/color.ts index 5cbd4dab..68c4440c 100644 --- a/src/types/model/color.ts +++ b/src/types/model/color.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A color custom type field. @@ -6,9 +6,9 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/color} */ export interface CustomTypeModelColorField { - type: typeof CustomTypeModelFieldType.Color; + type: typeof CustomTypeModelFieldType.Color config?: { - label?: string | null; - placeholder?: string; - }; + label?: string | null + placeholder?: string + } } diff --git a/src/types/model/contentRelationship.ts b/src/types/model/contentRelationship.ts index cae0f8ca..09f06294 100644 --- a/src/types/model/contentRelationship.ts +++ b/src/types/model/contentRelationship.ts @@ -1,6 +1,6 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" -import type { CustomTypeModelLinkSelectType } from "./link"; +import type { CustomTypeModelLinkSelectType } from "./link" /** * A content relationship custom type field. @@ -11,12 +11,12 @@ export interface CustomTypeModelContentRelationshipField< CustomTypeIDs extends string = string, Tags extends string = string, > { - type: typeof CustomTypeModelFieldType.Link; + type: typeof CustomTypeModelFieldType.Link config?: { - label?: string | null; - placeholder?: string; - select: typeof CustomTypeModelLinkSelectType.Document; - customtypes?: readonly CustomTypeIDs[]; - tags?: readonly Tags[]; - }; + label?: string | null + placeholder?: string + select: typeof CustomTypeModelLinkSelectType.Document + customtypes?: readonly CustomTypeIDs[] + tags?: readonly Tags[] + } } diff --git a/src/types/model/customType.ts b/src/types/model/customType.ts index cf76384c..99518039 100644 --- a/src/types/model/customType.ts +++ b/src/types/model/customType.ts @@ -1,4 +1,4 @@ -import { CustomTypeModelField } from "./types"; +import type { CustomTypeModelField } from "./types" /** * A Prismic custom type model. @@ -13,35 +13,35 @@ export interface CustomTypeModel< /** * The ID of the custom type model. */ - id: ID; + id: ID /** * The human readable name of the custom type model. */ // TODO: Revert to `label?: string | null` if `label` can be partial in: https://github.com/prismicio/prismic-types-internal/blob/HEAD/src/customtypes/CustomType.ts#L39 - label: string | null | undefined; + label: string | null | undefined /** * The format of the custom type model. * * Fallback to "custom" if undefined. */ - format?: "page" | "custom"; + format?: "page" | "custom" /** * Determines if more than one document for the custom type can be created. */ - repeatable: boolean; + repeatable: boolean /** * The custom type model definition. */ - json: Definition; + json: Definition /** * Determines if new documents for the custom type can be created. */ - status: boolean; + status: boolean } /** @@ -52,7 +52,7 @@ export interface CustomTypeModel< export type CustomTypeModelDefinition = Record< TabName, CustomTypeModelTab ->; +> /** * A custom type's tab. Each tab can contain any number of fields but is limited @@ -65,4 +65,4 @@ export type CustomTypeModelTab< string, CustomTypeModelField >, -> = Fields; +> = Fields diff --git a/src/types/model/date.ts b/src/types/model/date.ts index e4c7e561..2c604818 100644 --- a/src/types/model/date.ts +++ b/src/types/model/date.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A date custom type field. @@ -6,10 +6,10 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/date} */ export interface CustomTypeModelDateField { - type: typeof CustomTypeModelFieldType.Date; + type: typeof CustomTypeModelFieldType.Date config?: { - label?: string | null; - placeholder?: string; - default?: string; - }; + label?: string | null + placeholder?: string + default?: string + } } diff --git a/src/types/model/embed.ts b/src/types/model/embed.ts index cb4d59e9..8b72238c 100644 --- a/src/types/model/embed.ts +++ b/src/types/model/embed.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * An embed custom type field. @@ -6,9 +6,9 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/embed} */ export interface CustomTypeModelEmbedField { - type: typeof CustomTypeModelFieldType.Embed; + type: typeof CustomTypeModelFieldType.Embed config?: { - label?: string | null; - placeholder?: string; - }; + label?: string | null + placeholder?: string + } } diff --git a/src/types/model/geoPoint.ts b/src/types/model/geoPoint.ts index b7c36f81..8249fd2b 100644 --- a/src/types/model/geoPoint.ts +++ b/src/types/model/geoPoint.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A geopoint custom type field. @@ -6,8 +6,8 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/geopoint} */ export interface CustomTypeModelGeoPointField { - type: typeof CustomTypeModelFieldType.GeoPoint; + type: typeof CustomTypeModelFieldType.GeoPoint config?: { - label?: string | null; - }; + label?: string | null + } } diff --git a/src/types/model/group.ts b/src/types/model/group.ts index 0ec898eb..99cecd41 100644 --- a/src/types/model/group.ts +++ b/src/types/model/group.ts @@ -2,7 +2,7 @@ import type { CustomTypeModelFieldForGroup, CustomTypeModelFieldForNestedGroup, CustomTypeModelFieldType, -} from "./types"; +} from "./types" /** * A group custom type field. @@ -17,11 +17,11 @@ export interface CustomTypeModelGroupField< CustomTypeModelFieldForGroup >, > { - type: typeof CustomTypeModelFieldType.Group; + type: typeof CustomTypeModelFieldType.Group config?: { - label?: string | null; - fields?: Fields; - }; + label?: string | null + fields?: Fields + } } /** @@ -36,4 +36,4 @@ export type CustomTypeModelNestedGroupField< string, CustomTypeModelFieldForNestedGroup >, -> = CustomTypeModelGroupField; +> = CustomTypeModelGroupField diff --git a/src/types/model/image.ts b/src/types/model/image.ts index 7fe42a09..aae03e88 100644 --- a/src/types/model/image.ts +++ b/src/types/model/image.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * Dimension constraints for an image custom type field. @@ -6,8 +6,8 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/image} */ export interface CustomTypeModelImageConstraint { - width?: number | null; - height?: number | null; + width?: number | null + height?: number | null } /** @@ -17,7 +17,7 @@ export interface CustomTypeModelImageConstraint { */ export interface CustomTypeModelImageThumbnail extends CustomTypeModelImageConstraint { - name: Name; + name: Name } /** @@ -28,10 +28,10 @@ export interface CustomTypeModelImageThumbnail export interface CustomTypeModelImageField< ThumbnailNames extends string = string, > { - type: typeof CustomTypeModelFieldType.Image; + type: typeof CustomTypeModelFieldType.Image config?: { - label?: string | null; - constraint?: CustomTypeModelImageConstraint; - thumbnails?: readonly CustomTypeModelImageThumbnail[]; - }; + label?: string | null + constraint?: CustomTypeModelImageConstraint + thumbnails?: readonly CustomTypeModelImageThumbnail[] + } } diff --git a/src/types/model/integration.ts b/src/types/model/integration.ts index c97a2b58..64f8a2b5 100644 --- a/src/types/model/integration.ts +++ b/src/types/model/integration.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * An integration custom type field. @@ -6,10 +6,10 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/integration-fields} */ export interface CustomTypeModelIntegrationField { - type: typeof CustomTypeModelFieldType.Integration; + type: typeof CustomTypeModelFieldType.Integration config?: { - label?: string | null; - placeholder?: string; - catalog?: string; - }; + label?: string | null + placeholder?: string + catalog?: string + } } diff --git a/src/types/model/keyText.ts b/src/types/model/keyText.ts index 92f5186c..f5c40959 100644 --- a/src/types/model/keyText.ts +++ b/src/types/model/keyText.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A key text custom type field. @@ -6,9 +6,9 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/key-text} */ export interface CustomTypeModelKeyTextField { - type: typeof CustomTypeModelFieldType.Text; + type: typeof CustomTypeModelFieldType.Text config?: { - label?: string | null; - placeholder?: string; - }; + label?: string | null + placeholder?: string + } } diff --git a/src/types/model/link.ts b/src/types/model/link.ts index 73b5dcd6..aa29c8d0 100644 --- a/src/types/model/link.ts +++ b/src/types/model/link.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A link custom type field. @@ -6,15 +6,15 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/link} */ export interface CustomTypeModelLinkField { - type: typeof CustomTypeModelFieldType.Link; + type: typeof CustomTypeModelFieldType.Link config?: { - label?: string | null; - placeholder?: string; + label?: string | null + placeholder?: string select?: | null - | (typeof CustomTypeModelLinkSelectType)[keyof typeof CustomTypeModelLinkSelectType]; - allowTargetBlank?: boolean; - }; + | (typeof CustomTypeModelLinkSelectType)[keyof typeof CustomTypeModelLinkSelectType] + allowTargetBlank?: boolean + } } /** @@ -26,4 +26,4 @@ export const CustomTypeModelLinkSelectType = { Document: "document", Media: "media", Web: "web", -} as const; +} as const diff --git a/src/types/model/linkToMedia.ts b/src/types/model/linkToMedia.ts index fc4ec65b..2b447dbd 100644 --- a/src/types/model/linkToMedia.ts +++ b/src/types/model/linkToMedia.ts @@ -1,6 +1,6 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" -import type { CustomTypeModelLinkSelectType } from "./link"; +import type { CustomTypeModelLinkSelectType } from "./link" /** * A link to media custom type field. @@ -8,10 +8,10 @@ import type { CustomTypeModelLinkSelectType } from "./link"; * More details: {@link https://prismic.io/docs/media} */ export interface CustomTypeModelLinkToMediaField { - type: typeof CustomTypeModelFieldType.Link; + type: typeof CustomTypeModelFieldType.Link config?: { - label?: string | null; - placeholder?: string; - select: typeof CustomTypeModelLinkSelectType.Media; - }; + label?: string | null + placeholder?: string + select: typeof CustomTypeModelLinkSelectType.Media + } } diff --git a/src/types/model/number.ts b/src/types/model/number.ts index 709d56d8..494a3e51 100644 --- a/src/types/model/number.ts +++ b/src/types/model/number.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A number custom type field. @@ -6,11 +6,11 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/number} */ export interface CustomTypeModelNumberField { - type: typeof CustomTypeModelFieldType.Number; + type: typeof CustomTypeModelFieldType.Number config?: { - label?: string | null; - placeholder?: string; - min?: number; - max?: number; - }; + label?: string | null + placeholder?: string + min?: number + max?: number + } } diff --git a/src/types/model/range.ts b/src/types/model/range.ts index 642fd30e..43b4eb09 100644 --- a/src/types/model/range.ts +++ b/src/types/model/range.ts @@ -1,15 +1,15 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * @deprecated - Legacy field. Use `CustomTypeModelNumberField` instead. */ export interface CustomTypeModelRangeField { - type: typeof CustomTypeModelFieldType.Range; + type: typeof CustomTypeModelFieldType.Range config?: { - label?: string | null; - placeholder?: string; - min?: number; - max?: number; - step?: number; - }; + label?: string | null + placeholder?: string + min?: number + max?: number + step?: number + } } diff --git a/src/types/model/richText.ts b/src/types/model/richText.ts index ba68c68c..1c396a4c 100644 --- a/src/types/model/richText.ts +++ b/src/types/model/richText.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A rich text custom type field. @@ -7,7 +7,7 @@ import type { CustomTypeModelFieldType } from "./types"; */ export type CustomTypeModelRichTextField = | CustomTypeModelRichTextMultiField - | CustomTypeModelRichTextSingleField; + | CustomTypeModelRichTextSingleField /** * A rich text custom type field which supports multiple blocks of content. @@ -15,15 +15,15 @@ export type CustomTypeModelRichTextField = * More details: {@link https://prismic.io/docs/rich-text-title} */ export interface CustomTypeModelRichTextMultiField { - type: typeof CustomTypeModelFieldType.StructuredText; + type: typeof CustomTypeModelFieldType.StructuredText config?: { - label?: string | null; - placeholder?: string; - allowTargetBlank?: boolean; - multi?: string; + label?: string | null + placeholder?: string + allowTargetBlank?: boolean + multi?: string // @prismicio/types-internal types `labels` as readonly. - labels?: readonly string[]; - }; + labels?: readonly string[] + } } /** @@ -32,13 +32,13 @@ export interface CustomTypeModelRichTextMultiField { * More details: {@link https://prismic.io/docs/rich-text-title} */ export interface CustomTypeModelRichTextSingleField { - type: typeof CustomTypeModelFieldType.StructuredText; + type: typeof CustomTypeModelFieldType.StructuredText config?: { - label?: string | null; - placeholder?: string; - allowTargetBlank?: boolean; - single?: string; + label?: string | null + placeholder?: string + allowTargetBlank?: boolean + single?: string // @prismicio/types-internal types `labels` as readonly. - labels?: readonly string[]; - }; + labels?: readonly string[] + } } diff --git a/src/types/model/select.ts b/src/types/model/select.ts index 053d1a30..21724978 100644 --- a/src/types/model/select.ts +++ b/src/types/model/select.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A select custom type field. @@ -12,11 +12,11 @@ export interface CustomTypeModelSelectField< Option extends string = string, DefaultValue extends Option = Option, > { - type: typeof CustomTypeModelFieldType.Select; + type: typeof CustomTypeModelFieldType.Select config?: { - label?: string | null; - placeholder?: string; - options?: readonly Option[]; - default_value?: DefaultValue; - }; + label?: string | null + placeholder?: string + options?: readonly Option[] + default_value?: DefaultValue + } } diff --git a/src/types/model/separator.ts b/src/types/model/separator.ts index d6a11946..2b603406 100644 --- a/src/types/model/separator.ts +++ b/src/types/model/separator.ts @@ -1,11 +1,11 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * @deprecated - Legacy field. Do not use. */ export interface CustomTypeModelSeparatorField { - type: typeof CustomTypeModelFieldType.Separator; + type: typeof CustomTypeModelFieldType.Separator config?: { - label?: string | null; - }; + label?: string | null + } } diff --git a/src/types/model/sharedSlice.ts b/src/types/model/sharedSlice.ts index ef664b65..05cc69bf 100644 --- a/src/types/model/sharedSlice.ts +++ b/src/types/model/sharedSlice.ts @@ -1,5 +1,5 @@ -import type { SharedSliceModelVariation } from "./sharedSliceVariation"; -import type { CustomTypeModelSliceType } from "./sliceZone"; +import type { SharedSliceModelVariation } from "./sharedSliceVariation" +import type { CustomTypeModelSliceType } from "./sliceZone" /** * A Prismic shared Slice model. @@ -12,9 +12,9 @@ export interface SharedSliceModel< ID extends string = string, Variation extends SharedSliceModelVariation = SharedSliceModelVariation, > { - type: typeof CustomTypeModelSliceType.SharedSlice; - id: ID; - name: string; - description?: string; - variations: readonly Variation[]; + type: typeof CustomTypeModelSliceType.SharedSlice + id: ID + name: string + description?: string + variations: readonly Variation[] } diff --git a/src/types/model/sharedSliceVariation.ts b/src/types/model/sharedSliceVariation.ts index 4a2d3745..dd89705a 100644 --- a/src/types/model/sharedSliceVariation.ts +++ b/src/types/model/sharedSliceVariation.ts @@ -1,7 +1,7 @@ import type { CustomTypeModelFieldForNestedGroup, CustomTypeModelFieldForSlicePrimary, -} from "./types"; +} from "./types" /** * A shared Slice variation. @@ -22,12 +22,12 @@ export interface SharedSliceModelVariation< CustomTypeModelFieldForNestedGroup > = Record, > { - id: ID; - name: string; - docURL: string; - version: string; - description: string; - primary?: PrimaryFields; - items?: ItemFields; - imageUrl: string; + id: ID + name: string + docURL: string + version: string + description: string + primary?: PrimaryFields + items?: ItemFields + imageUrl: string } diff --git a/src/types/model/slice.ts b/src/types/model/slice.ts index 4cc1d3f8..25d420c2 100644 --- a/src/types/model/slice.ts +++ b/src/types/model/slice.ts @@ -1,7 +1,7 @@ -import type { CustomTypeModelFieldForNestedGroup } from "./types"; +import type { CustomTypeModelFieldForNestedGroup } from "./types" -import type { CustomTypeModelNestedGroupField } from "./group"; -import type { CustomTypeModelSliceType } from "./sliceZone"; +import type { CustomTypeModelNestedGroupField } from "./group" +import type { CustomTypeModelSliceType } from "./sliceZone" /** * A Slice for a custom type. @@ -21,15 +21,15 @@ export interface CustomTypeModelSlice< CustomTypeModelFieldForNestedGroup > = Record, > { - type: typeof CustomTypeModelSliceType.Slice; - fieldset?: string | null; - description?: string; - icon?: string; + type: typeof CustomTypeModelSliceType.Slice + fieldset?: string | null + description?: string + icon?: string display?: | (typeof CustomTypeModelSliceDisplay)[keyof typeof CustomTypeModelSliceDisplay] - | string; - "non-repeat"?: NonRepeatFields; - repeat?: RepeatFields; + | string + "non-repeat"?: NonRepeatFields + repeat?: RepeatFields } /** @@ -40,11 +40,11 @@ export interface CustomTypeModelSlice< export const CustomTypeModelSliceDisplay = { List: "list", Grid: "grid", -} as const; +} as const /** * @deprecated - Legacy slice type. Do not use. */ export type CustomTypeModelLegacySlice = | CustomTypeModelNestedGroupField - | CustomTypeModelFieldForNestedGroup; + | CustomTypeModelFieldForNestedGroup diff --git a/src/types/model/sliceZone.ts b/src/types/model/sliceZone.ts index ef1db3c8..eaa624b3 100644 --- a/src/types/model/sliceZone.ts +++ b/src/types/model/sliceZone.ts @@ -1,6 +1,6 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" -import type { CustomTypeModelLegacySlice, CustomTypeModelSlice } from "./slice"; +import type { CustomTypeModelLegacySlice, CustomTypeModelSlice } from "./slice" /** * A Slice Zone custom type field. @@ -22,12 +22,12 @@ export interface CustomTypeModelSliceZoneField< > { type: | typeof CustomTypeModelFieldType.Slices - | typeof CustomTypeModelFieldType.LegacySlices; - fieldset?: string | null; + | typeof CustomTypeModelFieldType.LegacySlices + fieldset?: string | null config?: { - labels?: Record | null; - choices?: Slices; - }; + labels?: Record | null + choices?: Slices + } } /** @@ -36,8 +36,8 @@ export interface CustomTypeModelSliceZoneField< * More details: {@link https://prismic.io/docs/slice} */ export interface CustomTypeModelSliceLabel { - name: string; - display?: string; + name: string + display?: string } /** @@ -48,7 +48,7 @@ export interface CustomTypeModelSliceLabel { export const CustomTypeModelSliceType = { Slice: "Slice", SharedSlice: "SharedSlice", -} as const; +} as const /** * A shared Slice for a custom type. @@ -56,5 +56,5 @@ export const CustomTypeModelSliceType = { * More details: {@link https://prismic.io/docs/slice} */ export interface CustomTypeModelSharedSlice { - type: typeof CustomTypeModelSliceType.SharedSlice; + type: typeof CustomTypeModelSliceType.SharedSlice } diff --git a/src/types/model/timestamp.ts b/src/types/model/timestamp.ts index e1e7c4c0..b2a53ed4 100644 --- a/src/types/model/timestamp.ts +++ b/src/types/model/timestamp.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A timestamp custom type field. @@ -6,10 +6,10 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/timestamp} */ export interface CustomTypeModelTimestampField { - type: typeof CustomTypeModelFieldType.Timestamp; + type: typeof CustomTypeModelFieldType.Timestamp config?: { - label?: string | null; - placeholder?: string; - default?: string; - }; + label?: string | null + placeholder?: string + default?: string + } } diff --git a/src/types/model/title.ts b/src/types/model/title.ts index 51ba5380..992551a1 100644 --- a/src/types/model/title.ts +++ b/src/types/model/title.ts @@ -1,8 +1,8 @@ -import { CustomTypeModelRichTextSingleField } from "./richText"; +import type { CustomTypeModelRichTextSingleField } from "./richText" /** * A title custom type field. * * More details: {@link https://prismic.io/docs/rich-text-title} */ -export type CustomTypeModelTitleField = CustomTypeModelRichTextSingleField; +export type CustomTypeModelTitleField = CustomTypeModelRichTextSingleField diff --git a/src/types/model/types.ts b/src/types/model/types.ts index 7c09c76d..86e83081 100644 --- a/src/types/model/types.ts +++ b/src/types/model/types.ts @@ -1,27 +1,27 @@ -import type { CustomTypeModelBooleanField } from "./boolean"; -import type { CustomTypeModelColorField } from "./color"; -import type { CustomTypeModelContentRelationshipField } from "./contentRelationship"; -import type { CustomTypeModelDateField } from "./date"; -import type { CustomTypeModelEmbedField } from "./embed"; -import type { CustomTypeModelGeoPointField } from "./geoPoint"; +import type { CustomTypeModelBooleanField } from "./boolean" +import type { CustomTypeModelColorField } from "./color" +import type { CustomTypeModelContentRelationshipField } from "./contentRelationship" +import type { CustomTypeModelDateField } from "./date" +import type { CustomTypeModelEmbedField } from "./embed" +import type { CustomTypeModelGeoPointField } from "./geoPoint" import type { CustomTypeModelGroupField, CustomTypeModelNestedGroupField, -} from "./group"; -import type { CustomTypeModelImageField } from "./image"; -import type { CustomTypeModelIntegrationField } from "./integration"; -import type { CustomTypeModelKeyTextField } from "./keyText"; -import type { CustomTypeModelLinkField } from "./link"; -import type { CustomTypeModelLinkToMediaField } from "./linkToMedia"; -import type { CustomTypeModelNumberField } from "./number"; -import type { CustomTypeModelRangeField } from "./range"; -import type { CustomTypeModelRichTextField } from "./richText"; -import type { CustomTypeModelSelectField } from "./select"; -import type { CustomTypeModelSeparatorField } from "./separator"; -import type { CustomTypeModelSliceZoneField } from "./sliceZone"; -import type { CustomTypeModelTimestampField } from "./timestamp"; -import type { CustomTypeModelTitleField } from "./title"; -import type { CustomTypeModelUIDField } from "./uid"; +} from "./group" +import type { CustomTypeModelImageField } from "./image" +import type { CustomTypeModelIntegrationField } from "./integration" +import type { CustomTypeModelKeyTextField } from "./keyText" +import type { CustomTypeModelLinkField } from "./link" +import type { CustomTypeModelLinkToMediaField } from "./linkToMedia" +import type { CustomTypeModelNumberField } from "./number" +import type { CustomTypeModelRangeField } from "./range" +import type { CustomTypeModelRichTextField } from "./richText" +import type { CustomTypeModelSelectField } from "./select" +import type { CustomTypeModelSeparatorField } from "./separator" +import type { CustomTypeModelSliceZoneField } from "./sliceZone" +import type { CustomTypeModelTimestampField } from "./timestamp" +import type { CustomTypeModelTitleField } from "./title" +import type { CustomTypeModelUIDField } from "./uid" /** * Type identifier for a custom type field. @@ -59,7 +59,7 @@ export const CustomTypeModelFieldType = { * @deprecated - Legacy field type. Use `Slices` instead. */ LegacySlices: "Choice", -} as const; +} as const /** * A custom type field. @@ -68,21 +68,21 @@ export type CustomTypeModelField = | CustomTypeModelUIDField | CustomTypeModelGroupField | CustomTypeModelSliceZoneField - | CustomTypeModelFieldForNestedGroup; + | CustomTypeModelFieldForNestedGroup /** * Any custom type field that is valid for a slice's primary section. */ export type CustomTypeModelFieldForSlicePrimary = | CustomTypeModelGroupField - | CustomTypeModelFieldForNestedGroup; + | CustomTypeModelFieldForNestedGroup /** * Any custom type field that is valid for a group field. */ export type CustomTypeModelFieldForGroup = | CustomTypeModelNestedGroupField - | CustomTypeModelFieldForNestedGroup; + | CustomTypeModelFieldForNestedGroup /** * Any custom type field that is valid for a nested group field. @@ -105,4 +105,4 @@ export type CustomTypeModelFieldForNestedGroup = | CustomTypeModelTitleField | CustomTypeModelKeyTextField | CustomTypeModelTimestampField - | CustomTypeModelSeparatorField; + | CustomTypeModelSeparatorField diff --git a/src/types/model/uid.ts b/src/types/model/uid.ts index 104f974e..95dc5e7e 100644 --- a/src/types/model/uid.ts +++ b/src/types/model/uid.ts @@ -1,4 +1,4 @@ -import type { CustomTypeModelFieldType } from "./types"; +import type { CustomTypeModelFieldType } from "./types" /** * A UID custom type field. @@ -6,9 +6,9 @@ import type { CustomTypeModelFieldType } from "./types"; * More details: {@link https://prismic.io/docs/uid} */ export interface CustomTypeModelUIDField { - type: typeof CustomTypeModelFieldType.UID; + type: typeof CustomTypeModelFieldType.UID config?: { - label?: string | null; - placeholder?: string; - }; + label?: string | null + placeholder?: string + } } diff --git a/src/types/value/boolean.ts b/src/types/value/boolean.ts index 94056d6b..fe20a948 100644 --- a/src/types/value/boolean.ts +++ b/src/types/value/boolean.ts @@ -3,4 +3,4 @@ * * @see More details: {@link https://prismic.io/docs/boolean} */ -export type BooleanField = boolean; +export type BooleanField = boolean diff --git a/src/types/value/color.ts b/src/types/value/color.ts index 585f80d6..804af45c 100644 --- a/src/types/value/color.ts +++ b/src/types/value/color.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" /** * A color field. @@ -8,4 +8,4 @@ import type { FieldState } from "./types"; * @see More details: {@link https://prismic.io/docs/color} */ export type ColorField = - State extends "empty" ? null : `#${string}`; + State extends "empty" ? null : `#${string}` diff --git a/src/types/value/contentRelationship.ts b/src/types/value/contentRelationship.ts index dbc788d6..00438e44 100644 --- a/src/types/value/contentRelationship.ts +++ b/src/types/value/contentRelationship.ts @@ -1,8 +1,8 @@ -import type { AnyRegularField, FieldState } from "./types"; +import type { AnyRegularField, FieldState } from "./types" -import type { GroupField } from "./group"; -import type { EmptyLinkField, LinkType } from "./link"; -import type { SliceZone } from "./sliceZone"; +import type { GroupField } from "./group" +import type { EmptyLinkField, LinkType } from "./link" +import type { SliceZone } from "./sliceZone" /** * Field for related documents @@ -22,7 +22,7 @@ export type ContentRelationshipField< State extends FieldState = FieldState, > = State extends "empty" ? EmptyLinkField - : FilledContentRelationshipField; + : FilledContentRelationshipField /** * Links that refer to documents @@ -34,14 +34,14 @@ export interface FilledContentRelationshipField< | Record | unknown = unknown, > { - link_type: typeof LinkType.Document; - id: string; - uid?: string; - type: TypeEnum; - tags: string[]; - lang: LangEnum; - url?: string; - slug?: string; - isBroken?: boolean; - data?: DataInterface; + link_type: typeof LinkType.Document + id: string + uid?: string + type: TypeEnum + tags: string[] + lang: LangEnum + url?: string + slug?: string + isBroken?: boolean + data?: DataInterface } diff --git a/src/types/value/date.ts b/src/types/value/date.ts index b9b2b3f3..096639d3 100644 --- a/src/types/value/date.ts +++ b/src/types/value/date.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" /** * A date field. @@ -8,4 +8,4 @@ import type { FieldState } from "./types"; * @see More details: {@link https://prismic.io/docs/date} */ export type DateField = - State extends "empty" ? null : `${number}-${number}-${number}`; + State extends "empty" ? null : `${number}-${number}-${number}` diff --git a/src/types/value/document.ts b/src/types/value/document.ts index dbf9474b..5d033e94 100644 --- a/src/types/value/document.ts +++ b/src/types/value/document.ts @@ -1,17 +1,17 @@ -import { AnyRegularField } from "./types"; +import type { AnyRegularField } from "./types" -import { GroupField } from "./group"; -import { SliceZone } from "./sliceZone"; -import { TimestampField } from "./timestamp"; +import type { GroupField } from "./group" +import type { SliceZone } from "./sliceZone" +import type { TimestampField } from "./timestamp" /** * Document metadata for a translation of a Prismic document. */ export interface AlternateLanguage { - id: string; - uid?: string; - type: TypeEnum; - lang: LangEnum; + id: string + uid?: string + type: TypeEnum + lang: LangEnum } /** @@ -22,36 +22,36 @@ export interface PrismicDocumentHeader { * The unique identifier for the document. Guaranteed to be unique among all * documents in the Prismic repository. */ - id: string; + id: string /** * The unique identifier for the document. Guaranteed to be unique among all * Prismic documents of the same type. */ - uid: string | null; + uid: string | null /** * Url that refers to document. */ - url: string | null; + url: string | null /** * Type of the document. */ - type: TypeEnum; + type: TypeEnum /** * Href for document. */ - href: string; + href: string /** * Tags associated with document. */ - tags: string[]; + tags: string[] /** * The timestamp at which the document was first published. */ - first_publication_date: TimestampField<"filled">; + first_publication_date: TimestampField<"filled"> /** * The timestamp at which the document was last published. */ - last_publication_date: TimestampField<"filled">; + last_publication_date: TimestampField<"filled"> /** * Slugs associated with document. * @@ -59,19 +59,19 @@ export interface PrismicDocumentHeader { * introduced. Migrate to the UID field. For more details, see * https://community.prismic.io/t/what-are-slugs/6493 */ - slugs: string[]; + slugs: string[] /** * Documents that are related to this document. */ - linked_documents: unknown[]; // TODO: Not sure of the type for this one + linked_documents: unknown[] // TODO: Not sure of the type for this one /** * Language of document. */ - lang: LangEnum; + lang: LangEnum /** * Array to access alternate language versions for document. */ - alternate_languages: AlternateLanguage[]; + alternate_languages: AlternateLanguage[] } /** @@ -91,7 +91,7 @@ export interface PrismicDocument< /** * Data contained in the document. */ - data: DataInterface; + data: DataInterface } /** @@ -117,7 +117,7 @@ export interface PrismicDocumentWithoutUID< * The unique identifier for the document. Guaranteed to be unique among all * Prismic documents of the same type. */ - uid: null; + uid: null } /** @@ -140,5 +140,5 @@ export interface PrismicDocumentWithUID< * The unique identifier for the document. Guaranteed to be unique among all * Prismic documents of the same type. */ - uid: string; + uid: string } diff --git a/src/types/value/embed.ts b/src/types/value/embed.ts index 4e4ae0da..30bfb0ab 100644 --- a/src/types/value/embed.ts +++ b/src/types/value/embed.ts @@ -1,4 +1,4 @@ -import type { EmptyObjectField, FieldState } from "./types"; +import type { EmptyObjectField, FieldState } from "./types" /** * oEmbed 1.0 possible types. @@ -10,7 +10,7 @@ export const OEmbedType = { Video: "video", Link: "link", Rich: "rich", -} as const; +} as const /** * oEmbed response base fields. Those are every mandatory fields an oEmbed @@ -22,13 +22,13 @@ type OEmbedBase = { /** * oEmbed resource type. */ - type: TType; + type: TType /** * oEmbed version number, this must be "1.0". */ - version: string; -}; + version: string +} /** * oEmbed response extra fields. Those are every non-mandatory and unknown @@ -40,47 +40,47 @@ export type OEmbedExtra = { /** * oEmbed text title, describing the resource. */ - title?: string | null; + title?: string | null /** * oEmbed resource author/owner name. */ - author_name?: string | null; + author_name?: string | null /** * oEmbed resource author/owner URL. */ - author_url?: string | null; + author_url?: string | null /** * oEmbed resource provider name. */ - provider_name?: string | null; + provider_name?: string | null /** * oEmbed resource provider URL. */ - provider_url?: string | null; + provider_url?: string | null /** * oEmbed suggested cache lifetime for the resource, in seconds. */ - cache_age?: number | null; + cache_age?: number | null /** * oEmbed resource thumbnail URL. */ - thumbnail_url?: string | null; + thumbnail_url?: string | null /** * oEmbed resource thumbnail width. */ - thumbnail_width?: number | null; + thumbnail_width?: number | null /** * oEmbed resource thumbnail height. */ - thumbnail_height?: number | null; + thumbnail_height?: number | null /** * Providers may optionally include any parameters not specified in this @@ -90,8 +90,8 @@ export type OEmbedExtra = { * * @see oEmbed specification: {@link https://oembed.com} */ - [key: string]: unknown | null; -}; + [key: string]: unknown | null +} /** * oEmbed photo type. Those are every mandatory fields an oEmbed photo response @@ -103,18 +103,18 @@ export type PhotoOEmbed = OEmbedBase & { /** * oEmbed source URL of the image. */ - url: string; + url: string /** * oEmbed width in pixels of the image. */ - width: number; + width: number /** * oEmbed height in pixels of the image. */ - height: number; -}; + height: number +} /** * oEmbed video type. Those are every mandatory fields an oEmbed video response @@ -126,18 +126,18 @@ export type VideoOEmbed = OEmbedBase & { /** * oEmbed HTML required to embed a video player. */ - html: string; + html: string /** * oEmbed width in pixels required to display the HTML. */ - width: number; + width: number /** * oEmbed height in pixels required to display the HTML. */ - height: number; -}; + height: number +} /** * oEmbed link type. Those are every mandatory fields an oEmbed link response @@ -145,7 +145,7 @@ export type VideoOEmbed = OEmbedBase & { * * @see oEmbed specification: {@link https://oembed.com} */ -export type LinkOEmbed = OEmbedBase; +export type LinkOEmbed = OEmbedBase /** * oEmbed rich type. Those are every mandatory fields an oEmbed rich response @@ -157,18 +157,18 @@ export type RichOEmbed = OEmbedBase & { /** * oEmbed HTML required to display the resource. */ - html: string; + html: string /** * oEmbed width in pixels required to display the HTML. */ - width: number; + width: number /** * oEmbed height in pixels required to display the HTML. */ - height: number; -}; + height: number +} /** * Any of the possible types of oEmbed response. Those contains only mandatory @@ -176,7 +176,7 @@ export type RichOEmbed = OEmbedBase & { * * @see oEmbed specification: {@link https://oembed.com} */ -export type AnyOEmbed = PhotoOEmbed | VideoOEmbed | LinkOEmbed | RichOEmbed; +export type AnyOEmbed = PhotoOEmbed | VideoOEmbed | LinkOEmbed | RichOEmbed /** * An embed field. @@ -192,6 +192,6 @@ export type EmbedField< > = State extends "empty" ? EmptyObjectField : Data & { - embed_url: string; - html: string | null; - }; + embed_url: string + html: string | null + } diff --git a/src/types/value/geoPoint.ts b/src/types/value/geoPoint.ts index 73dc0087..b1fa6ce0 100644 --- a/src/types/value/geoPoint.ts +++ b/src/types/value/geoPoint.ts @@ -1,4 +1,4 @@ -import type { EmptyObjectField, FieldState } from "./types"; +import type { EmptyObjectField, FieldState } from "./types" /** * A geopoint field. @@ -11,6 +11,6 @@ export type GeoPointField = State extends "empty" ? EmptyObjectField : { - latitude: number; - longitude: number; - }; + latitude: number + longitude: number + } diff --git a/src/types/value/group.ts b/src/types/value/group.ts index 4498c2b0..34fa4a89 100644 --- a/src/types/value/group.ts +++ b/src/types/value/group.ts @@ -1,4 +1,4 @@ -import type { AnyRegularField, FieldState } from "./types"; +import type { AnyRegularField, FieldState } from "./types" /** * A group field. @@ -11,7 +11,7 @@ export type GroupField< AnyRegularField | NestedGroupField >, State extends FieldState = FieldState, -> = State extends "empty" ? [] : [Fields, ...Fields[]]; +> = State extends "empty" ? [] : [Fields, ...Fields[]] /** * A nested group field. @@ -24,4 +24,4 @@ export type NestedGroupField< AnyRegularField >, State extends FieldState = FieldState, -> = GroupField; +> = GroupField diff --git a/src/types/value/image.ts b/src/types/value/image.ts index 6c51539a..d7672ac8 100644 --- a/src/types/value/image.ts +++ b/src/types/value/image.ts @@ -1,4 +1,4 @@ -import type { FieldState, Simplify } from "./types"; +import type { FieldState, Simplify } from "./types" /** * An individual image within an image field. The base image and each thumbnail @@ -9,32 +9,32 @@ import type { FieldState, Simplify } from "./types"; * @see {@link ImageField} for a full image field type. */ export type ImageFieldImage = - State extends "empty" ? EmptyImageFieldImage : FilledImageFieldImage; + State extends "empty" ? EmptyImageFieldImage : FilledImageFieldImage export interface FilledImageFieldImage { - id: string; - url: string; + id: string + url: string dimensions: { - width: number; - height: number; - }; + width: number + height: number + } edit: { - x: number; - y: number; - zoom: number; - background: string; - }; - alt: string | null; - copyright: string | null; + x: number + y: number + zoom: number + background: string + } + alt: string | null + copyright: string | null } export interface EmptyImageFieldImage { - id?: null; - url?: null; - dimensions?: null; - edit?: null; - alt?: null; - copyright?: null; + id?: null + url?: null + dimensions?: null + edit?: null + alt?: null + copyright?: null } /** @@ -75,4 +75,4 @@ export type ImageField< Record, ImageFieldImage> : ImageFieldImage & Record, ImageFieldImage> - >; + > diff --git a/src/types/value/integration.ts b/src/types/value/integration.ts index c44b04a5..f2cd1dc2 100644 --- a/src/types/value/integration.ts +++ b/src/types/value/integration.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" /** * An integration field. @@ -11,4 +11,4 @@ import type { FieldState } from "./types"; export type IntegrationField< Data extends Record = Record, State extends FieldState = FieldState, -> = State extends "empty" ? null : Data; +> = State extends "empty" ? null : Data diff --git a/src/types/value/keyText.ts b/src/types/value/keyText.ts index 47fee0db..e889f6a9 100644 --- a/src/types/value/keyText.ts +++ b/src/types/value/keyText.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" /** * A key text field @@ -8,4 +8,4 @@ import type { FieldState } from "./types"; * @see More details: {@link https://prismic.io/docs/key-text} */ export type KeyTextField = - State extends "empty" ? null | "" : string; + State extends "empty" ? null | "" : string diff --git a/src/types/value/link.ts b/src/types/value/link.ts index c71f0fa9..2c2439f4 100644 --- a/src/types/value/link.ts +++ b/src/types/value/link.ts @@ -1,9 +1,9 @@ -import type { AnyRegularField, FieldState } from "./types"; +import type { AnyRegularField, FieldState } from "./types" -import type { ContentRelationshipField } from "./contentRelationship"; -import type { GroupField } from "./group"; -import type { LinkToMediaField } from "./linkToMedia"; -import type { SliceZone } from "./sliceZone"; +import type { ContentRelationshipField } from "./contentRelationship" +import type { GroupField } from "./group" +import type { LinkToMediaField } from "./linkToMedia" +import type { SliceZone } from "./sliceZone" /** * Link types @@ -13,7 +13,7 @@ export const LinkType = { Document: "Document", Media: "Media", Web: "Web", -} as const; +} as const /** * For link fields that haven't been filled @@ -23,16 +23,16 @@ export const LinkType = { export type EmptyLinkField< Type extends (typeof LinkType)[keyof typeof LinkType] = typeof LinkType.Any, > = { - link_type: Type | string; -}; + link_type: Type | string +} /** * Link that points to external website */ export interface FilledLinkToWebField { - link_type: typeof LinkType.Web; - url: string; - target?: string; + link_type: typeof LinkType.Web + url: string + target?: string } /** @@ -56,4 +56,4 @@ export type LinkField< : | ContentRelationshipField | FilledLinkToWebField - | LinkToMediaField; + | LinkToMediaField diff --git a/src/types/value/linkToMedia.ts b/src/types/value/linkToMedia.ts index 858910a1..cc43ebb6 100644 --- a/src/types/value/linkToMedia.ts +++ b/src/types/value/linkToMedia.ts @@ -1,6 +1,6 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" -import type { EmptyLinkField, LinkType } from "./link"; +import type { EmptyLinkField, LinkType } from "./link" /** * A link field that points to media. @@ -10,18 +10,18 @@ import type { EmptyLinkField, LinkType } from "./link"; export type LinkToMediaField = State extends "empty" ? EmptyLinkField - : FilledLinkToMediaField; + : FilledLinkToMediaField /** * A link that points to media. */ export interface FilledLinkToMediaField { - id: string; - link_type: typeof LinkType.Media; - name: string; - kind: string; - url: string; - size: string; - height?: string | null; - width?: string | null; + id: string + link_type: typeof LinkType.Media + name: string + kind: string + url: string + size: string + height?: string | null + width?: string | null } diff --git a/src/types/value/number.ts b/src/types/value/number.ts index 8bceab80..c414d4dc 100644 --- a/src/types/value/number.ts +++ b/src/types/value/number.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" /** * A number field. @@ -8,4 +8,4 @@ import type { FieldState } from "./types"; * @see More details: {@link https://prismic.io/docs/number} */ export type NumberField = - State extends "empty" ? null : number; + State extends "empty" ? null : number diff --git a/src/types/value/richText.ts b/src/types/value/richText.ts index 85af0e8a..3156c4aa 100644 --- a/src/types/value/richText.ts +++ b/src/types/value/richText.ts @@ -1,9 +1,9 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" -import type { FilledContentRelationshipField } from "./contentRelationship"; -import type { EmbedField } from "./embed"; -import type { FilledLinkToWebField } from "./link"; -import type { FilledLinkToMediaField } from "./linkToMedia"; +import type { FilledContentRelationshipField } from "./contentRelationship" +import type { EmbedField } from "./embed" +import type { FilledLinkToWebField } from "./link" +import type { FilledLinkToMediaField } from "./linkToMedia" /** * Types enum for RichTextNodes @@ -30,7 +30,7 @@ export const RichTextNodeType = { hyperlink: "hyperlink", label: "label", span: "span", -} as const; +} as const /** * Types for RichTextNodes @@ -38,7 +38,7 @@ export const RichTextNodeType = { * @see More details: {@link https://prismic.io/docs/rich-text-title} */ export type RichTextNodeTypes = - (typeof RichTextNodeType)[keyof typeof RichTextNodeType]; + (typeof RichTextNodeType)[keyof typeof RichTextNodeType] // Text nodes @@ -46,79 +46,79 @@ export type RichTextNodeTypes = * Base to be extended by other rich text nodes. */ export interface RTTextNodeBase { - text: string; - spans: RTInlineNode[]; - direction?: "ltr" | "rtl"; + text: string + spans: RTInlineNode[] + direction?: "ltr" | "rtl" } /** * Rich text `heading1` node */ export interface RTHeading1Node extends RTTextNodeBase { - type: typeof RichTextNodeType.heading1; + type: typeof RichTextNodeType.heading1 } /** * Rich text `heading2` node */ export interface RTHeading2Node extends RTTextNodeBase { - type: typeof RichTextNodeType.heading2; + type: typeof RichTextNodeType.heading2 } /** * Rich text `heading3` node */ export interface RTHeading3Node extends RTTextNodeBase { - type: typeof RichTextNodeType.heading3; + type: typeof RichTextNodeType.heading3 } /** * Rich text `heading4` node */ export interface RTHeading4Node extends RTTextNodeBase { - type: typeof RichTextNodeType.heading4; + type: typeof RichTextNodeType.heading4 } /** * Rich text `heading5` node */ export interface RTHeading5Node extends RTTextNodeBase { - type: typeof RichTextNodeType.heading5; + type: typeof RichTextNodeType.heading5 } /** * Rich text `heading6` node */ export interface RTHeading6Node extends RTTextNodeBase { - type: typeof RichTextNodeType.heading6; + type: typeof RichTextNodeType.heading6 } /** * Rich text `paragraph` node */ export interface RTParagraphNode extends RTTextNodeBase { - type: typeof RichTextNodeType.paragraph; + type: typeof RichTextNodeType.paragraph } /** * Rich text `preformatted` node */ export interface RTPreformattedNode extends RTTextNodeBase { - type: typeof RichTextNodeType.preformatted; + type: typeof RichTextNodeType.preformatted } /** * Rich text `list-item` node */ export interface RTListItemNode extends RTTextNodeBase { - type: typeof RichTextNodeType.listItem; + type: typeof RichTextNodeType.listItem } /** * Rich text `o-list-item` node for ordered lists */ export interface RTOListItemNode extends RTTextNodeBase { - type: typeof RichTextNodeType.oListItem; + type: typeof RichTextNodeType.oListItem } // Span nodes @@ -127,31 +127,31 @@ export interface RTOListItemNode extends RTTextNodeBase { * @internal Span Node base to be extended for other Span nodes */ export interface RTSpanNodeBase { - start: number; - end: number; + start: number + end: number } /** * Rich text `strong` node */ export interface RTStrongNode extends RTSpanNodeBase { - type: typeof RichTextNodeType.strong; + type: typeof RichTextNodeType.strong } /** * Rich text `embed` node */ export interface RTEmNode extends RTSpanNodeBase { - type: typeof RichTextNodeType.em; + type: typeof RichTextNodeType.em } /** * Rich text `label` node */ export interface RTLabelNode extends RTSpanNodeBase { - type: typeof RichTextNodeType.label; + type: typeof RichTextNodeType.label data: { - label: string; - }; + label: string + } } // Media nodes @@ -161,34 +161,34 @@ export interface RTLabelNode extends RTSpanNodeBase { * links and media fields */ export type RTImageNode = { - type: typeof RichTextNodeType.image; - id: string; - url: string; - alt: string | null; - copyright: string | null; + type: typeof RichTextNodeType.image + id: string + url: string + alt: string | null + copyright: string | null dimensions: { - width: number; - height: number; - }; + width: number + height: number + } edit: { - x: number; - y: number; - zoom: number; - background: string; - }; + x: number + y: number + zoom: number + background: string + } linkTo?: | FilledContentRelationshipField | FilledLinkToWebField - | FilledLinkToMediaField; -}; + | FilledLinkToMediaField +} /** * Rich text `embed` node */ export type RTEmbedNode = { - type: typeof RichTextNodeType.embed; - oembed: EmbedField; -}; + type: typeof RichTextNodeType.embed + oembed: EmbedField +} // Link nodes @@ -198,11 +198,11 @@ export type RTEmbedNode = { * @see More details: {@link https://prismic.io/docs/rich-text-title#elements-and-styles} */ export interface RTLinkNode extends RTSpanNodeBase { - type: typeof RichTextNodeType.hyperlink; + type: typeof RichTextNodeType.hyperlink data: | FilledContentRelationshipField | FilledLinkToWebField - | FilledLinkToMediaField; + | FilledLinkToMediaField } // Serialization related nodes @@ -211,16 +211,16 @@ export interface RTLinkNode extends RTSpanNodeBase { * Rich text `list` node */ export interface RTListNode { - type: typeof RichTextNodeType.list; - items: RTListItemNode[]; + type: typeof RichTextNodeType.list + items: RTListItemNode[] } /** * Rich text o-lost node */ export interface RTOListNode { - type: typeof RichTextNodeType.oList; - items: RTOListItemNode[]; + type: typeof RichTextNodeType.oList + items: RTOListItemNode[] } // This one is confusing but it's actually the inner content of a block @@ -228,7 +228,7 @@ export interface RTOListNode { * Rich text `span` node */ export interface RTSpanNode extends RTTextNodeBase { - type: typeof RichTextNodeType.span; + type: typeof RichTextNodeType.span } // Helpers @@ -248,7 +248,7 @@ export type RTNode = | RTListItemNode | RTOListItemNode | RTImageNode - | RTEmbedNode; + | RTEmbedNode /** * Rich text nodes with text @@ -263,7 +263,7 @@ export type RTTextNode = | RTParagraphNode | RTPreformattedNode | RTListItemNode - | RTOListItemNode; + | RTOListItemNode /** * Rich text block nodes @@ -282,17 +282,17 @@ export type RTBlockNode = | RTListNode | RTOListNode | RTImageNode - | RTEmbedNode; + | RTEmbedNode /** * Inline rich text nodes */ -export type RTInlineNode = RTStrongNode | RTEmNode | RTLabelNode | RTLinkNode; +export type RTInlineNode = RTStrongNode | RTEmNode | RTLabelNode | RTLinkNode /** * All rich text nodes */ -export type RTAnyNode = RTBlockNode | RTInlineNode | RTSpanNode; +export type RTAnyNode = RTBlockNode | RTInlineNode | RTSpanNode /** * A rich text field. @@ -300,4 +300,4 @@ export type RTAnyNode = RTBlockNode | RTInlineNode | RTSpanNode; * @see Rich text field documentation: {@link https://prismic.io/docs/rich-text-title} */ export type RichTextField = - State extends "empty" ? [] : [RTNode, ...RTNode[]]; + State extends "empty" ? [] : [RTNode, ...RTNode[]] diff --git a/src/types/value/select.ts b/src/types/value/select.ts index 1a529b9f..f46c05ec 100644 --- a/src/types/value/select.ts +++ b/src/types/value/select.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" /** * A select field. @@ -11,4 +11,4 @@ import type { FieldState } from "./types"; export type SelectField< Enum extends string = string, State extends FieldState = FieldState, -> = State extends "empty" ? null : Enum; +> = State extends "empty" ? null : Enum diff --git a/src/types/value/sharedSlice.ts b/src/types/value/sharedSlice.ts index c3215ee0..0012251d 100644 --- a/src/types/value/sharedSlice.ts +++ b/src/types/value/sharedSlice.ts @@ -1,4 +1,4 @@ -import type { SharedSliceVariation } from "./sharedSliceVariation"; +import type { SharedSliceVariation } from "./sharedSliceVariation" /** * A shared Slice. @@ -9,7 +9,7 @@ export type SharedSlice< SliceType = string, Variations extends SharedSliceVariation = SharedSliceVariation, > = { - slice_type: SliceType; - slice_label: null; - id: string; -} & Variations; + slice_type: SliceType + slice_label: null + id: string +} & Variations diff --git a/src/types/value/sharedSliceVariation.ts b/src/types/value/sharedSliceVariation.ts index b607086c..b20ed215 100644 --- a/src/types/value/sharedSliceVariation.ts +++ b/src/types/value/sharedSliceVariation.ts @@ -1,4 +1,4 @@ -import type { AnyRegularField, AnySlicePrimaryField } from "./types"; +import type { AnyRegularField, AnySlicePrimaryField } from "./types" /** * A shared Slice variation. @@ -14,8 +14,8 @@ export interface SharedSliceVariation< AnyRegularField >, > { - variation: Variation; - version: string; - primary: PrimaryFields; - items: ItemsFields[]; + variation: Variation + version: string + primary: PrimaryFields + items: ItemsFields[] } diff --git a/src/types/value/slice.ts b/src/types/value/slice.ts index 9cb50112..6a0cbd2f 100644 --- a/src/types/value/slice.ts +++ b/src/types/value/slice.ts @@ -1,4 +1,4 @@ -import type { AnyRegularField } from "./types"; +import type { AnyRegularField } from "./types" /** * A Slice - sections of your webpages. @@ -16,9 +16,9 @@ export interface Slice< AnyRegularField >, > { - slice_type: SliceType; - slice_label: string | null; - id: string; - primary: PrimaryFields; - items: ItemsFields[]; + slice_type: SliceType + slice_label: string | null + id: string + primary: PrimaryFields + items: ItemsFields[] } diff --git a/src/types/value/sliceZone.ts b/src/types/value/sliceZone.ts index 2e495500..0a7eebb6 100644 --- a/src/types/value/sliceZone.ts +++ b/src/types/value/sliceZone.ts @@ -1,7 +1,7 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" -import type { SharedSlice } from "./sharedSlice"; -import type { Slice } from "./slice"; +import type { SharedSlice } from "./sharedSlice" +import type { Slice } from "./slice" /** * Prismic Slices are sections of your website. Prismic documents contain a @@ -14,4 +14,4 @@ import type { Slice } from "./slice"; export type SliceZone< Slices extends Slice | SharedSlice = Slice | SharedSlice, State extends FieldState = FieldState, -> = State extends "empty" ? [] : [Slices, ...Slices[]]; +> = State extends "empty" ? [] : [Slices, ...Slices[]] diff --git a/src/types/value/timestamp.ts b/src/types/value/timestamp.ts index 2137102f..5a32bf5a 100644 --- a/src/types/value/timestamp.ts +++ b/src/types/value/timestamp.ts @@ -1,6 +1,6 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" -import type { DateField } from "./date"; +import type { DateField } from "./date" /** * A timestamp field. @@ -10,4 +10,4 @@ import type { DateField } from "./date"; export type TimestampField = State extends "empty" ? null - : `${DateField<"filled">}T${number}:${number}:${number}+${number}`; + : `${DateField<"filled">}T${number}:${number}:${number}+${number}` diff --git a/src/types/value/title.ts b/src/types/value/title.ts index a37678e6..d70fe1e7 100644 --- a/src/types/value/title.ts +++ b/src/types/value/title.ts @@ -1,4 +1,4 @@ -import type { FieldState } from "./types"; +import type { FieldState } from "./types" import type { RTHeading1Node, @@ -7,7 +7,7 @@ import type { RTHeading4Node, RTHeading5Node, RTHeading6Node, -} from "./richText"; +} from "./richText" /** * A title field. @@ -27,6 +27,6 @@ export type TitleField = | RTHeading6Node, "spans" > & { - spans: []; + spans: [] }, - ]; + ] diff --git a/src/types/value/types.ts b/src/types/value/types.ts index 3c144381..73c41d9c 100644 --- a/src/types/value/types.ts +++ b/src/types/value/types.ts @@ -1,30 +1,30 @@ -import type { BooleanField } from "./boolean"; -import type { ColorField } from "./color"; -import type { ContentRelationshipField } from "./contentRelationship"; -import type { DateField } from "./date"; -import type { EmbedField } from "./embed"; -import type { GeoPointField } from "./geoPoint"; -import type { GroupField } from "./group"; -import type { ImageField } from "./image"; -import type { IntegrationField } from "./integration"; -import type { KeyTextField } from "./keyText"; -import type { LinkField } from "./link"; -import type { LinkToMediaField } from "./linkToMedia"; -import type { NumberField } from "./number"; -import type { RichTextField } from "./richText"; -import type { SelectField } from "./select"; -import type { TimestampField } from "./timestamp"; -import type { TitleField } from "./title"; +import type { BooleanField } from "./boolean" +import type { ColorField } from "./color" +import type { ContentRelationshipField } from "./contentRelationship" +import type { DateField } from "./date" +import type { EmbedField } from "./embed" +import type { GeoPointField } from "./geoPoint" +import type { GroupField } from "./group" +import type { ImageField } from "./image" +import type { IntegrationField } from "./integration" +import type { KeyTextField } from "./keyText" +import type { LinkField } from "./link" +import type { LinkToMediaField } from "./linkToMedia" +import type { NumberField } from "./number" +import type { RichTextField } from "./richText" +import type { SelectField } from "./select" +import type { TimestampField } from "./timestamp" +import type { TitleField } from "./title" /** * Empty state for object-shaped fields. */ -export type EmptyObjectField = Record; +export type EmptyObjectField = Record /** * Valid states for fields. Not all fields use this type (e.g. BooleanField). */ -export type FieldState = "empty" | "filled"; +export type FieldState = "empty" | "filled" /** * Any regular field that can be nested in a group-like field. @@ -45,12 +45,12 @@ export type AnyRegularField = | SelectField | BooleanField | GeoPointField - | IntegrationField; + | IntegrationField /** * Any field that can be used in a slice's primary section. */ -export type AnySlicePrimaryField = GroupField | AnyRegularField; +export type AnySlicePrimaryField = GroupField | AnyRegularField /** * Useful to flatten the type output to improve type hints shown in editors. And @@ -62,4 +62,4 @@ export type AnySlicePrimaryField = GroupField | AnyRegularField; * * @see https://github.com/sindresorhus/type-fest/blob/cbd7ec510bd136ac045bbc74e391ee686b8a9a2f/source/simplify.d.ts */ -export type Simplify = { [P in keyof T]: T[P] }; +export type Simplify = { [P in keyof T]: T[P] } diff --git a/src/types/webhook/apiUpdate.ts b/src/types/webhook/apiUpdate.ts index baad6c1f..a79ac3ef 100644 --- a/src/types/webhook/apiUpdate.ts +++ b/src/types/webhook/apiUpdate.ts @@ -1,4 +1,4 @@ -import { WebhookBodyBase, WebhookType } from "./types"; +import type { WebhookBodyBase, WebhookType } from "./types" /** * Webhook payload sent when a Prismic repository content is updated. @@ -6,22 +6,22 @@ import { WebhookBodyBase, WebhookType } from "./types"; * @see More details: {@link https://prismic.io/docs/webhooks} */ export interface WebhookBodyAPIUpdate extends WebhookBodyBase { - type: typeof WebhookType.APIUpdate; - masterRef?: string; - releases: WebhookBodyAPIUpdateOperations; - masks: WebhookBodyAPIUpdateOperations; - tags: WebhookBodyAPIUpdateOperations; - documents: string[]; + type: typeof WebhookType.APIUpdate + masterRef?: string + releases: WebhookBodyAPIUpdateOperations + masks: WebhookBodyAPIUpdateOperations + tags: WebhookBodyAPIUpdateOperations + documents: string[] /** * @deprecated Experiments are no longer supported by Prismic. */ - experiments?: WebhookBodyAPIUpdateOperations; + experiments?: WebhookBodyAPIUpdateOperations } interface WebhookBodyAPIUpdateOperations { - update?: T[]; - addition?: T[]; - deletion?: T[]; + update?: T[] + addition?: T[] + deletion?: T[] } /** @@ -30,8 +30,8 @@ interface WebhookBodyAPIUpdateOperations { * @see More details: {@link https://prismic.io/docs/custom-types} */ interface WebhookBodyAPIUpdateMask { - id: string; - label: string; + id: string + label: string } /** @@ -40,7 +40,7 @@ interface WebhookBodyAPIUpdateMask { * @see More details: {@link https://prismic.io/docs/guides/document-tags} */ interface WebhookBodyAPIUpdateTag { - id: string; + id: string } /** @@ -49,8 +49,8 @@ interface WebhookBodyAPIUpdateTag { * @see More details: {@link https://prismic.io/docs/guides/draft-plan-and-schedule-content#releases} */ interface WebhookBodyAPIUpdateRelease { - id: string; - ref: string; - label: string; - documents: string[]; + id: string + ref: string + label: string + documents: string[] } diff --git a/src/types/webhook/testTrigger.ts b/src/types/webhook/testTrigger.ts index f9244134..19789f3e 100644 --- a/src/types/webhook/testTrigger.ts +++ b/src/types/webhook/testTrigger.ts @@ -1,4 +1,4 @@ -import { WebhookBodyBase, WebhookType } from "./types"; +import type { WebhookBodyBase, WebhookType } from "./types" /** * Webhook payload sent when a test webhook action is triggered. @@ -6,5 +6,5 @@ import { WebhookBodyBase, WebhookType } from "./types"; * @see More details: {@link https://prismic.io/docs/webhooks} */ export interface WebhookBodyTestTrigger extends WebhookBodyBase { - type: typeof WebhookType.TestTrigger; + type: typeof WebhookType.TestTrigger } diff --git a/src/types/webhook/types.ts b/src/types/webhook/types.ts index 6b6ba83c..ee56a58d 100644 --- a/src/types/webhook/types.ts +++ b/src/types/webhook/types.ts @@ -1,7 +1,7 @@ -import { WebhookBodyAPIUpdate } from "./apiUpdate"; -import { WebhookBodyTestTrigger } from "./testTrigger"; +import type { WebhookBodyAPIUpdate } from "./apiUpdate" +import type { WebhookBodyTestTrigger } from "./testTrigger" -export type WebhookBody = WebhookBodyAPIUpdate | WebhookBodyTestTrigger; +export type WebhookBody = WebhookBodyAPIUpdate | WebhookBodyTestTrigger /** * Types of Prismic Webhooks. @@ -11,11 +11,11 @@ export type WebhookBody = WebhookBodyAPIUpdate | WebhookBodyTestTrigger; export const WebhookType = { APIUpdate: "api-update", TestTrigger: "test-trigger", -} as const; +} as const export interface WebhookBodyBase { - type: (typeof WebhookType)[keyof typeof WebhookType]; - domain: string; - apiUrl: string; - secret: string | null; + type: (typeof WebhookType)[keyof typeof WebhookType] + domain: string + apiUrl: string + secret: string | null } diff --git a/test/__fixtures__/document.ts b/test/__fixtures__/document.ts index 3b3962d1..731773a0 100644 --- a/test/__fixtures__/document.ts +++ b/test/__fixtures__/document.ts @@ -1,7 +1,7 @@ -import emptyDocumentJSON from "./emptyDocument.json"; +import emptyDocumentJSON from "./emptyDocument.json" -import * as prismic from "../../src"; +import type * as prismic from "../../src" export const documentFixture = { empty: emptyDocumentJSON as prismic.PrismicDocument, -}; +} diff --git a/test/__fixtures__/htmlRichTextFunctionSerializer.ts b/test/__fixtures__/htmlRichTextFunctionSerializer.ts index ffd7fdf8..531653df 100644 --- a/test/__fixtures__/htmlRichTextFunctionSerializer.ts +++ b/test/__fixtures__/htmlRichTextFunctionSerializer.ts @@ -1,69 +1,70 @@ -import { LinkType } from "../../src"; -import { Element, RichTextFunctionSerializer } from "../../src/richtext"; +import { LinkType } from "../../src" +import type { RichTextFunctionSerializer } from "../../src/richtext" +import { Element } from "../../src/richtext" export const htmlRichTextFunctionSerializer: RichTextFunctionSerializer< string > = (_type, node, text, children) => { switch (node.type) { case Element.heading1: { - return `

${children.join("")}

`; + return `

${children.join("")}

` } case Element.heading2: { - return `

${children.join("")}

`; + return `

${children.join("")}

` } case Element.heading3: { - return `

${children.join("")}

`; + return `

${children.join("")}

` } case Element.heading4: { - return `

${children.join("")}

`; + return `

${children.join("")}

` } case Element.heading5: { - return `
${children.join("")}
`; + return `
${children.join("")}
` } case Element.heading6: { - return `
${children.join("")}
`; + return `
${children.join("")}
` } case Element.paragraph: { - return `

${children.join("")}

`; + return `

${children.join("")}

` } case Element.preformatted: { - return `
${children.join("")}
`; + return `
${children.join("")}
` } case Element.strong: { - return `${children.join("")}`; + return `${children.join("")}` } case Element.em: { - return `${children.join("")}`; + return `${children.join("")}` } case Element.list: { - return `
    ${children.join("")}
`; + return `
    ${children.join("")}
` } case Element.oList: { - return `
    ${children.join("")}
`; + return `
    ${children.join("")}
` } case Element.listItem: case Element.oListItem: { - return `
  • ${children.join("")}
  • `; + return `
  • ${children.join("")}
  • ` } case Element.image: { - return `${node.alt}`; + return `${node.alt}` } case Element.embed: { - return node.oembed.html; + return node.oembed.html } case Element.hyperlink: { @@ -71,27 +72,27 @@ export const htmlRichTextFunctionSerializer: RichTextFunctionSerializer< case LinkType.Web: { return `${children.join("")}`; + }">${children.join("")}` } case LinkType.Document: { return `${children.join( "", - )}`; + )}` } case LinkType.Media: { - return `${children.join("")}`; + return `${children.join("")}` } } } case Element.label: { - return `${children.join("")}`; + return `${children.join("")}` } default: { - return text ? text.replace("\n", "
    ") : ""; + return text ? text.replace("\n", "
    ") : "" } } -}; +} diff --git a/test/__fixtures__/htmlRichTextMapSerializer.ts b/test/__fixtures__/htmlRichTextMapSerializer.ts index c23c8130..0fd2edf1 100644 --- a/test/__fixtures__/htmlRichTextMapSerializer.ts +++ b/test/__fixtures__/htmlRichTextMapSerializer.ts @@ -1,5 +1,5 @@ -import { LinkType } from "../../src"; -import { RichTextMapSerializer } from "../../src/richtext"; +import { LinkType } from "../../src" +import type { RichTextMapSerializer } from "../../src/richtext" export const htmlRichTextMapSerializer: RichTextMapSerializer = { heading1: ({ children }) => `

    ${children.join("")}

    `, @@ -23,21 +23,21 @@ export const htmlRichTextMapSerializer: RichTextMapSerializer = { case LinkType.Web: { return `${children.join("")}`; + }">${children.join("")}` } case LinkType.Document: { return `${children.join( "", - )}`; + )}` } case LinkType.Media: { - return `${children.join("")}`; + return `${children.join("")}` } } }, label: ({ node, children }) => `${children.join("")}`, span: ({ text }) => (text ? text.replace("\n", "
    ") : ""), -}; +} diff --git a/test/__fixtures__/linkResolver.ts b/test/__fixtures__/linkResolver.ts index 722bed41..94178fba 100644 --- a/test/__fixtures__/linkResolver.ts +++ b/test/__fixtures__/linkResolver.ts @@ -1,4 +1,3 @@ -import * as prismic from "../../src"; +import type * as prismic from "../../src" -export const linkResolver: prismic.LinkResolverFunction = (doc) => - `/${doc.uid}`; +export const linkResolver: prismic.LinkResolverFunction = (doc) => `/${doc.uid}` diff --git a/test/__fixtures__/partialHTMLRichTextFunctionSerializer.ts b/test/__fixtures__/partialHTMLRichTextFunctionSerializer.ts index b67f5748..f78af23c 100644 --- a/test/__fixtures__/partialHTMLRichTextFunctionSerializer.ts +++ b/test/__fixtures__/partialHTMLRichTextFunctionSerializer.ts @@ -1,12 +1,12 @@ -import * as prismic from "../../src"; +import * as prismic from "../../src" export const partialHTMLRichTextFunctionSerializer: prismic.HTMLRichTextFunctionSerializer = (_type, node, _text, children) => { switch (node.type) { case prismic.RichTextNodeType.heading1: { - return `

    ${children}

    `; + return `

    ${children}

    ` } } - return null; - }; + return null + } diff --git a/test/__fixtures__/partialHTMLRichTextMapSerializer.ts b/test/__fixtures__/partialHTMLRichTextMapSerializer.ts index 3060ee55..66344d08 100644 --- a/test/__fixtures__/partialHTMLRichTextMapSerializer.ts +++ b/test/__fixtures__/partialHTMLRichTextMapSerializer.ts @@ -1,4 +1,4 @@ -import * as prismic from "../../src"; +import type * as prismic from "../../src" export const partialHTMLRichTextMapSerializer: prismic.HTMLRichTextMapSerializer = { @@ -7,4 +7,4 @@ export const partialHTMLRichTextMapSerializer: prismic.HTMLRichTextMapSerializer heading2: undefined, // `undefined` returning serializers should fallback to default serializer. heading3: () => undefined, - }; + } diff --git a/test/__fixtures__/richText.ts b/test/__fixtures__/richText.ts index c2a103ad..cfc73943 100644 --- a/test/__fixtures__/richText.ts +++ b/test/__fixtures__/richText.ts @@ -1,9 +1,9 @@ -import enRichTextJSON from "./enRichText.json"; -import xssRichTextJSON from "./xssRichText.json"; +import enRichTextJSON from "./enRichText.json" +import xssRichTextJSON from "./xssRichText.json" -import * as prismic from "../../src"; +import type * as prismic from "../../src" export const richTextFixture = { en: enRichTextJSON as prismic.RichTextField, xss: xssRichTextJSON as prismic.RichTextField, -}; +} diff --git a/test/__setup__.ts b/test/__setup__.ts index b33ee3ec..85bfb8b8 100644 --- a/test/__setup__.ts +++ b/test/__setup__.ts @@ -1,36 +1,38 @@ -import { afterAll, beforeAll, beforeEach, vi } from "vitest"; +import { afterAll, beforeAll, beforeEach, vi } from "vitest" -import { MockFactory, createMockFactory } from "@prismicio/mock"; -import AbortController from "abort-controller"; -import { SetupServer, setupServer } from "msw/node"; +import type { MockFactory } from "@prismicio/mock" +import { createMockFactory } from "@prismicio/mock" +import AbortController from "abort-controller" +import type { SetupServer } from "msw/node" +import { setupServer } from "msw/node" -import * as prismic from "../src"; +import * as prismic from "../src" declare module "vitest" { export interface TestContext { - mock: MockFactory; - server: SetupServer; + mock: MockFactory + server: SetupServer } } -const server = setupServer(); +const server = setupServer() -vi.stubGlobal("AbortController", AbortController); +vi.stubGlobal("AbortController", AbortController) beforeAll(() => { - server.listen({ onUnhandledRequest: "error" }); -}); + server.listen({ onUnhandledRequest: "error" }) +}) beforeEach((ctx) => { - ctx.mock = createMockFactory({ seed: ctx.task.name }); - ctx.server = server; + ctx.mock = createMockFactory({ seed: ctx.task.name }) + ctx.server = server // Reset cookies. if (typeof document !== "undefined") { - document.cookie = `foo=bar; ${prismic.cookie.preview}=; baz=qux`; + document.cookie = `foo=bar; ${prismic.cookie.preview}=; baz=qux` } -}); +}) afterAll(() => { - server.close(); -}); + server.close() +}) diff --git a/test/__testutils__/createAuthorizationHeader.ts b/test/__testutils__/createAuthorizationHeader.ts index 10c1614a..1a935867 100644 --- a/test/__testutils__/createAuthorizationHeader.ts +++ b/test/__testutils__/createAuthorizationHeader.ts @@ -1,4 +1,4 @@ export const createAuthorizationHeader = ( accessToken?: string, ): string | undefined => - accessToken != null ? `Token ${accessToken}` : undefined; + accessToken != null ? `Token ${accessToken}` : undefined diff --git a/test/__testutils__/createClient.ts b/test/__testutils__/createClient.ts index 7564880a..e77d14f5 100644 --- a/test/__testutils__/createClient.ts +++ b/test/__testutils__/createClient.ts @@ -1,29 +1,29 @@ -import fetch from "node-fetch"; +import fetch from "node-fetch" -import { createRepositoryName } from "./createRepositoryName"; +import { createRepositoryName } from "./createRepositoryName" -import * as prismic from "../../src"; +import * as prismic from "../../src" type CreateTestClientArgs = ( | { - repositoryName?: string; - apiEndpoint?: never; + repositoryName?: string + apiEndpoint?: never } | { - repositoryName?: never; - apiEndpoint?: string; + repositoryName?: never + apiEndpoint?: string } ) & { - clientConfig?: prismic.ClientConfig; -}; + clientConfig?: prismic.ClientConfig +} export const createTestClient = ( args: CreateTestClientArgs = {}, ): prismic.Client => { - const repositoryName = args.repositoryName || createRepositoryName(); + const repositoryName = args.repositoryName || createRepositoryName() return prismic.createClient(args.apiEndpoint || repositoryName, { fetch, ...args.clientConfig, - }); -}; + }) +} diff --git a/test/__testutils__/createPagedQueryResponses.ts b/test/__testutils__/createPagedQueryResponses.ts index 2e79bc64..7c45c931 100644 --- a/test/__testutils__/createPagedQueryResponses.ts +++ b/test/__testutils__/createPagedQueryResponses.ts @@ -1,24 +1,24 @@ -import { TestContext } from "vitest"; +import type { TestContext } from "vitest" -import * as prismic from "../../src"; +import type * as prismic from "../../src" type CreatePagedQueryResponsesArgs = { - ctx: TestContext; - pages?: number; - pageSize?: number; -}; + ctx: TestContext + pages?: number + pageSize?: number +} export const createPagedQueryResponses = ({ ctx, pages = 2, pageSize = 1, }: CreatePagedQueryResponsesArgs): prismic.Query[] => { - const documents = []; + const documents = [] for (let i = 0; i < pages * pageSize; i++) { - documents.push(ctx.mock.value.document()); + documents.push(ctx.mock.value.document()) } - const responses = []; + const responses = [] for (let page = 1; page <= pages; page++) { responses.push( @@ -27,8 +27,8 @@ export const createPagedQueryResponses = ({ page, documents, }), - ); + ) } - return responses; -}; + return responses +} diff --git a/test/__testutils__/createRepositoryName.ts b/test/__testutils__/createRepositoryName.ts index b7a1af37..b049e632 100644 --- a/test/__testutils__/createRepositoryName.ts +++ b/test/__testutils__/createRepositoryName.ts @@ -1,14 +1,14 @@ -import { expect } from "vitest"; +import { expect } from "vitest" -import * as crypto from "node:crypto"; +import * as crypto from "node:crypto" export const createRepositoryName = (): string => { - const seed = expect.getState().currentTestName; + const seed = expect.getState().currentTestName if (!seed) { throw new Error( `createRepositoryName() can only be called within a Vitest test.`, - ); + ) } - return crypto.createHash("md5").update(seed).digest("hex"); -}; + return crypto.createHash("md5").update(seed).digest("hex") +} diff --git a/test/__testutils__/createRichTextFixtures.ts b/test/__testutils__/createRichTextFixtures.ts index 1744946c..9e4ee5b3 100644 --- a/test/__testutils__/createRichTextFixtures.ts +++ b/test/__testutils__/createRichTextFixtures.ts @@ -1,15 +1,15 @@ -import cnRichTextJSON from "../__fixtures__/cnRichText.json"; -import emojiRichTextJSON from "../__fixtures__/emojiRichText.json"; -import enRichTextJSON from "../__fixtures__/enRichText.json"; -import koRichTextJSON from "../__fixtures__/koRichText.json"; -import overlappedRichTextJSON from "../__fixtures__/overlappedRichText.json"; -import xssRichTextJSON from "../__fixtures__/xssRichText.json"; +import cnRichTextJSON from "../__fixtures__/cnRichText.json" +import emojiRichTextJSON from "../__fixtures__/emojiRichText.json" +import enRichTextJSON from "../__fixtures__/enRichText.json" +import koRichTextJSON from "../__fixtures__/koRichText.json" +import overlappedRichTextJSON from "../__fixtures__/overlappedRichText.json" +import xssRichTextJSON from "../__fixtures__/xssRichText.json" -import type { RichTextField } from "../../src"; +import type { RichTextField } from "../../src" const deepCloneJSON = (json: T): T => { - return JSON.parse(JSON.stringify(json)); -}; + return JSON.parse(JSON.stringify(json)) +} export const createRichTextFixtures = (): Record< "en" | "cn" | "ko" | "emoji" | "overlapped" | "xss", @@ -22,5 +22,5 @@ export const createRichTextFixtures = (): Record< emoji: deepCloneJSON(emojiRichTextJSON) as RichTextField, overlapped: deepCloneJSON(overlappedRichTextJSON) as RichTextField, xss: deepCloneJSON(xssRichTextJSON) as RichTextField, - }; -}; + } +} diff --git a/test/__testutils__/getMasterRef.ts b/test/__testutils__/getMasterRef.ts index 34399d17..98032674 100644 --- a/test/__testutils__/getMasterRef.ts +++ b/test/__testutils__/getMasterRef.ts @@ -1,13 +1,13 @@ -import * as prismic from "../../src"; +import type * as prismic from "../../src" export const getMasterRef = ( repositoryResponse: prismic.Repository, ): string => { - const masterRef = repositoryResponse.refs.find((ref) => ref.isMasterRef); + const masterRef = repositoryResponse.refs.find((ref) => ref.isMasterRef) if (!masterRef) { - throw new Error("Could not find master ref"); + throw new Error("Could not find master ref") } - return masterRef.ref; -}; + return masterRef.ref +} diff --git a/test/__testutils__/mockPrismicRestAPIV2.ts b/test/__testutils__/mockPrismicRestAPIV2.ts index 5f0041a9..d4db1d5e 100644 --- a/test/__testutils__/mockPrismicRestAPIV2.ts +++ b/test/__testutils__/mockPrismicRestAPIV2.ts @@ -1,29 +1,30 @@ -import { TestContext, expect } from "vitest"; +import type { TestContext } from "vitest" +import { expect } from "vitest" -import { rest } from "msw"; +import { rest } from "msw" -import { createRepositoryName } from "./createRepositoryName"; +import { createRepositoryName } from "./createRepositoryName" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -const DEFAULT_DELAY = 0; +const DEFAULT_DELAY = 0 type MockPrismicRestAPIV2Args = { - ctx: TestContext; - accessToken?: string; - repositoryResponse?: prismic.Repository; - queryResponse?: prismic.Query | prismic.Query[]; - queryRequiredParams?: Record; - queryDelay?: number; -}; + ctx: TestContext + accessToken?: string + repositoryResponse?: prismic.Repository + queryResponse?: prismic.Query | prismic.Query[] + queryRequiredParams?: Record + queryDelay?: number +} export const mockPrismicRestAPIV2 = (args: MockPrismicRestAPIV2Args): void => { - const repositoryName = createRepositoryName(); - const repositoryEndpoint = `https://${repositoryName}.cdn.prismic.io/api/v2`; + const repositoryName = createRepositoryName() + const repositoryEndpoint = `https://${repositoryName}.cdn.prismic.io/api/v2` const queryEndpoint = new URL( "documents/search", repositoryEndpoint + "/", - ).toString(); + ).toString() args.ctx.server.use( rest.get(repositoryEndpoint, (req, res, ctx) => { @@ -38,48 +39,47 @@ export const mockPrismicRestAPIV2 = (args: MockPrismicRestAPIV2Args): void => { oauth_initiate: "oauth_initiate", oauth_token: "oauth_token", }), - ); + ) } - const response = - args.repositoryResponse || args.ctx.mock.api.repository(); + const response = args.repositoryResponse || args.ctx.mock.api.repository() - return res(ctx.json(response)); + return res(ctx.json(response)) }), rest.get(queryEndpoint, (req, res, ctx) => { if (args.queryRequiredParams) { for (const paramKey in args.queryRequiredParams) { - const requiredValue = args.queryRequiredParams[paramKey]; + const requiredValue = args.queryRequiredParams[paramKey] expect(req.url.searchParams.getAll(paramKey)).toStrictEqual( Array.isArray(requiredValue) ? requiredValue : [requiredValue], - ); + ) } } if (Array.isArray(args.queryResponse)) { - const page = Number.parseInt(req.url.searchParams.get("page") || "1"); + const page = Number.parseInt(req.url.searchParams.get("page") || "1") - const response = args.queryResponse[page - 1]; + const response = args.queryResponse[page - 1] if (!response) { throw new Error( `A query response was not generated for \`page=${page}\`.`, - ); + ) } return res( ctx.delay(args.queryDelay || DEFAULT_DELAY), ctx.json(response), - ); + ) } else { - const response = args.queryResponse || args.ctx.mock.api.query(); + const response = args.queryResponse || args.ctx.mock.api.query() return res( ctx.delay(args.queryDelay || DEFAULT_DELAY), ctx.json(response), - ); + ) } }), - ); -}; + ) +} diff --git a/test/__testutils__/testAbortableMethod.ts b/test/__testutils__/testAbortableMethod.ts index 6b040ee9..164a194f 100644 --- a/test/__testutils__/testAbortableMethod.ts +++ b/test/__testutils__/testAbortableMethod.ts @@ -1,55 +1,55 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./createClient"; -import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2"; +import { createTestClient } from "./createClient" +import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2" -import * as prismic from "../../src"; +import type * as prismic from "../../src" type TestAbortableMethodArgs = { run: ( client: prismic.Client, params?: Parameters[0], - ) => Promise; -}; + ) => Promise +} export const testAbortableMethod = ( description: string, args: TestAbortableMethodArgs, ): void => { it.concurrent(description, async (ctx) => { - const controller = new AbortController(); - controller.abort(); + const controller = new AbortController() + controller.abort() - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() await expect(async () => { await args.run(client, { fetchOptions: { signal: controller.signal, }, - }); - }).rejects.toThrow(/aborted/i); - }); + }) + }).rejects.toThrow(/aborted/i) + }) // TODO: Remove once the `signal` parameter is removed in favor of // `fetchOptions.signal`. it.concurrent( `${description} (using deprecated \`signal\` param)`, async (ctx) => { - const controller = new AbortController(); - controller.abort(); + const controller = new AbortController() + controller.abort() - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() await expect(async () => { await args.run(client, { signal: controller.signal, - }); - }).rejects.toThrow(/aborted/i); + }) + }).rejects.toThrow(/aborted/i) }, - ); -}; + ) +} diff --git a/test/__testutils__/testAnyGetMethod.ts b/test/__testutils__/testAnyGetMethod.ts index f2605c55..c50d93b4 100644 --- a/test/__testutils__/testAnyGetMethod.ts +++ b/test/__testutils__/testAnyGetMethod.ts @@ -1,10 +1,10 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./createClient"; -import { createPagedQueryResponses } from "./createPagedQueryResponses"; -import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2"; +import { createTestClient } from "./createClient" +import { createPagedQueryResponses } from "./createPagedQueryResponses" +import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2" -import * as prismic from "../../src"; +import type * as prismic from "../../src" type TestGetAllMethodArgs< TResponse extends @@ -15,13 +15,13 @@ type TestGetAllMethodArgs< | prismic.Query | prismic.PrismicDocument[], > = { - run: (client: prismic.Client) => Promise; - requiredParams?: Record; - clientConfig?: prismic.ClientConfig; - resultLimit?: number; - mockedPages?: number; - mockedPageSize?: number; -}; + run: (client: prismic.Client) => Promise + requiredParams?: Record + clientConfig?: prismic.ClientConfig + resultLimit?: number + mockedPages?: number + mockedPageSize?: number +} export const testAnyGetMethodFactory = ( description: string, @@ -33,49 +33,49 @@ export const testAnyGetMethodFactory = ( ctx, pages: args.mockedPages, pageSize: args.mockedPageSize, - }); + }) mockPrismicRestAPIV2({ ctx, queryResponse: queryResponses, queryRequiredParams: args.requiredParams, - }); + }) const client = createTestClient({ clientConfig: args.clientConfig, - }); + }) - const res = await args.run(client); + const res = await args.run(client) switch (mode) { case "get": - expect(res).toStrictEqual(queryResponses[0]); - break; + expect(res).toStrictEqual(queryResponses[0]) + break case "getFirst": - expect(res).toStrictEqual(queryResponses[0].results[0]); - break; + expect(res).toStrictEqual(queryResponses[0].results[0]) + break case "getAll": const allDocs = Object.values(queryResponses).flatMap( (page) => page.results, - ); + ) - expect(res).toStrictEqual(allDocs.slice(0, args.resultLimit)); - break; + expect(res).toStrictEqual(allDocs.slice(0, args.resultLimit)) + break default: - throw new Error(`Unknown mode \`${mode}\``); + throw new Error(`Unknown mode \`${mode}\``) } - }); -}; + }) +} export const testGetMethod = ( description: string, args: TestGetAllMethodArgs, ): void => { - testAnyGetMethodFactory(description, args, "get"); -}; + testAnyGetMethodFactory(description, args, "get") +} export const testGetFirstMethod = ( description: string, @@ -91,8 +91,8 @@ export const testGetFirstMethod = ( }, }, "getFirst", - ); -}; + ) +} export const testGetAllMethod = ( description: string, @@ -108,5 +108,5 @@ export const testGetAllMethod = ( }, }, "getAll", - ); -}; + ) +} diff --git a/test/__testutils__/testAsRichTextHelper.ts b/test/__testutils__/testAsRichTextHelper.ts index 560f35fe..5feffa76 100644 --- a/test/__testutils__/testAsRichTextHelper.ts +++ b/test/__testutils__/testAsRichTextHelper.ts @@ -1,22 +1,19 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { LinkType, asHTML } from "../../src"; -import { - unstable_htmlAsRichText, - unstable_markdownAsRichText, -} from "../../src"; -import type { HTMLAsRichTextConfig } from "../../src/helpers/unstable_htmlAsRichText"; -import type { MarkdownAsRichTextConfig } from "../../src/helpers/unstable_markdownAsRichText"; +import { LinkType, asHTML } from "../../src" +import { unstable_htmlAsRichText, unstable_markdownAsRichText } from "../../src" +import type { HTMLAsRichTextConfig } from "../../src/helpers/unstable_htmlAsRichText" +import type { MarkdownAsRichTextConfig } from "../../src/helpers/unstable_markdownAsRichText" type TestAsRichTextHelperArgs = { - input: string; + input: string - config?: TConfig; + config?: TConfig /** * Warnings that are expected to be present in the output. */ - expectWarnings?: string[]; + expectWarnings?: string[] /** * The rich text format is a lossy representation of HTML. Namely it does not @@ -27,8 +24,8 @@ type TestAsRichTextHelperArgs = { * output to exactly match the input. This flag can be used to tell it to * expect the output to not match the input instead. */ - expectHTMLToMatchInputExactly?: boolean; -}; + expectHTMLToMatchInputExactly?: boolean +} const testAsRichTextHelperFactory = < THelper extends @@ -46,9 +43,9 @@ const testAsRichTextHelperFactory = < helper: THelper, ): void => { it(description, () => { - const output = helper(args.input, args.config); + const output = helper(args.input, args.config) - expect(output.result).toMatchSnapshot(); + expect(output.result).toMatchSnapshot() const outputAsHTML = asHTML(output.result, { serializer: { @@ -59,9 +56,9 @@ const testAsRichTextHelperFactory = < const maybeTarget = node.data.link_type === LinkType.Web && node.data.target ? ` target="${node.data.target}"` - : ""; + : "" - return `${children}`; + return `${children}` }, // A simplified image serializer so that we don't have to // wrap the images in a `div` element like the default @@ -72,29 +69,29 @@ const testAsRichTextHelperFactory = < // attributes the default serializer applies. embed: ({ node }) => node.oembed.html, }, - }); + }) expect(output.warnings.sort()).toStrictEqual( args.expectWarnings?.sort() ?? [], - ); + ) if ( typeof args.expectHTMLToMatchInputExactly === "undefined" || args.expectHTMLToMatchInputExactly ) { - expect(outputAsHTML).toBe(args.input); + expect(outputAsHTML).toBe(args.input) } else { - expect(outputAsHTML).not.toBe(args.input); + expect(outputAsHTML).not.toBe(args.input) } - }); -}; + }) +} export const testHTMLAsRichTextHelper = ( description: string, args: TestAsRichTextHelperArgs, ): void => { - testAsRichTextHelperFactory(description, args, unstable_htmlAsRichText); -}; + testAsRichTextHelperFactory(description, args, unstable_htmlAsRichText) +} export const testMarkdownAsRichTextHelper = ( description: string, @@ -107,5 +104,5 @@ export const testMarkdownAsRichTextHelper = ( description, { ...args, expectHTMLToMatchInputExactly: !args.input }, unstable_markdownAsRichText, - ); -}; + ) +} diff --git a/test/__testutils__/testConcurrentMethod.ts b/test/__testutils__/testConcurrentMethod.ts index e483da48..cd736b4e 100644 --- a/test/__testutils__/testConcurrentMethod.ts +++ b/test/__testutils__/testConcurrentMethod.ts @@ -1,46 +1,46 @@ -import { expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest" -import { rest } from "msw"; -import fetch from "node-fetch"; +import { rest } from "msw" +import fetch from "node-fetch" -import { createTestClient } from "./createClient"; -import { createPagedQueryResponses } from "./createPagedQueryResponses"; -import { createRepositoryName } from "./createRepositoryName"; -import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2"; +import { createTestClient } from "./createClient" +import { createPagedQueryResponses } from "./createPagedQueryResponses" +import { createRepositoryName } from "./createRepositoryName" +import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2" -import * as prismic from "../../src"; +import type * as prismic from "../../src" type TestConcurrentMethodArgs = { run: ( client: prismic.Client, params?: Parameters[0], - ) => Promise; + ) => Promise mode: | "get" | "getAll" | "repository" | "tags" | "resolvePreview" - | "NOT-SHARED___graphQL"; -}; + | "NOT-SHARED___graphQL" +} export const testConcurrentMethod = ( description: string, args: TestConcurrentMethodArgs, ): void => { it.concurrent(description, async (ctx) => { - const fetchSpy = vi.fn(fetch); - const controller1 = new AbortController(); - const controller2 = new AbortController(); + const fetchSpy = vi.fn(fetch) + const controller1 = new AbortController() + const controller2 = new AbortController() - const masterRef = ctx.mock.api.ref({ isMasterRef: true }); - const releaseRef = ctx.mock.api.ref({ isMasterRef: false }); - releaseRef.id = "id"; // Referenced in ref-related tests. - releaseRef.label = "label"; // Referenced in ref-related tests. - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [masterRef, releaseRef]; + const masterRef = ctx.mock.api.ref({ isMasterRef: true }) + const releaseRef = ctx.mock.api.ref({ isMasterRef: false }) + releaseRef.id = "id" // Referenced in ref-related tests. + releaseRef.label = "label" // Referenced in ref-related tests. + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [masterRef, releaseRef] - const queryResponse = createPagedQueryResponses({ ctx }); + const queryResponse = createPagedQueryResponses({ ctx }) mockPrismicRestAPIV2({ ctx, @@ -50,19 +50,19 @@ export const testConcurrentMethod = ( // request. Without the delay, network requests would // not be shared. queryDelay: 10, - }); + }) - const client = createTestClient({ clientConfig: { fetch: fetchSpy } }); + const client = createTestClient({ clientConfig: { fetch: fetchSpy } }) - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } ctx.server.use( rest.get(graphqlURL, (req, res, ctx) => { if (req.headers.get("Prismic-Ref") === masterRef.ref) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) await Promise.all([ // Shared @@ -76,11 +76,11 @@ export const testConcurrentMethod = ( // Shared args.run(client, { signal: controller2.signal }), args.run(client, { signal: controller2.signal }), - ]); + ]) // Not shared - await args.run(client); - await args.run(client); + await args.run(client) + await args.run(client) // `get` methods use a total of 6 requests: // - 1x /api/v2 (shared across all requests) @@ -92,45 +92,45 @@ export const testConcurrentMethod = ( switch (args.mode) { case "get": { - expect(fetchSpy.mock.calls.length).toBe(8); + expect(fetchSpy.mock.calls.length).toBe(8) - break; + break } case "getAll": { - expect(fetchSpy.mock.calls.length).toBe(13); + expect(fetchSpy.mock.calls.length).toBe(13) - break; + break } case "repository": { - expect(fetchSpy.mock.calls.length).toBe(5); + expect(fetchSpy.mock.calls.length).toBe(5) - break; + break } case "tags": { - expect(fetchSpy.mock.calls.length).toBe(8); + expect(fetchSpy.mock.calls.length).toBe(8) - break; + break } case "resolvePreview": { - expect(fetchSpy.mock.calls.length).toBe(8); + expect(fetchSpy.mock.calls.length).toBe(8) - break; + break } // GraphQL requests are not shared. case "NOT-SHARED___graphQL": { - expect(fetchSpy.mock.calls.length).toBe(9); + expect(fetchSpy.mock.calls.length).toBe(9) - break; + break } default: { - throw new Error(`Invalid mode: ${args.mode}`); + throw new Error(`Invalid mode: ${args.mode}`) } } - }); -}; + }) +} diff --git a/test/__testutils__/testFetchOptions.ts b/test/__testutils__/testFetchOptions.ts index d5619209..95161a52 100644 --- a/test/__testutils__/testFetchOptions.ts +++ b/test/__testutils__/testFetchOptions.ts @@ -1,41 +1,41 @@ -import { expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest" -import fetch from "node-fetch"; +import fetch from "node-fetch" -import { createTestClient } from "./createClient"; -import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2"; +import { createTestClient } from "./createClient" +import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2" -import * as prismic from "../../src"; +import type * as prismic from "../../src" type TestFetchOptionsArgs = { run: ( client: prismic.Client, params?: Parameters[0], - ) => Promise; -}; + ) => Promise +} export const testFetchOptions = ( description: string, args: TestFetchOptionsArgs, ): void => { it.concurrent(`${description} (on client)`, async (ctx) => { - const abortController = new AbortController(); + const abortController = new AbortController() - const fetchSpy = vi.fn(fetch); + const fetchSpy = vi.fn(fetch) const fetchOptions: prismic.RequestInitLike = { cache: "no-store", headers: { foo: "bar", }, signal: abortController.signal, - }; + } - const masterRef = ctx.mock.api.ref({ isMasterRef: true }); - const releaseRef = ctx.mock.api.ref({ isMasterRef: false }); - releaseRef.id = "id"; // Referenced in ref-related tests. - releaseRef.label = "label"; // Referenced in ref-related tests. - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [masterRef, releaseRef]; + const masterRef = ctx.mock.api.ref({ isMasterRef: true }) + const releaseRef = ctx.mock.api.ref({ isMasterRef: false }) + releaseRef.id = "id" // Referenced in ref-related tests. + releaseRef.label = "label" // Referenced in ref-related tests. + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [masterRef, releaseRef] mockPrismicRestAPIV2({ ctx, @@ -43,40 +43,40 @@ export const testFetchOptions = ( queryResponse: ctx.mock.api.query({ documents: [ctx.mock.value.document()], }), - }); + }) const client = createTestClient({ clientConfig: { fetch: fetchSpy, fetchOptions, }, - }); + }) - await args.run(client); + await args.run(client) for (const [input, init] of fetchSpy.mock.calls) { - expect(init, input.toString()).toStrictEqual(fetchOptions); + expect(init, input.toString()).toStrictEqual(fetchOptions) } - }); + }) it.concurrent(`${description} (on method)`, async (ctx) => { - const abortController = new AbortController(); + const abortController = new AbortController() - const fetchSpy = vi.fn(fetch); + const fetchSpy = vi.fn(fetch) const fetchOptions: prismic.RequestInitLike = { cache: "no-store", headers: { foo: "bar", }, signal: abortController.signal, - }; + } - const masterRef = ctx.mock.api.ref({ isMasterRef: true }); - const releaseRef = ctx.mock.api.ref({ isMasterRef: false }); - releaseRef.id = "id"; // Referenced in ref-related tests. - releaseRef.label = "label"; // Referenced in ref-related tests. - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [masterRef, releaseRef]; + const masterRef = ctx.mock.api.ref({ isMasterRef: true }) + const releaseRef = ctx.mock.api.ref({ isMasterRef: false }) + releaseRef.id = "id" // Referenced in ref-related tests. + releaseRef.label = "label" // Referenced in ref-related tests. + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [masterRef, releaseRef] mockPrismicRestAPIV2({ ctx, @@ -84,18 +84,18 @@ export const testFetchOptions = ( queryResponse: ctx.mock.api.query({ documents: [ctx.mock.value.document()], }), - }); + }) const client = createTestClient({ clientConfig: { fetch: fetchSpy, }, - }); + }) - await args.run(client, { fetchOptions }); + await args.run(client, { fetchOptions }) for (const [input, init] of fetchSpy.mock.calls) { - expect(init, input.toString()).toStrictEqual(fetchOptions); + expect(init, input.toString()).toStrictEqual(fetchOptions) } - }); -}; + }) +} diff --git a/test/__testutils__/testFilter.ts b/test/__testutils__/testFilter.ts index d1036a57..a61a6203 100644 --- a/test/__testutils__/testFilter.ts +++ b/test/__testutils__/testFilter.ts @@ -1,10 +1,10 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" export const testFilter = ( descriptionAndExpected: string, actual: string, ): void => { it(descriptionAndExpected, () => { - expect(actual).toBe(descriptionAndExpected); - }); -}; + expect(actual).toBe(descriptionAndExpected) + }) +} diff --git a/test/__testutils__/testGetTTL.ts b/test/__testutils__/testGetTTL.ts index 17aa8c6b..1a3d9605 100644 --- a/test/__testutils__/testGetTTL.ts +++ b/test/__testutils__/testGetTTL.ts @@ -1,11 +1,11 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { rest } from "msw"; +import { rest } from "msw" -import { createTestClient } from "./createClient"; -import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2"; +import { createTestClient } from "./createClient" +import { mockPrismicRestAPIV2 } from "./mockPrismicRestAPIV2" -import * as prismic from "../../src"; +import type * as prismic from "../../src" /** * The number of milliseconds in which repository metadata is considered valid. @@ -18,18 +18,18 @@ import * as prismic from "../../src"; * note that changing `REPOSITORY_CACHE_TTL` in the public code may have an * effect on tests using this test-specific constant. */ -export const REPOSITORY_CACHE_TTL = 5000; +export const REPOSITORY_CACHE_TTL = 5000 type GetContext = { - repositoryResponse?: Partial; - getRef(repository: prismic.Repository): string; -}; + repositoryResponse?: Partial + getRef(repository: prismic.Repository): string +} type TestGetWithinTTLArgs = { - getContext: GetContext; - beforeFirstGet: (args: { client: prismic.Client }) => void; - requestParams?: Parameters[0]; -}; + getContext: GetContext + beforeFirstGet: (args: { client: prismic.Client }) => void + requestParams?: Parameters[0] +} export const testGetWithinTTL = ( description: string, @@ -39,9 +39,9 @@ export const testGetWithinTTL = ( const repositoryResponse = { ...ctx.mock.api.repository(), ...args.getContext.repositoryResponse, - }; - const ref = args.getContext.getRef(repositoryResponse); - const queryResponse = ctx.mock.api.query(); + } + const ref = args.getContext.getRef(repositoryResponse) + const queryResponse = ctx.mock.api.query() mockPrismicRestAPIV2({ repositoryResponse, @@ -50,37 +50,37 @@ export const testGetWithinTTL = ( ref, }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() if (args.beforeFirstGet) { - args.beforeFirstGet({ client }); + args.beforeFirstGet({ client }) } - const res1 = await client.get(); + const res1 = await client.get() // We're setting the next repository metadata response to include a different ref. // Notice that we aren't setting a new query handler. The next query should // use the previous ref. ctx.server.use( rest.get(client.endpoint, (_req, res, serverCtx) => { - return res(serverCtx.json(ctx.mock.api.repository())); + return res(serverCtx.json(ctx.mock.api.repository())) }), - ); + ) - const res2 = await client.get(); + const res2 = await client.get() - expect(res1).toStrictEqual(queryResponse); - expect(res2).toStrictEqual(queryResponse); - }); -}; + expect(res1).toStrictEqual(queryResponse) + expect(res2).toStrictEqual(queryResponse) + }) +} type TestGetOutsideTTLArgs = { - getContext1: GetContext; - getContext2: GetContext; - beforeFirstGet: (args: { client: prismic.Client }) => void; -}; + getContext1: GetContext + getContext2: GetContext + beforeFirstGet: (args: { client: prismic.Client }) => void +} export const testGetOutsideTTL = ( description: string, @@ -92,16 +92,16 @@ export const testGetOutsideTTL = ( const repositoryResponse1 = { ...ctx.mock.api.repository(), ...args.getContext1.repositoryResponse, - }; - const ref1 = args.getContext1.getRef(repositoryResponse1); - const queryResponse1 = ctx.mock.api.query(); + } + const ref1 = args.getContext1.getRef(repositoryResponse1) + const queryResponse1 = ctx.mock.api.query() const repositoryResponse2 = { ...ctx.mock.api.repository(), ...args.getContext2.repositoryResponse, - }; - const ref2 = args.getContext2.getRef(repositoryResponse2); - const queryResponse2 = ctx.mock.api.query(); + } + const ref2 = args.getContext2.getRef(repositoryResponse2) + const queryResponse2 = ctx.mock.api.query() mockPrismicRestAPIV2({ repositoryResponse: repositoryResponse1, @@ -110,20 +110,20 @@ export const testGetOutsideTTL = ( ref: ref1, }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() if (args.beforeFirstGet) { - args.beforeFirstGet({ client }); + args.beforeFirstGet({ client }) } - const res1 = await client.get(); + const res1 = await client.get() // We wait for the cached ref's TTL to expire. await new Promise((res) => setTimeout(() => res(undefined), REPOSITORY_CACHE_TTL + 1), - ); + ) // We're setting the next repository metadata response to include a different ref. // We're also using a new query handler using the new master ref. @@ -134,13 +134,13 @@ export const testGetOutsideTTL = ( ref: ref2, }, ctx, - }); + }) - const res2 = await client.get(); + const res2 = await client.get() - expect(res1).toStrictEqual(queryResponse1); - expect(res2).toStrictEqual(queryResponse2); + expect(res1).toStrictEqual(queryResponse1) + expect(res2).toStrictEqual(queryResponse2) }, REPOSITORY_CACHE_TTL * 2, - ); -}; + ) +} diff --git a/test/buildQueryURL.test.ts b/test/buildQueryURL.test.ts index d86f26bd..5396d043 100644 --- a/test/buildQueryURL.test.ts +++ b/test/buildQueryURL.test.ts @@ -1,14 +1,14 @@ -import { expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" -const endpoint = prismic.getRepositoryEndpoint("qwerty"); +const endpoint = prismic.getRepositoryEndpoint("qwerty") it("includes ref", () => { expect(prismic.buildQueryURL(endpoint, { ref: "ref" })).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref", - ); -}); + ) +}) it("supports single filter", () => { expect( @@ -20,7 +20,7 @@ it("supports single filter", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?q=[[has(my.document.title)]]&ref=ref", - ); + ) // TODO: Remove when we remove support for deprecated `predicates` argument. expect( @@ -32,8 +32,8 @@ it("supports single filter", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?q=[[has(my.document.title)]]&ref=ref", - ); -}); + ) +}) it("supports multiple filters", () => { expect( @@ -48,7 +48,7 @@ it("supports multiple filters", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?q=[[has(my.document.title)]]&q=[[has(my.document.subtitle)]]&ref=ref", - ); + ) // TODO: Remove when we remove support for deprecated `predicates` argument. expect( @@ -63,8 +63,8 @@ it("supports multiple filters", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?q=[[has(my.document.title)]]&q=[[has(my.document.subtitle)]]&ref=ref", - ); -}); + ) +}) it("supports params", () => { expect( @@ -86,8 +86,8 @@ it("supports params", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&access_token=accessToken&pageSize=1&page=1&after=after&fetch=fetch&fetchLinks=fetchLinks&graphQuery=graphQuery&lang=lang&orderings=[orderings]&routes=routes&brokenRoute=brokenRoute", - ); -}); + ) +}) it("ignores nullish params", () => { expect( @@ -105,8 +105,8 @@ it("ignores nullish params", () => { orderings: undefined, }), ), - ).toBe("https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref"); -}); + ).toBe("https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref") +}) it("supports array fetch param", () => { expect( @@ -118,8 +118,8 @@ it("supports array fetch param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&fetch=title,subtitle", - ); -}); + ) +}) it("supports array fetchLinks param", () => { expect( @@ -131,8 +131,8 @@ it("supports array fetchLinks param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&fetchLinks=page.link,page.second_link", - ); -}); + ) +}) it("supports empty orderings param", () => { expect( @@ -145,7 +145,7 @@ it("supports empty orderings param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&orderings=[]", - ); + ) expect( decodeURIComponent( @@ -156,8 +156,8 @@ it("supports empty orderings param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&orderings=[]", - ); -}); + ) +}) it("supports array orderings param", () => { expect( @@ -170,8 +170,8 @@ it("supports array orderings param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&orderings=[page.title,page.subtitle]", - ); -}); + ) +}) it("supports setting direction of ordering param", () => { expect( @@ -184,7 +184,7 @@ it("supports setting direction of ordering param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&orderings=[page.title,page.subtitle]", - ); + ) expect( decodeURIComponent( @@ -199,15 +199,15 @@ it("supports setting direction of ordering param", () => { ), ).toBe( "https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&orderings=[page.title+desc,page.subtitle+desc]", - ); -}); + ) +}) it("supports single item routes param", () => { const route = { type: "type", path: "path", resolvers: { foo: "bar" }, - }; + } expect( decodeURIComponent( @@ -220,8 +220,8 @@ it("supports single item routes param", () => { `https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&routes=[${JSON.stringify( route, )}]`, - ); -}); + ) +}) it("supports array routes param", () => { const routes: prismic.Route[] = [ @@ -235,7 +235,7 @@ it("supports array routes param", () => { path: "bar-path", resolvers: { foo: "bar" }, }, - ]; + ] expect( decodeURIComponent( @@ -248,80 +248,80 @@ it("supports array routes param", () => { `https://qwerty.cdn.prismic.io/api/v2/documents/search?ref=ref&routes=${JSON.stringify( routes, )}`, - ); -}); + ) +}) it("warns if NODE_ENV is development and a string is provided to `orderings`", () => { - const originalEnv = { ...process.env }; + const originalEnv = { ...process.env } - process.env.NODE_ENV = "development"; + process.env.NODE_ENV = "development" const consoleWarnSpy = vi .spyOn(console, "warn") - .mockImplementation(() => void 0); + .mockImplementation(() => void 0) prismic.buildQueryURL(endpoint, { ref: "ref", orderings: "orderings", - }); + }) expect(consoleWarnSpy).toHaveBeenCalledWith( expect.stringMatching(/orderings-must-be-an-array-of-objects/i), - ); + ) - consoleWarnSpy.mockRestore(); + consoleWarnSpy.mockRestore() - process.env = originalEnv; -}); + process.env = originalEnv +}) it("warns if NODE_ENV is development and an array of strings is provided to `orderings`", () => { - const originalEnv = { ...process.env }; + const originalEnv = { ...process.env } - process.env.NODE_ENV = "development"; + process.env.NODE_ENV = "development" const consoleWarnSpy = vi .spyOn(console, "warn") - .mockImplementation(() => void 0); + .mockImplementation(() => void 0) prismic.buildQueryURL(endpoint, { ref: "ref", orderings: ["orderings"], - }); + }) prismic.buildQueryURL(endpoint, { ref: "ref", orderings: ["orderings desc"], - }); + }) expect(consoleWarnSpy).toHaveBeenNthCalledWith( 2, expect.stringMatching(/orderings-must-be-an-array-of-objects/i), - ); + ) - consoleWarnSpy.mockRestore(); + consoleWarnSpy.mockRestore() - process.env = originalEnv; -}); + process.env = originalEnv +}) it("warns if NODE_ENV is development and a string is provided to `filters`", () => { - const originalEnv = { ...process.env }; + const originalEnv = { ...process.env } - process.env.NODE_ENV = "development"; + process.env.NODE_ENV = "development" const consoleWarnSpy = vi .spyOn(console, "warn") - .mockImplementation(() => void 0); + .mockImplementation(() => void 0) prismic.buildQueryURL(endpoint, { ref: "ref", filters: "filters", - }); + }) expect(consoleWarnSpy).toHaveBeenCalledWith( expect.stringMatching(/filters-must-be-an-array/i), - ); + ) - consoleWarnSpy.mockRestore(); + consoleWarnSpy.mockRestore() - process.env = originalEnv; -}); + process.env = originalEnv +}) diff --git a/test/client-buildQueryURL.test.ts b/test/client-buildQueryURL.test.ts index dac77ed8..1aff7f14 100644 --- a/test/client-buildQueryURL.test.ts +++ b/test/client-buildQueryURL.test.ts @@ -1,109 +1,109 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { getMasterRef } from "./__testutils__/getMasterRef"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; +import { createTestClient } from "./__testutils__/createClient" +import { getMasterRef } from "./__testutils__/getMasterRef" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" -import * as prismic from "../src"; +import type * as prismic from "../src" it("builds a query URL using the master ref", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - const ref = getMasterRef(repositoryResponse); + const repositoryResponse = ctx.mock.api.repository() + const ref = getMasterRef(repositoryResponse) mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.buildQueryURL(); - const url = new URL(res); + const client = createTestClient() + const res = await client.buildQueryURL() + const url = new URL(res) const expectedSearchParams = new URLSearchParams({ ref, - }); - url.searchParams.delete("integrationFieldsRef"); - url.searchParams.sort(); - expectedSearchParams.sort(); + }) + url.searchParams.delete("integrationFieldsRef") + url.searchParams.sort() + expectedSearchParams.sort() - expect(url.host).toBe(new URL(client.endpoint).host); - expect(url.pathname).toBe("/api/v2/documents/search"); - expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()); -}); + expect(url.host).toBe(new URL(client.endpoint).host) + expect(url.pathname).toBe("/api/v2/documents/search") + expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()) +}) it("includes params if provided", async (ctx) => { const params: prismic.BuildQueryURLArgs = { accessToken: "custom-accessToken", ref: "custom-ref", lang: "*", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); - const res = await client.buildQueryURL(params); - const url = new URL(res); + const client = createTestClient() + const res = await client.buildQueryURL(params) + const url = new URL(res) const expectedSearchParams = new URLSearchParams({ ref: params.ref, lang: params.lang?.toString() ?? "", // TODO: Remove when Authorization header support works in browsers with CORS. access_token: params.accessToken ?? "", - }); + }) - url.searchParams.delete("integrationFieldsRef"); - url.searchParams.sort(); - expectedSearchParams.sort(); + url.searchParams.delete("integrationFieldsRef") + url.searchParams.sort() + expectedSearchParams.sort() - expect(url.host).toBe(new URL(client.endpoint).host); - expect(url.pathname).toBe("/api/v2/documents/search"); - expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()); -}); + expect(url.host).toBe(new URL(client.endpoint).host) + expect(url.pathname).toBe("/api/v2/documents/search") + expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()) +}) it("includes default params if provided", async (ctx) => { const clientConfig: prismic.ClientConfig = { accessToken: "custom-accessToken", ref: "custom-ref", defaultParams: { lang: "*" }, - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient({ clientConfig }); - const res = await client.buildQueryURL(); - const url = new URL(res); + const client = createTestClient({ clientConfig }) + const res = await client.buildQueryURL() + const url = new URL(res) const expectedSearchParams = new URLSearchParams({ ref: clientConfig.ref?.toString() ?? "", lang: clientConfig.defaultParams?.lang?.toString() ?? "", // TODO: Remove when Authorization header support works in browsers with CORS. access_token: clientConfig.accessToken ?? "", - }); + }) - url.searchParams.delete("integrationFieldsRef"); - url.searchParams.sort(); - expectedSearchParams.sort(); + url.searchParams.delete("integrationFieldsRef") + url.searchParams.sort() + expectedSearchParams.sort() - expect(url.host).toBe(new URL(client.endpoint).host); - expect(url.pathname).toBe("/api/v2/documents/search"); - expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()); -}); + expect(url.host).toBe(new URL(client.endpoint).host) + expect(url.pathname).toBe("/api/v2/documents/search") + expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()) +}) it("merges params and default params if provided", async (ctx) => { const clientConfig: prismic.ClientConfig = { accessToken: "custom-accessToken", ref: "custom-ref", defaultParams: { lang: "*", page: 2 }, - }; + } const params: prismic.BuildQueryURLArgs = { ref: "overridden-ref", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient({ clientConfig }); - const res = await client.buildQueryURL(params); - const url = new URL(res); + const client = createTestClient({ clientConfig }) + const res = await client.buildQueryURL(params) + const url = new URL(res) const expectedSearchParams = new URLSearchParams({ ref: params.ref, @@ -111,13 +111,13 @@ it("merges params and default params if provided", async (ctx) => { page: clientConfig.defaultParams?.page?.toString() ?? "", // TODO: Remove when Authorization header support works in browsers with CORS. access_token: clientConfig.accessToken ?? "", - }); + }) - url.searchParams.delete("integrationFieldsRef"); - url.searchParams.sort(); - expectedSearchParams.sort(); + url.searchParams.delete("integrationFieldsRef") + url.searchParams.sort() + expectedSearchParams.sort() - expect(url.host).toBe(new URL(client.endpoint).host); - expect(url.pathname).toBe("/api/v2/documents/search"); - expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()); -}); + expect(url.host).toBe(new URL(client.endpoint).host) + expect(url.pathname).toBe("/api/v2/documents/search") + expect(url.searchParams.toString()).toBe(expectedSearchParams.toString()) +}) diff --git a/test/client-dangerouslyGetAll.test.ts b/test/client-dangerouslyGetAll.test.ts index eb6632be..e48f72e6 100644 --- a/test/client-dangerouslyGetAll.test.ts +++ b/test/client-dangerouslyGetAll.test.ts @@ -1,12 +1,12 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { createPagedQueryResponses } from "./__testutils__/createPagedQueryResponses"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { createPagedQueryResponses } from "./__testutils__/createPagedQueryResponses" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" /** * The number of milliseconds in which a multi-page `getAll` (e.g. `getAll`, @@ -20,7 +20,7 @@ import { testFetchOptions } from "./__testutils__/testFetchOptions"; * note that changing `GET_ALL_QUERY_DELAY` in the public code may have an * effect on tests using this test-specific constant. */ -export const GET_ALL_QUERY_DELAY = 500; +export const GET_ALL_QUERY_DELAY = 500 /** * Tolerance in number of milliseconds for the duration of a simulated network @@ -29,11 +29,11 @@ export const GET_ALL_QUERY_DELAY = 500; * If tests are failing due to incorrect timed durations, increase the tolerance * amount. */ -const NETWORK_REQUEST_DURATION_TOLERANCE = 300; +const NETWORK_REQUEST_DURATION_TOLERANCE = 300 testGetAllMethod("returns all documents from paginated response", { run: (client) => client.dangerouslyGetAll(), -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -47,7 +47,7 @@ testGetAllMethod("includes params if provided", { ref: "custom-ref", lang: "*", }, -}); +}) testGetAllMethod("includes default params if provided", { run: (client) => client.dangerouslyGetAll(), @@ -59,7 +59,7 @@ testGetAllMethod("includes default params if provided", { requiredParams: { lang: "*", }, -}); +}) testGetAllMethod("merges params and default params if provided", { run: (client) => @@ -80,7 +80,7 @@ testGetAllMethod("merges params and default params if provided", { ref: "overridden-ref", lang: "fr-fr", }, -}); +}) testGetAllMethod( "uses the default pageSize when given a falsey pageSize param", @@ -93,7 +93,7 @@ testGetAllMethod( pageSize: "100", }, }, -); +) testGetAllMethod("optimizes pageSize when limit is below the pageSize", { run: (client) => @@ -104,7 +104,7 @@ testGetAllMethod("optimizes pageSize when limit is below the pageSize", { requiredParams: { pageSize: "3", }, -}); +}) testGetAllMethod( "does not optimize pageSize when limit is above the pageSize", @@ -118,16 +118,16 @@ testGetAllMethod( pageSize: "100", }, }, -); +) it("throttles requests past first page", async (ctx) => { - const numPages = 3; + const numPages = 3 const queryResponses = createPagedQueryResponses({ ctx, pages: numPages, - }); + }) - const queryDelay = 200; + const queryDelay = 200 mockPrismicRestAPIV2({ ctx, @@ -136,17 +136,17 @@ it("throttles requests past first page", async (ctx) => { pageSize: "100", }, queryDelay, - }); + }) - const client = createTestClient(); + const client = createTestClient() - const startTime = Date.now(); - await client.dangerouslyGetAll(); - const endTime = Date.now(); + const startTime = Date.now() + await client.dangerouslyGetAll() + const endTime = Date.now() - const totalTime = endTime - startTime; - const minTime = numPages * queryDelay + (numPages - 1) * 500; - const maxTime = minTime + NETWORK_REQUEST_DURATION_TOLERANCE; + const totalTime = endTime - startTime + const minTime = numPages * queryDelay + (numPages - 1) * 500 + const maxTime = minTime + NETWORK_REQUEST_DURATION_TOLERANCE // The total time should be the amount of time it takes to resolve all // network requests in addition to a delay between requests (accounting for @@ -154,15 +154,15 @@ it("throttles requests past first page", async (ctx) => { expect( minTime <= totalTime && totalTime <= maxTime, `Total time should be between ${minTime}ms and ${maxTime}ms (inclusive), but was ${totalTime}ms`, - ).toBe(true); -}); + ).toBe(true) +}) it("does not throttle single page queries", async (ctx) => { const queryResponses = createPagedQueryResponses({ ctx, pages: 1, - }); - const queryDelay = 200; + }) + const queryDelay = 200 mockPrismicRestAPIV2({ ctx, @@ -171,17 +171,17 @@ it("does not throttle single page queries", async (ctx) => { pageSize: "100", }, queryDelay, - }); + }) - const client = createTestClient(); + const client = createTestClient() - const startTime = Date.now(); - await client.dangerouslyGetAll(); - const endTime = Date.now(); + const startTime = Date.now() + await client.dangerouslyGetAll() + const endTime = Date.now() - const totalTime = endTime - startTime; - const minTime = queryDelay; - const maxTime = minTime + NETWORK_REQUEST_DURATION_TOLERANCE; + const totalTime = endTime - startTime + const minTime = queryDelay + const maxTime = minTime + NETWORK_REQUEST_DURATION_TOLERANCE // The total time should only be the amount of time it takes to resolve the // network request (accounting for some tolerance). In other words, there is @@ -189,18 +189,18 @@ it("does not throttle single page queries", async (ctx) => { expect( minTime <= totalTime && totalTime <= maxTime, `Total time should be between ${minTime}ms and ${maxTime}ms (inclusive), but was ${totalTime}ms`, - ).toBe(true); -}); + ).toBe(true) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.dangerouslyGetAll(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.dangerouslyGetAll(params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.dangerouslyGetAll(params), mode: "getAll", -}); +}) diff --git a/test/client-get.test.ts b/test/client-get.test.ts index df73ee6f..e4caa71b 100644 --- a/test/client-get.test.ts +++ b/test/client-get.test.ts @@ -1,16 +1,16 @@ -import { expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest" -import fetch from "node-fetch"; +import fetch from "node-fetch" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("resolves a query", { run: (client) => client.get(), -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -24,7 +24,7 @@ testGetMethod("includes params if provided", { ref: "custom-ref", lang: "*", }, -}); +}) testGetMethod("includes default params if provided", { run: (client) => client.get(), @@ -36,7 +36,7 @@ testGetMethod("includes default params if provided", { requiredParams: { lang: "*", }, -}); +}) testGetMethod("merges params and default params if provided", { run: (client) => @@ -57,45 +57,45 @@ testGetMethod("merges params and default params if provided", { ref: "overridden-ref", lang: "fr-fr", }, -}); +}) it("uses cached repository metadata within the client's repository cache TTL", async (ctx) => { - const fetchSpy = vi.fn(fetch); + const fetchSpy = vi.fn(fetch) - const client = createTestClient({ clientConfig: { fetch: fetchSpy } }); + const client = createTestClient({ clientConfig: { fetch: fetchSpy } }) - const repositoryResponse1 = ctx.mock.api.repository(); - repositoryResponse1.refs = [ctx.mock.api.ref({ isMasterRef: true })]; - mockPrismicRestAPIV2({ ctx, repositoryResponse: repositoryResponse1 }); + const repositoryResponse1 = ctx.mock.api.repository() + repositoryResponse1.refs = [ctx.mock.api.ref({ isMasterRef: true })] + mockPrismicRestAPIV2({ ctx, repositoryResponse: repositoryResponse1 }) - await client.get(); + await client.get() // This response response will not be used. - const repositoryResponse2 = ctx.mock.api.repository(); - repositoryResponse2.refs = [ctx.mock.api.ref({ isMasterRef: true })]; - mockPrismicRestAPIV2({ ctx, repositoryResponse: repositoryResponse2 }); + const repositoryResponse2 = ctx.mock.api.repository() + repositoryResponse2.refs = [ctx.mock.api.ref({ isMasterRef: true })] + mockPrismicRestAPIV2({ ctx, repositoryResponse: repositoryResponse2 }) - await client.get(); + await client.get() const getRequests = fetchSpy.mock.calls .filter( (call) => new URL(call[0] as string).pathname === "/api/v2/documents/search", ) - .map((call) => call[0] as string); + .map((call) => call[0] as string) expect(new URL(getRequests[0]).searchParams.get("ref")).toBe( repositoryResponse1.refs[0].ref, - ); + ) expect(new URL(getRequests[1]).searchParams.get("ref")).toBe( repositoryResponse1.refs[0].ref, - ); -}); + ) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.get(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.get(params), -}); +}) diff --git a/test/client-getAllByEveryTag.test.ts b/test/client-getAllByEveryTag.test.ts index 374fb601..ffca2b71 100644 --- a/test/client-getAllByEveryTag.test.ts +++ b/test/client-getAllByEveryTag.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetAllMethod("returns all documents by every tag from paginated response", { run: (client) => client.getAllByEveryTag(["foo", "bar"]), requiredParams: { q: `[[at(document.tags, ["foo", "bar"])]]`, }, -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetAllMethod("includes params if provided", { lang: "*", q: `[[at(document.tags, ["foo", "bar"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getAllByEveryTag(["foo", "bar"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getAllByEveryTag(["foo", "bar"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getAllByEveryTag(["foo", "bar"], params), mode: "getAll", -}); +}) diff --git a/test/client-getAllByIDs.test.ts b/test/client-getAllByIDs.test.ts index cc53ca74..fbe027a3 100644 --- a/test/client-getAllByIDs.test.ts +++ b/test/client-getAllByIDs.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetAllMethod("returns all documents by IDs from paginated response", { run: (client) => client.getAllByIDs(["id1", "id2"]), requiredParams: { q: `[[in(document.id, ["id1", "id2"])]]`, }, -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetAllMethod("includes params if provided", { lang: "*", q: `[[in(document.id, ["id1", "id2"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getAllByIDs(["id1", "id2"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getAllByIDs(["id1", "id2"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getAllByIDs(["id1", "id2"], params), mode: "getAll", -}); +}) diff --git a/test/client-getAllBySomeTags.test.ts b/test/client-getAllBySomeTags.test.ts index a3b7934a..002f92b0 100644 --- a/test/client-getAllBySomeTags.test.ts +++ b/test/client-getAllBySomeTags.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetAllMethod("returns all documents by some tags from paginated response", { run: (client) => client.getAllBySomeTags(["foo", "bar"]), requiredParams: { q: `[[any(document.tags, ["foo", "bar"])]]`, }, -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetAllMethod("includes params if provided", { lang: "*", q: `[[any(document.tags, ["foo", "bar"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getAllBySomeTags(["foo", "bar"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getAllBySomeTags(["foo", "bar"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getAllBySomeTags(["foo", "bar"], params), mode: "getAll", -}); +}) diff --git a/test/client-getAllByTag.test.ts b/test/client-getAllByTag.test.ts index 995d81fd..d2b81bd4 100644 --- a/test/client-getAllByTag.test.ts +++ b/test/client-getAllByTag.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetAllMethod("returns all documents by tag from paginated response", { run: (client) => client.getAllByTag("tag"), requiredParams: { q: `[[any(document.tags, ["tag"])]]`, }, -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetAllMethod("includes params if provided", { lang: "*", q: `[[any(document.tags, ["tag"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getAllByTag("tag", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getAllByTag("tag", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getAllByTag("tag", params), mode: "getAll", -}); +}) diff --git a/test/client-getAllByType.test.ts b/test/client-getAllByType.test.ts index 2fad65b6..2af6e770 100644 --- a/test/client-getAllByType.test.ts +++ b/test/client-getAllByType.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetAllMethod("returns all documents by type from paginated response", { run: (client) => client.getAllByType("type"), requiredParams: { q: `[[at(document.type, "type")]]`, }, -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetAllMethod("includes params if provided", { lang: "*", q: `[[at(document.type, "type")]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getAllByType("type", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getAllByType("type", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getAllByType("type", params), mode: "getAll", -}); +}) diff --git a/test/client-getAllByUIDs.test.ts b/test/client-getAllByUIDs.test.ts index b23206a5..c1ddb21b 100644 --- a/test/client-getAllByUIDs.test.ts +++ b/test/client-getAllByUIDs.test.ts @@ -1,7 +1,7 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetAllMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetAllMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetAllMethod("returns all documents by UIDs from paginated response", { run: (client) => client.getAllByUIDs("type", ["uid1", "uid2"]), @@ -11,7 +11,7 @@ testGetAllMethod("returns all documents by UIDs from paginated response", { `[[in(my.type.uid, ["uid1", "uid2"])]]`, ], }, -}); +}) testGetAllMethod("includes params if provided", { run: (client) => @@ -29,20 +29,20 @@ testGetAllMethod("includes params if provided", { `[[in(my.type.uid, ["uid1", "uid2"])]]`, ], }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getAllByUIDs("type", ["uid1", "uid2"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getAllByUIDs("type", ["uid1", "uid2"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getAllByUIDs("type", ["uid1", "uid2"], params), mode: "getAll", -}); +}) diff --git a/test/client-getByEveryTag.test.ts b/test/client-getByEveryTag.test.ts index 5c052fa7..fa5b34a5 100644 --- a/test/client-getByEveryTag.test.ts +++ b/test/client-getByEveryTag.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("queries for documents by tag", { run: (client) => client.getByEveryTag(["foo", "bar"]), requiredParams: { q: `[[at(document.tags, ["foo", "bar"])]]`, }, -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetMethod("includes params if provided", { lang: "*", q: `[[at(document.tags, ["foo", "bar"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByEveryTag(["foo", "bar"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByEveryTag(["foo", "bar"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByEveryTag(["foo", "bar"], params), mode: "get", -}); +}) diff --git a/test/client-getByID.test.ts b/test/client-getByID.test.ts index e0897007..1914dffa 100644 --- a/test/client-getByID.test.ts +++ b/test/client-getByID.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetFirstMethod("queries for document by ID", { run: (client) => client.getByID("id"), requiredParams: { q: `[[at(document.id, "id")]]`, }, -}); +}) testGetFirstMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetFirstMethod("includes params if provided", { lang: "*", q: `[[at(document.id, "id")]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByID("id", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByID("id", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByID("id", params), mode: "get", -}); +}) diff --git a/test/client-getByIDs.test.ts b/test/client-getByIDs.test.ts index c6dbd72c..1bbfbad9 100644 --- a/test/client-getByIDs.test.ts +++ b/test/client-getByIDs.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("queries for documents by IDs", { run: (client) => client.getByIDs(["id1", "id2"]), requiredParams: { q: `[[in(document.id, ["id1", "id2"])]]`, }, -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetMethod("includes params if provided", { lang: "*", q: `[[in(document.id, ["id1", "id2"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByIDs(["id1", "id2"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByIDs(["id1", "id2"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByIDs(["id1", "id2"], params), mode: "get", -}); +}) diff --git a/test/client-getBySomeTags.test.ts b/test/client-getBySomeTags.test.ts index f537f71a..b90922be 100644 --- a/test/client-getBySomeTags.test.ts +++ b/test/client-getBySomeTags.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("queries for documents by some tags", { run: (client) => client.getBySomeTags(["foo", "bar"]), requiredParams: { q: `[[any(document.tags, ["foo", "bar"])]]`, }, -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetMethod("includes params if provided", { lang: "*", q: `[[any(document.tags, ["foo", "bar"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getBySomeTags(["foo", "bar"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getBySomeTags(["foo", "bar"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getBySomeTags(["foo", "bar"], params), mode: "get", -}); +}) diff --git a/test/client-getByTag.test.ts b/test/client-getByTag.test.ts index 5af1688e..fa6d0567 100644 --- a/test/client-getByTag.test.ts +++ b/test/client-getByTag.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("queries for documents by tag", { run: (client) => client.getByTag("tag"), requiredParams: { q: `[[any(document.tags, ["tag"])]]`, }, -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetMethod("includes params if provided", { lang: "*", q: `[[any(document.tags, ["tag"])]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByTag("tag", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByTag("tag", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByTag("tag", params), mode: "get", -}); +}) diff --git a/test/client-getByType.test.ts b/test/client-getByType.test.ts index 0b626724..9ef415b2 100644 --- a/test/client-getByType.test.ts +++ b/test/client-getByType.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("queries for documents by type", { run: (client) => client.getByType("type"), requiredParams: { q: `[[at(document.type, "type")]]`, }, -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetMethod("includes params if provided", { lang: "*", q: `[[at(document.type, "type")]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByType("type", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByType("type", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByType("type", params), mode: "get", -}); +}) diff --git a/test/client-getByUID.test.ts b/test/client-getByUID.test.ts index e1a9e842..27fa358a 100644 --- a/test/client-getByUID.test.ts +++ b/test/client-getByUID.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetFirstMethod("queries for document by UID", { run: (client) => client.getByUID("type", "uid"), requiredParams: { q: [`[[at(document.type, "type")]]`, `[[at(my.type.uid, "uid")]]`], }, -}); +}) testGetFirstMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetFirstMethod("includes params if provided", { lang: "*", q: [`[[at(document.type, "type")]]`, `[[at(my.type.uid, "uid")]]`], }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByUID("type", "uid", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByUID("type", "uid", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByUID("type", "uid", params), mode: "get", -}); +}) diff --git a/test/client-getByUIDs.test.ts b/test/client-getByUIDs.test.ts index 5976fcec..45ac76ac 100644 --- a/test/client-getByUIDs.test.ts +++ b/test/client-getByUIDs.test.ts @@ -1,7 +1,7 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetMethod("queries for documents by UIDs", { run: (client) => client.getByUIDs("type", ["uid1", "uid2"]), @@ -11,7 +11,7 @@ testGetMethod("queries for documents by UIDs", { `[[in(my.type.uid, ["uid1", "uid2"])]]`, ], }, -}); +}) testGetMethod("includes params if provided", { run: (client) => @@ -29,17 +29,17 @@ testGetMethod("includes params if provided", { `[[in(my.type.uid, ["uid1", "uid2"])]]`, ], }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getByUIDs("type", ["uid1", "uid2"], params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getByUIDs("type", ["uid1", "uid2"], params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getByUIDs("type", ["uid1", "uid2"], params), mode: "get", -}); +}) diff --git a/test/client-getFirst.test.ts b/test/client-getFirst.test.ts index 8fc73064..307e6814 100644 --- a/test/client-getFirst.test.ts +++ b/test/client-getFirst.test.ts @@ -1,19 +1,19 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismicM from "@prismicio/mock"; +import * as prismicM from "@prismicio/mock" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -import * as prismic from "../src"; +import * as prismic from "../src" testGetFirstMethod("returns the first document from a response", { run: (client) => client.getFirst(), -}); +}) testGetFirstMethod("includes params if provided", { run: (client) => @@ -27,7 +27,7 @@ testGetFirstMethod("includes params if provided", { ref: "custom-ref", lang: "*", }, -}); +}) testGetFirstMethod("includes default params if provided", { run: (client) => client.getFirst(), @@ -39,7 +39,7 @@ testGetFirstMethod("includes default params if provided", { requiredParams: { lang: "*", }, -}); +}) testGetFirstMethod("merges params and default params if provided", { run: (client) => @@ -60,7 +60,7 @@ testGetFirstMethod("merges params and default params if provided", { ref: "overridden-ref", lang: "fr-fr", }, -}); +}) testGetFirstMethod( "ignores default pageSize=1 param if a page param is given", @@ -73,7 +73,7 @@ testGetFirstMethod( pageSize: "2", }, }, -); +) it("throws if no documents were returned", async (ctx) => { mockPrismicRestAPIV2({ @@ -82,27 +82,27 @@ it("throws if no documents were returned", async (ctx) => { documents: [], }), ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() await expect(() => client.getFirst()).rejects.toThrowError( /no documents were returned/i, - ); + ) await expect(() => client.getFirst()).rejects.toThrowError( prismic.NotFoundError, - ); -}); + ) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getFirst(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getFirst(params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getFirst(params), mode: "get", -}); +}) diff --git a/test/client-getMasterRef.test.ts b/test/client-getMasterRef.test.ts index 98bae2fa..0e1b98a9 100644 --- a/test/client-getMasterRef.test.ts +++ b/test/client-getMasterRef.test.ts @@ -1,37 +1,37 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" it("returns the master ref", async (ctx) => { - const masterRef = ctx.mock.api.ref({ isMasterRef: true }); - const ref2 = ctx.mock.api.ref({ isMasterRef: false }); - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref2, masterRef]; + const masterRef = ctx.mock.api.ref({ isMasterRef: true }) + const ref2 = ctx.mock.api.ref({ isMasterRef: false }) + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref2, masterRef] mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getMasterRef(); + const client = createTestClient() + const res = await client.getMasterRef() - expect(res).toStrictEqual(masterRef); -}); + expect(res).toStrictEqual(masterRef) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getMasterRef(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getMasterRef(params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getMasterRef(params), mode: "repository", -}); +}) diff --git a/test/client-getRefByID.test.ts b/test/client-getRefByID.test.ts index 4a2e45a7..f4449ce7 100644 --- a/test/client-getRefByID.test.ts +++ b/test/client-getRefByID.test.ts @@ -1,53 +1,53 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns a ref by ID", async (ctx) => { - const ref1 = ctx.mock.api.ref({ isMasterRef: true }); - const ref2 = ctx.mock.api.ref({ isMasterRef: false }); - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref1, ref2]; + const ref1 = ctx.mock.api.ref({ isMasterRef: true }) + const ref2 = ctx.mock.api.ref({ isMasterRef: false }) + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref1, ref2] mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getRefByID(ref2.id); + const client = createTestClient() + const res = await client.getRefByID(ref2.id) - expect(res).toStrictEqual(ref2); -}); + expect(res).toStrictEqual(ref2) +}) it("throws if ref could not be found", async (ctx) => { mockPrismicRestAPIV2({ ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() await expect(() => client.getRefByID("non-existant")).rejects.toThrowError( /could not be found/i, - ); + ) await expect(() => client.getRefByID("non-existant")).rejects.toThrowError( prismic.PrismicError, - ); -}); + ) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getRefByID("id", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getRefByID("id", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getRefByID("id", params), mode: "repository", -}); +}) diff --git a/test/client-getRefByLabel.test.ts b/test/client-getRefByLabel.test.ts index fa45747f..d5798736 100644 --- a/test/client-getRefByLabel.test.ts +++ b/test/client-getRefByLabel.test.ts @@ -1,53 +1,53 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns a ref by label", async (ctx) => { - const ref1 = ctx.mock.api.ref({ isMasterRef: true }); - const ref2 = ctx.mock.api.ref({ isMasterRef: false }); - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref1, ref2]; + const ref1 = ctx.mock.api.ref({ isMasterRef: true }) + const ref2 = ctx.mock.api.ref({ isMasterRef: false }) + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref1, ref2] mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getRefByLabel(ref2.label); + const client = createTestClient() + const res = await client.getRefByLabel(ref2.label) - expect(res).toStrictEqual(ref2); -}); + expect(res).toStrictEqual(ref2) +}) it("throws if ref could not be found", async (ctx) => { mockPrismicRestAPIV2({ ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() await expect(() => client.getRefByLabel("non-existant")).rejects.toThrowError( /could not be found/i, - ); + ) await expect(() => client.getRefByLabel("non-existant")).rejects.toThrowError( prismic.PrismicError, - ); -}); + ) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getRefByLabel("label", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getRefByLabel("label", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getRefByLabel("label", params), mode: "repository", -}); +}) diff --git a/test/client-getRefs.test.ts b/test/client-getRefs.test.ts index f140d62c..32c03bd4 100644 --- a/test/client-getRefs.test.ts +++ b/test/client-getRefs.test.ts @@ -1,33 +1,33 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" it("returns all refs", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getRefs(); + const client = createTestClient() + const res = await client.getRefs() - expect(res).toStrictEqual(repositoryResponse.refs); -}); + expect(res).toStrictEqual(repositoryResponse.refs) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getRefs(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getRefs(params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getRefs(params), mode: "repository", -}); +}) diff --git a/test/client-getReleaseById.test.ts b/test/client-getReleaseById.test.ts index a9f7f752..35c4be77 100644 --- a/test/client-getReleaseById.test.ts +++ b/test/client-getReleaseById.test.ts @@ -1,51 +1,51 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns a Release by ID", async (ctx) => { - const ref1 = ctx.mock.api.ref({ isMasterRef: true }); - const ref2 = ctx.mock.api.ref({ isMasterRef: false }); - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref1, ref2]; + const ref1 = ctx.mock.api.ref({ isMasterRef: true }) + const ref2 = ctx.mock.api.ref({ isMasterRef: false }) + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref1, ref2] mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getReleaseByID(ref2.id); + const client = createTestClient() + const res = await client.getReleaseByID(ref2.id) - expect(res).toStrictEqual(ref2); -}); + expect(res).toStrictEqual(ref2) +}) it("throws if Release could not be found", async (ctx) => { - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() await expect(() => client.getReleaseByID("non-existant"), - ).rejects.toThrowError(/could not be found/i); + ).rejects.toThrowError(/could not be found/i) await expect(() => client.getReleaseByID("non-existant"), - ).rejects.toThrowError(prismic.PrismicError); -}); + ).rejects.toThrowError(prismic.PrismicError) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getReleaseByID("id", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getReleaseByID("id", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getReleaseByID("id", params), mode: "repository", -}); +}) diff --git a/test/client-getReleaseByLabel.test.ts b/test/client-getReleaseByLabel.test.ts index 25ec9fdc..81c54ccc 100644 --- a/test/client-getReleaseByLabel.test.ts +++ b/test/client-getReleaseByLabel.test.ts @@ -1,51 +1,51 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns a Release by label", async (ctx) => { - const ref1 = ctx.mock.api.ref({ isMasterRef: true }); - const ref2 = ctx.mock.api.ref({ isMasterRef: false }); - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref1, ref2]; + const ref1 = ctx.mock.api.ref({ isMasterRef: true }) + const ref2 = ctx.mock.api.ref({ isMasterRef: false }) + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref1, ref2] mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getReleaseByLabel(ref2.label); + const client = createTestClient() + const res = await client.getReleaseByLabel(ref2.label) - expect(res).toStrictEqual(ref2); -}); + expect(res).toStrictEqual(ref2) +}) it("throws if Release could not be found", async (ctx) => { - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() await expect(() => client.getReleaseByLabel("non-existant"), - ).rejects.toThrowError(/could not be found/i); + ).rejects.toThrowError(/could not be found/i) await expect(() => client.getReleaseByLabel("non-existant"), - ).rejects.toThrowError(prismic.PrismicError); -}); + ).rejects.toThrowError(prismic.PrismicError) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getReleaseByLabel("label", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getReleaseByLabel("label", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getReleaseByLabel("label", params), mode: "repository", -}); +}) diff --git a/test/client-getReleases.test.ts b/test/client-getReleases.test.ts index 062729c1..61cefcc4 100644 --- a/test/client-getReleases.test.ts +++ b/test/client-getReleases.test.ts @@ -1,35 +1,35 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" it("returns all Releases", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getReleases(); + const client = createTestClient() + const res = await client.getReleases() expect(res).toStrictEqual( repositoryResponse.refs.filter((ref) => !ref.isMasterRef), - ); -}); + ) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getReleases(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getReleases(params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getReleases(params), mode: "repository", -}); +}) diff --git a/test/client-getRepository.test.ts b/test/client-getRepository.test.ts index 54ce5331..3fe18100 100644 --- a/test/client-getRepository.test.ts +++ b/test/client-getRepository.test.ts @@ -1,48 +1,48 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -import * as prismic from "../src"; +import type * as prismic from "../src" it("returns repository metadata", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getRepository(); + const client = createTestClient() + const res = await client.getRepository() - expect(res).toStrictEqual(repositoryResponse); -}); + expect(res).toStrictEqual(repositoryResponse) +}) // TODO: Remove when Authorization header support works in browsers with CORS. it("includes access token if configured", async (ctx) => { const clientConfig: prismic.ClientConfig = { accessToken: "accessToken", - }; + } - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() mockPrismicRestAPIV2({ repositoryResponse, accessToken: clientConfig.accessToken, ctx, - }); + }) - const client = createTestClient({ clientConfig }); - const res = await client.getRepository(); + const client = createTestClient({ clientConfig }) + const res = await client.getRepository() - expect(res).toStrictEqual(repositoryResponse); -}); + expect(res).toStrictEqual(repositoryResponse) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getRepository(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getRepository(params), -}); +}) diff --git a/test/client-getSingle.test.ts b/test/client-getSingle.test.ts index 20b94f51..8e123578 100644 --- a/test/client-getSingle.test.ts +++ b/test/client-getSingle.test.ts @@ -1,14 +1,14 @@ -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testGetFirstMethod } from "./__testutils__/testAnyGetMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" testGetFirstMethod("queries for singleton document", { run: (client) => client.getSingle("type"), requiredParams: { q: `[[at(document.type, "type")]]`, }, -}); +}) testGetFirstMethod("includes params if provided", { run: (client) => @@ -23,17 +23,17 @@ testGetFirstMethod("includes params if provided", { lang: "*", q: `[[at(document.type, "type")]]`, }, -}); +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getSingle("type", params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getSingle("type", params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getSingle("type", params), mode: "get", -}); +}) diff --git a/test/client-getTags.test.ts b/test/client-getTags.test.ts index 18162bd7..c170591e 100644 --- a/test/client-getTags.test.ts +++ b/test/client-getTags.test.ts @@ -1,31 +1,31 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as msw from "msw"; +import * as msw from "msw" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" it("returns all tags", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.getTags(); + const client = createTestClient() + const res = await client.getTags() - expect(res).toStrictEqual(repositoryResponse.tags); -}); + expect(res).toStrictEqual(repositoryResponse.tags) +}) it("uses form endpoint if available", async (ctx) => { - const tagsEndpoint = "https://example.com/tags-form-endpoint"; - const tagsResponse = ["foo", "bar"]; + const tagsEndpoint = "https://example.com/tags-form-endpoint" + const tagsResponse = ["foo", "bar"] - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() repositoryResponse.forms = { tags: { method: "GET", @@ -33,29 +33,29 @@ it("uses form endpoint if available", async (ctx) => { enctype: "", fields: {}, }, - }; + } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(tagsEndpoint, (_req, res, ctx) => { - return res(ctx.json(tagsResponse)); + return res(ctx.json(tagsResponse)) }), - ); + ) - const client = createTestClient(); - const res = await client.getTags(); + const client = createTestClient() + const res = await client.getTags() - expect(res).toStrictEqual(tagsResponse); -}); + expect(res).toStrictEqual(tagsResponse) +}) it("sends access token if form endpoint is used", async (ctx) => { - const tagsEndpoint = "https://example.com/tags-form-endpoint"; - const tagsResponse = ["foo", "bar"]; - const accessToken = "accessToken"; + const tagsEndpoint = "https://example.com/tags-form-endpoint" + const tagsResponse = ["foo", "bar"] + const accessToken = "accessToken" - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() repositoryResponse.forms = { tags: { method: "GET", @@ -63,34 +63,34 @@ it("sends access token if form endpoint is used", async (ctx) => { enctype: "", fields: {}, }, - }; + } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(tagsEndpoint, (req, res, ctx) => { if (req.url.searchParams.get("access_token") === accessToken) { - return res(ctx.json(tagsResponse)); + return res(ctx.json(tagsResponse)) } }), - ); + ) - const client = createTestClient({ clientConfig: { accessToken } }); - const res = await client.getTags(); + const client = createTestClient({ clientConfig: { accessToken } }) + const res = await client.getTags() - expect(res).toStrictEqual(tagsResponse); -}); + expect(res).toStrictEqual(tagsResponse) +}) testFetchOptions("supports fetch options", { run: (client, params) => client.getTags(params), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => client.getTags(params), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => client.getTags(params), mode: "tags", -}); +}) diff --git a/test/client-graphQLFetch.test.ts b/test/client-graphQLFetch.test.ts index f9e282f8..5a4c540e 100644 --- a/test/client-graphQLFetch.test.ts +++ b/test/client-graphQLFetch.test.ts @@ -1,50 +1,50 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as msw from "msw"; +import * as msw from "msw" -import { createAuthorizationHeader } from "./__testutils__/createAuthorizationHeader"; -import { createTestClient } from "./__testutils__/createClient"; -import { createRepositoryName } from "./__testutils__/createRepositoryName"; -import { getMasterRef } from "./__testutils__/getMasterRef"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; +import { createAuthorizationHeader } from "./__testutils__/createAuthorizationHeader" +import { createTestClient } from "./__testutils__/createClient" +import { createRepositoryName } from "./__testutils__/createRepositoryName" +import { getMasterRef } from "./__testutils__/getMasterRef" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" it("resolves a query", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const repositoryResponse = ctx.mock.api.repository() + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(graphqlURL, (req, res, ctx) => { if (req.headers.get("Prismic-Ref") === getMasterRef(repositoryResponse)) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) - const client = createTestClient(); - const res = await client.graphQLFetch(graphqlURL); - const json = await res.json(); + const client = createTestClient() + const res = await client.graphQLFetch(graphqlURL) + const json = await res.json() - expect(json).toStrictEqual(graphqlResponse); -}); + expect(json).toStrictEqual(graphqlResponse) +}) it("merges provided headers with defaults", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.integrationFieldsRef = ctx.mock.api.ref().ref; - const ref = "custom-ref"; + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.integrationFieldsRef = ctx.mock.api.ref().ref + const ref = "custom-ref" - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(graphqlURL, (req, res, ctx) => { if ( @@ -52,34 +52,34 @@ it("merges provided headers with defaults", async (ctx) => { req.headers.get("Prismic-integration-field-ref") === repositoryResponse.integrationFieldsRef ) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) - const client = createTestClient(); + const client = createTestClient() const res = await client.graphQLFetch(graphqlURL, { headers: { "Prismic-Ref": ref, }, - }); - const json = await res.json(); + }) + const json = await res.json() - expect(json).toStrictEqual(graphqlResponse); -}); + expect(json).toStrictEqual(graphqlResponse) +}) // TODO: This test doesn't seem to test what the description claims. it("includes Authorization header if access token is provided", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.integrationFieldsRef = ctx.mock.api.ref().ref; + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.integrationFieldsRef = ctx.mock.api.ref().ref - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(graphqlURL, (req, res, ctx) => { if ( @@ -87,30 +87,30 @@ it("includes Authorization header if access token is provided", async (ctx) => { req.headers.get("Prismic-integration-field-ref") === repositoryResponse.integrationFieldsRef ) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) - const client = createTestClient(); - const res = await client.graphQLFetch(graphqlURL); - const json = await res.json(); + const client = createTestClient() + const res = await client.graphQLFetch(graphqlURL) + const json = await res.json() - expect(json).toStrictEqual(graphqlResponse); -}); + expect(json).toStrictEqual(graphqlResponse) +}) // TODO: This test doesn't seem to test what the description claims. it("includes integration fields header if ref is available", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - const accessToken = "accessToken"; + const repositoryResponse = ctx.mock.api.repository() + const accessToken = "accessToken" - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(graphqlURL, (req, res, ctx) => { if ( @@ -118,25 +118,25 @@ it("includes integration fields header if ref is available", async (ctx) => { req.headers.get("Authorization") === createAuthorizationHeader(accessToken) ) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) - const client = createTestClient({ clientConfig: { accessToken } }); - const res = await client.graphQLFetch(graphqlURL); - const json = await res.json(); + const client = createTestClient({ clientConfig: { accessToken } }) + const res = await client.graphQLFetch(graphqlURL) + const json = await res.json() - expect(json).toStrictEqual(graphqlResponse); -}); + expect(json).toStrictEqual(graphqlResponse) +}) it("optimizes queries by removing whitespace", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); + const repositoryResponse = ctx.mock.api.repository() - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } - const graphqlURLWithUncompressedQuery = new URL(graphqlURL); + const graphqlURLWithUncompressedQuery = new URL(graphqlURL) graphqlURLWithUncompressedQuery.searchParams.set( "query", `query { @@ -150,12 +150,12 @@ it("optimizes queries by removing whitespace", async (ctx) => { } } }`, - ); + ) mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(graphqlURL, (req, res, ctx) => { if ( @@ -163,65 +163,65 @@ it("optimizes queries by removing whitespace", async (ctx) => { "query{allPage{edges{node{_meta{uid}}}}}" && req.headers.get("Prismic-Ref") === getMasterRef(repositoryResponse) ) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) - const client = createTestClient(); + const client = createTestClient() const res = await client.graphQLFetch( graphqlURLWithUncompressedQuery.toString(), - ); - const json = await res.json(); + ) + const json = await res.json() - expect(json).toStrictEqual(graphqlResponse); -}); + expect(json).toStrictEqual(graphqlResponse) +}) it("includes a ref URL parameter to cache-bust", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - const ref = getMasterRef(repositoryResponse); + const repositoryResponse = ctx.mock.api.repository() + const ref = getMasterRef(repositoryResponse) - const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`; - const graphqlResponse = { foo: "bar" }; + const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql` + const graphqlResponse = { foo: "bar" } mockPrismicRestAPIV2({ repositoryResponse, ctx, - }); + }) ctx.server.use( msw.rest.get(graphqlURL, (req, res, ctx) => { if ( req.url.searchParams.get("ref") === ref && req.headers.get("Prismic-Ref") === ref ) { - return res(ctx.json(graphqlResponse)); + return res(ctx.json(graphqlResponse)) } }), - ); + ) - const client = createTestClient(); - const res = await client.graphQLFetch(graphqlURL); - const json = await res.json(); + const client = createTestClient() + const res = await client.graphQLFetch(graphqlURL) + const json = await res.json() - expect(json).toStrictEqual(graphqlResponse); -}); + expect(json).toStrictEqual(graphqlResponse) +}) // `graphQLFetch()` uses a different function signature from query methods, so // we cannot use the generalized `testAbortableMethod()` test util. it("is abortable with an AbortController", async (ctx) => { - const controller = new AbortController(); - controller.abort(); + const controller = new AbortController() + controller.abort() - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() await expect(async () => { await client.graphQLFetch("https://foo.cdn.prismic.io/graphql", { signal: controller.signal, - }); - }).rejects.toThrow(/aborted/i); -}); + }) + }).rejects.toThrow(/aborted/i) +}) testConcurrentMethod("does not share concurrent equivalent network requests", { run: (client, params) => @@ -230,4 +230,4 @@ testConcurrentMethod("does not share concurrent equivalent network requests", { params, ), mode: "NOT-SHARED___graphQL", -}); +}) diff --git a/test/client-queryContentFromRef.test.ts b/test/client-queryContentFromRef.test.ts index 058fd7e9..aa74ad65 100644 --- a/test/client-queryContentFromRef.test.ts +++ b/test/client-queryContentFromRef.test.ts @@ -1,37 +1,37 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismicM from "@prismicio/mock"; +import * as prismicM from "@prismicio/mock" -import { createTestClient } from "./__testutils__/createClient"; -import { getMasterRef } from "./__testutils__/getMasterRef"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testGetMethod } from "./__testutils__/testAnyGetMethod"; +import { createTestClient } from "./__testutils__/createClient" +import { getMasterRef } from "./__testutils__/getMasterRef" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testGetMethod } from "./__testutils__/testAnyGetMethod" testGetMethod("supports manual string ref", { run: (client) => { - client.queryContentFromRef("ref"); + client.queryContentFromRef("ref") - return client.get(); + return client.get() }, requiredParams: { ref: "ref", }, -}); +}) testGetMethod("supports manual thunk ref", { run: (client) => { - client.queryContentFromRef(async () => "thunk"); + client.queryContentFromRef(async () => "thunk") - return client.get(); + return client.get() }, requiredParams: { ref: "thunk", }, -}); +}) it("uses master ref if manual thunk ref returns non-string value", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, @@ -40,13 +40,13 @@ it("uses master ref if manual thunk ref returns non-string value", async (ctx) = ref: getMasterRef(repositoryResponse), }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() - client.queryContentFromRef(async () => undefined); + client.queryContentFromRef(async () => undefined) - const res = await client.get(); + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) diff --git a/test/client-queryContentFromReleaseById.test.ts b/test/client-queryContentFromReleaseById.test.ts index 882b0dca..3855d2ef 100644 --- a/test/client-queryContentFromReleaseById.test.ts +++ b/test/client-queryContentFromReleaseById.test.ts @@ -1,26 +1,23 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismicM from "@prismicio/mock"; +import * as prismicM from "@prismicio/mock" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { - testGetOutsideTTL, - testGetWithinTTL, -} from "./__testutils__/testGetTTL"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testGetOutsideTTL, testGetWithinTTL } from "./__testutils__/testGetTTL" // Do not use `_mock` within tests. Use the text-specific `ctx.mock` instead. const _mock = prismicM.createMockFactory({ seed: "queryContentFromReleaseByID", -}); -const ref1 = _mock.api.ref({ isMasterRef: false }); -const ref2 = _mock.api.ref({ isMasterRef: false }); -ref2.id = ref1.id; +}) +const ref1 = _mock.api.ref({ isMasterRef: false }) +const ref2 = _mock.api.ref({ isMasterRef: false }) +ref2.id = ref1.id it("uses a releases ref by ID", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref1]; - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref1] + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, @@ -29,16 +26,16 @@ it("uses a releases ref by ID", async (ctx) => { ref: ref1.ref, }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() - client.queryContentFromReleaseByID(ref1.id); + client.queryContentFromReleaseByID(ref1.id) - const res = await client.get(); + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) testGetWithinTTL("uses the cached release ref within the ref's TTL", { getContext: { @@ -46,7 +43,7 @@ testGetWithinTTL("uses the cached release ref within the ref's TTL", { getRef: () => ref1.ref, }, beforeFirstGet: (args) => args.client.queryContentFromReleaseByID(ref1.id), -}); +}) testGetOutsideTTL("uses a fresh release ref outside of the cached ref's TTL", { getContext1: { @@ -58,4 +55,4 @@ testGetOutsideTTL("uses a fresh release ref outside of the cached ref's TTL", { getRef: () => ref2.ref, }, beforeFirstGet: (args) => args.client.queryContentFromReleaseByID(ref1.id), -}); +}) diff --git a/test/client-queryContentFromReleaseByLabel.test.ts b/test/client-queryContentFromReleaseByLabel.test.ts index b12920fe..8eb2e78f 100644 --- a/test/client-queryContentFromReleaseByLabel.test.ts +++ b/test/client-queryContentFromReleaseByLabel.test.ts @@ -1,26 +1,23 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismicM from "@prismicio/mock"; +import * as prismicM from "@prismicio/mock" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { - testGetOutsideTTL, - testGetWithinTTL, -} from "./__testutils__/testGetTTL"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testGetOutsideTTL, testGetWithinTTL } from "./__testutils__/testGetTTL" // Do not use `_mock` within tests. Use the text-specific `ctx.mock` instead. const _mock = prismicM.createMockFactory({ seed: "queryContentFromReleaseByLabel", -}); -const ref1 = _mock.api.ref({ isMasterRef: false }); -const ref2 = _mock.api.ref({ isMasterRef: false }); -ref2.label = ref1.label; +}) +const ref1 = _mock.api.ref({ isMasterRef: false }) +const ref2 = _mock.api.ref({ isMasterRef: false }) +ref2.label = ref1.label it("uses a releases ref by label", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.refs = [ref1]; - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.refs = [ref1] + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, @@ -29,16 +26,16 @@ it("uses a releases ref by label", async (ctx) => { ref: ref1.ref, }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() - client.queryContentFromReleaseByLabel(ref1.label); + client.queryContentFromReleaseByLabel(ref1.label) - const res = await client.get(); + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) testGetWithinTTL("uses the cached release ref within the ref's TTL", { getContext: { @@ -47,7 +44,7 @@ testGetWithinTTL("uses the cached release ref within the ref's TTL", { }, beforeFirstGet: (args) => args.client.queryContentFromReleaseByLabel(ref1.label), -}); +}) testGetOutsideTTL("uses a fresh release ref outside of the cached ref's TTL", { getContext1: { @@ -60,4 +57,4 @@ testGetOutsideTTL("uses a fresh release ref outside of the cached ref's TTL", { }, beforeFirstGet: (args) => args.client.queryContentFromReleaseByLabel(ref1.label), -}); +}) diff --git a/test/client-queryLatestContent.test.ts b/test/client-queryLatestContent.test.ts index 1fca69ba..70e07624 100644 --- a/test/client-queryLatestContent.test.ts +++ b/test/client-queryLatestContent.test.ts @@ -1,15 +1,12 @@ -import { getMasterRef } from "./__testutils__/getMasterRef"; -import { - testGetOutsideTTL, - testGetWithinTTL, -} from "./__testutils__/testGetTTL"; +import { getMasterRef } from "./__testutils__/getMasterRef" +import { testGetOutsideTTL, testGetWithinTTL } from "./__testutils__/testGetTTL" testGetWithinTTL("uses the cached master ref within the ref's TTL", { getContext: { getRef: getMasterRef, }, beforeFirstGet: (args) => args.client.queryLatestContent(), -}); +}) testGetOutsideTTL( "uses a fresh master ref outside of the cached ref's TTL", @@ -23,4 +20,4 @@ testGetOutsideTTL( }, beforeFirstGet: (args) => args.client.queryLatestContent(), }, -); +) diff --git a/test/client-resolvePreviewUrl.test.ts b/test/client-resolvePreviewUrl.test.ts index 3eee966b..46b13418 100644 --- a/test/client-resolvePreviewUrl.test.ts +++ b/test/client-resolvePreviewUrl.test.ts @@ -1,25 +1,25 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismicM from "@prismicio/mock"; -import { Headers } from "node-fetch"; +import * as prismicM from "@prismicio/mock" +import { Headers } from "node-fetch" -import { createTestClient } from "./__testutils__/createClient"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; -import { testAbortableMethod } from "./__testutils__/testAbortableMethod"; -import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod"; -import { testFetchOptions } from "./__testutils__/testFetchOptions"; +import { createTestClient } from "./__testutils__/createClient" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" +import { testAbortableMethod } from "./__testutils__/testAbortableMethod" +import { testConcurrentMethod } from "./__testutils__/testConcurrentMethod" +import { testFetchOptions } from "./__testutils__/testFetchOptions" -const previewToken = "previewToken"; +const previewToken = "previewToken" it("resolves a preview url in the browser", async (ctx) => { - const seed = ctx.task.name; - const document = { ...prismicM.value.document({ seed }), uid: seed }; - const queryResponse = prismicM.api.query({ seed, documents: [document] }); + const seed = ctx.task.name + const document = { ...prismicM.value.document({ seed }), uid: seed } + const queryResponse = prismicM.api.query({ seed, documents: [document] }) globalThis.location = { ...globalThis.location, search: `?documentId=${document.id}&token=${previewToken}`, - }; + } mockPrismicRestAPIV2({ queryResponse, @@ -30,31 +30,31 @@ it("resolves a preview url in the browser", async (ctx) => { q: `[[at(document.id, "${document.id}")]]`, }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL: "defaultURL", - }); + }) - expect(res).toBe(`/${document.uid}`); + expect(res).toBe(`/${document.uid}`) // @ts-expect-error - Need to reset back to Node.js's default globalThis without `location` - globalThis.location = undefined; -}); + globalThis.location = undefined +}) it("resolves a preview url using a server req object", async (ctx) => { - const seed = ctx.task.name; - const document = { ...prismicM.value.document({ seed }), uid: seed }; - const queryResponse = prismicM.api.query({ seed, documents: [document] }); + const seed = ctx.task.name + const document = { ...prismicM.value.document({ seed }), uid: seed } + const queryResponse = prismicM.api.query({ seed, documents: [document] }) const req = { query: { documentId: document.id, token: previewToken }, // This `url` property simulates a Next.js request. It is a // partial URL only containing the pathname + search params. url: `/foo?bar=baz`, - }; + } mockPrismicRestAPIV2({ queryResponse, @@ -65,31 +65,31 @@ it("resolves a preview url using a server req object", async (ctx) => { q: `[[at(document.id, "${document.id}")]]`, }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL: "defaultURL", - }); + }) - expect(res).toBe(`/${document.uid}`); -}); + expect(res).toBe(`/${document.uid}`) +}) it("resolves a preview url using a Web API-based server req object", async (ctx) => { - const seed = ctx.task.name; - const document = { ...prismicM.value.document({ seed }), uid: seed }; - const queryResponse = prismicM.api.query({ seed, documents: [document] }); - - const headers = new Headers(); - const url = new URL("https://example.com"); - url.searchParams.set("documentId", document.id); - url.searchParams.set("token", previewToken); + const seed = ctx.task.name + const document = { ...prismicM.value.document({ seed }), uid: seed } + const queryResponse = prismicM.api.query({ seed, documents: [document] }) + + const headers = new Headers() + const url = new URL("https://example.com") + url.searchParams.set("documentId", document.id) + url.searchParams.set("token", previewToken) const req = { headers, url: url.toString(), - }; + } mockPrismicRestAPIV2({ queryResponse, @@ -100,29 +100,29 @@ it("resolves a preview url using a Web API-based server req object", async (ctx) q: `[[at(document.id, "${document.id}")]]`, }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL: "defaultURL", - }); + }) - expect(res).toBe(`/${document.uid}`); -}); + expect(res).toBe(`/${document.uid}`) +}) it("resolves a preview url using a Web API-based server req object containing a URL without a host", async (ctx) => { - const seed = ctx.task.name; - const document = { ...prismicM.value.document({ seed }), uid: seed }; - const queryResponse = prismicM.api.query({ seed, documents: [document] }); + const seed = ctx.task.name + const document = { ...prismicM.value.document({ seed }), uid: seed } + const queryResponse = prismicM.api.query({ seed, documents: [document] }) - const headers = new Headers(); - const url = `/foo?documentId=${document.id}&token=${previewToken}`; + const headers = new Headers() + const url = `/foo?documentId=${document.id}&token=${previewToken}` const req = { headers, url: url.toString(), - }; + } mockPrismicRestAPIV2({ queryResponse, @@ -133,29 +133,29 @@ it("resolves a preview url using a Web API-based server req object containing a q: `[[at(document.id, "${document.id}")]]`, }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL: "defaultURL", - }); + }) - expect(res).toBe(`/${document.uid}`); -}); + expect(res).toBe(`/${document.uid}`) +}) it("allows providing an explicit documentId and previewToken", async (ctx) => { - const seed = ctx.task.name; - const document = { ...prismicM.value.document({ seed }), uid: seed }; - const queryResponse = prismicM.api.query({ seed, documents: [document] }); + const seed = ctx.task.name + const document = { ...prismicM.value.document({ seed }), uid: seed } + const queryResponse = prismicM.api.query({ seed, documents: [document] }) const req = { query: { documentId: "this will not be used", token: "this will not be used", }, - }; + } mockPrismicRestAPIV2({ queryResponse, @@ -166,73 +166,73 @@ it("allows providing an explicit documentId and previewToken", async (ctx) => { q: `[[at(document.id, "${document.id}")]]`, }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL: "defaultURL", documentID: document.id, previewToken, - }); + }) - expect(res).toBe(`/${document.uid}`); -}); + expect(res).toBe(`/${document.uid}`) +}) it("returns defaultURL if current url does not contain preview params in browser", async () => { - const defaultURL = "defaultURL"; + const defaultURL = "defaultURL" // Set a global Location object without the parameters we need for automatic // preview support. - globalThis.location = { ...globalThis.location, search: "" }; + globalThis.location = { ...globalThis.location, search: "" } - const client = createTestClient(); + const client = createTestClient() const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL, - }); + }) - expect(res).toBe(defaultURL); + expect(res).toBe(defaultURL) // @ts-expect-error - Need to reset back to Node.js's default globalThis without `location` - globalThis.location = undefined; -}); + globalThis.location = undefined +}) it("returns defaultURL if req does not contain preview params in server req object", async () => { - const defaultURL = "defaultURL"; - const req = {}; + const defaultURL = "defaultURL" + const req = {} - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL, - }); + }) - expect(res).toBe(defaultURL); -}); + expect(res).toBe(defaultURL) +}) it("returns defaultURL if no preview context is available", async () => { - const defaultURL = "defaultURL"; + const defaultURL = "defaultURL" - const client = createTestClient(); + const client = createTestClient() const res = await client.resolvePreviewURL({ linkResolver: (document) => `/${document.uid}`, defaultURL, - }); + }) - expect(res).toBe(defaultURL); -}); + expect(res).toBe(defaultURL) +}) it("returns defaultURL if resolved URL is not a string", async (ctx) => { - const seed = ctx.task.name; + const seed = ctx.task.name const document = { ...prismicM.value.document({ seed, withURL: false }), uid: seed, - }; - const queryResponse = prismicM.api.query({ seed, documents: [document] }); - const defaultURL = "defaultURL"; + } + const queryResponse = prismicM.api.query({ seed, documents: [document] }) + const defaultURL = "defaultURL" mockPrismicRestAPIV2({ queryResponse, @@ -243,18 +243,18 @@ it("returns defaultURL if resolved URL is not a string", async (ctx) => { q: `[[at(document.id, "${document.id}")]]`, }, ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() const res = await client.resolvePreviewURL({ linkResolver: () => null, defaultURL, documentID: document.id, previewToken, - }); + }) - expect(res).toBe(defaultURL); -}); + expect(res).toBe(defaultURL) +}) testFetchOptions("supports fetch options", { run: (client, params) => @@ -264,7 +264,7 @@ testFetchOptions("supports fetch options", { documentID: "foo", previewToken, }), -}); +}) testAbortableMethod("is abortable with an AbortController", { run: (client, params) => @@ -274,7 +274,7 @@ testAbortableMethod("is abortable with an AbortController", { documentID: "foo", previewToken, }), -}); +}) testConcurrentMethod("shares concurrent equivalent network requests", { run: (client, params) => @@ -285,4 +285,4 @@ testConcurrentMethod("shares concurrent equivalent network requests", { previewToken, }), mode: "resolvePreview", -}); +}) diff --git a/test/client.test.ts b/test/client.test.ts index 80869619..1f3a7d77 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -1,43 +1,43 @@ -import { expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest" -import * as prismicM from "@prismicio/mock"; -import * as msw from "msw"; -import { Headers, Response } from "node-fetch"; +import * as prismicM from "@prismicio/mock" +import * as msw from "msw" +import { Headers, Response } from "node-fetch" -import { createTestClient } from "./__testutils__/createClient"; -import { getMasterRef } from "./__testutils__/getMasterRef"; -import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2"; +import { createTestClient } from "./__testutils__/createClient" +import { getMasterRef } from "./__testutils__/getMasterRef" +import { mockPrismicRestAPIV2 } from "./__testutils__/mockPrismicRestAPIV2" -import * as prismic from "../src"; +import * as prismic from "../src" it("createClient creates a Client", () => { const client = prismic.createClient("qwerty", { fetch: vi.fn(), - }); + }) - expect(client).toBeInstanceOf(prismic.Client); -}); + expect(client).toBeInstanceOf(prismic.Client) +}) it("creates a client with a repository name", () => { - const repositoryName = "qwerty"; + const repositoryName = "qwerty" const client = prismic.createClient(repositoryName, { fetch: vi.fn(), - }); + }) - expect(client.endpoint).toBe(prismic.getRepositoryEndpoint(repositoryName)); -}); + expect(client.endpoint).toBe(prismic.getRepositoryEndpoint(repositoryName)) +}) it("creates a client with a Rest API V2 endpoint", () => { - const endpoint = prismic.getRepositoryEndpoint("qwerty"); + const endpoint = prismic.getRepositoryEndpoint("qwerty") const client = prismic.createClient(endpoint, { fetch: vi.fn(), - }); + }) - expect(client.endpoint).toBe(endpoint); -}); + expect(client.endpoint).toBe(endpoint) +}) it("client has correct default state", () => { - const endpoint = prismic.getRepositoryEndpoint("qwerty"); + const endpoint = prismic.getRepositoryEndpoint("qwerty") const options: prismic.ClientConfig = { accessToken: "accessToken", ref: "ref", @@ -45,135 +45,135 @@ it("client has correct default state", () => { defaultParams: { lang: "*", }, - }; - const client = prismic.createClient(endpoint, options); + } + const client = prismic.createClient(endpoint, options) - expect(client.endpoint).toBe(endpoint); - expect(client.accessToken).toBe(options.accessToken); - expect(client.fetchFn).toBe(options.fetch as prismic.FetchLike); - expect(client.defaultParams).toBe(options.defaultParams); -}); + expect(client.endpoint).toBe(endpoint) + expect(client.accessToken).toBe(options.accessToken) + expect(client.fetchFn).toBe(options.fetch as prismic.FetchLike) + expect(client.defaultParams).toBe(options.defaultParams) +}) it("constructor throws if an invalid repository name is provided", () => { expect(() => { prismic.createClient("invalid repository name", { fetch: vi.fn(), - }); - }).toThrowError(/an invalid Prismic repository name was given/i); + }) + }).toThrowError(/an invalid Prismic repository name was given/i) expect(() => { prismic.createClient("invalid repository name", { fetch: vi.fn(), - }); - }).toThrowError(prismic.PrismicError); -}); + }) + }).toThrowError(prismic.PrismicError) +}) it("constructor throws if an invalid repository endpoint is provided", () => { expect(() => { prismic.createClient("https://invalid url.cdn.prismic.io/api/v2", { fetch: vi.fn(), - }); - }).toThrowError(/an invalid Prismic repository name was given/i); + }) + }).toThrowError(/an invalid Prismic repository name was given/i) expect(() => { prismic.createClient("https://invalid url.cdn.prismic.io/api/v2", { fetch: vi.fn(), - }); - }).toThrowError(prismic.PrismicError); -}); + }) + }).toThrowError(prismic.PrismicError) +}) it("constructor throws if a prismic.io endpoint is given that is not for Rest API V2", () => { - const fetch = vi.fn(); + const fetch = vi.fn() - const originalNodeEnv = process.env.NODE_ENV; - process.env.NODE_ENV = "development"; + const originalNodeEnv = process.env.NODE_ENV + process.env.NODE_ENV = "development" expect(() => { - prismic.createClient("https://qwerty.cdn.prismic.io/api/v1", { fetch }); - }).toThrowError(/only supports Prismic Rest API V2/i); + prismic.createClient("https://qwerty.cdn.prismic.io/api/v1", { fetch }) + }).toThrowError(/only supports Prismic Rest API V2/i) expect(() => { - prismic.createClient("https://qwerty.cdn.prismic.io/api/v1", { fetch }); - }).toThrowError(prismic.PrismicError); + prismic.createClient("https://qwerty.cdn.prismic.io/api/v1", { fetch }) + }).toThrowError(prismic.PrismicError) expect(() => { - prismic.createClient("https://example.com/custom/endpoint", { fetch }); - }, "Non-prismic.io endpoints are not checked").not.toThrow(); + prismic.createClient("https://example.com/custom/endpoint", { fetch }) + }, "Non-prismic.io endpoints are not checked").not.toThrow() expect(() => { - prismic.createClient("https://qwerty.cdn.prismic.io/api/v2", { fetch }); - }, "A valid prismic.io V2 endpoint does not throw").not.toThrow(); + prismic.createClient("https://qwerty.cdn.prismic.io/api/v2", { fetch }) + }, "A valid prismic.io V2 endpoint does not throw").not.toThrow() expect(() => { - prismic.createClient(prismic.getRepositoryEndpoint("qwerty"), { fetch }); - }, "An endpoint created with getRepositoryEndpoint does not throw").not.toThrow(); + prismic.createClient(prismic.getRepositoryEndpoint("qwerty"), { fetch }) + }, "An endpoint created with getRepositoryEndpoint does not throw").not.toThrow() - process.env.NODE_ENV = originalNodeEnv; -}); + process.env.NODE_ENV = originalNodeEnv +}) it("constructor warns if a non-.cdn prismic.io endpoint is given", () => { - const fetch = vi.fn(); + const fetch = vi.fn() - const originalNodeEnv = process.env.NODE_ENV; - process.env.NODE_ENV = "development"; + const originalNodeEnv = process.env.NODE_ENV + process.env.NODE_ENV = "development" const consoleWarnSpy = vi .spyOn(console, "warn") - .mockImplementation(() => void 0); + .mockImplementation(() => void 0) - prismic.createClient("https://qwerty.prismic.io/api/v2", { fetch }); + prismic.createClient("https://qwerty.prismic.io/api/v2", { fetch }) expect(consoleWarnSpy).toHaveBeenCalledWith( expect.stringMatching(/endpoint-must-use-cdn/i), - ); - consoleWarnSpy.mockClear(); + ) + consoleWarnSpy.mockClear() - prismic.createClient("https://example.com/custom/endpoint", { fetch }); + prismic.createClient("https://example.com/custom/endpoint", { fetch }) expect( consoleWarnSpy, "Non-prismic.io endpoints are not checked", - ).not.toHaveBeenCalledWith(expect.stringMatching(/endpoint-must-use-cdn/i)); - consoleWarnSpy.mockClear(); + ).not.toHaveBeenCalledWith(expect.stringMatching(/endpoint-must-use-cdn/i)) + consoleWarnSpy.mockClear() - prismic.createClient("https://qwerty.cdn.prismic.io/api/v2", { fetch }); + prismic.createClient("https://qwerty.cdn.prismic.io/api/v2", { fetch }) expect( consoleWarnSpy, "A .cdn prismic.io endpoint does not warn", - ).not.toHaveBeenCalledWith(expect.stringMatching(/endpoint-must-use-cdn/i)); - consoleWarnSpy.mockClear(); + ).not.toHaveBeenCalledWith(expect.stringMatching(/endpoint-must-use-cdn/i)) + consoleWarnSpy.mockClear() - prismic.createClient(prismic.getRepositoryEndpoint("qwerty"), { fetch }); + prismic.createClient(prismic.getRepositoryEndpoint("qwerty"), { fetch }) expect( consoleWarnSpy, "An endpoint created with getRepositoryEndpoint does not warn", - ).not.toHaveBeenCalledWith(expect.stringMatching(/endpoint-must-use-cdn/i)); + ).not.toHaveBeenCalledWith(expect.stringMatching(/endpoint-must-use-cdn/i)) - consoleWarnSpy.mockRestore(); + consoleWarnSpy.mockRestore() - process.env.NODE_ENV = originalNodeEnv; -}); + process.env.NODE_ENV = originalNodeEnv +}) it("constructor throws if fetch is unavailable", () => { - const endpoint = prismic.getRepositoryEndpoint("qwerty"); + const endpoint = prismic.getRepositoryEndpoint("qwerty") - const originalFetch = globalThis.fetch; + const originalFetch = globalThis.fetch // @ts-expect-error - Forcing fetch to be undefined - delete globalThis.fetch; + delete globalThis.fetch expect(() => prismic.createClient(endpoint)).toThrowError( /fetch implementation was not provided/i, - ); + ) expect(() => prismic.createClient(endpoint)).toThrowError( prismic.PrismicError, - ); + ) - globalThis.fetch = originalFetch; -}); + globalThis.fetch = originalFetch +}) it("constructor throws if provided fetch is not a function", () => { - const endpoint = prismic.getRepositoryEndpoint("qwerty"); - const fetch = "not a function"; + const endpoint = prismic.getRepositoryEndpoint("qwerty") + const fetch = "not a function" // Unset global fetch to ensure the client won't fall back to the global implementation. - const originalFetch = globalThis.fetch; + const originalFetch = globalThis.fetch // @ts-expect-error - Forcing fetch to be undefined - delete globalThis.fetch; + delete globalThis.fetch expect(() => prismic.createClient(endpoint, { @@ -183,7 +183,7 @@ it("constructor throws if provided fetch is not a function", () => { // @ts-expect-error - We are purposly providing an invalid type to test if it throws. fetch, }), - ).toThrowError(/fetch implementation was not provided/i); + ).toThrowError(/fetch implementation was not provided/i) expect(() => prismic.createClient(endpoint, { // We wouldn't normally test for input types since TypeScript handles @@ -192,232 +192,232 @@ it("constructor throws if provided fetch is not a function", () => { // @ts-expect-error - We are purposly providing an invalid type to test if it throws. fetch, }), - ).toThrowError(prismic.PrismicError); + ).toThrowError(prismic.PrismicError) - globalThis.fetch = originalFetch; -}); + globalThis.fetch = originalFetch +}) it("uses globalThis.fetch if available", async () => { - const endpoint = prismic.getRepositoryEndpoint("qwerty"); - const responseBody = { foo: "bar" }; + const endpoint = prismic.getRepositoryEndpoint("qwerty") + const responseBody = { foo: "bar" } - const existingFetch = globalThis.fetch; + const existingFetch = globalThis.fetch globalThis.fetch = async () => // @ts-expect-error - node-fetch does not implement the full Response interface - new Response(JSON.stringify(responseBody)); + new Response(JSON.stringify(responseBody)) - const client = prismic.createClient(endpoint); - const fetchResponse = await client.fetchFn(""); - const jsonResponse = await fetchResponse.json(); + const client = prismic.createClient(endpoint) + const fetchResponse = await client.fetchFn("") + const jsonResponse = await fetchResponse.json() - expect(jsonResponse).toStrictEqual(responseBody); + expect(jsonResponse).toStrictEqual(responseBody) - globalThis.fetch = existingFetch; -}); + globalThis.fetch = existingFetch +}) it("uses the master ref by default", async (ctx) => { - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ queryResponse, ctx, - }); + }) - const client = createTestClient(); - const res = await client.get(); + const client = createTestClient() + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("supports manual string ref", async (ctx) => { - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); - const ref = "ref"; + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) + const ref = "ref" mockPrismicRestAPIV2({ queryResponse, queryRequiredParams: { ref }, ctx, - }); + }) - const client = createTestClient({ clientConfig: { ref } }); - const res = await client.get(); + const client = createTestClient({ clientConfig: { ref } }) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("supports manual thunk ref", async (ctx) => { - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); - const ref = "ref"; + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) + const ref = "ref" mockPrismicRestAPIV2({ queryResponse, queryRequiredParams: { ref }, ctx, - }); + }) - const client = createTestClient({ clientConfig: { ref: () => ref } }); - const res = await client.get(); + const client = createTestClient({ clientConfig: { ref: () => ref } }) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("uses master ref if ref thunk param returns non-string value", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, queryResponse, queryRequiredParams: { ref: getMasterRef(repositoryResponse) }, ctx, - }); + }) - const client = createTestClient({ clientConfig: { ref: () => undefined } }); - const res = await client.get(); + const client = createTestClient({ clientConfig: { ref: () => undefined } }) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("uses browser preview ref if available", async (ctx) => { - const previewRef = "previewRef"; + const previewRef = "previewRef" globalThis.document = { ...globalThis.document, cookie: `io.prismic.preview=${previewRef}`, - }; + } - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ queryResponse, queryRequiredParams: { ref: previewRef }, ctx, - }); + }) - const client = createTestClient(); - const res = await client.get(); + const client = createTestClient() + const res = await client.get() - expect(res).toStrictEqual(queryResponse); + expect(res).toStrictEqual(queryResponse) - globalThis.document.cookie = ""; -}); + globalThis.document.cookie = "" +}) it("uses req preview ref if available", async (ctx) => { - const previewRef = "previewRef"; + const previewRef = "previewRef" const req = { headers: { cookie: `io.prismic.preview=${previewRef}`, }, - }; + } - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ queryResponse, queryRequiredParams: { ref: previewRef }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); - const res = await client.get(); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("supports req with Web APIs", async (ctx) => { - const previewRef = "previewRef"; - const headers = new Headers(); - headers.set("cookie", `io.prismic.preview=${previewRef}`); + const previewRef = "previewRef" + const headers = new Headers() + headers.set("cookie", `io.prismic.preview=${previewRef}`) const req = { headers, url: "https://example.com", - }; + } - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ queryResponse, queryRequiredParams: { ref: previewRef }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); - const res = await client.get(); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("ignores req without cookies", async (ctx) => { const req = { headers: {}, - }; + } - const repositoryResponse = ctx.mock.api.repository(); - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, queryResponse, queryRequiredParams: { ref: getMasterRef(repositoryResponse) }, ctx, - }); + }) - const client = createTestClient(); - client.enableAutoPreviewsFromReq(req); - const res = await client.get(); + const client = createTestClient() + client.enableAutoPreviewsFromReq(req) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("does not use preview ref if auto previews are disabled", async (ctx) => { - const previewRef = "previewRef"; + const previewRef = "previewRef" globalThis.document = { ...globalThis.document, cookie: `io.prismic.preview=${previewRef}`, - }; + } - const repositoryResponse = ctx.mock.api.repository(); - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) - const client = createTestClient(); + const client = createTestClient() // Disable auto previews and ensure the default ref is being used. Note that // the global cookie has already been set by this point, which should be // ignored by the client. - client.disableAutoPreviews(); + client.disableAutoPreviews() mockPrismicRestAPIV2({ repositoryResponse, queryResponse, queryRequiredParams: { ref: getMasterRef(repositoryResponse) }, ctx, - }); + }) - const res1 = await client.get(); + const res1 = await client.get() - expect(res1).toStrictEqual(queryResponse); + expect(res1).toStrictEqual(queryResponse) // Enable previews and ensure the preview ref is being used. - client.enableAutoPreviews(); + client.enableAutoPreviews() mockPrismicRestAPIV2({ repositoryResponse, queryResponse, queryRequiredParams: { ref: previewRef }, ctx, - }); + }) - const resWithPreviews = await client.get(); + const resWithPreviews = await client.get() - expect(resWithPreviews).toStrictEqual(queryResponse); + expect(resWithPreviews).toStrictEqual(queryResponse) - globalThis.document.cookie = ""; -}); + globalThis.document.cookie = "" +}) it("uses the integration fields ref if the repository provides it", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.integrationFieldsRef = ctx.mock.api.ref().ref; - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.integrationFieldsRef = ctx.mock.api.ref().ref + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, @@ -428,18 +428,18 @@ it("uses the integration fields ref if the repository provides it", async (ctx) integrationFieldsRef: repositoryResponse.integrationFieldsRef!, }, ctx, - }); + }) - const client = createTestClient(); - const res = await client.get(); + const client = createTestClient() + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("ignores the integration fields ref if the repository provides a null value", async (ctx) => { - const repositoryResponse = ctx.mock.api.repository(); - repositoryResponse.integrationFieldsRef = null; - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const repositoryResponse = ctx.mock.api.repository() + repositoryResponse.integrationFieldsRef = null + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ repositoryResponse, @@ -448,16 +448,16 @@ it("ignores the integration fields ref if the repository provides a null value", ref: getMasterRef(repositoryResponse), }, ctx, - }); + }) - const client = createTestClient(); - const res = await client.get(); + const client = createTestClient() + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("uses client-provided routes in queries", async (ctx) => { - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) const routes: prismic.Route[] = [ { @@ -475,7 +475,7 @@ it("uses client-provided routes in queries", async (ctx) => { lang: "it-it", path: "/it", }, - ]; + ] mockPrismicRestAPIV2({ queryResponse, @@ -483,18 +483,18 @@ it("uses client-provided routes in queries", async (ctx) => { routes: JSON.stringify(routes), }, ctx, - }); + }) - const client = createTestClient({ clientConfig: { routes } }); - const res = await client.get(); + const client = createTestClient({ clientConfig: { routes } }) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("uses client-provided brokenRoute in queries", async (ctx) => { - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) - const brokenRoute = "/404"; + const brokenRoute = "/404" mockPrismicRestAPIV2({ queryResponse, @@ -502,76 +502,74 @@ it("uses client-provided brokenRoute in queries", async (ctx) => { brokenRoute, }, ctx, - }); + }) - const client = createTestClient({ clientConfig: { brokenRoute } }); - const res = await client.get(); + const client = createTestClient({ clientConfig: { brokenRoute } }) + const res = await client.get() - expect(res).toStrictEqual(queryResponse); -}); + expect(res).toStrictEqual(queryResponse) +}) it("throws ForbiddenError if access token is invalid for repository metadata", async (ctx) => { mockPrismicRestAPIV2({ accessToken: "token", ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() await expect(() => client.getRepository()).rejects.toThrowError( /invalid access token/i, - ); + ) await expect(() => client.getRepository()).rejects.toThrowError( prismic.ForbiddenError, - ); -}); + ) +}) it("throws ForbiddenError if access token is invalid for query", async (ctx) => { mockPrismicRestAPIV2({ accessToken: "token", ctx, - }); + }) - const client = createTestClient(); + const client = createTestClient() - await expect(() => client.get()).rejects.toThrowError( - /invalid access token/i, - ); - await expect(() => client.get()).rejects.toThrowError(prismic.ForbiddenError); -}); + await expect(() => client.get()).rejects.toThrowError(/invalid access token/i) + await expect(() => client.get()).rejects.toThrowError(prismic.ForbiddenError) +}) it("throws ForbiddenError if response code is 403", async (ctx) => { const queryResponse = { error: "Invalid access token", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(403), ctx.json(queryResponse)); + return res(ctx.status(403), ctx.json(queryResponse)) }), - ); + ) - let error: prismic.ForbiddenError | undefined; + let error: prismic.ForbiddenError | undefined try { - await client.get(); + await client.get() } catch (e) { if (e instanceof prismic.ForbiddenError) { - error = e; + error = e } } - expect(error?.message).toBe(queryResponse.error); -}); + expect(error?.message).toBe(queryResponse.error) +}) it("throws ParsingError if response code is 400 with parsing-error type", async (ctx) => { const queryResponse = { @@ -581,164 +579,156 @@ it("throws ParsingError if response code is 400 with parsing-error type", async column: 1, id: 2, location: 3, - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(400), ctx.json(queryResponse)); + return res(ctx.status(400), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError(queryResponse.message); - await expect(() => client.get()).rejects.toThrowError(prismic.ParsingError); -}); + await expect(() => client.get()).rejects.toThrowError(queryResponse.message) + await expect(() => client.get()).rejects.toThrowError(prismic.ParsingError) +}) it("throws PrismicError if response code is 400 but is not a parsing error", async (ctx) => { - const queryResponse = {}; + const queryResponse = {} - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(400), ctx.json(queryResponse)); + return res(ctx.status(400), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError(prismic.PrismicError); -}); + await expect(() => client.get()).rejects.toThrowError(prismic.PrismicError) +}) it("throws PrismicError if response is not 200, 400, 401, 403, or 404", async (ctx) => { - const queryResponse = {}; + const queryResponse = {} - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "./documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(418), ctx.json(queryResponse)); + return res(ctx.status(418), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError( - /invalid api response/i, - ); - await expect(() => client.get()).rejects.toThrowError(prismic.PrismicError); -}); + await expect(() => client.get()).rejects.toThrowError(/invalid api response/i) + await expect(() => client.get()).rejects.toThrowError(prismic.PrismicError) +}) it("throws PrismicError if response is not JSON", async (ctx) => { - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(200)); + return res(ctx.status(200)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError( - /invalid api response/i, - ); - await expect(() => client.get()).rejects.toThrowError(prismic.PrismicError); -}); + await expect(() => client.get()).rejects.toThrowError(/invalid api response/i) + await expect(() => client.get()).rejects.toThrowError(prismic.PrismicError) +}) it("throws RepositoryNotFoundError if repository does not exist", async (ctx) => { - const client = createTestClient(); + const client = createTestClient() ctx.server.use( msw.rest.get(client.endpoint, (_req, res, ctx) => { - return res(ctx.status(404)); + return res(ctx.status(404)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError( - /repository not found/i, - ); + await expect(() => client.get()).rejects.toThrowError(/repository not found/i) await expect(() => client.get()).rejects.toThrowError( prismic.RepositoryNotFoundError, - ); -}); + ) +}) it("throws RefNotFoundError if ref does not exist", async (ctx) => { const queryResponse = { type: "api_notfound_error", message: "message", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "./documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(404), ctx.json(queryResponse)); + return res(ctx.status(404), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError(queryResponse.message); + await expect(() => client.get()).rejects.toThrowError(queryResponse.message) await expect(() => client.get()).rejects.toThrowError( prismic.RefNotFoundError, - ); -}); + ) +}) it("throws RefExpiredError if ref is expired", async (ctx) => { const queryResponse = { type: "api_validation_error", message: "message", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "./documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(410), ctx.json(queryResponse)); + return res(ctx.status(410), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError(queryResponse.message); - await expect(() => client.get()).rejects.toThrowError( - prismic.RefExpiredError, - ); -}); + await expect(() => client.get()).rejects.toThrowError(queryResponse.message) + await expect(() => client.get()).rejects.toThrowError(prismic.RefExpiredError) +}) it("throws PreviewTokenExpiredError if preview token is expired", async (ctx) => { const queryResponse = { @@ -746,86 +736,86 @@ it("throws PreviewTokenExpiredError if preview token is expired", async (ctx) => message: "This preview token has expired", oauth_initiate: "https://qwerty.prismic.io/auth", oauth_token: "https://qwerty.prismic.io/auth/token", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "./documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(404), ctx.json(queryResponse)); + return res(ctx.status(404), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError(queryResponse.message); + await expect(() => client.get()).rejects.toThrowError(queryResponse.message) await expect(() => client.get()).rejects.toThrowError( prismic.PreviewTokenExpiredError, - ); -}); + ) +}) it("throws NotFoundError if the 404 error is unknown", async (ctx) => { const queryResponse = { type: "unknown_type", message: "message", - }; + } - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "./documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - return res(ctx.status(404), ctx.json(queryResponse)); + return res(ctx.status(404), ctx.json(queryResponse)) }), - ); + ) - await expect(() => client.get()).rejects.toThrowError(queryResponse.message); - await expect(() => client.get()).rejects.toThrowError(prismic.NotFoundError); -}); + await expect(() => client.get()).rejects.toThrowError(queryResponse.message) + await expect(() => client.get()).rejects.toThrowError(prismic.NotFoundError) +}) it("retries after `retry-after` milliseconds if response code is 429", async (ctx) => { - const retryAfter = 200; // ms + const retryAfter = 200 // ms /** * The number of milliseconds that time-measuring tests can vary. */ - const testTolerance = 100; + const testTolerance = 100 /** * The number of times 429 is returned. */ - const retryResponseQty = 2; + const retryResponseQty = 2 - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ ctx, queryResponse, - }); + }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() - let responseTries = 0; + let responseTries = 0 // Override the query endpoint to return a 429 while `responseTries` is // less than or equal to `retryResponseQty` ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - responseTries++; + responseTries++ if (responseTries <= retryResponseQty) { return res( @@ -836,59 +826,59 @@ it("retries after `retry-after` milliseconds if response code is 429", async (ct "Your request count (11) is over the allowed limit of 10.", }), ctx.set("retry-after", retryAfter.toString()), - ); + ) } }), - ); + ) // Rate limited. Should resolve roughly after retryAfter * retryResponseQty milliseconds. - const t0_0 = performance.now(); - const res0 = await client.get(); - const t0_1 = performance.now(); + const t0_0 = performance.now() + const res0 = await client.get() + const t0_1 = performance.now() - expect(res0).toStrictEqual(queryResponse); - expect(t0_1 - t0_0).toBeGreaterThanOrEqual(retryAfter * retryResponseQty); + expect(res0).toStrictEqual(queryResponse) + expect(t0_1 - t0_0).toBeGreaterThanOrEqual(retryAfter * retryResponseQty) expect(t0_1 - t0_0).toBeLessThanOrEqual( retryAfter * retryResponseQty + testTolerance, - ); + ) // Not rate limited. Should resolve nearly immediately. - const t1_0 = performance.now(); - const res1 = await client.get(); - const t1_1 = performance.now(); + const t1_0 = performance.now() + const res1 = await client.get() + const t1_1 = performance.now() - expect(res1).toStrictEqual(queryResponse); - expect(t1_1 - t1_0).toBeGreaterThanOrEqual(0); - expect(t1_1 - t1_0).toBeLessThanOrEqual(testTolerance); -}); + expect(res1).toStrictEqual(queryResponse) + expect(t1_1 - t1_0).toBeGreaterThanOrEqual(0) + expect(t1_1 - t1_0).toBeLessThanOrEqual(testTolerance) +}) it("retries after 1000 milliseconds if response code is 429 and an invalid `retry-after` value is returned", async (ctx) => { /** * The number of milliseconds that time-measuring tests can vary. */ - const testTolerance = 100; + const testTolerance = 100 - const queryResponse = prismicM.api.query({ seed: ctx.task.name }); + const queryResponse = prismicM.api.query({ seed: ctx.task.name }) mockPrismicRestAPIV2({ ctx, queryResponse, - }); + }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() - let responseTries = 0; + let responseTries = 0 // Override the query endpoint to return a 429 while `responseTries` is // less than or equal to `retryResponseQty` ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - responseTries++; + responseTries++ if (responseTries <= 1) { return res( @@ -899,43 +889,43 @@ it("retries after 1000 milliseconds if response code is 429 and an invalid `retr "Your request count (11) is over the allowed limit of 10.", }), ctx.set("retry-after", "invalid"), - ); + ) } }), - ); + ) // Rate limited. Should resolve roughly after 1000 milliseconds. - const t0 = performance.now(); - const res = await client.get(); - const t1 = performance.now(); + const t0 = performance.now() + const res = await client.get() + const t1 = performance.now() - expect(res).toStrictEqual(queryResponse); - expect(t1 - t0).toBeGreaterThanOrEqual(1000); - expect(t1 - t0).toBeLessThanOrEqual(1000 + testTolerance); -}); + expect(res).toStrictEqual(queryResponse) + expect(t1 - t0).toBeGreaterThanOrEqual(1000) + expect(t1 - t0).toBeLessThanOrEqual(1000 + testTolerance) +}) it("throws if a non-2xx response is returned even after retrying", async (ctx) => { /** * The number of milliseconds that time-measuring tests can vary. */ - const testTolerance = 100; + const testTolerance = 100 - mockPrismicRestAPIV2({ ctx }); + mockPrismicRestAPIV2({ ctx }) - const client = createTestClient(); + const client = createTestClient() const queryEndpoint = new URL( "documents/search", `${client.endpoint}/`, - ).toString(); + ).toString() - let responseTries = 0; + let responseTries = 0 // Override the query endpoint to return a 429 while `responseTries` is // less than or equal to `retryResponseQty` ctx.server.use( msw.rest.get(queryEndpoint, (_req, res, ctx) => { - responseTries++; + responseTries++ if (responseTries <= 1) { return res( @@ -946,20 +936,18 @@ it("throws if a non-2xx response is returned even after retrying", async (ctx) = "Your request count (11) is over the allowed limit of 10.", }), ctx.set("retry-after", "invalid"), - ); + ) } else { - return res(ctx.status(418)); + return res(ctx.status(418)) } }), - ); + ) // Rate limited. Should reject roughly after 1000 milliseconds. - const t0 = performance.now(); - await expect(() => client.get()).rejects.toThrowError( - /invalid api response/i, - ); - const t1 = performance.now(); + const t0 = performance.now() + await expect(() => client.get()).rejects.toThrowError(/invalid api response/i) + const t1 = performance.now() - expect(t1 - t0).toBeGreaterThanOrEqual(1000); - expect(t1 - t0).toBeLessThanOrEqual(1000 + testTolerance); -}); + expect(t1 - t0).toBeGreaterThanOrEqual(1000) + expect(t1 - t0).toBeLessThanOrEqual(1000 + testTolerance) +}) diff --git a/test/errors-ForbiddenError.test.ts b/test/errors-ForbiddenError.test.ts index 7a338a2c..c1babc4a 100644 --- a/test/errors-ForbiddenError.test.ts +++ b/test/errors-ForbiddenError.test.ts @@ -1,18 +1,18 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("contains the request url and error properties", () => { - const message = "message"; - const url = "url"; + const message = "message" + const url = "url" const response = { error: "error", oauth_initiate: "oauth_initiate", oauth_token: "oauth_token", - } as const; - const error = new prismic.ForbiddenError(message, url, response); + } as const + const error = new prismic.ForbiddenError(message, url, response) - expect(error.message).toBe(message); - expect(error.url).toBe(url); - expect(error.response).toStrictEqual(response); -}); + expect(error.message).toBe(message) + expect(error.url).toBe(url) + expect(error.response).toStrictEqual(response) +}) diff --git a/test/errors-ParsingError.test.ts b/test/errors-ParsingError.test.ts index ea9fba1a..02241c50 100644 --- a/test/errors-ParsingError.test.ts +++ b/test/errors-ParsingError.test.ts @@ -1,10 +1,10 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("contains the request url and error properties", () => { - const message = "message"; - const url = "url"; + const message = "message" + const url = "url" const response = { type: "parsing-error", message: "message", @@ -12,10 +12,10 @@ it("contains the request url and error properties", () => { line: 0, column: 0, id: 0, - } as const; - const error = new prismic.ParsingError(message, url, response); + } as const + const error = new prismic.ParsingError(message, url, response) - expect(error.message).toBe(message); - expect(error.url).toBe(url); - expect(error.response).toStrictEqual(response); -}); + expect(error.message).toBe(message) + expect(error.url).toBe(url) + expect(error.response).toStrictEqual(response) +}) diff --git a/test/errors-PrismicError.test.ts b/test/errors-PrismicError.test.ts index e8650c2f..66b69d78 100644 --- a/test/errors-PrismicError.test.ts +++ b/test/errors-PrismicError.test.ts @@ -1,24 +1,20 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("contains the request url and optional response", () => { - const message = "message"; - const url = "url"; - const response = { foo: "bar" } as const; + const message = "message" + const url = "url" + const response = { foo: "bar" } as const - const errorWithResponse = new prismic.PrismicError(message, url, response); - const errorWithoutResponse = new prismic.PrismicError( - message, - url, - undefined, - ); + const errorWithResponse = new prismic.PrismicError(message, url, response) + const errorWithoutResponse = new prismic.PrismicError(message, url, undefined) - expect(errorWithResponse.message).toBe(message); - expect(errorWithResponse.url).toBe(url); - expect(errorWithResponse.response).toStrictEqual(response); + expect(errorWithResponse.message).toBe(message) + expect(errorWithResponse.url).toBe(url) + expect(errorWithResponse.response).toStrictEqual(response) - expect(errorWithoutResponse.message).toBe(message); - expect(errorWithoutResponse.url).toBe(url); - expect(errorWithoutResponse.response).toBeUndefined(); -}); + expect(errorWithoutResponse.message).toBe(message) + expect(errorWithoutResponse.url).toBe(url) + expect(errorWithoutResponse.response).toBeUndefined() +}) diff --git a/test/filter-any.test.ts b/test/filter-any.test.ts index 5060b7f5..81be90f0 100644 --- a/test/filter-any.test.ts +++ b/test/filter-any.test.ts @@ -1,16 +1,16 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[any(document.type, ["product", "blog-post"])]', prismic.filter.any("document.type", ["product", "blog-post"]), -); +) testFilter( "[any(my.product.out_of_stock, [true, false])]", prismic.filter.any("my.product.out_of_stock", [true, false]), -); +) testFilter( "[any(my.product.restock_date, [1600000000000, 1700000000000])]", @@ -18,4 +18,4 @@ testFilter( new Date(1600000000000), new Date(1700000000000), ]), -); +) diff --git a/test/filter-at.test.ts b/test/filter-at.test.ts index 10928b10..74e23ecc 100644 --- a/test/filter-at.test.ts +++ b/test/filter-at.test.ts @@ -1,28 +1,28 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[at(document.type, "product")]', prismic.filter.at("document.type", "product"), -); +) testFilter( '[at(document.tags, ["Macaron", "Cupcake"])]', prismic.filter.at("document.tags", ["Macaron", "Cupcake"]), -); +) testFilter( "[at(my.product.price, 50)]", prismic.filter.at("my.product.price", 50), -); +) testFilter( "[at(my.product.out_of_stock, true)]", prismic.filter.at("my.product.out_of_stock", true), -); +) testFilter( "[at(my.product.restock_date, 1600000000000)]", prismic.filter.at("my.product.restock_date", new Date(1600000000000)), -); +) diff --git a/test/filter-date.test.ts b/test/filter-date.test.ts index 153cfaf8..6f6f8c42 100644 --- a/test/filter-date.test.ts +++ b/test/filter-date.test.ts @@ -1,6 +1,6 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[date.after(document.first_publication_date, "2017-05-18T17:00:00-0500")]', @@ -8,22 +8,22 @@ testFilter( "document.first_publication_date", "2017-05-18T17:00:00-0500", ), -); +) testFilter( "[date.after(document.last_publication_date, 1495080000000)]", prismic.filter.dateAfter("document.last_publication_date", 1495080000000), -); +) testFilter( '[date.after(my.article.release-date, "2017-01-22")]', prismic.filter.dateAfter("my.article.release-date", "2017-01-22"), -); +) testFilter( "[date.after(my.article.release-date, 1485043200000)]", prismic.filter.dateAfter("my.article.release-date", Date.parse("2017-01-22")), -); +) testFilter( '[date.before(document.first_publication_date, "2016-09-19T14:00:00-0400")]', @@ -31,22 +31,22 @@ testFilter( "document.first_publication_date", "2016-09-19T14:00:00-0400", ), -); +) testFilter( "[date.before(document.last_publication_date, 1476504000000)]", prismic.filter.dateBefore("document.last_publication_date", 1476504000000), -); +) testFilter( '[date.before(my.post.date, "2017-02-24")]', prismic.filter.dateBefore("my.post.date", "2017-02-24"), -); +) testFilter( "[date.before(my.post.date, 1487894400000)]", prismic.filter.dateBefore("my.post.date", Date.parse("2017-02-24")), -); +) testFilter( '[date.between(document.first_publication_date, "2017-01-16", "2017-01-20")]', @@ -55,7 +55,7 @@ testFilter( "2017-01-16", "2017-01-20", ), -); +) testFilter( '[date.between(document.last_publication_date, "2016-09-15T05:30:00+0100", "2017-10-15T11:45:00+0100")]', @@ -64,7 +64,7 @@ testFilter( "2016-09-15T05:30:00+0100", "2017-10-15T11:45:00+0100", ), -); +) testFilter( "[date.between(my.query-fields.date, 1483074000000, 1483333200000)]", @@ -73,7 +73,7 @@ testFilter( 1483074000000, 1483333200000, ), -); +) testFilter( "[date.between(my.query-fields.date, 1583074000000, 1583333200000)]", @@ -82,97 +82,97 @@ testFilter( new Date(1583074000000), new Date(1583333200000), ), -); +) testFilter( "[date.day-of-month(document.first_publication_date, 22)]", prismic.filter.dateDayOfMonth("document.first_publication_date", 22), -); +) testFilter( "[date.day-of-month(document.last_publication_date, 30)]", prismic.filter.dateDayOfMonth("document.last_publication_date", 30), -); +) testFilter( "[date.day-of-month(my.post.date, 14)]", prismic.filter.dateDayOfMonth("my.post.date", 14), -); +) testFilter( "[date.day-of-month-after(document.first_publication_date, 22)]", prismic.filter.dateDayOfMonthAfter("document.first_publication_date", 22), -); +) testFilter( "[date.day-of-month-after(document.last_publication_date, 10)]", prismic.filter.dateDayOfMonthAfter("document.last_publication_date", 10), -); +) testFilter( "[date.day-of-month-after(my.event.date-and-time, 15)]", prismic.filter.dateDayOfMonthAfter("my.event.date-and-time", 15), -); +) testFilter( "[date.day-of-month-before(document.first_publication_date, 20)]", prismic.filter.dateDayOfMonthBefore("document.first_publication_date", 20), -); +) testFilter( "[date.day-of-month-before(document.last_publication_date, 10)]", prismic.filter.dateDayOfMonthBefore("document.last_publication_date", 10), -); +) testFilter( "[date.day-of-month-before(my.blog-post.release-date, 23)]", prismic.filter.dateDayOfMonthBefore("my.blog-post.release-date", 23), -); +) testFilter( '[date.day-of-week(document.first_publication_date, "monday")]', prismic.filter.dateDayOfWeek("document.first_publication_date", "monday"), -); +) testFilter( '[date.day-of-week(document.last_publication_date, "sun")]', prismic.filter.dateDayOfWeek("document.last_publication_date", "sun"), -); +) testFilter( '[date.day-of-week(my.concert.show-date, "Friday")]', prismic.filter.dateDayOfWeek("my.concert.show-date", "Friday"), -); +) testFilter( "[date.day-of-week(my.concert.show-date, 5)]", prismic.filter.dateDayOfWeek("my.concert.show-date", 5), -); +) testFilter( '[date.day-of-week-after(document.first_publication_date, "fri")]', prismic.filter.dateDayOfWeekAfter("document.first_publication_date", "fri"), -); +) testFilter( '[date.day-of-week-after(document.last_publication_date, "Thu")]', prismic.filter.dateDayOfWeekAfter("document.last_publication_date", "Thu"), -); +) testFilter( '[date.day-of-week-after(my.blog-post.date, "tuesday")]', prismic.filter.dateDayOfWeekAfter("my.blog-post.date", "tuesday"), -); +) testFilter( "[date.day-of-week-after(my.blog-post.date, 2)]", prismic.filter.dateDayOfWeekAfter("my.blog-post.date", 2), -); +) testFilter( '[date.day-of-week-before(document.first_publication_date, "Wed")]', prismic.filter.dateDayOfWeekBefore("document.first_publication_date", "Wed"), -); +) testFilter( '[date.day-of-week-before(document.last_publication_date, "saturday")]', @@ -180,119 +180,119 @@ testFilter( "document.last_publication_date", "saturday", ), -); +) testFilter( '[date.day-of-week-before(my.page.release-date, "Saturday")]', prismic.filter.dateDayOfWeekBefore("my.page.release-date", "Saturday"), -); +) testFilter( "[date.day-of-week-before(my.page.release-date, 6)]", prismic.filter.dateDayOfWeekBefore("my.page.release-date", 6), -); +) testFilter( '[date.month(document.first_publication_date, "august")]', prismic.filter.dateMonth("document.first_publication_date", "august"), -); +) testFilter( '[date.month(document.last_publication_date, "Sep")]', prismic.filter.dateMonth("document.last_publication_date", "Sep"), -); +) testFilter( "[date.month(my.blog-post.date, 1)]", prismic.filter.dateMonth("my.blog-post.date", 1), -); +) testFilter( '[date.month-after(document.first_publication_date, "February")]', prismic.filter.dateMonthAfter("document.first_publication_date", "February"), -); +) testFilter( "[date.month-after(document.last_publication_date, 6)]", prismic.filter.dateMonthAfter("document.last_publication_date", 6), -); +) testFilter( '[date.month-after(my.article.date, "oct")]', prismic.filter.dateMonthAfter("my.article.date", "oct"), -); +) testFilter( "[date.month-before(document.first_publication_date, 8)]", prismic.filter.dateMonthBefore("document.first_publication_date", 8), -); +) testFilter( '[date.month-before(document.last_publication_date, "june")]', prismic.filter.dateMonthBefore("document.last_publication_date", "june"), -); +) testFilter( '[date.month-before(my.blog-post.release-date, "Sep")]', prismic.filter.dateMonthBefore("my.blog-post.release-date", "Sep"), -); +) testFilter( "[date.year(document.first_publication_date, 2016)]", prismic.filter.dateYear("document.first_publication_date", 2016), -); +) testFilter( "[date.year(document.last_publication_date, 2017)]", prismic.filter.dateYear("document.last_publication_date", 2017), -); +) testFilter( "[date.year(my.employee.birthday, 1986)]", prismic.filter.dateYear("my.employee.birthday", 1986), -); +) testFilter( "[date.hour(document.first_publication_date, 12)]", prismic.filter.dateHour("document.first_publication_date", 12), -); +) testFilter( "[date.hour(document.last_publication_date, 8)]", prismic.filter.dateHour("document.last_publication_date", 8), -); +) testFilter( "[date.hour(my.event.date-and-time, 19)]", prismic.filter.dateHour("my.event.date-and-time", 19), -); +) testFilter( "[date.hour-after(document.first_publication_date, 21)]", prismic.filter.dateHourAfter("document.first_publication_date", 21), -); +) testFilter( "[date.hour-after(document.last_publication_date, 8)]", prismic.filter.dateHourAfter("document.last_publication_date", 8), -); +) testFilter( "[date.hour-after(my.blog-post.releaseDate, 16)]", prismic.filter.dateHourAfter("my.blog-post.releaseDate", 16), -); +) testFilter( "[date.hour-before(document.first_publication_date, 10)]", prismic.filter.dateHourBefore("document.first_publication_date", 10), -); +) testFilter( "[date.hour-before(document.last_publication_date, 12)]", prismic.filter.dateHourBefore("document.last_publication_date", 12), -); +) testFilter( "[date.hour-before(my.event.dateAndTime, 12)]", prismic.filter.dateHourBefore("my.event.dateAndTime", 12), -); +) diff --git a/test/filter-fulltext.test.ts b/test/filter-fulltext.test.ts index 84f19dd2..02b6cdfb 100644 --- a/test/filter-fulltext.test.ts +++ b/test/filter-fulltext.test.ts @@ -1,18 +1,18 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[fulltext(document, "banana")]', prismic.filter.fulltext("document", "banana"), -); +) testFilter( '[fulltext(document, "banana apple")]', prismic.filter.fulltext("document", "banana apple"), -); +) testFilter( '[fulltext(my.product.title, "phone")]', prismic.filter.fulltext("my.product.title", "phone"), -); +) diff --git a/test/filter-geopoint.test.ts b/test/filter-geopoint.test.ts index 05e7506d..d579c51c 100644 --- a/test/filter-geopoint.test.ts +++ b/test/filter-geopoint.test.ts @@ -1,6 +1,6 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( "[geopoint.near(my.restaurant.location, 9.656896299, -9.77508544, 10)]", @@ -10,4 +10,4 @@ testFilter( -9.77508544, 10, ), -); +) diff --git a/test/filter-has.test.ts b/test/filter-has.test.ts index 8a38f37b..4246299a 100644 --- a/test/filter-has.test.ts +++ b/test/filter-has.test.ts @@ -1,5 +1,5 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" -testFilter("[has(my.product.price)]", prismic.filter.has("my.product.price")); +testFilter("[has(my.product.price)]", prismic.filter.has("my.product.price")) diff --git a/test/filter-in.test.ts b/test/filter-in.test.ts index dcf2b5c1..d845fce6 100644 --- a/test/filter-in.test.ts +++ b/test/filter-in.test.ts @@ -1,13 +1,13 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[in(document.id, ["V9rIvCQAAB0ACq6y", "V9ZtvCcAALuRUzmO"])]', prismic.filter.in("document.id", ["V9rIvCQAAB0ACq6y", "V9ZtvCcAALuRUzmO"]), -); +) testFilter( '[in(my.page.uid, ["myuid1", "myuid2"])]', prismic.filter.in("my.page.uid", ["myuid1", "myuid2"]), -); +) diff --git a/test/filter-missing.test.ts b/test/filter-missing.test.ts index 090461ac..eff55b21 100644 --- a/test/filter-missing.test.ts +++ b/test/filter-missing.test.ts @@ -1,8 +1,8 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( "[missing(my.product.price)]", prismic.filter.missing("my.product.price"), -); +) diff --git a/test/filter-not.test.ts b/test/filter-not.test.ts index 59ff7577..f5aa084e 100644 --- a/test/filter-not.test.ts +++ b/test/filter-not.test.ts @@ -1,28 +1,28 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[not(document.type, "product")]', prismic.filter.not("document.type", "product"), -); +) testFilter( '[not(document.tags, ["Macaron", "Cupcake"])]', prismic.filter.not("document.tags", ["Macaron", "Cupcake"]), -); +) testFilter( "[not(my.product.price, 50)]", prismic.filter.not("my.product.price", 50), -); +) testFilter( "[not(my.product.out_of_stock, true)]", prismic.filter.not("my.product.out_of_stock", true), -); +) testFilter( "[not(my.product.restock_date, 1600000000000)]", prismic.filter.not("my.product.restock_date", new Date(1600000000000)), -); +) diff --git a/test/filter-number.test.ts b/test/filter-number.test.ts index 81bf749f..c48fbfb6 100644 --- a/test/filter-number.test.ts +++ b/test/filter-number.test.ts @@ -1,33 +1,33 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( "[number.lt(my.instructions.numberOfSteps, 10)]", prismic.filter.numberLessThan("my.instructions.numberOfSteps", 10), -); +) testFilter( "[number.lt(my.product.price, 49.99)]", prismic.filter.numberLessThan("my.product.price", 49.99), -); +) testFilter( "[number.gt(my.rental.numberOfBedrooms, 2)]", prismic.filter.numberGreaterThan("my.rental.numberOfBedrooms", 2), -); +) testFilter( "[number.gt(my.product.price, 9.99)]", prismic.filter.numberGreaterThan("my.product.price", 9.99), -); +) testFilter( "[number.inRange(my.album.track-count, 7, 10)]", prismic.filter.numberInRange("my.album.track-count", 7, 10), -); +) testFilter( "[number.inRange(my.product.price, 9.99, 49.99)]", prismic.filter.numberInRange("my.product.price", 9.99, 49.99), -); +) diff --git a/test/filter-similar.test.ts b/test/filter-similar.test.ts index be34e505..9716de08 100644 --- a/test/filter-similar.test.ts +++ b/test/filter-similar.test.ts @@ -1,8 +1,8 @@ -import { testFilter } from "./__testutils__/testFilter"; +import { testFilter } from "./__testutils__/testFilter" -import * as prismic from "../src"; +import * as prismic from "../src" testFilter( '[similar("VkRmhykAAFA6PoBj", 10)]', prismic.filter.similar("VkRmhykAAFA6PoBj", 10), -); +) diff --git a/test/getGraphQLEndpoint.test.ts b/test/getGraphQLEndpoint.test.ts index b5993d84..65570228 100644 --- a/test/getGraphQLEndpoint.test.ts +++ b/test/getGraphQLEndpoint.test.ts @@ -1,20 +1,20 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns default GraphQL API CDN URL", () => { - const endpoint = prismic.getGraphQLEndpoint("qwerty"); + const endpoint = prismic.getGraphQLEndpoint("qwerty") - expect(endpoint).toBe("https://qwerty.cdn.prismic.io/graphql"); -}); + expect(endpoint).toBe("https://qwerty.cdn.prismic.io/graphql") +}) it("throws if an invalid repository name is given", () => { expect(() => { - prismic.getGraphQLEndpoint("this is invalid"); + prismic.getGraphQLEndpoint("this is invalid") }).toThrowError( /an invalid Prismic repository name was given: this is invalid/i, - ); + ) expect(() => { - prismic.getGraphQLEndpoint("this is invalid"); - }).toThrowError(prismic.PrismicError); -}); + prismic.getGraphQLEndpoint("this is invalid") + }).toThrowError(prismic.PrismicError) +}) diff --git a/test/getRepositoryEndpoint.test.ts b/test/getRepositoryEndpoint.test.ts index 1fcb128d..45f43325 100644 --- a/test/getRepositoryEndpoint.test.ts +++ b/test/getRepositoryEndpoint.test.ts @@ -1,20 +1,20 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns default Rest API V2 CDN URL", () => { - const endpoint = prismic.getRepositoryEndpoint("qwerty"); + const endpoint = prismic.getRepositoryEndpoint("qwerty") - expect(endpoint).toBe("https://qwerty.cdn.prismic.io/api/v2"); -}); + expect(endpoint).toBe("https://qwerty.cdn.prismic.io/api/v2") +}) it("throws if an invalid repository name is given", () => { expect(() => { - prismic.getRepositoryEndpoint("this is invalid"); + prismic.getRepositoryEndpoint("this is invalid") }).toThrowError( /An invalid Prismic repository name was given: this is invalid/i, - ); + ) expect(() => { - prismic.getRepositoryEndpoint("this is invalid"); - }).toThrowError(prismic.PrismicError); -}); + prismic.getRepositoryEndpoint("this is invalid") + }).toThrowError(prismic.PrismicError) +}) diff --git a/test/getRepositoryName.test.ts b/test/getRepositoryName.test.ts index 75daee46..8f97db0a 100644 --- a/test/getRepositoryName.test.ts +++ b/test/getRepositoryName.test.ts @@ -1,22 +1,22 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns the repository name from a valid Prismic Rest API V2 endpoint", () => { const repositoryName = prismic.getRepositoryName( "https://qwerty.cdn.prismic.io/api/v2", - ); + ) - expect(repositoryName).toBe("qwerty"); -}); + expect(repositoryName).toBe("qwerty") +}) it("throws if the input is not a valid URL", () => { expect(() => { - prismic.getRepositoryName("qwerty"); + prismic.getRepositoryName("qwerty") }).toThrowError( /An invalid Prismic Rest API V2 endpoint was provided: qwerty/i, - ); + ) expect(() => { - prismic.getRepositoryName("qwerty"); - }).toThrowError(prismic.PrismicError); -}); + prismic.getRepositoryName("qwerty") + }).toThrowError(prismic.PrismicError) +}) diff --git a/test/getToolbarSrc.test.ts b/test/getToolbarSrc.test.ts index 2ffce071..31d8aa11 100644 --- a/test/getToolbarSrc.test.ts +++ b/test/getToolbarSrc.test.ts @@ -1,22 +1,22 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns a URL for the Prismic Toolbar script", () => { - const endpoint = prismic.getToolbarSrc("qwerty"); + const endpoint = prismic.getToolbarSrc("qwerty") expect(endpoint).toBe( "https://static.cdn.prismic.io/prismic.js?new=true&repo=qwerty", - ); -}); + ) +}) it("throws if an invalid repository name is given", () => { expect(() => { - prismic.getToolbarSrc("this is invalid"); + prismic.getToolbarSrc("this is invalid") }).toThrowError( /An invalid Prismic repository name was given: this is invalid/i, - ); + ) expect(() => { - prismic.getToolbarSrc("this is invalid"); - }).toThrowError(prismic.PrismicError); -}); + prismic.getToolbarSrc("this is invalid") + }).toThrowError(prismic.PrismicError) +}) diff --git a/test/helpers-asDate.test.ts b/test/helpers-asDate.test.ts index 8aa0993d..7089bef3 100644 --- a/test/helpers-asDate.test.ts +++ b/test/helpers-asDate.test.ts @@ -1,37 +1,37 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { documentFixture } from "./__fixtures__/document"; +import { documentFixture } from "./__fixtures__/document" -import { asDate } from "../src"; +import { asDate } from "../src" it("returns null for nullish inputs", () => { - expect(asDate(null)).toBeNull(); - expect(asDate(undefined)).toBeNull(); -}); + expect(asDate(null)).toBeNull() + expect(asDate(undefined)).toBeNull() +}) it("returns null when date field is empty", () => { - const field = null; + const field = null - expect(asDate(field)).toBeNull(); -}); + expect(asDate(field)).toBeNull() +}) it("returns a date object from a date field", () => { - const field = "2021-05-12"; + const field = "2021-05-12" - expect(asDate(field)).toBeInstanceOf(Date); -}); + expect(asDate(field)).toBeInstanceOf(Date) +}) it("returns null when timestamp field is empty", () => { - const field = null; + const field = null - expect(asDate(field)).toBeNull(); -}); + expect(asDate(field)).toBeNull() +}) it("returns a date object from a timestamp field", () => { - const field = "2021-05-11T22:00:00+0000"; + const field = "2021-05-11T22:00:00+0000" - expect(asDate(field)).toBeInstanceOf(Date); -}); + expect(asDate(field)).toBeInstanceOf(Date) +}) it("is compatible with a document's first_publication_date and last_publication_date properties", () => { // This test is functionally no different than the tests above, but we @@ -40,8 +40,8 @@ it("is compatible with a document's first_publication_date and last_publication_ expect(asDate(documentFixture.empty.first_publication_date)).toBeInstanceOf( Date, - ); + ) expect(asDate(documentFixture.empty.last_publication_date)).toBeInstanceOf( Date, - ); -}); + ) +}) diff --git a/test/helpers-asHTML.test.ts b/test/helpers-asHTML.test.ts index 4a0669bd..bbb84344 100644 --- a/test/helpers-asHTML.test.ts +++ b/test/helpers-asHTML.test.ts @@ -1,33 +1,34 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "./__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "./__testutils__/createRichTextFixtures" -import { linkResolver } from "./__fixtures__/linkResolver"; -import { partialHTMLRichTextFunctionSerializer } from "./__fixtures__/partialHTMLRichTextFunctionSerializer"; -import { partialHTMLRichTextMapSerializer } from "./__fixtures__/partialHTMLRichTextMapSerializer"; +import { linkResolver } from "./__fixtures__/linkResolver" +import { partialHTMLRichTextFunctionSerializer } from "./__fixtures__/partialHTMLRichTextFunctionSerializer" +import { partialHTMLRichTextMapSerializer } from "./__fixtures__/partialHTMLRichTextMapSerializer" -import { RichTextField, asHTML } from "../src"; +import type { RichTextField } from "../src" +import { asHTML } from "../src" it("serializes with default serializer", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - expect(asHTML(richTextFixtures.en, { linkResolver })).toMatchSnapshot(); + expect(asHTML(richTextFixtures.en, { linkResolver })).toMatchSnapshot() // TODO: Remove when we remove support for deprecated tuple-style configuration. expect(asHTML(richTextFixtures.en, linkResolver)).toBe( asHTML(richTextFixtures.en, { linkResolver }), - ); -}); + ) +}) it("serializes with a custom function serializer", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() expect( asHTML(richTextFixtures.en, { linkResolver, serializer: partialHTMLRichTextFunctionSerializer, }), - ).toMatchSnapshot(); + ).toMatchSnapshot() // TODO: Remove when we remove support for deprecated tuple-style configuration. expect( @@ -41,18 +42,18 @@ it("serializes with a custom function serializer", () => { linkResolver, serializer: partialHTMLRichTextFunctionSerializer, }), - ); -}); + ) +}) it("serializes with a custom map serializer", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() expect( asHTML(richTextFixtures.en, { linkResolver, serializer: partialHTMLRichTextMapSerializer, }), - ).toMatchSnapshot(); + ).toMatchSnapshot() // TODO: Remove when we remove support for deprecated tuple-style configuration. expect( @@ -62,11 +63,11 @@ it("serializes with a custom map serializer", () => { linkResolver, serializer: partialHTMLRichTextMapSerializer, }), - ); -}); + ) +}) it("serializes with a custom shorthand map serializer", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() expect( asHTML(richTextFixtures.en, { @@ -79,14 +80,14 @@ it("serializes with a custom shorthand map serializer", () => { label: { class: "shorthand" }, }, }), - ).toMatchSnapshot(); -}); + ).toMatchSnapshot() +}) it("escapes external links to prevent XSS", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - expect(asHTML(richTextFixtures.xss, { linkResolver })).toMatchSnapshot(); -}); + expect(asHTML(richTextFixtures.xss, { linkResolver })).toMatchSnapshot() +}) it("omits target attribute on links without a target value", () => { const field: RichTextField = [ @@ -105,12 +106,12 @@ it("omits target attribute on links without a target value", () => { }, ], }, - ]; + ] expect(asHTML(field, { linkResolver })).toMatchInlineSnapshot( `"

    link

    "`, - ); -}); + ) +}) it("includes target attribute on links with a target value", () => { const field: RichTextField = [ @@ -130,14 +131,14 @@ it("includes target attribute on links with a target value", () => { }, ], }, - ]; + ] expect(asHTML(field, { linkResolver })).toMatchInlineSnapshot( `"

    link

    "`, - ); -}); + ) +}) it("returns null for nullish inputs", () => { - expect(asHTML(null)).toBeNull(); - expect(asHTML(undefined)).toBeNull(); -}); + expect(asHTML(null)).toBeNull() + expect(asHTML(undefined)).toBeNull() +}) diff --git a/test/helpers-asImagePixelDensitySrcSet.test.ts b/test/helpers-asImagePixelDensitySrcSet.test.ts index 6bd37493..d7894c06 100644 --- a/test/helpers-asImagePixelDensitySrcSet.test.ts +++ b/test/helpers-asImagePixelDensitySrcSet.test.ts @@ -1,11 +1,12 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { ImageField, asImagePixelDensitySrcSet } from "../src"; +import type { ImageField } from "../src" +import { asImagePixelDensitySrcSet } from "../src" it("returns null for nullish inputs", () => { - expect(asImagePixelDensitySrcSet(null)).toBeNull(); - expect(asImagePixelDensitySrcSet(undefined)).toBeNull(); -}); + expect(asImagePixelDensitySrcSet(null)).toBeNull() + expect(asImagePixelDensitySrcSet(undefined)).toBeNull() +}) it("returns an image field pixel-density-based srcset with [1, 2, 3] pxiel densities by default", () => { const field: ImageField = { @@ -20,7 +21,7 @@ it("returns an image field pixel-density-based srcset with [1, 2, 3] pxiel densi alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } expect(asImagePixelDensitySrcSet(field)).toStrictEqual({ src: field.url, @@ -28,8 +29,8 @@ it("returns an image field pixel-density-based srcset with [1, 2, 3] pxiel densi `${field.url}&dpr=1 1x, ` + `${field.url}&dpr=2 2x, ` + `${field.url}&dpr=3 3x`, - }); -}); + }) +}) it("supports custom pixel densities", () => { const field: ImageField = { @@ -44,7 +45,7 @@ it("supports custom pixel densities", () => { alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } expect( asImagePixelDensitySrcSet(field, { @@ -56,8 +57,8 @@ it("supports custom pixel densities", () => { `${field.url}&dpr=2 2x, ` + `${field.url}&dpr=4 4x, ` + `${field.url}&dpr=6 6x`, - }); -}); + }) +}) it("applies given Imgix URL parameters", () => { const field: ImageField = { @@ -72,7 +73,7 @@ it("applies given Imgix URL parameters", () => { alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } expect( asImagePixelDensitySrcSet(field, { @@ -84,11 +85,11 @@ it("applies given Imgix URL parameters", () => { `${field.url}&sat=100&dpr=1 1x, ` + `${field.url}&sat=100&dpr=2 2x, ` + `${field.url}&sat=100&dpr=3 3x`, - }); -}); + }) +}) it("returns null when image field is empty", () => { - const field: ImageField = {}; + const field: ImageField = {} - expect(asImagePixelDensitySrcSet(field)).toBeNull(); -}); + expect(asImagePixelDensitySrcSet(field)).toBeNull() +}) diff --git a/test/helpers-asImageSrc.test.ts b/test/helpers-asImageSrc.test.ts index 8df8a4e6..2176dde8 100644 --- a/test/helpers-asImageSrc.test.ts +++ b/test/helpers-asImageSrc.test.ts @@ -1,11 +1,12 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { ImageField, asImageSrc } from "../src"; +import type { ImageField } from "../src" +import { asImageSrc } from "../src" it("returns null for nullish inputs", () => { - expect(asImageSrc(null)).toBeNull(); - expect(asImageSrc(undefined)).toBeNull(); -}); + expect(asImageSrc(null)).toBeNull() + expect(asImageSrc(undefined)).toBeNull() +}) it("returns an image field URL", () => { const field: ImageField = { @@ -20,10 +21,10 @@ it("returns an image field URL", () => { alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } - expect(asImageSrc(field)).toBe(field.url); -}); + expect(asImageSrc(field)).toBe(field.url) +}) it("applies given Imgix URL parameters", () => { const field: ImageField = { @@ -38,15 +39,15 @@ it("applies given Imgix URL parameters", () => { alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } - expect(asImageSrc(field, { sat: 100 })).toBe(`${field.url}&sat=100`); - expect(asImageSrc(field, { w: 100 })).toBe(`${field.url}&w=100`); - expect(asImageSrc(field, { width: 100 })).toBe(`${field.url}&width=100`); -}); + expect(asImageSrc(field, { sat: 100 })).toBe(`${field.url}&sat=100`) + expect(asImageSrc(field, { w: 100 })).toBe(`${field.url}&w=100`) + expect(asImageSrc(field, { width: 100 })).toBe(`${field.url}&width=100`) +}) it("returns null when image field is empty", () => { - const field: ImageField = {}; + const field: ImageField = {} - expect(asImageSrc(field)).toBeNull(); -}); + expect(asImageSrc(field)).toBeNull() +}) diff --git a/test/helpers-asImageWidthSrcSet.test.ts b/test/helpers-asImageWidthSrcSet.test.ts index 6dac502a..4dbaa069 100644 --- a/test/helpers-asImageWidthSrcSet.test.ts +++ b/test/helpers-asImageWidthSrcSet.test.ts @@ -1,11 +1,12 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { ImageField, asImageWidthSrcSet } from "../src"; +import type { ImageField } from "../src" +import { asImageWidthSrcSet } from "../src" it("returns null for nullish inputs", () => { - expect(asImageWidthSrcSet(null)).toBeNull(); - expect(asImageWidthSrcSet(undefined)).toBeNull(); -}); + expect(asImageWidthSrcSet(null)).toBeNull() + expect(asImageWidthSrcSet(undefined)).toBeNull() +}) it("returns an image field src and width-based srcset with [640, 750, 828, 1080, 1200, 1920, 2048, 3840] widths by default", () => { const field: ImageField = { @@ -20,7 +21,7 @@ it("returns an image field src and width-based srcset with [640, 750, 828, 1080, alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } expect(asImageWidthSrcSet(field)).toStrictEqual({ src: field.url, @@ -30,8 +31,8 @@ it("returns an image field src and width-based srcset with [640, 750, 828, 1080, `${field.url}&width=1200 1200w, ` + `${field.url}&width=2048 2048w, ` + `${field.url}&width=3840 3840w`, - }); -}); + }) +}) it("supports custom widths", () => { const field: ImageField = { @@ -46,7 +47,7 @@ it("supports custom widths", () => { alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } expect( asImageWidthSrcSet(field, { @@ -58,8 +59,8 @@ it("supports custom widths", () => { `${field.url}&width=400 400w, ` + `${field.url}&width=800 800w, ` + `${field.url}&width=1600 1600w`, - }); -}); + }) +}) it("applies given Imgix URL parameters", () => { const field: ImageField = { @@ -74,7 +75,7 @@ it("applies given Imgix URL parameters", () => { alt: null, copyright: null, dimensions: { width: 400, height: 300 }, - }; + } expect( asImageWidthSrcSet(field, { @@ -88,8 +89,8 @@ it("applies given Imgix URL parameters", () => { `${field.url}&sat=100&width=1200 1200w, ` + `${field.url}&sat=100&width=2048 2048w, ` + `${field.url}&sat=100&width=3840 3840w`, - }); -}); + }) +}) it('if widths is "thumbnails", returns a srcset of responsive views if the field contains responsive views', () => { const field: ImageField<"foo" | "bar"> = { @@ -130,7 +131,7 @@ it('if widths is "thumbnails", returns a srcset of responsive views if the field copyright: null, dimensions: { width: 250, height: 200 }, }, - }; + } expect(asImageWidthSrcSet(field, { widths: "thumbnails" })).toStrictEqual({ src: field.url, @@ -138,8 +139,8 @@ it('if widths is "thumbnails", returns a srcset of responsive views if the field `${field.url}&width=1000 1000w, ` + `${field.foo.url}&width=500 500w, ` + `${field.bar.url}&width=250 250w`, - }); -}); + }) +}) it('if widths is "thumbnails", but the field does not contain responsive views, uses the default widths', () => { const field: ImageField = { @@ -154,7 +155,7 @@ it('if widths is "thumbnails", but the field does not contain responsive views, alt: null, copyright: null, dimensions: { width: 1000, height: 800 }, - }; + } expect(asImageWidthSrcSet(field, { widths: "thumbnails" })).toStrictEqual({ src: field.url, @@ -164,8 +165,8 @@ it('if widths is "thumbnails", but the field does not contain responsive views, `${field.url}&width=1200 1200w, ` + `${field.url}&width=2048 2048w, ` + `${field.url}&width=3840 3840w`, - }); -}); + }) +}) it('if widths is not "thumbnails", but the field contains responsive views, uses the default widths and ignores thumbnails', () => { const field: ImageField<"foo" | "bar"> = { @@ -206,7 +207,7 @@ it('if widths is not "thumbnails", but the field contains responsive views, uses copyright: null, dimensions: { width: 250, height: 200 }, }, - }; + } expect(asImageWidthSrcSet(field)).toStrictEqual({ src: field.url, @@ -216,11 +217,11 @@ it('if widths is not "thumbnails", but the field contains responsive views, uses `${field.url}&width=1200 1200w, ` + `${field.url}&width=2048 2048w, ` + `${field.url}&width=3840 3840w`, - }); -}); + }) +}) it("returns null when image field is empty", () => { - const field: ImageField = {}; + const field: ImageField = {} - expect(asImageWidthSrcSet(field)).toBeNull(); -}); + expect(asImageWidthSrcSet(field)).toBeNull() +}) diff --git a/test/helpers-asLink.test.ts b/test/helpers-asLink.test.ts index 23064a7a..80264fd7 100644 --- a/test/helpers-asLink.test.ts +++ b/test/helpers-asLink.test.ts @@ -1,38 +1,38 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { documentFixture } from "./__fixtures__/document"; -import { linkResolver } from "./__fixtures__/linkResolver"; +import { documentFixture } from "./__fixtures__/document" +import { linkResolver } from "./__fixtures__/linkResolver" -import { LinkType, asLink } from "../src"; +import { LinkType, asLink } from "../src" it("returns null for nullish inputs", () => { - expect(asLink(null, linkResolver)).toBeNull(); - expect(asLink(undefined, linkResolver)).toBeNull(); -}); + expect(asLink(null, linkResolver)).toBeNull() + expect(asLink(undefined, linkResolver)).toBeNull() +}) it("returns null when link to document field is empty", () => { const field = { link_type: LinkType.Document, - }; + } - expect(asLink(field, linkResolver)).toBeNull(); -}); + expect(asLink(field, linkResolver)).toBeNull() +}) it("returns null when link to media field is empty", () => { const field = { link_type: LinkType.Media, - }; + } - expect(asLink(field, linkResolver)).toBeNull(); -}); + expect(asLink(field, linkResolver)).toBeNull() +}) it("returns null when link field is empty", () => { const field = { link_type: LinkType.Any, - }; + } - expect(asLink(field, linkResolver)).toBeNull(); -}); + expect(asLink(field, linkResolver)).toBeNull() +}) it("resolves a link to document field without route resolver", () => { const field = { @@ -44,30 +44,30 @@ it("resolves a link to document field without route resolver", () => { uid: "test", link_type: LinkType.Document, isBroken: false, - }; + } expect( asLink(field), "returns null if both link resolver and route resolver are not used", - ).toBeNull(); + ).toBeNull() expect( asLink(field, { linkResolver }), "uses link resolver URL if link resolver returns a non-nullish value", - ).toBe("/test"); + ).toBe("/test") // TODO: Remove when we remove support for deprecated tuple-style configuration. expect( asLink(field, linkResolver), "uses link resolver URL if link resolver returns a non-nullish value (deprecated tuple configuration)", - ).toBe("/test"); + ).toBe("/test") expect( asLink(field, { linkResolver: () => undefined }), "returns null if link resolver returns undefined", - ).toBeNull(); + ).toBeNull() expect( asLink(field, { linkResolver: () => null }), "returns null if link resolver returns null", - ).toBeNull(); -}); + ).toBeNull() +}) it("resolves a link to document field with route resolver", () => { const field = { @@ -80,43 +80,43 @@ it("resolves a link to document field with route resolver", () => { url: "url", link_type: LinkType.Document, isBroken: false, - }; + } expect( asLink(field), "uses route resolver URL if link resolver is not given", - ).toBe(field.url); + ).toBe(field.url) expect( asLink(field, { linkResolver: () => "link-resolver-value" }), "uses link resolver URL if link resolver returns a non-nullish value", - ).toBe("link-resolver-value"); + ).toBe("link-resolver-value") expect( asLink(field, { linkResolver: () => undefined }), "uses route resolver URL if link resolver returns undefined", - ).toBe(field.url); + ).toBe(field.url) expect( asLink(field, { linkResolver: () => null }), "uses route resolver URL if link resolver returns null", - ).toBe(field.url); -}); + ).toBe(field.url) +}) it("returns null when given a document field and linkResolver is not provided ", () => { const field = { id: "XvoFFREAAM0WGBng", link_type: LinkType.Document, - }; + } - expect(asLink(field)).toBeNull(); -}); + expect(asLink(field)).toBeNull() +}) it("resolves a link to web field", () => { const field = { link_type: LinkType.Web, url: "https://prismic.io", - }; + } - expect(asLink(field, { linkResolver })).toBe("https://prismic.io"); -}); + expect(asLink(field, { linkResolver })).toBe("https://prismic.io") +}) it("resolves a link to media field", () => { const field = { @@ -127,13 +127,13 @@ it("resolves a link to media field", () => { size: "420", height: "42", width: "42", - }; + } - expect(asLink(field, { linkResolver })).toBe("https://prismic.io"); -}); + expect(asLink(field, { linkResolver })).toBe("https://prismic.io") +}) it("resolves a document", () => { - const document = { ...documentFixture.empty }; + const document = { ...documentFixture.empty } - expect(asLink(document)).toBe("/test"); -}); + expect(asLink(document)).toBe("/test") +}) diff --git a/test/helpers-asLinkAttrs.test.ts b/test/helpers-asLinkAttrs.test.ts index 2bced41e..a37ee933 100644 --- a/test/helpers-asLinkAttrs.test.ts +++ b/test/helpers-asLinkAttrs.test.ts @@ -1,161 +1,161 @@ -import { expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest" -import { asLinkAttrs } from "../src"; +import { asLinkAttrs } from "../src" it("returns empty object for nullish inputs", () => { - expect(asLinkAttrs(null)).toEqual({}); - expect(asLinkAttrs(undefined)).toEqual({}); -}); + expect(asLinkAttrs(null)).toEqual({}) + expect(asLinkAttrs(undefined)).toEqual({}) +}) it("returns empty object when link field is empty", (ctx) => { - const field = ctx.mock.value.link({ type: "Any", state: "empty" }); + const field = ctx.mock.value.link({ type: "Any", state: "empty" }) - expect(asLinkAttrs(field)).toEqual({}); -}); + expect(asLinkAttrs(field)).toEqual({}) +}) it("returns empty object when link to document field is empty", (ctx) => { - const field = ctx.mock.value.link({ type: "Document", state: "empty" }); + const field = ctx.mock.value.link({ type: "Document", state: "empty" }) - expect(asLinkAttrs(field)).toEqual({}); -}); + expect(asLinkAttrs(field)).toEqual({}) +}) it("returns empty object when link to media field is empty", (ctx) => { - const field = ctx.mock.value.link({ type: "Media", state: "empty" }); + const field = ctx.mock.value.link({ type: "Media", state: "empty" }) - expect(asLinkAttrs(field)).toEqual({}); -}); + expect(asLinkAttrs(field)).toEqual({}) +}) it("returns empty object when link to web field is empty", (ctx) => { - const field = ctx.mock.value.link({ type: "Web", state: "empty" }); + const field = ctx.mock.value.link({ type: "Web", state: "empty" }) - expect(asLinkAttrs(field)).toEqual({}); -}); + expect(asLinkAttrs(field)).toEqual({}) +}) it("resolves a link to document field with route resolver", (ctx) => { - const field = ctx.mock.value.link({ type: "Document" }); - field.url = "/url"; + const field = ctx.mock.value.link({ type: "Document" }) + field.url = "/url" expect(asLinkAttrs(field)).toEqual({ href: field.url, target: undefined, rel: undefined, - }); + }) expect(asLinkAttrs(field, { linkResolver: () => "/linkResolver" })).toEqual({ href: "/linkResolver", target: undefined, rel: undefined, - }); -}); + }) +}) it("resolves a link to document field without route resolver", (ctx) => { - const field = ctx.mock.value.link({ type: "Document" }); - field.url = undefined; + const field = ctx.mock.value.link({ type: "Document" }) + field.url = undefined expect(asLinkAttrs(field)).toEqual({ href: undefined, target: undefined, rel: undefined, - }); + }) expect(asLinkAttrs(field, { linkResolver: () => "/linkResolver" })).toEqual({ href: "/linkResolver", target: undefined, rel: undefined, - }); -}); + }) +}) it("resolves a link to web field", (ctx) => { - const field = ctx.mock.value.link({ type: "Web" }); + const field = ctx.mock.value.link({ type: "Web" }) expect(asLinkAttrs(field)).toEqual({ href: field.url, target: undefined, rel: "noreferrer", - }); + }) expect(asLinkAttrs(field, { linkResolver: () => "/linkResolver" })).toEqual({ href: field.url, target: undefined, rel: "noreferrer", - }); -}); + }) +}) it("returns correct target when field has a target", (ctx) => { - const field = ctx.mock.value.link({ type: "Web", withTargetBlank: true }); + const field = ctx.mock.value.link({ type: "Web", withTargetBlank: true }) expect(asLinkAttrs(field)).toEqual({ href: field.url, target: field.target, rel: "noreferrer", - }); + }) expect(asLinkAttrs(field, { linkResolver: () => "/linkResolver" })).toEqual({ href: field.url, target: field.target, rel: "noreferrer", - }); -}); + }) +}) it("resolves a link to media field", (ctx) => { - const field = ctx.mock.value.link({ type: "Media" }); + const field = ctx.mock.value.link({ type: "Media" }) expect(asLinkAttrs(field)).toEqual({ href: field.url, target: undefined, rel: "noreferrer", - }); + }) expect(asLinkAttrs(field, { linkResolver: () => "/linkResolver" })).toEqual({ href: field.url, target: undefined, rel: "noreferrer", - }); -}); + }) +}) it("resolves a document", (ctx) => { - const doc = ctx.mock.value.document(); - doc.url = "/foo"; + const doc = ctx.mock.value.document() + doc.url = "/foo" expect(asLinkAttrs(doc)).toEqual({ href: doc.url, target: undefined, rel: undefined, - }); + }) expect(asLinkAttrs(doc, { linkResolver: () => "/linkResolver" })).toEqual({ href: "/linkResolver", target: undefined, rel: undefined, - }); -}); + }) +}) it('returns "noreferrer" `rel` value when the field\'s `href` is external', (ctx) => { - const field = ctx.mock.value.link({ type: "Web" }); + const field = ctx.mock.value.link({ type: "Web" }) - expect(asLinkAttrs(field).rel).toBe("noreferrer"); + expect(asLinkAttrs(field).rel).toBe("noreferrer") expect(asLinkAttrs(field, { linkResolver: () => "/linkResolver" }).rel).toBe( "noreferrer", - ); -}); + ) +}) it("allows the `rel` value to be configured using `config.rel`", (ctx) => { - const internalField = ctx.mock.value.link({ type: "Document" }); - internalField.url = "/foo"; + const internalField = ctx.mock.value.link({ type: "Document" }) + internalField.url = "/foo" - const externalField = ctx.mock.value.link({ type: "Web" }); - externalField.url = "https://prismic.io"; - externalField.target = "_blank"; + const externalField = ctx.mock.value.link({ type: "Web" }) + externalField.url = "https://prismic.io" + externalField.target = "_blank" - const relFn = vi.fn().mockImplementation(() => "bar"); + const relFn = vi.fn().mockImplementation(() => "bar") - const internalRes = asLinkAttrs(internalField, { rel: relFn }); - expect(internalRes.rel).toBe("bar"); + const internalRes = asLinkAttrs(internalField, { rel: relFn }) + expect(internalRes.rel).toBe("bar") expect(relFn).toHaveBeenNthCalledWith(1, { href: internalField.url, target: undefined, isExternal: false, - }); + }) - const externalRes = asLinkAttrs(externalField, { rel: relFn }); - expect(externalRes.rel).toBe("bar"); + const externalRes = asLinkAttrs(externalField, { rel: relFn }) + expect(externalRes.rel).toBe("bar") expect(relFn).toHaveBeenNthCalledWith(2, { href: externalField.url, target: externalField.target, isExternal: true, - }); -}); + }) +}) diff --git a/test/helpers-asText.test.ts b/test/helpers-asText.test.ts index a1239b4e..a51fc5a3 100644 --- a/test/helpers-asText.test.ts +++ b/test/helpers-asText.test.ts @@ -1,26 +1,26 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { richTextFixture } from "./__fixtures__/richText"; +import { richTextFixture } from "./__fixtures__/richText" -import { asText } from "../src"; -import { asText as richTextAsText } from "../src/richtext"; +import { asText } from "../src" +import { asText as richTextAsText } from "../src/richtext" it("is an alias for @prismicio/client/richtext's `asText` function for non-nullish inputs", () => { - expect(asText(richTextFixture.en)).toBe(richTextAsText(richTextFixture.en)); -}); + expect(asText(richTextFixture.en)).toBe(richTextAsText(richTextFixture.en)) +}) it("returns null for nullish inputs", () => { - expect(asText(null)).toBeNull(); - expect(asText(undefined)).toBeNull(); -}); + expect(asText(null)).toBeNull() + expect(asText(undefined)).toBeNull() +}) it("supports separator configuration", () => { expect(asText(richTextFixture.en, { separator: "__separator__" })).toBe( richTextAsText(richTextFixture.en, "__separator__"), - ); + ) // TODO: Remove when we remove support for deprecated tuple-style configuration. expect(asText(richTextFixture.en, "__separator__")).toBe( richTextAsText(richTextFixture.en, "__separator__"), - ); -}); + ) +}) diff --git a/test/helpers-documentToLinkField.test.ts b/test/helpers-documentToLinkField.test.ts index 808a02c2..a454091e 100644 --- a/test/helpers-documentToLinkField.test.ts +++ b/test/helpers-documentToLinkField.test.ts @@ -1,11 +1,11 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { documentFixture } from "./__fixtures__/document"; +import { documentFixture } from "./__fixtures__/document" -import { LinkType, documentToLinkField } from "../src"; +import { LinkType, documentToLinkField } from "../src" it("returns equivalent link field from given document", () => { - const document = { ...documentFixture.empty, url: null }; + const document = { ...documentFixture.empty, url: null } expect(documentToLinkField(document)).toStrictEqual({ link_type: LinkType.Document, @@ -16,11 +16,11 @@ it("returns equivalent link field from given document", () => { lang: "en-us", url: undefined, slug: "slug", - }); -}); + }) +}) it("returns equivalent link field from given document with `apiOptions.routes`", () => { - const document = { ...documentFixture.empty }; + const document = { ...documentFixture.empty } expect(documentToLinkField(document)).toStrictEqual({ link_type: LinkType.Document, @@ -31,11 +31,11 @@ it("returns equivalent link field from given document with `apiOptions.routes`", lang: "en-us", url: "/test", slug: "slug", - }); -}); + }) +}) it("returns equivalent link field from given document without uid", () => { - const document = { ...documentFixture.empty, uid: null }; + const document = { ...documentFixture.empty, uid: null } expect(documentToLinkField(document)).toStrictEqual({ link_type: LinkType.Document, @@ -46,11 +46,11 @@ it("returns equivalent link field from given document without uid", () => { lang: "en-us", url: "/test", slug: "slug", - }); -}); + }) +}) it("returns equivalent link field from given document with non-empty data", () => { - const document = { ...documentFixture.empty, data: { foo: "bar" } }; + const document = { ...documentFixture.empty, data: { foo: "bar" } } expect(documentToLinkField(document)).toStrictEqual({ link_type: LinkType.Document, @@ -62,8 +62,8 @@ it("returns equivalent link field from given document with non-empty data", () = url: "/test", slug: "slug", data: { foo: "bar" }, - }); -}); + }) +}) // This test checks support for Gatsby users. The `slugs` field is not // queriable in Gatsby since it is deprecated. @@ -73,7 +73,7 @@ it("supports documents without slugs field", () => { ...documentFixture.empty, url: null, slugs: undefined, - }; + } expect(documentToLinkField(document)).toStrictEqual({ link_type: LinkType.Document, @@ -84,5 +84,5 @@ it("supports documents without slugs field", () => { lang: "en-us", url: undefined, slug: undefined, - }); -}); + }) +}) diff --git a/test/helpers-isFilled.test.ts b/test/helpers-isFilled.test.ts index 533f315e..75970667 100644 --- a/test/helpers-isFilled.test.ts +++ b/test/helpers-isFilled.test.ts @@ -1,77 +1,78 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { documentFixture } from "./__fixtures__/document"; +import { documentFixture } from "./__fixtures__/document" -import { GroupField, SliceZone, isFilled } from "../src"; +import type { GroupField, SliceZone } from "../src" +import { isFilled } from "../src" it("color", (ctx) => { - expect(isFilled.color(null)).toBe(false); - expect(isFilled.color(undefined)).toBe(false); - expect(isFilled.color(ctx.mock.value.color())).toBe(true); -}); + expect(isFilled.color(null)).toBe(false) + expect(isFilled.color(undefined)).toBe(false) + expect(isFilled.color(ctx.mock.value.color())).toBe(true) +}) it("content relationship", (ctx) => { - expect(isFilled.contentRelationship(null)).toBe(false); - expect(isFilled.contentRelationship(undefined)).toBe(false); + expect(isFilled.contentRelationship(null)).toBe(false) + expect(isFilled.contentRelationship(undefined)).toBe(false) expect( isFilled.contentRelationship( ctx.mock.value.contentRelationship({ state: "empty", }), ), - ).toBe(false); + ).toBe(false) expect( isFilled.contentRelationship( ctx.mock.value.contentRelationship({ state: "filled", }), ), - ).toBe(true); -}); + ).toBe(true) +}) it("date", (ctx) => { - expect(isFilled.date(null)).toBe(false); - expect(isFilled.date(undefined)).toBe(false); - expect(isFilled.date(ctx.mock.value.date())).toBe(true); -}); + expect(isFilled.date(null)).toBe(false) + expect(isFilled.date(undefined)).toBe(false) + expect(isFilled.date(ctx.mock.value.date())).toBe(true) +}) it("embed", (ctx) => { - expect(isFilled.embed(null)).toBe(false); - expect(isFilled.embed(undefined)).toBe(false); - expect(isFilled.embed({})).toBe(false); - expect(isFilled.embed(ctx.mock.value.embed())).toBe(true); -}); + expect(isFilled.embed(null)).toBe(false) + expect(isFilled.embed(undefined)).toBe(false) + expect(isFilled.embed({})).toBe(false) + expect(isFilled.embed(ctx.mock.value.embed())).toBe(true) +}) it("geopoint", (ctx) => { - expect(isFilled.geoPoint(null)).toBe(false); - expect(isFilled.geoPoint(undefined)).toBe(false); - expect(isFilled.geoPoint({})).toBe(false); - expect(isFilled.geoPoint(ctx.mock.value.geoPoint())).toBe(true); -}); + expect(isFilled.geoPoint(null)).toBe(false) + expect(isFilled.geoPoint(undefined)).toBe(false) + expect(isFilled.geoPoint({})).toBe(false) + expect(isFilled.geoPoint(ctx.mock.value.geoPoint())).toBe(true) +}) it("group", (ctx) => { - expect(isFilled.group(null)).toBe(false); - expect(isFilled.group(undefined)).toBe(false); - expect(isFilled.group([])).toBe(false); - expect(isFilled.group(ctx.mock.value.group() as GroupField)).toBe(true); -}); + expect(isFilled.group(null)).toBe(false) + expect(isFilled.group(undefined)).toBe(false) + expect(isFilled.group([])).toBe(false) + expect(isFilled.group(ctx.mock.value.group() as GroupField)).toBe(true) +}) it("image", (ctx) => { - expect(isFilled.image(null)).toBe(false); - expect(isFilled.image(undefined)).toBe(false); - expect(isFilled.image({})).toBe(false); + expect(isFilled.image(null)).toBe(false) + expect(isFilled.image(undefined)).toBe(false) + expect(isFilled.image({})).toBe(false) expect( isFilled.image( // @ts-expect-error Remove this comment after v7.3.0 is published. ctx.mock.value.image(), ), - ).toBe(true); -}); + ).toBe(true) +}) it("image thumbnail", () => { - expect(isFilled.imageThumbnail(null)).toBe(false); - expect(isFilled.imageThumbnail(undefined)).toBe(false); - expect(isFilled.imageThumbnail({})).toBe(false); + expect(isFilled.imageThumbnail(null)).toBe(false) + expect(isFilled.imageThumbnail(undefined)).toBe(false) + expect(isFilled.imageThumbnail({})).toBe(false) expect( isFilled.imageThumbnail({ id: "id", @@ -86,67 +87,67 @@ it("image thumbnail", () => { copyright: null, dimensions: { width: 1, height: 1 }, }), - ).toBe(true); -}); + ).toBe(true) +}) it("integration fields", (ctx) => { - expect(isFilled.integrationField(null)).toBe(false); - expect(isFilled.integrationField(undefined)).toBe(false); - expect(isFilled.integrationField(ctx.mock.value.integration())).toBe(true); -}); + expect(isFilled.integrationField(null)).toBe(false) + expect(isFilled.integrationField(undefined)).toBe(false) + expect(isFilled.integrationField(ctx.mock.value.integration())).toBe(true) +}) it("aliases integrationFields to integrationField", () => { - expect(isFilled.integrationField).toBe(isFilled.integrationField); -}); + expect(isFilled.integrationField).toBe(isFilled.integrationField) +}) it("key text", (ctx) => { - expect(isFilled.keyText(null)).toBe(false); - expect(isFilled.keyText(undefined)).toBe(false); - expect(isFilled.keyText("")).toBe(false); - expect(isFilled.keyText(ctx.mock.value.keyText())).toBe(true); -}); + expect(isFilled.keyText(null)).toBe(false) + expect(isFilled.keyText(undefined)).toBe(false) + expect(isFilled.keyText("")).toBe(false) + expect(isFilled.keyText(ctx.mock.value.keyText())).toBe(true) +}) it("link", (ctx) => { - expect(isFilled.link(null)).toBe(false); - expect(isFilled.link(undefined)).toBe(false); - expect(isFilled.link(ctx.mock.value.link({ state: "empty" }))).toBe(false); - expect(isFilled.link(ctx.mock.value.link({ state: "filled" }))).toBe(true); -}); + expect(isFilled.link(null)).toBe(false) + expect(isFilled.link(undefined)).toBe(false) + expect(isFilled.link(ctx.mock.value.link({ state: "empty" }))).toBe(false) + expect(isFilled.link(ctx.mock.value.link({ state: "filled" }))).toBe(true) +}) it("link to media", (ctx) => { - expect(isFilled.linkToMedia(null)).toBe(false); - expect(isFilled.linkToMedia(undefined)).toBe(false); + expect(isFilled.linkToMedia(null)).toBe(false) + expect(isFilled.linkToMedia(undefined)).toBe(false) expect( isFilled.linkToMedia(ctx.mock.value.linkToMedia({ state: "empty" })), - ).toBe(false); + ).toBe(false) expect( isFilled.linkToMedia(ctx.mock.value.linkToMedia({ state: "filled" })), - ).toBe(true); -}); + ).toBe(true) +}) it("number", (ctx) => { - expect(isFilled.number(null)).toBe(false); - expect(isFilled.number(undefined)).toBe(false); - expect(isFilled.number(ctx.mock.value.number())).toBe(true); -}); + expect(isFilled.number(null)).toBe(false) + expect(isFilled.number(undefined)).toBe(false) + expect(isFilled.number(ctx.mock.value.number())).toBe(true) +}) it("rich text", (ctx) => { - expect(isFilled.richText(null)).toBe(false); - expect(isFilled.richText(undefined)).toBe(false); - expect(isFilled.richText([])).toBe(false); + expect(isFilled.richText(null)).toBe(false) + expect(isFilled.richText(undefined)).toBe(false) + expect(isFilled.richText([])).toBe(false) expect(isFilled.richText([{ type: "paragraph", text: "", spans: [] }])).toBe( false, - ); + ) expect( isFilled.richText( // @ts-expect-error Remove this comment after v7.3.0 is published. ctx.mock.value.richText(), ), - ).toBe(true); -}); + ).toBe(true) +}) it("select", (ctx) => { - expect(isFilled.select(null)).toBe(false); - expect(isFilled.select(undefined)).toBe(false); + expect(isFilled.select(null)).toBe(false) + expect(isFilled.select(undefined)).toBe(false) expect( isFilled.select( ctx.mock.value.select({ @@ -155,13 +156,13 @@ it("select", (ctx) => { }), }), ), - ).toBe(true); -}); + ).toBe(true) +}) it("slice zone", (ctx) => { - expect(isFilled.sliceZone(null)).toBe(false); - expect(isFilled.sliceZone(undefined)).toBe(false); - expect(isFilled.sliceZone([])).toBe(false); + expect(isFilled.sliceZone(null)).toBe(false) + expect(isFilled.sliceZone(undefined)).toBe(false) + expect(isFilled.sliceZone([])).toBe(false) expect( isFilled.sliceZone( ctx.mock.value.sliceZone({ @@ -173,27 +174,27 @@ it("slice zone", (ctx) => { }), }) as SliceZone, ), - ).toBe(true); -}); + ).toBe(true) +}) it("timestamp", (ctx) => { - expect(isFilled.timestamp(null)).toBe(false); - expect(isFilled.timestamp(undefined)).toBe(false); - expect(isFilled.timestamp(ctx.mock.value.timestamp())).toBe(true); + expect(isFilled.timestamp(null)).toBe(false) + expect(isFilled.timestamp(undefined)).toBe(false) + expect(isFilled.timestamp(ctx.mock.value.timestamp())).toBe(true) expect(isFilled.timestamp(documentFixture.empty.first_publication_date)).toBe( true, - ); + ) expect(isFilled.timestamp(documentFixture.empty.last_publication_date)).toBe( true, - ); -}); + ) +}) it("title", (ctx) => { - expect(isFilled.title(null)).toBe(false); - expect(isFilled.title(undefined)).toBe(false); - expect(isFilled.title([])).toBe(false); + expect(isFilled.title(null)).toBe(false) + expect(isFilled.title(undefined)).toBe(false) + expect(isFilled.title([])).toBe(false) expect(isFilled.title([{ type: "heading1", text: "", spans: [] }])).toBe( false, - ); - expect(isFilled.title(ctx.mock.value.title())).toBe(true); -}); + ) + expect(isFilled.title(ctx.mock.value.title())).toBe(true) +}) diff --git a/test/helpers-mapSliceZone.test.ts b/test/helpers-mapSliceZone.test.ts index 8a71c7a2..b431d300 100644 --- a/test/helpers-mapSliceZone.test.ts +++ b/test/helpers-mapSliceZone.test.ts @@ -1,6 +1,7 @@ -import { TestContext, expect, it, vi } from "vitest"; +import type { TestContext } from "vitest" +import { expect, it, vi } from "vitest" -import { mapSliceZone } from "../src"; +import { mapSliceZone } from "../src" const generateTestData = (ctx: TestContext) => { const model1 = ctx.mock.model.sharedSlice({ @@ -10,7 +11,7 @@ const generateTestData = (ctx: TestContext) => { itemsFields: { bar: ctx.mock.model.keyText() }, }), ], - }); + }) const model2 = ctx.mock.model.sharedSlice({ variations: [ ctx.mock.model.sharedSliceVariation({ @@ -18,22 +19,22 @@ const generateTestData = (ctx: TestContext) => { itemsFields: { bar: ctx.mock.model.keyText() }, }), ], - }); + }) const sliceZone = [ ctx.mock.value.sharedSlice({ model: model1 }), ctx.mock.value.sharedSlice({ model: model2 }), - ]; + ] return { sliceZone, model1, model2, - }; -}; + } +} it("maps a Slice Zone", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) const actual = await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -42,16 +43,16 @@ it("maps a Slice Zone", async (ctx) => { [model1.id]: () => ({ foo: "bar" }), [model2.id]: () => ({ baz: "qux" }), }, - ); + ) expect(actual).toStrictEqual([ { __mapped: true, id: undefined, slice_type: model1.id, foo: "bar" }, { __mapped: true, id: undefined, slice_type: model2.id, baz: "qux" }, - ]); -}); + ]) +}) it("supports mapping functions that return undefined", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) const actual = await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -60,16 +61,16 @@ it("supports mapping functions that return undefined", async (ctx) => { [model1.id]: () => void 0, [model2.id]: () => void 0, }, - ); + ) expect(actual).toStrictEqual([ { __mapped: true, id: undefined, slice_type: model1.id }, { __mapped: true, id: undefined, slice_type: model2.id }, - ]); -}); + ]) +}) it("supports async mapping functions", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) const actual = await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -78,16 +79,16 @@ it("supports async mapping functions", async (ctx) => { [model1.id]: async () => ({ foo: "bar" }), [model2.id]: async () => ({ baz: "qux" }), }, - ); + ) expect(actual).toStrictEqual([ { __mapped: true, id: undefined, slice_type: model1.id, foo: "bar" }, { __mapped: true, id: undefined, slice_type: model2.id, baz: "qux" }, - ]); -}); + ]) +}) it("supports overriding id and slice_type properties", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) const actual = await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -96,19 +97,19 @@ it("supports overriding id and slice_type properties", async (ctx) => { [model1.id]: async () => ({ id: "foo", slice_type: "bar" }), [model2.id]: async () => ({ id: "baz", slice_type: "qux" }), }, - ); + ) expect(actual).toStrictEqual([ { __mapped: true, id: "foo", slice_type: "bar" }, { __mapped: true, id: "baz", slice_type: "qux" }, - ]); -}); + ]) +}) it("provides Slice data to mapping functions", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) - const mapper1 = vi.fn(); - const mapper2 = vi.fn(); + const mapper1 = vi.fn() + const mapper2 = vi.fn() await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -117,29 +118,29 @@ it("provides Slice data to mapping functions", async (ctx) => { [model1.id]: mapper1, [model2.id]: mapper2, }, - ); + ) expect(mapper1).toHaveBeenCalledWith({ context: undefined, index: 0, slice: sliceZone[0], slices: sliceZone, - }); + }) expect(mapper2).toHaveBeenCalledWith({ context: undefined, index: 1, slice: sliceZone[1], slices: sliceZone, - }); -}); + }) +}) it("supports context", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) - const mapper1 = vi.fn(); - const mapper2 = vi.fn(); + const mapper1 = vi.fn() + const mapper2 = vi.fn() - const context = { foo: "bar" }; + const context = { foo: "bar" } await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -149,24 +150,24 @@ it("supports context", async (ctx) => { [model2.id]: mapper2, }, context, - ); + ) expect(mapper1).toHaveBeenCalledWith({ context, index: 0, slice: sliceZone[0], slices: sliceZone, - }); + }) expect(mapper2).toHaveBeenCalledWith({ context, index: 1, slice: sliceZone[1], slices: sliceZone, - }); -}); + }) +}) it("supports lazy-loaded mapping functions", async (ctx) => { - const { sliceZone, model1, model2 } = generateTestData(ctx); + const { sliceZone, model1, model2 } = generateTestData(ctx) const actual = await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -177,16 +178,16 @@ it("supports lazy-loaded mapping functions", async (ctx) => { // Simulates `import()` with a default export. [model2.id]: async () => () => ({ baz: "qux" }), }, - ); + ) expect(actual).toStrictEqual([ { __mapped: true, id: undefined, slice_type: model1.id, foo: "bar" }, { __mapped: true, id: undefined, slice_type: model2.id, baz: "qux" }, - ]); -}); + ]) +}) it("skips Slices without a mapping function", async (ctx) => { - const { sliceZone, model1 } = generateTestData(ctx); + const { sliceZone, model1 } = generateTestData(ctx) const actual = await mapSliceZone( // @ts-expect-error Remove this comment after v7.3.0 is published. @@ -194,24 +195,24 @@ it("skips Slices without a mapping function", async (ctx) => { { [model1.id]: () => void 0, }, - ); + ) expect(actual).toStrictEqual([ { __mapped: true, id: undefined, slice_type: model1.id }, sliceZone[1], - ]); -}); + ]) +}) it("supports GraphQL Slice Zones", async () => { - const sliceZone = [{ type: "foo" }, { type: "bar" }]; + const sliceZone = [{ type: "foo" }, { type: "bar" }] const actual = await mapSliceZone(sliceZone, { foo: () => ({ foo: "bar" }), bar: () => ({ baz: "qux" }), - }); + }) expect(actual).toStrictEqual([ { __mapped: true, type: "foo", foo: "bar" }, { __mapped: true, type: "bar", baz: "qux" }, - ]); -}); + ]) +}) diff --git a/test/helpers-unstable_htmlAsRichText.test.ts b/test/helpers-unstable_htmlAsRichText.test.ts index d12b456b..5513d43a 100644 --- a/test/helpers-unstable_htmlAsRichText.test.ts +++ b/test/helpers-unstable_htmlAsRichText.test.ts @@ -1,42 +1,42 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest" -import { testHTMLAsRichTextHelper } from "./__testutils__/testAsRichTextHelper"; +import { testHTMLAsRichTextHelper } from "./__testutils__/testAsRichTextHelper" -import { unstable_htmlAsRichText } from "../src"; +import { unstable_htmlAsRichText } from "../src" describe("transforms HTML to rich text", () => { describe("basic", () => { testHTMLAsRichTextHelper("empty", { input: /* html */ ``, - }); + }) testHTMLAsRichTextHelper("single tag", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, - }); + }) testHTMLAsRichTextHelper("multiple tags", { input: /* html */ `

    lorem ipsum dolor sit amet

    consectetur adipiscing elit

    `, - }); + }) testHTMLAsRichTextHelper("innerHTML", { input: /* html */ `lorem ipsum dolor sit amet`, expectHTMLToMatchInputExactly: false, - }); - }); + }) + }) describe("spans", () => { testHTMLAsRichTextHelper("strong, em", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, - }); + }) testHTMLAsRichTextHelper("label", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, config: { serializer: { "span.underline": { label: "underline" } } }, - }); + }) testHTMLAsRichTextHelper("hyperlink", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, - }); + }) testHTMLAsRichTextHelper("hyperlink missing href", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, @@ -44,18 +44,18 @@ describe("transforms HTML to rich text", () => { "1:10-1:22: Element of type `hyperlink` is missing an `href` attribute", ], expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("empty spans", { // It's normal for `dolor` and `sit` to be concatenated here. - // That how the browser would render it. + // That's how the browser would render it. input: /* html */ `

    lorem ipsum dolor sit amet

    `, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("nested spans", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, - }); + }) describe("directly adjacent spans", () => { describe("compacts similar", () => { @@ -63,30 +63,30 @@ describe("transforms HTML to rich text", () => { input: /* html */ `

    lorem ipsum dolor sit amet consectetur adipiscing elit

    `, // `strong` and `em` tags will be merged into single ones. expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("hyperlink", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, // `a` tags will be merged into single ones. expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("label", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, config: { serializer: { "span.underline": { label: "underline" } } }, // `span.underline` tags will be merged into single ones. expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("nested spans", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, - }); - }); + }) + }) describe("does not compact different", () => { testHTMLAsRichTextHelper("hyperlink", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, - }); + }) testHTMLAsRichTextHelper("label", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, @@ -96,52 +96,52 @@ describe("transforms HTML to rich text", () => { "span.strikethrough": { label: "strikethrough" }, }, }, - }); - }); - }); - }); + }) + }) + }) + }) describe("lists", () => { testHTMLAsRichTextHelper("list-item", { input: /* html */ `
    • lorem ipsum dolor sit amet
    • consectetur adipiscing elit
    `, - }); + }) testHTMLAsRichTextHelper("o-list-item", { input: /* html */ `
    1. lorem ipsum dolor sit amet
    2. consectetur adipiscing elit
    `, - }); + }) testHTMLAsRichTextHelper("list-item and o-list-item", { input: /* html */ `
    1. lorem ipsum dolor sit amet
    2. consectetur adipiscing elit
    • sed do eiusmod tempor incididunt
    • ut labore et dolore magna aliqua
    `, - }); + }) // We expect the last list item to be an `o-list-item` because we don't support nested lists. testHTMLAsRichTextHelper("nested list-item and o-list-item", { input: /* html */ `
    • lorem ipsum dolor sit amet
      1. consectetur adipiscing elit
      2. sed do eiusmod tempor incididunt
    • ut labore et dolore magna aliqua
    `, expectHTMLToMatchInputExactly: false, - }); - }); + }) + }) describe("image", () => { testHTMLAsRichTextHelper("absolute", { input: /* html */ `foo`, - }); + }) testHTMLAsRichTextHelper("relative", { input: /* html */ `foo`, - }); + }) testHTMLAsRichTextHelper("prismic", { input: /* html */ `foo`, - }); + }) testHTMLAsRichTextHelper("empty alt", { input: /* html */ ``, - }); + }) testHTMLAsRichTextHelper("missing alt", { input: /* html */ ``, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("missing src", { input: /* html */ ``, @@ -149,42 +149,42 @@ describe("transforms HTML to rich text", () => { "1:1-1:8: Element of type `img` is missing an `src` attribute", ], expectHTMLToMatchInputExactly: false, - }); + }) describe("extracts image in text nodes and resume previous text node", () => { testHTMLAsRichTextHelper("basic", { input: /* html */ `

    lorem ipsum bar dolor sit amet

    `, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("spans", { input: /* html */ `

    lorem ipsum bar dolor sit amet

    `, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("adjacent spans", { input: /* html */ `

    lorem ipsum bar dolor sit amet

    `, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("adjacent spans (respects direction)", { input: /* html */ `

    lorem ipsum bar dolor sit amet

    `, config: { direction: "rtl" }, expectHTMLToMatchInputExactly: false, - }); - }); - }); + }) + }) + }) describe("embed", () => { testHTMLAsRichTextHelper("iframe", { input: /* html */ ``, - }); + }) // TODO: Update with function serializer to remove the first link testHTMLAsRichTextHelper("custom", { input: /* html */ ``, config: { serializer: { blockquote: "embed" } }, - }); + }) testHTMLAsRichTextHelper("missing src", { input: /* html */ ``, @@ -192,8 +192,8 @@ describe("transforms HTML to rich text", () => { "1:1-1:18: Element of type `embed` is missing an `src` attribute", ], expectHTMLToMatchInputExactly: false, - }); - }); + }) + }) describe("configuration", () => { describe("serializer", () => { @@ -205,7 +205,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("selector", { input: /* html */ `

    lorem ipsum dolor sit amet

    consectetur adipiscing elit

    `, @@ -215,7 +215,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("complex selector", { input: /* html */ ` @@ -227,7 +227,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) describe("shorthand serializer", () => { it("throws on invalide rich text node type", () => { @@ -240,9 +240,9 @@ describe("transforms HTML to rich text", () => { ), ).toThrowErrorMatchingInlineSnapshot( `[Error: Unknown rich text node type: \`foo\`]`, - ); - }); - }); + ) + }) + }) describe("function serializer", () => { testHTMLAsRichTextHelper("basic", { @@ -254,7 +254,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("undefined", { input: /* html */ `

    lorem ipsum dolor sit amet

    consectetur adipiscing elit

    `, @@ -265,7 +265,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("text nodes", { input: /* html */ `
    lorem ipsum dolor sit amet
    `, @@ -275,7 +275,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("image node", { input: /* html */ ``, @@ -293,7 +293,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("embed node", { input: /* html */ ``, @@ -314,7 +314,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) describe("span nodes", () => { testHTMLAsRichTextHelper("partial", { @@ -325,7 +325,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("full", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, @@ -335,7 +335,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) describe("with extracted image node", () => { testHTMLAsRichTextHelper("partial", { @@ -346,7 +346,7 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("full", { input: /* html */ `

    lorem ipsum bar dolor sit amet

    `, @@ -356,11 +356,11 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); - }); - }); - }); - }); + }) + }) + }) + }) + }) describe("container", () => { testHTMLAsRichTextHelper("converts only the given container", { @@ -369,16 +369,16 @@ describe("transforms HTML to rich text", () => {

    consectetur adipiscing elit

    `, config: { container: "article#bar" }, expectHTMLToMatchInputExactly: false, - }); + }) it("throws when the container cannot be found", () => { expect(() => unstable_htmlAsRichText("", { container: "article#baz" }), ).toThrowErrorMatchingInlineSnapshot( `[Error: No container matching \`article#baz\` could be found in the input AST.]`, - ); - }); - }); + ) + }) + }) describe("exclude", () => { testHTMLAsRichTextHelper("excludes the given selectors", { @@ -387,7 +387,7 @@ describe("transforms HTML to rich text", () => {

    consectetur adipiscing elit

    `, config: { exclude: ["h1"] }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("excludes the given complex selectors", { input: /* html */ ` @@ -395,8 +395,8 @@ describe("transforms HTML to rich text", () => {

    consectetur adipiscing elit

    `, config: { exclude: ["h1 > a"] }, expectHTMLToMatchInputExactly: false, - }); - }); + }) + }) describe("include", () => { testHTMLAsRichTextHelper("includes only the given selectors", { @@ -405,7 +405,7 @@ describe("transforms HTML to rich text", () => {

    consectetur adipiscing elit

    `, config: { include: ["h1"] }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("includes only the given complex selectors", { input: /* html */ ` @@ -413,7 +413,7 @@ describe("transforms HTML to rich text", () => {

    consectetur adipiscing elit

    `, config: { include: ["article#bar > p"] }, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper( "dedupes matches that are child of other matches", @@ -424,8 +424,8 @@ describe("transforms HTML to rich text", () => { config: { include: ["article#bar", "p"] }, expectHTMLToMatchInputExactly: false, }, - ); - }); + ) + }) describe("model", () => { testHTMLAsRichTextHelper( @@ -440,7 +440,7 @@ describe("transforms HTML to rich text", () => { }, expectHTMLToMatchInputExactly: false, }, - ); + ) testHTMLAsRichTextHelper("filters output according to multi type model", { input: /* html */ ` @@ -454,31 +454,31 @@ describe("transforms HTML to rich text", () => { }, }, expectHTMLToMatchInputExactly: false, - }); - }); + }) + }) describe("direction", () => { testHTMLAsRichTextHelper("marks text as left-to-right", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, config: { direction: "ltr" }, - }); + }) testHTMLAsRichTextHelper("marks text as right-to-left", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, config: { direction: "rtl" }, - }); - }); - }); + }) + }) + }) describe("whistespaces", () => { testHTMLAsRichTextHelper("treats `
    ` as new lines", { input: /* html */ `

    lorem ipsum dolor sit amet
    consectetur adipiscing elit

    `, - }); + }) testHTMLAsRichTextHelper("ignores wild `
    `", { input: /* html */ `

    lorem ipsum dolor sit amet

    `, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("strips indentation", { input: /* html */ ` @@ -487,7 +487,7 @@ describe("transforms HTML to rich text", () => {

    `, expectHTMLToMatchInputExactly: false, - }); + }) testHTMLAsRichTextHelper("strips complex indentation", { input: /* html */ ` @@ -497,6 +497,6 @@ describe("transforms HTML to rich text", () => {

    `, expectHTMLToMatchInputExactly: false, - }); - }); -}); + }) + }) +}) diff --git a/test/helpers-unstable_markdownAsRichText.test.ts b/test/helpers-unstable_markdownAsRichText.test.ts index 857c9e2f..f5206647 100644 --- a/test/helpers-unstable_markdownAsRichText.test.ts +++ b/test/helpers-unstable_markdownAsRichText.test.ts @@ -1,20 +1,20 @@ -import { describe } from "vitest"; +import { describe } from "vitest" -import { testMarkdownAsRichTextHelper } from "./__testutils__/testAsRichTextHelper"; +import { testMarkdownAsRichTextHelper } from "./__testutils__/testAsRichTextHelper" describe("transforms markdown to rich text", () => { describe("basic", () => { testMarkdownAsRichTextHelper("empty", { input: /* md */ ``, - }); + }) testMarkdownAsRichTextHelper("single tag", { input: /* md */ `lorem ipsum dolor sit amet`, - }); + }) testMarkdownAsRichTextHelper("multiple tags", { input: /* md */ `# lorem ipsum dolor sit amet consectetur adipiscing elit`, - }); - }); -}); + }) + }) +}) diff --git a/test/index.test.ts b/test/index.test.ts index 1963441f..38e3fc63 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1,6 +1,6 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("rich text node type mapping", () => { expect(prismic.RichTextNodeType).toMatchObject({ @@ -23,8 +23,8 @@ it("rich text node type mapping", () => { hyperlink: "hyperlink", label: "label", span: "span", - }); -}); + }) +}) it("link type mapping", () => { expect(prismic.LinkType).toMatchObject({ @@ -32,8 +32,8 @@ it("link type mapping", () => { Web: "Web", Media: "Media", Document: "Document", - }); -}); + }) +}) it("embed type mapping", () => { expect(prismic.OEmbedType).toMatchObject({ @@ -41,8 +41,8 @@ it("embed type mapping", () => { Video: "video", Link: "link", Rich: "rich", - }); -}); + }) +}) it("custom type field type mapping", () => { expect(prismic.CustomTypeModelFieldType).toStrictEqual({ @@ -67,43 +67,43 @@ it("custom type field type mapping", () => { Range: "Range", Separator: "Separator", LegacySlices: "Choice", - }); -}); + }) +}) it("custom type link select mapping", () => { expect(prismic.CustomTypeModelLinkSelectType).toMatchObject({ Document: "document", Media: "media", - }); -}); + }) +}) it("custom type slice display mapping", () => { expect(prismic.CustomTypeModelSliceDisplay).toMatchObject({ Grid: "grid", List: "list", - }); -}); + }) +}) it("custom type slice type mapping", () => { expect(prismic.CustomTypeModelSliceType).toMatchObject({ Slice: "Slice", SharedSlice: "SharedSlice", - }); -}); + }) +}) it("webhook type mapping", () => { expect(prismic.WebhookType).toMatchObject({ APIUpdate: "api-update", TestTrigger: "test-trigger", - }); -}); + }) +}) // TODO: Remove when we remove support for deprecated `predicate` export. it("predicate is a temporary alias for filter", () => { - expect(prismic.predicate).toStrictEqual(prismic.filter); -}); + expect(prismic.predicate).toStrictEqual(prismic.filter) +}) // TODO: Remove when we remove support for deprecated `unstable_mapSliceZone` export. it("unstable_mapSliceZone is a temporary alias for mapSliceZone", () => { - expect(prismic.unstable_mapSliceZone).toStrictEqual(prismic.mapSliceZone); -}); + expect(prismic.unstable_mapSliceZone).toStrictEqual(prismic.mapSliceZone) +}) diff --git a/test/isRepositoryEndpoint.test.ts b/test/isRepositoryEndpoint.test.ts index 8bb9c665..f2abaa8f 100644 --- a/test/isRepositoryEndpoint.test.ts +++ b/test/isRepositoryEndpoint.test.ts @@ -1,22 +1,22 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns true if the input is a repository endpoint", () => { expect( prismic.isRepositoryEndpoint("https://qwerty.cdn.prismic.io/api/v2"), - ).toBe(true); + ).toBe(true) expect( prismic.isRepositoryEndpoint("https://example.com"), "Any valid URL is a valid Prismic repository endpoint to support network proxies.", - ).toBe(true); -}); + ).toBe(true) +}) it("returns false if the input is not a repository endpoint", () => { - expect(prismic.isRepositoryEndpoint("qwerty")).toBe(false); + expect(prismic.isRepositoryEndpoint("qwerty")).toBe(false) expect( prismic.isRepositoryEndpoint( "https://this is invalid.cdn.prismic.io/api/v2", ), - ).toBe(false); -}); + ).toBe(false) +}) diff --git a/test/isRepositoryName.test.ts b/test/isRepositoryName.test.ts index ea19e940..65382209 100644 --- a/test/isRepositoryName.test.ts +++ b/test/isRepositoryName.test.ts @@ -1,14 +1,14 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import * as prismic from "../src"; +import * as prismic from "../src" it("returns true if the input is a repository name", () => { - expect(prismic.isRepositoryName("qwerty")).toBe(true); -}); + expect(prismic.isRepositoryName("qwerty")).toBe(true) +}) it("returns false if the input is not a repository name", () => { expect(prismic.isRepositoryName("https://qwerty.cdn.prismic.io/api/v2")).toBe( false, - ); - expect(prismic.isRepositoryName("this is invalid")).toBe(false); -}); + ) + expect(prismic.isRepositoryName("this is invalid")).toBe(false) +}) diff --git a/test/lib-filterRichTextField.test.ts b/test/lib-filterRichTextField.test.ts index 20782d23..c6e6a6d6 100644 --- a/test/lib-filterRichTextField.test.ts +++ b/test/lib-filterRichTextField.test.ts @@ -1,9 +1,10 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "./__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "./__testutils__/createRichTextFixtures" -import { LinkType, RTImageNode, RTParagraphNode, RichTextField } from "../src"; -import { filterRichTextField } from "../src/lib/filterRichTextField"; +import type { RTImageNode, RTParagraphNode, RichTextField } from "../src" +import { LinkType } from "../src" +import { filterRichTextField } from "../src/lib/filterRichTextField" it("filters out node types that aren't allowed by single type model", () => { const input: RichTextField = [ @@ -22,40 +23,40 @@ it("filters out node types that aren't allowed by single type model", () => { text: "sed do eiusmod tempor", type: "heading1", }, - ]; + ] - const allowedNodeTypes = ["heading1"]; + const allowedNodeTypes = ["heading1"] const output = filterRichTextField(input, { type: "StructuredText", config: { single: allowedNodeTypes.join(","), }, - }); + }) - expect(output).toHaveLength(1); + expect(output).toHaveLength(1) expect(output.every((node) => allowedNodeTypes.includes(node.type))).toBe( true, - ); -}); + ) +}) it("filters out node types that aren't allowed by multi type model", () => { - const { en: input } = createRichTextFixtures(); + const { en: input } = createRichTextFixtures() - const allowedNodeTypes = ["paragraph", "embed"]; + const allowedNodeTypes = ["paragraph", "embed"] const output = filterRichTextField(input, { type: "StructuredText", config: { multi: allowedNodeTypes.join(","), }, - }); + }) - expect(output.length).toBeGreaterThanOrEqual(1); + expect(output.length).toBeGreaterThanOrEqual(1) expect(output.every((node) => allowedNodeTypes.includes(node.type))).toBe( true, - ); -}); + ) +}) it("filters out span node types that aren't allowed by single type model", () => { const input: RichTextField = [ @@ -75,22 +76,22 @@ it("filters out span node types that aren't allowed by single type model", () => text: "lorem ipsum dolor sit amet", type: "paragraph", }, - ]; + ] - const allowedNodeTypes = ["paragraph", "strong"]; + const allowedNodeTypes = ["paragraph", "strong"] const [output] = filterRichTextField(input, { type: "StructuredText", config: { single: allowedNodeTypes.join(","), }, - }) as RTParagraphNode[]; + }) as RTParagraphNode[] - expect(output.spans.length).toBeGreaterThanOrEqual(1); + expect(output.spans.length).toBeGreaterThanOrEqual(1) expect( output.spans.every((span) => allowedNodeTypes.includes(span.type)), - ).toBe(true); -}); + ).toBe(true) +}) it("filters out label span nodes that aren't allowed by single type model", () => { const input: RichTextField = [ @@ -112,9 +113,9 @@ it("filters out label span nodes that aren't allowed by single type model", () = text: "lorem ipsum dolor sit amet", type: "paragraph", }, - ]; + ] - const allowedLabelTypes = ["code"]; + const allowedLabelTypes = ["code"] const [output] = filterRichTextField(input, { type: "StructuredText", @@ -122,16 +123,16 @@ it("filters out label span nodes that aren't allowed by single type model", () = single: "paragraph", labels: allowedLabelTypes, }, - }) as RTParagraphNode[]; + }) as RTParagraphNode[] - expect(output.spans.length).toBeGreaterThanOrEqual(1); + expect(output.spans.length).toBeGreaterThanOrEqual(1) expect( output.spans.every( (span) => span.type === "label" && allowedLabelTypes.includes(span.data.label), ), - ).toBe(true); -}); + ).toBe(true) +}) it('removes `target: "_blank"` from hyperlink spans when they are not allowed', () => { const input: RichTextField = [ @@ -157,7 +158,7 @@ it('removes `target: "_blank"` from hyperlink spans when they are not allowed', text: "lorem ipsum dolor sit amet", type: "paragraph", }, - ]; + ] const [allowedOutput] = filterRichTextField(input, { type: "StructuredText", @@ -165,9 +166,9 @@ it('removes `target: "_blank"` from hyperlink spans when they are not allowed', single: "paragraph,hyperlink", allowTargetBlank: true, }, - }) as RTParagraphNode[]; + }) as RTParagraphNode[] - expect(allowedOutput.spans.length).toBeGreaterThanOrEqual(1); + expect(allowedOutput.spans.length).toBeGreaterThanOrEqual(1) expect( allowedOutput.spans.every( (span) => @@ -175,7 +176,7 @@ it('removes `target: "_blank"` from hyperlink spans when they are not allowed', span.data.link_type === LinkType.Web && !span.data.target, ), - ).toBe(false); + ).toBe(false) const [notAllowedOutput] = filterRichTextField(input, { type: "StructuredText", @@ -183,9 +184,9 @@ it('removes `target: "_blank"` from hyperlink spans when they are not allowed', single: "paragraph,hyperlink", allowTargetBlank: false, }, - }) as RTParagraphNode[]; + }) as RTParagraphNode[] - expect(notAllowedOutput.spans.length).toBeGreaterThanOrEqual(1); + expect(notAllowedOutput.spans.length).toBeGreaterThanOrEqual(1) expect( notAllowedOutput.spans.every( (span) => @@ -193,8 +194,8 @@ it('removes `target: "_blank"` from hyperlink spans when they are not allowed', span.data.link_type === LinkType.Web && !span.data.target, ), - ).toBe(true); -}); + ).toBe(true) +}) it('removes `target: "_blank"` from image nodes when they are not allowed', () => { const baseImageNode = { @@ -205,7 +206,7 @@ it('removes `target: "_blank"` from image nodes when they are not allowed', () = copyright: "", dimensions: { height: 100, width: 100 }, edit: { x: 0, y: 0, zoom: 1, background: "transparent" }, - } as const; + } as const const input: RichTextField = [ { @@ -220,7 +221,7 @@ it('removes `target: "_blank"` from image nodes when they are not allowed', () = target: "_blank", }, }, - ]; + ] const allowedOutput = filterRichTextField(input, { type: "StructuredText", @@ -228,9 +229,9 @@ it('removes `target: "_blank"` from image nodes when they are not allowed', () = multi: "image", allowTargetBlank: true, }, - }) as RTImageNode[]; + }) as RTImageNode[] - expect(allowedOutput.length).toBeGreaterThanOrEqual(1); + expect(allowedOutput.length).toBeGreaterThanOrEqual(1) expect( allowedOutput.every( (node) => @@ -238,7 +239,7 @@ it('removes `target: "_blank"` from image nodes when they are not allowed', () = node.linkTo.link_type === LinkType.Web && !node.linkTo.target, ), - ).toBe(false); + ).toBe(false) const notAllowedOutput = filterRichTextField(input, { type: "StructuredText", @@ -246,9 +247,9 @@ it('removes `target: "_blank"` from image nodes when they are not allowed', () = multi: "image", allowTargetBlank: false, }, - }) as RTImageNode[]; + }) as RTImageNode[] - expect(notAllowedOutput.length).toBeGreaterThanOrEqual(1); + expect(notAllowedOutput.length).toBeGreaterThanOrEqual(1) expect( notAllowedOutput.every( (node) => @@ -256,5 +257,5 @@ it('removes `target: "_blank"` from image nodes when they are not allowed', () = node.linkTo.link_type === LinkType.Web && !node.linkTo.target, ), - ).toBe(true); -}); + ).toBe(true) +}) diff --git a/test/richtext/asText.test.ts b/test/richtext/asText.test.ts index fcc842dd..a4bd087d 100644 --- a/test/richtext/asText.test.ts +++ b/test/richtext/asText.test.ts @@ -1,17 +1,17 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures" -import { asText } from "../../src/richtext"; +import { asText } from "../../src/richtext" it("returns a string representation of a rich text field value", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - expect(asText(richTextFixtures.en)).toMatchSnapshot(); -}); + expect(asText(richTextFixtures.en)).toMatchSnapshot() +}) it("allows for custom separator", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - expect(asText(richTextFixtures.en, "SEPARATOR")).toMatchSnapshot(); -}); + expect(asText(richTextFixtures.en, "SEPARATOR")).toMatchSnapshot() +}) diff --git a/test/richtext/asTree.test.ts b/test/richtext/asTree.test.ts index ad598869..f5dcc90f 100644 --- a/test/richtext/asTree.test.ts +++ b/test/richtext/asTree.test.ts @@ -1,24 +1,24 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures" -import { asTree } from "../../src/richtext"; +import { asTree } from "../../src/richtext" it("does not mutate the provided rich text field", () => { - const richTextFixturesUntouched = createRichTextFixtures(); - const richTextFixturesMaybeMutated = createRichTextFixtures(); + const richTextFixturesUntouched = createRichTextFixtures() + const richTextFixturesMaybeMutated = createRichTextFixtures() // We run it twice to ensure successive runs does not mutate the value. - asTree(richTextFixturesMaybeMutated.en); - asTree(richTextFixturesMaybeMutated.en); + asTree(richTextFixturesMaybeMutated.en) + asTree(richTextFixturesMaybeMutated.en) expect(richTextFixturesUntouched.en).toStrictEqual( richTextFixturesMaybeMutated.en, - ); -}); + ) +}) it("converts a rich text field value to a tree", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - expect(asTree(richTextFixtures.en)).toMatchSnapshot(); -}); + expect(asTree(richTextFixtures.en)).toMatchSnapshot() +}) diff --git a/test/richtext/composeSerializers.test.ts b/test/richtext/composeSerializers.test.ts index 3ba6f88f..06f7c235 100644 --- a/test/richtext/composeSerializers.test.ts +++ b/test/richtext/composeSerializers.test.ts @@ -1,60 +1,60 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures" -import { htmlRichTextMapSerializer } from "../__fixtures__/htmlRichTextMapSerializer"; +import { htmlRichTextMapSerializer } from "../__fixtures__/htmlRichTextMapSerializer" import { composeSerializers, serialize, wrapMapSerializer, -} from "../../src/richtext"; +} from "../../src/richtext" it("composes multiple serializers", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - const mapSerializer1 = { ...htmlRichTextMapSerializer }; - delete mapSerializer1.heading1; + const mapSerializer1 = { ...htmlRichTextMapSerializer } + delete mapSerializer1.heading1 - const mapSerializer2 = { heading1: htmlRichTextMapSerializer.heading1 }; + const mapSerializer2 = { heading1: htmlRichTextMapSerializer.heading1 } const serializer = composeSerializers( wrapMapSerializer(mapSerializer1), wrapMapSerializer(mapSerializer2), - ); + ) - const composedSerialization = serialize(richTextFixtures.en, serializer); + const composedSerialization = serialize(richTextFixtures.en, serializer) - expect(composedSerialization).toMatchSnapshot(); -}); + expect(composedSerialization).toMatchSnapshot() +}) it("ignores undefined serializers", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - const serializer = wrapMapSerializer(htmlRichTextMapSerializer); + const serializer = wrapMapSerializer(htmlRichTextMapSerializer) expect( serialize(richTextFixtures.en, composeSerializers(undefined, serializer)), - ).toStrictEqual(serialize(richTextFixtures.en, serializer)); -}); + ).toStrictEqual(serialize(richTextFixtures.en, serializer)) +}) it("composes serializers that do not support all node types", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - const mapSerializer1 = { ...htmlRichTextMapSerializer }; - delete mapSerializer1.heading1; - delete mapSerializer1.heading2; + const mapSerializer1 = { ...htmlRichTextMapSerializer } + delete mapSerializer1.heading1 + delete mapSerializer1.heading2 - const mapSerializer2 = { ...htmlRichTextMapSerializer }; - delete mapSerializer2.heading1; + const mapSerializer2 = { ...htmlRichTextMapSerializer } + delete mapSerializer2.heading1 // This serializer does not handle `heading1` nodes. const serializer = composeSerializers( wrapMapSerializer(mapSerializer1), wrapMapSerializer(mapSerializer2), - ); + ) - const composedSerialization = serialize(richTextFixtures.en, serializer); + const composedSerialization = serialize(richTextFixtures.en, serializer) - expect(composedSerialization).toMatchSnapshot(); -}); + expect(composedSerialization).toMatchSnapshot() +}) diff --git a/test/richtext/index.test-d.ts b/test/richtext/index.test-d.ts index 8e79c5ee..9c08631f 100644 --- a/test/richtext/index.test-d.ts +++ b/test/richtext/index.test-d.ts @@ -1,7 +1,7 @@ -import { expectTypeOf, it } from "vitest"; +import { expectTypeOf, it } from "vitest" -import * as lib from "../../src/richtext"; +import * as lib from "../../src/richtext" it("returns string", () => { - expectTypeOf(lib.asText).returns.toBeString(); -}); + expectTypeOf(lib.asText).returns.toBeString() +}) diff --git a/test/richtext/serialize.test.ts b/test/richtext/serialize.test.ts index 177e1bcc..4227e62f 100644 --- a/test/richtext/serialize.test.ts +++ b/test/richtext/serialize.test.ts @@ -1,51 +1,47 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures" -import { htmlRichTextFunctionSerializer } from "../__fixtures__/htmlRichTextFunctionSerializer"; -import { htmlRichTextMapSerializer } from "../__fixtures__/htmlRichTextMapSerializer"; +import { htmlRichTextFunctionSerializer } from "../__fixtures__/htmlRichTextFunctionSerializer" +import { htmlRichTextMapSerializer } from "../__fixtures__/htmlRichTextMapSerializer" -import { - Element, - RichTextFunctionSerializer, - serialize, - wrapMapSerializer, -} from "../../src/richtext"; +import type { RichTextFunctionSerializer } from "../../src/richtext" +import { Element, serialize, wrapMapSerializer } from "../../src/richtext" const serializeMacro = (richTextKey: keyof ReturnType) => () => { - const richTextFixtures = createRichTextFixtures(); - const richTextFixture = richTextFixtures[richTextKey]; + const richTextFixtures = createRichTextFixtures() + const richTextFixture = richTextFixtures[richTextKey] const functionSerialization = serialize( richTextFixture, htmlRichTextFunctionSerializer, - ); + ) const mapSerialization = serialize( richTextFixture, wrapMapSerializer(htmlRichTextMapSerializer), - ); + ) - expect(functionSerialization).toMatchSnapshot(); - expect(mapSerialization).toMatchSnapshot(); - }; + expect(functionSerialization).toMatchSnapshot() + expect(mapSerialization).toMatchSnapshot() + } it( "serializes a rich text field value using given serializers", serializeMacro("en"), -); +) -it("handles Chinese characters correctly", serializeMacro("cn")); +it("handles Chinese characters correctly", serializeMacro("cn")) -it("handles Korean characters correctly", serializeMacro("ko")); +it("handles Korean characters correctly", serializeMacro("ko")) -it("handles emoji characters correctly", serializeMacro("emoji")); +it("handles emoji characters correctly", serializeMacro("emoji")) // See: https://github.com/prismicio/prismic-client/issues/198 -it("handles overlapped styling correctly", serializeMacro("overlapped")); +it("handles overlapped styling correctly", serializeMacro("overlapped")) it("omits nullish serialized values from the result", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() // We are expecting only heading1 to be included in the serialized result. // Note that we are returning `null` for embed. This will be omitted just like @@ -59,16 +55,16 @@ it("omits nullish serialized values from the result", () => { ) => { switch (node.type) { case Element.heading1: { - return `

    ${text}

    `; + return `

    ${text}

    ` } case Element.embed: { - return null; + return null } } - }; + } - const serialization = serialize(richTextFixtures.en, serializer); + const serialization = serialize(richTextFixtures.en, serializer) - expect(serialization).toMatchSnapshot(); -}); + expect(serialization).toMatchSnapshot() +}) diff --git a/test/richtext/wrapMapSerializer.test.ts b/test/richtext/wrapMapSerializer.test.ts index 3c5831be..b3e705e9 100644 --- a/test/richtext/wrapMapSerializer.test.ts +++ b/test/richtext/wrapMapSerializer.test.ts @@ -1,25 +1,25 @@ -import { expect, it } from "vitest"; +import { expect, it } from "vitest" -import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures"; +import { createRichTextFixtures } from "../__testutils__/createRichTextFixtures" -import { htmlRichTextMapSerializer } from "../__fixtures__/htmlRichTextMapSerializer"; +import { htmlRichTextMapSerializer } from "../__fixtures__/htmlRichTextMapSerializer" -import { serialize, wrapMapSerializer } from "../../src/richtext"; +import { serialize, wrapMapSerializer } from "../../src/richtext" it("serializes a rich text field value using a given serializer map", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - const serializer = wrapMapSerializer(htmlRichTextMapSerializer); - const serialization = serialize(richTextFixtures.en, serializer); + const serializer = wrapMapSerializer(htmlRichTextMapSerializer) + const serialization = serialize(richTextFixtures.en, serializer) - expect(serialization).toMatchSnapshot(); -}); + expect(serialization).toMatchSnapshot() +}) it("returns `undefined` when serializer does not handle given tag", () => { - const richTextFixtures = createRichTextFixtures(); + const richTextFixtures = createRichTextFixtures() - const serializer = wrapMapSerializer({}); - const serialization = serialize(richTextFixtures.en, serializer); + const serializer = wrapMapSerializer({}) + const serialization = serialize(richTextFixtures.en, serializer) - expect(serialization.every((element) => element === undefined)).toBe(true); -}); + expect(serialization.every((element) => element === undefined)).toBe(true) +}) diff --git a/test/types/api-form.types.ts b/test/types/api-form.types.ts index ab9524e9..3d4ca4fe 100644 --- a/test/types/api-form.types.ts +++ b/test/types/api-form.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Form): true => { +;(value: prismic.Form): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ method: "GET", @@ -31,7 +31,7 @@ expectType({ default: "string", }, }, -}); +}) /** * `method` must be "GET". @@ -44,7 +44,7 @@ expectType({ name: "string", rel: "string", fields: {}, -}); +}) /** * Supports optional `name` and `rel` properties. @@ -54,4 +54,4 @@ expectType({ enctype: "string", action: "string", fields: {}, -}); +}) diff --git a/test/types/api-formField.types.ts b/test/types/api-formField.types.ts index a74ca404..e7c967f9 100644 --- a/test/types/api-formField.types.ts +++ b/test/types/api-formField.types.ts @@ -1,33 +1,33 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.FormField): true => { +;(value: prismic.FormField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: "String", multiple: true, default: "string", -}); +}) expectType({ type: "Integer", multiple: true, default: "string", -}); +}) /** * `type` must be "String" or "Integer". @@ -37,7 +37,7 @@ expectType({ type: "string", multiple: true, default: "string", -}); +}) /** * Supports optional `default` property. @@ -45,4 +45,4 @@ expectType({ expectType({ type: "String", multiple: true, -}); +}) diff --git a/test/types/api-language.types.ts b/test/types/api-language.types.ts index 2eda5c9b..c58beb45 100644 --- a/test/types/api-language.types.ts +++ b/test/types/api-language.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Language): true => { +;(value: prismic.Language): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", name: "string", -}); +}) diff --git a/test/types/api-query.types.ts b/test/types/api-query.types.ts index 29ea65ce..8e8a93c7 100644 --- a/test/types/api-query.types.ts +++ b/test/types/api-query.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Query): true => { +;(value: prismic.Query): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ page: 0, @@ -50,7 +50,7 @@ expectType({ data: {}, }, ], -}); +}) /** * Supports nullable `next_page` and `prev_page` properties. @@ -64,7 +64,7 @@ expectType({ next_page: null, prev_page: null, results: [], -}); +}) /** * Supports custom document type. @@ -72,7 +72,7 @@ expectType({ expectType< prismic.Query< prismic.PrismicDocument<{ - foo: prismic.BooleanField; + foo: prismic.BooleanField }> > >({ @@ -111,4 +111,4 @@ expectType< }, }, ], -}); +}) diff --git a/test/types/api-ref.types.ts b/test/types/api-ref.types.ts index 6d60b5bd..be5871e0 100644 --- a/test/types/api-ref.types.ts +++ b/test/types/api-ref.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Ref): true => { +;(value: prismic.Ref): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", @@ -24,7 +24,7 @@ expectType({ label: "string", isMasterRef: true, scheduledAt: "string", -}); +}) /** * Supports optional `scheduledAt` property. @@ -34,4 +34,4 @@ expectType({ ref: "string", label: "string", isMasterRef: true, -}); +}) diff --git a/test/types/api-release.types.ts b/test/types/api-release.types.ts index 8d345d03..90d690b1 100644 --- a/test/types/api-release.types.ts +++ b/test/types/api-release.types.ts @@ -1,8 +1,9 @@ -import { TypeEqual, expectType } from "ts-expect"; +import type { TypeEqual } from "ts-expect" +import { expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" /** * Equivelant to Ref. */ -expectType>(true); +expectType>(true) diff --git a/test/types/api-repository.types.ts b/test/types/api-repository.types.ts index 170bd173..24fd1794 100644 --- a/test/types/api-repository.types.ts +++ b/test/types/api-repository.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Repository): true => { +;(value: prismic.Repository): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ refs: [ @@ -56,4 +56,4 @@ expectType({ bookmarks: { foo: "string", }, -}); +}) diff --git a/test/types/api-tags.types.ts b/test/types/api-tags.types.ts index a1837487..0ea86c38 100644 --- a/test/types/api-tags.types.ts +++ b/test/types/api-tags.types.ts @@ -1,35 +1,35 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Tags): true => { +;(value: prismic.Tags): true => { if (!Array.isArray(value)) { - return expectNever(value); + return expectNever(value) } switch (typeof value[0]) { case "string": { - return true; + return true } default: { - return expectNever(value[0]); + return expectNever(value[0]) } } -}; +} -expectType(["string"]); +expectType(["string"]) /** * Supports empty lists. */ -expectType([]); +expectType([]) /** * Supports custom tag enum-like (string union). */ -expectType>(["foo", "bar"]); +expectType>(["foo", "bar"]) expectType>([ // @ts-expect-error - Only given tags are valid. "string", -]); +]) diff --git a/test/types/client.types.ts b/test/types/client.types.ts index bffa8f03..6ab5335d 100644 --- a/test/types/client.types.ts +++ b/test/types/client.types.ts @@ -1,437 +1,429 @@ -import { TypeEqual, expectType } from "ts-expect"; +import type { TypeEqual } from "ts-expect" +import { expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" // Default client -const defaultClient = prismic.createClient("example"); +const defaultClient = prismic.createClient("example") // Client Documents -type FooDocument = prismic.PrismicDocument, "foo">; -type BarDocument = prismic.PrismicDocument, "bar">; -type BazDocument = prismic.PrismicDocument, "baz">; -type Documents = FooDocument | BarDocument | BazDocument; +type FooDocument = prismic.PrismicDocument, "foo"> +type BarDocument = prismic.PrismicDocument, "bar"> +type BazDocument = prismic.PrismicDocument, "baz"> +type Documents = FooDocument | BarDocument | BazDocument -const documentsClient = prismic.createClient("example"); +const documentsClient = prismic.createClient("example") /** * Ensuring no full overlap between test types as we're testing for narrowing. */ -expectType>(false); +expectType>(false) expectType< TypeEqual, prismic.Query> ->(false); -expectType>(false); +>(false) +expectType>(false) -expectType>(false); +expectType>(false) expectType, prismic.Query>>( false, -); -expectType>(false); +) +expectType>(false) -expectType>(false); +expectType>(false) expectType< TypeEqual, prismic.Query> ->(false); -expectType>(false); +>(false) +expectType>(false) /** * get */ // Default -const defaultGet = await defaultClient.get({}); +const defaultGet = await defaultClient.get({}) expectType< TypeEqual> ->(true); +>(true) // Default with generic -const genericGet = await defaultClient.get({}); -expectType>>(true); +const genericGet = await defaultClient.get({}) +expectType>>(true) // Documents -const documentsGet = await documentsClient.get({}); -expectType>>(true); +const documentsGet = await documentsClient.get({}) +expectType>>(true) /** * getFirst */ // Default -const defaultGetFirst = await defaultClient.getFirst({}); -expectType>(true); +const defaultGetFirst = await defaultClient.getFirst({}) +expectType>(true) // Default with generic -const genericGetFirst = await defaultClient.getFirst({}); -expectType>(true); +const genericGetFirst = await defaultClient.getFirst({}) +expectType>(true) // Documents -const documentsGetFirst = await documentsClient.getFirst({}); -expectType>(true); +const documentsGetFirst = await documentsClient.getFirst({}) +expectType>(true) /** * dangerouslyGetAll */ // Default -const defaultDangerouslyGetAll = await defaultClient.dangerouslyGetAll({}); +const defaultDangerouslyGetAll = await defaultClient.dangerouslyGetAll({}) expectType< TypeEqual ->(true); +>(true) // Default with generic const genericDangerouslyGetAll = - await defaultClient.dangerouslyGetAll({}); -expectType>(true); + await defaultClient.dangerouslyGetAll({}) +expectType>(true) // Documents -const documentsDangerouslyGetAll = await documentsClient.dangerouslyGetAll({}); -expectType>(true); +const documentsDangerouslyGetAll = await documentsClient.dangerouslyGetAll({}) +expectType>(true) /** * getByID */ // Default -const defaultGetByID = await defaultClient.getByID("qux"); -expectType>(true); +const defaultGetByID = await defaultClient.getByID("qux") +expectType>(true) // With generic -const genericGetByID = await defaultClient.getByID("qux"); -expectType>(true); +const genericGetByID = await defaultClient.getByID("qux") +expectType>(true) // Documents -const documentsGetByID = await documentsClient.getByID("qux"); -expectType>(true); +const documentsGetByID = await documentsClient.getByID("qux") +expectType>(true) /** * getByIDs */ // Default -const defaultGetByIDs = await defaultClient.getByIDs(["qux"]); +const defaultGetByIDs = await defaultClient.getByIDs(["qux"]) expectType< TypeEqual> ->(true); +>(true) // With generic -const genericGetByIDs = await defaultClient.getByIDs(["qux"]); -expectType>>(true); +const genericGetByIDs = await defaultClient.getByIDs(["qux"]) +expectType>>(true) // Documents -const documentsGetByIDs = await documentsClient.getByIDs(["qux"]); -expectType>>(true); +const documentsGetByIDs = await documentsClient.getByIDs(["qux"]) +expectType>>(true) /** * getAllByIDs */ // Default -const defaultGetAllByIDs = await defaultClient.getAllByIDs(["qux"]); +const defaultGetAllByIDs = await defaultClient.getAllByIDs(["qux"]) expectType>( true, -); +) // With generic -const genericGetAllByIDs = await defaultClient.getAllByIDs([ - "qux", -]); -expectType>(true); +const genericGetAllByIDs = await defaultClient.getAllByIDs(["qux"]) +expectType>(true) // Documents -const documentsGetAllByIDs = await documentsClient.getAllByIDs(["qux"]); -expectType>(true); +const documentsGetAllByIDs = await documentsClient.getAllByIDs(["qux"]) +expectType>(true) /** * getByUID */ // Default -const defaultGetByUID = await defaultClient.getByUID("foo", "qux"); -expectType>(true); +const defaultGetByUID = await defaultClient.getByUID("foo", "qux") +expectType>(true) // With generic -const genericGetByUID = await defaultClient.getByUID("foo", "qux"); -expectType>(true); +const genericGetByUID = await defaultClient.getByUID("foo", "qux") +expectType>(true) // Documents (known) -const documentsGetByUID = await documentsClient.getByUID("foo", "qux"); -expectType>(true); +const documentsGetByUID = await documentsClient.getByUID("foo", "qux") +expectType>(true) // Documents (unknown) const documentsGetByUIDUnknown = await documentsClient.getByUID( // @ts-expect-error - Unknown document type "unknown", "qux", -); -expectType>(true); +) +expectType>(true) /** * getByUIDs */ // Default -const defaultGetByUIDs = await defaultClient.getByUIDs("foo", ["qux"]); +const defaultGetByUIDs = await defaultClient.getByUIDs("foo", ["qux"]) expectType< TypeEqual> ->(true); +>(true) // With generic const genericGetByUIDs = await defaultClient.getByUIDs("foo", [ "qux", -]); -expectType>>( - true, -); +]) +expectType>>(true) // Documents (known) -const documentsGetByUIDs = await documentsClient.getByUIDs("foo", ["qux"]); +const documentsGetByUIDs = await documentsClient.getByUIDs("foo", ["qux"]) expectType>>( true, -); +) // Documents (known) const documentsGetByUIDsUnknown = await documentsClient.getByUIDs( // @ts-expect-error - Unknown document type "unknown", ["qux"], -); +) expectType< TypeEqual> ->(true); +>(true) /** * getAllByUIDs */ // Default -const defaultGetAllByUIDs = await defaultClient.getAllByUIDs("foo", ["qux"]); +const defaultGetAllByUIDs = await defaultClient.getAllByUIDs("foo", ["qux"]) expectType>( true, -); +) // With generic const genericGetAllByUIDs = await defaultClient.getAllByUIDs( "foo", ["qux"], -); -expectType>(true); +) +expectType>(true) // Documents (known) -const documentsGetAllByUIDs = await documentsClient.getAllByUIDs("foo", [ - "qux", -]); -expectType>(true); +const documentsGetAllByUIDs = await documentsClient.getAllByUIDs("foo", ["qux"]) +expectType>(true) // Documents (known) const documentsGetAllByUIDsUnknown = await documentsClient.getAllByUIDs( // @ts-expect-error - Unknown document type "unknown", ["qux"], -); -expectType>(true); +) +expectType>(true) /** * getSingle */ // Default -const defaultGetSingle = await defaultClient.getSingle("foo"); -expectType>(true); +const defaultGetSingle = await defaultClient.getSingle("foo") +expectType>(true) // With generic -const genericGetSingle = await defaultClient.getSingle("foo"); -expectType>(true); +const genericGetSingle = await defaultClient.getSingle("foo") +expectType>(true) // Documents (known) -const documentsGetSingle = await documentsClient.getSingle("foo"); -expectType>(true); +const documentsGetSingle = await documentsClient.getSingle("foo") +expectType>(true) // Documents (unknown) const documentsGetSingleUnknown = await documentsClient.getSingle( // @ts-expect-error - Unknown document type "unknown", -); -expectType>(true); +) +expectType>(true) /** * getByType */ // Default -const defaultGetByType = await defaultClient.getByType("foo"); +const defaultGetByType = await defaultClient.getByType("foo") expectType< TypeEqual> ->(true); +>(true) // With generic -const genericGetByType = await defaultClient.getByType("foo"); -expectType>>( - true, -); +const genericGetByType = await defaultClient.getByType("foo") +expectType>>(true) // Documents (known) -const documentsGetByType = await documentsClient.getByType("foo"); +const documentsGetByType = await documentsClient.getByType("foo") expectType>>( true, -); +) // Documents (unknown) const documentsGetByTypeUnknown = await documentsClient.getByType( // @ts-expect-error - Unknown document type "unknown", -); +) expectType< TypeEqual> ->(true); +>(true) /** * getAllByType */ // Default -const defaultGetAllByType = await defaultClient.getAllByType("foo"); +const defaultGetAllByType = await defaultClient.getAllByType("foo") expectType>( true, -); +) // With generic -const genericGetAllByType = - await defaultClient.getAllByType("foo"); -expectType>(true); +const genericGetAllByType = await defaultClient.getAllByType("foo") +expectType>(true) // Documents (known) -const documentsGetAllByType = await documentsClient.getAllByType("foo"); -expectType>(true); +const documentsGetAllByType = await documentsClient.getAllByType("foo") +expectType>(true) // Documents (unknown) const documentsGetAllByTypeUnknown = await documentsClient.getAllByType( // @ts-expect-error - Unknown document type "unknown", -); -expectType>(true); +) +expectType>(true) /** * getByTag */ // Default -const defaultGetByTag = await defaultClient.getByTag("qux"); +const defaultGetByTag = await defaultClient.getByTag("qux") expectType< TypeEqual> ->(true); +>(true) // With generic -const genericGetByTag = await defaultClient.getByTag("qux"); -expectType>>(true); +const genericGetByTag = await defaultClient.getByTag("qux") +expectType>>(true) // Documents -const documentsGetByTag = await documentsClient.getByTag("qux"); -expectType>>(true); +const documentsGetByTag = await documentsClient.getByTag("qux") +expectType>>(true) /** * getAllByTag */ // Default -const defaultGetAllByTag = await defaultClient.getAllByTag("qux"); +const defaultGetAllByTag = await defaultClient.getAllByTag("qux") expectType>( true, -); +) // With generic -const genericGetAllByTag = await defaultClient.getAllByTag("qux"); -expectType>(true); +const genericGetAllByTag = await defaultClient.getAllByTag("qux") +expectType>(true) // Documents -const documentsGetAllByTag = await documentsClient.getAllByTag("qux"); -expectType>(true); +const documentsGetAllByTag = await documentsClient.getAllByTag("qux") +expectType>(true) /** * getByEveryTag */ // Default -const defaultGetByEveryTag = await defaultClient.getByEveryTag(["qux"]); +const defaultGetByEveryTag = await defaultClient.getByEveryTag(["qux"]) expectType< TypeEqual> ->(true); +>(true) // With generic const genericGetByEveryTag = await defaultClient.getByEveryTag([ "qux", -]); +]) expectType>>( true, -); +) // Documents -const documentsGetByEveryTag = await documentsClient.getByEveryTag(["qux"]); +const documentsGetByEveryTag = await documentsClient.getByEveryTag(["qux"]) expectType>>( true, -); +) /** * getAllByEveryTag */ // Default -const defaultGetAllByEveryTag = await defaultClient.getAllByEveryTag(["qux"]); +const defaultGetAllByEveryTag = await defaultClient.getAllByEveryTag(["qux"]) expectType< TypeEqual ->(true); +>(true) // With generic const genericGetAllByEveryTag = - await defaultClient.getAllByEveryTag(["qux"]); -expectType>(true); + await defaultClient.getAllByEveryTag(["qux"]) +expectType>(true) // Documents const documentsGetAllByEveryTag = await documentsClient.getAllByEveryTag([ "qux", -]); -expectType>(true); +]) +expectType>(true) /** * getBySomeTags */ // Default -const defaultGetBySomeTags = await defaultClient.getBySomeTags(["qux"]); +const defaultGetBySomeTags = await defaultClient.getBySomeTags(["qux"]) expectType< TypeEqual> ->(true); +>(true) // With generic const genericGetBySomeTags = await defaultClient.getBySomeTags([ "qux", -]); +]) expectType>>( true, -); +) // Documents -const documentsGetBySomeTags = await documentsClient.getBySomeTags(["qux"]); +const documentsGetBySomeTags = await documentsClient.getBySomeTags(["qux"]) expectType>>( true, -); +) /** * getAllBySomeTags */ // Default -const defaultGetAllBySomeTags = await defaultClient.getAllBySomeTags(["qux"]); +const defaultGetAllBySomeTags = await defaultClient.getAllBySomeTags(["qux"]) expectType< TypeEqual ->(true); +>(true) // With generic const genericGetAllBySomeTags = - await defaultClient.getAllBySomeTags(["qux"]); -expectType>(true); + await defaultClient.getAllBySomeTags(["qux"]) +expectType>(true) // Documents const documentsGetAllBySomeTags = await documentsClient.getAllBySomeTags([ "qux", -]); -expectType>(true); +]) +expectType>(true) diff --git a/test/types/customType-boolean.types.ts b/test/types/customType-boolean.types.ts index de1775b2..6e0f1f80 100644 --- a/test/types/customType-boolean.types.ts +++ b/test/types/customType-boolean.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelBooleanField): true => { +;(value: prismic.CustomTypeModelBooleanField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Boolean, config: { label: "string", }, -}); +}) /** * Does not support a placeholder. @@ -37,18 +37,18 @@ expectType({ // @ts-expect-error - Does not support a placeholder. placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.BooleanField, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelBooleanField, -); +) diff --git a/test/types/customType-color.types.ts b/test/types/customType-color.types.ts index 39a581c5..236e18ea 100644 --- a/test/types/customType-color.types.ts +++ b/test/types/customType-color.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelColorField): true => { +;(value: prismic.CustomTypeModelColorField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Color, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,14 +36,14 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.Color); +expectType({} as prismicTICustomTypes.Color) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelColorField); +expectType({} as prismic.CustomTypeModelColorField) diff --git a/test/types/customType-contentRelationship.types.ts b/test/types/customType-contentRelationship.types.ts index bafb2e4b..2789c2be 100644 --- a/test/types/customType-contentRelationship.types.ts +++ b/test/types/customType-contentRelationship.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelContentRelationshipField): true => { +;(value: prismic.CustomTypeModelContentRelationshipField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Link, @@ -26,7 +26,7 @@ expectType({ label: "string", select: prismic.CustomTypeModelLinkSelectType.Document, }, -}); +}) /** * Supports optional placeholder. @@ -38,7 +38,7 @@ expectType({ placeholder: "string", select: prismic.CustomTypeModelLinkSelectType.Document, }, -}); +}) /** * Supports optional `customtypes` property. @@ -50,7 +50,7 @@ expectType({ select: prismic.CustomTypeModelLinkSelectType.Document, customtypes: ["string"], }, -}); +}) /** * Supports custom `customtypes` values. @@ -66,7 +66,7 @@ expectType>({ "bar", ], }, -}); +}) /** * Supports optional `tags` property. @@ -78,7 +78,7 @@ expectType({ select: prismic.CustomTypeModelLinkSelectType.Document, tags: ["string"], }, -}); +}) /** * Supports custom `tags` values. @@ -94,7 +94,7 @@ expectType>({ "bar", ], }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` @@ -105,13 +105,13 @@ expectType( // to match a Content Relationship field; // `@prismicio/types-internal` does not contain a Content // Relationship-specific type. - config?: { select: "document" }; + config?: { select: "document" } }, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelContentRelationshipField, -); +) diff --git a/test/types/customType-date.types.ts b/test/types/customType-date.types.ts index 466c4daa..9e3876de 100644 --- a/test/types/customType-date.types.ts +++ b/test/types/customType-date.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelDateField): true => { +;(value: prismic.CustomTypeModelDateField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Date, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,14 +36,14 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.Date); +expectType({} as prismicTICustomTypes.Date) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelDateField); +expectType({} as prismic.CustomTypeModelDateField) diff --git a/test/types/customType-embed.types.ts b/test/types/customType-embed.types.ts index 165033c4..40202e37 100644 --- a/test/types/customType-embed.types.ts +++ b/test/types/customType-embed.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelEmbedField): true => { +;(value: prismic.CustomTypeModelEmbedField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Embed, config: { label: "string", }, -}); +}) /** * Supports optional placeholder @@ -36,14 +36,14 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.Embed); +expectType({} as prismicTICustomTypes.Embed) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelEmbedField); +expectType({} as prismic.CustomTypeModelEmbedField) diff --git a/test/types/customType-geoPoint.types.ts b/test/types/customType-geoPoint.types.ts index a5754af5..bb51cd84 100644 --- a/test/types/customType-geoPoint.types.ts +++ b/test/types/customType-geoPoint.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelGeoPointField): true => { +;(value: prismic.CustomTypeModelGeoPointField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.GeoPoint, config: { label: "string", }, -}); +}) /** * Does not support a placeholder. @@ -37,18 +37,18 @@ expectType({ // @ts-expect-error - Does not support a placeholder. placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.GeoPoint, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelGeoPointField, -); +) diff --git a/test/types/customType-group.types.ts b/test/types/customType-group.types.ts index b7974252..a5a58b7f 100644 --- a/test/types/customType-group.types.ts +++ b/test/types/customType-group.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelGroupField): true => { +;(value: prismic.CustomTypeModelGroupField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Group, @@ -33,7 +33,7 @@ expectType({ }, }, }, -}); +}) /** * Does not support a placeholder. @@ -46,14 +46,14 @@ expectType({ placeholder: "string", fields: {}, }, -}); +}) /** * Supports custom fields. */ expectType< prismic.CustomTypeModelGroupField<{ - foo: prismic.CustomTypeModelBooleanField; + foo: prismic.CustomTypeModelBooleanField }> >({ type: prismic.CustomTypeModelFieldType.Group, @@ -75,7 +75,7 @@ expectType< }, }, }, -}); +}) /** * Supports nested groups. @@ -83,8 +83,8 @@ expectType< expectType< prismic.CustomTypeModelGroupField<{ foo: prismic.CustomTypeModelNestedGroupField<{ - bar: prismic.CustomTypeModelBooleanField; - }>; + bar: prismic.CustomTypeModelBooleanField + }> }> >({ type: prismic.CustomTypeModelFieldType.Group, @@ -107,14 +107,14 @@ expectType< }, }, }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.Group); +expectType({} as prismicTICustomTypes.Group) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelGroupField); +expectType({} as prismic.CustomTypeModelGroupField) diff --git a/test/types/customType-image.types.ts b/test/types/customType-image.types.ts index c1fe11fd..0429dc18 100644 --- a/test/types/customType-image.types.ts +++ b/test/types/customType-image.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelImageField): true => { +;(value: prismic.CustomTypeModelImageField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Image, @@ -33,7 +33,7 @@ expectType({ }, ], }, -}); +}) /** * Does not support a placeholder. @@ -56,7 +56,7 @@ expectType({ }, ], }, -}); +}) /** * Supports optional constraint. @@ -71,7 +71,7 @@ expectType({ }, thumbnails: [], }, -}); +}) /** * Supports custom thumbnail names. @@ -95,7 +95,7 @@ expectType>({ }, ], }, -}); +}) /** * Constraint supports nullable width and height to represent no constraint. @@ -103,15 +103,15 @@ expectType>({ expectType({ width: null, height: null, -}); +}) expectType({ width: 1, height: null, -}); +}) expectType({ width: null, height: 1, -}); +}) /** * Thumbnail supports configurable name. @@ -120,20 +120,20 @@ expectType>({ name: "Foo", width: null, height: null, -}); +}) expectType>({ // @ts-expect-error - Name must match the given name. name: "string", width: null, height: null, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.Image); +expectType({} as prismicTICustomTypes.Image) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelImageField); +expectType({} as prismic.CustomTypeModelImageField) diff --git a/test/types/customType-integration.types.ts b/test/types/customType-integration.types.ts index 27c235a9..ad1f95fd 100644 --- a/test/types/customType-integration.types.ts +++ b/test/types/customType-integration.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelIntegrationField): true => { +;(value: prismic.CustomTypeModelIntegrationField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Integration, @@ -26,7 +26,7 @@ expectType({ label: "string", catalog: "string", }, -}); +}) /** * Supports optional placeholder. @@ -38,18 +38,18 @@ expectType({ placeholder: "string", catalog: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.IntegrationField, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelIntegrationField, -); +) diff --git a/test/types/customType-keyText.types.ts b/test/types/customType-keyText.types.ts index 3a1e1421..f52dd1b3 100644 --- a/test/types/customType-keyText.types.ts +++ b/test/types/customType-keyText.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelKeyTextField): true => { +;(value: prismic.CustomTypeModelKeyTextField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Text, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,18 +36,14 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType( - {} as prismicTICustomTypes.Text, -); +expectType({} as prismicTICustomTypes.Text) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType( - {} as prismic.CustomTypeModelKeyTextField, -); +expectType({} as prismic.CustomTypeModelKeyTextField) diff --git a/test/types/customType-link.types.ts b/test/types/customType-link.types.ts index 67194c47..a44fcd91 100644 --- a/test/types/customType-link.types.ts +++ b/test/types/customType-link.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelLinkField): true => { +;(value: prismic.CustomTypeModelLinkField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Link, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,7 +36,7 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * Supports optional null `select` option. @@ -47,7 +47,7 @@ expectType({ label: "string", select: null, }, -}); +}) /** * Supports optional allowTargetBlank. @@ -58,14 +58,14 @@ expectType({ label: "string", allowTargetBlank: true, }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.Link); +expectType({} as prismicTICustomTypes.Link) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelLinkField); +expectType({} as prismic.CustomTypeModelLinkField) diff --git a/test/types/customType-linkToMedia.types.ts b/test/types/customType-linkToMedia.types.ts index 8f8681c8..dae8e2af 100644 --- a/test/types/customType-linkToMedia.types.ts +++ b/test/types/customType-linkToMedia.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelLinkToMediaField): true => { +;(value: prismic.CustomTypeModelLinkToMediaField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Link, @@ -26,7 +26,7 @@ expectType({ label: "string", select: prismic.CustomTypeModelLinkSelectType.Media, }, -}); +}) /** * Supports optional placeholder. @@ -38,7 +38,7 @@ expectType({ placeholder: "string", select: prismic.CustomTypeModelLinkSelectType.Media, }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` @@ -48,13 +48,13 @@ expectType( // We must manually narrow `@prismicio/types-internal`'s type // to match a link to media field; `@prismicio/types-internal` // does not contain a link to media-specific type. - config?: { select: "media" }; + config?: { select: "media" } }, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelLinkToMediaField, -); +) diff --git a/test/types/customType-number.types.ts b/test/types/customType-number.types.ts index 3de89057..3c796d3e 100644 --- a/test/types/customType-number.types.ts +++ b/test/types/customType-number.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelNumberField): true => { +;(value: prismic.CustomTypeModelNumberField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Number, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,18 +36,18 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.Number, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelNumberField, -); +) diff --git a/test/types/customType-richText.types.ts b/test/types/customType-richText.types.ts index fbd342c3..41bbf64e 100644 --- a/test/types/customType-richText.types.ts +++ b/test/types/customType-richText.types.ts @@ -1,24 +1,25 @@ -import { TypeOf, expectNever, expectType } from "ts-expect"; +import type { TypeOf } from "ts-expect" +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelRichTextField): true => { +;(value: prismic.CustomTypeModelRichTextField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * Supports multi block fields. @@ -28,14 +29,14 @@ expectType< prismic.CustomTypeModelRichTextField, prismic.CustomTypeModelRichTextMultiField > ->(true); +>(true) expectType({ type: prismic.CustomTypeModelFieldType.StructuredText, config: { label: "string", multi: "string", }, -}); +}) /** * Supports single block fields. @@ -45,14 +46,14 @@ expectType< prismic.CustomTypeModelRichTextField, prismic.CustomTypeModelRichTextSingleField > ->(true); +>(true) expectType({ type: prismic.CustomTypeModelFieldType.StructuredText, config: { label: "string", single: "string", }, -}); +}) /** * Supports optional placeholder. @@ -64,7 +65,7 @@ expectType({ placeholder: "string", multi: "string", }, -}); +}) /** * Supports optional allowTargetBlank. @@ -76,18 +77,18 @@ expectType({ multi: "string", allowTargetBlank: true, }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.RichText, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelRichTextField, -); +) diff --git a/test/types/customType-select.types.ts b/test/types/customType-select.types.ts index 820bba65..05d31480 100644 --- a/test/types/customType-select.types.ts +++ b/test/types/customType-select.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelSelectField): true => { +;(value: prismic.CustomTypeModelSelectField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Select, @@ -26,7 +26,7 @@ expectType({ label: "string", options: ["string"], }, -}); +}) /** * Supports optional placeholder. @@ -38,7 +38,7 @@ expectType({ placeholder: "string", options: ["string"], }, -}); +}) /** * Supports optional default value. @@ -51,7 +51,7 @@ expectType({ options: ["string"], default_value: "string", }, -}); +}) /** * Supports custom options type. @@ -67,7 +67,7 @@ expectType>({ "bar", ], }, -}); +}) /** * Supports custom default value type. @@ -80,7 +80,7 @@ expectType>({ options: ["string"], default_value: "foo", }, -}); +}) /** * Default value must be one of the given options. @@ -93,7 +93,7 @@ expectType>({ options: ["foo"], default_value: "foo", }, -}); +}) expectType>({ type: prismic.CustomTypeModelFieldType.Select, config: { @@ -103,18 +103,18 @@ expectType>({ // @ts-expect-error - Default value must be one of the given options. default_value: "bar", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.Select, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelSelectField, -); +) diff --git a/test/types/customType-sharedSlice.types.ts b/test/types/customType-sharedSlice.types.ts index 3fdfcced..23e5e793 100644 --- a/test/types/customType-sharedSlice.types.ts +++ b/test/types/customType-sharedSlice.types.ts @@ -1,39 +1,39 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelSharedSlice): true => { +;(value: prismic.CustomTypeModelSharedSlice): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelSliceType.SharedSlice, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.SharedSliceRef, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelSharedSlice, -); +) diff --git a/test/types/customType-sharedSliceModel.types.ts b/test/types/customType-sharedSliceModel.types.ts index c0b545d8..746ccd6f 100644 --- a/test/types/customType-sharedSliceModel.types.ts +++ b/test/types/customType-sharedSliceModel.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.SharedSliceModel): true => { +;(value: prismic.SharedSliceModel): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelSliceType.SharedSlice, @@ -51,7 +51,7 @@ expectType({ imageUrl: "string", }, ], -}); +}) /** * Supports custom ID. @@ -62,7 +62,7 @@ expectType>({ name: "string", description: "string", variations: [], -}); +}) expectType>({ type: prismic.CustomTypeModelSliceType.SharedSlice, // @ts-expect-error - Slice ID must match the given ID. @@ -70,7 +70,7 @@ expectType>({ name: "string", description: "string", variations: [], -}); +}) /** * Supports custom variations. @@ -105,14 +105,14 @@ expectType< imageUrl: "string", }, ], -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.SharedSlice); +expectType({} as prismicTICustomTypes.SharedSlice) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.SharedSliceModel); +expectType({} as prismic.SharedSliceModel) diff --git a/test/types/customType-sharedSliceModelVariation.types.ts b/test/types/customType-sharedSliceModelVariation.types.ts index 2ea86aa8..24acff99 100644 --- a/test/types/customType-sharedSliceModelVariation.types.ts +++ b/test/types/customType-sharedSliceModelVariation.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.SharedSliceModelVariation): true => { +;(value: prismic.SharedSliceModelVariation): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", @@ -43,7 +43,7 @@ expectType({ }, }, imageUrl: "string", -}); +}) /** * Supports custom ID. @@ -57,7 +57,7 @@ expectType>({ primary: {}, items: {}, imageUrl: "string", -}); +}) expectType>({ // @ts-expect-error - Slice ID must match the given ID. id: "string", @@ -68,7 +68,7 @@ expectType>({ primary: {}, items: {}, imageUrl: "string", -}); +}) /** * Supports custom primary fields. @@ -77,10 +77,10 @@ expectType< prismic.SharedSliceModelVariation< string, { - foo: prismic.CustomTypeModelBooleanField; + foo: prismic.CustomTypeModelBooleanField bar: prismic.CustomTypeModelGroupField<{ - baz: prismic.CustomTypeModelBooleanField; - }>; + baz: prismic.CustomTypeModelBooleanField + }> } > >({ @@ -120,7 +120,7 @@ expectType< }, items: {}, imageUrl: "string", -}); +}) /** * Supports custom items fields. @@ -154,7 +154,7 @@ expectType< }, }, imageUrl: "string", -}); +}) /** * Does not support groups in items section. @@ -176,18 +176,18 @@ expectType< // @ts-expect-error - We don't care about the actual value. items: {}, imageUrl: "string", -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.Variation, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.SharedSliceModelVariation, -); +) diff --git a/test/types/customType-slice.types.ts b/test/types/customType-slice.types.ts index dd1be3cf..057dcddc 100644 --- a/test/types/customType-slice.types.ts +++ b/test/types/customType-slice.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelSlice): true => { +;(value: prismic.CustomTypeModelSlice): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelSliceType.Slice, @@ -42,7 +42,7 @@ expectType({ }, }, }, -}); +}) /** * Supports custom non-repeat fields. @@ -71,7 +71,7 @@ expectType< }, }, repeat: {}, -}); +}) /** * Supports custom repeat fields. @@ -103,18 +103,18 @@ expectType< }, }, }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.CompositeSlice, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelSlice, -); +) diff --git a/test/types/customType-sliceZone.types.ts b/test/types/customType-sliceZone.types.ts index 610c46e0..d58bc892 100644 --- a/test/types/customType-sliceZone.types.ts +++ b/test/types/customType-sliceZone.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelSliceZoneField): true => { +;(value: prismic.CustomTypeModelSliceZoneField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Slices, @@ -58,15 +58,15 @@ expectType({ }, }, }, -}); +}) /** * Supports custom Slice types. */ expectType< prismic.CustomTypeModelSliceZoneField<{ - foo: prismic.CustomTypeModelSlice; - bar: prismic.CustomTypeModelSharedSlice; + foo: prismic.CustomTypeModelSlice + bar: prismic.CustomTypeModelSharedSlice }> >({ type: prismic.CustomTypeModelFieldType.Slices, @@ -88,18 +88,18 @@ expectType< }, }, }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.DynamicSlices, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelSliceZoneField, -); +) diff --git a/test/types/customType-timestamp.types.ts b/test/types/customType-timestamp.types.ts index 18f79f08..8860bb65 100644 --- a/test/types/customType-timestamp.types.ts +++ b/test/types/customType-timestamp.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelTimestampField): true => { +;(value: prismic.CustomTypeModelTimestampField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.Timestamp, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,18 +36,18 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.Timestamp, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelTimestampField, -); +) diff --git a/test/types/customType-title.types.ts b/test/types/customType-title.types.ts index ce98ae79..23a1c2ba 100644 --- a/test/types/customType-title.types.ts +++ b/test/types/customType-title.types.ts @@ -1,24 +1,24 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelTitleField): true => { +;(value: prismic.CustomTypeModelTitleField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.StructuredText, @@ -26,7 +26,7 @@ expectType({ label: "string", single: "string", }, -}); +}) /** * Supports optional placeholder. @@ -38,18 +38,18 @@ expectType({ placeholder: "string", single: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ expectType( {} as prismicTICustomTypes.RichText, -); +) /** * `@prismicio/types-internal` extends `@prismicio/types` */ expectType( {} as prismic.CustomTypeModelTitleField, -); +) diff --git a/test/types/customType-uid.types.ts b/test/types/customType-uid.types.ts index f9b5d27c..febd07b4 100644 --- a/test/types/customType-uid.types.ts +++ b/test/types/customType-uid.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.CustomTypeModelUIDField): true => { +;(value: prismic.CustomTypeModelUIDField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: prismic.CustomTypeModelFieldType.UID, config: { label: "string", }, -}); +}) /** * Supports optional placeholder. @@ -36,14 +36,14 @@ expectType({ label: "string", placeholder: "string", }, -}); +}) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.UID); +expectType({} as prismicTICustomTypes.UID) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModelUIDField); +expectType({} as prismic.CustomTypeModelUIDField) diff --git a/test/types/customType.types.ts b/test/types/customType.types.ts index 065297f8..29283621 100644 --- a/test/types/customType.types.ts +++ b/test/types/customType.types.ts @@ -1,27 +1,28 @@ -import { TypeOf, expectNever, expectType } from "ts-expect"; +import type { TypeOf } from "ts-expect" +import { expectNever, expectType } from "ts-expect" -import * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes"; - -import * as prismic from "../../src"; +import type * as prismicTICustomTypes from "@prismicio/types-internal/lib/customtypes" +import * as prismic from "../../src" /** * CustomTypeModel */ -(value: prismic.CustomTypeModel): true => { + +;(value: prismic.CustomTypeModel): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", label: "string", @@ -37,7 +38,7 @@ expectType({ }, }, status: true, -}); +}) expectType>({ id: "foo", label: "string", @@ -53,7 +54,7 @@ expectType>({ }, }, status: true, -}); +}) expectType>({ // @ts-expect-error - ID must match the given type. id: "string", @@ -70,14 +71,14 @@ expectType>({ }, }, status: true, -}); +}) expectType< prismic.CustomTypeModel< string, { Foo: { - foo: prismic.CustomTypeModelBooleanField; - }; + foo: prismic.CustomTypeModelBooleanField + } } > >({ @@ -104,26 +105,26 @@ expectType< }, }, status: true, -}); +}) /** * CustomTypeModelDefinition */ -(value: prismic.CustomTypeModelDefinition): true => { +;(value: prismic.CustomTypeModelDefinition): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ Foo: { foo: { @@ -133,7 +134,7 @@ expectType({ }, }, }, -}); +}) expectType>({ Foo: { foo: { @@ -152,26 +153,26 @@ expectType>({ }, }, }, -}); +}) /** * CustomTypeModelTab */ -(value: prismic.CustomTypeModelTab): true => { +;(value: prismic.CustomTypeModelTab): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ foo: { type: prismic.CustomTypeModelFieldType.Boolean, @@ -179,7 +180,7 @@ expectType({ label: "string", }, }, -}); +}) expectType< prismic.CustomTypeModelTab<{ foo: prismic.CustomTypeModelBooleanField }> >({ @@ -196,7 +197,7 @@ expectType< label: "string", }, }, -}); +}) /** * CustomTypeModelFieldForGroup supports any field compatible with a Group. @@ -206,133 +207,133 @@ expectType< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelBooleanField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelColorField > ->(true); +>(true) expectType< TypeOf ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelEmbedField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelGeoPointField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelImageField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelIntegrationField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelKeyTextField > ->(true); +>(true) expectType< TypeOf ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelLinkToMediaField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelNestedGroupField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelNumberField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelRichTextField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelSelectField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelTimestampField > ->(true); +>(true) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelTitleField > ->(true); +>(true) /** * CustomTypeModelFieldForGroup excludes any fields not compatible with a Group. */ expectType< TypeOf ->(false); +>(false) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelSliceZoneField > ->(false); +>(false) expectType< TypeOf< prismic.CustomTypeModelFieldForGroup, prismic.CustomTypeModelGroupField > ->(false); +>(false) /** * CustomTypeModelField includes any field. */ expectType< TypeOf ->(true); +>(true) expectType< TypeOf ->(true); +>(true) expectType< TypeOf ->(true); +>(true) expectType< TypeOf ->(true); +>(true) /** * `@prismicio/types` extends `@prismicio/types-internal` */ -expectType({} as prismicTICustomTypes.CustomType); +expectType({} as prismicTICustomTypes.CustomType) /** * `@prismicio/types-internal` extends `@prismicio/types` */ -expectType({} as prismic.CustomTypeModel); +expectType({} as prismic.CustomTypeModel) diff --git a/test/types/document-alternativeLanguage.types.ts b/test/types/document-alternativeLanguage.types.ts index 66996b45..685b3fdc 100644 --- a/test/types/document-alternativeLanguage.types.ts +++ b/test/types/document-alternativeLanguage.types.ts @@ -1,29 +1,29 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.AlternateLanguage): true => { +;(value: prismic.AlternateLanguage): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", uid: "string", type: "string", lang: "string", -}); +}) /** * Supports optional UID. @@ -32,7 +32,7 @@ expectType({ id: "string", type: "string", lang: "string", -}); +}) /** * Supports custom type. @@ -41,13 +41,13 @@ expectType>({ id: "string", type: "foo", lang: "string", -}); +}) expectType>({ id: "string", // @ts-expect-error - Document type must match the given type. type: "string", lang: "string", -}); +}) /** * Supports custom language. @@ -56,10 +56,10 @@ expectType>({ id: "string", type: "string", lang: "fr-fr", -}); +}) expectType>({ id: "string", type: "string", // @ts-expect-error - Document lang must match the given language. lang: "string", -}); +}) diff --git a/test/types/document-prismicDocument.types.ts b/test/types/document-prismicDocument.types.ts index fa5b8621..8bac1777 100644 --- a/test/types/document-prismicDocument.types.ts +++ b/test/types/document-prismicDocument.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.PrismicDocument): true => { +;(value: prismic.PrismicDocument): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", @@ -39,7 +39,7 @@ expectType({ }, ], data: {}, -}); +}) /** * Supports nullable UID and URL. @@ -58,7 +58,7 @@ expectType({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports custom data interface. @@ -81,15 +81,15 @@ expectType>({ // @ts-expect-error - Only given fields are valid. bar: false, }, -}); +}) /** * Custom data interface supports Group and Slice Zone fields. */ expectType< prismic.PrismicDocument<{ - group: prismic.GroupField; - sliceZone: prismic.SliceZone; + group: prismic.GroupField + sliceZone: prismic.SliceZone }> >({ id: "string", @@ -108,7 +108,7 @@ expectType< group: [], sliceZone: [], }, -}); +}) /** * Supports custom type. @@ -127,7 +127,7 @@ expectType, "foo">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) expectType, "foo">>({ id: "string", uid: "string", @@ -143,7 +143,7 @@ expectType, "foo">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports custom language. @@ -162,7 +162,7 @@ expectType, string, "fr-fr">>({ lang: "fr-fr", alternate_languages: [], data: {}, -}); +}) expectType, string, "fr-fr">>({ id: "string", uid: "string", @@ -178,4 +178,4 @@ expectType, string, "fr-fr">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) diff --git a/test/types/document-prismicDocumentWithUID.types.ts b/test/types/document-prismicDocumentWithUID.types.ts index d18060dd..5a4f6563 100644 --- a/test/types/document-prismicDocumentWithUID.types.ts +++ b/test/types/document-prismicDocumentWithUID.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.PrismicDocumentWithUID): true => { +;(value: prismic.PrismicDocumentWithUID): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", @@ -39,7 +39,7 @@ expectType({ }, ], data: {}, -}); +}) /** * Does not support null UID value. @@ -59,7 +59,7 @@ expectType({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports nullable URL. @@ -78,7 +78,7 @@ expectType({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports custom data interface. @@ -101,15 +101,15 @@ expectType>({ // @ts-expect-error - Only given fields are valid. bar: false, }, -}); +}) /** * Custom data interface supports Group and Slice Zone fields. */ expectType< prismic.PrismicDocumentWithUID<{ - group: prismic.GroupField; - sliceZone: prismic.SliceZone; + group: prismic.GroupField + sliceZone: prismic.SliceZone }> >({ id: "string", @@ -128,7 +128,7 @@ expectType< group: [], sliceZone: [], }, -}); +}) /** * Supports custom type. @@ -147,7 +147,7 @@ expectType, "foo">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) expectType, "foo">>({ id: "string", uid: "string", @@ -163,7 +163,7 @@ expectType, "foo">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports custom language. @@ -184,7 +184,7 @@ expectType< lang: "fr-fr", alternate_languages: [], data: {}, -}); +}) expectType< prismic.PrismicDocumentWithUID, string, "fr-fr"> >({ @@ -202,4 +202,4 @@ expectType< lang: "string", alternate_languages: [], data: {}, -}); +}) diff --git a/test/types/document-prismicDocumentWithoutUID.types.ts b/test/types/document-prismicDocumentWithoutUID.types.ts index 5ccfbf51..06a36578 100644 --- a/test/types/document-prismicDocumentWithoutUID.types.ts +++ b/test/types/document-prismicDocumentWithoutUID.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.PrismicDocumentWithoutUID): true => { +;(value: prismic.PrismicDocumentWithoutUID): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "string", @@ -39,7 +39,7 @@ expectType({ }, ], data: {}, -}); +}) /** * Does not support string UID value. @@ -59,7 +59,7 @@ expectType({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports nullable URL. @@ -78,7 +78,7 @@ expectType({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports custom data interface. @@ -101,15 +101,15 @@ expectType>({ // @ts-expect-error - Only given fields are valid. bar: false, }, -}); +}) /** * Custom data interface supports Group and Slice Zone fields. */ expectType< prismic.PrismicDocumentWithoutUID<{ - group: prismic.GroupField; - sliceZone: prismic.SliceZone; + group: prismic.GroupField + sliceZone: prismic.SliceZone }> >({ id: "string", @@ -128,7 +128,7 @@ expectType< group: [], sliceZone: [], }, -}); +}) /** * Supports custom type. @@ -147,7 +147,7 @@ expectType, "foo">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) expectType, "foo">>({ id: "string", uid: null, @@ -163,7 +163,7 @@ expectType, "foo">>({ lang: "string", alternate_languages: [], data: {}, -}); +}) /** * Supports custom language. @@ -184,7 +184,7 @@ expectType< lang: "fr-fr", alternate_languages: [], data: {}, -}); +}) expectType< prismic.PrismicDocumentWithoutUID, string, "fr-fr"> >({ @@ -202,4 +202,4 @@ expectType< lang: "string", alternate_languages: [], data: {}, -}); +}) diff --git a/test/types/fields-boolean.types.ts b/test/types/fields-boolean.types.ts index 1193f344..61cd4ada 100644 --- a/test/types/fields-boolean.types.ts +++ b/test/types/fields-boolean.types.ts @@ -1,15 +1,15 @@ -import { expectNever } from "ts-expect"; +import { expectNever } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.BooleanField): true => { +;(value: prismic.BooleanField): true => { switch (typeof value) { case "boolean": { - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} diff --git a/test/types/fields-color.types.ts b/test/types/fields-color.types.ts index a46864e6..9d6a311d 100644 --- a/test/types/fields-color.types.ts +++ b/test/types/fields-color.types.ts @@ -1,42 +1,42 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.ColorField): true => { +;(value: prismic.ColorField): true => { switch (typeof value) { case "string": { - return true; + return true } default: { if (value === null) { - return true; + return true } - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ -expectType("#FF00FF"); -expectType>("#FF00FF"); +expectType("#FF00FF") +expectType>("#FF00FF") expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. "#FF00FF", -); +) /** * Empty state. */ -expectType(null); -expectType>(null); +expectType(null) +expectType>(null) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) /** * Must be in hex triplet format. @@ -44,8 +44,8 @@ expectType>( expectType( // @ts-expect-error - Arbitrary strings are invalid. "yellow", -); +) expectType( // @ts-expect-error - Non-hex-triplet color formats are invalid. "rgb(255, 0, 255)", -); +) diff --git a/test/types/fields-contentRelationship.types.ts b/test/types/fields-contentRelationship.types.ts index b54d729f..352cf78f 100644 --- a/test/types/fields-contentRelationship.types.ts +++ b/test/types/fields-contentRelationship.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.ContentRelationshipField): true => { +;(value: prismic.ContentRelationshipField): true => { switch (typeof value) { case "object": { if (value === null) { - return expectNever(value); + return expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. @@ -32,7 +32,7 @@ expectType({ slug: "string", isBroken: true, data: undefined, -}); +}) expectType>({ link_type: prismic.LinkType.Document, id: "string", @@ -44,7 +44,7 @@ expectType>({ slug: "string", isBroken: true, data: undefined, -}); +}) expectType>({ link_type: prismic.LinkType.Document, // @ts-expect-error - Empty fields cannot contain a filled value. @@ -57,23 +57,23 @@ expectType>({ slug: "string", isBroken: true, data: undefined, -}); +}) /** * Empty state. */ expectType({ link_type: prismic.LinkType.Document, -}); +}) expectType>({ link_type: prismic.LinkType.Document, -}); +}) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. { link_type: prismic.LinkType.Document, }, -); +) /** * Supports custom document type. @@ -84,7 +84,7 @@ expectType>({ type: "foo", tags: [], lang: "string", -}); +}) expectType>({ link_type: prismic.LinkType.Document, id: "string", @@ -92,7 +92,7 @@ expectType>({ type: "string", tags: [], lang: "string", -}); +}) /** * Supports custom document language. @@ -103,7 +103,7 @@ expectType>({ type: "string", tags: [], lang: "fr-fr", -}); +}) expectType>({ link_type: prismic.LinkType.Document, id: "string", @@ -111,7 +111,7 @@ expectType>({ tags: [], // @ts-expect-error - Document language must match the given type. lang: "string", -}); +}) /** * Supports custom document data. @@ -133,4 +133,4 @@ expectType< // @ts-expect-error - Only given fields are valid. bar: false, }, -}); +}) diff --git a/test/types/fields-date.types.ts b/test/types/fields-date.types.ts index d8388618..bc16624d 100644 --- a/test/types/fields-date.types.ts +++ b/test/types/fields-date.types.ts @@ -1,42 +1,42 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.DateField): true => { +;(value: prismic.DateField): true => { switch (typeof value) { case "string": { - return true; + return true } default: { if (value === null) { - return true; + return true } - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ -expectType("1984-01-24"); -expectType>("1984-01-24"); +expectType("1984-01-24") +expectType>("1984-01-24") expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. "1984-01-24", -); +) /** * Empty state. */ -expectType(null); -expectType>(null); +expectType(null) +expectType>(null) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) /** * Must be in YYYY-MM-DD format. @@ -44,4 +44,4 @@ expectType>( expectType( // @ts-expect-error - Arbitrary strings are invalid. "Jan 24, 1984", -); +) diff --git a/test/types/fields-embed.types.ts b/test/types/fields-embed.types.ts index 94ccf957..6cc7a13d 100644 --- a/test/types/fields-embed.types.ts +++ b/test/types/fields-embed.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.EmbedField): true => { +;(value: prismic.EmbedField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * `EmbedType` keeps compatibility with other versions. @@ -26,12 +26,12 @@ import * as prismic from "../../src"; const ForeignEmbedType = { Link: "link", Breaking: "breaking", -} as const; -expectType(ForeignEmbedType.Link); +} as const +expectType(ForeignEmbedType.Link) expectType( // @ts-expect-error - `EmbedType` should still fail with breaking changes ForeignEmbedType.Breaking, -); +) /** * Filled state. @@ -50,13 +50,13 @@ expectType({ thumbnail_width: null, thumbnail_height: null, html: null, -}); +}) expectType>({ embed_url: "https://example.com", type: prismic.OEmbedType.Link, version: "1.0", html: null, -}); +}) expectType>({ // @ts-expect-error - Empty fields cannot contain a filled value. embed_url: "https://example.com", @@ -66,17 +66,17 @@ expectType>({ version: "1.0", // @ts-expect-error - Empty fields cannot contain a filled value. html: null, -}); +}) /** * Empty state. */ -expectType({}); -expectType>({}); +expectType({}) +expectType>({}) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. {}, -); +) /** * Includes common oEmbed data by default. @@ -95,7 +95,7 @@ expectType({ thumbnail_width: 666, thumbnail_height: 999, html: "html", -}); +}) /** * Supports unknown keys by default. @@ -115,7 +115,7 @@ expectType({ thumbnail_height: null, html: null, unknown_key: "string", -}); +}) /** * Supports custom oEmbed data. @@ -126,7 +126,7 @@ expectType>({ version: "1.0", html: null, foo: "bar", -}); +}) /** * Gives priority to custom oEmbed data. @@ -138,4 +138,4 @@ expectType>({ html: null, // @ts-expect-error - Now expects `foo` to be `"bar"`. foo: "baz", -}); +}) diff --git a/test/types/fields-geoPoint.types.ts b/test/types/fields-geoPoint.types.ts index 1f751c23..fa94737f 100644 --- a/test/types/fields-geoPoint.types.ts +++ b/test/types/fields-geoPoint.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.GeoPointField): true => { +;(value: prismic.GeoPointField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. @@ -24,24 +24,24 @@ import * as prismic from "../../src"; expectType({ longitude: 0, latitude: 0, -}); +}) expectType>({ longitude: 0, latitude: 0, -}); +}) expectType>({ // @ts-expect-error - Empty fields cannot contain a filled value. longitude: 0, // @ts-expect-error - Empty fields cannot contain a filled value. latitude: 0, -}); +}) /** * Empty state. */ -expectType({}); -expectType>({}); +expectType({}) +expectType>({}) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. {}, -); +) diff --git a/test/types/fields-group.types.ts b/test/types/fields-group.types.ts index 5796fcdd..d367f1a4 100644 --- a/test/types/fields-group.types.ts +++ b/test/types/fields-group.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.GroupField): true => { +;(value: prismic.GroupField): true => { if (!Array.isArray(value)) { - return expectNever(value); + return expectNever(value) } switch (typeof value[0]) { case "object": { if (value[0] === null) { - expectNever(value[0]); + expectNever(value[0]) } - return true; + return true } // When the field is empty, value[0] is undefined. case "undefined": { - return true; + return true } default: { - return expectNever(value[0]); + return expectNever(value[0]) } } -}; +} /** * Filled state. It does not use FieldState like other fields; an array with @@ -35,13 +35,13 @@ expectType([ { boolean: true, }, -]); +]) /** * Empty state. It does not use FieldState like other fields; an empty array * implicity signals an empty state. */ -expectType([]); +expectType([]) /** * Supports custom fields definition. @@ -50,18 +50,18 @@ expectType>([ { boolean: true, }, -]); +]) expectType>([ { // @ts-expect-error - Fields must match the given type definition. boolean: "string", }, -]); +]) /** * Supports nested groups. */ -expectType>([]); +expectType>([]) /** * Custom fields may only contain group-compatible fields. @@ -69,6 +69,6 @@ expectType>([]); expectType< prismic.GroupField ->([]); +>([]) diff --git a/test/types/fields-image.types.ts b/test/types/fields-image.types.ts index c1accca2..7b5bccf3 100644 --- a/test/types/fields-image.types.ts +++ b/test/types/fields-image.types.ts @@ -1,22 +1,23 @@ -import { TypeOf, expectNever, expectType } from "ts-expect"; +import type { TypeOf } from "ts-expect" +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.ImageField): true => { +;(value: prismic.ImageField): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. @@ -28,7 +29,7 @@ expectType({ edit: { x: 0, y: 0, zoom: 1, background: "background" }, alt: "alt", copyright: "copyright", -}); +}) expectType>({ id: "id", url: "url", @@ -36,7 +37,7 @@ expectType>({ edit: { x: 0, y: 0, zoom: 1, background: "background" }, alt: "alt", copyright: "copyright", -}); +}) expectType>({ // @ts-expect-error - Empty fields cannot contain a filled value. id: "id", @@ -50,7 +51,7 @@ expectType>({ alt: "alt", // @ts-expect-error - Empty fields cannot contain a filled value. copyright: "copyright", -}); +}) /** * Empty state. @@ -60,14 +61,14 @@ expectType({ dimensions: null, alt: null, copyright: null, -}); -expectType({}); +}) +expectType({}) expectType>({ url: null, dimensions: null, alt: null, copyright: null, -}); +}) expectType>({ // @ts-expect-error - Filled fields cannot contain an empty value. id: null, @@ -79,7 +80,7 @@ expectType>({ edit: null, alt: null, copyright: null, -}); +}) /** * Allows null alt and copyright. @@ -91,7 +92,7 @@ expectType({ edit: { x: 0, y: 0, zoom: 1, background: "background" }, alt: null, copyright: null, -}); +}) /** * Does not contain thumbnails by default. @@ -103,7 +104,7 @@ expectType({ copyright: "copyright", // @ts-expect-error - No thumbnails are included by default. Foo: {}, -}); +}) /** * Supports thumbnails. @@ -131,11 +132,11 @@ expectType>({ alt: "alt", copyright: "copyright", }, -}); +}) // See: #27 -const withThumbnails = {} as prismic.ImageField<"Foo" | "Bar">; -withThumbnails.Foo; -withThumbnails.Bar; +const withThumbnails = {} as prismic.ImageField<"Foo" | "Bar"> +withThumbnails.Foo +withThumbnails.Bar /** * Thumbnails can be disabled with `never` ThumbnailNames. @@ -152,12 +153,12 @@ expectType>({ alt: "alt", copyright: "copyright", }, -}); -const withoutThumbnails = {} as prismic.ImageField; +}) +const withoutThumbnails = {} as prismic.ImageField // @ts-expect-error - No thumbnails should be included when set to `never`. -withoutThumbnails.Foo; +withoutThumbnails.Foo // @ts-expect-error - No thumbnails should be included when set to `never`. -withoutThumbnails.Bar; +withoutThumbnails.Bar // TODO: Remove this group of tests when support for `null` ThumbnailNames is // removed. @@ -176,12 +177,12 @@ expectType>({ alt: "alt", copyright: "copyright", }, -}); -const withoutThumbnailsNull = {} as prismic.ImageField; +}) +const withoutThumbnailsNull = {} as prismic.ImageField // @ts-expect-error - No thumbnails should be included when set to `null`. -withoutThumbnailsNull.Foo; +withoutThumbnailsNull.Foo // @ts-expect-error - No thumbnails should be included when set to `null`. -withoutThumbnailsNull.Bar; +withoutThumbnailsNull.Bar /** * Thumbnail name can be `"length"` (edge case, see: #31) @@ -198,7 +199,7 @@ expectType({ alt: "alt", copyright: "copyright", }, -}); +}) expectType>({ id: "id", url: "url", @@ -214,28 +215,28 @@ expectType>({ alt: "alt", copyright: "copyright", }, -}); +}) /** * ImageFields are valid ImageFieldImage extends. */ -expectType>(true); -expectType>>(true); -expectType>>(true); +expectType>(true) +expectType>>(true) +expectType>>(true) expectType>>( true, -); +) const _ImageFieldIsValidImageFieldImageExtendDebug: prismic.ImageFieldImage = - {} as prismic.ImageField; + {} as prismic.ImageField /** * ImageFieldImages are valid ImageField extends with no thumbnails. */ -expectType>(true); -expectType, prismic.ImageFieldImage>>(true); -expectType, prismic.ImageFieldImage>>(false); +expectType>(true) +expectType, prismic.ImageFieldImage>>(true) +expectType, prismic.ImageFieldImage>>(false) expectType, prismic.ImageFieldImage>>( false, -); +) const _ImageFieldImageIsValidImageFieldExtendDebug: prismic.ImageField = - {} as prismic.ImageFieldImage; + {} as prismic.ImageFieldImage diff --git a/test/types/fields-integration.types.ts b/test/types/fields-integration.types.ts index 1a236844..34068e43 100644 --- a/test/types/fields-integration.types.ts +++ b/test/types/fields-integration.types.ts @@ -1,56 +1,56 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.IntegrationField): true => { +;(value: prismic.IntegrationField): true => { switch (typeof value) { case "object": { if (value === null) { - return true; + return true } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ expectType({ foo: "bar", -}); +}) expectType, "filled">>({ foo: "bar", -}); +}) expectType, "empty">>( // @ts-expect-error - Empty fields cannot contain a filled value. { foo: "bar", }, -); +) /** * Empty state. */ -expectType(null); -expectType, "empty">>(null); +expectType(null) +expectType, "empty">>(null) expectType, "filled">>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) /** * Supports custom blob type. */ expectType>({ foo: "bar", -}); +}) expectType>({ // @ts-expect-error - Blob should match the given type. baz: "qux", -}); +}) diff --git a/test/types/fields-keyText.types.ts b/test/types/fields-keyText.types.ts index 8a4034cf..d7ab8128 100644 --- a/test/types/fields-keyText.types.ts +++ b/test/types/fields-keyText.types.ts @@ -1,39 +1,39 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.KeyTextField): true => { +;(value: prismic.KeyTextField): true => { switch (typeof value) { case "string": { - return true; + return true } default: { if (value === null) { - return true; + return true } - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ -expectType("foo"); -expectType>("foo"); +expectType("foo") +expectType>("foo") expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. "foo", -); +) /** * Empty state. */ -expectType(null); -expectType>(null); +expectType(null) +expectType>(null) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) diff --git a/test/types/fields-link.types.ts b/test/types/fields-link.types.ts index 5f5a8072..813eea01 100644 --- a/test/types/fields-link.types.ts +++ b/test/types/fields-link.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.LinkField): true => { +;(value: prismic.LinkField): true => { switch (typeof value) { case "object": { if (value === null) { - return expectNever(value); + return expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * `LinkType` keeps compatibility with other versions. @@ -26,12 +26,12 @@ import * as prismic from "../../src"; const ForeignLinkType = { Document: "Document", Breaking: "Breaking", -} as const; -expectType(ForeignLinkType.Document); +} as const +expectType(ForeignLinkType.Document) expectType( // @ts-expect-error - `LinkType` should still fail with breaking changes ForeignLinkType.Breaking, -); +) /** * Filled state. @@ -41,7 +41,7 @@ expectType({ link_type: prismic.LinkType.Web, url: "string", target: "string", -}); +}) // Content relationship link expectType({ link_type: prismic.LinkType.Document, @@ -54,7 +54,7 @@ expectType({ slug: "string", isBroken: true, data: undefined, -}); +}) // Media link expectType({ link_type: prismic.LinkType.Media, @@ -64,32 +64,32 @@ expectType({ size: "string", height: "string", width: "string", -}); +}) expectType>({ link_type: prismic.LinkType.Web, url: "string", target: "string", -}); +}) expectType>({ link_type: prismic.LinkType.Web, // @ts-expect-error - Empty fields cannot contain a filled value. url: "string", target: "string", -}); +}) /** * Empty state. */ expectType({ link_type: prismic.LinkType.Any, -}); +}) expectType>({ link_type: prismic.LinkType.Any, -}); +}) expectType>({ // @ts-expect-error - Filled fields cannot contain an empty value. link_type: prismic.LinkType.Any, -}); +}) /** * Supports custom document type for document links. @@ -100,7 +100,7 @@ expectType>({ type: "foo", tags: [], lang: "string", -}); +}) // @ts-expect-error - Document type must match the given type. expectType>({ link_type: prismic.LinkType.Document, @@ -108,7 +108,7 @@ expectType>({ type: "string", tags: [], lang: "string", -}); +}) /** * Supports custom document language for document links. @@ -119,7 +119,7 @@ expectType>({ type: "string", tags: [], lang: "fr-fr", -}); +}) // @ts-expect-error - Document language must match the given type. expectType>({ link_type: prismic.LinkType.Document, @@ -127,7 +127,7 @@ expectType>({ type: "string", tags: [], lang: "string", -}); +}) /** * Supports custom document data for document links. @@ -143,4 +143,4 @@ expectType>({ // @ts-expect-error - Only given fields are valid. bar: false, }, -}); +}) diff --git a/test/types/fields-linkToMedia.types.ts b/test/types/fields-linkToMedia.types.ts index e19ab463..44a10d15 100644 --- a/test/types/fields-linkToMedia.types.ts +++ b/test/types/fields-linkToMedia.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.LinkToMediaField): true => { +;(value: prismic.LinkToMediaField): true => { switch (typeof value) { case "object": { if (value === null) { - return expectNever(value); + return expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. @@ -30,7 +30,7 @@ expectType({ size: "string", height: "string", width: "string", -}); +}) expectType>({ id: "string", link_type: prismic.LinkType.Media, @@ -40,7 +40,7 @@ expectType>({ size: "string", height: "string", width: "string", -}); +}) expectType>({ link_type: prismic.LinkType.Media, // @ts-expect-error - Empty fields cannot contain a filled value. @@ -51,20 +51,20 @@ expectType>({ size: "string", height: "string", width: "string", -}); +}) /** * Empty state. */ expectType({ link_type: prismic.LinkType.Media, -}); +}) expectType>({ link_type: prismic.LinkType.Media, -}); +}) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. { link_type: prismic.LinkType.Media, }, -); +) diff --git a/test/types/fields-number.types.ts b/test/types/fields-number.types.ts index 8c942c37..b2fe4c56 100644 --- a/test/types/fields-number.types.ts +++ b/test/types/fields-number.types.ts @@ -1,39 +1,39 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.NumberField): true => { +;(value: prismic.NumberField): true => { switch (typeof value) { case "number": { - return true; + return true } default: { if (value === null) { - return true; + return true } - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ -expectType(0); -expectType>(0); +expectType(0) +expectType>(0) expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. 0, -); +) /** * Empty state. */ -expectType(null); -expectType>(null); +expectType(null) +expectType>(null) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) diff --git a/test/types/fields-richText.types.ts b/test/types/fields-richText.types.ts index 81b9e86a..bcf88741 100644 --- a/test/types/fields-richText.types.ts +++ b/test/types/fields-richText.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.RichTextField): true => { +;(value: prismic.RichTextField): true => { if (!Array.isArray(value)) { - return expectNever(value); + return expectNever(value) } switch (typeof value[0]) { case "object": { if (value[0] === null) { - expectNever(value[0]); + expectNever(value[0]) } - return true; + return true } // When the field is empty, value[0] is undefined. case "undefined": { - return true; + return true } default: { - return expectNever(value[0]); + return expectNever(value[0]) } } -}; +} /** * `RichTextNodeType` keeps compatibility with other versions. @@ -35,14 +35,14 @@ import * as prismic from "../../src"; const ForeignRichTextNodeType = { heading1: "heading1", breaking: "breaking", -} as const; +} as const expectType( ForeignRichTextNodeType.heading1, -); +) expectType( // @ts-expect-error - `RichTextNodeType` should still fail with breaking changes ForeignRichTextNodeType.breaking, -); +) /** * Filled state. @@ -59,7 +59,7 @@ expectType([ }, ], }, -]); +]) expectType>([ { type: prismic.RichTextNodeType.paragraph, @@ -72,7 +72,7 @@ expectType>([ }, ], }, -]); +]) expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. [ @@ -88,17 +88,17 @@ expectType>( ], }, ], -); +) /** * Empty state. */ -expectType([]); -expectType>([]); +expectType([]) +expectType>([]) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. [], -); +) /** * Supports all root-level Structured Text block types. @@ -149,43 +149,43 @@ expectType([ html: null, }, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-level block type. type: prismic.RichTextNodeType.strong, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-level block type. type: prismic.RichTextNodeType.em, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-level block type. type: prismic.RichTextNodeType.label, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-level block type. type: prismic.RichTextNodeType.hyperlink, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-label block type (meta block for internal use only). type: prismic.RichTextNodeType.list, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-label block type (meta block for internal use only). type: prismic.RichTextNodeType.oList, }, -]); +]) /** * Text blocks support spans. @@ -225,4 +225,4 @@ expectType([ }, ], }, -]); +]) diff --git a/test/types/fields-select.types.ts b/test/types/fields-select.types.ts index 0f44b45f..1bd844d3 100644 --- a/test/types/fields-select.types.ts +++ b/test/types/fields-select.types.ts @@ -1,55 +1,55 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.SelectField): true => { +;(value: prismic.SelectField): true => { switch (typeof value) { case "string": { - return true; + return true } default: { if (value === null) { - return true; + return true } - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ -expectType("foo"); -expectType>("foo"); +expectType("foo") +expectType>("foo") expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. "foo", -); +) /** * Empty state. */ -expectType(null); -expectType>(null); +expectType(null) +expectType>(null) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) /** * Supports options enum (loosely typed using string union). */ -(value: prismic.SelectField<"foo" | "bar", "filled">) => { +;(value: prismic.SelectField<"foo" | "bar", "filled">) => { switch (value) { case "foo": case "bar": { - break; + break } default: { - expectNever(value); + expectNever(value) } } -}; +} diff --git a/test/types/fields-sharedSlice.types.ts b/test/types/fields-sharedSlice.types.ts index 723fbb5f..8fb3cb76 100644 --- a/test/types/fields-sharedSlice.types.ts +++ b/test/types/fields-sharedSlice.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.SharedSlice): true => { +;(value: prismic.SharedSlice): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "id", @@ -26,7 +26,7 @@ expectType({ version: "string", primary: {}, items: [], -}); +}) /** * Supports custom shared Slice type API ID. @@ -39,7 +39,7 @@ expectType>({ version: "string", primary: {}, items: [], -}); +}) expectType>({ id: "id", // @ts-expect-error - Slice type must match the given type. @@ -49,7 +49,7 @@ expectType>({ version: "string", primary: {}, items: [], -}); +}) /** * Supports custom variation types. @@ -62,7 +62,7 @@ expectType>>({ version: "string", primary: {}, items: [], -}); +}) expectType>>({ id: "id", slice_type: "string", @@ -72,4 +72,4 @@ expectType>>({ version: "string", primary: {}, items: [], -}); +}) diff --git a/test/types/fields-sharedSliceVariation.types.ts b/test/types/fields-sharedSliceVariation.types.ts index 7085934f..add16742 100644 --- a/test/types/fields-sharedSliceVariation.types.ts +++ b/test/types/fields-sharedSliceVariation.types.ts @@ -1,29 +1,29 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.SharedSliceVariation): true => { +;(value: prismic.SharedSliceVariation): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ variation: "string", version: "string", primary: {}, items: [], -}); +}) /** * Supports custom API ID. @@ -33,14 +33,14 @@ expectType>({ version: "string", primary: {}, items: [], -}); +}) expectType>({ // @ts-expect-error - Variation type must match the given type. variation: "string", version: "string", primary: {}, items: [], -}); +}) /** * Supports custom primary fields type. @@ -60,7 +60,7 @@ expectType< baz: false, }, items: [], -}); +}) /** * Supports custom items fields type. @@ -82,7 +82,7 @@ expectType< baz: false, }, ], -}); +}) /** * Does not support groups in items section. @@ -99,4 +99,4 @@ expectType< version: "string", primary: {}, items: [], -}); +}) diff --git a/test/types/fields-slice.types.ts b/test/types/fields-slice.types.ts index c42dae11..29f6b820 100644 --- a/test/types/fields-slice.types.ts +++ b/test/types/fields-slice.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.Slice): true => { +;(value: prismic.Slice): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ id: "id", @@ -24,7 +24,7 @@ expectType({ slice_label: null, primary: {}, items: [], -}); +}) /** * Supports Slice labels. @@ -35,7 +35,7 @@ expectType({ slice_label: "string", primary: {}, items: [], -}); +}) /** * Supports custom Slice type API ID. @@ -46,7 +46,7 @@ expectType>({ slice_label: "string", primary: {}, items: [], -}); +}) expectType>({ id: "id", // @ts-expect-error - Slice type must match the given type. @@ -54,7 +54,7 @@ expectType>({ slice_label: "string", primary: {}, items: [], -}); +}) /** * Supports custom primary fields type. @@ -69,7 +69,7 @@ expectType>({ bar: false, }, items: [], -}); +}) /** * Custom primary fields may only contain group-compatible fields. @@ -79,7 +79,7 @@ expectType< string, // @ts-expect-error - Groups are invalid within primary fields. { - group: prismic.GroupField; + group: prismic.GroupField } > >({ @@ -90,13 +90,13 @@ expectType< group: [], }, items: [], -}); +}) expectType< prismic.Slice< string, // @ts-expect-error - Slice Zones are invalid within primary fields. { - sliceZone: prismic.SliceZone; + sliceZone: prismic.SliceZone } > >({ @@ -107,7 +107,7 @@ expectType< sliceZone: [], }, items: [], -}); +}) /** * Supports custom items fields type. @@ -132,7 +132,7 @@ expectType< baz: false, }, ], -}); +}) /** * Custom item fields may only contain group-compatible fields. @@ -143,7 +143,7 @@ expectType< { foo: prismic.BooleanField }, // @ts-expect-error - Groups are invalid within item fields. { - group: prismic.GroupField; + group: prismic.GroupField } > >({ @@ -154,14 +154,14 @@ expectType< foo: true, }, items: [], -}); +}) expectType< prismic.Slice< string, { foo: prismic.BooleanField }, // @ts-expect-error - Slice Zones are invalid within item fields. { - sliceZone: prismic.SliceZone; + sliceZone: prismic.SliceZone } > >({ @@ -172,4 +172,4 @@ expectType< foo: true, }, items: [], -}); +}) diff --git a/test/types/fields-sliceZone.types.ts b/test/types/fields-sliceZone.types.ts index 4f03d3c5..56838961 100644 --- a/test/types/fields-sliceZone.types.ts +++ b/test/types/fields-sliceZone.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.SliceZone): true => { +;(value: prismic.SliceZone): true => { if (!Array.isArray(value)) { - return expectNever(value); + return expectNever(value) } switch (typeof value[0]) { case "object": { if (value[0] === null) { - expectNever(value[0]); + expectNever(value[0]) } - return true; + return true } // When the field is empty, value[0] is undefined. case "undefined": { - return true; + return true } default: { - return expectNever(value[0]); + return expectNever(value[0]) } } -}; +} /** * Filled state. It does not use FieldState like other fields; an array with @@ -50,13 +50,13 @@ expectType([ primary: {}, items: [], }, -]); +]) /** * Empty state. It does not use FieldState like other fields; an empty array * implicity signals an empty state. */ -expectType([]); +expectType([]) /** * Supports custom Slice definitions. @@ -69,7 +69,7 @@ expectType>>([ primary: {}, items: [], }, -]); +]) expectType>>([ { id: "id", @@ -79,7 +79,7 @@ expectType>>([ primary: {}, items: [], }, -]); +]) /** * Supports custom shared Slice definitions. @@ -94,7 +94,7 @@ expectType>>([ primary: {}, items: [], }, -]); +]) expectType>>([ { id: "id", @@ -106,4 +106,4 @@ expectType>>([ primary: {}, items: [], }, -]); +]) diff --git a/test/types/fields-timestamp.types.ts b/test/types/fields-timestamp.types.ts index 54ebd199..49bf1a9c 100644 --- a/test/types/fields-timestamp.types.ts +++ b/test/types/fields-timestamp.types.ts @@ -1,42 +1,42 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.TimestampField): true => { +;(value: prismic.TimestampField): true => { switch (typeof value) { case "string": { - return true; + return true } default: { if (value === null) { - return true; + return true } - return expectNever(value); + return expectNever(value) } } -}; +} /** * Filled state. */ -expectType("1984-01-24T05:00:00+0000"); -expectType>("1984-01-24T05:00:00+0000"); +expectType("1984-01-24T05:00:00+0000") +expectType>("1984-01-24T05:00:00+0000") expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. "1984-01-24T05:00:00+0000", -); +) /** * Empty state. */ -expectType(null); -expectType>(null); +expectType(null) +expectType>(null) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. null, -); +) /** * Must be in YYYY-MM-DDTHH:MM:SS+ZZZZ format. @@ -44,4 +44,4 @@ expectType>( expectType( // @ts-expect-error - Arbitrary strings are invalid. "1984-01-24", -); +) diff --git a/test/types/fields-title.types.ts b/test/types/fields-title.types.ts index 09c2245e..d0fd2f5f 100644 --- a/test/types/fields-title.types.ts +++ b/test/types/fields-title.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import * as prismic from "../../src" -(value: prismic.TitleField): true => { +;(value: prismic.TitleField): true => { if (!Array.isArray(value)) { - return expectNever(value); + return expectNever(value) } switch (typeof value[0]) { case "object": { if (value[0] === null) { - expectNever(value[0]); + expectNever(value[0]) } - return true; + return true } // When the field is empty, value[0] is undefined. case "undefined": { - return true; + return true } default: { - return expectNever(value[0]); + return expectNever(value[0]) } } -}; +} /** * Filled state. @@ -36,14 +36,14 @@ expectType([ text: "string", spans: [], }, -]); +]) expectType>([ { type: prismic.RichTextNodeType.heading1, text: "string", spans: [], }, -]); +]) expectType>( // @ts-expect-error - Empty fields cannot contain a filled value. [ @@ -53,39 +53,39 @@ expectType>( spans: [], }, ], -); +) /** * Empty state. */ -expectType([]); -expectType>([]); +expectType([]) +expectType>([]) expectType>( // @ts-expect-error - Filled fields cannot contain an empty value. [], -); +) /** * Supports all heading Structured Text block types. */ expectType([ { type: prismic.RichTextNodeType.heading1, text: "string", spans: [] }, -]); +]) expectType([ { type: prismic.RichTextNodeType.heading2, text: "string", spans: [] }, -]); +]) expectType([ { type: prismic.RichTextNodeType.heading3, text: "string", spans: [] }, -]); +]) expectType([ { type: prismic.RichTextNodeType.heading4, text: "string", spans: [] }, -]); +]) expectType([ { type: prismic.RichTextNodeType.heading5, text: "string", spans: [] }, -]); +]) expectType([ { type: prismic.RichTextNodeType.heading5, text: "string", spans: [] }, -]); +]) /** * Does not allow non-heading Structured Text block types. @@ -95,73 +95,73 @@ expectType([ // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.paragraph, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.preformatted, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.listItem, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.oListItem, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.image, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.embed, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.strong, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.em, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.label, }, -]); +]) expectType([ { // @ts-expect-error Not a heading block type. type: prismic.RichTextNodeType.hyperlink, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-label block type (meta block for internal use only). type: prismic.RichTextNodeType.list, }, -]); +]) expectType([ { // @ts-expect-error - Not a root-label block type (meta block for internal use only). type: prismic.RichTextNodeType.oList, }, -]); +]) /** * Does not allow spans elements. @@ -179,4 +179,4 @@ expectType([ }, ], }, -]); +]) diff --git a/test/types/fields.types.ts b/test/types/fields.types.ts index 7c01054e..9bcc25aa 100644 --- a/test/types/fields.types.ts +++ b/test/types/fields.types.ts @@ -1,61 +1,62 @@ -import { TypeOf, expectNever, expectType } from "ts-expect"; - -import * as prismic from "../../src"; +import type { TypeOf } from "ts-expect" +import { expectNever, expectType } from "ts-expect" +import type * as prismic from "../../src" /** * FieldState */ -(value: prismic.FieldState): true => { + +;(value: prismic.FieldState): true => { switch (value) { case "filled": case "empty": { - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} /** * AnyRegularField supports any field compatible with a nested Group. */ -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) expectType>( true, -); -expectType>(true); -expectType>(true); -expectType>(true); -expectType>(true); +) +expectType>(true) +expectType>(true) +expectType>(true) +expectType>(true) /** * AnyRegularField excludes any fields not compatible with a nested Group. */ -expectType>(false); -expectType>(false); -expectType>(false); +expectType>(false) +expectType>(false) +expectType>(false) /** * AnySlicePrimaryField supports any field compatible with a slice's primary * section. */ -expectType>(true); -expectType>(true); +expectType>(true) +expectType>(true) /** * AnySlicePrimaryField excludes any fields not compatible with a slice's * primary section. */ -expectType>(false); +expectType>(false) diff --git a/test/types/helpers-isFilled.types.ts b/test/types/helpers-isFilled.types.ts index f8e9b44f..4eb995cc 100644 --- a/test/types/helpers-isFilled.types.ts +++ b/test/types/helpers-isFilled.types.ts @@ -1,222 +1,217 @@ -import { TypeEqual, expectType } from "ts-expect"; - -import * as prismic from "../../src"; +import type { TypeEqual } from "ts-expect" +import { expectType } from "ts-expect" +import * as prismic from "../../src" /** * RichText */ -(value: prismic.RichTextField) => { + +;(value: prismic.RichTextField) => { if (prismic.isFilled.richText(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * Title */ -(value: prismic.TitleField) => { +;(value: prismic.TitleField) => { if (prismic.isFilled.title(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * Image thumbnail */ -(value: prismic.ImageFieldImage) => { +;(value: prismic.ImageFieldImage) => { if (prismic.isFilled.imageThumbnail(value)) { - expectType, typeof value>>( - true, - ); - expectType, typeof value>>( - false, - ); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { expectType, typeof value>>( false, - ); - expectType, typeof value>>(true); + ) + expectType, typeof value>>(true) } -}; +} /** * Image */ // Default (without thumbnail) -(value: prismic.ImageField) => { +;(value: prismic.ImageField) => { if (prismic.isFilled.image(value)) { expectType, typeof value>>( true, - ); + ) expectType, typeof value>>( false, - ); + ) } else { expectType, typeof value>>( false, - ); + ) expectType, typeof value>>( true, - ); + ) } -}; +} // With thumbnails -(value: prismic.ImageField<"foo">) => { +;(value: prismic.ImageField<"foo">) => { if (prismic.isFilled.image(value)) { expectType, typeof value>>( true, - ); + ) expectType, typeof value>>( false, - ); + ) } else { expectType, typeof value>>( false, - ); + ) expectType, typeof value>>( true, - ); + ) } -}; +} /** * Link */ // Default -(value: prismic.LinkField) => { +;(value: prismic.LinkField) => { if (prismic.isFilled.link(value)) { expectType< TypeEqual< prismic.LinkField, typeof value > - >(true); + >(true) expectType< TypeEqual< prismic.LinkField, typeof value > - >(false); + >(false) } else { expectType< TypeEqual< prismic.LinkField, typeof value > - >(false); + >(false) expectType< TypeEqual< prismic.LinkField, typeof value > - >(true); + >(true) } -}; +} -type LinkData = { baz: prismic.RichTextField }; +type LinkData = { baz: prismic.RichTextField } // With type, lang, and data -(value: prismic.LinkField<"foo", "bar", LinkData>) => { +;(value: prismic.LinkField<"foo", "bar", LinkData>) => { if (prismic.isFilled.link(value)) { expectType< TypeEqual< prismic.LinkField<"foo", "bar", LinkData, "filled">, typeof value > - >(true); + >(true) expectType< TypeEqual< prismic.LinkField<"foo", "bar", LinkData, "empty">, typeof value > - >(false); + >(false) } else { expectType< TypeEqual< prismic.LinkField<"foo", "bar", LinkData, "filled">, typeof value > - >(false); + >(false) expectType< TypeEqual< prismic.LinkField<"foo", "bar", LinkData, "empty">, typeof value > - >(true); + >(true) } -}; +} /** * Link to media */ -(value: prismic.LinkToMediaField) => { +;(value: prismic.LinkToMediaField) => { if (prismic.isFilled.linkToMedia(value)) { expectType, typeof value>>( true, - ); + ) expectType, typeof value>>( false, - ); + ) } else { expectType, typeof value>>( false, - ); - expectType, typeof value>>( - true, - ); + ) + expectType, typeof value>>(true) } -}; +} /** * Content relationship */ // Default -(value: prismic.ContentRelationshipField) => { +;(value: prismic.ContentRelationshipField) => { if (prismic.isFilled.contentRelationship(value)) { expectType< TypeEqual< prismic.ContentRelationshipField, typeof value > - >(true); + >(true) expectType< TypeEqual< prismic.ContentRelationshipField, typeof value > - >(false); + >(false) } else { expectType< TypeEqual< prismic.ContentRelationshipField, typeof value > - >(false); + >(false) expectType< TypeEqual< prismic.ContentRelationshipField, typeof value > - >(true); + >(true) } -}; +} -type ContentRelationshipData = { baz: prismic.RichTextField }; +type ContentRelationshipData = { baz: prismic.RichTextField } // With type, lang, and data -( +;( value: prismic.ContentRelationshipField< "foo", "bar", @@ -234,7 +229,7 @@ type ContentRelationshipData = { baz: prismic.RichTextField }; >, typeof value > - >(true); + >(true) expectType< TypeEqual< prismic.ContentRelationshipField< @@ -245,7 +240,7 @@ type ContentRelationshipData = { baz: prismic.RichTextField }; >, typeof value > - >(false); + >(false) } else { expectType< TypeEqual< @@ -257,7 +252,7 @@ type ContentRelationshipData = { baz: prismic.RichTextField }; >, typeof value > - >(false); + >(false) expectType< TypeEqual< prismic.ContentRelationshipField< @@ -268,250 +263,248 @@ type ContentRelationshipData = { baz: prismic.RichTextField }; >, typeof value > - >(true); + >(true) } -}; +} /** * Date */ -(value: prismic.DateField) => { +;(value: prismic.DateField) => { if (prismic.isFilled.date(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * Timestamp */ -(value: prismic.TimestampField) => { +;(value: prismic.TimestampField) => { if (prismic.isFilled.timestamp(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>( - false, - ); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * Color */ -(value: prismic.ColorField) => { +;(value: prismic.ColorField) => { if (prismic.isFilled.color(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * Number */ -(value: prismic.NumberField) => { +;(value: prismic.NumberField) => { if (prismic.isFilled.number(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * KeyText */ -(value: prismic.KeyTextField) => { +;(value: prismic.KeyTextField) => { if (prismic.isFilled.keyText(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); + expectType, typeof value>>(false) // `""` is of type string and gets TypeScript confused in the narrowing. expectType, typeof value | "">>( true, - ); + ) } -}; +} /** * Select */ // Default -(value: prismic.SelectField) => { +;(value: prismic.SelectField) => { if (prismic.isFilled.select(value)) { expectType, typeof value>>( true, - ); + ) expectType, typeof value>>( false, - ); + ) } else { expectType, typeof value>>( false, - ); + ) expectType, typeof value>>( true, - ); + ) } -}; +} // With enum -(value: prismic.SelectField<"foo" | "bar">) => { +;(value: prismic.SelectField<"foo" | "bar">) => { if (prismic.isFilled.select(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType< TypeEqual, typeof value> - >(false); + >(false) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType< TypeEqual, typeof value> - >(true); + >(true) } -}; +} /** * Embed */ -type EmbedDefault = prismic.AnyOEmbed & prismic.OEmbedExtra; +type EmbedDefault = prismic.AnyOEmbed & prismic.OEmbedExtra // Default -(value: prismic.EmbedField) => { +;(value: prismic.EmbedField) => { if (prismic.isFilled.embed(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType< TypeEqual, typeof value> - >(false); + >(false) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType< TypeEqual, typeof value> - >(true); + >(true) } -}; +} -type EmbedData = prismic.VideoOEmbed & { foo: string }; +type EmbedData = prismic.VideoOEmbed & { foo: string } // With data -(value: prismic.EmbedField) => { +;(value: prismic.EmbedField) => { if (prismic.isFilled.embed(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType, typeof value>>( false, - ); + ) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType, typeof value>>( true, - ); + ) } -}; +} /** * GeoPoint */ -(value: prismic.GeoPointField) => { +;(value: prismic.GeoPointField) => { if (prismic.isFilled.geoPoint(value)) { - expectType, typeof value>>(true); - expectType, typeof value>>(false); + expectType, typeof value>>(true) + expectType, typeof value>>(false) } else { - expectType, typeof value>>(false); - expectType, typeof value>>(true); + expectType, typeof value>>(false) + expectType, typeof value>>(true) } -}; +} /** * Integration fields */ -type IntegrationFieldDefault = Record; +type IntegrationFieldDefault = Record // Default -(value: prismic.IntegrationField) => { +;(value: prismic.IntegrationField) => { if (prismic.isFilled.integrationField(value)) { expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(true); + >(true) expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(false); + >(false) } else { expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(false); + >(false) expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(true); + >(true) } -}; +} -type IntegrationFieldData = { foo: string }; +type IntegrationFieldData = { foo: string } // With data -(value: prismic.IntegrationField) => { +;(value: prismic.IntegrationField) => { if (prismic.isFilled.integrationField(value)) { expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(true); + >(true) expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(false); + >(false) } else { expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(false); + >(false) expectType< TypeEqual< prismic.IntegrationField, typeof value > - >(true); + >(true) } -}; +} /** * Group @@ -520,90 +513,90 @@ type IntegrationFieldData = { foo: string }; type GroupDefault = Record< string, prismic.AnyRegularField | prismic.NestedGroupField ->; +> // Default -(value: prismic.GroupField) => { +;(value: prismic.GroupField) => { if (prismic.isFilled.group(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType< TypeEqual, typeof value> - >(false); + >(false) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType< TypeEqual, typeof value> - >(true); + >(true) } -}; +} -type GroupFields = { foo: prismic.RichTextField }; +type GroupFields = { foo: prismic.RichTextField } // With fields -(value: prismic.GroupField) => { +;(value: prismic.GroupField) => { if (prismic.isFilled.group(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType< TypeEqual, typeof value> - >(false); + >(false) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType< TypeEqual, typeof value> - >(true); + >(true) } -}; +} /** * SliceZone */ -type SliceZoneDefault = prismic.Slice | prismic.SharedSlice; +type SliceZoneDefault = prismic.Slice | prismic.SharedSlice // Default -(value: prismic.SliceZone) => { +;(value: prismic.SliceZone) => { if (prismic.isFilled.sliceZone(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType< TypeEqual, typeof value> - >(false); + >(false) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType< TypeEqual, typeof value> - >(true); + >(true) } -}; +} -type SliceZoneSlices = prismic.Slice<"foo">; +type SliceZoneSlices = prismic.Slice<"foo"> // With fields -(value: prismic.SliceZone) => { +;(value: prismic.SliceZone) => { if (prismic.isFilled.sliceZone(value)) { expectType< TypeEqual, typeof value> - >(true); + >(true) expectType< TypeEqual, typeof value> - >(false); + >(false) } else { expectType< TypeEqual, typeof value> - >(false); + >(false) expectType< TypeEqual, typeof value> - >(true); + >(true) } -}; +} diff --git a/test/types/webhook-apiUpdate.types.ts b/test/types/webhook-apiUpdate.types.ts index 30e502bc..2fc63dd2 100644 --- a/test/types/webhook-apiUpdate.types.ts +++ b/test/types/webhook-apiUpdate.types.ts @@ -1,22 +1,22 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.WebhookBodyAPIUpdate): true => { +;(value: prismic.WebhookBodyAPIUpdate): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: "api-update", @@ -93,19 +93,19 @@ expectType({ addition: ["unknown"], deletion: ["unknown"], }, -}); +}) /** * Secret is nullable. */ -expectType(null); +expectType(null) /** * MasterRef is optional. */ -expectType(undefined); +expectType(undefined) /** * Experiments is optional */ -expectType(undefined); +expectType(undefined) diff --git a/test/types/webhook-testTrigger.types.ts b/test/types/webhook-testTrigger.types.ts index 9027dc27..5dcc988a 100644 --- a/test/types/webhook-testTrigger.types.ts +++ b/test/types/webhook-testTrigger.types.ts @@ -1,31 +1,31 @@ -import { expectNever, expectType } from "ts-expect"; +import { expectNever, expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" -(value: prismic.WebhookBodyTestTrigger): true => { +;(value: prismic.WebhookBodyTestTrigger): true => { switch (typeof value) { case "object": { if (value === null) { - expectNever(value); + expectNever(value) } - return true; + return true } default: { - return expectNever(value); + return expectNever(value) } } -}; +} expectType({ type: "test-trigger", domain: "string", apiUrl: "string", secret: "string", -}); +}) /** * Secret is nullable. */ -expectType(null); +expectType(null) diff --git a/test/types/webhook.types.ts b/test/types/webhook.types.ts index ef6f2d7f..c318b5c9 100644 --- a/test/types/webhook.types.ts +++ b/test/types/webhook.types.ts @@ -1,9 +1,10 @@ -import { TypeOf, expectType } from "ts-expect"; +import type { TypeOf } from "ts-expect" +import { expectType } from "ts-expect" -import * as prismic from "../../src"; +import type * as prismic from "../../src" /** * WebhookBody supports any webhook body. */ -expectType>(true); -expectType>(true); +expectType>(true) +expectType>(true) diff --git a/vite.config.ts b/vite.config.ts index 563ced28..f2c329f6 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,5 +1,5 @@ -import { defineConfig } from "vite"; -import sdk from "vite-plugin-sdk"; +import { defineConfig } from "vite" +import sdk from "vite-plugin-sdk" export default defineConfig({ plugins: [sdk()], @@ -19,4 +19,4 @@ export default defineConfig({ }, setupFiles: ["./test/__setup__"], }, -}); +})