swf2js 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.
- package/LICENSE-GPL +680 -0
- package/README.md +208 -2
- package/package.json +24 -4
- package/src/cli.js +272 -0
- package/src/decoder/button-decoder.js +136 -0
- package/src/decoder/shape-decoder.js +786 -0
- package/src/decoder/symbol-table.js +36 -0
- package/src/decoder/tag-decoder.js +1190 -0
- package/src/decoder/tag-types.js +258 -0
- package/src/emitter/asset-encoder.js +708 -0
- package/src/emitter/bundle-emitter.js +596 -0
- package/src/emitter/embedded-swf.js +246 -0
- package/src/emitter/font-encoder.js +365 -0
- package/src/emitter/timeline-data-codec.js +58 -0
- package/src/model/swf-document.js +59 -0
- package/src/model/transpile-result.js +32 -0
- package/src/parser/bit-reader.js +237 -0
- package/src/parser/decompressor.js +91 -0
- package/src/parser/swf-parser.js +164 -0
- package/src/pretty-printer/pretty-printer.js +137 -0
- package/src/runtime/avm1-runtime.js +4907 -0
- package/src/runtime/avm2-runtime.js +1591 -0
- package/src/runtime/embedded-movie-runtime.js +208 -0
- package/src/runtime/index.js +17 -0
- package/src/runtime/movie-runtime.js +306 -0
- package/src/runtime/swflib.js +14050 -0
- package/src/transpiler/actionscript.js +390 -0
- package/src/transpiler/avm1/avm1-ir.js +205 -0
- package/src/transpiler/avm1/avm1-opcodes.js +149 -0
- package/src/transpiler/avm1/avm1-rewrite.js +291 -0
- package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
- package/src/transpiler/avm2/abc-reader.js +416 -0
- package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
- package/src/transpiler/cfg-structurer.js +876 -0
- package/src/transpiler/timeline/display-list.js +643 -0
- package/src/transpiler/timeline/timeline-codegen.js +6354 -0
- package/src/util/diagnostics.js +50 -0
- package/src/util/logger.js +40 -0
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview ActionScript transpilation coordinator.
|
|
3
|
+
* Extracts and transpiles all AVM1 (DoAction, DoInitAction, Sprite scripts)
|
|
4
|
+
* and AVM2 (DoABC) bytecode from decoded SWF tags.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { TAG } from '../decoder/tag-types.js';
|
|
8
|
+
import { decodeTag } from '../decoder/tag-decoder.js';
|
|
9
|
+
import { decodeButton } from '../decoder/button-decoder.js';
|
|
10
|
+
import { BitReader } from '../parser/bit-reader.js';
|
|
11
|
+
import { OP } from './avm1/avm1-opcodes.js';
|
|
12
|
+
import { transpileAvm1WithMeta } from './avm1/avm1-transpiler.js';
|
|
13
|
+
import { AVM1_RUNTIME_BOOTSTRAP, AVM1_RUNTIME_STUB, CLIP_EVENT_HANDLERS } from '../runtime/avm1-runtime.js';
|
|
14
|
+
import { transpileAvm2, AVM2_RUNTIME_BOOTSTRAP, AVM2_RUNTIME_STUB } from './avm2/avm2-transpiler.js';
|
|
15
|
+
|
|
16
|
+
/** @import { DiagnosticsCollector } from '../util/diagnostics.js' */
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {Object} CompiledActionScript
|
|
20
|
+
* @property {Array<{ frameIndex: number, spriteId?: number, jsSource: string }>} avm1Scripts
|
|
21
|
+
* @property {Array<{ name: string, flags: number, jsSource: string }>} avm2Blocks
|
|
22
|
+
* @property {string[]} jsFragments
|
|
23
|
+
* @property {string} fullJs
|
|
24
|
+
* @property {Map<number, string[]>} legacyButtonScripts - button handlers compiled in movie tag order
|
|
25
|
+
* @property {boolean} needsSwflib - true when bundle should load swflib.js
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Decode and transpile all ActionScript tags (AVM1 + AVM2) from decoded SWF tags.
|
|
30
|
+
*
|
|
31
|
+
* @param {object[]} tags - Decoded tags from `decode()`
|
|
32
|
+
* @param {DiagnosticsCollector} diagnostics
|
|
33
|
+
* @param {object} [opts]
|
|
34
|
+
* @param {boolean} [opts.skeletonOnly=false]
|
|
35
|
+
* @param {number} [opts.maxAbcMethods=Infinity]
|
|
36
|
+
* @param {boolean} [opts.deferAvm2Initializers=false]
|
|
37
|
+
* @param {boolean} [opts.sharedAvm1Runtime=false]
|
|
38
|
+
* @param {boolean} [opts.sharedAvm2Runtime=false]
|
|
39
|
+
* @param {number} [opts.swfVersion]
|
|
40
|
+
* @returns {CompiledActionScript}
|
|
41
|
+
*/
|
|
42
|
+
export function transpileActionScript(tags, diagnostics, opts = {}) {
|
|
43
|
+
/** @type {Array<{ frameIndex: number, spriteId?: number, jsSource: string }>} */
|
|
44
|
+
const avm1Scripts = [];
|
|
45
|
+
/** @type {Array<{ name: string, flags: number, jsSource: string }>} */
|
|
46
|
+
const avm2Blocks = [];
|
|
47
|
+
/** @type {string[]} */
|
|
48
|
+
const jsFragments = [];
|
|
49
|
+
let avm2BlockIndex = 0;
|
|
50
|
+
const sharedAvm1Runtime = opts.sharedAvm1Runtime;
|
|
51
|
+
const decodingContext = { header: { version: opts.swfVersion } };
|
|
52
|
+
// Unversioned bytecode retains the historical function lookup heuristic.
|
|
53
|
+
let nameSpellings;
|
|
54
|
+
if (opts.swfVersion > 0) nameSpellings = opts.swfVersion < 7 ? new Map() : null;
|
|
55
|
+
const legacyButtonScripts = new Map();
|
|
56
|
+
let hasButtonActions = false;
|
|
57
|
+
|
|
58
|
+
let frameIndex = 0;
|
|
59
|
+
|
|
60
|
+
for (const [index, tag] of tags.entries()) {
|
|
61
|
+
const previousTag = tags[index - 1];
|
|
62
|
+
if (tag.type === 'ShowFrame') {
|
|
63
|
+
frameIndex++;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// PlaceObject clip actions: on(press)/on(release)/onClipEvent(…)
|
|
68
|
+
if (
|
|
69
|
+
(tag.type === 'PlaceObject2' || tag.type === 'PlaceObject3') &&
|
|
70
|
+
tag.clipActions &&
|
|
71
|
+
tag.clipActions.length
|
|
72
|
+
) {
|
|
73
|
+
const bound = wrapClipActions(tag, frameIndex, null, diagnostics, sharedAvm1Runtime, nameSpellings, previousTag);
|
|
74
|
+
for (const w of bound) {
|
|
75
|
+
avm1Scripts.push({ frameIndex, jsSource: w });
|
|
76
|
+
jsFragments.push(w);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (tag.type === 'Button' && tag.rawData) {
|
|
81
|
+
let actions;
|
|
82
|
+
try { actions = decodeButton(tag.rawData, tag.version || 2).actions; }
|
|
83
|
+
catch (_) { continue; } // The display-list compiler reports malformed buttons.
|
|
84
|
+
hasButtonActions ||= actions.length > 0;
|
|
85
|
+
if ((nameSpellings || sharedAvm1Runtime || previousTag?.code === 253) && actions.length) {
|
|
86
|
+
// Compile in tag order so button scripts can also contribute companion URLs.
|
|
87
|
+
legacyButtonScripts.set(tag.characterId, actions.map((action, index) => {
|
|
88
|
+
const { bytecode, entryOffset } = linkedActionSource(action.bytecode, previousTag, action.bytecodeOffset ?? null, tag.rawData.length);
|
|
89
|
+
return transpileAvm1WithMeta(bytecode, diagnostics, {
|
|
90
|
+
entryOffset, timelineDeclarations: true,
|
|
91
|
+
sharedAvm1Runtime, nameSpellings, useRuntimeNumbers: true, label: `button_${tag.characterId}_action_${index}`,
|
|
92
|
+
}).js;
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
} else if (tag.type === 'DoAction') {
|
|
96
|
+
const { bytecode, entryOffset } = linkedActionSource(tag.bytecode, previousTag);
|
|
97
|
+
const meta = transpileAvm1WithMeta(bytecode, diagnostics, {
|
|
98
|
+
entryOffset,
|
|
99
|
+
timelineDeclarations: true,
|
|
100
|
+
spriteFrameScope: opts.swfVersion >= 6,
|
|
101
|
+
sharedAvm1Runtime,
|
|
102
|
+
nameSpellings,
|
|
103
|
+
useRuntimeNumbers: true,
|
|
104
|
+
label: `frame_${frameIndex}`,
|
|
105
|
+
});
|
|
106
|
+
// Root DoAction runs when the playhead enters this frame — not at load.
|
|
107
|
+
const wrapped = wrapAvm1Script(`frame ${frameIndex} DoAction`, meta.js, {
|
|
108
|
+
frameIndex,
|
|
109
|
+
sharedAvm1Runtime,
|
|
110
|
+
});
|
|
111
|
+
avm1Scripts.push({ frameIndex, jsSource: wrapped });
|
|
112
|
+
jsFragments.push(wrapped);
|
|
113
|
+
} else if (tag.type === 'DoInitAction') {
|
|
114
|
+
const { bytecode, entryOffset } = linkedActionSource(tag.bytecode, previousTag, 2);
|
|
115
|
+
const meta = transpileAvm1WithMeta(bytecode, diagnostics, {
|
|
116
|
+
entryOffset,
|
|
117
|
+
sharedAvm1Runtime,
|
|
118
|
+
nameSpellings,
|
|
119
|
+
useRuntimeNumbers: true,
|
|
120
|
+
scopeLookup: true,
|
|
121
|
+
label: `sprite_${tag.spriteId}`,
|
|
122
|
+
});
|
|
123
|
+
// A root DoInitAction runs before the referenced sprite is instantiated.
|
|
124
|
+
// Its definitions belong to the movie timeline that contains the tag.
|
|
125
|
+
const wrapped = wrapAvm1Script(`sprite ${tag.spriteId} DoInitAction`, meta.js, {
|
|
126
|
+
frameIndex,
|
|
127
|
+
sharedAvm1Runtime,
|
|
128
|
+
init: true,
|
|
129
|
+
});
|
|
130
|
+
avm1Scripts.push({ frameIndex, spriteId: tag.spriteId, jsSource: wrapped });
|
|
131
|
+
jsFragments.push(wrapped);
|
|
132
|
+
} else if (tag.type === 'Sprite' && Array.isArray(tag.tags)) {
|
|
133
|
+
let spriteFrame = 0;
|
|
134
|
+
for (const [spriteTagIndex, raw] of tag.tags.entries()) {
|
|
135
|
+
const previousSpriteTag = tag.tags[spriteTagIndex - 1];
|
|
136
|
+
if (raw.code === TAG.ShowFrame) {
|
|
137
|
+
spriteFrame++;
|
|
138
|
+
} else if (raw.code === TAG.PlaceObject2 || raw.code === TAG.PlaceObject3) {
|
|
139
|
+
// Sprite-internal PlaceObject may carry on(release) handlers.
|
|
140
|
+
try {
|
|
141
|
+
const placed = decodeTag(raw, decodingContext, diagnostics);
|
|
142
|
+
if (placed && placed.clipActions && placed.clipActions.length) {
|
|
143
|
+
const bound = wrapClipActions(placed, spriteFrame, tag.characterId, diagnostics, sharedAvm1Runtime, nameSpellings, previousSpriteTag);
|
|
144
|
+
for (const w of bound) {
|
|
145
|
+
avm1Scripts.push({ frameIndex: spriteFrame, spriteId: tag.characterId, jsSource: w });
|
|
146
|
+
jsFragments.push(w);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
} catch (_) {}
|
|
150
|
+
} else if (raw.code === TAG.DoAction) {
|
|
151
|
+
const { bytecode, entryOffset } = linkedActionSource(raw.data, previousSpriteTag);
|
|
152
|
+
const meta = transpileAvm1WithMeta(bytecode, diagnostics, {
|
|
153
|
+
entryOffset,
|
|
154
|
+
timelineDeclarations: true,
|
|
155
|
+
spriteFrameScope: opts.swfVersion >= 6,
|
|
156
|
+
sharedAvm1Runtime,
|
|
157
|
+
nameSpellings,
|
|
158
|
+
useRuntimeNumbers: true,
|
|
159
|
+
label: `sprite_${tag.characterId}`,
|
|
160
|
+
});
|
|
161
|
+
// Nested sprite frame scripts: register for that sprite's playhead (not root load).
|
|
162
|
+
const wrapped = wrapAvm1Script(
|
|
163
|
+
`sprite ${tag.characterId} frame ${spriteFrame} DoAction`,
|
|
164
|
+
meta.js,
|
|
165
|
+
{
|
|
166
|
+
spriteId: tag.characterId,
|
|
167
|
+
frameIndex: spriteFrame,
|
|
168
|
+
sharedAvm1Runtime,
|
|
169
|
+
}
|
|
170
|
+
);
|
|
171
|
+
avm1Scripts.push({ frameIndex: spriteFrame, spriteId: tag.characterId, jsSource: wrapped });
|
|
172
|
+
jsFragments.push(wrapped);
|
|
173
|
+
} else if (raw.code === TAG.DoInitAction && raw.data.length >= 2) {
|
|
174
|
+
const spriteId = raw.data[0] | (raw.data[1] << 8);
|
|
175
|
+
const { bytecode, entryOffset } = linkedActionSource(raw.data.subarray(2), previousSpriteTag, 2);
|
|
176
|
+
const meta = transpileAvm1WithMeta(bytecode, diagnostics, {
|
|
177
|
+
entryOffset,
|
|
178
|
+
sharedAvm1Runtime,
|
|
179
|
+
nameSpellings,
|
|
180
|
+
useRuntimeNumbers: true,
|
|
181
|
+
scopeLookup: true,
|
|
182
|
+
label: `sprite_${spriteId}`,
|
|
183
|
+
});
|
|
184
|
+
const wrapped = wrapAvm1Script(`sprite ${spriteId} DoInitAction`, meta.js, {
|
|
185
|
+
spriteId,
|
|
186
|
+
sharedAvm1Runtime,
|
|
187
|
+
init: true,
|
|
188
|
+
});
|
|
189
|
+
avm1Scripts.push({ frameIndex: spriteFrame, spriteId, jsSource: wrapped });
|
|
190
|
+
jsFragments.push(wrapped);
|
|
191
|
+
} else if (raw.code === TAG.DoABC) {
|
|
192
|
+
const r = new BitReader(raw.data);
|
|
193
|
+
const flags = r.readUI32();
|
|
194
|
+
const name = r.readString();
|
|
195
|
+
const abcData = raw.data.slice(r.bytePos);
|
|
196
|
+
const jsSource = transpileAvm2(abcData, diagnostics, {
|
|
197
|
+
skeletonOnly: opts.skeletonOnly,
|
|
198
|
+
maxMethods: opts.maxAbcMethods,
|
|
199
|
+
blockId: avm2BlockIndex++,
|
|
200
|
+
});
|
|
201
|
+
avm2Blocks.push({ name, flags, jsSource });
|
|
202
|
+
jsFragments.push(jsSource);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
} else if (tag.type === 'DoABC') {
|
|
206
|
+
const jsSource = transpileAvm2(tag.abcData, diagnostics, {
|
|
207
|
+
skeletonOnly: opts.skeletonOnly,
|
|
208
|
+
maxMethods: opts.maxAbcMethods,
|
|
209
|
+
blockId: avm2BlockIndex++,
|
|
210
|
+
});
|
|
211
|
+
avm2Blocks.push({ name: tag.name ?? '', flags: tag.flags ?? 0, jsSource });
|
|
212
|
+
jsFragments.push(jsSource);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// AVM glue + game scripts only — swflib.js is emitted as a separate file by the bundle emitter
|
|
217
|
+
const headerStubs = [];
|
|
218
|
+
if (avm1Scripts.length > 0 || hasButtonActions) {
|
|
219
|
+
if (!sharedAvm1Runtime && opts.swfVersion) headerStubs.push(`var SWF_VERSION = ${Number(opts.swfVersion) || 0};`);
|
|
220
|
+
headerStubs.push(sharedAvm1Runtime ? AVM1_RUNTIME_BOOTSTRAP : AVM1_RUNTIME_STUB);
|
|
221
|
+
}
|
|
222
|
+
if (avm2Blocks.length > 0) {
|
|
223
|
+
headerStubs.push(opts.sharedAvm2Runtime ? AVM2_RUNTIME_BOOTSTRAP : AVM2_RUNTIME_STUB);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const fullJs = [
|
|
227
|
+
...headerStubs,
|
|
228
|
+
...jsFragments,
|
|
229
|
+
...(avm2Blocks.length > 0 && !opts.deferAvm2Initializers ? ['_runAvm2Initializers();'] : []),
|
|
230
|
+
].join('\n\n');
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
avm1Scripts,
|
|
234
|
+
avm2Blocks,
|
|
235
|
+
jsFragments,
|
|
236
|
+
fullJs,
|
|
237
|
+
legacyButtonScripts,
|
|
238
|
+
needsSwflib: avm1Scripts.length > 0 || hasButtonActions || avm2Blocks.length > 0,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function bridgeJumpTarget(bytes, offset) {
|
|
243
|
+
if (bytes[offset] !== OP.Jump || bytes[offset + 1] !== 2 || bytes[offset + 2] !== 0) return null;
|
|
244
|
+
const displacement = bytes[offset + 3] | (bytes[offset + 4] << 8);
|
|
245
|
+
return offset + 5 + ((displacement << 16) >> 16);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function linkedActionSource(bytecode, previousTag, bodyOffset = 0, bodyLength = bodyOffset + bytecode.length) {
|
|
249
|
+
const prefix = previousTag?.code === 253 ? previousTag.data : null;
|
|
250
|
+
if (!prefix || prefix.length < 10 || bodyLength < 0x3f || !Number.isInteger(bodyOffset) ||
|
|
251
|
+
bodyOffset < 0 || bodyOffset + bytecode.length > bodyLength) return { bytecode, entryOffset: 0 };
|
|
252
|
+
// Obfuscated long-form action carriers can branch into the adjacent tag 253.
|
|
253
|
+
// The final two Jump records bridge in both directions across the tag header.
|
|
254
|
+
const bridge = prefix.length - 10;
|
|
255
|
+
const bodyStart = prefix.length + 6;
|
|
256
|
+
const entryOffset = bodyStart + bodyOffset;
|
|
257
|
+
const returnTarget = bridgeJumpTarget(prefix, bridge);
|
|
258
|
+
const hiddenTarget = bridgeJumpTarget(prefix, bridge + 5);
|
|
259
|
+
if (returnTarget == null || returnTarget < bodyStart || returnTarget >= bodyStart + bodyLength ||
|
|
260
|
+
hiddenTarget == null || hiddenTarget < 0 || hiddenTarget >= bridge) return { bytecode, entryOffset: 0 };
|
|
261
|
+
|
|
262
|
+
const source = new Uint8Array(entryOffset + bytecode.length);
|
|
263
|
+
source.set(prefix);
|
|
264
|
+
source.set(bytecode, entryOffset);
|
|
265
|
+
return { bytecode: source, entryOffset };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* @param {string} label
|
|
270
|
+
* @param {string} body
|
|
271
|
+
* @param {object} [opts]
|
|
272
|
+
* @param {number} [opts.frameIndex]
|
|
273
|
+
* @param {number|null} [opts.spriteId]
|
|
274
|
+
* @param {boolean} [opts.sharedAvm1Runtime]
|
|
275
|
+
* @param {boolean} [opts.init] - DoInitAction initializer
|
|
276
|
+
* @param {number} [opts.clipRegistration] - timeline clip event flags
|
|
277
|
+
* @param {number|null} [opts.placementDepth] - depth of the clip event placement
|
|
278
|
+
* @returns {string}
|
|
279
|
+
*/
|
|
280
|
+
function wrapAvm1Script(label, body, opts = {}) {
|
|
281
|
+
const { frameIndex = 0, spriteId = null, init = false, sharedAvm1Runtime, clipRegistration, placementDepth } = opts;
|
|
282
|
+
const parameters = clipRegistration ? 'initializeOnly, cloneSource, clone' : '';
|
|
283
|
+
const bodyFunction = `function (${parameters}) {\n${indent(body)}\n}`;
|
|
284
|
+
const fn = clipRegistration
|
|
285
|
+
? `_avm1MarkClipRegistration(${bodyFunction}, ${clipRegistration}, ${placementDepth})`
|
|
286
|
+
: bodyFunction;
|
|
287
|
+
|
|
288
|
+
if (init && spriteId == null) {
|
|
289
|
+
return `/* ${label} */\ntimeline.registerRootInitializer(${frameIndex}, ${fn});`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (sharedAvm1Runtime) {
|
|
293
|
+
const registration = init
|
|
294
|
+
? `_avm1InitScript(${spriteId}, ${fn});`
|
|
295
|
+
: `_avm1FrameScript(${spriteId}, ${frameIndex}, ${fn});`;
|
|
296
|
+
return `/* ${label} */\n${registration}`;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Sprite-internal initializers still use their symbol's init clip.
|
|
300
|
+
if (init) {
|
|
301
|
+
return `/* ${label} */\nrunClipScript(_clip(${spriteId}), ${fn});`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Root timeline: register for playhead enter (FPS keyframe).
|
|
305
|
+
if (spriteId == null) {
|
|
306
|
+
return (
|
|
307
|
+
`/* ${label} */\n` +
|
|
308
|
+
`(FRAME_SCRIPTS[${frameIndex}] || (FRAME_SCRIPTS[${frameIndex}] = [])).push(${fn});`
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Sprite timeline: register on that character's frame list (run when sprite playhead enters).
|
|
313
|
+
return (
|
|
314
|
+
`/* ${label} */\n` +
|
|
315
|
+
`(function () {\n` +
|
|
316
|
+
` var _ss = SPRITE_FRAME_SCRIPTS[${spriteId}] || (SPRITE_FRAME_SCRIPTS[${spriteId}] = []);\n` +
|
|
317
|
+
` (_ss[${frameIndex}] || (_ss[${frameIndex}] = [])).push(${fn});\n` +
|
|
318
|
+
`})();`
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function indent(src) {
|
|
323
|
+
return src.split('\n').map(l => ' ' + l).join('\n');
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Bind PlaceObject clip actions onto the live placement when the host frame is entered.
|
|
328
|
+
* @param {object} place - decoded PlaceObject2/3 with depth and clipActions
|
|
329
|
+
* @param {number} frameIndex
|
|
330
|
+
* @param {number|null} hostSpriteId - null = root timeline
|
|
331
|
+
* @param {DiagnosticsCollector} diagnostics
|
|
332
|
+
* @param {boolean} sharedAvm1Runtime
|
|
333
|
+
* @param {Map<string, string>|null|undefined} nameSpellings
|
|
334
|
+
* @param {object} [previousTag]
|
|
335
|
+
* @returns {string[]}
|
|
336
|
+
*/
|
|
337
|
+
function wrapClipActions(place, frameIndex, hostSpriteId, diagnostics, sharedAvm1Runtime, nameSpellings, previousTag) {
|
|
338
|
+
const name = String(place.name || '');
|
|
339
|
+
const depth = Number.isInteger(place.depth) ? place.depth : null;
|
|
340
|
+
if ((!name && depth == null) || !place.clipActions?.length) return [];
|
|
341
|
+
const nameLit = JSON.stringify(name);
|
|
342
|
+
const charId = place.characterId != null ? (place.characterId | 0) : null;
|
|
343
|
+
/** @type {string[]} */
|
|
344
|
+
const out = [];
|
|
345
|
+
|
|
346
|
+
for (let i = 0; i < place.clipActions.length; i++) {
|
|
347
|
+
const ca = place.clipActions[i];
|
|
348
|
+
if (!ca || !ca.bytecode || !ca.bytecode.length) continue;
|
|
349
|
+
const handlers = CLIP_EVENT_HANDLERS.filter(([bit]) => (ca.eventFlags & bit) !== 0).map(([, n]) => n);
|
|
350
|
+
if (!handlers.length) continue;
|
|
351
|
+
|
|
352
|
+
const { bytecode, entryOffset } = linkedActionSource(ca.bytecode, previousTag, ca.bytecodeOffset ?? null, place.clipActionTagLength);
|
|
353
|
+
const meta = transpileAvm1WithMeta(bytecode, diagnostics, {
|
|
354
|
+
entryOffset,
|
|
355
|
+
timelineDeclarations: true,
|
|
356
|
+
clipActionScope: true,
|
|
357
|
+
sharedAvm1Runtime,
|
|
358
|
+
nameSpellings,
|
|
359
|
+
useRuntimeNumbers: true,
|
|
360
|
+
label: `${name || `depth_${depth}`}_${handlers.join('_')}`,
|
|
361
|
+
});
|
|
362
|
+
if (!meta.js || !meta.js.trim()) continue;
|
|
363
|
+
|
|
364
|
+
const label = `clip ${name || `depth ${depth}`} ${handlers.join('+')} @${frameIndex}`;
|
|
365
|
+
const keyCode = ca.keyCode != null ? (ca.keyCode | 0) : 0;
|
|
366
|
+
if (sharedAvm1Runtime) {
|
|
367
|
+
const fn = `function () {\n${indent(meta.js)}\n}`;
|
|
368
|
+
out.push(
|
|
369
|
+
`/* ${label} */\n` +
|
|
370
|
+
`_avm1ClipAction(${hostSpriteId}, ${frameIndex}, ${nameLit}, ${charId}, ${ca.eventFlags | 0}, ${keyCode}, ${i}, ${fn}, ${depth});`
|
|
371
|
+
);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const body =
|
|
376
|
+
`var mc = _resolveAvm1ActionClip(this, ${hostSpriteId}, ${depth}, ${nameLit}, ${charId}, cloneSource, clone);\n` +
|
|
377
|
+
`if (!mc) return;\n` +
|
|
378
|
+
`var _fn = function () {\n${indent(meta.js)}\n};\n` +
|
|
379
|
+
`_avm1InstallClipAction(mc, ${ca.eventFlags | 0}, ${JSON.stringify(`${keyCode}:${frameIndex}:${i}`)}, _fn, initializeOnly);`;
|
|
380
|
+
|
|
381
|
+
const wrapped = wrapAvm1Script(label, body, {
|
|
382
|
+
frameIndex,
|
|
383
|
+
spriteId: hostSpriteId,
|
|
384
|
+
clipRegistration: ca.eventFlags | 0,
|
|
385
|
+
placementDepth: depth,
|
|
386
|
+
});
|
|
387
|
+
out.push(wrapped);
|
|
388
|
+
}
|
|
389
|
+
return out;
|
|
390
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview AVM1 IR helpers — typed refs, DefineFunction2 flag decode, usage profiles.
|
|
3
|
+
* Pass 1 records semantics; Pass 2 (avm1-rewrite.js) lowers to idiomatic JS + shapes.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Adobe SWF bitfields for DefineFunction2 (MSB-first within the first flags byte). */
|
|
7
|
+
export const DF2 = {
|
|
8
|
+
PRELOAD_THIS: 0x01,
|
|
9
|
+
SUPPRESS_THIS: 0x02,
|
|
10
|
+
PRELOAD_ARGUMENTS: 0x04,
|
|
11
|
+
SUPPRESS_ARGUMENTS: 0x08,
|
|
12
|
+
PRELOAD_SUPER: 0x10,
|
|
13
|
+
SUPPRESS_SUPER: 0x20,
|
|
14
|
+
PRELOAD_ROOT: 0x40,
|
|
15
|
+
PRELOAD_PARENT: 0x80,
|
|
16
|
+
PRELOAD_GLOBAL: 0x100,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Build register→init-expression map for DefineFunction2 preloads.
|
|
21
|
+
* Assignment order: this, arguments, super, root, parent, global.
|
|
22
|
+
*
|
|
23
|
+
* @param {number} flags
|
|
24
|
+
* @returns {Map<number, string>}
|
|
25
|
+
*/
|
|
26
|
+
export function buildPreloadAliases(flags) {
|
|
27
|
+
/** @type {Map<number, string>} */
|
|
28
|
+
const aliases = new Map();
|
|
29
|
+
let reg = 1;
|
|
30
|
+
if (flags & DF2.PRELOAD_THIS) aliases.set(reg++, 'this');
|
|
31
|
+
if (flags & DF2.PRELOAD_ARGUMENTS) aliases.set(reg++, 'Array.prototype.slice.call(arguments)');
|
|
32
|
+
if (flags & DF2.PRELOAD_SUPER) aliases.set(reg++, '_avm1Super(this, _avm1Function)');
|
|
33
|
+
if (flags & DF2.PRELOAD_ROOT) aliases.set(reg++, 'root');
|
|
34
|
+
if (flags & DF2.PRELOAD_PARENT) aliases.set(reg++, '(this.parent || root)');
|
|
35
|
+
if (flags & DF2.PRELOAD_GLOBAL) aliases.set(reg++, 'globals');
|
|
36
|
+
return aliases;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Flash clip field → browser-friendly JS name */
|
|
40
|
+
export const FLASH_PROP_TO_JS = {
|
|
41
|
+
_x: 'x',
|
|
42
|
+
_y: 'y',
|
|
43
|
+
_xscale: 'scaleX',
|
|
44
|
+
_yscale: 'scaleY',
|
|
45
|
+
_alpha: 'alpha',
|
|
46
|
+
_visible: 'visible',
|
|
47
|
+
_width: 'width',
|
|
48
|
+
_height: 'height',
|
|
49
|
+
_rotation: 'rotation',
|
|
50
|
+
_name: 'name',
|
|
51
|
+
_currentframe: 'currentFrame',
|
|
52
|
+
_totalframes: 'totalFrames',
|
|
53
|
+
_framesloaded: 'framesLoaded',
|
|
54
|
+
_url: 'url',
|
|
55
|
+
_xmouse: 'mouseX',
|
|
56
|
+
_ymouse: 'mouseY',
|
|
57
|
+
_parent: 'parent',
|
|
58
|
+
_root: 'root',
|
|
59
|
+
_highquality: 'highQuality',
|
|
60
|
+
_focusrect: 'focusRect',
|
|
61
|
+
_soundbuftime: 'soundBufTime',
|
|
62
|
+
_quality: 'quality',
|
|
63
|
+
_droptarget: 'dropTarget',
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param {string} name
|
|
68
|
+
* @returns {string}
|
|
69
|
+
*/
|
|
70
|
+
export function flashPropToJs(name) {
|
|
71
|
+
if (typeof name !== 'string') return name;
|
|
72
|
+
return name[0] === '_' && Object.prototype.hasOwnProperty.call(FLASH_PROP_TO_JS, name)
|
|
73
|
+
? FLASH_PROP_TO_JS[name] : name;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const avm1DisplayMemberNames = new Set([
|
|
77
|
+
...Object.keys(FLASH_PROP_TO_JS), ...Object.values(FLASH_PROP_TO_JS).map(name => name.toLowerCase()),
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
export function isAvm1DisplayMemberName(name) {
|
|
81
|
+
return typeof name === 'string' && avm1DisplayMemberNames.has(name.toLowerCase());
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Turn preload expressions into mutable locals so StoreRegister is valid JS.
|
|
86
|
+
* e.g. `(this.parent || root) = 0` is illegal → `var _r2 = (this.parent || root); _r2 = 0;`
|
|
87
|
+
*
|
|
88
|
+
* @param {number} flags
|
|
89
|
+
* @returns {{ aliases: Map<number, string>, preamble: string[] }}
|
|
90
|
+
*/
|
|
91
|
+
export function materializePreloadAliases(flags) {
|
|
92
|
+
const exprs = buildPreloadAliases(flags);
|
|
93
|
+
/** @type {Map<number, string>} */
|
|
94
|
+
const aliases = new Map();
|
|
95
|
+
/** @type {string[]} */
|
|
96
|
+
const preamble = [];
|
|
97
|
+
for (const [reg, expr] of exprs) {
|
|
98
|
+
const local = `_r${reg}`;
|
|
99
|
+
preamble.push(`var ${local} = ${expr};`);
|
|
100
|
+
aliases.set(reg, local);
|
|
101
|
+
}
|
|
102
|
+
return { aliases, preamble };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* @returns {{ props: Set<string>, methods: Set<string>, assigns: Set<string> }}
|
|
107
|
+
*/
|
|
108
|
+
export function createUsageProfile() {
|
|
109
|
+
return {
|
|
110
|
+
props: new Set(),
|
|
111
|
+
methods: new Set(),
|
|
112
|
+
assigns: new Set(),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Record `this.prop` style usage for shape inference.
|
|
118
|
+
* @param {{ props: Set<string>, methods: Set<string>, assigns: Set<string> }} profile
|
|
119
|
+
* @param {string} kind
|
|
120
|
+
* @param {string} name
|
|
121
|
+
*/
|
|
122
|
+
export function noteUsage(profile, kind, name) {
|
|
123
|
+
if (!profile || !name || typeof name !== 'string') return;
|
|
124
|
+
if (!/^[a-zA-Z_$][\w$]*$/.test(name)) return;
|
|
125
|
+
if (kind === 'prop') profile.props.add(name);
|
|
126
|
+
else if (kind === 'method') profile.methods.add(name);
|
|
127
|
+
else if (kind === 'assign') profile.assigns.add(name);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @typedef {Object} ClipShape
|
|
132
|
+
* @property {string} label
|
|
133
|
+
* @property {string[]} props
|
|
134
|
+
* @property {string[]} methods
|
|
135
|
+
*/
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* @param {string} label
|
|
139
|
+
* @param {{ props: Set<string>, methods: Set<string>, assigns: Set<string> }} profile
|
|
140
|
+
* @returns {ClipShape|null}
|
|
141
|
+
*/
|
|
142
|
+
export function shapeFromProfile(label, profile) {
|
|
143
|
+
if (!profile) return null;
|
|
144
|
+
const props = [...new Set([...profile.props, ...profile.assigns])].sort();
|
|
145
|
+
const methods = [...profile.methods].sort();
|
|
146
|
+
if (props.length === 0 && methods.length === 0) return null;
|
|
147
|
+
return { label, props, methods };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* IR expr tags used on the operand stack (lightweight — mostly documentation + rewrite hooks).
|
|
152
|
+
* @typedef {{ kind: string, [key: string]: unknown }} IrExpr
|
|
153
|
+
*/
|
|
154
|
+
|
|
155
|
+
/** @returns {IrExpr} */
|
|
156
|
+
export function irThis() {
|
|
157
|
+
return { kind: 'this' };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** @returns {IrExpr} */
|
|
161
|
+
export function irRoot() {
|
|
162
|
+
return { kind: 'root' };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* @param {number} n
|
|
167
|
+
* @returns {IrExpr}
|
|
168
|
+
*/
|
|
169
|
+
export function irReg(n) {
|
|
170
|
+
return { kind: 'reg', n };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @param {string} name
|
|
175
|
+
* @returns {IrExpr}
|
|
176
|
+
*/
|
|
177
|
+
export function irVar(name) {
|
|
178
|
+
return { kind: 'var', name };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Lower a simple IR expr, or pass through string expressions.
|
|
183
|
+
* @param {IrExpr|string|null|undefined} expr
|
|
184
|
+
* @param {Map<number, string>} [regAliases]
|
|
185
|
+
* @returns {string}
|
|
186
|
+
*/
|
|
187
|
+
export function lowerExpr(expr, regAliases) {
|
|
188
|
+
if (expr == null) return 'undefined';
|
|
189
|
+
if (typeof expr === 'string') return expr;
|
|
190
|
+
switch (expr.kind) {
|
|
191
|
+
case 'this':
|
|
192
|
+
return 'this';
|
|
193
|
+
case 'root':
|
|
194
|
+
return 'root';
|
|
195
|
+
case 'reg': {
|
|
196
|
+
const n = /** @type {number} */ (expr.n);
|
|
197
|
+
if (regAliases && regAliases.has(n)) return /** @type {string} */ (regAliases.get(n));
|
|
198
|
+
return `_registers[${n}]`;
|
|
199
|
+
}
|
|
200
|
+
case 'var':
|
|
201
|
+
return `this.${expr.name}`;
|
|
202
|
+
default:
|
|
203
|
+
return 'undefined';
|
|
204
|
+
}
|
|
205
|
+
}
|