@mercuryworkshop/scramjet-controller 0.0.9 → 0.0.11

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/src/index.ts CHANGED
@@ -1,40 +1,55 @@
1
1
  import { type MethodsDefinition, RpcHelper } from "@mercuryworkshop/rpc";
2
- import type * as ScramjetGlobal from "@mercuryworkshop/scramjet";
3
-
4
- declare const $scramjet: typeof ScramjetGlobal;
5
-
6
- import {
7
- type TransportToController,
8
- type Controllerbound,
9
- type ControllerToTransport,
10
- type SWbound,
11
- type WebSocketMessage,
12
- } from "./types";
13
2
  import {
14
- BareCompatibleClient,
15
3
  BareResponse,
16
4
  type ProxyTransport,
17
5
  } from "@mercuryworkshop/proxy-transports";
6
+ import type * as ScramjetGlobal from "@mercuryworkshop/scramjet";
7
+ declare const $scramjet: typeof ScramjetGlobal;
8
+ import { deepmerge } from "@fastify/deepmerge";
9
+ import { CONTROLLERFRAME } from "./symbols";
10
+ import type {
11
+ FrameInitHooks,
12
+ SerializedCookieSyncEntry,
13
+ TransportToController,
14
+ Controllerbound,
15
+ ControllerToTransport,
16
+ SWbound,
17
+ WebSocketMessage,
18
+ FrameErrorHooks,
19
+ } from "./types";
18
20
 
19
- const cookieJar = new $scramjet.CookieJar();
21
+ export { HttpCachePlugin, type HttpCachePluginOptions } from "./cache";
20
22
 
