@morphql/core 0.1.13 → 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 +57 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +57 -30
- package/dist/index.js.map +1 -1
- package/package.json +3 -1
package/dist/index.cjs
CHANGED
|
@@ -1,65 +1,92 @@
|
|
|
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 Lt=chevrotain.createToken({name:"WhiteSpace",pattern:/\s+/,group:chevrotain.Lexer.SKIPPED}),St=chevrotain.createToken({name:"LineComment",pattern:/\/\/[^\n\r]*/,group:chevrotain.Lexer.SKIPPED}),At=chevrotain.createToken({name:"BlockComment",pattern:/\/\*[\s\S]*?\*\//,group:chevrotain.Lexer.SKIPPED}),u=chevrotain.createToken({name:"Identifier",pattern:/[a-zA-Z_$][a-zA-Z0-9_.[\]]*/}),v=chevrotain.createToken({name:"QuotedIdentifier",pattern:/`([^`\\]|\\.)*`/}),A=chevrotain.createToken({name:"From",pattern:/from/i,longer_alt:u}),T=chevrotain.createToken({name:"To",pattern:/to/i,longer_alt:u}),R=chevrotain.createToken({name:"Transform",pattern:/transform/i,longer_alt:u}),$=chevrotain.createToken({name:"Set",pattern:/set/i,longer_alt:u}),C=chevrotain.createToken({name:"Section",pattern:/section/i,longer_alt:u}),B=chevrotain.createToken({name:"Multiple",pattern:/multiple/i,longer_alt:u}),M=chevrotain.createToken({name:"Clone",pattern:/clone/i,longer_alt:u}),I=chevrotain.createToken({name:"Delete",pattern:/delete/i,longer_alt:u}),w=chevrotain.createToken({name:"Define",pattern:/define/i,longer_alt:u}),k=chevrotain.createToken({name:"Modify",pattern:/modify/i,longer_alt:u}),b=chevrotain.createToken({name:"If",pattern:/if/i,longer_alt:u}),q=chevrotain.createToken({name:"Else",pattern:/else/i,longer_alt:u}),P=chevrotain.createToken({name:"True",pattern:/true/i,longer_alt:u}),_=chevrotain.createToken({name:"False",pattern:/false/i,longer_alt:u}),j=chevrotain.createToken({name:"Null",pattern:/null/i,longer_alt:u}),z=chevrotain.createToken({name:"Return",pattern:/return/i,longer_alt:u}),F=chevrotain.createToken({name:"Unsafe",pattern:/unsafe/i,longer_alt:u}),x=chevrotain.createToken({name:"EqualsEquals",pattern:/==/}),D=chevrotain.createToken({name:"EqualsEqualsEquals",pattern:/===/}),W=chevrotain.createToken({name:"NotEquals",pattern:/!=/}),Y=chevrotain.createToken({name:"NotEqualsEquals",pattern:/!==/}),G=chevrotain.createToken({name:"LessThanOrEqual",pattern:/<=/}),J=chevrotain.createToken({name:"GreaterThanOrEqual",pattern:/>=/}),Q=chevrotain.createToken({name:"LessThan",pattern:/</}),V=chevrotain.createToken({name:"GreaterThan",pattern:/>/}),Z=chevrotain.createToken({name:"And",pattern:/&&/}),K=chevrotain.createToken({name:"Or",pattern:/\|\|/}),H=chevrotain.createToken({name:"Not",pattern:/!/}),d=chevrotain.createToken({name:"Equals",pattern:/=/}),X=chevrotain.createToken({name:"Plus",pattern:/\+/}),O=chevrotain.createToken({name:"Minus",pattern:/-/}),tt=chevrotain.createToken({name:"Times",pattern:/\*/}),et=chevrotain.createToken({name:"Divide",pattern:/\//}),g=chevrotain.createToken({name:"LParen",pattern:/\(/}),y=chevrotain.createToken({name:"RParen",pattern:/\)/}),U=chevrotain.createToken({name:"Comma",pattern:/,/}),rt=chevrotain.createToken({name:"StringLiteral",pattern:/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/}),st=chevrotain.createToken({name:"NumericLiteral",pattern:/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/}),it=[Lt,St,At,A,T,R,$,C,B,M,I,w,k,b,q,P,_,j,z,F,D,x,Y,W,G,J,Z,K,d,Q,V,H,X,O,tt,et,g,y,U,rt,st,v,u],ht=new chevrotain.Lexer(it);var nt=class extends chevrotain.CstParser{constructor(){super(it),this.performSelfAnalysis();}query=this.RULE("query",()=>{this.CONSUME(A),this.SUBRULE(this.typeFormat,{LABEL:"sourceType"}),this.CONSUME(T),this.SUBRULE1(this.typeFormat,{LABEL:"targetType"}),this.OPTION(()=>{this.CONSUME(R),this.OPTION1(()=>{this.CONSUME(F);}),this.MANY(()=>{this.SUBRULE(this.action);});});});typeFormat=this.RULE("typeFormat",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"name"}),this.OPTION(()=>{this.CONSUME(g),this.MANY_SEP({SEP:U,DEF:()=>{this.SUBRULE(this.typeFormatParameter,{LABEL:"params"});}}),this.CONSUME(y);});});typeFormatParameter=this.RULE("typeFormatParameter",()=>{this.OR([{GATE:()=>this.LA(2).tokenType===d,ALT:()=>this.SUBRULE(this.namedParameter)},{ALT:()=>this.SUBRULE(this.literal)}]);});namedParameter=this.RULE("namedParameter",()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"key"}),this.CONSUME(d),this.SUBRULE(this.literal,{LABEL:"value"});});anyIdentifier=this.RULE("anyIdentifier",()=>{this.OR([{ALT:()=>this.CONSUME(u)},{ALT:()=>this.CONSUME(v)}]);});literal=this.RULE("literal",()=>{this.OR([{ALT:()=>this.CONSUME(rt)},{ALT:()=>this.CONSUME(st)},{ALT:()=>this.CONSUME(P)},{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(z),this.SUBRULE(this.expression,{LABEL:"expr"});});deleteRule=this.RULE("deleteRule",()=>{this.CONSUME(I),this.SUBRULE(this.anyIdentifier,{LABEL:"field"});});ifAction=this.RULE("ifAction",()=>{this.CONSUME(b),this.CONSUME(g),this.SUBRULE(this.expression,{LABEL:"condition"}),this.CONSUME(y),this.CONSUME2(g),this.MANY(()=>{this.SUBRULE(this.action,{LABEL:"thenActions"});}),this.CONSUME2(y),this.OPTION(()=>{this.CONSUME(q),this.CONSUME3(g),this.MANY2(()=>{this.SUBRULE2(this.action,{LABEL:"elseActions"});}),this.CONSUME3(y);});});cloneRule=this.RULE("cloneRule",()=>{this.CONSUME(M),this.OPTION(()=>{this.CONSUME(g),this.MANY_SEP({SEP:U,DEF:()=>{this.SUBRULE(this.anyIdentifier,{LABEL:"fields"});}}),this.CONSUME(y);});});setRule=this.RULE("setRule",()=>{this.CONSUME($),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(d),this.SUBRULE(this.expression,{LABEL:"right"});});modifyRule=this.RULE("modifyRule",()=>{this.CONSUME(k),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(d),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(K),this.SUBRULE1(this.logicalAnd,{LABEL:"rhs"});});});logicalAnd=this.RULE("logicalAnd",()=>{this.SUBRULE(this.comparison,{LABEL:"lhs"}),this.MANY(()=>{this.CONSUME(Z),this.SUBRULE1(this.comparison,{LABEL:"rhs"});});});comparison=this.RULE("comparison",()=>{this.SUBRULE(this.addition,{LABEL:"lhs"}),this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(x,{LABEL:"ops"})},{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"})}]),this.SUBRULE1(this.addition,{LABEL:"rhs"});});});addition=this.RULE("addition",()=>{this.SUBRULE(this.multiplication,{LABEL:"lhs"}),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(X,{LABEL:"ops"})},{ALT:()=>this.CONSUME(O,{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(tt,{LABEL:"ops"})},{ALT:()=>this.CONSUME(et,{LABEL:"ops"})}]),this.SUBRULE1(this.unaryExpression,{LABEL:"rhs"});});});unaryExpression=this.RULE("unaryExpression",()=>{this.OPTION(()=>{this.OR([{ALT:()=>this.CONSUME(O,{LABEL:"sign"})},{ALT:()=>this.CONSUME(H,{LABEL:"sign"})}]);}),this.SUBRULE(this.atomic);});atomic=this.RULE("atomic",()=>{this.OR([{ALT:()=>this.SUBRULE(this.literal)},{GATE:()=>this.LA(2).tokenType===g,ALT:()=>this.SUBRULE(this.functionCall)},{ALT:()=>this.SUBRULE(this.anyIdentifier)},{ALT:()=>{this.CONSUME(g),this.SUBRULE(this.expression),this.CONSUME(y);}}]);});functionCall=this.RULE("functionCall",()=>{this.OR([{ALT:()=>this.CONSUME(u,{LABEL:"name"})},{ALT:()=>this.CONSUME(b,{LABEL:"name"})}]),this.CONSUME(g),this.MANY_SEP({SEP:U,DEF:()=>{this.SUBRULE(this.expression,{LABEL:"args"});}}),this.CONSUME(y);});sectionRule=this.RULE("sectionRule",()=>{this.CONSUME(C),this.OPTION(()=>{this.CONSUME(B);}),this.SUBRULE(this.anyIdentifier,{LABEL:"sectionName"}),this.CONSUME(g),this.OPTION1(()=>{this.CONSUME(A,{LABEL:"subqueryFrom"}),this.SUBRULE(this.typeFormat,{LABEL:"subquerySourceType"}),this.CONSUME(T,{LABEL:"subqueryTo"}),this.SUBRULE1(this.typeFormat,{LABEL:"subqueryTargetType"}),this.OPTION2(()=>{this.CONSUME(R,{LABEL:"subqueryTransform"});});}),this.MANY(()=>{this.SUBRULE(this.action);}),this.CONSUME(y),this.OPTION3(()=>{this.CONSUME1(A,{LABEL:"followFrom"}),this.SUBRULE(this.expression,{LABEL:"followExpr"});});});defineRule=this.RULE("defineRule",()=>{this.CONSUME(w),this.SUBRULE(this.anyIdentifier,{LABEL:"left"}),this.CONSUME(d),this.SUBRULE(this.expression,{LABEL:"right"});})},E=new nt;var ut={substring:r=>{if(r.length<2)throw new Error("substring() requires at least 2 arguments (string, start, [length])");let[t,e,s]=r;return s!==void 0?`String(${t}).slice(${e}, (${e}) + (${s}))`:`String(${t}).slice(${e})`},if:r=>{if(r.length!==3)throw new Error("if() requires exactly 3 arguments (condition, trueValue, falseValue)");let[t,e,s]=r;return `((${t}) ? (${e}) : (${s}))`},text:r=>{if(r.length!==1)throw new Error("text() requires exactly 1 argument (string or number)");let[t]=r;return `String(${t})`},replace:r=>{if(r.length!==3)throw new Error("replace() requires exactly 3 arguments (string, search, replacement)");let[t,e,s]=r;return `String(${t}).replace(${e}, ${s})`},number:r=>{if(r.length!==1)throw new Error("number() requires exactly 1 argument (string)");let[t]=r;return `Number(${t})`},extractnumber:r=>{if(r.length!==1)throw new Error("extractNumber() requires exactly 1 argument (string)");let[t]=r;return `(() => { const match = String(${t}).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[t]=r;return `String(${t}).toUpperCase()`},lowercase:r=>{if(r.length!==1)throw new Error("lowercase() requires exactly 1 argument (string)");let[t]=r;return `String(${t}).toLowerCase()`},xmlnode:r=>{if(r.length<1)throw new Error("xmlnode() requires at least 1 argument (string)");let[t,...e]=r,s=e.join(", ");return `env.functions.xmlnode(${t}${s?", "+s:""})`},split:r=>{if(r.length<1)throw new Error("split() requires at least 1 argument (string)");let[t,e,s]=r,n=e!==void 0?e:'""',i=s!==void 0?`, ${s}`:"";return `String(${t}).split(${n}${i})`},to_base64:r=>{if(r.length!==1)throw new Error("to_base64() requires exactly 1 argument (string)");let[t]=r;return `env.functions.to_base64(${t})`},from_base64:r=>{if(r.length!==1)throw new Error("from_base64() requires exactly 1 argument (string)");let[t]=r;return `env.functions.from_base64(${t})`},aslist:r=>{if(r.length!==1)throw new Error("aslist() requires exactly 1 argument");let[t]=r;return `env.functions.aslist(${t})`},spreadsheet:r=>{if(r.length!==1)throw new Error("spreadsheet() requires exactly 1 argument");let[t]=r;return `env.functions.spreadsheet(${t})`},unpack:r=>{if(r.length<2)throw new Error("unpack() requires at least 2 arguments (string, fieldSpec1, [fieldSpec2, ...])");let[t,...e]=r;e.forEach(n=>{let i=n.replace(/^["']|["']$/g,""),a=i.split(":");if(a.length<3)throw new Error(`Invalid field spec for unpack(): ${i}. Expected "name:start:length[:modifier]"`);let[o,h,p]=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 c=parseInt(h,10),f=parseInt(p,10);if(isNaN(c)||isNaN(f))throw new Error(`Invalid character positions in unpack() spec: ${i}`)});let s=e.join(", ");return `env.functions.unpack(${t}, ${s})`},pack:r=>{if(r.length<2)throw new Error("pack() requires at least 2 arguments (object, fieldSpec1, [fieldSpec2, ...])");let[t,...e]=r;e.forEach(n=>{let i=n.replace(/^["']|["']$/g,""),a=i.split(":");if(a.length<3)throw new Error(`Invalid field spec for pack(): ${i}. Expected "name:start:length[:modifier]"`);let[o,h,p]=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 c=parseInt(h,10),f=parseInt(p,10);if(isNaN(c)||isNaN(f))throw new Error(`Invalid character positions in pack() spec: ${i}`)});let s=e.join(", ");return `env.functions.pack(${t}, ${s})`},concat:r=>`env.functions.concat(${r.join(", ")})`};var L=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",s=false){let n=s?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(s=>{this.setInNode(this.getCurrentSource(),s,"any"),this.setInNode(e,s,"any");}):e.isOpen=true;}recordDelete(t){let e=this.getCurrentTarget();this.deleteInNode(e,t);}pushSection(t,e,s){e!=="parent"&&this.setInNode(this.getCurrentSource(),e,s?"array":"object");let n={type:s?"array":"object"};s?n.items={type:"object",properties:{}}:n.properties={};let i={type:"object",properties:{}};this.setInNodeExplicit(this.getCurrentTarget(),t,n),this.targetStack.push(s?n.items:n),this.sourceStack.push(i);}popSection(t,e){let s=this.sourceStack.pop();this.targetStack.pop();let n=this.getCurrentSource();if(t!=="parent"){let i=this.getOrSetNode(n,t,e?"array":"object"),a=e?i.items:i;a&&(a.properties||(a.properties={}),Object.assign(a.properties,s.properties||{}));}else n.properties||(n.properties={}),Object.assign(n.properties,s.properties||{});}setInNode(t,e,s){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a];i.properties||(i.properties={}),a===n.length-1?(!i.properties[o]||i.properties[o].type==="any")&&(i.properties[o]={type:s},s==="object"?i.properties[o].properties={}:s==="array"&&(i.properties[o].items={type:"object",properties:{}})):(i.properties[o]||(i.properties[o]={type:"object",properties:{}}),i=i.properties[o]);}}setInNodeExplicit(t,e,s){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a];i.properties||(i.properties={}),a===n.length-1?i.properties[o]=s:(i.properties[o]||(i.properties[o]={type:"object",properties:{}}),i=i.properties[o]);}}deleteInNode(t,e){let s=e.split("."),n=t;for(let i=0;i<s.length;i++){if(!n.properties)return;if(i===s.length-1)delete n.properties[s[i]];else if(n=n.properties[s[i]],!n)return}}getOrSetNode(t,e,s){let n=e.split("."),i=t;for(let a=0;a<n.length;a++){let o=n[a],p=a===n.length-1?s:"object";i.properties||(i.properties={}),i.properties[o]||(i.properties[o]={type:p},p==="object"?i.properties[o].properties={}:p==="array"&&(i.properties[o].items={type:"object",properties:{}})),i=i.properties[o];}return i}getResult(){return {source:this.sourceRoot,target:this.targetRoot}}};var Tt=E.getBaseCstVisitorConstructor(),at=class extends Tt{readFrom="source";scopeStack=[];safeMode=true;isAnalyzing=false;tracker=new L;lastInferredType="any";constructor(){super(),this.validateVisitor();}reset(){this.readFrom="source",this.scopeStack=[],this.tracker=new L,this.lastInferredType="any";}visitWithContext(t,e){let s=this.readFrom;this.readFrom=e.readFrom;try{return this.visit(t)}finally{this.readFrom=s;}}query(t){this.reset(),this.isAnalyzing&&(this.tracker=new L);let e=this.visit(t.sourceType),s=this.visit(t.targetType),n=!!t.Unsafe;this.safeMode=!n,this.scopeStack.push({format:s.name,options:s.options,isSerializationScope:true});try{let i=t.action?t.action.map(m=>this.visit(m)):[];t.Transform||i.push("Object.assign(target, source);");let a=e.name,o=s.name,h=JSON.stringify(e.options),p=JSON.stringify(s.options),c=i.some(m=>typeof m=="string"&&m.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:`
|
|
2
2
|
return function(input, env) {
|
|
3
3
|
// 1. Parse Input
|
|
4
|
-
const source = env.parse('${a}', input, ${
|
|
4
|
+
const source = env.parse('${a}', input, ${p});
|
|
5
5
|
const _rootSource = source;
|
|
6
6
|
|
|
7
7
|
// 2. Transform
|
|
8
8
|
const target = {};
|
|
9
9
|
const _rootTarget = target;
|
|
10
|
-
${
|
|
10
|
+
${n.join(`
|
|
11
11
|
`)}
|
|
12
12
|
|
|
13
13
|
// 3. Serialize Output
|
|
14
|
-
${
|
|
14
|
+
${f?"":`return env.serialize('${o}', target, ${u});`}
|
|
15
15
|
}
|
|
16
|
-
`,sourceType:
|
|
17
|
-
`):"",
|
|
18
|
-
`)} }`:"";return `if (${
|
|
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
19
|
${s}
|
|
20
|
-
} ${
|
|
21
|
-
`)}return this.isAnalyzing&&this.tracker.recordClone(),"Object.assign(target, source);"}setRule(
|
|
22
|
-
if (${
|
|
23
|
-
${
|
|
24
|
-
const subSource = env.parse('${
|
|
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});
|
|
25
25
|
const source = subSource;
|
|
26
26
|
const target = {};
|
|
27
|
-
${
|
|
27
|
+
${y.join(`
|
|
28
28
|
`)}
|
|
29
|
-
return env.serialize('${
|
|
29
|
+
return env.serialize('${h.name}', target, ${L});
|
|
30
30
|
});
|
|
31
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
|
+
}
|
|
32
46
|
`:`
|
|
33
|
-
if (${
|
|
34
|
-
${
|
|
35
|
-
const subSource = env.parse('${
|
|
47
|
+
if (${n}) {
|
|
48
|
+
${i} = (function(innerSource) {
|
|
49
|
+
const subSource = env.parse('${l.name}', innerSource, ${d});
|
|
36
50
|
const source = subSource;
|
|
37
51
|
const target = {};
|
|
38
|
-
${
|
|
52
|
+
${y.join(`
|
|
39
53
|
`)}
|
|
40
|
-
return env.serialize('${
|
|
41
|
-
})(${
|
|
54
|
+
return env.serialize('${h.name}', target, ${L});
|
|
55
|
+
})(${n});
|
|
42
56
|
}
|
|
43
|
-
`}finally{this.scopeStack.pop();}}this.scopeStack.push({format:"object",options:{},isSerializationScope:false});try{let
|
|
44
|
-
if (${
|
|
45
|
-
${
|
|
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 => {
|
|
46
60
|
const source = item;
|
|
47
61
|
const target = {};
|
|
48
|
-
${
|
|
62
|
+
${h.join(`
|
|
49
63
|
`)}
|
|
50
64
|
return target;
|
|
51
65
|
});
|
|
52
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
|
+
}
|
|
53
80
|
`:`
|
|
54
|
-
if (${
|
|
55
|
-
${
|
|
81
|
+
if (${n}) {
|
|
82
|
+
${i} = (function(innerSource) {
|
|
56
83
|
const source = innerSource;
|
|
57
84
|
const target = {};
|
|
58
|
-
${
|
|
85
|
+
${h.join(`
|
|
59
86
|
`)}
|
|
60
87
|
return target;
|
|
61
|
-
})(${
|
|
88
|
+
})(${n});
|
|
62
89
|
}
|
|
63
|
-
`}finally{this.isAnalyzing&&this.tracker.popSection(
|
|
64
|
-
`;return r.rows.join(
|
|
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
|
|
65
92
|
//# sourceMappingURL=index.cjs.map
|