@alva-ai/toolkit 0.7.0 → 0.9.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.
package/dist/index.cjs CHANGED
@@ -22,7 +22,29 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  AlvaClient: () => AlvaClient,
24
24
  AlvaError: () => AlvaError,
25
- VERSION: () => VERSION
25
+ PBSV_UPDATE_MESSAGE: () => PBSV_UPDATE_MESSAGE,
26
+ UDF_CONSENT_REQUEST_MESSAGE: () => UDF_CONSENT_REQUEST_MESSAGE,
27
+ UDF_CONSENT_RESPONSE_MESSAGE: () => UDF_CONSENT_RESPONSE_MESSAGE,
28
+ UdfAuthRequiredError: () => UdfAuthRequiredError,
29
+ UdfConsentDeniedError: () => UdfConsentDeniedError,
30
+ UdfConsentRequiredError: () => UdfConsentRequiredError,
31
+ UdfConsentTimeoutError: () => UdfConsentTimeoutError,
32
+ UdfError: () => UdfError,
33
+ UdfExecutionError: () => UdfExecutionError,
34
+ UdfFunctionDisabledError: () => UdfFunctionDisabledError,
35
+ UdfFunctionNotFoundError: () => UdfFunctionNotFoundError,
36
+ UdfInsufficientCredits: () => UdfInsufficientCredits,
37
+ UdfPidMismatchError: () => UdfPidMismatchError,
38
+ UdfRateLimitedError: () => UdfRateLimitedError,
39
+ UdfTokenExpiredError: () => UdfTokenExpiredError,
40
+ UdfTokenInvalidError: () => UdfTokenInvalidError,
41
+ UdfTransportError: () => UdfTransportError,
42
+ VERSION: () => VERSION,
43
+ getViewerToken: () => getViewerToken,
44
+ installPlaybookRuntime: () => installPlaybookRuntime,
45
+ mapUdfErrorResponse: () => mapUdfErrorResponse,
46
+ playbookIdFromToken: () => playbookIdFromToken,
47
+ udf: () => udf
26
48
  });
27
49
  module.exports = __toCommonJS(src_exports);
28
50
 
@@ -175,7 +197,8 @@ var RunResource = class {
175
197
  code: params.code,
176
198
  entry_path: params.entry_path,
177
199
  working_dir: params.working_dir,
178
- args: params.args
200
+ args: params.args,
201
+ max_heap_size_mb: params.max_heap_size_mb
179
202
  }
180
203
  });
181
204
  }
@@ -303,7 +326,8 @@ var ReleaseResource = class {
303
326
  description: params.description,
304
327
  feeds: params.feeds,
305
328
  trading_symbols: params.trading_symbols,
306
- template_id: params.template_id
329
+ skill_id: params.skill_id,
330
+ tags: params.tags
307
331
  }
308
332
  });
309
333
  }
@@ -321,6 +345,86 @@ var ReleaseResource = class {
321
345
  }
322
346
  };
323
347
 
