@gulujs/toml
Version:
TOML parser and serializer
68 lines (67 loc) • 2.72 kB
JavaScript
import { SchemaType } from '../schema.js';
import { serializeAny, BREAK } from './any.js';
import { assertIsArray, serializeArray } from './array.js';
import { assertIsBoolean, serializeBoolean } from './boolean.js';
import { assertIsDateTime, serializeDateTime } from './datetime.js';
import { assertIsFloat, serializeFloat } from './float.js';
import { assertIsInlineTable, serializeInlineTable } from './inline-table.js';
import { assertIsInteger, serializeInteger } from './integer.js';
import { assertIsString, serializeString } from './string.js';
import { stringifyKey } from '../utils.js';
export const valueAssertors = {
[SchemaType.String]: assertIsString,
[SchemaType.Integer]: assertIsInteger,
[SchemaType.Float]: assertIsFloat,
[SchemaType.Boolean]: assertIsBoolean,
[SchemaType.DateTime]: assertIsDateTime,
[SchemaType.Array]: assertIsArray,
[SchemaType.InlineTable]: assertIsInlineTable
};
export const valueSerializers = {
[SchemaType.String]: serializeString,
[SchemaType.Integer]: serializeInteger,
[SchemaType.Float]: serializeFloat,
[SchemaType.Boolean]: serializeBoolean,
[SchemaType.DateTime]: serializeDateTime,
[SchemaType.Array]: serializeArray,
[SchemaType.InlineTable]: serializeInlineTable
};
export function serializeSimpleTypeValue(value, schema, options, path) {
let serializedValue;
const serialize = schema.serialize;
if (typeof serialize === 'function') {
serializedValue = serialize(value);
}
else {
if (options.simpleMode !== true) {
valueAssertors[schema.type](value, options, path);
}
serializedValue = valueSerializers[schema.type](value, schema, options, path);
}
return serializedValue;
}
export function tryStringifyKeyValue(value, schema, options, path, lines) {
let serializedValue;
switch (schema.type) {
case SchemaType.Any:
serializedValue = serializeAny(value, schema, options, path);
if (serializedValue === BREAK) {
return false;
}
if (serializedValue !== null) {
lines.push(`${stringifyKey(schema.key, options.objectPath.keyPath)} = ${serializedValue}`);
}
return true;
case SchemaType.String:
case SchemaType.Boolean:
case SchemaType.Integer:
case SchemaType.Float:
case SchemaType.DateTime:
case SchemaType.Array:
case SchemaType.InlineTable:
lines.push(`${stringifyKey(schema.key, options.objectPath.keyPath)} = ${serializeSimpleTypeValue(value, schema, options, path)}`);
return true;
default:
return false;
}
}