-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathaleph.ts
1520 lines (1378 loc) · 49.1 KB
/
aleph.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { dim } from 'https://deno.land/[email protected]/fmt/colors.ts'
import { indexOf, copy, equals } from 'https://deno.land/[email protected]/bytes/mod.ts'
import { ensureDir } from 'https://deno.land/[email protected]/fs/ensure_dir.ts'
import { walk } from 'https://deno.land/[email protected]/fs/walk.ts'
import { createHash } from 'https://deno.land/[email protected]/hash/mod.ts'
import { basename, dirname, extname, join, resolve } from 'https://deno.land/[email protected]/path/mod.ts'
import { Bundler, bundlerRuntimeCode, simpleJSMinify } from '../bundler/mod.ts'
import type { TransformOptions } from '../compiler/mod.ts'
import { wasmChecksum, parseExportNames, SourceType, transform, stripSsrCode } from '../compiler/mod.ts'
import { EventEmitter } from '../framework/core/events.ts'
import { builtinModuleExts, toPagePath, trimBuiltinModuleExts } from '../framework/core/module.ts'
import { Routing } from '../framework/core/routing.ts'
import cssPlugin, { cssLoader, isCSS } from '../plugins/css.ts'
import { ensureTextFile, existsDir, existsFile, lazyRemove } from '../shared/fs.ts'
import log, { Measure } from '../shared/log.ts'
import util from '../shared/util.ts'
import type {
Aleph as IAleph, ImportMap, LoadInput, LoadOutput, RouterURL, ResolveResult,
TransformOutput, TransformInput
} from '../types.ts'
import { VERSION } from '../version.ts'
import { Analyzer } from './analyzer.ts'
import { cache } from './cache.ts'
import type { RequiredConfig } from './config.ts'
import { defaultConfig, fixConfigAndImportMap, getDefaultImportMap, loadConfig, loadImportMap } from './config.ts'
import {
checkAlephDev, checkDenoVersion, clearBuildCache, computeHash, findFile,
getAlephPkgUri, getSourceType, isLocalUrl, moduleExclude, toLocalPath, toRelativePath
} from './helper.ts'
import { getContentType } from './mime.ts'
import type { SSRData } from './renderer.ts'
import { Renderer } from './renderer.ts'
/** A module includes the compilation details. */
export type Module = {
specifier: string
deps: DependencyDescriptor[]
external?: boolean
isStyle?: boolean
externalRemoteDeps?: boolean
ssrPropsFn?: string
ssgPathsFn?: boolean
denoHooks?: string[]
hash?: string
sourceHash: string
jsFile: string
jsBuffer?: Uint8Array
ready: Promise<void>
}
type ModuleSource = {
code: string
type: SourceType
isStyle: boolean
map?: string
}
type DependencyDescriptor = {
specifier: string
isDynamic?: boolean
hashLoc?: number
}
type CompileOptions = {
source?: ModuleSource,
forceRefresh?: boolean,
ignoreDeps?: boolean,
externalRemoteDeps?: boolean
}
type ResolveListener = {
test: RegExp,
resolve(specifier: string): ResolveResult,
}
type LoadListener = {
test: RegExp,
load(input: LoadInput): Promise<LoadOutput> | LoadOutput,
}
type TransformListener = {
test: RegExp | string,
transform(input: TransformInput): TransformOutput,
}
type SsrListener = (path: string, html: string) => { html: string }
/** The Aleph class for aleph runtime. */
export class Aleph implements IAleph {
readonly mode: 'development' | 'production'
readonly workingDir: string
readonly buildDir: string
readonly config: RequiredConfig
readonly importMap: ImportMap
readonly ready: Promise<void>
#modules: Map<string, Module> = new Map()
#appModule: Module | null = null
#pageRouting: Routing = new Routing()
#apiRouting: Routing = new Routing()
#analyzer: Analyzer = new Analyzer(this)
#bundler: Bundler = new Bundler(this)
#renderer: Renderer = new Renderer(this)
#fsWatchListeners: Array<EventEmitter> = []
#resolverListeners: Array<ResolveListener> = []
#loadListeners: Array<LoadListener> = []
#transformListeners: Array<TransformListener> = []
#ssrListeners: Array<SsrListener> = []
#dists: Set<string> = new Set()
#reloading = false
constructor(
workingDir = '.',
mode: 'development' | 'production' = 'production',
reload = false
) {
checkDenoVersion()
checkAlephDev()
this.mode = mode
this.workingDir = resolve(workingDir)
this.buildDir = join(this.workingDir, '.aleph', mode)
this.config = { ...defaultConfig() }
this.importMap = { imports: {}, scopes: {} }
this.ready = Deno.env.get('DENO_TESTING') ? Promise.resolve() : this.init(reload)
}
/** initiate runtime */
private async init(reload: boolean) {
const ms = new Measure()
let [importMapFile, configFile] = await Promise.all([
findFile(this.workingDir, ['import_map', 'import-map', 'importmap', 'importMap'].map(name => `${name}.json`)),
findFile(this.workingDir, ['ts', 'js', 'mjs', 'json'].map(ext => `aleph.config.${ext}`))
])
if (importMapFile) {
Object.assign(this.importMap, await loadImportMap(importMapFile))
} else {
Object.assign(this.importMap, getDefaultImportMap())
}
if (configFile) {
if (!configFile.endsWith('.json')) {
const mod = await this.compile(`/${basename(configFile)}`, { externalRemoteDeps: true })
configFile = join(this.buildDir, mod.jsFile)
}
Object.assign(this.config, await loadConfig(configFile))
this.#pageRouting = new Routing(this.config)
}
await fixConfigAndImportMap(this.workingDir, this.config, this.importMap)
ms.stop('load config')
// load .env files
for await (const { path: p, } of walk(this.workingDir, { match: [/(^|\/|\\)\.env(\.|$)/i], maxDepth: 1 })) {
const text = await Deno.readTextFile(p)
text.split('\n').forEach(line => {
let [key, value] = util.splitBy(line, '=')
key = key.trim()
if (key) {
Deno.env.set(key, value.trim())
}
})
log.info('load env from', basename(p))
}
Deno.env.set('ALEPH_ENV', this.mode)
Deno.env.set('ALEPH_FRAMEWORK', this.config.framework)
Deno.env.set('ALEPH_VERSION', VERSION)
const alephPkgUri = getAlephPkgUri()
const srcDir = join(this.workingDir, this.config.srcDir)
const apiDir = join(srcDir, 'api')
const pagesDir = join(srcDir, 'pages')
const buildManifestFile = join(this.buildDir, 'build.manifest.json')
const importMapString = JSON.stringify(this.importMap)
let shouldRebuild = !await existsFile(buildManifestFile)
let saveManifestFile = shouldRebuild
if (!shouldRebuild) {
try {
const v = JSON.parse(await Deno.readTextFile(buildManifestFile))
shouldRebuild = (
typeof v !== 'object' ||
v === null ||
v.compiler !== wasmChecksum ||
(v.importMap !== importMapString && confirm('The import-maps has been changed, rebuild modules?'))
)
if (!shouldRebuild && v.importMap !== importMapString) {
saveManifestFile = true
}
} catch (e) { }
}
this.#reloading = reload
if (reload || shouldRebuild) {
if (await existsDir(this.buildDir)) {
await Deno.remove(this.buildDir, { recursive: true })
}
await ensureDir(this.buildDir)
}
if (saveManifestFile) {
log.debug('rebuild...')
ensureTextFile(buildManifestFile, JSON.stringify({
aleph: VERSION,
deno: Deno.version.deno,
compiler: wasmChecksum,
importMap: importMapString,
}, undefined, 2))
}
ms.stop(`init env`)
// apply plugins
cssPlugin().setup(this)
await Promise.all(
this.config.plugins.map(async plugin => {
await plugin.setup(this)
})
)
ms.stop('apply plugins')
const mwFile = await findFile(this.workingDir, ['ts', 'js', 'mjs'].map(ext => `${this.config.srcDir}/api/_middlewares.${ext}`))
if (mwFile) {
const mwMod = await this.compile(`/api/${basename(mwFile)}`, { externalRemoteDeps: true })
const { default: _middlewares } = await import('file://' + join(this.buildDir, mwMod.jsFile))
const middlewares = Array.isArray(_middlewares) ? _middlewares.filter(fn => util.isFunction(fn)) : []
this.config.server.middlewares.push(...middlewares)
ms.stop(`load API middlewares (${middlewares.length}) from 'api/${basename(mwFile)}'`)
}
// init framework
const { init } = await import(`../framework/${this.config.framework}/init.ts`)
await init(this)
// compile and import framework renderer
if (this.config.ssr) {
const mod = await this.compile(`${alephPkgUri}/framework/${this.config.framework}/renderer.ts`)
const { render } = await this.importModule(mod)
if (util.isFunction(render)) {
this.#renderer.setFrameworkRenderer({ render })
}
}
ms.stop(`init ${this.config.framework} framework`)
const appFile = await findFile(srcDir, builtinModuleExts.map(ext => `app.${ext}`))
const modules: string[] = []
const moduleWalkOptions = {
includeDirs: false,
skip: moduleExclude
}
// pre-compile framework modules
modules.push(`${alephPkgUri}/framework/${this.config.framework}/bootstrap.ts`)
if (this.isDev) {
modules.push(`${alephPkgUri}/framework/core/hmr.ts`)
modules.push(`${alephPkgUri}/framework/core/nomodule.ts`)
}
if (appFile) {
modules.push(`/${basename(appFile)}`)
}
// create API routing
if (await existsDir(apiDir)) {
for await (const { path: p } of walk(apiDir, { ...moduleWalkOptions, exts: builtinModuleExts })) {
const specifier = util.cleanPath('/api/' + util.trimPrefix(p, apiDir))
if (!specifier.startsWith('/api/_middlewares.')) {
this.#apiRouting.update(...this.createRouteUpdate(specifier))
}
}
}
// create Page routing
if (await existsDir(pagesDir)) {
for await (const { path: p } of walk(pagesDir, moduleWalkOptions)) {
const specifier = util.cleanPath('/pages/' + util.trimPrefix(p, pagesDir))
if (this.isPageModule(specifier)) {
this.#pageRouting.update(...this.createRouteUpdate(specifier))
if (!this.isDev) {
modules.push(specifier)
}
}
}
}
// wait all compilation tasks are done
await Promise.all(modules.map(specifier => this.compile(specifier)))
// bundle
if (!this.isDev) {
await this.bundle()
}
// end reload
if (reload) {
this.#reloading = false
}
ms.stop('init project')
if (this.isDev) {
this.watch()
}
}
/** watch file changes, re-compile modules, and send HMR signal to client. */
private async watch() {
const srcDir = join(this.workingDir, this.config.srcDir)
const w = Deno.watchFs(srcDir, { recursive: true })
log.info('Start watching code changes...')
for await (const event of w) {
for (const path of event.paths) {
const specifier = util.cleanPath(util.trimPrefix(path, srcDir))
if (this.isScopedModule(specifier)) {
util.debounceById(
specifier,
() => this.watchHandler(path, specifier),
50
)
}
}
}
}
private async watchHandler(path: string, specifier: string): Promise<void> {
if (await existsFile(path)) {
if (this.#modules.has(specifier)) {
try {
const prevModule = this.#modules.get(specifier)!
const module = await this.compile(specifier, {
forceRefresh: true,
ignoreDeps: true,
externalRemoteDeps: specifier.startsWith('/api/')
})
const refreshPage = (
this.config.ssr &&
(
(module.denoHooks !== undefined && JSON.stringify(prevModule.denoHooks) !== JSON.stringify(module.denoHooks)) ||
(module.ssrPropsFn !== undefined && prevModule.ssrPropsFn !== module.ssrPropsFn)
)
)
const hmrable = this.isHMRable(specifier)
if (hmrable) {
this.#fsWatchListeners.forEach(e => {
e.emit('modify-' + module.specifier, { refreshPage: refreshPage || undefined })
})
}
this.applyCompilationSideEffect(module, ({ specifier }) => {
if (!hmrable && this.isHMRable(specifier)) {
log.debug('compilation side-effect:', specifier, dim('<-'), module.specifier)
this.#fsWatchListeners.forEach(e => {
e.emit('modify-' + specifier, { refreshPage: refreshPage || undefined })
})
}
this.clearSSRCache(specifier)
})
this.clearSSRCache(specifier)
log.info('modify', specifier)
} catch (err) {
log.error(`compile(${specifier}):`, err.message)
}
} else {
let routePath: string | undefined = undefined
let isIndex: boolean | undefined = undefined
let emit = false
if (this.isPageModule(specifier)) {
let isNew = true
this.#pageRouting.lookup(routes => {
routes.forEach(({ module }) => {
if (module === specifier) {
isNew = false
return false // break loop
}
})
})
if (isNew) {
const [_routePath, _specifier, _isIndex] = this.createRouteUpdate(specifier)
routePath = _routePath
specifier = _specifier
isIndex = _isIndex
emit = true
this.#pageRouting.update(routePath, specifier, isIndex)
}
} else if (specifier.startsWith('/api/') && !specifier.startsWith('/api/_middlewares.')) {
this.#apiRouting.update(...this.createRouteUpdate(specifier))
}
if (trimBuiltinModuleExts(specifier) === '/app') {
await this.compile(specifier)
emit = true
}
if (emit) {
this.#fsWatchListeners.forEach(e => {
e.emit('add', { specifier, routePath, isIndex })
})
}
log.info('add', specifier)
}
} else {
if (this.#modules.has(specifier)) {
this.#modules.delete(specifier)
}
if (trimBuiltinModuleExts(specifier) === '/app') {
this.#fsWatchListeners.forEach(e => e.emit('remove', specifier))
} else if (this.isPageModule(specifier)) {
this.#pageRouting.removeRouteByModule(specifier)
this.#fsWatchListeners.forEach(e => e.emit('remove', specifier))
} else if (specifier.startsWith('/api/')) {
this.#apiRouting.removeRouteByModule(specifier)
}
this.clearSSRCache(specifier)
log.info('remove', specifier)
}
}
/** check the file whether it is a scoped module. */
private isScopedModule(specifier: string) {
if (moduleExclude.some(r => r.test(specifier))) {
return false
}
// is compiled module
if (this.#modules.has(specifier)) {
return true
}
// is page module by plugin
if (this.isPageModule(specifier)) {
return true
}
// is api or app module
for (const ext of builtinModuleExts) {
if (
specifier.endsWith('.' + ext) &&
(
specifier.startsWith('/api/') ||
util.trimSuffix(specifier, '.' + ext) === '/app'
)
) {
return true
}
}
return false
}
get isDev() {
return this.mode === 'development'
}
/** get the module by given specifier. */
getModule(specifier: string): Module | null {
if (specifier === 'app') {
return this.#appModule
}
if (this.#modules.has(specifier)) {
return this.#modules.get(specifier)!
}
return null
}
/** get the first module in the modules map where predicate is true, and null otherwise. */
findModule(predicate: (module: Module) => boolean): Module | null {
for (const specifier of this.#modules.keys()) {
const module = this.#modules.get(specifier)!
if (predicate(module)) {
return module
}
}
return null
}
/** get api route by given location. */
async getAPIRoute(location: { pathname: string, search?: string }): Promise<[RouterURL, Module] | null> {
const router = this.#apiRouting.createRouter(location)
if (router !== null) {
const [url, nestedModules] = router
if (url.routePath !== '') {
const specifier = nestedModules.pop()!
if (this.#modules.has(specifier)) {
return [url, this.#modules.get(specifier)!]
}
const module = await this.compile(specifier, { externalRemoteDeps: true })
return [url, module]
}
}
return null
}
onResolve(test: RegExp, callback: (specifier: string) => ResolveResult): void {
this.#resolverListeners.push({ test, resolve: callback })
}
onLoad(test: RegExp, callback: (input: LoadInput) => LoadOutput | Promise<LoadOutput>): void {
this.#loadListeners.push({ test, load: callback })
}
onTransform(test: RegExp | string, callback: (input: TransformInput) => TransformOutput): void {
this.#transformListeners.push({ test, transform: callback })
}
onSSR(callback: (path: string, html: string) => { html: string }): void {
this.#ssrListeners.push(callback)
}
/** add a module by given path and optional source code. */
async addModule(specifier: string, sourceCode?: string): Promise<void> {
const source = sourceCode ? {
code: sourceCode,
type: SourceType.TSX,
external: false,
isStyle: false,
} : undefined
if (source !== undefined) {
const type = getSourceType(specifier)
if (type !== SourceType.Unknown) {
source.type = type
}
}
await this.compile(specifier, { source })
if (specifier.startsWith('/pages/')) {
this.#pageRouting.update(...this.createRouteUpdate(specifier))
} else if (specifier.startsWith('/api/') && !specifier.startsWith('/api/_middlewares.')) {
this.#apiRouting.update(...this.createRouteUpdate(specifier))
}
return
}
/** add a dist. */
async addDist(path: string, content: Uint8Array): Promise<void> {
const pathname = util.cleanPath(path)
const savePath = join(this.buildDir, pathname)
if (!await existsFile(savePath)) {
const saveDir = dirname(savePath)
await ensureDir(saveDir)
await clearBuildCache(savePath, extname(savePath).slice(1))
await Deno.writeFile(savePath, content)
}
this.#dists.add(pathname)
}
/** get ssr data */
async getSSRData(loc: { pathname: string, search?: string }): Promise<Record<string, SSRData> | null> {
const [router, nestedModules] = this.#pageRouting.createRouter(loc)
const { routePath } = router
if (routePath === '' || !this.isSSRable(router.pathname)) {
return null
}
// pre-compile modules to check ssr options
await Promise.all(
nestedModules
.filter(specifier => !this.#modules.has(specifier))
.map(specifier => this.compile(specifier))
)
let shouldRender = false
const pageModule = this.getModule(nestedModules[nestedModules.length - 1])
if (pageModule && pageModule.ssrPropsFn) {
shouldRender = true
}
if (!shouldRender) {
for (const specifier of ['app', ...nestedModules]) {
const mod = this.getModule(specifier)
if (mod) {
if (mod.denoHooks?.length) {
shouldRender = true
} else {
this.lookupDeps(mod.specifier, dep => {
const depMod = this.getModule(dep.specifier)
if (depMod?.denoHooks?.length) {
shouldRender = true
return false
}
})
}
if (shouldRender) {
break
}
}
}
}
if (!shouldRender) {
return null
}
const path = loc.pathname + (loc.search || '')
const [_, data] = await this.#renderer.cache(routePath, path, async () => {
return await this.#renderer.renderPage(router, nestedModules)
})
return data
}
/** get page ssr html */
async getPageHTML(loc: { pathname: string, search?: string }): Promise<[number, string]> {
const [router, nestedModules] = this.#pageRouting.createRouter(loc)
const { routePath } = router
const path = loc.pathname + (loc.search || '')
if (!this.isSSRable(loc.pathname)) {
const [html] = await this.#renderer.cache('-', 'spa-index', async () => {
return [await this.#renderer.renderSPAIndexPage(), null]
})
return [200, html]
}
if (routePath === '') {
const [html] = await this.#renderer.cache('404', path, async () => {
const [_, nestedModules] = this.#pageRouting.createRouter({ pathname: '/404' })
return await this.renderPage(router, nestedModules.slice(0, 1))
})
return [404, html]
}
const [html] = await this.#renderer.cache(routePath, path, async () => {
return await this.renderPage(router, nestedModules)
})
return [200, html]
}
private async renderPage(url: RouterURL, nestedModules: string[]): Promise<[string, Record<string, SSRData> | null]> {
const href = url.toString()
let [html, data] = await this.#renderer.renderPage(url, nestedModules)
for (const callback of this.#ssrListeners) {
const ret = callback(href, html)
html = ret.html
}
return [html, data]
}
/** create a fs watcher. */
createFSWatcher(): EventEmitter {
const e = new EventEmitter()
this.#fsWatchListeners.push(e)
return e
}
/** remove the fs watcher. */
removeFSWatcher(e: EventEmitter) {
e.removeAllListeners()
const index = this.#fsWatchListeners.indexOf(e)
if (index > -1) {
this.#fsWatchListeners.splice(index, 1)
}
}
/** create main bootstrap script in javascript. */
createMainJS(bundleMode = false): string {
const alephPkgUri = getAlephPkgUri()
const alephPkgPath = alephPkgUri.replace('https://', '').replace('http://localhost:', 'http_localhost_')
const { framework, basePath: basePath, i18n: { defaultLocale } } = this.config
const { routes } = this.#pageRouting
const config: Record<string, any> = {
basePath,
appModule: this.#appModule?.specifier,
routes,
renderMode: this.config.ssr ? 'ssr' : 'spa',
defaultLocale,
locales: [],
rewrites: this.config.server.rewrites,
}
if (bundleMode) {
return [
`__ALEPH__.basePath = ${JSON.stringify(basePath)};`,
`__ALEPH__.pack["${alephPkgUri}/framework/${framework}/bootstrap.ts"].default(${JSON.stringify(config)});`
].join('')
}
let code = [
`import bootstrap from "./-/${alephPkgPath}/framework/${framework}/bootstrap.js";`,
this.isDev && `import { connect } from "./-/${alephPkgPath}/framework/core/hmr.js";`,
this.isDev && `connect(${JSON.stringify(basePath)});`,
`bootstrap(${JSON.stringify(config, undefined, this.isDev ? 2 : undefined)});`
].filter(Boolean).join('\n')
this.#transformListeners.forEach(({ test, transform }) => {
if (test === 'main.js') {
const ret = transform({ specifier: '/main.js', code })
code = ret.code
}
})
return code
}
/** get ssr html scripts */
getSSRHTMLScripts(entryFile?: string) {
const { framework } = this.config
const basePath = util.trimSuffix(this.config.basePath, '/')
const alephPkgPath = getAlephPkgUri().replace('https://', '').replace('http://localhost:', 'http_localhost_')
if (this.isDev) {
const preload: string[] = [
`/framework/core/module.js`,
`/framework/core/events.js`,
`/framework/core/routing.js`,
`/framework/core/hmr.js`,
`/framework/${framework}/bootstrap.js`,
`/shared/util.js`,
].map(p => `${basePath}/_aleph/-/${alephPkgPath}${p}`)
if (this.#appModule) {
preload.push(`${basePath}/_aleph/app.js`)
}
if (entryFile) {
preload.push(`${basePath}/_aleph${entryFile}`)
}
return [
...preload.map(src => ({ src, type: 'module', preload: true })),
{ src: `${basePath}/_aleph/main.js`, type: 'module' },
{ src: `${basePath}/_aleph/-/${alephPkgPath}/nomodule.js`, nomodule: true },
]
}
return [
simpleJSMinify(bundlerRuntimeCode),
... this.#bundler.getSyncChunks().map(filename => ({
src: `${basePath}/_aleph/${filename}`
}))
]
}
/** parse the export names of the module. */
async parseModuleExportNames(specifier: string): Promise<string[]> {
const { content, contentType } = await this.fetchModule(specifier)
const sourceType = getSourceType(specifier, contentType || undefined)
if (sourceType === SourceType.Unknown || sourceType === SourceType.CSS) {
return []
}
const code = (new TextDecoder).decode(content)
const names = await parseExportNames(specifier, code, { sourceType })
return (await Promise.all(names.map(async name => {
if (name.startsWith('{') && name.startsWith('}')) {
return await this.parseModuleExportNames(name.slice(1, -1))
}
return name
}))).flat()
}
/** common compiler options */
get commonCompileOptions(): TransformOptions {
return {
workingDir: this.workingDir,
alephPkgUri: getAlephPkgUri(),
importMap: this.importMap,
inlineStylePreprocess: async (key: string, type: string, tpl: string) => {
if (type !== 'css') {
for (const { test, load } of this.#loadListeners) {
if (test.test(`.${type}`)) {
const { code, type: codeType } = await load({ specifier: key, data: (new TextEncoder).encode(tpl) })
if (codeType === 'css') {
type = 'css'
tpl = code
break
}
}
}
}
const { code } = await cssLoader({ specifier: key, data: (new TextEncoder).encode(tpl) }, this)
return code
},
isDev: this.isDev,
react: this.config.react,
}
}
analyze() {
this.#analyzer.reset()
this.#pageRouting.lookup(routes => {
routes.forEach(({ module: specifier }) => {
const module = this.getModule(specifier)
if (module) {
this.#analyzer.addEntry(module)
}
})
})
return this.#analyzer.entries
}
/** build the application to a static site(SSG) */
async build() {
const start = performance.now()
// wait for app ready
await this.ready
const outputDir = join(this.workingDir, this.config.build.outputDir)
const distDir = join(outputDir, '_aleph')
// clean previous build
if (await existsDir(outputDir)) {
for await (const entry of Deno.readDir(outputDir)) {
await Deno.remove(join(outputDir, entry.name), { recursive: entry.isDirectory })
}
}
// copy bundle dist
await this.#bundler.copyDist()
// ssg
await this.ssg()
// copy public assets
const publicDir = join(this.workingDir, 'public')
if (await existsDir(publicDir)) {
for await (const { path: p } of walk(publicDir, { includeDirs: false, skip: [/(^|\/|\\)\./] })) {
const rp = util.trimPrefix(p, publicDir)
const fp = join(outputDir, rp)
await ensureDir(dirname(fp))
await Deno.copyFile(p, fp)
}
}
// copy custom dist files
if (this.#dists.size > 0) {
Promise.all(Array.from(this.#dists.values()).map(async path => {
const src = join(this.buildDir, path)
if (await existsFile(src)) {
const dest = join(distDir, path)
await ensureDir(dirname(dest))
return Deno.copyFile(src, dest)
}
}))
}
log.info(`Done in ${Math.round(performance.now() - start)}ms`)
}
private createRouteUpdate(specifier: string): [string, string, boolean | undefined] {
const isBuiltinModuleType = builtinModuleExts.some(ext => specifier.endsWith('.' + ext))
let routePath = isBuiltinModuleType ? toPagePath(specifier) : util.trimSuffix(specifier, '/pages')
let isIndex: boolean | undefined = undefined
if (!isBuiltinModuleType) {
for (const { test, resolve } of this.#resolverListeners) {
if (test.test(specifier)) {
const { specifier: _specifier, asPage } = resolve(specifier)
if (asPage) {
const { path: pagePath, isIndex: _isIndex } = asPage
if (util.isFilledString(pagePath)) {
routePath = pagePath
if (_specifier) {
specifier = _specifier
}
if (_isIndex) {
isIndex = true
}
break
}
}
}
}
} else if (routePath !== '/') {
for (const ext of builtinModuleExts) {
if (specifier.endsWith(`/index.${ext}`)) {
isIndex = true
break
}
}
}
return [routePath, specifier, isIndex]
}
/** fetch module content by the specifier. */
async fetchModule(specifier: string): Promise<{ content: Uint8Array, contentType: string | null }> {
if (!util.isLikelyHttpURL(specifier)) {
const filepath = join(this.workingDir, this.config.srcDir, util.trimPrefix(specifier, 'file://'))
if (await existsFile(filepath)) {
const content = await Deno.readFile(filepath)
return { content, contentType: getContentType(filepath) }
} else {
return Promise.reject(new Error(`No such file: ${util.trimPrefix(filepath, this.workingDir + '/')}`))
}
}
// append `dev` query for development mode
if (this.isDev && specifier.startsWith('https://esm.sh/')) {
const u = new URL(specifier)
if (!u.searchParams.has('dev')) {
u.searchParams.set('dev', '')
u.search = u.search.replace('dev=', 'dev')
specifier = u.toString()
}
}
return await cache(specifier, {
forceRefresh: this.#reloading,
retryTimes: 10
})
}
async importModule<T = any>({ jsFile, hash, sourceHash }: Module): Promise<T> {
return await import(`file://${join(this.buildDir, jsFile)}#${(hash || sourceHash).slice(0, 6)}`)
}
async readModuleJS(module: Module): Promise<Uint8Array | null> {
const { specifier, jsFile, jsBuffer } = module
if (!jsBuffer) {
const cacheFp = join(this.buildDir, jsFile)
if (await existsFile(cacheFp)) {
module.jsBuffer = await Deno.readFile(cacheFp)
log.debug(`load '${jsFile}'` + dim(' • ' + util.formatBytes(module.jsBuffer.length)))
}
}
if (!this.isDev || !this.isHMRable(specifier) || !module.jsBuffer) {
return module.jsBuffer || null
}
let code = new TextDecoder().decode(module.jsBuffer)
if (module.denoHooks?.length || module.ssrPropsFn || module.ssgPathsFn) {
if ('csrCode' in module) {
code = (module as any).csrCode
} else {
const { code: csrCode } = await stripSsrCode(specifier, code, { sourceMap: true, swcOptions: { sourceType: SourceType.JS } })
Object.assign(module, { csrCode })
// todo: merge source map
code = csrCode
}
}
this.#transformListeners.forEach(({ test, transform }) => {
if (test === 'hmr') {
const ret = transform({ specifier, code })
// todo: merge source map
code = ret.code
}
})
return new TextEncoder().encode([
`import.meta.hot = $createHotContext(${JSON.stringify(specifier)});`,
'',
code,
'',
'import.meta.hot.accept();'
].join('\n'))
}
async loadModuleSource(specifier: string, data?: any): Promise<ModuleSource> {
let sourceCode: string = ''
let sourceType: SourceType = SourceType.Unknown
let sourceMap: string | null = null
let loader = this.#loadListeners.find(l => l.test.test(specifier))
let isStyle = isCSS(specifier)
if (loader) {
const { code, type = 'js', map } = await loader.load({ specifier, data })
switch (type) {
case 'js':
sourceType = SourceType.JS
break
case 'jsx':
sourceType = SourceType.JSX
break
case 'ts':
sourceType = SourceType.TS
break
case 'tsx':
sourceType = SourceType.TSX
break
case 'css':
sourceType = SourceType.CSS
break
}
sourceCode = code
sourceMap = map || null
} else {
const source = await this.fetchModule(specifier)
sourceType = getSourceType(specifier, source.contentType || undefined)
if (sourceType !== SourceType.Unknown) {
sourceCode = (new TextDecoder).decode(source.content)
}
}
if (sourceType === SourceType.CSS) {
isStyle = true
// todo: covert source map
const { code, type = 'js' } = await cssLoader({ specifier, data: sourceCode }, this)
if (type === 'js') {
sourceCode = code
sourceType = SourceType.JS
}
}
return {
code: sourceCode,
type: sourceType,
isStyle,
map: sourceMap ? sourceMap : undefined
}
}
/** compile the module by given specifier */
async compile(specifier: string, options: CompileOptions = {}) {
const [module, source] = await this.initModule(specifier, options)
if (!module.external) {
await this.transpileModule(module, source, options.ignoreDeps)
}
return module
}