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.
Files changed (38) hide show
  1. package/LICENSE-GPL +680 -0
  2. package/README.md +208 -2
  3. package/package.json +24 -4
  4. package/src/cli.js +272 -0
  5. package/src/decoder/button-decoder.js +136 -0
  6. package/src/decoder/shape-decoder.js +786 -0
  7. package/src/decoder/symbol-table.js +36 -0
  8. package/src/decoder/tag-decoder.js +1190 -0
  9. package/src/decoder/tag-types.js +258 -0
  10. package/src/emitter/asset-encoder.js +708 -0
  11. package/src/emitter/bundle-emitter.js +596 -0
  12. package/src/emitter/embedded-swf.js +246 -0
  13. package/src/emitter/font-encoder.js +365 -0
  14. package/src/emitter/timeline-data-codec.js +58 -0
  15. package/src/model/swf-document.js +59 -0
  16. package/src/model/transpile-result.js +32 -0
  17. package/src/parser/bit-reader.js +237 -0
  18. package/src/parser/decompressor.js +91 -0
  19. package/src/parser/swf-parser.js +164 -0
  20. package/src/pretty-printer/pretty-printer.js +137 -0
  21. package/src/runtime/avm1-runtime.js +4907 -0
  22. package/src/runtime/avm2-runtime.js +1591 -0
  23. package/src/runtime/embedded-movie-runtime.js +208 -0
  24. package/src/runtime/index.js +17 -0
  25. package/src/runtime/movie-runtime.js +306 -0
  26. package/src/runtime/swflib.js +14050 -0
  27. package/src/transpiler/actionscript.js +390 -0
  28. package/src/transpiler/avm1/avm1-ir.js +205 -0
  29. package/src/transpiler/avm1/avm1-opcodes.js +149 -0
  30. package/src/transpiler/avm1/avm1-rewrite.js +291 -0
  31. package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
  32. package/src/transpiler/avm2/abc-reader.js +416 -0
  33. package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
  34. package/src/transpiler/cfg-structurer.js +876 -0
  35. package/src/transpiler/timeline/display-list.js +643 -0
  36. package/src/transpiler/timeline/timeline-codegen.js +6354 -0
  37. package/src/util/diagnostics.js +50 -0
  38. package/src/util/logger.js +40 -0
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Prepare independently compiled child movies from DefineBinaryData and
3
+ * locally referenced and explicitly declared SWF files.
4
+ */
5
+
6
+ import { readFile, realpath, stat } from 'node:fs/promises';
7
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
8
+ import { tokenizer } from 'acorn';
9
+ import { decode } from '../decoder/tag-decoder.js';
10
+ import { SymbolTable } from '../decoder/symbol-table.js';
11
+ import { parse } from '../parser/swf-parser.js';
12
+ import { transpileActionScript } from '../transpiler/actionscript.js';
13
+ import { OP } from '../transpiler/avm1/avm1-opcodes.js';
14
+ import { DiagnosticsCollector } from '../util/diagnostics.js';
15
+
16
+ function hasSwfSignature(bytes) {
17
+ if (!bytes || bytes.length < 8) return false;
18
+ const signature = String.fromCharCode(bytes[0], bytes[1], bytes[2]);
19
+ return signature === 'FWS' || signature === 'CWS' || signature === 'ZWS';
20
+ }
21
+
22
+ async function compileChild(bytes, childDiagnostics, diagnostics, ancestry) {
23
+ const { doc } = await parse(bytes, childDiagnostics);
24
+ if (childDiagnostics.hasErrors()) return null;
25
+ const { tags, symbolTable } = decode(doc, childDiagnostics);
26
+ const actionScript = transpileActionScript(tags, childDiagnostics,
27
+ { deferAvm2Initializers: true, sharedAvm1Runtime: true, sharedAvm2Runtime: true, swfVersion: doc.header.version });
28
+ if (childDiagnostics.hasErrors()) return null;
29
+ const embeddedSwfs = await precompileEmbeddedSwfs(symbolTable, diagnostics, ancestry);
30
+ return { bytes, header: doc.header, tags, symbolTable, actionScript, embeddedSwfs };
31
+ }
32
+
33
+ /**
34
+ * Parse and compile embedded movies through the same pipeline as the outer SWF.
35
+ * Linked and unlinked payloads both qualify, since LoadBytes matches bytes.
36
+ * Diagnostics on an optional payload must not abort the containing movie.
37
+ */
38
+ export async function precompileEmbeddedSwfs(symbolTable, diagnostics, ancestry = []) {
39
+ const embeddedSwfs = [];
40
+
41
+ for (const characterId of symbolTable.ids()) {
42
+ const character = symbolTable.get(characterId);
43
+ if (character?.type !== 'DefineBinaryData' || !hasSwfSignature(character.rawData)) continue;
44
+
45
+ const bytes = character.rawData;
46
+ const characterPath = [...ancestry, characterId];
47
+ const childDiagnostics = new DiagnosticsCollector();
48
+ try {
49
+ const movie = await compileChild(bytes, childDiagnostics, diagnostics, characterPath);
50
+ if (movie) embeddedSwfs.push({ ...movie, characterId });
51
+ } catch (err) {
52
+ childDiagnostics.error(err.message, 'emit');
53
+ } finally {
54
+ for (const issue of childDiagnostics.all()) {
55
+ diagnostics.warn(`Embedded SWF ${characterPath.join('/')}: ${issue.message}`,
56
+ issue.stage, { ...issue.context, embeddedCharacterPath: characterPath });
57
+ }
58
+ }
59
+ }
60
+
61
+ return embeddedSwfs;
62
+ }
63
+
64
+ function companionPath(url) {
65
+ if (!url || url.startsWith('/') || /[?#]/.test(url)) {
66
+ throw new Error(`Companion SWF must be a package-relative .swf path: ${url}`);
67
+ }
68
+ const parts = url.replace(/^\.\//, '').split('/').map(part => decodeURIComponent(part));
69
+ if (parts.some(part => !part || part === '.' || part === '..' || /[/\\:\x00-\x1f\x7f]/.test(part)) ||
70
+ !/\.swf$/i.test(parts.at(-1))) {
71
+ throw new Error(`Companion SWF must be a package-relative .swf path: ${url}`);
72
+ }
73
+ return parts;
74
+ }
75
+
76
+ export function companionSwfKey(url) {
77
+ if (/^https?:\/\//i.test(url)) {
78
+ const parsed = new URL(url);
79
+ const segments = parsed.pathname.split('/').map(part => encodeURIComponent(decodeURIComponent(part)));
80
+ if (parsed.username || parsed.password || !/\.swf$/i.test(segments.at(-1))) {
81
+ throw new Error('Companion URL must address a SWF: ' + url);
82
+ }
83
+ return parsed.origin + segments.join('/');
84
+ }
85
+ return companionPath(url).map(encodeURIComponent).join('/');
86
+ }
87
+
88
+ function referencedSiblings({ tags, actionScript }) {
89
+ const urls = new Set();
90
+ function add(reference) {
91
+ const path = reference.split(/[?#]/, 1)[0];
92
+ if (!/\.swf$/i.test(path)) return;
93
+ try {
94
+ const parts = companionPath(path);
95
+ if (parts.length === 1) urls.add(encodeURIComponent(parts[0]));
96
+ } catch (_) { /* Leave unresolvable or non-local URLs alone. */ }
97
+ }
98
+ for (const tag of tags) {
99
+ if (tag.type === 'ImportAssets' || tag.type === 'ImportAssets2') add(tag.url);
100
+ }
101
+ const fragments = [...actionScript.jsFragments, ...[...actionScript.legacyButtonScripts.values()].flat()];
102
+ for (const source of fragments) {
103
+ if (!/\.swf/i.test(source)) continue;
104
+ for (const token of tokenizer(source, { ecmaVersion: 'latest' })) {
105
+ if (token.type.label === 'string') add(token.value);
106
+ }
107
+ }
108
+ return urls;
109
+ }
110
+
111
+ function blankCompanion(companionUrl, diagnostics) {
112
+ const tags = [
113
+ { type: 'ShowFrame' },
114
+ { type: 'DoAction', bytecode: Uint8Array.of(OP.Stop, OP.End) },
115
+ { type: 'ShowFrame' },
116
+ ];
117
+ const header = {
118
+ version: 8, frameRate: 24, frameCount: 2,
119
+ frameSize: { xMin: 0, yMin: 0, xMax: 20, yMax: 20 },
120
+ };
121
+ return {
122
+ companionUrl, header, tags, symbolTable: new SymbolTable(), embeddedSwfs: [],
123
+ actionScript: transpileActionScript(tags, diagnostics, { sharedAvm1Runtime: true, swfVersion: header.version }),
124
+ };
125
+ }
126
+
127
+ /** Resolve URL aliases to local files and follow static references to siblings. */
128
+ export async function precompileCompanionSwfs(source, urls, diagnostics, rootMovie, blankUrls = []) {
129
+ const root = await realpath(dirname(resolve(source)));
130
+ const companions = new Map();
131
+ const queue = [];
132
+ for (const declaration of urls) {
133
+ const equals = declaration.indexOf('=');
134
+ const mapped = equals >= 0 && /\.swf$/i.test(declaration.slice(0, equals));
135
+ const requestedUrl = mapped ? declaration.slice(0, equals) : declaration;
136
+ const parts = mapped ? null : companionPath(requestedUrl);
137
+ const url = mapped ? companionSwfKey(requestedUrl) : parts.map(encodeURIComponent).join('/');
138
+ const input = mapped ? declaration.slice(equals + 1) : null;
139
+ if (mapped && !input) throw new Error('Missing local file for companion SWF ' + requestedUrl);
140
+ const file = mapped ? resolve(input) : resolve(root, ...parts);
141
+ queue.push({ url, requestedUrl, file, mapped });
142
+ }
143
+ for (const reference of blankUrls) {
144
+ const url = companionSwfKey(reference);
145
+ if (queue.some(entry => entry.url === url)) {
146
+ throw new Error('Companion SWF has both a local file and a blank replacement: ' + reference);
147
+ }
148
+ if (!companions.has(url)) companions.set(url, blankCompanion(url, diagnostics));
149
+ }
150
+ const manifest = resolve(root, basename(source).replace(/\.swf$/i, '') + '.companions.json');
151
+ const manifestSource = await readFile(manifest, 'utf8').catch(error => {
152
+ if (error.code !== 'ENOENT') throw error;
153
+ return null;
154
+ });
155
+ if (manifestSource !== null) {
156
+ const mappings = JSON.parse(manifestSource);
157
+ if (!mappings || typeof mappings !== 'object' || Array.isArray(mappings)) {
158
+ throw new Error('Expected a JSON object mapping SWF URLs to local paths in ' + manifest);
159
+ }
160
+ for (const [requestedUrl, path] of Object.entries(mappings)) {
161
+ const url = companionSwfKey(requestedUrl);
162
+ if (companions.has(url) || queue.some(entry => entry.url === url)) continue;
163
+ if (typeof path !== 'string' || !path || isAbsolute(path)) {
164
+ throw new Error('Expected an archive-relative path for ' + requestedUrl + ' in ' + manifest);
165
+ }
166
+ queue.push({ url, requestedUrl, file: resolve(root, path), mapped: true, packageLocal: true });
167
+ }
168
+ }
169
+ function includeSiblings(movie) {
170
+ for (const url of referencedSiblings(movie)) {
171
+ queue.push({ url, requestedUrl: url, file: resolve(root, decodeURIComponent(url)), automatic: true });
172
+ }
173
+ for (const child of movie.embeddedSwfs || []) includeSiblings(child);
174
+ }
175
+ if (rootMovie) includeSiblings(rootMovie);
176
+ const sourceFile = rootMovie && await realpath(source);
177
+ const attempted = new Set();
178
+ for (const { url, requestedUrl, file: candidate, automatic, mapped, packageLocal } of queue) {
179
+ if (companions.has(url)) continue;
180
+ if (automatic && attempted.has(url)) continue;
181
+ attempted.add(url);
182
+ try {
183
+ const file = await realpath(candidate);
184
+ const localPath = relative(root, file);
185
+ if ((!mapped || packageLocal) && (isAbsolute(localPath) || localPath === '..' || localPath.startsWith('..' + sep))) {
186
+ throw new Error(`Companion SWF is outside the source directory: ${requestedUrl}`);
187
+ }
188
+ if (automatic && (file === sourceFile || dirname(file) !== root)) continue;
189
+ if (!(await stat(file)).isFile()) throw new Error(`Companion SWF is not a file: ${requestedUrl}`);
190
+ if (mapped && /\.js$/i.test(candidate)) {
191
+ const factorySource = await readFile(file, 'utf8');
192
+ companions.set(url, { companionUrl: url, factorySource });
193
+ continue;
194
+ }
195
+ const bytes = new Uint8Array(await readFile(file));
196
+ if (!hasSwfSignature(bytes)) throw new Error(`Companion is not a SWF: ${requestedUrl}`);
197
+ const childDiagnostics = new DiagnosticsCollector();
198
+ const movie = await compileChild(bytes, childDiagnostics, diagnostics, [url]);
199
+ if (!movie) throw new Error(`Unable to compile companion SWF ${requestedUrl}: ${childDiagnostics.errors().map(issue => issue.message).join(', ')}`);
200
+ for (const issue of childDiagnostics.warnings()) {
201
+ diagnostics.warn(`Companion SWF ${url}: ${issue.message}`, issue.stage, issue.context);
202
+ }
203
+ companions.set(url, { ...movie, companionUrl: url });
204
+ if (dirname(file) === root && !url.includes('/')) includeSiblings(movie);
205
+ } catch (error) {
206
+ if (!automatic) throw error;
207
+ if (error.code !== 'ENOENT') diagnostics.warn(error.message, 'emit');
208
+ }
209
+ }
210
+ return [...companions.values()];
211
+ }
212
+
213
+ /** Emit the movie data and scripts with their local runtime bindings. */
214
+ export function embeddedSwfFactorySource(movie) {
215
+ const { stageW, stageH, frameRate, swfVersion, sourceBytes, assetManifest, timelineJs,
216
+ symbolClasses, linkedBinaryData, exportAssets, actionScriptJs } = movie;
217
+ const metadata = { stageW, stageH, frameRate, swfVersion, sourceBytes, assets: assetManifest,
218
+ symbolClasses, linkedBinaryData, exportAssets };
219
+ return `function (environment, loadMovieAssets, getBinaryPayload) {
220
+ return __swoof_swflib.createEmbeddedMovieRuntime(__swoof_swflib, globalThis,
221
+ environment, ${JSON.stringify(metadata)}, loadMovieAssets, getBinaryPayload, function (_embedded, _metadata) {
222
+ var globalThis = _embedded.global, window = globalThis, __swoof_swflib = _embedded.runtime;
223
+ var STAGE_WIDTH = _metadata.stageW, STAGE_HEIGHT = _metadata.stageH, FRAME_RATE = _metadata.frameRate;
224
+ var BACKGROUND = 'transparent';
225
+ var SWF_VERSION = _metadata.swfVersion;
226
+ var SYMBOL_CLASSES = _metadata.symbolClasses, EXPORT_ASSETS = _metadata.exportAssets, ASSETS = _metadata.assets;
227
+ var loaded = _embedded.loaded, ctx = _embedded.ctx;
228
+
229
+ ${timelineJs}
230
+
231
+ var _embeddedTimeline = _embedded.bindTimeline(timeline, displayList, CHARACTERS, FRAMES, FRAME_COUNT);
232
+ var root = _embeddedTimeline.root;
233
+ var __swoof_root = root;
234
+ var bindConstructingDocument = _embeddedTimeline.bindConstructingDocument;
235
+
236
+ function resolveLinkedClass(name) {
237
+ return typeof _getDefinition === 'function' ? _getDefinition(name) : null;
238
+ }
239
+
240
+ ${actionScriptJs}
241
+
242
+ return _embeddedTimeline.boot(typeof _classes === 'undefined' ? null : _classes, resolveLinkedClass,
243
+ typeof _runAvm2Initializers === 'function' ? _runAvm2Initializers : null);
244
+ });
245
+ }`;
246
+ }
@@ -0,0 +1,365 @@
1
+ const UNITS_PER_EM = 1024;
2
+ const GLYPH_OPT = { min: -32768, max: 32767 };
3
+
4
+ function signed(value) { return Math.max(GLYPH_OPT.min, Math.min(GLYPH_OPT.max, value)); }
5
+ function unsigned(value) { return Math.max(0, Math.min(65535, value)); }
6
+ function aligned(size) { return (size + 3) & ~3; }
7
+
8
+ function searchFields(count, width) {
9
+ if (!count) return [0, 0, 0];
10
+ const selector = Math.floor(Math.log2(count));
11
+ const range = (2 ** selector) * width;
12
+ return [range, selector, count * width - range];
13
+ }
14
+
15
+ function boundsOf(points) {
16
+ if (!points.length) return { xMin: 0, yMin: 0, xMax: 0, yMax: 0 };
17
+ let xMin = Infinity, yMin = Infinity, xMax = -Infinity, yMax = -Infinity;
18
+ for (const { x, y } of points) {
19
+ xMin = Math.min(xMin, x); xMax = Math.max(xMax, x);
20
+ yMin = Math.min(yMin, y); yMax = Math.max(yMax, y);
21
+ }
22
+ return { xMin, yMin, xMax, yMax };
23
+ }
24
+
25
+ function writeBounds(table, offset, bounds) {
26
+ ['xMin', 'yMin', 'xMax', 'yMax'].forEach((field, index) => table.writeInt16BE(bounds[field], offset + index * 2));
27
+ }
28
+
29
+ function encodeGlyph(path, scale) {
30
+ const contours = [];
31
+ let contour = [];
32
+ function finish() {
33
+ if (contour.length > 1) {
34
+ const first = contour[0], end = contour[contour.length - 1];
35
+ if (end.on && end.x === first.x && end.y === first.y) contour.pop();
36
+ if (contour.length > 1) contours.push(contour);
37
+ }
38
+ contour = [];
39
+ }
40
+ function point(x, y, on) {
41
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('Invalid glyph point');
42
+ const nx = scale(x), ny = -scale(y);
43
+ if (signed(nx) !== nx || signed(ny) !== ny) throw new Error('Glyph point is outside the TrueType range');
44
+ contour.push({ x: nx, y: ny, on });
45
+ }
46
+ for (const [op, x, y, nx, ny] of path) {
47
+ if (op === 'M') { finish(); point(x, y, true); }
48
+ else if (op === 'L' && contour.length) point(x, y, true);
49
+ else if (op === 'Q' && contour.length) { point(x, y, false); point(nx, ny, true); }
50
+ else if (op === 'Z') finish();
51
+ else throw new Error('Unsupported glyph path');
52
+ }
53
+ finish();
54
+
55
+ const points = contours.flat();
56
+ const bounds = boundsOf(points);
57
+ if (!points.length) return { data: Buffer.alloc(0), contours: 0, points: 0, bounds };
58
+ if (contours.length > 32767 || points.length > 65535) throw new Error('Oversized glyph outline');
59
+
60
+ const header = 12 + contours.length * 2;
61
+ const data = Buffer.alloc(aligned(header + points.length * 5));
62
+ data.writeInt16BE(contours.length, 0);
63
+ writeBounds(data, 2, bounds);
64
+ let end = -1;
65
+ for (const [index, part] of contours.entries()) {
66
+ end += part.length;
67
+ data.writeUInt16BE(end, 10 + index * 2);
68
+ }
69
+ let x = 0, y = 0;
70
+ for (const [index, p] of points.entries()) {
71
+ data[header + index] = p.on ? 1 : 0;
72
+ data.writeInt16BE(p.x - x, header + points.length + index * 2);
73
+ data.writeInt16BE(p.y - y, header + 3 * points.length + index * 2);
74
+ x = p.x; y = p.y;
75
+ }
76
+ return { data, contours: contours.length, points: points.length, bounds };
77
+ }
78
+
79
+ function encodeCmap(mapping) {
80
+ const groups = [];
81
+ for (const [code, glyph] of mapping) {
82
+ const prior = groups[groups.length - 1];
83
+ if (prior && code === prior.end + 1 && glyph === prior.glyph + code - prior.start) prior.end = code;
84
+ else groups.push({ start: code, end: code, glyph });
85
+ }
86
+ const cmap12 = Buffer.alloc(16 + groups.length * 12);
87
+ cmap12.writeUInt16BE(12, 0);
88
+ cmap12.writeUInt32BE(cmap12.length, 4);
89
+ cmap12.writeUInt32BE(groups.length, 12);
90
+ for (const [index, group] of groups.entries()) {
91
+ cmap12.writeUInt32BE(group.start, 16 + index * 12);
92
+ cmap12.writeUInt32BE(group.end, 20 + index * 12);
93
+ cmap12.writeUInt32BE(group.glyph, 24 + index * 12);
94
+ }
95
+
96
+ const segments = groups.filter(group => group.start < 0xffff).map(group =>
97
+ ({ start: group.start, end: Math.min(0xfffe, group.end), delta: (group.glyph - group.start) & 0xffff }));
98
+ segments.push({ start: 0xffff, end: 0xffff, delta: 1 });
99
+ const count = segments.length;
100
+ const cmap4 = 16 + count * 8 <= 65535 ? Buffer.alloc(16 + count * 8) : null;
101
+ if (cmap4) {
102
+ cmap4.writeUInt16BE(4, 0);
103
+ cmap4.writeUInt16BE(cmap4.length, 2);
104
+ cmap4.writeUInt16BE(count * 2, 6);
105
+ searchFields(count, 2).forEach((value, index) => cmap4.writeUInt16BE(value, 8 + index * 2));
106
+ for (const [index, segment] of segments.entries()) {
107
+ cmap4.writeUInt16BE(segment.end, 14 + index * 2);
108
+ cmap4.writeUInt16BE(segment.start, 16 + (count + index) * 2);
109
+ cmap4.writeUInt16BE(segment.delta, 16 + (2 * count + index) * 2);
110
+ }
111
+ }
112
+
113
+ const records = cmap4 ? [[3, 1, cmap4], [3, 10, cmap12]] : [[3, 10, cmap12]];
114
+ const directory = Buffer.alloc(4 + records.length * 8);
115
+ directory.writeUInt16BE(records.length, 2);
116
+ let offset = directory.length;
117
+ for (const [index, [platform, encoding, table]] of records.entries()) {
118
+ const address = 4 + index * 8;
119
+ directory.writeUInt16BE(platform, address);
120
+ directory.writeUInt16BE(encoding, address + 2);
121
+ directory.writeUInt32BE(offset, address + 4);
122
+ offset += table.length;
123
+ }
124
+ return Buffer.concat([directory, ...records.map(record => record[2])]);
125
+ }
126
+
127
+ function encodeName(name, bold, italic) {
128
+ const family = String(name || 'SWF Embedded Font').replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 120) || 'SWF Embedded Font';
129
+ const style = bold && italic ? 'Bold Italic' : bold ? 'Bold' : italic ? 'Italic' : 'Regular';
130
+ const full = style === 'Regular' ? family : family + ' ' + style;
131
+ const postscript = full.replace(/[^a-z0-9-]+/gi, '-').slice(0, 63) || 'SWFEmbeddedFont';
132
+ const values = [[1, family], [2, style], [3, postscript], [4, full], [6, postscript]];
133
+ const directory = Buffer.alloc(6 + 12 * values.length);
134
+ directory.writeUInt16BE(values.length, 2);
135
+ directory.writeUInt16BE(directory.length, 4);
136
+ const strings = [];
137
+ let offset = 0;
138
+ for (const [index, [id, value]] of values.entries()) {
139
+ const data = Buffer.from(value, 'utf16le').swap16();
140
+ const record = 6 + index * 12;
141
+ [3, 1, 0x409, id, data.length, offset].forEach((part, index) => directory.writeUInt16BE(part, record + index * 2));
142
+ strings.push(data);
143
+ offset += data.length;
144
+ }
145
+ return Buffer.concat([directory, ...strings]);
146
+ }
147
+
148
+ function addAuthoredNames(table, font) {
149
+ const values = [[0, font.copyright], [4, font.fullName]].filter(([, value]) => value);
150
+ if (!values.length || table.length < 6) return table;
151
+ const count = table.readUInt16BE(2);
152
+ const recordEnd = 6 + 12 * count;
153
+ const storage = table.readUInt16BE(4);
154
+ if (table.readUInt16BE(0) > 1 || storage < recordEnd || storage > table.length) return table;
155
+
156
+ let records = Array.from({ length: count }, (_, index) => table.subarray(6 + 12 * index, 18 + 12 * index));
157
+ const extra = table.subarray(recordEnd, storage); // Format 1 can carry language-tag records here.
158
+ const strings = [table.subarray(storage)];
159
+ let offset = strings[0].length;
160
+ for (const [id, value] of values) {
161
+ const data = Buffer.from(value, 'utf16le').swap16();
162
+ if (data.length > 65535 || offset > 65535) continue;
163
+ const record = Buffer.alloc(12);
164
+ [3, 1, 0x409, id, data.length, offset].forEach((part, index) => record.writeUInt16BE(part, index * 2));
165
+ const selector = record.subarray(0, 8);
166
+ records = records.filter(existing => !existing.subarray(0, 8).equals(selector));
167
+ records.push(record);
168
+ strings.push(data);
169
+ offset += data.length;
170
+ }
171
+ const newStorage = 6 + 12 * records.length + extra.length;
172
+ if (strings.length === 1 || newStorage > 65535) return table;
173
+ records.sort((a, b) => a.subarray(0, 8).compare(b.subarray(0, 8)));
174
+ const header = Buffer.from(table.subarray(0, 6));
175
+ header.writeUInt16BE(records.length, 2);
176
+ header.writeUInt16BE(newStorage, 4);
177
+ return Buffer.concat([header, ...records, extra, ...strings]);
178
+ }
179
+
180
+ function encodeKern(kerning, mapping, scale) {
181
+ const pairs = new Map();
182
+ for (const [left, right, adjustment] of kerning || []) {
183
+ const a = mapping.get(left), b = mapping.get(right);
184
+ if (a == null || b == null || !Number.isFinite(adjustment)) continue;
185
+ const value = signed(scale(adjustment));
186
+ if (value) pairs.set(a * 65536 + b, value);
187
+ }
188
+ if (!pairs.size) return null;
189
+ const sorted = [...pairs].sort((a, b) => a[0] - b[0]);
190
+ const tables = [];
191
+ const limit = Math.floor((65535 - 14) / 6);
192
+ for (let start = 0; start < sorted.length; start += limit) {
193
+ const chunk = sorted.slice(start, start + limit);
194
+ const table = Buffer.alloc(14 + chunk.length * 6);
195
+ table.writeUInt16BE(table.length, 2);
196
+ table.writeUInt16BE(1, 4); // Horizontal kerning, format 0.
197
+ table.writeUInt16BE(chunk.length, 6);
198
+ searchFields(chunk.length, 6).forEach((value, index) => table.writeUInt16BE(value, 8 + index * 2));
199
+ for (const [index, [key, value]] of chunk.entries()) {
200
+ table.writeUInt32BE(key, 14 + index * 6);
201
+ table.writeInt16BE(value, 18 + index * 6);
202
+ }
203
+ tables.push(table);
204
+ }
205
+ const header = Buffer.alloc(4);
206
+ header.writeUInt16BE(tables.length, 2);
207
+ return Buffer.concat([header, ...tables]);
208
+ }
209
+
210
+ function checksum(data) {
211
+ let value = 0;
212
+ for (let at = 0; at < data.length; at += 4) {
213
+ const word = ((data[at] || 0) << 24) | ((data[at + 1] || 0) << 16) | ((data[at + 2] || 0) << 8) | (data[at + 3] || 0);
214
+ value = (value + word) >>> 0;
215
+ }
216
+ return value;
217
+ }
218
+
219
+ function encodeSfnt(tables) {
220
+ const entries = Object.entries(tables).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
221
+ const directorySize = 12 + 16 * entries.length;
222
+ const file = Buffer.alloc(directorySize + entries.reduce((size, [, table]) => size + aligned(table.length), 0));
223
+ file.writeUInt32BE(tables['CFF '] ? 0x4f54544f : 0x00010000, 0);
224
+ file.writeUInt16BE(entries.length, 4);
225
+ searchFields(entries.length, 16).forEach((value, index) => file.writeUInt16BE(value, 6 + index * 2));
226
+ let offset = directorySize, headOffset = 0;
227
+ for (const [index, [tag, table]] of entries.entries()) {
228
+ const record = 12 + index * 16;
229
+ file.write(tag, record, 4, 'ascii');
230
+ file.writeUInt32BE(checksum(table), record + 4);
231
+ file.writeUInt32BE(offset, record + 8);
232
+ file.writeUInt32BE(table.length, record + 12);
233
+ if (tag === 'head') headOffset = offset;
234
+ table.copy(file, offset);
235
+ offset += aligned(table.length);
236
+ }
237
+ file.writeUInt32BE((0xb1b0afba - checksum(file)) >>> 0, headOffset + 8);
238
+ return file;
239
+ }
240
+
241
+ function encodeCffFont(font) {
242
+ if (!font.fontData) return null;
243
+ const bytes = Buffer.from(font.fontData);
244
+ const tables = Object.create(null);
245
+ for (let index = 0; index < bytes.readUInt16BE(4); index++) {
246
+ const record = 12 + 16 * index;
247
+ const tag = bytes.toString('ascii', record, record + 4);
248
+ const start = bytes.readUInt32BE(record + 8);
249
+ tables[tag] = bytes.subarray(start, start + bytes.readUInt32BE(record + 12));
250
+ }
251
+ // SWF allows the name table to be absent, while browser font sanitizers require it.
252
+ const name = addAuthoredNames(tables.name || encodeName(font.name, !!(font.flags & 1), !!(font.flags & 2)), font);
253
+ if (name === tables.name) return bytes;
254
+ tables.head = Buffer.from(tables.head);
255
+ tables.head.writeUInt32BE(0, 8);
256
+ tables.name = name;
257
+ return encodeSfnt(tables);
258
+ }
259
+
260
+ /** Return a browser font from an authored DefineFont2/3 subset or decoded DefineFont4. */
261
+ export function encodeBrowserFont(font) {
262
+ const { version, glyphs, codes, layout } = font || {};
263
+ if (version === 4) return encodeCffFont(font);
264
+ if ((version !== 2 && version !== 3) || !glyphs?.length || glyphs.length >= 65535 ||
265
+ codes?.length !== glyphs.length || layout?.advances?.length !== glyphs.length ||
266
+ ![layout.ascent, layout.descent, layout.leading, ...layout.advances].every(Number.isFinite)) return null;
267
+
268
+ const scale = value => Math.round(value / (version === 3 ? 20 : 1));
269
+ const mapping = new Map();
270
+ for (const [index, code] of codes.entries()) {
271
+ if (Number.isInteger(code) && code >= 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) && !mapping.has(code)) {
272
+ mapping.set(code, index + 1);
273
+ }
274
+ }
275
+ if (!mapping.size) return null;
276
+ const codeMap = [...mapping].sort((a, b) => a[0] - b[0]);
277
+
278
+ try {
279
+ const outlines = [encodeGlyph([], scale)];
280
+ for (const glyph of glyphs) outlines.push(encodeGlyph(glyph?.path ?? [], scale));
281
+ const glyphCount = outlines.length;
282
+ const loca = Buffer.alloc(4 * (glyphCount + 1));
283
+ const hmtx = Buffer.alloc(4 * glyphCount);
284
+ let offset = 0, advanceMax = 0, lsbMin = 32767, rsbMin = 32767, extentMax = -32768;
285
+ for (const [index, outline] of outlines.entries()) {
286
+ loca.writeUInt32BE(offset, index * 4);
287
+ offset += outline.data.length;
288
+ const advance = index ? unsigned(scale(layout.advances[index - 1])) : UNITS_PER_EM / 2;
289
+ const { xMin: lsb, xMax } = outline.bounds;
290
+ hmtx.writeUInt16BE(advance, index * 4);
291
+ hmtx.writeInt16BE(lsb, index * 4 + 2);
292
+ advanceMax = Math.max(advanceMax, advance);
293
+ if (outline.contours) {
294
+ lsbMin = Math.min(lsbMin, lsb);
295
+ rsbMin = Math.min(rsbMin, advance - xMax);
296
+ extentMax = Math.max(extentMax, xMax);
297
+ }
298
+ }
299
+ loca.writeUInt32BE(offset, glyphCount * 4);
300
+ const rendered = outlines.filter(glyph => glyph.contours);
301
+ if (!rendered.length) return null;
302
+ const bounds = boundsOf(rendered.flatMap(({ bounds }) => [
303
+ { x: bounds.xMin, y: bounds.yMin }, { x: bounds.xMax, y: bounds.yMax },
304
+ ]));
305
+ const bold = !!(font.flags & 1), italic = !!(font.flags & 2);
306
+ const ascent = signed(Math.abs(scale(layout.ascent)));
307
+ const descent = signed(-Math.abs(scale(layout.descent)));
308
+ const leading = signed(scale(layout.leading));
309
+
310
+ const head = Buffer.alloc(54);
311
+ head.writeUInt32BE(0x00010000, 0);
312
+ head.writeUInt32BE(0x00010000, 4);
313
+ head.writeUInt32BE(0x5f0f3cf5, 12);
314
+ head.writeUInt16BE(3, 16);
315
+ head.writeUInt16BE(UNITS_PER_EM, 18);
316
+ writeBounds(head, 36, bounds);
317
+ head.writeUInt16BE((bold ? 1 : 0) | (italic ? 2 : 0), 44);
318
+ head.writeUInt16BE(8, 46);
319
+ head.writeInt16BE(2, 48);
320
+ head.writeInt16BE(1, 50); // loca uses 32-bit offsets.
321
+
322
+ const hhea = Buffer.alloc(36);
323
+ hhea.writeUInt32BE(0x00010000, 0);
324
+ hhea.writeInt16BE(ascent, 4);
325
+ hhea.writeInt16BE(descent, 6);
326
+ hhea.writeInt16BE(leading, 8);
327
+ hhea.writeUInt16BE(advanceMax, 10);
328
+ hhea.writeInt16BE(lsbMin, 12);
329
+ hhea.writeInt16BE(signed(rsbMin), 14);
330
+ hhea.writeInt16BE(extentMax, 16);
331
+ hhea.writeInt16BE(1, 18);
332
+ hhea.writeUInt16BE(glyphCount, 34);
333
+
334
+ const maxp = Buffer.alloc(32);
335
+ maxp.writeUInt32BE(0x00010000, 0);
336
+ maxp.writeUInt16BE(glyphCount, 4);
337
+ maxp.writeUInt16BE(outlines.reduce((max, glyph) => Math.max(max, glyph.points), 0), 6);
338
+ maxp.writeUInt16BE(outlines.reduce((max, glyph) => Math.max(max, glyph.contours), 0), 8);
339
+ maxp.writeUInt16BE(1, 14);
340
+
341
+ const os2 = Buffer.alloc(78);
342
+ const average = Math.round(layout.advances.reduce((sum, value) => sum + scale(value), 0) / glyphs.length);
343
+ os2.writeInt16BE(signed(average), 2);
344
+ os2.writeUInt16BE(bold ? 700 : 400, 4);
345
+ os2.writeUInt16BE(5, 6);
346
+ os2.writeUInt16BE((italic ? 1 : 0) | (bold ? 32 : 0) | (!italic && !bold ? 64 : 0), 62);
347
+ os2.writeUInt16BE(unsigned(codeMap[0][0]), 64);
348
+ os2.writeUInt16BE(unsigned(codeMap[codeMap.length - 1][0]), 66);
349
+ os2.writeInt16BE(ascent, 68);
350
+ os2.writeInt16BE(descent, 70);
351
+ os2.writeInt16BE(leading, 72);
352
+ os2.writeUInt16BE(Math.max(ascent, bounds.yMax), 74);
353
+ os2.writeUInt16BE(Math.max(-descent, -bounds.yMin), 76);
354
+
355
+ const post = Buffer.alloc(32);
356
+ post.writeUInt32BE(0x00030000, 0);
357
+ const tables = { cmap: encodeCmap(codeMap), glyf: Buffer.concat(outlines.map(glyph => glyph.data)),
358
+ head, hhea, hmtx, loca, maxp, name: addAuthoredNames(encodeName(font.name, bold, italic), font), 'OS/2': os2, post };
359
+ const kern = encodeKern(layout.kerning, mapping, scale);
360
+ if (kern) tables.kern = kern;
361
+ return encodeSfnt(tables);
362
+ } catch (_) {
363
+ return null;
364
+ }
365
+ }
@@ -0,0 +1,58 @@
1
+ import { gzipSync } from 'node:zlib';
2
+
3
+ const PACK_THRESHOLD_BYTES = 8 * 1024 * 1024;
4
+
5
+ // A classic script can be loaded relative to index.html under file://. Only
6
+ // the already-read bytes go through the browser decompressor.
7
+ export function openPackedTimeline(payload) {
8
+ function fail(error) {
9
+ console.error('swoof: packed timeline', error);
10
+ function showError() {
11
+ var message = document.createElement('p');
12
+ message.setAttribute('role', 'alert');
13
+ message.textContent = error.message;
14
+ document.body.appendChild(message);
15
+ }
16
+ if (document.body) showError();
17
+ else document.addEventListener('DOMContentLoaded', showError, { once: true });
18
+ }
19
+
20
+ if (typeof DecompressionStream !== 'function') {
21
+ fail(new Error('This browser cannot decode packed SWF timelines. Regenerate this bundle with --plain-timeline.'));
22
+ return;
23
+ }
24
+
25
+ Promise.resolve().then(function () {
26
+ var raw = atob(payload);
27
+ var bytes = new Uint8Array(raw.length);
28
+ for (var i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
29
+ var gzip = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
30
+ return new Response(gzip).text();
31
+ }).then(function (json) {
32
+ globalThis.__swoofTimelineData = JSON.parse(json);
33
+ var script = document.createElement('script');
34
+ script.src = 'bundle.js';
35
+ script.onerror = function () { fail(new Error('Unable to load bundle.js after decoding the SWF timeline.')); };
36
+ document.head.appendChild(script);
37
+ }).catch(fail);
38
+ }
39
+
40
+ export function encodeTimelineDataScript(data, mode = 'plain') {
41
+ const json = `{
42
+ "frames": ${data.frames},
43
+ "characters": ${data.characters},
44
+ "frameCount": ${data.frameCount},
45
+ "scenes": ${data.scenes}
46
+ }`;
47
+ const raw = `globalThis.__swoofTimelineData = ${json};\n`;
48
+ if (mode === 'plain' || (mode === 'auto' && Buffer.byteLength(raw) < PACK_THRESHOLD_BYTES)) {
49
+ return { source: raw, packed: false };
50
+ }
51
+
52
+ const payload = gzipSync(json).toString('base64');
53
+ const source = `globalThis.__swoof_swflib.openPackedTimeline(${JSON.stringify(payload)});\n`;
54
+ if (mode === 'auto' && Buffer.byteLength(source) >= Buffer.byteLength(raw)) {
55
+ return { source: raw, packed: false };
56
+ }
57
+ return { source, packed: true };
58
+ }