Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
97 lines (88 loc) · 3.03 KB
/
Copy pathindex.ts
File metadata and controls
97 lines (88 loc) · 3.03 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
import { createUnplugin, type UnpluginInstance } from 'unplugin'
import { createFilter } from 'unplugin-utils'
import { resolveOptions, type Options } from './core/options.ts'
import { transformRaw } from './core/transform.ts'
import type { PluginContext } from 'rollup'
const rawRE = /[&?]raw(?:&|$)/
const bytesRE = /[&?]bytes(?:&|$)/
const postfixRE = /[#?].*$/s
function cleanUrl(url: string) {
return url.replace(postfixRE, '')
}
const unplugin: UnpluginInstance<Options | undefined, false> = createUnplugin(
(rawOptions = {}, meta) => {
const options = resolveOptions(rawOptions)
const transformFilter = options.transform
? createFilter(options.transform.include, options.transform.exclude)
: undefined
return {
name: 'unplugin-raw',
enforce: options.enforce,
resolveId: ['rollup', 'rolldown', 'vite'].includes(meta.framework)
? async function (this, id, importer, options) {
const attributeType = (options as any)?.attributes?.type
if (attributeType === 'text') {
id += `${id.includes('?') ? '&' : '?'}raw`
} else if (attributeType === 'bytes') {
id += `${id.includes('?') ? '&' : '?'}bytes`
} else if (!rawRE.test(id) && !bytesRE.test(id)) {
return
}
const file = cleanUrl(id)
const resolved = await (this as PluginContext).resolve(
file,
importer,
)
if (!resolved) return
return id.replace(file, resolved.id)
}
: undefined,
load: {
filter: {
id: { include: [rawRE, bytesRE] },
},
async handler(id) {
const file = cleanUrl(id)
this.addWatchFile(file)
const context = this.getNativeBuildContext?.()
const transform =
context?.framework === 'esbuild'
? context.build.esbuild.transform
: undefined
let contents = await transformRaw(
file,
bytesRE.test(id) ? 'bytes' : 'text',
transform,
transformFilter,
options.transform ? options.transform.options : undefined,
)
if (typeof contents !== 'string') {
contents = `export default new Uint8Array([${contents.join(', ')}])`
}
return contents
},
},
esbuild: {
setup(build) {
build.onLoad({ filter: /.*/ }, async (args) => {
const type = args.with.type
if (type === 'text' || type === 'bytes') {
const contents = await transformRaw(
args.path,
type,
build.esbuild.transform,
transformFilter,
options.transform ? options.transform.options : undefined,
)
return {
contents,
loader: typeof contents === 'string' ? 'js' : 'binary',
}
}
})
},
},
}
},
)
export default unplugin