-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-source-plugin.ts
More file actions
77 lines (64 loc) · 2.31 KB
/
code-source-plugin.ts
File metadata and controls
77 lines (64 loc) · 2.31 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
import path from 'node:path'
import type { Plugin } from 'vite'
const node_modules_path = path.resolve(__dirname, 'node_modules')
const sourceVariableRegex =
/(const|let|var)\s*(\w+)\s*=\s*["']["']\s*\/\*\s*code-source:\s*([a-zA-Z0-9\s]+)\s*\*\//g
const sectionStartRegex = /\/\/\s*#region ([a-zA-Z0-9_\s]+)/g
const sectionEndRegex = /\/\/\s*#endregion/g
export default function CodeSourcePlugin() {
return {
name: 'code-source-plugin',
enforce: 'pre',
transform(code, fileName) {
// Check if id is subpath of node_modules_path
if (path.resolve(fileName).startsWith(node_modules_path)) {
return
}
// Does the file have a source variable?
const sourceVariableMatch = code.match(sourceVariableRegex)
if (!sourceVariableMatch) {
return
}
const sections: Record<string, string> = {}
const lines = code.split('\n')
let sectionName = ''
let currentSection = ''
for (const line of lines) {
const sectionMatchStart = sectionStartRegex.exec(line)
if (sectionMatchStart != null) {
sectionName = sectionMatchStart[1]
currentSection = ''
continue
}
const sectionMatchEnd = line.match(sectionEndRegex)
if (sectionMatchEnd != null && currentSection.trim() !== '') {
sections[sectionName.trim()] = currentSection
currentSection = ''
sectionName = ''
continue
}
currentSection += line + '\n'
}
let finalCode = code
for (const sourceLine of sourceVariableMatch) {
// For some reason i need to instantiate a new regex object every time
const [, variableType, variableName, codeSectionName] =
/(const|let|var)\s*(\w+)\s*=\s*["']["']\s*\/\*\s*code-source:\s*([a-zA-Z0-9\s]+)\s*\*\//g.exec(
sourceLine,
) ?? []
if (variableName == null || codeSectionName == null) {
continue
}
const sourceCode = sections[codeSectionName.trim()]
if (sourceCode == null) {
continue
}
finalCode = finalCode.replace(
sourceLine,
`${variableType} ${variableName} = "${sourceCode.trim().replaceAll('\n', '\\n').replaceAll('"', '\\"')}";`,
)
}
return finalCode
},
} satisfies Plugin
}