@beworke/pixel 0.1.0-rc.1 → 0.1.0-rc.6

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 (156) hide show
  1. package/CHANGELOG.md +260 -4
  2. package/README.md +65 -118
  3. package/RELEASE_CANDIDATE.md +181 -36
  4. package/dist/{StorageFactory-BhpbB6Jj.d.mts → StorageFactory-CPghDPBj.d.mts} +2 -2
  5. package/dist/{StorageFactory-CAkJJqVD.d.ts → StorageFactory-tjfzk57c.d.ts} +2 -2
  6. package/dist/config/index.cjs.js +1 -1
  7. package/dist/config/index.cjs.js.map +1 -1
  8. package/dist/config/index.d.mts +4 -3
  9. package/dist/config/index.d.ts +4 -3
  10. package/dist/config/index.esm.js +1 -1
  11. package/dist/config/index.esm.js.map +1 -1
  12. package/dist/events/index.cjs.js +1 -1
  13. package/dist/events/index.cjs.js.map +1 -1
  14. package/dist/events/index.d.mts +2 -1
  15. package/dist/events/index.d.ts +2 -1
  16. package/dist/events/index.esm.js +1 -1
  17. package/dist/events/index.esm.js.map +1 -1
  18. package/dist/examples/html-script/README.md +24 -2
  19. package/dist/examples/html-script/RELEASE_CANDIDATE.md +20 -6
  20. package/dist/examples/html-script/add-payment-info/README.md +3 -3
  21. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-autocomplete.html +66 -48
  22. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-disabled.html +66 -48
  23. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-fields.html +65 -47
  24. package/dist/examples/html-script/add-payment-info/example-add-payment-info-data-track.html +73 -47
  25. package/dist/examples/html-script/add-payment-info/example-add-payment-info-dedupe.html +65 -47
  26. package/dist/examples/html-script/add-payment-info/example-add-payment-info-manual.html +56 -47
  27. package/dist/examples/html-script/add-payment-info/example-add-payment-info-rules-card.html +65 -47
  28. package/dist/examples/html-script/add-payment-info/example-add-payment-info-security.html +65 -47
  29. package/dist/examples/html-script/add-to-cart/README.md +3 -3
  30. package/dist/examples/html-script/add-to-cart/example-add-to-cart-attribute.html +90 -70
  31. package/dist/examples/html-script/add-to-cart/example-add-to-cart-auto.html +103 -81
  32. package/dist/examples/html-script/add-to-cart/example-add-to-cart-click.html +101 -78
  33. package/dist/examples/html-script/add-to-cart/example-add-to-cart-dedupe.html +90 -70
  34. package/dist/examples/html-script/add-to-cart/example-add-to-cart-manual.html +81 -67
  35. package/dist/examples/html-script/add-to-cart/example-add-to-cart-order-bump.html +90 -70
  36. package/dist/examples/html-script/add-to-cart/example-add-to-cart-text.html +104 -81
  37. package/dist/examples/html-script/behavior/example-behavior-engagement.html +489 -0
  38. package/dist/examples/html-script/behavior/example-behavior-heartbeat.html +350 -0
  39. package/dist/examples/html-script/behavior/example-behavior-runtime-intelligence.html +433 -0
  40. package/dist/examples/html-script/behavior/example-behavior-viewport.html +397 -0
  41. package/dist/examples/html-script/{example-behavior.html → behavior/example-behavior.html} +23 -17
  42. package/dist/examples/html-script/example-checkout-commerce.html +825 -0
  43. package/dist/examples/html-script/example-integration.html +5 -5
  44. package/dist/examples/html-script/example-landing-commerce.html +380 -0
  45. package/dist/examples/html-script/example-runtime-diagnostics.html +108 -0
  46. package/dist/examples/html-script/example-transport.html +5 -5
  47. package/dist/examples/html-script/full-funnel/README.md +64 -0
  48. package/dist/examples/html-script/full-funnel/checkout.html +116 -0
  49. package/dist/examples/html-script/full-funnel/downsell.html +58 -0
  50. package/dist/examples/html-script/full-funnel/landing.html +99 -0
  51. package/dist/examples/html-script/full-funnel/thank-you.html +85 -0
  52. package/dist/examples/html-script/full-funnel/upsell.html +64 -0
  53. package/dist/examples/html-script/initiate-checkout/README.md +6 -6
  54. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-attribute.html +94 -74
  55. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-auto.html +102 -80
  56. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-click.html +103 -80
  57. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-manual.html +86 -72
  58. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-snapshot.html +95 -75
  59. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-submit.html +103 -83
  60. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-text.html +105 -82
  61. package/dist/examples/html-script/lead/README.md +9 -7
  62. package/dist/examples/html-script/lead/example-lead-trigger-attribute.html +67 -47
  63. package/dist/examples/html-script/lead/example-lead-trigger-auto.html +78 -56
  64. package/dist/examples/html-script/lead/example-lead-trigger-click.html +78 -55
  65. package/dist/examples/html-script/release-candidate.html +187 -76
  66. package/dist/examples/html-script/remove-from-cart/README.md +1 -1
  67. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-attribute.html +93 -73
  68. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-css.html +93 -73
  69. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-dedupe.html +93 -73
  70. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-manual.html +84 -70
  71. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-multi.html +94 -74
  72. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-state.html +95 -75
  73. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-text.html +98 -76
  74. package/dist/examples/html-script/search/README.md +1 -1
  75. package/dist/examples/html-script/search/example-search-attribute.html +66 -51
  76. package/dist/examples/html-script/search/example-search-button-sync.html +66 -51
  77. package/dist/examples/html-script/search/example-search-dedupe.html +66 -51
  78. package/dist/examples/html-script/search/example-search-input.html +67 -51
  79. package/dist/examples/html-script/search/example-search-manual.html +57 -48
  80. package/dist/examples/html-script/search/example-search-submit.html +66 -51
  81. package/dist/examples/html-script/search/example-search-text.html +71 -51
  82. package/dist/examples/html-script/url-context/example-url-context-allowed-domains.html +63 -0
  83. package/dist/examples/html-script/url-context/example-url-context-landing.html +70 -0
  84. package/dist/examples/html-script/url-context/example-url-context-upsell.html +67 -0
  85. package/dist/examples/html-script/url-context/example-url-context.html +171 -0
  86. package/dist/examples/html-script/view-content/README.md +1 -1
  87. package/dist/examples/html-script/view-content/example-view-content-attribute.html +85 -70
  88. package/dist/examples/html-script/view-content/example-view-content-css.html +85 -70
  89. package/dist/examples/html-script/view-content/example-view-content-dedupe.html +85 -70
  90. package/dist/examples/html-script/view-content/example-view-content-empty.html +85 -70
  91. package/dist/examples/html-script/view-content/example-view-content-manual.html +76 -67
  92. package/dist/examples/html-script/view-content/example-view-content-product-card.html +85 -70
  93. package/dist/examples/html-script/view-content/example-view-content-text.html +90 -73
  94. package/dist/examples/v2/README.md +4 -1
  95. package/dist/{index-DUfFzniE.d.ts → index-CQAyT5Od.d.ts} +170 -3
  96. package/dist/{index-DUfFzniE.d.mts → index-JlKPz4pp.d.mts} +170 -3
  97. package/dist/index.cjs.js +1 -1
  98. package/dist/index.cjs.js.map +1 -1
  99. package/dist/index.d.mts +435 -12
  100. package/dist/index.d.ts +435 -12
  101. package/dist/index.esm.js +1 -1
  102. package/dist/index.esm.js.map +1 -1
  103. package/dist/{pixel-CbeF25mD.d.mts → pixel-BxZZx8l5.d.ts} +248 -72
  104. package/dist/{pixel-CbeF25mD.d.ts → pixel-CKc4OQUx.d.mts} +248 -72
  105. package/dist/{pixel-default-config-1VgLFOiL.d.mts → pixel-default-config-CJl-eypl.d.mts} +1 -1
  106. package/dist/{pixel-default-config-Bxb-Vdd8.d.ts → pixel-default-config-aAOujzwp.d.ts} +1 -1
  107. package/dist/runtime/index.cjs.js +1 -1
  108. package/dist/runtime/index.cjs.js.map +1 -1
  109. package/dist/runtime/index.d.mts +19 -26
  110. package/dist/runtime/index.d.ts +19 -26
  111. package/dist/runtime/index.esm.js +1 -1
  112. package/dist/runtime/index.esm.js.map +1 -1
  113. package/dist/services/index.cjs.js +1 -1
  114. package/dist/services/index.cjs.js.map +1 -1
  115. package/dist/services/index.d.mts +14 -6
  116. package/dist/services/index.d.ts +14 -6
  117. package/dist/services/index.esm.js +1 -1
  118. package/dist/services/index.esm.js.map +1 -1
  119. package/dist/types-BP8dz1gP.d.mts +19 -0
  120. package/dist/types-C75pQP31.d.ts +19 -0
  121. package/dist/types-DMhzHSVC.d.mts +293 -0
  122. package/dist/types-D_SsCur9.d.ts +293 -0
  123. package/dist/url-context-BjAsQoVl.d.mts +85 -0
  124. package/dist/url-context-BjAsQoVl.d.ts +85 -0
  125. package/dist/v2/global.global.js +1 -1
  126. package/dist/v2/global.global.js.map +1 -1
  127. package/dist/v2/index.cjs.js +1 -1
  128. package/dist/v2/index.cjs.js.map +1 -1
  129. package/dist/v2/index.d.mts +8 -6
  130. package/dist/v2/index.d.ts +8 -6
  131. package/dist/v2/index.esm.js +1 -1
  132. package/dist/v2/index.esm.js.map +1 -1
  133. package/docs/public/README.md +75 -0
  134. package/docs/public/api/exports.md +47 -0
  135. package/docs/public/api/pixel.md +65 -0
  136. package/docs/public/configuration/commerce.md +44 -0
  137. package/docs/public/configuration/modules.md +66 -0
  138. package/docs/public/configuration/overview.md +66 -0
  139. package/docs/public/events/catalog.md +65 -0
  140. package/docs/public/getting-started/installation.md +75 -0
  141. package/docs/public/getting-started/quick-start.md +77 -0
  142. package/docs/public/getting-started/react-nextjs.md +55 -0
  143. package/docs/public/getting-started/script-tag.md +57 -0
  144. package/docs/public/guides/funnel-checkout.md +52 -0
  145. package/docs/public/guides/funnel-downsell.md +53 -0
  146. package/docs/public/guides/funnel-full.md +64 -0
  147. package/docs/public/guides/funnel-landing.md +68 -0
  148. package/docs/public/guides/funnel-thank-you.md +48 -0
  149. package/docs/public/guides/funnel-upsell.md +72 -0
  150. package/docs/public/limitations.md +32 -0
  151. package/docs/public/privacy/limitations.md +33 -0
  152. package/docs/public/release-candidate/validation.md +37 -0
  153. package/docs/public/troubleshooting.md +55 -0
  154. package/package.json +13 -1
  155. package/dist/types-CTpRvFKZ.d.ts +0 -71
  156. package/dist/types-DGlBdsAy.d.mts +0 -71
