@prismicio/client 6.2.0 → 6.4.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -17,6 +17,8 @@ import { NotFoundError } from "./NotFoundError";
17
17
  import { ParsingError } from "./ParsingError";
18
18
  import { PrismicError } from "./PrismicError";
19
19
  import { buildQueryURL, BuildQueryURLArgs } from "./buildQueryURL";
20
+ import { getRepositoryEndpoint } from "./getRepositoryEndpoint";
21
+ import { isRepositoryEndpoint } from "./isRepositoryEndpoint";
20
22
  import { predicate } from "./predicate";
21
23
 
22
24
  /**
@@ -179,11 +181,11 @@ type GetAllParams = {
179
181
  /**
180
182
  * Arguments to determine how the URL for a preview session is resolved.
181
183
  */
182
- type ResolvePreviewArgs = {
184
+ type ResolvePreviewArgs<LinkResolverReturnType> = {
183
185
  /**
184
186
  * A function that maps a Prismic document to a URL within your app.
185
187
  */
186
- linkResolver?: prismicH.LinkResolverFunction;
188
+ linkResolver?: prismicH.LinkResolverFunction<LinkResolverReturnType>;
187
189
 
188
190
  /**
189
191
  * A fallback URL if the Link Resolver does not return a value.
@@ -237,8 +239,18 @@ const someTagsPredicate = (tags: string | string[]): string =>
237
239
  /**
238
240
  * Creates a Prismic client that can be used to query a repository.
239
241
  *
240
- * @param endpoint - The Prismic REST API V2 endpoint for the repository (use
241
- * `prismic.getEndpoint` for the default endpoint).
242
+ * @example
243
+ *
244
+ * ```ts
245
+ * // With a repository name.
246
+ * createClient("qwerty");
247
+ *
248
+ * // Or with a full Prismic Rest API V2 endpoint.
249
+ * createClient("https://qwerty.cdn.prismic.io/api/v2");
250
+ * ```
251
+ *
252
+ * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
253
+ * API V2 endpoint for the repository.
242
254
  * @param options - Configuration that determines how content will be queried
243
255
  * from the Prismic repository.
244
256
  *
@@ -258,7 +270,7 @@ export const createClient = (
258
270
  export class Client {
259
271
  /**
260
272
  * The Prismic REST API V2 endpoint for the repository (use
261
- * `prismic.getEndpoint` for the default endpoint).
273
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
262
274
  */
263
275
  endpoint: string;
264
276
 
@@ -319,26 +331,31 @@ export class Client {
319
331
  * such as Node.js, the `fetch` option must be provided as part of the
320
332
  * `options` parameter.
321
333
  *
322
- * @param endpoint - The Prismic REST API V2 endpoint for the repository (use
323
- * `prismic.getEndpoint` to get the default endpoint).
334
+ * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
335
+ * API V2 endpoint for the repository.
324
336
  * @param options - Configuration that determines how content will be queried
325
337
  * from the Prismic repository.
326
338
  *
327
339
  * @returns A client that can query content from the repository.
328
340
  */
329
- constructor(endpoint: string, options: ClientConfig = {}) {
330
- if (
331
- process.env.NODE_ENV === "development" &&
332
- /\.prismic\.io\/(?!api\/v2\/?)/.test(endpoint)
333
- ) {
334
- throw new PrismicError(
335
- "@prismicio/client only supports Prismic Rest API V2. Please use the getEndpoint helper to generate a valid Rest API V2 endpoint URL.",
336
- undefined,
337
- undefined,
338
- );
341
+ constructor(repositoryNameOrEndpoint: string, options: ClientConfig = {}) {
342
+ if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
343
+ if (
344
+ process.env.NODE_ENV === "development" &&
345
+ /\.prismic\.io\/(?!api\/v2\/?)/.test(repositoryNameOrEndpoint)
346
+ ) {
347
+ throw new PrismicError(
348
+ "@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.",
349
+ undefined,
350
+ undefined,
351
+ );
352
+ }
353
+
354
+ this.endpoint = repositoryNameOrEndpoint;
355
+ } else {
356
+ this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint);
339
357
  }
340
358
 
341
- this.endpoint = endpoint;
342
359
  this.accessToken = options.accessToken;
343
360
  this.routes = options.routes;
344
361
  this.defaultParams = options.defaultParams;
@@ -364,7 +381,7 @@ export class Client {
364
381
  this.fetchFn = this.fetchFn.bind(globalThis);
365
382
  }
366
383
 
367
- this.graphqlFetch = this.graphqlFetch.bind(this);
384
+ this.graphQLFetch = this.graphQLFetch.bind(this);
368
385
  }
369
386
 
370
387
  /**
@@ -530,7 +547,8 @@ export class Client {
530
547
  const { limit = Infinity, ...actualParams } = params;
531
548
  const resolvedParams = {
532
549
  ...actualParams,
533
- pageSize: actualParams.pageSize || MAX_PAGE_SIZE,
550
+ pageSize:
551
+ actualParams.pageSize || this.defaultParams?.pageSize || MAX_PAGE_SIZE,
534
552
  };
535
553
 
536
554
  const documents: TDocument[] = [];
@@ -1176,8 +1194,8 @@ export class Client {
1176
1194
  * @returns The URL for the previewed document during an active preview
1177
1195
  * session. The user should be redirected to this URL.
1178
1196
  */
1179
- async resolvePreviewURL(
1180
- args: ResolvePreviewArgs & FetchParams,
1197
+ async resolvePreviewURL<LinkResolverReturnType>(
1198
+ args: ResolvePreviewArgs<LinkResolverReturnType> & FetchParams,
1181
1199
  ): Promise<string> {
1182
1200
  let documentID = args.documentID;
1183
1201
  let previewToken = args.previewToken;
@@ -1194,19 +1212,21 @@ export class Client {
1194
1212
  previewToken || (this.refState.httpRequest.query.token as string);
1195
1213
  }
1196
1214
 
1197
- if (documentID != null) {
1215
+ if (documentID != null && previewToken != null) {
1198
1216
  const document = await this.getByID(documentID, {
1199
1217
  signal: args.signal,
1200
1218
  ref: previewToken,
1201
1219
  lang: "*",
1202
1220
  });
1203
1221
 
1204
- // We know we have a valid field to resolve since we are using prismicH.documentToLinkField
1205
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1206
- return prismicH.asLink(document, args.linkResolver)!;
1207
- } else {
1208
- return args.defaultURL;
1222
+ const url = prismicH.asLink(document, args.linkResolver);
1223
+
1224
+ if (typeof url === "string") {
1225
+ return url;
1226
+ }
1209
1227
  }
1228
+
1229
+ return args.defaultURL;
1210
1230
  }
1211
1231
 
1212
1232
  /**
@@ -1295,6 +1315,12 @@ export class Client {
1295
1315
  };
1296
1316
  }
1297
1317
 
1318
+ /**
1319
+ * @deprecated Renamed to `graphQLFetch()` (note the capitalization of "QL").
1320
+ */
1321
+ // TODO: Remove in v3
1322
+ graphqlFetch = this.graphQLFetch;
1323
+
1298
1324
  /**
1299
1325
  * A `fetch()` function to be used with GraphQL clients configured for
1300
1326
  * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
@@ -1322,7 +1348,7 @@ export class Client {
1322
1348
  * @returns The `fetch()` Response for the request.
1323
1349
  * @experimental
1324
1350
  */
1325
- async graphqlFetch(
1351
+ async graphQLFetch(
1326
1352
  input: RequestInfo,
1327
1353
  init?: RequestInit,
1328
1354
  ): Promise<Response> {
@@ -1351,18 +1377,34 @@ export class Client {
1351
1377
  }
1352
1378
  }
1353
1379
 
1354
- // Compress the GraphQL query (if it exists) by removing
1355
- // whitespace. This is done to optimize the query size and avoid hitting the
1356
- // upper limit of GET requests (2048 characters).
1357
1380
  const url = new URL(
1358
1381
  // Asserting `input` is a string since popular GraphQL
1359
1382
  // libraries pass this as a string. Request objects as
1360
1383
  // input are unsupported.
1361
1384
  input as string,
1362
1385
  );
1386
+
1387
+ // This prevents the request from being cached unnecessarily.
1388
+ // Without adding this `ref` param, re-running a query
1389
+ // could return a locally cached response, even if the
1390
+ // `ref` changed. This happens because the URL is
1391
+ // identical when the `ref` is not included. Caches may ignore
1392
+ // headers.
1393
+ //
1394
+ // The Prismic GraphQL API ignores the `ref` param.
1395
+ url.searchParams.set("ref", ref);
1396
+
1363
1397
  const query = url.searchParams.get("query");
1364
1398
  if (query) {
1365
- url.searchParams.set("query", minifyGraphQLQuery(query));
1399
+ url.searchParams.set(
1400
+ "query",
1401
+ // Compress the GraphQL query (if it exists) by
1402
+ // removing whitespace. This is done to
1403
+ // optimize the query size and avoid
1404
+ // hitting the upper limit of GET requests
1405
+ // (2048 characters).
1406
+ minifyGraphQLQuery(query),
1407
+ );
1366
1408
  }
1367
1409
 
1368
1410
  return (await this.fetchFn(url.toString(), {
@@ -1,3 +1,6 @@
1
+ import { isRepositoryName } from "./isRepositoryName";
2
+ import { PrismicError } from "./PrismicError";
3
+
1
4
  /**
2
5
  * Get a repository's Prismic GraphQL endpoint.
3
6
  *
@@ -8,5 +11,14 @@
8
11
  */
9
12
  export const getGraphQLEndpoint = <RepositoryName extends string>(
10
13
  repositoryName: RepositoryName,
11
- ): `https://${RepositoryName}.cdn.prismic.io/graphql` =>
12
- `https://${repositoryName}.cdn.prismic.io/graphql` as const;
14
+ ): `https://${RepositoryName}.cdn.prismic.io/graphql` => {
15
+ if (isRepositoryName(repositoryName)) {
16
+ return `https://${repositoryName}.cdn.prismic.io/graphql` as const;
17
+ } else {
18
+ throw new PrismicError(
19
+ `An invalid Prismic repository name was given: ${repositoryName}`,
20
+ undefined,
21
+ undefined,
22
+ );
23
+ }
24
+ };
@@ -0,0 +1,25 @@
1
+ import { isRepositoryName } from "./isRepositoryName";
2
+ import { PrismicError } from "./PrismicError";
3
+
4
+ /**
5
+ * Get a repository's Prismic Rest API V2 endpoint.
6
+ *
7
+ * @typeParam RepositoryName - Name of the Prismic repository.
8
+ * @param repositoryName - Name of the repository.
9
+ *
10
+ * @returns The repository's Prismic Rest API V2 endpoint
11
+ * @throws {@link Error} Thrown if an invalid repository name is provided.
12
+ */
13
+ export const getRepositoryEndpoint = <RepositoryName extends string>(
14
+ repositoryName: RepositoryName,
15
+ ): `https://${RepositoryName}.cdn.prismic.io/api/v2` => {
16
+ if (isRepositoryName(repositoryName)) {
17
+ return `https://${repositoryName}.cdn.prismic.io/api/v2` as const;
18
+ } else {
19
+ throw new PrismicError(
20
+ `An invalid Prismic repository name was given: ${repositoryName}`,
21
+ undefined,
22
+ undefined,
23
+ );
24
+ }
25
+ };
@@ -0,0 +1,23 @@
1
+ import { PrismicError } from "./PrismicError";
2
+
3
+ /**
4
+ * Get a Prismic repository's name from its standard Prismic Rest API V2 or
5
+ * GraphQL endpoint.
6
+ *
7
+ * @typeParam RepositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
8
+ * @param repositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
9
+ *
10
+ * @returns The Prismic repository's name.
11
+ * @throws {@link Error} Thrown if an invalid Prismic Rest API V2 endpoint is provided.
12
+ */
13
+ export const getRepositoryName = (repositoryEndpoint: string): string => {
14
+ try {
15
+ return new URL(repositoryEndpoint).hostname.split(".")[0];
16
+ } catch {
17
+ throw new PrismicError(
18
+ `An invalid Prismic Rest API V2 endpoint was provided: ${repositoryEndpoint}`,
19
+ undefined,
20
+ undefined,
21
+ );
22
+ }
23
+ };
package/src/index.ts CHANGED
@@ -1,7 +1,16 @@
1
1
  // Primary library API.
2
- export * from "./getEndpoint";
3
- export * from "./getGraphQLEndpoint";
4
- export * from "./buildQueryURL";
2
+ import { getRepositoryEndpoint } from "./getRepositoryEndpoint";
3
+ export { getRepositoryEndpoint };
4
+ /**
5
+ * @deprecated Renamed to `getRepositoryEndpoint`.
6
+ */
7
+ // TODO: Remove in v3.
8
+ export const getEndpoint = getRepositoryEndpoint;
9
+ export { getRepositoryName } from "./getRepositoryName";
10
+ export { getGraphQLEndpoint } from "./getGraphQLEndpoint";
11
+ export { isRepositoryName } from "./isRepositoryName";
12
+ export { isRepositoryEndpoint } from "./isRepositoryEndpoint";
13
+ export { buildQueryURL } from "./buildQueryURL";
5
14
  export { createClient, Client } from "./client";
6
15
 
7
16
  // Predicates API.
@@ -29,6 +38,7 @@ export * as cookie from "./cookie";
29
38
 
30
39
  // General types used throughout the project. These are made public to allow users to better type their projects.
31
40
  export type { ClientConfig } from "./client";
41
+ export type { QueryParams, BuildQueryURLArgs } from "./buildQueryURL";
32
42
  export type {
33
43
  FetchLike,
34
44
  HttpRequestLike,
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Determines if a string if a Prismic Rest API V2 endpoint. Note that any valid
3
+ * URL is a valid endpoint to support network proxies.
4
+ *
5
+ * @param input - Input to test.
6
+ *
7
+ * @returns `true` if `input` is a valid Prismic Rest API V2 endpoint, `false` otherwise.
8
+ */
9
+ export const isRepositoryEndpoint = (input: string): boolean => {
10
+ try {
11
+ new URL(input);
12
+
13
+ return true;
14
+ } catch {
15
+ return false;
16
+ }
17
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Determines if an input is a valid Prismic repository name.
3
+ *
4
+ * @param input - Input to test.
5
+ *
6
+ * @returns `true` if `input` is a valid Prismic repository name, `false` otherwise.
7
+ */
8
+ export const isRepositoryName = (input: string): boolean => {
9
+ return /^[a-zA-Z0-9][-a-zA-Z0-9]{2,}[a-zA-Z0-9]$/.test(input);
10
+ };
@@ -1,12 +0,0 @@
1
- /**
2
- * Get a repository's Prismic REST API V2 endpoint.
3
- *
4
- * @typeParam RepositoryName - Name of the Prismic repository.
5
- * @param repositoryName - Name of the repository.
6
- *
7
- * @returns The repository's Prismic REST API V2 endpoint
8
- */
9
- export const getEndpoint = <RepositoryName extends string>(
10
- repositoryName: RepositoryName,
11
- ): `https://${RepositoryName}.cdn.prismic.io/api/v2` =>
12
- `https://${repositoryName}.cdn.prismic.io/api/v2` as const;