Skip to content

AI-native design editor. Open-source Figma alternative.

fix(kiwi): interpret compiled schemas without eval

Dmitriy Shekhovtsovdd15190fc952
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 5ba9a51a9..4ea2b5dc0 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -55,6 +55,7 @@ export async function parseFigmaClipboard(
const schemaBytes = inflateSync(chunks[0])
const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
const compiled = compileSchema(schema)
+ if (!compiled.decodeMessage) return null
const dataRaw = await decompressFigKiwiDataAsync(chunks[1])
const msg = compiled.decodeMessage(dataRaw) as {
nodeChanges?: KiwiNodeChange[]
diff --git a/packages/kiwi/NOTICE b/packages/kiwi/NOTICE
new file mode 100644
index 000000000..ac825b3ab
--- /dev/null
+++ b/packages/kiwi/NOTICE
@@ -0,0 +1,28 @@
+Kiwi schema runtime
+
+Copyright (c) 2016-2023 Evan Wallace
+
+This package includes an adapted implementation of the JavaScript Kiwi schema
+runtime from:
+
+https://github.com/evanw/kiwi
+
+The original implementation is licensed under the MIT License:
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/kiwi/README.md b/packages/kiwi/README.md
index 52c71a036..0b0c7ec25 100644
--- a/packages/kiwi/README.md
+++ b/packages/kiwi/README.md
@@ -4,7 +4,13 @@ Scene-graph-agnostic Kiwi runtime utilities for OpenPencil.
This package owns pure Kiwi schema parsing, Figma Kiwi schema data, low-level Figma message encode/decode, raw `fig-kiwi` container helpers, and GUID formatting. Complete `.fig` archive parsing lives in `@open-pencil/fig`; SceneGraph integration remains outside this package.
-## Installation
+## Credits and licensing
+
+The schema runtime is based on [Kiwi](https://github.com/evanw/kiwi), a
+schema-based binary format and JavaScript implementation by Evan Wallace.
+The original Kiwi implementation is copyright (c) 2016–2023 Evan Wallace and
+is licensed under the MIT License. OpenPencil's adapted runtime is distributed
+under the terms of that license; see [`NOTICE`](./NOTICE).
```sh
bun add @open-pencil/kiwi
diff --git a/packages/kiwi/package.json b/packages/kiwi/package.json
index fe8014b47..9222e6b37 100644
--- a/packages/kiwi/package.json
+++ b/packages/kiwi/package.json
@@ -2,7 +2,20 @@
"name": "@open-pencil/kiwi",
"version": "0.14.0",
"license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/open-pencil/open-pencil.git",
+ "directory": "packages/kiwi"
+ },
+ "files": [
+ "dist",
+ "README.md",
+ "NOTICE"
+ ],
"type": "module",
+ "sideEffects": false,
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
@@ -47,13 +60,10 @@
"default": "./dist/fig/parse.js"
}
},
- "main": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "sideEffects": false,
- "files": [
- "dist",
- "README.md"
- ],
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
+ },
"scripts": {
"build": "bunx tsdown --config tsdown.config.ts",
"check": "bun run typecheck && bun run test && bun run build && bun run smoke:dist",
@@ -62,15 +72,6 @@
"test": "bun test tests",
"typecheck": "bunx tsc --noEmit -p tsconfig.test.json"
},
- "repository": {
- "type": "git",
- "url": "git+https://github.com/open-pencil/open-pencil.git",
- "directory": "packages/kiwi"
- },
- "publishConfig": {
- "access": "public",
- "provenance": true
- },
"dependencies": {
"fflate": "^0.8.3",
"fzstd": "^0.1.1"
diff --git a/packages/kiwi/src/schema-runtime/index.ts b/packages/kiwi/src/schema-runtime/index.ts
index 9b8cbc5d4..baa71d9aa 100644
--- a/packages/kiwi/src/schema-runtime/index.ts
+++ b/packages/kiwi/src/schema-runtime/index.ts
@@ -1,6 +1,6 @@
export type { Schema, Definition, Field } from './schema'
export { ByteBuffer } from './bb'
-export { compileSchema } from './js'
+export { compileSchemaRuntime as compileSchema } from './interpreter'
export { decodeBinarySchema, encodeBinarySchema } from './binary'
export { parseSchema } from './parser'
export {
diff --git a/packages/kiwi/src/schema-runtime/interpreter.ts b/packages/kiwi/src/schema-runtime/interpreter.ts
new file mode 100644
index 000000000..c780ea25a
--- /dev/null
+++ b/packages/kiwi/src/schema-runtime/interpreter.ts
@@ -0,0 +1,317 @@
+import { ByteBuffer } from './bb'
+import { nativeTypes } from './parser'
+import type { Definition, Field, Schema } from './schema'
+import { error, quote } from './util'
+
+type RuntimeEnum = { [name: string]: string | number }
+type RuntimeValue =
+ | boolean
+ | number
+ | string
+ | bigint
+ | Uint8Array
+ | RuntimeMessage
+ | RuntimeValue[]
+export type RuntimeMessage = { [name: string]: RuntimeValue }
+type DecodeFunction = (bb: ByteBuffer | Uint8Array) => RuntimeMessage
+type EncodeFunction = (message: RuntimeMessage, bb?: ByteBuffer) => Uint8Array | undefined
+type RuntimeEntry =
+ | typeof ByteBuffer
+ | RuntimeEnum
+ | RuntimeValue
+ | DecodeFunction
+ | EncodeFunction
+ | undefined
+export type RuntimeCodec = {
+ ByteBuffer: typeof ByteBuffer
+ encodeMessage?: EncodeFunction
+ decodeMessage?: DecodeFunction
+ encodePaint?: EncodeFunction
+ encodeNodeChange?: EncodeFunction
+ [name: string]: RuntimeEntry
+}
+type Definitions = { [name: string]: Definition }
+
+function asDecodeFunction(value: unknown): DecodeFunction {
+ return value as DecodeFunction
+}
+function asEncodeFunction(value: unknown): EncodeFunction {
+ return value as EncodeFunction
+}
+function asRuntimeEnum(value: unknown): RuntimeEnum {
+ return value as RuntimeEnum
+}
+
+function hasDefinition(definitions: Definitions, name: string): boolean {
+ return Object.hasOwn(definitions, name)
+}
+
+function validateFieldTypes(definitions: Definitions): void {
+ let definitionList = Object.values(definitions)
+ for (let i = 0; i < definitionList.length; i++) {
+ let definition = definitionList[i]
+ if (definition.kind === 'ENUM') continue
+ for (let j = 0; j < definition.fields.length; j++) {
+ let field = definition.fields[j]
+ let type = field.type
+ if (type === null) {
+ error('Invalid type null for field ' + quote(field.name), field.line, field.column)
+ }
+ if (!nativeTypes.includes(type) && !hasDefinition(definitions, type)) {
+ error(
+ 'Invalid type ' + quote(type) + ' for field ' + quote(field.name),
+ field.line,
+ field.column
+ )
+ }
+ }
+ }
+}
+
+// Interprets a schema field-by-field instead of generating and `eval`-ing a
+// per-schema decoder/encoder (as `compileSchemaJS` + `new Function` do). A
+// `new Function(...)`-built codec is indistinguishable from `eval` to a CSP:
+// embedders that run under `script-src` without `unsafe-eval` (e.g. a
+// sandboxed plugin host) cannot call `compileSchema` at all otherwise. This
+// walk produces byte-identical output to the generated code — same field
+// order, same tag/no-tag rules for MESSAGE vs STRUCT, same deprecated-field
+// skip behavior — so it is a drop-in replacement, not a new format.
+function readField(
+ self: RuntimeCodec,
+ definitions: Definitions,
+ type: string,
+ bb: ByteBuffer
+): RuntimeValue {
+ switch (type) {
+ case 'bool':
+ return !!bb.readByte()
+ case 'byte':
+ return bb.readByte()
+ case 'int':
+ return bb.readVarInt()
+ case 'uint':
+ return bb.readVarUint()
+ case 'float':
+ return bb.readVarFloat()
+ case 'string':
+ return bb.readString()
+ case 'int64':
+ return bb.readVarInt64()
+ case 'uint64':
+ return bb.readVarUint64()
+ default: {
+ let definition = definitions[type]
+ if (!definition) error('Invalid type ' + quote(type), 0, 0)
+ if (definition.kind === 'ENUM') return asRuntimeEnum(self[definition.name])[bb.readVarUint()]
+ return asDecodeFunction(self['decode' + definition.name])(bb)
+ }
+ }
+}
+
+function writeField(
+ self: RuntimeCodec,
+ definitions: Definitions,
+ type: string,
+ value: RuntimeValue,
+ bb: ByteBuffer
+): void {
+ switch (type) {
+ case 'bool':
+ case 'byte':
+ bb.writeByte(value as number)
+ return
+ case 'int':
+ bb.writeVarInt(value as number)
+ return
+ case 'uint':
+ bb.writeVarUint(value as number)
+ return
+ case 'float':
+ bb.writeVarFloat(value as number)
+ return
+ case 'string':
+ bb.writeString(value as string)
+ return
+ case 'int64':
+ bb.writeVarInt64(value as bigint | string)
+ return
+ case 'uint64':
+ bb.writeVarUint64(value as bigint | string)
+ return
+ default: {
+ let definition = definitions[type]
+ if (!definition) error('Invalid type ' + quote(type), 0, 0)
+ if (definition.kind === 'ENUM') {
+ let encoded = asRuntimeEnum(self[definition.name])[value as string]
+ if (encoded === undefined) {
+ throw new Error(
+ 'Invalid value ' + JSON.stringify(value) + ' for enum ' + quote(definition.name)
+ )
+ }
+ bb.writeVarUint(encoded as number)
+ } else {
+ asEncodeFunction(self['encode' + definition.name])(value as RuntimeMessage, bb)
+ }
+ }
+ }
+}
+
+function readInto(
+ self: RuntimeCodec,
+ definitions: Definitions,
+ field: Field,
+ bb: ByteBuffer,
+ result: RuntimeMessage
+): void {
+ let type = field.type
+ if (type === null)
+ error('Invalid type null for field ' + quote(field.name), field.line, field.column)
+
+ if (field.isArray) {
+ if (field.isDeprecated) {
+ if (type === 'byte') bb.readByteArray()
+ else {
+ let length = bb.readVarUint()
+ while (length-- > 0) readField(self, definitions, type, bb)
+ }
+ return
+ }
+ if (type === 'byte') {
+ result[field.name] = bb.readByteArray()
+ return
+ }
+ let length = bb.readVarUint()
+ let values: RuntimeValue[] = Array.from({ length })
+ result[field.name] = values
+ for (let i = 0; i < length; i++) values[i] = readField(self, definitions, type, bb)
+ return
+ }
+
+ if (field.isDeprecated) {
+ readField(self, definitions, type, bb)
+ return
+ }
+
+ result[field.name] = readField(self, definitions, type, bb)
+}
+
+function writeFrom(
+ self: RuntimeCodec,
+ definitions: Definitions,
+ field: Field,
+ value: RuntimeValue,
+ bb: ByteBuffer
+): void {
+ let type = field.type
+ if (type === null)
+ error('Invalid type null for field ' + quote(field.name), field.line, field.column)
+
+ if (field.isArray) {
+ if (type === 'byte') {
+ bb.writeByteArray(value as Uint8Array)
+ return
+ }
+ let values = value as RuntimeValue[]
+ bb.writeVarUint(values.length)
+ for (let i = 0; i < values.length; i++) writeField(self, definitions, type, values[i], bb)
+ return
+ }
+
+ writeField(self, definitions, type, value, bb)
+}
+
+function interpretDecode(self: RuntimeCodec, definitions: Definitions, definition: Definition) {
+ let fieldsById = new Map<number, Field>()
+ for (let i = 0; i < definition.fields.length; i++)
+ fieldsById.set(definition.fields[i].value, definition.fields[i])
+ return function (bb: ByteBuffer | Uint8Array): RuntimeMessage {
+ let buffer = bb instanceof self.ByteBuffer ? bb : new self.ByteBuffer(bb)
+ let result: RuntimeMessage = {}
+
+ if (definition.kind === 'MESSAGE') {
+ while (true) {
+ let id = buffer.readVarUint()
+ if (id === 0) return result
+ let field = fieldsById.get(id)
+ if (!field) throw new Error('Attempted to parse invalid message')
+ readInto(self, definitions, field, buffer, result)
+ }
+ }
+
+ for (let i = 0; i < definition.fields.length; i++) {
+ readInto(self, definitions, definition.fields[i], buffer, result)
+ }
+ return result
+ }
+}
+
+function interpretEncode(self: RuntimeCodec, definitions: Definitions, definition: Definition) {
+ return function (message: RuntimeMessage, bb?: ByteBuffer): Uint8Array | undefined {
+ let isTopLevel = !bb
+ let buffer = bb || new self.ByteBuffer()
+
+ for (let i = 0; i < definition.fields.length; i++) {
+ let field = definition.fields[i]
+ if (field.isDeprecated) continue
+ let value = message[field.name]
+ if (value != null) {
+ if (definition.kind === 'MESSAGE') buffer.writeVarUint(field.value)
+ writeFrom(self, definitions, field, value, buffer)
+ } else if (definition.kind === 'STRUCT') {
+ throw new Error('Missing required field ' + quote(field.name))
+ }
+ }
+
+ if (definition.kind === 'MESSAGE') buffer.writeVarUint(0)
+ if (isTopLevel) return buffer.toUint8Array()
+ return undefined
+ }
+}
+
+export function compileSchemaRuntime(schema: Schema): RuntimeCodec {
+ let definitions: Definitions = Object.create(null) as Definitions
+ for (let i = 0; i < schema.definitions.length; i++) {
+ definitions[schema.definitions[i].name] = schema.definitions[i]
+ }
+
+ validateFieldTypes(definitions)
+
+ let result: RuntimeCodec = {
+ ByteBuffer: ByteBuffer
+ }
+
+ for (let i = 0; i < schema.definitions.length; i++) {
+ let definition = schema.definitions[i]
+
+ switch (definition.kind) {
+ case 'ENUM': {
+ let value: RuntimeEnum = {}
+ for (let j = 0; j < definition.fields.length; j++) {
+ let field = definition.fields[j]
+ value[field.name] = field.value
+ value[field.value] = field.name
+ }
+ result[definition.name] = value
+ break
+ }
+
+ case 'STRUCT':
+ case 'MESSAGE': {
+ result['decode' + definition.name] = interpretDecode(result, definitions, definition)
+ result['encode' + definition.name] = interpretEncode(result, definitions, definition)
+ break
+ }
+
+ default: {
+ error(
+ 'Invalid definition kind ' + quote(definition.kind),
+ definition.line,
+ definition.column
+ )
+ break
+ }
+ }
+ }
+
+ return result
+}
diff --git a/packages/kiwi/src/schema-runtime/js.ts b/packages/kiwi/src/schema-runtime/js.ts
deleted file mode 100644
index 63649e7e8..000000000
--- a/packages/kiwi/src/schema-runtime/js.ts
+++ /dev/null
@@ -1,339 +0,0 @@
-import { ByteBuffer } from './bb'
-import { Schema, Definition } from './schema'
-import { error, quote } from './util'
-
-function compileDecode(
- definition: Definition,
- definitions: { [name: string]: Definition }
-): string {
- let lines: string[] = []
- let indent = ' '
-
- lines.push('function (bb) {')
- lines.push(' var result = {};')
- lines.push(' if (!(bb instanceof this.ByteBuffer)) {')
- lines.push(' bb = new this.ByteBuffer(bb);')
- lines.push(' }')
- lines.push('')
-
- if (definition.kind === 'MESSAGE') {
- lines.push(' while (true) {')
- lines.push(' switch (bb.readVarUint()) {')
- lines.push(' case 0:')
- lines.push(' return result;')
- lines.push('')
- indent = ' '
- }
-
- for (let i = 0; i < definition.fields.length; i++) {
- let field = definition.fields[i]
- let code: string
-
- switch (field.type) {
- case 'bool': {
- code = '!!bb.readByte()'
- break
- }
-
- case 'byte': {
- code = 'bb.readByte()' // only used if not array
- break
- }
-
- case 'int': {
- code = 'bb.readVarInt()'
- break
- }
-
- case 'uint': {
- code = 'bb.readVarUint()'
- break
- }
-
- case 'float': {
- code = 'bb.readVarFloat()'
- break
- }
-
- case 'string': {
- code = 'bb.readString()'
- break
- }
-
- case 'int64': {
- code = 'bb.readVarInt64()'
- break
- }
-
- case 'uint64': {
- code = 'bb.readVarUint64()'
- break
- }
-
- default: {
- let type = definitions[field.type!]
- if (!type) {
- error(
- 'Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name),
- field.line,
- field.column
- )
- } else if (type.kind === 'ENUM') {
- code = 'this[' + quote(type.name) + '][bb.readVarUint()]'
- } else {
- code = 'this[' + quote('decode' + type.name) + '](bb)'
- }
- }
- }
-
- if (definition.kind === 'MESSAGE') {
- lines.push(' case ' + field.value + ':')
- }
-
- if (field.isArray) {
- if (field.isDeprecated) {
- if (field.type === 'byte') {
- lines.push(indent + 'bb.readByteArray();')
- } else {
- lines.push(indent + 'var length = bb.readVarUint();')
- lines.push(indent + 'while (length-- > 0) ' + code + ';')
- }
- } else {
- if (field.type === 'byte') {
- lines.push(indent + 'result[' + quote(field.name) + '] = bb.readByteArray();')
- } else {
- lines.push(indent + 'var length = bb.readVarUint();')
- lines.push(indent + 'var values = result[' + quote(field.name) + '] = Array(length);')
- lines.push(indent + 'for (var i = 0; i < length; i++) values[i] = ' + code + ';')
- }
- }
- } else {
- if (field.isDeprecated) {
- lines.push(indent + code + ';')
- } else {
- lines.push(indent + 'result[' + quote(field.name) + '] = ' + code + ';')
- }
- }
-
- if (definition.kind === 'MESSAGE') {
- lines.push(' break;')
- lines.push('')
- }
- }
-
- if (definition.kind === 'MESSAGE') {
- lines.push(' default:')
- lines.push(' throw new Error("Attempted to parse invalid message");')
- lines.push(' }')
- lines.push(' }')
- } else {
- lines.push(' return result;')
- }
-
- lines.push('}')
-
- return lines.join('\n')
-}
-
-function compileEncode(
- definition: Definition,
- definitions: { [name: string]: Definition }
-): string {
- let lines: string[] = []
-
- lines.push('function (message, bb) {')
- lines.push(' var isTopLevel = !bb;')
- lines.push(' if (isTopLevel) bb = new this.ByteBuffer();')
-
- for (let j = 0; j < definition.fields.length; j++) {
- let field = definition.fields[j]
- let code: string
-
- if (field.isDeprecated) {
- continue
- }
-
- switch (field.type) {
- case 'bool': {
- code = 'bb.writeByte(value);'
- break
- }
-
- case 'byte': {
- code = 'bb.writeByte(value);' // only used if not array
- break
- }
-
- case 'int': {
- code = 'bb.writeVarInt(value);'
- break
- }
-
- case 'uint': {
- code = 'bb.writeVarUint(value);'
- break
- }
-
- case 'float': {
- code = 'bb.writeVarFloat(value);'
- break
- }
-
- case 'string': {
- code = 'bb.writeString(value);'
- break
- }
-
- case 'int64': {
- code = 'bb.writeVarInt64(value);'
- break
- }
-
- case 'uint64': {
- code = 'bb.writeVarUint64(value);'
- break
- }
-
- default: {
- let type = definitions[field.type!]
- if (!type) {
- throw new Error('Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name))
- } else if (type.kind === 'ENUM') {
- code =
- 'var encoded = this[' +
- quote(type.name) +
- '][value]; ' +
- 'if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' +
- quote(' for enum ' + quote(type.name)) +
- '); ' +
- 'bb.writeVarUint(encoded);'
- } else {
- code = 'this[' + quote('encode' + type.name) + '](value, bb);'
- }
- }
- }
-
- lines.push('')
- lines.push(' var value = message[' + quote(field.name) + '];')
- lines.push(' if (value != null) {') // Comparing with null using "!=" also checks for undefined
-
- if (definition.kind === 'MESSAGE') {
- lines.push(' bb.writeVarUint(' + field.value + ');')
- }
-
- if (field.isArray) {
- if (field.type === 'byte') {
- lines.push(' bb.writeByteArray(value);')
- } else {
- lines.push(' var values = value, n = values.length;')
- lines.push(' bb.writeVarUint(n);')
- lines.push(' for (var i = 0; i < n; i++) {')
- lines.push(' value = values[i];')
- lines.push(' ' + code)
- lines.push(' }')
- }
- } else {
- lines.push(' ' + code)
- }
-
- if (definition.kind === 'STRUCT') {
- lines.push(' } else {')
- lines.push(
- ' throw new Error(' + quote('Missing required field ' + quote(field.name)) + ');'
- )
- }
-
- lines.push(' }')
- }
-
- // A field id of zero is reserved to indicate the end of the message
- if (definition.kind === 'MESSAGE') {
- lines.push(' bb.writeVarUint(0);')
- }
-
- lines.push('')
- lines.push(' if (isTopLevel) return bb.toUint8Array();')
- lines.push('}')
-
- return lines.join('\n')
-}
-
-export function compileSchemaJS(schema: Schema): string {
- let definitions: { [name: string]: Definition } = {}
- let name = schema.package
- let js: string[] = []
-
- if (name !== null) {
- js.push('var ' + name + ' = exports || ' + name + ' || {}, exports;')
- } else {
- js.push('var exports = exports || {};')
- name = 'exports'
- }
-
- js.push(name + '.ByteBuffer = ' + name + '.ByteBuffer || require("kiwi-schema").ByteBuffer;')
-
- for (let i = 0; i < schema.definitions.length; i++) {
- let definition = schema.definitions[i]
- definitions[definition.name] = definition
- }
-
- for (let i = 0; i < schema.definitions.length; i++) {
- let definition = schema.definitions[i]
-
- switch (definition.kind) {
- case 'ENUM': {
- let value: any = {}
- for (let j = 0; j < definition.fields.length; j++) {
- let field = definition.fields[j]
- value[field.name] = field.value
- value[field.value] = field.name
- }
- js.push(name + '[' + quote(definition.name) + '] = ' + JSON.stringify(value, null, 2) + ';')
- break
- }
-
- case 'STRUCT':
- case 'MESSAGE': {
- js.push('')
- js.push(
- name +
- '[' +
- quote('decode' + definition.name) +
- '] = ' +
- compileDecode(definition, definitions) +
- ';'
- )
- js.push('')
- js.push(
- name +
- '[' +
- quote('encode' + definition.name) +
- '] = ' +
- compileEncode(definition, definitions) +
- ';'
- )
- break
- }
-
- default: {
- error(
- 'Invalid definition kind ' + quote(definition.kind),
- definition.line,
- definition.column
- )
- break
- }
- }
- }
-
- js.push('')
- return js.join('\n')
-}
-
-export function compileSchema(schema: Schema): any {
- let result = {
- ByteBuffer: ByteBuffer
- }
- new Function('exports', compileSchemaJS(schema))(result)
- return result
-}
diff --git a/packages/kiwi/tests/schema-runtime.test.ts b/packages/kiwi/tests/schema-runtime.test.ts
index 401a595f9..416598869 100644
--- a/packages/kiwi/tests/schema-runtime.test.ts
+++ b/packages/kiwi/tests/schema-runtime.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import {
+ ByteBuffer,
compileSchema,
expectEnumValue,
expectFieldNumber,
@@ -8,6 +9,17 @@ import {
validateSchema
} from '../src/schema-runtime'
+interface RuntimeMessage {
+ [name: string]:
+ | boolean
+ | number
+ | string
+ | bigint
+ | Uint8Array
+ | RuntimeMessage
+ | RuntimeMessage[]
+}
+
const schemaText = `
package Example;
@@ -52,4 +64,116 @@ describe('Kiwi schema runtime', () => {
tags: ['kiwi']
})
})
+
+ test('compiles and round-trips without calling the Function constructor', () => {
+ const OriginalFunction = globalThis.Function
+ globalThis.Function = new Proxy(OriginalFunction, {
+ construct() {
+ throw new EvalError(
+ "Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script"
+ )
+ }
+ })
+
+ try {
+ const codec = compileSchema(parseSchema(schemaText)) as {
+ encodeItem(value: unknown): Uint8Array
+ decodeItem(value: Uint8Array): unknown
+ }
+ const encoded = codec.encodeItem({ id: 7, name: 'CSP-safe', kind: 'BADGE', tags: [] })
+ expect(codec.decodeItem(encoded)).toEqual({
+ id: 7,
+ name: 'CSP-safe',
+ kind: 'BADGE',
+ tags: []
+ })
+ } finally {
+ globalThis.Function = OriginalFunction
+ }
+ })
+
+ test('uses the codec ByteBuffer override', () => {
+ class CustomByteBuffer extends ByteBuffer {}
+
+ const codec = compileSchema(parseSchema(schemaText))
+ codec.ByteBuffer = CustomByteBuffer
+
+ const encoded = (codec.encodeItem as (value: RuntimeMessage) => Uint8Array)({
+ id: 1,
+ name: 'custom',
+ kind: 'CARD',
+ tags: []
+ })
+ const decoded = (codec.decodeItem as (value: Uint8Array) => RuntimeMessage)(encoded)
+
+ expect(decoded.name).toBe('custom')
+ })
+
+ test('reports unknown field types at their source location', () => {
+ const malformedSchema = {
+ package: null,
+ definitions: [
+ {
+ name: 'Item',
+ line: 4,
+ column: 1,
+ kind: 'MESSAGE' as const,
+ fields: [
+ {
+ name: 'value',
+ line: 5,
+ column: 3,
+ type: 'MissingType',
+ isArray: false,
+ isDeprecated: false,
+ value: 1
+ }
+ ]
+ }
+ ]
+ }
+
+ expect(() => compileSchema(malformedSchema)).toThrow(
+ 'Invalid type "MissingType" for field "value"'
+ )
+ try {
+ compileSchema(malformedSchema)
+ } catch (error) {
+ expect(error).toMatchObject({ line: 5, column: 3 })
+ }
+ })
+
+ test('rejects inherited names as field types', () => {
+ const malformedSchema = {
+ package: null,
+ definitions: [
+ {
+ name: 'Item',
+ line: 4,
+ column: 1,
+ kind: 'MESSAGE' as const,
+ fields: [
+ {
+ name: 'value',
+ line: 5,
+ column: 3,
+ type: 'constructor',
+ isArray: false,
+ isDeprecated: false,
+ value: 1
+ }
+ ]
+ }
+ ]
+ }
+
+ expect(() => compileSchema(malformedSchema)).toThrow(
+ 'Invalid type "constructor" for field "value"'
+ )
+ try {
+ compileSchema(malformedSchema)
+ } catch (error) {
+ expect(error).toMatchObject({ line: 5, column: 3 })
+ }
+ })
})