@dotcms/client 0.0.1-beta.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +565 -153
  2. package/index.cjs.js +1418 -741
  3. package/index.esm.js +1418 -732
  4. package/internal.cjs.d.ts +1 -0
  5. package/internal.cjs.default.js +1 -0
  6. package/internal.cjs.js +85 -0
  7. package/internal.cjs.mjs +2 -0
  8. package/internal.esm.d.ts +1 -0
  9. package/internal.esm.js +83 -0
  10. package/package.json +14 -17
  11. package/src/index.d.ts +1 -8
  12. package/src/internal.d.ts +1 -0
  13. package/src/lib/client/client.d.ts +1 -29
  14. package/src/lib/client/content/builders/collection/collection.d.ts +1 -1
  15. package/src/lib/client/content/content-api.d.ts +3 -6
  16. package/src/lib/client/content/shared/types.d.ts +1 -42
  17. package/src/lib/client/navigation/navigation-api.d.ts +3 -20
  18. package/src/lib/client/page/page-api.d.ts +14 -84
  19. package/src/lib/utils/graphql/transforms.d.ts +2 -13
  20. package/src/lib/utils/index.d.ts +0 -1
  21. package/next.cjs.d.ts +0 -1
  22. package/next.cjs.default.js +0 -1
  23. package/next.cjs.js +0 -553
  24. package/next.cjs.mjs +0 -2
  25. package/next.esm.d.ts +0 -1
  26. package/next.esm.js +0 -551
  27. package/src/lib/client/models/types.d.ts +0 -516
  28. package/src/lib/deprecated/editor/listeners/listeners.d.ts +0 -45
  29. package/src/lib/deprecated/editor/models/client.model.d.ts +0 -111
  30. package/src/lib/deprecated/editor/models/editor.model.d.ts +0 -62
  31. package/src/lib/deprecated/editor/models/inline-event.model.d.ts +0 -9
  32. package/src/lib/deprecated/editor/models/listeners.model.d.ts +0 -55
  33. package/src/lib/deprecated/editor/sdk-editor-vtl.d.ts +0 -1
  34. package/src/lib/deprecated/editor/sdk-editor.d.ts +0 -92
  35. package/src/lib/deprecated/editor/utils/editor.utils.d.ts +0 -159
  36. package/src/lib/deprecated/editor/utils/traditional-vtl.utils.d.ts +0 -4
  37. package/src/lib/deprecated/sdk-js-client.d.ts +0 -276
  38. package/src/lib/utils/page/common-utils.d.ts +0 -33
  39. package/src/next.d.ts +0 -1
  40. package/src/types.d.ts +0 -2
  41. package/transforms.cjs.js +0 -1145
  42. package/transforms.esm.js +0 -1139
  43. package/types.cjs.d.ts +0 -1
  44. package/types.cjs.default.js +0 -1
  45. package/types.cjs.js +0 -2
  46. package/types.cjs.mjs +0 -2
  47. package/types.esm.d.ts +0 -1
  48. package/types.esm.js +0 -1
