mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-05-05 22:07:10 -04:00
18 lines
38 KiB
JavaScript
18 lines
38 KiB
JavaScript
![]() |
typeof window<"u"&&typeof window.global>"u"&&(window.global=window);const ParserEND=1114112;class ParserError extends Error{constructor(e,s,r){super("[ParserError] "+e,s,r),this.name="ParserError",this.code="ParserError",Error.captureStackTrace&&Error.captureStackTrace(this,ParserError)}}class State{constructor(e){this.parser=e,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}}class Parser{constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf="",this.char=null,this.ii=0,this.state=new State(this.parseStart)}parse(e){if(e.length===0||e.length==null)return;this._buf=String(e),this.ii=-1,this.char=-1;let s;for(;s===!1||this.nextChar();)s=this.runOne();this._buf=null}nextChar(){return this.char===10&&(++this.line,this.col=-1),++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=ParserEND;let e;do e=this.state.parser,this.runOne();while(this.state.parser!==e);return this.ctx=null,this.state=null,this._buf=null,this.obj}next(e){if(typeof e!="function")throw new ParserError("Tried to set state to non-existent state: "+JSON.stringify(e));this.state.parser=e}goto(e){return this.next(e),this.runOne()}call(e,s){s&&this.next(s),this.stack.push(this.state),this.state=new State(e)}callNow(e,s){return this.call(e,s),this.runOne()}return(e){if(this.stack.length===0)throw this.error(new ParserError("Stack underflow"));e===void 0&&(e=this.state.buf),this.state=this.stack.pop(),this.state.returned=e}returnNow(e){return this.return(e),this.runOne()}consume(){if(this.char===ParserEND)throw this.error(new ParserError("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(e){return e.line=this.line,e.col=this.col,e.pos=this.pos,e}parseStart(){throw new ParserError("Must declare a parseStart method")}}Parser.END=ParserEND;Parser.Error=ParserError;const createDateTime=t=>{const e=new Date(t);if(isNaN(e))throw new TypeError("Invalid Datetime");return e},f=(t,e)=>{for(e=String(e);e.length<t;)e="0"+e;return e};class FloatingDateTime extends Date{constructor(e){super(e+"Z"),this.isFloating=!0}toISOString(){const e=`${this.getUTCFullYear()}-${f(2,this.getUTCMonth()+1)}-${f(2,this.getUTCDate())}`,s=`${f(2,this.getUTCHours())}:${f(2,this.getUTCMinutes())}:${f(2,this.getUTCSeconds())}.${f(3,this.getUTCMilliseconds())}`;return`${e}T${s}`}}const createDateTimeFloat=t=>{const e=new FloatingDateTime(t);if(isNaN(e))throw new TypeError("Invalid Datetime");return e};class Date_ extends Date{constructor(e){super(e),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${f(2,this.getUTCMonth()+1)}-${f(2,this.getUTCDate())}`}}const createDate=t=>{const e=new Date_(t);if(isNaN(e))throw new TypeError("Invalid Datetime");return e};class Time extends Date{constructor(e){super(`0000-01-01T${e}Z`),this.isTime=!0}toISOString(){return`${f(2,this.getUTCHours())}:${f(2,this.getUTCMinutes())}:${f(2,this.getUTCSeconds())}.${f(3,this.getUTCMilliseconds())}`}}const createTime=t=>{const e=new Time(t);if(isNaN(e))throw new TypeError("Invalid Datetime");return e},TOMLParser=makeParserClass(Parser);class TomlError extends Error{constructor(e){super(e),this.name="TomlError",Error.captureStackTrace&&Error.captureStackTrace(this,TomlError),this.fromTOML=!0,this.wrapped=null}}TomlError.wrap=t=>{const e=new TomlError(t.message);return e.code=t.code,e.wrapped=t,e};const CTRL_I=9,CTRL_J=10,CTRL_M=13,CTRL_CHAR_BOUNDARY=31,CHAR_SP=32,CHAR_QUOT=34,CHAR_NUM=35,CHAR_APOS=39,CHAR_PLUS=43,CHAR_COMMA=44,CHAR_HYPHEN=45,CHAR_PERIOD=46,CHAR_0=48,CHAR_1=49,CHAR_7=55,CHAR_9=57,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_A=65,CHAR_E=69,CHAR_F=70,CHAR_T=84,CHAR_U=85,CHAR_Z=90,CHAR_LOWBAR=95,CHAR_a=97,CHAR_b=98,CHAR_e=101,CHAR_f=102,CHAR_i=105,CHAR_l=108,CHAR_n=110,CHAR_o=111,CHAR_r=114,CHAR_s=115,CHAR_t=116,CHAR_u=117,CHAR_x=120,CHAR_z=122,CHAR_LCUB=123,CHAR_RCUB=125,CHAR_LSQB=91,CHAR_BSOL=92,CHAR_RSQB=93,CHAR_DEL=127,SURROGATE_FIRST=5529
|
||
|
`,[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(t){return t>=CHAR_0&&t<=CHAR_9}function isHexit(t){return t>=CHAR_A&&t<=CHAR_F||t>=CHAR_a&&t<=CHAR_f||t>=CHAR_0&&t<=CHAR_9}function isBit(t){return t===CHAR_1||t===CHAR_0}function isOctit(t){return t>=CHAR_0&&t<=CHAR_7}function isAlphaNumQuoteHyphen(t){return t>=CHAR_A&&t<=CHAR_Z||t>=CHAR_a&&t<=CHAR_z||t>=CHAR_0&&t<=CHAR_9||t===CHAR_APOS||t===CHAR_QUOT||t===CHAR_LOWBAR||t===CHAR_HYPHEN}function isAlphaNumHyphen(t){return t>=CHAR_A&&t<=CHAR_Z||t>=CHAR_a&&t<=CHAR_z||t>=CHAR_0&&t<=CHAR_9||t===CHAR_LOWBAR||t===CHAR_HYPHEN}const _type=Symbol("type"),_declared=Symbol("declared"),hasOwnProperty=Object.prototype.hasOwnProperty,defineProperty=Object.defineProperty,descriptor={configurable:!0,enumerable:!0,writable:!0,value:void 0};function hasKey(t,e){return hasOwnProperty.call(t,e)?!0:(e==="__proto__"&&defineProperty(t,"__proto__",descriptor),!1)}const INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}function isInlineTable(t){return t===null||typeof t!="object"?!1:t[_type]===INLINE_TABLE}const TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:!1,writable:!0}})}function isTable(t){return t===null||typeof t!="object"?!1:t[_type]===TABLE}const _contentType=Symbol("content-type"),INLINE_LIST=Symbol("inline-list");function InlineList(t){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:t}})}function isInlineList(t){return t===null||typeof t!="object"?!1:t[_type]===INLINE_LIST}const LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}function isList(t){return t===null||typeof t!="object"?!1:t[_type]===LIST}let _custom;try{const utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(t){}const _inspect=_custom||"inspect";class BoxedBigInt{constructor(e){try{this.value=global.BigInt.asIntN(64,e)}catch{this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}}const INTEGER=Symbol("integer");function Integer(t){let e=Number(t);return Object.is(e,-0)&&(e=0),global.BigInt&&!Number.isSafeInteger(e)?new BoxedBigInt(t):Object.defineProperties(new Number(e),{isNaN:{value:function(){return isNaN(this)}},[_type]:{value:INTEGER},[_inspect]:{value:()=>`[Integer: ${t}]`}})}function isInteger(t){return t===null||typeof t!="object"?!1:t[_type]===INTEGER}const FLOAT=Symbol("float");function Float(t){return Object.defineProperties(new Number(t),{[_type]:{value:FLOAT},[_inspect]:{value:()=>`[Float: ${t}]`}})}function isFloat(t){return t===null||typeof t!="object"?!1:t[_type]===FLOAT}function tomlType$1(t){const e=typeof t;if(e==="object"){if(t===null)return"null";if(t instanceof Date)return"datetime";if(_type in t)switch(t[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}return e}function makeParserClass(t){class e extends t{constructor(){super(),this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===t.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===t.END)return null;if(this.char===CHAR_LSQB)return this.call(this.parseTableOrList);if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(isAlphaNumQuoteHyphen(this.char))return this.callNow(this.parseAssignStatement);throw this.error(new TomlError(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(this.char===CHAR_NUM)return this.goto(this.parseComment);if(this.char===t.END||this.char===C
|
||
|
`,e&&e.split){const r=e.split(/\n/),i=String(Math.min(r.length,t.line+3)).length;let h=" ";for(;h.length<i;)h+=" ";for(let n=Math.max(0,t.line-1);n<Math.min(r.length,t.line+2);++n){let a=String(n+1);if(a.length<i&&(a=" "+a),t.line===n){s+=a+"> "+r[n]+`
|
||
|
`,s+=h+" ";for(let o=0;o<t.col;++o)s+=" ";s+=`^
|
||
|
`}else s+=a+": "+r[n]+`
|
||
|
`}}return t.message=s+`
|
||
|
`,t}function parseString(t){global.Buffer&&global.Buffer.isBuffer(t)&&(t=t.toString("utf8"));const e=new TOMLParser;try{return e.parse(t),e.finish()}catch(s){throw prettyError(s,t)}}function stringify$1(t){if(t===null)throw typeError("null");if(t===void 0)throw typeError("undefined");if(typeof t!="object")throw typeError(typeof t);if(typeof t.toJSON=="function"&&(t=t.toJSON()),t==null)return null;const e=tomlType(t);if(e!=="table")throw typeError(e);return stringifyObject("","",t)}function typeError(t){return new Error("Can only stringify objects, not "+t)}function getInlineKeys(t){return Object.keys(t).filter(e=>isInline(t[e]))}function getComplexKeys(t){return Object.keys(t).filter(e=>!isInline(t[e]))}function toJSON(t){let e=Array.isArray(t)?[]:Object.prototype.hasOwnProperty.call(t,"__proto__")?{["__proto__"]:void 0}:{};for(let s of Object.keys(t))t[s]&&typeof t[s].toJSON=="function"&&!("toISOString"in t[s])?e[s]=t[s].toJSON():e[s]=t[s];return e}function stringifyObject(t,e,s){s=toJSON(s);let r,i;r=getInlineKeys(s),i=getComplexKeys(s);const h=[],n=e||"";r.forEach(o=>{var l=tomlType(s[o]);l!=="undefined"&&l!=="null"&&h.push(n+stringifyKey(o)+" = "+stringifyAnyInline(s[o],!0))}),h.length>0&&h.push("");const a=t&&r.length>0?e+" ":"";return i.forEach(o=>{h.push(stringifyComplex(t,a,o,s[o]))}),h.join(`
|
||
|
`)}function isInline(t){switch(tomlType(t)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return!0;case"array":return t.length===0||tomlType(t[0])!=="table";case"table":return Object.keys(t).length===0;default:return!1}}function tomlType(t){return t===void 0?"undefined":t===null?"null":typeof t=="bigint"||Number.isInteger(t)&&!Object.is(t,-0)?"integer":typeof t=="number"?"float":typeof t=="boolean"?"boolean":typeof t=="string"?"string":"toISOString"in t?isNaN(t)?"undefined":"datetime":Array.isArray(t)?"array":"table"}function stringifyKey(t){const e=String(t);return/^[-A-Za-z0-9_]+$/.test(e)?e:stringifyBasicString(e)}function stringifyBasicString(t){return'"'+escapeString(t).replace(/"/g,'\\"')+'"'}function stringifyLiteralString(t){return"'"+t+"'"}function numpad(t,e){for(;e.length<t;)e="0"+e;return e}function escapeString(t){return t.replace(/\\/g,"\\\\").replace(/[\b]/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/([\u0000-\u001f\u007f])/,e=>"\\u"+numpad(4,e.codePointAt(0).toString(16)))}function stringifyMultilineString(t){let e=t.split(/\n/).map(s=>escapeString(s).replace(/"(?="")/g,'\\"')).join(`
|
||
|
`);return e.slice(-1)==='"'&&(e+=`\\
|
||
|
`),`"""
|
||
|
`+e+'"""'}function stringifyAnyInline(t,e){let s=tomlType(t);return s==="string"&&(e&&/\n/.test(t)?s="string-multiline":!/[\b\t\n\f\r']/.test(t)&&/"/.test(t)&&(s="string-literal")),stringifyInline(t,s)}function stringifyInline(t,e){switch(e||(e=tomlType(t)),e){case"string-multiline":return stringifyMultilineString(t);case"string":return stringifyBasicString(t);case"string-literal":return stringifyLiteralString(t);case"integer":return stringifyInteger(t);case"float":return stringifyFloat(t);case"boolean":return stringifyBoolean(t);case"datetime":return stringifyDatetime(t);case"array":return stringifyInlineArray(t.filter(s=>tomlType(s)!=="null"&&tomlType(s)!=="undefined"&&tomlType(s)!=="nan"));case"table":return stringifyInlineTable(t);default:throw typeError(e)}}function stringifyInteger(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}function stringifyFloat(t){if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,NaN))return"nan";if(Object.is(t,-0))return"-0.0";const[e,s]=String(t).split(".");return stringifyInteger(e)+"."+s}function stringifyBoolean(t){return String(t)}function stringifyDatetime(t){return t.toISOString()}function stringifyInlineArray(t){t=toJSON(t);let e="[";const s=t.map(r=>stringifyInline(r));return s.join(", ").length>60||/\n/.test(s)?e+=`
|
||
|
`+s.join(`,
|
||
|
`)+`
|
||
|
`:e+=" "+s.join(", ")+(s.length>0?" ":""),e+"]"}function stringifyInlineTable(t){t=toJSON(t);const e=[];return Object.keys(t).forEach(s=>{e.push(stringifyKey(s)+" = "+stringifyAnyInline(t[s],!1))}),"{ "+e.join(", ")+(e.length>0?" ":"")+"}"}function stringifyComplex(t,e,s,r){const i=tomlType(r);if(i==="array")return stringifyArrayOfTables(t,e,s,r);if(i==="table")return stringifyComplexTable(t,e,s,r);throw typeError(i)}function stringifyArrayOfTables(t,e,s,r){r=toJSON(r);const i=tomlType(r[0]);if(i!=="table")throw typeError(i);const h=t+stringifyKey(s);let n="";return r.forEach(a=>{n.length>0&&(n+=`
|
||
|
`),n+=e+"[["+h+`]]
|
||
|
`,n+=stringifyObject(h+".",e,a)}),n}function stringifyComplexTable(t,e,s,r){const i=t+stringifyKey(s);let h="";return getInlineKeys(r).length>0&&(h+=e+"["+i+`]
|
||
|
`),h+stringifyObject(i+".",e,r)}const parse=parseString,stringify=stringify$1;export{parse as p,stringify as s};
|