@zerogpu/browser-extension-sdk 0.2.0 → 0.2.1-dev.202607301617.g61d37c5

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/loader.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e){"use strict";const t="ZeroGpuBrowserSdk",r="ZeroGpuSdk",n=e=>{const{script:n,documentRef:o,windowRef:i,fetchImpl:s}=e;if(i[t]?.initZeroGpuSdk)return Promise.resolve();const c=n.getAttribute("src")??"";let d;try{d=new URL(c,e.baseUri)}catch{d=new URL(e.baseUri)}const a=new URL("manifest.json",d).toString(),u=new URL("zerogpu-browser-sdk.umd.js",d).toString(),l=[];let m=()=>{};const f=new Promise(e=>{m=e}),w=()=>{const e=i[t];if(e&&"function"==typeof e.initZeroGpuSdk){for(i[r]=e;l.length>0;){const t=l.shift();try{Promise.resolve(e[t.method]?.(...t.args)).then(t.resolve,t.reject)}catch(e){t.reject(e)}}m()}else console.error("[ZeroGpuSdk] Core bundle loaded but global API is missing.")};i[r]||(i[r]={ready:f,initZeroGpuSdk:(...e)=>new Promise((t,r)=>{l.push({method:"initZeroGpuSdk",args:e,resolve:t,reject:r})})});const p=(e,t)=>{const r=o.createElement("script");for(const e of Array.from(n.attributes))"src"!==e.name&&"integrity"!==e.name&&r.setAttribute(e.name,e.value);r.src=e,r.async=!0,r.setAttribute("data-zerogpu-core","true"),t&&(r.integrity=t,r.crossOrigin=n.crossOrigin??"anonymous"),r.addEventListener("load",w),r.addEventListener("error",()=>{console.error("[ZeroGpuSdk] Failed to load core bundle from",e)}),(o.head??o.documentElement).appendChild(r)};return(async()=>{try{const e=await s(a,{credentials:"omit"});if(!e.ok)throw new Error(`manifest HTTP ${e.status}`);const t=await e.json();if(!t?.coreBundleUrl)throw new Error("manifest missing coreBundleUrl");const r=new URL(t.coreBundleUrl,a).toString();p(r,t.integrity)}catch(e){console.warn("[ZeroGpuSdk] Manifest unavailable, falling back to stable bundle.",e),p(u)}})()};(()=>{if("undefined"==typeof document||"undefined"==typeof window)return;const e=document.currentScript instanceof HTMLScriptElement?document.currentScript:null;e&&n({script:e,documentRef:document,windowRef:window,fetchImpl:window.fetch.bind(window),baseUri:document.baseURI})})(),e.bootZeroGpuLoader=n}({});
1
+ !function(e){"use strict";const t="ZeroGpuBrowserSdk",r="ZeroGpuSdk",n=e=>{const{script:n,documentRef:o,windowRef:i,fetchImpl:s}=e;if(i[t]?.initZeroGpuSdk)return Promise.resolve();const c=/^(true|1)$/i.test((n.getAttribute("data-enable-console-logs")??n.getAttribute("enableConsoleLogs")??"").trim()),d=(...e)=>{c&&console.warn(...e)},a=(...e)=>{c&&console.error(...e)},u=n.getAttribute("src")??"";let l;try{l=new URL(u,e.baseUri)}catch{l=new URL(e.baseUri)}const m=new URL("manifest.json",l).toString(),f=new URL("zerogpu-browser-sdk.umd.js",l).toString(),w=[];let p=()=>{};const b=new Promise(e=>{p=e}),g=()=>{const e=i[t];if(e&&"function"==typeof e.initZeroGpuSdk){for(i[r]=e;w.length>0;){const t=w.shift();try{const r=e[t.method];Promise.resolve(r?.(...t.args)).then(t.resolve,t.reject)}catch(e){t.reject(e)}}p()}else a("[ZeroGpuSdk] Core bundle loaded but global API is missing.")};i[r]||(i[r]={ready:b,initZeroGpuSdk:(...e)=>new Promise((t,r)=>{w.push({method:"initZeroGpuSdk",args:e,resolve:t,reject:r})})});const h=(e,t)=>{const r=o.createElement("script");for(const e of Array.from(n.attributes))"src"!==e.name&&"integrity"!==e.name&&r.setAttribute(e.name,e.value);r.src=e,r.async=!0,r.setAttribute("data-zerogpu-core","true"),t&&(r.integrity=t,r.crossOrigin=n.crossOrigin??"anonymous"),r.addEventListener("load",g),r.addEventListener("error",()=>{a("[ZeroGpuSdk] Failed to load core bundle from",e)}),(o.head??o.documentElement).appendChild(r)};return(async()=>{try{const e=await s(m,{credentials:"omit"});if(!e.ok)throw new Error(`manifest HTTP ${e.status}`);const t=await e.json();if(!t?.coreBundleUrl)throw new Error("manifest missing coreBundleUrl");const r=new URL(t.coreBundleUrl,m).toString();h(r,t.integrity)}catch(e){d("[ZeroGpuSdk] Manifest unavailable, falling back to stable bundle.",e),h(f)}})()};(()=>{if("undefined"==typeof document||"undefined"==typeof window)return;const e=document.currentScript instanceof HTMLScriptElement?document.currentScript:null;e&&n({script:e,documentRef:document,windowRef:window,fetchImpl:window.fetch.bind(window),baseUri:document.baseURI})})(),e.bootZeroGpuLoader=n}({});
2
2
  //# sourceMappingURL=loader.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader.js","sources":["../../src/loader.ts"],"sourcesContent":[null],"names":["GLOBAL_NAME","STUB_NAME","bootZeroGpuLoader","env","script","documentRef","windowRef","fetchImpl","initZeroGpuSdk","Promise","resolve","loaderSrc","getAttribute","baseUrl","URL","baseUri","manifestUrl","toString","fallbackBundleUrl","queue","resolveReady","ready","flushQueue","api","length","call","shift","method","args","then","reject","error","console","push","injectCoreBundle","bundleUrl","integrity","core","createElement","attr","Array","from","attributes","name","setAttribute","value","src","async","crossOrigin","addEventListener","head","documentElement","appendChild","response","credentials","ok","Error","status","manifest","json","coreBundleUrl","warn","document","window","currentScript","HTMLScriptElement","fetch","bind","baseURI"],"mappings":"0BA2CA,MAAMA,EAAc,oBACdC,EAAY,aAELC,EAAqBC,IAChC,MAAMC,OAAEA,EAAMC,YAAEA,EAAWC,UAAEA,EAASC,UAAEA,GAAcJ,EAItD,GAAIG,EAAUN,IAAcQ,eAC1B,OAAOC,QAAQC,UAGjB,MAAMC,EAAYP,EAAOQ,aAAa,QAAU,GAChD,IAAIC,EACJ,IACEA,EAAU,IAAIC,IAAIH,EAAWR,EAAIY,QACnC,CACA,MACEF,EAAU,IAAIC,IAAIX,EAAIY,QACxB,CACA,MAAMC,EAAc,IAAIF,IAAI,gBAAiBD,GAASI,WAGhDC,EAAoB,IAAIJ,IAC5B,6BACAD,GACAI,WAIIE,EAAsB,GAC5B,IAAIC,EAA2B,OAC/B,MAAMC,EAAQ,IA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M,kCAElB,MAAMrB,EAAY,IAAIrB,IAAI4C,EAASE,cAAe5C,GAAaC,WAC/DiB,EAAiBC,EAAWuB,EAAStB,UACvC,CACA,MAAOL,GACLC,QAAQ6B,KACN,oEACA9B,GAEFG,EAAiBhB,EACnB,CACD,EApBM,IAwBT,MACE,GAAwB,oBAAb4C,UAA8C,oBAAXC,OAC5C,OAEF,MAAM3D,EACJ0D,SAASE,yBAAyBC,kBAC9BH,SAASE,cACT,KACD5D,GAGAF,EAAkB,CACrBE,SACAC,YAAayD,SACbxD,UAAWyD,OACXxD,UAAWwD,OAAOG,MAAMC,KAAKJ,QAC7BhD,QAAS+C,SAASM,SAErB,EAlBD"}
