@asiyst/sdk 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,29 @@
1
1
  'use strict';
2
2
 
3
+ var THREE = require('three');
4
+ var FBXLoader_js = require('three/examples/jsm/loaders/FBXLoader.js');
5
+ var GLTFLoader_js = require('three/examples/jsm/loaders/GLTFLoader.js');
6
+
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var THREE__namespace = /*#__PURE__*/_interopNamespace(THREE);
26
+
3
27
  // src/errors/index.ts
4
28
  var AsiystError = class extends Error {
5
29
  constructor(code, message) {
@@ -73,7 +97,7 @@ var ALL_ACTION_KINDS = [
73
97
  // src/core/constants.ts
74
98
  function resolveSdkVersion() {
75
99
  {
76
- return "0.1.20";
100
+ return "0.1.22";
77
101
  }
78
102
  }
79
103
  var SDK_VERSION = resolveSdkVersion();
@@ -91,6 +115,7 @@ var AVATAR_VIEWPORT_PADDING = 12;
91
115
  var AVATAR_TARGET_GAP = 16;
92
116
  var WEBSITE_MAP_TEXT_LIMIT = 80;
93
117
  var CONFIG_CACHE_TTL_MS = 1e3 * 60 * 10;
118
+ var HEARTBEAT_INTERVAL_MS = 45e3;
94
119
 
95
120
  // src/security/selectors.ts
96
121
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -133,11 +158,12 @@ var ANCHORS = [
133
158
  "top-left"
134
159
  ];
135
160
  var PUBLIC_IDENTIFIER_PATTERN = /^(?=.{1,128}$)[A-Za-z0-9_][A-Za-z0-9_-]*$/;
161
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
136
162
  function isValidPublicIdentifier(value) {
137
163
  if (typeof value !== "string") return false;
138
164
  const trimmed = value.trim();
139
165
  if (!trimmed || trimmed.length > 128) return false;
140
- if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trimmed)) {
166
+ if (UUID_PATTERN.test(trimmed)) {
141
167
  return false;
142
168
  }
143
169
  return PUBLIC_IDENTIFIER_PATTERN.test(trimmed);
@@ -310,6 +336,12 @@ function fallbackConfig() {
310
336
  version: 0,
311
337
  avatarName: "Asiyst",
312
338
  avatar: "avatar_default",
339
+ avatarId: void 0,
340
+ assetUrl: void 0,
341
+ thumbnailUrl: void 0,
342
+ publishedVersion: void 0,
343
+ animations: [],
344
+ branding: void 0,
313
345
  size: 96,
314
346
  position: "bottom-right",
315
347
  animation: "friendly",
@@ -333,22 +365,69 @@ function fallbackConfig() {
333
365
  elementSelectors: {}
334
366
  };
335
367
  }
368
+ function parseAnimations(value) {
369
+ if (!Array.isArray(value)) return void 0;
370
+ const list = [];
371
+ for (const item of value) {
372
+ if (isRecord(item) && typeof item.name === "string") {
373
+ list.push({
374
+ id: typeof item.id === "string" ? sanitizeText(item.id, 64) : void 0,
375
+ name: sanitizeText(item.name, 64),
376
+ intent: typeof item.intent === "string" ? sanitizeText(item.intent, 64) : void 0,
377
+ clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
378
+ loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
379
+ durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
380
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
381
+ });
382
+ }
383
+ }
384
+ return list;
385
+ }
386
+ function parseBranding(value) {
387
+ if (!isRecord(value)) return void 0;
388
+ return {
389
+ siteLogoUrl: typeof value.siteLogoUrl === "string" ? value.siteLogoUrl : null
390
+ };
391
+ }
336
392
  function normalizeProjectConfig(raw) {
337
393
  const base = fallbackConfig();
338
394
  if (!isRecord(raw)) {
339
395
  return base;
340
396
  }
397
+ const rawAvatarRecord = isRecord(raw.avatar) ? raw.avatar : void 0;
398
+ const avatarId = asString(
399
+ raw.avatarId ?? rawAvatarRecord?.avatarId ?? rawAvatarRecord?.id,
400
+ "",
401
+ 128
402
+ ) || void 0;
403
+ const assetUrl = typeof raw.assetUrl === "string" ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" ? rawAvatarRecord.assetUrl : void 0;
404
+ const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
405
+ const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : void 0;
406
+ const animations = parseAnimations(raw.animations ?? rawAvatarRecord?.animations);
407
+ const branding = parseBranding(raw.branding);
408
+ const avatarName = asString(
409
+ raw.avatarName ?? rawAvatarRecord?.name,
410
+ base.avatarName,
411
+ 40
412
+ );
413
+ const avatar = typeof raw.avatar === "string" ? asString(raw.avatar, base.avatar, 64) : avatarId ?? base.avatar;
341
414
  const position = ANCHORS.includes(raw.position) ? raw.position : base.position;
342
415
  return {
343
416
  schemaVersion: CONFIG_SCHEMA_VERSION,
344
417
  version: asNumber(raw.version, base.version, 0, Number.MAX_SAFE_INTEGER),
345
- avatarName: asString(raw.avatarName, base.avatarName, 40),
346
- avatar: asString(raw.avatar, base.avatar, 64),
418
+ avatarName,
419
+ avatar,
420
+ avatarId,
421
+ assetUrl,
422
+ thumbnailUrl,
423
+ publishedVersion,
424
+ animations,
425
+ branding,
347
426
  size: asNumber(raw.size, base.size, 48, 220),
348
427
  position,
349
428
  voice: typeof raw.voice === "string" ? sanitizeText(raw.voice, 64) : void 0,
350
429
  animation: asString(raw.animation, base.animation ?? "friendly", 40),
351
- theme: { ...base.theme, ...parseTheme(raw.theme) },
430
+ theme: { ...base.theme, ...parseTheme(raw.theme ?? rawAvatarRecord?.theme) },
352
431
  personality: parsePersonality(raw.personality),
353
432
  behavior: { ...base.behavior, ...parseBehavior(raw.behavior) },
354
433
  mode: raw.mode === "assist" ? "assist" : "guided",
@@ -435,6 +514,12 @@ var HttpTransport = class {
435
514
  constructor(options) {
436
515
  this.options = options;
437
516
  }
517
+ getApiBaseUrl() {
518
+ return this.options.apiBaseUrl;
519
+ }
520
+ getAvatarId() {
521
+ return this.options.avatarId;
522
+ }
438
523
  async request(req) {
439
524
  const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
440
525
  const requestId = req.requestId || generateRequestId();
@@ -531,13 +616,17 @@ var HttpTransport = class {
531
616
 
532
617
  // src/communication/CloudClient.ts
533
618
  var CloudClient = class {
534
- constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId) {
619
+ constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
535
620
  this.transport = transport;
536
621
  this.projectId = projectId;
537
622
  this.publicKey = publicKey;
538
623
  this.runtimeAuth = runtimeAuth;
624
+ this.avatarId = avatarId;
539
625
  this.inFlightConversations = /* @__PURE__ */ new Map();
540
626
  this.sessionId = sessionId;
627
+ if (!this.avatarId && typeof transport.getAvatarId === "function") {
628
+ this.avatarId = transport.getAvatarId();
629
+ }
541
630
  }
542
631
  setSessionId(sessionId) {
543
632
  this.sessionId = sessionId;
@@ -551,6 +640,18 @@ var CloudClient = class {
551
640
  getConversationId() {
552
641
  return this.conversationId;
553
642
  }
643
+ getAvatarId() {
644
+ return this.avatarId;
645
+ }
646
+ setAvatarId(avatarId) {
647
+ this.avatarId = avatarId;
648
+ }
649
+ getApiBaseUrl() {
650
+ if (typeof this.transport.getApiBaseUrl === "function") {
651
+ return this.transport.getApiBaseUrl();
652
+ }
653
+ return DEFAULT_API_BASE_URL;
654
+ }
554
655
  async getAuthToken(capability) {
555
656
  if (!this.runtimeAuth) return void 0;
556
657
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
@@ -565,36 +666,119 @@ var CloudClient = class {
565
666
  return this.inFlightToken;
566
667
  }
567
668
  async fetchConfig() {
669
+ const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
670
+ const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
671
+ const baseUrl = this.getApiBaseUrl();
672
+ const resolveAssetUrls = (raw) => {
673
+ const canonicalBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
674
+ if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
675
+ const av = { ...raw.avatar };
676
+ if (typeof av.assetUrl === "string" && av.assetUrl.startsWith("/")) {
677
+ av.assetUrl = new URL(av.assetUrl, canonicalBase).href;
678
+ }
679
+ if (typeof av.thumbnailUrl === "string" && av.thumbnailUrl.startsWith("/")) {
680
+ av.thumbnailUrl = new URL(av.thumbnailUrl, canonicalBase).href;
681
+ }
682
+ if (Array.isArray(av.animations)) {
683
+ av.animations = av.animations.map((item) => {
684
+ if (item && typeof item === "object") {
685
+ const animObj = item;
686
+ if (typeof animObj.assetUrl === "string" && animObj.assetUrl.startsWith("/")) {
687
+ return { ...animObj, assetUrl: new URL(animObj.assetUrl, canonicalBase).href };
688
+ }
689
+ }
690
+ return item;
691
+ });
692
+ }
693
+ raw.avatar = av;
694
+ }
695
+ if (typeof raw.assetUrl === "string" && raw.assetUrl.startsWith("/")) {
696
+ raw.assetUrl = new URL(raw.assetUrl, canonicalBase).href;
697
+ }
698
+ if (typeof raw.thumbnailUrl === "string" && raw.thumbnailUrl.startsWith("/")) {
699
+ raw.thumbnailUrl = new URL(raw.thumbnailUrl, canonicalBase).href;
700
+ }
701
+ if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
702
+ const br = { ...raw.branding };
703
+ if (typeof br.siteLogoUrl === "string" && br.siteLogoUrl.startsWith("/")) {
704
+ br.siteLogoUrl = new URL(br.siteLogoUrl, canonicalBase).href;
705
+ }
706
+ raw.branding = br;
707
+ }
708
+ return raw;
709
+ };
710
+ let lastError;
568
711
  try {
569
712
  const response = await this.runtimeRequest({
570
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
713
+ path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
571
714
  method: "GET",
572
715
  idempotent: true
573
716
  });
574
717
  if (response.ok && response.data) {
575
- return normalizeProjectConfig(response.data.config ?? response.data);
718
+ const dataObj = response.data.config ?? response.data;
719
+ return normalizeProjectConfig(resolveAssetUrls(dataObj));
576
720
  }
577
- } catch {
721
+ if (response.status === 404) {
722
+ lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
723
+ }
724
+ } catch (err) {
725
+ if (err instanceof Error) lastError = err;
726
+ }
727
+ try {
728
+ const runtimeResponse = await this.runtimeRequest({
729
+ path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
730
+ method: "GET",
731
+ idempotent: true
732
+ });
733
+ if (runtimeResponse.ok && runtimeResponse.data) {
734
+ return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
735
+ }
736
+ if (runtimeResponse.status === 404) {
737
+ lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
738
+ }
739
+ } catch (err) {
740
+ if (err instanceof Error) lastError = err;
578
741
  }
579
742
  try {
580
- const res = await fetch(`https://asiyst.com/api/v1/runtime/avatar?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}`, {
581
- headers: { Accept: "application/json" }
743
+ const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
744
+ const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
745
+ const res = await fetch(fullUrl, {
746
+ headers: {
747
+ Accept: "application/json",
748
+ "x-asiyst-public-key": this.publicKey
749
+ }
582
750
  });
583
751
  if (res.ok) {
584
752
  const body = await res.json();
585
- if (body?.avatar) {
586
- return normalizeProjectConfig({
587
- avatarName: body.avatar.name,
588
- avatarId: body.avatar.avatarId
589
- });
753
+ if (body && typeof body === "object") {
754
+ return normalizeProjectConfig(resolveAssetUrls(body));
755
+ }
756
+ } else {
757
+ const errorBody = await res.json().catch(() => ({}));
758
+ const errObj = errorBody?.error ?? errorBody;
759
+ const code = String(errObj?.code ?? "");
760
+ const message = String(errObj?.message ?? `HTTP ${res.status}`);
761
+ if (res.status === 404) {
762
+ throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
763
+ } else if (res.status === 401 || res.status === 403) {
764
+ throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
765
+ } else if (res.status >= 500) {
766
+ throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
590
767
  }
591
768
  }
592
- } catch {
769
+ } catch (err) {
770
+ if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
771
+ throw err;
772
+ }
773
+ if (err instanceof Error) lastError = err;
774
+ }
775
+ if (lastError) {
776
+ throw lastError;
593
777
  }
594
- return normalizeProjectConfig({});
778
+ throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
595
779
  }
596
780
  async heartbeat(metadata) {
597
- const response = await this.runtimeRequest({
781
+ let response = await this.runtimeRequest({
598
782
  path: "/sdk/heartbeat",
599
783
  method: "POST",
600
784
  idempotent: true,
@@ -607,6 +791,21 @@ var CloudClient = class {
607
791
  timestamp: metadata.timestamp
608
792
  }
609
793
  }, "assistant:heartbeat");
794
+ if (response.status === 404) {
795
+ response = await this.runtimeRequest({
796
+ path: "/api/v1/sdk/heartbeat",
797
+ method: "POST",
798
+ idempotent: true,
799
+ body: {
800
+ project_id: this.projectId,
801
+ public_key: this.publicKey,
802
+ sdk_version: SDK_VERSION,
803
+ origin: metadata.origin,
804
+ environment: metadata.environment,
805
+ timestamp: metadata.timestamp
806
+ }
807
+ }, "assistant:heartbeat");
808
+ }
610
809
  const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
611
810
  const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
612
811
  const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
@@ -619,13 +818,22 @@ var CloudClient = class {
619
818
  };
620
819
  }
621
820
  async registerInstallation(registration) {
622
- const response = await this.transport.request({
821
+ let response = await this.transport.request({
623
822
  path: "/sdk/installations/register",
624
823
  method: "POST",
625
824
  body: registration,
626
825
  idempotent: true,
627
826
  sessionId: this.sessionId
628
827
  });
828
+ if (response.status === 404) {
829
+ response = await this.transport.request({
830
+ path: "/api/v1/sdk/installations/register",
831
+ method: "POST",
832
+ body: registration,
833
+ idempotent: true,
834
+ sessionId: this.sessionId
835
+ });
836
+ }
629
837
  if (!response.ok) {
630
838
  throw new NetworkError(`SDK installation registration failed (${response.status}).`);
631
839
  }
@@ -696,18 +904,32 @@ var CloudClient = class {
696
904
  try {
697
905
  const origin = typeof window !== "undefined" ? window.location.origin : void 0;
698
906
  const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
907
+ const sanitizedMeta = {
908
+ sdkVersion: SDK_VERSION
909
+ };
910
+ for (const [key, val] of Object.entries(metadata)) {
911
+ if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
912
+ continue;
913
+ }
914
+ if (typeof val === "string") {
915
+ sanitizedMeta[key] = sanitizeText(val, 512);
916
+ } else if (typeof val === "number" || typeof val === "boolean") {
917
+ sanitizedMeta[key] = val;
918
+ } else if (val && typeof val === "object" && !Array.isArray(val)) {
919
+ sanitizedMeta[key] = val;
920
+ }
921
+ }
699
922
  const payload = {
700
923
  projectId: this.projectId,
701
924
  publicKey: this.publicKey,
702
925
  eventType,
703
926
  installationId,
704
927
  origin,
705
- metadata: {
706
- ...metadata,
707
- sdkVersion: SDK_VERSION
708
- }
928
+ metadata: sanitizedMeta
709
929
  };
710
- await fetch("https://asiyst.com/api/v1/events", {
930
+ const baseUrl = this.getApiBaseUrl();
931
+ const targetUrl = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? `${baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "")}/api/v1/events` : "https://asiyst.com/api/v1/events";
932
+ await fetch(targetUrl, {
711
933
  method: "POST",
712
934
  headers: {
713
935
  "Content-Type": "application/json",
@@ -1522,6 +1744,617 @@ var HighlightLayer = class {
1522
1744
  }
1523
1745
  };
1524
1746
 
1747
+ // src/avatar/AssetLoader.ts
1748
+ var GLB_MAGIC = 1179937895;
1749
+ var CHUNK_TYPE_JSON = 1313821514;
1750
+ var CHUNK_TYPE_BIN = 5130562;
1751
+ var AssetLoader = class {
1752
+ constructor() {
1753
+ this.inFlightController = null;
1754
+ this.createdObjectUrls = [];
1755
+ }
1756
+ async load(assetUrl, options) {
1757
+ const startTime = Date.now();
1758
+ const sanitizedUrl = sanitizeText(assetUrl.trim(), 2048);
1759
+ if (!sanitizedUrl) {
1760
+ throw new Error("Asset URL is required");
1761
+ }
1762
+ this.inFlightController = new AbortController();
1763
+ const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1764
+ const timeoutMs = options?.timeoutMs ?? 15e3;
1765
+ const timeoutId = setTimeout(() => {
1766
+ this.inFlightController?.abort();
1767
+ }, timeoutMs);
1768
+ try {
1769
+ const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
1770
+ const isImageExtension = /\.(png|jpe?g|webp|svg|gif|avif)$/i.test(cleanPath);
1771
+ const isJsonExtension = /\.json$/i.test(cleanPath);
1772
+ const isFbxExtension = /\.fbx$/i.test(cleanPath);
1773
+ const isGlbExtension = /\.glb$/i.test(cleanPath);
1774
+ if (isImageExtension) {
1775
+ const imageResult = await this.loadImage(sanitizedUrl, abortSignal);
1776
+ return {
1777
+ format: "image",
1778
+ url: sanitizedUrl,
1779
+ image: imageResult.element,
1780
+ width: imageResult.width,
1781
+ height: imageResult.height,
1782
+ durationMs: Date.now() - startTime
1783
+ };
1784
+ }
1785
+ let response;
1786
+ try {
1787
+ response = await fetch(sanitizedUrl, {
1788
+ method: "GET",
1789
+ headers: {
1790
+ Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1791
+ },
1792
+ signal: abortSignal
1793
+ });
1794
+ } catch (err) {
1795
+ if (err instanceof Error && err.name === "AbortError") {
1796
+ throw new Error("Avatar asset request timed out or was aborted");
1797
+ }
1798
+ throw new Error(`CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`);
1799
+ }
1800
+ if (!response.ok) {
1801
+ throw new Error(`Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`);
1802
+ }
1803
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
1804
+ if (isJsonExtension || contentType.includes("application/json")) {
1805
+ const text = await response.text();
1806
+ let manifest;
1807
+ try {
1808
+ manifest = JSON.parse(text);
1809
+ } catch {
1810
+ throw new Error("Invalid avatar manifest: JSON decoding failed");
1811
+ }
1812
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
1813
+ throw new Error("Invalid avatar manifest schema");
1814
+ }
1815
+ return {
1816
+ format: "manifest",
1817
+ url: sanitizedUrl,
1818
+ manifest,
1819
+ durationMs: Date.now() - startTime
1820
+ };
1821
+ }
1822
+ if (contentType.startsWith("image/")) {
1823
+ const imageResult = await this.loadImage(sanitizedUrl, abortSignal);
1824
+ return {
1825
+ format: "image",
1826
+ url: sanitizedUrl,
1827
+ image: imageResult.element,
1828
+ width: imageResult.width,
1829
+ height: imageResult.height,
1830
+ durationMs: Date.now() - startTime
1831
+ };
1832
+ }
1833
+ const arrayBuffer = await response.arrayBuffer();
1834
+ if (arrayBuffer.byteLength < 12) {
1835
+ throw new Error("Avatar asset payload is too small to be a valid 3D container");
1836
+ }
1837
+ if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1838
+ const fbxHeader = this.parseFbxHeader(arrayBuffer);
1839
+ const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1840
+ return {
1841
+ format: "fbx",
1842
+ url: sanitizedUrl,
1843
+ buffer: arrayBuffer,
1844
+ version: fbxHeader.version,
1845
+ isBinary: fbxHeader.isBinary,
1846
+ resourcePath,
1847
+ durationMs: Date.now() - startTime
1848
+ };
1849
+ }
1850
+ const parsedGlb = this.parseGlb(arrayBuffer);
1851
+ return {
1852
+ format: "glb",
1853
+ url: sanitizedUrl,
1854
+ json: parsedGlb.json,
1855
+ bin: parsedGlb.bin,
1856
+ meshes: parsedGlb.meshes,
1857
+ embeddedImageUrls: parsedGlb.embeddedImageUrls,
1858
+ durationMs: Date.now() - startTime
1859
+ };
1860
+ } finally {
1861
+ clearTimeout(timeoutId);
1862
+ this.inFlightController = null;
1863
+ }
1864
+ }
1865
+ isFbxBuffer(buffer) {
1866
+ if (buffer.byteLength < 18) return false;
1867
+ const bytes = new Uint8Array(buffer, 0, Math.min(64, buffer.byteLength));
1868
+ const headerStr = String.fromCharCode(...bytes.slice(0, 20));
1869
+ if (headerStr.startsWith("Kaydara FBX Binary")) {
1870
+ return true;
1871
+ }
1872
+ const sample = new TextDecoder("utf-8").decode(bytes);
1873
+ return sample.startsWith("; FBX") || sample.includes("FBXHeaderExtension");
1874
+ }
1875
+ parseFbxHeader(buffer) {
1876
+ if (buffer.byteLength < 18) {
1877
+ throw new Error("Corrupted FBX asset: payload is too small to contain an FBX header");
1878
+ }
1879
+ const bytes = new Uint8Array(buffer, 0, Math.min(64, buffer.byteLength));
1880
+ const headerStr = String.fromCharCode(...bytes.slice(0, 20));
1881
+ if (headerStr.startsWith("Kaydara FBX Binary")) {
1882
+ if (buffer.byteLength < 27) {
1883
+ throw new Error("Corrupted binary FBX asset: payload is truncated");
1884
+ }
1885
+ const view = new DataView(buffer);
1886
+ const version = view.getUint32(23, true);
1887
+ if (version < 6400) {
1888
+ throw new Error(`Unsupported legacy FBX version: ${version}. Versions prior to 6.4 (6400) are not supported.`);
1889
+ }
1890
+ return { isBinary: true, version };
1891
+ }
1892
+ const textSample = new TextDecoder("utf-8").decode(bytes);
1893
+ if (textSample.startsWith("; FBX") || textSample.includes("FBXHeaderExtension")) {
1894
+ const match = textSample.match(/;\s*FBX\s*(\d+(?:\.\d+)?)/i);
1895
+ const version = match && match[1] ? Math.round(parseFloat(match[1]) * 1e3) : void 0;
1896
+ return { isBinary: false, version };
1897
+ }
1898
+ throw new Error("Invalid FBX container: header does not match Kaydara binary or ASCII FBX signatures");
1899
+ }
1900
+ isGlbBuffer(buffer) {
1901
+ if (buffer.byteLength < 4) return false;
1902
+ const view = new DataView(buffer);
1903
+ return view.getUint32(0, true) === GLB_MAGIC;
1904
+ }
1905
+ async loadImage(url, signal) {
1906
+ if (typeof Image === "undefined") {
1907
+ return { width: 96, height: 96 };
1908
+ }
1909
+ return new Promise((resolve, reject) => {
1910
+ const img = new Image();
1911
+ img.crossOrigin = "anonymous";
1912
+ const onAbort = () => {
1913
+ img.src = "";
1914
+ reject(new Error("Image loading aborted"));
1915
+ };
1916
+ if (signal) {
1917
+ if (signal.aborted) {
1918
+ return reject(new Error("Image loading aborted"));
1919
+ }
1920
+ signal.addEventListener("abort", onAbort, { once: true });
1921
+ }
1922
+ img.onload = () => {
1923
+ if (signal) signal.removeEventListener("abort", onAbort);
1924
+ resolve({
1925
+ element: img,
1926
+ width: img.naturalWidth || 96,
1927
+ height: img.naturalHeight || 96
1928
+ });
1929
+ };
1930
+ img.onerror = () => {
1931
+ if (signal) signal.removeEventListener("abort", onAbort);
1932
+ reject(new Error(`Failed to load avatar image asset from ${url}`));
1933
+ };
1934
+ img.src = url;
1935
+ });
1936
+ }
1937
+ parseGlb(buffer) {
1938
+ const view = new DataView(buffer);
1939
+ const magic = view.getUint32(0, true);
1940
+ if (magic !== GLB_MAGIC) {
1941
+ throw new Error(`Invalid GLB container header: expected 0x${GLB_MAGIC.toString(16)}, received 0x${magic.toString(16)}`);
1942
+ }
1943
+ const version = view.getUint32(4, true);
1944
+ if (version !== 2) {
1945
+ throw new Error(`Unsupported glTF version: ${version}. Only version 2 is supported.`);
1946
+ }
1947
+ const totalLength = view.getUint32(8, true);
1948
+ if (totalLength > buffer.byteLength) {
1949
+ throw new Error(`Corrupted GLB asset: declared byteLength ${totalLength} exceeds actual payload ${buffer.byteLength}`);
1950
+ }
1951
+ let offset = 12;
1952
+ let json = null;
1953
+ let bin = new Uint8Array(0);
1954
+ while (offset < buffer.byteLength) {
1955
+ if (offset + 8 > buffer.byteLength) {
1956
+ break;
1957
+ }
1958
+ const chunkLength = view.getUint32(offset, true);
1959
+ const chunkType = view.getUint32(offset + 4, true);
1960
+ const chunkStart = offset + 8;
1961
+ const chunkEnd = chunkStart + chunkLength;
1962
+ if (chunkEnd > buffer.byteLength) {
1963
+ throw new Error("Corrupted GLB chunk: chunk length exceeds container bounds");
1964
+ }
1965
+ if (chunkType === CHUNK_TYPE_JSON) {
1966
+ const jsonSlice = new Uint8Array(buffer, chunkStart, chunkLength);
1967
+ const jsonText = new TextDecoder("utf-8").decode(jsonSlice);
1968
+ try {
1969
+ json = JSON.parse(jsonText);
1970
+ } catch {
1971
+ throw new Error("Invalid GLB JSON chunk: parsing failed");
1972
+ }
1973
+ } else if (chunkType === CHUNK_TYPE_BIN) {
1974
+ bin = new Uint8Array(buffer, chunkStart, chunkLength);
1975
+ }
1976
+ offset = chunkEnd;
1977
+ }
1978
+ if (!json) {
1979
+ throw new Error("Invalid GLB asset: missing required JSON chunk");
1980
+ }
1981
+ const bufferViews = Array.isArray(json.bufferViews) ? json.bufferViews : [];
1982
+ const accessors = Array.isArray(json.accessors) ? json.accessors : [];
1983
+ const meshesDef = Array.isArray(json.meshes) ? json.meshes : [];
1984
+ const imagesDef = Array.isArray(json.images) ? json.images : [];
1985
+ const embeddedImageUrls = [];
1986
+ if (typeof URL !== "undefined" && typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
1987
+ for (const imgDef of imagesDef) {
1988
+ const bvIndex = typeof imgDef.bufferView === "number" ? imgDef.bufferView : void 0;
1989
+ if (bvIndex !== void 0 && bufferViews[bvIndex]) {
1990
+ const bv = bufferViews[bvIndex];
1991
+ const bOffset = typeof bv.byteOffset === "number" ? bv.byteOffset : 0;
1992
+ const bLength = typeof bv.byteLength === "number" ? bv.byteLength : 0;
1993
+ if (bOffset + bLength <= bin.byteLength) {
1994
+ const imgBytes = bin.slice(bOffset, bOffset + bLength);
1995
+ const mime = typeof imgDef.mimeType === "string" ? imgDef.mimeType : "image/png";
1996
+ const blob = new Blob([imgBytes], { type: mime });
1997
+ const objUrl = URL.createObjectURL(blob);
1998
+ this.createdObjectUrls.push(objUrl);
1999
+ embeddedImageUrls.push(objUrl);
2000
+ }
2001
+ }
2002
+ }
2003
+ }
2004
+ const meshes = [];
2005
+ for (const meshObj of meshesDef) {
2006
+ const meshName = typeof meshObj.name === "string" ? meshObj.name : void 0;
2007
+ const primitives = Array.isArray(meshObj.primitives) ? meshObj.primitives : [];
2008
+ for (const prim of primitives) {
2009
+ const attrs = typeof prim.attributes === "object" && prim.attributes !== null ? prim.attributes : {};
2010
+ const posAccessorIdx = typeof attrs.POSITION === "number" ? attrs.POSITION : void 0;
2011
+ if (posAccessorIdx === void 0 || !accessors[posAccessorIdx]) {
2012
+ continue;
2013
+ }
2014
+ const posAcc = accessors[posAccessorIdx];
2015
+ const posBvIdx = typeof posAcc.bufferView === "number" ? posAcc.bufferView : void 0;
2016
+ if (posBvIdx === void 0 || !bufferViews[posBvIdx]) {
2017
+ continue;
2018
+ }
2019
+ const posBv = bufferViews[posBvIdx];
2020
+ const posOffset = (typeof posBv.byteOffset === "number" ? posBv.byteOffset : 0) + (typeof posAcc.byteOffset === "number" ? posAcc.byteOffset : 0);
2021
+ const posCount = typeof posAcc.count === "number" ? posAcc.count : 0;
2022
+ const posBytes = posCount * 3 * 4;
2023
+ if (posOffset + posBytes > bin.byteLength) {
2024
+ continue;
2025
+ }
2026
+ const positions = new Float32Array(bin.buffer, bin.byteOffset + posOffset, posCount * 3);
2027
+ let normals;
2028
+ const normAccessorIdx = typeof attrs.NORMAL === "number" ? attrs.NORMAL : void 0;
2029
+ if (normAccessorIdx !== void 0 && accessors[normAccessorIdx]) {
2030
+ const normAcc = accessors[normAccessorIdx];
2031
+ const normBvIdx = typeof normAcc.bufferView === "number" ? normAcc.bufferView : void 0;
2032
+ if (normBvIdx !== void 0 && bufferViews[normBvIdx]) {
2033
+ const normBv = bufferViews[normBvIdx];
2034
+ const normOffset = (typeof normBv.byteOffset === "number" ? normBv.byteOffset : 0) + (typeof normAcc.byteOffset === "number" ? normAcc.byteOffset : 0);
2035
+ const normCount = typeof normAcc.count === "number" ? normAcc.count : 0;
2036
+ if (normOffset + normCount * 3 * 4 <= bin.byteLength) {
2037
+ normals = new Float32Array(bin.buffer, bin.byteOffset + normOffset, normCount * 3);
2038
+ }
2039
+ }
2040
+ }
2041
+ let indices;
2042
+ const idxAccessorIdx = typeof prim.indices === "number" ? prim.indices : void 0;
2043
+ if (idxAccessorIdx !== void 0 && accessors[idxAccessorIdx]) {
2044
+ const idxAcc = accessors[idxAccessorIdx];
2045
+ const idxBvIdx = typeof idxAcc.bufferView === "number" ? idxAcc.bufferView : void 0;
2046
+ if (idxBvIdx !== void 0 && bufferViews[idxBvIdx]) {
2047
+ const idxBv = bufferViews[idxBvIdx];
2048
+ const idxOffset = (typeof idxBv.byteOffset === "number" ? idxBv.byteOffset : 0) + (typeof idxAcc.byteOffset === "number" ? idxAcc.byteOffset : 0);
2049
+ const idxCount = typeof idxAcc.count === "number" ? idxAcc.count : 0;
2050
+ const compType = typeof idxAcc.componentType === "number" ? idxAcc.componentType : 5123;
2051
+ if (compType === 5123) {
2052
+ if (idxOffset + idxCount * 2 <= bin.byteLength) {
2053
+ indices = new Uint16Array(bin.buffer, bin.byteOffset + idxOffset, idxCount);
2054
+ }
2055
+ } else if (compType === 5125) {
2056
+ if (idxOffset + idxCount * 4 <= bin.byteLength) {
2057
+ indices = new Uint32Array(bin.buffer, bin.byteOffset + idxOffset, idxCount);
2058
+ }
2059
+ }
2060
+ }
2061
+ }
2062
+ meshes.push({
2063
+ name: meshName,
2064
+ positions,
2065
+ normals,
2066
+ indices
2067
+ });
2068
+ }
2069
+ }
2070
+ return {
2071
+ json,
2072
+ bin,
2073
+ meshes,
2074
+ embeddedImageUrls
2075
+ };
2076
+ }
2077
+ destroy() {
2078
+ if (this.inFlightController) {
2079
+ this.inFlightController.abort();
2080
+ this.inFlightController = null;
2081
+ }
2082
+ if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
2083
+ for (const objUrl of this.createdObjectUrls) {
2084
+ try {
2085
+ URL.revokeObjectURL(objUrl);
2086
+ } catch {
2087
+ }
2088
+ }
2089
+ }
2090
+ this.createdObjectUrls.length = 0;
2091
+ }
2092
+ };
2093
+ function anySignal(signals) {
2094
+ const controller = new AbortController();
2095
+ for (const sig of signals) {
2096
+ if (sig.aborted) {
2097
+ controller.abort();
2098
+ return controller.signal;
2099
+ }
2100
+ sig.addEventListener("abort", () => controller.abort(), { once: true });
2101
+ }
2102
+ return controller.signal;
2103
+ }
2104
+ var FbxRenderer = class {
2105
+ constructor() {
2106
+ this.canvas = null;
2107
+ this.renderer = null;
2108
+ this.scene = null;
2109
+ this.camera = null;
2110
+ this.modelRoot = null;
2111
+ this.mixer = null;
2112
+ this.animFrameId = null;
2113
+ this.lastTime = 0;
2114
+ this.facing = "right";
2115
+ this.currentPose = "idle";
2116
+ this.initialRenderCompleted = false;
2117
+ }
2118
+ async mount(container, asset, options) {
2119
+ const doc = container.ownerDocument;
2120
+ if (!doc) {
2121
+ throw new Error("Unable to access document DOM for 3D avatar viewport");
2122
+ }
2123
+ this.canvas = doc.createElement("canvas");
2124
+ this.canvas.className = "asiyst-avatar-canvas";
2125
+ this.canvas.setAttribute("role", "presentation");
2126
+ const glContext = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
2127
+ if (!glContext) {
2128
+ throw new Error("WebGLRenderingContext is not available or supported in this browser environment");
2129
+ }
2130
+ const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2131
+ const size = options?.config?.size || 96;
2132
+ this.canvas.width = Math.round(size * dpr);
2133
+ this.canvas.height = Math.round(size * dpr);
2134
+ try {
2135
+ this.renderer = new THREE__namespace.WebGLRenderer({
2136
+ canvas: this.canvas,
2137
+ alpha: true,
2138
+ antialias: true,
2139
+ powerPreference: "low-power"
2140
+ });
2141
+ this.renderer.setPixelRatio(Math.min(dpr, 2));
2142
+ this.renderer.setSize(size, size, false);
2143
+ this.renderer.outputColorSpace = THREE__namespace.SRGBColorSpace;
2144
+ } catch (err) {
2145
+ const msg = err instanceof Error ? err.message : String(err);
2146
+ throw new Error(`Failed to initialize WebGLRenderer: ${msg}`);
2147
+ }
2148
+ this.scene = new THREE__namespace.Scene();
2149
+ this.camera = new THREE__namespace.PerspectiveCamera(40, 1, 0.1, 100);
2150
+ this.camera.position.set(0, 0, 3.4);
2151
+ const ambientLight = new THREE__namespace.AmbientLight(16777215, 1.2);
2152
+ this.scene.add(ambientLight);
2153
+ const keyLight = new THREE__namespace.DirectionalLight(16777215, 1.2);
2154
+ keyLight.position.set(2, 3.5, 3);
2155
+ this.scene.add(keyLight);
2156
+ const fillLight = new THREE__namespace.DirectionalLight(10859772, 0.6);
2157
+ fillLight.position.set(-2.5, -1, -1.5);
2158
+ this.scene.add(fillLight);
2159
+ let rawObject;
2160
+ let modelAnimations = [];
2161
+ if (asset.format === "fbx") {
2162
+ const manager = new THREE__namespace.LoadingManager();
2163
+ manager.onError = (itemUrl) => {
2164
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2165
+ console.warn(`[asiyst] Optional FBX texture resource could not be loaded: ${itemUrl}`);
2166
+ }
2167
+ };
2168
+ const loader = new FBXLoader_js.FBXLoader(manager);
2169
+ if (asset.resourcePath) {
2170
+ loader.setResourcePath(asset.resourcePath);
2171
+ }
2172
+ try {
2173
+ const parsedGroup = loader.parse(asset.buffer, asset.resourcePath || "");
2174
+ rawObject = parsedGroup;
2175
+ modelAnimations = parsedGroup.animations || [];
2176
+ } catch (parseErr) {
2177
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
2178
+ throw new Error(`FBX decoding and parsing failed: ${msg}`);
2179
+ }
2180
+ } else {
2181
+ const loader = new GLTFLoader_js.GLTFLoader();
2182
+ try {
2183
+ const gltf = await new Promise((resolve, reject) => {
2184
+ const glbBuffer = asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2185
+ loader.parse(glbBuffer, asset.url, resolve, reject);
2186
+ });
2187
+ rawObject = gltf.scene;
2188
+ modelAnimations = gltf.animations || [];
2189
+ } catch (parseErr) {
2190
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
2191
+ throw new Error(`GLB decoding and parsing failed: ${msg}`);
2192
+ }
2193
+ }
2194
+ const { meshCount, vertexCount: totalVertices } = this.validateGeometry(rawObject);
2195
+ const box = new THREE__namespace.Box3().setFromObject(rawObject);
2196
+ if (box.isEmpty()) {
2197
+ throw new Error("FBX asset geometry bounding box is empty");
2198
+ }
2199
+ const center = new THREE__namespace.Vector3();
2200
+ box.getCenter(center);
2201
+ const boxSize = new THREE__namespace.Vector3();
2202
+ box.getSize(boxSize);
2203
+ rawObject.position.x -= center.x;
2204
+ rawObject.position.y -= center.y;
2205
+ rawObject.position.z -= center.z;
2206
+ this.modelRoot = new THREE__namespace.Group();
2207
+ this.modelRoot.add(rawObject);
2208
+ this.scene.add(this.modelRoot);
2209
+ const maxDim = Math.max(boxSize.x, boxSize.y, boxSize.z);
2210
+ if (maxDim > 0) {
2211
+ const targetSpan = 1.85;
2212
+ const scale = targetSpan / maxDim;
2213
+ this.modelRoot.scale.setScalar(scale);
2214
+ }
2215
+ if (modelAnimations.length > 0) {
2216
+ this.mixer = new THREE__namespace.AnimationMixer(rawObject);
2217
+ const clip = modelAnimations[0];
2218
+ if (clip) {
2219
+ const action = this.mixer.clipAction(clip);
2220
+ action.play();
2221
+ }
2222
+ }
2223
+ container.replaceChildren();
2224
+ container.appendChild(this.canvas);
2225
+ try {
2226
+ this.renderer.render(this.scene, this.camera);
2227
+ this.initialRenderCompleted = true;
2228
+ } catch (renderErr) {
2229
+ const msg = renderErr instanceof Error ? renderErr.message : String(renderErr);
2230
+ throw new Error(`Initial FBX WebGL render failed: ${msg}`);
2231
+ }
2232
+ this.startLoop();
2233
+ this.setFacing(this.facing);
2234
+ this.setPose(this.currentPose);
2235
+ return {
2236
+ meshCount,
2237
+ vertexCount: totalVertices,
2238
+ animationCount: modelAnimations.length
2239
+ };
2240
+ }
2241
+ setFacing(direction) {
2242
+ this.facing = direction;
2243
+ if (this.modelRoot) {
2244
+ this.modelRoot.rotation.y = direction === "left" ? -0.35 : 0.35;
2245
+ }
2246
+ }
2247
+ setPose(pose) {
2248
+ this.currentPose = pose;
2249
+ if (!this.modelRoot) return;
2250
+ switch (pose) {
2251
+ case "point":
2252
+ this.modelRoot.rotation.z = -0.15;
2253
+ this.modelRoot.rotation.x = 0.08;
2254
+ break;
2255
+ case "think":
2256
+ this.modelRoot.rotation.z = 0.12;
2257
+ this.modelRoot.rotation.x = -0.1;
2258
+ break;
2259
+ case "celebrate":
2260
+ this.modelRoot.rotation.z = 0;
2261
+ this.modelRoot.rotation.x = -0.15;
2262
+ this.modelRoot.scale.multiplyScalar(1.05);
2263
+ break;
2264
+ default:
2265
+ this.modelRoot.rotation.z = 0;
2266
+ this.modelRoot.rotation.x = 0;
2267
+ break;
2268
+ }
2269
+ }
2270
+ isRendered() {
2271
+ return this.initialRenderCompleted;
2272
+ }
2273
+ validateGeometry(rawObject) {
2274
+ let totalVertices = 0;
2275
+ let meshCount = 0;
2276
+ rawObject.traverse((child) => {
2277
+ const mesh = child;
2278
+ if (mesh.isMesh && mesh.geometry) {
2279
+ meshCount++;
2280
+ const posAttr = mesh.geometry.attributes.position;
2281
+ if (posAttr) {
2282
+ totalVertices += posAttr.count;
2283
+ }
2284
+ }
2285
+ });
2286
+ if (meshCount === 0 || totalVertices === 0) {
2287
+ throw new Error("FBX asset contains no drawable 3D geometry");
2288
+ }
2289
+ return { meshCount, vertexCount: totalVertices };
2290
+ }
2291
+ getCanvas() {
2292
+ return this.canvas;
2293
+ }
2294
+ startLoop() {
2295
+ if (typeof requestAnimationFrame === "undefined") return;
2296
+ this.lastTime = typeof performance !== "undefined" ? performance.now() : Date.now();
2297
+ const tick = (now) => {
2298
+ if (!this.renderer || !this.scene || !this.camera) return;
2299
+ const current = now || (typeof performance !== "undefined" ? performance.now() : Date.now());
2300
+ const delta = Math.min(Math.max((current - this.lastTime) / 1e3, 0), 0.1);
2301
+ this.lastTime = current;
2302
+ if (this.mixer) {
2303
+ this.mixer.update(delta);
2304
+ }
2305
+ this.renderer.render(this.scene, this.camera);
2306
+ this.animFrameId = requestAnimationFrame(tick);
2307
+ };
2308
+ this.animFrameId = requestAnimationFrame(tick);
2309
+ }
2310
+ destroy() {
2311
+ if (this.animFrameId !== null && typeof cancelAnimationFrame !== "undefined") {
2312
+ cancelAnimationFrame(this.animFrameId);
2313
+ this.animFrameId = null;
2314
+ }
2315
+ if (this.mixer) {
2316
+ this.mixer.stopAllAction();
2317
+ this.mixer = null;
2318
+ }
2319
+ if (this.scene) {
2320
+ this.scene.traverse((obj) => {
2321
+ const mesh = obj;
2322
+ if (mesh.isMesh) {
2323
+ if (mesh.geometry) {
2324
+ mesh.geometry.dispose();
2325
+ }
2326
+ if (mesh.material) {
2327
+ if (Array.isArray(mesh.material)) {
2328
+ mesh.material.forEach((m) => {
2329
+ const mat = m;
2330
+ mat.map?.dispose();
2331
+ mat.dispose();
2332
+ });
2333
+ } else {
2334
+ const mat = mesh.material;
2335
+ mat.map?.dispose();
2336
+ mat.dispose();
2337
+ }
2338
+ }
2339
+ }
2340
+ });
2341
+ this.scene.clear();
2342
+ this.scene = null;
2343
+ }
2344
+ if (this.renderer) {
2345
+ this.renderer.dispose();
2346
+ this.renderer = null;
2347
+ }
2348
+ if (this.canvas) {
2349
+ this.canvas.remove();
2350
+ this.canvas = null;
2351
+ }
2352
+ this.camera = null;
2353
+ this.modelRoot = null;
2354
+ this.initialRenderCompleted = false;
2355
+ }
2356
+ };
2357
+
1525
2358
  // src/avatar/CssAvatarRenderer.ts
1526
2359
  var AVATAR_CSS = `
1527
2360
  .asiyst-avatar {
@@ -1544,10 +2377,80 @@ var AVATAR_CSS = `
1544
2377
  color: #fff;
1545
2378
  font: 700 14px/1.2 system-ui, sans-serif;
1546
2379
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.28);
2380
+ position: relative;
2381
+ overflow: hidden;
2382
+ cursor: pointer;
2383
+ border: none;
2384
+ padding: 0;
2385
+ outline: none;
2386
+ background: #2563eb;
1547
2387
  }
1548
2388
  .asiyst-figure[data-pose="point"] { transform: rotate(-12deg); }
1549
2389
  .asiyst-figure[data-pose="think"] { opacity: 0.85; }
1550
2390
  .asiyst-figure[data-pose="celebrate"] { transform: scale(1.08); }
2391
+ .asiyst-avatar-viewport {
2392
+ position: absolute;
2393
+ inset: 0;
2394
+ width: 100%;
2395
+ height: 100%;
2396
+ display: grid;
2397
+ place-items: center;
2398
+ border-radius: inherit;
2399
+ overflow: hidden;
2400
+ pointer-events: none;
2401
+ }
2402
+ .asiyst-avatar-canvas {
2403
+ width: 100%;
2404
+ height: 100%;
2405
+ object-fit: contain;
2406
+ border-radius: inherit;
2407
+ display: block;
2408
+ pointer-events: none;
2409
+ }
2410
+ .asiyst-avatar-graphic {
2411
+ width: 100%;
2412
+ height: 100%;
2413
+ object-fit: cover;
2414
+ border-radius: inherit;
2415
+ display: block;
2416
+ pointer-events: none;
2417
+ }
2418
+ .asiyst-avatar-loader {
2419
+ width: 32px;
2420
+ height: 32px;
2421
+ border: 3px solid rgba(255, 255, 255, 0.35);
2422
+ border-top-color: #fff;
2423
+ border-radius: 50%;
2424
+ animation: asiyst-spin 0.8s linear infinite;
2425
+ }
2426
+ @keyframes asiyst-spin {
2427
+ to { transform: rotate(360deg); }
2428
+ }
2429
+ .asiyst-avatar-fallback {
2430
+ display: grid;
2431
+ place-items: center;
2432
+ width: 100%;
2433
+ height: 100%;
2434
+ position: relative;
2435
+ }
2436
+ .asiyst-avatar-fallback-badge {
2437
+ position: absolute;
2438
+ top: 8px;
2439
+ right: 8px;
2440
+ width: 14px;
2441
+ height: 14px;
2442
+ background: #ef4444;
2443
+ color: #fff;
2444
+ border-radius: 50%;
2445
+ font-size: 10px;
2446
+ line-height: 14px;
2447
+ text-align: center;
2448
+ }
2449
+ .asiyst-avatar-initial {
2450
+ font-size: 28px;
2451
+ font-weight: 700;
2452
+ line-height: 1;
2453
+ }
1551
2454
  .asiyst-bubble {
1552
2455
  max-width: 220px;
1553
2456
  background: #0f172a;
@@ -1560,6 +2463,7 @@ var AVATAR_CSS = `
1560
2463
  .asiyst-name { font: 600 12px/1 system-ui, sans-serif; color: #0f172a; }
1561
2464
  @media (prefers-reduced-motion: reduce) {
1562
2465
  .asiyst-avatar.asiyst-animate { transition: none; }
2466
+ .asiyst-avatar-loader { animation: none; }
1563
2467
  }
1564
2468
  `;
1565
2469
  var CssAvatarRenderer = class {
@@ -1568,6 +2472,14 @@ var CssAvatarRenderer = class {
1568
2472
  this.hidden = false;
1569
2473
  this.facing = "right";
1570
2474
  this.pose = "idle";
2475
+ this.accentColor = "#2563eb";
2476
+ this.avatarName = "Asiyst";
2477
+ // Asset loading & rendering state
2478
+ this.assetLoader = new AssetLoader();
2479
+ this.fbxRenderer = null;
2480
+ this.renderState = "idle";
2481
+ this.isAssetLoadedFlag = false;
2482
+ this.isFallbackFlag = true;
1571
2483
  }
1572
2484
  mount(container, config) {
1573
2485
  const doc = container.ownerDocument;
@@ -1581,6 +2493,10 @@ var CssAvatarRenderer = class {
1581
2493
  this.figure.type = "button";
1582
2494
  this.figure.className = "asiyst-figure";
1583
2495
  this.figure.setAttribute("aria-label", `${config.avatarName} assistant`);
2496
+ this.figure.setAttribute("data-state", this.renderState);
2497
+ this.viewport = doc.createElement("div");
2498
+ this.viewport.className = "asiyst-avatar-viewport";
2499
+ this.figure.appendChild(this.viewport);
1584
2500
  this.nameEl = doc.createElement("div");
1585
2501
  this.nameEl.className = "asiyst-name";
1586
2502
  this.bubble = doc.createElement("div");
@@ -1591,16 +2507,24 @@ var CssAvatarRenderer = class {
1591
2507
  this.applyConfig(config);
1592
2508
  }
1593
2509
  unmount() {
2510
+ this.assetLoader.destroy();
2511
+ if (this.fbxRenderer) {
2512
+ this.fbxRenderer.destroy();
2513
+ this.fbxRenderer = null;
2514
+ }
1594
2515
  this.root?.remove();
1595
2516
  this.root = void 0;
2517
+ this.figure = void 0;
2518
+ this.viewport = void 0;
1596
2519
  }
1597
2520
  applyConfig(config) {
1598
2521
  this.size = config.size;
2522
+ this.accentColor = config.theme.accent ?? "#2563eb";
2523
+ this.avatarName = config.avatarName;
1599
2524
  if (this.figure) {
1600
2525
  this.figure.style.width = `${config.size}px`;
1601
2526
  this.figure.style.height = `${config.size}px`;
1602
- this.figure.style.background = config.theme.accent ?? "#2563eb";
1603
- renderSafeText(this.figure, config.avatarName.slice(0, 1).toUpperCase());
2527
+ this.figure.style.background = this.accentColor;
1604
2528
  }
1605
2529
  if (this.nameEl) {
1606
2530
  renderSafeText(this.nameEl, config.avatarName);
@@ -1608,36 +2532,149 @@ var CssAvatarRenderer = class {
1608
2532
  if (this.root) {
1609
2533
  this.root.setAttribute("aria-label", config.avatarName);
1610
2534
  }
2535
+ if (!this.isAssetLoadedFlag && this.viewport) {
2536
+ this.renderFallback();
2537
+ }
1611
2538
  }
1612
- setPosition(x, y, animate) {
1613
- if (!this.root) {
1614
- return;
2539
+ async loadAsset(config) {
2540
+ const assetUrl = config.assetUrl ?? config.thumbnailUrl;
2541
+ if (!assetUrl) {
2542
+ this.renderState = "idle";
2543
+ this.isAssetLoadedFlag = false;
2544
+ this.isFallbackFlag = true;
2545
+ this.renderFallback();
2546
+ return false;
1615
2547
  }
2548
+ this.activeAssetUrl = assetUrl;
2549
+ this.renderState = "loading";
2550
+ this.isFallbackFlag = false;
2551
+ this.lastErrorMessage = void 0;
2552
+ if (this.figure) {
2553
+ this.figure.setAttribute("data-state", "loading");
2554
+ }
2555
+ this.renderLoader();
2556
+ try {
2557
+ const asset = await this.assetLoader.load(assetUrl);
2558
+ await this.renderLoadedAsset(asset, config);
2559
+ this.renderState = "ready";
2560
+ this.isAssetLoadedFlag = true;
2561
+ this.isFallbackFlag = false;
2562
+ this.loadedFormat = asset.format;
2563
+ if (this.figure) {
2564
+ this.figure.setAttribute("data-state", "ready");
2565
+ }
2566
+ return true;
2567
+ } catch (err) {
2568
+ const message = err instanceof Error ? err.message : "Failed to load avatar asset";
2569
+ this.lastErrorMessage = message;
2570
+ this.renderState = "error";
2571
+ this.isAssetLoadedFlag = false;
2572
+ this.isFallbackFlag = true;
2573
+ if (this.figure) {
2574
+ this.figure.setAttribute("data-state", "error");
2575
+ }
2576
+ this.renderFallback(true);
2577
+ return false;
2578
+ }
2579
+ }
2580
+ renderLoader() {
2581
+ if (!this.viewport) return;
2582
+ this.viewport.replaceChildren();
2583
+ const doc = this.viewport.ownerDocument;
2584
+ const loader = doc.createElement("div");
2585
+ loader.className = "asiyst-avatar-loader";
2586
+ loader.setAttribute("aria-label", `Loading ${this.avatarName}`);
2587
+ this.viewport.appendChild(loader);
2588
+ }
2589
+ async renderLoadedAsset(asset, config) {
2590
+ if (!this.viewport) return;
2591
+ if (this.fbxRenderer) {
2592
+ this.fbxRenderer.destroy();
2593
+ this.fbxRenderer = null;
2594
+ }
2595
+ if (asset.format === "fbx" || asset.format === "glb") {
2596
+ this.fbxRenderer = new FbxRenderer();
2597
+ this.renderMetrics = await this.fbxRenderer.mount(this.viewport, asset, {
2598
+ accentColor: this.accentColor,
2599
+ config
2600
+ });
2601
+ this.fbxRenderer.setFacing(this.facing);
2602
+ this.fbxRenderer.setPose(this.pose);
2603
+ } else if (asset.format === "image") {
2604
+ this.viewport.replaceChildren();
2605
+ const doc = this.viewport.ownerDocument;
2606
+ const img = doc.createElement("img");
2607
+ img.className = "asiyst-avatar-graphic";
2608
+ img.alt = `${config.avatarName} visual avatar`;
2609
+ img.src = asset.url;
2610
+ this.viewport.appendChild(img);
2611
+ } else if (asset.format === "manifest") {
2612
+ const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
2613
+ const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
2614
+ if (modelUrl) {
2615
+ const subAsset = await this.assetLoader.load(modelUrl);
2616
+ await this.renderLoadedAsset(subAsset, config);
2617
+ } else if (thumb) {
2618
+ this.viewport.replaceChildren();
2619
+ const doc = this.viewport.ownerDocument;
2620
+ const img = doc.createElement("img");
2621
+ img.className = "asiyst-avatar-graphic";
2622
+ img.alt = `${config.avatarName} visual avatar`;
2623
+ img.src = thumb;
2624
+ this.viewport.appendChild(img);
2625
+ } else {
2626
+ throw new Error("Manifest did not provide a drawable 3D asset or thumbnail URL");
2627
+ }
2628
+ }
2629
+ }
2630
+ renderFallback(isError = false) {
2631
+ if (!this.viewport) return;
2632
+ this.viewport.replaceChildren();
2633
+ const doc = this.viewport.ownerDocument;
2634
+ const fallback = doc.createElement("div");
2635
+ fallback.className = "asiyst-avatar-fallback";
2636
+ fallback.setAttribute("data-fallback", "true");
2637
+ if (isError) {
2638
+ fallback.setAttribute("data-state", "error");
2639
+ }
2640
+ const initial = doc.createElement("span");
2641
+ initial.className = "asiyst-avatar-initial";
2642
+ renderSafeText(initial, this.avatarName.slice(0, 1).toUpperCase());
2643
+ fallback.appendChild(initial);
2644
+ if (isError) {
2645
+ const badge = doc.createElement("span");
2646
+ badge.className = "asiyst-avatar-fallback-badge";
2647
+ badge.setAttribute("title", "Avatar asset failed to load");
2648
+ badge.textContent = "!";
2649
+ fallback.appendChild(badge);
2650
+ }
2651
+ this.viewport.appendChild(fallback);
2652
+ }
2653
+ setPosition(x, y, animate) {
2654
+ if (!this.root) return;
1616
2655
  this.root.classList.toggle("asiyst-animate", animate);
1617
2656
  this.root.style.left = `${x}px`;
1618
2657
  this.root.style.top = `${y}px`;
1619
2658
  }
1620
2659
  setFacing(direction) {
1621
2660
  this.facing = direction;
2661
+ this.fbxRenderer?.setFacing(direction);
1622
2662
  this.syncTransform();
1623
2663
  }
1624
2664
  setPose(pose) {
1625
2665
  this.pose = pose;
2666
+ this.fbxRenderer?.setPose(pose);
1626
2667
  this.figure?.setAttribute("data-pose", pose);
1627
2668
  this.syncTransform();
1628
2669
  }
1629
2670
  syncTransform() {
1630
- if (!this.figure) {
1631
- return;
1632
- }
2671
+ if (!this.figure) return;
1633
2672
  const face = this.facing === "left" ? "scaleX(-1)" : "";
1634
2673
  const pose = this.pose === "point" ? "rotate(-12deg)" : this.pose === "celebrate" ? "scale(1.08)" : "";
1635
2674
  this.figure.style.transform = `${face} ${pose}`.trim();
1636
2675
  }
1637
2676
  setSpeech(text) {
1638
- if (!this.bubble) {
1639
- return;
1640
- }
2677
+ if (!this.bubble) return;
1641
2678
  if (!text) {
1642
2679
  this.bubble.hidden = true;
1643
2680
  this.bubble.textContent = "";
@@ -1661,6 +2698,33 @@ var CssAvatarRenderer = class {
1661
2698
  getFigure() {
1662
2699
  return this.figure;
1663
2700
  }
2701
+ getViewport() {
2702
+ return this.viewport;
2703
+ }
2704
+ isAssetLoaded() {
2705
+ return this.isAssetLoadedFlag;
2706
+ }
2707
+ isRendered() {
2708
+ return this.isAssetLoadedFlag && (this.fbxRenderer ? this.fbxRenderer.isRendered() : true);
2709
+ }
2710
+ isFallbackActive() {
2711
+ return this.isFallbackFlag;
2712
+ }
2713
+ getRenderState() {
2714
+ return this.renderState;
2715
+ }
2716
+ getLoadedFormat() {
2717
+ return this.loadedFormat;
2718
+ }
2719
+ getAssetUrl() {
2720
+ return this.activeAssetUrl;
2721
+ }
2722
+ getLastError() {
2723
+ return this.lastErrorMessage;
2724
+ }
2725
+ getMetrics() {
2726
+ return this.renderMetrics;
2727
+ }
1664
2728
  };
1665
2729
 
1666
2730
  // src/accessibility/a11y.ts
@@ -1998,6 +3062,9 @@ function isLikelyJavaScriptUrl(value) {
1998
3062
  const lower = value.trim().toLowerCase();
1999
3063
  return lower.startsWith("javascript:") || lower.startsWith("data:") || lower.startsWith("vbscript:") || lower.includes("eval(") || lower.includes("new function") || lower.includes("document.cookie");
2000
3064
  }
3065
+ function isLocalHost(host) {
3066
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
3067
+ }
2001
3068
  function validateWebsiteDomain(config, currentUrl) {
2002
3069
  const allowedDomains = config.allowedDomains.map((domain) => normalizeHost(domain));
2003
3070
  if (allowedDomains.length === 0) {
@@ -2006,7 +3073,16 @@ function validateWebsiteDomain(config, currentUrl) {
2006
3073
  try {
2007
3074
  const parsed = new URL(currentUrl);
2008
3075
  const host = normalizeHost(parsed.host);
2009
- const allowed = allowedDomains.some((domain) => host === domain || host.endsWith(`.${domain}`));
3076
+ const hostIsLocal = isLocalHost(host);
3077
+ const allowed = allowedDomains.some((domain) => {
3078
+ if (host === domain || host.endsWith(`.${domain}`)) {
3079
+ return true;
3080
+ }
3081
+ if (hostIsLocal && isLocalHost(domain)) {
3082
+ return true;
3083
+ }
3084
+ return false;
3085
+ });
2010
3086
  if (!allowed) {
2011
3087
  return { allowed: false, reason: "DOMAIN_NOT_AUTHORIZED" };
2012
3088
  }
@@ -2658,23 +3734,36 @@ var RuntimeAuth = class {
2658
3734
  const timeout = setTimeout(() => controller.abort(), 1e4);
2659
3735
  let response;
2660
3736
  try {
2661
- response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
3737
+ const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
3738
+ const payload = JSON.stringify({
3739
+ projectId: this.options.projectId,
3740
+ publicKey: this.options.publicKey,
3741
+ installationId: this.options.installationId,
3742
+ origin: this.options.origin,
3743
+ environment: this.options.environment,
3744
+ sdkVersion: SDK_VERSION,
3745
+ capabilities: [...RUNTIME_CAPABILITIES]
3746
+ });
3747
+ response = await fetch(`${baseUrl}/sdk/runtime/token`, {
2662
3748
  method: "POST",
2663
3749
  headers: {
2664
3750
  Accept: "application/json",
2665
3751
  "Content-Type": "application/json"
2666
3752
  },
2667
- body: JSON.stringify({
2668
- projectId: this.options.projectId,
2669
- publicKey: this.options.publicKey,
2670
- installationId: this.options.installationId,
2671
- origin: this.options.origin,
2672
- environment: this.options.environment,
2673
- sdkVersion: SDK_VERSION,
2674
- capabilities: [...RUNTIME_CAPABILITIES]
2675
- }),
3753
+ body: payload,
2676
3754
  signal: controller.signal
2677
3755
  });
3756
+ if (response.status === 404) {
3757
+ response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
3758
+ method: "POST",
3759
+ headers: {
3760
+ Accept: "application/json",
3761
+ "Content-Type": "application/json"
3762
+ },
3763
+ body: payload,
3764
+ signal: controller.signal
3765
+ });
3766
+ }
2678
3767
  } catch {
2679
3768
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
2680
3769
  } finally {
@@ -2821,6 +3910,9 @@ var AsiystRuntime = class {
2821
3910
  this.connectionStatus = "disconnected";
2822
3911
  this.verificationStatus = "not_detected";
2823
3912
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
3913
+ this.isHeartbeatInFlight = false;
3914
+ this.lastHeartbeatTime = 0;
3915
+ this.registrationSucceeded = false;
2824
3916
  if (!doc.body) {
2825
3917
  throw new InitializationError("document.body is not available");
2826
3918
  }
@@ -2828,7 +3920,7 @@ var AsiystRuntime = class {
2828
3920
  this.installationId = loadOrCreateInstallationId(options.projectId);
2829
3921
  this.visitorSessionId = options.visitorSessionId || `vsess_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
2830
3922
  const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
2831
- this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
3923
+ this.environment = options.environment || (isLocalOrigin ? "development" : "production");
2832
3924
  const transport = new HttpTransport({
2833
3925
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2834
3926
  projectId: options.projectId,
@@ -2843,7 +3935,7 @@ var AsiystRuntime = class {
2843
3935
  origin: win.location.origin,
2844
3936
  environment: this.environment
2845
3937
  }) : void 0;
2846
- this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId);
3938
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
2847
3939
  this.config = new ConfigManager(options, this.cloud, this.events);
2848
3940
  this.analytics = new Analytics(options.projectId, this.cloud);
2849
3941
  this.host = new HostRoot(doc);
@@ -2925,91 +4017,82 @@ var AsiystRuntime = class {
2925
4017
  sdkVersion: SDK_VERSION
2926
4018
  });
2927
4019
  await this.registerInstallation();
2928
- const previousConnection = this.connectionStatus === "connected";
2929
- try {
2930
- const heartbeat = await this.cloud.heartbeat({
2931
- origin: window.location.origin,
2932
- environment: this.environment,
2933
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4020
+ await this.sendHeartbeat();
4021
+ const doc = this.host.host.ownerDocument;
4022
+ this.startHeartbeatScheduler(doc);
4023
+ this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4024
+ void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4025
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4026
+ avatarName: cfg.avatarName,
4027
+ publishedVersion: cfg.publishedVersion
4028
+ });
4029
+ const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4030
+ if (assetTarget) {
4031
+ this.events.emit("asiyst:avatar:loading", {
4032
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4033
+ assetUrl: assetTarget
2934
4034
  });
2935
- this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
2936
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
2937
- if (heartbeat.ok) {
2938
- this.lifecycle.emit("sdk.connected", {
2939
- projectId: this.options.projectId,
2940
- origin: window.location.origin,
2941
- environment: this.environment,
2942
- installationId: this.installationId,
2943
- sdkVersion: SDK_VERSION
2944
- });
2945
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
2946
- this.lifecycle.emit("sdk.verified", {
2947
- projectId: this.options.projectId,
2948
- origin: window.location.origin,
2949
- environment: this.environment,
2950
- installationId: this.installationId,
2951
- sdkVersion: SDK_VERSION
4035
+ void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4036
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4037
+ assetUrl: assetTarget
4038
+ });
4039
+ try {
4040
+ const loaded = await this.renderer.loadAsset(cfg);
4041
+ if (loaded) {
4042
+ const format = this.renderer.getLoadedFormat();
4043
+ const assetUrl = this.renderer.getAssetUrl();
4044
+ const isRendered = this.renderer.isRendered();
4045
+ this.events.emit("asiyst:avatar:loaded", {
4046
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4047
+ assetUrl,
4048
+ format
2952
4049
  });
2953
- }
2954
- if (heartbeat.versionOutdated) {
2955
- this.lifecycle.emit("sdk.version_outdated", {
2956
- projectId: this.options.projectId,
2957
- origin: window.location.origin,
2958
- environment: this.environment,
2959
- installationId: this.installationId,
2960
- sdkVersion: SDK_VERSION
4050
+ void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4051
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4052
+ avatarName: cfg.avatarName,
4053
+ assetUrl,
4054
+ format,
4055
+ publishedVersion: cfg.publishedVersion
2961
4056
  });
2962
- }
2963
- } else {
2964
- const reason = heartbeat.verificationStatus ?? "unverified";
2965
- this.lifecycle.emit("sdk.verification_failed", {
2966
- projectId: this.options.projectId,
2967
- origin: window.location.origin,
2968
- environment: this.environment,
2969
- status: reason,
2970
- reason: "heartbeat_failed"
2971
- });
2972
- if (previousConnection) {
2973
- this.lifecycle.emit("sdk.disconnected", {
2974
- projectId: this.options.projectId,
2975
- origin: window.location.origin,
2976
- environment: this.environment,
2977
- installationId: this.installationId,
2978
- reason: "heartbeat_failed",
2979
- status: reason
4057
+ if (isRendered) {
4058
+ this.events.emit("asiyst:avatar:rendered", {
4059
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4060
+ format
4061
+ });
4062
+ void this.cloud.sendTelemetryEvent("avatar_rendered", {
4063
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4064
+ avatarName: cfg.avatarName,
4065
+ format,
4066
+ publishedVersion: cfg.publishedVersion
4067
+ });
4068
+ }
4069
+ } else {
4070
+ const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
4071
+ this.events.emit("asiyst:avatar:error", {
4072
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4073
+ error: err,
4074
+ stage: "renderer_init"
4075
+ });
4076
+ void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4077
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4078
+ error: err,
4079
+ stage: "renderer_init"
2980
4080
  });
2981
4081
  }
2982
- }
2983
- } catch (error) {
2984
- this.connectionStatus = "offline";
2985
- this.verificationStatus = "error";
2986
- this.lifecycle.emit("sdk.verification_failed", {
2987
- projectId: this.options.projectId,
2988
- origin: window.location.origin,
2989
- environment: this.environment,
2990
- installationId: this.installationId,
2991
- reason: "heartbeat_failed",
2992
- category: error instanceof AuthenticationError ? "authorization" : "network"
2993
- });
2994
- if (previousConnection) {
2995
- this.lifecycle.emit("sdk.disconnected", {
2996
- projectId: this.options.projectId,
2997
- origin: window.location.origin,
2998
- environment: this.environment,
2999
- reason: "heartbeat_failed",
3000
- category: "network"
4082
+ } catch (error) {
4083
+ const err = error instanceof Error ? error.message : "Avatar asset rendering failed";
4084
+ this.events.emit("asiyst:avatar:error", {
4085
+ avatarId: this.options.avatarId ?? cfg.avatarId,
4086
+ error: err,
4087
+ stage: "asset_fetch"
4088
+ });
4089
+ void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4090
+ avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4091
+ error: err,
4092
+ stage: "asset_fetch"
3001
4093
  });
3002
4094
  }
3003
4095
  }
3004
- this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
3005
- void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
3006
- avatarId: this.options.avatarId ?? cfg.avatarName,
3007
- avatarName: cfg.avatarName
3008
- });
3009
- void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
3010
- avatarId: this.options.avatarId ?? cfg.avatarName,
3011
- avatarName: cfg.avatarName
3012
- });
3013
4096
  }
3014
4097
  getConnectionStatus() {
3015
4098
  return this.connectionStatus;
@@ -3061,6 +4144,16 @@ var AsiystRuntime = class {
3061
4144
  return;
3062
4145
  }
3063
4146
  this.destroyed = true;
4147
+ if (this.heartbeatTimer) {
4148
+ clearInterval(this.heartbeatTimer);
4149
+ this.heartbeatTimer = void 0;
4150
+ }
4151
+ const doc = this.host.host.ownerDocument;
4152
+ if (doc && this.visibilityListener) {
4153
+ doc.removeEventListener("visibilitychange", this.visibilityListener);
4154
+ this.visibilityListener = void 0;
4155
+ }
4156
+ this.isHeartbeatInFlight = false;
3064
4157
  if (this.pagehideListener) {
3065
4158
  win.removeEventListener("pagehide", this.pagehideListener);
3066
4159
  }
@@ -3080,6 +4173,135 @@ var AsiystRuntime = class {
3080
4173
  this.events.removeAll();
3081
4174
  await this.analytics.destroy();
3082
4175
  }
4176
+ startHeartbeatScheduler(doc) {
4177
+ if (this.heartbeatTimer) {
4178
+ clearInterval(this.heartbeatTimer);
4179
+ }
4180
+ this.heartbeatTimer = setInterval(() => {
4181
+ if (!this.destroyed) {
4182
+ void this.sendHeartbeat(true);
4183
+ }
4184
+ }, HEARTBEAT_INTERVAL_MS);
4185
+ if (doc && typeof doc.addEventListener === "function") {
4186
+ this.visibilityListener = () => {
4187
+ if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
4188
+ void this.sendHeartbeat(true);
4189
+ }
4190
+ };
4191
+ doc.addEventListener("visibilitychange", this.visibilityListener);
4192
+ }
4193
+ }
4194
+ async sendHeartbeat(_isPeriodic = false) {
4195
+ if (this.destroyed || this.isHeartbeatInFlight) {
4196
+ return false;
4197
+ }
4198
+ this.isHeartbeatInFlight = true;
4199
+ const previousConnection = this.connectionStatus === "connected";
4200
+ const origin = window.location.origin;
4201
+ const environment = this.environment;
4202
+ const installationId = this.installationId;
4203
+ try {
4204
+ if (!this.registrationSucceeded && installationId) {
4205
+ await this.registerInstallation();
4206
+ }
4207
+ const heartbeat = await this.cloud.heartbeat({
4208
+ origin,
4209
+ environment,
4210
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4211
+ });
4212
+ this.lastHeartbeatTime = Date.now();
4213
+ this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
4214
+ this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
4215
+ if (heartbeat.ok) {
4216
+ if (!previousConnection) {
4217
+ this.events.emit("asiyst:runtime:connected", {
4218
+ projectId: this.options.projectId,
4219
+ status: "connected",
4220
+ environment,
4221
+ origin
4222
+ });
4223
+ this.lifecycle.emit("sdk.connected", {
4224
+ projectId: this.options.projectId,
4225
+ origin,
4226
+ environment,
4227
+ installationId,
4228
+ sdkVersion: SDK_VERSION
4229
+ });
4230
+ }
4231
+ if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
4232
+ this.lifecycle.emit("sdk.verified", {
4233
+ projectId: this.options.projectId,
4234
+ origin,
4235
+ environment,
4236
+ installationId,
4237
+ sdkVersion: SDK_VERSION
4238
+ });
4239
+ }
4240
+ if (heartbeat.versionOutdated) {
4241
+ this.lifecycle.emit("sdk.version_outdated", {
4242
+ projectId: this.options.projectId,
4243
+ origin,
4244
+ environment,
4245
+ installationId,
4246
+ sdkVersion: SDK_VERSION
4247
+ });
4248
+ }
4249
+ return true;
4250
+ } else {
4251
+ const reason = heartbeat.verificationStatus ?? "unverified";
4252
+ this.lifecycle.emit("sdk.verification_failed", {
4253
+ projectId: this.options.projectId,
4254
+ origin,
4255
+ environment,
4256
+ status: reason,
4257
+ reason: "heartbeat_failed"
4258
+ });
4259
+ if (previousConnection) {
4260
+ this.events.emit("asiyst:runtime:disconnected", {
4261
+ projectId: this.options.projectId,
4262
+ reason: "heartbeat_failed"
4263
+ });
4264
+ this.lifecycle.emit("sdk.disconnected", {
4265
+ projectId: this.options.projectId,
4266
+ origin,
4267
+ environment,
4268
+ installationId,
4269
+ reason: "heartbeat_failed",
4270
+ status: reason
4271
+ });
4272
+ }
4273
+ return false;
4274
+ }
4275
+ } catch (error) {
4276
+ this.connectionStatus = "offline";
4277
+ this.verificationStatus = "error";
4278
+ this.lifecycle.emit("sdk.verification_failed", {
4279
+ projectId: this.options.projectId,
4280
+ origin,
4281
+ environment,
4282
+ installationId,
4283
+ reason: "heartbeat_failed",
4284
+ category: error instanceof AuthenticationError ? "authorization" : "network"
4285
+ });
4286
+ if (previousConnection) {
4287
+ this.events.emit("asiyst:runtime:disconnected", {
4288
+ projectId: this.options.projectId,
4289
+ reason: "heartbeat_failed"
4290
+ });
4291
+ this.lifecycle.emit("sdk.disconnected", {
4292
+ projectId: this.options.projectId,
4293
+ origin,
4294
+ environment,
4295
+ installationId,
4296
+ reason: "heartbeat_failed",
4297
+ category: "network"
4298
+ });
4299
+ }
4300
+ return false;
4301
+ } finally {
4302
+ this.isHeartbeatInFlight = false;
4303
+ }
4304
+ }
3083
4305
  async registerInstallation() {
3084
4306
  const origin = window.location.origin;
3085
4307
  const environment = this.environment;
@@ -3101,6 +4323,7 @@ var AsiystRuntime = class {
3101
4323
  environment,
3102
4324
  sdk_version: SDK_VERSION
3103
4325
  });
4326
+ this.registrationSucceeded = true;
3104
4327
  return;
3105
4328
  } catch (error) {
3106
4329
  lastError = error;
@@ -3200,6 +4423,9 @@ var Asiyst = {
3200
4423
  getVerificationStatus() {
3201
4424
  return requireRuntime().getVerificationStatus();
3202
4425
  },
4426
+ isRuntimeConnected() {
4427
+ return requireRuntime().getConnectionStatus() === "connected";
4428
+ },
3203
4429
  avatar: {
3204
4430
  show() {
3205
4431
  withIsolation(() => requireRuntime().avatarApi().show());
@@ -3258,8 +4484,11 @@ var Asiyst = {
3258
4484
  exports.ActionNotAllowedError = ActionNotAllowedError;
3259
4485
  exports.Asiyst = Asiyst;
3260
4486
  exports.AsiystError = AsiystError;
4487
+ exports.AssetLoader = AssetLoader;
3261
4488
  exports.AuthenticationError = AuthenticationError;
3262
4489
  exports.ConfigurationError = ConfigurationError;
4490
+ exports.CssAvatarRenderer = CssAvatarRenderer;
4491
+ exports.FbxRenderer = FbxRenderer;
3263
4492
  exports.InitializationError = InitializationError;
3264
4493
  exports.NetworkError = NetworkError;
3265
4494
  exports.SDK_VERSION = SDK_VERSION;