@dotcms/client 0.0.1-alpha.37 → 0.0.1-alpha.39

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 (66) hide show
  1. package/.eslintrc.json +18 -0
  2. package/README.md +4 -4
  3. package/jest.config.ts +15 -0
  4. package/package.json +3 -15
  5. package/project.json +72 -0
  6. package/src/index.ts +30 -0
  7. package/src/lib/client/content/builders/collection/collection.spec.ts +515 -0
  8. package/src/lib/client/content/builders/collection/collection.ts +416 -0
  9. package/src/lib/client/content/content-api.ts +139 -0
  10. package/src/lib/client/content/shared/const.ts +15 -0
  11. package/src/lib/client/content/shared/types.ts +155 -0
  12. package/src/lib/client/content/shared/utils.ts +28 -0
  13. package/src/lib/client/models/index.ts +19 -0
  14. package/src/lib/client/models/types.ts +14 -0
  15. package/src/lib/client/sdk-js-client.spec.ts +483 -0
  16. package/src/lib/client/sdk-js-client.ts +442 -0
  17. package/src/lib/editor/listeners/listeners.spec.ts +119 -0
  18. package/src/lib/editor/listeners/listeners.ts +223 -0
  19. package/src/lib/editor/models/{client.model.d.ts → client.model.ts} +19 -16
  20. package/src/lib/editor/models/{editor.model.d.ts → editor.model.ts} +9 -5
  21. package/src/lib/editor/models/{listeners.model.d.ts → listeners.model.ts} +9 -6
  22. package/src/lib/editor/sdk-editor-vtl.ts +31 -0
  23. package/src/lib/editor/sdk-editor.spec.ts +116 -0
  24. package/src/lib/editor/sdk-editor.ts +105 -0
  25. package/src/lib/editor/utils/editor.utils.spec.ts +206 -0
  26. package/src/lib/editor/utils/editor.utils.ts +258 -0
  27. package/src/lib/query-builder/lucene-syntax/{Equals.d.ts → Equals.ts} +83 -18
  28. package/src/lib/query-builder/lucene-syntax/Field.ts +40 -0
  29. package/src/lib/query-builder/lucene-syntax/{NotOperand.d.ts → NotOperand.ts} +18 -6
  30. package/src/lib/query-builder/lucene-syntax/{Operand.d.ts → Operand.ts} +21 -7
  31. package/src/lib/query-builder/sdk-query-builder.spec.ts +159 -0
  32. package/src/lib/query-builder/sdk-query-builder.ts +87 -0
  33. package/src/lib/query-builder/utils/index.ts +179 -0
  34. package/src/lib/utils/graphql/transforms.spec.ts +150 -0
  35. package/src/lib/utils/graphql/transforms.ts +99 -0
  36. package/src/lib/utils/page/common-utils.spec.ts +37 -0
  37. package/src/lib/utils/page/common-utils.ts +64 -0
  38. package/tsconfig.json +22 -0
  39. package/tsconfig.lib.json +13 -0
  40. package/tsconfig.spec.json +9 -0
  41. package/index.cjs.d.ts +0 -1
  42. package/index.cjs.default.js +0 -1
  43. package/index.cjs.js +0 -1490
  44. package/index.cjs.mjs +0 -2
  45. package/index.esm.d.ts +0 -1
  46. package/index.esm.js +0 -1481
  47. package/src/index.d.ts +0 -6
  48. package/src/lib/client/content/builders/collection/collection.d.ts +0 -148
  49. package/src/lib/client/content/content-api.d.ts +0 -78
  50. package/src/lib/client/content/shared/const.d.ts +0 -3
  51. package/src/lib/client/content/shared/types.d.ts +0 -62
  52. package/src/lib/client/content/shared/utils.d.ts +0 -12
  53. package/src/lib/client/models/index.d.ts +0 -1
  54. package/src/lib/client/models/types.d.ts +0 -5
  55. package/src/lib/client/sdk-js-client.d.ts +0 -193
  56. package/src/lib/editor/listeners/listeners.d.ts +0 -46
  57. package/src/lib/editor/sdk-editor-vtl.d.ts +0 -6
  58. package/src/lib/editor/sdk-editor.d.ts +0 -29
  59. package/src/lib/editor/utils/editor.utils.d.ts +0 -83
  60. package/src/lib/query-builder/lucene-syntax/Field.d.ts +0 -23
  61. package/src/lib/query-builder/sdk-query-builder.d.ts +0 -42
  62. package/src/lib/query-builder/utils/index.d.ts +0 -91
  63. package/src/lib/utils/graphql/transforms.d.ts +0 -11
  64. package/src/lib/utils/page/common-utils.d.ts +0 -11
  65. /package/src/lib/query-builder/lucene-syntax/{index.d.ts → index.ts} +0 -0
  66. /package/src/lib/utils/{index.d.ts → index.ts} +0 -0
