@swf2es/web 0.0.0-stage → 0.1.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.
Files changed (58) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +43 -2
  3. package/dist/air-files.d.ts +40 -0
  4. package/dist/air-files.d.ts.map +1 -0
  5. package/dist/air-files.js +304 -0
  6. package/dist/air-files.js.map +1 -0
  7. package/dist/air-items.d.ts +28 -0
  8. package/dist/air-items.d.ts.map +1 -0
  9. package/dist/air-items.js +186 -0
  10. package/dist/air-items.js.map +1 -0
  11. package/dist/air.d.ts +81 -0
  12. package/dist/air.d.ts.map +1 -0
  13. package/dist/air.js +409 -0
  14. package/dist/air.js.map +1 -0
  15. package/dist/config.d.ts +123 -0
  16. package/dist/config.d.ts.map +1 -0
  17. package/dist/config.js +127 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/element.d.ts +80 -0
  20. package/dist/element.d.ts.map +1 -0
  21. package/dist/element.js +725 -0
  22. package/dist/element.js.map +1 -0
  23. package/dist/external.d.ts +49 -0
  24. package/dist/external.d.ts.map +1 -0
  25. package/dist/external.js +268 -0
  26. package/dist/external.js.map +1 -0
  27. package/dist/index.d.ts +9 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +18 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/layout.d.ts +47 -0
  32. package/dist/layout.d.ts.map +1 -0
  33. package/dist/layout.js +75 -0
  34. package/dist/layout.js.map +1 -0
  35. package/dist/playback.d.ts +107 -0
  36. package/dist/playback.d.ts.map +1 -0
  37. package/dist/playback.js +308 -0
  38. package/dist/playback.js.map +1 -0
  39. package/dist/replace.d.ts +22 -0
  40. package/dist/replace.d.ts.map +1 -0
  41. package/dist/replace.js +141 -0
  42. package/dist/replace.js.map +1 -0
  43. package/dist/stage3d.d.ts +25 -0
  44. package/dist/stage3d.d.ts.map +1 -0
  45. package/dist/stage3d.js +90 -0
  46. package/dist/stage3d.js.map +1 -0
  47. package/package.json +38 -3
  48. package/src/air-files.ts +371 -0
  49. package/src/air-items.ts +217 -0
  50. package/src/air.ts +497 -0
  51. package/src/config.ts +244 -0
  52. package/src/element.ts +902 -0
  53. package/src/external.ts +338 -0
  54. package/src/index.ts +33 -0
  55. package/src/layout.ts +127 -0
  56. package/src/playback.ts +388 -0
  57. package/src/replace.ts +166 -0
  58. package/src/stage3d.ts +112 -0
