-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
197 lines (178 loc) · 5.39 KB
/
Copy pathindex.ts
File metadata and controls
197 lines (178 loc) · 5.39 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
/**
* This entry file is for main unplugin.
* @module
*/
import jsTokens from 'js-tokens'
import { withMagicString } from 'rolldown-string'
import { createUnplugin, type UnpluginInstance } from 'unplugin'
import {
resolveOptions,
type Options,
type ReplaceItem,
} from './core/options.ts'
export type { Options }
/**
* The main unplugin instance.
*/
const plugin: UnpluginInstance<Options | undefined, false> = createUnplugin<
Options | undefined,
false
>((rawOptions = {}) => {
const options = resolveOptions(rawOptions)
const {
include,
exclude,
enforce,
delimiters,
objectGuards,
preventAssignment,
includeComments,
} = options
const stringValues = options.values.filter(
(value): value is ReplaceItem<string> => typeof value.find === 'string',
)
const regexpValues = options.values.filter(
(value): value is ReplaceItem<RegExp> => value.find instanceof RegExp,
)
if (objectGuards) expandTypeofReplacements(stringValues)
const pattern = buildStringPattern()
const values = [...regexpValues]
if (pattern) {
values.unshift({ find: pattern, replacement: null! })
}
const name = 'unplugin-replace'
return {
name,
enforce,
buildStart() {
if (![true, false].includes(preventAssignment)) {
console.warn({
message: `${name}: 'preventAssignment' currently defaults to false. It is recommended to set this option to \`true\`, as the next major version will default this option to \`true\`.`,
})
}
},
transform: {
filter: { id: { include, exclude } },
handler: withMagicString(function (s, id) {
if (!values.length) return
let code = ''
if (includeComments) {
code = s.toString()
} else {
const tokens = jsTokens(s.toString(), { jsx: /\.[jt]sx?$/.test(id) })
for (const token of tokens) {
if (
token.type === 'MultiLineComment' ||
token.type === 'SingleLineComment' ||
token.type === 'HashbangComment'
) {
code += ' '.repeat(token.value.length)
} else {
code += token.value
}
}
}
let match: RegExpExecArray | null
for (const { find, replacement } of values) {
while ((match = find.exec(code))) {
const start = match.index
const end = start + match[0].length
const finalReplacement =
find === pattern
? stringValues.find(({ find }) => find === match![1])!
.replacement
: replacement
const result = String(ensureFunction(finalReplacement)(id, match))
s.overwrite(start, end, result)
if (!find.global) break
}
}
}),
},
vite: {
configResolved(config) {
options.sourceMap =
config.command === 'build' ? !!config.build.sourcemap : true
},
},
}
function buildStringPattern(): RegExp | undefined {
const escapedKeys = stringValues
.map(({ find }) => find)
.toSorted(longest)
.map(escape)
const lookbehind = preventAssignment
? String.raw`(?<!\b(?:const|let|var)\s*)`
: ''
const lookahead = preventAssignment ? String.raw`(?!\s*=[^=])` : ''
const pattern = new RegExp(
`${lookbehind}${delimiters[0]}(${escapedKeys.join('|')})${delimiters[1]}${lookahead}`,
'g',
)
if (escapedKeys.length > 0) {
return pattern
}
}
})
export default plugin
function escape(str: string) {
// eslint-disable-next-line unicorn/prefer-string-replace-all
return str.replace(/[$()*+./?[\\\]^{|}-]/g, String.raw`\$&`)
}
function ensureFunction(
functionOrValue: any,
): (id: string, match: RegExpExecArray) => any {
if (typeof functionOrValue === 'function') return functionOrValue
return () => functionOrValue
}
function longest(a: string, b: string) {
return b.length - a.length
}
const objKeyRegEx =
/^([$A-Z_\u00A0-\uFFFF][\w$\u00A0-\uFFFF]*)(\.([$A-Z_\u00A0-\uFFFF][\w$\u00A0-\uFFFF]*))+$/i
function expandTypeofReplacements(values: ReplaceItem<string>[]) {
values.forEach(({ find }) => {
const objMatch = find.match(objKeyRegEx)
if (!objMatch) return
let dotIndex = objMatch[1].length
let lastIndex = 0
do {
values.push(
{
find: `typeof ${find.slice(lastIndex, dotIndex)} ===`,
replacement: '"object" ===',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)} !==`,
replacement: '"object" !==',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)}===`,
replacement: '"object"===',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)}!==`,
replacement: '"object"!==',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)} ==`,
replacement: '"object" ===',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)} !=`,
replacement: '"object" !==',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)}==`,
replacement: '"object"===',
},
{
find: `typeof ${find.slice(lastIndex, dotIndex)}!=`,
replacement: '"object"!==',
},
)
lastIndex = dotIndex + 1
dotIndex = find.indexOf('.', lastIndex)
} while (dotIndex !== -1)
})
}