flucto 1.26.0 → 1.27.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 (43) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +1 -0
  3. package/dist-electron/cli/args.js +64 -1
  4. package/dist-electron/cli/args.js.map +1 -1
  5. package/dist-electron/cli/index.js +210 -39
  6. package/dist-electron/cli/index.js.map +1 -1
  7. package/dist-electron/cli/output.js +12 -0
  8. package/dist-electron/cli/output.js.map +1 -1
  9. package/dist-electron/main/analysis/agentLabelValidation.js +15 -0
  10. package/dist-electron/main/analysis/agentLabelValidation.js.map +1 -0
  11. package/dist-electron/main/analysis/avCommands.js +19 -0
  12. package/dist-electron/main/analysis/avCommands.js.map +1 -1
  13. package/dist-electron/main/analysis/cameraMotion.js +212 -0
  14. package/dist-electron/main/analysis/cameraMotion.js.map +1 -0
  15. package/dist-electron/main/analysis/contactSheet.js +106 -0
  16. package/dist-electron/main/analysis/contactSheet.js.map +1 -0
  17. package/dist-electron/main/analysis/csvWriter.js +12 -8
  18. package/dist-electron/main/analysis/csvWriter.js.map +1 -1
  19. package/dist-electron/main/analysis/dialogueAlign.js +27 -0
  20. package/dist-electron/main/analysis/dialogueAlign.js.map +1 -0
  21. package/dist-electron/main/analysis/ffmpegSignals.js +15 -4
  22. package/dist-electron/main/analysis/ffmpegSignals.js.map +1 -1
  23. package/dist-electron/main/analysis/framePlan.js +84 -0
  24. package/dist-electron/main/analysis/framePlan.js.map +1 -0
  25. package/dist-electron/main/services/agentLabeling.js +846 -0
  26. package/dist-electron/main/services/agentLabeling.js.map +1 -0
  27. package/dist-electron/main/services/agentLabelingInstructions.js +43 -0
  28. package/dist-electron/main/services/agentLabelingInstructions.js.map +1 -0
  29. package/dist-electron/main/services/analysisReport.js +165 -19
  30. package/dist-electron/main/services/analysisReport.js.map +1 -1
  31. package/dist-electron/main/services/cinematicAnalysis.js +2 -1
  32. package/dist-electron/main/services/cinematicAnalysis.js.map +1 -1
  33. package/dist-electron/main/services/timelineExports.js +254 -0
  34. package/dist-electron/main/services/timelineExports.js.map +1 -0
  35. package/dist-electron/main/transcript/captionExtractor.js +6 -2
  36. package/dist-electron/main/transcript/captionExtractor.js.map +1 -1
  37. package/dist-electron/shared/agentLabelTypes.js +8 -0
  38. package/dist-electron/shared/agentLabelTypes.js.map +1 -0
  39. package/dist-electron/shared/analysisTypes.js.map +1 -1
  40. package/package.json +1 -1
  41. package/schemas/agent-labels.v1.schema.json +375 -0
  42. package/skills/flucto-media-research/SKILL.md +3 -2
  43. package/skills/flucto-media-research/references/shot-analysis.md +96 -0
