-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiframe-preview-executor.js
More file actions
619 lines (523 loc) · 16.9 KB
/
Copy pathiframe-preview-executor.js
File metadata and controls
619 lines (523 loc) · 16.9 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
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
import {
createPreviewChannelId,
isPreviewProtocolMessage,
previewProtocolMessageTypes,
previewProtocolVersion,
toPreviewProtocolMessage,
} from './iframe-preview-protocol.js'
const previewIframeSandbox = 'allow-scripts allow-modals allow-forms allow-popups'
const createIframeHost = target => {
const iframe = document.createElement('iframe')
iframe.setAttribute('title', 'Preview iframe runtime')
iframe.setAttribute('sandbox', previewIframeSandbox)
target.replaceChildren(iframe)
return iframe
}
const escapeJsonForScriptTag = value =>
JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
const createIframeShellDocument = ({ channelId, parentOrigin, importMap }) => {
const bootstrapPayload = {
channelId,
parentOrigin,
protocolVersion: previewProtocolVersion,
}
const importMapJson = escapeJsonForScriptTag(importMap ?? {})
const bootstrapJson = escapeJsonForScriptTag(bootstrapPayload)
return `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="importmap">${importMapJson}</script>
</head>
<body>
<script type="module">
const __knightedBootstrap = ${bootstrapJson}
const __knightedChannelId = __knightedBootstrap.channelId
const __knightedParentOrigin = __knightedBootstrap.parentOrigin
const __knightedProtocolVersion = __knightedBootstrap.protocolVersion
const __knightedMessageTypes = {
ready: 'ready',
render: 'render',
configPatch: 'config-patch',
rendered: 'rendered',
runtimeError: 'runtime-error',
}
const __knightedState = {
entrySpecifier: '',
reactRoot: null,
renderedNodes: [],
visualConfig: {
cssText: '',
hostPadding: '',
backgroundColor: '',
},
}
const __knightedRuntimeErrorFingerprints = new Set()
const __knightedToMessage = (type, payload = {}) => ({
__knightedPreview: true,
version: __knightedProtocolVersion,
channelId: __knightedChannelId,
type,
...payload,
})
const __knightedIsValidMessage = data => {
return (
typeof data === 'object' &&
data !== null &&
data.__knightedPreview === true &&
data.version === __knightedProtocolVersion &&
data.channelId === __knightedChannelId &&
typeof data.type === 'string'
)
}
const __knightedEmit = (type, payload = {}) => {
parent.postMessage(__knightedToMessage(type, payload), __knightedParentOrigin)
}
const __knightedToBaseStyles = hostPadding => {
const resolvedPadding =
typeof hostPadding === 'string' && hostPadding.trim().length > 0
? hostPadding.trim()
: '18px'
return [
'html, body {',
' margin: 0;',
' min-height: 100%;',
' background: transparent;',
'}',
'html {',
' box-sizing: border-box;',
'}',
'*, *::before, *::after {',
' box-sizing: inherit;',
'}',
'body {',
' padding: var(--preview-host-padding, ' + resolvedPadding + ');',
' overflow-y: auto;',
' overflow-x: hidden;',
'}',
].join('\\n')
}
const __knightedApplyVisualConfig = ({ cssText = '', hostPadding = '', backgroundColor = '' }) => {
__knightedState.visualConfig = {
cssText: typeof cssText === 'string' ? cssText : '',
hostPadding: typeof hostPadding === 'string' ? hostPadding : '',
backgroundColor: typeof backgroundColor === 'string' ? backgroundColor : '',
}
let styleElement = document.getElementById('knighted-preview-styles')
if (!(styleElement instanceof HTMLStyleElement)) {
styleElement = document.createElement('style')
styleElement.id = 'knighted-preview-styles'
document.head.append(styleElement)
}
styleElement.textContent =
__knightedToBaseStyles(__knightedState.visualConfig.hostPadding) +
'\\n' +
String(__knightedState.visualConfig.cssText)
if (__knightedState.visualConfig.hostPadding.trim().length > 0) {
document.documentElement.style.setProperty(
'--preview-host-padding',
__knightedState.visualConfig.hostPadding.trim(),
)
} else {
document.documentElement.style.removeProperty('--preview-host-padding')
}
if (__knightedState.visualConfig.backgroundColor.length > 0) {
document.documentElement.style.backgroundColor =
__knightedState.visualConfig.backgroundColor
document.body.style.backgroundColor = __knightedState.visualConfig.backgroundColor
return
}
document.documentElement.style.removeProperty('background-color')
document.body.style.removeProperty('background-color')
}
const __knightedToErrorDetails = (error, origin) => {
const message = error instanceof Error ? error.message : String(error)
const stack = error instanceof Error && typeof error.stack === 'string' ? error.stack : ''
const moduleMatch = stack.match(/knighted-workspace\\/([^\\n\\s)]+)/)
return {
origin,
entrySpecifier: __knightedState.entrySpecifier,
message: String(message || 'Unknown runtime error'),
stack,
moduleContext: moduleMatch ? 'knighted-workspace/' + moduleMatch[1] : '',
}
}
const __knightedEmitRuntimeError = details => {
const isMissingReference =
typeof details.message === 'string' &&
details.message.toLowerCase().includes(' is not defined')
const isTransientOrigin = details.origin === 'window-error' || details.origin === 'promise'
if (isMissingReference && isTransientOrigin) {
return
}
const fingerprint =
String(details.origin) +
'|' +
String(details.entrySpecifier) +
'|' +
String(details.moduleContext) +
'|' +
String(details.message)
if (__knightedRuntimeErrorFingerprints.has(fingerprint)) {
return
}
__knightedRuntimeErrorFingerprints.add(fingerprint)
__knightedEmit(__knightedMessageTypes.runtimeError, details)
}
const __knightedRender = async config => {
const {
mode,
entrySpecifier,
entryDisplaySpecifier,
entryExportName,
runtimeSpecifiers,
} = config
__knightedState.entrySpecifier =
typeof entryDisplaySpecifier === 'string' && entryDisplaySpecifier.length > 0
? entryDisplaySpecifier
: typeof entrySpecifier === 'string'
? entrySpecifier
: ''
__knightedApplyVisualConfig(config)
if (
__knightedState.reactRoot &&
typeof __knightedState.reactRoot.unmount === 'function'
) {
__knightedState.reactRoot.unmount()
__knightedState.reactRoot = null
}
if (Array.isArray(__knightedState.renderedNodes)) {
for (const node of __knightedState.renderedNodes) {
if (node instanceof Node && node.parentNode) {
node.parentNode.removeChild(node)
}
}
__knightedState.renderedNodes = []
}
document.querySelectorAll('knighted-preview-root').forEach(node => node.remove())
try {
const entryModule = await import(entrySpecifier)
const App = entryModule.default ?? entryModule.App ?? entryModule[entryExportName]
if (typeof App !== 'function') {
throw new Error('Expected a function or const named App.')
}
if (mode === 'react') {
const [{ createRoot }, { reactJsx }] = await Promise.all([
import(runtimeSpecifiers.reactDomClient),
import(runtimeSpecifiers.jsxReact),
])
const output = reactJsx\`<\${App} />\`
if (!output) {
throw new Error('Expected a function or const named App.')
}
const host = document.createElement('knighted-preview-root')
document.body.append(host)
const root = createRoot(host)
__knightedState.reactRoot = root
__knightedState.renderedNodes = [host]
root.render(output)
} else {
const { jsx } = await import(runtimeSpecifiers.jsxDom)
const output = jsx\`<\${App} />\`
if (!(output instanceof Node)) {
throw new Error('Expected a function or const named App.')
}
const domNodes =
output instanceof DocumentFragment ? Array.from(output.childNodes) : [output]
document.body.append(output)
__knightedState.renderedNodes = domNodes
}
__knightedEmit(__knightedMessageTypes.rendered)
} catch (error) {
const details = __knightedToErrorDetails(error, 'execution')
__knightedEmitRuntimeError(details)
}
}
window.addEventListener('error', event => {
event.preventDefault()
const details = __knightedToErrorDetails(
event?.error ?? event?.message ?? 'Unknown runtime error',
'window-error',
)
__knightedEmitRuntimeError(details)
})
window.addEventListener('unhandledrejection', event => {
event.preventDefault()
const details = __knightedToErrorDetails(
event?.reason ?? 'Unknown promise rejection',
'promise',
)
__knightedEmitRuntimeError(details)
})
window.addEventListener('message', event => {
if (event.origin !== __knightedParentOrigin || !__knightedIsValidMessage(event.data)) {
return
}
const data = event.data
if (data.type === __knightedMessageTypes.configPatch) {
const patch =
data && typeof data.payload === 'object' && data.payload !== null
? data.payload
: data && typeof data === 'object'
? data
: {}
__knightedApplyVisualConfig({
...__knightedState.visualConfig,
...patch,
})
return
}
if (data.type !== __knightedMessageTypes.render) {
return
}
void __knightedRender(data)
})
__knightedEmit(__knightedMessageTypes.ready)
</script>
</body>
</html>`
}
const toIframeRuntimeError = data => {
const message =
typeof data?.message === 'string' && data.message.length > 0
? data.message
: 'Unknown runtime error'
const lines = [`[runtime] ${message}`]
if (typeof data?.entrySpecifier === 'string' && data.entrySpecifier.length > 0) {
lines.push(`Entry: ${data.entrySpecifier}`)
}
if (typeof data?.moduleContext === 'string' && data.moduleContext.length > 0) {
lines.push(`Module: ${data.moduleContext}`)
}
if (typeof data?.origin === 'string' && data.origin.length > 0) {
lines.push(`Source: ${data.origin}`)
}
const error = new Error(lines.join('\n'))
if (typeof data?.stack === 'string' && data.stack.length > 0) {
error.stack = data.stack
}
return error
}
export const createWorkspaceIframePreviewBridge = ({
target,
parentOrigin = globalThis.location.origin,
onRuntimeError,
onTelemetryEvent,
}) => {
const iframe = createIframeHost(target)
const channelId = createPreviewChannelId()
const emitTelemetry = (name, details = {}) => {
if (typeof onTelemetryEvent === 'function') {
onTelemetryEvent({
name,
at: performance.now(),
channelId,
...details,
})
}
}
let active = true
let ready = false
let resolveReady = () => {}
const readyWaiters = new Set()
const readyPromise = new Promise(resolve => {
resolveReady = resolve
})
let pendingRender = null
const waitForReady = timeoutMs => {
if (ready) {
return Promise.resolve()
}
if (!active) {
return Promise.reject(new Error('Preview iframe bridge is not active.'))
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
readyWaiters.delete(onDisposed)
reject(new Error('Workspace preview iframe did not become ready before timeout.'))
}, timeoutMs)
const onReady = () => {
clearTimeout(timer)
readyWaiters.delete(onDisposed)
resolve()
}
const onDisposed = error => {
clearTimeout(timer)
reject(
error instanceof Error
? error
: new Error('Preview iframe bridge was disposed before readiness.'),
)
}
readyPromise.then(onReady)
readyWaiters.add(onDisposed)
})
}
const cleanupPendingRender = (error = null) => {
if (!pendingRender) {
return
}
const { timer, resolve, reject } = pendingRender
clearTimeout(timer)
pendingRender = null
if (error) {
reject(error)
return
}
resolve()
}
const postMessageToIframe = ({ type, payload = {} }) => {
if (!active || !iframe.contentWindow) {
return false
}
iframe.contentWindow.postMessage(
toPreviewProtocolMessage({
channelId,
type,
payload,
}),
'*',
)
return true
}
const onMessage = event => {
if (!active) {
return
}
if (!iframe.contentWindow || event.source !== iframe.contentWindow) {
return
}
const data = event?.data
if (!isPreviewProtocolMessage({ data, channelId })) {
return
}
if (data.type === previewProtocolMessageTypes.ready) {
ready = true
emitTelemetry('iframe-ready')
resolveReady()
return
}
if (data.type === previewProtocolMessageTypes.rendered) {
emitTelemetry('rendered')
cleanupPendingRender()
return
}
if (data.type === previewProtocolMessageTypes.runtimeError) {
emitTelemetry('runtime-error', {
origin: typeof data?.origin === 'string' ? data.origin : '',
})
const runtimeError = toIframeRuntimeError(data)
if (pendingRender) {
cleanupPendingRender(runtimeError)
return
}
if (typeof onRuntimeError === 'function') {
onRuntimeError(runtimeError)
}
}
}
window.addEventListener('message', onMessage)
iframe.srcdoc = createIframeShellDocument({
channelId,
parentOrigin,
importMap: {},
})
const dispose = () => {
if (!active) {
return
}
active = false
window.removeEventListener('message', onMessage)
if (readyWaiters.size > 0) {
const disposeError = new Error(
'Preview iframe bridge was disposed before readiness.',
)
for (const notifyDisposed of readyWaiters) {
notifyDisposed(disposeError)
}
readyWaiters.clear()
}
if (pendingRender) {
cleanupPendingRender(
new Error('Preview iframe bridge disposed before render completed.'),
)
}
}
const render = async ({
mode,
entrySpecifier,
entryDisplaySpecifier,
entryExportName,
importMap,
cssText,
hostPadding = '',
backgroundColor = '',
runtimeSpecifiers,
timeoutMs = 12000,
}) => {
if (!active) {
throw new Error('Preview iframe bridge is not active.')
}
if (pendingRender) {
throw new Error('Preview iframe render already in flight.')
}
await waitForReady(timeoutMs)
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingRender = null
emitTelemetry('timeout')
reject(new Error('Workspace preview execution timed out.'))
}, timeoutMs)
pendingRender = {
resolve: () => {
resolve({
iframe,
dispose,
render,
updateBackgroundColor,
})
},
reject,
timer,
}
const payload = {
mode,
entrySpecifier,
entryDisplaySpecifier,
entryExportName,
runtimeSpecifiers,
cssText,
hostPadding,
backgroundColor,
importMap,
parentOrigin,
}
const sent = postMessageToIframe({
type: previewProtocolMessageTypes.render,
payload,
})
if (!sent) {
clearTimeout(timer)
pendingRender = null
reject(new Error('Unable to initialize preview iframe document.'))
}
})
}
const updateBackgroundColor = nextColor => {
postMessageToIframe({
type: previewProtocolMessageTypes.configPatch,
payload: {
backgroundColor: typeof nextColor === 'string' ? nextColor : '',
},
})
}
return {
target,
iframe,
dispose,
render,
updateBackgroundColor,
isReady: () => ready,
}
}