1- import { matchFile , REWRITE_PATTERN , REWRITE_REPLACER } from './config'
1+ import type { Group } from './config'
2+ import { GROUPS } from './config'
23
34async function rewriteScript ( ) {
45 const current = document . currentScript as HTMLScriptElement
@@ -13,15 +14,38 @@ async function rewriteScript() {
1314 current . replaceWith ( script )
1415 }
1516
17+ function applyGroup ( content : string , group : Group ) {
18+ const markers = group . markers || [ ]
19+
20+ if ( ! markers . every ( ( marker ) => content . includes ( marker ) ) ) {
21+ return content
22+ }
23+
24+ let out = content
25+ for ( const { pattern, replacer } of group . replacements ) {
26+ if ( typeof pattern === 'string' ) {
27+ // @ts -ignore
28+ out = out . replaceAll ( pattern , replacer )
29+ } else {
30+ // @ts -ignore
31+ out = out . replace ( pattern , replacer )
32+ }
33+ }
34+ return out
35+ }
36+
1637 try {
17- let content = await ( await fetch ( src ) ) . text ( )
38+ const original = await ( await fetch ( src ) ) . text ( )
39+ let content = original
40+
41+ for ( const group of GROUPS ) {
42+ content = applyGroup ( content , group )
43+ }
1844
19- if ( matchFile ( src , content ) ) {
20- content = content . replace ( REWRITE_PATTERN , REWRITE_REPLACER )
45+ if ( content !== original ) {
2146 console . log ( `Rewrote script: ${ src } ` )
2247 }
2348
24- // delete window.figma may throw Error in strict mode
2549 content = content . replaceAll ( 'delete window.figma' , 'window.figma = undefined' )
2650
2751 Object . defineProperty ( document , 'currentScript' , {
0 commit comments