1
+ {"version":3,"file":"loader.js","sources":["../../src/loader.ts"],"sourcesContent":[null],"names":["GLOBAL_NAME","STUB_NAME","bootZeroGpuLoader","env","script","documentRef","windowRef","fetchImpl","initZeroGpuSdk","Promise","resolve","consoleLogsEnabled","test","getAttribute","trim","loaderLog","args","console","warn","error","loaderSrc","baseUrl","URL","baseUri","manifestUrl","toString","fallbackBundleUrl","queue","resolveReady","ready","flushQueue","api","length","call","shift","method","then","reject","push","injectCoreBundle","bundleUrl","integrity","core","createElement","attr","Array","from","attributes","name","setAttribute","value","src","async","crossOrigin","addEventListener","head","documentElement","appendChild","response","credentials","ok","Error","status","manifest","json","coreBundleUrl","document","window","currentScript","HTMLScriptElement","fetch","bind","baseURI"],"mappings":"0BAwDA,MAAMA,EAAc,oBACdC,EAAY,aAELC,EAAqBC,IAChC,MAAMC,OAAEA,EAAMC,YAAEA,EAAWC,UAAEA,EAASC,UAAEA,GAAcJ,EAItD,GAAIG,EAAUN,IAAcQ,eAC1B,OAAOC,QAAQC,UAQjB,MAAMC,EAAqB,cAAcC,MAErCR,EAAOS,aAAa,6BACpBT,EAAOS,aAAa,sBACpB,IACAC,QAEEC,EACE,IAAIC,KACJL,GAAoBM,QAAQC,QAAQF,IAFtCD,EAIG,IAAIC,KACLL,GAAoBM,QAAQE,SAASH,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iB,OAAQxB,GAC9BY,EAAKY,iBAAiB,QAAS,KAC7BvC,EAAgB,+CAAgDyB,MAEjEnC,EAAYkD,MAAQlD,EAAYmD,iBAAiBC,YAAYf,IAGhE,MAAO,WACL,IACE,MAAMgB,QAAiBnD,EAAUiB,EAAa,CAAEmC,YAAa,SAC7D,IAAKD,EAASE,GACZ,MAAM,IAAIC,MAAM,iBAAiBH,EAASI,UAE5C,MAAMC,QAAkBL,EAASM,OACjC,IAAKD,GAAUE,cACb,MAAM,IAAIJ,MAAM,kCAElB,MAAMrB,EAAY,IAAIlB,IAAIyC,EAASE,cAAezC,GAAaC,WAC/Dc,EAAiBC,EAAWuB,EAAStB,UACvC,CACA,MAAOtB,GACLJ,EACE,oEACAI,GAEFoB,EAAiBb,EACnB,CACD,EApBM,IAwBT,MACE,GAAwB,oBAAbwC,UAA8C,oBAAXC,OAC5C,OAEF,MAAM/D,EACJ8D,SAASE,yBAAyBC,kBAC9BH,SAASE,cACT,KACDhE,GAGAF,EAAkB,CACrBE,SACAC,YAAa6D,SACb5D,UAAW6D,OACX5D,UAAW4D,OAAOG,MAAMC,KAAKJ,QAC7B5C,QAAS2C,SAASM,SAErB,EAlBD"}
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.2.0+12c5b00",
3
- "channel": "official",
4
- "buildId": "af4825958dcb",
5
- "coreBundleUrl": "v/zerogpu-browser-sdk.af4825958dcb.umd.js",
6
- "integrity": "sha384-ExHvkUH6N4JKKRVxyQ81XCh2w6UGICAL085F9/veTAS300PslrNBk/gN3A1r2q/Q",
7
- "builtAt": "2026-07-24T18:44:23.675Z"
2
+ "version": "0.2.1-dev.202607301617.g61d37c5+61d37c5",
3
+ "channel": "development",
4
+ "buildId": "f232041bce9b",
5
+ "coreBundleUrl": "v/zerogpu-browser-sdk.f232041bce9b.umd.js",
6
+ "integrity": "sha384-PAqCAjbkHKDZwTDhypstDjf1KhauTIL51/OhERrCSNIe6VcynayWmDayjH684w0G",
7
+ "builtAt": "2026-07-30T16:18:26.779Z"
8
8
  }
