Skip to content

Commit 545d244

Browse files
authored
feat: support offset modification (#4)
1 parent 4c0fa2e commit 545d244

File tree

4 files changed

+99
-21
lines changed

4 files changed

+99
-21
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
},
5353
"dependencies": {
5454
"@ampproject/remapping": "^2.3.0",
55-
"magic-string": "^0.30.10"
55+
"magic-string": "^0.30.17"
5656
},
5757
"devDependencies": {
5858
"@antfu/eslint-config": "^2.14.0",

pnpm-lock.yaml

+82-19
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/index.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@ export default class MagicStringStack implements MagicStringStackType {
4444
return parent
4545
},
4646
set: (_, p, value) => {
47-
return Reflect.set(this, p, value, this)
47+
if (Reflect.has(this, p))
48+
return Reflect.set(this, p, value, this)
49+
50+
return Reflect.set(this._current, p, value)
4851
},
4952
}) as any
5053

@@ -58,6 +61,7 @@ export default class MagicStringStack implements MagicStringStackType {
5861
*/
5962
commit() {
6063
const newOne = new MagicString(this._current.toString(), this._options)
64+
newOne.offset = this._current.offset
6165
this._current = newOne
6266
this._stack.unshift(newOne)
6367
return this

test/index.test.ts

+11
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@ it('should be chainable', () => {
111111
.toMatchInlineSnapshot(`"AAAA,OAAK,CAAC"`)
112112
})
113113

114+
it('should support offset modification', () => {
115+
const s = new MagicStringStack(' problems = 99')
116+
s.offset = 1
117+
s.update(0, 8, 'answer')
118+
expect(s.toString()).toMatchInlineSnapshot(`" answer = 99"`)
119+
120+
s.commit()
121+
s.update(0, 6, 'problems')
122+
expect(s.toString()).toMatchInlineSnapshot(`" problems = 99"`)
123+
})
124+
114125
function removeEmptyKeys(obj: any) {
115126
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => !(v == null || (Array.isArray(v) && !v.length))))
116127
}

0 commit comments

Comments
 (0)