@compilacion/colleciones-clientos 2.0.5 → 2.0.7

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.
@@ -1,924 +1,962 @@
1
1
  (function () {
2
- 'use strict';
3
-
4
- // helper 'private' functions
5
-
6
-
7
- /**
8
- * Encodes a string to Base64.
9
- * Uses browser or Node.js method depending on environment.
10
- * @param {string} str
11
- * @returns {string}
12
- */
13
- const toBase64 = function (str) {
14
- if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
15
- return window.btoa(unescape(encodeURIComponent(str)));
16
- } else {
17
- return Buffer.from(str, 'utf-8').toString('base64');
18
- }
19
- };
20
-
21
- /**
22
- * Collects browser-related context values like screen size, language, etc.
23
- * Returns an empty object if not in browser environment.
24
- * @returns {Object}
25
- */
26
- const getBrowserContext = function() {
27
- if (typeof window === 'undefined' || typeof navigator === 'undefined') {
28
- return {};
29
- }
30
- return {
31
- hasFocus: document.hasFocus(),
32
- language: navigator.language,
33
- platform: navigator.platform,
34
- referrer: document.referrer,
35
- screenHeight: window.screen.height,
36
- screenWidth: window.screen.width,
37
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
38
- url: window.location.href,
39
- userAgent: navigator.userAgent,
40
- viewportHeight: window.innerHeight,
41
- viewportWidth: window.innerWidth,
42
- };
43
- };
44
-
45
- /**
46
- * CollecionesEvent
47
- * -----------------
48
- * Base class representing a semantically structured event object.
49
- * Each event models a specific interaction with an entity, optionally performed by an actor,
50
- * and may reference related entities or include contextual metadata.
51
- *
52
- * Key features:
53
- * - Captures structured semantics: entity, action, actor, context, references
54
- * - Supports multiple identifiers for both the main entity and the actor
55
- * - Allows origin tagging for cross-context or cross-application references
56
- * - Supports referencing collections of entities or grouped data
57
- * - Includes timestamps and tracker/app metadata for auditability
58
- * - Fully serializable and deserializable via toJSON/fromJSON
59
- */
60
- class CollecionesEvent {
61
-
62
- /**
63
- * Constructs a new CollecionesEvent with default structure and timestamps.
64
- * Initializes empty containers for semantic attributes such as:
65
- * - entity: the subject of the event
66
- * - adjectives: descriptors of the entity
67
- * - identifiers: identifiers of the entity
68
- * - action: what happened to the entity
69
- * - actor: who or what triggered the event (with identifiers in actorIdentifiers)
70
- * - context: environmental data related to the event
71
- * - references: external entities involved, optionally scoped by origin
72
- * - collections: groups of related entities
73
- * - meta: tracking metadata and timestamps
74
- */
75
- constructor() {
76
- // initialize event properties
77
- this.entity = '';
78
- this.adjevtives = [];
79
- this.identifiers = {};
80
- this.action = '';
81
- this.actor = {};
82
- this.actorIdentifiers = {};
83
- this.context = {};
84
- this.references = {};
85
- this.collections = {};
86
- // set default values
87
- this.meta = {
88
- eventFormat: 'CollecionesEvent',
89
- eventFormatVersion: '1'
90
- };
91
- this.meta.tracker = '';
92
- this.meta.app = '';
93
- this.meta.timestamps = {};
94
- this.meta.timestamps.clientDatetimeUtc = new Date().toISOString();
95
- if (typeof window !== 'undefined' && typeof navigator !== 'undefined' && navigator.language) {
96
- this.meta.timestamps.clientDatetimeLocal = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString();
97
- this.meta.timestamps.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
98
- this.meta.timestamps.timeZoneOffset = new Date().getTimezoneOffset();
99
- } else {
100
- this.meta.timestamps.clientDatetimeLocal = new Date().toISOString();
101
- this.meta.timestamps.timeZone = 'UTC';
102
- }
103
- }
104
-
105
- /**
106
- * Returns the declared event format.
107
- * @returns {string} The format name (e.g. 'CollecionesEvent').
108
- */
109
- getEventFormat() {
110
- let v = this.meta?.eventFormat;
111
- return (typeof v !== 'undefined') ? v : '1';
112
- }
113
-
114
- /**
115
- * Returns the version of the event format.
116
- * @returns {string} The format version string.
117
- */
118
- getEventFormatVersion() {
119
- let v = this?.meta?.eventFormatVersion;
120
- return (typeof v !== 'undefined') ? v : 'CollecionesEvent';
121
- }
122
-
123
- /**
124
- * Overrides or supplements the event's timestamp fields with custom values.
125
- * @param {object} dateTimeObject - Key-value pairs to merge into the existing timestamp object.
126
- */
127
- overrideDatetime(dateTimeObject = {}) {
128
- for (const [key, value] of Object.entries(dateTimeObject)) {
129
- this.meta.timestamps[key] = value;
130
- }
131
- }
132
-
133
- /**
134
- * Sets the name of the tracker responsible for generating this event.
135
- * @param {string} name - Tracker name.
136
- */
137
- setTracker(name) {
138
- this.meta.tracker = name;
139
- }
140
-
141
- /**
142
- * Sets the name of the application that generated the event.
143
- * @param {string} name - Application name.
144
- */
145
- setAppName(name) {
146
- this.meta.appName = name;
147
- }
148
-
149
- /**
150
- * Sets the expected schema name for this event.
151
- * @param {string} schema - The name of the schema.
152
- */
153
- setSchema(schema) {
154
- if (typeof schema !== 'string') {
155
- throw new Error('Schema must be a string');
156
- }
157
- this.meta.schema = schema;
158
- }
159
-
160
- /**
161
- * Sets the entity (subject) of the event.
162
- * @param {string} entity - The entity name.
163
- */
164
- setEntity = function(entity) {
165
- this.entity = entity;
166
- }
167
-
168
- /**
169
- * Defines the main action of the event (e.g., 'clicked').
170
- * @param {string} action - The action string.
171
- */
172
- setAction = function(action) {
173
- this.action = action;
174
- }
175
-
176
- /**
177
- * Adds an adjective that describes the entity in more detail.
178
- * @param {string} adjective - An adjective string.
179
- */
180
- addAdjective = function(adjective) {
181
- if (typeof adjective !== 'string') {
182
- throw new Error('Adjective must be a string');
183
- }
184
- this.adjevtives.push(adjective);
185
- }
186
-
187
- /**
188
- * Adds or updates an identifier for the primary entity.
189
- * Identifiers allow multiple keys to uniquely identify the entity.
190
- * @param {string} name - The identifier key.
191
- * @param {*} identifier - The identifier value.
192
- */
193
- setIdentifier = function(name, identifier) {
194
- if (typeof name !== 'string') {
195
- throw new Error('Identifier name must be a string');
196
- }
197
- this.identifiers[name] = identifier;
198
- }
199
-
200
- /**
201
- * Defines the name of the actor (who or what performed the action).
202
- * @param {string} name - Actor name (e.g., 'user', 'system').
203
- */
204
- setActor = function(name) {
205
- if (typeof name !== 'string') {
206
- throw new Error('Actor name must be a string');
207
- }
208
- this.actor.name = name;
209
- }
210
-
211
- /**
212
- * Adds or updates an identifier for the actor.
213
- * Supports multiple identifiers to uniquely identify the actor.
214
- * @param {string} name - Identifier key.
215
- * @param {*} identifier - Identifier value.
216
- */
217
- setActorIdentifier = function(name, identifier) {
218
- if (typeof name !== 'string') {
219
- throw new Error('Actor Identifier name must be a string');
220
- }
221
- this.actorIdentifiers[name] = identifier;
222
- }
223
-
224
- /**
225
- * Adds contextual information to the event.
226
- * Context can include any additional environmental or situational data.
227
- * @param {string} context - The key of the context field.
228
- * @param {*} value - The value of the context field.
229
- */
230
- setContext = function(context, value) {
231
- if (typeof context !== 'string') {
232
- throw new Error('Context must be a string');
233
- }
234
- this.context[context] = value;
235
- }
236
-
237
- /**
238
- * Alias for `setReference` for compatibility.
239
- * Declares an external entity referenced by this event.
240
- * @param {string} entity - The referenced entity name.
241
- * @param {string|null} origin - The origin application or context (optional).
242
- */
243
- setRefence = function(entity, origin=null) {
244
- return this.setReference(entity, origin);
245
- }
246
-
247
- /**
248
- * Declares an entity referenced by this event.
249
- * References may include multiple identifiers and an optional origin to scope the reference.
250
- * @param {string} entity - The referenced entity name.
251
- * @param {string|null} origin - The origin application or context (optional).
252
- */
253
- setReference = function(entity, origin=null) {
254
- if (typeof entity !== 'string') {
255
- throw new Error('Referenced entity must be a string');
256
- }
257
- if(this.references[entity] === undefined) {
258
- this.references[entity] = {
259
- identifiers: {},
260
- origin
261
- };
262
- }
263
- }
264
-
265
- /**
266
- * Adds or updates an identifier for a referenced entity.
267
- * Ensures the reference is declared and sets the identifier under that reference.
268
- * @param {string} entity - The referenced entity name.
269
- * @param {string} name - The identifier key.
270
- * @param {*} identifier - The identifier value.
271
- * @param {string|null} origin - Optional origin context.
272
- */
273
- setRefenceIdentifier = function(entity, name, identifier, origin=null) {
274
- return this.setReferenceIdentifier(entity, name, identifier, origin);
275
- }
276
-
277
- /**
278
- * Adds or updates an identifier for a referenced entity.
279
- * @param {string} entity - The referenced entity name.
280
- * @param {string} name - The identifier key.
281
- * @param {*} identifier - The identifier value.
282
- * @param {string|null} origin - Optional origin context.
283
- */
284
- setReferenceIdentifier = function(entity, name, identifier, origin=null) {
285
- if (typeof entity !== 'string') {
286
- throw new Error('Referenced entity name must be a string');
287
- }
288
- if (typeof name !== 'string') {
289
- throw new Error('Actor Identifier name must be a string');
290
- }
291
- this.setRefence(entity, origin);
292
- this.references[entity].identifiers[name] = identifier;
293
- }
294
-
295
- /**
296
- * Declares a collection of related entities for this event.
297
- * Collections group multiple related items and may include identifiers and origin metadata.
298
- * @param {string} entity - The collection name.
299
- * @param {string|null} origin - Optional origin identifier (e.g. system name).
300
- */
301
- setCollection = function(entity, origin=null) {
302
- if(this.collections[entity] == undefined) {
303
- this.collections[entity] = {
304
- items: [],
305
- identifiers: {},
306
- origin
307
- };
308
- }
309
- }
310
-
311
- /**
312
- * Adds a new item to a collection and returns its index key.
313
- * Items represent individual elements within the collection.
314
- * @param {string} entity - The name of the collection.
315
- * @returns {number} Index of the newly added item in the collection.
316
- */
317
- setCollectionItem = function(entity) {
318
- this.setCollection(entity);
319
- this.collections[entity].items.push({});
320
- let itemKey = this.collections[entity].items.length - 1;
321
- return itemKey;
322
- }
323
-
324
- /**
325
- * Assigns a reference (identifier) to a specific item in a collection.
326
- * Useful for tagging individual collection elements with identifiers.
327
- * @param {string} entity - Collection name.
328
- * @param {number} itemKey - The index of the item in the collection.
329
- * @param {string} name - The identifier key.
330
- * @param {*} identifier - The identifier value.
331
- * @throws {Error} If the item does not exist at the given index.
332
- */
333
- setCollectionItemReference = function(entity, itemKey, name, identifier) {
334
- this.setCollection(entity);
335
- if(typeof this.collections[entity].items[itemKey] !== 'object') {
336
- throw new Error('bad bad man, the collection key does not exists');
337
- }
338
- this.collections[entity].items[itemKey][name] = identifier;
339
- }
340
-
341
- /**
342
- * Sets a static identifier that applies to the entire collection.
343
- * These identifiers describe the collection as a whole.
344
- * @param {string} entity - Collection name.
345
- * @param {string} name - Identifier key.
346
- * @param {*} identifier - Identifier value.
347
- */
348
- setCollectionIdentifier = function(entity, name, identifier) {
349
- if(this.collections[entity] == undefined) {
350
- this.collections[entity] = {};
351
- }
352
- this.collections[entity].identifiers[name] = identifier;
353
- }
354
-
355
- /**
356
- * Serializes the event instance to a plain object suitable for transport or storage.
357
- * The output includes all semantic fields and metadata.
358
- * @returns {object} A plain JavaScript object representing the event.
359
- */
360
- toJSON() {
361
- return {
362
- class: 'CollecionesEvent',
363
- entity: this.entity,
364
- adjectives: this.adjevtives,
365
- identifiers: this.identifiers,
366
- action: this.action,
367
- actor: this.actor,
368
- actorIdentifiers: this.actorIdentifiers,
369
- actorIds: this.actorIds,
370
- context: this.context,
371
- references: this.references,
372
- meta: this.meta,
373
- collections: this.collections
374
- };
375
- }
376
-
377
- /**
378
- * Recreates a CollecionesEvent instance from a plain object.
379
- * Used when deserializing events from storage or network transport.
380
- * @param {object} obj - The input object containing event data.
381
- * @returns {CollecionesEvent} A rehydrated event instance.
382
- * @throws {Error} If the class type is not 'CollecionesEvent'.
383
- */
384
- static fromJSON(obj) {
385
- if (!obj || obj.class !== 'CollecionesEvent') {
386
- throw new Error('Invalid or missing event class type');
387
- }
388
- const instance = new CollecionesEvent();
389
- instance.entity = obj.entity;
390
- instance.adjevtives = obj.adjectives || [];
391
- instance.identifiers = obj.identifiers || {};
392
- instance.action = obj.action;
393
- instance.actor = obj.actor;
394
- instance.actorIdentifiers = obj.actorIdentifiers;
395
- instance.actorIds = obj.actorIds;
396
- instance.context = obj.context || {};
397
- instance.references = obj.references || {};
398
- instance.meta = obj.meta || {};
399
- instance.collections = obj.collections || {};
400
- return instance;
401
- }
402
-
403
- }
404
-
405
- /**
406
- * CollecionesEmitter
407
- * -------------------
408
- * This class collects and sends event objects to a remote endpoint (e.g., an event collector API).
409
- * It is used in both client- and server-side tracking scenarios, typically in combination with
410
- * CollecionesEvent or subclasses like CollecionesBaseEvent.
411
- *
412
- * Behavior:
413
- * - Events are buffered via `.track()` or `.trackAsync()`.
414
- * - If the number of buffered events reaches `flushSize`, the buffer is automatically flushed.
415
- * - If `flushInterval` is provided, the buffer is flushed at a fixed interval.
416
- * - Flushing serializes each event using `.toJSON()`, encodes it with base64, and posts
417
- * the resulting array to the configured endpoint.
418
- *
419
- * Example usage:
420
- * const emitter = new CollecionesEmitter('/track', 5, 10000);
421
- * emitter.track(new CollecionesEvent());
422
- *
423
- * Note:
424
- * This class is stateful. To stop periodic flushing, call `.stopTimer()` when the emitter is no longer in use.
425
- */
426
- class CollecionesEmitter {
427
-
428
- /**
429
- * Initializes the emitter with buffering settings.
430
- * @param {string} [endpoint='/collect'] - The URL to send events to.
431
- * @param {number} [flushSize=10] - Number of events to buffer before flushing.
432
- * @param {number|boolean} [flushInterval=false] - Time in ms to flush events periodically.
433
- */
434
- constructor(endpoint = '/collect', flushSize = 10, flushInterval = false) {
435
- this.endpoint = endpoint;
436
- this.flushInterval = flushInterval;
437
- this.flushSize = flushSize;
438
- this.buffer = [];
439
- this.timer = null;
440
- this.lastPayload = null;
441
- }
442
-
443
- /**
444
- * Starts the flush timer if a valid interval is set.
445
- * @returns {void}
446
- */
447
- startTimer() {
448
- this.stopTimer();
449
- if (typeof this.flushInterval == 'number' && this.flushInterval > 0) {
450
- this.timer = setInterval(() => this.flush(), this.flushInterval);
451
- }
452
- }
453
-
454
- /**
455
- * Starts the flush timer only if not already running.
456
- * @returns {void}
457
- */
458
- startTimerIfStopped() {
459
- if (!this.timer) {
460
- this.startTimer();
461
- }
462
- }
463
-
464
- /**
465
- * Stops the active flush timer.
466
- * @returns {void}
467
- */
468
- stopTimer() {
469
- if (this.timer) {
470
- clearInterval(this.timer);
471
- }
472
- this.timer = null;
473
- }
474
-
475
- /**
476
- * Adds an event to the buffer and flushes if threshold is reached.
477
- * Validates that the event is an instance of CollecionesEvent to ensure correct event type.
478
- * @param {CollecionesEvent} event - Event instance to be tracked.
479
- * @throws {Error} Throws if event is not a CollecionesEvent instance.
480
- * @returns {void}
481
- */
482
- track(event) {
483
- if (!(event instanceof CollecionesEvent)) {
484
- throw new Error('Event must be an instance of CollecionesEvent');
485
- }
486
- this.trackAsync(event);
487
- }
488
-
489
- /**
490
- * Asynchronously adds an event and flushes if the buffer size is exceeded.
491
- * Validates that the event is an instance of CollecionesEvent to ensure correct event type.
492
- * @param {CollecionesEvent} event - Event instance to be tracked asynchronously.
493
- * @throws {Error} Throws if event is not a CollecionesEvent instance.
494
- * @returns {Promise<void>} Resolves when event is added and flush triggered if needed.
495
- */
496
- async trackAsync(event) {
497
- if (!(event instanceof CollecionesEvent)) {
498
- throw new Error('Event must be an instance of CollecionesEvent');
499
- }
500
- this.startTimerIfStopped();
501
- this.buffer.push(event);
502
- return (this.buffer.length >= this.flushSize) ? this.flush() : Promise.resolve();
503
- }
504
-
505
- /**
506
- * Sends all buffered events in a single POST request to the server.
507
- * Each event is serialized via `.toJSON()` and encoded as a base64 string.
508
- * Response status is checked for HTTP success; errors are logged but not thrown.
509
- *
510
- * @returns {Promise<boolean|undefined>} Resolves true if flush was triggered, or undefined if buffer was empty.
511
- */
512
- async flush() {
513
- if (this.buffer.length === 0) return;
514
- this.stopTimer();
515
- const body = this.buildBody();
516
- this.lastPayload = body;
517
- this.buffer = [];
518
- try {
519
- const response = await fetch(this.endpoint, {
520
- method: 'POST',
521
- credentials: 'include',
522
- headers: {
523
- 'Content-Type': 'application/json'
524
- },
525
- body
526
- });
527
- if (!response.ok) {
528
- console.log(`Failed to send events: ${response.statusText}`);
529
- }
530
- return true;
531
- } catch (error) {
532
- console.log(`Network error sending events: ${error.message}`);
533
- }
534
- }
535
-
536
- /**
537
- * Builds a POST-ready payload from the current buffer, without clearing it.
538
- * @returns {string} JSON string of base64-encoded serialized events.
539
- */
540
- buildBody() {
541
- return JSON.stringify(this.buffer.map(e => toBase64(JSON.stringify(e.toJSON()))));
542
- }
543
-
544
- }
545
-
546
- /**
547
- * Tracks events by enriching them with shared identifiers and routing through configured emitters.
548
- */
549
- class CollecionesTracker {
550
-
551
- /**
552
- * Constructs a new tracker instance.
553
- * @param {Array} emitters - Array of emitter instances responsible for sending events.
554
- * @param {string} trackerName - Name identifying this tracker.
555
- * @param {string} appName - Name of the application generating events.
556
- */
557
- constructor(emitters, trackerName, appName) {
558
- this.emitters = emitters;
559
- this.trackerName = trackerName;
560
- this.appName = appName;
561
- }
562
-
563
- /**
564
- * Sends an event to all emitters after enriching it with identifiers and metadata.
565
- * @param {CollecionesEvent} collecionesEvent - The event to be sent.
566
- * @throws {Error} If the input is not an instance of CollecionesEvent.
567
- */
568
- track(collecionesEvent) {
569
- if (!(collecionesEvent instanceof CollecionesEvent)) {
570
- throw new Error('Event must be of type CollecionesEvent');
571
- }
572
- collecionesEvent.setTracker(this.trackerName);
573
- collecionesEvent.setAppName(this.appName);
574
- this.emitters.forEach(element => {
575
- element.track(collecionesEvent, this.trackerName, this.appName);
576
- });
577
- }
578
- }
579
-
580
- /**
581
- * Web-specific tracker that enriches events with browser context before sending them.
582
- * Extends the base CollecionesTracker.
583
- */
584
- class CollecionesWebTracker extends CollecionesTracker {
585
- /**
586
- * Creates a new instance of CollecionesWebTracker.
587
- * @param {Array} emitters - A list of emitter instances used to send the event.
588
- * @param {string} trackerName - The name of the tracker.
589
- * @param {string} appName - The name of the application generating events.
590
- */
591
- constructor(emitters, trackerName, appName) {
592
- super(emitters, trackerName, appName);
593
- }
594
-
595
- /**
596
- * Tracks an event, enriching it with browser context information.
597
- * @param {CollecionesEvent} collecionesEvent - The event object to track.
598
- * @throws {Error} If the event is not an instance of CollecionesEvent.
599
- */
600
- track(collecionesEvent) {
601
- if (!(collecionesEvent instanceof CollecionesEvent)) {
602
- throw new Error('Event must be of type CollecionesEvent');
603
- }
604
- collecionesEvent.setContext('browserContext', getBrowserContext());
605
- super.track(collecionesEvent);
606
- }
607
- }
608
-
609
- /**
610
- * Colleciones DSL
611
- * ---------------
612
- * This module provides a fluent, human-readable DSL (domain-specific language) for constructing
613
- * structured tracking events based on CollecionesBaseEvent. Each step in the chain represents
614
- * a semantically meaningful piece of the event: the entity, the action, the actor, references, etc.
615
- *
616
- * Entry Point:
617
- * collecionesDsl.the('dark')
618
- *
619
- * Chaining:
620
- * - .and('...') : add additional adjectives
621
- * - ._('entity') : specify the entity being acted on
622
- * - .identified.by('field') : declare primary identifier for the subject
623
- * - .has.been('action') : declare what happened
624
- * - .by('actor') : describe the actor performing the action
625
- * - .identified.by('id') : add identifiers for the actor
626
- * - .with('key').set.to('val') : add contextual data fields
627
- * - .referring.to('entity') : describe referenced/related entities
628
- * - .identified.by('refId') : add identifiers for the reference
629
- * - .conform.to('SchemaName') : attach schema metadata
630
- * - .then.track.with(emitter) : finalize and emit the event
631
- *
632
- * Each function in the chain passes forward a scoped version of the CollecionesBaseEvent instance,
633
- * and enforces semantic constraints (e.g. `.as()` is required after `.by()`).
634
- *
635
- * Internal:
636
- * - Uses setRefence / setRefenceIdentifier for references
637
- * - Uses helpers.getEvent() for test access
638
- * - Uses instanceof CollecionesEmitter for validation
639
- *
640
- * This file is designed for internal use by developers building with the Colleciones tracking model.
641
- */
642
-
643
-
644
- let init = (entity) => {
645
- return ((entity)=>{
646
- let eventInstance = new CollecionesEvent(); // Core event object
647
- eventInstance.setEntity(entity);
648
-
649
- let helpers = {
650
- getEvent: () => {
651
- return eventInstance;
652
- },
653
- };
654
-
655
- // DSL function groups
656
- let andEntity = () => {}; // .and(...) chaining after the()
657
- let setEntityAfterAnd = () => {}; // ._('entity') after .and
658
- let setEntityIdentifiers = () => {}; // .identified.by(...) for main subject
659
- let setAction = () => {}; // .has.been(...) for action
660
- let setActor = () => {}; // .by('actor')
661
- let setActorIdentifier = () => {}; // .identified.by(...) inside .by(...)
662
- let addContext = () => {}; // .with(...).set.to(...)
663
- let addReference = () => {}; // .referring.to(...)
664
- let getAddReference = () => {}; // .identified.by().as() inside .referring
665
- let conformingTo = () => {}; // .conform.to('SchemaName')
666
- let track = () => {}; // .then.track.with(emitter)
667
- let addCollection = () => {};
668
-
669
- // Adjective chaining: .and(...)._('entity')
670
- setEntityAfterAnd = (entity) => {
671
- eventInstance.addAdjective(eventInstance.entity);
672
- eventInstance.setEntity(entity);
673
- return {
674
- as: () => {
675
- return { helpers }
676
- },
677
- identified: {
678
- by: setEntityIdentifiers
679
- },
680
- has: { been: setAction },
681
- helpers
682
- };
683
- };
684
-
685
- // Identifier setup: .identified.by().as()
686
- setEntityIdentifiers = (name) => {
687
- eventInstance.setIdentifier(name, null);
688
- return {
689
- as: (value) => {
690
- eventInstance.setIdentifier(name, value);
691
- return {
692
- helpers,
693
- and: {
694
- by: setEntityIdentifiers
695
- },
696
- has: { been: setAction },
697
- }
698
- },
699
- helpers
700
- };
701
- };
702
-
703
- // Additional adjectives: .and('...')._()
704
- andEntity = (entity) => {
705
- eventInstance.addAdjective(eventInstance.entity);
706
- eventInstance.setEntity(entity);
707
- return {
708
- and: andEntity,
709
- _ : setEntityAfterAnd,
710
- helpers
711
- }
712
- };
713
-
714
- // Action: .has.been('...')
715
- setAction = (action) => {
716
- eventInstance.setAction(action);
717
- return {
718
- by: setActor,
719
- referring: { to: addReference },
720
- with: addContext,
721
- conform: {to: conformingTo},
722
- then: {track: {with: track}},
723
- including: {
724
- a: addCollection,
725
- },
726
- helpers
727
- }
728
- };
729
-
730
- // Actor: .by('user')
731
- setActor = (name) => {
732
- eventInstance.setActor(name);
733
- return {
734
- identified: {
735
- by: setActorIdentifier
736
- },
737
- with: addContext,
738
- including: {
739
- a: addCollection,
740
- },
741
- helpers
742
- }
743
- };
744
-
745
- // Actor identifier: .identified.by().as()
746
- setActorIdentifier = (name) => {
747
- return {
748
- as: (value) => {
749
- eventInstance.setActorIdentifier(name, value);
750
- return {
751
- helpers,
752
- and: setActorIdentifier,
753
- with: addContext,
754
- referring: { to: addReference },
755
- including: {
756
- a: addCollection,
757
- },
758
- }
759
- },
760
- helpers
761
- }
762
- };
763
-
764
- // Contextual field: .with('key').set.to('value')
765
- addContext = (context) => {
766
- return {
767
- helpers,
768
- set: {
769
- to: (value) => {
770
- eventInstance.setContext(context, value);
771
- return {
772
- helpers,
773
- and: addContext,
774
- referring: { to: addReference },
775
- including: {
776
- a: addCollection,
777
- },
778
- }
779
- }
780
- }
781
- }
782
- };
783
-
784
- // Reference: .referring.to('...')
785
- addReference = (entity) => {
786
- eventInstance.setRefence(entity);
787
- return {
788
- identified: {
789
- by: getAddReference(entity)
790
- },
791
- conform: {to: conformingTo},
792
- then: {track: {with: track}},
793
- including: {
794
- a: addCollection,
795
- },
796
- helpers
797
- }
798
- };
799
-
800
- // Reference identifier setup: .identified.by().as()
801
- getAddReference = (entity) => {
802
- return (name) => {
803
- return {
804
- as: (value) => {
805
- eventInstance.setRefenceIdentifier(entity, name, value);
806
- return {
807
- helpers,
808
- and: {by: getAddReference(entity) },
809
- conform: {to: conformingTo},
810
- then: {track: {with: track}},
811
- including: {
812
- a: addCollection,
813
- },
814
- }
815
- },
816
- helpers,
817
- };
818
- };
819
- };
820
-
821
- // Schema declaration: .conform.to('...')
822
- conformingTo = (name) => {
823
- eventInstance.setSchema(name);
824
- return {
825
- then: {track: {with: track}},
826
- helpers
827
- }
828
- };
829
-
830
- addCollection = (entity) => {
831
- const collection = () => {
832
- eventInstance.setCollection(entity);
833
-
834
- const addItem = (referenceName) => {
835
- const itemKey = eventInstance.setCollectionItem(entity);
836
- const addIdentifier = (referenceNameNewIdentifier) => {
837
- referenceName = referenceNameNewIdentifier;
838
- return {
839
- as: addItemReferenceValue,
840
- }
841
- };
842
- const addItemReferenceValue = (value) => {
843
- eventInstance.setCollectionItemReference(entity, itemKey, referenceName, value);
844
- return {
845
- and: {
846
- helpers,
847
- by: addIdentifier,
848
- item: {
849
- identified: {
850
- by: addItem
851
- }
852
- },
853
- a: addCollection
854
- },
855
- conform: {
856
- to: conformingTo,
857
- },
858
- then: {track: {with: track}},
859
- helpers
860
- }
861
- };
862
- return {
863
- as: addItemReferenceValue
864
- }
865
-
866
- };
867
-
868
- return {
869
- helpers,
870
- with: {
871
- item: {
872
- identified: {
873
- by: addItem
874
- }
875
- }
876
- },
877
- and: { a: addCollection }
878
- }
879
- };
880
- return {
881
- collection
882
- }
883
- };
884
-
885
- // Final dispatch: .then.track.with(tracker)
886
- track = (tracker) => {
887
- if(!(tracker instanceof CollecionesTracker)){
888
- throw new Error('can only be a CollecionesTracker')
889
- }
890
- tracker.track(eventInstance);
891
- return {
892
- and: track,
893
- helpers,
894
- }
895
- };
896
-
897
- return {
898
- and: andEntity,
899
- _: setEntityAfterAnd,
900
- identified: {
901
- by: setEntityIdentifiers
902
- },
903
- has: { been: setAction},
904
- node: '_base',
905
- helpers
906
- }
907
-
908
- })(entity);
909
- };
910
-
911
- let collecionesDsl = {
912
- the: init
913
- };
914
-
915
- (function(global) {
916
- global.CollecionesEmitter = CollecionesEmitter;
917
- global.CollecionesTracker = CollecionesTracker;
918
- global.CollecionesWebTracker = CollecionesWebTracker;
919
- global.CollecionesEvent = CollecionesEvent;
920
- global.collecionesDsl = collecionesDsl;
921
- })(typeof window !== 'undefined' ? window : globalThis);
2
+ 'use strict';
3
+
4
+ // helper 'private' functions
5
+
6
+
7
+ /**
8
+ * Encodes a string to Base64.
9
+ * Uses browser or Node.js method depending on environment.
10
+ * @param {string} str
11
+ * @returns {string}
12
+ */
13
+ const toBase64 = function (str) {
14
+ if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
15
+ return window.btoa(unescape(encodeURIComponent(str)));
16
+ } else {
17
+ return Buffer.from(str, 'utf-8').toString('base64');
18
+ }
19
+ };
20
+
21
+ /**
22
+ * Collects browser-related context values like screen size, language, etc.
23
+ * Returns an empty object if not in browser environment.
24
+ * @returns {Object}
25
+ */
26
+ const getBrowserContext = function() {
27
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
28
+ return {};
29
+ }
30
+ return {
31
+ hasFocus: document.hasFocus(),
32
+ language: navigator.language,
33
+ platform: navigator.platform,
34
+ referrer: document.referrer,
35
+ screenHeight: window.screen.height,
36
+ screenWidth: window.screen.width,
37
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
38
+ url: window.location.href,
39
+ userAgent: navigator.userAgent,
40
+ viewportHeight: window.innerHeight,
41
+ viewportWidth: window.innerWidth,
42
+ };
43
+ };
44
+
45
+ const formatToCamelCase = function(input) {
46
+ return input
47
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
48
+ .trim()
49
+ .split(/\s+/)
50
+ .map((word, index) => {
51
+ if (index === 0) return word;
52
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
53
+ })
54
+ .join('');
55
+ };
56
+
57
+ /**
58
+ * CollecionesEvent
59
+ * -----------------
60
+ * Base class representing a semantically structured event object.
61
+ * Each event models a specific interaction with an entity, optionally performed by an actor,
62
+ * and may reference related entities or include contextual metadata.
63
+ *
64
+ * Key features:
65
+ * - Captures structured semantics: entity, action, actor, context, references
66
+ * - Supports multiple identifiers for both the main entity and the actor
67
+ * - Allows origin tagging for cross-context or cross-application references
68
+ * - Supports referencing collections of entities or grouped data
69
+ * - Includes timestamps and tracker/app metadata for auditability
70
+ * - Fully serializable and deserializable via toJSON/fromJSON
71
+ */
72
+
73
+
74
+ class CollecionesEvent {
75
+
76
+ /**
77
+ * Constructs a new CollecionesEvent with default structure and timestamps.
78
+ * Initializes empty containers for semantic attributes such as:
79
+ * - entity: the subject of the event
80
+ * - adjectives: descriptors of the entity
81
+ * - identifiers: identifiers of the entity
82
+ * - action: what happened to the entity
83
+ * - actor: who or what triggered the event (with identifiers in actorIdentifiers)
84
+ * - context: environmental data related to the event
85
+ * - references: external entities involved, optionally scoped by origin
86
+ * - collections: groups of related entities
87
+ * - meta: tracking metadata and timestamps
88
+ */
89
+ constructor() {
90
+ // initialize event properties
91
+ this.entity = '';
92
+ this.adjevtives = [];
93
+ this.identifiers = {};
94
+ this.action = '';
95
+ this.actor = {};
96
+ this.actorIdentifiers = {};
97
+ this.context = {};
98
+ this.references = {};
99
+ this.collections = {};
100
+ // set default values
101
+ this.meta = {
102
+ eventFormat: 'CollecionesEvent',
103
+ eventFormatVersion: '1'
104
+ };
105
+ this.meta.tracker = '';
106
+ this.meta.app = '';
107
+ this.meta.timestamps = {};
108
+ this.meta.timestamps.clientDatetimeUtc = new Date().toISOString();
109
+ if (typeof window !== 'undefined' && typeof navigator !== 'undefined' && navigator.language) {
110
+ this.meta.timestamps.clientDatetimeLocal = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString();
111
+ this.meta.timestamps.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
112
+ this.meta.timestamps.timeZoneOffset = new Date().getTimezoneOffset();
113
+ } else {
114
+ this.meta.timestamps.clientDatetimeLocal = new Date().toISOString();
115
+ this.meta.timestamps.timeZone = 'UTC';
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Returns the declared event format.
121
+ * @returns {string} The format name (e.g. 'CollecionesEvent').
122
+ */
123
+ getEventFormat() {
124
+ let v = this.meta?.eventFormat;
125
+ return (typeof v !== 'undefined') ? v : '1';
126
+ }
127
+
128
+ /**
129
+ * Returns the version of the event format.
130
+ * @returns {string} The format version string.
131
+ */
132
+ getEventFormatVersion() {
133
+ let v = this?.meta?.eventFormatVersion;
134
+ return (typeof v !== 'undefined') ? v : 'CollecionesEvent';
135
+ }
136
+
137
+ /**
138
+ * Overrides or supplements the event's timestamp fields with custom values.
139
+ * @param {object} dateTimeObject - Key-value pairs to merge into the existing timestamp object.
140
+ */
141
+ overrideDatetime(dateTimeObject = {}) {
142
+ for (const [key, value] of Object.entries(dateTimeObject)) {
143
+ this.meta.timestamps[key] = value;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Sets the name of the tracker responsible for generating this event.
149
+ * @param {string} name - Tracker name.
150
+ */
151
+ setTracker(name) {
152
+ this.meta.tracker = name;
153
+ }
154
+
155
+ /**
156
+ * Sets the name of the application that generated the event.
157
+ * @param {string} name - Application name.
158
+ */
159
+ setAppName(name) {
160
+ this.meta.appName = name;
161
+ }
162
+
163
+ /**
164
+ * Sets the expected schema name for this event.
165
+ * @param {string} schema - The name of the schema.
166
+ */
167
+ setSchema(schema) {
168
+ if (typeof schema !== 'string') {
169
+ throw new Error('Schema must be a string');
170
+ }
171
+ this.meta.schema = schema;
172
+ }
173
+
174
+ /**
175
+ * Sets the entity (subject) of the event.
176
+ * @param {string} entity - The entity name.
177
+ */
178
+ setEntity = function(entity) {
179
+ this.entity = formatToCamelCase(entity);
180
+ }
181
+
182
+ /**
183
+ * Defines the main action of the event (e.g., 'clicked').
184
+ * @param {string} action - The action string.
185
+ */
186
+ setAction = function(action) {
187
+ this.action = formatToCamelCase(action);
188
+ }
189
+
190
+ /**
191
+ * Adds an adjective that describes the entity in more detail.
192
+ * @param {string} adjective - An adjective string.
193
+ */
194
+ addAdjective = function(adjective) {
195
+ if (typeof adjective !== 'string') {
196
+ throw new Error('Adjective must be a string');
197
+ }
198
+ this.adjevtives.push(formatToCamelCase(adjective));
199
+ }
200
+
201
+ /**
202
+ * Adds or updates an identifier for the primary entity.
203
+ * Identifiers allow multiple keys to uniquely identify the entity.
204
+ * @param {string} name - The identifier key.
205
+ * @param {*} identifier - The identifier value.
206
+ */
207
+ setIdentifier = function(name, identifier) {
208
+ if (typeof name !== 'string') {
209
+ throw new Error('Identifier name must be a string');
210
+ }
211
+ this.identifiers[name] = identifier;
212
+ }
213
+
214
+ /**
215
+ * Defines the name of the actor (who or what performed the action).
216
+ * @param {string} name - Actor name (e.g., 'user', 'system').
217
+ */
218
+ setActor = function(name) {
219
+ if (typeof name !== 'string') {
220
+ throw new Error('Actor name must be a string');
221
+ }
222
+ this.actor.name = name;
223
+ }
224
+
225
+ /**
226
+ * Adds or updates an identifier for the actor.
227
+ * Supports multiple identifiers to uniquely identify the actor.
228
+ * @param {string} name - Identifier key.
229
+ * @param {*} identifier - Identifier value.
230
+ */
231
+ setActorIdentifier = function(name, identifier) {
232
+ if (typeof name !== 'string') {
233
+ throw new Error('Actor Identifier name must be a string');
234
+ }
235
+ this.actorIdentifiers[name] = identifier;
236
+ }
237
+
238
+ /**
239
+ * Adds contextual information to the event.
240
+ * Context can include any additional environmental or situational data.
241
+ * @param {string} context - The key of the context field.
242
+ * @param {*} value - The value of the context field.
243
+ */
244
+ setContext = function(context, value) {
245
+ if (typeof context !== 'string') {
246
+ throw new Error('Context must be a string');
247
+ }
248
+ this.context[context] = value;
249
+ }
250
+
251
+ /**
252
+ * Alias for `setReference` for compatibility.
253
+ * Declares an external entity referenced by this event.
254
+ * @param {string} entity - The referenced entity name.
255
+ * @param {string|null} origin - The origin application or context (optional).
256
+ */
257
+ setRefence = function(entity, origin=null) {
258
+ return this.setReference(entity, origin);
259
+ }
260
+
261
+ /**
262
+ * Declares an entity referenced by this event.
263
+ * References may include multiple identifiers and an optional origin to scope the reference.
264
+ * @param {string} entity - The referenced entity name.
265
+ * @param {string|null} origin - The origin application or context (optional).
266
+ */
267
+ setReference = function(entity, origin=null) {
268
+ if (typeof entity !== 'string') {
269
+ throw new Error('Referenced entity must be a string');
270
+ }
271
+ entity = formatToCamelCase(entity);
272
+ if (origin !== null) {
273
+ entity = `${origin}.${entity}`;
274
+ }
275
+ if(this.references[entity] === undefined) {
276
+ this.references[entity] = {
277
+ identifiers: {},
278
+ origin
279
+ };
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Adds or updates an identifier for a referenced entity.
285
+ * Ensures the reference is declared and sets the identifier under that reference.
286
+ * @param {string} entity - The referenced entity name.
287
+ * @param {string} name - The identifier key.
288
+ * @param {*} identifier - The identifier value.
289
+ * @param {string|null} origin - Optional origin context.
290
+ */
291
+ setRefenceIdentifier = function(entity, name, identifier, origin=null) {
292
+ return this.setReferenceIdentifier(entity, name, identifier, origin);
293
+ }
294
+
295
+ /**
296
+ * Adds or updates an identifier for a referenced entity.
297
+ * @param {string} entity - The referenced entity name.
298
+ * @param {string} name - The identifier key.
299
+ * @param {*} identifier - The identifier value.
300
+ * @param {string|null} origin - Optional origin context.
301
+ */
302
+ setReferenceIdentifier = function(entity, name, identifier, origin=null) {
303
+ if (typeof entity !== 'string') {
304
+ throw new Error('Referenced entity name must be a string');
305
+ }
306
+ if (typeof name !== 'string') {
307
+ throw new Error('Actor Identifier name must be a string');
308
+ }
309
+ this.setRefence(entity, origin);
310
+ entity = formatToCamelCase(entity);
311
+ if (origin !== null) {
312
+ entity = `${origin}.${entity}`;
313
+ }
314
+ this.references[entity].identifiers[name] = identifier;
315
+ }
316
+
317
+ /**
318
+ * Declares a collection of related entities for this event.
319
+ * Collections group multiple related items and may include identifiers and origin metadata.
320
+ * @param {string} entity - The collection name.
321
+ * @param {string|null} origin - Optional origin identifier (e.g. system name).
322
+ */
323
+ setCollection = function(entity, origin=null) {
324
+ entity = formatToCamelCase(entity);
325
+ if (origin !== null) {
326
+ entity = `${origin}.${entity}`;
327
+ }
328
+ if(this.collections[entity] == undefined) {
329
+ this.collections[entity] = {
330
+ items: [],
331
+ identifiers: {},
332
+ origin
333
+ };
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Adds a new item to a collection and returns its index key.
339
+ * Items represent individual elements within the collection.
340
+ * @param {string} entity - The name of the collection.
341
+ * @returns {number} Index of the newly added item in the collection.
342
+ */
343
+ setCollectionItem = function(entity, origin=null) {
344
+ entity = formatToCamelCase(entity);
345
+ if (origin !== null) {
346
+ entity = `${origin}.${entity}`;
347
+ }
348
+ this.setCollection(entity);
349
+ this.collections[entity].items.push({});
350
+ let itemKey = this.collections[entity].items.length - 1;
351
+ return itemKey;
352
+ }
353
+
354
+ /**
355
+ * Assigns a reference (identifier) to a specific item in a collection.
356
+ * Useful for tagging individual collection elements with identifiers.
357
+ * @param {string} entity - Collection name.
358
+ * @param {number} itemKey - The index of the item in the collection.
359
+ * @param {string} name - The identifier key.
360
+ * @param {*} identifier - The identifier value.
361
+ * @throws {Error} If the item does not exist at the given index.
362
+ */
363
+ setCollectionItemReference = function(entity, itemKey, name, identifier, origin=null) {
364
+ entity = formatToCamelCase(entity);
365
+ if (origin !== null) {
366
+ entity = `${origin}.${entity}`;
367
+ }
368
+ this.setCollection(entity);
369
+ if(typeof this.collections[entity].items[itemKey] !== 'object') {
370
+ throw new Error('bad bad man, the collection key does not exists');
371
+ }
372
+ this.collections[entity].items[itemKey][name] = identifier;
373
+ }
374
+
375
+ /**
376
+ * Sets a static identifier that applies to the entire collection.
377
+ * These identifiers describe the collection as a whole.
378
+ * @param {string} entity - Collection name.
379
+ * @param {string} name - Identifier key.
380
+ * @param {*} identifier - Identifier value.
381
+ */
382
+ setCollectionIdentifier = function(entity, name, identifier, origin=null) {
383
+ entity = formatToCamelCase(entity);
384
+ if (origin !== null) {
385
+ entity = `${origin}.${entity}`;
386
+ }
387
+ if(this.collections[entity] == undefined) {
388
+ this.collections[entity] = {};
389
+ }
390
+ this.collections[entity].identifiers[name] = identifier;
391
+ }
392
+
393
+ /**
394
+ * Serializes the event instance to a plain object suitable for transport or storage.
395
+ * The output includes all semantic fields and metadata.
396
+ * @returns {object} A plain JavaScript object representing the event.
397
+ */
398
+ toJSON() {
399
+ return {
400
+ class: 'CollecionesEvent',
401
+ entity: this.entity,
402
+ adjectives: this.adjevtives,
403
+ identifiers: this.identifiers,
404
+ action: this.action,
405
+ actor: this.actor,
406
+ actorIdentifiers: this.actorIdentifiers,
407
+ actorIds: this.actorIds,
408
+ context: this.context,
409
+ references: this.references,
410
+ meta: this.meta,
411
+ collections: this.collections
412
+ };
413
+ }
414
+
415
+ /**
416
+ * Recreates a CollecionesEvent instance from a plain object.
417
+ * Used when deserializing events from storage or network transport.
418
+ * @param {object} obj - The input object containing event data.
419
+ * @returns {CollecionesEvent} A rehydrated event instance.
420
+ * @throws {Error} If the class type is not 'CollecionesEvent'.
421
+ */
422
+ static fromJSON(obj) {
423
+ if (!obj || obj.class !== 'CollecionesEvent') {
424
+ throw new Error('Invalid or missing event class type');
425
+ }
426
+ const instance = new CollecionesEvent();
427
+ instance.entity = obj.entity;
428
+ instance.adjevtives = obj.adjectives || [];
429
+ instance.identifiers = obj.identifiers || {};
430
+ instance.action = obj.action;
431
+ instance.actor = obj.actor;
432
+ instance.actorIdentifiers = obj.actorIdentifiers;
433
+ instance.actorIds = obj.actorIds;
434
+ instance.context = obj.context || {};
435
+ instance.references = obj.references || {};
436
+ instance.meta = obj.meta || {};
437
+ instance.collections = obj.collections || {};
438
+ return instance;
439
+ }
440
+
441
+ }
442
+
443
+ /**
444
+ * CollecionesEmitter
445
+ * -------------------
446
+ * This class collects and sends event objects to a remote endpoint (e.g., an event collector API).
447
+ * It is used in both client- and server-side tracking scenarios, typically in combination with
448
+ * CollecionesEvent or subclasses like CollecionesBaseEvent.
449
+ *
450
+ * Behavior:
451
+ * - Events are buffered via `.track()` or `.trackAsync()`.
452
+ * - If the number of buffered events reaches `flushSize`, the buffer is automatically flushed.
453
+ * - If `flushInterval` is provided, the buffer is flushed at a fixed interval.
454
+ * - Flushing serializes each event using `.toJSON()`, encodes it with base64, and posts
455
+ * the resulting array to the configured endpoint.
456
+ *
457
+ * Example usage:
458
+ * const emitter = new CollecionesEmitter('/track', 5, 10000);
459
+ * emitter.track(new CollecionesEvent());
460
+ *
461
+ * Note:
462
+ * This class is stateful. To stop periodic flushing, call `.stopTimer()` when the emitter is no longer in use.
463
+ */
464
+ class CollecionesEmitter {
465
+
466
+ /**
467
+ * Initializes the emitter with buffering settings.
468
+ * @param {string} [endpoint='/collect'] - The URL to send events to.
469
+ * @param {number} [flushSize=10] - Number of events to buffer before flushing.
470
+ * @param {number|boolean} [flushInterval=false] - Time in ms to flush events periodically.
471
+ */
472
+ constructor(endpoint = '/collect', flushSize = 10, flushInterval = false) {
473
+ this.endpoint = endpoint;
474
+ this.flushInterval = flushInterval;
475
+ this.flushSize = flushSize;
476
+ this.buffer = [];
477
+ this.timer = null;
478
+ this.lastPayload = null;
479
+ }
480
+
481
+ /**
482
+ * Starts the flush timer if a valid interval is set.
483
+ * @returns {void}
484
+ */
485
+ startTimer() {
486
+ this.stopTimer();
487
+ if (typeof this.flushInterval == 'number' && this.flushInterval > 0) {
488
+ this.timer = setInterval(() => this.flush(), this.flushInterval);
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Starts the flush timer only if not already running.
494
+ * @returns {void}
495
+ */
496
+ startTimerIfStopped() {
497
+ if (!this.timer) {
498
+ this.startTimer();
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Stops the active flush timer.
504
+ * @returns {void}
505
+ */
506
+ stopTimer() {
507
+ if (this.timer) {
508
+ clearInterval(this.timer);
509
+ }
510
+ this.timer = null;
511
+ }
512
+
513
+ /**
514
+ * Adds an event to the buffer and flushes if threshold is reached.
515
+ * Validates that the event is an instance of CollecionesEvent to ensure correct event type.
516
+ * @param {CollecionesEvent} event - Event instance to be tracked.
517
+ * @throws {Error} Throws if event is not a CollecionesEvent instance.
518
+ * @returns {void}
519
+ */
520
+ track(event) {
521
+ if (!(event instanceof CollecionesEvent)) {
522
+ throw new Error('Event must be an instance of CollecionesEvent');
523
+ }
524
+ this.trackAsync(event);
525
+ }
526
+
527
+ /**
528
+ * Asynchronously adds an event and flushes if the buffer size is exceeded.
529
+ * Validates that the event is an instance of CollecionesEvent to ensure correct event type.
530
+ * @param {CollecionesEvent} event - Event instance to be tracked asynchronously.
531
+ * @throws {Error} Throws if event is not a CollecionesEvent instance.
532
+ * @returns {Promise<void>} Resolves when event is added and flush triggered if needed.
533
+ */
534
+ async trackAsync(event) {
535
+ if (!(event instanceof CollecionesEvent)) {
536
+ throw new Error('Event must be an instance of CollecionesEvent');
537
+ }
538
+ this.startTimerIfStopped();
539
+ this.buffer.push(event);
540
+ return (this.buffer.length >= this.flushSize) ? this.flush() : Promise.resolve();
541
+ }
542
+
543
+ /**
544
+ * Sends all buffered events in a single POST request to the server.
545
+ * Each event is serialized via `.toJSON()` and encoded as a base64 string.
546
+ * Response status is checked for HTTP success; errors are logged but not thrown.
547
+ *
548
+ * @returns {Promise<boolean|undefined>} Resolves true if flush was triggered, or undefined if buffer was empty.
549
+ */
550
+ async flush() {
551
+ if (this.buffer.length === 0) return;
552
+ this.stopTimer();
553
+ const body = this.buildBody();
554
+ this.lastPayload = body;
555
+ this.buffer = [];
556
+ try {
557
+ const response = await fetch(this.endpoint, {
558
+ method: 'POST',
559
+ credentials: 'include',
560
+ headers: {
561
+ 'Content-Type': 'application/json'
562
+ },
563
+ body
564
+ });
565
+ if (!response.ok) {
566
+ console.log(`Failed to send events: ${response.statusText}`);
567
+ }
568
+ return true;
569
+ } catch (error) {
570
+ console.log(`Network error sending events: ${error.message}`);
571
+ }
572
+ }
573
+
574
+ /**
575
+ * Builds a POST-ready payload from the current buffer, without clearing it.
576
+ * @returns {string} JSON string of base64-encoded serialized events.
577
+ */
578
+ buildBody() {
579
+ return JSON.stringify(this.buffer.map(e => toBase64(JSON.stringify(e.toJSON()))));
580
+ }
581
+
582
+ }
583
+
584
+ /**
585
+ * Tracks events by enriching them with shared identifiers and routing through configured emitters.
586
+ */
587
+ class CollecionesTracker {
588
+
589
+ /**
590
+ * Constructs a new tracker instance.
591
+ * @param {Array} emitters - Array of emitter instances responsible for sending events.
592
+ * @param {string} trackerName - Name identifying this tracker.
593
+ * @param {string} appName - Name of the application generating events.
594
+ */
595
+ constructor(emitters, trackerName, appName) {
596
+ this.emitters = emitters;
597
+ this.trackerName = trackerName;
598
+ this.appName = appName;
599
+ }
600
+
601
+ /**
602
+ * Sends an event to all emitters after enriching it with identifiers and metadata.
603
+ * @param {CollecionesEvent} collecionesEvent - The event to be sent.
604
+ * @throws {Error} If the input is not an instance of CollecionesEvent.
605
+ */
606
+ track(collecionesEvent) {
607
+ if (!(collecionesEvent instanceof CollecionesEvent)) {
608
+ throw new Error('Event must be of type CollecionesEvent');
609
+ }
610
+ collecionesEvent.setTracker(this.trackerName);
611
+ collecionesEvent.setAppName(this.appName);
612
+ this.emitters.forEach(element => {
613
+ element.track(collecionesEvent, this.trackerName, this.appName);
614
+ });
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Web-specific tracker that enriches events with browser context before sending them.
620
+ * Extends the base CollecionesTracker.
621
+ */
622
+ class CollecionesWebTracker extends CollecionesTracker {
623
+ /**
624
+ * Creates a new instance of CollecionesWebTracker.
625
+ * @param {Array} emitters - A list of emitter instances used to send the event.
626
+ * @param {string} trackerName - The name of the tracker.
627
+ * @param {string} appName - The name of the application generating events.
628
+ */
629
+ constructor(emitters, trackerName, appName) {
630
+ super(emitters, trackerName, appName);
631
+ }
632
+
633
+ /**
634
+ * Tracks an event, enriching it with browser context information.
635
+ * @param {CollecionesEvent} collecionesEvent - The event object to track.
636
+ * @throws {Error} If the event is not an instance of CollecionesEvent.
637
+ */
638
+ track(collecionesEvent) {
639
+ if (!(collecionesEvent instanceof CollecionesEvent)) {
640
+ throw new Error('Event must be of type CollecionesEvent');
641
+ }
642
+ collecionesEvent.setContext('browserContext', getBrowserContext());
643
+ super.track(collecionesEvent);
644
+ }
645
+ }
646
+
647
+ /**
648
+ * Colleciones DSL
649
+ * ---------------
650
+ * This module provides a fluent, human-readable DSL (domain-specific language) for constructing
651
+ * structured tracking events based on CollecionesBaseEvent. Each step in the chain represents
652
+ * a semantically meaningful piece of the event: the entity, the action, the actor, references, etc.
653
+ *
654
+ * Entry Point:
655
+ * collecionesDsl.the('dark')
656
+ *
657
+ * Chaining:
658
+ * - .and('...') : add additional adjectives
659
+ * - ._('entity') : specify the entity being acted on
660
+ * - .identified.by('field') : declare primary identifier for the subject
661
+ * - .has.been('action') : declare what happened
662
+ * - .by('actor') : describe the actor performing the action
663
+ * - .identified.by('id') : add identifiers for the actor
664
+ * - .with('key').set.to('val') : add contextual data fields
665
+ * - .referring.to('entity') : describe referenced/related entities
666
+ * - .identified.by('refId') : add identifiers for the reference
667
+ * - .conform.to('SchemaName') : attach schema metadata
668
+ * - .then.track.with(emitter) : finalize and emit the event
669
+ *
670
+ * Each function in the chain passes forward a scoped version of the CollecionesBaseEvent instance,
671
+ * and enforces semantic constraints (e.g. `.as()` is required after `.by()`).
672
+ *
673
+ * Internal:
674
+ * - Uses setRefence / setRefenceIdentifier for references
675
+ * - Uses helpers.getEvent() for test access
676
+ * - Uses instanceof CollecionesEmitter for validation
677
+ *
678
+ * This file is designed for internal use by developers building with the Colleciones tracking model.
679
+ */
680
+
681
+
682
+ let init = (entity) => {
683
+ return ((entity)=>{
684
+ let eventInstance = new CollecionesEvent(); // Core event object
685
+ eventInstance.setEntity(entity);
686
+
687
+ let helpers = {
688
+ getEvent: () => {
689
+ return eventInstance;
690
+ },
691
+ };
692
+
693
+ // DSL function groups
694
+ let andEntity = () => {}; // .and(...) chaining after the()
695
+ let setEntityAfterAnd = () => {}; // ._('entity') after .and
696
+ let setEntityIdentifiers = () => {}; // .identified.by(...) for main subject
697
+ let setAction = () => {}; // .has.been(...) for action
698
+ let setActor = () => {}; // .by('actor')
699
+ let setActorIdentifier = () => {}; // .identified.by(...) inside .by(...)
700
+ let addContext = () => {}; // .with(...).set.to(...)
701
+ let addReference = () => {}; // .referring.to(...)
702
+ let getAddReference = () => {}; // .identified.by().as() inside .referring
703
+ let conformingTo = () => {}; // .conform.to('SchemaName')
704
+ let track = () => {}; // .then.track.with(emitter)
705
+ let addCollection = () => {};
706
+
707
+ // Adjective chaining: .and(...)._('entity')
708
+ setEntityAfterAnd = (entity) => {
709
+ eventInstance.addAdjective(eventInstance.entity);
710
+ eventInstance.setEntity(entity);
711
+ return {
712
+ as: () => {
713
+ return { helpers }
714
+ },
715
+ identified: {
716
+ by: setEntityIdentifiers
717
+ },
718
+ has: { been: setAction },
719
+ helpers
720
+ };
721
+ };
722
+
723
+ // Identifier setup: .identified.by().as()
724
+ setEntityIdentifiers = (name) => {
725
+ eventInstance.setIdentifier(name, null);
726
+ return {
727
+ as: (value) => {
728
+ eventInstance.setIdentifier(name, value);
729
+ return {
730
+ helpers,
731
+ and: {
732
+ by: setEntityIdentifiers
733
+ },
734
+ has: { been: setAction },
735
+ }
736
+ },
737
+ helpers
738
+ };
739
+ };
740
+
741
+ // Additional adjectives: .and('...')._()
742
+ andEntity = (entity) => {
743
+ eventInstance.addAdjective(eventInstance.entity);
744
+ eventInstance.setEntity(entity);
745
+ return {
746
+ and: andEntity,
747
+ _ : setEntityAfterAnd,
748
+ helpers
749
+ }
750
+ };
751
+
752
+ // Action: .has.been('...')
753
+ setAction = (action) => {
754
+ eventInstance.setAction(action);
755
+ return {
756
+ by: setActor,
757
+ referring: { to: addReference },
758
+ with: addContext,
759
+ conform: {to: conformingTo},
760
+ then: {track: {with: track}},
761
+ including: {
762
+ a: addCollection,
763
+ },
764
+ helpers
765
+ }
766
+ };
767
+
768
+ // Actor: .by('user')
769
+ setActor = (name) => {
770
+ eventInstance.setActor(name);
771
+ return {
772
+ identified: {
773
+ by: setActorIdentifier
774
+ },
775
+ with: addContext,
776
+ including: {
777
+ a: addCollection,
778
+ },
779
+ helpers
780
+ }
781
+ };
782
+
783
+ // Actor identifier: .identified.by().as()
784
+ setActorIdentifier = (name) => {
785
+ return {
786
+ as: (value) => {
787
+ eventInstance.setActorIdentifier(name, value);
788
+ return {
789
+ helpers,
790
+ and: setActorIdentifier,
791
+ with: addContext,
792
+ referring: { to: addReference },
793
+ including: {
794
+ a: addCollection,
795
+ },
796
+ }
797
+ },
798
+ helpers
799
+ }
800
+ };
801
+
802
+ // Contextual field: .with('key').set.to('value')
803
+ addContext = (context) => {
804
+ return {
805
+ helpers,
806
+ set: {
807
+ to: (value) => {
808
+ eventInstance.setContext(context, value);
809
+ return {
810
+ helpers,
811
+ and: addContext,
812
+ referring: { to: addReference },
813
+ including: {
814
+ a: addCollection,
815
+ },
816
+ }
817
+ }
818
+ }
819
+ }
820
+ };
821
+
822
+ // Reference: .referring.to('...')
823
+ addReference = (entity) => {
824
+ eventInstance.setRefence(entity);
825
+ return {
826
+ identified: {
827
+ by: getAddReference(entity)
828
+ },
829
+ conform: {to: conformingTo},
830
+ then: {track: {with: track}},
831
+ including: {
832
+ a: addCollection,
833
+ },
834
+ helpers
835
+ }
836
+ };
837
+
838
+ // Reference identifier setup: .identified.by().as()
839
+ getAddReference = (entity) => {
840
+ return (name) => {
841
+ return {
842
+ as: (value) => {
843
+ eventInstance.setRefenceIdentifier(entity, name, value);
844
+ return {
845
+ helpers,
846
+ and: {by: getAddReference(entity) },
847
+ conform: {to: conformingTo},
848
+ then: {track: {with: track}},
849
+ including: {
850
+ a: addCollection,
851
+ },
852
+ }
853
+ },
854
+ helpers,
855
+ };
856
+ };
857
+ };
858
+
859
+ // Schema declaration: .conform.to('...')
860
+ conformingTo = (name) => {
861
+ eventInstance.setSchema(name);
862
+ return {
863
+ then: {track: {with: track}},
864
+ helpers
865
+ }
866
+ };
867
+
868
+ addCollection = (entity) => {
869
+ const collection = () => {
870
+ eventInstance.setCollection(entity);
871
+
872
+ const addItem = (referenceName) => {
873
+ const itemKey = eventInstance.setCollectionItem(entity);
874
+ const addIdentifier = (referenceNameNewIdentifier) => {
875
+ referenceName = referenceNameNewIdentifier;
876
+ return {
877
+ as: addItemReferenceValue,
878
+ }
879
+ };
880
+ const addItemReferenceValue = (value) => {
881
+ eventInstance.setCollectionItemReference(entity, itemKey, referenceName, value);
882
+ return {
883
+ and: {
884
+ helpers,
885
+ by: addIdentifier,
886
+ item: {
887
+ identified: {
888
+ by: addItem
889
+ }
890
+ },
891
+ a: addCollection
892
+ },
893
+ conform: {
894
+ to: conformingTo,
895
+ },
896
+ then: {track: {with: track}},
897
+ helpers
898
+ }
899
+ };
900
+ return {
901
+ as: addItemReferenceValue
902
+ }
903
+
904
+ };
905
+
906
+ return {
907
+ helpers,
908
+ with: {
909
+ item: {
910
+ identified: {
911
+ by: addItem
912
+ }
913
+ }
914
+ },
915
+ and: { a: addCollection }
916
+ }
917
+ };
918
+ return {
919
+ collection
920
+ }
921
+ };
922
+
923
+ // Final dispatch: .then.track.with(tracker)
924
+ track = (tracker) => {
925
+ if(!(tracker instanceof CollecionesTracker)){
926
+ throw new Error('can only be a CollecionesTracker')
927
+ }
928
+ tracker.track(eventInstance);
929
+ return {
930
+ and: track,
931
+ helpers,
932
+ }
933
+ };
934
+
935
+ return {
936
+ and: andEntity,
937
+ _: setEntityAfterAnd,
938
+ identified: {
939
+ by: setEntityIdentifiers
940
+ },
941
+ has: { been: setAction},
942
+ node: '_base',
943
+ helpers
944
+ }
945
+
946
+ })(entity);
947
+ };
948
+
949
+ let collecionesDsl = {
950
+ the: init
951
+ };
952
+
953
+ (function(global) {
954
+ global.CollecionesEmitter = CollecionesEmitter;
955
+ global.CollecionesTracker = CollecionesTracker;
956
+ global.CollecionesWebTracker = CollecionesWebTracker;
957
+ global.CollecionesEvent = CollecionesEvent;
958
+ global.collecionesDsl = collecionesDsl;
959
+ })(typeof window !== 'undefined' ? window : globalThis);
922
960
 
923
961
  })();
924
962
  //# sourceMappingURL=collecionesClientos.iife.js.map