package/index.esm.js DELETED
@@ -1,1481 +0,0 @@
1
- /******************************************************************************
2
- Copyright (c) Microsoft Corporation.
3
-
4
- Permission to use, copy, modify, and/or distribute this software for any
5
- purpose with or without fee is hereby granted.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
- PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */
15
- /* global Reflect, Promise, SuppressedError, Symbol */
16
-
17
-
18
- function __classPrivateFieldGet(receiver, state, kind, f) {
19
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
20
- 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");
21
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
22
- }
23
-
24
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
25
- if (kind === "m") throw new TypeError("Private method is not writable");
26
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
27
- 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");
28
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
29
- }
30
-
31
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
32
- var e = new Error(message);
33
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
34
- };
35
-
36
- var _Field_query;
37
- /**
38
- * 'Field' class is used to build a query with a field.
39
- * A Lucene Field is a key used to search for a specific value in a document.
40
- *
41
- * @export
42
- * @class Field
43
- */
44
- class Field {
45
- constructor(query) {
46
- this.query = query;
47
- _Field_query.set(this, '');
48
- __classPrivateFieldSet(this, _Field_query, this.query, "f");
49
- }
50
- /**
51
- * This method appends to the query a term that should be included in the search..
52
- *
53
- * Ex: myValue or "My value"
54
- *
55
- * @param {string} term - The term that should be included in the search.
56
- * @return {*} {Equals} - An instance of Equals.
57
- * @memberof Field
58
- */
59
- equals(term) {
60
- return buildEquals(__classPrivateFieldGet(this, _Field_query, "f"), term);
61
- }
62
- }
63
- _Field_query = new WeakMap();
64
-
65
- var _NotOperand_query;
66
- /**
67
- * 'NotOperand' Is a Typescript class that provides the ability to use the NOT operand in the lucene query string.
68
- *
69
- * @export
70
- * @class NotOperand
71
- */
72
- class NotOperand {
73
- constructor(query) {
74
- this.query = query;
75
- _NotOperand_query.set(this, '');
76
- __classPrivateFieldSet(this, _NotOperand_query, this.query, "f");
77
- }
78
- /**
79
- * This method appends to the query a term that should be included in the search.
80
- *
81
- * Ex: myValue or "My value"
82
- *
83
- * @param {string} term - The term that should be included in the search.
84
- * @return {*} {Equals} - An instance of Equals.
85
- * @memberof NotOperand
86
- */
87
- equals(term) {
88
- return buildEquals(__classPrivateFieldGet(this, _NotOperand_query, "f"), term);
89
- }
90
- }
91
- _NotOperand_query = new WeakMap();
92
-
93
- var _Operand_query;
94
- /**
95
- * 'Operand' Is a Typescript class that provides the ability to use operands in the lucene query string.}
96
- * An operand is a logical operator used to join two or more conditions in a query.
97
- *
98
- * @export
99
- * @class Operand
100
- */
101
- class Operand {
102
- constructor(query) {
103
- this.query = query;
104
- _Operand_query.set(this, '');
105
- __classPrivateFieldSet(this, _Operand_query, this.query, "f");
106
- }
107
- /**
108
- * This method appends to the query a term that should be excluded in the search.
109
- *
110
- * Ex: "-myValue"
111
- *
112
- * @param {string} field - The field that should be excluded in the search.
113
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
114
- * @memberof Operand
115
- */
116
- excludeField(field) {
117
- return buildExcludeField(__classPrivateFieldGet(this, _Operand_query, "f"), field);
118
- }
119
- /**
120
- * This method appends to the query a field that should be included in the search.
121
- *
122
- * Ex: "+myField:"
123
- *
124
- * @param {string} field - The field that should be included in the search.
125
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
126
- * @memberof Operand
127
- */
128
- field(field) {
129
- return buildField(__classPrivateFieldGet(this, _Operand_query, "f"), field);
130
- }
131
- /**
132
- * This method appends to the query a term that should be included in the search.
133
- *
134
- * Ex: myValue or "My value"
135
- *
136
- * @param {string} term - The term that should be included in the search.
137
- * @return {*} {Equals} - An instance of Equals.
138
- * @memberof Operand
139
- */
140
- equals(term) {
141
- return buildEquals(__classPrivateFieldGet(this, _Operand_query, "f"), term);
142
- }
143
- }
144
- _Operand_query = new WeakMap();
145
-
146
- /**
147
- * Enum for common Operands
148
- *
149
- * @export
150
- * @enum {number}
151
- */
152
- var OPERAND;
153
- (function (OPERAND) {
154
- OPERAND["OR"] = "OR";
155
- OPERAND["AND"] = "AND";
156
- OPERAND["NOT"] = "NOT";
157
- })(OPERAND || (OPERAND = {}));
158
- /**
159
- * This function removes extra spaces from a string.
160
- *
161
- * @export
162
- * @param {string} str
163
- * @return {*} {string}
164
- */
165
- function sanitizeQuery(str) {
166
- return str.replace(/\s{2,}/g, ' ').trim();
167
- }
168
- /**
169
- * This function sanitizes a term by adding quotes if it contains spaces.
170
- * In lucene, a term with spaces should be enclosed in quotes.
171
- *
172
- * @export
173
- * @param {string} term
174
- * @return {*} {string}
175
- */
176
- function sanitizePhrases(term) {
177
- return term.includes(' ') ? `"${term}"` : term;
178
- }
179
- /**
180
- * This function builds a term to be used in a lucene query.
181
- * We need to sanitize the term before adding it to the query.
182
- *
183
- * @export
184
- * @param {string} query
185
- * @param {string} term
186
- * @return {*} {Equals}
187
- */
188
- function buildEquals(query, term) {
189
- const newQuery = query + sanitizePhrases(term);
190
- return new Equals(newQuery);
191
- }
192
- /**
193
- * This function builds a term to be used in a lucene query.
194
- * We need to sanitize the raw query before adding it to the query.
195
- *
196
- * @export
197
- * @param {string} query
198
- * @param {string} raw
199
- * @return {*} {Equals}
200
- */
201
- function buildRawEquals(query, raw) {
202
- const newQuery = query + ` ${raw}`;
203
- return new Equals(sanitizeQuery(newQuery));
204
- }
205
- /**
206
- * This function builds a field to be used in a lucene query.
207
- * We need to format the field before adding it to the query.
208
- *
209
- * @export
210
- * @param {string} query
211
- * @param {string} field
212
- * @return {*} {Field}
213
- */
214
- function buildField(query, field) {
215
- const newQuery = query + ` +${field}:`;
216
- return new Field(newQuery);
217
- }
218
- /**
219
- * This function builds an exclude field to be used in a lucene query.
220
- * We need to format the field before adding it to the query.
221
- *
222
- * @export
223
- * @param {string} query
224
- * @param {string} field
225
- * @return {*} {Field}
226
- */
227
- function buildExcludeField(query, field) {
228
- const newQuery = query + ` -${field}:`;
229
- return new Field(newQuery);
230
- }
231
- /**
232
- * This function builds an operand to be used in a lucene query.
233
- * We need to format the operand before adding it to the query.
234
- *
235
- * @export
236
- * @param {string} query
237
- * @param {OPERAND} operand
238
- * @return {*} {Operand}
239
- */
240
- function buildOperand(query, operand) {
241
- const newQuery = query + ` ${operand} `;
242
- return new Operand(newQuery);
243
- }
244
- /**
245
- * This function builds a NOT operand to be used in a lucene query.
246
- * We need to format the operand before adding it to the query.
247
- *
248
- * @export
249
- * @param {string} query
250
- * @return {*} {NotOperand}
251
- */
252
- function buildNotOperand(query) {
253
- const newQuery = query + ` ${OPERAND.NOT} `;
254
- return new NotOperand(newQuery);
255
- }
256
-
257
- var _Equals_query;
258
- /**
259
- * 'Equal' Is a Typescript class that provides the ability to use terms in the lucene query string.
260
- * A term is a value used to search for a specific value in a document. It can be a word or a phrase.
261
- *
262
- * Ex: myValue or "My Value"
263
- *
264
- * @export
265
- * @class Equal
266
- */
267
- class Equals {
268
- constructor(query) {
269
- this.query = query;
270
- _Equals_query.set(this, '');
271
- __classPrivateFieldSet(this, _Equals_query, this.query, "f");
272
- }
273
- /**
274
- * This method appends to the query a term that should be excluded in the search.
275
- *
276
- * Ex: "-myValue"
277
- *
278
- * @param {string} field - The field that should be excluded in the search.
279
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
280
- * @memberof Equal
281
- */
282
- excludeField(field) {
283
- return buildExcludeField(__classPrivateFieldGet(this, _Equals_query, "f"), field);
284
- }
285
- /**
286
- * This method appends to the query a field that should be included in the search.
287
- *
288
- * Ex: "+myField:"
289
- *
290
- * @param {string} field - The field that should be included in the search.
291
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
292
- * @memberof Equal
293
- */
294
- field(field) {
295
- return buildField(__classPrivateFieldGet(this, _Equals_query, "f"), field);
296
- }
297
- /**
298
- * This method appends to the query an operand to use logic operators in the query.
299
- *
300
- * Ex: "OR"
301
- *
302
- * @return {*} {Operand} - An instance of a Lucene Operand. An operand is a logical operator used to combine terms or phrases in a query.
303
- * @memberof Equal
304
- */
305
- or() {
306
- return buildOperand(__classPrivateFieldGet(this, _Equals_query, "f"), OPERAND.OR);
307
- }
308
- /**
309
- * This method appends to the query an operand to use logic operators in the query.
310
- *
311
- * Ex: "AND"
312
- *
313
- * @return {*} {Operand} - An instance of a Lucene Operand. An operand is a logical operator used to combine terms or phrases in a query.
314
- * @memberof Equal
315
- */
316
- and() {
317
- return buildOperand(__classPrivateFieldGet(this, _Equals_query, "f"), OPERAND.AND);
318
- }
319
- /**
320
- * This method appends to the query an operand to use logic operators in the query.
321
- *
322
- * Ex: "NOT"
323
- *
324
- * @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.
325
- * @memberof Equal
326
- */
327
- not() {
328
- return buildNotOperand(__classPrivateFieldGet(this, _Equals_query, "f"));
329
- }
330
- /**
331
- * This method allows to pass a raw query string to the query builder.
332
- * This raw query should end in a Lucene Equal.
333
- * This method is useful when you want to append a complex query or an already written query to the query builder.
334
- *
335
- * Ex: "+myField: value AND (someOtherValue OR anotherValue)"
336
- *
337
- * @param {string} query - A raw query string.
338
- * @return {*} {Equal} - An instance of a Lucene Equal. A term is a value used to search for a specific value in a document.
339
- * @memberof QueryBuilder
340
- */
341
- raw(query) {
342
- return buildRawEquals(__classPrivateFieldGet(this, _Equals_query, "f"), query);
343
- }
344
- /**
345
- * This method returns the final query string.
346
- *
347
- * @return {*} {string} - The final query string.
348
- * @memberof Equal
349
- */
350
- build() {
351
- return sanitizeQuery(__classPrivateFieldGet(this, _Equals_query, "f"));
352
- }
353
- }
354
- _Equals_query = new WeakMap();
355
-
356
- var _QueryBuilder_query;
357
- /**
358
- * 'QueryBuilder' Is a Typescript class that provides the ability to build a query string using the Lucene syntax in a more readable way.
359
- *
360
- * @export
361
- * @class QueryBuilder
362
- */
363
- class QueryBuilder {
364
- constructor() {
365
- _QueryBuilder_query.set(this, '');
366
- }
367
- /**
368
- * This method appends to the query a field that should be included in the search.
369
- *
370
- * Ex: "+myField:"
371
- *
372
- * @param {string} field - The field that should be included in the search.
373
- * @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
374
- * @memberof QueryBuilder
375
- */
376
- field(field) {
377
- return buildField(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), field);
378
- }
379
- /**
380
- * This method appends to the query a field that should be excluded from the search.
381
- *
382
- * Ex: "-myField:"
383
- *
384
- * @param {string} field - The field that should be excluded from the search.
385
- * @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.
386
- * @memberof QueryBuilder
387
- */
388
- excludeField(field) {
389
- return buildExcludeField(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), field);
390
- }
391
- /**
392
- * This method allows to pass a raw query string to the query builder.
393
- * This raw query should end in Equals.
394
- * This method is useful when you want to append a complex query or an already written query to the query builder.
395
- *
396
- * Ex: "+myField: value AND (someOtherValue OR anotherValue)"
397
- *
398
- * @param {string} query - A raw query string.
399
- * @return {*} {Equals} - An instance of Equals. A term is a value used to search for a specific value in a document.
400
- * @memberof QueryBuilder
401
- */
402
- raw(query) {
403
- return buildRawEquals(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), query);
404
- }
405
- }
406
- _QueryBuilder_query = new WeakMap();
407
-
408
- // Fields that we don't want to format when sanitizing the query
409
- const CONTENT_TYPE_MAIN_FIELDS = ['live', 'variant', 'contentType', 'languageId'];
410
- const CONTENT_API_URL = '/api/content/_search';
411
-
412
- /**
413
- * Sanitizes the query for the given content type.
414
- * It replaces the fields that are not contentType fields with the correct format.
415
- * Example: +field: -> +contentTypeVar.field:
416
- *
417
- *
418
- * @export
419
- * @param {string} query
420
- * @param {string} contentType
421
- * @return {*} {string}
422
- */
423
- function sanitizeQueryForContentType(query, contentType) {
424
- return query.replace(/\+([^+:]*?):/g, (original, field) => {
425
- return !CONTENT_TYPE_MAIN_FIELDS.includes(field) // Fields that are not contentType fields
426
- ? `+${contentType}.${field}:` // Should have this format: +contentTypeVar.field:
427
- : original; // Return the field if it is a contentType field
428
- });
429
- }
430
-
431
- 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;
432
- /**
433
- * Creates a Builder to filter and fetch content from the content API for an specific content type
434
- *
435
- * @export
436
- * @class CollectionBuilder
437
- * @template T Represents the type of the content type to fetch. Defaults to unknown
438
- */
439
- class CollectionBuilder {
440
- constructor(requestOptions, serverUrl, contentType) {
441
- _CollectionBuilder_page.set(this, 1);
442
- _CollectionBuilder_limit.set(this, 10);
443
- _CollectionBuilder_depth.set(this, 0);
444
- _CollectionBuilder_render.set(this, false);
445
- _CollectionBuilder_sortBy.set(this, void 0);
446
- _CollectionBuilder_contentType.set(this, void 0);
447
- _CollectionBuilder_defaultQuery.set(this, void 0);
448
- _CollectionBuilder_query.set(this, void 0);
449
- _CollectionBuilder_rawQuery.set(this, void 0);
450
- _CollectionBuilder_languageId.set(this, 1);
451
- _CollectionBuilder_draft.set(this, false);
452
- _CollectionBuilder_serverUrl.set(this, void 0);
453
- _CollectionBuilder_requestOptions.set(this, void 0);
454
- __classPrivateFieldSet(this, _CollectionBuilder_requestOptions, requestOptions, "f");
455
- __classPrivateFieldSet(this, _CollectionBuilder_serverUrl, serverUrl, "f");
456
- __classPrivateFieldSet(this, _CollectionBuilder_contentType, contentType, "f");
457
- // We need to build the default query with the contentType field
458
- __classPrivateFieldSet(this, _CollectionBuilder_defaultQuery, new QueryBuilder().field('contentType').equals(__classPrivateFieldGet(this, _CollectionBuilder_contentType, "f")), "f");
459
- }
460
- /**
461
- * This method returns the sort query in this format: field order, field order, ...
462
- *
463
- * @readonly
464
- * @private
465
- * @memberof CollectionBuilder
466
- */
467
- get sort() {
468
- return __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")?.map((sort) => `${sort.field} ${sort.order}`).join(',');
469
- }
470
- get offset() {
471
- // This could end in an empty response
472
- return __classPrivateFieldGet(this, _CollectionBuilder_limit, "f") * (__classPrivateFieldGet(this, _CollectionBuilder_page, "f") - 1);
473
- }
474
- get url() {
475
- return `${__classPrivateFieldGet(this, _CollectionBuilder_serverUrl, "f")}${CONTENT_API_URL}`;
476
- }
477
- /**
478
- * This method returns the current query built
479
- *
480
- * @readonly
481
- * @private
482
- * @memberof CollectionBuilder
483
- */
484
- get currentQuery() {
485
- return __classPrivateFieldGet(this, _CollectionBuilder_query, "f") ?? __classPrivateFieldGet(this, _CollectionBuilder_defaultQuery, "f");
486
- }
487
- /**
488
- * Takes a language id and filters the content by that language.
489
- *
490
- * The language id defaults to 1
491
- *
492
- *
493
- * @param {number | string} languageId The language id to filter the content by
494
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
495
- * @memberof CollectionBuilder
496
- */
497
- language(languageId) {
498
- __classPrivateFieldSet(this, _CollectionBuilder_languageId, languageId, "f");
499
- return this;
500
- }
501
- /**
502
- * The retrieved content will have the rendered HTML
503
- *
504
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
505
- * @memberof CollectionBuilder
506
- */
507
- render() {
508
- __classPrivateFieldSet(this, _CollectionBuilder_render, true, "f");
509
- return this;
510
- }
511
- /**
512
- * Takes an array of constrains to sort the content by field an specific order
513
- *
514
- * @example
515
- * ```javascript
516
- * // This will sort the content by title in ascending order
517
- * // and by modDate in descending order
518
- * const sortBy = [{ field: 'title', order: 'asc' }, { field: 'modDate', order: 'desc' }]
519
- *
520
- * client.content.getCollection("Blog").sortBy(sortBy)
521
- *```
522
- *
523
- * @param {SortBy[]} sortBy Array of constrains to sort the content by
524
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
525
- * @memberof CollectionBuilder
526
- */
527
- sortBy(sortBy) {
528
- __classPrivateFieldSet(this, _CollectionBuilder_sortBy, sortBy, "f");
529
- return this;
530
- }
531
- /**
532
- * Takes a number that represents the max amount of content to fetch
533
- *
534
- * `limit` is set to 10 by default
535
- *
536
- * @param {number} limit The max amount of content to fetch
537
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
538
- * @memberof CollectionBuilder
539
- */
540
- limit(limit) {
541
- __classPrivateFieldSet(this, _CollectionBuilder_limit, limit, "f");
542
- return this;
543
- }
544
- /**
545
- * Takes a number that represents the page to fetch
546
- *
547
- * @param {number} page The page to fetch
548
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
549
- * @memberof CollectionBuilder
550
- */
551
- page(page) {
552
- __classPrivateFieldSet(this, _CollectionBuilder_page, page, "f");
553
- return this;
554
- }
555
- query(arg) {
556
- if (typeof arg === 'string') {
557
- __classPrivateFieldSet(this, _CollectionBuilder_rawQuery, arg, "f");
558
- return this;
559
- }
560
- if (typeof arg !== 'function') {
561
- 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.`);
562
- }
563
- const builtQuery = arg(new QueryBuilder());
564
- // This can be use in Javascript so we cannot rely on the type checking
565
- if (builtQuery instanceof Equals) {
566
- __classPrivateFieldSet(this, _CollectionBuilder_query, builtQuery.raw(this.currentQuery.build()), "f");
567
- }
568
- else {
569
- 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.');
570
- }
571
- return this;
572
- }
573
- /**
574
- * The retrieved content will be draft content
575
- *
576
- * The default value is false to fetch content that is not on draft
577
- *
578
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
579
- * @memberof CollectionBuilder
580
- */
581
- draft() {
582
- __classPrivateFieldSet(this, _CollectionBuilder_draft, true, "f");
583
- return this;
584
- }
585
- /**
586
- * Takes a string that represents a variant ID of content created with the {@link https://www.dotcms.com/docs/latest/experiments-and-a-b-testing A/B Testing} feature
587
- *
588
- * `variantId` defaults to "DEFAULT" to fetch content that is not part of an A/B test
589
- *
590
- * @param {string} variantId A string that represents a variant ID
591
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
592
- * @memberof CollectionBuilder
593
- */
594
- variant(variantId) {
595
- __classPrivateFieldSet(this, _CollectionBuilder_query, this.currentQuery.field('variant').equals(variantId), "f");
596
- return this;
597
- }
598
- /**
599
- * Takes a number that represents the depth of the relationships of a content
600
- *
601
- * The `depth` is set to 0 by default and the max supported value is 3.
602
- *
603
- * @param {number} depth The depth of the relationships of a content
604
- * @return {CollectionBuilder} CollectionBuilder - A CollectionBuilder instance
605
- * @memberof CollectionBuilder
606
- */
607
- depth(depth) {
608
- if (depth < 0 || depth > 3) {
609
- throw new Error('Depth value must be between 0 and 3');
610
- }
611
- __classPrivateFieldSet(this, _CollectionBuilder_depth, depth, "f");
612
- return this;
613
- }
614
- /**
615
- * Executes the fetch and returns a promise that resolves to the content or rejects to an error
616
- *
617
- * @param {OnFullfilled} [onfulfilled] A callback that is called when the fetch is successful
618
- * @param {OnRejected} [onrejected] A callback that is called when the fetch fails
619
- * @return {Promise<GetCollectionResponse<T> | GetCollectionError>} A promise that resolves to the content or rejects to an error
620
- * @memberof CollectionBuilder
621
- */
622
- then(onfulfilled, onrejected) {
623
- return this.fetch().then(async (response) => {
624
- const data = await response.json();
625
- if (response.ok) {
626
- const formattedResponse = this.formatResponse(data);
627
- const finalResponse = typeof onfulfilled === 'function'
628
- ? onfulfilled(formattedResponse)
629
- : formattedResponse;
630
- return finalResponse;
631
- }
632
- else {
633
- // Fetch does not reject on server errors, so we only have to bubble up the error as a normal fetch
634
- return {
635
- status: response.status,
636
- ...data
637
- };
638
- }
639
- }, onrejected);
640
- }
641
- // Formats the response to the desired format
642
- formatResponse(data) {
643
- const contentlets = data.entity.jsonObjectView.contentlets;
644
- const total = data.entity.resultsSize;
645
- const mappedResponse = {
646
- contentlets,
647
- total,
648
- page: __classPrivateFieldGet(this, _CollectionBuilder_page, "f"),
649
- size: contentlets.length
650
- };
651
- return __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")
652
- ? {
653
- ...mappedResponse,
654
- sortedBy: __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")
655
- }
656
- : mappedResponse;
657
- }
658
- // Calls the content API to fetch the content
659
- fetch() {
660
- const finalQuery = this.currentQuery
661
- .field('languageId')
662
- .equals(__classPrivateFieldGet(this, _CollectionBuilder_languageId, "f").toString())
663
- .field('live')
664
- .equals((!__classPrivateFieldGet(this, _CollectionBuilder_draft, "f")).toString())
665
- .build();
666
- const sanitizedQuery = sanitizeQueryForContentType(finalQuery, __classPrivateFieldGet(this, _CollectionBuilder_contentType, "f"));
667
- const query = __classPrivateFieldGet(this, _CollectionBuilder_rawQuery, "f") ? `${sanitizedQuery} ${__classPrivateFieldGet(this, _CollectionBuilder_rawQuery, "f")}` : sanitizedQuery;
668
- return fetch(this.url, {
669
- ...__classPrivateFieldGet(this, _CollectionBuilder_requestOptions, "f"),
670
- method: 'POST',
671
- headers: {
672
- ...__classPrivateFieldGet(this, _CollectionBuilder_requestOptions, "f").headers,
673
- 'Content-Type': 'application/json'
674
- },
675
- body: JSON.stringify({
676
- query,
677
- render: __classPrivateFieldGet(this, _CollectionBuilder_render, "f"),
678
- sort: this.sort,
679
- limit: __classPrivateFieldGet(this, _CollectionBuilder_limit, "f"),
680
- offset: this.offset,
681
- depth: __classPrivateFieldGet(this, _CollectionBuilder_depth, "f")
682
- //userId: This exist but we currently don't use it
683
- //allCategoriesInfo: This exist but we currently don't use it
684
- })
685
- });
686
- }
687
- }
688
- _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();
689
-
690
- var _Content_requestOptions, _Content_serverUrl;
691
- /**
692
- * Content classs exposes the content api methods
693
- *
694
- * @export
695
- * @class Content
696
- */
697
- class Content {
698
- constructor(requestOptions, serverUrl) {
699
- _Content_requestOptions.set(this, void 0);
700
- _Content_serverUrl.set(this, void 0);
701
- __classPrivateFieldSet(this, _Content_requestOptions, requestOptions, "f");
702
- __classPrivateFieldSet(this, _Content_serverUrl, serverUrl, "f");
703
- }
704
- /**
705
- * Takes a content type and returns a builder to filter and fetch the collection
706
- *
707
- * @example
708
- * ```javascript
709
- * // Using await and async
710
- * const collectionResponse = await client.content
711
- * .getCollection('Blog')
712
- * .limit(10)
713
- * .page(2)
714
- * .sortBy([{ field: 'title', order: 'asc' }])
715
- * .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
716
- * .depth(1);
717
- * ```
718
- * @example
719
- * ```javascript
720
- * // Using then and catch
721
- * client.content
722
- * .getCollection('Blog')
723
- * .limit(10)
724
- * .page(2)
725
- * .sortBy([{ field: 'title', order: 'asc' }])
726
- * .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
727
- * .depth(1)
728
- * .then((response) => {
729
- * console.log(response.contentlets);
730
- * })
731
- * .catch((error) => {
732
- * console.error(error);
733
- * });
734
- * ```
735
- * @example
736
- * ```typescript
737
- * // Using an specific type for your content
738
- *
739
- * type Blog = {
740
- * summary: string;
741
- * author: string;
742
- * title: string;
743
- * };
744
- *
745
- * client.content
746
- * .getCollection<Blog>('Blog')
747
- * .limit(10)
748
- * .page(2)
749
- * .sortBy([{ field: 'title', order: 'asc' }])
750
- * .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
751
- * .depth(1)
752
- * .then((response) => {
753
- * response.contentlets.forEach((blog) => {
754
- * console.log(blog.title);
755
- * console.log(blog.author);
756
- * console.log(blog.summary);
757
- * });
758
- * })
759
- * .catch((error) => {
760
- * console.error(error);
761
- * });
762
- * ```
763
- *
764
- * @param {string} contentType The content type to get the collection
765
- * @return {CollectionBuilder} CollectionBuilder to filter and fetch the collection
766
- * @template T Represents the type of the content type to fetch. Defaults to unknown
767
- * @memberof Content
768
- */
769
- getCollection(contentType) {
770
- return new CollectionBuilder(__classPrivateFieldGet(this, _Content_requestOptions, "f"), __classPrivateFieldGet(this, _Content_serverUrl, "f"), contentType);
771
- }
772
- }
773
- _Content_requestOptions = new WeakMap(), _Content_serverUrl = new WeakMap();
774
-
775
- const ErrorMessages = {
776
- 401: 'Unauthorized. Check the token and try again.',
777
- 403: 'Forbidden. Check the permissions and try again.',
778
- 404: 'Not Found. Check the URL and try again.',
779
- 500: 'Internal Server Error. Try again later.',
780
- 502: 'Bad Gateway. Try again later.',
781
- 503: 'Service Unavailable. Try again later.'
782
- };
783
-
784
- /**
785
- * Actions send to the dotcms editor
786
- *
787
- * @export
788
- * @enum {number}
789
- */
790
- var CUSTOMER_ACTIONS;
791
- (function (CUSTOMER_ACTIONS) {
792
- /**
793
- * Tell the dotcms editor that page change
794
- */
795
- CUSTOMER_ACTIONS["NAVIGATION_UPDATE"] = "set-url";
796
- /**
797
- * Send the element position of the rows, columnsm containers and contentlets
798
- */
799
- CUSTOMER_ACTIONS["SET_BOUNDS"] = "set-bounds";
800
- /**
801
- * Send the information of the hovered contentlet
802
- */
803
- CUSTOMER_ACTIONS["SET_CONTENTLET"] = "set-contentlet";
804
- /**
805
- * Tell the editor that the page is being scrolled
806
- */
807
- CUSTOMER_ACTIONS["IFRAME_SCROLL"] = "scroll";
808
- /**
809
- * Tell the editor that the page has stopped scrolling
810
- */
811
- CUSTOMER_ACTIONS["IFRAME_SCROLL_END"] = "scroll-end";
812
- /**
813
- * Ping the editor to see if the page is inside the editor
814
- */
815
- CUSTOMER_ACTIONS["PING_EDITOR"] = "ping-editor";
816
- /**
817
- * Tell the editor to init the inline editing editor.
818
- */
819
- CUSTOMER_ACTIONS["INIT_INLINE_EDITING"] = "init-inline-editing";
820
- /**
821
- * Tell the editor to open the Copy-contentlet dialog
822
- * To copy a content and then edit it inline.
823
- */
824
- CUSTOMER_ACTIONS["COPY_CONTENTLET_INLINE_EDITING"] = "copy-contentlet-inline-editing";
825
- /**
826
- * Tell the editor to save inline edited contentlet
827
- */
828
- CUSTOMER_ACTIONS["UPDATE_CONTENTLET_INLINE_EDITING"] = "update-contentlet-inline-editing";
829
- /**
830
- * Tell the editor to trigger a menu reorder
831
- */
832
- CUSTOMER_ACTIONS["REORDER_MENU"] = "reorder-menu";
833
- /**
834
- * Tell the editor to send the page info to iframe
835
- */
836
- CUSTOMER_ACTIONS["GET_PAGE_DATA"] = "get-page-data";
837
- /**
838
- * Tell the editor an user send a graphql query
839
- */
840
- CUSTOMER_ACTIONS["CLIENT_READY"] = "client-ready";
841
- /**
842
- * Tell the editor to do nothing
843
- */
844
- CUSTOMER_ACTIONS["NOOP"] = "noop";
845
- })(CUSTOMER_ACTIONS || (CUSTOMER_ACTIONS = {}));
846
- /**
847
- * Post message to dotcms page editor
848
- *
849
- * @export
850
- * @template T
851
- * @param {PostMessageProps<T>} message
852
- */
853
- function postMessageToEditor(message) {
854
- window.parent.postMessage(message, '*');
855
- }
856
-
857
- /**
858
- * Actions received from the dotcms editor
859
- *
860
- * @export
861
- * @enum {number}
862
- */
863
- var NOTIFY_CUSTOMER;
864
- (function (NOTIFY_CUSTOMER) {
865
- /**
866
- * Request to page to reload
867
- */
868
- NOTIFY_CUSTOMER["EMA_RELOAD_PAGE"] = "ema-reload-page";
869
- /**
870
- * Request the bounds for the elements
871
- */
872
- NOTIFY_CUSTOMER["EMA_REQUEST_BOUNDS"] = "ema-request-bounds";
873
- /**
874
- * Received pong from the editor
875
- */
876
- NOTIFY_CUSTOMER["EMA_EDITOR_PONG"] = "ema-editor-pong";
877
- /**
878
- * Received scroll event trigger from the editor
879
- */
880
- NOTIFY_CUSTOMER["EMA_SCROLL_INSIDE_IFRAME"] = "scroll-inside-iframe";
881
- })(NOTIFY_CUSTOMER || (NOTIFY_CUSTOMER = {}));
882
-
883
- /**
884
- * Calculates the bounding information for each page element within the given containers.
885
- *
886
- * @export
887
- * @param {HTMLDivElement[]} containers
888
- * @return {*} An array of objects containing the bounding information for each page element.
889
- */
890
- function getPageElementBound(containers) {
891
- return containers.map((container) => {
892
- const containerRect = container.getBoundingClientRect();
893
- const contentlets = Array.from(container.querySelectorAll('[data-dot-object="contentlet"]'));
894
- return {
895
- x: containerRect.x,
896
- y: containerRect.y,
897
- width: containerRect.width,
898
- height: containerRect.height,
899
- payload: JSON.stringify({
900
- container: getContainerData(container)
901
- }),
902
- contentlets: getContentletsBound(containerRect, contentlets)
903
- };
904
- });
905
- }
906
- /**
907
- * An array of objects containing the bounding information for each contentlet inside a container.
908
- *
909
- * @export
910
- * @param {DOMRect} containerRect
911
- * @param {HTMLDivElement[]} contentlets
912
- * @return {*}
913
- */
914
- function getContentletsBound(containerRect, contentlets) {
915
- return contentlets.map((contentlet) => {
916
- const contentletRect = contentlet.getBoundingClientRect();
917
- return {
918
- x: 0,
919
- y: contentletRect.y - containerRect.y,
920
- width: contentletRect.width,
921
- height: contentletRect.height,
922
- payload: JSON.stringify({
923
- container: contentlet.dataset?.['dotContainer']
924
- ? JSON.parse(contentlet.dataset?.['dotContainer'])
925
- : getClosestContainerData(contentlet),
926
- contentlet: {
927
- identifier: contentlet.dataset?.['dotIdentifier'],
928
- title: contentlet.dataset?.['dotTitle'],
929
- inode: contentlet.dataset?.['dotInode'],
930
- contentType: contentlet.dataset?.['dotType']
931
- }
932
- })
933
- };
934
- });
935
- }
936
- /**
937
- * Get container data from VTLS.
938
- *
939
- * @export
940
- * @param {HTMLElement} container
941
- * @return {*}
942
- */
943
- function getContainerData(container) {
944
- return {
945
- acceptTypes: container.dataset?.['dotAcceptTypes'] || '',
946
- identifier: container.dataset?.['dotIdentifier'] || '',
947
- maxContentlets: container.dataset?.['maxContentlets'] || '',
948
- uuid: container.dataset?.['dotUuid'] || ''
949
- };
950
- }
951
- /**
952
- * Get the closest container data from the contentlet.
953
- *
954
- * @export
955
- * @param {Element} element
956
- * @return {*}
957
- */
958
- function getClosestContainerData(element) {
959
- // Find the closest ancestor element with data-dot-object="container" attribute
960
- const container = element.closest('[data-dot-object="container"]');
961
- // If a container element is found
962
- if (container) {
963
- // Return the dataset of the container element
964
- return getContainerData(container);
965
- }
966
- else {
967
- // If no container element is found, return null
968
- console.warn('No container found for the contentlet');
969
- return null;
970
- }
971
- }
972
- /**
973
- * Find the closest contentlet element based on HTMLElement.
974
- *
975
- * @export
976
- * @param {(HTMLElement | null)} element
977
- * @return {*}
978
- */
979
- function findDotElement(element) {
980
- if (!element)
981
- return null;
982
- if (element?.dataset?.['dotObject'] === 'contentlet' ||
983
- (element?.dataset?.['dotObject'] === 'container' && element.children.length === 0)) {
984
- return element;
985
- }
986
- return findDotElement(element?.['parentElement']);
987
- }
988
- function findVTLData(target) {
989
- const vltElements = target.querySelectorAll('[data-dot-object="vtl-file"]');
990
- if (!vltElements.length) {
991
- return null;
992
- }
993
- return Array.from(vltElements).map((vltElement) => {
994
- return {
995
- inode: vltElement.dataset?.['dotInode'],
996
- name: vltElement.dataset?.['dotUrl']
997
- };
998
- });
999
- }
1000
- function scrollIsInBottom() {
1001
- const documentHeight = document.documentElement.scrollHeight;
1002
- const viewportHeight = window.innerHeight;
1003
- const scrollY = window.scrollY;
1004
- return scrollY + viewportHeight >= documentHeight;
1005
- }
1006
-
1007
- /**
1008
- * Represents an array of DotCMSPageEditorSubscription objects.
1009
- * Used to store the subscriptions for the editor and unsubscribe later.
1010
- */
1011
- const subscriptions = [];
1012
- /**
1013
- * Sets the bounds of the containers in the editor.
1014
- * Retrieves the containers from the DOM and sends their position data to the editor.
1015
- * @private
1016
- * @memberof DotCMSPageEditor
1017
- */
1018
- function setBounds() {
1019
- const containers = Array.from(document.querySelectorAll('[data-dot-object="container"]'));
1020
- const positionData = getPageElementBound(containers);
1021
- postMessageToEditor({
1022
- action: CUSTOMER_ACTIONS.SET_BOUNDS,
1023
- payload: positionData
1024
- });
1025
- }
1026
- /**
1027
- * Listens for editor messages and performs corresding actions based on the received message.
1028
- *
1029
- * @private
1030
- * @memberof DotCMSPageEditor
1031
- */
1032
- function listenEditorMessages() {
1033
- const messageCallback = (event) => {
1034
- switch (event.data) {
1035
- case NOTIFY_CUSTOMER.EMA_REQUEST_BOUNDS: {
1036
- setBounds();
1037
- break;
1038
- }
1039
- }
1040
- if (event.data.name === NOTIFY_CUSTOMER.EMA_SCROLL_INSIDE_IFRAME) {
1041
- const direction = event.data.direction;
1042
- if ((window.scrollY === 0 && direction === 'up') ||
1043
- (scrollIsInBottom() && direction === 'down')) {
1044
- /**
1045
- * If the iframe scroll is in the top of bottom, we dont send anything.
1046
- * This to avoid the lost of scrollend event
1047
- **/
1048
- return;
1049
- }
1050
- const scrollY = direction === 'up' ? -120 : 120;
1051
- window.scrollBy({ left: 0, top: scrollY, behavior: 'smooth' });
1052
- }
1053
- };
1054
- window.addEventListener('message', messageCallback);
1055
- subscriptions.push({
1056
- type: 'listener',
1057
- event: 'message',
1058
- callback: messageCallback
1059
- });
1060
- }
1061
- /**
1062
- * Listens for pointer move events and extracts information about the hovered contentlet.
1063
- *
1064
- * @private
1065
- * @memberof DotCMSPageEditor
1066
- */
1067
- function listenHoveredContentlet() {
1068
- const pointerMoveCallback = (event) => {
1069
- const foundElement = findDotElement(event.target);
1070
- if (!foundElement)
1071
- return;
1072
- const { x, y, width, height } = foundElement.getBoundingClientRect();
1073
- const isContainer = foundElement.dataset?.['dotObject'] === 'container';
1074
- const contentletForEmptyContainer = {
1075
- identifier: 'TEMP_EMPTY_CONTENTLET',
1076
- title: 'TEMP_EMPTY_CONTENTLET',
1077
- contentType: 'TEMP_EMPTY_CONTENTLET_TYPE',
1078
- inode: 'TEMPY_EMPTY_CONTENTLET_INODE',
1079
- widgetTitle: 'TEMP_EMPTY_CONTENTLET',
1080
- baseType: 'TEMP_EMPTY_CONTENTLET',
1081
- onNumberOfPages: 1
1082
- };
1083
- const contentlet = {
1084
- identifier: foundElement.dataset?.['dotIdentifier'],
1085
- title: foundElement.dataset?.['dotTitle'],
1086
- inode: foundElement.dataset?.['dotInode'],
1087
- contentType: foundElement.dataset?.['dotType'],
1088
- baseType: foundElement.dataset?.['dotBasetype'],
1089
- widgetTitle: foundElement.dataset?.['dotWidgetTitle'],
1090
- onNumberOfPages: foundElement.dataset?.['dotOnNumberOfPages']
1091
- };
1092
- const vtlFiles = findVTLData(foundElement);
1093
- const contentletPayload = {
1094
- container:
1095
- // Here extract dot-container from contentlet if is Headless
1096
- // or search in parent container if is VTL
1097
- foundElement.dataset?.['dotContainer']
1098
- ? JSON.parse(foundElement.dataset?.['dotContainer'])
1099
- : getClosestContainerData(foundElement),
1100
- contentlet: isContainer ? contentletForEmptyContainer : contentlet,
1101
- vtlFiles
1102
- };
1103
- postMessageToEditor({
1104
- action: CUSTOMER_ACTIONS.SET_CONTENTLET,
1105
- payload: {
1106
- x,
1107
- y,
1108
- width,
1109
- height,
1110
- payload: contentletPayload
1111
- }
1112
- });
1113
- };
1114
- document.addEventListener('pointermove', pointerMoveCallback);
1115
- subscriptions.push({
1116
- type: 'listener',
1117
- event: 'pointermove',
1118
- callback: pointerMoveCallback
1119
- });
1120
- }
1121
- /**
1122
- * Attaches a scroll event listener to the window
1123
- * and sends a message to the editor when the window is scrolled.
1124
- *
1125
- * @private
1126
- * @memberof DotCMSPageEditor
1127
- */
1128
- function scrollHandler() {
1129
- const scrollCallback = () => {
1130
- postMessageToEditor({
1131
- action: CUSTOMER_ACTIONS.IFRAME_SCROLL
1132
- });
1133
- window.lastScrollYPosition = window.scrollY;
1134
- };
1135
- const scrollEndCallback = () => {
1136
- postMessageToEditor({
1137
- action: CUSTOMER_ACTIONS.IFRAME_SCROLL_END
1138
- });
1139
- };
1140
- window.addEventListener('scroll', scrollCallback);
1141
- window.addEventListener('scrollend', scrollEndCallback);
1142
- subscriptions.push({
1143
- type: 'listener',
1144
- event: 'scroll',
1145
- callback: scrollEndCallback
1146
- });
1147
- subscriptions.push({
1148
- type: 'listener',
1149
- event: 'scroll',
1150
- callback: scrollCallback
1151
- });
1152
- }
1153
- /**
1154
- * Sends a message to the editor to get the page data.
1155
- * @param {string} pathname - The pathname of the page.
1156
- * @private
1157
- * @memberof DotCMSPageEditor
1158
- */
1159
- function fetchPageDataFromInsideUVE(pathname) {
1160
- postMessageToEditor({
1161
- action: CUSTOMER_ACTIONS.GET_PAGE_DATA,
1162
- payload: {
1163
- pathname
1164
- }
1165
- });
1166
- }
1167
-
1168
- /**
1169
- *
1170
- * Updates the navigation in the editor.
1171
- * @param {string} pathname - The pathname to update the navigation with.
1172
- * @memberof DotCMSPageEditor
1173
- */
1174
- function updateNavigation(pathname) {
1175
- postMessageToEditor({
1176
- action: CUSTOMER_ACTIONS.NAVIGATION_UPDATE,
1177
- payload: {
1178
- url: pathname === '/' ? 'index' : pathname?.replace('/', '')
1179
- }
1180
- });
1181
- }
1182
- /**
1183
- * Checks if the code is running inside an editor.
1184
- * @returns {boolean} Returns true if the code is running inside an editor, otherwise false.
1185
- */
1186
- function isInsideEditor() {
1187
- if (typeof window === 'undefined') {
1188
- return false;
1189
- }
1190
- return window.parent !== window;
1191
- }
1192
- /**
1193
- * Initializes the DotCMS page editor.
1194
- *
1195
- * @param conf - Optional configuration for the editor.
1196
- */
1197
- function initEditor(config) {
1198
- fetchPageDataFromInsideUVE(config.pathname);
1199
- listenEditorMessages();
1200
- listenHoveredContentlet();
1201
- scrollHandler();
1202
- }
1203
- /**
1204
- * Destroys the editor by removing event listeners and disconnecting observers.
1205
- */
1206
- function destroyEditor() {
1207
- subscriptions.forEach((subscription) => {
1208
- if (subscription.type === 'listener') {
1209
- window.removeEventListener(subscription.event, subscription.callback);
1210
- }
1211
- if (subscription.type === 'observer') {
1212
- subscription.observer.disconnect();
1213
- }
1214
- });
1215
- }
1216
-
1217
- var _DotCmsClient_config, _DotCmsClient_requestOptions, _DotCmsClient_listeners;
1218
- function getHostURL(url) {
1219
- try {
1220
- return new URL(url);
1221
- }
1222
- catch (error) {
1223
- return undefined;
1224
- }
1225
- }
1226
- /**
1227
- * `DotCmsClient` is a TypeScript class that provides methods to interact with the DotCMS REST API.
1228
- * It requires a configuration object on instantiation, which includes the DotCMS URL, site ID, and authentication token.
1229
- *
1230
- * @class DotCmsClient
1231
- *
1232
- * @property {ClientConfig} config - The configuration object for the DotCMS client.
1233
- *
1234
- * @method constructor(config: ClientConfig) - Constructs a new instance of the DotCmsClient class.
1235
- *
1236
- * @method page.get(options: PageApiOptions): Promise<unknown> - Retrieves all the elements of any Page in your dotCMS system in JSON format.
1237
- *
1238
- * @method nav.get(options: NavApiOptions = { depth: 0, path: '/', languageId: 1 }): Promise<unknown> - Retrieves information about the dotCMS file and folder tree.
1239
- *
1240
- */
1241
- class DotCmsClient {
1242
- constructor(config = { dotcmsUrl: '', authToken: '', requestOptions: {}, siteId: '' }) {
1243
- _DotCmsClient_config.set(this, void 0);
1244
- _DotCmsClient_requestOptions.set(this, void 0);
1245
- _DotCmsClient_listeners.set(this, []);
1246
- this.page = {
1247
- /**
1248
- * `page.get` is an asynchronous method of the `DotCmsClient` class that retrieves all the elements of any Page in your dotCMS system in JSON format.
1249
- * It takes a `PageApiOptions` object as a parameter and returns a Promise that resolves to the response from the DotCMS API.
1250
- *
1251
- * The Page API enables you to retrieve all the elements of any Page in your dotCMS system.
1252
- * The elements may be retrieved in JSON format.
1253
- *
1254
- * @link https://www.dotcms.com/docs/latest/page-rest-api-layout-as-a-service-laas
1255
- * @async
1256
- * @param {PageApiOptions} options - The options for the Page API call.
1257
- * @returns {Promise<unknown>} - A Promise that resolves to the response from the DotCMS API.
1258
- * @throws {Error} - Throws an error if the options are not valid.
1259
- */
1260
- get: async (options) => {
1261
- this.validatePageOptions(options);
1262
- const queryParamsObj = {};
1263
- for (const [key, value] of Object.entries(options)) {
1264
- if (value === undefined || key === 'path' || key === 'siteId')
1265
- continue;
1266
- if (key === 'personaId') {
1267
- queryParamsObj['com.dotmarketing.persona.id'] = String(value);
1268
- }
1269
- else if (key === 'mode' && value) {
1270
- queryParamsObj['mode'] = String(value);
1271
- }
1272
- else {
1273
- queryParamsObj[key] = String(value);
1274
- }
1275
- }
1276
- const queryHostId = options.siteId ?? __classPrivateFieldGet(this, _DotCmsClient_config, "f").siteId ?? '';
1277
- if (queryHostId) {
1278
- queryParamsObj['host_id'] = queryHostId;
1279
- }
1280
- const queryParams = new URLSearchParams(queryParamsObj).toString();
1281
- const formattedPath = options.path.startsWith('/') ? options.path : `/${options.path}`;
1282
- const url = `${__classPrivateFieldGet(this, _DotCmsClient_config, "f").dotcmsUrl}/api/v1/page/json${formattedPath}${queryParams ? `?${queryParams}` : ''}`;
1283
- const response = await fetch(url, __classPrivateFieldGet(this, _DotCmsClient_requestOptions, "f"));
1284
- if (!response.ok) {
1285
- const error = {
1286
- status: response.status,
1287
- message: ErrorMessages[response.status] || response.statusText
1288
- };
1289
- console.error(error);
1290
- throw error;
1291
- }
1292
- return response.json().then((data) => data.entity);
1293
- }
1294
- };
1295
- this.editor = {
1296
- /**
1297
- * `editor.on` is an asynchronous method of the `DotCmsClient` class that allows you to react to actions issued by the UVE.
1298
- *
1299
- * NOTE: This is being used by the development team - This logic is probably varied or moved to another function/object.
1300
- * @param action - The name of the name emitted by UVE
1301
- * @param callbackFn - The function to execute when the UVE emits the action
1302
- */
1303
- on: (action, callbackFn) => {
1304
- if (!isInsideEditor()) {
1305
- return;
1306
- }
1307
- if (action === 'changes') {
1308
- const messageCallback = (event) => {
1309
- if (event.data.name === 'SET_PAGE_DATA') {
1310
- callbackFn(event.data.payload);
1311
- }
1312
- };
1313
- window.addEventListener('message', messageCallback);
1314
- __classPrivateFieldGet(this, _DotCmsClient_listeners, "f").push({ event: 'message', callback: messageCallback, action });
1315
- }
1316
- },
1317
- /**
1318
- * `editor.off` is an synchronous method of the `DotCmsClient` class that allows you to stop listening and reacting to an action issued by UVE.
1319
- *
1320
- * NOTE: This is being used by the development team - This logic is probably varied or moved to another function/object.
1321
- * @param action
1322
- */
1323
- off: (action) => {
1324
- const listenerIndex = __classPrivateFieldGet(this, _DotCmsClient_listeners, "f").findIndex((listener) => listener.action === action);
1325
- if (listenerIndex !== -1) {
1326
- const listener = __classPrivateFieldGet(this, _DotCmsClient_listeners, "f")[listenerIndex];
1327
- window.removeEventListener(listener.event, listener.callback);
1328
- __classPrivateFieldGet(this, _DotCmsClient_listeners, "f").splice(listenerIndex, 1);
1329
- }
1330
- }
1331
- };
1332
- this.nav = {
1333
- /**
1334
- * `nav.get` is an asynchronous method of the `DotCmsClient` class that retrieves information about the dotCMS file and folder tree.
1335
- * It takes a `NavApiOptions` object as a parameter (with default values) and returns a Promise that resolves to the response from the DotCMS API.
1336
- *
1337
- * The navigation REST API enables you to retrieve information about the dotCMS file and folder tree through REST API calls.
1338
- * @link https://www.dotcms.com/docs/latest/navigation-rest-api
1339
- * @async
1340
- * @param {NavApiOptions} options - The options for the Nav API call. Defaults to `{ depth: 0, path: '/', languageId: 1 }`.
1341
- * @returns {Promise<unknown>} - A Promise that resolves to the response from the DotCMS API.
1342
- * @throws {Error} - Throws an error if the options are not valid.
1343
- */
1344
- get: async (options = { depth: 0, path: '/', languageId: 1 }) => {
1345
- this.validateNavOptions(options);
1346
- // Extract the 'path' from the options and prepare the rest as query parameters
1347
- const { path, ...queryParamsOptions } = options;
1348
- const queryParamsObj = {};
1349
- Object.entries(queryParamsOptions).forEach(([key, value]) => {
1350
- if (value !== undefined) {
1351
- queryParamsObj[key] = String(value);
1352
- }
1353
- });
1354
- const queryParams = new URLSearchParams(queryParamsObj).toString();
1355
- // Format the URL correctly depending on the 'path' value
1356
- const formattedPath = path === '/' ? '/' : `/${path}`;
1357
- const url = `${__classPrivateFieldGet(this, _DotCmsClient_config, "f").dotcmsUrl}/api/v1/nav${formattedPath}${queryParams ? `?${queryParams}` : ''}`;
1358
- const response = await fetch(url, __classPrivateFieldGet(this, _DotCmsClient_requestOptions, "f"));
1359
- return response.json();
1360
- }
1361
- };
1362
- if (!config.dotcmsUrl) {
1363
- throw new Error("Invalid configuration - 'dotcmsUrl' is required");
1364
- }
1365
- this.dotcmsUrl = getHostURL(config.dotcmsUrl)?.origin;
1366
- if (!this.dotcmsUrl) {
1367
- throw new Error("Invalid configuration - 'dotcmsUrl' must be a valid URL");
1368
- }
1369
- if (!config.authToken) {
1370
- throw new Error("Invalid configuration - 'authToken' is required");
1371
- }
1372
- __classPrivateFieldSet(this, _DotCmsClient_config, {
1373
- ...config,
1374
- dotcmsUrl: this.dotcmsUrl
1375
- }, "f");
1376
- __classPrivateFieldSet(this, _DotCmsClient_requestOptions, {
1377
- ...__classPrivateFieldGet(this, _DotCmsClient_config, "f").requestOptions,
1378
- headers: {
1379
- Authorization: `Bearer ${__classPrivateFieldGet(this, _DotCmsClient_config, "f").authToken}`,
1380
- ...__classPrivateFieldGet(this, _DotCmsClient_config, "f").requestOptions?.headers
1381
- }
1382
- }, "f");
1383
- this.content = new Content(__classPrivateFieldGet(this, _DotCmsClient_requestOptions, "f"), __classPrivateFieldGet(this, _DotCmsClient_config, "f").dotcmsUrl);
1384
- }
1385
- static init(config) {
1386
- if (this.instance) {
1387
- console.warn('DotCmsClient has already been initialized. Please use the instance to interact with the DotCMS API.');
1388
- }
1389
- return this.instance ?? (this.instance = new DotCmsClient(config));
1390
- }
1391
- static get dotcmsUrl() {
1392
- return (this.instance && __classPrivateFieldGet(this.instance, _DotCmsClient_config, "f").dotcmsUrl) || '';
1393
- }
1394
- validatePageOptions(options) {
1395
- if (!options.path) {
1396
- throw new Error("The 'path' parameter is required for the Page API");
1397
- }
1398
- }
1399
- validateNavOptions(options) {
1400
- if (!options.path) {
1401
- throw new Error("The 'path' parameter is required for the Nav API");
1402
- }
1403
- }
1404
- }
1405
- _DotCmsClient_config = new WeakMap(), _DotCmsClient_requestOptions = new WeakMap(), _DotCmsClient_listeners = new WeakMap();
1406
-
1407
- // For now, we are not typing the functions in this file
1408
- /* eslint-disable @typescript-eslint/no-explicit-any */
1409
- const graphqlToPageEntity = ({ page }) => {
1410
- // If there is no page, return null
1411
- if (!page) {
1412
- return null;
1413
- }
1414
- const { layout, template, containers, urlContentMap, viewAs, site, _map, ...pageAsset } = page;
1415
- const data = _map || {};
1416
- return {
1417
- layout,
1418
- template,
1419
- viewAs,
1420
- urlContentMap,
1421
- site,
1422
- page: {
1423
- ...data,
1424
- ...pageAsset
1425
- },
1426
- containers: parseContainers(containers)
1427
- };
1428
- };
1429
- const parseContainers = (containers = []) => {
1430
- return containers.reduce((acc, container) => {
1431
- const { path, identifier, containerStructures, containerContentlets, ...rest } = container;
1432
- const key = (path || identifier);
1433
- acc[key] = {
1434
- containerStructures,
1435
- container: {
1436
- path,
1437
- identifier,
1438
- ...rest
1439
- },
1440
- contentlets: parseContentletsToUuidMap(containerContentlets)
1441
- };
1442
- return acc;
1443
- }, {});
1444
- };
1445
- const parseContentletsToUuidMap = (containerContentlets) => {
1446
- return containerContentlets.reduce((acc, containerContentlet) => {
1447
- const { uuid, contentlets } = containerContentlet;
1448
- // TODO: This is a temporary solution, we need to find a better way to handle this.
1449
- acc[uuid] = contentlets.map(({ _map = {}, ...rest }) => {
1450
- return {
1451
- ..._map,
1452
- ...rest
1453
- };
1454
- });
1455
- return acc;
1456
- }, {});
1457
- };
1458
-
1459
- const getPageRequestParams = ({ path = '', params = {} }) => {
1460
- const copiedParams = params instanceof URLSearchParams ? Object.fromEntries(params.entries()) : { ...params };
1461
- const finalParams = {};
1462
- const dotMarketingPersonaId = copiedParams['com.dotmarketing.persona.id'] || '';
1463
- if (copiedParams['mode']) {
1464
- finalParams['mode'] = copiedParams['mode'];
1465
- }
1466
- if (copiedParams['language_id']) {
1467
- finalParams['language_id'] = copiedParams['language_id'];
1468
- }
1469
- if (copiedParams['variantName']) {
1470
- finalParams['variantName'] = copiedParams['variantName'];
1471
- }
1472
- if (copiedParams['personaId'] || dotMarketingPersonaId) {
1473
- finalParams['personaId'] = copiedParams['personaId'] || dotMarketingPersonaId;
1474
- }
1475
- return {
1476
- path,
1477
- ...finalParams
1478
- };
1479
- };
1480
-
1481
- export { CUSTOMER_ACTIONS, DotCmsClient, destroyEditor, getPageRequestParams, graphqlToPageEntity, initEditor, isInsideEditor, postMessageToEditor, updateNavigation };