@wwchen/stack 0.6.3 → 0.7.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 +9 -8
- package/blocks/env.example +1 -2
- package/dist/auth/better-auth/index.d.ts +2 -316
- package/dist/auth/better-auth/index.js +2 -237
- package/dist/auth/index.d.ts +2 -58
- package/dist/auth/index.js +2 -120
- package/dist/auth/proxy.d.ts +2 -14
- package/dist/auth/proxy.js +2 -50
- package/dist/cli/context.d.ts +6 -3
- package/dist/cli/context.js +3 -0
- package/dist/cli/db.d.ts +3 -0
- package/dist/cli/db.js +26 -0
- package/dist/cli/index.js +14 -3
- package/dist/cli/migrate-suite.d.ts +2 -0
- package/dist/cli/migrate-suite.js +787 -0
- package/dist/cli/neon.d.ts +11 -44
- package/dist/cli/neon.js +15 -56
- package/dist/cli/sync-blocks.d.ts +1 -3
- package/dist/cli/sync-blocks.js +2 -6
- package/dist/cli/vercel-build.js +5 -16
- package/dist/configs/vitest.js +3 -7
- package/dist/connections/index.d.ts +2 -8
- package/dist/connections/index.js +3 -9
- package/dist/connections/providers.d.ts +1 -3
- package/dist/connections/table.d.ts +2 -3
- package/dist/connections/table.js +1 -2
- package/dist/db/explaining-pool.d.ts +1 -6
- package/dist/db/explaining-pool.js +3 -10
- package/dist/db/index.d.ts +1 -3
- package/dist/db/index.js +5 -13
- package/dist/db/migration-status.d.ts +1 -4
- package/dist/db/migration-status.js +1 -4
- package/dist/db/schema-changes.d.ts +13 -0
- package/dist/db/schema-changes.js +99 -0
- package/dist/db/ssl.d.ts +1 -5
- package/dist/db/ssl.js +1 -5
- package/dist/db/target.d.ts +2 -9
- package/dist/db/target.js +2 -9
- package/dist/db/testing/index.d.ts +3 -7
- package/dist/db/testing/index.js +3 -7
- package/dist/db/testing/isolate.js +1 -2
- package/dist/db/testing/pglite.d.ts +2 -6
- package/dist/db/testing/pglite.js +2 -6
- package/dist/env/define-env.d.ts +3 -9
- package/dist/env/define-env.js +6 -16
- package/dist/env/load-env-file.d.ts +4 -9
- package/dist/env/load-env-file.js +5 -11
- package/dist/env/stack-env.d.ts +1 -3
- package/dist/env/stack-env.js +3 -7
- package/dist/env/testing.d.ts +1 -3
- package/dist/env/testing.js +2 -5
- package/dist/http/guards.d.ts +3 -10
- package/dist/http/guards.js +4 -12
- package/dist/jobs/index.d.ts +2 -9
- package/dist/jobs/index.js +2 -9
- package/dist/mail/index.d.ts +4 -45
- package/dist/mail/index.js +4 -97
- package/dist/next/api.d.ts +7 -19
- package/dist/next/api.js +6 -15
- package/dist/next/config.js +10 -32
- package/dist/next/cron.d.ts +2 -6
- package/dist/next/cron.js +3 -8
- package/dist/next/health.d.ts +3 -8
- package/dist/next/health.js +3 -8
- package/dist/testing/next.d.ts +1 -4
- package/dist/testing/next.js +2 -7
- package/dist/ui/app.css +5 -16
- package/dist/ui/globals.css +6 -20
- package/dist/ui/icons.d.ts +1 -3
- package/dist/ui/icons.js +3 -10
- package/dist/ui/index.d.ts +4 -12
- package/dist/ui/index.js +4 -12
- package/dist/ui/theme.d.ts +3 -9
- package/dist/ui/theme.js +3 -9
- package/package.json +15 -9
- package/dist/auth/better-auth/tables.d.ts +0 -628
- package/dist/auth/better-auth/tables.js +0 -76
- package/dist/auth/better-auth/users.d.ts +0 -27
- package/dist/auth/better-auth/users.js +0 -128
- package/dist/auth/safe-next.d.ts +0 -17
- package/dist/auth/safe-next.js +0 -36
- package/dist/auth/types.d.ts +0 -47
- package/dist/auth/types.js +0 -5
- package/dist/http/client-ip.d.ts +0 -12
- package/dist/http/client-ip.js +0 -28
- package/dist/http/rate-limit.d.ts +0 -34
- package/dist/http/rate-limit.js +0 -79
|
@@ -0,0 +1,787 @@
|
|
|
1
|
+
// `stack migrate-suite [--expect <version>]` — moves an app onto the suite's packages, as the installed stack knows them: adds the `@wwchen/stack-*` packages to package.json and to pnpm-workspace.yaml's release-age exemptions, moves imports of the stack's old paths to them, and exports and passes the auth package's `rate_limit` table where the schema and auth file have the template's shape. Copier runs it after `pnpm install`; it changes nothing on an app already moved.
|
|
2
|
+
//
|
|
3
|
+
// Imports are found with the TypeScript compiler API, never by searching text: a comment or a string that names an old path stays as it is. Every change is worked out before any file is written.
|
|
4
|
+
//
|
|
5
|
+
// It exits non-zero, after making every change it can, when the auth provider would get the `rate_limit` table from `authTables()` while the schema does not export it: drizzle-kit would never create the table and every sign-in would answer `unavailable`, so the upgrade must fail where someone sees it.
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname, join, relative, sep } from "node:path";
|
|
8
|
+
import { CliError, STACK_PACKAGE } from "./context.js";
|
|
9
|
+
const AUTH = "@wwchen/stack-auth";
|
|
10
|
+
const NOTIFY = "@wwchen/stack-notify";
|
|
11
|
+
const MAIL = "@wwchen/stack/mail";
|
|
12
|
+
/** Each old path and the specifier that replaces it. A Map, so no string matches an inherited property name. */
|
|
13
|
+
const MOVED = new Map([
|
|
14
|
+
["@wwchen/stack/auth", AUTH],
|
|
15
|
+
["@wwchen/stack/auth/better-auth", `${AUTH}/better-auth`],
|
|
16
|
+
["@wwchen/stack/auth/proxy", `${AUTH}/proxy`],
|
|
17
|
+
[MAIL, NOTIFY],
|
|
18
|
+
]);
|
|
19
|
+
/** Vitest's calls whose first argument is a module specifier: a mock left on an old path stops applying once the code imports the new one. */
|
|
20
|
+
const VI_MODULE_CALLS = new Set([
|
|
21
|
+
"mock",
|
|
22
|
+
"doMock",
|
|
23
|
+
"unmock",
|
|
24
|
+
"doUnmock",
|
|
25
|
+
"importActual",
|
|
26
|
+
"importMock",
|
|
27
|
+
]);
|
|
28
|
+
/** The one name `@wwchen/stack/mail` exports that lives in auth, not notify. */
|
|
29
|
+
const MAGIC = "waitForMagicLink";
|
|
30
|
+
const BETTER_AUTH = new Set(["@wwchen/stack/auth/better-auth", `${AUTH}/better-auth`]);
|
|
31
|
+
const SCHEMA = "src/db/schema.ts";
|
|
32
|
+
const AUTH_FILE = "src/lib/auth.ts";
|
|
33
|
+
const SCHEMA_IMPORT = "../db/schema.ts";
|
|
34
|
+
const TEMPLATE_TABLES = ["account", "appUser", "session", "verification"];
|
|
35
|
+
const RATE_LIMIT = "rateLimit";
|
|
36
|
+
const STACK_PACKAGE_NAME = "@wwchen/stack";
|
|
37
|
+
const WORKSPACE = "pnpm-workspace.yaml";
|
|
38
|
+
const RELEASE_AGE_EXCLUDE = "minimumReleaseAgeExclude";
|
|
39
|
+
export async function migrateSuite(cli, args) {
|
|
40
|
+
const expected = parseArgs(args);
|
|
41
|
+
if (expected !== undefined && expected !== "workspace:*" && expected !== STACK_PACKAGE.version) {
|
|
42
|
+
throw new CliError(`Upgrade @wwchen/stack to ${expected} first: ${STACK_PACKAGE.version} is installed.`);
|
|
43
|
+
}
|
|
44
|
+
const ts = await loadTypeScript();
|
|
45
|
+
const pkgPath = join(cli.cwd, "package.json");
|
|
46
|
+
if (!existsSync(pkgPath))
|
|
47
|
+
throw new CliError(`migrate-suite: no package.json in ${cli.cwd}`);
|
|
48
|
+
const pkgText = readFileSync(pkgPath, "utf8");
|
|
49
|
+
const packages = addPackages(pkgText);
|
|
50
|
+
const writes = new Map();
|
|
51
|
+
const notes = [];
|
|
52
|
+
for (const path of await sourceFiles(cli)) {
|
|
53
|
+
const text = readFileSync(join(cli.cwd, path), "utf8");
|
|
54
|
+
const moved = moveImports(ts, path, text);
|
|
55
|
+
notes.push(...moved.notes);
|
|
56
|
+
if (moved.text !== text)
|
|
57
|
+
writes.set(path, moved.text);
|
|
58
|
+
}
|
|
59
|
+
const moved = [...writes.keys()];
|
|
60
|
+
const current = (path) => writes.get(path) ??
|
|
61
|
+
(existsSync(join(cli.cwd, path)) ? readFileSync(join(cli.cwd, path), "utf8") : undefined);
|
|
62
|
+
const tables = rateLimitEdits(ts, current(SCHEMA), current(AUTH_FILE), new Set(moved));
|
|
63
|
+
for (const [path, text] of Object.entries(tables.writes))
|
|
64
|
+
writes.set(path, text);
|
|
65
|
+
const workspacePath = join(cli.cwd, WORKSPACE);
|
|
66
|
+
const workspace = releaseAgeEdit(existsSync(workspacePath) ? readFileSync(workspacePath, "utf8") : undefined, suitePackages(packages.text));
|
|
67
|
+
if (packages.added.length > 0)
|
|
68
|
+
writeFileSync(pkgPath, packages.text);
|
|
69
|
+
if (workspace.text !== undefined)
|
|
70
|
+
writeFileSync(workspacePath, workspace.text);
|
|
71
|
+
for (const [path, text] of writes)
|
|
72
|
+
writeFileSync(join(cli.cwd, path), text);
|
|
73
|
+
const sorted = await sortImports(cli, [...writes.keys()]);
|
|
74
|
+
const lines = [];
|
|
75
|
+
if (packages.added.length > 0) {
|
|
76
|
+
lines.push(`package.json: added ${packages.added.map((name) => `${name} ${packages.spec}`).join(", ")}`);
|
|
77
|
+
}
|
|
78
|
+
if (workspace.added.length > 0) {
|
|
79
|
+
lines.push(`${WORKSPACE}: ${RELEASE_AGE_EXCLUDE} now lists ${workspace.added.join(", ")}`);
|
|
80
|
+
}
|
|
81
|
+
lines.push(...workspace.manual);
|
|
82
|
+
if (moved.length > 0) {
|
|
83
|
+
lines.push(`imports moved to the suite's packages in ${moved.length} ${moved.length === 1 ? "file" : "files"}:`, ...moved.sort().map((path) => ` ${path}`));
|
|
84
|
+
}
|
|
85
|
+
lines.push(...tables.done, ...tables.manual, ...notes);
|
|
86
|
+
if (!sorted) {
|
|
87
|
+
lines.push("Biome could not sort the imports of the files above; run `pnpm lint:fix`.");
|
|
88
|
+
}
|
|
89
|
+
if (lines.length === 0) {
|
|
90
|
+
cli.log("migrate-suite: nothing to change");
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
cli.log(lines.map((line) => (line.startsWith(" ") ? line : `migrate-suite: ${line}`)).join("\n"));
|
|
94
|
+
let code = 0;
|
|
95
|
+
// A new package, or a new exemption from the release-age hold, takes an install to settle the lockfile.
|
|
96
|
+
if (packages.added.length > 0 || workspace.text !== undefined) {
|
|
97
|
+
// In CI pnpm defaults to a frozen lockfile, which the packages just added would fail.
|
|
98
|
+
({ code } = await cli.exec("pnpm", ["--dir", cli.cwd, "install", "--no-frozen-lockfile"], {
|
|
99
|
+
inherit: true,
|
|
100
|
+
}));
|
|
101
|
+
if (code !== 0)
|
|
102
|
+
cli.error("migrate-suite: pnpm install failed; run it again in the app.");
|
|
103
|
+
}
|
|
104
|
+
if (tables.refusal === undefined)
|
|
105
|
+
return code;
|
|
106
|
+
cli.error(`migrate-suite: ${tables.refusal}`);
|
|
107
|
+
return code === 0 ? 1 : code;
|
|
108
|
+
}
|
|
109
|
+
function parseArgs(args) {
|
|
110
|
+
if (args.length === 0)
|
|
111
|
+
return undefined;
|
|
112
|
+
if (args.length === 2 && args[0] === "--expect" && args[1])
|
|
113
|
+
return args[1];
|
|
114
|
+
throw new CliError("usage: stack migrate-suite [--expect <version>]");
|
|
115
|
+
}
|
|
116
|
+
/** TypeScript is a peer, loaded only here, so the other commands run without it. */
|
|
117
|
+
async function loadTypeScript() {
|
|
118
|
+
try {
|
|
119
|
+
return (await import("typescript")).default;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new CliError("migrate-suite needs typescript, a peer of @wwchen/stack: install it.");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The app's package.json with every suite package the installed stack depends on, sorted in among `dependencies`; nothing else moves. Each is added at the stack's version, or at the app's own `workspace:` spec for the stack when it takes the stack from its workspace.
|
|
127
|
+
*/
|
|
128
|
+
function addPackages(text) {
|
|
129
|
+
const pkg = JSON.parse(text);
|
|
130
|
+
const sections = [
|
|
131
|
+
"dependencies",
|
|
132
|
+
"devDependencies",
|
|
133
|
+
"peerDependencies",
|
|
134
|
+
"optionalDependencies",
|
|
135
|
+
].map((s) => pkg[s] ?? {});
|
|
136
|
+
const has = (name) => sections.some((section) => Object.hasOwn(section, name));
|
|
137
|
+
const stackSpec = sections.map((section) => section["@wwchen/stack"]).find(Boolean);
|
|
138
|
+
const spec = stackSpec?.startsWith("workspace:") ? stackSpec : STACK_PACKAGE.version;
|
|
139
|
+
const added = Object.keys(STACK_PACKAGE.dependencies)
|
|
140
|
+
.filter((name) => name.startsWith("@wwchen/stack-") && !has(name))
|
|
141
|
+
.sort();
|
|
142
|
+
if (added.length === 0)
|
|
143
|
+
return { text, added, spec };
|
|
144
|
+
const entries = Object.entries(pkg.dependencies ?? {});
|
|
145
|
+
for (const name of added) {
|
|
146
|
+
const at = entries.findIndex(([existing]) => existing > name);
|
|
147
|
+
entries.splice(at === -1 ? entries.length : at, 0, [name, spec]);
|
|
148
|
+
}
|
|
149
|
+
pkg.dependencies = Object.fromEntries(entries);
|
|
150
|
+
return { text: `${JSON.stringify(pkg, null, 2)}\n`, added, spec };
|
|
151
|
+
}
|
|
152
|
+
/** `@wwchen/stack` and every `@wwchen/stack-*` package the app's package.json names, sorted. */
|
|
153
|
+
function suitePackages(pkgText) {
|
|
154
|
+
const pkg = JSON.parse(pkgText);
|
|
155
|
+
const names = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]
|
|
156
|
+
.flatMap((s) => Object.keys(pkg[s] ?? {}))
|
|
157
|
+
.filter((name) => name === STACK_PACKAGE_NAME || name.startsWith(`${STACK_PACKAGE_NAME}-`));
|
|
158
|
+
return [...new Set(names)].sort();
|
|
159
|
+
}
|
|
160
|
+
/** A single-line scalar and an optional comment after it; undefined for anything else (an anchor, an alias, a nested collection). */
|
|
161
|
+
function readScalar(raw) {
|
|
162
|
+
const text = raw.trim();
|
|
163
|
+
const double = /^"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$/.exec(text);
|
|
164
|
+
if (double)
|
|
165
|
+
return { value: double[1], quote: '"' };
|
|
166
|
+
const single = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(text);
|
|
167
|
+
if (single)
|
|
168
|
+
return { value: single[1].replace(/''/g, "'"), quote: "'" };
|
|
169
|
+
const plain = /^([^\s#&*!|>[\]{},'"%@`-][^#]*?|-[^\s#][^#]*?)(?:\s+#.*)?$/.exec(text);
|
|
170
|
+
return plain ? { value: plain[1], quote: "" } : undefined;
|
|
171
|
+
}
|
|
172
|
+
/** Whether an exemption names a package: exactly, or by a `*` pattern (`@scope/*`). */
|
|
173
|
+
const exempts = (entry, name) => entry === name ||
|
|
174
|
+
(entry.includes("*") &&
|
|
175
|
+
new RegExp(`^${entry.split("*").map(escapeRegExp).join(".*")}$`).test(name));
|
|
176
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
177
|
+
/**
|
|
178
|
+
* pnpm-workspace.yaml with every suite package in `minimumReleaseAgeExclude`, so an upgrade installs a release on the day it ships: missing names go in after the list's last `@wwchen/` entry (or its end), quoted and indented as its items are. Where only `minimumReleaseAge` is set, the key is added after it. Nothing where neither key is set (no name is exempt from the hold), the hold is off, or there is no file; the names to add when the key holds something else.
|
|
179
|
+
*/
|
|
180
|
+
function releaseAgeEdit(text, names) {
|
|
181
|
+
const none = { added: [], manual: [] };
|
|
182
|
+
if (text === undefined || names.length === 0)
|
|
183
|
+
return none;
|
|
184
|
+
const lines = text.split("\n");
|
|
185
|
+
const quoted = (name, quote) => `${quote || '"'}${name}${quote || '"'}`;
|
|
186
|
+
const keyAt = lines.findIndex((line) => line.startsWith(`${RELEASE_AGE_EXCLUDE}:`));
|
|
187
|
+
if (keyAt === -1) {
|
|
188
|
+
const ageAt = lines.findIndex((line) => /^minimumReleaseAge\s*:/.test(line));
|
|
189
|
+
const age = ageAt === -1 ? undefined : lines[ageAt].replace(/^[^:]*:|#.*$/g, "");
|
|
190
|
+
if (age === undefined || /^\s*0*\s*$/.test(age))
|
|
191
|
+
return none;
|
|
192
|
+
const block = [`${RELEASE_AGE_EXCLUDE}:`, ...names.map((name) => ` - ${quoted(name, '"')}`)];
|
|
193
|
+
lines.splice(ageAt + 1, 0, ...block);
|
|
194
|
+
return { text: lines.join("\n"), added: names, manual: [] };
|
|
195
|
+
}
|
|
196
|
+
const unreadable = {
|
|
197
|
+
added: [],
|
|
198
|
+
manual: [
|
|
199
|
+
`${WORKSPACE}'s ${RELEASE_AGE_EXCLUDE} is not a list migrate-suite can read; add these to it by hand, or a release of them is held for a day:`,
|
|
200
|
+
...names.map((name) => ` - ${quoted(name, '"')}`),
|
|
201
|
+
],
|
|
202
|
+
};
|
|
203
|
+
const keyLine = lines[keyAt];
|
|
204
|
+
const rest = keyLine.slice(RELEASE_AGE_EXCLUDE.length + 1);
|
|
205
|
+
const missingFrom = (entries) => names.filter((name) => !entries.some((entry) => exempts(entry.value, name)));
|
|
206
|
+
/** Where the new names go: after the last `@wwchen/` entry, else after the last entry. */
|
|
207
|
+
const insertAfter = (entries) => {
|
|
208
|
+
const at = entries.findLastIndex((entry) => entry.value.startsWith("@wwchen/"));
|
|
209
|
+
return at === -1 ? entries.length - 1 : at;
|
|
210
|
+
};
|
|
211
|
+
// A flow list on the key's line: `[a, "b"]`.
|
|
212
|
+
const flow = /^(\s*\[)(.*)\](\s*(?:#.*)?)$/.exec(rest);
|
|
213
|
+
if (flow) {
|
|
214
|
+
const inner = flow[2];
|
|
215
|
+
const pieces = inner.trim() === "" ? [] : inner.split(",");
|
|
216
|
+
const entries = pieces.map(readScalar);
|
|
217
|
+
if (entries.some((entry) => entry === undefined))
|
|
218
|
+
return unreadable;
|
|
219
|
+
const read = entries;
|
|
220
|
+
const missing = missingFrom(read);
|
|
221
|
+
if (missing.length === 0)
|
|
222
|
+
return none;
|
|
223
|
+
const quote = read.at(-1)?.quote ?? '"';
|
|
224
|
+
const list = missing.map((name) => quoted(name, quote)).join(", ");
|
|
225
|
+
let rewritten;
|
|
226
|
+
if (pieces.length === 0) {
|
|
227
|
+
rewritten = list;
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
const after = insertAfter(read);
|
|
231
|
+
const end = pieces
|
|
232
|
+
.slice(0, after + 1)
|
|
233
|
+
.join(",")
|
|
234
|
+
.trimEnd().length;
|
|
235
|
+
rewritten = `${inner.slice(0, end)}, ${list}${inner.slice(end)}`;
|
|
236
|
+
}
|
|
237
|
+
lines[keyAt] = `${RELEASE_AGE_EXCLUDE}:${flow[1]}${rewritten}]${flow[3]}`;
|
|
238
|
+
return { text: lines.join("\n"), added: missing, manual: [] };
|
|
239
|
+
}
|
|
240
|
+
if (!/^\s*(#.*)?$/.test(rest))
|
|
241
|
+
return unreadable;
|
|
242
|
+
// A block list under the key: `- item` lines, with blank and comment lines among them.
|
|
243
|
+
const items = [];
|
|
244
|
+
for (let at = keyAt + 1; at < lines.length; at++) {
|
|
245
|
+
const line = lines[at];
|
|
246
|
+
if (/^\s*(#.*)?$/.test(line))
|
|
247
|
+
continue;
|
|
248
|
+
const item = /^(\s*)-\s+(.*)$/.exec(line);
|
|
249
|
+
if (!item) {
|
|
250
|
+
// An indented line that is not an item belongs to the value: something this cannot read.
|
|
251
|
+
if (/^\s/.test(line))
|
|
252
|
+
return unreadable;
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
const scalar = readScalar(item[2]);
|
|
256
|
+
if (!scalar || (items[0] && items[0].indent !== item[1]))
|
|
257
|
+
return unreadable;
|
|
258
|
+
items.push({ at, indent: item[1], scalar });
|
|
259
|
+
}
|
|
260
|
+
const read = items.map((item) => item.scalar);
|
|
261
|
+
const missing = missingFrom(read);
|
|
262
|
+
if (missing.length === 0)
|
|
263
|
+
return none;
|
|
264
|
+
const last = items[insertAfter(read)];
|
|
265
|
+
const indent = last?.indent ?? " ";
|
|
266
|
+
const quote = items.at(-1)?.scalar.quote ?? '"';
|
|
267
|
+
lines.splice((last?.at ?? keyAt) + 1, 0, ...missing.map((name) => `${indent}- ${quoted(name, quote)}`));
|
|
268
|
+
return { text: lines.join("\n"), added: missing, manual: [] };
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Sorts the imports of the files just rewritten with the app's own Biome, its formatter and linter off: a moved specifier can sort differently (`@wwchen/stack/ui` before `@wwchen/stack-auth`), and the app's lint checks the order. Skipped when the app has no Biome; false when Biome failed.
|
|
272
|
+
*/
|
|
273
|
+
async function sortImports(cli, paths) {
|
|
274
|
+
if (paths.length === 0)
|
|
275
|
+
return true;
|
|
276
|
+
if (!existsSync(join(cli.cwd, "node_modules", "@biomejs", "biome", "package.json")))
|
|
277
|
+
return true;
|
|
278
|
+
const { code } = await cli.exec("pnpm", [
|
|
279
|
+
"--dir",
|
|
280
|
+
cli.cwd,
|
|
281
|
+
"exec",
|
|
282
|
+
"biome",
|
|
283
|
+
"check",
|
|
284
|
+
"--write",
|
|
285
|
+
"--formatter-enabled=false",
|
|
286
|
+
"--linter-enabled=false",
|
|
287
|
+
"--no-errors-on-unmatched",
|
|
288
|
+
"--files-ignore-unknown=true",
|
|
289
|
+
...paths.sort().map((path) => join(cli.cwd, path)),
|
|
290
|
+
]);
|
|
291
|
+
return code === 0;
|
|
292
|
+
}
|
|
293
|
+
const SOURCE = /\.(ts|tsx|mts)$/;
|
|
294
|
+
const SKIPPED_DIRS = new Set(["node_modules", ".next", "dist"]);
|
|
295
|
+
/** The app's TypeScript files, relative to its root: those git tracks, or, outside a repository, every one outside dependencies and build output. */
|
|
296
|
+
async function sourceFiles(cli) {
|
|
297
|
+
const isSource = (path) => SOURCE.test(path) &&
|
|
298
|
+
!path.split("/").includes("node_modules") &&
|
|
299
|
+
existsSync(join(cli.cwd, path));
|
|
300
|
+
if (!insideGit(cli.cwd))
|
|
301
|
+
return walk(cli.cwd).filter(isSource);
|
|
302
|
+
const { stdout, code } = await cli.exec("git", ["-C", cli.cwd, "ls-files", "-z"]);
|
|
303
|
+
if (code !== 0)
|
|
304
|
+
throw new CliError(`migrate-suite: git ls-files failed in ${cli.cwd}`);
|
|
305
|
+
return stdout.split("\0").filter(Boolean).filter(isSource);
|
|
306
|
+
}
|
|
307
|
+
function insideGit(dir) {
|
|
308
|
+
for (let at = dir;; at = dirname(at)) {
|
|
309
|
+
if (existsSync(join(at, ".git")))
|
|
310
|
+
return true;
|
|
311
|
+
if (dirname(at) === at)
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function walk(root, dir = root) {
|
|
316
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
317
|
+
const path = join(dir, entry.name);
|
|
318
|
+
if (entry.isDirectory())
|
|
319
|
+
return SKIPPED_DIRS.has(entry.name) ? [] : walk(root, path);
|
|
320
|
+
return entry.isFile() ? [relative(root, path).split(sep).join("/")] : [];
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
function parse(ts, path, text) {
|
|
324
|
+
const kind = path.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
|
|
325
|
+
return ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kind);
|
|
326
|
+
}
|
|
327
|
+
function applyEdits(text, edits) {
|
|
328
|
+
let out = text;
|
|
329
|
+
for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
|
|
330
|
+
out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
|
|
331
|
+
}
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
const newlines = (text) => text.split("\n").length - 1;
|
|
335
|
+
/** An edit made against the whole file, moved to apply to the slice of it that starts at `offset`. */
|
|
336
|
+
const within = (edit, offset) => ({
|
|
337
|
+
...edit,
|
|
338
|
+
start: edit.start - offset,
|
|
339
|
+
end: edit.end - offset,
|
|
340
|
+
});
|
|
341
|
+
/** A statement's text with `edits` applied, for a line to print. */
|
|
342
|
+
const statementWith = (sf, node, edits) => {
|
|
343
|
+
const start = node.getStart(sf);
|
|
344
|
+
return applyEdits(sf.text.slice(start, node.end), edits.map((edit) => within(edit, start)));
|
|
345
|
+
};
|
|
346
|
+
/** Moves every import and export specifier (static, dynamic, `import type`, `import x = require`) off the old paths. Comments and other strings are never changed; a string that is exactly an old path is pointed out. */
|
|
347
|
+
function moveImports(ts, path, text) {
|
|
348
|
+
const sf = parse(ts, path, text);
|
|
349
|
+
const edits = [];
|
|
350
|
+
const specifiers = new Set();
|
|
351
|
+
const pending = [];
|
|
352
|
+
let usesMagic;
|
|
353
|
+
const mentionsMagic = () => {
|
|
354
|
+
usesMagic ??= hasIdentifier(ts, sf, MAGIC);
|
|
355
|
+
return usesMagic;
|
|
356
|
+
};
|
|
357
|
+
const replace = (literal, to) => edits.push({ start: literal.getStart(sf) + 1, end: literal.end - 1, text: to });
|
|
358
|
+
/** A specifier that brings in the module whole (namespace, dynamic, `require`, type query). */
|
|
359
|
+
const whole = (literal) => {
|
|
360
|
+
const to = MOVED.get(literal.text);
|
|
361
|
+
if (!to)
|
|
362
|
+
return;
|
|
363
|
+
if (literal.text === MAIL && mentionsMagic()) {
|
|
364
|
+
pending.push({
|
|
365
|
+
pos: literal.getStart(sf),
|
|
366
|
+
note: (line) => `${path}:${line}: "${MAIL}" is imported whole and the file uses ${MAGIC}; left as is. Import ${MAGIC} from "${AUTH}" and the rest from "${NOTIFY}".`,
|
|
367
|
+
});
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
replace(literal, to);
|
|
371
|
+
};
|
|
372
|
+
const visit = (node) => {
|
|
373
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
|
|
374
|
+
node.moduleSpecifier &&
|
|
375
|
+
ts.isStringLiteral(node.moduleSpecifier)) {
|
|
376
|
+
specifiers.add(node.moduleSpecifier);
|
|
377
|
+
const literal = node.moduleSpecifier;
|
|
378
|
+
if (literal.text !== MAIL) {
|
|
379
|
+
const to = MOVED.get(literal.text);
|
|
380
|
+
if (to)
|
|
381
|
+
replace(literal, to);
|
|
382
|
+
}
|
|
383
|
+
else {
|
|
384
|
+
const split = splitMail(ts, sf, node);
|
|
385
|
+
if (split === "whole")
|
|
386
|
+
whole(literal);
|
|
387
|
+
else
|
|
388
|
+
edits.push(split);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
else if (ts.isImportEqualsDeclaration(node) &&
|
|
392
|
+
ts.isExternalModuleReference(node.moduleReference) &&
|
|
393
|
+
ts.isStringLiteralLike(node.moduleReference.expression)) {
|
|
394
|
+
specifiers.add(node.moduleReference.expression);
|
|
395
|
+
whole(node.moduleReference.expression);
|
|
396
|
+
}
|
|
397
|
+
else if (ts.isCallExpression(node) &&
|
|
398
|
+
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
|
399
|
+
node.arguments[0] &&
|
|
400
|
+
ts.isStringLiteralLike(node.arguments[0])) {
|
|
401
|
+
specifiers.add(node.arguments[0]);
|
|
402
|
+
whole(node.arguments[0]);
|
|
403
|
+
}
|
|
404
|
+
else if (ts.isImportTypeNode(node) &&
|
|
405
|
+
ts.isLiteralTypeNode(node.argument) &&
|
|
406
|
+
ts.isStringLiteral(node.argument.literal)) {
|
|
407
|
+
specifiers.add(node.argument.literal);
|
|
408
|
+
whole(node.argument.literal);
|
|
409
|
+
}
|
|
410
|
+
else if (ts.isCallExpression(node) &&
|
|
411
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
412
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
413
|
+
node.expression.expression.text === "vi" &&
|
|
414
|
+
VI_MODULE_CALLS.has(node.expression.name.text) &&
|
|
415
|
+
node.arguments[0] &&
|
|
416
|
+
ts.isStringLiteralLike(node.arguments[0])) {
|
|
417
|
+
specifiers.add(node.arguments[0]);
|
|
418
|
+
whole(node.arguments[0]);
|
|
419
|
+
}
|
|
420
|
+
else if (ts.isStringLiteralLike(node) && !specifiers.has(node) && MOVED.has(node.text)) {
|
|
421
|
+
const { text: name } = node;
|
|
422
|
+
pending.push({
|
|
423
|
+
pos: node.getStart(sf),
|
|
424
|
+
note: (line) => `${path}:${line}: a string names "${name}" outside an import; if it names the module, change it to "${MOVED.get(name)}"`,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
ts.forEachChild(node, visit);
|
|
428
|
+
};
|
|
429
|
+
visit(sf);
|
|
430
|
+
// A note's line is counted in the file as rewritten.
|
|
431
|
+
const lineAfterEdits = (pos) => sf.getLineAndCharacterOfPosition(pos).line +
|
|
432
|
+
1 +
|
|
433
|
+
edits
|
|
434
|
+
.filter((edit) => edit.end <= pos)
|
|
435
|
+
.reduce((sum, edit) => sum + newlines(edit.text) - newlines(text.slice(edit.start, edit.end)), 0);
|
|
436
|
+
const notes = pending
|
|
437
|
+
.sort((a, b) => a.pos - b.pos)
|
|
438
|
+
.map(({ pos, note }) => note(lineAfterEdits(pos)));
|
|
439
|
+
return { text: applyEdits(text, edits), notes };
|
|
440
|
+
}
|
|
441
|
+
function hasIdentifier(ts, sf, name) {
|
|
442
|
+
const visit = (node) => (ts.isIdentifier(node) && node.text === name) || (ts.forEachChild(node, visit) ?? false);
|
|
443
|
+
return visit(sf);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* An import or export of `@wwchen/stack/mail` as one edit: `waitForMagicLink` from auth, the rest from notify, split in two declarations when it names both. `"whole"` for a namespace import or export, which names nothing.
|
|
447
|
+
*/
|
|
448
|
+
function splitMail(ts, sf, decl) {
|
|
449
|
+
const literal = decl.moduleSpecifier;
|
|
450
|
+
const start = decl.getStart(sf);
|
|
451
|
+
const original = sf.text.slice(start, decl.end);
|
|
452
|
+
const at = (node) => node.getStart(sf) - start;
|
|
453
|
+
const specifier = (to) => ({
|
|
454
|
+
start: at(literal) + 1,
|
|
455
|
+
end: literal.end - start - 1,
|
|
456
|
+
text: to,
|
|
457
|
+
});
|
|
458
|
+
const indent = sf.text.slice(sf.text.lastIndexOf("\n", start - 1) + 1, start);
|
|
459
|
+
const whole = (to) => ({
|
|
460
|
+
start,
|
|
461
|
+
end: decl.end,
|
|
462
|
+
text: applyEdits(original, [specifier(to)]),
|
|
463
|
+
});
|
|
464
|
+
let named;
|
|
465
|
+
let defaultName;
|
|
466
|
+
if (ts.isImportDeclaration(decl)) {
|
|
467
|
+
const clause = decl.importClause;
|
|
468
|
+
if (!clause)
|
|
469
|
+
return whole(NOTIFY);
|
|
470
|
+
if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings))
|
|
471
|
+
return "whole";
|
|
472
|
+
named = clause.namedBindings;
|
|
473
|
+
defaultName = clause.name;
|
|
474
|
+
}
|
|
475
|
+
else if (!decl.exportClause) {
|
|
476
|
+
// `export *` re-exports every name mail did: notify's, and waitForMagicLink from auth.
|
|
477
|
+
const magic = applyEdits(original, [
|
|
478
|
+
{
|
|
479
|
+
start: 0,
|
|
480
|
+
end: at(literal),
|
|
481
|
+
text: `export ${decl.isTypeOnly ? "type " : ""}{ ${MAGIC} } from `,
|
|
482
|
+
},
|
|
483
|
+
specifier(AUTH),
|
|
484
|
+
]);
|
|
485
|
+
return {
|
|
486
|
+
start,
|
|
487
|
+
end: decl.end,
|
|
488
|
+
text: `${magic}\n${indent}${applyEdits(original, [specifier(NOTIFY)])}`,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
else if (ts.isNamespaceExport(decl.exportClause)) {
|
|
492
|
+
return "whole";
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
named = decl.exportClause;
|
|
496
|
+
}
|
|
497
|
+
const elements = [...(named?.elements ?? [])];
|
|
498
|
+
const magic = elements.filter((e) => (e.propertyName ?? e.name).text === MAGIC);
|
|
499
|
+
const rest = elements.filter((e) => !magic.includes(e));
|
|
500
|
+
if (magic.length === 0)
|
|
501
|
+
return whole(NOTIFY);
|
|
502
|
+
if (!named || (rest.length === 0 && !defaultName))
|
|
503
|
+
return whole(AUTH);
|
|
504
|
+
// The names between the braces, first to last.
|
|
505
|
+
const names = {
|
|
506
|
+
start: at(elements[0]),
|
|
507
|
+
end: elements.at(-1).end - start,
|
|
508
|
+
};
|
|
509
|
+
const list = (picked) => picked.map((e) => e.getText(sf)).join(", ");
|
|
510
|
+
const authPart = applyEdits(original, [
|
|
511
|
+
// `import x, { waitForMagicLink }` keeps the default import with the rest.
|
|
512
|
+
...(defaultName ? [{ start: at(defaultName), end: at(named), text: "" }] : []),
|
|
513
|
+
{ ...names, text: list(magic) },
|
|
514
|
+
specifier(AUTH),
|
|
515
|
+
]);
|
|
516
|
+
const notifyPart = applyEdits(original, [{ ...names, text: list(rest) }, specifier(NOTIFY)]);
|
|
517
|
+
return { start, end: decl.end, text: `${authPart}\n${indent}${notifyPart}` };
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Adds `rateLimit` to the schema's `authTables()` export and to auth's `tables` and its import, each only when it has exactly the template's shape; otherwise the file is left as it is and the lines to write are given. Auth is edited only once the schema exports the table. A refusal when auth hands the provider an `authTables()` result, which carries the table, and the schema will not export it.
|
|
521
|
+
*/
|
|
522
|
+
function rateLimitEdits(ts, schemaText, authText, moved) {
|
|
523
|
+
const result = { writes: {}, done: [], manual: [] };
|
|
524
|
+
const heldBack = (path) => `rateLimit is not added to it${moved.has(path) ? " (only its imports were moved)" : ""}`;
|
|
525
|
+
if (schemaText === undefined)
|
|
526
|
+
return result;
|
|
527
|
+
const schema = schemaEdit(ts, schemaText);
|
|
528
|
+
if (schema.kind === "edit") {
|
|
529
|
+
result.writes[SCHEMA] = schema.text;
|
|
530
|
+
result.done.push(`${SCHEMA}: exports rateLimit`);
|
|
531
|
+
}
|
|
532
|
+
else if (schema.kind === "manual") {
|
|
533
|
+
result.manual.push(`${SCHEMA} does not have the template's shape, so ${heldBack(SCHEMA)}. Export the rate_limit table by hand, ${schema.replace ? "so this line reads" : "adding this line"}:`, ...schema.lines.map((line) => ` ${line}`));
|
|
534
|
+
}
|
|
535
|
+
if (authText === undefined)
|
|
536
|
+
return result;
|
|
537
|
+
const auth = authEdit(ts, authText);
|
|
538
|
+
if (auth.kind === "has")
|
|
539
|
+
return result;
|
|
540
|
+
if (auth.kind === "carries") {
|
|
541
|
+
if (schema.kind === "manual") {
|
|
542
|
+
result.refusal = `${AUTH_FILE} gives betterAuthProvider the rate_limit table from authTables(), and ${SCHEMA} does not export it: every sign-in would answer \`unavailable\` until the table is exported and migrated. Make ${SCHEMA} read as printed above, run this command again, then \`pnpm exec stack db:upgrade\` and \`pnpm exec stack sync-blocks\`, and commit the migration with the rest. As a Copier task, this stopped \`copier update\` before it put back the app's own changes to the template's files, so commit nothing from this run: discard it (\`git reset --hard && git clean -fd\`), run \`copier update\` again with \`--skip-tasks\`, then \`pnpm install\` and the steps above.`;
|
|
543
|
+
}
|
|
544
|
+
return result;
|
|
545
|
+
}
|
|
546
|
+
if (auth.kind === "edit" && schema.kind !== "manual") {
|
|
547
|
+
result.writes[AUTH_FILE] = auth.text;
|
|
548
|
+
result.done.push(`${AUTH_FILE}: passes rateLimit to betterAuthProvider`);
|
|
549
|
+
return result;
|
|
550
|
+
}
|
|
551
|
+
result.manual.push(auth.kind === "edit"
|
|
552
|
+
? `${AUTH_FILE} gets no rateLimit until ${SCHEMA} exports it${moved.has(AUTH_FILE) ? " (only its imports were moved)" : ""}. Then make these lines read:`
|
|
553
|
+
: `${AUTH_FILE} does not have the template's shape, so ${heldBack(AUTH_FILE)}. Pass the rate_limit table to betterAuthProvider by hand, so these lines read:`, ...auth.lines.map((line) => ` ${line}`));
|
|
554
|
+
return result;
|
|
555
|
+
}
|
|
556
|
+
/** The name a file binds an export of the better-auth entry to, if it imports it. */
|
|
557
|
+
function importedFromBetterAuth(ts, sf, name) {
|
|
558
|
+
for (const statement of sf.statements) {
|
|
559
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
560
|
+
continue;
|
|
561
|
+
if (!BETTER_AUTH.has(statement.moduleSpecifier.text))
|
|
562
|
+
continue;
|
|
563
|
+
const bindings = statement.importClause?.namedBindings;
|
|
564
|
+
if (!bindings || !ts.isNamedImports(bindings))
|
|
565
|
+
continue;
|
|
566
|
+
const element = bindings.elements.find((e) => (e.propertyName ?? e.name).text === name);
|
|
567
|
+
if (element)
|
|
568
|
+
return element.name.text;
|
|
569
|
+
}
|
|
570
|
+
return undefined;
|
|
571
|
+
}
|
|
572
|
+
/** Names the file's top level binds, and those it exports. */
|
|
573
|
+
function topLevel(ts, sf) {
|
|
574
|
+
const bound = new Set();
|
|
575
|
+
const exported = new Set();
|
|
576
|
+
const bind = (name, isExported) => {
|
|
577
|
+
if (ts.isIdentifier(name)) {
|
|
578
|
+
bound.add(name.text);
|
|
579
|
+
if (isExported)
|
|
580
|
+
exported.add(name.text);
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
for (const element of name.elements) {
|
|
584
|
+
if (!ts.isOmittedExpression(element))
|
|
585
|
+
bind(element.name, isExported);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
for (const statement of sf.statements) {
|
|
590
|
+
const isExported = ts.canHaveModifiers(statement) &&
|
|
591
|
+
(ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
|
|
592
|
+
if (ts.isImportDeclaration(statement)) {
|
|
593
|
+
const clause = statement.importClause;
|
|
594
|
+
if (clause?.name)
|
|
595
|
+
bound.add(clause.name.text);
|
|
596
|
+
const bindings = clause?.namedBindings;
|
|
597
|
+
if (bindings && ts.isNamespaceImport(bindings))
|
|
598
|
+
bound.add(bindings.name.text);
|
|
599
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
600
|
+
for (const element of bindings.elements)
|
|
601
|
+
bound.add(element.name.text);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
else if (ts.isVariableStatement(statement)) {
|
|
605
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
606
|
+
bind(declaration.name, isExported);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) &&
|
|
610
|
+
statement.name) {
|
|
611
|
+
bind(statement.name, isExported);
|
|
612
|
+
}
|
|
613
|
+
else if (ts.isExportDeclaration(statement) &&
|
|
614
|
+
statement.exportClause &&
|
|
615
|
+
ts.isNamedExports(statement.exportClause)) {
|
|
616
|
+
for (const element of statement.exportClause.elements)
|
|
617
|
+
exported.add(element.name.text);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return { bound, exported };
|
|
621
|
+
}
|
|
622
|
+
/** `, rateLimit` after the last element of a list. */
|
|
623
|
+
const appendTo = (list) => {
|
|
624
|
+
const last = list[list.length - 1];
|
|
625
|
+
return { start: last.end, end: last.end, text: `, ${RATE_LIMIT}` };
|
|
626
|
+
};
|
|
627
|
+
const isTemplateNames = (names) => names.length === TEMPLATE_TABLES.length &&
|
|
628
|
+
[...names].sort().every((name, i) => name === TEMPLATE_TABLES[i]);
|
|
629
|
+
function schemaEdit(ts, text) {
|
|
630
|
+
const sf = parse(ts, SCHEMA, text);
|
|
631
|
+
const { bound, exported } = topLevel(ts, sf);
|
|
632
|
+
if (exported.has(RATE_LIMIT))
|
|
633
|
+
return { kind: "has" };
|
|
634
|
+
const local = importedFromBetterAuth(ts, sf, "authTables");
|
|
635
|
+
// Each `export const { … } = authTables(…)`.
|
|
636
|
+
const exports = sf.statements.flatMap((statement) => {
|
|
637
|
+
if (!ts.isVariableStatement(statement))
|
|
638
|
+
return [];
|
|
639
|
+
const declaration = statement.declarationList.declarations[0];
|
|
640
|
+
const isExportedConst = (ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword) &&
|
|
641
|
+
(statement.declarationList.flags & ts.NodeFlags.Const) !== 0 &&
|
|
642
|
+
statement.declarationList.declarations.length === 1;
|
|
643
|
+
if (!isExportedConst ||
|
|
644
|
+
!declaration ||
|
|
645
|
+
!ts.isObjectBindingPattern(declaration.name) ||
|
|
646
|
+
!declaration.initializer ||
|
|
647
|
+
!ts.isCallExpression(declaration.initializer) ||
|
|
648
|
+
!ts.isIdentifier(declaration.initializer.expression) ||
|
|
649
|
+
declaration.initializer.expression.text !== local) {
|
|
650
|
+
return [];
|
|
651
|
+
}
|
|
652
|
+
return [{ statement, pattern: declaration.name }];
|
|
653
|
+
});
|
|
654
|
+
const only = exports.length === 1 ? exports[0] : undefined;
|
|
655
|
+
if (only && !bound.has(RATE_LIMIT)) {
|
|
656
|
+
const { elements } = only.pattern;
|
|
657
|
+
const plain = elements.every((e) => !e.dotDotDotToken && !e.propertyName && !e.initializer && ts.isIdentifier(e.name));
|
|
658
|
+
if (plain && isTemplateNames(elements.map((e) => e.name.text))) {
|
|
659
|
+
return { kind: "edit", text: applyEdits(text, [appendTo(elements)]), lines: [] };
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (only && only.pattern.elements.length > 0) {
|
|
663
|
+
const line = statementWith(sf, only.statement, [appendTo(only.pattern.elements)]);
|
|
664
|
+
return { kind: "manual", lines: [line], replace: true };
|
|
665
|
+
}
|
|
666
|
+
return {
|
|
667
|
+
kind: "manual",
|
|
668
|
+
lines: [
|
|
669
|
+
...(local ? [] : [`import { authTables } from "${AUTH}/better-auth";`]),
|
|
670
|
+
`export const { ${RATE_LIMIT} } = ${local ?? "authTables"}();`,
|
|
671
|
+
],
|
|
672
|
+
replace: false,
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
function authEdit(ts, text) {
|
|
676
|
+
const sf = parse(ts, AUTH_FILE, text);
|
|
677
|
+
const provider = importedFromBetterAuth(ts, sf, "betterAuthProvider");
|
|
678
|
+
const tablesFn = importedFromBetterAuth(ts, sf, "authTables");
|
|
679
|
+
const calls = [];
|
|
680
|
+
const visit = (node) => {
|
|
681
|
+
if (ts.isCallExpression(node) &&
|
|
682
|
+
ts.isIdentifier(node.expression) &&
|
|
683
|
+
node.expression.text === provider) {
|
|
684
|
+
calls.push(node);
|
|
685
|
+
}
|
|
686
|
+
ts.forEachChild(node, visit);
|
|
687
|
+
};
|
|
688
|
+
if (provider)
|
|
689
|
+
visit(sf);
|
|
690
|
+
const options = calls.length === 1 ? calls[0]?.arguments[0] : undefined;
|
|
691
|
+
const tablesProps = options && ts.isObjectLiteralExpression(options)
|
|
692
|
+
? options.properties.filter((p) => p.name && ts.isIdentifier(p.name) && p.name.text === "tables")
|
|
693
|
+
: [];
|
|
694
|
+
const tables = tablesProps.length === 1 ? tablesProps[0] : undefined;
|
|
695
|
+
const value = tables && ts.isPropertyAssignment(tables)
|
|
696
|
+
? tables.initializer
|
|
697
|
+
: tables && ts.isShorthandPropertyAssignment(tables)
|
|
698
|
+
? tables.name
|
|
699
|
+
: undefined;
|
|
700
|
+
if (value && ts.isObjectLiteralExpression(value)) {
|
|
701
|
+
const names = value.properties.map((p) => p.name && ts.isIdentifier(p.name) ? p.name.text : "");
|
|
702
|
+
if (names.includes(RATE_LIMIT))
|
|
703
|
+
return { kind: "has" };
|
|
704
|
+
}
|
|
705
|
+
if (value && tablesFn) {
|
|
706
|
+
// Top-level `const x = authTables(…)`.
|
|
707
|
+
const results = new Set(sf.statements.flatMap((s) => ts.isVariableStatement(s) && (s.declarationList.flags & ts.NodeFlags.Const) !== 0
|
|
708
|
+
? s.declarationList.declarations.flatMap((d) => ts.isIdentifier(d.name) && d.initializer && callsTables(ts, d.initializer, tablesFn)
|
|
709
|
+
? [d.name.text]
|
|
710
|
+
: [])
|
|
711
|
+
: []));
|
|
712
|
+
const isResult = (node) => {
|
|
713
|
+
const inner = unwrap(ts, node);
|
|
714
|
+
return (callsTables(ts, inner, tablesFn) || (ts.isIdentifier(inner) && results.has(inner.text)));
|
|
715
|
+
};
|
|
716
|
+
const inner = unwrap(ts, value);
|
|
717
|
+
if (isResult(inner) ||
|
|
718
|
+
(ts.isObjectLiteralExpression(inner) &&
|
|
719
|
+
inner.properties.some((p) => ts.isSpreadAssignment(p) && isResult(p.expression)))) {
|
|
720
|
+
return { kind: "carries" };
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
const imports = sf.statements.filter((s) => ts.isImportDeclaration(s) &&
|
|
724
|
+
ts.isStringLiteral(s.moduleSpecifier) &&
|
|
725
|
+
s.moduleSpecifier.text === SCHEMA_IMPORT &&
|
|
726
|
+
!!s.importClause?.namedBindings &&
|
|
727
|
+
ts.isNamedImports(s.importClause.namedBindings));
|
|
728
|
+
const schemaImport = imports.length === 1 ? imports[0] : undefined;
|
|
729
|
+
const elements = schemaImport?.importClause?.namedBindings
|
|
730
|
+
?.elements;
|
|
731
|
+
const importEdit = () => {
|
|
732
|
+
if (!elements || elements.length === 0)
|
|
733
|
+
return undefined;
|
|
734
|
+
// Sorted in, as the app's formatter keeps a named import.
|
|
735
|
+
const after = elements.find((e) => e.name.text.toLowerCase() > RATE_LIMIT.toLowerCase());
|
|
736
|
+
if (after) {
|
|
737
|
+
const start = after.getStart(sf);
|
|
738
|
+
return { start, end: start, text: `${RATE_LIMIT}, ` };
|
|
739
|
+
}
|
|
740
|
+
return appendTo(elements);
|
|
741
|
+
};
|
|
742
|
+
const importLine = () => {
|
|
743
|
+
const edit = importEdit();
|
|
744
|
+
if (!schemaImport || !edit)
|
|
745
|
+
return `import { ${RATE_LIMIT} } from "${SCHEMA_IMPORT}";`;
|
|
746
|
+
return statementWith(sf, schemaImport, [edit]);
|
|
747
|
+
};
|
|
748
|
+
const tablesLine = () => {
|
|
749
|
+
if (value && ts.isObjectLiteralExpression(value) && value.properties.length > 0 && tables) {
|
|
750
|
+
return `${statementWith(sf, tables, [appendTo(value.properties)])},`;
|
|
751
|
+
}
|
|
752
|
+
return value
|
|
753
|
+
? `tables: { ...${value.getText(sf)}, ${RATE_LIMIT} },`
|
|
754
|
+
: `tables: { appUser, session, account, verification, ${RATE_LIMIT} },`;
|
|
755
|
+
};
|
|
756
|
+
const lines = [importLine(), tablesLine()];
|
|
757
|
+
const isTemplate = value &&
|
|
758
|
+
ts.isObjectLiteralExpression(value) &&
|
|
759
|
+
value.properties.every((p) => ts.isShorthandPropertyAssignment(p) && !p.objectAssignmentInitializer) &&
|
|
760
|
+
isTemplateNames(value.properties.map((p) => p.name.text)) &&
|
|
761
|
+
!!schemaImport &&
|
|
762
|
+
schemaImport.importClause?.phaseModifier === undefined &&
|
|
763
|
+
TEMPLATE_TABLES.every((name) => elements?.some((e) => !e.propertyName && !e.isTypeOnly && e.name.text === name)) &&
|
|
764
|
+
!topLevel(ts, sf).bound.has(RATE_LIMIT);
|
|
765
|
+
if (!isTemplate || !value || !ts.isObjectLiteralExpression(value)) {
|
|
766
|
+
return { kind: "manual", lines, replace: true };
|
|
767
|
+
}
|
|
768
|
+
const edits = [appendTo(value.properties), importEdit()];
|
|
769
|
+
return { kind: "edit", text: applyEdits(text, edits), lines };
|
|
770
|
+
}
|
|
771
|
+
/** An expression without the parentheses, `as`, `satisfies` and `!` around it. */
|
|
772
|
+
function unwrap(ts, node) {
|
|
773
|
+
let at = node;
|
|
774
|
+
while (ts.isParenthesizedExpression(at) ||
|
|
775
|
+
ts.isAsExpression(at) ||
|
|
776
|
+
ts.isSatisfiesExpression(at) ||
|
|
777
|
+
ts.isNonNullExpression(at)) {
|
|
778
|
+
at = at.expression;
|
|
779
|
+
}
|
|
780
|
+
return at;
|
|
781
|
+
}
|
|
782
|
+
const callsTables = (ts, node, tablesFn) => {
|
|
783
|
+
const inner = unwrap(ts, node);
|
|
784
|
+
return (ts.isCallExpression(inner) &&
|
|
785
|
+
ts.isIdentifier(inner.expression) &&
|
|
786
|
+
inner.expression.text === tablesFn);
|
|
787
|
+
};
|