Skip to content

Commit f3f1ce2

Browse files
authored
Accept ArrayBuffer as .parse data (#125)
* Accept ArrayBuffer as data * update readme
1 parent 4f68086 commit f3f1ce2

File tree

4 files changed

+47
-44
lines changed

4 files changed

+47
-44
lines changed

README.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,13 @@ const nbt = require('prismarine-nbt')
1818
async function main(file) {
1919
const buffer = fs.readFileSync(file)
2020
const { parsed, type } = await nbt.parse(buffer)
21-
console.log('JSON serialized', JSON.stringify(parsed, null, 2))
22-
fs.createWriteStream('bigtest.nbt').write(nbt.writeUncompressed(parsed, type)) // Write it back
21+
22+
console.log('As JSON', JSON.stringify(parsed))
23+
console.log('Simplified', nbt.simplify(parsed))
24+
25+
// Write it back
26+
fs.createWriteStream('bigtest.nbt')
27+
.write(nbt.writeUncompressed(parsed, type))
2328
}
2429
main('bigtest.nbt')
2530
```
@@ -47,7 +52,7 @@ If the data is gzipped, it is automatically decompressed, for the buffer see met
4752
### parse(data, [format]): Promise<{ parsed, type, metadata: { size, buffer? } }>
4853
### parse(data, [format,] callback)
4954

50-
Takes an optionally compressed `data` buffer and reads the nbt data.
55+
Takes an optionally compressed `data` buffer (`Buffer` or `ArrayBuffer`) and reads the nbt data.
5156

5257
If the endian `format` is known, it can be specified as 'big', 'little' or 'littleVarint'. If not specified, the library will
5358
try to sequentially load as big, little and little varint until the parse is successful. The deduced type is returned as `type`.
@@ -123,14 +128,13 @@ For webpack usage, see an example configuration [here](https://github.com/Prisma
123128

124129
For a web bundle with browserify (after you ran `npm install prismarine-nbt` in your project):
125130
```
126-
npx browserify -r prismarine-nbt -r buffer -o pnbt.js
131+
npx browserify -r prismarine-nbt -o pnbt.js
127132
```
128133
```html
129134
<script src="./pnbt.js"></script>
130135
<script>
131136
const nbt = require('prismarine-nbt')
132-
const { Buffer } = require('buffer')
133137
fetch('test.nbt').then(resp => resp.arrayBuffer())
134-
.then(buf => nbt.parse(Buffer.from(buf))).then(console.log)
138+
.then(nbt.parse).then(console.log)
135139
</script>
136140
```

nbt.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ const hasBedrockLevelHeader = (data) =>
7272
data[1] === 0 && data[2] === 0 && data[3] === 0
7373

7474
async function parseAs (data, type, options = {}) {
75+
if (!(data instanceof Buffer)) throw new Error('Invalid argument: `data` must be a Buffer object')
7576
if (hasGzipHeader(data)) {
7677
data = await new Promise((resolve, reject) => {
7778
zlib.gunzip(data, (error, uncompressed) => {
@@ -91,6 +92,12 @@ async function parseAs (data, type, options = {}) {
9192
}
9293

9394
async function parse (data, format, callback) {
95+
if (data instanceof ArrayBuffer) {
96+
data = Buffer.from(data)
97+
} else if (!(data instanceof Buffer)) {
98+
throw new Error('Invalid argument: `data` must be a Buffer or ArrayBuffer object')
99+
}
100+
94101
let fmt = null
95102
if (typeof format === 'function') {
96103
callback = format

sample/builderExample.js

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1+
const fs = require('fs')
12
const nbt = require('prismarine-nbt')
23

3-
const writePlayerNbt = () => {}
4-
writePlayerNbt({
4+
const tag = nbt.comp({
55
Air: nbt.short(300),
6-
Armor: nbt.list(
7-
nbt.comp({ Count: nbt.byte(0), Damage: nbt.short(0), Name: nbt.string('') }),
8-
nbt.comp({ Count: nbt.byte(0), Damage: nbt.short(0), Name: nbt.string('') }),
9-
nbt.comp({ Count: nbt.byte(0), Damage: nbt.short(0), Name: nbt.string('') })
10-
)
6+
Armor: nbt.list(nbt.comp([
7+
{ Count: nbt.byte(0), Damage: nbt.short(0), Name: nbt.string('a') },
8+
{ Count: nbt.byte(0), Damage: nbt.short(0), Name: nbt.string('b') },
9+
{ Count: nbt.byte(0), Damage: nbt.short(0), Name: nbt.string('c') }
10+
]))
1111
})
12+
13+
const buffer = nbt.writeUncompressed(tag)
14+
fs.createWriteStream('tag.nbt').write(buffer)

typings/index.d.ts

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,23 @@
11
/// <reference types="node" resolution-mode="require"/>
2-
declare module 'prismarine-nbt'{
2+
declare module 'prismarine-nbt' {
33
// @ts-expect-error - protodef is untyped
44
import type { Compiler, Interpreter } from "protodef";
55

66
export type Byte = { type: `${TagType.Byte}`, value: number };
7-
87
export type Short = { type: `${TagType.Short}`, value: number };
9-
108
export type Int = { type: `${TagType.Int}`, value: number };
11-
129
export type Long = { type: `${TagType.Long}`, value: [number, number] };
13-
1410
export type Float = { type: `${TagType.Float}`, value: number };
15-
1611
export type Double = { type: `${TagType.Double}`, value: number };
17-
1812
export type String = { type: `${TagType.String}`, value: string };
19-
2013
export type List<T extends TagType> = {
2114
type: `${TagType.List}`,
2215
value: { type: Tags[T]['type'], value: Tags[T]['value'][] }
2316
};
24-
2517
export type Compound = { type: `${TagType.Compound}`, value: Record<string, undefined | Tags[TagType]> };
26-
2718
export type ByteArray = { type: `${TagType.ByteArray}`, value: Byte["value"][] };
28-
2919
export type ShortArray = { type: `${TagType.ShortArray}`, value: Short["value"][] };
30-
3120
export type IntArray = { type: `${TagType.IntArray}`, value: Int["value"][] };
32-
3321
export type LongArray = { type: `${TagType.LongArray}`, value: Long["value"][] };
3422

3523
export enum TagType {
@@ -70,7 +58,7 @@ declare module 'prismarine-nbt'{
7058

7159
export type NBTFormat = 'big' | 'little' | 'littleVarint'
7260

73-
export type NBT = Tags['compound'] & {name: string};
61+
export type NBT = Tags['compound'] & { name: string };
7462
export type Metadata = {
7563
// The decompressed buffer
7664
buffer: Buffer
@@ -79,9 +67,9 @@ declare module 'prismarine-nbt'{
7967
}
8068
export function writeUncompressed(value: NBT, format?: NBTFormat): Buffer;
8169
export function parseUncompressed(value: Buffer, format?: NBTFormat, options?: ParseOptions): NBT;
82-
export function parseAs(value: Buffer, type: NBTFormat, options?: ParseOptions): Promise<{parsed: NBT, type: NBTFormat, metadata: Metadata}>;
83-
84-
export function parse(data: Buffer, nbtType?: NBTFormat): Promise<{parsed: NBT, type: NBTFormat, metadata: Metadata}>;
70+
export function parseAs(value: Buffer, type: NBTFormat, options?: ParseOptions): Promise<{ parsed: NBT, type: NBTFormat, metadata: Metadata }>;
71+
72+
export function parse(data: Buffer | ArrayBuffer, nbtType?: NBTFormat): Promise<{ parsed: NBT, type: NBTFormat, metadata: Metadata }>;
8573
export function simplify(data: Tags[TagType]): any
8674
export function equal(nbt1: Tags[TagType], nbt2: Tags[TagType]): boolean
8775
// ProtoDef compiled protocols
@@ -106,22 +94,23 @@ declare module 'prismarine-nbt'{
10694
/** @deprecated */
10795
export function parse(data: Buffer, callback: (err: Error | null, value: NBT) => any): void;
10896

109-
export function bool(val: number): { type: `${TagType.Short}`, value: number }
110-
export function short (val: number): { type: `${TagType.Short}`, value: number }
111-
export function byte<T extends number> (val: number): { type: `${TagType.Byte}`, value: number }
112-
export function string<T extends string | string[]> (val: T): { type: `${TagType.String}`, value: T }
113-
export function comp<T extends object | object[]> (val: T, name?: string): { type: `${TagType.Compound}`, name?: string, value: T }
114-
export function int<T extends number | number[]> (val: T): { type: `${TagType.Int}`, value: T }
115-
export function list<T extends string, K extends {type: T}>(value: K): { type: `${TagType.List}`; value: { type: T | 'end', value: K } }
116-
export function float<T extends number | number[]> (value: T): { type: `${TagType.Float}`, value: T}
117-
export function double<T extends number | number[]> (value: T): { type: `${TagType.Double}`, value: T}
97+
// Builder methods
98+
export function bool<T extends number | number[]>(val: T): { type: `${TagType.Short}`, value: T }
99+
export function short<T extends number | number[]>(val: T): { type: `${TagType.Short}`, value: T }
100+
export function byte<T extends number | number[]>(val: T): { type: `${TagType.Byte}`, value: T }
101+
export function string<T extends string | string[]>(val: T): { type: `${TagType.String}`, value: T }
102+
export function comp<T extends object | object[]>(val: T, name?: string): { type: `${TagType.Compound}`, name?: string, value: T }
103+
export function int<T extends number | number[]>(val: T): { type: `${TagType.Int}`, value: T }
104+
export function list<T extends string, K extends { type: T }>(value: K): { type: `${TagType.List}`; value: { type: T | 'end', value: K } }
105+
export function float<T extends number | number[]>(value: T): { type: `${TagType.Float}`, value: T }
106+
export function double<T extends number | number[]>(value: T): { type: `${TagType.Double}`, value: T }
118107
/**
119108
* @param value Takes a BigInt or an array of two 32-bit integers
120109
*/
121-
export function long<T extends number | number[] | BigInt> (value: T): { type: `${TagType.Long}`, value: T}
110+
export function long<T extends number | number[] | BigInt>(value: T): { type: `${TagType.Long}`, value: T }
122111
// Arrays
123-
export function byteArray (value: number[]): { type: `${TagType.ByteArray}`, value: number[]}
124-
export function shortArray (value: number[]): { type: `${TagType.ShortArray}`, value: number[]}
125-
export function intArray (value: number[]): { type: `${TagType.ByteArray}`, value: number[]}
126-
export function longArray<T extends number[] | BigInt[]> (value: T): { type: `${TagType.LongArray}`, value: T}
112+
export function byteArray(value: number[]): { type: `${TagType.ByteArray}`, value: number[] }
113+
export function shortArray(value: number[]): { type: `${TagType.ShortArray}`, value: number[] }
114+
export function intArray(value: number[]): { type: `${TagType.ByteArray}`, value: number[] }
115+
export function longArray<T extends number[] | BigInt[]>(value: T): { type: `${TagType.LongArray}`, value: T }
127116
}

0 commit comments

Comments
 (0)