@alva-ai/toolkit 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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
  }
@@ -348,6 +371,60 @@ var FeedResource = class {
348
371
  }
349
372
  };
350
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
+
351
428
  // src/resources/secrets.ts
352
429
  var SecretsResource = class {
353
430
  constructor(client) {
@@ -417,6 +494,26 @@ var SdkDocsResource = class {
417
494
 
418
495
  // src/resources/skillTiers.ts
419
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
+ },
420
517
  {
421
518
  skill: "arrays-data-api-spot-market-price-and-volume",
422
519
  file: "crypto-detail",
@@ -448,10 +545,10 @@ var SKILL_ENDPOINT_METADATA = [
448
545
  pro_required: false
449
546
  },
450
547
  {
451
- skill: "arrays-data-api-spot-market-price-and-volume",
452
- file: "crypto-futures-ohlcv",
548
+ skill: "arrays-data-api-crypto-futures-data",
549
+ file: "hyperliquid-perp-usdc-kline",
453
550
  method: "GET",
454
- path: "/api/v1/crypto/futures/ohlcv",
551
+ path: "/api/v1/crypto/hyperliquid/perp/usdc/kline",
455
552
  tier: "public",
456
553
  required_subscription_tier: "free",
457
554
  access: "free_and_pro",
@@ -459,9 +556,9 @@ var SKILL_ENDPOINT_METADATA = [
459
556
  },
460
557
  {
461
558
  skill: "arrays-data-api-spot-market-price-and-volume",
462
- file: "crypto-kline",
559
+ file: "hyperliquid-spot-usdc-kline",
463
560
  method: "GET",
464
- path: "/api/v1/crypto/kline",
561
+ path: "/api/v1/crypto/hyperliquid/spot/usdc/kline",
465
562
  tier: "public",
466
563
  required_subscription_tier: "free",
467
564
  access: "free_and_pro",
@@ -507,16 +604,6 @@ var SKILL_ENDPOINT_METADATA = [
507
604
  access: "free_and_pro",
508
605
  pro_required: false
509
606
  },
510
- {
511
- skill: "arrays-data-api-spot-market-price-and-volume",
512
- file: "crypto-ohlcv",
513
- method: "GET",
514
- path: "/api/v1/crypto/ohlcv",
515
- tier: "public",
516
- required_subscription_tier: "free",
517
- access: "free_and_pro",
518
- pro_required: false
519
- },
520
607
  {
521
608
  skill: "arrays-data-api-crypto-futures-data",
522
609
  file: "open-interest",
@@ -1207,16 +1294,6 @@ var SKILL_ENDPOINT_METADATA = [
1207
1294
  access: "pro_only",
1208
1295
  pro_required: true
1209
1296
  },
1210
- {
1211
- skill: "arrays-data-api-equity-ownership-and-flow",
1212
- file: "senate-trade",
1213
- method: "GET",
1214
- path: "/api/v1/stocks/company/senate-trade",
1215
- tier: "alternative",
1216
- required_subscription_tier: "pro",
1217
- access: "pro_only",
1218
- pro_required: true
1219
- },
1220
1297
  {
1221
1298
  skill: "arrays-data-api-stock-metrics",
1222
1299
  file: "darkpool",
@@ -1456,6 +1533,50 @@ var SKILL_ENDPOINT_METADATA = [
1456
1533
  required_subscription_tier: "pro",
1457
1534
  access: "pro_only",
1458
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
1459
1580
  }
1460
1581
  ];
1461
1582
  function getSkillEndpointMetadata(skill, file) {
@@ -1780,6 +1901,34 @@ var TradingResource = class {
1780
1901
  }
1781
1902
  };
1782
1903
 
1904
+ // src/resources/portfolio.ts
1905
+ var PortfolioResource = class {
1906
+ constructor(client) {
1907
+ this.client = client;
1908
+ }
1909
+ client;
1910
+ async accounts() {
1911
+ this.client._requireAuth();
1912
+ return this.client._request("GET", "/api/v1/portfolio/accounts");
1913
+ }
1914
+ async summary(accountId) {
1915
+ this.client._requireAuth();
1916
+ return this.client._request("GET", "/api/v1/portfolio/summary", {
1917
+ query: { accountId }
1918
+ });
1919
+ }
1920
+ async activities(params) {
1921
+ this.client._requireAuth();
1922
+ return this.client._request("GET", "/api/v1/portfolio/activities", {
1923
+ query: {
1924
+ accountId: params.accountId,
1925
+ limit: params.limit,
1926
+ pageToken: params.pageToken
1927
+ }
1928
+ });
1929
+ }
1930
+ };
1931
+
1783
1932
  // src/resources/arraysJwt.ts
1784
1933
  var ArraysJwtResource = class {
1785
1934
  constructor(client) {
@@ -1850,6 +1999,38 @@ function buildQuery(params) {
1850
1999
  return q;
1851
2000
  }
1852
2001
 
2002
+ // src/resources/notificationPreferences.ts
2003
+ var NotificationPreferencesResource = class {
2004
+ constructor(client) {
2005
+ this.client = client;
2006
+ }
2007
+ client;
2008
+ /**
2009
+ * List the caller's notification preference settings. Server defaults
2010
+ * are included even when the caller has not explicitly stored a setting.
2011
+ */
2012
+ async list() {
2013
+ this.client._requireAuth();
2014
+ return this.client._request(
2015
+ "GET",
2016
+ "/api/v1/me/notifications/preferences"
2017
+ );
2018
+ }
2019
+ /**
2020
+ * Enable or disable one notification preference.
2021
+ */
2022
+ async update(params) {
2023
+ this.client._requireAuth();
2024
+ return this.client._request(
2025
+ "PATCH",
2026
+ `/api/v1/me/notifications/preferences/${encodeURIComponent(params.key)}`,
2027
+ {
2028
+ body: { enabled: params.enabled }
2029
+ }
2030
+ );
2031
+ }
2032
+ };
2033
+
1853
2034
  // src/resources/pushSubscriptions.ts
1854
2035
  var PushSubscriptionsResource = class {
1855
2036
  constructor(client) {
@@ -1995,12 +2176,17 @@ var AlvaClient = class {
1995
2176
  baseUrl;
1996
2177
  arraysBaseUrl;
1997
2178
  viewer_token;
2179
+ pbsvToken;
1998
2180
  apiKey;
2181
+ gaClientId;
2182
+ gaSessionId;
2183
+ utmParams;
1999
2184
  _fs;
2000
2185
  _run;
2001
2186
  _deploy;
2002
2187
  _release;
2003
2188
  _feed;
2189
+ _playbooks;
2004
2190
  _secrets;
2005
2191
  _sdk;
2006
2192
  _dataSkills;
@@ -2010,15 +2196,21 @@ var AlvaClient = class {
2010
2196
  _screenshot;
2011
2197
  _user;
2012
2198
  _trading;
2199
+ _portfolio;
2013
2200
  _arraysJwt;
2014
2201
  _notifications;
2202
+ _notificationPreferences;
2015
2203
  _pushSubscriptions;
2016
2204
  _channelGroupSubscriptions;
2017
2205
  constructor(config) {
2018
2206
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
2019
2207
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
2020
2208
  this.viewer_token = config.viewer_token;
2209
+ this.pbsvToken = config.pbsvToken;
2021
2210
  this.apiKey = config.apiKey;
2211
+ this.gaClientId = config.gaClientId;
2212
+ this.gaSessionId = config.gaSessionId;
2213
+ this.utmParams = config.utmParams;
2022
2214
  }
2023
2215
  get fs() {
2024
2216
  return this._fs ??= new FsResource(this);
@@ -2035,6 +2227,9 @@ var AlvaClient = class {
2035
2227
  get feed() {
2036
2228
  return this._feed ??= new FeedResource(this);
2037
2229
  }
2230
+ get playbooks() {
2231
+ return this._playbooks ??= new PlaybooksResource(this);
2232
+ }
2038
2233
  get secrets() {
2039
2234
  return this._secrets ??= new SecretsResource(this);
2040
2235
  }
@@ -2062,12 +2257,18 @@ var AlvaClient = class {
2062
2257
  get trading() {
2063
2258
  return this._trading ??= new TradingResource(this);
2064
2259
  }
2260
+ get portfolio() {
2261
+ return this._portfolio ??= new PortfolioResource(this);
2262
+ }
2065
2263
  get arraysJwt() {
2066
2264
  return this._arraysJwt ??= new ArraysJwtResource(this);
2067
2265
  }
2068
2266
  get notifications() {
2069
2267
  return this._notifications ??= new NotificationsResource(this);
2070
2268
  }
2269
+ get notificationPreferences() {
2270
+ return this._notificationPreferences ??= new NotificationPreferencesResource(this);
2271
+ }
2071
2272
  get pushSubscriptions() {
2072
2273
  return this._pushSubscriptions ??= new PushSubscriptionsResource(this);
2073
2274
  }
@@ -2075,10 +2276,10 @@ var AlvaClient = class {
2075
2276
  return this._channelGroupSubscriptions ??= new ChannelGroupSubscriptionsResource(this);
2076
2277
  }
2077
2278
  _requireAuth() {
2078
- if (!this.viewer_token && !this.apiKey) {
2279
+ if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
2079
2280
  throw new AlvaError(
2080
2281
  "UNAUTHENTICATED",
2081
- "Authentication is required. Pass viewer_token or apiKey in the constructor.",
2282
+ "Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",
2082
2283
  401
2083
2284
  );
2084
2285
  }
@@ -2100,12 +2301,24 @@ var AlvaClient = class {
2100
2301
  }
2101
2302
  const headers = {};
2102
2303
  if (!options?.noAuth) {
2103
- if (this.viewer_token) {
2304
+ if (this.pbsvToken) {
2305
+ headers.Authorization = `Bearer ${this.pbsvToken}`;
2306
+ headers["X-Pbsv"] = "1";
2307
+ } else if (this.viewer_token) {
2104
2308
  headers["x-Playbook-Viewer"] = this.viewer_token;
2105
2309
  } else if (this.apiKey) {
2106
2310
  headers["X-Alva-Api-Key"] = this.apiKey;
2107
2311
  }
2108
2312
  }
2313
+ if (this.gaClientId) {
2314
+ headers["X-Alva-GA-Client-ID"] = this.gaClientId;
2315
+ }
2316
+ if (this.gaSessionId) {
2317
+ headers["X-Alva-GA-Session-ID"] = this.gaSessionId;
2318
+ }
2319
+ if (this.utmParams) {
2320
+ headers["X-Alva-UTM-Params"] = this.utmParams;
2321
+ }
2109
2322
  let fetchBody;
2110
2323
  if (options?.rawBody !== void 0) {
2111
2324
  headers["Content-Type"] = "application/octet-stream";
@@ -2165,12 +2378,381 @@ var AlvaClient = class {
2165
2378
  }
2166
2379
  };
2167
2380
 
2381
+ // src/playbookRuntime.ts
2382
+ var UdfError = class extends Error {
2383
+ code;
2384
+ metadata;
2385
+ status;
2386
+ constructor(message, {
2387
+ code,
2388
+ metadata = {},
2389
+ status
2390
+ }) {
2391
+ super(message);
2392
+ this.name = new.target.name;
2393
+ this.code = code;
2394
+ this.metadata = metadata;
2395
+ this.status = status;
2396
+ }
2397
+ };
2398
+ var UdfAuthRequiredError = class extends UdfError {
2399
+ constructor() {
2400
+ super("Sign in to use this UDF.", { code: "AUTH_REQUIRED" });
2401
+ }
2402
+ };
2403
+ var UdfTokenExpiredError = class extends UdfError {
2404
+ };
2405
+ var UdfTokenInvalidError = class extends UdfError {
2406
+ };
2407
+ var UdfPidMismatchError = class extends UdfError {
2408
+ };
2409
+ var UdfConsentRequiredError = class extends UdfError {
2410
+ };
2411
+ var UdfConsentDeniedError = class extends UdfError {
2412
+ constructor() {
2413
+ super("UDF consent was denied.", { code: "CONSENT_DENIED" });
2414
+ }
2415
+ };
2416
+ var UdfConsentTimeoutError = class extends UdfError {
2417
+ constructor() {
2418
+ super("UDF consent timed out.", { code: "CONSENT_TIMEOUT" });
2419
+ }
2420
+ };
2421
+ var UdfInsufficientCredits = class extends UdfError {
2422
+ };
2423
+ var UdfFunctionNotFoundError = class extends UdfError {
2424
+ };
2425
+ var UdfFunctionDisabledError = class extends UdfError {
2426
+ };
2427
+ var UdfRateLimitedError = class extends UdfError {
2428
+ };
2429
+ var UdfExecutionError = class extends UdfError {
2430
+ };
2431
+ var UdfTransportError = class extends UdfError {
2432
+ };
2433
+ var PBSV_UPDATE_MESSAGE = "alva:pbsv:update";
2434
+ var UDF_CONSENT_REQUEST_MESSAGE = "alva:udf:consent-request";
2435
+ var UDF_CONSENT_RESPONSE_MESSAGE = "alva:udf:consent-response";
2436
+ var DEFAULT_API_ORIGIN = "https://api.alva.ai";
2437
+ var CONSENT_TIMEOUT_MS = 5 * 60 * 1e3;
2438
+ var cachedToken = null;
2439
+ var expectedParentOrigin = null;
2440
+ var apiOrigin = DEFAULT_API_ORIGIN;
2441
+ var playbookIdFromBoot = null;
2442
+ var runtimeWindow = null;
2443
+ var installed = false;
2444
+ var pendingConsents = /* @__PURE__ */ new Map();
2445
+ var decodeBase64Url = (value) => {
2446
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
2447
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
2448
+ return atob(padded);
2449
+ };
2450
+ var playbookIdFromToken = (token) => {
2451
+ if (!token) return null;
2452
+ const [, payload] = token.split(".");
2453
+ if (!payload) return null;
2454
+ try {
2455
+ const parsed = JSON.parse(decodeBase64Url(payload));
2456
+ if (typeof parsed.pid === "number") return String(parsed.pid);
2457
+ if (typeof parsed.pid === "string") return parsed.pid;
2458
+ } catch {
2459
+ return null;
2460
+ }
2461
+ return null;
2462
+ };
2463
+ var getViewerToken = () => cachedToken;
2464
+ var stripPbsvFromUrl = (targetWindow) => {
2465
+ const url = new URL(targetWindow.location.href);
2466
+ url.searchParams.delete("_pbsv");
2467
+ targetWindow.history.replaceState(
2468
+ null,
2469
+ "",
2470
+ url.pathname + url.search + url.hash
2471
+ );
2472
+ };
2473
+ var parseBootParams = (targetWindow) => {
2474
+ const params = new URLSearchParams(targetWindow.location.search);
2475
+ cachedToken = params.get("_pbsv");
2476
+ expectedParentOrigin = params.get("parent_origin");
2477
+ apiOrigin = (params.get("api_origin") || DEFAULT_API_ORIGIN).replace(
2478
+ /\/$/,
2479
+ ""
2480
+ );
2481
+ playbookIdFromBoot = playbookIdFromToken(cachedToken);
2482
+ if (cachedToken) stripPbsvFromUrl(targetWindow);
2483
+ };
2484
+ var safeJson = async (response) => {
2485
+ try {
2486
+ return await response.json();
2487
+ } catch {
2488
+ return {};
2489
+ }
2490
+ };
2491
+ var errorMetadata = (body) => body.error?.metadata || body.details?.metadata || {};
2492
+ var mapUdfErrorResponse = (body, status) => {
2493
+ const code = body.error?.code || "TRANSPORT";
2494
+ const message = body.error?.message || code;
2495
+ const metadata = errorMetadata(body);
2496
+ const props = { code, metadata, status };
2497
+ switch (code) {
2498
+ case "PBSV_EXPIRED":
2499
+ return new UdfTokenExpiredError(message, props);
2500
+ case "PBSV_INVALID":
2501
+ case "UNAUTHENTICATED":
2502
+ return new UdfTokenInvalidError(message, props);
2503
+ case "PBSV_PID_MISMATCH":
2504
+ return new UdfPidMismatchError(message, props);
2505
+ case "CONSENT_REQUIRED":
2506
+ return new UdfConsentRequiredError(message, props);
2507
+ case "INSUFFICIENT_CREDITS":
2508
+ return new UdfInsufficientCredits(message, props);
2509
+ case "FUNCTION_NOT_FOUND":
2510
+ return new UdfFunctionNotFoundError(message, props);
2511
+ case "FUNCTION_DISABLED":
2512
+ return new UdfFunctionDisabledError(message, props);
2513
+ case "RESOURCE_EXHAUSTED":
2514
+ return new UdfRateLimitedError(message, props);
2515
+ case "EXECUTION_FAILED":
2516
+ return new UdfExecutionError(message, props);
2517
+ default:
2518
+ return new UdfTransportError(message, props);
2519
+ }
2520
+ };
2521
+ var onMessage = (event) => {
2522
+ if (!runtimeWindow || !expectedParentOrigin) return;
2523
+ if (event.origin !== expectedParentOrigin) return;
2524
+ if (event.source !== runtimeWindow.parent) return;
2525
+ if (!event.data || typeof event.data !== "object") return;
2526
+ const data = event.data;
2527
+ if (data.type === PBSV_UPDATE_MESSAGE) {
2528
+ if (typeof data.token === "string" && data.token.length > 0) {
2529
+ cachedToken = data.token;
2530
+ playbookIdFromBoot = playbookIdFromToken(data.token);
2531
+ }
2532
+ return;
2533
+ }
2534
+ if (data.type !== UDF_CONSENT_RESPONSE_MESSAGE) return;
2535
+ if (typeof data.request_id !== "string") return;
2536
+ const pending = pendingConsents.get(data.request_id);
2537
+ if (!pending) return;
2538
+ clearTimeout(pending.timer);
2539
+ pendingConsents.delete(data.request_id);
2540
+ pending.resolve(data.granted === true ? "granted" : "denied");
2541
+ };
2542
+ var randomRequestId = () => {
2543
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
2544
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2545
+ };
2546
+ var playbookIdForInvoke = () => {
2547
+ if (!playbookIdFromBoot) return null;
2548
+ const numericId = Number(playbookIdFromBoot);
2549
+ return Number.isSafeInteger(numericId) ? numericId : null;
2550
+ };
2551
+ var requestConsent = async (playbookId, minAllowance) => {
2552
+ if (!runtimeWindow || !expectedParentOrigin) return "denied";
2553
+ const targetOrigin = expectedParentOrigin;
2554
+ const requestId = randomRequestId();
2555
+ return new Promise((resolve) => {
2556
+ const timer = setTimeout(() => {
2557
+ pendingConsents.delete(requestId);
2558
+ resolve("timeout");
2559
+ }, CONSENT_TIMEOUT_MS);
2560
+ pendingConsents.set(requestId, { resolve, timer });
2561
+ runtimeWindow?.parent.postMessage(
2562
+ {
2563
+ type: UDF_CONSENT_REQUEST_MESSAGE,
2564
+ request_id: requestId,
2565
+ playbook_id: playbookId,
2566
+ min_allowance: minAllowance
2567
+ },
2568
+ targetOrigin
2569
+ );
2570
+ });
2571
+ };
2572
+ var call = async (functionName, params, retried = false) => {
2573
+ const token = getViewerToken();
2574
+ if (!token) throw new UdfAuthRequiredError();
2575
+ if (!playbookIdFromBoot) {
2576
+ throw new UdfPidMismatchError("Missing playbook id.", {
2577
+ code: "PBSV_PID_MISMATCH"
2578
+ });
2579
+ }
2580
+ const playbookId = playbookIdForInvoke();
2581
+ if (!playbookId) {
2582
+ throw new UdfPidMismatchError("Invalid playbook id.", {
2583
+ code: "PBSV_PID_MISMATCH"
2584
+ });
2585
+ }
2586
+ let response;
2587
+ try {
2588
+ response = await fetch(`${apiOrigin}/api/v1/service/invoke`, {
2589
+ method: "POST",
2590
+ headers: {
2591
+ Authorization: `Bearer ${token}`,
2592
+ "X-Pbsv": "1",
2593
+ "Content-Type": "application/json"
2594
+ },
2595
+ body: JSON.stringify({
2596
+ playbook_id: playbookId,
2597
+ function_name: functionName,
2598
+ parameters_json: JSON.stringify(params)
2599
+ })
2600
+ });
2601
+ } catch {
2602
+ throw new UdfTransportError("Network error while invoking UDF.", {
2603
+ code: "TRANSPORT"
2604
+ });
2605
+ }
2606
+ const body = await safeJson(response);
2607
+ if (response.ok) {
2608
+ return body.result;
2609
+ }
2610
+ if (body.error?.code === "CONSENT_REQUIRED" && !retried) {
2611
+ const metadata = errorMetadata(body);
2612
+ const playbookId2 = typeof metadata.playbook_id === "string" ? metadata.playbook_id : playbookIdFromBoot;
2613
+ const minAllowance = typeof metadata.min_allowance_suggested === "number" ? metadata.min_allowance_suggested : 1;
2614
+ const consent = await requestConsent(playbookId2, minAllowance);
2615
+ if (consent === "granted") return call(functionName, params, true);
2616
+ if (consent === "timeout") throw new UdfConsentTimeoutError();
2617
+ throw new UdfConsentDeniedError();
2618
+ }
2619
+ throw mapUdfErrorResponse(body, response.status);
2620
+ };
2621
+ var list = async () => {
2622
+ const token = getViewerToken();
2623
+ if (!token) throw new UdfAuthRequiredError();
2624
+ if (!playbookIdFromBoot) {
2625
+ throw new UdfPidMismatchError("Missing playbook id.", {
2626
+ code: "PBSV_PID_MISMATCH"
2627
+ });
2628
+ }
2629
+ const url = new URL(`${apiOrigin}/api/v1/service/functions`);
2630
+ url.searchParams.set("playbook_id", playbookIdFromBoot);
2631
+ const response = await fetch(url.toString(), {
2632
+ headers: {
2633
+ Authorization: `Bearer ${token}`,
2634
+ "X-Pbsv": "1"
2635
+ }
2636
+ });
2637
+ const body = await safeJson(response);
2638
+ if (!response.ok) throw mapUdfErrorResponse(body, response.status);
2639
+ const functions = body.functions;
2640
+ return Array.isArray(functions) ? functions : [];
2641
+ };
2642
+ var dispatchButtonEvent = (button, name, detail) => {
2643
+ button.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
2644
+ };
2645
+ var resolveButtonTarget = (target) => {
2646
+ if (typeof target !== "string") return target;
2647
+ const root = runtimeWindow?.document;
2648
+ const element = root?.querySelector(target);
2649
+ if (element && "appendChild" in element) {
2650
+ return element;
2651
+ }
2652
+ throw new Error(`UDF button target not found: ${target}`);
2653
+ };
2654
+ var renderButton = (target, options) => {
2655
+ if (!runtimeWindow) throw new Error("Playbook runtime is not installed.");
2656
+ const container = resolveButtonTarget(target);
2657
+ const button = runtimeWindow.document.createElement("button");
2658
+ const label = options.label || options.functionName;
2659
+ const loadingLabel = options.loadingLabel || "Running...";
2660
+ const disabledLabel = options.disabledLabel || "Sign in to run";
2661
+ button.type = "button";
2662
+ button.className = "alva-udf-button";
2663
+ button.textContent = getViewerToken() ? label : disabledLabel;
2664
+ button.disabled = !getViewerToken();
2665
+ button.setAttribute("data-function-name", options.functionName);
2666
+ if (button.disabled) button.setAttribute("aria-disabled", "true");
2667
+ button.addEventListener("click", async () => {
2668
+ if (button.disabled) return;
2669
+ button.disabled = true;
2670
+ button.textContent = loadingLabel;
2671
+ dispatchButtonEvent(button, "alva:udf-button:loading", {
2672
+ functionName: options.functionName
2673
+ });
2674
+ try {
2675
+ const result = await call(options.functionName, options.params ?? {});
2676
+ dispatchButtonEvent(button, "alva:udf-button:result", {
2677
+ functionName: options.functionName,
2678
+ result
2679
+ });
2680
+ } catch (error) {
2681
+ dispatchButtonEvent(button, "alva:udf-button:error", {
2682
+ functionName: options.functionName,
2683
+ error
2684
+ });
2685
+ } finally {
2686
+ button.disabled = !getViewerToken();
2687
+ button.textContent = button.disabled ? disabledLabel : label;
2688
+ }
2689
+ });
2690
+ container.appendChild(button);
2691
+ return button;
2692
+ };
2693
+ var udf = {
2694
+ call,
2695
+ list,
2696
+ getViewerToken,
2697
+ renderButton,
2698
+ UdfError,
2699
+ UdfAuthRequiredError,
2700
+ UdfTokenExpiredError,
2701
+ UdfTokenInvalidError,
2702
+ UdfPidMismatchError,
2703
+ UdfConsentRequiredError,
2704
+ UdfConsentDeniedError,
2705
+ UdfConsentTimeoutError,
2706
+ UdfInsufficientCredits,
2707
+ UdfFunctionNotFoundError,
2708
+ UdfFunctionDisabledError,
2709
+ UdfRateLimitedError,
2710
+ UdfExecutionError,
2711
+ UdfTransportError
2712
+ };
2713
+ var installPlaybookRuntime = (targetWindow) => {
2714
+ const nextWindow = targetWindow ?? (typeof window === "undefined" ? void 0 : window);
2715
+ if (!nextWindow || installed) return;
2716
+ runtimeWindow = nextWindow;
2717
+ installed = true;
2718
+ parseBootParams(nextWindow);
2719
+ nextWindow.addEventListener("message", onMessage);
2720
+ const target = nextWindow;
2721
+ const existing = target.alva || {};
2722
+ target.alva = {
2723
+ ...existing,
2724
+ udf
2725
+ };
2726
+ };
2727
+
2168
2728
  // src/index.ts
2169
- var VERSION = true ? "0.8.0" : "dev";
2729
+ var VERSION = true ? "0.9.1" : "dev";
2170
2730
  // Annotate the CommonJS export names for ESM import in node:
2171
2731
  0 && (module.exports = {
2172
2732
  AlvaClient,
2173
2733
  AlvaError,
2174
- VERSION
2734
+ PBSV_UPDATE_MESSAGE,
2735
+ UDF_CONSENT_REQUEST_MESSAGE,
2736
+ UDF_CONSENT_RESPONSE_MESSAGE,
2737
+ UdfAuthRequiredError,
2738
+ UdfConsentDeniedError,
2739
+ UdfConsentRequiredError,
2740
+ UdfConsentTimeoutError,
2741
+ UdfError,
2742
+ UdfExecutionError,
2743
+ UdfFunctionDisabledError,
2744
+ UdfFunctionNotFoundError,
2745
+ UdfInsufficientCredits,
2746
+ UdfPidMismatchError,
2747
+ UdfRateLimitedError,
2748
+ UdfTokenExpiredError,
2749
+ UdfTokenInvalidError,
2750
+ UdfTransportError,
2751
+ VERSION,
2752
+ getViewerToken,
2753
+ installPlaybookRuntime,
2754
+ mapUdfErrorResponse,
2755
+ playbookIdFromToken,
2756
+ udf
2175
2757
  });
2176
2758
  //# sourceMappingURL=index.cjs.map