admesh-ui-sdk 1.0.8 โ 1.0.10
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.
- package/CHANGELOG.md +41 -0
- package/README.md +26 -0
- package/dist/components/AdMeshLayout.d.ts.map +1 -1
- package/dist/components/AdMeshProductCard.d.ts.map +1 -1
- package/dist/components/AdMeshSummaryLayout.d.ts +1 -0
- package/dist/components/AdMeshSummaryLayout.d.ts.map +1 -1
- package/dist/components/AdMeshSummaryUnit.d.ts +1 -0
- package/dist/components/AdMeshSummaryUnit.d.ts.map +1 -1
- package/dist/components/AdMeshViewabilityTracker.d.ts +6 -0
- package/dist/components/AdMeshViewabilityTracker.d.ts.map +1 -1
- package/dist/components/WeaveAdFormatContainer.d.ts.map +1 -1
- package/dist/hooks/useWeaveAdFormat.d.ts.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +924 -809
- package/dist/index.mjs.map +1 -1
- package/dist/sdk/AdMeshRenderer.d.ts.map +1 -1
- package/dist/sdk/AdMeshSDK.d.ts.map +1 -1
- package/dist/sdk/WeaveResponseProcessor.d.ts +7 -2
- package/dist/sdk/WeaveResponseProcessor.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/inlineExposureTracker.d.ts +17 -0
- package/dist/utils/inlineExposureTracker.d.ts.map +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,47 @@ All notable changes to the AdMesh UI SDK will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.0.10] - 2025-11-18
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Inline exposure tracker for Weave links**: new utility monitors detected AdMesh anchors (50% visible for 1s) before firing their signed `exposure_url`, preventing premature pixels in organic/inline responses.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
- **WeaveAdFormatContainer & useWeaveAdFormat** now fire exposure pixels only when in-view, leveraging the inline tracker and properly passing `sessionId` for deduplication.
|
|
15
|
+
- TypeScript build now emits declarations for the new tracker and tightened callback types.
|
|
16
|
+
|
|
17
|
+
### Breaking
|
|
18
|
+
- `WeaveResponseProcessor.scanAndProcessLinks` now invokes the `onExposurePixel` callback with an object `{ exposureUrl, adId, linkElement }` so consumers have access to the DOM node required for viewability tracking. Update custom integrations accordingly.
|
|
19
|
+
|
|
20
|
+
## [1.0.9] - 2025-11-17
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
- **๐จ CRITICAL: Fixed exposure tracking system** - Exposure pixels now fire correctly when ads meet MRC viewability standards
|
|
24
|
+
- Added exposure pixel firing to `AdMeshViewabilityTracker` component
|
|
25
|
+
- Exposure pixels fire when ads are 50% visible for 1 continuous second (MRC-compliant)
|
|
26
|
+
- Removed legacy immediate exposure firing from `AdMeshSDK` (non-MRC compliant)
|
|
27
|
+
- Added `exposureUrl`, `sessionId`, and `recommendationId` props to `AdMeshViewabilityTracker`
|
|
28
|
+
- Added `sessionId` prop threading through component tree (`AdMeshProductCard` โ `AdMeshSummaryLayout` โ `AdMeshLayout` โ `AdMeshRenderer`)
|
|
29
|
+
- Prevents duplicate exposure tracking with `exposureFired` ref
|
|
30
|
+
- Uses `fetch()` with `keepalive: true` for reliable pixel firing even during page unload
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
- **Exposure tracking lifecycle**: Recommendations now transition from `generated` โ `exposed` only when MRC viewability threshold is met
|
|
34
|
+
- **CPX billing**: Exposure pixels fire on viewability, not on recommendation fetch
|
|
35
|
+
- **Analytics**: More accurate exposure tracking aligned with industry standards (MRC viewability)
|
|
36
|
+
|
|
37
|
+
### Technical Details
|
|
38
|
+
- Exposure pixel fires via `fetch(exposureUrl, { method: 'GET', keepalive: true })`
|
|
39
|
+
- Viewability threshold: 50% of ad pixels visible for 1 continuous second
|
|
40
|
+
- Backend `/exposure` endpoint receives pixel and updates recommendation status atomically
|
|
41
|
+
- CPX budget reservation happens when exposure pixel fires, not when recommendations are generated
|
|
42
|
+
|
|
43
|
+
### Migration Notes
|
|
44
|
+
- **No breaking changes** - This is a bug fix release
|
|
45
|
+
- Existing integrations will automatically benefit from MRC-compliant exposure tracking
|
|
46
|
+
- No code changes required in your integration
|
|
47
|
+
- Exposure tracking will be more accurate and aligned with industry standards
|
|
48
|
+
|
|
8
49
|
## [1.0.0] - 2025-10-27
|
|
9
50
|
|
|
10
51
|
### BREAKING CHANGES
|
package/README.md
CHANGED
|
@@ -209,6 +209,32 @@ await admesh.showRecommendations({
|
|
|
209
209
|
});
|
|
210
210
|
```
|
|
211
211
|
|
|
212
|
+
## ๐ Advanced: Inline Weave Exposure Tracking
|
|
213
|
+
|
|
214
|
+
When working directly with `WeaveResponseProcessor` you now receive richer context for exposure tracking. The optional `onExposurePixel` callback passed to `scanAndProcessLinks()` is invoked with `{ exposureUrl, adId, linkElement }`, enabling you to plug the DOM node into your own IntersectionObserver logic (or the SDKโs helper).
|
|
215
|
+
|
|
216
|
+
```typescript
|
|
217
|
+
import {
|
|
218
|
+
WeaveResponseProcessor,
|
|
219
|
+
createInlineExposureTracker
|
|
220
|
+
} from 'admesh-ui-sdk';
|
|
221
|
+
|
|
222
|
+
const processor = new WeaveResponseProcessor();
|
|
223
|
+
const inlineTracker = createInlineExposureTracker();
|
|
224
|
+
|
|
225
|
+
processor.scanAndProcessLinks(container, recommendations, ({ exposureUrl, adId, linkElement }) => {
|
|
226
|
+
inlineTracker.startTracking({
|
|
227
|
+
exposureUrl,
|
|
228
|
+
adId,
|
|
229
|
+
linkElement,
|
|
230
|
+
sessionId: currentSessionId,
|
|
231
|
+
logPrefix: '[CustomInlineTracking]'
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
This guarantees inline/weave ads also respect the MRC requirement (50โฏ% visible for 1โฏs) before firing pixels, and keeps exposure deduplication tied to your `sessionId`.
|
|
237
|
+
|
|
212
238
|
## โจ Self-Contained Design
|
|
213
239
|
|
|
214
240
|
**Zero configuration required!** The AdMesh UI SDK is completely self-contained and works like Google Ads or any professional SDK:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdMeshLayout.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshLayout.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAGxD,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,
|
|
1
|
+
{"version":3,"file":"AdMeshLayout.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshLayout.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAGxD,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAwCpD,CAAC;AAEF,eAAe,YAAY,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdMeshProductCard.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshProductCard.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAS7D,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAAC,sBAAsB,
|
|
1
|
+
{"version":3,"file":"AdMeshProductCard.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshProductCard.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAS7D,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAAC,sBAAsB,CA6R9D,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdMeshSummaryLayout.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshSummaryLayout.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAIxE,MAAM,WAAW,wBAAwB;IAEvC,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IAGrB,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAG5B,WAAW,CAAC,EAAE,CAAC,cAAc,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAG7D,QAAQ,CAAC,EAAE;QACT,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,eAAe,CAAC,EAAE,oBAAoB,EAAE,CAAC;QACzC,gBAAgB,CAAC,EAAE,OAAO,CAAC;KAC5B,CAAC;CACH;AAED,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,wBAAwB,
|
|
1
|
+
{"version":3,"file":"AdMeshSummaryLayout.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshSummaryLayout.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAIxE,MAAM,WAAW,wBAAwB;IAEvC,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IAGrB,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAG5B,WAAW,CAAC,EAAE,CAAC,cAAc,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAG7D,SAAS,CAAC,EAAE,MAAM,CAAC;IAGnB,QAAQ,CAAC,EAAE;QACT,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,eAAe,CAAC,EAAE,oBAAoB,EAAE,CAAC;QACzC,gBAAgB,CAAC,EAAE,OAAO,CAAC;KAC5B,CAAC;CACH;AAED,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,wBAAwB,CA2DlE,CAAC;AAEF,eAAe,mBAAmB,CAAC"}
|
|
@@ -7,6 +7,7 @@ export interface AdMeshSummaryUnitProps {
|
|
|
7
7
|
className?: string;
|
|
8
8
|
style?: React.CSSProperties;
|
|
9
9
|
onLinkClick?: (recommendation: AdMeshRecommendation) => void;
|
|
10
|
+
sessionId?: string;
|
|
10
11
|
}
|
|
11
12
|
export declare const AdMeshSummaryUnit: React.FC<AdMeshSummaryUnitProps>;
|
|
12
13
|
export default AdMeshSummaryUnit;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdMeshSummaryUnit.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshSummaryUnit.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAGxE,MAAM,WAAW,sBAAsB;IACrC,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,WAAW,CAAC,EAAE,CAAC,cAAc,EAAE,oBAAoB,KAAK,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"AdMeshSummaryUnit.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshSummaryUnit.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAGxE,MAAM,WAAW,sBAAsB;IACrC,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,WAAW,CAAC,EAAE,CAAC,cAAc,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA6LD,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAuE9D,CAAC;AAEF,eAAe,iBAAiB,CAAC"}
|
|
@@ -9,6 +9,12 @@ export interface AdMeshViewabilityTrackerProps {
|
|
|
9
9
|
offerId?: string;
|
|
10
10
|
/** Agent ID */
|
|
11
11
|
agentId?: string;
|
|
12
|
+
/** Recommendation ID (for exposure tracking) */
|
|
13
|
+
recommendationId?: string;
|
|
14
|
+
/** Exposure URL (for MRC-compliant exposure pixel firing) */
|
|
15
|
+
exposureUrl?: string;
|
|
16
|
+
/** Session ID (for exposure tracking) */
|
|
17
|
+
sessionId?: string;
|
|
12
18
|
/** Children to wrap with viewability tracking */
|
|
13
19
|
children: React.ReactNode;
|
|
14
20
|
/** Custom viewability tracker configuration */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdMeshViewabilityTracker.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshViewabilityTracker.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAA4B,MAAM,OAAO,CAAC;AAEjD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAEnE,MAAM,WAAW,6BAA6B;IAC5C,YAAY;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,iBAAiB;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iDAAiD;IACjD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,+CAA+C;IAC/C,MAAM,CAAC,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAC;IAC3C,qBAAqB;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB;IACpB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,8CAA8C;IAC9C,mBAAmB,CAAC,EAAE,CAAC,UAAU,EAAE,OAAO,KAAK,IAAI,CAAC;IACpD,uCAAuC;IACvC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IACvB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,wBAAwB,EAAE,KAAK,CAAC,EAAE,CAAC,6BAA6B,
|
|
1
|
+
{"version":3,"file":"AdMeshViewabilityTracker.d.ts","sourceRoot":"","sources":["../../src/components/AdMeshViewabilityTracker.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAA4B,MAAM,OAAO,CAAC;AAEjD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAEnE,MAAM,WAAW,6BAA6B;IAC5C,YAAY;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,iBAAiB;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gDAAgD;IAChD,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6DAA6D;IAC7D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yCAAyC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,+CAA+C;IAC/C,MAAM,CAAC,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAC;IAC3C,qBAAqB;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB;IACpB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,8CAA8C;IAC9C,mBAAmB,CAAC,EAAE,CAAC,UAAU,EAAE,OAAO,KAAK,IAAI,CAAC;IACpD,uCAAuC;IACvC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IACvB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,wBAAwB,EAAE,KAAK,CAAC,EAAE,CAAC,6BAA6B,CA0G5E,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeaveAdFormatContainer.d.ts","sourceRoot":"","sources":["../../src/components/WeaveAdFormatContainer.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAmD,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"WeaveAdFormatContainer.d.ts","sourceRoot":"","sources":["../../src/components/WeaveAdFormatContainer.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAmD,MAAM,OAAO,CAAC;AA4KxE,MAAM,WAAW,2BAA2B;IAC1C,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAC;IAElB,0DAA0D;IAC1D,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAE1B,iEAAiE;IACjE,cAAc,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;IAExC,uDAAuD;IACvD,eAAe,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAE1C,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,IAAI,CAAC;IAE/B,iCAAiC;IACjC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC,2CAA2C;IAC3C,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,mFAAmF;IACnF,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,CAAC,cAAc,EAAE,OAAO,KAAK,IAAI,CAAC;CACtD;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,sBAAsB,EAAE,KAAK,CAAC,EAAE,CAAC,2BAA2B,CA2DxE,CAAC;AAEF,eAAe,sBAAsB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useWeaveAdFormat.d.ts","sourceRoot":"","sources":["../../src/hooks/useWeaveAdFormat.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useWeaveAdFormat.d.ts","sourceRoot":"","sources":["../../src/hooks/useWeaveAdFormat.ts"],"names":[],"mappings":"AASA,MAAM,WAAW,uBAAuB;IACtC,4EAA4E;IAC5E,oBAAoB,EAAE,MAAM,CAAC;IAE7B,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,iEAAiE;IACjE,cAAc,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;IAExC,uDAAuD;IACvD,eAAe,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAE1C,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,IAAI,CAAC;IAE/B,iCAAiC;IACjC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC,8EAA8E;IAC9E,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,mFAAmF;IACnF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,GAAI,SAAS,uBAAuB;;;;;;CAqQhE,CAAC;AAEF,eAAe,gBAAgB,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -41,5 +41,7 @@ export type { UseWeaveAdFormatOptions } from './hooks/useWeaveAdFormat';
|
|
|
41
41
|
export type { AdMeshTheme } from './types/index';
|
|
42
42
|
export { dispatchStreamingStartEvent, dispatchStreamingCompleteEvent, onStreamingStart, onStreamingComplete, STREAMING_START_EVENT, STREAMING_COMPLETE_EVENT } from './utils/streamingEvents';
|
|
43
43
|
export type { StreamingStartEventDetail, StreamingCompleteEventDetail } from './utils/streamingEvents';
|
|
44
|
-
export
|
|
44
|
+
export { createInlineExposureTracker } from './utils/inlineExposureTracker';
|
|
45
|
+
export type { InlineExposureTracker, InlineExposureTrackingParams } from './utils/inlineExposureTracker';
|
|
46
|
+
export declare const VERSION = "1.0.10";
|
|
45
47
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,YAAY,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAGnF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAMlF,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,YAAY,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,YAAY,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AACrF,OAAO,EAAE,4BAA4B,EAAE,MAAM,2CAA2C,CAAC;AACzF,YAAY,EAAE,iCAAiC,EAAE,MAAM,2CAA2C,CAAC;AAGnG,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC1E,YAAY,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAChG,YAAY,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAG/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,YAAY,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAGvF,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,YAAY,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAGxE,YAAY,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACzB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,yBAAyB,EACzB,4BAA4B,EAC7B,MAAM,yBAAyB,CAAC;AAGjC,eAAO,MAAM,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,YAAY,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAGnF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAMlF,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,YAAY,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,YAAY,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AACrF,OAAO,EAAE,4BAA4B,EAAE,MAAM,2CAA2C,CAAC;AACzF,YAAY,EAAE,iCAAiC,EAAE,MAAM,2CAA2C,CAAC;AAGnG,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC1E,YAAY,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAChG,YAAY,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAG/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,YAAY,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAGvF,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,YAAY,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAGxE,YAAY,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACzB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,yBAAyB,EACzB,4BAA4B,EAC7B,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EACL,2BAA2B,EAC5B,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,qBAAqB,EACrB,4BAA4B,EAC7B,MAAM,+BAA+B,CAAC;AAGvC,eAAO,MAAM,OAAO,WAAW,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var be=Object.defineProperty;var xe=(t,e,r)=>e in t?be(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var L=(t,e,r)=>xe(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),ye=require("react-dom/client"),h=require("react");function we(t,e,r){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...r}}function ve(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function ke(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,n=window.innerWidth||document.documentElement.clientWidth,s=e.height,o=e.width;if(s===0||o===0)return 0;const a=Math.max(0,e.top),i=Math.min(r,e.bottom),c=Math.max(0,e.left),m=Math.min(n,e.right),l=Math.max(0,i-a),u=Math.max(0,m-c),p=l*u,f=s*o;return f>0?p/f:0}function G(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,n=e-t;return n<=0?100:Math.min(100,r/n*100)}function _e(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,n=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+n}}function Me(t){const e=t.getBoundingClientRect(),r=_e(t),n=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,o=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ve(n),viewportWidth:n,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:o,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function Se(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Ae(){return`batch_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Te(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function V(t=new Date){return t.toISOString()}function Ce(t){return t.length===0?0:t.reduce((r,n)=>r+n,0)/t.length}function Q(t,e){let r;return function(...s){r||(t(...s),r=!0,setTimeout(()=>r=!1,e))}}async function Ee(t,e,r=3,n=1e3){if(!e||e.trim()==="")return!0;let s=null;for(let o=0;o<r;o++){try{const a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});if(a.ok)return!0;const i=await a.text().catch(()=>"");s=new Error(`HTTP ${a.status}: ${a.statusText} - ${i}`)}catch(a){s=a}o<r-1&&await new Promise(a=>setTimeout(a,n*Math.pow(2,o)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",s),!1}async function Le(t,e,r,n=3,s=1e3){if(t.length===0||!r||r.trim()==="")return!0;const o={batchId:Ae(),sessionId:e,createdAt:V(),events:t,eventCount:t.length};let a=null;for(let i=0;i<n;i++){try{const c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});if(c.ok)return!0;const m=await c.text().catch(()=>"");a=new Error(`HTTP ${c.status}: ${c.statusText} - ${m}`)}catch(c){a=c}i<n-1&&await new Promise(c=>setTimeout(c,s*Math.pow(2,i)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",a),!1}const Re={enabled:!0,apiEndpoint:"https://api.useadmesh.com/api/recommendations/viewability/batch",enableBatching:!0,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let je=Re;function ee({adId:t,productId:e,offerId:r,agentId:n,recommendationId:s,elementRef:o,config:a}){const i={...je,...a},c=h.useRef(Se()),[m,l]=h.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:V(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:i.enabled}),u=h.useRef(null),p=h.useRef(null),f=h.useRef(null),k=h.useRef(null),y=h.useRef(null),_=h.useRef([]),b=h.useRef([]),S=h.useRef(null),M=h.useCallback((g,v)=>{i.debug&&console.log(`[AdMesh Viewability] ${g}`,v)},[i.debug]),w=h.useCallback(async(g,v)=>{if(!i.enabled||!o.current||!u.current)return;if(!["ad_viewable","ad_click"].includes(g)){M(`Skipping non-critical event: ${g} (only ad_viewable and ad_click are sent)`);return}const T=Me(o.current),x={eventType:g,timestamp:V(),sessionId:c.current,adId:t,productId:e,offerId:r,agentId:n,recommendationId:s,timeMetrics:m.timeMetrics,engagementMetrics:m.engagementMetrics,contextMetrics:T,mrcStandards:u.current,isViewable:m.isViewable,metadata:v};M(`Sending critical event: ${g}`,x),i.onEvent&&i.onEvent(x),i.enableBatching?(b.current.push(x),b.current.length>=i.batchSize?await C():(S.current&&clearTimeout(S.current),S.current=setTimeout(C,i.batchTimeout))):await Ee(x,i.apiEndpoint,i.maxRetries,i.retryDelay)},[i,t,e,r,n,o,m,M]),C=h.useCallback(async()=>{if(b.current.length===0)return;const g=[...b.current];b.current=[],S.current&&(clearTimeout(S.current),S.current=null),await Le(g,c.current,i.apiEndpoint,i.maxRetries,i.retryDelay)&&i.onBatchSent&&i.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:c.current,createdAt:V(),events:g,eventCount:g.length})},[i,M]),E=h.useCallback(Q(()=>{if(!o.current)return;const g=ke(o.current),v=Date.now(),A=new Date(m.timeMetrics.loadedAt).getTime();l(T=>{const x={...T};g>0&&_.current.push(g);const D=T.isVisible,I=g>0;if(I&&!D)p.current=v,x.engagementMetrics.viewportEnterCount++,x.timeMetrics.timeToFirstVisible||(x.timeMetrics.timeToFirstVisible=v-A,x.engagementMetrics.scrollDepthAtFirstVisible=G(),w("ad_visible"));else if(!I&&D){if(p.current){const R=v-p.current;x.timeMetrics.totalVisibleDuration+=R,p.current=null}x.engagementMetrics.viewportExitCount++,w("ad_hidden")}else if(I&&D&&p.current){const R=v-p.current;x.timeMetrics.totalVisibleDuration+=R,p.current=v}if(x.isVisible=I,x.visibilityPercentage=g,g>x.engagementMetrics.maxVisibilityPercentage&&(x.engagementMetrics.maxVisibilityPercentage=g),_.current.length>0&&(x.engagementMetrics.averageVisibilityPercentage=Ce(_.current)),u.current){const R=T.isViewable,Y=Te(g,x.timeMetrics.totalVisibleDuration,u.current);if(Y&&!R)x.isViewable=!0,x.timeMetrics.timeToViewable=v-A,f.current=v,w("ad_viewable");else if(Y&&R&&f.current){const ge=v-f.current;x.timeMetrics.totalViewableDuration+=ge,f.current=v}}return x.engagementMetrics.currentScrollDepth=G(),x})},100),[o,m.timeMetrics.loadedAt,w]);return h.useEffect(()=>{if(!o.current)return;const g=o.current.getBoundingClientRect();u.current=we(g.width,g.height,i.mrcStandards),M("Initialized MRC standards",u.current),w("ad_loaded")},[o,i.mrcStandards,M,w]),h.useEffect(()=>{if(!i.enabled||!o.current)return;const g=new IntersectionObserver(v=>{v.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return g.observe(o.current),()=>{g.disconnect()}},[i.enabled,o,E]),h.useEffect(()=>{if(!i.enabled)return;const g=Q(()=>{E()},100);return window.addEventListener("scroll",g,{passive:!0}),()=>window.removeEventListener("scroll",g)},[i.enabled,E]),h.useEffect(()=>{if(!i.enabled||!o.current)return;const g=o.current,v=()=>{k.current=Date.now(),l(T=>({...T,engagementMetrics:{...T.engagementMetrics,hoverCount:T.engagementMetrics.hoverCount+1}})),w("ad_hover_start")},A=()=>{if(k.current){const T=Date.now()-k.current;l(x=>({...x,timeMetrics:{...x.timeMetrics,totalHoverDuration:x.timeMetrics.totalHoverDuration+T}})),k.current=null,w("ad_hover_end",{hoverDuration:T})}};return g.addEventListener("mouseenter",v),g.addEventListener("mouseleave",A),()=>{g.removeEventListener("mouseenter",v),g.removeEventListener("mouseleave",A)}},[i.enabled,o,w]),h.useEffect(()=>{if(!i.enabled||!o.current)return;const g=o.current,v=()=>{y.current=Date.now(),w("ad_focus")},A=()=>{if(y.current){const T=Date.now()-y.current;l(x=>({...x,timeMetrics:{...x.timeMetrics,totalFocusDuration:x.timeMetrics.totalFocusDuration+T}})),y.current=null,w("ad_blur",{focusDuration:T})}};return g.addEventListener("focus",v),g.addEventListener("blur",A),()=>{g.removeEventListener("focus",v),g.removeEventListener("blur",A)}},[i.enabled,o,w]),h.useEffect(()=>{if(!i.enabled||!o.current)return;const g=o.current,v=()=>{l(A=>({...A,engagementMetrics:{...A.engagementMetrics,wasClicked:!0}})),w("ad_click")};return g.addEventListener("click",v),()=>{g.removeEventListener("click",v)}},[i.enabled,o,w]),h.useEffect(()=>()=>{const g=Date.now(),v=new Date(m.timeMetrics.loadedAt).getTime(),A=g-v;l(T=>({...T,timeMetrics:{...T.timeMetrics,sessionDuration:A}})),w("ad_unloaded",{sessionDuration:A}),C()},[]),m}const j=({adId:t,productId:e,offerId:r,agentId:n,children:s,config:o,className:a,style:i,onViewabilityChange:c,onVisible:m,onViewable:l,onClick:u})=>{const p=h.useRef(null),f=ee({adId:t,productId:e,offerId:r,agentId:n,elementRef:p,config:o}),k=h.useRef(f.isViewable);h.useEffect(()=>{f.isViewable!==k.current&&(k.current=f.isViewable,c&&c(f.isViewable),f.isViewable&&l&&l())},[f.isViewable,c,l]);const y=h.useRef(f.isVisible);h.useEffect(()=>{f.isVisible!==y.current&&(y.current=f.isVisible,f.isVisible&&m&&m())},[f.isVisible,m]);const _=()=>{u&&u()};return d.jsx("div",{ref:p,className:a,style:i,onClick:_,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":f.isViewable,"data-is-visible":f.isVisible,"data-visibility-percentage":f.visibilityPercentage.toFixed(2),children:s})};j.displayName="AdMeshViewabilityTracker";const Ne=t=>{try{return new URL(t),!0}catch{return!1}},J=(t,e)=>{const r=new Map;e.forEach(c=>{c.click_url&&r.set(c.click_url,c)}),console.log("[AdMesh Summary] Processing recommendations:",{totalRecommendations:e.length,recommendationFields:e.map(c=>({ad_id:c.ad_id,click_url:c.click_url,product_title:c.product_title}))}),r.size>0?console.log("[AdMesh Summary] Available recommendation links:",{click_urls:Array.from(r.keys())}):console.warn("[AdMesh Summary] No click_url found in recommendations!");const n=/\[([^\]]+)\]\(([^)]+)\)/g,s=[];let o=0,a,i=0;for(;(a=n.exec(t))!==null;){const[c,m,l]=a;console.log("[AdMesh Summary] Processing markdown link:",{linkText:m,url:l,urlLength:l.length});let u=r.get(l);if(console.log("[AdMesh Summary] URL match result:",{found:!!u,matchedBy:u?"exact_match":"none"}),u||(u=e.find(p=>p.ad_id&&l.includes(p.ad_id)),u&&console.log("[AdMesh Summary] Found by ad_id match")),a.index>o&&s.push(t.slice(o,a.index)),u){i++;const p=l||u.click_url;s.push(d.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary link clicked:",{adId:u.ad_id,productId:u.product_id,title:u.product_title,clickUrl:u.click_url,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:u.ad_id,productId:u.product_id,clickUrl:u.click_url,source:"summary"}).catch(f=>{console.error("[AdMesh] Failed to track summary link click:",f)})},children:m},`summary-link-${i}`))}else console.warn(`[AdMesh Summary] No recommendation found for link: [${m}](${l}), creating regular link`,{availableLinks:Array.from(r.keys()),totalRecommendations:e.length,urlToMatch:l}),Ne(l)?(i++,s.push(d.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary unmatched link clicked:",{linkText:m,url:l,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:l,linkText:m,source:"summary_unmatched"}).catch(p=>{console.error("[AdMesh] Failed to track unmatched link click:",p)})},children:m},`summary-link-${i}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${m}](${l})`),s.push(m));o=a.index+c.length}return o<t.length&&s.push(t.slice(o)),s},te=({summaryText:t,recommendations:e,theme:r,className:n="",style:s={}})=>{var i;if(!t||!t.trim())return console.warn("[AdMesh Summary] No summary text provided"),null;if(!e||e.length===0){console.warn("[AdMesh Summary] No recommendations provided");const c=J(t,[]);return d.jsx("div",{className:`admesh-summary-unit ${n}`,style:s,children:d.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:c.map((m,l)=>d.jsx(h.Fragment,{children:m},l))})})}const o=J(t,e),a=((i=e[0])==null?void 0:i.ad_id)||"";return d.jsx(j,{adId:a,className:`admesh-summary-unit ${n}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:d.jsxs("div",{children:[d.jsx("div",{className:"summary-content",children:d.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:o.map((c,m)=>d.jsx(h.Fragment,{children:c},m))})}),d.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})})]})})};function De(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W={exports:{}};/*!
|
|
1
|
+
"use strict";var xe=Object.defineProperty;var ye=(t,e,r)=>e in t?xe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var L=(t,e,r)=>ye(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),we=require("react-dom/client"),h=require("react");function ve(t,e,r){const s=t*e>242500;return{...{visibilityThreshold:s?.3:.5,minimumDuration:1e3,isLargeAd:s},...r}}function ke(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Me(t){const e=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth,s=e.height,n=e.width;if(s===0||n===0)return 0;const a=Math.max(0,e.top),i=Math.min(r,e.bottom),c=Math.max(0,e.left),m=Math.min(o,e.right),u=Math.max(0,i-a),l=Math.max(0,m-c),p=u*l,b=s*n;return b>0?p/b:0}function Q(){const t=window.innerHeight,e=document.documentElement.scrollHeight,r=window.pageYOffset||document.documentElement.scrollTop,o=e-t;return o<=0?100:Math.min(100,r/o*100)}function _e(t){const e=t.getBoundingClientRect(),r=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+r,left:e.left+o}}function Se(t){const e=t.getBoundingClientRect(),r=_e(t),o=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight,n=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:ke(o),viewportWidth:o,viewportHeight:s,adWidth:e.width,adHeight:e.height,adPositionTop:r.top,adPositionLeft:r.left,isDarkMode:n,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function Ae(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Te(){return`batch_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Ce(t,e,r){return t>=r.visibilityThreshold&&e>=r.minimumDuration}function V(t=new Date){return t.toISOString()}function Ee(t){return t.length===0?0:t.reduce((r,o)=>r+o,0)/t.length}function J(t,e){let r;return function(...s){r||(t(...s),r=!0,setTimeout(()=>r=!1,e))}}async function Le(t,e,r=3,o=1e3){if(!e||e.trim()==="")return!0;let s=null;for(let n=0;n<r;n++){try{const a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});if(a.ok)return!0;const i=await a.text().catch(()=>"");s=new Error(`HTTP ${a.status}: ${a.statusText} - ${i}`)}catch(a){s=a}n<r-1&&await new Promise(a=>setTimeout(a,o*Math.pow(2,n)))}return console.error("[AdMesh Viewability] Failed to send analytics event:",s),!1}async function Re(t,e,r,o=3,s=1e3){if(t.length===0||!r||r.trim()==="")return!0;const n={batchId:Te(),sessionId:e,createdAt:V(),events:t,eventCount:t.length};let a=null;for(let i=0;i<o;i++){try{const c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0});if(c.ok)return!0;const m=await c.text().catch(()=>"");a=new Error(`HTTP ${c.status}: ${c.statusText} - ${m}`)}catch(c){a=c}i<o-1&&await new Promise(c=>setTimeout(c,s*Math.pow(2,i)))}return console.error("[AdMesh Viewability] Failed to send analytics batch:",a),!1}const je={enabled:!0,apiEndpoint:"https://api.useadmesh.com/api/recommendations/viewability/batch",enableBatching:!0,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let Ne=je;function te({adId:t,productId:e,offerId:r,agentId:o,recommendationId:s,elementRef:n,config:a}){const i={...Ne,...a},c=h.useRef(Ae()),[m,u]=h.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:V(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:i.enabled}),l=h.useRef(null),p=h.useRef(null),b=h.useRef(null),w=h.useRef(null),v=h.useRef(null),_=h.useRef([]),f=h.useRef([]),M=h.useRef(null),A=h.useCallback((g,y)=>{i.debug&&console.log(`[AdMesh Viewability] ${g}`,y)},[i.debug]),S=h.useCallback(async(g,y)=>{if(!i.enabled||!n.current||!l.current)return;if(!["ad_viewable","ad_click"].includes(g)){A(`Skipping non-critical event: ${g} (only ad_viewable and ad_click are sent)`);return}const T=Se(n.current),x={eventType:g,timestamp:V(),sessionId:c.current,adId:t,productId:e,offerId:r,agentId:o,recommendationId:s,timeMetrics:m.timeMetrics,engagementMetrics:m.engagementMetrics,contextMetrics:T,mrcStandards:l.current,isViewable:m.isViewable,metadata:y};A(`Sending critical event: ${g}`,x),i.onEvent&&i.onEvent(x),i.enableBatching?(f.current.push(x),f.current.length>=i.batchSize?await k():(M.current&&clearTimeout(M.current),M.current=setTimeout(k,i.batchTimeout))):await Le(x,i.apiEndpoint,i.maxRetries,i.retryDelay)},[i,t,e,r,o,n,m,A]),k=h.useCallback(async()=>{if(f.current.length===0)return;const g=[...f.current];f.current=[],M.current&&(clearTimeout(M.current),M.current=null),await Re(g,c.current,i.apiEndpoint,i.maxRetries,i.retryDelay)&&i.onBatchSent&&i.onBatchSent({batchId:`batch_${Date.now()}`,sessionId:c.current,createdAt:V(),events:g,eventCount:g.length})},[i,A]),E=h.useCallback(J(()=>{if(!n.current)return;const g=Me(n.current),y=Date.now(),C=new Date(m.timeMetrics.loadedAt).getTime();u(T=>{const x={...T};g>0&&_.current.push(g);const R=T.isVisible,j=g>0;if(j&&!R)p.current=y,x.engagementMetrics.viewportEnterCount++,x.timeMetrics.timeToFirstVisible||(x.timeMetrics.timeToFirstVisible=y-C,x.engagementMetrics.scrollDepthAtFirstVisible=Q(),S("ad_visible"));else if(!j&&R){if(p.current){const N=y-p.current;x.timeMetrics.totalVisibleDuration+=N,p.current=null}x.engagementMetrics.viewportExitCount++,S("ad_hidden")}else if(j&&R&&p.current){const N=y-p.current;x.timeMetrics.totalVisibleDuration+=N,p.current=y}if(x.isVisible=j,x.visibilityPercentage=g,g>x.engagementMetrics.maxVisibilityPercentage&&(x.engagementMetrics.maxVisibilityPercentage=g),_.current.length>0&&(x.engagementMetrics.averageVisibilityPercentage=Ee(_.current)),l.current){const N=T.isViewable,G=Ce(g,x.timeMetrics.totalVisibleDuration,l.current);if(G&&!N)x.isViewable=!0,x.timeMetrics.timeToViewable=y-C,b.current=y,S("ad_viewable");else if(G&&N&&b.current){const be=y-b.current;x.timeMetrics.totalViewableDuration+=be,b.current=y}}return x.engagementMetrics.currentScrollDepth=Q(),x})},100),[n,m.timeMetrics.loadedAt,S]);return h.useEffect(()=>{if(!n.current)return;const g=n.current.getBoundingClientRect();l.current=ve(g.width,g.height,i.mrcStandards),A("Initialized MRC standards",l.current),S("ad_loaded")},[n,i.mrcStandards,A,S]),h.useEffect(()=>{if(!i.enabled||!n.current)return;const g=new IntersectionObserver(y=>{y.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return g.observe(n.current),()=>{g.disconnect()}},[i.enabled,n,E]),h.useEffect(()=>{if(!i.enabled)return;const g=J(()=>{E()},100);return window.addEventListener("scroll",g,{passive:!0}),()=>window.removeEventListener("scroll",g)},[i.enabled,E]),h.useEffect(()=>{if(!i.enabled||!n.current)return;const g=n.current,y=()=>{w.current=Date.now(),u(T=>({...T,engagementMetrics:{...T.engagementMetrics,hoverCount:T.engagementMetrics.hoverCount+1}})),S("ad_hover_start")},C=()=>{if(w.current){const T=Date.now()-w.current;u(x=>({...x,timeMetrics:{...x.timeMetrics,totalHoverDuration:x.timeMetrics.totalHoverDuration+T}})),w.current=null,S("ad_hover_end",{hoverDuration:T})}};return g.addEventListener("mouseenter",y),g.addEventListener("mouseleave",C),()=>{g.removeEventListener("mouseenter",y),g.removeEventListener("mouseleave",C)}},[i.enabled,n,S]),h.useEffect(()=>{if(!i.enabled||!n.current)return;const g=n.current,y=()=>{v.current=Date.now(),S("ad_focus")},C=()=>{if(v.current){const T=Date.now()-v.current;u(x=>({...x,timeMetrics:{...x.timeMetrics,totalFocusDuration:x.timeMetrics.totalFocusDuration+T}})),v.current=null,S("ad_blur",{focusDuration:T})}};return g.addEventListener("focus",y),g.addEventListener("blur",C),()=>{g.removeEventListener("focus",y),g.removeEventListener("blur",C)}},[i.enabled,n,S]),h.useEffect(()=>{if(!i.enabled||!n.current)return;const g=n.current,y=()=>{u(C=>({...C,engagementMetrics:{...C.engagementMetrics,wasClicked:!0}})),S("ad_click")};return g.addEventListener("click",y),()=>{g.removeEventListener("click",y)}},[i.enabled,n,S]),h.useEffect(()=>()=>{const g=Date.now(),y=new Date(m.timeMetrics.loadedAt).getTime(),C=g-y;u(T=>({...T,timeMetrics:{...T.timeMetrics,sessionDuration:C}})),S("ad_unloaded",{sessionDuration:C}),k()},[]),m}const D=({adId:t,productId:e,offerId:r,agentId:o,recommendationId:s,exposureUrl:n,sessionId:a,children:i,config:c,className:m,style:u,onViewabilityChange:l,onVisible:p,onViewable:b,onClick:w})=>{const v=h.useRef(null),_=h.useRef(!1),f=te({adId:t,productId:e,offerId:r,agentId:o,recommendationId:s,elementRef:v,config:c}),M=h.useRef(f.isViewable);h.useEffect(()=>{f.isViewable!==M.current&&(M.current=f.isViewable,l&&l(f.isViewable),f.isViewable&&b&&b(),f.isViewable&&!_.current&&n&&a&&(_.current=!0,fetch(n,{method:"GET",keepalive:!0}).then(()=>{console.log("[AdMesh] โ
Exposure pixel fired for:",{adId:t,recommendationId:s,sessionId:a.substring(0,20)+"..."})}).catch(k=>{console.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",k),_.current=!1})))},[f.isViewable,l,b,n,a,t,s]);const A=h.useRef(f.isVisible);h.useEffect(()=>{f.isVisible!==A.current&&(A.current=f.isVisible,f.isVisible&&p&&p())},[f.isVisible,p]);const S=()=>{w&&w()};return d.jsx("div",{ref:v,className:m,style:u,onClick:S,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":f.isViewable,"data-is-visible":f.isVisible,"data-visibility-percentage":f.visibilityPercentage.toFixed(2),children:i})};D.displayName="AdMeshViewabilityTracker";const De=t=>{try{return new URL(t),!0}catch{return!1}},X=(t,e)=>{const r=new Map;e.forEach(c=>{c.click_url&&r.set(c.click_url,c)}),console.log("[AdMesh Summary] Processing recommendations:",{totalRecommendations:e.length,recommendationFields:e.map(c=>({ad_id:c.ad_id,click_url:c.click_url,product_title:c.product_title}))}),r.size>0?console.log("[AdMesh Summary] Available recommendation links:",{click_urls:Array.from(r.keys())}):console.warn("[AdMesh Summary] No click_url found in recommendations!");const o=/\[([^\]]+)\]\(([^)]+)\)/g,s=[];let n=0,a,i=0;for(;(a=o.exec(t))!==null;){const[c,m,u]=a;console.log("[AdMesh Summary] Processing markdown link:",{linkText:m,url:u,urlLength:u.length});let l=r.get(u);if(console.log("[AdMesh Summary] URL match result:",{found:!!l,matchedBy:l?"exact_match":"none"}),l||(l=e.find(p=>p.ad_id&&u.includes(p.ad_id)),l&&console.log("[AdMesh Summary] Found by ad_id match")),a.index>n&&s.push(t.slice(n,a.index)),l){i++;const p=u||l.click_url;s.push(d.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary link clicked:",{adId:l.ad_id,productId:l.product_id,title:l.product_title,clickUrl:l.click_url,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:l.ad_id,productId:l.product_id,clickUrl:l.click_url,source:"summary"}).catch(b=>{console.error("[AdMesh] Failed to track summary link click:",b)})},children:m},`summary-link-${i}`))}else console.warn(`[AdMesh Summary] No recommendation found for link: [${m}](${u}), creating regular link`,{availableLinks:Array.from(r.keys()),totalRecommendations:e.length,urlToMatch:u}),De(u)?(i++,s.push(d.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:()=>{console.log("AdMesh summary unmatched link clicked:",{linkText:m,url:u,source:"summary"}),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({url:u,linkText:m,source:"summary_unmatched"}).catch(p=>{console.error("[AdMesh] Failed to track unmatched link click:",p)})},children:m},`summary-link-${i}`))):(console.warn(`[AdMesh Summary] Invalid URL in markdown link: [${m}](${u})`),s.push(m));n=a.index+c.length}return n<t.length&&s.push(t.slice(n)),s},re=({summaryText:t,recommendations:e,theme:r,className:o="",style:s={},sessionId:n})=>{var l,p,b,w;if(!t||!t.trim())return console.warn("[AdMesh Summary] No summary text provided"),null;if(!e||e.length===0){console.warn("[AdMesh Summary] No recommendations provided");const v=X(t,[]);return d.jsx("div",{className:`admesh-summary-unit ${o}`,style:s,children:d.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed",children:v.map((_,f)=>d.jsx(h.Fragment,{children:_},f))})})}const a=X(t,e),i=((l=e[0])==null?void 0:l.ad_id)||"",c=(p=e[0])==null?void 0:p.product_id,m=(b=e[0])==null?void 0:b.exposure_url,u=(w=e[0])==null?void 0:w.recommendation_id;return d.jsx(D,{adId:i,productId:c,recommendationId:u,exposureUrl:m,sessionId:n,className:`admesh-summary-unit ${o}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:d.jsxs("div",{children:[d.jsx("div",{className:"summary-content",children:d.jsx("p",{className:"text-gray-700 dark:text-gray-300 leading-relaxed text-base",children:a.map((v,_)=>d.jsx(h.Fragment,{children:v},_))})}),d.jsx("div",{className:"mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})})]})})};function Fe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W={exports:{}};/*!
|
|
2
2
|
Copyright (c) 2018 Jed Watson.
|
|
3
3
|
Licensed under the MIT License (MIT), see
|
|
4
4
|
http://jedwatson.github.io/classnames
|
|
5
|
-
*/var
|
|
5
|
+
*/var q;function Pe(){return q||(q=1,(function(t){(function(){var e={}.hasOwnProperty;function r(){for(var n="",a=0;a<arguments.length;a++){var i=arguments[a];i&&(n=s(n,o(i)))}return n}function o(n){if(typeof n=="string"||typeof n=="number")return n;if(typeof n!="object")return"";if(Array.isArray(n))return r.apply(null,n);if(n.toString!==Object.prototype.toString&&!n.toString.toString().includes("[native code]"))return n.toString();var a="";for(var i in n)e.call(n,i)&&n[i]&&(a=s(a,i));return a}function s(n,a){return a?n?n+" "+a:n+a:n}t.exports?(r.default=r,t.exports=r):window.classNames=r})()})(W)),W.exports}var Ie=Pe();const F=Fe(Ie),ze="https://api.useadmesh.com/track";let Ve={enabled:!0,retryAttempts:3,retryDelay:1e3};const ne=t=>{const[e,r]=h.useState(!1),[o,s]=h.useState(null),n=h.useMemo(()=>({...Ve,...t}),[t]),a=h.useCallback(async(u,l)=>{if(!n.enabled)return;if(!l.adId||!l.admeshLink){s("Missing required tracking data: adId and admeshLink are required");return}r(!0),s(null);const p={event_type:u,ad_id:l.adId,admesh_link:l.admeshLink,product_id:l.productId,user_id:l.userId,session_id:l.sessionId,revenue:l.revenue,conversion_type:l.conversionType,metadata:l.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let b=null;for(let v=1;v<=(n.retryAttempts||3);v++)try{const _=await fetch(`${ze}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});if(!_.ok)throw new Error(`HTTP ${_.status}: ${_.statusText}`);await _.json(),r(!1);return}catch(_){b=_,v<(n.retryAttempts||3)&&await new Promise(f=>setTimeout(f,(n.retryDelay||1e3)*v))}const w=`Failed to track ${u} event after ${n.retryAttempts} attempts: ${b==null?void 0:b.message}`;s(w),r(!1)},[n]),i=h.useCallback(async u=>a("click",u),[a]),c=h.useCallback(async u=>a("view",u),[a]),m=h.useCallback(async u=>a("conversion",u),[a]);return{trackClick:i,trackView:c,trackConversion:m,isTracking:e,error:o}},P=({adId:t,admeshLink:e,productId:r,children:o,trackingData:s,className:n,style:a})=>{const{trackClick:i,trackView:c}=ne(),m=h.useRef(null),u=h.useRef(!1);h.useEffect(()=>{if(!m.current||u.current)return;const p=new IntersectionObserver(b=>{b.forEach(w=>{w.isIntersecting&&!u.current&&(u.current=!0,c({adId:t,admeshLink:e,productId:r,...s}).catch(console.error))})},{threshold:.5,rootMargin:"0px"});return p.observe(m.current),()=>{p.disconnect()}},[t,e,r,s,c]);const l=h.useCallback(p=>{i({adId:t,admeshLink:e,productId:r,...s}).catch(v=>{console.error("[AdMesh] Failed to track click:",v)}),p.target.closest("a")||window.open(e,"_blank","noopener,noreferrer")},[t,e,r,s,i]);return d.jsx("div",{ref:m,className:n,onClick:l,style:{cursor:"pointer",...a},children:o})};P.displayName="AdMeshLinkTracker";const B="admesh-ui-sdk-styles",U="admesh-ui-sdk-reset",$e=`
|
|
6
6
|
/* AdMesh UI SDK - CSS Reset & Normalization */
|
|
7
7
|
.admesh-component,
|
|
8
8
|
.admesh-component * {
|
|
@@ -91,7 +91,7 @@
|
|
|
91
91
|
.admesh-component[data-admesh-theme="light"] {
|
|
92
92
|
color-scheme: light;
|
|
93
93
|
}
|
|
94
|
-
|
|
94
|
+
`,Oe=`
|
|
95
95
|
/* AdMesh Core Component Styles */
|
|
96
96
|
|
|
97
97
|
.admesh-component {
|
|
@@ -302,7 +302,7 @@
|
|
|
302
302
|
font-size: 0.875rem;
|
|
303
303
|
}
|
|
304
304
|
}
|
|
305
|
-
`,
|
|
305
|
+
`,We=()=>{if(!(typeof document>"u")&&!(document.getElementById(U)&&document.getElementById(B))){if(!document.getElementById(U)){const t=document.createElement("style");t.id=U,t.textContent=$e,document.head.appendChild(t)}if(!document.getElementById(B)){const t=document.createElement("style");t.id=B,t.textContent=Oe,document.head.appendChild(t)}}},Be=`
|
|
306
306
|
/* AdMesh UI SDK - Complete Self-Contained Styles */
|
|
307
307
|
|
|
308
308
|
/* CSS Reset for AdMesh components */
|
|
@@ -970,7 +970,7 @@
|
|
|
970
970
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
971
971
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
972
972
|
}
|
|
973
|
-
`;let q=!1;const ne=()=>{h.useEffect(()=>{if(!q){try{Oe();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=We,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),q=!0}catch(t){console.error("[AdMesh] Failed to inject styles:",t)}return()=>{}}},[])},z=(t,e={})=>{const r=t.intent_match_score||0,n=e.customLabels||{};return r>=.8?n.partnerRecommendation||"Smart Pick":r>=.6?n.partnerMatch||"Partner Recommendation":r>=.3?n.promotedOption||"Promoted Match":n.relatedOption||"Related"},Z=(t,e)=>{const r=t.intent_match_score||0;return r>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":r>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":r>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},H=({recommendation:t,theme:e,variation:r="default",className:n,style:s})=>{var u,p,f,k,y,_,b,S,M,w,C,E,g,v,A,T;ne();const a=r==="simple"?{title:t.product_title||t.title,description:t.product_summary||t.weave_summary||t.reason,ctaText:t.product_title||t.title,isSimple:!0}:{title:t.product_title||t.title,description:t.product_summary||t.weave_summary||t.reason,ctaText:t.product_title||t.title},i=N("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",n),c=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(u=e.shadows)==null?void 0:u.small,"--admesh-shadow-md":(p=e.shadows)==null?void 0:p.medium,"--admesh-shadow-lg":(f=e.shadows)==null?void 0:f.large,"--admesh-spacing-sm":(k=e.spacing)==null?void 0:k.small,"--admesh-spacing-md":(y=e.spacing)==null?void 0:y.medium,"--admesh-spacing-lg":(_=e.spacing)==null?void 0:_.large,"--admesh-font-size-sm":(b=e.fontSize)==null?void 0:b.small,"--admesh-font-size-base":(S=e.fontSize)==null?void 0:S.base,"--admesh-font-size-lg":(M=e.fontSize)==null?void 0:M.large,"--admesh-font-size-title":(w=e.fontSize)==null?void 0:w.title,fontFamily:e.fontFamily,width:((E=(C=e.components)==null?void 0:C.productCard)==null?void 0:E.width)||"100%"}:{width:"100%"};if(r==="simple"){const x=t.ad_id||"",D=t.product_id||"";return d.jsx(j,{adId:x,productId:D,className:N("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",n),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(g=e==null?void 0:e.components)==null?void 0:g.productCard,...s},children:d.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[d.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:Z(t,z(t)),children:z(t)}),d.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[a.description," "]}),d.jsx(F,{adId:t.ad_id||"",admeshLink:t.click_url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"simple_ad_cta"},children:d.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:a.ctaText})})]})})}const m=t.ad_id||"",l=t.product_id||"";return d.jsx(j,{adId:m,productId:l,className:i,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(v=e==null?void 0:e.components)==null?void 0:v.productCard,...s},children:d.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(A=e==null?void 0:e.components)==null?void 0:A.productCard,...s},"data-admesh-theme":e==null?void 0:e.mode,children:d.jsxs("div",{className:"h-full flex flex-col",style:c,children:[d.jsx("div",{className:"mb-1.5",children:d.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:Z(t,z(t)),children:z(t)})}),d.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((T=t.product_logo)==null?void 0:T.url)&&d.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:x=>{x.target.style.display="none"}}),d.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:a.title})]}),d.jsx("div",{className:"flex-shrink-0",children:d.jsx(F,{adId:t.ad_id||"",admeshLink:t.click_url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"product_card_cta"},children:d.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:["Visit",d.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),d.jsx("div",{className:"mb-3",children:d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:a.description})}),d.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:d.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[d.jsx("span",{children:"Sponsored"}),d.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};H.displayName="AdMeshProductCard";const oe=({recommendations:t,summaryText:e,theme:r,className:n="",style:s={},onLinkClick:o,response:a})=>{const i=t||(a==null?void 0:a.recommendations)||[],c=e||(a==null?void 0:a.citation_summary);if(!i||i.length===0)return console.log("[AdMesh Summary Layout] Empty recommendations array - not rendering anything"),null;console.log(`[AdMesh Summary Layout] Rendering with ${i.length} recommendations`);const m=()=>c?d.jsx(te,{summaryText:c,recommendations:i,theme:r,onLinkClick:o}):d.jsx("div",{className:"fallback-citation",children:d.jsx(H,{recommendation:i[0],theme:r})});return d.jsx("div",{className:`admesh-summary-layout ${n}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:m()})},ae=({recommendations:t,summaryText:e,theme:r,className:n,style:s,onLinkClick:o,response:a})=>{const i=t||(a==null?void 0:a.recommendations)||[],c=e||(a==null?void 0:a.citation_summary);return!i||i.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):d.jsx(oe,{recommendations:i,summaryText:c,theme:r,className:n,style:s,onLinkClick:o})};class se{constructor(e){L(this,"firedExposures",new Set);L(this,"debug",!1);L(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,n){const s=`${n}_${r}`;if(this.firedExposures.has(s)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(o=>{this.debug&&console.warn("[Tracker] Failed to fire exposure:",o)}),this.debug&&console.log("[Tracker] Fired MRC-compliant exposure for:",r)}catch(o){this.debug&&console.error("[Tracker] Error firing exposure:",o)}}async fireExposureWithMRCCompliance(e,r,n,s){const o=`${n}_${r}`;if(this.firedExposures.has(o)){this.debug&&console.log("[Tracker] MRC exposure already fired for:",r);return}return new Promise(a=>{let i=null,c=null;const m=new IntersectionObserver(p=>{p.forEach(f=>{const k=f.intersectionRatio*100;k>=this.mrcThreshold.visibilityPercentage?i===null&&(i=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold:",{adId:r,visibilityPercentage:k.toFixed(2)}),c=setTimeout(()=>{this.fireExposure(e,r,n),m.disconnect(),a()},this.mrcThreshold.minimumDurationMs)):i!==null&&(c&&(clearTimeout(c),c=null),i=null,this.debug&&console.log("[Tracker] Ad visibility dropped below MRC threshold:",{adId:r,visibilityPercentage:k.toFixed(2)}))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});m.observe(s);const u=setTimeout(()=>{m.disconnect(),c&&clearTimeout(c),a()},3e4);s.__admeshTrackerCleanup=()=>{m.disconnect(),c&&clearTimeout(c),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class ie{constructor(){L(this,"roots",new Map)}async render(e){var r,n,s;try{console.log(`[AdMeshRenderer] ๐จ Attempting to render into container: ${e.containerId}`);const o=document.getElementById(e.containerId);if(!o)throw console.error(`[AdMeshRenderer] โ Container not found: ${e.containerId}`),console.log("[AdMeshRenderer] ๐ Available containers in DOM:",Array.from(document.querySelectorAll('[id*="admesh"]')).map(m=>m.id)),new Error(`Container with ID "${e.containerId}" not found`);console.log("[AdMeshRenderer] โ
Container found:",{id:e.containerId,tagName:o.tagName,className:o.className,innerHTML:o.innerHTML.substring(0,100)});const a=this.roots.get(e.containerId);a&&(console.log(`[AdMeshRenderer] ๐งน Cleaning up existing root for: ${e.containerId}`),a.unmount(),this.roots.delete(e.containerId)),o.innerHTML="";const i=ye.createRoot(o),c=((n=(r=e.response.recommendations)==null?void 0:r[0])==null?void 0:n.citation_summary)||"";console.log("[AdMeshRenderer] ๐ Rendering recommendations:",{containerId:e.containerId,recommendationsCount:((s=e.response.recommendations)==null?void 0:s.length)||0,hasCitationSummary:!!c}),i.render(d.jsx(ae,{recommendations:e.response.recommendations||[],summaryText:c,theme:e.theme})),console.log(`[AdMeshRenderer] โ
Recommendations rendered successfully into: ${e.containerId}`),this.roots.set(e.containerId,i)}catch(o){throw console.error("[AdMeshRenderer] โ Error rendering recommendations:",o),o}}unmount(e){const r=this.roots.get(e);r&&(r.unmount(),this.roots.delete(e))}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class de{constructor(e={}){L(this,"autoAddLabels");L(this,"fireExposurePixels");L(this,"labelStyle");L(this,"processedLinks",new Set);L(this,"mutationObserver",null);var r,n,s,o;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((r=e.labelStyle)==null?void 0:r.fontSize)||"0.75em",fontWeight:((n=e.labelStyle)==null?void 0:n.fontWeight)||"bold",color:((s=e.labelStyle)==null?void 0:s.color)||"#666",marginLeft:((o=e.labelStyle)==null?void 0:o.marginLeft)||"2px"}}getLinksToProcess(e){const n=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return n.length>0?Array.from(n):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,n){if(!e)return[];const s=[];if(r.length>0){const o=this.getLinksToProcess(e),a=new Map(r.filter(i=>i.click_url).map(i=>[i.click_url,i]));o.forEach(i=>{var u;const c=i.getAttribute("href")||"",m=`${c}`;if(this.processedLinks.has(m))return;const l=a.get(c);if(l){this.processedLinks.add(m);const p={element:i,href:c,text:i.textContent||"",hasAdLabel:this.hasAdLabel(i),matchedRecommendation:{ad_id:l.ad_id||((u=l.meta)==null?void 0:u.ad_id)||"",click_url:l.click_url,exposure_url:l.exposure_url}};this.autoAddLabels&&!p.hasAdLabel&&(this.addAdLabel(i),p.hasAdLabel=!0),this.fireExposurePixels&&l.exposure_url&&n&&p.matchedRecommendation&&n(l.exposure_url,p.matchedRecommendation.ad_id),s.push(p)}})}else Array.from(e.querySelectorAll("a")).forEach(a=>{const i=a.getAttribute("href")||"",c=`${i}`;if(this.processedLinks.has(c))return;if(this.isAdMeshLink(i)){this.processedLinks.add(c);const l={element:a,href:i,text:a.textContent||"",hasAdLabel:this.hasAdLabel(a),matchedRecommendation:void 0};a.setAttribute("target","_blank"),a.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!l.hasAdLabel&&(this.addAdLabel(a),l.hasAdLabel=!0),this.fireExposurePixels&&n&&n(i,this.extractAdIdFromUrl(i)),s.push(l)}});return s}hasAdLabel(e){var s,o;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const a=r.textContent||"";if(a.trim()===""){r=r.previousSibling;continue}if(a.includes("[Ad]"))return!0;break}if(r&&r.nodeType===Node.ELEMENT_NODE){const a=r;if((a.tagName==="SUB"||a.tagName==="SPAN")&&((s=a.textContent)!=null&&s.includes("[Ad]")))return!0}let n=e.nextSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const a=n.textContent||"";if(a.trim()===""){n=n.nextSibling;continue}if(a.includes("[Ad]"))return!0;break}if(n&&n.nodeType===Node.ELEMENT_NODE){const a=n;if((a.tagName==="SUB"||a.tagName==="SPAN")&&((o=a.textContent)!=null&&o.includes("[Ad]")))return!0}return!1}addAdLabel(e){var o;if(this.hasAdLabel(e))return;this.removeLeftAdLabel(e);const r=document.createElement("sub");r.textContent="[Ad]",r.style.fontSize=this.labelStyle.fontSize,r.style.fontWeight=this.labelStyle.fontWeight,r.style.color=this.labelStyle.color,r.style.marginLeft=this.labelStyle.marginLeft,r.style.cursor="pointer",r.style.borderBottom=`1px dotted ${this.labelStyle.color}`,r.style.whiteSpace="nowrap",r.title="Why this ad? This is a sponsored recommendation based on your search query.";let n=!1;r.addEventListener("mouseenter",()=>{r.style.opacity="0.7"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1",n&&(n=!1)}),r.addEventListener("click",a=>{a.stopPropagation(),n=!n,n?(r.style.textDecoration="underline",r.style.opacity="0.7"):(r.style.textDecoration="none",r.style.opacity="1")});const s=a=>{n&&a.target!==r&&(n=!1,r.style.textDecoration="none",r.style.opacity="1")};document.addEventListener("click",s),(o=e.parentNode)==null||o.insertBefore(r,e.nextSibling)}removeLeftAdLabel(e){var n,s,o;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const a=r.textContent||"";if(a.trim()===""){r=r.previousSibling;continue}if(a.includes("[Ad]")){(n=r.parentNode)==null||n.removeChild(r);return}break}if(r&&r.nodeType===Node.ELEMENT_NODE){const a=r;(a.tagName==="SUB"||a.tagName==="SPAN")&&((s=a.textContent)!=null&&s.includes("[Ad]"))&&((o=a.parentNode)==null||o.removeChild(a))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(s=>e.includes(s)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractAdIdFromUrl(e){try{const r=e.match(/\/click\/([^/?]+)/);return r&&r[1]?r[1]:e}catch{return e}}watchForNewLinks(e,r,n){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,n)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}class ce{constructor(e){L(this,"config");L(this,"apiBaseUrl");L(this,"renderer",null);L(this,"tracker",null);L(this,"weaveProcessor",null);L(this,"weaveCache",new Map);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),n=Math.random().toString(36).substring(2,15);return`msg_${e}_${r}_${n}`}getRenderer(){return this.renderer||(this.renderer=new ie),this.renderer}getTracker(){return this.tracker||(this.tracker=new se({apiKey:this.config.apiKey})),this.tracker}getWeaveProcessor(){return this.weaveProcessor||(this.weaveProcessor=new de({autoAddLabels:!0,fireExposurePixels:!0})),this.weaveProcessor}async showRecommendations(e){try{const r=await this.fetchRecommendationsFromAPI({query:e.query,format:e.format||"auto",previousQuery:e.previousQuery,previousSummary:e.previousSummary,sessionId:e.session_id,messageId:e.message_id,isFallbackAllowed:e.isFallbackAllowed!==!1});if(e.format==="weave")await this.handleWeaveFormat(e,r);else{const n=this.getRenderer(),s=this.getTracker();if(await n.render({containerId:e.containerId,response:r,theme:e.theme||this.config.theme,tracker:s,sessionId:e.session_id||""}),r.recommendations){for(const o of r.recommendations)if(o.exposure_url){const a=o.ad_id||"";s.fireExposure(o.exposure_url,a,e.session_id||"")}}}}catch(r){throw console.error("[AdMeshSDK] Error showing recommendations:",r),r}}async handleWeaveFormat(e,r){const n=e.session_id||"",s=e.message_id||"",o=e.timeoutMs||900,a=e.fallbackFormat||"citation",i=`${n}:${s}`;if(this.weaveCache.set(i,r.recommendations||[]),e.llmOutputContainerId)try{if(await this.scanLLMOutputForAdMeshLinks(e.llmOutputContainerId,r.recommendations||[],n,o)){console.log("[AdMeshSDK] Weave format: AdMesh links detected in LLM output. Skipping fallback UI.");return}}catch(u){console.error("[AdMeshSDK] Error scanning LLM output for AdMesh links:",u)}console.log("[AdMeshSDK] Weave format: No AdMesh links detected. Rendering fallback UI with format:",a);const c=r,m=this.getRenderer(),l=this.getTracker();if(await m.render({containerId:e.containerId,response:c,theme:e.theme||this.config.theme,tracker:l,sessionId:n}),r.recommendations){for(const u of r.recommendations)if(u.exposure_url){const p=u.ad_id||"";l.fireExposure(u.exposure_url,p,n)}}}async scanLLMOutputForAdMeshLinks(e,r,n,s){const o=document.getElementById(e);if(!o)return console.warn(`[AdMeshSDK] LLM output container not found: ${e}`),!1;const a=Date.now(),i=100;let c=!1,m=null;try{const l=new Promise(f=>{const k=new MutationObserver(()=>{this.scanAndLabelAds(e,r,n)&&!c&&(c=!0,console.log("[AdMeshSDK] AdMesh links detected via MutationObserver"),f(!0))});k.observe(o,{childList:!0,subtree:!0,characterData:!1}),m=k}),u=(async()=>{for(;Date.now()-a<s;){if(this.scanAndLabelAds(e,r,n)&&!c)return c=!0,console.log("[AdMeshSDK] AdMesh links detected via polling"),!0;await this.sleep(i)}return!1})();return await Promise.race([l,u])}finally{m&&m.disconnect()}}scanAndLabelAds(e,r,n){const s=document.getElementById(e);if(!s)return!1;const o=this.getWeaveProcessor(),a=this.getTracker();return o.scanAndProcessLinks(s,r,(c,m)=>{a.fireExposure(c,m,n)}).length>0}async fetchRecommendationsFromAPI(e){var c;const r=`${this.apiBaseUrl}/agent/recommend`;console.log("[AdMeshSDK] ๐ฅ fetchRecommendationsFromAPI called with params:",{query:e.query?`"${e.query.substring(0,50)}${e.query.length>50?"...":""}"`:"(EMPTY)",queryType:typeof e.query,queryLength:(c=e.query)==null?void 0:c.length,format:e.format,sessionId:e.sessionId,messageId:e.messageId});const n={query:e.query,format:e.format||"auto",source:"admesh_ui_sdk"};e.previousQuery&&(n.previous_query=e.previousQuery),e.previousSummary&&(n.previous_summary=e.previousSummary),e.sessionId&&(n.session_id=e.sessionId),e.messageId&&(n.message_id=e.messageId),e.isFallbackAllowed!==void 0&&(n.is_fallback_allowed=e.isFallbackAllowed);const s=typeof n.query=="string"?n.query:"";(!s||!s.trim())&&(console.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query"),console.log("[AdMeshSDK] Full payload:",JSON.stringify(n,null,2)));const o=JSON.stringify(n);console.log("[AdMeshSDK] ๐ค Sending JSON body:",o);const a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:o});if(!a.ok){const l=(await a.json().catch(()=>({}))).detail||`HTTP ${a.status}`;throw new Error(`Failed to fetch recommendations: ${l}`)}return await a.json()}sleep(e){return new Promise(r=>setTimeout(r,e))}}const K=h.createContext(void 0);function le(){const t=h.useContext(K);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const Be=({apiKey:t,sessionId:e,theme:r,apiBaseUrl:n,children:s})=>{const o=h.useRef(null),[a,i]=h.useState(new Set);h.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}try{o.current=new ce({apiKey:t,theme:r,apiBaseUrl:n}),console.log("[AdMeshProvider] โ
AdMesh SDK initialized"),n&&console.log(`[AdMeshProvider] ๐ Using custom API base URL: ${n}`)}catch(m){console.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",m)}return()=>{console.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,r,n]);const c={sdk:o.current,apiKey:t,sessionId:e,theme:r,processedMessageIds:a,markMessageAsProcessed:m=>{i(l=>{const u=new Set(l);return u.add(m),u})},isMessageProcessed:m=>a.has(m)};return d.jsx(K.Provider,{value:c,children:s})};function P(){const t=le();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const Ue=({format:t="citation",onRecommendationsShown:e,onError:r,messageId:n,query:s})=>{const{sdk:o,sessionId:a}=P(),i=h.useRef(null),[c,m]=h.useState("");return h.useEffect(()=>{n&&m(`admesh-recommendations-${n}`)},[n]),h.useEffect(()=>{if(console.log("[AdMeshRecommendations] ๐ SDK VERSION CHECK - Props received:",{sdkVersion:"1.0.6-no-dedup",timestamp:new Date().toISOString(),messageId:n,query:s?`"${s.substring(0,50)}${s.length>50?"...":""}"`:"(EMPTY)",queryType:typeof s,queryLength:s==null?void 0:s.length,format:t,sessionId:a}),!n||!s||s.trim()===""){console.log("[AdMeshRecommendations] โ Validation failed - returning early:",{hasMessageId:!!n,hasQuery:!!s,queryTrimmed:s==null?void 0:s.trim(),queryTrimmedLength:s==null?void 0:s.trim().length});return}if(console.log("[AdMeshRecommendations] โ
Validation passed"),!o||!c){console.log("[AdMeshRecommendations] SDK or containerId not ready:",{hasSdk:!!o,hasContainerId:!!c});return}(async()=>{try{if(!(o!=null&&o.showRecommendations)){console.log("[AdMeshRecommendations] SDK showRecommendations not available");return}console.log("[AdMeshRecommendations] ๐ค Calling sdk.showRecommendations with:",{query:s.trim().substring(0,50),containerId:c,format:t,session_id:a,message_id:n}),await o.showRecommendations({query:s.trim(),containerId:c,format:t,session_id:a,message_id:n}),e==null||e(n)}catch(u){const p=u instanceof Error?u:new Error(String(u));console.log("[AdMeshRecommendations] โ Error:",p.message),r==null||r(p)}})()},[o,a,c,t,n,s,e,r]),d.jsx("div",{ref:i,id:c,className:"admesh-recommendations-container",style:{marginTop:"1rem",minHeight:"100px",display:"block"}})},me=({format:t="citation",onError:e,messageId:r,query:n,fallback:s})=>{const{sdk:o,sessionId:a}=P(),i=h.useRef(null),[c,m]=h.useState("");return h.useEffect(()=>{r&&m(`admesh-weave-fallback-${r}`)},[r]),console.log("[WeaveFallbackRecommendations] ๐จ Component render:",{messageId:r,fallback:s,hasQuery:!!n,timestamp:new Date().toISOString()}),h.useEffect(()=>{if(console.log("[WeaveFallbackRecommendations] ๐ useEffect triggered - Props:",{timestamp:new Date().toISOString(),messageId:r,query:n?`"${n.substring(0,50)}${n.length>50?"...":""}"`:"(EMPTY)",queryType:typeof n,queryLength:n==null?void 0:n.length,format:t,sessionId:a,fallback:s}),!s){console.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(console.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!r||!n||n.trim()===""){console.log("[WeaveFallbackRecommendations] โ Validation failed - returning early:",{hasMessageId:!!r,hasQuery:!!n,queryTrimmed:n==null?void 0:n.trim(),queryTrimmedLength:n==null?void 0:n.trim().length});return}if(console.log("[WeaveFallbackRecommendations] โ
Validation passed"),!o||!c){console.log("[WeaveFallbackRecommendations] SDK or containerId not ready:",{hasSdk:!!o,hasContainerId:!!c});return}(async()=>{try{if(!(o!=null&&o.showRecommendations)){console.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}console.log("[WeaveFallbackRecommendations] ๐ค Calling sdk.showRecommendations with:",{query:n.trim().substring(0,50),containerId:c,format:t,session_id:a,message_id:r}),await o.showRecommendations({query:n.trim(),containerId:c,format:t,session_id:a,message_id:r}),console.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(u){const p=u instanceof Error?u:new Error(String(u));console.log("[WeaveFallbackRecommendations] โ Error:",p.message),e==null||e(p)}})()},[o,a,c,t,r,n,s,e]),d.jsx("div",{ref:i,id:c,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",minHeight:"100px",display:"block"}})},ue=h.createContext(void 0),He=({children:t,shouldRenderFallback:e,messageId:r,sessionId:n,query:s})=>d.jsx(ue.Provider,{value:{shouldRenderFallback:e,messageId:r,sessionId:n,query:s},children:t}),Ke=()=>h.useContext(ue),Ye=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:n="",cardClassName:s="",onProductClick:o,maxCards:a=10,cardWidth:i="md",theme:c="auto",borderRadius:m="md",shadow:l="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const u=t.slice(0,a),p=()=>{switch(i){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},f=()=>{switch(m){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},k=()=>{switch(l){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},y=()=>c==="dark"?"bg-gray-900 text-white":c==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",_=b=>{if(o)o(b);else{const S=b.click_url||b.url;S&&window.open(S,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:d.jsxs("div",{className:N("w-full",n),children:[r&&d.jsxs("div",{className:"mb-4",children:[d.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),d.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),d.jsxs("div",{className:"relative",children:[u.length===0?d.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):d.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:u.map(b=>{var C;const S=b.product_id||b.id||b.ad_id,M=b.ad_id||b.product_id||"",w=b.product_id||"";return d.jsx(j,{adId:M,productId:w,className:N(p(),f(),k(),y(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",s),onClick:()=>_(b),children:d.jsxs("div",{children:[d.jsx("div",{className:"relative aspect-square w-full overflow-hidden",children:(C=b.product_logo)!=null&&C.url?d.jsx("img",{src:b.product_logo.url,alt:b.product_title,className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy"}):d.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:d.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),d.jsxs("div",{className:"p-3",children:[d.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:b.product_title}),b.weave_summary&&d.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2 mb-2",children:b.weave_summary}),b.categories&&b.categories.length>0&&d.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:b.categories.slice(0,2).map((E,g)=>d.jsx("span",{className:"text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded",children:E},g))}),b.trust_score!==void 0&&d.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Trust Score: ",(b.trust_score*100).toFixed(0),"%"]})]})]})},S)})}),u.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),d.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),d.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),d.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),d.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
973
|
+
`;let Z=!1;const oe=()=>{h.useEffect(()=>{if(!Z){try{We();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Be,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),Z=!0}catch(t){console.error("[AdMesh] Failed to inject styles:",t)}return()=>{}}},[])},z=(t,e={})=>{const r=t.intent_match_score||0,o=e.customLabels||{};return r>=.8?o.partnerRecommendation||"Smart Pick":r>=.6?o.partnerMatch||"Partner Recommendation":r>=.3?o.promotedOption||"Promoted Match":o.relatedOption||"Related"},ee=(t,e)=>{const r=t.intent_match_score||0;return r>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":r>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":r>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},H=({recommendation:t,theme:e,variation:r="default",className:o,style:s,sessionId:n})=>{var p,b,w,v,_,f,M,A,S,k,E,g,y,C,T,x;oe();const i=r==="simple"?{title:t.product_title||t.title,description:t.product_summary||t.weave_summary||t.reason,ctaText:t.product_title||t.title,isSimple:!0}:{title:t.product_title||t.title,description:t.product_summary||t.weave_summary||t.reason,ctaText:t.product_title||t.title},c=F("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",o),m=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(p=e.shadows)==null?void 0:p.small,"--admesh-shadow-md":(b=e.shadows)==null?void 0:b.medium,"--admesh-shadow-lg":(w=e.shadows)==null?void 0:w.large,"--admesh-spacing-sm":(v=e.spacing)==null?void 0:v.small,"--admesh-spacing-md":(_=e.spacing)==null?void 0:_.medium,"--admesh-spacing-lg":(f=e.spacing)==null?void 0:f.large,"--admesh-font-size-sm":(M=e.fontSize)==null?void 0:M.small,"--admesh-font-size-base":(A=e.fontSize)==null?void 0:A.base,"--admesh-font-size-lg":(S=e.fontSize)==null?void 0:S.large,"--admesh-font-size-title":(k=e.fontSize)==null?void 0:k.title,fontFamily:e.fontFamily,width:((g=(E=e.components)==null?void 0:E.productCard)==null?void 0:g.width)||"100%"}:{width:"100%"};if(r==="simple"){const R=t.ad_id||"",j=t.product_id||"";return d.jsx(D,{adId:R,productId:j,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:n,className:F("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",o),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(y=e==null?void 0:e.components)==null?void 0:y.productCard,...s},children:d.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[d.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:ee(t,z(t)),children:z(t)}),d.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[i.description," "]}),d.jsx(P,{adId:t.ad_id||"",admeshLink:t.click_url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"simple_ad_cta"},children:d.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:i.ctaText})})]})})}const u=t.ad_id||"",l=t.product_id||"";return d.jsx(D,{adId:u,productId:l,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:n,className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(C=e==null?void 0:e.components)==null?void 0:C.productCard,...s},children:d.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(T=e==null?void 0:e.components)==null?void 0:T.productCard,...s},"data-admesh-theme":e==null?void 0:e.mode,children:d.jsxs("div",{className:"h-full flex flex-col",style:m,children:[d.jsx("div",{className:"mb-1.5",children:d.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:ee(t,z(t)),children:z(t)})}),d.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((x=t.product_logo)==null?void 0:x.url)&&d.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:R=>{R.target.style.display="none"}}),d.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:i.title})]}),d.jsx("div",{className:"flex-shrink-0",children:d.jsx(P,{adId:t.ad_id||"",admeshLink:t.click_url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"product_card_cta"},children:d.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:["Visit",d.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),d.jsx("div",{className:"mb-3",children:d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:i.description})}),d.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:d.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[d.jsx("span",{children:"Sponsored"}),d.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};H.displayName="AdMeshProductCard";const ae=({recommendations:t,summaryText:e,theme:r,className:o="",style:s={},onLinkClick:n,sessionId:a,response:i})=>{const c=t||(i==null?void 0:i.recommendations)||[],m=e||(i==null?void 0:i.citation_summary);if(!c||c.length===0)return console.log("[AdMesh Summary Layout] Empty recommendations array - not rendering anything"),null;console.log(`[AdMesh Summary Layout] Rendering with ${c.length} recommendations`);const u=()=>m?d.jsx(re,{summaryText:m,recommendations:c,theme:r,onLinkClick:n,sessionId:a}):d.jsx("div",{className:"fallback-citation",children:d.jsx(H,{recommendation:c[0],theme:r,sessionId:a})});return d.jsx("div",{className:`admesh-summary-layout ${o}`,style:{fontFamily:(r==null?void 0:r.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...s},children:u()})},se=({recommendations:t,summaryText:e,theme:r,className:o,style:s,onLinkClick:n,sessionId:a,response:i})=>{const c=t||(i==null?void 0:i.recommendations)||[],m=e||(i==null?void 0:i.citation_summary);return!c||c.length===0?(console.log("[AdMeshLayout] Empty recommendations array - not rendering anything"),null):d.jsx(ae,{recommendations:c,summaryText:m,theme:r,className:o,style:s,onLinkClick:n,sessionId:a})};class ie{constructor(e){L(this,"firedExposures",new Set);L(this,"debug",!1);L(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,r,o){const s=`${o}_${r}`;if(this.firedExposures.has(s)){this.debug&&console.log("[Tracker] Exposure already fired for:",r);return}this.firedExposures.add(s);try{fetch(e,{method:"GET",keepalive:!0}).catch(n=>{this.debug&&console.warn("[Tracker] Failed to fire exposure:",n)}),this.debug&&console.log("[Tracker] Fired MRC-compliant exposure for:",r)}catch(n){this.debug&&console.error("[Tracker] Error firing exposure:",n)}}async fireExposureWithMRCCompliance(e,r,o,s){const n=`${o}_${r}`;if(this.firedExposures.has(n)){this.debug&&console.log("[Tracker] MRC exposure already fired for:",r);return}return new Promise(a=>{let i=null,c=null;const m=new IntersectionObserver(p=>{p.forEach(b=>{const w=b.intersectionRatio*100;w>=this.mrcThreshold.visibilityPercentage?i===null&&(i=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold:",{adId:r,visibilityPercentage:w.toFixed(2)}),c=setTimeout(()=>{this.fireExposure(e,r,o),m.disconnect(),a()},this.mrcThreshold.minimumDurationMs)):i!==null&&(c&&(clearTimeout(c),c=null),i=null,this.debug&&console.log("[Tracker] Ad visibility dropped below MRC threshold:",{adId:r,visibilityPercentage:w.toFixed(2)}))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});m.observe(s);const l=setTimeout(()=>{m.disconnect(),c&&clearTimeout(c),a()},3e4);s.__admeshTrackerCleanup=()=>{m.disconnect(),c&&clearTimeout(c),clearTimeout(l)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class ce{constructor(){L(this,"roots",new Map)}async render(e){var r,o,s;try{console.log(`[AdMeshRenderer] ๐จ Attempting to render into container: ${e.containerId}`);const n=document.getElementById(e.containerId);if(!n)throw console.error(`[AdMeshRenderer] โ Container not found: ${e.containerId}`),console.log("[AdMeshRenderer] ๐ Available containers in DOM:",Array.from(document.querySelectorAll('[id*="admesh"]')).map(m=>m.id)),new Error(`Container with ID "${e.containerId}" not found`);console.log("[AdMeshRenderer] โ
Container found:",{id:e.containerId,tagName:n.tagName,className:n.className,innerHTML:n.innerHTML.substring(0,100)});const a=this.roots.get(e.containerId);a&&(console.log(`[AdMeshRenderer] ๐งน Cleaning up existing root for: ${e.containerId}`),a.unmount(),this.roots.delete(e.containerId)),n.innerHTML="";const i=we.createRoot(n),c=((o=(r=e.response.recommendations)==null?void 0:r[0])==null?void 0:o.citation_summary)||"";console.log("[AdMeshRenderer] ๐ Rendering recommendations:",{containerId:e.containerId,recommendationsCount:((s=e.response.recommendations)==null?void 0:s.length)||0,hasCitationSummary:!!c}),i.render(d.jsx(se,{recommendations:e.response.recommendations||[],summaryText:c,theme:e.theme,sessionId:e.sessionId})),console.log(`[AdMeshRenderer] โ
Recommendations rendered successfully into: ${e.containerId}`),this.roots.set(e.containerId,i)}catch(n){throw console.error("[AdMeshRenderer] โ Error rendering recommendations:",n),n}}unmount(e){const r=this.roots.get(e);r&&(r.unmount(),this.roots.delete(e))}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class de{constructor(e={}){L(this,"autoAddLabels");L(this,"fireExposurePixels");L(this,"labelStyle");L(this,"processedLinks",new Set);L(this,"mutationObserver",null);var r,o,s,n;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((r=e.labelStyle)==null?void 0:r.fontSize)||"0.75em",fontWeight:((o=e.labelStyle)==null?void 0:o.fontWeight)||"bold",color:((s=e.labelStyle)==null?void 0:s.color)||"#666",marginLeft:((n=e.labelStyle)==null?void 0:n.marginLeft)||"2px"}}getLinksToProcess(e){const o=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return o.length>0?Array.from(o):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,r,o){if(!e)return[];const s=[];if(r.length>0){const n=this.getLinksToProcess(e),a=new Map(r.filter(i=>i.click_url).map(i=>[i.click_url,i]));n.forEach(i=>{var l;const c=i.getAttribute("href")||"",m=`${c}`;if(this.processedLinks.has(m))return;const u=a.get(c);if(u){this.processedLinks.add(m);const p={element:i,href:c,text:i.textContent||"",hasAdLabel:this.hasAdLabel(i),matchedRecommendation:{ad_id:u.ad_id||((l=u.meta)==null?void 0:l.ad_id)||"",click_url:u.click_url,exposure_url:u.exposure_url}};this.autoAddLabels&&!p.hasAdLabel&&(this.addAdLabel(i),p.hasAdLabel=!0),this.fireExposurePixels&&u.exposure_url&&o&&p.matchedRecommendation&&o({exposureUrl:u.exposure_url,adId:p.matchedRecommendation.ad_id,linkElement:i}),s.push(p)}})}else Array.from(e.querySelectorAll("a")).forEach(a=>{const i=a.getAttribute("href")||"",c=`${i}`;if(this.processedLinks.has(c))return;if(this.isAdMeshLink(i)){this.processedLinks.add(c);const u={element:a,href:i,text:a.textContent||"",hasAdLabel:this.hasAdLabel(a),matchedRecommendation:void 0};a.setAttribute("target","_blank"),a.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!u.hasAdLabel&&(this.addAdLabel(a),u.hasAdLabel=!0),this.fireExposurePixels&&o&&o({exposureUrl:i,adId:this.extractAdIdFromUrl(i),linkElement:a}),s.push(u)}});return s}hasAdLabel(e){var s,n;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const a=r.textContent||"";if(a.trim()===""){r=r.previousSibling;continue}if(a.includes("[Ad]"))return!0;break}if(r&&r.nodeType===Node.ELEMENT_NODE){const a=r;if((a.tagName==="SUB"||a.tagName==="SPAN")&&((s=a.textContent)!=null&&s.includes("[Ad]")))return!0}let o=e.nextSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const a=o.textContent||"";if(a.trim()===""){o=o.nextSibling;continue}if(a.includes("[Ad]"))return!0;break}if(o&&o.nodeType===Node.ELEMENT_NODE){const a=o;if((a.tagName==="SUB"||a.tagName==="SPAN")&&((n=a.textContent)!=null&&n.includes("[Ad]")))return!0}return!1}addAdLabel(e){var n;if(this.hasAdLabel(e))return;this.removeLeftAdLabel(e);const r=document.createElement("sub");r.textContent="[Ad]",r.style.fontSize=this.labelStyle.fontSize,r.style.fontWeight=this.labelStyle.fontWeight,r.style.color=this.labelStyle.color,r.style.marginLeft=this.labelStyle.marginLeft,r.style.cursor="pointer",r.style.borderBottom=`1px dotted ${this.labelStyle.color}`,r.style.whiteSpace="nowrap",r.title="Why this ad? This is a sponsored recommendation based on your search query.";let o=!1;r.addEventListener("mouseenter",()=>{r.style.opacity="0.7"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1",o&&(o=!1)}),r.addEventListener("click",a=>{a.stopPropagation(),o=!o,o?(r.style.textDecoration="underline",r.style.opacity="0.7"):(r.style.textDecoration="none",r.style.opacity="1")});const s=a=>{o&&a.target!==r&&(o=!1,r.style.textDecoration="none",r.style.opacity="1")};document.addEventListener("click",s),(n=e.parentNode)==null||n.insertBefore(r,e.nextSibling)}removeLeftAdLabel(e){var o,s,n;let r=e.previousSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const a=r.textContent||"";if(a.trim()===""){r=r.previousSibling;continue}if(a.includes("[Ad]")){(o=r.parentNode)==null||o.removeChild(r);return}break}if(r&&r.nodeType===Node.ELEMENT_NODE){const a=r;(a.tagName==="SUB"||a.tagName==="SPAN")&&((s=a.textContent)!=null&&s.includes("[Ad]"))&&((n=a.parentNode)==null||n.removeChild(a))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(s=>e.includes(s)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractAdIdFromUrl(e){try{const r=e.match(/\/click\/([^/?]+)/);return r&&r[1]?r[1]:e}catch{return e}}watchForNewLinks(e,r,o){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,r,o)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}class le{constructor(e){L(this,"config");L(this,"apiBaseUrl");L(this,"renderer",null);L(this,"tracker",null);L(this,"weaveProcessor",null);L(this,"weaveCache",new Map);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}static createSession(){const e=Date.now(),r=Math.random().toString(36).substring(2,15);return`session_${e}_${r}`}static createMessageId(e){const r=Date.now(),o=Math.random().toString(36).substring(2,15);return`msg_${e}_${r}_${o}`}getRenderer(){return this.renderer||(this.renderer=new ce),this.renderer}getTracker(){return this.tracker||(this.tracker=new ie({apiKey:this.config.apiKey})),this.tracker}getWeaveProcessor(){return this.weaveProcessor||(this.weaveProcessor=new de({autoAddLabels:!0,fireExposurePixels:!0})),this.weaveProcessor}async showRecommendations(e){try{const r=await this.fetchRecommendationsFromAPI({query:e.query,format:e.format||"auto",previousQuery:e.previousQuery,previousSummary:e.previousSummary,sessionId:e.session_id,messageId:e.message_id,isFallbackAllowed:e.isFallbackAllowed!==!1});if(e.format==="weave")await this.handleWeaveFormat(e,r);else{const o=this.getRenderer(),s=this.getTracker();await o.render({containerId:e.containerId,response:r,theme:e.theme||this.config.theme,tracker:s,sessionId:e.session_id||""})}}catch(r){throw console.error("[AdMeshSDK] Error showing recommendations:",r),r}}async handleWeaveFormat(e,r){const o=e.session_id||"",s=e.message_id||"",n=e.timeoutMs||900,a=e.fallbackFormat||"citation",i=`${o}:${s}`;if(this.weaveCache.set(i,r.recommendations||[]),e.llmOutputContainerId)try{if(await this.scanLLMOutputForAdMeshLinks(e.llmOutputContainerId,r.recommendations||[],o,n)){console.log("[AdMeshSDK] Weave format: AdMesh links detected in LLM output. Skipping fallback UI.");return}}catch(l){console.error("[AdMeshSDK] Error scanning LLM output for AdMesh links:",l)}console.log("[AdMeshSDK] Weave format: No AdMesh links detected. Rendering fallback UI with format:",a);const c=r,m=this.getRenderer(),u=this.getTracker();await m.render({containerId:e.containerId,response:c,theme:e.theme||this.config.theme,tracker:u,sessionId:o})}async scanLLMOutputForAdMeshLinks(e,r,o,s){const n=document.getElementById(e);if(!n)return console.warn(`[AdMeshSDK] LLM output container not found: ${e}`),!1;const a=Date.now(),i=100;let c=!1,m=null;try{const u=new Promise(b=>{const w=new MutationObserver(()=>{this.scanAndLabelAds(e,r,o)&&!c&&(c=!0,console.log("[AdMeshSDK] AdMesh links detected via MutationObserver"),b(!0))});w.observe(n,{childList:!0,subtree:!0,characterData:!1}),m=w}),l=(async()=>{for(;Date.now()-a<s;){if(this.scanAndLabelAds(e,r,o)&&!c)return c=!0,console.log("[AdMeshSDK] AdMesh links detected via polling"),!0;await this.sleep(i)}return!1})();return await Promise.race([u,l])}finally{m&&m.disconnect()}}scanAndLabelAds(e,r,o){const s=document.getElementById(e);if(!s)return!1;const n=this.getWeaveProcessor(),a=this.getTracker();return n.scanAndProcessLinks(s,r,({exposureUrl:c,adId:m,linkElement:u})=>{!c||!m||!u||!o||a.fireExposureWithMRCCompliance(c,m,o,u)}).length>0}async fetchRecommendationsFromAPI(e){var c;const r=`${this.apiBaseUrl}/agent/recommend`;console.log("[AdMeshSDK] ๐ฅ fetchRecommendationsFromAPI called with params:",{query:e.query?`"${e.query.substring(0,50)}${e.query.length>50?"...":""}"`:"(EMPTY)",queryType:typeof e.query,queryLength:(c=e.query)==null?void 0:c.length,format:e.format,sessionId:e.sessionId,messageId:e.messageId});const o={query:e.query,format:e.format||"auto",source:"admesh_ui_sdk"};e.previousQuery&&(o.previous_query=e.previousQuery),e.previousSummary&&(o.previous_summary=e.previousSummary),e.sessionId&&(o.session_id=e.sessionId),e.messageId&&(o.message_id=e.messageId),e.isFallbackAllowed!==void 0&&(o.is_fallback_allowed=e.isFallbackAllowed);const s=typeof o.query=="string"?o.query:"";(!s||!s.trim())&&(console.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query"),console.log("[AdMeshSDK] Full payload:",JSON.stringify(o,null,2)));const n=JSON.stringify(o);console.log("[AdMeshSDK] ๐ค Sending JSON body:",n);const a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:n});if(!a.ok){const u=(await a.json().catch(()=>({}))).detail||`HTTP ${a.status}`;throw new Error(`Failed to fetch recommendations: ${u}`)}return await a.json()}sleep(e){return new Promise(r=>setTimeout(r,e))}}const K=h.createContext(void 0);function me(){const t=h.useContext(K);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}const Ue=({apiKey:t,sessionId:e,theme:r,apiBaseUrl:o,children:s})=>{const n=h.useRef(null),[a,i]=h.useState(new Set);h.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}try{n.current=new le({apiKey:t,theme:r,apiBaseUrl:o}),console.log("[AdMeshProvider] โ
AdMesh SDK initialized"),o&&console.log(`[AdMeshProvider] ๐ Using custom API base URL: ${o}`)}catch(m){console.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK:",m)}return()=>{console.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,r,o]);const c={sdk:n.current,apiKey:t,sessionId:e,theme:r,processedMessageIds:a,markMessageAsProcessed:m=>{i(u=>{const l=new Set(u);return l.add(m),l})},isMessageProcessed:m=>a.has(m)};return d.jsx(K.Provider,{value:c,children:s})};function I(){const t=me();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const He=({format:t="citation",onRecommendationsShown:e,onError:r,messageId:o,query:s})=>{const{sdk:n,sessionId:a}=I(),i=h.useRef(null),[c,m]=h.useState("");return h.useEffect(()=>{o&&m(`admesh-recommendations-${o}`)},[o]),h.useEffect(()=>{if(console.log("[AdMeshRecommendations] ๐ SDK VERSION CHECK - Props received:",{sdkVersion:"1.0.6-no-dedup",timestamp:new Date().toISOString(),messageId:o,query:s?`"${s.substring(0,50)}${s.length>50?"...":""}"`:"(EMPTY)",queryType:typeof s,queryLength:s==null?void 0:s.length,format:t,sessionId:a}),!o||!s||s.trim()===""){console.log("[AdMeshRecommendations] โ Validation failed - returning early:",{hasMessageId:!!o,hasQuery:!!s,queryTrimmed:s==null?void 0:s.trim(),queryTrimmedLength:s==null?void 0:s.trim().length});return}if(console.log("[AdMeshRecommendations] โ
Validation passed"),!n||!c){console.log("[AdMeshRecommendations] SDK or containerId not ready:",{hasSdk:!!n,hasContainerId:!!c});return}(async()=>{try{if(!(n!=null&&n.showRecommendations)){console.log("[AdMeshRecommendations] SDK showRecommendations not available");return}console.log("[AdMeshRecommendations] ๐ค Calling sdk.showRecommendations with:",{query:s.trim().substring(0,50),containerId:c,format:t,session_id:a,message_id:o}),await n.showRecommendations({query:s.trim(),containerId:c,format:t,session_id:a,message_id:o}),e==null||e(o)}catch(l){const p=l instanceof Error?l:new Error(String(l));console.log("[AdMeshRecommendations] โ Error:",p.message),r==null||r(p)}})()},[n,a,c,t,o,s,e,r]),d.jsx("div",{ref:i,id:c,className:"admesh-recommendations-container",style:{marginTop:"1rem",minHeight:"100px",display:"block"}})},ue=({format:t="citation",onError:e,messageId:r,query:o,fallback:s})=>{const{sdk:n,sessionId:a}=I(),i=h.useRef(null),[c,m]=h.useState("");return h.useEffect(()=>{r&&m(`admesh-weave-fallback-${r}`)},[r]),console.log("[WeaveFallbackRecommendations] ๐จ Component render:",{messageId:r,fallback:s,hasQuery:!!o,timestamp:new Date().toISOString()}),h.useEffect(()=>{if(console.log("[WeaveFallbackRecommendations] ๐ useEffect triggered - Props:",{timestamp:new Date().toISOString(),messageId:r,query:o?`"${o.substring(0,50)}${o.length>50?"...":""}"`:"(EMPTY)",queryType:typeof o,queryLength:o==null?void 0:o.length,format:t,sessionId:a,fallback:s}),!s){console.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(console.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!r||!o||o.trim()===""){console.log("[WeaveFallbackRecommendations] โ Validation failed - returning early:",{hasMessageId:!!r,hasQuery:!!o,queryTrimmed:o==null?void 0:o.trim(),queryTrimmedLength:o==null?void 0:o.trim().length});return}if(console.log("[WeaveFallbackRecommendations] โ
Validation passed"),!n||!c){console.log("[WeaveFallbackRecommendations] SDK or containerId not ready:",{hasSdk:!!n,hasContainerId:!!c});return}(async()=>{try{if(!(n!=null&&n.showRecommendations)){console.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}console.log("[WeaveFallbackRecommendations] ๐ค Calling sdk.showRecommendations with:",{query:o.trim().substring(0,50),containerId:c,format:t,session_id:a,message_id:r}),await n.showRecommendations({query:o.trim(),containerId:c,format:t,session_id:a,message_id:r}),console.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(l){const p=l instanceof Error?l:new Error(String(l));console.log("[WeaveFallbackRecommendations] โ Error:",p.message),e==null||e(p)}})()},[n,a,c,t,r,o,s,e]),d.jsx("div",{ref:i,id:c,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",minHeight:"100px",display:"block"}})},he=h.createContext(void 0),Ke=({children:t,shouldRenderFallback:e,messageId:r,sessionId:o,query:s})=>d.jsx(he.Provider,{value:{shouldRenderFallback:e,messageId:r,sessionId:o,query:s},children:t}),Ye=()=>h.useContext(he),Ge=({recommendations:t,title:e="Product Recommendations",showTitle:r=!0,className:o="",cardClassName:s="",onProductClick:n,maxCards:a=10,cardWidth:i="md",theme:c="auto",borderRadius:m="md",shadow:u="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const l=t.slice(0,a),p=()=>{switch(i){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},b=()=>{switch(m){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},w=()=>{switch(u){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},v=()=>c==="dark"?"bg-gray-900 text-white":c==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",_=f=>{if(n)n(f);else{const M=f.click_url||f.url;M&&window.open(M,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:d.jsxs("div",{className:F("w-full",o),children:[r&&d.jsxs("div",{className:"mb-4",children:[d.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),d.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),d.jsxs("div",{className:"relative",children:[l.length===0?d.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):d.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:l.map(f=>{var k;const M=f.product_id||f.id||f.ad_id,A=f.ad_id||f.product_id||"",S=f.product_id||"";return d.jsx(D,{adId:A,productId:S,className:F(p(),b(),w(),v(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",s),onClick:()=>_(f),children:d.jsxs("div",{children:[d.jsx("div",{className:"relative aspect-square w-full overflow-hidden",children:(k=f.product_logo)!=null&&k.url?d.jsx("img",{src:f.product_logo.url,alt:f.product_title,className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy"}):d.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:d.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),d.jsxs("div",{className:"p-3",children:[d.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:f.product_title}),f.weave_summary&&d.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2 mb-2",children:f.weave_summary}),f.categories&&f.categories.length>0&&d.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:f.categories.slice(0,2).map((E,g)=>d.jsx("span",{className:"text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded",children:E},g))}),f.trust_score!==void 0&&d.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Trust Score: ",(f.trust_score*100).toFixed(0),"%"]})]})]})},M)})}),l.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),d.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:d.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),d.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),d.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),d.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
974
974
|
.scrollbar-hide {
|
|
975
975
|
-ms-overflow-style: none;
|
|
976
976
|
scrollbar-width: none;
|
|
@@ -984,5 +984,5 @@
|
|
|
984
984
|
-webkit-box-orient: vertical;
|
|
985
985
|
overflow: hidden;
|
|
986
986
|
}
|
|
987
|
-
`}})]})},he=({recommendation:t,theme:e,variation:r="default",expandable:n=!1,className:s,style:o})=>{var m,l,u,p;const i={title:t.product_title||t.title,description:t.weave_summary||t.reason||"",ctaText:t.product_title||t.title},c=N("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":n&&(r==="question"||r==="statement")},s);return d.jsx("div",{className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((l=(m=e==null?void 0:e.components)==null?void 0:m.inlineRecommendation)==null?void 0:l.width)||"100%",...(u=e==null?void 0:e.components)==null?void 0:u.productCard,...o},"data-admesh-theme":e==null?void 0:e.mode,children:d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((p=t.product_logo)==null?void 0:p.url)&&d.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:f=>{f.target.style.display="none"}}),d.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:i.title})]}),d.jsx("div",{className:"flex-shrink-0",children:d.jsx(F,{adId:t.ad_id||"",admeshLink:t.click_url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"inline_card_cta"},children:d.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[r==="question"?"Try":"Visit",d.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.description&&d.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:i.description}),d.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:d.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[d.jsx("span",{children:"Sponsored"}),d.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};he.displayName="AdMeshInlineCard";const Ge={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Qe={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},pe=({type:t,variant:e,size:r="md",className:n,style:s})=>{const o=e||Ge[t]||"secondary",a=Qe[t],i=N("admesh-component","admesh-badge",`admesh-badge--${o}`,`admesh-badge--${r}`,n);return d.jsxs("span",{className:i,style:s,children:[a&&d.jsx("span",{className:"admesh-badge__icon",children:a}),d.jsx("span",{className:"admesh-badge__text",children:t})]})};pe.displayName="AdMeshBadge";const $="admesh:streamingStart",O="admesh:streamingComplete";function Je(t,e){const r={messageId:t,sessionId:e,timestamp:Date.now()},n=new CustomEvent($,{detail:r});window.dispatchEvent(n),console.log("[StreamingEvents] ๐ข Dispatched streamingStart event:",{messageId:t,sessionId:e})}function Xe(t,e,r){const n={messageId:t,sessionId:e,timestamp:Date.now(),metadata:r},s=new CustomEvent(O,{detail:n});window.dispatchEvent(s),console.log("[StreamingEvents] ๐ข Dispatched streamingComplete event:",{messageId:t,sessionId:e,metadata:r})}function qe(t,e,r){const n=s=>{const o=s;o.detail.messageId===t&&o.detail.sessionId===e&&(console.log("[StreamingEvents] ๐จ Received streamingStart for:",t),r(o.detail))};return window.addEventListener($,n),()=>{window.removeEventListener($,n)}}function fe(t,e,r){const n=s=>{const o=s;o.detail.messageId===t&&o.detail.sessionId===e&&(console.log("[StreamingEvents] ๐จ Received streamingComplete for:",t),r(o.detail))};return window.addEventListener(O,n),()=>{window.removeEventListener(O,n)}}const Ze=({containerId:t,messageId:e,sessionId:r,sdk:n,onLinksFound:s,onNoLinksFound:o,children:a})=>{const[i,c]=h.useState(!1),[m,l]=h.useState(!0),[u,p]=h.useState(!1),f=h.useRef(s),k=h.useRef(o),y=h.useRef(t),_=h.useRef(n);h.useEffect(()=>{f.current=s,k.current=o,y.current=t,_.current=n},[s,o,t,n]);const b=h.useCallback(()=>{var S,M;console.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const w=document.getElementById(y.current);if(!w){console.warn(`[FinalLinkDetectionCheck] โ Container not found: ${y.current}`),c(!0),o();return}const C=(M=(S=_.current)==null?void 0:S.getWeaveProcessor)==null?void 0:M.call(S);if(!C){console.warn("[FinalLinkDetectionCheck] โ WeaveProcessor not available"),c(!0),o();return}const E=C.scanAndProcessLinks(w,[],()=>{});console.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${E.length} links`),E.length>0?(console.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),f.current(E.length)):(console.log("[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will make API call)"),p(!1),k.current()),c(!0)}catch(w){console.error("[FinalLinkDetectionCheck] โ Error during final check:",w),c(!0),k.current()}},[]);return h.useEffect(()=>{const S=Date.now();console.log("[FinalLinkDetectionCheck] โณ Setting up listener at",S,":",{messageId:e,sessionId:r});const M=fe(e,r,w=>{const C=Date.now();console.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event at",C,"(listener was set up",C-S,"ms ago):",w),l(!1),setTimeout(()=>{b()},100)});return()=>{console.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener for:",e),M()}},[e,r]),m?d.jsx(d.Fragment,{}):i?u?(console.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),d.jsx(d.Fragment,{})):(console.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),d.jsx(d.Fragment,{children:a})):d.jsx(d.Fragment,{})},et=({messageId:t,children:e,fallbackFormat:r="citation",onLinksDetected:n,onNoLinksDetected:s,onError:o,className:a,query:i,onFallbackChange:c})=>{const{sessionId:m,sdk:l}=P(),u=h.useRef(null),p=`weave-ad-container-${t}`;return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:u,id:p,className:a,"data-weave-ad-format":"true","data-message-id":t,children:e}),i&&d.jsx(Ze,{containerId:p,messageId:t,sessionId:m,sdk:l,onLinksFound:f=>{console.log(`[WeaveAdFormatContainer] โ
Links found (${f}) - no fallback needed`),n==null||n(f),c==null||c(!1)},onNoLinksFound:()=>{console.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),s==null||s(),c==null||c(!0)},children:d.jsx(me,{format:r,messageId:t,query:i,fallback:!0,onError:o})})]})},tt=t=>{const{sdk:e,sessionId:r}=P(),n=h.useRef(!1),s=h.useRef(0),o=h.useRef(!1),a=h.useRef(!1),i=h.useRef(null),c=h.useRef(Date.now()),m=h.useRef(0),l=h.useRef(null),u=h.useRef([]),p=h.useRef(300),f=h.useCallback(async()=>{var y,_,b,S;if(!(!e||!r||n.current)){n.current=!0,s.current=0;try{const M=document.getElementById(t.llmOutputContainerId);if(!M)return;const w=(y=e.getWeaveProcessor)==null?void 0:y.call(e);if(!w)return;const C=w.scanAndProcessLinks(M,[],()=>{});s.current=C.length;const E=C.length>0;if(E&&!o.current)o.current=!0,(_=t.onLinksDetected)==null||_.call(t,C.length),a.current=!0;else if(!E&&o.current)o.current=!1,a.current=!1;else if(!E&&!a.current){i.current&&clearTimeout(i.current),l.current&&clearInterval(l.current),m.current=0,c.current=Date.now();const g=Math.max(100,p.current/3);l.current=setInterval(()=>{var x;const A=Date.now()-c.current,T=p.current;A>=T?(m.current++,m.current>=2&&(l.current&&(clearInterval(l.current),l.current=null),!o.current&&!a.current&&((x=t.onNoLinksDetected)==null||x.call(t),a.current=!0))):m.current=0},g);const v=Math.max(1500,p.current*5);i.current=setTimeout(()=>{var A;l.current&&(clearInterval(l.current),l.current=null),!o.current&&!a.current&&((A=t.onNoLinksDetected)==null||A.call(t),a.current=!0)},v)}else E&&a.current&&!o.current&&(i.current&&(clearTimeout(i.current),i.current=null),o.current=!0,(b=t.onLinksDetected)==null||b.call(t,C.length),a.current=!0)}catch(M){const w=M instanceof Error?M:new Error(String(M));(S=t.onError)==null||S.call(t,w)}finally{n.current=!1}}},[e,r,t]),k=h.useCallback(()=>{const y=u.current;if(y.length<2){p.current=300;return}const _=[];for(let M=1;M<y.length;M++)_.push(y[M]-y[M-1]);const b=_.reduce((M,w)=>M+w,0)/_.length,S=Math.max(100,Math.min(b*3,1e3));p.current=S},[]);return h.useEffect(()=>{const y=document.getElementById(t.llmOutputContainerId);if(!y)return;f();const _=new MutationObserver(()=>{const b=Date.now();c.current=b,m.current=0,u.current.push(b),u.current.length>10&&u.current.shift(),k(),f()});return _.observe(y,{childList:!0,subtree:!0,characterData:!1}),()=>{_.disconnect(),i.current&&clearTimeout(i.current),l.current&&clearInterval(l.current)}},[t.llmOutputContainerId,f,k]),{isProcessing:n.current,detectedLinksCount:s.current,linksFound:o.current,shouldRenderFallback:!o.current&&a.current,processWeaveFormat:f}},rt="1.0.0";exports.AdMeshBadge=pe;exports.AdMeshContext=K;exports.AdMeshEcommerceCards=Ye;exports.AdMeshInlineCard=he;exports.AdMeshLayout=ae;exports.AdMeshLinkTracker=F;exports.AdMeshProductCard=H;exports.AdMeshProvider=Be;exports.AdMeshRecommendations=Ue;exports.AdMeshRenderer=ie;exports.AdMeshSDK=ce;exports.AdMeshSummaryLayout=oe;exports.AdMeshSummaryUnit=te;exports.AdMeshTracker=se;exports.AdMeshViewabilityTracker=j;exports.STREAMING_COMPLETE_EVENT=O;exports.STREAMING_START_EVENT=$;exports.VERSION=rt;exports.WeaveAdFormatContainer=et;exports.WeaveAdFormatProvider=He;exports.WeaveFallbackRecommendations=me;exports.WeaveResponseProcessor=de;exports.dispatchStreamingCompleteEvent=Xe;exports.dispatchStreamingStartEvent=Je;exports.onStreamingComplete=fe;exports.onStreamingStart=qe;exports.useAdMesh=P;exports.useAdMeshContext=le;exports.useAdMeshStyles=ne;exports.useAdMeshTracker=re;exports.useViewabilityTracker=ee;exports.useWeaveAdFormat=tt;exports.useWeaveAdFormatContext=Ke;
|
|
987
|
+
`}})]})},pe=({recommendation:t,theme:e,variation:r="default",expandable:o=!1,className:s,style:n})=>{var m,u,l,p;const i={title:t.product_title||t.title,description:t.weave_summary||t.reason||"",ctaText:t.product_title||t.title},c=F("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":o&&(r==="question"||r==="statement")},s);return d.jsx("div",{className:c,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((u=(m=e==null?void 0:e.components)==null?void 0:m.inlineRecommendation)==null?void 0:u.width)||"100%",...(l=e==null?void 0:e.components)==null?void 0:l.productCard,...n},"data-admesh-theme":e==null?void 0:e.mode,children:d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((p=t.product_logo)==null?void 0:p.url)&&d.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:b=>{b.target.style.display="none"}}),d.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:i.title})]}),d.jsx("div",{className:"flex-shrink-0",children:d.jsx(P,{adId:t.ad_id||"",admeshLink:t.click_url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"inline_card_cta"},children:d.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[r==="question"?"Try":"Visit",d.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.description&&d.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:i.description}),d.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:d.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[d.jsx("span",{children:"Sponsored"}),d.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};pe.displayName="AdMeshInlineCard";const Qe={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},Je={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},fe=({type:t,variant:e,size:r="md",className:o,style:s})=>{const n=e||Qe[t]||"secondary",a=Je[t],i=F("admesh-component","admesh-badge",`admesh-badge--${n}`,`admesh-badge--${r}`,o);return d.jsxs("span",{className:i,style:s,children:[a&&d.jsx("span",{className:"admesh-badge__icon",children:a}),d.jsx("span",{className:"admesh-badge__text",children:t})]})};fe.displayName="AdMeshBadge";const $="admesh:streamingStart",O="admesh:streamingComplete";function Xe(t,e){const r={messageId:t,sessionId:e,timestamp:Date.now()},o=new CustomEvent($,{detail:r});window.dispatchEvent(o),console.log("[StreamingEvents] ๐ข Dispatched streamingStart event:",{messageId:t,sessionId:e})}function qe(t,e,r){const o={messageId:t,sessionId:e,timestamp:Date.now(),metadata:r},s=new CustomEvent(O,{detail:o});window.dispatchEvent(s),console.log("[StreamingEvents] ๐ข Dispatched streamingComplete event:",{messageId:t,sessionId:e,metadata:r})}function Ze(t,e,r){const o=s=>{const n=s;n.detail.messageId===t&&n.detail.sessionId===e&&(console.log("[StreamingEvents] ๐จ Received streamingStart for:",t),r(n.detail))};return window.addEventListener($,o),()=>{window.removeEventListener($,o)}}function ge(t,e,r){const o=s=>{const n=s;n.detail.messageId===t&&n.detail.sessionId===e&&(console.log("[StreamingEvents] ๐จ Received streamingComplete for:",t),r(n.detail))};return window.addEventListener(O,o),()=>{window.removeEventListener(O,o)}}const Y=()=>{const t=new Set,e=new Map,r=n=>{const a=e.get(n);a&&(a.observer.disconnect(),a.timeoutId&&clearTimeout(a.timeoutId),e.delete(n))};return{startTracking:({exposureUrl:n,adId:a,linkElement:i,sessionId:c,logPrefix:m="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!n||!i){m&&console.warn(`${m} โ ๏ธ Missing exposure tracking data`,{hasExposureUrl:!!n,hasLinkElement:!!i});return}const u=`${c||"anonymous"}::${a||n}`;if(t.has(u)||e.has(u))return;const l={observer:void 0,timeoutId:null,viewableStart:null},p=()=>{r(u),t.add(u),fetch(n,{method:"GET",keepalive:!0}).then(()=>{m&&console.log(`${m} โ
Exposure pixel fired`,{adId:a,exposureUrl:n.substring(0,80),sessionId:c})}).catch(w=>{m&&console.warn(`${m} โ ๏ธ Failed to fire exposure pixel`,w),t.delete(u)})},b=new IntersectionObserver(w=>{w.forEach(v=>{v.intersectionRatio>=.5?l.viewableStart===null&&(l.viewableStart=performance.now(),l.timeoutId=setTimeout(p,1e3)):(l.viewableStart=null,l.timeoutId&&(clearTimeout(l.timeoutId),l.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});l.observer=b,b.observe(i),e.set(u,l)},cleanup:()=>{Array.from(e.keys()).forEach(r)}}},et=({containerId:t,messageId:e,sessionId:r,sdk:o,onLinksFound:s,onNoLinksFound:n,children:a})=>{const[i,c]=h.useState(!1),[m,u]=h.useState(!0),[l,p]=h.useState(!1),b=h.useRef(Y()),w=h.useRef(s),v=h.useRef(n),_=h.useRef(t),f=h.useRef(o),M=h.useRef(r);h.useEffect(()=>{w.current=s,v.current=n,_.current=t,f.current=o,M.current=r},[s,n,t,o,r]),h.useEffect(()=>()=>{b.current.cleanup()},[]);const A=h.useCallback(({exposureUrl:k,adId:E,linkElement:g})=>{b.current.startTracking({exposureUrl:k,adId:E,linkElement:g,sessionId:M.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),S=h.useCallback(()=>{var k,E;console.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const g=document.getElementById(_.current);if(!g){console.warn(`[FinalLinkDetectionCheck] โ Container not found: ${_.current}`),c(!0),n();return}const y=(E=(k=f.current)==null?void 0:k.getWeaveProcessor)==null?void 0:E.call(k);if(!y){console.warn("[FinalLinkDetectionCheck] โ WeaveProcessor not available"),c(!0),n();return}const C=y.scanAndProcessLinks(g,[],({exposureUrl:T,adId:x,linkElement:R})=>A({exposureUrl:T,adId:x,linkElement:R}));console.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${C.length} links`),C.length>0?(console.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),w.current(C.length)):(console.log("[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will make API call)"),p(!1),v.current()),c(!0)}catch(g){console.error("[FinalLinkDetectionCheck] โ Error during final check:",g),c(!0),v.current()}},[A]);return h.useEffect(()=>{const k=Date.now();console.log("[FinalLinkDetectionCheck] โณ Setting up listener at",k,":",{messageId:e,sessionId:r});const E=ge(e,r,g=>{const y=Date.now();console.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event at",y,"(listener was set up",y-k,"ms ago):",g),u(!1),setTimeout(()=>{S()},100)});return()=>{console.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener for:",e),E()}},[e,r]),m?d.jsx(d.Fragment,{}):i?l?(console.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),d.jsx(d.Fragment,{})):(console.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),d.jsx(d.Fragment,{children:a})):d.jsx(d.Fragment,{})},tt=({messageId:t,children:e,fallbackFormat:r="citation",onLinksDetected:o,onNoLinksDetected:s,onError:n,className:a,query:i,onFallbackChange:c})=>{const{sessionId:m,sdk:u}=I(),l=h.useRef(null),p=`weave-ad-container-${t}`;return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:l,id:p,className:a,"data-weave-ad-format":"true","data-message-id":t,children:e}),i&&d.jsx(et,{containerId:p,messageId:t,sessionId:m,sdk:u,onLinksFound:b=>{console.log(`[WeaveAdFormatContainer] โ
Links found (${b}) - no fallback needed`),o==null||o(b),c==null||c(!1)},onNoLinksFound:()=>{console.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),s==null||s(),c==null||c(!0)},children:d.jsx(ue,{format:r,messageId:t,query:i,fallback:!0,onError:n})})]})},rt=t=>{const{sdk:e,sessionId:r}=I(),o=h.useRef(!1),s=h.useRef(0),n=h.useRef(!1),a=h.useRef(!1),i=h.useRef(null),c=h.useRef(Y());h.useEffect(()=>()=>{c.current.cleanup()},[]);const m=h.useCallback(({exposureUrl:f,adId:M,linkElement:A})=>{c.current.startTracking({exposureUrl:f,adId:M,linkElement:A,sessionId:r,logPrefix:"[useWeaveAdFormat]"})},[r]),u=h.useRef(Date.now()),l=h.useRef(0),p=h.useRef(null),b=h.useRef([]),w=h.useRef(300),v=h.useCallback(async()=>{var f,M,A,S;if(!(!e||!r||o.current)){o.current=!0,s.current=0;try{const k=document.getElementById(t.llmOutputContainerId);if(!k)return;const E=(f=e.getWeaveProcessor)==null?void 0:f.call(e);if(!E)return;const g=E.scanAndProcessLinks(k,[],({exposureUrl:C,adId:T,linkElement:x})=>m({exposureUrl:C,adId:T,linkElement:x}));s.current=g.length;const y=g.length>0;if(y&&!n.current)n.current=!0,(M=t.onLinksDetected)==null||M.call(t,g.length),a.current=!0;else if(!y&&n.current)n.current=!1,a.current=!1;else if(!y&&!a.current){i.current&&clearTimeout(i.current),p.current&&clearInterval(p.current),l.current=0,u.current=Date.now();const C=Math.max(100,w.current/3);p.current=setInterval(()=>{var j;const x=Date.now()-u.current,R=w.current;x>=R?(l.current++,l.current>=2&&(p.current&&(clearInterval(p.current),p.current=null),!n.current&&!a.current&&((j=t.onNoLinksDetected)==null||j.call(t),a.current=!0))):l.current=0},C);const T=Math.max(1500,w.current*5);i.current=setTimeout(()=>{var x;p.current&&(clearInterval(p.current),p.current=null),!n.current&&!a.current&&((x=t.onNoLinksDetected)==null||x.call(t),a.current=!0)},T)}else y&&a.current&&!n.current&&(i.current&&(clearTimeout(i.current),i.current=null),n.current=!0,(A=t.onLinksDetected)==null||A.call(t,g.length),a.current=!0)}catch(k){const E=k instanceof Error?k:new Error(String(k));(S=t.onError)==null||S.call(t,E)}finally{o.current=!1}}},[e,r,t,m]),_=h.useCallback(()=>{const f=b.current;if(f.length<2){w.current=300;return}const M=[];for(let k=1;k<f.length;k++)M.push(f[k]-f[k-1]);const A=M.reduce((k,E)=>k+E,0)/M.length,S=Math.max(100,Math.min(A*3,1e3));w.current=S},[]);return h.useEffect(()=>{const f=document.getElementById(t.llmOutputContainerId);if(!f)return;v();const M=new MutationObserver(()=>{const A=Date.now();u.current=A,l.current=0,b.current.push(A),b.current.length>10&&b.current.shift(),_(),v()});return M.observe(f,{childList:!0,subtree:!0,characterData:!1}),()=>{M.disconnect(),i.current&&clearTimeout(i.current),p.current&&clearInterval(p.current)}},[t.llmOutputContainerId,v,_]),{isProcessing:o.current,detectedLinksCount:s.current,linksFound:n.current,shouldRenderFallback:!n.current&&a.current,processWeaveFormat:v}},nt="1.0.10";exports.AdMeshBadge=fe;exports.AdMeshContext=K;exports.AdMeshEcommerceCards=Ge;exports.AdMeshInlineCard=pe;exports.AdMeshLayout=se;exports.AdMeshLinkTracker=P;exports.AdMeshProductCard=H;exports.AdMeshProvider=Ue;exports.AdMeshRecommendations=He;exports.AdMeshRenderer=ce;exports.AdMeshSDK=le;exports.AdMeshSummaryLayout=ae;exports.AdMeshSummaryUnit=re;exports.AdMeshTracker=ie;exports.AdMeshViewabilityTracker=D;exports.STREAMING_COMPLETE_EVENT=O;exports.STREAMING_START_EVENT=$;exports.VERSION=nt;exports.WeaveAdFormatContainer=tt;exports.WeaveAdFormatProvider=Ke;exports.WeaveFallbackRecommendations=ue;exports.WeaveResponseProcessor=de;exports.createInlineExposureTracker=Y;exports.dispatchStreamingCompleteEvent=qe;exports.dispatchStreamingStartEvent=Xe;exports.onStreamingComplete=ge;exports.onStreamingStart=Ze;exports.useAdMesh=I;exports.useAdMeshContext=me;exports.useAdMeshStyles=oe;exports.useAdMeshTracker=ne;exports.useViewabilityTracker=te;exports.useWeaveAdFormat=rt;exports.useWeaveAdFormatContext=Ye;
|
|
988
988
|
//# sourceMappingURL=index.js.map
|