@@ -0,0 +1,846 @@
1
+ /**
2
+ * `analyze prepare`: measures shots with the existing ffmpeg signal passes,
3
+ * renders one timecoded contact sheet per shot and writes the labeling request
4
+ * that the calling agent's own vision model works from.
5
+ *
6
+ * Everything under `labels/` belongs to the agent: prepare creates the folder
7
+ * and never deletes or rewrites anything inside it, not even with `force`.
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import { createRequire } from 'node:module';
12
+ import path from 'node:path';
13
+ import { pipeline } from 'node:stream/promises';
14
+ import { formatTimecode } from '../../shared/analysisTypes.js';
15
+ import { validateAgentLabelBatch } from '../analysis/agentLabelValidation.js';
16
+ import { measureShotCameraMotion, resolveVidstabFfmpeg } from '../analysis/cameraMotion.js';
17
+ import { renderContactSheet, resolveSheetFont, tileSizeFor } from '../analysis/contactSheet.js';
18
+ import { alignCuesToShots, segmentsToCues } from '../analysis/dialogueAlign.js';
19
+ import { computeShotSignals, probeVideo, readAudioRmsRows, readLumaRows, readMotionProfile, readSceneRows, readSilences, } from '../analysis/ffmpegSignals.js';
20
+ import { selectMotionFrameTimes, uniformFrameTimes } from '../analysis/framePlan.js';
21
+ import { extractTranscript, parseCaptionFile } from '../transcript/captionExtractor.js';
22
+ import { AGENT_LABELING_INSTRUCTIONS } from './agentLabelingInstructions.js';
23
+ import { assignAgentScenes, writeStructuredAnalysisReport } from './analysisReport.js';
24
+ import { matchTechniques, segmentFromProbeAndRows, shotIdFor } from './cinematicAnalysis.js';
25
+ import { loadCraftTaxonomy } from './craftTaxonomy.js';
26
+ import { writeTimelineExports } from './timelineExports.js';
27
+ export const PREPARE_STATE_FILE = 'prepare-state.json';
28
+ export const LABELING_REQUEST_FILE = 'labeling-request.json';
29
+ export const FRAMES_DIR = 'frames';
30
+ export const LABELS_DIR = 'labels';
31
+ /** Where `analyze prepare <url> -o <dir>` downloads the source before prepare runs. */
32
+ const SOURCE_DIR = 'source';
33
+ const DETAIL_FPS = 4;
34
+ const MAX_TILES_PER_SHEET = 12;
35
+ const SHEET_CONCURRENCY = 4;
36
+ /** One vidstabdetect pass decodes a whole shot; two at a time keep the CPU busy without thrashing it. */
37
+ const CAMERA_MOTION_CONCURRENCY = 2;
38
+ const SHOT_COUNT_WARN_THRESHOLD = 300;
39
+ /** A beat read off a tile timecode may land a frame outside the measured cut. */
40
+ const BEAT_RANGE_TOLERANCE_S = 0.05;
41
+ /** `$defs.id` of schemas/analysis-run.v1.schema.json: agent scene ids must pass it to reach analysis.json. */
42
+ const ANALYSIS_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
43
+ /** Minimum tail guard; one frame period wins when the source runs below 25 fps. */
44
+ const FRAME_EOF_GUARD_S = 0.04;
45
+ const require = createRequire(import.meta.url);
46
+ const AGENT_LABEL_SCHEMA_PATH = require.resolve('../../../schemas/agent-labels.v1.schema.json');
47
+ const round3 = (value) => Math.round(value * 1000) / 1000;
48
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
49
+ const writeJsonFile = (filePath, value) => {
50
+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
51
+ };
52
+ /** A missing file is absent (null); an unreadable or corrupt one is an error naming the file. */
53
+ const readJsonFile = (filePath) => {
54
+ let text;
55
+ try {
56
+ text = fs.readFileSync(filePath, 'utf8');
57
+ }
58
+ catch (error) {
59
+ if (error.code === 'ENOENT')
60
+ return null;
61
+ throw new Error(`${path.basename(filePath)} could not be read (${messageOf(error)}); pass --force to regenerate it.`);
62
+ }
63
+ try {
64
+ return JSON.parse(text);
65
+ }
66
+ catch (error) {
67
+ throw new Error(`${path.basename(filePath)} is corrupt (${messageOf(error)}); pass --force to regenerate it.`);
68
+ }
69
+ };
70
+ /** Streamed so multi-GB sources never land in memory. */
71
+ export const sha256OfFile = async (filePath) => {
72
+ const hash = createHash('sha256');
73
+ await pipeline(fs.createReadStream(filePath), hash);
74
+ return hash.digest('hex');
75
+ };
76
+ /** B001, B002, … over consecutive shot ids. */
77
+ export const batchShotIds = (shotIds, batchSize) => {
78
+ const size = Math.max(1, Math.floor(batchSize));
79
+ const batches = [];
80
+ for (let index = 0; index < shotIds.length; index += size) {
81
+ batches.push({
82
+ batchId: `B${String(batches.length + 1).padStart(3, '0')}`,
83
+ shotIds: shotIds.slice(index, index + size),
84
+ });
85
+ }
86
+ return batches;
87
+ };
88
+ const overlapRange = (window, detail) => {
89
+ const startS = Math.max(window.startS, detail.startS);
90
+ const endS = Math.min(window.endS, detail.endS);
91
+ return endS > startS ? { startS, endS } : null;
92
+ };
93
+ /**
94
+ * `-ss t` drops every frame starting before `t`, so a tail guard shorter than one
95
+ * frame period either overshoots the stream (no frame at all) or lands on the next
96
+ * shot's first frame.
97
+ */
98
+ export const frameEofGuardS = (fps) => Number.isFinite(fps) && fps > 0 ? Math.max(FRAME_EOF_GUARD_S, 1 / fps) : FRAME_EOF_GUARD_S;
99
+ /** Clamp planned times into the decodable part of the shot and drop duplicates. */
100
+ export const clampFrameTimes = (times, startS, endS, durationS, fps) => {
101
+ const guard = frameEofGuardS(fps);
102
+ const shotStart = Math.max(0, startS);
103
+ // Short shots keep their own start; only the end of the stream can pull a time back before it.
104
+ const upper = Math.min(Math.max(shotStart, Math.min(endS, durationS) - guard), Math.max(0, durationS - guard));
105
+ const lower = Math.min(shotStart, upper);
106
+ const clamped = new Set();
107
+ for (const time of times)
108
+ clamped.add(round3(Math.min(Math.max(time, lower), upper)));
109
+ const sorted = Array.from(clamped).sort((left, right) => left - right);
110
+ return sorted.length > 0 ? sorted : [round3(lower)];
111
+ };
112
+ /** Detail mode can plan more tiles than fit one sheet; clampFrameTimes guarantees at least one. */
113
+ const chunkTimes = (times, perSheet) => {
114
+ const chunks = [];
115
+ for (let index = 0; index < times.length; index += perSheet)
116
+ chunks.push(times.slice(index, index + perSheet));
117
+ return chunks;
118
+ };
119
+ const sheetPathFor = (framesDir, shotId, sheetIndex) => path.join(framesDir, sheetIndex === 0 ? `${shotId}.jpg` : `${shotId}-${sheetIndex + 1}.jpg`);
120
+ /** The only entries a first prepare may find in its own `-o` dir: the empty labels/ it creates and the source/ the CLI downloaded into. */
121
+ const isPrepareOwnedEntry = (dir, name, sourceUrl) => {
122
+ if (name === LABELS_DIR) {
123
+ try {
124
+ return fs.readdirSync(path.join(dir, LABELS_DIR)).length === 0;
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ }
130
+ return name === SOURCE_DIR && sourceUrl !== null;
131
+ };
132
+ /**
133
+ * Without prepare-state.json the folder is not a flucto job dir: prepare would replace its
134
+ * `frames/` and write analysis files over same-named files. Refuse it instead.
135
+ */
136
+ const assertDirIsFreeForPrepare = (dir, sourceUrl) => {
137
+ let entries;
138
+ try {
139
+ entries = fs.readdirSync(dir);
140
+ }
141
+ catch (error) {
142
+ if (error.code === 'ENOENT')
143
+ return;
144
+ throw error;
145
+ }
146
+ const blocking = entries.filter((name) => !isPrepareOwnedEntry(dir, name, sourceUrl)).sort();
147
+ if (blocking.length === 0)
148
+ return;
149
+ throw new Error(`${dir} is not empty (${blocking.slice(0, 5).join(', ')}${blocking.length > 5 ? ', …' : ''}) and has no ${PREPARE_STATE_FILE}: `
150
+ + `prepare replaces ${FRAMES_DIR}/ and writes its own files here. Choose an empty or new -o directory.`);
151
+ };
152
+ /** Renders into frames.tmp-<pid> and swaps it into frames/ only when every sheet succeeded. */
153
+ const renderSheetsAtomically = async (plans, context, onSheetRendered) => {
154
+ let renderFailure = null;
155
+ let renderedSheets = 0;
156
+ fs.rmSync(context.framesTmpDir, { recursive: true, force: true });
157
+ fs.mkdirSync(context.framesTmpDir, { recursive: true });
158
+ const rendered = await mapWithConcurrency(plans, SHEET_CONCURRENCY, async (plan) => {
159
+ if (renderFailure)
160
+ return null;
161
+ try {
162
+ const sheet = await renderContactSheet({
163
+ ffmpegPath: context.ffmpegPath,
164
+ videoPath: context.videoPath,
165
+ shotId: plan.shotId,
166
+ startS: plan.startS,
167
+ endS: plan.endS,
168
+ times: plan.times,
169
+ outPath: plan.tmpPath,
170
+ fontPath: context.fontPath,
171
+ tileSize: context.tileSize,
172
+ });
173
+ renderedSheets += 1;
174
+ onSheetRendered?.(plan, renderedSheets);
175
+ return { ...sheet, path: plan.outPath };
176
+ }
177
+ catch (error) {
178
+ renderFailure = error;
179
+ return null;
180
+ }
181
+ });
182
+ if (renderFailure) {
183
+ fs.rmSync(context.framesTmpDir, { recursive: true, force: true });
184
+ throw renderFailure;
185
+ }
186
+ // Only a complete render replaces the previous frames/.
187
+ fs.rmSync(context.framesDir, { recursive: true, force: true });
188
+ fs.renameSync(context.framesTmpDir, context.framesDir);
189
+ return rendered;
190
+ };
191
+ const PREPARE_OPTION_FLAGS = [
192
+ ['sceneThreshold', '--scene-threshold'],
193
+ ['batchSize', '--batch-size'],
194
+ ['detail', '--detail'],
195
+ ['subsPath', '--subs'],
196
+ ['subLang', '--sub-lang'],
197
+ ];
198
+ /** CLI flags whose current value differs from the one the stored sheets and batches were built with. */
199
+ const changedPrepareOptions = (stored, requested) => {
200
+ if (!stored)
201
+ return [];
202
+ return PREPARE_OPTION_FLAGS
203
+ .filter(([key]) => JSON.stringify(stored[key] ?? null) !== JSON.stringify(requested[key] ?? null))
204
+ .map(([, flag]) => flag);
205
+ };
206
+ const mapWithConcurrency = async (items, limit, run) => {
207
+ const results = new Array(items.length);
208
+ let next = 0;
209
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
210
+ for (let index = next; index < items.length; index = next) {
211
+ next = index + 1;
212
+ results[index] = await run(items[index], index);
213
+ }
214
+ });
215
+ await Promise.all(workers);
216
+ return results;
217
+ };
218
+ const countDialogueCues = (dialogue) => {
219
+ const keys = new Set();
220
+ for (const cues of Object.values(dialogue)) {
221
+ for (const cue of cues)
222
+ keys.add(`${cue.startS}|${cue.endS}|${cue.text}`);
223
+ }
224
+ return keys.size;
225
+ };
226
+ const NO_DIALOGUE = { kind: 'none', language: null, automatic: null };
227
+ /** --subs file → platform captions → none. Caption failures never fail prepare. */
228
+ const resolveDialogue = async (input, deps) => {
229
+ if (input.subsPath) {
230
+ try {
231
+ return {
232
+ cues: segmentsToCues(parseCaptionFile(input.subsPath)),
233
+ source: { kind: 'subs-file', language: input.subLang ?? null, automatic: null },
234
+ warnings: [],
235
+ };
236
+ }
237
+ catch (error) {
238
+ return { cues: [], source: NO_DIALOGUE, warnings: [`Subtitle file ${input.subsPath} could not be read: ${messageOf(error)}`] };
239
+ }
240
+ }
241
+ if (input.sourceUrl) {
242
+ try {
243
+ const transcript = await extractTranscript(input.sourceUrl, {
244
+ language: input.subLang ?? null,
245
+ binaries: { ytDlpPath: deps.ytDlpPath },
246
+ ...(deps.captionNetwork ? { network: deps.captionNetwork } : {}),
247
+ });
248
+ const language = transcript.metadata.language || input.subLang || null;
249
+ const chosen = transcript.availableLanguages.find((candidate) => candidate.code === language) ?? null;
250
+ return {
251
+ cues: segmentsToCues(transcript.segments),
252
+ source: { kind: 'platform-captions', language, automatic: chosen ? chosen.isAuto : null },
253
+ warnings: [],
254
+ };
255
+ }
256
+ catch (error) {
257
+ return { cues: [], source: NO_DIALOGUE, warnings: [`Captions for ${input.sourceUrl} are unavailable: ${messageOf(error)}`] };
258
+ }
259
+ }
260
+ return {
261
+ cues: [],
262
+ source: NO_DIALOGUE,
263
+ // A local file has no caption source to pick a language from.
264
+ warnings: input.subLang ? [`--sub-lang ${input.subLang} needs a caption source: pass --subs <file> for a local video. This run has no dialogue.`] : [],
265
+ };
266
+ };
267
+ const reuseSummary = (dir, requestPath, state, request, warnings) => ({
268
+ dir,
269
+ requestPath,
270
+ shotCount: request.shots.length,
271
+ batchCount: request.batches.length,
272
+ sheetCount: request.shots.reduce((total, shot) => total + shot.sheets.length, 0),
273
+ dialogueCues: countDialogueCues(state.dialogue),
274
+ warnings: [...(state.warnings ?? []), ...warnings, 'Reused the existing prepare state for the same source video; pass --force to regenerate.'],
275
+ });
276
+ export const prepareAgentLabeling = async (input, deps) => {
277
+ const dir = path.resolve(input.outputDir);
278
+ const framesDir = path.join(dir, FRAMES_DIR);
279
+ const framesTmpDir = path.join(dir, `${FRAMES_DIR}.tmp-${process.pid}`);
280
+ const labelsDir = path.join(dir, LABELS_DIR);
281
+ const statePath = path.join(dir, PREPARE_STATE_FILE);
282
+ const requestPath = path.join(dir, LABELING_REQUEST_FILE);
283
+ const requestedOptions = {
284
+ sceneThreshold: input.sceneThreshold,
285
+ batchSize: input.batchSize,
286
+ detail: input.detail ?? null,
287
+ subsPath: input.subsPath ?? null,
288
+ subLang: input.subLang ?? null,
289
+ };
290
+ if (!fs.existsSync(statePath))
291
+ assertDirIsFreeForPrepare(dir, input.sourceUrl ?? null);
292
+ fs.mkdirSync(labelsDir, { recursive: true });
293
+ const progress = (stage, shotsTotal, shotsDone, message) => {
294
+ deps.onProgress?.({ stage, shotsTotal, shotsDone, status: 'running', message });
295
+ };
296
+ progress('probe', 0, 0, `Hashing ${path.basename(input.videoPath)}`);
297
+ const videoSha256 = await sha256OfFile(input.videoPath);
298
+ const existingState = input.force ? null : readJsonFile(statePath);
299
+ if (existingState) {
300
+ if (existingState.videoSha256 !== videoSha256) {
301
+ throw new Error(`${dir} was prepared from a different source video (sha256 mismatch); pass --force to regenerate it.`);
302
+ }
303
+ const existingRequest = readJsonFile(requestPath);
304
+ if (existingRequest) {
305
+ const reuseWarnings = [];
306
+ const changedOptions = changedPrepareOptions(existingState.options, requestedOptions);
307
+ if (changedOptions.length > 0) {
308
+ reuseWarnings.push(`${changedOptions.join(', ')} differ from the prepared run; the stored sheets, batches and dialogue are reused unchanged. Pass --force to rebuild them.`);
309
+ }
310
+ if (!fs.existsSync(framesDir)) {
311
+ // A successful merge removes frames/; re-render the stored sheet plan and leave labels/ alone.
312
+ const sheetPlans = existingRequest.shots.flatMap((shot) => shot.sheets.map((sheet, sheetIndex) => ({
313
+ shotId: shot.shotId,
314
+ startS: shot.startS,
315
+ endS: shot.endS,
316
+ times: sheet.tiles.map((tile) => tile.t),
317
+ outPath: sheetPathFor(framesDir, shot.shotId, sheetIndex),
318
+ tmpPath: sheetPathFor(framesTmpDir, shot.shotId, sheetIndex),
319
+ })));
320
+ progress('label', existingRequest.shots.length, 0, `Re-rendering ${sheetPlans.length} missing contact sheet(s)`);
321
+ await renderSheetsAtomically(sheetPlans, {
322
+ ffmpegPath: deps.ffmpegPath,
323
+ videoPath: input.videoPath,
324
+ fontPath: resolveSheetFont(),
325
+ tileSize: tileSizeFor(existingState.probe.width, existingState.probe.height),
326
+ framesDir,
327
+ framesTmpDir,
328
+ });
329
+ reuseWarnings.push(`${FRAMES_DIR}/ was missing (a successful merge removes it); the contact sheets were re-rendered from the stored plan.`);
330
+ }
331
+ return reuseSummary(dir, requestPath, existingState, existingRequest, reuseWarnings);
332
+ }
333
+ }
334
+ const warnings = [];
335
+ const existingLabelFiles = fs.readdirSync(labelsDir).filter((name) => name.toLowerCase().endsWith('.json')).sort();
336
+ if (existingLabelFiles.length > 0) {
337
+ warnings.push(`${LABELS_DIR}/ already holds ${existingLabelFiles.join(', ')} from an earlier prepare run; prepare never deletes them, so merge would apply them to the shots measured now. Delete the stale files if this run uses a different source or segmentation.`);
338
+ }
339
+ const probe = await probeVideo(deps.ffmpegPath, input.videoPath);
340
+ progress('detect', 0, 0, `Scene, luma and motion passes (${probe.durationS.toFixed(0)}s video)`);
341
+ const [sceneRows, lumaRows, motionRows, silences, audioRmsRows] = await Promise.all([
342
+ readSceneRows(deps.ffmpegPath, input.videoPath, input.sceneThreshold),
343
+ readLumaRows(deps.ffmpegPath, input.videoPath),
344
+ readMotionProfile(deps.ffmpegPath, input.videoPath),
345
+ probe.hasAudio ? readSilences(deps.ffmpegPath, input.videoPath) : Promise.resolve([]),
346
+ probe.hasAudio ? readAudioRmsRows(deps.ffmpegPath, input.videoPath) : Promise.resolve([]),
347
+ ]);
348
+ const segmented = segmentFromProbeAndRows(probe, sceneRows);
349
+ const windows = segmented.windows;
350
+ progress('detect', windows.length, 0, `${windows.length} shot(s) (${segmented.segmentation.mode})`);
351
+ if (segmented.segmentation.mode === 'sampled') {
352
+ warnings.push(`Segmentation fell back to uniform sampling (${segmented.segmentation.reason ?? 'no scene candidates'}); shot rows are time slices, not cuts.`);
353
+ }
354
+ if (windows.length > SHOT_COUNT_WARN_THRESHOLD) {
355
+ warnings.push(`${windows.length} shots exceed ${SHOT_COUNT_WARN_THRESHOLD}; label a range with --detail or analyze a shorter clip to keep the agent pass affordable.`);
356
+ }
357
+ const dialogue = await resolveDialogue(input, deps);
358
+ warnings.push(...dialogue.warnings);
359
+ const dialogueByShot = alignCuesToShots(dialogue.cues, windows.map((window) => ({ shotId: shotIdFor(window.index), startS: window.startS, endS: window.endS })));
360
+ const camera = {};
361
+ for (const window of windows)
362
+ camera[shotIdFor(window.index)] = null;
363
+ const cameraMotionBinary = await resolveVidstabFfmpeg(deps.vidstabFfmpegPath ?? deps.ffmpegPath);
364
+ if (cameraMotionBinary) {
365
+ progress('detect', windows.length, 0, `Measuring camera motion for ${windows.length} shot(s)`);
366
+ let failedShots = 0;
367
+ let firstFailure = '';
368
+ let measuredShots = 0;
369
+ await mapWithConcurrency(windows, CAMERA_MOTION_CONCURRENCY, async (window) => {
370
+ const shotId = shotIdFor(window.index);
371
+ try {
372
+ camera[shotId] = await measureShotCameraMotion({ ffmpegPath: cameraMotionBinary, videoPath: input.videoPath, probe }, { startS: window.startS, durationS: Math.max(0, window.endS - window.startS) });
373
+ }
374
+ catch (error) {
375
+ failedShots += 1;
376
+ if (!firstFailure)
377
+ firstFailure = messageOf(error);
378
+ }
379
+ measuredShots += 1;
380
+ progress('detect', windows.length, measuredShots, `Camera motion measured for ${measuredShots}/${windows.length} shot(s)`);
381
+ });
382
+ // A failed pass never fails prepare: those shots stay unmeasured.
383
+ if (failedShots > 0) {
384
+ warnings.push(`vidstabdetect failed for ${failedShots} of ${windows.length} shot(s) (first error: ${firstFailure}); their camera motion is not measured.`);
385
+ }
386
+ }
387
+ else {
388
+ warnings.push('vidstabdetect unavailable: camera motion not measured');
389
+ }
390
+ const sheetPlans = [];
391
+ for (const window of windows) {
392
+ const shotId = shotIdFor(window.index);
393
+ const clamp = (times) => clampFrameTimes(times, window.startS, window.endS, probe.durationS, probe.fps);
394
+ // The motion-based sheet always comes first; --detail only appends denser sheets for the overlap.
395
+ const chunks = chunkTimes(clamp(selectMotionFrameTimes(window, motionRows)), MAX_TILES_PER_SHEET);
396
+ const detailRange = input.detail ? overlapRange(window, input.detail) : null;
397
+ if (detailRange) {
398
+ chunks.push(...chunkTimes(clamp(uniformFrameTimes(detailRange.startS, detailRange.endS, DETAIL_FPS)), MAX_TILES_PER_SHEET));
399
+ }
400
+ chunks.forEach((chunk, sheetIndex) => {
401
+ sheetPlans.push({
402
+ shotId,
403
+ startS: window.startS,
404
+ endS: window.endS,
405
+ times: chunk,
406
+ outPath: sheetPathFor(framesDir, shotId, sheetIndex),
407
+ tmpPath: sheetPathFor(framesTmpDir, shotId, sheetIndex),
408
+ });
409
+ });
410
+ }
411
+ progress('label', windows.length, 0, `Rendering ${sheetPlans.length} contact sheet(s)`);
412
+ const fontPath = resolveSheetFont();
413
+ const tileSize = tileSizeFor(probe.width, probe.height);
414
+ const sheetsLeftByShot = new Map();
415
+ for (const plan of sheetPlans)
416
+ sheetsLeftByShot.set(plan.shotId, (sheetsLeftByShot.get(plan.shotId) ?? 0) + 1);
417
+ let shotsDone = 0;
418
+ const sheets = await renderSheetsAtomically(sheetPlans, { ffmpegPath: deps.ffmpegPath, videoPath: input.videoPath, fontPath, tileSize, framesDir, framesTmpDir }, (plan, renderedSheets) => {
419
+ const sheetsLeft = (sheetsLeftByShot.get(plan.shotId) ?? 1) - 1;
420
+ sheetsLeftByShot.set(plan.shotId, sheetsLeft);
421
+ if (sheetsLeft === 0)
422
+ shotsDone += 1;
423
+ progress('label', windows.length, shotsDone, `${renderedSheets}/${sheetPlans.length} contact sheet(s) rendered`);
424
+ });
425
+ const sheetsByShot = new Map();
426
+ sheetPlans.forEach((plan, index) => {
427
+ const list = sheetsByShot.get(plan.shotId) ?? [];
428
+ list.push(sheets[index]);
429
+ sheetsByShot.set(plan.shotId, list);
430
+ });
431
+ progress('emit', windows.length, windows.length, 'Writing labeling request');
432
+ const signals = {};
433
+ const dialogueRecord = {};
434
+ const shots = windows.map((window) => {
435
+ const shotId = shotIdFor(window.index);
436
+ const shotSignals = computeShotSignals(window, sceneRows, lumaRows, silences, audioRmsRows, probe.hasAudio);
437
+ const shotDialogue = dialogueByShot.get(shotId) ?? [];
438
+ signals[shotId] = shotSignals;
439
+ dialogueRecord[shotId] = shotDialogue;
440
+ return {
441
+ shotId,
442
+ startS: round3(window.startS),
443
+ endS: round3(window.endS),
444
+ startTimecode: formatTimecode(window.startS),
445
+ endTimecode: formatTimecode(window.endS),
446
+ sheets: sheetsByShot.get(shotId) ?? [],
447
+ signals: shotSignals,
448
+ cameraMotionMeasured: camera[shotId],
449
+ dialogue: shotDialogue,
450
+ };
451
+ });
452
+ const request = {
453
+ version: 1,
454
+ instructions: AGENT_LABELING_INSTRUCTIONS,
455
+ schemaPath: AGENT_LABEL_SCHEMA_PATH,
456
+ labelsDir,
457
+ batchSize: input.batchSize,
458
+ segmentationMode: segmented.segmentation,
459
+ dialogueSource: dialogue.source,
460
+ batches: batchShotIds(shots.map((shot) => shot.shotId), input.batchSize),
461
+ shots,
462
+ };
463
+ const state = {
464
+ version: 1,
465
+ videoPath: input.videoPath,
466
+ sourceUrl: input.sourceUrl ?? null,
467
+ videoSha256,
468
+ probe,
469
+ segmentation: segmented.segmentation,
470
+ windows,
471
+ signals,
472
+ camera,
473
+ cameraMotionBinary,
474
+ dialogue: dialogueRecord,
475
+ dialogueSource: dialogue.source,
476
+ options: requestedOptions,
477
+ warnings,
478
+ createdAt: new Date().toISOString(),
479
+ };
480
+ writeJsonFile(statePath, state);
481
+ writeJsonFile(requestPath, request);
482
+ return {
483
+ dir,
484
+ requestPath,
485
+ shotCount: shots.length,
486
+ batchCount: request.batches.length,
487
+ sheetCount: sheets.length,
488
+ dialogueCues: countDialogueCues(dialogueRecord),
489
+ warnings,
490
+ };
491
+ };
492
+ const labelFileNameFor = (batchId) => `${batchId}.json`;
493
+ const statMtimeMs = (filePath) => {
494
+ try {
495
+ return fs.statSync(filePath).mtimeMs;
496
+ }
497
+ catch {
498
+ return null;
499
+ }
500
+ };
501
+ /** A missing batch file is absent (null); unreadable, corrupt and schema-invalid ones carry named errors. */
502
+ const readLabelBatchFile = (filePath) => {
503
+ const name = path.basename(filePath);
504
+ let text;
505
+ try {
506
+ text = fs.readFileSync(filePath, 'utf8');
507
+ }
508
+ catch (error) {
509
+ if (error.code === 'ENOENT')
510
+ return null;
511
+ return { ok: false, errors: [`${name} could not be read (${messageOf(error)}); the batch was skipped.`] };
512
+ }
513
+ let parsed;
514
+ try {
515
+ parsed = JSON.parse(text);
516
+ }
517
+ catch (error) {
518
+ return { ok: false, errors: [`${name} is not valid JSON (${messageOf(error)}); the batch was skipped.`] };
519
+ }
520
+ const validation = validateAgentLabelBatch(parsed);
521
+ if (validation.ok)
522
+ return validation;
523
+ return { ok: false, errors: validation.errors.map((error) => `${name} does not match the label schema: ${error}`) };
524
+ };
525
+ /**
526
+ * Craft taxonomy anchors are whole words ("close-up", "tracking"), so the short label
527
+ * codes are expanded before the matcher compares them. Codes that are already words
528
+ * (`pan`, `static`, `low`, `dutch`, …) stay as they are.
529
+ */
530
+ const CRAFT_TERM_BY_LABEL_CODE = {
531
+ ecu: 'extreme close-up',
532
+ cu: 'close-up',
533
+ mcu: 'medium close-up',
534
+ ms: 'medium shot',
535
+ fs: 'full shot',
536
+ ws: 'wide shot',
537
+ ews: 'extreme wide shot',
538
+ topdown: 'top-down',
539
+ eye: 'eye-level',
540
+ ots: 'over-the-shoulder',
541
+ pov: 'pov',
542
+ track: 'tracking',
543
+ whip: 'whip pan',
544
+ push: 'push-in',
545
+ pull: 'pull-out',
546
+ };
547
+ const craftTermFor = (code) => code ? CRAFT_TERM_BY_LABEL_CODE[code] ?? code : undefined;
548
+ /** The subset of an agent label the taxonomy matcher and the production plan text read. */
549
+ const toSemanticLabels = (label) => {
550
+ const subjectKind = (label.characters ?? []).map((character) => character.ref.trim()).filter(Boolean).join(', ');
551
+ const candidate = {
552
+ shotSize: craftTermFor(label.shotSize),
553
+ angle: craftTermFor(label.angle),
554
+ cameraMotion: craftTermFor(label.cameraMotion),
555
+ cameraAxis: label.cameraAxis ?? undefined,
556
+ lightingType: label.lightingType ?? undefined,
557
+ palette: label.palette ?? undefined,
558
+ composition: label.composition ?? undefined,
559
+ subjectKind: subjectKind || undefined,
560
+ narrativeFunctionGuess: label.narrativeFunction ?? undefined,
561
+ transitionGuess: label.transitionIn ?? undefined,
562
+ actionPhaseSummary: label.directionNotes ?? undefined,
563
+ confidence: typeof label.confidence === 'number' && Number.isFinite(label.confidence) ? label.confidence : undefined,
564
+ };
565
+ return Object.fromEntries(Object.entries(candidate).filter(([, value]) => value !== undefined));
566
+ };
567
+ const FALLBACK_SCENE_RATIONALE = 'fallback: no agent scene proposal';
568
+ /** Timeline input with the final scene ids; shots the agent left out get a synthesized SC-U scene. */
569
+ const buildTimelineExportData = (state, observations, labels, proposals) => {
570
+ const assignment = assignAgentScenes(observations, proposals);
571
+ const shots = observations.map((observation) => ({
572
+ shotId: observation.shotId,
573
+ sceneId: assignment.sceneIdByShot.get(observation.shotId) ?? observation.sceneId,
574
+ startS: observation.startS,
575
+ endS: observation.endS,
576
+ label: labels.get(observation.shotId) ?? null,
577
+ dialogue: state.dialogue?.[observation.shotId] ?? [],
578
+ camera: state.camera?.[observation.shotId] ?? null,
579
+ }));
580
+ const scenes = [];
581
+ for (const sceneId of new Set(shots.map((shot) => shot.sceneId))) {
582
+ const shotIds = shots.filter((shot) => shot.sceneId === sceneId).map((shot) => shot.shotId);
583
+ const proposal = assignment.proposalBySceneId.get(sceneId);
584
+ scenes.push(proposal ? { ...proposal, shotIds } : { sceneId, shotIds, rationale: FALLBACK_SCENE_RATIONALE });
585
+ }
586
+ return { shots, scenes, segmentation: state.segmentation, videoName: path.basename(state.videoPath), dialogueSource: state.dialogueSource };
587
+ };
588
+ /**
589
+ * Merges the agent's label batches into the measured prepare state and writes the
590
+ * structured report. Invalid batches, unknown shot ids and out-of-range beats are
591
+ * reported in `labelErrors` instead of failing the run.
592
+ */
593
+ export const mergeAgentLabels = async (dir, opts, deps = {}) => {
594
+ const startedAt = new Date().toISOString();
595
+ const resolved = path.resolve(dir);
596
+ const state = readJsonFile(path.join(resolved, PREPARE_STATE_FILE));
597
+ if (!state)
598
+ throw new Error(`${resolved} has no ${PREPARE_STATE_FILE}; run analyze prepare on the source video first.`);
599
+ const request = readJsonFile(path.join(resolved, LABELING_REQUEST_FILE));
600
+ if (!request)
601
+ throw new Error(`${resolved} has no ${LABELING_REQUEST_FILE}; run analyze prepare on the source video first.`);
602
+ const labelsDir = path.join(resolved, LABELS_DIR);
603
+ const windowByShotId = new Map(state.windows.map((window) => [shotIdFor(window.index), window]));
604
+ const labelErrors = [];
605
+ const labelWarnings = [];
606
+ const labels = new Map();
607
+ const batchByShotId = new Map();
608
+ const scenes = [];
609
+ const sceneIdByShotId = new Map();
610
+ const labeledBy = new Map();
611
+ // Only the request's own batch files, sorted by name: B001 before B002, so a later batch wins a repeated shot.
612
+ const presentFiles = fs.existsSync(labelsDir) ? fs.readdirSync(labelsDir).filter((name) => name.toLowerCase().endsWith('.json')) : [];
613
+ const requestedFiles = new Set(request.batches.map((batch) => labelFileNameFor(batch.batchId)));
614
+ const batchFiles = presentFiles.filter((name) => requestedFiles.has(name)).sort();
615
+ for (const name of presentFiles.filter((file) => !requestedFiles.has(file)).sort()) {
616
+ labelWarnings.push(`${LABELS_DIR}/${name} is not a batch file of this prepare run (expected ${LABELS_DIR}/<batchId>.json); it was ignored.`);
617
+ }
618
+ const progress = (stage, shotsDone, message) => {
619
+ deps.onProgress?.({ stage, shotsTotal: state.windows.length, shotsDone, status: 'running', message });
620
+ };
621
+ progress('label', 0, `Reading ${batchFiles.length} label batch file(s)`);
622
+ const preparedAtMs = Date.parse(state.createdAt);
623
+ for (const fileName of batchFiles) {
624
+ const batchName = path.basename(fileName, path.extname(fileName));
625
+ const filePath = path.join(labelsDir, fileName);
626
+ // prepare never deletes labels/, so a file older than the current prepare run may describe other shots.
627
+ const writtenAtMs = statMtimeMs(filePath);
628
+ if (Number.isFinite(preparedAtMs) && writtenAtMs !== null && writtenAtMs < preparedAtMs) {
629
+ labelWarnings.push(`${batchName}: ${LABELS_DIR}/${fileName} is older than this prepare run (${state.createdAt}); it may label the shots of an earlier run.`);
630
+ }
631
+ const read = readLabelBatchFile(filePath);
632
+ if (!read || !read.ok) {
633
+ labelErrors.push(...(read?.errors ?? []));
634
+ continue;
635
+ }
636
+ const batch = read.batch;
637
+ labeledBy.set(`${batch.labeledBy.agent}/${batch.labeledBy.model}`, batch.labeledBy);
638
+ for (const label of batch.shots) {
639
+ const window = windowByShotId.get(label.shotId);
640
+ if (!window) {
641
+ labelErrors.push(`${batchName}: ${label.shotId} is not a shot of this prepare run; the label was ignored.`);
642
+ continue;
643
+ }
644
+ const previousBatch = batchByShotId.get(label.shotId);
645
+ if (previousBatch)
646
+ labelWarnings.push(`${batchName}: ${label.shotId} was already labeled in ${previousBatch}; the later label wins.`);
647
+ const beats = (label.beats ?? []).filter((beat) => {
648
+ const inRange = beat.t >= window.startS - BEAT_RANGE_TOLERANCE_S && beat.t <= window.endS + BEAT_RANGE_TOLERANCE_S;
649
+ if (!inRange)
650
+ labelErrors.push(`${batchName}: ${label.shotId} beat t=${beat.t} is outside ${round3(window.startS)}–${round3(window.endS)} s; the beat was dropped.`);
651
+ return inRange;
652
+ });
653
+ labels.set(label.shotId, label.beats ? { ...label, beats } : label);
654
+ batchByShotId.set(label.shotId, batchName);
655
+ }
656
+ for (const proposal of batch.scenes ?? []) {
657
+ if (!ANALYSIS_ID_PATTERN.test(proposal.sceneId)) {
658
+ labelErrors.push(`${batchName}: scene id ${proposal.sceneId} is not a usable analysis id; the proposal was ignored.`);
659
+ continue;
660
+ }
661
+ const freshShotIds = [];
662
+ for (const shotId of proposal.shotIds) {
663
+ if (!windowByShotId.has(shotId)) {
664
+ labelErrors.push(`${batchName}: scene ${proposal.sceneId} references ${shotId}, which is not a shot of this prepare run; it was ignored.`);
665
+ continue;
666
+ }
667
+ const assignedSceneId = sceneIdByShotId.get(shotId);
668
+ if (assignedSceneId) {
669
+ labelErrors.push(`${batchName}: ${shotId} already belongs to scene ${assignedSceneId}; its duplicate in ${proposal.sceneId} was ignored.`);
670
+ continue;
671
+ }
672
+ sceneIdByShotId.set(shotId, proposal.sceneId);
673
+ freshShotIds.push(shotId);
674
+ }
675
+ if (freshShotIds.length > 0)
676
+ scenes.push({ ...proposal, shotIds: freshShotIds });
677
+ }
678
+ }
679
+ const videoName = path.basename(state.videoPath);
680
+ const observations = state.windows.map((window) => {
681
+ const shotId = shotIdFor(window.index);
682
+ const signals = state.signals[shotId];
683
+ if (!signals)
684
+ throw new Error(`${PREPARE_STATE_FILE} has no signals for ${shotId}; re-run analyze prepare with force.`);
685
+ const label = labels.get(shotId) ?? null;
686
+ return {
687
+ videoPath: state.videoPath,
688
+ videoName,
689
+ shotId,
690
+ sceneId: '',
691
+ index: window.index,
692
+ startS: window.startS,
693
+ endS: window.endS,
694
+ durationS: Math.max(0, window.endS - window.startS),
695
+ startTimecode: formatTimecode(window.startS),
696
+ endTimecode: formatTimecode(window.endS),
697
+ cutType: window.cutType,
698
+ outgoingBoundaryCandidate: window.outgoingBoundaryCandidate ? {
699
+ timeSeconds: window.outgoingBoundaryCandidate.ptsS,
700
+ score: window.outgoingBoundaryCandidate.score,
701
+ method: window.outgoingBoundaryCandidate.method,
702
+ verification: 'estimated',
703
+ } : null,
704
+ signals,
705
+ labels: label ? toSemanticLabels(label) : {},
706
+ visionOutcome: label ? 'labeled' : 'not-requested',
707
+ frameRequestAttempted: false,
708
+ frameRequestResponseReceived: false,
709
+ frameRequestDestination: null,
710
+ matchedTechniqueIds: [],
711
+ matchedEvidence: [],
712
+ unmatchedAnchors: [],
713
+ analysisStatus: label ? 'labeled' : 'signal-only',
714
+ };
715
+ });
716
+ const taxonomyRows = opts.craftDir ? loadCraftTaxonomy(opts.craftDir).rows : [];
717
+ for (const observation of observations) {
718
+ if (taxonomyRows.length === 0)
719
+ break;
720
+ const outcome = matchTechniques(observation.cutType, observation.signals, observation.labels, taxonomyRows);
721
+ observation.matchedTechniqueIds = outcome.matchedIds;
722
+ observation.matchedEvidence = outcome.matchedEvidence;
723
+ observation.unmatchedAnchors = outcome.unmatchedAnchors;
724
+ }
725
+ const labeledShots = observations.filter((observation) => observation.analysisStatus === 'labeled').length;
726
+ const signalOnlyShots = observations.length - labeledShots;
727
+ const visionSummary = {
728
+ attemptedModelCalls: 0,
729
+ modelCallLimit: 0,
730
+ labeledShots,
731
+ signalOnlyShots,
732
+ partialReasons: [
733
+ ...(signalOnlyShots > 0 ? ['unlabeled-shots'] : []),
734
+ ...(labelErrors.length > 0 ? ['label-errors'] : []),
735
+ ],
736
+ frameRequestAttempted: false,
737
+ frameRequestResponseReceived: false,
738
+ externalFrameRequestAttempted: false,
739
+ localServerFrameRequestAttempted: false,
740
+ // Flucto transmits nothing here; where the calling agent's own model runs is not observable.
741
+ externalOnwardTransmission: null,
742
+ };
743
+ // The timeline files are written first so the manifest can list them as artifacts.
744
+ progress('emit', observations.length, 'Writing the timeline exports');
745
+ const timelinePaths = writeTimelineExports(resolved, buildTimelineExportData(state, observations, labels, scenes), opts.exports);
746
+ progress('emit', observations.length, 'Writing the analysis report');
747
+ const structured = await writeStructuredAnalysisReport({
748
+ // Report-only request: merge reuses prepare's measurements, so budget and vision settings are unused.
749
+ request: {
750
+ videoPath: state.videoPath,
751
+ ...(state.sourceUrl ? { sourceUrl: state.sourceUrl } : {}),
752
+ craftDir: opts.craftDir ?? '',
753
+ outputDir: resolved,
754
+ budget: { maxFramesPerShot: 0, maxApiCalls: 0 },
755
+ vision: { enabled: false, provider: null },
756
+ sceneThreshold: 0,
757
+ },
758
+ probe: state.probe,
759
+ observations,
760
+ taxonomyRows,
761
+ segmentationMode: state.segmentation,
762
+ startedAt,
763
+ visionSummary,
764
+ // The hash recorded by prepare: the source may have moved or changed since, and rehashing a multi-GB file is wasted work.
765
+ sourceSha256: state.videoSha256,
766
+ additionalArtifacts: timelinePaths,
767
+ agent: {
768
+ labels,
769
+ scenes,
770
+ dialogue: state.dialogue ?? {},
771
+ camera: state.camera ?? {},
772
+ dialogueSource: state.dialogueSource,
773
+ labeledBy: Array.from(labeledBy.values()),
774
+ },
775
+ });
776
+ if (!opts.keepFrames)
777
+ fs.rmSync(path.join(resolved, FRAMES_DIR), { recursive: true, force: true });
778
+ return {
779
+ success: true,
780
+ videoPath: state.videoPath,
781
+ outputDir: resolved,
782
+ // Agent mode writes no legacy CSVs; only the files merge actually produced are reported.
783
+ shotlogPath: null,
784
+ techniquesPath: null,
785
+ analysisJsonPath: structured.analysisJsonPath,
786
+ manifestPath: structured.manifestPath,
787
+ toolRecommendationsPath: structured.toolRecommendationsPath,
788
+ shotCount: observations.length,
789
+ rowsIncomplete: signalOnlyShots > 0 || labelErrors.length > 0 || state.segmentation.mode !== 'full',
790
+ segmentationMode: state.segmentation,
791
+ labeledShots,
792
+ signalOnlyShots,
793
+ unknownShots: 0,
794
+ budgetExceeded: false,
795
+ visionSummary,
796
+ matchedTechniqueCount: new Set(observations.flatMap((observation) => observation.matchedTechniqueIds)).size,
797
+ labelErrors,
798
+ labelWarnings,
799
+ timelinePaths,
800
+ };
801
+ };
802
+ /** Labeling progress of a prepared dir: which batches the agent still has to write or finish. */
803
+ export const labelingStatus = (dir) => {
804
+ const resolved = path.resolve(dir);
805
+ const labelsDir = path.join(resolved, LABELS_DIR);
806
+ const request = readJsonFile(path.join(resolved, LABELING_REQUEST_FILE));
807
+ if (!request)
808
+ throw new Error(`${resolved} has no ${LABELING_REQUEST_FILE}; run analyze prepare on the source video first.`);
809
+ const shotIds = new Set(request.shots.map((shot) => shot.shotId));
810
+ const labeledShotIds = new Set();
811
+ const pendingBatches = [];
812
+ const invalidBatches = [];
813
+ const validBatches = [];
814
+ for (const batch of request.batches) {
815
+ const read = readLabelBatchFile(path.join(labelsDir, labelFileNameFor(batch.batchId)));
816
+ if (!read) {
817
+ pendingBatches.push(batch.batchId);
818
+ continue;
819
+ }
820
+ if (!read.ok) {
821
+ invalidBatches.push({ batchId: batch.batchId, errors: read.errors });
822
+ continue;
823
+ }
824
+ validBatches.push(batch);
825
+ for (const label of read.batch.shots)
826
+ if (shotIds.has(label.shotId))
827
+ labeledShotIds.add(label.shotId);
828
+ }
829
+ // A shot another valid batch file labeled still counts as done, as it does in merge.
830
+ const incompleteBatches = validBatches
831
+ .map((batch) => ({ batchId: batch.batchId, missingShotIds: batch.shotIds.filter((shotId) => !labeledShotIds.has(shotId)) }))
832
+ .filter((batch) => batch.missingShotIds.length > 0);
833
+ const requestedFiles = new Set(request.batches.map((batch) => labelFileNameFor(batch.batchId)));
834
+ const unexpectedFiles = (fs.existsSync(labelsDir) ? fs.readdirSync(labelsDir) : [])
835
+ .filter((name) => name.toLowerCase().endsWith('.json') && !requestedFiles.has(name))
836
+ .sort();
837
+ return {
838
+ shotCount: request.shots.length,
839
+ labeledShots: labeledShotIds.size,
840
+ pendingBatches,
841
+ incompleteBatches,
842
+ invalidBatches,
843
+ unexpectedFiles,
844
+ };
845
+ };
846
+ //# sourceMappingURL=agentLabeling.js.map