@swf2es/web 0.0.0-stage → 0.1.1

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,217 @@
1
+ // An AIR application's EncryptedLocalStore in a page: its items held in
2
+ // memory and kept in the browser's IndexedDB by the application's id, read
3
+ // back before it plays again, as an installed application finds its items.
4
+ // A page has no keychain to encrypt them by: the browser keeps them as it
5
+ // keeps the origin's other data, apart from other sites'. The elements that
6
+ // play one application share its items.
7
+ import type { EncryptedStoreHost } from "@swf2es/player";
8
+
9
+ const DATABASE = "swf2es-air-items";
10
+ const VERSION = 1;
11
+ const ITEMS = "items";
12
+ const BY_ID = "id";
13
+
14
+ /** An item as IndexedDB keeps it, by its application's id and its name. */
15
+ interface Stored {
16
+ id: string;
17
+ name: string;
18
+ bytes: Uint8Array;
19
+ }
20
+
21
+ /** The items of one application; `ready` once what IndexedDB kept is read. */
22
+ export class AirItems implements EncryptedStoreHost {
23
+ readonly #items = new Map<string, Uint8Array>();
24
+ /** The names changed since IndexedDB last had them. */
25
+ readonly #dirty = new Set<string>();
26
+ readonly #database: Promise<IDBDatabase | null>;
27
+ readonly #id: string;
28
+ #saving: Promise<void> = Promise.resolve();
29
+ #scheduled = false;
30
+ readonly ready: Promise<void>;
31
+
32
+ /**
33
+ * The items of the application `id`, kept in `indexedDB` where given, in
34
+ * memory alone otherwise, read from it once `after` settles.
35
+ */
36
+ constructor(id: string, indexedDB: IDBFactory | null, after: Promise<void> = Promise.resolve()) {
37
+ this.#id = id;
38
+ this.#database = indexedDB
39
+ ? after.then(() => open(indexedDB)).catch(() => null)
40
+ : Promise.resolve(null);
41
+ this.ready = this.#database.then(async (db) => {
42
+ if (!db) {
43
+ return;
44
+ }
45
+
46
+ try {
47
+ const index = db.transaction(ITEMS).objectStore(ITEMS).index(BY_ID);
48
+ for (const stored of await request<Stored[]>(index.getAll(id))) {
49
+ this.#items.set(stored.name, stored.bytes);
50
+ }
51
+ } catch {
52
+ // What could not be read is not there.
53
+ }
54
+ });
55
+ }
56
+
57
+ getItem(name: string): Uint8Array | null {
58
+ return this.#items.get(name) ?? null;
59
+ }
60
+
61
+ setItem(name: string, bytes: Uint8Array): void {
62
+ this.#items.set(name, bytes.slice());
63
+ this.#changed(name);
64
+ }
65
+
66
+ removeItem(name: string): void {
67
+ if (this.#items.delete(name)) {
68
+ this.#changed(name);
69
+ }
70
+ }
71
+
72
+ reset(): void {
73
+ for (const name of this.#items.keys()) {
74
+ this.#changed(name);
75
+ }
76
+
77
+ this.#items.clear();
78
+ }
79
+
80
+ /** Lets go of the database once what was changed is saved: resolves then. */
81
+ close(): Promise<void> {
82
+ // After the turn's changes join the saves.
83
+ return new Promise<void>((resolve) => setTimeout(resolve, 0))
84
+ .then(() => this.#saving)
85
+ .then(() => this.#database)
86
+ .then((db) => db?.close());
87
+ }
88
+
89
+ /** Marks `name` for IndexedDB, which gets the changes of a turn together. */
90
+ #changed(name: string): void {
91
+ this.#dirty.add(name);
92
+ if (this.#scheduled) {
93
+ return;
94
+ }
95
+
96
+ this.#scheduled = true;
97
+ setTimeout(() => {
98
+ this.#scheduled = false;
99
+ const names = [...this.#dirty];
100
+ this.#dirty.clear();
101
+ this.#saving = this.#saving.then(() => this.#save(names));
102
+ }, 0);
103
+ }
104
+
105
+ async #save(names: string[]): Promise<void> {
106
+ const db = await this.#database;
107
+ if (!db) {
108
+ return;
109
+ }
110
+
111
+ try {
112
+ const tx = db.transaction(ITEMS, "readwrite");
113
+ const store = tx.objectStore(ITEMS);
114
+ for (const name of names) {
115
+ const bytes = this.#items.get(name);
116
+ if (bytes) {
117
+ store.put({ id: this.#id, name, bytes } satisfies Stored);
118
+ } else {
119
+ store.delete([this.#id, name]);
120
+ }
121
+ }
122
+
123
+ await done(tx);
124
+ } catch (e) {
125
+ // A quota, say: the items are still in memory while the page plays.
126
+ console.warn(`swf2es: the AIR application's EncryptedLocalStore could not be kept: ${e}`);
127
+ }
128
+ }
129
+ }
130
+
131
+ /** Each application's items, by its id, with how many elements play it. */
132
+ const shared = new Map<string, { items: AirItems; users: number }>();
133
+ /** By application id, the last items let go of, until what they changed is saved. */
134
+ const closing = new Map<string, Promise<void>>();
135
+
136
+ /**
137
+ * The items of the application `id` for an element to play it with,
138
+ * shared with other elements playing it, kept in IndexedDB where the page
139
+ * has it; `release` when the element is done with them. One that plays it
140
+ * next waits for the last to save.
141
+ */
142
+ export function airItems(id: string): { items: AirItems; release(): void } {
143
+ let entry = shared.get(id);
144
+ if (!entry) {
145
+ entry = { items: new AirItems(id, globalThis.indexedDB ?? null, closing.get(id)), users: 0 };
146
+ shared.set(id, entry);
147
+ }
148
+
149
+ entry.users++;
150
+ const held = entry;
151
+ let released = false;
152
+ return {
153
+ items: held.items,
154
+ release: () => {
155
+ if (released) {
156
+ return;
157
+ }
158
+
159
+ released = true;
160
+ held.users--;
161
+ if (held.users === 0 && shared.get(id) === held) {
162
+ shared.delete(id);
163
+ const closed = held.items.close();
164
+ closing.set(id, closed);
165
+ void closed.then(() => {
166
+ if (closing.get(id) === closed) {
167
+ closing.delete(id);
168
+ }
169
+ });
170
+ }
171
+ },
172
+ };
173
+ }
174
+
175
+ function open(factory: IDBFactory): Promise<IDBDatabase> {
176
+ return new Promise((resolve, reject) => {
177
+ // Another tab holding an older version open blocks it: done without.
178
+ let late = false;
179
+ const timer = setTimeout(() => {
180
+ late = true;
181
+ reject(new Error(`IndexedDB ${DATABASE} did not open`));
182
+ }, 2000);
183
+ const opening = factory.open(DATABASE, VERSION);
184
+ opening.onupgradeneeded = () => {
185
+ opening.result
186
+ .createObjectStore(ITEMS, { keyPath: ["id", "name"] })
187
+ .createIndex(BY_ID, BY_ID);
188
+ };
189
+ opening.onsuccess = () => {
190
+ clearTimeout(timer);
191
+ if (late) {
192
+ opening.result.close();
193
+ } else {
194
+ resolve(opening.result);
195
+ }
196
+ };
197
+ opening.onerror = () => {
198
+ clearTimeout(timer);
199
+ reject(opening.error);
200
+ };
201
+ });
202
+ }
203
+
204
+ function request<T>(r: IDBRequest): Promise<T> {
205
+ return new Promise((resolve, reject) => {
206
+ r.onsuccess = () => resolve(r.result as T);
207
+ r.onerror = () => reject(r.error);
208
+ });
209
+ }
210
+
211
+ function done(tx: IDBTransaction): Promise<void> {
212
+ return new Promise((resolve, reject) => {
213
+ tx.oncomplete = () => resolve();
214
+ tx.onerror = () => reject(tx.error);
215
+ tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
216
+ });
217
+ }
package/src/air.ts ADDED
@@ -0,0 +1,497 @@
1
+ // An AIR application a page plays: its files held in memory, from an AIR
2
+ // package (`.air`), a ZIP of its folder, or the files of one the page was
3
+ // given. Its descriptor names the content SWF the element plays, as adl
4
+ // does, under AIR's API and its application sandbox. File sees the files
5
+ // under the application's directory, which it does not write, as an
6
+ // installed application's; the rest of the file system, its storage and
7
+ // the user's directories among them, is what it writes (air-files.ts).
8
+ // app:, app-storage: and file: URLs load from memory, and any other goes
9
+ // to the network as the page's would.
10
+ import {
11
+ type AirDescriptor,
12
+ abcReferences,
13
+ readAirDescriptor,
14
+ readDoAbc,
15
+ readZip,
16
+ type Swf,
17
+ tags,
18
+ } from "@swf2es/format";
19
+ import {
20
+ AIR_DEFINITIONS,
21
+ type AirApplication,
22
+ type AirWindow,
23
+ type FetchRequest,
24
+ type FetchResult,
25
+ type FileStat,
26
+ type FileSystemHost,
27
+ } from "@swf2es/player";
28
+ import { AirFiles } from "./air-files.js";
29
+
30
+ /** One of an application's files, its path relative to the folder it came in, "/"-separated. */
31
+ export interface AirAppFile {
32
+ path: string;
33
+ bytes: Uint8Array;
34
+ /** When it was last changed, in ms since 1970; when it was opened if not given. */
35
+ modified?: number;
36
+ }
37
+
38
+ /** Where AIR's directories are on the file system File sees. */
39
+ const DIRECTORIES = {
40
+ application: "/app",
41
+ applicationStorage: "/app-storage",
42
+ user: "/user",
43
+ documents: "/user/Documents",
44
+ desktop: "/user/Desktop",
45
+ cache: "/cache",
46
+ };
47
+
48
+ /** AIR's directories but the application's, there before it writes, as paths from the root. */
49
+ export const AIR_DIRECTORIES: readonly string[] = [
50
+ DIRECTORIES.applicationStorage,
51
+ DIRECTORIES.documents,
52
+ DIRECTORIES.desktop,
53
+ DIRECTORIES.cache,
54
+ ].map((d) => d.slice(1));
55
+
56
+ /** Where an AIR package keeps its descriptor; its root is the application's directory. */
57
+ const PACKAGE_DESCRIPTOR = "META-INF/AIR/application.xml";
58
+
59
+ /** Where the application's directory and its storage are, as paths from the root. */
60
+ const ROOT_APP = DIRECTORIES.application.slice(1);
61
+ const ROOT_STORAGE = DIRECTORIES.applicationStorage.slice(1);
62
+
63
+ interface Entry {
64
+ size: number;
65
+ modified: number;
66
+ bytes(): Uint8Array;
67
+ }
68
+
69
+ /** An AIR application opened from its files; `Swf2esPlayerElement.loadAir` plays it. */
70
+ export class AirApp {
71
+ /** The descriptor as written, which NativeApplication.applicationDescriptor gives. */
72
+ readonly xml: string;
73
+ readonly descriptor: AirDescriptor;
74
+ /** The application's files, by their path under its directory. */
75
+ readonly #files: Map<string, Entry>;
76
+ /** Every directory the files are in, the application's own ("") among them. */
77
+ readonly #directories: Set<string>;
78
+ readonly #opened = Date.now();
79
+ /**
80
+ * Where the files not in memory are on the network, the directory a SWF
81
+ * played alone came from (`airAppForSwf`): an app: URL loads from there
82
+ * what the application does not hold, as its folder on a server is.
83
+ */
84
+ readonly base: string | null;
85
+
86
+ constructor(xml: string, files: Map<string, Entry>, base: string | null = null) {
87
+ this.xml = xml;
88
+ this.base = base;
89
+ this.descriptor = readAirDescriptor(xml);
90
+ this.#files = files;
91
+ this.#directories = new Set([""]);
92
+ for (const path of files.keys()) {
93
+ for (let at = path.indexOf("/"); at >= 0; at = path.indexOf("/", at + 1)) {
94
+ this.#directories.add(path.slice(0, at));
95
+ }
96
+ }
97
+
98
+ if (!files.has(this.descriptor.content)) {
99
+ throw new Error(
100
+ `the application has no ${this.descriptor.content}, its descriptor's content`,
101
+ );
102
+ }
103
+ }
104
+
105
+ /** The bytes of the file at `path` under the application's directory; null where none is. */
106
+ read(path: string): Uint8Array | null {
107
+ return this.#files.get(path)?.bytes() ?? null;
108
+ }
109
+
110
+ /**
111
+ * The file system File sees: the application's files under its
112
+ * directory, which it does not write, and `files` for the rest, by
113
+ * default its own, in memory.
114
+ */
115
+ fileSystem(files = new AirFiles(this.descriptor.id, AIR_DIRECTORIES, null)): FileSystemHost {
116
+ // A native path's place: under the application's directory, or else in `files`; null for neither.
117
+ const place = (native: string): { app: string } | { files: string } | null => {
118
+ const path = normalize(native);
119
+ if (path === null) {
120
+ return null;
121
+ }
122
+
123
+ const inApp = under(path, DIRECTORIES.application);
124
+ return inApp === null ? { files: path } : { app: inApp };
125
+ };
126
+ const writable = (native: string): string | null => {
127
+ const at = place(native);
128
+ return at && "files" in at ? at.files : null;
129
+ };
130
+ return {
131
+ separator: "/",
132
+ directories: DIRECTORIES,
133
+ stat: (native) => {
134
+ const at = place(native);
135
+ if (!at) {
136
+ return null;
137
+ }
138
+
139
+ return "app" in at ? this.#stat(at.app) : files.stat(at.files);
140
+ },
141
+ list: (native) => {
142
+ const at = place(native);
143
+ if (!at) {
144
+ return null;
145
+ }
146
+
147
+ if ("app" in at) {
148
+ return this.#list(at.app);
149
+ }
150
+
151
+ const names = files.list(at.files);
152
+ // The root holds the application's directory too.
153
+ return names && at.files === "" ? [...new Set([...names, ROOT_APP])].sort() : names;
154
+ },
155
+ read: (native) => {
156
+ const at = place(native);
157
+ if (!at) {
158
+ return null;
159
+ }
160
+
161
+ return "app" in at ? this.read(at.app) : files.read(at.files);
162
+ },
163
+ write: (native, bytes, offset, length) => {
164
+ const path = writable(native);
165
+ return path !== null && files.write(path, bytes, offset, length);
166
+ },
167
+ createDirectory: (native) => {
168
+ const path = writable(native);
169
+ return path !== null && files.createDirectory(path);
170
+ },
171
+ remove: (native) => {
172
+ const path = writable(native);
173
+ return path !== null && files.remove(path);
174
+ },
175
+ move: (from, to) => {
176
+ const a = writable(from);
177
+ const b = writable(to);
178
+ return a !== null && b !== null && files.move(a, b);
179
+ },
180
+ };
181
+ }
182
+
183
+ /**
184
+ * NativeApplication's view: the descriptor, `args` as the launch's
185
+ * arguments, and `window`, the element playing it. Its exit is `exit`.
186
+ */
187
+ application(
188
+ window: AirWindow,
189
+ args: readonly string[],
190
+ exit: (code: number) => void,
191
+ ): AirApplication {
192
+ return {
193
+ descriptor: this.xml,
194
+ id: this.descriptor.id,
195
+ arguments: args,
196
+ currentDirectory: DIRECTORIES.application,
197
+ window,
198
+ exit,
199
+ };
200
+ }
201
+
202
+ /**
203
+ * What the application's SWFs load from it: an app: URL, or a file: URL
204
+ * under its directory, from memory, and an app-storage: URL or a file:
205
+ * URL elsewhere from `files`, if given, a missing one as a 404 is. Null
206
+ * for any other URL, which the page's fetch loads.
207
+ */
208
+ fetch(request: FetchRequest, files?: AirFiles): FetchResult | null {
209
+ const path = this.#pathOf(request.url);
210
+ if (path === undefined) {
211
+ return null;
212
+ }
213
+
214
+ const inApp = path === null ? null : under(path, DIRECTORIES.application);
215
+ const bytes =
216
+ path === null ? null : inApp !== null ? this.read(inApp) : (files?.read(path) ?? null);
217
+ return { bytes, status: bytes ? 200 : 404, headers: [] };
218
+ }
219
+
220
+ /** Where on the network `url`, an app: URL of a file not in memory, is under `base`; null for none. */
221
+ remote(url: string): string | null {
222
+ const path = this.#pathOf(url);
223
+ const inApp = path ? under(path, DIRECTORIES.application) : null;
224
+ if (this.base === null || inApp === null || this.#files.has(inApp)) {
225
+ return null;
226
+ }
227
+
228
+ return /^app:/i.test(url)
229
+ ? new URL(inApp.split("/").map(encodeURIComponent).join("/"), this.base).href
230
+ : null;
231
+ }
232
+
233
+ /**
234
+ * The path `url` names on the file system File sees, "/"-separated with
235
+ * no leading separator; null for a local URL that names none; undefined
236
+ * for a URL that is not local.
237
+ */
238
+ #pathOf(url: string): string | null | undefined {
239
+ const m = /^(app|app-storage|file):(.*)$/i.exec(url);
240
+ if (!m) {
241
+ return undefined;
242
+ }
243
+
244
+ let rest: string;
245
+ try {
246
+ // A query or a fragment is no part of the file's name.
247
+ rest = decodeURIComponent(m[2].replace(/[?#].*$/, ""));
248
+ } catch {
249
+ return null;
250
+ }
251
+
252
+ switch (m[1].toLowerCase()) {
253
+ case "app":
254
+ case "app-storage": {
255
+ // Never above the directory the URL starts from.
256
+ const path = normalize(rest);
257
+ const root = m[1].toLowerCase() === "app" ? ROOT_APP : ROOT_STORAGE;
258
+ return path === null ? null : path === "" ? root : `${root}/${path}`;
259
+ }
260
+ default:
261
+ return normalize(rest.replace(/^\/\/[^/]*/, ""));
262
+ }
263
+ }
264
+
265
+ /** What is at `path` under the application's directory. */
266
+ #stat(path: string): FileStat | null {
267
+ const file = this.#files.get(path);
268
+ if (file) {
269
+ return {
270
+ directory: false,
271
+ size: file.size,
272
+ modified: file.modified,
273
+ created: file.modified,
274
+ };
275
+ }
276
+
277
+ return this.#directories.has(path) ? this.#directory() : null;
278
+ }
279
+
280
+ /** The names in the directory at `path` under the application's directory. */
281
+ #list(path: string): string[] | null {
282
+ if (this.#stat(path)?.directory !== true) {
283
+ return null;
284
+ }
285
+
286
+ const names = new Set<string>();
287
+ const prefix = path === "" ? "" : `${path}/`;
288
+ for (const name of [...this.#files.keys(), ...this.#directories]) {
289
+ if (name.startsWith(prefix) && name.length > prefix.length) {
290
+ names.add(name.slice(prefix.length).split("/")[0]);
291
+ }
292
+ }
293
+
294
+ return [...names].sort();
295
+ }
296
+
297
+ #directory(): FileStat {
298
+ return { directory: true, size: 0, modified: this.#opened, created: this.#opened };
299
+ }
300
+ }
301
+
302
+ /**
303
+ * The application in `source`: an AIR package's or a ZIP's bytes, or the
304
+ * files of its folder. Its descriptor is the package's, or else the
305
+ * shallowest `*-app.xml` or `application.xml`, whose folder is the
306
+ * application's directory. An Error says what it lacks.
307
+ */
308
+ export function openAirApp(source: Uint8Array | ArrayBuffer | Iterable<AirAppFile>): AirApp {
309
+ const opened = Date.now();
310
+ const all = new Map<string, Entry>();
311
+ if (source instanceof Uint8Array || source instanceof ArrayBuffer) {
312
+ for (const entry of readZip(source instanceof Uint8Array ? source : new Uint8Array(source))) {
313
+ const path = normalize(entry.name);
314
+ if (path && !entry.name.endsWith("/")) {
315
+ all.set(path, entry);
316
+ }
317
+ }
318
+ } else {
319
+ for (const file of source) {
320
+ const path = normalize(file.path);
321
+ if (path) {
322
+ const bytes = file.bytes;
323
+ all.set(path, {
324
+ size: bytes.length,
325
+ modified: file.modified ?? opened,
326
+ bytes: () => bytes,
327
+ });
328
+ }
329
+ }
330
+ }
331
+
332
+ const descriptor = all.has(PACKAGE_DESCRIPTOR) ? PACKAGE_DESCRIPTOR : descriptorIn(all);
333
+ if (descriptor === null) {
334
+ throw new Error("no AIR application descriptor (META-INF/AIR/application.xml or *-app.xml)");
335
+ }
336
+
337
+ const root =
338
+ descriptor === PACKAGE_DESCRIPTOR ? "" : descriptor.slice(0, descriptor.lastIndexOf("/") + 1);
339
+ const files = new Map<string, Entry>();
340
+ for (const [path, entry] of all) {
341
+ if (path.startsWith(root)) {
342
+ files.set(path.slice(root.length), entry);
343
+ }
344
+ }
345
+
346
+ const xml = new TextDecoder().decode(all.get(descriptor)?.bytes());
347
+ return new AirApp(xml, files);
348
+ }
349
+
350
+ /**
351
+ * Whether `swf` is an AIR application's, though it came alone: its
352
+ * ActionScript names a definition only AIR has (AIR_DEFINITIONS), which a
353
+ * browser's Flash Player would refuse it for.
354
+ */
355
+ export function namesAir(swf: Swf): boolean {
356
+ for (const tag of swf.tags) {
357
+ if (tag.code === tags.DoABC || tag.code === tags.DoABC2) {
358
+ for (const name of abcReferences(readDoAbc(swf.bytes, tag).abc)) {
359
+ if (AIR_DEFINITIONS.has(name)) {
360
+ return true;
361
+ }
362
+ }
363
+ }
364
+ }
365
+
366
+ return false;
367
+ }
368
+
369
+ /**
370
+ * The AIR application of `bytes`, a SWF played alone from `url`, as adl
371
+ * runs one from a descriptor that names only it: its id and title from
372
+ * its file's name, its directory holding it alone, and the directory it
373
+ * came from, if from a server, where its app: URLs load what else it has.
374
+ */
375
+ export function airAppForSwf(bytes: Uint8Array, url: string): AirApp {
376
+ let name = "Main.swf";
377
+ let base: string | null = null;
378
+ try {
379
+ const at = new URL(url);
380
+ const last = decodeURIComponent(at.pathname.slice(at.pathname.lastIndexOf("/") + 1));
381
+ if (last) {
382
+ name = last;
383
+ }
384
+
385
+ if (at.protocol === "http:" || at.protocol === "https:") {
386
+ base = new URL(".", at).href;
387
+ }
388
+ } catch {
389
+ // A page's own bytes, of no URL: the defaults.
390
+ }
391
+
392
+ const stem = name.replace(/\.[^.]*$/, "") || "Main";
393
+ const xmlText = (text: string) =>
394
+ text.replace(
395
+ /[&<>"]/g,
396
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] as string,
397
+ );
398
+ const id = `swf2es.${stem.replace(/[^A-Za-z0-9.-]/g, "-")}`;
399
+ const xml = `<?xml version="1.0" encoding="utf-8" ?>
400
+ <application xmlns="http://ns.adobe.com/air/application/51.3">
401
+ <id>${xmlText(id)}</id>
402
+ <filename>${xmlText(stem)}</filename>
403
+ <versionNumber>1.0</versionNumber>
404
+ <initialWindow><content>${xmlText(name)}</content><title>${xmlText(stem)}</title></initialWindow>
405
+ </application>`;
406
+ const files = new Map<string, Entry>([
407
+ [name, { size: bytes.length, modified: Date.now(), bytes: () => bytes }],
408
+ ]);
409
+ return new AirApp(xml, files, base);
410
+ }
411
+
412
+ /** The shallowest `*-app.xml` or `application.xml` among `files`, outside META-INF; null for none. */
413
+ function descriptorIn(files: Map<string, Entry>): string | null {
414
+ let best: string | null = null;
415
+ for (const path of files.keys()) {
416
+ const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
417
+ if (
418
+ (name.endsWith("-app.xml") || name === "application.xml") &&
419
+ !path.startsWith("META-INF/") &&
420
+ (best === null || depth(path) < depth(best))
421
+ ) {
422
+ best = path;
423
+ }
424
+ }
425
+
426
+ return best;
427
+ }
428
+
429
+ function depth(path: string): number {
430
+ return path.split("/").length;
431
+ }
432
+
433
+ /**
434
+ * `path`'s segments, "/"-joined, without its leading separator, "." and
435
+ * empty segments, each ".." taking the one before it; null where one
436
+ * climbs above the start.
437
+ */
438
+ function normalize(path: string): string | null {
439
+ const segments: string[] = [];
440
+ for (const segment of path.replaceAll("\\", "/").split("/")) {
441
+ if (segment === "" || segment === ".") {
442
+ continue;
443
+ }
444
+
445
+ if (segment === "..") {
446
+ if (segments.length === 0) {
447
+ return null;
448
+ }
449
+
450
+ segments.pop();
451
+ continue;
452
+ }
453
+
454
+ segments.push(segment);
455
+ }
456
+
457
+ return segments.join("/");
458
+ }
459
+
460
+ /** `path` relative to the directory `directory` ("/"-rooted) if it is in it or is it; null otherwise. */
461
+ function under(path: string, directory: string): string | null {
462
+ const root = directory.slice(1);
463
+ if (path === root) {
464
+ return "";
465
+ }
466
+
467
+ return path.startsWith(`${root}/`) ? path.slice(root.length + 1) : null;
468
+ }
469
+
470
+ /**
471
+ * The window an application sees, the element playing it: where it is on
472
+ * the page, the descriptor's title until the application sets another, in
473
+ * the normal state and shown, active while it has the focus.
474
+ */
475
+ export function elementWindow(element: HTMLElement, title: string | null): AirWindow {
476
+ let current = title ?? "";
477
+ return {
478
+ bounds: () => {
479
+ const r = element.getBoundingClientRect();
480
+ return {
481
+ x: Math.round(r.left),
482
+ y: Math.round(r.top),
483
+ width: Math.round(r.width),
484
+ height: Math.round(r.height),
485
+ };
486
+ },
487
+ title: () => current,
488
+ setTitle: (value) => {
489
+ current = value;
490
+ },
491
+ displayState: () => "normal",
492
+ active: () => document.hasFocus() && document.activeElement === element,
493
+ activate: () => element.focus(),
494
+ visible: () => true,
495
+ stageOffset: () => ({ x: 0, y: 0 }),
496
+ };
497
+ }