-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathindex.ts
299 lines (262 loc) · 7.29 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* @packageDocumentation
*
* This module contains the protobuf definition of the UnixFS data structure found at the root of all UnixFS DAGs.
*
* The UnixFS spec can be found in the [ipfs/specs repository](http://github.com/ipfs/specs)
*
* @example Create a file composed of several blocks
*
* ```JavaScript
* const data = new UnixFS({ type: 'file' })
* data.addBlockSize(256) // add the size of each block
* data.addBlockSize(256)
* // ...
* ```
*
* @example Create a directory that contains several files
*
* Creating a directory that contains several files is achieve by creating a unixfs element that identifies a MerkleDAG node as a directory. The links of that MerkleDAG node are the files that are contained in this directory.
*
* ```JavaScript
* const data = new UnixFS({ type: 'directory' })
* ```
*
* @example Create an unixfs Data element
*
* ```JavaScript
* const data = new UnixFS([options])
* ```
*
* `options` is an optional object argument that might include the following keys:
*
* - type (string, default `file`): The type of UnixFS entry. Can be:
* - `raw`
* - `directory`
* - `file`
* - `metadata`
* - `symlink`
* - `hamt-sharded-directory`
* - data (Uint8Array): The optional data field for this node
* - blockSizes (Array, default: `[]`): If this is a `file` node that is made up of multiple blocks, `blockSizes` is a list numbers that represent the size of the file chunks stored in each child node. It is used to calculate the total file size.
* - mode (Number, default `0644` for files, `0755` for directories/hamt-sharded-directories) file mode
* - mtime (`Date`, `{ secs, nsecs }`, `{ Seconds, FractionalNanoseconds }`, `[ secs, nsecs ]`): The modification time of this node
*
* @example Add and remove a block size to the block size list
*
* ```JavaScript
* data.addBlockSize(<size in bytes>)
* ```
*
* ```JavaScript
* data.removeBlockSize(<index>)
* ```
*
* @example Get total fileSize
*
* ```JavaScript
* data.fileSize() // => size in bytes
* ```
*
* @example Marshal and unmarshal
*
* ```javascript
* const marshaled = data.marshal()
* const unmarshaled = Unixfs.unmarshal(marshaled)
* ```
*
* @example Is this UnixFS entry a directory?
*
* ```JavaScript
* const dir = new Data({ type: 'directory' })
* dir.isDirectory() // true
*
* const file = new Data({ type: 'file' })
* file.isDirectory() // false
* ```
*
* @example Has an mtime been set?
*
* If no modification time has been set, no `mtime` property will be present on the `Data` instance:
*
* ```JavaScript
* const file = new Data({ type: 'file' })
* file.mtime // undefined
*
* Object.prototype.hasOwnProperty.call(file, 'mtime') // false
*
* const dir = new Data({ type: 'dir', mtime: new Date() })
* dir.mtime // { secs: Number, nsecs: Number }
* ```
*/
import { InvalidTypeError } from './errors.js'
import { Data as PBData } from './unixfs.js'
export interface Mtime {
secs: bigint
nsecs?: number
}
export type MtimeLike = Mtime | { Seconds: number, FractionalNanoseconds?: number } | [number, number] | Date
const types: Record<string, string> = {
Raw: 'raw',
Directory: 'directory',
File: 'file',
Metadata: 'metadata',
Symlink: 'symlink',
HAMTShard: 'hamt-sharded-directory'
}
const dirTypes = [
'directory',
'hamt-sharded-directory'
]
const DEFAULT_FILE_MODE = parseInt('0644', 8)
const DEFAULT_DIRECTORY_MODE = parseInt('0755', 8)
export interface UnixFSOptions {
type?: string
data?: Uint8Array
blockSizes?: bigint[]
hashType?: bigint
fanout?: bigint
mtime?: Mtime
mode?: number
}
class UnixFS {
/**
* Decode from protobuf https://github.com/ipfs/specs/blob/master/UNIXFS.md
*/
static unmarshal (marshaled: Uint8Array): UnixFS {
const message = PBData.decode(marshaled)
const data = new UnixFS({
type: types[message.Type != null ? message.Type.toString() : 'File'],
data: message.Data,
blockSizes: message.blocksizes,
mode: message.mode,
mtime: message.mtime != null
? {
secs: message.mtime.Seconds ?? 0n,
nsecs: message.mtime.FractionalNanoseconds
}
: undefined,
fanout: message.fanout
})
// make sure we honour the original mode
data._originalMode = message.mode ?? 0
return data
}
public type: string
public data?: Uint8Array
public blockSizes: bigint[]
public hashType?: bigint
public fanout?: bigint
public mtime?: Mtime
private _mode?: number
private _originalMode: number
constructor (options: UnixFSOptions = {
type: 'file'
}) {
const {
type,
data,
blockSizes,
hashType,
fanout,
mtime,
mode
} = options
if (type != null && !Object.values(types).includes(type)) {
throw new InvalidTypeError('Type: ' + type + ' is not valid')
}
this.type = type ?? 'file'
this.data = data
this.hashType = hashType
this.fanout = fanout
this.blockSizes = blockSizes ?? []
this._originalMode = 0
this.mode = mode
this.mtime = mtime
}
set mode (mode: number | undefined) {
if (mode == null) {
this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE
} else {
this._mode = (mode & 0xFFF)
}
}
get mode (): number | undefined {
return this._mode
}
isDirectory (): boolean {
return dirTypes.includes(this.type)
}
addBlockSize (size: bigint): void {
this.blockSizes.push(size)
}
removeBlockSize (index: number): void {
this.blockSizes.splice(index, 1)
}
/**
* Returns `0n` for directories or `data.length + sum(blockSizes)` for everything else
*/
fileSize (): bigint {
if (this.isDirectory()) {
// dirs don't have file size
return 0n
}
let sum = 0n
this.blockSizes.forEach((size) => {
sum += size
})
if (this.data != null) {
sum += BigInt(this.data.length)
}
return sum
}
/**
* encode to protobuf Uint8Array
*/
marshal (): Uint8Array {
let type
switch (this.type) {
case 'raw': type = PBData.DataType.Raw; break
case 'directory': type = PBData.DataType.Directory; break
case 'file': type = PBData.DataType.File; break
case 'metadata': type = PBData.DataType.Metadata; break
case 'symlink': type = PBData.DataType.Symlink; break
case 'hamt-sharded-directory': type = PBData.DataType.HAMTShard; break
default:
throw new InvalidTypeError(`Type: ${type} is not valid`)
}
let data = this.data
if (this.data == null || this.data.length === 0) {
data = undefined
}
let mode
if (this.mode != null) {
mode = (this._originalMode & 0xFFFFF000) | (this.mode ?? 0)
if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) {
mode = undefined
}
if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) {
mode = undefined
}
}
let mtime
if (this.mtime != null) {
mtime = {
Seconds: this.mtime.secs,
FractionalNanoseconds: this.mtime.nsecs
}
}
return PBData.encode({
Type: type,
Data: data,
filesize: this.isDirectory() ? undefined : this.fileSize(),
blocksizes: this.blockSizes,
hashType: this.hashType,
fanout: this.fanout,
mode,
mtime
})
}
}
export { UnixFS }
export * from './errors.js'