@bitmagic/cli 0.1.60-dev.1 → 0.1.60-dev.3
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/README.md +49 -0
- package/dist/cli.d.ts +36 -0
- package/dist/cli.js +2 -0
- package/dist/cli.js.map +1 -1
- package/dist/commands/cover.js +2 -1
- package/dist/commands/cover.js.map +1 -1
- package/dist/commands/forge.js +15 -25
- package/dist/commands/forge.js.map +1 -1
- package/dist/commands/import.d.ts +75 -0
- package/dist/commands/import.js +338 -0
- package/dist/commands/import.js.map +1 -0
- package/dist/commands/init.js +1 -45
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/verify.js +17 -29
- package/dist/commands/verify.js.map +1 -1
- package/dist/editor/motion-panel.d.ts +3 -3
- package/dist/editor/motion-panel.js +50 -5
- package/dist/editor/motion-panel.js.map +1 -1
- package/dist/local-port.d.ts +23 -4
- package/dist/local-port.js +44 -13
- package/dist/local-port.js.map +1 -1
- package/dist/scaffold/export-zip.d.ts +48 -0
- package/dist/scaffold/export-zip.js +167 -0
- package/dist/scaffold/export-zip.js.map +1 -0
- package/dist/scaffold/import-project.d.ts +34 -0
- package/dist/scaffold/import-project.js +108 -0
- package/dist/scaffold/import-project.js.map +1 -0
- package/dist/scaffold/project-files.js +9 -1
- package/dist/scaffold/project-files.js.map +1 -1
- package/dist/scaffold/project.d.ts +34 -0
- package/dist/scaffold/project.js +53 -22
- package/dist/scaffold/project.js.map +1 -1
- package/dist/scaffold/rehost-assets.d.ts +63 -0
- package/dist/scaffold/rehost-assets.js +270 -0
- package/dist/scaffold/rehost-assets.js.map +1 -0
- package/dist/scaffold/scaffold-run.d.ts +17 -0
- package/dist/scaffold/scaffold-run.js +57 -0
- package/dist/scaffold/scaffold-run.js.map +1 -0
- package/dist/theme/hud-theme-catalog.d.ts +0 -1
- package/dist/theme/hud-theme-catalog.js +9 -6
- package/dist/theme/hud-theme-catalog.js.map +1 -1
- package/dist/theme/theme-io.js +2 -1
- package/dist/theme/theme-io.js.map +1 -1
- package/dist/verify/browser.js +87 -18
- package/dist/verify/browser.js.map +1 -1
- package/dist/verify/classify.d.ts +12 -0
- package/dist/verify/classify.js +24 -3
- package/dist/verify/classify.js.map +1 -1
- package/dist/verify/start.d.ts +23 -3
- package/dist/verify/start.js +13 -1
- package/dist/verify/start.js.map +1 -1
- package/dist/verify/wait-for-server.d.ts +11 -0
- package/dist/verify/wait-for-server.js +29 -1
- package/dist/verify/wait-for-server.js.map +1 -1
- package/package.json +7 -5
|
@@ -11,10 +11,10 @@
|
|
|
11
11
|
* Same template-literal rules as the host: **no backticks**, no regex literals starting with a
|
|
12
12
|
* dot-escape, every colour a `--bm-*` token — `shell-page.test.ts` enforces all three.
|
|
13
13
|
*/
|
|
14
|
-
export declare const MOTION_PANEL_CSS = "\n /* Level with the other dialogs: each opens from its own control and they never stack. */\n #motion-overlay { z-index: 10; }\n #motion-dialog { width: min(520px, 94vw); padding: 20px; }\n #motion-dialog .bm-label { display: block; margin: 14px 0 6px; }\n #motion-stage { position: relative; aspect-ratio: 16 / 9; border-radius: 8px; overflow: hidden;\n background: var(--bm-surface-alt); border: 1px solid var(--bm-border-muted); }\n #motion-preview { width: 100%; height: 100%; object-fit: contain; background: #000000; display: block; }\n #motion-preview.mirror { transform: scaleX(-1); }\n #motion-timer { position: absolute; top: 10px; left: 10px; display: none; padding: 3px 10px;\n border-radius: 999px; background: var(--bm-pink); color: #ffffff; font-size: 12px;\n font-family: var(--bm-font-mono); }\n #motion-timer.show { display: inline-block; }\n #motion-countdown { position: absolute; inset: 0; display: none; flex-direction: column; align-items: center;\n justify-content: center; gap: 6px; background: var(--bm-scrim); pointer-events: none; }\n #motion-countdown.show { display: flex; }\n #motion-countdown-number { font-size: 96px; font-weight: 700; line-height: 1; color: #ffffff; }\n #motion-countdown-hint { font-size: 13px; color: #ffffff; opacity: 0.85; }\n #motion-hint { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;\n text-align: center; padding: 20px; font-size: 13px; color: var(--bm-text-muted); }\n #motion-hint.hidden { display: none; }\n #motion-trim { display: none; margin-top: 10px; }\n #motion-trim.show { display: block; }\n #motion-trimbar { position: relative; height: 14px; border-radius: 7px; background: var(--bm-surface-alt);\n touch-action: none; }\n #motion-trim-kept { position: absolute; top: 0; bottom: 0; border-radius: 7px; background: var(--bm-aqua); }\n #motion-trim-playhead { position: absolute; top: 0; bottom: 0; width: 2px; background: var(--bm-pink);\n pointer-events: none; }\n .motion-trim-handle { position: absolute; top: 50%; width: 14px; height: 22px;\n transform: translate(-50%, -50%); border-radius: 5px; background: var(--bm-text);\n cursor: ew-resize; touch-action: none; }\n #motion-trim-row { display: flex; align-items: center; justify-content: space-between; gap: 8px;\n margin-top: 6px; min-height: 24px; }\n #motion-trim-note { font-size: 11px; color: var(--bm-text-muted); }\n #motion-sources { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }\n #motion-file { display: none; }\n #motion-guidance { margin: 10px 0 0; font-size: 12px; color: var(--bm-text-muted); }\n #motion-options { display: grid; grid-template-columns: 1fr auto; gap: 10px 12px; align-items: end; }\n #motion-name, #motion-slot { width: 100%; }\n .motion-check { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 13px; cursor: pointer; }\n .motion-check input { accent-color: var(--bm-aqua); }\n #motion-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }\n #motion-note { display: none; margin-top: 12px; padding: 12px; border-radius: 6px; font-size: 12px;\n background: var(--bm-surface-alt); border: 1px solid var(--bm-border-muted);\n color: var(--bm-text-muted); }\n #motion-note.show { display: block; }\n #motion-note code { display: block; margin-top: 6px; color: var(--bm-aqua);\n font-family: var(--bm-font-mono); word-break: break-all; }\n";
|
|
15
|
-
export declare const MOTION_PANEL_HTML = " <div id=\"motion-overlay\" class=\"bm-overlay\">\n <div id=\"motion-dialog\" class=\"bm-dialog\">\n <h2>Record a motion</h2>\n <p>Perform the move on camera, or pick a video. Uthana turns it into an animation clip for\n this game's characters. Costs sparks.</p>\n <div id=\"motion-stage\">\n <video id=\"motion-preview\" playsinline muted></video>\n <span id=\"motion-timer\">0:00</span>\n <div id=\"motion-countdown\"><span id=\"motion-countdown-number\">3</span><span id=\"motion-countdown-hint\">Get in frame</span></div>\n <div id=\"motion-hint\">Whole body in frame, one person, plain background, good light.\n 2–60 seconds.</div>\n </div>\n <div id=\"motion-trim\">\n <div id=\"motion-trimbar\" title=\"Drag the handles to choose what the animation is made from\">\n <div id=\"motion-trim-kept\"></div>\n <div id=\"motion-trim-playhead\"></div>\n <div id=\"motion-trim-start\" class=\"motion-trim-handle\"></div>\n <div id=\"motion-trim-end\" class=\"motion-trim-handle\"></div>\n </div>\n <div id=\"motion-trim-row\">\n <span id=\"motion-trim-note\"></span>\n <button id=\"motion-trim-full\" class=\"bm-pill bm-pill--ghost\" type=\"button\" hidden>Use full clip</button>\n </div>\n </div>\n <div id=\"motion-sources\">\n <button id=\"motion-record\" class=\"bm-pill bm-pill--primary\" type=\"button\">Record with webcam</button>\n <button id=\"motion-stop\" class=\"bm-pill\" type=\"button\" hidden>Stop</button>\n <button id=\"motion-pick\" class=\"bm-pill\" type=\"button\">Choose a video…</button>\n <button id=\"motion-retake\" class=\"bm-pill bm-pill--ghost\" type=\"button\" hidden>Start over</button>\n <input id=\"motion-file\" type=\"file\" accept=\".mp4,.mov,.avi,.webm,video/mp4,video/quicktime,video/webm\">\n </div>\n <p id=\"motion-guidance\"></p>\n <div id=\"motion-options\">\n <div>\n <label class=\"bm-label\" for=\"motion-name\">Name</label>\n <input id=\"motion-name\" class=\"bm-input\" type=\"text\" placeholder=\"e.g. Victory dance\" maxlength=\"80\">\n </div>\n <div>\n <label class=\"bm-label\" for=\"motion-slot\">Use as</label>\n <select id=\"motion-slot\" class=\"bm-input\">\n <option value=\"\">One-shot clip</option>\n <option value=\"idle\">Idle</option>\n <option value=\"walk\">Walk</option>\n <option value=\"run\">Run</option>\n </select>\n </div>\n </div>\n <label class=\"motion-check\"><input id=\"motion-loop\" type=\"checkbox\"> Loops</label>\n <div id=\"motion-actions\">\n <button id=\"motion-close\" class=\"bm-pill bm-pill--ghost\" type=\"button\">Close</button>\n <button id=\"motion-submit\" class=\"bm-pill bm-pill--primary\" type=\"button\" disabled>Make the animation</button>\n </div>\n <div id=\"motion-note\">\n <span id=\"motion-note-text\"></span>\n <code id=\"motion-command\"></code>\n </div>\n </div>\n </div>\n";
|
|
14
|
+
export declare const MOTION_PANEL_CSS = "\n /* Level with the other dialogs: each opens from its own control and they never stack. */\n #motion-overlay { z-index: 10; }\n #motion-dialog { width: min(520px, 94vw); padding: 20px; }\n #motion-dialog .bm-label { display: block; margin: 14px 0 6px; }\n #motion-stage { position: relative; aspect-ratio: 16 / 9; border-radius: 8px; overflow: hidden;\n background: var(--bm-surface-alt); border: 1px solid var(--bm-border-muted); }\n #motion-preview { width: 100%; height: 100%; object-fit: contain; background: #000000; display: block; }\n #motion-preview.mirror { transform: scaleX(-1); }\n #motion-timer { position: absolute; top: 10px; left: 10px; display: none; padding: 3px 10px;\n border-radius: 999px; background: var(--bm-pink); color: #ffffff; font-size: 12px;\n font-family: var(--bm-font-mono); }\n #motion-timer.show { display: inline-block; }\n #motion-countdown { position: absolute; inset: 0; display: none; flex-direction: column; align-items: center;\n justify-content: center; gap: 6px; background: var(--bm-scrim); pointer-events: none; }\n #motion-countdown.show { display: flex; }\n #motion-countdown-number { font-size: 96px; font-weight: 700; line-height: 1; color: #ffffff; }\n #motion-countdown-hint { font-size: 13px; color: #ffffff; opacity: 0.85; }\n #motion-hint { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;\n text-align: center; padding: 20px; font-size: 13px; color: var(--bm-text-muted); }\n #motion-hint.hidden { display: none; }\n #motion-trim { display: none; margin-top: 10px; }\n #motion-trim.show { display: block; }\n #motion-trimbar { position: relative; height: 14px; border-radius: 7px; background: var(--bm-surface-alt);\n touch-action: none; }\n #motion-trim-kept { position: absolute; top: 0; bottom: 0; border-radius: 7px; background: var(--bm-aqua); }\n #motion-trim-playhead { position: absolute; top: 0; bottom: 0; width: 2px; background: var(--bm-pink);\n pointer-events: none; }\n .motion-trim-handle { position: absolute; top: 50%; width: 14px; height: 22px;\n transform: translate(-50%, -50%); border-radius: 5px; background: var(--bm-text);\n cursor: ew-resize; touch-action: none; }\n #motion-trim-row { display: flex; align-items: center; justify-content: space-between; gap: 8px;\n margin-top: 6px; min-height: 24px; }\n #motion-trim-note { font-size: 11px; color: var(--bm-text-muted); }\n #motion-trim-actions { display: flex; gap: 6px; }\n #motion-sources { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }\n #motion-file { display: none; }\n #motion-guidance { margin: 10px 0 0; font-size: 12px; color: var(--bm-text-muted); }\n #motion-options { display: grid; grid-template-columns: 1fr auto; gap: 10px 12px; align-items: end; }\n #motion-name, #motion-slot { width: 100%; }\n .motion-check { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 13px; cursor: pointer; }\n .motion-check input { accent-color: var(--bm-aqua); }\n #motion-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }\n #motion-note { display: none; margin-top: 12px; padding: 12px; border-radius: 6px; font-size: 12px;\n background: var(--bm-surface-alt); border: 1px solid var(--bm-border-muted);\n color: var(--bm-text-muted); }\n #motion-note.show { display: block; }\n #motion-note code { display: block; margin-top: 6px; color: var(--bm-aqua);\n font-family: var(--bm-font-mono); word-break: break-all; }\n";
|
|
15
|
+
export declare const MOTION_PANEL_HTML = " <div id=\"motion-overlay\" class=\"bm-overlay\">\n <div id=\"motion-dialog\" class=\"bm-dialog\">\n <h2>Record a motion</h2>\n <p>Perform the move on camera, or pick a video. Uthana turns it into an animation clip for\n this game's characters. Costs sparks.</p>\n <div id=\"motion-stage\">\n <video id=\"motion-preview\" playsinline muted></video>\n <span id=\"motion-timer\">0:00</span>\n <div id=\"motion-countdown\"><span id=\"motion-countdown-number\">3</span><span id=\"motion-countdown-hint\">Get in frame</span></div>\n <div id=\"motion-hint\">Whole body in frame, one person, plain background, good light.\n 2–60 seconds.</div>\n </div>\n <div id=\"motion-trim\">\n <div id=\"motion-trimbar\" title=\"Drag the handles to choose what the animation is made from\">\n <div id=\"motion-trim-kept\"></div>\n <div id=\"motion-trim-playhead\"></div>\n <div id=\"motion-trim-start\" class=\"motion-trim-handle\"></div>\n <div id=\"motion-trim-end\" class=\"motion-trim-handle\"></div>\n </div>\n <div id=\"motion-trim-row\">\n <span id=\"motion-trim-note\"></span>\n <span id=\"motion-trim-actions\">\n <button id=\"motion-trim-preview\" class=\"bm-pill\" type=\"button\">▶ Play</button>\n <button id=\"motion-trim-full\" class=\"bm-pill bm-pill--ghost\" type=\"button\" hidden>Use full clip</button>\n </span>\n </div>\n </div>\n <div id=\"motion-sources\">\n <button id=\"motion-record\" class=\"bm-pill bm-pill--primary\" type=\"button\">Record with webcam</button>\n <button id=\"motion-stop\" class=\"bm-pill\" type=\"button\" hidden>Stop</button>\n <button id=\"motion-pick\" class=\"bm-pill\" type=\"button\">Choose a video…</button>\n <button id=\"motion-retake\" class=\"bm-pill bm-pill--ghost\" type=\"button\" hidden>Start over</button>\n <input id=\"motion-file\" type=\"file\" accept=\".mp4,.mov,.avi,.webm,video/mp4,video/quicktime,video/webm\">\n </div>\n <p id=\"motion-guidance\"></p>\n <div id=\"motion-options\">\n <div>\n <label class=\"bm-label\" for=\"motion-name\">Name</label>\n <input id=\"motion-name\" class=\"bm-input\" type=\"text\" placeholder=\"e.g. Victory dance\" maxlength=\"80\">\n </div>\n <div>\n <label class=\"bm-label\" for=\"motion-slot\">Use as</label>\n <select id=\"motion-slot\" class=\"bm-input\">\n <option value=\"\">One-shot clip</option>\n <option value=\"idle\">Idle</option>\n <option value=\"walk\">Walk</option>\n <option value=\"run\">Run</option>\n </select>\n </div>\n </div>\n <label class=\"motion-check\"><input id=\"motion-loop\" type=\"checkbox\"> Loops</label>\n <div id=\"motion-actions\">\n <button id=\"motion-close\" class=\"bm-pill bm-pill--ghost\" type=\"button\">Close</button>\n <button id=\"motion-submit\" class=\"bm-pill bm-pill--primary\" type=\"button\" disabled>Make the animation</button>\n </div>\n <div id=\"motion-note\">\n <span id=\"motion-note-text\"></span>\n <code id=\"motion-command\"></code>\n </div>\n </div>\n </div>\n";
|
|
16
16
|
/**
|
|
17
17
|
* Behaviour, spliced into the shell's IIFE. Runs after the shell's own helpers are defined, so
|
|
18
18
|
* `setStatus`, `start`, `autoReload`, `banner` and `frame` are in scope.
|
|
19
19
|
*/
|
|
20
|
-
export declare const MOTION_PANEL_JS = "\n // ---- Record motion: webcam or file -> Uthana video-to-motion -> assets[] ----------------------\n var motionToggle = document.getElementById('motion');\n var motionOverlay = document.getElementById('motion-overlay');\n var motionPreview = document.getElementById('motion-preview');\n var motionTimer = document.getElementById('motion-timer');\n var motionCountdown = document.getElementById('motion-countdown');\n var motionCountdownNumber = document.getElementById('motion-countdown-number');\n /** Seconds shown on the live preview before the recorder starts, so the first frames are the pose. */\n var MOTION_COUNTDOWN_S = 3;\n var motionCountdownToken = 0;\n var motionHint = document.getElementById('motion-hint');\n var motionRecordBtn = document.getElementById('motion-record');\n var motionStopBtn = document.getElementById('motion-stop');\n var motionPickBtn = document.getElementById('motion-pick');\n var motionRetakeBtn = document.getElementById('motion-retake');\n var motionFile = document.getElementById('motion-file');\n var motionGuidance = document.getElementById('motion-guidance');\n var motionName = document.getElementById('motion-name');\n var motionSlot = document.getElementById('motion-slot');\n var motionLoop = document.getElementById('motion-loop');\n var motionSubmit = document.getElementById('motion-submit');\n var motionNote = document.getElementById('motion-note');\n var MOTION_MIN_S = 2;\n var MOTION_MAX_S = 60;\n var MOTION_MAX_BYTES = 200 * 1024 * 1024;\n var motionBlob = null;\n // Whether motionBlob came from the webcam recorder (auto-trim applies) or a picked file (it does not).\n var motionFromRecording = false;\n var motionSeconds = 0;\n var motionStream = null;\n var motionRecorder = null;\n var motionChunks = [];\n var motionTickTimer = null;\n var motionStartedAt = 0;\n var motionObjectUrl = null;\n // ---- Trim window: seeded by the sidecar's trim analysis, adjusted on the handles ------------\n var motionTrimWrap = document.getElementById('motion-trim');\n var motionTrimBar = document.getElementById('motion-trimbar');\n var motionTrimKept = document.getElementById('motion-trim-kept');\n var motionTrimPlayhead = document.getElementById('motion-trim-playhead');\n var motionTrimStartHandle = document.getElementById('motion-trim-start');\n var motionTrimEndHandle = document.getElementById('motion-trim-end');\n var motionTrimNote = document.getElementById('motion-trim-note');\n var motionTrimFullBtn = document.getElementById('motion-trim-full');\n var MOTION_TRIM_MIN_KEPT_S = 2;\n var motionTrimDuration = 0;\n var motionTrimStart = 0;\n var motionTrimEnd = 0;\n var motionPendingId = null;\n var motionAnalysisState = 'idle';\n var motionAnalysisToken = 0;\n var motionAnalyzePollTimer = null;\n\n function motionHasTrim() {\n return motionTrimDuration > 0 && motionTrimEnd > motionTrimStart\n && (motionTrimStart >= 0.1 || motionTrimDuration - motionTrimEnd >= 0.1);\n }\n\n function renderMotionTrim() {\n if (motionTrimDuration <= 0) { motionTrimWrap.classList.remove('show'); return; }\n motionTrimWrap.classList.add('show');\n var pct = function (seconds) {\n return Math.min(Math.max(seconds / motionTrimDuration, 0), 1) * 100 + '%';\n };\n motionTrimKept.style.left = pct(motionTrimStart);\n motionTrimKept.style.width = Math.max(0, (motionTrimEnd - motionTrimStart) / motionTrimDuration) * 100 + '%';\n motionTrimStartHandle.style.left = pct(motionTrimStart);\n motionTrimEndHandle.style.left = pct(motionTrimEnd);\n motionTrimFullBtn.hidden = !motionHasTrim();\n var note;\n if (motionAnalysisState === 'running') {\n note = 'Analyzing the clip for a good trim\u2026';\n } else if (!motionHasTrim()) {\n note = 'Using the full clip.';\n } else {\n var parts = [];\n if (motionTrimStart >= 0.1) parts.push(motionTrimStart.toFixed(1) + 's from the start');\n if (motionTrimDuration - motionTrimEnd >= 0.1) parts.push((motionTrimDuration - motionTrimEnd).toFixed(1) + 's from the end');\n note = 'Trimming ' + parts.join(' and ') + '.';\n }\n motionTrimNote.textContent = note;\n }\n\n function resetMotionTrim() {\n motionAnalysisToken++;\n if (motionAnalyzePollTimer) { clearTimeout(motionAnalyzePollTimer); motionAnalyzePollTimer = null; }\n motionPendingId = null;\n motionAnalysisState = 'idle';\n motionTrimDuration = 0;\n motionTrimStart = 0;\n motionTrimEnd = 0;\n motionTrimWrap.classList.remove('show');\n }\n\n function seedMotionTrim(durationSeconds) {\n if (!(durationSeconds > 0)) return;\n motionTrimDuration = durationSeconds;\n motionTrimStart = 0;\n motionTrimEnd = durationSeconds;\n renderMotionTrim();\n }\n\n function applyMotionSuggestion(suggestion) {\n if (!suggestion) { renderMotionTrim(); return; }\n if (suggestion.durationSeconds > 0) {\n motionTrimDuration = suggestion.durationSeconds;\n motionTrimStart = 0;\n motionTrimEnd = suggestion.durationSeconds;\n }\n if (suggestion.confidence === 'high'\n && typeof suggestion.suggestedStartSeconds === 'number'\n && typeof suggestion.suggestedEndSeconds === 'number'\n && suggestion.suggestedEndSeconds > suggestion.suggestedStartSeconds) {\n motionTrimStart = suggestion.suggestedStartSeconds;\n motionTrimEnd = Math.min(suggestion.suggestedEndSeconds, motionTrimDuration || suggestion.suggestedEndSeconds);\n }\n renderMotionTrim();\n }\n\n function beginMotionTrimDrag(which, event) {\n if (motionTrimDuration <= 0) return;\n var handle = event.currentTarget;\n handle.setPointerCapture(event.pointerId);\n var move = function (e) {\n var rect = motionTrimBar.getBoundingClientRect();\n if (rect.width === 0) return;\n var at = Math.min(Math.max((e.clientX - rect.left) / rect.width, 0), 1) * motionTrimDuration;\n if (which === 'start') motionTrimStart = Math.min(at, motionTrimEnd - MOTION_TRIM_MIN_KEPT_S);\n else motionTrimEnd = Math.max(at, motionTrimStart + MOTION_TRIM_MIN_KEPT_S);\n renderMotionTrim();\n };\n var up = function () {\n handle.removeEventListener('pointermove', move);\n handle.removeEventListener('pointerup', up);\n handle.removeEventListener('pointercancel', up);\n };\n handle.addEventListener('pointermove', move);\n handle.addEventListener('pointerup', up);\n handle.addEventListener('pointercancel', up);\n event.preventDefault();\n }\n\n function pollMotionAnalysis(token) {\n var tick = async function () {\n if (token !== motionAnalysisToken) return;\n var payload;\n try {\n payload = await (await fetch('/api/editor/motion-analyze-status')).json();\n } catch (error) {\n motionAnalyzePollTimer = setTimeout(tick, 2000);\n return;\n }\n if (token !== motionAnalysisToken) return;\n if (payload && payload.status === 'done') {\n motionAnalysisState = 'done';\n applyMotionSuggestion(payload.suggestion);\n return;\n }\n if (payload && payload.status === 'running') {\n motionAnalyzePollTimer = setTimeout(tick, 2000);\n return;\n }\n // failed / unavailable / none: no suggestion, the full-range handles stand.\n motionAnalysisState = 'failed';\n renderMotionTrim();\n };\n motionAnalyzePollTimer = setTimeout(tick, 2000);\n }\n\n /**\n * Hand the clip to the sidecar ahead of submission: it uploads once and runs the unbilled trim\n * analysis while the creator reviews. Degraded, never blocking \u2014 any failure just leaves the\n * handles at full range, and Submit works throughout.\n */\n async function startMotionAnalysis(blob) {\n var token = ++motionAnalysisToken;\n motionPendingId = null;\n motionAnalysisState = 'running';\n renderMotionTrim();\n var result = null;\n try {\n var response = await fetch('/api/editor/motion-analyze', {\n method: 'POST',\n headers: { 'Content-Type': blob.type || 'video/webm' },\n body: blob\n });\n result = await response.json();\n } catch (error) { /* the sidecar said nothing; treat as unavailable */ }\n if (token !== motionAnalysisToken) return;\n if (!result || result.ok !== true || result.analysing !== true) {\n motionAnalysisState = 'idle';\n renderMotionTrim();\n return;\n }\n motionPendingId = result.pendingId || null;\n pollMotionAnalysis(token);\n }\n\n function motionSupported() {\n return !!(window.isSecureContext && navigator.mediaDevices && navigator.mediaDevices.getUserMedia\n && typeof MediaRecorder !== 'undefined');\n }\n\n /** mp4 first (Safari), then the WebM the rest produce; asset-forger re-encodes either. */\n function pickMotionMime() {\n var candidates = ['video/mp4', 'video/webm;codecs=vp9', 'video/webm'];\n for (var i = 0; i < candidates.length; i++) {\n if (MediaRecorder.isTypeSupported(candidates[i])) return candidates[i];\n }\n return '';\n }\n\n function motionCameraError(error) {\n var name = error && error.name;\n if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was refused. Allow it in the address bar, or choose a video file.';\n if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera found. Choose a video file instead.';\n if (name === 'NotReadableError') return 'The camera is in use by another app. Close it, or choose a video file.';\n return 'Could not start the camera: ' + ((error && error.message) || 'unknown error');\n }\n\n function formatMotionClock(seconds) {\n var s = Math.max(0, Math.floor(seconds));\n var rest = s % 60;\n return Math.floor(s / 60) + ':' + (rest < 10 ? '0' : '') + rest;\n }\n\n function showMotionNote(text, command) {\n document.getElementById('motion-note-text').textContent = text;\n document.getElementById('motion-command').textContent = command || '';\n motionNote.classList.add('show');\n }\n\n function releaseMotionObjectUrl() {\n if (motionObjectUrl) { URL.revokeObjectURL(motionObjectUrl); motionObjectUrl = null; }\n }\n\n /** Stop the recorder if one is still live \u2014 it may already have stopped itself. */\n function discardMotionRecorder() {\n if (motionRecorder && motionRecorder.state !== 'inactive') {\n try { motionRecorder.stop(); } catch (error) { /* already stopped */ }\n }\n }\n\n function stopMotionStream() {\n if (motionStream) {\n motionStream.getTracks().forEach(function (track) { track.stop(); });\n motionStream = null;\n }\n if (motionTickTimer) { clearInterval(motionTickTimer); motionTickTimer = null; }\n motionCountdownToken++;\n motionCountdown.classList.remove('show');\n motionTimer.classList.remove('show');\n motionPreview.classList.remove('mirror');\n }\n\n function setMotionButtons(state) {\n motionRecordBtn.hidden = state !== 'idle';\n motionPickBtn.hidden = state !== 'idle';\n motionStopBtn.hidden = state !== 'recording';\n motionRetakeBtn.hidden = state !== 'ready';\n motionSubmit.disabled = state !== 'ready';\n }\n\n function resetMotionPanel() {\n resetMotionTrim();\n stopMotionStream();\n discardMotionRecorder();\n motionRecorder = null;\n motionChunks = [];\n motionBlob = null;\n motionFromRecording = false;\n motionSeconds = 0;\n releaseMotionObjectUrl();\n motionPreview.srcObject = null;\n motionPreview.removeAttribute('src');\n motionPreview.controls = false;\n motionPreview.muted = true;\n motionHint.classList.remove('hidden');\n var supported = motionSupported();\n motionGuidance.textContent = supported ? '' : 'Webcam recording needs a secure page with a camera; choose a video file instead.';\n motionRecordBtn.disabled = !supported;\n motionNote.classList.remove('show');\n setMotionButtons('idle');\n }\n\n function openMotionPanel() {\n resetMotionPanel();\n motionOverlay.classList.add('show');\n motionName.focus();\n }\n\n /** Returns whether it was open \u2014 the Escape handler's contract, like closeAssetDetail. */\n function closeMotionPanel() {\n if (!motionOverlay.classList.contains('show')) return false;\n stopMotionStream();\n discardMotionRecorder();\n motionOverlay.classList.remove('show');\n frame.focus();\n return true;\n }\n\n /** The clip is in hand: show it back, and say whether it is within Uthana's 2-60 s window. */\n function acceptMotionClip(blob, seconds) {\n motionBlob = blob;\n motionSeconds = seconds;\n releaseMotionObjectUrl();\n motionObjectUrl = URL.createObjectURL(blob);\n motionPreview.srcObject = null;\n motionPreview.src = motionObjectUrl;\n motionPreview.controls = true;\n motionPreview.muted = true;\n motionHint.classList.add('hidden');\n var note;\n if (blob.size > MOTION_MAX_BYTES) note = 'That video is over 200 MB. Trim it to the seconds that matter.';\n else if (seconds > 0 && seconds < MOTION_MIN_S) note = 'Too short: Uthana needs at least ' + MOTION_MIN_S + ' seconds.';\n else if (seconds > MOTION_MAX_S) note = 'Too long: Uthana takes at most ' + MOTION_MAX_S + ' seconds. Trim it, or record again.';\n var ok = !note;\n motionGuidance.textContent = ok\n ? (seconds > 0 ? formatMotionClock(seconds) + ' of video ready.' : 'Video ready.')\n : note;\n setMotionButtons('ready');\n motionSubmit.disabled = !ok;\n resetMotionTrim();\n if (ok) {\n seedMotionTrim(seconds);\n // A fresh WebM often reports no duration; the preview's metadata is the fallback scale.\n motionPreview.onloadedmetadata = function () {\n if (motionTrimDuration === 0 && isFinite(motionPreview.duration) && motionPreview.duration > 0) {\n seedMotionTrim(motionPreview.duration);\n }\n };\n void startMotionAnalysis(blob);\n }\n }\n\n async function startMotionRecording() {\n if (!motionSupported()) return;\n motionNote.classList.remove('show');\n try {\n motionStream = await navigator.mediaDevices.getUserMedia({\n video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' }, audio: false\n });\n } catch (error) {\n motionGuidance.textContent = motionCameraError(error);\n return;\n }\n releaseMotionObjectUrl();\n motionPreview.removeAttribute('src');\n motionPreview.controls = false;\n motionPreview.srcObject = motionStream;\n motionPreview.classList.add('mirror');\n motionHint.classList.add('hidden');\n try { await motionPreview.play(); } catch (error) { /* autoplay refused; the stream still shows on interaction */ }\n var mime = pickMotionMime();\n try {\n motionRecorder = mime ? new MediaRecorder(motionStream, { mimeType: mime }) : new MediaRecorder(motionStream);\n } catch (error) {\n stopMotionStream();\n motionGuidance.textContent = 'This browser cannot record video. Choose a video file instead.';\n return;\n }\n // Count down on the live preview; Stop during the count aborts without recording.\n var token = ++motionCountdownToken;\n setMotionButtons('recording');\n motionGuidance.textContent = 'Get in frame \u2014 recording starts after the count.';\n motionCountdown.classList.add('show');\n for (var left = MOTION_COUNTDOWN_S; left > 0; left--) {\n motionCountdownNumber.textContent = String(left);\n await new Promise(function (resolve) { setTimeout(resolve, 1000); });\n if (token !== motionCountdownToken) return;\n }\n motionCountdown.classList.remove('show');\n motionChunks = [];\n motionRecorder.ondataavailable = function (event) { if (event.data && event.data.size > 0) motionChunks.push(event.data); };\n motionRecorder.onstop = function () {\n var seconds = (Date.now() - motionStartedAt) / 1000;\n var type = motionRecorder.mimeType || mime || 'video/webm';\n stopMotionStream();\n motionFromRecording = true;\n acceptMotionClip(new Blob(motionChunks, { type: type }), seconds);\n };\n motionStartedAt = Date.now();\n motionRecorder.start(1000);\n motionTimer.textContent = '0:00';\n motionTimer.classList.add('show');\n motionGuidance.textContent = 'Recording. Stop when the move is done (auto-stops at ' + MOTION_MAX_S + ' s).';\n motionTickTimer = setInterval(function () {\n var elapsed = (Date.now() - motionStartedAt) / 1000;\n motionTimer.textContent = formatMotionClock(elapsed);\n if (elapsed >= MOTION_MAX_S) stopMotionRecording();\n }, 250);\n }\n\n function stopMotionRecording() {\n if (motionRecorder && motionRecorder.state === 'recording') { motionRecorder.stop(); return; }\n // Stop pressed during the countdown: nothing was recorded, back to the start.\n if (motionCountdown.classList.contains('show')) resetMotionPanel();\n }\n\n function pickMotionFile(file) {\n if (!file) return;\n // Read the duration off the file itself; a picked video knows its length, a fresh WebM often\n // does not (Infinity), so 0 means \"unknown\" and the server's ffprobe is the judge.\n var probe = document.createElement('video');\n probe.preload = 'metadata';\n var url = URL.createObjectURL(file);\n var settled = false;\n var finish = function (seconds) {\n if (settled) return;\n settled = true;\n URL.revokeObjectURL(url);\n motionFromRecording = false;\n acceptMotionClip(file, seconds);\n };\n probe.onloadedmetadata = function () { finish(isFinite(probe.duration) ? probe.duration : 0); };\n probe.onerror = function () { finish(0); };\n probe.src = url;\n setTimeout(function () { finish(0); }, 3000);\n }\n\n var motionPollTimer = null;\n function pollMotionJob() {\n if (motionPollTimer) clearTimeout(motionPollTimer);\n var tick = async function () {\n var job;\n try {\n job = (await (await fetch('/api/editor/motion-status')).json()).job;\n } catch (error) {\n motionPollTimer = setTimeout(tick, 3000);\n return;\n }\n if (!job) return;\n if (job.status === 'running') {\n showMotionNote(job.message, '');\n setStatus('saving', 'Making the animation\u2026');\n motionPollTimer = setTimeout(tick, 3000);\n return;\n }\n if (job.status === 'failed') {\n showMotionNote('Could not make the animation: ' + job.message, '');\n setStatus('error', 'Animation failed');\n setMotionButtons('ready');\n return;\n }\n showMotionNote(job.message + ' Reloading to show it.', '');\n setStatus('saved', 'Animation added');\n setMotionButtons('ready');\n if (autoReload && !voxelSessionActive && !voxelSessionPending) start();\n else banner.classList.add('show');\n };\n void tick();\n }\n\n async function submitMotion() {\n if (!motionBlob) return;\n var name = motionName.value.trim();\n if (name === '') { motionName.focus(); return; }\n // Whatever the handles show is what gets made; a still-running analysis must not move them.\n motionAnalysisToken++;\n if (motionAnalyzePollTimer) { clearTimeout(motionAnalyzePollTimer); motionAnalyzePollTimer = null; }\n var query = '?name=' + encodeURIComponent(name)\n + '&slot=' + encodeURIComponent(motionSlot.value)\n + '&loop=' + (motionLoop.checked ? '1' : '0');\n if (motionHasTrim()) {\n query += '&trimStart=' + encodeURIComponent(String(Math.round(motionTrimStart * 100) / 100))\n + '&trimEnd=' + encodeURIComponent(String(Math.round(motionTrimEnd * 100) / 100));\n }\n if (motionPendingId) {\n query += '&pendingId=' + encodeURIComponent(motionPendingId);\n }\n motionSubmit.disabled = true;\n showMotionNote('Uploading the video\u2026', '');\n var response, result;\n try {\n response = await fetch('/api/editor/motion-video' + query, {\n method: 'POST',\n headers: { 'Content-Type': motionBlob.type || 'video/webm' },\n body: motionBlob\n });\n result = await response.json();\n } catch (error) {\n showMotionNote('Could not send the video to the sidecar.', '');\n motionSubmit.disabled = false;\n return;\n }\n if (!response.ok || result.ok !== true) {\n showMotionNote(result.error || 'The sidecar refused the video.', '');\n motionSubmit.disabled = false;\n return;\n }\n if (result.running !== true) {\n // The one case the sidecar cannot run itself: nobody is logged in.\n showMotionNote(result.reason || '', result.command || '');\n setStatus('saved', 'Video saved');\n return;\n }\n showMotionNote(result.note || 'Making the animation \u2014 this takes a few minutes. You can keep editing.', '');\n setStatus('saving', 'Making the animation\u2026');\n pollMotionJob();\n }\n\n motionToggle.addEventListener('click', openMotionPanel);\n document.getElementById('motion-close').addEventListener('click', function () { closeMotionPanel(); });\n motionOverlay.addEventListener('click', function (event) {\n if (event.target === motionOverlay) closeMotionPanel();\n });\n motionRecordBtn.addEventListener('click', function () { void startMotionRecording(); });\n motionStopBtn.addEventListener('click', stopMotionRecording);\n motionRetakeBtn.addEventListener('click', resetMotionPanel);\n motionPickBtn.addEventListener('click', function () { motionFile.value = ''; motionFile.click(); });\n motionFile.addEventListener('change', function () { pickMotionFile(motionFile.files && motionFile.files[0]); });\n motionSubmit.addEventListener('click', function () { void submitMotion(); });\n motionTrimStartHandle.addEventListener('pointerdown', function (event) { beginMotionTrimDrag('start', event); });\n motionTrimEndHandle.addEventListener('pointerdown', function (event) { beginMotionTrimDrag('end', event); });\n motionTrimFullBtn.addEventListener('click', function () {\n motionTrimStart = 0;\n motionTrimEnd = motionTrimDuration;\n renderMotionTrim();\n });\n // Review playback stays inside the kept range, so the creator sees what gets made.\n motionPreview.addEventListener('timeupdate', function () {\n if (motionTrimDuration > 0) {\n motionTrimPlayhead.style.left = Math.min(Math.max(motionPreview.currentTime / motionTrimDuration, 0), 1) * 100 + '%';\n }\n if (!motionBlob || !motionHasTrim()) return;\n if (motionPreview.currentTime >= motionTrimEnd || motionPreview.currentTime < motionTrimStart - 0.25) {\n motionPreview.currentTime = motionTrimStart;\n }\n });\n";
|
|
20
|
+
export declare const MOTION_PANEL_JS = "\n // ---- Record motion: webcam or file -> Uthana video-to-motion -> assets[] ----------------------\n var motionToggle = document.getElementById('motion');\n var motionOverlay = document.getElementById('motion-overlay');\n var motionPreview = document.getElementById('motion-preview');\n var motionTimer = document.getElementById('motion-timer');\n var motionCountdown = document.getElementById('motion-countdown');\n var motionCountdownNumber = document.getElementById('motion-countdown-number');\n /** Seconds shown on the live preview before the recorder starts, so the first frames are the pose. */\n var MOTION_COUNTDOWN_S = 3;\n var motionCountdownToken = 0;\n var motionHint = document.getElementById('motion-hint');\n var motionRecordBtn = document.getElementById('motion-record');\n var motionStopBtn = document.getElementById('motion-stop');\n var motionPickBtn = document.getElementById('motion-pick');\n var motionRetakeBtn = document.getElementById('motion-retake');\n var motionFile = document.getElementById('motion-file');\n var motionGuidance = document.getElementById('motion-guidance');\n var motionName = document.getElementById('motion-name');\n var motionSlot = document.getElementById('motion-slot');\n var motionLoop = document.getElementById('motion-loop');\n var motionSubmit = document.getElementById('motion-submit');\n var motionNote = document.getElementById('motion-note');\n var MOTION_MIN_S = 2;\n var MOTION_MAX_S = 60;\n var MOTION_MAX_BYTES = 200 * 1024 * 1024;\n var motionBlob = null;\n // Whether motionBlob came from the webcam recorder (auto-trim applies) or a picked file (it does not).\n var motionFromRecording = false;\n var motionSeconds = 0;\n var motionStream = null;\n var motionRecorder = null;\n var motionChunks = [];\n var motionTickTimer = null;\n var motionStartedAt = 0;\n var motionObjectUrl = null;\n // ---- Trim window: seeded by the sidecar's trim analysis, adjusted on the handles ------------\n var motionTrimWrap = document.getElementById('motion-trim');\n var motionTrimBar = document.getElementById('motion-trimbar');\n var motionTrimKept = document.getElementById('motion-trim-kept');\n var motionTrimPlayhead = document.getElementById('motion-trim-playhead');\n var motionTrimStartHandle = document.getElementById('motion-trim-start');\n var motionTrimEndHandle = document.getElementById('motion-trim-end');\n var motionTrimNote = document.getElementById('motion-trim-note');\n var motionTrimFullBtn = document.getElementById('motion-trim-full');\n var motionTrimPreviewBtn = document.getElementById('motion-trim-preview');\n // True while \"Preview the kept range\" is playing trimStart -> trimEnd.\n var motionPreviewingTrim = false;\n var MOTION_TRIM_MIN_KEPT_S = 2;\n var motionTrimDuration = 0;\n var motionTrimStart = 0;\n var motionTrimEnd = 0;\n var motionPendingId = null;\n var motionAnalysisState = 'idle';\n var motionAnalysisToken = 0;\n var motionAnalyzePollTimer = null;\n\n function motionHasTrim() {\n return motionTrimDuration > 0 && motionTrimEnd > motionTrimStart\n && (motionTrimStart >= 0.1 || motionTrimDuration - motionTrimEnd >= 0.1);\n }\n\n function renderMotionTrim() {\n if (motionTrimDuration <= 0) { motionTrimWrap.classList.remove('show'); return; }\n motionTrimWrap.classList.add('show');\n var pct = function (seconds) {\n return Math.min(Math.max(seconds / motionTrimDuration, 0), 1) * 100 + '%';\n };\n motionTrimKept.style.left = pct(motionTrimStart);\n motionTrimKept.style.width = Math.max(0, (motionTrimEnd - motionTrimStart) / motionTrimDuration) * 100 + '%';\n motionTrimStartHandle.style.left = pct(motionTrimStart);\n motionTrimEndHandle.style.left = pct(motionTrimEnd);\n motionTrimFullBtn.hidden = !motionHasTrim();\n motionTrimPreviewBtn.textContent = motionPreviewingTrim\n ? '\u23F9 Stop'\n : (motionHasTrim() ? '\u25B6 Preview the kept range' : '\u25B6 Play');\n var note;\n if (motionAnalysisState === 'running') {\n note = 'Analyzing the clip for a good trim\u2026';\n } else if (!motionHasTrim()) {\n note = 'Using the full clip.';\n } else {\n var parts = [];\n if (motionTrimStart >= 0.1) parts.push(motionTrimStart.toFixed(1) + 's from the start');\n if (motionTrimDuration - motionTrimEnd >= 0.1) parts.push((motionTrimDuration - motionTrimEnd).toFixed(1) + 's from the end');\n note = 'Trimming ' + parts.join(' and ') + '.';\n }\n motionTrimNote.textContent = note;\n }\n\n function resetMotionTrim() {\n motionPreviewingTrim = false;\n motionAnalysisToken++;\n if (motionAnalyzePollTimer) { clearTimeout(motionAnalyzePollTimer); motionAnalyzePollTimer = null; }\n motionPendingId = null;\n motionAnalysisState = 'idle';\n motionTrimDuration = 0;\n motionTrimStart = 0;\n motionTrimEnd = 0;\n motionTrimWrap.classList.remove('show');\n }\n\n function seedMotionTrim(durationSeconds) {\n if (!(durationSeconds > 0)) return;\n motionTrimDuration = durationSeconds;\n motionTrimStart = 0;\n motionTrimEnd = durationSeconds;\n // Review playback is the trim: the Play/Preview button below drives the\n // video, and a native full-clip scrubber under a trim bar read as \"it\n // plays the whole video anyway\". Controls stay native only while the\n // duration is unknown and the bar cannot render.\n motionPreview.controls = false;\n renderMotionTrim();\n }\n\n function applyMotionSuggestion(suggestion) {\n if (!suggestion) { renderMotionTrim(); return; }\n if (suggestion.durationSeconds > 0) {\n motionTrimDuration = suggestion.durationSeconds;\n motionTrimStart = 0;\n motionTrimEnd = suggestion.durationSeconds;\n }\n if (suggestion.confidence === 'high'\n && typeof suggestion.suggestedStartSeconds === 'number'\n && typeof suggestion.suggestedEndSeconds === 'number'\n && suggestion.suggestedEndSeconds > suggestion.suggestedStartSeconds) {\n motionTrimStart = suggestion.suggestedStartSeconds;\n motionTrimEnd = Math.min(suggestion.suggestedEndSeconds, motionTrimDuration || suggestion.suggestedEndSeconds);\n }\n renderMotionTrim();\n }\n\n function beginMotionTrimDrag(which, event) {\n if (motionTrimDuration <= 0) return;\n var handle = event.currentTarget;\n handle.setPointerCapture(event.pointerId);\n var move = function (e) {\n var rect = motionTrimBar.getBoundingClientRect();\n if (rect.width === 0) return;\n var at = Math.min(Math.max((e.clientX - rect.left) / rect.width, 0), 1) * motionTrimDuration;\n if (which === 'start') motionTrimStart = Math.min(at, motionTrimEnd - MOTION_TRIM_MIN_KEPT_S);\n else motionTrimEnd = Math.max(at, motionTrimStart + MOTION_TRIM_MIN_KEPT_S);\n // Show the exact frame the cut lands on while the handle moves.\n motionPreview.pause();\n motionPreviewingTrim = false;\n motionPreview.currentTime = which === 'start' ? motionTrimStart : motionTrimEnd;\n renderMotionTrim();\n };\n var up = function () {\n handle.removeEventListener('pointermove', move);\n handle.removeEventListener('pointerup', up);\n handle.removeEventListener('pointercancel', up);\n };\n handle.addEventListener('pointermove', move);\n handle.addEventListener('pointerup', up);\n handle.addEventListener('pointercancel', up);\n event.preventDefault();\n }\n\n function pollMotionAnalysis(token) {\n var tick = async function () {\n if (token !== motionAnalysisToken) return;\n var payload;\n try {\n payload = await (await fetch('/api/editor/motion-analyze-status')).json();\n } catch (error) {\n motionAnalyzePollTimer = setTimeout(tick, 2000);\n return;\n }\n if (token !== motionAnalysisToken) return;\n if (payload && payload.status === 'done') {\n motionAnalysisState = 'done';\n applyMotionSuggestion(payload.suggestion);\n return;\n }\n if (payload && payload.status === 'running') {\n motionAnalyzePollTimer = setTimeout(tick, 2000);\n return;\n }\n // failed / unavailable / none: no suggestion, the full-range handles stand.\n motionAnalysisState = 'failed';\n renderMotionTrim();\n };\n motionAnalyzePollTimer = setTimeout(tick, 2000);\n }\n\n /**\n * Hand the clip to the sidecar ahead of submission: it uploads once and runs the unbilled trim\n * analysis while the creator reviews. Degraded, never blocking \u2014 any failure just leaves the\n * handles at full range, and Submit works throughout.\n */\n async function startMotionAnalysis(blob) {\n var token = ++motionAnalysisToken;\n motionPendingId = null;\n motionAnalysisState = 'running';\n renderMotionTrim();\n var result = null;\n try {\n var response = await fetch('/api/editor/motion-analyze', {\n method: 'POST',\n headers: { 'Content-Type': blob.type || 'video/webm' },\n body: blob\n });\n result = await response.json();\n } catch (error) { /* the sidecar said nothing; treat as unavailable */ }\n if (token !== motionAnalysisToken) return;\n if (!result || result.ok !== true || result.analysing !== true) {\n motionAnalysisState = 'idle';\n renderMotionTrim();\n return;\n }\n motionPendingId = result.pendingId || null;\n pollMotionAnalysis(token);\n }\n\n function motionSupported() {\n return !!(window.isSecureContext && navigator.mediaDevices && navigator.mediaDevices.getUserMedia\n && typeof MediaRecorder !== 'undefined');\n }\n\n /** mp4 first (Safari), then the WebM the rest produce; asset-forger re-encodes either. */\n function pickMotionMime() {\n var candidates = ['video/mp4', 'video/webm;codecs=vp9', 'video/webm'];\n for (var i = 0; i < candidates.length; i++) {\n if (MediaRecorder.isTypeSupported(candidates[i])) return candidates[i];\n }\n return '';\n }\n\n function motionCameraError(error) {\n var name = error && error.name;\n if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was refused. Allow it in the address bar, or choose a video file.';\n if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera found. Choose a video file instead.';\n if (name === 'NotReadableError') return 'The camera is in use by another app. Close it, or choose a video file.';\n return 'Could not start the camera: ' + ((error && error.message) || 'unknown error');\n }\n\n function formatMotionClock(seconds) {\n var s = Math.max(0, Math.floor(seconds));\n var rest = s % 60;\n return Math.floor(s / 60) + ':' + (rest < 10 ? '0' : '') + rest;\n }\n\n function showMotionNote(text, command) {\n document.getElementById('motion-note-text').textContent = text;\n document.getElementById('motion-command').textContent = command || '';\n motionNote.classList.add('show');\n }\n\n function releaseMotionObjectUrl() {\n if (motionObjectUrl) { URL.revokeObjectURL(motionObjectUrl); motionObjectUrl = null; }\n }\n\n /** Stop the recorder if one is still live \u2014 it may already have stopped itself. */\n function discardMotionRecorder() {\n if (motionRecorder && motionRecorder.state !== 'inactive') {\n try { motionRecorder.stop(); } catch (error) { /* already stopped */ }\n }\n }\n\n function stopMotionStream() {\n if (motionStream) {\n motionStream.getTracks().forEach(function (track) { track.stop(); });\n motionStream = null;\n }\n if (motionTickTimer) { clearInterval(motionTickTimer); motionTickTimer = null; }\n motionCountdownToken++;\n motionCountdown.classList.remove('show');\n motionTimer.classList.remove('show');\n motionPreview.classList.remove('mirror');\n }\n\n function setMotionButtons(state) {\n motionRecordBtn.hidden = state !== 'idle';\n motionPickBtn.hidden = state !== 'idle';\n motionStopBtn.hidden = state !== 'recording';\n motionRetakeBtn.hidden = state !== 'ready';\n motionSubmit.disabled = state !== 'ready';\n }\n\n function resetMotionPanel() {\n resetMotionTrim();\n stopMotionStream();\n discardMotionRecorder();\n motionRecorder = null;\n motionChunks = [];\n motionBlob = null;\n motionFromRecording = false;\n motionSeconds = 0;\n releaseMotionObjectUrl();\n motionPreview.srcObject = null;\n motionPreview.removeAttribute('src');\n motionPreview.controls = false;\n motionPreview.muted = true;\n motionHint.classList.remove('hidden');\n var supported = motionSupported();\n motionGuidance.textContent = supported ? '' : 'Webcam recording needs a secure page with a camera; choose a video file instead.';\n motionRecordBtn.disabled = !supported;\n motionNote.classList.remove('show');\n setMotionButtons('idle');\n }\n\n function openMotionPanel() {\n resetMotionPanel();\n motionOverlay.classList.add('show');\n motionName.focus();\n }\n\n /** Returns whether it was open \u2014 the Escape handler's contract, like closeAssetDetail. */\n function closeMotionPanel() {\n if (!motionOverlay.classList.contains('show')) return false;\n stopMotionStream();\n discardMotionRecorder();\n motionOverlay.classList.remove('show');\n frame.focus();\n return true;\n }\n\n /** The clip is in hand: show it back, and say whether it is within Uthana's 2-60 s window. */\n function acceptMotionClip(blob, seconds) {\n motionBlob = blob;\n motionSeconds = seconds;\n releaseMotionObjectUrl();\n motionObjectUrl = URL.createObjectURL(blob);\n motionPreview.srcObject = null;\n motionPreview.src = motionObjectUrl;\n motionPreview.controls = true;\n motionPreview.muted = true;\n motionHint.classList.add('hidden');\n var note;\n if (blob.size > MOTION_MAX_BYTES) note = 'That video is over 200 MB. Trim it to the seconds that matter.';\n else if (seconds > 0 && seconds < MOTION_MIN_S) note = 'Too short: Uthana needs at least ' + MOTION_MIN_S + ' seconds.';\n else if (seconds > MOTION_MAX_S) note = 'Too long: Uthana takes at most ' + MOTION_MAX_S + ' seconds. Trim it, or record again.';\n var ok = !note;\n motionGuidance.textContent = ok\n ? (seconds > 0 ? formatMotionClock(seconds) + ' of video ready.' : 'Video ready.')\n : note;\n setMotionButtons('ready');\n motionSubmit.disabled = !ok;\n resetMotionTrim();\n if (ok) {\n seedMotionTrim(seconds);\n // A fresh WebM often reports no duration; the preview's metadata is the fallback scale.\n motionPreview.onloadedmetadata = function () {\n if (motionTrimDuration === 0 && isFinite(motionPreview.duration) && motionPreview.duration > 0) {\n seedMotionTrim(motionPreview.duration);\n }\n };\n void startMotionAnalysis(blob);\n }\n }\n\n async function startMotionRecording() {\n if (!motionSupported()) return;\n motionNote.classList.remove('show');\n try {\n motionStream = await navigator.mediaDevices.getUserMedia({\n video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' }, audio: false\n });\n } catch (error) {\n motionGuidance.textContent = motionCameraError(error);\n return;\n }\n releaseMotionObjectUrl();\n motionPreview.removeAttribute('src');\n motionPreview.controls = false;\n motionPreview.srcObject = motionStream;\n motionPreview.classList.add('mirror');\n motionHint.classList.add('hidden');\n try { await motionPreview.play(); } catch (error) { /* autoplay refused; the stream still shows on interaction */ }\n var mime = pickMotionMime();\n try {\n motionRecorder = mime ? new MediaRecorder(motionStream, { mimeType: mime }) : new MediaRecorder(motionStream);\n } catch (error) {\n stopMotionStream();\n motionGuidance.textContent = 'This browser cannot record video. Choose a video file instead.';\n return;\n }\n // Count down on the live preview; Stop during the count aborts without recording.\n var token = ++motionCountdownToken;\n setMotionButtons('recording');\n motionGuidance.textContent = 'Get in frame \u2014 recording starts after the count.';\n motionCountdown.classList.add('show');\n for (var left = MOTION_COUNTDOWN_S; left > 0; left--) {\n motionCountdownNumber.textContent = String(left);\n await new Promise(function (resolve) { setTimeout(resolve, 1000); });\n if (token !== motionCountdownToken) return;\n }\n motionCountdown.classList.remove('show');\n motionChunks = [];\n motionRecorder.ondataavailable = function (event) { if (event.data && event.data.size > 0) motionChunks.push(event.data); };\n motionRecorder.onstop = function () {\n var seconds = (Date.now() - motionStartedAt) / 1000;\n var type = motionRecorder.mimeType || mime || 'video/webm';\n stopMotionStream();\n motionFromRecording = true;\n acceptMotionClip(new Blob(motionChunks, { type: type }), seconds);\n };\n motionStartedAt = Date.now();\n motionRecorder.start(1000);\n motionTimer.textContent = '0:00';\n motionTimer.classList.add('show');\n motionGuidance.textContent = 'Recording. Stop when the move is done (auto-stops at ' + MOTION_MAX_S + ' s).';\n motionTickTimer = setInterval(function () {\n var elapsed = (Date.now() - motionStartedAt) / 1000;\n motionTimer.textContent = formatMotionClock(elapsed);\n if (elapsed >= MOTION_MAX_S) stopMotionRecording();\n }, 250);\n }\n\n function stopMotionRecording() {\n if (motionRecorder && motionRecorder.state === 'recording') { motionRecorder.stop(); return; }\n // Stop pressed during the countdown: nothing was recorded, back to the start.\n if (motionCountdown.classList.contains('show')) resetMotionPanel();\n }\n\n function pickMotionFile(file) {\n if (!file) return;\n // Read the duration off the file itself; a picked video knows its length, a fresh WebM often\n // does not (Infinity), so 0 means \"unknown\" and the server's ffprobe is the judge.\n var probe = document.createElement('video');\n probe.preload = 'metadata';\n var url = URL.createObjectURL(file);\n var settled = false;\n var finish = function (seconds) {\n if (settled) return;\n settled = true;\n URL.revokeObjectURL(url);\n motionFromRecording = false;\n acceptMotionClip(file, seconds);\n };\n probe.onloadedmetadata = function () { finish(isFinite(probe.duration) ? probe.duration : 0); };\n probe.onerror = function () { finish(0); };\n probe.src = url;\n setTimeout(function () { finish(0); }, 3000);\n }\n\n var motionPollTimer = null;\n function pollMotionJob() {\n if (motionPollTimer) clearTimeout(motionPollTimer);\n var tick = async function () {\n var job;\n try {\n job = (await (await fetch('/api/editor/motion-status')).json()).job;\n } catch (error) {\n motionPollTimer = setTimeout(tick, 3000);\n return;\n }\n if (!job) return;\n if (job.status === 'running') {\n showMotionNote(job.message, '');\n setStatus('saving', 'Making the animation\u2026');\n motionPollTimer = setTimeout(tick, 3000);\n return;\n }\n if (job.status === 'failed') {\n showMotionNote('Could not make the animation: ' + job.message, '');\n setStatus('error', 'Animation failed');\n setMotionButtons('ready');\n return;\n }\n showMotionNote(job.message + ' Reloading to show it.', '');\n setStatus('saved', 'Animation added');\n setMotionButtons('ready');\n if (autoReload && !voxelSessionActive && !voxelSessionPending) start();\n else banner.classList.add('show');\n };\n void tick();\n }\n\n async function submitMotion() {\n if (!motionBlob) return;\n var name = motionName.value.trim();\n if (name === '') { motionName.focus(); return; }\n // Whatever the handles show is what gets made; a still-running analysis must not move them.\n motionAnalysisToken++;\n if (motionAnalyzePollTimer) { clearTimeout(motionAnalyzePollTimer); motionAnalyzePollTimer = null; }\n var query = '?name=' + encodeURIComponent(name)\n + '&slot=' + encodeURIComponent(motionSlot.value)\n + '&loop=' + (motionLoop.checked ? '1' : '0');\n if (motionHasTrim()) {\n query += '&trimStart=' + encodeURIComponent(String(Math.round(motionTrimStart * 100) / 100))\n + '&trimEnd=' + encodeURIComponent(String(Math.round(motionTrimEnd * 100) / 100));\n }\n if (motionPendingId) {\n query += '&pendingId=' + encodeURIComponent(motionPendingId);\n }\n motionSubmit.disabled = true;\n showMotionNote('Uploading the video\u2026', '');\n var response, result;\n try {\n response = await fetch('/api/editor/motion-video' + query, {\n method: 'POST',\n headers: { 'Content-Type': motionBlob.type || 'video/webm' },\n body: motionBlob\n });\n result = await response.json();\n } catch (error) {\n showMotionNote('Could not send the video to the sidecar.', '');\n motionSubmit.disabled = false;\n return;\n }\n if (!response.ok || result.ok !== true) {\n showMotionNote(result.error || 'The sidecar refused the video.', '');\n motionSubmit.disabled = false;\n return;\n }\n if (result.running !== true) {\n // The one case the sidecar cannot run itself: nobody is logged in.\n showMotionNote(result.reason || '', result.command || '');\n setStatus('saved', 'Video saved');\n return;\n }\n showMotionNote(result.note || 'Making the animation \u2014 this takes a few minutes. You can keep editing.', '');\n setStatus('saving', 'Making the animation\u2026');\n pollMotionJob();\n }\n\n motionToggle.addEventListener('click', openMotionPanel);\n document.getElementById('motion-close').addEventListener('click', function () { closeMotionPanel(); });\n motionOverlay.addEventListener('click', function (event) {\n if (event.target === motionOverlay) closeMotionPanel();\n });\n motionRecordBtn.addEventListener('click', function () { void startMotionRecording(); });\n motionStopBtn.addEventListener('click', stopMotionRecording);\n motionRetakeBtn.addEventListener('click', resetMotionPanel);\n motionPickBtn.addEventListener('click', function () { motionFile.value = ''; motionFile.click(); });\n motionFile.addEventListener('change', function () { pickMotionFile(motionFile.files && motionFile.files[0]); });\n motionSubmit.addEventListener('click', function () { void submitMotion(); });\n motionTrimStartHandle.addEventListener('pointerdown', function (event) { beginMotionTrimDrag('start', event); });\n motionTrimEndHandle.addEventListener('pointerdown', function (event) { beginMotionTrimDrag('end', event); });\n motionTrimFullBtn.addEventListener('click', function () {\n motionTrimStart = 0;\n motionTrimEnd = motionTrimDuration;\n renderMotionTrim();\n });\n // \"Preview the kept range\" plays exactly trimStart -> trimEnd once and stops\n // on the last kept frame: what was just watched IS what the animation is\n // made from.\n motionTrimPreviewBtn.addEventListener('click', function () {\n if (motionPreviewingTrim) {\n motionPreview.pause();\n motionPreviewingTrim = false;\n renderMotionTrim();\n return;\n }\n motionPreview.currentTime = motionTrimStart;\n motionPreviewingTrim = true;\n renderMotionTrim();\n var played = motionPreview.play();\n if (played && played.catch) {\n played.catch(function () { motionPreviewingTrim = false; renderMotionTrim(); });\n }\n });\n motionPreview.addEventListener('pause', function () {\n if (motionPreviewingTrim) { motionPreviewingTrim = false; renderMotionTrim(); }\n });\n motionPreview.addEventListener('ended', function () {\n if (motionPreviewingTrim) { motionPreviewingTrim = false; renderMotionTrim(); }\n });\n motionPreview.addEventListener('timeupdate', function () {\n if (motionTrimDuration > 0) {\n motionTrimPlayhead.style.left = Math.min(Math.max(motionPreview.currentTime / motionTrimDuration, 0), 1) * 100 + '%';\n }\n if (motionPreviewingTrim && motionPreview.currentTime >= motionTrimEnd) {\n motionPreview.pause();\n motionPreview.currentTime = motionTrimEnd;\n motionPreviewingTrim = false;\n renderMotionTrim();\n }\n });\n";
|
|
@@ -45,6 +45,7 @@ export const MOTION_PANEL_CSS = `
|
|
|
45
45
|
#motion-trim-row { display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
|
46
46
|
margin-top: 6px; min-height: 24px; }
|
|
47
47
|
#motion-trim-note { font-size: 11px; color: var(--bm-text-muted); }
|
|
48
|
+
#motion-trim-actions { display: flex; gap: 6px; }
|
|
48
49
|
#motion-sources { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
|
|
49
50
|
#motion-file { display: none; }
|
|
50
51
|
#motion-guidance { margin: 10px 0 0; font-size: 12px; color: var(--bm-text-muted); }
|
|
@@ -81,7 +82,10 @@ export const MOTION_PANEL_HTML = ` <div id="motion-overlay" class="bm-overlay">
|
|
|
81
82
|
</div>
|
|
82
83
|
<div id="motion-trim-row">
|
|
83
84
|
<span id="motion-trim-note"></span>
|
|
84
|
-
<
|
|
85
|
+
<span id="motion-trim-actions">
|
|
86
|
+
<button id="motion-trim-preview" class="bm-pill" type="button">▶ Play</button>
|
|
87
|
+
<button id="motion-trim-full" class="bm-pill bm-pill--ghost" type="button" hidden>Use full clip</button>
|
|
88
|
+
</span>
|
|
85
89
|
</div>
|
|
86
90
|
</div>
|
|
87
91
|
<div id="motion-sources">
|
|
@@ -168,6 +172,9 @@ export const MOTION_PANEL_JS = `
|
|
|
168
172
|
var motionTrimEndHandle = document.getElementById('motion-trim-end');
|
|
169
173
|
var motionTrimNote = document.getElementById('motion-trim-note');
|
|
170
174
|
var motionTrimFullBtn = document.getElementById('motion-trim-full');
|
|
175
|
+
var motionTrimPreviewBtn = document.getElementById('motion-trim-preview');
|
|
176
|
+
// True while "Preview the kept range" is playing trimStart -> trimEnd.
|
|
177
|
+
var motionPreviewingTrim = false;
|
|
171
178
|
var MOTION_TRIM_MIN_KEPT_S = 2;
|
|
172
179
|
var motionTrimDuration = 0;
|
|
173
180
|
var motionTrimStart = 0;
|
|
@@ -193,6 +200,9 @@ export const MOTION_PANEL_JS = `
|
|
|
193
200
|
motionTrimStartHandle.style.left = pct(motionTrimStart);
|
|
194
201
|
motionTrimEndHandle.style.left = pct(motionTrimEnd);
|
|
195
202
|
motionTrimFullBtn.hidden = !motionHasTrim();
|
|
203
|
+
motionTrimPreviewBtn.textContent = motionPreviewingTrim
|
|
204
|
+
? '\u23F9 Stop'
|
|
205
|
+
: (motionHasTrim() ? '\u25B6 Preview the kept range' : '\u25B6 Play');
|
|
196
206
|
var note;
|
|
197
207
|
if (motionAnalysisState === 'running') {
|
|
198
208
|
note = 'Analyzing the clip for a good trim\u2026';
|
|
@@ -208,6 +218,7 @@ export const MOTION_PANEL_JS = `
|
|
|
208
218
|
}
|
|
209
219
|
|
|
210
220
|
function resetMotionTrim() {
|
|
221
|
+
motionPreviewingTrim = false;
|
|
211
222
|
motionAnalysisToken++;
|
|
212
223
|
if (motionAnalyzePollTimer) { clearTimeout(motionAnalyzePollTimer); motionAnalyzePollTimer = null; }
|
|
213
224
|
motionPendingId = null;
|
|
@@ -223,6 +234,11 @@ export const MOTION_PANEL_JS = `
|
|
|
223
234
|
motionTrimDuration = durationSeconds;
|
|
224
235
|
motionTrimStart = 0;
|
|
225
236
|
motionTrimEnd = durationSeconds;
|
|
237
|
+
// Review playback is the trim: the Play/Preview button below drives the
|
|
238
|
+
// video, and a native full-clip scrubber under a trim bar read as "it
|
|
239
|
+
// plays the whole video anyway". Controls stay native only while the
|
|
240
|
+
// duration is unknown and the bar cannot render.
|
|
241
|
+
motionPreview.controls = false;
|
|
226
242
|
renderMotionTrim();
|
|
227
243
|
}
|
|
228
244
|
|
|
@@ -253,6 +269,10 @@ export const MOTION_PANEL_JS = `
|
|
|
253
269
|
var at = Math.min(Math.max((e.clientX - rect.left) / rect.width, 0), 1) * motionTrimDuration;
|
|
254
270
|
if (which === 'start') motionTrimStart = Math.min(at, motionTrimEnd - MOTION_TRIM_MIN_KEPT_S);
|
|
255
271
|
else motionTrimEnd = Math.max(at, motionTrimStart + MOTION_TRIM_MIN_KEPT_S);
|
|
272
|
+
// Show the exact frame the cut lands on while the handle moves.
|
|
273
|
+
motionPreview.pause();
|
|
274
|
+
motionPreviewingTrim = false;
|
|
275
|
+
motionPreview.currentTime = which === 'start' ? motionTrimStart : motionTrimEnd;
|
|
256
276
|
renderMotionTrim();
|
|
257
277
|
};
|
|
258
278
|
var up = function () {
|
|
@@ -643,14 +663,39 @@ export const MOTION_PANEL_JS = `
|
|
|
643
663
|
motionTrimEnd = motionTrimDuration;
|
|
644
664
|
renderMotionTrim();
|
|
645
665
|
});
|
|
646
|
-
//
|
|
666
|
+
// "Preview the kept range" plays exactly trimStart -> trimEnd once and stops
|
|
667
|
+
// on the last kept frame: what was just watched IS what the animation is
|
|
668
|
+
// made from.
|
|
669
|
+
motionTrimPreviewBtn.addEventListener('click', function () {
|
|
670
|
+
if (motionPreviewingTrim) {
|
|
671
|
+
motionPreview.pause();
|
|
672
|
+
motionPreviewingTrim = false;
|
|
673
|
+
renderMotionTrim();
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
motionPreview.currentTime = motionTrimStart;
|
|
677
|
+
motionPreviewingTrim = true;
|
|
678
|
+
renderMotionTrim();
|
|
679
|
+
var played = motionPreview.play();
|
|
680
|
+
if (played && played.catch) {
|
|
681
|
+
played.catch(function () { motionPreviewingTrim = false; renderMotionTrim(); });
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
motionPreview.addEventListener('pause', function () {
|
|
685
|
+
if (motionPreviewingTrim) { motionPreviewingTrim = false; renderMotionTrim(); }
|
|
686
|
+
});
|
|
687
|
+
motionPreview.addEventListener('ended', function () {
|
|
688
|
+
if (motionPreviewingTrim) { motionPreviewingTrim = false; renderMotionTrim(); }
|
|
689
|
+
});
|
|
647
690
|
motionPreview.addEventListener('timeupdate', function () {
|
|
648
691
|
if (motionTrimDuration > 0) {
|
|
649
692
|
motionTrimPlayhead.style.left = Math.min(Math.max(motionPreview.currentTime / motionTrimDuration, 0), 1) * 100 + '%';
|
|
650
693
|
}
|
|
651
|
-
if (
|
|
652
|
-
|
|
653
|
-
motionPreview.currentTime =
|
|
694
|
+
if (motionPreviewingTrim && motionPreview.currentTime >= motionTrimEnd) {
|
|
695
|
+
motionPreview.pause();
|
|
696
|
+
motionPreview.currentTime = motionTrimEnd;
|
|
697
|
+
motionPreviewingTrim = false;
|
|
698
|
+
renderMotionTrim();
|
|
654
699
|
}
|
|
655
700
|
});
|
|
656
701
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"motion-panel.js","sourceRoot":"","sources":["../../src/editor/motion-panel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG
|
|
1
|
+
{"version":3,"file":"motion-panel.js","sourceRoot":"","sources":["../../src/editor/motion-panel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiD/B,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6DhC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2jB9B,CAAC"}
|
package/dist/local-port.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type PortLane } from './port-lane.js';
|
|
2
2
|
/**
|
|
3
3
|
* The port window the platform's bucket CORS policy allowlists as an origin.
|
|
4
4
|
*
|
|
@@ -38,6 +38,18 @@ export declare const CORS_ALLOWED_PORT_MAX = 3199;
|
|
|
38
38
|
* line nominally owns that half would make the flag a suggestion for no benefit.
|
|
39
39
|
*/
|
|
40
40
|
export declare function parseLocalPort(value: string | undefined, fallback: number, flag: string): number;
|
|
41
|
+
/**
|
|
42
|
+
* Whether this exact port is free right now. Same TOCTOU caveat as `reservePortInLane` below.
|
|
43
|
+
*
|
|
44
|
+
* A port counts as free only when BOTH loopback families are free. Vite binds `localhost`, which
|
|
45
|
+
* Node resolves to `::1` on modern systems — so a running `bitmagic dev` holds only the IPv6 side
|
|
46
|
+
* of its port. Probing 127.0.0.1 alone once called such a port "free": `verify` then bound its own
|
|
47
|
+
* vite to the IPv4 side, `http://localhost:<port>/` resolved to `::1`, and the run drove — and
|
|
48
|
+
* graded — whichever OTHER project's dev server was already there, printing "Verification passed"
|
|
49
|
+
* for a game it never loaded. A machine without IPv6 reports the family as unavailable rather
|
|
50
|
+
* than the port as busy, and that must not mark every port taken.
|
|
51
|
+
*/
|
|
52
|
+
export declare function isPortFree(port: number): Promise<boolean>;
|
|
41
53
|
/**
|
|
42
54
|
* A free port in this install's lane, or `null` when every port in the lane is taken.
|
|
43
55
|
*
|
|
@@ -51,7 +63,7 @@ export declare function parseLocalPort(value: string | undefined, fallback: numb
|
|
|
51
63
|
* quietly. A hundred held ports is a machine with a problem to report, not a lane to abandon.
|
|
52
64
|
*
|
|
53
65
|
* The scan starts at a pseudo-random offset so two concurrent runs do not both take the lane's
|
|
54
|
-
* first port and race; `
|
|
66
|
+
* first port and race; `isPortFree` closing before the caller binds leaves a window either way,
|
|
55
67
|
* which is why callers must handle a bind failure rather than trusting this.
|
|
56
68
|
*/
|
|
57
69
|
export declare function reservePortInLane(lane: PortLane, exclude?: ReadonlySet<number>): Promise<number | null>;
|
|
@@ -63,8 +75,15 @@ export declare function reservePortInLane(lane: PortLane, exclude?: ReadonlySet<
|
|
|
63
75
|
* ports and has just been told a hundred of them are the limit.
|
|
64
76
|
*/
|
|
65
77
|
export declare function laneExhaustedMessage(lane: PortLane, remedy: string): string;
|
|
66
|
-
/**
|
|
67
|
-
|
|
78
|
+
/**
|
|
79
|
+
* A free port in THIS install's lane, or a `CliError` carrying `remedy` when the lane is full.
|
|
80
|
+
*
|
|
81
|
+
* What every command that serves the project for a real browser to load actually wants: `verify`
|
|
82
|
+
* and `forge` alike need a port inside the CDN's CORS window (see the file header) and have
|
|
83
|
+
* nothing useful to do with a `null`. Bundling the lane lookup, the scan and the refusal here
|
|
84
|
+
* keeps the three from drifting apart — a caller varies only what it tells the creator to do.
|
|
85
|
+
*/
|
|
86
|
+
export declare function reserveLanePort(remedy: string, exclude?: ReadonlySet<number>): Promise<number>;
|
|
68
87
|
/**
|
|
69
88
|
* The port to actually bind: `preferred` when it is free, otherwise another one in the window.
|
|
70
89
|
*
|
package/dist/local-port.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as net from 'net';
|
|
2
2
|
import { CliError } from './errors.js';
|
|
3
|
+
import { currentPortLane } from './port-lane.js';
|
|
3
4
|
/**
|
|
4
5
|
* The port window the platform's bucket CORS policy allowlists as an origin.
|
|
5
6
|
*
|
|
@@ -51,17 +52,37 @@ export function parseLocalPort(value, fallback, flag) {
|
|
|
51
52
|
}
|
|
52
53
|
return port;
|
|
53
54
|
}
|
|
54
|
-
|
|
55
|
+
/** `null` when the port bound cleanly on this host, otherwise the OS error code that refused it. */
|
|
56
|
+
function tryBind(port, host) {
|
|
55
57
|
return new Promise((resolve) => {
|
|
56
58
|
const server = net.createServer();
|
|
57
|
-
server.once('error', () => resolve(
|
|
58
|
-
server.listen(port,
|
|
59
|
-
|
|
60
|
-
const bound = address !== null && typeof address !== 'string' ? address.port : null;
|
|
61
|
-
server.close(() => resolve(bound));
|
|
59
|
+
server.once('error', (error) => resolve(error.code ?? 'UNKNOWN'));
|
|
60
|
+
server.listen(port, host, () => {
|
|
61
|
+
server.close(() => resolve(null));
|
|
62
62
|
});
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
|
+
/** Codes that mean "this machine has no such loopback family", not "this port is taken". */
|
|
66
|
+
const FAMILY_UNAVAILABLE_CODES = new Set(['EADDRNOTAVAIL', 'EAFNOSUPPORT']);
|
|
67
|
+
/**
|
|
68
|
+
* Whether this exact port is free right now. Same TOCTOU caveat as `reservePortInLane` below.
|
|
69
|
+
*
|
|
70
|
+
* A port counts as free only when BOTH loopback families are free. Vite binds `localhost`, which
|
|
71
|
+
* Node resolves to `::1` on modern systems — so a running `bitmagic dev` holds only the IPv6 side
|
|
72
|
+
* of its port. Probing 127.0.0.1 alone once called such a port "free": `verify` then bound its own
|
|
73
|
+
* vite to the IPv4 side, `http://localhost:<port>/` resolved to `::1`, and the run drove — and
|
|
74
|
+
* graded — whichever OTHER project's dev server was already there, printing "Verification passed"
|
|
75
|
+
* for a game it never loaded. A machine without IPv6 reports the family as unavailable rather
|
|
76
|
+
* than the port as busy, and that must not mark every port taken.
|
|
77
|
+
*/
|
|
78
|
+
export async function isPortFree(port) {
|
|
79
|
+
for (const host of ['127.0.0.1', '::1']) {
|
|
80
|
+
const code = await tryBind(port, host);
|
|
81
|
+
if (code !== null && !FAMILY_UNAVAILABLE_CODES.has(code))
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
65
86
|
/**
|
|
66
87
|
* A free port in this install's lane, or `null` when every port in the lane is taken.
|
|
67
88
|
*
|
|
@@ -75,7 +96,7 @@ function tryListen(port) {
|
|
|
75
96
|
* quietly. A hundred held ports is a machine with a problem to report, not a lane to abandon.
|
|
76
97
|
*
|
|
77
98
|
* The scan starts at a pseudo-random offset so two concurrent runs do not both take the lane's
|
|
78
|
-
* first port and race; `
|
|
99
|
+
* first port and race; `isPortFree` closing before the caller binds leaves a window either way,
|
|
79
100
|
* which is why callers must handle a bind failure rather than trusting this.
|
|
80
101
|
*/
|
|
81
102
|
export async function reservePortInLane(lane, exclude = new Set()) {
|
|
@@ -85,9 +106,8 @@ export async function reservePortInLane(lane, exclude = new Set()) {
|
|
|
85
106
|
const port = lane.min + ((start + i) % span);
|
|
86
107
|
if (exclude.has(port))
|
|
87
108
|
continue;
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return bound;
|
|
109
|
+
if (await isPortFree(port))
|
|
110
|
+
return port;
|
|
91
111
|
}
|
|
92
112
|
return null;
|
|
93
113
|
}
|
|
@@ -104,9 +124,20 @@ export function laneExhaustedMessage(lane, remedy) {
|
|
|
104
124
|
+ 'the other half is left free so a bitmagic from the other release line can run beside this '
|
|
105
125
|
+ `one. ${remedy}`);
|
|
106
126
|
}
|
|
107
|
-
/**
|
|
108
|
-
|
|
109
|
-
|
|
127
|
+
/**
|
|
128
|
+
* A free port in THIS install's lane, or a `CliError` carrying `remedy` when the lane is full.
|
|
129
|
+
*
|
|
130
|
+
* What every command that serves the project for a real browser to load actually wants: `verify`
|
|
131
|
+
* and `forge` alike need a port inside the CDN's CORS window (see the file header) and have
|
|
132
|
+
* nothing useful to do with a `null`. Bundling the lane lookup, the scan and the refusal here
|
|
133
|
+
* keeps the three from drifting apart — a caller varies only what it tells the creator to do.
|
|
134
|
+
*/
|
|
135
|
+
export async function reserveLanePort(remedy, exclude = new Set()) {
|
|
136
|
+
const lane = currentPortLane();
|
|
137
|
+
const port = await reservePortInLane(lane, exclude);
|
|
138
|
+
if (port === null)
|
|
139
|
+
throw new CliError(laneExhaustedMessage(lane, remedy));
|
|
140
|
+
return port;
|
|
110
141
|
}
|
|
111
142
|
/**
|
|
112
143
|
* The port to actually bind: `preferred` when it is free, otherwise another one in the window.
|
package/dist/local-port.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-port.js","sourceRoot":"","sources":["../src/local-port.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"local-port.js","sourceRoot":"","sources":["../src/local-port.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,eAAe,EAAiB,MAAM,gBAAgB,CAAC;AAEhE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAC1C,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAE1C;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,cAAc,CAAC,KAAyB,EAAE,QAAgB,EAAE,IAAY;IACtF,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IACzC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,QAAQ,CAAC,KAAK,IAAI,mCAAmC,KAAK,IAAI,CAAC,CAAC;IAC5E,CAAC;IACD,IAAI,IAAI,GAAG,qBAAqB,IAAI,IAAI,GAAG,qBAAqB,EAAE,CAAC;QACjE,MAAM,IAAI,QAAQ,CAChB,KAAK,IAAI,sBAAsB,qBAAqB,QAAQ,qBAAqB,IAAI;cACnF,8FAA8F,CACjG,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,oGAAoG;AACpG,SAAS,OAAO,CAAC,IAAY,EAAE,IAAY;IACzC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,MAAM,GAAG,GAAG,CAAC,YAAY,EAAE,CAAC;QAClC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,KAAgC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC;QAC7F,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE;YAC7B,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,4FAA4F;AAC5F,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC,CAAC,eAAe,EAAE,cAAc,CAAC,CAAC,CAAC;AAE5E;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,IAAY;IAC3C,KAAK,MAAM,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC;QACxC,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACvC,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,wBAAwB,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,OAAO,KAAK,CAAC;IACzE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,IAAc,EACd,UAA+B,IAAI,GAAG,EAAE;IAExC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;IACrC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACjC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,SAAS;QAChC,IAAI,MAAM,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC;IAC1C,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB,CAAC,IAAc,EAAE,MAAc;IACjE,OAAO,CACL,mBAAmB,IAAI,CAAC,GAAG,OAAO,IAAI,CAAC,GAAG,6CAA6C;UACrF,GAAG,qBAAqB,IAAI,qBAAqB,8CAA8C;UAC/F,4FAA4F;UAC5F,QAAQ,MAAM,EAAE,CACnB,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAc,EACd,UAA+B,IAAI,GAAG,EAAE;IAExC,MAAM,IAAI,GAAG,eAAe,EAAE,CAAC;IAC/B,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACpD,IAAI,IAAI,KAAK,IAAI;QAAE,MAAM,IAAI,QAAQ,CAAC,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,SAAiB,EACjB,IAAc,EACd,UAA+B,IAAI,GAAG,EAAE;IAExC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,MAAM,UAAU,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IAC7E,OAAO,iBAAiB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC1C,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** One file from the export's `source/`, keyed by its path RELATIVE to that directory. */
|
|
2
|
+
export interface ExportSourceFile {
|
|
3
|
+
/** Forward-slash separated, e.g. `Game.ts` or `levels/level-2.json`. */
|
|
4
|
+
path: string;
|
|
5
|
+
contents: Uint8Array;
|
|
6
|
+
}
|
|
7
|
+
export interface CreatorExport {
|
|
8
|
+
/** The game's id on the Creator's api-server — the row a CLI project can adopt. */
|
|
9
|
+
gameId: string;
|
|
10
|
+
genre: string;
|
|
11
|
+
/** The engine the game was last edited against, or null when the export predates the field. */
|
|
12
|
+
engineVersion: string | null;
|
|
13
|
+
/** The Creator template the game began from (`metadata.importedFrom`), or null. */
|
|
14
|
+
template: string | null;
|
|
15
|
+
/** `game.json`'s `gameName`, for the summary. Null when absent or unreadable. */
|
|
16
|
+
gameName: string | null;
|
|
17
|
+
/** Every file under `<gameId>/source/`, with `.git` already dropped. */
|
|
18
|
+
sourceFiles: ExportSourceFile[];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Read and validate the export at `zipPath`.
|
|
22
|
+
*
|
|
23
|
+
* Every failure is a CliError naming the file, because all of them mean the same thing to a
|
|
24
|
+
* creator: this is not an export the CLI can convert, and nothing has been written yet.
|
|
25
|
+
*/
|
|
26
|
+
export declare function readCreatorExport(zipPath: string): CreatorExport;
|
|
27
|
+
/**
|
|
28
|
+
* The hosts serving assets that belong to THIS game — http(s) URLs in `world.json` and
|
|
29
|
+
* `game.json` whose path carries the game's own id.
|
|
30
|
+
*
|
|
31
|
+
* Read for one reason: a game's assets are minted under `worlds/v3/<gameId>/` by the api-server
|
|
32
|
+
* that hosts the Creator, and so is the game row a CLI project adopts by id. Importing a dev game
|
|
33
|
+
* into a project pinned to prod produces something that builds, runs and then fails every server
|
|
34
|
+
* command with a flat "not found or is not owned by the caller" — the one failure this conversion
|
|
35
|
+
* can see coming and the creator cannot. The caller compares these against the environment it
|
|
36
|
+
* resolved; nothing here decides anything.
|
|
37
|
+
*
|
|
38
|
+
* **The gameId filter is the whole point, not a refinement.** Every game — on every environment —
|
|
39
|
+
* references shared defaults that live on prod: `mini.bitmagic.ai/worlds/v3/BaseCharacter.glb` is
|
|
40
|
+
* in the game.json of a dev game and a prod game alike. Classifying on "any bitmagic host" reads
|
|
41
|
+
* that one line and calls every dev export a prod game, which is precisely the mistake this check
|
|
42
|
+
* exists to prevent. Only a URL carrying the game's own id was minted for this game, by the
|
|
43
|
+
* api-server that owns it.
|
|
44
|
+
*
|
|
45
|
+
* Named for what it returns rather than `assetHosts`, which is `mobile/asset-hosts.ts` — a
|
|
46
|
+
* different question (which hosts the LAN bridge proxies for a phone) about the same URLs.
|
|
47
|
+
*/
|
|
48
|
+
export declare function gameAssetHosts(source: CreatorExport): string[];
|