/** * JData decoding (https://neurojson.org/jdata/draft3): the annotated forms of a JSON or BJData * document turned into JavaScript values. * * Copyright (c) 2019-2026 Qianqian Fang . BSD 3-clause license. */ import { Codec, getCodec, base64ToBytes, unshuffle, own, takeOwned, ZLIB_CODEC, GZIP_CODEC } from './codecs'; import { NDArray, SparseArray, canonicalType, typedArrayFor, ELEM_BYTES, toTyped, specialNumber, product, nest, reorder, isTypedArray, typeOfTypedArray } from './ndarray'; import { halfToFloat } from './half'; export interface DecodeOptions { /** N-D arrays as: 'auto' (default: numjs NdArray when numjs is loaded or passed as `nj`, else * NDArray), 'ndarray' (NDArray), 'numjs', 'nested' (nested arrays), 'typed' (the flat typed * array), 'jdata' (an {_ArrayType_, _ArraySize_, _ArrayData_: TypedArray} object, for BJData), or * a function (data, shape, dtype) => value */ ndarray?: 'auto' | 'ndarray' | 'numjs' | 'nested' | 'typed' | 'jdata' | ((data: any, shape: number[], dtype: string) => any); /** the numjs module (default: the global nj) */ nj?: any; /** sparse arrays as SparseArray (default 'sparse') or 'dense' */ sparse?: 'sparse' | 'dense'; /** special matrices (_ArrayShape_) are always expanded; tables as an object of columns * ('columns', default) or an array of records ('records') */ table?: 'columns' | 'records'; /** _ArrayZipData_ text is base64 (default true; false: a binary string, one byte per char) */ base64?: boolean; /** codecs for this call, by _ArrayZipType_ (see registerCodec) */ codecs?: { [name: string]: Codec }; /** decode nested values too (default true) */ recursive?: boolean; /** _ByteStream_ data as Uint8Array (default) or, in browsers, 'blob' */ bytestream?: 'bytes' | 'blob'; } const MAX_ELEMENTS = Math.pow(2, 31); function isFlag(x: any): boolean { if (Array.isArray(x) || isTypedArray(x)) { return x.length > 0 && !!x[0]; } return !!x; } function numbers(x: any): number[] { if (x === undefined || x === null) { return []; } if (typeof x === 'number' || typeof x === 'bigint') { return [Number(x)]; } if (x && x._ArrayData_ !== undefined && x._ArrayType_ !== undefined) { return Array.from(x._ArrayData_ as ArrayLike, Number); } return Array.from(x as ArrayLike, Number); } /** Bytes of a _ArrayZipData_ (base64 text, bytes, or an array of byte values). */ export function zipBytes(z: any, base64: boolean, isBase64Codec: boolean): Uint8Array { if (typeof z === 'string') { if (base64 && !isBase64Codec) { // the text is base64 of the compressed stream (a base64 zip type: the codec decodes it) return base64ToBytes(z); } const b = new Uint8Array(z.length); for (let k = 0; k < z.length; k++) { b[k] = z.charCodeAt(k) & 255; } return b; } if (z && z.bytes instanceof Uint8Array && typeof z.toString === 'function') { return z.bytes; // (a bjd HighPrec) } if (z instanceof Uint8Array) { return z; } if (isTypedArray(z)) { return new Uint8Array(z.buffer, z.byteOffset, z.byteLength); } if (z && z._ArrayData_ !== undefined) { return zipBytes(z._ArrayData_, base64, isBase64Codec); } if (Array.isArray(z)) { return Uint8Array.from(z); } throw new Error('jdata: _ArrayZipData_ is not text or bytes'); } /** Numbers of type t from little- or big-endian bytes. */ function fromBytes(b: Uint8Array, t: string, count: number, big: boolean): any { const w = ELEM_BYTES[t]; if (b.length < count * w) { throw new Error('jdata: ' + b.length + ' bytes for ' + count + ' ' + t + ' values'); } // (bytes made by a codec here are kept; others are copied: they may be a view of the input) const raw = b.length === count * w && takeOwned(b) ? b : own(b.subarray(0, count * w)); if (big && w > 1) { for (let k = 0; k < raw.length; k += w) { for (let i = 0, j = w - 1; i < j; i++, j--) { const x = raw[k + i]; raw[k + i] = raw[k + j]; raw[k + j] = x; } } } if (t === 'half') { const v = new DataView(raw.buffer); const out = new Float32Array(count); for (let k = 0; k < count; k++) { out[k] = halfToFloat(v.getUint16(2 * k, true)); } return out; } return new (typedArrayFor(t))(raw.buffer, 0, count); } /** Flat row-major values and the shape of an _ArrayData_ (an array, nested arrays, a typed * array, a BJData N-D object, an NDArray). */ function flatData(x: any): { values: any; shape: number[] } { if (x instanceof NDArray) { return { values: x.data, shape: x.shape.slice() }; } if (isTypedArray(x)) { return { values: x, shape: [x.length] }; } if (x && typeof x === 'object' && x._ArrayType_ !== undefined && x._ArrayData_ !== undefined && x._ArraySize_ !== undefined) { // a packed N-D array read by bjd const shape = numbers(x._ArraySize_); let v = flatData(x._ArrayData_).values; if (x._ArrayOrder_ && String(x._ArrayOrder_)[0].toLowerCase() === 'c') { v = reorder(v, shape); } return { values: v, shape }; } if (!Array.isArray(x)) { return { values: [x], shape: [1] }; } const shape: number[] = []; let y: any = x; while (Array.isArray(y)) { shape.push(y.length); y = y[0]; } if (shape.length === 1) { return { values: x, shape }; } const out: any[] = []; const walk = (z: any, k: number) => { if (k === shape.length - 1) { const f = flatData(z); for (let i = 0; i < f.values.length; i++) { out.push(f.values[i]); } return; } for (const e of z) { walk(e, k + 1); } }; walk(x, 0); return { values: out, shape }; } export class JDataDecoder { private o: DecodeOptions; private mode: any; private unzipped?: Map; /** unzipped: _ArrayZipData_ entries already decompressed (decodeAsync) */ constructor(opts: DecodeOptions = {}, unzipped?: Map) { this.o = opts; this.unzipped = unzipped; let mode: any = opts.ndarray || 'auto'; if (mode === 'auto' || mode === 'numjs') { const nj = opts.nj || (typeof globalThis !== 'undefined' ? (globalThis as any).nj : undefined); mode = nj && nj.NdArray ? { nj } : mode === 'numjs' ? null : 'ndarray'; if (!mode) { throw new Error('jdata: ndarray "numjs" needs numjs (pass it as the nj option)'); } } this.mode = mode; } /** An N-D array in the requested form. */ nd(data: any, shape: number[], dtype: string, imag?: any): any { const m = this.mode; if (typeof m === 'function') { return imag !== undefined ? { re: m(data, shape, dtype), im: m(imag, shape, dtype) } : m(data, shape, dtype); } if (m === 'ndarray') { return new NDArray(data, shape, dtype, imag); } if (imag !== undefined && m !== 'ndarray') { return { re: this.nd(data, shape, dtype), im: this.nd(imag, shape, dtype) }; } switch (m) { case 'nested': return nest(Array.from(data), shape); case 'typed': return data; case 'jdata': return { _ArrayType_: dtype === 'logical' ? 'uint8' : dtype, _ArraySize_: shape.slice(), _ArrayData_: data }; } // numjs: no 64-bit integers, no half (its float32 holds them) const nj = m.nj; const NJ: { [t: string]: string } = { int8: 'int8', uint8: 'uint8', logical: 'uint8', int16: 'int16', uint16: 'uint16', int32: 'int32', uint32: 'uint32', half: 'float32', single: 'float32', double: 'float64' }; if (!NJ[dtype]) { return new NDArray(data, shape, dtype); } const a = nj.array(data, NJ[dtype]); return shape.length === 1 ? a : a.reshape(shape); } value(x: any): any { if (x === null || x === undefined) { return x; } if (typeof x === 'string') { if (x.length <= 6 && x.charCodeAt(x.length - 1) === 95 && (x === '_NaN_' || x === '_Inf_' || x === '-_Inf_' || x === '+_Inf_')) { return specialNumber(x); } return x; } if (typeof x !== 'object' || isTypedArray(x) || x instanceof NDArray) { return x; } if (Array.isArray(x)) { return this.o.recursive === false ? x : x.map((e) => this.value(e)); } if (x instanceof Map || (x.constructor && x.constructor.name === 'HighPrec') || (x.constructor && x.constructor.name === 'Extension')) { return x; } if (x._ArrayType_ !== undefined && (x._ArrayData_ !== undefined || x._ArrayZipData_ !== undefined || x._ArrayShape_ !== undefined)) { return this.array(x); } if (x._MapData_ !== undefined && Array.isArray(x._MapData_)) { const m = new Map(); for (const e of x._MapData_) { m.set(this.value(e[0]), this.value(e[1])); } return m; } if (x._EnumKey_ !== undefined && x._EnumValue_ !== undefined) { return this.enumeration(x); } if (x._TableRecords_ !== undefined) { return this.table(x); } if (x._ByteStream_ !== undefined) { return this.bytestream(x._ByteStream_); } const out: any = {}; for (const k of Object.keys(x)) { let v = x[k]; let key = k; if (this.o.recursive !== false) { const m = /^_TableData_\((.*)\)$/.exec(k); if (m && v && typeof v === 'object' && v._TableRecords_ !== undefined) { key = m[1]; } v = this.value(v); } if (key === '__proto__') { Object.defineProperty(out, key, { value: v, writable: true, enumerable: true, configurable: true }); } else { out[key] = v; } } if (Object.keys(out).length === 1 && out._TableData_ !== undefined && x._TableData_ && x._TableData_._TableRecords_ !== undefined) { return out._TableData_; } return out; } // ---- annotated arrays ------------------------------------------------------------------- array(x: any): any { const t = canonicalType(x._ArrayType_); if (!t) { throw new Error('jdata: unknown _ArrayType_ "' + x._ArrayType_ + '"'); } const size = numbers(x._ArraySize_); const iscomplex = isFlag(x._ArrayIsComplex_); const issparse = isFlag(x._ArrayIsSparse_); const colmajor = x._ArrayOrder_ !== undefined && String(x._ArrayOrder_)[0].toLowerCase() === 'c'; const shapeSpec = x._ArrayShape_; // the pre-processed array: its flat row-major values and dimensions let values: any; let pre: number[]; if (x._ArrayZipData_ !== undefined) { if (x._ArrayData_ !== undefined) { throw new Error('jdata: _ArrayData_ and _ArrayZipData_ under the same node'); } pre = numbers(x._ArrayZipSize_); if (!pre.length) { pre = [product(size)]; } const ztype = x._ArrayZipType_ === undefined ? 'zlib' : String(x._ArrayZipType_); const codec = getCodec(ztype, this.o.codecs); const isB64 = ztype.toLowerCase() === 'base64'; const big = x._ArrayZipEndian_ !== undefined && String(x._ArrayZipEndian_).toLowerCase() === 'big'; const nshuffle = x._ArrayShuffle_ !== undefined ? Number(numbers(x._ArrayShuffle_)[0]) : 0; if (nshuffle < 0) { throw new Error('jdata: bit-wise shuffled payloads (_ArrayShuffle_ < 0) are not supported'); } const zopts = { level: x._ArrayZipLevel_, options: x._ArrayZipOptions_, type: t }; // the bytes of one payload (count values, when known), unshuffled const bytesOf = (z: any, count?: number): Uint8Array => { const done = this.unzipped && (codec === ZLIB_CODEC || codec === GZIP_CODEC) ? this.unzipped.get(z) : undefined; if (done) { this.unzipped!.delete(z); // (used once: the array takes the bytes) } let b = done || codec.decode(zipBytes(z, this.o.base64 !== false, isB64), count === undefined ? undefined : count * ELEM_BYTES[t as string], zopts); if (nshuffle > 1) { b = unshuffle(b, nshuffle); } return b; }; const inflate = (z: any, count: number): any => fromBytes(bytesOf(z, count), t as string, count, big); if (x._ArrayChunks_ !== undefined && Array.isArray(x._ArrayZipData_) && numbers(x._ArrayChunks_).length === 1) { // 1-D tiles: slices of the byte stream of the pre-processed array const parts = x._ArrayZipData_.map((z: any) => bytesOf(z)); const all = new Uint8Array(parts.reduce((n: number, b: Uint8Array) => n + b.length, 0)); let at = 0; for (const b of parts) { all.set(b, at); at += b.length; } values = fromBytes(all, t, product(pre), big); } else if (x._ArrayChunks_ !== undefined && Array.isArray(x._ArrayZipData_)) { values = this.chunks(x, t, size, pre, iscomplex, issparse || shapeSpec !== undefined, colmajor, inflate); if (values.pre) { pre = values.pre; } values = values.values; } else { const count = product(pre); if (count > MAX_ELEMENTS) { throw new Error('jdata: array too large'); } values = inflate(x._ArrayZipData_, count); } } else if (x._ArrayData_ !== undefined) { const f = flatData(x._ArrayData_); values = f.values; pre = x._ArrayZipSize_ !== undefined ? numbers(x._ArrayZipSize_) : f.shape; values = toTyped(values, t); } else { values = new (typedArrayFor(t))(0); pre = [0]; } if (pre.length === 1) { pre = [1, pre[0]]; } let out: any; if (issparse) { out = this.sparse(values, pre, size, t, iscomplex); } else if (shapeSpec !== undefined) { out = this.special(values, pre, size, t, iscomplex, shapeSpec); } else { let re = values, im: any; if (iscomplex) { if (values.length % 2) { throw new Error('jdata: a complex array needs as many real as imaginary parts'); } const half = values.length / 2; re = values.slice(0, half); im = values.slice(half); } let shape = size.length ? size : [re.length]; if (product(shape) !== re.length) { throw new Error('jdata: ' + re.length + ' values for _ArraySize_ [' + shape + ']'); } if (colmajor) { re = reorder(re, shape); if (im !== undefined) { im = reorder(im, shape); } } if (x._ArrayFillValue_ !== undefined && (t === 'single' || t === 'double' || t === 'half')) { const fv = Number(numbers(x._ArrayFillValue_)[0]); for (let k = 0; k < re.length; k++) { if (re[k] === fv) { re[k] = NaN; } } } if (!shape.length) { shape = [1]; } out = this.nd(re, shape, t, im); } if (out instanceof NDArray && (x._ArrayLabel_ !== undefined || x._ArrayCoords_ !== undefined || x._ArrayUnits_ !== undefined)) { out.attrs = {}; if (x._ArrayLabel_ !== undefined) { out.attrs.label = x._ArrayLabel_; } if (x._ArrayCoords_ !== undefined) { out.attrs.coords = this.value(x._ArrayCoords_); } if (x._ArrayUnits_ !== undefined) { out.attrs.units = x._ArrayUnits_; } } return out; } /** The pre-processed array of _ArrayChunks_ tiles. */ private chunks(x: any, t: string, size: number[], pre: number[], iscomplex: boolean, nondense: boolean, colmajor: boolean, inflate: (z: any, count: number) => any): { values: any; pre?: number[] } { const chunk = numbers(x._ArrayChunks_); const parts: any[] = x._ArrayZipData_; const Ctor = typedArrayFor(t); // N-D tiles: of _ArraySize_ for dense arrays (each tile [real..., imag...] when complex), // of _ArrayZipSize_ for sparse and special ones; row-major tiles in row-major order, or // column-major ones in column-major order for _ArrayOrder_ "c" const dims = nondense ? pre.slice() : size.slice(); const nd = dims.length; const cs = chunk.slice(); while (cs.length < nd) { cs.unshift(dims[nd - cs.length - 1]); } for (let k = 0; k < nd; k++) { cs[k] = Math.min(cs[k], dims[k]); } const grid = dims.map((d, k) => Math.ceil(d / cs[k])); const ntiles = product(grid); if (ntiles !== parts.length) { throw new Error('jdata: ' + parts.length + ' chunks, ' + ntiles + ' expected'); } const total = product(dims); const re = new Ctor(total); const im = iscomplex && !nondense ? new Ctor(total) : undefined; const order = (shape: number[]) => { // the dimension order in which a tile or the grid is walked (fastest last) const ks = shape.map((_, k) => k); return colmajor && !nondense ? ks.reverse() : ks; }; const gidx = new Array(nd).fill(0); const st = new Array(nd); let s = 1; for (let k = nd - 1; k >= 0; k--) { st[k] = s; s *= dims[k]; } for (let ci = 0; ci < ntiles; ci++) { const lo = gidx.map((g: number, k: number) => g * cs[k]); const ext = lo.map((l: number, k: number) => Math.min(cs[k], dims[k] - l)); const count = product(ext); const v = inflate(parts[ci], iscomplex && !nondense ? 2 * count : count); // place the tile, walking it in its storage order const ord = order(ext); const tidx = new Array(nd).fill(0); for (let e = 0; e < count; e++) { let p = 0; for (let k = 0; k < nd; k++) { p += (lo[k] + tidx[k]) * st[k]; } re[p] = v[e]; if (im) { im[p] = v[count + e]; } for (let j = nd - 1; j >= 0; j--) { const k = ord[j]; if (++tidx[k] < ext[k]) { break; } tidx[k] = 0; } } const gord = order(grid); for (let j = nd - 1; j >= 0; j--) { const k = gord[j]; if (++gidx[k] < grid[k]) { break; } gidx[k] = 0; } } if (nondense) { return { values: re }; } let all: any = re; if (colmajor) { // (the assembled array is row-major; the caller reorders column-major data) all = reorder(re, dims, true); } if (im) { const both = new Ctor(2 * total); both.set(all, 0); both.set(colmajor ? reorder(im, dims, true) : im, total); return { values: both, pre: [2, total] }; } return { values: all, pre: [1, total] }; } private sparse(values: any, pre: number[], size: number[], t: string, iscomplex: boolean): any { const rows = pre[0]; const nnz = rows ? values.length / rows : 0; const nval = iscomplex ? 2 : 1; const nidx = rows - nval; const shape = size.length === 1 ? [1, size[0]] : size.slice(); const nd = shape.length; const row = (r: number) => (Array.isArray(values) ? values.slice(r * nnz, (r + 1) * nnz) : sliceTyped(values, r * nnz, (r + 1) * nnz)); const indices: Int32Array[] = []; if (nidx === nd) { for (let r = 0; r < nd; r++) { indices.push(Int32Array.from(row(r) as ArrayLike, (i: any) => Number(i) - 1)); } } else if (nidx === 1 && nd === 2 && (shape[0] === 1 || shape[1] === 1)) { // a sparse vector, as jsonlab writes it: one index row along its long dimension const along = Int32Array.from(row(0) as ArrayLike, (i: any) => Number(i) - 1); const zero = new Int32Array(nnz); indices.push(shape[0] === 1 ? zero : along, shape[0] === 1 ? along : zero); } else if (nidx === 2 && nd > 2) { // (an N-D sparse array folded into rows x (columns of the other dimensions), as MATLAB) const r = Int32Array.from(row(0) as ArrayLike, (i: any) => Number(i) - 1); const c = Int32Array.from(row(1) as ArrayLike, (i: any) => Number(i) - 1); indices.push(r); const rest = shape.slice(1); const sub: Int32Array[] = rest.map(() => new Int32Array(nnz)); for (let k = 0; k < nnz; k++) { let q = c[k]; for (let d = 0; d < rest.length; d++) { sub[d][k] = q % rest[d]; q = Math.floor(q / rest[d]); } } indices.push(...sub); } else { throw new Error('jdata: a sparse array of ' + rows + ' rows for ' + nd + ' dimensions'); } const vals = toTyped(row(nidx), t); const imag = iscomplex ? toTyped(row(nidx + 1), t) : undefined; const sp = new SparseArray(shape, indices, vals, t, imag); if (this.o.sparse === 'dense') { const d = sp.toDense(); return this.nd(d.data, d.shape, t, d.imag); } return sp; } /** A special matrix (_ArrayShape_) expanded. */ private special(values: any, pre: number[], size: number[], t: string, iscomplex: boolean, spec: any): any { const sid = String(Array.isArray(spec) ? spec[0] : spec).toLowerCase(); const params = Array.isArray(spec) ? spec.slice(1).map(Number) : []; const planes = iscomplex ? 2 : 1; const per = values.length / planes; const pdims = iscomplex ? pre.slice(1) : pre; const Ctor = typedArrayFor(t); const plane = (p: number) => (Array.isArray(values) ? values.slice(p * per, (p + 1) * per) : sliceTyped(values, p * per, (p + 1) * per)); if (sid === 'range') { const d = Array.from(plane(0) as ArrayLike, Number); const axis = (a: number, b: number, n: number) => { const o = new Ctor(n); for (let i = 0; i < n; i++) { o[i] = n > 1 ? a + (b - a) * i / (n - 1) : a; } return o; }; if (d.length === 2) { const n = product(size); return this.nd(axis(d[0], d[1], n), size.length ? size : [n], t); } // an N-D separable grid: one axis per dimension return size.map((n, k) => this.nd(axis(d[2 * k], d[2 * k + 1], n), [n], t)); } const N = size[0], M = size.length > 1 ? size[1] : size[0]; const build = (p: number, conj: boolean) => { const src: any = plane(p); const rows = pdims.length > 1 ? pdims[0] : 1; const cols = pdims.length > 1 ? pdims[pdims.length - 1] : src.length; const at = (r: number, c: number) => (r < rows && c < cols ? Number(src[r * cols + c]) : 0); const out = new Ctor(N * M); const put = (i: number, j: number, v: number) => { if (i >= 0 && i < N && j >= 0 && j < M) { out[i * M + j] = v; } }; switch (sid) { case 'diag': { const n = Math.min(N, M, src.length); for (let i = 0; i < n; i++) { put(i, i, Number(src[i])); } break; } case 'upper': case 'uppersymm': case 'upperherm': case 'lower': case 'lowersymm': case 'lowerherm': { const upper = sid.startsWith('upper'); const mirror = sid.endsWith('symm') || sid.endsWith('herm'); let k = 0; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { if (upper ? j >= i : j <= i) { const v = Number(src[k++]); put(i, j, v); if (mirror && i !== j) { put(j, i, conj ? -v : v); } } } } break; } case 'upperband': case 'lowerband': case 'band': case 'uppersymmband': case 'lowersymmband': case 'upperhermband': case 'lowerhermband': { // LAPACK band storage: A(i,j) in row ku + i - j, column j let ku: number, kl: number; if (sid === 'band') { ku = params.length ? params[0] : (rows - 1) / 2; kl = params.length > 1 ? params[1] : params.length ? params[0] : (rows - 1) / 2; } else if (sid.startsWith('upper')) { ku = params.length ? params[0] : rows - 1; kl = 0; } else { ku = 0; kl = params.length ? params[0] : rows - 1; } const mirror = sid.indexOf('symm') > 0 || sid.indexOf('herm') > 0; for (let j = 0; j < M; j++) { for (let i = Math.max(0, j - ku); i <= Math.min(N - 1, j + kl); i++) { const v = at(ku + i - j, j); put(i, j, v); if (mirror && i !== j) { put(j, i, conj ? -v : v); } } } break; } case 'toeplitz': { // first row r (data row 0) and first column c (data row 1) const len = params.length ? params[0] : cols; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { const d = j - i; put(i, j, d >= 0 ? (d < len ? at(0, d) : 0) : (-d < len ? at(1, -d) : 0)); } } break; } case 'circulant': { const n = src.length; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { put(i, j, Number(src[((j - i) % n + n) % n])); } } break; } case 'hankel': { // first row (data row 0) and last column (data row 1): H(i,j) = h(i+j) for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { const s = i + j; put(i, j, s < M ? at(0, s) : at(1, s - M + 1)); } } break; } case 'identity': { const v = Number(src[0] !== undefined ? src[0] : 1); for (let i = 0; i < Math.min(N, M); i++) { put(i, i, v); } break; } case 'zero': break; default: throw new Error('jdata: unknown _ArrayShape_ "' + sid + '"'); } return out; }; const herm = sid.indexOf('herm') > 0; const re = build(0, false); const im = iscomplex ? build(1, herm) : undefined; return this.nd(re, [N, M], t, im); } private enumeration(x: any): any { const keys = this.value(x._EnumKey_); const kl = Array.isArray(keys) ? keys : Array.from(keys); const v = this.value(x._EnumValue_); let shape: number[] | null = null; let idx: ArrayLike; if (v instanceof NDArray) { idx = v.data; shape = v.shape; } else if (v && v.selection && v.shape) { idx = v.flatten().selection.data; shape = v.shape; } else if (isTypedArray(v)) { idx = v; } else { const f = flatData(v); idx = f.values; shape = f.shape.length > 1 ? f.shape : null; } const out = Array.from(idx, (i: any) => kl[Number(i) - 1]); return shape && shape.length > 1 ? nest(out, shape) : out; } private table(x: any): any { const recs: any[] = this.value(x._TableRecords_) || []; const colsSpec: any[] = x._TableCols_ ? Array.from(x._TableCols_) : []; const cols = colsSpec.map((c: any, k: number) => (c && typeof c === 'object' ? c.DataName : c) || 'Var' + (k + 1)); const ncol = cols.length || (recs.length ? recs[0].length : 0); while (cols.length < ncol) { cols.push('Var' + (cols.length + 1)); } if (this.o.table === 'records') { return recs.map((r: any) => { const o: any = {}; cols.forEach((c, k) => { o[c] = r[k]; }); return o; }); } const out: any = {}; cols.forEach((c, k) => { out[c] = recs.map((r: any) => r[k]); }); return out; } private bytestream(b: any): any { let bytes: Uint8Array; if (b && typeof b === 'object' && b._DataInfo_ !== undefined && b.Data !== undefined) { const enc = b._DataInfo_.Encoding; const steps: string[] = enc === undefined ? [] : Array.isArray(enc) ? enc.map(String) : [String(enc)]; let d: any = b.Data; for (const s of steps.slice().reverse()) { if (s.toLowerCase() === 'base64') { d = typeof d === 'string' ? base64ToBytes(d) : base64ToBytes(zipBytes(d, false, true)); } else { d = getCodec(s, this.o.codecs).decode(zipBytes(d, false, false), undefined, {}); } } bytes = typeof d === 'string' ? zipBytes(d, false, false) : zipBytes(d, false, false); } else if (b && typeof b === 'object' && b._ArrayType_ !== undefined) { return this.array(b); } else if (typeof b === 'string') { bytes = this.o.base64 === false ? zipBytes(b, false, false) : base64ToBytes(b); } else { bytes = zipBytes(b, false, false); } if (this.o.bytestream === 'blob' && typeof Blob !== 'undefined') { return new Blob([bytes], { type: 'application/octet-stream' }); } return bytes; } } function sliceTyped(a: any, s: number, e: number): any { return a.slice(s, e); } /** The JavaScript values of the JData annotations in a JSON or BJData document. */ export function decode(value: any, opts: DecodeOptions = {}): any { return new JDataDecoder(opts).value(value); } export { typeOfTypedArray };