@nativue/core 0.5.0 → 0.6.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.
- package/android/src/main/cpp/bridge.cpp +49 -0
- package/android/src/main/java/dev/nativue/BlobStore.kt +72 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +30 -38
- package/android/src/main/java/dev/nativue/Networking.kt +323 -0
- package/android/src/main/java/dev/nativue/Views.kt +33 -2
- package/cli/nativue.mjs +46 -6
- package/cli/run.mjs +156 -48
- package/ios/BlobStore.swift +74 -0
- package/ios/Bridge.swift +42 -31
- package/ios/ImageView.swift +14 -2
- package/ios/JavaScriptRuntime/JavaScriptRuntime.mm +35 -0
- package/ios/Networking.swift +321 -0
- package/ios/VueScrollView.swift +25 -2
- package/package.json +4 -2
- package/src/blob.ts +204 -0
- package/src/components.ts +55 -27
- package/src/entry.ts +10 -2
- package/src/events.ts +119 -0
- package/src/fetch.ts +97 -102
- package/src/globals.ts +6 -4
- package/src/native-components.ts +2 -0
- package/src/networking.ts +24 -0
- package/src/renderer.ts +2 -2
- package/src/streams.ts +206 -0
- package/src/types.ts +59 -7
- package/src/url.ts +282 -0
- package/src/xhr.ts +414 -0
package/src/streams.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// ReadableStream, like the browser's (Hermes has none), for Blob.stream(): read with getReader() or
|
|
2
|
+
// iterate it. Chunks are pulled only when read.
|
|
3
|
+
// Limitation: Default readers only: no pipeTo/pipeThrough, tee, byte (BYOB) readers or queuing strategies.
|
|
4
|
+
// Use a full web streams polyfill if a library needs those.
|
|
5
|
+
|
|
6
|
+
export interface UnderlyingSource<Chunk> {
|
|
7
|
+
start?(controller: ReadableStreamDefaultController<Chunk>): void | Promise<void>
|
|
8
|
+
pull?(controller: ReadableStreamDefaultController<Chunk>): void | Promise<void>
|
|
9
|
+
cancel?(reason?: unknown): void | Promise<void>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type ReadResult<Chunk> = { done: false; value: Chunk } | { done: true; value: undefined }
|
|
13
|
+
|
|
14
|
+
interface PendingRead<Chunk> {
|
|
15
|
+
resolve(result: ReadResult<Chunk>): void
|
|
16
|
+
reject(error: unknown): void
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class ReadableStreamDefaultController<Chunk> {
|
|
20
|
+
constructor(private readonly stream: ReadableStream<Chunk>) {}
|
|
21
|
+
|
|
22
|
+
get desiredSize(): number | null {
|
|
23
|
+
return this.stream.desiredSize()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
enqueue(chunk: Chunk): void {
|
|
27
|
+
this.stream.enqueue(chunk)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
close(): void {
|
|
31
|
+
this.stream.close()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
error(error?: unknown): void {
|
|
35
|
+
this.stream.fail(error)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class ReadableStream<Chunk = Uint8Array> {
|
|
40
|
+
private readonly source: UnderlyingSource<Chunk>
|
|
41
|
+
private readonly controller = new ReadableStreamDefaultController<Chunk>(this)
|
|
42
|
+
private readonly queue: Chunk[] = []
|
|
43
|
+
private readonly pendingReads: PendingRead<Chunk>[] = []
|
|
44
|
+
private state: 'readable' | 'closed' | 'errored' = 'readable'
|
|
45
|
+
private storedError: unknown = undefined
|
|
46
|
+
private started = false
|
|
47
|
+
private pulling = false
|
|
48
|
+
private reader: ReadableStreamDefaultReader<Chunk> | null = null
|
|
49
|
+
|
|
50
|
+
constructor(source: UnderlyingSource<Chunk> = {}) {
|
|
51
|
+
this.source = source
|
|
52
|
+
|
|
53
|
+
Promise.resolve()
|
|
54
|
+
.then(() => source.start?.(this.controller))
|
|
55
|
+
.then(
|
|
56
|
+
() => {
|
|
57
|
+
this.started = true
|
|
58
|
+
this.pullIfNeeded()
|
|
59
|
+
},
|
|
60
|
+
(error) => this.fail(error),
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get locked(): boolean {
|
|
65
|
+
return this.reader !== null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
getReader(): ReadableStreamDefaultReader<Chunk> {
|
|
69
|
+
if (this.reader) throw new TypeError('The stream is locked to a reader')
|
|
70
|
+
|
|
71
|
+
this.reader = new ReadableStreamDefaultReader(this)
|
|
72
|
+
|
|
73
|
+
return this.reader
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
cancel(reason?: unknown): Promise<void> {
|
|
77
|
+
if (this.locked) return Promise.reject(new TypeError('The stream is locked to a reader'))
|
|
78
|
+
|
|
79
|
+
return this.cancelSource(reason)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
values({ preventCancel = false } = {}): AsyncIterableIterator<Chunk> {
|
|
83
|
+
const reader = this.getReader()
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
next: async () => {
|
|
87
|
+
const result = await reader.read()
|
|
88
|
+
if (result.done) reader.releaseLock()
|
|
89
|
+
|
|
90
|
+
return result as IteratorResult<Chunk>
|
|
91
|
+
},
|
|
92
|
+
return: async (value?: unknown) => {
|
|
93
|
+
if (!preventCancel) await reader.cancel()
|
|
94
|
+
reader.releaseLock()
|
|
95
|
+
|
|
96
|
+
return { done: true, value } as IteratorResult<Chunk>
|
|
97
|
+
},
|
|
98
|
+
[Symbol.asyncIterator]() {
|
|
99
|
+
return this
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
[Symbol.asyncIterator](): AsyncIterableIterator<Chunk> {
|
|
105
|
+
return this.values()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ---------- For the reader and the controller ----------
|
|
109
|
+
|
|
110
|
+
/** Next chunk, waiting for the source if none is queued. */
|
|
111
|
+
read(): Promise<ReadResult<Chunk>> {
|
|
112
|
+
if (this.queue.length > 0) return Promise.resolve({ done: false, value: this.queue.shift()! })
|
|
113
|
+
if (this.state === 'closed') return Promise.resolve({ done: true, value: undefined })
|
|
114
|
+
if (this.state === 'errored') return Promise.reject(this.storedError)
|
|
115
|
+
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
this.pendingReads.push({ resolve, reject })
|
|
118
|
+
this.pullIfNeeded()
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
release(reader: ReadableStreamDefaultReader<Chunk>): void {
|
|
123
|
+
if (this.reader === reader) this.reader = null
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
cancelSource(reason?: unknown): Promise<void> {
|
|
127
|
+
if (this.state !== 'readable') return Promise.resolve()
|
|
128
|
+
|
|
129
|
+
this.queue.length = 0
|
|
130
|
+
this.close()
|
|
131
|
+
|
|
132
|
+
return Promise.resolve(this.source.cancel?.(reason)).then(() => undefined)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
desiredSize(): number | null {
|
|
136
|
+
if (this.state === 'errored') return null
|
|
137
|
+
if (this.state === 'closed') return 0
|
|
138
|
+
|
|
139
|
+
return this.pendingReads.length - this.queue.length
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
enqueue(chunk: Chunk): void {
|
|
143
|
+
if (this.state !== 'readable') throw new TypeError('The stream is closed')
|
|
144
|
+
|
|
145
|
+
const pendingRead = this.pendingReads.shift()
|
|
146
|
+
if (pendingRead) pendingRead.resolve({ done: false, value: chunk })
|
|
147
|
+
else this.queue.push(chunk)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
close(): void {
|
|
151
|
+
if (this.state !== 'readable') return
|
|
152
|
+
|
|
153
|
+
this.state = 'closed'
|
|
154
|
+
this.pendingReads.splice(0).forEach((read) => read.resolve({ done: true, value: undefined }))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
fail(error: unknown): void {
|
|
158
|
+
if (this.state !== 'readable') return
|
|
159
|
+
|
|
160
|
+
this.state = 'errored'
|
|
161
|
+
this.storedError = error
|
|
162
|
+
this.queue.length = 0
|
|
163
|
+
this.pendingReads.splice(0).forEach((read) => read.reject(error))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Pulls one chunk at a time, only while someone is waiting for one.
|
|
167
|
+
private pullIfNeeded() {
|
|
168
|
+
const waiting = this.pendingReads.length > 0
|
|
169
|
+
if (!this.started || this.pulling || !waiting || this.state !== 'readable' || !this.source.pull)
|
|
170
|
+
return
|
|
171
|
+
|
|
172
|
+
this.pulling = true
|
|
173
|
+
Promise.resolve()
|
|
174
|
+
.then(() => this.source.pull!(this.controller))
|
|
175
|
+
.then(
|
|
176
|
+
() => {
|
|
177
|
+
this.pulling = false
|
|
178
|
+
this.pullIfNeeded()
|
|
179
|
+
},
|
|
180
|
+
(error) => this.fail(error),
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export class ReadableStreamDefaultReader<Chunk> {
|
|
186
|
+
private stream: ReadableStream<Chunk> | null
|
|
187
|
+
|
|
188
|
+
constructor(stream: ReadableStream<Chunk>) {
|
|
189
|
+
this.stream = stream
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
read(): Promise<ReadResult<Chunk>> {
|
|
193
|
+
if (!this.stream) return Promise.reject(new TypeError('The reader has been released'))
|
|
194
|
+
|
|
195
|
+
return this.stream.read()
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
cancel(reason?: unknown): Promise<void> {
|
|
199
|
+
return this.stream?.cancelSource(reason) ?? Promise.resolve()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
releaseLock(): void {
|
|
203
|
+
this.stream?.release(this)
|
|
204
|
+
this.stream = null
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -139,11 +139,63 @@ export interface NativeModule {
|
|
|
139
139
|
storageKeys(): string[]
|
|
140
140
|
storageClear(): void
|
|
141
141
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
142
|
+
/** Starts an HTTP request; its progress comes back through __networkEvent. */
|
|
143
|
+
sendRequest(requestId: number, request: NativeRequest): void
|
|
144
|
+
abortRequest(requestId: number): void
|
|
145
|
+
|
|
146
|
+
/** Joins the parts into new native bytes; null if a part's blob has been released. */
|
|
147
|
+
blobCreate(parts: NativeBlobPart[]): { blobId: string; size: number } | null
|
|
148
|
+
/** UTF-8 text or base64 of the bytes; null once released. */
|
|
149
|
+
blobRead(blobId: string, offset: number, size: number, encoding: 'text' | 'base64'): string | null
|
|
150
|
+
blobRelease(blobId: string): void
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Bytes held natively: a Blob's, or a slice of them. */
|
|
154
|
+
export interface NativeBlob {
|
|
155
|
+
blobId: string
|
|
156
|
+
offset: number
|
|
157
|
+
size: number
|
|
158
|
+
type: string
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export type NativeBlobPart = { string: string } | { base64: string } | { blob: NativeBlob }
|
|
162
|
+
|
|
163
|
+
export interface NativeRequest {
|
|
164
|
+
method: string
|
|
165
|
+
url: string
|
|
166
|
+
headers: Record<string, string>
|
|
167
|
+
body: NativeRequestBody
|
|
168
|
+
/** 'base64' for arraybuffer responses; 'blob' keeps the bytes native. */
|
|
169
|
+
responseType: 'text' | 'base64' | 'blob'
|
|
170
|
+
/** Send the text as it arrives (incrementaldata) and download progress, not just the whole at the end. */
|
|
171
|
+
incrementalUpdates: boolean
|
|
172
|
+
/** In milliseconds; 0 for the platform's. */
|
|
173
|
+
timeout: number
|
|
174
|
+
withCredentials: boolean
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Text, bytes as base64, a file native reads by uri, or the parts of a multipart/form-data body.
|
|
178
|
+
export type NativeRequestBody =
|
|
179
|
+
| null
|
|
180
|
+
| { string: string }
|
|
181
|
+
| { base64: string }
|
|
182
|
+
| { uri: string }
|
|
183
|
+
| { blob: NativeBlob }
|
|
184
|
+
| { formData: NativeFormDataPart[] }
|
|
185
|
+
|
|
186
|
+
export type NativeFormDataPart =
|
|
187
|
+
| { name: string; value: string }
|
|
188
|
+
| { name: string; uri: string; filename: string; type: string }
|
|
189
|
+
| { name: string; blob: NativeBlob; filename: string; type: string }
|
|
190
|
+
|
|
191
|
+
/** What native reports about a request, by event name. */
|
|
192
|
+
export interface NetworkEventPayloads {
|
|
193
|
+
uploadprogress: { loaded: number; total: number }
|
|
194
|
+
response: { status: number; headers: Record<string, string>; url: string }
|
|
195
|
+
/** The whole response, once: text, base64 for 'base64', a NativeBlob for 'blob'. Not sent after incrementaldata. */
|
|
196
|
+
data: { data: string | NativeBlob }
|
|
197
|
+
incrementaldata: { text: string; loaded: number; total: number }
|
|
198
|
+
progress: { loaded: number; total: number }
|
|
199
|
+
/** The end: `error` set when it failed. */
|
|
200
|
+
complete: { error: string | null; timedOut: boolean }
|
|
149
201
|
}
|
package/src/url.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// URL and URLSearchParams, like the browser's: Hermes has neither. Also URL.createObjectURL, for showing
|
|
2
|
+
// a Blob in <Image>.
|
|
3
|
+
// Limitation: parses URLs without the full WHATWG algorithm: no IDN (punycode) hosts, no percent-encoding
|
|
4
|
+
// or IPv6 normalization. Enough for building and reading http(s) URLs; use a full parser if that falls short.
|
|
5
|
+
import type { Blob } from './blob'
|
|
6
|
+
|
|
7
|
+
type SearchParamsInit = string | URLSearchParams | Record<string, string> | [string, string][]
|
|
8
|
+
|
|
9
|
+
export class URLSearchParams {
|
|
10
|
+
private readonly pairs: [string, string][] = []
|
|
11
|
+
/** Set by a URL, whose `search` follows its searchParams. */
|
|
12
|
+
onChange: (() => void) | null = null
|
|
13
|
+
|
|
14
|
+
constructor(init: SearchParamsInit = '') {
|
|
15
|
+
if (typeof init === 'string') this.replaceWith(init)
|
|
16
|
+
else if (init instanceof URLSearchParams) this.pairs.push(...init.pairs)
|
|
17
|
+
else if (Array.isArray(init))
|
|
18
|
+
init.forEach(([name, value]) => this.pairs.push([name, String(value)]))
|
|
19
|
+
else Object.entries(init).forEach(([name, value]) => this.pairs.push([name, String(value)]))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
get size(): number {
|
|
23
|
+
return this.pairs.length
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
append(name: string, value: string): void {
|
|
27
|
+
this.pairs.push([name, String(value)])
|
|
28
|
+
this.onChange?.()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
delete(name: string): void {
|
|
32
|
+
this.splice(this.pairs.filter(([pairName]) => pairName !== name))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
get(name: string): string | null {
|
|
36
|
+
return this.pairs.find(([pairName]) => pairName === name)?.[1] ?? null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
getAll(name: string): string[] {
|
|
40
|
+
return this.pairs.filter(([pairName]) => pairName === name).map(([, value]) => value)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
has(name: string): boolean {
|
|
44
|
+
return this.pairs.some(([pairName]) => pairName === name)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Replaces the first pair with that name and drops the others, keeping its place.
|
|
48
|
+
set(name: string, value: string): void {
|
|
49
|
+
const index = this.pairs.findIndex(([pairName]) => pairName === name)
|
|
50
|
+
if (index === -1) return this.append(name, value)
|
|
51
|
+
|
|
52
|
+
const others = this.pairs.filter(
|
|
53
|
+
([pairName], pairIndex) => pairName !== name || pairIndex === index,
|
|
54
|
+
)
|
|
55
|
+
this.splice(others.map((pair) => (pair[0] === name ? [name, String(value)] : pair)))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
sort(): void {
|
|
59
|
+
this.splice(
|
|
60
|
+
[...this.pairs].sort(([first], [second]) => (first < second ? -1 : first > second ? 1 : 0)),
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
forEach(callback: (value: string, name: string, searchParams: URLSearchParams) => void): void {
|
|
65
|
+
this.pairs.forEach(([name, value]) => callback(value, name, this))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
keys(): IterableIterator<string> {
|
|
69
|
+
return this.pairs.map(([name]) => name)[Symbol.iterator]()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
values(): IterableIterator<string> {
|
|
73
|
+
return this.pairs.map(([, value]) => value)[Symbol.iterator]()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
entries(): IterableIterator<[string, string]> {
|
|
77
|
+
return this.pairs.map(([name, value]): [string, string] => [name, value])[Symbol.iterator]()
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
[Symbol.iterator](): IterableIterator<[string, string]> {
|
|
81
|
+
return this.entries()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
toString(): string {
|
|
85
|
+
return this.pairs
|
|
86
|
+
.map(([name, value]) => `${encodeFormComponent(name)}=${encodeFormComponent(value)}`)
|
|
87
|
+
.join('&')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** From a query string, without telling a URL: it's the one setting it. */
|
|
91
|
+
replaceWith(query: string): void {
|
|
92
|
+
const pairs = query
|
|
93
|
+
.replace(/^\?/, '')
|
|
94
|
+
.split('&')
|
|
95
|
+
.filter(Boolean)
|
|
96
|
+
.map((pair): [string, string] => {
|
|
97
|
+
const separator = pair.indexOf('=')
|
|
98
|
+
const name = separator === -1 ? pair : pair.slice(0, separator)
|
|
99
|
+
const value = separator === -1 ? '' : pair.slice(separator + 1)
|
|
100
|
+
|
|
101
|
+
return [decodeFormComponent(name), decodeFormComponent(value)]
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
this.pairs.splice(0, this.pairs.length, ...pairs)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private splice(pairs: [string, string][]) {
|
|
108
|
+
this.pairs.splice(0, this.pairs.length, ...pairs)
|
|
109
|
+
this.onChange?.()
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// application/x-www-form-urlencoded: encodeURIComponent leaves !'()~ as they are, and a space is '+'.
|
|
114
|
+
function encodeFormComponent(text: string): string {
|
|
115
|
+
return encodeURIComponent(text)
|
|
116
|
+
.replace(/[!'()~]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)
|
|
117
|
+
.replace(/%20/g, '+')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function decodeFormComponent(text: string): string {
|
|
121
|
+
const spaced = text.replace(/\+/g, ' ')
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
return decodeURIComponent(spaced)
|
|
125
|
+
} catch {
|
|
126
|
+
return spaced
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// scheme:, then //user:password@host:port (optional), path, ?query, #fragment.
|
|
131
|
+
const URL_PATTERN =
|
|
132
|
+
/^([a-z][a-z\d+.-]*:)(?:\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[^\]]*\]|[^:/?#]*)(?::(\d*))?)?([^?#]*)(\?[^#]*)?(#.*)?$/i
|
|
133
|
+
|
|
134
|
+
const DEFAULT_PORTS: Record<string, string> = {
|
|
135
|
+
'http:': '80',
|
|
136
|
+
'https:': '443',
|
|
137
|
+
'ws:': '80',
|
|
138
|
+
'wss:': '443',
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Blobs shown through an object URL, kept alive until it's revoked. */
|
|
142
|
+
const blobsByObjectUrl = new Map<string, Blob>()
|
|
143
|
+
|
|
144
|
+
export class URL {
|
|
145
|
+
protocol = ''
|
|
146
|
+
username = ''
|
|
147
|
+
password = ''
|
|
148
|
+
hostname = ''
|
|
149
|
+
port = ''
|
|
150
|
+
pathname = ''
|
|
151
|
+
hash = ''
|
|
152
|
+
private hasAuthority = false
|
|
153
|
+
private query = ''
|
|
154
|
+
private params: URLSearchParams | null = null
|
|
155
|
+
|
|
156
|
+
constructor(url: string | URL, base?: string | URL) {
|
|
157
|
+
this.href = base === undefined ? String(url) : resolve(String(url), new URL(base))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** `blob:` URL for a Blob, which <Image> can show. The Blob stays alive until revokeObjectURL. */
|
|
161
|
+
static createObjectURL(blob: Blob): string {
|
|
162
|
+
const { blobId, offset, size } = blob.data
|
|
163
|
+
const url = `blob:${blobId}?offset=${offset}&size=${size}`
|
|
164
|
+
blobsByObjectUrl.set(url, blob)
|
|
165
|
+
|
|
166
|
+
return url
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
static revokeObjectURL(url: string): void {
|
|
170
|
+
blobsByObjectUrl.delete(url)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
static canParse(url: string, base?: string): boolean {
|
|
174
|
+
try {
|
|
175
|
+
new URL(url, base)
|
|
176
|
+
return true
|
|
177
|
+
} catch {
|
|
178
|
+
return false
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
get href(): string {
|
|
183
|
+
const credentials = this.username
|
|
184
|
+
? `${this.username}${this.password ? `:${this.password}` : ''}@`
|
|
185
|
+
: ''
|
|
186
|
+
const authority = this.hasAuthority ? `//${credentials}${this.host}` : ''
|
|
187
|
+
|
|
188
|
+
return `${this.protocol}${authority}${this.pathname}${this.search}${this.hash}`
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
set href(url: string) {
|
|
192
|
+
const match = URL_PATTERN.exec(url.trim())
|
|
193
|
+
if (!match) throw new TypeError(`Invalid URL: ${url}`)
|
|
194
|
+
|
|
195
|
+
const [, protocol, username, password, hostname, port, pathname, query, hash] = match
|
|
196
|
+
this.protocol = protocol.toLowerCase()
|
|
197
|
+
this.hasAuthority = hostname !== undefined
|
|
198
|
+
this.username = username ?? ''
|
|
199
|
+
this.password = password ?? ''
|
|
200
|
+
this.hostname = (hostname ?? '').toLowerCase()
|
|
201
|
+
this.port = port === DEFAULT_PORTS[this.protocol] ? '' : (port ?? '')
|
|
202
|
+
this.pathname = this.hasAuthority ? removeDotSegments(pathname) || '/' : pathname
|
|
203
|
+
this.search = query ?? ''
|
|
204
|
+
this.hash = hash === '#' ? '' : (hash ?? '')
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
get host(): string {
|
|
208
|
+
return this.port ? `${this.hostname}:${this.port}` : this.hostname
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
set host(host: string) {
|
|
212
|
+
const [hostname, port = ''] = host.split(':')
|
|
213
|
+
this.hostname = hostname.toLowerCase()
|
|
214
|
+
this.port = port
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
get origin(): string {
|
|
218
|
+
return this.hasAuthority ? `${this.protocol}//${this.host}` : 'null'
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
get search(): string {
|
|
222
|
+
return this.query.length > 1 ? this.query : ''
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
set search(search: string) {
|
|
226
|
+
this.query = search && !search.startsWith('?') ? `?${search}` : search
|
|
227
|
+
this.params?.replaceWith(this.query)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
get searchParams(): URLSearchParams {
|
|
231
|
+
if (this.params) return this.params
|
|
232
|
+
|
|
233
|
+
this.params = new URLSearchParams(this.query)
|
|
234
|
+
this.params.onChange = () => {
|
|
235
|
+
const query = this.params!.toString()
|
|
236
|
+
this.query = query ? `?${query}` : ''
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return this.params
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
toString(): string {
|
|
243
|
+
return this.href
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
toJSON(): string {
|
|
247
|
+
return this.href
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** `url` relative to `base`, as a browser resolves a link. */
|
|
252
|
+
function resolve(url: string, base: URL): string {
|
|
253
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(url)) return url
|
|
254
|
+
if (url.startsWith('//')) return `${base.protocol}${url}`
|
|
255
|
+
|
|
256
|
+
const root = `${base.protocol}${base.origin === 'null' ? '' : `//${base.host}`}`
|
|
257
|
+
if (url.startsWith('/')) return `${root}${url}`
|
|
258
|
+
if (url.startsWith('?')) return `${root}${base.pathname}${url}`
|
|
259
|
+
if (url.startsWith('#')) return `${root}${base.pathname}${base.search}${url}`
|
|
260
|
+
if (url === '') return `${root}${base.pathname}${base.search}`
|
|
261
|
+
|
|
262
|
+
const directory = base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1)
|
|
263
|
+
|
|
264
|
+
return `${root}${directory}${url}`
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// "/a/b/../c/./d" → "/a/c/d"
|
|
268
|
+
function removeDotSegments(path: string): string {
|
|
269
|
+
const segments: string[] = []
|
|
270
|
+
|
|
271
|
+
for (const segment of path.split('/')) {
|
|
272
|
+
if (segment === '..') {
|
|
273
|
+
if (segments.length > 1) segments.pop()
|
|
274
|
+
} else if (segment !== '.') {
|
|
275
|
+
segments.push(segment)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const endsInDirectory = /\/\.{1,2}$/.test(path)
|
|
280
|
+
|
|
281
|
+
return segments.join('/') + (endsInDirectory ? '/' : '')
|
|
282
|
+
}
|