@ddunigma/node 2.1.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +178 -229
- package/dist/DduStream-NP3CMCKK.js +2 -0
- package/dist/chunk-FVBZKVPE.js +4 -0
- package/dist/index.cjs +7 -0
- package/dist/index.d.cts +784 -0
- package/dist/index.d.ts +784 -0
- package/dist/index.js +5 -0
- package/package.json +39 -16
- package/dist/cjs/base/BaseDdu.d.ts +0 -53
- package/dist/cjs/base/BaseDdu.js +0 -29
- package/dist/cjs/base/index.d.ts +0 -1
- package/dist/cjs/base/index.js +0 -5
- package/dist/cjs/charSets/index.d.ts +0 -18
- package/dist/cjs/charSets/index.js +0 -4385
- package/dist/cjs/encoders/Ddu64.d.ts +0 -302
- package/dist/cjs/encoders/Ddu64.js +0 -1308
- package/dist/cjs/encoders/index.d.ts +0 -1
- package/dist/cjs/encoders/index.js +0 -5
- package/dist/cjs/index.d.ts +0 -5
- package/dist/cjs/index.js +0 -16
- package/dist/cjs/package.json +0 -3
- package/dist/cjs/types/DduDefaultTypes.d.ts +0 -3
- package/dist/cjs/types/DduDefaultTypes.js +0 -17
- package/dist/cjs/types/DduEnums.d.ts +0 -6
- package/dist/cjs/types/DduEnums.js +0 -10
- package/dist/cjs/types/DduInterface.d.ts +0 -91
- package/dist/cjs/types/DduInterface.js +0 -2
- package/dist/cjs/types/index.d.ts +0 -3
- package/dist/cjs/types/index.js +0 -19
- package/dist/cjs/utils/CharsetBuilder.d.ts +0 -129
- package/dist/cjs/utils/CharsetBuilder.js +0 -246
- package/dist/cjs/utils/DduPipeline.d.ts +0 -114
- package/dist/cjs/utils/DduPipeline.js +0 -229
- package/dist/cjs/utils/DduStream.d.ts +0 -64
- package/dist/cjs/utils/DduStream.js +0 -221
- package/dist/cjs/utils/crypto.d.ts +0 -30
- package/dist/cjs/utils/crypto.js +0 -84
- package/dist/cjs/utils/index.d.ts +0 -3
- package/dist/cjs/utils/index.js +0 -12
- package/dist/mjs/base/BaseDdu.d.ts +0 -53
- package/dist/mjs/base/BaseDdu.js +0 -23
- package/dist/mjs/base/index.d.ts +0 -1
- package/dist/mjs/base/index.js +0 -1
- package/dist/mjs/charSets/index.d.ts +0 -18
- package/dist/mjs/charSets/index.js +0 -4380
- package/dist/mjs/encoders/Ddu64.d.ts +0 -302
- package/dist/mjs/encoders/Ddu64.js +0 -1343
- package/dist/mjs/encoders/index.d.ts +0 -1
- package/dist/mjs/encoders/index.js +0 -1
- package/dist/mjs/index.d.ts +0 -5
- package/dist/mjs/index.js +0 -4
- package/dist/mjs/package.json +0 -3
- package/dist/mjs/types/DduDefaultTypes.d.ts +0 -3
- package/dist/mjs/types/DduDefaultTypes.js +0 -14
- package/dist/mjs/types/DduEnums.d.ts +0 -6
- package/dist/mjs/types/DduEnums.js +0 -7
- package/dist/mjs/types/DduInterface.d.ts +0 -91
- package/dist/mjs/types/DduInterface.js +0 -1
- package/dist/mjs/types/index.d.ts +0 -3
- package/dist/mjs/types/index.js +0 -3
- package/dist/mjs/utils/CharsetBuilder.d.ts +0 -129
- package/dist/mjs/utils/CharsetBuilder.js +0 -241
- package/dist/mjs/utils/DduPipeline.d.ts +0 -114
- package/dist/mjs/utils/DduPipeline.js +0 -223
- package/dist/mjs/utils/DduStream.d.ts +0 -64
- package/dist/mjs/utils/DduStream.js +0 -225
- package/dist/mjs/utils/crypto.d.ts +0 -30
- package/dist/mjs/utils/crypto.js +0 -78
- package/dist/mjs/utils/index.d.ts +0 -3
- package/dist/mjs/utils/index.js +0 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
'use strict';var stream=require('stream'),zlib=require('zlib'),crypto=require('crypto');var Be=Object.defineProperty;var ae=(s,e)=>()=>(s&&(e=s(s=0)),e);var we=(s,e)=>{for(var t in e)Be(s,t,{get:e[t],enumerable:true});};function ke(s,e){let t=s.charCodeAt(0);if(t<44032||t>55203)return s;let r=t-(t-44032)%28,n=xe[e]??0;return String.fromCharCode(r+n)}function F(s,e){let t=new Array(s.length*e.length),r=0;for(let n of s)for(let i of e)t[r++]=ke(n,i);return t}function me(s){return s.length===0?s:s.replaceAll("+","-").replaceAll("/","_").replaceAll("=",".")}function pe(s){return s.length===0?s:s.replaceAll("-","+").replaceAll("_","/").replaceAll(".","=")}function ge(s,e,t){if(e<=0||s.length<=e)return s;let r=Math.ceil(s.length/e),n=new Array(r*2-1),i=0;for(let a=0;a<s.length;a+=e)n[i++]=s.slice(a,a+e),a+e<s.length&&(n[i++]=t);return n.join("")}function D(s,e){if(s.length===0)return s;let t=s.replace(/[\r\n]/g,""),r=e&&e!==`
|
|
2
|
+
`&&e!==`\r
|
|
3
|
+
`&&e!=="\r"?e:"";return r.length>0&&t.includes(r)&&(t=t.replaceAll(r,"")),t}function ee(s){let e=4294967295;for(let t=0;t<s.length;t++)e=e>>>8^Ae[(e^s[t])&255];return ((e^4294967295)>>>0).toString(16).padStart(8,"0")}function ye(s){let e=s.lastIndexOf($);if(e===-1)return {data:s,checksum:null};let t=s.slice(e+$.length);return t.length!==8||!/^[0-9a-f]+$/i.test(t)?{data:s,checksum:null}:{data:s.slice(0,e),checksum:t.toLowerCase()}}function M(s,e){let r=s===void 0||!Number.isFinite(s)?6:Math.floor(s);return Math.min(e==="brotli"?11:9,Math.max(0,r))}var le,xe,Ae,E,v,$,L,te=ae(()=>{le=["-","_","."],xe={"":0,\u3131:1,\u3132:2,\u3133:3,\u3134:4,\u3135:5,\u3136:6,\u3137:7,\u3139:8,\u313A:9,\u313B:10,\u313C:11,\u313D:12,\u313E:13,\u313F:14,\u3140:15,\u3141:16,\u3142:17,\u3144:18,\u3145:19,\u3146:20,\u3147:21,\u3148:22,\u314A:23,\u314B:24,\u314C:25,\u314D:26,\u314E:27};Ae=(()=>{let s=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=t>>>1^(t&1?3988292384:0);s[e]=t;}return s})(),E="ELYSIA",v="GRISEO",$="CHK",L="ENC";});var ie={};we(ie,{DduDecodeStream:()=>exports.DduDecodeStream,DduEncodeStream:()=>exports.DduEncodeStream,createDecodeStream:()=>G,createEncodeStream:()=>se});function Ce(s){return s.length*2+x.length+2}function Oe(s,e){let t=e.compressionAlgorithm==="brotli"?"B":e.compressionAlgorithm==="deflate"?"D":"N",r=e.encrypted?"1":"0";return `${s}${x}${t}${r}${s}`}function ze(s,e){let t=Ce(e);if(s.length<t||!s.startsWith(e))return null;let r=e.length;if(s.slice(r,r+x.length)!==x)throw new Error("[DduStream decode] Invalid stream header magic");let i=s[r+x.length],a=s[r+x.length+1];if(s.slice(t-e.length,t)!==e)throw new Error("[DduStream decode] Invalid stream header terminator");let o=i==="B"?"brotli":i==="D"?"deflate":i==="N"?void 0:null;if(o===null)throw new Error("[DduStream decode] Invalid stream header compression flag");if(a!=="0"&&a!=="1")throw new Error("[DduStream decode] Invalid stream header encryption flag");return {compressionAlgorithm:o,encrypted:a==="1"}}function _e(s,e){let t=new stream.PassThrough,r=t.write.bind(t);return t.write=function(n,i,a){return typeof i=="function"?s.write(n,i):s.write(n,i,a)},t.end=function(n,i,a){return typeof n=="function"?s.end(n):typeof i=="function"?s.end(n,i):s.end(n,i,a)},e.on("data",n=>r(n)),e.on("end",()=>t.push(null)),e.on("error",n=>t.destroy(n)),s.on("error",n=>t.destroy(n)),t}function be(s){if(s.length===0)return new stream.PassThrough;for(let t=0;t<s.length-1;t++)s[t].pipe(s[t+1]);let e=_e(s[0],s[s.length-1]);for(let t of s)t.on("error",r=>{e.destroy(r);});return e}function se(s,e){let t=s.getCharSetInfo(),r=e?.compress??t.defaultCompress,n=(e?.encrypt??true)&&t.hasEncryptionKey,i=e?.streamAutoDetect!==false,a=r?e?.compressionAlgorithm??t.defaultCompressionAlgorithm:void 0,c=new exports.DduEncodeStream(s,e),o=[];if(r){let h=a??t.defaultCompressionAlgorithm,f=h==="brotli",d=M(e?.compressionLevel??t.defaultCompressionLevel,h),u=f?zlib.createBrotliCompress({params:{[zlib.constants.BROTLI_PARAM_QUALITY]:Math.min(11,Math.max(0,d))}}):zlib.createDeflate({level:Math.min(9,Math.max(0,d))});o.push(u);}if(n){let h=s.createEncryptionStream();h&&o.push(h);}return o.push(c),i&&o.push(new re(Oe(t.paddingChar,{compressionAlgorithm:a,encrypted:n}))),o.length===1?c:be(o)}function G(s,e){if(e?.streamAutoDetect??true)return new ne(s,e);let r=s.getCharSetInfo(),n=e?.compress??r.defaultCompress,i=(e?.encrypt??true)&&r.hasEncryptionKey,a=new exports.DduDecodeStream(s,e),c=[a];if(i){let o=s.createDecryptionStream();o&&c.push(o);}if(n){let f=(e?.compressionAlgorithm??r.defaultCompressionAlgorithm)==="brotli"?zlib.createBrotliDecompress():zlib.createInflate();c.push(f);}return c.length===1?a:be(c)}var x,re;exports.DduEncodeStream=void 0;exports.DduDecodeStream=void 0;var ne,W=ae(()=>{te();x="DDS1";re=class extends stream.Transform{prefix;emittedPrefix=false;constructor(e){super(),this.prefix=e;}_transform(e,t,r){try{this.emittedPrefix||(this.push(this.prefix),this.emittedPrefix=!0),this.push(e),r();}catch(n){r(n);}}};exports.DduEncodeStream=class extends stream.Transform{encoder;buffers;bufferOffset;totalLength;chunkSize;footerCompressionAlgorithm;footerEncrypted;constructor(e,t){super({...t,readableObjectMode:false,writableObjectMode:false}),this.encoder=e;let r=e.getCharSetInfo();this.buffers=[],this.bufferOffset=0,this.totalLength=0,this.footerCompressionAlgorithm=t?.compress??r.defaultCompress?t?.compressionAlgorithm??r.defaultCompressionAlgorithm:void 0,this.footerEncrypted=(t?.encrypt??true)&&r.hasEncryptionKey,this.chunkSize=this.calculateChunkSize(r.bitLength);}calculateChunkSize(e){let t=(i,a)=>a===0?i:t(a,i%a),r=8*e/t(8,e),n=Math.max(1,Math.floor(4096/r));return r*n}_transform(e,t,r){try{for(this.buffers.push(e),this.totalLength+=e.length;this.totalLength>=this.chunkSize;){let n=this.readBytes(this.chunkSize),i=this.encodeChunk(n,!1);this.push(i);}r();}catch(n){r(n);}}_flush(e){try{if(this.totalLength>0){let t=this.readBytes(this.totalLength),r=this.encodeChunk(t,!0);this.push(r);}e();}catch(t){e(t);}}encodeChunk(e,t){return this.encoder.encodeRawBuffer(e,{compressionAlgorithm:t?this.footerCompressionAlgorithm:void 0,encrypted:t?this.footerEncrypted:false,omitFooter:!t})}readBytes(e){if(e<=0||this.totalLength<e)return Buffer.alloc(0);let t=this.buffers[0];if(this.buffers.length===1&&t&&this.bufferOffset===0&&t.length===e)return this.buffers=[],this.totalLength=0,t;let r=Buffer.allocUnsafe(e),n=0;for(;n<e&&this.buffers.length>0;){let i=this.buffers[0],a=i.length-this.bufferOffset,c=Math.min(e-n,a);i.copy(r,n,this.bufferOffset,this.bufferOffset+c),n+=c,this.bufferOffset+=c,this.bufferOffset>=i.length&&(this.buffers.shift(),this.bufferOffset=0);}return this.totalLength-=e,r}},exports.DduDecodeStream=class extends stream.Transform{encoder;options;normalizedBuffer;chunkSize;chunkSeparator;separatorTail;constructor(e,t){super({...t,readableObjectMode:false,writableObjectMode:false}),this.encoder=e,this.options={...t,compress:false,checksum:false,encrypt:false},this.normalizedBuffer="";let r=e.getCharSetInfo();this.chunkSeparator=t?.chunkSeparator??r.defaultChunkSeparator,this.separatorTail="",this.chunkSize=1024;}_transform(e,t,r){try{this.appendNormalizedChunk(e.toString("utf-8"));let n=100;for(;this.normalizedBuffer.length>=this.chunkSize+n;){let i=this.normalizedBuffer.slice(0,this.chunkSize);this.normalizedBuffer=this.normalizedBuffer.slice(this.chunkSize);let a=this.encoder.decodeToBuffer(i,this.options);this.push(a);}r();}catch(n){r(n);}}_flush(e){try{if(this.separatorTail.length>0&&(this.normalizedBuffer+=D(this.separatorTail,this.chunkSeparator),this.separatorTail=""),this.normalizedBuffer.length>0){let t=this.encoder.decodeStreamToBuffer(this.normalizedBuffer,this.options);this.push(t),this.normalizedBuffer="";}e();}catch(t){e(t);}}appendNormalizedChunk(e){if(e.length===0)return;let t=Math.max(0,this.chunkSeparator.length-1);if(t===0){this.normalizedBuffer+=D(e,this.chunkSeparator);return}let r=this.separatorTail+e;if(r.length<=t){this.separatorTail=r;return}let n=r.length-t,i=r.slice(0,n);this.separatorTail=r.slice(n),this.normalizedBuffer+=D(i,this.chunkSeparator);}},ne=class extends stream.Transform{encoder;options;normalizedBuffer;chunkSeparator;separatorTail;paddingChar;headerLength;mode;innerStream;constructor(e,t){super({...t,readableObjectMode:false,writableObjectMode:false}),this.encoder=e,this.options={...t},this.normalizedBuffer="";let r=e.getCharSetInfo();this.paddingChar=r.paddingChar,this.headerLength=Ce(r.paddingChar),this.chunkSeparator=t?.chunkSeparator??r.defaultChunkSeparator,this.separatorTail="",this.mode="pending",this.innerStream=null;}_transform(e,t,r){try{if(this.appendNormalizedChunk(e.toString("utf-8")),this.maybeInitializeMode(!1),this.mode==="pipeline"){this.flushBufferedToInner(r);return}r();}catch(n){r(n);}}_flush(e){try{if(this.separatorTail.length>0&&(this.normalizedBuffer+=D(this.separatorTail,this.chunkSeparator),this.separatorTail=""),this.maybeInitializeMode(!0),this.mode==="pipeline"){this.finishInnerPipeline(e);return}if(this.normalizedBuffer.length>0){let t=this.encoder.decodeStreamToBuffer(this.normalizedBuffer,this.options);this.push(t),this.normalizedBuffer="";}e();}catch(t){e(t);}}appendNormalizedChunk(e){if(e.length===0)return;let t=Math.max(0,this.chunkSeparator.length-1);if(t===0){this.normalizedBuffer+=D(e,this.chunkSeparator);return}let r=this.separatorTail+e;if(r.length<=t){this.separatorTail=r;return}let n=r.length-t,i=r.slice(0,n);this.separatorTail=r.slice(n),this.normalizedBuffer+=D(i,this.chunkSeparator);}maybeInitializeMode(e){if(this.mode!=="pending")return;let t=this.paddingChar.length;if(this.normalizedBuffer.length<t){e&&this.normalizedBuffer.length>0&&(this.mode="legacy");return}if(!this.normalizedBuffer.startsWith(this.paddingChar)){this.mode="legacy";return}if(this.normalizedBuffer.length<this.headerLength){if(e)throw new Error("[DduStream decode] Incomplete stream header");return}let r=this.normalizedBuffer.slice(0,this.headerLength),n=ze(r,this.paddingChar);if(!n){this.mode="legacy";return}this.mode="pipeline",this.normalizedBuffer=this.normalizedBuffer.slice(this.headerLength),this.initializeInnerPipeline(n);}initializeInnerPipeline(e){if(e.encrypted&&!this.encoder.getCharSetInfo().hasEncryptionKey)throw new Error("[DduStream decode] Encrypted stream requires an encryptionKey");let t=G(this.encoder,{...this.options,streamAutoDetect:false,compress:!!e.compressionAlgorithm,compressionAlgorithm:e.compressionAlgorithm,encrypt:e.encrypted});t.on("data",r=>{this.push(r);}),t.on("error",r=>{this.destroy(r);}),this.innerStream=t;}flushBufferedToInner(e){if(!this.innerStream||this.normalizedBuffer.length===0){e();return}let t=this.normalizedBuffer;if(this.normalizedBuffer="",!this.innerStream.write(Buffer.from(t,"utf-8"))){this.innerStream.once("drain",()=>e());return}e();}finishInnerPipeline(e){if(!this.innerStream){e();return}let t=this.innerStream,r=()=>{t.once("end",()=>e()),t.end();};if(this.normalizedBuffer.length>0){let n=this.normalizedBuffer;if(this.normalizedBuffer="",!t.write(Buffer.from(n,"utf-8"))){t.once("drain",r);return}}r();}};});var J=(r=>(r.DDU="ddu",r.DDU_V1="ddu_v1",r.ONECHARSET="oneCharSet",r))(J||{}),Z={dduSetSymbol:"ddu",usePowerOfTwo:true,requiredLength:64,bitLength:6};var De={symbol:"ddu",charSet:["\uB70C","\uB568","\uC774","\uC6B0","\uC57C","\uB4C0","\uB31C","\uB3A8"],codaChar:["","\u3131","\u3132","\u3137","\u3148","\u3147","\u3145","\u3146"],maxRequiredLength:64,bitLength:6,paddingChar:"\uBB50",useRepeatPadding:true},Ee={symbol:"ddu_v1",charSet:["\uB70C","\uB568","\uC774","\uC6B0","\uC57C","!","?","."],maxRequiredLength:8,bitLength:3,paddingChar:"\uBB50"},ve={symbol:"oneCharSet",charSet:["A","s","q","r","0","z","3","t","y","1","5","2","4","E","B","C","Q","F","R","T","U","W","V","X","Y","Z","b","a","c","d","D","G","L","H","I","-","J","K","M","O","N","f","e","h","g","P","i","S","k","l","m","u","j","v","n","o","p","9","w","6","7","8","x","_"],paddingChar:"=",maxRequiredLength:64,bitLength:6};function z(s){switch(s){case "ddu":return De;case "ddu_v1":return Ee;case "oneCharSet":return ve;default:return}}function I(s){return crypto.createHash("sha256").update(s).digest()}function U(s,e){let t=crypto.randomBytes(12),r=crypto.createCipheriv("aes-256-gcm",e,t),n=Buffer.concat([r.update(s),r.final()]),i=r.getAuthTag();return Buffer.concat([t,i,n])}function K(s,e){if(s.length<28)throw new Error("[decrypt] Invalid encrypted data: too short");let t=s.subarray(0,12),r=s.subarray(12,28),n=s.subarray(28),i=crypto.createDecipheriv("aes-256-gcm",e,t);return i.setAuthTag(r),Buffer.concat([i.update(n),i.final()])}function fe(s,e){if(s.length<28)throw new Error("[decrypt] Invalid encrypted stream data: too short");let t=s.subarray(0,12),r=s.subarray(s.length-16),n=s.subarray(12,s.length-16),i=crypto.createDecipheriv("aes-256-gcm",e,t);return i.setAuthTag(r),Buffer.concat([i.update(n),i.final()])}function R(s,e,t="brotli decompress"){if(e===Number.POSITIVE_INFINITY)return zlib.brotliDecompressSync(s);try{let r=zlib.brotliDecompressSync(s,{maxOutputLength:e});if(r.length>e)throw new Error(`[${t}] Decompressed data exceeds limit. Size: ${r.length} bytes, Limit: ${e} bytes`);return r}catch(r){let n=r,i=String(n?.message??"").toLowerCase();throw String(n?.code??"")==="ERR_BUFFER_TOO_LARGE"||i.includes("cannot create a buffer larger")||i.includes("buffer larger than")||i.includes("output length")?new Error(`[${t}] Decompressed data exceeds limit. Limit: ${e} bytes`,{cause:r}):r}}function H(s,e,t="inflate"){if(e===Number.POSITIVE_INFINITY)return zlib.inflateSync(s);try{return zlib.inflateSync(s,{maxOutputLength:e})}catch(r){let n=r,i=String(n?.message??""),a=String(n?.code??"");if(i.toLowerCase().includes("maxoutputlength")||i.toLowerCase().includes("unknown option")||a==="ERR_INVALID_ARG_VALUE"){let c=zlib.inflateSync(s);if(c.length>e)throw new Error(`[${t}] Decompressed data exceeds limit. Size: ${c.length} bytes, Limit: ${e} bytes`,{cause:r});return c}throw a==="ERR_BUFFER_TOO_LARGE"||i.toLowerCase().includes("output length")||i.toLowerCase().includes("buffer too large")?new Error(`[${t}] Decompressed data exceeds limit. Limit: ${e} bytes`,{cause:r}):r}}var _=class extends stream.Transform{cipher;constructor(e){super();let t=crypto.randomBytes(12);this.cipher=crypto.createCipheriv("aes-256-gcm",e,t),this.push(t);}_transform(e,t,r){let n=this.cipher.update(e);n.length>0&&this.push(n),r();}_flush(e){try{let t=this.cipher.final();t.length>0&&this.push(t),this.push(this.cipher.getAuthTag()),e();}catch(t){e(t instanceof Error?t:new Error(String(t)));}}},N=class extends stream.Transform{keyHash;iv=null;decipher=null;tail=Buffer.alloc(0);constructor(e){super(),this.keyHash=e;}_transform(e,t,r){if(this.tail=Buffer.concat([this.tail,e]),!this.iv&&this.tail.length>=12&&(this.iv=this.tail.subarray(0,12),this.decipher=crypto.createDecipheriv("aes-256-gcm",this.keyHash,this.iv),this.tail=this.tail.subarray(12)),this.decipher&&this.tail.length>16){let n=this.tail.length-16,i=this.tail.subarray(0,n);this.tail=this.tail.subarray(n);try{let a=this.decipher.update(i);a.length>0&&this.push(a);}catch(a){return r(a instanceof Error?a:new Error(String(a)))}}r();}_flush(e){if(!this.decipher||this.tail.length!==16)return e(new Error("[GcmDecryptStream] Invalid encrypted data: too short or no auth tag"));try{this.decipher.setAuthTag(this.tail);let t=this.decipher.final();t.length>0&&this.push(t),e();}catch(t){e(t instanceof Error?t:new Error(String(t)));}}};te();var B=8,Y=255,He=65536,$e=64*1024*1024,Fe=64*1024*1024,T={START:0,ENCRYPT:15,CHECKSUM:20,COMPRESS:40,ENCODE:50,DONE:100},P={START:0,DECODE:20,DECOMPRESS:50,CHECKSUM:70,DECRYPT:85,DONE:100},O=class{defaultEncoding="utf-8";dduChar;paddingChar;bitLength;usePowerOfTwo;encoding;defaultCompress;defaultMaxDecodedBytes;defaultMaxDecompressedBytes;dduBinaryLookup=new Map;isPredefinedCharSet;effectiveBitLength;maxBinaryValue;fastAsciiLookup=null;useAsciiLookup=false;urlSafe;encryptionKeyHash;defaultChecksum;defaultChunkSize;defaultChunkSeparator;defaultCompressionLevel;defaultCompressionAlgorithm;useRepeatPadding;constructor(e,t,r){let n=r?.throwOnError??r?.useBuildErrorReturn??false,i=this.resolveInitialCharSet(e,t,r,n),a=this.normalizeCharSet(i,n,r);this.dduChar=a.charSet,this.paddingChar=a.padding,this.isPredefinedCharSet=a.isPredefined,this.encoding=r?.encoding??this.defaultEncoding,this.defaultCompress=r?.compress??false,this.defaultMaxDecodedBytes=this.normalizeLimit(r?.maxDecodedBytes,$e,n,"maxDecodedBytes"),this.defaultMaxDecompressedBytes=this.normalizeLimit(r?.maxDecompressedBytes,Fe,n,"maxDecompressedBytes");let c=this.dduChar.length;this.usePowerOfTwo=c>0&&(c&c-1)===0;let o=this.getBitLength(c);this.bitLength=this.usePowerOfTwo?this.getLargestPowerOfTwoExponent(c):o,this.effectiveBitLength=this.usePowerOfTwo?this.bitLength:o,this.maxBinaryValue=this.effectiveBitLength<31?1<<this.effectiveBitLength:Math.pow(2,this.effectiveBitLength);{let f=true;for(let d=0;d<c;d++)if(this.dduChar[d].charCodeAt(0)>=128){f=false;break}if(f){this.fastAsciiLookup=new Int16Array(128).fill(-1);for(let d=0;d<c;d++)this.fastAsciiLookup[this.dduChar[d].charCodeAt(0)]=d;this.useAsciiLookup=true;}}for(let f=0;f<c;f++)this.dduBinaryLookup.set(this.dduChar[f],f);this.isPredefinedCharSet||this.validateCombinationDuplicates(this.dduChar,this.paddingChar,c);let h=r?.urlSafe??false;this.urlSafe=h?this.isUrlSafeCompatible(this.dduChar,this.paddingChar,n):false,this.encryptionKeyHash=r?.encryptionKey?I(r.encryptionKey):void 0,this.defaultChecksum=r?.checksum??false,this.defaultChunkSize=r?.chunkSize,this.defaultChunkSeparator=r?.chunkSeparator??`
|
|
4
|
+
`,this.defaultCompressionAlgorithm=r?.compressionAlgorithm??"deflate",this.defaultCompressionLevel=M(r?.compressionLevel,this.defaultCompressionAlgorithm),this.useRepeatPadding=r?.useRepeatPadding??i.useRepeatPadding??false;}encode(e,t){return this.encodeInternal(e,t).encoded}encodeInternal(e,t){let r=t?.compress??this.defaultCompress,n=t?.checksum??this.defaultChecksum,i=(t?.encrypt??true)&&!!this.encryptionKeyHash,a=t?.omitFooter??false,c=t?.chunkSize??this.defaultChunkSize,o=t?.chunkSeparator??this.defaultChunkSeparator,h=t?.onProgress,f=!!c&&c>0&&!n&&!this.urlSafe,d=typeof e=="string"?Buffer.from(e,this.encoding):e,u=d.length;h&&h({processedBytes:0,totalBytes:u,percent:T.START,stage:"start"});let l=false;i&&(d=this.encryptData(d),l=true,h&&h({processedBytes:0,totalBytes:u,percent:T.ENCRYPT,stage:"encrypt"}));let p="";n&&(p=ee(d),h&&h({processedBytes:0,totalBytes:u,percent:T.CHECKSUM,stage:"checksum"}));let m="",g;if(r){let S=t?.compressionAlgorithm??this.defaultCompressionAlgorithm,C=S==="brotli",b=M(t?.compressionLevel??this.defaultCompressionLevel,S),w=C?zlib.brotliCompressSync(d,{params:{[zlib.constants.BROTLI_PARAM_QUALITY]:Math.min(11,Math.max(0,b))}}):zlib.deflateSync(d,{level:Math.min(9,Math.max(0,b))});g=w.length,w.length<d.length&&(d=w,m=C?v:E),h&&h({processedBytes:Math.floor(u*.4),totalBytes:u,percent:T.COMPRESS,stage:"compress"});}h&&h({processedBytes:Math.floor(u*.5),totalBytes:u,percent:T.ENCODE,stage:"encode"});let y=this.encodeFast(d,m,l,a,f?c:void 0,f?o:void 0);return n&&p&&(y=y+$+p),this.urlSafe&&(y=me(y)),!f&&c&&c>0&&(y=ge(y,c,o)),h&&h({processedBytes:u,totalBytes:u,percent:T.DONE,stage:"done"}),{encoded:y,compressedSize:g}}decodeToBuffer(e,t){let r=t?.checksum??this.defaultChecksum,n=t?.compress!==false,i=t?.encrypt!==false,a=t?.onProgress,c=e,o=e.length;a&&a({processedBytes:0,totalBytes:o,percent:P.START,stage:"start"});let h=t?.chunkSeparator??this.defaultChunkSeparator;c=D(c,h),this.urlSafe&&(c=pe(c));let f=null;if(r){let S=ye(c);f=S.checksum,c=S.data;}let{cleanedInput:d,paddingBits:u,compressionAlgorithm:l,isEncrypted:p}=this.parseFooter(c);if(p&&i&&!this.encryptionKeyHash)throw new Error("[Ddu64 decode] Encrypted payload requires an encryptionKey");this.assertEncodedInputAligned(d);let m=this.normalizeLimit(t?.maxDecodedBytes,this.defaultMaxDecodedBytes,true,"maxDecodedBytes"),g=this.estimateDecodedBytes(d.length,u);if(g>m)throw new Error(`[Ddu64 decode] Decoded output exceeds limit. Estimated: ${g} bytes, Limit: ${m} bytes`);a&&a({processedBytes:Math.floor(o*.2),totalBytes:o,percent:P.DECODE,stage:"decode"});let y=this.decodeFast(d,u);if(l&&n){a&&a({processedBytes:Math.floor(o*.5),totalBytes:o,percent:P.DECOMPRESS,stage:"decompress"});let S=this.normalizeLimit(t?.maxDecompressedBytes,this.defaultMaxDecompressedBytes,true,"maxDecompressedBytes");l==="brotli"||t?.compressionAlgorithm==="brotli"||!t?.compressionAlgorithm&&this.defaultCompressionAlgorithm==="brotli"?y=R(y,S,"Ddu64 decode"):y=this.inflateWithLimit(y,S);}if(f){a&&a({processedBytes:Math.floor(o*.7),totalBytes:o,percent:P.CHECKSUM,stage:"checksum"});let S=ee(y);if(S!==f)throw new Error(`[Ddu64 decode] Checksum mismatch. Expected: ${f}, Got: ${S}`)}return p&&this.encryptionKeyHash&&i&&(a&&a({processedBytes:Math.floor(o*.85),totalBytes:o,percent:P.DECRYPT,stage:"decrypt"}),y=this.decryptData(y)),a&&a({processedBytes:o,totalBytes:o,percent:P.DONE,stage:"done"}),y}decode(e,t){return this.decodeToBuffer(e,t).toString(this.encoding)}decodeStreamToBuffer(e,t){let r=t?.compress!==false,n=t?.encrypt!==false,{decoded:i,compressionAlgorithm:a,isEncrypted:c}=this.decodeRaw(e,t),o=i;if(c&&this.encryptionKeyHash&&n&&(o=this.decryptStreamData(o)),a&&r){let h=this.normalizeLimit(t?.maxDecompressedBytes,this.defaultMaxDecompressedBytes,true,"maxDecompressedBytes");a==="brotli"?o=R(o,h,"Ddu64 decode"):o=this.inflateWithLimit(o,h);}return o}decodeRaw(e,t){let r=t?.chunkSeparator??this.defaultChunkSeparator,n=D(e,r),{cleanedInput:i,paddingBits:a,compressionAlgorithm:c,isEncrypted:o}=this.parseFooter(n);if(o&&t?.encrypt!==false&&!this.encryptionKeyHash)throw new Error("[Ddu64 decode] Encrypted payload requires an encryptionKey");this.assertEncodedInputAligned(i);let h=this.normalizeLimit(t?.maxDecodedBytes,this.defaultMaxDecodedBytes,true,"maxDecodedBytes"),f=this.estimateDecodedBytes(i.length,a);if(f>h)throw new Error(`[Ddu64 decode] Decoded output exceeds limit. Estimated: ${f} bytes, Limit: ${h} bytes`);return {decoded:this.decodeFast(i,a),compressionAlgorithm:c,isEncrypted:o}}getCharSetInfo(){return {charSet:[...this.dduChar],paddingChar:this.paddingChar,bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,encoding:this.encoding,defaultCompress:this.defaultCompress,defaultMaxDecodedBytes:this.defaultMaxDecodedBytes,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,urlSafe:this.urlSafe,hasEncryptionKey:!!this.encryptionKeyHash,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm}}encodeRawBuffer(e,t){let r=t?.compressionAlgorithm==="brotli"?v:t?.compressionAlgorithm==="deflate"?E:"";return this.encodeFast(e,r,t?.encrypted,t?.omitFooter)}getStats(e,t){let r=t?.compress??this.defaultCompress,i=(typeof e=="string"?Buffer.from(e,this.encoding):e).length,{encoded:a,compressedSize:c}=this.encodeInternal(e,t),o=a.length,h=i>0?o/i:0,f=r&&c!==void 0&&i>0?c/i:void 0;return {originalSize:i,encodedSize:o,compressedSize:c,compressionRatio:f,expansionRatio:h,charsetSize:this.dduChar.length,bitLength:this.bitLength}}async encodeAsync(e,t){let r=typeof e=="string"?Buffer.from(e,this.encoding):e,n=64*1024,i=t?.compress??this.defaultCompress,a=t?.checksum??this.defaultChecksum,c=(t?.encrypt??true)&&!!this.encryptionKeyHash;if(r.length<=n||i||a||c||this.urlSafe)return new Promise((h,f)=>{setImmediate(()=>{try{h(this.encode(r,t));}catch(d){f(d);}});});let{createEncodeStream:o}=await Promise.resolve().then(()=>(W(),ie));return new Promise((h,f)=>{let d=o(this,t),u=[];d.on("data",m=>u.push(m.toString())),d.on("end",()=>h(u.join(""))),d.on("error",f);let l=0;function p(){try{for(;l<r.length;){let m=Math.min(l+n,r.length),g=r.subarray(l,m);if(l=m,!d.write(g)){d.once("drain",p);return}if(l%(n*16)===0){setImmediate(p);return}}d.end();}catch(m){d.destroy(m);}}p();})}async decodeAsync(e,t){return (await this.decodeToBufferAsync(e,t)).toString(this.encoding)}async decodeToBufferAsync(e,t){let i=(t?.checksum??this.defaultChecksum)||this.urlSafe||!!this.defaultChunkSize||!!t?.chunkSize;if(e.length<=65536)return new Promise((f,d)=>{setImmediate(()=>{try{f(this.decodeToBuffer(e,t));}catch(u){d(u);}});});let a=i?null:this.parseFooter(e),c=(t?.compress??this.defaultCompress)||!!a?.compressionAlgorithm,o=(t?.encrypt??true)&&!!this.encryptionKeyHash||!!a?.isEncrypted;if(i||c||o)return new Promise((f,d)=>{setImmediate(()=>{try{f(this.decodeToBuffer(e,t));}catch(u){d(u);}});});let{createDecodeStream:h}=await Promise.resolve().then(()=>(W(),ie));return new Promise((f,d)=>{let u=h(this,t),l=[];u.on("data",g=>l.push(g)),u.on("end",()=>f(Buffer.concat(l))),u.on("error",d);let p=0;function m(){try{for(;p<e.length;){let g=Math.min(p+65536,e.length),y=e.slice(p,g);if(p=g,!u.write(y)){u.once("drain",m);return}if(p%(65536*16)===0){setImmediate(m);return}}u.end();}catch(g){u.destroy(g);}}m();})}encryptData(e){if(!this.encryptionKeyHash)throw new Error("[Ddu64 encrypt] Encryption key is not set");return U(e,this.encryptionKeyHash)}decryptData(e){if(!this.encryptionKeyHash)throw new Error("[Ddu64 decrypt] Encryption key is not set");return K(e,this.encryptionKeyHash)}decryptStreamData(e){if(!this.encryptionKeyHash)throw new Error("[Ddu64 decrypt] Encryption key is not set");return fe(e,this.encryptionKeyHash)}createEncryptionStream(){if(this.encryptionKeyHash)return new _(this.encryptionKeyHash)}createDecryptionStream(){if(this.encryptionKeyHash)return new N(this.encryptionKeyHash)}getLargestPowerOfTwoExponent(e){return Math.floor(Math.log2(e))}getBitLength(e){return Math.ceil(Math.log2(e))}normalizeLimit(e,t,r,n){if(e===void 0)return t;if(e===Number.POSITIVE_INFINITY)return Number.POSITIVE_INFINITY;if(!Number.isFinite(e)||e<=0){if(r)throw new Error(`[Ddu64 options] Invalid ${n}. Must be a positive finite number or Infinity.`);return t}return Math.floor(e)}estimateDecodedBytes(e,t){if(e===0)return 0;if(t<0||t>=this.effectiveBitLength)throw new Error(`[Ddu64 decode] Invalid padding bits: ${t}`);let r=this.usePowerOfTwo?1:2,i=Math.ceil(e/r)*this.effectiveBitLength-t;if(i<0)throw new Error("[Ddu64 decode] Invalid decoded bit length");return Math.ceil(i/B)}assertEncodedInputAligned(e){if(!this.usePowerOfTwo&&e.length%2!==0)throw new Error(`[Ddu64 decode] Invalid encoded length for variable charset. Expected multiple of 2, got ${e.length}`)}inflateWithLimit(e,t){return H(e,t,"Ddu64 decode")}parseFooter(e){let t=e.length,r=this.paddingChar,n=r.length,i={cleanedInput:e,paddingBits:0,isEncrypted:false};if(t<n)return i;let c=Math.max(0,this.effectiveBitLength-1).toString().length;for(let o=Math.min(c,t);o>=1;o--){let h=t-o,f=true;for(let y=h;y<t;y++){let S=e.charCodeAt(y);if(S<48||S>57){f=false;break}}if(!f)continue;let d=e.substring(h),u=parseInt(d,10);if(Number.isNaN(u)||u<0||u>=this.effectiveBitLength||d!==u.toString())continue;let l=h,p=false,m;l>=L.length&&e.substring(l-L.length,l)===L&&(p=true,l-=L.length),l>=E.length&&e.substring(l-E.length,l)===E?(m="deflate",l-=E.length):l>=v.length&&e.substring(l-v.length,l)===v&&(m="brotli",l-=v.length);let g=l-n;if(g>=0&&e.substring(g,l)===r)return {cleanedInput:e.substring(0,g),paddingBits:u,compressionAlgorithm:m,isEncrypted:p}}if(e.endsWith(r)){let o=0,h=t;for(;h>=n&&e.substring(h-n,h)===r;)o++,h-=n;if(o>0){let f=o*2;if(f<this.effectiveBitLength)return {cleanedInput:e.substring(0,h),paddingBits:f,isEncrypted:false}}}return i}encodeFast(e,t,r,n=false,i,a){let c=e.length;if(c===0)return "";let{dduChar:o,effectiveBitLength:h,paddingChar:f}=this,d=o.length,u=c*B,l=Math.ceil(u/h),p=this.usePowerOfTwo?l:l*2,m=new Array(p+3),g=0,y=0,S=0;if(this.usePowerOfTwo){let C=(1<<h)-1;for(let b=0;b<c;b++)for(y=y<<B|e[b],S+=B;S>=h;)S-=h,m[g++]=o[y>>S&C],y&=(1<<S)-1;}else for(let C=0;C<c;C++)for(y=y<<B|e[C],S+=B;S>=h;){S-=h;let b=y>>S,w=b/d|0;m[g++]=o[w],m[g++]=o[b-w*d],y&=(1<<S)-1;}if(S>0){let C=h-S,b=y<<C;if(this.usePowerOfTwo)m[g++]=o[b];else {let w=b/d|0;m[g++]=o[w],m[g++]=o[b-w*d];}if(this.useRepeatPadding&&!t&&!r){if(!n){let w=C>>1;for(let oe=0;oe<w;oe++)m[g++]=f;}}else {if(n)throw new Error("[Ddu64 encode] Cannot omit footer when padding bits remain");m[g++]=f,m[g++]=t+(r?L:"")+C.toString();}}else !n&&(t||r)&&(m[g++]=f,m[g++]=t+(r?L:"")+"0");return this.serializeEncodedParts(m,g,i,a)}decodeFast(e,t){let r=e.length;if(r===0)return Buffer.alloc(0);let{effectiveBitLength:n}=this,i=this.dduChar.length,a=this.usePowerOfTwo?1:2,c=Math.ceil(r/a),o=Math.ceil((c*n-t)/B),h=new Uint8Array(o+1),f=0,d=0,u=0;if(this.usePowerOfTwo)if(this.useAsciiLookup&&this.fastAsciiLookup){let l=this.fastAsciiLookup;for(let p=0;p<r;p+=a){let m=e.charCodeAt(p),g=m<128?l[m]:-1;if(g<0)throw new Error(`[Ddu64 decode] Invalid character "${e[p]}" at ${p}`);for(d=d<<n|g,u+=n,p+a>=r&&t>0&&(d>>=t,u-=t);u>=B;)u-=B,h[f++]=d>>u&Y,d&=(1<<u)-1;}}else {let l=this.dduBinaryLookup;for(let p=0;p<r;p+=a){let m=e[p],g=l.get(m);if(g===void 0)throw new Error(`[Ddu64 decode] Invalid character "${m}" at ${p}`);for(d=d<<n|g,u+=n,p+a>=r&&t>0&&(d>>=t,u-=t);u>=B;)u-=B,h[f++]=d>>u&Y,d&=(1<<u)-1;}}else if(this.useAsciiLookup&&this.fastAsciiLookup){let l=this.fastAsciiLookup,p=this.maxBinaryValue;for(let m=0;m<r;m+=a){let g=e.charCodeAt(m),y=e.charCodeAt(m+1),S=g<128?l[g]:-1,C=y<128?l[y]:-1;if(S<0)throw new Error(`[Ddu64 decode] Invalid character "${e[m]}" at ${m}`);if(C<0)throw new Error(`[Ddu64 decode] Invalid character "${e[m+1]}" at ${m+1}`);let b=S*i+C;if(b>=p)throw new Error(`[Ddu64 decode] Value ${b} exceeds range`);for(d=d<<n|b,u+=n,m+a>=r&&t>0&&(d>>=t,u-=t);u>=B;)u-=B,h[f++]=d>>u&Y,d&=(1<<u)-1;}}else {let l=this.dduBinaryLookup;for(let p=0;p<r;p+=a){let m=e[p],g=e[p+1],y=l.get(m),S=l.get(g);if(y===void 0)throw new Error(`[Ddu64 decode] Invalid character "${m}" at ${p}`);if(S===void 0)throw new Error(`[Ddu64 decode] Invalid character "${g}" at ${p+1}`);let C=y*i+S;if(C>=this.maxBinaryValue)throw new Error(`[Ddu64 decode] Value ${C} exceeds range`);for(d=d<<n|C,u+=n,p+a>=r&&t>0&&(d>>=t,u-=t);u>=B;)u-=B,h[f++]=d>>u&Y,d&=(1<<u)-1;}}return Buffer.from(h.subarray(0,f))}serializeEncodedParts(e,t,r,n){if(e.length=t,!r||r<=0)return e.join("");let i=n??this.defaultChunkSeparator,a=[],c=0;for(let o=0;o<t;o++){let h=e[o],f=0;for(;f<h.length;){let d=r-c,u=Math.min(d,h.length-f);a.push(h.slice(f,f+u)),f+=u,c+=u,c===r&&(f<h.length||o<t-1)&&(a.push(i),c=0);}}return a.join("")}normalizeCharSet(e,t,r){let n=[e,null];for(let a of n){let c=a?{...a}:this.getFallbackCharSet(r);try{let o=c.charSet,h=c.requiredLength,f=Array.from(new Set(o));if(f.length!==o.length){if(t){let l=o.filter((p,m)=>o.indexOf(p)!==m);throw new Error(`[Ddu64 normalizeCharSet] Character set contains duplicate characters: [${[...new Set(l)].join(", ")}]`)}o=f,c.isPredefined||(h=o.length);}if(o.length<h)throw new Error(`[Ddu64 normalizeCharSet] Insufficient characters. Required: ${h}, Has: ${o.length}`);if(h<2)throw new Error("[Ddu64 normalizeCharSet] At least 2 unique characters required.");if(o.length===0)throw new Error("[Ddu64 normalizeCharSet] Empty charset.");if(o.find(l=>l.length!==1)){if(t)throw new Error("[Ddu64 normalizeCharSet] Multi-character symbols are not supported. All charset characters must have length 1.");continue}if(o.length>He){if(t)throw new Error("[Ddu64 normalizeCharSet] Charset size exceeds maximum supported size of 65536.");continue}if(c.padding.length!==1)throw new Error(`[Ddu64 normalizeCharSet] Padding length mismatch. Expected 1, got ${c.padding.length}`);if(o.includes(c.padding)){if(t)throw new Error(`[Ddu64 normalizeCharSet] Padding character "${c.padding}" conflicts with charset.`);o=o.filter(l=>l!==c.padding);}for(let l of o)if(l.includes(`
|
|
5
|
+
`)||l.includes("\r"))throw new Error("[Ddu64 normalizeCharSet] Newline and carriage return characters are reserved for chunk normalization and cannot be used in charset.");if(c.padding.includes(`
|
|
6
|
+
`)||c.padding.includes("\r"))throw new Error("[Ddu64 normalizeCharSet] Newline and carriage return characters are reserved for chunk normalization and cannot be used in padding.");return {charSet:o.length===h?o:o.slice(0,h),padding:c.padding,isPredefined:c.isPredefined}}catch(o){if(t)throw o}}let i=this.getFallbackCharSet(r);return {charSet:i.charSet.slice(0,i.requiredLength),padding:i.padding,isPredefined:true}}resolveInitialCharSet(e,t,r,n){let i=(a,c,o,h,f)=>{if(this.shouldUsePowerOfTwo(o,r?.usePowerOfTwo)&&o>0){let l=this.getLargestPowerOfTwoExponent(o),p=1<<l;return {charSet:a.length===p?a:a.slice(0,p),padding:c,requiredLength:p,bitLength:l,isPredefined:h,useRepeatPadding:f}}return {charSet:a.length===o?a:a.slice(0,o),padding:c,requiredLength:o,bitLength:o>0?this.getBitLength(o):0,isPredefined:h,useRepeatPadding:f}};try{let a=e??r?.dduChar,c=t??r?.paddingChar;if(a){if(!c)throw new Error("[Ddu64 Constructor] paddingChar is required when dduChar is provided.");let d=typeof a=="string"?[...a.trim()]:[...a],u=r?.codaChar,l=u?!0:r?.useRepeatPadding??!1;if(u&&u.length>0&&(d=F(d,u)),n&&new Set(d).size!==d.length){let g=d.filter((y,S)=>d.indexOf(y)!==S);throw new Error(`[Ddu64 Constructor] Character set contains duplicate characters: [${[...new Set(g)].join(", ")}]`)}let p=r?.requiredLength??d.length;if(d.length<p)throw new Error("[Ddu64 Constructor] Insufficient characters.");return i(d,c,p,!1,l)}let o=r?.dduSetSymbol??Z.dduSetSymbol??"ddu",h=this.getCharSetOrThrow(o),f=h.codaChar?F(h.charSet,h.codaChar):h.charSet;return i(f,h.paddingChar,h.maxRequiredLength,!0,h.useRepeatPadding)}catch(a){if(n)throw a;return this.getFallbackCharSet(r)}}getFallbackCharSet(e){let t=e?.dduSetSymbol??Z.dduSetSymbol??"oneCharSet",r=z(t)??z("oneCharSet");if(!r)throw new Error("Critical: No fallback CharSet available");return {charSet:r.codaChar?F(r.charSet,r.codaChar):r.charSet,padding:r.paddingChar,requiredLength:r.maxRequiredLength,bitLength:r.bitLength,isPredefined:true,useRepeatPadding:r.useRepeatPadding}}shouldUsePowerOfTwo(e,t){return t!==void 0?t?e>0:false:e>0&&(e&e-1)===0}getCharSetOrThrow(e){let t=z(e);if(!t)throw new Error(`CharSet with symbol ${e} not found`);return t}isUrlSafeCompatible(e,t,r){let n=le;for(let i of n){for(let a of e)if(a.includes(i)){let c=`[Ddu64 Constructor] URL-Safe mode conflict: charset character "${a}" contains "${i}" which conflicts with URL-safe encoding.`;if(r)throw new Error(c);return false}if(t.includes(i)){let a=`[Ddu64 Constructor] URL-Safe mode conflict: padding character "${t}" contains "${i}" which conflicts with URL-safe encoding.`;if(r)throw new Error(a);return false}}return true}validateCombinationDuplicates(e,t,r){if(r>256)return;let n=Math.min(e.length,r),i=e.slice(0,n),a=new Set,c=(o,h)=>{if(a.has(o))throw new Error(`Combination conflict: ${h}`);a.add(o);};for(let o=0;o<i.length;o++)a.add(i[o]);a.add(t);for(let o=0;o<i.length;o++){let h=i[o];for(let f=0;f<i.length;f++)c(h+i[f],`"${h}" + "${i[f]}"`);c(h+t,`"${h}" + padding`),c(t+h,`padding + "${h}"`);}c(t+t,"double padding");}};var V=class s{chars=[];constructor(){}static create(){return new s}static fromUnicodeRange(e,t){return new s().addUnicodeRange(e,t)}static fromString(e){return new s().addString(e)}static base64(){return new s().addString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")}static base32(){return new s().addString("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")}static uppercase(){return s.fromUnicodeRange(65,90)}static lowercase(){return s.fromUnicodeRange(97,122)}static digits(){return s.fromUnicodeRange(48,57)}static hangulJamo(){return new s().addUnicodeRange(4352,4370).addUnicodeRange(4449,4469).addUnicodeRange(4520,4546)}addUnicodeRange(e,t){for(let r=e;r<=t;r++)this.chars.push(String.fromCodePoint(r));return this}addString(e){return typeof e=="string"?this.chars.push(...e):this.chars.push(...e),this}add(...e){return this.chars.push(...e),this}excludeConfusing(){let e=new Set(["0","O","o","1","l","I","i","|","L"]);return this.chars=this.chars.filter(t=>!e.has(t)),this}exclude(...e){let t=new Set(e);return this.chars=this.chars.filter(r=>!t.has(r)),this}excludeUrlUnsafe(){let e=new Set(["+","/","=","?","&","#","%"," "]);return this.chars=this.chars.filter(t=>!e.has(t)),this}unique(){return this.chars=[...new Set(this.chars)],this}shuffle(e){let t=e!==void 0?this.seededRandom(e):Math.random;for(let r=this.chars.length-1;r>0;r--){let n=Math.floor(t()*(r+1));[this.chars[r],this.chars[n]]=[this.chars[n],this.chars[r]];}return this}seededRandom(e){let t=e|0||1;return ()=>(t^=t<<13,t^=t>>17,t^=t<<5,(t>>>0)/4294967296)}limit(e){return this.chars=this.chars.slice(0,e),this}limitToPowerOfTwo(){let e=this.chars.length;if(e===0)return this;let t=1<<Math.floor(Math.log2(e));return this.chars=this.chars.slice(0,t),this}sort(){return this.chars.sort(),this}reverse(){return this.chars.reverse(),this}get length(){return this.chars.length}buildString(){return this.chars.join("")}build(){return [...this.chars]}buildWithPadding(e){let t=[...this.chars],r=e;if(!r){let n=["=",".","_","-","~","!"];for(let i of n)if(!t.includes(i)){r=i;break}if(!r)throw new Error("Cannot find suitable padding character")}return {charset:t,padding:r}}};var j=class s{steps=[];compress(e=9,t="deflate"){return this.steps.push({type:"compress",level:e,algorithm:t}),this}decompress(e,t="deflate"){return this.steps.push({type:"decompress",maxDecompressedBytes:e,algorithm:t}),this}encrypt(e){return this.steps.push({type:"encrypt",key:e}),this}decrypt(e){return this.steps.push({type:"decrypt",key:e}),this}encode(e){return this.steps.push({type:"encode",encoder:e}),this}decode(e){return this.steps.push({type:"decode",encoder:e}),this}encodeWith(e,t,r){let n=new O(e,t,r);return this.encode(n)}transform(e){return this.steps.push({type:"transform",fn:e}),this}transformString(e){return this.steps.push({type:"transformString",fn:e}),this}reverse(){let e=new s;return e.steps=this.steps.slice().reverse().map(t=>{switch(t.type){case "compress":return {type:"decompress",algorithm:t.algorithm};case "decompress":return {type:"compress",level:9,algorithm:t.algorithm};case "encrypt":return {type:"decrypt",key:t.key};case "decrypt":return {type:"encrypt",key:t.key};case "encode":return {type:"decode",encoder:t.encoder};case "decode":return {type:"encode",encoder:t.encoder};case "transform":case "transformString":throw new Error(`[DduPipeline reverse] Cannot reverse "${t.type}" step. Custom transform functions are not reversible. Use explicit encode/decode pairs instead.`)}}),e}process(e){let t=e;for(let r of this.steps)t=this.executeStep(r,t);return t}processToString(e,t="utf-8"){let r=this.process(e);return typeof r=="string"?r:r.toString(t)}processToBuffer(e,t="utf-8"){let r=this.process(e);return Buffer.isBuffer(r)?r:Buffer.from(r,t)}executeStep(e,t){switch(e.type){case "compress":return this.compressData(this.toBuffer(t),e.level??9,e.algorithm??"deflate");case "decompress":return this.decompressData(this.toBuffer(t),e.maxDecompressedBytes,e.algorithm??"deflate");case "encrypt":return this.encryptData(this.toBuffer(t),e.key);case "decrypt":return this.decryptData(this.toBuffer(t),e.key);case "encode":return e.encoder.encode(this.toBuffer(t));case "decode":return e.encoder.decodeToBuffer(this.toString(t));case "transform":return e.fn(this.toBuffer(t));case "transformString":return e.fn(this.toString(t))}}toBuffer(e){return typeof e=="string"?Buffer.from(e,"utf-8"):e}toString(e){return typeof e=="string"?e:e.toString("utf-8")}compressData(e,t,r){return r==="brotli"?zlib.brotliCompressSync(e,{params:{[zlib.constants.BROTLI_PARAM_QUALITY]:Math.min(11,Math.max(0,t))}}):zlib.deflateSync(e,{level:Math.min(9,Math.max(0,t))})}decompressData(e,t,r="deflate"){if(r==="brotli"){let n=t??Number.POSITIVE_INFINITY;return R(e,n,"DduPipeline decompress")}return H(e,t??Number.POSITIVE_INFINITY,"DduPipeline decompress")}encryptData(e,t){return U(e,I(t))}decryptData(e,t){return K(e,I(t))}get stepCount(){return this.steps.length}clone(){let e=new s;return e.steps=[...this.steps],e}clear(){return this.steps=[],this}};W();exports.CharsetBuilder=V;exports.Ddu64=O;exports.DduPipeline=j;exports.DduSetSymbol=J;exports.createDecodeStream=G;exports.createEncodeStream=se;//# sourceMappingURL=index.cjs.map
|
|
7
|
+
//# sourceMappingURL=index.cjs.map
|