348
+ // src/resources/feed.ts
349
+ var FeedResource = class {
350
+ constructor(client) {
351
+ this.client = client;
352
+ }
353
+ client;
354
+ /**
355
+ * Soft-delete a feed and all its active majors. Cascades:
356
+ * - all active feed_majors are soft-deleted in the same transaction
357
+ * - associated producer cronjobs are removed best-effort (the cronjob
358
+ * scavenger reconciles any leftover rows on its next sweep)
359
+ *
360
+ * Auth: caller must own the feed (uid match), enforced by the backend.
361
+ */
362
+ async delete(params) {
363
+ this.client._requireAuth();
364
+ if (!Number.isInteger(params.id) || params.id <= 0) {
365
+ throw new Error("feed id must be a positive integer");
366
+ }
367
+ return this.client._request(
368
+ "DELETE",
369
+ `/api/v1/feed/${encodeURIComponent(String(params.id))}`
370
+ );
371
+ }
372
+ };
373
+
374
+ // src/resources/playbooks.ts
375
+ var PlaybooksResource = class {
376
+ constructor(client) {
377
+ this.client = client;
378
+ }
379
+ client;
380
+ /**
381
+ * List trending / searchable playbooks. Auth is optional: when the client
382
+ * has an API key it is forwarded, otherwise this uses the public surface.
383
+ *
384
+ * The gateway returns a frontend-oriented preview payload; this SDK projects
385
+ * it into a smaller, agent-friendly shape.
386
+ */
387
+ async trending(params = {}) {
388
+ const query = {};
389
+ if (params.cursor) query.cursor = params.cursor;
390
+ if (params.current) query.current = params.current;
391
+ if (params.limit !== void 0) query.limit = params.limit;
392
+ if (params.dir) query.dir = params.dir;
393
+ if (params.sort) query.sort = params.sort;
394
+ if (params.keyword) query.keyword = params.keyword;
395
+ if (params.tags && params.tags.length > 0) {
396
+ query.tags = params.tags.join(",");
397
+ }
398
+ const raw = await this.client._request(
399
+ "GET",
400
+ "/api/v1/playbooks/trending",
401
+ { query }
402
+ );
403
+ return {
404
+ playbooks: (raw.playbooks ?? []).map(toAgentPlaybook),
405
+ has_next: raw.has_next ?? false
406
+ };
407
+ }
408
+ };
409
+ function toAgentPlaybook(raw) {
410
+ const username = raw.creator?.name ?? "";
411
+ const name = raw.name ?? "";
412
+ const ref = username && name ? `${username}/${name}` : name;
413
+ return {
414
+ id: raw.id === void 0 ? "" : String(raw.id),
415
+ ref,
416
+ username,
417
+ name,
418
+ display_name: raw.display_name ?? "",
419
+ description: raw.description ?? "",
420
+ tags: raw.tags ?? [],
421
+ follow_count: raw.follow_count ?? 0,
422
+ url_path: username && name ? `/${username}/playbooks/${name}` : "",
423
+ ...raw.readme ? { readme: raw.readme } : {},
424
+ cursor: raw.cursor ?? ""
425
+ };
426
+ }
427
+
324
428
  // src/resources/secrets.ts
