Skip to content

Commit aead708

Browse files
panvanodejs-github-bot
authored andcommitted
buffer: align Blob and File with Web IDL
Convert constructor arguments in Web IDL order before processing blob parts, including inherited dictionary members and File.lastModified's long long conversion. Read buffer slots and copy bytes without invoking user getters, slice methods, or species constructors. Treat detached parts as empty and track Blob brands without invoking user getters or accepting proxies. Keep rejecting bare SharedArrayBuffers and shared-memory views for browser compatibility pending resolution of the union conversion rules. Refs: whatwg/webidl#1491 Signed-off-by: Filip Skokan <panva.ip@gmail.com> Assisted-by: Codex PR-URL: #66776 Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 96148d5 commit aead708

4 files changed

Lines changed: 359 additions & 51 deletions

File tree

‎lib/internal/blob.js‎

Lines changed: 74 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
'use strict';
22

33
const {
4+
ArrayBufferPrototypeGetByteLength,
5+
ArrayBufferPrototypeGetDetached,
46
ArrayPrototypePush,
7+
DataViewPrototypeGetBuffer,
8+
DataViewPrototypeGetByteLength,
9+
DataViewPrototypeGetByteOffset,
510
MathMax,
611
MathMin,
712
ObjectDefineProperties,
@@ -12,10 +17,14 @@ const {
1217
PromiseWithResolvers,
1318
RegExpPrototypeExec,
1419
RegExpPrototypeSymbolReplace,
20+
SafeWeakSet,
1521
StringPrototypeSplit,
1622
StringPrototypeToLowerCase,
1723
Symbol,
1824
SymbolToStringTag,
25+
TypedArrayPrototypeGetBuffer,
26+
TypedArrayPrototypeGetByteLength,
27+
TypedArrayPrototypeGetByteOffset,
1928
Uint8Array,
2029
} = primordials;
2130

@@ -43,7 +52,9 @@ const {
4352

4453
const {
4554
isAnyArrayBuffer,
55+
isArrayBuffer,
4656
isArrayBufferView,
57+
isDataView,
4758
} = require('internal/util/types');
4859

4960
const {
@@ -55,22 +66,19 @@ const {
5566
const { inspect } = require('internal/util/inspect');
5667
const {
5768
converters,
69+
createDictionaryConverter,
70+
createEnumConverter,
5871
createSequenceConverter,
5972
} = require('internal/webidl');
6073

6174
const {
6275
codes: {
6376
ERR_BUFFER_TOO_LARGE,
64-
ERR_INVALID_ARG_VALUE,
6577
ERR_INVALID_STATE,
6678
ERR_INVALID_THIS,
6779
},
6880
} = require('internal/errors');
6981

70-
const {
71-
validateDictionary,
72-
} = require('internal/validators');
73-
7482
const {
7583
setImmediate,
7684
} = require('timers');
@@ -81,6 +89,8 @@ const kHandle = Symbol('kHandle');
8189
const kType = Symbol('kType');
8290
const kLength = Symbol('kLength');
8391
const kNotCloneable = Symbol('kNotCloneable');
92+
const kAlreadyConverted = Symbol('kAlreadyConverted');
93+
const blobBrand = new SafeWeakSet();
8494

8595
const disallowedTypeCharacters = /[^\u{0020}-\u{007E}]/u;
8696

@@ -110,16 +120,14 @@ function lazyTextDecoderStream() {
110120
const { EOL } = require('internal/constants');
111121

112122
function isBlob(object) {
113-
return object?.[kHandle] !== undefined;
123+
return blobBrand.has(object);
114124
}
115125

116126
function getSource(source, endings) {
117127
if (isBlob(source))
118-
return [source.size, source[kHandle]];
128+
return [source[kLength], source[kHandle]];
119129

120-
if (isAnyArrayBuffer(source)) {
121-
source = new Uint8Array(source);
122-
} else if (!isArrayBufferView(source)) {
130+
if (typeof source === 'string') {
123131
if (endings === 'native')
124132
source = RegExpPrototypeSymbolReplace(/\r\n|\r|\n/g, source, EOL);
125133
source = enc.encode(source);
@@ -128,21 +136,49 @@ function getSource(source, endings) {
128136
// We copy into a new Uint8Array because the underlying
129137
// BackingStores are going to be detached and owned by
130138
// the Blob.
131-
const { buffer, byteOffset, byteLength } = source;
132-
const slice = buffer.slice(byteOffset, byteOffset + byteLength);
133-
return [byteLength, new Uint8Array(slice)];
139+
const isBuffer = isArrayBuffer(source);
140+
const isDataViewSource = !isBuffer && isDataView(source);
141+
const buffer = isBuffer ? source :
142+
isDataViewSource ? DataViewPrototypeGetBuffer(source) : TypedArrayPrototypeGetBuffer(source);
143+
// Check before reading byteOffset and byteLength, whose DataView getters
144+
// throw when the backing buffer is detached.
145+
if (ArrayBufferPrototypeGetDetached(buffer))
146+
return [0, new Uint8Array()];
147+
const byteOffset = isBuffer ? 0 :
148+
isDataViewSource ? DataViewPrototypeGetByteOffset(source) : TypedArrayPrototypeGetByteOffset(source);
149+
const byteLength = isBuffer ? ArrayBufferPrototypeGetByteLength(source) :
150+
isDataViewSource ? DataViewPrototypeGetByteLength(source) : TypedArrayPrototypeGetByteLength(source);
151+
const copy = new Uint8Array(new Uint8Array(buffer, byteOffset, byteLength));
152+
return [byteLength, copy];
134153
}
135154

136-
const sourcesConverter = createSequenceConverter((source, opts = kEmptyObject) => {
155+
const blobPartsConverter = createSequenceConverter((source, opts = kEmptyObject) => {
137156
if (isBlob(source)) {
138157
return source;
139158
}
159+
// Match browsers for bare SharedArrayBuffer pending a resolution of
160+
// https://github.com/whatwg/webidl/issues/1491.
140161
if (isAnyArrayBuffer(source) || isArrayBufferView(source)) {
141162
return converters.BufferSource(source, opts);
142163
}
143-
return converters.DOMString(source, opts);
164+
return converters.USVString(source, opts);
144165
});
145166

167+
const blobPropertyBag = [
168+
{
169+
key: 'endings',
170+
converter: createEnumConverter('EndingType', ['transparent', 'native']),
171+
defaultValue: () => 'transparent',
172+
},
173+
{
174+
key: 'type',
175+
converter: converters.DOMString,
176+
defaultValue: () => '',
177+
},
178+
];
179+
180+
const blobPropertyBagConverter = createDictionaryConverter('BlobPropertyBag', blobPropertyBag);
181+
146182
class Blob {
147183
/**
148184
* @typedef {string|ArrayBuffer|ArrayBufferView|Blob} SourcePart
@@ -156,40 +192,38 @@ class Blob {
156192
* }} [options]
157193
* @constructs Blob
158194
*/
159-
constructor(sources = [], options) {
195+
constructor(sources = [], options, alreadyConverted) {
160196
markTransferMode(this, true, false);
161197

162-
const sources_ = sourcesConverter(sources, {
163-
__proto__: null,
164-
context: 'sources',
165-
});
166-
167-
validateDictionary(options, 'options');
168-
let {
169-
endings = 'transparent',
170-
type = '',
171-
} = options ?? kEmptyObject;
172-
173-
endings = `${endings}`;
174-
if (endings !== 'transparent' && endings !== 'native')
175-
throw new ERR_INVALID_ARG_VALUE('options.endings', endings);
198+
// File converts all of its arguments before entering the Blob constructor.
199+
if (alreadyConverted !== kAlreadyConverted) {
200+
sources = blobPartsConverter(sources, {
201+
__proto__: null,
202+
context: 'sources',
203+
});
204+
options = blobPropertyBagConverter(options, {
205+
__proto__: null,
206+
context: 'options',
207+
});
208+
}
209+
const { endings, type } = options;
176210

177211
let length = 0;
178-
for (let i = 0; i < sources_.length; ++i) {
179-
const { 0: len, 1: src } = getSource(sources_[i], endings);
212+
for (let i = 0; i < sources.length; ++i) {
213+
const { 0: len, 1: src } = getSource(sources[i], endings);
180214
length += len;
181-
sources_[i] = src;
215+
sources[i] = src;
182216
}
183217

184218
if (length > kMaxLength)
185219
throw new ERR_BUFFER_TOO_LARGE(kMaxLength);
186220

187-
this[kHandle] = _createBlob(sources_, length);
221+
this[kHandle] = _createBlob(sources, length);
188222
this[kLength] = length;
189223

190-
type = `${type}`;
191224
this[kType] = RegExpPrototypeExec(disallowedTypeCharacters, type) !== null ?
192225
'' : StringPrototypeToLowerCase(type);
226+
blobBrand.add(this);
193227
}
194228

195229
[kInspect](depth, options) {
@@ -226,6 +260,7 @@ class Blob {
226260
this[kHandle] = handle;
227261
this[kType] = type;
228262
this[kLength] = length;
263+
blobBrand.add(this);
229264
}
230265

231266
/**
@@ -357,6 +392,7 @@ function TransferableBlob(handle, length, type = '') {
357392
this[kHandle] = handle;
358393
this[kType] = type;
359394
this[kLength] = length;
395+
blobBrand.add(this);
360396
}
361397

362398
ObjectSetPrototypeOf(TransferableBlob.prototype, Blob.prototype);
@@ -701,12 +737,15 @@ async function* createBlobReaderIterable(reader, options = kEmptyObject) {
701737

702738
module.exports = {
703739
Blob,
740+
blobPartsConverter,
741+
blobPropertyBag,
704742
createBlob,
705743
createBlobFromFilePath,
706744
createBlobReaderIterable,
707745
createBlobReaderStream,
708746
getBlobDataSync,
709747
isBlob,
748+
kAlreadyConverted,
710749
kHandle,
711750
kType,
712751
resolveObjectURL,

‎lib/internal/file.js‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,25 @@
33
const {
44
DateNow,
55
FunctionPrototypeCall,
6-
NumberIsNaN,
76
ObjectDefineProperties,
87
ObjectSetPrototypeOf,
9-
StringPrototypeToWellFormed,
108
Symbol,
119
SymbolToStringTag,
1210
} = primordials;
1311

1412
const {
1513
Blob,
14+
blobPartsConverter,
15+
blobPropertyBag,
16+
kAlreadyConverted,
1617
TransferableBlob,
1718
} = require('internal/blob');
1819

20+
const {
21+
converters,
22+
createDictionaryConverter,
23+
} = require('internal/webidl');
24+
1925
const {
2026
customInspectSymbol: kInspect,
2127
kEnumerableProperty,
@@ -40,6 +46,11 @@ const {
4046

4147
const kState = Symbol('state');
4248

49+
const filePropertyBagConverter = createDictionaryConverter('FilePropertyBag', [
50+
blobPropertyBag,
51+
[{ key: 'lastModified', converter: converters['long long'] }],
52+
]);
53+
4354
function isFile(object) {
4455
return object?.[kState] !== undefined;
4556
}
@@ -64,22 +75,13 @@ class File extends Blob {
6475
throw new ERR_MISSING_ARGS('fileBits', 'fileName');
6576
}
6677

67-
super(fileBits, options);
78+
fileBits = blobPartsConverter(fileBits, { __proto__: null, context: 'fileBits' });
79+
fileName = converters.USVString(fileName, { __proto__: null, context: 'fileName' });
80+
options = filePropertyBagConverter(options, { __proto__: null, context: 'options' });
6881

69-
let { lastModified } = options ?? kEmptyObject;
70-
71-
if (lastModified !== undefined) {
72-
// Using Number(...) will not throw an error for bigints.
73-
lastModified = +lastModified;
74-
75-
if (NumberIsNaN(lastModified)) {
76-
lastModified = 0;
77-
}
78-
} else {
79-
lastModified = DateNow();
80-
}
82+
super(fileBits, options, kAlreadyConverted);
8183

82-
this[kState] = new FileState(StringPrototypeToWellFormed(`${fileName}`), lastModified);
84+
this[kState] = new FileState(fileName, options.lastModified ?? DateNow());
8385
}
8486

8587
get name() {
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('node:assert');
5+
const { Blob, File } = require('node:buffer');
6+
7+
(async () => {
8+
for (const create of [
9+
(parts, options) => new Blob(parts, options),
10+
(parts, options) => new File(parts, 'test', options),
11+
]) {
12+
const buffer = new ArrayBuffer(16);
13+
const parts = [
14+
buffer,
15+
new Uint8Array(buffer),
16+
new Uint8Array(buffer, 4, 8),
17+
new Uint16Array(buffer, 4, 4),
18+
new DataView(buffer),
19+
new DataView(buffer, 4, 8),
20+
Buffer.from(buffer, 4, 8),
21+
];
22+
buffer.transfer();
23+
24+
for (const part of parts) {
25+
const empty = create([part]);
26+
assert.strictEqual(empty.size, 0);
27+
assert.deepStrictEqual(await empty.arrayBuffer(), new ArrayBuffer(0));
28+
29+
const mixed = create(['hello', part, 'world']);
30+
assert.strictEqual(mixed.size, 10);
31+
assert.strictEqual(await mixed.text(), 'helloworld');
32+
}
33+
34+
// Options conversion can detach buffers after blob parts conversion.
35+
const anotherBuffer = new ArrayBuffer(16);
36+
const view = new DataView(anotherBuffer, 4, 8);
37+
const blob = create([anotherBuffer, view, 'hello'], {
38+
get endings() {
39+
anotherBuffer.transfer();
40+
return 'transparent';
41+
},
42+
});
43+
assert.strictEqual(blob.size, 5);
44+
assert.strictEqual(await blob.text(), 'hello');
45+
}
46+
})().then(common.mustCall());

0 commit comments

Comments
 (0)