@dotcms/client 0.0.1-beta.4 → 0.0.1-beta.40

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/next.cjs.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var consola = require('consola');
3
4
  var transforms = require('./transforms.cjs.js');
4
5
 
5
6
  class NavigationClient {
@@ -10,7 +11,7 @@ class NavigationClient {
10
11
  /**
11
12
  * Retrieves information about the dotCMS file and folder tree.
12
13
  * @param {NavigationApiOptions} options - The options for the Navigation API call. Defaults to `{ depth: 0, path: '/', languageId: 1 }`.
13
- * @returns {Promise<unknown>} - A Promise that resolves to the response from the DotCMS API.
14
+ * @returns {Promise<DotCMSNavigationItem[]>} - A Promise that resolves to the response from the DotCMS API.
14
15
  * @throws {Error} - Throws an error if the options are not valid.
15
16
  */
16
17
  async get(path, params) {
@@ -79,7 +80,7 @@ const DEFAULT_PAGE_CONTENTLETS_CONTENT = `
79
80
  */
80
81
  const buildPageQuery = ({ page, fragments, additionalQueries }) => {
81
82
  if (!page) {
82
- console.warn('No page query provided. The query will be used by fetching all content with _map. This may mean poor performance in the query. We suggest you provide a detailed query on page attribute.');
83
+ consola.consola.warn("[DotCMS Client]: No page query was found, so we're loading all content using _map. This might slow things down. For better performance, we recommend adding a specific query in the page attribute.");
83
84
  }
84
85
  return `
85
86
  fragment DotCMSPage on DotPage {
@@ -99,6 +100,7 @@ const buildPageQuery = ({ page, fragments, additionalQueries }) => {
99
100
  friendlyName
100
101
  workingInode
101
102
  url
103
+ pageURI
102
104
  hasLiveVersion
103
105
  deleted
104
106
  pageUrl
@@ -125,6 +127,22 @@ const buildPageQuery = ({ page, fragments, additionalQueries }) => {
125
127
  canEdit
126
128
  canLock
127
129
  canRead
130
+ runningExperimentId
131
+ urlContentMap {
132
+ _map
133
+ }
134
+ host {
135
+ identifier
136
+ hostName
137
+ googleMap
138
+ archived
139
+ contentType
140
+ }
141
+ vanityUrl {
142
+ action
143
+ forwardTo
144
+ uri
145
+ }
128
146
  conLanguage {
129
147
  id
130
148
  language
@@ -132,6 +150,9 @@ const buildPageQuery = ({ page, fragments, additionalQueries }) => {
132
150
  }
133
151
  template {
134
152
  drawed
153
+ anonymous
154
+ theme
155
+ identifier
135
156
  }
136
157
  containers {
137
158
  path
@@ -173,7 +194,24 @@ const buildPageQuery = ({ page, fragments, additionalQueries }) => {
173
194
  viewAs {
174
195
  visitor {
175
196
  persona {
197
+ modDate
198
+ inode
176
199
  name
200
+ identifier
201
+ keyTag
202
+ photo {
203
+ versionPath
204
+ }
205
+ }
206
+ }
207
+ persona {
208
+ modDate
209
+ inode
210
+ name
211
+ identifier
212
+ keyTag
213
+ photo {
214
+ versionPath
177
215
  }
178
216
  }
179
217
  language {
@@ -190,8 +228,8 @@ const buildPageQuery = ({ page, fragments, additionalQueries }) => {
190
228
 
191
229
  ${fragments ? fragments.join('\n\n') : ''}
192
230
 
193
- query PageContent($url: String!, $languageId: String, $mode: String) {
194
- page: page(url: $url, languageId: $languageId, pageMode: $mode) {
231
+ query PageContent($url: String!, $languageId: String, $mode: String, $personaId: String, $fireRules: Boolean, $publishDate: String, $siteId: String) {
232
+ page: page(url: $url, languageId: $languageId, pageMode: $mode, persona: $personaId, fireRules: $fireRules, publishDate: $publishDate, site: $siteId) {
195
233
  ...DotCMSPage
196
234
  ${page ? '...ClientPage' : ''}
197
235
  }
@@ -255,7 +293,6 @@ async function fetchGraphQL({ baseURL, body, headers }) {
255
293
  return await response.json();
256
294
  }
257
295
 
258
- var _PageClient_instances, _PageClient_isGraphQLRequest, _PageClient_getPageFromAPI, _PageClient_getPageFromGraphQL, _PageClient_mapToBackendParams;
259
296
  /**
260
297
  * Client for interacting with the DotCMS Page API.
261
298
  * Provides methods to retrieve and manipulate pages.
@@ -283,181 +320,120 @@ class PageClient {
283
320
  * ```
284
321
  */
285
322
  constructor(config, requestOptions) {
286
- _PageClient_instances.add(this);
287
323
  this.requestOptions = requestOptions;
288
324
  this.siteId = config.siteId || '';
289
325
  this.dotcmsUrl = config.dotcmsUrl;
290
326
  }
291
- get(url, options) {
292
- if (!options) {
293
- return transforms.__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_getPageFromAPI).call(this, url);
294
- }
295
- if (transforms.__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_isGraphQLRequest).call(this, options)) {
296
- return transforms.__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_getPageFromGraphQL).call(this, url, options);
297
- }
298
- return transforms.__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_getPageFromAPI).call(this, url, options);
299
- }
300
- }
301
- _PageClient_instances = new WeakSet(), _PageClient_isGraphQLRequest = function _PageClient_isGraphQLRequest(options) {
302
- return 'graphql' in options;
303
- }, _PageClient_getPageFromAPI =
304
- /**
305
- * Retrieves all the elements of a Page in your dotCMS system in JSON format.
306
- *
307
- * @param {string} path - The path of the page to retrieve
308
- * @param {PageRequestParams} params - The options for the Page API call
309
- * @returns {Promise<unknown>} A Promise that resolves to the page data
310
- * @throws {Error} Throws an error if the path parameter is missing or if the fetch request fails
311
- * @example
312
- * ```typescript
313
- * // Get a page with default parameters
314
- * const homePage = await pageClient.get('/');
315
- *
316
- * // Get a page with specific language and mode
317
- * const aboutPage = await pageClient.get('/about-us', {
318
- * languageId: 2,
319
- * mode: 'PREVIEW_MODE'
320
- * });
321
- *
322
- * // Get a page with persona targeting
323
- * const productPage = await pageClient.get('/products', {
324
- * personaId: 'persona-123',
325
- * depth: 2
326
- * });
327
- * ```
328
- */
329
- async function _PageClient_getPageFromAPI(path, params) {
330
- if (!path) {
331
- throw new Error("The 'path' parameter is required for the Page API");
332
- }
333
- // Remove leading and trailing slashes from the path.
334
- // Add a leading slash if it's missing.
335
- const pagePath = `/${path.replace(/^\/+/, '').replace(/\/+/g, '/')}${path.endsWith('/') ? '/' : ''}`;
336
- const pageParams = transforms.__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_mapToBackendParams).call(this, params || {});
337
- const urlParams = new URLSearchParams(pageParams).toString();
338
- const url = `${this.dotcmsUrl}/api/v1/page/json${pagePath}${urlParams ? `?${urlParams}` : ''}`;
339
- const response = await fetch(url, this.requestOptions);
340
- if (!response.ok) {
341
- const error = {
342
- status: response.status,
343
- message: transforms.ErrorMessages[response.status] || response.statusText
344
- };
345
- throw error;
346
- }
347
- return response.json().then((data) => data.entity);
348
- }, _PageClient_getPageFromGraphQL =
349
- /**
350
- * Retrieves a personalized page with associated content and navigation.
351
- *
352
- * @param {Object} options - Options for the personalized page request
353
- * @param {string} options.url - The URL of the page to retrieve
354
- * @param {string} options.languageId - The language ID for the page content
355
- * @param {string} options.mode - The rendering mode for the page
356
- * @param {string} options.pageFragment - GraphQL fragment for page data
357
- * @param {Record<string, string>} options.content - Content queries to include
358
- * @param {Record<string, string>} options.nav - Navigation queries to include
359
- * @returns {Promise<Object>} A Promise that resolves to the personalized page data with content and navigation
360
- * @example
361
- * ```typescript
362
- * // Get a personalized page with content and navigation
363
- * const personalizedPage = await pageClient.getPageFromGraphQL({
364
- * url: '/about-us',
365
- * languageId: '1',
366
- * mode: 'LIVE',
367
- * pageFragment: `
368
- * fragment PageFields on Page {
369
- * title
370
- * description
371
- * modDate
372
- * }
373
- * `,
374
- * content: {
375
- * blogs: `
376
- * search(query: "+contentType: blog", limit: 3) {
377
- * title
378
- * ...on Blog {
379
- * author {
380
- * title
381
- * }
382
- * }
383
- }
384
- * nav: {
385
- * mainNav: `
386
- * query MainNav {
387
- * Nav(identifier: "main-nav") {
388
- * title
389
- * items {
390
- * label
391
- * url
392
- * }
393
- * }
394
- * }
395
- * `
396
- * }
397
- * });
398
- * ```
399
- */
400
- async function _PageClient_getPageFromGraphQL(url, options) {
401
- const { languageId = '1', mode = 'LIVE', graphql = {} } = options || {};
402
- const { page, content = {}, variables, fragments } = graphql;
403
- const contentQuery = buildQuery(content);
404
- const completeQuery = buildPageQuery({
405
- page,
406
- fragments,
407
- additionalQueries: contentQuery
408
- });
409
- const requestVariables = {
410
- url,
411
- mode,
412
- languageId,
413
- ...variables
414
- };
415
- const requestHeaders = this.requestOptions.headers;
416
- const requestBody = JSON.stringify({ query: completeQuery, variables: requestVariables });
417
- try {
418
- const { data, errors } = await fetchGraphQL({
419
- baseURL: this.dotcmsUrl,
420
- body: requestBody,
421
- headers: requestHeaders
327
+ /**
328
+ * Retrieves a page from DotCMS using GraphQL.
329
+ *
330
+ * @param {string} url - The URL of the page to retrieve
331
+ * @param {DotCMSPageRequestParams} [options] - Options for the request
332
+ * @template T - The type of the page and content, defaults to DotCMSBasicPage and Record<string, unknown> | unknown
333
+ * @returns {Promise<DotCMSComposedPageResponse<T>>} A Promise that resolves to the page data
334
+ *
335
+ * @example Using GraphQL
336
+ * ```typescript
337
+ * const page = await pageClient.get<{ page: MyPageWithBanners; content: { blogPosts: { blogTitle: string } } }>(
338
+ * '/index',
339
+ * {
340
+ * languageId: '1',
341
+ * mode: 'LIVE',
342
+ * graphql: {
343
+ * page: `
344
+ * containers {
345
+ * containerContentlets {
346
+ * contentlets {
347
+ * ... on Banner {
348
+ * ...bannerFragment
349
+ * }
350
+ * }
351
+ * }
352
+ * `,
353
+ * content: {
354
+ * blogPosts: `
355
+ * BlogCollection(limit: 3) {
356
+ * ...blogFragment
357
+ * }
358
+ * `,
359
+ * },
360
+ * fragments: [
361
+ * `
362
+ * fragment bannerFragment on Banner {
363
+ * caption
364
+ * }
365
+ * `,
366
+ * `
367
+ * fragment blogFragment on Blog {
368
+ * title
369
+ * urlTitle
370
+ * }
371
+ * `
372
+ * ]
373
+ * }
374
+ * });
375
+ * ```
376
+ */
377
+ async get(url, options) {
378
+ const { languageId = '1', mode = 'LIVE', siteId = this.siteId, fireRules = false, personaId, publishDate, graphql = {} } = options || {};
379
+ const { page, content = {}, variables, fragments } = graphql;
380
+ const contentQuery = buildQuery(content);
381
+ const completeQuery = buildPageQuery({
382
+ page,
383
+ fragments,
384
+ additionalQueries: contentQuery
422
385
  });
423
- if (errors) {
424
- errors.forEach((error) => {
425
- throw new Error(error.message);
386
+ const requestVariables = {
387
+ // The url is expected to have a leading slash to comply on VanityURL Matching, some frameworks like Angular will not add the leading slash
388
+ url: url.startsWith('/') ? url : `/${url}`,
389
+ mode,
390
+ languageId,
391
+ personaId,
392
+ fireRules,
393
+ publishDate,
394
+ siteId,
395
+ ...variables
396
+ };
397
+ const requestHeaders = this.requestOptions.headers;
398
+ const requestBody = JSON.stringify({ query: completeQuery, variables: requestVariables });
399
+ try {
400
+ const { data, errors } = await fetchGraphQL({
401
+ baseURL: this.dotcmsUrl,
402
+ body: requestBody,
403
+ headers: requestHeaders
426
404
  });
405
+ if (errors) {
406
+ errors.forEach((error) => {
407
+ throw new Error(error.message);
408
+ });
409
+ }
410
+ const pageResponse = transforms.graphqlToPageEntity(data);
411
+ if (!pageResponse) {
412
+ throw new Error('No page data found');
413
+ }
414
+ const contentResponse = mapResponseData(data, Object.keys(content));
415
+ return {
416
+ pageAsset: pageResponse,
417
+ content: contentResponse,
418
+ graphql: {
419
+ query: completeQuery,
420
+ variables: requestVariables
421
+ }
422
+ };
427
423
  }
428
- const pageResponse = transforms.graphqlToPageEntity(data);
429
- if (!pageResponse) {
430
- throw new Error('No page data found');
424
+ catch (error) {
425
+ const errorMessage = {
426
+ error,
427
+ message: 'Failed to retrieve page data',
428
+ graphql: {
429
+ query: completeQuery,
430
+ variables: requestVariables
431
+ }
432
+ };
433
+ throw errorMessage;
431
434
  }
432
- const contentResponse = mapResponseData(data, Object.keys(content));
433
- return {
434
- page: pageResponse,
435
- content: contentResponse,
436
- errors
437
- };
438
- }
439
- catch (error) {
440
- const errorMessage = {
441
- error,
442
- message: 'Failed to retrieve page data',
443
- query: completeQuery,
444
- variables: requestVariables
445
- };
446
- throw errorMessage;
447
435
  }
448
- }, _PageClient_mapToBackendParams = function _PageClient_mapToBackendParams(params) {
449
- const backendParams = {
450
- hostId: params.siteId || this.siteId,
451
- mode: params.mode,
452
- language_id: params.languageId ? String(params.languageId) : undefined,
453
- 'com.dotmarketing.persona.id': params.personaId,
454
- fireRules: params.fireRules ? String(params.fireRules) : undefined,
455
- depth: params.depth ? String(params.depth) : undefined,
456
- publishDate: params.publishDate
457
- };
458
- // Remove undefined values
459
- return Object.fromEntries(Object.entries(backendParams).filter(([_, value]) => value !== undefined));
460
- };
436
+ }
461
437
 
462
438
  /**
463
439
  * Parses a string into a URL object.
@@ -470,7 +446,7 @@ function parseURL(url) {
470
446
  return new URL(url);
471
447
  }
472
448
  catch {
473
- console.error('Invalid URL:', url);
449
+ consola.consola.error('[DotCMS Client]: Invalid URL:', url);
474
450
  return undefined;
475
451
  }
476
452
  }