@@ -1,7 +1,21 @@
1
+ /**
2
+ * wllama ships no bundled types and is loaded at runtime from a CDN (or a
3
+ * vendored copy under MV3), so it cannot be imported for its types. These are
4
+ * structural stand-ins: `unknown`-valued bags that force narrowing at the call
5
+ * site rather than `any`, which would silently disable checking everywhere the
6
+ * instance travels.
7
+ */
8
+ export interface WllamaInstance {
9
+ loadModel: (blobs: Blob[], options?: Record<string, unknown>) => Promise<void>;
10
+ createCompletion: (prompt: string, options?: Record<string, unknown>) => Promise<string>;
11
+ }
12
+ export interface WllamaModule {
13
+ Wllama: new (config?: Record<string, string>) => WllamaInstance;
14
+ }
1
15
  declare global {
2
16
  interface Window {
3
- WllamaModule?: any;
4
- WllamaInstance?: any;
17
+ WllamaModule?: WllamaModule;
18
+ WllamaInstance?: WllamaInstance;
5
19
  /**
6
20
  * Optional override for the wllama wasm asset paths. When set (e.g. by a
7
21
  * Chrome-extension offscreen host that vendors wllama locally), the GGUF
@@ -12,5 +26,5 @@ declare global {
12
26
  WllamaWasmPaths?: Record<string, string>;
13
27
  }
14
28
  }
15
- export declare const ensureWllamaRuntime: () => Promise<any>;
29
+ export declare const ensureWllamaRuntime: () => Promise<WllamaModule>;
16
30
  export declare const WLLAMA_CDN_BASE: string;
@@ -1,7 +1,35 @@
1
+ /**
2
+ * transformers.js is loaded at runtime from a CDN (or a vendored copy under
3
+ * MV3) and ships no types we can import, so these describe only the surface
4
+ * this SDK actually touches. Everything is optional because the shape differs
5
+ * across transformers.js versions and the SDK must degrade rather than throw.
6
+ */
7
+ export type TransformersPipelineFn = (input: string | string[], options?: unknown) => Promise<unknown>;
8
+ export interface TransformersOnnxWasmEnv {
9
+ proxy?: boolean;
10
+ numThreads?: number;
11
+ wasmPaths?: string;
12
+ /** Present only on builds that expose SIMD detection; probed before use. */
13
+ simd?: boolean;
14
+ }
15
+ export interface TransformersEnv {
16
+ allowLocalModels?: boolean;
17
+ allowRemoteModels?: boolean;
18
+ logLevel?: string;
19
+ fetch?: typeof fetch;
20
+ backends?: {
21
+ onnx?: {
22
+ env?: {
23
+ logLevel?: string;
24
+ };
25
+ wasm?: TransformersOnnxWasmEnv;
26
+ };
27
+ };
28
+ }
1
29
  declare global {
2
30
  interface Window {
3
- TransformersPipeline?: (task: string, modelPath: string, options?: Record<string, unknown>) => Promise<any>;
4
- TransformersEnv?: Record<string, any>;
31
+ TransformersPipeline?: (task: string, modelPath: string, options?: Record<string, unknown>) => Promise<TransformersPipelineFn>;
32
+ TransformersEnv?: TransformersEnv;
5
33
  }
6
34
  }
7
35
  export declare const TRANSFORMERS_CDN = "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";
@@ -1,6 +1,6 @@
1
1
  import { SdkConfig } from './types';
2
2
  type DeepPartial<T> = {
3
- [K in keyof T]?: T[K] extends Array<infer U> ? Array<DeepPartial<U>> : T[K] extends Record<string, any> ? DeepPartial<T[K]> : T[K];
3
+ [K in keyof T]?: T[K] extends Array<infer U> ? Array<DeepPartial<U>> : T[K] extends object ? DeepPartial<T[K]> : T[K];
4
4
  };
5
5
  export type ConfigOverrides = DeepPartial<SdkConfig>;
6
6
  export declare const resolveConfig: (overrides?: ConfigOverrides) => SdkConfig;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Typed accessors for the non-standard browser surfaces this SDK reads.
3
+ *
4
+ * None of these are in TypeScript's DOM lib: the Telegram Mini App bridge is
5
+ * injected by the host, and `userAgentData` / `deviceMemory` / `getBattery` /
6
+ * `connection` are all optional vendor extensions that may be absent on any
7
+ * given engine. Declaring them here once — rather than casting to `any` at each
8
+ * read — keeps the optionality visible at the call site, which matters because
9
+ * every one of these fields feeds a guardrail decision.
10
+ */
11
+ export interface TelegramUser {
12
+ id?: number;
13
+ username?: string;
14
+ first_name?: string;
15
+ last_name?: string;
16
+ language_code?: string;
17
+ }
18
+ export interface TelegramWebApp {
19
+ platform?: string;
20
+ version?: string;
21
+ themeParams?: Record<string, unknown>;
22
+ initDataUnsafe?: {
23
+ user?: TelegramUser;
24
+ };
25
+ }
26
+ /** Chromium-only; absent on Safari and Firefox. */
27
+ export interface NavigatorUserAgentData {
28
+ mobile?: boolean;
29
+ platform?: string;
30
+ }
31
+ /** Battery Status API — removed from Firefox, gated in Safari. */
32
+ export interface BatteryManager {
33
+ level: number;
34
+ charging: boolean;
35
+ }
36
+ /** Network Information API — Chromium-only, and vendor-prefixed on older builds. */
37
+ export interface NetworkInformation {
38
+ effectiveType?: string;
39
+ downlink?: number;
40
+ rtt?: number;
41
+ }
42
+ type ExtendedNavigator = Navigator & {
43
+ userAgentData?: NavigatorUserAgentData;
44
+ /** Approximate device RAM in GiB, rounded down to a power of two. Chromium-only. */
45
+ deviceMemory?: number;
46
+ getBattery?: () => Promise<BatteryManager>;
47
+ connection?: NetworkInformation;
48
+ mozConnection?: NetworkInformation;
49
+ webkitConnection?: NetworkInformation;
50
+ };
51
+ export declare const extendedNavigator: () => ExtendedNavigator;
52
+ /** The injected Telegram bridge, or undefined when not running inside a Mini App. */
53
+ export declare const telegramWebApp: () => TelegramWebApp | undefined;
54
+ export {};
@@ -14,12 +14,24 @@
14
14
  *
15
15
  * The loader has no runtime imports — it must stay self-contained and minifiable.
16
16
  */
17
+ /**
18
+ * The SDK's own window globals, as the loader sees them before the core bundle
19
+ * has replaced the stub. Methods are indexed by name because the queue replays
20
+ * arbitrary calls, so the value type stays callable rather than `unknown`.
21
+ */
22
+ type LoaderApiMethod = (...args: unknown[]) => unknown;
23
+ interface ZeroGpuGlobal {
24
+ ready?: Promise<void>;
25
+ initZeroGpuSdk?: LoaderApiMethod;
26
+ [method: string]: LoaderApiMethod | Promise<void> | undefined;
27
+ }
17
28
  /** Injected dependencies so the loader is unit-testable without a real browser. */
18
29
  export interface LoaderEnv {
19
30
  script: HTMLScriptElement;
20
31
  documentRef: Document;
21
- windowRef: Record<string, any>;
32
+ windowRef: Record<string, ZeroGpuGlobal | undefined>;
22
33
  fetchImpl: typeof fetch;
23
34
  baseUri: string;
24
35
  }
25
36
  export declare const bootZeroGpuLoader: (env: LoaderEnv) => Promise<void>;
37
+ export {};
@@ -4,8 +4,8 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZeroGpuBrowserSdk = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- const SDK_VERSION = typeof "0.2.0+12c5b00" === 'string' && "0.2.0+12c5b00".length > 0
8
- ? "0.2.0+12c5b00"
7
+ const SDK_VERSION = typeof "0.2.1-dev.202607301617.g61d37c5+61d37c5" === 'string' && "0.2.1-dev.202607301617.g61d37c5+61d37c5".length > 0
8
+ ? "0.2.1-dev.202607301617.g61d37c5+61d37c5"
9
9
  : '0.0.0-dev';
10
10
 
11
11
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -52,7 +52,11 @@
52
52
  };
53
53
  const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
54
54
  const deepMerge = (target, source) => {
55
- const result = Array.isArray(target) ? [...target] : { ...target };
55
+ // Structural clone first, then index it as a plain bag. `T extends object`
56
+ // admits interfaces without index signatures (SdkConfig is one), so the cast
57
+ // is what lets us walk it by key — the `as T` on the way out restores the
58
+ // caller's type, which the per-field validators below re-check anyway.
59
+ const result = (Array.isArray(target) ? [...target] : { ...target });
56
60
  for (const key of Object.keys(source)) {
57
61
  const srcValue = source[key];
58
62
  if (srcValue === undefined)
@@ -150,9 +154,27 @@
150
154
  setStoredDeviceId(deviceId);
151
155
  };
152
156
 
157
+ /**
158
+ * Typed accessors for the non-standard browser surfaces this SDK reads.
159
+ *
160
+ * None of these are in TypeScript's DOM lib: the Telegram Mini App bridge is
161
+ * injected by the host, and `userAgentData` / `deviceMemory` / `getBattery` /
162
+ * `connection` are all optional vendor extensions that may be absent on any
163
+ * given engine. Declaring them here once — rather than casting to `any` at each
164
+ * read — keeps the optionality visible at the call site, which matters because
165
+ * every one of these fields feeds a guardrail decision.
166
+ */
167
+ const extendedNavigator = () => navigator;
168
+ /** The injected Telegram bridge, or undefined when not running inside a Mini App. */
169
+ const telegramWebApp = () => {
170
+ if (typeof window === 'undefined')
171
+ return undefined;
172
+ return window.Telegram?.WebApp;
173
+ };
174
+
153
175
  const getPlatform = () => {
154
176
  const ua = navigator.userAgent.toLowerCase();
155
- const tg = window.Telegram?.WebApp;
177
+ const tg = telegramWebApp();
156
178
  if (tg?.platform)
157
179
  return tg.platform;
158
180
  if (tg)
@@ -169,7 +191,7 @@
169
191
  };
170
192
  const getDeviceType = () => {
171
193
  const ua = navigator.userAgent ?? '';
172
- const uaData = navigator.userAgentData;
194
+ const uaData = extendedNavigator().userAgentData;
173
195
  if (uaData?.mobile === true)
174
196
  return 'mobile';
175
197
  const isTablet = /iPad|Tablet|PlayBook|Silk/i.test(ua) || (navigator.maxTouchPoints > 1 && window.innerWidth >= 768);
@@ -194,8 +216,9 @@
194
216
  };
195
217
  const getBatteryInfo = async () => {
196
218
  try {
197
- if ('getBattery' in navigator) {
198
- const battery = await navigator.getBattery();
219
+ const getBattery = extendedNavigator().getBattery;
220
+ if (getBattery) {
221
+ const battery = await getBattery.call(navigator);
199
222
  return {
200
223
  level: battery.level,
201
224
  charging: battery.charging
@@ -208,7 +231,8 @@
208
231
  return undefined;
209
232
  };
210
233
  const getNetworkInfo = () => {
211
- const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
234
+ const nav = extendedNavigator();
235
+ const conn = nav.connection || nav.mozConnection || nav.webkitConnection;
212
236
  if (conn) {
213
237
  return {
214
238
  type: conn.effectiveType || 'unknown',
@@ -252,7 +276,7 @@
252
276
  }
253
277
  };
254
278
  const getTelegramUser = () => {
255
- const tg = window.Telegram?.WebApp;
279
+ const tg = telegramWebApp();
256
280
  const user = tg?.initDataUnsafe?.user;
257
281
  if (user) {
258
282
  return user;
@@ -269,7 +293,7 @@
269
293
  try {
270
294
  if (typeof window === 'undefined')
271
295
  return false;
272
- if (window.Telegram?.WebApp)
296
+ if (telegramWebApp())
273
297
  return true;
274
298
  return (window.location?.hash || '').includes('tgWebAppData');
275
299
  }
@@ -279,7 +303,7 @@
279
303
  };
280
304
  const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
281
305
  const screen = window.screen || { width: null, height: null };
282
- const tg = window.Telegram?.WebApp;
306
+ const tg = telegramWebApp();
283
307
  const telegramUser = getTelegramUser();
284
308
  const telegramFullName = telegramUser?.first_name || telegramUser?.last_name
285
309
  ? [telegramUser?.first_name, telegramUser?.last_name].filter(Boolean).join(' ')
@@ -305,7 +329,7 @@
305
329
  themeParams: tg?.themeParams,
306
330
  // Hardware
307
331
  cpuCores: navigator.hardwareConcurrency || 1,
308
- memoryGb: navigator.deviceMemory,
332
+ memoryGb: extendedNavigator().deviceMemory,
309
333
  gpuRenderer: getWebGLRenderer(),
310
334
  webglFingerprint: getWebGLRenderer(), // Using renderer as simple fingerprint for now
311
335
  screen: {
@@ -3206,7 +3230,7 @@
3206
3230
  }
3207
3231
  catch (error) {
3208
3232
  transformersRuntimePromise = null;
3209
- console.error('[ZeroGPU][SLM] Failed to import Transformers runtime', {
3233
+ logger.error('[SLM] Failed to import Transformers runtime', {
3210
3234
  runtimeUrl: TRANSFORMERS_CDN,
3211
3235
  error: serializeError$5(error)
3212
3236
  });
@@ -3316,7 +3340,7 @@
3316
3340
  }
3317
3341
  }
3318
3342
  if (sawNonWasmPayloadAtBase) {
3319
- console.warn('[ZeroGPU][SLM] ONNX wasm probe got non-wasm payload', {
3343
+ getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3320
3344
  wasmBase: baseWithSlash
3321
3345
  });
3322
3346
  }
@@ -3447,7 +3471,7 @@
3447
3471
  return await originalFetch(url, init);
3448
3472
  }
3449
3473
  catch (error) {
3450
- console.error('[ZeroGPU][SLM][fetch] non-model wasm/ort request failed', {
3474
+ logger.error('[SLM][fetch] non-model wasm/ort request failed', {
3451
3475
  modelId,
3452
3476
  requestUrl: originalRequestUrl,
3453
3477
  error: serializeError$4(error)
@@ -3498,7 +3522,19 @@
3498
3522
  return new Response('required_file_not_found', { status: 404, statusText: 'Not Found' });
3499
3523
  }
3500
3524
  catch (err) {
3501
- logger.warn(`[ZeroGPU] Failed to fetch ${relative}:`, err);
3525
+ // NOTE: this 502 is synthesised HERE — no gateway was involved. The
3526
+ // caller (transformers.js) reports it against the URL *it* built, which
3527
+ // still carries the huggingface.co prefix this fetch was installed to
3528
+ // replace, so the resulting message reads
3529
+ // "Bad gateway ... https://huggingface.co/https://models.zerogpu.ai/...".
3530
+ // That string means "every candidate URL threw", i.e. a network/abort
3531
+ // failure against the real model host — not an upstream 502 and not a
3532
+ // malformed URL actually being requested.
3533
+ logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
3534
+ modelId,
3535
+ candidates: requestUrls,
3536
+ error: serializeError$4(err)
3537
+ });
3502
3538
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
3503
3539
  }
3504
3540
  };
@@ -3879,9 +3915,9 @@
3879
3915
  catch (error) {
3880
3916
  const message = error instanceof Error ? error.message : String(error);
3881
3917
  if (message.includes("Unexpected token '<'")) {
3882
- console.error('[ZeroGPU][SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected', { modelId: slm.modelId, modelUrl: slm.modelUrl });
3918
+ logger.error('[SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected', { modelId: slm.modelId, modelUrl: slm.modelUrl });
3883
3919
  }
3884
- console.error('[ZeroGPU][SLM][loadOnnxAdapter] failed', {
3920
+ logger.error('[SLM][loadOnnxAdapter] failed', {
3885
3921
  modelId: slm.modelId,
3886
3922
  modelVersion: slm.modelVersion,
3887
3923
  modelRepoId: slm.modelRepoId,
@@ -3889,7 +3925,6 @@
3889
3925
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
3890
3926
  error: serializeError$3(error)
3891
3927
  });
3892
- logger.error('ONNX adapter load failed', error);
3893
3928
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
3894
3929
  return { error: error, metrics: {} };
3895
3930
  }
@@ -4172,14 +4207,13 @@
4172
4207
  return { adapter, metrics };
4173
4208
  }
4174
4209
  catch (error) {
4175
- console.error('[ZeroGPU][Transformers][load] failed', {
4210
+ logger.error('Transformers adapter load failed', {
4176
4211
  modelId: slm.modelId,
4177
4212
  modelVersion: slm.modelVersion,
4178
4213
  modelRepoId: slm.modelRepoId,
4179
4214
  modelUrl: slm.modelUrl,
4180
4215
  error: serializeError$2(error)
4181
4216
  });
4182
- logger.error('Transformers adapter load failed', error);
4183
4217
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4184
4218
  return { error: error, metrics: {} };
4185
4219
  }
@@ -4219,7 +4253,7 @@
4219
4253
  }
4220
4254
  catch (error) {
4221
4255
  wllamaRuntimePromise = null;
4222
- console.error('[ZeroGPU][GGUF] Failed to import wllama runtime', {
4256
+ getLogger().error('[GGUF] Failed to import wllama runtime', {
4223
4257
  runtimeUrl: WLLAMA_CDN,
4224
4258
  error: serializeError$1(error)
4225
4259
  });
@@ -4438,13 +4472,12 @@
4438
4472
  return { adapter, metrics };
4439
4473
  }
4440
4474
  catch (error) {
4441
- console.error('[ZeroGPU][GGUF][load] failed', {
4475
+ logger.error('GGUF adapter load failed', {
4442
4476
  modelId: slm.modelId,
4443
4477
  modelVersion: slm.modelVersion,
4444
4478
  modelUrl: slm.modelUrl,
4445
4479
  error: serializeError(error)
4446
4480
  });
4447
- logger.error('GGUF adapter load failed', error);
4448
4481
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4449
4482
  return { error: error, metrics: {} };
4450
4483
  }
@@ -4616,7 +4649,13 @@
4616
4649
  options.overrides = { telemetry };
4617
4650
  }
4618
4651
  void initZeroGpuSdk(options).catch((error) => {
4619
- console.error('[ZeroGpuSdk] Auto-init failed', error);
4652
+ // The logger singleton may not exist yet when init fails before config
4653
+ // resolution, so honour the script-tag attribute directly. Silent unless
4654
+ // the integrator asked for logs — the failure is reported as an
4655
+ // `sdk.init_failed` device event regardless.
4656
+ if (enableConsoleLogs) {
4657
+ console.error('[ZeroGpuSdk] Auto-init failed', error);
4658
+ }
4620
4659
  });
4621
4660
  };
4622
4661
 
@@ -4625,4 +4664,4 @@
4625
4664
  exports.initZeroGpuSdk = initZeroGpuSdk;
4626
4665
 
4627
4666
  }));
4628
- //# sourceMappingURL=zerogpu-browser-sdk.af4825958dcb.umd.js.map
4667
+ //# sourceMappingURL=zerogpu-browser-sdk.f232041bce9b.umd.js.map