325
429
  var SecretsResource = class {
326
430
  constructor(client) {
@@ -390,6 +494,26 @@ var SdkDocsResource = class {
390
494
 
391
495
  // src/resources/skillTiers.ts
392
496
  var SKILL_ENDPOINT_METADATA = [
497
+ {
498
+ skill: "arrays-data-api-crypto-futures-data",
499
+ file: "binance-perp-usdt-kline",
500
+ method: "GET",
501
+ path: "/api/v1/crypto/binance/perp/usdt/kline",
502
+ tier: "public",
503
+ required_subscription_tier: "free",
504
+ access: "free_and_pro",
505
+ pro_required: false
506
+ },
507
+ {
508
+ skill: "arrays-data-api-spot-market-price-and-volume",
509
+ file: "binance-spot-usdt-kline",
510
+ method: "GET",
511
+ path: "/api/v1/crypto/binance/spot/usdt/kline",
512
+ tier: "public",
513
+ required_subscription_tier: "free",
514
+ access: "free_and_pro",
515
+ pro_required: false
516
+ },
393
517
  {
394
518
  skill: "arrays-data-api-spot-market-price-and-volume",
395
519
  file: "crypto-detail",
@@ -421,10 +545,10 @@ var SKILL_ENDPOINT_METADATA = [
421
545
  pro_required: false
422
546
  },
423
547
  {
424
- skill: "arrays-data-api-spot-market-price-and-volume",
425
- file: "crypto-futures-ohlcv",
548
+ skill: "arrays-data-api-crypto-futures-data",
549
+ file: "hyperliquid-perp-usdc-kline",
426
550
  method: "GET",
427
- path: "/api/v1/crypto/futures/ohlcv",
551
+ path: "/api/v1/crypto/hyperliquid/perp/usdc/kline",
428
552
  tier: "public",
429
553
  required_subscription_tier: "free",
430
554
  access: "free_and_pro",
@@ -432,9 +556,9 @@ var SKILL_ENDPOINT_METADATA = [
432
556
  },
433
557
  {
434
558
  skill: "arrays-data-api-spot-market-price-and-volume",
435
- file: "crypto-kline",
559
+ file: "hyperliquid-spot-usdc-kline",
436
560
  method: "GET",
437
- path: "/api/v1/crypto/kline",
561
+ path: "/api/v1/crypto/hyperliquid/spot/usdc/kline",
438
562
  tier: "public",
439
563
  required_subscription_tier: "free",
440
564
  access: "free_and_pro",
@@ -480,16 +604,6 @@ var SKILL_ENDPOINT_METADATA = [
480
604
  access: "free_and_pro",
481
605
  pro_required: false
482
606
  },
483
- {
484
- skill: "arrays-data-api-spot-market-price-and-volume",
485
- file: "crypto-ohlcv",
486
- method: "GET",
487
- path: "/api/v1/crypto/ohlcv",
488
- tier: "public",
489
- required_subscription_tier: "free",
490
- access: "free_and_pro",
491
- pro_required: false
492
- },
493
607
  {
494
608
  skill: "arrays-data-api-crypto-futures-data",
495
609
  file: "open-interest",
@@ -1180,16 +1294,6 @@ var SKILL_ENDPOINT_METADATA = [
1180
1294
  access: "pro_only",
1181
1295
  pro_required: true
1182
1296
  },
1183
- {
1184
- skill: "arrays-data-api-equity-ownership-and-flow",
1185
- file: "senate-trade",
1186
- method: "GET",
1187
- path: "/api/v1/stocks/company/senate-trade",
1188
- tier: "alternative",
1189
- required_subscription_tier: "pro",
1190
- access: "pro_only",
1191
- pro_required: true
1192
- },
1193
1297
  {
1194
1298
  skill: "arrays-data-api-stock-metrics",
1195
1299
  file: "darkpool",
@@ -1429,6 +1533,50 @@ var SKILL_ENDPOINT_METADATA = [
1429
1533
  required_subscription_tier: "pro",
1430
1534
  access: "pro_only",
1431
1535
  pro_required: true
1536
+ },
1537
+ {
1538
+ // TODO(audit): verify tier — auto-defaulted to pro
1539
+ skill: "arrays-data-api-social-feeds",
1540
+ file: "x-by-handle",
1541
+ method: "GET",
1542
+ path: "/api/v1/social-feeds/x/by-handle",
1543
+ tier: "alternative",
1544
+ required_subscription_tier: "pro",
1545
+ access: "pro_only",
1546
+ pro_required: true
1547
+ },
1548
+ {
1549
+ // TODO(audit): verify tier — auto-defaulted to pro
1550
+ skill: "arrays-data-api-social-feeds",
1551
+ file: "x-by-url",
1552
+ method: "GET",
1553
+ path: "/api/v1/social-feeds/x/by-url",
1554
+ tier: "alternative",
1555
+ required_subscription_tier: "pro",
1556
+ access: "pro_only",
1557
+ pro_required: true
1558
+ },
1559
+ {
1560
+ // TODO(audit): verify tier — auto-defaulted to pro
1561
+ skill: "arrays-data-api-social-feeds",
1562
+ file: "x-entities-handle",
1563
+ method: "GET",
1564
+ path: "/api/v1/social-feeds/x/entities/handle/{twitter_handle}",
1565
+ tier: "alternative",
1566
+ required_subscription_tier: "pro",
1567
+ access: "pro_only",
1568
+ pro_required: true
1569
+ },
1570
+ {
1571
+ // TODO(audit): verify tier — auto-defaulted to pro
1572
+ skill: "arrays-data-api-social-feeds",
1573
+ file: "x-entities-handles",
1574
+ method: "GET",
1575
+ path: "/api/v1/social-feeds/x/entities/handles",
1576
+ tier: "alternative",
1577
+ required_subscription_tier: "pro",
1578
+ access: "pro_only",
1579
+ pro_required: true
1432
1580
  }
1433
1581
  ];
1434
1582
  function getSkillEndpointMetadata(skill, file) {
@@ -1823,6 +1971,38 @@ function buildQuery(params) {
1823
1971
  return q;
1824
1972
  }
1825
1973
 
1974
+ // src/resources/notificationPreferences.ts
1975
+ var NotificationPreferencesResource = class {
1976
+ constructor(client) {
1977
+ this.client = client;
1978
+ }
1979
+ client;
1980
+ /**
1981
+ * List the caller's notification preference settings. Server defaults
1982
+ * are included even when the caller has not explicitly stored a setting.
1983
+ */
1984
+ async list() {
1985
+ this.client._requireAuth();
1986
+ return this.client._request(
1987
+ "GET",
1988
+ "/api/v1/me/notifications/preferences"
1989
+ );
1990
+ }
1991
+ /**
1992
+ * Enable or disable one notification preference.
1993
+ */
1994
+ async update(params) {
1995
+ this.client._requireAuth();
1996
+ return this.client._request(
1997
+ "PATCH",
1998
+ `/api/v1/me/notifications/preferences/${encodeURIComponent(params.key)}`,
1999
+ {
2000
+ body: { enabled: params.enabled }
2001
+ }
2002
+ );
2003
+ }
2004
+ };
2005
+
1826
2006
  // src/resources/pushSubscriptions.ts
1827
2007
  var PushSubscriptionsResource = class {
1828
2008
  constructor(client) {
@@ -1882,16 +2062,16 @@ var PushSubscriptionsResource = class {
1882
2062
  );
1883
2063
  }
1884
2064
  /**
1885
- * List the caller's personal push subscriptions across all targets
1886
- * (playbook + feed). Defaults to currently-active rows only; pass
1887
- * `include_history=true` to also return previously-unsubscribed rows.
2065
+ * List the caller's currently active personal push subscriptions.
2066
+ * Results are cursor-paginated.
1888
2067
  */
1889
2068
  async list(params = {}) {
1890
2069
  this.client._requireAuth();
1891
2070
  const query = {};
1892
- if (params.include_history !== void 0) {
1893
- query.include_history = String(params.include_history);
2071
+ if (params.first !== void 0 && params.first > 0) {
2072
+ query.first = String(params.first);
1894
2073
  }
2074
+ if (params.cursor) query.cursor = params.cursor;
1895
2075
  return this.client._request("GET", "/api/v1/me/push-subscriptions", {
1896
2076
  query
1897
2077
  });
@@ -1968,11 +2148,17 @@ var AlvaClient = class {
1968
2148
  baseUrl;
1969
2149
  arraysBaseUrl;
1970
2150
  viewer_token;
2151
+ pbsvToken;
1971
2152
  apiKey;
2153
+ gaClientId;
2154
+ gaSessionId;
2155
+ utmParams;
1972
2156
  _fs;
1973
2157
  _run;
1974
2158
  _deploy;
1975
2159
  _release;
2160
+ _feed;
2161
+ _playbooks;
1976
2162
  _secrets;
1977
2163
  _sdk;
1978
2164
  _dataSkills;
@@ -1984,13 +2170,18 @@ var AlvaClient = class {
1984
2170
  _trading;
1985
2171
  _arraysJwt;
1986
2172
  _notifications;
2173
+ _notificationPreferences;
1987
2174
  _pushSubscriptions;
1988
2175
  _channelGroupSubscriptions;
1989
2176
  constructor(config) {
1990
2177
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
1991
2178
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
1992
2179
  this.viewer_token = config.viewer_token;
2180
+ this.pbsvToken = config.pbsvToken;
1993
2181
  this.apiKey = config.apiKey;
2182
+ this.gaClientId = config.gaClientId;
2183
+ this.gaSessionId = config.gaSessionId;
2184
+ this.utmParams = config.utmParams;
1994
2185
  }
1995
2186
  get fs() {
1996
2187
  return this._fs ??= new FsResource(this);
@@ -2004,6 +2195,12 @@ var AlvaClient = class {
2004
2195
  get release() {
2005
2196
  return this._release ??= new ReleaseResource(this);
2006
2197
  }
2198
+ get feed() {
2199
+ return this._feed ??= new FeedResource(this);
2200
+ }
2201
+ get playbooks() {
2202
+ return this._playbooks ??= new PlaybooksResource(this);
2203
+ }
2007
2204
  get secrets() {
2008
2205
  return this._secrets ??= new SecretsResource(this);
2009
2206
  }
@@ -2037,6 +2234,9 @@ var AlvaClient = class {
2037
2234
  get notifications() {
2038
2235
  return this._notifications ??= new NotificationsResource(this);
2039
2236
  }
2237
+ get notificationPreferences() {
2238
+ return this._notificationPreferences ??= new NotificationPreferencesResource(this);
2239
+ }
2040
2240
  get pushSubscriptions() {
2041
2241
  return this._pushSubscriptions ??= new PushSubscriptionsResource(this);
2042
2242
  }
@@ -2044,10 +2244,10 @@ var AlvaClient = class {
2044
2244
  return this._channelGroupSubscriptions ??= new ChannelGroupSubscriptionsResource(this);
2045
2245
  }
2046
2246
  _requireAuth() {
2047
- if (!this.viewer_token && !this.apiKey) {
2247
+ if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
2048
2248
  throw new AlvaError(
2049
2249
  "UNAUTHENTICATED",
2050
- "Authentication is required. Pass viewer_token or apiKey in the constructor.",
2250
+ "Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",
2051
2251
  401
2052
2252
  );
2053
2253
  }
@@ -2069,12 +2269,24 @@ var AlvaClient = class {
2069
2269
  }
2070
2270
  const headers = {};
2071
2271
  if (!options?.noAuth) {
2072
- if (this.viewer_token) {
2272
+ if (this.pbsvToken) {
2273
+ headers.Authorization = `Bearer ${this.pbsvToken}`;
2274
+ headers["X-Pbsv"] = "1";
2275
+ } else if (this.viewer_token) {
2073
2276
  headers["x-Playbook-Viewer"] = this.viewer_token;
2074
2277
  } else if (this.apiKey) {
2075
2278
  headers["X-Alva-Api-Key"] = this.apiKey;
2076
2279
  }
2077
2280
  }
2281
+ if (this.gaClientId) {
2282
+ headers["X-Alva-GA-Client-ID"] = this.gaClientId;
2283
+ }
2284
+ if (this.gaSessionId) {
2285
+ headers["X-Alva-GA-Session-ID"] = this.gaSessionId;
2286
+ }
2287
+ if (this.utmParams) {
2288
+ headers["X-Alva-UTM-Params"] = this.utmParams;
2289
+ }
2078
2290
  let fetchBody;
2079
2291
  if (options?.rawBody !== void 0) {
2080
2292
  headers["Content-Type"] = "application/octet-stream";
@@ -2134,12 +2346,381 @@ var AlvaClient = class {
2134
2346
  }
2135
2347
  };
2136
2348
 
2349
+ // src/playbookRuntime.ts
2350
+ var UdfError = class extends Error {
2351
+ code;
2352
+ metadata;
2353
+ status;
2354
+ constructor(message, {
2355
+ code,
2356
+ metadata = {},
2357
+ status
2358
+ }) {
2359
+ super(message);
2360
+ this.name = new.target.name;
2361
+ this.code = code;
2362
+ this.metadata = metadata;
2363
+ this.status = status;
2364
+ }
2365
+ };
2366
+ var UdfAuthRequiredError = class extends UdfError {
2367
+ constructor() {
2368
+ super("Sign in to use this UDF.", { code: "AUTH_REQUIRED" });
2369
+ }
2370
+ };
2371
+ var UdfTokenExpiredError = class extends UdfError {
2372
+ };
2373
+ var UdfTokenInvalidError = class extends UdfError {
2374
+ };
2375
+ var UdfPidMismatchError = class extends UdfError {
2376
+ };
2377
+ var UdfConsentRequiredError = class extends UdfError {
2378
+ };
2379
+ var UdfConsentDeniedError = class extends UdfError {
2380
+ constructor() {
2381
+ super("UDF consent was denied.", { code: "CONSENT_DENIED" });
2382
+ }
2383
+ };
2384
+ var UdfConsentTimeoutError = class extends UdfError {
2385
+ constructor() {
2386
+ super("UDF consent timed out.", { code: "CONSENT_TIMEOUT" });
2387
+ }
2388
+ };
2389
+ var UdfInsufficientCredits = class extends UdfError {
2390
+ };
2391
+ var UdfFunctionNotFoundError = class extends UdfError {
2392
+ };
2393
+ var UdfFunctionDisabledError = class extends UdfError {
2394
+ };
2395
+ var UdfRateLimitedError = class extends UdfError {
2396
+ };
2397
+ var UdfExecutionError = class extends UdfError {
2398
+ };
2399
+ var UdfTransportError = class extends UdfError {
2400
+ };
2401
+ var PBSV_UPDATE_MESSAGE = "alva:pbsv:update";
2402
+ var UDF_CONSENT_REQUEST_MESSAGE = "alva:udf:consent-request";
2403
+ var UDF_CONSENT_RESPONSE_MESSAGE = "alva:udf:consent-response";
2404
+ var DEFAULT_API_ORIGIN = "https://api.alva.ai";
2405
+ var CONSENT_TIMEOUT_MS = 5 * 60 * 1e3;
2406
+ var cachedToken = null;
2407
+ var expectedParentOrigin = null;
2408
+ var apiOrigin = DEFAULT_API_ORIGIN;
2409
+ var playbookIdFromBoot = null;
2410
+ var runtimeWindow = null;
2411
+ var installed = false;
2412
+ var pendingConsents = /* @__PURE__ */ new Map();
2413
+ var decodeBase64Url = (value) => {
2414
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
2415
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
2416
+ return atob(padded);
2417
+ };
2418
+ var playbookIdFromToken = (token) => {
2419
+ if (!token) return null;
2420
+ const [, payload] = token.split(".");
2421
+ if (!payload) return null;
2422
+ try {
2423
+ const parsed = JSON.parse(decodeBase64Url(payload));
2424
+ if (typeof parsed.pid === "number") return String(parsed.pid);
2425
+ if (typeof parsed.pid === "string") return parsed.pid;
2426
+ } catch {
2427
+ return null;
2428
+ }
2429
+ return null;
2430
+ };
2431
+ var getViewerToken = () => cachedToken;
2432
+ var stripPbsvFromUrl = (targetWindow) => {
2433
+ const url = new URL(targetWindow.location.href);
2434
+ url.searchParams.delete("_pbsv");
2435
+ targetWindow.history.replaceState(
2436
+ null,
2437
+ "",
2438
+ url.pathname + url.search + url.hash
2439
+ );
2440
+ };
2441
+ var parseBootParams = (targetWindow) => {
2442
+ const params = new URLSearchParams(targetWindow.location.search);
2443
+ cachedToken = params.get("_pbsv");
2444
+ expectedParentOrigin = params.get("parent_origin");
2445
+ apiOrigin = (params.get("api_origin") || DEFAULT_API_ORIGIN).replace(
2446
+ /\/$/,
2447
+ ""
2448
+ );
2449
+ playbookIdFromBoot = playbookIdFromToken(cachedToken);
2450
+ if (cachedToken) stripPbsvFromUrl(targetWindow);
2451
+ };
2452
+ var safeJson = async (response) => {
2453
+ try {
2454
+ return await response.json();
2455
+ } catch {
2456
+ return {};
2457
+ }
2458
+ };
2459
+ var errorMetadata = (body) => body.error?.metadata || body.details?.metadata || {};
2460
+ var mapUdfErrorResponse = (body, status) => {
2461
+ const code = body.error?.code || "TRANSPORT";
2462
+ const message = body.error?.message || code;
2463
+ const metadata = errorMetadata(body);
2464
+ const props = { code, metadata, status };
2465
+ switch (code) {
2466
+ case "PBSV_EXPIRED":
2467
+ return new UdfTokenExpiredError(message, props);
2468
+ case "PBSV_INVALID":
2469
+ case "UNAUTHENTICATED":
2470
+ return new UdfTokenInvalidError(message, props);
2471
+ case "PBSV_PID_MISMATCH":
2472
+ return new UdfPidMismatchError(message, props);
2473
+ case "CONSENT_REQUIRED":
2474
+ return new UdfConsentRequiredError(message, props);
2475
+ case "INSUFFICIENT_CREDITS":
2476
+ return new UdfInsufficientCredits(message, props);
2477
+ case "FUNCTION_NOT_FOUND":
2478
+ return new UdfFunctionNotFoundError(message, props);
2479
+ case "FUNCTION_DISABLED":
2480
+ return new UdfFunctionDisabledError(message, props);
2481
+ case "RESOURCE_EXHAUSTED":
2482
+ return new UdfRateLimitedError(message, props);
2483
+ case "EXECUTION_FAILED":
2484
+ return new UdfExecutionError(message, props);
2485
+ default:
2486
+ return new UdfTransportError(message, props);
2487
+ }
2488
+ };
2489
+ var onMessage = (event) => {
2490
+ if (!runtimeWindow || !expectedParentOrigin) return;
2491
+ if (event.origin !== expectedParentOrigin) return;
2492
+ if (event.source !== runtimeWindow.parent) return;
2493
+ if (!event.data || typeof event.data !== "object") return;
2494
+ const data = event.data;
2495
+ if (data.type === PBSV_UPDATE_MESSAGE) {
2496
+ if (typeof data.token === "string" && data.token.length > 0) {
2497
+ cachedToken = data.token;
2498
+ playbookIdFromBoot = playbookIdFromToken(data.token);
2499
+ }
2500
+ return;
2501
+ }
2502
+ if (data.type !== UDF_CONSENT_RESPONSE_MESSAGE) return;
2503
+ if (typeof data.request_id !== "string") return;
2504
+ const pending = pendingConsents.get(data.request_id);
2505
+ if (!pending) return;
2506
+ clearTimeout(pending.timer);
2507
+ pendingConsents.delete(data.request_id);
2508
+ pending.resolve(data.granted === true ? "granted" : "denied");
2509
+ };
2510
+ var randomRequestId = () => {
2511
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
2512
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2513
+ };
2514
+ var playbookIdForInvoke = () => {
2515
+ if (!playbookIdFromBoot) return null;
2516
+ const numericId = Number(playbookIdFromBoot);
2517
+ return Number.isSafeInteger(numericId) ? numericId : null;
2518
+ };
2519
+ var requestConsent = async (playbookId, minAllowance) => {
2520
+ if (!runtimeWindow || !expectedParentOrigin) return "denied";
2521
+ const targetOrigin = expectedParentOrigin;
2522
+ const requestId = randomRequestId();
2523
+ return new Promise((resolve) => {
2524
+ const timer = setTimeout(() => {
2525
+ pendingConsents.delete(requestId);
2526
+ resolve("timeout");
2527
+ }, CONSENT_TIMEOUT_MS);
2528
+ pendingConsents.set(requestId, { resolve, timer });
2529
+ runtimeWindow?.parent.postMessage(
2530
+ {
2531
+ type: UDF_CONSENT_REQUEST_MESSAGE,
2532
+ request_id: requestId,
2533
+ playbook_id: playbookId,
2534
+ min_allowance: minAllowance
2535
+ },
2536
+ targetOrigin
2537
+ );
2538
+ });
2539
+ };
2540
+ var call = async (functionName, params, retried = false) => {
2541
+ const token = getViewerToken();
2542
+ if (!token) throw new UdfAuthRequiredError();
2543
+ if (!playbookIdFromBoot) {
2544
+ throw new UdfPidMismatchError("Missing playbook id.", {
2545
+ code: "PBSV_PID_MISMATCH"
2546
+ });
2547
+ }
2548
+ const playbookId = playbookIdForInvoke();
2549
+ if (!playbookId) {
2550
+ throw new UdfPidMismatchError("Invalid playbook id.", {
2551
+ code: "PBSV_PID_MISMATCH"
2552
+ });
2553
+ }
2554
+ let response;
2555
+ try {
2556
+ response = await fetch(`${apiOrigin}/api/v1/service/invoke`, {
2557
+ method: "POST",
2558
+ headers: {
2559
+ Authorization: `Bearer ${token}`,
2560
+ "X-Pbsv": "1",
2561
+ "Content-Type": "application/json"
2562
+ },
2563
+ body: JSON.stringify({
2564
+ playbook_id: playbookId,
2565
+ function_name: functionName,
2566
+ parameters_json: JSON.stringify(params)
2567
+ })
2568
+ });
2569
+ } catch {
2570
+ throw new UdfTransportError("Network error while invoking UDF.", {
2571
+ code: "TRANSPORT"
2572
+ });
2573
+ }
2574
+ const body = await safeJson(response);
2575
+ if (response.ok) {
2576
+ return body.result;
2577
+ }
2578
+ if (body.error?.code === "CONSENT_REQUIRED" && !retried) {
2579
+ const metadata = errorMetadata(body);
2580
+ const playbookId2 = typeof metadata.playbook_id === "string" ? metadata.playbook_id : playbookIdFromBoot;
2581
+ const minAllowance = typeof metadata.min_allowance_suggested === "number" ? metadata.min_allowance_suggested : 1;
2582
+ const consent = await requestConsent(playbookId2, minAllowance);
2583
+ if (consent === "granted") return call(functionName, params, true);
2584
+ if (consent === "timeout") throw new UdfConsentTimeoutError();
2585
+ throw new UdfConsentDeniedError();
2586
+ }
2587
+ throw mapUdfErrorResponse(body, response.status);
2588
+ };
2589
+ var list = async () => {
2590
+ const token = getViewerToken();
2591
+ if (!token) throw new UdfAuthRequiredError();
2592
+ if (!playbookIdFromBoot) {
2593
+ throw new UdfPidMismatchError("Missing playbook id.", {
2594
+ code: "PBSV_PID_MISMATCH"
2595
+ });
2596
+ }
2597
+ const url = new URL(`${apiOrigin}/api/v1/service/functions`);
2598
+ url.searchParams.set("playbook_id", playbookIdFromBoot);
2599
+ const response = await fetch(url.toString(), {
2600
+ headers: {
2601
+ Authorization: `Bearer ${token}`,
2602
+ "X-Pbsv": "1"
2603
+ }
2604
+ });
2605
+ const body = await safeJson(response);
2606
+ if (!response.ok) throw mapUdfErrorResponse(body, response.status);
2607
+ const functions = body.functions;
2608
+ return Array.isArray(functions) ? functions : [];
2609
+ };
2610
+ var dispatchButtonEvent = (button, name, detail) => {
2611
+ button.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
2612
+ };
2613
+ var resolveButtonTarget = (target) => {
2614
+ if (typeof target !== "string") return target;
2615
+ const root = runtimeWindow?.document;
2616
+ const element = root?.querySelector(target);
2617
+ if (element && "appendChild" in element) {
2618
+ return element;
2619
+ }
2620
+ throw new Error(`UDF button target not found: ${target}`);
2621
+ };
2622
+ var renderButton = (target, options) => {
2623
+ if (!runtimeWindow) throw new Error("Playbook runtime is not installed.");
2624
+ const container = resolveButtonTarget(target);
2625
+ const button = runtimeWindow.document.createElement("button");
2626
+ const label = options.label || options.functionName;
2627
+ const loadingLabel = options.loadingLabel || "Running...";
2628
+ const disabledLabel = options.disabledLabel || "Sign in to run";
2629
+ button.type = "button";
2630
+ button.className = "alva-udf-button";
2631
+ button.textContent = getViewerToken() ? label : disabledLabel;
2632
+ button.disabled = !getViewerToken();
2633
+ button.setAttribute("data-function-name", options.functionName);
2634
+ if (button.disabled) button.setAttribute("aria-disabled", "true");
2635
+ button.addEventListener("click", async () => {
2636
+ if (button.disabled) return;
2637
+ button.disabled = true;
2638
+ button.textContent = loadingLabel;
2639
+ dispatchButtonEvent(button, "alva:udf-button:loading", {
2640
+ functionName: options.functionName
2641
+ });
2642
+ try {
2643
+ const result = await call(options.functionName, options.params ?? {});
2644
+ dispatchButtonEvent(button, "alva:udf-button:result", {
2645
+ functionName: options.functionName,
2646
+ result
2647
+ });
2648
+ } catch (error) {
2649
+ dispatchButtonEvent(button, "alva:udf-button:error", {
2650
+ functionName: options.functionName,
2651
+ error
2652
+ });
2653
+ } finally {
2654
+ button.disabled = !getViewerToken();
2655
+ button.textContent = button.disabled ? disabledLabel : label;
2656
+ }
2657
+ });
2658
+ container.appendChild(button);
2659
+ return button;
2660
+ };
2661
+ var udf = {
2662
+ call,
2663
+ list,
2664
+ getViewerToken,
2665
+ renderButton,
2666
+ UdfError,
2667
+ UdfAuthRequiredError,
2668
+ UdfTokenExpiredError,
2669
+ UdfTokenInvalidError,
2670
+ UdfPidMismatchError,
2671
+ UdfConsentRequiredError,
2672
+ UdfConsentDeniedError,
2673
+ UdfConsentTimeoutError,
2674
+ UdfInsufficientCredits,
2675
+ UdfFunctionNotFoundError,
2676
+ UdfFunctionDisabledError,
2677
+ UdfRateLimitedError,
2678
+ UdfExecutionError,
2679
+ UdfTransportError
2680
+ };
2681
+ var installPlaybookRuntime = (targetWindow) => {
2682
+ const nextWindow = targetWindow ?? (typeof window === "undefined" ? void 0 : window);
2683
+ if (!nextWindow || installed) return;
2684
+ runtimeWindow = nextWindow;
2685
+ installed = true;
2686
+ parseBootParams(nextWindow);
2687
+ nextWindow.addEventListener("message", onMessage);
2688
+ const target = nextWindow;
2689
+ const existing = target.alva || {};
2690
+ target.alva = {
2691
+ ...existing,
2692
+ udf
2693
+ };
2694
+ };
2695
+
2137
2696
  // src/index.ts
2138
- var VERSION = true ? "0.7.0" : "dev";
2697
+ var VERSION = true ? "0.9.0" : "dev";
2139
2698
  // Annotate the CommonJS export names for ESM import in node:
2140
2699
  0 && (module.exports = {
2141
2700
  AlvaClient,
2142
2701
  AlvaError,
2143
- VERSION
2702
+ PBSV_UPDATE_MESSAGE,
2703
+ UDF_CONSENT_REQUEST_MESSAGE,
2704
+ UDF_CONSENT_RESPONSE_MESSAGE,
2705
+ UdfAuthRequiredError,
2706
+ UdfConsentDeniedError,
2707
+ UdfConsentRequiredError,
2708
+ UdfConsentTimeoutError,
2709
+ UdfError,
2710
+ UdfExecutionError,
2711
+ UdfFunctionDisabledError,
2712
+ UdfFunctionNotFoundError,
2713
+ UdfInsufficientCredits,
2714
+ UdfPidMismatchError,
2715
+ UdfRateLimitedError,
2716
+ UdfTokenExpiredError,
2717
+ UdfTokenInvalidError,
2718
+ UdfTransportError,
2719
+ VERSION,
2720
+ getViewerToken,
2721
+ installPlaybookRuntime,
2722
+ mapUdfErrorResponse,
2723
+ playbookIdFromToken,
2724
+ udf
2144
2725
  });
2145
2726
  //# sourceMappingURL=index.cjs.map