-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCore.ts
299 lines (250 loc) · 11 KB
/
Core.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
/* tslint:disable:no-eval */
import * as bluebird from 'bluebird'
import * as express from 'express'
import * as requireFromString from 'require-from-string'
import { log as _log, logError as _logError } from './Logger'
import { Builder, BuildLogStage, BuildManifest, BuildManifestEntry, ComponentLibrary, ComponentLibraryConfigurations, Configuration, Environment, RenderResult, RenderResultAssets, Stats, Storage } from './theia'
import { TypedAsyncParallelHook } from './TypedTapable'
export type OnBeforeRenderArgs = {
core: Core
req: express.Request
componentLibrary: string
component: string
props: object
}
export type OnBuildTickArgs = {
core: Core
componentLibrary: string
buildLog: BuildLogStage[]
buildManifestEntry: BuildManifestEntry
}
export type OnComponentLibraryLoadArgs = {
core: Core
componentLibrary: string
manifestEntry: BuildManifestEntry
}
export type OnComponentLibraryUpdateArgs = {
core: Core
componentLibrary: string
manifestEntry: BuildManifestEntry
}
export type OnErrorArgs = {
core: Core
error: Error | string
}
export type OnExpressArgs = {
core: Core
app: express.Application
}
export type OnRenderArgs = OnBeforeRenderArgs
export type OnStartArgs = {
core: Core
}
export type BeforeRenderHook = Tapable.ITypedAsyncParallelHook<OnBeforeRenderArgs>
export type BuildTickHook = Tapable.ITypedAsyncParallelHook<OnBuildTickArgs>
export type ComponentLibraryLoadHook = Tapable.ITypedAsyncParallelHook<OnComponentLibraryLoadArgs>
export type ComponentLibraryUpdateHook = Tapable.ITypedAsyncParallelHook<OnComponentLibraryUpdateArgs>
export type ErrorHook = Tapable.ITypedAsyncParallelHook<OnErrorArgs>
export type ExpressHook = Tapable.ITypedAsyncParallelHook<OnExpressArgs>
export type RenderHook = Tapable.ITypedAsyncParallelHook<OnRenderArgs>
export type StartHook = Tapable.ITypedAsyncParallelHook<OnStartArgs>
class Core {
builder: Builder
libs: ComponentLibraryConfigurations
environment: Environment
storage: Storage
hooks: {
beforeRender: BeforeRenderHook
buildTick: BuildTickHook
componentLibraryLoad: ComponentLibraryLoadHook
componentLibraryUpdate: ComponentLibraryUpdateHook
error: ErrorHook
express: ExpressHook
render: RenderHook
start: StartHook
} = {
beforeRender: new TypedAsyncParallelHook(['core', 'req', 'componentLibrary', 'component', 'props']),
buildTick: new TypedAsyncParallelHook(['core', 'componentLibrary', 'buildLog', 'buildManifestEntry']),
componentLibraryLoad: new TypedAsyncParallelHook(['core', 'componentLibrary', 'manifestEntry']),
componentLibraryUpdate: new TypedAsyncParallelHook(['core', 'componentLibrary', 'manifestEntry']),
error: new TypedAsyncParallelHook(['core', 'error']),
express: new TypedAsyncParallelHook(['core', 'app']),
render: new TypedAsyncParallelHook(['core', 'req', 'componentLibrary', 'component', 'props']),
start: new TypedAsyncParallelHook(['core'])
}
libCache: { [key: string]: ComponentLibrary } = {}
buildManifestCache: { [key: string]: BuildManifest } = {}
statsContentsCache: { [key: string]: Stats } = {}
constructor (public config: Required<Configuration>) {
this.builder = config.builder
this.libs = config.libs
this.environment = config.environment
this.storage = config.storage
if (config.plugins) {
for (const plugin of config.plugins) {
plugin.apply(this)
}
}
}
start (): Promise<void> {
return this.hooks.start.promise({ core: this }).catch(err => {
// TODO: find out how to get which plugin threw the error
const plugin = 'plugin'
this.logError(`theia:${plugin}:start`, err)
})
}
async render (req: express.Request, componentLibrary: string, componentName: string, props: object): Promise<RenderResult> {
// don't wait for completion
this.hooks.beforeRender.promise({ core: this, req, componentLibrary, component: componentName, props }).catch(err => {
// TODO: find out how to get which plugin threw the error
const plugin = 'plugin'
this.logError(`theia:${plugin}:beforeRender`, err)
})
const componentLibraryObject = await this.getComponentLibrary(componentLibrary)
if (!(componentName in componentLibraryObject.Components)) {
throw new Error(`${componentName} is not a registered component of ${componentLibrary}`)
}
const React = componentLibraryObject.React
const ReactDOMServer = componentLibraryObject.ReactDOMServer
const Component = componentLibraryObject.Components[componentName]
const html = ReactDOMServer.renderToString(React.createElement(Component, props))
// TODO: code splitting w/ universal components
const assets = await this.getAssets(componentLibrary, componentName)
// don't wait for completion
this.hooks.render.promise({ core: this, req, componentLibrary, component: componentName, props }).catch(err => {
// TODO: find out how to get which plugin threw the error
const plugin = 'plugin'
this.logError(`theia:${plugin}:render`, err)
})
return {
html,
assets
}
}
async registerComponentLibrary (componentLibrary: string, buildAssets: string[], manifestEntry: BuildManifestEntry): Promise<void> {
if (manifestEntry.success) {
for (const asset of buildAssets) {
await this.storage.copy(componentLibrary, asset)
}
}
let manifest: BuildManifest = []
if (await this.hasBuildManifest(componentLibrary)) {
manifest = await this.getBuildManifest(componentLibrary)
}
manifest.push(manifestEntry)
if (manifestEntry.success) {
await this.hooks.componentLibraryUpdate.promise({ core: this, componentLibrary, manifestEntry }).catch(err => {
// TODO: find out how to get which plugin threw the error
const plugin = 'plugin'
this.logError(`theia:${plugin}:componentLibraryUpdate`, err)
})
}
const manifestJson = JSON.stringify(manifest, null, 2)
await this.storage.write(componentLibrary, 'build-manifest.json', manifestJson)
delete this.libCache[componentLibrary]
delete this.buildManifestCache[componentLibrary]
delete this.statsContentsCache[componentLibrary]
}
hasBuildManifest (componentLibrary: string): Promise<boolean> {
return this.storage.exists(componentLibrary, 'build-manifest.json')
}
async getBuildManifest (componentLibrary: string): Promise<BuildManifest> {
if (this.buildManifestCache[componentLibrary]) {
return this.buildManifestCache[componentLibrary]
}
const contents = await this.storage.load(componentLibrary, 'build-manifest.json')
return this.buildManifestCache[componentLibrary] = JSON.parse(contents)
}
async getLatestStatsContents (componentLibrary: string): Promise<Stats> {
if (this.statsContentsCache[componentLibrary]) {
return this.statsContentsCache[componentLibrary]
}
const buildManifest = await this.getBuildManifest(componentLibrary)
let latest: BuildManifestEntry | null = null
for (let i = buildManifest.length - 1; i >= 0; i--) {
if (buildManifest[i].success !== false) {
latest = buildManifest[i]
break
}
}
if (!latest) {
throw new Error(`${componentLibrary} has no successful build`)
}
const browserStatsContents = await this.storage.load(componentLibrary, latest.browserStats)
const nodeStatsContents = await this.storage.load(componentLibrary, latest.nodeStats)
return this.statsContentsCache[componentLibrary] = {
browser: JSON.parse(browserStatsContents),
node: JSON.parse(nodeStatsContents)
}
}
async getComponentLibrary (componentLibrary: string): Promise<ComponentLibrary> {
if (this.libCache[componentLibrary]) {
return this.libCache[componentLibrary]
}
if (!await this.hasBuildManifest(componentLibrary)) {
throw new Error(`${componentLibrary} is not a registered component library`)
}
const buildManifest = await this.getBuildManifest(componentLibrary)
const latest = buildManifest[buildManifest.length - 1]
const componentLibraryObject: ComponentLibrary = {
React: requireFromString(await this.storage.load(componentLibrary, latest.react), `${componentLibrary}/${latest.react}`),
ReactDOMServer: requireFromString(await this.storage.load(componentLibrary, latest.reactDOMServer), `${componentLibrary}/${latest.reactDOMServer}`),
Components: {}
}
const stats = (await this.getLatestStatsContents(componentLibrary)).node
for (const [componentName, componentAssets] of Object.entries(stats.assetsByChunkName)) {
const componentBasename = componentAssets.find((asset: string) => asset.endsWith('.js'))
const source = await this.storage.load(componentLibrary, componentBasename!)
const Component = requireFromString(source, `${componentLibrary}/${componentBasename}`).default
componentLibraryObject.Components[componentName] = Component
}
await this.hooks.componentLibraryLoad.promise({ core: this, componentLibrary, manifestEntry: latest }).catch(err => {
// TODO: find out how to get which plugin threw the error
const plugin = 'plugin'
this.logError(`theia:${plugin}:componentLibraryLoad`, err)
})
return this.libCache[componentLibrary] = componentLibraryObject
}
// temporary. just returns all the assets for a CL. change when codesplitting is working
async getAssets (componentLibrary: string, componentName: string): Promise<RenderResultAssets> {
const stats = (await this.getLatestStatsContents(componentLibrary)).browser
const assets = stats.assetsByChunkName[componentName]
return {
javascripts: assets.filter((asset: string) => asset.endsWith('.js')),
stylesheets: assets.filter((asset: string) => asset.endsWith('.css'))
}
}
async buildAll (): Promise<void> {
this.log('theia:build-all', 'building component libraries ...')
// purposefully serial - yarn has trouble running multiple processes
return bluebird.each(Object.keys(this.libs), componentLibrary => {
const componentLibraryConfig = this.libs[componentLibrary]
return this.builder.build(this, componentLibrary, componentLibraryConfig)
}).then(() => {
this.log('theia:build-all', 'finished building component libraries')
}).catch(err => {
this.logError('theia:build-all', `error while building component libraries ${err}`)
})
}
clearCache (componentLibrary?: string) {
if (componentLibrary) {
delete this.libCache[componentLibrary]
delete this.buildManifestCache[componentLibrary]
delete this.statsContentsCache[componentLibrary]
} else {
this.libCache = {}
this.buildManifestCache = {}
this.statsContentsCache = {}
}
}
log (namespace: string, ...toLog: any[]) {
_log(namespace, toLog.join())
}
logError (namespace: string, error: Error | string) {
_logError(namespace, error)
this.hooks.error.promise({ core: this, error }).catch(err => {
_logError(namespace, `there was an error in the error handling hooks: ${err}`)
})
}
}
export default Core