Experiment to rebuild Diffuse using web applets.
1import * as Uint8 from "uint8arrays";
2import * as Comlink from "comlink";
3import { xxh32 } from "xxh32";
4import { getTransferables } from "@okikio/transferables";
5
6import type { Track } from "@applets/core/types";
7
8// export { SharedWorkerPolyfill as SharedWorker } from "@okikio/sharedworker";
9export const SharedWorker = globalThis.SharedWorker;
10
11////////////////////////////////////////////
12// 🌳
13////////////////////////////////////////////
14
15export type WorkerActions = {
16 perform: ReturnType<typeof handleWorkerActions>;
17};
18
19////////////////////////////////////////////
20// 🛠️
21////////////////////////////////////////////
22
23export function arrayShuffle<T>(array: Array<T>): Array<T> {
24 if (array.length === 0) {
25 return [];
26 }
27
28 array = [...array];
29
30 for (let index = array.length - 1; index > 0; index--) {
31 const randArr = crypto.getRandomValues(new Uint32Array(1));
32 const randVal = randArr[0] / 2 ** 32;
33 const newIndex = Math.floor(randVal * (index + 1));
34 [array[index], array[newIndex]] = [array[newIndex], array[index]];
35 }
36
37 return array;
38}
39
40export function cleanUndefinedValuesForTracks(tracks: Track[]): Track[] {
41 return tracks.map((track) => {
42 const t = { ...track };
43
44 if (t.tags) {
45 if ("album" in t.tags && t.tags.album === undefined) delete t.tags.album;
46 if ("artist" in t.tags && t.tags.artist === undefined) delete t.tags.artist;
47 if ("genre" in t.tags && t.tags.genre === undefined) delete t.tags.genre;
48 if ("year" in t.tags && t.tags.year === undefined) delete t.tags.year;
49
50 if ("of" in t.tags.disc && t.tags.disc.of === undefined) delete t.tags.disc.of;
51 if ("of" in t.tags.track && t.tags.track.of === undefined) delete t.tags.track.of;
52 }
53
54 return t;
55 });
56}
57
58export function comparable(value: unknown) {
59 return xxh32(JSON.stringify(value));
60}
61
62export function endpoint<T extends Record<string, any> = WorkerActions>(ini: Comlink.Endpoint) {
63 const e = Comlink.wrap<T>(ini);
64 if ("start" in ini && typeof ini.start === "function") ini.start();
65 return e;
66}
67
68export function expose<A extends Record<string, any>>(actions: A): A {
69 if (globalThis.SharedWorkerGlobalScope && self instanceof SharedWorkerGlobalScope) {
70 self.onconnect = (event: MessageEvent) => {
71 const port = event.ports[0];
72 Comlink.expose(actions, port);
73 port.start();
74 };
75
76 (self as any).connected = true;
77 } else {
78 Comlink.expose(actions, self);
79 }
80
81 return actions;
82}
83
84export function groupTracksPerScheme(
85 tracks: Track[],
86 initial: Record<string, Track[]> = {},
87): Record<string, Track[]> {
88 return tracks.reduce((acc: Record<string, Track[]>, track: Track) => {
89 const scheme = track.uri.split(":", 1)[0];
90 return { ...acc, [scheme]: [...(acc[scheme] || []), track] };
91 }, initial);
92}
93
94export function inIframe() {
95 return window.self !== window.top;
96}
97
98export function isPrimitive(test: unknown) {
99 return test !== Object(test);
100}
101
102export function jsonDecode<T>(a: any): T {
103 return JSON.parse(new TextDecoder().decode(a));
104}
105
106export function jsonEncode<T>(a: T): Uint8Array {
107 return new TextEncoder().encode(JSON.stringify(a));
108}
109
110export function provide<A extends Record<string, any>>(actions: A) {
111 return expose({
112 perform: handleWorkerActions(actions),
113 });
114}
115
116export async function trackArtworkCacheId(track: Track): Promise<string> {
117 return await crypto.subtle
118 .digest("SHA-256", new TextEncoder().encode(track.uri))
119 .then((a) => Uint8.toString(new Uint8Array(a), "base64url"));
120}
121
122export function transfer<T = unknown>(a: T) {
123 const b = getTransferables(a);
124 return Comlink.transfer(a, b);
125}
126
127// PRIVATE
128
129function handleWorkerActions<A extends Record<string, any>>(actions: A) {
130 async function handleAction(
131 port: MessagePort,
132 action: {
133 type: "action";
134 id: string;
135 actionId: string;
136 arguments: any;
137 },
138 ) {
139 const result = await actions[action.actionId]?.(action.arguments);
140 return postMessage(port, action.id, result);
141 }
142
143 function postMessage<T>(port: MessagePort, id: string, result: T) {
144 port.postMessage(
145 {
146 type: "actioncomplete",
147 id,
148 result,
149 },
150 {
151 transfer: getTransferables(result),
152 },
153 );
154 }
155
156 return (port: MessagePort) => {
157 port.onmessage = async (message) => {
158 switch (message.data?.type) {
159 case "action":
160 return handleAction(port, message.data);
161 }
162 };
163 };
164}