Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 2517649

Browse files
committed
Clean up
1 parent a24c4cd commit 2517649

File tree

5 files changed

+65
-46
lines changed

5 files changed

+65
-46
lines changed

server/app.ts

Lines changed: 40 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ export class Application implements ServerApplication {
258258
skip: [
259259
/(^|\/|\\)\./,
260260
/\.d\.ts$/i,
261-
/(\.|_)(test|spec|e2e)\.(tsx?|jsx?|mjs)?$/i
261+
/(\.|_)(test|spec|e2e)\.[a-z]+$/i
262262
]
263263
}
264264

@@ -399,6 +399,7 @@ export class Application implements ServerApplication {
399399
}
400400
}
401401

402+
/** check the changed file whether it is a scoped module */
402403
private isScopedModule(url: string) {
403404
for (const ext of moduleExts) {
404405
if (url.endsWith('.' + ext)) {
@@ -452,14 +453,15 @@ export class Application implements ServerApplication {
452453
return this.config.plugins.filter(isLoaderPlugin)
453454
}
454455

455-
/** returns the module by given url. */
456+
/** get the module by given url. */
456457
getModule(url: string): Module | null {
457458
if (this.#modules.has(url)) {
458459
return this.#modules.get(url)!
459460
}
460461
return null
461462
}
462463

464+
/** find the module by given name. */
463465
findModuleByName(name: string): Module | null {
464466
for (const ext of moduleExts) {
465467
const url = `/${util.trimPrefix(name, '/')}.${ext}`
@@ -470,6 +472,7 @@ export class Application implements ServerApplication {
470472
return null
471473
}
472474

475+
/** lookup style deps of given modules. */
473476
lookupStyleModules(...urls: string[]): Module[] {
474477
const mods: Module[] = []
475478
urls.forEach(url => {
@@ -483,10 +486,12 @@ export class Application implements ServerApplication {
483486
return mods
484487
}
485488

489+
/** get page route by given location. */
486490
getPageRoute(location: { pathname: string, search?: string }): [RouterURL, RouteModule[]] {
487491
return this.#pageRouting.createRouter(location)
488492
}
489493

494+
/** get api route by given location. */
490495
getAPIRoute(location: { pathname: string, search?: string }): [RouterURL, Module] | null {
491496
const router = this.#apiRouting.createRouter(location)
492497
if (router !== null) {
@@ -568,16 +573,19 @@ export class Application implements ServerApplication {
568573
return [status, html]
569574
}
570575

576+
/** get code injects */
571577
getCodeInjects(phase: 'compilation' | 'hmr' | 'ssr') {
572578
return this.#injects.get(phase)
573579
}
574580

581+
/** create a fs watcher. */
575582
createFSWatcher(): EventEmitter {
576583
const e = new EventEmitter()
577584
this.#fsWatchListeners.push(e)
578585
return e
579586
}
580587

588+
/** remove the fs watcher. */
581589
removeFSWatcher(e: EventEmitter) {
582590
e.removeAllListeners()
583591
const index = this.#fsWatchListeners.indexOf(e)
@@ -586,6 +594,7 @@ export class Application implements ServerApplication {
586594
}
587595
}
588596

597+
/** check the module whether it is hmrable. */
589598
isHMRable(url: string) {
590599
if (!this.isDev || util.isLikelyHttpURL(url)) {
591600
return false
@@ -730,7 +739,8 @@ export class Application implements ServerApplication {
730739
]
731740
}
732741

733-
async resolveModule(url: string) {
742+
/** read the module contents. */
743+
async readModule(url: string) {
734744
const { content, contentType } = await this.fetchModule(url)
735745
const source = await this.precompile(url, content, contentType)
736746
if (source === null) {
@@ -739,6 +749,18 @@ export class Application implements ServerApplication {
739749
return source
740750
}
741751

752+
/** parse the export names of the module. */
753+
async parseModuleExportNames(url: string): Promise<string[]> {
754+
const source = await this.readModule(url)
755+
const names = await parseExportNames(url, source.code, { sourceType: source.type })
756+
return (await Promise.all(names.map(async name => {
757+
if (name.startsWith('{') && name.startsWith('}')) {
758+
return await this.parseModuleExportNames(name.slice(1, -1))
759+
}
760+
return name
761+
}))).flat()
762+
}
763+
742764
/** default compiler options */
743765
get sharedCompileOptions(): TransformOptions {
744766
return {
@@ -1002,18 +1024,11 @@ export class Application implements ServerApplication {
10021024
}
10031025
}
10041026

1005-
async parseModuleExportNames(url: string): Promise<string[]> {
1006-
const source = await this.resolveModule(url)
1007-
const names = await parseExportNames(url, source.code, { sourceType: source.type })
1008-
return (await Promise.all(names.map(async name => {
1009-
if (name.startsWith('{') && name.startsWith('}')) {
1010-
return await this.parseModuleExportNames(name.slice(1, -1))
1011-
}
1012-
return name
1013-
}))).flat()
1014-
}
1015-
1016-
/** compile a moudle by given url, then cache on the disk. */
1027+
/**
1028+
* compile a moudle by given url, then cache on the disk.
1029+
* each moudle only be compiled once unless you set the
1030+
* `forceCompile` option to true.
1031+
*/
10171032
private async compile(
10181033
url: string,
10191034
options: {
@@ -1170,7 +1185,7 @@ export class Application implements ServerApplication {
11701185
if (jsContent === '') {
11711186
jsContent = await Deno.readTextFile(mod.jsFile)
11721187
}
1173-
jsContent = this.replaceDepHash(jsContent, dep)
1188+
jsContent = this.updateImportUrls(jsContent, dep)
11741189
if (!fsync) {
11751190
fsync = true
11761191
}
@@ -1179,23 +1194,26 @@ export class Application implements ServerApplication {
11791194
}
11801195
}
11811196

1182-
// update hash by deps
1197+
// update hash using deps status
11831198
if (mod.deps.length > 0) {
11841199
mod.hash = computeHash(mod.sourceHash + mod.deps.map(({ hash }) => hash).join(''))
11851200
}
11861201

11871202
if (fsync) {
1188-
await lazyRemove(util.trimSuffix(mod.jsFile, '.js') + '.bundling.js')
1203+
if (jsSourceMap) {
1204+
jsContent += `//# sourceMappingURL=${basename(mod.jsFile)}.map`
1205+
}
11891206
await Promise.all([
11901207
ensureTextFile(metaFile, JSON.stringify({
11911208
url,
11921209
deps: mod.deps,
11931210
sourceHash: mod.sourceHash,
11941211
isStyle: mod.isStyle ? true : undefined
11951212
}, undefined, 2)),
1196-
ensureTextFile(mod.jsFile, jsContent + (jsSourceMap ? `//# sourceMappingURL=${basename(mod.jsFile)}.map` : '')),
1213+
ensureTextFile(mod.jsFile, jsContent),
11971214
jsSourceMap ? ensureTextFile(mod.jsFile + '.map', jsSourceMap) : Promise.resolve(),
11981215
])
1216+
await lazyRemove(util.trimSuffix(mod.jsFile, '.js') + '.bundling.js')
11991217
}
12001218

12011219
return mod
@@ -1204,11 +1222,10 @@ export class Application implements ServerApplication {
12041222
/** apply compilation side-effect caused by dependency graph breaking. */
12051223
private async applyCompilationSideEffect(url: string, callback: (mod: Module) => void) {
12061224
const { hash } = this.#modules.get(url)!
1207-
12081225
for (const mod of this.#modules.values()) {
12091226
for (const dep of mod.deps) {
12101227
if (dep.url === url) {
1211-
const jsContent = this.replaceDepHash(
1228+
const jsContent = this.updateImportUrls(
12121229
await Deno.readTextFile(mod.jsFile),
12131230
{ url, hash }
12141231
)
@@ -1353,7 +1370,8 @@ export class Application implements ServerApplication {
13531370
return ssr
13541371
}
13551372

1356-
private replaceDepHash(jsContent: string, dep: DependencyDescriptor) {
1373+
/** update the hash in import url of deps. */
1374+
private updateImportUrls(jsContent: string, dep: DependencyDescriptor) {
13571375
const s = `.js#${dep.url}@`
13581376
return jsContent.split(s).map((p, i) => {
13591377
if (i > 0 && p.charAt(6) === '"') {

server/cache.ts

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,28 @@ import { ensureDir } from 'https://deno.land/[email protected]/fs/ensure_dir.ts'
22
import { createHash } from 'https://deno.land/[email protected]/hash/mod.ts'
33
import { join } from 'https://deno.land/[email protected]/path/mod.ts'
44
import { existsFileSync } from '../shared/fs.ts'
5-
import util from '../shared/util.ts'
65
import log from '../shared/log.ts'
6+
import util from '../shared/util.ts'
77
import { getDenoDir } from './helper.ts'
88

9-
/** download and cache remote content */
9+
/** download and cache remote contents */
1010
export async function cache(url: string, options?: { forceRefresh?: boolean, retryTimes?: number }) {
11-
const u = new URL(url)
12-
const { protocol, hostname, port, pathname, search } = u
13-
const isLocalhost = hostname === 'localhost' || hostname === '0.0.0.0' || hostname === '172.0.0.1'
11+
const { protocol, hostname, port, pathname, search } = new URL(url)
12+
const hashname = createHash('sha256').update(pathname + search).toString()
13+
const isLocalhost = hostname === 'localhost' || hostname === '0.0.0.0' || hostname === '127.0.0.1'
1414
const cacheDir = join(
1515
await getDenoDir(),
1616
'deps',
1717
util.trimSuffix(protocol, ':'),
1818
hostname + (port ? '_PORT' + port : '')
1919
)
20-
const hash = createHash('sha256').update(pathname + search).toString()
21-
const contentFile = join(cacheDir, hash)
22-
const metaFile = join(cacheDir, hash + '.metadata.json')
20+
const contentFilepath = join(cacheDir, hashname)
21+
const metaFilepath = join(cacheDir, hashname + '.metadata.json')
2322

24-
if (!options?.forceRefresh && !isLocalhost && existsFileSync(contentFile) && existsFileSync(metaFile)) {
23+
if (!options?.forceRefresh && !isLocalhost && existsFileSync(contentFilepath) && existsFileSync(metaFilepath)) {
2524
const [content, meta] = await Promise.all([
26-
Deno.readFile(contentFile),
27-
Deno.readTextFile(metaFile),
25+
Deno.readFile(contentFilepath),
26+
Deno.readTextFile(metaFilepath),
2827
])
2928
try {
3029
const { headers = {} } = JSON.parse(meta)
@@ -47,7 +46,7 @@ export async function cache(url: string, options?: { forceRefresh?: boolean, ret
4746
log.warn(`Download ${url} failed, retrying...`)
4847
}
4948
try {
50-
const resp = await fetch(u.toString())
49+
const resp = await fetch(url)
5150
if (resp.status >= 400) {
5251
return Promise.reject(new Error(resp.statusText))
5352
}
@@ -59,8 +58,8 @@ export async function cache(url: string, options?: { forceRefresh?: boolean, ret
5958
headers[key] = val
6059
})
6160
await ensureDir(cacheDir)
62-
Deno.writeFile(contentFile, content)
63-
Deno.writeTextFile(metaFile, JSON.stringify({ headers, url }, undefined, 2))
61+
Deno.writeFile(contentFilepath, content)
62+
Deno.writeTextFile(metaFilepath, JSON.stringify({ headers, url }, undefined, 2))
6463
}
6564
return {
6665
content,

server/helper.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
// @deno-types="https://deno.land/x/[email protected]/mod.d.ts"
2-
export { build as esbuild, stop as stopEsbuild } from 'https://deno.land/x/[email protected]/mod.js'
31
import { dim, red, yellow } from 'https://deno.land/[email protected]/fmt/colors.ts'
42
import { createHash } from 'https://deno.land/[email protected]/hash/mod.ts'
53
import { relative } from 'https://deno.land/[email protected]/path/mod.ts'
@@ -9,13 +7,16 @@ import type { ServerPlugin, LoaderPlugin } from '../types.ts'
97
import { VERSION } from '../version.ts'
108
import { localProxy } from './localproxy.ts'
119

10+
// @deno-types="https://deno.land/x/[email protected]/mod.d.ts"
11+
export { build as esbuild, stop as stopEsbuild } from 'https://deno.land/x/[email protected]/mod.js'
12+
1213
export const reLocaleID = /^[a-z]{2}(-[a-zA-Z0-9]+)?$/
1314
export const reFullVersion = /@v?\d+\.\d+\.\d+/i
1415

1516
let __denoDir: string | null = null
1617
let __localProxy = false
1718

18-
/** check whether should proxy https://deno.land/x/aleph on local. */
19+
/** check whether should proxy https://deno.land/x/aleph on localhost. */
1920
export function checkAlephDev() {
2021
const v = Deno.env.get('ALEPH_DEV')
2122
if (v !== undefined && !__localProxy) {
@@ -24,12 +25,12 @@ export function checkAlephDev() {
2425
}
2526
}
2627

27-
/** check the plugin whether is a loader plugin. */
28+
/** check the plugin whether it is a loader. */
2829
export function isLoaderPlugin(plugin: LoaderPlugin | ServerPlugin): plugin is LoaderPlugin {
2930
return plugin.type === 'loader'
3031
}
3132

32-
/** get deno dir. */
33+
/** get the deno cache dir. */
3334
export async function getDenoDir() {
3435
if (__denoDir !== null) {
3536
return __denoDir
@@ -100,7 +101,7 @@ export function computeHash(content: string | Uint8Array): string {
100101
}
101102

102103
/**
103-
* colorful the bytes string
104+
* coloring the bytes string
104105
* - dim: 0 - 1MB
105106
* - yellow: 1MB - 10MB
106107
* - red: > 10MB

server/oak.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { Middleware, Context } from 'https://deno.land/x/oak/mod.ts'
1+
import type { Context } from 'https://deno.land/x/[email protected]/context.ts'
2+
import type { Middleware } from 'https://deno.land/x/[email protected]/middleware.ts'
23
import { Application } from './app.ts'
34
import { Server } from './server.ts'
45

@@ -7,8 +8,7 @@ export function alephOak(app: Application): Middleware {
78
const server = new Server(app)
89

910
return (ctx: Context) => {
10-
const req = ctx.request as any
11-
server.handle(req.originalRequest || req.serverRequest)
11+
server.handle(ctx.request.originalRequest)
1212
ctx.respond = false
1313
}
1414
}

server/stdserver.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ export type ServeOptions = {
1212
/** The port to listen on. */
1313
port: number
1414
/** A literal IP address or host name that can be resolved to an IP address.
15-
* If not specified, defaults to `0.0.0.0`. */
15+
* If not specified, defaults to `0.0.0.0`.
16+
*/
1617
hostname?: string
1718
/** Server certificate file. */
1819
certFile?: string

0 commit comments

Comments
 (0)