@zerogpu/browser-extension-sdk 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const SDK_VERSION = typeof "0.2.3+38ce04b" === 'string' && "0.2.3+38ce04b".length > 0
4
- ? "0.2.3+38ce04b"
3
+ const SDK_VERSION = typeof "0.3.0+b41a26f" === 'string' && "0.3.0+b41a26f".length > 0
4
+ ? "0.3.0+b41a26f"
5
5
  : '0.0.0-dev';
6
6
 
7
7
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -169,7 +169,7 @@ const sanitizeString = (key, value) => {
169
169
  return cap(value, ID_MAX);
170
170
  return `[string:${value.length}]`;
171
171
  };
172
- const sanitizeValue = (key, value) => {
172
+ const sanitizeValue$1 = (key, value) => {
173
173
  if (CREDENTIAL_KEY_PATTERN.test(key))
174
174
  return '[redacted]';
175
175
  if (value === null || value === undefined)
@@ -194,7 +194,7 @@ const sanitizeLogFields = (fields) => {
194
194
  return { error: summarizeError(fields) };
195
195
  }
196
196
  if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
197
- return { detail: sanitizeValue('detail', fields) };
197
+ return { detail: sanitizeValue$1('detail', fields) };
198
198
  }
199
199
  const sanitized = {};
200
200
  for (const [key, value] of Object.entries(fields)) {
@@ -203,14 +203,14 @@ const sanitizeLogFields = (fields) => {
203
203
  sanitized[key] = '[redacted]';
204
204
  }
205
205
  else if (value.every((item) => item === null || typeof item !== 'object')) {
206
- sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
206
+ sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue$1(key, item));
207
207
  }
208
208
  else {
209
209
  sanitized[key] = describeOpaque(value);
210
210
  }
211
211
  continue;
212
212
  }
213
- sanitized[key] = sanitizeValue(key, value);
213
+ sanitized[key] = sanitizeValue$1(key, value);
214
214
  }
215
215
  return sanitized;
216
216
  };
@@ -2122,6 +2122,140 @@ const fireTrackingScript = async (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
2122
2122
  return fireBeacon(url, timeoutMs);
2123
2123
  };
2124
2124
 
