tempest-react-sdk 0.77.0 → 0.78.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.
Files changed (79) hide show
  1. package/bin/lib/alias/collect.mjs +20 -3
  2. package/bin/lib/alias/index.mjs +12 -1
  3. package/bin/lib/alias/index.test.mjs +24 -0
  4. package/bin/lib/css/analyze.test.mjs +21 -1
  5. package/bin/lib/css/collect.mjs +14 -0
  6. package/bin/lib/css/extract.mjs +63 -5
  7. package/bin/lib/css/extract.test.mjs +110 -1
  8. package/bin/lib/css/fix.e2e.test.mjs +50 -0
  9. package/bin/lib/css/index.mjs +6 -1
  10. package/bin/lib/fs/contain.mjs +50 -0
  11. package/bin/lib/icons/generate.mjs +28 -3
  12. package/bin/lib/icons/generate.test.mjs +57 -1
  13. package/bin/lib/openapi/escape.mjs +20 -6
  14. package/bin/lib/openapi/generate.encode.test.mjs +120 -0
  15. package/bin/lib/openapi/generate.hostile.test.mjs +38 -9
  16. package/bin/lib/openapi/generate.mjs +41 -6
  17. package/bin/lib/openapi/generate.test.mjs +7 -2
  18. package/bin/lib/openapi/schema-to-zod.mjs +5 -3
  19. package/bin/tempest-gen.test.mjs +188 -0
  20. package/bin/tempest.mjs +120 -44
  21. package/dist/auth/create-tempest-auth.cjs +1 -1
  22. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  23. package/dist/auth/create-tempest-auth.js +186 -113
  24. package/dist/auth/create-tempest-auth.js.map +1 -1
  25. package/dist/br/pix.cjs +1 -1
  26. package/dist/br/pix.cjs.map +1 -1
  27. package/dist/br/pix.js +30 -27
  28. package/dist/br/pix.js.map +1 -1
  29. package/dist/br.d.ts +11 -4
  30. package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
  31. package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
  32. package/dist/components/CodeBlock/CodeBlock.js +1 -1
  33. package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
  34. package/dist/components/CodeBlock/tokenize.cjs +1 -1
  35. package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
  36. package/dist/components/CodeBlock/tokenize.js +54 -25
  37. package/dist/components/CodeBlock/tokenize.js.map +1 -1
  38. package/dist/components/Markdown/markdown-parse.cjs +6 -6
  39. package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
  40. package/dist/components/Markdown/markdown-parse.js +91 -74
  41. package/dist/components/Markdown/markdown-parse.js.map +1 -1
  42. package/dist/http/resumable-upload.cjs +1 -1
  43. package/dist/http/resumable-upload.cjs.map +1 -1
  44. package/dist/http/resumable-upload.js +141 -105
  45. package/dist/http/resumable-upload.js.map +1 -1
  46. package/dist/http/retry.cjs +1 -1
  47. package/dist/http/retry.cjs.map +1 -1
  48. package/dist/http/retry.js +5 -6
  49. package/dist/http/retry.js.map +1 -1
  50. package/dist/sw/background-sync.cjs +1 -1
  51. package/dist/sw/background-sync.cjs.map +1 -1
  52. package/dist/sw/background-sync.js +32 -31
  53. package/dist/sw/background-sync.js.map +1 -1
  54. package/dist/sw/credential-headers.cjs.map +1 -1
  55. package/dist/sw/credential-headers.js.map +1 -1
  56. package/dist/sw.d.ts +46 -8
  57. package/dist/telemetry/app-error-reporter.cjs +1 -1
  58. package/dist/telemetry/app-error-reporter.cjs.map +1 -1
  59. package/dist/telemetry/app-error-reporter.js +1 -1
  60. package/dist/telemetry/app-error-reporter.js.map +1 -1
  61. package/dist/tempest-react-sdk.cjs +1 -1
  62. package/dist/tempest-react-sdk.d.ts +214 -12
  63. package/dist/tempest-react-sdk.js +119 -119
  64. package/dist/utils/csv.cjs +3 -3
  65. package/dist/utils/csv.cjs.map +1 -1
  66. package/dist/utils/csv.js +11 -10
  67. package/dist/utils/csv.js.map +1 -1
  68. package/dist/{telemetry/app-error-owner.cjs → utils/owner-fingerprint.cjs} +2 -2
  69. package/dist/utils/owner-fingerprint.cjs.map +1 -0
  70. package/dist/{telemetry/app-error-owner.js → utils/owner-fingerprint.js} +3 -3
  71. package/dist/utils/owner-fingerprint.js.map +1 -0
  72. package/dist/vite/tempest-csp.cjs +2 -2
  73. package/dist/vite/tempest-csp.cjs.map +1 -1
  74. package/dist/vite/tempest-csp.js +69 -58
  75. package/dist/vite/tempest-csp.js.map +1 -1
  76. package/dist/vite.d.ts +5 -3
  77. package/package.json +1 -1
  78. package/dist/telemetry/app-error-owner.cjs.map +0 -1
  79. package/dist/telemetry/app-error-owner.js.map +0 -1
package/bin/tempest.mjs CHANGED
@@ -9,7 +9,7 @@
9
9
  // tempest gen <api|icons|component> … code generators (`new component` = alias)
10
10
  // tempest --help | --version
11
11
  import { spawnSync } from "node:child_process";
12
- import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
12
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
13
13
  import { mkdir, writeFile } from "node:fs/promises";
14
14
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
@@ -17,7 +17,14 @@ import { aliasImports } from "./lib/alias/index.mjs";
17
17
  import { describeTypeScript, loadTypeScript } from "./lib/alias/typescript.mjs";
18
18
  import { readTsconfig } from "./lib/alias/tsconfig.mjs";
19
19
  import { componentFiles } from "./lib/component/generate.mjs";
20
- import { analyzeCss, applyCssFixes, applyExtraction, planExtraction } from "./lib/css/index.mjs";
20
+ import { landsInside, lstatOrNull } from "./lib/fs/contain.mjs";
21
+ import {
22
+ analyzeCss,
23
+ applyCssFixes,
24
+ applyExtraction,
25
+ OUTSIDE_PROJECT,
26
+ planExtraction,
27
+ } from "./lib/css/index.mjs";
21
28
  import { analyzeDesign } from "./lib/design/index.mjs";
22
29
  import { checkLucide } from "./lib/doctor/lucide.mjs";
23
30
  import { generateRegistry, loadIconTables } from "./lib/icons/generate.mjs";
