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

Commit 9a46893

Browse files
committed
refactor: clean up
1 parent 54099fb commit 9a46893

File tree

7 files changed

+51
-62
lines changed

7 files changed

+51
-62
lines changed

framework/core/routing.ts

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { pageModuleExts } from '../../shared/constants.ts'
1+
import { moduleExts } from '../../shared/constants.ts'
22
import util from '../../shared/util.ts'
33
import type { DependencyDescriptor, RouterURL } from '../../types.ts'
44
import events from './events.ts'
@@ -232,7 +232,7 @@ export function isHttpUrl(url: string) {
232232
}
233233

234234
export function isModuleURL(url: string) {
235-
for (const ext of pageModuleExts) {
235+
for (const ext of moduleExts) {
236236
if (url.endsWith('.' + ext)) {
237237
return true
238238
}
@@ -241,7 +241,7 @@ export function isModuleURL(url: string) {
241241
}
242242

243243
export function toPagePath(url: string): string {
244-
let pathname = trimModuleExt(url)
244+
let pathname = util.trimModuleExt(url)
245245
if (pathname.startsWith('/pages/')) {
246246
pathname = util.trimPrefix(pathname, '/pages')
247247
}
@@ -253,12 +253,3 @@ export function toPagePath(url: string): string {
253253
}
254254
return pathname
255255
}
256-
257-
export function trimModuleExt(url: string) {
258-
for (const ext of pageModuleExts) {
259-
if (url.endsWith('.' + ext)) {
260-
return url.slice(0, -(ext.length + 1))
261-
}
262-
}
263-
return url
264-
}

framework/react/bootstrap.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import type { ComponentType } from 'https://esm.sh/react'
22
import { createElement } from 'https://esm.sh/react'
33
import { hydrate, render } from 'https://esm.sh/react-dom'
4-
import { Route, RouteModule, Routing, trimModuleExt } from '../core/routing.ts'
4+
import util from "../../shared/util.ts"
5+
import { Route, RouteModule, Routing } from '../core/routing.ts'
56
import type { PageRoute } from './pageprops.ts'
67
import { createPageProps } from './pageprops.ts'
78
import Router from './router.ts'
@@ -22,7 +23,7 @@ export default async function bootstrap(options: Options) {
2223
const customComponents: Record<string, ComponentType> = {}
2324
await Promise.all(sharedModules.map(async mod => {
2425
const { default: C } = await importModule(baseUrl, mod)
25-
switch (trimModuleExt(mod.url)) {
26+
switch (util.trimModuleExt(mod.url)) {
2627
case '/404':
2728
customComponents['E404'] = C
2829
break

framework/react/util.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { createContext } from 'https://esm.sh/react'
22
import util from '../../shared/util.ts'
33
import type { RouterURL } from '../../types.ts'
4-
import { trimModuleExt } from '../core/routing.ts'
54

65
const symbolFor = typeof Symbol === 'function' && Symbol.for
76
const REACT_FORWARD_REF_TYPE = symbolFor ? Symbol.for('react.forward_ref') : 0xead0
@@ -50,7 +49,7 @@ export function importModule(baseUrl: string, mod: { url: string, hash: string }
5049
}
5150

5251
if (ALEPH && mod.url.startsWith('/pages/')) {
53-
const src = util.cleanPath(baseUrl + '/_aleph/' + trimModuleExt(mod.url) + `.bundle.${util.shortHash(mod.hash)}.js`)
52+
const src = util.cleanPath(baseUrl + '/_aleph/' + util.trimModuleExt(mod.url) + `.bundle.${util.shortHash(mod.hash)}.js`)
5453
return new Promise((resolve, reject) => {
5554
const script = document.createElement('script')
5655
script.onload = () => {
@@ -64,7 +63,7 @@ export function importModule(baseUrl: string, mod: { url: string, hash: string }
6463
})
6564
}
6665

67-
const src = util.cleanPath(baseUrl + '/_aleph/' + trimModuleExt(mod.url) + `.${util.shortHash(mod.hash)}.js`) + (forceRefetch ? `?t=${Date.now()}` : '')
66+
const src = util.cleanPath(baseUrl + '/_aleph/' + util.trimModuleExt(mod.url) + `.${util.shortHash(mod.hash)}.js`) + (forceRefetch ? `?t=${Date.now()}` : '')
6867
return import(src)
6968
}
7069

server/app.ts

Lines changed: 30 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import { buildChecksum, initWasm, SWCOptions, TransformOptions, transpileSync }
22
import type { AcceptedPlugin, ECMA } from '../deps.ts'
33
import { CleanCSS, colors, ensureDir, minify, path, postcss, Sha256, walk } from '../deps.ts'
44
import { EventEmitter } from '../framework/core/events.ts'
5-
import { isModuleURL, RouteModule, Routing, toPagePath, trimModuleExt } from '../framework/core/routing.ts'
6-
import { defaultReactVersion, minDenoVersion, pageModuleExts } from '../shared/constants.ts'
5+
import { isModuleURL, RouteModule, Routing, toPagePath } from '../framework/core/routing.ts'
6+
import { defaultReactVersion, minDenoVersion, moduleExts } from '../shared/constants.ts'
77
import { ensureTextFile, existsDirSync, existsFileSync, lazyRemove } from '../shared/fs.ts'
88
import log from '../shared/log.ts'
99
import util from '../shared/util.ts'
@@ -87,8 +87,8 @@ export class Application {
8787
if (url.endsWith('.' + ext)) {
8888
return url.startsWith('/pages/') ||
8989
url.startsWith('/components/') ||
90-
trimModuleExt(url) === '/app' ||
91-
trimModuleExt(url) === '/404'
90+
util.trimModuleExt(url) === '/app' ||
91+
util.trimModuleExt(url) === '/404'
9292
}
9393
}
9494
for (const plugin of this.config.plugins) {
@@ -117,7 +117,7 @@ export class Application {
117117
if (/[a-z]/.test(ext)) {
118118
if (ext === 'css' || ext === 'pcss') {
119119
mod.loader = 'css'
120-
} else if (pageModuleExts.includes(ext)) {
120+
} else if (moduleExts.includes(ext)) {
121121
if (ext === 'mjs') {
122122
mod.loader = 'js'
123123
} else {
@@ -506,7 +506,7 @@ export class Application {
506506
const t = performance.now()
507507
const alephPkgUrl = getAlephPkgUrl()
508508
const { env, framework, plugins, ssr } = this.config
509-
const walkOptions = { includeDirs: false, exts: ['.ts', '.js', '.mjs'], skip: [/^\./, /\.d\.ts$/i, /\.(test|spec|e2e)\.m?(j|t)sx?$/i] }
509+
const walkOptions = { includeDirs: false, exts: moduleExts, skip: [/^\./, /\.d\.ts$/i, /\.(test|spec|e2e)\.m?(j|t)sx?$/i] }
510510
const apiDir = path.join(this.srcDir, 'api')
511511
const pagesDir = path.join(this.srcDir, 'pages')
512512

@@ -561,20 +561,14 @@ export class Application {
561561
}
562562

563563
// check custom components
564-
for await (const { path: p, } of walk(this.srcDir, { ...walkOptions, maxDepth: 1, exts: [...walkOptions.exts, '.tsx', '.jsx'] })) {
564+
for await (const { path: p, } of walk(this.srcDir, { ...walkOptions, maxDepth: 1 })) {
565565
const name = path.basename(p)
566-
let isCustom = true
567-
switch (trimModuleExt(name)) {
566+
switch (util.trimModuleExt(name)) {
568567
case 'app':
569568
case '404':
570569
case 'loading':
570+
await this.compile('/' + name)
571571
break
572-
default:
573-
isCustom = false
574-
break
575-
}
576-
if (isCustom) {
577-
await this.compile('/' + name)
578572
}
579573
}
580574

@@ -587,7 +581,7 @@ export class Application {
587581
}
588582

589583
// create page routing
590-
for await (const { path: p } of walk(pagesDir, { ...walkOptions, exts: [...walkOptions.exts, '.tsx', '.jsx', '.md'] })) {
584+
for await (const { path: p } of walk(pagesDir, { ...walkOptions })) {
591585
const mod = await this.compile(util.cleanPath('/pages/' + util.trimPrefix(p, pagesDir)))
592586
this.#pageRouting.update(this.getRouteModule(mod))
593587
}
@@ -626,15 +620,10 @@ export class Application {
626620

627621
log.debug(`init project in ${Math.round(performance.now() - t)}ms`)
628622

629-
if (this.isDev) {
630-
this.watch()
631-
} else {
632-
this.#modules.forEach(({ url }) => {
633-
if (!util.isLikelyHttpURL(url)) {
634-
this.checkCompilationSideEffect(url)
635-
}
636-
})
623+
if (!this.isDev) {
637624
await this.bundle()
625+
} else {
626+
this.watch()
638627
}
639628
}
640629

@@ -656,7 +645,7 @@ export class Application {
656645
if (url.startsWith('/pages/') || url.startsWith('/api/')) {
657646
return true
658647
}
659-
switch (trimModuleExt(url)) {
648+
switch (util.trimModuleExt(url)) {
660649
case '/404':
661650
case '/app':
662651
return true
@@ -685,12 +674,14 @@ export class Application {
685674
this.compile(url, { forceCompile: true }).then(mod => {
686675
const hmrable = this.isHMRable(mod.url)
687676
const update = ({ url, hash }: Module) => {
688-
if (trimModuleExt(url) === '/app') {
677+
if (util.trimModuleExt(url) === '/app') {
689678
this.#renderCache.clear()
690679
} else if (url.startsWith('/pages/')) {
691680
this.#renderCache.delete(toPagePath(url))
692-
this.#pageRouting.update(this.getRouteModule({ url, hash }))
693-
} else if (url.startsWith('/api/')) {
681+
if (type === 'add') {
682+
this.#pageRouting.update(this.getRouteModule({ url, hash }))
683+
}
684+
} else if (url.startsWith('/api/') && type === 'add') {
694685
this.#apiRouting.update(this.getRouteModule({ url, hash }))
695686
}
696687
}
@@ -712,7 +703,7 @@ export class Application {
712703
log.error(`compile(${url}):`, err.message)
713704
})
714705
} else if (this.#modules.has(url)) {
715-
if (trimModuleExt(url) === '/app') {
706+
if (util.trimModuleExt(url) === '/app') {
716707
this.#renderCache.clear()
717708
} else if (url.startsWith('/pages/')) {
718709
this.#renderCache.delete(toPagePath(url))
@@ -748,7 +739,7 @@ export class Application {
748739
locales: [],
749740
routes: this.#pageRouting.routes,
750741
sharedModules: Array.from(this.#modules.values()).filter(({ url }) => {
751-
switch (trimModuleExt(url)) {
742+
switch (util.trimModuleExt(url)) {
752743
case '/404':
753744
case '/app':
754745
return true
@@ -777,7 +768,7 @@ export class Application {
777768
if (isRemote) {
778769
const url = new URL(importUrl)
779770
let pathname = url.pathname
780-
let ok = [...pageModuleExts, 'css', 'pcss'].includes(path.extname(pathname).slice(1))
771+
let ok = [...moduleExts, 'css', 'pcss'].includes(path.extname(pathname).slice(1))
781772
if (ok) {
782773
for (const plugin of this.config.plugins) {
783774
if (plugin.type === 'loader' && plugin.test.test(pathname)) {
@@ -887,7 +878,7 @@ export class Application {
887878
const alephPkgUrl = getAlephPkgUrl()
888879
const isRemote = util.isLikelyHttpURL(url)
889880
const localUrl = this.fixImportUrl(url)
890-
const name = trimModuleExt(path.basename(localUrl))
881+
const name = util.trimModuleExt(path.basename(localUrl))
891882
const saveDir = path.join(this.buildDir, path.dirname(localUrl))
892883
const metaFile = path.join(saveDir, `${name}.meta.json`)
893884
const { sourceCode, forceCompile, bundleMode, bundledModules } = options ?? {}
@@ -1131,7 +1122,7 @@ export class Application {
11311122
if (!util.isLikelyHttpURL(dep.url)) {
11321123
const relativePathname = getRelativePath(
11331124
path.dirname(url),
1134-
trimModuleExt(dep.url)
1125+
util.trimModuleExt(dep.url)
11351126
)
11361127
if (!changed && jsContent === '') {
11371128
if (!bundleMode) {
@@ -1195,7 +1186,6 @@ export class Application {
11951186
}
11961187

11971188
/** check compilation side-effect caused by dependency graph. */
1198-
// use browser native import maps to hand changes in the future.
11991189
private async checkCompilationSideEffect(url: string, callback?: (mod: Module) => void) {
12001190
const { hash, sourceHash } = this.#modules.get(url)!
12011191

@@ -1207,7 +1197,7 @@ export class Application {
12071197
dep.hash = hash
12081198
const relativePath = getRelativePath(
12091199
path.dirname(mod.url),
1210-
trimModuleExt(dep.url)
1200+
util.trimModuleExt(dep.url)
12111201
)
12121202
let jsContent = await Deno.readTextFile(mod.jsFile)
12131203
jsContent = jsContent.replace(reHashResolve, (s, key, spaces, ql, importPath, qr) => {
@@ -1312,8 +1302,8 @@ export class Application {
13121302
}
13131303
}
13141304
const mods = Array.from(this.#modules.values())
1315-
const appModule = mods.find(({ url }) => trimModuleExt(url) == '/app')
1316-
const e404Module = mods.find(({ url }) => trimModuleExt(url) == '/404')
1305+
const appModule = mods.find(({ url }) => util.trimModuleExt(url) == '/app')
1306+
const e404Module = mods.find(({ url }) => util.trimModuleExt(url) == '/404')
13171307
const pageModules: Module[] = []
13181308

13191309
// add framework bootstrap
@@ -1608,7 +1598,7 @@ export class Application {
16081598
return await this.render404Page(url)
16091599
}
16101600
try {
1611-
const appModule = Array.from(this.#modules.values()).find(({ url }) => trimModuleExt(url) == '/app')
1601+
const appModule = Array.from(this.#modules.values()).find(({ url }) => util.trimModuleExt(url) == '/app')
16121602
const { default: App } = appModule ? await import('file://' + appModule.jsFile) : {} as any
16131603
const imports = pageModuleChain.map(async ({ url }) => {
16141604
const mod = this.#modules.get(url)!
@@ -1678,7 +1668,7 @@ export class Application {
16781668
const ret: RenderResult = { url, status: 404, head: [], scripts: [], body: '<div id="__aleph"></div>', data: null }
16791669
try {
16801670
const e404Module = Array.from(this.#modules.keys())
1681-
.filter(url => trimModuleExt(url) == '/404')
1671+
.filter(url => util.trimModuleExt(url) == '/404')
16821672
.map(url => this.#modules.get(url))[0]
16831673
const { default: E404 } = e404Module ? await import('file://' + e404Module.jsFile) : {} as any
16841674
const { head, body, data, scripts } = await this.#renderer.render(
@@ -1708,9 +1698,7 @@ export class Application {
17081698

17091699
/** render custom loading page for SPA mode. */
17101700
private async renderLoadingPage() {
1711-
const loadingModule = Array.from(this.#modules.keys())
1712-
.filter(url => trimModuleExt(url) == '/loading')
1713-
.map(url => this.#modules.get(url))[0]
1701+
const loadingModule = Array.from(this.#modules.values()).find(({ url }) => util.trimModuleExt(url) === '/loading')
17141702
if (loadingModule) {
17151703
const { default: Loading } = await import('file://' + loadingModule.jsFile)
17161704
const router = {

server/server.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { path, serve as stdServe, ws } from '../deps.ts'
2-
import { RouteModule, trimModuleExt } from '../framework/core/routing.ts'
2+
import { RouteModule } from '../framework/core/routing.ts'
33
import { existsFileSync } from '../shared/fs.ts'
44
import log from '../shared/log.ts'
55
import util from '../shared/util.ts'
@@ -51,7 +51,7 @@ export class Server {
5151
watcher.on('modify-' + mod.url, (hash: string) => socket.send(JSON.stringify({
5252
type: 'update',
5353
url: mod.url,
54-
updateUrl: util.cleanPath(`${app.config.baseUrl}/_aleph/${trimModuleExt(mod.url)}.${util.shortHash(hash!)}.js`),
54+
updateUrl: util.cleanPath(`${app.config.baseUrl}/_aleph/${util.trimModuleExt(mod.url)}.${util.shortHash(hash!)}.js`),
5555
hash,
5656
})))
5757
}

shared/constants.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
export const pageModuleExts = ['tsx', 'jsx', 'ts', 'js', 'mjs']
1+
export const moduleExts = ['tsx', 'jsx', 'ts', 'js', 'mjs']
22
export const defaultReactVersion = '17.0.1'
33
export const minDenoVersion = '1.7.0'

shared/util.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { moduleExts } from './constants.ts'
2+
13
export default {
24
inDeno(): boolean {
35
return typeof Deno !== 'undefined' && this.isNEString(Deno.version?.deno)
@@ -39,6 +41,14 @@ export default {
3941
}
4042
return s
4143
},
44+
trimModuleExt(url: string) {
45+
for (const ext of moduleExts) {
46+
if (url.endsWith('.' + ext)) {
47+
return url.slice(0, -(ext.length + 1))
48+
}
49+
}
50+
return url
51+
},
4252
ensureExt(s: string, ext: string): string {
4353
if (s.endsWith(ext)) {
4454
return s

0 commit comments

Comments
 (0)