@open-artifact/motion-export 0.0.0-stage → 0.12.0-rc.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 (81) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +56 -4
  5. package/src/build.d.ts +13 -0
  6. package/src/build.js +47 -0
  7. package/src/engine.d.ts +46 -0
  8. package/src/engine.js +225 -0
  9. package/src/errors.d.ts +79 -0
  10. package/src/errors.js +104 -0
  11. package/src/estimate.d.ts +27 -0
  12. package/src/estimate.js +103 -0
  13. package/src/filename.d.ts +14 -0
  14. package/src/filename.js +44 -0
  15. package/src/frame-source.d.ts +54 -0
  16. package/src/frame-source.js +1 -0
  17. package/src/frames.d.ts +36 -0
  18. package/src/frames.js +112 -0
  19. package/src/gif/encode.d.ts +23 -0
  20. package/src/gif/encode.js +60 -0
  21. package/src/gif/estimator.d.ts +50 -0
  22. package/src/gif/estimator.js +82 -0
  23. package/src/gif/surface.d.ts +8 -0
  24. package/src/gif/surface.js +20 -0
  25. package/src/index.d.ts +28 -0
  26. package/src/index.js +15 -0
  27. package/src/mov/encode.d.ts +25 -0
  28. package/src/mov/encode.js +48 -0
  29. package/src/mov/estimate.d.ts +22 -0
  30. package/src/mov/estimate.js +34 -0
  31. package/src/mov/plan.d.ts +32 -0
  32. package/src/mov/plan.js +21 -0
  33. package/src/mov/surface.d.ts +4 -0
  34. package/src/mov/surface.js +20 -0
  35. package/src/plan.d.ts +54 -0
  36. package/src/plan.js +76 -0
  37. package/src/problems.d.ts +10 -0
  38. package/src/problems.js +32 -0
  39. package/src/raster/document.d.ts +7 -0
  40. package/src/raster/document.js +15 -0
  41. package/src/raster/frame-entry.d.ts +1 -0
  42. package/src/raster/frame-entry.js +36 -0
  43. package/src/raster/host.d.ts +28 -0
  44. package/src/raster/host.js +191 -0
  45. package/src/raster/messages.d.ts +34 -0
  46. package/src/raster/messages.js +25 -0
  47. package/src/source/layout.d.ts +49 -0
  48. package/src/source/layout.js +83 -0
  49. package/src/source/names.d.ts +14 -0
  50. package/src/source/names.js +65 -0
  51. package/src/source/readme.d.ts +17 -0
  52. package/src/source/readme.js +43 -0
  53. package/src/source/zip.d.ts +27 -0
  54. package/src/source/zip.js +61 -0
  55. package/src/stage-frame.d.ts +8 -0
  56. package/src/stage-frame.js +39 -0
  57. package/src/standalone/audio-entry.d.ts +1 -0
  58. package/src/standalone/audio-entry.js +51 -0
  59. package/src/standalone/html.d.ts +35 -0
  60. package/src/standalone/html.js +60 -0
  61. package/src/types.d.ts +65 -0
  62. package/src/types.js +1 -0
  63. package/src/video/attempts.d.ts +34 -0
  64. package/src/video/attempts.js +49 -0
  65. package/src/video/avc.d.ts +15 -0
  66. package/src/video/avc.js +158 -0
  67. package/src/video/encode-attempt.d.ts +39 -0
  68. package/src/video/encode-attempt.js +154 -0
  69. package/src/video/encode.d.ts +6 -0
  70. package/src/video/encode.js +66 -0
  71. package/src/video/format.d.ts +20 -0
  72. package/src/video/format.js +34 -0
  73. package/src/video/output.d.ts +12 -0
  74. package/src/video/output.js +38 -0
  75. package/src/virtual.d.ts +11 -0
  76. package/src/visibility.d.ts +45 -0
  77. package/src/visibility.js +131 -0
  78. package/src/vite.d.ts +8 -0
  79. package/src/vite.js +43 -0
  80. package/src/words.d.ts +37 -0
  81. package/src/words.js +37 -0
