@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
package/src/element.ts ADDED
@@ -0,0 +1,902 @@
1
+ // <swf2es-player>: a SWF on a page as an <embed> showed one, with the
2
+ // embedding's attributes, a load() and destroy() of its own, and the
3
+ // SWF's ExternalInterface callbacks as methods on the element.
4
+ import { isAs3, readActions, readSwf, type Swf, tags } from "@swf2es/format";
5
+ import {
6
+ type AirApplication,
7
+ Avm1,
8
+ type ExternalInterfaceHost,
9
+ type FetchRequest,
10
+ type FetchResult,
11
+ type FileSystemHost,
12
+ Player,
13
+ Scripting,
14
+ type WorkerHost,
15
+ } from "@swf2es/player";
16
+ import type { WebWorkerHost } from "@swf2es/player-hosts/workers";
17
+ import { AIR_DIRECTORIES, AirApp, airAppForSwf, elementWindow, namesAir } from "./air.js";
18
+ import { type AirFiles, airFiles } from "./air-files.js";
19
+ import { type AirItems, airItems } from "./air-items.js";
20
+ import {
21
+ codegenForPlayer,
22
+ configuration,
23
+ moduleCacheOptions,
24
+ playerLibraries,
25
+ socketHost,
26
+ workerHostForPlayer,
27
+ } from "./config.js";
28
+ import { externalInterfaceHost, type PageBridge, type PageValue } from "./external.js";
29
+ import { scaleMode } from "./layout.js";
30
+ import { type Look, Playback } from "./playback.js";
31
+ import type { Stage3DSession } from "./stage3d.js";
32
+
33
+ export const TAG = "swf2es-player";
34
+
35
+ /** What `load` takes: a URL, relative to the page, or the SWF's bytes. */
36
+ export type SwfSource = string | URL | ArrayBuffer | Uint8Array;
37
+
38
+ /** In node, which has no DOM, the module still loads, for its other exports. */
39
+ const ElementBase = (globalThis.HTMLElement ?? class {}) as typeof HTMLElement;
40
+
41
+ /**
42
+ * The DOM's own methods, taken as the module loads and called on the
43
+ * element, never looked up on it: a SWF's callbacks live on the element,
44
+ * and must not reach what it does for itself.
45
+ */
46
+ const dom = globalThis.HTMLElement
47
+ ? {
48
+ getAttribute: Element.prototype.getAttribute,
49
+ hasAttribute: Element.prototype.hasAttribute,
50
+ setAttribute: Element.prototype.setAttribute,
51
+ dispatchEvent: EventTarget.prototype.dispatchEvent,
52
+ focus: HTMLElement.prototype.focus,
53
+ isConnected: Object.getOwnPropertyDescriptor(Node.prototype, "isConnected")?.get,
54
+ id: Object.getOwnPropertyDescriptor(Element.prototype, "id")?.get,
55
+ }
56
+ : null;
57
+ const attribute = (e: HTMLElement, name: string): string | null =>
58
+ dom?.getAttribute.call(e, name) ?? null;
59
+ const hasAttribute = (e: HTMLElement, name: string) => dom?.hasAttribute.call(e, name) ?? false;
60
+ const setAttribute = (e: HTMLElement, name: string, value: string) =>
61
+ dom?.setAttribute.call(e, name, value);
62
+ const dispatch = (e: HTMLElement, event: Event) => dom?.dispatchEvent.call(e, event);
63
+ const focus = (e: HTMLElement) => dom?.focus.call(e, { preventScroll: true });
64
+ const connected = (e: HTMLElement): boolean => Boolean(dom?.isConnected?.call(e));
65
+ const idOf = (e: HTMLElement): string => String(dom?.id?.call(e) ?? "");
66
+
67
+ /** What one load holds, let go of all at once when the next load or destroy comes. */
68
+ interface Session {
69
+ scripting: Scripting | null;
70
+ player: Player | null;
71
+ playback: Playback | null;
72
+ stage3D: Stage3DSession | null;
73
+ /** The ExternalInterface callbacks the SWF put on the element. */
74
+ callbacks: Set<string>;
75
+ /** Aborts the fetch of the SWF itself, as a destroy comes before it arrives. */
76
+ abort: AbortController;
77
+ /** The Web Workers its SWF starts, let go of with it. */
78
+ workers: WebWorkerHost | null;
79
+ /** The AIR application it plays (`loadAir`), its hosts made for this element; null for a SWF. */
80
+ air: {
81
+ app: AirApp;
82
+ application: AirApplication;
83
+ fileSystem: FileSystemHost;
84
+ /** What it writes, and its EncryptedLocalStore, each read back from IndexedDB once `ready`. */
85
+ files: AirFiles;
86
+ items: AirItems;
87
+ /** Lets go of both once the session is done with them. */
88
+ release(): void;
89
+ } | null;
90
+ }
91
+
92
+ interface Deferred {
93
+ promise: Promise<void>;
94
+ resolve(): void;
95
+ reject(error: unknown): void;
96
+ settled: boolean;
97
+ }
98
+
99
+ function deferred(): Deferred {
100
+ let resolve!: () => void;
101
+ let reject!: (error: unknown) => void;
102
+ const promise = new Promise<void>((ok, fail) => {
103
+ resolve = ok;
104
+ reject = fail;
105
+ });
106
+ // A page that never awaits `ready` should not hear of its failure as unhandled.
107
+ promise.catch(() => {});
108
+ const d: Deferred = {
109
+ promise,
110
+ settled: false,
111
+ resolve: () => {
112
+ d.settled = true;
113
+ resolve();
114
+ },
115
+ reject: (error) => {
116
+ d.settled = true;
117
+ reject(error);
118
+ },
119
+ };
120
+ return d;
121
+ }
122
+
123
+ /** "550" is pixels, as an <embed>'s width is; "100%" and other CSS lengths are themselves. */
124
+ function cssLength(value: string | null): string | null {
125
+ if (value === null || value.trim() === "") {
126
+ return null;
127
+ }
128
+
129
+ return /^\s*\d+(\.\d+)?\s*$/.test(value) ? `${Number(value)}px` : value.trim();
130
+ }
131
+
132
+ /** A colour as Flash's bgcolor gives it, "#RRGGBB" or "RRGGBB"; null for none or another form. */
133
+ export function parseColor(value: string | null): number | null {
134
+ const hex = /^\s*#?([0-9a-f]{6})\s*$/i.exec(value ?? "")?.[1];
135
+ return hex ? Number.parseInt(hex, 16) : null;
136
+ }
137
+
138
+ /** FlashVars, "name=value&...", URL-encoded, as Flash read them. */
139
+ export function parseFlashVars(value: string | null): Record<string, string> {
140
+ const vars: Record<string, string> = {};
141
+ for (const [name, text] of new URLSearchParams(value ?? "")) {
142
+ vars[name] = text;
143
+ }
144
+
145
+ return vars;
146
+ }
147
+
148
+ /**
149
+ * Whether a SWF from `swfUrl` may script its page, by allowScriptAccess as
150
+ * Flash read it: "always", "never", or by default "sameDomain", the SWF's
151
+ * origin the page's.
152
+ */
153
+ export function scriptAccess(value: string | null, swfUrl: string, pageUrl: string): boolean {
154
+ switch (value?.toLowerCase()) {
155
+ case "always":
156
+ return true;
157
+ case "never":
158
+ return false;
159
+ default:
160
+ try {
161
+ const origin = new URL(swfUrl, pageUrl).origin;
162
+ // An opaque origin ("null": data:, a sandboxed frame) is no one's domain, not even its own.
163
+ return origin !== "null" && origin === new URL(pageUrl).origin;
164
+ } catch {
165
+ return false;
166
+ }
167
+ }
168
+ }
169
+
170
+ /** The bytes of "WorkerDomain", the class a SWF's ActionScript names to start a worker. */
171
+ const WORKER_DOMAIN = new TextEncoder().encode("WorkerDomain");
172
+
173
+ /**
174
+ * Whether a SWF's ActionScript names WorkerDomain, in its ABCs' strings:
175
+ * one that does may start a worker and wait for it in the same script,
176
+ * which only a Web Worker started ahead can answer.
177
+ */
178
+ export function namesWorkers(swf: Swf): boolean {
179
+ const bytes = swf.bytes;
180
+ const first = WORKER_DOMAIN[0];
181
+ for (const tag of swf.tags) {
182
+ if (tag.code !== tags.DoABC && tag.code !== tags.DoABC2) {
183
+ continue;
184
+ }
185
+
186
+ const end = tag.offset + tag.length - WORKER_DOMAIN.length;
187
+ for (let at = bytes.indexOf(first, tag.offset); at !== -1 && at <= end; ) {
188
+ let k = 1;
189
+ while (k < WORKER_DOMAIN.length && bytes[at + k] === WORKER_DOMAIN[k]) {
190
+ k++;
191
+ }
192
+
193
+ if (k === WORKER_DOMAIN.length) {
194
+ return true;
195
+ }
196
+
197
+ at = bytes.indexOf(first, at + 1);
198
+ }
199
+ }
200
+
201
+ return false;
202
+ }
203
+
204
+ /**
205
+ * How long a SWF that names workers waits for the Web Workers started
206
+ * ahead before its first frame: past it, it plays on, and a worker it
207
+ * starts takes one still loading.
208
+ */
209
+ const READY_WAIT = 10_000;
210
+
211
+ /** A player's Web Workers, or none where their module does not load, as under an import map that does not name it. */
212
+ async function workersOrNone(ahead: boolean): Promise<WebWorkerHost | null> {
213
+ try {
214
+ return await workerHostForPlayer(ahead);
215
+ } catch (error) {
216
+ console.warn(`swf2es: workers are off, as their host did not load: ${error}`);
217
+ return null;
218
+ }
219
+ }
220
+
221
+ /** Flash's quality names; the auto ones as what they start at. */
222
+ function quality(value: string | null): string {
223
+ const named = (value ?? "high").toUpperCase();
224
+ if (named === "AUTOLOW") {
225
+ return "LOW";
226
+ }
227
+
228
+ return ["LOW", "MEDIUM", "HIGH", "BEST"].includes(named) ? named : "HIGH";
229
+ }
230
+
231
+ /** The SWF at `url`, by the embedder's fetch where it gave one, and the URL a redirect took it to. */
232
+ async function fetchMovie(
233
+ url: string,
234
+ signal: AbortSignal,
235
+ ): Promise<{ bytes: Uint8Array; url: string }> {
236
+ const fetchOf = configuration().fetch;
237
+ if (fetchOf) {
238
+ const result = await fetchOf(
239
+ { url, method: "GET", headers: [], body: null, purpose: "movie" },
240
+ signal,
241
+ );
242
+ if (!result.bytes) {
243
+ throw new Error(`swf2es: ${result.status} for ${url}`);
244
+ }
245
+
246
+ return { bytes: result.bytes, url: result.url ?? url };
247
+ }
248
+
249
+ const response = await fetch(url, { signal });
250
+ if (!response.ok) {
251
+ throw new Error(`swf2es: ${response.status} for ${url}`);
252
+ }
253
+
254
+ return { bytes: new Uint8Array(await response.arrayBuffer()), url: response.url || url };
255
+ }
256
+
257
+ /**
258
+ * What a session's SWFs load by: its AIR application's files, then the
259
+ * embedder's fetch or the browser's; `offline` (allowNetworking "none"),
260
+ * nothing past the application's own files, which are no network.
261
+ */
262
+ function fetchFor(
263
+ session: Session,
264
+ offline: boolean,
265
+ ): (request: FetchRequest, signal: AbortSignal) => Promise<FetchResult> {
266
+ const fetchOf: (request: FetchRequest, signal: AbortSignal) => Promise<FetchResult> = offline
267
+ ? () => Promise.reject(new Error("allowNetworking is none"))
268
+ : (configuration().fetch ?? browserFetch);
269
+ const app = session.air?.app;
270
+ if (!app) {
271
+ return fetchOf;
272
+ }
273
+
274
+ return (request, signal) => {
275
+ const local = app.fetch(request, session.air?.files);
276
+ if (!local) {
277
+ return fetchOf(request, signal);
278
+ }
279
+
280
+ // A file the application does not hold, from the directory it came from.
281
+ const remote = local.bytes ? null : app.remote(request.url);
282
+ return remote ? fetchOf({ ...request, url: remote }, signal) : Promise.resolve(local);
283
+ };
284
+ }
285
+
286
+ /** The host's fetch for what a SWF loads: the browser's, its status and headers as they come. */
287
+ async function browserFetch(request: FetchRequest, signal: AbortSignal): Promise<FetchResult> {
288
+ const response = await fetch(request.url, {
289
+ signal,
290
+ method: request.method,
291
+ headers: request.headers.map(([name, value]) => [name, value]),
292
+ body: request.body ? new Uint8Array(request.body).buffer : null,
293
+ });
294
+ const headers: [string, string][] = [];
295
+ response.headers.forEach((value, name) => {
296
+ headers.push([name, value]);
297
+ });
298
+
299
+ return {
300
+ bytes: response.ok ? new Uint8Array(await response.arrayBuffer()) : null,
301
+ status: response.status,
302
+ headers,
303
+ // Where a redirect took it: the SWF is judged and named by that.
304
+ ...(response.redirected ? { url: response.url } : {}),
305
+ };
306
+ }
307
+
308
+ /**
309
+ * Callback names the element refuses though it has no such property:
310
+ * protocols other code looks for on any object. A `then` would make the
311
+ * element a thenable, so that awaiting it, or Promise.resolve(it), would
312
+ * call into the SWF and hang; `toJSON` would answer JSON.stringify, and
313
+ * `handleEvent` would take every event the element is added as a listener for.
314
+ */
315
+ const RESERVED = new Set(["then", "toJSON", "handleEvent"]);
316
+
317
+ export class Swf2esPlayerElement extends ElementBase {
318
+ static readonly observedAttributes = [
319
+ "src",
320
+ "width",
321
+ "height",
322
+ "scale",
323
+ "salign",
324
+ "wmode",
325
+ "bgcolor",
326
+ "quality",
327
+ "menu",
328
+ ];
329
+
330
+ #session: Session | null = null;
331
+ #readiness = deferred();
332
+ /** The source the element last loaded, to tell a new src from the one playing. */
333
+ #loaded: string | null = null;
334
+ readonly #box: HTMLDivElement;
335
+ readonly #sizing: HTMLStyleElement;
336
+ /** The stage's size once a SWF is read, the element's own where the page gives it none. */
337
+ #stageSize: [number, number] | null = null;
338
+
339
+ constructor() {
340
+ super();
341
+ const shadow = this.attachShadow({ mode: "open" });
342
+ const style = document.createElement("style");
343
+ // :host's rules give way to the page's, which may size it as it likes.
344
+ style.textContent =
345
+ ":host { display: inline-block; position: relative; overflow: hidden; outline: none }" +
346
+ " .box { position: absolute; inset: 0; overflow: hidden }";
347
+ this.#sizing = document.createElement("style");
348
+ this.#box = document.createElement("div");
349
+ this.#box.className = "box";
350
+ shadow.append(style, this.#sizing, this.#box);
351
+ this.#size();
352
+ this.addEventListener("pointerdown", () => focus(this));
353
+ }
354
+
355
+ /** Resolves once the SWF loading, or the next one asked for, plays; rejects if it fails. */
356
+ get ready(): Promise<void> {
357
+ return this.#readiness.promise;
358
+ }
359
+
360
+ /** The player playing, for a host that needs more than the element gives; null before a load and after destroy. */
361
+ get player(): Player | null {
362
+ return this.#session?.player ?? null;
363
+ }
364
+
365
+ /**
366
+ * The WebGL context the player draws with, for a host that measures it (the demo site counts its
367
+ * draw calls); null before a load and after destroy. A lost context comes back as the same
368
+ * object, its extensions anew.
369
+ */
370
+ get gl(): WebGL2RenderingContext | null {
371
+ return this.#session?.playback?.gl ?? null;
372
+ }
373
+
374
+ get src(): string {
375
+ return attribute(this, "src") ?? "";
376
+ }
377
+
378
+ set src(value: string) {
379
+ setAttribute(this, "src", value);
380
+ }
381
+
382
+ connectedCallback(): void {
383
+ // Focusable, for the keys, as a plug-in's object was.
384
+ if (!hasAttribute(this, "tabindex")) {
385
+ setAttribute(this, "tabindex", "0");
386
+ }
387
+
388
+ const src = attribute(this, "src");
389
+ if (src && !this.#session) {
390
+ void this.#load(src);
391
+ }
392
+ }
393
+
394
+ disconnectedCallback(): void {
395
+ // Moved within the page, it is back by the time this runs; taken away, it stops.
396
+ queueMicrotask(() => {
397
+ if (!connected(this)) {
398
+ this.#destroy();
399
+ }
400
+ });
401
+ }
402
+
403
+ attributeChangedCallback(name: string, old: string | null, value: string | null): void {
404
+ if (old === value) {
405
+ return;
406
+ }
407
+
408
+ if (name === "src") {
409
+ if (value && connected(this) && value !== this.#loaded) {
410
+ void this.#load(value);
411
+ }
412
+
413
+ return;
414
+ }
415
+
416
+ if (name === "width" || name === "height") {
417
+ this.#size();
418
+ }
419
+
420
+ if (name === "quality" && this.#session?.player) {
421
+ this.#session.player.quality = quality(value);
422
+ }
423
+
424
+ if (name === "menu" && this.#session?.player) {
425
+ this.#session.player.showDefaultContextMenu = value?.toLowerCase() !== "false";
426
+ }
427
+
428
+ this.#session?.playback?.changed();
429
+ }
430
+
431
+ /**
432
+ * Play `source` in place of what plays now: a URL, relative to the page,
433
+ * or the SWF's bytes. Resolves once it plays, and rejects with what kept
434
+ * it from playing, as `ready` does; a load asked for before it played
435
+ * settles it in its place.
436
+ */
437
+ load(source: SwfSource): Promise<void> {
438
+ return this.#load(source);
439
+ }
440
+
441
+ /**
442
+ * Play `app`, an AIR application (`openAirApp`), in place of what plays
443
+ * now, as adl runs it: its descriptor's content SWF under AIR's API and
444
+ * its application sandbox, `args` its launch's arguments, this element
445
+ * its window. What it writes outside its directory is kept in IndexedDB
446
+ * by its id for the next time it plays, unless `keepFiles` is false.
447
+ * Resolves and rejects as `load` does. Its NativeApplication's exit stops
448
+ * it, and the element dispatches `airexit` with the code.
449
+ */
450
+ loadAir(
451
+ app: AirApp,
452
+ options: { arguments?: readonly string[]; keepFiles?: boolean } = {},
453
+ ): Promise<void> {
454
+ return this.#load(app, options.arguments ?? [], options.keepFiles ?? true);
455
+ }
456
+
457
+ #load(source: SwfSource | AirApp, args: readonly string[] = [], keep = true): Promise<void> {
458
+ this.#release();
459
+ if (this.#readiness.settled) {
460
+ this.#readiness = deferred();
461
+ }
462
+
463
+ const ready = this.#readiness;
464
+ const session: Session = {
465
+ scripting: null,
466
+ player: null,
467
+ playback: null,
468
+ stage3D: null,
469
+ callbacks: new Set(),
470
+ workers: null,
471
+ abort: new AbortController(),
472
+ air: null,
473
+ };
474
+ if (source instanceof AirApp) {
475
+ this.#playAsAir(session, source, args, keep);
476
+ }
477
+
478
+ this.#session = session;
479
+ this.#loaded = typeof source === "string" || source instanceof URL ? String(source) : null;
480
+ void this.#start(source instanceof AirApp ? null : source, session, ready);
481
+ return ready.promise;
482
+ }
483
+
484
+ /**
485
+ * `session` playing `app`, with `args` its launch's arguments and this
486
+ * element its window, its files kept in IndexedDB where `keep`.
487
+ */
488
+ #playAsAir(session: Session, app: AirApp, args: readonly string[], keep: boolean): void {
489
+ const exit = (code: number) => {
490
+ // After the script that called it, which a destroy would pull from under it.
491
+ queueMicrotask(() => {
492
+ if (this.#session === session) {
493
+ this.#destroy();
494
+ dispatch(this, new CustomEvent("airexit", { detail: { code } }));
495
+ }
496
+ });
497
+ };
498
+ const files = airFiles(app.descriptor.id, AIR_DIRECTORIES, keep);
499
+ const items = airItems(app.descriptor.id);
500
+ session.air = {
501
+ app,
502
+ application: app.application(elementWindow(this, app.descriptor.title), args, exit),
503
+ fileSystem: app.fileSystem(files.files),
504
+ files: files.files,
505
+ items: items.items,
506
+ release: () => {
507
+ files.release();
508
+ items.release();
509
+ },
510
+ };
511
+ }
512
+
513
+ async #start(source: SwfSource | null, session: Session, ready: Deferred): Promise<void> {
514
+ const current = () => this.#session === session;
515
+ try {
516
+ const pageUrl = document.baseURI;
517
+ const base = attribute(this, "base");
518
+ let bytes: Uint8Array;
519
+ let url: string;
520
+ if (session.air) {
521
+ // The content SWF, by the app: URL adl names it with.
522
+ const content = session.air.app.descriptor.content;
523
+ bytes = session.air.app.read(content) as Uint8Array;
524
+ url = `app:/${content.split("/").map(encodeURIComponent).join("/")}`;
525
+ } else if (source === null) {
526
+ throw new Error("swf2es: nothing to play");
527
+ } else if (typeof source === "string" || source instanceof URL) {
528
+ ({ bytes, url } = await fetchMovie(new URL(source, pageUrl).href, session.abort.signal));
529
+ } else {
530
+ // A copy: the page may reuse its buffer.
531
+ bytes = new Uint8Array(source instanceof Uint8Array ? source : new Uint8Array(source));
532
+ url = base ? new URL(base, pageUrl).href : pageUrl;
533
+ }
534
+
535
+ if (!current()) {
536
+ return;
537
+ }
538
+
539
+ const swf = readSwf(bytes);
540
+ // A SWF that names what only AIR has plays as an AIR application, as
541
+ // adl would run it, rather than fail as Flash Player's plugin does.
542
+ if (!session.air && !configuration().air && isAs3(swf) && namesAir(swf)) {
543
+ const app = airAppForSwf(bytes, url);
544
+ this.#playAsAir(session, app, [], true);
545
+ url = `app:/${encodeURIComponent(app.descriptor.content)}`;
546
+ }
547
+
548
+ // What the application wrote and kept when it last played, before it plays.
549
+ if (session.air) {
550
+ await Promise.all([session.air.files.ready, session.air.items.ready]);
551
+ if (!current()) {
552
+ return;
553
+ }
554
+ }
555
+
556
+ // An AIR application's window is the size its descriptor gives, where it gives one.
557
+ const descriptor = session.air?.app.descriptor;
558
+ this.#stageSize = [
559
+ descriptor?.width ?? Math.round((swf.frameSize.xMax - swf.frameSize.xMin) / 20),
560
+ descriptor?.height ?? Math.round((swf.frameSize.yMax - swf.frameSize.yMin) / 20),
561
+ ];
562
+ this.#size();
563
+ const scripted =
564
+ isAs3(swf) && swf.tags.some((t) => t.code === tags.DoABC || t.code === tags.DoABC2);
565
+ if (scripted) {
566
+ const [codegen, abcs] = await Promise.all([
567
+ codegenForPlayer(),
568
+ playerLibraries(session.air !== null || !!configuration().air),
569
+ ]);
570
+ if (!current()) {
571
+ return;
572
+ }
573
+
574
+ const host = this.#workers() ? await workersOrNone(namesWorkers(swf)) : null;
575
+ if (!current()) {
576
+ host?.release?.();
577
+ return;
578
+ }
579
+
580
+ session.workers = host;
581
+ session.scripting = this.#scripting(session, codegen, url, pageUrl, host);
582
+ const stage3D = configuration().stage3D;
583
+ if (stage3D) {
584
+ const { Stage3DSession } = await import("./stage3d.js");
585
+ if (!current()) {
586
+ return;
587
+ }
588
+
589
+ session.stage3D = new Stage3DSession(this.#box, session.scripting, stage3D, () =>
590
+ session.playback?.invalidate(),
591
+ );
592
+ }
593
+ await session.scripting.loadLibraries(abcs);
594
+ if (!current()) {
595
+ return;
596
+ }
597
+ }
598
+
599
+ // An AVM1 SWF's actions, compiled by the same codegen.
600
+ let avm1: Avm1 | null = null;
601
+ if (!isAs3(swf) && readActions(swf).blocks.length > 0) {
602
+ const codegen = await codegenForPlayer();
603
+ if (!current()) {
604
+ return;
605
+ }
606
+
607
+ // Its URL keys its SharedObjects, as a page's AS3 SWFs' are. Its
608
+ // fscommand, getURL and ExternalInterface reach the page as an AS3
609
+ // SWF's do: "quit" goes to the page, as a plug-in's did, and stops
610
+ // nothing.
611
+ const { internal, offline, allows, objectID } = this.#access(pageUrl);
612
+ const base = attribute(this, "base");
613
+ avm1 = new Avm1(codegen, {
614
+ url,
615
+ base: base ? new URL(base, pageUrl).href : undefined,
616
+ // XML, LoadVars and XMLSocket reach the network as an AS3 SWF's loads and sockets do.
617
+ fetch: fetchFor(session, offline),
618
+ socket: offline ? undefined : socketHost(),
619
+ sendToUrl: !internal,
620
+ onUncaught: (error) => this.#report(session, error),
621
+ // Asked of the calling SWF, as for an AS3 SWF: a child from another origin is not the main one.
622
+ fsCommand: (command, args, callers) => {
623
+ if (callers.every(allows)) {
624
+ this.#fsCommand(objectID, command, args);
625
+ }
626
+ },
627
+ navigate: internal ? null : undefined,
628
+ fileHost: configuration().fileHost,
629
+ externalInterface: this.#externalInterface(session, objectID, allows),
630
+ });
631
+ }
632
+
633
+ session.player = new Player(bytes, session.scripting, avm1);
634
+ session.player.quality = quality(attribute(this, "quality"));
635
+ session.player.showDefaultContextMenu = attribute(this, "menu")?.toLowerCase() !== "false";
636
+ session.player.build = configuration().build ?? null;
637
+ const playback = await Playback.create(
638
+ this.#box,
639
+ session.player,
640
+ session.scripting,
641
+ () => this.#look(),
642
+ (error) => this.#report(session, error),
643
+ session.stage3D,
644
+ );
645
+ if (!current()) {
646
+ playback.destroy();
647
+ return;
648
+ }
649
+
650
+ session.playback = playback;
651
+ // The workers started ahead, loaded before a script may wait for one;
652
+ // a script that never says it loaded does not keep the SWF from playing.
653
+ if (session.workers) {
654
+ await Promise.race([
655
+ session.workers.ready,
656
+ new Promise((done) => setTimeout(done, READY_WAIT)),
657
+ ]);
658
+ }
659
+ if (!current()) {
660
+ return;
661
+ }
662
+
663
+ await session.player.start();
664
+ if (!current()) {
665
+ return;
666
+ }
667
+
668
+ playback.run();
669
+ ready.resolve();
670
+ dispatch(this, new Event("load"));
671
+ } catch (error) {
672
+ if (!current()) {
673
+ return;
674
+ }
675
+
676
+ this.#release();
677
+ ready.reject(error);
678
+ dispatch(this, new CustomEvent("error", { detail: { error } }));
679
+ }
680
+ }
681
+
682
+ /** The scripting of a load from `url`, its ExternalInterface and fscommand the page's only for the SWFs it lets script it. */
683
+ #scripting(
684
+ session: Session,
685
+ codegen: Awaited<ReturnType<typeof codegenForPlayer>>,
686
+ url: string,
687
+ pageUrl: string,
688
+ workerHost: WorkerHost | null,
689
+ ): Scripting {
690
+ const { internal, offline, allows, objectID } = this.#access(pageUrl);
691
+ const base = attribute(this, "base");
692
+ const scripting = new Scripting(codegen, {
693
+ url,
694
+ base: base ? new URL(base, pageUrl).href : undefined,
695
+ parameters: parseFlashVars(attribute(this, "flashvars")),
696
+ fetch: fetchFor(session, offline),
697
+ loadPolicyFile: configuration().loadPolicyFile,
698
+ sandboxType: session.air ? "application" : configuration().sandboxType,
699
+ // An AIR application's: AIR's API, its application and its file system.
700
+ air: session.air !== null || !!configuration().air,
701
+ application: session.air?.application ?? configuration().air?.application,
702
+ fileSystem: session.air?.fileSystem ?? configuration().air?.fileSystem,
703
+ encryptedStore: session.air?.items ?? configuration().air?.encryptedStore,
704
+ socket: offline ? undefined : socketHost(),
705
+ webSocket: offline ? null : undefined,
706
+ navigate: internal ? null : undefined,
707
+ fileHost: configuration().fileHost,
708
+ sendToUrl: !internal,
709
+ externalInterface: this.#externalInterface(session, objectID, allows),
710
+ fsCommand: (command, args, callers) => {
711
+ if (callers.every(allows)) {
712
+ this.#fsCommand(objectID, command, args);
713
+ }
714
+ },
715
+ onUncaught: (error) => this.#report(session, error),
716
+ lazyCompilation: configuration().lazyCompilation,
717
+ workerHost,
718
+ ...moduleCacheOptions(),
719
+ });
720
+ return scripting;
721
+ }
722
+
723
+ /** Whether the SWFs the element plays next have workers: its `workers` attribute, else the page's configuration. */
724
+ #workers(): boolean {
725
+ switch (attribute(this, "workers")?.trim().toLowerCase()) {
726
+ case "false":
727
+ return false;
728
+ case "true":
729
+ return true;
730
+ default:
731
+ return configuration().workers !== false;
732
+ }
733
+ }
734
+
735
+ /** What the element's attributes let a SWF reach of its page and the network. */
736
+ #access(pageUrl: string): {
737
+ internal: boolean;
738
+ offline: boolean;
739
+ allows: (swfUrl: string) => boolean;
740
+ objectID: string | null;
741
+ } {
742
+ const access = attribute(this, "allowscriptaccess");
743
+ // Flash's allowNetworking: "internal" takes the page's scripting and
744
+ // navigation away, "none" every network access besides.
745
+ const networking = (attribute(this, "allownetworking") ?? "all").toLowerCase();
746
+ const internal = networking === "internal" || networking === "none";
747
+ return {
748
+ internal,
749
+ offline: networking === "none",
750
+ // Asked of the calling SWF, as Flash asked: a child from another origin is not the main SWF.
751
+ allows: (swfUrl) => !internal && scriptAccess(access, swfUrl, pageUrl),
752
+ objectID: idOf(this) || attribute(this, "name") || null,
753
+ };
754
+ }
755
+
756
+ /** The page's ExternalInterface for a load, an AS3 or an AVM1 SWF's alike, for the SWFs `allows` lets script it. */
757
+ #externalInterface(
758
+ session: Session,
759
+ objectID: string | null,
760
+ allows: (url: string) => boolean,
761
+ ): ExternalInterfaceHost {
762
+ const bridge: PageBridge = {
763
+ objectID,
764
+ callback: (name, call) => this.#callback(session, name, call),
765
+ alive: () => this.#session === session,
766
+ };
767
+ return externalInterfaceHost(bridge, (error) => this.#report(session, error), allows);
768
+ }
769
+
770
+ /** The SWF's callback `name` on the element, or taken off it, while its load is the one playing. */
771
+ #callback(
772
+ session: Session,
773
+ name: string,
774
+ call: ((...args: PageValue[]) => PageValue) | null,
775
+ ): void {
776
+ if (this.#session !== session) {
777
+ return;
778
+ }
779
+
780
+ if (call) {
781
+ // Never over what the element is or does, its own methods or the DOM's.
782
+ if ((name in this || RESERVED.has(name)) && !session.callbacks.has(name)) {
783
+ console.warn(
784
+ `swf2es: the SWF's ExternalInterface callback "${name}" is the element's own; left out`,
785
+ );
786
+ return;
787
+ }
788
+
789
+ Object.defineProperty(this, name, {
790
+ value: call,
791
+ configurable: true,
792
+ writable: true,
793
+ enumerable: false,
794
+ });
795
+ session.callbacks.add(name);
796
+ } else if (session.callbacks.delete(name)) {
797
+ Reflect.deleteProperty(this, name);
798
+ }
799
+ }
800
+
801
+ /** fscommand as Flash's plug-in delivered it, to the page's `<id>_DoFSCommand`, and as an event. */
802
+ #fsCommand(objectID: string | null, command: string, args: string): void {
803
+ dispatch(this, new CustomEvent("fscommand", { detail: { command, args } }));
804
+ const handler = objectID
805
+ ? (globalThis as Record<string, unknown>)[`${objectID}_DoFSCommand`]
806
+ : undefined;
807
+ if (typeof handler === "function") {
808
+ handler(command, args);
809
+ }
810
+ }
811
+
812
+ /** An error the SWF's code threw and nothing caught: told, as Flash's debugger told it, and played on. */
813
+ #report(session: Session, error: unknown): void {
814
+ let text: string;
815
+ try {
816
+ text = session.scripting ? session.scripting.rt.toString(error as never) : String(error);
817
+ } catch {
818
+ text = String(error);
819
+ }
820
+
821
+ console.error(`swf2es: ${text}`);
822
+ }
823
+
824
+ #look(): Look {
825
+ return {
826
+ scale: scaleMode(attribute(this, "scale")),
827
+ salign: attribute(this, "salign"),
828
+ wmode: (attribute(this, "wmode") ?? "window").toLowerCase(),
829
+ bgcolor: parseColor(attribute(this, "bgcolor")),
830
+ };
831
+ }
832
+
833
+ /** The element's size: its width and height attributes, else its SWF's stage, else Flash's default stage. */
834
+ #size(): void {
835
+ const [w, h] = this.#stageSize ?? [550, 400];
836
+ const width = cssLength(attribute(this, "width")) ?? `${w}px`;
837
+ const height = cssLength(attribute(this, "height")) ?? `${h}px`;
838
+ this.#sizing.textContent = `:host { width: ${width}; height: ${height} }`;
839
+ }
840
+
841
+ /**
842
+ * Stop the SWF and let go of everything it holds: its frames, sounds and
843
+ * audio device, its open sockets and fetches, the renderer and its GL
844
+ * context, the pointer, the keys, and its callbacks on the element. The
845
+ * element stays, and may load another.
846
+ */
847
+ destroy(): void {
848
+ this.#destroy();
849
+ }
850
+
851
+ #destroy(): void {
852
+ const loading = this.#session !== null && !this.#readiness.settled;
853
+ this.#release();
854
+ this.#loaded = null;
855
+ if (loading) {
856
+ this.#readiness.reject(new Error("swf2es: destroyed before it played"));
857
+ }
858
+ }
859
+
860
+ #release(): void {
861
+ const session = this.#session;
862
+ if (!session) {
863
+ return;
864
+ }
865
+
866
+ this.#session = null;
867
+ for (const name of session.callbacks) {
868
+ Reflect.deleteProperty(this, name);
869
+ }
870
+
871
+ session.callbacks.clear();
872
+ session.abort.abort();
873
+ session.playback?.destroy();
874
+ session.stage3D?.destroy();
875
+ session.player?.destroy();
876
+ session.scripting?.destroy();
877
+ // Its scripting let it go already, if it had any: a release counts once.
878
+ session.workers?.release?.();
879
+ session.air?.release();
880
+ this.#box.style.background = "";
881
+ }
882
+ }
883
+
884
+ /**
885
+ * Define the element as `name`, once; what a page or extension calls
886
+ * before using it, if index.js has not. Whether it is defined: not where
887
+ * there is no registry, as in node or an extension's isolated world,
888
+ * whose `customElements` is null.
889
+ */
890
+ export function defineElement(name = TAG): boolean {
891
+ const registry = (globalThis as { customElements?: CustomElementRegistry | null }).customElements;
892
+ if (typeof registry !== "object" || registry === null) {
893
+ return false;
894
+ }
895
+
896
+ if (!registry.get(name)) {
897
+ // A class of its own for each name: a registry takes a constructor once.
898
+ registry.define(name, class extends Swf2esPlayerElement {});
899
+ }
900
+
901
+ return true;
902
+ }