@dotcms/client 1.0.0 → 1.0.1

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 (54) hide show
  1. package/.eslintrc.json +18 -0
  2. package/CLAUDE.md +253 -0
  3. package/MIGRATION.md +329 -0
  4. package/README.md +250 -434
  5. package/jest.config.ts +15 -0
  6. package/package.json +8 -25
  7. package/project.json +73 -0
  8. package/src/lib/client/client.spec.ts +147 -0
  9. package/src/lib/client/client.ts +125 -0
  10. package/src/lib/client/content/builders/collection/collection.spec.ts +514 -0
  11. package/src/lib/client/content/builders/collection/{collection.d.ts → collection.ts} +210 -19
  12. package/src/lib/client/content/builders/query/lucene-syntax/{Equals.d.ts → Equals.ts} +45 -11
  13. package/src/lib/client/content/builders/query/lucene-syntax/{Field.d.ts → Field.ts} +13 -5
  14. package/src/lib/client/content/builders/query/lucene-syntax/{NotOperand.d.ts → NotOperand.ts} +13 -5
  15. package/src/lib/client/content/builders/query/lucene-syntax/{Operand.d.ts → Operand.ts} +21 -7
  16. package/src/lib/client/content/builders/query/query.spec.ts +159 -0
  17. package/src/lib/client/content/builders/query/{query.d.ts → query.ts} +16 -5
  18. package/src/lib/client/content/builders/query/utils/{index.d.ts → index.ts} +49 -12
  19. package/src/lib/client/content/{content-api.d.ts → content-api.ts} +14 -4
  20. package/src/lib/client/content/shared/{const.d.ts → const.ts} +5 -3
  21. package/src/lib/client/content/shared/{types.d.ts → types.ts} +18 -2
  22. package/src/lib/client/content/shared/{utils.d.ts → utils.ts} +9 -1
  23. package/src/lib/client/models/{index.d.ts → index.ts} +8 -1
  24. package/src/lib/client/navigation/navigation-api.spec.ts +167 -0
  25. package/src/lib/client/navigation/navigation-api.ts +62 -0
  26. package/src/lib/client/page/page-api.spec.ts +359 -0
  27. package/src/lib/client/page/page-api.ts +197 -0
  28. package/src/lib/client/page/utils.ts +291 -0
  29. package/src/lib/utils/graphql/transforms.spec.ts +250 -0
  30. package/src/lib/utils/graphql/transforms.ts +128 -0
  31. package/tsconfig.json +22 -0
  32. package/tsconfig.lib.json +13 -0
  33. package/tsconfig.spec.json +9 -0
  34. package/index.cjs.d.ts +0 -1
  35. package/index.cjs.default.js +0 -1
  36. package/index.cjs.js +0 -1591
  37. package/index.cjs.mjs +0 -2
  38. package/index.esm.d.ts +0 -1
  39. package/index.esm.js +0 -1589
  40. package/internal.cjs.d.ts +0 -1
  41. package/internal.cjs.default.js +0 -1
  42. package/internal.cjs.js +0 -85
  43. package/internal.cjs.mjs +0 -2
  44. package/internal.esm.d.ts +0 -1
  45. package/internal.esm.js +0 -83
  46. package/src/lib/client/client.d.ts +0 -56
  47. package/src/lib/client/navigation/navigation-api.d.ts +0 -14
  48. package/src/lib/client/page/page-api.d.ts +0 -95
  49. package/src/lib/client/page/utils.d.ts +0 -41
  50. package/src/lib/utils/graphql/transforms.d.ts +0 -13
  51. /package/src/{index.d.ts → index.ts} +0 -0
  52. /package/src/{internal.d.ts → internal.ts} +0 -0
  53. /package/src/lib/client/content/builders/query/lucene-syntax/{index.d.ts → index.ts} +0 -0
  54. /package/src/lib/utils/{index.d.ts → index.ts} +0 -0