@@ -0,0 +1,90 @@
1
+ import { installContext3D } from "@swf2es/player/context3d";
2
+ import { stage3DCanvasHost } from "@swf2es/player-hosts/stage3d";
3
+ /** One load's Stage3D layers, below its transparent display-list canvas. */
4
+ export class Stage3DSession {
5
+ layer = document.createElement("div");
6
+ slots = new Map();
7
+ host;
8
+ close;
9
+ destroyed = false;
10
+ x = 0;
11
+ y = 0;
12
+ sx = 1;
13
+ sy = 1;
14
+ box;
15
+ isolation;
16
+ constructor(box, scripting, create, changed) {
17
+ this.box = box;
18
+ this.isolation = box.style.isolation;
19
+ this.layer.style.cssText = "position:absolute;inset:0;pointer-events:none;z-index:0";
20
+ const host = stage3DCanvasHost(this.layer, create);
21
+ this.host = host;
22
+ try {
23
+ box.append(this.layer);
24
+ // Keep canvases from different overlapping players in separate stacks.
25
+ box.style.isolation = "isolate";
26
+ this.close = installContext3D(scripting, {
27
+ create: (slot, lifecycle) => {
28
+ const context = host.create(slot, lifecycle);
29
+ this.slots.set(slot, { x: 0, y: 0, visible: true });
30
+ changed();
31
+ return context;
32
+ },
33
+ place: (slot, x, y, visible) => {
34
+ const position = this.slots.get(slot);
35
+ if (position) {
36
+ position.x = x;
37
+ position.y = y;
38
+ position.visible = visible;
39
+ this.place(slot, position);
40
+ }
41
+ },
42
+ remove: (slot) => {
43
+ host.remove(slot);
44
+ if (this.slots.delete(slot) && !this.destroyed) {
45
+ changed();
46
+ }
47
+ },
48
+ });
49
+ }
50
+ catch (error) {
51
+ this.layer.remove();
52
+ box.style.isolation = this.isolation;
53
+ throw error;
54
+ }
55
+ }
56
+ get active() {
57
+ return this.slots.size !== 0;
58
+ }
59
+ layout(placed, width, height) {
60
+ this.x = placed.x;
61
+ this.y = placed.y;
62
+ this.sx = placed.width / (width || 1);
63
+ this.sy = placed.height / (height || 1);
64
+ // AIR transforms viewport positions with the stage, but keeps configured
65
+ // back-buffer sizes in pixels instead of scaling the entire surface.
66
+ for (let slot = 0; slot < 4; slot++) {
67
+ const position = this.slots.get(slot);
68
+ if (position) {
69
+ this.place(slot, position);
70
+ }
71
+ }
72
+ }
73
+ place(slot, position) {
74
+ this.host.place(slot, this.x + position.x * this.sx, this.y + position.y * this.sy, position.visible);
75
+ }
76
+ destroy() {
77
+ if (this.destroyed) {
78
+ return;
79
+ }
80
+ this.destroyed = true;
81
+ try {
82
+ this.close();
83
+ }
84
+ finally {
85
+ this.layer.remove();
86
+ this.box.style.isolation = this.isolation;
87
+ }
88
+ }
89
+ }
90
+ //# sourceMappingURL=stage3d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stage3d.js","sourceRoot":"","sources":["../src/stage3d.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAuB,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAMtF,4EAA4E;AAC5E,MAAM,OAAO,cAAc;IACR,KAAK,GAAG,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACtC,KAAK,GAAG,IAAI,GAAG,EAAsD,CAAC;IACtE,IAAI,CAAuC;IAC3C,KAAK,CAAa;IAC3B,SAAS,GAAG,KAAK,CAAC;IAClB,CAAC,GAAG,CAAC,CAAC;IACN,CAAC,GAAG,CAAC,CAAC;IACN,EAAE,GAAG,CAAC,CAAC;IACP,EAAE,GAAG,CAAC,CAAC;IACE,GAAG,CAAc;IACjB,SAAS,CAAS;IAEnC,YACE,GAAgB,EAChB,SAAoB,EACpB,MAA6B,EAC7B,OAAmB;QAEnB,IAAI,CAAC,GAAG,GAAG,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AAY,EAAE,QAAoD;QAC9E,IAAI,CAAC,IAAI,CAAC,KAAK,CACb,IAAI,EACJ,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,EAC7B,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,EAC7B,QAAQ,CAAC,OAAO,CACjB,CAAC;IACJ,CAAC;IAED,OAAO;QACL,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC;YACH,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;YACpB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAC5C,CAAC;IACH,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@swf2es/web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Plays SWFs on any web page: the <swf2es-player> element, replaceFlash and ExternalInterface",
5
+ "keywords": [
6
+ "swf",
7
+ "flash",
8
+ "flash-player",
9
+ "embed",
10
+ "custom-element",
11
+ "actionscript",
12
+ "player"
13
+ ],
14
+ "homepage": "https://swf2es.github.io/swf2es/",
15
+ "bugs": "https://github.com/swf2es/swf2es/issues",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/swf2es/swf2es.git",
19
+ "directory": "packages/web"
20
+ },
21
+ "license": "Apache-2.0",
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "!dist/**/.tsbuildinfo",
32
+ "src"
33
+ ],
34
+ "dependencies": {
35
+ "@swf2es/codegen": "0.1.0",
36
+ "@swf2es/native": "0.1.0",
37
+ "@swf2es/format": "0.1.0",
38
+ "@swf2es/player": "0.1.0",
39
+ "@swf2es/player-hosts": "0.1.0"
40
+ }
6
41
  }
