tokenusage-cli 0.3.0 → 0.4.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +52 -11
  3. package/bin/tokenusage.js +14 -2
  4. package/package.json +1 -2
  5. package/src/cli.js +325 -78
  6. package/src/commands/device-login.js +3 -3
  7. package/src/commands/init.js +343 -153
  8. package/src/commands/pause.js +11 -23
  9. package/src/commands/reconcile.js +496 -0
  10. package/src/commands/sessions.js +57 -14
  11. package/src/commands/sync.js +69 -15
  12. package/src/commands/uninstall.js +6 -9
  13. package/src/commands/upload.js +147 -0
  14. package/src/lib/cli-errors.js +33 -0
  15. package/src/lib/cli-ui.js +93 -0
  16. package/src/lib/queue-row-normalize.js +55 -0
  17. package/src/lib/scheduled-task.js +597 -75
  18. package/src/lib/antigravity-paths.js +0 -48
  19. package/src/lib/async-queue-reader.js +0 -138
  20. package/src/lib/atomic-json.js +0 -27
  21. package/src/lib/bearer-token.js +0 -11
  22. package/src/lib/cloud-account.js +0 -541
  23. package/src/lib/codex-context-breakdown.js +0 -806
  24. package/src/lib/context-health.js +0 -124
  25. package/src/lib/grok-context-breakdown.js +0 -890
  26. package/src/lib/heatmap-compact.js +0 -114
  27. package/src/lib/local-api.js +0 -3574
  28. package/src/lib/outcomes-engine.js +0 -253
  29. package/src/lib/pet-packages.js +0 -722
  30. package/src/lib/skill-usage.js +0 -267
  31. package/src/lib/skills-manager.js +0 -1591
  32. package/src/lib/source-metadata.js +0 -48
  33. package/src/lib/subscription-manager.js +0 -293
  34. package/src/lib/wrapped-aggregator.js +0 -236
  35. package/test/audit-fixes.test.js +0 -249
  36. package/test/branding.test.js +0 -24
  37. package/test/cli-options.test.js +0 -43
  38. package/test/cli-smoke.test.js +0 -53
  39. package/test/cli-ui.test.js +0 -47
  40. package/test/collection-controls.test.js +0 -255
  41. package/test/ingest-sanitize.test.js +0 -162
  42. package/test/packaging.test.js +0 -107
  43. package/test/quiet-warnings.test.js +0 -53
  44. package/test/runtime-copy.test.js +0 -111
  45. package/test/session-upload.test.js +0 -427
  46. package/test/trae-db.test.js +0 -67
  47. package/test/zstd-native.test.js +0 -36
