swf2js 0.1.2 → 0.4.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 (416) hide show
  1. package/README.md +81 -14
  2. package/package.json +11 -7
  3. package/studio/actionscript-roundtrip.test.js +54 -0
  4. package/studio/actionscript-scripts.test.js +169 -0
  5. package/studio/animated-image.test.js +137 -0
  6. package/studio/arithmetic.test.js +16 -0
  7. package/studio/as3-import.test.js +110 -0
  8. package/studio/audio-info.test.js +44 -0
  9. package/studio/components.test.js +152 -0
  10. package/studio/document-editing.test.js +92 -0
  11. package/studio/examples/01-space-mission.json +1628 -0
  12. package/studio/examples/02-clockwork-vault.json +1079 -0
  13. package/studio/examples/03-neon-synth.json +1364 -0
  14. package/studio/examples/04-kinetic-poster.json +923 -0
  15. package/studio/examples/05-signal-relay.json +1131 -0
  16. package/studio/examples/06-calculator.json +564 -0
  17. package/studio/frame-editing.test.js +129 -0
  18. package/studio/frame-events.test.js +117 -0
  19. package/studio/groups.test.js +88 -0
  20. package/studio/index.html +962 -0
  21. package/studio/interaction-triggers.test.js +37 -0
  22. package/studio/linked-actions.test.js +48 -0
  23. package/studio/lottie.test.js +208 -0
  24. package/studio/masks.test.js +43 -0
  25. package/studio/media-assets.test.js +62 -0
  26. package/studio/paint-tools.test.js +60 -0
  27. package/studio/playback.test.js +17 -0
  28. package/studio/project-io.test.js +405 -0
  29. package/studio/project-preview.test.js +475 -0
  30. package/studio/scene-transition.test.js +32 -0
  31. package/studio/server/archive-companions.js +27 -0
  32. package/studio/server/as3-library.js +91 -0
  33. package/studio/server/assets.js +162 -0
  34. package/studio/server/audio-info.js +82 -0
  35. package/studio/server/font-files.js +332 -0
  36. package/studio/server/http.js +135 -0
  37. package/studio/server/linked-actions.js +93 -0
  38. package/studio/server/png-decode.js +1 -0
  39. package/studio/server/project-movie.js +1164 -0
  40. package/studio/server/project-preview.js +152 -0
  41. package/studio/server/projects.js +370 -0
  42. package/studio/server/report.js +29 -0
  43. package/studio/server/routes.js +93 -0
  44. package/studio/server/swf-authoring.js +90 -0
  45. package/studio/server/swf-control-runtime.as +513 -0
  46. package/studio/server/swf-controls.js +119 -0
  47. package/studio/server/swf-export.js +293 -0
  48. package/studio/server/swf-import.js +1675 -0
  49. package/studio/server/swf-morphs.js +64 -0
  50. package/studio/server/swf-routes.js +42 -0
  51. package/studio/server/swf-streams.js +80 -0
  52. package/studio/server/swf-transition-runtime.as +52 -0
  53. package/studio/server/tween-recovery.js +106 -0
  54. package/studio/server-api.test.js +283 -0
  55. package/studio/server.js +320 -0
  56. package/studio/src/animated-image.js +423 -0
  57. package/studio/src/appearance-inspector.js +63 -0
  58. package/studio/src/arithmetic.js +50 -0
  59. package/studio/src/authored-controls.js +42 -0
  60. package/studio/src/busy.js +41 -0
  61. package/studio/src/canvas.js +430 -0
  62. package/studio/src/clipper-browser.js +2 -0
  63. package/studio/src/color-transform.js +38 -0
  64. package/studio/src/component-inspector.js +126 -0
  65. package/studio/src/components.js +268 -0
  66. package/studio/src/display-frame.js +262 -0
  67. package/studio/src/document-editing.js +69 -0
  68. package/studio/src/event-editor.js +150 -0
  69. package/studio/src/frame-editing.js +150 -0
  70. package/studio/src/frame-events.js +128 -0
  71. package/studio/src/frame-image.js +28 -0
  72. package/studio/src/groups.js +125 -0
  73. package/studio/src/handler-editor.js +122 -0
  74. package/studio/src/history.js +83 -0
  75. package/studio/src/imported-paths.js +99 -0
  76. package/studio/src/index.js +3582 -0
  77. package/studio/src/interaction-triggers.js +42 -0
  78. package/studio/src/json-patch.js +77 -0
  79. package/studio/src/layer-icons.js +25 -0
  80. package/studio/src/lottie-export.js +948 -0
  81. package/studio/src/lottie-import.js +1138 -0
  82. package/studio/src/masks.js +69 -0
  83. package/studio/src/media-assets.js +188 -0
  84. package/studio/src/media-library.js +193 -0
  85. package/studio/src/model.js +431 -0
  86. package/studio/src/numeric-fields.js +46 -0
  87. package/studio/src/object-list.js +57 -0
  88. package/studio/src/paint-tools.js +76 -0
  89. package/studio/src/placement-effects.js +74 -0
  90. package/studio/src/playback.js +10 -0
  91. package/studio/src/preview-audio.js +64 -0
  92. package/studio/src/preview-interactions.js +106 -0
  93. package/studio/src/preview-recorder.js +335 -0
  94. package/studio/src/preview-surface.js +338 -0
  95. package/studio/src/project-io.js +905 -0
  96. package/studio/src/project-session.js +375 -0
  97. package/studio/src/projects-dialog.js +319 -0
  98. package/studio/src/scene-transition.js +129 -0
  99. package/studio/src/script-editor.js +175 -0
  100. package/studio/src/script-references.js +74 -0
  101. package/studio/src/scripted-controls.js +146 -0
  102. package/studio/src/scripts.js +185 -0
  103. package/studio/src/stage-guides.js +101 -0
  104. package/studio/src/svg-animation.js +416 -0
  105. package/studio/src/svg-context.js +522 -0
  106. package/studio/src/svg-frame.js +413 -0
  107. package/studio/src/svg-import.js +1208 -0
  108. package/studio/src/swf-recording.js +104 -0
  109. package/studio/src/symbol-library.js +39 -0
  110. package/studio/src/symbols.js +62 -0
  111. package/studio/src/text-fields.js +58 -0
  112. package/studio/src/theme.js +43 -0
  113. package/studio/src/timeline.js +321 -0
  114. package/studio/src/vector-cut.js +103 -0
  115. package/studio/src/vector-geometry.js +254 -0
  116. package/studio/src/vector-style.js +146 -0
  117. package/studio/src/video-encode.js +84 -0
  118. package/studio/src/video-export.js +331 -0
  119. package/studio/src/video-mux.js +339 -0
  120. package/studio/src/video-playback.js +281 -0
  121. package/studio/src/workspace.js +344 -0
  122. package/studio/stroke-style.test.js +119 -0
  123. package/studio/styles.css +1547 -0
  124. package/studio/svg-export.test.js +162 -0
  125. package/studio/svg-import.test.js +318 -0
  126. package/studio/swf-authoring.test.js +140 -0
  127. package/studio/swf-export.test.js +324 -0
  128. package/studio/swf-import.test.js +489 -0
  129. package/studio/symbols.test.js +68 -0
  130. package/studio/tests/accessibility-interactions.mjs +138 -0
  131. package/studio/tests/appearance-interactions.mjs +103 -0
  132. package/studio/tests/control-interactions.mjs +60 -0
  133. package/studio/tests/event-interactions.mjs +117 -0
  134. package/studio/tests/external-resources.mjs +174 -0
  135. package/studio/tests/frame-image.mjs +71 -0
  136. package/studio/tests/html-export.mjs +68 -0
  137. package/studio/tests/import-files.mjs +131 -0
  138. package/studio/tests/lottie.mjs +125 -0
  139. package/studio/tests/mask-interactions.mjs +148 -0
  140. package/studio/tests/media-interactions.mjs +109 -0
  141. package/studio/tests/paint-interactions.mjs +64 -0
  142. package/studio/tests/project-interactions.mjs +244 -0
  143. package/studio/tests/script-interactions.mjs +178 -0
  144. package/studio/tests/scripted-control-interactions.mjs +107 -0
  145. package/studio/tests/svg-export.mjs +149 -0
  146. package/studio/tests/text-field-interactions.mjs +64 -0
  147. package/studio/tests/theme-interactions.mjs +53 -0
  148. package/studio/tests/timeline-browser.mjs +507 -0
  149. package/studio/tests/transition-interactions.mjs +94 -0
  150. package/studio/tests/trigger-interactions.mjs +93 -0
  151. package/studio/tests/video-export.mjs +243 -0
  152. package/studio/tests/workspace-interactions.mjs +226 -0
  153. package/studio/tween-recovery.test.js +31 -0
  154. package/studio/vector-style.test.js +56 -0
  155. package/studio/video-export.test.js +326 -0
  156. package/studiospec/actionscript.md +88 -0
  157. package/studiospec/architecture.md +378 -0
  158. package/studiospec/controls.md +100 -0
  159. package/studiospec/file-support.md +268 -0
  160. package/studiospec/lottie.md +69 -0
  161. package/studiospec/requirements.md +135 -0
  162. package/studiospec/stroke-style.md +95 -0
  163. package/studiospec/svg-export.md +83 -0
  164. package/studiospec/svg-import.md +139 -0
  165. package/studiospec/swooflib-integration.md +115 -0
  166. package/studiospec/tasks.md +573 -0
  167. package/studiospec/video-export.md +127 -0
  168. package/swf2js/__tests__/actionscript.test.js +1609 -0
  169. package/swf2js/__tests__/adpcm-audio.test.js +43 -0
  170. package/swf2js/__tests__/as2-compiler.test.js +153 -0
  171. package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
  172. package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
  173. package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
  174. package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
  175. package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
  176. package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
  177. package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
  178. package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
  179. package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
  180. package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
  181. package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
  182. package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
  183. package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
  184. package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
  185. package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
  186. package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
  187. package/swf2js/__tests__/avm1-key-events.test.js +52 -0
  188. package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
  189. package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
  190. package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
  191. package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
  192. package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
  193. package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
  194. package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
  195. package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
  196. package/swf2js/__tests__/avm1-super.test.js +70 -0
  197. package/swf2js/__tests__/avm1-target-path.test.js +325 -0
  198. package/swf2js/__tests__/avm1-try.test.js +229 -0
  199. package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
  200. package/swf2js/__tests__/avm2-applytype.test.js +180 -0
  201. package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
  202. package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
  203. package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
  204. package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
  205. package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
  206. package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
  207. package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
  208. package/swf2js/__tests__/avm2-e4x.test.js +326 -0
  209. package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
  210. package/swf2js/__tests__/avm2-findprop.test.js +110 -0
  211. package/swf2js/__tests__/avm2-getlex.test.js +166 -0
  212. package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
  213. package/swf2js/__tests__/avm2-interface.test.js +95 -0
  214. package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
  215. package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
  216. package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
  217. package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
  218. package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
  219. package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
  220. package/swf2js/__tests__/avm2-protected.test.js +214 -0
  221. package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
  222. package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
  223. package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
  224. package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
  225. package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
  226. package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
  227. package/swf2js/__tests__/bevel-filter.test.js +116 -0
  228. package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
  229. package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
  230. package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
  231. package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
  232. package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
  233. package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
  234. package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
  235. package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
  236. package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
  237. package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
  238. package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
  239. package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
  240. package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
  241. package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
  242. package/swf2js/__tests__/blur-filter.test.js +48 -0
  243. package/swf2js/__tests__/bundle-emitter.test.js +394 -0
  244. package/swf2js/__tests__/button-actions.test.js +370 -0
  245. package/swf2js/__tests__/button-color-transform.test.js +48 -0
  246. package/swf2js/__tests__/button-decoder.test.js +106 -0
  247. package/swf2js/__tests__/button-hit-test.test.js +825 -0
  248. package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
  249. package/swf2js/__tests__/button-sound.test.js +105 -0
  250. package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
  251. package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
  252. package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
  253. package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
  254. package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
  255. package/swf2js/__tests__/companion-swf.test.js +638 -0
  256. package/swf2js/__tests__/context-menu.test.js +149 -0
  257. package/swf2js/__tests__/convolution-filter.test.js +74 -0
  258. package/swf2js/__tests__/definefont4.test.js +280 -0
  259. package/swf2js/__tests__/display-displacement.test.js +161 -0
  260. package/swf2js/__tests__/display-list.test.js +80 -0
  261. package/swf2js/__tests__/display-mask-render.test.js +656 -0
  262. package/swf2js/__tests__/displayobject-stage.test.js +320 -0
  263. package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
  264. package/swf2js/__tests__/embedded-swf.test.js +202 -0
  265. package/swf2js/__tests__/embedded-textfield.test.js +107 -0
  266. package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
  267. package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
  268. package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
  269. package/swf2js/__tests__/event-priority-order.test.js +125 -0
  270. package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
  271. package/swf2js/__tests__/event-will-trigger.test.js +43 -0
  272. package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
  273. package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
  274. package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
  275. package/swf2js/__tests__/font-encoder.test.js +95 -0
  276. package/swf2js/__tests__/font-outline-text.test.js +659 -0
  277. package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
  278. package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
  279. package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
  280. package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
  281. package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
  282. package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
  283. package/swf2js/__tests__/input-events.test.js +714 -0
  284. package/swf2js/__tests__/integration/corpus.test.js +41 -0
  285. package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
  286. package/swf2js/__tests__/loader-info.test.js +81 -0
  287. package/swf2js/__tests__/local-connection.test.js +122 -0
  288. package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
  289. package/swf2js/__tests__/morph-topology.test.js +267 -0
  290. package/swf2js/__tests__/movie-data-codec.test.js +128 -0
  291. package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
  292. package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
  293. package/swf2js/__tests__/path-stream.test.js +81 -0
  294. package/swf2js/__tests__/place-object-filters.test.js +88 -0
  295. package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
  296. package/swf2js/__tests__/place-object3-image.test.js +85 -0
  297. package/swf2js/__tests__/player-version.test.js +46 -0
  298. package/swf2js/__tests__/root-textfield.test.js +287 -0
  299. package/swf2js/__tests__/scaling-grid.test.js +183 -0
  300. package/swf2js/__tests__/shape-decoder.test.js +361 -0
  301. package/swf2js/__tests__/shape-line-style2.test.js +138 -0
  302. package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
  303. package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
  304. package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
  305. package/swf2js/__tests__/socket-offline.test.js +67 -0
  306. package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
  307. package/swf2js/__tests__/sound-envelope.test.js +110 -0
  308. package/swf2js/__tests__/sound-extract.test.js +168 -0
  309. package/swf2js/__tests__/sound-id3.test.js +283 -0
  310. package/swf2js/__tests__/sound-load.test.js +259 -0
  311. package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
  312. package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
  313. package/swf2js/__tests__/sound-transform.test.js +104 -0
  314. package/swf2js/__tests__/speex-audio.test.js +77 -0
  315. package/swf2js/__tests__/stage-noscale.test.js +45 -0
  316. package/swf2js/__tests__/swf-encoder.test.js +134 -0
  317. package/swf2js/__tests__/swflib-assemble.test.js +20 -0
  318. package/swf2js/__tests__/textfield-html-text.test.js +368 -0
  319. package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
  320. package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
  321. package/swf2js/__tests__/textfield-scroll.test.js +79 -0
  322. package/swf2js/__tests__/textfield-selection.test.js +383 -0
  323. package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
  324. package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
  325. package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
  326. package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
  327. package/{src → swf2js}/cli.js +43 -11
  328. package/swf2js/compiler/as2-classes.js +156 -0
  329. package/swf2js/compiler/as2-parser.js +598 -0
  330. package/swf2js/compiler/avm1-codegen.js +897 -0
  331. package/swf2js/compiler/index.js +28 -0
  332. package/{src → swf2js}/decoder/button-decoder.js +3 -1
  333. package/swf2js/decoder/png.js +114 -0
  334. package/{src → swf2js}/decoder/shape-decoder.js +20 -10
  335. package/{src → swf2js}/decoder/tag-decoder.js +5 -3
  336. package/{src → swf2js}/decoder/tag-types.js +4 -0
  337. package/swf2js/decompiler/avm1-decompiler.js +1138 -0
  338. package/{src → swf2js}/emitter/asset-encoder.js +66 -113
  339. package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
  340. package/swf2js/emitter/external-resources.js +39 -0
  341. package/swf2js/emitter/movie-data-codec.js +91 -0
  342. package/swf2js/encoder/bit-writer.js +182 -0
  343. package/swf2js/encoder/shape-encoder.js +310 -0
  344. package/swf2js/encoder/swf-builder.js +639 -0
  345. package/swf2js/encoder/swf-writer.js +55 -0
  346. package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
  347. package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
  348. package/{src → swf2js}/runtime/index.js +1 -1
  349. package/{src → swf2js}/runtime/movie-runtime.js +28 -2
  350. package/{src → swf2js}/transpiler/actionscript.js +82 -19
  351. package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
  352. package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
  353. package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
  354. package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
  355. package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
  356. package/swooflib/README.md +569 -0
  357. package/swooflib/adpcm.js +147 -0
  358. package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
  359. package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
  360. package/swooflib/control-definitions.js +42 -0
  361. package/swooflib/control-widget.js +763 -0
  362. package/swooflib/controls.js +300 -0
  363. package/{src/runtime/swflib → swooflib}/display.js +16 -10
  364. package/{src/runtime/swflib → swooflib}/events.js +11 -0
  365. package/{src/runtime/swflib → swooflib}/flash.js +6 -5
  366. package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
  367. package/{src/runtime/swflib → swooflib}/input.js +12 -14
  368. package/{src/runtime/swflib → swooflib}/loader.js +52 -22
  369. package/swooflib/movie-network.js +86 -0
  370. package/swooflib/path-stream.js +169 -0
  371. package/{src/runtime/swflib → swooflib}/render.js +3 -13
  372. package/{src/runtime/swflib → swooflib}/sound.js +25 -2
  373. package/{src/runtime/swflib → swooflib}/stage.js +3 -3
  374. package/swooflib/stream-time.js +21 -0
  375. package/{src/runtime/swflib → swooflib}/system.js +88 -37
  376. package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
  377. package/{src/runtime/swflib → swooflib}/text.js +8 -0
  378. package/swooflib/xml-node.js +53 -0
  379. package/src/emitter/timeline-data-codec.js +0 -58
  380. /package/{src → swf2js}/decoder/symbol-table.js +0 -0
  381. /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
  382. /package/{src → swf2js}/emitter/font-encoder.js +0 -0
  383. /package/{src → swf2js}/model/swf-document.js +0 -0
  384. /package/{src → swf2js}/model/transpile-result.js +0 -0
  385. /package/{src → swf2js}/parser/bit-reader.js +0 -0
  386. /package/{src → swf2js}/parser/decompressor.js +0 -0
  387. /package/{src → swf2js}/parser/swf-parser.js +0 -0
  388. /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
  389. /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
  390. /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
  391. /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
  392. /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
  393. /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
  394. /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
  395. /package/{src → swf2js}/util/diagnostics.js +0 -0
  396. /package/{src → swf2js}/util/logger.js +0 -0
  397. /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
  398. /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
  399. /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
  400. /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
  401. /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
  402. /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
  403. /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
  404. /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
  405. /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
  406. /package/{src/runtime/swflib → swooflib}/host.js +0 -0
  407. /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
  408. /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
  409. /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
  410. /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
  411. /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
  412. /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
  413. /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
  414. /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
  415. /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
  416. /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