@@ -1,3 +1,5 @@
1
+ import { U as UrlContextConfig } from './url-context-BjAsQoVl.mjs';
2
+
1
3
  type MetaBrowserDestinationConfig = {
2
4
  enabled: boolean;
3
5
  pixelIds: string[];
@@ -184,12 +186,54 @@ type SelectorFormConfig = string[] | {
184
186
  };
185
187
 
186
188
  /**
187
- * Contratos globais de commerce (catálogo, checkout inicial, mappings).
188
- * Vivem em `conversion.commerce`, fora de `auto`.
189
- * Runtime: ProductCatalog + CommerceState + Extractors +
190
- * CommerceResolver + OrderCalculator (Etapas 12C–12F).
189
+ * Contrato de fontes independentes para auto detectors (Etapa 14).
190
+ * Um evento automático pode ter várias sources; cada uma vira um detector.
191
191
  */
192
- type ProductType = 'main' | 'order_bump' | 'upsell' | 'downsell' | 'cross_sell' | 'addon' | 'subscription' | 'custom';
192
+
193
+ type AutoSourceType = 'selector' | 'form' | 'payment' | 'lifecycle' | 'url';
194
+ type AutoSourceBase = {
195
+ name: string;
196
+ type: AutoSourceType;
197
+ enabled?: boolean;
198
+ fireOnce?: boolean;
199
+ debounceMs?: number;
200
+ cooldownMs?: number;
201
+ };
202
+ type SelectorAutoSource = AutoSourceBase & {
203
+ type: 'selector';
204
+ selector: SelectorConfig;
205
+ selectorType?: SelectorType;
206
+ trigger?: 'click' | 'submit';
207
+ };
208
+ type FormAutoSource = AutoSourceBase & {
209
+ type: 'form';
210
+ selectorForm: SelectorFormConfig;
211
+ /** Opcional: restringe a fonte form a um target específico. */
212
+ selector?: SelectorConfig;
213
+ selectorType?: SelectorType;
214
+ };
215
+ type PaymentAutoSource = AutoSourceBase & {
216
+ type: 'payment';
217
+ paymentMethod?: PaymentMethod | (string & {});
218
+ cardDetection?: boolean;
219
+ autoDispatch?: boolean;
220
+ formSelector?: string;
221
+ };
222
+ type LifecycleAutoSource = AutoSourceBase & {
223
+ type: 'lifecycle';
224
+ trigger: 'init' | 'ready';
225
+ };
226
+ type UrlAutoSource = AutoSourceBase & {
227
+ type: 'url';
228
+ patterns: string[];
229
+ };
230
+ type AutoTrackSource = SelectorAutoSource | FormAutoSource | PaymentAutoSource | LifecycleAutoSource | UrlAutoSource;
231
+
232
+ /**
233
+ * Contratos globais de commerce (root `PixelConfig.commerce`).
234
+ * Não pertencem a conversion — representam o contexto comercial da página/fluxo.
235
+ */
236
+ type ProductType = 'main' | 'order_bump' | 'upsell' | 'downsell' | 'cross_sell' | 'addon' | 'subscription' | 'custom' | 'other';
193
237
  type CommerceProduct = {
194
238
  id: string;
195
239
  name?: string;
@@ -203,7 +247,7 @@ type CommerceProduct = {
203
247
  brand?: string;
204
248
  metadata?: Record<string, unknown>;
205
249
  };
206
- type CommerceItem = {
250
+ type CommerceCartItem = {
207
251
  productId: string;
208
252
  quantity?: number;
209
253
  price?: number;
@@ -211,36 +255,76 @@ type CommerceItem = {
211
255
  selected?: boolean;
212
256
  metadata?: Record<string, unknown>;
213
257
  };
214
- type CommerceCheckoutMode = 'single_product' | 'multi_product' | 'cart' | 'funnel';
215
- type CommerceCalculateValueFrom = 'selected_items' | 'event_items' | 'manual';
258
+ type CommerceCartMode = 'landing_page' | 'single_product' | 'multi_product' | 'checkout' | 'upsell' | 'custom' | 'cart' | 'funnel';
259
+ type CommerceCalculateValueFrom = 'cart' | 'event' | 'manual' | 'catalog';
260
+ type CommerceEnrichmentSource = 'cart' | 'event' | 'event_or_cart' | 'catalog';
261
+ type CommerceEventEnrichmentConfig = {
262
+ enabled: boolean;
263
+ source?: CommerceEnrichmentSource;
264
+ };
265
+ type CommerceEnrichmentConfig = {
266
+ pageView?: CommerceEventEnrichmentConfig;
267
+ viewContent?: CommerceEventEnrichmentConfig;
268
+ lead?: CommerceEventEnrichmentConfig;
269
+ addToCart?: CommerceEventEnrichmentConfig;
270
+ removeFromCart?: CommerceEventEnrichmentConfig;
271
+ initiateCheckout?: CommerceEventEnrichmentConfig;
272
+ addPaymentInfo?: CommerceEventEnrichmentConfig;
273
+ purchase?: CommerceEventEnrichmentConfig;
274
+ };
275
+ type ProductCatalogConfig = {
276
+ products?: CommerceProduct[];
277
+ };
278
+ type CommerceCartConfig = {
279
+ mode?: CommerceCartMode;
280
+ /** Seed inicial do carrinho — não é estado vivo. */
281
+ initialItems?: CommerceCartItem[];
282
+ allowDynamicItems?: boolean;
283
+ calculateValueFrom?: CommerceCalculateValueFrom;
284
+ metadata?: Record<string, unknown>;
285
+ };
286
+ type CommerceMappingsConfig = {
287
+ attributes?: Record<string, string[]>;
288
+ fields?: Record<string, string[]>;
289
+ };
216
290
  type CommerceConfig = {
291
+ enabled?: boolean;
217
292
  currency?: string;
218
- catalog?: {
219
- products?: CommerceProduct[];
220
- };
221
- checkout?: {
222
- mode?: CommerceCheckoutMode;
223
- selectedItems?: CommerceItem[];
224
- calculateValueFrom?: CommerceCalculateValueFrom;
225
- allowDynamicItems?: boolean;
226
- };
227
- mappings?: {
228
- attributes?: Record<string, string[]>;
229
- fields?: Record<string, string[]>;
230
- };
293
+ catalog?: ProductCatalogConfig;
294
+ cart?: CommerceCartConfig;
295
+ mappings?: CommerceMappingsConfig;
296
+ enrichment?: CommerceEnrichmentConfig;
231
297
  };
232
- /** Default seguro: sem produtos, sem itens, sem auto-disparo implícito. */
298
+ declare const DEFAULT_COMMERCE_ENRICHMENT: Required<CommerceEnrichmentConfig>;
299
+ /** Default seguro: commerce off, sem produtos, sem itens. */
233
300
  declare const DEFAULT_COMMERCE_CONFIG: CommerceConfig;
301
+ /** Normaliza calculateValueFrom (inclui aliases legado em runtime). */
302
+ declare function normalizeCalculateValueFrom(value: CommerceCalculateValueFrom | string | undefined): 'cart' | 'event' | 'manual' | 'catalog';
234
303
 
304
+ /** Limites de nível do Engagement Runtime (Etapa 19). */
235
305
  type EngagementThresholds = {
236
- low: number;
237
- medium: number;
306
+ /** Score máximo (inclusive) do nível `low`. */
307
+ lowMax: number;
308
+ /** Score máximo (inclusive) do nível `medium`. */
309
+ mediumMax: number;
238
310
  };
239
311
 
312
+ /** Pesos positivos do Engagement Runtime (Etapa 19). */
240
313
  type EngagementWeights = {
314
+ activeTime: number;
241
315
  scroll: number;
242
316
  click: number;
243
- time: number;
317
+ viewport: number;
318
+ visibility: number;
319
+ heartbeat: number;
320
+ };
321
+
322
+ /** Penalidades do Engagement Runtime (Etapa 19). */
323
+ type EngagementPenalties = {
324
+ /** Penalidade proporcional ao tempo ocioso (0..1). */
325
+ idle: number;
326
+ /** Penalidade proporcional a rage clicks (0..1). */
327
+ rageClick: number;
244
328
  };
245
329
 
246
330
  type ScrollBehaviorConfig = {
@@ -266,24 +350,129 @@ type VisibilityBehaviorConfig = {
266
350
  type ExitIntentBehaviorConfig = {
267
351
  enabled: boolean;
268
352
  };
353
+ /**
354
+ * Alvo observado pelo ViewportTracker (Etapa 18).
355
+ * `key` deve ser único dentro de `targets`.
356
+ */
357
+ type ViewportTargetConfig = {
358
+ readonly key: string;
359
+ /** Seletor CSS oficial. */
360
+ readonly selector: string;
361
+ /** Ratio mínimo para confirmar entrada (0..1). Default 0.5. */
362
+ readonly enterThreshold?: number;
363
+ /** Ratio no qual sai (0..enterThreshold). Default 0. */
364
+ readonly exitThreshold?: number;
365
+ /** Tempo mínimo contínuo acima do enterThreshold. Default 0. */
366
+ readonly minVisibleMs?: number;
367
+ /** Emite VIEWPORT_EXIT após entrada. Default true. */
368
+ readonly trackExit?: boolean;
369
+ /** Um único ciclo válido por elemento. Default false. */
370
+ readonly once?: boolean;
371
+ /** Inclui descritor sanitizado do elemento. Default false. */
372
+ readonly includeElement?: boolean;
373
+ };
374
+ /**
375
+ * Viewport Tracker — contrato oficial em `trackers.viewport`.
376
+ */
269
377
  type ViewportBehaviorConfig = {
270
- enabled: boolean;
271
- selector: string;
272
- selectorType: SelectorType;
273
- visibilityThreshold: number;
378
+ readonly enabled: boolean;
379
+ readonly targets: readonly ViewportTargetConfig[];
380
+ readonly rootMargin: string;
381
+ readonly observeMutations: boolean;
382
+ readonly mutationDebounceMs: number;
383
+ readonly maxObservedElements: number;
274
384
  };
275
- type HeartbeatBehaviorConfig = {
385
+ /**
386
+ * Heartbeat Runtime Engine (único contrato oficial).
387
+ * Não faz parte de `trackers`.
388
+ */
389
+ type HeartbeatModuleConfig = {
276
390
  enabled: boolean;
277
391
  intervalMs: number;
278
392
  hiddenIntervalMs: number;
393
+ emitWhenHidden: boolean;
394
+ emitWhenIdle: boolean;
395
+ includeSnapshot: boolean;
396
+ fireImmediately: boolean;
397
+ minActivityWindowMs?: number;
279
398
  };
399
+ /**
400
+ * Engagement Runtime Engine (Etapa 19) — contrato oficial em
401
+ * `modules.behavior.engagement`. Não faz parte de `trackers`.
402
+ */
280
403
  type EngagementBehaviorConfig = {
281
404
  enabled: boolean;
405
+ /** Intervalo de avaliação periódica via ManagedScheduler. */
406
+ evaluationIntervalMs: number;
407
+ /** Emite ENGAGEMENT_UPDATE apenas quando o score muda o suficiente. */
408
+ emitOnChange: boolean;
409
+ /** Delta mínimo de score para emitir um novo ENGAGEMENT_UPDATE. */
410
+ minScoreDelta: number;
411
+ /** Emite ENGAGEMENT_SUMMARY (uma vez) no destroy. */
412
+ emitSummaryOnDestroy: boolean;
282
413
  weights: EngagementWeights;
414
+ penalties: EngagementPenalties;
283
415
  thresholds: EngagementThresholds;
284
416
  };
417
+ /**
418
+ * Behavior Rate Limiter (Etapa 20) — limitador interno por instância.
419
+ * Protege o runtime de bursts de sinais; não é rate limit de Transport.
420
+ */
421
+ type RateLimitBehaviorConfig = {
422
+ enabled: boolean;
423
+ /** Janela deslizante (ms). */
424
+ windowMs: number;
425
+ /** Máximo de sinais aceitos por janela. */
426
+ maxSignalsPerWindow: number;
427
+ /** Sinais críticos (IDLE/ACTIVITY/VISIBLE/HIDDEN/EXIT_INTENT) ignoram o limite. */
428
+ criticalBypass: boolean;
429
+ };
430
+ /** Estratégia de descarte quando o buffer atinge `maxSize`. */
431
+ type BufferDropStrategy = 'drop_oldest' | 'drop_newest' | 'compress_similar';
432
+ /**
433
+ * Behavior Buffer (Etapa 20) — agregação interna de sinais normalizados.
434
+ * NÃO é a Transport Queue: sem persistência, retry, batch HTTP ou sendBeacon.
435
+ */
436
+ type BufferBehaviorConfig = {
437
+ enabled: boolean;
438
+ /** Capacidade máxima de entries antes de aplicar a drop strategy. */
439
+ maxSize: number;
440
+ /** Idade máxima (ms) de um entry antes do flush por idade (0 = desabilitado). */
441
+ maxAgeMs: number;
442
+ /** Tamanho que dispara flush por tamanho. */
443
+ flushSize: number;
444
+ dropStrategy: BufferDropStrategy;
445
+ /** Flush automático quando a página fica hidden. */
446
+ flushOnHidden: boolean;
447
+ };
448
+ /**
449
+ * Behavior State Machine (Etapa 20) — estado do runtime por instância.
450
+ */
451
+ type StateMachineBehaviorConfig = {
452
+ enabled: boolean;
453
+ /** Tamanho máximo do histórico de transições retido. */
454
+ historyLimit: number;
455
+ };
456
+ /**
457
+ * Behavior Session Summary (Etapa 20) — resumo consolidado da sessão.
458
+ */
459
+ type SessionSummaryBehaviorConfig = {
460
+ enabled: boolean;
461
+ /** Emite BEHAVIOR_SESSION_SUMMARY quando a página fica hidden. */
462
+ emitOnHidden: boolean;
463
+ /** Emite BEHAVIOR_SESSION_SUMMARY no destroy. */
464
+ emitOnDestroy: boolean;
465
+ /** Duração mínima da sessão (ms) para emitir o summary. */
466
+ minimumSessionMs: number;
467
+ };
285
468
  type BehaviorModuleConfig = {
286
469
  enabled: boolean;
470
+ heartbeat: HeartbeatModuleConfig;
471
+ engagement: EngagementBehaviorConfig;
472
+ rateLimit: RateLimitBehaviorConfig;
473
+ buffer: BufferBehaviorConfig;
474
+ stateMachine: StateMachineBehaviorConfig;
475
+ sessionSummary: SessionSummaryBehaviorConfig;
287
476
  trackers: {
288
477
  scroll: ScrollBehaviorConfig;
289
478
  click: ClickBehaviorConfig;
@@ -291,8 +480,6 @@ type BehaviorModuleConfig = {
291
480
  visibility: VisibilityBehaviorConfig;
292
481
  exitIntent: ExitIntentBehaviorConfig;
293
482
  viewport: ViewportBehaviorConfig;
294
- heartbeat: HeartbeatBehaviorConfig;
295
- engagement: EngagementBehaviorConfig;
296
483
  };
297
484
  };
298
485
 
@@ -311,46 +498,33 @@ type ManualConversionConfig = {
311
498
  viewContent: ManualEventConfig;
312
499
  };
313
500
  /**
314
- * Base compartilhada pelos auto detectors baseados em selector.
315
- * `selectorType` é fallback para strings sem prefixo (DEFAULT_SELECTOR_TYPE = css).
501
+ * Config de um auto detector — fontes independentes em `sources[]`.
316
502
  */
317
- type ConfiguredAutoDetectorConfig = {
318
- enabled: boolean;
319
- selector?: SelectorConfig;
320
- selectorType?: SelectorType;
321
- };
322
- /**
323
- * Detectors que podem exigir condição de formulário (`selectorForm`)
324
- * para liberar o disparo — não é fonte de dados de produto.
325
- */
326
- type FormCapableAutoDetectorConfig = ConfiguredAutoDetectorConfig & {
327
- selectorForm?: SelectorFormConfig;
328
- };
329
- type LeadAutoDetectorConfig = FormCapableAutoDetectorConfig;
330
- type AddToCartAutoDetectorConfig = FormCapableAutoDetectorConfig;
331
- type InitiateCheckoutAutoDetectorConfig = FormCapableAutoDetectorConfig;
332
- type PurchaseAutoDetectorConfig = ConfiguredAutoDetectorConfig;
333
- type RemoveFromCartAutoDetectorConfig = ConfiguredAutoDetectorConfig;
334
- type SearchAutoDetectorConfig = ConfiguredAutoDetectorConfig;
335
- type ViewContentAutoDetectorConfig = ConfiguredAutoDetectorConfig;
336
- type AddPaymentInfoAutoDetectorConfig = {
337
- enabled: boolean;
338
- paymentMethod: PaymentMethod;
339
- cardDetection: boolean;
340
- autoDispatch: boolean;
503
+ type AutoDetectorConfig = {
504
+ enabled: boolean;
505
+ sources: AutoTrackSource[];
506
+ };
507
+ type LeadAutoDetectorConfig = AutoDetectorConfig;
508
+ type AddToCartAutoDetectorConfig = AutoDetectorConfig;
509
+ type InitiateCheckoutAutoDetectorConfig = AutoDetectorConfig;
510
+ type PurchaseAutoDetectorConfig = AutoDetectorConfig;
511
+ type RemoveFromCartAutoDetectorConfig = AutoDetectorConfig;
512
+ type SearchAutoDetectorConfig = AutoDetectorConfig;
513
+ type ViewContentAutoDetectorConfig = AutoDetectorConfig;
514
+ type AddPaymentInfoAutoDetectorConfig = AutoDetectorConfig;
515
+ type ConversionAutoDetectorsConfig = {
516
+ lead: AutoDetectorConfig;
517
+ addToCart: AutoDetectorConfig;
518
+ removeFromCart: AutoDetectorConfig;
519
+ initiateCheckout: AutoDetectorConfig;
520
+ purchase: AutoDetectorConfig;
521
+ addPaymentInfo: AutoDetectorConfig;
522
+ search: AutoDetectorConfig;
523
+ viewContent: AutoDetectorConfig;
341
524
  };
342
525
  type AutoConversionConfig = {
343
526
  enabled: boolean;
344
- detectors: {
345
- lead: LeadAutoDetectorConfig;
346
- purchase: PurchaseAutoDetectorConfig;
347
- addToCart: AddToCartAutoDetectorConfig;
348
- removeFromCart: RemoveFromCartAutoDetectorConfig;
349
- initiateCheckout: InitiateCheckoutAutoDetectorConfig;
350
- addPaymentInfo: AddPaymentInfoAutoDetectorConfig;
351
- search: SearchAutoDetectorConfig;
352
- viewContent: ViewContentAutoDetectorConfig;
353
- };
527
+ detectors: ConversionAutoDetectorsConfig;
354
528
  };
355
529
  type ConversionRulesConfig = {
356
530
  enabled: boolean;
@@ -366,12 +540,10 @@ type ConversionRulesConfig = {
366
540
  };
367
541
  /**
368
542
  * Config do módulo de conversion.
369
- * `commerce` é global ao módulo (manual + auto), fora de `auto`.
543
+ * Commerce é root (`PixelConfig.commerce`) — não vive aqui.
370
544
  */
371
545
  type ConversionModuleConfig = {
372
546
  enabled: boolean;
373
- /** Catálogo, checkout inicial e mappings — compartilhado por manual e auto. */
374
- commerce: CommerceConfig;
375
547
  manual: ManualConversionConfig;
376
548
  auto: AutoConversionConfig;
377
549
  rules: ConversionRulesConfig;
@@ -427,6 +599,8 @@ type CoreModuleConfig = {
427
599
  dedupe: DedupeConfig;
428
600
  coordination: CoordinationConfig;
429
601
  ordering: OrderingConfig;
602
+ /** Core UrlContext — off por default. */
603
+ urlContext?: UrlContextConfig;
430
604
  };
431
605
 
432
606
  type PrivacyConsentConfig = {
@@ -549,7 +723,9 @@ type PixelConfig = {
549
723
  transport: TransportConfig;
550
724
  storage: StorageConfig;
551
725
  attribution: AttributionConfig;
726
+ /** Contexto comercial global da página/fluxo (fora dos módulos). */
727
+ commerce: CommerceConfig;
552
728
  modules: ModulesConfig;
553
729
  };
554
730
 
555
- export { type FingerprintConfig as $, type AttributionStoragePersistence as A, type BehaviorModuleConfig as B, type ConversionModuleConfig as C, DEFAULT_SELECTOR_TYPE as D, type EngagementThresholds as E, type FingerprintMode as F, DEFAULT_COMMERCE_CONFIG as G, getPrimarySelectorValue as H, type IntegrationsModuleConfig as I, resolveSelectorTypeFallback as J, type AddPaymentInfoAutoDetectorConfig as K, type AddToCartAutoDetectorConfig as L, type AnonymizationConfig as M, type AutoConversionConfig as N, type ClickBehaviorConfig as O, type PixelConfig as P, type QueueStoragePersistence as Q, type ConfiguredAutoDetectorConfig as R, type SessionStoragePersistence as S, type TransportModuleConfig as T, type ConsentConfig as U, type VisitorStoragePersistence as V, type ConversionRulesConfig as W, type CoordinationConfig as X, type DedupeConfig as Y, type EngagementBehaviorConfig as Z, type ExitIntentBehaviorConfig as _, type AttributionConfig as a, type FormCapableAutoDetectorConfig as a0, type GoogleBrowserDestinationConfig as a1, type GoogleIntegrationConfig as a2, type HeartbeatBehaviorConfig as a3, type IdleBehaviorConfig as a4, type InitiateCheckoutAutoDetectorConfig as a5, type IntegrationTestDestinationConfig as a6, type LeadAutoDetectorConfig as a7, type ManualConversionConfig as a8, type ManualEventConfig as a9, type MetaBrowserDestinationConfig as aa, type MetaIntegrationConfig as ab, type ModulesConfig as ac, type TikTokBrowserDestinationConfig as ad, type OrderingConfig as ae, type PageViewConfig as af, type PiiConfig as ag, type PrivacyConsentConfig as ah, type PurchaseAutoDetectorConfig as ai, type RemoveFromCartAutoDetectorConfig as aj, type ScrollBehaviorConfig as ak, type SearchAutoDetectorConfig as al, type SessionConfig as am, type TransportBatchConfig as an, type TransportFlushConfig as ao, type TransportOfflineConfig as ap, type TransportRetryConfig as aq, type TransportTimeoutConfig as ar, type ViewContentAutoDetectorConfig as as, type ViewportBehaviorConfig as at, type VisibilityBehaviorConfig as au, type VisitorConfig as av, type CoreModuleConfig as b, type PrivacyModuleConfig as c, type AppConfig as d, type PixelEnvironment as e, type PixelSource as f, type PixelTarget as g, type IdentityConfig as h, type TransportConfig as i, type StorageConfig as j, type StorageKeysConfig as k, type EngagementWeights as l, type PaymentMethod as m, type SelectorConfig as n, type SelectorDescriptor as o, type SelectorInput as p, type SelectorType as q, type SelectorFormConfig as r, type SelectorFormMode as s, type SelectorFormTrigger as t, type CommerceCalculateValueFrom as u, type CommerceCheckoutMode as v, type CommerceConfig as w, type CommerceItem as x, type CommerceProduct as y, type ProductType as z };
731
+ export { DEFAULT_COMMERCE_CONFIG as $, type AttributionStoragePersistence as A, type BehaviorModuleConfig as B, type ConversionModuleConfig as C, type SelectorFormTrigger as D, type EngagementThresholds as E, type FingerprintMode as F, type CommerceCalculateValueFrom as G, type CommerceCartConfig as H, type IntegrationsModuleConfig as I, type CommerceCartItem as J, type CommerceCartMode as K, type LifecycleAutoSource as L, type CommerceConfig as M, type CommerceEnrichmentConfig as N, type CommerceEnrichmentSource as O, type PixelConfig as P, type QueueStoragePersistence as Q, type CommerceEventEnrichmentConfig as R, type SessionStoragePersistence as S, type TransportModuleConfig as T, type CommerceMappingsConfig as U, type VisitorStoragePersistence as V, type CommerceProduct as W, type ProductCatalogConfig as X, type ProductType as Y, type UrlAutoSource as Z, DEFAULT_SELECTOR_TYPE as _, type AttributionConfig as a, DEFAULT_COMMERCE_ENRICHMENT as a0, getPrimarySelectorValue as a1, normalizeCalculateValueFrom as a2, resolveSelectorTypeFallback as a3, type AddPaymentInfoAutoDetectorConfig as a4, type AddToCartAutoDetectorConfig as a5, type AnonymizationConfig as a6, type AutoConversionConfig as a7, type AutoDetectorConfig as a8, type ClickBehaviorConfig as a9, type RemoveFromCartAutoDetectorConfig as aA, type ScrollBehaviorConfig as aB, type SearchAutoDetectorConfig as aC, type SessionConfig as aD, type TransportBatchConfig as aE, type TransportFlushConfig as aF, type TransportOfflineConfig as aG, type TransportRetryConfig as aH, type TransportTimeoutConfig as aI, type ViewContentAutoDetectorConfig as aJ, type ViewportBehaviorConfig as aK, type ViewportTargetConfig as aL, type VisibilityBehaviorConfig as aM, type VisitorConfig as aN, type ConsentConfig as aa, type ConversionAutoDetectorsConfig as ab, type ConversionRulesConfig as ac, type CoordinationConfig as ad, type DedupeConfig as ae, type EngagementBehaviorConfig as af, type ExitIntentBehaviorConfig as ag, type FingerprintConfig as ah, type GoogleBrowserDestinationConfig as ai, type GoogleIntegrationConfig as aj, type HeartbeatModuleConfig as ak, type IdleBehaviorConfig as al, type InitiateCheckoutAutoDetectorConfig as am, type IntegrationTestDestinationConfig as an, type LeadAutoDetectorConfig as ao, type ManualConversionConfig as ap, type ManualEventConfig as aq, type MetaBrowserDestinationConfig as ar, type MetaIntegrationConfig as as, type ModulesConfig as at, type TikTokBrowserDestinationConfig as au, type OrderingConfig as av, type PageViewConfig as aw, type PiiConfig as ax, type PrivacyConsentConfig as ay, type PurchaseAutoDetectorConfig as az, type CoreModuleConfig as b, type PrivacyModuleConfig as c, type AppConfig as d, type PixelEnvironment as e, type PixelSource as f, type PixelTarget as g, type IdentityConfig as h, type TransportConfig as i, type StorageConfig as j, type StorageKeysConfig as k, type AutoSourceBase as l, type AutoSourceType as m, type AutoTrackSource as n, type EngagementWeights as o, type EngagementPenalties as p, type FormAutoSource as q, type PaymentAutoSource as r, type PaymentMethod as s, type SelectorAutoSource as t, type SelectorConfig as u, type SelectorDescriptor as v, type SelectorInput as w, type SelectorType as x, type SelectorFormConfig as y, type SelectorFormMode as z };
@@ -1,4 +1,4 @@
1
- import { P as PixelConfig } from './pixel-CbeF25mD.mjs';
1
+ import { P as PixelConfig } from './pixel-CKc4OQUx.mjs';
2
2
 
3
3
  declare const DEFAULT_PIXEL_CONFIG: PixelConfig;
4
4
 
@@ -1,4 +1,4 @@
1
- import { P as PixelConfig } from './pixel-CbeF25mD.js';
1
+ import { P as PixelConfig } from './pixel-BxZZx8l5.js';
2
2
 
3
3
  declare const DEFAULT_PIXEL_CONFIG: PixelConfig;
4
4
 
@@ -1,3 +1,3 @@
1
1
  /* Pixel v2 — SDK de analytics e conversão */
2
- "use strict";var C=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var $=(o,e)=>{for(var t in e)C(o,t,{get:e[t],enumerable:!0})},V=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!O.call(o,i)&&i!==t&&C(o,i,{get:()=>e[i],enumerable:!(r=B(e,i))||r.enumerable});return o};var G=o=>V(C({},"__esModule",{value:!0}),o);var ee={};$(ee,{ModuleRegistry:()=>c,PixelRuntime:()=>P});module.exports=G(ee);var c=class{constructor(){this.modules=[]}register(e){if(this.modules.some(t=>t.name===e.name))throw new Error(`[Pixel] Module "${e.name}" is already registered`);this.modules.push(e)}getAll(){return this.modules}size(){return this.modules.length}};var d=class{constructor(e,t){this.metadataService=e,this.attribution=t??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),i=r!==void 0&&Object.keys(r).some(n=>{let s=r[n];return s!=null&&s!==""});return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...i?{identifiers:r}:{}}}};var g=class{constructor(e){this.debugEnabled=e}debug(...e){this.debugEnabled&&(typeof console>"u"||console.debug(...e))}info(...e){typeof console>"u"||console.info(...e)}warn(...e){typeof console>"u"||console.warn(...e)}error(...e){typeof console>"u"||console.error(...e)}};var u={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},M="attribution";var j=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],p=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},i={};for(let n of j){let s=t.get(n);s&&(n==="li_fat_id"?r.liFatId=s:r[n]=s)}for(let n of e){let s=t.get(n);s&&(i[n]=s)}return Object.keys(i).length>0&&(r.customClickIds=i),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var m=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[i,n]of Object.entries(r)){let s=e[i];s&&(t[n]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...i]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(i.join("=")||"")),e},{})}catch{return{}}}};var f=class{constructor(e={}){this.clickIdParser=new p;this.cookieCollector=new m;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},r={...t,...e},i={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(i).length>0&&(r.customClickIds=i),typeof r.fbclid=="string"&&r.fbclid){let n=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);n&&(r.fbc=n)}if(typeof window<"u")try{r.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(r.referrer=document.referrer)}catch{}return r}merge(e,t){let r={...e};for(let[n,s]of Object.entries(t))if(!(s==null||s==="")){if(n==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[n]=s}let i=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=i),r.lastCollectedAt=i,r}};var h=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??M}load(){if(!this.persist)return null;try{let e=this.storage.get(this.storageKey);return e?this.isExpired(e)?(this.clear(),null):e:null}catch{return null}}save(e){if(this.persist)try{this.storage.set(this.storageKey,e)}catch{}}clear(){try{this.storage.remove(this.storageKey)}catch{}}isExpired(e){let t=e.lastCollectedAt??e.firstCollectedAt;return t?Date.now()-t>this.ttlMs:!1}};var y=class{constructor(e,t=u){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new h(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new f({customParams:t.customClickIdParams??[],captureUrlParams:t.captureUrlParams!==!1,captureCookies:t.captureCookies!==!1})}init(){if(this.active||(this.active=!0,!this.enabled))return;let e=this.store.load();e&&(this.snapshot=e),this.collect()}destroy(){this.active&&(this.active=!1)}collect(){if(!this.enabled)return this.snapshot;let e=this.collector.collectFresh();return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.snapshot}getSnapshot(){return{...this.snapshot}}update(e){return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.getSnapshot()}clear(){this.snapshot={},this.store.clear()}};var S=class{getMetadata(){if(typeof window>"u")return{};let e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})();return{url:location.href,path:location.pathname,hostname:location.hostname,origin:location.origin,title:typeof document<"u"?document.title:void 0,referrer:typeof document<"u"?document.referrer:void 0,language:navigator.language,timezone:e,userAgent:navigator.userAgent,platform:navigator.platform,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth}}};var b=class{constructor(){this.listeners=new Set;this.lastEvent=null}dispatch(e){this.lastEvent=e;for(let t of this.listeners)t(e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};var Y="fingerprint";function H(o){let e=0;for(let i=0;i<o.length;i++)e=(e<<5)-e+o.charCodeAt(i),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let i=o.length-1;i>=0;i--)r=(r<<5)-r+o.charCodeAt(i),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function W(o){let e=o.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return H(t.join("|"))}var x=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Y,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=W(this.metadataService);return this.storage.set(this.storageKey,t),t}};var l=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let r=0;r<this.storage.length;r++){let i=this.storage.key(r);i&&e(i)&&t.push(i)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var a=class{constructor(){this.store=new Map}get(e){return this.store.get(e)??null}set(e,t){this.store.set(e,t)}remove(e){this.store.delete(e)}clear(){this.store.clear()}removeKeysMatching(e){for(let t of this.store.keys())e(t)&&this.store.delete(t)}};function J(o){return"removeKeysMatching"in o&&typeof o.removeKeysMatching=="function"}var v=class{constructor(e,t,r){this.adapter=e,this.namespace=t,this.prefix=r}get(e){let t=this.adapter.get(this.createKey(e));if(t===null)return null;try{return JSON.parse(t)}catch{return null}}set(e,t){this.adapter.set(this.createKey(e),JSON.stringify(t))}remove(e){this.adapter.remove(this.createKey(e))}has(e){return this.adapter.get(this.createKey(e))!==null}clear(){let e=this.getNamespaceKeyPrefix();if(J(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function R(o){let e=o??"memory";if(typeof window>"u")return new a;switch(e){case"memory":return new a;case"localStorage":return new l(window.localStorage);case"sessionStorage":return new l(window.sessionStorage);case"cookie_localStorage":return new l(window.localStorage);case"cookie":return new a;case"indexedDB":return new a;default:return new a}}function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function A(){return`ses_${Q()}`}var X="session",I=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??X}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),r=Date.now();if(!t){let i=A();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let i=t.sessionId,n=A();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!0,previousSessionId:i,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=A();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};function Z(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function E(){return`vst_${Z()}`}var q="visitor",w=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??q}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=E();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var P=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new c,this.fallbackLogger=new g(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let r=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${r.name}`);try{await r.destroy?.()}catch(i){e.error(`[Pixel] Failed to destroy module "${r.name}"`,i)}}this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}createServices(){let{namespace:e,prefix:t,persistence:r}=this.config.storage,i=this.createStorageService(e,t,r?.visitor),n=this.createStorageService(e,t,r?.session),s=this.createStorageService(e,t,r?.attribution),K=this.createStorageService(e,t,r?.attribution??"localStorage"),T=this.createStorageService(e,t,"memory"),k=new S,D=new y(K,this.config.attribution??u),_=new d(k,D),F=new w(i,this.config),L=new I(n,this.config),U=new x(s,this.config,k),N=new b;return{storage:T,visitor:F,session:L,fingerprint:U,dispatcher:N,browserMetadata:k,eventBuilder:_,attribution:D}}createStorageService(e,t,r){return new v(R(r),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices()}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};0&&(module.exports={ModuleRegistry,PixelRuntime});
2
+ "use strict";var ae=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var De=(n,e)=>{for(var t in e)ae(n,t,{get:e[t],enumerable:!0})},Te=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Re(e))!_e.call(n,o)&&o!==t&&ae(n,o,{get:()=>e[o],enumerable:!(r=Ae(e,o))||r.enumerable});return n};var Ue=n=>Te(ae({},"__esModule",{value:!0}),n);var Je={};De(Je,{ModuleRegistry:()=>k,PixelRuntime:()=>se});module.exports=Ue(Je);var k=class{constructor(){this.modules=[]}register(e){if(this.modules.some(t=>t.name===e.name))throw new Error(`[Pixel] Module "${e.name}" is already registered`);this.modules.push(e)}getAll(){return this.modules}size(){return this.modules.length}};var E=class{constructor(e,t,r){this.metadataService=e,this.attribution=t??null,this.urlContext=r??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),o=r!==void 0&&Object.keys(r).some(l=>{let c=r[l];return c!=null&&c!==""}),i=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,s=i!==null&&Object.keys(i.queryParams).length>0,a=i!==null&&(i.urlContext.managed&&Object.keys(i.urlContext.managed).length>0||i.urlContext.forwarded&&Object.keys(i.urlContext.forwarded).length>0||i.urlContext.source&&Object.keys(i.urlContext.source).length>0);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...o?{identifiers:r}:{},...s?{queryParams:{...i.queryParams}}:{},...a?{urlContext:{...i.urlContext.managed?{managed:{...i.urlContext.managed}}:{},...i.urlContext.forwarded?{forwarded:{...i.urlContext.forwarded}}:{},...i.urlContext.source?{source:{...i.urlContext.source}}:{}}}:{}}}};var w=class{constructor(e){this.debugEnabled=e}debug(...e){this.debugEnabled&&(typeof console>"u"||console.debug(...e))}info(...e){typeof console>"u"||console.info(...e)}warn(...e){typeof console>"u"||console.warn(...e)}error(...e){typeof console>"u"||console.error(...e)}};var A={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ce="attribution";var Le=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],R=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},o={};for(let i of Le){let s=t.get(i);s&&(i==="li_fat_id"?r.liFatId=s:r[i]=s)}for(let i of e){let s=t.get(i);s&&(o[i]=s)}return Object.keys(o).length>0&&(r.customClickIds=o),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var _=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[o,i]of Object.entries(r)){let s=e[o];s&&(t[i]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...o]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(o.join("=")||"")),e},{})}catch{return{}}}};var D=class{constructor(e={}){this.clickIdParser=new R;this.cookieCollector=new _;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},r={...t,...e},o={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(o).length>0&&(r.customClickIds=o),typeof r.fbclid=="string"&&r.fbclid){let i=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);i&&(r.fbc=i)}if(typeof window<"u")try{r.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(r.referrer=document.referrer)}catch{}return r}merge(e,t){let r={...e};for(let[i,s]of Object.entries(t))if(!(s==null||s==="")){if(i==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[i]=s}let o=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=o),r.lastCollectedAt=o,r}};var T=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??ce}load(){if(!this.persist)return null;try{let e=this.storage.get(this.storageKey);return e?this.isExpired(e)?(this.clear(),null):e:null}catch{return null}}save(e){if(this.persist)try{this.storage.set(this.storageKey,e)}catch{}}clear(){try{this.storage.remove(this.storageKey)}catch{}}isExpired(e){let t=e.lastCollectedAt??e.firstCollectedAt;return t?Date.now()-t>this.ttlMs:!1}};var U=class{constructor(e,t=A){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new T(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new D({customParams:t.customClickIdParams??[],captureUrlParams:t.captureUrlParams!==!1,captureCookies:t.captureCookies!==!1})}init(){if(this.active||(this.active=!0,!this.enabled))return;let e=this.store.load();e&&(this.snapshot=e),this.collect()}destroy(){this.active&&(this.active=!1)}collect(){if(!this.enabled)return this.snapshot;let e=this.collector.collectFresh();return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.snapshot}getSnapshot(){return{...this.snapshot}}update(e){return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.getSnapshot()}clear(){this.snapshot={},this.store.clear()}};var Z=class{getMetadata(){if(typeof window>"u")return{};let e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})();return{url:location.href,path:location.pathname,hostname:location.hostname,origin:location.origin,title:typeof document<"u"?document.title:void 0,referrer:typeof document<"u"?document.referrer:void 0,language:navigator.language,timezone:e,userAgent:navigator.userAgent,platform:navigator.platform,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth}}};var J=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let o=t[r];if(o)try{o(e)}catch(i){this.logger?.warn(Me(i,e.type,r))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function Me(n,e,t){let r=n instanceof Error?n.name:typeof n=="object"&&n!==null&&"name"in n?String(n.name):"Error",o=n instanceof Error?n.message:typeof n=="string"?n:"unknown";return o=o.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),o.length>200&&(o=`${o.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:o,timestamp:Date.now()}}var Oe="fingerprint";function Ne(n){let e=0;for(let o=0;o<n.length;o++)e=(e<<5)-e+n.charCodeAt(o),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let o=n.length-1;o>=0;o--)r=(r<<5)-r+n.charCodeAt(o),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function Fe(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Ne(t.join("|"))}var ee=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Oe,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Fe(this.metadataService);return this.storage.set(this.storageKey,t),t}};var P=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let r=0;r<this.storage.length;r++){let o=this.storage.key(r);o&&e(o)&&t.push(o)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var S=class{constructor(){this.store=new Map}get(e){return this.store.get(e)??null}set(e,t){this.store.set(e,t)}remove(e){this.store.delete(e)}clear(){this.store.clear()}removeKeysMatching(e){for(let t of this.store.keys())e(t)&&this.store.delete(t)}};function Be(n){return"removeKeysMatching"in n&&typeof n.removeKeysMatching=="function"}var L=class{constructor(e,t,r){this.adapter=e,this.namespace=t,this.prefix=r}get(e){let t=this.adapter.get(this.createKey(e));if(t===null)return null;try{return JSON.parse(t)}catch{return null}}set(e,t){this.adapter.set(this.createKey(e),JSON.stringify(t))}remove(e){this.adapter.remove(this.createKey(e))}has(e){return this.adapter.get(this.createKey(e))!==null}clear(){let e=this.getNamespaceKeyPrefix();if(Be(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function le(n){let e=n??"memory";if(typeof window>"u")return new S;switch(e){case"memory":return new S;case"localStorage":return new P(window.localStorage);case"sessionStorage":return new P(window.sessionStorage);case"cookie_localStorage":return new P(window.localStorage);case"cookie":return new S;case"indexedDB":return new S;default:return new S}}var M=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let r of e){if(!r||typeof r!="object")continue;let o=typeof r.id=="string"?r.id.trim():"";if(!o||this.productsById.has(o))continue;let i=this.normalizeProduct(r,o,t);this.productsById.set(o,i),this.orderedIds.push(o);let s=typeof i.sku=="string"?i.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,i)}}normalizeProduct(e,t,r){let o=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...o!==void 0?{sku:o}:{},...i!==void 0?{currency:i}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var O=class{constructor(e=[],t={}){this.itemsByProductId=new Map;this.allowDynamicItems=t.allowDynamicItems!==!1,this.seed(e??[])}getSelectedItems(){return Array.from(this.itemsByProductId.values()).map(e=>this.cloneItem(e))}hasItem(e){return!!e&&this.itemsByProductId.has(e)}getItem(e){if(!e)return null;let t=this.itemsByProductId.get(e);return t?this.cloneItem(t):null}upsertItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;if(e.selected===!1){this.itemsByProductId.delete(t);return}let r=this.normalizeQuantity(e.quantity);if(r<=0){this.itemsByProductId.delete(t);return}if(!this.itemsByProductId.has(t)&&!this.allowDynamicItems)return;let i=this.itemsByProductId.get(t),s=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,a={...i,...e,productId:t,quantity:r,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,a)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let r=this.normalizeQuantity(t);if(r<=0){this.itemsByProductId.delete(e);return}let o=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...o,quantity:r})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let r=this.normalizeQuantity(e.quantity);r<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:r,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var N=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of r)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let o=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...o!==void 0?{value:o}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let o of e){if(typeof o.price!="number"||!Number.isFinite(o.price))continue;let i=typeof o.quantity=="number"&&Number.isFinite(o.quantity)?o.quantity:1;t+=o.price*i,r=!0}return r?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let r of t)if(typeof r.currency=="string"&&r.currency.trim())return r.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var te={pageView:{enabled:!1,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},ue={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...te}};function F(n){switch(n){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var B=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=qe(e.defaultCurrency),this.calculateValueFrom=F(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},o=e.enrichmentSource??"event_or_cart",i=o==="cart"||o==="event_or_cart",s=o==="catalog"||o==="cart"||o==="event_or_cart",a=d(t.productId)??d(r.productId)??(s?this.lookupIdBySku(d(t.sku)??d(r.sku)):void 0),l=!a&&i?this.resolvePrimaryCartItem():null;!a&&l&&(a=l.productId);let c=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(d(t.sku)??d(r.sku)):null,u=a??c?.id,y=i&&u?this.state.getItem(u)??l:null;if(o==="catalog"&&!u&&!c)return{data:{...t}};let g=d(t.productName)??d(r.productName)??c?.name,p=h(t.price)??h(r.price)??(i?h(y?.price):void 0)??c?.price,m=h(t.quantity)??h(r.quantity)??(i?h(y?.quantity):void 0)??c?.quantity??1,f=d(t.currency)??d(r.currency)??(i?d(y?.currency):void 0)??c?.currency??this.defaultCurrency,C={};u&&(C.productId=u),g&&(C.productName=g),p!==void 0&&(C.price=p),f&&(C.currency=f),m!==void 0&&(C.quantity=m);for(let[Q,Y]of Object.entries(t))Y!==void 0&&(Q in C||(C[Q]=Y));return{data:C}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},o=d(t.productId)??d(r.productId)??this.lookupIdBySku(d(t.sku)??d(r.sku)),i=o?this.catalog.getById(o):null,s=o??i?.id,a=s?this.state.getItem(s):null,l=h(t.quantity)??h(r.quantity)??h(a?.quantity)??1,c={};s&&(c.productId=s),l!==void 0&&(c.quantity=l);for(let[u,y]of Object.entries(t))y!==void 0&&(u in c||(c[u]=y));return{data:c}}resolveCheckoutLike(e,t){let r={...e.payload??{}},o=h(r.value),i=d(r.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,l=this.resolveItemsSource(s,a),c=l.map(C=>this.toPixelItem(C)),u=a!=="catalog"&&this.calculateValueFrom!=="manual",y=o===void 0&&u,g=this.calculator.calculate({items:l,value:y?void 0:o,currency:i,defaultCurrency:this.defaultCurrency}),p=o!==void 0?o:u?g.value:void 0,m=i??g.currency??this.defaultCurrency,f={...r};return c.length>0?f.items=c:s===null&&delete f.items,p!==void 0?f.value=p:delete f.value,m&&(f.currency=m),{data:f,items:g.items,...p!==void 0?{value:p}:{},...m?{currency:m}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),s={...t},a=d(t.contentId)??d(o.data.productId)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].id=="string"?i.data.items[0].id:void 0),l=d(t.contentName)??d(o.data.productName)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].name=="string"?i.data.items[0].name:void 0);return a&&(s.contentId=a),l&&(s.contentName=l),h(t.value)===void 0&&i.value!==void 0&&(s.value=i.value),!d(t.currency)&&i.currency&&(s.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(s.items=i.data.items),{data:s,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return o.data.productId&&!d(t.contentId)&&(i.contentId=o.data.productId),o.data.productName&&!d(t.contentName)&&(i.contentName=o.data.productName),o.data.price!==void 0&&h(t.value)===void 0&&(i.value=o.data.price),o.data.currency&&!d(t.currency)&&(i.currency=o.data.currency),{data:i}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(r=>this.normalizeLooseItem(r));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(r=>this.normalizeLooseItem(r&&typeof r=="object"?r:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(r=>this.enrichItem(r));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="catalog"){let r=this.state.getSelectedItems();return r.length>0?r.map(o=>this.enrichItem({productId:o.productId,price:o.price,quantity:o.quantity,currency:o.currency})):this.catalog.list().map(o=>this.enrichItem({productId:o.id,price:o.price,quantity:o.quantity??1,currency:o.currency,productName:o.name,sku:o.sku,category:o.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),o=t??r?.id;return{...e,...o?{productId:o}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:d(e.productId)??d(e.id),sku:d(e.sku),productName:d(e.productName)??d(e.name),price:h(e.price),quantity:h(e.quantity),currency:d(e.currency),category:d(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function d(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function h(n){if(!(typeof n!="number"||!Number.isFinite(n)))return n}function qe(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}var q=class{constructor(e){this.config={...ue,...e,catalog:{products:e?.catalog?.products??[]},cart:{...ue.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...te,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new M(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new O(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new B({catalog:this.catalog,state:this.state,calculator:new N,defaultCurrency:this.config.currency,calculateValueFrom:F(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=te[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),r=t.data.items??[],o=r[0],i=o&&typeof o.id=="string"?o.id:void 0,s=o&&typeof o.name=="string"?o.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...i?{contentId:i}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return F(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Ke(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function re(){return`ses_${Ke()}`}var ze="session",oe=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??ze}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),r=Date.now();if(!t){let o=re();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let o=t.sessionId,i=re();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:o,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=re();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};function Ve(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Se(){return`vst_${Ve()}`}var $e="visitor",ne=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??$e}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Se();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var de=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],me=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],ge=["[data-no-url-context]","[download]"],xe="[data-no-sid]";function x(n){return n.trim().toLowerCase()}function K(n){try{return decodeURIComponent(n)}catch{return n}}function z(n,e){let t=new Set;if(e!==!1)for(let r of de)t.add(x(r));for(let r of n??[])typeof r=="string"&&r.trim()&&t.add(x(r));return t}function Ie(n,e){let t=[];e!==!1&&t.push(...me);for(let r of n??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function Pe(n,e,t){let r=[];e!==!1&&r.push(...ge),t&&r.push(xe);for(let o of n??[])typeof o=="string"&&o.trim()&&r.push(o.trim());return Array.from(new Set(r))}function ie(n,e){return e.has(x(n))}function be(n,e){let r=n.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),o=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===o||r.endsWith(`.${o}`)}function pe(n,e,t){if(!n)return!1;for(let r of t)if(be(n,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>be(n,r))}function fe(n="sid"){let e=(n||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),r=Math.random().toString(36).slice(2,10);return`${e}_${t}_${r}`}function v(){return typeof window<"u"&&typeof document<"u"}function ye(n){if(v())try{History.prototype.replaceState.call(history,history.state,document.title,n)}catch{}}function b(n){let e={};if(!n||n==="?")return e;let t=n.startsWith("?")?n.slice(1):n;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let o=r.indexOf("="),i=K((o>=0?r.slice(0,o):r).replace(/\+/g," ")).trim();if(!i)continue;let s=o>=0?K(r.slice(o+1).replace(/\+/g," ")):"";e[i]=s}return e}function V(n){let e=[];for(let[t,r]of Object.entries(n))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function I(n){return Object.freeze({...n})}function he(n,e){let t=n.trim(),r=e.search||"",o=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${o}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${o}`:t.startsWith("#")?`${r}${o}`:`${t.split(/[?#]/)[0]??t}${r}${o}`}var $=class{collect(e){if(!e||e.enabled===!1)return{};if(!v())return{};let t=b(window.location.search),r=z(e.denylist,e.mergeDefaultDenylist),o=e.mode??"all_except",i=new Set((e.allowlist??[]).map(x).filter(Boolean)),s={};for(let[a,l]of Object.entries(t))ie(a,r)||o==="allowlist"&&!i.has(x(a))||l!==""&&(s[a]=l);return s}};var j=class{constructor(e){this.store=e}resolve(e){let t={},r={},o={},i={},s=v()?b(window.location.search):{};for(let a of e){let l=a.param?.trim();if(!l)continue;let c=a.mode??"read_write",u=c==="read_only"||c==="read_write",y=c==="write_only"||c==="read_write",g=null,p=null;if(u){let m=s[l];m&&m.length>0&&(g=m,p="url")}if(!g&&u&&a.persistence?.enabled!==!1){let m=a.persistence?.cookie?.name?.trim()||l;if(a.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(m);f&&(g=f,p="cookie")}}if(!g&&u&&a.persistence?.enabled!==!1){let m=a.persistence?.storageKey?.trim()||l,f=this.store.getStorage(m);f&&(g=f,p="storage")}!g&&y&&a.generator?.type==="public_id"&&(g=fe(a.generator.prefix??l),p="generated"),!(!g||!p)&&(t[l]=g,r[l]=p,a.decorateLinks!==!1&&(o[l]=g),a.persistence?.enabled!==!1&&this.persist(a,g),y&&(a.writeStrategy??"replaceState")==="replaceState"&&v()&&s[l]!==g&&(i[l]=g))}return Object.keys(i).length>0&&v()&&this.writeToUrl(i),{values:t,sources:r,decorateParams:o}}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",o=e.persistence?.storageKey?.trim()||e.param,i=e.persistence?.cookie,s=i?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(o,t),(r==="cookie"||r==="localStorage_cookie")&&i?.enabled!==!1&&this.store.setCookie({name:s,value:t,path:i?.path??"/",domain:i?.domain??"auto",sameSite:i?.sameSite??"Lax",secure:i?.secure??!0,maxAgeMs:i?.maxAgeMs})}writeToUrl(e){let r={...b(window.location.search),...e},o=V(r),i=window.location.hash??"",s=window.location.pathname+o+i;ye(s)}};var H=class{resolve(e){let{queryParams:t,managedValues:r,config:o}=e;if(!o||o.enabled===!1)return{};let i=z(o.denylist,o.mergeDefaultDenylist),s=o.mode??"all_except",a=new Set((o.allowlist??[]).map(x).filter(Boolean)),l={};for(let[c,u]of Object.entries(t))u&&(ie(c,i)||c in r||s==="allowlist"&&!a.has(x(c))||(l[c]=u));return l}};var je=["mailto:","tel:","javascript:","data:","blob:"],X=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;this.params=Object.freeze({...e}),this.config=t,this.excludedDomains=Ie(t.excludedDomains,t.mergeDefaultExcludedDomains),this.excludeSelectors=Pe(t.excludeSelectors,t.mergeDefaultExcludeSelectors,r)}start(){if(this.started||!v()||this.config.enabled===!1||Object.keys(this.params).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let r=He(t.target);r&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let r=e.trim(),o=r.toLowerCase();for(let m of je)if(o.startsWith(m))return m==="mailto:"&&this.config.decorateMailto===!0||m==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let i;try{let m=v()?window.location.href:`https://${t??"example.com"}/`;i=new URL(r,m)}catch{return null}if(!pe(i.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=b(i.search),a=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,c={...s},u=!1;for(let[m,f]of Object.entries(this.params))m in c&&a&&!l||(c[m]!==f&&(u=!0),c[m]=f);let y=b(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),g=Xe(r)>Object.keys(y).length;if(!u&&!g)return r;let p=V(c);return i.search=p.startsWith("?")?p.slice(1):p,he(r,i)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let r of t)r instanceof HTMLAnchorElement&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let r=this.decorateHref(t);r!=null&&r!==t&&e.setAttribute("href",r)}};function He(n){return n instanceof Element?n.closest("a[href]"):null}function Xe(n){let e=n.indexOf("?");if(e<0)return 0;let t=n.indexOf("#",e),r=t>=0?n.slice(e+1,t):n.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var W=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!v())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let o=r.indexOf("=");if((o>=0?r.slice(0,o):r).trim()!==e)continue;let s=o>=0?r.slice(o+1).trim():"";return K(s)}}catch{return null}return null}setCookie(e){if(!v())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=We(e.domain);r&&t.push(`domain=${r}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let o=e.sameSite??"Lax";t.push(`SameSite=${o}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function We(n){if(!n||n==="auto"){if(!v())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return n}var Ee={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},Qe={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ye={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ze={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function ve(n){if(!n||n.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=n.managedParams!==void 0?n.managedParams.map(ke):[ke(Ee)];return{enabled:!0,queryParams:{...Qe,...n.queryParams,...n.queryParams?.allowlist?{allowlist:[...n.queryParams.allowlist]}:{},...n.queryParams?.denylist?{denylist:[...n.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...Ye,...n.forwardParams,...n.forwardParams?.allowlist?{allowlist:[...n.forwardParams.allowlist]}:{},...n.forwardParams?.denylist?{denylist:[...n.forwardParams.denylist]}:{}},linkDecoration:{...Ze,...n.linkDecoration,...n.linkDecoration?.allowedDomains&&n.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...n.linkDecoration.allowedDomains]}:{},...n.linkDecoration?.excludedDomains?{excludedDomains:[...n.linkDecoration.excludedDomains]}:{},...n.linkDecoration?.excludeSelectors?{excludeSelectors:[...n.linkDecoration.excludeSelectors]}:{}}}}function ke(n){return{...n,...n.generator?{generator:{...n.generator}}:{},...n.persistence?{persistence:{...n.persistence,...n.persistence.cookie?{cookie:{...n.persistence.cookie}}:{}}}:{}}}var G=class{constructor(e,t){this.collector=new $;this.forwardResolver=new H;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Ce();this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=ve(this.rawConfig);if(this.enabled=e.enabled,!e.enabled){this.snapshot=Ce();return}this.store=new W(this.storage),this.managedResolver=new j(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),o=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,i=this.forwardResolver.resolve({queryParams:o,managedValues:r.values,config:e.forwardParams}),s={...r.sources};for(let u of Object.keys(i))s[u]||(s[u]="url");let a={...Object.keys(r.values).length>0?{managed:I(r.values)}:{},...Object.keys(i).length>0?{forwarded:I(i)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:I(o),urlContext:Object.freeze(a)};let l={...i,...r.decorateParams},c=e.managedParams.some(u=>u.param==="sid"&&u.decorateLinks!==!1);this.decorator=new X(l,e.linkDecoration,c),this.decorator.start()}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.initialized=!1,this.enabled=!1,this.snapshot=Ce()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:I(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:I(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:I(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function Ce(){return{queryParams:I({}),urlContext:Object.freeze({})}}var se=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new k,this.fallbackLogger=new w(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let r=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${r.name}`);try{await r.destroy?.()}catch(o){e.error(`[Pixel] Failed to destroy module "${r.name}"`,o)}}this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:r,persistence:o}=this.config.storage,i=this.createStorageService(t,r,o?.visitor),s=this.createStorageService(t,r,o?.session),a=this.createStorageService(t,r,o?.attribution),l=this.createStorageService(t,r,o?.attribution??"localStorage"),c=this.createStorageService(t,r,"memory"),u=new Z,y=new U(l,this.config.attribution??A),g=this.createStorageService(t,r,o?.attribution??"localStorage"),p=new G(this.config.modules.core.urlContext,g),m=new E(u,y,p),f=new ne(i,this.config),C=new oe(s,this.config),Q=new ee(a,this.config,u),Y=new J(e),we=new q(this.config.commerce);return{storage:c,visitor:f,session:C,fingerprint:Q,dispatcher:Y,browserMetadata:u,eventBuilder:m,attribution:y,commerce:we,urlContext:p}}createStorageService(e,t,r){return new L(le(r),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};0&&(module.exports={ModuleRegistry,PixelRuntime});
3
3
  //# sourceMappingURL=index.cjs.js.map