@sharadtech/infralytiqs-sdk 1.0.1 → 1.0.3

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 (69) hide show
  1. package/buildScripts/Jenkinsfile.deploy +241 -125
  2. package/clients/publicis/arc/README.md +212 -0
  3. package/clients/publicis/arc/package-lock.json +808 -0
  4. package/clients/publicis/arc/package.json +23 -0
  5. package/clients/publicis/arc/rollup.config.mjs +28 -0
  6. package/clients/publicis/arc/src/index.js +2900 -0
  7. package/clients/publicis/atl/README.md +203 -0
  8. package/clients/publicis/atl/package-lock.json +808 -0
  9. package/clients/publicis/atl/package.json +23 -0
  10. package/clients/publicis/atl/rollup.config.mjs +28 -0
  11. package/clients/publicis/atl/src/index.js +2902 -0
  12. package/clients/publicis/colab/README.md +213 -0
  13. package/clients/publicis/colab/package-lock.json +808 -0
  14. package/clients/publicis/colab/package.json +23 -0
  15. package/clients/publicis/colab/rollup.config.mjs +28 -0
  16. package/clients/publicis/colab/src/index.js +2901 -0
  17. package/clients/publicis/fnacdarty/README.md +210 -0
  18. package/clients/publicis/fnacdarty/package-lock.json +808 -0
  19. package/clients/publicis/fnacdarty/package.json +23 -0
  20. package/clients/publicis/fnacdarty/rollup.config.mjs +28 -0
  21. package/clients/publicis/fnacdarty/src/index.js +2900 -0
  22. package/clients/publicis/garnier/README.md +206 -0
  23. package/clients/publicis/garnier/package-lock.json +808 -0
  24. package/clients/publicis/garnier/package.json +23 -0
  25. package/clients/publicis/garnier/rollup.config.mjs +28 -0
  26. package/clients/publicis/garnier/src/index.js +2894 -0
  27. package/clients/publicis/pmigtr/README.md +212 -0
  28. package/clients/publicis/pmigtr/package-lock.json +808 -0
  29. package/clients/publicis/pmigtr/package.json +23 -0
  30. package/clients/publicis/pmigtr/rollup.config.mjs +28 -0
  31. package/clients/publicis/pmigtr/src/index.js +2903 -0
  32. package/clients/publicis/ps/README.md +105 -5
  33. package/clients/publicis/ps/package-lock.json +2 -2
  34. package/clients/publicis/ps/package.json +1 -1
  35. package/clients/publicis/ps/src/index.js +2473 -70
  36. package/clients/publicis/px/README.md +209 -0
  37. package/clients/publicis/px/package-lock.json +808 -0
  38. package/clients/publicis/px/package.json +23 -0
  39. package/clients/publicis/px/rollup.config.mjs +28 -0
  40. package/clients/publicis/px/src/index.js +2899 -0
  41. package/clients/publicis/pxp/README.md +212 -0
  42. package/clients/publicis/pxp/package-lock.json +808 -0
  43. package/clients/publicis/pxp/package.json +23 -0
  44. package/clients/publicis/pxp/rollup.config.mjs +28 -0
  45. package/clients/publicis/pxp/src/index.js +2900 -0
  46. package/clients/publicis/razorfish/README.md +210 -0
  47. package/clients/publicis/razorfish/package-lock.json +808 -0
  48. package/clients/publicis/razorfish/package.json +23 -0
  49. package/clients/publicis/razorfish/rollup.config.mjs +28 -0
  50. package/clients/publicis/razorfish/src/index.js +2900 -0
  51. package/clients/publicis/stellantis/README.md +208 -0
  52. package/clients/publicis/stellantis/package-lock.json +808 -0
  53. package/clients/publicis/stellantis/package.json +23 -0
  54. package/clients/publicis/stellantis/rollup.config.mjs +28 -0
  55. package/clients/publicis/stellantis/src/index.js +2895 -0
  56. package/clients/publicis/visa/README.md +208 -0
  57. package/clients/publicis/visa/package-lock.json +808 -0
  58. package/clients/publicis/visa/package.json +23 -0
  59. package/clients/publicis/visa/rollup.config.mjs +28 -0
  60. package/clients/publicis/visa/src/index.js +2894 -0
  61. package/dist/infralytiqs.js +272 -3
  62. package/dist/infralytiqs.min.js +2 -2
  63. package/package.json +1 -1
  64. package/src/envConfig.ts +1 -1
  65. package/src/index.ts +31 -0
  66. package/src/remoteConfig.ts +164 -0
  67. package/src/token.ts +79 -0
  68. package/src/tracker.ts +30 -0
  69. package/src/types.ts +10 -2
