forked from vitejs/vite
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathworkerImportMetaUrl.ts
216 lines (190 loc) · 6.31 KB
/
workerImportMetaUrl.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
import path from 'node:path'
import MagicString from 'magic-string'
import type { RolldownPlugin, RollupError } from 'rolldown'
import { stripLiteral } from 'strip-literal'
import type { ResolvedConfig } from '../config'
import { evalValue, injectQuery, transformStableResult } from '../utils'
import { createBackCompatIdResolver } from '../idResolver'
import type { ResolveIdFn } from '../idResolver'
import { cleanUrl, slash } from '../../shared/utils'
import type { WorkerType } from './worker'
import { WORKER_FILE_ID, workerFileToUrl } from './worker'
import { fileToUrl } from './asset'
import type { InternalResolveOptions } from './resolve'
import { tryFsResolve } from './resolve'
import { hasViteIgnoreRE } from './importAnalysis'
interface WorkerOptions {
type?: WorkerType
}
function err(e: string, pos: number) {
const error = new Error(e) as RollupError
error.pos = pos
return error
}
function parseWorkerOptions(
rawOpts: string,
optsStartIndex: number,
): WorkerOptions {
let opts: WorkerOptions = {}
try {
opts = evalValue<WorkerOptions>(rawOpts)
} catch {
throw err(
'Vite is unable to parse the worker options as the value is not static.' +
'To ignore this error, please use /* @vite-ignore */ in the worker options.',
optsStartIndex,
)
}
if (opts == null) {
return {}
}
if (typeof opts !== 'object') {
throw err(
`Expected worker options to be an object, got ${typeof opts}`,
optsStartIndex,
)
}
return opts
}
function getWorkerType(raw: string, clean: string, i: number): WorkerType {
const commaIndex = clean.indexOf(',', i)
if (commaIndex === -1) {
return 'classic'
}
const endIndex = clean.indexOf(')', i)
// case: ') ... ,' mean no worker options params
if (commaIndex > endIndex) {
return 'classic'
}
// need to find in comment code
const workerOptString = raw
.substring(commaIndex + 1, endIndex)
.replace(/\}[\s\S]*,/g, '}') // strip trailing comma for parsing
const hasViteIgnore = hasViteIgnoreRE.test(workerOptString)
if (hasViteIgnore) {
return 'ignore'
}
// need to find in no comment code
const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex).trim()
if (!cleanWorkerOptString.length) {
return 'classic'
}
const workerOpts = parseWorkerOptions(workerOptString, commaIndex + 1)
if (
workerOpts.type &&
(workerOpts.type === 'module' || workerOpts.type === 'classic')
) {
return workerOpts.type
}
return 'classic'
}
function isIncludeWorkerImportMetaUrl(code: string): boolean {
if (
(code.includes('new Worker') || code.includes('new SharedWorker')) &&
code.includes('new URL') &&
code.includes(`import.meta.url`)
) {
return true
}
return false
}
export function workerImportMetaUrlPlugin(
config: ResolvedConfig,
): RolldownPlugin {
const isBuild = config.command === 'build'
let workerResolver: ResolveIdFn
const fsResolveOptions: InternalResolveOptions = {
...config.resolve,
root: config.root,
isProduction: config.isProduction,
isBuild: config.command === 'build',
packageCache: config.packageCache,
asSrc: true,
}
return {
name: 'vite:worker-import-meta-url',
// shouldTransformCachedModule({ code }) {
// if (isBuild && config.build.watch && isIncludeWorkerImportMetaUrl(code)) {
// return true
// }
// },
transform: {
filter: {
code: {
include: [/(?:new Worker|new SharedWorker)/],
},
},
async handler(code, id) {
if (
this.environment.config.consumer === 'client' &&
isIncludeWorkerImportMetaUrl(code)
) {
let s: MagicString | undefined
const cleanString = stripLiteral(code)
const workerImportMetaUrlRE =
/\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg
let match: RegExpExecArray | null
while ((match = workerImportMetaUrlRE.exec(cleanString))) {
const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] =
match.indices!
const rawUrl = code.slice(urlStart, urlEnd)
// potential dynamic template string
if (rawUrl[0] === '`' && rawUrl.includes('${')) {
this.error(
`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`,
expStart,
)
}
s ||= new MagicString(code)
const workerType = getWorkerType(code, cleanString, endIndex)
const url = rawUrl.slice(1, -1)
let file: string | undefined
if (url[0] === '.') {
file = path.resolve(path.dirname(id), url)
file = tryFsResolve(file, fsResolveOptions) ?? file
} else {
workerResolver ??= createBackCompatIdResolver(config, {
extensions: [],
tryIndex: false,
preferRelative: true,
})
file = await workerResolver(this.environment, url, id)
file ??=
url[0] === '/'
? slash(path.join(config.publicDir, url))
: slash(path.resolve(path.dirname(id), url))
}
if (
isBuild &&
config.isWorker &&
config.bundleChain.at(-1) === cleanUrl(file)
) {
s.update(expStart, expEnd, 'self.location.href')
} else {
let builtUrl: string
if (isBuild) {
builtUrl = await workerFileToUrl(config, file)
} else {
builtUrl = await fileToUrl(this, cleanUrl(file))
builtUrl = injectQuery(
builtUrl,
`${WORKER_FILE_ID}&type=${workerType}`,
)
}
s.update(
expStart,
expEnd,
// NOTE: add `'' +` to opt-out rolldown's transform: https://github.com/rolldown/rolldown/issues/2745
`new URL(/* @vite-ignore */ ${JSON.stringify(builtUrl)}, '' + import.meta.url)`,
)
}
}
if (s) {
return transformStableResult(s, id, config)
}
return null
}
},
},
}
}