@@ -1052,6 +1059,7 @@ function reportAlias(result, dryRun) {
1052
1059
  for (const err of result.errors) {
1053
1060
  console.log(` ${c.red}✗ ${err.path}${c.reset} ${c.dim}${err.message}${c.reset}`);
1054
1061
  }
1062
+ reportOutside(result.outside ?? 0);
1055
1063
  if (!result.total) {
1056
1064
  console.log(` ${c.dim}nothing to convert${c.reset}`);
1057
1065
  return;
@@ -1062,6 +1070,22 @@ function reportAlias(result, dryRun) {
1062
1070
  );
1063
1071
  }
1064
1072
 
1073
+ /**
1074
+ * Say how many files a `fix` pass left alone because they resolve outside the
1075
+ * project through a symlink.
1076
+ *
1077
+ * The passes skip those files rather than rewrite them; printing the count here,
1078
+ * and not only in `doctor`, keeps a planted `src -> /elsewhere` from turning
1079
+ * `fix` into a silent no-op.
1080
+ *
1081
+ * @param {number} count - Files skipped by one pass.
1082
+ * @returns {void}
1083
+ */
1084
+ function reportOutside(count) {
1085
+ if (count === 0) return;
1086
+ console.log(` ${c.yellow}! ${count} arquivo(s) fora do projeto (symlink) — pulados${c.reset}`);
1087
+ }
1088
+
1065
1089
  /** Prefix for a finding line: red for a browser-visible defect, yellow otherwise. */
1066
1090
  function severityMark(severity) {
1067
1091
  if (severity === "error") return `${c.red}✗${c.reset}`;
@@ -1098,6 +1122,7 @@ function cssPass({ targets, dryRun, extract = false, target, prefix }) {
1098
1122
  );
1099
1123
  return 1;
1100
1124
  }
1125
+ reportOutside(analysis.skipped.filter((s) => s.reason === OUTSIDE_PROJECT).length);
1101
1126
  if (analysis.stats.files === 0) {
1102
1127
  console.log(` ${c.dim}no stylesheets found${c.reset}`);
1103
1128
  return 0;
@@ -1296,12 +1321,29 @@ async function genApi(args) {
1296
1321
  return 1;
1297
1322
  }
1298
1323
  const outDir = resolve(ROOT, parseOut(args, "src/api"));
1324
+ const outProblem = writeTargetProblem(outDir, "dir");
1325
+ if (outProblem) {
1326
+ console.error(
1327
+ `${c.red}✗ ${shownPath(outDir)} ${outProblem}.${c.reset} Nothing was written.`,
1328
+ );
1329
+ return 1;
1330
+ }
1299
1331
  console.log(`${c.dim}→ loading ${source}${c.reset}`);
1300
1332
  const doc = await loadSpec(source);
1301
1333
  const { files, tags } = generate(doc);
1302
1334
 
1303
- for (const [rel, contents] of Object.entries(files)) {
1304
- const dest = join(outDir, rel);
1335
+ const targets = Object.entries(files).map(([rel, contents]) => ({
1336
+ dest: join(outDir, rel),
1337
+ contents,
1338
+ }));
1339
+ for (const { dest } of targets) {
1340
+ const problem = generatedFileProblem(outDir, dest);
1341
+ if (problem) {
1342
+ console.error(`${c.red}✗ ${problem}.${c.reset} Nothing was written.`);
1343
+ return 1;
1344
+ }
1345
+ }
1346
+ for (const { dest, contents } of targets) {
1305
1347
  await mkdir(dirname(dest), { recursive: true });
1306
1348
  await writeFile(dest, contents);
1307
1349
  }
@@ -1343,6 +1385,12 @@ async function genIcons(args) {
1343
1385
  const dirIndex = args.indexOf("--dir");
1344
1386
  const dirRel = dirIndex >= 0 && args[dirIndex + 1] ? args[dirIndex + 1] : "src";
1345
1387
  const dir = resolve(ROOT, dirRel);
1388
+ const dest = resolve(ROOT, outRel);
1389
+ const destProblem = generatedFileProblem(dirname(dest), dest);
1390
+ if (destProblem) {
1391
+ console.error(`${c.red}✗ ${destProblem}.${c.reset} Nothing was written.`);
1392
+ return 1;
1393
+ }
1346
1394
 
1347
1395
  let tables;
1348
1396
  try {
@@ -1361,7 +1409,6 @@ async function genIcons(args) {
1361
1409
  aliases: tables.aliases,
1362
1410
  });
1363
1411
 
1364
- const dest = resolve(ROOT, outRel);
1365
1412
  await mkdir(dirname(dest), { recursive: true });
1366
1413
  await writeFile(dest, source);
1367
1414
 
@@ -1380,34 +1427,74 @@ async function genIcons(args) {
1380
1427
  // ------------------------------------------------------- gen component ----
1381
1428
 
1382
1429
  /**
1383
- * `lstat` that answers `null` for a missing path instead of throwing.
1430
+ * Why a generator must not write `path`, or `null` when it may.
1384
1431
  *
1385
- * @param {string} path - Absolute path.
1386
- * @returns {import("node:fs").Stats | null}
1432
+ * The one check every generator (`gen api`, `gen icons`, `gen component`) runs on
1433
+ * each folder it creates and each file it writes, before the first write:
1434
+ *
1435
+ * - `path` itself must not be a symlink — dangling included, since `mkdir` and
1436
+ * `writeFile` follow a link to wherever it points, existing or not;
1437
+ * - it must land inside the project once symlinks are resolved
1438
+ * ({@link landsInside});
1439
+ * - if it exists, it must be what is about to be written there: a folder for
1440
+ * `"dir"`, a regular file for `"file"`.
1441
+ *
1442
+ * A symlinked ancestor that resolves inside the project is accepted, as it
1443
+ * always was for `gen component`; one that leaves it, or dangles, is refused.
1444
+ *
1445
+ * @param {string} path - Absolute path about to be created or rewritten.
1446
+ * @param {"dir" | "file"} kind - What the generator writes there.
1447
+ * @returns {string | null} A phrase completing "`<path>` …", or `null`.
1387
1448
  */
1388
- function lstatOrNull(path) {
1389
- try {
1390
- return lstatSync(path);
1391
- } catch {
1392
- return null;
1393
- }
1449
+ function writeTargetProblem(path, kind) {
1450
+ const stat = lstatOrNull(path);
1451
+ if (stat?.isSymbolicLink()) return "is a symlink; refusing to write through it";
1452
+ if (!landsInside(ROOT, path)) {
1453
+ return `is outside the project (${ROOT}) once symlinks are resolved`;
1454
+ }
1455
+ if (stat && kind === "dir" && !stat.isDirectory()) return "exists and is not a folder";
1456
+ if (stat && kind === "file" && !stat.isFile()) return "is not a regular file";
1457
+ return null;
1394
1458
  }
1395
1459
 
1396
1460
  /**
1397
- * Whether `path` would be created inside the project.
1461
+ * Check one generated file and every folder between `base` and it.
1398
1462
  *
1399
- * Resolves the nearest ancestor that exists through `realpath`, so `../x`, an
1400
- * absolute path and an ancestor that is a symlink to somewhere else
1401
- * (`src/components -> /elsewhere`) are all seen where they really land.
1463
+ * `gen api` writes `<out>/<tag>/service.ts`, so a symlink at `<out>/<tag>` would
1464
+ * carry the write elsewhere as surely as one at `<out>`; each level is checked,
1465
+ * not just the leaf.
1402
1466
  *
1403
- * @param {string} path - Absolute path about to be created.
1404
- * @returns {boolean}
1467
+ * @param {string} base - Folder already checked (the `--out` of `gen api`), or
1468
+ * the file's own folder when nothing above it is generated.
1469
+ * @param {string} dest - Absolute path of the file about to be written.
1470
+ * @returns {string | null} The full refusal ("`<path>` is …"), or `null`.
1405
1471
  */
1406
- function landsInsideProject(path) {
1407
- let existing = path;
1408
- while (!existsSync(existing) && dirname(existing) !== existing) existing = dirname(existing);
1409
- const rel = relative(realpathSync(ROOT), realpathSync(existing));
1410
- return !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel));
1472
+ function generatedFileProblem(base, dest) {
1473
+ const rel = relative(base, dirname(dest));
1474
+ const folders = [base];
1475
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
1476
+ folders[0] = dirname(dest);
1477
+ } else {
1478
+ for (const segment of rel.split(sep).filter(Boolean)) {
1479
+ folders.push(join(folders[folders.length - 1], segment));
1480
+ }
1481
+ }
1482
+ for (const folder of folders) {
1483
+ const problem = writeTargetProblem(folder, "dir");
1484
+ if (problem) return `${shownPath(folder)} ${problem}`;
1485
+ }
1486
+ const problem = writeTargetProblem(dest, "file");
1487
+ return problem ? `${shownPath(dest)} ${problem}` : null;
1488
+ }
1489
+
1490
+ /**
1491
+ * `path` relative to the project, with `/` separators, for messages.
1492
+ *
1493
+ * @param {string} path - Absolute path.
1494
+ * @returns {string}
1495
+ */
1496
+ function shownPath(path) {
1497
+ return relative(ROOT, path).split(sep).join("/") || ".";
1411
1498
  }
1412
1499
 
1413
1500
  /**
@@ -1480,33 +1567,22 @@ async function genComponent(args) {
1480
1567
  return 1;
1481
1568
  }
1482
1569
  const dir = resolve(ROOT, parsed.out, generated.name);
1483
- const shown = relative(ROOT, dir).split(sep).join("/") || ".";
1570
+ const shown = shownPath(dir);
1484
1571
 
1485
- if (!landsInsideProject(dir)) {
1486
- console.error(
1487
- `${c.red}✗ ${dir} is outside the project${c.reset} (${ROOT}), once symlinks are resolved. Pick an --out inside it.`,
1488
- );
1489
- return 1;
1490
- }
1491
- const dirStat = lstatOrNull(dir);
1492
- if (dirStat?.isSymbolicLink()) {
1493
- console.error(`${c.red}✗ ${shown} is a symlink; refusing to write through it.${c.reset}`);
1572
+ const dirProblem = writeTargetProblem(dir, "dir");
1573
+ if (dirProblem) {
1574
+ console.error(`${c.red}✗ ${shown} ${dirProblem}.${c.reset}`);
1494
1575
  return 1;
1495
1576
  }
1496
- if (dirStat && !parsed.force) {
1577
+ if (lstatOrNull(dir) && !parsed.force) {
1497
1578
  console.error(
1498
1579
  `${c.red}✗ ${shown} already exists.${c.reset} Pass --force to rewrite its five generated files.`,
1499
1580
  );
1500
1581
  return 1;
1501
1582
  }
1502
- if (dirStat && !dirStat.isDirectory()) {
1503
- console.error(`${c.red}✗ ${shown} exists and is not a folder.${c.reset}`);
1504
- return 1;
1505
- }
1506
- const blocked = Object.keys(generated.files).find((file) => {
1507
- const stat = lstatOrNull(join(dir, file));
1508
- return stat !== null && !stat.isFile();
1509
- });
1583
+ const blocked = Object.keys(generated.files).find((file) =>
1584
+ writeTargetProblem(join(dir, file), "file"),
1585
+ );
1510
1586
  if (blocked) {
1511
1587
  console.error(
1512
1588
  `${c.red}✗ ${shown}/${blocked} is not a regular file${c.reset} (a folder or a symlink); nothing was written.`,
@@ -1,2 +1,2 @@
1
- const e=require("../http/errors.cjs"),t=require("../http/api-client.cjs"),n=require("./create-auth-store.cjs"),r=require("./refresh-queue.cjs");function i(e){let t=e??{};return{token:t.access_token,refreshToken:t.refresh_token}}function a(a){let{baseURL:o,prefix:s,loginPath:c=`/api/auth/login`,refreshPath:l=`/api/auth/refresh`,mePath:u,storeName:d=`tempest-auth`,storage:f=`local`,withCredentials:p=!1,csrf:m,fetcher:h,parseTokens:g=i,parseUser:_,refreshBody:v=e=>e?{refresh_token:e}:void 0,retry:y,redirectTo:b,onSessionEnd:x}=a,S=n.createAuthStore({name:d,storage:f}),C=`${d}-refresh`;function w(){return typeof window>`u`?null:f===`session`?window.sessionStorage:window.localStorage}function T(){return w()?.getItem(C)??null}function E(e){let t=w();t&&(e?t.setItem(C,e):t.removeItem(C))}let D=()=>S.getState(),O=()=>D().token;async function k(){if(!u)return D().user;let e=await U.get(u,{skipAuthRetry:!0});return D().setUser(e),e}let A=0,j=Promise.resolve(),M=0;function N(){A+=1,F=r.createRefreshQueue(P)}async function P(){let t=A,n;try{n=await U.post(l,{body:v(T()),skipAuth:!0})}catch(n){throw A===t?n:new e.SessionSupersededError}if(A!==t)throw new e.SessionSupersededError;let{token:r,refreshToken:i}=g(n);D().setToken(r),i&&E(i)}let F=r.createRefreshQueue(P);function I(e){let t=O();return t===null?!1:e.token===null||e.token!==t}async function L(t){if(t.epoch!==null&&t.epoch!==A)throw new e.SessionSupersededError;if(I(t)){if(t.token===null)throw Error(`anonymous 401 under a live session`);return}return F()}async function R(t,n){if(n.epoch!==null&&n.epoch!==A)throw new e.SessionSupersededError;I(n)||await H()}async function z(t){let n=A,r=await U.post(c,{body:t,skipAuth:!0});if(A!==n)throw new e.SessionSupersededError;let{token:i,refreshToken:a}=g(r),{done:o}=B(`switch`),s=A;if(await o.catch(()=>void 0),A!==s)throw new e.SessionSupersededError;D().setToken(i),E(a??null);let l=_?.(r);return l==null?k():(D().setUser(l),l)}function B(e){N();let{user:n,token:r}=D(),i=r!==null||n!==null||T()!==null;if(D().logout(),E(null),!i)return{live:i,done:e===`switch`||M===0?j:Promise.resolve()};if(!x)return{live:i,done:Promise.resolve()};let a=t.createApiClient({baseURL:o,prefix:s,withCredentials:p,csrf:m,fetcher:h,getToken:()=>r});M+=1;let c=(async()=>{try{await x({reason:e,user:n,token:r,api:a})}finally{--M}})();return j=c.then(()=>void 0,()=>void 0),{live:i,done:c.then(()=>void 0)}}function V(){return B(`logout`).done}async function H(){let{live:e,done:t}=B(`expired`);await t.catch(()=>void 0),e&&b&&typeof window<`u`&&window.location.assign(b)}let U=t.createApiClient({baseURL:o,prefix:s,withCredentials:p,csrf:m,fetcher:h,getToken:O,getSessionEpoch:()=>A,refresh:L,retry:y,onUnauthorized:R});return{useAuthStore:S,api:U,login:z,logout:V,refresh:()=>F(),getToken:O}}exports.createTempestAuth=a;
1
+ const e=require("../utils/dev-mode.cjs"),t=require("../http/errors.cjs"),n=require("../http/api-client.cjs"),r=require("./create-auth-store.cjs"),i=require("./refresh-queue.cjs");var a=1e4;function o(e,t){return e.length===0?Promise.resolve():new Promise(n=>{let r=setTimeout(n,t);Promise.allSettled(e).then(()=>{clearTimeout(r),n()})})}function s(e){let t=e??{};return{token:t.access_token,refreshToken:t.refresh_token}}function c(c){let{baseURL:l,prefix:u,loginPath:d=`/api/auth/login`,refreshPath:ee=`/api/auth/refresh`,logoutPath:f,onLogoutError:te,mePath:p,storeName:m=`tempest-auth`,storage:h=`local`,withCredentials:g=!1,csrf:_,fetcher:v,parseTokens:y=s,parseUser:b,refreshBody:x=e=>e?{refresh_token:e}:void 0,retry:ne,redirectTo:S,onSessionEnd:C}=c,w=r.createAuthStore({name:m,storage:h}),T=`${m}-refresh`;function E(){return typeof window>`u`?null:h===`session`?window.sessionStorage:window.localStorage}function D(){return E()?.getItem(T)??null}function O(e){let t=E();t&&(e?t.setItem(T,e):t.removeItem(T))}let k=()=>w.getState(),A=()=>k().token;async function j(){if(!p)return k().user;let e=M,n;try{n=await $.get(p,{skipAuthRetry:!0})}catch(n){throw M===e?n:new t.SessionSupersededError}if(M!==e)throw new t.SessionSupersededError;return k().setUser(n),n}let M=0,N=Promise.resolve(),P=0,F=new Set,I=new Set,L=new Set,R=new Set;function z(e){let t=e.then(()=>void 0,()=>void 0);return L.add(t),t.then(()=>L.delete(t)),e}function B(t){e.isDevBuild()&&console.warn(`[tempest-react-sdk] createTempestAuth: logoutPath revocation failed`,t);try{te?.(t)}catch{return}}function V(e){let t=(async()=>{try{await e()}catch(e){B(e)}})();return I.add(t),t.then(()=>I.delete(t)),t}function H(e,t){f&&!g&&t&&V(()=>U(e).post(f,{body:x(t)}))}function U(e){return n.createApiClient({baseURL:l,prefix:u,withCredentials:g,csrf:_,fetcher:v,getToken:()=>e})}function W(){M+=1,K=i.createRefreshQueue(G)}async function G(){let e=M;R.add(e);try{let n;try{n=await z($.post(ee,{body:x(D()),skipAuth:!0}))}catch(n){throw M===e?n:new t.SessionSupersededError}let{token:r,refreshToken:i}=y(n);if(M!==e)throw H(r??null,i),new t.SessionSupersededError;k().setToken(r),i&&O(i)}finally{R.delete(e)}}let K=i.createRefreshQueue(G);function q(e){let t=A();return t===null?!1:e.token===null||e.token!==t}function J(){return A()===null&&D()===null}async function Y(){if(!(F.size>0&&P===0&&(await Promise.allSettled([...F]),A()!==null)))throw Error(`anonymous 401 with no session`)}async function X(e){if(e.epoch!==null&&e.epoch!==M)throw new t.SessionSupersededError;if(q(e)){if(e.token===null)throw Error(`anonymous 401 under a live session`);return}return e.token===null&&J()?R.has(M)?K():Y():K()}async function Z(e,n){if(n.epoch!==null&&n.epoch!==M)throw new t.SessionSupersededError;q(n)||n.token===null&&J()||await se()}async function re(e){I.size>0&&await o([...I],a);let t=ie(e);F.add(t);try{return await t}finally{F.delete(t)}}async function ie(e){let n=M,r=await z($.post(d,{body:e,skipAuth:!0})),{token:i,refreshToken:a}=y(r);if(M!==n)throw H(i??null,a),new t.SessionSupersededError;let{done:o}=Q(`switch`),s=M;if(await o.catch(()=>void 0),M!==s)throw new t.SessionSupersededError;k().setToken(i),O(a??null);let c=b?.(r);return c==null?j():(k().setUser(c),c)}function Q(e){let{user:t,token:n}=k(),r=n!==null||t!==null||D()!==null;if((r||e!==`expired`)&&W(),k().logout(),O(null),!r)return{live:r,done:e===`switch`||P===0?N:Promise.resolve()};if(!C)return{live:r,done:Promise.resolve()};let i=U(n);P+=1;let a=(async()=>{try{await C({reason:e,user:t,token:n,api:i})}finally{--P}})();return N=a.then(()=>void 0,()=>void 0),{live:r,done:a.then(()=>void 0)}}function ae(){if(!f)return null;let e=f,{token:t,user:n}=k(),r=D();if(!g&&t===null&&n===null&&r===null)return null;let i=g?[...L]:[];return V(async()=>(await o(i,a),U(t).post(e,{body:x(r)})))}function oe(){let e=ae(),{done:t}=Q(`logout`);return e?Promise.all([e,t]).then(()=>void 0):t}async function se(){let{live:e,done:t}=Q(`expired`);await t.catch(()=>void 0),e&&S&&typeof window<`u`&&window.location.assign(S)}let $=n.createApiClient({baseURL:l,prefix:u,withCredentials:g,csrf:_,fetcher:v,getToken:A,getSessionEpoch:()=>M,refresh:X,retry:ne,onUnauthorized:Z});return{useAuthStore:w,api:$,login:re,logout:oe,refresh:()=>K(),getToken:A}}exports.createTempestAuth=c;
2
2
  //# sourceMappingURL=create-tempest-auth.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-tempest-auth.cjs","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient, SessionSupersededError } from \"../http\";\nimport type { ApiClient, CsrfOptions, RequestAuthContext, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\n/**\n * What {@link CreateTempestAuthOptions.onSessionEnd} receives about the session\n * that just ended.\n */\nexport interface TempestSessionEnd<TUser> {\n /**\n * Why it ended: `\"logout\"` for an explicit `logout()`, `\"expired\"` when the\n * client ended it on its own — the refresh failed, or the request replayed\n * after a refresh still came back `401` — and `\"switch\"` when `login()`\n * succeeded for another set of credentials while this session was live.\n */\n reason: \"logout\" | \"expired\" | \"switch\";\n /** The user of the ended session, as the store held it. */\n user: TUser | null;\n /** The access token of the ended session, or `null` when it had none. */\n token: string | null;\n /**\n * A client that sends the ended session's access token — the store has\n * already been cleared, so `auth.api` no longer does.\n *\n * Use it for the server-side half of the teardown, such as deleting this\n * browser's push subscription. It never refreshes and never ends a session:\n * a `401` here just rejects. On `\"logout\"` the token is usually still\n * valid; on `\"expired\"` the server has already refused it, so expect the\n * call to fail and keep the local half of the teardown independent of it.\n */\n api: ApiClient;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /**\n * CSRF token for every write, forwarded to `createApiClient`'s `csrf`. Off\n * by default; `true` echoes the `csrf_token` cookie as `X-CSRF-Token`.\n *\n * The pair to `withCredentials`: once the refresh token lives in a cookie,\n * the browser attaches it to a `POST /auth/refresh` that another site\n * triggers. Login and refresh carry the header too — they go out with\n * `skipAuth`, and the CSRF header does not follow auth.\n */\n csrf?: boolean | CsrfOptions;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n /**\n * Tear down per-user state when a session ends — on an explicit `logout()`,\n * when the client ends the session on its own after a failed refresh, and\n * when a successful `login()` replaces a live session. Without it, the automatic path had no place to hook into, and\n * state derived from the user (a push subscription, a persisted query\n * cache, a background-sync queue) survived into the next account.\n *\n * Order, on every path:\n *\n * 1. any refresh still in flight is superseded, so it cannot reinstall the\n * ending session's tokens;\n * 2. the store and the stored refresh token are cleared — synchronously, so\n * `isAuthenticated` is already `false` when `logout()` returns;\n * 3. this hook runs with a {@link TempestSessionEnd} whose `api` still sends\n * the ended session's access token;\n * 4. on `\"expired\"` with `redirectTo` set, the browser navigates — after the\n * hook settled, even if it threw; on `\"switch\"`, the new session is\n * installed — after the hook settled, even if it threw.\n *\n * It may be async. `logout()` resolves when it settles and rejects with what\n * it threw; on the automatic path the error is swallowed, because the\n * request that ended the session already rejects with its own `401`. It\n * runs once per session: a second `logout()`, or the other requests of a\n * burst of `401`s, find nothing left to end and skip it.\n *\n * On `\"switch\"` the hook runs only **after** the new credentials were\n * accepted, so a failed `login()` leaves the live session untouched. It runs\n * **before** the new session is installed: teardown of the previous\n * account's state (clearing a persisted cache, a background-sync queue) has\n * to finish before the new account's requests start filling them, or it\n * would wipe — or race with — the new account's data. The cost is that\n * `isAuthenticated` is `false` while the hook runs, which a route guard may\n * act on; keep the hook short. Its error is swallowed there, since the\n * login itself succeeded.\n *\n * Inside the hook, reach the backend only through `session.api`. `auth.api`\n * goes out with no token; `auth.login()` waits on the teardown in progress —\n * this hook — and never settles. Telling the hook apart from an outside\n * caller would need an async context the browser does not have, so this is\n * a documented rule, not a runtime check.\n */\n onSessionEnd?: (session: TempestSessionEnd<TUser>) => void | Promise<void>;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /**\n * End the session: supersede any refresh in flight, clear the store and the\n * stored refresh token, then run `onSessionEnd`.\n *\n * The store is cleared synchronously, before the first `await`, so callers\n * that ignore the promise see the signed-out state at once. The promise\n * resolves when `onSessionEnd` settled and rejects with its error.\n */\n logout: () => Promise<void>;\n /**\n * Refresh the access token (deduplicated across concurrent callers).\n *\n * @throws {SessionSupersededError} When the session ended or changed while\n * the refresh was in flight; its tokens were discarded.\n */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * Every refresh is bound to a **session epoch**, bumped by `logout()` and by a\n * `login()` whose credentials were accepted. A refresh that resolves after its epoch ended discards\n * what it brought back and rejects with {@link SessionSupersededError}, which\n * the client passes through without ending the new session. Before 0.77.0 a\n * refresh that was in flight during `logout()` reinstalled the old tokens —\n * and after `logout()` + `login(B)`, replaced B's token with A's while the UI\n * showed B (#435). A `401` from a request sent under an ended session is\n * refused the same way, instead of being replayed as the account signed in now.\n *\n * Refreshes are collapsed per rotation, not just per overlap: a `401` whose\n * request left with a token that has since been replaced in the same session\n * replays with the new token and refreshes nothing. Three expired requests take\n * one refresh whether their `401`s arrive together or one after another.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * await auth.logout(); // clears, then runs onSessionEnd\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n csrf,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n onSessionEnd,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n /**\n * Load the current user, without letting a `401` end the session.\n *\n * `skipAuthRetry` is what keeps this one client honest: the call is\n * authenticated, but a `401` here surfaces instead of triggering a refresh\n * and `onUnauthorized`. That was the behaviour of the throwaway client this\n * used to build per invocation, and it is the reason the preset needed\n * three clients before 0.66.0.\n */\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const user = await api.get<TUser>(mePath, { skipAuthRetry: true });\n state().setUser(user);\n return user;\n }\n\n let epoch = 0;\n let ending: Promise<void> = Promise.resolve();\n let hooksRunning = 0;\n\n /**\n * Start a new session epoch: supersede the refresh in flight and give the\n * new epoch a refresh queue of its own, so a `401` under the new session\n * never joins the old session's refresh.\n *\n * The client reads the epoch when each attempt leaves (`getSessionEpoch`),\n * which is what ties a `401` to the session that sent it — no set of\n * tokens to keep, and nothing that grows with the session's length.\n */\n function nextEpoch(): void {\n epoch += 1;\n queue = createRefreshQueue(rotate);\n }\n\n /**\n * Perform one refresh for the epoch that is current when it starts.\n *\n * Checked again after the round trip, on success and on failure alike: a\n * refresh that fails after `logout()` + `login(B)` must not reach\n * `onUnauthorized` either, or it would end B's session.\n *\n * @throws {SessionSupersededError} When the epoch changed during the call.\n */\n async function rotate(): Promise<void> {\n const started = epoch;\n let data: unknown;\n try {\n data = await api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n });\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n if (epoch !== started) throw new SessionSupersededError();\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n }\n\n let queue = createRefreshQueue(rotate);\n\n /**\n * Whether a `401` must be left alone: no refresh, no ending the session.\n *\n * Two cases, both of the current epoch: an attempt that carried no token\n * while a session is now installed (it left before the sign-in, and\n * refreshing or ending the new session for it would punish the wrong\n * session); and an attempt whose token the session has since rotated past\n * (the rotation it would trigger already happened).\n *\n * @param context - The attempt's credential.\n * @returns Whether the attempt is stale within the current session.\n */\n function staleWithinSession(context: RequestAuthContext): boolean {\n const current = getToken();\n if (current === null) return false;\n return context.token === null || context.token !== current;\n }\n\n /**\n * The `refresh` the client calls on a `401`.\n *\n * - An attempt from an ended epoch is refused rather than replayed as\n * whoever is signed in now.\n * - A token this session already rotated past: the replay just picks up the\n * new one — no second refresh.\n * - No token, while a session is now installed: the `401` surfaces as is.\n * - Otherwise: join or start this epoch's refresh.\n *\n * @param context - The credential and epoch the rejected attempt left with.\n * @throws {SessionSupersededError} When the attempt belongs to an ended\n * session, or the session changed during the refresh.\n */\n async function refreshFor(context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) {\n if (context.token === null) throw new Error(\"anonymous 401 under a live session\");\n return;\n }\n return queue();\n }\n\n /**\n * The client's `onUnauthorized`: end the session only when the `401` is the\n * current session's own.\n *\n * The replay after a refresh is checked here too — it can come back `401`\n * after the user signed out and another account signed in, and ending the\n * session then would sign the new account out.\n *\n * @param context - The credential and epoch of the attempt that failed.\n * @throws {SessionSupersededError} When that attempt belongs to an ended\n * session.\n */\n async function onUnauthorized(_response: Response, context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) return;\n await endSession();\n }\n\n /**\n * Authenticate and install the new session.\n *\n * The previous session ends only once the new credentials are accepted: a\n * login that fails leaves it, and the refresh it may have in flight,\n * untouched. When one was live, `onSessionEnd` runs with `\"switch\"` before\n * the new tokens are installed — see the option for why that order. A\n * `logout()` still tearing down is awaited the same way, so the new\n * account's state never starts before the previous one's teardown ended.\n * Never call it from inside `onSessionEnd`: it would wait on that hook.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} When a `logout()` or another `login()`\n * moved the session while this one was in flight — during its request or\n * during the teardown; the new tokens are discarded.\n */\n async function login(credentials: TCredentials): Promise<TUser | null> {\n const started = epoch;\n const data = await api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n });\n if (epoch !== started) throw new SessionSupersededError();\n const { token, refreshToken } = parseTokens(data);\n const { done } = finish(\"switch\");\n const mine = epoch;\n await done.catch(() => undefined);\n if (epoch !== mine) throw new SessionSupersededError();\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n /**\n * End the current session, synchronously up to the hook.\n *\n * The epoch moves first, so a refresh resolving between here and the hook\n * is already superseded. The hook only runs when there was a session to\n * end — a token, a stored refresh token or a user — which is what keeps a\n * burst of `401`s from running it once per request.\n *\n * With nothing left to end, the caller waits on the teardown already under\n * way (`ending`, which never rejects, so a later no-op does not inherit an\n * old error). Two callers skip that wait while a hook is running, because\n * they may be the hook itself and would wait on their own teardown forever:\n * `endSession` — a hook awaiting `auth.api` goes out tokenless, gets a\n * `401`, and lands here — and a `logout()` with no session left. `login()`\n * (`\"switch\"`) always waits: the new account's state must not start while\n * the previous one's teardown is still clearing it. A hook awaiting\n * `auth.login()` therefore never settles — misuse the option documents.\n *\n * The returned `done` is a fresh promise derived from the hook, not the one\n * `ending` holds: a `logout()` nobody awaits still surfaces the hook's error\n * as an unhandled rejection instead of losing it.\n *\n * @param reason - Whether the caller signed out, the client gave up, or a\n * login replaced the session.\n * @returns Whether a live session ended here, and a promise settling with\n * the hook.\n */\n function finish(reason: TempestSessionEnd<TUser>[\"reason\"]): {\n live: boolean;\n done: Promise<void>;\n } {\n nextEpoch();\n const { user, token } = state();\n const live = token !== null || user !== null || readRefreshToken() !== null;\n state().logout();\n writeRefreshToken(null);\n if (!live) {\n const wait = reason === \"switch\" || hooksRunning === 0;\n return { live, done: wait ? ending : Promise.resolve() };\n }\n if (!onSessionEnd) return { live, done: Promise.resolve() };\n const sessionApi = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken: () => token,\n });\n hooksRunning += 1;\n const run = (async () => {\n try {\n await onSessionEnd({ reason, user, token, api: sessionApi });\n } finally {\n hooksRunning -= 1;\n }\n })();\n ending = run.then(\n () => undefined,\n () => undefined,\n );\n return { live, done: run.then(() => undefined) };\n }\n\n function logout(): Promise<void> {\n return finish(\"logout\").done;\n }\n\n /**\n * End the session after the client gave up on it and, when `redirectTo`\n * is set, leave the page once `onSessionEnd` settled.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation. The hook is awaited before navigating because a\n * hard navigation aborts whatever request it still had in flight. Only the\n * call that ended a live session navigates; the rest of a burst of `401`s\n * waits on the same teardown, or returns at once inside a hook.\n */\n async function endSession(): Promise<void> {\n const { live, done } = finish(\"expired\");\n await done.catch(() => undefined);\n if (live && redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n getSessionEpoch: () => epoch,\n refresh: refreshFor,\n retry,\n onUnauthorized,\n });\n\n const refresh = (): Promise<void> => queue();\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":"gJAsLA,SAAS,EAAmB,EAAyD,CACjF,IAAM,EAAK,GAAQ,CAAC,EACpB,MAAO,CAAE,MAAO,EAAE,aAAc,aAAc,EAAE,aAAc,CAClE,CAyCA,SAAgB,EACZ,EACgC,CAChC,GAAM,CACF,UACA,SACA,YAAY,kBACZ,cAAc,oBACd,SACA,YAAY,eACZ,UAAU,QACV,kBAAkB,GAClB,OACA,UACA,cAAc,EACd,YACA,cAAe,GAAQ,EAAK,CAAE,cAAe,CAAG,EAAI,IAAA,GACpD,QACA,aACA,gBACA,EAEE,EAAe,EAAA,gBAAuB,CAAE,KAAM,EAAW,SAAQ,CAAC,EAClE,EAAa,GAAG,EAAU,UAEhC,SAAS,GAA8B,CAEnC,OADI,OAAO,OAAW,IAAoB,KACnC,IAAY,UAAY,OAAO,eAAiB,OAAO,YAClE,CACA,SAAS,GAAkC,CACvC,OAAO,EAAY,CAAC,EAAE,QAAQ,CAAU,GAAK,IACjD,CACA,SAAS,EAAkB,EAA4B,CACnD,IAAM,EAAI,EAA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ACA,IAAA,EACV,EACO,CAAE,OAAM,KAAM,EAAI,SAAW,IAAA,EAAS,CAAE,CACnD,CAEA,SAAS,GAAwB,CAC7B,OAAO,EAAO,QAAQ,CAAC,CAAC,IAC5B,CAaA,eAAe,GAA4B,CACvC,GAAM,CAAE,OAAM,QAAS,EAAO,SAAS,EACvC,MAAM,EAAK,UAAY,IAAA,EAAS,EAC5B,GAAQ,GAAc,OAAO,OAAW,KACxC,OAAO,SAAS,OAAO,CAAU,CAEzC,CAEA,IAAM,EAAM,EAAA,gBAAgB,CACxB,UACA,SACA,kBACA,OACA,UACA,WACA,oBAAuB,EACvB,QAAS,EACT,QACA,gBACJ,CAAC,EAID,MAAO,CAAE,eAAc,MAAK,QAAO,SAAQ,YAFN,EAAM,EAES,UAAS,CACjE"}
1
+ {"version":3,"file":"create-tempest-auth.cjs","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient, SessionSupersededError } from \"../http\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport type { ApiClient, CsrfOptions, RequestAuthContext, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\n/**\n * What {@link CreateTempestAuthOptions.onSessionEnd} receives about the session\n * that just ended.\n */\nexport interface TempestSessionEnd<TUser> {\n /**\n * Why it ended: `\"logout\"` for an explicit `logout()`, `\"expired\"` when the\n * client ended it on its own — the refresh failed, or the request replayed\n * after a refresh still came back `401` — and `\"switch\"` when `login()`\n * succeeded for another set of credentials while this session was live.\n */\n reason: \"logout\" | \"expired\" | \"switch\";\n /** The user of the ended session, as the store held it. */\n user: TUser | null;\n /** The access token of the ended session, or `null` when it had none. */\n token: string | null;\n /**\n * A client that sends the ended session's access token — the store has\n * already been cleared, so `auth.api` no longer does.\n *\n * Use it for the server-side half of the teardown, such as deleting this\n * browser's push subscription. It never refreshes and never ends a session:\n * a `401` here just rejects. On `\"logout\"` the token is usually still\n * valid; on `\"expired\"` the server has already refused it, so expect the\n * call to fail and keep the local half of the teardown independent of it.\n */\n api: ApiClient;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /**\n * Server-side logout route (`POST`), called by an explicit `logout()` to\n * revoke the ending session. Off by default.\n *\n * `logout()` alone only clears client state, and an HttpOnly refresh\n * cookie is out of its reach: with `withCredentials`, the cookie stays\n * redeemable until the backend revokes it. The tempest-fastapi-sdk mounts\n * `POST /auth/logout` (`204`, idempotent) when it stores refresh tokens in\n * the database — at `/auth/cookie/logout` when it delivers tokens both in\n * the body and in cookies — and stateless refresh tokens cannot be\n * revoked, so the route is absent there.\n *\n * The request goes out through the ended session's client (the same one\n * `onSessionEnd` receives, carrying its access token), with the body that\n * `refreshBody` builds from the refresh token stored before the clear:\n * `{ refresh_token }` in body mode, no body in cookie mode, which is what\n * that route reads. The local clear does not wait on it — `isAuthenticated`\n * is still `false` when `logout()` returns — but the promise `logout()`\n * returns does, so a navigation after `await auth.logout()` does not abort\n * it. A failure (network, `4xx`, `5xx`) is swallowed: revocation is\n * best-effort and never keeps the user signed in. A `login()` started\n * while it is in flight waits for it, because the logout response clears\n * the auth cookies and would otherwise clear the new account's.\n *\n * Only an explicit `logout()` revokes. On `\"switch\"` the cookie jar already\n * holds the new account's cookie, and on `\"expired\"` the server has already\n * refused the session.\n *\n * Overlapping sign-outs each send their own revocation, and `login()` waits\n * for all of them — at most 10 seconds, so one that\n * never answers delays the sign-in instead of blocking it. In cookie mode,\n * a revocation also waits (within the same bound) for the login and\n * refresh responses that were in flight when `logout()` ran: the server\n * sets the ended session's cookie when that response arrives, and a\n * revocation sent earlier would leave it behind. In body mode, the refresh\n * token such a superseded response brings back is revoked on its own.\n */\n logoutPath?: string;\n /**\n * Called with the error when a `logoutPath` revocation fails — network\n * failure, `4xx` or `5xx`. `logout()` still resolves, since the local\n * sign-out already happened; this is where the app logs or retries. A dev\n * build also warns in the console. Errors it throws are swallowed.\n */\n onLogoutError?: (error: unknown) => void;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /**\n * CSRF token for every write, forwarded to `createApiClient`'s `csrf`. Off\n * by default; `true` echoes the `csrf_token` cookie as `X-CSRF-Token`.\n *\n * The pair to `withCredentials`: once the refresh token lives in a cookie,\n * the browser attaches it to a `POST /auth/refresh` that another site\n * triggers. Login and refresh carry the header too — they go out with\n * `skipAuth`, and the CSRF header does not follow auth.\n */\n csrf?: boolean | CsrfOptions;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n /**\n * Tear down per-user state when a session ends — on an explicit `logout()`,\n * when the client ends the session on its own after a failed refresh, and\n * when a successful `login()` replaces a live session. Without it, the automatic path had no place to hook into, and\n * state derived from the user (a push subscription, a persisted query\n * cache, a background-sync queue) survived into the next account.\n *\n * Order, on every path:\n *\n * 1. any refresh still in flight is superseded, so it cannot reinstall the\n * ending session's tokens;\n * 2. the store and the stored refresh token are cleared — synchronously, so\n * `isAuthenticated` is already `false` when `logout()` returns;\n * 3. this hook runs with a {@link TempestSessionEnd} whose `api` still sends\n * the ended session's access token;\n * 4. on `\"expired\"` with `redirectTo` set, the browser navigates — after the\n * hook settled, even if it threw; on `\"switch\"`, the new session is\n * installed — after the hook settled, even if it threw.\n *\n * It may be async. `logout()` resolves when it settles and rejects with what\n * it threw; on the automatic path the error is swallowed, because the\n * request that ended the session already rejects with its own `401`. It\n * runs once per session: a second `logout()`, or the other requests of a\n * burst of `401`s, find nothing left to end and skip it.\n *\n * On `\"switch\"` the hook runs only **after** the new credentials were\n * accepted, so a failed `login()` leaves the live session untouched. It runs\n * **before** the new session is installed: teardown of the previous\n * account's state (clearing a persisted cache, a background-sync queue) has\n * to finish before the new account's requests start filling them, or it\n * would wipe — or race with — the new account's data. The cost is that\n * `isAuthenticated` is `false` while the hook runs, which a route guard may\n * act on; keep the hook short. Its error is swallowed there, since the\n * login itself succeeded.\n *\n * Inside the hook, reach the backend only through `session.api`. `auth.api`\n * goes out with no token; `auth.login()` waits on the teardown in progress —\n * this hook — and never settles. Telling the hook apart from an outside\n * caller would need an async context the browser does not have, so this is\n * a documented rule, not a runtime check.\n */\n onSessionEnd?: (session: TempestSessionEnd<TUser>) => void | Promise<void>;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /**\n * End the session: supersede any refresh in flight, clear the store and the\n * stored refresh token, then run `onSessionEnd`.\n *\n * The store is cleared synchronously, before the first `await`, so callers\n * that ignore the promise see the signed-out state at once. The promise\n * resolves when `onSessionEnd` settled — and, with `logoutPath`, when the\n * server-side revocation settled too — and rejects with the hook's error;\n * a failed revocation never rejects it.\n */\n logout: () => Promise<void>;\n /**\n * Refresh the access token (deduplicated across concurrent callers).\n *\n * @throws {SessionSupersededError} When the session ended or changed while\n * the refresh was in flight; its tokens were discarded.\n */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\n/**\n * How long `login()` waits for pending `logoutPath` revocations, and how long a\n * cookie-mode revocation waits for the login or refresh responses still in\n * flight when `logout()` ran, before going ahead anyway.\n *\n * A bound, not a guess at latency: a fetcher that ignores abort, or a backend\n * that never answers, would otherwise leave the next `login()` waiting forever.\n * Ten seconds is past any healthy round trip and short enough that a stuck\n * revocation costs a slow sign-in, not a dead one.\n */\nconst LOGOUT_REVOCATION_WAIT_MS = 10_000;\n\n/**\n * Wait until every promise settled, or until `ms` passed, whichever is first.\n *\n * @param pending - What to wait for; rejections count as settled.\n * @param ms - The bound.\n * @returns A promise that always resolves.\n */\nfunction settleWithin(pending: readonly Promise<unknown>[], ms: number): Promise<void> {\n if (pending.length === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n void Promise.allSettled(pending).then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * Every refresh is bound to a **session epoch**, bumped by `logout()` and by a\n * `login()` whose credentials were accepted. A refresh that resolves after its epoch ended discards\n * what it brought back and rejects with {@link SessionSupersededError}, which\n * the client passes through without ending the new session. Before 0.77.0 a\n * refresh that was in flight during `logout()` reinstalled the old tokens —\n * and after `logout()` + `login(B)`, replaced B's token with A's while the UI\n * showed B (#435). A `401` from a request sent under an ended session is\n * refused the same way, instead of being replayed as the account signed in now.\n *\n * A `401` from a request that carried no token, while no session is installed,\n * surfaces without a refresh: in cookie mode that refresh would be answered by\n * the HttpOnly cookie `logout()` cannot clear, signing the previous account\n * back in (#474). With a `login()` in flight, that `401` waits for it and\n * replays with the token it installed, or surfaces when it failed — still\n * without a refresh (#496). Restore a session at boot with an explicit\n * `refresh()`, and pass `logoutPath` so the backend revokes the cookie:\n * without a working revocation, that boot `refresh()` restores the previous\n * account for whoever uses the browser next.\n *\n * Refreshes are collapsed per rotation, not just per overlap: a `401` whose\n * request left with a token that has since been replaced in the same session\n * replays with the new token and refreshes nothing. Three expired requests take\n * one refresh whether their `401`s arrive together or one after another.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * await auth.logout(); // clears, then runs onSessionEnd\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n logoutPath,\n onLogoutError,\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n csrf,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n onSessionEnd,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n /**\n * Load the current user, without letting a `401` end the session.\n *\n * `skipAuthRetry` is what keeps this one client honest: the call is\n * authenticated, but a `401` here surfaces instead of triggering a refresh\n * and `onUnauthorized`. That was the behaviour of the throwaway client this\n * used to build per invocation, and it is the reason the preset needed\n * three clients before 0.66.0.\n *\n * Bound to the epoch current when the request leaves, like `rotate()`: a\n * profile that resolves after `logout()` — or after `logout()` +\n * `login(B)` — is discarded instead of written next to B's token, and the\n * `login()` that asked for it rejects as superseded (#473).\n *\n * @throws {SessionSupersededError} When the epoch changed while the\n * request was in flight, on success and on failure alike.\n */\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const started = epoch;\n let user: TUser;\n try {\n user = await api.get<TUser>(mePath, { skipAuthRetry: true });\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n if (epoch !== started) throw new SessionSupersededError();\n state().setUser(user);\n return user;\n }\n\n let epoch = 0;\n let ending: Promise<void> = Promise.resolve();\n let hooksRunning = 0;\n const loginsInFlight = new Set<Promise<unknown>>();\n const revocations = new Set<Promise<void>>();\n const credentialRequests = new Set<Promise<unknown>>();\n const rotatingEpochs = new Set<number>();\n\n /**\n * Track a login or refresh request until it settles, so a cookie-mode\n * revocation can wait for the response that sets the cookie it revokes.\n *\n * @param request - The request in flight.\n * @returns The same request.\n */\n function trackCredentialRequest<T>(request: Promise<T>): Promise<T> {\n const settled = request.then(\n () => undefined,\n () => undefined,\n );\n credentialRequests.add(settled);\n void settled.then(() => credentialRequests.delete(settled));\n return request;\n }\n\n /**\n * Surface a failed revocation: `onLogoutError`, plus a console warning in a\n * dev build.\n *\n * @param error - What the revocation rejected with.\n */\n function reportLogoutError(error: unknown): void {\n if (isDevBuild()) {\n console.warn(\n \"[tempest-react-sdk] createTempestAuth: logoutPath revocation failed\",\n error,\n );\n }\n try {\n onLogoutError?.(error);\n } catch {\n return;\n }\n }\n\n /**\n * Send one `logoutPath` revocation and track it until it settles. Never\n * rejects.\n *\n * @param build - Produces the request, after whatever wait it needs.\n * @returns A promise settling when the revocation settled.\n */\n function trackRevocation(build: () => Promise<unknown>): Promise<void> {\n const tracked = (async () => {\n try {\n await build();\n } catch (error) {\n reportLogoutError(error);\n }\n })();\n revocations.add(tracked);\n void tracked.then(() => revocations.delete(tracked));\n return tracked;\n }\n\n /**\n * Revoke, in body mode, the refresh token a superseded login or refresh\n * brought back. Nobody can use it — the client discarded it — but it would\n * stay valid on the server until it expires.\n *\n * Cookie mode is left to `revoke()`, which waits for these responses\n * instead: re-sending a cookie revocation here could carry whichever\n * account's cookie the browser holds by then.\n *\n * @param token - The superseded response's access token.\n * @param refreshToken - The superseded response's refresh token.\n */\n function revokeDiscarded(token: string | null, refreshToken: string | undefined): void {\n if (!logoutPath || withCredentials || !refreshToken) return;\n void trackRevocation(() =>\n endedSessionApi(token).post<unknown>(logoutPath, {\n body: refreshBody(refreshToken),\n }),\n );\n }\n\n /**\n * A client that sends an ended session's access token, and never refreshes\n * or ends a session: a `401` there just rejects.\n *\n * @param token - The ended session's access token.\n * @returns The client `onSessionEnd` and the `logoutPath` call go through.\n */\n function endedSessionApi(token: string | null): ApiClient {\n return createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken: () => token,\n });\n }\n\n /**\n * Start a new session epoch: supersede the refresh in flight and give the\n * new epoch a refresh queue of its own, so a `401` under the new session\n * never joins the old session's refresh.\n *\n * The client reads the epoch when each attempt leaves (`getSessionEpoch`),\n * which is what ties a `401` to the session that sent it — no set of\n * tokens to keep, and nothing that grows with the session's length.\n */\n function nextEpoch(): void {\n epoch += 1;\n queue = createRefreshQueue(rotate);\n }\n\n /**\n * Perform one refresh for the epoch that is current when it starts.\n *\n * Checked again after the round trip, on success and on failure alike: a\n * refresh that fails after `logout()` + `login(B)` must not reach\n * `onUnauthorized` either, or it would end B's session.\n *\n * @throws {SessionSupersededError} When the epoch changed during the call.\n */\n async function rotate(): Promise<void> {\n const started = epoch;\n rotatingEpochs.add(started);\n try {\n let data: unknown;\n try {\n data = await trackCredentialRequest(\n api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n }),\n );\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n } finally {\n rotatingEpochs.delete(started);\n }\n }\n\n let queue = createRefreshQueue(rotate);\n\n /**\n * Whether a `401` must be left alone: no refresh, no ending the session.\n *\n * Two cases, both of the current epoch: an attempt that carried no token\n * while a session is now installed (it left before the sign-in, and\n * refreshing or ending the new session for it would punish the wrong\n * session); and an attempt whose token the session has since rotated past\n * (the rotation it would trigger already happened).\n *\n * @param context - The attempt's credential.\n * @returns Whether the attempt is stale within the current session.\n */\n function staleWithinSession(context: RequestAuthContext): boolean {\n const current = getToken();\n if (current === null) return false;\n return context.token === null || context.token !== current;\n }\n\n /**\n * Whether nothing could make a tokenless `401` worth a refresh: no access\n * token and no stored refresh token.\n *\n * With `withCredentials`, the refresh would otherwise be answered by an\n * HttpOnly cookie the client cannot see or clear — after `logout()`, that\n * signed the previous account back in for whoever used the browser next\n * (#474). A `login()` in flight does not count as a session either: the\n * cookie a refresh would present during it is still the ended account's\n * (#496). Restoring a session from the cookie is an explicit `refresh()`,\n * typically at boot, which this does not touch.\n *\n * @returns Whether no session is installed.\n */\n function signedOut(): boolean {\n return getToken() === null && readRefreshToken() === null;\n }\n\n /**\n * Settle a tokenless `401` that arrived with no session installed while a\n * `login()` is in flight: wait for every login in flight, then let the\n * request replay when one of them installed a token.\n *\n * No refresh is sent. In cookie mode one would present whatever cookie\n * the browser holds — after `logout()` without a working `logoutPath`,\n * the previous account's: a failed login then left the client signed in\n * as that account, and a successful one could have its cookie overwritten\n * by the refresh's late `Set-Cookie` (#496).\n *\n * Skipped while an `onSessionEnd` hook runs: an account switch waits on\n * that hook, so a hook awaiting `auth.api` would wait on itself.\n *\n * @throws {Error} When no login is in flight, a hook is running, or every\n * login settled without installing a token — the `401` surfaces as is.\n */\n async function awaitLogins(): Promise<void> {\n if (loginsInFlight.size > 0 && hooksRunning === 0) {\n await Promise.allSettled([...loginsInFlight]);\n if (getToken() !== null) return;\n }\n throw new Error(\"anonymous 401 with no session\");\n }\n\n /**\n * The `refresh` the client calls on a `401`.\n *\n * - An attempt from an ended epoch is refused rather than replayed as\n * whoever is signed in now.\n * - A token this session already rotated past: the replay just picks up the\n * new one — no second refresh.\n * - No token, while a session is now installed: the `401` surfaces as is.\n * - No token, and no session installed: joins this epoch's refresh when\n * one is already in flight — the boot `refresh()` restoring a session\n * from the cookie, which the request then replays under; otherwise waits\n * for a `login()` in flight and replays with its token, see\n * `awaitLogins`; otherwise surfaces the `401` as is, see `signedOut`.\n * - Otherwise: join or start this epoch's refresh.\n *\n * @param context - The credential and epoch the rejected attempt left with.\n * @throws {SessionSupersededError} When the attempt belongs to an ended\n * session, or the session changed during the refresh.\n */\n async function refreshFor(context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) {\n if (context.token === null) throw new Error(\"anonymous 401 under a live session\");\n return;\n }\n if (context.token === null && signedOut()) {\n if (rotatingEpochs.has(epoch)) return queue();\n return awaitLogins();\n }\n return queue();\n }\n\n /**\n * The client's `onUnauthorized`: end the session only when the `401` is the\n * current session's own.\n *\n * The replay after a refresh is checked here too — it can come back `401`\n * after the user signed out and another account signed in, and ending the\n * session then would sign the new account out. A tokenless `401` with no\n * session installed ends nothing either: there is no session to end, and\n * ending \"nothing\" used to move the epoch and supersede the boot\n * `refresh()` in flight.\n *\n * @param context - The credential and epoch of the attempt that failed.\n * @throws {SessionSupersededError} When that attempt belongs to an ended\n * session.\n */\n async function onUnauthorized(_response: Response, context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) return;\n if (context.token === null && signedOut()) return;\n await endSession();\n }\n\n /**\n * Authenticate and install the new session.\n *\n * The previous session ends only once the new credentials are accepted: a\n * login that fails leaves it, and the refresh it may have in flight,\n * untouched. When one was live, `onSessionEnd` runs with `\"switch\"` before\n * the new tokens are installed — see the option for why that order. A\n * `logout()` still tearing down is awaited the same way, so the new\n * account's state never starts before the previous one's teardown ended.\n * Never call it from inside `onSessionEnd`: it would wait on that hook.\n * Every `logoutPath` revocation still in flight is awaited before the\n * request leaves — at most {@link LOGOUT_REVOCATION_WAIT_MS} — so a\n * cookie-clearing response cannot land after the new account's cookies.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} When a `logout()` or another `login()`\n * moved the session while this one was in flight — during its request,\n * during the teardown or while `mePath` was loading the user; the new\n * tokens, or the user, are discarded.\n */\n async function login(credentials: TCredentials): Promise<TUser | null> {\n if (revocations.size > 0) await settleWithin([...revocations], LOGOUT_REVOCATION_WAIT_MS);\n const run = signIn(credentials);\n loginsInFlight.add(run);\n try {\n return await run;\n } finally {\n loginsInFlight.delete(run);\n }\n }\n\n /**\n * The body of `login()`, tracked in `loginsInFlight` by its caller so a\n * tokenless `401` during the sign-in waits for it and replays with the\n * token it installs, see `awaitLogins`. Tracking starts only after a\n * pending revocation settled.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} See `login()`.\n */\n async function signIn(credentials: TCredentials): Promise<TUser | null> {\n const started = epoch;\n const data = await trackCredentialRequest(\n api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n }),\n );\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n const { done } = finish(\"switch\");\n const mine = epoch;\n await done.catch(() => undefined);\n if (epoch !== mine) throw new SessionSupersededError();\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n /**\n * End the current session, synchronously up to the hook.\n *\n * The epoch moves first, so a refresh resolving between here and the hook\n * is already superseded. The hook only runs when there was a session to\n * end — a token, a stored refresh token or a user — which is what keeps a\n * burst of `401`s from running it once per request.\n *\n * With nothing left to end, the caller waits on the teardown already under\n * way (`ending`, which never rejects, so a later no-op does not inherit an\n * old error). Two callers skip that wait while a hook is running, because\n * they may be the hook itself and would wait on their own teardown forever:\n * `endSession` — a hook awaiting `auth.api` goes out tokenless, gets a\n * `401`, and lands here — and a `logout()` with no session left. `login()`\n * (`\"switch\"`) always waits: the new account's state must not start while\n * the previous one's teardown is still clearing it. A hook awaiting\n * `auth.login()` therefore never settles — misuse the option documents.\n *\n * `\"expired\"` with nothing live leaves the epoch alone: there is nothing to\n * supersede but a refresh with no session behind it — the boot `refresh()`\n * restoring one from the cookie — and moving the epoch would throw that\n * away. `logout()` and `login()` always move it, since they must supersede\n * such a refresh.\n *\n * The returned `done` is a fresh promise derived from the hook, not the one\n * `ending` holds: a `logout()` nobody awaits still surfaces the hook's error\n * as an unhandled rejection instead of losing it.\n *\n * @param reason - Whether the caller signed out, the client gave up, or a\n * login replaced the session.\n * @returns Whether a live session ended here, and a promise settling with\n * the hook.\n */\n function finish(reason: TempestSessionEnd<TUser>[\"reason\"]): {\n live: boolean;\n done: Promise<void>;\n } {\n const { user, token } = state();\n const live = token !== null || user !== null || readRefreshToken() !== null;\n if (live || reason !== \"expired\") nextEpoch();\n state().logout();\n writeRefreshToken(null);\n if (!live) {\n const wait = reason === \"switch\" || hooksRunning === 0;\n return { live, done: wait ? ending : Promise.resolve() };\n }\n if (!onSessionEnd) return { live, done: Promise.resolve() };\n const sessionApi = endedSessionApi(token);\n hooksRunning += 1;\n const run = (async () => {\n try {\n await onSessionEnd({ reason, user, token, api: sessionApi });\n } finally {\n hooksRunning -= 1;\n }\n })();\n ending = run.then(\n () => undefined,\n () => undefined,\n );\n return { live, done: run.then(() => undefined) };\n }\n\n /**\n * Send the `logoutPath` revocation for the session about to end, with the\n * credentials it holds now — read before `finish` clears them.\n *\n * Skipped without `logoutPath`, and in body mode when there is nothing to\n * revoke; in cookie mode it always goes out, since the cookie it revokes is\n * invisible to the client. Never rejects.\n *\n * In cookie mode it first waits — at most\n * {@link LOGOUT_REVOCATION_WAIT_MS} — for the login and refresh responses\n * in flight right now: each one sets a cookie for the session this\n * `logout()` ends, and a revocation that left before it would leave that\n * cookie behind.\n *\n * @returns A promise settling when the revocation settled, or null when\n * none was sent.\n */\n function revoke(): Promise<void> | null {\n if (!logoutPath) return null;\n const path = logoutPath;\n const { token, user } = state();\n const refreshToken = readRefreshToken();\n if (!withCredentials && token === null && user === null && refreshToken === null) {\n return null;\n }\n const inFlight = withCredentials ? [...credentialRequests] : [];\n return trackRevocation(async () => {\n await settleWithin(inFlight, LOGOUT_REVOCATION_WAIT_MS);\n return endedSessionApi(token).post<unknown>(path, { body: refreshBody(refreshToken) });\n });\n }\n\n function logout(): Promise<void> {\n const revocation = revoke();\n const { done } = finish(\"logout\");\n if (!revocation) return done;\n return Promise.all([revocation, done]).then(() => undefined);\n }\n\n /**\n * End the session after the client gave up on it and, when `redirectTo`\n * is set, leave the page once `onSessionEnd` settled.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation. The hook is awaited before navigating because a\n * hard navigation aborts whatever request it still had in flight. Only the\n * call that ended a live session navigates; the rest of a burst of `401`s\n * waits on the same teardown, or returns at once inside a hook.\n */\n async function endSession(): Promise<void> {\n const { live, done } = finish(\"expired\");\n await done.catch(() => undefined);\n if (live && redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n getSessionEpoch: () => epoch,\n refresh: refreshFor,\n retry,\n onUnauthorized,\n });\n\n const refresh = (): Promise<void> => queue();\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":"mLAgPA,IAAM,EAA4B,IASlC,SAAS,EAAa,EAAsC,EAA2B,CAEnF,OADI,EAAQ,SAAW,EAAU,QAAQ,QAAQ,EAC1C,IAAI,QAAe,GAAY,CAClC,IAAM,EAAQ,WAAW,EAAS,CAAE,EACpC,QAAa,WAAW,CAAO,CAAC,CAAC,SAAW,CACxC,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