@ddunigma/node 3.1.0 → 4.0.1
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 +42 -8
- package/dist/BrowserAdapter-G4XORUQJ.js +2 -0
- package/dist/BrowserAdapter-LIUL744V.cjs +2 -0
- package/dist/NodeAdapter-AHALQ4DQ.js +2 -0
- package/dist/NodeAdapter-DS44MI5D.cjs +2 -0
- package/dist/{ObfuscationLayer-DAVKTnHf.d.cts → ObfuscationLayer-BRiyE5xu.d.cts} +10 -12
- package/dist/{ObfuscationLayer-D-xl5d7P.d.ts → ObfuscationLayer-DZiQGHMw.d.ts} +10 -12
- package/dist/browser.cjs +1 -1
- package/dist/browser.d.cts +5 -4
- package/dist/browser.d.ts +5 -4
- package/dist/browser.js +1 -1
- package/dist/chunk-342X2QEY.js +2 -0
- package/dist/chunk-65RDFQV7.js +10 -0
- package/dist/chunk-FACJ5LAG.cjs +10 -0
- package/dist/chunk-M7526IW7.js +2 -0
- package/dist/chunk-P7WJ2LOQ.js +2 -0
- package/dist/chunk-RFBXQWSA.cjs +2 -0
- package/dist/chunk-RHVBUC4T.cjs +2 -0
- package/dist/chunk-WS6GB27C.cjs +2 -0
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +40 -1
- package/dist/core.d.ts +40 -1
- package/dist/core.js +1 -1
- package/dist/{core-DYSnygnp.d.cts → errors-DxOlTuHc.d.cts} +94 -81
- package/dist/{core-DYSnygnp.d.ts → errors-DxOlTuHc.d.ts} +94 -81
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +23 -8
- package/dist/index.d.ts +23 -8
- package/dist/index.js +1 -1
- package/package.json +42 -5
- package/dist/BrowserAdapter-BHHWPUTB.js +0 -2
- package/dist/BrowserAdapter-M7PUHVGS.cjs +0 -2
- package/dist/NodeAdapter-JB2EZ3T4.js +0 -2
- package/dist/NodeAdapter-JRRSYUJT.cjs +0 -2
- package/dist/chunk-5RZDTEOZ.js +0 -2
- package/dist/chunk-JUBMOKKH.js +0 -2
- package/dist/chunk-JZSHJ6KN.cjs +0 -9
- package/dist/chunk-KEWLOPEV.js +0 -9
- package/dist/chunk-M6LY6DIE.js +0 -2
- package/dist/chunk-NFMYVNOG.cjs +0 -2
- package/dist/chunk-PHMARSJE.cjs +0 -2
- package/dist/chunk-TJTDYO65.cjs +0 -2
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ V2 추가사항
|
|
|
17
17
|
|
|
18
18
|
## Requirements
|
|
19
19
|
|
|
20
|
-
- **Node.js >=
|
|
20
|
+
- **Node.js >= 22.0.0**
|
|
21
21
|
|
|
22
22
|
## Install
|
|
23
23
|
|
|
@@ -93,6 +93,9 @@ const hangulCoda = new Ddu64(["가", "나", "다", "라"], "뭐", {
|
|
|
93
93
|
// → 가, 각, 갂, 갇, 나, 낙, 낚, 낟, 다, 닥, 닦, 닫, 라, 락, 랔, 랗 (16문자)
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
커스텀 charset의 각 심볼과 `paddingChar`는 단일 UTF-16 코드 유닛 문자여야 합니다.
|
|
97
|
+
이모지처럼 surrogate pair가 필요한 문자나 여러 문자로 이루어진 심볼은 지원하지 않습니다.
|
|
98
|
+
|
|
96
99
|
## CharsetBuilder
|
|
97
100
|
|
|
98
101
|
```typescript
|
|
@@ -211,7 +214,7 @@ const encoded = await ddu.encodeAsync("browser text");
|
|
|
211
214
|
const decoded = await ddu.decodeAsync(encoded);
|
|
212
215
|
```
|
|
213
216
|
|
|
214
|
-
Node.js에서도 async 메서드를 사용할 수 있습니다.
|
|
217
|
+
Node.js에서도 async 메서드를 사용할 수 있습니다. v4부터 루트 진입점(`@ddunigma/node`)은 런타임 조건형 export를 사용하므로 브라우저 번들러와 Workers 계열 런타임에서는 BrowserAdapter 경로로 해석됩니다. 명시적인 브라우저 경로가 필요하면 `@ddunigma/node/browser`를 사용하세요.
|
|
215
218
|
코어 진입점(`@ddunigma/node/core`)은 기본 인코딩/디코딩만 포함하며, 압축/암호화가 필요하면 명시적으로 어댑터를 전달하세요.
|
|
216
219
|
|
|
217
220
|
## Web Streams
|
|
@@ -231,6 +234,9 @@ const encodedStream = readableByteStream.pipeThrough(
|
|
|
231
234
|
const decodedStream = encodedStream.pipeThrough(createReadableDecodeStream(ddu));
|
|
232
235
|
```
|
|
233
236
|
|
|
237
|
+
인코딩 스트림은 압축/암호화/체크섬이 꺼져 있고 2의 제곱수 charset일 때 청크 단위로 즉시 출력합니다.
|
|
238
|
+
디코딩 스트림은 footer의 압축/암호화 메타데이터를 최종 신뢰하므로 payload를 모아 `flush`에서 처리합니다.
|
|
239
|
+
|
|
234
240
|
## WASM Acceleration
|
|
235
241
|
|
|
236
242
|
```typescript
|
|
@@ -240,6 +246,7 @@ await preloadWasm(); // 동기 encode/decode hot path에서 WASM을 쓰려면
|
|
|
240
246
|
|
|
241
247
|
const ddu = new Ddu64({
|
|
242
248
|
wasmThreshold: 4096, // 이 크기 이상일 때 WASM 사용
|
|
249
|
+
// wasmThreshold: Infinity, // WASM hot path 비활성화
|
|
243
250
|
});
|
|
244
251
|
|
|
245
252
|
const encoded = ddu.encode(new Uint8Array(1024 * 1024));
|
|
@@ -279,6 +286,27 @@ const ddu = new Ddu64({
|
|
|
279
286
|
});
|
|
280
287
|
```
|
|
281
288
|
|
|
289
|
+
## Custom Errors
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
import { Ddu64, Ddu64ErrorCode, isDdu64Error } from "@ddunigma/node";
|
|
293
|
+
|
|
294
|
+
const ddu = new Ddu64({ checksum: true });
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
ddu.decode(tamperedInput);
|
|
298
|
+
} catch (err) {
|
|
299
|
+
if (isDdu64Error(err) && err.code === Ddu64ErrorCode.ChecksumMismatch) {
|
|
300
|
+
// 체크섬 불일치 처리
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
인코딩, 디코딩, 압축, 암호화, 체크섬, charset, 크기 제한, adapter, stream 실패는
|
|
306
|
+
`Ddu64Error` 계열로 래핑됩니다. 모든 공개 진입점(`@ddunigma/node`,
|
|
307
|
+
`@ddunigma/node/browser`, `@ddunigma/node/core`)에서 같은 에러 타입과
|
|
308
|
+
`Ddu64ErrorCode`를 export합니다.
|
|
309
|
+
|
|
282
310
|
---
|
|
283
311
|
|
|
284
312
|
## API
|
|
@@ -369,7 +397,7 @@ new Ddu64(dduChar, paddingChar, options?);
|
|
|
369
397
|
| `chunkSeparator` | `string` | `"\n"` | 청크 구분자 |
|
|
370
398
|
| `maxDecodedBytes` | `number` | `67108864` | 디코딩 크기 제한 |
|
|
371
399
|
| `maxDecompressedBytes` | `number` | `67108864` | 압축해제 크기 제한 |
|
|
372
|
-
| `wasmThreshold` | `number` | `4096` | WASM 사용 임계값
|
|
400
|
+
| `wasmThreshold` | `number` | `4096` | WASM 사용 임계값 (`Infinity`면 비활성화) |
|
|
373
401
|
| `throwOnError` | `boolean` | `false` | 초기화 에러 시 throw |
|
|
374
402
|
|
|
375
403
|
## Per-Call Options
|
|
@@ -391,18 +419,24 @@ new Ddu64(dduChar, paddingChar, options?);
|
|
|
391
419
|
|
|
392
420
|
## Entry Points
|
|
393
421
|
|
|
394
|
-
| Import Path
|
|
395
|
-
|
|
|
396
|
-
| `@ddunigma/node`
|
|
397
|
-
| `@ddunigma/node
|
|
398
|
-
| `@ddunigma/node
|
|
422
|
+
| Runtime / Target | Import Path | 용도 |
|
|
423
|
+
| ------------------------------- | ----------------------------------- | ------------------------------------- |
|
|
424
|
+
| Node.js server/CLI | `@ddunigma/node` | Node.js 전체 기능 (동기+비동기) |
|
|
425
|
+
| Browser / Vite / webpack | `@ddunigma/node` 또는 `/browser` | 브라우저 최적화 (BrowserAdapter 기본) |
|
|
426
|
+
| Cloudflare Workers / Deno / Bun | `@ddunigma/node` 또는 `/browser` | Node.js 내장 모듈 없는 Web API 경로 |
|
|
427
|
+
| Adapter 직접 주입 최소 번들 | `@ddunigma/node/core` | 최소 코어 (인코딩/디코딩만) |
|
|
428
|
+
|
|
429
|
+
루트 진입점은 v4부터 `browser`/`worker`/`workerd`/`deno`/`bun`/`node` 조건을 가진 conditional export입니다. Node.js에서는 기존처럼 `Buffer` API와 NodeAdapter를 노출하고, 브라우저 및 Workers 계열 번들러에서는 Node.js 내장 모듈 없는 BrowserAdapter 경로로 해석됩니다. 런타임 조건을 알 수 없는 ESM 환경의 기본 fallback도 browser 번들을 사용합니다.
|
|
430
|
+
Node.js 런타임에서는 `node` 조건이 `index.js`/`index.cjs`를 선택하므로 기본 import로 NodeAdapter와 `decodeToBuffer()`를 사용할 수 있습니다.
|
|
399
431
|
|
|
400
432
|
## Build & Test
|
|
401
433
|
|
|
402
434
|
```bash
|
|
403
435
|
pnpm test
|
|
436
|
+
pnpm typecheck
|
|
404
437
|
pnpm build
|
|
405
438
|
pnpm lint
|
|
439
|
+
pnpm pack:check
|
|
406
440
|
pnpm bench
|
|
407
441
|
```
|
|
408
442
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkRFBXQWSA_cjs=require('./chunk-RFBXQWSA.cjs');require('./chunk-NY4FGVF3.cjs');Object.defineProperty(exports,"BrowserAdapter",{enumerable:true,get:function(){return chunkRFBXQWSA_cjs.a}});//# sourceMappingURL=BrowserAdapter-LIUL744V.cjs.map
|
|
2
|
+
//# sourceMappingURL=BrowserAdapter-LIUL744V.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkRHVBUC4T_cjs=require('./chunk-RHVBUC4T.cjs');require('./chunk-NY4FGVF3.cjs');Object.defineProperty(exports,"NodeAdapter",{enumerable:true,get:function(){return chunkRHVBUC4T_cjs.a}});//# sourceMappingURL=NodeAdapter-DS44MI5D.cjs.map
|
|
2
|
+
//# sourceMappingURL=NodeAdapter-DS44MI5D.cjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PlatformAdapter,
|
|
1
|
+
import { P as PlatformAdapter, y as KeyDerivationOptions, D as Ddu64Core, u as DduOptions, O as ObfuscationLayer } from './errors-DxOlTuHc.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* 브라우저 플랫폼 어댑터 구현.
|
|
@@ -21,8 +21,9 @@ import { P as PlatformAdapter, i as KeyDerivationOptions, D as Ddu64Core, e as D
|
|
|
21
21
|
declare class BrowserAdapter implements PlatformAdapter {
|
|
22
22
|
readonly supportsSyncCrypto = false;
|
|
23
23
|
readonly supportsSyncCompression = false;
|
|
24
|
-
readonly
|
|
25
|
-
|
|
24
|
+
readonly runtime: "browser" | "edge" | "deno" | "bun";
|
|
25
|
+
constructor(runtime?: "browser" | "edge" | "deno" | "bun");
|
|
26
|
+
get supportsBrotli(): boolean;
|
|
26
27
|
/**
|
|
27
28
|
* UTF-8 키 문자열에서 SHA-256을 통해 256비트 키를 파생합니다.
|
|
28
29
|
* UTF-8 인코딩된 키에 SubtleCrypto.digest('SHA-256', ...)를 사용합니다.
|
|
@@ -35,13 +36,13 @@ declare class BrowserAdapter implements PlatformAdapter {
|
|
|
35
36
|
* 참고: Web Crypto는 authTag를 암호문에 추가하므로,
|
|
36
37
|
* 마지막 16바이트를 authTag로 추출하고 와이어 포맷에 맞게 재배치합니다.
|
|
37
38
|
*/
|
|
38
|
-
encrypt(data: Uint8Array, keyHash: Uint8Array): Promise<Uint8Array>;
|
|
39
|
+
encrypt(data: Uint8Array, keyHash: Uint8Array, aad?: Uint8Array): Promise<Uint8Array>;
|
|
39
40
|
/**
|
|
40
41
|
* AES-256-GCM 페이로드를 복호화합니다.
|
|
41
42
|
* 와이어 포맷 기대: IV(12바이트) + authTag(16바이트) + 암호문.
|
|
42
43
|
* 복호화 전에 Web Crypto 형식(암호문 + authTag)으로 재구성합니다.
|
|
43
44
|
*/
|
|
44
|
-
decrypt(data: Uint8Array, keyHash: Uint8Array): Promise<Uint8Array>;
|
|
45
|
+
decrypt(data: Uint8Array, keyHash: Uint8Array, aad?: Uint8Array): Promise<Uint8Array>;
|
|
45
46
|
/**
|
|
46
47
|
* 암호학적으로 안전한 랜덤 바이트를 생성합니다.
|
|
47
48
|
*/
|
|
@@ -97,8 +98,8 @@ declare function detectRuntime(): RuntimeId;
|
|
|
97
98
|
* 모든 최신 브라우저와 Node.js에서 사용 가능합니다.
|
|
98
99
|
*
|
|
99
100
|
* 스트리밍 모드:
|
|
100
|
-
* - 압축/암호화/체크섬 비활성화 + 2의 제곱수 charset
|
|
101
|
-
* -
|
|
101
|
+
* - 인코딩: 압축/암호화/체크섬 비활성화 + 2의 제곱수 charset에서 청크 단위 출력
|
|
102
|
+
* - 디코딩: footer의 압축/암호화 마커를 최종 신뢰하기 위해 payload를 축적 후 처리
|
|
102
103
|
*
|
|
103
104
|
* 스트림 헤더 형식: [pad]DDS1[D|B|N][1|0][pad]
|
|
104
105
|
* D=deflate, B=brotli, N=없음 (압축), 1/0 (암호화).
|
|
@@ -122,11 +123,8 @@ declare function createReadableEncodeStream(encoder: Ddu64Core, options?: DduOpt
|
|
|
122
123
|
* charset 인코딩 문자열을 바이너리 데이터로 역변환하는
|
|
123
124
|
* Web Streams API TransformStream을 생성합니다.
|
|
124
125
|
*
|
|
125
|
-
* 스트림은 DDS1 스트림 헤더를
|
|
126
|
-
* 페이로드를
|
|
127
|
-
*
|
|
128
|
-
* 압축/암호화/체크섬이 없고 charset이 2의 제곱수인 스트림은 헤더 파싱 후 각 청크를 즉시 디코딩합니다.
|
|
129
|
-
* 그 외에는 전체 페이로드를 축적 후 일괄 디코딩합니다.
|
|
126
|
+
* 스트림은 DDS1 스트림 헤더를 조기 검증하되, 헤더만으로 복호화/압축해제를 비활성화하지 않습니다.
|
|
127
|
+
* footer가 최종 wire metadata이므로 전체 페이로드를 축적 후 일괄 디코딩합니다.
|
|
130
128
|
*
|
|
131
129
|
* @param encoder - 디코딩에 사용할 Ddu64Core 인스턴스
|
|
132
130
|
* @param options - 디코딩 옵션
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PlatformAdapter,
|
|
1
|
+
import { P as PlatformAdapter, y as KeyDerivationOptions, D as Ddu64Core, u as DduOptions, O as ObfuscationLayer } from './errors-DxOlTuHc.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* 브라우저 플랫폼 어댑터 구현.
|
|
@@ -21,8 +21,9 @@ import { P as PlatformAdapter, i as KeyDerivationOptions, D as Ddu64Core, e as D
|
|
|
21
21
|
declare class BrowserAdapter implements PlatformAdapter {
|
|
22
22
|
readonly supportsSyncCrypto = false;
|
|
23
23
|
readonly supportsSyncCompression = false;
|
|
24
|
-
readonly
|
|
25
|
-
|
|
24
|
+
readonly runtime: "browser" | "edge" | "deno" | "bun";
|
|
25
|
+
constructor(runtime?: "browser" | "edge" | "deno" | "bun");
|
|
26
|
+
get supportsBrotli(): boolean;
|
|
26
27
|
/**
|
|
27
28
|
* UTF-8 키 문자열에서 SHA-256을 통해 256비트 키를 파생합니다.
|
|
28
29
|
* UTF-8 인코딩된 키에 SubtleCrypto.digest('SHA-256', ...)를 사용합니다.
|
|
@@ -35,13 +36,13 @@ declare class BrowserAdapter implements PlatformAdapter {
|
|
|
35
36
|
* 참고: Web Crypto는 authTag를 암호문에 추가하므로,
|
|
36
37
|
* 마지막 16바이트를 authTag로 추출하고 와이어 포맷에 맞게 재배치합니다.
|
|
37
38
|
*/
|
|
38
|
-
encrypt(data: Uint8Array, keyHash: Uint8Array): Promise<Uint8Array>;
|
|
39
|
+
encrypt(data: Uint8Array, keyHash: Uint8Array, aad?: Uint8Array): Promise<Uint8Array>;
|
|
39
40
|
/**
|
|
40
41
|
* AES-256-GCM 페이로드를 복호화합니다.
|
|
41
42
|
* 와이어 포맷 기대: IV(12바이트) + authTag(16바이트) + 암호문.
|
|
42
43
|
* 복호화 전에 Web Crypto 형식(암호문 + authTag)으로 재구성합니다.
|
|
43
44
|
*/
|
|
44
|
-
decrypt(data: Uint8Array, keyHash: Uint8Array): Promise<Uint8Array>;
|
|
45
|
+
decrypt(data: Uint8Array, keyHash: Uint8Array, aad?: Uint8Array): Promise<Uint8Array>;
|
|
45
46
|
/**
|
|
46
47
|
* 암호학적으로 안전한 랜덤 바이트를 생성합니다.
|
|
47
48
|
*/
|
|
@@ -97,8 +98,8 @@ declare function detectRuntime(): RuntimeId;
|
|
|
97
98
|
* 모든 최신 브라우저와 Node.js에서 사용 가능합니다.
|
|
98
99
|
*
|
|
99
100
|
* 스트리밍 모드:
|
|
100
|
-
* - 압축/암호화/체크섬 비활성화 + 2의 제곱수 charset
|
|
101
|
-
* -
|
|
101
|
+
* - 인코딩: 압축/암호화/체크섬 비활성화 + 2의 제곱수 charset에서 청크 단위 출력
|
|
102
|
+
* - 디코딩: footer의 압축/암호화 마커를 최종 신뢰하기 위해 payload를 축적 후 처리
|
|
102
103
|
*
|
|
103
104
|
* 스트림 헤더 형식: [pad]DDS1[D|B|N][1|0][pad]
|
|
104
105
|
* D=deflate, B=brotli, N=없음 (압축), 1/0 (암호화).
|
|
@@ -122,11 +123,8 @@ declare function createReadableEncodeStream(encoder: Ddu64Core, options?: DduOpt
|
|
|
122
123
|
* charset 인코딩 문자열을 바이너리 데이터로 역변환하는
|
|
123
124
|
* Web Streams API TransformStream을 생성합니다.
|
|
124
125
|
*
|
|
125
|
-
* 스트림은 DDS1 스트림 헤더를
|
|
126
|
-
* 페이로드를
|
|
127
|
-
*
|
|
128
|
-
* 압축/암호화/체크섬이 없고 charset이 2의 제곱수인 스트림은 헤더 파싱 후 각 청크를 즉시 디코딩합니다.
|
|
129
|
-
* 그 외에는 전체 페이로드를 축적 후 일괄 디코딩합니다.
|
|
126
|
+
* 스트림은 DDS1 스트림 헤더를 조기 검증하되, 헤더만으로 복호화/압축해제를 비활성화하지 않습니다.
|
|
127
|
+
* footer가 최종 wire metadata이므로 전체 페이로드를 축적 후 일괄 디코딩합니다.
|
|
130
128
|
*
|
|
131
129
|
* @param encoder - 디코딩에 사용할 Ddu64Core 인스턴스
|
|
132
130
|
* @param options - 디코딩 옵션
|
package/dist/browser.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkWS6GB27C_cjs=require('./chunk-WS6GB27C.cjs'),chunkFACJ5LAG_cjs=require('./chunk-FACJ5LAG.cjs'),chunkRFBXQWSA_cjs=require('./chunk-RFBXQWSA.cjs');require('./chunk-NY4FGVF3.cjs');var e=class extends chunkFACJ5LAG_cjs.B{constructor(s,n,p){let o=chunkFACJ5LAG_cjs.x(s,n,p),u={...o.dduOptions,adapter:o.dduOptions?.adapter??new chunkRFBXQWSA_cjs.a};super(o.dduChar,o.paddingChar,u);}};async function z(){return new chunkRFBXQWSA_cjs.a}Object.defineProperty(exports,"createReadableDecodeStream",{enumerable:true,get:function(){return chunkWS6GB27C_cjs.c}});Object.defineProperty(exports,"createReadableEncodeStream",{enumerable:true,get:function(){return chunkWS6GB27C_cjs.b}});Object.defineProperty(exports,"detectRuntime",{enumerable:true,get:function(){return chunkWS6GB27C_cjs.a}});Object.defineProperty(exports,"CharsetBuilder",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.C}});Object.defineProperty(exports,"Ddu64AdapterError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.s}});Object.defineProperty(exports,"Ddu64CharsetError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.q}});Object.defineProperty(exports,"Ddu64ChecksumError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.p}});Object.defineProperty(exports,"Ddu64CompressionError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.l}});Object.defineProperty(exports,"Ddu64Core",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.B}});Object.defineProperty(exports,"Ddu64DecodeError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.k}});Object.defineProperty(exports,"Ddu64DecompressionError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.m}});Object.defineProperty(exports,"Ddu64DecryptionError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.o}});Object.defineProperty(exports,"Ddu64EncodeError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.j}});Object.defineProperty(exports,"Ddu64EncryptionError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.n}});Object.defineProperty(exports,"Ddu64Error",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.i}});Object.defineProperty(exports,"Ddu64ErrorCode",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.h}});Object.defineProperty(exports,"Ddu64LimitError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.r}});Object.defineProperty(exports,"Ddu64ObfuscationError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.t}});Object.defineProperty(exports,"Ddu64StreamError",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.u}});Object.defineProperty(exports,"DduSetSymbol",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.a}});Object.defineProperty(exports,"HangulObfuscationLayer",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.b}});Object.defineProperty(exports,"createObfuscationLayer",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.c}});Object.defineProperty(exports,"getWasmCodec",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.e}});Object.defineProperty(exports,"getWasmCodecSync",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.f}});Object.defineProperty(exports,"isDdu64Error",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.v}});Object.defineProperty(exports,"preloadWasm",{enumerable:true,get:function(){return chunkFACJ5LAG_cjs.d}});Object.defineProperty(exports,"BrowserAdapter",{enumerable:true,get:function(){return chunkRFBXQWSA_cjs.a}});exports.Ddu64=e;exports.Ddu64Browser=e;exports.getAdapter=z;//# sourceMappingURL=browser.cjs.map
|
|
2
2
|
//# sourceMappingURL=browser.cjs.map
|
package/dist/browser.d.cts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { B as BrowserAdapter } from './ObfuscationLayer-
|
|
2
|
-
export { H as HangulObfuscationLayer, c as createObfuscationLayer, a as createReadableDecodeStream, b as createReadableEncodeStream, d as detectRuntime } from './ObfuscationLayer-
|
|
3
|
-
import { D as Ddu64Core, a as DduConstructorOptions } from './
|
|
4
|
-
export { C as CharSetConfig, b as CharSetInfo, c as CharsetBuilder, d as
|
|
1
|
+
import { B as BrowserAdapter } from './ObfuscationLayer-BRiyE5xu.cjs';
|
|
2
|
+
export { H as HangulObfuscationLayer, c as createObfuscationLayer, a as createReadableDecodeStream, b as createReadableEncodeStream, d as detectRuntime } from './ObfuscationLayer-BRiyE5xu.cjs';
|
|
3
|
+
import { D as Ddu64Core, a as DduConstructorOptions } from './errors-DxOlTuHc.cjs';
|
|
4
|
+
export { C as CharSetConfig, b as CharSetInfo, c as CharsetBuilder, d as Ddu64AdapterError, e as Ddu64CharsetError, f as Ddu64ChecksumError, g as Ddu64CompressionError, h as Ddu64DecodeError, i as Ddu64DecompressionError, j as Ddu64DecryptionError, k as Ddu64EncodeError, l as Ddu64EncryptionError, m as Ddu64Error, n as Ddu64ErrorCode, o as Ddu64ErrorOptions, p as Ddu64LimitError, q as Ddu64ObfuscationError, r as Ddu64Operation, s as Ddu64StreamError, t as DduEncodeStats, u as DduOptions, v as DduProgressInfo, w as DduSetSymbol, x as DduTextEncoding, E as EncodingProfile, K as KeyDerivationAlgorithm, y as KeyDerivationOptions, O as ObfuscationLayer, P as PlatformAdapter, W as WasmCodec, z as isDdu64Error } from './errors-DxOlTuHc.cjs';
|
|
5
|
+
export { getWasmCodec, getWasmCodecSync, preloadWasm } from './core.cjs';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Browser-optimized Ddu64 wrapper.
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { B as BrowserAdapter } from './ObfuscationLayer-
|
|
2
|
-
export { H as HangulObfuscationLayer, c as createObfuscationLayer, a as createReadableDecodeStream, b as createReadableEncodeStream, d as detectRuntime } from './ObfuscationLayer-
|
|
3
|
-
import { D as Ddu64Core, a as DduConstructorOptions } from './
|
|
4
|
-
export { C as CharSetConfig, b as CharSetInfo, c as CharsetBuilder, d as
|
|
1
|
+
import { B as BrowserAdapter } from './ObfuscationLayer-DZiQGHMw.js';
|
|
2
|
+
export { H as HangulObfuscationLayer, c as createObfuscationLayer, a as createReadableDecodeStream, b as createReadableEncodeStream, d as detectRuntime } from './ObfuscationLayer-DZiQGHMw.js';
|
|
3
|
+
import { D as Ddu64Core, a as DduConstructorOptions } from './errors-DxOlTuHc.js';
|
|
4
|
+
export { C as CharSetConfig, b as CharSetInfo, c as CharsetBuilder, d as Ddu64AdapterError, e as Ddu64CharsetError, f as Ddu64ChecksumError, g as Ddu64CompressionError, h as Ddu64DecodeError, i as Ddu64DecompressionError, j as Ddu64DecryptionError, k as Ddu64EncodeError, l as Ddu64EncryptionError, m as Ddu64Error, n as Ddu64ErrorCode, o as Ddu64ErrorOptions, p as Ddu64LimitError, q as Ddu64ObfuscationError, r as Ddu64Operation, s as Ddu64StreamError, t as DduEncodeStats, u as DduOptions, v as DduProgressInfo, w as DduSetSymbol, x as DduTextEncoding, E as EncodingProfile, K as KeyDerivationAlgorithm, y as KeyDerivationOptions, O as ObfuscationLayer, P as PlatformAdapter, W as WasmCodec, z as isDdu64Error } from './errors-DxOlTuHc.js';
|
|
5
|
+
export { getWasmCodec, getWasmCodecSync, preloadWasm } from './core.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Browser-optimized Ddu64 wrapper.
|
package/dist/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{c as createReadableDecodeStream,b as createReadableEncodeStream,a as detectRuntime}from'./chunk-
|
|
1
|
+
export{c as createReadableDecodeStream,b as createReadableEncodeStream,a as detectRuntime}from'./chunk-M7526IW7.js';import {B,x}from'./chunk-65RDFQV7.js';export{C as CharsetBuilder,s as Ddu64AdapterError,q as Ddu64CharsetError,p as Ddu64ChecksumError,l as Ddu64CompressionError,B as Ddu64Core,k as Ddu64DecodeError,m as Ddu64DecompressionError,o as Ddu64DecryptionError,j as Ddu64EncodeError,n as Ddu64EncryptionError,i as Ddu64Error,h as Ddu64ErrorCode,r as Ddu64LimitError,t as Ddu64ObfuscationError,u as Ddu64StreamError,a as DduSetSymbol,b as HangulObfuscationLayer,c as createObfuscationLayer,e as getWasmCodec,f as getWasmCodecSync,v as isDdu64Error,d as preloadWasm}from'./chunk-65RDFQV7.js';import {a}from'./chunk-P7WJ2LOQ.js';export{a as BrowserAdapter}from'./chunk-P7WJ2LOQ.js';import'./chunk-QR43FNIY.js';var e=class extends B{constructor(s,n,p){let o=x(s,n,p),u={...o.dduOptions,adapter:o.dduOptions?.adapter??new a};super(o.dduChar,o.paddingChar,u);}};async function z(){return new a}export{e as Ddu64,e as Ddu64Browser,z as getAdapter};//# sourceMappingURL=browser.js.map
|
|
2
2
|
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {d,a,b}from'./chunk-QR43FNIY.js';import {pbkdf2,pbkdf2Sync,createHash,randomBytes,createCipheriv,createDecipheriv}from'crypto';import {deflateRaw,inflateRaw,brotliCompress,brotliDecompress,deflateRawSync,inflateRawSync,constants,brotliCompressSync,brotliDecompressSync}from'zlib';import {promisify}from'util';var N=promisify(deflateRaw),w=promisify(inflateRaw),v=promisify(brotliCompress),h=promisify(brotliDecompress),E=promisify(pbkdf2);function _(e){let n=e,r=String(n?.message??"").toLowerCase();return String(n?.code??"")==="ERR_BUFFER_TOO_LARGE"||r.includes("output length")||r.includes("buffer too large")||r.includes("cannot create a buffer larger")}function f(e,n,r){throw _(e)?new Error(`[Ddu64 ${r}] Decompressed data exceeds limit. Limit: ${n} bytes`,{cause:e}):e}function s(e){return Buffer.isBuffer(e)?e:e.buffer instanceof SharedArrayBuffer?Buffer.from(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var g=class{supportsSyncCrypto=true;supportsSyncCompression=true;supportsBrotli=true;runtime="node";async deriveKey(n,r){if(r?.algorithm==="pbkdf2"){let t=await E(n,d(r.salt),a(r.iterations),32,b(r.hash));return new Uint8Array(t)}return this.deriveKeySync(n,r)}deriveKeySync(n,r){return r?.algorithm==="pbkdf2"?new Uint8Array(pbkdf2Sync(n,d(r.salt),a(r.iterations),32,b(r.hash))):new Uint8Array(createHash("sha256").update(n).digest())}async encrypt(n,r,t){return this.encryptSync(n,r,t)}encryptSync(n,r,t){let i=randomBytes(12),o=createCipheriv("aes-256-gcm",r,i);t&&t.length>0&&o.setAAD(s(t));let u=Buffer.concat([o.update(n),o.final()]),a=o.getAuthTag(),c=new Uint8Array(28+u.length);return c.set(i,0),c.set(a,12),c.set(u,28),c}async decrypt(n,r,t){return this.decryptSync(n,r,t)}decryptSync(n,r,t){if(n.length<28)throw new Error("[Ddu64 decrypt] Invalid encrypted data: too short");let i=n.subarray(0,12),o=n.subarray(12,28),u=n.subarray(28),a=createDecipheriv("aes-256-gcm",r,i);t&&t.length>0&&a.setAAD(s(t)),a.setAuthTag(o);let c=Buffer.concat([a.update(u),a.final()]);return new Uint8Array(c)}randomBytes(n){return new Uint8Array(randomBytes(n))}async deflate(n,r){let t={};r!==void 0&&(t.level=r);let i=await N(s(n),t);return new Uint8Array(i)}deflateSync(n,r){let t={};return r!==void 0&&(t.level=r),new Uint8Array(deflateRawSync(s(n),t))}async inflate(n,r){if(r===void 0||r===Number.POSITIVE_INFINITY){let i=await w(s(n));return new Uint8Array(i)}let t={maxOutputLength:r};try{let i=await w(s(n),t);return new Uint8Array(i)}catch(i){f(i,r,"inflate");}}inflateSync(n,r){if(r===void 0||r===Number.POSITIVE_INFINITY)return new Uint8Array(inflateRawSync(s(n)));try{return new Uint8Array(inflateRawSync(s(n),{maxOutputLength:r}))}catch(t){f(t,r,"inflate");}}async brotliCompress(n,r){let t={};r!==void 0&&(t.params={[constants.BROTLI_PARAM_QUALITY]:Math.max(0,Math.min(11,r))});let i=await v(s(n),t);return new Uint8Array(i)}brotliCompressSync(n,r){let t={};return r!==void 0&&(t.params={[constants.BROTLI_PARAM_QUALITY]:Math.max(0,Math.min(11,r))}),new Uint8Array(brotliCompressSync(s(n),t))}async brotliDecompress(n,r){if(r===void 0||r===Number.POSITIVE_INFINITY){let t=await h(s(n));return new Uint8Array(t)}try{let t=await h(s(n),{maxOutputLength:r});return new Uint8Array(t)}catch(t){f(t,r,"brotli");}}brotliDecompressSync(n,r){if(r===void 0||r===Number.POSITIVE_INFINITY)return new Uint8Array(brotliDecompressSync(s(n)));try{return new Uint8Array(brotliDecompressSync(s(n),{maxOutputLength:r}))}catch(t){f(t,r,"brotli");}}};export{g as a};//# sourceMappingURL=chunk-342X2QEY.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-342X2QEY.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var se=(n=>(n.DDU="ddu",n.DDU_V1="ddu_v1",n.ONECHARSET="oneCharSet",n))(se||{}),j={dduSetSymbol:"ddu",usePowerOfTwo:true,requiredLength:64};function ae(e){if(e.length===0)throw new Error("[Ddu64 obfuscation] Alphabet must not be empty.");if(e.length>11172)throw new Error(`[Ddu64 obfuscation] Alphabet size (${e.length}) exceeds available Hangul syllables (11172).`);let r=Math.floor(11172/e.length),t=new Map;for(let n=0;n<e.length;n++)t.set(e[n],n);return {alphabet:e,syllablesPerChar:r,charToIndex:t}}function de(e,r,t){let n=44032+e*t.syllablesPerChar,o=r%t.syllablesPerChar;return n+o}function ce(e,r){if(e<44032||e>55203)return -1;let t=e-44032,n=Math.floor(t/r.syllablesPerChar);return n>=r.alphabet.length?-1:n}var _=class{config;constructor(r){this.config=ae(r);}obfuscate(r){if(r.length===0)return "";let t=new Array(r.length);for(let n=0;n<r.length;n++){let o=r[n],s=this.config.charToIndex.get(o);if(s===void 0)throw new Error(`[Ddu64 obfuscation] Character "${o}" (U+${o.charCodeAt(0).toString(16).padStart(4,"0").toUpperCase()}) not found in obfuscation alphabet.`);let i=de(s,n,this.config);t[n]=String.fromCharCode(i);}return t.join("")}deobfuscate(r){if(r.length===0)return "";let t=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n),s=ce(o,this.config);if(s===-1)throw new Error(`[Ddu64 obfuscation] Invalid syllable at position ${n}: U+${o.toString(16).padStart(4,"0").toUpperCase()} is not in the mapped range.`);t[n]=this.config.alphabet[s];}return t.join("")}};function et(e,r){let t=new Set(e);t.add(r);let n=[...t];return new _(n)}var U=null,V=false,S=false,w=null,ue=Cr,X=class{exports;constructor(r){this.exports=r;}get ready(){return true}encode(r,t){let{exports:n}=this;if(r.length===0)return {indices:new Uint16Array(0),paddingBits:0};let o=n.alloc(r.length);new Uint8Array(n.memory.buffer).set(r,o);let i=1<<t,a=1;try{let d=n.encode(o,r.length,t,i,a),c=n.get_result_ptr(),u=new Uint16Array(n.memory.buffer,c,d),f=new Uint16Array(d);return f.set(u),{indices:f,paddingBits:n.get_padding_bits()}}finally{n.dealloc(o,r.length);}}decode(r,t,n){let{exports:o}=this;if(r.length===0)return new Uint8Array(0);let s=r.length*2,i=o.alloc(s);new Uint16Array(o.memory.buffer,i,r.length).set(r);let d=1<<t,c=1;try{let u=o.decode(i,r.length,t,d,c,n);if(u===4294967295)throw new Error("[WasmCodec decode] Invalid index in input");let f=o.get_result_ptr(),p=new Uint8Array(o.memory.buffer,f,u),l=new Uint8Array(u);return l.set(p),l}finally{o.dealloc(i,s);}}};async function Cr(){try{if(typeof fetch!="function")return null;let e=await fetch(new URL("./wasm/codec.wasm",import.meta.url));return e.ok?await e.arrayBuffer():null}catch{return null}}async function Ar(e){try{if(e.byteLength<16)return null;let r=new Uint8Array(e,0,4);if(r[0]!==0||r[1]!==97||r[2]!==115||r[3]!==109)return null;let t;try{t=await WebAssembly.compile(e);}catch{return null}let o=(await WebAssembly.instantiate(t,{})).exports;return typeof o.alloc!="function"||typeof o.dealloc!="function"||typeof o.encode!="function"||typeof o.decode!="function"||typeof o.get_result_ptr!="function"||typeof o.get_result_len!="function"||typeof o.get_padding_bits!="function"||!o.memory?null:o}catch{return null}}async function le(){try{if(U)return !0;if(S)return !1;let e=await ue();if(!e)return S=!0,!1;let r=await Ar(e);return r?(U=new X(r),!0):(S=!0,!1)}catch{return S=true,false}}function wr(e,r){let t;return {promise:new Promise((s,i)=>{t=setTimeout(()=>i(new Error(r)),e);}),clear:()=>clearTimeout(t)}}async function tt(){if(U)return;if(w)return w;let e=wr(1e4,"[Ddu64 wasm] WASM initialization timed out (10s)"),r=async()=>{try{if(!await le())throw new Error("[Ddu64 wasm] WASM initialization failed")}finally{e.clear();}};return w=Promise.race([r(),e.promise]).finally(()=>{w=null,V=true;}),w}function nt(){if(U)return U;if(S)return null;if(!V&&!w){V=true;let e;w=new Promise(r=>{e=setTimeout(()=>{S=true,r();},5e3),le().then(t=>{t||(S=true);}).catch(()=>{S=true;}).finally(()=>{e!==void 0&&clearTimeout(e),r();});}).finally(()=>{w=null;});}return null}function Z(){return U}function he(e){if(e===Number.POSITIVE_INFINITY)return Number.POSITIVE_INFINITY;if(!Number.isFinite(e))throw new Error(`[Ddu64 config] wasmThreshold must be a finite number or Infinity, got ${e}`);return Math.max(1024,Math.min(1048576,Math.round(e)))}function ot(e){ue=e,!U&&!w&&(V=false,S=false);}var Sr=(l=>(l.EncodeFailed="DDU64_ENCODE_FAILED",l.DecodeFailed="DDU64_DECODE_FAILED",l.CompressionFailed="DDU64_COMPRESSION_FAILED",l.DecompressionFailed="DDU64_DECOMPRESSION_FAILED",l.EncryptionFailed="DDU64_ENCRYPTION_FAILED",l.DecryptionFailed="DDU64_DECRYPTION_FAILED",l.ChecksumMismatch="DDU64_CHECKSUM_MISMATCH",l.InvalidCharset="DDU64_INVALID_CHARSET",l.InvalidInput="DDU64_INVALID_INPUT",l.LimitExceeded="DDU64_LIMIT_EXCEEDED",l.AdapterUnavailable="DDU64_ADAPTER_UNAVAILABLE",l.ObfuscationFailed="DDU64_OBFUSCATION_FAILED",l.StreamFailed="DDU64_STREAM_FAILED",l))(Sr||{}),g=class extends Error{code;operation;constructor(r,t){super(r,{cause:t.cause}),this.name=new.target.name,this.code=t.code,this.operation=t.operation;}},J=class extends g{constructor(r,t){super(r,{code:"DDU64_ENCODE_FAILED",operation:"encode",cause:t});}},Q=class extends g{constructor(r,t){super(r,{code:"DDU64_DECODE_FAILED",operation:"decode",cause:t});}},x=class extends g{constructor(r,t){super(r,{code:"DDU64_COMPRESSION_FAILED",operation:"compress",cause:t});}},L=class extends g{constructor(r,t){super(r,{code:"DDU64_DECOMPRESSION_FAILED",operation:"decompress",cause:t});}},P=class extends g{constructor(r,t){super(r,{code:"DDU64_ENCRYPTION_FAILED",operation:"encrypt",cause:t});}},D=class extends g{constructor(r,t){super(r,{code:"DDU64_DECRYPTION_FAILED",operation:"decrypt",cause:t});}},M=class extends g{constructor(r,t){super(r,{code:"DDU64_CHECKSUM_MISMATCH",operation:"checksum",cause:t});}},ee=class extends g{constructor(r,t){super(r,{code:"DDU64_INVALID_CHARSET",operation:"charset",cause:t});}},re=class extends g{constructor(r,t,n){super(r,{code:"DDU64_LIMIT_EXCEEDED",operation:t,cause:n});}},N=class extends g{constructor(r,t,n){super(r,{code:"DDU64_ADAPTER_UNAVAILABLE",operation:t,cause:n});}},I=class extends g{constructor(r,t){super(r,{code:"DDU64_OBFUSCATION_FAILED",operation:"obfuscation",cause:t});}},te=class extends g{constructor(r,t){super(r,{code:"DDU64_STREAM_FAILED",operation:"stream",cause:t});}};function Pr(e){return e instanceof g}function E(e){return e instanceof Error&&e.message?e.message:String(e)}function A(e,r){if(Pr(e))return e;let t=E(e),n=t.toLowerCase();if(n.startsWith("[ddu64")||n.startsWith("[bitpack")){if(n.includes("checksum"))return new M(t,e);if(n.includes("obfuscation"))return new I(t,e);if(n.includes("adapter")||n.includes("sync")||n.includes("provider"))return new N(t,r,e);if(n.includes("encryptionkey")||n.includes("encrypted payload requires"))return r==="encode"?new P(t,e):new D(t,e);if(n.includes("decrypt")||n.includes("decryption")||n.includes("incorrect key"))return new D(t,e);if(n.includes("encrypt"))return new P(t,e);if(n.includes("decompress")||n.includes("inflate"))return new L(t,e);if(n.includes("compress")||n.includes("brotli"))return new x(t,e);if(n.includes("limit")||n.includes("exceeds"))return new re(t,r,e);if(n.includes("charset")||n.includes("character")||n.includes("invalid"))return new ee(t,e)}return r==="stream"?new te(t,e):r==="encode"?new J(t,e):new Q(t,e)}function pe(e,r){let{bitLength:t,usePowerOfTwo:n,charsetSize:o}=r,s=e.length;if(s===0)return {indices:[],paddingBits:0};let i=s*8,a=Math.ceil(i/t),d=n?a:a*2,c=new Array(d),u=0,f=0,p=0;if(n){let h=(1<<t)-1;for(let m=0;m<s;m++)for(f=f<<8|e[m],p+=8;p>=t;)p-=t,c[u++]=f>>p&h,f&=(1<<p)-1;}else for(let h=0;h<s;h++)for(f=f<<8|e[h],p+=8;p>=t;){p-=t;let m=f>>p,y=m/o|0;c[u++]=y,c[u++]=m-y*o,f&=(1<<p)-1;}let l=0;if(p>0){l=t-p;let h=f<<l;if(n)c[u++]=h;else {let m=h/o|0;c[u++]=m,c[u++]=h-m*o;}}return c.length=u,{indices:c,paddingBits:l}}function fe(e,r,t){let{bitLength:n,usePowerOfTwo:o,charsetSize:s}=t,i=e.length;if(i===0)return new Uint8Array(0);let a=o?1:2,d=Math.ceil(i/a),c=n<31?1<<n:Math.pow(2,n),u=Math.ceil((d*n-r)/8),f=new Uint8Array(u+1),p=0,l=0,h=0;if(o)for(let m=0;m<i;m+=a){let y=e[m];if(y<0||y>=s)throw new Error(`[BitPack decode] Invalid index ${y} at position ${m}`);for(l=l<<n|y,h+=n,m+a>=i&&r>0&&(l>>=r,h-=r);h>=8;)h-=8,f[p++]=l>>h&255,l&=(1<<h)-1;}else for(let m=0;m<i;m+=a){let y=e[m],b=e[m+1];if(y<0||y>=s)throw new Error(`[BitPack decode] Invalid index ${y} at position ${m}`);if(b===void 0||b<0||b>=s)throw new Error(`[BitPack decode] Invalid index ${b} at position ${m+1}`);let C=y*s+b;if(C>=c)throw new Error(`[BitPack decode] Value ${C} exceeds range at position ${m}`);for(l=l<<n|C,h+=n,m+a>=i&&r>0&&(l>>=r,h-=r);h>=8;)h-=8,f[p++]=l>>h&255,l&=(1<<h)-1;}return f.subarray(0,p)}function me(e,r){return e<=1?0:r?Math.floor(Math.log2(e)):Math.ceil(Math.log2(e))}function ye(e){return e>0&&(e&e-1)===0}var Dr=(()=>{let e=new Uint32Array(256);for(let r=0;r<256;r++){let t=r;for(let n=0;n<8;n++)t=t>>>1^(t&1?3988292384:0);e[r]=t;}return e})();function K(e){let r=4294967295;for(let t=0;t<e.length;t++)r=r>>>8^Dr[(r^e[t])&255];return ((r^4294967295)>>>0).toString(16).padStart(8,"0")}function ge(e,r){let t=Math.max(e.length,r.length),n=e.length^r.length;for(let o=0;o<t;o++){let s=o<e.length?e.charCodeAt(o):0,i=o<r.length?r.charCodeAt(o):0;n|=s^i;}return n===0}var be=["-","_","."];function Ce(e){return e.length===0?e:e.replaceAll("+","-").replaceAll("/","_").replaceAll("=",".")}function Ae(e){return e.length===0?e:e.replaceAll("-","+").replaceAll("_","/").replaceAll(".","=")}function we(e,r,t){if(r<=0||e.length<=r)return e;let n=Math.ceil(e.length/r),o=new Array(n*2-1),s=0;for(let i=0;i<e.length;i+=r)o[s++]=e.slice(i,i+r),i+r<e.length&&(o[s++]=t);return o.join("")}function Se(e,r){if(e.length===0)return e;let t=r&&r!==`
|
|
2
|
+
`&&r!==`\r
|
|
3
|
+
`&&r!=="\r"?r:"",n=e.includes(`
|
|
4
|
+
`)||e.includes("\r"),o=t.length>0&&e.includes(t);if(!n&&!o)return e;let s=n?e.replace(/[\r\n]/g,""):e;return o&&(s=s.replaceAll(t,"")),s}var Er={"":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};function Ur(e,r){let t=e.charCodeAt(0);if(t<44032||t>55203)return e;let n=t-(t-44032)%28,o=Er[r]??0;return String.fromCharCode(n+o)}function W(e,r){let t=new Array(e.length*r.length),n=0;for(let o of e)for(let s of r)t[n++]=Ur(o,s);return t}function H(e,r){let n=e===void 0||!Number.isFinite(e)?6:Math.floor(e);return Math.min(r==="brotli"?11:9,Math.max(0,n))}var xr=new TextEncoder,Lr=new TextDecoder;function z(e){return xr.encode(e)}function ne(e){return Lr.decode(e)}var kr={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},Br={symbol:"ddu_v1",charSet:["\uB70C","\uB568","\uC774","\uC6B0","\uC57C","!","?","."],maxRequiredLength:8,bitLength:6,paddingChar:"\uBB50",useRepeatPadding:true,usePowerOfTwo:false,encodingProfile:{bitLength:6,usePowerOfTwo:false,bitsPerPadChar:2}},vr={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 $(e){switch(e){case "ddu":return kr;case "ddu_v1":return Br;case "oneCharSet":return vr;default:return}}var Tr=65536;function Pe(e,r,t,n){let o=(s,i,a,d,c)=>{if(Ir(a,t?.usePowerOfTwo)&&a>0){let p=Math.floor(Math.log2(a)),l=1<<p;return {charSet:s.length===l?s:s.slice(0,l),padding:i,requiredLength:l,bitLength:p,isPredefined:d,useRepeatPadding:c}}return {charSet:s.length===a?s:s.slice(0,a),padding:i,requiredLength:a,bitLength:a>0?Math.ceil(Math.log2(a)):0,isPredefined:d,useRepeatPadding:c}};try{let s=e??t?.dduChar,i=r??t?.paddingChar;if(s){if(!i)throw new Error("[Ddu64 Constructor] paddingChar is required when dduChar is provided.");let p=typeof s=="string"?[...s]:[...s],l=t?.codaChar,h=l?!0:t?.useRepeatPadding??!1;if(l&&l.length>0&&(p=W(p,l)),n&&new Set(p).size!==p.length){let b=p.filter((C,O)=>p.indexOf(C)!==O);throw new Error(`[Ddu64 Constructor] Character set contains duplicate characters: [${[...new Set(b)].join(", ")}]`)}let m=t?.requiredLength??p.length;if(p.length<m)throw new Error("[Ddu64 Constructor] Insufficient characters.");return o(p,i,m,!1,h)}let a=t?.dduSetSymbol??j.dduSetSymbol??"ddu",d=Rr(a),c=d.codaChar?W(d.charSet,d.codaChar):d.charSet,u=o(c,d.paddingChar,d.maxRequiredLength,!0,d.useRepeatPadding),f=d.encodingProfile;return f?(u.encodingProfile=f,u.bitLength=f.bitLength,u.usePowerOfTwo=f.usePowerOfTwo,u.bitsPerPadChar=f.bitsPerPadChar):(u.bitsPerPadChar=d.bitsPerPadChar,u.usePowerOfTwo=d.usePowerOfTwo,d.usePowerOfTwo===!1&&(u.bitLength=d.bitLength)),u}catch(s){if(n)throw s;return oe(t)}}function De(e,r,t){let n=[e,null];for(let s of n){let i=s?{...s}:oe(t);try{let a=i.charSet,d=i.requiredLength,c=Array.from(new Set(a));if(c.length!==a.length){if(r){let p=a.filter((l,h)=>a.indexOf(l)!==h);throw new Error(`[Ddu64 normalizeCharSet] Character set contains duplicate characters: [${[...new Set(p)].join(", ")}]`)}a=c,i.isPredefined||(d=a.length);}if(a.length<d)throw new Error(`[Ddu64 normalizeCharSet] Insufficient characters. Required: ${d}, Has: ${a.length}`);if(d<2)throw new Error("[Ddu64 normalizeCharSet] At least 2 unique characters required.");if(a.length===0)throw new Error("[Ddu64 normalizeCharSet] Empty charset.");if(a.find(p=>p.length!==1)){if(r)throw new Error("[Ddu64 normalizeCharSet] Multi-character symbols are not supported.");continue}if(a.length>Tr){if(r)throw new Error("[Ddu64 normalizeCharSet] Charset size exceeds maximum supported size of 65536.");continue}if(i.padding.length!==1)throw new Error(`[Ddu64 normalizeCharSet] Padding length mismatch. Expected 1, got ${i.padding.length}`);if(a.includes(i.padding)){if(r)throw new Error(`[Ddu64 normalizeCharSet] Padding character "${i.padding}" conflicts with charset.`);a=a.filter(p=>p!==i.padding);}for(let p of a)if(p.includes(`
|
|
5
|
+
`)||p.includes("\r"))throw new Error("[Ddu64 normalizeCharSet] Newline and carriage return characters are reserved.");if(i.padding.includes(`
|
|
6
|
+
`)||i.padding.includes("\r"))throw new Error("[Ddu64 normalizeCharSet] Newline and carriage return characters are reserved.");return {charSet:a.length===d?a:a.slice(0,d),padding:i.padding,isPredefined:i.isPredefined}}catch(a){if(r)throw a}}let o=oe(t);return {charSet:o.charSet.slice(0,o.requiredLength),padding:o.padding,isPredefined:true}}function Ee(e,r,t){for(let n of be){for(let o of e)if(o.includes(n)){let s=`[Ddu64 Constructor] URL-Safe mode conflict: charset character "${o}" contains "${n}".`;if(t)throw new Error(s);return false}if(r.includes(n)){let o=`[Ddu64 Constructor] URL-Safe mode conflict: padding character "${r}" contains "${n}".`;if(t)throw new Error(o);return false}}return true}function Ue(e,r,t){if(t>256)return;let n=Math.min(e.length,t),o=e.slice(0,n),s=new Set;for(let a=0;a<o.length;a++)s.add(o[a]);s.add(r);for(let a=0;a<o.length;a++){let d=o[a];for(let f=0;f<o.length;f++){let p=d+o[f];if(s.has(p))throw new Error(`Combination conflict: "${d}" + "${o[f]}"`);s.add(p);}let c=d+r;if(s.has(c))throw new Error(`Combination conflict: "${d}" + padding`);s.add(c);let u=r+d;if(s.has(u))throw new Error(`Combination conflict: padding + "${d}"`);s.add(u);}let i=r+r;if(s.has(i))throw new Error("Combination conflict: double padding");s.add(i);}function Ir(e,r){return r!==void 0?r?e>0:false:e>0&&(e&e-1)===0}function Rr(e){let r=$(e);if(!r)throw new Error(`CharSet with symbol ${e} not found`);return r}function oe(e){let r=e?.dduSetSymbol??j.dduSetSymbol??"oneCharSet",t=$(r)??$("oneCharSet");if(!t)throw new Error("Critical: No fallback CharSet available");return {charSet:t.codaChar?W(t.charSet,t.codaChar):t.charSet,padding:t.paddingChar,requiredLength:t.maxRequiredLength,bitLength:t.encodingProfile?.bitLength??t.bitLength,isPredefined:true,useRepeatPadding:t.useRepeatPadding,bitsPerPadChar:t.encodingProfile?.bitsPerPadChar??t.bitsPerPadChar,usePowerOfTwo:t.encodingProfile?.usePowerOfTwo??t.usePowerOfTwo,encodingProfile:t.encodingProfile}}var Or="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function xe(e,r,t,n){return t&&n===6&&r==="="&&e.join("")===Or}function Le(e){let r=_r(e);if(r===null)return null;let t=0,n=r.length;for(;n>0&&r[n-1]==="=";)t++,n--;return {payload:r.slice(0,n),paddingBits:t===2?4:t===1?2:0}}function ke(e,r,t){let n=r===4?2:r===2?1:r===0?0:-1;if(n<0)return null;for(let o=0;o<e.length;o++)if(!t(e.charCodeAt(o)))return null;return Mr(e+"=".repeat(n))}function _r(e){let r=e.toBase64;if(typeof r=="function")return r.call(e);let t=globalThis.Buffer;return t?.from?t.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):null}function Mr(e){let r=Uint8Array;if(typeof r.fromBase64=="function")return r.fromBase64(e);let t=globalThis.Buffer;if(t?.from){let n=t.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}return null}function Y(e){if(!e)throw new Error("[Ddu64 adapter] No platform adapter available. Use encodeAsync()/decodeAsync() in browser environments, or provide an adapter via options.adapter.");return e}function Be(e,r,t){let n=Y(e.adapter);if(!n.encryptSync)throw new Error("[Ddu64 encrypt] Sync encryption unavailable. Use encodeAsync() in browser environments.");let o=Re(e,n,"encrypt");return n.encryptSync(r,o,t)}function ve(e,r,t){let n=Y(e.adapter);if(!n.decryptSync)throw new Error("[Ddu64 decrypt] Sync decryption unavailable. Use decodeAsync() in browser environments.");let o=Re(e,n,"decrypt");return n.decryptSync(r,o,t)}function Te(e,r,t,n){let o=Y(e);if(t==="brotli"){if(!o.brotliCompressSync)throw new Error("[Ddu64 compress] Brotli compression is unavailable in the current runtime.");return o.brotliCompressSync(r,n)}if(!o.deflateSync)throw new Error("[Ddu64 compress] Sync compression unavailable. Use encodeAsync() in browser environments.");return o.deflateSync(r,n)}function Ie(e,r,t,n){let o=Y(e);if(t==="brotli"){if(!o.brotliDecompressSync)throw new Error("[Ddu64 decompress] Brotli decompression is unavailable in the current runtime.");return o.brotliDecompressSync(r,n)}if(!o.inflateSync)throw new Error("[Ddu64 decompress] Sync decompression unavailable. Use decodeAsync() in browser environments.");return o.inflateSync(r,n)}function Re(e,r,t){if(e.encryptionKeyHash)return e.encryptionKeyHash;if(!r.deriveKeySync){let o=t==="encrypt"?"encodeAsync":"decodeAsync";throw new Error(`[Ddu64 ${t}] Sync key derivation unavailable. Use ${o}() in browser environments.`)}let n=r.deriveKeySync(e.encryptionKey,e.keyDerivation);return e.setEncryptionKeyHash(n),n}function k(e){let r=e.toLowerCase();return r.includes("adapter")||r.includes("sync")||r.includes("provider")}async function Oe(e,r,t){try{let n=G(e.adapter),o=await Ke(e,n);return await n.encrypt(r,o,t)}catch(n){throw q(n,"encode","encrypt")}}async function _e(e,r,t){try{let n=G(e.adapter),o=await Ke(e,n);return await n.decrypt(r,o,t)}catch(n){throw q(n,"decode","decrypt")}}async function Me(e,r,t,n){try{let o=G(e);if(t==="brotli"){if(!o.brotliCompress)throw new Error("[Ddu64 compress] Brotli compression is unavailable in the current runtime.");return await o.brotliCompress(r,n)}return await o.deflate(r,n)}catch(o){throw q(o,"encode","compress")}}async function Ne(e,r,t,n){try{let o=G(e);if(t==="brotli"){if(!o.brotliDecompress)throw new Error("[Ddu64 decompress] Brotli decompression is unavailable in the current runtime.");return await o.brotliDecompress(r,n)}return await o.inflate(r,n)}catch(o){throw q(o,"decode","decompress")}}function G(e){if(!e)throw new Error("[Ddu64 adapter] No platform adapter available. Use @ddunigma/node or @ddunigma/node/browser, or provide an adapter via options.adapter.");return e}async function Ke(e,r){if(e.encryptionKeyHash)return e.encryptionKeyHash;let t=await r.deriveKey(e.encryptionKey,e.keyDerivation);return e.setEncryptionKeyHash(t),t}function q(e,r,t){let n=E(e);if(k(n))return new N(n,r,e);switch(t){case "compress":return new x(n,e);case "decompress":return new L(n,e);case "encrypt":return new P(n,e);case "decrypt":return new D(n,e)}}function He(e,r,t){return e!=null&&typeof e=="object"&&!Array.isArray(e)?{dduChar:void 0,paddingChar:void 0,dduOptions:e}:{dduChar:e,paddingChar:r,dduOptions:t}}function ze(e){let r=new Int32Array(65536);r.fill(-1);let t=new Uint16Array(e.length);for(let n=0;n<e.length;n++){let o=e[n].charCodeAt(0);r[o]=n,t[n]=o;}return {charCodeLookup:r,charCodes:t}}function B(e,r,t,n){if(e===void 0)return r;if(e===Number.POSITIVE_INFINITY)return Number.POSITIVE_INFINITY;if(!Number.isFinite(e)||e<=0){if(t)throw new Error(`[Ddu64 options] Invalid ${n}. Must be a positive finite number or Infinity.`);return r}return Math.floor(e)}function Fe(e,r,t,n){if(e===0)return 0;if(r<0||r>=t)throw new Error(`[Ddu64 decode] Invalid padding bits: ${r}`);let i=Math.ceil(e/(n?1:2))*t-r;if(i<0)throw new Error("[Ddu64 decode] Invalid decoded bit length");return Math.ceil(i/8)}function Ve(e,r){if(!r&&e.length%2!==0)throw new Error(`[Ddu64 decode] Invalid encoded length for variable charset. Expected multiple of 2, got ${e.length}`)}function We(e,r,t,n){if(e.length===0)return;let o=n?1:2,i=e.length/o*t-r;if(i<0||i%8!==0)throw new Error(`[Ddu64 decode] Invalid encoded bit length. Expected a whole number of bytes, got ${i} bits.`)}function $e(e,r,t,n,o){if(r===0)return;if(e.length===0)throw new Error("[Ddu64 decode] Invalid padding bits without payload");let s=(1<<r)-1,i;if(t){let a=e[e.length-1],d=n[a.charCodeAt(0)];if(d<0)throw new Error(`[Ddu64 decode] Invalid character "${a}" at ${e.length-1}`);i=d;}else {let a=e[e.length-2],d=e[e.length-1],c=n[a.charCodeAt(0)],u=n[d.charCodeAt(0)];if(c<0||u<0)throw new Error("[Ddu64 decode] Invalid character in final encoded chunk");i=c*o+u;}if((i&s)!==0)throw new Error("[Ddu64 decode] Invalid non-zero padding bits in final symbol")}var R="DDS1",v="ELYSIA",T="GRISEO";var Nr=new TextEncoder;function Ye(e,r,t,n=2){let o=e.length,s=r.length,i={cleanedInput:e,paddingBits:0,isEncrypted:false,pipelineVersion:2};if(o<s)return i;let d=Math.max(0,t-1).toString().length;for(let c=Math.min(d,o);c>=1;c--){let u=o-c,f=true;for(let O=u;O<o;O++){let ie=e.charCodeAt(O);if(ie<48||ie>57){f=false;break}}if(!f)continue;let p=e.substring(u),l=parseInt(p,10);if(Number.isNaN(l)||l<0||l>=t||p!==l.toString())continue;let h=u,m=false,y,b=2;h>=2&&e.substring(h-2,h)==="V4"?(b=4,h-=2):h>=2&&e.substring(h-2,h)==="V3"&&(b=3,h-=2),h>=3&&e.substring(h-3,h)==="ENC"&&(m=true,h-=3),h>=v.length&&e.substring(h-v.length,h)===v?(y="deflate",h-=v.length):h>=T.length&&e.substring(h-T.length,h)===T&&(y="brotli",h-=T.length);let C=h-s;if(C>=0&&e.substring(C,h)===r)return {cleanedInput:e.substring(0,C),paddingBits:l,compressionAlgorithm:y,isEncrypted:m,pipelineVersion:b}}if(e.endsWith(r)){let c=0,u=o;for(;u>=s&&e.substring(u-s,u)===r;)c++,u-=s;if(c>0){let f=c*n;if(f<t)return {cleanedInput:e.substring(0,u),paddingBits:f,isEncrypted:false,pipelineVersion:2}}}return i}function Ge(e){let r=e.lastIndexOf("CHK");if(r===-1)return {data:e,checksum:null};let t=e.slice(r+3);return t.length!==8||!/^[0-9a-f]+$/i.test(t)?{data:e,checksum:null}:{data:e.slice(0,r),checksum:t.toLowerCase()}}function Kr(e){return e.length*2+R.length+2}function Pt(e,r){let t=r.compressionAlgorithm==="brotli"?"B":r.compressionAlgorithm==="deflate"?"D":"N",n=r.encrypted?"1":"0";return `${e}${R}${t}${n}${e}`}function Dt(e,r){let t=Kr(r);if(e.length<t||!e.startsWith(r))return null;let n=r.length;if(e.slice(n,n+R.length)!==R)throw new Error("[wireFormat] Invalid stream header magic");let s=e[n+R.length],i=e[n+R.length+1];if(e.slice(t-r.length,t)!==r)throw new Error("[wireFormat] Invalid stream header terminator");let d=s==="B"?"brotli":s==="D"?"deflate":s==="N"?void 0:null;if(d===null)throw new Error("[wireFormat] Invalid stream header compression flag");if(i!=="0"&&i!=="1")throw new Error("[wireFormat] Invalid stream header encryption flag");return {compressionAlgorithm:d,encrypted:i==="1"}}function qe(e){let{paddingBits:r,compressionAlgorithm:t,isEncrypted:n,paddingChar:o,useRepeatPadding:s,bitsPerPadChar:i=2,pipelineVersion:a=2}=e;if(!n&&a!==2)throw new Error("[wireFormat] Pipeline version markers require encryption");if(r===0&&!t&&!n&&a===2)return "";if(s&&!t&&!n&&a===2&&r>0&&r%i===0){let c=r/i;return o.repeat(c)}return o+(t==="deflate"?v:t==="brotli"?T:"")+(n?"ENC":"")+(a===4?"V4":a===3?"V3":"")+r.toString()}function F(e){return Nr.encode(`ddunigma:wire:v4;enc=1;compress=${e.compressionAlgorithm??"none"}`)}function je(e,r,t){let n=r?.checksum??t.defaultChecksum,o=r?.compress!==false,s=r?.encrypt!==false,i=e;t.reportDecodeStart(e.length);let a=r?.chunkSeparator??t.defaultChunkSeparator;i=Se(i,a),t.urlSafe&&(i=Ae(i));let d=null;if(n){let C=Ge(i);d=C.checksum,i=C.data;}t.shouldObfuscate(r)&&(i=t.deobfuscate(i));let{cleanedInput:c,paddingBits:u,compressionAlgorithm:f,isEncrypted:p,pipelineVersion:l}=Ye(i,t.paddingChar,t.bitLength,t.bitsPerPadChar);if(p&&s&&!t.encryptionKey)throw new Error("[Ddu64 decode] Encrypted payload requires an encryptionKey");let h=p&&l===4?F({compressionAlgorithm:f}):void 0;Ve(c,t.usePowerOfTwo),$e(c,u,t.usePowerOfTwo,t.dduCharCodeLookup,t.charSetSize),We(c,u,t.bitLength,t.usePowerOfTwo);let m=B(r?.maxDecodedBytes,t.defaultMaxDecodedBytes,true,"maxDecodedBytes"),y=Fe(c.length,u,t.bitLength,t.usePowerOfTwo);if(y>m)throw new Error(`[Ddu64 decode] Decoded output exceeds limit. Estimated: ${y} bytes, Limit: ${m} bytes`);return t.reportBitpackDecode(c.length,e.length),{decoded:t.decodeChars(c,u),extractedChecksum:d,compressionAlgorithm:f,isEncrypted:p,pipelineVersion:l,encryptionAAD:h,allowInternalDecompress:o,allowInternalDecrypt:s}}function Xe(e){return e.omitFooter?"":qe({paddingBits:e.paddingBits,compressionAlgorithm:e.compressionAlgorithm,isEncrypted:e.isEncrypted,paddingChar:e.paddingChar,useRepeatPadding:e.useRepeatPadding&&!e.compressionAlgorithm&&!e.isEncrypted,bitsPerPadChar:e.bitsPerPadChar,pipelineVersion:e.isEncrypted?e.pipelineVersion:2})}function Ze(e){let r=e.encoded;return e.shouldObfuscate(e.options)&&(r=e.getObfuscationLayer().obfuscate(r)),e.shouldChecksum&&e.checksum&&(r=r+"CHK"+e.checksum),e.urlSafe&&(r=Ce(r)),e.chunkSize&&e.chunkSize>0&&(e.assertSafeChunkSeparator(r,e.chunkSeparator),r=we(r,e.chunkSize,e.chunkSeparator)),r}function Je(e,r){let t=e.length;if(t<=8192){let i=new Uint16Array(t);for(let a=0;a<t;a++)i[a]=r[e[a]];return String.fromCharCode.apply(null,i)}let n=new Uint16Array(t);for(let i=0;i<t;i++)n[i]=r[e[i]];let o=new Array(Math.ceil(t/8192)),s=0;for(let i=0;i<t;i+=8192){let a=n.subarray(i,Math.min(i+8192,t));o[s++]=String.fromCharCode.apply(null,a);}return o.join("")}function Qe(e,r,t,n,o){if(e.length===0)return "";let s=o.canUseNativeBase64?Le(e):null,i,a;if(s)i=s.paddingBits,a=s.payload;else {let c=zr(e,o);i=c.paddingBits,a=Je(c.indices,o.dduCharCodes);}let d=Xe({paddingBits:i,compressionAlgorithm:r,isEncrypted:t,paddingChar:o.paddingChar,useRepeatPadding:o.useRepeatPadding,bitsPerPadChar:o.bitsPerPadChar,pipelineVersion:o.encryptedPipelineVersion,omitFooter:n?.omitFooter});return a+d}function er(e,r,t){let n=e.length;if(n===0)return new Uint8Array(0);let o=t.canUseNativeBase64?ke(e,r,d=>t.dduCharCodeLookup[d]>=0):null;if(o)return o;let i=n>=t.wasmThreshold?new Uint16Array(n):new Array(n);for(let d=0;d<n;d++){let c=t.dduCharCodeLookup[e.charCodeAt(d)];if(c<0)throw new Error(`[Ddu64 decode] Invalid character "${e[d]}" at ${d}`);i[d]=c;}let a=rr(n,t)?Z():null;if(a?.ready&&t.usePowerOfTwo){let d=i instanceof Uint16Array?i:Uint16Array.from(i);return a.decode(d,t.bitLength,r)}return fe(i,r,t.bitPackConfig)}function zr(e,r){let t=rr(e.length,r)?Z():null;return t?.ready&&r.usePowerOfTwo?t.encode(e,r.bitLength):pe(e,r.bitPackConfig)}function rr(e,r){return e>=r.wasmThreshold}function tr(e,r){let t=new Set(e);t.add(r);let n=v+T+"ENC"+"V3"+"V4";for(let o of n)t.add(o);for(let o of "0123456789")t.add(o);return [...t]}function nr(e,r,t){let n=e.decoded;return n=$r(e,t,n),n=Yr(e,r,t,n),dr(e,t,r,n),n=Gr(e,t,n),ur(t,n),n}async function or(e,r,t){let n=e.decoded;if(ir(e,t)&&(t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:55,stage:"decrypt"}),n=await t.decrypt(n,e.encryptionAAD)),ar(e)){let o=cr(r,t);t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:70,stage:"decompress"}),n=await t.decompress(n,e.compressionAlgorithm,o);}return dr(e,t,r,n),sr(e,t)&&(t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:90,stage:"decrypt"}),n=await t.decrypt(n,e.encryptionAAD)),ur(t,n),n}function $r(e,r,t){return ir(e,r)?(r.reportProgress({processedBytes:t.length,totalBytes:t.length,percent:55,stage:"decrypt"}),r.decrypt(t,e.encryptionAAD)):t}function Yr(e,r,t,n){if(!ar(e))return n;let o=cr(r,t);return t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:70,stage:"decompress"}),t.decompress(n,e.compressionAlgorithm,o)}function Gr(e,r,t){return sr(e,r)?(r.reportProgress({processedBytes:t.length,totalBytes:t.length,percent:90,stage:"decrypt"}),r.decrypt(t,e.encryptionAAD)):t}function ir(e,r){return (e.pipelineVersion===3||e.pipelineVersion===4)&&e.isEncrypted&&!!r.encryptionKey&&e.allowInternalDecrypt}function sr(e,r){return e.pipelineVersion===2&&e.isEncrypted&&!!r.encryptionKey&&e.allowInternalDecrypt}function ar(e){return !!e.compressionAlgorithm&&e.allowInternalDecompress&&(e.pipelineVersion===2||!e.isEncrypted||e.allowInternalDecrypt)}function dr(e,r,t,n){if(!e.extractedChecksum||!(e.pipelineVersion===2||!e.isEncrypted||e.allowInternalDecrypt))return;r.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:85,stage:"checksum"});let o=K(n);if(!ge(o,e.extractedChecksum))throw new M(`[Ddu64 decode] Checksum mismatch. Expected: ${e.extractedChecksum}, Got: ${o}`)}function cr(e,r){return B(e?.maxDecompressedBytes,r.defaultMaxDecompressedBytes,true,"maxDecompressedBytes")}function ur(e,r){e.reportProgress({processedBytes:r.length,totalBytes:r.length,percent:100,stage:"done"});}function lr(e,r,t){let n=pr(r,t),o=typeof e=="string"?z(e):e;fr(t,o.length);let s=n.shouldChecksum?K(o):"",i,a;if(n.shouldCompress){let c=r?.compressionAlgorithm??t.defaultCompressionAlgorithm,u=H(r?.compressionLevel??t.defaultCompressionLevel,c);mr(t,o.length);let f=t.compress(o,c,u);a=f.length,f.length<o.length&&(o=f,i=c);}let d=false;return n.shouldEncrypt&&(yr(t,o.length),o=t.encrypt(o,t.getEncryptionAAD(i)),d=true),{encoded:t.finalize(o,i,d,s,n.shouldChecksum,n.chunkSize,n.chunkSeparator),compressedSize:a}}async function hr(e,r,t){let n=pr(r,t),o=typeof e=="string"?z(e):e;fr(t,o.length);let s=n.shouldChecksum?K(o):"",i;if(n.shouldCompress){let d=r?.compressionAlgorithm??t.defaultCompressionAlgorithm,c=H(r?.compressionLevel??t.defaultCompressionLevel,d);mr(t,o.length);let u=await t.compress(o,d,c);u.length<o.length&&(o=u,i=d);}let a=false;return n.shouldEncrypt&&(yr(t,o.length),o=await t.encrypt(o,t.getEncryptionAAD(i)),a=true),t.finalize(o,i,a,s,n.shouldChecksum,n.chunkSize,n.chunkSeparator)}function pr(e,r){return {shouldCompress:e?.compress??r.defaultCompress,shouldChecksum:e?.checksum??r.defaultChecksum,shouldEncrypt:(e?.encrypt??true)&&r.hasEncryptionKey,chunkSize:e?.chunkSize??r.defaultChunkSize,chunkSeparator:e?.chunkSeparator??r.defaultChunkSeparator}}function fr(e,r){e.reportProgress({processedBytes:0,totalBytes:r,percent:0,stage:"start"});}function mr(e,r){e.reportProgress({processedBytes:r,totalBytes:r,percent:20,stage:"compress"});}function yr(e,r){e.reportProgress({processedBytes:r,totalBytes:r,percent:45,stage:"encrypt"});}var jr=64*1024*1024,Xr=64*1024*1024,gr=class{dduChar;dduCharCodes;paddingChar;bitLength;usePowerOfTwo;dduCharCodeLookup;isPredefinedCharSet;defaultCompress;defaultMaxDecodedBytes;defaultMaxDecompressedBytes;urlSafe;encryptionKey;keyDerivation;encryptionKeyHash;defaultChecksum;defaultChunkSize;defaultChunkSeparator;defaultCompressionLevel;defaultCompressionAlgorithm;useRepeatPadding;bitsPerPadChar;bitPackConfig;wasmThreshold;canUseNativeBase64;payloadCodecContext;adapter;defaultObfuscate;obfuscationLayer;constructor(r,t,n){let o=He(r,t,n);r=o.dduChar,t=o.paddingChar,n=o.dduOptions;let s=n?.throwOnError??false;n?.adapter?this.adapter=n.adapter:this.adapter=void 0;let i=Pe(r,t,n,s),a=De(i,s,n);this.dduChar=a.charSet,this.paddingChar=a.padding,this.isPredefinedCharSet=a.isPredefined,this.defaultCompress=n?.compress??false,this.defaultMaxDecodedBytes=B(n?.maxDecodedBytes,jr,s,"maxDecodedBytes"),this.defaultMaxDecompressedBytes=B(n?.maxDecompressedBytes,Xr,s,"maxDecompressedBytes");let d=this.dduChar.length,c=ye(d),u=n?.usePowerOfTwo,f=i.encodingProfile;this.usePowerOfTwo=f?.usePowerOfTwo??i.usePowerOfTwo??(u!==void 0?u&&c:c);let p=f?.bitLength??(i.isPredefined&&i.usePowerOfTwo!==void 0?i.bitLength:void 0);this.bitLength=p??me(d,this.usePowerOfTwo);let l=ze(this.dduChar);this.dduCharCodeLookup=l.charCodeLookup,this.dduCharCodes=l.charCodes,this.isPredefinedCharSet||Ue(this.dduChar,this.paddingChar,d);let h=n?.urlSafe??false;if(this.urlSafe=h?Ee(this.dduChar,this.paddingChar,s):false,this.encryptionKey=n?.encryptionKey,this.keyDerivation=n?.keyDerivation,this.encryptionKey&&this.adapter?.deriveKeySync&&(this.encryptionKeyHash=this.adapter.deriveKeySync(this.encryptionKey,this.keyDerivation)),this.defaultChecksum=n?.checksum??false,this.defaultChunkSize=n?.chunkSize,this.defaultChunkSeparator=n?.chunkSeparator??`
|
|
7
|
+
`,this.defaultCompressionAlgorithm=n?.compressionAlgorithm??"deflate",this.defaultCompressionLevel=H(n?.compressionLevel,this.defaultCompressionAlgorithm),this.useRepeatPadding=n?.useRepeatPadding??i.useRepeatPadding??false,this.bitsPerPadChar=f?.bitsPerPadChar??i.bitsPerPadChar??2,this.defaultObfuscate=n?.obfuscate??false,this.defaultObfuscate&&!this.encryptionKey)throw new I("[Ddu64 obfuscation] Obfuscation requires encryption to be enabled.");this.bitPackConfig={bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,charsetSize:d},this.wasmThreshold=he(n?.wasmThreshold??4096),this.canUseNativeBase64=xe(this.dduChar,this.paddingChar,this.usePowerOfTwo,this.bitLength),this.payloadCodecContext={bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,bitPackConfig:this.bitPackConfig,wasmThreshold:this.wasmThreshold,canUseNativeBase64:this.canUseNativeBase64,dduCharCodes:this.dduCharCodes,dduCharCodeLookup:this.dduCharCodeLookup,paddingChar:this.paddingChar,useRepeatPadding:this.useRepeatPadding,bitsPerPadChar:this.bitsPerPadChar,encryptedPipelineVersion:4};}encode(r,t){try{return this.encodeInternal(r,t).encoded}catch(n){throw A(n,"encode")}}decode(r,t){try{let n=this.decodeToUint8Array(r,t);return ne(n)}catch(n){throw A(n,"decode")}}decodeToUint8Array(r,t){try{return this.decodeToUint8ArrayInternal(r,t)}catch(n){throw A(n,"decode")}}decodeToUint8ArrayInternal(r,t){let n=this.decodePrelude(r,t);return nr(n,t,{encryptionKey:this.encryptionKey,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,reportProgress:o=>this.reportProgress(t,o),decrypt:(o,s)=>this.decryptSync(o,s),decompress:(o,s,i)=>this.decompressSync(o,s,i)})}async encodeAsync(r,t){try{return await this.encodeAsyncInternal(r,t)}catch(n){throw A(n,"encode")}}async encodeAsyncInternal(r,t){return hr(r,t,{defaultCompress:this.defaultCompress,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm,hasEncryptionKey:!!this.encryptionKey,reportProgress:n=>this.reportProgress(t,n),getEncryptionAAD:n=>F({compressionAlgorithm:n}),compress:(n,o,s)=>Me(this.adapter,n,o,s),encrypt:(n,o)=>Oe(this.getSyncGatewayContext(),n,o),finalize:(n,o,s,i,a,d,c)=>this.finalizeEncode(n,o,s,i,a,d,c,t)})}async decodeAsync(r,t){try{let n=await this.decodeToUint8ArrayAsync(r,t);return ne(n)}catch(n){throw A(n,"decode")}}async decodeToUint8ArrayAsync(r,t){try{return await this.decodeToUint8ArrayAsyncInternal(r,t)}catch(n){throw A(n,"decode")}}async decodeToUint8ArrayAsyncInternal(r,t){let n=this.decodePrelude(r,t);return or(n,t,{encryptionKey:this.encryptionKey,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,reportProgress:o=>this.reportProgress(t,o),decrypt:(o,s)=>_e(this.getSyncGatewayContext(),o,s),decompress:(o,s,i)=>Ne(this.adapter,o,s,i)})}getCharSetInfo(){return {charSet:[...this.dduChar],paddingChar:this.paddingChar,bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,encoding:"utf-8",defaultCompress:this.defaultCompress,defaultMaxDecodedBytes:this.defaultMaxDecodedBytes,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,urlSafe:this.urlSafe,hasEncryptionKey:!!this.encryptionKey,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm}}getStats(r,t){let o=(typeof r=="string"?z(r):r).length,{encoded:s,compressedSize:i}=this.encodeInternal(r,t),a=s.length,d=o>0?a/o:0,u=(t?.compress??this.defaultCompress)&&i!==void 0&&o>0?i/o:void 0;return {originalSize:o,encodedSize:a,compressedSize:i,compressionRatio:u,expansionRatio:d,charsetSize:this.dduChar.length,bitLength:this.bitLength}}encodeInternal(r,t){return lr(r,t,{defaultCompress:this.defaultCompress,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm,hasEncryptionKey:!!this.encryptionKey,reportProgress:n=>this.reportProgress(t,n),getEncryptionAAD:n=>F({compressionAlgorithm:n}),compress:(n,o,s)=>this.compressSync(n,o,s),encrypt:(n,o)=>this.encryptSync(n,o),finalize:(n,o,s,i,a,d,c)=>this.finalizeEncode(n,o,s,i,a,d,c,t)})}finalizeEncode(r,t,n,o,s,i,a,d){this.reportProgress(d,{processedBytes:r.length,totalBytes:r.length,percent:70,stage:"encode"});let c=Qe(r,t,n,d,this.getPayloadCodecContext());return c=this.applyPostEncoding(c,d,o,s,i,a),this.reportProgress(d,{processedBytes:r.length,totalBytes:r.length,percent:100,stage:"done"}),c}applyPostEncoding(r,t,n,o,s,i){return Ze({encoded:r,options:t,checksum:n,shouldChecksum:o,chunkSize:s,chunkSeparator:i,urlSafe:this.urlSafe,shouldObfuscate:a=>this.shouldObfuscate(a),getObfuscationLayer:()=>this.getObfuscationLayer(),assertSafeChunkSeparator:(a,d)=>this.assertSafeChunkSeparator(a,d)})}decodePrelude(r,t){return je(r,t,{defaultChecksum:this.defaultChecksum,defaultChunkSeparator:this.defaultChunkSeparator,defaultMaxDecodedBytes:this.defaultMaxDecodedBytes,urlSafe:this.urlSafe,paddingChar:this.paddingChar,bitLength:this.bitLength,bitsPerPadChar:this.bitsPerPadChar,usePowerOfTwo:this.usePowerOfTwo,dduCharCodeLookup:this.dduCharCodeLookup,charSetSize:this.dduChar.length,encryptionKey:this.encryptionKey,shouldObfuscate:n=>this.shouldObfuscate(n),deobfuscate:n=>this.getObfuscationLayer().deobfuscate(n),decodeChars:(n,o)=>er(n,o,this.getPayloadCodecContext()),reportDecodeStart:n=>{this.reportProgress(t,{processedBytes:0,totalBytes:n,percent:0,stage:"start"});},reportBitpackDecode:(n,o)=>{this.reportProgress(t,{processedBytes:n,totalBytes:o,percent:30,stage:"decode"});}})}getPayloadCodecContext(){return this.payloadCodecContext}reportProgress(r,t){r?.onProgress?.(t);}encryptSync(r,t){try{return Be(this.getSyncGatewayContext(),r,t)}catch(n){let o=E(n);throw k(o)?A(n,"encode"):new P(o,n)}}decryptSync(r,t){try{return ve(this.getSyncGatewayContext(),r,t)}catch(n){let o=E(n);throw k(o)?A(n,"decode"):new D(o,n)}}compressSync(r,t,n){try{return Te(this.adapter,r,t,n)}catch(o){let s=E(o);throw k(s)?A(o,"encode"):new x(s,o)}}decompressSync(r,t,n){try{return Ie(this.adapter,r,t,n)}catch(o){let s=E(o);throw k(s)?A(o,"decode"):new L(s,o)}}getSyncGatewayContext(){return {adapter:this.adapter,encryptionKey:this.encryptionKey,keyDerivation:this.keyDerivation,encryptionKeyHash:this.encryptionKeyHash,setEncryptionKeyHash:r=>{this.encryptionKeyHash=r;}}}getObfuscationLayer(){return this.obfuscationLayer||(this.obfuscationLayer=new _(tr(this.dduChar,this.paddingChar))),this.obfuscationLayer}shouldObfuscate(r){let t=r?.obfuscate??this.defaultObfuscate;if(t&&!this.encryptionKey)throw new I("[Ddu64 obfuscation] Obfuscation requires encryption to be enabled.");return t}assertSafeChunkSeparator(r,t){if(!(t.length===0||this.isLineBreakSeparator(t))&&r.includes(t))throw new Error(`[Ddu64 chunking] Unsafe chunkSeparator "${t}" appears in encoded output. Use a separator that cannot be produced by the charset, footer, checksum, or URL-safe output.`)}isLineBreakSeparator(r){return r===`
|
|
8
|
+
`||r===`\r
|
|
9
|
+
`||r==="\r"}};var br=class e{chars=[];constructor(){}static create(){return new e}static fromUnicodeRange(r,t){return new e().addUnicodeRange(r,t)}static fromString(r){return new e().addString(r)}static base64(){return new e().addString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")}static base32(){return new e().addString("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")}static uppercase(){return e.fromUnicodeRange(65,90)}static lowercase(){return e.fromUnicodeRange(97,122)}static digits(){return e.fromUnicodeRange(48,57)}static hangulJamo(){return new e().addUnicodeRange(4352,4370).addUnicodeRange(4449,4469).addUnicodeRange(4520,4546)}addUnicodeRange(r,t){for(let n=r;n<=t;n++)this.chars.push(String.fromCodePoint(n));return this}addString(r){return typeof r=="string"?this.chars.push(...r):this.chars.push(...r),this}add(...r){return this.chars.push(...r),this}excludeConfusing(){let r=new Set(["0","O","o","1","l","I","i","|","L"]);return this.chars=this.chars.filter(t=>!r.has(t)),this}exclude(...r){let t=new Set(r);return this.chars=this.chars.filter(n=>!t.has(n)),this}excludeUrlUnsafe(){let r=new Set(["+","/","=","?","&","#","%"," "]);return this.chars=this.chars.filter(t=>!r.has(t)),this}unique(){return this.chars=[...new Set(this.chars)],this}shuffle(r){let t=r!==void 0?this.seededRandom(r):Math.random;for(let n=this.chars.length-1;n>0;n--){let o=Math.floor(t()*(n+1));[this.chars[n],this.chars[o]]=[this.chars[o],this.chars[n]];}return this}seededRandom(r){let t=r|0||1;return ()=>(t^=t<<13,t^=t>>17,t^=t<<5,(t>>>0)/4294967296)}limit(r){return this.chars=this.chars.slice(0,r),this}limitToPowerOfTwo(){let r=this.chars.length;if(r===0)return this;let t=1<<Math.floor(Math.log2(r));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(r){let t=[...this.chars],n=r;if(!n){let o=["=",".","_","-","~","!"];for(let s of o)if(!t.includes(s)){n=s;break}if(!n)throw new Error("Cannot find suitable padding character")}return {charset:t,padding:n}}};export{Dt as A,gr as B,br as C,se as a,_ as b,et as c,tt as d,nt as e,Z as f,ot as g,Sr as h,g as i,J as j,Q as k,x as l,L as m,P as n,D as o,M as p,ee as q,re as r,N as s,I as t,te as u,Pr as v,A as w,He as x,Kr as y,Pt as z};//# sourceMappingURL=chunk-65RDFQV7.js.map
|
|
10
|
+
//# sourceMappingURL=chunk-65RDFQV7.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
'use strict';var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var se=(n=>(n.DDU="ddu",n.DDU_V1="ddu_v1",n.ONECHARSET="oneCharSet",n))(se||{}),j={dduSetSymbol:"ddu",usePowerOfTwo:true,requiredLength:64};function ae(e){if(e.length===0)throw new Error("[Ddu64 obfuscation] Alphabet must not be empty.");if(e.length>11172)throw new Error(`[Ddu64 obfuscation] Alphabet size (${e.length}) exceeds available Hangul syllables (11172).`);let r=Math.floor(11172/e.length),t=new Map;for(let n=0;n<e.length;n++)t.set(e[n],n);return {alphabet:e,syllablesPerChar:r,charToIndex:t}}function de(e,r,t){let n=44032+e*t.syllablesPerChar,o=r%t.syllablesPerChar;return n+o}function ce(e,r){if(e<44032||e>55203)return -1;let t=e-44032,n=Math.floor(t/r.syllablesPerChar);return n>=r.alphabet.length?-1:n}var _=class{config;constructor(r){this.config=ae(r);}obfuscate(r){if(r.length===0)return "";let t=new Array(r.length);for(let n=0;n<r.length;n++){let o=r[n],s=this.config.charToIndex.get(o);if(s===void 0)throw new Error(`[Ddu64 obfuscation] Character "${o}" (U+${o.charCodeAt(0).toString(16).padStart(4,"0").toUpperCase()}) not found in obfuscation alphabet.`);let i=de(s,n,this.config);t[n]=String.fromCharCode(i);}return t.join("")}deobfuscate(r){if(r.length===0)return "";let t=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n),s=ce(o,this.config);if(s===-1)throw new Error(`[Ddu64 obfuscation] Invalid syllable at position ${n}: U+${o.toString(16).padStart(4,"0").toUpperCase()} is not in the mapped range.`);t[n]=this.config.alphabet[s];}return t.join("")}};function et(e,r){let t=new Set(e);t.add(r);let n=[...t];return new _(n)}var U=null,V=false,S=false,w=null,ue=Cr,X=class{exports;constructor(r){this.exports=r;}get ready(){return true}encode(r,t){let{exports:n}=this;if(r.length===0)return {indices:new Uint16Array(0),paddingBits:0};let o=n.alloc(r.length);new Uint8Array(n.memory.buffer).set(r,o);let i=1<<t,a=1;try{let d=n.encode(o,r.length,t,i,a),c=n.get_result_ptr(),u=new Uint16Array(n.memory.buffer,c,d),f=new Uint16Array(d);return f.set(u),{indices:f,paddingBits:n.get_padding_bits()}}finally{n.dealloc(o,r.length);}}decode(r,t,n){let{exports:o}=this;if(r.length===0)return new Uint8Array(0);let s=r.length*2,i=o.alloc(s);new Uint16Array(o.memory.buffer,i,r.length).set(r);let d=1<<t,c=1;try{let u=o.decode(i,r.length,t,d,c,n);if(u===4294967295)throw new Error("[WasmCodec decode] Invalid index in input");let f=o.get_result_ptr(),p=new Uint8Array(o.memory.buffer,f,u),l=new Uint8Array(u);return l.set(p),l}finally{o.dealloc(i,s);}}};async function Cr(){try{if(typeof fetch!="function")return null;let e=await fetch(new URL("./wasm/codec.wasm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-FACJ5LAG.cjs', document.baseURI).href))));return e.ok?await e.arrayBuffer():null}catch{return null}}async function Ar(e){try{if(e.byteLength<16)return null;let r=new Uint8Array(e,0,4);if(r[0]!==0||r[1]!==97||r[2]!==115||r[3]!==109)return null;let t;try{t=await WebAssembly.compile(e);}catch{return null}let o=(await WebAssembly.instantiate(t,{})).exports;return typeof o.alloc!="function"||typeof o.dealloc!="function"||typeof o.encode!="function"||typeof o.decode!="function"||typeof o.get_result_ptr!="function"||typeof o.get_result_len!="function"||typeof o.get_padding_bits!="function"||!o.memory?null:o}catch{return null}}async function le(){try{if(U)return !0;if(S)return !1;let e=await ue();if(!e)return S=!0,!1;let r=await Ar(e);return r?(U=new X(r),!0):(S=!0,!1)}catch{return S=true,false}}function wr(e,r){let t;return {promise:new Promise((s,i)=>{t=setTimeout(()=>i(new Error(r)),e);}),clear:()=>clearTimeout(t)}}async function tt(){if(U)return;if(w)return w;let e=wr(1e4,"[Ddu64 wasm] WASM initialization timed out (10s)"),r=async()=>{try{if(!await le())throw new Error("[Ddu64 wasm] WASM initialization failed")}finally{e.clear();}};return w=Promise.race([r(),e.promise]).finally(()=>{w=null,V=true;}),w}function nt(){if(U)return U;if(S)return null;if(!V&&!w){V=true;let e;w=new Promise(r=>{e=setTimeout(()=>{S=true,r();},5e3),le().then(t=>{t||(S=true);}).catch(()=>{S=true;}).finally(()=>{e!==void 0&&clearTimeout(e),r();});}).finally(()=>{w=null;});}return null}function Z(){return U}function he(e){if(e===Number.POSITIVE_INFINITY)return Number.POSITIVE_INFINITY;if(!Number.isFinite(e))throw new Error(`[Ddu64 config] wasmThreshold must be a finite number or Infinity, got ${e}`);return Math.max(1024,Math.min(1048576,Math.round(e)))}function ot(e){ue=e,!U&&!w&&(V=false,S=false);}var Sr=(l=>(l.EncodeFailed="DDU64_ENCODE_FAILED",l.DecodeFailed="DDU64_DECODE_FAILED",l.CompressionFailed="DDU64_COMPRESSION_FAILED",l.DecompressionFailed="DDU64_DECOMPRESSION_FAILED",l.EncryptionFailed="DDU64_ENCRYPTION_FAILED",l.DecryptionFailed="DDU64_DECRYPTION_FAILED",l.ChecksumMismatch="DDU64_CHECKSUM_MISMATCH",l.InvalidCharset="DDU64_INVALID_CHARSET",l.InvalidInput="DDU64_INVALID_INPUT",l.LimitExceeded="DDU64_LIMIT_EXCEEDED",l.AdapterUnavailable="DDU64_ADAPTER_UNAVAILABLE",l.ObfuscationFailed="DDU64_OBFUSCATION_FAILED",l.StreamFailed="DDU64_STREAM_FAILED",l))(Sr||{}),g=class extends Error{code;operation;constructor(r,t){super(r,{cause:t.cause}),this.name=new.target.name,this.code=t.code,this.operation=t.operation;}},J=class extends g{constructor(r,t){super(r,{code:"DDU64_ENCODE_FAILED",operation:"encode",cause:t});}},Q=class extends g{constructor(r,t){super(r,{code:"DDU64_DECODE_FAILED",operation:"decode",cause:t});}},x=class extends g{constructor(r,t){super(r,{code:"DDU64_COMPRESSION_FAILED",operation:"compress",cause:t});}},L=class extends g{constructor(r,t){super(r,{code:"DDU64_DECOMPRESSION_FAILED",operation:"decompress",cause:t});}},P=class extends g{constructor(r,t){super(r,{code:"DDU64_ENCRYPTION_FAILED",operation:"encrypt",cause:t});}},D=class extends g{constructor(r,t){super(r,{code:"DDU64_DECRYPTION_FAILED",operation:"decrypt",cause:t});}},M=class extends g{constructor(r,t){super(r,{code:"DDU64_CHECKSUM_MISMATCH",operation:"checksum",cause:t});}},ee=class extends g{constructor(r,t){super(r,{code:"DDU64_INVALID_CHARSET",operation:"charset",cause:t});}},re=class extends g{constructor(r,t,n){super(r,{code:"DDU64_LIMIT_EXCEEDED",operation:t,cause:n});}},N=class extends g{constructor(r,t,n){super(r,{code:"DDU64_ADAPTER_UNAVAILABLE",operation:t,cause:n});}},I=class extends g{constructor(r,t){super(r,{code:"DDU64_OBFUSCATION_FAILED",operation:"obfuscation",cause:t});}},te=class extends g{constructor(r,t){super(r,{code:"DDU64_STREAM_FAILED",operation:"stream",cause:t});}};function Pr(e){return e instanceof g}function E(e){return e instanceof Error&&e.message?e.message:String(e)}function A(e,r){if(Pr(e))return e;let t=E(e),n=t.toLowerCase();if(n.startsWith("[ddu64")||n.startsWith("[bitpack")){if(n.includes("checksum"))return new M(t,e);if(n.includes("obfuscation"))return new I(t,e);if(n.includes("adapter")||n.includes("sync")||n.includes("provider"))return new N(t,r,e);if(n.includes("encryptionkey")||n.includes("encrypted payload requires"))return r==="encode"?new P(t,e):new D(t,e);if(n.includes("decrypt")||n.includes("decryption")||n.includes("incorrect key"))return new D(t,e);if(n.includes("encrypt"))return new P(t,e);if(n.includes("decompress")||n.includes("inflate"))return new L(t,e);if(n.includes("compress")||n.includes("brotli"))return new x(t,e);if(n.includes("limit")||n.includes("exceeds"))return new re(t,r,e);if(n.includes("charset")||n.includes("character")||n.includes("invalid"))return new ee(t,e)}return r==="stream"?new te(t,e):r==="encode"?new J(t,e):new Q(t,e)}function pe(e,r){let{bitLength:t,usePowerOfTwo:n,charsetSize:o}=r,s=e.length;if(s===0)return {indices:[],paddingBits:0};let i=s*8,a=Math.ceil(i/t),d=n?a:a*2,c=new Array(d),u=0,f=0,p=0;if(n){let h=(1<<t)-1;for(let m=0;m<s;m++)for(f=f<<8|e[m],p+=8;p>=t;)p-=t,c[u++]=f>>p&h,f&=(1<<p)-1;}else for(let h=0;h<s;h++)for(f=f<<8|e[h],p+=8;p>=t;){p-=t;let m=f>>p,y=m/o|0;c[u++]=y,c[u++]=m-y*o,f&=(1<<p)-1;}let l=0;if(p>0){l=t-p;let h=f<<l;if(n)c[u++]=h;else {let m=h/o|0;c[u++]=m,c[u++]=h-m*o;}}return c.length=u,{indices:c,paddingBits:l}}function fe(e,r,t){let{bitLength:n,usePowerOfTwo:o,charsetSize:s}=t,i=e.length;if(i===0)return new Uint8Array(0);let a=o?1:2,d=Math.ceil(i/a),c=n<31?1<<n:Math.pow(2,n),u=Math.ceil((d*n-r)/8),f=new Uint8Array(u+1),p=0,l=0,h=0;if(o)for(let m=0;m<i;m+=a){let y=e[m];if(y<0||y>=s)throw new Error(`[BitPack decode] Invalid index ${y} at position ${m}`);for(l=l<<n|y,h+=n,m+a>=i&&r>0&&(l>>=r,h-=r);h>=8;)h-=8,f[p++]=l>>h&255,l&=(1<<h)-1;}else for(let m=0;m<i;m+=a){let y=e[m],b=e[m+1];if(y<0||y>=s)throw new Error(`[BitPack decode] Invalid index ${y} at position ${m}`);if(b===void 0||b<0||b>=s)throw new Error(`[BitPack decode] Invalid index ${b} at position ${m+1}`);let C=y*s+b;if(C>=c)throw new Error(`[BitPack decode] Value ${C} exceeds range at position ${m}`);for(l=l<<n|C,h+=n,m+a>=i&&r>0&&(l>>=r,h-=r);h>=8;)h-=8,f[p++]=l>>h&255,l&=(1<<h)-1;}return f.subarray(0,p)}function me(e,r){return e<=1?0:r?Math.floor(Math.log2(e)):Math.ceil(Math.log2(e))}function ye(e){return e>0&&(e&e-1)===0}var Dr=(()=>{let e=new Uint32Array(256);for(let r=0;r<256;r++){let t=r;for(let n=0;n<8;n++)t=t>>>1^(t&1?3988292384:0);e[r]=t;}return e})();function K(e){let r=4294967295;for(let t=0;t<e.length;t++)r=r>>>8^Dr[(r^e[t])&255];return ((r^4294967295)>>>0).toString(16).padStart(8,"0")}function ge(e,r){let t=Math.max(e.length,r.length),n=e.length^r.length;for(let o=0;o<t;o++){let s=o<e.length?e.charCodeAt(o):0,i=o<r.length?r.charCodeAt(o):0;n|=s^i;}return n===0}var be=["-","_","."];function Ce(e){return e.length===0?e:e.replaceAll("+","-").replaceAll("/","_").replaceAll("=",".")}function Ae(e){return e.length===0?e:e.replaceAll("-","+").replaceAll("_","/").replaceAll(".","=")}function we(e,r,t){if(r<=0||e.length<=r)return e;let n=Math.ceil(e.length/r),o=new Array(n*2-1),s=0;for(let i=0;i<e.length;i+=r)o[s++]=e.slice(i,i+r),i+r<e.length&&(o[s++]=t);return o.join("")}function Se(e,r){if(e.length===0)return e;let t=r&&r!==`
|
|
2
|
+
`&&r!==`\r
|
|
3
|
+
`&&r!=="\r"?r:"",n=e.includes(`
|
|
4
|
+
`)||e.includes("\r"),o=t.length>0&&e.includes(t);if(!n&&!o)return e;let s=n?e.replace(/[\r\n]/g,""):e;return o&&(s=s.replaceAll(t,"")),s}var Er={"":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};function Ur(e,r){let t=e.charCodeAt(0);if(t<44032||t>55203)return e;let n=t-(t-44032)%28,o=Er[r]??0;return String.fromCharCode(n+o)}function W(e,r){let t=new Array(e.length*r.length),n=0;for(let o of e)for(let s of r)t[n++]=Ur(o,s);return t}function H(e,r){let n=e===void 0||!Number.isFinite(e)?6:Math.floor(e);return Math.min(r==="brotli"?11:9,Math.max(0,n))}var xr=new TextEncoder,Lr=new TextDecoder;function z(e){return xr.encode(e)}function ne(e){return Lr.decode(e)}var kr={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},Br={symbol:"ddu_v1",charSet:["\uB70C","\uB568","\uC774","\uC6B0","\uC57C","!","?","."],maxRequiredLength:8,bitLength:6,paddingChar:"\uBB50",useRepeatPadding:true,usePowerOfTwo:false,encodingProfile:{bitLength:6,usePowerOfTwo:false,bitsPerPadChar:2}},vr={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 $(e){switch(e){case "ddu":return kr;case "ddu_v1":return Br;case "oneCharSet":return vr;default:return}}var Tr=65536;function Pe(e,r,t,n){let o=(s,i,a,d,c)=>{if(Ir(a,t?.usePowerOfTwo)&&a>0){let p=Math.floor(Math.log2(a)),l=1<<p;return {charSet:s.length===l?s:s.slice(0,l),padding:i,requiredLength:l,bitLength:p,isPredefined:d,useRepeatPadding:c}}return {charSet:s.length===a?s:s.slice(0,a),padding:i,requiredLength:a,bitLength:a>0?Math.ceil(Math.log2(a)):0,isPredefined:d,useRepeatPadding:c}};try{let s=e??t?.dduChar,i=r??t?.paddingChar;if(s){if(!i)throw new Error("[Ddu64 Constructor] paddingChar is required when dduChar is provided.");let p=typeof s=="string"?[...s]:[...s],l=t?.codaChar,h=l?!0:t?.useRepeatPadding??!1;if(l&&l.length>0&&(p=W(p,l)),n&&new Set(p).size!==p.length){let b=p.filter((C,O)=>p.indexOf(C)!==O);throw new Error(`[Ddu64 Constructor] Character set contains duplicate characters: [${[...new Set(b)].join(", ")}]`)}let m=t?.requiredLength??p.length;if(p.length<m)throw new Error("[Ddu64 Constructor] Insufficient characters.");return o(p,i,m,!1,h)}let a=t?.dduSetSymbol??j.dduSetSymbol??"ddu",d=Rr(a),c=d.codaChar?W(d.charSet,d.codaChar):d.charSet,u=o(c,d.paddingChar,d.maxRequiredLength,!0,d.useRepeatPadding),f=d.encodingProfile;return f?(u.encodingProfile=f,u.bitLength=f.bitLength,u.usePowerOfTwo=f.usePowerOfTwo,u.bitsPerPadChar=f.bitsPerPadChar):(u.bitsPerPadChar=d.bitsPerPadChar,u.usePowerOfTwo=d.usePowerOfTwo,d.usePowerOfTwo===!1&&(u.bitLength=d.bitLength)),u}catch(s){if(n)throw s;return oe(t)}}function De(e,r,t){let n=[e,null];for(let s of n){let i=s?{...s}:oe(t);try{let a=i.charSet,d=i.requiredLength,c=Array.from(new Set(a));if(c.length!==a.length){if(r){let p=a.filter((l,h)=>a.indexOf(l)!==h);throw new Error(`[Ddu64 normalizeCharSet] Character set contains duplicate characters: [${[...new Set(p)].join(", ")}]`)}a=c,i.isPredefined||(d=a.length);}if(a.length<d)throw new Error(`[Ddu64 normalizeCharSet] Insufficient characters. Required: ${d}, Has: ${a.length}`);if(d<2)throw new Error("[Ddu64 normalizeCharSet] At least 2 unique characters required.");if(a.length===0)throw new Error("[Ddu64 normalizeCharSet] Empty charset.");if(a.find(p=>p.length!==1)){if(r)throw new Error("[Ddu64 normalizeCharSet] Multi-character symbols are not supported.");continue}if(a.length>Tr){if(r)throw new Error("[Ddu64 normalizeCharSet] Charset size exceeds maximum supported size of 65536.");continue}if(i.padding.length!==1)throw new Error(`[Ddu64 normalizeCharSet] Padding length mismatch. Expected 1, got ${i.padding.length}`);if(a.includes(i.padding)){if(r)throw new Error(`[Ddu64 normalizeCharSet] Padding character "${i.padding}" conflicts with charset.`);a=a.filter(p=>p!==i.padding);}for(let p of a)if(p.includes(`
|
|
5
|
+
`)||p.includes("\r"))throw new Error("[Ddu64 normalizeCharSet] Newline and carriage return characters are reserved.");if(i.padding.includes(`
|
|
6
|
+
`)||i.padding.includes("\r"))throw new Error("[Ddu64 normalizeCharSet] Newline and carriage return characters are reserved.");return {charSet:a.length===d?a:a.slice(0,d),padding:i.padding,isPredefined:i.isPredefined}}catch(a){if(r)throw a}}let o=oe(t);return {charSet:o.charSet.slice(0,o.requiredLength),padding:o.padding,isPredefined:true}}function Ee(e,r,t){for(let n of be){for(let o of e)if(o.includes(n)){let s=`[Ddu64 Constructor] URL-Safe mode conflict: charset character "${o}" contains "${n}".`;if(t)throw new Error(s);return false}if(r.includes(n)){let o=`[Ddu64 Constructor] URL-Safe mode conflict: padding character "${r}" contains "${n}".`;if(t)throw new Error(o);return false}}return true}function Ue(e,r,t){if(t>256)return;let n=Math.min(e.length,t),o=e.slice(0,n),s=new Set;for(let a=0;a<o.length;a++)s.add(o[a]);s.add(r);for(let a=0;a<o.length;a++){let d=o[a];for(let f=0;f<o.length;f++){let p=d+o[f];if(s.has(p))throw new Error(`Combination conflict: "${d}" + "${o[f]}"`);s.add(p);}let c=d+r;if(s.has(c))throw new Error(`Combination conflict: "${d}" + padding`);s.add(c);let u=r+d;if(s.has(u))throw new Error(`Combination conflict: padding + "${d}"`);s.add(u);}let i=r+r;if(s.has(i))throw new Error("Combination conflict: double padding");s.add(i);}function Ir(e,r){return r!==void 0?r?e>0:false:e>0&&(e&e-1)===0}function Rr(e){let r=$(e);if(!r)throw new Error(`CharSet with symbol ${e} not found`);return r}function oe(e){let r=e?.dduSetSymbol??j.dduSetSymbol??"oneCharSet",t=$(r)??$("oneCharSet");if(!t)throw new Error("Critical: No fallback CharSet available");return {charSet:t.codaChar?W(t.charSet,t.codaChar):t.charSet,padding:t.paddingChar,requiredLength:t.maxRequiredLength,bitLength:t.encodingProfile?.bitLength??t.bitLength,isPredefined:true,useRepeatPadding:t.useRepeatPadding,bitsPerPadChar:t.encodingProfile?.bitsPerPadChar??t.bitsPerPadChar,usePowerOfTwo:t.encodingProfile?.usePowerOfTwo??t.usePowerOfTwo,encodingProfile:t.encodingProfile}}var Or="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function xe(e,r,t,n){return t&&n===6&&r==="="&&e.join("")===Or}function Le(e){let r=_r(e);if(r===null)return null;let t=0,n=r.length;for(;n>0&&r[n-1]==="=";)t++,n--;return {payload:r.slice(0,n),paddingBits:t===2?4:t===1?2:0}}function ke(e,r,t){let n=r===4?2:r===2?1:r===0?0:-1;if(n<0)return null;for(let o=0;o<e.length;o++)if(!t(e.charCodeAt(o)))return null;return Mr(e+"=".repeat(n))}function _r(e){let r=e.toBase64;if(typeof r=="function")return r.call(e);let t=globalThis.Buffer;return t?.from?t.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):null}function Mr(e){let r=Uint8Array;if(typeof r.fromBase64=="function")return r.fromBase64(e);let t=globalThis.Buffer;if(t?.from){let n=t.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}return null}function Y(e){if(!e)throw new Error("[Ddu64 adapter] No platform adapter available. Use encodeAsync()/decodeAsync() in browser environments, or provide an adapter via options.adapter.");return e}function Be(e,r,t){let n=Y(e.adapter);if(!n.encryptSync)throw new Error("[Ddu64 encrypt] Sync encryption unavailable. Use encodeAsync() in browser environments.");let o=Re(e,n,"encrypt");return n.encryptSync(r,o,t)}function ve(e,r,t){let n=Y(e.adapter);if(!n.decryptSync)throw new Error("[Ddu64 decrypt] Sync decryption unavailable. Use decodeAsync() in browser environments.");let o=Re(e,n,"decrypt");return n.decryptSync(r,o,t)}function Te(e,r,t,n){let o=Y(e);if(t==="brotli"){if(!o.brotliCompressSync)throw new Error("[Ddu64 compress] Brotli compression is unavailable in the current runtime.");return o.brotliCompressSync(r,n)}if(!o.deflateSync)throw new Error("[Ddu64 compress] Sync compression unavailable. Use encodeAsync() in browser environments.");return o.deflateSync(r,n)}function Ie(e,r,t,n){let o=Y(e);if(t==="brotli"){if(!o.brotliDecompressSync)throw new Error("[Ddu64 decompress] Brotli decompression is unavailable in the current runtime.");return o.brotliDecompressSync(r,n)}if(!o.inflateSync)throw new Error("[Ddu64 decompress] Sync decompression unavailable. Use decodeAsync() in browser environments.");return o.inflateSync(r,n)}function Re(e,r,t){if(e.encryptionKeyHash)return e.encryptionKeyHash;if(!r.deriveKeySync){let o=t==="encrypt"?"encodeAsync":"decodeAsync";throw new Error(`[Ddu64 ${t}] Sync key derivation unavailable. Use ${o}() in browser environments.`)}let n=r.deriveKeySync(e.encryptionKey,e.keyDerivation);return e.setEncryptionKeyHash(n),n}function k(e){let r=e.toLowerCase();return r.includes("adapter")||r.includes("sync")||r.includes("provider")}async function Oe(e,r,t){try{let n=G(e.adapter),o=await Ke(e,n);return await n.encrypt(r,o,t)}catch(n){throw q(n,"encode","encrypt")}}async function _e(e,r,t){try{let n=G(e.adapter),o=await Ke(e,n);return await n.decrypt(r,o,t)}catch(n){throw q(n,"decode","decrypt")}}async function Me(e,r,t,n){try{let o=G(e);if(t==="brotli"){if(!o.brotliCompress)throw new Error("[Ddu64 compress] Brotli compression is unavailable in the current runtime.");return await o.brotliCompress(r,n)}return await o.deflate(r,n)}catch(o){throw q(o,"encode","compress")}}async function Ne(e,r,t,n){try{let o=G(e);if(t==="brotli"){if(!o.brotliDecompress)throw new Error("[Ddu64 decompress] Brotli decompression is unavailable in the current runtime.");return await o.brotliDecompress(r,n)}return await o.inflate(r,n)}catch(o){throw q(o,"decode","decompress")}}function G(e){if(!e)throw new Error("[Ddu64 adapter] No platform adapter available. Use @ddunigma/node or @ddunigma/node/browser, or provide an adapter via options.adapter.");return e}async function Ke(e,r){if(e.encryptionKeyHash)return e.encryptionKeyHash;let t=await r.deriveKey(e.encryptionKey,e.keyDerivation);return e.setEncryptionKeyHash(t),t}function q(e,r,t){let n=E(e);if(k(n))return new N(n,r,e);switch(t){case "compress":return new x(n,e);case "decompress":return new L(n,e);case "encrypt":return new P(n,e);case "decrypt":return new D(n,e)}}function He(e,r,t){return e!=null&&typeof e=="object"&&!Array.isArray(e)?{dduChar:void 0,paddingChar:void 0,dduOptions:e}:{dduChar:e,paddingChar:r,dduOptions:t}}function ze(e){let r=new Int32Array(65536);r.fill(-1);let t=new Uint16Array(e.length);for(let n=0;n<e.length;n++){let o=e[n].charCodeAt(0);r[o]=n,t[n]=o;}return {charCodeLookup:r,charCodes:t}}function B(e,r,t,n){if(e===void 0)return r;if(e===Number.POSITIVE_INFINITY)return Number.POSITIVE_INFINITY;if(!Number.isFinite(e)||e<=0){if(t)throw new Error(`[Ddu64 options] Invalid ${n}. Must be a positive finite number or Infinity.`);return r}return Math.floor(e)}function Fe(e,r,t,n){if(e===0)return 0;if(r<0||r>=t)throw new Error(`[Ddu64 decode] Invalid padding bits: ${r}`);let i=Math.ceil(e/(n?1:2))*t-r;if(i<0)throw new Error("[Ddu64 decode] Invalid decoded bit length");return Math.ceil(i/8)}function Ve(e,r){if(!r&&e.length%2!==0)throw new Error(`[Ddu64 decode] Invalid encoded length for variable charset. Expected multiple of 2, got ${e.length}`)}function We(e,r,t,n){if(e.length===0)return;let o=n?1:2,i=e.length/o*t-r;if(i<0||i%8!==0)throw new Error(`[Ddu64 decode] Invalid encoded bit length. Expected a whole number of bytes, got ${i} bits.`)}function $e(e,r,t,n,o){if(r===0)return;if(e.length===0)throw new Error("[Ddu64 decode] Invalid padding bits without payload");let s=(1<<r)-1,i;if(t){let a=e[e.length-1],d=n[a.charCodeAt(0)];if(d<0)throw new Error(`[Ddu64 decode] Invalid character "${a}" at ${e.length-1}`);i=d;}else {let a=e[e.length-2],d=e[e.length-1],c=n[a.charCodeAt(0)],u=n[d.charCodeAt(0)];if(c<0||u<0)throw new Error("[Ddu64 decode] Invalid character in final encoded chunk");i=c*o+u;}if((i&s)!==0)throw new Error("[Ddu64 decode] Invalid non-zero padding bits in final symbol")}var R="DDS1",v="ELYSIA",T="GRISEO";var Nr=new TextEncoder;function Ye(e,r,t,n=2){let o=e.length,s=r.length,i={cleanedInput:e,paddingBits:0,isEncrypted:false,pipelineVersion:2};if(o<s)return i;let d=Math.max(0,t-1).toString().length;for(let c=Math.min(d,o);c>=1;c--){let u=o-c,f=true;for(let O=u;O<o;O++){let ie=e.charCodeAt(O);if(ie<48||ie>57){f=false;break}}if(!f)continue;let p=e.substring(u),l=parseInt(p,10);if(Number.isNaN(l)||l<0||l>=t||p!==l.toString())continue;let h=u,m=false,y,b=2;h>=2&&e.substring(h-2,h)==="V4"?(b=4,h-=2):h>=2&&e.substring(h-2,h)==="V3"&&(b=3,h-=2),h>=3&&e.substring(h-3,h)==="ENC"&&(m=true,h-=3),h>=v.length&&e.substring(h-v.length,h)===v?(y="deflate",h-=v.length):h>=T.length&&e.substring(h-T.length,h)===T&&(y="brotli",h-=T.length);let C=h-s;if(C>=0&&e.substring(C,h)===r)return {cleanedInput:e.substring(0,C),paddingBits:l,compressionAlgorithm:y,isEncrypted:m,pipelineVersion:b}}if(e.endsWith(r)){let c=0,u=o;for(;u>=s&&e.substring(u-s,u)===r;)c++,u-=s;if(c>0){let f=c*n;if(f<t)return {cleanedInput:e.substring(0,u),paddingBits:f,isEncrypted:false,pipelineVersion:2}}}return i}function Ge(e){let r=e.lastIndexOf("CHK");if(r===-1)return {data:e,checksum:null};let t=e.slice(r+3);return t.length!==8||!/^[0-9a-f]+$/i.test(t)?{data:e,checksum:null}:{data:e.slice(0,r),checksum:t.toLowerCase()}}function Kr(e){return e.length*2+R.length+2}function Pt(e,r){let t=r.compressionAlgorithm==="brotli"?"B":r.compressionAlgorithm==="deflate"?"D":"N",n=r.encrypted?"1":"0";return `${e}${R}${t}${n}${e}`}function Dt(e,r){let t=Kr(r);if(e.length<t||!e.startsWith(r))return null;let n=r.length;if(e.slice(n,n+R.length)!==R)throw new Error("[wireFormat] Invalid stream header magic");let s=e[n+R.length],i=e[n+R.length+1];if(e.slice(t-r.length,t)!==r)throw new Error("[wireFormat] Invalid stream header terminator");let d=s==="B"?"brotli":s==="D"?"deflate":s==="N"?void 0:null;if(d===null)throw new Error("[wireFormat] Invalid stream header compression flag");if(i!=="0"&&i!=="1")throw new Error("[wireFormat] Invalid stream header encryption flag");return {compressionAlgorithm:d,encrypted:i==="1"}}function qe(e){let{paddingBits:r,compressionAlgorithm:t,isEncrypted:n,paddingChar:o,useRepeatPadding:s,bitsPerPadChar:i=2,pipelineVersion:a=2}=e;if(!n&&a!==2)throw new Error("[wireFormat] Pipeline version markers require encryption");if(r===0&&!t&&!n&&a===2)return "";if(s&&!t&&!n&&a===2&&r>0&&r%i===0){let c=r/i;return o.repeat(c)}return o+(t==="deflate"?v:t==="brotli"?T:"")+(n?"ENC":"")+(a===4?"V4":a===3?"V3":"")+r.toString()}function F(e){return Nr.encode(`ddunigma:wire:v4;enc=1;compress=${e.compressionAlgorithm??"none"}`)}function je(e,r,t){let n=r?.checksum??t.defaultChecksum,o=r?.compress!==false,s=r?.encrypt!==false,i=e;t.reportDecodeStart(e.length);let a=r?.chunkSeparator??t.defaultChunkSeparator;i=Se(i,a),t.urlSafe&&(i=Ae(i));let d=null;if(n){let C=Ge(i);d=C.checksum,i=C.data;}t.shouldObfuscate(r)&&(i=t.deobfuscate(i));let{cleanedInput:c,paddingBits:u,compressionAlgorithm:f,isEncrypted:p,pipelineVersion:l}=Ye(i,t.paddingChar,t.bitLength,t.bitsPerPadChar);if(p&&s&&!t.encryptionKey)throw new Error("[Ddu64 decode] Encrypted payload requires an encryptionKey");let h=p&&l===4?F({compressionAlgorithm:f}):void 0;Ve(c,t.usePowerOfTwo),$e(c,u,t.usePowerOfTwo,t.dduCharCodeLookup,t.charSetSize),We(c,u,t.bitLength,t.usePowerOfTwo);let m=B(r?.maxDecodedBytes,t.defaultMaxDecodedBytes,true,"maxDecodedBytes"),y=Fe(c.length,u,t.bitLength,t.usePowerOfTwo);if(y>m)throw new Error(`[Ddu64 decode] Decoded output exceeds limit. Estimated: ${y} bytes, Limit: ${m} bytes`);return t.reportBitpackDecode(c.length,e.length),{decoded:t.decodeChars(c,u),extractedChecksum:d,compressionAlgorithm:f,isEncrypted:p,pipelineVersion:l,encryptionAAD:h,allowInternalDecompress:o,allowInternalDecrypt:s}}function Xe(e){return e.omitFooter?"":qe({paddingBits:e.paddingBits,compressionAlgorithm:e.compressionAlgorithm,isEncrypted:e.isEncrypted,paddingChar:e.paddingChar,useRepeatPadding:e.useRepeatPadding&&!e.compressionAlgorithm&&!e.isEncrypted,bitsPerPadChar:e.bitsPerPadChar,pipelineVersion:e.isEncrypted?e.pipelineVersion:2})}function Ze(e){let r=e.encoded;return e.shouldObfuscate(e.options)&&(r=e.getObfuscationLayer().obfuscate(r)),e.shouldChecksum&&e.checksum&&(r=r+"CHK"+e.checksum),e.urlSafe&&(r=Ce(r)),e.chunkSize&&e.chunkSize>0&&(e.assertSafeChunkSeparator(r,e.chunkSeparator),r=we(r,e.chunkSize,e.chunkSeparator)),r}function Je(e,r){let t=e.length;if(t<=8192){let i=new Uint16Array(t);for(let a=0;a<t;a++)i[a]=r[e[a]];return String.fromCharCode.apply(null,i)}let n=new Uint16Array(t);for(let i=0;i<t;i++)n[i]=r[e[i]];let o=new Array(Math.ceil(t/8192)),s=0;for(let i=0;i<t;i+=8192){let a=n.subarray(i,Math.min(i+8192,t));o[s++]=String.fromCharCode.apply(null,a);}return o.join("")}function Qe(e,r,t,n,o){if(e.length===0)return "";let s=o.canUseNativeBase64?Le(e):null,i,a;if(s)i=s.paddingBits,a=s.payload;else {let c=zr(e,o);i=c.paddingBits,a=Je(c.indices,o.dduCharCodes);}let d=Xe({paddingBits:i,compressionAlgorithm:r,isEncrypted:t,paddingChar:o.paddingChar,useRepeatPadding:o.useRepeatPadding,bitsPerPadChar:o.bitsPerPadChar,pipelineVersion:o.encryptedPipelineVersion,omitFooter:n?.omitFooter});return a+d}function er(e,r,t){let n=e.length;if(n===0)return new Uint8Array(0);let o=t.canUseNativeBase64?ke(e,r,d=>t.dduCharCodeLookup[d]>=0):null;if(o)return o;let i=n>=t.wasmThreshold?new Uint16Array(n):new Array(n);for(let d=0;d<n;d++){let c=t.dduCharCodeLookup[e.charCodeAt(d)];if(c<0)throw new Error(`[Ddu64 decode] Invalid character "${e[d]}" at ${d}`);i[d]=c;}let a=rr(n,t)?Z():null;if(a?.ready&&t.usePowerOfTwo){let d=i instanceof Uint16Array?i:Uint16Array.from(i);return a.decode(d,t.bitLength,r)}return fe(i,r,t.bitPackConfig)}function zr(e,r){let t=rr(e.length,r)?Z():null;return t?.ready&&r.usePowerOfTwo?t.encode(e,r.bitLength):pe(e,r.bitPackConfig)}function rr(e,r){return e>=r.wasmThreshold}function tr(e,r){let t=new Set(e);t.add(r);let n=v+T+"ENC"+"V3"+"V4";for(let o of n)t.add(o);for(let o of "0123456789")t.add(o);return [...t]}function nr(e,r,t){let n=e.decoded;return n=$r(e,t,n),n=Yr(e,r,t,n),dr(e,t,r,n),n=Gr(e,t,n),ur(t,n),n}async function or(e,r,t){let n=e.decoded;if(ir(e,t)&&(t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:55,stage:"decrypt"}),n=await t.decrypt(n,e.encryptionAAD)),ar(e)){let o=cr(r,t);t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:70,stage:"decompress"}),n=await t.decompress(n,e.compressionAlgorithm,o);}return dr(e,t,r,n),sr(e,t)&&(t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:90,stage:"decrypt"}),n=await t.decrypt(n,e.encryptionAAD)),ur(t,n),n}function $r(e,r,t){return ir(e,r)?(r.reportProgress({processedBytes:t.length,totalBytes:t.length,percent:55,stage:"decrypt"}),r.decrypt(t,e.encryptionAAD)):t}function Yr(e,r,t,n){if(!ar(e))return n;let o=cr(r,t);return t.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:70,stage:"decompress"}),t.decompress(n,e.compressionAlgorithm,o)}function Gr(e,r,t){return sr(e,r)?(r.reportProgress({processedBytes:t.length,totalBytes:t.length,percent:90,stage:"decrypt"}),r.decrypt(t,e.encryptionAAD)):t}function ir(e,r){return (e.pipelineVersion===3||e.pipelineVersion===4)&&e.isEncrypted&&!!r.encryptionKey&&e.allowInternalDecrypt}function sr(e,r){return e.pipelineVersion===2&&e.isEncrypted&&!!r.encryptionKey&&e.allowInternalDecrypt}function ar(e){return !!e.compressionAlgorithm&&e.allowInternalDecompress&&(e.pipelineVersion===2||!e.isEncrypted||e.allowInternalDecrypt)}function dr(e,r,t,n){if(!e.extractedChecksum||!(e.pipelineVersion===2||!e.isEncrypted||e.allowInternalDecrypt))return;r.reportProgress({processedBytes:n.length,totalBytes:n.length,percent:85,stage:"checksum"});let o=K(n);if(!ge(o,e.extractedChecksum))throw new M(`[Ddu64 decode] Checksum mismatch. Expected: ${e.extractedChecksum}, Got: ${o}`)}function cr(e,r){return B(e?.maxDecompressedBytes,r.defaultMaxDecompressedBytes,true,"maxDecompressedBytes")}function ur(e,r){e.reportProgress({processedBytes:r.length,totalBytes:r.length,percent:100,stage:"done"});}function lr(e,r,t){let n=pr(r,t),o=typeof e=="string"?z(e):e;fr(t,o.length);let s=n.shouldChecksum?K(o):"",i,a;if(n.shouldCompress){let c=r?.compressionAlgorithm??t.defaultCompressionAlgorithm,u=H(r?.compressionLevel??t.defaultCompressionLevel,c);mr(t,o.length);let f=t.compress(o,c,u);a=f.length,f.length<o.length&&(o=f,i=c);}let d=false;return n.shouldEncrypt&&(yr(t,o.length),o=t.encrypt(o,t.getEncryptionAAD(i)),d=true),{encoded:t.finalize(o,i,d,s,n.shouldChecksum,n.chunkSize,n.chunkSeparator),compressedSize:a}}async function hr(e,r,t){let n=pr(r,t),o=typeof e=="string"?z(e):e;fr(t,o.length);let s=n.shouldChecksum?K(o):"",i;if(n.shouldCompress){let d=r?.compressionAlgorithm??t.defaultCompressionAlgorithm,c=H(r?.compressionLevel??t.defaultCompressionLevel,d);mr(t,o.length);let u=await t.compress(o,d,c);u.length<o.length&&(o=u,i=d);}let a=false;return n.shouldEncrypt&&(yr(t,o.length),o=await t.encrypt(o,t.getEncryptionAAD(i)),a=true),t.finalize(o,i,a,s,n.shouldChecksum,n.chunkSize,n.chunkSeparator)}function pr(e,r){return {shouldCompress:e?.compress??r.defaultCompress,shouldChecksum:e?.checksum??r.defaultChecksum,shouldEncrypt:(e?.encrypt??true)&&r.hasEncryptionKey,chunkSize:e?.chunkSize??r.defaultChunkSize,chunkSeparator:e?.chunkSeparator??r.defaultChunkSeparator}}function fr(e,r){e.reportProgress({processedBytes:0,totalBytes:r,percent:0,stage:"start"});}function mr(e,r){e.reportProgress({processedBytes:r,totalBytes:r,percent:20,stage:"compress"});}function yr(e,r){e.reportProgress({processedBytes:r,totalBytes:r,percent:45,stage:"encrypt"});}var jr=64*1024*1024,Xr=64*1024*1024,gr=class{dduChar;dduCharCodes;paddingChar;bitLength;usePowerOfTwo;dduCharCodeLookup;isPredefinedCharSet;defaultCompress;defaultMaxDecodedBytes;defaultMaxDecompressedBytes;urlSafe;encryptionKey;keyDerivation;encryptionKeyHash;defaultChecksum;defaultChunkSize;defaultChunkSeparator;defaultCompressionLevel;defaultCompressionAlgorithm;useRepeatPadding;bitsPerPadChar;bitPackConfig;wasmThreshold;canUseNativeBase64;payloadCodecContext;adapter;defaultObfuscate;obfuscationLayer;constructor(r,t,n){let o=He(r,t,n);r=o.dduChar,t=o.paddingChar,n=o.dduOptions;let s=n?.throwOnError??false;n?.adapter?this.adapter=n.adapter:this.adapter=void 0;let i=Pe(r,t,n,s),a=De(i,s,n);this.dduChar=a.charSet,this.paddingChar=a.padding,this.isPredefinedCharSet=a.isPredefined,this.defaultCompress=n?.compress??false,this.defaultMaxDecodedBytes=B(n?.maxDecodedBytes,jr,s,"maxDecodedBytes"),this.defaultMaxDecompressedBytes=B(n?.maxDecompressedBytes,Xr,s,"maxDecompressedBytes");let d=this.dduChar.length,c=ye(d),u=n?.usePowerOfTwo,f=i.encodingProfile;this.usePowerOfTwo=f?.usePowerOfTwo??i.usePowerOfTwo??(u!==void 0?u&&c:c);let p=f?.bitLength??(i.isPredefined&&i.usePowerOfTwo!==void 0?i.bitLength:void 0);this.bitLength=p??me(d,this.usePowerOfTwo);let l=ze(this.dduChar);this.dduCharCodeLookup=l.charCodeLookup,this.dduCharCodes=l.charCodes,this.isPredefinedCharSet||Ue(this.dduChar,this.paddingChar,d);let h=n?.urlSafe??false;if(this.urlSafe=h?Ee(this.dduChar,this.paddingChar,s):false,this.encryptionKey=n?.encryptionKey,this.keyDerivation=n?.keyDerivation,this.encryptionKey&&this.adapter?.deriveKeySync&&(this.encryptionKeyHash=this.adapter.deriveKeySync(this.encryptionKey,this.keyDerivation)),this.defaultChecksum=n?.checksum??false,this.defaultChunkSize=n?.chunkSize,this.defaultChunkSeparator=n?.chunkSeparator??`
|
|
7
|
+
`,this.defaultCompressionAlgorithm=n?.compressionAlgorithm??"deflate",this.defaultCompressionLevel=H(n?.compressionLevel,this.defaultCompressionAlgorithm),this.useRepeatPadding=n?.useRepeatPadding??i.useRepeatPadding??false,this.bitsPerPadChar=f?.bitsPerPadChar??i.bitsPerPadChar??2,this.defaultObfuscate=n?.obfuscate??false,this.defaultObfuscate&&!this.encryptionKey)throw new I("[Ddu64 obfuscation] Obfuscation requires encryption to be enabled.");this.bitPackConfig={bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,charsetSize:d},this.wasmThreshold=he(n?.wasmThreshold??4096),this.canUseNativeBase64=xe(this.dduChar,this.paddingChar,this.usePowerOfTwo,this.bitLength),this.payloadCodecContext={bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,bitPackConfig:this.bitPackConfig,wasmThreshold:this.wasmThreshold,canUseNativeBase64:this.canUseNativeBase64,dduCharCodes:this.dduCharCodes,dduCharCodeLookup:this.dduCharCodeLookup,paddingChar:this.paddingChar,useRepeatPadding:this.useRepeatPadding,bitsPerPadChar:this.bitsPerPadChar,encryptedPipelineVersion:4};}encode(r,t){try{return this.encodeInternal(r,t).encoded}catch(n){throw A(n,"encode")}}decode(r,t){try{let n=this.decodeToUint8Array(r,t);return ne(n)}catch(n){throw A(n,"decode")}}decodeToUint8Array(r,t){try{return this.decodeToUint8ArrayInternal(r,t)}catch(n){throw A(n,"decode")}}decodeToUint8ArrayInternal(r,t){let n=this.decodePrelude(r,t);return nr(n,t,{encryptionKey:this.encryptionKey,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,reportProgress:o=>this.reportProgress(t,o),decrypt:(o,s)=>this.decryptSync(o,s),decompress:(o,s,i)=>this.decompressSync(o,s,i)})}async encodeAsync(r,t){try{return await this.encodeAsyncInternal(r,t)}catch(n){throw A(n,"encode")}}async encodeAsyncInternal(r,t){return hr(r,t,{defaultCompress:this.defaultCompress,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm,hasEncryptionKey:!!this.encryptionKey,reportProgress:n=>this.reportProgress(t,n),getEncryptionAAD:n=>F({compressionAlgorithm:n}),compress:(n,o,s)=>Me(this.adapter,n,o,s),encrypt:(n,o)=>Oe(this.getSyncGatewayContext(),n,o),finalize:(n,o,s,i,a,d,c)=>this.finalizeEncode(n,o,s,i,a,d,c,t)})}async decodeAsync(r,t){try{let n=await this.decodeToUint8ArrayAsync(r,t);return ne(n)}catch(n){throw A(n,"decode")}}async decodeToUint8ArrayAsync(r,t){try{return await this.decodeToUint8ArrayAsyncInternal(r,t)}catch(n){throw A(n,"decode")}}async decodeToUint8ArrayAsyncInternal(r,t){let n=this.decodePrelude(r,t);return or(n,t,{encryptionKey:this.encryptionKey,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,reportProgress:o=>this.reportProgress(t,o),decrypt:(o,s)=>_e(this.getSyncGatewayContext(),o,s),decompress:(o,s,i)=>Ne(this.adapter,o,s,i)})}getCharSetInfo(){return {charSet:[...this.dduChar],paddingChar:this.paddingChar,bitLength:this.bitLength,usePowerOfTwo:this.usePowerOfTwo,encoding:"utf-8",defaultCompress:this.defaultCompress,defaultMaxDecodedBytes:this.defaultMaxDecodedBytes,defaultMaxDecompressedBytes:this.defaultMaxDecompressedBytes,urlSafe:this.urlSafe,hasEncryptionKey:!!this.encryptionKey,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm}}getStats(r,t){let o=(typeof r=="string"?z(r):r).length,{encoded:s,compressedSize:i}=this.encodeInternal(r,t),a=s.length,d=o>0?a/o:0,u=(t?.compress??this.defaultCompress)&&i!==void 0&&o>0?i/o:void 0;return {originalSize:o,encodedSize:a,compressedSize:i,compressionRatio:u,expansionRatio:d,charsetSize:this.dduChar.length,bitLength:this.bitLength}}encodeInternal(r,t){return lr(r,t,{defaultCompress:this.defaultCompress,defaultChecksum:this.defaultChecksum,defaultChunkSize:this.defaultChunkSize,defaultChunkSeparator:this.defaultChunkSeparator,defaultCompressionLevel:this.defaultCompressionLevel,defaultCompressionAlgorithm:this.defaultCompressionAlgorithm,hasEncryptionKey:!!this.encryptionKey,reportProgress:n=>this.reportProgress(t,n),getEncryptionAAD:n=>F({compressionAlgorithm:n}),compress:(n,o,s)=>this.compressSync(n,o,s),encrypt:(n,o)=>this.encryptSync(n,o),finalize:(n,o,s,i,a,d,c)=>this.finalizeEncode(n,o,s,i,a,d,c,t)})}finalizeEncode(r,t,n,o,s,i,a,d){this.reportProgress(d,{processedBytes:r.length,totalBytes:r.length,percent:70,stage:"encode"});let c=Qe(r,t,n,d,this.getPayloadCodecContext());return c=this.applyPostEncoding(c,d,o,s,i,a),this.reportProgress(d,{processedBytes:r.length,totalBytes:r.length,percent:100,stage:"done"}),c}applyPostEncoding(r,t,n,o,s,i){return Ze({encoded:r,options:t,checksum:n,shouldChecksum:o,chunkSize:s,chunkSeparator:i,urlSafe:this.urlSafe,shouldObfuscate:a=>this.shouldObfuscate(a),getObfuscationLayer:()=>this.getObfuscationLayer(),assertSafeChunkSeparator:(a,d)=>this.assertSafeChunkSeparator(a,d)})}decodePrelude(r,t){return je(r,t,{defaultChecksum:this.defaultChecksum,defaultChunkSeparator:this.defaultChunkSeparator,defaultMaxDecodedBytes:this.defaultMaxDecodedBytes,urlSafe:this.urlSafe,paddingChar:this.paddingChar,bitLength:this.bitLength,bitsPerPadChar:this.bitsPerPadChar,usePowerOfTwo:this.usePowerOfTwo,dduCharCodeLookup:this.dduCharCodeLookup,charSetSize:this.dduChar.length,encryptionKey:this.encryptionKey,shouldObfuscate:n=>this.shouldObfuscate(n),deobfuscate:n=>this.getObfuscationLayer().deobfuscate(n),decodeChars:(n,o)=>er(n,o,this.getPayloadCodecContext()),reportDecodeStart:n=>{this.reportProgress(t,{processedBytes:0,totalBytes:n,percent:0,stage:"start"});},reportBitpackDecode:(n,o)=>{this.reportProgress(t,{processedBytes:n,totalBytes:o,percent:30,stage:"decode"});}})}getPayloadCodecContext(){return this.payloadCodecContext}reportProgress(r,t){r?.onProgress?.(t);}encryptSync(r,t){try{return Be(this.getSyncGatewayContext(),r,t)}catch(n){let o=E(n);throw k(o)?A(n,"encode"):new P(o,n)}}decryptSync(r,t){try{return ve(this.getSyncGatewayContext(),r,t)}catch(n){let o=E(n);throw k(o)?A(n,"decode"):new D(o,n)}}compressSync(r,t,n){try{return Te(this.adapter,r,t,n)}catch(o){let s=E(o);throw k(s)?A(o,"encode"):new x(s,o)}}decompressSync(r,t,n){try{return Ie(this.adapter,r,t,n)}catch(o){let s=E(o);throw k(s)?A(o,"decode"):new L(s,o)}}getSyncGatewayContext(){return {adapter:this.adapter,encryptionKey:this.encryptionKey,keyDerivation:this.keyDerivation,encryptionKeyHash:this.encryptionKeyHash,setEncryptionKeyHash:r=>{this.encryptionKeyHash=r;}}}getObfuscationLayer(){return this.obfuscationLayer||(this.obfuscationLayer=new _(tr(this.dduChar,this.paddingChar))),this.obfuscationLayer}shouldObfuscate(r){let t=r?.obfuscate??this.defaultObfuscate;if(t&&!this.encryptionKey)throw new I("[Ddu64 obfuscation] Obfuscation requires encryption to be enabled.");return t}assertSafeChunkSeparator(r,t){if(!(t.length===0||this.isLineBreakSeparator(t))&&r.includes(t))throw new Error(`[Ddu64 chunking] Unsafe chunkSeparator "${t}" appears in encoded output. Use a separator that cannot be produced by the charset, footer, checksum, or URL-safe output.`)}isLineBreakSeparator(r){return r===`
|
|
8
|
+
`||r===`\r
|
|
9
|
+
`||r==="\r"}};var br=class e{chars=[];constructor(){}static create(){return new e}static fromUnicodeRange(r,t){return new e().addUnicodeRange(r,t)}static fromString(r){return new e().addString(r)}static base64(){return new e().addString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")}static base32(){return new e().addString("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")}static uppercase(){return e.fromUnicodeRange(65,90)}static lowercase(){return e.fromUnicodeRange(97,122)}static digits(){return e.fromUnicodeRange(48,57)}static hangulJamo(){return new e().addUnicodeRange(4352,4370).addUnicodeRange(4449,4469).addUnicodeRange(4520,4546)}addUnicodeRange(r,t){for(let n=r;n<=t;n++)this.chars.push(String.fromCodePoint(n));return this}addString(r){return typeof r=="string"?this.chars.push(...r):this.chars.push(...r),this}add(...r){return this.chars.push(...r),this}excludeConfusing(){let r=new Set(["0","O","o","1","l","I","i","|","L"]);return this.chars=this.chars.filter(t=>!r.has(t)),this}exclude(...r){let t=new Set(r);return this.chars=this.chars.filter(n=>!t.has(n)),this}excludeUrlUnsafe(){let r=new Set(["+","/","=","?","&","#","%"," "]);return this.chars=this.chars.filter(t=>!r.has(t)),this}unique(){return this.chars=[...new Set(this.chars)],this}shuffle(r){let t=r!==void 0?this.seededRandom(r):Math.random;for(let n=this.chars.length-1;n>0;n--){let o=Math.floor(t()*(n+1));[this.chars[n],this.chars[o]]=[this.chars[o],this.chars[n]];}return this}seededRandom(r){let t=r|0||1;return ()=>(t^=t<<13,t^=t>>17,t^=t<<5,(t>>>0)/4294967296)}limit(r){return this.chars=this.chars.slice(0,r),this}limitToPowerOfTwo(){let r=this.chars.length;if(r===0)return this;let t=1<<Math.floor(Math.log2(r));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(r){let t=[...this.chars],n=r;if(!n){let o=["=",".","_","-","~","!"];for(let s of o)if(!t.includes(s)){n=s;break}if(!n)throw new Error("Cannot find suitable padding character")}return {charset:t,padding:n}}};exports.A=Dt;exports.B=gr;exports.C=br;exports.a=se;exports.b=_;exports.c=et;exports.d=tt;exports.e=nt;exports.f=Z;exports.g=ot;exports.h=Sr;exports.i=g;exports.j=J;exports.k=Q;exports.l=x;exports.m=L;exports.n=P;exports.o=D;exports.p=M;exports.q=ee;exports.r=re;exports.s=N;exports.t=I;exports.u=te;exports.v=Pr;exports.w=A;exports.x=He;exports.y=Kr;exports.z=Pt;//# sourceMappingURL=chunk-FACJ5LAG.cjs.map
|
|
10
|
+
//# sourceMappingURL=chunk-FACJ5LAG.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {z,w,y,A}from'./chunk-65RDFQV7.js';function R(){let e=globalThis;return e.Deno?.version?.deno?"deno":e.Bun?.version?"bun":e.process?.versions?.node?"node":typeof e.EdgeRuntime=="string"||typeof e.WebSocketPair<"u"&&e.crypto?.subtle?"edge":typeof e.crypto<"u"&&e.crypto?.subtle?"browser":"unknown"}function W(e,n){let r=e.getCharSetInfo(),d=n?.compress??r.defaultCompress,p=(n?.encrypt??true)&&r.hasEncryptionKey,y=n?.checksum??r.defaultChecksum,t=d?n?.compressionAlgorithm??r.defaultCompressionAlgorithm:void 0,m=r.paddingChar,f=D(r,{compressed:d,encrypted:p,checksum:y}),c=false,s=[],h=0,o=null;return new TransformStream({async transform(a,u){if(f){if(!c){let k=z(m,{compressionAlgorithm:void 0,encrypted:false});u.enqueue(k),c=true;}let i;o&&o.length>0?(i=new Uint8Array(o.length+a.length),i.set(o,0),i.set(a,o.length)):i=a;let g=r.bitLength,S=U(g,8)/8,l=Math.floor(i.length/S)*S;if(l>0){let k=i.subarray(0,l),E=await e.encodeAsync(k,{compress:false,encrypt:false,checksum:false,chunkSize:void 0,chunkSeparator:void 0,omitFooter:true});u.enqueue(E);}l<i.length?o=i.slice(l):o=null;}else s.push(a),h+=a.length;},async flush(a){try{if(f){if(!c){let u=z(m,{compressionAlgorithm:void 0,encrypted:!1});a.enqueue(u);}if(o&&o.length>0){let u=await e.encodeAsync(o,{compress:!1,encrypt:!1,checksum:!1,chunkSize:void 0,chunkSeparator:void 0});a.enqueue(u);}o=null;}else {let u=z(m,{compressionAlgorithm:t,encrypted:p});if(a.enqueue(u),h>0){let i=new Uint8Array(h),g=0;for(let l of s)i.set(l,g),g+=l.length;let S=await e.encodeAsync(i,{...n,compress:d,encrypt:p,checksum:y,chunkSize:void 0,chunkSeparator:void 0});a.enqueue(S);}s=[],h=0;}}catch(u){a.error(w(u,"stream"));}}})}function L(e,n){let r=e.getCharSetInfo(),d=r.paddingChar,p=y(d),y$1=n?.checksum??r.defaultChecksum,t="",m=false,f=null;return new TransformStream({async transform(c,s){if(t+=c,!m&&t.length>=p){if(!t.startsWith(d)){s.error(new Error("[WebStreams decode] Invalid or missing stream header"));return}if(f=A(t,d),f===null){s.error(new Error("[WebStreams decode] Invalid or missing stream header"));return}if(f.encrypted&&!r.hasEncryptionKey){s.error(new Error("[WebStreams decode] Encrypted stream requires an encryptionKey"));return}m=true,t=t.slice(p);}},async flush(c){try{if(!m){if(t.length===0)return;c.error(new Error("[WebStreams decode] Incomplete stream header"));return}if(t.length===0)return;let s=f.compressionAlgorithm,h=await e.decodeToUint8ArrayAsync(t,{...n,compress:n?.compress,compressionAlgorithm:s,encrypt:n?.encrypt,checksum:y$1,chunkSize:void 0,chunkSeparator:void 0});h.length>0&&c.enqueue(h),t="";}catch(s){c.error(w(s,"stream"));}}})}function D(e,n){return e.usePowerOfTwo&&!n.compressed&&!n.encrypted&&!n.checksum}function U(e,n){return e*n/I(e,n)}function I(e,n){for(;n!==0;){let r=n;n=e%n,e=r;}return e}export{R as a,W as b,L as c};//# sourceMappingURL=chunk-M7526IW7.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-M7526IW7.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c,a,d}from'./chunk-QR43FNIY.js';var h=new Map;function m(t){if(t.buffer instanceof ArrayBuffer)return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);let e=new Uint8Array(t.byteLength);return e.set(t),e.buffer}function A(t){let e=h.get(t);if(e!==void 0)return e;if(typeof CompressionStream>"u"||typeof DecompressionStream>"u")return false;try{return new CompressionStream(t),new DecompressionStream(t),h.set(t,!0),!0}catch{return false}}function l(t,e){if(!A(t)){let n=t==="brotli"?"Brotli":"Deflate raw";throw new Error(`[Ddu64 ${e}] ${n} ${e}ion is unsupported in the current runtime. CompressionStream/DecompressionStream does not support "${t}".`)}return t}var b=class{supportsSyncCrypto=false;supportsSyncCompression=false;runtime;constructor(e="browser"){this.runtime=e;}get supportsBrotli(){return A("brotli")}async deriveKey(e,n){let r=new TextEncoder().encode(e);if(n?.algorithm==="pbkdf2"){let a$1=await crypto.subtle.importKey("raw",r,"PBKDF2",false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:d(n.salt),iterations:a(n.iterations),hash:c(n.hash)},a$1,256);return new Uint8Array(i)}let c$1=await crypto.subtle.digest("SHA-256",r);return new Uint8Array(c$1)}async encrypt(e,n,s){let r=crypto.getRandomValues(new Uint8Array(12)),c=await crypto.subtle.importKey("raw",m(n),{name:"AES-GCM"},false,["encrypt"]),a={name:"AES-GCM",iv:r,tagLength:128};s&&s.length>0&&(a.additionalData=m(s));let i=await crypto.subtle.encrypt(a,c,m(e)),o=new Uint8Array(i),p=o.slice(0,o.length-16),u=o.slice(o.length-16),y=new Uint8Array(28+p.length);return y.set(r,0),y.set(u,12),y.set(p,28),y}async decrypt(e,n,s){if(e.length<28)throw new Error("[Ddu64 decrypt] Encrypted data is invalid. Payload must be at least 28 bytes (12 IV + 16 authTag + ciphertext).");let r=e.slice(0,12),c=e.slice(12,28),a=e.slice(28),i=new Uint8Array(a.length+16);i.set(a,0),i.set(c,a.length);let o=await crypto.subtle.importKey("raw",m(n),{name:"AES-GCM"},false,["decrypt"]);try{let p={name:"AES-GCM",iv:r,tagLength:128};s&&s.length>0&&(p.additionalData=m(s));let u=await crypto.subtle.decrypt(p,o,m(i));return new Uint8Array(u)}catch{throw new Error("[Ddu64 decrypt] Decryption failed: data tampering or incorrect key.")}}randomBytes(e){return crypto.getRandomValues(new Uint8Array(e))}async deflate(e,n){if(typeof CompressionStream>"u")throw new Error("[Ddu64 compress] Deflate compression is unsupported in the current runtime. CompressionStream API is not available.");let s=this.getDeflateFormat("compress"),r=new CompressionStream(s);return this.writeAndReadStream(r,e)}async inflate(e,n){if(typeof DecompressionStream>"u")throw new Error("[Ddu64 decompress] Deflate decompression is unsupported in the current runtime. DecompressionStream API is not available.");let s=this.getDeflateFormat("decompress"),r=new DecompressionStream(s);return this.writeAndReadStream(r,e,n)}async brotliCompress(e,n){let s=l("brotli","compress"),r=new CompressionStream(s);return this.writeAndReadStream(r,e)}async brotliDecompress(e,n){let s=l("brotli","decompress"),r=new DecompressionStream(s);return this.writeAndReadStream(r,e,n)}getDeflateFormat(e){return l("deflate-raw",e)}async writeAndReadStream(e,n,s){let r=e.writable.getWriter(),c=e.readable.getReader(),a=(async()=>{await r.write(new Uint8Array(m(n))),await r.close();})(),i=this.readAllChunks(c,s);try{let[o]=await Promise.all([i,a]);return o}catch(o){throw await c.cancel(o).catch(()=>{}),await r.abort(o).catch(()=>{}),o}}async readAllChunks(e,n){let s=[],r=0;for(;;){let{done:i,value:o}=await e.read();if(i)break;if(r+=o.length,n!==void 0&&r>n)throw new Error(`[Ddu64 decompress] Decompressed size exceeds limit. Estimated ${r}+ bytes exceeds maximum of ${n} bytes.`);s.push(o);}let c=new Uint8Array(r),a=0;for(let i of s)c.set(i,a),a+=i.length;return c}};export{b as a};//# sourceMappingURL=chunk-P7WJ2LOQ.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-P7WJ2LOQ.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkNY4FGVF3_cjs=require('./chunk-NY4FGVF3.cjs');var h=new Map;function m(t){if(t.buffer instanceof ArrayBuffer)return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);let e=new Uint8Array(t.byteLength);return e.set(t),e.buffer}function A(t){let e=h.get(t);if(e!==void 0)return e;if(typeof CompressionStream>"u"||typeof DecompressionStream>"u")return false;try{return new CompressionStream(t),new DecompressionStream(t),h.set(t,!0),!0}catch{return false}}function l(t,e){if(!A(t)){let n=t==="brotli"?"Brotli":"Deflate raw";throw new Error(`[Ddu64 ${e}] ${n} ${e}ion is unsupported in the current runtime. CompressionStream/DecompressionStream does not support "${t}".`)}return t}var b=class{supportsSyncCrypto=false;supportsSyncCompression=false;runtime;constructor(e="browser"){this.runtime=e;}get supportsBrotli(){return A("brotli")}async deriveKey(e,n){let r=new TextEncoder().encode(e);if(n?.algorithm==="pbkdf2"){let a=await crypto.subtle.importKey("raw",r,"PBKDF2",false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:chunkNY4FGVF3_cjs.d(n.salt),iterations:chunkNY4FGVF3_cjs.a(n.iterations),hash:chunkNY4FGVF3_cjs.c(n.hash)},a,256);return new Uint8Array(i)}let c=await crypto.subtle.digest("SHA-256",r);return new Uint8Array(c)}async encrypt(e,n,s){let r=crypto.getRandomValues(new Uint8Array(12)),c=await crypto.subtle.importKey("raw",m(n),{name:"AES-GCM"},false,["encrypt"]),a={name:"AES-GCM",iv:r,tagLength:128};s&&s.length>0&&(a.additionalData=m(s));let i=await crypto.subtle.encrypt(a,c,m(e)),o=new Uint8Array(i),p=o.slice(0,o.length-16),u=o.slice(o.length-16),y=new Uint8Array(28+p.length);return y.set(r,0),y.set(u,12),y.set(p,28),y}async decrypt(e,n,s){if(e.length<28)throw new Error("[Ddu64 decrypt] Encrypted data is invalid. Payload must be at least 28 bytes (12 IV + 16 authTag + ciphertext).");let r=e.slice(0,12),c=e.slice(12,28),a=e.slice(28),i=new Uint8Array(a.length+16);i.set(a,0),i.set(c,a.length);let o=await crypto.subtle.importKey("raw",m(n),{name:"AES-GCM"},false,["decrypt"]);try{let p={name:"AES-GCM",iv:r,tagLength:128};s&&s.length>0&&(p.additionalData=m(s));let u=await crypto.subtle.decrypt(p,o,m(i));return new Uint8Array(u)}catch{throw new Error("[Ddu64 decrypt] Decryption failed: data tampering or incorrect key.")}}randomBytes(e){return crypto.getRandomValues(new Uint8Array(e))}async deflate(e,n){if(typeof CompressionStream>"u")throw new Error("[Ddu64 compress] Deflate compression is unsupported in the current runtime. CompressionStream API is not available.");let s=this.getDeflateFormat("compress"),r=new CompressionStream(s);return this.writeAndReadStream(r,e)}async inflate(e,n){if(typeof DecompressionStream>"u")throw new Error("[Ddu64 decompress] Deflate decompression is unsupported in the current runtime. DecompressionStream API is not available.");let s=this.getDeflateFormat("decompress"),r=new DecompressionStream(s);return this.writeAndReadStream(r,e,n)}async brotliCompress(e,n){let s=l("brotli","compress"),r=new CompressionStream(s);return this.writeAndReadStream(r,e)}async brotliDecompress(e,n){let s=l("brotli","decompress"),r=new DecompressionStream(s);return this.writeAndReadStream(r,e,n)}getDeflateFormat(e){return l("deflate-raw",e)}async writeAndReadStream(e,n,s){let r=e.writable.getWriter(),c=e.readable.getReader(),a=(async()=>{await r.write(new Uint8Array(m(n))),await r.close();})(),i=this.readAllChunks(c,s);try{let[o]=await Promise.all([i,a]);return o}catch(o){throw await c.cancel(o).catch(()=>{}),await r.abort(o).catch(()=>{}),o}}async readAllChunks(e,n){let s=[],r=0;for(;;){let{done:i,value:o}=await e.read();if(i)break;if(r+=o.length,n!==void 0&&r>n)throw new Error(`[Ddu64 decompress] Decompressed size exceeds limit. Estimated ${r}+ bytes exceeds maximum of ${n} bytes.`);s.push(o);}let c=new Uint8Array(r),a=0;for(let i of s)c.set(i,a),a+=i.length;return c}};exports.a=b;//# sourceMappingURL=chunk-RFBXQWSA.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-RFBXQWSA.cjs.map
|