Skip to content

Commit

Permalink
Fix FS in browser
Browse files Browse the repository at this point in the history
  • Loading branch information
mischnic committed Nov 21, 2021
1 parent 7a70384 commit e1c2ef5
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
3 changes: 3 additions & 0 deletions packages/core/fs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,8 @@
},
"peerDependencies": {
"@parcel/core": "^2.0.0"
},
"browser": {
"./src/NodeFS.js": "./src/NodeFS.browser.js"
}
}
29 changes: 24 additions & 5 deletions packages/core/fs/src/MemoryFS.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @flow
/* global MessageChannel:readonly */

import type {FileSystem, FileOptions, ReaddirOptions, Encoding} from './types';
import type {FilePath} from '@parcel/types';
Expand All @@ -17,6 +18,27 @@ import nullthrows from 'nullthrows';
import EventEmitter from 'events';
import {findAncestorFile, findNodeModule, findFirstFile} from './find';

let SharedBuffer: Class<ArrayBuffer> | Class<SharedArrayBuffer>;
// $FlowFixMe[prop-missing]
if (process.browser) {
SharedBuffer = ArrayBuffer;
// Safari has removed the constructor
if (typeof SharedArrayBuffer !== 'undefined') {
let channel = new MessageChannel();
try {
// Firefox might throw when sending the Buffer over a MessagePort
channel.port1.postMessage(new SharedArrayBuffer(0));
SharedBuffer = SharedArrayBuffer;
} catch (_) {
// NOOP
}
channel.port1.close();
channel.port2.close();
}
} else {
SharedBuffer = SharedArrayBuffer;
}

const instances: Map<number, MemoryFS> = new Map();
let id = 0;

Expand Down Expand Up @@ -904,15 +926,12 @@ class Directory extends Entry {
}

function makeShared(contents: Buffer | string): Buffer {
if (
typeof contents !== 'string' &&
contents.buffer instanceof SharedArrayBuffer
) {
if (typeof contents !== 'string' && contents.buffer instanceof SharedBuffer) {
return contents;
}

let length = Buffer.byteLength(contents);
let shared = new SharedArrayBuffer(length);
let shared = new SharedBuffer(length);
let buffer = Buffer.from(shared);
if (typeof contents === 'string') {
buffer.write(contents);
Expand Down
9 changes: 9 additions & 0 deletions packages/core/fs/src/NodeFS.browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// @flow
import type {FileSystem} from './types';

// $FlowFixMe[prop-missing] handled by the throwing constructor
export class NodeFS implements FileSystem {
constructor() {
throw new Error("NodeFS isn't available in the browser");
}
}

0 comments on commit e1c2ef5

Please sign in to comment.