@jsonjoy.com/json-type
Version:
High-performance JSON Pointer implementation
87 lines (86 loc) • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinType = void 0;
const tslib_1 = require("tslib");
const printTree_1 = require("tree-dump/lib/printTree");
const schema = tslib_1.__importStar(require("../../schema"));
const json_binary_1 = require("@jsonjoy.com/json-pack/lib/json-binary");
const AbsType_1 = require("./AbsType");
const constants_1 = require("../../constants");
class BinType extends AbsType_1.AbsType {
constructor(type, options) {
super();
this.type = type;
this.schema = schema.s.Binary(schema.s.any, options);
}
format(format) {
this.schema.format = format;
return this;
}
min(min) {
this.schema.min = min;
return this;
}
max(max) {
this.schema.max = max;
return this;
}
getSchema() {
return {
...this.schema,
type: this.type.getSchema(),
};
}
getOptions() {
const { kind, type, ...options } = this.schema;
return options;
}
codegenValidator(ctx, path, r) {
const hasBuffer = typeof Buffer === 'function';
const err = ctx.err(constants_1.ValidationError.BIN, path);
ctx.js(
// prettier-ignore
`if(!(${r} instanceof Uint8Array)${hasBuffer ? ` && !Buffer.isBuffer(${r})` : ''}) return ${err};`);
const { min, max } = this.schema;
if (typeof min === 'number' && min === max) {
const err = ctx.err(constants_1.ValidationError.BIN_LEN, path);
ctx.js(`if(${r}.length !== ${min}) return ${err};`);
}
else {
if (typeof min === 'number') {
const err = ctx.err(constants_1.ValidationError.BIN_LEN, path);
ctx.js(`if(${r}.length < ${min}) return ${err};`);
}
if (typeof max === 'number') {
const err = ctx.err(constants_1.ValidationError.BIN_LEN, path);
ctx.js(`if(${r}.length > ${max}) return ${err};`);
}
}
ctx.emitCustomValidators(this, path, r);
}
codegenJsonTextEncoder(ctx, value) {
ctx.linkBase64();
ctx.writeText('"data:application/octet-stream;base64,');
ctx.js(/* js */ `s += toBase64(${value.use()});`);
ctx.writeText('"');
}
codegenBinaryEncoder(ctx, value) {
ctx.js(/* js */ `encoder.writeBin(${value.use()});`);
}
codegenCborEncoder(ctx, value) {
this.codegenBinaryEncoder(ctx, value);
}
codegenMessagePackEncoder(ctx, value) {
this.codegenBinaryEncoder(ctx, value);
}
codegenJsonEncoder(ctx, value) {
this.codegenBinaryEncoder(ctx, value);
}
toJson(value, system = this.system) {
return ('"' + (0, json_binary_1.stringifyBinary)(value) + '"');
}
toString(tab = '') {
return super.toString(tab) + (0, printTree_1.printTree)(tab, [(tab) => this.type.toString(tab)]);
}
}
exports.BinType = BinType;