@morphql/core 0.1.12 → 0.1.14

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 CHANGED
@@ -1,31 +1,4 @@
1
- 'use strict';var chevrotain=require('chevrotain'),fastXmlParser=require('fast-xml-parser'),ft=require('papaparse'),vt=require('js-beautify');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ft__default=/*#__PURE__*/_interopDefault(ft);var vt__default=/*#__PURE__*/_interopDefault(vt);var Et=chevrotain.createToken({name:"WhiteSpace",pattern:/\s+/,group:chevrotain.Lexer.SKIPPED}),Lt=chevrotain.createToken({name:"LineComment",pattern:/\/\/[^\n\r]*/,group:chevrotain.Lexer.SKIPPED}),St=chevrotain.createToken({name:"BlockComment",pattern:/\/\*[\s\S]*?\*\//,group:chevrotain.Lexer.SKIPPED}),c=chevrotain.createToken({name:"Identifier",pattern:/[a-zA-Z_$][a-zA-Z0-9_.[\]]*/}),O=chevrotain.createToken({name:"QuotedIdentifier",pattern:/`([^`\\]|\\.)*`/}),U=chevrotain.createToken({name:"From",pattern:/from/i,longer_alt:c}),R=chevrotain.createToken({name:"To",pattern:/to/i,longer_alt:c}),$=chevrotain.createToken({name:"Transform",pattern:/transform/i,longer_alt:c}),C=chevrotain.createToken({name:"Set",pattern:/set/i,longer_alt:c}),B=chevrotain.createToken({name:"Section",pattern:/section/i,longer_alt:c}),M=chevrotain.createToken({name:"Multiple",pattern:/multiple/i,longer_alt:c}),I=chevrotain.createToken({name:"Clone",pattern:/clone/i,longer_alt:c}),w=chevrotain.createToken({name:"Delete",pattern:/delete/i,longer_alt:c}),k=chevrotain.createToken({name:"Define",pattern:/define/i,longer_alt:c}),q=chevrotain.createToken({name:"Modify",pattern:/modify/i,longer_alt:c}),v=chevrotain.createToken({name:"If",pattern:/if/i,longer_alt:c}),P=chevrotain.createToken({name:"Else",pattern:/else/i,longer_alt:c}),z=chevrotain.createToken({name:"True",pattern:/true/i,longer_alt:c}),_=chevrotain.createToken({name:"False",pattern:/false/i,longer_alt:c}),j=chevrotain.createToken({name:"Null",pattern:/null/i,longer_alt:c}),F=chevrotain.createToken({name:"Return",pattern:/return/i,longer_alt:c}),x=chevrotain.createToken({name:"Unsafe",pattern:/unsafe/i,longer_alt:c}),D=chevrotain.createToken({name:"EqualsEquals",pattern:/==/}),W=chevrotain.createToken({name:"EqualsEqualsEquals",pattern:/===/}),Y=chevrotain.createToken({name:"NotEquals",pattern:/!=/}),G=chevrotain.createToken({name:"NotEqualsEquals",pattern:/!==/}),J=chevrotain.createToken({name:"LessThanOrEqual",pattern:/<=/}),Q=chevrotain.createToken({name:"GreaterThanOrEqual",pattern:/>=/}),V=chevrotain.createToken({name:"LessThan",pattern:/</}),Z=chevrotain.createToken({name:"GreaterThan",pattern:/>/}),K=chevrotain.createToken({name:"And",pattern:/&&/}),H=chevrotain.createToken({name:"Or",pattern:/\|\|/}),X=chevrotain.createToken({name:"Not",pattern:/!/}),E=chevrotain.createToken({name:"Equals",pattern:/=/}),tt=chevrotain.createToken({name:"Plus",pattern:/\+/}),b=chevrotain.createToken({name:"Minus",pattern:/-/}),et=chevrotain.createToken({name:"Times",pattern:/\*/}),rt=chevrotain.createToken({name:"Divide",pattern:/\//}),m=chevrotain.createToken({name:"LParen",pattern:/\(/}),g=chevrotain.createToken({name:"RParen",pattern:/\)/}),N=chevrotain.createToken({name:"Comma",pattern:/,/}),st=chevrotain.createToken({name:"StringLiteral",pattern:/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/}),it=chevrotain.createToken({name:"NumericLiteral",pattern:/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/}),nt=[Et,Lt,St,U,R,$,C,B,M,I,w,k,q,v,P,z,_,j,F,x,W,D,G,Y,J,Q,K,H,E,V,Z,X,tt,b,et,rt,m,g,N,st,it,O,c],ct=new chevrotain.Lexer(nt);var at=class extends chevrotain.CstParser{constructor(){super(nt),this.performSelfAnalysis();}query=this.RULE("query",()=>{this.CONSUME(U),this.SUBRULE(this.typeFormat,{LABEL:"sourceType"}),this.CONSUME(R),this.SUBRULE1(this.typeFormat,{LABEL:"targetType"}),this.OPTION(()=>{this.CONSUME($),this.OPTION1(()=>{this.CONSUME(x);}),this.MANY(()=>{this.SUBRULE(this.action);});});});typeFormat=this.RULE("typeFormat",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"name"}),this.OPTION(()=>{this.CONSUME(m),this.MANY_SEP({SEP:N,DEF:()=>{this.SUBRULE(this.typeFormatParameter,{LABEL:"params"});}}),this.CONSUME(g);});});typeFormatParameter=this.RULE("typeFormatParameter",()=>{this.OR([{GATE:()=>this.LA(2).tokenType===E,ALT:()=>this.SUBRULE(this.namedParameter)},{ALT:()=>this.SUBRULE(this.literal)}]);});namedParameter=this.RULE("namedParameter",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"key"}),this.CONSUME(E),this.SUBRULE(this.literal,{LABEL:"value"});});anyIdentifier=this.RULE("anyIdentifier",()=>{this.OR([{ALT:()=>this.CONSUME(c)},{ALT:()=>this.CONSUME(O)}]);});literal=this.RULE("literal",()=>{this.OR([{ALT:()=>this.CONSUME(st)},{ALT:()=>this.CONSUME(it)},{ALT:()=>this.CONSUME(z)},{ALT:()=>this.CONSUME(_)},{ALT:()=>this.CONSUME(j)}]);});action=this.RULE("action",()=>{this.OR([{ALT:()=>this.SUBRULE(this.setRule)},{ALT:()=>this.SUBRULE(this.modifyRule)},{ALT:()=>this.SUBRULE(this.sectionRule)},{ALT:()=>this.SUBRULE(this.cloneRule)},{ALT:()=>this.SUBRULE(this.deleteRule)},{ALT:()=>this.SUBRULE(this.ifAction)},{ALT:()=>this.SUBRULE(this.defineRule)},{ALT:()=>this.SUBRULE(this.returnRule)}]);});returnRule=this.RULE("returnRule",()=>{this.CONSUME(F),this.SUBRULE(this.expression,{LABEL:"expr"});});deleteRule=this.RULE("deleteRule",()=>{this.CONSUME(w),this.SUBRULE(this.anyIdentifier,{LABEL:"field"});});ifAction=this.RULE("ifAction",()=>{this.CONSUME(v),this.CONSUME(m),this.SUBRULE(this.expression,{LABEL:"condition"}),this.CONSUME(g),this.CONSUME2(m),this.MANY(()=>{this.SUBRULE(this.action,{LABEL:"thenActions"});}),this.CONSUME2(g),this.OPTION(()=>{this.CONSUME(P),this.CONSUME3(m),this.MANY2(()=>{this.SUBRULE2(this.action,{LABEL:"elseActions"});}),this.CONSUME3(g);});});cloneRule=this.RULE("cloneRule",()=>{this.CONSUME(I),this.OPTION(()=>{this.CONSUME(m),this.MANY_SEP({SEP:N,DEF:()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"fields"});}}),this.CONSUME(g);});});setRule=this.RULE("setRule",()=>{this.CONSUME(C),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(E),this.SUBRULE(this.expression,{LABEL:"right"});});modifyRule=this.RULE("modifyRule",()=>{this.CONSUME(q),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(E),this.SUBRULE(this.expression,{LABEL:"right"});});expression=this.RULE("expression",()=>{this.SUBRULE(this.logicalOr);});logicalOr=this.RULE("logicalOr",()=>{this.SUBRULE(this.logicalAnd,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(H),this.SUBRULE1(this.logicalAnd,{LABEL:"rhs"});});});logicalAnd=this.RULE("logicalAnd",()=>{this.SUBRULE(this.comparison,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(K),this.SUBRULE1(this.comparison,{LABEL:"rhs"});});});comparison=this.RULE("comparison",()=>{this.SUBRULE(this.addition,{LABEL:"lhs"}),this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(D,{LABEL:"ops"})},{ALT:()=>this.CONSUME(W,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Y,{LABEL:"ops"})},{ALT:()=>this.CONSUME(G,{LABEL:"ops"})},{ALT:()=>this.CONSUME(J,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Q,{LABEL:"ops"})},{ALT:()=>this.CONSUME(V,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Z,{LABEL:"ops"})}]),this.SUBRULE1(this.addition,{LABEL:"rhs"});});});addition=this.RULE("addition",()=>{this.SUBRULE(this.multiplication,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(tt,{LABEL:"ops"})},{ALT:()=>this.CONSUME(b,{LABEL:"ops"})}]),this.SUBRULE1(this.multiplication,{LABEL:"rhs"});});});multiplication=this.RULE("multiplication",()=>{this.SUBRULE(this.unaryExpression,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(et,{LABEL:"ops"})},{ALT:()=>this.CONSUME(rt,{LABEL:"ops"})}]),this.SUBRULE1(this.unaryExpression,{LABEL:"rhs"});});});unaryExpression=this.RULE("unaryExpression",()=>{this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(b,{LABEL:"sign"})},{ALT:()=>this.CONSUME(X,{LABEL:"sign"})}]);}),this.SUBRULE(this.atomic);});atomic=this.RULE("atomic",()=>{this.OR([{ALT:()=>this.SUBRULE(this.literal)},{GATE:()=>this.LA(2).tokenType===m,ALT:()=>this.SUBRULE(this.functionCall)},{ALT:()=>this.SUBRULE(this.anyIdentifier)},{ALT:()=>{this.CONSUME(m),this.SUBRULE(this.expression),this.CONSUME(g);}}]);});functionCall=this.RULE("functionCall",()=>{this.OR([{ALT:()=>this.CONSUME(c,{LABEL:"name"})},{ALT:()=>this.CONSUME(v,{LABEL:"name"})}]),this.CONSUME(m),this.MANY_SEP({SEP:N,DEF:()=>{this.SUBRULE(this.expression,{LABEL:"args"});}}),this.CONSUME(g);});sectionRule=this.RULE("sectionRule",()=>{this.CONSUME(B),this.OPTION(()=>{this.CONSUME(M);}),this.SUBRULE(this.anyIdentifier,{LABEL:"sectionName"}),this.CONSUME(m),this.OPTION1(()=>{this.CONSUME(U,{LABEL:"subqueryFrom"}),this.SUBRULE(this.typeFormat,{LABEL:"subquerySourceType"}),this.CONSUME(R,{LABEL:"subqueryTo"}),this.SUBRULE1(this.typeFormat,{LABEL:"subqueryTargetType"}),this.OPTION2(()=>{this.CONSUME($,{LABEL:"subqueryTransform"});});}),this.MANY(()=>{this.SUBRULE(this.action);}),this.CONSUME(g),this.OPTION3(()=>{this.CONSUME1(U,{LABEL:"followFrom"}),this.SUBRULE2(this.anyIdentifier,{LABEL:"followPath"});});});defineRule=this.RULE("defineRule",()=>{this.CONSUME(k),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(E),this.SUBRULE(this.expression,{LABEL:"right"});})},L=new at;var ut={substring:i=>{if(i.length<2)throw new Error("substring() requires at least 2 arguments (string, start, [length])");let[t,e,r]=i;return r!==void 0?`String(${t}).slice(${e}, (${e}) + (${r}))`:`String(${t}).slice(${e})`},if:i=>{if(i.length!==3)throw new Error("if() requires exactly 3 arguments (condition, trueValue, falseValue)");let[t,e,r]=i;return `((${t}) ? (${e}) : (${r}))`},text:i=>{if(i.length!==1)throw new Error("text() requires exactly 1 argument (string or number)");let[t]=i;return `String(${t})`},replace:i=>{if(i.length!==3)throw new Error("replace() requires exactly 3 arguments (string, search, replacement)");let[t,e,r]=i;return `String(${t}).replace(${e}, ${r})`},number:i=>{if(i.length!==1)throw new Error("number() requires exactly 1 argument (string)");let[t]=i;return `Number(${t})`},extractnumber:i=>{if(i.length!==1)throw new Error("extractNumber() requires exactly 1 argument (string)");let[t]=i;return `(() => { const match = String(${t}).match(/\\d+(\\.\\d+)?/); return match ? Number(match[0]) : null; })()`},uppercase:i=>{if(i.length!==1)throw new Error("uppercase() requires exactly 1 argument (string)");let[t]=i;return `String(${t}).toUpperCase()`},lowercase:i=>{if(i.length!==1)throw new Error("lowercase() requires exactly 1 argument (string)");let[t]=i;return `String(${t}).toLowerCase()`},xmlnode:i=>{if(i.length<1)throw new Error("xmlnode() requires at least 1 argument (string)");let t=i[0],e=[...i.slice(1)],r="";if(e.length>0){let s=[...e];s=[...Array(Math.ceil(s.length/2))].map(()=>s.splice(0,2)).map(([a,o])=>{let p=a;return a.startsWith('"')||a.startsWith("'")?p=`"$${a.slice(1,-1)}"`:p=`["$"+${a}]`,`${p}:${o||"null"}`}),r=","+s.join(",");}else return t;return `{_:${t}${r}}`},split:i=>{if(i.length<1)throw new Error("split() requires at least 1 argument (string)");let[t,e,r]=i,n=e!==void 0?e:'""',s=r!==void 0?`, ${r}`:"";return `String(${t}).split(${n}${s})`},to_base64:i=>{if(i.length!==1)throw new Error("to_base64() requires exactly 1 argument (string)");let[t]=i;return `(typeof btoa === 'function' ? btoa(unescape(encodeURIComponent(String(${t})))) : Buffer.from(String(${t}), 'utf-8').toString('base64'))`},from_base64:i=>{if(i.length!==1)throw new Error("from_base64() requires exactly 1 argument (string)");let[t]=i;return `(typeof atob === 'function' ? decodeURIComponent(escape(atob(String(${t})))) : Buffer.from(String(${t}), 'base64').toString('utf-8'))`},aslist:i=>{if(i.length!==1)throw new Error("aslist() requires exactly 1 argument");let[t]=i;return `(Array.isArray(${t}) ? ${t} : (${t} == null ? [] : [${t}]))`},spreadsheet:i=>{if(i.length!==1)throw new Error("spreadsheet() requires exactly 1 argument");let[t]=i;return `((data)=>{
2
- const spreadsheet = Array.isArray(data) ? data : (data == null ? [] : [data]);
3
- const out = [];
4
- const titles = [];
5
- let keys = [];
6
- for (let i = 0; i < spreadsheet.length; i++) {
7
- const line = spreadsheet[i];
8
- if (!line || typeof line !== 'object') continue;
9
- if (i === 0) {
10
- keys = Object.keys(line);
11
- for (const k of keys) titles.push(line[k]);
12
- } else {
13
- const tempLine = {};
14
- for (let j = 0; j < keys.length; j++) {
15
- tempLine[titles[j]] = line[keys[j]];
16
- }
17
- out.push(tempLine);
18
- }
19
- }
20
- return out;
21
- })(${t})`},unpack:i=>{if(i.length<2)throw new Error("unpack() requires at least 2 arguments (string, fieldSpec1, [fieldSpec2, ...])");let[t,...e]=i;return `({ ${e.map(n=>{let s=n.replace(/^["']|["']$/g,""),a=s.split(":");if(a.length<3)throw new Error(`Invalid field spec for unpack(): ${s}. Expected "name:start:length[:modifier]"`);let[o,p,h,u]=a;if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new Error(`Invalid field name in unpack() spec: "${o}". Must be a valid JavaScript identifier.`);let y=parseInt(p,10),f=parseInt(h,10);if(isNaN(y)||isNaN(f))throw new Error(`Invalid character positions in unpack() spec: ${s}`);let d=`String(${t} || "").substring(${y}, ${y} + ${f})`;return u!=="raw"&&(d=`(${d}).trim()`),`"${o}": ${d}`}).join(", ")} })`},pack:i=>{if(i.length<2)throw new Error("pack() requires at least 2 arguments (object, fieldSpec1, [fieldSpec2, ...])");let[t,...e]=i,r=e.map(s=>{let a=s.replace(/^["']|["']$/g,""),o=a.split(":");if(o.length<3)throw new Error(`Invalid field spec for pack(): ${a}. Expected "name:start:length[:modifier]"`);let[p,h,u,y]=o;if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(p))throw new Error(`Invalid field name in pack() spec: "${p}". Must be a valid JavaScript identifier.`);let f=parseInt(h,10),d=parseInt(u,10);if(isNaN(f)||isNaN(d))throw new Error(`Invalid character positions in pack() spec: ${a}`);return {name:p,start:f,length:d,left:y==="left"}}),n=r.reduce((s,a)=>Math.max(s,a.start+a.length),0);return `((val) => {
22
- if (!val) return ' '.repeat(${n});
23
- let line = ' '.repeat(${n});
24
- ${r.map((s,a)=>{let o=`String(val["${s.name}"] ?? "")`,p=s.left?`(${o}).padStart(${s.length})`:`(${o}).padEnd(${s.length})`;return `
25
- const v${a} = (${p}).substring(0, ${s.length});
26
- line = line.substring(0, ${s.start}) + v${a} + line.substring(${s.start} + ${s.length});`}).join("")}
27
- return line;
28
- })(${t})`}};var S=class{sourceRoot={type:"object",properties:{}};targetRoot={type:"object",properties:{}};sourceStack=[this.sourceRoot];targetStack=[this.targetRoot];getCurrentSource(){return this.sourceStack[this.sourceStack.length-1]}getCurrentTarget(){return this.targetStack[this.targetStack.length-1]}recordAccess(t,e="any",r=false){let n=r?this.getCurrentTarget():this.getCurrentSource();this.setInNode(n,t,e);}recordAssignment(t,e="any"){this.setInNode(this.getCurrentTarget(),t,e);}recordClone(t){let e=this.getCurrentTarget();t?t.forEach(r=>{this.setInNode(this.getCurrentSource(),r,"any"),this.setInNode(e,r,"any");}):e.isOpen=true;}recordDelete(t){let e=this.getCurrentTarget();this.deleteInNode(e,t);}pushSection(t,e,r){e!=="parent"&&this.setInNode(this.getCurrentSource(),e,r?"array":"object");let n={type:r?"array":"object"};r?n.items={type:"object",properties:{}}:n.properties={};let s={type:"object",properties:{}};this.setInNodeExplicit(this.getCurrentTarget(),t,n),this.targetStack.push(r?n.items:n),this.sourceStack.push(s);}popSection(t,e){let r=this.sourceStack.pop();this.targetStack.pop();let n=this.getCurrentSource();if(t!=="parent"){let s=this.getOrSetNode(n,t,e?"array":"object"),a=e?s.items:s;a&&(a.properties||(a.properties={}),Object.assign(a.properties,r.properties||{}));}else n.properties||(n.properties={}),Object.assign(n.properties,r.properties||{});}setInNode(t,e,r){let n=e.split("."),s=t;for(let a=0;a<n.length;a++){let o=n[a];s.properties||(s.properties={}),a===n.length-1?s.properties[o]||(s.properties[o]={type:r},r==="object"?s.properties[o].properties={}:r==="array"&&(s.properties[o].items={type:"object",properties:{}})):(s.properties[o]||(s.properties[o]={type:"object",properties:{}}),s=s.properties[o]);}}setInNodeExplicit(t,e,r){let n=e.split("."),s=t;for(let a=0;a<n.length;a++){let o=n[a];s.properties||(s.properties={}),a===n.length-1?s.properties[o]=r:(s.properties[o]||(s.properties[o]={type:"object",properties:{}}),s=s.properties[o]);}}deleteInNode(t,e){let r=e.split("."),n=t;for(let s=0;s<r.length;s++){if(!n.properties)return;if(s===r.length-1)delete n.properties[r[s]];else if(n=n.properties[r[s]],!n)return}}getOrSetNode(t,e,r){let n=e.split("."),s=t;for(let a=0;a<n.length;a++){let o=n[a],h=a===n.length-1?r:"object";s.properties||(s.properties={}),s.properties[o]||(s.properties[o]={type:h},h==="object"?s.properties[o].properties={}:h==="array"&&(s.properties[o].items={type:"object",properties:{}})),s=s.properties[o];}return s}getResult(){return {source:this.sourceRoot,target:this.targetRoot}}};var Nt=L.getBaseCstVisitorConstructor(),ot=class extends Nt{readFrom="source";scopeStack=[];safeMode=true;isAnalyzing=false;tracker=new S;lastInferredType="any";constructor(){super(),this.validateVisitor();}reset(){this.readFrom="source",this.scopeStack=[],this.tracker=new S,this.lastInferredType="any";}visitWithContext(t,e){let r=this.readFrom;this.readFrom=e.readFrom;try{return this.visit(t)}finally{this.readFrom=r;}}query(t){this.reset(),this.isAnalyzing&&(this.tracker=new S);let e=this.visit(t.sourceType),r=this.visit(t.targetType),n=!!t.Unsafe;this.safeMode=!n,this.scopeStack.push({format:r.name,options:r.options,isSerializationScope:true});try{let s=t.action?t.action.map(f=>this.visit(f)):[];t.Transform||s.push("Object.assign(target, source);");let a=e.name,o=r.name,p=JSON.stringify(e.options),h=JSON.stringify(r.options),u=s.some(f=>typeof f=="string"&&f.trim().startsWith("return "));return {code:`
1
+ 'use strict';var chevrotain=require('chevrotain'),fastXmlParser=require('fast-xml-parser'),de=require('papaparse'),Me=require('js-beautify');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var de__default=/*#__PURE__*/_interopDefault(de);var Me__default=/*#__PURE__*/_interopDefault(Me);var Ne=chevrotain.createToken({name:"WhiteSpace",pattern:/\s+/,group:chevrotain.Lexer.SKIPPED}),Te=chevrotain.createToken({name:"LineComment",pattern:/\/\/[^\n\r]*/,group:chevrotain.Lexer.SKIPPED}),Re=chevrotain.createToken({name:"BlockComment",pattern:/\/\*[\s\S]*?\*\//,group:chevrotain.Lexer.SKIPPED}),m=chevrotain.createToken({name:"Identifier",pattern:/[a-zA-Z_$][a-zA-Z0-9_.[\]]*/}),w=chevrotain.createToken({name:"QuotedIdentifier",pattern:/`([^`\\]|\\.)*`/}),$=chevrotain.createToken({name:"From",pattern:/from/i,longer_alt:m}),v=chevrotain.createToken({name:"To",pattern:/to/i,longer_alt:m}),C=chevrotain.createToken({name:"Transform",pattern:/transform/i,longer_alt:m}),I=chevrotain.createToken({name:"Set",pattern:/set/i,longer_alt:m}),k=chevrotain.createToken({name:"Section",pattern:/section/i,longer_alt:m}),q=chevrotain.createToken({name:"Multiple",pattern:/multiple/i,longer_alt:m}),P=chevrotain.createToken({name:"Clone",pattern:/clone/i,longer_alt:m}),_=chevrotain.createToken({name:"Delete",pattern:/delete/i,longer_alt:m}),j=chevrotain.createToken({name:"Define",pattern:/define/i,longer_alt:m}),x=chevrotain.createToken({name:"Modify",pattern:/modify/i,longer_alt:m}),B=chevrotain.createToken({name:"If",pattern:/if/i,longer_alt:m}),z=chevrotain.createToken({name:"Else",pattern:/else/i,longer_alt:m}),F=chevrotain.createToken({name:"True",pattern:/true/i,longer_alt:m}),W=chevrotain.createToken({name:"False",pattern:/false/i,longer_alt:m}),D=chevrotain.createToken({name:"Null",pattern:/null/i,longer_alt:m}),Y=chevrotain.createToken({name:"Return",pattern:/return/i,longer_alt:m}),J=chevrotain.createToken({name:"Unsafe",pattern:/unsafe/i,longer_alt:m}),G=chevrotain.createToken({name:"Where",pattern:/where/i,longer_alt:m}),Q=chevrotain.createToken({name:"EqualsEquals",pattern:/==/}),V=chevrotain.createToken({name:"EqualsEqualsEquals",pattern:/===/}),Z=chevrotain.createToken({name:"NotEquals",pattern:/!=/}),K=chevrotain.createToken({name:"NotEqualsEquals",pattern:/!==/}),H=chevrotain.createToken({name:"LessThanOrEqual",pattern:/<=/}),X=chevrotain.createToken({name:"GreaterThanOrEqual",pattern:/>=/}),ee=chevrotain.createToken({name:"LessThan",pattern:/</}),te=chevrotain.createToken({name:"GreaterThan",pattern:/>/}),re=chevrotain.createToken({name:"And",pattern:/&&/}),se=chevrotain.createToken({name:"Or",pattern:/\|\|/}),ne=chevrotain.createToken({name:"Not",pattern:/!/}),U=chevrotain.createToken({name:"Equals",pattern:/=/}),ie=chevrotain.createToken({name:"Plus",pattern:/\+/}),M=chevrotain.createToken({name:"Minus",pattern:/-/}),ae=chevrotain.createToken({name:"Times",pattern:/\*/}),oe=chevrotain.createToken({name:"Divide",pattern:/\//}),S=chevrotain.createToken({name:"LParen",pattern:/\(/}),A=chevrotain.createToken({name:"RParen",pattern:/\)/}),b=chevrotain.createToken({name:"Comma",pattern:/,/}),le=chevrotain.createToken({name:"StringLiteral",pattern:/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/}),ce=chevrotain.createToken({name:"NumericLiteral",pattern:/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/}),pe=[Ne,Te,Re,$,v,C,I,k,q,P,_,j,x,B,z,F,W,D,Y,J,G,V,Q,K,Z,H,X,re,se,U,ee,te,ne,ie,M,ae,oe,S,A,b,le,ce,w,m],ge=new chevrotain.Lexer(pe);var ue=class extends chevrotain.CstParser{constructor(){super(pe),this.performSelfAnalysis();}query=this.RULE("query",()=>{this.CONSUME($),this.SUBRULE(this.typeFormat,{LABEL:"sourceType"}),this.CONSUME(v),this.SUBRULE1(this.typeFormat,{LABEL:"targetType"}),this.OPTION(()=>{this.CONSUME(C),this.OPTION1(()=>{this.CONSUME(J);}),this.MANY(()=>{this.SUBRULE(this.action);});});});typeFormat=this.RULE("typeFormat",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"name"}),this.OPTION(()=>{this.CONSUME(S),this.MANY_SEP({SEP:b,DEF:()=>{this.SUBRULE(this.typeFormatParameter,{LABEL:"params"});}}),this.CONSUME(A);});});typeFormatParameter=this.RULE("typeFormatParameter",()=>{this.OR([{GATE:()=>this.LA(2).tokenType===U,ALT:()=>this.SUBRULE(this.namedParameter)},{ALT:()=>this.SUBRULE(this.literal)}]);});namedParameter=this.RULE("namedParameter",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"key"}),this.CONSUME(U),this.SUBRULE(this.literal,{LABEL:"value"});});anyIdentifier=this.RULE("anyIdentifier",()=>{this.OR([{ALT:()=>this.CONSUME(m)},{ALT:()=>this.CONSUME(w)}]);});literal=this.RULE("literal",()=>{this.OR([{ALT:()=>this.CONSUME(le)},{ALT:()=>this.CONSUME(ce)},{ALT:()=>this.CONSUME(F)},{ALT:()=>this.CONSUME(W)},{ALT:()=>this.CONSUME(D)}]);});action=this.RULE("action",()=>{this.OR([{ALT:()=>this.SUBRULE(this.setRule)},{ALT:()=>this.SUBRULE(this.modifyRule)},{ALT:()=>this.SUBRULE(this.sectionRule)},{ALT:()=>this.SUBRULE(this.cloneRule)},{ALT:()=>this.SUBRULE(this.deleteRule)},{ALT:()=>this.SUBRULE(this.ifAction)},{ALT:()=>this.SUBRULE(this.defineRule)},{ALT:()=>this.SUBRULE(this.returnRule)}]);});returnRule=this.RULE("returnRule",()=>{this.CONSUME(Y),this.SUBRULE(this.expression,{LABEL:"expr"});});deleteRule=this.RULE("deleteRule",()=>{this.CONSUME(_),this.SUBRULE(this.anyIdentifier,{LABEL:"field"});});ifAction=this.RULE("ifAction",()=>{this.CONSUME(B),this.CONSUME(S),this.SUBRULE(this.expression,{LABEL:"condition"}),this.CONSUME(A),this.CONSUME2(S),this.MANY(()=>{this.SUBRULE(this.action,{LABEL:"thenActions"});}),this.CONSUME2(A),this.OPTION(()=>{this.CONSUME(z),this.CONSUME3(S),this.MANY2(()=>{this.SUBRULE2(this.action,{LABEL:"elseActions"});}),this.CONSUME3(A);});});cloneRule=this.RULE("cloneRule",()=>{this.CONSUME(P),this.OPTION(()=>{this.CONSUME(S),this.MANY_SEP({SEP:b,DEF:()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"fields"});}}),this.CONSUME(A);});});setRule=this.RULE("setRule",()=>{this.CONSUME(I),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(U),this.SUBRULE(this.expression,{LABEL:"right"});});modifyRule=this.RULE("modifyRule",()=>{this.CONSUME(x),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(U),this.SUBRULE(this.expression,{LABEL:"right"});});expression=this.RULE("expression",()=>{this.SUBRULE(this.logicalOr);});logicalOr=this.RULE("logicalOr",()=>{this.SUBRULE(this.logicalAnd,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(se),this.SUBRULE1(this.logicalAnd,{LABEL:"rhs"});});});logicalAnd=this.RULE("logicalAnd",()=>{this.SUBRULE(this.comparison,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(re),this.SUBRULE1(this.comparison,{LABEL:"rhs"});});});comparison=this.RULE("comparison",()=>{this.SUBRULE(this.addition,{LABEL:"lhs"}),this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(Q,{LABEL:"ops"})},{ALT:()=>this.CONSUME(V,{LABEL:"ops"})},{ALT:()=>this.CONSUME(Z,{LABEL:"ops"})},{ALT:()=>this.CONSUME(K,{LABEL:"ops"})},{ALT:()=>this.CONSUME(H,{LABEL:"ops"})},{ALT:()=>this.CONSUME(X,{LABEL:"ops"})},{ALT:()=>this.CONSUME(ee,{LABEL:"ops"})},{ALT:()=>this.CONSUME(te,{LABEL:"ops"})}]),this.SUBRULE1(this.addition,{LABEL:"rhs"});});});addition=this.RULE("addition",()=>{this.SUBRULE(this.multiplication,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(ie,{LABEL:"ops"})},{ALT:()=>this.CONSUME(M,{LABEL:"ops"})}]),this.SUBRULE1(this.multiplication,{LABEL:"rhs"});});});multiplication=this.RULE("multiplication",()=>{this.SUBRULE(this.unaryExpression,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(ae,{LABEL:"ops"})},{ALT:()=>this.CONSUME(oe,{LABEL:"ops"})}]),this.SUBRULE1(this.unaryExpression,{LABEL:"rhs"});});});unaryExpression=this.RULE("unaryExpression",()=>{this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(M,{LABEL:"sign"})},{ALT:()=>this.CONSUME(ne,{LABEL:"sign"})}]);}),this.SUBRULE(this.atomic);});atomic=this.RULE("atomic",()=>{this.OR([{ALT:()=>this.SUBRULE(this.literal)},{GATE:()=>this.LA(2).tokenType===S,ALT:()=>this.SUBRULE(this.functionCall)},{ALT:()=>this.SUBRULE(this.anyIdentifier)},{ALT:()=>{this.CONSUME(S),this.SUBRULE(this.expression),this.CONSUME(A);}}]);});functionCall=this.RULE("functionCall",()=>{this.OR([{ALT:()=>this.CONSUME(m,{LABEL:"name"})},{ALT:()=>this.CONSUME(B,{LABEL:"name"})}]),this.CONSUME(S),this.MANY_SEP({SEP:b,DEF:()=>{this.SUBRULE(this.expression,{LABEL:"args"});}}),this.CONSUME(A);});sectionRule=this.RULE("sectionRule",()=>{this.CONSUME(k),this.OPTION(()=>{this.CONSUME(q);}),this.SUBRULE(this.anyIdentifier,{LABEL:"sectionName"}),this.CONSUME(S),this.OPTION1(()=>{this.CONSUME($,{LABEL:"subqueryFrom"}),this.SUBRULE(this.typeFormat,{LABEL:"subquerySourceType"}),this.CONSUME(v,{LABEL:"subqueryTo"}),this.SUBRULE1(this.typeFormat,{LABEL:"subqueryTargetType"}),this.OPTION2(()=>{this.CONSUME(C,{LABEL:"subqueryTransform"});});}),this.MANY(()=>{this.SUBRULE(this.action);}),this.CONSUME(A),this.OPTION3(()=>{this.CONSUME1($,{LABEL:"followFrom"}),this.SUBRULE(this.expression,{LABEL:"followExpr"});}),this.OPTION4(()=>{this.CONSUME(G,{LABEL:"whereClause"}),this.SUBRULE1(this.expression,{LABEL:"whereExpr"});});});defineRule=this.RULE("defineRule",()=>{this.CONSUME(j),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(U),this.SUBRULE(this.expression,{LABEL:"right"});})},N=new ue;var ye={substring:r=>{if(r.length<2)throw new Error("substring() requires at least 2 arguments (string, start, [length])");let[e,t,s]=r;return s!==void 0?`String(${e}).slice(${t}, (${t}) + (${s}))`:`String(${e}).slice(${t})`},if:r=>{if(r.length!==3)throw new Error("if() requires exactly 3 arguments (condition, trueValue, falseValue)");let[e,t,s]=r;return `((${e}) ? (${t}) : (${s}))`},text:r=>{if(r.length!==1)throw new Error("text() requires exactly 1 argument (string or number)");let[e]=r;return `String(${e})`},replace:r=>{if(r.length!==3)throw new Error("replace() requires exactly 3 arguments (string, search, replacement)");let[e,t,s]=r;return `String(${e}).replace(${t}, ${s})`},number:r=>{if(r.length!==1)throw new Error("number() requires exactly 1 argument (string)");let[e]=r;return `Number(${e})`},extractnumber:r=>{if(r.length!==1)throw new Error("extractNumber() requires exactly 1 argument (string)");let[e]=r;return `(() => { const match = String(${e}).match(/\\d+(\\.\\d+)?/); return match ? Number(match[0]) : null; })()`},uppercase:r=>{if(r.length!==1)throw new Error("uppercase() requires exactly 1 argument (string)");let[e]=r;return `String(${e}).toUpperCase()`},lowercase:r=>{if(r.length!==1)throw new Error("lowercase() requires exactly 1 argument (string)");let[e]=r;return `String(${e}).toLowerCase()`},xmlnode:r=>{if(r.length<1)throw new Error("xmlnode() requires at least 1 argument (string)");let[e,...t]=r,s=t.join(", ");return `env.functions.xmlnode(${e}${s?", "+s:""})`},split:r=>{if(r.length<1)throw new Error("split() requires at least 1 argument (string)");let[e,t,s]=r,i=t!==void 0?t:'""',n=s!==void 0?`, ${s}`:"";return `String(${e}).split(${i}${n})`},to_base64:r=>{if(r.length!==1)throw new Error("to_base64() requires exactly 1 argument (string)");let[e]=r;return `env.functions.to_base64(${e})`},from_base64:r=>{if(r.length!==1)throw new Error("from_base64() requires exactly 1 argument (string)");let[e]=r;return `env.functions.from_base64(${e})`},aslist:r=>{if(r.length!==1)throw new Error("aslist() requires exactly 1 argument");let[e]=r;return `env.functions.aslist(${e})`},spreadsheet:r=>{if(r.length!==1)throw new Error("spreadsheet() requires exactly 1 argument");let[e]=r;return `env.functions.spreadsheet(${e})`},unpack:r=>{if(r.length<2)throw new Error("unpack() requires at least 2 arguments (string, fieldSpec1, [fieldSpec2, ...])");let[e,...t]=r;t.forEach(i=>{let n=i.replace(/^["']|["']$/g,""),a=n.split(":");if(a.length<3)throw new Error(`Invalid field spec for unpack(): ${n}. Expected "name:start:length[:modifier]"`);let[o,p,u]=a;if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new Error(`Invalid field name in unpack() spec: "${o}". Must be a valid JavaScript identifier.`);let f=parseInt(p,10),l=parseInt(u,10);if(isNaN(f)||isNaN(l))throw new Error(`Invalid character positions in unpack() spec: ${n}`)});let s=t.join(", ");return `env.functions.unpack(${e}, ${s})`},pack:r=>{if(r.length<2)throw new Error("pack() requires at least 2 arguments (object, fieldSpec1, [fieldSpec2, ...])");let[e,...t]=r;t.forEach(i=>{let n=i.replace(/^["']|["']$/g,""),a=n.split(":");if(a.length<3)throw new Error(`Invalid field spec for pack(): ${n}. Expected "name:start:length[:modifier]"`);let[o,p,u]=a;if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new Error(`Invalid field name in pack() spec: "${o}". Must be a valid JavaScript identifier.`);let f=parseInt(p,10),l=parseInt(u,10);if(isNaN(f)||isNaN(l))throw new Error(`Invalid character positions in pack() spec: ${n}`)});let s=t.join(", ");return `env.functions.pack(${e}, ${s})`},concat:r=>`env.functions.concat(${r.join(", ")})`,transpose:r=>{if(r.length<2)throw new Error("transpose() requires at least 2 arguments (source, key1, [key2, ...])");return `env.functions.transpose(${r.join(", ")})`}};var R=class{sourceRoot={type:"object",properties:{}};targetRoot={type:"object",properties:{}};sourceStack=[this.sourceRoot];targetStack=[this.targetRoot];getCurrentSource(){return this.sourceStack[this.sourceStack.length-1]}getCurrentTarget(){return this.targetStack[this.targetStack.length-1]}recordAccess(e,t="any",s=false){let i=s?this.getCurrentTarget():this.getCurrentSource();this.setInNode(i,e,t);}recordAssignment(e,t="any"){this.setInNode(this.getCurrentTarget(),e,t);}recordClone(e){let t=this.getCurrentTarget();e?e.forEach(s=>{this.setInNode(this.getCurrentSource(),s,"any"),this.setInNode(t,s,"any");}):t.isOpen=true;}recordDelete(e){let t=this.getCurrentTarget();this.deleteInNode(t,e);}pushSection(e,t,s){t!=="parent"&&this.setInNode(this.getCurrentSource(),t,s?"array":"object");let i={type:s?"array":"object"};s?i.items={type:"object",properties:{}}:i.properties={};let n={type:"object",properties:{}};this.setInNodeExplicit(this.getCurrentTarget(),e,i),this.targetStack.push(s?i.items:i),this.sourceStack.push(n);}popSection(e,t){let s=this.sourceStack.pop();this.targetStack.pop();let i=this.getCurrentSource();if(e!=="parent"){let n=this.getOrSetNode(i,e,t?"array":"object"),a=t?n.items:n;a&&(a.properties||(a.properties={}),Object.assign(a.properties,s.properties||{}));}else i.properties||(i.properties={}),Object.assign(i.properties,s.properties||{});}setInNode(e,t,s){let i=t.split("."),n=e;for(let a=0;a<i.length;a++){let o=i[a];n.properties||(n.properties={}),a===i.length-1?(!n.properties[o]||n.properties[o].type==="any")&&(n.properties[o]={type:s},s==="object"?n.properties[o].properties={}:s==="array"&&(n.properties[o].items={type:"object",properties:{}})):(n.properties[o]||(n.properties[o]={type:"object",properties:{}}),n=n.properties[o]);}}setInNodeExplicit(e,t,s){let i=t.split("."),n=e;for(let a=0;a<i.length;a++){let o=i[a];n.properties||(n.properties={}),a===i.length-1?n.properties[o]=s:(n.properties[o]||(n.properties[o]={type:"object",properties:{}}),n=n.properties[o]);}}deleteInNode(e,t){let s=t.split("."),i=e;for(let n=0;n<s.length;n++){if(!i.properties)return;if(n===s.length-1)delete i.properties[s[n]];else if(i=i.properties[s[n]],!i)return}}getOrSetNode(e,t,s){let i=t.split("."),n=e;for(let a=0;a<i.length;a++){let o=i[a],u=a===i.length-1?s:"object";n.properties||(n.properties={}),n.properties[o]||(n.properties[o]={type:u},u==="object"?n.properties[o].properties={}:u==="array"&&(n.properties[o].items={type:"object",properties:{}})),n=n.properties[o];}return n}getResult(){return {source:this.sourceRoot,target:this.targetRoot}}};var Oe=N.getBaseCstVisitorConstructor(),he=class extends Oe{readFrom="source";scopeStack=[];safeMode=true;isAnalyzing=false;tracker=new R;lastInferredType="any";constructor(){super(),this.validateVisitor();}reset(){this.readFrom="source",this.scopeStack=[],this.tracker=new R,this.lastInferredType="any";}visitWithContext(e,t){let s=this.readFrom;this.readFrom=t.readFrom;try{return this.visit(e)}finally{this.readFrom=s;}}query(e){this.reset(),this.isAnalyzing&&(this.tracker=new R);let t=this.visit(e.sourceType),s=this.visit(e.targetType),i=!!e.Unsafe;this.safeMode=!i,this.scopeStack.push({format:s.name,options:s.options,isSerializationScope:true});try{let n=e.action?e.action.map(h=>this.visit(h)):[];e.Transform||n.push("Object.assign(target, source);");let a=t.name,o=s.name,p=JSON.stringify(t.options),u=JSON.stringify(s.options),f=n.some(h=>typeof h=="string"&&h.trim().startsWith("return "));return {code:`
29
2
  return function(input, env) {
30
3
  // 1. Parse Input
31
4
  const source = env.parse('${a}', input, ${p});
@@ -34,42 +7,56 @@
34
7
  // 2. Transform
35
8
  const target = {};
36
9
  const _rootTarget = target;
37
- ${s.join(`
10
+ ${n.join(`
38
11
  `)}
39
12
 
40
13
  // 3. Serialize Output
41
- ${u?"":`return env.serialize('${o}', target, ${h});`}
14
+ ${f?"":`return env.serialize('${o}', target, ${u});`}
42
15
  }
43
- `,sourceType:e,targetType:r,analysis:this.isAnalyzing?this.tracker.getResult():void 0}}finally{this.scopeStack.pop();}}typeFormat(t){let e=this.visit(t.name),r={params:[]};return t.params&&t.params.forEach(n=>{let s=this.visit(n);typeof s=="object"&&"key"in s?r[s.key]=this.parseLiteral(s.value):r.params.push(this.parseLiteral(s));}),{name:e.name,options:r}}typeFormatParameter(t){if(t.namedParameter)return this.visit(t.namedParameter);if(t.literal)return this.visit(t.literal)}namedParameter(t){let e=this.visit(t.key).name,r=this.visit(t.value);return {key:e,value:r}}parseLiteral(t){if(t==="true")return true;if(t==="false")return false;if(t==="null")return null;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);let e=Number(t);return isNaN(e)?t:e}genAccess(t,e,r=false){let n=this.safeMode&&!r?"?.":".";return e.quoted||e.name.includes("-")&&!e.name.includes(".")&&!e.name.includes("[")?`${t}${this.safeMode&&!r?"?.":""}["${e.name}"]`:`${t}${n}${e.name}`}anyIdentifier(t){if(t.Identifier)return {name:t.Identifier[0].image,quoted:false};if(t.QuotedIdentifier)return {name:t.QuotedIdentifier[0].image.slice(1,-1).replace(/\\(.)/g,"$1"),quoted:true}}literal(t){if(t.StringLiteral)return this.lastInferredType="string",t.StringLiteral[0].image;if(t.NumericLiteral)return this.lastInferredType="number",t.NumericLiteral[0].image;if(t.True)return this.lastInferredType="boolean","true";if(t.False)return this.lastInferredType="boolean","false";if(t.Null)return this.lastInferredType="null","null"}action(t){if(t.setRule)return this.visit(t.setRule);if(t.modifyRule)return this.visit(t.modifyRule);if(t.sectionRule)return this.visit(t.sectionRule);if(t.cloneRule)return this.visit(t.cloneRule);if(t.ifAction)return this.visit(t.ifAction);if(t.deleteRule)return this.visit(t.deleteRule);if(t.defineRule)return this.visit(t.defineRule);if(t.returnRule)return this.visit(t.returnRule)}deleteRule(t){let e=this.visit(t.field);return this.isAnalyzing&&this.tracker.recordDelete(e.name),`delete ${this.genAccess("target",e,true)};`}ifAction(t){let e=this.visit(t.condition),r=t.thenActions?t.thenActions.map(s=>this.visit(s)).join(`
44
- `):"",n=t.elseActions?`else { ${t.elseActions.map(s=>this.visit(s)).join(`
45
- `)} }`:"";return `if (${e}) {
46
- ${r}
47
- } ${n}`}cloneRule(t){if(t.fields){let e=t.fields.map(r=>this.visit(r));return this.isAnalyzing&&this.tracker.recordClone(e.map(r=>r.name)),e.map(r=>`${this.genAccess("target",r,true)} = ${this.genAccess("source",r)};`).join(`
48
- `)}return this.isAnalyzing&&this.tracker.recordClone(),"Object.assign(target, source);"}setRule(t){let e=this.visit(t.left);this.lastInferredType="any";let r=this.visit(t.right);return this.isAnalyzing&&this.tracker.recordAssignment(e.name,this.lastInferredType),`${this.genAccess("target",e,true)} = ${r};`}modifyRule(t){let e=this.visit(t.left);this.lastInferredType="any";let r=this.visitWithContext(t.right,{readFrom:"target"});return this.isAnalyzing&&this.tracker.recordAssignment(e.name,this.lastInferredType),`${this.genAccess("target",e,true)} = ${r};`}defineRule(t){let e=this.visit(t.left);this.lastInferredType="any";let r=this.visit(t.right);return this.isAnalyzing&&this.tracker.recordAssignment(e.name,this.lastInferredType),`${this.genAccess("source",e,true)} = ${r};`}returnRule(t){let e=this.visitWithContext(t.expr,{readFrom:"target"}),r=this.scopeStack[this.scopeStack.length-1];if(r&&r.isSerializationScope){let n=JSON.stringify(r.options);return `return env.serialize('${r.format}', ${e}, ${n});`}return `return ${e};`}expression(t){return this.visit(t.logicalOr)}logicalOr(t){let e=this.visit(t.lhs);if(t.rhs&&t.rhs.length>0){this.lastInferredType="boolean";for(let r=0;r<t.rhs.length;r++){let n=this.visit(t.rhs[r]);e=`${e} || ${n}`;}}return e}logicalAnd(t){let e=this.visit(t.lhs);if(t.rhs&&t.rhs.length>0){this.lastInferredType="boolean";for(let r=0;r<t.rhs.length;r++){let n=this.visit(t.rhs[r]);e=`${e} && ${n}`;}}return e}comparison(t){let e=this.visit(t.lhs);if(t.rhs){this.lastInferredType="boolean";let r=t.ops[0].image,n=this.visit(t.rhs[0]);e=`${e} ${r} ${n}`;}return e}addition(t){let e=this.visit(t.lhs),r=this.lastInferredType,n=e;if(t.rhs&&t.rhs.length>0){let s=r==="string",a=r==="number";for(let o=0;o<t.rhs.length;o++){let p=t.ops[o].image,h=this.visit(t.rhs[o]);this.lastInferredType==="string"&&(s=true),this.lastInferredType!=="number"&&(a=false),n=`${n} ${p} ${h}`;}s?this.lastInferredType="string":a?this.lastInferredType="number":this.lastInferredType="any";}else this.lastInferredType=r;return n}multiplication(t){let e=this.visit(t.lhs);if(t.rhs&&t.rhs.length>0){this.lastInferredType="number";for(let r=0;r<t.rhs.length;r++){let n=t.ops[r].image,s=this.visit(t.rhs[r]);e=`${e} ${n} ${s}`;}}return e}unaryExpression(t){let e=this.visit(t.atomic);if(t.sign){let r=t.sign[0].image;return r==="!"&&(this.lastInferredType="boolean"),r==="-"&&(this.lastInferredType="number"),`${r}${e}`}return e}atomic(t){if(t.literal)return this.visit(t.literal);if(t.functionCall)return this.visit(t.functionCall);if(t.anyIdentifier){this.lastInferredType="any";let e=this.visit(t.anyIdentifier);if(["true","false","null"].includes(e.name)&&!e.quoted)return e.name;if(!e.quoted){if(e.name.startsWith("source.")||e.name.startsWith("source["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7),"any",false),e.name;if(e.name.startsWith("target.")||e.name.startsWith("target["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7),"any",true),e.name;if(e.name==="target")return "target";if(e.name==="source")return "source";if(e.name==="_source"||e.name.startsWith("_source.")||e.name.startsWith("_source["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7)||"","any",false),`_rootSource${e.name.substring(7)}`;if(e.name==="_target"||e.name.startsWith("_target.")||e.name.startsWith("_target["))return this.isAnalyzing&&this.tracker.recordAccess(e.name.substring(7)||"","any",true),`_rootTarget${e.name.substring(7)}`}return this.isAnalyzing&&this.tracker.recordAccess(e.name,"any",this.readFrom==="target"),this.genAccess(this.readFrom,e)}if(t.expression)return `(${this.visit(t.expression)})`}functionCall(t){let e=t.name[0].image,r=(e.startsWith("`")?e.slice(1,-1):e).toLowerCase(),n=t.args?t.args.map(a=>this.visit(a)):[],s=ut[r];if(s)return ["substring","text","replace","uppercase","lowercase","to_base64","from_base64"].includes(r)?this.lastInferredType="string":["number","extractnumber"].includes(r)?this.lastInferredType="number":["aslist"].includes(r)?this.lastInferredType="array":r==="asobject"&&(this.lastInferredType="object"),s(n);throw new Error(`Unknown function: ${e}`)}sectionRule(t){let e=this.visit(t.sectionName),r=e.name,n=this.genAccess("target",e,true),s=t.followPath?this.visit(t.followPath):e,a=s.name==="parent"?"source":this.genAccess("source",s),o=!!t.Multiple;if(!!t.subqueryFrom){let h=this.visit(t.subquerySourceType),u=this.visit(t.subqueryTargetType);this.scopeStack.push({format:u.name,options:u.options,isSerializationScope:true});try{let y=!!t.subqueryTransform,f=t.action?t.action.map(yt=>this.visit(yt)):[];y||f.push("Object.assign(target, source);");let d=JSON.stringify(h.options),ht=JSON.stringify(u.options);return o?`
49
- if (${a} && Array.isArray(${a})) {
50
- ${n} = ${a}.map(item => {
51
- const subSource = env.parse('${h.name}', item, ${d});
16
+ `,sourceType:t,targetType:s,analysis:this.isAnalyzing?this.tracker.getResult():void 0}}finally{this.scopeStack.pop();}}typeFormat(e){let t=this.visit(e.name),s={params:[]};return e.params&&e.params.forEach(i=>{let n=this.visit(i);typeof n=="object"&&"key"in n?s[n.key]=this.parseLiteral(n.value):s.params.push(this.parseLiteral(n));}),{name:t.name,options:s}}typeFormatParameter(e){if(e.namedParameter)return this.visit(e.namedParameter);if(e.literal)return this.visit(e.literal)}namedParameter(e){let t=this.visit(e.key).name,s=this.visit(e.value);return {key:t,value:s}}parseLiteral(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let t=Number(e);return isNaN(t)?e:t}safify(e){return this.safeMode?e.replace(/\.(?!\?)/g,"?.").replace(/\[/g,"?.["):e}genAccess(e,t,s=false){if(!this.safeMode||s)return t.quoted||t.name.includes("-")&&!t.name.includes(".")&&!t.name.includes("[")?`${e}["${t.name}"]`:`${e}.${t.name}`;if(t.quoted)return `${e}?.[${JSON.stringify(t.name)}]`;let i=this.safify(t.name);return `${e}?.${i}`}anyIdentifier(e){if(e.Identifier)return {name:e.Identifier[0].image,quoted:false};if(e.QuotedIdentifier)return {name:e.QuotedIdentifier[0].image.slice(1,-1).replace(/\\(.)/g,"$1"),quoted:true}}literal(e){if(e.StringLiteral)return this.lastInferredType="string",e.StringLiteral[0].image;if(e.NumericLiteral)return this.lastInferredType="number",e.NumericLiteral[0].image;if(e.True)return this.lastInferredType="boolean","true";if(e.False)return this.lastInferredType="boolean","false";if(e.Null)return this.lastInferredType="null","null"}action(e){if(e.setRule)return this.visit(e.setRule);if(e.modifyRule)return this.visit(e.modifyRule);if(e.sectionRule)return this.visit(e.sectionRule);if(e.cloneRule)return this.visit(e.cloneRule);if(e.ifAction)return this.visit(e.ifAction);if(e.deleteRule)return this.visit(e.deleteRule);if(e.defineRule)return this.visit(e.defineRule);if(e.returnRule)return this.visit(e.returnRule)}deleteRule(e){let t=this.visit(e.field);return this.isAnalyzing&&this.tracker.recordDelete(t.name),`delete ${this.genAccess("target",t,true)};`}ifAction(e){let t=this.visit(e.condition),s=e.thenActions?e.thenActions.map(n=>this.visit(n)).join(`
17
+ `):"",i=e.elseActions?`else { ${e.elseActions.map(n=>this.visit(n)).join(`
18
+ `)} }`:"";return `if (${t}) {
19
+ ${s}
20
+ } ${i}`}cloneRule(e){if(e.fields){let t=e.fields.map(s=>this.visit(s));return this.isAnalyzing&&this.tracker.recordClone(t.map(s=>s.name)),t.map(s=>`${this.genAccess("target",s,true)} = ${this.genAccess("source",s)};`).join(`
21
+ `)}return this.isAnalyzing&&this.tracker.recordClone(),"Object.assign(target, source);"}setRule(e){let t=this.visit(e.left);this.lastInferredType="any";let s=this.visit(e.right);return this.isAnalyzing&&this.tracker.recordAssignment(t.name,this.lastInferredType),`${this.genAccess("target",t,true)} = ${s};`}modifyRule(e){let t=this.visit(e.left);this.lastInferredType="any";let s=this.visitWithContext(e.right,{readFrom:"target"});return this.isAnalyzing&&this.tracker.recordAssignment(t.name,this.lastInferredType),`${this.genAccess("target",t,true)} = ${s};`}defineRule(e){let t=this.visit(e.left);this.lastInferredType="any";let s=this.visit(e.right);return this.isAnalyzing&&this.tracker.recordAssignment(t.name,this.lastInferredType),`${this.genAccess("source",t,true)} = ${s};`}returnRule(e){let t=this.visitWithContext(e.expr,{readFrom:"target"}),s=this.scopeStack[this.scopeStack.length-1];if(s&&s.isSerializationScope){let i=JSON.stringify(s.options);return `return env.serialize('${s.format}', ${t}, ${i});`}return `return ${t};`}expression(e){return this.visit(e.logicalOr)}logicalOr(e){let t=this.visit(e.lhs);if(e.rhs&&e.rhs.length>0){this.lastInferredType="boolean";for(let s=0;s<e.rhs.length;s++){let i=this.visit(e.rhs[s]);t=`${t} || ${i}`;}}return t}logicalAnd(e){let t=this.visit(e.lhs);if(e.rhs&&e.rhs.length>0){this.lastInferredType="boolean";for(let s=0;s<e.rhs.length;s++){let i=this.visit(e.rhs[s]);t=`${t} && ${i}`;}}return t}comparison(e){let t=this.visit(e.lhs);if(e.rhs){this.lastInferredType="boolean";let s=e.ops[0].image,i=this.visit(e.rhs[0]);t=`${t} ${s} ${i}`;}return t}addition(e){let t=this.visit(e.lhs),s=this.lastInferredType,i=t;if(e.rhs&&e.rhs.length>0){let n=s==="string",a=s==="number";for(let o=0;o<e.rhs.length;o++){let p=e.ops[o].image,u=this.visit(e.rhs[o]);this.lastInferredType==="string"&&(n=true),this.lastInferredType!=="number"&&(a=false),i=`${i} ${p} ${u}`;}n?this.lastInferredType="string":a?this.lastInferredType="number":this.lastInferredType="any";}else this.lastInferredType=s;return i}multiplication(e){let t=this.visit(e.lhs);if(e.rhs&&e.rhs.length>0){this.lastInferredType="number";for(let s=0;s<e.rhs.length;s++){let i=e.ops[s].image,n=this.visit(e.rhs[s]);t=`${t} ${i} ${n}`;}}return t}unaryExpression(e){let t=this.visit(e.atomic);if(e.sign){let s=e.sign[0].image;return s==="!"&&(this.lastInferredType="boolean"),s==="-"&&(this.lastInferredType="number"),`${s}${t}`}return t}atomic(e){if(e.literal)return this.visit(e.literal);if(e.functionCall)return this.visit(e.functionCall);if(e.anyIdentifier){this.lastInferredType="any";let t=this.visit(e.anyIdentifier);if(["true","false","null"].includes(t.name)&&!t.quoted)return t.name;if(!t.quoted){if(t.name.startsWith("source.")||t.name.startsWith("source["))return this.isAnalyzing&&this.tracker.recordAccess(t.name.substring(7),"any",false),this.safeMode?this.safify(t.name):t.name;if(t.name.startsWith("target.")||t.name.startsWith("target["))return this.isAnalyzing&&this.tracker.recordAccess(t.name.substring(7),"any",true),this.safeMode?this.safify(t.name):t.name;if(t.name==="target")return "target";if(t.name==="source")return "source";if(t.name==="_source"||t.name.startsWith("_source.")||t.name.startsWith("_source[")){this.isAnalyzing&&this.tracker.recordAccess(t.name.substring(7)||"","any",false);let s=t.name.substring(7);return `_rootSource${this.safeMode?this.safify(s):s}`}if(t.name==="_target"||t.name.startsWith("_target.")||t.name.startsWith("_target[")){this.isAnalyzing&&this.tracker.recordAccess(t.name.substring(7)||"","any",true);let s=t.name.substring(7);return `_rootTarget${this.safeMode?this.safify(s):s}`}}return this.isAnalyzing&&this.tracker.recordAccess(t.name,"any",this.readFrom==="target"),this.genAccess(this.readFrom,t)}if(e.expression)return `(${this.visit(e.expression)})`}functionCall(e){let t=e.name[0].image,s=(t.startsWith("`")?t.slice(1,-1):t).toLowerCase(),i=e.args?e.args.map(a=>this.visit(a)):[],n=ye[s];if(n)return ["substring","text","replace","uppercase","lowercase","to_base64","from_base64"].includes(s)?this.lastInferredType="string":["number","extractnumber"].includes(s)?this.lastInferredType="number":["aslist","transpose"].includes(s)?this.lastInferredType="array":s==="asobject"&&(this.lastInferredType="object"),n(i);throw new Error(`Unknown function: ${t}`)}sectionRule(e){let t=this.visit(e.sectionName),s=t.name,i=this.genAccess("target",t,true),n,a;if(e.followExpr){let l=this.visit(e.followExpr),h=l.replace(/\?\./g,".");h==="source.parent"||h==="this.source.parent"||h===`${this.readFrom.replace(/\?\./g,".")}.parent`?(n="source",a="parent"):(n=l,a=n);}else n=this.genAccess("source",t),a=t.name;let o=!!e.Multiple,p=!!e.whereExpr,u="";if(p&&(u=this.visit(e.whereExpr)),!!e.subqueryFrom){let l=this.visit(e.subquerySourceType),h=this.visit(e.subqueryTargetType);this.scopeStack.push({format:h.name,options:h.options,isSerializationScope:true});try{let g=!!e.subqueryTransform,y=e.action?e.action.map(E=>this.visit(E)):[];g||y.push("Object.assign(target, source);");let d=JSON.stringify(l.options),L=JSON.stringify(h.options);if(o){let E=p?`.filter(item => { const source = item; return ${u}; })`:"";return `
22
+ if (${n} && Array.isArray(${n})) {
23
+ ${i} = ${n}${E}.map(item => {
24
+ const subSource = env.parse('${l.name}', item, ${d});
52
25
  const source = subSource;
53
26
  const target = {};
54
- ${f.join(`
27
+ ${y.join(`
55
28
  `)}
56
- return env.serialize('${u.name}', target, ${ht});
29
+ return env.serialize('${h.name}', target, ${L});
57
30
  });
58
31
  }
32
+ `}else return p?`
33
+ if (${n} && Array.isArray(${n})) {
34
+ const _filtered = ${n}.find(item => { const source = item; return ${u}; });
35
+ if (_filtered) {
36
+ ${i} = (function(innerSource) {
37
+ const subSource = env.parse('${l.name}', innerSource, ${d});
38
+ const source = subSource;
39
+ const target = {};
40
+ ${y.join(`
41
+ `)}
42
+ return env.serialize('${h.name}', target, ${L});
43
+ })(_filtered);
44
+ }
45
+ }
59
46
  `:`
60
- if (${a}) {
61
- ${n} = (function(innerSource) {
62
- const subSource = env.parse('${h.name}', innerSource, ${d});
47
+ if (${n}) {
48
+ ${i} = (function(innerSource) {
49
+ const subSource = env.parse('${l.name}', innerSource, ${d});
63
50
  const source = subSource;
64
51
  const target = {};
65
- ${f.join(`
52
+ ${y.join(`
66
53
  `)}
67
- return env.serialize('${u.name}', target, ${ht});
68
- })(${a});
54
+ return env.serialize('${h.name}', target, ${L});
55
+ })(${n});
69
56
  }
70
- `}finally{this.scopeStack.pop();}}this.scopeStack.push({format:"object",options:{},isSerializationScope:false});try{this.isAnalyzing&&this.tracker.pushSection(r,s.name,o);try{let h=t.action?t.action.map(u=>this.visit(u)):[];return o?`
71
- if (${a} && Array.isArray(${a})) {
72
- ${n} = ${a}.map(item => {
57
+ `}finally{this.scopeStack.pop();}}this.scopeStack.push({format:"object",options:{},isSerializationScope:false});try{let l=a;l!=="parent"&&(l=l.replace(/^source\??\./,"").replace(/^this\.source\??\./,"").replace(/\?\./g,".")),this.isAnalyzing&&this.tracker.pushSection(s,l,o);try{let h=e.action?e.action.map(g=>this.visit(g)):[];if(o){let g=p?`.filter(item => { const source = item; return ${u}; })`:"";return `
58
+ if (${n} && Array.isArray(${n})) {
59
+ ${i} = ${n}${g}.map(item => {
73
60
  const source = item;
74
61
  const target = {};
75
62
  ${h.join(`
@@ -77,16 +64,29 @@
77
64
  return target;
78
65
  });
79
66
  }
67
+ `}else return p?`
68
+ if (${n} && Array.isArray(${n})) {
69
+ const _filtered = ${n}.find(item => { const source = item; return ${u}; });
70
+ if (_filtered) {
71
+ ${i} = (function(innerSource) {
72
+ const source = innerSource;
73
+ const target = {};
74
+ ${h.join(`
75
+ `)}
76
+ return target;
77
+ })(_filtered);
78
+ }
79
+ }
80
80
  `:`
81
- if (${a}) {
82
- ${n} = (function(innerSource) {
81
+ if (${n}) {
82
+ ${i} = (function(innerSource) {
83
83
  const source = innerSource;
84
84
  const target = {};
85
85
  ${h.join(`
86
86
  `)}
87
87
  return target;
88
- })(${a});
88
+ })(${n});
89
89
  }
90
- `}finally{this.isAnalyzing&&this.tracker.popSection(s.name,o);}}finally{this.scopeStack.pop();}}},lt=new ot;var gt={};function A(i,t){gt[i.toLowerCase()]=t;}function pt(i){let t=gt[i.toLowerCase()];if(!t)throw new Error(`No adapter found for format: ${i}`);return t}function Rt(i){let t="";for(;i>=0;)t=String.fromCharCode(i%26+65)+t,i=Math.floor(i/26)-1;return t}A("json",{parse:i=>typeof i!="string"?i:JSON.parse(i),serialize:i=>JSON.stringify(i,null,2)});var $t=new fastXmlParser.XMLBuilder({ignoreAttributes:false,attributeNamePrefix:"$",textNodeName:"_",format:true});A("xml",{parse:(i,t)=>typeof i!="string"?i:new fastXmlParser.XMLParser({ignoreAttributes:false,removeNSPrefix:true,...t}).parse(i),serialize:(i,t)=>{let e=t?.rootGenerated??t?.params?.[0]??"root";return (t?new fastXmlParser.XMLBuilder({ignoreAttributes:false,attributeNamePrefix:"$",textNodeName:"_",format:true,...t}):$t).build({[e]:i})}});A("csv",{parse:(i,t)=>{if(typeof i!="string")return i;let e=t?.delimiter??t?.params?.[0]??",";return {rows:ft__default.default.parse(i,{delimiter:e,skipEmptyLines:true,...t}).data.map(s=>{let a={};return Array.isArray(s)&&s.forEach((o,p)=>{a[Rt(p)]=o;}),a})}},serialize:(i,t)=>{if(!i||!Array.isArray(i.rows))return "";let e=t?.delimiter??t?.params?.[0]??",",r=i.rows.map(n=>Object.keys(n).filter(a=>/^[A-Z]+$/.test(a)).sort((a,o)=>a.length!==o.length?a.length-o.length:a.localeCompare(o)).map(a=>n[a]));return ft__default.default.unparse(r,{delimiter:e,...t})}});A("object",{parse:i=>i,serialize:i=>i});A("plaintext",{parse:(i,t)=>{if(typeof i!="string")return i;let e=t?.separator??t?.params?.[0]??/\r?\n/;return {rows:i.split(e).filter(r=>r.length>0)}},serialize:(i,t)=>{if(!i||!Array.isArray(i.rows))return "";let e=t?.separator??t?.params?.[0]??`
91
- `;return i.rows.join(e)}});async function Kt(i,t){if(t?.cache){let u=await t.cache.retrieve(i);if(u)return dt(u)}let e=ct.tokenize(i);if(e.errors.length>0)throw new Error(`Lexing errors: ${e.errors[0].message}`);L.input=e.tokens;let r=L.query();if(L.errors.length>0)throw new Error(`Parsing errors: ${L.errors[0].message}`);lt.isAnalyzing=!!t?.analyze;let{code:n,analysis:s,sourceType:a,targetType:o}=lt.visit(r),p=vt__default.default.js(n,{indent_size:2,space_in_empty_paren:true,end_with_newline:true});t?.cache&&await t.cache.save(i,p);let h=dt(p);return s&&(s.sourceFormat=a.name,s.targetFormat=o.name,h.analysis=s),h}function dt(i){let e=new Function(i)(),r={parse:(s,a,o)=>pt(s).parse(a,o),serialize:(s,a,o)=>pt(s).serialize(a,o)},n=(s=>e(s,r));return n.code=i,n}function Ht(i,...t){return i.reduce((e,r,n)=>e+r+(t[n]??""),"")}function Xt(i){return `Hello, ${i}! The Morph engine is ready.`}exports.compile=Kt;exports.getAdapter=pt;exports.greet=Xt;exports.morphQL=Ht;exports.registerAdapter=A;//# sourceMappingURL=index.cjs.map
90
+ `}finally{this.isAnalyzing&&this.tracker.popSection(l,o);}}finally{this.scopeStack.pop();}}},fe=new he;var Se={};function T(r,e){Se[r.toLowerCase()]=e;}function me(r){let e=Se[r.toLowerCase()];if(!e)throw new Error(`No adapter found for format: ${r}`);return e}function Ce(r){let e="";for(;r>=0;)e=String.fromCharCode(r%26+65)+e,r=Math.floor(r/26)-1;return e}T("json",{parse:r=>typeof r!="string"?r:JSON.parse(r),serialize:r=>JSON.stringify(r,null,2)});var Be=new fastXmlParser.XMLBuilder({ignoreAttributes:false,attributeNamePrefix:"$",textNodeName:"_",format:true});T("xml",{parse:(r,e)=>typeof r!="string"?r:new fastXmlParser.XMLParser({ignoreAttributes:false,removeNSPrefix:true,...e}).parse(r),serialize:(r,e)=>{let t=e?.rootGenerated??e?.params?.[0]??"root";return (e?new fastXmlParser.XMLBuilder({ignoreAttributes:false,attributeNamePrefix:"$",textNodeName:"_",format:true,...e}):Be).build({[t]:r})}});T("csv",{parse:(r,e)=>{if(typeof r!="string")return r;let t=e?.delimiter??e?.params?.[0]??",";return {rows:de__default.default.parse(r,{delimiter:t,skipEmptyLines:true,...e}).data.map(n=>{let a={};return Array.isArray(n)&&n.forEach((o,p)=>{a[Ce(p)]=o;}),a})}},serialize:(r,e)=>{if(!r||!Array.isArray(r.rows))return "";let t=e?.delimiter??e?.params?.[0]??",",s=r.rows.map(i=>Object.keys(i).filter(a=>/^[A-Z]+$/.test(a)).sort((a,o)=>a.length!==o.length?a.length-o.length:a.localeCompare(o)).map(a=>i[a]));return de__default.default.unparse(s,{delimiter:t,...e})}});T("edifact",{parse:(r,e)=>{if(typeof r!="string")return r;let t="'",s="+",i=":",n="?",a=r.trim();if(a.startsWith("UNA")){let l=a.substring(3,9);i=l[0],s=l[1],n=l[3],t=l[5],a=a.substring(9).trim();}e&&(e.segmentTerminator&&(t=e.segmentTerminator),e.elementSeparator&&(s=e.elementSeparator),e.componentSeparator&&(i=e.componentSeparator),e.releaseChar&&(n=e.releaseChar));let o={},p=(l,h,g)=>{let y=[],d="";for(let L=0;L<l.length;L++){let E=l[L];E===g&&L+1<l.length?d+=g+l[++L]:E===h?(y.push(d),d=""):d+=E;}return y.push(d),y},u=(l,h)=>{let g="";for(let y=0;y<l.length;y++)l[y]===h&&y+1<l.length?g+=l[++y]:g+=l[y];return g},f=p(a,t,n).map(l=>l.trim()).filter(l=>l.length>0);for(let l of f){let h=p(l,s,n),g=u(h[0],n),y=h.slice(1).map(d=>{let E=p(d,i,n).map(Ue=>u(Ue,n));return E.length>1?E:E[0]});o[g]||(o[g]=[]),o[g].push(y);}return o},serialize:(r,e)=>{if(!r||typeof r!="object")return "";let t=e?.segmentTerminator??"'",s=e?.elementSeparator??"+",i=e?.componentSeparator??":",n=e?.releaseChar??"?",a=p=>{if(p==null)return "";let u=String(p),f="";for(let l of u)(l===t||l===s||l===i||l===n)&&(f+=n),f+=l;return f},o="";e?.includeUNA&&(o+=`UNA${i}${s}.${n} ${t}`);for(let p in r){let u=Array.isArray(r[p])?r[p]:[r[p]];for(let f of u){if(o+=p,Array.isArray(f))for(let l of f)o+=s,Array.isArray(l)?o+=l.map(a).join(i):o+=a(l);o+=t;}}return o}});T("object",{parse:r=>r,serialize:r=>r});T("plaintext",{parse:(r,e)=>{if(typeof r!="string")return r;let t=e?.separator??e?.params?.[0]??/\r?\n/;return {rows:r.split(t).filter(s=>s.length>0)}},serialize:(r,e)=>{if(!r||!Array.isArray(r.rows))return "";let t=e?.separator??e?.params?.[0]??`
91
+ `;return r.rows.join(t)}});var Le={spreadsheet:r=>{let e=Array.isArray(r)?r:r==null?[]:[r];if(!Array.isArray(r)&&r&&typeof r=="object"&&Array.isArray(r.rows)&&(e=r.rows),e.length===0)return [];let t=[],s=[],i=[];for(let n=0;n<e.length;n++){let a=e[n];if(!(!a||typeof a!="object"))if(n===0){i=Object.keys(a);for(let o of i)s.push(String(a[o]));}else {let o={};for(let p=0;p<i.length;p++){let u=i[p],f=s[p];o[f]=a[u];}t.push(o);}}return t},aslist:r=>Array.isArray(r)?r:r==null?[]:[r],to_base64:r=>{let e=String(r);return typeof btoa=="function"?btoa(unescape(encodeURIComponent(e))):Buffer.from(e,"utf-8").toString("base64")},from_base64:r=>{let e=String(r);return typeof atob=="function"?decodeURIComponent(escape(atob(e))):Buffer.from(e,"base64").toString("utf-8")},xmlnode:(r,...e)=>{if(e.length>0){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);let s=t.map(([n,a])=>[`$${n}`,a]),i=Object.fromEntries(s);return {_:r,...i}}return r},unpack:(r,...e)=>{let t=String(r||""),s={};for(let i of e){let n=i.split(":");if(n.length<3)continue;let[a,o,p,u]=n,f=parseInt(o,10),l=parseInt(p,10);if(isNaN(f)||isNaN(l))continue;let h=t.substring(f,f+l);u!=="raw"&&(h=h.trim()),s[a]=h;}return s},pack:(r,...e)=>{let t=r||{},s=e.map(a=>{let o=a.split(":");if(o.length<3)return null;let[p,u,f,l]=o;return {name:p,start:parseInt(u,10),length:parseInt(f,10),left:l==="left"}}).filter(a=>a!==null),i=s.reduce((a,o)=>Math.max(a,o.start+o.length),0),n=" ".repeat(i);for(let a of s){let o=String(t[a.name]??""),u=(a.left?o.padStart(a.length):o.padEnd(a.length)).substring(0,a.length);n=n.substring(0,a.start)+u+n.substring(a.start+a.length);}return n},concat:(...r)=>r.reduce((e,t)=>e.concat(Array.isArray(t)?t:t==null?[]:[t]),[]),transpose:(r,...e)=>{if(!r||typeof r!="object"||e.length===0)return [];let t=0;for(let i of e){let n=r[i];Array.isArray(n)?t=Math.max(t,n.length):n!=null&&(t=Math.max(t,1));}let s=[];for(let i=0;i<t;i++){let n={};for(let a of e){let o=r[a];Array.isArray(o)?n[a]=o[i]:n[a]=i===0?o:void 0;}s.push(n);}return s}};async function nt(r,e){if(e?.cache){let f=await e.cache.retrieve(r);if(f)return Ae(f)}let t=ge.tokenize(r);if(t.errors.length>0)throw new Error(`Lexing errors: ${t.errors[0].message}`);N.input=t.tokens;let s=N.query();if(N.errors.length>0)throw new Error(`Parsing errors: ${N.errors[0].message}`);fe.isAnalyzing=!!e?.analyze;let{code:i,analysis:n,sourceType:a,targetType:o}=fe.visit(s),p=Me__default.default.js(i,{indent_size:2,space_in_empty_paren:true,end_with_newline:true});e?.cache&&await e.cache.save(r,p);let u=Ae(p);return n&&(n.sourceFormat=a.name,n.targetFormat=o.name,u.analysis=n),u}function Ae(r){let t=new Function(r)(),s={parse:(n,a,o)=>me(n).parse(a,o),serialize:(n,a,o)=>me(n).serialize(a,o),functions:Le},i=(n=>t(n,s));return i.code=r,i}function it(r,...e){return r.reduce((t,s,i)=>t+s+(e[i]??""),"")}function at(r){return `Hello, ${r}! The Morph engine is ready.`}exports.compile=nt;exports.getAdapter=me;exports.greet=at;exports.morphQL=it;exports.registerAdapter=T;//# sourceMappingURL=index.cjs.map
92
92
  //# sourceMappingURL=index.cjs.map