swf2js 0.1.0 → 0.1.2

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 (50) hide show
  1. package/README.md +9 -9
  2. package/package.json +3 -2
  3. package/src/cli.js +15 -6
  4. package/src/emitter/bundle-emitter.js +56 -16
  5. package/src/runtime/avm1-runtime.js +329 -84
  6. package/src/runtime/avm2-runtime.js +56 -6
  7. package/src/runtime/embedded-movie-runtime.js +6 -1
  8. package/src/runtime/index.js +2 -6
  9. package/src/runtime/movie-runtime.js +2 -1
  10. package/src/runtime/swflib/assemble.js +34 -0
  11. package/src/runtime/swflib/bitmap-image.js +4 -0
  12. package/src/runtime/swflib/bitmap.js +1004 -0
  13. package/src/runtime/swflib/builtins.js +156 -0
  14. package/src/runtime/swflib/bytearray.js +949 -0
  15. package/src/runtime/swflib/compiled-swf.js +3 -0
  16. package/src/runtime/swflib/context-menu.js +245 -0
  17. package/src/runtime/swflib/cursor-flag.js +12 -0
  18. package/src/runtime/swflib/dictionary.js +121 -0
  19. package/src/runtime/swflib/display.js +823 -0
  20. package/src/runtime/swflib/events.js +754 -0
  21. package/src/runtime/swflib/filters.js +298 -0
  22. package/src/runtime/swflib/flash.js +130 -0
  23. package/src/runtime/swflib/geom.js +759 -0
  24. package/src/runtime/swflib/glyph-metrics.js +14 -0
  25. package/src/runtime/swflib/graphics.js +735 -0
  26. package/src/runtime/swflib/host.js +2 -0
  27. package/src/runtime/swflib/inherit.js +22 -0
  28. package/src/runtime/swflib/input.js +1085 -0
  29. package/src/runtime/swflib/loader.js +687 -0
  30. package/src/runtime/swflib/marks.js +16 -0
  31. package/src/runtime/swflib/matrix3d.js +144 -0
  32. package/src/runtime/swflib/pointer-bridge.js +8 -0
  33. package/src/runtime/swflib/projection.js +158 -0
  34. package/src/runtime/swflib/render.js +1240 -0
  35. package/src/runtime/swflib/sound.js +1166 -0
  36. package/src/runtime/swflib/sprite-drag.js +116 -0
  37. package/src/runtime/swflib/stage-ref.js +9 -0
  38. package/src/runtime/swflib/stage.js +484 -0
  39. package/src/runtime/swflib/system.js +987 -0
  40. package/src/runtime/swflib/text-field.js +519 -0
  41. package/src/runtime/swflib/text-paint.js +797 -0
  42. package/src/runtime/swflib/text.js +1387 -0
  43. package/src/runtime/swflib/transform.js +133 -0
  44. package/src/runtime/swflib/xml.js +268 -0
  45. package/src/transpiler/avm1/avm1-ir.js +2 -1
  46. package/src/transpiler/avm1/avm1-rewrite.js +23 -2
  47. package/src/transpiler/avm1/avm1-transpiler.js +4 -1
  48. package/src/transpiler/avm2/avm2-transpiler.js +38 -7
  49. package/src/transpiler/timeline/timeline-codegen.js +366 -123
  50. package/src/runtime/swflib.js +0 -14050
package/README.md CHANGED
@@ -118,7 +118,7 @@ The output is self-contained ES2020 — class definitions, method bodies, and ru
118
118
  ### 3. Convert multiple movies for the browser
119
119
 
120
120
  ```bash
121
- node src/cli.js -o out Swf/*.swf
121
+ node src/cli.js -o out archive/Swf/*.swf
122
122
  ```
123
123
 
124
124
  ---
