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

Commit 9038e7e

Browse files
author
Je
committed
refactor: cleanup
1 parent 944e0de commit 9038e7e

File tree

10 files changed

+124
-104
lines changed

10 files changed

+124
-104
lines changed

aleph.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,10 @@ export function ALEPH({ initial }: {
208208
)
209209
}
210210

211+
export function getModuleImportUrl(baseUrl: string, mod: RouteModule, forceRefetch = false) {
212+
return util.cleanPath(baseUrl + '/_aleph/' + util.trimSuffix(mod.id, '.js') + `.${mod.hash.slice(0, hashShort)}.js` + (forceRefetch ? `?t=${Date.now()}` : ''))
213+
}
214+
211215
export async function redirect(url: string, replace?: boolean) {
212216
const { location, history } = window as any
213217

@@ -228,7 +232,3 @@ export async function redirect(url: string, replace?: boolean) {
228232
}
229233
events.emit('popstate', { type: 'popstate', resetScroll: true })
230234
}
231-
232-
export function getModuleImportUrl(baseUrl: string, mod: RouteModule, forceRefetch = false) {
233-
return util.cleanPath(baseUrl + '/_aleph/' + util.trimSuffix(mod.id, '.js') + `.${mod.hash.slice(0, hashShort)}.js` + (forceRefetch ? `?t=${Date.now()}` : ''))
234-
}

cli.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { Request } from './api.ts'
2+
import { existsDirSync, existsFileSync } from './fs.ts'
23
import { createHtml } from './html.ts'
34
import log from './log.ts'
45
import { getContentType } from './mime.ts'
56
import { listenAndServe, path, ServerRequest, walk } from './std.ts'
6-
import util, { existsDirSync, existsFileSync } from './util.ts'
7+
import util from './util.ts'
78
import { version } from './version.ts'
89

