@sparkvault/sdk-js 15.2.0 → 15.3.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/index.mjs CHANGED
@@ -14964,6 +14964,107 @@ function mapInvitation(wire) {
14964
14964
  };
14965
14965
  }
14966
14966
 
14967
+ /** The native support ceremony. Identity receipts stay inside the first-party window. */
14968
+ const VALUE = /^[A-Za-z0-9_-]{43}$/;
14969
+ /** Open synchronously inside the user's gesture, before preparing the server challenge. */
14970
+ function openWidgetIdentity(options, prepare, ready, redeem) {
14971
+ if (typeof window === 'undefined')
14972
+ return Promise.reject(new ValidationError('Support sign-in requires a browser.'));
14973
+ if (options.signal?.aborted)
14974
+ return Promise.reject(new UserCancelledError());
14975
+ const popup = window.open('about:blank', '_blank', 'popup=1,width=480,height=640');
14976
+ if (!popup)
14977
+ return Promise.reject(new SparkVaultError('Allow the sign-in window, then try again.', 'HELP_DESK_POPUP_BLOCKED'));
14978
+ try {
14979
+ popup.document.title = 'Secure support sign-in';
14980
+ popup.document.body.textContent = 'Opening secure sign-in…';
14981
+ }
14982
+ catch { /* The popup may already have navigated. */ }
14983
+ return new Promise((resolve, reject) => {
14984
+ let challenge = null;
14985
+ let firstPartyOrigin = null;
14986
+ let settled = false;
14987
+ let checking = false;
14988
+ let interval;
14989
+ const timeout = setTimeout(() => finish(new SparkVaultError('Support sign-in expired. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_EXPIRED')), 15 * 60 * 1000);
14990
+ const finish = (error, session) => {
14991
+ if (settled)
14992
+ return;
14993
+ settled = true;
14994
+ clearTimeout(timeout);
14995
+ if (interval)
14996
+ clearInterval(interval);
14997
+ window.removeEventListener('message', receive);
14998
+ options.signal?.removeEventListener('abort', cancel);
14999
+ try {
15000
+ popup.close();
15001
+ }
15002
+ catch { /* A severed opener is still completed by PKCE polling. */ }
15003
+ if (error)
15004
+ reject(error);
15005
+ else
15006
+ resolve(session);
15007
+ };
15008
+ const cancel = () => finish(new UserCancelledError());
15009
+ const complete = async (code) => {
15010
+ if (!challenge || settled || checking)
15011
+ return;
15012
+ checking = true;
15013
+ try {
15014
+ finish(null, await redeem(challenge, code));
15015
+ }
15016
+ catch (error) {
15017
+ finish(error instanceof Error ? error : new Error(String(error)));
15018
+ }
15019
+ };
15020
+ const receive = (event) => {
15021
+ if (!challenge || event.source !== popup || event.origin !== firstPartyOrigin)
15022
+ return;
15023
+ const data = event.data;
15024
+ if (!data || data.type !== 'sparkvault:help-desk:identity' || data.challenge_id !== challenge.challenge_id || data.state !== challenge.state)
15025
+ return;
15026
+ if (data.cancelled === true) {
15027
+ cancel();
15028
+ return;
15029
+ }
15030
+ if (typeof data.code === 'string' && VALUE.test(data.code))
15031
+ void complete(data.code);
15032
+ };
15033
+ window.addEventListener('message', receive);
15034
+ options.signal?.addEventListener('abort', cancel, { once: true });
15035
+ void prepare().then((value) => {
15036
+ if (settled)
15037
+ return;
15038
+ const url = new URL(value.sign_in_url);
15039
+ if (!VALUE.test(value.challenge_id) || !VALUE.test(value.verifier) || !VALUE.test(value.state) || !Number.isSafeInteger(value.expires_at) ||
15040
+ url.protocol !== 'https:' || url.origin !== 'https://auth.sv' || url.username || url.password || url.search || url.hash ||
15041
+ !/^\/help-desk\/acc_[0-9a-f]{32}\/[A-Za-z0-9_-]{43}$/.test(url.pathname) ||
15042
+ !url.pathname.endsWith(`/${value.challenge_id}`))
15043
+ throw new SparkVaultError('The support sign-in address is invalid.', 'HELP_DESK_INVALID_RESPONSE');
15044
+ challenge = value;
15045
+ firstPartyOrigin = url.origin;
15046
+ popup.location.replace(url.href);
15047
+ // Code delivery must survive a browser severing window.opener during
15048
+ // the first-party Identity redirect. Polling knows only the original
15049
+ // challenge and verifier; no Identity JWT ever reaches this page.
15050
+ interval = setInterval(() => {
15051
+ if (settled || checking || !challenge)
15052
+ return;
15053
+ checking = true;
15054
+ void ready(challenge).then((available) => {
15055
+ checking = false;
15056
+ if (available)
15057
+ void complete();
15058
+ }).catch((error) => {
15059
+ checking = false;
15060
+ if (error instanceof UserCancelledError || (error instanceof SparkVaultError && error.statusCode && error.statusCode < 500 && error.statusCode !== 429))
15061
+ finish(error);
15062
+ });
15063
+ }, 2500);
15064
+ }).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
15065
+ });
15066
+ }
15067
+
14967
15068
  /** The customer API. It never sends the enclosing SDK's operator credentials. */
14968
15069
  const CLIENT = 'help-desk-portal';
14969
15070
  const SESSION_TOKEN = /^hdt_[A-Za-z0-9_-]{43}$/;
@@ -15071,12 +15172,15 @@ class HelpDeskClient {
15071
15172
  this.deadline = null;
15072
15173
  this.token = null;
15073
15174
  this.revision = 0;
15175
+ this.websiteAccountSuppressed = false;
15176
+ this.ticketAccess = null;
15074
15177
  this.desk = Object.freeze({ ...desk, branding: Object.freeze({ ...desk.branding }), identity: desk.identity ? Object.freeze({ ...desk.identity }) : null,
15075
15178
  external_identity: desk.external_identity ? Object.freeze({ ...desk.external_identity }) : undefined });
15076
15179
  this.http = http;
15077
15180
  this.transfers = transfers;
15078
15181
  this.provider = provider;
15079
15182
  this.assertionProvider = assertionProvider;
15183
+ this.currentTicketPolicy = desk.ticket_access_control;
15080
15184
  }
15081
15185
  /** Discover a desk by its configured host, before any customer credentials are sent. */
15082
15186
  static async connect(config, options) {
@@ -15115,6 +15219,8 @@ class HelpDeskClient {
15115
15219
  * resumes the provider.
15116
15220
  */
15117
15221
  setSession(session) {
15222
+ if (session?.customer.assurance === 'identity' && ['external_sso', 'external_unavailable'].includes(this.desk.auth_mode))
15223
+ this.websiteAccountSuppressed = true;
15118
15224
  this.installSession(session, null);
15119
15225
  }
15120
15226
  installSession(session, deadline) {
@@ -15156,14 +15262,49 @@ class HelpDeskClient {
15156
15262
  }
15157
15263
  /** Whether company identity can be established without customer interaction. */
15158
15264
  get hasIdentityProvider() { return typeof this.assertionProvider === 'function'; }
15265
+ /** The independent ticket gate must be met before rendering authenticated ticket UI. */
15266
+ get hasTicketAccess() {
15267
+ const policy = this.currentTicketPolicy;
15268
+ if (!policy || policy.mode === 'public')
15269
+ return true;
15270
+ if (policy.mode === 'ip_allowlist')
15271
+ return policy.ip_allowed === true;
15272
+ return this.ticketAccess !== null && this.ticketAccess.deadline > Date.now() / 1000;
15273
+ }
15274
+ clearTicketAccess() { this.ticketAccess = null; }
15275
+ get ticketAccessPolicy() { return this.currentTicketPolicy; }
15276
+ /** Refresh network/policy hints without replacing requester state or composition. */
15277
+ async refreshTicketAccessPolicy() {
15278
+ const { data } = await this.http.request(apiPath `/v1/hd/desks`, {
15279
+ query: { host: this.desk.canonical_host }, headers: { 'X-SV-Client': CLIENT }, credentials: 'omit',
15280
+ });
15281
+ if (data?.kind !== 'desk' || data.desk_id !== this.desk.desk_id || data.portal_client !== CLIENT) {
15282
+ throw new SparkVaultError('This help desk could not refresh its access settings.', 'HELP_DESK_INVALID_RESPONSE');
15283
+ }
15284
+ if (JSON.stringify(data.ticket_access_control) !== JSON.stringify(this.currentTicketPolicy))
15285
+ this.clearTicketAccess();
15286
+ this.currentTicketPolicy = data.ticket_access_control ? Object.freeze({ ...data.ticket_access_control }) : undefined;
15287
+ }
15288
+ async unlockTicketAccess(options) {
15289
+ if ((options.password !== undefined) === (options.identityGrant !== undefined))
15290
+ throw new ValidationError('Choose a password or a verified employee identity.');
15291
+ const revision = this.revision;
15292
+ const mode = options.password !== undefined ? 'password' : 'identity';
15293
+ const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/access/${mode}`, mode === 'password' ? { password: options.password } : { token: options.identityGrant }, undefined, false);
15294
+ if (revision !== this.revision)
15295
+ throw sessionChanged();
15296
+ if (!/^hdapt_[A-Za-z0-9_-]{43}$/.test(result?.token) || !validLifetime(result.ttl_seconds))
15297
+ throw new SparkVaultError('The help desk returned an invalid access grant.', 'HELP_DESK_INVALID_RESPONSE');
15298
+ this.ticketAccess = { token: result.token, deadline: Date.now() / 1000 + result.ttl_seconds };
15299
+ }
15159
15300
  /** @internal Read an installed server-proven company bearer without invoking any identity provider. */
15160
15301
  verifiedSessionTokenFor(requesterId) {
15161
15302
  return this.verifiedRequesterId === requesterId && this.provedSession && this.session?.token === this.token ? this.token : null;
15162
15303
  }
15163
15304
  async getSessionToken() {
15164
- if (this.desk.auth_mode === 'external_unavailable')
15305
+ if (!this.websiteAccountSuppressed && this.desk.auth_mode === 'external_unavailable')
15165
15306
  throw new SparkVaultError('Company-session authentication is unavailable.', 'HELP_DESK_EXTERNAL_UNAVAILABLE', 503);
15166
- if (this.assertionProvider && this.desk.auth_mode === 'external_sso' &&
15307
+ if (!this.websiteAccountSuppressed && this.assertionProvider && this.desk.auth_mode === 'external_sso' &&
15167
15308
  (this.session === undefined || (this.session && (!this.provedSession || (this.verifiedRequesterId !== null && this.deadline !== null && this.deadline <= Date.now() / 1000 + RENEW_BEFORE_SECONDS))))) {
15168
15309
  await this.authenticate();
15169
15310
  return this.session?.token ?? null;
@@ -15173,6 +15314,8 @@ class HelpDeskClient {
15173
15314
  this.clearSession();
15174
15315
  return this.session?.token ?? null;
15175
15316
  }
15317
+ if (this.websiteAccountSuppressed)
15318
+ return null;
15176
15319
  const revision = this.revision;
15177
15320
  const token = await this.provider?.() ?? null;
15178
15321
  if (revision !== this.revision)
@@ -15216,7 +15359,8 @@ class HelpDeskClient {
15216
15359
  try {
15217
15360
  const { data } = await this.http.request(path, {
15218
15361
  method, body, query, credentials: 'omit',
15219
- headers: { 'X-SV-Client': CLIENT, ...(token ? { Authorization: `Bearer ${token}` } : {}) },
15362
+ headers: { 'X-SV-Client': CLIENT, ...(token ? { Authorization: `Bearer ${token}` } : {}),
15363
+ ...(this.ticketAccess && this.ticketAccess.deadline > Date.now() / 1000 ? { 'X-SV-HelpDesk-Access': this.ticketAccess.token } : {}) },
15220
15364
  });
15221
15365
  // A headless caller can render an awaited result without its own UI
15222
15366
  // generation guard. Never return the former customer's data after an
@@ -15228,6 +15372,8 @@ class HelpDeskClient {
15228
15372
  catch (error) {
15229
15373
  if (!stillCurrent())
15230
15374
  throw sessionChanged();
15375
+ if (error instanceof SparkVaultError && ['HELP_DESK_ACCESS_REQUIRED', 'HELP_DESK_IP_DENIED'].includes(error.serviceCode || error.code))
15376
+ this.clearTicketAccess();
15231
15377
  if (token && error instanceof SparkVaultError && error.statusCode === 401 && revision === this.revision && this.token === token)
15232
15378
  this.clearSession();
15233
15379
  throw error;
@@ -15275,6 +15421,8 @@ class HelpDeskClient {
15275
15421
  }
15276
15422
  /** Silently establish/renew a company session. Concurrent calls share one proof. */
15277
15423
  authenticate() {
15424
+ if (this.websiteAccountSuppressed)
15425
+ return Promise.resolve(null);
15278
15426
  if (this.authentication)
15279
15427
  return this.authentication;
15280
15428
  if (this.desk.auth_mode !== 'external_sso' || !this.assertionProvider || !this.desk.external_identity) {
@@ -15362,6 +15510,48 @@ class HelpDeskClient {
15362
15510
  completeIdentity(options) {
15363
15511
  return this.establish(apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/identity/complete`, { token: options.token });
15364
15512
  }
15513
+ /** Uninstalled result: the owning form/controller decides when the new requester becomes current. */
15514
+ signInWidgetIdentity(options = {}) {
15515
+ const revision = this.revision;
15516
+ return openWidgetIdentity(options, () => this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/challenge`, {
15517
+ ...(options.email && { email: options.email }), ...(options.givenName && { given_name: options.givenName }),
15518
+ ...(options.familyName && { family_name: options.familyName }), ...(options.selectAccount && { select_account: true }),
15519
+ ...(options.employeeCompanyId && { employee_company_id: options.employeeCompanyId }),
15520
+ }, undefined, false), async (challenge) => {
15521
+ const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/result`, {
15522
+ challenge_id: challenge.challenge_id, verifier: challenge.verifier,
15523
+ }, undefined, false);
15524
+ if (result.cancelled)
15525
+ throw new UserCancelledError();
15526
+ return result.ready;
15527
+ }, async (challenge, code) => {
15528
+ const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/redeem`, {
15529
+ challenge_id: challenge.challenge_id, verifier: challenge.verifier, ...(code && { code }),
15530
+ }, undefined, false);
15531
+ if (revision !== this.revision)
15532
+ throw sessionChanged();
15533
+ if (!validToken(result?.token) || result.customer?.assurance !== 'identity' || !/^hdwip_[A-Za-z0-9_-]{43}$/.test(result.identity_grant?.token)) {
15534
+ throw new SparkVaultError('The help desk returned an invalid support identity.', 'HELP_DESK_INVALID_RESPONSE');
15535
+ }
15536
+ return result;
15537
+ });
15538
+ }
15539
+ /** Choose a different support identity without logging out or changing the host website. */
15540
+ switchSupportAccount() {
15541
+ this.websiteAccountSuppressed = true;
15542
+ return this.logout();
15543
+ }
15544
+ /** The only operation that resumes the website's configured identity provider after an explicit switch. */
15545
+ async useWebsiteAccount() {
15546
+ await this.logout();
15547
+ this.websiteAccountSuppressed = false;
15548
+ if (!this.hasTicketAccess)
15549
+ return null;
15550
+ if (this.assertionProvider)
15551
+ return this.authenticate();
15552
+ await this.refreshSession();
15553
+ return null;
15554
+ }
15365
15555
  getMe() { return this.send('GET', apiPath `/v1/hd/desks/${this.desk.desk_id}/me`); }
15366
15556
  updateMe(patch, context) { return this.send('PUT', apiPath `/v1/hd/desks/${this.desk.desk_id}/me`, patch, undefined, true, context); }
15367
15557
  createDraft(context) { return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/drafts`, undefined, undefined, true, context); }
@@ -15370,6 +15560,8 @@ class HelpDeskClient {
15370
15560
  const ticket = resource('ticket', options.ticketId, 'ticketId');
15371
15561
  return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets`, {
15372
15562
  ticket_id: ticket, subject: options.subject, body: options.body, attachments: options.attachments ?? [],
15563
+ ...(options.assistance_attempt_id && { assistance_attempt_id: options.assistance_attempt_id }),
15564
+ ...(options.assistance_visitor_id && { assistance_visitor_id: options.assistance_visitor_id }),
15373
15565
  }, undefined, true, context);
15374
15566
  }
15375
15567
  listTickets(options = {}) {
@@ -15417,11 +15609,13 @@ class HelpDeskClient {
15417
15609
  // Snapshot first: logging out must not call a provider or renew a session
15418
15610
  // using a website account which may already have changed.
15419
15611
  const token = this.token;
15612
+ const accessToken = this.ticketAccess?.token;
15420
15613
  this.clearSession();
15421
- if (!token)
15614
+ this.clearTicketAccess();
15615
+ if (!token && !accessToken)
15422
15616
  return;
15423
15617
  await this.http.request(apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/logout`, {
15424
- method: 'POST', credentials: 'omit', headers: { 'X-SV-Client': CLIENT, Authorization: `Bearer ${token}` },
15618
+ method: 'POST', credentials: 'omit', headers: { 'X-SV-Client': CLIENT, ...(token && { Authorization: `Bearer ${token}` }), ...(accessToken && { 'X-SV-HelpDesk-Access': accessToken }) },
15425
15619
  });
15426
15620
  }
15427
15621
  }