@@ -0,0 +1,371 @@
1
+ // The files an AIR application in a page writes: all of its file system
2
+ // but its own directory, which its package holds (air.ts). They are held
3
+ // in memory, kept in the browser's IndexedDB by the application's id where
4
+ // the page can keep them, and read back from there when it plays again, as
5
+ // an installed application finds its storage. The elements that play one
6
+ // application at once share its files.
7
+ import type { FileStat } from "@swf2es/player";
8
+
9
+ interface Node {
10
+ directory: boolean;
11
+ bytes: Uint8Array;
12
+ modified: number;
13
+ created: number;
14
+ }
15
+
16
+ /** A node as IndexedDB keeps it, by its application's id and its path. */
17
+ interface Stored extends Node {
18
+ id: string;
19
+ path: string;
20
+ }
21
+
22
+ const DATABASE = "swf2es-air";
23
+ const VERSION = 1;
24
+ const FILES = "files";
25
+ const BY_ID = "id";
26
+ const EMPTY = new Uint8Array(0);
27
+
28
+ /**
29
+ * The file system an application writes, its paths "/"-separated with no
30
+ * leading separator, "" its root. A directory is there once made or once
31
+ * a file is in it.
32
+ */
33
+ export class AirFiles {
34
+ readonly #nodes = new Map<string, Node>();
35
+ /** The paths changed since IndexedDB last had them. */
36
+ readonly #dirty = new Set<string>();
37
+ readonly #database: Promise<IDBDatabase | null>;
38
+ readonly #id: string;
39
+ /** The last save, which the next one follows. */
40
+ #saving: Promise<void> = Promise.resolve();
41
+ #scheduled = false;
42
+ /** Resolves once what IndexedDB kept is read, or there is nothing to read. */
43
+ readonly ready: Promise<void>;
44
+
45
+ /**
46
+ * The files of the application `id`, with `directories` made: kept in
47
+ * `indexedDB` where given, in memory alone otherwise, read from it once
48
+ * `after` settles.
49
+ */
50
+ constructor(
51
+ id: string,
52
+ directories: readonly string[],
53
+ indexedDB: IDBFactory | null,
54
+ after: Promise<void> = Promise.resolve(),
55
+ ) {
56
+ this.#id = id;
57
+ const now = Date.now();
58
+ for (const directory of directories) {
59
+ for (const path of ancestors(directory)) {
60
+ this.#nodes.set(path, { directory: true, bytes: EMPTY, modified: now, created: now });
61
+ }
62
+ }
63
+
64
+ this.#database = indexedDB
65
+ ? after.then(() => open(indexedDB)).catch(() => null)
66
+ : Promise.resolve(null);
67
+ this.ready = this.#database.then(async (db) => {
68
+ if (!db) {
69
+ return;
70
+ }
71
+
72
+ try {
73
+ const index = db.transaction(FILES).objectStore(FILES).index(BY_ID);
74
+ for (const stored of await request<Stored[]>(index.getAll(id))) {
75
+ const { directory, bytes, modified, created } = stored;
76
+ this.#nodes.set(stored.path, { directory, bytes, modified, created });
77
+ }
78
+ } catch {
79
+ // What could not be read is not there.
80
+ }
81
+ });
82
+ }
83
+
84
+ stat(path: string): FileStat | null {
85
+ if (path === "") {
86
+ return { directory: true, size: 0, modified: 0, created: 0 };
87
+ }
88
+
89
+ const node = this.#nodes.get(path);
90
+ return node
91
+ ? {
92
+ directory: node.directory,
93
+ size: node.directory ? 0 : node.bytes.length,
94
+ modified: node.modified,
95
+ created: node.created,
96
+ }
97
+ : null;
98
+ }
99
+
100
+ list(path: string): string[] | null {
101
+ if (path !== "" && !this.#nodes.get(path)?.directory) {
102
+ return null;
103
+ }
104
+
105
+ const prefix = path === "" ? "" : `${path}/`;
106
+ const names: string[] = [];
107
+ for (const key of this.#nodes.keys()) {
108
+ if (key.startsWith(prefix) && !key.includes("/", prefix.length)) {
109
+ names.push(key.slice(prefix.length));
110
+ }
111
+ }
112
+
113
+ return names.sort();
114
+ }
115
+
116
+ read(path: string): Uint8Array | null {
117
+ const node = this.#nodes.get(path);
118
+ return node && !node.directory ? node.bytes : null;
119
+ }
120
+
121
+ /** FileSystemHost's write: `bytes` at `offset` of the file at `path`, which is then `length` long. */
122
+ write(path: string, bytes: Uint8Array, offset: number, length: number): boolean {
123
+ const node = this.#nodes.get(path);
124
+ if (node?.directory || !this.#makeDirectories(parent(path))) {
125
+ return false;
126
+ }
127
+
128
+ // A new array each time: what read gave out, and what IndexedDB is yet to copy, stay as they were.
129
+ const now = Date.now();
130
+ const old = node?.bytes ?? EMPTY;
131
+ const next = new Uint8Array(length);
132
+ next.set(old.subarray(0, Math.min(old.length, length)));
133
+ next.set(bytes.subarray(0, Math.max(0, Math.min(bytes.length, length - offset))), offset);
134
+ this.#nodes.set(path, {
135
+ directory: false,
136
+ bytes: next,
137
+ modified: now,
138
+ created: node?.created ?? now,
139
+ });
140
+ this.#changed(path);
141
+ return true;
142
+ }
143
+
144
+ createDirectory(path: string): boolean {
145
+ return this.#makeDirectories(path);
146
+ }
147
+
148
+ /** Removes what is at `path`, with all in it. */
149
+ remove(path: string): boolean {
150
+ if (path === "" || !this.#nodes.has(path)) {
151
+ return false;
152
+ }
153
+
154
+ for (const key of this.#under(path)) {
155
+ this.#nodes.delete(key);
156
+ this.#changed(key);
157
+ }
158
+
159
+ return true;
160
+ }
161
+
162
+ /** Moves what is at `from`, with all in it, to `to`, where nothing is. */
163
+ move(from: string, to: string): boolean {
164
+ if (
165
+ from === "" ||
166
+ !this.#nodes.has(from) ||
167
+ this.#nodes.has(to) ||
168
+ to.startsWith(`${from}/`) ||
169
+ !this.#makeDirectories(parent(to))
170
+ ) {
171
+ return false;
172
+ }
173
+
174
+ for (const key of this.#under(from)) {
175
+ const moved = to + key.slice(from.length);
176
+ this.#nodes.set(moved, this.#nodes.get(key) as Node);
177
+ this.#nodes.delete(key);
178
+ this.#changed(key);
179
+ this.#changed(moved);
180
+ }
181
+
182
+ return true;
183
+ }
184
+
185
+ /** Lets go of the database once what was written is saved: resolves then. */
186
+ close(): Promise<void> {
187
+ // After the turn's changes join the saves.
188
+ return new Promise<void>((resolve) => setTimeout(resolve, 0))
189
+ .then(() => this.#saving)
190
+ .then(() => this.#database)
191
+ .then((db) => db?.close());
192
+ }
193
+
194
+ /** `path` and what is under it. */
195
+ #under(path: string): string[] {
196
+ const prefix = `${path}/`;
197
+ return [...this.#nodes.keys()].filter((key) => key === path || key.startsWith(prefix));
198
+ }
199
+
200
+ /** Makes the directory at `path` and those it is in; false where a file is in the way. */
201
+ #makeDirectories(path: string): boolean {
202
+ const chain = ancestors(path);
203
+ if (chain.some((p) => this.#nodes.get(p)?.directory === false)) {
204
+ return false;
205
+ }
206
+
207
+ const now = Date.now();
208
+ for (const p of chain) {
209
+ if (!this.#nodes.has(p)) {
210
+ this.#nodes.set(p, { directory: true, bytes: EMPTY, modified: now, created: now });
211
+ this.#changed(p);
212
+ }
213
+ }
214
+
215
+ return true;
216
+ }
217
+
218
+ /** Marks `path` for IndexedDB, which gets the changes of a turn together. */
219
+ #changed(path: string): void {
220
+ this.#dirty.add(path);
221
+ if (this.#scheduled) {
222
+ return;
223
+ }
224
+
225
+ this.#scheduled = true;
226
+ setTimeout(() => {
227
+ this.#scheduled = false;
228
+ const paths = [...this.#dirty];
229
+ this.#dirty.clear();
230
+ this.#saving = this.#saving.then(() => this.#save(paths));
231
+ }, 0);
232
+ }
233
+
234
+ async #save(paths: string[]): Promise<void> {
235
+ const db = await this.#database;
236
+ if (!db) {
237
+ return;
238
+ }
239
+
240
+ try {
241
+ const tx = db.transaction(FILES, "readwrite");
242
+ const store = tx.objectStore(FILES);
243
+ for (const path of paths) {
244
+ const node = this.#nodes.get(path);
245
+ if (node) {
246
+ store.put({ id: this.#id, path, ...node } satisfies Stored);
247
+ } else {
248
+ store.delete([this.#id, path]);
249
+ }
250
+ }
251
+
252
+ await done(tx);
253
+ } catch (e) {
254
+ // A quota, say: the files are still in memory while the page plays.
255
+ console.warn(`swf2es: the AIR application's files could not be kept: ${e}`);
256
+ }
257
+ }
258
+ }
259
+
260
+ /** Shared files by application id, with how many elements play each. */
261
+ const shared = new Map<string, { files: AirFiles; users: number }>();
262
+ /** By application id, the last files let go of, until what they wrote is saved. */
263
+ const closing = new Map<string, Promise<void>>();
264
+
265
+ /**
266
+ * The files of the application `id` for an element to play it with, with
267
+ * `directories` made: shared with other elements playing it, and kept in
268
+ * IndexedDB, unless `keep` is false, when they are the element's own, in
269
+ * memory alone. `release` when the element is done with them.
270
+ */
271
+ export function airFiles(
272
+ id: string,
273
+ directories: readonly string[],
274
+ keep: boolean,
275
+ ): { files: AirFiles; release(): void } {
276
+ const indexedDB = keep ? (globalThis.indexedDB ?? null) : null;
277
+ if (!indexedDB) {
278
+ return { files: new AirFiles(id, directories, null), release: () => {} };
279
+ }
280
+
281
+ let entry = shared.get(id);
282
+ if (!entry) {
283
+ entry = { files: new AirFiles(id, directories, indexedDB, closing.get(id)), users: 0 };
284
+ shared.set(id, entry);
285
+ }
286
+
287
+ entry.users++;
288
+ const held = entry;
289
+ let released = false;
290
+ return {
291
+ files: held.files,
292
+ release: () => {
293
+ if (released) {
294
+ return;
295
+ }
296
+
297
+ released = true;
298
+ held.users--;
299
+ if (held.users === 0 && shared.get(id) === held) {
300
+ shared.delete(id);
301
+ const closed = held.files.close();
302
+ closing.set(id, closed);
303
+ void closed.then(() => {
304
+ if (closing.get(id) === closed) {
305
+ closing.delete(id);
306
+ }
307
+ });
308
+ }
309
+ },
310
+ };
311
+ }
312
+
313
+ /** `path` and the directories it is in, outermost first; none for the root. */
314
+ function ancestors(path: string): string[] {
315
+ if (path === "") {
316
+ return [];
317
+ }
318
+
319
+ const segments = path.split("/");
320
+ return segments.map((_, i) => segments.slice(0, i + 1).join("/"));
321
+ }
322
+
323
+ /** The directory `path` is in; "" for one in the root. */
324
+ function parent(path: string): string {
325
+ const at = path.lastIndexOf("/");
326
+ return at < 0 ? "" : path.slice(0, at);
327
+ }
328
+
329
+ function open(factory: IDBFactory): Promise<IDBDatabase> {
330
+ return new Promise((resolve, reject) => {
331
+ // Another tab holding an older version open blocks it: done without.
332
+ let late = false;
333
+ const timer = setTimeout(() => {
334
+ late = true;
335
+ reject(new Error(`IndexedDB ${DATABASE} did not open`));
336
+ }, 2000);
337
+ const opening = factory.open(DATABASE, VERSION);
338
+ opening.onupgradeneeded = () => {
339
+ opening.result
340
+ .createObjectStore(FILES, { keyPath: ["id", "path"] })
341
+ .createIndex(BY_ID, BY_ID);
342
+ };
343
+ opening.onsuccess = () => {
344
+ clearTimeout(timer);
345
+ if (late) {
346
+ opening.result.close();
347
+ } else {
348
+ resolve(opening.result);
349
+ }
350
+ };
351
+ opening.onerror = () => {
352
+ clearTimeout(timer);
353
+ reject(opening.error);
354
+ };
355
+ });
356
+ }
357
+
358
+ function request<T>(r: IDBRequest): Promise<T> {
359
+ return new Promise((resolve, reject) => {
360
+ r.onsuccess = () => resolve(r.result as T);
361
+ r.onerror = () => reject(r.error);
362
+ });
363
+ }
364
+
365
+ function done(tx: IDBTransaction): Promise<void> {
366
+ return new Promise((resolve, reject) => {
367
+ tx.oncomplete = () => resolve();
368
+ tx.onerror = () => reject(tx.error);
369
+ tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
370
+ });
371
+ }