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