-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrenderDocument.ts
More file actions
86 lines (70 loc) · 1.99 KB
/
renderDocument.ts
File metadata and controls
86 lines (70 loc) · 1.99 KB
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
import {ux} from '@oclif/core'
import {tsWorkerTask} from '@sanity/cli-core'
import {buildDebug} from './buildDebug.js'
interface DocumentProps {
basePath: string
css?: string[]
entryPath?: string
}
interface RenderDocumentOptions {
studioRootPath: string
importMap?: {
imports?: Record<string, string>
}
isApp?: boolean
props?: DocumentProps
}
const hasWarnedAbout = new Set<string>()
interface RenderDocumentWorkerResult {
type: 'error' | 'result' | 'warning'
html?: string
message?: string | string[]
warnKey?: string
}
export async function renderDocument(options: RenderDocumentOptions): Promise<string> {
buildDebug('Starting worker thread for %s', import.meta.url)
try {
const msg = await tsWorkerTask<RenderDocumentWorkerResult>(
new URL(`renderDocument.worker.js`, import.meta.url),
{
name: 'renderDocument',
workerData: {...options, shouldWarn: true},
},
)
if (msg.type === 'warning') {
if (msg.warnKey && hasWarnedAbout.has(msg.warnKey)) {
return ''
}
if (Array.isArray(msg.message)) {
for (const warning of msg.message) {
ux.warn(warning)
}
} else if (msg.message) {
ux.warn(msg.message)
}
if (msg.warnKey) {
hasWarnedAbout.add(msg.warnKey)
}
return ''
}
if (msg.type === 'error') {
buildDebug('Error from worker: %s', msg.message || 'Unknown error')
throw new Error(
Array.isArray(msg.message)
? msg.message.join('\n')
: msg.message || 'Document rendering worker stopped with an unknown error',
)
}
if (msg.type === 'result') {
if (!msg.html) {
throw new Error('Document rendering worker stopped with an unknown error')
}
buildDebug('Document HTML rendered, %d bytes', msg.html.length)
return msg.html
}
throw new Error('Unknown message type')
} catch (err) {
buildDebug('Worker errored: %s', err.message)
throw err
}
}