@@ -16371,6 +16565,7 @@ function injectHelpDeskFormStyles() {
16371
16565
  .svhd-done{display:grid;gap:12px}
16372
16566
  .svhd-done-title{font-size:18px;line-height:1.3;margin:0}
16373
16567
  .svhd-done-title:focus{outline:none}
16568
+ .svhd-confirmation-message{white-space:pre-wrap;overflow-wrap:anywhere}
16374
16569
  .svhd-link{display:inline-flex;align-items:center;justify-self:start;min-height:44px;color:${DS.action};text-decoration:underline}
16375
16570
  .svhd-attachments[hidden],.svhd-attachments [hidden]{display:none}
16376
16571
  .svhd-file-hint{font-size:13px;color:${DS.slate600};margin:0}
@@ -17209,7 +17404,7 @@ function createDescriptionInput() {
17209
17404
  return document.createElement('textarea');
17210
17405
  }
17211
17406
  /** Host callback failures do not change a ticket's accepted or failed result. */
17212
- function notify(callback, value) {
17407
+ function notify$1(callback, value) {
17213
17408
  try {
17214
17409
  void Promise.resolve(callback?.(value)).catch(() => undefined);
17215
17410
  }
@@ -17321,7 +17516,9 @@ function mountHelpDeskForm(client, options) {
17321
17516
  const email = field('Email address', 'email');
17322
17517
  const code = field('Email code', 'code');
17323
17518
  const name = field('Your name', 'display_name');
17324
- const fields = [subject, description, email, code, name];
17519
+ const firstName = field('First name', 'given_name');
17520
+ const lastName = field('Last name (optional)', 'family_name');
17521
+ const fields = [subject, description, email, code, name, firstName, lastName];
17325
17522
  subject.input.maxLength = 200;
17326
17523
  subject.input.value = options.subject ?? '';
17327
17524
  description.input.value = options.body ?? '';
@@ -17330,6 +17527,10 @@ function mountHelpDeskForm(client, options) {
17330
17527
  code.input.inputMode = 'numeric';
17331
17528
  code.input.autocomplete = 'one-time-code';
17332
17529
  name.input.autocomplete = 'name';
17530
+ firstName.input.autocomplete = 'given-name';
17531
+ lastName.input.autocomplete = 'family-name';
17532
+ firstName.input.maxLength = 100;
17533
+ lastName.input.maxLength = 100;
17333
17534
  const codeHint = document.createElement('p');
17334
17535
  codeHint.id = `${code.input.id}-hint`;
17335
17536
  codeHint.className = 'svhd-file-hint';
@@ -17353,6 +17554,19 @@ function mountHelpDeskForm(client, options) {
17353
17554
  auth.className = 'svhd-auth';
17354
17555
  auth.hidden = true;
17355
17556
  auth.append(email.wrapper, code.wrapper, name.wrapper);
17557
+ const widgetAccount = document.createElement('div');
17558
+ widgetAccount.className = 'svhd-widget-account';
17559
+ let widgetCustomer = options.widgetIdentity?.customer ?? null;
17560
+ if (options.widgetIdentity) {
17561
+ const names = document.createElement('div');
17562
+ names.className = 'svhd-widget-names';
17563
+ names.append(firstName.wrapper, lastName.wrapper);
17564
+ auth.prepend(names);
17565
+ form.classList.add('svhd-widget-form');
17566
+ heading.textContent = `Contact ${client.desk.organization_name || 'support'}`;
17567
+ description.wrapper.querySelector('label').textContent = 'Message';
17568
+ description.wrapper.classList.add('svhd-widget-message');
17569
+ }
17356
17570
  const status = document.createElement('p');
17357
17571
  status.className = 'svhd-status';
17358
17572
  status.setAttribute('role', 'status');
@@ -17372,7 +17586,7 @@ function mountHelpDeskForm(client, options) {
17372
17586
  const send = document.createElement('button');
17373
17587
  send.className = 'svhd-button';
17374
17588
  send.type = 'submit';
17375
- send.textContent = 'Send request';
17589
+ send.textContent = options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
17376
17590
  const cancel = document.createElement('button');
17377
17591
  cancel.className = 'svhd-button svhd-secondary';
17378
17592
  cancel.type = 'button';
@@ -17404,7 +17618,7 @@ function mountHelpDeskForm(client, options) {
17404
17618
  discard.textContent = DISCARD_REQUEST_COPY.discard;
17405
17619
  confirmActions.append(keepEditing, discard);
17406
17620
  confirm.append(confirmTitle, confirmNote, confirmActions);
17407
- form.append(subject.wrapper, description.wrapper, auth, status, hosted, actions, confirm);
17621
+ form.append(subject.wrapper, description.wrapper, auth, widgetAccount, status, hosted, actions, confirm);
17408
17622
  let state = 'editing';
17409
17623
  let destroyed = false;
17410
17624
  let pending = false;
@@ -17431,9 +17645,59 @@ function mountHelpDeskForm(client, options) {
17431
17645
  let resendTimer = null;
17432
17646
  let confirmReturn = null;
17433
17647
  let done = null;
17648
+ function safeComposition() {
17649
+ // An account switch must not turn an uncertain send into a fresh request.
17650
+ return pending || uncertainSubmission !== null || completed ? null : { subject: subject.input.value, body: description.input.value };
17651
+ }
17652
+ function renderWidgetIdentity() {
17653
+ if (!options.widgetIdentity)
17654
+ return;
17655
+ widgetAccount.replaceChildren();
17656
+ send.textContent = widgetCustomer ? 'Send message' : 'Continue';
17657
+ auth.hidden = widgetCustomer !== null;
17658
+ email.wrapper.hidden = false;
17659
+ code.wrapper.hidden = true;
17660
+ name.wrapper.hidden = true;
17661
+ if (widgetCustomer) {
17662
+ const identity = document.createElement('p');
17663
+ identity.className = 'svhd-widget-identity';
17664
+ const customerName = document.createElement('strong');
17665
+ customerName.textContent = widgetCustomer.display_name || widgetCustomer.email;
17666
+ const customerEmail = document.createElement('span');
17667
+ customerEmail.textContent = widgetCustomer.email;
17668
+ identity.append(customerName, customerEmail);
17669
+ const change = document.createElement('button');
17670
+ change.type = 'button';
17671
+ change.className = 'svhd-widget-account-link';
17672
+ change.textContent = 'Not you?';
17673
+ change.addEventListener('click', () => {
17674
+ if (pending || destroyed || uncertainSubmission !== null || completed)
17675
+ return;
17676
+ options.widgetIdentity?.switchAccount(safeComposition());
17677
+ });
17678
+ widgetAccount.append(identity, change);
17679
+ }
17680
+ else {
17681
+ const note = document.createElement('p');
17682
+ note.className = 'svhd-file-hint';
17683
+ note.textContent = 'We’ll confirm your email before sending your request.';
17684
+ widgetAccount.append(note);
17685
+ }
17686
+ if (options.widgetIdentity.useWebsiteAccount) {
17687
+ const website = document.createElement('button');
17688
+ website.type = 'button';
17689
+ website.className = 'svhd-widget-account-link';
17690
+ website.textContent = 'Use website account';
17691
+ website.addEventListener('click', () => {
17692
+ if (!pending && !destroyed && uncertainSubmission === null && !completed)
17693
+ options.widgetIdentity?.useWebsiteAccount?.(safeComposition());
17694
+ });
17695
+ widgetAccount.append(website);
17696
+ }
17697
+ }
17434
17698
  function setState(next) {
17435
17699
  state = next;
17436
- notify(options.onStateChange, next);
17700
+ notify$1(options.onStateChange, next);
17437
17701
  }
17438
17702
  function message(text, isError = false) {
17439
17703
  status.textContent = text;
@@ -17460,8 +17724,10 @@ function mountHelpDeskForm(client, options) {
17460
17724
  renderResend();
17461
17725
  }
17462
17726
  function disable(disabled) {
17463
- for (const input of [subject.input, description.input, email.input, code.input, name.input, send, cancel, changeEmail])
17727
+ for (const input of [subject.input, description.input, email.input, code.input, name.input, firstName.input, lastName.input, send, cancel, changeEmail])
17464
17728
  input.disabled = disabled;
17729
+ for (const button of widgetAccount.querySelectorAll('button'))
17730
+ button.disabled = disabled || uncertainSubmission !== null || completed;
17465
17731
  renderResend();
17466
17732
  attachments?.disablePicking(disabled);
17467
17733
  attachments?.lock(completed || uncertainSubmission !== null);
@@ -17570,6 +17836,12 @@ function mountHelpDeskForm(client, options) {
17570
17836
  note.textContent = next.join(' ');
17571
17837
  section.append(note);
17572
17838
  }
17839
+ if (client.desk.ticket_confirmation_message) {
17840
+ const message = document.createElement('p');
17841
+ message.className = 'svhd-status svhd-confirmation-message';
17842
+ message.textContent = client.desk.ticket_confirmation_message;
17843
+ section.append(message);
17844
+ }
17573
17845
  if (requestUrl) {
17574
17846
  const link = document.createElement('a');
17575
17847
  link.className = 'svhd-link';
@@ -17613,6 +17885,11 @@ function mountHelpDeskForm(client, options) {
17613
17885
  code.wrapper.hidden = true;
17614
17886
  name.wrapper.hidden = true;
17615
17887
  auth.hidden = true;
17888
+ if (options.widgetIdentity) {
17889
+ firstName.input.value = '';
17890
+ lastName.input.value = '';
17891
+ renderWidgetIdentity();
17892
+ }
17616
17893
  hosted.hidden = true;
17617
17894
  draftId = null;
17618
17895
  draftPromise = null;
@@ -17664,6 +17941,8 @@ function mountHelpDeskForm(client, options) {
17664
17941
  generation += 1;
17665
17942
  pending = false;
17666
17943
  sessionKnown = false;
17944
+ if (options.widgetIdentity)
17945
+ widgetCustomer = null;
17667
17946
  clearComposer();
17668
17947
  disable(false);
17669
17948
  setState('editing');
@@ -17769,19 +18048,51 @@ function mountHelpDeskForm(client, options) {
17769
18048
  refused.input.focus();
17770
18049
  return;
17771
18050
  }
18051
+ let widgetSignIn;
18052
+ if (options.widgetIdentity && !widgetCustomer) {
18053
+ const givenName = firstName.input.value.trim();
18054
+ const familyName = lastName.input.value.trim();
18055
+ const emailAddress = email.input.value.trim();
18056
+ const invalid = !givenName ? firstName : !email.input.validity.valid || !emailAddress ? email : null;
18057
+ if (invalid) {
18058
+ setFieldError(invalid, invalid === email ? 'Enter your email address.' : 'Enter your first name.');
18059
+ invalid.input.focus();
18060
+ return;
18061
+ }
18062
+ // Invoke in the original submit gesture, before any awaited token read:
18063
+ // the Identity adapter can open its native window without a popup block.
18064
+ try {
18065
+ widgetSignIn = options.widgetIdentity.signIn({ email: emailAddress, givenName, familyName });
18066
+ }
18067
+ catch (failure) {
18068
+ const error = failure instanceof Error ? failure : new Error('Sign-in could not be opened.');
18069
+ message(error.message, true);
18070
+ notify$1(options.onError, error);
18071
+ return;
18072
+ }
18073
+ // A failed popup must not produce an unhandled rejection while the
18074
+ // account provider finishes its own asynchronous token read.
18075
+ void widgetSignIn.catch(() => undefined);
18076
+ }
17772
18077
  const ownGeneration = generation;
17773
18078
  let ticketAttempted = false;
17774
18079
  pending = true;
17775
18080
  disable(true);
17776
18081
  message('');
17777
18082
  try {
18083
+ if (widgetSignIn) {
18084
+ authenticating = true;
18085
+ authNotification = false;
18086
+ setState('authenticating');
18087
+ message('Confirm your email in the sign-in window.');
18088
+ }
17778
18089
  let token = await tokenFor(ownGeneration);
17779
18090
  if (!alive(ownGeneration))
17780
18091
  return;
17781
- if (!token && options.onAuthRequired && client.desk.auth_mode !== 'external_sso' && client.desk.auth_mode !== 'external_unavailable') {
18092
+ if (widgetSignIn || (!token && options.onAuthRequired && client.desk.auth_mode !== 'external_sso' && client.desk.auth_mode !== 'external_unavailable')) {
17782
18093
  authenticating = true;
17783
18094
  authNotification = false;
17784
- const session = await options.onAuthRequired();
18095
+ const session = await (widgetSignIn ?? options.onAuthRequired());
17785
18096
  if (!alive(ownGeneration))
17786
18097
  return;
17787
18098
  const currentToken = await client.getSessionToken();
@@ -17802,6 +18113,11 @@ function mountHelpDeskForm(client, options) {
17802
18113
  attachments.element.hidden = false;
17803
18114
  subject.input.value = subjectText;
17804
18115
  description.input.value = body;
18116
+ if (options.widgetIdentity && session) {
18117
+ widgetCustomer = session.customer;
18118
+ renderWidgetIdentity();
18119
+ message('');
18120
+ }
17805
18121
  }
17806
18122
  if (!alive(ownGeneration))
17807
18123
  return;
@@ -17891,7 +18207,7 @@ function mountHelpDeskForm(client, options) {
17891
18207
  setState('submitting');
17892
18208
  if (!alive(ownGeneration))
17893
18209
  return;
17894
- send.textContent = 'Sending request';
18210
+ send.textContent = options.widgetIdentity ? 'Sending message' : 'Sending request';
17895
18211
  if (!uncertainSubmission) {
17896
18212
  const id = await ensureDraft(ownGeneration, token);
17897
18213
  if (!alive(ownGeneration) || !(await tokenFor(ownGeneration)))
@@ -17900,7 +18216,7 @@ function mountHelpDeskForm(client, options) {
17900
18216
  }
17901
18217
  attachments?.lock(true);
17902
18218
  ticketAttempted = true;
17903
- const ticket = await client.createTicket({ ...uncertainSubmission, attachments: [...uncertainSubmission.attachments] }, { expectedSessionToken: token });
18219
+ const ticket = await client.createTicket({ ...uncertainSubmission, attachments: [...uncertainSubmission.attachments], ...options.assistanceContext?.() }, { expectedSessionToken: token });
17904
18220
  if (!alive(ownGeneration) || !(await tokenFor(ownGeneration)))
17905
18221
  return;
17906
18222
  completed = true;
@@ -17909,7 +18225,7 @@ function mountHelpDeskForm(client, options) {
17909
18225
  if (!alive(ownGeneration))
17910
18226
  return;
17911
18227
  showDone(ticket, customer);
17912
- notify(options.onSuccess, ticket);
18228
+ notify$1(options.onSuccess, ticket);
17913
18229
  }
17914
18230
  catch (failure) {
17915
18231
  if (!alive(ownGeneration))
@@ -17950,8 +18266,8 @@ function mountHelpDeskForm(client, options) {
17950
18266
  setState(uncertainSubmission ? 'uncertain' : challenge ? 'verifying' : 'editing');
17951
18267
  if (!alive(ownGeneration))
17952
18268
  return;
17953
- send.textContent = uncertainSubmission ? 'Check submission' : challenge ? 'Verify and send request' : 'Send request';
17954
- notify(options.onError, error);
18269
+ send.textContent = uncertainSubmission ? 'Check submission' : challenge ? 'Verify and send request' : options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
18270
+ notify$1(options.onError, error);
17955
18271
  }
17956
18272
  finally {
17957
18273
  if (alive(ownGeneration)) {
@@ -17985,7 +18301,7 @@ function mountHelpDeskForm(client, options) {
17985
18301
  return;
17986
18302
  const error = failure instanceof Error ? failure : new Error('A new code could not be sent. Try again.');
17987
18303
  message(error instanceof SparkVaultError && error.statusCode === 429 ? 'Too many codes have been sent. Try again later.' : error.message, true);
17988
- notify(options.onError, error);
18304
+ notify$1(options.onError, error);
17989
18305
  }
17990
18306
  finally {
17991
18307
  if (alive(ownGeneration)) {
@@ -18016,7 +18332,7 @@ function mountHelpDeskForm(client, options) {
18016
18332
  /** The Cancel path: remove the form, then tell the host the customer closed it. */
18017
18333
  function dismiss() {
18018
18334
  controller.destroy();
18019
- notify(options.onCancel, undefined);
18335
+ notify$1(options.onCancel, undefined);
18020
18336
  }
18021
18337
  const controller = {
18022
18338
  destroy() {
@@ -18041,6 +18357,11 @@ function mountHelpDeskForm(client, options) {
18041
18357
  setState('editing');
18042
18358
  },
18043
18359
  getState: () => state,
18360
+ getComposition: safeComposition,
18361
+ resumeAfterAccess() {
18362
+ if (!destroyed && !pending && !completed && uncertainSubmission === null)
18363
+ message('');
18364
+ },
18044
18365
  requestDismiss() {
18045
18366
  if (destroyed)
18046
18367
  return;
@@ -18074,10 +18395,11 @@ function mountHelpDeskForm(client, options) {
18074
18395
  keepEditing.addEventListener('click', () => closeConfirm(true));
18075
18396
  discard.addEventListener('click', dismiss);
18076
18397
  form.addEventListener('submit', onSubmit);
18077
- notify(options.onStateChange, state);
18398
+ renderWidgetIdentity();
18399
+ notify$1(options.onStateChange, state);
18078
18400
  // Native company identity starts as the form opens, never from a Connect,
18079
18401
  // Allow, verification or submit gesture. Guest email is explicit desk policy.
18080
- if ((client.desk.auth_mode === 'external_sso' && client.hasIdentityProvider) || client.desk.auth_mode === 'external_unavailable') {
18402
+ if (!options.widgetIdentity && ((client.desk.auth_mode === 'external_sso' && client.hasIdentityProvider) || client.desk.auth_mode === 'external_unavailable')) {
18081
18403
  const ownGeneration = generation;
18082
18404
  nativeProofGeneration = ownGeneration;
18083
18405
  pending = true;
@@ -18105,7 +18427,7 @@ function mountHelpDeskForm(client, options) {
18105
18427
  if (!alive(ownGeneration))
18106
18428
  return;
18107
18429
  message(error.message, true);
18108
- notify(options.onError, error);
18430
+ notify$1(options.onError, error);
18109
18431
  }).finally(() => {
18110
18432
  if (nativeProofGeneration === ownGeneration)
18111
18433
  nativeProofGeneration = null;
@@ -18213,13 +18535,2492 @@ function openHelpDeskForm(client, options = {}) {
18213
18535
  return handle;
18214
18536
  }
18215
18537
 
18216
- class HelpDeskModule {
18217
- constructor(config) {
18218
- this.config = config;
18538
+ /** Dependency-free local search shared by the help center and embedded support. */
18539
+ const SEARCH_STOP_WORDS = new Set('a an and are as at be been but by can do does for from had has have how i if in is it its me my of on or our should so that the their them there these they this to was we were what when where which who why will with would you your'.split(' '));
18540
+ const SEARCH_FIELD_WEIGHTS = [160, 140, 80, 60, 45, 10];
18541
+ const SEARCH_MAX_QUERY_LENGTH = 300;
18542
+ const SEARCH_MAX_QUERY_TERMS = 12;
18543
+ const SEARCH_MAX_TYPO_LENGTH = 64;
18544
+ const RECOMMEND_STOP_WORDS = new Set('also am anymore around back because could did didnt doesnt dont else even getting get gets got hello help hey hi im into just like looking lot much need needing now please really something thank thanks trying tried try using want wanted whenever whether without working'.split(' '));
18545
+ const RECOMMEND_MAX_QUERY_LENGTH = 20000;
18546
+ const RECOMMEND_MAX_KNOWN_TERMS = 36;
18547
+ const RECOMMEND_MAX_UNKNOWN_TERMS = 12;
18548
+
18549
+ function searchTokens(value) {
18550
+ return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) || [];
18551
+ }
18552
+ function searchCompare(left, right) {
18553
+ return left < right ? -1 : left > right ? 1 : 0;
18554
+ }
18555
+ function searchLowerBound(values, target) {
18556
+ let lo = 0; let hi = values.length;
18557
+ while (lo < hi) { const mid = (lo + hi) >>> 1; if (values[mid] < target) lo = mid + 1; else hi = mid; }
18558
+ return lo;
18559
+ }
18560
+ /** One insertion, deletion, substitution or adjacent transposition; never edit distance two. */
18561
+ function searchOneEdit(left, right) {
18562
+ if (left === right) return false;
18563
+ if (Math.abs(left.length - right.length) > 1) return false;
18564
+ let i = 0;
18565
+ while (i < left.length && left[i] === right[i]) i++;
18566
+ if (left.length === right.length) {
18567
+ if (left.slice(i + 1) === right.slice(i + 1)) return true;
18568
+ return left[i] === right[i + 1] && left[i + 1] === right[i] && left.slice(i + 2) === right.slice(i + 2);
18569
+ }
18570
+ return left.length > right.length ? left.slice(i + 1) === right.slice(i) : left.slice(i) === right.slice(i + 1);
18571
+ }
18572
+
18573
+ /** Prepare normalization, vocabulary and weighted postings once after the index downloads. */
18574
+ function prepareSearchIndex(rows) {
18575
+ const postings = new Map();
18576
+ const entries = (Array.isArray(rows) ? rows : []).map((article, index) => {
18577
+ const keywords = typeof article.seo_keywords === 'string' ? article.seo_keywords : Array.isArray(article.seo_keywords) ? article.seo_keywords.filter(value => typeof value === 'string').join(' ') : '';
18578
+ const tokenFields = [article.title, article.seo_title, keywords, article.summary, article.category, article.text].map(searchTokens);
18579
+ tokenFields.forEach((tokens, field) => {
18580
+ for (const word of new Set(tokens)) {
18581
+ if (!postings.has(word)) postings.set(word, new Map());
18582
+ const docs = postings.get(word);
18583
+ docs.set(index, Math.max(docs.get(index) || 0, SEARCH_FIELD_WEIGHTS[field]));
18584
+ }
18585
+ });
18586
+ const fields = tokenFields.map(tokens => tokens.join(' '));
18587
+ return { article, fields, title: fields[0], categoryId: article.category_id ?? article.categoryId ?? null, tie: `${article.path || ''}\u0000${article.id || ''}`, index };
18588
+ });
18589
+ const vocabulary = [...postings.keys()].sort(searchCompare);
18590
+ // A single edit preserves either the first or last character. These buckets
18591
+ // avoid scanning the entire vocabulary for every typo, including transpositions.
18592
+ const typoBuckets = new Map();
18593
+ for (const word of vocabulary) {
18594
+ if (word.length < 3 || word.length > SEARCH_MAX_TYPO_LENGTH + 1) continue;
18595
+ for (const key of [`${word.length}:first:${word[0]}`, `${word.length}:last:${word.at(-1)}`]) {
18596
+ if (!typoBuckets.has(key)) typoBuckets.set(key, []);
18597
+ typoBuckets.get(key).push(word);
18219
18598
  }
18220
- /** Resolve a configured desk host and obtain its customer-only, headless API. */
18221
- connect(options) {
18222
- return HelpDeskClient.connect(this.config, options);
18599
+ }
18600
+ return { entries, postings, vocabulary, typoBuckets };
18601
+ }
18602
+
18603
+ function searchTermMatches(prepared, term, mode) {
18604
+ const matches = new Map();
18605
+ const append = (word, multiplier, typo, minimumWeight = 0) => {
18606
+ for (const [index, weight] of prepared.postings.get(word) || []) {
18607
+ if (weight < minimumWeight) continue;
18608
+ const score = Math.round(weight * multiplier);
18609
+ const previous = matches.get(index);
18610
+ if (!previous || score > previous.score || (score === previous.score && searchCompare(word, previous.word) < 0)) matches.set(index, { score, word, typo });
18611
+ }
18612
+ };
18613
+ append(term, 1, false);
18614
+ for (let i = searchLowerBound(prepared.vocabulary, term); i < prepared.vocabulary.length; i++) {
18615
+ const word = prepared.vocabulary[i];
18616
+ if (!word.startsWith(term)) break;
18617
+ if (word !== term) append(word, 0.75, false);
18618
+ }
18619
+ // Recover partial title/metadata words only when exact/prefix search failed.
18620
+ // Broad body substrings are intentionally excluded: "word" should recover a
18621
+ // Password article without matching every page mentioning it deep in its body.
18622
+ if (mode !== 'exact' && term.length >= 3) {
18623
+ for (const word of prepared.vocabulary) {
18624
+ if (word.includes(term) && !word.startsWith(term)) append(word, 0.5, false, SEARCH_FIELD_WEIGHTS[2]);
18625
+ }
18626
+ }
18627
+ if (mode === 'typo' && term.length >= 4 && term.length <= SEARCH_MAX_TYPO_LENGTH) {
18628
+ const candidates = new Set();
18629
+ for (let length = term.length - 1; length <= term.length + 1; length++) {
18630
+ for (const side of ['first', 'last']) {
18631
+ const character = side === 'first' ? term[0] : term.at(-1);
18632
+ for (const word of prepared.typoBuckets.get(`${length}:${side}:${character}`) || []) candidates.add(word);
18633
+ }
18634
+ }
18635
+ for (const word of candidates) if (searchOneEdit(term, word)) append(word, 0.35, true);
18636
+ }
18637
+ return matches;
18638
+ }
18639
+ function searchRank(prepared, terms, phrase, categoryId, mode) {
18640
+ const matches = terms.map(term => searchTermMatches(prepared, term, mode));
18641
+ if (matches.some(map => !map.size)) return [];
18642
+ const smallest = matches.reduce((left, right) => left.size <= right.size ? left : right);
18643
+ const results = [];
18644
+ for (const index of smallest.keys()) {
18645
+ const entry = prepared.entries[index];
18646
+ if (categoryId !== null && entry.categoryId !== categoryId) continue;
18647
+ const parts = matches.map(map => map.get(index));
18648
+ if (parts.some(part => !part)) continue;
18649
+ let score = parts.reduce((sum, part) => sum + part.score, 0);
18650
+ if (entry.title === phrase) score += 4000;
18651
+ else if (` ${entry.title} `.includes(` ${phrase} `)) score += 1500;
18652
+ if (entry.fields[1] === phrase) score += 3000;
18653
+ else if (` ${entry.fields[1]} `.includes(` ${phrase} `)) score += 1000;
18654
+ if (` ${entry.fields[3]} `.includes(` ${phrase} `)) score += 25;
18655
+ const typo = parts.some(part => part.typo);
18656
+ results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, entry });
18657
+ }
18658
+ results.sort((left, right) => right.score - left.score || searchCompare(left.entry.title, right.entry.title) || searchCompare(left.entry.tie, right.entry.tie) || left.entry.index - right.entry.index);
18659
+ return results;
18660
+ }
18661
+
18662
+ /** All query terms must match. Search falls back from exact/prefix to title substrings, then typos. */
18663
+ function searchKnowledgeBase(prepared, query, { limit = 20, offset = 0, categoryId = null } = {}) {
18664
+ const value = String(query ?? '').trim();
18665
+ if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0 };
18666
+ const raw = searchTokens(value);
18667
+ const meaningful = raw.filter(term => !SEARCH_STOP_WORDS.has(term));
18668
+ const terms = [...new Set(meaningful.length ? meaningful : raw)];
18669
+ if (!terms.length || terms.length > SEARCH_MAX_QUERY_TERMS) return { results: [], total: 0 };
18670
+ const phrase = terms.join(' ');
18671
+ let ranked = searchRank(prepared, terms, phrase, categoryId, 'exact');
18672
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'substring');
18673
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'typo');
18674
+ const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
18675
+ const size = Number.isSafeInteger(limit) && limit >= 0 ? limit : 20;
18676
+ return { results: ranked.slice(start, start + size).map(({ article, score, matchedTerms, typo }) => ({ article, score, matchedTerms, typo })), total: ranked.length };
18677
+ }
18678
+
18679
+ /** Select bounded, useful terms without making a long description an AND query. */
18680
+ function recommendationTerms(prepared, issue) {
18681
+ const terms = new Map();
18682
+ const raw = searchTokens(String(issue ?? '').slice(0, RECOMMEND_MAX_QUERY_LENGTH));
18683
+ for (const term of raw) {
18684
+ if (term.length < 2 || term.length > SEARCH_MAX_TYPO_LENGTH || SEARCH_STOP_WORDS.has(term) || RECOMMEND_STOP_WORDS.has(term)) continue;
18685
+ if (!terms.has(term)) terms.set(term, { term, frequency: 0, order: terms.size, documents: prepared.postings.get(term)?.size ?? 0 });
18686
+ terms.get(term).frequency++;
18687
+ }
18688
+ const values = [...terms.values()];
18689
+ // Rare indexed terms carry useful detail even when they occur after a long
18690
+ // introduction. A separate small budget retains prefixes and misspellings.
18691
+ const known = values.filter(value => value.documents).sort((a, b) => a.documents - b.documents || b.frequency - a.frequency || a.order - b.order).slice(0, RECOMMEND_MAX_KNOWN_TERMS);
18692
+ const unknown = values.filter(value => !value.documents).sort((a, b) => b.frequency - a.frequency || b.term.length - a.term.length || a.order - b.order).slice(0, RECOMMEND_MAX_UNKNOWN_TERMS);
18693
+ return [...known, ...unknown].sort((a, b) => a.order - b.order).map(value => value.term);
18694
+ }
18695
+
18696
+ /**
18697
+ * Recommend published answers for a paragraph using the same prepared postings,
18698
+ * normalization, field weights and bounded spelling recovery as normal search.
18699
+ * Unknown details do not veto an otherwise relevant answer. Coverage and field
18700
+ * strength keep incidental body mentions out of multi-word recommendations.
18701
+ */
18702
+ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
18703
+ const terms = recommendationTerms(prepared, issue);
18704
+ if (!terms.length) return { results: [], total: 0 };
18705
+ const candidates = new Map();
18706
+ const withinCategory = matches => categoryId === null ? matches : new Map([...matches].filter(([index]) => prepared.entries[index].categoryId === categoryId));
18707
+ let totalWeight = 0; let searchableTerms = 0;
18708
+ for (const term of terms) {
18709
+ let matches = withinCategory(searchTermMatches(prepared, term, 'exact'));
18710
+ if (!matches.size) matches = withinCategory(searchTermMatches(prepared, term, 'substring'));
18711
+ if (!matches.size) matches = withinCategory(searchTermMatches(prepared, term, 'typo'));
18712
+ if (!matches.size) continue;
18713
+ const weight = 1 + Math.log((prepared.entries.length + 1) / (matches.size + 1));
18714
+ totalWeight += weight; searchableTerms++;
18715
+ for (const [index, part] of matches) {
18716
+ if (!candidates.has(index)) candidates.set(index, { entry: prepared.entries[index], score: 0, matchedTerms: [], count: 0, weight: 0, strongest: 0, typo: false });
18717
+ const hit = candidates.get(index);
18718
+ hit.score += part.score * weight; hit.weight += weight; hit.count++;
18719
+ hit.strongest = Math.max(hit.strongest, part.score); hit.typo ||= part.typo;
18720
+ hit.matchedTerms.push(part.word);
18721
+ }
18722
+ }
18723
+ const ranked = [];
18724
+ for (const hit of candidates.values()) {
18725
+ const coverage = hit.weight / totalWeight;
18726
+ const strong = hit.strongest >= 50;
18727
+ // One clear keyword is useful. Within a paragraph, a weak body-only match
18728
+ // needs corroboration; category names alone must not recommend every page.
18729
+ if (!strong && hit.count < 2 && !(terms.length === 1 && hit.strongest <= SEARCH_FIELD_WEIGHTS[5])) continue;
18730
+ if (coverage < (strong ? 0.25 : 0.5)) continue;
18731
+ const score = Math.round(hit.score + coverage * 100 + hit.count / searchableTerms * 50);
18732
+ ranked.push({ article: hit.entry.article, score, matchedTerms: [...new Set(hit.matchedTerms)], typo: hit.typo, coverage, entry: hit.entry });
18733
+ }
18734
+ ranked.sort((a, b) => b.score - a.score || b.coverage - a.coverage || searchCompare(a.entry.title, b.entry.title) || searchCompare(a.entry.tie, b.entry.tie) || a.entry.index - b.entry.index);
18735
+ const size = Number.isSafeInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 5;
18736
+ return { results: ranked.slice(0, size).map(({ article, score, matchedTerms, typo, coverage }) => ({ article, score, matchedTerms, typo, coverage })), total: ranked.length };
18737
+ }
18738
+
18739
+ /** The emitted module uses exactly the tested engine, with no runtime dependencies. */
18740
+ [
18741
+ `const SEARCH_STOP_WORDS=new Set(${JSON.stringify([...SEARCH_STOP_WORDS])});`,
18742
+ `const SEARCH_FIELD_WEIGHTS=${JSON.stringify(SEARCH_FIELD_WEIGHTS)};`,
18743
+ `const SEARCH_MAX_QUERY_LENGTH=${SEARCH_MAX_QUERY_LENGTH};`,
18744
+ `const SEARCH_MAX_QUERY_TERMS=${SEARCH_MAX_QUERY_TERMS};`,
18745
+ `const SEARCH_MAX_TYPO_LENGTH=${SEARCH_MAX_TYPO_LENGTH};`,
18746
+ `const RECOMMEND_STOP_WORDS=new Set(${JSON.stringify([...RECOMMEND_STOP_WORDS])});`,
18747
+ `const RECOMMEND_MAX_QUERY_LENGTH=${RECOMMEND_MAX_QUERY_LENGTH};`,
18748
+ `const RECOMMEND_MAX_KNOWN_TERMS=${RECOMMEND_MAX_KNOWN_TERMS};`,
18749
+ `const RECOMMEND_MAX_UNKNOWN_TERMS=${RECOMMEND_MAX_UNKNOWN_TERMS};`,
18750
+ searchTokens, searchCompare, searchLowerBound, searchOneEdit, prepareSearchIndex,
18751
+ searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, recommendKnowledgeBase,
18752
+ ].map(value => typeof value === 'function' ? value.toString() : value).join('\n') + '\nexport { prepareSearchIndex, searchKnowledgeBase, recommendKnowledgeBase };\n';
18753
+
18754
+ /** One published-KB transport and shared local search engine for support entry points. */
18755
+ const invalid = () => new SparkVaultError('The help center returned an invalid answer. Try again.', 'KB_INVALID_RESPONSE');
18756
+ const changed = () => new SparkVaultError('The help center changed. Search again to see current answers.', 'KB_PUBLICATION_CHANGED', 409);
18757
+ const validPath = (value) => typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') &&
18758
+ !Array.from(value).some(character => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127 || character === '\\') &&
18759
+ !value.split(/[/?#]/).some(part => part === '.' || part === '..');
18760
+ const assetPath = (value) => validPath(value) && /^\/_kb\/assets\/[a-zA-Z0-9_./-]+$/.test(value);
18761
+ class HelpDeskKnowledgeBaseClient {
18762
+ constructor(sdkConfig, deskId) {
18763
+ this.sdkConfig = sdkConfig;
18764
+ this.deskId = deskId;
18765
+ this.grant = null;
18766
+ this.grantDeadline = null;
18767
+ this.config = null;
18768
+ this.index = null;
18769
+ this.indexPending = null;
18770
+ this.objectUrls = new Set();
18771
+ this.generation = 0;
18772
+ this.readerRevision = 0;
18773
+ this.readerDocument = null;
18774
+ this.activeMedia = null;
18775
+ this.destroyed = false;
18776
+ this.close = new AbortController();
18777
+ if (!isResourceIdOf('account', deskId))
18778
+ throw new ValidationError('deskId must be a Help Desk account');
18779
+ }
18780
+ getAccessHeaders() {
18781
+ if (this.grantDeadline !== null && this.grantDeadline <= Date.now())
18782
+ this.clearAccess();
18783
+ return this.grant ? { Authorization: `Bearer ${this.grant}` } : {};
18784
+ }
18785
+ async request(suffix, options = {}) {
18786
+ if (this.destroyed)
18787
+ throw new SparkVaultError('This support session has closed.', 'KB_CLOSED');
18788
+ const route = typeof suffix === 'object'
18789
+ ? apiPath `/v1/hd/desks/${this.deskId}/kb/widget/documents/${suffix.document}`
18790
+ : apiPath `/v1/hd/desks/${this.deskId}/kb/widget/${suffix}`;
18791
+ const url = new URL(`${this.sdkConfig.apiBaseUrl}${route}`);
18792
+ if (options.release)
18793
+ url.searchParams.set('release_id', options.release);
18794
+ if (options.path)
18795
+ url.searchParams.set('path', options.path);
18796
+ if (options.cursor)
18797
+ url.searchParams.set('cursor', options.cursor);
18798
+ if (options.offset !== undefined)
18799
+ url.searchParams.set('offset', String(options.offset));
18800
+ const accessHeaders = this.getAccessHeaders();
18801
+ const generation = this.generation;
18802
+ return exchange(url.href, { method: options.body !== undefined ? 'POST' : 'GET', credentials: 'omit', redirect: 'error',
18803
+ headers: { Accept: 'application/json', ...accessHeaders,
18804
+ ...(options.body !== undefined && { 'Content-Type': 'application/json' }) },
18805
+ ...(options.body !== undefined && { body: JSON.stringify(options.body) }) }, {
18806
+ timeoutMs: this.sdkConfig.timeout, closeSignal: options.signal ?? this.close.signal,
18807
+ read: async (response) => {
18808
+ if (!response.ok) {
18809
+ const failure = await readApiFailure(response);
18810
+ if (['KB_ACCESS_REQUIRED', 'KB_PUBLICATION_CHANGED', 'KB_IP_RESTRICTED', 'KB_UNAVAILABLE'].includes(failure.code))
18811
+ this.clearAccess();
18812
+ throw new SparkVaultError(failure.message, failure.code, failure.status, failure.details, failure.retryAfterMs, failure.code);
18813
+ }
18814
+ if (generation !== this.generation)
18815
+ throw changed();
18816
+ const value = await response.json();
18817
+ return (value !== null && typeof value === 'object' && 'data' in value ? value.data : value);
18818
+ },
18819
+ fail: failure => failure === 'timeout' ? new TimeoutError() : new NetworkError('The help center could not be reached. Try again.')
18820
+ });
18821
+ }
18822
+ /** Fresh config validates publication and access before a cached index is reused. */
18823
+ async load() {
18824
+ const value = await this.request('config');
18825
+ if (typeof value?.available !== 'boolean' || typeof value.authorized !== 'boolean' || typeof value.search_enabled !== 'boolean' ||
18826
+ !['public', 'password', 'ip_allowlist', 'identity'].includes(value.access?.mode) ||
18827
+ (value.available && (!/^[a-f0-9]{64}$/.test(value.release_id ?? '') || !this.canonicalOrigin(value.canonical_origin))))
18828
+ throw invalid();
18829
+ if (this.config?.release_id !== value.release_id || !value.authorized)
18830
+ this.clearContent();
18831
+ this.config = value;
18832
+ return value;
18833
+ }
18834
+ canonicalOrigin(value) {
18835
+ try {
18836
+ const url = new URL(String(value));
18837
+ return url.protocol === 'https:' && url.origin === value && !url.username && !url.password && !url.port;
18838
+ }
18839
+ catch {
18840
+ return false;
18841
+ }
18842
+ }
18843
+ async unlock(options) {
18844
+ const current = this.config ?? await this.load();
18845
+ const answer = await this.request('access', {
18846
+ body: { ...options, release_id: current.release_id }
18847
+ });
18848
+ if (!answer || (answer.token !== null && (typeof answer.token !== 'string' || !/^(?:hdkbt_[A-Za-z0-9_-]{43}|hdkbw_\d{10,12}\.[a-f0-9]{64})$/.test(answer.token))))
18849
+ throw invalid();
18850
+ if (answer.token && (!Number.isSafeInteger(answer.ttl_seconds) || (answer.ttl_seconds ?? 0) <= 0))
18851
+ throw invalid();
18852
+ this.clearAccess();
18853
+ this.grant = answer.token;
18854
+ this.grantDeadline = answer.ttl_seconds ? Date.now() + answer.ttl_seconds * 1000 : null;
18855
+ return this.load();
18856
+ }
18857
+ async currentIndex() {
18858
+ const config = await this.load();
18859
+ if (!config.available)
18860
+ throw new SparkVaultError('This help center is unavailable. Contact support to continue.', 'KB_UNAVAILABLE', 404);
18861
+ if (!config.authorized)
18862
+ throw new SparkVaultError(config.access.mode === 'ip_allowlist' ? 'Connect to an approved network to read this help center.' : 'Sign in to this help center to read its answers.', config.access.mode === 'ip_allowlist' ? 'KB_IP_RESTRICTED' : 'KB_ACCESS_REQUIRED', config.access.mode === 'ip_allowlist' ? 403 : 401);
18863
+ if (!config.search_enabled)
18864
+ throw new SparkVaultError('Search is not enabled for this help center.', 'KB_SEARCH_UNAVAILABLE', 404);
18865
+ if (this.index?.release_id === config.release_id)
18866
+ return this.index;
18867
+ if (this.indexPending)
18868
+ return this.indexPending;
18869
+ const release = config.release_id;
18870
+ const generation = this.generation;
18871
+ const pending = (async () => {
18872
+ const articles = [];
18873
+ const seen = new Set();
18874
+ let cursor;
18875
+ do {
18876
+ const value = await this.request('index', { release, cursor });
18877
+ if (!value || generation !== this.generation || value.release_id !== release || value.canonical_origin !== config.canonical_origin ||
18878
+ !Array.isArray(value.articles) || articles.length + value.articles.length > 4000 || value.articles.some(row => typeof row.id !== 'string' || row.id.length > 256 ||
18879
+ typeof row.title !== 'string' || !validPath(row.path)))
18880
+ throw invalid();
18881
+ articles.push(...value.articles);
18882
+ const next = value.next_cursor;
18883
+ if (next !== undefined && next !== null && (typeof next !== 'string' || !new RegExp(`^${release}\\.[0-9]{1,6}$`).test(next) || seen.has(next) || seen.size >= 32))
18884
+ throw invalid();
18885
+ if (next)
18886
+ seen.add(next);
18887
+ cursor = next ?? undefined;
18888
+ } while (cursor);
18889
+ const held = { release_id: release, canonical_origin: config.canonical_origin, articles, prepared: prepareSearchIndex(articles) };
18890
+ this.index = held;
18891
+ return held;
18892
+ })();
18893
+ this.indexPending = pending;
18894
+ try {
18895
+ return await pending;
18896
+ }
18897
+ finally {
18898
+ if (this.indexPending === pending)
18899
+ this.indexPending = null;
18900
+ }
18901
+ }
18902
+ result(row, index) {
18903
+ return { id: row.id, kind: row.kind ?? (row.path.startsWith('/faq/') && row.path.includes('#') ? 'faq' : 'article'),
18904
+ title: row.title, summary: String(row.summary ?? ''), category: String(row.category ?? ''), path: row.path,
18905
+ canonical_url: new URL(row.path, index.canonical_origin).href, release_id: index.release_id };
18906
+ }
18907
+ async search(issue) {
18908
+ if (typeof issue !== 'string' || !issue.trim())
18909
+ throw new ValidationError('Describe what you need help with.');
18910
+ const index = await this.currentIndex();
18911
+ const found = recommendKnowledgeBase(index.prepared, issue, { limit: 5 });
18912
+ return { release_id: index.release_id, total: found.total, results: found.results.map(hit => this.result(hit.article, index)) };
18913
+ }
18914
+ async resolveLink(value) {
18915
+ const index = await this.currentIndex();
18916
+ let url;
18917
+ try {
18918
+ url = new URL(value, index.canonical_origin);
18919
+ }
18920
+ catch {
18921
+ return null;
18922
+ }
18923
+ if (url.origin !== index.canonical_origin || url.username || url.password)
18924
+ return null;
18925
+ const path = url.pathname + url.hash;
18926
+ const row = index.articles.find(article => article.path === path || (!url.hash && article.path === url.pathname));
18927
+ return row ? this.result(row, index) : null;
18928
+ }
18929
+ async read(result) {
18930
+ const config = await this.load();
18931
+ if (config.release_id !== result.release_id)
18932
+ throw changed();
18933
+ if (!config.authorized)
18934
+ throw new SparkVaultError('Sign in to this help center to read its answers.', config.access.mode === 'ip_allowlist' ? 'KB_IP_RESTRICTED' : 'KB_ACCESS_REQUIRED', config.access.mode === 'ip_allowlist' ? 403 : 401);
18935
+ const readerRevision = ++this.readerRevision;
18936
+ const value = await this.request({ document: result.id }, { release: result.release_id });
18937
+ if (value?.version !== 1 || value.id !== result.id || value.release_id !== result.release_id || value.kind !== result.kind ||
18938
+ value.canonical_url !== result.canonical_url || typeof value.body_html !== 'string' || value.body_html.length > 5 * 1024 ** 2 ||
18939
+ !Array.isArray(value.assets) || value.assets.some(path => !assetPath(path)))
18940
+ throw invalid();
18941
+ if (readerRevision !== this.readerRevision)
18942
+ throw changed();
18943
+ const body_html = sanitizeReader(value.body_html, value.canonical_url, new Set(value.assets));
18944
+ this.activeMedia?.abort();
18945
+ this.activeMedia = null;
18946
+ for (const url of this.objectUrls)
18947
+ URL.revokeObjectURL(url);
18948
+ this.objectUrls.clear();
18949
+ this.readerDocument = { ...value, body_html };
18950
+ return this.readerDocument;
18951
+ }
18952
+ /** Paint article text first; hydrate only approved media without replacing the reader DOM. */
18953
+ hydrateAssets(document, callbacks) {
18954
+ if (this.destroyed || this.readerDocument?.id !== document.id || this.readerDocument.release_id !== document.release_id)
18955
+ return () => { };
18956
+ this.activeMedia?.abort();
18957
+ const close = new AbortController();
18958
+ this.activeMedia = close;
18959
+ const readerRevision = this.readerRevision;
18960
+ const generation = this.generation;
18961
+ const urls = new Set();
18962
+ const paths = [...new Set(this.readerDocument.assets)];
18963
+ let cancelled = false;
18964
+ let bytes = 0;
18965
+ const active = () => !cancelled && !close.signal.aborted && generation === this.generation && readerRevision === this.readerRevision;
18966
+ void (async () => {
18967
+ for (let offset = 0; offset < paths.length && active(); offset += 4) {
18968
+ await Promise.all(paths.slice(offset, offset + 4).map(async (path, index) => {
18969
+ try {
18970
+ if (offset + index >= 64 || bytes >= 32 * 1024 ** 2)
18971
+ throw new SparkVaultError('Open the full answer to view all its images.', 'KB_READER_UNAVAILABLE');
18972
+ const blob = await this.readAsset(document.release_id, path, close.signal);
18973
+ bytes += blob.size;
18974
+ if (bytes > 32 * 1024 ** 2)
18975
+ throw new SparkVaultError('Open the full answer to view all its images.', 'KB_READER_UNAVAILABLE');
18976
+ if (!active())
18977
+ return;
18978
+ const url = URL.createObjectURL(blob);
18979
+ this.objectUrls.add(url);
18980
+ urls.add(url);
18981
+ callbacks.onAsset(path, url);
18982
+ }
18983
+ catch (error) {
18984
+ if (!cancelled && !this.destroyed)
18985
+ callbacks.onError?.(path, error);
18986
+ }
18987
+ }));
18988
+ }
18989
+ })();
18990
+ return () => {
18991
+ cancelled = true;
18992
+ close.abort();
18993
+ for (const url of urls) {
18994
+ URL.revokeObjectURL(url);
18995
+ this.objectUrls.delete(url);
18996
+ }
18997
+ if (this.activeMedia === close)
18998
+ this.activeMedia = null;
18999
+ };
19000
+ }
19001
+ async readAsset(release, path, signal) {
19002
+ const chunks = [];
19003
+ let offset = 0;
19004
+ let size = null;
19005
+ let contentType = null;
19006
+ for (let page = 0; page < 21; page++) {
19007
+ const value = await this.request('asset', { release, path, offset, signal });
19008
+ if (!value || !Number.isSafeInteger(value.total_size) || value.total_size < 0 || value.total_size > 10 * 1024 ** 2 || value.offset !== offset ||
19009
+ (size !== null && size !== value.total_size) || (contentType !== null && contentType !== value.content_type) ||
19010
+ !/^image\/(?:png|jpeg|gif|webp|avif|svg\+xml)$/.test(value.content_type) || typeof value.data !== 'string' ||
19011
+ value.data.length > 700000 || value.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value.data))
19012
+ throw invalid();
19013
+ size = value.total_size;
19014
+ contentType = value.content_type;
19015
+ let text;
19016
+ try {
19017
+ text = globalThis.atob(value.data);
19018
+ }
19019
+ catch {
19020
+ throw invalid();
19021
+ }
19022
+ if (text.length > 512 * 1024 || offset + text.length > size)
19023
+ throw invalid();
19024
+ const bytes = new Uint8Array(text.length);
19025
+ for (let i = 0; i < text.length; i++)
19026
+ bytes[i] = text.charCodeAt(i);
19027
+ chunks.push(bytes);
19028
+ offset += bytes.byteLength;
19029
+ if (value.next_offset === null) {
19030
+ if (offset !== size)
19031
+ throw invalid();
19032
+ return new Blob(chunks, { type: contentType });
19033
+ }
19034
+ if (!bytes.byteLength || value.next_offset !== offset || offset >= size)
19035
+ throw invalid();
19036
+ }
19037
+ throw invalid();
19038
+ }
19039
+ clearContent() {
19040
+ this.generation++;
19041
+ this.readerRevision++;
19042
+ this.readerDocument = null;
19043
+ this.activeMedia?.abort();
19044
+ this.activeMedia = null;
19045
+ this.index = null;
19046
+ this.indexPending = null;
19047
+ for (const url of this.objectUrls)
19048
+ URL.revokeObjectURL(url);
19049
+ this.objectUrls.clear();
19050
+ }
19051
+ clearAccess() {
19052
+ this.grant = null;
19053
+ this.grantDeadline = null;
19054
+ this.config = null;
19055
+ this.clearContent();
19056
+ }
19057
+ destroy() { this.destroyed = true; this.close.abort(); this.clearAccess(); }
19058
+ }
19059
+ /** Defense in depth: a reader can never run theme HTML or fetch unapproved image URLs. */
19060
+ function sanitizeReader(html, canonical, assets) {
19061
+ if (typeof globalThis.document === 'undefined')
19062
+ throw new SparkVaultError('Open this answer in the help center to read it.', 'KB_READER_UNAVAILABLE');
19063
+ // Template contents stay inert, including image/iframe requests, until the
19064
+ // sanitized result is mounted. DOMParser documents can load remote media.
19065
+ const document = globalThis.document;
19066
+ const template = document.createElement('template');
19067
+ template.innerHTML = html;
19068
+ const tags = new Set('p h1 h2 h3 h4 h5 h6 ul ol li blockquote pre code em strong del s hr br table thead tbody tr th td figure figcaption img a div span details summary'.split(' '));
19069
+ for (const element of [...template.content.querySelectorAll('*')]) {
19070
+ if (!tags.has(element.localName)) {
19071
+ element.remove();
19072
+ continue;
19073
+ }
19074
+ const source = element.getAttribute('src');
19075
+ const href = element.getAttribute('href');
19076
+ for (const attribute of [...element.attributes]) {
19077
+ if (!['class', 'id', 'alt', 'title', 'width', 'height', 'colspan', 'rowspan', 'start', 'aria-level'].includes(attribute.name))
19078
+ element.removeAttribute(attribute.name);
19079
+ }
19080
+ if (element.localName === 'img') {
19081
+ if (!source || !assets.has(source)) {
19082
+ const fallback = document.createElement('span');
19083
+ fallback.textContent = element.getAttribute('alt') || 'Image unavailable';
19084
+ element.replaceWith(fallback);
19085
+ continue;
19086
+ }
19087
+ element.setAttribute('data-kb-asset', source);
19088
+ element.setAttribute('data-kb-image-state', 'loading');
19089
+ element.setAttribute('loading', 'lazy');
19090
+ element.setAttribute('decoding', 'async');
19091
+ }
19092
+ if (element.localName === 'a' && href) {
19093
+ try {
19094
+ const url = new URL(href, canonical);
19095
+ if (!['https:', 'http:', 'mailto:', 'tel:'].includes(url.protocol) || url.username || url.password)
19096
+ continue;
19097
+ element.setAttribute('href', href.startsWith('#') ? href : url.href);
19098
+ if (!href.startsWith('#')) {
19099
+ element.setAttribute('target', '_blank');
19100
+ element.setAttribute('rel', 'noopener noreferrer');
19101
+ }
19102
+ }
19103
+ catch { /* Keep the readable link text without an unsafe destination. */ }
19104
+ }
19105
+ }
19106
+ return template.innerHTML;
19107
+ }
19108
+
19109
+ let sequence$2 = 0;
19110
+ const interactionId = () => `${Date.now()}-${++sequence$2}`;
19111
+ function createSupportAnalytics({ deskId, post }) {
19112
+ const base = `/hd/desks/${encodeURIComponent(deskId)}/support`;
19113
+ let disposed = false;
19114
+ let visitor = null;
19115
+ // The same IDs are retried after a lost response; neither attempts nor outcomes multiply.
19116
+ async function send(path, body) {
19117
+ try {
19118
+ return await post(path, body);
19119
+ }
19120
+ catch (error) {
19121
+ if (disposed)
19122
+ throw error;
19123
+ return post(path, body);
19124
+ }
19125
+ }
19126
+ function getVisitor() {
19127
+ if (!visitor) {
19128
+ visitor = send(`${base}/visitor`, {}).then((answer) => {
19129
+ if (!/^[a-f0-9]{64}$/.test(answer.visitor_id))
19130
+ throw new Error('Invalid support visitor');
19131
+ return answer;
19132
+ }).catch((error) => { visitor = null; throw error; });
19133
+ }
19134
+ return visitor;
19135
+ }
19136
+ async function start(options) {
19137
+ if (disposed)
19138
+ return null;
19139
+ const attemptId = interactionId();
19140
+ try {
19141
+ const active = await getVisitor();
19142
+ if (disposed)
19143
+ return null;
19144
+ await send(`${base}/attempts`, {
19145
+ visitor_id: active.visitor_id, attempt_id: attemptId, availability: options.availability,
19146
+ ...(options.availability === 'available' && { release_id: options.releaseId, result_count: options.resultCount }),
19147
+ });
19148
+ if (disposed)
19149
+ return null;
19150
+ let queue = Promise.resolve();
19151
+ let terminal = false;
19152
+ let opened = false;
19153
+ const context = { assistance_attempt_id: attemptId, assistance_visitor_id: active.visitor_id };
19154
+ const emit = (fields) => {
19155
+ const body = { visitor_id: active.visitor_id, event_id: interactionId(), ...fields };
19156
+ queue = queue.then(async () => {
19157
+ if (!disposed)
19158
+ await send(`${base}/attempts/${encodeURIComponent(attemptId)}/events`, body);
19159
+ }).catch(() => { });
19160
+ };
19161
+ return {
19162
+ articleOpened(articleId, releaseId) {
19163
+ if (disposed || terminal || options.availability !== 'available')
19164
+ return;
19165
+ opened = true;
19166
+ emit({ type: 'article_opened', article_id: articleId, release_id: releaseId ?? options.releaseId });
19167
+ },
19168
+ solved() {
19169
+ if (disposed || terminal || !opened)
19170
+ return;
19171
+ terminal = true;
19172
+ emit({ type: 'solved' });
19173
+ },
19174
+ contactRequested(reason) {
19175
+ if (disposed || terminal || (options.availability === 'available' && !reason))
19176
+ return;
19177
+ terminal = true;
19178
+ emit({ type: 'contact_requested', ...(options.availability === 'available' && { reason }) });
19179
+ },
19180
+ ticketContext() { return disposed ? undefined : { ...context }; },
19181
+ };
19182
+ }
19183
+ catch {
19184
+ visitor = null;
19185
+ return null;
19186
+ }
19187
+ }
19188
+ return { start, dispose: () => { disposed = true; visitor = null; } };
19189
+ }
19190
+
19191
+ let launcherSequence = 0;
19192
+ /** A convenience path only: it never owns a second support flow. */
19193
+ function createSupportLauncher(options, open) {
19194
+ const button = document.createElement('button');
19195
+ button.type = 'button';
19196
+ button.className = 'sv-support-launcher';
19197
+ button.id = `sv-support-launcher-${++launcherSequence}`;
19198
+ button.setAttribute('aria-label', options.label || 'Open support');
19199
+ button.setAttribute('aria-haspopup', 'dialog');
19200
+ button.setAttribute('aria-expanded', 'false');
19201
+ const offset = (value, fallback) => typeof value === 'number' && Number.isFinite(value) ? Math.min(240, Math.max(12, value)) : fallback;
19202
+ button.style.cssText = `position:fixed;right:calc(${offset(options.right, 24)}px + env(safe-area-inset-right,0px));bottom:calc(${offset(options.bottom, 24)}px + env(safe-area-inset-bottom,0px));z-index:2147482800;width:56px;height:56px;border-radius:50%;border:1px solid ${withAlpha(DS.white, .22)};background:${DS.slate900};color:${DS.white};box-shadow:${DS.shadowPopover};display:grid;place-items:center;cursor:pointer;padding:0;overflow:hidden;`;
19203
+ if (options.imageUrl) {
19204
+ let url;
19205
+ try {
19206
+ url = new URL(options.imageUrl);
19207
+ }
19208
+ catch {
19209
+ throw new ValidationError('launcher.imageUrl must be an HTTPS URL');
19210
+ }
19211
+ if (url.protocol !== 'https:' || url.username || url.password)
19212
+ throw new ValidationError('launcher.imageUrl must be an HTTPS URL');
19213
+ const image = document.createElement('img');
19214
+ image.src = url.href;
19215
+ image.alt = '';
19216
+ image.style.cssText = 'width:100%;height:100%;object-fit:cover';
19217
+ image.referrerPolicy = 'no-referrer';
19218
+ image.addEventListener('error', () => { image.remove(); button.textContent = '?'; }, { once: true });
19219
+ button.append(image);
19220
+ }
19221
+ else {
19222
+ const mark = document.createElement('span');
19223
+ mark.setAttribute('aria-hidden', 'true');
19224
+ mark.textContent = '?';
19225
+ mark.style.cssText = 'display:grid;place-items:center;width:26px;height:26px;border:1.8px solid currentColor;border-radius:50%;font:600 20px/1 system-ui,sans-serif';
19226
+ button.append(mark);
19227
+ }
19228
+ button.addEventListener('click', open);
19229
+ document.body.append(button);
19230
+ return {
19231
+ setExpanded(expanded) { button.setAttribute('aria-expanded', String(expanded)); },
19232
+ destroy() { button.removeEventListener('click', open); button.remove(); },
19233
+ };
19234
+ }
19235
+
19236
+ /** The support journey's only skin. Customer content stays in the product register. */
19237
+ function injectHelpDeskSupportStyles() {
19238
+ if (document.getElementById('sparkvault-help-desk-support-styles'))
19239
+ return;
19240
+ const style = document.createElement('style');
19241
+ style.id = 'sparkvault-help-desk-support-styles';
19242
+ style.textContent = `
19243
+ .svhs-panel,.svhs-panel *{box-sizing:border-box}
19244
+ .svhs-panel{position:fixed;right:calc(var(--svhs-right,24px) + env(safe-area-inset-right,0px));bottom:calc(var(--svhs-bottom,96px) + env(safe-area-inset-bottom,0px));z-index:2147482900;width:408px;height:438px;max-width:calc(100vw - 32px);max-height:calc(100dvh - var(--svhs-bottom,96px) - 24px);display:flex;flex-direction:column;overflow:hidden;border:1px solid ${DS.slate200};border-radius:16px;background:${DS.white};color:${DS.slate900};font:400 15px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',sans-serif;text-align:left;box-shadow:${DS.shadowPopover};transform-origin:bottom right;transition:width 180ms cubic-bezier(.2,0,0,1),height 180ms cubic-bezier(.2,0,0,1)}
19245
+ .svhs-panel[hidden],.svhs-panel [hidden]{display:none!important}
19246
+ .svhs-panel[data-stage=results]{height:680px}
19247
+ .svhs-panel[data-stage=article]{width:704px;height:700px}
19248
+ .svhs-panel[data-stage=feedback]{height:358px}
19249
+ .svhs-panel[data-stage=contact]{height:720px}
19250
+ .svhs-panel[data-stage=receipt]{height:430px}
19251
+ .svhs-panel button,.svhs-panel input,.svhs-panel textarea{font:inherit;letter-spacing:normal;text-transform:none}
19252
+ .svhs-panel button,.svhs-panel a{touch-action:manipulation;-webkit-tap-highlight-color:transparent}
19253
+ .svhs-panel button{appearance:none;cursor:pointer;margin:0}
19254
+ .svhs-panel button:active{transform:translateY(1px)}
19255
+ .svhs-panel button:focus-visible,.svhs-panel a:focus-visible,.svhs-panel input:focus-visible,.svhs-panel textarea:focus-visible{outline:2px solid ${DS.action};outline-offset:3px}
19256
+ .svhs-panel svg{display:block;width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex:none;pointer-events:none}
19257
+ .svhs-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:68px;flex:none;padding:12px 14px 12px 24px;border-bottom:1px solid ${DS.slate100}}
19258
+ .svhs-desk-name{font-size:14px;font-weight:600;line-height:1.35;color:${DS.slate600};overflow-wrap:anywhere;min-width:0}
19259
+ .svhs-toolbar-actions{display:flex;align-items:center;gap:4px;margin-left:auto;flex:none}
19260
+ .svhs-identity-notice{display:flex;align-items:center;justify-content:space-between;gap:8px;flex:none;padding:8px 24px;border-bottom:1px solid ${DS.slate200};background:${DS.slate50}}
19261
+ .svhs-identity-notice .svhs-status{margin:0;font-size:13px}
19262
+ .svhs-identity-notice .svhs-text-button{flex:none;font-size:13px!important}
19263
+ .svhs-icon-button{display:grid;place-items:center;width:40px;height:40px;flex:none;padding:0;border:0;border-radius:6px;background:transparent;color:${DS.slate500};text-decoration:none}
19264
+ .svhs-icon-button:hover{background:${DS.slate100};color:${DS.slate900}}
19265
+ .svhs-back{display:flex;align-items:center;gap:4px;flex:none;min-height:40px;margin-left:-10px!important;padding:8px;border:0;border-radius:6px;background:transparent;color:${DS.slate600};font-size:14px!important;font-weight:500!important;line-height:1.4}
19266
+ .svhs-back:hover{background:${DS.slate50}}
19267
+ .svhs-back:disabled{background:transparent;color:${DS.slate500};cursor:default;transform:none}
19268
+ .svhs-screen{display:flex;flex-direction:column;min-height:0;flex:1}
19269
+ .svhs-scroll{padding:26px 24px;overflow:auto;overscroll-behavior:contain;min-height:0;flex:1;scrollbar-gutter:stable}
19270
+ .svhs-heading{margin:0 0 9px;padding:0;color:${DS.slate900};font-size:23px;font-weight:600;line-height:1.25;letter-spacing:-.7px;overflow-wrap:anywhere}
19271
+ .svhs-heading:focus,.svhs-article-title:focus{outline:none}
19272
+ .svhs-copy{margin:0 0 20px;color:${DS.slate500};font-size:14px;line-height:1.55}
19273
+ .svhs-label{display:block;margin:0 0 7px;font-size:13px;font-weight:600;color:${DS.slate600}}
19274
+ .svhs-issue{display:block;width:100%;min-height:116px;max-height:200px;resize:none;overflow-y:auto;border:1px solid ${DS.slate300};border-radius:6px;padding:11px 12px;background:${DS.white};color:${DS.slate900};font-size:16px!important;line-height:1.5!important;box-shadow:none}
19275
+ .svhs-issue::placeholder{color:${DS.slate500};opacity:1}
19276
+ .svhs-issue:focus{border-color:${DS.action}}
19277
+ .svhs-primary,.svhs-secondary{display:flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:10px 16px;border:1px solid transparent;border-radius:6px;font-size:14px!important;font-weight:600!important;line-height:1.4!important;text-decoration:none;transition:background 120ms cubic-bezier(.2,0,0,1)}
19278
+ .svhs-primary{background:${DS.action};color:${DS.white}}
19279
+ .svhs-primary:hover{background:${DS.actionHover}}
19280
+ .svhs-primary[aria-disabled=true]{cursor:progress}
19281
+ .svhs-secondary{border-color:${DS.slate300};background:${DS.white};color:${DS.slate600}}
19282
+ .svhs-secondary:hover{background:${DS.slate50}}
19283
+ .svhs-text-button{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:9px 4px;border:0;border-radius:6px;background:transparent;color:${DS.action};font-size:14px!important;line-height:1.4!important;text-decoration:none}
19284
+ .svhs-text-button:hover{text-decoration:underline}
19285
+ .svhs-full{width:100%}
19286
+ .svhs-bottom{padding:16px 24px 18px;flex:none;border-top:1px solid ${DS.slate100}}
19287
+ .svhs-start-bottom{display:flex;flex-direction:column;align-items:center;gap:6px;padding-top:0;border-top:0}
19288
+ .svhs-start-bottom .svhs-primary{width:100%}
19289
+ .svhs-query{display:flex;align-items:flex-start;gap:12px;margin:0 0 15px;padding:0 0 18px;border-bottom:1px solid ${DS.slate100}}
19290
+ .svhs-query-text{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;flex:1;margin:0;color:${DS.slate600};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
19291
+ .svhs-query .svhs-text-button{flex:none;min-height:32px;padding:4px 0}
19292
+ .svhs-results{display:flex;flex-direction:column;margin:0;padding:0;list-style:none}
19293
+ .svhs-result{display:block;width:100%;padding:17px 0;border:0;border-bottom:1px solid ${DS.slate100};background:${DS.white};color:${DS.slate900};text-align:left}
19294
+ .svhs-results li:last-child .svhs-result{border-bottom:0}
19295
+ .svhs-result-title{display:block;margin:0 0 5px;color:inherit;font-size:16px;font-weight:600;line-height:1.4;letter-spacing:-.2px;overflow-wrap:anywhere}
19296
+ .svhs-result:hover .svhs-result-title{color:${DS.action};text-decoration:underline}
19297
+ .svhs-result-excerpt{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin:0;color:${DS.slate500};font-size:13px;line-height:1.55;overflow-wrap:anywhere}
19298
+ .svhs-result-category{display:block;margin-top:7px;color:${DS.slate500};font-size:12px;line-height:1.4}
19299
+ .svhs-footer-copy{margin:0 0 9px;color:${DS.slate500};font-size:13px;line-height:1.5;text-align:center}
19300
+ .svhs-error{margin:12px 0 0;color:${DS.error};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
19301
+ .svhs-status{margin:16px 0;color:${DS.slate600};font-size:14px;line-height:1.5}
19302
+ .svhs-empty{padding:12px 0 4px}
19303
+ .svhs-empty .svhs-heading{font-size:18px;letter-spacing:-.3px}
19304
+ .svhs-spinner{width:15px;height:15px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:svhs-spin .7s linear infinite;flex:none}
19305
+ @keyframes svhs-spin{to{transform:rotate(360deg)}}
19306
+ .svhs-article-scroll{padding:34px 48px 28px}
19307
+ .svhs-category{margin:0 0 12px;color:${DS.slate500};font-size:13px;line-height:1.5;overflow-wrap:anywhere}
19308
+ .svhs-article-title{margin:0 0 18px;color:${DS.slate900};font-size:28px;font-weight:600;line-height:1.2;letter-spacing:-.8px;overflow-wrap:anywhere}
19309
+ .svhs-article-content{color:${DS.slate600};font-size:15px;line-height:1.65;overflow-wrap:anywhere}
19310
+ .svhs-article-content>*:first-child{margin-top:0}
19311
+ .svhs-article-content p{margin:0 0 18px;font:inherit;color:inherit}
19312
+ .svhs-article-content h1,.svhs-article-content h2,.svhs-article-content h3,.svhs-article-content h4,.svhs-article-content h5,.svhs-article-content h6{margin:28px 0 12px;color:${DS.slate900};font-size:18px;font-weight:600;line-height:1.35;letter-spacing:-.3px;scroll-margin-top:24px}
19313
+ .svhs-article-content h3,.svhs-article-content h4,.svhs-article-content h5,.svhs-article-content h6{font-size:16px}
19314
+ .svhs-article-content ul,.svhs-article-content ol{margin:0 0 22px;padding-left:22px}
19315
+ .svhs-article-content li{margin:8px 0;padding-left:5px}
19316
+ .svhs-article-content strong{font-weight:600;color:${DS.slate900}}
19317
+ .svhs-article-content a{color:${DS.action};text-decoration:underline;text-underline-offset:2px}
19318
+ .svhs-article-content img,.svhs-article-content video{display:block;max-width:100%;height:auto;margin:20px 0}
19319
+ .svhs-reader-asset{display:block;max-width:100%;margin:20px 0}
19320
+ .svhs-reader-asset img{margin:0}
19321
+ .svhs-reader-asset-status{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:4px;min-height:140px;padding:20px;border:1px solid ${DS.slate200};border-radius:6px;background:${DS.slate50};color:${DS.slate500};font-size:13px;text-align:center}
19322
+ .svhs-reader-asset-status[style]{min-height:0}
19323
+ .svhs-article-content blockquote{margin:22px 0;padding:0 0 0 16px;border-left:2px solid ${DS.slate300};font-size:14px}
19324
+ .svhs-article-content pre{margin:20px 0;padding:14px;border:1px solid ${DS.slate200};border-radius:6px;background:${DS.slate50};overflow:auto;overscroll-behavior:contain;font:13px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace}
19325
+ .svhs-article-content code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:.9em}
19326
+ .svhs-article-content table{display:block;max-width:100%;border-collapse:collapse;overflow:auto;overscroll-behavior:contain;margin:20px 0;font-size:14px}
19327
+ .svhs-article-content th,.svhs-article-content td{padding:10px 12px;border:1px solid ${DS.slate200};text-align:left}
19328
+ .svhs-article-content hr{margin:24px 0;border:0;border-top:1px solid ${DS.slate200}}
19329
+ .svhs-article-footer{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 24px;border-top:1px solid ${DS.slate100};flex:none}
19330
+ .svhs-article-footer .svhs-primary{min-width:110px}
19331
+ .svhs-article-footer .svhs-text-button{white-space:nowrap;font-size:13px!important}
19332
+ .svhs-article-question{color:${DS.slate500};font-size:13px;line-height:1.5}
19333
+ .svhs-reader-actions{display:flex;align-items:stretch;gap:12px;flex:none}
19334
+ .svhs-feedback-scroll{padding-top:30px}
19335
+ .svhs-feedback-actions{display:flex;flex-direction:column;gap:9px;margin-top:24px}
19336
+ .svhs-feedback-actions .svhs-text-button{align-self:center;color:${DS.slate500}}
19337
+ .svhs-contact-scroll{padding:0;scrollbar-gutter:auto}
19338
+ .svhs-contact-target{display:flex;flex-direction:column;min-height:100%}
19339
+ .svhs-contact-target:empty{display:none;min-height:0}
19340
+ .svhs-contact-prelude{padding:24px}
19341
+ .svhs-contact-prelude .svhs-secondary{margin-top:16px}
19342
+ .svhs-ticket-gate{padding:0 24px 24px}
19343
+ .svhs-unlock-input{display:block;box-sizing:border-box;width:100%;min-height:46px;margin:0 0 16px;border:1px solid ${DS.slate300};border-radius:6px;padding:11px 12px;background:${DS.white};color:${DS.slate900};font-size:16px!important;line-height:1.5!important}
19344
+ .svhs-unlock-input:focus{border-color:${DS.action}}
19345
+ .svhs-unlock-form{margin:0}
19346
+ .svhs-contact-target>.svhd-container{display:flex;flex:1;flex-direction:column;min-height:100%;max-width:none;padding:24px;border:0;border-radius:0;box-shadow:none;background:transparent}
19347
+ .svhs-contact-target .svhd-body{display:flex;flex:1;flex-direction:column;min-height:0}
19348
+ .svhs-contact-target .svhd-container h2{margin-bottom:12px;font-size:22px;line-height:1.25;letter-spacing:-.6px;overflow-wrap:anywhere}
19349
+ .svhs-contact-target .svhd-form{gap:16px}
19350
+ .svhs-contact-target .svhd-label{font-size:13px;line-height:1.5}
19351
+ .svhs-contact-target .svhd-input{font-size:16px;line-height:1.5}
19352
+ .svhs-contact-target .svhd-description{min-height:138px}
19353
+ .svhs-contact-target .svhd-actions{gap:10px}
19354
+ .svhs-contact-target .svhd-actions>.svhd-button:first-child{flex:1}
19355
+ .svhs-contact-target .svhd-status{font-size:14px}
19356
+ .svhs-contact-target .svhd-auth{gap:14px}
19357
+ .svhs-contact-target .svhd-widget-account{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;min-width:0}
19358
+ .svhs-contact-target .svhd-widget-identity{display:flex;flex:1;min-width:0;flex-direction:column;gap:2px;margin:0;line-height:1.4;overflow-wrap:anywhere}
19359
+ .svhs-contact-target .svhd-widget-identity strong{color:${DS.slate900};font-size:14px;font-weight:600}
19360
+ .svhs-contact-target .svhd-widget-identity span{color:${DS.slate500};font-size:13px}
19361
+ .svhs-contact-target .svhd-widget-account-link{display:inline-flex;align-items:center;justify-content:center;min-height:44px;max-width:100%;padding:8px 0;border:0;border-radius:6px;background:transparent;color:${DS.action};font-size:13px;line-height:1.4}
19362
+ .svhs-contact-target .svhd-widget-account-link:hover{text-decoration:underline}
19363
+ .svhs-contact-target .svhd-widget-account-link:focus-visible{outline:2px solid ${DS.action};outline-offset:3px}
19364
+ .svhs-contact-target .svhd-widget-account-link:disabled{cursor:progress;color:${DS.slate500}}
19365
+ .svhs-contact-target .svhd-widget-names{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px}
19366
+ .svhs-contact-target .svhd-widget-form{display:flex;flex:1;flex-direction:column;gap:16px}
19367
+ .svhs-contact-target .svhd-widget-message{display:flex;flex:1;flex-direction:column;gap:6px;min-height:164px}
19368
+ .svhs-contact-target .svhd-widget-message .svhd-description{flex:1;resize:vertical}
19369
+ .svhs-contact-target .svhd-widget-form>.svhd-actions{position:sticky;bottom:0;z-index:1;margin:auto -24px 0;padding:16px 24px 0;border-top:1px solid ${DS.slate100};background:${DS.white}}
19370
+ .svhs-contact-target .svhd-widget-form>.svhd-actions>.svhd-secondary{display:none}
19371
+ .svhs-contact-target .svhd-widget-form .svhd-actions>.svhd-button{font-size:14px}
19372
+ .svhs-contact-target .svhd-widget-form>.svhd-confirm{position:sticky;bottom:-24px;z-index:2;margin:0 -24px -24px;padding:16px 24px 24px;border-top:1px solid ${DS.slate200};background:${DS.white}}
19373
+ .svhs-contact-target .svhd-widget-form>.svhd-confirm .svhd-actions{flex-wrap:nowrap}
19374
+ .svhs-contact-target .svhd-widget-form>.svhd-confirm .svhd-button{flex:1}
19375
+ .svhs-contact-target .svhd-footer{margin-top:16px;text-align:center;font-size:11px}
19376
+ .svhs-account-return{padding:0 24px 12px}
19377
+ .svhs-account-return .svhs-text-button{font-size:13px!important}
19378
+ .svhs-receipt-scroll{padding-top:36px}
19379
+ .svhs-receipt-mark{width:30px!important;height:30px!important;margin-bottom:20px;color:${DS.action}}
19380
+ .svhs-ticket-link{display:inline-flex;align-items:center;min-height:44px;margin:0 0 10px;color:${DS.action};font-size:14px;font-weight:600;text-decoration:underline}
19381
+ .svhs-receipt-note{white-space:pre-wrap;overflow-wrap:anywhere}
19382
+ .svhs-receipt-actions{display:flex;flex-direction:column;align-items:center;gap:4px}
19383
+ .svhs-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
19384
+ .svhs-toast{box-sizing:border-box;position:fixed;right:24px;bottom:calc(96px + var(--svhs-toast-offset,0px) + env(safe-area-inset-bottom));z-index:2147482901;display:flex;align-items:center;gap:10px;max-width:calc(100vw - 36px);padding:14px 18px;border:1px solid transparent;border-radius:8px;background:${DS.slate900};color:${DS.white};box-shadow:${DS.shadowPopover};font:400 14px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',sans-serif;overflow-wrap:anywhere}
19385
+ .svhs-toast svg{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
19386
+ .svhs-overlay{position:fixed;inset:0;z-index:2147482900;display:flex;background:${DS.white};padding:0;overflow:hidden}
19387
+ .svhs-modal{width:100%;height:100%;min-width:0;outline:none}
19388
+ .svhs-overlay .svhs-panel{position:relative;inset:auto;width:100%;height:100%;max-width:none;max-height:none;border:0;border-radius:0;box-shadow:none;padding-top:env(safe-area-inset-top);transition:none}
19389
+ .sv-support-launcher{touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:background 120ms cubic-bezier(.2,0,0,1)}
19390
+ .sv-support-launcher:hover{filter:brightness(1.12)}
19391
+ .sv-support-launcher:active{transform:translateY(1px)}
19392
+ .sv-support-launcher:focus-visible{outline:3px solid ${DS.action};outline-offset:3px}
19393
+ @media(max-width:640px){
19394
+ .svhs-panel{right:0;bottom:0;width:100%;height:100dvh;max-width:none;max-height:none;border:0;border-radius:0}
19395
+ .svhs-toolbar{min-height:70px;padding:12px 12px 12px 24px;border-bottom-color:${DS.slate200}}
19396
+ .svhs-icon-button{width:44px;height:44px}
19397
+ .svhs-back{min-height:44px;max-width:42%}
19398
+ .svhs-scroll{padding:28px 24px}
19399
+ .svhs-heading{font-size:25px}
19400
+ .svhs-issue{min-height:148px;max-height:260px}
19401
+ .svhs-bottom{padding-bottom:calc(20px + env(safe-area-inset-bottom))}
19402
+ .svhs-start-bottom{margin-top:0}
19403
+ .svhs-panel[data-stage=issue] .svhs-scroll{flex:0}
19404
+ .svhs-query .svhs-text-button{min-height:44px;min-width:44px}
19405
+ .svhs-query-text{font-size:15px}
19406
+ .svhs-result{padding:20px 0}
19407
+ .svhs-result-title{font-size:17px}
19408
+ .svhs-result-excerpt{font-size:14px}
19409
+ .svhs-article-scroll{padding:32px 25px}
19410
+ .svhs-article-title{font-size:28px}
19411
+ .svhs-article-content{font-size:16px}
19412
+ .svhs-article-footer{align-items:stretch;padding:12px 24px calc(12px + env(safe-area-inset-bottom))}
19413
+ .svhs-article-question{display:none}
19414
+ .svhs-reader-actions{flex:1}
19415
+ .svhs-article-footer .svhs-primary,.svhs-article-footer .svhs-text-button{flex:1;font-size:14px!important}
19416
+ .svhs-feedback-scroll{padding-top:50px}
19417
+ .svhs-feedback-actions{margin-top:30px}
19418
+ .svhs-feedback-actions .svhs-primary,.svhs-feedback-actions .svhs-secondary{min-height:48px}
19419
+ .svhs-contact-scroll{padding:0}
19420
+ .svhs-contact-target .svhd-description{min-height:160px}
19421
+ .svhs-contact-target>.svhd-container{padding:24px}
19422
+ .svhs-contact-target .svhd-widget-form>.svhd-actions{padding-bottom:env(safe-area-inset-bottom)}
19423
+ .svhs-receipt-scroll{padding-top:58px;flex:0}
19424
+ .svhs-panel[data-stage=receipt] .svhs-bottom{border-top:0;padding-top:8px}
19425
+ .svhs-toast{right:18px;left:18px;bottom:calc(88px + var(--svhs-toast-offset,0px) + env(safe-area-inset-bottom));max-width:none}
19426
+ }
19427
+ @media(pointer:coarse){.svhs-icon-button{width:44px;height:44px}.svhs-back{min-height:44px}.svhs-query .svhs-text-button{min-height:44px;min-width:44px}}
19428
+ @media(prefers-reduced-motion:reduce){.svhs-panel,.svhs-panel *,.sv-support-launcher{transition-duration:0s!important;animation-duration:.01ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important}}
19429
+ @media(forced-colors:active){.svhs-panel button:focus-visible,.svhs-panel a:focus-visible,.svhs-panel input:focus-visible,.svhs-panel textarea:focus-visible{outline:2px solid Highlight}.svhs-panel,.svhs-primary,.svhs-secondary{border:1px solid ButtonText}}
19430
+ `;
19431
+ document.head.appendChild(style);
19432
+ }
19433
+
19434
+ /** Same-document history belongs to the host; support only owns its marked entry. */
19435
+ let internalMutation = 0;
19436
+ const hostMutationListeners = new Set();
19437
+ let stopObserving = null;
19438
+ let sequence$1 = 0;
19439
+ function observeHostMutations(listener) {
19440
+ hostMutationListeners.add(listener);
19441
+ if (!stopObserving) {
19442
+ const history = window.history;
19443
+ const push = history.pushState;
19444
+ const replace = history.replaceState;
19445
+ const changed = () => {
19446
+ if (!internalMutation)
19447
+ for (const notify of [...hostMutationListeners])
19448
+ notify();
19449
+ };
19450
+ const wrappedPush = function (...args) { push.apply(this, args); changed(); };
19451
+ const wrappedReplace = function (...args) { replace.apply(this, args); changed(); };
19452
+ history.pushState = wrappedPush;
19453
+ history.replaceState = wrappedReplace;
19454
+ stopObserving = () => {
19455
+ // A host may install its own adapter after support opened. Never undo it.
19456
+ if (history.pushState === wrappedPush)
19457
+ history.pushState = push;
19458
+ if (history.replaceState === wrappedReplace)
19459
+ history.replaceState = replace;
19460
+ stopObserving = null;
19461
+ };
19462
+ }
19463
+ return () => {
19464
+ hostMutationListeners.delete(listener);
19465
+ if (!hostMutationListeners.size)
19466
+ stopObserving?.();
19467
+ };
19468
+ }
19469
+ function ownMutation(action) {
19470
+ internalMutation += 1;
19471
+ try {
19472
+ action();
19473
+ }
19474
+ finally {
19475
+ internalMutation -= 1;
19476
+ }
19477
+ }
19478
+ /**
19479
+ * One same-URL entry while phone support is open. No popstate is cancelled or
19480
+ * swallowed, and no cleanup ever calls history.back()/go(). Explicit close,
19481
+ * resize and disposal replace only a proven owned current entry with its
19482
+ * original host state. The inactive entry can be reused while still owned.
19483
+ * A harmless same-URL entry is preferable to consuming a host's later route.
19484
+ */
19485
+ class SupportPhoneHistory {
19486
+ constructor(actions) {
19487
+ this.actions = actions;
19488
+ this.marker = `__sv_support_phone_${++sequence$1}`;
19489
+ // A DOM ownership label, never a credential or an unpredictable identifier.
19490
+ this.token = `${Date.now()}-${sequence$1}`;
19491
+ this.baseState = null;
19492
+ this.url = '';
19493
+ this.hasInactiveEntry = false;
19494
+ this.wantsPhone = false;
19495
+ this.mobile = false;
19496
+ this.active = false;
19497
+ this.forwardAllowed = false;
19498
+ this.destroyed = false;
19499
+ this.unobserve = null;
19500
+ this.onHostMutation = () => {
19501
+ this.active = false;
19502
+ this.hasInactiveEntry = false;
19503
+ this.forwardAllowed = false;
19504
+ this.activeReference = undefined;
19505
+ this.inactiveReference = undefined;
19506
+ };
19507
+ this.onPopState = () => {
19508
+ if (this.destroyed)
19509
+ return;
19510
+ if (this.isMarkedEntry() && this.active && window.history.state === this.activeReference)
19511
+ return;
19512
+ if (this.isMarkedEntry() && this.forwardAllowed && this.mobile && !this.wantsPhone) {
19513
+ this.active = true;
19514
+ this.wantsPhone = true;
19515
+ this.activeReference = window.history.state;
19516
+ this.actions.onForward();
19517
+ return;
19518
+ }
19519
+ if (this.wantsPhone) {
19520
+ this.forwardAllowed = this.active;
19521
+ this.active = false;
19522
+ this.wantsPhone = false;
19523
+ this.activeReference = undefined;
19524
+ this.actions.onBack();
19525
+ }
19526
+ };
19527
+ window.addEventListener('popstate', this.onPopState);
19528
+ }
19529
+ sync(visible, mobile) {
19530
+ if (this.destroyed)
19531
+ return;
19532
+ this.mobile = mobile;
19533
+ if (!mobile)
19534
+ this.forwardAllowed = false;
19535
+ const wantsPhone = visible && mobile;
19536
+ if (wantsPhone === this.wantsPhone)
19537
+ return;
19538
+ this.wantsPhone = wantsPhone;
19539
+ if (wantsPhone)
19540
+ this.arm();
19541
+ else
19542
+ this.deactivate();
19543
+ }
19544
+ /** Explicit close also invalidates a forward entry after a neutral Back. */
19545
+ deactivate() {
19546
+ if (this.destroyed)
19547
+ return;
19548
+ this.wantsPhone = false;
19549
+ this.forwardAllowed = false;
19550
+ const ownsEntry = this.active && this.isMarkedEntry() && window.history.state === this.activeReference;
19551
+ this.active = false;
19552
+ this.activeReference = undefined;
19553
+ if (!ownsEntry)
19554
+ return;
19555
+ ownMutation(() => window.history.replaceState(this.baseState, '', this.url));
19556
+ this.inactiveReference = window.history.state;
19557
+ this.hasInactiveEntry = true;
19558
+ }
19559
+ destroy() {
19560
+ if (this.destroyed)
19561
+ return;
19562
+ this.deactivate();
19563
+ this.destroyed = true;
19564
+ window.removeEventListener('popstate', this.onPopState);
19565
+ this.unobserve?.();
19566
+ this.unobserve = null;
19567
+ }
19568
+ arm() {
19569
+ this.unobserve ?? (this.unobserve = observeHostMutations(this.onHostMutation));
19570
+ const reuse = this.hasInactiveEntry && window.location.href === this.url && window.history.state === this.inactiveReference;
19571
+ this.baseState = window.history.state;
19572
+ this.url = window.location.href;
19573
+ const value = this.baseState;
19574
+ const record = value !== null && typeof value === 'object' && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
19575
+ const state = record ? { ...value, [this.marker]: this.token } : { [this.marker]: this.token, hostState: value };
19576
+ try {
19577
+ ownMutation(() => {
19578
+ if (reuse)
19579
+ window.history.replaceState(state, '', this.url);
19580
+ else
19581
+ window.history.pushState(state, '', this.url);
19582
+ });
19583
+ this.activeReference = window.history.state;
19584
+ this.active = true;
19585
+ this.hasInactiveEntry = false;
19586
+ this.forwardAllowed = false;
19587
+ }
19588
+ catch {
19589
+ // A denied history write must never prevent someone contacting support.
19590
+ this.active = false;
19591
+ this.forwardAllowed = false;
19592
+ }
19593
+ }
19594
+ isMarkedEntry() {
19595
+ const state = window.history.state;
19596
+ return window.location.href === this.url && state !== null && typeof state === 'object' &&
19597
+ state[this.marker] === this.token;
19598
+ }
19599
+ }
19600
+
19601
+ /* global MediaQueryList, HTMLImageElement, HTMLAnchorElement, Element */
19602
+ let sequence = 0;
19603
+ function element(tag, className, text) {
19604
+ const node = document.createElement(tag);
19605
+ if (className)
19606
+ node.className = className;
19607
+ if (text !== undefined)
19608
+ node.textContent = text;
19609
+ return node;
19610
+ }
19611
+ function button(className, text, action) {
19612
+ const node = element('button', className, text);
19613
+ node.type = 'button';
19614
+ node.addEventListener('click', action);
19615
+ return node;
19616
+ }
19617
+ function icon(name) {
19618
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
19619
+ svg.setAttribute('viewBox', '0 0 24 24');
19620
+ svg.setAttribute('aria-hidden', 'true');
19621
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
19622
+ path.setAttribute('d', {
19623
+ back: 'm14.5 6-6 6 6 6',
19624
+ close: 'm6 6 12 12M18 6 6 18',
19625
+ external: 'M14 4h6v6m0-6L10 14M11 5H5a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1v-6',
19626
+ check: 'm5 12 4 4L19 6',
19627
+ }[name]);
19628
+ svg.append(path);
19629
+ return svg;
19630
+ }
19631
+ function httpUrl(value, base = window.location.href) {
19632
+ if (!value)
19633
+ return null;
19634
+ try {
19635
+ const url = new URL(value, base);
19636
+ return (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password ? url : null;
19637
+ }
19638
+ catch {
19639
+ return null;
19640
+ }
19641
+ }
19642
+ /**
19643
+ * The durable support surface. Every screen is kept, including the shared
19644
+ * contact form's mount node; navigating, minimizing and stacking Identity do
19645
+ * not destroy the caller's unsent composition.
19646
+ *
19647
+ * Desktop is deliberately nonmodal. Phone uses the SDK's shared ModalShell,
19648
+ * so its page lock and keyboard ownership compose with the Identity dialog.
19649
+ */
19650
+ class SupportView {
19651
+ constructor(actions) {
19652
+ this.actions = actions;
19653
+ this.contactTarget = element('div', 'svhs-contact-target');
19654
+ this.panel = element('section', 'svhs-panel');
19655
+ this.prefix = `svhs-${++sequence}`;
19656
+ this.screens = new Map();
19657
+ this.scrollers = new Map();
19658
+ this.scrollPositions = new Map();
19659
+ this.headings = new Map();
19660
+ this.deskName = element('span', 'svhs-desk-name');
19661
+ this.external = element('a', 'svhs-icon-button');
19662
+ this.issue = element('textarea', 'svhs-issue');
19663
+ this.issueError = element('p', 'svhs-error');
19664
+ this.query = element('p', 'svhs-query-text');
19665
+ this.resultList = element('ul', 'svhs-results');
19666
+ this.resultCopy = element('p', 'svhs-copy');
19667
+ this.resultStatus = element('div', 'svhs-empty');
19668
+ this.resultError = element('p', 'svhs-error');
19669
+ this.articleTitle = element('h2', 'svhs-article-title');
19670
+ this.articleCategory = element('p', 'svhs-category');
19671
+ this.articleContent = element('div', 'svhs-article-content');
19672
+ this.articleStatus = element('p', 'svhs-status');
19673
+ this.articleError = element('p', 'svhs-error');
19674
+ this.articleFooter = element('div', 'svhs-article-footer');
19675
+ this.contactTitle = element('h2', 'svhs-heading');
19676
+ this.contactStatus = element('p', 'svhs-status');
19677
+ this.contactError = element('p', 'svhs-error');
19678
+ this.ticketGate = element('div', 'svhs-ticket-gate');
19679
+ this.receiptCopy = element('p', 'svhs-copy');
19680
+ this.receiptTicket = element('a', 'svhs-ticket-link');
19681
+ this.receiptMessage = element('p', 'svhs-copy svhs-receipt-note');
19682
+ this.live = element('div', 'svhs-live');
19683
+ this.identityNotice = element('div', 'svhs-identity-notice');
19684
+ this.onMediaChange = () => this.syncPresentation();
19685
+ this.onViewportChange = () => this.syncViewport();
19686
+ this.shell = null;
19687
+ this.opener = null;
19688
+ this.state = null;
19689
+ this.resultSignature = '';
19690
+ this.resultStatusSignature = '';
19691
+ this.articleSignature = '';
19692
+ this.ticketGateSignature = '';
19693
+ this.toastCleanups = new Set();
19694
+ this.destroyed = false;
19695
+ injectHelpDeskSupportStyles();
19696
+ this.phoneHistory = actions.onBrowserBack && actions.onBrowserForward ? new SupportPhoneHistory({
19697
+ onBack: () => this.actions.onBrowserBack?.(),
19698
+ onForward: () => this.actions.onBrowserForward?.(),
19699
+ }) : null;
19700
+ this.panel.id = `${this.prefix}-panel`;
19701
+ this.panel.tabIndex = -1;
19702
+ this.panel.hidden = true;
19703
+ this.panel.setAttribute('aria-labelledby', `${this.prefix}-name`);
19704
+ this.deskName.id = `${this.prefix}-name`;
19705
+ this.live.setAttribute('role', 'status');
19706
+ this.live.setAttribute('aria-live', 'polite');
19707
+ const toolbar = element('header', 'svhs-toolbar');
19708
+ this.back = button('svhs-back', 'Back', () => this.actions.onBack());
19709
+ this.back.prepend(icon('back'));
19710
+ this.close = button('svhs-icon-button', '', () => this.actions.onClose());
19711
+ this.close.setAttribute('aria-label', 'Close support');
19712
+ this.close.append(icon('close'));
19713
+ this.external.setAttribute('aria-label', 'Open article in a new tab');
19714
+ this.external.title = 'Open article in a new tab';
19715
+ this.external.target = '_blank';
19716
+ this.external.rel = 'noopener noreferrer';
19717
+ this.external.append(icon('external'));
19718
+ const toolbarActions = element('div', 'svhs-toolbar-actions');
19719
+ toolbarActions.append(this.external, this.close);
19720
+ toolbar.append(this.back, this.deskName, toolbarActions);
19721
+ this.panel.append(toolbar);
19722
+ this.identityNotice.append(element('p', 'svhs-status', 'Sign-in is open in another window.'), button('svhs-text-button', 'Cancel sign-in', () => this.actions.onCancelIdentity?.()));
19723
+ this.identityNotice.hidden = true;
19724
+ this.panel.append(this.identityNotice);
19725
+ const intro = this.screen('issue', 'How can we help?');
19726
+ intro.append(element('p', 'svhs-copy', 'Tell us what you need. We’ll look for an answer in our help articles.'));
19727
+ const issueLabel = element('label', 'svhs-live', 'What do you need help with?');
19728
+ issueLabel.htmlFor = `${this.prefix}-issue`;
19729
+ this.issue.id = issueLabel.htmlFor;
19730
+ this.issue.name = 'support_issue';
19731
+ this.issue.placeholder = 'Describe your question or issue…';
19732
+ this.issue.autocomplete = 'off';
19733
+ this.issue.setAttribute('aria-describedby', `${this.prefix}-issue-error`);
19734
+ this.issueError.id = `${this.prefix}-issue-error`;
19735
+ this.issueError.setAttribute('role', 'alert');
19736
+ this.issueError.hidden = true;
19737
+ this.issue.addEventListener('input', () => {
19738
+ this.resizeIssue();
19739
+ this.issueError.hidden = true;
19740
+ this.issue.removeAttribute('aria-invalid');
19741
+ this.actions.onIssueChange(this.issue.value);
19742
+ });
19743
+ this.issue.addEventListener('keydown', (event) => {
19744
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter' && !event.isComposing) {
19745
+ event.preventDefault();
19746
+ this.search();
19747
+ }
19748
+ });
19749
+ intro.append(issueLabel, this.issue, this.issueError);
19750
+ this.find = button('svhs-primary', 'Find answers', () => this.search());
19751
+ this.footer('issue', 'svhs-start-bottom').append(this.find, button('svhs-text-button', 'Contact support instead', () => this.actions.onContact('direct')));
19752
+ const results = this.screen('results', 'These may help');
19753
+ const queryLine = element('div', 'svhs-query');
19754
+ queryLine.append(this.query, button('svhs-text-button', 'Edit', () => this.actions.onBack()));
19755
+ results.append(this.resultCopy, queryLine, this.resultList, this.resultStatus, this.resultError);
19756
+ this.resultError.setAttribute('role', 'alert');
19757
+ this.contactResults = button('svhs-secondary svhs-full', 'None of these help. Contact support', () => {
19758
+ this.actions.onContact(this.state?.busy || ['locked', 'unavailable'].includes(this.state?.kbState || '') ? 'direct' : this.state?.results?.length ? 'none_match' : 'no_results');
19759
+ });
19760
+ this.footer('results').append(element('p', 'svhs-footer-copy', 'Still need a hand?'), this.contactResults);
19761
+ const article = this.screen('article');
19762
+ article.classList.add('svhs-article-scroll');
19763
+ this.articleTitle.tabIndex = -1;
19764
+ this.articleTitle.id = `${this.prefix}-article-title`;
19765
+ this.headings.set('article', this.articleTitle);
19766
+ this.articleStatus.setAttribute('role', 'status');
19767
+ this.articleError.setAttribute('role', 'alert');
19768
+ this.articleRetry = button('svhs-secondary', 'Try again', () => this.actions.onRetry?.());
19769
+ article.append(this.articleCategory, this.articleTitle, this.articleStatus, this.articleContent, this.articleError, this.articleRetry);
19770
+ this.articleContent.addEventListener('click', (event) => this.articleLink(event));
19771
+ const readerActions = element('div', 'svhs-reader-actions');
19772
+ readerActions.append(button('svhs-primary', 'Yes, thanks', () => { if (this.state?.article && !this.state.busy && !this.state.error)
19773
+ this.actions.onAnswered(); }), button('svhs-text-button', 'Contact support', () => this.actions.onContact('article_not_answered')));
19774
+ this.articleFooter.append(element('span', 'svhs-article-question', 'Did this answer your question?'), readerActions);
19775
+ this.screens.get('article').append(this.articleFooter);
19776
+ const feedback = this.screen('feedback', 'Did this answer your question?');
19777
+ feedback.classList.add('svhs-feedback-scroll');
19778
+ feedback.append(element('p', 'svhs-copy', 'Your feedback helps us improve our help articles.'));
19779
+ const feedbackActions = element('div', 'svhs-feedback-actions');
19780
+ feedbackActions.append(button('svhs-primary', 'Yes, that helped', () => this.actions.onAnswered()), button('svhs-secondary', 'No, contact support', () => this.actions.onContact('article_not_answered')), button('svhs-text-button', 'Not now', () => this.actions.onClose()));
19781
+ feedback.append(feedbackActions);
19782
+ const contact = this.screen('contact');
19783
+ contact.classList.add('svhs-contact-scroll');
19784
+ const contactPrelude = element('div', 'svhs-contact-prelude');
19785
+ this.contactTitle.tabIndex = -1;
19786
+ this.contactStatus.setAttribute('role', 'status');
19787
+ this.contactError.setAttribute('role', 'alert');
19788
+ this.contactError.id = `${this.prefix}-contact-error`;
19789
+ this.contactRetry = button('svhs-secondary', 'Try again', () => this.actions.onRetry?.());
19790
+ contactPrelude.append(this.contactTitle, this.contactStatus, this.contactError, this.contactRetry);
19791
+ contact.append(contactPrelude);
19792
+ contact.append(this.ticketGate);
19793
+ contact.append(this.contactTarget);
19794
+ const accountReturn = element('div', 'svhs-account-return');
19795
+ this.accountReturn = button('svhs-text-button', 'Use website account', () => this.actions.onUseWebsiteAccount?.());
19796
+ accountReturn.append(this.accountReturn);
19797
+ this.screens.get('contact').append(accountReturn);
19798
+ const receipt = this.screen('receipt', 'Message sent');
19799
+ receipt.classList.add('svhs-receipt-scroll');
19800
+ const receiptMark = icon('check');
19801
+ receiptMark.classList.add('svhs-receipt-mark');
19802
+ receipt.prepend(receiptMark);
19803
+ this.receiptTicket.target = '_blank';
19804
+ this.receiptTicket.rel = 'noopener noreferrer';
19805
+ receipt.append(this.receiptCopy, this.receiptTicket, this.receiptMessage);
19806
+ this.restart = button('svhs-text-button', 'Ask another question', () => this.actions.onRestart?.());
19807
+ const receiptFooter = this.footer('receipt', 'svhs-receipt-actions');
19808
+ receiptFooter.append(button('svhs-secondary svhs-full', 'Done', () => this.actions.onClose()), this.restart);
19809
+ this.panel.append(this.live);
19810
+ this.media = typeof window.matchMedia === 'function' ? window.matchMedia('(max-width:640px)') : null;
19811
+ this.media?.addEventListener('change', this.onMediaChange);
19812
+ window.visualViewport?.addEventListener('resize', this.onViewportChange);
19813
+ window.visualViewport?.addEventListener('scroll', this.onViewportChange);
19814
+ this.onKeydown = (event) => {
19815
+ if (this.shell || !this.state?.visible || this.destroyed || event.defaultPrevented || event.isComposing || event.keyCode === 229)
19816
+ return;
19817
+ // A nonmodal panel leaves the host's shortcuts alone once focus leaves.
19818
+ if (event.key !== 'Escape' || !this.panel.contains(document.activeElement))
19819
+ return;
19820
+ const activeDialog = document.activeElement?.closest('[role="dialog"],[role="alertdialog"],[aria-modal="true"]');
19821
+ if (activeDialog && activeDialog !== this.panel)
19822
+ return;
19823
+ event.preventDefault();
19824
+ this.actions.onClose();
19825
+ };
19826
+ document.addEventListener('keydown', this.onKeydown);
19827
+ }
19828
+ render(next) {
19829
+ if (this.destroyed)
19830
+ return;
19831
+ const previous = this.state;
19832
+ if (previous)
19833
+ this.saveScroll(previous);
19834
+ this.state = next;
19835
+ this.panel.dataset.stage = next.stage;
19836
+ const inset = (value, fallback) => typeof value === 'number' && Number.isFinite(value) ? Math.min(480, Math.max(0, value)) : fallback;
19837
+ this.panel.style.setProperty('--svhs-right', `${inset(next.position?.right, 24)}px`);
19838
+ this.panel.style.setProperty('--svhs-bottom', `${inset(next.position?.bottom, 96)}px`);
19839
+ this.deskName.textContent = next.deskName || 'Support';
19840
+ this.identityNotice.hidden = !next.identityPending || !this.actions.onCancelIdentity;
19841
+ this.restart.hidden = !this.actions.onRestart;
19842
+ this.back.hidden = !['results', 'article', 'feedback', 'contact'].includes(next.stage);
19843
+ this.back.disabled = Boolean(next.navigationLocked || next.identityPending);
19844
+ this.back.lastChild.textContent = next.stage === 'article' ? 'All answers' : next.stage === 'feedback' ? 'Keep reading' : 'Back';
19845
+ this.deskName.hidden = next.stage === 'article';
19846
+ this.panel.setAttribute('aria-labelledby', next.stage === 'article' ? this.articleTitle.id : this.deskName.id);
19847
+ for (const [stage, screen] of this.screens)
19848
+ screen.hidden = stage !== next.stage;
19849
+ if (this.issue.value !== next.issue)
19850
+ this.issue.value = next.issue;
19851
+ this.resizeIssue();
19852
+ this.find.setAttribute('aria-disabled', String(Boolean(next.busy)));
19853
+ this.find.setAttribute('aria-busy', String(Boolean(next.busy)));
19854
+ this.find.replaceChildren();
19855
+ if (next.busy)
19856
+ this.find.append(element('span', 'svhs-spinner'));
19857
+ this.find.append(document.createTextNode(next.busy ? 'Finding answers…' : 'Find answers'));
19858
+ this.issueError.textContent = next.stage === 'issue' ? next.error || '' : '';
19859
+ this.issueError.hidden = !this.issueError.textContent;
19860
+ this.query.textContent = next.issue;
19861
+ this.renderResults(next);
19862
+ this.renderArticle(next);
19863
+ this.accountReturn.parentElement.hidden = !next.returnToWebsiteAccount;
19864
+ this.contactTitle.textContent = `Contact ${next.deskName}`;
19865
+ this.contactTitle.hidden = !next.ticketAccessRequired && Boolean(this.contactTarget.querySelector('h1,h2,h3'));
19866
+ this.contactStatus.textContent = next.stage === 'contact' && next.busy ? next.ticketAccessRequired ? 'Checking support access…' : 'Connecting to support…' : '';
19867
+ this.contactStatus.hidden = !this.contactStatus.textContent;
19868
+ this.contactError.textContent = next.stage === 'contact' ? next.error || '' : '';
19869
+ this.contactError.hidden = !this.contactError.textContent;
19870
+ this.contactRetry.hidden = Boolean(next.ticketAccessRequired) || !this.contactError.textContent || !this.actions.onRetry || Boolean(next.busy);
19871
+ this.contactTitle.parentElement.hidden = this.contactTitle.hidden && this.contactStatus.hidden && this.contactError.hidden;
19872
+ this.renderTicketGate(next);
19873
+ this.renderReceipt(next);
19874
+ this.syncPresentation();
19875
+ if (!next.visible)
19876
+ return;
19877
+ if (!previous?.visible || previous.stage !== next.stage || previous.article?.id !== next.article?.id) {
19878
+ this.restoreScroll(next);
19879
+ this.focusCurrent();
19880
+ }
19881
+ }
19882
+ /** Programmatic close invalidates Forward restoration even after neutral Back. */
19883
+ deactivateHistory() {
19884
+ this.phoneHistory?.deactivate();
19885
+ }
19886
+ /** Focus the shared form after its controller has mounted it. */
19887
+ focusContact() {
19888
+ if (this.destroyed || !this.state?.visible || this.state.stage !== 'contact')
19889
+ return;
19890
+ const heading = this.contactTarget.querySelector('h1,h2,h3');
19891
+ this.contactTitle.hidden = Boolean(heading);
19892
+ this.contactTitle.parentElement.hidden = this.contactTitle.hidden && this.contactStatus.hidden && this.contactError.hidden;
19893
+ const target = heading ?? this.contactTarget;
19894
+ target.tabIndex = -1;
19895
+ target.focus({ preventScroll: true });
19896
+ }
19897
+ /** Hydrate only the current reader's matching authorized publication assets. */
19898
+ setArticleAsset(path, blobUrl) {
19899
+ if (this.destroyed || !blobUrl.startsWith('blob:'))
19900
+ return;
19901
+ for (const image of this.articleContent.querySelectorAll('img[data-kb-asset]')) {
19902
+ if (image.getAttribute('data-kb-asset') !== path)
19903
+ continue;
19904
+ image.src = blobUrl;
19905
+ image.hidden = false;
19906
+ const frame = image.closest('.svhs-reader-asset');
19907
+ if (frame) {
19908
+ frame.setAttribute('aria-busy', 'false');
19909
+ const status = frame.querySelector('.svhs-reader-asset-status');
19910
+ if (status)
19911
+ status.hidden = true;
19912
+ }
19913
+ }
19914
+ }
19915
+ setArticleAssetError(path) {
19916
+ if (this.destroyed)
19917
+ return;
19918
+ for (const image of this.articleContent.querySelectorAll('img[data-kb-asset]')) {
19919
+ if (image.getAttribute('data-kb-asset') !== path || image.hasAttribute('src'))
19920
+ continue;
19921
+ const frame = image.closest('.svhs-reader-asset');
19922
+ const status = frame?.querySelector('.svhs-reader-asset-status');
19923
+ if (!frame || !status)
19924
+ continue;
19925
+ frame.setAttribute('aria-busy', 'false');
19926
+ status.hidden = false;
19927
+ status.replaceChildren(document.createTextNode('This image couldn’t be loaded.'));
19928
+ const canonical = httpUrl(this.state?.article?.canonical_url);
19929
+ if (canonical) {
19930
+ const link = element('a', '', 'Open the full article');
19931
+ link.href = canonical.href;
19932
+ link.target = '_blank';
19933
+ link.rel = 'noopener noreferrer';
19934
+ link.setAttribute('data-svhs-canonical', 'true');
19935
+ status.append(document.createTextNode(' '), link);
19936
+ }
19937
+ }
19938
+ }
19939
+ /** A nonessential confirmation; timers pause while it cannot be read. */
19940
+ showToast(message) {
19941
+ if (this.destroyed || !message.trim())
19942
+ return;
19943
+ const toast = element('div', 'svhs-toast');
19944
+ toast.setAttribute('role', 'status');
19945
+ toast.setAttribute('aria-atomic', 'true');
19946
+ toast.append(icon('check'), document.createTextNode(message));
19947
+ document.body.append(toast);
19948
+ const arrange = () => {
19949
+ let offset = 0;
19950
+ for (const item of document.querySelectorAll('.svhs-toast')) {
19951
+ item.style.setProperty('--svhs-toast-offset', `${offset}px`);
19952
+ offset += item.getBoundingClientRect().height + 8;
19953
+ }
19954
+ };
19955
+ arrange();
19956
+ let remaining = 4000;
19957
+ let started = 0;
19958
+ let timer;
19959
+ let hovered = false;
19960
+ const pause = () => {
19961
+ if (timer === undefined)
19962
+ return;
19963
+ window.clearTimeout(timer);
19964
+ timer = undefined;
19965
+ remaining = Math.max(0, remaining - (Date.now() - started));
19966
+ };
19967
+ const cleanup = () => {
19968
+ pause();
19969
+ toast.remove();
19970
+ document.removeEventListener('visibilitychange', visibility);
19971
+ this.toastCleanups.delete(cleanup);
19972
+ arrange();
19973
+ };
19974
+ const resume = () => {
19975
+ if (timer !== undefined || document.hidden || hovered)
19976
+ return;
19977
+ started = Date.now();
19978
+ timer = window.setTimeout(cleanup, remaining);
19979
+ };
19980
+ const visibility = () => { if (document.hidden)
19981
+ pause();
19982
+ else
19983
+ resume(); };
19984
+ toast.addEventListener('pointerenter', () => { hovered = true; pause(); });
19985
+ toast.addEventListener('pointerleave', () => { hovered = false; resume(); });
19986
+ toast.addEventListener('focusin', pause);
19987
+ toast.addEventListener('focusout', resume);
19988
+ document.addEventListener('visibilitychange', visibility);
19989
+ this.toastCleanups.add(cleanup);
19990
+ resume();
19991
+ }
19992
+ destroy() {
19993
+ if (this.destroyed)
19994
+ return;
19995
+ this.destroyed = true;
19996
+ this.phoneHistory?.destroy();
19997
+ document.removeEventListener('keydown', this.onKeydown);
19998
+ this.media?.removeEventListener('change', this.onMediaChange);
19999
+ window.visualViewport?.removeEventListener('resize', this.onViewportChange);
20000
+ window.visualViewport?.removeEventListener('scroll', this.onViewportChange);
20001
+ for (const cleanup of [...this.toastCleanups])
20002
+ cleanup();
20003
+ this.hide();
20004
+ this.panel.remove();
20005
+ }
20006
+ screen(stage, title) {
20007
+ const screen = element('section', 'svhs-screen');
20008
+ screen.hidden = true;
20009
+ const body = element('div', 'svhs-scroll');
20010
+ if (title) {
20011
+ const heading = element('h2', 'svhs-heading', title);
20012
+ heading.tabIndex = -1;
20013
+ body.append(heading);
20014
+ this.headings.set(stage, heading);
20015
+ }
20016
+ screen.append(body);
20017
+ this.panel.append(screen);
20018
+ this.screens.set(stage, screen);
20019
+ this.scrollers.set(stage, body);
20020
+ return body;
20021
+ }
20022
+ footer(stage, extraClass = '') {
20023
+ const footer = element('div', `svhs-bottom ${extraClass}`.trim());
20024
+ this.screens.get(stage).append(footer);
20025
+ return footer;
20026
+ }
20027
+ search() {
20028
+ if (this.state?.busy)
20029
+ return;
20030
+ if (!this.issue.value.trim()) {
20031
+ this.issueError.textContent = 'Tell us a little about what you need help with.';
20032
+ this.issueError.hidden = false;
20033
+ this.issue.setAttribute('aria-invalid', 'true');
20034
+ this.issue.focus();
20035
+ return;
20036
+ }
20037
+ this.issue.removeAttribute('aria-invalid');
20038
+ this.actions.onSearch(this.issue.value);
20039
+ }
20040
+ resizeIssue() {
20041
+ if (!this.issue.isConnected || this.issue.closest('[hidden]'))
20042
+ return;
20043
+ this.issue.style.height = 'auto';
20044
+ const maximum = this.media?.matches ? 260 : 200;
20045
+ if (this.issue.scrollHeight)
20046
+ this.issue.style.height = `${Math.min(this.issue.scrollHeight, maximum)}px`;
20047
+ }
20048
+ renderResults(state) {
20049
+ const results = state.results ?? [];
20050
+ const signature = JSON.stringify(results);
20051
+ if (signature !== this.resultSignature) {
20052
+ this.resultSignature = signature;
20053
+ this.resultList.replaceChildren();
20054
+ for (const result of results) {
20055
+ const item = element('li');
20056
+ const open = button('svhs-result', '', () => this.actions.onOpenArticle(result.id));
20057
+ open.append(element('span', 'svhs-result-title', result.title));
20058
+ if (result.summary)
20059
+ open.append(element('span', 'svhs-result-excerpt', result.summary));
20060
+ if (result.category)
20061
+ open.append(element('span', 'svhs-result-category', result.category));
20062
+ item.append(open);
20063
+ this.resultList.append(item);
20064
+ }
20065
+ }
20066
+ this.resultCopy.textContent = results.length === 1 ? `1 suggestion from the ${state.deskName} help center.` : `${results.length} suggestions from the ${state.deskName} help center.`;
20067
+ this.resultList.hidden = Boolean(state.busy) || state.kbState === 'locked' || state.kbState === 'unavailable';
20068
+ this.resultCopy.hidden = this.resultList.hidden || results.length === 0;
20069
+ this.resultError.textContent = state.stage === 'results' ? state.error || '' : '';
20070
+ this.resultError.hidden = !this.resultError.textContent;
20071
+ this.renderResultStatus(state, results);
20072
+ for (const control of this.resultStatus.querySelectorAll('button')) {
20073
+ control.setAttribute('aria-disabled', String(Boolean(state.busy)));
20074
+ control.setAttribute('aria-busy', String(Boolean(state.busy)));
20075
+ }
20076
+ this.contactResults.textContent = results.length > 0 && !this.resultList.hidden ? 'None of these help. Contact support' : 'Contact support';
20077
+ }
20078
+ renderResultStatus(state, results) {
20079
+ const signature = state.kbState === 'locked' ? `locked:${state.kbAccessMode}` : state.busy ? 'busy' : state.kbState === 'unavailable' ? 'unavailable' : results.length ? 'matches' : 'empty';
20080
+ if (signature === this.resultStatusSignature)
20081
+ return;
20082
+ this.resultStatusSignature = signature;
20083
+ this.resultStatus.replaceChildren();
20084
+ this.resultStatus.hidden = false;
20085
+ if (state.busy && state.kbState !== 'locked') {
20086
+ this.resultStatus.append(element('p', 'svhs-status', 'Looking for answers…'));
20087
+ this.resultStatus.setAttribute('role', 'status');
20088
+ }
20089
+ else if (state.kbState === 'locked') {
20090
+ this.resultStatus.removeAttribute('role');
20091
+ this.resultStatus.append(element('h3', 'svhs-heading', 'These articles are protected'));
20092
+ if (state.kbAccessMode === 'password' && this.actions.onUnlock) {
20093
+ this.resultStatus.append(element('p', 'svhs-copy', 'Enter the help center password to view articles, or contact support below.'));
20094
+ const form = element('form', 'svhs-unlock-form');
20095
+ const label = element('label', 'svhs-label', 'Help center password');
20096
+ const input = element('input', 'svhs-unlock-input');
20097
+ input.id = `${this.prefix}-password`;
20098
+ input.type = 'password';
20099
+ input.autocomplete = 'current-password';
20100
+ input.required = true;
20101
+ label.htmlFor = input.id;
20102
+ const submit = button('svhs-secondary svhs-full', 'View articles', () => undefined);
20103
+ submit.type = 'submit';
20104
+ form.addEventListener('submit', (event) => { event.preventDefault(); if (!this.state?.busy)
20105
+ this.actions.onUnlock?.(input.value); });
20106
+ form.append(label, input, submit);
20107
+ this.resultStatus.append(form);
20108
+ }
20109
+ else if (state.kbAccessMode === 'identity' && this.actions.onUnlock) {
20110
+ this.resultStatus.append(element('p', 'svhs-copy', 'Sign in to view the help center, or contact support below.'), button('svhs-secondary svhs-full', 'Sign in to view articles', () => { if (!this.state?.busy)
20111
+ this.actions.onUnlock?.(); }));
20112
+ }
20113
+ else {
20114
+ this.resultStatus.append(element('p', 'svhs-copy', 'The help center isn’t available from this network. You can still contact support below.'));
20115
+ }
20116
+ }
20117
+ else if (state.kbState === 'unavailable') {
20118
+ this.resultStatus.removeAttribute('role');
20119
+ this.resultStatus.append(element('h3', 'svhs-heading', 'We couldn’t load the help center'), element('p', 'svhs-copy', 'Try again, or send your question to support. Your message is saved here.'));
20120
+ if (this.actions.onRetry)
20121
+ this.resultStatus.append(button('svhs-secondary', 'Try again', () => this.actions.onRetry?.()));
20122
+ }
20123
+ else if (results.length === 0) {
20124
+ this.resultStatus.removeAttribute('role');
20125
+ this.resultStatus.append(element('h3', 'svhs-heading', 'No matching articles'), element('p', 'svhs-copy', 'Try describing your question a different way, or contact our support team.'));
20126
+ }
20127
+ else
20128
+ this.resultStatus.hidden = true;
20129
+ }
20130
+ renderArticle(state) {
20131
+ const article = state.article;
20132
+ const url = httpUrl(article?.canonical_url || state.articleUrl);
20133
+ this.external.hidden = state.stage !== 'article' || !url;
20134
+ this.articleFooter.hidden = !article || Boolean(state.busy) || Boolean(state.error);
20135
+ if (url)
20136
+ this.external.href = url.href;
20137
+ else
20138
+ this.external.removeAttribute('href');
20139
+ this.articleStatus.hidden = !state.busy;
20140
+ this.articleStatus.textContent = state.busy ? 'Loading article…' : '';
20141
+ this.articleError.textContent = state.stage === 'article' ? state.error || '' : '';
20142
+ this.articleError.hidden = !this.articleError.textContent;
20143
+ this.articleRetry.hidden = !this.articleError.textContent || Boolean(state.busy) || !this.actions.onRetry;
20144
+ this.articleContent.hidden = Boolean(state.busy);
20145
+ this.articleTitle.textContent = article?.title || (state.error ? 'We couldn’t load this article' : 'Help article');
20146
+ const category = state.results?.find((result) => result.id === article?.id)?.category;
20147
+ this.articleCategory.textContent = category || '';
20148
+ this.articleCategory.hidden = !category;
20149
+ const signature = article ? `${article.release_id}:${article.id}:${article.body_html}` : '';
20150
+ if (signature === this.articleSignature)
20151
+ return;
20152
+ this.articleSignature = signature;
20153
+ this.articleContent.replaceChildren();
20154
+ if (!article)
20155
+ return;
20156
+ // The platform owns Markdown rendering and sanitization. Keep this a
20157
+ // second boundary for executable markup and URLs, not a second renderer.
20158
+ const template = element('template');
20159
+ template.innerHTML = article.body_html;
20160
+ template.content.querySelectorAll('script,style,iframe,object,embed,form,input,button,textarea,select,link,meta,base,svg,math,template').forEach((node) => node.remove());
20161
+ for (const node of template.content.querySelectorAll('*')) {
20162
+ for (const attribute of [...node.attributes]) {
20163
+ if (/^on/i.test(attribute.name) || ['style', 'srcdoc', 'formaction', 'autofocus'].includes(attribute.name))
20164
+ node.removeAttribute(attribute.name);
20165
+ }
20166
+ if (node.id)
20167
+ node.id = `${this.prefix}-article-${node.id}`;
20168
+ if (node instanceof HTMLAnchorElement) {
20169
+ const href = node.getAttribute('href') || '';
20170
+ if (href.startsWith('#'))
20171
+ node.setAttribute('href', href);
20172
+ else if (/^(?:mailto:|tel:)/i.test(href)) {
20173
+ // The canonical reader permits explicit email and telephone links.
20174
+ // They invoke the customer's chosen app rather than another KB view.
20175
+ node.href = href;
20176
+ node.removeAttribute('target');
20177
+ node.rel = 'noopener noreferrer';
20178
+ }
20179
+ else {
20180
+ const link = httpUrl(href, article.canonical_url);
20181
+ if (!link)
20182
+ node.removeAttribute('href');
20183
+ else {
20184
+ node.href = link.href;
20185
+ node.target = '_blank';
20186
+ node.rel = 'noopener noreferrer';
20187
+ }
20188
+ }
20189
+ }
20190
+ if (node instanceof HTMLImageElement) {
20191
+ // KbClient authorizes and rewrites every publication asset to a
20192
+ // memory-only URL. Reader content cannot turn into a tracking pixel.
20193
+ if (!node.getAttribute('src')?.startsWith('blob:'))
20194
+ node.removeAttribute('src');
20195
+ node.removeAttribute('srcset');
20196
+ node.loading = 'lazy';
20197
+ if (node.getAttribute('data-kb-asset') && !node.hasAttribute('src')) {
20198
+ const frame = element('span', 'svhs-reader-asset');
20199
+ frame.setAttribute('aria-busy', 'true');
20200
+ const status = element('span', 'svhs-reader-asset-status', 'Loading image…');
20201
+ if (node.width > 0 && node.height > 0)
20202
+ status.style.aspectRatio = `${node.width}/${node.height}`;
20203
+ node.replaceWith(frame);
20204
+ frame.append(status, node);
20205
+ node.hidden = true;
20206
+ node.addEventListener('error', () => {
20207
+ if (!this.articleContent.contains(node) || !node.getAttribute('src')?.startsWith('blob:'))
20208
+ return;
20209
+ node.removeAttribute('src');
20210
+ node.hidden = true;
20211
+ this.setArticleAssetError(node.getAttribute('data-kb-asset'));
20212
+ });
20213
+ }
20214
+ }
20215
+ }
20216
+ this.articleContent.append(template.content);
20217
+ }
20218
+ articleLink(event) {
20219
+ if (!(event.target instanceof Element))
20220
+ return;
20221
+ const link = event.target.closest('a[href]');
20222
+ if (!link || !this.articleContent.contains(link))
20223
+ return;
20224
+ if (link.hasAttribute('data-svhs-canonical'))
20225
+ return;
20226
+ const href = link.getAttribute('href') || '';
20227
+ if (href.startsWith('#')) {
20228
+ event.preventDefault();
20229
+ let id;
20230
+ try {
20231
+ id = decodeURIComponent(href.slice(1));
20232
+ }
20233
+ catch {
20234
+ return;
20235
+ }
20236
+ const target = document.getElementById(`${this.prefix}-article-${id}`);
20237
+ if (!target || !this.articleContent.contains(target))
20238
+ return;
20239
+ const scroll = this.scrollers.get('article');
20240
+ scroll.scrollTop += target.getBoundingClientRect().top - scroll.getBoundingClientRect().top - 24;
20241
+ return;
20242
+ }
20243
+ const articleUrl = httpUrl(this.state?.article?.canonical_url);
20244
+ const targetUrl = httpUrl(href, articleUrl?.href);
20245
+ if (articleUrl && targetUrl?.origin === articleUrl.origin && this.actions.onArticleLink) {
20246
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0)
20247
+ return;
20248
+ event.preventDefault();
20249
+ this.actions.onArticleLink(targetUrl.href);
20250
+ }
20251
+ }
20252
+ renderReceipt(state) {
20253
+ const receipt = state.receipt;
20254
+ this.receiptCopy.replaceChildren(document.createTextNode(receipt?.email ? 'Your message has been sent. We’ll reply to ' : 'Your message has been sent.'));
20255
+ if (receipt?.email)
20256
+ this.receiptCopy.append(element('strong', '', receipt.email), document.createTextNode('.'));
20257
+ this.receiptTicket.textContent = receipt?.ticketNumber !== undefined ? `Ticket #${receipt.ticketNumber}` : '';
20258
+ const ticketUrl = httpUrl(receipt?.ticketUrl);
20259
+ this.receiptTicket.hidden = !receipt?.ticketNumber;
20260
+ if (ticketUrl)
20261
+ this.receiptTicket.href = ticketUrl.href;
20262
+ else
20263
+ this.receiptTicket.removeAttribute('href');
20264
+ this.receiptMessage.textContent = receipt?.message || '';
20265
+ this.receiptMessage.hidden = !receipt?.message;
20266
+ }
20267
+ renderTicketGate(state) {
20268
+ this.ticketGate.hidden = !state.ticketAccessRequired;
20269
+ this.contactTarget.hidden = Boolean(state.ticketAccessRequired);
20270
+ const signature = state.ticketAccessRequired ? `${state.ticketAccessMode}:${state.ticketPortalUrl || ''}` : '';
20271
+ if (signature !== this.ticketGateSignature) {
20272
+ this.ticketGateSignature = signature;
20273
+ this.ticketGate.replaceChildren();
20274
+ if (state.ticketAccessRequired && state.ticketAccessMode === 'password') {
20275
+ this.ticketGate.append(element('p', 'svhs-copy', 'This support desk is password protected. Enter its password to continue. Your message is saved here.'));
20276
+ const form = element('form', 'svhs-unlock-form');
20277
+ const input = element('input', 'svhs-unlock-input');
20278
+ input.id = `${this.prefix}-ticket-password`;
20279
+ input.name = 'support-password';
20280
+ input.type = 'password';
20281
+ input.autocomplete = 'current-password';
20282
+ input.required = true;
20283
+ input.setAttribute('aria-describedby', this.contactError.id);
20284
+ const label = element('label', 'svhs-label', 'Ticket portal password');
20285
+ label.htmlFor = input.id;
20286
+ const submit = button('svhs-primary svhs-full', 'Continue', () => undefined);
20287
+ submit.type = 'submit';
20288
+ form.addEventListener('submit', (event) => {
20289
+ event.preventDefault();
20290
+ if (!this.state?.busy)
20291
+ this.actions.onUnlockTicketAccess?.(input.value);
20292
+ });
20293
+ form.append(label, input, submit);
20294
+ this.ticketGate.append(form);
20295
+ }
20296
+ else if (state.ticketAccessRequired && state.ticketAccessMode === 'identity') {
20297
+ this.ticketGate.append(element('p', 'svhs-copy', 'This support desk is for employees. Sign in with your employee email to continue. Your message is saved here.'), button('svhs-primary svhs-full', 'Sign in with employee email', () => { if (!this.state?.busy)
20298
+ this.actions.onUnlockTicketAccess?.(); }));
20299
+ }
20300
+ else if (state.ticketAccessRequired) {
20301
+ this.ticketGate.append(element('p', 'svhs-copy', 'Connect to an approved network to contact support. Your message is saved here.'), button('svhs-secondary svhs-full', 'Check access again', () => { if (!this.state?.busy)
20302
+ this.actions.onRetry?.(); }));
20303
+ }
20304
+ const portal = httpUrl(state.ticketPortalUrl);
20305
+ if (state.ticketAccessRequired && portal) {
20306
+ const link = element('a', 'svhs-text-button', 'Open support in a new tab');
20307
+ link.href = portal.href;
20308
+ link.target = '_blank';
20309
+ link.rel = 'noopener noreferrer';
20310
+ this.ticketGate.append(link);
20311
+ }
20312
+ }
20313
+ for (const control of this.ticketGate.querySelectorAll('button')) {
20314
+ control.setAttribute('aria-disabled', String(Boolean(state.busy)));
20315
+ control.setAttribute('aria-busy', String(Boolean(state.busy)));
20316
+ }
20317
+ }
20318
+ syncPresentation() {
20319
+ if (this.destroyed)
20320
+ return;
20321
+ this.phoneHistory?.sync(Boolean(this.state?.visible), Boolean(this.media?.matches));
20322
+ const active = this.panel.contains(document.activeElement) && document.activeElement instanceof HTMLElement ? document.activeElement : null;
20323
+ if (!this.state?.visible) {
20324
+ this.hide();
20325
+ return;
20326
+ }
20327
+ if (this.panel.hidden)
20328
+ this.opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
20329
+ this.panel.hidden = false;
20330
+ if (this.media?.matches) {
20331
+ if (!this.shell) {
20332
+ this.panel.removeAttribute('role');
20333
+ this.panel.removeAttribute('aria-modal');
20334
+ this.shell = new ModalShell({
20335
+ overlayId: `${this.prefix}-overlay`, modalId: `${this.prefix}-modal`, classPrefix: 'svhs',
20336
+ titleId: this.panel.getAttribute('aria-labelledby'), backdropBlur: false, onDismiss: () => this.actions.onClose(),
20337
+ });
20338
+ this.shell.modal.append(this.panel);
20339
+ active?.focus({ preventScroll: true });
20340
+ }
20341
+ }
20342
+ else {
20343
+ if (this.shell) {
20344
+ document.body.append(this.panel);
20345
+ this.shell.destroy();
20346
+ this.shell = null;
20347
+ active?.focus({ preventScroll: true });
20348
+ }
20349
+ else if (!this.panel.isConnected)
20350
+ document.body.append(this.panel);
20351
+ this.panel.setAttribute('role', 'dialog');
20352
+ this.panel.setAttribute('aria-modal', 'false');
20353
+ }
20354
+ this.resizeIssue();
20355
+ this.shell?.overlay.setAttribute('aria-labelledby', this.panel.getAttribute('aria-labelledby'));
20356
+ this.syncViewport();
20357
+ }
20358
+ syncViewport() {
20359
+ const viewport = window.visualViewport;
20360
+ if (!this.shell || !viewport)
20361
+ return;
20362
+ // Mobile keyboards shrink the visual viewport without always resizing
20363
+ // the CSS viewport. Keep the support actions above that keyboard. Zoom
20364
+ // remains the browser's own: never resize content to cancel its scale.
20365
+ if (viewport.scale === 1) {
20366
+ this.shell.overlay.style.top = `${viewport.offsetTop}px`;
20367
+ this.shell.overlay.style.height = `${viewport.height}px`;
20368
+ this.shell.overlay.style.bottom = 'auto';
20369
+ }
20370
+ else {
20371
+ this.shell.overlay.style.top = '';
20372
+ this.shell.overlay.style.height = '';
20373
+ this.shell.overlay.style.bottom = '';
20374
+ }
20375
+ }
20376
+ hide() {
20377
+ const wasVisible = !this.panel.hidden;
20378
+ this.panel.hidden = true;
20379
+ if (this.shell) {
20380
+ this.panel.remove();
20381
+ this.shell.destroy();
20382
+ this.shell = null;
20383
+ }
20384
+ this.panel.remove();
20385
+ if (wasVisible && this.opener?.isConnected)
20386
+ this.opener.focus({ preventScroll: true });
20387
+ }
20388
+ scrollKey(state) {
20389
+ return state.stage === 'article' ? `article:${state.article?.release_id}:${state.article?.id}` : state.stage;
20390
+ }
20391
+ saveScroll(state) {
20392
+ const scroll = this.scrollers.get(state.stage);
20393
+ if (scroll && state.visible)
20394
+ this.scrollPositions.set(this.scrollKey(state), scroll.scrollTop);
20395
+ }
20396
+ restoreScroll(state) {
20397
+ const scroll = this.scrollers.get(state.stage);
20398
+ if (scroll)
20399
+ scroll.scrollTop = this.scrollPositions.get(this.scrollKey(state)) ?? 0;
20400
+ }
20401
+ focusCurrent() {
20402
+ if (!this.state?.visible)
20403
+ return;
20404
+ if (this.state.stage === 'issue') {
20405
+ (this.media?.matches ? this.close : this.issue).focus({ preventScroll: true });
20406
+ }
20407
+ else if (this.state.stage === 'contact')
20408
+ this.focusContact();
20409
+ else
20410
+ (this.headings.get(this.state.stage) ?? this.panel).focus({ preventScroll: true });
20411
+ }
20412
+ }
20413
+
20414
+ function notify(callback, value) {
20415
+ try {
20416
+ void Promise.resolve(callback?.(value)).catch(() => undefined);
20417
+ }
20418
+ catch { /* Host callbacks do not own support state. */ }
20419
+ }
20420
+ function failure(value) { return value instanceof Error ? value : new Error('Support could not be loaded. Please try again.'); }
20421
+ function errorCode(value) { return value instanceof SparkVaultError ? value.serviceCode ?? value.code : undefined; }
20422
+ /** One state machine owns launcher, host links, KB suggestions and the ticket front door. */
20423
+ function createHelpDeskSupport(config, options) {
20424
+ if (typeof document === 'undefined' || !document.body)
20425
+ throw new ValidationError('Create support after the document body is available.');
20426
+ let destroyed = false;
20427
+ let sequence = 0;
20428
+ let connected = null;
20429
+ let client = null;
20430
+ let kb = null;
20431
+ let kbConfig = null;
20432
+ let contact = null;
20433
+ let contactCustomer = null;
20434
+ let contactOpening = false;
20435
+ let pendingComposition = null;
20436
+ let nativeIdentity = null;
20437
+ let switchedAccount = false;
20438
+ let attempt = null;
20439
+ let results = [];
20440
+ let requestedArticle = null;
20441
+ let articleRetrySearch = false;
20442
+ let cancelArticleAssets = null;
20443
+ const lifetime = new AbortController();
20444
+ const bindings = new Set();
20445
+ let state = { visible: false, stage: 'issue', deskName: 'Support', issue: '' };
20446
+ if (typeof options.launcher === 'object') {
20447
+ const offset = (value, fallback) => typeof value === 'number' && Number.isFinite(value) ? Math.min(240, Math.max(12, value)) : fallback;
20448
+ state.position = { right: offset(options.launcher.right, 24), bottom: offset(options.launcher.bottom, 24) + 72 };
20449
+ }
20450
+ const http = new HttpClient({ ...config, accessToken: undefined, getAccessToken: undefined, apiKey: undefined });
20451
+ const analytics = createSupportAnalytics({
20452
+ deskId: config.accountId,
20453
+ post: async (path, body) => {
20454
+ if (destroyed)
20455
+ throw new Error('Support is closed.');
20456
+ const prefix = `/hd/desks/${encodeURIComponent(config.accountId)}/support`;
20457
+ const suffix = path.slice(prefix.length);
20458
+ if (!path.startsWith(prefix))
20459
+ throw new Error('Invalid support analytics route.');
20460
+ const event = /^\/attempts\/([^/]+)\/events$/.exec(suffix);
20461
+ const route = suffix === '/visitor' ? apiPath `/v1/hd/desks/${config.accountId}/support/visitor`
20462
+ : suffix === '/attempts' ? apiPath `/v1/hd/desks/${config.accountId}/support/attempts`
20463
+ : event ? apiPath `/v1/hd/desks/${config.accountId}/support/attempts/${decodeURIComponent(event[1])}/events` : null;
20464
+ if (!route)
20465
+ throw new Error('Invalid support analytics route.');
20466
+ const headers = kb?.getAccessHeaders() ?? {};
20467
+ return (await http.request(route, { method: 'POST', body, credentials: 'omit', headers: { 'X-SV-Client': 'help-desk-portal', ...headers } })).data;
20468
+ },
20469
+ });
20470
+ const view = new SupportView({
20471
+ onIssueChange: (issue) => { state.issue = issue; },
20472
+ onSearch: (issue) => { void search(issue); },
20473
+ onContact: (reason) => { void showContact(reason); },
20474
+ onOpenArticle: (id) => { void openArticle(id); },
20475
+ onArticleLink: (url) => { void followArticle(url); },
20476
+ onBack: () => {
20477
+ if (destroyed || state.navigationLocked || state.identityPending)
20478
+ return;
20479
+ if (state.busy) {
20480
+ sequence += 1;
20481
+ contactOpening = false;
20482
+ }
20483
+ update({ busy: false });
20484
+ if (state.stage === 'feedback')
20485
+ update({ stage: 'article', error: undefined });
20486
+ else if (state.stage === 'article') {
20487
+ cancelArticleAssets?.();
20488
+ cancelArticleAssets = null;
20489
+ update({ stage: 'results', error: undefined, article: undefined, articleUrl: undefined });
20490
+ }
20491
+ else if (state.stage === 'contact')
20492
+ update({ stage: results.length || kbConfig ? 'results' : 'issue', error: undefined });
20493
+ else
20494
+ update({ stage: 'issue', error: undefined });
20495
+ },
20496
+ onClose: () => {
20497
+ if (state.stage === 'article' && state.article)
20498
+ update({ stage: 'feedback', error: undefined });
20499
+ else {
20500
+ if (state.stage === 'feedback')
20501
+ update({ stage: 'article' });
20502
+ minimize();
20503
+ }
20504
+ },
20505
+ onAnswered: () => {
20506
+ if (destroyed || !state.article)
20507
+ return;
20508
+ void attempt?.then((active) => active?.solved());
20509
+ contact?.destroy();
20510
+ contact = null;
20511
+ contactCustomer = null;
20512
+ cancelArticleAssets?.();
20513
+ cancelArticleAssets = null;
20514
+ minimize();
20515
+ view.showToast('We’re happy we could help.');
20516
+ sequence += 1;
20517
+ attempt = null;
20518
+ results = [];
20519
+ state = { visible: false, stage: 'issue', deskName: state.deskName, issue: '', position: state.position };
20520
+ update({});
20521
+ },
20522
+ onRestart: () => {
20523
+ contact?.destroy();
20524
+ contact = null;
20525
+ contactCustomer = null;
20526
+ cancelArticleAssets?.();
20527
+ cancelArticleAssets = null;
20528
+ sequence += 1;
20529
+ attempt = null;
20530
+ results = [];
20531
+ requestedArticle = null;
20532
+ pendingComposition = null;
20533
+ update({ stage: 'issue', issue: '', results: [], article: undefined, receipt: undefined, error: undefined, busy: false });
20534
+ },
20535
+ onRetry: () => {
20536
+ if (state.stage === 'contact')
20537
+ void showContact('direct');
20538
+ else if (state.stage === 'article' && articleRetrySearch)
20539
+ void search(state.issue);
20540
+ else if (state.stage === 'article' && requestedArticle)
20541
+ void readArticle(requestedArticle);
20542
+ else
20543
+ void search(state.issue);
20544
+ },
20545
+ onUnlock: (password) => { void unlock(password); },
20546
+ onUnlockTicketAccess: (password) => { void unlockTicketAccess(password); },
20547
+ onCancelIdentity: () => nativeIdentity?.abort(),
20548
+ onBrowserBack: minimize,
20549
+ onBrowserForward: () => update({ visible: true }),
20550
+ });
20551
+ const launcher = (() => {
20552
+ try {
20553
+ return options.launcher ? createSupportLauncher(typeof options.launcher === 'object' ? options.launcher : {}, () => { void open(); }) : null;
20554
+ }
20555
+ catch (error) {
20556
+ view.destroy();
20557
+ analytics.dispose();
20558
+ throw error;
20559
+ }
20560
+ })();
20561
+ function snapshot() { return { visible: state.visible, stage: state.stage, busy: state.busy === true }; }
20562
+ function update(change) {
20563
+ if (destroyed)
20564
+ return;
20565
+ state = { ...state, ...change };
20566
+ view.render(state);
20567
+ launcher?.setExpanded(state.visible);
20568
+ notify(options.onStateChange, snapshot());
20569
+ }
20570
+ async function connect() {
20571
+ if (!connected)
20572
+ connected = HelpDeskClient.connect(config, options).then((answer) => {
20573
+ if (destroyed)
20574
+ throw new Error('Support is closed.');
20575
+ client = answer;
20576
+ kb = new HelpDeskKnowledgeBaseClient(config, answer.desk.desk_id);
20577
+ update({ deskName: answer.desk.organization_name || 'Support' });
20578
+ return answer;
20579
+ }).catch((error) => { connected = null; throw error; });
20580
+ return connected;
20581
+ }
20582
+ async function open(input = {}) {
20583
+ if (destroyed)
20584
+ return;
20585
+ if (state.stage === 'issue' && !state.issue && input.issue)
20586
+ state.issue = input.issue.slice(0, 12000);
20587
+ update({ visible: true });
20588
+ try {
20589
+ await connect();
20590
+ }
20591
+ catch (value) {
20592
+ if (!destroyed) {
20593
+ const error = failure(value);
20594
+ update({ error: error.message });
20595
+ notify(options.onError, error);
20596
+ }
20597
+ }
20598
+ }
20599
+ function minimize() { update({ visible: false }); }
20600
+ function signIn(input = {}) {
20601
+ if (!client)
20602
+ return Promise.reject(new Error('Support is still loading. Please try again.'));
20603
+ nativeIdentity?.abort();
20604
+ const operation = new AbortController();
20605
+ nativeIdentity = operation;
20606
+ const cancel = () => operation.abort();
20607
+ lifetime.signal.addEventListener('abort', cancel, { once: true });
20608
+ // This call must remain synchronous with the invoking user gesture.
20609
+ const result = client.signInWidgetIdentity({ ...input, signal: operation.signal });
20610
+ update({ identityPending: true });
20611
+ return result.finally(() => {
20612
+ lifetime.signal.removeEventListener('abort', cancel);
20613
+ if (nativeIdentity === operation) {
20614
+ nativeIdentity = null;
20615
+ update({ identityPending: false });
20616
+ }
20617
+ });
20618
+ }
20619
+ function startAttempt(available, releaseId, resultCount) {
20620
+ if (!attempt)
20621
+ attempt = available && releaseId !== undefined && resultCount !== undefined
20622
+ ? analytics.start({ availability: 'available', releaseId, resultCount })
20623
+ : analytics.start({ availability: 'unavailable' });
20624
+ return attempt;
20625
+ }
20626
+ async function search(issue) {
20627
+ if (destroyed || !issue.trim())
20628
+ return;
20629
+ const ownSequence = ++sequence;
20630
+ update({ stage: 'results', issue: issue.slice(0, 12000), busy: true, error: undefined, results: [], article: undefined, kbState: undefined });
20631
+ results = [];
20632
+ try {
20633
+ const active = await connect();
20634
+ if (destroyed || ownSequence !== sequence)
20635
+ return;
20636
+ if (!active.desk.knowledge_base_enabled) {
20637
+ update({ busy: false, kbState: 'unavailable' });
20638
+ await showContact('direct');
20639
+ return;
20640
+ }
20641
+ kbConfig = await kb.load();
20642
+ if (destroyed || ownSequence !== sequence)
20643
+ return;
20644
+ if (!kbConfig.available || !kbConfig.search_enabled) {
20645
+ update({ busy: false, kbState: 'unavailable' });
20646
+ await showContact('direct');
20647
+ return;
20648
+ }
20649
+ if (!kbConfig.authorized) {
20650
+ update({ busy: false, kbState: 'locked', kbAccessMode: kbConfig.access.mode === 'public' ? undefined : kbConfig.access.mode });
20651
+ return;
20652
+ }
20653
+ const answer = await kb.search(state.issue);
20654
+ if (destroyed || ownSequence !== sequence)
20655
+ return;
20656
+ results = answer.results;
20657
+ update({ busy: false, results, kbState: results.length ? 'ready' : 'empty' });
20658
+ startAttempt(true, answer.release_id, results.length);
20659
+ }
20660
+ catch (value) {
20661
+ if (destroyed || ownSequence !== sequence)
20662
+ return;
20663
+ const error = failure(value);
20664
+ const locked = ['KB_ACCESS_REQUIRED', 'KB_IP_RESTRICTED'].includes(errorCode(value) ?? '');
20665
+ update({ busy: false, kbState: locked ? 'locked' : 'unavailable', kbAccessMode: kbConfig?.access.mode === 'public' ? undefined : kbConfig?.access.mode, error: error.message });
20666
+ notify(options.onError, error);
20667
+ }
20668
+ }
20669
+ async function unlock(password) {
20670
+ if (destroyed || !kb || state.busy)
20671
+ return;
20672
+ const ownSequence = ++sequence;
20673
+ update({ busy: true, error: undefined });
20674
+ try {
20675
+ if (password !== undefined)
20676
+ await kb.unlock({ password });
20677
+ else {
20678
+ // A platform grant proves employee access independently of the host's ticket identity.
20679
+ if (!client)
20680
+ throw new Error('Support is still loading. Please try again.');
20681
+ const session = await signIn({ employeeCompanyId: kbConfig?.access.company_id });
20682
+ await kb.unlock({ identity_grant: session.identity_grant.token });
20683
+ }
20684
+ if (destroyed || ownSequence !== sequence)
20685
+ return;
20686
+ await search(state.issue);
20687
+ }
20688
+ catch (value) {
20689
+ if (destroyed || ownSequence !== sequence)
20690
+ return;
20691
+ const error = failure(value);
20692
+ update({ busy: false, error: error.message });
20693
+ notify(options.onError, error);
20694
+ }
20695
+ }
20696
+ async function readArticle(result) {
20697
+ cancelArticleAssets?.();
20698
+ cancelArticleAssets = null;
20699
+ requestedArticle = result;
20700
+ articleRetrySearch = false;
20701
+ const ownSequence = ++sequence;
20702
+ update({ stage: 'article', busy: true, error: undefined, article: undefined, articleUrl: result.canonical_url });
20703
+ try {
20704
+ const article = await kb.read(result);
20705
+ if (destroyed || ownSequence !== sequence)
20706
+ return;
20707
+ update({ article, busy: false });
20708
+ cancelArticleAssets = kb.hydrateAssets(article, {
20709
+ onAsset: (path, url) => { if (!destroyed && ownSequence === sequence && state.article?.id === article.id)
20710
+ view.setArticleAsset(path, url); },
20711
+ onError: (path) => { if (!destroyed && ownSequence === sequence && state.article?.id === article.id)
20712
+ view.setArticleAssetError(path); },
20713
+ });
20714
+ void attempt?.then((active) => active?.articleOpened(article.id, article.release_id));
20715
+ }
20716
+ catch (value) {
20717
+ if (destroyed || ownSequence !== sequence)
20718
+ return;
20719
+ const error = failure(value);
20720
+ articleRetrySearch = ['KB_PUBLICATION_CHANGED', 'KB_DOCUMENT_NOT_FOUND', 'KB_ACCESS_REQUIRED', 'KB_IP_RESTRICTED'].includes(errorCode(error) ?? '');
20721
+ update({ busy: false, error: error.message });
20722
+ notify(options.onError, error);
20723
+ }
20724
+ }
20725
+ async function openArticle(id) {
20726
+ const result = results.find((candidate) => candidate.id === id);
20727
+ if (result && kb)
20728
+ await readArticle(result);
20729
+ }
20730
+ async function followArticle(url) {
20731
+ if (!kb || destroyed)
20732
+ return;
20733
+ const ownSequence = sequence;
20734
+ try {
20735
+ const result = await kb.resolveLink(url);
20736
+ if (destroyed || ownSequence !== sequence)
20737
+ return;
20738
+ if (result)
20739
+ await readArticle(result);
20740
+ else
20741
+ window.open(url, '_blank', 'noopener,noreferrer');
20742
+ }
20743
+ catch (value) {
20744
+ const error = failure(value);
20745
+ update({ error: error.message });
20746
+ notify(options.onError, error);
20747
+ }
20748
+ }
20749
+ function mountContact(composition, customer) {
20750
+ if (!client || destroyed)
20751
+ return;
20752
+ contactCustomer = customer;
20753
+ let activeAttempt = null;
20754
+ contact = mountHelpDeskForm(client, {
20755
+ target: view.contactTarget,
20756
+ ...composition,
20757
+ attachments: options.attachments,
20758
+ widgetIdentity: {
20759
+ customer,
20760
+ signIn: (input) => signIn(input).then((session) => { contactCustomer = session.customer; return session; }),
20761
+ switchAccount: (safe) => { void switchAccount(safe); },
20762
+ ...(switchedAccount && (options.getSessionToken || options.getIdentityAssertion || options.identityEndpoint) ? { useWebsiteAccount: (safe) => { void useWebsiteAccount(safe); } } : {}),
20763
+ },
20764
+ assistanceContext: () => activeAttempt?.ticketContext(),
20765
+ onError: (error) => {
20766
+ notify(options.onError, error);
20767
+ if (['HELP_DESK_ACCESS_REQUIRED', 'HELP_DESK_IP_DENIED'].includes(errorCode(error) ?? ''))
20768
+ window.queueMicrotask(() => {
20769
+ void client?.refreshTicketAccessPolicy().catch(() => undefined).then(() => {
20770
+ if (destroyed || contact !== activeForm)
20771
+ return;
20772
+ const policy = client?.ticketAccessPolicy;
20773
+ update({ ticketAccessRequired: true, ticketAccessMode: policy?.mode === 'public' ? undefined : policy?.mode,
20774
+ ticketPortalUrl: `https://${client.desk.canonical_host}/requests/new`, error: error.message });
20775
+ });
20776
+ });
20777
+ },
20778
+ onCancel: () => { contact = null; minimize(); },
20779
+ onSuccess: (ticket) => receipt(ticket),
20780
+ onStateChange: (next) => update({ navigationLocked: ['authenticating', 'submitting', 'uncertain'].includes(next) }),
20781
+ });
20782
+ const activeForm = contact;
20783
+ void attempt?.then((active) => {
20784
+ // Keep the mutable callback small: an analytics response arriving late
20785
+ // must not delay contact, authentication or ticket submission.
20786
+ if (contact === activeForm && active)
20787
+ activeAttempt = active;
20788
+ });
20789
+ view.focusContact();
20790
+ }
20791
+ async function showContact(reason) {
20792
+ if (destroyed || contactOpening)
20793
+ return;
20794
+ cancelArticleAssets?.();
20795
+ cancelArticleAssets = null;
20796
+ if (reason === 'direct' && state.kbState === 'unavailable' && !attempt) {
20797
+ void startAttempt(false).then((active) => active?.contactRequested());
20798
+ }
20799
+ if (reason !== 'direct')
20800
+ void attempt?.then((active) => active?.contactRequested(reason));
20801
+ update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: undefined });
20802
+ contactOpening = true;
20803
+ const ownSequence = ++sequence;
20804
+ try {
20805
+ const active = await connect();
20806
+ await active.refreshTicketAccessPolicy();
20807
+ if (destroyed || ownSequence !== sequence)
20808
+ return;
20809
+ if (!active.hasTicketAccess) {
20810
+ const policy = active.ticketAccessPolicy;
20811
+ update({ busy: false, ticketAccessRequired: true, ticketAccessMode: policy?.mode === 'public' ? undefined : policy?.mode,
20812
+ ticketPortalUrl: `https://${active.desk.canonical_host}/requests/new` });
20813
+ return;
20814
+ }
20815
+ if (contact) {
20816
+ contact.resumeAfterAccess();
20817
+ update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
20818
+ view.focusContact();
20819
+ return;
20820
+ }
20821
+ const token = await active.getSessionToken();
20822
+ const customer = token ? await active.getMe() : null;
20823
+ if (destroyed || ownSequence !== sequence)
20824
+ return;
20825
+ update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
20826
+ mountContact(pendingComposition ?? { subject: state.issue.trim().split(/\n|(?<=[.!?])\s/)[0].slice(0, 200), body: state.issue }, customer);
20827
+ pendingComposition = null;
20828
+ }
20829
+ catch (value) {
20830
+ if (destroyed || ownSequence !== sequence)
20831
+ return;
20832
+ const error = failure(value);
20833
+ const gate = ['HELP_DESK_ACCESS_REQUIRED', 'HELP_DESK_IP_DENIED'].includes(errorCode(error) ?? '');
20834
+ update({ busy: false, error: error.message, ...(gate && { ticketAccessRequired: true,
20835
+ ticketAccessMode: client?.ticketAccessPolicy?.mode === 'public' ? undefined : client?.ticketAccessPolicy?.mode,
20836
+ ticketPortalUrl: `https://${client.desk.canonical_host}/requests/new` }) });
20837
+ notify(options.onError, error);
20838
+ }
20839
+ finally {
20840
+ if (ownSequence === sequence)
20841
+ contactOpening = false;
20842
+ }
20843
+ }
20844
+ async function unlockTicketAccess(password) {
20845
+ if (destroyed || !client || state.busy)
20846
+ return;
20847
+ const ownSequence = ++sequence;
20848
+ const active = client;
20849
+ const policy = active.ticketAccessPolicy;
20850
+ // Native Identity must be invoked before the first await in this gesture.
20851
+ const identity = policy?.mode === 'identity' ? signIn({ employeeCompanyId: policy.company_id }) : null;
20852
+ update({ busy: true, error: undefined });
20853
+ try {
20854
+ if (policy?.mode === 'password')
20855
+ await active.unlockTicketAccess({ password });
20856
+ else if (identity) {
20857
+ const session = await identity;
20858
+ await active.unlockTicketAccess({ identityGrant: session.identity_grant.token });
20859
+ const hostToken = await active.getSessionToken();
20860
+ if (!hostToken)
20861
+ active.setSession(session);
20862
+ }
20863
+ else
20864
+ throw new Error('Connect to an approved network, then try again.');
20865
+ if (destroyed || ownSequence !== sequence)
20866
+ return;
20867
+ update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
20868
+ await showContact('direct');
20869
+ }
20870
+ catch (value) {
20871
+ if (destroyed || ownSequence !== sequence)
20872
+ return;
20873
+ const error = failure(value);
20874
+ update({ busy: false, error: error.message });
20875
+ notify(options.onError, error);
20876
+ }
20877
+ }
20878
+ async function switchAccount(composition) {
20879
+ if (!client || destroyed || state.navigationLocked)
20880
+ return;
20881
+ const ownSequence = ++sequence;
20882
+ const active = client;
20883
+ contact?.destroy();
20884
+ contact = null;
20885
+ cancelArticleAssets?.();
20886
+ cancelArticleAssets = null;
20887
+ pendingComposition = composition ?? { subject: '', body: '' };
20888
+ kb?.clearAccess();
20889
+ kbConfig = null;
20890
+ results = [];
20891
+ requestedArticle = null;
20892
+ attempt = null;
20893
+ update({ results: [], article: undefined, articleUrl: undefined, kbState: undefined });
20894
+ switchedAccount = true;
20895
+ const logout = active.switchSupportAccount();
20896
+ // Open synchronously in the Not you? gesture, before awaiting revocation.
20897
+ const signingIn = signIn({ selectAccount: true, employeeCompanyId: active.ticketAccessPolicy?.mode === 'identity' ? active.ticketAccessPolicy.company_id : undefined });
20898
+ update({ stage: 'contact', busy: true, error: undefined });
20899
+ try {
20900
+ const [, session] = await Promise.all([logout, signingIn]);
20901
+ if (destroyed || ownSequence !== sequence)
20902
+ return;
20903
+ if (active.ticketAccessPolicy?.mode === 'identity')
20904
+ await active.unlockTicketAccess({ identityGrant: session.identity_grant.token });
20905
+ if (destroyed || ownSequence !== sequence)
20906
+ return;
20907
+ active.setSession(session);
20908
+ update({ busy: false });
20909
+ await showContact('direct');
20910
+ }
20911
+ catch (value) {
20912
+ await logout.catch(() => undefined);
20913
+ if (destroyed || ownSequence !== sequence)
20914
+ return;
20915
+ const error = failure(value);
20916
+ update({ busy: false, error: error.message });
20917
+ if (active.hasTicketAccess) {
20918
+ mountContact(composition ?? { subject: '', body: '' }, null);
20919
+ pendingComposition = null;
20920
+ }
20921
+ else
20922
+ await showContact('direct');
20923
+ }
20924
+ }
20925
+ async function useWebsiteAccount(composition) {
20926
+ if (!client || destroyed || state.navigationLocked)
20927
+ return;
20928
+ const ownSequence = ++sequence;
20929
+ contact?.destroy();
20930
+ contact = null;
20931
+ cancelArticleAssets?.();
20932
+ cancelArticleAssets = null;
20933
+ pendingComposition = composition ?? { subject: '', body: '' };
20934
+ kb?.clearAccess();
20935
+ kbConfig = null;
20936
+ results = [];
20937
+ requestedArticle = null;
20938
+ attempt = null;
20939
+ update({ busy: true, error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
20940
+ try {
20941
+ await client.useWebsiteAccount();
20942
+ if (destroyed || ownSequence !== sequence)
20943
+ return;
20944
+ switchedAccount = false;
20945
+ update({ busy: false });
20946
+ await showContact('direct');
20947
+ }
20948
+ catch (value) {
20949
+ if (destroyed || ownSequence !== sequence)
20950
+ return;
20951
+ const error = failure(value);
20952
+ update({ busy: false, error: error.message });
20953
+ if (client.hasTicketAccess) {
20954
+ mountContact(composition ?? { subject: '', body: '' }, null);
20955
+ pendingComposition = null;
20956
+ }
20957
+ else
20958
+ await showContact('direct');
20959
+ }
20960
+ }
20961
+ function receipt(ticket) {
20962
+ const customer = contactCustomer;
20963
+ update({ stage: 'receipt', busy: false, error: undefined, receipt: {
20964
+ ticketNumber: ticket.number,
20965
+ ticketUrl: `https://${client.desk.canonical_host}/requests/${ticket.number}`,
20966
+ ...(customer?.email_updates === true && customer.email_verified !== false ? { email: customer.email } : {}),
20967
+ message: client.desk.ticket_confirmation_message ?? undefined,
20968
+ } });
20969
+ notify(options.onSuccess, ticket);
20970
+ // A completed journey must never reopen an old draft or its file authority.
20971
+ contact?.destroy();
20972
+ contact = null;
20973
+ contactCustomer = null;
20974
+ }
20975
+ return {
20976
+ open,
20977
+ close: () => { view.deactivateHistory(); minimize(); },
20978
+ getState: snapshot,
20979
+ attach(selector) {
20980
+ if (destroyed)
20981
+ return () => undefined;
20982
+ const detach = attachClickHandler(selector, (event) => { event.preventDefault(); void open(); });
20983
+ const cleanup = () => { detach(); bindings.delete(cleanup); };
20984
+ bindings.add(cleanup);
20985
+ return cleanup;
20986
+ },
20987
+ destroy() {
20988
+ if (destroyed)
20989
+ return;
20990
+ destroyed = true;
20991
+ sequence += 1;
20992
+ lifetime.abort();
20993
+ for (const cleanup of bindings)
20994
+ cleanup();
20995
+ contact?.destroy();
20996
+ contact = null;
20997
+ cancelArticleAssets?.();
20998
+ cancelArticleAssets = null;
20999
+ kb?.destroy();
21000
+ kb = null;
21001
+ analytics.dispose();
21002
+ launcher?.destroy();
21003
+ view.destroy();
21004
+ // Only this support client is cleared; the host site's sign-in is untouched.
21005
+ client?.clearTicketAccess();
21006
+ client?.setSession(null);
21007
+ client = null;
21008
+ state = { visible: false, stage: 'issue', deskName: 'Support', issue: '' };
21009
+ },
21010
+ };
21011
+ }
21012
+
21013
+ class HelpDeskModule {
21014
+ constructor(config) {
21015
+ this.config = config;
21016
+ }
21017
+ /** Resolve a configured desk host and obtain its customer-only, headless API. */
21018
+ connect(options) {
21019
+ return HelpDeskClient.connect(this.config, options);
21020
+ }
21021
+ /** Create one KB-first support front door, with an optional floating launcher. */
21022
+ createSupport(options) {
21023
+ return createHelpDeskSupport(this.config, options);
18223
21024
  }
18224
21025
  /**
18225
21026
  * Inject a ticket form, including email-code verification where the desk
@@ -22202,7 +25003,7 @@ class SparkVault {
22202
25003
  }
22203
25004
  /** Get the SDK version */
22204
25005
  static get version() {
22205
- return '15.2.0';
25006
+ return '15.3.0';
22206
25007
  }
22207
25008
  }
22208
25009
  if (typeof window !== 'undefined') {