Skip to content

Commit

Permalink
feat: compatible with magic-string-stack
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed May 3, 2024
1 parent c066a67 commit 310f60d
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 3 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"bumpp": "^9.4.0",
"eslint": "^9.1.0",
"fast-glob": "^3.3.2",
"magic-string-stack": "^0.1.1",
"prettier": "^3.2.5",
"tsup": "^8.0.2",
"tsx": "^4.7.2",
Expand Down
44 changes: 44 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 10 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@ export class MagicStringAST implements MagicString {
/** offset of node */
offset?: number
},
private prototype: typeof MagicString = typeof str === 'string'
? MagicString
: (str.constructor as any),
) {
this.s = typeof str === 'string' ? new MagicString(str, options) : str
this.s = typeof str === 'string' ? new prototype(str, options) : str
this.offset = options?.offset ?? 0
return new Proxy(this.s, {
get: (target, p, receiver) => {
Expand Down Expand Up @@ -86,11 +89,15 @@ export class MagicStringAST implements MagicString {
let newS: MagicString
if (isEmptyNodes(node)) newS = this.s.snip(0, 0)
else newS = this.s.snip(...this.getNodePos(node, offset))
return new MagicStringAST(newS, { offset: this.offset })
return new MagicStringAST(newS, { offset: this.offset }, this.prototype)
}

clone(): this {
return new MagicStringAST(this.s.clone(), { offset: this.offset }) as any
return new MagicStringAST(
this.s.clone(),
{ offset: this.offset },
this.prototype,
) as any
}

toString(): string {
Expand Down
17 changes: 17 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, test } from 'vitest'
import MagicStringStack from 'magic-string-stack'
import { MagicString, MagicStringAST } from '../src'

test('basic', () => {
Expand Down Expand Up @@ -37,3 +38,19 @@ test('empty array', () => {
expect(s.overwriteNode([], 'new').toString()).toBe(ORIGINAL)
expect(s.moveNode([], 0).toString()).toBe(ORIGINAL)
})

test('compatible with magic-string-stack', () => {
const s = new MagicStringAST(
'hello world',
undefined,
MagicStringStack,
) as MagicStringAST & MagicStringStack
expect(s.commit).toBeDefined()
expect(s.clone().commit).toBeDefined()

const s2 = new MagicStringAST(
new MagicStringStack('hello world'),
) as MagicStringAST & MagicStringStack
expect(s2.commit).toBeDefined()
expect(s2.clone().commit).toBeDefined()
})

0 comments on commit 310f60d

Please sign in to comment.