@sparkvault/sdk-js 15.2.0 → 15.3.1

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