@@ -129,13 +129,13 @@ Open the generated `index.html` in a browser and keep its companion files and `a
129
129
 
130
130
  | File | Contents |
131
131
  |---|---|
132
- | `swflib.js` | Shared player with `__swoof_swflib.mountMovie(...)`, Flash APIs, AVM1 and AVM2 helpers, Canvas rendering, effects, input, and audio |
132
+ | `swoof.js` | Shared player with `__swoof_swflib.mountMovie(...)`, the `swoof.*` API, AVM1 and AVM2 helpers, Canvas rendering, effects, input, and audio. `--swoof split` writes the same modules into `swoof/` instead |
133
133
  | `timeline-data.js` | Frames, scene labels, symbols, and geometry. CLI output packs timelines at 8 MiB when packing saves space. |
134
134
  | `binary-data.js` | Original linked ByteArray payloads, retained for ActionScript code that reads or changes them |
135
135
  | `bundle.js` | One shared-player call with movie metadata, compiled ActionScript, and compact class and namespace metadata |
136
136
  | `assets/` | Images, sounds, and compiled embedded movies loaded on demand. Named children use paths such as `assets/preloader/preloader.js`. |
137
137
 
138
- Every conversion using the same transpiler sources emits the same `swflib.js`. Each folder includes a copy for direct file playback. A web server can use one shared copy for its generated pages. Packed timelines use gzip in a classic JavaScript sidecar and open directly from disk in browsers with `DecompressionStream` gzip support. Use `--plain-timeline` for older browsers or to inspect a large timeline as text.
138
+ The player source is the ES modules in `src/runtime/swflib/`. The default output bundles them into one `swoof.js` with no import statements, so a generated folder still opens from disk. `--swoof split` copies those modules into a `swoof/` folder and loads them from `swoof/boot.js`; that form needs a web server. Every conversion using the same transpiler sources emits the same player. Each folder includes a copy for playback. A web server can use one shared copy for its generated pages. Packed timelines use gzip in a classic JavaScript sidecar and open directly from disk in browsers with `DecompressionStream` gzip support. Use `--plain-timeline` for older browsers or to inspect a large timeline as text.
139
139
 
140
140
  The shared AVM2 runtime registers classes and methods, initializes activation slots, and caches ordered property keys from each compiled block's namespace table. Compiled AVM1 scripts use shared enumeration and string helpers.
141
141
 
@@ -154,7 +154,7 @@ These options are repeatable. Explicit mappings also accept complete HTTP(S) URL
154
154
  A source SWF can carry its local mappings in a sibling `<movie>.companions.json` file. The JSON object maps requested SWF URLs to paths inside the source directory. Explicit CLI mappings take precedence. Raze 2 uses this manifest to preserve its offline companion on ordinary rebuilds.
155
155
 
156
156
  ```sh
157
- node src/cli.js Swf/raze-2.swf
157
+ node src/cli.js archive/Swf/raze-2.swf
158
158
  ```
159
159
 
160
160
  AS3 `Loader.load` and AVM1 clip loading use these compiled companions, including with `--omit-embedded-swf-bytes`.
@@ -188,7 +188,7 @@ src/
188
188
  cfg-structurer.js # Control-flow graph → structured JS (while/if/else)
189
189
  actionscript.js # Coordinator: runs AVM1 + AVM2 transpilation
190
190
  util/ # Diagnostics, bit utilities
191
- Swf/ # Test corpus (27 Flash games)
191
+ archive/Swf/ # Test corpus (27 Flash games)
192
192
  ```
193
193
 
194
194
  ---
@@ -201,9 +201,9 @@ Swf/ # Test corpus (27 Flash games)
201
201
  | AVM1 ActionScript transpilation | ✅ |
202
202
  | AVM2 ActionScript 3 transpilation | ✅ |
203
203
  | CFG structured control flow | ✅ |
204
- | Timeline / display-list codegen | 🚧 In progress |
205
- | Shape → Canvas 2D rendering | 🚧 In progress |
206
- | Audio / sound playback | 🚧 In progress |
204
+ | Timeline / display-list codegen | ✅ |
205
+ | Shape → Canvas 2D rendering | ✅ |
206
+ | Audio / sound playback | ✅ |
207
207
  | HTML bundle output | Available through the CLI |
208
208
 
209
- **Capability matrix** (shapes, morphs, tweens, swflib W/P/S audit, corpus needs): see [SUPPORT.md](./SUPPORT.md).
209
+ **Capability matrix** (shapes, morphs, tweens, swflib)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swf2js",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "SWF-to-browser transpiler — converts compiled .swf files to self-contained HTML/JS bundles",
5
5
  "license": "SEE LICENSE IN LICENSE-GPL",
6
6
  "type": "module",
@@ -13,7 +13,6 @@
13
13
  "test:integration": "vitest --run --config vitest.integration.config.js"
14
14
  },
15
15
  "devDependencies": {
16
- "acorn": "^8.0.0",
17
16
  "fast-check": "^3.0.0",
18
17
  "vitest": "^2.0.0"
19
18
  },
@@ -21,6 +20,8 @@
21
20
  "node": ">=20.0.0"
22
21
  },