2125
+ /**
2126
+ * Operator macros: three opaque slots an app attaches to every request its
2127
+ * devices serve. ZeroGPU stores and counts them, never interprets them, and
2128
+ * reports them back only to the operator that owns the SDK key.
2129
+ */
2130
+ const CUST_PARAM_SLOTS = ['cust_param1', 'cust_param2', 'cust_param3'];
2131
+ /** Longer values are truncated, never rejected — the server applies the same cap. */
2132
+ const CUST_PARAM_MAX_LENGTH = 128;
2133
+ /**
2134
+ * A slot takes a bare value (`1231231313`, `plan_a`), never a nested
2135
+ * parameter: the slot name is the key, so `user-id=123` is dropped. The server
2136
+ * enforces the same set (@zerogpu/global-types CUST_PARAM_VALUE_PATTERN).
2137
+ */
2138
+ const CUST_PARAM_VALUE_PATTERN = /^[A-Za-z0-9._-]+$/;
2139
+ const isControlChar = (codePoint) => codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
2140
+ const EMAIL_SHAPED = /[^\s@]+@[^\s@]+\.[^\s@]+/;
2141
+ const isSlot = (key) => CUST_PARAM_SLOTS.includes(key);
2142
+ let truncationWarned = false;
2143
+ const sanitizeValue = (slot, raw) => {
2144
+ if (raw === undefined || raw === null)
2145
+ return undefined;
2146
+ let value;
2147
+ if (typeof raw === 'string') {
2148
+ value = raw;
2149
+ }
2150
+ else if ((typeof raw === 'number' && Number.isFinite(raw)) || typeof raw === 'boolean') {
2151
+ value = String(raw);
2152
+ }
2153
+ else {
2154
+ getLogger().warn('[CustomParams] Dropped a value that is not a string, number or boolean', {
2155
+ name: slot,
2156
+ type: typeof raw
2157
+ });
2158
+ return undefined;
2159
+ }
2160
+ value = Array.from(value)
2161
+ .filter((char) => !isControlChar(char.codePointAt(0) ?? 0))
2162
+ .join('')
2163
+ .trim();
2164
+ if (!value)
2165
+ return undefined;
2166
+ // A slot is reported back verbatim and cannot be deleted per value, so an
2167
+ // email address in one is a data-protection problem, not a formatting one.
2168
+ // Loud regardless of enableConsoleLogs: this is an integration mistake that
2169
+ // otherwise shows up only as a silently empty slot.
2170
+ if (EMAIL_SHAPED.test(value)) {
2171
+ // eslint-disable-next-line no-console
2172
+ console.warn(`[ZeroGPU] customParams.${slot} looks like an email address and was dropped. Slots must not carry personal data.`);
2173
+ return undefined;
2174
+ }
2175
+ // Loud for the same reason: the server would drop it too, and the value is
2176
+ // left out of the message in case it is someone's identifier.
2177
+ if (!CUST_PARAM_VALUE_PATTERN.test(value)) {
2178
+ // eslint-disable-next-line no-console
2179
+ console.warn(`[ZeroGPU] customParams.${slot} was dropped. A slot takes just a value (letters, digits, "." "_" "-"), not a nested parameter such as "user-id=123".`);
2180
+ return undefined;
2181
+ }
2182
+ if (value.length > CUST_PARAM_MAX_LENGTH) {
2183
+ if (!truncationWarned) {
2184
+ truncationWarned = true;
2185
+ getLogger().warn('[CustomParams] Value truncated', {
2186
+ name: slot,
2187
+ length: value.length,
2188
+ maxLength: CUST_PARAM_MAX_LENGTH
2189
+ });
2190
+ }
2191
+ value = value.slice(0, CUST_PARAM_MAX_LENGTH);
2192
+ }
2193
+ return value;
2194
+ };
2195
+ /**
2196
+ * Normalizes host input to the slots the server accepts. Never throws: a bad
2197
+ * value is dropped (with a warning) so a macro mistake can never stop the SDK.
2198
+ * Unset, empty and dropped slots are all simply absent from the result.
2199
+ */
2200
+ const sanitizeCustomParams = (input) => {
2201
+ const resolved = {};
2202
+ if (input === undefined || input === null)
2203
+ return resolved;
2204
+ if (typeof input !== 'object' || Array.isArray(input)) {
2205
+ getLogger().warn('[CustomParams] Ignored: expected an object of cust_param1..3', {
2206
+ type: Array.isArray(input) ? 'array' : typeof input
2207
+ });
2208
+ return resolved;
2209
+ }
2210
+ const source = input;
2211
+ // Host objects can be Proxies or carry getters, and either can throw on read.
2212
+ let keys;
2213
+ try {
2214
+ keys = Object.keys(source);
2215
+ }
2216
+ catch {
2217
+ getLogger().warn('[CustomParams] Ignored: the object could not be read');
2218
+ return resolved;
2219
+ }
2220
+ for (const key of keys) {
2221
+ if (!isSlot(key)) {
2222
+ getLogger().warn('[CustomParams] Ignored an unknown key; only cust_param1..3 are accepted', {
2223
+ name: key
2224
+ });
2225
+ continue;
2226
+ }
2227
+ let raw;
2228
+ try {
2229
+ raw = source[key];
2230
+ }
2231
+ catch {
2232
+ getLogger().warn('[CustomParams] Dropped a value that could not be read', { name: key });
2233
+ continue;
2234
+ }
2235
+ const value = sanitizeValue(key, raw);
2236
+ if (value !== undefined)
2237
+ resolved[key] = value;
2238
+ }
2239
+ return resolved;
2240
+ };
2241
+ let current = {};
2242
+ /** Replaces the whole map: slots omitted from `input` become unset. */
2243
+ const setCustomParamsState = (input) => {
2244
+ current = sanitizeCustomParams(input);
2245
+ };
2246
+ /** Only the set slots — spread flat onto the register body. */
2247
+ const getRegisterCustomParams = () => ({ ...current });
2248
+ /**
2249
+ * Every slot, `''` when unset. The server merges per job over the register-time
2250
+ * values slot by slot, and an explicit `''` is what clears a slot that was set
2251
+ * at register time — omitting it would leave the stale value in place.
2252
+ */
2253
+ const getTaskResultCustomParams = () => ({
2254
+ cust_param1: current.cust_param1 ?? '',
2255
+ cust_param2: current.cust_param2 ?? '',
2256
+ cust_param3: current.cust_param3 ?? ''
2257
+ });
2258
+
2125
2259
  let executing = false;
