@saar-ai/web-widget 0.7.0 → 0.8.0
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/dist/chunks/{chat-tMKkYmTC.js → chat-e1afSRBr.js} +188 -3
- package/dist/chunks/{host-widget-B97T89b7.js → host-widget-Ce-l1xu1.js} +1147 -17
- package/dist/chunks/{schemas-Bl_6mxe4.js → schemas-D-uDc-9q.js} +164 -1
- package/dist/chunks/{telemetry-BI_SEWTb.js → telemetry-CBblNC6C.js} +1 -1
- package/dist/dock/dock-motion.d.ts +14 -0
- package/dist/dock/dock-motion.d.ts.map +1 -1
- package/dist/dock/dock.d.ts +30 -0
- package/dist/dock/dock.d.ts.map +1 -1
- package/dist/host-widget.d.ts +14 -2
- package/dist/host-widget.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/next/index.js +1 -1
- package/dist/use-chat-session.d.ts +45 -1
- package/dist/use-chat-session.d.ts.map +1 -1
- package/dist/use-voice-session.d.ts +35 -0
- package/dist/use-voice-session.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -462,8 +462,8 @@ function createScrollRecede(options) {
|
|
|
462
462
|
enabled = next;
|
|
463
463
|
if (next) anchor = last;
|
|
464
464
|
},
|
|
465
|
-
markProgrammatic() {
|
|
466
|
-
programmaticUntil = Date.now() + PROGRAMMATIC_WINDOW_MS;
|
|
465
|
+
markProgrammatic(ms) {
|
|
466
|
+
programmaticUntil = Date.now() + (ms ?? PROGRAMMATIC_WINDOW_MS);
|
|
467
467
|
if (timer !== void 0) {
|
|
468
468
|
clearTimeout(timer);
|
|
469
469
|
timer = void 0;
|
|
@@ -1620,6 +1620,20 @@ var SWAP_EASING = "cubic-bezier(0.2, 0, 0, 1)";
|
|
|
1620
1620
|
/** §7.2 — the waveform's per-frame smoothing. */
|
|
1621
1621
|
var LEVEL_LERP = .25;
|
|
1622
1622
|
/**
|
|
1623
|
+
* §5.3/§5.5's concierge-scroll exception — how long a flagged scroll stays
|
|
1624
|
+
* ours.
|
|
1625
|
+
*
|
|
1626
|
+
* Longer than `recede.ts`'s own default window, deliberately: that one is
|
|
1627
|
+
* sized for the few frames a bridge `navigate` emits before the document goes
|
|
1628
|
+
* away, and a `spotlight` is a SMOOTH scroll across an arbitrary distance —
|
|
1629
|
+
* the length of a collection page, on a slow phone. The cost of being generous
|
|
1630
|
+
* is asymmetric and that is why it is generous: too long and the dock ignores
|
|
1631
|
+
* one deliberate shopper scroll a second after the concierge acted; too short
|
|
1632
|
+
* and it recedes and ducks in the middle of its own gesture, which is the
|
|
1633
|
+
* failure the exception exists for.
|
|
1634
|
+
*/
|
|
1635
|
+
var CONCIERGE_SCROLL_WINDOW_MS = 1200;
|
|
1636
|
+
/**
|
|
1623
1637
|
* `prefers-reduced-motion`, as a subscription rather than a one-shot read.
|
|
1624
1638
|
*
|
|
1625
1639
|
* A shopper can turn it on mid-session (iOS has it in Control Center), and a
|
|
@@ -3542,7 +3556,7 @@ var DEFAULT_LAYOUT = {
|
|
|
3542
3556
|
};
|
|
3543
3557
|
var INTERRUPT_SEEN_STORAGE_KEY = "wgt_dock_interrupt_seen";
|
|
3544
3558
|
function Dock(props) {
|
|
3545
|
-
const { identity, color = DEFAULT_COLOR, type = DEFAULT_TYPE, layout = DEFAULT_LAYOUT, copy = {}, direction = "ltr", locale = "en", messages = defaultWidgetMessages, voice, escalated = false, offline = false, status, notice, statusKind, operatorLine, reconnecting = false, roomDropped = false, partialTranscript, preamble, clause, channel = "text", shelf, transcript, latestExchange, exchangeCount, sheetExtra, followKey, revealSheet = false, showPrice = true, cardImageAspect = DEFAULT_CARD_ASPECT, bottomOffset = "auto", curationHref, productHref, navigate, draft, onDraftChange, onSubmit, composerDisabled = false, onAttach, attachSlot, attachBusy, proactive, pageKey, onEndCall, skinStyle, skin, preview = false, announcement, attribution, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady } = props;
|
|
3559
|
+
const { identity, color = DEFAULT_COLOR, type = DEFAULT_TYPE, layout = DEFAULT_LAYOUT, copy = {}, direction = "ltr", locale = "en", messages = defaultWidgetMessages, voice, escalated = false, offline = false, status, notice, statusKind, operatorLine, reconnecting = false, roomDropped = false, partialTranscript, preamble, clause, channel = "text", shelf, transcript, latestExchange, exchangeCount, sheetExtra, followKey, revealSheet = false, showPrice = true, cardImageAspect = DEFAULT_CARD_ASPECT, bottomOffset = "auto", curationHref, productHref, navigate, draft, onDraftChange, onSubmit, composerDisabled = false, onAttach, attachSlot, attachBusy, proactive, pageKey, conciergeScrollRef, onEndCall, skinStyle, skin, preview = false, announcement, attribution, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady } = props;
|
|
3546
3560
|
const scopeId = useId().replace(/[^a-zA-Z0-9_-]/g, "");
|
|
3547
3561
|
const rootRef = useRef(null);
|
|
3548
3562
|
const rowRef = useRef(null);
|
|
@@ -4068,6 +4082,10 @@ function Dock(props) {
|
|
|
4068
4082
|
anchor = offset;
|
|
4069
4083
|
return;
|
|
4070
4084
|
}
|
|
4085
|
+
if (Date.now() < conciergeScrollUntilRef.current) {
|
|
4086
|
+
anchor = offset;
|
|
4087
|
+
return;
|
|
4088
|
+
}
|
|
4071
4089
|
if (Math.abs(offset - anchor) <= 24) return;
|
|
4072
4090
|
anchor = offset;
|
|
4073
4091
|
duckRef.current();
|
|
@@ -4104,6 +4122,32 @@ function Dock(props) {
|
|
|
4104
4122
|
speaking,
|
|
4105
4123
|
ownScroller
|
|
4106
4124
|
]);
|
|
4125
|
+
/**
|
|
4126
|
+
* Until when the page's own scroll is the CONCIERGE's, not the shopper's —
|
|
4127
|
+
* see {@link DockProps.conciergeScrollRef}. A timestamp rather than a
|
|
4128
|
+
* boolean so it lapses on its own: a `spotlight` whose smooth scroll never
|
|
4129
|
+
* arrives (the card was removed, the host cancelled it) must not deafen the
|
|
4130
|
+
* dock to the shopper for the rest of the session.
|
|
4131
|
+
*/
|
|
4132
|
+
const conciergeScrollUntilRef = useRef(0);
|
|
4133
|
+
/**
|
|
4134
|
+
* Publish the flag-raiser. Both halves of the exception are raised together
|
|
4135
|
+
* and by the SAME call — §5.5's duck guard (this component's own scroll
|
|
4136
|
+
* listener) and §5.3's recede (`cdn/recede.ts`, which keeps its own window)
|
|
4137
|
+
* — because a spotlight that ducked the sheet but not the row, or the other
|
|
4138
|
+
* way round, is half a bug rather than none.
|
|
4139
|
+
*/
|
|
4140
|
+
useEffect(() => {
|
|
4141
|
+
const ref = conciergeScrollRef;
|
|
4142
|
+
if (!ref) return;
|
|
4143
|
+
ref.current = (ms = CONCIERGE_SCROLL_WINDOW_MS) => {
|
|
4144
|
+
conciergeScrollUntilRef.current = ms > 0 ? Date.now() + ms : 0;
|
|
4145
|
+
recedeRef.current?.markProgrammatic(ms);
|
|
4146
|
+
};
|
|
4147
|
+
return () => {
|
|
4148
|
+
ref.current = null;
|
|
4149
|
+
};
|
|
4150
|
+
}, [conciergeScrollRef]);
|
|
4107
4151
|
const firstPage = useRef(true);
|
|
4108
4152
|
useEffect(() => {
|
|
4109
4153
|
if (firstPage.current) {
|
|
@@ -6096,14 +6140,319 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
|
|
|
6096
6140
|
exchangeCount: exchangeCount(speakers)
|
|
6097
6141
|
});
|
|
6098
6142
|
}
|
|
6099
|
-
|
|
6143
|
+
//#endregion
|
|
6144
|
+
//#region ../widget-bridge/dist/index.js
|
|
6145
|
+
/**
|
|
6146
|
+
* The subset of {@link VISITOR_EVENT_KIND_NAMES} that is BEHAVIOURAL tracking
|
|
6147
|
+
* — a record of what a shopper looked at or did while merely browsing — and
|
|
6148
|
+
* therefore requires consent before it ships. Single source of truth for
|
|
6149
|
+
* BOTH sides of the wire: `apps/api/src/widget/widget-chat.service.ts`'s
|
|
6150
|
+
* `CONSENT_REQUIRED_WIDGET_EVENT_KINDS` imports this directly (replacing a
|
|
6151
|
+
* hand-duplicated literal that had drifted from `packages/widget-bridge`'s
|
|
6152
|
+
* own client-side gate — the client was gating everything except
|
|
6153
|
+
* `checkout.handoff`, which silently dropped `session.started`/
|
|
6154
|
+
* `session.ended` forever since they were never queued in the first place),
|
|
6155
|
+
* and `packages/widget-bridge`'s `VisitorEventCollector` imports it too (via
|
|
6156
|
+
* the zod-free `/constants` subpath, same as every other constant here).
|
|
6157
|
+
*
|
|
6158
|
+
* `checkout.handoff` is deliberately EXCLUDED — it records a transaction the
|
|
6159
|
+
* shopper themselves just initiated, not a browsing observation (GDPR Art.
|
|
6160
|
+
* 6(1)(b) contract necessity), so it ships regardless of consent on both
|
|
6161
|
+
* sides. `session.started`/`session.ended`, `scroll.depth`, `exit.intent`
|
|
6162
|
+
* and `search.performed` are also excluded: a session's start/end and a
|
|
6163
|
+
* scroll/exit-intent signal carry no identifying browsing content on their
|
|
6164
|
+
* own, and a shopper's own search text is the one allowlisted content field
|
|
6165
|
+
* in the registry (`payloads.ts`) — none of the five is the kind of
|
|
6166
|
+
* behavioural profiling a consent banner is asking permission for. See
|
|
6167
|
+
* `widget-chat.service.ts`'s doc comment on `recordEvents` for the full
|
|
6168
|
+
* reasoning on the server side.
|
|
6169
|
+
*/
|
|
6170
|
+
var CONSENT_REQUIRED_VISITOR_EVENT_KINDS$1 = [
|
|
6100
6171
|
"page.viewed",
|
|
6101
6172
|
"product.viewed",
|
|
6102
6173
|
"collection.viewed",
|
|
6103
6174
|
"cart.viewed",
|
|
6104
6175
|
"cart.changed",
|
|
6105
6176
|
"product.hovered"
|
|
6106
|
-
]
|
|
6177
|
+
];
|
|
6178
|
+
/** How long the ring stays on screen. Long enough to be seen, short enough not to become furniture. */
|
|
6179
|
+
var SPOTLIGHT_RING_MS = 2e3;
|
|
6180
|
+
/**
|
|
6181
|
+
* Above every storefront's own stacking context, below the widget's dock.
|
|
6182
|
+
* `2147483647` is the maximum, and taking it outright would put a decorative
|
|
6183
|
+
* ring above a merchant's cookie banner and their own modals.
|
|
6184
|
+
*/
|
|
6185
|
+
var RING_Z_INDEX = 2147483e3;
|
|
6186
|
+
/** How far outside the card's own box the ring is drawn, so it reads as around the card rather than as a border on it. */
|
|
6187
|
+
var RING_INSET_PX = 4;
|
|
6188
|
+
/** The same defaults `page-tracker.ts` uses — one answer to "which element is a product card". */
|
|
6189
|
+
var DEFAULT_PRODUCT_CARD$1 = {
|
|
6190
|
+
selector: ".product-card, [data-product-id]",
|
|
6191
|
+
idFrom: "data-attr",
|
|
6192
|
+
idAttr: "data-product-id"
|
|
6193
|
+
};
|
|
6194
|
+
/**
|
|
6195
|
+
* CSS-escape a value that is about to be spliced into an attribute selector.
|
|
6196
|
+
*
|
|
6197
|
+
* These ids come from OUR server (a catalogue uuid, a parsed Shopify GID), not
|
|
6198
|
+
* from the page — but a selector built by concatenation is a selector
|
|
6199
|
+
* injection waiting for the day one of them contains a quote, and
|
|
6200
|
+
* `querySelector` throws on a malformed selector rather than returning null,
|
|
6201
|
+
* which would take a live call down over a highlight. `CSS.escape` where the
|
|
6202
|
+
* browser has it (every browser above this package's floor), a conservative
|
|
6203
|
+
* manual escape where it does not.
|
|
6204
|
+
*/
|
|
6205
|
+
function escapeAttrValue(win, value) {
|
|
6206
|
+
const css = win.CSS;
|
|
6207
|
+
if (typeof css?.escape === "function") return css.escape(value);
|
|
6208
|
+
return value.replace(/["\\]/g, "\\$&");
|
|
6209
|
+
}
|
|
6210
|
+
/**
|
|
6211
|
+
* Does `href` contain `needle` (`/products/<handle>`) as a whole path SEGMENT
|
|
6212
|
+
* — followed by the end of the string, a `/` (a collection-scoped url
|
|
6213
|
+
* continues past it), a `?` or a `#`?
|
|
6214
|
+
*
|
|
6215
|
+
* Plain string scanning rather than a constructed `RegExp`, and that is not a
|
|
6216
|
+
* style choice: a regex built by concatenation from a catalogue field is a
|
|
6217
|
+
* ReDoS surface a security scanner is right to refuse, and this needs no
|
|
6218
|
+
* backtracking at all. Every occurrence is checked, because a url may name the
|
|
6219
|
+
* handle twice (`/collections/rug/products/rug`).
|
|
6220
|
+
*/
|
|
6221
|
+
function endsHandleSegment(href, needle) {
|
|
6222
|
+
for (let at = href.indexOf(needle); at !== -1; at = href.indexOf(needle, at + 1)) {
|
|
6223
|
+
const after = href.charAt(at + needle.length);
|
|
6224
|
+
if (after === "" || after === "/" || after === "?" || after === "#") return true;
|
|
6225
|
+
}
|
|
6226
|
+
return false;
|
|
6227
|
+
}
|
|
6228
|
+
/**
|
|
6229
|
+
* Find the element for `target`, or `null`.
|
|
6230
|
+
*
|
|
6231
|
+
* The ladder, in order of how reliably a storefront actually carries each:
|
|
6232
|
+
*
|
|
6233
|
+
* 1. **The id attribute** the site profile names (`data-product-id` by
|
|
6234
|
+
* default) — tried with the PLATFORM id first, because that is what a
|
|
6235
|
+
* theme emits, then with our internal uuid, because a host that built its
|
|
6236
|
+
* grid from our catalogue would emit that one instead.
|
|
6237
|
+
* 2. **A PDP link** — `a[href*="/products/<handle>"]`, then the nearest
|
|
6238
|
+
* enclosing card. A link is what exists on a theme that carries no id
|
|
6239
|
+
* attribute at all, and the enclosing card is what the shopper sees as
|
|
6240
|
+
* "the product", so the ring goes round the card and not round the anchor.
|
|
6241
|
+
*
|
|
6242
|
+
* Never throws: a malformed profile selector, a document mid-teardown, an
|
|
6243
|
+
* element without `closest` — all answer `null`, and a highlight that did not
|
|
6244
|
+
* happen is reported honestly rather than crashing a merchant's page.
|
|
6245
|
+
*/
|
|
6246
|
+
function findProductCard(win, doc, target, profile) {
|
|
6247
|
+
const config = profile?.productCard ?? DEFAULT_PRODUCT_CARD$1;
|
|
6248
|
+
const idAttr = config.idAttr ?? DEFAULT_PRODUCT_CARD$1.idAttr ?? "data-product-id";
|
|
6249
|
+
try {
|
|
6250
|
+
for (const id of [target.platformProductId, target.productId]) {
|
|
6251
|
+
if (!id) continue;
|
|
6252
|
+
const byAttr = doc.querySelector(`[${idAttr}="${escapeAttrValue(win, id)}"]`);
|
|
6253
|
+
if (byAttr) return byAttr.closest(config.selector) ?? byAttr;
|
|
6254
|
+
}
|
|
6255
|
+
if (target.handle) {
|
|
6256
|
+
const escaped = escapeAttrValue(win, target.handle);
|
|
6257
|
+
const needle = `/products/${target.handle}`;
|
|
6258
|
+
for (const link of Array.from(doc.querySelectorAll(`a[href*="/products/${escaped}"]`))) {
|
|
6259
|
+
if (!endsHandleSegment(link.getAttribute("href") ?? "", needle)) continue;
|
|
6260
|
+
return link.closest(config.selector) ?? link;
|
|
6261
|
+
}
|
|
6262
|
+
}
|
|
6263
|
+
} catch {}
|
|
6264
|
+
return null;
|
|
6265
|
+
}
|
|
6266
|
+
/**
|
|
6267
|
+
* Scroll `target`'s card into view and ring it. `false` when the card is not
|
|
6268
|
+
* on this page — see the module doc comment on why that is ordinary.
|
|
6269
|
+
*
|
|
6270
|
+
* The scroll is `block: 'center'` so the card lands where a shopper looks, and
|
|
6271
|
+
* it is `behavior: 'smooth'` ONLY when the shopper has not asked for less
|
|
6272
|
+
* motion. `prefers-reduced-motion: reduce` gets an instant jump: the point of
|
|
6273
|
+
* the setting is that nothing slides, and this is the one scroll on the page
|
|
6274
|
+
* the shopper did not start themselves.
|
|
6275
|
+
*
|
|
6276
|
+
* The CALLER is responsible for telling the dock that this scroll was ours
|
|
6277
|
+
* (§5.3/§5.5 — otherwise the row recedes and the sheet ducks at the exact
|
|
6278
|
+
* moment the concierge acted). That flag lives in `@saar-ai/web-widget`'s
|
|
6279
|
+
* dock, which this package deliberately knows nothing about.
|
|
6280
|
+
*/
|
|
6281
|
+
function spotlightProductCard(win, doc, target, options = {}) {
|
|
6282
|
+
const card = findProductCard(win, doc, target, options.siteProfile);
|
|
6283
|
+
if (!card) return false;
|
|
6284
|
+
try {
|
|
6285
|
+
let smooth = true;
|
|
6286
|
+
try {
|
|
6287
|
+
smooth = win.matchMedia?.("(prefers-reduced-motion: reduce)").matches !== true;
|
|
6288
|
+
} catch {}
|
|
6289
|
+
card.scrollIntoView({
|
|
6290
|
+
block: "center",
|
|
6291
|
+
behavior: smooth ? "smooth" : "auto"
|
|
6292
|
+
});
|
|
6293
|
+
drawRing(win, doc, card, options.setTimeoutImpl ?? win.setTimeout.bind(win));
|
|
6294
|
+
} catch {}
|
|
6295
|
+
return true;
|
|
6296
|
+
}
|
|
6297
|
+
/**
|
|
6298
|
+
* One FIXED element over the card's box, re-placed on scroll, removed on a
|
|
6299
|
+
* timer.
|
|
6300
|
+
*
|
|
6301
|
+
* The double `box-shadow` is what makes this legible on a storefront whose
|
|
6302
|
+
* colours we do not know: a dark inner ring reads on a light theme, the light
|
|
6303
|
+
* outer one reads on a dark theme, and together they read on a photograph.
|
|
6304
|
+
* Static — no transition, no keyframes, nothing for §7.1 rule 1 to object to.
|
|
6305
|
+
*
|
|
6306
|
+
* The element sits at the viewport origin and is moved by `transform` alone,
|
|
6307
|
+
* so tracking the card through the smooth scroll costs a compositor property
|
|
6308
|
+
* per event and never a `top`/`left` write. The listener is PASSIVE and
|
|
6309
|
+
* capturing (a card inside the merchant's own scroll container emits its
|
|
6310
|
+
* scroll there, not on `window`), and it is removed with the ring — a stray
|
|
6311
|
+
* listener outliving a two-second decoration would be our bytes running on a
|
|
6312
|
+
* merchant's page for the rest of the session.
|
|
6313
|
+
*/
|
|
6314
|
+
function drawRing(win, doc, card, schedule) {
|
|
6315
|
+
const body = doc.body;
|
|
6316
|
+
if (!body) return;
|
|
6317
|
+
const ring = doc.createElement("div");
|
|
6318
|
+
ring.setAttribute("aria-hidden", "true");
|
|
6319
|
+
ring.setAttribute("data-concierge-spotlight", "");
|
|
6320
|
+
const px = (value) => `${Math.round(value)}px`;
|
|
6321
|
+
const place = () => {
|
|
6322
|
+
const rect = card.getBoundingClientRect();
|
|
6323
|
+
ring.style.width = px(rect.width + RING_INSET_PX * 2);
|
|
6324
|
+
ring.style.height = px(rect.height + RING_INSET_PX * 2);
|
|
6325
|
+
ring.style.transform = `translate(${px(rect.left - RING_INSET_PX)},${px(rect.top - RING_INSET_PX)})`;
|
|
6326
|
+
};
|
|
6327
|
+
ring.style.cssText = `position:fixed;top:0;left:0;border-radius:10px;pointer-events:none;z-index:${RING_Z_INDEX};box-shadow:0 0 0 2px rgba(17,17,17,.85),0 0 0 5px rgba(255,255,255,.9)`;
|
|
6328
|
+
place();
|
|
6329
|
+
body.appendChild(ring);
|
|
6330
|
+
const onMove = () => {
|
|
6331
|
+
try {
|
|
6332
|
+
place();
|
|
6333
|
+
} catch {}
|
|
6334
|
+
};
|
|
6335
|
+
const listen = (add) => {
|
|
6336
|
+
try {
|
|
6337
|
+
if (add) {
|
|
6338
|
+
win.addEventListener("scroll", onMove, {
|
|
6339
|
+
passive: true,
|
|
6340
|
+
capture: true
|
|
6341
|
+
});
|
|
6342
|
+
win.addEventListener("resize", onMove, { passive: true });
|
|
6343
|
+
} else {
|
|
6344
|
+
win.removeEventListener("scroll", onMove, { capture: true });
|
|
6345
|
+
win.removeEventListener("resize", onMove);
|
|
6346
|
+
}
|
|
6347
|
+
} catch {}
|
|
6348
|
+
};
|
|
6349
|
+
listen(true);
|
|
6350
|
+
schedule(() => {
|
|
6351
|
+
listen(false);
|
|
6352
|
+
try {
|
|
6353
|
+
ring.remove();
|
|
6354
|
+
} catch {}
|
|
6355
|
+
}, SPOTLIGHT_RING_MS);
|
|
6356
|
+
}
|
|
6357
|
+
/**
|
|
6358
|
+
* STOREFRONT PATHS — the two things every act event's destination has to be
|
|
6359
|
+
* rewritten for before a browser is sent to it.
|
|
6360
|
+
*
|
|
6361
|
+
* Both are facts about the SHOPPER'S storefront that the server cannot know,
|
|
6362
|
+
* which is why neither belongs in `apps/api`'s `act-destinations.ts`:
|
|
6363
|
+
*
|
|
6364
|
+
* 1. **The locale prefix.** Shopify Markets puts a locale/market code on the
|
|
6365
|
+
* front of every path — `/en-gb/collections/rugs`, `/fr-ca/cart`. The
|
|
6366
|
+
* catalogue holds handles, not markets, so a resolved path is always
|
|
6367
|
+
* spelt without one. Sending a shopper who is browsing `/en-gb/...` to a
|
|
6368
|
+
* bare `/collections/rugs` drops them out of their own market: a different
|
|
6369
|
+
* currency, a different language, and on some storefronts a redirect that
|
|
6370
|
+
* loses the path entirely. {@link storefrontLocalePrefix} reads the prefix
|
|
6371
|
+
* off the page they are actually on and {@link withStorefrontLocale} puts
|
|
6372
|
+
* it back.
|
|
6373
|
+
* 2. **The facet query.** A filter for a collection the shopper is NOT on
|
|
6374
|
+
* cannot go through `applyFilter` — that method narrows the CURRENT page
|
|
6375
|
+
* by construction — so the facets have to travel in the destination's own
|
|
6376
|
+
* query string instead. {@link withStorefrontFacets} builds it, and
|
|
6377
|
+
* `ShopifyBridge.applyFilter` uses the same function so the scheme exists
|
|
6378
|
+
* in one place.
|
|
6379
|
+
*
|
|
6380
|
+
* Pure string functions, no `window`, no DOM: everything here is testable
|
|
6381
|
+
* against a literal and is shared by the bridge and by `@saar-ai/web-widget`.
|
|
6382
|
+
*/
|
|
6383
|
+
/**
|
|
6384
|
+
* Shopify's own facet query-param scheme — `filter.<key>=<value>`, one param
|
|
6385
|
+
* per value (repeated for a multi-select facet).
|
|
6386
|
+
*
|
|
6387
|
+
* The KEY is the exact suffix after `filter.` in Shopify's URL scheme
|
|
6388
|
+
* (`v.option.color`, `p.vendor`, `p.product_type`), which is what the
|
|
6389
|
+
* `apply_filter` tool emits and what `ShopifyBridge.applyFilter` documents
|
|
6390
|
+
* itself as taking. Neither this module nor that method invents a mapping.
|
|
6391
|
+
*
|
|
6392
|
+
* Exported because `ShopifyBridge` READS the same params back for the page
|
|
6393
|
+
* context it hands the model (`pageContextExtras`) — one reader, one writer,
|
|
6394
|
+
* one spelling of the convention.
|
|
6395
|
+
*/
|
|
6396
|
+
var FILTER_PARAM_PREFIX = "filter.";
|
|
6397
|
+
/**
|
|
6398
|
+
* The leading locale/market segment of a storefront path, WITH its slash
|
|
6399
|
+
* (`/en-gb`), or `''` when there is none.
|
|
6400
|
+
*
|
|
6401
|
+
* `[a-z]{2}` language, optional `-[a-z]{2}` region — the same shape
|
|
6402
|
+
* `shopify-bridge.ts`'s own `LOCALE_PREFIX` matches, and deliberately no
|
|
6403
|
+
* wider: every storefront route this concierge can name (`/products`,
|
|
6404
|
+
* `/collections`, `/search`, `/cart`, `/pages`, `/policies`) is longer than
|
|
6405
|
+
* two characters, so a two-letter first segment on a storefront is a market
|
|
6406
|
+
* code and not a page.
|
|
6407
|
+
*/
|
|
6408
|
+
function storefrontLocalePrefix(path) {
|
|
6409
|
+
const match = /^\/([a-z]{2}(?:-[a-z]{2})?)(?=\/|$)/i.exec(path);
|
|
6410
|
+
return match ? `/${match[1]}` : "";
|
|
6411
|
+
}
|
|
6412
|
+
/**
|
|
6413
|
+
* Put `prefix` (from {@link storefrontLocalePrefix}) on the front of a
|
|
6414
|
+
* resolved path — unless that path already carries one of its own.
|
|
6415
|
+
*
|
|
6416
|
+
* The "already carries one" case is real rather than defensive: `navigate`'s
|
|
6417
|
+
* `target: 'url'` accepts a locale-prefixed storefront path, so a model
|
|
6418
|
+
* echoing the URL it was shown produces `/en-gb/collections/rugs` and
|
|
6419
|
+
* prefixing it again would produce `/en-gb/en-gb/...`.
|
|
6420
|
+
*/
|
|
6421
|
+
function withStorefrontLocale(prefix, path) {
|
|
6422
|
+
if (prefix === "" || storefrontLocalePrefix(path) !== "") return path;
|
|
6423
|
+
return `${prefix}${path}`;
|
|
6424
|
+
}
|
|
6425
|
+
/**
|
|
6426
|
+
* `path` with `filters` applied as Shopify's own facet query params, REPLACING
|
|
6427
|
+
* any `filter.*` params it already carried.
|
|
6428
|
+
*
|
|
6429
|
+
* Replacing rather than accumulating is the documented contract of
|
|
6430
|
+
* `apply_filter` ("applying a filter replaces the previous one rather than
|
|
6431
|
+
* adding to it") and of `ShopifyBridge.applyFilter`; anything else turns a
|
|
6432
|
+
* shopper's second thought into an intersection that matches nothing. Every
|
|
6433
|
+
* other query param on the path is kept: a collection url may legitimately
|
|
6434
|
+
* carry `?sort_by=`, and dropping it would undo a choice the shopper made.
|
|
6435
|
+
*
|
|
6436
|
+
* Never throws — a path this cannot parse comes back unchanged, which is a
|
|
6437
|
+
* destination without a filter rather than a navigation that did not happen.
|
|
6438
|
+
*/
|
|
6439
|
+
function withStorefrontFacets(path, filters) {
|
|
6440
|
+
try {
|
|
6441
|
+
const hash = path.indexOf("#");
|
|
6442
|
+
const withoutHash = hash === -1 ? path : path.slice(0, hash);
|
|
6443
|
+
const fragment = hash === -1 ? "" : path.slice(hash);
|
|
6444
|
+
const split = withoutHash.indexOf("?");
|
|
6445
|
+
const base = split === -1 ? withoutHash : withoutHash.slice(0, split);
|
|
6446
|
+
const params = new URLSearchParams(split === -1 ? "" : withoutHash.slice(split + 1));
|
|
6447
|
+
for (const key of Array.from(params.keys())) if (key.startsWith("filter.")) params.delete(key);
|
|
6448
|
+
for (const [key, values] of Object.entries(filters)) for (const value of values) params.append(`${FILTER_PARAM_PREFIX}${key}`, value);
|
|
6449
|
+
const query = params.toString();
|
|
6450
|
+
return `${base}${query ? `?${query}` : ""}${fragment}`;
|
|
6451
|
+
} catch {
|
|
6452
|
+
return path;
|
|
6453
|
+
}
|
|
6454
|
+
}
|
|
6455
|
+
new Set(CONSENT_REQUIRED_VISITOR_EVENT_KINDS$1);
|
|
6107
6456
|
/**
|
|
6108
6457
|
* Append `embedKey` as a query param, preserving whatever query string `url`
|
|
6109
6458
|
* already carries — a CORS preflight for `/widget/*` has neither the
|
|
@@ -6354,7 +6703,7 @@ var DEFAULT_PATTERNS = {
|
|
|
6354
6703
|
search: ["/search"],
|
|
6355
6704
|
cart: ["/cart"]
|
|
6356
6705
|
};
|
|
6357
|
-
var DEFAULT_SEARCH_QUERY_PARAMS
|
|
6706
|
+
var DEFAULT_SEARCH_QUERY_PARAMS = [
|
|
6358
6707
|
"q",
|
|
6359
6708
|
"s",
|
|
6360
6709
|
"search"
|
|
@@ -6382,7 +6731,7 @@ function detectFromUrlAndDom(doc, location, profile) {
|
|
|
6382
6731
|
cart: profile?.cart ?? DEFAULT_PATTERNS.cart
|
|
6383
6732
|
};
|
|
6384
6733
|
const path = location.pathname;
|
|
6385
|
-
const hasSearchQueryParam = DEFAULT_SEARCH_QUERY_PARAMS
|
|
6734
|
+
const hasSearchQueryParam = DEFAULT_SEARCH_QUERY_PARAMS.some((p) => new URLSearchParams(location.search).has(p));
|
|
6386
6735
|
if (matchesAny(path, patterns.cart)) return {
|
|
6387
6736
|
pageKind: "cart",
|
|
6388
6737
|
source: "heuristic"
|
|
@@ -6452,6 +6801,30 @@ var DESK_TYPING_INDICATOR_TTL_MS = 6e3;
|
|
|
6452
6801
|
//#endregion
|
|
6453
6802
|
//#region src/use-chat-session.ts
|
|
6454
6803
|
/**
|
|
6804
|
+
* The RUNTIME twin of `@saar-ai/widget-protocol`'s `SameOriginPathSchema`,
|
|
6805
|
+
* kept as a bare regex because that module is zod-backed and `ui` is a
|
|
6806
|
+
* `forbidZod` CDN artefact (`tools/check-config.json`).
|
|
6807
|
+
*
|
|
6808
|
+
* Two copies of one predicate is a drift risk and is worth naming: the SERVER
|
|
6809
|
+
* is the boundary, this is defence in depth, and `act.ts`'s own doc comment
|
|
6810
|
+
* carries the reasoning for every character of it. Kept byte-identical
|
|
6811
|
+
* deliberately — a looser copy would be worse than no copy, because it would
|
|
6812
|
+
* read as a check.
|
|
6813
|
+
*/
|
|
6814
|
+
var SAME_ORIGIN_PATH_RE = /^\/(?![/\\])[^\s\\]*$/;
|
|
6815
|
+
/**
|
|
6816
|
+
* Is `value` a root-relative, same-origin storefront path?
|
|
6817
|
+
*
|
|
6818
|
+
* Exported so `host-widget.tsx` re-checks at the POINT OF USE as well — the
|
|
6819
|
+
* two act events that carry a navigable field arrive on two different
|
|
6820
|
+
* transports (this hook's SSE stream, and `use-voice-session.ts`'s data
|
|
6821
|
+
* channel), and a check that lived only here would cover one of them. The
|
|
6822
|
+
* bytes are one regex either way.
|
|
6823
|
+
*/
|
|
6824
|
+
function isSameOriginPath(value) {
|
|
6825
|
+
return typeof value === "string" && SAME_ORIGIN_PATH_RE.test(value);
|
|
6826
|
+
}
|
|
6827
|
+
/**
|
|
6455
6828
|
* `''` = same-origin — every fetch/socket URL this hook builds is relative to
|
|
6456
6829
|
* whatever origin the browser loaded the widget from (docs/WIDGET_EMBED_PLAN.md
|
|
6457
6830
|
* §4 Phase 3, coupling (4)). `apps/web` overrides this to its own same-origin
|
|
@@ -6674,6 +7047,7 @@ function useChatSession(options) {
|
|
|
6674
7047
|
* field's doc comment on `UseChatSessionResult`.
|
|
6675
7048
|
*/
|
|
6676
7049
|
const [cartAdds, setCartAdds] = useState([]);
|
|
7050
|
+
const [actEvents, setActEvents] = useState([]);
|
|
6677
7051
|
/**
|
|
6678
7052
|
* The basket the caller last told us about — see
|
|
6679
7053
|
* {@link UseChatSessionResult.setCart}. A ref because nothing renders from
|
|
@@ -7509,6 +7883,9 @@ function useChatSession(options) {
|
|
|
7509
7883
|
onCartAddEvent: (evt) => {
|
|
7510
7884
|
if (mountedRef.current) setCartAdds((prev) => [...prev, evt]);
|
|
7511
7885
|
},
|
|
7886
|
+
onActEvent: (evt) => {
|
|
7887
|
+
if (mountedRef.current) setActEvents((prev) => [...prev, evt]);
|
|
7888
|
+
},
|
|
7512
7889
|
onEscalated: () => {
|
|
7513
7890
|
markHandoffToHuman();
|
|
7514
7891
|
},
|
|
@@ -7551,19 +7928,30 @@ function useChatSession(options) {
|
|
|
7551
7928
|
const setCart = useCallback((cart) => {
|
|
7552
7929
|
cartRef.current = cart;
|
|
7553
7930
|
}, []);
|
|
7554
|
-
/**
|
|
7555
|
-
|
|
7931
|
+
/**
|
|
7932
|
+
* The shape `pushCart` and `pushPageContext` share: a tokened POST of one
|
|
7933
|
+
* JSON body, with every failure reported as `false` and none of them ever
|
|
7934
|
+
* thrown at the shopper.
|
|
7935
|
+
*
|
|
7936
|
+
* Both are STATEMENTS INSIDE a conversation and never the thing that starts
|
|
7937
|
+
* one, so both refuse before there is a token — the same gate the
|
|
7938
|
+
* add-to-cart nudge applies. And both treat a 204 as a refusal rather than a
|
|
7939
|
+
* success: `POST /widget/context` answers one when the server's own consent
|
|
7940
|
+
* and tracking gates decline the push, and `Response.ok` is `true` for it.
|
|
7941
|
+
*/
|
|
7942
|
+
const postSessionState = useCallback(async (path, body) => {
|
|
7556
7943
|
const chatToken = chatTokenRef.current;
|
|
7557
7944
|
if (chatToken === void 0) return false;
|
|
7558
7945
|
try {
|
|
7559
|
-
|
|
7946
|
+
const res = await fetchImpl(withEmbedKeyParam(`${apiBase}${path}`, embedKey), {
|
|
7560
7947
|
method: "POST",
|
|
7561
7948
|
headers: {
|
|
7562
7949
|
"content-type": "application/json",
|
|
7563
7950
|
authorization: `Bearer ${chatToken}`
|
|
7564
7951
|
},
|
|
7565
|
-
body: JSON.stringify(
|
|
7566
|
-
})
|
|
7952
|
+
body: JSON.stringify(body)
|
|
7953
|
+
});
|
|
7954
|
+
return res.ok && res.status !== 204;
|
|
7567
7955
|
} catch {
|
|
7568
7956
|
return false;
|
|
7569
7957
|
}
|
|
@@ -7572,6 +7960,10 @@ function useChatSession(options) {
|
|
|
7572
7960
|
embedKey,
|
|
7573
7961
|
fetchImpl
|
|
7574
7962
|
]);
|
|
7963
|
+
/** See {@link UseChatSessionResult.pushCart}. */
|
|
7964
|
+
const pushCart = useCallback(async (cart) => postSessionState("/cart", { cart }), [postSessionState]);
|
|
7965
|
+
/** See {@link UseChatSessionResult.pushPageContext}. */
|
|
7966
|
+
const pushPageContext = useCallback(async (context) => postSessionState("/context", { context }), [postSessionState]);
|
|
7575
7967
|
const sendEvent = useCallback(async (events) => {
|
|
7576
7968
|
const chatToken = chatTokenRef.current;
|
|
7577
7969
|
if (chatToken === void 0 || events.length === 0) return false;
|
|
@@ -7901,8 +8293,10 @@ function useChatSession(options) {
|
|
|
7901
8293
|
cartAdds,
|
|
7902
8294
|
send,
|
|
7903
8295
|
sendReport,
|
|
8296
|
+
actEvents,
|
|
7904
8297
|
setCart,
|
|
7905
8298
|
pushCart,
|
|
8299
|
+
pushPageContext,
|
|
7906
8300
|
sendEvent,
|
|
7907
8301
|
notifyTyping,
|
|
7908
8302
|
checkout,
|
|
@@ -7916,7 +8310,7 @@ function useChatSession(options) {
|
|
|
7916
8310
|
* promise and is trivially unit-testable with a synthetic `ReadableStream`.
|
|
7917
8311
|
*/
|
|
7918
8312
|
async function streamReply(args) {
|
|
7919
|
-
const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onEscalated, onDone, onError, isMounted } = args;
|
|
8313
|
+
const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onActEvent, onEscalated, onDone, onError, isMounted } = args;
|
|
7920
8314
|
const reader = body.getReader();
|
|
7921
8315
|
const decoder = new TextDecoder();
|
|
7922
8316
|
const parser = new SseFrameParser();
|
|
@@ -8034,6 +8428,21 @@ async function streamReply(args) {
|
|
|
8034
8428
|
onCartAddEvent({ item });
|
|
8035
8429
|
break;
|
|
8036
8430
|
}
|
|
8431
|
+
case "navigate": {
|
|
8432
|
+
const data = evt.data;
|
|
8433
|
+
if (!isSameOriginPath(data?.url)) break;
|
|
8434
|
+
onActEvent(evt.data);
|
|
8435
|
+
break;
|
|
8436
|
+
}
|
|
8437
|
+
case "filter": {
|
|
8438
|
+
const data = evt.data;
|
|
8439
|
+
if (data?.collectionUrl !== void 0 && !isSameOriginPath(data.collectionUrl)) break;
|
|
8440
|
+
onActEvent(evt.data);
|
|
8441
|
+
break;
|
|
8442
|
+
}
|
|
8443
|
+
case "spotlight":
|
|
8444
|
+
onActEvent(evt.data);
|
|
8445
|
+
break;
|
|
8037
8446
|
case "escalated":
|
|
8038
8447
|
onEscalated();
|
|
8039
8448
|
break;
|
|
@@ -8059,7 +8468,7 @@ async function streamReply(args) {
|
|
|
8059
8468
|
* cache makes a second `start()` after `stop()` free).
|
|
8060
8469
|
*/
|
|
8061
8470
|
async function loadVoiceProtocol() {
|
|
8062
|
-
const [telemetry, chat] = await Promise.all([import("./telemetry-
|
|
8471
|
+
const [telemetry, chat] = await Promise.all([import("./telemetry-CBblNC6C.js"), import("./chat-e1afSRBr.js")]);
|
|
8063
8472
|
return {
|
|
8064
8473
|
decodeTelemetry: telemetry.decodeTelemetry,
|
|
8065
8474
|
encodeCallerText: telemetry.encodeCallerText,
|
|
@@ -8723,6 +9132,23 @@ function useVoiceSession(options = {}) {
|
|
|
8723
9132
|
reason
|
|
8724
9133
|
}), [publishControl]);
|
|
8725
9134
|
/**
|
|
9135
|
+
* §8.6's hint, sent DELIBERATELY rather than from `pagehide` — the
|
|
9136
|
+
* concierge's own `navigate` is about to move the page.
|
|
9137
|
+
*
|
|
9138
|
+
* `pagehide` already covers a shopper's click and a full-document
|
|
9139
|
+
* `location.assign`, and it still does. It does not cover the case this
|
|
9140
|
+
* exists for: a SOFT navigation (a `NextBridge` host, any bridge with a
|
|
9141
|
+
* router) fires no `pagehide` at all, so a concierge-driven move on a
|
|
9142
|
+
* headless storefront would look, at the transport layer, exactly like a
|
|
9143
|
+
* caller who said nothing for a while. Sending it explicitly means the
|
|
9144
|
+
* session gets its bounded hold either way — and on a hard navigation the
|
|
9145
|
+
* duplicate is free: the worker reads the hint as a flag, not a counter.
|
|
9146
|
+
*
|
|
9147
|
+
* Resolves `false` and sends nothing when there is no room, so a typed-only
|
|
9148
|
+
* panel calling this pays one function call.
|
|
9149
|
+
*/
|
|
9150
|
+
const notifyNavigating = useCallback(async () => publishControl({ type: "navigating" }), [publishControl]);
|
|
9151
|
+
/**
|
|
8726
9152
|
* §8.6 — `navigating`, sent from `pagehide` while a call is live.
|
|
8727
9153
|
*
|
|
8728
9154
|
* The caller's participant disconnects on EVERY click of a conventionally
|
|
@@ -8818,9 +9244,349 @@ function useVoiceSession(options = {}) {
|
|
|
8818
9244
|
sendText,
|
|
8819
9245
|
sendEouHint,
|
|
8820
9246
|
sendResume,
|
|
8821
|
-
interrupt
|
|
9247
|
+
interrupt,
|
|
9248
|
+
notifyNavigating
|
|
9249
|
+
};
|
|
9250
|
+
}
|
|
9251
|
+
//#endregion
|
|
9252
|
+
//#region ../widget-bridge/dist/page-context.js
|
|
9253
|
+
function clampId(value, max) {
|
|
9254
|
+
if (typeof value !== "string") return void 0;
|
|
9255
|
+
const trimmed = value.replace(/\s+/gu, " ").trim();
|
|
9256
|
+
if (trimmed === "") return void 0;
|
|
9257
|
+
return trimmed.slice(0, max);
|
|
9258
|
+
}
|
|
9259
|
+
/**
|
|
9260
|
+
* A pathname, or `undefined`.
|
|
9261
|
+
*
|
|
9262
|
+
* Deliberately NOT a URL parser. Every caller hands this `location.pathname`
|
|
9263
|
+
* (or an adapter's own classification of it), so the `new URL()` branch this
|
|
9264
|
+
* used to carry was defensive code for a caller that does not exist — and
|
|
9265
|
+
* this module is bundled into `ui.mjs`, which has a few hundred bytes of
|
|
9266
|
+
* headroom. What survives is the rule that actually matters: anything
|
|
9267
|
+
* carrying a `?`, a `#`, whitespace, or no leading `/` is REFUSED rather than
|
|
9268
|
+
* repaired, because a query string is where storefronts put session ids and
|
|
9269
|
+
* email addresses and this field must never carry one.
|
|
9270
|
+
*/
|
|
9271
|
+
function clampPath(value) {
|
|
9272
|
+
if (typeof value !== "string") return void 0;
|
|
9273
|
+
const path = value.trim();
|
|
9274
|
+
if (!path.startsWith("/") || /[?#\s]/u.test(path)) return void 0;
|
|
9275
|
+
return path.slice(0, 512);
|
|
9276
|
+
}
|
|
9277
|
+
function clampFilters(filters) {
|
|
9278
|
+
if (!filters) return void 0;
|
|
9279
|
+
const out = {};
|
|
9280
|
+
for (const [rawKey, rawValue] of Object.entries(filters)) {
|
|
9281
|
+
if (Object.keys(out).length >= 8) break;
|
|
9282
|
+
const key = clampId(rawKey, 64);
|
|
9283
|
+
const value = clampId(rawValue, 64);
|
|
9284
|
+
if (key === void 0 || value === void 0) continue;
|
|
9285
|
+
out[key] = value;
|
|
9286
|
+
}
|
|
9287
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
9288
|
+
}
|
|
9289
|
+
function byteLength(context) {
|
|
9290
|
+
return new TextEncoder().encode(JSON.stringify(context)).byteLength;
|
|
9291
|
+
}
|
|
9292
|
+
/**
|
|
9293
|
+
* Build a bounded, wire-legal `PageContext`, or `undefined` when there is not
|
|
9294
|
+
* even a path to report.
|
|
9295
|
+
*
|
|
9296
|
+
* ## Degrade, never fabricate — and never drop the whole thing
|
|
9297
|
+
*
|
|
9298
|
+
* Every optional field is omitted rather than defaulted: no `cartCount: 0` for
|
|
9299
|
+
* a host that does not report one (zero is a real answer, "the cart is
|
|
9300
|
+
* empty"), no handle substituted for a missing id. `pageType` and `path` are
|
|
9301
|
+
* the only things this needs, and a page that cannot supply a path supplies no
|
|
9302
|
+
* context at all.
|
|
9303
|
+
*
|
|
9304
|
+
* ## Trimming to the byte ceiling
|
|
9305
|
+
*
|
|
9306
|
+
* `PAGE_CONTEXT_MAX_BYTES` is a hard ceiling on both wires, and a payload over
|
|
9307
|
+
* it is dropped WHOLE by the decoder on the other side. Rather than let a
|
|
9308
|
+
* merchant with very long handles lose their context entirely, this trims in
|
|
9309
|
+
* increasing order of usefulness to the model: the facets go first, then the
|
|
9310
|
+
* search text and the ids together. The page type and the path always
|
|
9311
|
+
* survive, and they are together far below the ceiling by construction.
|
|
9312
|
+
*
|
|
9313
|
+
* @param draft the raw values, from whichever `HostBridge` resolved them
|
|
9314
|
+
*/
|
|
9315
|
+
/**
|
|
9316
|
+
* The locale shape `PageContextSchema` accepts, mirrored here rather than
|
|
9317
|
+
* imported.
|
|
9318
|
+
*
|
|
9319
|
+
* This package deliberately does not depend on `@saar-ai/widget-protocol` —
|
|
9320
|
+
* zod would land in `core.mjs` — so the contract is written down on both
|
|
9321
|
+
* sides with a pointer between them, the same way the bridge's other
|
|
9322
|
+
* cross-package literals are. `page-context-contract.test.ts` in
|
|
9323
|
+
* `@saar-ai/web-widget` pins the two together.
|
|
9324
|
+
*
|
|
9325
|
+
* It is applied as a DROP rather than a repair, and that is the whole point.
|
|
9326
|
+
* `<html lang>` is whatever the merchant's theme wrote, and themes write
|
|
9327
|
+
* `EN`, `en_US` and `en-us` as readily as `en-US`. Passing one of those
|
|
9328
|
+
* through is not a cosmetic problem: the wire schema is strict, so the server
|
|
9329
|
+
* refuses the entire body with a 400 and the shopper loses their page context
|
|
9330
|
+
* because of one optional field. Dropping it costs a locale the model barely
|
|
9331
|
+
* uses and keeps the page. A platform adapter that knows the real locale
|
|
9332
|
+
* supplies it through `pageContextExtras()` and is unaffected — Shopify's
|
|
9333
|
+
* does, from `Shopify.locale`.
|
|
9334
|
+
*
|
|
9335
|
+
* Normalising the case instead was measured at ~115 bytes of `ui.mjs` against
|
|
9336
|
+
* 77 bytes of headroom, and buys only the generic fallback path on badly
|
|
9337
|
+
* written themes. Not worth the budget; revisit if `ui` ever has room.
|
|
9338
|
+
*/
|
|
9339
|
+
var WIRE_LOCALE_PATTERN = /^[a-z]{2,3}(-[A-Za-z]{2,4})?(-[A-Z]{2}|-\d{3})?$/u;
|
|
9340
|
+
function buildPageContext(draft) {
|
|
9341
|
+
const path = clampPath(draft.path);
|
|
9342
|
+
if (path === void 0) return void 0;
|
|
9343
|
+
const capturedAt = new Date(draft.capturedAt ?? Date.now()).toISOString();
|
|
9344
|
+
const cartCount = typeof draft.cartCount === "number" && Number.isFinite(draft.cartCount) && draft.cartCount >= 0 ? Math.min(9999, Math.floor(draft.cartCount)) : void 0;
|
|
9345
|
+
let filters = clampFilters(draft.filters);
|
|
9346
|
+
let searchQuery = clampId(draft.searchQuery, 128);
|
|
9347
|
+
let productId = clampId(draft.productId, 128);
|
|
9348
|
+
let variantId = clampId(draft.variantId, 128);
|
|
9349
|
+
let collectionHandle = clampId(draft.collectionHandle, 128);
|
|
9350
|
+
const clampedLocale = clampId(draft.locale, 35);
|
|
9351
|
+
const locale = clampedLocale !== void 0 && WIRE_LOCALE_PATTERN.test(clampedLocale) ? clampedLocale : void 0;
|
|
9352
|
+
const assemble = () => ({
|
|
9353
|
+
pageType: draft.pageType,
|
|
9354
|
+
path,
|
|
9355
|
+
...productId !== void 0 ? { productId } : {},
|
|
9356
|
+
...variantId !== void 0 ? { variantId } : {},
|
|
9357
|
+
...collectionHandle !== void 0 ? { collectionHandle } : {},
|
|
9358
|
+
...filters !== void 0 ? { filters } : {},
|
|
9359
|
+
...searchQuery !== void 0 ? { searchQuery } : {},
|
|
9360
|
+
...cartCount !== void 0 ? { cartCount } : {},
|
|
9361
|
+
...locale !== void 0 ? { locale } : {},
|
|
9362
|
+
capturedAt
|
|
9363
|
+
});
|
|
9364
|
+
let context = assemble();
|
|
9365
|
+
if (byteLength(context) > 2048) {
|
|
9366
|
+
filters = void 0;
|
|
9367
|
+
context = assemble();
|
|
9368
|
+
}
|
|
9369
|
+
if (byteLength(context) > 2048) {
|
|
9370
|
+
searchQuery = void 0;
|
|
9371
|
+
productId = void 0;
|
|
9372
|
+
variantId = void 0;
|
|
9373
|
+
collectionHandle = void 0;
|
|
9374
|
+
context = assemble();
|
|
9375
|
+
}
|
|
9376
|
+
return context;
|
|
9377
|
+
}
|
|
9378
|
+
/**
|
|
9379
|
+
* Are these two contexts the same PLACE?
|
|
9380
|
+
*
|
|
9381
|
+
* `capturedAt` is excluded deliberately — it moves on every capture and is
|
|
9382
|
+
* descriptive, never the thing that makes a context new. Used by
|
|
9383
|
+
* `PageContextTracker` to avoid re-pushing an identical context when a host's
|
|
9384
|
+
* router fires `onPageChange` twice for one navigation, which several
|
|
9385
|
+
* storefront themes do.
|
|
9386
|
+
*
|
|
9387
|
+
* Compares the JSON up to `capturedAt`, which {@link buildPageContext} always
|
|
9388
|
+
* emits LAST — cheaper than rebuilding both objects without it, on a module
|
|
9389
|
+
* that ships inside a budgeted bundle. A hand-written field-by-field compare
|
|
9390
|
+
* would be cheaper still and is exactly the thing that silently stops
|
|
9391
|
+
* comparing a field somebody adds later.
|
|
9392
|
+
*
|
|
9393
|
+
* @param a one context, or nothing
|
|
9394
|
+
* @param b the other, or nothing
|
|
9395
|
+
*/
|
|
9396
|
+
function samePageContext(a, b) {
|
|
9397
|
+
if (a === void 0 || b === void 0) return a === b;
|
|
9398
|
+
return place(a) === place(b);
|
|
9399
|
+
}
|
|
9400
|
+
function place(context) {
|
|
9401
|
+
const json = JSON.stringify(context);
|
|
9402
|
+
return json.slice(0, json.lastIndexOf("\"capturedAt\""));
|
|
9403
|
+
}
|
|
9404
|
+
/**
|
|
9405
|
+
* The query-string parameter names a storefront's search box puts its text
|
|
9406
|
+
* in, in the order they are tried.
|
|
9407
|
+
*
|
|
9408
|
+
* ONE list, read by both callers: `PageTracker` builds `search.performed`
|
|
9409
|
+
* from it and `GenericBridge.pageContextExtras` builds the page context's
|
|
9410
|
+
* `searchQuery` from it. A second spelling would let the visitor timeline and
|
|
9411
|
+
* the model's prompt disagree about what the shopper searched for — and, on a
|
|
9412
|
+
* bundle with a few hundred bytes of headroom, a second copy of the loop is
|
|
9413
|
+
* not free either.
|
|
9414
|
+
*/
|
|
9415
|
+
var SEARCH_QUERY_PARAMS = [
|
|
9416
|
+
"q",
|
|
9417
|
+
"s",
|
|
9418
|
+
"search"
|
|
9419
|
+
];
|
|
9420
|
+
/**
|
|
9421
|
+
* The shopper's own search text out of a query string, or `undefined`.
|
|
9422
|
+
*
|
|
9423
|
+
* @param search `location.search`, with or without its leading `?`
|
|
9424
|
+
*/
|
|
9425
|
+
function readSearchQueryParam(search) {
|
|
9426
|
+
try {
|
|
9427
|
+
const params = new URLSearchParams(search);
|
|
9428
|
+
for (const name of SEARCH_QUERY_PARAMS) {
|
|
9429
|
+
const value = params.get(name);
|
|
9430
|
+
if (value && value.trim()) return value.trim();
|
|
9431
|
+
}
|
|
9432
|
+
return;
|
|
9433
|
+
} catch {
|
|
9434
|
+
return;
|
|
9435
|
+
}
|
|
9436
|
+
}
|
|
9437
|
+
/** The real `location.search` and `<html lang>`, or nothing outside a browser. */
|
|
9438
|
+
function browserPageContextGlobals() {
|
|
9439
|
+
if (typeof window === "undefined") return {};
|
|
9440
|
+
return {
|
|
9441
|
+
search: window.location?.search ?? "",
|
|
9442
|
+
...typeof document !== "undefined" && typeof document.documentElement?.lang === "string" ? { documentLang: document.documentElement.lang } : {}
|
|
8822
9443
|
};
|
|
8823
9444
|
}
|
|
9445
|
+
/**
|
|
9446
|
+
* `HostPageKind` → `PageContextType`.
|
|
9447
|
+
*
|
|
9448
|
+
* The one mapping that is not the identity is `'other'` at the site root,
|
|
9449
|
+
* which becomes `'home'`. The bridge's kind list never needed a name for the
|
|
9450
|
+
* front page because a home page is a `page.viewed` like any other; the model
|
|
9451
|
+
* does need one, because "they are on the front page" and "they are on some
|
|
9452
|
+
* page we could not classify" call for different opening sentences.
|
|
9453
|
+
*
|
|
9454
|
+
* @param kind the classified page kind
|
|
9455
|
+
* @param path the page's pathname
|
|
9456
|
+
*/
|
|
9457
|
+
function pageContextTypeFor(kind, path) {
|
|
9458
|
+
if (kind === "other") return /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/?)?$/iu.test(path) ? "home" : "other";
|
|
9459
|
+
return kind;
|
|
9460
|
+
}
|
|
9461
|
+
/**
|
|
9462
|
+
* Where the shopper is standing, as `PageContextSchema` wants it — or `null`
|
|
9463
|
+
* when there is no usable page to describe.
|
|
9464
|
+
*
|
|
9465
|
+
* Never throws: an adapter that explodes costs the concierge a grounded
|
|
9466
|
+
* phrase, never the merchant's page. Everything is CLAMPED rather than
|
|
9467
|
+
* rejected (`buildPageContext`), so a storefront with unusually long handles
|
|
9468
|
+
* loses a facet rather than its whole context.
|
|
9469
|
+
*
|
|
9470
|
+
* @param bridge the host adapter to ask
|
|
9471
|
+
*/
|
|
9472
|
+
function currentPageContext(bridge, globals) {
|
|
9473
|
+
try {
|
|
9474
|
+
const page = bridge.currentPage();
|
|
9475
|
+
const { search, documentLang } = globals ?? browserPageContextGlobals();
|
|
9476
|
+
const extras = bridge.pageContextExtras?.() ?? {};
|
|
9477
|
+
return buildPageContext({
|
|
9478
|
+
pageType: pageContextTypeFor(page.kind, page.path),
|
|
9479
|
+
path: page.path,
|
|
9480
|
+
searchQuery: readSearchQueryParam(search ?? ""),
|
|
9481
|
+
locale: documentLang,
|
|
9482
|
+
...page.kind === "product" ? { productId: page.entityId } : {},
|
|
9483
|
+
...page.kind === "collection" ? { collectionHandle: page.handle ?? page.entityId } : {},
|
|
9484
|
+
...extras
|
|
9485
|
+
}) ?? null;
|
|
9486
|
+
} catch {
|
|
9487
|
+
return null;
|
|
9488
|
+
}
|
|
9489
|
+
}
|
|
9490
|
+
/**
|
|
9491
|
+
* The default timer, declared here rather than imported from `coalescer.ts`.
|
|
9492
|
+
*
|
|
9493
|
+
* `realTimer` there is identical, and importing it would be the obvious
|
|
9494
|
+
* thing — but `coalescer.ts` also holds `ScrollDepthCoalescer`,
|
|
9495
|
+
* `ProductHoverTracker` and `PageViewDeduper`, none of which this module
|
|
9496
|
+
* uses, and this module is bundled into `ui.mjs` (which carries none of them
|
|
9497
|
+
* either) through the `@saar-ai/widget-bridge/page-context` entry. Two lines
|
|
9498
|
+
* of duplication against several hundred bytes on an artefact with under a
|
|
9499
|
+
* kilobyte of headroom. The TYPE is still imported, so the two cannot drift.
|
|
9500
|
+
*/
|
|
9501
|
+
var defaultTimer = {
|
|
9502
|
+
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
|
|
9503
|
+
clearTimeout: (handle) => globalThis.clearTimeout(handle)
|
|
9504
|
+
};
|
|
9505
|
+
/** The visitor-event kind whose gates this tracker borrows. See the class doc comment. */
|
|
9506
|
+
var GATED_AS = "page.viewed";
|
|
9507
|
+
var PageContextTracker = class {
|
|
9508
|
+
bridge;
|
|
9509
|
+
consent;
|
|
9510
|
+
trackingEnabled;
|
|
9511
|
+
send;
|
|
9512
|
+
timer;
|
|
9513
|
+
debounceMs;
|
|
9514
|
+
started = false;
|
|
9515
|
+
destroyed = false;
|
|
9516
|
+
unsubscribePageChange;
|
|
9517
|
+
pending;
|
|
9518
|
+
/** The last context that actually went out — see {@link samePageContext}. */
|
|
9519
|
+
lastSent;
|
|
9520
|
+
pageChangeListener = () => {
|
|
9521
|
+
try {
|
|
9522
|
+
this.schedule();
|
|
9523
|
+
} catch {}
|
|
9524
|
+
};
|
|
9525
|
+
constructor(options) {
|
|
9526
|
+
this.bridge = options.bridge;
|
|
9527
|
+
this.consent = options.consent;
|
|
9528
|
+
this.trackingEnabled = options.trackingEnabled ?? (() => true);
|
|
9529
|
+
this.send = options.send;
|
|
9530
|
+
this.timer = options.timer ?? defaultTimer;
|
|
9531
|
+
this.debounceMs = options.debounceMs ?? 250;
|
|
9532
|
+
}
|
|
9533
|
+
/**
|
|
9534
|
+
* Boot the tracker: capture the page the shopper opened on, then follow
|
|
9535
|
+
* every navigation.
|
|
9536
|
+
*
|
|
9537
|
+
* The FIRST capture is not debounced — it is the context the model needs
|
|
9538
|
+
* before the first turn, and a quarter-second of deliberate lateness on a
|
|
9539
|
+
* page that has only just loaded buys nothing. Every later capture is.
|
|
9540
|
+
*
|
|
9541
|
+
* Calling twice is a no-op. Never throws.
|
|
9542
|
+
*/
|
|
9543
|
+
start() {
|
|
9544
|
+
try {
|
|
9545
|
+
if (this.started || this.destroyed) return;
|
|
9546
|
+
this.started = true;
|
|
9547
|
+
this.capture();
|
|
9548
|
+
this.unsubscribePageChange = this.bridge.onPageChange(this.pageChangeListener);
|
|
9549
|
+
} catch {}
|
|
9550
|
+
}
|
|
9551
|
+
destroy() {
|
|
9552
|
+
try {
|
|
9553
|
+
this.destroyed = true;
|
|
9554
|
+
this.unsubscribePageChange?.();
|
|
9555
|
+
if (this.pending !== void 0) this.timer.clearTimeout(this.pending);
|
|
9556
|
+
this.pending = void 0;
|
|
9557
|
+
} catch {}
|
|
9558
|
+
}
|
|
9559
|
+
/** `true` when both gates allow a push right now. Exposed for the caller's own diagnostics. */
|
|
9560
|
+
mayPush() {
|
|
9561
|
+
return this.consent.mayTrack(GATED_AS) && this.trackingEnabled();
|
|
9562
|
+
}
|
|
9563
|
+
schedule() {
|
|
9564
|
+
if (this.destroyed) return;
|
|
9565
|
+
if (this.pending !== void 0) this.timer.clearTimeout(this.pending);
|
|
9566
|
+
this.pending = this.timer.setTimeout(() => {
|
|
9567
|
+
this.pending = void 0;
|
|
9568
|
+
this.capture();
|
|
9569
|
+
}, this.debounceMs);
|
|
9570
|
+
}
|
|
9571
|
+
/**
|
|
9572
|
+
* The whole decision, in order: gates first, then the bridge.
|
|
9573
|
+
*
|
|
9574
|
+
* Gates BEFORE `currentPageContext()` is deliberate. Reading the page is
|
|
9575
|
+
* cheap but not free (a `querySelectorAll` on some adapters), and more to
|
|
9576
|
+
* the point a visitor who denied consent should have nothing about their
|
|
9577
|
+
* page read at all — not read, then discarded.
|
|
9578
|
+
*/
|
|
9579
|
+
capture() {
|
|
9580
|
+
try {
|
|
9581
|
+
if (this.destroyed || !this.mayPush()) return;
|
|
9582
|
+
const context = currentPageContext(this.bridge) ?? void 0;
|
|
9583
|
+
if (context === void 0 || samePageContext(context, this.lastSent)) return;
|
|
9584
|
+
this.lastSent = context;
|
|
9585
|
+
const result = this.send(context);
|
|
9586
|
+
if (typeof result?.catch === "function") result.catch(() => {});
|
|
9587
|
+
} catch {}
|
|
9588
|
+
}
|
|
9589
|
+
};
|
|
8824
9590
|
//#endregion
|
|
8825
9591
|
//#region src/turn-order.ts
|
|
8826
9592
|
/**
|
|
@@ -8935,6 +9701,51 @@ var TurnOrderClock = class {
|
|
|
8935
9701
|
//#endregion
|
|
8936
9702
|
//#region src/host-widget.tsx
|
|
8937
9703
|
/**
|
|
9704
|
+
* DOCK_SPEC §6 — how long the TYPED leg waits before performing a
|
|
9705
|
+
* concierge-driven `navigate` or `filter`.
|
|
9706
|
+
*
|
|
9707
|
+
* "Agent-initiated navigation is scheduled, not immediate. Finish the clause,
|
|
9708
|
+
* then navigate." On a call the realtime tier does the scheduling
|
|
9709
|
+
* (`apps/voice/src/session/scheduled-widget-events.ts` holds the event until
|
|
9710
|
+
* the utterance ends), so by the time the event reaches this widget the
|
|
9711
|
+
* concierge has stopped speaking. A typed reply has no utterance to finish and
|
|
9712
|
+
* the event arrives mid-stream — the shopper would read half a sentence and
|
|
9713
|
+
* watch the page take the rest of it away. One beat is what lets the sentence
|
|
9714
|
+
* land, and it is short on purpose: a navigation the shopper asked for should
|
|
9715
|
+
* feel like a click, not like a wait.
|
|
9716
|
+
*/
|
|
9717
|
+
var NAVIGATE_BEAT_MS = 300;
|
|
9718
|
+
/**
|
|
9719
|
+
* Is this widget event one the concierge wants PERFORMED on the host page?
|
|
9720
|
+
*
|
|
9721
|
+
* Hand-written rather than imported from `@saar-ai/widget-protocol`'s
|
|
9722
|
+
* `ACT_EVENT_TYPES`, and that is a build constraint rather than a preference:
|
|
9723
|
+
* that module is zod-backed, and `ui` is a `forbidZod` CDN artefact
|
|
9724
|
+
* (`tools/check-config.json`) — a VALUE import from it would pull zod into an
|
|
9725
|
+
* artefact a shopper downloads the moment they open the concierge. The type
|
|
9726
|
+
* still comes from there, so a fourth act event is a compile error here rather
|
|
9727
|
+
* than a silent no-op.
|
|
9728
|
+
*/
|
|
9729
|
+
function isActEvent(event) {
|
|
9730
|
+
return event.type === "navigate" || event.type === "filter" || event.type === "spotlight";
|
|
9731
|
+
}
|
|
9732
|
+
/**
|
|
9733
|
+
* Do two storefront paths name the same PAGE — ignoring the query, the
|
|
9734
|
+
* fragment and a trailing slash?
|
|
9735
|
+
*
|
|
9736
|
+
* It decides one thing: whether a `filter`'s `collectionUrl` is the page the
|
|
9737
|
+
* shopper is already on (narrow it in place) or a different one (walk them
|
|
9738
|
+
* there with the facets in the url). Deliberately a string comparison rather
|
|
9739
|
+
* than a `URL` parse: both sides are root-relative by construction — the
|
|
9740
|
+
* server's schema and `isSameOriginPath` have both refused anything else — so
|
|
9741
|
+
* there is no origin to resolve against and nothing a parser would add except
|
|
9742
|
+
* a second place for the two to disagree.
|
|
9743
|
+
*/
|
|
9744
|
+
function isSamePagePath(a, b) {
|
|
9745
|
+
const bare = (value) => (value.split("#")[0] ?? "").split("?")[0]?.replace(/\/+$/, "") ?? "";
|
|
9746
|
+
return bare(a) === bare(b);
|
|
9747
|
+
}
|
|
9748
|
+
/**
|
|
8938
9749
|
* Resolves the widget's "add to cart" handler from the bridge's OWN degraded
|
|
8939
9750
|
* path — docs/WIDGET_EMBED_PLAN.md §3, rule 1 ("every optional method is
|
|
8940
9751
|
* genuinely optional... the widget has a working degraded path for each —
|
|
@@ -9240,7 +10051,7 @@ function deriveCallPhase(voice) {
|
|
|
9240
10051
|
* about offering voice here costs a byte until a caller actually presses
|
|
9241
10052
|
* the microphone.
|
|
9242
10053
|
*/
|
|
9243
|
-
function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady }) {
|
|
10054
|
+
function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, siteProfile, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady }) {
|
|
9244
10055
|
/**
|
|
9245
10056
|
* Maps the tenant's semantic config fields onto the widget's historical
|
|
9246
10057
|
* CSS custom properties — this is the "one becomes the other" site
|
|
@@ -9299,6 +10110,66 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9299
10110
|
*/
|
|
9300
10111
|
const escalated = session.status === "escalated";
|
|
9301
10112
|
/**
|
|
10113
|
+
* Page context — where the shopper is standing, pushed to both legs
|
|
10114
|
+
* (ADR 0014).
|
|
10115
|
+
*
|
|
10116
|
+
* ## Why it is wired HERE and not in `core.ts`
|
|
10117
|
+
*
|
|
10118
|
+
* `core.ts` is where `PageTracker` starts, and this tracker's sibling
|
|
10119
|
+
* naturally belongs beside it — the ENTRY page is the one that says which
|
|
10120
|
+
* campaign or product brought the shopper, and by the time this component
|
|
10121
|
+
* mounts they may have navigated twice. It is here anyway, for one reason
|
|
10122
|
+
* that is not a preference: `core.mjs` has a hard min+gz budget
|
|
10123
|
+
* (`tools/check-config.json`, `bundle-budget.artefacts.core`) with under
|
|
10124
|
+
* 250 bytes of headroom at the time of writing, and a tracker plus a POST
|
|
10125
|
+
* does not fit in it. `ui.mjs` has room and is where the chat token already
|
|
10126
|
+
* lives.
|
|
10127
|
+
*
|
|
10128
|
+
* What that costs, stated plainly rather than hidden: no page context
|
|
10129
|
+
* exists until the shopper OPENS the concierge, because `ui.mjs` is not
|
|
10130
|
+
* requested until intent (§4.1). A context still arrives before the first
|
|
10131
|
+
* TURN, which is what the feature needs — the concierge grounds its first
|
|
10132
|
+
* reply — but a proactive opener cannot be grounded on the page, and a
|
|
10133
|
+
* visitor who never opens the widget pushes nothing at all. Moving this to
|
|
10134
|
+
* `core` is the follow-up, and it is gated on the theme derivation coming
|
|
10135
|
+
* out of `core` (option 2 of `packages/web-widget/AGENTS.md`'s "Measured
|
|
10136
|
+
* sizes" table), which returns eight times what this would spend.
|
|
10137
|
+
*
|
|
10138
|
+
* ## ONE push, and both legs read what it stored
|
|
10139
|
+
*
|
|
10140
|
+
* The tracker decides WHETHER; this decides WHERE, and the answer is the
|
|
10141
|
+
* one gated endpoint. `POST /widget/context` re-checks the visitor's
|
|
10142
|
+
* consent and the tenant's tracking toggle server-side and stores the
|
|
10143
|
+
* context against the session; the typed leg renders it from there, and the
|
|
10144
|
+
* turn tier reads the SAME key per turn (`PageContextStore`, `apps/agent`).
|
|
10145
|
+
*
|
|
10146
|
+
* There is deliberately no second push down the call's data channel. A
|
|
10147
|
+
* frame like that reaches a model without passing any server gate, so a
|
|
10148
|
+
* merchant who switched behavioural tracking off would still have their
|
|
10149
|
+
* shoppers' browsing narrated into a prompt on every call — and no check
|
|
10150
|
+
* running in the merchant's own page could prevent it. One gated write, two
|
|
10151
|
+
* readers. See ADR 0014.
|
|
10152
|
+
*/
|
|
10153
|
+
const pushPageContext = session.pushPageContext;
|
|
10154
|
+
const sendPageContextRef = useRef(() => {});
|
|
10155
|
+
sendPageContextRef.current = (context) => {
|
|
10156
|
+
pushPageContext(context);
|
|
10157
|
+
};
|
|
10158
|
+
useEffect(() => {
|
|
10159
|
+
if (!bridge || !collector || chatToken === void 0) return;
|
|
10160
|
+
const tracker = new PageContextTracker({
|
|
10161
|
+
bridge,
|
|
10162
|
+
consent: collector,
|
|
10163
|
+
send: (context) => sendPageContextRef.current(context)
|
|
10164
|
+
});
|
|
10165
|
+
tracker.start();
|
|
10166
|
+
return () => tracker.destroy();
|
|
10167
|
+
}, [
|
|
10168
|
+
bridge,
|
|
10169
|
+
collector,
|
|
10170
|
+
chatToken
|
|
10171
|
+
]);
|
|
10172
|
+
/**
|
|
9302
10173
|
* The basket this widget built from its OWN adds — see `AddedCartLine`.
|
|
9303
10174
|
* Always accumulated, even when the host has a `readCart` that reports
|
|
9304
10175
|
* lines: the host read is asynchronous and can fail, and this is what the
|
|
@@ -9635,6 +10506,264 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9635
10506
|
* `/cart/add.js`, and a storefront cart is one resource — two concurrent
|
|
9636
10507
|
* posts against it is exactly the shape that loses one of them.
|
|
9637
10508
|
*/
|
|
10509
|
+
/**
|
|
10510
|
+
* §5.3/§5.5's concierge-scroll flag, as a function the DOCK publishes.
|
|
10511
|
+
*
|
|
10512
|
+
* Called immediately BEFORE a spotlight scroll and synchronously, which is
|
|
10513
|
+
* the whole point of it being a callback rather than the state nonce it
|
|
10514
|
+
* started as: the dock's scroll listener is a capture listener on
|
|
10515
|
+
* `document`, so the first `scroll` event of a smooth scroll can arrive in
|
|
10516
|
+
* the same task — before React has re-rendered — and a flag raised by a
|
|
10517
|
+
* `setState` would be raised one event too late. The row receding and the
|
|
10518
|
+
* sheet ducking at the exact moment the concierge pointed at something is
|
|
10519
|
+
* precisely the failure §5.3's exception exists to prevent.
|
|
10520
|
+
*
|
|
10521
|
+
* `null` until the dock mounts (a harness with no dock at all), and calling
|
|
10522
|
+
* it with `0` DISARMS — see `performAct`'s spotlight branch.
|
|
10523
|
+
*/
|
|
10524
|
+
const conciergeScrollRef = useRef(null);
|
|
10525
|
+
/**
|
|
10526
|
+
* The facts an act reads at the moment it RUNS, rather than at the moment
|
|
10527
|
+
* its callback was built.
|
|
10528
|
+
*
|
|
10529
|
+
* An act is asynchronous by construction — `navigate` waits a beat, a bridge
|
|
10530
|
+
* returns a promise — so a call that starts during that window changes the
|
|
10531
|
+
* right answer after the closure was made. `inCall` decides whether a
|
|
10532
|
+
* failure report is sent now or held (`heldFailureReportsRef`), and a stale
|
|
10533
|
+
* `false` there is a chat request answered out loud over whatever the caller
|
|
10534
|
+
* is saying. `actLive` is the unmount latch: nothing may assign
|
|
10535
|
+
* `location`, and nothing may send a report, after this widget is gone.
|
|
10536
|
+
*/
|
|
10537
|
+
const inCallRef = useRef(inCall);
|
|
10538
|
+
const actLiveRef = useRef(true);
|
|
10539
|
+
useEffect(() => {
|
|
10540
|
+
inCallRef.current = inCall;
|
|
10541
|
+
}, [inCall]);
|
|
10542
|
+
useEffect(() => () => {
|
|
10543
|
+
actLiveRef.current = false;
|
|
10544
|
+
actQueueRef.current = [];
|
|
10545
|
+
}, []);
|
|
10546
|
+
/**
|
|
10547
|
+
* Send a storefront report about an act that did not happen, or hold it
|
|
10548
|
+
* until the call ends.
|
|
10549
|
+
*
|
|
10550
|
+
* The exact gates `reportFailedAgentCartAdd` keeps, and for the identical
|
|
10551
|
+
* reasons: no conversation ⇒ nothing to correct; mid-call ⇒ a chat request
|
|
10552
|
+
* is answered OUT LOUD over whatever the caller is saying, so it is held and
|
|
10553
|
+
* flushed when the call ends, never dropped. `inCall` is read from the ref
|
|
10554
|
+
* because this is called at the END of an asynchronous act.
|
|
10555
|
+
*/
|
|
10556
|
+
const sendActReport = useCallback((report) => {
|
|
10557
|
+
if (chatToken === void 0 || !actLiveRef.current) return;
|
|
10558
|
+
if (inCallRef.current) {
|
|
10559
|
+
heldFailureReportsRef.current = [...heldFailureReportsRef.current, report];
|
|
10560
|
+
return;
|
|
10561
|
+
}
|
|
10562
|
+
session.sendReport(report).catch(() => void 0);
|
|
10563
|
+
}, [chatToken, session]);
|
|
10564
|
+
/**
|
|
10565
|
+
* Tell the concierge that a `spotlight` it asked for found NOTHING.
|
|
10566
|
+
*
|
|
10567
|
+
* The exact mirror of `reportFailedAgentCartAdd`: the server said
|
|
10568
|
+
* `status: 'requested'` because the card lives in a DOM it cannot see, so
|
|
10569
|
+
* this widget is the only party that learns the answer. A caller is not
|
|
10570
|
+
* looking at the panel at all, and by then the concierge has said "that's
|
|
10571
|
+
* the one, highlighted on your screen" out loud.
|
|
10572
|
+
*/
|
|
10573
|
+
const reportFailedSpotlight = useCallback((event) => {
|
|
10574
|
+
sendActReport({
|
|
10575
|
+
kind: "spotlight_failed",
|
|
10576
|
+
title: event.title ?? event.productId,
|
|
10577
|
+
productId: event.productId
|
|
10578
|
+
});
|
|
10579
|
+
}, [sendActReport]);
|
|
10580
|
+
/**
|
|
10581
|
+
* Tell the concierge the page did NOT move.
|
|
10582
|
+
*
|
|
10583
|
+
* This used to be a comment explaining that there was no correction channel
|
|
10584
|
+
* for a navigation the way there is for a cart add. There is now
|
|
10585
|
+
* (`navigate_failed`), and it is needed more than the cart one: a bridge
|
|
10586
|
+
* with no `navigate` is §3's ordinary case rather than an exotic one, and
|
|
10587
|
+
* "taking you to the cushions" is the most concrete claim the concierge
|
|
10588
|
+
* makes. A caller cannot see that the page stayed put.
|
|
10589
|
+
*
|
|
10590
|
+
* It deliberately carries no path — the guardrails forbid the concierge to
|
|
10591
|
+
* say one out loud, and a report holding a url puts it in the model's
|
|
10592
|
+
* context with nothing but an instruction in the way.
|
|
10593
|
+
*/
|
|
10594
|
+
const reportFailedNavigate = useCallback((target) => {
|
|
10595
|
+
sendActReport({
|
|
10596
|
+
kind: "navigate_failed",
|
|
10597
|
+
...target !== void 0 ? { target } : {}
|
|
10598
|
+
});
|
|
10599
|
+
}, [sendActReport]);
|
|
10600
|
+
/**
|
|
10601
|
+
* The path prefix of the storefront the shopper is ACTUALLY on.
|
|
10602
|
+
*
|
|
10603
|
+
* Shopify Markets puts a locale/market code on the front of every path
|
|
10604
|
+
* (`/en-gb/collections/rugs`). The catalogue holds handles, not markets, so
|
|
10605
|
+
* every path the server resolves is spelt without one — and sending a
|
|
10606
|
+
* shopper browsing `/en-gb/...` to a bare `/collections/rugs` drops them out
|
|
10607
|
+
* of their own market: another currency, another language, and on some
|
|
10608
|
+
* storefronts a redirect that loses the path entirely. The bridge already
|
|
10609
|
+
* classifies these prefixes; this reads the one it is looking at.
|
|
10610
|
+
*/
|
|
10611
|
+
const bridgePath = useCallback(() => {
|
|
10612
|
+
try {
|
|
10613
|
+
return bridge?.currentPage?.().path ?? "";
|
|
10614
|
+
} catch {
|
|
10615
|
+
return "";
|
|
10616
|
+
}
|
|
10617
|
+
}, [bridge]);
|
|
10618
|
+
/**
|
|
10619
|
+
* Walk the shopper to another page — `navigate` (§6).
|
|
10620
|
+
*
|
|
10621
|
+
* The §6 beat is NOT here — `performAct` waits it once per page-moving
|
|
10622
|
+
* event, so the `filter` fallback below does not wait it twice.
|
|
10623
|
+
*
|
|
10624
|
+
* ## Same-origin, re-checked HERE
|
|
10625
|
+
*
|
|
10626
|
+
* The server's schema is the boundary and `useChatSession` re-checks the
|
|
10627
|
+
* SSE frame, but the spoken leg does not come through that hook at all, and
|
|
10628
|
+
* a `filter`'s `collectionUrl` reaches this function by the same route a
|
|
10629
|
+
* `navigate`'s url does. This is the one place both legs and both fields
|
|
10630
|
+
* meet, so the predicate lives here too. A path that fails it is not
|
|
10631
|
+
* repaired: it is a page nobody meant to open.
|
|
10632
|
+
*
|
|
10633
|
+
* ## The `navigating` hint goes FIRST
|
|
10634
|
+
*
|
|
10635
|
+
* §8.6 — a caller's participant disconnects on every navigation, and at the
|
|
10636
|
+
* transport layer that is indistinguishable from a hangup. The hint is what
|
|
10637
|
+
* buys the session its bounded hold so the next page REJOINS the same
|
|
10638
|
+
* conversation. Awaited, not fired and forgotten: `location.assign` can tear
|
|
10639
|
+
* the page down before an unawaited publish reaches the wire.
|
|
10640
|
+
*/
|
|
10641
|
+
const notifyNavigating = voice.notifyNavigating;
|
|
10642
|
+
const performNavigate = useCallback(async (url, target) => {
|
|
10643
|
+
if (!isSameOriginPath(url) || !bridge?.navigate) {
|
|
10644
|
+
reportFailedNavigate(target);
|
|
10645
|
+
return;
|
|
10646
|
+
}
|
|
10647
|
+
const path = withStorefrontLocale(storefrontLocalePrefix(bridgePath()), url);
|
|
10648
|
+
if (!actLiveRef.current) return;
|
|
10649
|
+
if (voiceEnabled) await notifyNavigating().catch(() => false);
|
|
10650
|
+
if (!actLiveRef.current) return;
|
|
10651
|
+
try {
|
|
10652
|
+
await bridge.navigate(path);
|
|
10653
|
+
} catch {
|
|
10654
|
+
reportFailedNavigate(target);
|
|
10655
|
+
}
|
|
10656
|
+
}, [
|
|
10657
|
+
bridge,
|
|
10658
|
+
bridgePath,
|
|
10659
|
+
voiceEnabled,
|
|
10660
|
+
notifyNavigating,
|
|
10661
|
+
reportFailedNavigate
|
|
10662
|
+
]);
|
|
10663
|
+
/**
|
|
10664
|
+
* Perform ONE act event. Never throws — every branch is a host-facing call.
|
|
10665
|
+
*/
|
|
10666
|
+
const performAct = useCallback(async (event) => {
|
|
10667
|
+
if (event.type !== "spotlight") {
|
|
10668
|
+
if (!inCallRef.current) await new Promise((resolve) => setTimeout(resolve, NAVIGATE_BEAT_MS));
|
|
10669
|
+
if (!actLiveRef.current) return;
|
|
10670
|
+
}
|
|
10671
|
+
if (event.type === "navigate") {
|
|
10672
|
+
await performNavigate(event.url, event.target);
|
|
10673
|
+
return;
|
|
10674
|
+
}
|
|
10675
|
+
if (event.type === "filter") {
|
|
10676
|
+
if (event.collectionUrl !== void 0 && !isSameOriginPath(event.collectionUrl)) return;
|
|
10677
|
+
const prefix = storefrontLocalePrefix(bridgePath());
|
|
10678
|
+
const collectionUrl = event.collectionUrl === void 0 ? void 0 : withStorefrontLocale(prefix, event.collectionUrl);
|
|
10679
|
+
if (!(collectionUrl !== void 0 && !isSamePagePath(collectionUrl, bridgePath())) && bridge?.applyFilter) try {
|
|
10680
|
+
if (await bridge.applyFilter(event.filters) !== false) return;
|
|
10681
|
+
} catch {}
|
|
10682
|
+
if (collectionUrl !== void 0) await performNavigate(withStorefrontFacets(collectionUrl, event.filters), "collection");
|
|
10683
|
+
return;
|
|
10684
|
+
}
|
|
10685
|
+
conciergeScrollRef.current?.();
|
|
10686
|
+
const target = event;
|
|
10687
|
+
let found = false;
|
|
10688
|
+
try {
|
|
10689
|
+
found = bridge?.spotlight?.(target) ?? (typeof window === "undefined" ? false : spotlightProductCard(window, window.document, target, { ...siteProfile ? { siteProfile } : {} }));
|
|
10690
|
+
} catch {}
|
|
10691
|
+
if (!found) {
|
|
10692
|
+
conciergeScrollRef.current?.(0);
|
|
10693
|
+
reportFailedSpotlight(event);
|
|
10694
|
+
}
|
|
10695
|
+
}, [
|
|
10696
|
+
bridge,
|
|
10697
|
+
bridgePath,
|
|
10698
|
+
siteProfile,
|
|
10699
|
+
performNavigate,
|
|
10700
|
+
reportFailedSpotlight
|
|
10701
|
+
]);
|
|
10702
|
+
/**
|
|
10703
|
+
* The acts the concierge asked for, from both legs, performed exactly once
|
|
10704
|
+
* each and one at a time.
|
|
10705
|
+
*
|
|
10706
|
+
* Two sources (`session.actEvents` for the typed leg, `voice.widgetEvents`
|
|
10707
|
+
* for the spoken one), one consumption record, **consumed by object
|
|
10708
|
+
* IDENTITY**, marked consumed BEFORE they are performed — all of that is the
|
|
10709
|
+
* agent-cart-add effect's discipline and the reasons are the same there.
|
|
10710
|
+
* Identity matters MORE here: a shopper who says "that one again" produces a
|
|
10711
|
+
* second `spotlight` for the SAME product, and a consumer keyed on the
|
|
10712
|
+
* payload would silently swallow the repeat.
|
|
10713
|
+
*
|
|
10714
|
+
* ## Why a queue and a ref, rather than an async loop per run
|
|
10715
|
+
*
|
|
10716
|
+
* The effect used to depend on `performAct`, whose identity churns on every
|
|
10717
|
+
* render (`useChatSession` returns a fresh object, so every callback built
|
|
10718
|
+
* from `session` is new every frame). So the effect re-ran constantly, and
|
|
10719
|
+
* an event arriving while a previous act was still in flight started a
|
|
10720
|
+
* SECOND async loop beside the first: a `filter` and a `navigate` racing to
|
|
10721
|
+
* assign `location`, or two beats elapsing concurrently. The events were
|
|
10722
|
+
* still performed once each — identity saw to that — but "sequential" was
|
|
10723
|
+
* never true.
|
|
10724
|
+
*
|
|
10725
|
+
* Now the effect only ENQUEUES, and depends on nothing but the two lists. A
|
|
10726
|
+
* single drain runs at a time (`actDrainingRef`), reads the latest
|
|
10727
|
+
* `performAct` out of a ref at the moment it runs each event (so nothing is
|
|
10728
|
+
* performed with a stale `bridge` or a stale call state), and stops on
|
|
10729
|
+
* unmount — no `location.assign` and no `sendReport` after teardown.
|
|
10730
|
+
*/
|
|
10731
|
+
const consumedActsRef = useRef(/* @__PURE__ */ new WeakSet());
|
|
10732
|
+
const actQueueRef = useRef([]);
|
|
10733
|
+
const actDrainingRef = useRef(false);
|
|
10734
|
+
const performActRef = useRef(performAct);
|
|
10735
|
+
useEffect(() => {
|
|
10736
|
+
performActRef.current = performAct;
|
|
10737
|
+
}, [performAct]);
|
|
10738
|
+
const voiceWidgetEventsForActs = voice.widgetEvents;
|
|
10739
|
+
const sessionActEvents = session.actEvents;
|
|
10740
|
+
useEffect(() => {
|
|
10741
|
+
for (const event of voiceWidgetEventsForActs) {
|
|
10742
|
+
if (!isActEvent(event)) continue;
|
|
10743
|
+
if (consumedActsRef.current.has(event)) continue;
|
|
10744
|
+
consumedActsRef.current.add(event);
|
|
10745
|
+
actQueueRef.current.push(event);
|
|
10746
|
+
}
|
|
10747
|
+
for (const event of sessionActEvents) {
|
|
10748
|
+
if (consumedActsRef.current.has(event)) continue;
|
|
10749
|
+
consumedActsRef.current.add(event);
|
|
10750
|
+
actQueueRef.current.push(event);
|
|
10751
|
+
}
|
|
10752
|
+
if (actDrainingRef.current || actQueueRef.current.length === 0) return;
|
|
10753
|
+
actDrainingRef.current = true;
|
|
10754
|
+
(async () => {
|
|
10755
|
+
try {
|
|
10756
|
+
for (;;) {
|
|
10757
|
+
if (!actLiveRef.current) break;
|
|
10758
|
+
const next = actQueueRef.current.shift();
|
|
10759
|
+
if (next === void 0) break;
|
|
10760
|
+
await performActRef.current(next);
|
|
10761
|
+
}
|
|
10762
|
+
} finally {
|
|
10763
|
+
actDrainingRef.current = false;
|
|
10764
|
+
}
|
|
10765
|
+
})();
|
|
10766
|
+
}, [voiceWidgetEventsForActs, sessionActEvents]);
|
|
9638
10767
|
const consumedCartAddsRef = useRef(/* @__PURE__ */ new WeakSet());
|
|
9639
10768
|
const voiceWidgetEvents = voice.widgetEvents;
|
|
9640
10769
|
const sessionCartAdds = session.cartAdds;
|
|
@@ -10396,6 +11525,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
10396
11525
|
roomDropped: voiceEnabled && voice.phase === "disconnected",
|
|
10397
11526
|
...latestCuration ? { shelf: latestCuration } : {},
|
|
10398
11527
|
pageKey,
|
|
11528
|
+
conciergeScrollRef,
|
|
10399
11529
|
...initialDraft !== void 0 ? { initialDraft } : {},
|
|
10400
11530
|
...initialSelection !== void 0 ? { initialSelection } : {},
|
|
10401
11531
|
...initialFocus !== void 0 ? { initialFocus } : {},
|
|
@@ -10436,4 +11566,4 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
10436
11566
|
});
|
|
10437
11567
|
}
|
|
10438
11568
|
//#endregion
|
|
10439
|
-
export {
|
|
11569
|
+
export { RADII as $, latencyBetween as A, linearToSrgb as At, CONTROL as B, srgbToLinear as Bt, parseBlocks as C, themeToCss as Ct, SESSION_EVENTS as D, hexToOklab as Dt, SseFrameParser as E, formatHex as Et, idleDockInput as F, oklchToHex as Ft, DOCK_ALIGN_STORAGE_KEY as G, widgetMessagesFromCopy as Gt, DESKTOP_BREAKPOINT as H, defaultWidgetMessages as Ht, latestExchangeStart as I, oklchToOklab as It, MARK as J, DOCK_MINIMISED_STORAGE_KEY as K, formatMoney as L, parseHex as Lt, DOCK_STATES as M, oklabToHex as Mt, deriveDockState as N, oklabToLinearRgb as Nt, SessionLog as O, hexToOklch as Ot, exchangeCount as P, oklabToOklch as Pt, PROACTIVE_NUDGE_MS as Q, ACTIVITY_W as R, relativeLuminance as Rt, WidgetMarkdown as S, deriveTheme as St, botStateFor as T, contrastRatio as Tt, DESKTOP_GUTTER as U, formatMessage as Ut, DESKTOP_BOTTOM as V, withAlpha as Vt, DESKTOP_WIDTHS as W, resolveWidgetMessages as Wt, PILL_H as X, MOBILE_MARGIN as Y, PILL_MARK as Z, readsAsCartViewIntent as _, writeStored as _t, mergeAddedCartLine as a, SHEET_TOP_CLEARANCE as at, WidgetCartSummary as b, SYSTEM_FONT_STACK as bt, toChatCart as c, bottomLen as ct, useVoiceSession as d, pillAnchor as dt, ROW_H as et, isSameOriginPath as f, readStored as ft, basketIntentFromTurns as g, snapAlign as gt, VoiceWidget as h, sheetMaxHeightLen as ht, deriveCallPhase as i, SHEET_PEEK_MAX as it, Dock as j, mixToward as jt, formatMs as k, linearRgbToOklab as kt, ROOM_EVENTS as l, geometryVars as lt, detectPage as m, rowWidthLen as mt, MAX_REPORTED_CART_LINES as n, SHEET_EXPANDED_VH as nt, resolveAddToCartHandler as o, SHORT_VIEWPORT as ot, useChatSession as p, readStoredAlign as pt, DRAG_TAP_SLOP_PX as q, cartLinesFromSnapshot as r, SHEET_GAP as rt, resolveCheckoutUrl as s, Z_INDEX as st, ConciergeWidget as t, SHEET_EXPANDED_DESKTOP_MAX as tt, createWidgetVoiceTokenFetcher as u, persistAlign as ut, readsAsCheckoutIntent as v, CARD_RADIUS_MAX_PX as vt, IDLE_SNAPSHOT as w, themeToInlineStyle as wt, WidgetCardList as x, WIDGET_THEME_TOKENS as xt, textDirectionFor as y, SHEET_RADIUS_MAX_PX as yt, BOTTOM_FLOOR as z, rotateHue as zt };
|