@nativue/core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -139,6 +139,38 @@ class DataBuffer : public jsi::Buffer {
139
139
  NSData *data_;
140
140
  };
141
141
 
142
+ // ---------- Blobs ----------
143
+
144
+ // What __blobCollector returns: when the garbage collector collects it (with the last Blob that holds it),
145
+ // it releases the blob's native bytes.
146
+ class BlobCollector : public jsi::HostObject {
147
+ public:
148
+ BlobCollector(NativueNativeFunction release, NSString *blobId) : release_(release), blobId_(blobId) {}
149
+
150
+ ~BlobCollector() override {
151
+ release_(@[ blobId_ ]);
152
+ }
153
+
154
+ private:
155
+ NativueNativeFunction release_;
156
+ NSString *blobId_;
157
+ };
158
+
159
+ void installBlobCollector(jsi::Runtime &runtime, NativueNativeFunction release) {
160
+ auto collector = [release](jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *arguments, size_t count) {
161
+ if (count < 1 || !arguments[0].isString()) throw jsi::JSError(runtime, "__blobCollector needs a blob id");
162
+
163
+ NSString *blobId = toObjectiveCString(runtime, arguments[0].getString(runtime));
164
+
165
+ return jsi::Value(runtime, jsi::Object::createFromHostObject(runtime, std::make_shared<BlobCollector>(release, blobId)));
166
+ };
167
+
168
+ runtime.global().setProperty(
169
+ runtime,
170
+ "__blobCollector",
171
+ jsi::Function::createFromHostFunction(runtime, jsi::PropNameID::forAscii(runtime, "__blobCollector"), 1, collector));
172
+ }
173
+
142
174
  } // namespace
143
175
 
144
176
  @implementation NativueJavaScriptRuntime {
@@ -182,6 +214,9 @@ class DataBuffer : public jsi::Buffer {
182
214
  }
183
215
 
184
216
  runtime.global().setProperty(runtime, "__native", nativeModule);
217
+
218
+ NativueNativeFunction releaseBlob = functions[@"blobRelease"];
219
+ if (releaseBlob) installBlobCollector(runtime, releaseBlob);
185
220
  }
186
221
 
