File size: 8,492 Bytes
cd6720a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// @ts-check

/**
 * @param {unknown} value
 */
const getType = (value) => {
  if (value === undefined) return 0
  if (value === null) return 1
  if (isBuffer(value)) return 10
  const t = typeof value
  if (t === 'boolean') return 2
  if (t === 'number') return 3
  if (t === 'string') return 4
  if (t === 'object') return 6
  if (t === 'bigint') return 9
  return -1
}

/**
 * @param {unknown} value
 * @returns {value is Uint8Array}
 */
const isBuffer = (value) => {
  const BufferCtor = globalThis.Buffer
  if (typeof BufferCtor?.isBuffer === 'function') {
    return BufferCtor.isBuffer(value)
  }
  return value instanceof Uint8Array && value.constructor?.name === 'Buffer'
}

const RESPONSE_HEADER_SIZE = 16
const RESPONSE_PAYLOAD_SIZE = 10240
const RESPONSE_BUFFER_SIZE = RESPONSE_HEADER_SIZE + RESPONSE_PAYLOAD_SIZE

/**
 * @param {Int32Array} sab
 * @param {Uint8Array} payload
 */
const writeResponsePayload = (sab, payload) => {
  if (payload.length > RESPONSE_PAYLOAD_SIZE) {
    throw new RangeError('payload overflow')
  }
  new Uint8Array(sab.buffer).set(payload, RESPONSE_HEADER_SIZE)
}

/**
 * @param {import('memfs').IFs} memfs
 * @param {any} value
 * @param {ReturnType<typeof getType>} type
 * @returns {Uint8Array}
 */
const encodeValue = (memfs, value, type) => {
  switch (type) {
    case 0:
    case 1:
      return new Uint8Array(0)
    case 2: {
      const view = new Int32Array(1)
      view[0] = value ? 1 : 0
      return new Uint8Array(view.buffer)
    }
    case 3: {
      const view = new Float64Array(1)
      view[0] = value
      return new Uint8Array(view.buffer)
    }
    case 4: {
      const view = new TextEncoder().encode(value)
      return view
    }
    case 10:
      return new Uint8Array(value)
    case 6: {
      function storeConstructor(obj, memfs, processed = new WeakSet()) {
        if (!obj || typeof obj !== 'object') {
          return
        }

        if (processed.has(obj)) {
          return
        }

        processed.add(obj)

        const [entry] =
          Object.entries(memfs).filter(([_, v]) => v === obj.constructor)[0] ??
          []
        if (entry) {
          Object.defineProperty(obj, '__constructor__', {
            configurable: true,
            writable: true,
            enumerable: true,
            value: entry,
          })
        }

        for (const value of Object.values(obj)) {
          storeConstructor(value, memfs, processed)
        }
      }

      storeConstructor(value, memfs)

      const json = JSON.stringify(value, (_, value) => {
        if (typeof value === 'bigint') {
          return `BigInt(${String(value)})`
        }
        if (value instanceof Error) {
          return {
            ...value,
            message: value.message,
            stack: value.stack,
            __error__: value.constructor.name,
          }
        }
        return value
      })
      const view = new TextEncoder().encode(json)
      return view
    }
    case 9: {
      return new TextEncoder().encode(String(value))
    }
    case -1:
    default:
      throw new Error('unsupported data')
  }
}

/**
 * @param {typeof import('memfs')} memfs
 * @param {Uint8Array} payload
 * @param {number} type
 * @returns {any}
 */
