@noya-app/noya-multiplayer-react 0.1.61 → 0.1.63

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.
@@ -0,0 +1,202 @@
1
+ import { Asset, decodeSchema, encodeSchema } from "@noya-app/noya-schemas";
2
+ import { createHash, NoyaManager, TSchema } from "@noya-app/state-manager";
3
+ import { TinyZip } from "./zip/TinyZip";
4
+
5
+ export async function fetchAssetMap(
6
+ assets: Asset[]
7
+ ): Promise<Record<string, Uint8Array>> {
8
+ const res = await Promise.all(
9
+ assets.map(async (asset) => {
10
+ const url = asset.url;
11
+ const response = await fetch(url);
12
+ const data = await response.arrayBuffer();
13
+ return [asset.id, data];
14
+ })
15
+ );
16
+
17
+ return Object.fromEntries(res);
18
+ }
19
+
20
+ export async function exportAll(noyaManager: NoyaManager<any, any, any, any>) {
21
+ const { multiplayerStateManager, assetManager } = noyaManager;
22
+
23
+ const assetMap = await fetchAssetMap(assetManager.assets$.get());
24
+
25
+ return encodeAll({
26
+ state: multiplayerStateManager.optimisticState$.get(),
27
+ schema: multiplayerStateManager.schema,
28
+ assets: assetManager.assets$.get(),
29
+ assetMap,
30
+ });
31
+ }
32
+
33
+ export function encodeAll({
34
+ state,
35
+ schema,
36
+ assets,
37
+ assetMap,
38
+ }: {
39
+ state: unknown;
40
+ schema?: TSchema;
41
+ assets: Asset[];
42
+ assetMap: Record<string, Uint8Array>;
43
+ }) {
44
+ const zip = new TinyZip();
45
+
46
+ zip.addFile("state.json", JSON.stringify(state, null, 2));
47
+
48
+ if (schema) {
49
+ const encodedSchema = encodeSchema(schema);
50
+
51
+ zip.addFile("schema.json", JSON.stringify(encodedSchema, null, 2));
52
+ }
53
+
54
+ if (assets.length) {
55
+ zip.addFile("assets.json", JSON.stringify(assets, null, 2));
56
+ }
57
+
58
+ for (const [id, data] of Object.entries(assetMap)) {
59
+ zip.addFile(`assets/${id}`, data);
60
+ }
61
+
62
+ return zip.finish();
63
+ }
64
+
65
+ export async function importAll(
66
+ buffer: Uint8Array | ArrayBuffer,
67
+ noyaManager: NoyaManager<any, any, any, any>,
68
+ {
69
+ shouldAllowSchemaChange,
70
+ }: {
71
+ shouldAllowSchemaChange?: ({
72
+ oldSchema,
73
+ newSchema,
74
+ }: {
75
+ oldSchema: TSchema;
76
+ newSchema: TSchema;
77
+ }) => boolean;
78
+ } = {}
79
+ ) {
80
+ let { state, schema, assets, assetMap } = await decodeAll(buffer);
81
+
82
+ if (shouldAllowSchemaChange && noyaManager.options.schema && schema) {
83
+ const oldSchemaHash = createHash(noyaManager.options.schema);
84
+ const newSchemaHash = createHash(schema);
85
+
86
+ if (oldSchemaHash !== newSchemaHash) {
87
+ const shouldAllow = shouldAllowSchemaChange({
88
+ oldSchema: noyaManager.options.schema,
89
+ newSchema: schema,
90
+ });
91
+
92
+ if (!shouldAllow) {
93
+ throw new Error("Schema change not allowed");
94
+ }
95
+ }
96
+ }
97
+
98
+ if (assets.length) {
99
+ // Delete all existing assets
100
+ await Promise.all(
101
+ noyaManager.assetManager.assets$
102
+ .get()
103
+ .map((asset) => noyaManager.assetManager.delete(asset.id))
104
+ );
105
+
106
+ // Add new assets
107
+ const idPairs = await Promise.all(
108
+ assets.map(async (asset): Promise<[string, string]> => {
109
+ const newAsset = await noyaManager.assetManager.create({
110
+ data: assetMap[asset.id],
111
+ contentType: asset.contentType,
112
+ });
113
+
114
+ return [asset.id, newAsset.id];
115
+ })
116
+ );
117
+
118
+ const replacementMap = Object.fromEntries(idPairs);
119
+
120
+ state = replaceDeep(state, replacementMap);
121
+ }
122
+
123
+ // if (schema) {
124
+ // noyaManager.options.schema = schema;
125
+ // }
126
+
127
+ noyaManager.initialState = state;
128
+ noyaManager.forceInit();
129
+ }
130
+
131
+ export function decodeAll(buffer: Uint8Array | ArrayBuffer): {
132
+ state: unknown;
133
+ schema?: TSchema;
134
+ assets: Asset[];
135
+ assetMap: Record<string, Uint8Array>;
136
+ } {
137
+ const zip = TinyZip.extract(buffer);
138
+
139
+ const stateFile = zip["state.json"];
140
+ const schemaFile = zip["schema.json"];
141
+ const assetsFile = zip["assets.json"];
142
+
143
+ if (!stateFile) {
144
+ throw new Error("State file not found");
145
+ }
146
+
147
+ const state = JSON.parse(new TextDecoder().decode(stateFile));
148
+
149
+ let schema: TSchema | undefined;
150
+
151
+ if (schemaFile) {
152
+ const encodedSchema = JSON.parse(new TextDecoder().decode(schemaFile));
153
+ schema = decodeSchema(encodedSchema);
154
+ }
155
+
156
+ let assets: Asset[] = [];
157
+
158
+ let assetMap: Record<string, Uint8Array> = {};
159
+
160
+ if (assetsFile) {
161
+ assets = JSON.parse(new TextDecoder().decode(assetsFile));
162
+
163
+ for (const asset of assets) {
164
+ const data = zip[`assets/${asset.id}`];
165
+
166
+ if (!data) {
167
+ throw new Error(`Asset ${asset.id} not found`);
168
+ }
169
+
170
+ assetMap[asset.id] = data;
171
+ }
172
+ }
173
+
174
+ return { state, schema, assets, assetMap };
175
+ }
176
+
177
+ export function replaceDeep<T>(
178
+ obj: T,
179
+ replacementMap: Record<string, string>
180
+ ): T {
181
+ switch (typeof obj) {
182
+ case "object":
183
+ if (obj === null) {
184
+ return obj;
185
+ }
186
+
187
+ if (Array.isArray(obj)) {
188
+ return obj.map((item) => replaceDeep(item, replacementMap)) as any;
189
+ }
190
+
191
+ return Object.fromEntries(
192
+ Object.entries(obj).map(([key, value]) => [
193
+ key,
194
+ replaceDeep(value, replacementMap),
195
+ ])
196
+ ) as any;
197
+ case "string":
198
+ return (replacementMap[obj] ?? obj) as any;
199
+ default:
200
+ return obj;
201
+ }
202
+ }
@@ -0,0 +1,60 @@
1
+ import { ExtendedPathKey } from "@noya-app/state-manager";
2
+
3
+ export function pathToString(extendedPath: ExtendedPathKey[]) {
4
+ return extendedPath
5
+ .map((key) =>
6
+ typeof key === "object"
7
+ ? `:${ellipsis(key.id.toString(), 8, "middle")}`
8
+ : key
9
+ )
10
+ .map((key, index) =>
11
+ index === 0 || (typeof key === "string" && key.startsWith(":"))
12
+ ? key
13
+ : `.${key}`
14
+ )
15
+ .join("");
16
+ }
17
+
18
+ export type EllipsisPosition = "start" | "middle" | "end";
19
+
20
+ export function ellipsis(
21
+ str: string,
22
+ maxLength: number,
23
+ position: EllipsisPosition = "end"
24
+ ) {
25
+ if (str.length <= maxLength) return str;
26
+
27
+ switch (position) {
28
+ case "start":
29
+ return `…${str.slice(str.length - maxLength)}`;
30
+ case "middle": {
31
+ const halfLength = Math.floor(maxLength / 2);
32
+ return `${str.slice(0, halfLength)}…${str.slice(str.length - halfLength)}`;
33
+ }
34
+ case "end":
35
+ return `${str.slice(0, maxLength)}…`;
36
+ }
37
+ }
38
+
39
+ export function uploadFile() {
40
+ return new Promise<Blob>((resolve, reject) => {
41
+ const input = document.createElement("input");
42
+ input.type = "file";
43
+ input.onchange = () => {
44
+ const file = input.files?.[0];
45
+ if (file) {
46
+ const reader = new FileReader();
47
+ reader.onload = () => {
48
+ const buffer = reader.result as ArrayBuffer;
49
+ const blob = new Blob([buffer]);
50
+ resolve(blob);
51
+ };
52
+ reader.onerror = () => {
53
+ reject(new Error("Failed to read file"));
54
+ };
55
+ reader.readAsArrayBuffer(file);
56
+ }
57
+ };
58
+ input.click();
59
+ });
60
+ }