@tslite/codec 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var printer=require('@tslite/printer'),core=require('@tslite/core');var c=e=>{if(e.type==="Literal")return e.value;if(e.type==="ArrayExpression")return e.elements.map(c);if(e.type==="ObjectExpression")return S(e);let t=a(e);if(t&&typeof t=="object"&&"type"in t){let{type:s,...l}=t;return {[core.AST_MARKER]:s,...l}}return {[core.AST_MARKER]:"Unknown",value:t}},h=e=>e.type==="Literal"?e.value:printer.print(e);function S(e){let t=e.properties.flatMap(s=>{if(s.type==="SpreadElement"){let i=c(s.argument);if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(core.AST_MARKER in i))return Object.entries(i);let y=a(s);return [["...spread",{[core.AST_MARKER]:"SpreadElement",argument:y?.argument}]]}let l=h(s.key);return s.computed?[[`[${l}]`,c(s.value)]]:[[l,c(s.value)]]});return Object.fromEntries(t)}var p=e=>{let t={};for(let s in e)e[s]==false||e[s]==null||(t[s]=e[s]);return t},a=e=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(a):g[e.type]?.(e),g={ArrayExpression:e=>({type:"ArrayExpression",elements:a(e.elements||[])}),ArrayPattern:e=>({type:"ArrayPattern",elements:a(e.elements||[])}),ArrowFunctionExpression:e=>({type:"ArrowFunctionExpression",params:a(e.params||[]),body:a(e.body),...p({async:e.async})}),AssignmentExpression:e=>({type:"AssignmentExpression",operator:e.operator,left:a(e.left),right:a(e.right)}),AssignmentProperty:e=>({type:"Property",key:a(e.key),value:a(e.value),...p({shorthand:e.shorthand})}),AwaitExpression:e=>({type:"AwaitExpression",argument:a(e.argument)}),BinaryExpression:e=>({type:"BinaryExpression",operator:e.operator,left:a(e.left),right:a(e.right)}),BlockStatement:e=>({type:"BlockStatement",body:a(e.body||[])}),BreakStatement:e=>({type:"BreakStatement",...p({label:a(e.label)})}),CallExpression:e=>({type:"CallExpression",callee:a(e.callee),arguments:a(e.arguments||[]),...p({optional:e.optional})}),CatchClause:e=>({type:"CatchClause",param:a(e.param||[]),body:a(e.body)}),ChainExpression:e=>({type:"ChainExpression",expression:a(e.expression)}),ConditionalExpression:e=>({type:"ConditionalExpression",test:a(e.test),consequent:a(e.consequent),alternate:a(e.alternate)}),ContinueStatement:e=>({type:"ContinueStatement",...p({label:a(e.label)})}),DoWhileStatement:e=>({type:"DoWhileStatement",body:a(e.body),test:a(e.test)}),EmptyStatement:()=>({type:"EmptyStatement"}),ExpressionStatement:e=>({type:"ExpressionStatement",expression:a(e.expression)}),ForInStatement:e=>({type:"ForInStatement",left:a(e.left),right:a(e.right),body:a(e.body)}),ForOfStatement:e=>({type:"ForOfStatement",left:a(e.left),right:a(e.right),body:a(e.body),...p({await:e.await})}),ForStatement:e=>({type:"ForStatement",body:a(e.body),...p({init:a(e.init),test:a(e.test),update:a(e.update)})}),FunctionDeclaration:e=>({type:"FunctionDeclaration",id:a(e.id),params:a(e.params||[]),body:a(e.body),...p(core.pick(e,["async"]))}),FunctionExpression:e=>({type:"FunctionExpression",params:a(e.params||[]),body:a(e.body),...p({id:e.id?a(e.id):false,async:e.async})}),Identifier:e=>({type:"Identifier",name:e.name}),IfStatement:e=>({type:"IfStatement",test:a(e.test),consequent:a(e.consequent),alternate:a(e.alternate)}),JsonExpression:e=>({type:"JsonExpression",body:e.body}),Literal:e=>({type:"Literal",value:e.value,raw:e.raw}),LogicalExpression:e=>({type:"LogicalExpression",operator:e.operator,left:a(e.left),right:a(e.right)}),MemberExpression:e=>({type:"MemberExpression",object:a(e.object),property:a(e.property),...p(core.pick(e,["computed","optional"]))}),NewExpression:e=>({type:"NewExpression",callee:a(e.callee),arguments:a(e.arguments||[])}),ObjectExpression:e=>({type:"JsonExpression",body:S(e)}),ObjectPattern:e=>({type:"ObjectPattern",properties:a(e.properties||[])}),Program:e=>({type:"Program",body:a(e.body)}),Property:e=>({type:"Property",key:a(e.key),value:a(e.value),...p(core.pick(e,["kind","shorthand","computed"]))}),ReturnStatement:e=>({type:"ReturnStatement",argument:a(e.argument)}),SwitchCase:e=>({type:"SwitchCase",test:a(e.test),consequent:a(e.consequent)}),SwitchStatement:e=>({type:"SwitchStatement",discriminant:a(e.discriminant),cases:a(e.cases)}),TemplateElement:e=>({type:"TemplateElement",value:e.value,...p({tail:e.tail})}),TemplateLiteral:e=>({type:"TemplateLiteral",quasis:a(e.quasis),expressions:a(e.expressions)}),ThrowStatement:e=>({type:"ThrowStatement",argument:a(e.argument)}),TryStatement:e=>({type:"TryStatement",block:a(e.block),handler:a(e.handler),finalizer:a(e.finalizer)}),UnaryExpression:e=>({type:"UnaryExpression",operator:e.operator,argument:a(e.argument)}),UpdateExpression:e=>({type:"UpdateExpression",operator:e.operator,argument:a(e.argument),...p({prefix:e.prefix})}),VariableDeclaration:e=>({type:"VariableDeclaration",kind:e.kind,declarations:a(e.declarations||[])}),VariableDeclarator:e=>({type:"VariableDeclarator",id:a(e.id),init:a(e.init)}),WhileStatement:e=>({type:"WhileStatement",test:a(e.test),body:a(e.body)}),SpreadElement:e=>({type:"SpreadElement",argument:a(e.argument)}),RestElement:e=>({type:"RestElement",argument:a(e.argument)})};function r(e,t=new WeakMap){if(e==null)return e;if(typeof e!="object")throw new core.TSLiteError("not-an-object","AST node must be an object");if(t.has(e))throw new core.TSLiteError("circular-reference","Circular reference detected in AST",{phase:"ast"});t.set(e,true);try{if(Array.isArray(e))return e.map(l=>r(l,t));let s=e;if(s.type==="JsonExpression")return E(s.body,t);if(typeof s.type=="string"&&x[s.type])return x[s.type](s,t);throw new core.TSLiteError("unknown-node-type",`Unknown node type: ${s.type}`,{type:s.type})}finally{t.delete(e);}}function E(e,t=new WeakMap){if(e===null||typeof e!="object")return core.builders.literal(e);if(t.has(e))throw new core.TSLiteError("circular-reference","Circular reference detected in JSON",{phase:"json"});t.set(e,true);try{if(Array.isArray(e))return core.builders.arrayExpression(e.map(i=>E(i,t)));let s=e;if(core.AST_MARKER in s){let i=s[core.AST_MARKER];if(!core.isValidAstEntryType(i))throw core.invalidAstEntryError(i);let y={...s,type:i};return delete y[core.AST_MARKER],k(y,t)}let l=Object.entries(s).map(([i,y])=>core.builders.property(core.builders.identifier(i),E(y,t),!1,!1));return core.builders.objectExpression(l)}finally{t.delete(e);}}function k(e,t){if(typeof e.type!="string")throw new core.TSLiteError("missing-node-type","AST node must have a type property");if(!x[e.type])throw new core.TSLiteError("unknown-node-type",`Unknown AST node type: ${e.type}`,{type:e.type});return x[e.type](e,t)}var x={ArrayExpression:(e,t)=>core.builders.arrayExpression(o(e.elements,t)),ArrayPattern:(e,t)=>core.builders.arrayPattern(o(e.elements,t)),ArrowFunctionExpression:(e,t)=>core.builders.arrowFunctionExpression(o(e.params,t),r(e.body,t),e.async||false,e.generator||false),AssignmentExpression:(e,t)=>core.builders.assignmentExpression(e.operator,r(e.left,t),r(e.right,t)),AssignmentProperty:(e,t)=>core.builders.assignmentProperty(r(e.key,t),r(e.value,t),e.shorthand||false),AwaitExpression:(e,t)=>core.builders.awaitExpression(r(e.argument,t)),BinaryExpression:(e,t)=>core.builders.binaryExpression(e.operator,r(e.left,t),r(e.right,t)),BlockStatement:(e,t)=>core.builders.blockStatement(o(e.body,t)),BreakStatement:(e,t)=>core.builders.breakStatement(e.label?r(e.label,t):null),CallExpression:(e,t)=>core.builders.callExpression(r(e.callee,t),o(e.arguments,t),e.optional||false),CatchClause:(e,t)=>core.builders.catchClause(e.param?r(e.param,t):null,r(e.body,t)),ChainExpression:(e,t)=>core.builders.chainExpression(r(e.expression,t)),ConditionalExpression:(e,t)=>core.builders.conditionalExpression(r(e.test,t),r(e.consequent,t),r(e.alternate,t)),ContinueStatement:(e,t)=>core.builders.continueStatement(e.label?r(e.label,t):null),DoWhileStatement:(e,t)=>core.builders.doWhileStatement(r(e.body,t),r(e.test,t)),EmptyStatement:()=>core.builders.emptyStatement(),ExpressionStatement:(e,t)=>core.builders.expressionStatement(r(e.expression,t)),ForInStatement:(e,t)=>core.builders.forInStatement(r(e.left,t),r(e.right,t),r(e.body,t)),ForOfStatement:(e,t)=>core.builders.forOfStatement(r(e.left,t),r(e.right,t),r(e.body,t),e.await||false),ForStatement:(e,t)=>core.builders.forStatement(e.init?r(e.init,t):null,e.test?r(e.test,t):null,e.update?r(e.update,t):null,r(e.body,t)),FunctionDeclaration:(e,t)=>core.builders.functionDeclaration(r(e.id,t),o(e.params,t),r(e.body,t),e.generator||false,e.async||false),FunctionExpression:(e,t)=>core.builders.functionExpression(e.id?r(e.id,t):null,o(e.params,t),r(e.body,t),e.async||false,e.generator||false),Identifier:e=>core.builders.identifier(e.name),IfStatement:(e,t)=>core.builders.ifStatement(r(e.test,t),r(e.consequent,t),e.alternate?r(e.alternate,t):null),Literal:e=>core.builders.literal(e.value),LogicalExpression:(e,t)=>core.builders.logicalExpression(e.operator,r(e.left,t),r(e.right,t)),MemberExpression:(e,t)=>core.builders.memberExpression(r(e.object,t),r(e.property,t),e.computed||false,e.optional||false),NewExpression:(e,t)=>core.builders.newExpression(r(e.callee,t),o(e.arguments,t)),ObjectExpression:(e,t)=>core.builders.objectExpression(o(e.properties,t)),ObjectPattern:(e,t)=>core.builders.objectPattern(o(e.properties,t)),Program:(e,t)=>core.builders.program(o(e.body,t)),Property:(e,t)=>core.builders.property(r(e.key,t),r(e.value,t),e.shorthand||false,e.computed||false),RestElement:(e,t)=>core.builders.restElement(r(e.argument,t)),ReturnStatement:(e,t)=>core.builders.returnStatement(e.argument?r(e.argument,t):null),SpreadElement:(e,t)=>core.builders.spreadElement(r(e.argument,t)),SwitchCase:(e,t)=>core.builders.switchCase(e.test?r(e.test,t):null,o(e.consequent,t)),SwitchStatement:(e,t)=>core.builders.switchStatement(r(e.discriminant,t),o(e.cases,t)),TemplateElement:e=>core.builders.templateElement(e.value,e.tail||false),TemplateLiteral:(e,t)=>core.builders.templateLiteral(o(e.quasis,t),o(e.expressions,t)),ThrowStatement:(e,t)=>core.builders.throwStatement(r(e.argument,t)),TryStatement:(e,t)=>core.builders.tryStatement(r(e.block,t),e.handler?r(e.handler,t):null,e.finalizer?r(e.finalizer,t):null),UnaryExpression:(e,t)=>core.builders.unaryExpression(e.operator,r(e.argument,t)),UpdateExpression:(e,t)=>core.builders.updateExpression(e.operator,r(e.argument,t),e.prefix||false),VariableDeclaration:(e,t)=>core.builders.variableDeclaration(e.kind,o(e.declarations,t)),VariableDeclarator:(e,t)=>core.builders.variableDeclarator(r(e.id,t),e.init?r(e.init,t):null),WhileStatement:(e,t)=>core.builders.whileStatement(r(e.test,t),r(e.body,t))};function o(e,t){return e?e.map(s=>s!=null?r(s,t):null):[]}exports.decode=r;exports.encode=a;exports.fromJson=E;exports.objectToJson=S;exports.valueToJson=c;
@@ -0,0 +1,102 @@
1
+ import { types, ObjectExpression } from '@tslite/core';
2
+
3
+ /**
4
+ * Compacta um AST ESTree na forma serializada do TSLite — um
5
+ * {@link SimpleNode} (campos falsy omitidos; `ObjectExpression` vira
6
+ * `JsonExpression` cujo `body` é {@link TSLite}). É o inverso de `decode`.
7
+ *
8
+ * A assinatura é deliberadamente larga (`any`): `encode` é um dispatcher
9
+ * recursivo sobre nós, arrays e primitivos — a precisão de tipo vive nos
10
+ * parsers por tipo (que retornam `Simple*`).
11
+ */
12
+ declare const encode: (n: any) => any;
13
+
14
+ /**
15
+ * decode.ts - Reconstrói AST ESTree a partir de SimpleAST/JSON
16
+ *
17
+ * Fluxo: SimpleAST (JSON com #ast markers) → Full ESTree AST
18
+ *
19
+ * Este é o inverso do encode():
20
+ * - encode() compacta AST → JSON (TSLite)
21
+ * - decode() reconstrói JSON → AST
22
+ *
23
+ * ## Formato #ast
24
+ *
25
+ * O marcador `#ast` indica a fronteira JSON → AST. O valor é o tipo do nó:
26
+ *
27
+ * ```json
28
+ * {
29
+ * "name": "João",
30
+ * "calc": {
31
+ * "#ast": "CallExpression",
32
+ * "callee": { "type": "Identifier", "name": "getValue" },
33
+ * "arguments": []
34
+ * }
35
+ * }
36
+ * ```
37
+ *
38
+ * - `#ast` marca onde começa o AST (fronteira)
39
+ * - Dentro do AST, usa `type` normal (ESTree)
40
+ * - Só expressões são válidas como `#ast` (coisas que retornam valor)
41
+ */
42
+
43
+ /** Code dos erros lançados pelo decode do codec. */
44
+ type CodecErrorCode = "not-an-object" | "circular-reference" | "missing-node-type" | "unknown-node-type";
45
+ /**
46
+ * Reconstrói um nó AST simplificado para AST ESTree completo.
47
+ *
48
+ * @param node - SimpleAST node (pode conter #ast markers)
49
+ * @returns Full ESTree AST node
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const simpleAst = {
54
+ * type: "JsonExpression",
55
+ * body: {
56
+ * name: "João",
57
+ * calc: { "#ast": "CallExpression", callee: {...}, arguments: [] }
58
+ * }
59
+ * };
60
+ * const fullAst = decode(simpleAst);
61
+ * ```
62
+ */
63
+ declare function decode(node: unknown, visited?: WeakMap<object, boolean>): types.Node;
64
+ /**
65
+ * Converte JSON puro (com possíveis #ast markers) para AST Expression.
66
+ * Usado internamente para processar o `body` de JsonExpression.
67
+ *
68
+ * @param value - Valor JSON (pode conter #ast markers aninhados)
69
+ * @returns AST Expression equivalente
70
+ */
71
+ declare function fromJson(value: unknown, visited?: WeakMap<object, boolean>): types.Expression;
72
+
73
+ /**
74
+ * json.ts — conversão AST → forma JSON híbrida (encode helpers)
75
+ *
76
+ * Converte nós AST em valores JSON, marcando lógica executável com `#ast`.
77
+ * A direção inversa (JSON → AST) vive em decode.ts; a emissão para código JS
78
+ * vive em @tslite/printer (printJson).
79
+ *
80
+ * Formato `#ast`: o valor de `#ast` é o tipo do nó; as propriedades ficam no
81
+ * mesmo nível.
82
+ *
83
+ * ```json
84
+ * { "#ast": "CallExpression", "callee": { ... }, "arguments": [] }
85
+ * ```
86
+ */
87
+
88
+ /**
89
+ * Converte um nó AST em valor JSON.
90
+ * - Literal → valor direto
91
+ * - ArrayExpression → array JSON
92
+ * - ObjectExpression → objeto JSON (via objectToJson)
93
+ * - Outros → marcador #ast com o nó codificado
94
+ */
95
+ declare const valueToJson: (node: any) => any;
96
+ /**
97
+ * Converte ObjectExpression AST para objeto JSON.
98
+ * Valores estáticos viram JSON direto; valores com lógica recebem `#ast`.
99
+ */
100
+ declare function objectToJson(expr: ObjectExpression): any;
101
+
102
+ export { type CodecErrorCode, decode, encode, fromJson, objectToJson, valueToJson };
@@ -0,0 +1,102 @@
1
+ import { types, ObjectExpression } from '@tslite/core';
2
+
3
+ /**
4
+ * Compacta um AST ESTree na forma serializada do TSLite — um
5
+ * {@link SimpleNode} (campos falsy omitidos; `ObjectExpression` vira
6
+ * `JsonExpression` cujo `body` é {@link TSLite}). É o inverso de `decode`.
7
+ *
8
+ * A assinatura é deliberadamente larga (`any`): `encode` é um dispatcher
9
+ * recursivo sobre nós, arrays e primitivos — a precisão de tipo vive nos
10
+ * parsers por tipo (que retornam `Simple*`).
11
+ */
12
+ declare const encode: (n: any) => any;
13
+
14
+ /**
15
+ * decode.ts - Reconstrói AST ESTree a partir de SimpleAST/JSON
16
+ *
17
+ * Fluxo: SimpleAST (JSON com #ast markers) → Full ESTree AST
18
+ *
19
+ * Este é o inverso do encode():
20
+ * - encode() compacta AST → JSON (TSLite)
21
+ * - decode() reconstrói JSON → AST
22
+ *
23
+ * ## Formato #ast
24
+ *
25
+ * O marcador `#ast` indica a fronteira JSON → AST. O valor é o tipo do nó:
26
+ *
27
+ * ```json
28
+ * {
29
+ * "name": "João",
30
+ * "calc": {
31
+ * "#ast": "CallExpression",
32
+ * "callee": { "type": "Identifier", "name": "getValue" },
33
+ * "arguments": []
34
+ * }
35
+ * }
36
+ * ```
37
+ *
38
+ * - `#ast` marca onde começa o AST (fronteira)
39
+ * - Dentro do AST, usa `type` normal (ESTree)
40
+ * - Só expressões são válidas como `#ast` (coisas que retornam valor)
41
+ */
42
+
43
+ /** Code dos erros lançados pelo decode do codec. */
44
+ type CodecErrorCode = "not-an-object" | "circular-reference" | "missing-node-type" | "unknown-node-type";
45
+ /**
46
+ * Reconstrói um nó AST simplificado para AST ESTree completo.
47
+ *
48
+ * @param node - SimpleAST node (pode conter #ast markers)
49
+ * @returns Full ESTree AST node
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const simpleAst = {
54
+ * type: "JsonExpression",
55
+ * body: {
56
+ * name: "João",
57
+ * calc: { "#ast": "CallExpression", callee: {...}, arguments: [] }
58
+ * }
59
+ * };
60
+ * const fullAst = decode(simpleAst);
61
+ * ```
62
+ */
63
+ declare function decode(node: unknown, visited?: WeakMap<object, boolean>): types.Node;
64
+ /**
65
+ * Converte JSON puro (com possíveis #ast markers) para AST Expression.
66
+ * Usado internamente para processar o `body` de JsonExpression.
67
+ *
68
+ * @param value - Valor JSON (pode conter #ast markers aninhados)
69
+ * @returns AST Expression equivalente
70
+ */
71
+ declare function fromJson(value: unknown, visited?: WeakMap<object, boolean>): types.Expression;
72
+
73
+ /**
74
+ * json.ts — conversão AST → forma JSON híbrida (encode helpers)
75
+ *
76
+ * Converte nós AST em valores JSON, marcando lógica executável com `#ast`.
77
+ * A direção inversa (JSON → AST) vive em decode.ts; a emissão para código JS
78
+ * vive em @tslite/printer (printJson).
79
+ *
80
+ * Formato `#ast`: o valor de `#ast` é o tipo do nó; as propriedades ficam no
81
+ * mesmo nível.
82
+ *
83
+ * ```json
84
+ * { "#ast": "CallExpression", "callee": { ... }, "arguments": [] }
85
+ * ```
86
+ */
87
+
88
+ /**
89
+ * Converte um nó AST em valor JSON.
90
+ * - Literal → valor direto
91
+ * - ArrayExpression → array JSON
92
+ * - ObjectExpression → objeto JSON (via objectToJson)
93
+ * - Outros → marcador #ast com o nó codificado
94
+ */
95
+ declare const valueToJson: (node: any) => any;
96
+ /**
97
+ * Converte ObjectExpression AST para objeto JSON.
98
+ * Valores estáticos viram JSON direto; valores com lógica recebem `#ast`.
99
+ */
100
+ declare function objectToJson(expr: ObjectExpression): any;
101
+
102
+ export { type CodecErrorCode, decode, encode, fromJson, objectToJson, valueToJson };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import {print}from'@tslite/printer';import {AST_MARKER,pick,TSLiteError,builders,isValidAstEntryType,invalidAstEntryError}from'@tslite/core';var c=e=>{if(e.type==="Literal")return e.value;if(e.type==="ArrayExpression")return e.elements.map(c);if(e.type==="ObjectExpression")return S(e);let t=a(e);if(t&&typeof t=="object"&&"type"in t){let{type:s,...l}=t;return {[AST_MARKER]:s,...l}}return {[AST_MARKER]:"Unknown",value:t}},h=e=>e.type==="Literal"?e.value:print(e);function S(e){let t=e.properties.flatMap(s=>{if(s.type==="SpreadElement"){let i=c(s.argument);if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(AST_MARKER in i))return Object.entries(i);let y=a(s);return [["...spread",{[AST_MARKER]:"SpreadElement",argument:y?.argument}]]}let l=h(s.key);return s.computed?[[`[${l}]`,c(s.value)]]:[[l,c(s.value)]]});return Object.fromEntries(t)}var p=e=>{let t={};for(let s in e)e[s]==false||e[s]==null||(t[s]=e[s]);return t},a=e=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(a):g[e.type]?.(e),g={ArrayExpression:e=>({type:"ArrayExpression",elements:a(e.elements||[])}),ArrayPattern:e=>({type:"ArrayPattern",elements:a(e.elements||[])}),ArrowFunctionExpression:e=>({type:"ArrowFunctionExpression",params:a(e.params||[]),body:a(e.body),...p({async:e.async})}),AssignmentExpression:e=>({type:"AssignmentExpression",operator:e.operator,left:a(e.left),right:a(e.right)}),AssignmentProperty:e=>({type:"Property",key:a(e.key),value:a(e.value),...p({shorthand:e.shorthand})}),AwaitExpression:e=>({type:"AwaitExpression",argument:a(e.argument)}),BinaryExpression:e=>({type:"BinaryExpression",operator:e.operator,left:a(e.left),right:a(e.right)}),BlockStatement:e=>({type:"BlockStatement",body:a(e.body||[])}),BreakStatement:e=>({type:"BreakStatement",...p({label:a(e.label)})}),CallExpression:e=>({type:"CallExpression",callee:a(e.callee),arguments:a(e.arguments||[]),...p({optional:e.optional})}),CatchClause:e=>({type:"CatchClause",param:a(e.param||[]),body:a(e.body)}),ChainExpression:e=>({type:"ChainExpression",expression:a(e.expression)}),ConditionalExpression:e=>({type:"ConditionalExpression",test:a(e.test),consequent:a(e.consequent),alternate:a(e.alternate)}),ContinueStatement:e=>({type:"ContinueStatement",...p({label:a(e.label)})}),DoWhileStatement:e=>({type:"DoWhileStatement",body:a(e.body),test:a(e.test)}),EmptyStatement:()=>({type:"EmptyStatement"}),ExpressionStatement:e=>({type:"ExpressionStatement",expression:a(e.expression)}),ForInStatement:e=>({type:"ForInStatement",left:a(e.left),right:a(e.right),body:a(e.body)}),ForOfStatement:e=>({type:"ForOfStatement",left:a(e.left),right:a(e.right),body:a(e.body),...p({await:e.await})}),ForStatement:e=>({type:"ForStatement",body:a(e.body),...p({init:a(e.init),test:a(e.test),update:a(e.update)})}),FunctionDeclaration:e=>({type:"FunctionDeclaration",id:a(e.id),params:a(e.params||[]),body:a(e.body),...p(pick(e,["async"]))}),FunctionExpression:e=>({type:"FunctionExpression",params:a(e.params||[]),body:a(e.body),...p({id:e.id?a(e.id):false,async:e.async})}),Identifier:e=>({type:"Identifier",name:e.name}),IfStatement:e=>({type:"IfStatement",test:a(e.test),consequent:a(e.consequent),alternate:a(e.alternate)}),JsonExpression:e=>({type:"JsonExpression",body:e.body}),Literal:e=>({type:"Literal",value:e.value,raw:e.raw}),LogicalExpression:e=>({type:"LogicalExpression",operator:e.operator,left:a(e.left),right:a(e.right)}),MemberExpression:e=>({type:"MemberExpression",object:a(e.object),property:a(e.property),...p(pick(e,["computed","optional"]))}),NewExpression:e=>({type:"NewExpression",callee:a(e.callee),arguments:a(e.arguments||[])}),ObjectExpression:e=>({type:"JsonExpression",body:S(e)}),ObjectPattern:e=>({type:"ObjectPattern",properties:a(e.properties||[])}),Program:e=>({type:"Program",body:a(e.body)}),Property:e=>({type:"Property",key:a(e.key),value:a(e.value),...p(pick(e,["kind","shorthand","computed"]))}),ReturnStatement:e=>({type:"ReturnStatement",argument:a(e.argument)}),SwitchCase:e=>({type:"SwitchCase",test:a(e.test),consequent:a(e.consequent)}),SwitchStatement:e=>({type:"SwitchStatement",discriminant:a(e.discriminant),cases:a(e.cases)}),TemplateElement:e=>({type:"TemplateElement",value:e.value,...p({tail:e.tail})}),TemplateLiteral:e=>({type:"TemplateLiteral",quasis:a(e.quasis),expressions:a(e.expressions)}),ThrowStatement:e=>({type:"ThrowStatement",argument:a(e.argument)}),TryStatement:e=>({type:"TryStatement",block:a(e.block),handler:a(e.handler),finalizer:a(e.finalizer)}),UnaryExpression:e=>({type:"UnaryExpression",operator:e.operator,argument:a(e.argument)}),UpdateExpression:e=>({type:"UpdateExpression",operator:e.operator,argument:a(e.argument),...p({prefix:e.prefix})}),VariableDeclaration:e=>({type:"VariableDeclaration",kind:e.kind,declarations:a(e.declarations||[])}),VariableDeclarator:e=>({type:"VariableDeclarator",id:a(e.id),init:a(e.init)}),WhileStatement:e=>({type:"WhileStatement",test:a(e.test),body:a(e.body)}),SpreadElement:e=>({type:"SpreadElement",argument:a(e.argument)}),RestElement:e=>({type:"RestElement",argument:a(e.argument)})};function r(e,t=new WeakMap){if(e==null)return e;if(typeof e!="object")throw new TSLiteError("not-an-object","AST node must be an object");if(t.has(e))throw new TSLiteError("circular-reference","Circular reference detected in AST",{phase:"ast"});t.set(e,true);try{if(Array.isArray(e))return e.map(l=>r(l,t));let s=e;if(s.type==="JsonExpression")return E(s.body,t);if(typeof s.type=="string"&&x[s.type])return x[s.type](s,t);throw new TSLiteError("unknown-node-type",`Unknown node type: ${s.type}`,{type:s.type})}finally{t.delete(e);}}function E(e,t=new WeakMap){if(e===null||typeof e!="object")return builders.literal(e);if(t.has(e))throw new TSLiteError("circular-reference","Circular reference detected in JSON",{phase:"json"});t.set(e,true);try{if(Array.isArray(e))return builders.arrayExpression(e.map(i=>E(i,t)));let s=e;if(AST_MARKER in s){let i=s[AST_MARKER];if(!isValidAstEntryType(i))throw invalidAstEntryError(i);let y={...s,type:i};return delete y[AST_MARKER],k(y,t)}let l=Object.entries(s).map(([i,y])=>builders.property(builders.identifier(i),E(y,t),!1,!1));return builders.objectExpression(l)}finally{t.delete(e);}}function k(e,t){if(typeof e.type!="string")throw new TSLiteError("missing-node-type","AST node must have a type property");if(!x[e.type])throw new TSLiteError("unknown-node-type",`Unknown AST node type: ${e.type}`,{type:e.type});return x[e.type](e,t)}var x={ArrayExpression:(e,t)=>builders.arrayExpression(o(e.elements,t)),ArrayPattern:(e,t)=>builders.arrayPattern(o(e.elements,t)),ArrowFunctionExpression:(e,t)=>builders.arrowFunctionExpression(o(e.params,t),r(e.body,t),e.async||false,e.generator||false),AssignmentExpression:(e,t)=>builders.assignmentExpression(e.operator,r(e.left,t),r(e.right,t)),AssignmentProperty:(e,t)=>builders.assignmentProperty(r(e.key,t),r(e.value,t),e.shorthand||false),AwaitExpression:(e,t)=>builders.awaitExpression(r(e.argument,t)),BinaryExpression:(e,t)=>builders.binaryExpression(e.operator,r(e.left,t),r(e.right,t)),BlockStatement:(e,t)=>builders.blockStatement(o(e.body,t)),BreakStatement:(e,t)=>builders.breakStatement(e.label?r(e.label,t):null),CallExpression:(e,t)=>builders.callExpression(r(e.callee,t),o(e.arguments,t),e.optional||false),CatchClause:(e,t)=>builders.catchClause(e.param?r(e.param,t):null,r(e.body,t)),ChainExpression:(e,t)=>builders.chainExpression(r(e.expression,t)),ConditionalExpression:(e,t)=>builders.conditionalExpression(r(e.test,t),r(e.consequent,t),r(e.alternate,t)),ContinueStatement:(e,t)=>builders.continueStatement(e.label?r(e.label,t):null),DoWhileStatement:(e,t)=>builders.doWhileStatement(r(e.body,t),r(e.test,t)),EmptyStatement:()=>builders.emptyStatement(),ExpressionStatement:(e,t)=>builders.expressionStatement(r(e.expression,t)),ForInStatement:(e,t)=>builders.forInStatement(r(e.left,t),r(e.right,t),r(e.body,t)),ForOfStatement:(e,t)=>builders.forOfStatement(r(e.left,t),r(e.right,t),r(e.body,t),e.await||false),ForStatement:(e,t)=>builders.forStatement(e.init?r(e.init,t):null,e.test?r(e.test,t):null,e.update?r(e.update,t):null,r(e.body,t)),FunctionDeclaration:(e,t)=>builders.functionDeclaration(r(e.id,t),o(e.params,t),r(e.body,t),e.generator||false,e.async||false),FunctionExpression:(e,t)=>builders.functionExpression(e.id?r(e.id,t):null,o(e.params,t),r(e.body,t),e.async||false,e.generator||false),Identifier:e=>builders.identifier(e.name),IfStatement:(e,t)=>builders.ifStatement(r(e.test,t),r(e.consequent,t),e.alternate?r(e.alternate,t):null),Literal:e=>builders.literal(e.value),LogicalExpression:(e,t)=>builders.logicalExpression(e.operator,r(e.left,t),r(e.right,t)),MemberExpression:(e,t)=>builders.memberExpression(r(e.object,t),r(e.property,t),e.computed||false,e.optional||false),NewExpression:(e,t)=>builders.newExpression(r(e.callee,t),o(e.arguments,t)),ObjectExpression:(e,t)=>builders.objectExpression(o(e.properties,t)),ObjectPattern:(e,t)=>builders.objectPattern(o(e.properties,t)),Program:(e,t)=>builders.program(o(e.body,t)),Property:(e,t)=>builders.property(r(e.key,t),r(e.value,t),e.shorthand||false,e.computed||false),RestElement:(e,t)=>builders.restElement(r(e.argument,t)),ReturnStatement:(e,t)=>builders.returnStatement(e.argument?r(e.argument,t):null),SpreadElement:(e,t)=>builders.spreadElement(r(e.argument,t)),SwitchCase:(e,t)=>builders.switchCase(e.test?r(e.test,t):null,o(e.consequent,t)),SwitchStatement:(e,t)=>builders.switchStatement(r(e.discriminant,t),o(e.cases,t)),TemplateElement:e=>builders.templateElement(e.value,e.tail||false),TemplateLiteral:(e,t)=>builders.templateLiteral(o(e.quasis,t),o(e.expressions,t)),ThrowStatement:(e,t)=>builders.throwStatement(r(e.argument,t)),TryStatement:(e,t)=>builders.tryStatement(r(e.block,t),e.handler?r(e.handler,t):null,e.finalizer?r(e.finalizer,t):null),UnaryExpression:(e,t)=>builders.unaryExpression(e.operator,r(e.argument,t)),UpdateExpression:(e,t)=>builders.updateExpression(e.operator,r(e.argument,t),e.prefix||false),VariableDeclaration:(e,t)=>builders.variableDeclaration(e.kind,o(e.declarations,t)),VariableDeclarator:(e,t)=>builders.variableDeclarator(r(e.id,t),e.init?r(e.init,t):null),WhileStatement:(e,t)=>builders.whileStatement(r(e.test,t),r(e.body,t))};function o(e,t){return e?e.map(s=>s!=null?r(s,t):null):[]}export{r as decode,a as encode,E as fromJson,S as objectToJson,c as valueToJson};
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@tslite/codec",
3
+ "version": "0.1.0",
4
+ "description": "TSLite codec — serializes AST to hybrid #ast JSON and back (encode/decode)",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/andersondrosa/tslite.git",
26
+ "directory": "packages/codec"
27
+ },
28
+ "keywords": [
29
+ "ast",
30
+ "estree",
31
+ "json",
32
+ "serialization",
33
+ "encode",
34
+ "decode",
35
+ "typescript"
36
+ ],
37
+ "author": "Anderson D. Rosa <andersondrosa@outlook.com>",
38
+ "license": "MIT",
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "dependencies": {
43
+ "@tslite/core": "0.1.0",
44
+ "@tslite/printer": "0.1.0"
45
+ },
46
+ "scripts": {
47
+ "build": "tsup",
48
+ "dev": "tsup --watch",
49
+ "test": "vitest run",
50
+ "test:watch": "vitest",
51
+ "test:coverage": "vitest run --coverage",
52
+ "typecheck": "tsc --noEmit",
53
+ "lint": "eslint src tests",
54
+ "lint:fix": "eslint src tests --fix",
55
+ "clean": "rm -rf dist",
56
+ "format": "prettier --write \"src/**/*.ts\"",
57
+ "format:check": "prettier --check \"src/**/*.ts\""
58
+ }
59
+ }