diff --git a/.changeset/shy-planets-move.md b/.changeset/shy-planets-move.md new file mode 100644 index 000000000000..08541e30096a --- /dev/null +++ b/.changeset/shy-planets-move.md @@ -0,0 +1,7 @@ +--- +"wrangler": patch +--- + +fix: correctly escape newlines in `constructType` function for multiline strings + +This fix ensures that multiline strings are correctly handled by the `constructType` function. Newlines are now properly escaped to prevent invalid JavaScript code generation when using the `wrangler types` command. This improves robustness and prevents errors related to multiline string handling in environment variables and other configuration settings. diff --git a/packages/wrangler/src/__tests__/type-generation.test.ts b/packages/wrangler/src/__tests__/type-generation.test.ts index cbe99af69aa1..bdd22e0115f0 100644 --- a/packages/wrangler/src/__tests__/type-generation.test.ts +++ b/packages/wrangler/src/__tests__/type-generation.test.ts @@ -65,9 +65,9 @@ describe("constructType", () => { ); expect(constructType("valid", 'a"', false)).toBe('valid: "a\\"";'); - expect(constructType("valid", "a\\", false)).toBe('valid: "a\\";'); - expect(constructType("valid", "a\\b", false)).toBe('valid: "a\\b";'); - expect(constructType("valid", 'a\\b"', false)).toBe('valid: "a\\b\\"";'); + expect(constructType("valid", "a\\", false)).toBe('valid: "a\\\\";'); + expect(constructType("valid", "a\\b", false)).toBe('valid: "a\\\\b";'); + expect(constructType("valid", 'a\\b"', false)).toBe('valid: "a\\\\b\\"";'); expect(constructType("valid", 1)).toBe("valid: 1;"); expect(constructType("valid", 12345)).toBe("valid: 12345;"); @@ -76,6 +76,14 @@ describe("constructType", () => { }); }); +describe("constructType with multiline strings", () => { + it("should correctly escape newlines in string values", () => { + const multilineString = "This is a\nmulti-line\nstring"; + const expected = `valid: "This is a\\nmulti-line\\nstring";`; + expect(constructType("valid", multilineString, false)).toBe(expected); + }); +}); + const bindingsConfigMock: Omit< EnvironmentNonInheritable, "define" | "tail_consumers" | "constellation" | "cloudchamber" diff --git a/packages/wrangler/src/type-generation.ts b/packages/wrangler/src/type-generation.ts index aec6cf5cd38d..b665cba9e66a 100644 --- a/packages/wrangler/src/type-generation.ts +++ b/packages/wrangler/src/type-generation.ts @@ -144,7 +144,7 @@ export function constructType( if (useRawVal) { return `${typeKey}: ${value};`; } - return `${typeKey}: "${value.replace(/"/g, '\\"')}";`; + return `${typeKey}: ${JSON.stringify(value)};`; } if (typeof value === "number" || typeof value === "boolean") { return `${typeKey}: ${value};`;