Skip to content

Commit

Permalink
fix(config): avoid serialization warning when primitives have prototy…
Browse files Browse the repository at this point in the history
…pe changed (#2902)
  • Loading branch information
SoaresMG authored Jan 6, 2025
1 parent d63d0df commit d8fb358
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/core/config/resolvers/runtime-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,13 @@ function provideFallbackValues(obj: Record<string, any>) {
}

function checkSerializableRuntimeConfig(obj: any, path: string[] = []) {
if (isPrimitiveValue(obj)) {
return;
}

for (const key in obj) {
const value = obj[key];
if (
value === null ||
typeof value === "string" ||
value === undefined ||
typeof value === "number" ||
typeof value === "boolean"
) {
if (value === null || value === undefined || isPrimitiveValue(value)) {
continue;
}

Expand All @@ -67,3 +65,11 @@ function checkSerializableRuntimeConfig(obj: any, path: string[] = []) {
}
}
}

function isPrimitiveValue(value: any) {
return (
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
);
}
62 changes: 62 additions & 0 deletions test/unit/runtime-config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from "vitest";
import { normalizeRuntimeConfig } from "../../src/core/config/resolvers/runtime-config";
import type { NitroConfig } from "nitropack/types";

const defaultRuntimeConfig = {
textProperty: "value",
numberProperty: 42,
booleanProperty: true,
arrayProperty: ["A", "B", "C"],
objectProperty: {
innerProperty: "value",
},
mixedArrayProperty: [
"A",
"B",
{
inner: {
innerProperty: "value",
},
},
],
};

const nitroConfig: NitroConfig = {
runtimeConfig: defaultRuntimeConfig,
baseURL: "https://example.com",
experimental: {
envExpansion: false,
},
};

describe("normalizeRuntimeConfig", () => {
it("should not warn on a serializable runtime config", () => {
const warnSpy = vi.spyOn(console, "warn");
normalizeRuntimeConfig(nitroConfig);
expect(warnSpy).not.toHaveBeenCalled();
});

it("should not warn when primitive prototype is changed", () => {
const warnSpy = vi.spyOn(console, "warn");

// https://github.com/nitrojs/nitro/pull/2902
(String.prototype as any).brokenFunction = () => undefined;

normalizeRuntimeConfig(nitroConfig);
expect(warnSpy).not.toHaveBeenCalled();

delete (String.prototype as any).brokenFunction;
});

it("should throw a warning when runtimeConfig is not serializable", () => {
const warnSpy = vi.spyOn(console, "warn");
normalizeRuntimeConfig({
...nitroConfig,
runtimeConfig: {
...defaultRuntimeConfig,
brokenProperty: new Map(),
},
});
expect(warnSpy).toHaveBeenCalled();
});
});

0 comments on commit d8fb358

Please sign in to comment.