diff --git a/src/proxy/array.ts b/src/proxy/array.ts index 326b317..4f8dc74 100644 --- a/src/proxy/array.ts +++ b/src/proxy/array.ts @@ -42,7 +42,11 @@ export function proxifyArrayElements( if (typeof key === "symbol") { return; } - const prop = getItem(+key); + const index = +key; + if (Number.isNaN(index)) { + return; + } + const prop = getItem(index); if (prop) { return proxify(prop); } @@ -51,7 +55,22 @@ export function proxifyArrayElements( if (typeof key === "symbol") { return false; } - replaceItem(+key, literalToAst(value)); + const index = +key; + if (Number.isNaN(index)) { + return false; + } + replaceItem(index, literalToAst(value)); + return true; + }, + deleteProperty(_, key) { + if (typeof key === "symbol") { + return false; + } + const index = +key; + if (Number.isNaN(index)) { + return false; + } + elements[index] = literalToAst(undefined); return true; }, ownKeys() { diff --git a/src/proxy/object.ts b/src/proxy/object.ts index 30eed77..d754602 100644 --- a/src/proxy/object.ts +++ b/src/proxy/object.ts @@ -61,6 +61,18 @@ export function proxifyObject(node: ESNode): Proxified { replaceOrAddProp(key, literalToAst(value)); return true; }, + deleteProperty(_, key) { + if (typeof key !== "string") { + key = String(key); + } + const index = node.properties.findIndex( + (prop) => "key" in prop && "name" in prop.key && prop.key.name === key + ); + if (index !== -1) { + node.properties.splice(index, 1); + } + return true; + }, ownKeys() { return node.properties .map((prop) => { diff --git a/test/index.test.ts b/test/index.test.ts index 029a4ba..4818cd1 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -111,7 +111,7 @@ describe("magicast", () => { ); }); - it("parse, update, generate", () => { + it("function wrapper", () => { const mod = parseCode(` export const a: any = { foo: 1} export default defineConfig({ @@ -145,4 +145,26 @@ describe("magicast", () => { });" `); }); + + it("delete property", () => { + const mod = parseCode(`export default { a: 1, b: [1, { foo: 'bar' }] }`); + + delete mod.exports.default.b[1].foo; + + expect(generate(mod)).toMatchInlineSnapshot( + '"export default { a: 1, b: [1, {}] };"' + ); + + delete mod.exports.default.b[0]; + expect(generate(mod)).toMatchInlineSnapshot( + '"export default { a: 1, b: [undefined, {}] };"' + ); + + delete mod.exports.default.a; + expect(generate(mod)).toMatchInlineSnapshot(` + "export default { + b: [undefined, {}], + };" + `); + }); });