feat(new tools): ObjGen JSON and HTML

Fix #1731
This commit is contained in:
ShareVB committed 2026-02-15 14:31:33 +01:00
1 parent 64d06e5a1f
commit 40f1833aae
8 files changed
+1383

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
import { Brackets } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'ObjGen to HTML',
path: '/objgen-html',
description: 'Generate xomplex HTML from TOML like syntax',
keywords: ['objgen', 'html', 'toml'],
component: () => import('./objgen-html.vue'),
icon: Brackets,
createdAt: new Date('2026-02-14'),
category: 'XML',
});
@@ -0,0 +1,288 @@
import { describe, expect, it } from 'vitest';
import { xHtml } from './objgen-html.service';
describe('objgen-html service', () => {
describe('xHtml', () => {
it('generate correct HTML', () => {
expect(xHtml(`// This is a comment!
// HTML generator quick tips:
// - Each line with content will generate a HTML element
// - Generate elements by just using their tag names
// - Elements are nested using tabs and/or spaces
// - Element content (inner text) is specified using an equal sign '='
// - Specify one or more class attributes after the tag name
// - Class names can optionally be indicated using a dot prefix, '.some-class'
// - Element ids are assigned using a hash prefix, '#someElementId'
// - Assign attributes using a name=val enclosed in parens, '(attr="value")'
// - Comments in the model text, like this are ignored
// Demo using Bootstrap 4 styled elements
container-fluid
h2=HTML Generator Demo
p=The HTML Live Generator uses a shorthand syntax for quickly prototyping and generating HTML snippets. ObjGen includes support for styling elements using the Bootstrap v4.x toolkit and is used in this demo example.
a(href="https://getbootstrap.com" target="_blank")=Click here for Bootstrap documentation and reference
hr
h3 pb-3=Typography
row
col bg-light border rounded p-2
h1 = h1. Bootstrap Heading
h2 = h2. Bootstrap Heading
h3 = h3. Bootstrap Heading
h3 pt-4=Grid Layout
row mb-3
col bg-light border
p-3 = 1 of 2
col bg-light border
p-3 = 2 of 2
row
col bg-light border
p-3 = 1 of 3
col bg-light border
p-3 = 2 of 3
col bg-light border
p-3 = 3 of 3
h3 pt-4=Flex Layout
d-flex bg-light #flexDemoContainer
mr-auto p-2 border=1 of 3
p-2 border=2 of 3
p-2 border=3 of 3
h3 pt-4=Forms
small=(Login Form)
row
col
form bg-light border rounded p-3
form-group
label=Email
input form-control (type="email", placeholder="someone@example.com")
form-group
label=Password
input form-control (type="password", placeholder="********")
form-group form-check
input form-check-input (type="checkbox")
label form-check-label=Remember me
button btn btn-primary(type="button")=Submit
h3 pt-4=Cards
small=(with decks)
card-deck
card
img card-img-top(src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png")
card-body
h5 card-title=Card 1 Title
p=Card 1 Content
card-footer
small text-muted=Last updated 5 mins ago
card
img card-img-top(src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png")
card-body
h5 card-title=Card 2 Title
p=Card 2 Content
card-footer
small text-muted=Last updated 5 mins ago
card
img card-img-top(src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png")
card-body
h5 card-title=Card 3 Title
p=Card 3 Content
card-footer
small text-muted=Last updated 5 mins ago
h2 pt-4=List Group
small=(with badges)
ul list-group
li list-group-item d-flex justify-content-between align-items-center active=Item 1
span badge badge-danger badge-pill=100
li list-group-item d-flex justify-content-between align-items-center=Item 2
span badge badge-primary badge-pill=75
li list-group-item=Item 3
li list-group-item=Item 4
h2 pt-4=Tables
table .table table-bordered
thead thead-light
tr
th=ID
th=First
th=Last
th=Email
tbody
tr
td=1
td=John
td=Doe
td=john.doe@example.com
tr
td=2
td=Jane
td=Doe
td=jane.doe@example.com
tr
td=3
td=Dave
td=Kingman
td=dave@davekingman.com
h2 mt-4=Alerts
alert alert-primary mt-3 mb-3=Primary Alert
alert alert-secondary mt-3 mb-3=Secondary Alert
alert alert-success mt-3 mb-3=Success! Thank you for viewing this demo!
`)).toBe(` <div class="container-fluid">
<h2>HTML Generator Demo</h2>
<p>The HTML Live Generator uses a shorthand syntax for quickly prototyping and generating HTML snippets. ObjGen includes support for styling elements using the Bootstrap v4.x toolkit and is used in this demo example.</p>
<a href="https://getbootstrap.com" target="_blank">Click here for Bootstrap documentation and reference</a>
<hr></hr>
<h3 class="pb-3">Typography</h3>
<div class="row">
<div class="col bg-light border rounded p-2">
<h1>h1. Bootstrap Heading</h1>
<h2>h2. Bootstrap Heading</h2>
<h3>h3. Bootstrap Heading</h3>
</div>
</div>
<h3 class="pt-4">Grid Layout</h3>
<div class="row mb-3">
<div class="col bg-light border">
<div class="p-3">1 of 2</div>
</div>
<div class="col bg-light border">
<div class="p-3">2 of 2</div>
</div>
</div>
<div class="row">
<div class="col bg-light border">
<div class="p-3">1 of 3</div>
</div>
<div class="col bg-light border">
<div class="p-3">2 of 3</div>
</div>
<div class="col bg-light border">
<div class="p-3">3 of 3</div>
</div>
</div>
<h3 class="pt-4">Flex Layout</h3>
<div id="flexDemoContainer" class="d-flex bg-light">
<div class="mr-auto p-2 border">1 of 3</div>
<div class="p-2 border">2 of 3</div>
<div class="p-2 border">3 of 3</div>
</div>
<h3 class="pt-4">
Forms
<small>(Login Form)</small>
</h3>
<div class="row">
<div class="col">
<form class="bg-light border rounded p-3">
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email", placeholder="someone@example.com"></input>
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control" type="password", placeholder="********"></input>
</div>
<div class="form-group form-check">
<input class="form-check-input" type="checkbox"></input>
<label class="form-check-label">Remember me</label>
</div>
<button class="btn btn-primary" type="button">Submit</button>
</form>
</div>
</div>
<h3 class="pt-4">
Cards
<small>(with decks)</small>
</h3>
<div class="card-deck">
<div class="card">
<img class="card-img-top" src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png"></img>
<div class="card-body">
<h5 class="card-title">Card 1 Title</h5>
<p>Card 1 Content</p>
</div>
<div class="card-footer">
<small class="text-muted">Last updated 5 mins ago</small>
</div>
</div>
<div class="card">
<img class="card-img-top" src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png"></img>
<div class="card-body">
<h5 class="card-title">Card 2 Title</h5>
<p>Card 2 Content</p>
</div>
<div class="card-footer">
<small class="text-muted">Last updated 5 mins ago</small>
</div>
</div>
<div class="card">
<img class="card-img-top" src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png"></img>
<div class="card-body">
<h5 class="card-title">Card 3 Title</h5>
<p>Card 3 Content</p>
</div>
<div class="card-footer">
<small class="text-muted">Last updated 5 mins ago</small>
</div>
</div>
</div>
<h2 class="pt-4">
List Group
<small>(with badges)</small>
</h2>
<ul class="list-group">
<li class="list-group-item d-flex justify-content-between align-items-center active">
Item 1
<span class="badge badge-danger badge-pill">100</span>
</li>
<li class="list-group-item d-flex justify-content-between align-items-center">
Item 2
<span class="badge badge-primary badge-pill">75</span>
</li>
<li class="list-group-item">Item 3</li>
<li class="list-group-item">Item 4</li>
</ul>
<h2 class="pt-4">Tables</h2>
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>ID</th>
<th>First</th>
<th>Last</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Doe</td>
<td>john.doe@example.com</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>Doe</td>
<td>jane.doe@example.com</td>
</tr>
<tr>
<td>3</td>
<td>Dave</td>
<td>Kingman</td>
<td>dave@davekingman.com</td>
</tr>
</tbody>
</table>
<h2 class="mt-4">Alerts</h2>
<div class="alert alert-primary mt-3 mb-3">Primary Alert</div>
<div class="alert alert-secondary mt-3 mb-3">Secondary Alert</div>
<div class="alert alert-success mt-3 mb-3">Success! Thank you for viewing this demo!</div>
</div>
`);
});
});
});
@@ -0,0 +1,270 @@
import { parseLines } from '@/utils/objgen';
const indentString = ' ';
const htmlElements = {
a: true,
abbr: true,
acronym: true,
address: true,
applet: true,
area: true,
article: true,
aside: true,
audio: true,
b: true,
base: true,
basefont: true,
bdi: true,
bdo: true,
bgsound: true,
big: true,
blink: true,
blockquote: true,
body: false,
br: true,
button: true,
canvas: true,
caption: true,
center: true,
cite: true,
code: true,
colgroup: true,
command: true,
data: true,
datalist: true,
dd: true,
del: true,
details: true,
dfn: true,
dir: true,
div: true,
dl: true,
dt: true,
em: true,
embed: true,
fieldset: true,
figcaption: true,
figure: true,
font: true,
footer: true,
form: true,
frame: true,
frameset: true,
h1: true,
h2: true,
h3: true,
h4: true,
h5: true,
h6: true,
head: true,
header: true,
hgroup: true,
hr: true,
html: false,
i: true,
iframe: true,
img: true,
input: true,
ins: true,
isindex: true,
kbd: true,
keygen: true,
label: true,
legend: true,
li: true,
link: true,
listing: true,
map: true,
mark: true,
marquee: true,
menu: true,
meta: true,
meter: true,
nav: true,
nobr: true,
noframes: true,
noscript: true,
object: true,
ol: true,
optgroup: true,
option: true,
output: true,
p: true,
param: true,
plaintext: true,
pre: true,
progress: true,
q: true,
rp: true,
rt: true,
ruby: true,
s: true,
samp: true,
script: false,
section: true,
select: true,
small: true,
source: true,
spacer: true,
span: true,
strike: true,
strong: true,
style: true,
sub: true,
summary: true,
sup: true,
table: true,
tbody: true,
td: true,
textarea: true,
tfoot: true,
th: true,
thead: true,
time: true,
title: true,
tr: true,
track: true,
tt: true,
u: true,
ul: true,
var: true,
video: true,
wbr: true,
xmp: true,
};
interface Element {
kind: string
id: string
clazz: string[]
content: string
elements: Element[]
attributes: string
}
export function xHtml(modelText: string) {
const reggie = /([-\w]+)|(\.[-\w]+)|(#[-\w]+)|(\(.*?\))|(=.*$)/g;
const elements: Element[] = [];
let parents: Array<Element> = [];
// parse the inbound model text
parseLines(modelText, { numSpaces: 2 }, (line, depth) => {
if (line.match('^s+$/|^/$|^//|^s.*/$|^s.*//') !== null) {
return '';
}
const elem: Element = {
kind: 'div',
id: '',
clazz: [],
content: '',
elements: [],
attributes: '',
};
let parent: Element | null = null;
if (depth === 1) {
parent = null;
parents = [];
parents.push(elem);
}
else {
while (parents.length > depth - 1) {
parent = parents.pop()!;
}
parents.push(parent!);
parents.push(elem);
}
if (parent === null) {
elements.push(elem);
}
else {
parent.elements.push(elem);
}
parents.push(elem);
let matches = 0;
let match = reggie.exec(line);
while (match !== null) {
matches += 1;
if (matches === 1 && isHtmlElement(match[0])) {
elem.kind = match[0];
}
else if (match[2]) {
elem.clazz[elem.clazz.length] = match[0].replace(/\./, '');
}
else if (match[3]) {
elem.id = match[0].replace(/#/, '');
}
else if (match[4]) {
elem.attributes = match[0].replace(/^\(|\)$/g, '');
elem.attributes = elem.attributes.trim().replace(/\s+/g, ' ');
}
else if (match[5]) {
elem.content = match[0].replace(/=/, '').trim();
}
else {
elem.clazz.push(match[0]);
}
match = reggie.exec(line);
}
});
const h = genHtml(elements, 1);
return h;
}
function genHtml(elements: Element[], depth: number) {
if (depth == null) {
depth = 1;
}
const t = indentString.repeat(depth);
let result = '';
for (let i = 0; i < elements.length; i++) {
const e = elements[i];
result += `${t}<${e.kind}`;
if (hasContent(e.id)) {
result += ` id="${e.id}"`;
}
if (hasContent(e.clazz)) {
result += ` class="${e.clazz.join(' ')}"`;
}
if (hasContent(e.attributes)) {
result += ` ${e.attributes}`;
}
result += '>';
const hasChildren = hasContent(e.elements);
if (hasContent(e.content)) {
if (hasChildren) {
result += `\n${t}${indentString}`;
}
result += e.content;
}
if (hasChildren) {
result += `\n${genHtml(e.elements, depth + 1)}${t}`;
}
result += `</${e.kind}>\n`;
}
return result;
}
function hasContent(val: any[] | string) {
return val && val.length > 0;
}
function isHtmlElement(val: string) {
return Object.prototype.hasOwnProperty.call(htmlElements, val);
}
+159
View File
@@ -0,0 +1,159 @@
<script setup lang="ts">
import { xHtml } from './objgen-html.service';
const defaultValue = `// This is a comment!
// HTML generator quick tips:
// - Each line with content will generate a HTML element
// - Generate elements by just using their tag names
// - Elements are nested using tabs and/or spaces
// - Element content (inner text) is specified using an equal sign '='
// - Specify one or more class attributes after the tag name
// - Class names can optionally be indicated using a dot prefix, '.some-class'
// - Element ids are assigned using a hash prefix, '#someElementId'
// - Assign attributes using a name=val enclosed in parens, '(attr="value")'
// - Comments in the model text, like this are ignored
// Demo using Bootstrap 4 styled elements
container-fluid
h2=HTML Generator Demo
p=The HTML Live Generator uses a shorthand syntax for quickly prototyping and generating HTML snippets. ObjGen includes support for styling elements using the Bootstrap v4.x toolkit and is used in this demo example.
a(href="https://getbootstrap.com" target="_blank")=Click here for Bootstrap documentation and reference
hr
h3 pb-3=Typography
row
col bg-light border rounded p-2
h1 = h1. Bootstrap Heading
h2 = h2. Bootstrap Heading
h3 = h3. Bootstrap Heading
h3 pt-4=Grid Layout
row mb-3
col bg-light border
p-3 = 1 of 2
col bg-light border
p-3 = 2 of 2
row
col bg-light border
p-3 = 1 of 3
col bg-light border
p-3 = 2 of 3
col bg-light border
p-3 = 3 of 3
h3 pt-4=Flex Layout
d-flex bg-light #flexDemoContainer
mr-auto p-2 border=1 of 3
p-2 border=2 of 3
p-2 border=3 of 3
h3 pt-4=Forms
small=(Login Form)
row
col
form bg-light border rounded p-3
form-group
label=Email
input form-control (type="email", placeholder="someone@example.com")
form-group
label=Password
input form-control (type="password", placeholder="********")
form-group form-check
input form-check-input (type="checkbox")
label form-check-label=Remember me
button btn btn-primary(type="button")=Submit
h3 pt-4=Cards
small=(with decks)
card-deck
card
img card-img-top(src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png")
card-body
h5 card-title=Card 1 Title
p=Card 1 Content
card-footer
small text-muted=Last updated 5 mins ago
card
img card-img-top(src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png")
card-body
h5 card-title=Card 2 Title
p=Card 2 Content
card-footer
small text-muted=Last updated 5 mins ago
card
img card-img-top(src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png")
card-body
h5 card-title=Card 3 Title
p=Card 3 Content
card-footer
small text-muted=Last updated 5 mins ago
h2 pt-4=List Group
small=(with badges)
ul list-group
li list-group-item d-flex justify-content-between align-items-center active=Item 1
span badge badge-danger badge-pill=100
li list-group-item d-flex justify-content-between align-items-center=Item 2
span badge badge-primary badge-pill=75
li list-group-item=Item 3
li list-group-item=Item 4
h2 pt-4=Tables
table .table table-bordered
thead thead-light
tr
th=ID
th=First
th=Last
th=Email
tbody
tr
td=1
td=John
td=Doe
td=john.doe@example.com
tr
td=2
td=Jane
td=Doe
td=jane.doe@example.com
tr
td=3
td=Dave
td=Kingman
td=dave@davekingman.com
h2 mt-4=Alerts
alert alert-primary mt-3 mb-3=Primary Alert
alert alert-secondary mt-3 mb-3=Secondary Alert
alert alert-success mt-3 mb-3=Success! Thank you for viewing this demo!
`;
function transformer(value: string) {
try {
return xHtml(value);
}
catch (e: any) {
return `/* ERROR: ${e.toString()} */`;
}
}
</script>
<template>
<details mb-1>
<summary>Documentation</summary>
<textarea-copyable :value="defaultValue" language="toml" />
</details>
<format-transformer
input-label="ObjGen HTML definition"
:input-default="defaultValue"
input-placeholder="Put your ObjGen HTML definition here..."
output-label="Generated HTML"
output-language="html"
:transformer="transformer"
download-file-name="output.html"
/>
</template>
+13
View File
@@ -0,0 +1,13 @@
import { Braces } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'ObjGen to JSON',
path: '/objgen-json',
description: 'Generate xomplex JSON from TOML like syntax',
keywords: ['objgen', 'json', 'toml'],
component: () => import('./objgen-json.vue'),
icon: Braces,
createdAt: new Date('2026-02-14'),
category: 'JSON',
});
+67
View File
@@ -0,0 +1,67 @@
<script setup lang="ts">
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { ObjGen2Json } from '@/utils/objgen';
const defaultValue = `// Model & generate Live JSON data values
// interactively using a simple syntax.
// String is the default value type
product = Live JSON generator
// Number, Date & Boolean are also supported
// Specify types after property names
version n = 3.1
releaseDate d = 2014-06-25
demo b = true
// Tabs or spaces define complex values
person
id number = 12345
name = John Doe
phones
home = 800-123-4567
mobile = 877-123-1234
// Use [] to define simple type arrays
email[] s = jd@example.com, jd@example.org
dateOfBirth d = 1980-01-02
registered b = true
// Use [] or [n] to define object arrays
emergencyContacts[]
name s = Jane Doe
phone s = 888-555-1212
relationship = spouse
emergencyContacts[]
name s = Justin Doe
phone s = 877-123-1212
relationship = parent
`;
const indentSize = useQueryParamOrStorage({ name: 'indent', storageName: 'objgen-json:i', defaultValue: 2 });
function transformer(value: string) {
try {
return ObjGen2Json(value, { numSpaces: indentSize.value });
}
catch (e: any) {
return `/* ERROR: ${e.toString()} */`;
}
}
</script>
<template>
<details mb-1>
<summary>Documentation</summary>
<textarea-copyable :value="defaultValue" language="toml" />
</details>
<format-transformer
input-label="ObjGen JSON definition"
:input-default="defaultValue"
input-placeholder="Put your ObjGen JSON definition here..."
output-label="Generated JSON"
output-language="json"
:transformer="transformer"
download-file-name="output.json"
/>
</template>
+239
View File
@@ -0,0 +1,239 @@
import { describe, expect, it } from 'vitest';
import { ObjGen2Json } from './objgen';
describe('ObjGen', () => {
describe('ObjGen2Json()', () => {
it('should generate correct JSON from model', () => {
expect(ObjGen2Json(`// Model & generate Live JSON data values
// interactively using a simple syntax.
// String is the default value type
product = Live JSON generator
// Number, Date & Boolean are also supported
// Specify types after property names
version n = 3.1
releaseDate d = 2014-06-25
demo b = true
// Tabs or spaces define complex values
person
id number = 12345
name = John Doe
phones
home = 800-123-4567
mobile = 877-123-1234
// Use [] to define simple type arrays
email[] s = jd@example.com, jd@example.org
dateOfBirth d = 1980-01-02
registered b = true
// Use [] or [n] to define object arrays
emergencyContacts[]
name s = Jane Doe
phone s = 888-555-1212
relationship = spouse
emergencyContacts[]
name s = Justin Doe
phone s = 877-123-1212
relationship = parent
// See our Help page for additional info
// We hope you enjoy the tool!
`)).toBe(`{
"product": "Live JSON generator",
"version": 3.1,
"releaseDate": "2014-06-25T00:00:00.000Z",
"demo": true,
"person": {
"id": 12345,
"name": "John Doe",
"phones": {
"home": "800-123-4567",
"mobile": "877-123-1234"
},
"email": [
"jd@example.com",
"jd@example.org"
],
"dateOfBirth": "1980-01-02T00:00:00.000Z",
"registered": true,
"emergencyContacts": [
{
"name": "Jane Doe",
"phone": "888-555-1212",
"relationship": "spouse"
},
{
"name": "Justin Doe",
"phone": "877-123-1212",
"relationship": "parent"
}
]
}
}`);
});
it('should generate a simple JSON object', () => {
const simple = {
id: '1',
name: 'test',
amount: 100,
when: '2017-03-09T12:34:56.789Z',
};
const model = 'id s = 1\n'
+ 'name = test\n'
+ 'amount n = 100\n'
+ 'when d = 2017-03-09T12:34:56.789Z';
expect(JSON.parse(ObjGen2Json(model))).to.deep.eq(simple);
});
it('should generate a JSON object that uses _dots_ in prop names', () => {
const dots = {
'this.that': 'xxx',
};
expect(JSON.parse(ObjGen2Json('this.that s = xxx'))).to.deep.eq(dots);
});
it('should generate an array of strings', () => {
const model = 'a[] = 1, 2, 3';
const strings = { a: ['1', '2', '3'] };
expect(JSON.parse(ObjGen2Json(model))).to.deep.eq(strings);
});
it('should generate an array of objects using explicit indicies', () => {
const model = 'a[0]\n'
+ ' id n = 1\n'
+ ' name = one\n'
+ 'a[1]\n'
+ ' id n = 2\n'
+ ' name = two\n';
const objects = {
a: [
{
id: 1,
name: 'one',
},
{
id: 2,
name: 'two',
}],
};
expect(JSON.parse(ObjGen2Json(model))).to.deep.eq(objects);
});
it('should generate an array of objects using implied indicies', () => {
const model = 'a[]\n'
+ ' id n = 1\n'
+ ' name = one\n'
+ 'a[]\n'
+ ' id n = 2\n'
+ ' name = two\n';
const objects = {
a: [
{
id: 1,
name: 'one',
},
{
id: 2,
name: 'two',
}],
};
expect(JSON.parse(ObjGen2Json(model))).to.deep.eq(objects);
});
it('should generate a top level object array', () => {
const model = '[]\n'
+ ' id n = 1\n'
+ ' name = one\n'
+ '[]\n'
+ ' id n = 2\n'
+ ' name = two\n'
+ '[]\n'
+ ' id n = 3\n'
+ ' name = three\n';
const array = [
{
id: 1,
name: 'one',
},
{
id: 2,
name: 'two',
},
{
id: 3,
name: 'three',
},
];
expect(JSON.parse(ObjGen2Json(model))).to.deep.eq(array);
});
it('should generate a complex object', () => {
const model = 'id n = 1\n'
+ 'name = one\n'
+ 'child\n'
+ ' id n = 1.1\n'
+ ' name = one.one\n'
+ 'child2\n'
+ ' id n = 2.1\n'
+ ' name = two.one\n'
+ ' subArray[]\n'
+ ' id n = 2.11\n'
+ ' name = two.one.one\n'
+ ' subArray[]\n'
+ ' id n = 2.12\n'
+ ' name = two.one.two\n'
+ ' subArray[]\n'
+ ' id n = 2.13\n'
+ ' name = two.one.three\n'
+ 'child3\n'
+ ' id n = 3.1\n'
+ ' name = three.one\n'
+ 'flag b = true\n';
const complex = {
id: 1,
name: 'one',
child: {
id: 1.1,
name: 'one.one',
},
child2: {
id: 2.1,
name: 'two.one',
subArray: [
{
id: 2.11,
name: 'two.one.one',
},
{
id: 2.12,
name: 'two.one.two',
},
{
id: 2.13,
name: 'two.one.three',
},
],
},
child3: {
id: 3.1,
name: 'three.one',
},
flag: true,
};
expect(JSON.parse(ObjGen2Json(model))).to.deep.eq(complex);
});
});
});
+334
View File
@@ -0,0 +1,334 @@
// ! objgen.js
// ! version : 4.0.4
// ! authors : Jim Winfield, js contributors, typescripted by ShareVB
// ! license : AGPL-3.0
const rawLineRegx = /^.*$|\n|$/g;
const newLineRegx = /\n/;
const spacesRegx = /\s/;
const arrayRegx = /\[\s*?([0-9]{1,100})?\s*?\]/;
const typesRegx = /^(\w+)(\s+)(\w+).*?$/;
function isNotUndefined(variable: any) {
return typeof (variable) !== 'undefined' && variable !== null;
}
export function parseLines(
val: string,
options?: { numSpaces?: number },
callback?: (line: string, depth: number) => void) {
if (callback === null) {
return;
}
let lastOffset = 0;
let currentLevel = 1;
let lines = 0;
// parse the raw inbound lines, to find individual input lines
val.replace(rawLineRegx, (match, curOffset) => {
if (curOffset > lastOffset) {
// get the current "raw" line
const raw = val.substring(lastOffset, curOffset).replace(newLineRegx, '');
if (lines > 0) {
// glean current level from leading whitespace (tabs or spaces)
let spaces = 0;
let level = 1;
for (let i = 0; i < raw.length; i++) {
const c = raw.charAt(i);
if (c === '\t') {
level++;
spaces = 0;
}
else if (c === ' ') {
spaces++;
}
else {
break;
}
if (spaces === options!.numSpaces) {
level++;
spaces = 0;
}
}
currentLevel = level;
}
else {
currentLevel = 1;
}
// count and process lines with real values
const lineText = raw.replace(spacesRegx, '');
if (lineText.length > 0) {
lines++;
}
if (lineText.length > 0) {
callback!(raw.trim(), currentLevel);
}
// update progress parsing the inbound value
lastOffset = curOffset;
}
return match;
});
};
function newValueOfType(dataType: string, initialVal: any) {
if (initialVal === null) {
initialVal = {};
}
let val = initialVal;
const t = dataType.charAt(0);
if (t === 's') {
if (typeof val !== 'string') {
val = '';
}
}
else if (t === 'b') {
val = initialVal === 'true';
}
else if (t === 'd') {
const dt = new Date();
if (initialVal.length > 0) {
dt.setTime(Date.parse(initialVal));
}
val = dt;
}
else if (t === 'n') {
let num;
if (initialVal.length > 0) {
num = Number.parseFloat(initialVal);
if (Number.isNaN(num)) {
num = Number.parseInt(initialVal);
if (!Number.isNaN(num)) {
num = 0;
}
}
}
else {
num = 0;
}
val = num;
}
else {
val = {};
}
return val;
};
function newArrayOfType(dataType: string, initialVal: any) {
const a: any[] = [];
if (typeof initialVal === 'string') {
const vals = initialVal.split(',');
for (const i in vals) {
const val = vals[i].trim();
a[i] = newValueOfType(dataType, val);
}
}
return a;
};
export function ObjGen2Json(val: string, options?: { numSpaces?: number }) {
const propStack: string[] = [];
const arrays: Record<any, any> = {};
const model: Record<any, any> = {};
let genRoot: Record<any, any> = {};
const keysep = '__keysep__';
if (!options) {
options = {
numSpaces: 2,
};
}
else if (!isNotUndefined(options.numSpaces)) {
options.numSpaces = 2;
}
// parse the raw inbound lines, to find individual input lines
parseLines(val, options, (line, depth) => {
if (line.match('^\s+$/|^\/$|^\/\/|^\s.*\/$|^\s.*\/\/') !== null) {
return '';
}
while (depth !== propStack.length) {
if (depth > propStack.length) {
propStack.push('');
}
else {
propStack.pop();
}
}
// Determine the data type being defined at this line level
const level = depth - 1;
const arrayInfo = arrayRegx.exec(line);
const isArray = arrayInfo !== null ? arrayInfo.length > 0 : false;
let arrayIndex = -1;
let rootArray = false;
if (isArray === true) {
if (level === 0 && line.match(/^\s*?\[.*?$/)) {
rootArray = true;
}
if (arrayInfo!.length > 1) {
arrayIndex = Number.parseInt(arrayInfo![1]);
}
}
let type = null;
if (rootArray === true) {
type = 'object';
}
else {
const typeSearch = typesRegx.exec(line.replace(arrayRegx, ''));
if (typeSearch !== null && typeSearch.length >= 4) {
type = typeSearch[3].toLowerCase();
}
}
// Determine if there is a value to assign
let initialVal = null;
const eqs = line.indexOf('=');
if (eqs !== -1) {
initialVal = line.substring(eqs + 1);
if (initialVal.length > 0) {
initialVal = initialVal.trim();
if (type === null) {
type = 's';
}
}
line = line.substring(0, eqs);
}
else {
// Create a default initial value
if (isArray === true) {
if (arrayIndex > 0) {
initialVal = {};
}
else {
initialVal = [];
}
}
else {
initialVal = {};
}
}
// Find the JSON property the line is defining
let prop = line;
if (type !== null) {
if (isArray === true) {
initialVal = newArrayOfType(type, initialVal);
}
else {
initialVal = newValueOfType(type, initialVal);
}
// remove type info from model line
const propNameRegx = /(^[^\s]+)/;
const rx = propNameRegx.exec(prop);
if (rx !== null) {
prop = rx[0];
}
}
// clean up prop name
prop = prop.replace(spacesRegx, '');
prop = rootArray ? '[]' : prop.replace(arrayRegx, '');
prop = prop.replace(/\[.*|]/g, '');
propStack[level] = prop;
// derive prop type key
let propKey = '';
for (let k = 0; k < propStack.length; k++) {
if (k > 0) {
propKey += keysep;
}
propKey += propStack[k];
}
if (isArray === true) {
const arr = Object.hasOwnProperty.call(arrays, propKey) ? arrays[propKey] : { name: prop, length: 0 };
if (arrayIndex < 0 || Number.isNaN(arrayIndex)) {
arrayIndex = arr.length;
}
arr.length += 1;
arrays[propKey] = arr;
const idx = `:${arrayIndex}`;
propKey += idx;
propStack[level] += idx;
}
// represent model information
if (!isNotUndefined(model[propKey])) {
if (rootArray === true && arrayIndex === 0) {
genRoot = initialVal;
}
const parentKey = propKey.substring(0, propKey.lastIndexOf(keysep));
model[propKey] = {
name: prop,
type,
array: isArray,
index: arrayIndex > -1 ? arrayIndex : null,
modelParent: parentKey.length > 0 ? model[parentKey] : null,
genParent: genRoot,
val: initialVal,
};
}
// Add the current value into the generated object
const curProp = model[propKey];
const modelParent = curProp.modelParent;
if (modelParent !== null) {
if (modelParent.array) {
curProp.genParent = modelParent.genParent[modelParent.name];
if (!isNotUndefined(curProp.genParent)) {
curProp.genParent = [];
}
if ((curProp.genParent.length < modelParent.index + 1)
|| (Array.isArray(curProp.genParent[modelParent.index]) && curProp.genParent[modelParent.index].length === 0)) {
curProp.genParent[modelParent.index] = {};
}
curProp.genParent = curProp.genParent[modelParent.index];
}
else {
curProp.genParent = modelParent.genParent[modelParent.name];
}
}
if (rootArray && level === 0 && arrayIndex > 0) {
genRoot[arrayIndex] = {};
}
if (curProp.array && arrayIndex > 0) {
if (!isNotUndefined(curProp.genParent[prop])) {
curProp.genParent[prop] = [];
curProp.genParent[prop][0] = curProp.val;
}
else {
curProp.genParent[prop][arrayIndex] = curProp.val;
}
}
else {
curProp.genParent[prop] = curProp.val;
}
});
return JSON.stringify(genRoot, undefined, options.numSpaces);
};