swf2js 0.1.1 → 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 +2 -1
  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,133 @@
1
+ import { displayObjectMatrix, displayScaleProperty, displayTreePixelBounds, readDisplayScale } from './display.js';
2
+ import { StageQuality } from './events.js';
3
+ import { ColorTransform, Matrix, Rectangle, copyColorTransform } from './geom.js';
4
+ import { isStage, stageRef } from './stage-ref.js';
5
+
6
+ export class Transform {
7
+ constructor(owner) {
8
+ this._owner = owner || null;
9
+ this._matrix = new Matrix();
10
+ this._matrixExplicit = false;
11
+ this._colorTransform = new ColorTransform();
12
+ this.matrix3D = null;
13
+ this._perspectiveProjection = null;
14
+ this._bindMatrix(this._matrix);
15
+ }
16
+
17
+ _bindMatrix(matrix) {
18
+ var self = this;
19
+ matrix._changeListener = function (field) {
20
+ if (matrix !== self._matrix) return;
21
+ self._matrixExplicit = true;
22
+ self._syncOwnerFromMatrix(field);
23
+ };
24
+ }
25
+
26
+ _syncOwnerFromMatrix(field, useLayoutScale) {
27
+ var owner = this._owner, m = this._matrix;
28
+ if (!owner || !m) return;
29
+ if (field === 'tx' || field === 'ty') {
30
+ owner[field === 'tx' ? 'x' : 'y'] = m[field];
31
+ if (this._affineParts) return;
32
+ }
33
+ if (!field) { owner.x = m.tx; owner.y = m.ty; }
34
+ var xAngle = Math.atan2(m.b, m.a), yAngle = Math.atan2(-m.c, m.d);
35
+ var scaleX = useLayoutScale ? 'scaleX' : displayScaleProperty(owner, 'scaleX');
36
+ var scaleY = useLayoutScale ? 'scaleY' : displayScaleProperty(owner, 'scaleY');
37
+ this._affineParts = {
38
+ rotation: owner.rotation = xAngle * 180 / Math.PI,
39
+ scaleX: owner[scaleX] = Math.hypot(m.a, m.b),
40
+ scaleY: owner[scaleY] = Math.hypot(m.c, m.d),
41
+ skew: yAngle - xAngle,
42
+ };
43
+ }
44
+
45
+ _setMatrix(value, useLayoutScale) {
46
+ if (value != null) this.matrix3D = null;
47
+ this._matrix = value instanceof Matrix ? value : value ? new Matrix(value.a, value.b, value.c, value.d, value.tx, value.ty) : new Matrix();
48
+ this._matrixExplicit = true;
49
+ this._bindMatrix(this._matrix);
50
+ this._syncOwnerFromMatrix(null, useLayoutScale);
51
+ }
52
+
53
+ get matrix() {
54
+ if (this.matrix3D != null) return null;
55
+ var owner = this._owner, m = this._matrix;
56
+ if (owner) {
57
+ var rotation = +owner.rotation || 0;
58
+ var scaleX = readDisplayScale(owner, 'scaleX');
59
+ var scaleY = readDisplayScale(owner, 'scaleY');
60
+ var parts = this._affineParts;
61
+ if (!parts || parts.rotation !== rotation || parts.scaleX !== scaleX) {
62
+ var xAngle = rotation * Math.PI / 180;
63
+ m._a = Math.cos(xAngle) * scaleX; m._b = Math.sin(xAngle) * scaleX;
64
+ }
65
+ if (!parts || parts.rotation !== rotation || parts.scaleY !== scaleY) {
66
+ var yAngle = rotation * Math.PI / 180 + (parts?.skew || 0);
67
+ m._c = -Math.sin(yAngle) * scaleY; m._d = Math.cos(yAngle) * scaleY;
68
+ }
69
+ if (parts) {
70
+ parts.rotation = rotation;
71
+ parts.scaleX = scaleX;
72
+ parts.scaleY = scaleY;
73
+ }
74
+ m._tx = +owner.x || 0; m._ty = +owner.y || 0;
75
+ }
76
+ return m;
77
+ }
78
+
79
+ set matrix(value) { this._setMatrix(value, false); }
80
+
81
+ get perspectiveProjection() {
82
+ return this._perspectiveProjection || stageRef.defaultPerspective(this._owner);
83
+ }
84
+
85
+ set perspectiveProjection(value) { this._perspectiveProjection = value ?? null; }
86
+
87
+ get concatenatedColorTransform() {
88
+ var combined = new ColorTransform();
89
+ combined.concat(this._colorTransform);
90
+ for (var node = this._owner?.parent; node; node = node.parent) {
91
+ combined.concat(node.transform?._colorTransform || node.colorTransform);
92
+ }
93
+ return combined;
94
+ }
95
+
96
+ get concatenatedMatrix() {
97
+ var local = this.matrix || this._matrix;
98
+ var combined = local.clone();
99
+ var owner = this._owner;
100
+ if (!owner) return combined;
101
+ var node = owner.parent;
102
+ for (; node && !isStage(node); node = node.parent) {
103
+ combined.concat(displayObjectMatrix(node));
104
+ }
105
+ if (node) {
106
+ var canvas = node === stageRef.current && typeof document !== 'undefined' && document.getElementById?.('stage');
107
+ var view = canvas && canvas.getBoundingClientRect?.();
108
+ if (view && canvas.width && canvas.height) {
109
+ combined.concat(new Matrix(view.width / canvas.width, 0, 0,
110
+ view.height / canvas.height, view.left, view.top));
111
+ }
112
+ return combined;
113
+ }
114
+ // Flash exposes the local matrix at the stage's quality-dependent scale while detached.
115
+ var quality = (isStage(owner) ? owner : stageRef.current)?.quality;
116
+ var scale = quality === StageQuality.LOW ? 20 : quality === StageQuality.MEDIUM ? 10 : 5;
117
+ return new Matrix(local.a * scale, local.b, local.c, local.d * scale, local.tx, local.ty);
118
+ }
119
+
120
+ get pixelBounds() {
121
+ return displayTreePixelBounds(this._owner) || new Rectangle();
122
+ }
123
+ }
124
+
125
+ Object.defineProperty(Transform.prototype, 'colorTransform', {
126
+ enumerable: true, configurable: true,
127
+ get: function () { return copyColorTransform(this._colorTransform); },
128
+ set: function (value) {
129
+ if (value == null) throw new TypeError('Error #2007: Parameter colorTransform must be non-null.');
130
+ this._colorTransform = copyColorTransform(value);
131
+ if (this._owner) this._owner._colorTransform = this._colorTransform;
132
+ },
133
+ });
@@ -0,0 +1,268 @@
1
+ export function xmlRoot(source, defaultXmlNamespace) {
2
+ if (typeof DOMParser === 'undefined') return null;
3
+ var wrapped = defaultXmlNamespace && !/^\s*<\?xml[\s?]/i.test(source);
4
+ if (wrapped) {
5
+ var uri = defaultXmlNamespace.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
6
+ source = '<swoof-xml xmlns="' + uri + '">' + source + '</swoof-xml>';
7
+ }
8
+ var root = new DOMParser().parseFromString(source, 'application/xml').documentElement;
9
+ if (!root || root.namespaceURI === 'http://www.mozilla.org/newlayout/xml/parsererror.xml') return null;
10
+ if (!wrapped) return root;
11
+ var nodes = Array.from(root.childNodes || []).filter(function (node) {
12
+ return node.nodeType !== 3 || node.textContent.trim();
13
+ });
14
+ return nodes.length === 1 ? nodes[0] : null;
15
+ }
16
+
17
+ export function XML(value, defaultXmlNamespace) {
18
+ if (!(this instanceof XML)) return value instanceof XML ? value : new XML(value, defaultXmlNamespace);
19
+ this._xmlSource = value == null ? '' : value instanceof XML ? value.toXMLString() : String(value);
20
+ this._xmlNode = value instanceof XML && value._xmlNode ? value._xmlNode.cloneNode(true) : xmlRoot(this._xmlSource, defaultXmlNamespace);
21
+ }
22
+ export function xmlValue(node) {
23
+ var xml = Object.create(XML.prototype);
24
+ xml._xmlNode = node;
25
+ return xml;
26
+ }
27
+ XML.prototype.toString = function () {
28
+ var node = this._xmlNode;
29
+ if (!node) return this._xmlSource;
30
+ if (node.nodeType === 2) return node.value;
31
+ return Array.from(node.childNodes || []).some(function (child) { return child.nodeType === 1; })
32
+ ? this.toXMLString() : node.textContent;
33
+ };
34
+ XML.prototype.toXMLString = function () {
35
+ var node = this._xmlNode;
36
+ if (!node) return this._xmlSource;
37
+ if (node.nodeType === 2) {
38
+ var entities = { '&': '&amp;', '<': '&lt;', '"': '&quot;', '\n': '&#xA;', '\r': '&#xD;', '\t': '&#x9;' };
39
+ return node.value.replace(/[&<"\n\r\t]/g, function (char) { return entities[char]; });
40
+ }
41
+ return typeof XMLSerializer === 'undefined' ? this._xmlSource : new XMLSerializer().serializeToString(node);
42
+ };
43
+
44
+ export function XMLList(value, defaultXmlNamespace) {
45
+ if (!(this instanceof XMLList)) return value instanceof XMLList ? value : new XMLList(value, defaultXmlNamespace);
46
+ var nodes = value instanceof XMLList ? value._xmlNodes.slice() :
47
+ value instanceof XML ? (value._xmlNode ? [value._xmlNode] : []) : [];
48
+ if (value != null && !(value instanceof XML || value instanceof XMLList)) {
49
+ var root = xmlRoot('<xml-list>' + String(value) + '</xml-list>', defaultXmlNamespace);
50
+ if (root) nodes = Array.from(root.childNodes);
51
+ }
52
+ setXmlListNodes(this, nodes);
53
+ }
54
+ export function setXmlListNodes(list, nodes) {
55
+ Object.defineProperty(list, '_xmlNodes', { value: nodes });
56
+ for (var i = 0; i < nodes.length; i++) list[i] = xmlValue(nodes[i]);
57
+ }
58
+ XMLList.prototype._swoofSetXmlIndex = function (index, value) {
59
+ if (!(value instanceof XML) || !value._xmlNode) {
60
+ this[index] = value;
61
+ return value;
62
+ }
63
+ var position = Math.min(index, this._xmlNodes.length);
64
+ this._xmlNodes[position] = value._xmlNode;
65
+ this[position] = value;
66
+ return value;
67
+ };
68
+ XMLList.prototype.length = function () { return this._xmlNodes.length; };
69
+ XMLList.prototype.toString = function () {
70
+ if (this._xmlNodes.length > 1 && this._xmlNodes.some(function (node) { return node.nodeType === 1; })) return this.toXMLString();
71
+ var list = this;
72
+ return this._xmlNodes.map(function (_, i) { return String(list[i]); }).join('');
73
+ };
74
+ XMLList.prototype.toXMLString = function () {
75
+ var list = this;
76
+ return this._xmlNodes.map(function (_, i) { return list[i].toXMLString(); }).join('\n');
77
+ };
78
+
79
+ export function xmlMatches(node, selector) {
80
+ if (node.namespaceURI === 'http://www.w3.org/2000/xmlns/') return false;
81
+ if (selector.name !== '*' && node.localName !== selector.name) return false;
82
+ return selector.uris.includes(null) || selector.uris.includes(node.namespaceURI || '');
83
+ }
84
+ export function xmlMatchesUnder(element, selector, descendants, result) {
85
+ if (element.nodeType !== 1) return;
86
+ var children = Array.from(element.childNodes || []);
87
+ if (selector.attribute || !descendants) {
88
+ var candidates = selector.attribute ? Array.from(element.attributes) : children;
89
+ for (var node of candidates) if (xmlMatches(node, selector)) result.push(node);
90
+ }
91
+ if (descendants) {
92
+ for (var child of children) {
93
+ if (!selector.attribute && xmlMatches(child, selector)) result.push(child);
94
+ if (child.nodeType === 1) xmlMatchesUnder(child, selector, true, result);
95
+ }
96
+ }
97
+ }
98
+
99
+ export function xmlProperty(receiver, operation, selector, value) {
100
+ var nodes = receiver instanceof XMLList ? receiver._xmlNodes : receiver._xmlNode ? [receiver._xmlNode] : [];
101
+ if (operation === 'get' || operation === 'descendants') {
102
+ var result = [];
103
+ for (var node of nodes) xmlMatchesUnder(node, selector, operation === 'descendants', result);
104
+ var list = Object.create(XMLList.prototype);
105
+ setXmlListNodes(list, result);
106
+ return list;
107
+ }
108
+ if (operation === 'set' && nodes.length > 1) throw new TypeError('Cannot assign a property on a multi-item XMLList');
109
+ for (var element of nodes) {
110
+ if (element.nodeType !== 1) continue;
111
+ var matches = [];
112
+ xmlMatchesUnder(element, selector, false, matches);
113
+ if (operation === 'delete') {
114
+ for (var match of matches) {
115
+ if (selector.attribute) element.removeAttributeNode(match);
116
+ else element.removeChild(match);
117
+ }
118
+ } else if (selector.attribute) {
119
+ var text = value instanceof XMLList ? Array.from(value._xmlNodes, function (_, i) { return String(value[i]); }).join(' ') : String(value);
120
+ if (matches.length) {
121
+ matches[0].value = text;
122
+ for (var i = 1; i < matches.length; i++) element.removeAttributeNode(matches[i]);
123
+ } else if (selector.name !== '*') {
124
+ var uri = selector.uris[0] || null;
125
+ var prefix = selector.prefix || (uri && element.lookupPrefix(uri));
126
+ element.setAttributeNS(uri, prefix ? prefix + ':' + selector.name : selector.name, text);
127
+ } else throw new TypeError('Cannot create an unnamed XML attribute');
128
+ } else {
129
+ if (selector.name === '*' || value instanceof XML || value instanceof XMLList) {
130
+ throw new TypeError('Wildcard and XML child replacement are unsupported');
131
+ }
132
+ var child = matches[0];
133
+ if (!child) {
134
+ var uri = selector.uris[0] || null;
135
+ child = element.ownerDocument.createElementNS(uri, selector.name);
136
+ element.appendChild(child);
137
+ }
138
+ child.textContent = String(value);
139
+ for (var i = 1; i < matches.length; i++) element.removeChild(matches[i]);
140
+ }
141
+ }
142
+ return operation === 'delete' ? true : value;
143
+ }
144
+ export function xmlParent(node) {
145
+ var parent = node?.ownerElement || node?.parentNode;
146
+ return parent?.nodeType === 1 ? parent : null;
147
+ }
148
+ XML.prototype.parent = function () {
149
+ var parent = xmlParent(this._xmlNode);
150
+ return parent ? xmlValue(parent) : undefined;
151
+ };
152
+ XMLList.prototype.parent = function () {
153
+ var parent = xmlParent(this._xmlNodes[0]);
154
+ return parent && this._xmlNodes.every(function (node) { return xmlParent(node) === parent; })
155
+ ? xmlValue(parent) : undefined;
156
+ };
157
+ XML.prototype.children = XMLList.prototype.children = function () {
158
+ return xmlProperty(this, 'get', { name: '*', uris: [null], attribute: false });
159
+ };
160
+ XML.prototype.attribute = XMLList.prototype.attribute = function (name) {
161
+ var qualified = name && typeof name === 'object' && 'localName' in name && 'uri' in name;
162
+ return xmlProperty(this, 'get', { name: qualified ? name.localName : String(name), uris: [qualified ? name.uri : name === '*' ? null : ''], attribute: true });
163
+ };
164
+ XML.prototype._swoofXmlName = function () {
165
+ return this._xmlNode?.localName ? [this._xmlNode.namespaceURI || '', this._xmlNode.localName] : null;
166
+ };
167
+ XMLList.prototype._swoofXmlName = function () {
168
+ if (this._xmlNodes.length !== 1) throw new TypeError('XMLList.name requires exactly one item');
169
+ return this[0]._swoofXmlName();
170
+ };
171
+ export function* xmlNamespaceDeclarations(node) {
172
+ for (var attribute of node?.attributes || []) {
173
+ if (attribute.namespaceURI !== 'http://www.w3.org/2000/xmlns/') continue;
174
+ yield [attribute.prefix === 'xmlns' ? attribute.localName : '', attribute.value];
175
+ }
176
+ }
177
+ export function* xmlScopedNamespaces(node) {
178
+ var prefixes = new Set();
179
+ for (var element = node?.nodeType === 1 ? node : xmlParent(node); element; element = xmlParent(element)) {
180
+ for (var namespace of xmlNamespaceDeclarations(element)) {
181
+ if (prefixes.has(namespace[0])) continue;
182
+ prefixes.add(namespace[0]);
183
+ yield namespace;
184
+ }
185
+ }
186
+ }
187
+ XML.prototype._swoofXmlNamespace = function (prefix) {
188
+ var node = this._xmlNode;
189
+ if (!arguments.length) {
190
+ return node && (node.nodeType === 1 || node.nodeType === 2)
191
+ ? [node.prefix || '', node.namespaceURI || ''] : null;
192
+ }
193
+ prefix = String(prefix);
194
+ for (var namespace of xmlScopedNamespaces(node)) {
195
+ if (namespace[0] === prefix) return namespace;
196
+ }
197
+ return undefined;
198
+ };
199
+ XMLList.prototype._swoofXmlNamespace = function (...args) {
200
+ if (this._xmlNodes.length !== 1) throw new TypeError('XMLList.namespace requires exactly one item');
201
+ return this[0]._swoofXmlNamespace(...args);
202
+ };
203
+ XML.prototype._swoofXmlNamespaces = function (declarationsOnly) {
204
+ var node = this._xmlNode;
205
+ if (!declarationsOnly) {
206
+ var scope = Array.from(xmlScopedNamespaces(node));
207
+ return scope.length ? scope : [['', '']];
208
+ }
209
+ var inherited = Array.from(xmlScopedNamespaces(xmlParent(node)));
210
+ return Array.from(xmlNamespaceDeclarations(node)).filter(function ([prefix, uri]) {
211
+ if (!prefix && !uri) return false;
212
+ return !inherited.some(function ([parentPrefix, parentUri]) {
213
+ return parentUri === uri && (!prefix || prefix === parentPrefix);
214
+ });
215
+ });
216
+ };
217
+ XMLList.prototype._swoofXmlNamespaces = function (declarationsOnly) {
218
+ if (this._xmlNodes.length !== 1) throw new TypeError('XMLList namespace enumeration requires exactly one item');
219
+ return this[0]._swoofXmlNamespaces(declarationsOnly);
220
+ };
221
+ export function xmlNeedsNamespace(element, prefix, uri, local) {
222
+ if (!local && Array.from(xmlNamespaceDeclarations(element)).some(function (entry) { return entry[0] === prefix; })) return false;
223
+ if ((element.prefix || '') === prefix && (element.namespaceURI || '') === uri) return true;
224
+ for (var attribute of element.attributes || []) {
225
+ if (prefix && attribute.prefix === prefix && attribute.namespaceURI === uri) return true;
226
+ }
227
+ return Array.from(element.childNodes || []).some(function (child) {
228
+ return child.nodeType === 1 && xmlNeedsNamespace(child, prefix, uri, false);
229
+ });
230
+ }
231
+ export function xmlRemoveNamespace(element, prefix, uri) {
232
+ for (var attribute of Array.from(element.attributes || [])) {
233
+ if (attribute.namespaceURI !== 'http://www.w3.org/2000/xmlns/' || attribute.value !== uri) continue;
234
+ var declared = attribute.prefix === 'xmlns' ? attribute.localName : '';
235
+ if (prefix !== undefined && declared !== prefix) continue;
236
+ if (!xmlNeedsNamespace(element, declared, uri, true)) element.removeAttributeNode(attribute);
237
+ break;
238
+ }
239
+ for (var child of element.childNodes || []) {
240
+ if (child.nodeType === 1) xmlRemoveNamespace(child, prefix, uri);
241
+ }
242
+ }
243
+ XML.prototype._swoofMutateXmlNamespace = function (add, prefix, uri) {
244
+ var element = this._xmlNode;
245
+ if (element?.nodeType !== 1) return this;
246
+ if (!add) {
247
+ xmlRemoveNamespace(element, prefix, uri);
248
+ } else if (prefix !== undefined && (prefix || element.namespaceURI)) {
249
+ var previous = this._swoofXmlNamespace(prefix)?.[1] ?? '';
250
+ if (previous === uri || !xmlNeedsNamespace(element, prefix, previous, true)) {
251
+ element.setAttributeNS('http://www.w3.org/2000/xmlns/', prefix ? 'xmlns:' + prefix : 'xmlns', uri);
252
+ }
253
+ }
254
+ return this;
255
+ };
256
+ XMLList.prototype._swoofMutateXmlNamespace = function (...args) {
257
+ if (this._xmlNodes.length !== 1) throw new TypeError('XMLList namespace mutation requires exactly one item');
258
+ return this[0]._swoofMutateXmlNamespace(...args);
259
+ };
260
+ XML.prototype._swoofXmlProperty = XMLList.prototype._swoofXmlProperty = function (operation, selector, value) {
261
+ return xmlProperty(this, operation, selector, value);
262
+ };
263
+
264
+ // Legacy XMLDocument retains its source-only serialization API.
265
+ export function XMLDocument(value) { this._xmlSource = value == null ? '' : String(value); }
266
+ XMLDocument.prototype = Object.create(XML.prototype);
267
+ XMLDocument.prototype.constructor = XMLDocument;
268
+
@@ -28,7 +28,8 @@ export function buildPreloadAliases(flags) {
28
28
  const aliases = new Map();
29
29
  let reg = 1;
30
30
  if (flags & DF2.PRELOAD_THIS) aliases.set(reg++, 'this');
31
- if (flags & DF2.PRELOAD_ARGUMENTS) aliases.set(reg++, 'Array.prototype.slice.call(arguments)');
31
+ // Flash arguments keep .callee (mx.utils.Delegate, etc.). A plain slice loses it.
32
+ if (flags & DF2.PRELOAD_ARGUMENTS) aliases.set(reg++, '_avm1PreloadArguments(arguments, _avm1Function)');
32
33
  if (flags & DF2.PRELOAD_SUPER) aliases.set(reg++, '_avm1Super(this, _avm1Function)');
33
34
  if (flags & DF2.PRELOAD_ROOT) aliases.set(reg++, 'root');
34
35
  if (flags & DF2.PRELOAD_PARENT) aliases.set(reg++, '(this.parent || root)');
@@ -17,6 +17,10 @@ export function rewriteAvm1Js(js, opts = {}) {
17
17
  // Collapse dead temps
18
18
  out = out.replace(/var (_t\d+) = ([^;]+);\n(\s*)\1;/g, '$3$2;');
19
19
 
20
+ // The package objects exist before the script runs. A fixed name is a property.
21
+ out = out.replace(/_pkg\("flash"\)/g, 'globals.swoof');
22
+ out = out.replace(/_pkg\("mx"\)/g, 'globals.mx');
23
+
20
24
  // Pass 1 already resolves scope aliases. A generated binding such as
21
25
  // `_this` may be a local, and quoted AVM1 names need their original spelling.
22
26
  out = out.replace(/\barguments\.([a-zA-Z_$][\w$]*)/g, 'root.$1');
@@ -36,6 +40,7 @@ export function rewriteAvm1Js(js, opts = {}) {
36
40
 
37
41
  // _setMember(base, "prop", val) → base.prop = val
38
42
  out = rewriteSetMembers(out);
43
+ out = rewritePackageMembers(out);
39
44
 
40
45
  // Number(x) around literals
41
46
  out = out.replace(/(?<![\w$.])Number\((-?\d+(?:\.\d+)?)\)/g, '$1');
@@ -154,7 +159,8 @@ function rewriteCallMethods(src) {
154
159
  'getDepth', 'getBytesLoaded', 'getBytesTotal', 'attachMovie',
155
160
  'createEmptyMovieClip',
156
161
  ]);
157
- const knownRecv =
162
+ const packageRecv = /^globals\.(?:swoof|mx)(?:\.[A-Za-z_$][\w$]*)*$/.test(recv);
163
+ const knownRecv = packageRecv ||
158
164
  recv === 'Math' ||
159
165
  /^(?:this|root|_r\d+|Mouse|Key|Stage|globals)(?:\.[a-zA-Z_$][\w$]*)*$/.test(recv);
160
166
 
@@ -162,6 +168,8 @@ function rewriteCallMethods(src) {
162
168
  out += `_callMethod(${recv}, null, [${args}])`;
163
169
  } else if (recv === 'Math' && /^[a-zA-Z_$][\w$]*$/.test(method)) {
164
170
  out += `Math.${method}(${args})`;
171
+ } else if (packageRecv && /^[a-zA-Z_$][\w$]*$/.test(method)) {
172
+ out += `${recv}.${method}?.(${args})`;
165
173
  } else if (knownRecv && SAFE_CLIP_METHODS.has(method)) {
166
174
  // Optional chain: nested receivers like root.s_se / this.p1 are often
167
175
  // missing until their PlaceObject frame — bare `.gotoAndPlay` throws.
@@ -235,7 +243,8 @@ function rewriteSetMembers(src) {
235
243
  let afterCall = close + 1;
236
244
  if (src[afterCall] === ';') afterCall++;
237
245
 
238
- if ((base === 'this' || base === 'root') && !isAvm1DisplayMemberName(prop) && /^[a-zA-Z_$][\w$]*$/.test(prop)) {
246
+ const packageBase = /^globals\.(?:swoof|mx)(?:\.[A-Za-z_$][\w$]*)*$/.test(base);
247
+ if ((packageBase || base === 'this' || base === 'root') && !isAvm1DisplayMemberName(prop) && /^[a-zA-Z_$][\w$]*$/.test(prop)) {
239
248
  out += `${base}.${prop} = ${val};`;
240
249
  } else {
241
250
  out += `_setMember(${base}, ${JSON.stringify(prop)}, ${val}, this);`;
@@ -245,6 +254,18 @@ function rewriteSetMembers(src) {
245
254
  return out;
246
255
  }
247
256
 
257
+ /** `_member(globals.swoof, "display")` → `globals.swoof.display`. Clip fields stay lookups. */
258
+ function rewritePackageMembers(src) {
259
+ const member = /_member\((globals\.(?:swoof|mx)(?:\.[A-Za-z_$][\w$]*)*), "([A-Za-z_$][\w$]*)"\)/g;
260
+ let out = src;
261
+ for (let i = 0; i < 8; i++) {
262
+ const next = out.replace(member, '$1.$2');
263
+ if (next === out) return out;
264
+ out = next;
265
+ }
266
+ return out;
267
+ }
268
+
248
269
  /** Find a top-level delimiter while ignoring nested expressions and strings. */
249
270
  function findTopLevelDelimiter(src, start, delimiters) {
250
271
  const wanted = new Set(delimiters);
@@ -1514,7 +1514,10 @@ class Avm1Context {
1514
1514
  const inner = name
1515
1515
  ? `function ${safeName}(${params.join(', ')}) {\n var _constantPool = _capturedConstantPool.slice();\n${head}${indent(body)}\n}`
1516
1516
  : `function (${params.join(', ')}) {\n var _constantPool = _capturedConstantPool.slice();\n${head}${indent(body)}\n}`;
1517
- const fnExpr = this._captureFunction(inner, bodyCtx._needsTargetBase, flags & DF2.PRELOAD_SUPER);
1517
+ // PRELOAD_ARGUMENTS needs the function identity so .callee can point at it
1518
+ // (strict JS forbids arguments.callee; Flash Delegate relies on the property).
1519
+ const fnExpr = this._captureFunction(inner, bodyCtx._needsTargetBase,
1520
+ flags & (DF2.PRELOAD_SUPER | DF2.PRELOAD_ARGUMENTS));
1518
1521
 
1519
1522
  if (name) {
1520
1523
  this.lines.push(`var ${safeName} = ${fnExpr};`);
@@ -14,6 +14,7 @@
14
14
 
15
15
  import { AbcReader } from './abc-reader.js';
16
16
  import { DiagnosticsCollector } from '../../util/diagnostics.js';
17
+ import { hasSwoofBuiltin } from '../../runtime/swflib/flash.js';
17
18
  import { structureCfg } from '../cfg-structurer.js';
18
19
 
19
20
  // Multiname kinds that pop runtime components from the operand stack
@@ -387,16 +388,17 @@ export function transpileAvm2(abcData, diagnostics, opts = {}) {
387
388
  const superRaw = superMn?.localName || null;
388
389
  const superQualified = _avm2TypeTraitName(superMn, superRaw, methodTableName);
389
390
  const hasSuper = Boolean(superQualified && superQualified !== 'Object');
390
- // Resolve via _getlex so flash.utils.ByteArray / swflib builtins work even when
391
- // the bare identifier is not a lexical binding (ReferenceError on `extends ByteArray`).
391
+ const superBinding = swoofBuiltinBinding(superMn);
392
+ // Unqualified player classes are page globals. Anything else is resolved when
393
+ // the class statement runs, because the name may be a movie class.
392
394
  const nativeSuperNames = new Set(['Sprite', 'MovieClip', 'Shape', 'Bitmap', 'DisplayObject',
393
395
  'DisplayObjectContainer', 'EventDispatcher', 'ByteArray', 'Point', 'Rectangle', 'Matrix', 'TextField']);
394
396
  const superFallback = _avm2UsesNamespaceIdentity(superMn) ? 'Object' : nativeSuperNames.has(superRaw) ? superRaw : `_getlex(${JSON.stringify(superRaw)}) || Object`;
395
- const extendsClause = hasSuper
396
- ? superQualified !== superRaw
397
+ const extendsClause = !hasSuper ? ''
398
+ : superBinding ? ` extends _swoofPackage(function () { return ${superBinding}; }, function () { return ${superFallback}; })`
399
+ : superQualified !== superRaw
397
400
  ? ` extends (_getDefinition(${JSON.stringify(superQualified)}) || ${superFallback})`
398
- : nativeSuperNames.has(superRaw) ? ` extends ${superRaw}` : ` extends (${superFallback})`
399
- : '';
401
+ : nativeSuperNames.has(superRaw) ? ` extends ${superRaw}` : ` extends (${superFallback})`;
400
402
 
401
403
  const classLines = [];
402
404
  classLines.push(`class ${className}${extendsClause} {`);
@@ -860,6 +862,11 @@ class Avm2Context {
860
862
 
861
863
  _getlexExpression(name, namespaceKeys, nameIndex, receiver = this._lookupReceiver(), scopes = this._scopeExpression()) {
862
864
  const multiname = this.cp.multinames[nameIndex];
865
+ const builtin = swoofBuiltinBinding(multiname);
866
+ if (builtin) {
867
+ const redirect = `_getlexScoped(${JSON.stringify(name)}, ${receiver}, ${scopes}${this._classScopeArg(namespaceKeys, false, nameIndex)})`;
868
+ return `_swoofPackage(function () { return ${builtin}; }, function () { return ${redirect}; })`;
869
+ }
863
870
  if (_avm2UsesNamespaceIdentity(multiname)) {
864
871
  const exact = _avm2TypeTraitName(multiname, name, this.methodTableName);
865
872
  const lexicalClass = this.lexicalClass || (multiname.nsKind === 0x1A && this.ownerClass) || 'undefined';
@@ -1958,7 +1965,11 @@ class Avm2Context {
1958
1965
  const name = this._multinameTypeName(insn.a);
1959
1966
  const receiver = this._lookupReceiver();
1960
1967
  const scopes = this._scopeExpression();
1961
- const ctor = `_findProp(${JSON.stringify(name)}, ${receiver}, ${scopes}, true, false${this._classScopeArg()})[${JSON.stringify(name)}] || ${this._getlexExpression(name)}`;
1968
+ const runtime = `(_findProp(${JSON.stringify(name)}, ${receiver}, ${scopes}, true, false${this._classScopeArg()})[${JSON.stringify(name)}] || _getlexScoped(${JSON.stringify(name)}, ${receiver}, ${scopes}${this._classScopeArg(undefined, false, insn.a)}))`;
1969
+ const builtin = swoofBuiltinBinding(multiname);
1970
+ const ctor = builtin
1971
+ ? `_swoofPackage(function () { return ${builtin}; }, function () { return ${runtime}; })`
1972
+ : runtime;
1962
1973
  this.stack.push(this._constructExpression(ctor, args));
1963
1974
  } else {
1964
1975
  const candidates = this.namespaceKeys.lookup(insn.a);
@@ -2488,6 +2499,26 @@ function _hashAvm2Namespace(value) {
2488
2499
  return (hash >>> 0).toString(16);
2489
2500
  }
2490
2501
 
2502
+ /**
2503
+ * A package multiname such as `flash.display.Sprite` is `globalThis.swoof.display.Sprite`
2504
+ * only when that property is on the catalog. The `globalThis` receiver is required
2505
+ * because a split movie is an ES module. A name the catalog does not have returns
2506
+ * null so the caller keeps `_getlex`, which resolves the movie's own class.
2507
+ */
2508
+ function swoofBuiltinBinding(multiname) {
2509
+ if (!multiname || multiname.nsKind !== 0x16 || typeof multiname.ns !== 'string') return null;
2510
+ const local = multiname.localName;
2511
+ if (!local || !/^[A-Za-z_$][\w$]*$/.test(local)) return null;
2512
+ if (multiname.ns === 'flash') {
2513
+ return local === 'Vector' && hasSwoofBuiltin('', 'Vector') ? 'globalThis.swoof.Vector' : null;
2514
+ }
2515
+ if (!multiname.ns.startsWith('flash.')) return null;
2516
+ const rest = multiname.ns.slice('flash.'.length);
2517
+ if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(rest)) return null;
2518
+ if (!hasSwoofBuiltin(rest, local)) return null;
2519
+ return `globalThis.swoof.${rest}.${local}`;
2520
+ }
2521
+
2491
2522
  function _avm2UsesNamespaceIdentity(multiname) {
2492
2523
  const kind = multiname?.nsKind;
2493
2524
  return Boolean(kind && kind !== 0x16 && (kind !== 0x08 || multiname.ns));