@@ -0,0 +1,2901 @@
1
+ /**
2
+ * Infralytiqs client-specific bootstrap — Publicis Colab
3
+ * (aem-sit.publiciscolab.com, ...)
4
+ *
5
+ * This is the "colab" sibling of the "publicis/ps" bootstrap. Both target
6
+ * the same Adobe DAM Asset Share Commons platform (groupe-dam tenant), so
7
+ * the event taxonomy, selectors, and DOM heuristics are identical; only
8
+ * the host domain, the client-override global namespace (IL_COLAB_*), and
9
+ * the internal de-dupe flag prefixes (__ilColab*) differ. The per-tenant
10
+ * server/tenant/site/db values are still read from window.IL_* injected
11
+ * server-side by the AEM Sightly `Infralytiqs.html` fragment (colab runs
12
+ * on site_id = SIT), so this file hard-codes none of them.
13
+ *
14
+ * Colab serves its ASC pages under a /colab/us/en/ locale prefix
15
+ * (login at `/colab/us/en/login.html`, home/search at
16
+ * `/colab/us/en/home.html`, asset explorer at
17
+ * `/colab/us/en/home/asset-explorer.html`, details at
18
+ * `/.../details/<type>.html/<assetPath>`) and its DAM content lives under
19
+ * `/content/dam/px/colab`. The page-type heuristics below match
20
+ * `login` / `asset-explorer` / `details` anywhere in the path and accept
21
+ * any `/content/dam/...` asset path, so neither the locale prefix nor the
22
+ * nested DAM root needs special handling.
23
+ *
24
+ * Pipeline:
25
+ * 1. The host page embeds the Infralytiqs SDK from the CDN:
26
+ * <script src="https://assets.infralytiqs.com/cdn/infralytiqs.min.js"></script>
27
+ * 2. The host page injects per-tenant configuration as `window.IL_*` globals
28
+ * (server-side rendered via the Sightly `Infralytiqs.html` fragment).
29
+ * 3. This bootstrap loads after the SDK + config and:
30
+ * a. Reads window.IL_* and Infralytiqs.init() with browser-side enrichment.
31
+ * b. Resolves the logged-in AEM user via /libs/granite/security/currentuser.json
32
+ * and calls Infralytiqs.identify() so subsequent events carry user_id.
33
+ * c. Tracks two families of events:
34
+ *
35
+ * ──────────────────────────────────────────────────────────────
36
+ * LOGIN PAGE (auth_state = anonymous)
37
+ * ──────────────────────────────────────────────────────────────
38
+ * login_page_view — anonymous landing on the login page
39
+ * login_attempt — Sign-in button submit (captures typed username,
40
+ * NEVER the password)
41
+ * sso_click — "Login with Lion Login" SSO button click
42
+ * terms_click — "Terms and Conditions" link click
43
+ *
44
+ * ──────────────────────────────────────────────────────────────
45
+ * ASSET SHARE COMMONS (auth_state = authenticated)
46
+ * (search_context = "asc" — URL-driven, pushState SPA)
47
+ * ──────────────────────────────────────────────────────────────
48
+ * search_executed — fired on every page whose URL carries `?fulltext=…`.
49
+ * Captures search term, semantic / fuzzy toggles,
50
+ * active filters (group, human label, property,
51
+ * operation, values) cross-referenced against the
52
+ * right-rail predicate sections so reports can
53
+ * render `ASSET TYPE = Image` instead of
54
+ * `jcr:content/metadata/ps:assettype = Image`,
55
+ * order-by, sort direction, layout (card | list),
56
+ * offset / limit, plus the search-statistics widget
57
+ * (`search_time_ms`, `result_total`, `result_pages`)
58
+ * once ASC finishes rendering the result count and
59
+ * response time in the right rail. The bootstrap
60
+ * briefly observes the statistics block before
61
+ * firing so the timing reflects the search the
62
+ * user actually just executed (not a stale value
63
+ * left over from the previous in-page navigation).
64
+ *
65
+ * asset_preview — fired on every page whose URL matches
66
+ * /details/<type>.html/<assetPath>. Captures the
67
+ * /content/dam/... path, the asset-share asset type
68
+ * (image / video / document / 3d / …), file name
69
+ * and extension.
70
+ *
71
+ * asset_download — fired when the browser POSTs to the ASC download
72
+ * endpoint (network interception, NOT button click,
73
+ * so it captures bulk-download from card menus,
74
+ * detail-page button, and the dropdown rendition
75
+ * picker uniformly).
76
+ * Captures asset_path + rendition_name from the
77
+ * form-encoded POST body.
78
+ *
79
+ * asset_add_to_cart — fired on click of any element matched by the
80
+ * `addToCart` selector list, the `[data-il-cart-add]`
81
+ * opt-in attribute, or visible text /add to cart/i.
82
+ * Captures the asset_path from data-attrs on the
83
+ * button or its nearest card ancestor.
84
+ *
85
+ * asset_share — fired on click of any element matched by the
86
+ * `shareButton` selector list or visible text
87
+ * /share/i. Placeholder until the share workflow
88
+ * is finalized.
89
+ *
90
+ * ──────────────────────────────────────────────────────────────
91
+ * ASSET EXPLORER (search_context = "asset_explorer")
92
+ * /asset-explorer.html#/content/dam/... (React SPA, hash routing)
93
+ * ──────────────────────────────────────────────────────────────
94
+ * search_executed — fired when the user runs a search inside the
95
+ * explorer. Listens to every plausible trigger
96
+ * (Enter on the input, native form submit,
97
+ * Search Options modal close, right-rail filter
98
+ * click, debounced typing) and carries the
99
+ * original `search_trigger` on each event so we
100
+ * can prune redundant hooks once production
101
+ * tells us which path actually fires. Captures
102
+ * search_term, semantic_search, fuzzy_search
103
+ * (read from the toggles in the open Search
104
+ * Options modal — see readAssetExplorerToggleState
105
+ * for the four heuristics tried), `folder_path`
106
+ * (the `#/content/dam/...` hash), and the stats
107
+ * widget (`search_time_ms`, `result_total`,
108
+ * `result_displayed`, `result_pages` when shown)
109
+ * once it settles. Subtype is `asset_search` —
110
+ * same as ASC — so a single ClickHouse query can
111
+ * report cross-context search volume.
112
+ *
113
+ * folder_navigation — fired whenever the hash route changes (user
114
+ * clicked into another DAM folder). Carries
115
+ * `folder_path` + the standard browser-side
116
+ * enrichment dimensions. Subtype is `asset_browse`.
117
+ *
118
+ * asset_preview — reuses the ASC details-page detector when the
119
+ * explorer hands off to a /details/<type>.html URL,
120
+ * plus the body-level click delegation so a
121
+ * right-side preview panel that exposes a
122
+ * `data-asset-path` attribute is also captured.
123
+ *
124
+ * asset_download — same network-interception path as ASC, since the
125
+ * download endpoint is shared at the AEM backend
126
+ * layer.
127
+ *
128
+ * asset_add_to_cart, asset_share — same click delegation as ASC.
129
+ *
130
+ * Selector strategy
131
+ * -----------------
132
+ * The DOM may evolve, so every selector is overridable via window globals
133
+ * (set BEFORE this bootstrap runs):
134
+ *
135
+ * window.IL_COLAB_SELECTORS = {
136
+ * // Login page
137
+ * loginForm: '#loginForm',
138
+ * signInButton: 'button[type="submit"]',
139
+ * userField: 'input[name="username"]',
140
+ * ssoButton: '[data-il-sso-lion]',
141
+ * termsLink: 'a[href*="terms"]',
142
+ * // ASC
143
+ * searchInput: 'input[name="fulltext"]',
144
+ * filterRail: '#rail',
145
+ * addToCart: '[data-il-cart-add]',
146
+ * shareButton: '[data-il-share]'
147
+ * };
148
+ *
149
+ * If none are provided we fall back to a robust default set that matches
150
+ * by id, name, role, data-attribute, and visible text — so the bootstrap
151
+ * is essentially zero-config for the common ASC layout.
152
+ *
153
+ * The host page can also override how the logged-in user is resolved:
154
+ *
155
+ * window.IL_COLAB_USER_RESOLVER = function () {
156
+ * return 'qa-ps-asc-global'; // sync
157
+ * // or: return Promise.resolve('qa-ps-asc-global');
158
+ * };
159
+ */
160
+ (function () {
161
+ 'use strict';
162
+
163
+ if (window.__ilColabBootstrapped) {
164
+ return;
165
+ }
166
+ window.__ilColabBootstrapped = true;
167
+
168
+ // ─── 1. Read host-page configuration ──────────────────────
169
+ var SERVER_URL = window.IL_SERVER_URL;
170
+ var TENANT_ID = window.IL_TENANT_ID;
171
+ var SITE_ID = window.IL_SITE_ID;
172
+ var DB_NAME = window.IL_DB_NAME;
173
+
174
+ if (!SERVER_URL || !TENANT_ID || !SITE_ID) {
175
+ return;
176
+ }
177
+
178
+ var USER_OVERRIDES = (window.IL_COLAB_SELECTORS && typeof window.IL_COLAB_SELECTORS === 'object')
179
+ ? window.IL_COLAB_SELECTORS
180
+ : {};
181
+
182
+ // ─── 2. Default selectors ────────────────────────────────
183
+ // Each is a comma-separated list of CSS selectors tried in order. The first
184
+ // element that matches the page wins. Text-based fallback below handles
185
+ // pages whose controls don't carry stable IDs.
186
+ var SELECTORS = {
187
+ // ── Login page ─────────────────────────────────────────
188
+ loginForm: USER_OVERRIDES.loginForm
189
+ || 'form#loginForm, form[name="loginForm"], form[action*="login"], form[action*="signin"]',
190
+ signInButton: USER_OVERRIDES.signInButton
191
+ || '#signInButton, #signin, #signInBtn, #loginButton, button[name="signin"], button[data-action="signin"], button[type="submit"]',
192
+ userField: USER_OVERRIDES.userField
193
+ || '#username, #userId, #email, input[name="username"], input[name="userId"], input[name="email"], input[type="email"]',
194
+ ssoButton: USER_OVERRIDES.ssoButton
195
+ || '#lionLogin, [data-il-sso-lion], [data-sso="lion-login"], button[name="lion-login"], a[href*="lion-login"], a[href*="lionlogin"]',
196
+ termsLink: USER_OVERRIDES.termsLink
197
+ || 'a[data-il-terms], a#termsLink, a[href*="terms-and-conditions"], a[href*="terms_and_conditions"], a[href*="/terms"], a[href*="terms.html"]',
198
+
199
+ // ── Asset Share Commons ───────────────────────────────
200
+ // The search input on aem-sit.publiciscolab.com has `name="fulltext"` and the
201
+ // `data-search-input` attribute set by the ASC search-bar component
202
+ // (id includes a per-render numeric suffix, so we don't depend on it).
203
+ searchInput: USER_OVERRIDES.searchInput
204
+ || 'input[name="fulltext"], [data-search-input], input.cmp-fulltext, input[type="search"][data-cmp-hook-search-input]',
205
+ // The ASC right-rail container that holds the filter/predicate panel.
206
+ // On aem-sit.publiciscolab.com this is `#rail` inside the asset-share-commons
207
+ // root; we keep a comma-separated fallback list so the bootstrap also
208
+ // covers older / themed deployments that use a `.sidebar` wrapper.
209
+ filterRail: USER_OVERRIDES.filterRail
210
+ || '#rail, .search-rail, [data-cmp-is="search-rail"], #asset-share-commons .ui.wide.sidebar.right, .ui.wide.sidebar.right',
211
+ // Search-statistics widget (right-rail, "X assets / 54 ms / Y pages").
212
+ // On aem-sit.publiciscolab.com this is `.cmp.cmp-search-statistics` containing
213
+ // a Semantic-UI `.ui.mini.three.statistics` block with three `.statistic`
214
+ // tiles. We keep alternative selectors for themed / re-skinned variants.
215
+ searchStatistics: USER_OVERRIDES.searchStatistics
216
+ || '.cmp.cmp-search-statistics, [class*="cmp-search-statistics"], [data-cmp-is="search-statistics"], .search-statistics, .cmp-searchstatistics',
217
+ // Asset-level Add-to-Cart button (per-tile / per-card / details
218
+ // page). The Asset Share Commons convention puts the asset path on
219
+ // `data-asset-share-asset` and the button-id on `data-asset-share-id`.
220
+ // We prioritise the data attributes so the button can be detected
221
+ // even when rendered as an icon-only variant with no visible label.
222
+ addToCart: USER_OVERRIDES.addToCart
223
+ || '[data-asset-share-id="add-to-cart"], [data-asset-share-id="addToCart"], [data-il-cart-add], [data-cmp-cart-action="add"], [data-asset-cart-action="add"], button.cart-add, a.cart-add, button[data-action="cart-add"]',
224
+ // Asset-level Share button. Distinct from the cart-level share
225
+ // (`data-asset-share-id="share-all"`) which the click delegation
226
+ // checks BEFORE this so they never overlap.
227
+ shareButton: USER_OVERRIDES.shareButton
228
+ || '[data-asset-share-id="share-asset"], [data-asset-share-id="share"], [data-il-share], [data-cmp-share-action], button.share, a.share, button[data-action="share"]',
229
+ // ── Cart & downloads (ASC modal flow, used on the asset-explorer too) ──
230
+ // Top-bar cart icon — opens the cart modal. The Asset Share
231
+ // Commons template renders this as a Semantic UI `<i class="big
232
+ // cart icon">` inside an `<a class="item">` link. We keep a
233
+ // data-attribute path in front for installations that follow
234
+ // newer ASC conventions.
235
+ cartOpenButton: USER_OVERRIDES.cartOpenButton
236
+ || '[data-asset-share-id="cart"], [data-asset-share-id="open-cart"], a[data-il-cart-open], a.item > i.cart.icon, a.item > i.big.cart.icon, .cmp-structure-user-menu i.cart.icon, .cmp-structure-user-menu i.big.cart.icon',
237
+ // Cart-modal "Share Cart" button — applies to the WHOLE cart.
238
+ // The DOM uses `data-asset-share-id="share-all"`.
239
+ cartShareButton: USER_OVERRIDES.cartShareButton
240
+ || '[data-asset-share-id="share-all"], [data-asset-share-id="shareCart"]',
241
+ // Cart-modal "Download Cart" button — initiates the cart-download
242
+ // flow (a second confirmation modal opens afterwards, then the
243
+ // actual binaries are produced and listed in the downloads modal).
244
+ cartDownloadButton: USER_OVERRIDES.cartDownloadButton
245
+ || '[data-asset-share-id="download-all"], [data-asset-share-id="downloadCart"]',
246
+ // Cart modal itself — used to scrape the cart contents at the
247
+ // moment Share Cart / Download Cart is clicked.
248
+ cartModal: USER_OVERRIDES.cartModal
249
+ || 'form.cmp-modal-cart, .cmp-modal-cart, [class*="cmp-modal-cart"]',
250
+ // Top-bar downloads icon — opens the downloads-list modal.
251
+ downloadsOpenButton: USER_OVERRIDES.downloadsOpenButton
252
+ || '[data-asset-share-id="downloads"], [data-asset-share-id="open-downloads"], a[data-il-downloads-open], a.item > i.download.icon, a.item > i.big.download.icon, .cmp-structure-user-menu i.download.icon, .cmp-structure-user-menu i.big.download.icon',
253
+ // Per-artifact download link inside the downloads modal. Anchors
254
+ // pointing at the AEM download-binaries endpoint with a
255
+ // `downloadId` query string. We deliberately accept ANY scheme /
256
+ // host the href might carry — the path is the stable identifier.
257
+ downloadBinaryLink: USER_OVERRIDES.downloadBinaryLink
258
+ || 'a[href*="downloadbinaries.json"], a[href*="downloadbinaries"][href*="downloadId="]',
259
+ // Per-download "remove from downloads" button. Carries the
260
+ // download UUID on `data-asset-share-download-id`.
261
+ downloadRemoveButton: USER_OVERRIDES.downloadRemoveButton
262
+ || '[data-asset-share-id="remove-from-downloads"], [data-asset-share-id="removeFromDownloads"]',
263
+ // ── Cart-Share modal (cmp-modal-share) ─────────────────
264
+ // The "Share Cart" button opens a SECOND modal that collects the
265
+ // recipient e-mails, the "Share Publicly" flag, and the optional
266
+ // start/expiry dates. The class anchor `cmp-modal-share` is
267
+ // stable across themes and the variant suffix
268
+ // `__wrapper--initial` covers the "fresh" state; we accept all
269
+ // wrapper variants because some themes also produce
270
+ // `__wrapper--success` / `__wrapper--error` after submission.
271
+ shareModal: USER_OVERRIDES.shareModal
272
+ || 'form.cmp-modal-share, form[class*="cmp-modal-share"], [class*="cmp-modal-share__wrapper"]',
273
+ // Comma-delimited e-mail recipients. The DOM uses
274
+ // <input type="email" multiple name="email">; the type+name
275
+ // pairing is the most stable anchor.
276
+ shareEmailInput: USER_OVERRIDES.shareEmailInput
277
+ || 'form.cmp-modal-share input[name="email"], form[class*="cmp-modal-share"] input[name="email"], [class*="cmp-modal-share"] input[type="email"][name="email"]',
278
+ // "Share Publicly" checkbox. ASC renders this without a data
279
+ // attribute, so we use the Semantic UI wrapper + child input
280
+ // pattern. The reader (below) also accepts a label-text match
281
+ // so a future template tweak that renames the wrapper won't
282
+ // silently dark-launch.
283
+ sharePublicCheckbox: USER_OVERRIDES.sharePublicCheckbox
284
+ || 'form.cmp-modal-share .ui.checkbox input[type="checkbox"], form[class*="cmp-modal-share"] .ui.checkbox input[type="checkbox"]',
285
+ // External-share date range. Only required when the public
286
+ // checkbox is ticked; the inputs use plain HTML id anchors that
287
+ // the ASC template controls.
288
+ shareStartDateInput: USER_OVERRIDES.shareStartDateInput
289
+ || 'form.cmp-modal-share #startDate, form[class*="cmp-modal-share"] #startDate, form.cmp-modal-share input[name="startDate"], form[class*="cmp-modal-share"] input[name="startDate"]',
290
+ shareExpiryDateInput: USER_OVERRIDES.shareExpiryDateInput
291
+ || 'form.cmp-modal-share #expiryDate, form[class*="cmp-modal-share"] #expiryDate, form.cmp-modal-share input[name="expiryDate"], form[class*="cmp-modal-share"] input[name="expiryDate"]',
292
+
293
+ // ── Asset Explorer (React) ─────────────────────────────
294
+ // /asset-explorer.html is a React SPA whose CSS Modules generate class
295
+ // names with a build-hash suffix that changes on every deploy
296
+ // (`_input_x72oj_15` → `_input_a1b2c_42` on the next build). Every
297
+ // selector below uses [class*="_<stable-prefix>_"] so it survives the
298
+ // hash refresh; we anchor on the human-stable prefix from the source
299
+ // CSS Module file name (`*.module.css`) which is reused across deploys.
300
+ assetExplorerRoot: USER_OVERRIDES.assetExplorerRoot
301
+ || '[class*="_directoryExplorer_"], .directory-explorer',
302
+ assetExplorerForm: USER_OVERRIDES.assetExplorerForm
303
+ || '[class*="_directoryExplorer_"] form, [class*="_form_"]',
304
+ assetExplorerSearchInput: USER_OVERRIDES.assetExplorerSearchInput
305
+ || '[class*="_directoryExplorer_"] input[type="text"], [class*="_inputWrapper_"] input, [class*="_input_"][type="text"]',
306
+ // Each row in the open Search Options modal. We identify "Semantic
307
+ // Search" vs "Fuzzy Search" by visible text, not by row index, in case
308
+ // the modal grows additional rows in a future release.
309
+ assetExplorerSearchOptionRow: USER_OVERRIDES.assetExplorerSearchOptionRow
310
+ || '[class*="_searchOptionRow_"], [class*="_searchOption_Row_"]',
311
+ // The right-side filter rail. Contains both the facet sections and
312
+ // the search-statistics tiles (`N DISPLAYED / N TOTAL / N MILLISECONDS`)
313
+ // at the bottom on aem-sit.publiciscolab.com.
314
+ assetExplorerFilterRail: USER_OVERRIDES.assetExplorerFilterRail
315
+ || '[class*="_filterWrapper_"], [class*="_wrapper_tqpgs"], [class*="_filtersPanel_"]',
316
+ // Stats container. Live builds use `_statContainer_<hash>` (note the
317
+ // CamelCase — `_stat_` with a trailing underscore would not match) so
318
+ // we look for that prefix first, then progressively widen to other
319
+ // common React naming patterns. The reader pairs `_value_` children
320
+ // with `_label_` siblings inside whichever container matches, and
321
+ // falls back to a regex parse over the filter rail's text content
322
+ // when no structured tiles can be located.
323
+ assetExplorerSearchStatistics: USER_OVERRIDES.assetExplorerSearchStatistics
324
+ || '[class*="_statContainer_"], [class*="_statsContainer_"], [class*="_statisticsContainer_"], [class*="_statistics_"], [class*="_searchStats_"], [class*="_resultStats_"], [class*="_filterWrapper_"]',
325
+ // Filter sections inside the rail. Each section has a heading
326
+ // ("ASSET TYPE", "MARKETING FUNCTION / INDUSTRY", ...) plus its
327
+ // selectable options. We anchor on `_filterSection_`, `_facet_`,
328
+ // `_filterGroup_` and similar React naming conventions, and fall
329
+ // through to `<section>` / `<fieldset>` for un-prefixed builds.
330
+ assetExplorerFilterSection: USER_OVERRIDES.assetExplorerFilterSection
331
+ || '[class*="_filterSection_"], [class*="_filterGroup_"], [class*="_facet_"], [class*="_category_"], [class*="_section_"], section, fieldset',
332
+ // Left-side folder tree inside the explorer's content panel.
333
+ // `_directoryTree_<hash>` wraps the entire tree, `_directoryTreeContent_`
334
+ // is the scrollable inner container. Inner items also carry the
335
+ // `_directoryTree_<another-hash>` prefix from a nested CSS Module so
336
+ // the selector is intentionally permissive.
337
+ assetExplorerFolderTree: USER_OVERRIDES.assetExplorerFolderTree
338
+ || '[class*="_directoryTreeContent_"], [class*="_directoryTreeWrapper_"], [class*="_directoryTree_"]'
339
+ };
340
+
341
+ // Visible-text regexes used as a last-resort fallback when none of the CSS
342
+ // selectors above match. Intentionally case-insensitive and tolerant of
343
+ // surrounding whitespace / punctuation.
344
+ var TEXT_PATTERNS = {
345
+ signIn: /\b(sign[- ]?in|log[- ]?in|login)\b/i,
346
+ lionSso: /\blion\s*login\b/i,
347
+ terms: /\bterms?\s*(?:&|and)\s*conditions?\b/i,
348
+ cart: /\badd\s*to\s*(?:cart|collection)\b/i,
349
+ share: /\bshare\b/i,
350
+ semantic: /\bsemantic\s*search\b/i,
351
+ fuzzy: /\bfuzzy\s*search\b/i,
352
+ // "What are you looking for?" placeholder anchors the search input on
353
+ // /asset-explorer.html when the CSS-Module prefix has not yet been
354
+ // covered by the [class*="_input_"] selectors (themed builds, etc.).
355
+ aeSearchPlaceholder: /\b(looking for|search assets?|find assets?)\b/i
356
+ };
357
+
358
+ // ASC network endpoints — matched against the request URL. Patterns are
359
+ // intentionally tolerant so they survive moves in the AEM content tree
360
+ // (the `/content/<tenant>/<region>/.../actions/...` prefix varies but the
361
+ // suffix `/actions/download/.../download.download-asset-renditions.zip`
362
+ // is the ASC convention).
363
+ var ENDPOINTS = {
364
+ // POST /content/.../actions/download/.../download.download-asset-renditions.zip
365
+ // body: timezone=…&path=<assetPath>&renditionName=<name>&:cq_csrf_token=…
366
+ download: /\/actions\/download(?:\/[^?\s]*)?\/download\.download-asset-renditions\.zip(?:[?#]|$)/,
367
+ // Best-effort cart/share — used to OPPORTUNISTICALLY capture network calls
368
+ // if the click hook missed them. Not authoritative.
369
+ addToCart: /\/(?:cart|asset-collection|asset-collections)(?:\/[^?\s]*)?\.(?:add|json|html)(?:[?#]|$)|\/bin\/asset-share-commons\/cart/i,
370
+ share: /\/(?:share|email-asset|send)(?:\/[^?\s]*)?\.(?:send|json|html)(?:[?#]|$)/i
371
+ };
372
+
373
+ // Granite endpoint that returns { authorizableId, id, ... } for the
374
+ // currently logged-in AEM user. Public; requires the session cookie.
375
+ var CURRENT_USER_ENDPOINT = '/libs/granite/security/currentuser.json';
376
+
377
+ // localStorage cache key for the resolved user. Bypasses the Granite
378
+ // fetch on subsequent page loads so user_id is attached to events
379
+ // synchronously (avoids the "first event after navigation lacks user_id"
380
+ // race during a roundtrip to /libs/granite/...).
381
+ var CACHE_KEY_USER = 'IL_COLAB_USER_ID';
382
+
383
+ // ─── 3. SDK access + safe wrappers ───────────────────────
384
+ function getApi() {
385
+ var raw = window.Infralytiqs;
386
+ if (!raw) return null;
387
+ return raw && raw.default && typeof raw.default.init === 'function' ? raw.default : raw;
388
+ }
389
+
390
+ function track(eventType, dims, metrics, subtype) {
391
+ var api = getApi();
392
+ if (!api) return;
393
+ try {
394
+ api.track(eventType, dims || {}, metrics || {}, subtype);
395
+ } catch (e) {
396
+ console.error('[IL-COLAB] track failed', eventType, e);
397
+ }
398
+ }
399
+
400
+ function identify(userId) {
401
+ var api = getApi();
402
+ if (!api) return;
403
+ try { api.identify(userId); } catch (e) { /* noop */ }
404
+ }
405
+
406
+ function flush() {
407
+ var api = getApi();
408
+ if (!api) return Promise.resolve();
409
+ try { return api.flush(); } catch (e) { return Promise.resolve(); }
410
+ }
411
+
412
+ // ─── 4. Browser-side enrichment ──────────────────────────
413
+ // Each event picks up these as `custom_dimensions` so reports can break
414
+ // traffic down by browser, screen, timezone, etc. without per-event work.
415
+ function detectBrowser() {
416
+ var ua = (navigator && navigator.userAgent) || '';
417
+ var rules = [
418
+ { name: 'Edge', re: /\bEdg(?:e|A|iOS)?\/([\d\.]+)/i },
419
+ { name: 'Opera', re: /\bOPR\/([\d\.]+)/i },
420
+ { name: 'Samsung', re: /\bSamsungBrowser\/([\d\.]+)/i },
421
+ { name: 'Firefox', re: /\bFirefox\/([\d\.]+)/i },
422
+ { name: 'Chrome', re: /\bChrom(?:e|ium)\/([\d\.]+)/i },
423
+ { name: 'Safari', re: /\bVersion\/([\d\.]+).*Safari\b/i },
424
+ { name: 'IE', re: /\bMSIE\s([\d\.]+)|\bTrident\/.*\brv:([\d\.]+)/i }
425
+ ];
426
+ for (var i = 0; i < rules.length; i++) {
427
+ var m = ua.match(rules[i].re);
428
+ if (m) {
429
+ return { name: rules[i].name, version: (m[1] || m[2] || '').split('.')[0] };
430
+ }
431
+ }
432
+ return { name: 'Other', version: '' };
433
+ }
434
+
435
+ function safeStr(v) {
436
+ return (v === undefined || v === null) ? '' : String(v);
437
+ }
438
+
439
+ function getViewportSize() {
440
+ try {
441
+ var w = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || 0;
442
+ var h = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || 0;
443
+ return w && h ? (w + 'x' + h) : '';
444
+ } catch (e) { return ''; }
445
+ }
446
+
447
+ function getScreenResolution() {
448
+ try {
449
+ var s = window.screen || {};
450
+ var w = s.width || 0;
451
+ var h = s.height || 0;
452
+ return w && h ? (w + 'x' + h) : '';
453
+ } catch (e) { return ''; }
454
+ }
455
+
456
+ function getIanaTimezone() {
457
+ try {
458
+ if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
459
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || '';
460
+ }
461
+ } catch (e) { /* noop */ }
462
+ return '';
463
+ }
464
+
465
+ function getColorScheme() {
466
+ try {
467
+ if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';
468
+ if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) return 'light';
469
+ } catch (e) { /* noop */ }
470
+ return '';
471
+ }
472
+
473
+ function buildEnrichmentDims() {
474
+ var browser = detectBrowser();
475
+ var dims = {
476
+ client_app: 'publicis-ps',
477
+ client_origin: location.origin,
478
+ client_tenant: TENANT_ID,
479
+ client_site: SITE_ID,
480
+ browser_name: browser.name,
481
+ browser_version: browser.version,
482
+ viewport_size: getViewportSize(),
483
+ screen_resolution: getScreenResolution(),
484
+ timezone_iana: getIanaTimezone(),
485
+ language_full: safeStr(navigator && navigator.language),
486
+ color_scheme: getColorScheme()
487
+ };
488
+ var clean = {};
489
+ for (var k in dims) {
490
+ if (dims.hasOwnProperty(k) && dims[k] !== '' && dims[k] !== undefined) {
491
+ clean[k] = dims[k];
492
+ }
493
+ }
494
+ return clean;
495
+ }
496
+
497
+ // ─── 5. SDK initialization ───────────────────────────────
498
+ function initSdk() {
499
+ var api = getApi();
500
+ if (!api) return false;
501
+ try {
502
+ api.init({
503
+ serverUrl: SERVER_URL,
504
+ tenantId: TENANT_ID,
505
+ siteId: SITE_ID,
506
+ dbName: DB_NAME,
507
+ debug: !!window.IL_DEBUG,
508
+ captureLocation: window.IL_CAPTURE_LOCATION === true,
509
+ globalDimensions: buildEnrichmentDims()
510
+ });
511
+ } catch (e) {
512
+ console.error('[IL-COLAB] init failed', e);
513
+ return false;
514
+ }
515
+ return true;
516
+ }
517
+
518
+ // ─── 6. DOM + URL helpers ────────────────────────────────
519
+ function $(selectorList) {
520
+ if (!selectorList) return null;
521
+ try {
522
+ return document.querySelector(selectorList);
523
+ } catch (e) {
524
+ return null;
525
+ }
526
+ }
527
+
528
+ function visibleText(el) {
529
+ if (!el) return '';
530
+ var t = el.textContent || el.value || el.getAttribute('aria-label') || '';
531
+ return t.replace(/\s+/g, ' ').trim();
532
+ }
533
+
534
+ function closestMatchByText(root, tag, pattern) {
535
+ var nodes = root.querySelectorAll(tag);
536
+ for (var i = 0; i < nodes.length; i++) {
537
+ if (pattern.test(visibleText(nodes[i]))) {
538
+ return nodes[i];
539
+ }
540
+ }
541
+ return null;
542
+ }
543
+
544
+ /**
545
+ * Login-page heuristic: explicit URL hint, or DOM signals (password input
546
+ * inside a form). Anything that matches counts — false positives are
547
+ * harmless (just adds a `login_page` subtype to the page-view).
548
+ */
549
+ function isLoginPage() {
550
+ var href = (location.pathname + location.search + location.hash).toLowerCase();
551
+ if (/(^|\/)login(\.|\/|$|\?)/.test(href)) return true;
552
+ if (/signin/.test(href)) return true;
553
+ if (document.querySelector('input[type="password"]')) return true;
554
+ return false;
555
+ }
556
+
557
+ /**
558
+ * Parses `location.search` into a flat key→value (or key→string[]) map,
559
+ * URL-decoding both keys and values and tolerating duplicate keys.
560
+ */
561
+ function parseQuery() {
562
+ var out = {};
563
+ var qs = (location.search || '').replace(/^\?/, '');
564
+ if (!qs) return out;
565
+ var parts = qs.split('&');
566
+ for (var i = 0; i < parts.length; i++) {
567
+ if (!parts[i]) continue;
568
+ var eqIdx = parts[i].indexOf('=');
569
+ var k = eqIdx >= 0 ? parts[i].slice(0, eqIdx) : parts[i];
570
+ var v = eqIdx >= 0 ? parts[i].slice(eqIdx + 1) : '';
571
+ try { k = decodeURIComponent(k.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
572
+ try { v = decodeURIComponent(v.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
573
+ if (out[k] === undefined) out[k] = v;
574
+ else if (Array.isArray(out[k])) out[k].push(v);
575
+ else out[k] = [out[k], v];
576
+ }
577
+ return out;
578
+ }
579
+
580
+ /**
581
+ * Parses a form-encoded body (POST request) into a flat map. Accepts a
582
+ * raw string, a FormData, or a URLSearchParams. Returns {} on any error.
583
+ */
584
+ function parseFormBody(body) {
585
+ var out = {};
586
+ if (!body) return out;
587
+ try {
588
+ if (typeof FormData !== 'undefined' && body instanceof FormData) {
589
+ body.forEach(function (v, k) { if (!(k in out)) out[k] = String(v); });
590
+ return out;
591
+ }
592
+ if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
593
+ body.forEach(function (v, k) { if (!(k in out)) out[k] = String(v); });
594
+ return out;
595
+ }
596
+ } catch (e) { /* fall through to string parse */ }
597
+
598
+ var s = typeof body === 'string' ? body : '';
599
+ if (!s) return out;
600
+ var parts = s.split('&');
601
+ for (var i = 0; i < parts.length; i++) {
602
+ var p = parts[i];
603
+ if (!p) continue;
604
+ var eqIdx = p.indexOf('=');
605
+ var k = eqIdx >= 0 ? p.slice(0, eqIdx) : p;
606
+ var v = eqIdx >= 0 ? p.slice(eqIdx + 1) : '';
607
+ try { k = decodeURIComponent(k.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
608
+ try { v = decodeURIComponent(v.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
609
+ if (!(k in out)) out[k] = v;
610
+ }
611
+ return out;
612
+ }
613
+
614
+ /**
615
+ * ASC encodes search-rail filters into the URL using indexed groups, e.g.:
616
+ * 0_group.propertyvalues.property = jcr:content/metadata/ps:assettype
617
+ * 0_group.propertyvalues.operation = equals
618
+ * 0_group.propertyvalues.0_values = Image
619
+ * 1_group.propertyvalues.property = ...
620
+ *
621
+ * This helper walks the parsed query string, buckets params by their
622
+ * `<idx>_group.` prefix, and returns a normalized array of
623
+ * { group, property, operation, values: [...] }
624
+ * suitable for JSON-serializing into a single dimension.
625
+ */
626
+ function extractFilters(q) {
627
+ var groups = {};
628
+ for (var k in q) {
629
+ if (!q.hasOwnProperty(k)) continue;
630
+ var m = k.match(/^(\d+)_group\.(.+)$/);
631
+ if (!m) continue;
632
+ var idx = m[1];
633
+ var rest = m[2];
634
+ if (!groups[idx]) groups[idx] = {};
635
+ groups[idx][rest] = q[k];
636
+ }
637
+ var list = [];
638
+ var keys = Object.keys(groups).sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); });
639
+ for (var i = 0; i < keys.length; i++) {
640
+ var g = groups[keys[i]];
641
+ var prop = g['propertyvalues.property'] || g['property.property'] || '';
642
+ var op = g['propertyvalues.operation'] || g['property.operation'] || 'equals';
643
+ var values = [];
644
+ for (var p in g) {
645
+ if (!g.hasOwnProperty(p)) continue;
646
+ // `propertyvalues.0_values`, `propertyvalues.1_values`, ...
647
+ // or `property.0_value`, or singular `value` / `values`.
648
+ if (/^propertyvalues\.\d+_values$|^property\.\d+_value$|^propertyvalues\.values?$|^property\.values?$/.test(p)) {
649
+ var raw = g[p];
650
+ if (Array.isArray(raw)) {
651
+ for (var j = 0; j < raw.length; j++) values.push(raw[j]);
652
+ } else {
653
+ values.push(raw);
654
+ }
655
+ }
656
+ }
657
+ if (prop || values.length) {
658
+ list.push({ group: keys[i], property: prop, operation: op, values: values });
659
+ }
660
+ }
661
+ return list;
662
+ }
663
+
664
+ /**
665
+ * Locates the ASC right-rail filter container.
666
+ *
667
+ * The visible filter sections (ASSET TYPE, MARKETING FUNCTION / INDUSTRY,
668
+ * APPLICATION & USE, ORIGIN, ASSET USAGE RIGHTS, LANGUAGE / REGION, YEAR,
669
+ * LAST MODIFIED, CREATED, …) live inside this container along with the
670
+ * hidden inputs that ASC's predicate components use to encode the
671
+ * `<idx>_group.propertyvalues.property` URL params.
672
+ */
673
+ function findFilterRail() {
674
+ return $(SELECTORS.filterRail);
675
+ }
676
+
677
+ function cleanText(s) {
678
+ return (s == null ? '' : String(s)).replace(/\s+/g, ' ').trim();
679
+ }
680
+
681
+ /**
682
+ * Builds a property → human-readable label map by scanning the rail for
683
+ * predicate blocks. Each ASC predicate (`cmp-predicate`) carries a hidden
684
+ * `…propertyvalues.property` input and a visible heading. We walk up from
685
+ * the hidden input until we find the predicate block, then take its
686
+ * heading text as the label.
687
+ *
688
+ * Returns e.g.
689
+ * { 'jcr:content/metadata/ps:assettype': 'ASSET TYPE',
690
+ * 'jcr:content/metadata/cq:tags': 'MARKETING FUNCTION / INDUSTRY',
691
+ * ... }
692
+ */
693
+ function buildPropertyLabelMap(rail) {
694
+ var map = {};
695
+ if (!rail || !rail.querySelectorAll) return map;
696
+ var propInputs;
697
+ try {
698
+ // Hidden inputs whose name ends with `.property` or `.propertyvalues.property`.
699
+ propInputs = rail.querySelectorAll(
700
+ 'input[name$=".property"], ' +
701
+ 'input[name$=".propertyvalues.property"], ' +
702
+ '[data-cmp-predicate-property]'
703
+ );
704
+ } catch (e) { return map; }
705
+
706
+ for (var i = 0; i < propInputs.length; i++) {
707
+ var node = propInputs[i];
708
+ var prop = (node.tagName === 'INPUT' ? node.value : node.getAttribute('data-cmp-predicate-property')) || '';
709
+ prop = String(prop);
710
+ if (!prop || map[prop]) continue;
711
+
712
+ var section = (node.closest && node.closest(
713
+ '.cmp-predicate, [data-cmp-is="predicate"], .predicate, ' +
714
+ '.cmp-search-predicate, .filter-section, section, fieldset'
715
+ )) || node.parentNode;
716
+
717
+ // Walk up looking for a section heading. Stop at the rail boundary
718
+ // so we don't accidentally pick up the entire panel's outer label.
719
+ while (section && section !== rail && section.nodeType === 1) {
720
+ var heading = section.querySelector(
721
+ '.cmp-predicate__title, [data-cmp-hook-predicate-title], ' +
722
+ '[data-predicate-title], legend, h2, h3, h4, h5, ' +
723
+ '.predicate-title, .filter-title'
724
+ );
725
+ if (heading && cleanText(heading.textContent)) {
726
+ map[prop] = cleanText(heading.textContent);
727
+ break;
728
+ }
729
+ section = section.parentNode;
730
+ }
731
+ }
732
+ return map;
733
+ }
734
+
735
+ /**
736
+ * Scans the rail for currently-selected filter inputs and groups them by
737
+ * the visible section heading they live under. This is a belt-and-braces
738
+ * capture: it picks up predicates whose state lives only in the DOM (and
739
+ * isn't visible in the URL) — and it lets us emit a clean
740
+ * [{ name: "ASSET TYPE", values: ["Image"] }, ...]
741
+ * even when the property→label map didn't resolve.
742
+ */
743
+ function scanRailSelectedFilters(rail) {
744
+ if (!rail || !rail.querySelectorAll) return [];
745
+ var groupsByLabel = {};
746
+
747
+ var selected;
748
+ try {
749
+ selected = rail.querySelectorAll(
750
+ 'input[type="checkbox"]:checked, ' +
751
+ 'input[type="radio"]:checked, ' +
752
+ '[aria-checked="true"], ' +
753
+ '[data-selected="true"], ' +
754
+ '.is-selected:not(.disabled), ' +
755
+ '.cmp-predicate__option--selected'
756
+ );
757
+ } catch (e) { return []; }
758
+
759
+ for (var i = 0; i < selected.length; i++) {
760
+ var n = selected[i];
761
+ // Hidden, submit, and button inputs are infrastructure, not selections.
762
+ if (n.type === 'hidden' || n.type === 'submit' || n.type === 'button') continue;
763
+
764
+ // Prefer the visible label associated with the input.
765
+ var value = '';
766
+ try {
767
+ if (n.labels && n.labels.length) value = cleanText(n.labels[0].textContent);
768
+ } catch (e) { /* `labels` not supported */ }
769
+ if (!value) {
770
+ var labelEl = (n.closest && n.closest('label')) || null;
771
+ if (labelEl) value = cleanText(labelEl.textContent);
772
+ }
773
+ if (!value) value = cleanText(n.value);
774
+ if (!value || value.toLowerCase() === 'on') continue;
775
+
776
+ // Walk up to the predicate section + its heading.
777
+ var label = '';
778
+ var section = (n.closest && n.closest(
779
+ '.cmp-predicate, [data-cmp-is="predicate"], .predicate, ' +
780
+ '.cmp-search-predicate, .filter-section, section, fieldset'
781
+ )) || null;
782
+ var cur = section;
783
+ while (cur && cur !== rail && cur.nodeType === 1) {
784
+ var heading = cur.querySelector(
785
+ '.cmp-predicate__title, [data-cmp-hook-predicate-title], ' +
786
+ '[data-predicate-title], legend, h2, h3, h4, h5, ' +
787
+ '.predicate-title, .filter-title'
788
+ );
789
+ if (heading && cleanText(heading.textContent)) {
790
+ label = cleanText(heading.textContent);
791
+ break;
792
+ }
793
+ cur = cur.parentNode;
794
+ }
795
+ if (!label) label = 'filter';
796
+
797
+ if (!groupsByLabel[label]) groupsByLabel[label] = [];
798
+ if (groupsByLabel[label].indexOf(value) === -1) groupsByLabel[label].push(value);
799
+ }
800
+
801
+ var out = [];
802
+ for (var k in groupsByLabel) {
803
+ if (groupsByLabel.hasOwnProperty(k)) out.push({ name: k, values: groupsByLabel[k] });
804
+ }
805
+ return out;
806
+ }
807
+
808
+ /**
809
+ * Parses a stat value text into a Float64. Tolerates thousand separators,
810
+ * whitespace, and trailing unit suffixes like "ms", "s", "seconds".
811
+ * Returns null when the text doesn't contain a usable number.
812
+ */
813
+ function parseStatNumber(txt) {
814
+ if (txt == null) return null;
815
+ var s = String(txt).replace(/[\s,]/g, '');
816
+ var m = s.match(/-?\d+(?:\.\d+)?/);
817
+ if (!m) return null;
818
+ var n = parseFloat(m[0]);
819
+ return isFinite(n) ? n : null;
820
+ }
821
+
822
+ /**
823
+ * Classifies a stat-widget label to one of the metrics we surface.
824
+ *
825
+ * Observed ASC label variants (verified against `aem-sit.publiciscolab.com`
826
+ * search-stats raw_json captured 2026-05-28):
827
+ * "Displayed" → result_displayed (count shown on current page)
828
+ * "Total" → result_total (total assets matched)
829
+ * "Milliseconds" → search_time_ms (server-side query latency)
830
+ * And the wider OOTB ASC family:
831
+ * "Time", "Time (ms)", "Search Time", "Elapsed", "Duration",
832
+ * "Latency", "Response" → search_time_ms
833
+ * "Seconds" → search_time_ms (×1000 → ms)
834
+ * "Assets", "Results", "Hits", "Matches", "Found", "Count"
835
+ * → result_total
836
+ * "Pages" → result_pages
837
+ * "Showing", "Shown" → result_displayed (alternate displayed labels)
838
+ *
839
+ * Returns null for unrecognized labels — the caller must not invent an
840
+ * attribution from position alone unless EVERY label in the widget came
841
+ * back null (see readSearchStatistics() pass 2).
842
+ */
843
+ function classifyStatLabel(label) {
844
+ var s = String(label || '').toLowerCase();
845
+ if (!s) return null;
846
+ if (/\b(millisecond|msec|\bms\b)/.test(s)) return { key: 'time_ms', unit: 'ms' };
847
+ if (/\b(second|\bs\b)\b/.test(s)) return { key: 'time_ms', unit: 's' };
848
+ if (/\b(time|elapsed|duration|latency|response)\b/.test(s))
849
+ return { key: 'time_ms', unit: 'ms' };
850
+ if (/\b(displayed|showing|shown|visible)\b/.test(s))
851
+ return { key: 'displayed', unit: '' };
852
+ if (/\b(asset|result|hit|match|found|total|count)\b/.test(s))
853
+ return { key: 'total', unit: '' };
854
+ if (/\bpages?\b/.test(s)) return { key: 'pages', unit: '' };
855
+ return null;
856
+ }
857
+
858
+ /**
859
+ * Reads the ASC `cmp-search-statistics` widget into a normalized shape:
860
+ * { container,
861
+ * stats: {
862
+ * time_ms, total, pages,
863
+ * raw, // [{ idx, label, value }] in DOM order — diagnostic
864
+ * claimed // Set<idx> of blocks already attributed to a metric
865
+ * }
866
+ * }
867
+ * `time_ms`, `total`, `pages` are Float64s (or null when not displayed);
868
+ * `raw` is an ordered list so we can inspect classifier mistakes from
869
+ * the back-end (we JSON-serialize it onto every search_executed event
870
+ * as `custom_dimensions.search_stats_raw_json`). Returns
871
+ * `{ container: <el|null>, stats: null }` when the widget hasn't been
872
+ * mounted yet OR has no populated `.value` cells.
873
+ *
874
+ * Positional fallback (1st=total, 2nd=time_ms, 3rd=pages) only fires
875
+ * for blocks NOT already claimed by the label classifier — so a single
876
+ * cell can never be attributed to two metrics at once.
877
+ */
878
+ function readSearchStatistics() {
879
+ var container = $(SELECTORS.searchStatistics);
880
+ if (!container || !container.querySelectorAll) {
881
+ return { container: null, stats: null };
882
+ }
883
+
884
+ // First-pass: gather (index, label, value) tuples from every leaf
885
+ // `.statistic` block. We deliberately exclude the outer `.statistics`
886
+ // wrapper that `[class*="statistic"]` would otherwise match.
887
+ var statBlocks = container.querySelectorAll(
888
+ '.statistic, [class*="statistic"]:not(.statistics)'
889
+ );
890
+ var rows = [];
891
+ for (var i = 0; i < statBlocks.length; i++) {
892
+ var block = statBlocks[i];
893
+ if (block.querySelector && block.querySelector('.statistic')) continue;
894
+
895
+ var labelEl = block.querySelector('.label, [class*="label"]');
896
+ var valueEl = block.querySelector('.value, [class*="value"]');
897
+ if (!valueEl) continue;
898
+
899
+ var labelText = labelEl ? cleanText(labelEl.textContent) : '';
900
+ var rawText = cleanText(valueEl.textContent);
901
+ var n = parseStatNumber(rawText);
902
+ rows.push({ idx: rows.length, label: labelText, valueText: rawText, value: n });
903
+ }
904
+ if (!rows.length || !rows.some(function (r) { return r.value !== null; })) {
905
+ return { container: container, stats: null };
906
+ }
907
+
908
+ var stats = {
909
+ time_ms: null,
910
+ total: null,
911
+ pages: null,
912
+ displayed: null,
913
+ raw: rows.map(function (r) { return { idx: r.idx, label: r.label, value: r.valueText }; })
914
+ };
915
+ var claimed = {};
916
+ var anyClassified = false;
917
+
918
+ // Pass 1: label-driven classification — authoritative whenever the
919
+ // label is recognized. Skips blocks whose `.value` was empty.
920
+ for (var k = 0; k < rows.length; k++) {
921
+ var r = rows[k];
922
+ if (r.value === null) continue;
923
+ var c = classifyStatLabel(r.label);
924
+ if (!c) continue;
925
+ anyClassified = true;
926
+ // First match wins for each metric, so a duplicate label (rare) on
927
+ // a later block doesn't clobber an earlier one.
928
+ if (c.key === 'time_ms' && stats.time_ms === null) {
929
+ // Convert seconds → ms when label explicitly says seconds, so
930
+ // the metric column is always milliseconds regardless of label.
931
+ stats.time_ms = c.unit === 's' ? r.value * 1000 : r.value;
932
+ claimed[r.idx] = true;
933
+ } else if (c.key === 'total' && stats.total === null) {
934
+ stats.total = r.value;
935
+ claimed[r.idx] = true;
936
+ } else if (c.key === 'pages' && stats.pages === null) {
937
+ stats.pages = r.value;
938
+ claimed[r.idx] = true;
939
+ } else if (c.key === 'displayed' && stats.displayed === null) {
940
+ stats.displayed = r.value;
941
+ claimed[r.idx] = true;
942
+ }
943
+ }
944
+
945
+ // Pass 2: positional fallback. We deliberately keep this STRICT — it
946
+ // only fires when *no* label in the widget was recognized at all (a
947
+ // re-themed deployment with non-English / custom labels). Otherwise we
948
+ // trust the labels we DID recognize and leave any unclassified blocks
949
+ // out of the event, so an unrelated tile (e.g. "Displayed") can never
950
+ // bleed into `result_pages` or `search_time_ms`.
951
+ if (!anyClassified) {
952
+ // Stock ASC OOTB column order: 1) total assets, 2) time (ms), 3) pages.
953
+ if (rows[0] && rows[0].value !== null) {
954
+ stats.total = rows[0].value;
955
+ claimed[rows[0].idx] = true;
956
+ }
957
+ if (rows[1] && rows[1].value !== null) {
958
+ stats.time_ms = rows[1].value;
959
+ claimed[rows[1].idx] = true;
960
+ }
961
+ if (rows[2] && rows[2].value !== null) {
962
+ stats.pages = rows[2].value;
963
+ claimed[rows[2].idx] = true;
964
+ }
965
+ }
966
+
967
+ return { container: container, stats: stats };
968
+ }
969
+
970
+ /**
971
+ * Waits for a search-statistics widget to be populated for the CURRENT
972
+ * search and then invokes `cb(stats)`. Falls back to `cb(stats|null)`
973
+ * after `timeoutMs` (default 3000) so the search_executed event is never
974
+ * silenced indefinitely just because the widget didn't show up.
975
+ *
976
+ * `reader` is the page-specific stats-reader function returning the
977
+ * shared `{ container, stats: { time_ms, total, pages, displayed, raw } }`
978
+ * shape — `readSearchStatistics` for ASC, `readAssetExplorerSearchStatistics`
979
+ * for the React-based explorer. This way the wait/observe/baseline logic
980
+ * is written once and both contexts get the same race-safety guarantees.
981
+ *
982
+ * On the first invocation per page load the currently-displayed value is
983
+ * trusted (server-side rendered for the URL we just loaded). On every
984
+ * subsequent invocation — i.e. a pushState navigation — we cache the
985
+ * pre-call snapshot and require a MutationObserver hit AND a value
986
+ * difference vs the snapshot before resolving. That avoids attributing
987
+ * the previous search's "Time" reading to the new search.
988
+ *
989
+ * Returns a `cancel()` function so a fresh search that fires before the
990
+ * previous wait completes can abort the previous wait without leaving
991
+ * dangling observers.
992
+ */
993
+ function waitForSearchStats(reader, timeoutMs, cb) {
994
+ var read = typeof reader === 'function' ? reader : readSearchStatistics;
995
+ var done = false;
996
+ var mo = null;
997
+ var timer = null;
998
+
999
+ function teardown() {
1000
+ if (mo) { try { mo.disconnect(); } catch (e) {} mo = null; }
1001
+ if (timer) { clearTimeout(timer); timer = null; }
1002
+ }
1003
+
1004
+ function finish(stats) {
1005
+ if (done) return;
1006
+ done = true;
1007
+ teardown();
1008
+ try { cb(stats); } catch (e) { /* swallow */ }
1009
+ }
1010
+
1011
+ var initial = read();
1012
+ var baselineTime = initial.stats ? initial.stats.time_ms : null;
1013
+ var baselineTot = initial.stats ? initial.stats.total : null;
1014
+
1015
+ // First search of the page: the widget's current value WAS rendered for
1016
+ // this URL (either SSR or by the SDK's earlier auto-init pass), so we
1017
+ // can fire immediately.
1018
+ if (__searchFireCount === 0 && initial.stats && baselineTime !== null) {
1019
+ finish(initial.stats);
1020
+ return function noopCancel() {};
1021
+ }
1022
+
1023
+ var observeRoot = initial.container || document.body || document.documentElement;
1024
+
1025
+ timer = setTimeout(function () {
1026
+ // Hard timeout: fire with whatever the widget is showing right now,
1027
+ // even if it didn't change from the baseline. Better to record the
1028
+ // search with no time than to drop it.
1029
+ var late = read();
1030
+ finish(late.stats || null);
1031
+ }, timeoutMs || 3000);
1032
+
1033
+ if (typeof MutationObserver === 'function' && observeRoot) {
1034
+ try {
1035
+ mo = new MutationObserver(function () {
1036
+ var probe = read();
1037
+ if (!probe.stats || probe.stats.time_ms === null) return;
1038
+ // Require at least one of the two key cells to have changed vs
1039
+ // baseline. Cards, pagination, and skeleton loaders also mutate
1040
+ // the DOM while the search XHR is in flight — we don't want any
1041
+ // of those to count as "stats ready".
1042
+ if (probe.stats.time_ms !== baselineTime || probe.stats.total !== baselineTot) {
1043
+ finish(probe.stats);
1044
+ }
1045
+ });
1046
+ mo.observe(observeRoot, {
1047
+ childList: true,
1048
+ subtree: true,
1049
+ characterData: true
1050
+ });
1051
+ } catch (e) { /* fall back to timer-only path */ }
1052
+ }
1053
+
1054
+ return function cancel() {
1055
+ if (done) return;
1056
+ done = true;
1057
+ teardown();
1058
+ };
1059
+ }
1060
+
1061
+ /**
1062
+ * Pretty-fallback when the property→label map didn't have an entry. Picks
1063
+ * the most meaningful trailing token of a JCR-style path so reports don't
1064
+ * have to render `jcr:content/metadata/ps:assettype` unaltered.
1065
+ *
1066
+ * jcr:content/metadata/ps:assettype → ps:assettype
1067
+ * jcr:content/metadata/cq:tags → cq:tags
1068
+ * jcr:content/jcr:lastModified → jcr:lastModified
1069
+ */
1070
+ function deriveFallbackName(prop) {
1071
+ if (!prop) return '';
1072
+ var s = String(prop);
1073
+ var slash = s.lastIndexOf('/');
1074
+ return slash >= 0 ? s.slice(slash + 1) : s;
1075
+ }
1076
+
1077
+ /**
1078
+ * Detects an asset-preview / details URL anywhere in the path. Matches
1079
+ * both layouts we've observed on aem-sit.publiciscolab.com:
1080
+ *
1081
+ * ASC (root-level):
1082
+ * /details/image.html/content/dam/ps/branded-assets/Rolex-1.jpeg
1083
+ *
1084
+ * Asset Explorer (nested under the AEM page path):
1085
+ * /content/ps/global/us/en/home/asset-explorer/details/image.html/content/dam/ps/brand-toolkit/bmwi4_029.jpg
1086
+ *
1087
+ * We deliberately require the captured `assetPath` to start with
1088
+ * `/content/`, so a page accidentally named `details.html` somewhere else
1089
+ * in the tree can't match. Returns null when the URL isn't a details
1090
+ * page in either layout.
1091
+ */
1092
+ function detectDetailsAssetPath() {
1093
+ var m = location.pathname.match(/\/details\/([^/]+)\.html(\/content\/.+)$/);
1094
+ if (!m) return null;
1095
+ return { assetType: m[1], assetPath: m[2] };
1096
+ }
1097
+
1098
+ /**
1099
+ * Walks up from a clicked element looking for a DAM asset path:
1100
+ * 1. `data-asset-path`, `data-asset`, `data-cmp-asset`, or
1101
+ * `data-foundation-collection-item-id` carrying `/content/dam/…`.
1102
+ * 2. An ancestor `<a href="/details/…">` from which we extract the path.
1103
+ * Returns '' if nothing matches.
1104
+ */
1105
+ function extractAssetPathFromEl(el) {
1106
+ var cur = el;
1107
+ while (cur && cur !== document.body && cur.nodeType === 1) {
1108
+ // `data-asset-share-asset` is the ASC convention used by the
1109
+ // explorer tiles (`<button data-asset-share-id="add-to-cart"
1110
+ // data-asset-share-asset="/content/dam/...">`). Check it first so
1111
+ // we don't accidentally walk up to a card-level fallback when the
1112
+ // button itself already carries the precise asset.
1113
+ var dataAttrs = [
1114
+ 'data-asset-share-asset',
1115
+ 'data-asset-path',
1116
+ 'data-asset',
1117
+ 'data-cmp-asset',
1118
+ 'data-foundation-collection-item-id',
1119
+ 'data-path'
1120
+ ];
1121
+ for (var i = 0; i < dataAttrs.length; i++) {
1122
+ var v = cur.getAttribute && cur.getAttribute(dataAttrs[i]);
1123
+ if (v && /^\/content\/dam\//.test(v)) return v;
1124
+ }
1125
+ var href = (cur.getAttribute && (cur.getAttribute('data-href') || cur.getAttribute('href'))) || '';
1126
+ if (href) {
1127
+ var mm = href.match(/\/details\/[^/]+\.html(\/content\/dam\/[^\s?#]+)/);
1128
+ if (mm) return mm[1];
1129
+ }
1130
+ cur = cur.parentNode;
1131
+ }
1132
+ return '';
1133
+ }
1134
+
1135
+ /**
1136
+ * Parses a URL or query-string fragment into a plain object. Trivial
1137
+ * shim around `URLSearchParams` that survives IE / older Safari where
1138
+ * the constructor isn't available. Used to pull `downloadId` and
1139
+ * `artifactId` from the asset-download anchor href.
1140
+ */
1141
+ function parseUrlParams(href) {
1142
+ var out = {};
1143
+ if (!href) return out;
1144
+ var q = String(href);
1145
+ var hashIdx = q.indexOf('#');
1146
+ if (hashIdx >= 0) q = q.slice(0, hashIdx);
1147
+ var qIdx = q.indexOf('?');
1148
+ if (qIdx < 0) return out;
1149
+ var pairs = q.slice(qIdx + 1).split('&');
1150
+ for (var i = 0; i < pairs.length; i++) {
1151
+ var kv = pairs[i].split('=');
1152
+ if (!kv[0]) continue;
1153
+ var k, v;
1154
+ try { k = decodeURIComponent(kv[0].replace(/\+/g, ' ')); } catch (e) { k = kv[0]; }
1155
+ try { v = kv.length > 1 ? decodeURIComponent(kv[1].replace(/\+/g, ' ')) : ''; } catch (e) { v = kv[1] || ''; }
1156
+ out[k] = v;
1157
+ }
1158
+ return out;
1159
+ }
1160
+
1161
+ /**
1162
+ * Reads the current contents of the ASC cart modal (if open). Returns
1163
+ * an array of unique `/content/dam/...` paths discovered via, in
1164
+ * order:
1165
+ *
1166
+ * 1. `data-asset-share-asset` attributes (preferred — the cart
1167
+ * template renders these on each row),
1168
+ * 2. `data-asset-path` / `data-asset` / `data-cmp-asset` as
1169
+ * fallbacks for older / themed ASC builds,
1170
+ * 3. `<a href="/.../details/<type>.html/content/dam/...">` links,
1171
+ * 4. hidden `<input name="path">` form fields (legacy ASC).
1172
+ *
1173
+ * Returns `[]` when the modal isn't currently in the DOM — the
1174
+ * caller can attach an empty `cart_asset_paths_json=""` and a
1175
+ * `cart_item_count=0` so reports can distinguish "no cart open" from
1176
+ * "cart open but empty".
1177
+ */
1178
+ function readCartContents() {
1179
+ var modal = document.querySelector(SELECTORS.cartModal);
1180
+ if (!modal) return [];
1181
+ var paths = [];
1182
+ var seen = {};
1183
+ function add(p) {
1184
+ if (!p) return;
1185
+ if (!/^\/content\/dam\//.test(p)) return;
1186
+ if (seen[p]) return;
1187
+ seen[p] = true;
1188
+ paths.push(p);
1189
+ }
1190
+ var attrAttempts = ['data-asset-share-asset', 'data-asset-path', 'data-asset', 'data-cmp-asset'];
1191
+ for (var a = 0; a < attrAttempts.length; a++) {
1192
+ var els = modal.querySelectorAll('[' + attrAttempts[a] + ']');
1193
+ for (var i = 0; i < els.length; i++) {
1194
+ add(els[i].getAttribute(attrAttempts[a]));
1195
+ }
1196
+ }
1197
+ var anchors = modal.querySelectorAll('a[href*="/details/"]');
1198
+ for (var j = 0; j < anchors.length; j++) {
1199
+ var href = anchors[j].getAttribute('href') || '';
1200
+ var m = href.match(/\/details\/[^/]+\.html(\/content\/dam\/[^\s?#]+)/);
1201
+ if (m) add(m[1]);
1202
+ }
1203
+ var inputs = modal.querySelectorAll('input[name="path"], input[name="paths"]');
1204
+ for (var k = 0; k < inputs.length; k++) {
1205
+ add(inputs[k].value);
1206
+ }
1207
+ return paths;
1208
+ }
1209
+
1210
+ // ─── 7. User identity resolution ─────────────────────────
1211
+ function readCachedUserId() {
1212
+ try { return localStorage.getItem(CACHE_KEY_USER) || ''; } catch (e) { return ''; }
1213
+ }
1214
+ function writeCachedUserId(u) {
1215
+ try { localStorage.setItem(CACHE_KEY_USER, String(u || '')); } catch (e) { /* private mode etc. */ }
1216
+ }
1217
+
1218
+ /**
1219
+ * Resolves the AEM authorizable id of the currently logged-in user.
1220
+ * Resolution order:
1221
+ * 1. host-page-provided `window.IL_COLAB_USER_RESOLVER` (sync string or Promise)
1222
+ * 2. `<meta name="cq:user" | "user" | "user-id">`
1223
+ * 3. `/libs/granite/security/currentuser.json` (Granite endpoint)
1224
+ *
1225
+ * Calls `cb('')` for anonymous sessions; never throws.
1226
+ *
1227
+ * We deliberately use the unwrapped (pre-install) `fetch` so that our
1228
+ * own identity probe doesn't echo through the network interception
1229
+ * installed below for asset_download.
1230
+ */
1231
+ var ORIG_FETCH = (typeof window.fetch === 'function') ? window.fetch.bind(window) : null;
1232
+
1233
+ function resolveCurrentUser(cb) {
1234
+ try {
1235
+ if (typeof window.IL_COLAB_USER_RESOLVER === 'function') {
1236
+ var v = window.IL_COLAB_USER_RESOLVER();
1237
+ if (typeof v === 'string') { cb(v || ''); return; }
1238
+ if (v && typeof v.then === 'function') {
1239
+ v.then(function (s) { cb(typeof s === 'string' ? s : ''); }, function () { cb(''); });
1240
+ return;
1241
+ }
1242
+ }
1243
+ } catch (e) { /* fall through */ }
1244
+
1245
+ var meta = document.querySelector('meta[name="cq:user"], meta[name="user"], meta[name="user-id"]');
1246
+ if (meta && meta.getAttribute('content')) { cb(meta.getAttribute('content')); return; }
1247
+
1248
+ if (ORIG_FETCH) {
1249
+ ORIG_FETCH(CURRENT_USER_ENDPOINT, {
1250
+ credentials: 'same-origin',
1251
+ headers: { 'Accept': 'application/json' }
1252
+ })
1253
+ .then(function (r) { return r && r.ok ? r.json() : null; })
1254
+ .then(function (j) {
1255
+ if (!j) { cb(''); return; }
1256
+ cb(j.authorizableId || j.id || j.userId || j.name || '');
1257
+ })
1258
+ .catch(function () { cb(''); });
1259
+ return;
1260
+ }
1261
+ cb('');
1262
+ }
1263
+
1264
+ function resolveAndIdentifyUser() {
1265
+ var cached = readCachedUserId();
1266
+ if (cached) identify(cached);
1267
+ resolveCurrentUser(function (u) {
1268
+ if (u && u !== cached) {
1269
+ writeCachedUserId(u);
1270
+ identify(u);
1271
+ }
1272
+ });
1273
+ }
1274
+
1275
+ // ─── 8. URL-driven events ────────────────────────────────
1276
+
1277
+ // Cross-call state for trackSearchExecuted ↔ waitForSearchStats. Kept at
1278
+ // the bootstrap scope (not per-call) so we can flush an in-flight wait
1279
+ // when the user navigates to a new search before the previous one's
1280
+ // statistics widget finished updating — otherwise the old call's
1281
+ // MutationObserver would pick up the NEW search's stats.
1282
+ var __searchFireCount = 0;
1283
+ var __cancelInflightStatsWait = null;
1284
+ var __flushInflightSearchNow = null;
1285
+
1286
+ /**
1287
+ * EVENT (login page only): Anonymous landing on the Login page.
1288
+ *
1289
+ * The SDK already auto-fires a `page_view` on every load (including this
1290
+ * one), but we add an explicit `login_page_view` event so the Reports
1291
+ * "login funnel" panel can distinguish login-page traffic from generic
1292
+ * site traffic and segment anonymous visitors before identify() fires.
1293
+ */
1294
+ function trackLoginPageView() {
1295
+ if (!isLoginPage()) return;
1296
+ track('login_page_view', {
1297
+ page_type: 'login',
1298
+ auth_state: 'anonymous',
1299
+ page_url: location.href,
1300
+ referrer: document.referrer || ''
1301
+ }, {}, 'anonymous');
1302
+ }
1303
+
1304
+ /**
1305
+ * EVENT 1 (search): fires when the current URL is a search-results page.
1306
+ *
1307
+ * ASC submits the search form via GET, so every search materializes as
1308
+ * a navigation. The new page-load runs this bootstrap fresh; if the URL
1309
+ * carries `?fulltext=…` we have a verified search execution AND all the
1310
+ * inputs the user supplied (term, semantic toggle, fuzzy toggle, rail
1311
+ * filters, ordering, layout, pagination) right there in the query string.
1312
+ *
1313
+ * This is more reliable than hooking the submit handler because it also
1314
+ * captures bookmarked searches, browser-back navigations, and shareable
1315
+ * search URLs — every one of which counts as a "search executed" event.
1316
+ */
1317
+ function trackSearchExecuted(q) {
1318
+ if (!q.hasOwnProperty('fulltext')) return;
1319
+
1320
+ // A new search arrived before the previous wait completed. Fire the
1321
+ // previous event NOW with whatever it has — we cannot let its
1322
+ // MutationObserver pick up THIS search's stats and mis-attribute them.
1323
+ if (__flushInflightSearchNow) {
1324
+ try { __flushInflightSearchNow(); } catch (e) {}
1325
+ __flushInflightSearchNow = null;
1326
+ }
1327
+ if (__cancelInflightStatsWait) {
1328
+ try { __cancelInflightStatsWait(); } catch (e) {}
1329
+ __cancelInflightStatsWait = null;
1330
+ }
1331
+
1332
+ // 1. URL is the canonical source of WHICH filters were applied — group,
1333
+ // property, operation, values are all encoded there.
1334
+ var urlFilters = extractFilters(q);
1335
+
1336
+ // 2. Enrich each URL filter with the human-readable section heading
1337
+ // from the right rail (ASSET TYPE, MARKETING FUNCTION / INDUSTRY,
1338
+ // APPLICATION & USE, ORIGIN, ASSET USAGE RIGHTS, LANGUAGE / REGION,
1339
+ // YEAR, LAST MODIFIED, CREATED, …). Falls back to the property's
1340
+ // trailing JCR segment if the rail isn't present (e.g. event fired
1341
+ // from a shared URL on a page without the rail).
1342
+ var rail = findFilterRail();
1343
+ var labelMap = buildPropertyLabelMap(rail);
1344
+ for (var i = 0; i < urlFilters.length; i++) {
1345
+ var f = urlFilters[i];
1346
+ f.name = labelMap[f.property] || deriveFallbackName(f.property);
1347
+ }
1348
+
1349
+ // 3. DOM-only sweep as a safety net — captures any predicate that is
1350
+ // selected in the rail but didn't appear in the URL (e.g. local UI
1351
+ // state that hadn't been submitted yet, or predicates encoded by a
1352
+ // non-standard component). Indexed by visible section heading so
1353
+ // reports can render it without per-filter mapping.
1354
+ var domFilters = scanRailSelectedFilters(rail);
1355
+
1356
+ var dims = {
1357
+ search_term: safeStr(q.fulltext),
1358
+ semantic_search: String(safeStr(q.semanticSearchEnabled).toLowerCase() === 'true'),
1359
+ fuzzy_search: String(safeStr(q.fuzzySearchEnabled).toLowerCase() === 'true'),
1360
+ filters_json: urlFilters.length ? JSON.stringify(urlFilters) : '',
1361
+ filters_dom_json: domFilters.length ? JSON.stringify(domFilters) : '',
1362
+ orderby: safeStr(q.orderby),
1363
+ order_dir: safeStr(q['orderby.sort']),
1364
+ layout: safeStr(q.layout),
1365
+ search_context: 'asc',
1366
+ page_url: location.href,
1367
+ page_referrer: document.referrer || ''
1368
+ };
1369
+ var metrics = {
1370
+ filter_count: urlFilters.length,
1371
+ filter_dom_count: domFilters.length,
1372
+ result_offset: parseInt(safeStr(q['p.offset']) || '0', 10) || 0,
1373
+ result_limit: parseInt(safeStr(q['p.limit']) || '0', 10) || 0
1374
+ };
1375
+
1376
+ var fired = false;
1377
+ function fireWithStats(stats) {
1378
+ if (fired) return;
1379
+ fired = true;
1380
+ __cancelInflightStatsWait = null;
1381
+ __flushInflightSearchNow = null;
1382
+
1383
+ if (stats) {
1384
+ if (stats.time_ms !== null) metrics.search_time_ms = stats.time_ms;
1385
+ if (stats.total !== null) metrics.result_total = stats.total;
1386
+ if (stats.pages !== null) metrics.result_pages = stats.pages;
1387
+ if (stats.displayed !== null) metrics.result_displayed = stats.displayed;
1388
+ dims.search_stats_ready = 'true';
1389
+ // Persist the raw label→value pairs in DOM order so any classifier
1390
+ // misattribution can be diagnosed from the back-end (e.g. ASC
1391
+ // re-labels "Time (ms)" → "Search Speed" in a future release).
1392
+ // Truncated to 240 chars to stay well under any ClickHouse Map
1393
+ // value size limit and avoid bloating event payloads.
1394
+ try {
1395
+ if (stats.raw && stats.raw.length) {
1396
+ var rawJson = JSON.stringify(stats.raw);
1397
+ dims.search_stats_raw_json = rawJson.length > 240
1398
+ ? rawJson.slice(0, 240)
1399
+ : rawJson;
1400
+ }
1401
+ } catch (e) { /* swallow */ }
1402
+ } else {
1403
+ dims.search_stats_ready = 'false';
1404
+ }
1405
+
1406
+ // Fourth arg is the event subtype — surfaces in ClickHouse's
1407
+ // event_subtype column. ASC fires our bootstrap once per full page
1408
+ // load, but also navigates via history.pushState when the user
1409
+ // tweaks a filter / pagination / layout / sort. We re-fire search
1410
+ // events on those pushState transitions too (see installSpaNavHooks
1411
+ // below), and tag both initial + SPA fires with the SAME subtype so
1412
+ // reports don't have to special-case how the URL was reached.
1413
+ track('search_executed', dims, metrics, 'asset_search');
1414
+ __searchFireCount++;
1415
+ }
1416
+
1417
+ // Stash a synchronous flush hook so the next trackSearchExecuted call
1418
+ // can force this one to fire (without stats) before starting its own
1419
+ // wait — see the early-return block at the top of this function.
1420
+ __flushInflightSearchNow = function () { fireWithStats(null); };
1421
+ __cancelInflightStatsWait = waitForSearchStats(readSearchStatistics, 3000, fireWithStats);
1422
+ }
1423
+
1424
+ /**
1425
+ * EVENT 2 (asset preview): fires when the current URL is an ASC details
1426
+ * page — i.e. a thumbnail click in the results grid navigated here.
1427
+ *
1428
+ * The asset path (`/content/dam/…`) is the suffix of `location.pathname`
1429
+ * after `/details/<type>.html`; the asset type is the segment in front
1430
+ * of `.html` (image, video, document, 3d, audio, …).
1431
+ */
1432
+ function trackAssetPreview() {
1433
+ var info = detectDetailsAssetPath();
1434
+ if (!info) return;
1435
+ var assetName = (info.assetPath.split('/').pop() || '');
1436
+ var dotIdx = assetName.lastIndexOf('.');
1437
+ var assetExt = dotIdx > 0 ? assetName.slice(dotIdx + 1).toLowerCase() : '';
1438
+ track('asset_preview', {
1439
+ asset_path: info.assetPath,
1440
+ asset_type: info.assetType,
1441
+ asset_name: assetName,
1442
+ asset_extension: assetExt,
1443
+ page_url: location.href,
1444
+ page_referrer: document.referrer || ''
1445
+ }, {}, 'asset_detail');
1446
+ }
1447
+
1448
+ /**
1449
+ * Wraps `history.pushState` / `history.replaceState` (and listens for
1450
+ * `popstate`) so we re-evaluate the URL on every SPA navigation and
1451
+ * re-fire `search_executed` / `asset_preview` if appropriate.
1452
+ *
1453
+ * Why this matters: Asset Share Commons rewires its in-page filter /
1454
+ * sort / layout / pagination controls to call `history.pushState`
1455
+ * rather than doing a full page reload. Without this hook the SDK's
1456
+ * own pushState wrapper still fires a `page_view` with
1457
+ * `event_subtype = "spa_navigation"`, but our search_executed event
1458
+ * (with `search_term`, `semantic_search`, `fuzzy_search`,
1459
+ * `filters_json`, etc. on the `custom_dimensions` map) would never
1460
+ * fire on those in-page transitions.
1461
+ *
1462
+ * Dedup: we keep the previous URL in a closure variable and skip
1463
+ * re-firing when the URL hasn't actually changed (e.g. some libraries
1464
+ * call replaceState with the current state on hash-only updates).
1465
+ */
1466
+ function installSpaNavHooks() {
1467
+ if (window.__ilColabSpaHooked) return;
1468
+ window.__ilColabSpaHooked = true;
1469
+
1470
+ var lastUrl = location.href;
1471
+
1472
+ function reevaluate() {
1473
+ try {
1474
+ var nowUrl = location.href;
1475
+ if (nowUrl === lastUrl) return;
1476
+ lastUrl = nowUrl;
1477
+ var q = parseQuery();
1478
+ trackSearchExecuted(q);
1479
+ trackAssetPreview();
1480
+ } catch (e) { /* swallow — never break the host page */ }
1481
+ }
1482
+
1483
+ // Defer slightly so the URL change has actually settled in the address
1484
+ // bar by the time we read `location.href` (some routers call pushState
1485
+ // synchronously inside an event handler that hasn't yet committed).
1486
+ function scheduleReevaluate() {
1487
+ try { (window.requestAnimationFrame || setTimeout)(reevaluate, 0); }
1488
+ catch (e) { setTimeout(reevaluate, 0); }
1489
+ }
1490
+
1491
+ window.addEventListener('popstate', scheduleReevaluate);
1492
+ window.addEventListener('hashchange', scheduleReevaluate);
1493
+
1494
+ if (window.history && typeof history.pushState === 'function') {
1495
+ var origPush = history.pushState;
1496
+ history.pushState = function () {
1497
+ var ret = origPush.apply(this, arguments);
1498
+ scheduleReevaluate();
1499
+ return ret;
1500
+ };
1501
+ }
1502
+ if (window.history && typeof history.replaceState === 'function') {
1503
+ var origReplace = history.replaceState;
1504
+ history.replaceState = function () {
1505
+ var ret = origReplace.apply(this, arguments);
1506
+ scheduleReevaluate();
1507
+ return ret;
1508
+ };
1509
+ }
1510
+ }
1511
+
1512
+ // ─── 8b. Asset Explorer (React) ──────────────────────────
1513
+
1514
+ /**
1515
+ * Returns true when the current URL is the React-based Asset Explorer
1516
+ * (e.g. /asset-explorer.html#/content/dam/ps). We accept the URL signal
1517
+ * first because it doesn't require the DOM to have settled, and fall
1518
+ * back to a DOM probe for themed deployments that mount the explorer
1519
+ * under a different path.
1520
+ */
1521
+ function isAssetExplorerPage() {
1522
+ var p = location.pathname;
1523
+ // Asset-preview / details URLs are a *child* of the explorer page
1524
+ // (`.../asset-explorer/details/<type>.html/<asset-path>`) and we want
1525
+ // those to fall into the ASC-style branch so trackAssetPreview() fires.
1526
+ // The details-detector above is the authoritative match for that.
1527
+ if (detectDetailsAssetPath()) return false;
1528
+ // URL path heuristic: matches both `/asset-explorer.html` (vanity URL)
1529
+ // and `/content/.../asset-explorer.html` (resolved page path).
1530
+ if (/\/asset[-_]?explorer(\.html|\/|$)/i.test(p)) return true;
1531
+ if (document.querySelector('[class*="_directoryExplorer_"], .directory-explorer')) return true;
1532
+ return false;
1533
+ }
1534
+
1535
+ function findAssetExplorerRoot() {
1536
+ return $(SELECTORS.assetExplorerRoot);
1537
+ }
1538
+
1539
+ /**
1540
+ * Locates the visible search input. Falls back to placeholder-text match
1541
+ * if the [class*="_input_"] selectors haven't been baked into a themed
1542
+ * deployment yet.
1543
+ */
1544
+ function findAssetExplorerSearchInput() {
1545
+ var byClass = $(SELECTORS.assetExplorerSearchInput);
1546
+ if (byClass) return byClass;
1547
+ var inputs = document.querySelectorAll('input[type="text"], input:not([type])');
1548
+ for (var i = 0; i < inputs.length; i++) {
1549
+ var p = inputs[i].getAttribute('placeholder') || '';
1550
+ if (TEXT_PATTERNS.aeSearchPlaceholder.test(p)) return inputs[i];
1551
+ }
1552
+ return null;
1553
+ }
1554
+
1555
+ /**
1556
+ * Returns the current `#/content/dam/...` folder path the explorer is
1557
+ * showing. Strips the leading `#` and any embedded query suffix so the
1558
+ * value is directly comparable to AEM JCR paths.
1559
+ */
1560
+ function readAssetExplorerFolderPath() {
1561
+ var h = String(location.hash || '');
1562
+ h = h.replace(/^#/, '');
1563
+ var qIdx = h.indexOf('?');
1564
+ if (qIdx >= 0) h = h.slice(0, qIdx);
1565
+ return h;
1566
+ }
1567
+
1568
+ /**
1569
+ * Reads the on/off state of a labelled toggle inside the Search Options
1570
+ * modal. Toggle markup varies across React component libraries so we
1571
+ * walk several known patterns before giving up:
1572
+ *
1573
+ * 1. native checkbox / radio (`checked`)
1574
+ * 2. `aria-checked` / `aria-pressed` / `aria-selected`
1575
+ * 3. class names containing "checked", "active", "enabled", "on"
1576
+ * 4. `data-state="on"` (Radix UI) / `data-selected="true"`
1577
+ *
1578
+ * Returns `'true'` / `'false'` strings so the value drops directly into
1579
+ * the ClickHouse `custom_dimensions` map without further serialization,
1580
+ * and `''` when the labelled row isn't present (modal not open). The
1581
+ * caller treats `''` as "unknown" and won't emit a misleading default.
1582
+ */
1583
+ function readAssetExplorerToggleState(labelRe) {
1584
+ var rows = document.querySelectorAll(SELECTORS.assetExplorerSearchOptionRow);
1585
+ for (var i = 0; i < rows.length; i++) {
1586
+ var row = rows[i];
1587
+ var text = cleanText(row.textContent || '');
1588
+ if (!labelRe.test(text)) continue;
1589
+
1590
+ // 1. native form control
1591
+ var checkbox = row.querySelector('input[type="checkbox"], input[type="radio"]');
1592
+ if (checkbox && checkbox.checked !== undefined) {
1593
+ return String(!!checkbox.checked);
1594
+ }
1595
+
1596
+ // 2. ARIA
1597
+ var ariaChecked = row.querySelector('[aria-checked], [aria-pressed], [aria-selected]');
1598
+ if (ariaChecked) {
1599
+ var v = ariaChecked.getAttribute('aria-checked')
1600
+ || ariaChecked.getAttribute('aria-pressed')
1601
+ || ariaChecked.getAttribute('aria-selected');
1602
+ if (v === 'true' || v === 'false') return v;
1603
+ }
1604
+
1605
+ // 3. data-state / data-selected
1606
+ var dataStated = row.querySelector('[data-state], [data-selected]');
1607
+ if (dataStated) {
1608
+ var ds = (dataStated.getAttribute('data-state') || '').toLowerCase();
1609
+ if (ds === 'on' || ds === 'checked' || ds === 'true') return 'true';
1610
+ if (ds === 'off' || ds === 'unchecked' || ds === 'false') return 'false';
1611
+ var sel = (dataStated.getAttribute('data-selected') || '').toLowerCase();
1612
+ if (sel === 'true') return 'true';
1613
+ if (sel === 'false') return 'false';
1614
+ }
1615
+
1616
+ // 4. class-name heuristic on the row OR its toggle child
1617
+ var classRoot = row.querySelector('[class*="toggle"], [class*="switch"], [role="switch"]') || row;
1618
+ var cls = (classRoot.className && classRoot.className.baseVal !== undefined)
1619
+ ? classRoot.className.baseVal // SVG element
1620
+ : String(classRoot.className || '');
1621
+ if (/(^|[\s_-])(active|checked|enabled|on|selected)([\s_-]|$)/i.test(cls)) return 'true';
1622
+ if (/(^|[\s_-])(inactive|unchecked|disabled|off)([\s_-]|$)/i.test(cls)) return 'false';
1623
+
1624
+ // Row matched but we couldn't determine state — return empty so the
1625
+ // caller emits "" rather than a misleading default.
1626
+ return '';
1627
+ }
1628
+ return '';
1629
+ }
1630
+
1631
+ /**
1632
+ * Reads the Asset Explorer search-statistics tiles.
1633
+ *
1634
+ * The live aem-sit.publiciscolab.com build renders three tiles inside a
1635
+ * `<div class="_statContainer_1qyta_1">` (camelCase suffix → not
1636
+ * matched by `[class*="_stat_"]`!) where each tile is a sibling
1637
+ * `<div>` containing a `<div class="_value_1qyta_9">N</div>` and a
1638
+ * sibling `<div class="_label_*">LABEL</div>`. We try in order:
1639
+ *
1640
+ * 1. find the stats container (or fall back to the filter rail),
1641
+ * 2. for every `[class*="_value_"]` descendant, pair it with a
1642
+ * `[class*="_label_"]` peer found by climbing the closest tile
1643
+ * wrapper (`<div>` parent) — covers both
1644
+ * "value-then-label" and "label-then-value" tile layouts,
1645
+ * 3. as a last resort, regex-parse the container's textContent for
1646
+ * `<number><whitespace?><LABEL>` so a stripped-down themed build
1647
+ * with no _value_/_label_ class hints still resolves.
1648
+ *
1649
+ * Returns the same `{ container, stats: { time_ms, total, pages,
1650
+ * displayed, raw } }` shape as readSearchStatistics() so the shared
1651
+ * waitForSearchStats() works unchanged.
1652
+ */
1653
+ function readAssetExplorerSearchStatistics() {
1654
+ var container = $(SELECTORS.assetExplorerSearchStatistics);
1655
+ if (!container) return { container: null, stats: null };
1656
+
1657
+ var rows = [];
1658
+ var seen = {};
1659
+
1660
+ function pushRow(label, valueText, value) {
1661
+ var key = (label || '').toLowerCase() + ':' + valueText;
1662
+ if (seen[key]) return;
1663
+ seen[key] = true;
1664
+ rows.push({ idx: rows.length, label: label, valueText: valueText, value: value });
1665
+ }
1666
+
1667
+ // ── Strategy 1: _value_ / _label_ pairing ───────────────
1668
+ // Walk every `[class*="_value_"]` in the container, then look for a
1669
+ // sibling/uncle/parent text that's the label. This handles the
1670
+ // `_statContainer_ > div[i] > {_value_, _label_}` shape and the
1671
+ // common variant where value and label are wrapped together in
1672
+ // a `<div>` tile.
1673
+ var valueEls = container.querySelectorAll('[class*="_value_"]');
1674
+ for (var i = 0; i < valueEls.length; i++) {
1675
+ var vEl = valueEls[i];
1676
+ var valueText = cleanText(vEl.textContent);
1677
+ var n = parseStatNumber(valueText);
1678
+ if (n === null) continue;
1679
+
1680
+ // Skip $value$ blocks that aren't direct text values (e.g., a
1681
+ // nested wrapper). Only first-level numeric content qualifies.
1682
+ if (!/^[-+]?\d/.test(valueText)) continue;
1683
+
1684
+ var labelText = '';
1685
+
1686
+ // a) Sibling [class*="_label_"]
1687
+ if (vEl.parentElement) {
1688
+ var sibLabel = vEl.parentElement.querySelector('[class*="_label_"]');
1689
+ if (sibLabel && sibLabel !== vEl) labelText = cleanText(sibLabel.textContent);
1690
+ }
1691
+
1692
+ // b) Walk up one level — tile may wrap value+label in a div whose
1693
+ // parent has a separate [class*="_label_"] child.
1694
+ if (!labelText && vEl.parentElement && vEl.parentElement.parentElement) {
1695
+ var unc = vEl.parentElement.parentElement.querySelector('[class*="_label_"]');
1696
+ if (unc && unc !== vEl) labelText = cleanText(unc.textContent);
1697
+ }
1698
+
1699
+ // c) Adjacent textContent — parent's text minus the value
1700
+ if (!labelText && vEl.parentElement) {
1701
+ var parentText = cleanText(vEl.parentElement.textContent);
1702
+ if (parentText && parentText.indexOf(valueText) >= 0) {
1703
+ var residual = parentText.replace(valueText, '').trim();
1704
+ // Only keep if residual is short (a label) not a paragraph.
1705
+ if (residual && residual.length <= 80) labelText = residual;
1706
+ }
1707
+ }
1708
+
1709
+ pushRow(labelText, valueText, n);
1710
+ }
1711
+
1712
+ // ── Strategy 2: regex over container text ───────────────
1713
+ // Pattern: `<number><whitespace?><LABEL>` repeated (e.g.
1714
+ // "4 DISPLAYED 4 TOTAL 11 MILLISECONDS" or "4DISPLAYED…").
1715
+ if (!rows.length) {
1716
+ var fullText = cleanText(container.textContent || '');
1717
+ var re = /(\d+(?:[.,]\d+)?)\s*(displayed|showing|shown|visible|total|results?|assets?|hits?|matches?|found|count|milliseconds?|seconds?|elapsed|duration|time|pages?)\b/gi;
1718
+ var m;
1719
+ while ((m = re.exec(fullText)) !== null) {
1720
+ var rv = parseStatNumber(m[1]);
1721
+ if (rv === null) continue;
1722
+ pushRow(m[2], m[1], rv);
1723
+ }
1724
+ }
1725
+
1726
+ if (!rows.length || !rows.some(function (r) { return r.value !== null; })) {
1727
+ return { container: container, stats: null };
1728
+ }
1729
+
1730
+ var stats = {
1731
+ time_ms: null,
1732
+ total: null,
1733
+ pages: null,
1734
+ displayed: null,
1735
+ raw: rows.map(function (r) { return { idx: r.idx, label: r.label, value: r.valueText }; })
1736
+ };
1737
+
1738
+ // Label-driven classification. We deliberately DO NOT carry the
1739
+ // positional fallback over from the ASC reader — React layouts
1740
+ // have no stable left-to-right ordering convention and a silent
1741
+ // no-op is safer than a confident mis-attribution.
1742
+ for (var k = 0; k < rows.length; k++) {
1743
+ var r = rows[k];
1744
+ if (r.value === null) continue;
1745
+ var c = classifyStatLabel(r.label);
1746
+ if (!c) continue;
1747
+ if (c.key === 'time_ms' && stats.time_ms === null) {
1748
+ stats.time_ms = c.unit === 's' ? r.value * 1000 : r.value;
1749
+ } else if (c.key === 'total' && stats.total === null) {
1750
+ stats.total = r.value;
1751
+ } else if (c.key === 'pages' && stats.pages === null) {
1752
+ stats.pages = r.value;
1753
+ } else if (c.key === 'displayed' && stats.displayed === null) {
1754
+ stats.displayed = r.value;
1755
+ }
1756
+ }
1757
+
1758
+ return { container: container, stats: stats };
1759
+ }
1760
+
1761
+ /**
1762
+ * Reads the currently-selected filters from the right-rail facet panel.
1763
+ * Returns an array of `{ name, values[] }` blocks keyed by section
1764
+ * heading text — same shape `filters_dom_json` carries on the ASC
1765
+ * search_executed event so dashboards can pivot on either context
1766
+ * uniformly. An empty array (no selections) is the normal default;
1767
+ * the caller emits `filters_dom_json=""` in that case.
1768
+ *
1769
+ * Detection strategies, applied in order until something is found:
1770
+ * 1. Native form controls (`input[type="checkbox"]:checked`,
1771
+ * `input[type="radio"]:checked`).
1772
+ * 2. ARIA: `[aria-checked="true"]`, `[aria-selected="true"]`,
1773
+ * `[aria-pressed="true"]`.
1774
+ * 3. data-state: `[data-state="checked" | "on" | "selected"]`,
1775
+ * `[data-selected="true"]`.
1776
+ * 4. Class-name heuristic — any element under the rail with a class
1777
+ * containing "_selected", "_checked", "_active", or "_on" that
1778
+ * ISN'T paired with an "un-" prefix on the same chip.
1779
+ *
1780
+ * Each match is grouped under its enclosing section heading; the
1781
+ * heading is resolved by walking up to the closest filter-section
1782
+ * container and reading its first heading-class child.
1783
+ */
1784
+ function readAssetExplorerFilters() {
1785
+ var rail = $(SELECTORS.assetExplorerFilterRail);
1786
+ if (!rail) return [];
1787
+
1788
+ // Live aem-sit.publiciscolab.com filter rail captures show section
1789
+ // headings landing on classes the original `_filterSection_`-anchored
1790
+ // logic never saw. Climb up to 8 ancestor levels and, at each step,
1791
+ // look for either a previous-sibling or first-child element whose
1792
+ // class matches the heading patterns OR whose textContent is a
1793
+ // short ALL-CAPS label. The ALL-CAPS fallback handles builds
1794
+ // where the heading element has no recognisable class (just a plain
1795
+ // <div>FACET NAME</div>).
1796
+ //
1797
+ // We deliberately keep `[class*="_label_"]` / `[class*="_name_"]` /
1798
+ // `[class*="_header_"]` OUT of the heading selector — in this React
1799
+ // build the CHIP itself wraps its visible text in `_label_<hash>`,
1800
+ // and the chip's label appears in DOM order BEFORE its input, so
1801
+ // matching `_label_` would walk straight into the chip's own text
1802
+ // and return it as the section heading (v1.1.3 bug: "2026" / "Image"
1803
+ // ended up as section names). The ALL-CAPS visibility test below
1804
+ // is the more reliable signal for actual section names.
1805
+ var HEADING_SELECTOR =
1806
+ '[class*="_heading_"], [class*="_title_"], [class*="_sectionTitle_"], ' +
1807
+ '[class*="_categoryName_"], [class*="_facetTitle_"], [class*="_groupName_"], ' +
1808
+ '[class*="_groupTitle_"], [class*="_sectionHeader_"], [class*="_facetHeader_"], ' +
1809
+ '[class*="_categoryHeader_"], [class*="_filterHeader_"], [class*="_filterTitle_"], ' +
1810
+ 'h1, h2, h3, h4, h5, h6, legend, summary';
1811
+
1812
+ function looksLikeFacetHeading(txt) {
1813
+ if (!txt) return false;
1814
+ if (txt.length < 3 || txt.length > 80) return false;
1815
+ // Reject stat tiles ("4 DISPLAYED") and pure numbers ("2026").
1816
+ if (/^\d/.test(txt)) return false;
1817
+ // Must contain at least one A-Z letter and NO lowercase letters
1818
+ // — observed facets on this build are 100% uppercase with optional
1819
+ // punctuation: ASSET TYPE, MARKETING FUNCTION / INDUSTRY,
1820
+ // APPLICATION & USE, ORIGIN, ASSET USAGE RIGHTS,
1821
+ // LANGUAGE / REGION, YEAR.
1822
+ if (!/[A-Z]/.test(txt)) return false;
1823
+ if (/[a-z]/.test(txt)) return false;
1824
+ // Allowed character set — uppercase letters, digits (rare),
1825
+ // whitespace, and a handful of punctuation marks seen in facet
1826
+ // names. Anything else is probably a chip with weird casing.
1827
+ if (!/^[A-Z0-9 &/().,\-]+$/.test(txt)) return false;
1828
+ // Reject pure punctuation / pure whitespace.
1829
+ if (!/[A-Z]{2,}/.test(txt) && txt.length < 4) return false;
1830
+ return true;
1831
+ }
1832
+
1833
+ function sectionHeadingFor(el) {
1834
+ var ancestor = el;
1835
+ for (var depth = 0; depth < 8 && ancestor && ancestor !== rail; depth++) {
1836
+ // a) Heading-class previous sibling at this depth
1837
+ var prev = ancestor.previousElementSibling;
1838
+ while (prev) {
1839
+ if (prev.matches && prev.matches(HEADING_SELECTOR)) {
1840
+ var t1 = cleanText(prev.textContent || '');
1841
+ if (t1) return t1.slice(0, 80);
1842
+ }
1843
+ // ALL-CAPS plain element with short text counts too
1844
+ var pt = cleanText(prev.textContent || '');
1845
+ if (looksLikeFacetHeading(pt)) return pt.slice(0, 80);
1846
+ prev = prev.previousElementSibling;
1847
+ }
1848
+ // b) Heading-class first child of THIS ancestor (before the chip)
1849
+ var children = ancestor.children;
1850
+ for (var i = 0; i < children.length; i++) {
1851
+ var c = children[i];
1852
+ if (c === el) break;
1853
+ if (c.contains && c.contains(el)) continue; // skip the chip's branch
1854
+ if (c.matches && c.matches(HEADING_SELECTOR)) {
1855
+ var t2 = cleanText(c.textContent || '');
1856
+ if (t2) return t2.slice(0, 80);
1857
+ }
1858
+ // ALL-CAPS plain element
1859
+ var ct = cleanText(c.textContent || '');
1860
+ if (looksLikeFacetHeading(ct)) return ct.slice(0, 80);
1861
+ }
1862
+ ancestor = ancestor.parentElement;
1863
+ }
1864
+ return '';
1865
+ }
1866
+
1867
+ function chipLabel(el) {
1868
+ var inp;
1869
+ if (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'OPTION') {
1870
+ inp = el;
1871
+ }
1872
+ // Prefer an associated <label>, then aria-label, then visible text.
1873
+ if (inp && inp.id) {
1874
+ var lab = document.querySelector('label[for="' + CSS.escape(inp.id) + '"]');
1875
+ if (lab) return cleanText(lab.textContent || '');
1876
+ }
1877
+ var aria = el.getAttribute && el.getAttribute('aria-label');
1878
+ if (aria) return aria;
1879
+ // Climb to the nearest row/chip wrapper for the visible text — the
1880
+ // raw element itself might be an inner input/svg with no text.
1881
+ var wrapper = el.closest('label, li, [role="option"], [role="treeitem"], [role="menuitem"], [class*="_option_"], [class*="_chip_"], [class*="_item_"], [class*="_row_"]') || el;
1882
+ return cleanText(wrapper.textContent || '').slice(0, 120);
1883
+ }
1884
+
1885
+ var bySection = {};
1886
+ function record(el) {
1887
+ var section = sectionHeadingFor(el) || 'unknown';
1888
+ var label = chipLabel(el);
1889
+ if (!label) return;
1890
+ if (!bySection[section]) bySection[section] = [];
1891
+ // Dedup within the same section (a checkbox + its <label> wrapper
1892
+ // can both match the class-name heuristic).
1893
+ if (bySection[section].indexOf(label) < 0) bySection[section].push(label);
1894
+ }
1895
+
1896
+ // 1. native form controls
1897
+ var natives = rail.querySelectorAll('input[type="checkbox"]:checked, input[type="radio"]:checked');
1898
+ for (var n = 0; n < natives.length; n++) record(natives[n]);
1899
+
1900
+ // 2. ARIA / data-state
1901
+ var ariaSel = rail.querySelectorAll(
1902
+ '[aria-checked="true"], [aria-selected="true"], [aria-pressed="true"], ' +
1903
+ '[data-state="checked"], [data-state="on"], [data-state="selected"], ' +
1904
+ '[data-selected="true"]'
1905
+ );
1906
+ for (var a = 0; a < ariaSel.length; a++) record(ariaSel[a]);
1907
+
1908
+ // 3. class-name heuristic — narrow to elements whose className is
1909
+ // SHORT (likely a chip) and contains a positive state marker.
1910
+ var clsCandidates = rail.querySelectorAll(
1911
+ '[class*="_selected_"], [class*="_checked_"], [class*="_active_"], [class*="_on_"], [class*="_isSelected"]'
1912
+ );
1913
+ for (var c = 0; c < clsCandidates.length; c++) {
1914
+ var el = clsCandidates[c];
1915
+ var cls = (el.className && el.className.baseVal !== undefined) ? el.className.baseVal : String(el.className || '');
1916
+ if (cls.length > 240) continue; // skip container-level matches
1917
+ if (/_unselected|_unchecked|_inactive|_off/i.test(cls)) continue;
1918
+ // Skip elements that are descendants of an already-matched native
1919
+ // input — record() already handled them.
1920
+ if (el.querySelector('input[type="checkbox"]:checked, input[type="radio"]:checked')) continue;
1921
+ record(el);
1922
+ }
1923
+
1924
+ var out = [];
1925
+ for (var s in bySection) {
1926
+ if (bySection.hasOwnProperty(s)) {
1927
+ out.push({ name: s, values: bySection[s] });
1928
+ }
1929
+ }
1930
+ return out;
1931
+ }
1932
+
1933
+ // Cross-call state for trackAssetExplorerSearch (mirrors the ASC pair).
1934
+ var __aeCancelInflightStatsWait = null;
1935
+ var __aeFlushInflightSearchNow = null;
1936
+ // Dedup: avoid re-firing the same {term, semantic, fuzzy, folder} combo
1937
+ // when several triggers (Enter + form submit + click) overlap on a
1938
+ // single user action. Compared by string equality with the LAST fired
1939
+ // signature; cleared on hashchange.
1940
+ var __aeLastFiredSig = '';
1941
+
1942
+ /**
1943
+ * Emits `search_executed` (subtype `asset_search`) for the React Asset
1944
+ * Explorer page. Captures search term + semantic/fuzzy toggles + the
1945
+ * current folder + the stats widget once it settles. The `trigger`
1946
+ * argument records HOW the search was initiated (enter, submit, click,
1947
+ * options_close, filter_click, input_debounced) so we can prune the
1948
+ * hooks later once we see which paths actually fire in production.
1949
+ */
1950
+ function trackAssetExplorerSearch(searchTerm, opts) {
1951
+ opts = opts || {};
1952
+ searchTerm = safeStr(searchTerm).trim();
1953
+ if (!searchTerm) return;
1954
+
1955
+ var semantic = (typeof opts.semantic === 'string')
1956
+ ? opts.semantic
1957
+ : readAssetExplorerToggleState(TEXT_PATTERNS.semantic);
1958
+ var fuzzy = (typeof opts.fuzzy === 'string')
1959
+ ? opts.fuzzy
1960
+ : readAssetExplorerToggleState(TEXT_PATTERNS.fuzzy);
1961
+ var folder = readAssetExplorerFolderPath();
1962
+ var trigger = safeStr(opts.trigger);
1963
+ var filters = readAssetExplorerFilters();
1964
+ var filtersJson = filters.length ? JSON.stringify(filters) : '';
1965
+
1966
+ // Dedup signature includes the filter selection — flipping a single
1967
+ // facet on/off should re-fire even if the search term is unchanged,
1968
+ // since the result set itself changes.
1969
+ var sig = [searchTerm, semantic, fuzzy, folder, filtersJson].join('|');
1970
+ if (sig === __aeLastFiredSig && !opts.forceDedupBypass) return;
1971
+ __aeLastFiredSig = sig;
1972
+
1973
+ if (__aeFlushInflightSearchNow) {
1974
+ try { __aeFlushInflightSearchNow(); } catch (e) {}
1975
+ __aeFlushInflightSearchNow = null;
1976
+ }
1977
+ if (__aeCancelInflightStatsWait) {
1978
+ try { __aeCancelInflightStatsWait(); } catch (e) {}
1979
+ __aeCancelInflightStatsWait = null;
1980
+ }
1981
+
1982
+ var dims = {
1983
+ search_term: searchTerm,
1984
+ semantic_search: semantic,
1985
+ fuzzy_search: fuzzy,
1986
+ search_context: 'asset_explorer',
1987
+ search_trigger: trigger,
1988
+ folder_path: folder,
1989
+ filters_dom_json: filtersJson,
1990
+ page_url: location.href,
1991
+ page_referrer: document.referrer || ''
1992
+ };
1993
+ var metrics = {
1994
+ filter_dom_count: filters.reduce(function (acc, g) { return acc + (g.values ? g.values.length : 0); }, 0)
1995
+ };
1996
+
1997
+ var fired = false;
1998
+ function fireWithStats(stats) {
1999
+ if (fired) return;
2000
+ fired = true;
2001
+ __aeCancelInflightStatsWait = null;
2002
+ __aeFlushInflightSearchNow = null;
2003
+
2004
+ if (stats) {
2005
+ if (stats.time_ms !== null) metrics.search_time_ms = stats.time_ms;
2006
+ if (stats.total !== null) metrics.result_total = stats.total;
2007
+ if (stats.pages !== null) metrics.result_pages = stats.pages;
2008
+ if (stats.displayed !== null) metrics.result_displayed = stats.displayed;
2009
+ dims.search_stats_ready = 'true';
2010
+ try {
2011
+ if (stats.raw && stats.raw.length) {
2012
+ var rawJson = JSON.stringify(stats.raw);
2013
+ dims.search_stats_raw_json = rawJson.length > 240 ? rawJson.slice(0, 240) : rawJson;
2014
+ }
2015
+ } catch (e) { /* swallow */ }
2016
+ } else {
2017
+ dims.search_stats_ready = 'false';
2018
+ }
2019
+
2020
+ track('search_executed', dims, metrics, 'asset_search');
2021
+ __searchFireCount++;
2022
+ }
2023
+
2024
+ __aeFlushInflightSearchNow = function () { fireWithStats(null); };
2025
+ __aeCancelInflightStatsWait = waitForSearchStats(readAssetExplorerSearchStatistics, 3000, fireWithStats);
2026
+ }
2027
+
2028
+ /**
2029
+ * Emits a `folder_navigation` event with subtype `asset_browse`. The
2030
+ * `tree_action` dim distinguishes how the navigation was triggered so
2031
+ * a single event type can describe every kind of folder interaction:
2032
+ *
2033
+ * - "hash_change" — the URL hash route changed (true navigation)
2034
+ * - "click" — user clicked a folder label in the side tree
2035
+ * - "expand" — user expanded a tree node
2036
+ * - "collapse" — user collapsed a tree node
2037
+ *
2038
+ * The tree-action variants also carry `tree_target_label` (the visible
2039
+ * text of the clicked node) and `tree_target_class_hint` (the first
2040
+ * 240 chars of the target's className) so we can refine the action
2041
+ * detection later without re-instrumenting the page.
2042
+ */
2043
+ function trackAssetExplorerFolderNavigation(opts) {
2044
+ opts = opts || {};
2045
+ var folder = readAssetExplorerFolderPath();
2046
+ var action = safeStr(opts.tree_action) || 'hash_change';
2047
+ // Skip the initial page_load / hash_change variants when the React
2048
+ // app hasn't set its default route yet — the next real hashchange
2049
+ // will fire a clean event. We still fire on click/expand/collapse
2050
+ // even with an empty folder so a no-op gesture is observable.
2051
+ if (!folder && (action === 'hash_change' || action === 'page_load')) return;
2052
+ var dims = {
2053
+ folder_path: folder,
2054
+ search_context: 'asset_explorer',
2055
+ tree_action: action,
2056
+ page_url: location.href,
2057
+ page_referrer: document.referrer || ''
2058
+ };
2059
+ if (opts.tree_target_label) {
2060
+ dims.tree_target_label = safeStr(opts.tree_target_label).slice(0, 120);
2061
+ }
2062
+ if (opts.tree_target_class_hint) {
2063
+ dims.tree_target_class_hint = safeStr(opts.tree_target_class_hint).slice(0, 240);
2064
+ }
2065
+ track('folder_navigation', dims, {}, 'asset_browse');
2066
+ }
2067
+
2068
+ // ─── 9. DOM-driven hooks (clicks) ────────────────────────
2069
+
2070
+ // ── Login page hooks (preserved from earlier login-only bootstrap) ──
2071
+
2072
+ function hookSignInSubmit() {
2073
+ var form = $(SELECTORS.loginForm);
2074
+ var btn = $(SELECTORS.signInButton);
2075
+ if (!btn) {
2076
+ btn = closestMatchByText(document, 'button, a, [role="button"], input[type="submit"]', TEXT_PATTERNS.signIn);
2077
+ }
2078
+ function fire(reason) {
2079
+ var userInput = $(SELECTORS.userField);
2080
+ var typedUser = (userInput && (userInput.value || '').trim()) || '';
2081
+ if (typedUser) identify(typedUser);
2082
+ track('login_attempt', {
2083
+ method: 'credentials',
2084
+ attempt_user: typedUser,
2085
+ submit_reason: reason || 'click',
2086
+ page_url: location.href
2087
+ });
2088
+ flush();
2089
+ }
2090
+ if (btn) btn.addEventListener('click', function () { fire('click'); }, { capture: true });
2091
+ if (form) form.addEventListener('submit', function () { fire('submit'); }, { capture: true });
2092
+ }
2093
+
2094
+ function hookSsoClick() {
2095
+ var btn = $(SELECTORS.ssoButton);
2096
+ if (!btn) {
2097
+ btn = closestMatchByText(document, 'button, a, [role="button"]', TEXT_PATTERNS.lionSso);
2098
+ }
2099
+ if (!btn) return;
2100
+ btn.addEventListener('click', function () {
2101
+ track('sso_click', {
2102
+ method: 'lion_login',
2103
+ sso_provider: 'lion',
2104
+ button_text: visibleText(btn).substring(0, 120),
2105
+ page_url: location.href
2106
+ });
2107
+ flush();
2108
+ }, { capture: true });
2109
+ }
2110
+
2111
+ function hookTermsClick() {
2112
+ var link = $(SELECTORS.termsLink);
2113
+ if (!link) {
2114
+ link = closestMatchByText(document, 'a, button, [role="link"]', TEXT_PATTERNS.terms);
2115
+ }
2116
+ if (!link) return;
2117
+ link.addEventListener('click', function () {
2118
+ track('terms_click', {
2119
+ link_url: (link.getAttribute && link.getAttribute('href')) || '',
2120
+ link_text: visibleText(link).substring(0, 120),
2121
+ page_url: location.href
2122
+ });
2123
+ flush();
2124
+ }, { capture: true });
2125
+ }
2126
+
2127
+ // ── ASC click delegation (one body-level listener, survives SPA mutations) ──
2128
+
2129
+ /**
2130
+ * Body-level click listener that matches Add-to-Cart and Share buttons
2131
+ * across both the search-results grid (tile + table) and the asset detail
2132
+ * page. Uses `closest()` so it works whether the user clicks the icon,
2133
+ * the label, or any descendant of the button.
2134
+ */
2135
+ function installAscClickDelegation() {
2136
+ if (window.__ilColabClickDelegated) return;
2137
+ window.__ilColabClickDelegated = true;
2138
+
2139
+ function tryClosest(target, selector) {
2140
+ try { return target.closest(selector); } catch (e) { return null; }
2141
+ }
2142
+
2143
+ document.addEventListener('click', function (e) {
2144
+ var target = e.target;
2145
+ if (!target || target.nodeType !== 1 || !target.closest) return;
2146
+
2147
+ // The dispatch ordering matters — match the MOST SPECIFIC
2148
+ // data-asset-share-id first so cart-level controls don't fall
2149
+ // through to asset-level handlers. Each branch returns to
2150
+ // prevent a single user click from emitting multiple events.
2151
+
2152
+ // ── 1. Cart-level "Download Cart" (data-asset-share-id="download-all") ──
2153
+ // The user-confirmed intent to start downloading the entire
2154
+ // cart. A second confirmation modal appears AFTER this click;
2155
+ // the actual binaries are produced asynchronously and surface
2156
+ // in the downloads modal as individual downloadbinaries.json
2157
+ // anchors (covered by branch 3 below).
2158
+ var dlAllBtn = tryClosest(target, SELECTORS.cartDownloadButton);
2159
+ if (dlAllBtn) {
2160
+ var dlContents = readCartContents();
2161
+ var dlContentsJson = dlContents.length ? JSON.stringify(dlContents) : '';
2162
+ if (dlContentsJson.length > 480) dlContentsJson = dlContentsJson.slice(0, 480);
2163
+ track('cart_download', {
2164
+ cart_asset_paths_json: dlContentsJson,
2165
+ page_url: location.href,
2166
+ page_referrer: document.referrer || ''
2167
+ }, {
2168
+ cart_item_count: dlContents.length
2169
+ }, 'cart_action');
2170
+ return;
2171
+ }
2172
+
2173
+ // ── 2. Cart-level "Share Cart" (data-asset-share-id="share-all") ──
2174
+ // Clicking this OPENS a second modal where the user enters
2175
+ // recipient emails + public flag + optional date range. The
2176
+ // real share doesn't happen until that form is submitted,
2177
+ // which we capture in `installShareFormHook()`. To survive the
2178
+ // cart-modal closing before the share form is filled in, we
2179
+ // stash the cart snapshot module-globally so the submit
2180
+ // handler can attach it to the cart_share event.
2181
+ var shareAllBtn = tryClosest(target, SELECTORS.cartShareButton);
2182
+ if (shareAllBtn) {
2183
+ var shContents = readCartContents();
2184
+ var shContentsJson = shContents.length ? JSON.stringify(shContents) : '';
2185
+ if (shContentsJson.length > 480) shContentsJson = shContentsJson.slice(0, 480);
2186
+ // Stash for the submit handler.
2187
+ window.__ilColabPendingCartShare = {
2188
+ paths: shContents,
2189
+ paths_json: shContentsJson,
2190
+ captured_at: Date.now()
2191
+ };
2192
+ // "Intent to share" event — useful for the funnel
2193
+ // (clicked → completed) and fires regardless of whether
2194
+ // the user actually submits the form.
2195
+ track('cart_share_initiated', {
2196
+ cart_asset_paths_json: shContentsJson,
2197
+ page_url: location.href,
2198
+ page_referrer: document.referrer || ''
2199
+ }, {
2200
+ cart_item_count: shContents.length
2201
+ }, 'cart_action');
2202
+ return;
2203
+ }
2204
+
2205
+ // ── 3. Per-artifact download link (downloadbinaries.json) ──
2206
+ // Fired when a user clicks any individual download anchor in
2207
+ // the downloads modal. This is the REAL "asset_download" event
2208
+ // — the binary leaves the server on this click, unlike the
2209
+ // cart-download button above which is just the user's intent
2210
+ // to start the download pipeline.
2211
+ var dlLink = tryClosest(target, SELECTORS.downloadBinaryLink);
2212
+ if (dlLink) {
2213
+ var href = dlLink.getAttribute('href') || '';
2214
+ var params = parseUrlParams(href);
2215
+ var endpoint = href.split('?')[0];
2216
+ track('asset_download', {
2217
+ download_id: params.downloadId || '',
2218
+ artifact_id: params.artifactId || '',
2219
+ download_endpoint: endpoint,
2220
+ download_source: 'downloads_modal',
2221
+ download_method: 'binary_link_click',
2222
+ page_url: location.href,
2223
+ page_referrer: document.referrer || ''
2224
+ });
2225
+ return;
2226
+ }
2227
+
2228
+ // ── 4. Per-artifact "remove from downloads" button ──
2229
+ var dlRemoveBtn = tryClosest(target, SELECTORS.downloadRemoveButton);
2230
+ if (dlRemoveBtn) {
2231
+ track('download_removed', {
2232
+ download_id: dlRemoveBtn.getAttribute('data-asset-share-download-id') || '',
2233
+ page_url: location.href
2234
+ }, {}, 'cart_action');
2235
+ return;
2236
+ }
2237
+
2238
+ // ── 5. Asset-level "Add to Cart" tile button ──
2239
+ // Now that the cart-level controls are handled above, anything
2240
+ // remaining with `data-asset-share-id="add-to-cart"` is the
2241
+ // per-asset variant. We DO NOT rely on the button's visible
2242
+ // text — the icon-only variant has none — and pull the asset
2243
+ // path straight off `data-asset-share-asset` via the extractor.
2244
+ var cartBtn = tryClosest(target, SELECTORS.addToCart);
2245
+ if (!cartBtn) {
2246
+ // Visible-text fallback for installations that haven't been
2247
+ // migrated to the data-asset-share-id convention yet.
2248
+ var cartCandidate = tryClosest(target, 'button, a, [role="button"], [role="menuitem"]');
2249
+ if (cartCandidate && TEXT_PATTERNS.cart.test(visibleText(cartCandidate))) {
2250
+ cartBtn = cartCandidate;
2251
+ }
2252
+ }
2253
+ if (cartBtn) {
2254
+ track('asset_add_to_cart', {
2255
+ asset_path: extractAssetPathFromEl(cartBtn),
2256
+ page_url: location.href
2257
+ });
2258
+ return;
2259
+ }
2260
+
2261
+ // ── 6. Header cart-icon click (opens cart modal) ──
2262
+ var cartOpen = tryClosest(target, SELECTORS.cartOpenButton);
2263
+ if (cartOpen) {
2264
+ track('cart_open', { page_url: location.href }, {}, 'cart_action');
2265
+ return;
2266
+ }
2267
+
2268
+ // ── 7. Header download-icon click (opens downloads modal) ──
2269
+ var dlOpen = tryClosest(target, SELECTORS.downloadsOpenButton);
2270
+ if (dlOpen) {
2271
+ track('downloads_open', { page_url: location.href }, {}, 'cart_action');
2272
+ return;
2273
+ }
2274
+
2275
+ // ── 8. Asset-level Share button ──
2276
+ var shareBtn = tryClosest(target, SELECTORS.shareButton);
2277
+ if (!shareBtn) {
2278
+ var shareCandidate = tryClosest(target, 'button, a, [role="button"], [role="menuitem"]');
2279
+ // Visible-text fallback — explicitly reject anything that sits
2280
+ // under the cart-modal or matches the cart-share selector, so
2281
+ // a generic /share/i click on Share Cart can't fall through
2282
+ // to asset_share here.
2283
+ if (shareCandidate &&
2284
+ TEXT_PATTERNS.share.test(visibleText(shareCandidate)) &&
2285
+ !TEXT_PATTERNS.cart.test(visibleText(shareCandidate)) &&
2286
+ !tryClosest(shareCandidate, SELECTORS.cartShareButton) &&
2287
+ !tryClosest(shareCandidate, SELECTORS.cartModal)) {
2288
+ shareBtn = shareCandidate;
2289
+ }
2290
+ }
2291
+ if (shareBtn) {
2292
+ track('asset_share', {
2293
+ asset_path: extractAssetPathFromEl(shareBtn),
2294
+ page_url: location.href
2295
+ });
2296
+ }
2297
+ }, { capture: true });
2298
+ }
2299
+
2300
+ /**
2301
+ * Parses the recipient e-mail field. The input is `<input
2302
+ * type="email" multiple name="email">` and the user typically types
2303
+ * `a@b.com, c@d.com, e@f.com` (the placeholder advertises a
2304
+ * comma-delimited list). We accept commas, semicolons, and
2305
+ * whitespace as separators, trim and de-dupe (case-insensitive),
2306
+ * and drop anything that doesn't look vaguely like an e-mail. The
2307
+ * returned array preserves the user's typed order for the first
2308
+ * occurrence of each address.
2309
+ */
2310
+ function parseRecipientEmails(raw) {
2311
+ if (!raw) return [];
2312
+ var parts = String(raw).split(/[,;\s]+/);
2313
+ var out = [];
2314
+ var seen = {};
2315
+ for (var i = 0; i < parts.length; i++) {
2316
+ var t = (parts[i] || '').trim();
2317
+ if (!t) continue;
2318
+ // Loose validation — we only want to drop obvious garbage
2319
+ // like trailing punctuation; the server will do real
2320
+ // validation downstream. We DO require an `@` plus a `.`
2321
+ // somewhere after it.
2322
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)) continue;
2323
+ var key = t.toLowerCase();
2324
+ if (seen[key]) continue;
2325
+ seen[key] = true;
2326
+ out.push(t);
2327
+ }
2328
+ return out;
2329
+ }
2330
+
2331
+ /**
2332
+ * Captures the share-modal form submission. The cart-level "Share
2333
+ * Cart" button (handled in installAscClickDelegation, branch 2)
2334
+ * fires a `cart_share_initiated` intent event AND stashes the cart
2335
+ * contents in `window.__ilColabPendingCartShare` because the cart
2336
+ * modal usually closes before the share form is filled in. When
2337
+ * the user actually submits the share form, this hook fires the
2338
+ * REAL `cart_share` event with:
2339
+ *
2340
+ * - share_emails – comma-joined list (480-char cap)
2341
+ * - share_emails_count – metric, distinct after dedupe
2342
+ * - share_is_public – "true" / "false"
2343
+ * - share_start_date – yyyy-mm-dd (public-only)
2344
+ * - share_end_date – yyyy-mm-dd (public-only)
2345
+ * - share_date_range_days – metric, end-start in days (>=0)
2346
+ * - cart_asset_paths_json – snapshot from button-click stash,
2347
+ * falls back to a fresh
2348
+ * readCartContents() if the stash
2349
+ * expired (e.g. the user reloaded
2350
+ * between clicking and submitting)
2351
+ *
2352
+ * Capture phase + non-passive so we get the submit BEFORE ASC's
2353
+ * own jQuery validator can call preventDefault on an invalid form;
2354
+ * we still fire the event so the funnel sees the attempt. The
2355
+ * stash is cleared after a successful read so a subsequent
2356
+ * unrelated form submission can't accidentally inherit it.
2357
+ */
2358
+ function installShareFormHook() {
2359
+ if (window.__ilColabShareFormHooked) return;
2360
+ window.__ilColabShareFormHooked = true;
2361
+
2362
+ document.addEventListener('submit', function (e) {
2363
+ var form = e.target;
2364
+ if (!form || form.nodeType !== 1) return;
2365
+ var matchSelf = false;
2366
+ try { matchSelf = form.matches && form.matches(SELECTORS.shareModal); } catch (err) { /* ignore */ }
2367
+ // The event target IS the form, but be defensive in case the
2368
+ // template ever wraps the submission in a parent element.
2369
+ if (!matchSelf) {
2370
+ var ancestor = null;
2371
+ try { ancestor = form.closest && form.closest(SELECTORS.shareModal); } catch (err) { /* ignore */ }
2372
+ if (!ancestor) return;
2373
+ form = ancestor;
2374
+ }
2375
+
2376
+ var emailInput = form.querySelector(SELECTORS.shareEmailInput);
2377
+ var emails = parseRecipientEmails(emailInput && emailInput.value);
2378
+ var emailsJoined = emails.join(',');
2379
+ if (emailsJoined.length > 480) emailsJoined = emailsJoined.slice(0, 480);
2380
+
2381
+ // "Share Publicly" — the explicit checkbox match comes first.
2382
+ // If multiple checkboxes exist in the form (some themes add a
2383
+ // T&C tickbox), we look for the one paired with the "Share
2384
+ // Publicly" label by walking up to the .ui.checkbox wrapper.
2385
+ var publicChecked = false;
2386
+ var cbCandidates = form.querySelectorAll(SELECTORS.sharePublicCheckbox);
2387
+ for (var i = 0; i < cbCandidates.length; i++) {
2388
+ var cb = cbCandidates[i];
2389
+ var wrap = cb.closest('.ui.checkbox, .field');
2390
+ var lbl = wrap && (wrap.querySelector('label') || wrap);
2391
+ var txt = lbl ? (lbl.textContent || '').trim() : '';
2392
+ if (cbCandidates.length === 1 || /share\s*publicly/i.test(txt)) {
2393
+ publicChecked = !!cb.checked;
2394
+ break;
2395
+ }
2396
+ }
2397
+
2398
+ var startEl = form.querySelector(SELECTORS.shareStartDateInput);
2399
+ var expiryEl = form.querySelector(SELECTORS.shareExpiryDateInput);
2400
+ var startDate = (startEl && startEl.value) || '';
2401
+ var expiryDate = (expiryEl && expiryEl.value) || '';
2402
+ // Heuristic — if the dates are populated but the checkbox
2403
+ // matcher missed (e.g. the theme rebrands the label), treat
2404
+ // the share as public anyway. Better to over-tag than miss
2405
+ // the public-share population entirely.
2406
+ if (!publicChecked && (startDate || expiryDate)) publicChecked = true;
2407
+
2408
+ var rangeDays = 0;
2409
+ if (startDate && expiryDate) {
2410
+ var s = Date.parse(startDate);
2411
+ var e2 = Date.parse(expiryDate);
2412
+ if (!isNaN(s) && !isNaN(e2)) rangeDays = Math.max(0, Math.round((e2 - s) / 86400000));
2413
+ }
2414
+
2415
+ var stash = window.__ilColabPendingCartShare;
2416
+ var stashFresh = stash && (Date.now() - stash.captured_at < 10 * 60 * 1000);
2417
+ var pathsJson, pathsCount;
2418
+ if (stashFresh) {
2419
+ pathsJson = stash.paths_json || '';
2420
+ pathsCount = (stash.paths && stash.paths.length) || 0;
2421
+ } else {
2422
+ var fresh = readCartContents();
2423
+ pathsJson = fresh.length ? JSON.stringify(fresh) : '';
2424
+ if (pathsJson.length > 480) pathsJson = pathsJson.slice(0, 480);
2425
+ pathsCount = fresh.length;
2426
+ }
2427
+ window.__ilColabPendingCartShare = null;
2428
+
2429
+ track('cart_share', {
2430
+ share_emails: emailsJoined,
2431
+ share_is_public: publicChecked ? 'true' : 'false',
2432
+ share_start_date: publicChecked ? startDate : '',
2433
+ share_end_date: publicChecked ? expiryDate : '',
2434
+ cart_asset_paths_json: pathsJson,
2435
+ page_url: location.href,
2436
+ page_referrer: document.referrer || ''
2437
+ }, {
2438
+ share_emails_count: emails.length,
2439
+ share_date_range_days: rangeDays,
2440
+ cart_item_count: pathsCount
2441
+ }, 'cart_action');
2442
+ }, { capture: true });
2443
+ }
2444
+
2445
+ // ─── 9b. Asset Explorer (React) hooks ────────────────────
2446
+
2447
+ /**
2448
+ * Wires every plausible search trigger on /asset-explorer.html. The
2449
+ * page is a React SPA that doesn't expose a single canonical "search
2450
+ * submit" event, so we listen at the document level (capture phase)
2451
+ * for the four observed user intents:
2452
+ *
2453
+ * - Enter pressed inside the search input
2454
+ * - Native form submit (Enter or a button reachable via submit())
2455
+ * - The Search Options modal closing (treated as "user accepted
2456
+ * semantic/fuzzy choice and the search will now run")
2457
+ * - A click on any element inside the right-rail filter wrapper
2458
+ * (treated as "user changed a facet and a new search will run")
2459
+ *
2460
+ * Plus a debounced `input` listener so live-typing scenarios — if any —
2461
+ * still record the eventual term. Every fire carries a `search_trigger`
2462
+ * dimension so we can drop the redundant hooks once we see what the
2463
+ * page actually emits in ClickHouse.
2464
+ *
2465
+ * Dedup is centralized inside trackAssetExplorerSearch() via
2466
+ * __aeLastFiredSig so overlapping triggers (Enter + form submit) on the
2467
+ * same user action collapse into a single event.
2468
+ */
2469
+ function installAssetExplorerHooks() {
2470
+ if (window.__ilColabAEHooked) return;
2471
+ window.__ilColabAEHooked = true;
2472
+
2473
+ function currentTerm() {
2474
+ var inp = findAssetExplorerSearchInput();
2475
+ return inp ? (inp.value || '').trim() : '';
2476
+ }
2477
+
2478
+ function fireWithTrigger(trigger) {
2479
+ var term = currentTerm();
2480
+ if (!term) return;
2481
+ trackAssetExplorerSearch(term, { trigger: trigger });
2482
+ }
2483
+
2484
+ // ── 1. Enter inside the search input ─────────────────────
2485
+ document.addEventListener('keydown', function (e) {
2486
+ if (e.key !== 'Enter' && e.keyCode !== 13) return;
2487
+ var t = e.target;
2488
+ if (!t || t.nodeType !== 1) return;
2489
+ // Match either the explorer's React input OR any text input that
2490
+ // sits under the explorer root (themed deployments may swap the
2491
+ // CSS-Module class).
2492
+ var inExplorer = t.closest && t.closest(SELECTORS.assetExplorerRoot);
2493
+ if (!inExplorer) return;
2494
+ if (t.tagName !== 'INPUT' && t.tagName !== 'TEXTAREA') return;
2495
+ setTimeout(function () { fireWithTrigger('enter'); }, 0);
2496
+ }, { capture: true });
2497
+
2498
+ // ── 2. Native form submit ────────────────────────────────
2499
+ document.addEventListener('submit', function (e) {
2500
+ var f = e.target;
2501
+ if (!f || !f.closest) return;
2502
+ if (!f.closest(SELECTORS.assetExplorerRoot)) return;
2503
+ setTimeout(function () { fireWithTrigger('submit'); }, 0);
2504
+ }, { capture: true });
2505
+
2506
+ // ── 3. Search Options modal close ───────────────────────
2507
+ // We can't always observe the modal-close gesture directly (escape
2508
+ // key, clicking the backdrop, clicking a confirm button). Instead,
2509
+ // watch for the modal element being REMOVED from the DOM and treat
2510
+ // that as "user finished tweaking semantic/fuzzy".
2511
+ if (typeof MutationObserver === 'function') {
2512
+ var modalState = { open: false };
2513
+ try {
2514
+ var mo = new MutationObserver(function () {
2515
+ var modal = document.querySelector(
2516
+ '[class*="_searchOptionModal_"], [class*="_searchOption_Modal_"], [class*="_searchOptionsModal_"]'
2517
+ );
2518
+ var nowOpen = !!modal;
2519
+ if (modalState.open && !nowOpen) {
2520
+ setTimeout(function () { fireWithTrigger('options_close'); }, 0);
2521
+ }
2522
+ modalState.open = nowOpen;
2523
+ });
2524
+ mo.observe(document.body || document.documentElement, {
2525
+ childList: true,
2526
+ subtree: true
2527
+ });
2528
+ } catch (e) { /* fall through */ }
2529
+ }
2530
+
2531
+ // ── 4. Filter-rail clicks ───────────────────────────────
2532
+ document.addEventListener('click', function (e) {
2533
+ var t = e.target;
2534
+ if (!t || !t.closest) return;
2535
+ var rail = t.closest(SELECTORS.assetExplorerFilterRail);
2536
+ if (!rail) return;
2537
+ // Defer past React's re-render so the term + stats reflect the
2538
+ // new filter state when we read them.
2539
+ setTimeout(function () {
2540
+ // We bypass the term-empty check via forceDedupBypass=false so
2541
+ // a filter-only narrow over an empty search isn't tracked here;
2542
+ // it falls into folder_navigation territory.
2543
+ fireWithTrigger('filter_click');
2544
+ }, 30);
2545
+ }, { capture: true });
2546
+
2547
+ // ── 5. Debounced typing (catch-all for auto-search builds) ──
2548
+ var debounceTimer = null;
2549
+ document.addEventListener('input', function (e) {
2550
+ var t = e.target;
2551
+ if (!t || t.nodeType !== 1) return;
2552
+ if (t.tagName !== 'INPUT') return;
2553
+ if (!t.closest || !t.closest(SELECTORS.assetExplorerRoot)) return;
2554
+ var inp = findAssetExplorerSearchInput();
2555
+ if (!inp || t !== inp) return;
2556
+ if (debounceTimer) clearTimeout(debounceTimer);
2557
+ debounceTimer = setTimeout(function () {
2558
+ fireWithTrigger('input_debounced');
2559
+ }, 800);
2560
+ }, { capture: true });
2561
+
2562
+ // ── 6. Hash-route folder navigation ─────────────────────
2563
+ window.addEventListener('hashchange', function () {
2564
+ // Reset the search-event dedup signature so the new folder's first
2565
+ // search records cleanly even if its (term, toggles) happen to
2566
+ // match the previous folder's.
2567
+ __aeLastFiredSig = '';
2568
+ trackAssetExplorerFolderNavigation({ tree_action: 'hash_change' });
2569
+ });
2570
+
2571
+ // ── 7. Folder-tree click delegation ─────────────────────
2572
+ // Every click anywhere inside the side directory tree fires
2573
+ // folder_navigation(subtype=asset_browse) so we observe folder
2574
+ // selections (which usually also trigger hashchange) AND
2575
+ // expand/collapse gestures (which do not). We best-effort classify
2576
+ // the action via aria-expanded mutation, fall back to "click" if
2577
+ // we can't tell, and tag the event with diagnostic dims so the
2578
+ // refinement is data-driven from ClickHouse.
2579
+ document.addEventListener('click', function (e) {
2580
+ var target = e.target;
2581
+ if (!target || target.nodeType !== 1 || !target.closest) return;
2582
+ var tree = target.closest(SELECTORS.assetExplorerFolderTree);
2583
+ if (!tree) return;
2584
+ // Skip clicks that landed in the rail's facet panel — that's the
2585
+ // right side (search_executed/filter_click territory), not the
2586
+ // left tree. The selectors *can* overlap on extremely permissive
2587
+ // builds where both panels share `_wrapper_` ancestors.
2588
+ if (target.closest(SELECTORS.assetExplorerFilterRail)) return;
2589
+
2590
+ // Find the closest folder-row element so we can capture the
2591
+ // folder label (visible text) and the aria-expanded state.
2592
+ // Tree-row markup we expect (best-effort):
2593
+ // [role="treeitem"] | [class*="_treeNode_"] | [class*="_node_"]
2594
+ // | the immediate clickable wrapper (`<li>` / `<button>`).
2595
+ var node = target.closest(
2596
+ '[role="treeitem"], [class*="_treeNode_"], [class*="_node_"], [class*="_folder_"], [class*="_item_"], li, button, a'
2597
+ ) || target;
2598
+
2599
+ var labelEl = node.querySelector('[class*="_label_"], [class*="_name_"], [class*="_title_"]') || node;
2600
+ var label = cleanText(labelEl.textContent || '').slice(0, 120);
2601
+
2602
+ var preExpanded = node.getAttribute && node.getAttribute('aria-expanded');
2603
+
2604
+ // Sample the className for diagnostic use — strip whitespace and
2605
+ // cap aggressively to avoid blowing the custom_dimensions column.
2606
+ var cls = (target.className && target.className.baseVal !== undefined)
2607
+ ? target.className.baseVal
2608
+ : String(target.className || '');
2609
+
2610
+ // Snapshot the node's current className too — some React tree
2611
+ // libs put the expanded/collapsed state directly on the row
2612
+ // (`_isOpen`, `_expanded`, `_collapsed`, `_open`) rather than on
2613
+ // an aria-expanded attribute, so we'll need both pre- and post-
2614
+ // click className samples to classify the gesture.
2615
+ var preNodeCls = (node.className && node.className.baseVal !== undefined)
2616
+ ? node.className.baseVal
2617
+ : String(node.className || '');
2618
+
2619
+ // Live React Asset Explorer uses classes like `_toggleIcon_<hash>`
2620
+ // on the expand/collapse chevron. Anything matching one of these
2621
+ // unambiguous "this is a toggle gesture" prefixes is treated as
2622
+ // an expand/collapse even when aria-expanded never shows up.
2623
+ var TOGGLE_CLS_RE = /(?:^|[\s_-])(?:_?toggleIcon|_?toggle|_?chevron|_?arrow|_?caret|_?expand(?:er|Icon)?|_?collapse(?:r|Icon)?)(?:[\s_-]|$)/i;
2624
+ var isToggle = TOGGLE_CLS_RE.test(cls);
2625
+
2626
+ // Defer to the next tick so the React state has had time to apply
2627
+ // the click (aria-expanded flips, classNames toggled, hash routes
2628
+ // pushed, etc.) before we classify. The hashchange listener above
2629
+ // is independent and will fire its own event if the URL changes.
2630
+ setTimeout(function () {
2631
+ var postExpanded = node.getAttribute && node.getAttribute('aria-expanded');
2632
+ var postNodeCls = (node.className && node.className.baseVal !== undefined)
2633
+ ? node.className.baseVal
2634
+ : String(node.className || '');
2635
+
2636
+ // ── Strategy 1: aria-expanded mutation ───────────────
2637
+ var action = null;
2638
+ if (preExpanded !== null && postExpanded !== null && preExpanded !== postExpanded) {
2639
+ action = (postExpanded === 'true') ? 'expand' : 'collapse';
2640
+ } else if (postExpanded === 'true' && preExpanded === null) {
2641
+ action = 'expand';
2642
+ } else if (postExpanded === 'false' && preExpanded === null) {
2643
+ action = 'collapse';
2644
+ }
2645
+
2646
+ // ── Strategy 2: className state on the row ───────────
2647
+ // React tree libs commonly emit `_isOpen_<hash>` / `_expanded_<hash>`
2648
+ // / `_isCollapsed_<hash>` / `_collapsed_<hash>` on the row when
2649
+ // the open state changes. Compare pre vs post — if either flag
2650
+ // appeared / disappeared, that's our action.
2651
+ if (!action) {
2652
+ var EXP_RE = /_(?:isOpen|expanded|open(?![A-Za-z]))/i;
2653
+ var COLL_RE = /_(?:isClosed|collapsed|closed)/i;
2654
+ var preExp = EXP_RE.test(preNodeCls);
2655
+ var postExp = EXP_RE.test(postNodeCls);
2656
+ var preColl = COLL_RE.test(preNodeCls);
2657
+ var postColl = COLL_RE.test(postNodeCls);
2658
+ if (!preExp && postExp) action = 'expand';
2659
+ else if (preExp && !postExp) action = 'collapse';
2660
+ else if (!preColl && postColl) action = 'collapse';
2661
+ else if (preColl && !postColl) action = 'expand';
2662
+ }
2663
+
2664
+ // ── Strategy 3: toggle-class hint without direction ──
2665
+ // Click landed on an unambiguous toggle icon but we couldn't
2666
+ // determine direction from the row state. Record the gesture
2667
+ // as a generic `toggle` — still strictly more useful than
2668
+ // `click` because dashboards can split tree-navigation events
2669
+ // from open/close gestures.
2670
+ if (!action) {
2671
+ action = isToggle ? 'toggle' : 'click';
2672
+ }
2673
+
2674
+ // The handler also fires for clicks that ALSO trigger a hash
2675
+ // change. We DO NOT dedup against the hashchange-fired event
2676
+ // here — the user explicitly asked for every click / expand /
2677
+ // collapse gesture to be tracked, so emitting both a click
2678
+ // event AND a hash_change event for the same gesture is the
2679
+ // desired behaviour. Differentiate via the `tree_action` dim
2680
+ // in reports.
2681
+ trackAssetExplorerFolderNavigation({
2682
+ tree_action: action,
2683
+ tree_target_label: label,
2684
+ tree_target_class_hint: cls
2685
+ });
2686
+ }, 0);
2687
+ }, { capture: true });
2688
+ }
2689
+
2690
+ // ─── 10. Network interception for downloads ──────────────
2691
+
2692
+ /**
2693
+ * Emits `asset_download` if a request matches the ASC download endpoint.
2694
+ * Extracts `asset_path` (`path`) and `rendition_name` (`renditionName`)
2695
+ * directly from the form-encoded POST body so the event reflects exactly
2696
+ * what the user requested (single-asset, ZIP of renditions, etc.).
2697
+ */
2698
+ function emitDownloadIfMatch(method, url, body) {
2699
+ if (!url) return;
2700
+ if (method && String(method).toUpperCase() !== 'POST') return;
2701
+ if (!ENDPOINTS.download.test(url)) return;
2702
+ var info = parseFormBody(body);
2703
+ track('asset_download', {
2704
+ asset_path: safeStr(info.path),
2705
+ rendition_name: safeStr(info.renditionName),
2706
+ download_endpoint: url,
2707
+ page_url: location.href
2708
+ });
2709
+ }
2710
+
2711
+ /**
2712
+ * Wraps `window.fetch` and `XMLHttpRequest.prototype.{open,send}` once
2713
+ * per page. Idempotent across hot-reloads of the bootstrap. Always calls
2714
+ * the original implementation so site behavior is unchanged.
2715
+ */
2716
+ function installNetworkHooks() {
2717
+ if (typeof window.fetch === 'function' && !window.__ilColabFetchPatched) {
2718
+ window.__ilColabFetchPatched = true;
2719
+ var origFetch = window.fetch;
2720
+ window.fetch = function (input, init) {
2721
+ try {
2722
+ var url = typeof input === 'string' ? input : (input && input.url) || '';
2723
+ var method = (init && init.method) || (input && input.method) || 'GET';
2724
+ var body = init && init.body;
2725
+ emitDownloadIfMatch(method, url, body);
2726
+ } catch (e) { /* swallow — never break the page */ }
2727
+ return origFetch.apply(this, arguments);
2728
+ };
2729
+ }
2730
+
2731
+ if (typeof window.XMLHttpRequest === 'function' && !window.__ilColabXhrPatched) {
2732
+ window.__ilColabXhrPatched = true;
2733
+ var XHRProto = window.XMLHttpRequest.prototype;
2734
+ var origOpen = XHRProto.open;
2735
+ var origSend = XHRProto.send;
2736
+ XHRProto.open = function (method, url) {
2737
+ this.__ilColabMethod = method;
2738
+ this.__ilColabUrl = url;
2739
+ return origOpen.apply(this, arguments);
2740
+ };
2741
+ XHRProto.send = function (body) {
2742
+ try { emitDownloadIfMatch(this.__ilColabMethod, this.__ilColabUrl, body); } catch (e) {}
2743
+ return origSend.apply(this, arguments);
2744
+ };
2745
+ }
2746
+ }
2747
+
2748
+ // ─── 11. Orchestration ───────────────────────────────────
2749
+
2750
+ var HOOK_FLAG = '__il_colab_hooked__';
2751
+
2752
+ /**
2753
+ * Login-page hook installer. Idempotent thanks to per-element flags so the
2754
+ * MutationObserver can re-run safely as the SPA mounts late controls.
2755
+ */
2756
+ function safeHookLoginAll() {
2757
+ function once(el, name, fn) {
2758
+ if (!el || el[HOOK_FLAG + name]) return;
2759
+ el[HOOK_FLAG + name] = true;
2760
+ fn();
2761
+ }
2762
+ var form = $(SELECTORS.loginForm);
2763
+ var signBtn = $(SELECTORS.signInButton)
2764
+ || closestMatchByText(document, 'button, a, [role="button"], input[type="submit"]', TEXT_PATTERNS.signIn);
2765
+ var ssoBtn = $(SELECTORS.ssoButton)
2766
+ || closestMatchByText(document, 'button, a, [role="button"]', TEXT_PATTERNS.lionSso);
2767
+ var terms = $(SELECTORS.termsLink)
2768
+ || closestMatchByText(document, 'a, button, [role="link"]', TEXT_PATTERNS.terms);
2769
+
2770
+ once(form, 'form', function () {
2771
+ form.addEventListener('submit', function () {
2772
+ var userInput = $(SELECTORS.userField);
2773
+ var typedUser = (userInput && (userInput.value || '').trim()) || '';
2774
+ if (typedUser) identify(typedUser);
2775
+ track('login_attempt', {
2776
+ method: 'credentials',
2777
+ attempt_user: typedUser,
2778
+ submit_reason: 'submit',
2779
+ page_url: location.href
2780
+ });
2781
+ flush();
2782
+ }, { capture: true });
2783
+ });
2784
+
2785
+ once(signBtn, 'sign', function () {
2786
+ signBtn.addEventListener('click', function () {
2787
+ var userInput = $(SELECTORS.userField);
2788
+ var typedUser = (userInput && (userInput.value || '').trim()) || '';
2789
+ if (typedUser) identify(typedUser);
2790
+ track('login_attempt', {
2791
+ method: 'credentials',
2792
+ attempt_user: typedUser,
2793
+ submit_reason: 'click',
2794
+ page_url: location.href
2795
+ });
2796
+ flush();
2797
+ }, { capture: true });
2798
+ });
2799
+
2800
+ once(ssoBtn, 'sso', function () {
2801
+ ssoBtn.addEventListener('click', function () {
2802
+ track('sso_click', {
2803
+ method: 'lion_login',
2804
+ sso_provider: 'lion',
2805
+ button_text: visibleText(ssoBtn).substring(0, 120),
2806
+ page_url: location.href
2807
+ });
2808
+ flush();
2809
+ }, { capture: true });
2810
+ });
2811
+
2812
+ once(terms, 'terms', function () {
2813
+ terms.addEventListener('click', function () {
2814
+ track('terms_click', {
2815
+ link_url: (terms.getAttribute && terms.getAttribute('href')) || '',
2816
+ link_text: visibleText(terms).substring(0, 120),
2817
+ page_url: location.href
2818
+ });
2819
+ flush();
2820
+ }, { capture: true });
2821
+ });
2822
+ }
2823
+
2824
+ function start() {
2825
+ if (!initSdk()) {
2826
+ console.warn('[IL-COLAB] Infralytiqs SDK not loaded — bootstrap aborted');
2827
+ return;
2828
+ }
2829
+
2830
+ // Identity FIRST so subsequent events carry user_id.
2831
+ // (Cache-hit path is sync; Granite-fetch path updates identity for the
2832
+ // next event batch — pre-flush events are already correctly tagged via
2833
+ // the SDK's identify-then-flush ordering.)
2834
+ resolveAndIdentifyUser();
2835
+
2836
+ // URL-driven events (fire once on page load), dispatched by context.
2837
+ if (isLoginPage()) {
2838
+ trackLoginPageView();
2839
+ safeHookLoginAll();
2840
+
2841
+ if (typeof MutationObserver === 'function') {
2842
+ var mo = new MutationObserver(function () { safeHookLoginAll(); });
2843
+ mo.observe(document.documentElement || document.body, {
2844
+ childList: true,
2845
+ subtree: true
2846
+ });
2847
+ // Stop watching after 20s — by then the SPA has settled and anything
2848
+ // we missed isn't going to appear from a page-load mutation.
2849
+ setTimeout(function () { mo.disconnect(); }, 20000);
2850
+ }
2851
+ } else if (isAssetExplorerPage()) {
2852
+ // React-based Asset Explorer (/asset-explorer.html#/content/dam/...)
2853
+ // — search and folder browsing live entirely in client-side state,
2854
+ // so we rely on DOM event hooks rather than URL parsing.
2855
+ installAssetExplorerHooks();
2856
+ // Asset preview / download / cart / share interactions piggy-back on
2857
+ // the same delegated listeners as ASC. They're a no-op if the page
2858
+ // doesn't render those affordances.
2859
+ installAscClickDelegation();
2860
+ installShareFormHook();
2861
+ installNetworkHooks();
2862
+ // Initial folder-view ping so reports see the user landed.
2863
+ // tagged "page_load" to distinguish from later interactions.
2864
+ trackAssetExplorerFolderNavigation({ tree_action: 'page_load' });
2865
+ } else {
2866
+ var q = parseQuery();
2867
+ trackSearchExecuted(q);
2868
+ trackAssetPreview();
2869
+ installAscClickDelegation();
2870
+ installShareFormHook();
2871
+ installNetworkHooks();
2872
+ // ASC drives in-page filter / sort / layout / pagination changes
2873
+ // through history.pushState — without this our URL-driven events
2874
+ // would only fire on hard reloads.
2875
+ installSpaNavHooks();
2876
+ }
2877
+ }
2878
+
2879
+ // ─── 12. Entry point ─────────────────────────────────────
2880
+ function waitForSdkAndStart() {
2881
+ var attempts = 0;
2882
+ var max = 50;
2883
+ (function tick() {
2884
+ if (getApi()) {
2885
+ start();
2886
+ return;
2887
+ }
2888
+ if (++attempts >= max) {
2889
+ console.warn('[IL-COLAB] Infralytiqs SDK never appeared after ' + (max * 100) + 'ms');
2890
+ return;
2891
+ }
2892
+ setTimeout(tick, 100);
2893
+ })();
2894
+ }
2895
+
2896
+ if (document.readyState === 'loading') {
2897
+ document.addEventListener('DOMContentLoaded', waitForSdkAndStart, { once: true });
2898
+ } else {
2899
+ waitForSdkAndStart();
2900
+ }
2901
+ })();