21
- type Config = {
22
- wasmPath: string;
23
- injectPath: string;
23
+ export type Config = {
24
+ prefix: string;
24
25
  scramjetPath: string;
26
+ injectPath: string;
27
+ wasmPath: string;
25
28
  virtualWasmPath: string;
26
- prefix: string;
29
+ codec: Record<"encode" | "decode", (input: string) => string>;
27
30
  };
28
31
 
29
32
  export const config: Config = {
30
33
  prefix: "/~/sj/",
31
- virtualWasmPath: "scramjet.wasm.js",
32
- injectPath: "/controller/controller.inject.js",
33
34
  scramjetPath: "/scramjet/scramjet.js",
35
+ injectPath: "/controller/controller.inject.js",
34
36
  wasmPath: "/scramjet/scramjet.wasm",
37
+ virtualWasmPath: "scramjet.wasm.js",
38
+ codec: {
39
+ encode: (url: string) => {
40
+ if (!url) return url;
41
+
42
+ return encodeURIComponent(url);
43
+ },
44
+ decode: (url: string) => {
45
+ if (!url) return url;
46
+
47
+ return decodeURIComponent(url);
48
+ },
49
+ },
35
50
  };
36
51
 
37
- const cfg = {
52
+ const scramjetConfig: Partial<ScramjetGlobal.ScramjetConfig> = {
38
53
  flags: {
39
54
  ...$scramjet.defaultConfig.flags,
40
55
  allowFailedIntercepts: true,
@@ -42,69 +57,197 @@ const cfg = {
42
57
  maskedfiles: ["inject.js", "scramjet.wasm.js"],
43
58
  };
44
59
 
45
- const frames: Record<string, Frame> = {};
60
+ type PersistedCookieState = {
61
+ updatedAt: number;
62
+ cookies: string;
63
+ };
46
64
 
47
- let wasmPayload: string | null = null;
65
+ const COOKIE_DB_NAME = "__scramjet_controller";
66
+ const COOKIE_STORE_NAME = "state";
67
+ const COOKIE_STATE_KEY = "cookies";
68
+ const BROADCASTCHANNEL_NAME = "__scramjet_controller_channel";
69
+
70
+ let cookieDbPromise: Promise<IDBDatabase> | null = null;
71
+
72
+ function parsePersistedCookieState(
73
+ value: unknown
74
+ ): PersistedCookieState | null {
75
+ if (
76
+ typeof value !== "object" ||
77
+ value === null ||
78
+ typeof (value as PersistedCookieState).updatedAt !== "number" ||
79
+ !Number.isFinite((value as PersistedCookieState).updatedAt) ||
80
+ typeof (value as PersistedCookieState).cookies !== "string"
81
+ ) {
82
+ return null;
83
+ }
48
84
 
49
- function makeId(): string {
50
- return Math.random().toString(36).substring(2, 10);
85
+ return value as PersistedCookieState;
51
86
  }
52
87
 
53
- const codecEncode = (url: string) => {
54
- if (!url) return url;
88
+ function requestToPromise<T>(request: IDBRequest<T>): Promise<T> {
89
+ return new Promise<T>((resolve, reject) => {
90
+ request.onsuccess = () => resolve(request.result);
91
+ request.onerror = () =>
92
+ reject(request.error ?? new Error("IndexedDB request failed"));
93
+ });
94
+ }
55
95
 
56
- return encodeURIComponent(url);
57
- };
96
+ function transactionToPromise(transaction: IDBTransaction): Promise<void> {
97
+ return new Promise<void>((resolve, reject) => {
98
+ transaction.oncomplete = () => resolve();
99
+ transaction.onabort = () =>
100
+ reject(transaction.error ?? new Error("IndexedDB transaction aborted"));
101
+ transaction.onerror = () =>
102
+ reject(transaction.error ?? new Error("IndexedDB transaction failed"));
103
+ });
104
+ }
58
105
 
59
- const codecDecode = (url: string) => {
60
- if (!url) return url;
106
+ function openCookieDatabase(): Promise<IDBDatabase> {
107
+ if (cookieDbPromise) {
108
+ return cookieDbPromise;
109
+ }
61
110
 
62
- return decodeURIComponent(url);
63
- };
111
+ cookieDbPromise = new Promise<IDBDatabase>((resolve, reject) => {
112
+ const request = indexedDB.open(COOKIE_DB_NAME, 1);
113
+ request.onupgradeneeded = () => {
114
+ const db = request.result;
115
+ if (!db.objectStoreNames.contains(COOKIE_STORE_NAME)) {
116
+ db.createObjectStore(COOKIE_STORE_NAME);
117
+ }
118
+ };
119
+ request.onsuccess = () => resolve(request.result);
120
+ request.onerror = () =>
121
+ reject(request.error ?? new Error("Failed to open cookie database"));
122
+ });
64
123
 
65
- type ControllerInit = {
66
- serviceworker: ServiceWorker;
67
- transport: ProxyTransport;
68
- };
124
+ return cookieDbPromise;
125
+ }
69
126
 
70
- let wasmAlreadyFetched = false;
127
+ async function readCookieState(): Promise<PersistedCookieState | null> {
128
+ try {
129
+ const db = await openCookieDatabase();
130
+ const transaction = db.transaction(COOKIE_STORE_NAME, "readonly");
131
+ const store = transaction.objectStore(COOKIE_STORE_NAME);
132
+ const value = await requestToPromise(store.get(COOKIE_STATE_KEY));
133
+ await transactionToPromise(transaction);
134
+ return parsePersistedCookieState(value);
135
+ } catch (error) {
136
+ console.error("Failed to read persisted controller cookies:", error);
137
+ return null;
138
+ }
139
+ }
71
140
 
72
- async function loadScramjetWasm() {
73
- if (wasmAlreadyFetched) {
74
- return;
141
+ async function writeCookieState(
142
+ cookies: string,
143
+ currentUpdatedAt: number
144
+ ): Promise<number> {
145
+ try {
146
+ const db = await openCookieDatabase();
147
+ const transaction = db.transaction(COOKIE_STORE_NAME, "readwrite");
148
+ const store = transaction.objectStore(COOKIE_STORE_NAME);
149
+ const existing = parsePersistedCookieState(
150
+ await requestToPromise(store.get(COOKIE_STATE_KEY))
151
+ );
152
+ const updatedAt = Math.max(
153
+ Date.now(),
154
+ currentUpdatedAt + 1,
155
+ (existing?.updatedAt ?? 0) + 1
156
+ );
157
+ const state: PersistedCookieState = {
158
+ updatedAt,
159
+ cookies,
160
+ };
161
+ store.put(state, COOKIE_STATE_KEY);
162
+ await transactionToPromise(transaction);
163
+ return updatedAt;
164
+ } catch (error) {
165
+ console.error("Failed to persist controller cookies:", error);
166
+ return currentUpdatedAt;
75
167
  }
168
+ }
76
169
 
77
- let resp = await fetch(config.wasmPath);
78
- $scramjet.setWasm(await resp.arrayBuffer());
79
- wasmAlreadyFetched = true;
170
+ function makeId(): string {
171
+ return Math.random().toString(36).substring(2, 10);
80
172
  }
81
173
 
174
+ const deepMerge = deepmerge();
175
+
176
+ type ControllerInit = {
177
+ serviceworker: ServiceWorker;
178
+ transport: ProxyTransport;
179
+ config?: Partial<Config>;
180
+ scramjetConfig?: Partial<ScramjetGlobal.ScramjetConfig>;
181
+ };
182
+
82
183
  export class Controller {
83
184
  id: string;
185
+ config: Config;
186
+ scramjetConfig: ScramjetGlobal.ScramjetConfig;
84
187
  prefix: string;
85
- frames: Frame[] = [];
86
188
  cookieJar = new $scramjet.CookieJar();
189
+ frames: Frame[] = [];
190
+ serviceWorkerController: ServiceWorker;
191
+ guardServiceWorkerRevive = true;
87
192
 
88
- rpc: RpcHelper<Controllerbound, SWbound>;
89
- private ready: Promise<[void, void]>;
193
+ private ready: Promise<void>;
90
194
  private readyResolve!: () => void;
91
195
  public isReady: boolean = false;
196
+ rpc: RpcHelper<Controllerbound, SWbound>;
197
+ private port: MessagePort | null = null;
92
198
 
93
199
  transport: ProxyTransport;
200
+ private cookieUpdatedAt = 0;
201
+ private cookieSyncPromise: Promise<void> | null = null;
202
+ private cookieSyncDirty = true;
203
+ private cookieSyncChannel = new BroadcastChannel(BROADCASTCHANNEL_NAME);
204
+
205
+ private wasmAlreadyFetched = false;
206
+ private wasmPayload: string | null = null;
207
+ private onTabChannelMessage: (e: MessageEvent) => void = (e) => {
208
+ this.rpc.recieve(e.data);
209
+ };
210
+ private onCookieSyncMessage = (event: MessageEvent) => {
211
+ const updatedAt =
212
+ typeof event.data === "object" && event.data !== null
213
+ ? (event.data as { updatedAt?: unknown }).updatedAt
214
+ : undefined;
215
+ if (typeof updatedAt !== "number" || updatedAt <= this.cookieUpdatedAt) {
216
+ return;
217
+ }
218
+
219
+ this.cookieSyncDirty = true;
220
+ void this.loadSavedCookies();
221
+ };
222
+
223
+ private async loadScramjetWasm() {
224
+ if (this.wasmAlreadyFetched) {
225
+ return;
226
+ }
227
+
228
+ const resp = await fetch(this.config.wasmPath);
229
+ $scramjet.setWasm(await resp.arrayBuffer());
230
+ this.wasmAlreadyFetched = true;
231
+ }
94
232
 
95
233
  private methods: MethodsDefinition<Controllerbound> = {
96
234
  ready: async () => {
97
235
  this.readyResolve();
236
+ setTimeout(() => {
237
+ this.guardServiceWorkerRevive = false;
238
+ }, 5000);
98
239
  },
99
240
  request: async (data) => {
241
+ const path = new URL(data.rawUrl).pathname;
242
+ const frame = this.frames.find((f) => path.startsWith(f.prefix));
243
+ if (!frame) throw new Error("No frame found for request");
100
244
  try {
101
- let path = new URL(data.rawUrl).pathname;
102
- const frame = this.frames.find((f) => path.startsWith(f.prefix));
103
- if (!frame) throw new Error("No frame found for request");
245
+ // doesn't actually *load* every request, but hold up requests until the promise finishes
246
+ await this.loadSavedCookies();
104
247
 
105
- if (path === frame.prefix + config.virtualWasmPath) {
106
- if (!wasmPayload) {
107
- const resp = await fetch(config.wasmPath);
248
+ if (path === frame.prefix + this.config.virtualWasmPath) {
249
+ if (!this.wasmPayload) {
250
+ const resp = await fetch(this.config.wasmPath);
108
251
  const buf = await resp.arrayBuffer();
109
252
  const b64 = btoa(
110
253
  new Uint8Array(buf)
@@ -115,16 +258,12 @@ export class Controller {
115
258
  .join("")
116
259
  );
117
260
 
118
- let payload = "";
119
- payload +=
120
- "console.warn('WTF'); if ('document' in self && document.currentScript) { document.currentScript.remove(); }\n";
121
- payload += `self.WASM = '${b64}';`;
122
- wasmPayload = payload;
261
+ this.wasmPayload = `self.WASM = '${b64}';`;
123
262
  }
124
263
 
125
264
  return [
126
265
  {
127
- body: wasmPayload,
266
+ body: this.wasmPayload,
128
267
  status: 200,
129
268
  statusText: "OK",
130
269
  headers: [["Content-Type", "application/javascript"]],
@@ -133,7 +272,7 @@ export class Controller {
133
272
  ];
134
273
  }
135
274
 
136
- let sjheaders = $scramjet.ScramjetHeaders.fromRawHeaders(
275
+ const sjheaders = $scramjet.ScramjetHeaders.fromRawHeaders(
137
276
  data.initialHeaders
138
277
  );
139
278
 
@@ -143,12 +282,14 @@ export class Controller {
143
282
  ? new URL(data.rawClientUrl)
144
283
  : undefined,
145
284
  rawUrl: new URL(data.rawUrl),
146
- destination: data.destination,
285
+ rawReferrer: data.rawReferrer,
286
+ rawDestination: data.destination,
147
287
  method: data.method,
148
288
  mode: data.mode,
149
289
  referrer: data.referrer,
150
290
  body: data.body,
151
291
  cache: data.cache,
292
+ clientId: data.clientId,
152
293
  });
153
294
 
154
295
  return [
@@ -164,7 +305,24 @@ export class Controller {
164
305
  : [],
165
306
  ];
166
307
  } catch (e) {
167
- console.error("Error in controller request handler:", e);
308
+ const reqcontext: typeof frame.hooks.error.request.context = {
309
+ rawrequest: data,
310
+ };
311
+ const reqprops: typeof frame.hooks.error.request.props = {
312
+ setResponse: undefined,
313
+ suppressError: false,
314
+ };
315
+ await $scramjet.Tap.dispatch(
316
+ frame.hooks.error.request,
317
+ reqcontext,
318
+ reqprops
319
+ );
320
+ if (!reqprops.suppressError) {
321
+ console.error("Error in controller request handler:", e);
322
+ }
323
+ if (reqprops.setResponse) {
324
+ return [reqprops.setResponse, []];
325
+ }
168
326
  throw e;
169
327
  }
170
328
  },
@@ -172,7 +330,7 @@ export class Controller {
172
330
  const rpc = new RpcHelper<TransportToController, ControllerToTransport>(
173
331
  {
174
332
  request: async ({ remote, method, body, headers }) => {
175
- let response = await this.transport.request(
333
+ const response = await this.transport.request(
176
334
  new URL(remote),
177
335
  method,
178
336
  body,
@@ -181,9 +339,18 @@ export class Controller {
181
339
  );
182
340
  return [response, [response.body]];
183
341
  },
342
+ sendSetCookie: async ({ cookies, options }) => {
343
+ await this.loadSavedCookies(true);
344
+ if (options?.clear) {
345
+ this.cookieJar.clear();
346
+ }
347
+ this.applyCookieSyncEntries(cookies);
348
+ await this.persistCookies();
349
+ await this.propagateCookieSync(cookies, options);
350
+ },
184
351
  connect: async ({ url, protocols, requestHeaders, port }) => {
185
352
  let resolve: (arg: TransportToController["connect"][1]) => void;
186
- let promise = new Promise<TransportToController["connect"][1]>(
353
+ const promise = new Promise<TransportToController["connect"][1]>(
187
354
  (res) => (resolve = res)
188
355
  );
189
356
  const [send, close] = this.transport.connect(
@@ -251,38 +418,103 @@ export class Controller {
251
418
  };
252
419
  rpc.call("ready", undefined, []);
253
420
  },
254
- sendSetCookie: async ({ url, cookie }) => {},
255
421
  };
256
422
 
257
423
  constructor(public init: ControllerInit) {
258
- this.transport = init.transport;
259
424
  this.id = makeId();
260
- this.prefix = config.prefix + this.id + "/";
425
+ this.config = deepMerge(config, init.config || {}) as Config;
426
+ this.scramjetConfig = deepMerge(scramjetConfig, $scramjet.defaultConfig);
427
+ this.scramjetConfig = deepMerge(
428
+ this.scramjetConfig,
429
+ init.scramjetConfig || {}
430
+ ) as ScramjetGlobal.ScramjetConfig;
431
+ this.prefix = this.config.prefix + this.id + "/";
432
+ this.serviceWorkerController = init.serviceworker;
261
433
 
262
434
  this.ready = Promise.all([
263
435
  new Promise<void>((resolve) => {
264
436
  this.readyResolve = resolve;
265
437
  }),
266
- loadScramjetWasm(),
267
- ]);
438
+ this.loadScramjetWasm(),
439
+ this.loadSavedCookies(true),
440
+ ]).then(() => undefined);
268
441
 
269
- let channel = new MessageChannel();
270
442
  this.rpc = new RpcHelper<Controllerbound, SWbound>(
271
443
  this.methods,
272
444
  "tabchannel-" + this.id,
273
445
  (data, transfer) => {
274
- channel.port1.postMessage(data, transfer);
446
+ if (!this.port) {
447
+ throw new Error("Port not found");
448
+ }
449
+ this.port.postMessage(data, transfer);
275
450
  }
276
451
  );
277
- channel.port1.addEventListener("message", (e) => {
278
- this.rpc.recieve(e.data);
452
+ this.transport = init.transport;
453
+
454
+ this.cookieSyncChannel.addEventListener(
455
+ "message",
456
+ this.onCookieSyncMessage
457
+ );
458
+ this.setupMessagePort();
459
+
460
+ navigator.serviceWorker.addEventListener("message", (e) => {
461
+ if (
462
+ e.data?.$controller$setCookie &&
463
+ typeof e.data.$controller$setCookie === "object"
464
+ ) {
465
+ const payload = e.data.$controller$setCookie as {
466
+ cookies?: SerializedCookieSyncEntry[];
467
+ options?: ScramjetGlobal.CookieSyncOptions;
468
+ id?: string;
469
+ };
470
+
471
+ if (payload.options?.clear) {
472
+ this.cookieJar.clear();
473
+ }
474
+ this.applyCookieSyncEntries(payload.cookies);
475
+
476
+ if (typeof payload.id === "string") {
477
+ this.serviceWorkerController.postMessage({
478
+ $sw$setCookieDone: {
479
+ id: payload.id,
480
+ },
481
+ });
482
+ }
483
+
484
+ return;
485
+ }
486
+
487
+ if (e.data.$controller$swrevive) {
488
+ // if we just spawned the service worker, it will send this even though it's not actually dead
489
+ // TODO: pretty jank, fix at some point
490
+ if (this.guardServiceWorkerRevive) {
491
+ return;
492
+ }
493
+ this.setupMessagePort();
494
+ }
279
495
  });
280
- channel.port1.start();
496
+ }
281
497
 
282
- init.serviceworker.postMessage(
498
+ private setupMessagePort() {
499
+ if (this.port) {
500
+ this.port.removeEventListener("message", this.onTabChannelMessage);
501
+ try {
502
+ this.port.close();
503
+ } catch {
504
+ // ignore
505
+ }
506
+ this.port = null;
507
+ }
508
+
509
+ const channel = new MessageChannel();
510
+ this.port = channel.port1;
511
+ this.port.addEventListener("message", this.onTabChannelMessage);
512
+ this.port.start();
513
+
514
+ this.serviceWorkerController.postMessage(
283
515
  {
284
516
  $controller$init: {
285
- prefix: config.prefix + this.id,
517
+ prefix: this.prefix,
286
518
  id: this.id,
287
519
  },
288
520
  },
@@ -290,6 +522,84 @@ export class Controller {
290
522
  );
291
523
  }
292
524
 
525
+ // TODO: should this be a method on the cookie jar?
526
+ private applyCookieSyncEntries(
527
+ cookies: SerializedCookieSyncEntry[] | undefined
528
+ ) {
529
+ if (!Array.isArray(cookies)) {
530
+ return;
531
+ }
532
+
533
+ for (const entry of cookies) {
534
+ if (typeof entry?.url !== "string" || typeof entry.cookie !== "string") {
535
+ continue;
536
+ }
537
+
538
+ this.cookieJar.setCookies(entry.cookie, new URL(entry.url));
539
+ }
540
+ }
541
+
542
+ async propagateCookieSync(
543
+ cookies: SerializedCookieSyncEntry[],
544
+ options: ScramjetGlobal.CookieSyncOptions = {}
545
+ ): Promise<void> {
546
+ if (!this.port) {
547
+ return;
548
+ }
549
+
550
+ await this.rpc.call("sendSetCookie", {
551
+ cookies,
552
+ options,
553
+ });
554
+ }
555
+
556
+ private async loadSavedCookies(force = false): Promise<void> {
557
+ if (!force && !this.cookieSyncDirty) {
558
+ return;
559
+ }
560
+
561
+ if (this.cookieSyncPromise) {
562
+ return this.cookieSyncPromise;
563
+ }
564
+
565
+ this.cookieSyncPromise = (async () => {
566
+ const persisted = await readCookieState();
567
+ if (persisted && persisted.updatedAt > this.cookieUpdatedAt) {
568
+ this.cookieJar.load(persisted.cookies);
569
+ this.cookieUpdatedAt = persisted.updatedAt;
570
+ }
571
+ this.cookieSyncDirty = false;
572
+ })().finally(() => {
573
+ this.cookieSyncPromise = null;
574
+ });
575
+
576
+ return this.cookieSyncPromise;
577
+ }
578
+
579
+ async persistCookies(): Promise<void> {
580
+ const updatedAt = await writeCookieState(
581
+ this.cookieJar.dump(),
582
+ this.cookieUpdatedAt
583
+ );
584
+ if (updatedAt <= this.cookieUpdatedAt) {
585
+ return;
586
+ }
587
+
588
+ this.cookieUpdatedAt = updatedAt;
589
+ this.cookieSyncDirty = false;
590
+ this.cookieSyncChannel.postMessage({
591
+ updatedAt,
592
+ });
593
+ }
594
+
595
+ setTransport(transport: ProxyTransport) {
596
+ this.transport = transport;
597
+ for (const frame of this.frames) {
598
+ frame.controller.transport = transport;
599
+ frame.fetchHandler.client.transport = transport;
600
+ }
601
+ }
602
+
293
603
  createFrame(element?: HTMLIFrameElement): Frame {
294
604
  if (!this.ready) {
295
605
  throw new Error(
@@ -302,107 +612,137 @@ export class Controller {
302
612
  return frame;
303
613
  }
304
614
 
305
- wait(): Promise<void> {
306
- return this.ready;
615
+ async wait(): Promise<void> {
616
+ await this.ready;
307
617
  }
308
618
  }
309
619
 
620
+ function base64Encode(text: string) {
621
+ return btoa(
622
+ new TextEncoder()
623
+ .encode(text)
624
+ .reduce(
625
+ (data, byte) => (data.push(String.fromCharCode(byte)), data),
626
+ [] as any
627
+ )
628
+ .join("")
629
+ );
630
+ }
631
+
310
632
  function yieldGetInjectScripts(
311
- cookieJar: ScramjetGlobal.CookieJar,
312
633
  config: Config,
313
634
  sjconfig: ScramjetGlobal.ScramjetConfig,
314
- prefix: URL
635
+ prefix: URL,
636
+ cookieJar: ScramjetGlobal.CookieJar,
637
+ codecEncode: (input: string) => string,
638
+ codecDecode: (input: string) => string
315
639
  ) {
316
- let getInjectScripts: ScramjetGlobal.ScramjetInterface["getInjectScripts"] = (
317
- meta,
318
- handler,
319
- script
320
- ) => {
321
- return [
322
- script(config.scramjetPath),
323
- script(config.injectPath),
324
- script(prefix.href + config.virtualWasmPath),
325
- script(
326
- "data:text/javascript;base64," +
327
- btoa(`
328
- document.currentScript.remove();
640
+ const getInjectScripts: ScramjetGlobal.ScramjetInterface["getInjectScripts"] =
641
+ (meta, handler, htmlcontext, script) => {
642
+ function base64Encode(text: string) {
643
+ return btoa(
644
+ new TextEncoder()
645
+ .encode(text)
646
+ .reduce(
647
+ (data, byte) => (data.push(String.fromCharCode(byte)), data),
648
+ [] as any
649
+ )
650
+ .join("")
651
+ );
652
+ }
653
+ return [
654
+ script(config.scramjetPath),
655
+ script(prefix.href + config.virtualWasmPath),
656
+ script(config.injectPath),
657
+ script(
658
+ "data:text/javascript;charset=utf-8;base64," +
659
+ base64Encode(`
660
+ document.querySelectorAll("script[scramjet-injected]").forEach(script => script.remove());
329
661
  $scramjetController.load({
330
662
  config: ${JSON.stringify(config)},
331
663
  sjconfig: ${JSON.stringify(sjconfig)},
332
- cookies: ${cookieJar.dump()},
333
664
  prefix: new URL("${prefix.href}"),
665
+ cookies: ${JSON.stringify(cookieJar.dump())},
334
666
  yieldGetInjectScripts: ${yieldGetInjectScripts.toString()},
335
667
  codecEncode: ${codecEncode.toString()},
336
668
  codecDecode: ${codecDecode.toString()},
669
+ initHeaders: ${JSON.stringify(htmlcontext.headers ?? [])},
670
+ history: ${JSON.stringify(htmlcontext.history ?? [])},
337
671
  })
338
672
  `)
339
- ),
340
- ];
341
- };
673
+ ),
674
+ ];
675
+ };
342
676
  return getInjectScripts;
343
677
  }
344
678
 
345
- class Frame {
346
- fetchHandler: ScramjetGlobal.ScramjetFetchHandler;
679
+ export class Frame {
347
680
  id: string;
348
681
  prefix: string;
682
+ fetchHandler: ScramjetGlobal.ScramjetFetchHandler;
683
+ hooks: {
684
+ fetch: ScramjetGlobal.FetchHooks;
685
+ init: FrameInitHooks;
686
+ error: FrameErrorHooks;
687
+ };
349
688
 
350
689
  get context(): ScramjetGlobal.ScramjetContext {
351
- let sjcfg = {
352
- ...$scramjet.defaultConfig,
353
- ...cfg,
354
- };
355
690
  return {
356
- cookieJar,
691
+ config: this.controller.scramjetConfig,
357
692
  prefix: new URL(this.prefix, location.href),
358
- config: sjcfg,
693
+ cookieJar: this.controller.cookieJar,
359
694
  interface: {
360
695
  getInjectScripts: yieldGetInjectScripts(
696
+ this.controller.config,
697
+ this.controller.scramjetConfig,
698
+ new URL(this.prefix, location.href),
361
699
  this.controller.cookieJar,
362
- config,
363
- { ...$scramjet.defaultConfig, ...cfg },
364
- new URL(this.prefix, location.href)
700
+ this.controller.config.codec.encode,
701
+ this.controller.config.codec.decode
365
702
  ),
366
703
  getWorkerInjectScripts: (meta, type, script) => {
367
704
  let str = "";
368
705
 
369
- str += script(config.scramjetPath);
370
- str += script(this.prefix + config.virtualWasmPath);
371
- str += `
706
+ str += script(this.controller.config.scramjetPath);
707
+ str += script(this.prefix + this.controller.config.virtualWasmPath);
708
+ str += script(
709
+ "data:text/javascript;charset=utf-8;base64," +
710
+ base64Encode(`
372
711
  (()=>{
373
712
  const { ScramjetClient, CookieJar, setWasm } = $scramjet;
374
713
 
375
714
  setWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));
376
715
  delete self.WASM;
377
716
 
378
- const sjconfig = ${JSON.stringify(sjcfg)};
717
+ const sjconfig = ${JSON.stringify(this.controller.scramjetConfig)};
379
718
  const prefix = new URL("${this.prefix}", location.href);
380
719
 
381
720
  const context = {
721
+ config: sjconfig,
722
+ prefix,
382
723
  interface: {
383
- codecEncode: ${codecEncode.toString()},
384
- codecDecode: ${codecDecode.toString()},
724
+ codecEncode: ${this.controller.config.codec.encode.toString()},
725
+ codecDecode: ${this.controller.config.codec.decode.toString()},
385
726
  },
386
- prefix,
387
- config: sjconfig
388
727
  };
389
728
 
390
729
  const client = new ScramjetClient(globalThis, {
391
730
  context,
392
731
  transport: null,
393
732
  shouldPassthroughWebsocket: (url) => {
394
- return url === "wss://anura.pro/";
733
+ return false;
395
734
  }
396
735
  });
397
736
 
398
737
  client.hook();
399
738
  })();
400
- `;
739
+ `)
740
+ );
401
741
 
402
742
  return str;
403
743
  },
404
- codecEncode,
405
- codecDecode,
744
+ codecEncode: this.controller.config.codec.encode,
745
+ codecDecode: this.controller.config.codec.decode,
406
746
  },
407
747
  };
408
748
  }
@@ -418,7 +758,16 @@ class Frame {
418
758
  crossOriginIsolated: self.crossOriginIsolated,
419
759
  context: this.context,
420
760
  transport: controller.transport,
421
- async sendSetCookie(url, cookie) {},
761
+ async sendSetCookie(cookies, options) {
762
+ await controller.persistCookies();
763
+ await controller.propagateCookieSync(
764
+ cookies.map(({ url, cookie }) => ({
765
+ url: url.href,
766
+ cookie,
767
+ })),
768
+ options
769
+ );
770
+ },
422
771
  async fetchBlobUrl(url) {
423
772
  return BareResponse.fromNativeResponse(await fetch(url));
424
773
  },
@@ -426,11 +775,33 @@ class Frame {
426
775
  return BareResponse.fromNativeResponse(await fetch(url));
427
776
  },
428
777
  });
778
+
779
+ this.hooks = {
780
+ fetch: this.fetchHandler.hooks.fetch,
781
+ init: $scramjet.Tap.create<FrameInitHooks>(),
782
+ error: $scramjet.Tap.create<FrameErrorHooks>(),
783
+ };
784
+
785
+ element[CONTROLLERFRAME] = this;
786
+ }
787
+
788
+ back() {
789
+ this.element.contentWindow?.history.back();
790
+ }
791
+
792
+ forward() {
793
+ this.element.contentWindow?.history.forward();
794
+ }
795
+
796
+ reload() {
797
+ this.element.contentWindow?.location.reload();
429
798
  }
430
799
 
431
800
  go(url: string) {
432
801
  const encoded = $scramjet.rewriteUrl(url, this.context, {
802
+ //@ts-expect-error
433
803
  origin: new URL(location.href),
804
+ //@ts-expect-error
434
805
  base: new URL(location.href),
435
806
  });
436
807
  this.element.src = encoded;