/
index.ts
593 lines (524 loc) · 14.6 KB
/
index.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
/// <reference path="../declarations.d.ts" />
import path from 'path'
import http from 'http'
import { fs } from 'saber-utils'
import { log, colors, Log } from 'saber-log'
import resolveFrom from 'resolve-from'
import merge from 'lodash.merge'
import getPort from 'get-port'
import { Pages, CreatePageInput } from './Pages'
import { BrowserApi } from './BrowserApi'
import { Transformers } from './Transformers'
import configLoader from './utils/configLoader'
import resolvePackage from './utils/resolvePackage'
import builtinPlugins from './plugins'
import { Compiler } from './Compiler'
import { WebpackUtils } from './WebpackUtils'
import { hooks } from './hooks'
import { VueRenderer } from './vue-renderer'
import { validateConfig, ValidatedSaberConfig } from './utils/validateConfig'
export interface SaberConstructorOptions {
cwd?: string
verbose?: boolean
dev?: boolean
inspectWebpack?: boolean
}
export interface SaberOptions {
cwd: string
verbose?: boolean
dev?: boolean
inspectWebpack?: boolean
}
export interface SiteConfig {
/** Apply to <html> tag */
lang: string
[k: string]: any
}
export interface ThemeConfig {
[k: string]: any
}
export interface SaberPlugin {
name: string
apply: (api: Saber, options: any) => void | Promise<void>
filterPlugins?: (
plugins: ResolvedSaberPlugin[],
options?: any
) => ResolvedSaberPlugin[]
}
export interface SaberConfigPlugin {
resolve: string
options?: { [k: string]: any }
}
export interface ResolvedSaberPlugin extends SaberPlugin {
location: string
options?: any
}
export interface WebpackContext {
type: 'client' | 'server'
[k: string]: any
}
export type PageType = 'page' | 'post'
export interface Permalinks {
/**
* Permalink format for normal pages
* @default `/:slug.html`
*/
page?: string
/**
* Permalink format for posts
* @default `/posts/:slug.html`
*/
post?: string
}
export interface SaberConfig {
/** The path or name of your theme */
theme?: string
siteConfig?: SiteConfig
themeConfig?: object
locales?: {
[localePath: string]: {
siteConfig?: SiteConfig
themeConfig?: ThemeConfig
}
}
/**
* Customize permalink format based on page types (page or post)
*/
permalinks?: Permalinks | ((page: CreatePageInput) => Permalinks)
/** Build configurations */
build?: {
/**
* The path to output generated files
* Defaul to `./public`
*/
outDir?: string
/**
* The root path where your website is localed
* Default to `/`
*/
publicUrl?: string
/**
* Extract CSS into standalone files
* Default to `false`
*/
extractCSS?: boolean
/**
* Toggle sourcemap for CSS
* Default to `false`
*/
cssSourceMap?: boolean
/**
* Options for CSS loaders
*/
loaderOptions?: {
/** sass-loader */
sass?: any
/** less-loader */
less?: any
/** stylus-loader */
stylus?: any
/** css-loader */
css?: any
/** postcss-loader */
postcss?: any
}
/**
* Toggle cache for webpack
* Default to `true`
*/
cache?: boolean
/**
* Compile pages on demand
* @beta
*/
lazy?: boolean
}
server?: {
host?: string
port?: number
}
plugins?: Array<string | SaberConfigPlugin>
markdown?: {
/** The path to a module or npm package name that slugifies the markdown headers. */
slugify?: string
/**
* Options for the internal markdown-it plugin for generating markdown headings and heading anchors.
*/
headings?: {
/**
* Inject markdown headings as `page.markdownHeadings`
* @default `true`
*/
markdownHeadings?: boolean
/**
* Generating permalinks
* @default `false`
*/
permalink?: boolean
permalinkComponent?: string
/**
* Inject permalink before heading text.
* @default `true`
*/
permalinkBefore?: string
/**
* The permalink symbol.
* @default `'#'`
*/
permalinkSymbol?: string
}
/**
* Show line numbers in code blocks
* @default `false`
*/
lineNumbers?: boolean
/** markdown-it plugins */
plugins?: MarkdownPlugin[]
/** markdown-it options */
options?: {
[k: string]: any
}
}
template?: {
/**
* Whether to open external links in new tab.
* @default `true`
*/
openLinkInNewTab?: boolean
/**
* A set of plugins that are used to transform Vue template.
*/
plugins?: any[]
}
}
export interface MarkdownPlugin {
resolve: string
options?: {
[k: string]: any
}
}
export class Saber {
opts: SaberOptions
initialConfig: SaberConfig
config: ValidatedSaberConfig
pages: Pages
browserApi: BrowserApi
webpackUtils: WebpackUtils
log: Log
colors: typeof colors
utils: typeof import('saber-utils')
hooks: typeof hooks
transformers: Transformers
runtimePolyfills: Set<string>
compilers: {
[k: string]: Compiler
}
renderer: VueRenderer
pkg: {
path?: string
data: {
[k: string]: any
}
}
configDir?: string
configPath?: string
theme: string
actualServerPort?: number
constructor(opts: SaberConstructorOptions = {}, config: SaberConfig = {}) {
this.opts = {
...opts,
cwd: path.resolve(opts.cwd || '.')
}
this.initialConfig = config
this.pages = new Pages(this)
this.browserApi = new BrowserApi(this)
this.webpackUtils = new WebpackUtils(this)
this.log = log
this.colors = colors
this.utils = require('saber-utils')
this.hooks = hooks
this.transformers = new Transformers()
this.runtimePolyfills = new Set()
this.compilers = {
server: new Compiler('server', this),
client: new Compiler('client', this)
}
const hookNames = Object.keys(this.hooks) as Array<keyof typeof hooks>
for (const hook of hookNames) {
const ignoreNames = ['theme-node-api', 'user-node-api']
this.hooks[hook].intercept({
register(tapInfo) {
const { fn, name } = tapInfo
tapInfo.fn = (...args: any[]) => {
if (!ignoreNames.includes(name)) {
const msg = `${hook} ${colors.dim(`(${name})`)}`
log.verbose(msg)
}
return fn(...args)
}
return tapInfo
}
})
}
if (opts.verbose) {
process.env.SABER_LOG_LEVEL = '4'
}
// Load package.json data
const loadedPkg = configLoader.load({
files: ['package.json'],
cwd: this.opts.cwd
})
this.pkg = {
...loadedPkg,
data: loadedPkg.data || {}
}
// To make TypeScript happy
// We actually initialize them in `prepare()`
// TODO: find a better way
this.configDir = ''
this.configPath = ''
// Load Saber config
const loadedConfig = this.loadConfig()
this.config = loadedConfig.config
this.configPath = loadedConfig.configPath
this.configDir = this.configPath && path.dirname(this.configPath)
if (this.configPath) {
log.info(
`Using config file: ${colors.dim(
path.relative(process.cwd(), this.configPath)
)}`
)
}
this.renderer = new VueRenderer()
this.renderer.init(this)
// Load theme
if (this.config.theme) {
this.theme = resolvePackage(this.config.theme, {
cwd: this.configDir || this.opts.cwd,
prefix: 'saber-theme-'
})
// When a theme is loaded from `node_modules` and `$theme/dist` directory exists
// We use the `dist` directory instead
if (this.theme.includes('node_modules')) {
const distDir = path.join(this.theme, 'dist')
if (fs.existsSync(distDir)) {
this.theme = distDir
}
}
log.info(`Using theme: ${colors.dim(this.config.theme)}`)
log.verbose(() => `Theme directory: ${colors.dim(this.theme)}`)
} else {
this.theme = this.renderer.defaultTheme
}
}
loadConfig(configFiles = configLoader.CONFIG_FILES) {
const { data, path: configPath } = configLoader.load({
files: configFiles,
cwd: this.opts.cwd
})
return {
config: validateConfig(merge({}, data, this.initialConfig), {
dev: this.dev
}),
configPath
}
}
setConfig(config: ValidatedSaberConfig, configPath?: string) {
this.config = config
this.configPath = configPath
this.configDir = configPath && path.dirname(configPath)
}
get dev() {
return Boolean(this.opts.dev)
}
get lazy() {
return this.dev && this.config.build.lazy
}
async prepare() {
// Load built-in plugins
for (const plugin of builtinPlugins) {
const resolvedPlugin = require(plugin.resolve)
await this.applyPlugin(resolvedPlugin.default || resolvedPlugin)
}
// Load user plugins
await this.hooks.beforePlugins.promise()
const userPlugins = this.getUserPlugins()
if (userPlugins.length > 0) {
log.info(
`Using ${userPlugins.length} plugin${
userPlugins.length > 1 ? 's' : ''
} from config file`
)
}
for (const plugin of userPlugins) {
await this.applyPlugin(plugin, plugin.options, plugin.location)
}
await this.hooks.afterPlugins.promise()
}
async applyPlugin(
plugin: SaberPlugin,
options?: any,
pluginLocation?: string
) {
await plugin.apply(this, options)
if (!plugin.name.startsWith('builtin:')) {
log.verbose(
() =>
`Using plugin "${colors.bold(plugin.name)}" ${
pluginLocation ? colors.dim(pluginLocation) : ''
}`
)
}
}
getUserPlugins() {
// Plugins that are specified in user config, a.k.a. saber-config.js etc
const plugins: ResolvedSaberPlugin[] =
this.configDir && this.config.plugins
? this.config.plugins.map(p => {
if (typeof p === 'string') {
p = { resolve: p }
}
const location = resolveFrom(this.configDir as string, p.resolve)
const resolvedPlugin = {
...require(location),
location,
options: p.options
}
return resolvedPlugin
})
: []
const applyFilterPlugins = (
plugins: ResolvedSaberPlugin[]
): ResolvedSaberPlugin[] => {
type Handler = (plugins: ResolvedSaberPlugin[]) => ResolvedSaberPlugin[]
const handlers = new Set<Handler>()
for (const plugin of plugins) {
const { filterPlugins, options } = plugin
if (filterPlugins) {
delete plugin.filterPlugins
handlers.add(plugins => filterPlugins(plugins, options))
}
}
if (handlers.size > 0) {
for (const handler of handlers) {
plugins = handler(plugins)
}
return applyFilterPlugins(plugins)
}
return plugins
}
return applyFilterPlugins(this.hooks.filterPlugins.call(plugins))
}
resolveCache(...args: string[]) {
return this.resolveCwd('.saber', ...args)
}
resolveCwd(...args: string[]) {
return path.resolve(this.opts.cwd, ...args)
}
resolveOwnDir(...args: string[]) {
return path.join(__dirname, '../', ...args)
}
resolveOutDir(...args: string[]) {
return this.resolveCwd(this.config.build.outDir, ...args)
}
getWebpackConfig(opts: WebpackContext) {
opts = Object.assign({ type: 'client' }, opts)
const chain = require('./webpack/webpack.config')(this, opts)
this.hooks.chainWebpack.call(chain, opts)
const config = this.hooks.getWebpackConfig.call(chain.toConfig(), opts)
if (this.opts.inspectWebpack) {
require('./utils/inspectWebpack')(config, opts.type)
}
return config
}
async run() {
// Throw an error if both `public` and `.saber/public` exist
// Because they are replaced by `static` and `public`
// TODO: remove this error before v1.0
const hasOldPublicFolder = await Promise.all([
fs.pathExists(this.resolveCache('public')),
fs.pathExists(this.resolveCwd('public')),
fs.pathExists(this.resolveCwd('public/index.html'))
]).then(
([hasOldOutDir, hasPublicDir, hasNewPublicDir]) =>
hasOldOutDir && hasPublicDir && !hasNewPublicDir
)
if (hasOldPublicFolder) {
// Prevent from deleting public folder
throw new Error(
[
`It seems you are using the ${colors.underline(
colors.cyan('public')
)} folder to store static files,`,
` this behavior has changed and now we use ${colors.underline(
colors.cyan('static')
)} folder for static files`,
` while ${colors.underline(
colors.cyan('public')
)} folder is used to output generated files,`,
` to prevent from unexpectedly deleting your ${colors.underline(
colors.cyan('public')
)} folder, please rename it to ${colors.underline(
colors.cyan('static')
)} and delete ${colors.underline(
colors.cyan('.saber/public')
)} folder as well`
].join('')
)
}
await this.hooks.beforeRun.promise()
await this.hooks.emitRoutes.promise()
}
// Build app in production mode
async build(options: { skipCompilation?: boolean } = {}) {
const { skipCompilation } = options
await this.prepare()
await this.run()
if (!skipCompilation) {
await this.renderer.build()
await this.hooks.afterBuild.promise()
}
await this.renderer.generate()
await this.hooks.afterGenerate.promise()
}
async serve() {
await this.prepare()
await this.run()
const server = http.createServer(this.renderer.getRequestHandler())
// Make sure the port is available
const { host, port = 3000 } = this.config.server
this.actualServerPort = await getPort({
port: getPort.makeRange(port, port + 1000),
host
})
server.listen(this.actualServerPort, host)
}
async serveOutDir() {
await this.prepare()
return require('./utils/serveDir')({
dir: this.resolveOutDir(),
host: this.config.server.host,
port: this.config.server.port
})
}
hasDependency(name: string) {
return this.getDependencies().includes(name)
}
getDependencies() {
return [
...Object.keys(this.pkg.data.dependencies || {}),
...Object.keys(this.pkg.data.devDependencies || {})
]
}
localResolve(name: string): string {
return require('resolve-from').silent(this.opts.cwd, name)
}
localRequire(name: string): any {
const resolved = this.localResolve(name)
return resolved && require(resolved)
}
}
export const createSaber = (
opts: SaberConstructorOptions,
config: SaberConfig
) => new Saber(opts, config)