Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/quicktype-core/src/language/Elm/ElmRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export class ElmRenderer extends ConvenienceRenderer {
}

protected forbiddenNamesForGlobalNamespace(): readonly string[] {
if (this.forEachType((type) => type.kind).has("map"))
return [...forbiddenNames, "makeDictEncoder"];
return forbiddenNames;
}

Expand Down Expand Up @@ -344,7 +346,7 @@ export class ElmRenderer extends ConvenienceRenderer {
(mapType) =>
multiWord(
" ",
"Jenc.dict",
"makeDictEncoder",
"identity",
parenIfNeeded(this.encoderNameForType(mapType.values)),
),
Expand Down Expand Up @@ -801,6 +803,16 @@ import Dict exposing (Dict)`);

this.emitLine("--- encoder helpers");
this.ensureBlankLine();
if (this.haveMaps) {
this.emitMultiline(`makeDictEncoder : (String -> String) -> (a -> Jenc.Value) -> Dict String a -> Jenc.Value
makeDictEncoder f m r =
r
|> Dict.toList
|> List.map (\\( x, y ) -> Jenc.encode 0 (Jenc.string (f x)) ++ ":" ++ Jenc.encode 0 (m y))
|> String.join ","
|> (\\str -> Jdec.decodeString Jdec.value ("{" ++ str ++ "}") |> Result.withDefault Jenc.null)`);
this.ensureBlankLine();
}
this.emitMultiline(`makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
makeNullableEncoder f m =
case m of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ ${hasArrayConstraints ? ' if ((typ.min !== undefined && val.length < typ.
if (val === null || typeof val !== "object" || Array.isArray(val)) {
return invalidValue(l(ref || "object"), val, key, parent);
}
const result${anyAnnotation} = {};
const result${anyAnnotation} = Object.create(null);
Object.getOwnPropertyNames(props).forEach(key => {
const prop = props[key];
const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
Expand All @@ -471,7 +471,7 @@ ${hasArrayConstraints ? ' if ((typ.min !== undefined && val.length < typ.
};
}
});
return result;
return Object.setPrototypeOf(result, Object.prototype);
}

if (typ === "any") return val;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ export class TypeScriptEffectSchemaRenderer extends ConvenienceRenderer {
},
(_classType) => panic("Should already be handled."),
(_mapType) => [
"S.Record({ key: S.String, value: ",
"mapSchema(",
this.typeMapTypeFor(_mapType.values, false),
"})",
")",
],
(_enumType) => panic("Should already be handled."),
(unionType) => {
Expand Down Expand Up @@ -406,6 +406,26 @@ export class TypeScriptEffectSchemaRenderer extends ConvenienceRenderer {
}

this.emitImports();
if (this.haveMaps) {
this.emitMultiline(`
const objectSchema = <A>() =>
S.declare(
(input): input is Record<string, A> =>
typeof input === "object" && input !== null && !Array.isArray(input)
);
const mapSchema = <A, I, R>(value: S.Schema<A, I, R>) => {
const entries = S.transform(objectSchema<unknown>(), S.Array(S.Tuple(S.String, value)), {
strict: false,
decode: Object.entries,
encode: Object.fromEntries
});
return S.transform(entries, objectSchema<A>(), {
strict: false,
decode: Object.fromEntries,
encode: Object.entries
});
};`);
}
this.emitSchemas();
}
}
15 changes: 8 additions & 7 deletions test/inputs/json/priority/keywords.json
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@
"Locale": { "Locale": 123 },
"lock": { "lock": 123 },
"long": { "long": 123 },
"makeDictEncoder": { "makeDictEncoder": 123 },
"map": { "map": 123 },
"MarshalJSON": { "MarshalJSON": 123 },
"MapEntry": { "MapEntry": 123 },
Expand All @@ -197,11 +198,11 @@
"native": { "native": 123 },
"new": { "new": 123 },
"newtonsoft": { "newtonsoft": 123 },
"nil": { "nil": 123 },
"NO": { "NO": 123 },
"dummy": 123
},
"obj4": {
"nil": { "nil": 123 },
"NO": { "NO": 123 },
"noexcept": { "noexcept": 123 },
"nonatomic": { "nonatomic": 123 },
"none": { "none": 123 },
Expand Down Expand Up @@ -264,11 +265,11 @@
"runtimeType": { "runtimeType": 123 },
"s": { "s": 123 },
"sbyte": { "sbyte": 123 },
"sealed": { "sealed": 123 },
"SEL": { "SEL": 123 },
"dummy": 123
},
"obj5": {
"sealed": { "sealed": 123 },
"SEL": { "SEL": 123 },
"select": { "select": 123 },
"Self": { "Self": 123 },
"Serializable": { "Serializable": 123 },
Expand Down Expand Up @@ -331,12 +332,12 @@
"undefined": { "undefined": 123 },
"union": { "union": 123 },
"UnmarshalJSON": { "UnmarshalJSON": 123 },
"UseSerializers": { "UseSerializers": 123 },
"unowned": { "unowned": 123 },
"unsafe": { "unsafe": 123 },
"dummy": 123
},
"obj6": {
"UseSerializers": { "UseSerializers": 123 },
"unowned": { "unowned": 123 },
"unsafe": { "unsafe": 123 },
"unsigned": { "unsigned": 123 },
"ushort": { "ushort": 123 },
"using": { "using": 123 },
Expand Down
5 changes: 5 additions & 0 deletions test/inputs/schema/class-map-union.5.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"union": {
"__proto__": true
}
}
1 change: 1 addition & 0 deletions test/inputs/schema/keyword-enum.schema
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@
"Locale",
"lock",
"long",
"makeDictEncoder",
"map",
"MarshalJSON",
"MapEntry",
Expand Down
7 changes: 7 additions & 0 deletions test/inputs/schema/keyword-unions.schema
Original file line number Diff line number Diff line change
Expand Up @@ -1261,6 +1261,13 @@
],
"title": "union_long"
},
"makeDictEncoder": {
"oneOf": [
{ "type": "number" },
{ "type": "object", "additionalProperties": false, "title": "makeDictEncoder" }
],
"title": "union_makeDictEncoder"
},
"map": {
"oneOf": [
{ "type": "number" },
Expand Down
1 change: 1 addition & 0 deletions test/keywords.txt
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ list
Locale
lock
long
makeDictEncoder
map
MarshalJSON
MapEntry
Expand Down
24 changes: 24 additions & 0 deletions test/unit/javascript-prototype-key.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import vm from "node:vm";

import { InputData, JSONSchemaInput, quicktype } from "quicktype-core";
import { expect, test } from "vitest";

test("JavaScript converters return plain objects for prototype-named keys", async () => {
const schemaInput = new JSONSchemaInput(undefined);
await schemaInput.addSource({
name: "TopLevel",
schema: JSON.stringify({
type: "object",
additionalProperties: { type: "boolean" },
}),
});
const inputData = new InputData();
inputData.addInput(schemaInput);
const result = await quicktype({ inputData, lang: "javascript" });
const module = { exports: {} as Record<string, (json: string) => object> };

vm.runInNewContext(result.lines.join("\n"), { module, Object });
const converted = module.exports.toTopLevel('{"__proto__":true}');

expect(Object.getPrototypeOf(converted)).toBe(Object.prototype);
});
Loading