package/next.cjs.js DELETED
@@ -1,553 +0,0 @@
1
- 'use strict';
2
-
3
- var transforms = require('./transforms.cjs.js');
4
-
5
- class NavigationClient {
6
- constructor(config, requestOptions) {
7
- this.requestOptions = requestOptions;
8
- this.BASE_URL = `${config?.dotcmsUrl}/api/v1/nav`;
9
- }
10
- /**
11
- * Retrieves information about the dotCMS file and folder tree.
12
- * @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
- * @throws {Error} - Throws an error if the options are not valid.
15
- */
16
- async get(path, params) {
17
- if (!path) {
18
- throw new Error("The 'path' parameter is required for the Navigation API");
19
- }
20
- const navParams = params ? this.mapToBackendParams(params) : {};
21
- const urlParams = new URLSearchParams(navParams).toString();
22
- const parsedPath = path.replace(/^\/+/, '/').replace(/\/+$/, '/');
23
- const url = `${this.BASE_URL}${parsedPath}${urlParams ? `?${urlParams}` : ''}`;
24
- const response = await fetch(url, this.requestOptions);
25
- if (!response.ok) {
26
- throw new Error(`Failed to fetch navigation data: ${response.statusText} - ${response.status}`);
27
- }
28
- return response.json().then((data) => data.entity);
29
- }
30
- mapToBackendParams(params) {
31
- const backendParams = {};
32
- if (params.depth) {
33
- backendParams['depth'] = String(params.depth);
34
- }
35
- if (params.languageId) {
36
- backendParams['language_id'] = String(params.languageId);
37
- }
38
- return backendParams;
39
- }
40
- }
41
-
42
- const DEFAULT_PAGE_CONTENTLETS_CONTENT = `
43
- publishDate
44
- inode
45
- identifier
46
- archived
47
- urlMap
48
- urlMap
49
- locked
50
- contentType
51
- creationDate
52
- modDate
53
- title
54
- baseType
55
- working
56
- live
57
- publishUser {
58
- firstName
59
- lastName
60
- }
61
- owner {
62
- lastName
63
- }
64
- conLanguage {
65
- language
66
- languageCode
67
- }
68
- modUser {
69
- firstName
70
- lastName
71
- }
72
- `;
73
- /**
74
- * Builds a GraphQL query for retrieving page content from DotCMS.
75
- *
76
- * @param {string} pageQuery - Custom fragment fields to include in the ClientPage fragment
77
- * @param {string} additionalQueries - Additional GraphQL queries to include in the main query
78
- * @returns {string} Complete GraphQL query string for page content
79
- */
80
- const buildPageQuery = ({ page, fragments, additionalQueries }) => {
81
- 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
- }
84
- return `
85
- fragment DotCMSPage on DotPage {
86
- publishDate
87
- type
88
- httpsRequired
89
- inode
90
- path
91
- identifier
92
- hasTitleImage
93
- sortOrder
94
- extension
95
- canRead
96
- pageURI
97
- canEdit
98
- archived
99
- friendlyName
100
- workingInode
101
- url
102
- hasLiveVersion
103
- deleted
104
- pageUrl
105
- shortyWorking
106
- mimeType
107
- locked
108
- stInode
109
- contentType
110
- creationDate
111
- liveInode
112
- name
113
- shortyLive
114
- modDate
115
- title
116
- baseType
117
- working
118
- canLock
119
- live
120
- isContentlet
121
- statusIcons
122
- canEdit
123
- canLock
124
- canRead
125
- canEdit
126
- canLock
127
- canRead
128
- conLanguage {
129
- id
130
- language
131
- languageCode
132
- }
133
- template {
134
- drawed
135
- }
136
- containers {
137
- path
138
- identifier
139
- maxContentlets
140
- containerStructures {
141
- id
142
- code
143
- structureId
144
- containerId
145
- contentTypeVar
146
- containerInode
147
- }
148
- containerContentlets {
149
- uuid
150
- contentlets {
151
- ${page ? DEFAULT_PAGE_CONTENTLETS_CONTENT : '_map'}
152
- }
153
- }
154
- }
155
- layout {
156
- header
157
- footer
158
- body {
159
- rows {
160
- columns {
161
- leftOffset
162
- styleClass
163
- width
164
- left
165
- containers {
166
- identifier
167
- uuid
168
- }
169
- }
170
- }
171
- }
172
- }
173
- viewAs {
174
- visitor {
175
- persona {
176
- name
177
- }
178
- }
179
- language {
180
- id
181
- languageCode
182
- countryCode
183
- language
184
- country
185
- }
186
- }
187
- }
188
-
189
- ${page ? ` fragment ClientPage on DotPage { ${page} } ` : ''}
190
-
191
- ${fragments ? fragments.join('\n\n') : ''}
192
-
193
- query PageContent($url: String!, $languageId: String, $mode: String) {
194
- page: page(url: $url, languageId: $languageId, pageMode: $mode) {
195
- ...DotCMSPage
196
- ${page ? '...ClientPage' : ''}
197
- }
198
-
199
- ${additionalQueries}
200
- }
201
- `;
202
- };
203
- /**
204
- * Converts a record of query strings into a single GraphQL query string.
205
- *
206
- * @param {Record<string, string>} queryData - Object containing named query strings
207
- * @returns {string} Combined query string or empty string if no queryData provided
208
- */
209
- function buildQuery(queryData) {
210
- if (!queryData)
211
- return '';
212
- return Object.entries(queryData)
213
- .map(([key, query]) => `${key}: ${query}`)
214
- .join(' ');
215
- }
216
- /**
217
- * Filters response data to include only specified keys.
218
- *
219
- * @param {Record<string, string>} responseData - Original response data object
220
- * @param {string[]} keys - Array of keys to extract from the response data
221
- * @returns {Record<string, string>} New object containing only the specified keys
222
- */
223
- function mapResponseData(responseData, keys) {
224
- return keys.reduce((accumulator, key) => {
225
- if (responseData[key] !== undefined) {
226
- accumulator[key] = responseData[key];
227
- }
228
- return accumulator;
229
- }, {});
230
- }
231
- /**
232
- * Executes a GraphQL query against the DotCMS API.
233
- *
234
- * @param {Object} options - Options for the fetch request
235
- * @param {string} options.body - GraphQL query string
236
- * @param {Record<string, string>} options.headers - HTTP headers for the request
237
- * @returns {Promise<any>} Parsed JSON response from the GraphQL API
238
- * @throws {Error} If the HTTP response is not successful
239
- */
240
- async function fetchGraphQL({ baseURL, body, headers }) {
241
- const url = new URL(baseURL);
242
- url.pathname = '/api/v1/graphql';
243
- const response = await fetch(url.toString(), {
244
- method: 'POST',
245
- body,
246
- headers
247
- });
248
- if (!response.ok) {
249
- const error = {
250
- status: response.status,
251
- message: transforms.ErrorMessages[response.status] || response.statusText
252
- };
253
- throw error;
254
- }
255
- return await response.json();
256
- }
257
-
258
- var _PageClient_instances, _PageClient_isGraphQLRequest, _PageClient_getPageFromAPI, _PageClient_getPageFromGraphQL, _PageClient_mapToBackendParams;
259
- /**
260
- * Client for interacting with the DotCMS Page API.
261
- * Provides methods to retrieve and manipulate pages.
262
- */
263
- class PageClient {
264
- /**
265
- * Creates a new PageClient instance.
266
- *
267
- * @param {DotCMSClientConfig} config - Configuration options for the DotCMS client
268
- * @param {RequestOptions} requestOptions - Options for fetch requests including authorization headers
269
- * @example
270
- * ```typescript
271
- * const pageClient = new PageClient(
272
- * {
273
- * dotcmsUrl: 'https://demo.dotcms.com',
274
- * authToken: 'your-auth-token',
275
- * siteId: 'demo.dotcms.com'
276
- * },
277
- * {
278
- * headers: {
279
- * Authorization: 'Bearer your-auth-token'
280
- * }
281
- * }
282
- * );
283
- * ```
284
- */
285
- constructor(config, requestOptions) {
286
- _PageClient_instances.add(this);
287
- this.requestOptions = requestOptions;
288
- this.siteId = config.siteId || '';
289
- this.dotcmsUrl = config.dotcmsUrl;
290
- }
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
- const normalizedParams = transforms.__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_mapToBackendParams).call(this, params || {});
334
- const queryParams = new URLSearchParams(normalizedParams).toString();
335
- // If the path starts with a slash, remove it to avoid double slashes in the final URL
336
- // Because the page path is part of api url path
337
- const pagePath = path.startsWith('/') ? path.slice(1) : path;
338
- const url = `${this.dotcmsUrl}/api/v1/page/json/${pagePath}?${queryParams}`;
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
422
- });
423
- if (errors) {
424
- errors.forEach((error) => {
425
- throw new Error(error.message);
426
- });
427
- }
428
- const pageResponse = transforms.graphqlToPageEntity(data);
429
- if (!pageResponse) {
430
- throw new Error('No page data found');
431
- }
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
- }
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
- };
461
-
462
- /**
463
- * Parses a string into a URL object.
464
- *
465
- * @param url - The URL string to parse
466
- * @returns A URL object if parsing is successful, undefined otherwise
467
- */
468
- function parseURL(url) {
469
- try {
470
- return new URL(url);
471
- }
472
- catch {
473
- console.error('Invalid URL:', url);
474
- return undefined;
475
- }
476
- }
477
- /**
478
- * Default configuration for the DotCMS client.
479
- */
480
- const defaultConfig = {
481
- dotcmsUrl: '',
482
- authToken: '',
483
- requestOptions: {}
484
- };
485
- /**
486
- * Client for interacting with the DotCMS REST API.
487
- * Provides access to content, page, and navigation functionality.
488
- */
489
- class DotCMSClient {
490
- /**
491
- * Creates a new DotCMS client instance.
492
- *
493
- * @param config - Configuration options for the client
494
- * @throws Warning if dotcmsUrl is invalid or authToken is missing
495
- */
496
- constructor(config = defaultConfig) {
497
- this.config = config;
498
- this.requestOptions = this.createAuthenticatedRequestOptions(this.config);
499
- // Initialize clients
500
- this.page = new PageClient(this.config, this.requestOptions);
501
- this.nav = new NavigationClient(this.config, this.requestOptions);
502
- this.content = new transforms.Content(this.requestOptions, this.config.dotcmsUrl);
503
- }
504
- /**
505
- * Creates request options with authentication headers.
506
- *
507
- * @param config - The client configuration
508
- * @returns Request options with authorization headers
509
- */
510
- createAuthenticatedRequestOptions(config) {
511
- return {
512
- ...config.requestOptions,
513
- headers: {
514
- ...config.requestOptions?.headers,
515
- Authorization: `Bearer ${config.authToken}`
516
- }
517
- };
518
- }
519
- }
520
- /**
521
- * Creates and returns a new DotCMS client instance.
522
- *
523
- * @param config - Configuration options for the client
524
- * @returns A configured DotCMS client instance
525
- * @example
526
- * ```typescript
527
- * const client = dotCMSCreateClient({
528
- * dotcmsUrl: 'https://demo.dotcms.com',
529
- * authToken: 'your-auth-token'
530
- * });
531
- *
532
- * // Use the client to fetch content
533
- * const pages = await client.page.get('/about-us');
534
- * ```
535
- */
536
- const createDotCMSClient = (clientConfig) => {
537
- const { dotcmsUrl, authToken } = clientConfig || {};
538
- const instanceUrl = parseURL(dotcmsUrl)?.origin;
539
- if (!instanceUrl) {
540
- throw new TypeError("Invalid configuration - 'dotcmsUrl' must be a valid URL");
541
- }
542
- if (!authToken) {
543
- throw new TypeError("Invalid configuration - 'authToken' is required");
544
- }
545
- const config = {
546
- ...clientConfig,
547
- authToken,
548
- dotcmsUrl: instanceUrl
549
- };
550
- return new DotCMSClient(config);
551
- };
552
-
553
- exports.createDotCMSClient = createDotCMSClient;
package/next.cjs.mjs DELETED
@@ -1,2 +0,0 @@
1
- export * from './next.cjs.js';
2
- export { _default as default } from './next.cjs.default.js';
package/next.esm.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/next";