23
22
  "dependencies": {
23
+ "acorn": "^8.19.0",
24
+ "esbuild": "^0.21.5",
24
25
  "lzma-js": "^1.0.1"
25
26
  }
26
27
  }
package/src/cli.js CHANGED
@@ -15,7 +15,7 @@ import { emit, backgroundFromTags } from './emitter/bundle-emitter.js';
15
15
  import { DiagnosticsCollector } from './util/diagnostics.js';
16
16
  import { Logger } from './util/logger.js';
17
17
 
18
- const VERSION = '0.1.0';
18
+ const VERSION = '0.1.2';
19
19
 
20
20
  // --- Argument parsing ---
21
21
  const args = process.argv.slice(2);
@@ -36,6 +36,7 @@ const opts = {
36
36
  verbose: false,
37
37
  warnUnknown: false,
38
38
  inspect: false, // --inspect: pretty-print parse output instead of transpiling
39
+ swoof: 'file',
39
40
  timelineDataMode: 'auto',
40
41
  omitEmbeddedSwfBytes: false,
41
42
  companionSwfUrls: [],
@@ -55,6 +56,13 @@ for (let i = 0; i < args.length; i++) {
55
56
  opts.inspect = true;
56
57
  } else if (args[i] === '--actionscript') {
57
58
  opts.actionscript = true;
59
+ } else if (args[i] === '--swoof') {
60
+ const mode = args[++i];
61
+ if (mode !== 'file' && mode !== 'split') {
62
+ process.stderr.write('swoof: --swoof requires file or split\n');
63
+ process.exit(1);
64
+ }
65
+ opts.swoof = mode;
58
66
  } else if (args[i] === '--pack-timeline') {
59
67
  opts.timelineDataMode = 'packed';
60
68
  } else if (args[i] === '--plain-timeline') {
@@ -167,7 +175,7 @@ for (const filePath of inputFiles) {
167
175
  outParent,
168
176
  diag,
169
177
  { usedNames: usedBundleNames, externalTimelineData: true, timelineDataMode: opts.timelineDataMode,
170
- omitEmbeddedSwfBytes: opts.omitEmbeddedSwfBytes }
178
+ omitEmbeddedSwfBytes: opts.omitEmbeddedSwfBytes, swoof: opts.swoof }
171
179
  );
172
180
  flushDiags();
173
181
 
@@ -193,7 +201,7 @@ for (const filePath of inputFiles) {
193
201
  process.exit(anyFailed ? 1 : 0);
194
202
 
195
203
  /**
196
- * Expand CLI inputs: literal paths plus glob patterns (e.g. Swf/*.swf).
204
+ * Expand CLI inputs: literal paths plus glob patterns (e.g. archive/Swf/*.swf).
197
205
  * Shell may already expand globs; we still expand so quoted patterns work.
198
206
  * @param {string[]} patterns
199
207
  * @returns {string[]}
@@ -238,14 +246,15 @@ swoof ${VERSION} — SWF-to-browser transpiler
238
246
 
239
247
  Usage:
240
248
  swf2js [options] <file.swf> [file.swf ...]
241
- swf2js [options] <glob> e.g. Swf/*.swf
249
+ swf2js [options] <glob> e.g. archive/Swf/*.swf
242
250
 
243
251
  By default each SWF writes a folder next to that file (same directory):
244
- swf2js demos/neon-grid.swf → demos/neon-grid/index.html + bundle.js + assets/
245
- swf2js demos/*.swf → demos/<name>/ for each match
252
+ swf2js demos/neon-grid.swf → demos/neon-grid/index.html + swoof.js + bundle.js + assets/
253
+ swf2js archive/Swf/*.swf → archive/Swf/<name>/ for each match
246
254
 
247
255
  Options:
248
256
  --output-dir, -o <path> Parent directory for output folders (default: beside each SWF)
257
+ --swoof file|split Player as one swoof.js (default) or modules in swoof/
249
258
  --inspect Pretty-print parse output instead of emitting
250
259
  --actionscript Print transpiled ActionScript JS to stdout
251
260
  --pack-timeline Pack timeline data even for small movies (default: auto at 8 MiB)
@@ -3,15 +3,16 @@
3
3
  * for a transpiled SWF.
4
4
  */
5
5
 
6
- import { mkdirSync, writeFileSync, rmSync } from 'fs';
7
- import { basename, join } from 'path';
6
+ import { cpSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'fs';
7
+ import { basename, dirname, join } from 'path';
8
+ import { fileURLToPath } from 'url';
8
9
  import { createHash } from 'node:crypto';
9
10
  import { encodeBitmap, encodeSound, encodeSoundStreamSegments } from './asset-encoder.js';
10
11
  import { encodeBrowserFont } from './font-encoder.js';
11
12
  import { encodeTimelineDataScript, openPackedTimeline } from './timeline-data-codec.js';
12
13
  import { companionSwfKey, embeddedSwfFactorySource } from './embedded-swf.js';
13
14
  import { AVM1_RUNTIME_BOOTSTRAP, AVM1_RUNTIME_FACTORY_SOURCE, AVM1_RUNTIME_STUB, SWFLIB_SOURCE } from '../runtime/index.js';
14
- import { AVM2_RUNTIME_BOOTSTRAP, AVM2_RUNTIME_STUB } from '../runtime/avm2-runtime.js';
15
+ import { AVM2_RUNTIME_BOOTSTRAP, AVM2_RUNTIME_STUB, createAvm2Runtime } from '../runtime/avm2-runtime.js';
15
16
  import { createEmbeddedMovieRuntime } from '../runtime/embedded-movie-runtime.js';
16
17
  import { installMovieRuntime } from '../runtime/movie-runtime.js';
17
18
  import { decodeTag } from '../decoder/tag-decoder.js';
@@ -124,8 +125,9 @@ export function emit(input, swfPath, outputDir, diagnostics, opts = {}) {
124
125
  const externalBinaryData = externalTimelineData && binaryPayloads.length > 0;
125
126
 
126
127
  const title = basename(swfPath).replace(/\.swf$/i, '');
128
+ const swoof = opts.swoof === 'split' ? 'split' : 'file';
127
129
  const html = buildHtml({ title, stageW, stageH, backgroundColor, externalTimelineData, externalBinaryData,
128
- packedTimelineData: !!timelineDataScript?.packed });
130
+ packedTimelineData: !!timelineDataScript?.packed, swoof });
129
131
  const bundleJs = buildBundleJs({
130
132
  stageW,
131
133
  stageH,
@@ -148,12 +150,14 @@ export function emit(input, swfPath, outputDir, diagnostics, opts = {}) {
148
150
 
149
151
  const htmlPath = join(bundleDir, 'index.html');
150
152
  const jsPath = join(bundleDir, 'bundle.js');
151
- const swflibPath = join(bundleDir, 'swflib.js');
152
153
  const timelineDataPath = externalTimelineData ? join(bundleDir, 'timeline-data.js') : null;
153
154
  const binaryDataPath = externalBinaryData ? join(bundleDir, 'binary-data.js') : null;
154
155
  writeFileSync(htmlPath, html, 'utf8');
155
156
  writeFileSync(jsPath, bundleJs, 'utf8');
156
- writeFileSync(swflibPath, sharedPlayerSource(), 'utf8');
157
+ rmSync(join(bundleDir, 'swflib.js'), { force: true });
158
+ const swflibPath = swoof === 'split'
159
+ ? writeSplitPlayer(bundleDir, { externalTimelineData, externalBinaryData, packedTimelineData: !!timelineDataScript?.packed })
160
+ : writeBundledPlayer(bundleDir);
157
161
  if (timelineDataPath) writeFileSync(timelineDataPath, timelineDataScript.source, 'utf8');
158
162
 
159
163
  if (binaryDataPath) {
@@ -174,9 +178,13 @@ export function emit(input, swfPath, outputDir, diagnostics, opts = {}) {
174
178
  };
175
179
  }
176
180
 
177
- function sharedPlayerSource() {
178
- return `${SWFLIB_SOURCE}
179
- globalThis.__swoof_swflib.createAvm1Runtime = ${AVM1_RUNTIME_FACTORY_SOURCE};
181
+ const playerModuleDir = join(dirname(fileURLToPath(import.meta.url)), '../runtime/swflib');
182
+
183
+ function playerBindings(includeAvm2) {
184
+ const avm2 = includeAvm2
185
+ ? `globalThis.__swoof_swflib.createAvm2Runtime = ${createAvm2Runtime.toString()};\n`
186
+ : '';
187
+ return `${avm2}globalThis.__swoof_swflib.createAvm1Runtime = ${AVM1_RUNTIME_FACTORY_SOURCE};
180
188
  globalThis.__swoof_swflib.timelineHelpers = ${timelineHelpersSource()};
181
189
  globalThis.__swoof_swflib.createTimelineEngine = ${timelineEngineFactorySource()};
182
190
  globalThis.__swoof_swflib.createEmbeddedMovieRuntime = ${createEmbeddedMovieRuntime.toString()};
@@ -185,6 +193,36 @@ globalThis.__swoof_swflib.openPackedTimeline = ${openPackedTimeline.toString()};
185
193
  `;
186
194
  }
187
195
 
196
+ function sharedPlayerSource() {
197
+ return `${SWFLIB_SOURCE}\n${playerBindings(false)}`;
198
+ }
199
+
200
+ function writeBundledPlayer(bundleDir) {
201
+ rmSync(join(bundleDir, 'swoof'), { recursive: true, force: true });
202
+ const path = join(bundleDir, 'swoof.js');
203
+ writeFileSync(path, sharedPlayerSource(), 'utf8');
204
+ return path;
205
+ }
206
+
207
+ function writeSplitPlayer(bundleDir, movie) {
208
+ rmSync(join(bundleDir, 'swoof.js'), { force: true });
209
+ const outDir = join(bundleDir, 'swoof');
210
+ rmSync(outDir, { recursive: true, force: true });
211
+ mkdirSync(outDir, { recursive: true });
212
+ for (const name of readdirSync(playerModuleDir)) {
213
+ if (!name.endsWith('.js') || name === 'assemble.js') continue;
214
+ cpSync(join(playerModuleDir, name), join(outDir, name));
215
+ }
216
+ const loads = [];
217
+ if (movie.externalBinaryData) loads.push('../binary-data.js');
218
+ if (movie.externalTimelineData) loads.push('../timeline-data.js');
219
+ if (!movie.packedTimelineData) loads.push('../bundle.js');
220
+ const boot = `import './builtins.js';\n${playerBindings(true)}${loads.map(path => `await import(${JSON.stringify(path)});`).join('\n')}\n`;
221
+ const path = join(outDir, 'boot.js');
222
+ writeFileSync(path, boot, 'utf8');
223
+ return path;
224
+ }
225
+
188
226
  function bundledActionScript(actionScript) {
189
227
  const source = (actionScript.fullJs || '').replace(AVM1_RUNTIME_STUB, () => AVM1_RUNTIME_BOOTSTRAP);
190
228
  return actionScript.avm2Blocks?.length ? source.replace(AVM2_RUNTIME_STUB, () => AVM2_RUNTIME_BOOTSTRAP) : source;
@@ -446,17 +484,19 @@ function writeMovieAssets(tags, symbolTable, displayList, assetsDir, assetPrefix
446
484
  }
447
485
 
448
486
  /**
449
- * @param {{ title: string, stageW: number, stageH: number, backgroundColor: string, includeSwflib?: boolean, externalTimelineData?: boolean, externalBinaryData?: boolean, packedTimelineData?: boolean }} opts
487
+ * @param {{ title: string, stageW: number, stageH: number, backgroundColor: string, swoof?: 'file'|'split', externalTimelineData?: boolean, externalBinaryData?: boolean, packedTimelineData?: boolean }} opts
450
488
  * @returns {string}
451
489
  */
452
490
  function buildHtml(opts) {
453
491
  const { title, stageW, stageH, backgroundColor,
454
- externalTimelineData, externalBinaryData, packedTimelineData } = opts;
455
- const scriptFiles = ['swflib.js',
456
- ...(externalBinaryData ? ['binary-data.js'] : []),
457
- ...(externalTimelineData ? ['timeline-data.js'] : []),
458
- ...(packedTimelineData ? [] : ['bundle.js'])];
459
- const scripts = scriptFiles.map(file => ` <script src="${file}"></script>`).join('\n');
492
+ externalTimelineData, externalBinaryData, packedTimelineData, swoof } = opts;
493
+ const scriptFiles = swoof === 'split'
494
+ ? [{ src: 'swoof/boot.js', module: true }]
495
+ : ['swoof.js',
496
+ ...(externalBinaryData ? ['binary-data.js'] : []),
497
+ ...(externalTimelineData ? ['timeline-data.js'] : []),
498
+ ...(packedTimelineData ? [] : ['bundle.js'])].map(src => ({ src, module: false }));
499
+ const scripts = scriptFiles.map(file => ` <script${file.module ? ' type="module"' : ''} src="${file.src}"></script>`).join('\n');
460
500
  return `<!DOCTYPE html>
461
501
  <html lang="en">
462
502
  <head>