@joplo-app/server 0.6.2 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asset-usage.d.ts +48 -0
- package/dist/asset-usage.js +174 -0
- package/dist/audio-timing.d.ts +14 -0
- package/dist/audio-timing.js +66 -0
- package/dist/build.js +15 -2
- package/dist/capture.d.ts +15 -0
- package/dist/capture.js +49 -0
- package/dist/checkpoint.d.ts +10 -0
- package/dist/checkpoint.js +75 -0
- package/dist/contract.d.ts +63 -1
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +15 -7
- package/dist/export.d.ts +6 -0
- package/dist/export.js +5 -2
- package/dist/film.d.ts +12 -1
- package/dist/film.js +231 -25
- package/dist/index.d.ts +7 -1
- package/dist/index.js +5 -1
- package/dist/layout-audit-browser.js +114 -0
- package/dist/layout-audit.d.ts +94 -0
- package/dist/layout-audit.js +86 -0
- package/dist/local-resources.d.ts +5 -0
- package/dist/local-resources.js +32 -6
- package/dist/media-check.d.ts +7 -1
- package/dist/media-check.js +44 -3
- package/dist/output-file.d.ts +3 -0
- package/dist/output-file.js +23 -0
- package/dist/project.d.ts +5 -1
- package/dist/project.js +20 -4
- package/dist/render.d.ts +2 -0
- package/dist/render.js +24 -10
- package/dist/resources-run.d.ts +1 -0
- package/dist/resources-run.js +23 -2
- package/dist/timeline.d.ts +76 -0
- package/dist/timeline.js +143 -0
- package/dist/video-format.d.ts +2 -0
- package/dist/video-format.js +12 -0
- package/dist/vite-shared.d.ts +1 -1
- package/dist/vite-shared.js +2 -2
- package/dist/voice-http.d.ts +1 -0
- package/dist/voice-http.js +8 -2
- package/dist/voice-run.d.ts +17 -1
- package/dist/voice-run.js +71 -9
- package/dist/voice.d.ts +1 -0
- package/dist/voice.js +10 -2
- package/dist/watch-config.d.ts +3 -0
- package/dist/watch-config.js +10 -0
- package/package.json +4 -4
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type Importer } from '@joplo-app/core/node';
|
|
2
|
+
export type AssetUsageReference = {
|
|
3
|
+
workId: string | null;
|
|
4
|
+
scenarioId: string | null;
|
|
5
|
+
layer: string | null;
|
|
6
|
+
elementId: string | null;
|
|
7
|
+
source: string | null;
|
|
8
|
+
evidence: 'loaded-asset-call' | 'compiled-content' | 'declared-resource';
|
|
9
|
+
inSelectedScope?: boolean;
|
|
10
|
+
stepId?: string;
|
|
11
|
+
};
|
|
12
|
+
export type AssetUsageEntry = {
|
|
13
|
+
id: string;
|
|
14
|
+
path: string | null;
|
|
15
|
+
kind: string;
|
|
16
|
+
mime: string | null;
|
|
17
|
+
bytes: number | null;
|
|
18
|
+
authorReference: 'referenced' | 'not-found-in-loaded-model' | 'unknown';
|
|
19
|
+
publication: 'included-in-selected-ir' | 'not-in-selected-ir' | 'unknown';
|
|
20
|
+
sampledVisibility: 'unknown';
|
|
21
|
+
metadata: Record<string, string>;
|
|
22
|
+
references: AssetUsageReference[];
|
|
23
|
+
};
|
|
24
|
+
export type AssetUsageReport = {
|
|
25
|
+
schemaVersion: 1;
|
|
26
|
+
root: string;
|
|
27
|
+
scope: {
|
|
28
|
+
authorReferences: 'whole-loaded-project';
|
|
29
|
+
work: string | null;
|
|
30
|
+
scenario: string | null;
|
|
31
|
+
publicationScenarios: string[];
|
|
32
|
+
scan: string[];
|
|
33
|
+
sourceFiles: string[];
|
|
34
|
+
};
|
|
35
|
+
entries: AssetUsageEntry[];
|
|
36
|
+
unknowns: {
|
|
37
|
+
source: string | null;
|
|
38
|
+
reason: string;
|
|
39
|
+
}[];
|
|
40
|
+
limitations: string[];
|
|
41
|
+
};
|
|
42
|
+
export declare function assetUsage(opts: {
|
|
43
|
+
directory: string;
|
|
44
|
+
importer: Importer;
|
|
45
|
+
scan?: string[];
|
|
46
|
+
work?: string;
|
|
47
|
+
scenario?: string;
|
|
48
|
+
}): Promise<AssetUsageReport>;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/** Read-only provenance report. Never invokes a resource compiler, build, renderer, uploader or cleanup. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { captureAssetLoads } from '@joplo-app/kit';
|
|
6
|
+
import { compile, JoploError, resolveScope, scopeProject, nodeResourceIds, mediaResourceIds } from '@joplo-app/core';
|
|
7
|
+
import { discoverFiles, loadAuthoring } from '@joplo-app/core/node';
|
|
8
|
+
import { publishPayload } from "./build.js";
|
|
9
|
+
const digest = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
|
|
10
|
+
const strings = (value, visit) => {
|
|
11
|
+
if (typeof value === 'string')
|
|
12
|
+
visit(value);
|
|
13
|
+
else if (Array.isArray(value))
|
|
14
|
+
value.forEach(v => strings(v, visit));
|
|
15
|
+
else if (value && typeof value === 'object')
|
|
16
|
+
Object.values(value).forEach(v => strings(v, visit));
|
|
17
|
+
};
|
|
18
|
+
const hashes = (value) => {
|
|
19
|
+
const out = new Set();
|
|
20
|
+
strings(value, s => { for (const m of s.matchAll(/data:[\w.+/-]+;base64,([A-Za-z0-9+/=]+)/g))
|
|
21
|
+
out.add(digest(Buffer.from(m[1], 'base64'))); });
|
|
22
|
+
return out;
|
|
23
|
+
};
|
|
24
|
+
const resourceKey = (request) => JSON.stringify([request.plugin, request.compiler, request.input]);
|
|
25
|
+
export async function assetUsage(opts) {
|
|
26
|
+
const root = fs.realpathSync(opts.directory);
|
|
27
|
+
const rel = (value) => path.relative(root, value).split(path.sep).join('/');
|
|
28
|
+
const source = (value) => value ? (path.isAbsolute(value.replace(/:\d+:\d+$/, '')) ? rel(value) : value) : null;
|
|
29
|
+
const requests = [], publishRequests = [];
|
|
30
|
+
const captured = await captureAssetLoads(async () => {
|
|
31
|
+
const loaded = await loadAuthoring(root, opts.importer);
|
|
32
|
+
if (!loaded.authoring || loaded.diagnostics.some(d => d.severity === 'error'))
|
|
33
|
+
throw new JoploError('INVALID_SCHEMA', 'Cannot report asset usage until project loading succeeds', { diagnostics: loaded.diagnostics });
|
|
34
|
+
const dev = compile(loaded.authoring, 'dev', { onResource: request => requests.push(request) });
|
|
35
|
+
const published = compile(loaded.authoring, 'publish', { onResource: request => publishRequests.push(request) });
|
|
36
|
+
if (!dev.project || !published.project || [...dev.diagnostics, ...published.diagnostics].some(d => d.severity === 'error'))
|
|
37
|
+
throw new JoploError('INVALID_SCHEMA', `Cannot report asset usage until project compilation succeeds: ${[...dev.diagnostics, ...published.diagnostics].filter(d => d.severity === 'error').slice(0, 5).map(d => `${d.code}: ${d.message}`).join('; ')}`, { diagnostics: [...dev.diagnostics, ...published.diagnostics] });
|
|
38
|
+
return { dev: dev.project, published: published.project };
|
|
39
|
+
});
|
|
40
|
+
const { dev } = captured.value;
|
|
41
|
+
if (opts.work && !dev.works[opts.work])
|
|
42
|
+
throw new JoploError('USAGE', `Unknown work: ${opts.work}`);
|
|
43
|
+
if (opts.scenario && (!dev.scenarios[opts.scenario] || opts.work && dev.scenarios[opts.scenario]?.workId !== opts.work))
|
|
44
|
+
throw new JoploError('USAGE', `Unknown scenario or work mismatch: ${opts.scenario}`);
|
|
45
|
+
const selected = new Set(Object.values(dev.scenarios).filter(sc => (!opts.work || sc.workId === opts.work) && (!opts.scenario || sc.id === opts.scenario)).map(sc => sc.id));
|
|
46
|
+
for (const id of selected)
|
|
47
|
+
if (dev.scenarios[id]?.from)
|
|
48
|
+
selected.add(dev.scenarios[id].from);
|
|
49
|
+
let published = captured.value.published;
|
|
50
|
+
if (opts.work || opts.scenario) {
|
|
51
|
+
const ids = [...selected].filter(id => published.scenarios[id]);
|
|
52
|
+
// Draft-only author scope is valid for reporting, with no publication payload.
|
|
53
|
+
published = ids.length ? scopeProject(published, resolveScope(published, { scenarios: ids }, 'publish')).project : { ...published, scenarios: {}, scenes: {} };
|
|
54
|
+
}
|
|
55
|
+
const payload = Object.keys(published.scenarios).length ? publishPayload(published, null).project : null;
|
|
56
|
+
const publishedResources = payload ? new Set([...nodeResourceIds(payload), ...mediaResourceIds(published)]) : new Set();
|
|
57
|
+
const publishedByKey = new Map(publishRequests.map(request => [resourceKey(request), request]));
|
|
58
|
+
const publishedHashes = hashes(payload);
|
|
59
|
+
const unknowns = [];
|
|
60
|
+
if (!captured.assets.length)
|
|
61
|
+
unknowns.push({ source: null, reason: 'No asset() evaluations were captured; module caching or helper/kit instances may hide provenance. Unmatched files remain unknown.' });
|
|
62
|
+
const sourceFiles = discoverFiles(root).filter(f => /\.[cm]?[jt]sx?$/.test(f));
|
|
63
|
+
for (const file of sourceFiles) {
|
|
64
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
65
|
+
if (/\b(?:from\s*|import\s*\()(['"])(?:\.|\/)/.test(text))
|
|
66
|
+
unknowns.push({ source: rel(file), reason: 'Imported helper modules are not statically traversed; cached modules and hidden branches can carry additional asset references.' });
|
|
67
|
+
if ([...text.matchAll(/\basset\s*\(([^)]*)/g)].some(m => !/^(['"])[\s\S]*\1(?:\s*,|\s*$)/.test(m[1].trim())))
|
|
68
|
+
unknowns.push({ source: rel(file), reason: 'Potential dynamic asset path; only executed asset() calls are observed. Aliases, imports and unexecuted branches are not statically resolved.' });
|
|
69
|
+
}
|
|
70
|
+
const entries = new Map();
|
|
71
|
+
const byHash = new Map();
|
|
72
|
+
const addFile = (file, mime) => {
|
|
73
|
+
const real = fs.realpathSync(file), id = rel(real);
|
|
74
|
+
if (entries.has(id))
|
|
75
|
+
return entries.get(id);
|
|
76
|
+
const size = fs.statSync(real).size, hasher = crypto.createHash('sha256');
|
|
77
|
+
const fd = fs.openSync(real, 'r'), chunk = Buffer.alloc(64 * 1024);
|
|
78
|
+
try {
|
|
79
|
+
let count;
|
|
80
|
+
while ((count = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0)
|
|
81
|
+
hasher.update(chunk.subarray(0, count));
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
const hash = hasher.digest('hex');
|
|
87
|
+
const entry = { id, path: id, kind: mime?.split('/')[0] ?? (path.extname(real).slice(1) || 'file'), mime, bytes: size, authorReference: 'not-found-in-loaded-model', publication: publishedHashes.has(hash) ? 'included-in-selected-ir' : 'not-in-selected-ir', sampledVisibility: 'unknown', metadata: {}, references: [] };
|
|
88
|
+
entries.set(id, entry);
|
|
89
|
+
byHash.set(hash, [...(byHash.get(hash) ?? []), entry]);
|
|
90
|
+
return entry;
|
|
91
|
+
};
|
|
92
|
+
for (const load of captured.assets) {
|
|
93
|
+
const entry = addFile(load.file, load.mime);
|
|
94
|
+
entry.references.push({ workId: null, scenarioId: null, layer: null, elementId: null, source: source(load.source), evidence: 'loaded-asset-call' });
|
|
95
|
+
entry.authorReference = 'referenced';
|
|
96
|
+
}
|
|
97
|
+
const scan = (opts.scan ?? []).map(dir => {
|
|
98
|
+
const resolved = path.resolve(root, dir), real = fs.realpathSync(resolved), relative = path.relative(root, real);
|
|
99
|
+
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
100
|
+
throw new JoploError('USAGE', 'Asset scan directories must be inside the project root');
|
|
101
|
+
return resolved;
|
|
102
|
+
});
|
|
103
|
+
const walkFiles = (directory) => {
|
|
104
|
+
const stat = fs.lstatSync(directory);
|
|
105
|
+
if (stat.isSymbolicLink()) {
|
|
106
|
+
unknowns.push({ source: rel(directory), reason: 'Symlink skipped; its target is outside this explicit traversal.' });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (stat.isFile()) {
|
|
110
|
+
addFile(directory, null);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
for (const name of fs.readdirSync(directory).sort())
|
|
114
|
+
walkFiles(path.join(directory, name));
|
|
115
|
+
};
|
|
116
|
+
scan.forEach(walkFiles);
|
|
117
|
+
const addReferences = (value, ref) => {
|
|
118
|
+
for (const hash of hashes(value))
|
|
119
|
+
for (const entry of byHash.get(hash) ?? []) {
|
|
120
|
+
entry.authorReference = 'referenced';
|
|
121
|
+
entry.references.push(ref);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
for (const scene of Object.values(dev.scenes)) {
|
|
125
|
+
const scenarios = Object.values(dev.scenarios).filter(sc => (scene.workId ? sc.workId === scene.workId : dev.works[sc.workId]?.routes.includes(scene.route)));
|
|
126
|
+
const visit = (node) => {
|
|
127
|
+
for (const sc of scenarios) {
|
|
128
|
+
const layers = Object.entries(dev.works[sc.workId]?.layers ?? {}).filter(([, layer]) => layer.sceneId === scene.id).map(([key]) => key);
|
|
129
|
+
const { children: _children, ...own } = node;
|
|
130
|
+
for (const layer of layers.length ? layers : [null])
|
|
131
|
+
addReferences(own, { workId: sc.workId, scenarioId: sc.id, layer, elementId: node.id, source: source(node.source), evidence: 'compiled-content' });
|
|
132
|
+
}
|
|
133
|
+
node.children?.forEach(visit);
|
|
134
|
+
};
|
|
135
|
+
visit(scene.root);
|
|
136
|
+
}
|
|
137
|
+
for (const sc of Object.values(dev.scenarios)) {
|
|
138
|
+
addReferences(sc.initial, { workId: sc.workId, scenarioId: sc.id, layer: null, elementId: null, source: source(sc.source), evidence: 'compiled-content' });
|
|
139
|
+
for (const step of sc.steps)
|
|
140
|
+
addReferences(step, { workId: sc.workId, scenarioId: sc.id, layer: step.directorLayer, elementId: 'target' in step.action ? step.action.target : null, stepId: step.id, source: source(step.source), evidence: 'compiled-content' });
|
|
141
|
+
}
|
|
142
|
+
for (const request of new Map(requests.map(r => [r.id, r])).values()) {
|
|
143
|
+
const references = [];
|
|
144
|
+
for (const sc of Object.values(dev.scenarios)) {
|
|
145
|
+
if (nodeResourceIds(sc).has(request.id) || mediaResourceIds({ scenarios: { [sc.id]: sc } }).has(request.id))
|
|
146
|
+
references.push({ workId: sc.workId, scenarioId: sc.id, layer: null, elementId: null, source: source(request.source), evidence: 'declared-resource' });
|
|
147
|
+
for (const scene of Object.values(dev.scenes).filter(scene => scene.workId === sc.workId)) {
|
|
148
|
+
const visit = (node) => { const { children: _children, ...own } = node; if (nodeResourceIds(own).has(request.id))
|
|
149
|
+
references.push({ workId: sc.workId, scenarioId: sc.id, layer: Object.entries(dev.works[sc.workId]?.layers ?? {}).find(([, l]) => l.sceneId === scene.id)?.[0] ?? null, elementId: node.id, source: source(node.source ?? request.source), evidence: 'declared-resource' }); node.children?.forEach(visit); };
|
|
150
|
+
visit(scene.root);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
entries.set(`resource:${request.id}`, { id: request.id, path: null, kind: 'plugin-declared', mime: null, bytes: null, authorReference: references.length ? 'referenced' : 'unknown', publication: publishedResources.has(publishedByKey.get(resourceKey(request))?.id ?? '') ? 'included-in-selected-ir' : 'not-in-selected-ir', sampledVisibility: 'unknown', metadata: { plugin: request.plugin, compiler: request.compiler }, references });
|
|
154
|
+
unknowns.push({ source: source(request.source), reason: `Resource ${request.id}: compiler output, binary size and provider metadata were not evaluated (read-only report).` });
|
|
155
|
+
}
|
|
156
|
+
for (const same of byHash.values())
|
|
157
|
+
if (same.length > 1) {
|
|
158
|
+
for (const entry of same)
|
|
159
|
+
entry.metadata.contentMatch = 'ambiguous: multiple source files contain identical bytes; compiled references do not identify an exact source path';
|
|
160
|
+
}
|
|
161
|
+
for (const entry of entries.values()) {
|
|
162
|
+
entry.references.forEach(ref => { if (ref.scenarioId)
|
|
163
|
+
ref.inSelectedScope = selected.has(ref.scenarioId); });
|
|
164
|
+
entry.references = [...new Map(entry.references.map(ref => [JSON.stringify(ref), ref])).values()];
|
|
165
|
+
if (entry.authorReference === 'not-found-in-loaded-model' && unknowns.length)
|
|
166
|
+
entry.authorReference = 'unknown';
|
|
167
|
+
}
|
|
168
|
+
return { schemaVersion: 1, root, scope: { authorReferences: 'whole-loaded-project', work: opts.work ?? null, scenario: opts.scenario ?? null, publicationScenarios: Object.keys(published.scenarios), scan: scan.map(rel), sourceFiles: sourceFiles.map(rel) }, entries: [...entries.values()].sort((a, b) => a.id.localeCompare(b.id)), unknowns, limitations: [
|
|
169
|
+
'Author references cover the whole loaded project (including drafts); inSelectedScope marks contextual references inside the requested work/chapter scope. Publication inclusion uses only the selected published IR. Author references describe this module evaluation and loaded model, not all possible executions. Not found never means unused; dynamic/aliased paths, imported helper code and unexecuted branches can remain unknown.',
|
|
170
|
+
'Publication inclusion means content is present in the selected publish IR; no build was run and generated/plugin resources may still require preparation. Equal bytes can identify multiple source paths, so compiled-content references are content matches, not proof of a specific path.',
|
|
171
|
+
'Metadata currently covers only explicit captured MIME/size and declared plugin/compiler identities; author/source/year fields have no generic authoring declaration and remain absent rather than inferred.',
|
|
172
|
+
'No frames were rendered or sampled. Conditions, camera clipping, hidden layers and runtime plugin parsing mean visibility is always unknown. Metadata is reported only when declared; missing author/source/year is not inferred.',
|
|
173
|
+
] };
|
|
174
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Project, type Diagnostic, type VoiceConfig } from '@joplo-app/core';
|
|
2
|
+
export declare function audioDuration(bytes: Uint8Array): Promise<number | undefined>;
|
|
3
|
+
export declare function readAudioTiming(projectDir: string, project: Project, options?: {
|
|
4
|
+
voiceConfig?: VoiceConfig;
|
|
5
|
+
defaultProfile?: string | null;
|
|
6
|
+
home?: string;
|
|
7
|
+
}): Promise<{
|
|
8
|
+
diagnostics: Diagnostic[];
|
|
9
|
+
audioDurationFor: (url: string) => number | undefined;
|
|
10
|
+
voiceDurationFor: (stepId: string) => {
|
|
11
|
+
durationMs: number;
|
|
12
|
+
key: string;
|
|
13
|
+
} | undefined;
|
|
14
|
+
}>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Read-only audio facts. Never generate resources, call a voice provider, or serialize local paths. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Input, ALL_FORMATS, BufferSource } from 'mediabunny';
|
|
5
|
+
import { spokenLine, speakerRoleAt } from '@joplo-app/core';
|
|
6
|
+
import { joploHome } from "./home.js";
|
|
7
|
+
import { ProfileStore, VoiceCache, resolveVoices, voiceLocaleOf } from "./voice.js";
|
|
8
|
+
export async function audioDuration(bytes) {
|
|
9
|
+
const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(bytes) });
|
|
10
|
+
try {
|
|
11
|
+
const track = await input.getPrimaryAudioTrack();
|
|
12
|
+
const ms = track ? await track.computeDuration() * 1000 : 0;
|
|
13
|
+
return Number.isFinite(ms) && ms > 0 ? ms : undefined;
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
input.dispose();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export async function readAudioTiming(projectDir, project, options = {}) {
|
|
20
|
+
const audio = new Map(), voice = new Map();
|
|
21
|
+
const diagnostics = [];
|
|
22
|
+
const ids = new Set(Object.values(project.scenarios).flatMap(sc => sc.steps.flatMap(st => [st.audio, st.holdFor?.audio].filter((x) => !!x))));
|
|
23
|
+
for (const token of ids) {
|
|
24
|
+
const url = project.mediaAssets?.[token.slice(15)];
|
|
25
|
+
// localResource metadata follows the existing inspect/prepared mechanism; do not ensure or fetch here.
|
|
26
|
+
if (!url?.startsWith('data:audio/'))
|
|
27
|
+
continue;
|
|
28
|
+
try {
|
|
29
|
+
const region = project.mediaInfo?.[token.slice(15)];
|
|
30
|
+
const ms = region ? region.contentFrames / region.sourceSampleRate * 1000 : await audioDuration(Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));
|
|
31
|
+
if (ms) {
|
|
32
|
+
audio.set(url, ms);
|
|
33
|
+
audio.set(token, ms);
|
|
34
|
+
}
|
|
35
|
+
else
|
|
36
|
+
throw new Error('no finite audio duration');
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
const at = Object.values(project.scenarios).flatMap(sc => sc.steps).find(st => st.audio === token || st.holdFor?.audio === token)?.source;
|
|
40
|
+
diagnostics.push({ code: 'AUDIO_INVALID', severity: 'error', source: 'structure', at, message: 'An explicitly supplied audio asset is undecodable or has no finite positive duration; no voice provider was called' });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const cache = new VoiceCache(projectDir), store = new ProfileStore(options.home ?? joploHome());
|
|
44
|
+
const resolved = resolveVoices(options.voiceConfig ?? project.voiceConfig, cache.selection(), store, voiceLocaleOf(project, null), options.defaultProfile, cache.pins(), cache.officialCloud());
|
|
45
|
+
for (const sc of Object.values(project.scenarios))
|
|
46
|
+
for (const [i, st] of sc.steps.entries()) {
|
|
47
|
+
if (st.holdFor?.kind !== 'voice' || st.audio || st.mute)
|
|
48
|
+
continue;
|
|
49
|
+
const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
|
|
50
|
+
const plan = cache.plan({ stepId: st.id, ...line }, resolved);
|
|
51
|
+
const file = plan && cache.clipOf(plan.key);
|
|
52
|
+
if (!plan || !file)
|
|
53
|
+
continue;
|
|
54
|
+
const locale = project.i18n?.default ?? 'und';
|
|
55
|
+
const record = cache.read().clips[plan.key];
|
|
56
|
+
if (!record || record.fp !== plan.fp || record.text !== plan.text || record.locale !== locale)
|
|
57
|
+
continue;
|
|
58
|
+
try {
|
|
59
|
+
const ms = await audioDuration(await fs.readFile(path.join(cache.clipsDir, file)));
|
|
60
|
+
if (ms)
|
|
61
|
+
voice.set(st.id, { durationMs: ms, key: `${plan.key}:${locale}` });
|
|
62
|
+
}
|
|
63
|
+
catch { /* A missing/invalid cached clip is an estimate, never an implicit synthesis request. */ }
|
|
64
|
+
}
|
|
65
|
+
return { diagnostics, audioDurationFor: (url) => audio.get(url), voiceDurationFor: (stepId) => voice.get(stepId) };
|
|
66
|
+
}
|
package/dist/build.js
CHANGED
|
@@ -132,7 +132,7 @@ export async function buildSite(opts) {
|
|
|
132
132
|
});
|
|
133
133
|
let compiled;
|
|
134
134
|
try {
|
|
135
|
-
compiled = await compileProject(loader, projectDir, opts.review === true ? 'review' : 'publish');
|
|
135
|
+
compiled = await compileProject(loader, projectDir, opts.review === true ? 'review' : 'publish', { voiceDefault: opts.voiceDefault });
|
|
136
136
|
// 发布编译已跳过草稿与未选功能;范围的公开校验需要原始条目,避免误报不存在。
|
|
137
137
|
if (opts.scope?.entryIds?.length || opts.scope?.scenarios?.length && compiled.diagnostics.some(d => d.code === 'WORK_DRAFT_SKIPPED')) {
|
|
138
138
|
const dev = await compileProject(loader, projectDir, 'dev');
|
|
@@ -179,13 +179,26 @@ export async function buildSite(opts) {
|
|
|
179
179
|
if (compiled.resources) {
|
|
180
180
|
const resources = await inlineResources(project, compiled.resources.requests, compiled.resources.host);
|
|
181
181
|
if (Object.keys(resources.assets).length)
|
|
182
|
-
project = { ...project, mediaAssets: resources.assets, mediaInfo: resources.audioInfo };
|
|
182
|
+
project = { ...project, mediaAssets: { ...project.mediaAssets, ...resources.assets }, mediaInfo: { ...project.mediaInfo, ...resources.audioInfo } };
|
|
183
183
|
compiled.diagnostics.push(...resources.diagnostics);
|
|
184
184
|
mediaCredits = resources.credits;
|
|
185
185
|
mediaLicenses = resources.licenses;
|
|
186
186
|
if (resources.diagnostics.some(d => d.severity === 'error'))
|
|
187
187
|
throw new JoploError('EXPORT_FAILED', 'Audio attribution is incomplete; no site was published', { diagnostics: resources.diagnostics });
|
|
188
188
|
}
|
|
189
|
+
// Explicit speech must be deliverable in this selected publication. Timing-only
|
|
190
|
+
// holdFor.audio references may remain estimated and are not playback requirements.
|
|
191
|
+
const missingSpeech = Object.values(project.scenarios).flatMap(sc => sc.steps.flatMap(step => {
|
|
192
|
+
if (!step.audio)
|
|
193
|
+
return [];
|
|
194
|
+
const asset = project.mediaAssets?.[step.audio.slice('joplo-resource:'.length)];
|
|
195
|
+
if (typeof asset === 'string' && /^data:audio\/[^;,]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(asset))
|
|
196
|
+
return [];
|
|
197
|
+
return [{ severity: 'error', source: 'structure', code: asset === undefined ? 'AUDIO_ASSET_MISSING' : 'AUDIO_ASSET_INVALID',
|
|
198
|
+
at: step.source, message: `${step.id}: explicit narration audio is missing or is not a prepared audio asset. Prepare or repair it before building; no voice provider was called.` }];
|
|
199
|
+
}));
|
|
200
|
+
if (missingSpeech.length)
|
|
201
|
+
throw new JoploError('EXPORT_FAILED', 'Explicit narration audio is unavailable; no site was published', { diagnostics: missingSpeech });
|
|
189
202
|
binaryAssets(project, { diagnostics: compiled.diagnostics });
|
|
190
203
|
const inline = publishPayload(project, compiled.home);
|
|
191
204
|
if (scope)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { CDPSession, Page } from 'playwright-core';
|
|
2
|
+
import type { ExportCrop } from './contract.js';
|
|
3
|
+
/** Numeric crop coordinates are relative to the chosen export root, in CSS pixels. */
|
|
4
|
+
export declare function capture(page: Page, root: string, crop: ExportCrop | undefined, type?: 'png' | 'jpeg', quality?: number, session?: CDPSession, fixedAtMs?: number): Promise<Buffer<ArrayBufferLike>>;
|
|
5
|
+
export declare function geometryQuery(o: {
|
|
6
|
+
logicalViewport?: {
|
|
7
|
+
width: number;
|
|
8
|
+
height: number;
|
|
9
|
+
};
|
|
10
|
+
noFrame?: boolean;
|
|
11
|
+
}): {
|
|
12
|
+
noframe?: string | undefined;
|
|
13
|
+
vw?: string | undefined;
|
|
14
|
+
vh?: string | undefined;
|
|
15
|
+
};
|
package/dist/capture.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { JoploError } from '@joplo-app/core';
|
|
2
|
+
const fixedFrames = new WeakMap();
|
|
3
|
+
/** Numeric crop coordinates are relative to the chosen export root, in CSS pixels. */
|
|
4
|
+
export async function capture(page, root, crop, type = 'png', quality, session, fixedAtMs) {
|
|
5
|
+
const target = page.locator(root);
|
|
6
|
+
const base = await target.boundingBox();
|
|
7
|
+
if (!base)
|
|
8
|
+
throw new JoploError('RENDER_FAILED', `Export root is not visible: ${root}`);
|
|
9
|
+
// Locator screenshots wait for two stable animation frames; engine-time sampling already
|
|
10
|
+
// settled React and must capture intentional motion immediately, without that wall-clock wait.
|
|
11
|
+
const screenshot = async (clip) => {
|
|
12
|
+
if (fixedAtMs !== undefined) {
|
|
13
|
+
const previous = fixedFrames.get(page);
|
|
14
|
+
if (previous && (Math.abs(previous.width - clip.width) > .01 || Math.abs(previous.height - clip.height) > .01))
|
|
15
|
+
throw new JoploError('RENDER_FAILED', `Crop dimensions changed at ${fixedAtMs} ms: expected ${previous.width}x${previous.height}, got ${clip.width}x${clip.height}; use a fixed-size frame or numeric crop`);
|
|
16
|
+
fixedFrames.set(page, { width: clip.width, height: clip.height });
|
|
17
|
+
}
|
|
18
|
+
if (session) {
|
|
19
|
+
const result = await session.send('Page.captureScreenshot', { format: type, ...(quality ? { quality } : {}), clip: { ...clip, scale: 1 }, captureBeyondViewport: true, optimizeForSpeed: true });
|
|
20
|
+
return Buffer.from(result.data, 'base64');
|
|
21
|
+
}
|
|
22
|
+
return page.screenshot({ type, clip, ...(quality ? { quality } : {}) });
|
|
23
|
+
};
|
|
24
|
+
if (!crop)
|
|
25
|
+
return screenshot(base);
|
|
26
|
+
let rect;
|
|
27
|
+
if (typeof crop === 'string') {
|
|
28
|
+
try {
|
|
29
|
+
const selected = page.locator(crop);
|
|
30
|
+
if (await selected.count() !== 1)
|
|
31
|
+
throw new Error('selector must match exactly one element');
|
|
32
|
+
rect = await selected.boundingBox();
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
throw new JoploError('USAGE', `Invalid crop selector ${JSON.stringify(crop)}: ${e instanceof Error ? e.message : String(e)}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else
|
|
39
|
+
rect = { ...crop, x: base.x + crop.x, y: base.y + crop.y };
|
|
40
|
+
if (!rect || ![rect.x, rect.y, rect.width, rect.height].every(Number.isFinite) || rect.width <= 0 || rect.height <= 0 || rect.x < base.x || rect.y < base.y || rect.x + rect.width > base.x + base.width + 0.5 || rect.y + rect.height > base.y + base.height + 0.5)
|
|
41
|
+
throw new JoploError('USAGE', 'Crop must be a visible positive rectangle fully inside the export canvas');
|
|
42
|
+
return screenshot(rect);
|
|
43
|
+
}
|
|
44
|
+
export function geometryQuery(o) {
|
|
45
|
+
const v = o.logicalViewport;
|
|
46
|
+
if (v && (![v.width, v.height].every(n => Number.isInteger(n) && n > 0 && n <= 8192)))
|
|
47
|
+
throw new JoploError('USAGE', 'Logical viewport dimensions must be integers from 1 to 8192');
|
|
48
|
+
return { ...(v ? { vw: String(v.width), vh: String(v.height) } : {}), ...(o.noFrame ? { noframe: '1' } : {}) };
|
|
49
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Conservative content identity: safe false invalidations are preferable to reusing foreign pixels. */
|
|
2
|
+
export declare function contentIdentity(roots: readonly string[], excluded?: readonly string[]): string;
|
|
3
|
+
export declare function exportRuntimeRoots(projectDir: string, plugins: Record<string, string>): string[];
|
|
4
|
+
export declare function checkpointCommitsMatch(saved: readonly {
|
|
5
|
+
stepId: string;
|
|
6
|
+
commitMs: number;
|
|
7
|
+
}[], current: readonly {
|
|
8
|
+
stepId: string;
|
|
9
|
+
commitMs: number;
|
|
10
|
+
}[], toleranceMs?: number): boolean;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { locateWebAssets } from "./web-assets.js";
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
/** Conservative content identity: safe false invalidations are preferable to reusing foreign pixels. */
|
|
8
|
+
export function contentIdentity(roots, excluded = []) {
|
|
9
|
+
const hash = createHash('sha256'), visited = new Set();
|
|
10
|
+
const omit = excluded.map(p => path.resolve(p));
|
|
11
|
+
const visit = (file) => {
|
|
12
|
+
const abs = path.resolve(file);
|
|
13
|
+
if (omit.some(p => abs === p || abs.startsWith(p + path.sep)))
|
|
14
|
+
return;
|
|
15
|
+
let real;
|
|
16
|
+
try {
|
|
17
|
+
real = fs.realpathSync(abs);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
hash.update(`missing:${abs}\0`);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (visited.has(real))
|
|
24
|
+
return;
|
|
25
|
+
visited.add(real);
|
|
26
|
+
const stat = fs.statSync(real);
|
|
27
|
+
if (stat.isDirectory()) {
|
|
28
|
+
for (const name of fs.readdirSync(real).sort()) {
|
|
29
|
+
if (['node_modules', '.git'].includes(name))
|
|
30
|
+
continue;
|
|
31
|
+
// Only the managed resource host owns these exact temporary naming schemes.
|
|
32
|
+
const resourceCache = real.split(path.sep).slice(-2).join('/') === '.joplo/resources';
|
|
33
|
+
if (resourceCache && (/^(inspect|job)-[A-Za-z0-9]{6}$/.test(name) || /^[0-9a-f]{64}\.(?:mjs|json|info\.json)(?:\.[0-9a-f-]{36}\.tmp|\.lock)$/.test(name)))
|
|
34
|
+
continue;
|
|
35
|
+
if (name === '.joplo') {
|
|
36
|
+
for (const cache of ['voice', 'binary', 'resources'])
|
|
37
|
+
visit(path.join(real, name, cache));
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
visit(path.join(real, name));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else if (stat.isFile()) {
|
|
44
|
+
hash.update(real + '\0');
|
|
45
|
+
hash.update(fs.readFileSync(real));
|
|
46
|
+
hash.update('\0');
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
roots.forEach(visit);
|
|
50
|
+
return hash.digest('hex');
|
|
51
|
+
}
|
|
52
|
+
export function exportRuntimeRoots(projectDir, plugins) {
|
|
53
|
+
const roots = [], web = locateWebAssets();
|
|
54
|
+
for (const name of ['core', 'kit', 'server']) {
|
|
55
|
+
const root = path.dirname(fs.realpathSync(require.resolve(`@joplo-app/${name}/package.json`)));
|
|
56
|
+
roots.push(path.join(root, 'package.json'), path.join(root, import.meta.filename.endsWith('.ts') ? 'src' : 'dist'));
|
|
57
|
+
}
|
|
58
|
+
roots.push(path.join(web.webDir, 'package.json'), web.mode === 'source' ? path.join(web.webDir, 'src') : path.join(web.webDir, 'dist'));
|
|
59
|
+
for (const url of Object.values(plugins))
|
|
60
|
+
if (url.startsWith('/@fs/')) {
|
|
61
|
+
const file = decodeURIComponent(url.slice('/@fs'.length));
|
|
62
|
+
if (file.startsWith(projectDir + path.sep)) {
|
|
63
|
+
roots.push(file);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
let root = path.dirname(file);
|
|
67
|
+
while (!fs.existsSync(path.join(root, 'package.json')) && path.dirname(root) !== root)
|
|
68
|
+
root = path.dirname(root);
|
|
69
|
+
roots.push(fs.existsSync(path.join(root, 'package.json')) ? root : file);
|
|
70
|
+
}
|
|
71
|
+
return roots;
|
|
72
|
+
}
|
|
73
|
+
export function checkpointCommitsMatch(saved, current, toleranceMs = 50) {
|
|
74
|
+
return saved.length === current.length && current.every((c, i) => c.stepId === saved[i].stepId && Math.abs(c.commitMs - saved[i].commitMs) <= toleranceMs);
|
|
75
|
+
}
|
package/dist/contract.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export type DevOptions = {
|
|
|
18
18
|
};
|
|
19
19
|
/** 单进程:同一个 JOPLO_HOME 下只有一个看板进程,同时服务多个项目(编译、热更新、选中、导出)。 */
|
|
20
20
|
/**
|
|
21
|
-
* url:项目在看板中的链接。attached = true
|
|
21
|
+
* url:项目在看板中的链接。attached = true 表示本机已有存活的看板,项目加入该看板并等待初次编译完成(没有启动第二个进程,close 不做事)。
|
|
22
22
|
*/
|
|
23
23
|
export type DevHandle = {
|
|
24
24
|
url: string;
|
|
@@ -88,7 +88,23 @@ export type BuildResult = {
|
|
|
88
88
|
scope?: ScopeInfo;
|
|
89
89
|
};
|
|
90
90
|
export declare function buildSite(opts: BuildOptions): Promise<BuildResult>;
|
|
91
|
+
export type ExportCrop = string | {
|
|
92
|
+
x: number;
|
|
93
|
+
y: number;
|
|
94
|
+
width: number;
|
|
95
|
+
height: number;
|
|
96
|
+
};
|
|
91
97
|
export type RenderOptions = {
|
|
98
|
+
auditLayout?: import('./layout-audit.js').LayoutAuditOptions | boolean;
|
|
99
|
+
/** CSS 选择器或相对输出画布的 CSS 像素矩形。所有像素诊断在裁切后计算。 */
|
|
100
|
+
crop?: ExportCrop;
|
|
101
|
+
/** 直接决定布局、镜头和交互坐标的逻辑舞台尺寸。 */
|
|
102
|
+
logicalViewport?: {
|
|
103
|
+
width: number;
|
|
104
|
+
height: number;
|
|
105
|
+
};
|
|
106
|
+
/** 不绘制设备外框。 */
|
|
107
|
+
noFrame?: boolean;
|
|
92
108
|
projectDir: string;
|
|
93
109
|
scenarioId: string;
|
|
94
110
|
/** 渲染该步骤执行之后的状态;缺省为初始状态。 */
|
|
@@ -129,6 +145,7 @@ export type RenderedElement = {
|
|
|
129
145
|
};
|
|
130
146
|
};
|
|
131
147
|
export type RenderResult = {
|
|
148
|
+
audit?: import('./layout-audit.js').LayoutAuditResult;
|
|
132
149
|
path: string;
|
|
133
150
|
sceneId: string;
|
|
134
151
|
position: number;
|
|
@@ -153,6 +170,14 @@ export declare function renderSheet(opts: SheetOptions): Promise<SheetResult>;
|
|
|
153
170
|
* 每个场景一页(多页时 out 之后加 -1、-2…);cuts = 单帧整屏突变,stills = 至少 stillMs 没有可见变化,boundaries = 每次提交一步前后的最大相邻帧差。
|
|
154
171
|
*/
|
|
155
172
|
export type FilmOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope' | 'scale'> & {
|
|
173
|
+
width?: number;
|
|
174
|
+
height?: number;
|
|
175
|
+
timeline?: string;
|
|
176
|
+
checkpoint?: string;
|
|
177
|
+
resume?: boolean;
|
|
178
|
+
chapterTimeoutMs?: number;
|
|
179
|
+
hide?: ('cover' | 'cursor' | 'title' | 'subtitles')[];
|
|
180
|
+
voice?: 'real' | 'estimate' | 'off';
|
|
156
181
|
chain?: boolean;
|
|
157
182
|
every?: number;
|
|
158
183
|
sampleMs?: number;
|
|
@@ -183,6 +208,19 @@ export type FilmBoundary = {
|
|
|
183
208
|
maxChanged: number;
|
|
184
209
|
};
|
|
185
210
|
export type FilmResult = {
|
|
211
|
+
audit?: import('./layout-audit.js').LayoutAuditResult;
|
|
212
|
+
measurement?: {
|
|
213
|
+
baselineRssBytes: number;
|
|
214
|
+
endRssBytes: number;
|
|
215
|
+
memoryScope: 'node-process-lifetime';
|
|
216
|
+
rssSamples: {
|
|
217
|
+
engineMs: number;
|
|
218
|
+
rssBytes: number;
|
|
219
|
+
}[];
|
|
220
|
+
wallMs: number;
|
|
221
|
+
peakRssBytes: number;
|
|
222
|
+
resumedSamples: number;
|
|
223
|
+
};
|
|
186
224
|
path: string;
|
|
187
225
|
files: string[];
|
|
188
226
|
durationMs: number;
|
|
@@ -198,6 +236,9 @@ export type FilmResult = {
|
|
|
198
236
|
export declare function renderFilm(opts: FilmOptions): Promise<FilmResult>;
|
|
199
237
|
/** 视频(`joplo render --video`):与看板导出同一个录制器(真实时间,webm)。 */
|
|
200
238
|
export type VideoOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope' | 'scale'> & {
|
|
239
|
+
timeline?: string;
|
|
240
|
+
/** false records no narration or background audio while retaining playback timing. */
|
|
241
|
+
audio?: boolean;
|
|
201
242
|
chain?: boolean;
|
|
202
243
|
/**
|
|
203
244
|
* 输出分辨率(#55,两个都给或都不给):舞台原样居中放进这个画幅,四周是主题背景色,按比例放大或缩小保持清晰
|
|
@@ -213,6 +254,11 @@ export type VideoOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope' |
|
|
|
213
254
|
srt?: string;
|
|
214
255
|
};
|
|
215
256
|
export type VideoResult = {
|
|
257
|
+
sync?: {
|
|
258
|
+
offsetMs: number;
|
|
259
|
+
videoEndMs: number;
|
|
260
|
+
audioEndMs: number;
|
|
261
|
+
};
|
|
216
262
|
path: string;
|
|
217
263
|
durationMs: number;
|
|
218
264
|
/** 视频分辨率。 */
|
|
@@ -231,3 +277,19 @@ export type VideoResult = {
|
|
|
231
277
|
};
|
|
232
278
|
};
|
|
233
279
|
export declare function renderVideo(opts: VideoOptions): Promise<VideoResult>;
|
|
280
|
+
/** JPEG frame files named by engine milliseconds, plus a versioned actual-playback timeline. */
|
|
281
|
+
export type FramesOptions = Omit<FilmOptions, 'out'> & {
|
|
282
|
+
out?: string;
|
|
283
|
+
} & {
|
|
284
|
+
framesOut: string;
|
|
285
|
+
fps?: number;
|
|
286
|
+
scale?: number;
|
|
287
|
+
};
|
|
288
|
+
export declare function renderFrames(opts: FramesOptions): Promise<{
|
|
289
|
+
directory: string;
|
|
290
|
+
timeline: string;
|
|
291
|
+
fps: number;
|
|
292
|
+
frames: number;
|
|
293
|
+
durationMs: number;
|
|
294
|
+
toleranceMs: number;
|
|
295
|
+
}>;
|