tempest-react-sdk 0.76.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.
- package/README.md +2 -2
- package/bin/create-tempest-app.e2e.test.mjs +112 -0
- package/bin/create-tempest-app.mjs +69 -28
- package/bin/lib/alias/collect.mjs +20 -3
- package/bin/lib/alias/index.mjs +12 -1
- package/bin/lib/alias/index.test.mjs +24 -0
- package/bin/lib/component/generate.mjs +191 -0
- package/bin/lib/component/generate.test.mjs +336 -0
- package/bin/lib/css/analyze.test.mjs +21 -1
- package/bin/lib/css/collect.mjs +14 -0
- package/bin/lib/css/extract.mjs +63 -5
- package/bin/lib/css/extract.test.mjs +110 -1
- package/bin/lib/css/fix.e2e.test.mjs +50 -0
- package/bin/lib/css/index.mjs +6 -1
- package/bin/lib/fs/contain.mjs +50 -0
- package/bin/lib/icons/generate.mjs +28 -3
- package/bin/lib/icons/generate.test.mjs +57 -1
- package/bin/lib/openapi/escape.mjs +224 -0
- package/bin/lib/openapi/generate.encode.test.mjs +120 -0
- package/bin/lib/openapi/generate.hostile.test.mjs +621 -0
- package/bin/lib/openapi/generate.mjs +129 -18
- package/bin/lib/openapi/generate.test.mjs +7 -2
- package/bin/lib/openapi/schema-to-zod.mjs +43 -4
- package/bin/tempest-gen.test.mjs +188 -0
- package/bin/tempest.mjs +263 -6
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +203 -58
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/refresh-queue.cjs +1 -1
- package/dist/auth/refresh-queue.cjs.map +1 -1
- package/dist/auth/refresh-queue.js +13 -6
- package/dist/auth/refresh-queue.js.map +1 -1
- package/dist/br/pix.cjs +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js +85 -72
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +19 -4
- package/dist/components/Chat/ChatAttachments.cjs +1 -1
- package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
- package/dist/components/Chat/ChatAttachments.js +46 -38
- package/dist/components/Chat/ChatAttachments.js.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/CodeBlock/tokenize.cjs +1 -1
- package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
- package/dist/components/CodeBlock/tokenize.js +54 -25
- package/dist/components/CodeBlock/tokenize.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +7 -5
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +171 -90
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Toast/Toast.module.cjs +1 -1
- package/dist/components/Toast/Toast.module.cjs.map +1 -1
- package/dist/components/Toast/Toast.module.js +7 -3
- package/dist/components/Toast/Toast.module.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js +77 -51
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/data/create-data-provider.cjs +1 -1
- package/dist/data/create-data-provider.cjs.map +1 -1
- package/dist/data/create-data-provider.js +32 -21
- package/dist/data/create-data-provider.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +81 -73
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +39 -35
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +141 -105
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +5 -6
- package/dist/http/retry.js.map +1 -1
- package/dist/oauth/callback.cjs +2 -0
- package/dist/oauth/callback.cjs.map +1 -0
- package/dist/oauth/callback.js +42 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/use-oauth-callback.cjs +1 -1
- package/dist/oauth/use-oauth-callback.cjs.map +1 -1
- package/dist/oauth/use-oauth-callback.js +13 -20
- package/dist/oauth/use-oauth-callback.js.map +1 -1
- package/dist/push/use-push-subscription.cjs +1 -1
- package/dist/push/use-push-subscription.cjs.map +1 -1
- package/dist/push/use-push-subscription.js +42 -42
- package/dist/push/use-push-subscription.js.map +1 -1
- package/dist/push/web-push-client.cjs +1 -1
- package/dist/push/web-push-client.cjs.map +1 -1
- package/dist/push/web-push-client.js +23 -3
- package/dist/push/web-push-client.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +68 -23
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/styles/component/Toast.css +6 -1
- package/dist/styles/feedback.css +6 -1
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +272 -60
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache-inspect.cjs.map +1 -1
- package/dist/sw/cache-inspect.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +91 -64
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw/credential-headers.cjs +2 -0
- package/dist/sw/credential-headers.cjs.map +1 -0
- package/dist/sw/credential-headers.js +17 -0
- package/dist/sw/credential-headers.js.map +1 -0
- package/dist/sw/session-data.cjs +2 -0
- package/dist/sw/session-data.cjs.map +1 -0
- package/dist/sw/session-data.js +17 -0
- package/dist/sw/session-data.js.map +1 -0
- package/dist/sw.cjs +1 -1
- package/dist/sw.d.ts +309 -23
- package/dist/sw.js +7 -5
- package/dist/telemetry/app-error-queue.cjs +1 -1
- package/dist/telemetry/app-error-queue.cjs.map +1 -1
- package/dist/telemetry/app-error-queue.js +19 -14
- package/dist/telemetry/app-error-queue.js.map +1 -1
- package/dist/telemetry/app-error-reporter.cjs +1 -1
- package/dist/telemetry/app-error-reporter.cjs.map +1 -1
- package/dist/telemetry/app-error-reporter.js +75 -34
- package/dist/telemetry/app-error-reporter.js.map +1 -1
- package/dist/telemetry/app-error-transport.cjs +1 -1
- package/dist/telemetry/app-error-transport.cjs.map +1 -1
- package/dist/telemetry/app-error-transport.js +16 -3
- package/dist/telemetry/app-error-transport.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +1183 -64
- package/dist/tempest-react-sdk.js +160 -156
- package/dist/utils/csv.cjs +3 -3
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js +18 -14
- package/dist/utils/csv.js.map +1 -1
- package/dist/utils/owner-fingerprint.cjs +2 -0
- package/dist/utils/owner-fingerprint.cjs.map +1 -0
- package/dist/utils/owner-fingerprint.js +18 -0
- package/dist/utils/owner-fingerprint.js.map +1 -0
- package/dist/utils/safe-url.cjs +2 -0
- package/dist/utils/safe-url.cjs.map +1 -0
- package/dist/utils/safe-url.js +39 -0
- package/dist/utils/safe-url.js.map +1 -0
- package/dist/vite/tempest-csp.cjs +2 -2
- package/dist/vite/tempest-csp.cjs.map +1 -1
- package/dist/vite/tempest-csp.js +130 -64
- package/dist/vite/tempest-csp.js.map +1 -1
- package/dist/vite.d.ts +23 -5
- package/dist/webrtc/peer-link.cjs +1 -1
- package/dist/webrtc/peer-link.cjs.map +1 -1
- package/dist/webrtc/peer-link.js +2 -10
- package/dist/webrtc/peer-link.js.map +1 -1
- package/dist/webrtc/peer-mesh.cjs +1 -1
- package/dist/webrtc/peer-mesh.cjs.map +1 -1
- package/dist/webrtc/peer-mesh.js +110 -72
- package/dist/webrtc/peer-mesh.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/src/pwa.tsx +22 -0
- package/template-pwa/src/sw.ts +27 -14
- package/dist/components/Markdown/markdown-url.cjs +0 -2
- package/dist/components/Markdown/markdown-url.cjs.map +0 -1
- package/dist/components/Markdown/markdown-url.js +0 -28
- package/dist/components/Markdown/markdown-url.js.map +0 -1
package/bin/tempest.mjs
CHANGED
|
@@ -6,16 +6,25 @@
|
|
|
6
6
|
// tempest lint [paths…] run ESLint (report only)
|
|
7
7
|
// tempest fix [paths…] alias imports (../ → @/) + ESLint --fix + Prettier
|
|
8
8
|
// tempest format [paths…] Prettier --write
|
|
9
|
+
// tempest gen <api|icons|component> … code generators (`new component` = alias)
|
|
9
10
|
// tempest --help | --version
|
|
10
11
|
import { spawnSync } from "node:child_process";
|
|
11
12
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
12
13
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
13
|
-
import { dirname, join, resolve } from "node:path";
|
|
14
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
14
15
|
import { fileURLToPath } from "node:url";
|
|
15
16
|
import { aliasImports } from "./lib/alias/index.mjs";
|
|
16
17
|
import { describeTypeScript, loadTypeScript } from "./lib/alias/typescript.mjs";
|
|
17
18
|
import { readTsconfig } from "./lib/alias/tsconfig.mjs";
|
|
18
|
-
import {
|
|
19
|
+
import { componentFiles } from "./lib/component/generate.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";
|
|
19
28
|
import { analyzeDesign } from "./lib/design/index.mjs";
|
|
20
29
|
import { checkLucide } from "./lib/doctor/lucide.mjs";
|
|
21
30
|
import { generateRegistry, loadIconTables } from "./lib/icons/generate.mjs";
|
|
@@ -1050,6 +1059,7 @@ function reportAlias(result, dryRun) {
|
|
|
1050
1059
|
for (const err of result.errors) {
|
|
1051
1060
|
console.log(` ${c.red}✗ ${err.path}${c.reset} ${c.dim}${err.message}${c.reset}`);
|
|
1052
1061
|
}
|
|
1062
|
+
reportOutside(result.outside ?? 0);
|
|
1053
1063
|
if (!result.total) {
|
|
1054
1064
|
console.log(` ${c.dim}nothing to convert${c.reset}`);
|
|
1055
1065
|
return;
|
|
@@ -1060,6 +1070,22 @@ function reportAlias(result, dryRun) {
|
|
|
1060
1070
|
);
|
|
1061
1071
|
}
|
|
1062
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
|
+
|
|
1063
1089
|
/** Prefix for a finding line: red for a browser-visible defect, yellow otherwise. */
|
|
1064
1090
|
function severityMark(severity) {
|
|
1065
1091
|
if (severity === "error") return `${c.red}✗${c.reset}`;
|
|
@@ -1096,6 +1122,7 @@ function cssPass({ targets, dryRun, extract = false, target, prefix }) {
|
|
|
1096
1122
|
);
|
|
1097
1123
|
return 1;
|
|
1098
1124
|
}
|
|
1125
|
+
reportOutside(analysis.skipped.filter((s) => s.reason === OUTSIDE_PROJECT).length);
|
|
1099
1126
|
if (analysis.stats.files === 0) {
|
|
1100
1127
|
console.log(` ${c.dim}no stylesheets found${c.reset}`);
|
|
1101
1128
|
return 0;
|
|
@@ -1294,12 +1321,29 @@ async function genApi(args) {
|
|
|
1294
1321
|
return 1;
|
|
1295
1322
|
}
|
|
1296
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
|
+
}
|
|
1297
1331
|
console.log(`${c.dim}→ loading ${source}${c.reset}`);
|
|
1298
1332
|
const doc = await loadSpec(source);
|
|
1299
1333
|
const { files, tags } = generate(doc);
|
|
1300
1334
|
|
|
1301
|
-
|
|
1302
|
-
|
|
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) {
|
|
1303
1347
|
await mkdir(dirname(dest), { recursive: true });
|
|
1304
1348
|
await writeFile(dest, contents);
|
|
1305
1349
|
}
|
|
@@ -1341,6 +1385,12 @@ async function genIcons(args) {
|
|
|
1341
1385
|
const dirIndex = args.indexOf("--dir");
|
|
1342
1386
|
const dirRel = dirIndex >= 0 && args[dirIndex + 1] ? args[dirIndex + 1] : "src";
|
|
1343
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
|
+
}
|
|
1344
1394
|
|
|
1345
1395
|
let tables;
|
|
1346
1396
|
try {
|
|
@@ -1359,7 +1409,6 @@ async function genIcons(args) {
|
|
|
1359
1409
|
aliases: tables.aliases,
|
|
1360
1410
|
});
|
|
1361
1411
|
|
|
1362
|
-
const dest = resolve(ROOT, outRel);
|
|
1363
1412
|
await mkdir(dirname(dest), { recursive: true });
|
|
1364
1413
|
await writeFile(dest, source);
|
|
1365
1414
|
|
|
@@ -1375,7 +1424,193 @@ async function genIcons(args) {
|
|
|
1375
1424
|
return 0;
|
|
1376
1425
|
}
|
|
1377
1426
|
|
|
1378
|
-
|
|
1427
|
+
// ------------------------------------------------------- gen component ----
|
|
1428
|
+
|
|
1429
|
+
/**
|
|
1430
|
+
* Why a generator must not write `path`, or `null` when it may.
|
|
1431
|
+
*
|
|
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`.
|
|
1448
|
+
*/
|
|
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;
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
/**
|
|
1461
|
+
* Check one generated file and every folder between `base` and it.
|
|
1462
|
+
*
|
|
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.
|
|
1466
|
+
*
|
|
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`.
|
|
1471
|
+
*/
|
|
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("/") || ".";
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/**
|
|
1501
|
+
* Parse the `gen component` argv tail.
|
|
1502
|
+
*
|
|
1503
|
+
* Unlike the shared {@link parseOut}, a `--out` with no value, an empty one or
|
|
1504
|
+
* one that is another flag (`--out --force`) is an error rather than a silent
|
|
1505
|
+
* fallback to the default or a folder named `--force`.
|
|
1506
|
+
*
|
|
1507
|
+
* @param {string[]} args - Arguments after `component`.
|
|
1508
|
+
* @returns {{ error: string } | { name: string | undefined, out: string, force: boolean }}
|
|
1509
|
+
*/
|
|
1510
|
+
function parseComponentArgs(args) {
|
|
1511
|
+
let out = "src/components";
|
|
1512
|
+
let force = false;
|
|
1513
|
+
const positionals = [];
|
|
1514
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
1515
|
+
const arg = args[i];
|
|
1516
|
+
if (arg === "--force") {
|
|
1517
|
+
force = true;
|
|
1518
|
+
} else if (arg === "--out") {
|
|
1519
|
+
const value = args[i + 1];
|
|
1520
|
+
if (value === undefined || value === "" || value.startsWith("--")) {
|
|
1521
|
+
return { error: "--out needs a folder, e.g. --out src/components" };
|
|
1522
|
+
}
|
|
1523
|
+
out = value;
|
|
1524
|
+
i += 1;
|
|
1525
|
+
} else if (arg.startsWith("--")) {
|
|
1526
|
+
return { error: `Unknown option: ${arg}` };
|
|
1527
|
+
} else {
|
|
1528
|
+
positionals.push(arg);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
if (positionals.length > 1) {
|
|
1532
|
+
return {
|
|
1533
|
+
error: `Expected one component name, got ${positionals.length}. Quote a name with spaces: tempest gen component "User Card"`,
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
return { name: positionals[0], out, force };
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
/**
|
|
1540
|
+
* `tempest gen component <Name> [--out src/components] [--force]` — create
|
|
1541
|
+
* `<out>/<Name>/` with `index.tsx`, `styles.module.css`, `constants.ts`,
|
|
1542
|
+
* `utils.ts` and `hooks.ts`.
|
|
1543
|
+
*
|
|
1544
|
+
* The name is normalized to PascalCase (`"user card"` → `UserCard`). Every check
|
|
1545
|
+
* runs before the first write, so a refusal leaves the disk untouched:
|
|
1546
|
+
*
|
|
1547
|
+
* - the folder must land inside the project once symlinks are resolved;
|
|
1548
|
+
* - an existing folder is refused unless `--force`;
|
|
1549
|
+
* - the folder must not be a symlink, and each of the five files must be a
|
|
1550
|
+
* regular file or missing — never a symlink or a directory — even with
|
|
1551
|
+
* `--force`, which then rewrites only those five and leaves the rest alone.
|
|
1552
|
+
*
|
|
1553
|
+
* The closing hint prints an `@/` import when the folder is under `src/`, the
|
|
1554
|
+
* only place the template's alias reaches; elsewhere it prints the path.
|
|
1555
|
+
*/
|
|
1556
|
+
async function genComponent(args) {
|
|
1557
|
+
const parsed = parseComponentArgs(args);
|
|
1558
|
+
if ("error" in parsed) {
|
|
1559
|
+
console.error(`${c.red}✗ ${parsed.error}${c.reset}`);
|
|
1560
|
+
return 1;
|
|
1561
|
+
}
|
|
1562
|
+
let generated;
|
|
1563
|
+
try {
|
|
1564
|
+
generated = componentFiles(parsed.name);
|
|
1565
|
+
} catch (err) {
|
|
1566
|
+
console.error(`${c.red}✗ ${err.message}${c.reset}`);
|
|
1567
|
+
return 1;
|
|
1568
|
+
}
|
|
1569
|
+
const dir = resolve(ROOT, parsed.out, generated.name);
|
|
1570
|
+
const shown = shownPath(dir);
|
|
1571
|
+
|
|
1572
|
+
const dirProblem = writeTargetProblem(dir, "dir");
|
|
1573
|
+
if (dirProblem) {
|
|
1574
|
+
console.error(`${c.red}✗ ${shown} ${dirProblem}.${c.reset}`);
|
|
1575
|
+
return 1;
|
|
1576
|
+
}
|
|
1577
|
+
if (lstatOrNull(dir) && !parsed.force) {
|
|
1578
|
+
console.error(
|
|
1579
|
+
`${c.red}✗ ${shown} already exists.${c.reset} Pass --force to rewrite its five generated files.`,
|
|
1580
|
+
);
|
|
1581
|
+
return 1;
|
|
1582
|
+
}
|
|
1583
|
+
const blocked = Object.keys(generated.files).find((file) =>
|
|
1584
|
+
writeTargetProblem(join(dir, file), "file"),
|
|
1585
|
+
);
|
|
1586
|
+
if (blocked) {
|
|
1587
|
+
console.error(
|
|
1588
|
+
`${c.red}✗ ${shown}/${blocked} is not a regular file${c.reset} (a folder or a symlink); nothing was written.`,
|
|
1589
|
+
);
|
|
1590
|
+
return 1;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
await mkdir(dir, { recursive: true });
|
|
1594
|
+
for (const [file, contents] of Object.entries(generated.files)) {
|
|
1595
|
+
await writeFile(join(dir, file), contents);
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
console.log(`${c.green}✓ ${generated.name}${c.reset} → ${c.bold}${shown}/${c.reset}`);
|
|
1599
|
+
for (const file of Object.keys(generated.files)) console.log(` ${c.dim}· ${file}${c.reset}`);
|
|
1600
|
+
const fromSrc = relative(join(ROOT, "src"), dir);
|
|
1601
|
+
const outsideSrc = fromSrc === ".." || fromSrc.startsWith(`..${sep}`) || isAbsolute(fromSrc);
|
|
1602
|
+
if (outsideSrc) {
|
|
1603
|
+
console.log(
|
|
1604
|
+
`\n${c.yellow}! ${shown} is outside src/${c.reset}, where the template's @/ alias does not reach — import it by a relative path.`,
|
|
1605
|
+
);
|
|
1606
|
+
} else {
|
|
1607
|
+
console.log(`\n${c.dim}Use it:${c.reset}`);
|
|
1608
|
+
console.log(` import { ${generated.name} } from "@/${fromSrc.split(sep).join("/")}";`);
|
|
1609
|
+
}
|
|
1610
|
+
return 0;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
const GEN_TARGETS = { api: genApi, icons: genIcons, component: genComponent };
|
|
1379
1614
|
|
|
1380
1615
|
function gen(args) {
|
|
1381
1616
|
const what = args[0];
|
|
@@ -1389,6 +1624,21 @@ function gen(args) {
|
|
|
1389
1624
|
return target(args.slice(1));
|
|
1390
1625
|
}
|
|
1391
1626
|
|
|
1627
|
+
/**
|
|
1628
|
+
* `tempest new component <Name>` — the spelling from issue #454, kept as an
|
|
1629
|
+
* alias of `tempest gen component`. Only `component` is accepted, so `new` does
|
|
1630
|
+
* not become a second name for every generator.
|
|
1631
|
+
*/
|
|
1632
|
+
function newCommand(args) {
|
|
1633
|
+
if (args[0] !== "component") {
|
|
1634
|
+
console.error(
|
|
1635
|
+
`${c.red}✗ Unknown new target: ${args[0] ?? "(none)"}${c.reset} — supported: component (alias of tempest gen component).`,
|
|
1636
|
+
);
|
|
1637
|
+
return 1;
|
|
1638
|
+
}
|
|
1639
|
+
return genComponent(args.slice(1));
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1392
1642
|
// ------------------------------------------------------------------ main ----
|
|
1393
1643
|
|
|
1394
1644
|
function usage() {
|
|
@@ -1408,6 +1658,12 @@ ${c.bold}Commands${c.reset}
|
|
|
1408
1658
|
(e.g. tempest gen api http://127.0.0.1:8000/openapi.json --out src/api)
|
|
1409
1659
|
${c.bold}gen icons${c.reset} Write a static icon registry from the slugs your source uses
|
|
1410
1660
|
(e.g. tempest gen icons --out src/icons.generated.ts --dir src)
|
|
1661
|
+
${c.bold}gen component${c.reset} <Name>
|
|
1662
|
+
Create <out>/<Name>/ with index.tsx, styles.module.css,
|
|
1663
|
+
constants.ts, utils.ts and hooks.ts (name → PascalCase)
|
|
1664
|
+
(e.g. tempest gen component "user card" --out src/components)
|
|
1665
|
+
--force rewrites the five files of an existing folder.
|
|
1666
|
+
Alias: tempest new component <Name>
|
|
1411
1667
|
|
|
1412
1668
|
${c.bold}doctor options${c.reset}
|
|
1413
1669
|
--no-css Skip the CSS analysis
|
|
@@ -1450,6 +1706,7 @@ const commands = {
|
|
|
1450
1706
|
fix: () => fix(rest),
|
|
1451
1707
|
format: () => format(rest),
|
|
1452
1708
|
gen: () => gen(rest),
|
|
1709
|
+
new: () => newCommand(rest),
|
|
1453
1710
|
};
|
|
1454
1711
|
|
|
1455
1712
|
if (!commands[cmd]) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../http/api-client.cjs"),
|
|
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 } from \"../http\";\nimport type { ApiClient, CsrfOptions, 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\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\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 /** Clear the session (and the stored refresh token). */\n logout: () => void;\n /** Refresh the access token (deduplicated across concurrent callers). */\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 * @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 * auth.logout();\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 } = 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 async function login(credentials: TCredentials): Promise<TUser | null> {\n const data = await api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n });\n const { token, refreshToken } = parseTokens(data);\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 function logout(): void {\n state().logout();\n writeRefreshToken(null);\n }\n\n /**\n * Clear the session and, when `redirectTo` is set, leave the page.\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.\n */\n function endSession(): void {\n logout();\n if (redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const refresh = createRefreshQueue(async () => {\n const data = await api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n });\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n refresh,\n retry,\n onUnauthorized: () => endSession(),\n });\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":"gHAmGA,SAAS,EAAmB,EAAyD,CACjF,IAAM,EAAK,GAAQ,CAAC,EACpB,MAAO,CAAE,MAAO,EAAE,aAAc,aAAc,EAAE,aAAc,CAClE,CA2BA,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,cACA,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,EAAY,EACjB,IACD,EAAO,EAAE,QAAQ,EAAY,CAAK,EACjC,EAAE,WAAW,CAAU,EAChC,CAEA,IAAM,MAAgC,EAAa,SAAS,EACtD,MAAgC,EAAM,CAAC,CAAC,MAW9C,eAAe,GAAmC,CAC9C,GAAI,CAAC,EAAQ,OAAO,EAAM,CAAC,CAAC,KAC5B,IAAM,EAAO,MAAM,EAAI,IAAW,EAAQ,CAAE,cAAe,EAAK,CAAC,EAEjE,OADA,EAAM,CAAC,CAAC,QAAQ,CAAI,EACb,CACX,CAEA,eAAe,EAAM,EAAkD,CACnE,IAAM,EAAO,MAAM,EAAI,KAAc,EAAW,CAC5C,KAAM,EACN,SAAU,EACd,CAAC,EACK,CAAE,QAAO,gBAAiB,EAAY,CAAI,EAChD,EAAM,CAAC,CAAC,SAAS,CAAK,EACtB,EAAkB,GAAgB,IAAI,EACtC,IAAM,EAAW,IAAY,CAAI,EAKjC,OAJI,GAAY,KAIT,EAAU,GAHb,EAAM,CAAC,CAAC,QAAQ,CAAQ,EACjB,EAGf,CAEA,SAAS,GAAe,CACpB,EAAM,CAAC,CAAC,OAAO,EACf,EAAkB,IAAI,CAC1B,CASA,SAAS,GAAmB,CACxB,EAAO,EACH,GAAc,OAAO,OAAW,KAChC,OAAO,SAAS,OAAO,CAAU,CAEzC,CAEA,IAAM,EAAU,EAAA,mBAAmB,SAAY,CAC3C,IAAM,EAAO,MAAM,EAAI,KAAc,EAAa,CAC9C,KAAM,EAAY,EAAiB,CAAC,EACpC,SAAU,EACd,CAAC,EACK,CAAE,QAAO,gBAAiB,EAAY,CAAI,EAChD,EAAM,CAAC,CAAC,SAAS,CAAK,EAClB,GAAc,EAAkB,CAAY,CACpD,CAAC,EAEK,EAAM,EAAA,gBAAgB,CACxB,UACA,SACA,kBACA,OACA,UACA,WACA,UACA,QACA,mBAAsB,EAAW,CACrC,CAAC,EAED,MAAO,CAAE,eAAc,MAAK,QAAO,SAAQ,UAAS,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,aAAa,CAAK,EAClB,EAAQ,CACZ,CAAC,CACL,CAAC,CACL,CAEA,SAAS,EAAmB,EAAyD,CACjF,IAAM,EAAK,GAAQ,CAAC,EACpB,MAAO,CAAE,MAAO,EAAE,aAAc,aAAc,EAAE,aAAc,CAClE,CAmDA,SAAgB,EACZ,EACgC,CAChC,GAAM,CACF,UACA,SACA,YAAY,kBACZ,eAAc,oBACd,aACA,iBACA,SACA,YAAY,eACZ,UAAU,QACV,kBAAkB,GAClB,OACA,UACA,cAAc,EACd,YACA,cAAe,GAAQ,EAAK,CAAE,cAAe,CAAG,EAAI,IAAA,GACpD,SACA,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,EAAY,EACjB,IACD,EAAO,EA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