package/index.cjs.js DELETED
@@ -1,1591 +0,0 @@
1
- 'use strict';
2
-
3
- var consola = require('consola');
4
- var internal = require('./internal.cjs.js');
5
-
6
- /******************************************************************************
7
- Copyright (c) Microsoft Corporation.
8
-
9
- Permission to use, copy, modify, and/or distribute this software for any
10
- purpose with or without fee is hereby granted.
11
-
12
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
- PERFORMANCE OF THIS SOFTWARE.
19
- ***************************************************************************** */
20
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
-
22
-
23
- function __classPrivateFieldGet(receiver, state, kind, f) {
24
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
25
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
26
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
27
- }
28
-
29
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
30
- if (kind === "m") throw new TypeError("Private method is not writable");
31
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
32
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
33
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
34
- }
35
-
36
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
37
- var e = new Error(message);
38
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
39
- };
40
-
41
- /**
42
- * Default variant identifier used in the application.
43
- */
44
- /**
45
- * Fields that should not be formatted when sanitizing the query.
46
- * These fields are essential for maintaining the integrity of the content type.
47
- */
48
- const CONTENT_TYPE_MAIN_FIELDS = ['live', 'variant', 'contentType', 'languageId'];
49
- /**
50
- * URL endpoint for the content API search functionality.
51
- */
52
- const CONTENT_API_URL = '/api/content/_search';
53
-
54
- /**
55
- * @description
56
- * Sanitizes the query for the given content type.
57
- * It replaces the fields that are not content type fields with the correct format.
58
- * Example: +field: -> +contentTypeVar.field:
59
- *
60
- * @example
61
- *
62
- * ```ts
63
- * const query = '+field: value';
64
- * const contentType = 'contentTypeVar';
65
- * const sanitizedQuery = sanitizeQueryForContentType(query, contentType); // Output: '+contentTypeVar.field: value'
66
- * ```
67
- *
68
- * @export
69
- * @param {string} query - The query string to be sanitized.
70
- * @param {string} contentType - The content type to be used for formatting the fields.
71
- * @returns {string} The sanitized query string.
72
- */
73
- function sanitizeQueryForContentType(query, contentType) {
74
- return query.replace(/\+([^+:]*?):/g, (original, field) => {
75
- return !CONTENT_TYPE_MAIN_FIELDS.includes(field) // Fields that are not content type fields
76
- ? `+${contentType}.${field}:` // Should have this format: +contentTypeVar.field:
77
- : original; // Return the field if it is a content type field
78
- });
79
- }
80
-
81
- var _Field_query;
82
- /**
83
- * The `Field` class is used to build a query with a specific field.
84
- * A Lucene Field is a key used to search for a specific value in a document.
85
- *
86
- * @export
87
- * @class Field
88
- */
89
- class Field {
90
- /**
91
- * Creates an instance of the `Field` class.
92
- *
93
- * @param {string} query - The initial query string.
94
- */
95
- constructor(query) {
96
- this.query = query;
97
- _Field_query.set(this, '');
98
- __classPrivateFieldSet(this, _Field_query, this.query, "f");
99
- }
100
- /**
101
- * Appends a term to the query that should be included in the search.
102
- *
103
- * @example
104
- * ```typescript
105
- * const field = new Field("+myField");
106
- * field.equals("myValue");
107
- * ```
108
- *
109
- * @param {string} term - The term that should be included in the search.
110
- * @return {Equals} - An instance of `Equals`.
111
- * @memberof Field
112
- */
113
- equals(term) {
114
- return buildEquals(__classPrivateFieldGet(this, _Field_query, "f"), term);
115
- }
116
- }
117
- _Field_query = new WeakMap();
118
-
119
- var _NotOperand_query;
120
- /**
121
- * 'NotOperand' Is a Typescript class that provides the ability to use the NOT operand in the lucene query string.
122
- *
123
- * @export
124
- * @class NotOperand
125
- */
126
- class NotOperand {
127
- constructor(query) {
128
- this.query = query;
129
- _NotOperand_query.set(this, '');
130
- __classPrivateFieldSet(this, _NotOperand_query, this.query, "f");
131
- }
132
- /**
133
- * This method appends to the query a term that should be included in the search.
134
- *
135
- * @example
136
- * ```typescript
137
- * const notOperand = new NotOperand("+myField");
138
- * notOperand.equals("myValue");
139
- * ```
140
- *
141
- * @param {string} term - The term that should be included in the search.
142
- * @return {*} {Equals} - An instance of Equals.
143
- * @memberof NotOperand
144
- */
145
- equals(term) {
146
- return buildEquals(__classPrivateFieldGet(this, _NotOperand_query, "f"), term);
147
- }
148
- }
149
- _NotOperand_query = new WeakMap();
150
-
151
- var _Operand_query;
152
- /**
153
- * 'Operand' Is a Typescript class that provides the ability to use operands in the lucene query string.}
154
- * An operand is a logical operator used to join two or more conditions in a query.
155
- *
156
- * @export
157
- * @class Operand
158
- */
159
- class Operand {
160
- constructor(query) {
161
- this.query = query;
162
- _Operand_query.set(this, '');
163
- __classPrivateFieldSet(this, _Operand_query, this.query, "f");
164
- }
165
- /**
166
- * This method appends to the query a term that should be excluded in the search.
167
- *
168
- * Ex: "-myValue"
169
- *
170
- * @param {string} field - The field that should be excluded in the search.
171
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
172
- * @memberof Operand
173
- */
174
- excludeField(field) {
175
- return buildExcludeField(__classPrivateFieldGet(this, _Operand_query, "f"), field);
176
- }
177
- /**
178
- * This method appends to the query a field that should be included in the search.
179
- *
180
- * Ex: "+myField:"
181
- *
182
- * @param {string} field - The field that should be included in the search.
183
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
184
- * @memberof Operand
185
- */
186
- field(field) {
187
- return buildField(__classPrivateFieldGet(this, _Operand_query, "f"), field);
188
- }
189
- /**
190
- * This method appends to the query a term that should be included in the search.
191
- *
192
- * Ex: myValue or "My value"
193
- *
194
- * @param {string} term - The term that should be included in the search.
195
- * @return {*} {Equals} - An instance of Equals.
196
- * @memberof Operand
197
- */
198
- equals(term) {
199
- return buildEquals(__classPrivateFieldGet(this, _Operand_query, "f"), term);
200
- }
201
- }
202
- _Operand_query = new WeakMap();
203
-
204
- /**
205
- * Enum for common Operands
206
- *
207
- * @export
208
- * @enum {number}
209
- */
210
- var OPERAND;
211
- (function (OPERAND) {
212
- OPERAND["OR"] = "OR";
213
- OPERAND["AND"] = "AND";
214
- OPERAND["NOT"] = "NOT";
215
- })(OPERAND || (OPERAND = {}));
216
- /**
217
- * This function removes extra spaces from a string.
218
- *
219
- * @example
220
- * ```ts
221
- * sanitizeQuery(" my query "); // Output: "my query"
222
- * ```
223
- *
224
- * @export
225
- * @param {string} str
226
- * @return {*} {string}
227
- */
228
- function sanitizeQuery(str) {
229
- return str.replace(/\s{2,}/g, ' ').trim();
230
- }
231
- /**
232
- * This function sanitizes a term by adding quotes if it contains spaces.
233
- * In lucene, a term with spaces should be enclosed in quotes.
234
- *
235
- * @example
236
- * ```ts
237
- * sanitizePhrases(`my term`); // Output: `"my term"`
238
- * sanitizePhrases(`myterm`); // Output: `myterm`
239
- * ```
240
- *
241
- * @export
242
- * @param {string} term
243
- * @return {*} {string}
244
- */
245
- function sanitizePhrases(term) {
246
- return term.includes(' ') ? `'${term}'` : term;
247
- }
248
- /**
249
- * This function builds a term to be used in a lucene query.
250
- * We need to sanitize the term before adding it to the query.
251
- *
252
- * @example
253
- * ```ts
254
- * const equals = buildEquals("+myField: ", "myValue"); // Current query: "+myField: myValue"
255
- * ```
256
- *
257
- * @export
258
- * @param {string} query
259
- * @param {string} term
260
- * @return {*} {Equals}
261
- */
262
- function buildEquals(query, term) {
263
- const newQuery = query + sanitizePhrases(term);
264
- return new Equals(newQuery);
265
- }
266
- /**
267
- * This function builds a term to be used in a lucene query.
268
- * We need to sanitize the raw query before adding it to the query.
269
- *
270
- * @example
271
- * ```ts
272
- * const query = "+myField: myValue";
273
- * const field = buildRawEquals(query, "-myField2: myValue2"); // Current query: "+myField: myValue -myField2: myValue"
274
- * ```
275
- *
276
- * @export
277
- * @param {string} query
278
- * @param {string} raw
279
- * @return {*} {Equals}
280
- */
281
- function buildRawEquals(query, raw) {
282
- const newQuery = query + ` ${raw}`;
283
- return new Equals(sanitizeQuery(newQuery));
284
- }
285
- /**
286
- * This function builds a field to be used in a lucene query.
287
- * We need to format the field before adding it to the query.
288
- *
289
- * @example
290
- * ```ts
291
- * const field = buildField("+myField: ", "myValue"); // Current query: "+myField: myValue"
292
- * ```
293
- *
294
- * @export
295
- * @param {string} query
296
- * @param {string} field
297
- * @return {*} {Field}
298
- */
299
- function buildField(query, field) {
300
- const newQuery = query + ` +${field}:`;
301
- return new Field(newQuery);
302
- }
303
- /**
304
- * This function builds an exclude field to be used in a lucene query.
305
- * We need to format the field before adding it to the query.
306
- *
307
- * @example
308
- * ```ts
309
- * const query = "+myField: myValue";
310
- * const field = buildExcludeField(query, "myField2"); // Current query: "+myField: myValue -myField2:"
311
- * ```
312
- *
313
- * @export
314
- * @param {string} query
315
- * @param {string} field
316
- * @return {*} {Field}
317
- */
318
- function buildExcludeField(query, field) {
319
- const newQuery = query + ` -${field}:`;
320
- return new Field(newQuery);
321
- }
322
- /**
323
- * This function builds an operand to be used in a lucene query.
324
- * We need to format the operand before adding it to the query.
325
- *
326
- * @example
327
- * <caption>E.g. Using the AND operand</caption>
328
- * ```ts
329
- * const query = "+myField: myValue";
330
- * const field = buildOperand(query, OPERAND.AND); // Current query: "+myField: myValue AND"
331
- * ```
332
- * @example
333
- * <caption>E.g. Using the OR operand</caption>
334
- * ```ts
335
- * const query = "+myField: myValue";
336
- * const field = buildOperand(query, OPERAND.OR); // Current query: "+myField: myValue OR"
337
- * ```
338
- * @export
339
- * @param {string} query
340
- * @param {OPERAND} operand
341
- * @return {*} {Operand}
342
- */
343
- function buildOperand(query, operand) {
344
- const newQuery = query + ` ${operand} `;
345
- return new Operand(newQuery);
346
- }
347
- /**
348
- * This function builds a NOT operand to be used in a lucene query.
349
- * We need to format the operand before adding it to the query.
350
- *
351
- * @example
352
- * ```ts
353
- * const query = "+myField: myValue";
354
- * const field = buildNotOperand(query); // Current query: "+myField: myValue NOT"
355
- * ```
356
- *
357
- * @export
358
- * @param {string} query
359
- * @return {*} {NotOperand}
360
- */
361
- function buildNotOperand(query) {
362
- const newQuery = query + ` ${OPERAND.NOT} `;
363
- return new NotOperand(newQuery);
364
- }
365
-
366
- var _Equals_query;
367
- /**
368
- * 'Equal' Is a Typescript class that provides the ability to use terms in the lucene query string.
369
- * A term is a value used to search for a specific value in a document. It can be a word or a phrase.
370
- *
371
- * Ex: myValue or "My Value"
372
- *
373
- * @export
374
- * @class Equal
375
- */
376
- class Equals {
377
- constructor(query) {
378
- this.query = query;
379
- _Equals_query.set(this, '');
380
- __classPrivateFieldSet(this, _Equals_query, this.query, "f");
381
- }
382
- /**
383
- * This method appends to the query a term that should be excluded in the search.
384
- *
385
- * @example
386
- * ```ts
387
- * const equals = new Equals("+myField: myValue");
388
- * equals.excludeField("myField2").equals("myValue2"); // Current query: "+myField: myValue -myField2: myValue2"
389
- * ```
390
- *
391
- * @param {string} field - The field that should be excluded in the search.
392
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
393
- * @memberof Equal
394
- */
395
- excludeField(field) {
396
- return buildExcludeField(__classPrivateFieldGet(this, _Equals_query, "f"), field);
397
- }
398
- /**
399
- * This method appends to the query a field that should be included in the search.
400
- *
401
- * @example
402
- * ```ts
403
- * const equals = new Equals("+myField: myValue");
404
- * equals.field("myField2").equals("myValue2"); // Current query: "+myField: myValue +myField2: myValue2"
405
- *```
406
- * @param {string} field - The field that should be included in the search.
407
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
408
- * @memberof Equal
409
- */
410
- field(field) {
411
- return buildField(__classPrivateFieldGet(this, _Equals_query, "f"), field);
412
- }
413
- /**
414
- * This method appends to the query an operand to use logic operators in the query.
415
- *
416
- * @example
417
- * @example
418
- * ```ts
419
- * const equals = new Equals("+myField: myValue");
420
- * equals.or().field("myField2").equals("myValue2"); // Current query: "+myField: myValue OR +myField2: myValue2"
421
- * ```
422
- *
423
- * @return {*} {Operand} - An instance of a Lucene Operand. An operand is a logical operator used to combine terms or phrases in a query.
424
- * @memberof Equal
425
- */
426
- or() {
427
- return buildOperand(__classPrivateFieldGet(this, _Equals_query, "f"), OPERAND.OR);
428
- }
429
- /**
430
- * This method appends to the query an operand to use logic operators in the query.
431
- *
432
- * @example
433
- * ```ts
434
- * const equals = new Equals("+myField: myValue");
435
- * equals.and().field("myField2").equals("myValue2"); // Current query: "+myField: myValue AND +myField2: myValue2"
436
- * ```
437
- *
438
- * @return {*} {Operand} - An instance of a Lucene Operand. An operand is a logical operator used to combine terms or phrases in a query.
439
- * @memberof Equal
440
- */
441
- and() {
442
- return buildOperand(__classPrivateFieldGet(this, _Equals_query, "f"), OPERAND.AND);
443
- }
444
- /**
445
- * This method appends to the query an operand to use logic operators in the query.
446
- *
447
- * @example
448
- * ```ts
449
- * const equals = new Equals("+myField: myValue");
450
- * equals.not().field("myField").equals("myValue2"); // Current query: "+myField: myValue NOT +myField: myValue2"
451
- * ```
452
- *
453
- * @return {*} {NotOperand} - An instance of a Lucene Not Operand. A not operand is a logical operator used to exclude terms or phrases in a query.
454
- * @memberof Equal
455
- */
456
- not() {
457
- return buildNotOperand(__classPrivateFieldGet(this, _Equals_query, "f"));
458
- }
459
- /**
460
- * This method allows to pass a raw query string to the query builder.
461
- * This raw query should end in a Lucene Equal.
462
- * This method is useful when you want to append a complex query or an already written query to the query builder.
463
- *
464
- * @example
465
- * ```ts
466
- * // This builds the follow raw query "+myField: value AND (someOtherValue OR anotherValue)"
467
- * const equals = new Equals("+myField: value");
468
- * equals.raw("+myField2: value2"); // Current query: "+myField: value +myField2: anotherValue"
469
- * ```
470
- *
471
- * @param {string} query - A raw query string.
472
- * @return {*} {Equal} - An instance of a Lucene Equal. A term is a value used to search for a specific value in a document.
473
- * @memberof QueryBuilder
474
- */
475
- raw(query) {
476
- return buildRawEquals(__classPrivateFieldGet(this, _Equals_query, "f"), query);
477
- }
478
- /**
479
- * This method returns the final query string.
480
- *
481
- * @example
482
- * ```ts
483
- * const equals = new Equals("+myField: myValue");
484
- * equals.field("myField2").equals("myValue2").build(); // Returns "+myField: myValue +myField2: myValue2"
485
- * ```
486
- *
487
- * @return {*} {string} - The final query string.
488
- * @memberof Equal
489
- */
490
- build() {
491
- return sanitizeQuery(__classPrivateFieldGet(this, _Equals_query, "f"));
492
- }
493
- }
494
- _Equals_query = new WeakMap();
495
-
496
- var _QueryBuilder_query;
497
- /**
498
- * 'QueryBuilder' Is a Typescript class that provides the ability to build a query string using the Lucene syntax in a more readable way.
499
- * @example
500
- * ```ts
501
- * const qb = new QueryBuilder();
502
- * const query = qb
503
- * .field('contentType')
504
- * .equals('Blog')
505
- * .field('conhost')
506
- * .equals('my-super-cool-site')
507
- * .build(); // Output: `+contentType:Blog +conhost:my-super-cool-site"`
508
- * ```
509
- *
510
- * @example
511
- * ```ts
512
- * const qb = new QueryBuilder();
513
- * const query = qb
514
- * .field('contentType')
515
- * .equals('Blog')
516
- * .field('title')
517
- * .equals('Football')
518
- * .excludeField('summary')
519
- * .equals('Lionel Messi')
520
- * .build(); // Output: `+contentType:Blog +title:Football -summary:"Lionel Messi"`
521
- * ```
522
- * @export
523
- * @class QueryBuilder
524
- */
525
- class QueryBuilder {
526
- constructor() {
527
- _QueryBuilder_query.set(this, '');
528
- }
529
- /**
530
- * This method appends to the query a field that should be included in the search.
531
- *
532
- * @example
533
- * ```ts
534
- * const qb = new QueryBuilder();
535
- * qb.field("+myField: ", "myValue"); // Current query: "+myField: myValue"
536
- * ```
537
- *
538
- * @param {string} field - The field that should be included in the search.
539
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
540
- * @memberof QueryBuilder
541
- */
542
- field(field) {
543
- return buildField(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), field);
544
- }
545
- /**
546
- * This method appends to the query a field that should be excluded from the search.
547
- *
548
- * @example
549
- * ```ts
550
- * const qb = new QueryBuilder();
551
- * qb.excludeField("myField").equals("myValue"); // Current query: "-myField: myValue"
552
- * ```
553
- *
554
- * @param {string} field - The field that should be excluded from the search.
555
- * @return {*} {Field} - An instance of a Lucene Exclude Field. An exclude field is a key used to exclude for a specific value in a document.
556
- * @memberof QueryBuilder
557
- */
558
- excludeField(field) {
559
- return buildExcludeField(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), field);
560
- }
561
- /**
562
- * This method allows to pass a raw query string to the query builder.
563
- * This raw query should end in Equals.
564
- * This method is useful when you want to append a complex query or an already written query to the query builder.
565
- *
566
- * @example
567
- * ```ts
568
- * const qb = new QueryBuilder();
569
- * qb.raw("+myField: value AND (someOtherValue OR anotherValue)"); // Current query: "+myField: value AND (someOtherValue OR anotherValue)"
570
- * ```
571
- *
572
- * @param {string} query - A raw query string.
573
- * @return {*} {Equals} - An instance of Equals. A term is a value used to search for a specific value in a document.
574
- * @memberof QueryBuilder
575
- */
576
- raw(query) {
577
- return buildRawEquals(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), query);
578
- }
579
- }
580
- _QueryBuilder_query = new WeakMap();
581
-
582
- var _CollectionBuilder_page, _CollectionBuilder_limit, _CollectionBuilder_depth, _CollectionBuilder_render, _CollectionBuilder_sortBy, _CollectionBuilder_contentType, _CollectionBuilder_defaultQuery, _CollectionBuilder_query, _CollectionBuilder_rawQuery, _CollectionBuilder_languageId, _CollectionBuilder_draft, _CollectionBuilder_serverUrl, _CollectionBuilder_requestOptions;
583
- /**
584
- * Creates a Builder to filter and fetch content from the content API for a specific content type.
585
- *
586
- * @export
587
- * @class CollectionBuilder
588
- * @template T Represents the type of the content type to fetch. Defaults to unknown.
589
- */
590
- class CollectionBuilder {
591
- /**
592
- * Creates an instance of CollectionBuilder.
593
- * @param {ClientOptions} requestOptions Options for the client request.
594
- * @param {string} serverUrl The server URL.
595
- * @param {string} contentType The content type to fetch.
596
- * @memberof CollectionBuilder
597
- */
598
- constructor(requestOptions, serverUrl, contentType) {
599
- _CollectionBuilder_page.set(this, 1);
600
- _CollectionBuilder_limit.set(this, 10);
601
- _CollectionBuilder_depth.set(this, 0);
602
- _CollectionBuilder_render.set(this, false);
603
- _CollectionBuilder_sortBy.set(this, void 0);
604
- _CollectionBuilder_contentType.set(this, void 0);
605
- _CollectionBuilder_defaultQuery.set(this, void 0);
606
- _CollectionBuilder_query.set(this, void 0);
607
- _CollectionBuilder_rawQuery.set(this, void 0);
608
- _CollectionBuilder_languageId.set(this, 1);
609
- _CollectionBuilder_draft.set(this, false);
610
- _CollectionBuilder_serverUrl.set(this, void 0);
611
- _CollectionBuilder_requestOptions.set(this, void 0);
612
- __classPrivateFieldSet(this, _CollectionBuilder_requestOptions, requestOptions, "f");
613
- __classPrivateFieldSet(this, _CollectionBuilder_serverUrl, serverUrl, "f");
614
- __classPrivateFieldSet(this, _CollectionBuilder_contentType, contentType, "f");
615
- // Build the default query with the contentType field
616
- __classPrivateFieldSet(this, _CollectionBuilder_defaultQuery, new QueryBuilder().field('contentType').equals(__classPrivateFieldGet(this, _CollectionBuilder_contentType, "f")), "f");
617
- }
618
- /**
619
- * Returns the sort query in the format: field order, field order, ...
620
- *
621
- * @readonly
622
- * @private
623
- * @memberof CollectionBuilder
624
- */
625
- get sort() {
626
- return __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")?.map((sort) => `${sort.field} ${sort.order}`).join(',');
627
- }
628
- /**
629
- * Returns the offset for pagination.
630
- *
631
- * @readonly
632
- * @private
633
- * @memberof CollectionBuilder
634
- */
635
- get offset() {
636
- return __classPrivateFieldGet(this, _CollectionBuilder_limit, "f") * (__classPrivateFieldGet(this, _CollectionBuilder_page, "f") - 1);
637
- }
638
- /**
639
- * Returns the full URL for the content API.
640
- *
641
- * @readonly
642
- * @private
643
- * @memberof CollectionBuilder
644
- */
645
- get url() {
646
- return `${__classPrivateFieldGet(this, _CollectionBuilder_serverUrl, "f")}${CONTENT_API_URL}`;
647
- }
648
- /**
649
- * Returns the current query built.
650
- *
651
- * @readonly
652
- * @private
653
- * @memberof CollectionBuilder
654
- */
655
- get currentQuery() {
656
- return __classPrivateFieldGet(this, _CollectionBuilder_query, "f") ?? __classPrivateFieldGet(this, _CollectionBuilder_defaultQuery, "f");
657
- }
658
- /**
659
- * Filters the content by the specified language ID.
660
- *
661
- * @example
662
- * ```typescript
663
- * const client = new DotCMSClient(config);
664
- * const collectionBuilder = client.content.getCollection("Blog");
665
- * collectionBuilder.language(1);
666
- * ```
667
- *
668
- * @param {number | string} languageId The language ID to filter the content by.
669
- * @return {CollectionBuilder} A CollectionBuilder instance.
670
- * @memberof CollectionBuilder
671
- */
672
- language(languageId) {
673
- __classPrivateFieldSet(this, _CollectionBuilder_languageId, languageId, "f");
674
- return this;
675
- }
676
- /**
677
- * Setting this to true will server side render (using velocity) any widgets that are returned by the content query.
678
- *
679
- * More information here: {@link https://www.dotcms.com/docs/latest/content-api-retrieval-and-querying#ParamsOptional}
680
- *
681
- * @return {CollectionBuilder} A CollectionBuilder instance.
682
- * @memberof CollectionBuilder
683
- */
684
- render() {
685
- __classPrivateFieldSet(this, _CollectionBuilder_render, true, "f");
686
- return this;
687
- }
688
- /**
689
- * Sorts the content by the specified fields and orders.
690
- *
691
- * @example
692
- * ```typescript
693
- * const client = new DotCMSClient(config);
694
- * const collectionBuilder = client.content.getCollection("Blog");
695
- * const sortBy = [{ field: 'title', order: 'asc' }, { field: 'modDate', order: 'desc' }];
696
- * collectionBuilder("Blog").sortBy(sortBy);
697
- * ```
698
- *
699
- * @param {SortBy[]} sortBy Array of constraints to sort the content by.
700
- * @return {CollectionBuilder} A CollectionBuilder instance.
701
- * @memberof CollectionBuilder
702
- */
703
- sortBy(sortBy) {
704
- __classPrivateFieldSet(this, _CollectionBuilder_sortBy, sortBy, "f");
705
- return this;
706
- }
707
- /**
708
- * Sets the maximum amount of content to fetch.
709
- *
710
- * @param {number} limit The maximum amount of content to fetch.
711
- * @return {CollectionBuilder} A CollectionBuilder instance.
712
- * @memberof CollectionBuilder
713
- */
714
- limit(limit) {
715
- __classPrivateFieldSet(this, _CollectionBuilder_limit, limit, "f");
716
- return this;
717
- }
718
- /**
719
- * Sets the page number to fetch.
720
- *
721
- * @param {number} page The page number to fetch.
722
- * @return {CollectionBuilder} A CollectionBuilder instance.
723
- * @memberof CollectionBuilder
724
- */
725
- page(page) {
726
- __classPrivateFieldSet(this, _CollectionBuilder_page, page, "f");
727
- return this;
728
- }
729
- query(arg) {
730
- if (typeof arg === 'string') {
731
- __classPrivateFieldSet(this, _CollectionBuilder_rawQuery, arg, "f");
732
- return this;
733
- }
734
- if (typeof arg !== 'function') {
735
- throw new Error(`Parameter for query method should be a buildQuery function or a string.\nExample:\nclient.content.getCollection('Activity').query((queryBuilder) => queryBuilder.field('title').equals('Hello World'))\nor\nclient.content.getCollection('Activity').query('+Activity.title:"Hello World"') \nSee documentation for more information.`);
736
- }
737
- const builtQuery = arg(new QueryBuilder());
738
- // This can be use in Javascript so we cannot rely on the type checking
739
- if (builtQuery instanceof Equals) {
740
- __classPrivateFieldSet(this, _CollectionBuilder_query, builtQuery.raw(this.currentQuery.build()), "f");
741
- }
742
- else {
743
- throw new Error('Provided query is not valid. A query should end in an equals method call.\nExample:\n(queryBuilder) => queryBuilder.field("title").equals("Hello World")\nSee documentation for more information.');
744
- }
745
- return this;
746
- }
747
- /**
748
- * Retrieves draft content.
749
- * @example
750
- * ```ts
751
- * const client = new DotCMSClient(config);
752
- * const collectionBuilder = client.content.getCollection("Blog");
753
- * collectionBuilder
754
- * .draft() // This will retrieve draft/working content
755
- * .then((response) => // Your code here })
756
- * .catch((error) => // Your code here })
757
- * ```
758
- *
759
- * @return {CollectionBuilder} A CollectionBuilder instance.
760
- * @memberof CollectionBuilder
761
- */
762
- draft() {
763
- __classPrivateFieldSet(this, _CollectionBuilder_draft, true, "f");
764
- return this;
765
- }
766
- /**
767
- * Filters the content by a variant ID for [Experiments](https://www.dotcms.com/docs/latest/experiments-and-a-b-testing)
768
- *
769
- * More information here: {@link https://www.dotcms.com/docs/latest/content-api-retrieval-and-querying#ParamsOptional}
770
- *
771
- * @example
772
- * ```ts
773
- * const client = new DotCMSClient(config);
774
- * const collectionBuilder = client.content.getCollection("Blog");
775
- * collectionBuilder
776
- * .variant("YOUR_VARIANT_ID")
777
- * .then((response) => // Your code here })
778
- * .catch((error) => // Your code here })
779
- * ```
780
- *
781
- * @param {string} variantId A string that represents a variant ID.
782
- * @return {CollectionBuilder} A CollectionBuilder instance.
783
- * @memberof CollectionBuilder
784
- */
785
- variant(variantId) {
786
- __classPrivateFieldSet(this, _CollectionBuilder_query, this.currentQuery.field('variant').equals(variantId), "f");
787
- return this;
788
- }
789
- /**
790
- * Sets the depth of the relationships of the content.
791
- * Specifies the depth of related content to return in the results.
792
- *
793
- * More information here: {@link https://www.dotcms.com/docs/latest/content-api-retrieval-and-querying#ParamsOptional}
794
- *
795
- * @example
796
- * ```ts
797
- * const client = new DotCMSClient(config);
798
- * const collectionBuilder = client.content.getCollection("Blog");
799
- * collectionBuilder
800
- * .depth(1)
801
- * .then((response) => // Your code here })
802
- * .catch((error) => // Your code here })
803
- * ```
804
- *
805
- * @param {number} depth The depth of the relationships of the content.
806
- * @return {CollectionBuilder} A CollectionBuilder instance.
807
- * @memberof CollectionBuilder
808
- */
809
- depth(depth) {
810
- if (depth < 0 || depth > 3) {
811
- throw new Error('Depth value must be between 0 and 3');
812
- }
813
- __classPrivateFieldSet(this, _CollectionBuilder_depth, depth, "f");
814
- return this;
815
- }
816
- /**
817
- * Executes the fetch and returns a promise that resolves to the content or rejects with an error.
818
- *
819
- * @example
820
- * ```ts
821
- * const client = new DotCMSClient(config);
822
- * const collectionBuilder = client.content.getCollection("Blog");
823
- * collectionBuilder
824
- * .limit(10)
825
- * .then((response) => // Your code here })
826
- * .catch((error) => // Your code here })
827
- * ```
828
- *
829
- * @param {OnFullfilled} [onfulfilled] A callback that is called when the fetch is successful.
830
- * @param {OnRejected} [onrejected] A callback that is called when the fetch fails.
831
- * @return {Promise<GetCollectionResponse<T> | GetCollectionError>} A promise that resolves to the content or rejects with an error.
832
- * @memberof CollectionBuilder
833
- */
834
- then(onfulfilled, onrejected) {
835
- return this.fetch().then(async (response) => {
836
- const data = await response.json();
837
- if (response.ok) {
838
- const formattedResponse = this.formatResponse(data);
839
- const finalResponse = typeof onfulfilled === 'function'
840
- ? onfulfilled(formattedResponse)
841
- : formattedResponse;
842
- return finalResponse;
843
- }
844
- else {
845
- return {
846
- status: response.status,
847
- ...data
848
- };
849
- }
850
- }, onrejected);
851
- }
852
- /**
853
- * Formats the response to the desired format.
854
- *
855
- * @private
856
- * @param {GetCollectionRawResponse<T>} data The raw response data.
857
- * @return {GetCollectionResponse<T>} The formatted response.
858
- * @memberof CollectionBuilder
859
- */
860
- formatResponse(data) {
861
- const contentlets = data.entity.jsonObjectView.contentlets;
862
- const total = data.entity.resultsSize;
863
- const mappedResponse = {
864
- contentlets,
865
- total,
866
- page: __classPrivateFieldGet(this, _CollectionBuilder_page, "f"),
867
- size: contentlets.length
868
- };
869
- return __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")
870
- ? {
871
- ...mappedResponse,
872
- sortedBy: __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")
873
- }
874
- : mappedResponse;
875
- }
876
- /**
877
- * Calls the content API to fetch the content.
878
- *
879
- * @private
880
- * @return {Promise<Response>} The fetch response.
881
- * @memberof CollectionBuilder
882
- */
883
- fetch() {
884
- const finalQuery = this.currentQuery
885
- .field('languageId')
886
- .equals(__classPrivateFieldGet(this, _CollectionBuilder_languageId, "f").toString())
887
- .field('live')
888
- .equals((!__classPrivateFieldGet(this, _CollectionBuilder_draft, "f")).toString())
889
- .build();
890
- const sanitizedQuery = sanitizeQueryForContentType(finalQuery, __classPrivateFieldGet(this, _CollectionBuilder_contentType, "f"));
891
- const query = __classPrivateFieldGet(this, _CollectionBuilder_rawQuery, "f") ? `${sanitizedQuery} ${__classPrivateFieldGet(this, _CollectionBuilder_rawQuery, "f")}` : sanitizedQuery;
892
- return fetch(this.url, {
893
- ...__classPrivateFieldGet(this, _CollectionBuilder_requestOptions, "f"),
894
- method: 'POST',
895
- headers: {
896
- ...__classPrivateFieldGet(this, _CollectionBuilder_requestOptions, "f").headers,
897
- 'Content-Type': 'application/json'
898
- },
899
- body: JSON.stringify({
900
- query,
901
- render: __classPrivateFieldGet(this, _CollectionBuilder_render, "f"),
902
- sort: this.sort,
903
- limit: __classPrivateFieldGet(this, _CollectionBuilder_limit, "f"),
904
- offset: this.offset,
905
- depth: __classPrivateFieldGet(this, _CollectionBuilder_depth, "f")
906
- //userId: This exist but we currently don't use it
907
- //allCategoriesInfo: This exist but we currently don't use it
908
- })
909
- });
910
- }
911
- }
912
- _CollectionBuilder_page = new WeakMap(), _CollectionBuilder_limit = new WeakMap(), _CollectionBuilder_depth = new WeakMap(), _CollectionBuilder_render = new WeakMap(), _CollectionBuilder_sortBy = new WeakMap(), _CollectionBuilder_contentType = new WeakMap(), _CollectionBuilder_defaultQuery = new WeakMap(), _CollectionBuilder_query = new WeakMap(), _CollectionBuilder_rawQuery = new WeakMap(), _CollectionBuilder_languageId = new WeakMap(), _CollectionBuilder_draft = new WeakMap(), _CollectionBuilder_serverUrl = new WeakMap(), _CollectionBuilder_requestOptions = new WeakMap();
913
-
914
- var _Content_requestOptions, _Content_serverUrl;
915
- /**
916
- * Creates a builder to filter and fetch a collection of content items.
917
- * @param contentType - The content type to retrieve.
918
- * @returns A CollectionBuilder instance for chaining filters and executing the query.
919
- * @template T - The type of the content items (defaults to unknown).
920
- *
921
- * @example Fetch blog posts with async/await
922
- * ```typescript
923
- * const response = await client.content
924
- * .getCollection<BlogPost>('Blog')
925
- * .limit(10)
926
- * .page(2)
927
- * .sortBy([{ field: 'title', order: 'asc' }])
928
- * .query(q => q.field('author').equals('John Doe'))
929
- * .depth(1)
930
- *
931
- * console.log(response.contentlets);
932
- * ```
933
- *
934
- * @example Fetch blog posts with Promise chain
935
- * ```typescript
936
- * client.content
937
- * .getCollection<BlogPost>('Blog')
938
- * .limit(10)
939
- * .page(2)
940
- * .sortBy([{ field: 'title', order: 'asc' }])
941
- * .query(q => q.field('author').equals('John Doe'))
942
- * .depth(1)
943
- * .then(response => console.log(response.contentlets))
944
- * .catch(error => console.error(error));
945
- * ```
946
- *
947
- * @example Using a custom type
948
- * ```typescript
949
- * interface BlogPost {
950
- * summary: string;
951
- * author: string;
952
- * title: string;
953
- * }
954
- *
955
- * const posts = await client.content
956
- * .getCollection<BlogPost>('Blog')
957
- * .limit(10)
958
- *
959
- * posts.contentlets.forEach(post => {
960
- * console.log(post.title, post.author, post.summary);
961
- * });
962
- * ```
963
- */
964
- class Content {
965
- /**
966
- * Creates an instance of Content.
967
- * @param {RequestOptions} requestOptions - The options for the client request.
968
- * @param {string} serverUrl - The server URL.
969
- */
970
- constructor(requestOptions, serverUrl) {
971
- _Content_requestOptions.set(this, void 0);
972
- _Content_serverUrl.set(this, void 0);
973
- __classPrivateFieldSet(this, _Content_requestOptions, requestOptions, "f");
974
- __classPrivateFieldSet(this, _Content_serverUrl, serverUrl, "f");
975
- }
976
- /**
977
- * Takes a content type and returns a builder to filter and fetch the collection.
978
- * @param {string} contentType - The content type to get the collection.
979
- * @return {CollectionBuilder<T>} CollectionBuilder to filter and fetch the collection.
980
- * @template T - Represents the type of the content type to fetch. Defaults to unknown.
981
- * @memberof Content
982
- *
983
- * @example
984
- * ```javascript
985
- * // Using await and async
986
- * const collectionResponse = await client.content
987
- * .getCollection('Blog')
988
- * .limit(10)
989
- * .page(2)
990
- * .sortBy([{ field: 'title', order: 'asc' }])
991
- * .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
992
- * .depth(1);
993
- * ```
994
- * @example
995
- * ```javascript
996
- * // Using then and catch
997
- * client.content
998
- * .getCollection('Blog')
999
- * .limit(10)
1000
- * .page(2)
1001
- * .sortBy([{ field: 'title', order: 'asc' }])
1002
- * .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
1003
- * .depth(1)
1004
- * .then((response) => {
1005
- * console.log(response.contentlets);
1006
- * })
1007
- * .catch((error) => {
1008
- * console.error(error);
1009
- * });
1010
- * ```
1011
- * @example
1012
- * ```typescript
1013
- * // Using a specific type for your content
1014
- *
1015
- * type Blog = {
1016
- * summary: string;
1017
- * author: string;
1018
- * title: string;
1019
- * };
1020
- *
1021
- * client.content
1022
- * .getCollection<Blog>('Blog')
1023
- * .limit(10)
1024
- * .page(2)
1025
- * .sortBy([{ field: 'title', order: 'asc' }])
1026
- * .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
1027
- * .depth(1)
1028
- * .then((response) => {
1029
- * response.contentlets.forEach((blog) => {
1030
- * console.log(blog.title);
1031
- * console.log(blog.author);
1032
- * console.log(blog.summary);
1033
- * });
1034
- * })
1035
- * .catch((error) => {
1036
- * console.error(error);
1037
- * });
1038
- * ```
1039
- *
1040
- */
1041
- getCollection(contentType) {
1042
- return new CollectionBuilder(__classPrivateFieldGet(this, _Content_requestOptions, "f"), __classPrivateFieldGet(this, _Content_serverUrl, "f"), contentType);
1043
- }
1044
- }
1045
- _Content_requestOptions = new WeakMap(), _Content_serverUrl = new WeakMap();
1046
-
1047
- class NavigationClient {
1048
- constructor(config, requestOptions) {
1049
- this.requestOptions = requestOptions;
1050
- this.BASE_URL = `${config?.dotcmsUrl}/api/v1/nav`;
1051
- }
1052
- /**
1053
- * Retrieves information about the dotCMS file and folder tree.
1054
- * @param {NavigationApiOptions} options - The options for the Navigation API call. Defaults to `{ depth: 0, path: '/', languageId: 1 }`.
1055
- * @returns {Promise<DotCMSNavigationItem[]>} - A Promise that resolves to the response from the DotCMS API.
1056
- * @throws {Error} - Throws an error if the options are not valid.
1057
- */
1058
- async get(path, params) {
1059
- if (!path) {
1060
- throw new Error("The 'path' parameter is required for the Navigation API");
1061
- }
1062
- const navParams = params ? this.mapToBackendParams(params) : {};
1063
- const urlParams = new URLSearchParams(navParams).toString();
1064
- const parsedPath = path.replace(/^\/+/, '/').replace(/\/+$/, '/');
1065
- const url = `${this.BASE_URL}${parsedPath}${urlParams ? `?${urlParams}` : ''}`;
1066
- const response = await fetch(url, this.requestOptions);
1067
- if (!response.ok) {
1068
- throw new Error(`Failed to fetch navigation data: ${response.statusText} - ${response.status}`);
1069
- }
1070
- return response.json().then((data) => data.entity);
1071
- }
1072
- mapToBackendParams(params) {
1073
- const backendParams = {};
1074
- if (params.depth) {
1075
- backendParams['depth'] = String(params.depth);
1076
- }
1077
- if (params.languageId) {
1078
- backendParams['language_id'] = String(params.languageId);
1079
- }
1080
- return backendParams;
1081
- }
1082
- }
1083
-
1084
- /**
1085
- * A record of HTTP status codes and their corresponding error messages.
1086
- *
1087
- * @type {Record<number, string>}
1088
- * @property {string} 401 - Unauthorized. Check the token and try again.
1089
- * @property {string} 403 - Forbidden. Check the permissions and try again.
1090
- * @property {string} 404 - Not Found. Check the URL and try again.
1091
- * @property {string} 500 - Internal Server Error. Try again later.
1092
- * @property {string} 502 - Bad Gateway. Try again later.
1093
- * @property {string} 503 - Service Unavailable. Try again later.
1094
- */
1095
- const ErrorMessages = {
1096
- 401: 'Unauthorized. Check the token and try again.',
1097
- 403: 'Forbidden. Check the permissions and try again.',
1098
- 404: 'Not Found. Check the URL and try again.',
1099
- 500: 'Internal Server Error. Try again later.',
1100
- 502: 'Bad Gateway. Try again later.',
1101
- 503: 'Service Unavailable. Try again later.'
1102
- };
1103
-
1104
- const DEFAULT_PAGE_CONTENTLETS_CONTENT = `
1105
- publishDate
1106
- inode
1107
- identifier
1108
- archived
1109
- urlMap
1110
- urlMap
1111
- locked
1112
- contentType
1113
- creationDate
1114
- modDate
1115
- title
1116
- baseType
1117
- working
1118
- live
1119
- publishUser {
1120
- firstName
1121
- lastName
1122
- }
1123
- owner {
1124
- lastName
1125
- }
1126
- conLanguage {
1127
- language
1128
- languageCode
1129
- }
1130
- modUser {
1131
- firstName
1132
- lastName
1133
- }
1134
- `;
1135
- /**
1136
- * Builds a GraphQL query for retrieving page content from DotCMS.
1137
- *
1138
- * @param {string} pageQuery - Custom fragment fields to include in the ClientPage fragment
1139
- * @param {string} additionalQueries - Additional GraphQL queries to include in the main query
1140
- * @returns {string} Complete GraphQL query string for page content
1141
- */
1142
- const buildPageQuery = ({ page, fragments, additionalQueries }) => {
1143
- if (!page) {
1144
- 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.");
1145
- }
1146
- return `
1147
- fragment DotCMSPage on DotPage {
1148
- publishDate
1149
- type
1150
- httpsRequired
1151
- inode
1152
- path
1153
- identifier
1154
- hasTitleImage
1155
- sortOrder
1156
- extension
1157
- canRead
1158
- pageURI
1159
- canEdit
1160
- archived
1161
- friendlyName
1162
- workingInode
1163
- url
1164
- pageURI
1165
- hasLiveVersion
1166
- deleted
1167
- pageUrl
1168
- shortyWorking
1169
- mimeType
1170
- locked
1171
- stInode
1172
- contentType
1173
- creationDate
1174
- liveInode
1175
- name
1176
- shortyLive
1177
- modDate
1178
- title
1179
- baseType
1180
- working
1181
- canLock
1182
- live
1183
- isContentlet
1184
- statusIcons
1185
- canEdit
1186
- canLock
1187
- canRead
1188
- canEdit
1189
- canLock
1190
- canRead
1191
- runningExperimentId
1192
- urlContentMap {
1193
- _map
1194
- }
1195
- host {
1196
- identifier
1197
- hostName
1198
- googleMap
1199
- archived
1200
- contentType
1201
- }
1202
- vanityUrl {
1203
- action
1204
- forwardTo
1205
- uri
1206
- }
1207
- conLanguage {
1208
- id
1209
- language
1210
- languageCode
1211
- }
1212
- template {
1213
- drawed
1214
- anonymous
1215
- theme
1216
- identifier
1217
- }
1218
- containers {
1219
- path
1220
- identifier
1221
- maxContentlets
1222
- containerStructures {
1223
- id
1224
- code
1225
- structureId
1226
- containerId
1227
- contentTypeVar
1228
- containerInode
1229
- }
1230
- containerContentlets {
1231
- uuid
1232
- contentlets {
1233
- ${page ? DEFAULT_PAGE_CONTENTLETS_CONTENT : '_map'}
1234
- }
1235
- }
1236
- }
1237
- layout {
1238
- header
1239
- footer
1240
- body {
1241
- rows {
1242
- columns {
1243
- leftOffset
1244
- styleClass
1245
- width
1246
- left
1247
- containers {
1248
- identifier
1249
- uuid
1250
- }
1251
- }
1252
- }
1253
- }
1254
- }
1255
- viewAs {
1256
- visitor {
1257
- persona {
1258
- modDate
1259
- inode
1260
- name
1261
- identifier
1262
- keyTag
1263
- photo {
1264
- versionPath
1265
- }
1266
- }
1267
- }
1268
- persona {
1269
- modDate
1270
- inode
1271
- name
1272
- identifier
1273
- keyTag
1274
- photo {
1275
- versionPath
1276
- }
1277
- }
1278
- language {
1279
- id
1280
- languageCode
1281
- countryCode
1282
- language
1283
- country
1284
- }
1285
- }
1286
- }
1287
-
1288
- ${page ? ` fragment ClientPage on DotPage { ${page} } ` : ''}
1289
-
1290
- ${fragments ? fragments.join('\n\n') : ''}
1291
-
1292
- query PageContent($url: String!, $languageId: String, $mode: String, $personaId: String, $fireRules: Boolean, $publishDate: String, $siteId: String, $variantName: String) {
1293
- page: page(url: $url, languageId: $languageId, pageMode: $mode, persona: $personaId, fireRules: $fireRules, publishDate: $publishDate, site: $siteId, variantName: $variantName) {
1294
- ...DotCMSPage
1295
- ${page ? '...ClientPage' : ''}
1296
- }
1297
-
1298
- ${additionalQueries}
1299
- }
1300
- `;
1301
- };
1302
- /**
1303
- * Converts a record of query strings into a single GraphQL query string.
1304
- *
1305
- * @param {Record<string, string>} queryData - Object containing named query strings
1306
- * @returns {string} Combined query string or empty string if no queryData provided
1307
- */
1308
- function buildQuery(queryData) {
1309
- if (!queryData)
1310
- return '';
1311
- return Object.entries(queryData)
1312
- .map(([key, query]) => `${key}: ${query}`)
1313
- .join(' ');
1314
- }
1315
- /**
1316
- * Filters response data to include only specified keys.
1317
- *
1318
- * @param {Record<string, string>} responseData - Original response data object
1319
- * @param {string[]} keys - Array of keys to extract from the response data
1320
- * @returns {Record<string, string>} New object containing only the specified keys
1321
- */
1322
- function mapResponseData(responseData, keys) {
1323
- return keys.reduce((accumulator, key) => {
1324
- if (responseData[key] !== undefined) {
1325
- accumulator[key] = responseData[key];
1326
- }
1327
- return accumulator;
1328
- }, {});
1329
- }
1330
- /**
1331
- * Executes a GraphQL query against the DotCMS API.
1332
- *
1333
- * @param {Object} options - Options for the fetch request
1334
- * @param {string} options.body - GraphQL query string
1335
- * @param {Record<string, string>} options.headers - HTTP headers for the request
1336
- * @returns {Promise<any>} Parsed JSON response from the GraphQL API
1337
- * @throws {Error} If the HTTP response is not successful
1338
- */
1339
- async function fetchGraphQL({ baseURL, body, headers }) {
1340
- const url = new URL(baseURL);
1341
- url.pathname = '/api/v1/graphql';
1342
- const response = await fetch(url.toString(), {
1343
- method: 'POST',
1344
- body,
1345
- headers
1346
- });
1347
- if (!response.ok) {
1348
- const error = {
1349
- status: response.status,
1350
- message: ErrorMessages[response.status] || response.statusText
1351
- };
1352
- throw error;
1353
- }
1354
- return await response.json();
1355
- }
1356
-
1357
- /**
1358
- * Client for interacting with the DotCMS Page API.
1359
- * Provides methods to retrieve and manipulate pages.
1360
- */
1361
- class PageClient {
1362
- /**
1363
- * Creates a new PageClient instance.
1364
- *
1365
- * @param {DotCMSClientConfig} config - Configuration options for the DotCMS client
1366
- * @param {RequestOptions} requestOptions - Options for fetch requests including authorization headers
1367
- * @example
1368
- * ```typescript
1369
- * const pageClient = new PageClient(
1370
- * {
1371
- * dotcmsUrl: 'https://demo.dotcms.com',
1372
- * authToken: 'your-auth-token',
1373
- * siteId: 'demo.dotcms.com'
1374
- * },
1375
- * {
1376
- * headers: {
1377
- * Authorization: 'Bearer your-auth-token'
1378
- * }
1379
- * }
1380
- * );
1381
- * ```
1382
- */
1383
- constructor(config, requestOptions) {
1384
- this.requestOptions = requestOptions;
1385
- this.siteId = config.siteId || '';
1386
- this.dotcmsUrl = config.dotcmsUrl;
1387
- }
1388
- /**
1389
- * Retrieves a page from DotCMS using GraphQL.
1390
- *
1391
- * @param {string} url - The URL of the page to retrieve
1392
- * @param {DotCMSPageRequestParams} [options] - Options for the request
1393
- * @template T - The type of the page and content, defaults to DotCMSBasicPage and Record<string, unknown> | unknown
1394
- * @returns {Promise<DotCMSComposedPageResponse<T>>} A Promise that resolves to the page data
1395
- *
1396
- * @example Using GraphQL
1397
- * ```typescript
1398
- * const page = await pageClient.get<{ page: MyPageWithBanners; content: { blogPosts: { blogTitle: string } } }>(
1399
- * '/index',
1400
- * {
1401
- * languageId: '1',
1402
- * mode: 'LIVE',
1403
- * graphql: {
1404
- * page: `
1405
- * containers {
1406
- * containerContentlets {
1407
- * contentlets {
1408
- * ... on Banner {
1409
- * ...bannerFragment
1410
- * }
1411
- * }
1412
- * }
1413
- * `,
1414
- * content: {
1415
- * blogPosts: `
1416
- * BlogCollection(limit: 3) {
1417
- * ...blogFragment
1418
- * }
1419
- * `,
1420
- * },
1421
- * fragments: [
1422
- * `
1423
- * fragment bannerFragment on Banner {
1424
- * caption
1425
- * }
1426
- * `,
1427
- * `
1428
- * fragment blogFragment on Blog {
1429
- * title
1430
- * urlTitle
1431
- * }
1432
- * `
1433
- * ]
1434
- * }
1435
- * });
1436
- * ```
1437
- */
1438
- async get(url, options) {
1439
- const { languageId = '1', mode = 'LIVE', siteId = this.siteId, fireRules = false, personaId, publishDate, variantName, graphql = {} } = options || {};
1440
- const { page, content = {}, variables, fragments } = graphql;
1441
- const contentQuery = buildQuery(content);
1442
- const completeQuery = buildPageQuery({
1443
- page,
1444
- fragments,
1445
- additionalQueries: contentQuery
1446
- });
1447
- const requestVariables = {
1448
- // The url is expected to have a leading slash to comply on VanityURL Matching, some frameworks like Angular will not add the leading slash
1449
- url: url.startsWith('/') ? url : `/${url}`,
1450
- mode,
1451
- languageId,
1452
- personaId,
1453
- fireRules,
1454
- publishDate,
1455
- siteId,
1456
- variantName,
1457
- ...variables
1458
- };
1459
- const requestHeaders = this.requestOptions.headers;
1460
- const requestBody = JSON.stringify({ query: completeQuery, variables: requestVariables });
1461
- try {
1462
- const { data, errors } = await fetchGraphQL({
1463
- baseURL: this.dotcmsUrl,
1464
- body: requestBody,
1465
- headers: requestHeaders
1466
- });
1467
- if (errors) {
1468
- errors.forEach((error) => {
1469
- consola.error('[DotCMS GraphQL Error]: ', error.message);
1470
- });
1471
- }
1472
- const pageResponse = internal.graphqlToPageEntity(data);
1473
- if (!pageResponse) {
1474
- throw new Error('No page data found');
1475
- }
1476
- const contentResponse = mapResponseData(data, Object.keys(content));
1477
- return {
1478
- pageAsset: pageResponse,
1479
- content: contentResponse,
1480
- graphql: {
1481
- query: completeQuery,
1482
- variables: requestVariables
1483
- }
1484
- };
1485
- }
1486
- catch (error) {
1487
- const errorMessage = {
1488
- error,
1489
- message: 'Failed to retrieve page data',
1490
- graphql: {
1491
- query: completeQuery,
1492
- variables: requestVariables
1493
- }
1494
- };
1495
- throw errorMessage;
1496
- }
1497
- }
1498
- }
1499
-
1500
- /**
1501
- * Parses a string into a URL object.
1502
- *
1503
- * @param url - The URL string to parse
1504
- * @returns A URL object if parsing is successful, undefined otherwise
1505
- */
1506
- function parseURL(url) {
1507
- try {
1508
- return new URL(url);
1509
- }
1510
- catch {
1511
- consola.consola.error('[DotCMS Client]: Invalid URL:', url);
1512
- return undefined;
1513
- }
1514
- }
1515
- /**
1516
- * Default configuration for the DotCMS client.
1517
- */
1518
- const defaultConfig = {
1519
- dotcmsUrl: '',
1520
- authToken: '',
1521
- requestOptions: {}
1522
- };
1523
- /**
1524
- * Client for interacting with the DotCMS REST API.
1525
- * Provides access to content, page, and navigation functionality.
1526
- */
1527
- class DotCMSClient {
1528
- /**
1529
- * Creates a new DotCMS client instance.
1530
- *
1531
- * @param config - Configuration options for the client
1532
- * @throws Warning if dotcmsUrl is invalid or authToken is missing
1533
- */
1534
- constructor(config = defaultConfig) {
1535
- this.config = config;
1536
- this.requestOptions = this.createAuthenticatedRequestOptions(this.config);
1537
- // Initialize clients
1538
- this.page = new PageClient(this.config, this.requestOptions);
1539
- this.nav = new NavigationClient(this.config, this.requestOptions);
1540
- this.content = new Content(this.requestOptions, this.config.dotcmsUrl);
1541
- }
1542
- /**
1543
- * Creates request options with authentication headers.
1544
- *
1545
- * @param config - The client configuration
1546
- * @returns Request options with authorization headers
1547
- */
1548
- createAuthenticatedRequestOptions(config) {
1549
- return {
1550
- ...config.requestOptions,
1551
- headers: {
1552
- ...config.requestOptions?.headers,
1553
- Authorization: `Bearer ${config.authToken}`
1554
- }
1555
- };
1556
- }
1557
- }
1558
- /**
1559
- * Creates and returns a new DotCMS client instance.
1560
- *
1561
- * @param config - Configuration options for the client
1562
- * @returns A configured DotCMS client instance
1563
- * @example
1564
- * ```typescript
1565
- * const client = dotCMSCreateClient({
1566
- * dotcmsUrl: 'https://demo.dotcms.com',
1567
- * authToken: 'your-auth-token'
1568
- * });
1569
- *
1570
- * // Use the client to fetch content
1571
- * const pages = await client.page.get('/about-us');
1572
- * ```
1573
- */
1574
- const createDotCMSClient = (clientConfig) => {
1575
- const { dotcmsUrl, authToken } = clientConfig || {};
1576
- const instanceUrl = parseURL(dotcmsUrl)?.origin;
1577
- if (!instanceUrl) {
1578
- throw new TypeError("Invalid configuration - 'dotcmsUrl' must be a valid URL");
1579
- }
1580
- if (!authToken) {
1581
- throw new TypeError("Invalid configuration - 'authToken' is required");
1582
- }
1583
- const config = {
1584
- ...clientConfig,
1585
- authToken,
1586
- dotcmsUrl: instanceUrl
1587
- };
1588
- return new DotCMSClient(config);
1589
- };
1590
-
1591
- exports.createDotCMSClient = createDotCMSClient;