910
const commands = {

cli/init.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { gzipDecode } from 'https://deno.land/x/[email protected]/mod.ts'
2+
import { ensureTextFile } from '../fs.ts'
23
import log from '../log.ts'
3-
import { colors, ensureDir, ensureFile, fromStreamReader, path, Untar } from '../std.ts'
4+
import { colors, ensureDir, fromStreamReader, path, Untar } from '../std.ts'
45
import util from '../util.ts'
56

67
const gitignore = [
@@ -59,7 +60,7 @@ export default async function (appDir: string, options: Record<string, string |
5960
await ensureDir(fp)
6061
continue
6162
}
62-
await ensureFile(fp)
63+
await ensureTextFile(fp, '')
6364
const file = await Deno.open(fp, { write: true })
6465
await Deno.copy(entry, file)
6566
}

fs.ts

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { ensureDir, path } from './std.ts'
2+
3+
export async function existsDir(path: string) {
4+
try {
5+
const fi = await Deno.lstat(path)
6+
if (fi.isDirectory) {
7+
return true
8+
}
9+
return false
10+
} catch (err) {
11+
if (err instanceof Deno.errors.NotFound) {
12+
return false
13+
}
14+
throw err
15+
}
16+
}
17+
18+
export function existsDirSync(path: string) {
19+
try {
20+
const fi = Deno.lstatSync(path)
21+
if (fi.isDirectory) {
22+
return true
23+
}
24+
return false
25+
} catch (err) {
26+
if (err instanceof Deno.errors.NotFound) {
27+
return false
28+
}
29+
throw err
30+
}
31+
}
32+
33+
export async function existsFile(path: string) {
34+
try {
35+
const fi = await Deno.lstat(path)
36+
if (fi.isFile) {
37+
return true
38+
}
39+
return false
40+
} catch (err) {
41+
if (err instanceof Deno.errors.NotFound) {
42+
return false
43+
}
44+
throw err
45+
}
46+
}
47+
48+
export function existsFileSync(path: string) {
49+
try {
50+
const fi = Deno.lstatSync(path)
51+
if (fi.isFile) {
52+
return true
53+
}
54+
return false
55+
} catch (err) {
56+
if (err instanceof Deno.errors.NotFound) {
57+
return false
58+
}
59+
throw err
60+
}
61+
}
62+
63+
/** ensure and write a text file */
64+
export async function ensureTextFile(name: string, content: string) {
65+
const dir = path.dirname(name)
66+
await ensureDir(dir)
67+
await Deno.writeTextFile(name, content)
68+
}

head.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ export const serverHeadElements: Map<string, { type: string, props: Record<strin
55
export const serverScriptsElements: Map<string, { type: string, props: Record<string, any> }> = new Map()
66
export const serverStyles: Map<string, { css: string, asLink: boolean }> = new Map()
77

8-
export default function Head({ children }: PropsWithChildren<{}>) {
8+
export default function Head(props: PropsWithChildren<{}>) {
99
if (window.Deno) {
10-
parse(children).forEach(({ type, props }, key) => serverHeadElements.set(key, { type, props }))
10+
parse(props.children).forEach(({ type, props }, key) => serverHeadElements.set(key, { type, props }))
1111
}
1212

1313
useEffect(() => {
1414
const doc = (window as any).document
15-
const nodes = parse(children)
15+
const nodes = parse(props.children)
1616
const insertedEls: Array<Object> = []
1717

1818
if (nodes.size > 0) {
@@ -53,14 +53,14 @@ export default function Head({ children }: PropsWithChildren<{}>) {
5353
return () => {
5454
insertedEls.forEach(el => doc.head.removeChild(el))
5555
}
56-
}, [children])
56+
}, [props.children])
5757

5858
return null
5959
}
6060

61-
export function Scripts({ children }: PropsWithChildren<{}>) {
61+
export function Scripts(props: PropsWithChildren<{}>) {
6262
if (window.Deno) {
63-
parse(children).forEach(({ type, props }, key) => {
63+
parse(props.children).forEach(({ type, props }, key) => {
6464
if (type === 'script') {
6565
serverScriptsElements.set(key, { type, props })
6666
}
@@ -85,7 +85,8 @@ interface SEOProps {
8585
}
8686
}
8787

88-
export function SEO({ title, description, keywords, url, image, twitter }: SEOProps) {
88+
export function SEO(props: SEOProps) {
89+
const { title, description, keywords, url, image, twitter } = props
8990
return createElement(
9091
Head,
9192
undefined,

link.ts

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import events from './events.ts'
44
import { useRouter } from './hooks.ts'
55
import util, { reModuleExt } from './util.ts'
66

7+
const prefetchedPageModules = new Set<string>()
8+
79
interface LinkProps {
810
to: string
911
replace?: boolean
@@ -12,16 +14,8 @@ interface LinkProps {
1214
style?: CSSProperties
1315
}
1416

15-
const fetchedPageModules = new Set<string>()
16-
17-
export default function Link({
18-
to,
19-
replace = false,
20-
prefetch: prefetchImmediately = false,
21-
className,
22-
style,
23-
children
24-
}: PropsWithChildren<LinkProps>) {
17+
export default function Link(props: PropsWithChildren<LinkProps>) {
18+
const { to, replace = false, prefetch: prefetchNow = false, className, style, children } = props
2519
const { pathname: currentPathname, query: currentQuery } = useRouter()
2620
const currentHref = useMemo(() => {
2721
return [currentPathname, currentQuery.toString()].filter(Boolean).join('?')
@@ -39,9 +33,9 @@ export default function Link({
3933
return [pathname, search].filter(Boolean).join('?')
4034
}, [currentPathname, to])
4135
const prefetch = useCallback(() => {
42-
if (!util.isHttpUrl(href) && href !== currentHref && !fetchedPageModules.has(href)) {
36+
if (!util.isHttpUrl(href) && href !== currentHref && !prefetchedPageModules.has(href)) {
4337
events.emit('fetch-page-module', { href })
44-
fetchedPageModules.add(href)
38+
prefetchedPageModules.add(href)
4539
}
4640
}, [href, currentHref])
4741
const onClick = useCallback((e: MouseEvent) => {
@@ -52,10 +46,10 @@ export default function Link({
5246
}, [href, currentHref, replace])
5347

5448
useEffect(() => {
55-
if (prefetchImmediately) {
49+
if (prefetchNow) {
5650
prefetch()
5751
}
58-
}, [prefetchImmediately, prefetch])
52+
}, [prefetchNow, prefetch])
5953

6054
if (Children.count(children) === 1) {
6155
const child = Children.toArray(children)[0]
@@ -106,12 +100,8 @@ interface NavLinkProps extends LinkProps {
106100
activeStyle?: CSSProperties
107101
}
108102

109-
export function NavLink({
110-
activeClassName = 'active',
111-
activeStyle,
112-
to,
113-
...rest
114-
}: PropsWithChildren<NavLinkProps>) {
103+
export function NavLink(props: PropsWithChildren<NavLinkProps>) {
104+
const { activeClassName = 'active', activeStyle, to, ...rest } = props
115105
const { pathname: currentPathname } = useRouter()
116106
const pathname = useMemo(() => {
117107
if (util.isHttpUrl(to)) {

project.ts

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import { minify } from 'https://esm.sh/[email protected]'
44
import { safeLoadFront } from 'https://esm.sh/[email protected]'
55
import { Request } from './api.ts'
66
import { EventEmitter } from './events.ts'
7+
import { ensureTextFile, existsDirSync, existsFileSync } from './fs.ts'
78
import { createHtml } from './html.ts'
89
import log from './log.ts'
910
import { getPagePath, RouteModule, Routing } from './routing.ts'
1011
import { colors, ensureDir, fromStreamReader, path, ServerRequest, Sha1, walk } from './std.ts'
1112
import { compile } from './tsc/compile.ts'
1213
import type { AlephEnv, APIHandler, Config, RouterURL } from './types.ts'
13-
import util, { existsDirSync, existsFileSync, hashShort, MB, reHashJs, reHttp, reLocaleID, reMDExt, reModuleExt, reStyleModuleExt } from './util.ts'
14+
import util, { hashShort, MB, reHashJs, reHttp, reLocaleID, reMDExt, reModuleExt, reStyleModuleExt } from './util.ts'
1415
import { cleanCSS, Document, less } from './vendor/mod.ts'
1516
import { version } from './version.ts'
1617

@@ -341,10 +342,10 @@ export class Project {
341342
const [status, html, data] = await this.getPageHtml({ pathname })
342343
if (status == 200) {
343344
const htmlFile = path.join(outputDir, pathname, 'index.html')
344-
await writeTextFile(htmlFile, html)
345+
await ensureTextFile(htmlFile, html)
345346
if (data) {
346347
const dataFile = path.join(outputDir, '_aleph/data', pathname, 'data.js')
347-
await writeTextFile(dataFile, `export default ` + JSON.stringify(data))
348+
await ensureTextFile(dataFile, `export default ` + JSON.stringify(data))
348349
}
349350
log.info(' ○', pathname, colors.dim('• ' + util.bytesString(html.length)))
350351
} else if (status == 404) {
@@ -355,9 +356,9 @@ export class Project {
355356
}
356357
}))
357358
const fbHtmlFile = path.join(outputDir, util.isPlainObject(ssr) && ssr.fallback ? ssr.fallback : '_fallback.html')
358-
await writeTextFile(fbHtmlFile, SPAIndexHtml)
359+
await ensureTextFile(fbHtmlFile, SPAIndexHtml)
359360
} else {
360-
await writeTextFile(path.join(outputDir, 'index.html'), SPAIndexHtml)
361+
await ensureTextFile(path.join(outputDir, 'index.html'), SPAIndexHtml)
361362
}
362363

363364
// write 404 page
@@ -376,7 +377,7 @@ export class Project {
376377
body,
377378
minify: !this.isDev
378379
})
379-
await writeTextFile(path.join(outputDir, '404.html'), e404PageHtml)
380+
await ensureTextFile(path.join(outputDir, '404.html'), e404PageHtml)
380381

381382
// copy public assets
382383
const publicDir = path.join(this.appRoot, 'public')
@@ -419,8 +420,8 @@ export class Project {
419420
}
420421
}
421422
return Promise.all([
422-
writeTextFile(jsFile, jsContent),
423-
sourceMap && jsSourceMap ? writeTextFile(jsFile + '.map', jsSourceMap) : Promise.resolve(),
423+
ensureTextFile(jsFile, jsContent),
424+
sourceMap && jsSourceMap ? ensureTextFile(jsFile + '.map', jsSourceMap) : Promise.resolve(),
424425
])
425426
}))
426427

@@ -559,6 +560,7 @@ export class Project {
559560
Object.assign(globalThis, {
560561
ALEPH: {
561562
ENV: {
563+
...Deno.env.toObject(),
562564
...this.config.env,
563565
__version: version,
564566
__buildMode: this.mode,
@@ -832,7 +834,6 @@ export class Project {
832834
'import "./-/deno.land/x/aleph/routing.js";',
833835
'import "./-/deno.land/x/aleph/util.js";',
834836
'import bootstrap from "./-/deno.land/x/aleph/bootstrap.js";',
835-
`Object.assign(window, ${JSON.stringify({ ALEPH: (globalThis as any)['ALEPH'] }, undefined, this.isDev ? 4 : undefined)});`,
836837
`bootstrap(${JSON.stringify(config, undefined, this.isDev ? 4 : undefined)});`
837838
].filter(Boolean).join(this.isDev ? '\n' : '')
838839
module.hash = getHash(module.jsContent)
@@ -847,8 +848,8 @@ export class Project {
847848

848849
await cleanupCompilation(module.jsFile)
849850
await Promise.all([
850-
writeTextFile(module.jsFile, module.jsContent),
851-
writeTextFile(metaFile, JSON.stringify({
851+
ensureTextFile(module.jsFile, module.jsContent),
852+
ensureTextFile(metaFile, JSON.stringify({
852853
url: '/main.js',
853854
sourceHash: module.hash,
854855
hash: module.hash,
@@ -1134,14 +1135,14 @@ export class Project {
11341135
mod.jsFile = path.join(saveDir, name + (mod.isRemote ? '' : `.${mod.hash.slice(0, hashShort)}`)) + '.js'
11351136
await cleanupCompilation(mod.jsFile)
11361137
await Promise.all([
1137-
writeTextFile(metaFile, JSON.stringify({
1138+
ensureTextFile(metaFile, JSON.stringify({
11381139
url,
11391140
sourceHash: mod.sourceHash,
11401141
hash: mod.hash,
11411142
deps: mod.deps,
11421143
}, undefined, 4)),
1143-
writeTextFile(mod.jsFile, mod.jsContent),
1144-
mod.jsSourceMap !== '' ? writeTextFile(mod.jsFile + '.map', mod.jsSourceMap) : Promise.resolve()
1144+
ensureTextFile(mod.jsFile, mod.jsContent),
1145+
mod.jsSourceMap !== '' ? ensureTextFile(mod.jsFile + '.map', mod.jsSourceMap) : Promise.resolve()
11451146
])
11461147
}
11471148

@@ -1172,14 +1173,14 @@ export class Project {
11721173
mod.hash = getHash(mod.jsContent)
11731174
mod.jsFile = `${mod.jsFile.replace(reHashJs, '')}.${mod.hash.slice(0, hashShort)}.js`
11741175
Promise.all([
1175-
writeTextFile(mod.jsFile.replace(reHashJs, '') + '.meta.json', JSON.stringify({
1176+
ensureTextFile(mod.jsFile.replace(reHashJs, '') + '.meta.json', JSON.stringify({
11761177
sourceFile: mod.url,
11771178
sourceHash: mod.sourceHash,
11781179
hash: mod.hash,
11791180
deps: mod.deps,
11801181
}, undefined, 4)),
1181-
writeTextFile(mod.jsFile, mod.jsContent),
1182-
mod.jsSourceMap !== '' ? writeTextFile(mod.jsFile + '.map', mod.jsSourceMap) : Promise.resolve()
1182+
ensureTextFile(mod.jsFile, mod.jsContent),
1183+
mod.jsSourceMap !== '' ? ensureTextFile(mod.jsFile + '.map', mod.jsSourceMap) : Promise.resolve()
11831184
])
11841185
}
11851186
callback(mod)
@@ -1539,10 +1540,3 @@ async function cleanupCompilation(jsFile: string) {
15391540
}
15401541
}
15411542
}
1542-
1543-
/** ensure and write text file */
1544-
async function writeTextFile(filepath: string, content: string) {
1545-
const dir = path.dirname(filepath)
1546-
await ensureDir(dir)
1547-
await Deno.writeTextFile(filepath, content)
1548-
}

server.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { Request } from './api.ts'
2+
import { existsFileSync } from './fs.ts'
23
import { createHtml } from './html.ts'
34
import log from './log.ts'
45
import { getContentType } from './mime.ts'
56
import { injectHmr, Project } from './project.ts'
67
import { path, serve, ws } from './std.ts'
7-
import util, { existsFileSync, hashShort } from './util.ts'
8+
import util, { hashShort } from './util.ts'
89

910
export async function start(appDir: string, port: number, isDev = false, reload = false) {
1011
const project = new Project(appDir, isDev ? 'development' : 'production', reload)

std.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
export { Untar } from 'https://deno.land/[email protected]/archive/tar.ts'
22
export * as colors from 'https://deno.land/[email protected]/fmt/colors.ts'
33
export { ensureDir } from 'https://deno.land/[email protected]/fs/ensure_dir.ts'
4-
export { ensureFile } from 'https://deno.land/[email protected]/fs/ensure_file.ts'
54
export { walk } from 'https://deno.land/[email protected]/fs/walk.ts'
65
export { Sha1 } from 'https://deno.land/[email protected]/hash/sha1.ts'
76
export { listenAndServe, serve, ServerRequest } from 'https://deno.land/[email protected]/http/server.ts'

0 commit comments

Comments
 (0)