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
@@ -0,0 +1,3 @@
1
+ /** Byte arrays that carry a compiled SWF. Shared by the loader and ByteArray. */
2
+ export var compiledSwfEntries = new WeakSet();
3
+ export var compiledSwfByteArrays = new WeakMap();
@@ -0,0 +1,245 @@
1
+ import { ContextMenuEvent, EventDispatcher } from './events.js';
2
+ import { ColorTransform, copyColorTransform } from './geom.js';
3
+ import { Transform } from './transform.js';
4
+ import { global } from './host.js';
5
+ import { stageSingleton } from './stage.js';
6
+
7
+ export class ContextMenuBuiltInItems {
8
+ constructor() {
9
+ this.forwardAndBack = this.loop = this.play = this.print = this.quality = this.rewind = this.save = this.zoom = true;
10
+ }
11
+ }
12
+
13
+ export class ContextMenu extends EventDispatcher {
14
+ constructor() {
15
+ super();
16
+ this.customItems = [];
17
+ this.builtInItems = new ContextMenuBuiltInItems();
18
+ }
19
+
20
+ hideBuiltInItems() {
21
+ for (var name in this.builtInItems) this.builtInItems[name] = false;
22
+ }
23
+
24
+ clone() {
25
+ var menu = new ContextMenu();
26
+ Object.assign(menu.builtInItems, this.builtInItems);
27
+ menu.customItems = this.customItems.map(function (item) { return item && typeof item.clone === 'function' ? item.clone() : item; });
28
+ return menu;
29
+ }
30
+ }
31
+ ContextMenu.isSupported = typeof document !== 'undefined';
32
+
33
+ export class ContextMenuItem extends EventDispatcher {
34
+ constructor(caption, separatorBefore, enabled, visible) {
35
+ super();
36
+ if (typeof caption === 'function' || (caption == null && typeof separatorBefore === 'string')) {
37
+ this.onSelect = caption;
38
+ this.caption = separatorBefore || '';
39
+ this.separatorBefore = false;
40
+ } else {
41
+ this.caption = caption == null ? '' : String(caption);
42
+ this.separatorBefore = !!separatorBefore;
43
+ }
44
+ this.enabled = enabled !== false;
45
+ this.visible = visible !== false;
46
+ }
47
+
48
+ clone() {
49
+ return new ContextMenuItem(this.caption, this.separatorBefore, this.enabled, this.visible);
50
+ }
51
+ }
52
+
53
+ export var activeContextMenu = null;
54
+ export function closeContextMenu(restoreFocus) {
55
+ if (!activeContextMenu) return;
56
+ var previous = activeContextMenu;
57
+ activeContextMenu = null;
58
+ document.removeEventListener('pointerdown', previous.outside, true);
59
+ if (typeof window !== 'undefined') {
60
+ window.removeEventListener?.('blur', previous.dismiss);
61
+ window.removeEventListener?.('resize', previous.dismiss);
62
+ }
63
+ previous.element.remove();
64
+ if (restoreFocus) previous.focus?.focus?.({ preventScroll: true });
65
+ }
66
+
67
+ export function openContextMenu(canvas, event, menu, owner, mouseTarget, avm1) {
68
+ if (typeof document === 'undefined' || !document.body || !document.createElement) return false;
69
+ closeContextMenu(false);
70
+ try {
71
+ if (avm1) menu.onSelect?.(owner, menu);
72
+ else menu.dispatchEvent(new ContextMenuEvent(ContextMenuEvent.MENU_SELECT, false, false, mouseTarget, owner));
73
+ } catch (error) { if (typeof console !== 'undefined') console.warn('swoof: context menu', error); }
74
+
75
+ var rows = [], defaultRows = [], captions = new Set();
76
+ var timeline = global.__swoof?.timeline;
77
+ var defaults = menu.builtInItems || {};
78
+ function builtIn(name, caption, select, checked) {
79
+ if (defaults[name]) defaultRows.push({ caption: caption, select: select, checked: checked });
80
+ }
81
+ if (timeline) {
82
+ builtIn('play', 'Play', function () { if (timeline.playing) timeline.stop(); else timeline.play(); }, !!timeline.playing);
83
+ builtIn('loop', 'Loop', function () { timeline.loop = !timeline.loop; }, !!timeline.loop);
84
+ builtIn('rewind', 'Rewind', function () { timeline.gotoAndStop(1); });
85
+ var forwardAndBack = avm1 ? 'forward_back' : 'forwardAndBack';
86
+ builtIn(forwardAndBack, 'Forward', function () { timeline.nextFrame(); });
87
+ builtIn(forwardAndBack, 'Back', function () { timeline.prevFrame(); });
88
+ }
89
+ if (defaults.quality) {
90
+ for (var quality of ['low', 'medium', 'high']) {
91
+ defaultRows.push({ caption: quality[0].toUpperCase() + quality.slice(1) + ' quality', checked: stageSingleton.quality === quality,
92
+ select: (function (value) { return function () { stageSingleton.quality = value; }; })(quality) });
93
+ }
94
+ }
95
+ function captionKey(caption) { return caption.toLowerCase().replace(/[^\p{L}\p{N}]/gu, ''); }
96
+ for (var row of defaultRows) captions.add(captionKey(row.caption));
97
+ for (var item of Array.isArray(menu.customItems) ? menu.customItems : []) {
98
+ if (rows.length >= 15) break;
99
+ if (!item) continue;
100
+ var caption = String(item.caption ?? '').replace(/[\x00-\x1f\x7f]/g, ' ').trim();
101
+ if (!caption || caption.length > 100) continue;
102
+ var key = captionKey(caption);
103
+ if (key && captions.has(key)) continue;
104
+ captions.add(key);
105
+ if (item.visible === false) continue;
106
+ rows.push({ caption: caption, disabled: item.enabled === false, separator: item.separatorBefore,
107
+ select: (function (selected) { return function () {
108
+ if (avm1) selected.onSelect?.(owner, selected);
109
+ else selected.dispatchEvent?.(new ContextMenuEvent(ContextMenuEvent.MENU_ITEM_SELECT, false, false, mouseTarget, owner));
110
+ }; })(item) });
111
+ }
112
+ if (rows.length && defaultRows.length) defaultRows[0].separator = true;
113
+ rows.push(...defaultRows);
114
+ if (!rows.length) return false;
115
+
116
+ var element = document.createElement('div'), buttons = [];
117
+ element.setAttribute('role', 'menu');
118
+ element.setAttribute('aria-label', 'Game commands');
119
+ element.tabIndex = -1;
120
+ Object.assign(element.style, { position: 'fixed', zIndex: '2147483647', padding: '4px', color: '#171717', background: '#fff',
121
+ border: '1px solid #aaa', borderRadius: '4px', boxShadow: '0 4px 14px #0004', font: '13px system-ui',
122
+ maxWidth: 'calc(100vw - 8px)', maxHeight: 'calc(100vh - 8px)', overflow: 'auto' });
123
+ function addRow(row) {
124
+ if (row.separator && element.children.length) {
125
+ var separator = document.createElement('hr');
126
+ separator.setAttribute('role', 'separator');
127
+ Object.assign(separator.style, { border: '0', borderTop: '1px solid #ddd', margin: '3px 0' });
128
+ element.appendChild(separator);
129
+ }
130
+ var button = document.createElement('button');
131
+ button.type = 'button';
132
+ button.tabIndex = -1;
133
+ button.disabled = !!row.disabled;
134
+ button.setAttribute('role', row.checked === undefined ? 'menuitem' : 'menuitemcheckbox');
135
+ if (row.checked !== undefined) button.setAttribute('aria-checked', String(row.checked));
136
+ button.textContent = row.checked ? '✓ ' + row.caption : row.caption;
137
+ Object.assign(button.style, { display: 'block', width: '100%', padding: '5px 12px', textAlign: 'left', font: 'inherit',
138
+ background: 'transparent', border: '0', color: row.disabled ? '#777' : 'inherit', overflowWrap: 'anywhere' });
139
+ button.addEventListener('click', function () {
140
+ closeContextMenu(true);
141
+ try { row.select(); } catch (error) { if (typeof console !== 'undefined') console.warn('swoof: context menu item', error); }
142
+ });
143
+ button.addEventListener('pointerenter', function () { if (!button.disabled) button.focus({ preventScroll: true }); });
144
+ element.appendChild(button);
145
+ if (!button.disabled) buttons.push(button);
146
+ }
147
+ rows.forEach(addRow);
148
+ element.addEventListener('keydown', function (e) {
149
+ if (e.key === 'Tab') { closeContextMenu(true); return; }
150
+ var index = buttons.indexOf(document.activeElement);
151
+ if (e.key === 'Escape') closeContextMenu(true);
152
+ else if (e.key === 'Home') buttons[0]?.focus();
153
+ else if (e.key === 'End') buttons[buttons.length - 1]?.focus();
154
+ else if (e.key === 'ArrowDown') buttons[(index + 1) % buttons.length]?.focus();
155
+ else if (e.key === 'ArrowUp') buttons[(Math.max(index, 0) - 1 + buttons.length) % buttons.length]?.focus();
156
+ else return;
157
+ e.preventDefault();
158
+ });
159
+ var before = document.activeElement;
160
+ var stageBounds = canvas.getBoundingClientRect();
161
+ var keyboard = event.button !== 2 && !event.clientX && !event.clientY;
162
+ var left = keyboard ? stageBounds.left + stageBounds.width / 2 : event.clientX;
163
+ var top = keyboard ? stageBounds.top + stageBounds.height / 2 : event.clientY;
164
+ document.body.appendChild(element);
165
+ var bounds = element.getBoundingClientRect();
166
+ element.style.left = Math.max(0, Math.min(left || 0, (global.innerWidth || stageBounds.right) - bounds.width)) + 'px';
167
+ element.style.top = Math.max(0, Math.min(top || 0, (global.innerHeight || stageBounds.bottom) - bounds.height)) + 'px';
168
+ var outside = function (e) { if (!element.contains(e.target)) closeContextMenu(false); };
169
+ var dismiss = function () { closeContextMenu(false); };
170
+ activeContextMenu = { element: element, focus: before === document.body ? canvas : before, outside: outside, dismiss: dismiss };
171
+ document.addEventListener('pointerdown', outside, true);
172
+ if (typeof window !== 'undefined') {
173
+ window.addEventListener?.('blur', dismiss);
174
+ window.addEventListener?.('resize', dismiss);
175
+ }
176
+ (buttons[0] || element).focus({ preventScroll: true });
177
+ event.preventDefault();
178
+ return true;
179
+ }
180
+
181
+ // AS2 Color (timeline tint) — not installed on globalThis; AVM2 games often
182
+ // define their own `class Color extends ColorTransform`.
183
+ export class As2Color {
184
+ constructor(target) {
185
+ this._target = target && typeof target === 'object' ? target : null;
186
+ }
187
+
188
+ setRGB(rgb) {
189
+ if (!this._target) return;
190
+ var transform = this._currentTransform();
191
+ transform.color = rgb;
192
+ this._applyTransform(transform);
193
+ }
194
+
195
+ getRGB() {
196
+ if (this._target) return this._currentTransform().color;
197
+ }
198
+
199
+ _currentTransform() {
200
+ var target = this._target;
201
+ var color = target._swoofAvm1ColorTransform || target.transform?._colorTransform || target.colorTransform;
202
+ return color ? copyColorTransform(color) : new ColorTransform();
203
+ }
204
+
205
+ _applyTransform(transform) {
206
+ var target = this._target;
207
+ target._swoofAvm1ColorTransform = transform;
208
+ if (!target.transform) target.transform = new Transform();
209
+ if (target.transform._owner !== target) target.transform.colorTransform = transform;
210
+ target.colorTransform = transform;
211
+ }
212
+
213
+ setTransform(value) {
214
+ if (!this._target || !value) return;
215
+ if (value instanceof ColorTransform) {
216
+ this._applyTransform(copyColorTransform(value));
217
+ return;
218
+ }
219
+ var transform = this._currentTransform();
220
+ var channels = ['red', 'green', 'blue', 'alpha'];
221
+ var components = ['r', 'g', 'b', 'a'];
222
+ for (var i = 0; i < channels.length; i++) {
223
+ var mult = components[i] + 'a', offset = components[i] + 'b';
224
+ if (Object.prototype.hasOwnProperty.call(value, mult)) {
225
+ transform[channels[i] + 'Multiplier'] = (+value[mult] * 256 / 100 << 16 >> 16) / 256;
226
+ }
227
+ if (Object.prototype.hasOwnProperty.call(value, offset)) {
228
+ transform[channels[i] + 'Offset'] = +value[offset] << 16 >> 16;
229
+ }
230
+ }
231
+ this._applyTransform(transform);
232
+ }
233
+
234
+ getTransform() {
235
+ if (!this._target) return undefined;
236
+ var color = this._currentTransform();
237
+ return {
238
+ ra: color.redMultiplier * 100, rb: color.redOffset,
239
+ ga: color.greenMultiplier * 100, gb: color.greenOffset,
240
+ ba: color.blueMultiplier * 100, bb: color.blueOffset,
241
+ aa: color.alphaMultiplier * 100, ab: color.alphaOffset,
242
+ };
243
+ }
244
+ }
245
+
@@ -0,0 +1,12 @@
1
+ let onCursorFlagChange = function () {};
2
+ export function setCursorFlagChange(fn) { onCursorFlagChange = fn; }
3
+
4
+ export function cursorFlag(field, fallback) {
5
+ return {
6
+ get: function () { return this[field] ?? fallback; },
7
+ set: function (value) {
8
+ this[field] = !!value;
9
+ onCursorFlagChange(this);
10
+ },
11
+ };
12
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * flash.utils.Dictionary — identity-keyed map with optional weak object keys.
3
+ * Constructed as a class; instances are Proxies so `dict[key]` and AVM2
4
+ * property ops share the same storage as `.get` / `.set`.
5
+ */
6
+ export class Dictionary {
7
+ constructor(weakKeys = false) {
8
+ const strong = new Map();
9
+ let weak = weakKeys ? new WeakMap() : null;
10
+ // Numeric cursor shared by hasnext / nextname / nextvalue. Deleted
11
+ // positions are never reused while an enumeration might still hold them.
12
+ const entries = new Map();
13
+ let lastIndex = 0;
14
+ const registry = weak && typeof WeakRef === 'function' && typeof FinalizationRegistry === 'function'
15
+ ? new FinalizationRegistry((entry) => {
16
+ if (entries.get(entry.index) === entry) entries.delete(entry.index);
17
+ })
18
+ : null;
19
+
20
+ const table = (key) =>
21
+ weak && key !== null && (typeof key === 'object' || typeof key === 'function') ? weak : strong;
22
+
23
+ const entryKey = (entry) => (entry.ref ? entry.ref.deref() : entry.key);
24
+
25
+ const nextIndex = (index) => {
26
+ if (!entries.size) return 0;
27
+ while (index < lastIndex) {
28
+ const entry = entries.get(++index);
29
+ if (entry && (!entry.ref || entry.ref.deref() !== undefined)) return index;
30
+ }
31
+ return 0;
32
+ };
33
+
34
+ const api = {
35
+ get(k) { return table(k).get(k)?.value; },
36
+ set(k, v) {
37
+ const map = table(k);
38
+ const previous = map.get(k);
39
+ if (previous) previous.value = v;
40
+ else {
41
+ const entry = map === strong
42
+ ? { key: k }
43
+ : typeof WeakRef === 'function' ? { ref: new WeakRef(k) } : null;
44
+ if (entry) {
45
+ entry.index = ++lastIndex;
46
+ entries.set(entry.index, entry);
47
+ if (registry && entry.ref) registry.register(k, entry, entry);
48
+ }
49
+ map.set(k, { entry, value: v });
50
+ }
51
+ return v;
52
+ },
53
+ delete(k) {
54
+ const map = table(k);
55
+ const record = map.get(k);
56
+ if (record?.entry) {
57
+ if (registry && record.entry.ref) registry.unregister(record.entry);
58
+ entries.delete(record.entry.index);
59
+ }
60
+ return map.delete(k);
61
+ },
62
+ clear() {
63
+ if (registry) for (const entry of entries.values()) if (entry.ref) registry.unregister(entry);
64
+ entries.clear();
65
+ strong.clear();
66
+ if (weak) weak = new WeakMap();
67
+ },
68
+ hasOwnProperty(k) { return table(k).has(k); },
69
+ };
70
+
71
+ Object.defineProperties(api, {
72
+ weakKeys: { value: !!weakKeys, enumerable: true, configurable: true },
73
+ __swoofDictionary: { value: true },
74
+ _swoofNextIndex: { value: nextIndex },
75
+ _swoofNextName: {
76
+ value(index) {
77
+ const entry = entries.get(index);
78
+ return entry && entryKey(entry);
79
+ },
80
+ },
81
+ _swoofNextValue: {
82
+ value(index) {
83
+ const entry = entries.get(index);
84
+ if (!entry) return undefined;
85
+ const key = entryKey(entry);
86
+ return entry.ref && key === undefined ? undefined : api.get(key);
87
+ },
88
+ },
89
+ _getEntries: {
90
+ value() {
91
+ const result = [];
92
+ for (let index = nextIndex(0); index; index = nextIndex(index)) {
93
+ const key = entryKey(entries.get(index));
94
+ result.push([key, api.get(key)]);
95
+ }
96
+ return result;
97
+ },
98
+ },
99
+ });
100
+
101
+ Object.setPrototypeOf(api, Dictionary.prototype);
102
+ return new Proxy(api, {
103
+ get(t, p) {
104
+ if (p in t) return t[p];
105
+ return api.get(p);
106
+ },
107
+ set(t, p, v) {
108
+ if (p in t && typeof t[p] === 'function') return true;
109
+ api.set(p, v);
110
+ return true;
111
+ },
112
+ has(t, p) { return p in t || api.hasOwnProperty(p); },
113
+ deleteProperty(t, p) {
114
+ const descriptor = Object.getOwnPropertyDescriptor(t, p);
115
+ if (descriptor && !descriptor.configurable) return false;
116
+ api.delete(p);
117
+ return true;
118
+ },
119
+ });
120
+ }
121
+ }