@@ -1,541 +0,0 @@
1
- "use strict";
2
-
3
- // Account-aggregated (cross-device) cloud reads for the local server.
4
- //
5
- // The native menu-bar / tray popover talks only to the local CLI server and
6
- // knows nothing about OAuth/JWT. To make the popover show the SAME cross-device
7
- // totals the dashboard shows in "account view", the local server mints a
8
- // short-lived access token from the InsForge refresh token it already relays
9
- // (see local-api.js cookie relay) and proxies the `token-usage-account-*` edge
10
- // functions. Those functions mirror the local `token-usage-usage-*` response
11
- // schema exactly, so the popover renders the cloud payload unchanged.
12
-
13
- const { DEFAULT_BASE_URL, DEFAULT_ANON_KEY } = require("./runtime-config");
14
- const { expandHeatmapCompact } = require("./heatmap-compact");
15
- const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
16
-
17
- // usage-* (local CLI) → account-* (cloud) slug map. Only these have a
18
- // cross-device cloud equivalent; project-usage / usage-limits / category
19
- // breakdown remain local-only and are intentionally absent here.
20
- const USAGE_TO_ACCOUNT_SLUG = {
21
- "token-usage-usage-summary": "token-usage-account-summary",
22
- "token-usage-usage-daily": "token-usage-account-daily",
23
- "token-usage-usage-hourly": "token-usage-account-hourly",
24
- "token-usage-usage-monthly": "token-usage-account-monthly",
25
- "token-usage-usage-heatmap": "token-usage-account-heatmap",
26
- "token-usage-usage-model-breakdown": "token-usage-account-model-breakdown",
27
- };
28
-
29
- function accountSlugFor(usageSlug) {
30
- return USAGE_TO_ACCOUNT_SLUG[usageSlug] || null;
31
- }
32
-
33
- // The heatmap renders a 52-week grid out of a handful of active days, so the
34
- // dense form is mostly zero-filled cells and repeated keys: ~42 KB on the wire
35
- // for ~12 KB of data, and this proxy accounts for 94% of those reads. Asking
36
- // for the sparse rows and rebuilding the grid in `expandHeatmapCompact` gives
37
- // the caller a byte-identical payload. An edge that predates the compact branch
38
- // ignores the param and answers densely, which that helper passes through.
39
- const HEATMAP_ACCOUNT_SLUG = "token-usage-account-heatmap";
40
-
41
- // Mirror of dashboard/src/contexts/InsforgeAuthContext.jsx
42
- // `accessTokenFromRefreshPayload`: the refresh response may put the token at the
43
- // top level or nested under `session`, in camelCase or snake_case.
44
- function accessTokenFromRefreshPayload(data) {
45
- if (!data || typeof data !== "object") return null;
46
- const session = data.session && typeof data.session === "object" ? data.session : null;
47
- const raw =
48
- (typeof data.accessToken === "string" && data.accessToken) ||
49
- (typeof data.access_token === "string" && data.access_token) ||
50
- (session && typeof session.accessToken === "string" && session.accessToken) ||
51
- (session && typeof session.access_token === "string" && session.access_token) ||
52
- null;
53
- return raw && raw.length > 0 ? raw : null;
54
- }
55
-
56
- function refreshTokenFromRefreshPayload(data) {
57
- if (!data || typeof data !== "object") return null;
58
- const session = data.session && typeof data.session === "object" ? data.session : null;
59
- const raw =
60
- (typeof data.refreshToken === "string" && data.refreshToken) ||
61
- (typeof data.refresh_token === "string" && data.refresh_token) ||
62
- (session && typeof session.refreshToken === "string" && session.refreshToken) ||
63
- (session && typeof session.refresh_token === "string" && session.refresh_token) ||
64
- null;
65
- return raw && raw.length > 0 ? raw : null;
66
- }
67
-
68
- function decodeJwtExpMs(token) {
69
- try {
70
- const part = String(token || "").split(".")[1];
71
- if (!part) return 0;
72
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
73
- const payload = JSON.parse(json);
74
- if (payload && Number.isFinite(payload.exp)) return payload.exp * 1000;
75
- } catch {
76
- /* ignore */
77
- }
78
- return 0;
79
- }
80
-
81
- // The account id the access token was minted for. Used to key the payload cache
82
- // below on something the backend does NOT rotate: the refresh token changes
83
- // under us on rotation, which would throw away a still-warm cache entry on
84
- // exactly the reads that repeat most.
85
- function decodeJwtSub(token) {
86
- try {
87
- const part = String(token || "").split(".")[1];
88
- if (!part) return "";
89
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
90
- const payload = JSON.parse(json);
91
- if (payload && typeof payload.sub === "string") return payload.sub;
92
- } catch {
93
- /* ignore */
94
- }
95
- return "";
96
- }
97
-
98
- // Module-level access-token cache, keyed by the cloud base URL and refresh token
99
- // that produced it.
100
- // The popover polls frequently, so caching avoids hammering /api/auth/refresh.
101
- let tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
102
-
103
- // In-flight refresh de-duplication ("single flight"), keyed the same way as
104
- // `tokenCache`. A full popover refresh fires six account reads concurrently; on
105
- // a cold cache every one of them used to POST /api/auth/refresh with the SAME
106
- // refresh token. When the backend rotates refresh tokens, the losers of that
107
- // race present an already-consumed token and fail — which is exactly the
108
- // intermittent "Activity silently dropped to this-machine data" symptom.
109
- const mintInflight = new Map();
110
-
111
- // Ordinary cross-device reads may lag by two minutes for summaries and five
112
- // minutes for charts. Uploads and explicit refreshes invalidate this window.
113
- // Serialized copies prevent consumers from changing another consumer's data.
114
- const SUMMARY_PAYLOAD_TTL_MS = 120_000;
115
- const PAYLOAD_TTL_MS = 300_000;
116
- const PAYLOAD_CACHE_MAX = 64;
117
- const payloadCache = new Map();
118
- const payloadInflight = new Map();
119
- const payloadVersions = new Map();
120
- let payloadGeneration = 0;
121
- let sessionGeneration = 0;
122
-
123
- // Mirrors the params `fetchAccountFunction` actually puts on the wire, so two
124
- // requests share an entry only when they would have produced the same URL.
125
- function payloadCacheKey({ root, sub, slug, searchParams }) {
126
- const params = accountFunctionParams(slug, searchParams);
127
- params.sort();
128
- return `${root}\0${sub}\0${slug}\0${params}`;
129
- }
130
-
131
- function accountFunctionParams(slug, searchParams) {
132
- const params = new URLSearchParams();
133
- if (searchParams && typeof searchParams.entries === "function") {
134
- for (const [key, value] of searchParams.entries()) {
135
- if (key === "account" || key === "scope" || key === "refresh") continue;
136
- if (value == null || value === "") continue;
137
- params.set(key, String(value));
138
- }
139
- }
140
- if (slug === HEATMAP_ACCOUNT_SLUG) params.set("format", "compact");
141
- return params;
142
- }
143
-
144
- function payloadCacheGet(key, now) {
145
- const hit = payloadCache.get(key);
146
- if (!hit) return null;
147
- if (hit.expMs <= now()) {
148
- payloadCache.delete(key);
149
- return null;
150
- }
151
- // Re-insert so the eviction below drops the coldest entry, not this one.
152
- payloadCache.delete(key);
153
- payloadCache.set(key, hit);
154
- try {
155
- return JSON.parse(hit.body);
156
- } catch {
157
- payloadCache.delete(key);
158
- return null;
159
- }
160
- }
161
-
162
- function payloadCacheSet(key, data, now, ttlMs) {
163
- let body;
164
- try {
165
- body = JSON.stringify(data);
166
- } catch {
167
- return; // Not serializable: skip the cache rather than fail the read.
168
- }
169
- if (body === undefined) return;
170
- payloadCache.set(key, { expMs: now() + ttlMs, body });
171
- while (payloadCache.size > PAYLOAD_CACHE_MAX) {
172
- const oldest = payloadCache.keys().next();
173
- if (oldest.done) break;
174
- payloadCache.delete(oldest.value);
175
- }
176
- }
177
-
178
- function invalidateCloudAccountPayloadCache({ sessionChanged = false } = {}) {
179
- if (sessionChanged) {
180
- sessionGeneration += 1;
181
- tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
182
- mintInflight.clear();
183
- }
184
- payloadGeneration += 1;
185
- payloadCache.clear();
186
- payloadInflight.clear();
187
- payloadVersions.clear();
188
- }
189
-
190
- function getCloudAccountSessionGeneration() {
191
- return sessionGeneration;
192
- }
193
-
194
- function __resetCloudAccountCacheForTests() {
195
- tokenCache = { cacheKey: null, accessToken: null, expMs: 0 };
196
- mintInflight.clear();
197
- invalidateCloudAccountPayloadCache({ sessionChanged: true });
198
- }
199
-
200
- // Failure classes surfaced to local-api so it can tell an intentional local
201
- // view ("signed out", "cloud sync off") apart from a temporary cloud outage.
202
- class AccountAuthError extends Error {
203
- constructor(code, message) {
204
- super(message || code);
205
- this.name = "AccountAuthError";
206
- this.code = code;
207
- }
208
- }
209
-
210
- function csrfTokenFromRefreshPayload(data) {
211
- if (!data || typeof data !== "object") return null;
212
- const raw =
213
- (typeof data.csrfToken === "string" && data.csrfToken) ||
214
- (typeof data.csrf_token === "string" && data.csrf_token) ||
215
- null;
216
- return raw && raw.length > 0 ? raw : null;
217
- }
218
-
219
- /**
220
- * Perform the actual refresh POST. Throws a classified `AccountAuthError` on
221
- * every failure so callers can distinguish a transient outage (timeout,
222
- * offline, rotated-token rejection) from an intentionally local view.
223
- */
224
- async function performMint({ root, anonKey, refreshToken, fetchImpl, now, timeoutMs }) {
225
- const mintSessionGeneration = sessionGeneration;
226
- const headers = { "Content-Type": "application/json", Accept: "application/json" };
227
- if (anonKey) headers.apikey = anonKey;
228
-
229
- let timeoutId;
230
- const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
231
- const signal = controller ? controller.signal : undefined;
232
-
233
- if (controller && timeoutMs && timeoutMs > 0) {
234
- timeoutId = setTimeout(() => {
235
- controller.abort();
236
- }, timeoutMs);
237
- }
238
-
239
- let res;
240
- try {
241
- res = await fetchImpl(`${root}/api/auth/refresh?client_type=mobile`, {
242
- method: "POST",
243
- headers,
244
- body: JSON.stringify({ refresh_token: refreshToken }),
245
- signal,
246
- });
247
- } catch (e) {
248
- const aborted = e && (e.name === "AbortError" || e.name === "TimeoutError");
249
- throw new AccountAuthError(
250
- aborted ? "auth_timeout" : "auth_network",
251
- e?.message || "token refresh failed",
252
- );
253
- } finally {
254
- if (timeoutId) {
255
- clearTimeout(timeoutId);
256
- }
257
- }
258
- if (!res || !res.ok) {
259
- const err = new AccountAuthError(
260
- "auth_rejected",
261
- `token refresh failed with HTTP ${res ? res.status : "?"}`,
262
- );
263
- err.status = res ? res.status : 0;
264
- throw err;
265
- }
266
-
267
- let data = null;
268
- try {
269
- data = await res.json();
270
- } catch (e) {
271
- throw new AccountAuthError("auth_invalid", e?.message || "token refresh returned invalid JSON");
272
- }
273
-
274
- const accessToken = accessTokenFromRefreshPayload(data);
275
- if (!accessToken) {
276
- throw new AccountAuthError("auth_invalid", "token refresh returned no access token");
277
- }
278
-
279
- const expMs = decodeJwtExpMs(accessToken) || now() + 10 * 60_000;
280
- if (mintSessionGeneration !== sessionGeneration) {
281
- throw new AccountAuthError("auth_session_changed", "account session changed during token refresh");
282
- }
283
- const rotated = refreshTokenFromRefreshPayload(data);
284
- // The caller persists a rotation before its next account read. Key the
285
- // still-valid access token by that current refresh token, not the consumed one.
286
- tokenCache = { cacheKey: `${root}\0${rotated || refreshToken}`, accessToken, expMs };
287
- return {
288
- accessToken,
289
- refreshToken: rotated && rotated !== refreshToken ? rotated : null,
290
- // Rotating the refresh token can invalidate the csrf token paired with the
291
- // previous session state. Surface the fresh one so the caller can keep the
292
- // relayed (refresh, csrf) pair in sync — a stale relayed csrf breaks the
293
- // dashboard's cookie-path refresh with 403 Invalid CSRF.
294
- csrfToken: csrfTokenFromRefreshPayload(data),
295
- };
296
- }
297
-
298
- /**
299
- * Mint (or reuse a cached) InsForge access token from a refresh token.
300
- *
301
- * Concurrent callers with the same (baseUrl, refreshToken) share ONE in-flight
302
- * refresh; see `mintInflight`.
303
- *
304
- * @param {boolean} [throwOnFailure] when true, reject with a classified
305
- * `AccountAuthError` instead of resolving to `null`.
306
- * @returns {Promise<{accessToken: string, refreshToken: string|null, csrfToken: string|null}|null>}
307
- * null when no refresh token is available or the refresh failed.
308
- */
309
- async function mintAccessToken({
310
- baseUrl,
311
- anonKey,
312
- refreshToken,
313
- fetchImpl = fetch,
314
- now = Date.now,
315
- skewMs = 60_000,
316
- timeoutMs,
317
- throwOnFailure = false,
318
- } = {}) {
319
- if (!refreshToken) {
320
- if (throwOnFailure) throw new AccountAuthError("auth_missing_refresh_token", "not signed in");
321
- return null;
322
- }
323
- const root = String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
324
- const cacheKey = `${root}\0${refreshToken}`;
325
- if (
326
- tokenCache.cacheKey === cacheKey &&
327
- tokenCache.accessToken &&
328
- tokenCache.expMs - skewMs > now()
329
- ) {
330
- return { accessToken: tokenCache.accessToken, refreshToken: null, csrfToken: null };
331
- }
332
-
333
- let inflight = mintInflight.get(cacheKey);
334
- if (!inflight) {
335
- inflight = performMint({ root, anonKey, refreshToken, fetchImpl, now, timeoutMs })
336
- .finally(() => {
337
- // Only clear our own entry: a later caller may already have started a
338
- // fresh mint after this one settled.
339
- if (mintInflight.get(cacheKey) === inflight) mintInflight.delete(cacheKey);
340
- });
341
- mintInflight.set(cacheKey, inflight);
342
- }
343
-
344
- try {
345
- return await inflight;
346
- } catch (e) {
347
- if (throwOnFailure) throw e;
348
- return null;
349
- }
350
- }
351
-
352
- /**
353
- * GET a `token-usage-account-*` edge function, forwarding the popover's query
354
- * params (minus `account`/`scope`, which are local-only routing knobs).
355
- */
356
- async function fetchAccountFunction({
357
- baseUrl,
358
- anonKey,
359
- accessToken,
360
- slug,
361
- searchParams,
362
- fetchImpl = fetch,
363
- timeoutMs,
364
- } = {}) {
365
- const root = String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
366
- const url = new URL(functionUrlFor(root, slug));
367
- url.search = accountFunctionParams(slug, searchParams).toString();
368
- const headers = { Accept: "application/json", Authorization: `Bearer ${accessToken}` };
369
- if (anonKey) headers.apikey = anonKey;
370
-
371
- let timeoutId;
372
- const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
373
- const signal = controller ? controller.signal : undefined;
374
-
375
- if (controller && timeoutMs && timeoutMs > 0) {
376
- timeoutId = setTimeout(() => {
377
- controller.abort();
378
- }, timeoutMs);
379
- }
380
-
381
- try {
382
- const res = await fetchFunctionResponse(url.toString(), { method: "GET", headers, signal }, fetchImpl);
383
- if (!res || !res.ok) {
384
- const err = new Error(`Account fetch failed with HTTP ${res ? res.status : "?"}`);
385
- err.status = res ? res.status : 0;
386
- const failure = res?.json ? await res.json().catch(() => ({})) : {};
387
- if (typeof failure?.code === "string") err.code = failure.code;
388
- if (typeof failure?.recovery_url === "string") err.recoveryUrl = failure.recovery_url;
389
- throw err;
390
- }
391
- const data = await res.json();
392
- return slug === HEATMAP_ACCOUNT_SLUG ? expandHeatmapCompact(data) : data;
393
- } finally {
394
- if (timeoutId) {
395
- clearTimeout(timeoutId);
396
- }
397
- }
398
- }
399
-
400
- /**
401
- * High-level helper used by local-api: mint a token from `refreshToken`, then
402
- * fetch the cross-device aggregate matching `usageSlug`.
403
- *
404
- * @returns {Promise<{data: any, rotatedRefreshToken: string|null, rotatedCsrfToken: string|null}|null>}
405
- * null when there is no cloud equivalent, no refresh token, or the refresh
406
- * failed. Throws only when the account endpoint itself errors (so callers can
407
- * distinguish "not signed in" from "cloud request failed").
408
- */
409
- async function fetchAccountUsage({
410
- usageSlug,
411
- searchParams,
412
- baseUrl = DEFAULT_BASE_URL,
413
- anonKey = DEFAULT_ANON_KEY,
414
- refreshToken,
415
- fetchImpl = fetch,
416
- now = Date.now,
417
- timeoutMs,
418
- onSessionRefreshed,
419
- } = {}) {
420
- const slug = accountSlugFor(usageSlug);
421
- if (!slug) return null;
422
- if (!refreshToken) return null;
423
-
424
- const sessionAtStart = sessionGeneration;
425
- const startTime = now();
426
- const getRemainingTimeout = () => {
427
- if (!timeoutMs) return undefined;
428
- const elapsed = now() - startTime;
429
- const remaining = timeoutMs - elapsed;
430
- return remaining > 0 ? remaining : 1;
431
- };
432
-
433
- // `throwOnFailure` keeps "not signed in" (null, handled above) distinct from
434
- // "signed in but the refresh call failed" (throws) so the caller does not
435
- // silently downgrade an account view into a this-machine view.
436
- const minted = await mintAccessToken({
437
- baseUrl,
438
- anonKey,
439
- refreshToken,
440
- fetchImpl,
441
- now,
442
- timeoutMs: getRemainingTimeout(),
443
- throwOnFailure: true,
444
- });
445
- if (!minted) return null;
446
- if (sessionAtStart !== sessionGeneration) {
447
- throw new AccountAuthError("auth_session_changed", "account session changed during token refresh");
448
- }
449
-
450
- // The refresh already consumed the old credential. Persist its replacement
451
- // before an edge read can wait, fail, or overlap a different account query.
452
- if (typeof onSessionRefreshed === "function" && (minted.refreshToken || minted.csrfToken)) {
453
- await onSessionRefreshed({ refreshToken: minted.refreshToken, csrfToken: minted.csrfToken });
454
- if (sessionAtStart !== sessionGeneration) {
455
- throw new AccountAuthError("auth_session_changed", "account session changed during token persistence");
456
- }
457
- }
458
-
459
- // Keyed after the mint so rotation cannot invalidate the entry, and so a
460
- // revoked session fails here rather than being served from cache.
461
- const sub = decodeJwtSub(minted.accessToken);
462
- const cacheKey = sub
463
- ? payloadCacheKey({ root: String(baseUrl || DEFAULT_BASE_URL).replace(/\/$/, ""), sub, slug, searchParams })
464
- : null;
465
- const force = searchParams?.get("refresh") === "1";
466
- if (cacheKey && !force) {
467
- const cached = payloadCacheGet(cacheKey, now);
468
- if (cached !== null) {
469
- // Still surface a rotation from this mint: dropping it would leave the
470
- // caller relaying a refresh token the backend has already consumed.
471
- return {
472
- data: cached,
473
- rotatedRefreshToken: minted.refreshToken,
474
- rotatedCsrfToken: minted.csrfToken,
475
- };
476
- }
477
- }
478
-
479
- const flightKey = cacheKey ? `${cacheKey}\0${payloadGeneration}\0${force ? "refresh" : `normal:${payloadVersions.get(cacheKey) || 0}`}` : null;
480
- let pending = flightKey && payloadInflight.get(flightKey);
481
- if (!pending) {
482
- // A forced read supersedes an older ordinary read of the same account.
483
- // Keep concurrent forced consumers together without sharing its old flight.
484
- if (force && cacheKey) {
485
- payloadCache.delete(cacheKey);
486
- payloadVersions.set(cacheKey, (payloadVersions.get(cacheKey) || 0) + 1);
487
- }
488
- const generation = payloadGeneration;
489
- const version = payloadVersions.get(cacheKey) || 0;
490
- pending = (async () => {
491
- try {
492
- const data = await fetchAccountFunction({
493
- baseUrl, anonKey, accessToken: minted.accessToken, slug, searchParams,
494
- fetchImpl, timeoutMs: getRemainingTimeout(),
495
- });
496
- if (generation === payloadGeneration && version === (payloadVersions.get(cacheKey) || 0) && cacheKey && data != null) {
497
- payloadCacheSet(cacheKey, data, now, slug === "token-usage-account-summary" ? SUMMARY_PAYLOAD_TTL_MS : PAYLOAD_TTL_MS);
498
- }
499
- return JSON.stringify(data);
500
- } catch (error) {
501
- if (error.status === 401 && sessionAtStart === sessionGeneration) {
502
- invalidateCloudAccountPayloadCache({ sessionChanged: true });
503
- error.invalidatedSessionGeneration = sessionGeneration;
504
- }
505
- throw error;
506
- }
507
- })();
508
- if (flightKey) {
509
- payloadInflight.set(flightKey, pending);
510
- const cleanup = () => {
511
- if (payloadInflight.get(flightKey) === pending) payloadInflight.delete(flightKey);
512
- };
513
- pending.then(cleanup, cleanup);
514
- }
515
- }
516
- const body = await pending;
517
- if (sessionAtStart !== sessionGeneration) {
518
- throw new AccountAuthError("auth_session_changed", "account session changed during account read");
519
- }
520
- const data = body === undefined ? undefined : JSON.parse(body);
521
- return { data, rotatedRefreshToken: minted.refreshToken, rotatedCsrfToken: minted.csrfToken };
522
- }
523
-
524
- module.exports = {
525
- AccountAuthError,
526
- USAGE_TO_ACCOUNT_SLUG,
527
- PAYLOAD_TTL_MS,
528
- SUMMARY_PAYLOAD_TTL_MS,
529
- invalidateCloudAccountPayloadCache,
530
- getCloudAccountSessionGeneration,
531
- HEATMAP_ACCOUNT_SLUG,
532
- accountSlugFor,
533
- accessTokenFromRefreshPayload,
534
- refreshTokenFromRefreshPayload,
535
- decodeJwtExpMs,
536
- decodeJwtSub,
537
- mintAccessToken,
538
- fetchAccountFunction,
539
- fetchAccountUsage,
540
- __resetCloudAccountCacheForTests,
541
- };