2126
2260
  const buildInferenceInput = (request) => {
2127
2261
  const input = request.input ?? {};
@@ -2173,6 +2307,12 @@ const lazyLoadAdapter = async (modelId) => {
2173
2307
  const executeSingleRequest = async (request) => {
2174
2308
  const logger = getLogger();
2175
2309
  const start = performance.now();
2310
+ // Snapshot before the first await. The macros are module state a host can
2311
+ // replace at any time via setCustomParams, and everything below — the lazy
2312
+ // adapter load, inference, the pixel turn — yields. Reading them at result
2313
+ // time would attribute an in-flight request to whatever the host switched to
2314
+ // mid-flight, breaking the documented "applies from the next request served".
2315
+ const custParams = getTaskResultCustomParams();
2176
2316
  const { adaptersByModelId } = getState();
2177
2317
  let adapter = adaptersByModelId?.[request.modelId];
2178
2318
  if (!adapter) {
@@ -2265,7 +2405,8 @@ const executeSingleRequest = async (request) => {
2265
2405
  errorMessage: '',
2266
2406
  metadata: {
2267
2407
  processingTime: Math.round(performance.now() - start),
2268
- ...(await pixelMetadata())
2408
+ ...(await pixelMetadata()),
2409
+ customParams: custParams
2269
2410
  }
2270
2411
  };
2271
2412
  }
@@ -3139,7 +3280,8 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3139
3280
  cachedModels: cachedInfo && !cacheInvalid
3140
3281
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3141
3282
  : [],
3142
- device: deviceInfo
3283
+ device: deviceInfo,
3284
+ ...getRegisterCustomParams()
3143
3285
  };
3144
3286
  let registerResponse;
3145
3287
  let assignedModels = [];
@@ -5176,6 +5318,12 @@ const initZeroGpuSdk = async (options) => {
5176
5318
  }
5177
5319
  }
5178
5320
  const config = resolveConfig(options?.overrides);
5321
+ if (options?.customParams !== undefined) {
5322
+ // Validation warnings go through the logger, which startLifecycle would
5323
+ // otherwise only configure after the values are already applied.
5324
+ initLogger(config.telemetry);
5325
+ setCustomParamsState(options.customParams);
5326
+ }
5179
5327
  try {
5180
5328
  await startLifecycle({
5181
5329
  config,
@@ -5191,6 +5339,14 @@ const initZeroGpuSdk = async (options) => {
5191
5339
  }
5192
5340
  return handle;
5193
5341
  };
5342
+ /**
5343
+ * Replaces the operator macros: slots omitted here become unset, and
5344
+ * `setCustomParams({})` clears them all. Applies from the next request the
5345
+ * device serves — no re-registration. Safe to call before or after init.
5346
+ */
5347
+ const setCustomParams = (params) => {
5348
+ setCustomParamsState(params);
5349
+ };
5194
5350
 
5195
5351
  const readAttr = (script, names) => {
5196
5352
  for (const name of names) {
@@ -5268,6 +5424,17 @@ const autoInitFromScriptTag = () => {
5268
5424
  readSearchParam(searchParams, ['device-id', 'deviceId']),
5269
5425
  edgeOperatorKey
5270
5426
  };
5427
+ const customParams = {};
5428
+ for (const slot of CUST_PARAM_SLOTS) {
5429
+ const suffix = slot.slice('cust_param'.length);
5430
+ const value = readAttr(script, [`data-cust-param${suffix}`, slot]) ??
5431
+ readSearchParam(searchParams, [`cust-param${suffix}`, slot]);
5432
+ if (value !== undefined)
5433
+ customParams[slot] = value;
5434
+ }
5435
+ if (Object.keys(customParams).length > 0) {
5436
+ options.customParams = customParams;
5437
+ }
5271
5438
  const enableConsoleLogs = readBooleanAttr(script, ['data-enable-console-logs', 'enableConsoleLogs']) ??
5272
5439
  (() => {
5273
5440
  const value = readSearchParam(searchParams, ['enable-console-logs', 'enableConsoleLogs']);
@@ -5319,4 +5486,5 @@ const autoInitFromScriptTag = () => {
5319
5486
  autoInitFromScriptTag();
5320
5487
 
5321
5488
  exports.initZeroGpuSdk = initZeroGpuSdk;
5489
+ exports.setCustomParams = setCustomParams;
5322
5490
  //# sourceMappingURL=zerogpu-browser-sdk.cjs.map