187
222
  - (void)evaluate:(NSData *)bundle sourceURL:(NSString *)sourceURL {
@@ -0,0 +1,321 @@
1
+ import Foundation
2
+
3
+ /// HTTP requests for XMLHttpRequest (and fetch, built on it). URLSession runs them; their progress comes
4
+ /// back as events (see NetworkEventPayloads in types.ts), which the Bridge hands to JS's __networkEvent.
5
+ /// Everything, delegate callbacks included, runs on one serial queue.
6
+ final class Networking: NSObject, URLSessionDataDelegate {
7
+ /// (who asked, request id, event name, payload).
8
+ var onEvent: ((AnyObject?, Int, String, [String: Any]) -> Void)?
9
+ private let blobStore: BlobStore
10
+
11
+ init(blobStore: BlobStore) {
12
+ self.blobStore = blobStore
13
+ }
14
+
15
+ private final class RequestState {
16
+ let id: Int
17
+ weak var owner: AnyObject?
18
+ /// 'text', 'base64' or 'blob'.
19
+ let responseType: String
20
+ let incrementalUpdates: Bool
21
+ var mimeType: String?
22
+ var data = Data()
23
+ var loaded: Int64 = 0
24
+ var expectedLength: Int64 = -1
25
+ /// The start of a UTF-8 character split across chunks.
26
+ var undecodedBytes = Data()
27
+ /// A multipart body written to disk, deleted once the request ends.
28
+ var temporaryFile: URL?
29
+
30
+ init(id: Int, owner: AnyObject?, query: [String: Any]) {
31
+ self.id = id
32
+ self.owner = owner
33
+ responseType = query["responseType"] as? String ?? "text"
34
+ incrementalUpdates = query["incrementalUpdates"] as? Bool ?? false
35
+ }
36
+
37
+ var streamsText: Bool { incrementalUpdates && responseType == "text" }
38
+
39
+ func deleteTemporaryFile() {
40
+ if let temporaryFile { try? FileManager.default.removeItem(at: temporaryFile) }
41
+ }
42
+ }
43
+
44
+ /// What a request sends: bytes in memory, or a file URLSession reads as it uploads.
45
+ private enum Body {
46
+ case none
47
+ case data(Data)
48
+ case file(URL, isTemporary: Bool)
49
+ }
50
+
51
+ private let queue: OperationQueue = {
52
+ let queue = OperationQueue()
53
+ queue.maxConcurrentOperationCount = 1
54
+
55
+ return queue
56
+ }()
57
+
58
+ private lazy var session = URLSession(configuration: .default, delegate: self, delegateQueue: queue)
59
+ private var statesByTaskId: [Int: RequestState] = [:]
60
+ private var tasksByRequestId: [Int: URLSessionTask] = [:]
61
+
62
+ func send(requestId: Int, query: [String: Any], owner: AnyObject?) {
63
+ queue.addOperation { [self] in
64
+ let state = RequestState(id: requestId, owner: owner, query: query)
65
+
66
+ do {
67
+ var request = try urlRequest(from: query)
68
+ let task: URLSessionTask
69
+
70
+ switch try body(query["body"] as? [String: Any], of: &request) {
71
+ case .none:
72
+ task = session.dataTask(with: request)
73
+ case let .data(data):
74
+ task = session.uploadTask(with: request, from: data)
75
+ case let .file(file, isTemporary):
76
+ if isTemporary { state.temporaryFile = file }
77
+ task = session.uploadTask(with: request, fromFile: file)
78
+ }
79
+ statesByTaskId[task.taskIdentifier] = state
80
+ tasksByRequestId[requestId] = task
81
+ task.resume()
82
+ } catch {
83
+ emit(state, "complete", ["error": error.localizedDescription, "timedOut": false])
84
+ }
85
+ }
86
+ }
87
+
88
+ /// JS has already settled the request: nothing more is reported for it.
89
+ func abort(requestId: Int) {
90
+ queue.addOperation { [self] in
91
+ guard let task = tasksByRequestId.removeValue(forKey: requestId) else { return }
92
+
93
+ statesByTaskId.removeValue(forKey: task.taskIdentifier)?.deleteTemporaryFile()
94
+ task.cancel()
95
+ }
96
+ }
97
+
98
+ /// On reload: the requests' JS is gone.
99
+ func abortAll() {
100
+ queue.addOperation { [self] in
101
+ tasksByRequestId.values.forEach { $0.cancel() }
102
+ statesByTaskId.values.forEach { $0.deleteTemporaryFile() }
103
+ tasksByRequestId = [:]
104
+ statesByTaskId = [:]
105
+ }
106
+ }
107
+
108
+ // MARK: URLSessionDataDelegate
109
+
110
+ func urlSession(
111
+ _ session: URLSession,
112
+ task: URLSessionTask,
113
+ didSendBodyData bytesSent: Int64,
114
+ totalBytesSent: Int64,
115
+ totalBytesExpectedToSend: Int64
116
+ ) {
117
+ guard let state = statesByTaskId[task.taskIdentifier] else { return }
118
+
119
+ emit(state, "uploadprogress", ["loaded": totalBytesSent, "total": totalBytesExpectedToSend])
120
+ }
121
+
122
+ func urlSession(
123
+ _ session: URLSession,
124
+ dataTask: URLSessionDataTask,
125
+ didReceive response: URLResponse,
126
+ completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
127
+ ) {
128
+ completionHandler(.allow)
129
+ guard let state = statesByTaskId[dataTask.taskIdentifier] else { return }
130
+
131
+ let httpResponse = response as? HTTPURLResponse
132
+ state.expectedLength = response.expectedContentLength
133
+ state.mimeType = response.mimeType
134
+ emit(state, "response", [
135
+ "status": httpResponse?.statusCode ?? 200,
136
+ "headers": httpResponse?.allHeaderFields ?? [:],
137
+ "url": response.url?.absoluteString ?? "",
138
+ ])
139
+ }
140
+
141
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
142
+ guard let state = statesByTaskId[dataTask.taskIdentifier] else { return }
143
+
144
+ state.loaded += Int64(data.count)
145
+ let progress: [String: Any] = ["loaded": state.loaded, "total": state.expectedLength]
146
+
147
+ if state.streamsText {
148
+ emit(state, "incrementaldata", progress.merging(["text": decodedText(data, of: state)]) { $1 })
149
+ return
150
+ }
151
+
152
+ state.data.append(data)
153
+ if state.incrementalUpdates { emit(state, "progress", progress) }
154
+ }
155
+
156
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
157
+ guard let state = statesByTaskId.removeValue(forKey: task.taskIdentifier) else { return }
158
+
159
+ tasksByRequestId[state.id] = nil
160
+ state.deleteTemporaryFile()
161
+
162
+ if let error {
163
+ let timedOut = (error as? URLError)?.code == .timedOut
164
+ return emit(state, "complete", ["error": error.localizedDescription, "timedOut": timedOut])
165
+ }
166
+
167
+ if !state.streamsText { emit(state, "data", ["data": responseData(of: state)]) }
168
+ emit(state, "complete", ["error": NSNull(), "timedOut": false])
169
+ }
170
+
171
+ /// Text, base64, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob.
172
+ private func responseData(of state: RequestState) -> Any {
173
+ switch state.responseType {
174
+ case "base64":
175
+ return state.data.base64EncodedString()
176
+ case "blob":
177
+ let blobId = blobStore.store(state.data)
178
+ return ["blobId": blobId, "offset": 0, "size": state.data.count, "type": state.mimeType ?? ""]
179
+ default:
180
+ return decodedText(state.data, of: state)
181
+ }
182
+ }
183
+
184
+ // MARK: Requests
185
+
186
+ private func emit(_ state: RequestState, _ eventName: String, _ payload: [String: Any]) {
187
+ onEvent?(state.owner, state.id, eventName, payload)
188
+ }
189
+
190
+ private func urlRequest(from query: [String: Any]) throws -> URLRequest {
191
+ let urlString = query["url"] as? String ?? ""
192
+ guard let url = URL(string: urlString) else { throw NetworkingError("invalid URL \(urlString)") }
193
+
194
+ var request = URLRequest(url: url)
195
+ request.httpMethod = query["method"] as? String ?? "GET"
196
+ request.httpShouldHandleCookies = query["withCredentials"] as? Bool ?? true
197
+ (query["headers"] as? [String: String])?.forEach { request.setValue($1, forHTTPHeaderField: $0) }
198
+
199
+ let timeout = query["timeout"] as? Double ?? 0
200
+ if timeout > 0 { request.timeoutInterval = timeout / 1000 }
201
+
202
+ return request
203
+ }
204
+
205
+ private func body(_ body: [String: Any]?, of request: inout URLRequest) throws -> Body {
206
+ guard let body else { return .none }
207
+
208
+ if let text = body["string"] as? String { return .data(Data(text.utf8)) }
209
+ if let base64 = body["base64"] as? String { return .data(Data(base64Encoded: base64) ?? Data()) }
210
+ if let blob = body["blob"] as? [String: Any] { return .data(try blobData(blob)) }
211
+ if let uri = body["uri"] as? String {
212
+ let url = try fileOrDataURL(uri)
213
+ return url.isFileURL ? .file(url, isTemporary: false) : .data(try Data(contentsOf: url))
214
+ }
215
+ guard let parts = body["formData"] as? [[String: Any]] else { return .none }
216
+
217
+ let boundary = "nativue-\(UUID().uuidString)"
218
+ request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
219
+
220
+ return .file(try writeMultipartBody(parts, boundary: boundary), isTemporary: true)
221
+ }
222
+
223
+ /// multipart/form-data, written to a temporary file: text fields as they are, files copied in chunks
224
+ /// from their uri, so a large video never sits in memory.
225
+ private func writeMultipartBody(_ parts: [[String: Any]], boundary: String) throws -> URL {
226
+ let file = FileManager.default.temporaryDirectory.appendingPathComponent("nativue-upload-\(UUID().uuidString)")
227
+ FileManager.default.createFile(atPath: file.path, contents: nil)
228
+ let output = try FileHandle(forWritingTo: file)
229
+ defer { try? output.close() }
230
+
231
+ do {
232
+ for part in parts {
233
+ try writeMultipartPart(part, boundary: boundary, to: output)
234
+ }
235
+ try output.write(contentsOf: Data("--\(boundary)--\r\n".utf8))
236
+ } catch {
237
+ try? FileManager.default.removeItem(at: file)
238
+ throw error
239
+ }
240
+
241
+ return file
242
+ }
243
+
244
+ private func writeMultipartPart(_ part: [String: Any], boundary: String, to output: FileHandle) throws {
245
+ let name = part["name"] as? String ?? ""
246
+ try output.write(contentsOf: Data("--\(boundary)\r\n".utf8))
247
+
248
+ if let value = part["value"] as? String {
249
+ return try output.write(contentsOf: Data("Content-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".utf8))
250
+ }
251
+ let uri = part["uri"] as? String
252
+ let blob = part["blob"] as? [String: Any]
253
+ guard uri != nil || blob != nil else { return }
254
+
255
+ let filename = part["filename"] as? String ?? "file"
256
+ let type = part["type"] as? String ?? "application/octet-stream"
257
+ try output.write(contentsOf: Data("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\"\r\n".utf8))
258
+ try output.write(contentsOf: Data("Content-Type: \(type)\r\n\r\n".utf8))
259
+ if let uri { try copyContents(of: try fileOrDataURL(uri), to: output) }
260
+ if let blob { try output.write(contentsOf: try blobData(blob)) }
261
+ try output.write(contentsOf: Data("\r\n".utf8))
262
+ }
263
+
264
+ /// A file in chunks; a data: uri is already in memory.
265
+ private func copyContents(of url: URL, to output: FileHandle) throws {
266
+ guard url.isFileURL else { return try output.write(contentsOf: Data(contentsOf: url)) }
267
+
268
+ let input = try FileHandle(forReadingFrom: url)
269
+ defer { try? input.close() }
270
+
271
+ while let chunk = try input.read(upToCount: 64 * 1024), !chunk.isEmpty {
272
+ try output.write(contentsOf: chunk)
273
+ }
274
+ }
275
+
276
+ private func blobData(_ blob: [String: Any]) throws -> Data {
277
+ guard let data = blobStore.data(of: blob) else { throw NetworkingError("The blob has been released") }
278
+
279
+ return data
280
+ }
281
+
282
+ private func fileOrDataURL(_ uri: String) throws -> URL {
283
+ guard let url = URL(string: uri), url.isFileURL || url.scheme == "data" else {
284
+ throw NetworkingError("only file: and data: uris can be sent, not \(uri)")
285
+ }
286
+
287
+ return url
288
+ }
289
+
290
+ /// UTF-8. A character split between chunks waits for the rest in the next one.
291
+ private func decodedText(_ chunk: Data, of state: RequestState) -> String {
292
+ let bytes = state.undecodedBytes + chunk
293
+ let splitLength = incompleteCharacterLength(atEndOf: bytes)
294
+ state.undecodedBytes = bytes.suffix(splitLength)
295
+
296
+ return String(decoding: bytes.dropLast(splitLength), as: UTF8.self)
297
+ }
298
+
299
+ /// How many bytes at the end start a UTF-8 character that isn't complete yet.
300
+ private func incompleteCharacterLength(atEndOf bytes: Data) -> Int {
301
+ for (distanceFromEnd, byte) in bytes.suffix(4).reversed().enumerated() {
302
+ let isContinuationByte = byte & 0xC0 == 0x80
303
+ if isContinuationByte { continue }
304
+
305
+ let characterLength = byte >= 0xF0 ? 4 : byte >= 0xE0 ? 3 : byte >= 0xC0 ? 2 : 1
306
+ let availableLength = distanceFromEnd + 1
307
+
308
+ return availableLength < characterLength ? availableLength : 0
309
+ }
310
+
311
+ return 0
312
+ }
313
+ }
314
+
315
+ struct NetworkingError: LocalizedError {
316
+ let errorDescription: String?
317
+
318
+ init(_ message: String) {
319
+ errorDescription = message
320
+ }
321
+ }
@@ -23,13 +23,18 @@ final class VueScrollView: UIScrollView {
23
23
  /// above it.
24
24
  var adjustsForKeyboard = false
25
25
 
26
- /// Set when JS listens to @scroll. Called on every scroll step and size change (FlatList windowing).
27
- // Limitation: One JS call per frame while scrolling; coalesce / add scrollEventThrottle if JS falls behind.
26
+ /// Set when JS listens to @scroll. Called on every scroll step and size change (FlatList windowing),
27
+ /// at most once per `scrollEventThrottle`.
28
28
  var onScroll: ((CGRect) -> Void)? {
29
29
  didSet { lastReportedBounds = nil }
30
30
  }
31
31
 
32
+ /// scroll-event-throttle, in milliseconds: 0 reports every frame.
33
+ var scrollEventThrottle: Double = 0
34
+
32
35
  private var lastReportedBounds: CGRect?
36
+ private var lastReportTime: CFTimeInterval = 0
37
+ private var hasPendingReport = false
33
38
 
34
39
  /// Set when JS listens to @refresh: shows a pull-to-refresh spinner. JS owns `refreshing`.
35
40
  var onRefresh: (() -> Void)? {
@@ -79,10 +84,28 @@ final class VueScrollView: UIScrollView {
79
84
  super.layoutSubviews()
80
85
 
81
86
  onOffsetChange?(contentOffset)
87
+ reportScrollThrottled()
88
+ }
89
+
90
+ // Within the throttle, the report waits for its end, so the last position always reaches JS.
91
+ private func reportScrollThrottled() {
92
+ guard onScroll != nil, bounds != lastReportedBounds, !hasPendingReport else { return }
93
+
94
+ let elapsed = (CACurrentMediaTime() - lastReportTime) * 1000
95
+ guard elapsed < scrollEventThrottle else { return reportScroll() }
96
+
97
+ hasPendingReport = true
98
+ DispatchQueue.main.asyncAfter(deadline: .now() + (scrollEventThrottle - elapsed) / 1000) { [weak self] in
99
+ self?.hasPendingReport = false
100
+ self?.reportScroll()
101
+ }
102
+ }
82
103
 
104
+ private func reportScroll() {
83
105
  guard let onScroll, bounds != lastReportedBounds else { return }
84
106
 
85
107
  lastReportedBounds = bounds
108
+ lastReportTime = CACurrentMediaTime()
86
109
  onScroll(bounds)
87
110
  }
88
111
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -38,9 +38,11 @@
38
38
  "dependencies": {
39
39
  "@vitejs/plugin-vue": "^6.0.11",
40
40
  "@vue/runtime-core": "^3.5.45",
41
+ "base64-js": "^1.5.1",
41
42
  "hermes-compiler": "260318099.0.8",
42
43
  "vite": "^8.3.8",
43
- "vue": "^3.5.45"
44
+ "vue": "^3.5.45",
45
+ "whatwg-fetch": "^3.6.20"
44
46
  },
45
47
  "devDependencies": {
46
48
  "typescript": "^5.9.3",
package/src/blob.ts ADDED
@@ -0,0 +1,204 @@
1
+ // Blob, File and FileReader, like the browser's. The bytes stay native (see BlobStore), so a large
2
+ // download never crosses into JS unless it's read. They're freed when the garbage collector collects
3
+ // the last Blob that points to them: __blobCollector gives an object whose collection frees them.
4
+ import { fromByteArray, toByteArray } from 'base64-js'
5
+ import { EventTarget, ProgressEvent } from './events'
6
+ import { ReadableStream } from './streams'
7
+ import type { NativeBlob, NativeBlobPart } from './types'
8
+
9
+ const native = globalThis.__native
10
+
11
+ /** What stream() reads from native at a time. */
12
+ const STREAM_CHUNK_SIZE = 64 * 1024
13
+
14
+ export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob
15
+
16
+ export interface BlobPropertyBag {
17
+ type?: string
18
+ }
19
+
20
+ export class Blob {
21
+ /** Where the bytes are, natively. Read by XMLHttpRequest and FormData to send them. */
22
+ readonly data: NativeBlob
23
+ // Kept only so it's collected with the Blob (and its slices, which share it).
24
+ private readonly collector: object | undefined
25
+
26
+ constructor(parts: BlobPart[] = [], { type = '' }: BlobPropertyBag = {}) {
27
+ const created = native.blobCreate(parts.map(nativeBlobPart))
28
+ if (!created) throw new Error('The blob has been released')
29
+
30
+ const { blobId, size } = created
31
+
32
+ this.data = { blobId, offset: 0, size, type: type.toLowerCase() }
33
+ this.collector = globalThis.__blobCollector?.(blobId)
34
+ }
35
+
36
+ /** A Blob for bytes native already holds: a download's, or a slice's. */
37
+ static fromNative(data: NativeBlob, collector?: object): Blob {
38
+ const blob = Object.create(Blob.prototype) as Blob
39
+ Object.assign(blob, { data, collector: collector ?? globalThis.__blobCollector?.(data.blobId) })
40
+
41
+ return blob
42
+ }
43
+
44
+ get size(): number {
45
+ return this.data.size
46
+ }
47
+
48
+ get type(): string {
49
+ return this.data.type
50
+ }
51
+
52
+ slice(start = 0, end = this.size, type = ''): Blob {
53
+ const from = clampedIndex(start, this.size)
54
+ const to = Math.max(from, clampedIndex(end, this.size))
55
+ const data = { ...this.data, offset: this.data.offset + from, size: to - from, type }
56
+
57
+ return Blob.fromNative(data, this.collector)
58
+ }
59
+
60
+ async text(): Promise<string> {
61
+ return this.read('text')
62
+ }
63
+
64
+ async arrayBuffer(): Promise<ArrayBuffer> {
65
+ return toByteArray(this.read('base64')).buffer as ArrayBuffer
66
+ }
67
+
68
+ /** The bytes in chunks, each read from native when the stream is read. */
69
+ stream(): ReadableStream<Uint8Array> {
70
+ let offset = 0
71
+
72
+ return new ReadableStream({
73
+ pull: (controller) => {
74
+ if (offset >= this.size) return controller.close()
75
+
76
+ const chunk = this.slice(offset, offset + STREAM_CHUNK_SIZE)
77
+ offset += chunk.size
78
+ controller.enqueue(toByteArray(chunk.read('base64')))
79
+ },
80
+ })
81
+ }
82
+
83
+ /** Synchronous: the bytes are in native memory. */
84
+ read(encoding: 'text' | 'base64'): string {
85
+ const { blobId, offset, size } = this.data
86
+ const contents = native.blobRead(blobId, offset, size, encoding)
87
+ if (contents === null) throw new Error('The blob has been released')
88
+
89
+ return contents
90
+ }
91
+ }
92
+
93
+ export class File extends Blob {
94
+ readonly name: string
95
+ readonly lastModified: number
96
+
97
+ constructor(
98
+ parts: BlobPart[],
99
+ name: string,
100
+ { type, lastModified = Date.now() }: BlobPropertyBag & { lastModified?: number } = {},
101
+ ) {
102
+ super(parts, { type })
103
+ this.name = name
104
+ this.lastModified = lastModified
105
+ }
106
+ }
107
+
108
+ function nativeBlobPart(part: BlobPart): NativeBlobPart {
109
+ if (typeof part === 'string') return { string: part }
110
+ if (part instanceof Blob) return { blob: part.data }
111
+
112
+ return { base64: fromByteArray(bytesOf(part)) }
113
+ }
114
+
115
+ export function bytesOf(buffer: ArrayBuffer | ArrayBufferView): Uint8Array {
116
+ if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer)
117
+
118
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
119
+ }
120
+
121
+ function clampedIndex(index: number, size: number): number {
122
+ const fromStart = index < 0 ? size + index : index
123
+
124
+ return Math.min(Math.max(fromStart, 0), size)
125
+ }
126
+
127
+ type ReadResult = string | ArrayBuffer | null
128
+
129
+ export class FileReader extends EventTarget {
130
+ static readonly EMPTY = 0
131
+ static readonly LOADING = 1
132
+ static readonly DONE = 2
133
+ readonly EMPTY = 0
134
+ readonly LOADING = 1
135
+ readonly DONE = 2
136
+
137
+ readyState = 0
138
+ result: ReadResult = null
139
+ error: Error | null = null
140
+
141
+ onloadstart: ((event: ProgressEvent) => void) | null = null
142
+ onprogress: ((event: ProgressEvent) => void) | null = null
143
+ onload: ((event: ProgressEvent) => void) | null = null
144
+ onloadend: ((event: ProgressEvent) => void) | null = null
145
+ onerror: ((event: ProgressEvent) => void) | null = null
146
+ onabort: ((event: ProgressEvent) => void) | null = null
147
+
148
+ private readId = 0
149
+
150
+ // Only UTF-8: the encoding argument is ignored.
151
+ readAsText(blob: Blob): void {
152
+ this.startReading(blob, () => blob.read('text'))
153
+ }
154
+
155
+ readAsDataURL(blob: Blob): void {
156
+ const type = blob.type || 'application/octet-stream'
157
+
158
+ this.startReading(blob, () => `data:${type};base64,${blob.read('base64')}`)
159
+ }
160
+
161
+ readAsArrayBuffer(blob: Blob): void {
162
+ this.startReading(blob, () => toByteArray(blob.read('base64')).buffer as ArrayBuffer)
163
+ }
164
+
165
+ abort(): void {
166
+ if (this.readyState !== this.LOADING) return
167
+
168
+ this.readId++
169
+ this.finish(null, null, 'abort', 0)
170
+ }
171
+
172
+ // Asynchronous like the browser's, though the read itself is synchronous.
173
+ private startReading(blob: Blob, read: () => ReadResult) {
174
+ if (this.readyState === this.LOADING) throw new Error('The FileReader is already reading')
175
+
176
+ const readId = ++this.readId
177
+ this.readyState = this.LOADING
178
+ this.result = null
179
+ this.error = null
180
+ this.dispatchProgress('loadstart', 0, blob.size)
181
+
182
+ setTimeout(() => {
183
+ if (readId !== this.readId) return
184
+
185
+ try {
186
+ this.finish(read(), null, 'load', blob.size)
187
+ } catch (error) {
188
+ this.finish(null, error as Error, 'error', 0)
189
+ }
190
+ })
191
+ }
192
+
193
+ private finish(result: ReadResult, error: Error | null, outcome: string, loaded: number) {
194
+ this.readyState = this.DONE
195
+ this.result = result
196
+ this.error = error
197
+ this.dispatchProgress(outcome, loaded, loaded)
198
+ this.dispatchProgress('loadend', loaded, loaded)
199
+ }
200
+
201
+ private dispatchProgress(type: string, loaded: number, total: number) {
202
+ this.dispatchEvent(new ProgressEvent(type, { lengthComputable: true, loaded, total }))
203
+ }
204
+ }