const decodeValue = (memfs, payload, type) => {
  if (type === 0) return undefined
  if (type === 1) return null
  if (type === 2)
    return Boolean(new Int32Array(payload.buffer, payload.byteOffset, 1)[0])
  if (type === 3)
    return new Float64Array(payload.buffer, payload.byteOffset, 1)[0]
  if (type === 4) return new TextDecoder().decode(payload.slice())
  if (type === 10) {
    const BufferCtor = globalThis.Buffer
    if (typeof BufferCtor?.from === 'function') {
      return BufferCtor.from(payload)
    }
    return payload.slice()
  }
  if (type === 6) {
    const obj = JSON.parse(
      new TextDecoder().decode(payload.slice()),
      (_key, value) => {
        if (typeof value === 'string') {
          const matched = value.match(/^BigInt\((-?\d+)\)$/)
          if (matched && matched[1]) {
            return BigInt(matched[1])
          }
        }
        return value
      },
    )

    function loadConstructor(obj, memfs, processed = new WeakSet()) {
      if (!obj || typeof obj !== 'object') {
        return
      }

      if (processed.has(obj)) {
        return
      }

      processed.add(obj)

      if (obj.__constructor__) {
        const ctor = obj.__constructor__
        delete obj.__constructor__
        Object.setPrototypeOf(obj, memfs[ctor].prototype)
      }

      for (const value of Object.values(obj)) {
        loadConstructor(value, memfs, processed)
      }
    }

    loadConstructor(obj, memfs)

    if (obj.__error__) {
      const name = obj.__error__
      const ErrorConstructor = globalThis[name] || Error
      delete obj.__error__
      const err = new ErrorConstructor(obj.message)
      Object.defineProperty(err, 'stack', {
        configurable: true,
        enumerable: false,
        writable: true,
        value: err.stack,
      })
      Object.defineProperty(err, Symbol.toStringTag, {
        configurable: true,
        enumerable: false,
        writable: true,
        value: name,
      })
      for (const [k, v] of Object.entries(obj)) {
        if (k === 'message' || k === 'stack') continue
        err[k] = v
      }
      return err
    }
    return obj
  }
  if (type === 9) {
    return BigInt(new TextDecoder().decode(payload.slice()))
  }
  throw new Error('unsupported data')
}

/**
 * @param {import('memfs').IFs} fs
 * @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void}
 */
// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release
export const createOnMessage = (fs) =>
  function onMessage(e) {
    if (e.data.__fs__) {
      /**
       * 0..4                    status(int32_t):        21(waiting) 0(success) 1(error)
       * 5..8                    type(napi_valuetype):   0(undefined) 1(null) 2(boolean) 3(number) 4(string) 6(jsonstring) 9(bigint) 10(buffer) -1(unsupported)
       * 9..16                   payload_size(uint32_t)  <= 10240
       * 16..16 + payload_size   payload_content
       */
      const { sab, type, payload } = e.data.__fs__
      const fn = fs[type]
      try {
        const ret = fn.apply(fs, payload)
        const t = getType(ret)
        Atomics.store(sab, 1, t)
        const v = encodeValue(fs, ret, t)
        Atomics.store(sab, 2, v.length)
        writeResponsePayload(sab, v)
        Atomics.store(sab, 0, 0) // success
      } catch (/** @type {any} */ err) {
        let t = getType(err)
        let v
        try {
          if (t === -1) {
            throw new Error('unsupported data')
          }
          v = encodeValue(fs, err, t)
        } catch {
          const fallback = (() => {
            try {
              return String(err)
            } catch {
              return 'Unserializable thrown value'
            }
          })()
          t = getType(fallback)
          v = encodeValue(fs, fallback, t)
        }
        if (v.length > RESPONSE_PAYLOAD_SIZE) {
          const overflowErr = new RangeError('payload overflow')
          t = getType(overflowErr)
          v = encodeValue(fs, overflowErr, t)
        }
        Atomics.store(sab, 1, t)
        Atomics.store(sab, 2, v.length)
        writeResponsePayload(sab, v)
        Atomics.store(sab, 0, 1) // error
      } finally {
        Atomics.notify(sab, 0)
      }
    }
  }

/**
 * @param {typeof import('memfs')} memfs
 */
export const createFsProxy = (memfs) =>
  new Proxy(
    {},
    {
      get(_target, p, _receiver) {
        /**
         * @param {any[]} args
         */
        return function (...args) {
          const sab = new SharedArrayBuffer(RESPONSE_BUFFER_SIZE)
          const i32arr = new Int32Array(sab)
          Atomics.store(i32arr, 0, 21)

          postMessage({
            __fs__: {
              sab: i32arr,
              type: p,
              payload: args,
            },
          })

          Atomics.wait(i32arr, 0, 21)

          const status = Atomics.load(i32arr, 0)
          const type = Atomics.load(i32arr, 1)
          const size = Atomics.load(i32arr, 2)
          const content = new Uint8Array(sab, RESPONSE_HEADER_SIZE, size)
          const value = decodeValue(memfs, content, type)
          if (status === 1) {
            throw value
          }
          return value
        }
      },
    },
  )