@@ -0,0 +1,905 @@
1
+ import { copyCompactRecord, writeCompactGeometry, readCompactGeometry } from './imported-paths.js';
2
+ import { readPlacementFilters } from './placement-effects.js';
3
+ import { readTrigger } from './interaction-triggers.js';
4
+ import { readTransition } from './scene-transition.js';
5
+ import { readNumber, readInteger, stageRanges, numericPoseRange, MAX_TIMELINE_FRAMES } from './numeric-fields.js';
6
+ import { readColorTransform } from './color-transform.js';
7
+ import { imageFits, readAssets, readClips, readSoundInfo } from './media-assets.js';
8
+ import { normalizeEvents } from './frame-events.js';
9
+ import { validateMasks } from './masks.js';
10
+ import { appearanceKinds, hasVectorFill, readAppearance } from './vector-style.js';
11
+ import { validateSymbolReferences } from './symbols.js';
12
+ import { displayUnits, pruneGroups } from './groups.js';
13
+ import { readAvm2Records, readScriptEvents, readScripts, referencedScripts, validateScriptReferences } from './scripts.js';
14
+ import { controlDefinitions } from '../../swooflib/control-definitions.js';
15
+ import { readControl } from './authored-controls.js';
16
+ import { readComponent, readComponentSymbol } from './components.js';
17
+ import { POSE_NUMERIC_FIELDS, normalizeSceneLayers, orderedSceneLayers } from './model.js';
18
+
19
+ export const PROJECT_FORMAT = 'swoof-studio';
20
+ export const PROJECT_VERSION = 1;
21
+
22
+ export const ELEMENT_TYPES = new Set([
23
+ 'control',
24
+ 'bitmap',
25
+ 'symbol',
26
+ 'rectangle',
27
+ 'roundedRectangle',
28
+ 'circle',
29
+ 'ellipse',
30
+ 'triangle',
31
+ 'diamond',
32
+ 'pentagon',
33
+ 'hexagon',
34
+ 'star',
35
+ 'line',
36
+ 'curve',
37
+ 'path',
38
+ 'text',
39
+ ]);
40
+
41
+ export const TWEEN_TYPES = new Set(['linear', 'easeIn', 'easeOut', 'easeInOut', 'hold']);
42
+ export const TEXT_ALIGNS = new Set(['left', 'center', 'right']);
43
+ export const ACTION_TYPES = new Set(['gotoScene', 'gotoFrame', 'play', 'stop', 'toggleVisibility', 'editInput', 'script']);
44
+ const INPUT_OPERATIONS = new Set(['insert', 'clear', 'backspace', 'evaluate']);
45
+
46
+ const HEX_COLOR_RE = /^#[0-9a-f]{6}$/i;
47
+
48
+ function isPlainObject(value) {
49
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
50
+ }
51
+
52
+ function readBoolean(value, label) {
53
+ if (value === undefined) return false;
54
+ if (typeof value !== 'boolean') throw new Error(`${label} must be a boolean`);
55
+ return value;
56
+ }
57
+
58
+ function readHexColor(value, label, fallback) {
59
+ const resolved = value === undefined ? fallback : value;
60
+ if (typeof resolved !== 'string' || !HEX_COLOR_RE.test(resolved)) {
61
+ throw new Error(`${label} must be a 6-digit hex color like #101820`);
62
+ }
63
+ return resolved.toLowerCase();
64
+ }
65
+
66
+ function readNonEmptyString(value, label, maxLength = 128) {
67
+ if (typeof value !== 'string' || !value.trim()) {
68
+ throw new Error(`${label} must be a non-empty string`);
69
+ }
70
+ return value.trim().slice(0, maxLength);
71
+ }
72
+
73
+ function normalizeHandle(value, label) {
74
+ if (value === undefined) return { x: 0, y: 0 };
75
+ if (!isPlainObject(value)) throw new Error(`${label} must be an object`);
76
+ return {
77
+ x: readNumber(value.x, `${label}.x`, -100000, 100000, 0),
78
+ y: readNumber(value.y, `${label}.y`, -100000, 100000, 0),
79
+ };
80
+ }
81
+
82
+ // Extra closed contours of a compound path (holes and islands), filled with the main contour
83
+ // using the even-odd rule. Imported from SWF shapes and glyph outlines.
84
+ function normalizeSubpaths(raw, label) {
85
+ if (!Array.isArray(raw) || raw.length > 4096) throw new Error(`${label}.subpaths must be an array of contours`);
86
+ return raw.map((points, index) => normalizePathPoints(points, true, `${label}.subpaths[${index}]`));
87
+ }
88
+
89
+ function normalizePathPoints(points, closed, label) {
90
+ if (!Array.isArray(points)) throw new Error(`${label}.points must be an array`);
91
+ const minimum = closed ? 3 : 2;
92
+ if (points.length < minimum) {
93
+ throw new Error(`${label} needs at least ${minimum} path points`);
94
+ }
95
+ return points.map((point, index) => {
96
+ if (!isPlainObject(point)) throw new Error(`${label}.points[${index}] must be an object`);
97
+ return {
98
+ x: readNumber(point.x, `${label}.points[${index}].x`, -100000, 100000),
99
+ y: readNumber(point.y, `${label}.points[${index}].y`, -100000, 100000),
100
+ handleIn: normalizeHandle(point.handleIn, `${label}.points[${index}].handleIn`),
101
+ handleOut: normalizeHandle(point.handleOut, `${label}.points[${index}].handleOut`),
102
+ };
103
+ });
104
+ }
105
+
106
+ function normalizePoseFields(source, basePose, stage, label) {
107
+ const pose = {};
108
+ for (const field of POSE_NUMERIC_FIELDS) {
109
+ pose[field] = readNumber(source[field], `${label}.${field}`, ...numericPoseRange(field, stage), basePose[field]);
110
+ }
111
+ return pose;
112
+ }
113
+
114
+ function normalizeButtonAction(raw, label) {
115
+ if (raw === undefined || raw === null) return null;
116
+ if (!isPlainObject(raw)) throw new Error(`${label}.buttonAction must be an object`);
117
+ if (typeof raw.type !== 'string' || !ACTION_TYPES.has(raw.type)) {
118
+ throw new Error(`${label}.buttonAction.type "${raw.type}" is not supported`);
119
+ }
120
+ if (raw.type === 'script') {
121
+ if (typeof raw.script !== 'string' || !raw.script.trim()) throw new Error(`${label}.buttonAction.script must be a script id`);
122
+ return { ...readTrigger(raw), type: 'script', script: raw.script };
123
+ }
124
+ let target = null;
125
+ if (raw.type === 'gotoScene' || raw.type === 'toggleVisibility' || raw.type === 'editInput') {
126
+ target = typeof raw.target === 'string' && raw.target.trim() ? raw.target.trim() : '';
127
+ } else if (raw.type === 'gotoFrame') {
128
+ target = typeof raw.target === 'number' && Number.isInteger(raw.target) ? raw.target : null;
129
+ }
130
+ const action = { ...readTrigger(raw), type: raw.type, target };
131
+ if (['gotoScene', 'gotoFrame'].includes(raw.type) && readBoolean(raw.play, `${label}.buttonAction.play`)) {
132
+ action.play = true;
133
+ }
134
+ if (raw.type === 'editInput') {
135
+ if (!INPUT_OPERATIONS.has(raw.operation)) throw new Error(`${label}.buttonAction.operation is invalid`);
136
+ action.operation = raw.operation;
137
+ if (raw.operation === 'insert') {
138
+ if (typeof raw.value !== 'string') throw new Error(`${label}.buttonAction.value must be text`);
139
+ action.value = raw.value;
140
+ }
141
+ }
142
+ return action;
143
+ }
144
+
145
+ /**
146
+ * Validate a button's target reference against its owning scene and project.
147
+ */
148
+ export function validateButtonAction(action, scene, project) {
149
+ if (!action) return { valid: true, message: '' };
150
+ if (!ACTION_TYPES.has(action.type)) {
151
+ return { valid: false, message: `Unsupported action "${action.type}"` };
152
+ }
153
+ if (action.type === 'script') {
154
+ return project?.scripts?.some(script => script.id === action.script)
155
+ ? { valid: true, message: '' } : { valid: false, message: 'Choose a script for this button' };
156
+ }
157
+ if (action.type === 'play' || action.type === 'stop') {
158
+ return { valid: true, message: '' };
159
+ }
160
+ if (action.type === 'gotoScene') {
161
+ if (!action.target) return { valid: false, message: 'Select a destination scene' };
162
+ const exists = project?.scenes?.some(item => item.id === action.target);
163
+ return exists
164
+ ? { valid: true, message: '' }
165
+ : { valid: false, message: `Scene "${action.target}" does not exist` };
166
+ }
167
+ if (action.type === 'gotoFrame') {
168
+ const max = scene?.durationFrames ?? 1;
169
+ if (!Number.isInteger(action.target) || action.target < 1 || action.target > max) {
170
+ return { valid: false, message: `Target frame must be between 1 and ${max}` };
171
+ }
172
+ return { valid: true, message: '' };
173
+ }
174
+ if (action.type === 'editInput') {
175
+ const exists = scene?.elements?.some(item => item.id === action.target && item.inputText);
176
+ return exists ? { valid: true, message: '' } : { valid: false, message: 'Select an editable text field in this scene' };
177
+ }
178
+ if (action.type === 'toggleVisibility') {
179
+ if (!action.target) return { valid: false, message: 'Select an element to toggle' };
180
+ const exists = scene?.elements?.some(item => item.id === action.target);
181
+ return exists
182
+ ? { valid: true, message: '' }
183
+ : { valid: false, message: `Element "${action.target}" is not in this scene` };
184
+ }
185
+ return { valid: true, message: '' };
186
+ }
187
+
188
+ function normalizeVectorStyle(raw, target, element, label) {
189
+ if (raw.starPoints !== undefined || raw.starRadius !== undefined) {
190
+ if (element.type !== 'star') throw new Error(`${label} requires a star`);
191
+ if (raw.starPoints !== undefined) target.starPoints = readInteger(raw.starPoints, 'Star points', 3, 64);
192
+ if (raw.starRadius !== undefined) target.starRadius = readNumber(raw.starRadius, 'Star inner radius', 1, 99);
193
+ }
194
+ if (raw.cornerRadius !== undefined) {
195
+ if (element.type !== 'roundedRectangle') throw new Error(`${label} requires a rounded rectangle`);
196
+ target.cornerRadius = readNumber(raw.cornerRadius, 'Corner radius', 0, 5000);
197
+ }
198
+ if (raw.erasures !== undefined) {
199
+ if (['text', 'symbol', 'bitmap', 'control'].includes(element.type) || !Array.isArray(raw.erasures)) {
200
+ throw new Error(`${label}.erasures requires vector contours`);
201
+ }
202
+ target.erasures = raw.erasures.map(ring => {
203
+ if (!Array.isArray(ring) || ring.length < 3) throw new Error(`${label} needs a closed eraser contour`);
204
+ return ring.map(p => ({ x: readNumber(p?.x, 'Cut x', -1e8, 1e8), y: readNumber(p?.y, 'Cut y', -1e8, 1e8) }));
205
+ });
206
+ }
207
+ for (const property of Object.keys(appearanceKinds)) {
208
+ if (raw[property] === undefined) continue;
209
+ if (['text', 'symbol', 'bitmap', 'control'].includes(element.type) || (property === 'gradient' && !hasVectorFill(element))) {
210
+ throw new Error(`${label}.${property} is unsupported on this element`);
211
+ }
212
+ target[property] = readAppearance(property, raw[property], `${label}.${property}`);
213
+ }
214
+ }
215
+
216
+ function normalizeKeyframeStyleFields(raw, kfLabel, target) {
217
+ if (raw.fill !== undefined) target.fill = readHexColor(raw.fill, `${kfLabel}.fill`);
218
+ if (raw.stroke !== undefined) target.stroke = readHexColor(raw.stroke, `${kfLabel}.stroke`);
219
+ if (raw.strokeWidth !== undefined) target.strokeWidth = readNumber(raw.strokeWidth, `${kfLabel}.strokeWidth`, ...numericPoseRange('strokeWidth'));
220
+ if (raw.text !== undefined) target.text = String(raw.text);
221
+ if (raw.fontFamily !== undefined) target.fontFamily = readNonEmptyString(raw.fontFamily, `${kfLabel}.fontFamily`);
222
+ if (raw.fontSize !== undefined) target.fontSize = readNumber(raw.fontSize, `${kfLabel}.fontSize`, ...numericPoseRange('fontSize'));
223
+ if (raw.textColor !== undefined) target.textColor = readHexColor(raw.textColor, `${kfLabel}.textColor`);
224
+ if (raw.textAlign !== undefined) {
225
+ if (!TEXT_ALIGNS.has(raw.textAlign)) throw new Error(`${kfLabel}.textAlign "${raw.textAlign}" is not supported`);
226
+ target.textAlign = raw.textAlign;
227
+ }
228
+ if (raw.bold !== undefined) {
229
+ if (typeof raw.bold !== 'boolean') throw new Error(`${kfLabel}.bold must be a boolean`);
230
+ target.bold = raw.bold;
231
+ }
232
+ if (raw.filters !== undefined) target.filters = readPlacementFilters(raw.filters, kfLabel);
233
+ if (raw.blendMode !== undefined) target.blendMode = readInteger(raw.blendMode, kfLabel, 0, 14);
234
+ if (raw.mirror !== undefined) target.mirror = readBoolean(raw.mirror, `${kfLabel}.mirror`);
235
+ if (raw.colorTransform !== undefined) {
236
+ const colorTransform = readColorTransform(raw.colorTransform, `${kfLabel}.colorTransform`);
237
+ if (colorTransform) target.colorTransform = colorTransform;
238
+ }
239
+ return target;
240
+ }
241
+
242
+ function normalizeKeyframes(rawKeyframes, basePose, stage, durationFrames, label, element) {
243
+ if (rawKeyframes === undefined) {
244
+ return [{ frame: 1, ...basePose, tween: 'linear' }];
245
+ }
246
+ if (!Array.isArray(rawKeyframes)) {
247
+ throw new Error(`${label}.keyframes must be an array`);
248
+ }
249
+ if (rawKeyframes.length === 0) {
250
+ return [{ frame: 1, ...basePose, tween: 'linear' }];
251
+ }
252
+ const seenFrames = new Set();
253
+ const keyframes = rawKeyframes.map((raw, index) => {
254
+ const kfLabel = `${label}.keyframes[${index}]`;
255
+ if (!isPlainObject(raw)) throw new Error(`${kfLabel} must be an object`);
256
+ const frame = readInteger(raw.frame, `${kfLabel}.frame`, 1, durationFrames);
257
+ if (seenFrames.has(frame)) {
258
+ throw new Error(`${label} has duplicate keyframe at frame ${frame}`);
259
+ }
260
+ seenFrames.add(frame);
261
+ const tween = raw.tween === undefined ? 'linear' : raw.tween;
262
+ if (!TWEEN_TYPES.has(tween)) {
263
+ throw new Error(`${kfLabel}.tween "${tween}" is not supported`);
264
+ }
265
+ const normalized = {
266
+ frame,
267
+ ...normalizePoseFields(raw, basePose, stage, kfLabel),
268
+ tween,
269
+ };
270
+ if (raw.pointStream !== undefined || raw.contourStreams !== undefined) {
271
+ if (element.type !== 'path') throw new Error(`${kfLabel} geometry requires a path element`);
272
+ readCompactGeometry(raw, normalized, element.closed, kfLabel);
273
+ element.compactGeometry = true;
274
+ }
275
+ if (raw.points !== undefined) {
276
+ if (element.type !== 'path') throw new Error(`${kfLabel}.points requires a path element`);
277
+ normalized.points = normalizePathPoints(raw.points, element.closed, kfLabel);
278
+ }
279
+ if (raw.subpaths !== undefined) {
280
+ if (element.type !== 'path' || !element.closed) throw new Error(`${kfLabel}.subpaths requires a closed path`);
281
+ normalized.subpaths = normalizeSubpaths(raw.subpaths, kfLabel);
282
+ }
283
+ if (readBoolean(raw.blank, `${kfLabel}.blank`)) normalized.blank = true;
284
+ normalizeVectorStyle(raw, normalized, element, kfLabel);
285
+ return normalizeKeyframeStyleFields(raw, kfLabel, normalized);
286
+ });
287
+ return keyframes.sort((a, b) => a.frame - b.frame);
288
+ }
289
+
290
+ function normalizeLayers(rawLayers, sceneLabel, usedLayerIds, allocateId) {
291
+ if (rawLayers === undefined) {
292
+ const id = allocateId('layer');
293
+ usedLayerIds.add(id);
294
+ return [{ id, name: 'Layer 1', visible: true, locked: false, order: 0 }];
295
+ }
296
+ if (!Array.isArray(rawLayers) || rawLayers.length === 0) {
297
+ throw new Error(`${sceneLabel}.layers must be a non-empty array`);
298
+ }
299
+ return rawLayers.map((rawLayer, index) => {
300
+ const label = `${sceneLabel}.layers[${index}]`;
301
+ if (!isPlainObject(rawLayer)) throw new Error(`${label} must be an object`);
302
+ let id;
303
+ if (rawLayer.id === undefined) {
304
+ id = allocateId('layer');
305
+ } else {
306
+ id = readNonEmptyString(rawLayer.id, `${label}.id`);
307
+ if (usedLayerIds.has(id)) throw new Error(`Duplicate layer id "${id}"`);
308
+ }
309
+ usedLayerIds.add(id);
310
+ const name = rawLayer.name === undefined
311
+ ? `Layer ${index + 1}`
312
+ : readNonEmptyString(rawLayer.name, `${label}.name`, 48);
313
+ const visible = rawLayer.visible === undefined ? true : rawLayer.visible;
314
+ if (typeof visible !== 'boolean') throw new Error(`${label}.visible must be a boolean`);
315
+ const locked = rawLayer.locked === undefined ? false : rawLayer.locked;
316
+ if (typeof locked !== 'boolean') throw new Error(`${label}.locked must be a boolean`);
317
+ const order = readInteger(rawLayer.order, `${label}.order`, 0, 10000, index);
318
+ return { id, name, visible, locked, order };
319
+ });
320
+ }
321
+
322
+ // Text field settings kept from SWF import (variable bindings, HTML, editing flags).
323
+ function readTextField(raw, label) {
324
+ if (!isPlainObject(raw)) throw new Error(`${label}.field must be an object`);
325
+ const field = {};
326
+ if (raw.variable !== undefined) field.variable = readNonEmptyString(raw.variable, `${label}.field.variable`, 256);
327
+ if (raw.htmlText !== undefined) field.htmlText = String(raw.htmlText);
328
+ if (raw.fontId !== undefined) {
329
+ field.fontId = readInteger(raw.fontId, `${label}.field.fontId`, 1, 65535);
330
+ if (raw.fontLibrary) field.fontLibrary = readNonEmptyString(raw.fontLibrary, `${label}.field.fontLibrary`);
331
+ field.fontFamily = readNonEmptyString(raw.fontFamily, `${label}.field.fontFamily`, 80);
332
+ field.useOutlines = readBoolean(raw.useOutlines, `${label}.field.useOutlines`);
333
+ }
334
+ for (const flag of ['html', 'multiline', 'wordWrap', 'editable', 'selectable', 'password', 'border']) {
335
+ if (raw[flag] !== undefined) field[flag] = readBoolean(raw[flag], `${label}.field.${flag}`);
336
+ }
337
+ if (raw.maxLength !== undefined) field.maxLength = readInteger(raw.maxLength, `${label}.field.maxLength`, 0, 65535);
338
+ return field;
339
+ }
340
+
341
+ function readFrameLabels(raw, durationFrames, label) {
342
+ if (!Array.isArray(raw)) throw new Error(`${label}.labels must be an array`);
343
+ return raw.map((item, index) => {
344
+ if (!isPlainObject(item)) throw new Error(`${label}.labels[${index}] must be an object`);
345
+ return { frame: readInteger(item.frame, `${label}.labels[${index}].frame`, 1, durationFrames),
346
+ name: readNonEmptyString(item.name, `${label}.labels[${index}].name`, 256) };
347
+ });
348
+ }
349
+
350
+ function normalizeElement(raw, index, stage, durationFrames, layerIds, defaultLayerId, usedIds, allocateId) {
351
+ const label = `element[${index}]`;
352
+ if (!isPlainObject(raw)) throw new Error(`${label} must be an object`);
353
+ if (typeof raw.type !== 'string' || !ELEMENT_TYPES.has(raw.type)) {
354
+ throw new Error(`${label}.type "${raw.type}" is not supported`);
355
+ }
356
+
357
+ let id;
358
+ if (raw.id === undefined) {
359
+ id = allocateId('element');
360
+ } else {
361
+ id = readNonEmptyString(raw.id, `${label}.id`);
362
+ if (usedIds.has(id)) throw new Error(`Duplicate element id "${id}"`);
363
+ }
364
+ usedIds.add(id);
365
+
366
+ const isText = raw.type === 'text';
367
+ const name = raw.name === undefined ? `${raw.type} ${index + 1}` : readNonEmptyString(raw.name, `${label}.name`, 48);
368
+ const control = raw.type === 'control' ? readControl(raw, label) : null;
369
+ const defaultPose = {
370
+ x: stage.width / 2,
371
+ y: stage.height / 2,
372
+ width: control ? controlDefinitions[control.control].width : isText ? 280 : 120,
373
+ height: control ? controlDefinitions[control.control].height : isText ? 72 : 84,
374
+ scaleX: 1,
375
+ scaleY: 1,
376
+ rotation: 0,
377
+ skew: 0,
378
+ opacity: 1,
379
+ };
380
+ const pose = normalizePoseFields(raw, defaultPose, stage, label);
381
+
382
+ const textAlign = raw.textAlign === undefined ? 'center' : raw.textAlign;
383
+ if (!TEXT_ALIGNS.has(textAlign)) {
384
+ throw new Error(`${label}.textAlign "${textAlign}" is not supported`);
385
+ }
386
+ const bold = raw.bold === undefined ? false : raw.bold;
387
+ if (typeof bold !== 'boolean') {
388
+ throw new Error(`${label}.bold must be a boolean`);
389
+ }
390
+
391
+ let layerId = defaultLayerId;
392
+ if (raw.layerId !== undefined) {
393
+ layerId = readNonEmptyString(raw.layerId, `${label}.layerId`);
394
+ if (!layerIds.has(layerId)) {
395
+ throw new Error(`${label}.layerId "${layerId}" does not exist in scene`);
396
+ }
397
+ }
398
+
399
+ const element = {
400
+ id,
401
+ name,
402
+ type: raw.type,
403
+ layerId,
404
+ ...pose,
405
+ fill: readHexColor(raw.fill, `${label}.fill`, isText ? '#f4f6fb' : '#56d4ad'),
406
+ stroke: readHexColor(raw.stroke, `${label}.stroke`, isText ? '#f4f6fb' : '#e8f3ef'),
407
+ strokeWidth: readNumber(raw.strokeWidth, `${label}.strokeWidth`, ...numericPoseRange('strokeWidth'), isText ? 0 : 2),
408
+ text: raw.text === undefined ? (isText ? 'Type your text' : '') : String(raw.text),
409
+ fontFamily: raw.fontFamily === undefined ? 'Arial' : readNonEmptyString(raw.fontFamily, `${label}.fontFamily`),
410
+ fontSize: readNumber(raw.fontSize, `${label}.fontSize`, ...numericPoseRange('fontSize'), 32),
411
+ textColor: readHexColor(raw.textColor, `${label}.textColor`, '#f4f6fb'),
412
+ textAlign,
413
+ bold,
414
+ buttonAction: normalizeButtonAction(raw.buttonAction, label),
415
+ keyframes: [],
416
+ };
417
+ if (control) Object.assign(element, control);
418
+ if (raw.depth !== undefined) element.depth = readInteger(raw.depth, `${label}.depth`, -16384, 1048575);
419
+ if (raw.clipDepth !== undefined) element.clipDepth = readInteger(raw.clipDepth, `${label}.clipDepth`, -16384, 1048575);
420
+ if (raw.field !== undefined) {
421
+ if (raw.type !== 'text') throw new Error(`${label}.field requires a text element`);
422
+ element.field = readTextField(raw.field, label);
423
+ }
424
+ if (raw.component !== undefined) {
425
+ if (raw.type !== 'symbol') throw new Error(`${label}.component requires a movie clip`);
426
+ element.component = readComponent(raw.component, label);
427
+ }
428
+ if (raw.scriptEvents !== undefined) {
429
+ if (raw.type !== 'symbol') throw new Error(`${label}.scriptEvents requires a movie clip`);
430
+ const scriptEvents = readScriptEvents(raw.scriptEvents, 'clip', label);
431
+ if (scriptEvents) element.scriptEvents = scriptEvents;
432
+ }
433
+
434
+ readStrokeStyle(raw, element, label);
435
+
436
+ for (const key of ['bitmapFill', 'bitmapStroke']) {
437
+ if (raw[key] === undefined) continue;
438
+ if (raw.type !== 'path' || (key === 'bitmapFill' && !raw.closed) || !isPlainObject(raw[key])) {
439
+ throw new Error(`${label} has an invalid ${key} path`);
440
+ }
441
+ const { matrix, repeat, smoothed } = raw[key];
442
+ if (!matrix || !['a', 'b', 'c', 'd', 'tx', 'ty'].every(key => Number.isFinite(matrix[key]))) {
443
+ throw new Error(`${label}.${key} requires a finite placement matrix`);
444
+ }
445
+ element[key] = { matrix: { ...matrix }, repeat: readBoolean(repeat, label), smoothed: readBoolean(smoothed, label) };
446
+ if (key === 'bitmapFill') element.assetId = readNonEmptyString(raw.assetId, `${label}.assetId`);
447
+ else element[key].assetId = readNonEmptyString(raw[key].assetId, `${label}.bitmapStroke.assetId`);
448
+ }
449
+ if (raw.type === 'bitmap') {
450
+ element.assetId = readNonEmptyString(raw.assetId, `${label}.assetId`);
451
+ if (raw.smoothed !== undefined) element.smoothed = readBoolean(raw.smoothed, label);
452
+ element.fit = raw.fit ?? 'contain';
453
+ for (const field of ['cropX', 'cropY']) {
454
+ if (raw[field] !== undefined) element[field] = readNumber(raw[field], `${label}.${field}`, 0, 100);
455
+ }
456
+ if (!imageFits.includes(element.fit)) throw new Error('Choose a supported image fit');
457
+ if (raw.crop !== undefined) {
458
+ if (!isPlainObject(raw.crop)) throw new Error(`${label}.crop must be a rectangle`);
459
+ element.crop = {
460
+ x: readNumber(raw.crop.x, `${label}.crop.x`, 0, 100000),
461
+ y: readNumber(raw.crop.y, `${label}.crop.y`, 0, 100000),
462
+ width: readNumber(raw.crop.width, `${label}.crop.width`, 0.001, 100000),
463
+ height: readNumber(raw.crop.height, `${label}.crop.height`, 0.001, 100000),
464
+ };
465
+ }
466
+ }
467
+ if (raw.type === 'symbol') {
468
+ element.symbolId = readNonEmptyString(raw.symbolId, `${label}.symbolId`);
469
+ if (raw.symbolMode !== undefined) {
470
+ if (!['loop', 'once', 'single'].includes(raw.symbolMode)) throw new Error(`${label}.symbolMode is invalid`);
471
+ element.symbolMode = raw.symbolMode;
472
+ }
473
+ if (raw.firstFrame !== undefined) element.firstFrame = readInteger(raw.firstFrame, `${label}.firstFrame`, 1, MAX_TIMELINE_FRAMES);
474
+ }
475
+ if (raw.maskId !== undefined) element.maskId = readNonEmptyString(raw.maskId, `${label}.maskId`);
476
+ if (raw.groupId !== undefined) element.groupId = readNonEmptyString(raw.groupId, `${label}.groupId`);
477
+ const inputText = readBoolean(raw.inputText, `${label}.inputText`);
478
+ if (element.field?.editable ?? inputText) {
479
+ if (!isText || element.buttonAction) throw new Error(`${label}.inputText requires a text field without a button action`);
480
+ element.inputText = true;
481
+ }
482
+ if (raw.type === 'path') {
483
+ const closed = raw.closed === undefined ? false : raw.closed;
484
+ if (typeof closed !== 'boolean') throw new Error(`${label}.closed must be a boolean`);
485
+ element.closed = closed;
486
+ if (raw.pointStream !== undefined || raw.contourStreams !== undefined) element.compactGeometry = true;
487
+ readCompactGeometry(raw, element, closed, label);
488
+ if (raw.pointStream === undefined) element.points = normalizePathPoints(raw.points, closed, label);
489
+ if (raw.subpaths !== undefined) {
490
+ if (!closed) throw new Error(`${label}.subpaths requires a closed path`);
491
+ element.subpaths = normalizeSubpaths(raw.subpaths, label);
492
+ }
493
+ }
494
+
495
+ normalizeVectorStyle(raw, element, element, label);
496
+ element.keyframes = normalizeKeyframes(raw.keyframes, pose, stage, durationFrames, label, element);
497
+ return element;
498
+ }
499
+
500
+ export function serializeTimeline(scene, { expandPaths = false } = {}) {
501
+ const layers = orderedSceneLayers(scene);
502
+ const fallbackLayerId = layers[0]?.id;
503
+ return {
504
+ id: scene.id,
505
+ name: scene.name,
506
+ durationFrames: scene.durationFrames,
507
+ startFrame: scene.startFrame ?? 1,
508
+ loop: scene.loop ?? false,
509
+ transition: scene.transition,
510
+ audioClips: scene.audioClips?.length ? scene.audioClips : undefined,
511
+ events: scene.events?.length ? scene.events : undefined,
512
+ scriptEvents: scene.scriptEvents?.length ? structuredClone(scene.scriptEvents) : undefined,
513
+ initScript: scene.initScript,
514
+ initAt: scene.initAt,
515
+ avm2: scene.avm2?.length ? scene.avm2 : undefined,
516
+ labels: scene.labels?.length ? scene.labels.map(item => ({ ...item })) : undefined,
517
+ nativeMorph: scene.nativeMorph,
518
+ compoundShape: scene.compoundShape || undefined,
519
+ origin: scene.origin ? { ...scene.origin } : undefined,
520
+ button: scene.button || undefined,
521
+ scalingGrid: scene.scalingGrid,
522
+ trackAsMenu: scene.trackAsMenu,
523
+ buttonSounds: scene.buttonSounds,
524
+ linkage: scene.linkage,
525
+ component: scene.component ? { ...scene.component } : undefined,
526
+ layers: layers.length > 0
527
+ ? layers.map(layer => ({
528
+ id: layer.id,
529
+ name: layer.name,
530
+ visible: layer.visible !== false,
531
+ locked: Boolean(layer.locked),
532
+ order: layer.order,
533
+ }))
534
+ : undefined,
535
+ elements: scene.elements.map(element => {
536
+ const copy = {
537
+ id: element.id,
538
+ name: element.name,
539
+ type: element.type,
540
+ layerId: element.layerId ?? fallbackLayerId,
541
+ x: element.x,
542
+ y: element.y,
543
+ width: element.width,
544
+ height: element.height,
545
+ scaleX: element.scaleX,
546
+ scaleY: element.scaleY,
547
+ rotation: element.rotation,
548
+ skew: element.skew,
549
+ opacity: element.opacity,
550
+ fill: element.fill,
551
+ stroke: element.stroke,
552
+ strokeWidth: element.strokeWidth,
553
+ text: element.text,
554
+ fontFamily: element.fontFamily,
555
+ fontSize: element.fontSize,
556
+ textColor: element.textColor,
557
+ textAlign: element.textAlign,
558
+ bold: element.bold,
559
+ keyframes: element.keyframes.map(keyframe => {
560
+ if (!element.compactGeometry || expandPaths) return { ...keyframe };
561
+ return copyCompactRecord(keyframe);
562
+ }),
563
+ };
564
+ for (const property of [...Object.keys(appearanceKinds), 'starPoints', 'starRadius', 'cornerRadius', 'erasures']) {
565
+ if (element[property] !== undefined) copy[property] = structuredClone(element[property]);
566
+ }
567
+ if (element.bitmapStroke) copy.bitmapStroke = structuredClone(element.bitmapStroke);
568
+ for (const property of STROKE_STYLE_FIELDS) {
569
+ if (element[property] !== undefined) copy[property] = Array.isArray(element[property]) ? [...element[property]] : element[property];
570
+ }
571
+ if (element.bitmapFill) Object.assign(copy, { assetId: element.assetId, bitmapFill: structuredClone(element.bitmapFill) });
572
+ if (element.type === 'bitmap') {
573
+ if (element.smoothed !== undefined) copy.smoothed = element.smoothed;
574
+ Object.assign(copy, { assetId: element.assetId, fit: element.fit, cropX: element.cropX, cropY: element.cropY });
575
+ if (element.crop) copy.crop = { ...element.crop };
576
+ }
577
+ if (element.type === 'symbol') {
578
+ copy.symbolId = element.symbolId;
579
+ if (element.symbolMode) copy.symbolMode = element.symbolMode;
580
+ if (element.firstFrame !== undefined) copy.firstFrame = element.firstFrame;
581
+ }
582
+ if (element.maskId) copy.maskId = element.maskId;
583
+ if (element.groupId) copy.groupId = element.groupId;
584
+ if (element.inputText) copy.inputText = true;
585
+ if (element.buttonAction) {
586
+ copy.buttonAction = { ...element.buttonAction };
587
+ }
588
+ if (element.scriptEvents?.length) copy.scriptEvents = structuredClone(element.scriptEvents);
589
+ if (element.type === 'control') {
590
+ copy.control = element.control;
591
+ copy.parameters = structuredClone(element.parameters);
592
+ if (element.variable) copy.variable = element.variable;
593
+ }
594
+ if (element.component) copy.component = structuredClone(element.component);
595
+ if (element.depth !== undefined) copy.depth = element.depth;
596
+ if (element.clipDepth !== undefined) copy.clipDepth = element.clipDepth;
597
+ if (element.field) copy.field = { ...element.field };
598
+ if (element.type === 'path') {
599
+ copy.closed = Boolean(element.closed);
600
+ if (element.compactGeometry && !expandPaths) {
601
+ return writeCompactGeometry(element, copy);
602
+ }
603
+ copy.points = element.points.map(point => ({
604
+ x: point.x,
605
+ y: point.y,
606
+ handleIn: { x: point.handleIn.x, y: point.handleIn.y },
607
+ handleOut: { x: point.handleOut.x, y: point.handleOut.y },
608
+ }));
609
+ if (element.subpaths?.length) copy.subpaths = structuredClone(element.subpaths);
610
+ }
611
+ return copy;
612
+ }),
613
+ };
614
+ }
615
+
616
+ /**
617
+ * Collect the current editor project in the portable Studio document format.
618
+ */
619
+ export function projectDocument(project) {
620
+ const payload = {
621
+ format: PROJECT_FORMAT,
622
+ version: PROJECT_VERSION,
623
+ stage: {
624
+ width: project.stage.width,
625
+ height: project.stage.height,
626
+ frameRate: project.stage.frameRate,
627
+ background: project.stage.background,
628
+ },
629
+ scenes: project.scenes.map(scene => serializeTimeline(scene)),
630
+ };
631
+ if (project.assets?.length) payload.assets = project.assets;
632
+ if (project.symbols?.length) {
633
+ payload.symbols = project.symbols.map(symbol => ({
634
+ ...serializeTimeline(symbol), width: symbol.width, height: symbol.height,
635
+ }));
636
+ }
637
+ // Scripts nothing refers to any more (their object or frame was deleted) are not saved.
638
+ const used = referencedScripts(project);
639
+ const scripts = (project.scripts ?? []).filter(script => used.has(script.id));
640
+ if (scripts.length) payload.scripts = scripts;
641
+ return payload;
642
+ }
643
+
644
+ export function serializeProject(project, indent = 2) {
645
+ return JSON.stringify(projectDocument(project), null, indent);
646
+ }
647
+
648
+ // Stroke and fill details SVG and Flash have beyond width and colour (svg-import.md 13.2.3):
649
+ // line caps and joins, the miter limit, dashes, the fill rule, and italic text.
650
+ const STROKE_STYLE_FIELDS = ['lineCap', 'lineJoin', 'miterLimit', 'strokeDash', 'strokeDashOffset', 'fillRule', 'italic'];
651
+ function readStrokeStyle(raw, element, label) {
652
+ const choice = (key, values) => {
653
+ if (raw[key] === undefined) return;
654
+ if (!values.includes(raw[key])) throw new Error(`${label}.${key} must be one of ${values.join(', ')}`);
655
+ element[key] = raw[key];
656
+ };
657
+ choice('lineCap', ['butt', 'round', 'square']);
658
+ choice('lineJoin', ['round', 'miter', 'bevel']);
659
+ if (raw.miterLimit !== undefined) element.miterLimit = readNumber(raw.miterLimit, `${label}.miterLimit`, 1, 255);
660
+ if (raw.strokeDash !== undefined) {
661
+ if (!Array.isArray(raw.strokeDash) || raw.strokeDash.length < 1 || raw.strokeDash.length > 64) throw new Error(`${label}.strokeDash must list 1–64 lengths`);
662
+ element.strokeDash = raw.strokeDash.map((value, index) => readNumber(value, `${label}.strokeDash[${index}]`, 0, 10000));
663
+ if (!element.strokeDash.some(value => value > 0)) delete element.strokeDash;
664
+ }
665
+ if (raw.strokeDashOffset !== undefined) element.strokeDashOffset = readNumber(raw.strokeDashOffset, `${label}.strokeDashOffset`, -100000, 100000);
666
+ if (raw.fillRule !== undefined) {
667
+ if (element.type !== 'path') throw new Error(`${label}.fillRule requires a path`);
668
+ choice('fillRule', ['nonzero', 'evenodd']);
669
+ }
670
+ if (raw.italic !== undefined) {
671
+ if (element.type !== 'text') throw new Error(`${label}.italic requires text`);
672
+ element.italic = readBoolean(raw.italic, label);
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Parse and validate an animation JSON string into a normalized project object.
678
+ */
679
+ export function parseProjectJson(jsonText) {
680
+ if (typeof jsonText !== 'string' || !jsonText.trim()) {
681
+ throw new Error('Paste animation JSON before importing');
682
+ }
683
+ let raw;
684
+ try {
685
+ raw = JSON.parse(jsonText);
686
+ } catch (error) {
687
+ throw new Error(`Invalid JSON: ${error.message}`);
688
+ }
689
+ if (!isPlainObject(raw)) {
690
+ throw new Error('Animation JSON must be an object');
691
+ }
692
+ if (raw.format !== undefined && raw.format !== PROJECT_FORMAT) {
693
+ throw new Error(`Unsupported project format "${raw.format}"`);
694
+ }
695
+ if (raw.version !== undefined && raw.version !== PROJECT_VERSION) {
696
+ throw new Error(`Unsupported project version "${raw.version}"`);
697
+ }
698
+ if (!isPlainObject(raw.stage)) {
699
+ throw new Error('Missing stage configuration');
700
+ }
701
+ if (!Array.isArray(raw.scenes) || raw.scenes.length === 0) {
702
+ throw new Error('Project must include at least one scene');
703
+ }
704
+
705
+ const stage = {
706
+ width: readInteger(raw.stage.width, 'stage.width', ...stageRanges.width),
707
+ height: readInteger(raw.stage.height, 'stage.height', ...stageRanges.height),
708
+ frameRate: readNumber(raw.stage.frameRate, 'stage.frameRate', ...stageRanges.frameRate),
709
+ background: readHexColor(raw.stage.background, 'stage.background', '#101820'),
710
+ };
711
+
712
+ let syntheticCounter = 0;
713
+ const usedSceneIds = new Set();
714
+ const usedLayerIds = new Set();
715
+ const usedElementIds = new Set();
716
+ const explicitIds = new Set();
717
+ const rawSymbols = raw.symbols === undefined ? [] : raw.symbols;
718
+ if (!Array.isArray(rawSymbols)) throw new Error('symbols must be an array');
719
+ for (const scene of [...raw.scenes, ...rawSymbols]) {
720
+ for (const group of [[scene], scene?.layers, scene?.elements]) {
721
+ if (!Array.isArray(group)) continue;
722
+ for (const item of group) {
723
+ if (typeof item?.id === 'string') explicitIds.add(item.id.trim());
724
+ }
725
+ }
726
+ }
727
+ const allocateId = prefix => {
728
+ let id;
729
+ do {
730
+ id = `${prefix}-imported-${++syntheticCounter}`;
731
+ } while (explicitIds.has(id));
732
+ return id;
733
+ };
734
+
735
+ const assets = readAssets(raw.assets === undefined ? [] : raw.assets);
736
+ const scripts = readScripts(raw.scripts);
737
+
738
+ function normalizeTimeline(rawScene, index, isSymbol) {
739
+ const label = `${isSymbol ? 'symbols' : 'scenes'}[${index}]`;
740
+ if (!isPlainObject(rawScene)) throw new Error(`${label} must be an object`);
741
+ let id;
742
+ if (rawScene.id === undefined) {
743
+ id = allocateId(isSymbol ? 'symbol' : 'scene');
744
+ } else {
745
+ id = readNonEmptyString(rawScene.id, `${label}.id`);
746
+ if (usedSceneIds.has(id)) throw new Error(`Duplicate ${isSymbol ? 'symbol or scene' : 'scene'} id "${id}"`);
747
+ }
748
+ usedSceneIds.add(id);
749
+
750
+ const name = rawScene.name === undefined
751
+ ? `${isSymbol ? 'Symbol' : 'Scene'} ${index + 1}`
752
+ : readNonEmptyString(rawScene.name, `${label}.name`, 48);
753
+ const durationFrames = readInteger(rawScene.durationFrames, `${label}.durationFrames`, 1, MAX_TIMELINE_FRAMES, 120);
754
+ const startFrame = readInteger(rawScene.startFrame, `${label}.startFrame`, 1, durationFrames, 1);
755
+ const loop = readBoolean(rawScene.loop, `${label}.loop`);
756
+ const layers = normalizeLayers(rawScene.layers, label, usedLayerIds, allocateId);
757
+ const ordered = [...layers].sort((a, b) => a.order - b.order);
758
+ const layerIds = new Set(ordered.map(layer => layer.id));
759
+ const defaultLayerId = ordered[0].id;
760
+ if (!Array.isArray(rawScene.elements)) {
761
+ throw new Error(`${label}.elements must be an array`);
762
+ }
763
+ const dimensions = isSymbol ? {
764
+ width: readInteger(rawScene.width, `${label}.width`, ...stageRanges.width, 320),
765
+ height: readInteger(rawScene.height, `${label}.height`, ...stageRanges.height, 200),
766
+ } : stage;
767
+ const elements = rawScene.elements.map((rawElement, elementIndex) =>
768
+ normalizeElement(rawElement, elementIndex, dimensions, durationFrames, layerIds, defaultLayerId, usedElementIds, allocateId),
769
+ );
770
+ const scene = { id, name, durationFrames, startFrame, loop, layers, elements };
771
+ for (const item of elements) {
772
+ if (item.bitmapStroke && !assets.some(asset => asset.kind === 'image' && asset.id === item.bitmapStroke.assetId)) {
773
+ throw new Error(`Missing stroke image for ${item.name}`);
774
+ }
775
+ if ((item.type === 'bitmap' || item.bitmapFill) && !assets.some(asset => asset.kind === 'image' && asset.id === item.assetId)) {
776
+ throw new Error(`Missing image for ${item.name}`);
777
+ }
778
+ }
779
+ if (rawScene.transition !== undefined) {
780
+ if (isSymbol) throw new Error('Only movie scenes can have an entry transition');
781
+ scene.transition = readTransition(rawScene.transition);
782
+ }
783
+ if (rawScene.audioClips !== undefined) {
784
+ const clips = readClips(rawScene.audioClips, scene, assets);
785
+ if (clips.length) scene.audioClips = clips;
786
+ }
787
+ if (rawScene.events !== undefined) scene.events = rawScene.events;
788
+ if (rawScene.avm2 !== undefined) scene.avm2 = readAvm2Records(rawScene.avm2, durationFrames, label);
789
+ if (rawScene.labels !== undefined) {
790
+ const labels = readFrameLabels(rawScene.labels, durationFrames, label);
791
+ if (labels.length) scene.labels = labels;
792
+ }
793
+ if (isSymbol) Object.assign(scene, dimensions);
794
+ if (isSymbol && rawScene.compoundShape !== undefined) scene.compoundShape = readBoolean(rawScene.compoundShape, `${label}.compoundShape`);
795
+ if (isSymbol && rawScene.nativeMorph !== undefined) {
796
+ const m = rawScene.nativeMorph;
797
+ if (!m || typeof m.source !== 'string' || !m.source || ![1, 2].includes(m.version) ||
798
+ !Number.isInteger(m.ratio) || m.ratio < 0 || m.ratio > 65535 || !/^[a-f0-9]{64}$/.test(m.fingerprint) ||
799
+ !Array.isArray(m.bitmaps) || m.bitmaps.some(item => !Number.isInteger(item?.id) || typeof item.asset !== 'string'))
800
+ throw new Error('Invalid Flash morph artwork');
801
+ scene.nativeMorph = { source: m.source, version: m.version, ratio: m.ratio, fingerprint: m.fingerprint,
802
+ bitmaps: m.bitmaps.map(({ id, asset }) => ({ id, asset })) };
803
+ }
804
+ if (isSymbol && rawScene.origin !== undefined) {
805
+ if (!isPlainObject(rawScene.origin)) throw new Error(`${label}.origin must be a point`);
806
+ scene.origin = { x: readNumber(rawScene.origin.x, `${label}.origin.x`, -1e6, 1e6, 0), y: readNumber(rawScene.origin.y, `${label}.origin.y`, -1e6, 1e6, 0) };
807
+ }
808
+ if (isSymbol && rawScene.button !== undefined) scene.button = readBoolean(rawScene.button, `${label}.button`);
809
+ if (rawScene.scalingGrid !== undefined) {
810
+ if (!isSymbol || !isPlainObject(rawScene.scalingGrid)) throw new Error(`${label}.scalingGrid requires a symbol rectangle`);
811
+ const grid = rawScene.scalingGrid;
812
+ const limit = (2 ** 30 - 1) / 20; // SWF RECT holds up to 31 signed bits in twips.
813
+ scene.scalingGrid = {
814
+ x: readNumber(grid.x, 'scalingGrid.x', -limit - .05, limit),
815
+ y: readNumber(grid.y, 'scalingGrid.y', -limit - .05, limit),
816
+ w: readNumber(grid.w, 'scalingGrid.w', .05, limit - grid.x),
817
+ h: readNumber(grid.h, 'scalingGrid.h', .05, limit - grid.y),
818
+ };
819
+ }
820
+ if (rawScene.trackAsMenu !== undefined) {
821
+ if (!scene.button) throw new Error(`${label}.trackAsMenu requires a button symbol`);
822
+ scene.trackAsMenu = readBoolean(rawScene.trackAsMenu, label);
823
+ }
824
+ if (rawScene.buttonSounds !== undefined) {
825
+ if (!scene.button || !isPlainObject(rawScene.buttonSounds)) throw new Error('Button transition sounds require a button symbol');
826
+ scene.buttonSounds = {};
827
+ for (const [transition, cue] of Object.entries(rawScene.buttonSounds)) {
828
+ if (!['overUpToIdle', 'idleToOverUp', 'overUpToOverDown', 'overDownToOverUp'].includes(transition) ||
829
+ !assets.some(asset => asset.kind === 'audio' && asset.id === cue?.assetId)) throw new Error('Invalid button transition sound');
830
+ scene.buttonSounds[transition] = { assetId: cue.assetId, soundInfo: readSoundInfo(cue.soundInfo) };
831
+ }
832
+ }
833
+ // Linkage name scripts use to create the symbol (attachMovie).
834
+ if (isSymbol && rawScene.linkage !== undefined) scene.linkage = readNonEmptyString(rawScene.linkage, `${label}.linkage`, 256);
835
+ if (isSymbol && rawScene.component !== undefined) scene.component = readComponentSymbol(rawScene.component, label);
836
+ if (rawScene.scriptEvents !== undefined || rawScene.initScript !== undefined) {
837
+ if (!isSymbol) throw new Error(`${label}: only symbols can carry button or initialization scripts`);
838
+ const scriptEvents = readScriptEvents(rawScene.scriptEvents, 'button', label);
839
+ if (scriptEvents) scene.scriptEvents = scriptEvents;
840
+ if (rawScene.initScript !== undefined) scene.initScript = readNonEmptyString(rawScene.initScript, `${label}.initScript`);
841
+ }
842
+ if (rawScene.initAt !== undefined) {
843
+ const anchor = rawScene.initAt;
844
+ if (!scene.initScript || !isSymbol || !isPlainObject(anchor)) throw new Error(`${label}.initAt requires a symbol initialization script`);
845
+ const owner = scenes.find(item => item.id === anchor.scene);
846
+ if (!owner) throw new Error(`${label}.initAt requires an existing scene`);
847
+ scene.initAt = { scene: owner.id, frame: readInteger(anchor.frame, `${label}.initAt.frame`, 1, owner.durationFrames) };
848
+ }
849
+ // A display group belongs to one layer and occupies one stacking slot.
850
+ const groupLayers = new Map();
851
+ for (const element of elements) {
852
+ if (!element.groupId) continue;
853
+ const layer = groupLayers.get(element.groupId);
854
+ if (layer && layer !== element.layerId) throw new Error(`${label}: group "${element.groupId}" crosses layers`);
855
+ groupLayers.set(element.groupId, element.layerId);
856
+ }
857
+ if (groupLayers.size) {
858
+ for (const layerId of new Set(groupLayers.values())) {
859
+ const order = displayUnits(scene.elements.filter(item => item.layerId === layerId)).flat();
860
+ let slot = 0;
861
+ scene.elements = scene.elements.map(item => item.layerId === layerId ? order[slot++] : item);
862
+ }
863
+ pruneGroups(scene);
864
+ }
865
+ normalizeSceneLayers(scene);
866
+ validateMasks(scene);
867
+ return scene;
868
+ }
869
+ const scenes = raw.scenes.map((item, i) => normalizeTimeline(item, i, false));
870
+ const project = { stage, scenes };
871
+ if (assets.length) project.assets = assets;
872
+ if (scripts.length) project.scripts = scripts;
873
+ if (rawSymbols.length) project.symbols = rawSymbols.map((item, i) => normalizeTimeline(item, i, true));
874
+ for (const timeline of [...scenes, ...(project.symbols ?? [])]) {
875
+ if (timeline.events === undefined) continue;
876
+ const events = normalizeEvents(timeline.events, timeline, project);
877
+ if (events.length) timeline.events = events;
878
+ else delete timeline.events;
879
+ }
880
+ validateSymbolReferences(project);
881
+ validateScriptReferences(project);
882
+ return project;
883
+ }
884
+
885
+ /**
886
+ * Compute the highest numeric suffix across scene, layer, and element IDs so new IDs do not collide.
887
+ */
888
+ export function nextIdSequenceForProject(project) {
889
+ let maxId = 0;
890
+ const check = id => {
891
+ const match = typeof id === 'string' ? /-(\d+)$/.exec(id) : null;
892
+ if (match) maxId = Math.max(maxId, Number(match[1]));
893
+ };
894
+ for (const scene of [...project.scenes, ...(project.symbols ?? [])]) {
895
+ check(scene.id);
896
+ for (const layer of scene.layers || []) {
897
+ check(layer.id);
898
+ }
899
+ for (const element of scene.elements) {
900
+ check(element.id);
901
+ check(element.groupId);
902
+ }
903
+ }
904
+ return maxId;
905
+ }