-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathindex.ts
83 lines (72 loc) · 2.32 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
import type { Plugin } from 'histoire'
import { defu } from 'defu'
import path from 'pathe'
import { fileURLToPath } from 'url'
import { createRequire } from 'module'
import { isPercyEnabled, fetchPercyDOM, postSnapshot } from '@percy/sdk-utils'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const require = createRequire(import.meta.url)
export interface PercyPluginOptions {
/**
* Ignored stories.
*/
ignored?: (payload: { file: string, story: { title: string }, variant: { id: string, title: string } }) => boolean
/**
* Percy options.
*/
percyOptions?: any
}
const defaultOptions: PercyPluginOptions = {
percyOptions: {},
}
export function HstPercy (options: PercyPluginOptions = {}): Plugin {
const finalOptions: PercyPluginOptions = defu(options, defaultOptions)
return {
name: '@histoire/plugin-percy',
onBuild: async api => {
if (!await isPercyEnabled()) {
return
}
const { default: puppeteer } = await import('puppeteer')
const browser = await puppeteer.launch()
// Collect client and env info
const sdkPkg = require(path.join(__dirname, '../package.json'))
const puppeteerPkg = require('puppeteer/package.json')
const CLIENT_INFO = `${sdkPkg.name}/${sdkPkg.version}`
const ENV_INFO = `${puppeteerPkg.name}/${puppeteerPkg.version}`
api.onPreviewStory(async ({ file, story, variant, url }) => {
if (finalOptions.ignored?.({
file,
story: {
title: story.title,
},
variant: {
id: variant.id,
title: variant.title,
},
})) {
return
}
const page = await browser.newPage()
await page.goto(url)
const name = `${story.title} > ${variant.title}`
await page.evaluate(await fetchPercyDOM())
const domSnapshot = await page.evaluate((opts) => {
// @ts-expect-error window global var
return window.PercyDOM.serialize(opts)
}, finalOptions.percyOptions)
await postSnapshot({
...finalOptions.percyOptions,
environmentInfo: ENV_INFO,
clientInfo: CLIENT_INFO,
url: page.url(),
domSnapshot,
name,
})
})
api.onBuildEnd(async () => {
await browser.close()
})
},
}
}