-
Notifications
You must be signed in to change notification settings - Fork 664
/
update.ts
470 lines (428 loc) · 13.9 KB
/
update.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import * as path from "@std/path";
import * as JSONC from "@std/jsonc";
import * as tsmorph from "ts-morph";
export const SyntaxKind = tsmorph.ts.SyntaxKind;
export const FRESH_VERSION = "2.0.0-alpha.19";
export const PREACT_VERSION = "10.22.1";
export const PREACT_SIGNALS_VERSION = "1.2.3";
export interface DenoJson {
name?: string;
version?: string;
imports?: Record<string, string>;
}
async function format(filePath: string) {
const command = new Deno.Command(Deno.execPath(), {
args: ["fmt", filePath],
});
await command.output();
}
async function writeFormatted(filePath: string, content: string) {
await Deno.writeTextFile(filePath, content);
await format(filePath);
}
async function updateDenoJson(
dir: string,
fn: (json: DenoJson) => void | Promise<void>,
): Promise<void> {
let filePath = path.join(dir, "deno.json");
try {
const config = JSON.parse(await Deno.readTextFile(filePath)) as DenoJson;
await fn(config);
await writeFormatted(filePath, JSON.stringify(config));
return;
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
filePath = path.join(dir, "deno.jsonc");
try {
const config = JSONC.parse(await Deno.readTextFile(filePath)) as DenoJson;
await fn(config);
await writeFormatted(filePath, JSON.stringify(config));
return;
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
throw new Error(`Could not find deno.json or deno.jsonc in: ${dir}`);
}
export interface ImportState {
core: Set<string>;
runtime: Set<string>;
compat: Set<string>;
}
const compat = new Set([
"defineApp",
"defineLayout",
"defineRoute",
"AppProps",
"ErrorPageProps",
"Handler",
"Handlers",
"LayoutProps",
"RouteContext",
"UnknownPageProps",
]);
export async function updateProject(dir: string) {
// Update config
await updateDenoJson(dir, (config) => {
if (config.imports !== null && typeof config.imports !== "object") {
config.imports = {};
}
config.imports["fresh"] = `jsr:@fresh/core@^${FRESH_VERSION}`;
config.imports["preact"] = `npm:preact@^${PREACT_VERSION}`;
config.imports["@preact/signals"] =
`npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`;
delete config.imports["$fresh/"];
delete config.imports["@preact/signals-core"];
delete config.imports["preact-render-to-string"];
});
// Update routes folder
const project = new tsmorph.Project();
const sfs = project.addSourceFilesAtPaths(
path.join(dir, "**", "*.{js,jsx,ts,tsx}"),
);
await Promise.all(sfs.map(async (sourceFile) => {
try {
return await updateFile(sourceFile);
} catch (err) {
// deno-lint-ignore no-console
console.error(`Could not process ${sourceFile.getFilePath()}`);
throw err;
}
}));
}
async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
const newImports: ImportState = {
core: new Set(),
runtime: new Set(),
compat: new Set(),
};
const text = sourceFile.getFullText()
.replaceAll("/** @jsx h */\n", "")
.replaceAll("/** @jsxFrag Fragment */\n", "")
.replaceAll('/// <reference no-default-lib="true" />\n', "")
.replaceAll('/// <reference lib="dom" />\n', "")
.replaceAll('/// <reference lib="dom.iterable" />\n', "")
.replaceAll('/// <reference lib="dom.asynciterable" />\n', "")
.replaceAll('/// <reference lib="deno.ns" />\n', "");
sourceFile.replaceWithText(text);
if (
sourceFile.getFilePath().includes("/routes/") &&
!sourceFile.getDirectoryPath().includes("/(_")
) {
for (const [name, decl] of sourceFile.getExportedDeclarations()) {
if (name === "handler") {
const node = decl[0];
if (node.isKind(SyntaxKind.VariableDeclaration)) {
const init = node.getInitializer();
if (
init !== undefined &&
init.isKind(SyntaxKind.ObjectLiteralExpression)
) {
for (const property of init.getProperties()) {
if (property.isKind(SyntaxKind.MethodDeclaration)) {
const name = property.getName();
if (
name === "GET" || name === "POST" || name === "PATCH" ||
name === "PUT" || name === "DELETE"
) {
const body = property.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(property, newImports, true);
}
} else if (property.isKind(SyntaxKind.PropertyAssignment)) {
const init = property.getInitializer();
if (
init !== undefined &&
(init.isKind(SyntaxKind.ArrowFunction) ||
init.isKind(SyntaxKind.FunctionExpression))
) {
const body = init.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(init, newImports, true);
}
}
}
}
} else if (node.isKind(SyntaxKind.FunctionDeclaration)) {
const body = node.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(node, newImports, false);
}
} else if (name === "default" && decl.length > 0) {
const caller = decl[0];
if (caller.isKind(SyntaxKind.CallExpression)) {
const expr = caller.getExpression();
if (expr.isKind(SyntaxKind.Identifier)) {
const text = expr.getText();
if (
text === "defineApp" || text === "defineLayout" ||
text === "defineRoute"
) {
const args = caller.getArguments();
if (args.length > 0) {
const first = args[0];
if (
first.isKind(SyntaxKind.ArrowFunction) ||
first.isKind(SyntaxKind.FunctionExpression)
) {
const body = first.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(first, newImports, false);
}
}
}
}
} else if (caller.isKind(SyntaxKind.FunctionDeclaration)) {
const body = caller.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(caller, newImports, false);
}
}
}
}
let hasCoreImport = false;
let hasRuntimeImport = false;
for (const d of sourceFile.getImportDeclarations()) {
const specifier = d.getModuleSpecifierValue();
if (specifier === "preact") {
for (const n of d.getNamedImports()) {
const name = n.getName();
if (name === "h" || name === "Fragment") n.remove();
}
removeEmptyImport(d);
} else if (specifier === "$fresh/server.ts") {
hasCoreImport = true;
d.setModuleSpecifier("fresh");
for (const n of d.getNamedImports()) {
const name = n.getName();
newImports.core.delete(name);
if (compat.has(name)) {
n.remove();
newImports.compat.add(name);
}
}
if (newImports.core.size > 0) {
newImports.core.forEach((name) => {
d.addNamedImport(name);
});
}
removeEmptyImport(d);
} else if (specifier === "$fresh/runtime.ts") {
hasRuntimeImport = true;
d.setModuleSpecifier("fresh/runtime");
for (const n of d.getNamedImports()) {
const name = n.getName();
newImports.runtime.delete(name);
}
if (newImports.runtime.size > 0) {
newImports.runtime.forEach((name) => {
d.addNamedImport(name);
});
}
removeEmptyImport(d);
}
}
if (!hasCoreImport && newImports.core.size > 0) {
sourceFile.addImportDeclaration({
moduleSpecifier: "fresh",
namedImports: Array.from(newImports.core),
});
}
if (!hasRuntimeImport && newImports.runtime.size > 0) {
sourceFile.addImportDeclaration({
moduleSpecifier: "fresh/runtime",
namedImports: Array.from(newImports.core),
});
}
if (newImports.compat.size > 0) {
sourceFile.addImportDeclaration({
moduleSpecifier: "fresh/compat",
namedImports: Array.from(newImports.compat),
});
}
await sourceFile.save();
await format(sourceFile.getFilePath());
}
function removeEmptyImport(d: tsmorph.ImportDeclaration) {
if (
d.getNamedImports().length === 0 &&
d.getNamespaceImport() === undefined &&
d.getDefaultImport() === undefined
) {
d.remove();
}
}
function maybePrependReqVar(
method:
| tsmorph.MethodDeclaration
| tsmorph.FunctionDeclaration
| tsmorph.FunctionExpression
| tsmorph.ArrowFunction,
newImports: ImportState,
hasInferredTypes: boolean,
) {
let hasRequestVar = false;
const params = method.getParameters();
if (params.length > 0) {
const paramName = params[0].getName();
// Add explicit types if the user did that
if (hasInferredTypes && params[0].getTypeNode()) {
hasInferredTypes = false;
}
hasRequestVar = params.length > 1 || paramName === "req";
if (hasRequestVar || paramName === "_req") {
if (hasRequestVar && params.length === 1) {
params[0].replaceWithText("ctx");
if (!hasInferredTypes) {
newImports.core.add("FreshContext");
params[0].setType("FreshContext");
}
} else {
params[0].remove();
// Use proper type
if (params.length > 1) {
const initType = params[1].getTypeNode()?.getText();
if (initType !== undefined && initType === "RouteContext") {
newImports.core.add("FreshContext");
params[1].setType("FreshContext");
}
}
}
}
const maybeObjBinding = params.length > 1
? params[1].getNameNode()
: undefined;
if (method.isKind(SyntaxKind.ArrowFunction)) {
const body = method.getBody();
if (!body.isKind(SyntaxKind.Block)) {
// deno-lint-ignore no-console
console.warn(`Cannot transform arrow function`);
return;
}
}
if (
(maybeObjBinding === undefined ||
!maybeObjBinding.isKind(SyntaxKind.ObjectBindingPattern)) &&
hasRequestVar &&
!paramName.startsWith("_")
) {
method.insertVariableStatement(0, {
declarationKind: tsmorph.VariableDeclarationKind.Const,
declarations: [{
name: paramName,
initializer: "ctx.req",
}],
});
}
if (
maybeObjBinding !== undefined &&
maybeObjBinding.isKind(SyntaxKind.ObjectBindingPattern)
) {
const bindings = maybeObjBinding.getElements();
if (bindings.length > 0) {
let needsRemoteAddr = false;
for (let i = 0; i < bindings.length; i++) {
const binding = bindings[i];
const name = binding.getName();
if (name === "remoteAddr") {
binding.replaceWithText("info");
needsRemoteAddr = true;
}
}
if (hasRequestVar && !paramName.startsWith("_")) {
const txt = maybeObjBinding.getFullText().slice(0, -2);
maybeObjBinding.replaceWithText(txt + ", req }");
}
if (needsRemoteAddr) {
method.insertVariableStatement(0, {
declarationKind: tsmorph.VariableDeclarationKind.Const,
declarations: [{
name: "remoteAddr",
initializer: "info.remoteAddr",
}],
});
}
}
}
}
}
function rewriteCtxMethods(
nodes: (tsmorph.Node<tsmorph.ts.Node>)[],
) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node.isKind(SyntaxKind.PropertyAccessExpression)) {
rewriteCtxMemberName(node);
} else if (node.isKind(SyntaxKind.ReturnStatement)) {
const expr = node.getExpression();
if (expr !== undefined) {
rewriteCtxMethods([expr]);
}
} else if (node.isKind(SyntaxKind.VariableStatement)) {
const decls = node.getDeclarations();
for (let i = 0; i < decls.length; i++) {
const decl = decls[i];
const init = decl.getInitializer();
if (init !== undefined) {
rewriteCtxMethods([init]);
}
}
} else if (
node.isKind(SyntaxKind.ExpressionStatement) ||
node.isKind(SyntaxKind.AwaitExpression) ||
node.isKind(SyntaxKind.CallExpression)
) {
const expr = node.getExpression();
rewriteCtxMethods([expr]);
} else if (node.isKind(SyntaxKind.BinaryExpression)) {
rewriteCtxMethods([node.getLeft()]);
rewriteCtxMethods([node.getRight()]);
} else if (
!node.isKind(SyntaxKind.ExpressionStatement) &&
node.getKindName().endsWith("Statement")
) {
const inner = node.getDescendantStatements();
rewriteCtxMethods(inner);
}
}
}
function rewriteCtxMemberName(
node: tsmorph.PropertyAccessExpression,
) {
const children = node.getChildren();
if (children.length === 0) return;
const last = children[children.length - 1];
if (
node.getExpression().getText() === "ctx" &&
node.getName() === "remoteAddr"
) {
node.getExpression().replaceWithText("ctx.info.remoteAddr");
} else if (last.getText() === "renderNotFound") {
last.replaceWithText("throw");
const caller = node.getParentIfKind(SyntaxKind.CallExpression);
if (caller !== undefined) {
caller.addArgument("404");
}
} else if (children[0].isKind(SyntaxKind.PropertyAccessExpression)) {
rewriteCtxMemberName(children[0]);
}
}