@@ -0,0 +1,36 @@
1
+ import { drawSnapshot, makeHoldFirstDraw, whyNoDecode } from '@open-artifact/motion-stage/raster';
2
+ import { isRasterRequest } from "./messages.js";
3
+ // Runs in the raster frame: an opaque origin, so a snapshot's pictures cannot taint what the page reads back.
4
+ const holdFirstDraw = makeHoldFirstDraw();
5
+ let retained = document.createElement('canvas');
6
+ const reply = (message, transfer = []) => parent.postMessage(message, '*', transfer);
7
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
8
+ async function bitmapOf(surface) {
9
+ return surface instanceof ImageBitmap ? surface : createImageBitmap(surface);
10
+ }
11
+ addEventListener('message', (event) => {
12
+ const request = event.data;
13
+ if (event.source !== parent || !isRasterRequest(request))
14
+ return;
15
+ const fail = (error) => reply({ rid: request.rid, error: messageOf(error) });
16
+ try {
17
+ const picture = new Image();
18
+ picture.onload = () => {
19
+ holdFirstDraw(request.svg, request.waitMs, () => {
20
+ drawSnapshot(picture, request.pw, request.ph, retained)
21
+ .then(bitmapOf)
22
+ .then((bitmap) => reply({ rid: request.rid, bitmap }, [bitmap]))
23
+ .catch((error) => {
24
+ retained = document.createElement('canvas');
25
+ fail(error);
26
+ });
27
+ });
28
+ };
29
+ picture.onerror = () => fail('snapshot decode failed (foreignObject)' + whyNoDecode(request.svg));
30
+ picture.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(request.svg);
31
+ }
32
+ catch (error) {
33
+ fail(error);
34
+ }
35
+ });
36
+ reply({ rasterReady: true });
@@ -0,0 +1,28 @@
1
+ /** Turns a snapshot's SVG into an ImageBitmap, in a hidden frame of its own. */
2
+ export interface RasterHost {
3
+ raster(svg: string, pw: number, ph: number): Promise<ImageBitmap>;
4
+ dispose(): void;
5
+ }
6
+ /** When a raster frame is replaced by a fresh one: browsers keep every picture a frame decoded until it goes. */
7
+ export interface RasterCache {
8
+ /** How many requests ahead a replacement frame is made. */
9
+ nextAhead: number;
10
+ /** Requests at most in one frame, however it fares. */
11
+ keepMax: number;
12
+ /** Characters of SVG at most in one frame, however it fares. */
13
+ keepMaxChars: number;
14
+ }
15
+ export declare const RASTER_USES = 120;
16
+ export declare const RASTER_CHARS = 167772160;
17
+ export declare const RASTER_REPLY_TIMEOUT_MS = 15000;
18
+ export declare const MAX_RASTER_SVG_CHARS = 67108864;
19
+ export declare const MAX_RASTER_SIDE = 8192;
20
+ export declare const DEFAULT_RASTER_CACHE: RasterCache;
21
+ export interface RasterHostOptions {
22
+ /** The raster frame's script (`virtual:motion-raster-frame`, or `buildRasterFrame()`). */
23
+ script: string;
24
+ document?: Document;
25
+ clippedTextWaitMs?: () => number;
26
+ cache?: RasterCache;
27
+ }
28
+ export declare function createRasterHost(options: RasterHostOptions): RasterHost;
@@ -0,0 +1,191 @@
1
+ import { EXPORT_SETTINGS } from '@open-artifact/motion-core';
2
+ import { STAGE_SANDBOX } from '@open-artifact/motion-stage';
3
+ import { RasterDecodeError, RasterGoneError, RasterStallError, SnapshotLimitError } from "../errors.js";
4
+ import { words } from "../words.js";
5
+ import { FOREIGN_OBJECT_TEST_SVG, rasterDocument } from "./document.js";
6
+ import { readRasterReply } from "./messages.js";
7
+ export const RASTER_USES = 120;
8
+ export const RASTER_CHARS = 167_772_160;
9
+ export const RASTER_REPLY_TIMEOUT_MS = 15_000;
10
+ export const MAX_RASTER_SVG_CHARS = 67_108_864;
11
+ export const MAX_RASTER_SIDE = 8192;
12
+ export const DEFAULT_RASTER_CACHE = {
13
+ nextAhead: EXPORT_SETTINGS.rasterNextAhead,
14
+ keepMax: EXPORT_SETTINGS.rasterKeepMax,
15
+ keepMaxChars: EXPORT_SETTINGS.rasterKeepMaxMb * 1_048_576,
16
+ };
17
+ const HIDDEN_FRAME_STYLE = {
18
+ position: 'fixed',
19
+ left: '-10000px',
20
+ top: '0',
21
+ width: '4px',
22
+ height: '4px',
23
+ border: '0',
24
+ opacity: '0',
25
+ pointerEvents: 'none',
26
+ };
27
+ export function createRasterHost(options) {
28
+ const page = options.document ?? document;
29
+ const view = page.defaultView ?? window;
30
+ const cache = options.cache ?? DEFAULT_RASTER_CACHE;
31
+ const waitMs = options.clippedTextWaitMs ?? (() => EXPORT_SETTINGS.clippedTextWaitMs);
32
+ const html = rasterDocument(options.script);
33
+ const sessions = new Set();
34
+ let active = null;
35
+ let queued = null;
36
+ // How many replacements in a row may time out before making one waits longer.
37
+ let generation = 1;
38
+ let sequence = 0;
39
+ let disposed = false;
40
+ function close(session) {
41
+ for (const [, pending] of session.pending) {
42
+ clearTimeout(pending.timer);
43
+ pending.reject(new RasterGoneError(words.rasterGone));
44
+ }
45
+ session.pending.clear();
46
+ session.frame.remove();
47
+ session.off();
48
+ sessions.delete(session);
49
+ }
50
+ function take(session, rid) {
51
+ const pending = session.pending.get(rid);
52
+ if (!pending)
53
+ return undefined;
54
+ session.pending.delete(rid);
55
+ clearTimeout(pending.timer);
56
+ if (session !== active && session.pending.size === 0)
57
+ close(session);
58
+ return pending;
59
+ }
60
+ const worn = (session, extraChars) => session.stalled || session.uses >= RASTER_USES || session.chars + extraChars > RASTER_CHARS;
61
+ function rotate() {
62
+ const old = active;
63
+ const next = queued ?? open();
64
+ active = next;
65
+ queued = null;
66
+ if (old !== null && old.pending.size === 0)
67
+ close(old);
68
+ return next;
69
+ }
70
+ function open() {
71
+ const frame = page.createElement('iframe');
72
+ frame.setAttribute('sandbox', STAGE_SANDBOX);
73
+ frame.setAttribute('aria-hidden', 'true');
74
+ frame.setAttribute('inert', '');
75
+ frame.tabIndex = -1;
76
+ Object.assign(frame.style, HIDDEN_FRAME_STYLE);
77
+ const session = {
78
+ frame,
79
+ ready: Promise.resolve(),
80
+ drew: false,
81
+ waited: 0,
82
+ born: sequence,
83
+ stalled: false,
84
+ uses: 0,
85
+ chars: 0,
86
+ pending: new Map(),
87
+ off: () => undefined,
88
+ };
89
+ session.ready = new Promise((resolve) => {
90
+ const listen = (event) => {
91
+ if (event.source === null || event.source !== frame.contentWindow)
92
+ return;
93
+ const reply = readRasterReply(event.data);
94
+ switch (reply.kind) {
95
+ case 'ready': {
96
+ const warmUp = { rid: 0, svg: FOREIGN_OBJECT_TEST_SVG, pw: 2, ph: 2 };
97
+ frame.contentWindow?.postMessage(warmUp, '*');
98
+ resolve();
99
+ return;
100
+ }
101
+ case 'bitmap': {
102
+ session.drew = true;
103
+ if (session === queued && active !== null && worn(active, 0))
104
+ rotate();
105
+ const pending = take(session, reply.rid);
106
+ if (pending)
107
+ pending.resolve(reply.bitmap);
108
+ else
109
+ reply.bitmap.close();
110
+ return;
111
+ }
112
+ case 'error':
113
+ take(session, reply.rid)?.reject(new RasterDecodeError(reply.message));
114
+ return;
115
+ case 'other':
116
+ return;
117
+ default: {
118
+ const never = reply;
119
+ return never;
120
+ }
121
+ }
122
+ };
123
+ session.off = () => view.removeEventListener('message', listen);
124
+ view.addEventListener('message', listen);
125
+ });
126
+ frame.srcdoc = html;
127
+ (page.body ?? page.documentElement).appendChild(frame);
128
+ sessions.add(session);
129
+ return session;
130
+ }
131
+ function pick(chars) {
132
+ if (active !== null && (active.uses >= RASTER_USES - cache.nextAhead || active.chars + chars * cache.nextAhead > RASTER_CHARS))
133
+ queued ??= open();
134
+ const replace = active === null ||
135
+ (worn(active, chars) && queued?.drew === true) ||
136
+ active.uses >= cache.keepMax ||
137
+ active.chars + chars > cache.keepMaxChars;
138
+ return replace || active === null ? rotate() : active;
139
+ }
140
+ return {
141
+ raster(svg, pw, ph) {
142
+ if (disposed)
143
+ return Promise.reject(new RasterGoneError(words.rasterGone));
144
+ if (svg.length > MAX_RASTER_SVG_CHARS)
145
+ return Promise.reject(new SnapshotLimitError(words.snapshotTooLarge));
146
+ if (!(pw >= 1 && pw <= MAX_RASTER_SIDE && ph >= 1 && ph <= MAX_RASTER_SIDE))
147
+ return Promise.reject(new SnapshotLimitError(words.snapshotOutOfRange));
148
+ const session = pick(svg.length);
149
+ session.uses += 1;
150
+ session.chars += svg.length;
151
+ const rid = ++sequence;
152
+ return new Promise((resolve, reject) => {
153
+ const late = () => {
154
+ if (session === active) {
155
+ session.stalled = true;
156
+ if (queued?.drew === true)
157
+ rotate();
158
+ else if (queued !== null && queued.born < rid) {
159
+ // A replacement that never drew either: drop it, and wait twice as long for the next one.
160
+ queued.born = sequence;
161
+ queued.waited += 1;
162
+ if (queued.waited >= generation) {
163
+ close(queued);
164
+ queued = null;
165
+ generation = Math.min(16, generation * 2);
166
+ }
167
+ }
168
+ if (session === active)
169
+ queued ??= open();
170
+ }
171
+ if (take(session, rid))
172
+ reject(new RasterStallError(words.rasterTimedOut));
173
+ };
174
+ session.pending.set(rid, { resolve, reject, timer: setTimeout(late, RASTER_REPLY_TIMEOUT_MS) });
175
+ void session.ready.then(() => {
176
+ if (!session.pending.has(rid))
177
+ return;
178
+ const request = { rid, svg, pw: Math.round(pw), ph: Math.round(ph), waitMs: waitMs() };
179
+ session.frame.contentWindow?.postMessage(request, '*');
180
+ });
181
+ });
182
+ },
183
+ dispose() {
184
+ disposed = true;
185
+ active = null;
186
+ queued = null;
187
+ for (const session of [...sessions])
188
+ close(session);
189
+ },
190
+ };
191
+ }
@@ -0,0 +1,34 @@
1
+ /** Page → raster frame: draw this snapshot at `pw` × `ph`. */
2
+ export interface RasterRequest {
3
+ rid: number;
4
+ svg: string;
5
+ pw: number;
6
+ ph: number;
7
+ waitMs?: number;
8
+ }
9
+ /** Raster frame → page. */
10
+ export type RasterReply = {
11
+ rasterReady: true;
12
+ } | {
13
+ rid: number;
14
+ bitmap: ImageBitmap;
15
+ } | {
16
+ rid: number;
17
+ error: string;
18
+ };
19
+ export declare function isRasterRequest(value: unknown): value is RasterRequest;
20
+ /** A reply as the page reads it: whether the frame is ready, or the request it answers and how. */
21
+ export type ReadReply = {
22
+ kind: 'ready';
23
+ } | {
24
+ kind: 'bitmap';
25
+ rid: number;
26
+ bitmap: ImageBitmap;
27
+ } | {
28
+ kind: 'error';
29
+ rid: number;
30
+ message: string;
31
+ } | {
32
+ kind: 'other';
33
+ };
34
+ export declare function readRasterReply(value: unknown): ReadReply;
@@ -0,0 +1,25 @@
1
+ const isFields = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
2
+ const isNumber = (value) => typeof value === 'number' && Number.isFinite(value);
3
+ export function isRasterRequest(value) {
4
+ return (isFields(value) &&
5
+ isNumber(value['rid']) &&
6
+ typeof value['svg'] === 'string' &&
7
+ isNumber(value['pw']) &&
8
+ isNumber(value['ph']) &&
9
+ (value['waitMs'] === undefined || isNumber(value['waitMs'])));
10
+ }
11
+ const MAX_ERROR_CHARS = 300;
12
+ export function readRasterReply(value) {
13
+ if (!isFields(value))
14
+ return { kind: 'other' };
15
+ if (value['rasterReady'] === true)
16
+ return { kind: 'ready' };
17
+ const rid = Number(value['rid']);
18
+ if (!Number.isFinite(rid))
19
+ return { kind: 'other' };
20
+ const bitmap = value['bitmap'];
21
+ if (typeof ImageBitmap !== 'undefined' && bitmap instanceof ImageBitmap)
22
+ return { kind: 'bitmap', rid, bitmap };
23
+ const error = value['error'];
24
+ return { kind: 'error', rid, message: typeof error === 'string' ? error.slice(0, MAX_ERROR_CHARS) : 'raster failed' };
25
+ }
@@ -0,0 +1,49 @@
1
+ import type { AssetMime, FontLicence, ModuleKind } from '@open-artifact/motion-core';
2
+ import type { ZipEntry } from '@open-artifact/wasm-export';
3
+ import type { FilmFacts } from '../frame-source.ts';
4
+ export interface SourceModule {
5
+ name: string;
6
+ kind: ModuleKind;
7
+ text: string;
8
+ }
9
+ export interface SourceAsset {
10
+ name: string;
11
+ mime: AssetMime;
12
+ bytes: Uint8Array;
13
+ }
14
+ /** A typeface the video uses, with its files and the licence text that must go with them; null when there is none. */
15
+ export interface SourceFont {
16
+ family: string;
17
+ licence: FontLicence;
18
+ licenceText: string | null;
19
+ files: ReadonlyArray<{
20
+ name: string;
21
+ bytes: Uint8Array;
22
+ }>;
23
+ }
24
+ export interface SourceFolderInput {
25
+ title: string;
26
+ date: Date;
27
+ script: string;
28
+ modules: readonly SourceModule[];
29
+ assets: readonly SourceAsset[];
30
+ fonts: readonly SourceFont[];
31
+ /** The standalone page, or null when there is none. */
32
+ standalone: string | null;
33
+ facts?: Omit<FilmFacts, 'title'>;
34
+ /** The score as a MIDI file, put in as score.mid; null or absent to leave it out. */
35
+ midi?: Uint8Array | null;
36
+ }
37
+ /** Where the score's MIDI file goes in the folder. */
38
+ export declare const SCORE_MIDI_FILE = "score.mid";
39
+ export interface SourceFolder {
40
+ entries: ZipEntry[];
41
+ /** Files that could not be files of their own. */
42
+ filesLeftOut: string[];
43
+ fontsLeftOut: string[];
44
+ }
45
+ /**
46
+ * The folder as ZIP entries: README.txt, index.html, cut.js, film.json, score.mid, modules/, assets/ and fonts/ with
47
+ * licences.
48
+ */
49
+ export declare function sourceFolder(input: SourceFolderInput): SourceFolder;
@@ -0,0 +1,83 @@
1
+ import { FETCHED_FONTS_MODULE, RECOLORED_MODULE, REFACED_MODULE, RETYPED_MODULE } from '@open-artifact/motion-core';
2
+ import { exportFileStem } from "../filename.js";
3
+ import { FolderNames, fontFolder, licenceFileName, sourceRootFolder } from "./names.js";
4
+ import { sourceReadme } from "./readme.js";
5
+ /** Records the page keeps for itself and has already applied to the code. */
6
+ const PAGE_RECORDS = [RETYPED_MODULE, RECOLORED_MODULE, REFACED_MODULE, FETCHED_FONTS_MODULE];
7
+ /** Where the score's MIDI file goes in the folder. */
8
+ export const SCORE_MIDI_FILE = 'score.mid';
9
+ const pad = (value) => String(value).padStart(2, '0');
10
+ const dayOf = (date) => [date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate())].join('-');
11
+ const fontFileName = (name) => name.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '') || 'font.woff2';
12
+ /**
13
+ * The folder as ZIP entries: README.txt, index.html, cut.js, film.json, score.mid, modules/, assets/ and fonts/ with
14
+ * licences.
15
+ */
16
+ export function sourceFolder(input) {
17
+ const root = sourceRootFolder(exportFileStem(input.title));
18
+ const filesLeftOut = [];
19
+ const moduleNames = new FolderNames();
20
+ const modules = input.modules.filter((module) => {
21
+ if (PAGE_RECORDS.includes(module.name))
22
+ return false;
23
+ if (moduleNames.module(module.name, module.kind))
24
+ return true;
25
+ filesLeftOut.push('modules/' + module.name);
26
+ return false;
27
+ });
28
+ const assetNames = new FolderNames();
29
+ const assets = input.assets.filter((asset) => {
30
+ if (assetNames.asset(asset.name, asset.mime))
31
+ return true;
32
+ filesLeftOut.push('assets/' + asset.name);
33
+ return false;
34
+ });
35
+ const fonts = input.fonts.filter((font) => font.licenceText !== null && font.files.length > 0);
36
+ const fontsLeftOut = input.fonts.filter((font) => !fonts.includes(font)).map((font) => font.family);
37
+ const fontEntries = [];
38
+ const fontFacts = fonts.map((font) => {
39
+ const folder = fontFolder(font.family);
40
+ const names = new Set();
41
+ const files = font.files.map((file, index) => {
42
+ let name = fontFileName(file.name);
43
+ if (names.has(name.toLowerCase()))
44
+ name = `${index + 1}-${name}`;
45
+ names.add(name.toLowerCase());
46
+ fontEntries.push({ name: root + folder + name, data: file.bytes });
47
+ return folder + name;
48
+ });
49
+ fontEntries.push({ name: root + folder + licenceFileName(font.licence), data: font.licenceText ?? '' });
50
+ return { family: font.family, licence: font.licence, files };
51
+ });
52
+ const film = {
53
+ version: 1,
54
+ title: input.title,
55
+ created: input.date.toISOString(),
56
+ ...(input.facts !== undefined ? { width: input.facts.width, height: input.facts.height, fps: input.facts.fps, duration: input.facts.duration } : {}),
57
+ fonts: fontFacts,
58
+ ...(fontsLeftOut.length > 0 ? { fontsLeftOut } : {}),
59
+ ...(filesLeftOut.length > 0 ? { filesLeftOut } : {}),
60
+ };
61
+ const midi = input.midi ?? null;
62
+ const readme = sourceReadme({
63
+ day: dayOf(input.date),
64
+ standalone: input.standalone !== null,
65
+ parts: ['cut.js', 'film.json', ...(modules.length > 0 ? ['modules/'] : []), ...(assets.length > 0 ? ['assets/'] : [])],
66
+ assets: assets.length > 0,
67
+ fonts: fonts.length > 0,
68
+ midi: midi !== null,
69
+ fontsLeftOut,
70
+ filesLeftOut,
71
+ });
72
+ const entries = [
73
+ { name: root + 'README.txt', data: readme },
74
+ ...(input.standalone !== null ? [{ name: root + 'index.html', data: input.standalone }] : []),
75
+ { name: root + 'cut.js', data: input.script },
76
+ { name: root + 'film.json', data: JSON.stringify(film, null, 2) + '\n' },
77
+ ...(midi !== null ? [{ name: root + SCORE_MIDI_FILE, data: midi }] : []),
78
+ ...modules.map((module) => ({ name: root + 'modules/' + module.name, data: module.text })),
79
+ ...assets.map((asset) => ({ name: root + 'assets/' + asset.name, data: asset.bytes })),
80
+ ...fontEntries,
81
+ ];
82
+ return { entries, filesLeftOut, fontsLeftOut };
83
+ }
@@ -0,0 +1,14 @@
1
+ import type { AssetMime, FontLicence, ModuleKind } from '@open-artifact/motion-core';
2
+ /** Keeps track of the names taken in one folder of the ZIP, compared without case. */
3
+ export declare class FolderNames {
4
+ #private;
5
+ /** Takes the name when it can be a file of its own here; false when it cannot. */
6
+ accept(name: string, extension: RegExp): boolean;
7
+ module(name: string, kind: ModuleKind): boolean;
8
+ asset(name: string, mime: AssetMime): boolean;
9
+ }
10
+ /** The folder everything sits in: the title's file stem, kept clear of names a computer refuses. */
11
+ export declare const sourceRootFolder: (stem: string) => string;
12
+ /** A font family as a folder name. */
13
+ export declare const fontFolder: (family: string) => string;
14
+ export declare function licenceFileName(licence: FontLicence): string;
@@ -0,0 +1,65 @@
1
+ import { FILM_NAME_PATTERN } from '@open-artifact/motion-core';
2
+ const MODULE_EXTENSIONS = {
3
+ js: /\.js$/i,
4
+ css: /\.css$/i,
5
+ html: /\.html?$/i,
6
+ json: /\.json$/i,
7
+ text: /\.(?:txt|md|svg)$/i,
8
+ };
9
+ const ASSET_EXTENSIONS = {
10
+ 'image/png': /\.png$/i,
11
+ 'image/jpeg': /\.jpe?g$/i,
12
+ 'image/gif': /\.gif$/i,
13
+ 'image/webp': /\.webp$/i,
14
+ 'image/svg+xml': /\.svg$/i,
15
+ 'font/woff2': /\.woff2$/i,
16
+ 'font/woff': /\.woff$/i,
17
+ 'font/ttf': /\.ttf$/i,
18
+ 'font/otf': /\.otf$/i,
19
+ 'video/mp4': /\.mp4$/i,
20
+ 'video/webm': /\.webm$/i,
21
+ 'application/pdf': /\.pdf$/i,
22
+ 'audio/mpeg': /\.mp3$/i,
23
+ 'audio/wav': /\.wav$/i,
24
+ };
25
+ /** Names some computers cannot save a file under. */
26
+ const WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i;
27
+ /** Names that could be taken for the folder's own index.html or README.txt. */
28
+ const FOLDER_OWN = /^(?:index|readme)\./i;
29
+ /** Keeps track of the names taken in one folder of the ZIP, compared without case. */
30
+ export class FolderNames {
31
+ #seen = new Set();
32
+ /** Takes the name when it can be a file of its own here; false when it cannot. */
33
+ accept(name, extension) {
34
+ const key = name.toLowerCase();
35
+ const ok = FILM_NAME_PATTERN.test(name) && !WINDOWS_RESERVED.test(name) && !FOLDER_OWN.test(name) && extension.test(name) && !this.#seen.has(key);
36
+ if (ok)
37
+ this.#seen.add(key);
38
+ return ok;
39
+ }
40
+ module(name, kind) {
41
+ return this.accept(name, MODULE_EXTENSIONS[kind]);
42
+ }
43
+ asset(name, mime) {
44
+ return this.accept(name, ASSET_EXTENSIONS[mime]);
45
+ }
46
+ }
47
+ /** The folder everything sits in: the title's file stem, kept clear of names a computer refuses. */
48
+ export const sourceRootFolder = (stem) => (WINDOWS_RESERVED.test(stem) ? '_' + stem : stem) + '/';
49
+ /** A font family as a folder name. */
50
+ export const fontFolder = (family) => 'fonts/' + (family.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'font') + '/';
51
+ export function licenceFileName(licence) {
52
+ switch (licence) {
53
+ case 'OFL-1.1':
54
+ case 'OFL-1.0':
55
+ return 'OFL.txt';
56
+ case 'Apache-2.0':
57
+ return 'LICENSE.txt';
58
+ case 'UFL-1.0':
59
+ return 'UFL.txt';
60
+ default: {
61
+ const never = licence;
62
+ return never;
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,17 @@
1
+ export interface ReadmeFacts {
2
+ /** The day it was made, YYYY-MM-DD. */
3
+ day: string;
4
+ standalone: boolean;
5
+ /** The parts beside index.html: cut.js, film.json, modules/, assets/. */
6
+ parts: readonly string[];
7
+ assets: boolean;
8
+ fonts: boolean;
9
+ /** score.mid is in the folder. */
10
+ midi?: boolean;
11
+ /** Font families left out because no licence text could go with them. */
12
+ fontsLeftOut: readonly string[];
13
+ /** Files that could not be files of their own. */
14
+ filesLeftOut: readonly string[];
15
+ }
16
+ /** README.txt: what each part of the folder is, and what to know before running it. */
17
+ export declare function sourceReadme(facts: ReadmeFacts): string;
@@ -0,0 +1,43 @@
1
+ const indent = (lines) => lines.map((line) => ' ' + line).join('\n');
2
+ /** README.txt: what each part of the folder is, and what to know before running it. */
3
+ export function sourceReadme(facts) {
4
+ const sections = [`This folder is one video, as code. Made on ${facts.day}. An AI model wrote this code.`];
5
+ if (facts.standalone)
6
+ sections.push('index.html\n' +
7
+ indent([
8
+ 'Open it in a browser to watch the video. It needs no network.',
9
+ 'It is a built copy with everything it plays inside it' + (facts.fontsLeftOut.length > 0 ? ', except the fonts left out (see below)' : '') + ', so changing the other files does not change it.',
10
+ 'If someone else gave you this folder, trust it only as far as you trust them: they could have changed any file in it.',
11
+ 'If a window opens that asks you to pick a file, cancel it and close the tab: a video has no use for your files.',
12
+ ]));
13
+ sections.push(facts.parts.join(', ') +
14
+ '\n' +
15
+ indent([
16
+ 'The same code' + (facts.assets ? ', pictures and clips' : '') + ' as separate files, laid out the way the agent works on a video.',
17
+ 'To look at the code, open it in a text editor. Don’t double-click these files: a browser runs an .html or .svg file opened that way without the limits that index.html puts on the code, and Windows by default runs a .js file as a program.',
18
+ ]));
19
+ if (facts.midi === true)
20
+ sections.push('score.mid\n' +
21
+ indent([
22
+ 'The video’s music and sound effects as a MIDI file, to open in a music app: a track for each instrument, with the drums and effects together on channel 10.',
23
+ 'Its tempo is the video’s, and a marker shows where the video starts.',
24
+ ]));
25
+ if (facts.fonts)
26
+ sections.push('fonts/\n' +
27
+ indent([
28
+ 'The typefaces the video uses, one folder for each family: its font files and its licence file. film.json says which files make up which family.',
29
+ 'Each family stays under its own licence. If you pass the font files on, with this folder or without it, keep each licence file with them.',
30
+ ]));
31
+ if (facts.fontsLeftOut.length > 0)
32
+ sections.push('Fonts left out\n' +
33
+ indent([
34
+ facts.fontsLeftOut.join(', ') + ': no licence text could go with them, so their files are neither in this folder nor inside index.html.',
35
+ 'Their text shows in another font.',
36
+ ]));
37
+ if (facts.filesLeftOut.length > 0)
38
+ sections.push('Not here as files of their own, because some computers cannot save a file under that name, the name does not fit what the file holds, or it could be mistaken for this folder’s index.html or README.txt: ' +
39
+ facts.filesLeftOut.join(', ') +
40
+ '.' +
41
+ (facts.standalone ? '\nindex.html plays without them as files.' : ''));
42
+ return sections.join('\n\n') + '\n';
43
+ }
@@ -0,0 +1,27 @@
1
+ import type { Film, FilmAsset } from '@open-artifact/motion-core';
2
+ import type { FilmFacts } from '../frame-source.ts';
3
+ import type { ExportedFile } from '../types.ts';
4
+ import type { SourceFolder, SourceFont } from './layout.ts';
5
+ export declare const SOURCE_MAX_BYTES: number;
6
+ export interface SourceZipInput {
7
+ title: string;
8
+ /** The film as read from the store. */
9
+ film: Film;
10
+ /** An asset's bytes (an upload fetched, a `data:` URI decoded); null when it cannot be read. */
11
+ readAsset(asset: FilmAsset): Promise<Uint8Array | null>;
12
+ /** The standalone page to put in as index.html; null to leave it out. */
13
+ standalone: string | null;
14
+ fonts?: readonly SourceFont[];
15
+ facts?: Omit<FilmFacts, 'title'>;
16
+ /** The score as a MIDI file, put in as score.mid; null or absent to leave it out. */
17
+ midi?: Uint8Array | null;
18
+ date?: Date;
19
+ maxBytes?: number;
20
+ signal?: AbortSignal;
21
+ onProgress?: (done: number, total: number) => void;
22
+ }
23
+ export interface SourceZip extends ExportedFile {
24
+ folder: Omit<SourceFolder, 'entries'>;
25
+ }
26
+ /** The video's code as a ZIP of one folder, stored without compression. */
27
+ export declare function buildSourceZip(input: SourceZipInput): Promise<SourceZip>;