hyperframes 0.7.4 → 0.7.5

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/cli.js CHANGED
@@ -50,7 +50,7 @@ var VERSION;
50
50
  var init_version = __esm({
51
51
  "src/version.ts"() {
52
52
  "use strict";
53
- VERSION = true ? "0.7.4" : "0.0.0-dev";
53
+ VERSION = true ? "0.7.5" : "0.0.0-dev";
54
54
  }
55
55
  });
56
56
 
@@ -25071,8 +25071,16 @@ function findHtmlTag(source) {
25071
25071
  };
25072
25072
  }
25073
25073
  function findRootTag(source) {
25074
- const bodyOpenMatch = /<body\b[^>]*>/i.exec(source);
25074
+ const bodyOpenMatch = /<body\b([^>]*)>/i.exec(source);
25075
25075
  const bodyCloseMatch = /<\/body>/i.exec(source);
25076
+ if (bodyOpenMatch && (readAttr(bodyOpenMatch[0], "data-composition-id") || readAttr(bodyOpenMatch[0], "data-width") || readAttr(bodyOpenMatch[0], "data-height"))) {
25077
+ return {
25078
+ raw: bodyOpenMatch[0],
25079
+ name: "body",
25080
+ attrs: bodyOpenMatch[1] ?? "",
25081
+ index: bodyOpenMatch.index
25082
+ };
25083
+ }
25076
25084
  const bodyStart = bodyOpenMatch ? bodyOpenMatch.index + bodyOpenMatch[0].length : 0;
25077
25085
  const bodyEnd = bodyOpenMatch && bodyCloseMatch && bodyCloseMatch.index > bodyStart ? bodyCloseMatch.index : source.length;
25078
25086
  const bodyContent = bodyOpenMatch ? source.slice(bodyStart, bodyEnd) : source;
@@ -26137,6 +26145,30 @@ function isHiddenGsapState(values) {
26137
26145
  const display = stringValue(values.display)?.toLowerCase();
26138
26146
  return zeroValue(values.opacity) || zeroValue(values.autoAlpha) || visibility === "hidden" || display === "none";
26139
26147
  }
26148
+ function oneValue(values, keys2) {
26149
+ for (const key2 of keys2) {
26150
+ const value = values[key2];
26151
+ if (value !== void 0) return value;
26152
+ }
26153
+ return void 0;
26154
+ }
26155
+ function isVisibleGsapState(values) {
26156
+ const opacity = oneValue(values, ["opacity", "autoAlpha"]);
26157
+ if (typeof opacity === "number") return opacity > 0;
26158
+ if (typeof opacity === "string" && opacity.trim()) {
26159
+ const numeric = Number(opacity);
26160
+ if (Number.isFinite(numeric)) return numeric > 0;
26161
+ }
26162
+ const visibility = stringValue(values.visibility)?.toLowerCase();
26163
+ if (visibility === "visible" || visibility === "inherit") return true;
26164
+ const display = stringValue(values.display)?.toLowerCase();
26165
+ if (display && display !== "none") return true;
26166
+ return false;
26167
+ }
26168
+ function makesOverlayVisible(win) {
26169
+ if (win.method === "from" && isHiddenGsapState(win.propertyValues)) return true;
26170
+ return isVisibleGsapState(win.propertyValues);
26171
+ }
26140
26172
  function isSceneBoundaryExit(win) {
26141
26173
  if (win.end <= win.position) return false;
26142
26174
  if (win.method !== "to" && win.method !== "fromTo") return false;
@@ -26225,6 +26257,67 @@ function getSingleClassSelector(selector) {
26225
26257
  const match = selector.trim().match(/^\.(?<name>[A-Za-z0-9_-]+)$/);
26226
26258
  return match?.groups?.name || null;
26227
26259
  }
26260
+ function readStyleProperty(style, property) {
26261
+ const escapedProperty = property.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26262
+ const match = style.match(new RegExp(`(?:^|;)\\s*${escapedProperty}\\s*:\\s*([^;]+)`, "i"));
26263
+ return match?.[1]?.trim() || null;
26264
+ }
26265
+ function cssZero(value) {
26266
+ if (!value) return false;
26267
+ return /^0(?:\.0+)?(?:px|%|vw|vh|rem|em)?$/i.test(value.trim());
26268
+ }
26269
+ function styleHasHiddenInitialState(style) {
26270
+ const opacity = readStyleProperty(style, "opacity");
26271
+ if (opacity && Number(opacity) === 0) return true;
26272
+ if (readStyleProperty(style, "visibility")?.toLowerCase() === "hidden") return true;
26273
+ if (readStyleProperty(style, "display")?.toLowerCase() === "none") return true;
26274
+ return false;
26275
+ }
26276
+ function styleHasOpaqueBackground(style) {
26277
+ const background = readStyleProperty(style, "background") || readStyleProperty(style, "background-color");
26278
+ if (!background) return false;
26279
+ const normalized = background.toLowerCase().replace(/\s+/g, "");
26280
+ if (normalized === "transparent" || normalized === "none") return false;
26281
+ if (/rgba?\([^)]*,0(?:\.0+)?\)$/.test(normalized)) return false;
26282
+ if (/hsla?\([^)]*,0(?:\.0+)?\)$/.test(normalized)) return false;
26283
+ return true;
26284
+ }
26285
+ function styleLooksFullFrameOverlay(style) {
26286
+ const position = readStyleProperty(style, "position")?.toLowerCase();
26287
+ if (position !== "fixed" && position !== "absolute") return false;
26288
+ const coversFrame = cssZero(readStyleProperty(style, "inset")) || cssZero(readStyleProperty(style, "top")) && cssZero(readStyleProperty(style, "right")) && cssZero(readStyleProperty(style, "bottom")) && cssZero(readStyleProperty(style, "left"));
26289
+ return coversFrame && styleHasOpaqueBackground(style);
26290
+ }
26291
+ function collectSimpleStyleRules(styles) {
26292
+ const rules = /* @__PURE__ */ new Map();
26293
+ for (const style of styles) {
26294
+ for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) {
26295
+ if (!selectorList || !body) continue;
26296
+ for (const selector of selectorList.split(",")) {
26297
+ const token = selector.trim();
26298
+ if (!/^[#.][A-Za-z0-9_-]+$/.test(token)) continue;
26299
+ rules.set(token, `${rules.get(token) || ""};${body}`);
26300
+ }
26301
+ }
26302
+ }
26303
+ return rules;
26304
+ }
26305
+ function tagSimpleSelectors(tag) {
26306
+ const selectors = [];
26307
+ const id = readAttr(tag.raw, "id");
26308
+ if (id) selectors.push(`#${id}`);
26309
+ const classes = readAttr(tag.raw, "class")?.split(/\s+/).filter(Boolean) ?? [];
26310
+ for (const className of classes) selectors.push(`.${className}`);
26311
+ return selectors;
26312
+ }
26313
+ function combinedTagStyle(tag, styleRules) {
26314
+ const styles = [readAttr(tag.raw, "style") || ""];
26315
+ for (const selector of tagSimpleSelectors(tag)) {
26316
+ const ruleStyle = styleRules.get(selector);
26317
+ if (ruleStyle) styles.push(ruleStyle);
26318
+ }
26319
+ return styles.filter(Boolean).join(";");
26320
+ }
26228
26321
  function cssTransformToGsapProps(cssTransform) {
26229
26322
  const parts = [];
26230
26323
  const translateMatch = cssTransform.match(
@@ -26299,7 +26392,7 @@ var init_gsap = __esm({
26299
26392
  gsapRules = [
26300
26393
  // overlapping_gsap_tweens + gsap_animates_clip_element + unscoped_gsap_selector
26301
26394
  // fallow-ignore-next-line complexity
26302
- async ({ source, tags, scripts, rootCompositionId }) => {
26395
+ async ({ source, tags, scripts, styles, rootCompositionId }) => {
26303
26396
  const findings = [];
26304
26397
  const clipIds = /* @__PURE__ */ new Map();
26305
26398
  const clipClasses = /* @__PURE__ */ new Map();
@@ -26320,6 +26413,8 @@ var init_gsap = __esm({
26320
26413
  }
26321
26414
  const classUsage = countClassUsage(tags);
26322
26415
  const clipStartBoundariesByComposition = collectClipStartBoundariesByComposition(source, tags);
26416
+ const styleRules = collectSimpleStyleRules(styles);
26417
+ const reportedVisibleOverlayKeys = /* @__PURE__ */ new Set();
26323
26418
  for (const script of scripts) {
26324
26419
  const localTimelineCompId = readRegisteredTimelineCompositionId(script.content);
26325
26420
  const gsapWindows = await cachedExtractGsapWindows(script.content);
@@ -26371,6 +26466,45 @@ ${right.raw}`)
26371
26466
  });
26372
26467
  }
26373
26468
  }
26469
+ for (const tag of tags) {
26470
+ const selectors = tagSimpleSelectors(tag);
26471
+ if (selectors.length === 0) continue;
26472
+ const overlayKey = readAttr(tag.raw, "id") || String(tag.index);
26473
+ if (reportedVisibleOverlayKeys.has(overlayKey)) continue;
26474
+ const authoredStyle = combinedTagStyle(tag, styleRules);
26475
+ if (!authoredStyle || !styleLooksFullFrameOverlay(authoredStyle)) continue;
26476
+ if (styleHasHiddenInitialState(authoredStyle)) continue;
26477
+ const visibilityWindows = gsapWindows.filter((win) => {
26478
+ const tokens = targetedSelectorTokens(win.targetSelector);
26479
+ if (!selectors.some((selector2) => tokens.has(selector2))) return false;
26480
+ return win.properties.some(
26481
+ (prop2) => ["opacity", "autoAlpha", "visibility", "display"].includes(prop2)
26482
+ );
26483
+ }).sort((a, b2) => a.position - b2.position);
26484
+ const startsHiddenAtZero = visibilityWindows.some(
26485
+ (win) => win.position <= SCENE_BOUNDARY_EPSILON_SECONDS && isHiddenGsapState(win.propertyValues)
26486
+ );
26487
+ if (startsHiddenAtZero) continue;
26488
+ const firstVisible = visibilityWindows.find((win) => makesOverlayVisible(win));
26489
+ if (!firstVisible) continue;
26490
+ const selector = selectors.find(
26491
+ (candidate) => targetedSelectorTokens(firstVisible.targetSelector).has(candidate)
26492
+ ) || selectors[0] || tag.name;
26493
+ const laterHidden = visibilityWindows.some(
26494
+ (win) => win.position >= firstVisible.position && isHiddenGsapState(win.propertyValues)
26495
+ );
26496
+ if (firstVisible.method !== "from" && !laterHidden) continue;
26497
+ reportedVisibleOverlayKeys.add(overlayKey);
26498
+ findings.push({
26499
+ code: "gsap_fullscreen_overlay_starts_visible",
26500
+ severity: "error",
26501
+ message: `Full-frame overlay "${selector}" starts visible before its first GSAP opacity tween at ${firstVisible.position.toFixed(2)}s. It will cover earlier render frames, often as a blank/white video.`,
26502
+ selector,
26503
+ elementId: readAttr(tag.raw, "id") || void 0,
26504
+ fixHint: `Add \`opacity: 0\` to "${selector}" in CSS/inline styles, or add \`tl.set("${selector}", { opacity: 0 }, 0)\` before the reveal tween.`,
26505
+ snippet: truncateSnippet(firstVisible.raw)
26506
+ });
26507
+ }
26374
26508
  for (const win of gsapWindows) {
26375
26509
  const sel = win.targetSelector;
26376
26510
  const clipInfo = clipIds.get(sel) || clipClasses.get(sel);
@@ -34596,7 +34730,11 @@ function getCapturePerfSummary(session) {
34596
34730
  staticDedupSkipReason: session.staticDedupSkipReason
34597
34731
  };
34598
34732
  }
34599
- var BROWSER_CONSOLE_BUFFER_SIZE, CAPTURE_SESSION_CLOSE_TIMEOUT_MS, LOCKED_WARMUP_TICKS, realSleep, HF_READY_DIAGNOSTIC_EXPR;
34733
+ function isTransientBrowserError(error) {
34734
+ const message = error instanceof Error ? error.message : String(error);
34735
+ return TRANSIENT_BROWSER_ERROR_PATTERNS.some((pattern) => pattern.test(message));
34736
+ }
34737
+ var BROWSER_CONSOLE_BUFFER_SIZE, CAPTURE_SESSION_CLOSE_TIMEOUT_MS, LOCKED_WARMUP_TICKS, realSleep, HF_READY_DIAGNOSTIC_EXPR, TRANSIENT_BROWSER_ERROR_PATTERNS;
34600
34738
  var init_frameCapture = __esm({
34601
34739
  "../engine/src/services/frameCapture.ts"() {
34602
34740
  "use strict";
@@ -34627,6 +34765,17 @@ var init_frameCapture = __esm({
34627
34765
  declaredDuration: declaredDuration,
34628
34766
  };
34629
34767
  })()`;
34768
+ TRANSIENT_BROWSER_ERROR_PATTERNS = [
34769
+ /Navigating frame was detached/i,
34770
+ /Target closed/i,
34771
+ /Session closed/i,
34772
+ /browser has disconnected/i,
34773
+ /Page crashed/i,
34774
+ /Execution context was destroyed/i,
34775
+ /Cannot find context with specified id/i,
34776
+ /Failed to launch the browser process/i,
34777
+ /ECONNREFUSED/i
34778
+ ];
34630
34779
  }
34631
34780
  });
34632
34781
 
@@ -41885,6 +42034,7 @@ __export(src_exports2, {
41885
42034
  isHdrColorSpace: () => isHdrColorSpace,
41886
42035
  isHttpUrl: () => isHttpUrl,
41887
42036
  isLowMemorySystem: () => isLowMemorySystem,
42037
+ isTransientBrowserError: () => isTransientBrowserError,
41888
42038
  isVideoFrameFormat: () => isVideoFrameFormat,
41889
42039
  killTrackedProcesses: () => killTrackedProcesses,
41890
42040
  launchHdrBrowser: () => launchHdrBrowser,
@@ -96387,33 +96537,71 @@ async function runProbeStage(input2) {
96387
96537
  quality: needsAlpha ? void 0 : 80,
96388
96538
  deviceScaleFactor
96389
96539
  };
96390
- log2.info("Browser launched, creating capture session...");
96391
- probeSession = await createCaptureSession(
96392
- fileServer.url,
96393
- join44(workDir, "probe"),
96394
- captureOpts,
96395
- null,
96396
- probeCfg
96397
- );
96398
- log2.info("Waiting for composition to initialize...");
96399
- const initStart = Date.now();
96400
- const heartbeat = setInterval(() => {
96401
- const elapsed = ((Date.now() - initStart) / 1e3).toFixed(1);
96402
- log2.info(`Still waiting for browser initialization... (${elapsed}s elapsed)`);
96403
- }, 3e4);
96404
- try {
96405
- await initializeSession(probeSession);
96406
- } finally {
96407
- clearInterval(heartbeat);
96540
+ const PROBE_MAX_ATTEMPTS = 2;
96541
+ for (let attempt = 1; attempt <= PROBE_MAX_ATTEMPTS; attempt++) {
96542
+ const attemptStart = Date.now();
96543
+ try {
96544
+ log2.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
96545
+ probeSession = await createCaptureSession(
96546
+ fileServer.url,
96547
+ join44(workDir, "probe"),
96548
+ captureOpts,
96549
+ null,
96550
+ probeCfg
96551
+ );
96552
+ log2.info("Waiting for composition to initialize...", { attempt });
96553
+ const heartbeat = setInterval(() => {
96554
+ const elapsed = ((Date.now() - attemptStart) / 1e3).toFixed(1);
96555
+ log2.info(`Still waiting for browser initialization... (${elapsed}s elapsed)`);
96556
+ }, 3e4);
96557
+ try {
96558
+ await initializeSession(probeSession);
96559
+ } finally {
96560
+ clearInterval(heartbeat);
96561
+ }
96562
+ } catch (err) {
96563
+ const isTransient = isTransientBrowserError(err);
96564
+ const errMsg = err instanceof Error ? err.message : String(err);
96565
+ log2.warn("Browser probe attempt failed", {
96566
+ attempt,
96567
+ maxAttempts: PROBE_MAX_ATTEMPTS,
96568
+ isTransient,
96569
+ error: errMsg,
96570
+ elapsedMs: Date.now() - attemptStart
96571
+ });
96572
+ if (probeSession) {
96573
+ try {
96574
+ await closeCaptureSession(probeSession);
96575
+ } catch (closeErr) {
96576
+ log2.warn("Failed to close crashed probe session", {
96577
+ error: closeErr instanceof Error ? closeErr.message : String(closeErr)
96578
+ });
96579
+ }
96580
+ probeSession = null;
96581
+ }
96582
+ if (isTransient && attempt < PROBE_MAX_ATTEMPTS) {
96583
+ log2.info("Retrying with a fresh browser session...", {
96584
+ attempt: attempt + 1,
96585
+ maxAttempts: PROBE_MAX_ATTEMPTS
96586
+ });
96587
+ assertNotAborted();
96588
+ continue;
96589
+ }
96590
+ throw err;
96591
+ }
96592
+ log2.info("Composition ready", {
96593
+ attempt,
96594
+ initMs: Date.now() - attemptStart
96595
+ });
96596
+ break;
96408
96597
  }
96409
- log2.info("Composition ready", {
96410
- initMs: Date.now() - initStart
96411
- });
96412
96598
  assertNotAborted();
96413
- lastBrowserConsole = probeSession.browserConsoleBuffer;
96599
+ const session = probeSession;
96600
+ probeSession = session;
96601
+ lastBrowserConsole = session.browserConsoleBuffer;
96414
96602
  if (composition.duration <= 0) {
96415
96603
  log2.info("Discovering composition duration...");
96416
- const discoveredDuration = await getCompositionDuration(probeSession);
96604
+ const discoveredDuration = await getCompositionDuration(session);
96417
96605
  assertNotAborted();
96418
96606
  log2.info("Probed composition duration from browser", {
96419
96607
  discoveredDuration,
@@ -96427,7 +96615,7 @@ async function runProbeStage(input2) {
96427
96615
  }
96428
96616
  if (compiled.unresolvedCompositions.length > 0) {
96429
96617
  const resolutions = await resolveCompositionDurations(
96430
- probeSession.page,
96618
+ session.page,
96431
96619
  compiled.unresolvedCompositions
96432
96620
  );
96433
96621
  assertNotAborted();
@@ -96446,7 +96634,7 @@ async function runProbeStage(input2) {
96446
96634
  }
96447
96635
  }
96448
96636
  log2.info("Discovering media assets from browser DOM...");
96449
- const browserMedia = await discoverMediaFromBrowser(probeSession.page);
96637
+ const browserMedia = await discoverMediaFromBrowser(session.page);
96450
96638
  assertNotAborted();
96451
96639
  if (browserMedia.length > 0) {
96452
96640
  const existingVideoIds = new Set(composition.videos.map((v2) => v2.id));
@@ -96537,7 +96725,7 @@ async function runProbeStage(input2) {
96537
96725
  audioCount: composition.audios.length
96538
96726
  });
96539
96727
  const automation = await discoverAudioVolumeAutomationFromTimeline(
96540
- probeSession.page,
96728
+ session.page,
96541
96729
  composition.audios.map((audio) => audio.id),
96542
96730
  composition.duration,
96543
96731
  fpsToNumber(job.config.fps)
@@ -96560,7 +96748,7 @@ async function runProbeStage(input2) {
96560
96748
  videoCount: composition.videos.length
96561
96749
  });
96562
96750
  const visibilityWindows = await discoverVideoVisibilityFromTimeline(
96563
- probeSession.page,
96751
+ session.page,
96564
96752
  composition.duration
96565
96753
  );
96566
96754
  assertNotAborted();
@@ -1,4 +1,4 @@
1
- var pe=Object.defineProperty;var me=(r,t,e)=>t in r?pe(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var u=(r,t,e)=>me(r,typeof t!="symbol"?t+"":t,e);function fe(r){return r.hasRuntime||r.runtimeInjected?!1:!!(r.hasNestedCompositions||r.hasTimelines&&r.attempts>=5)}function F(r){return typeof r=="object"&&r!==null}function _e(r){return F(r)&&typeof r.getDuration=="function"}function ge(r){return F(r)&&typeof r.duration=="function"&&typeof r.time=="function"&&typeof r.seek=="function"&&typeof r.play=="function"&&typeof r.pause=="function"}const ve="https://cdn.jsdelivr.net/npm/@hyperframes/core/dist/hyperframe.runtime.iife.js";function U(r){if(r===null)return null;const t=Number.parseInt(r,10);return Number.isFinite(t)&&t>0?t:null}function be(r){const t=(r==null?void 0:r.querySelector("[data-composition-id][data-width][data-height]"))??(r==null?void 0:r.querySelector("[data-width][data-height]"));if(!t)return null;const e=U(t.getAttribute("data-width")),i=U(t.getAttribute("data-height"));return e!==null&&i!==null?{width:e,height:i}:null}class ye{constructor(t,e){u(this,"_interval",null);u(this,"_runtimeInjected",!1);this._iframe=t,this._callbacks=e}get runtimeInjected(){return this._runtimeInjected}start(){this.stop(),this._runtimeInjected=!1;let t=0;this._interval=setInterval(()=>{var e;t++;try{const i=this._iframe.contentWindow;if(!i)return;const s=!!(i.__hf||i.__player),n=!!(i.__timelines&&Object.keys(i.__timelines).length>0),o=!!((e=this._iframe.contentDocument)!=null&&e.querySelector("[data-composition-src]"));if(fe({hasRuntime:s,hasTimelines:n,hasNestedCompositions:o,runtimeInjected:this._runtimeInjected,attempts:t})){this._injectRuntime();return}if(this._runtimeInjected&&!s)return;const d=this._resolvePlaybackDurationAdapter(i);if(d&&d.getDuration()>0){this.stop();const c=be(this._iframe.contentDocument);this._callbacks.onReady({duration:d.getDuration(),adapter:d,compositionSize:c});return}}catch{}t>=40&&(this.stop(),this._callbacks.onError("Composition timeline not found after 8s"))},200)}stop(){this._interval!==null&&(clearInterval(this._interval),this._interval=null)}resolveDirectTimelineAdapter(){try{const t=this._iframe.contentWindow;return t?this._resolveDirectTimelineAdapterFromWindow(t):null}catch{return null}}resolveDirectTimelineAdapterFromWindow(t){return this._resolveDirectTimelineAdapterFromWindow(t)}hasRuntimeBridge(t){return Reflect.get(t,"__hf")!==void 0||F(Reflect.get(t,"__player"))}_injectRuntime(){var t,e;this._runtimeInjected=!0;try{const i=this._iframe.contentDocument;if(!i)return;const s=i.createElement("script");s.src=ve,(i.head||i.documentElement).appendChild(s),(e=(t=this._callbacks).onRuntimeInjected)==null||e.call(t)}catch{}}_resolveDirectTimelineAdapterFromWindow(t){var d,c;if(this.hasRuntimeBridge(t))return null;const e=Reflect.get(t,"__timelines");if(!F(e))return null;const i=Object.keys(e);if(i.length===0)return null;const s=(c=(d=this._iframe.contentDocument)==null?void 0:d.querySelector("[data-composition-id]"))==null?void 0:c.getAttribute("data-composition-id"),n=s&&s in e?s:i[i.length-1],o=e[n];return ge(o)?o:null}_resolvePlaybackDurationAdapter(t){const e=Reflect.get(t,"__player");if(_e(e))return{kind:"runtime",getDuration:()=>e.getDuration()};const i=this._resolveDirectTimelineAdapterFromWindow(t);return i?{kind:"direct-timeline",timeline:i,getDuration:()=>i.duration()}:null}}const we=`
1
+ var pe=Object.defineProperty;var me=(r,t,e)=>t in r?pe(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var u=(r,t,e)=>me(r,typeof t!="symbol"?t+"":t,e);function fe(r){return r.hasRuntime||r.runtimeInjected?!1:!!(r.hasNestedCompositions||r.hasTimelines&&r.attempts>=5)}function F(r){return typeof r=="object"&&r!==null}function _e(r){return F(r)&&typeof r.getDuration=="function"}function ge(r){return F(r)&&typeof r.duration=="function"&&typeof r.time=="function"&&typeof r.seek=="function"&&typeof r.play=="function"&&typeof r.pause=="function"}const ve="https://cdn.jsdelivr.net/npm/@hyperframes/core/dist/hyperframe.runtime.iife.js";function U(r){if(r===null)return null;const t=Number.parseInt(r,10);return Number.isFinite(t)&&t>0?t:null}function ye(r){const t=(r==null?void 0:r.querySelector("[data-composition-id][data-width][data-height]"))??(r==null?void 0:r.querySelector("[data-width][data-height]"));if(!t)return null;const e=U(t.getAttribute("data-width")),i=U(t.getAttribute("data-height"));return e!==null&&i!==null?{width:e,height:i}:null}class be{constructor(t,e){u(this,"_interval",null);u(this,"_runtimeInjected",!1);this._iframe=t,this._callbacks=e}get runtimeInjected(){return this._runtimeInjected}start(){this.stop(),this._runtimeInjected=!1;let t=0;this._interval=setInterval(()=>{var e;t++;try{const i=this._iframe.contentWindow;if(!i)return;const s=!!(i.__hf||i.__player),n=!!(i.__timelines&&Object.keys(i.__timelines).length>0),o=!!((e=this._iframe.contentDocument)!=null&&e.querySelector("[data-composition-src]"));if(fe({hasRuntime:s,hasTimelines:n,hasNestedCompositions:o,runtimeInjected:this._runtimeInjected,attempts:t})){this._injectRuntime();return}if(this._runtimeInjected&&!s)return;const d=this._resolvePlaybackDurationAdapter(i);if(d&&d.getDuration()>0){this.stop();const c=ye(this._iframe.contentDocument);this._callbacks.onReady({duration:d.getDuration(),adapter:d,compositionSize:c});return}}catch{}t>=40&&(this.stop(),this._callbacks.onError("Composition timeline not found after 8s"))},200)}stop(){this._interval!==null&&(clearInterval(this._interval),this._interval=null)}resolveDirectTimelineAdapter(){try{const t=this._iframe.contentWindow;return t?this._resolveDirectTimelineAdapterFromWindow(t):null}catch{return null}}resolveDirectTimelineAdapterFromWindow(t){return this._resolveDirectTimelineAdapterFromWindow(t)}hasRuntimeBridge(t){return Reflect.get(t,"__hf")!==void 0||F(Reflect.get(t,"__player"))}_injectRuntime(){var t,e;this._runtimeInjected=!0;try{const i=this._iframe.contentDocument;if(!i)return;const s=i.createElement("script");s.src=ve,(i.head||i.documentElement).appendChild(s),(e=(t=this._callbacks).onRuntimeInjected)==null||e.call(t)}catch{}}_resolveDirectTimelineAdapterFromWindow(t){var d,c;if(this.hasRuntimeBridge(t))return null;const e=Reflect.get(t,"__timelines");if(!F(e))return null;const i=Object.keys(e);if(i.length===0)return null;const s=(c=(d=this._iframe.contentDocument)==null?void 0:d.querySelector("[data-composition-id]"))==null?void 0:c.getAttribute("data-composition-id"),n=s&&s in e?s:i[i.length-1],o=e[n];return ge(o)?o:null}_resolvePlaybackDurationAdapter(t){const e=Reflect.get(t,"__player");if(_e(e))return{kind:"runtime",getDuration:()=>e.getDuration()};const i=this._resolveDirectTimelineAdapterFromWindow(t);return i?{kind:"direct-timeline",timeline:i,getDuration:()=>i.duration()}:null}}const we=`
2
2
  :host {
3
3
  display: block;
4
4
  position: relative;
@@ -422,4 +422,4 @@ var pe=Object.defineProperty;var me=(r,t,e)=>t in r?pe(r,t,{enumerable:!0,config
422
422
  background: var(--hfp-accent, #fff);
423
423
  pointer-events: none;
424
424
  }
425
- `,ne='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><polygon points="4,2 16,9 4,16"/></svg>',Ae='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><rect x="3" y="2" width="4" height="14"/><rect x="11" y="2" width="4" height="14"/></svg>',oe='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/><path d="M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',ae='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',Ee='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z" opacity="0.3"/><line x1="18" y1="7" x2="14" y2="17" stroke="currentColor" stroke-width="2"/></svg>',Ce=[.25,.5,1,1.5,2,4];function H(r){return Number.isInteger(r)?`${r}x`:`${r}x`}function de(r){if(!Number.isFinite(r)||r<0)return"0:00";const t=Math.floor(r),e=Math.floor(t/60),i=t%60;return`${e}:${i.toString().padStart(2,"0")}`}function Te(r,t,e={}){const i=e.speedPresets??Ce,s=document.createElement("div");s.className="hfp-controls",s.addEventListener("click",a=>{a.stopPropagation()});const n=document.createElement("button");n.className="hfp-play-btn",n.type="button",n.innerHTML=ne,n.setAttribute("aria-label","Play");const o=document.createElement("div");o.className="hfp-scrubber";const d=document.createElement("div");d.className="hfp-progress",d.style.width="0%",o.appendChild(d);const c=document.createElement("span");c.className="hfp-time",c.textContent="0:00 / 0:00";const p=document.createElement("div");p.className="hfp-speed-wrap";const h=document.createElement("button");h.className="hfp-speed-btn",h.type="button",h.textContent="1x",h.setAttribute("aria-label","Playback speed");const g=document.createElement("div");g.className="hfp-speed-menu",g.setAttribute("role","menu");for(const a of i){const l=document.createElement("button");l.className="hfp-speed-option",l.type="button",l.setAttribute("role","menuitem"),l.dataset.speed=String(a),l.textContent=H(a),a===1&&l.classList.add("hfp-active"),g.appendChild(l)}p.appendChild(g),p.appendChild(h);const v=document.createElement("div");v.className="hfp-volume-wrap";const f=document.createElement("button");f.className="hfp-mute-btn",f.type="button",f.innerHTML=oe,f.setAttribute("aria-label","Mute");const y=document.createElement("div");y.className="hfp-volume-slider-wrap";const m=document.createElement("div");m.className="hfp-volume-slider",m.setAttribute("role","slider"),m.setAttribute("aria-label","Volume"),m.setAttribute("aria-valuemin","0"),m.setAttribute("aria-valuemax","100"),m.setAttribute("aria-valuenow","100"),m.tabIndex=0;const b=document.createElement("div");b.className="hfp-volume-fill",b.style.width="100%",m.appendChild(b),y.appendChild(m),v.appendChild(y),v.appendChild(f),e.audioLocked&&(v.style.display="none"),s.appendChild(n),s.appendChild(o),s.appendChild(c),s.appendChild(v),s.appendChild(p),r.appendChild(s);let L=!1,E=!1,A=1,x=null;i.indexOf(1);const P=(a,l)=>a?Ee:l===0||l<.5?ae:oe;n.addEventListener("click",a=>{a.stopPropagation(),L?t.onPause():t.onPlay()}),f.addEventListener("click",a=>{a.stopPropagation(),t.onMuteToggle()});let C=!1;const R=a=>{const l=m.getBoundingClientRect(),_=Math.max(0,Math.min(1,(a-l.left)/l.width));A=_,b.style.width=`${_*100}%`,m.setAttribute("aria-valuenow",String(Math.round(_*100))),E&&_>0&&t.onMuteToggle(),f.innerHTML=P(E,_),t.onVolumeChange(_)};m.addEventListener("mousedown",a=>{a.stopPropagation(),C=!0,R(a.clientX)});const q=a=>{C&&R(a.clientX)},W=()=>{C=!1};document.addEventListener("mousemove",q),document.addEventListener("mouseup",W),m.addEventListener("touchstart",a=>{C=!0;const l=a.touches[0];l&&R(l.clientX)},{passive:!0});const G=a=>{if(C){const l=a.touches[0];l&&R(l.clientX)}},X=()=>{C=!1};document.addEventListener("touchmove",G,{passive:!0}),document.addEventListener("touchend",X);const Y=.05;m.addEventListener("keydown",a=>{let l=A;if(a.key==="ArrowRight"||a.key==="ArrowUp")l=Math.min(1,A+Y);else if(a.key==="ArrowLeft"||a.key==="ArrowDown")l=Math.max(0,A-Y);else return;a.preventDefault(),a.stopPropagation(),A=l,b.style.width=`${l*100}%`,m.setAttribute("aria-valuenow",String(Math.round(l*100))),E&&l>0&&t.onMuteToggle(),f.innerHTML=P(E,l),t.onVolumeChange(l)});const Q=a=>{for(const l of g.querySelectorAll(".hfp-speed-option"))l.classList.toggle("hfp-active",l.dataset.speed===String(a))};h.addEventListener("click",a=>{a.stopPropagation();const l=g.classList.toggle("hfp-open");h.setAttribute("aria-expanded",String(l))}),g.addEventListener("click",a=>{a.stopPropagation();const l=a.target.closest(".hfp-speed-option");if(!l)return;const _=parseFloat(l.dataset.speed);i.indexOf(_),h.textContent=H(_),Q(_),g.classList.remove("hfp-open"),h.setAttribute("aria-expanded","false"),t.onSpeedChange(_)});const J=()=>{g.classList.remove("hfp-open"),h.setAttribute("aria-expanded","false")};document.addEventListener("click",J);const I=a=>{const l=o.getBoundingClientRect(),_=Math.max(0,Math.min(1,(a-l.left)/l.width));t.onSeek(_)};let T=!1;o.addEventListener("mousedown",a=>{a.stopPropagation(),T=!0,I(a.clientX)});const K=a=>{T&&I(a.clientX)},Z=()=>{T=!1};document.addEventListener("mousemove",K),document.addEventListener("mouseup",Z),o.addEventListener("touchstart",a=>{T=!0;const l=a.touches[0];l&&I(l.clientX)},{passive:!0});const ee=a=>{if(T){const l=a.touches[0];l&&I(l.clientX)}},te=()=>{T=!1};document.addEventListener("touchmove",ee,{passive:!0}),document.addEventListener("touchend",te);const ie=()=>{x&&clearTimeout(x),x=setTimeout(()=>{L&&s.classList.add("hfp-hidden")},3e3)},O=r instanceof ShadowRoot?r.host:r,re=()=>{s.classList.remove("hfp-hidden"),ie()},se=()=>{L&&s.classList.add("hfp-hidden")};return O.addEventListener("mousemove",re),O.addEventListener("mouseleave",se),{updateTime(a,l){const _=l>0?Math.min(a,l):a,ce=l>0?_/l*100:0;d.style.width=`${ce}%`,c.textContent=`${de(_)} / ${de(l)}`},updatePlaying(a){L=a,n.innerHTML=a?Ae:ne,n.setAttribute("aria-label",a?"Pause":"Play"),a?ie():s.classList.remove("hfp-hidden")},updateSpeed(a){i.indexOf(a),h.textContent=H(a),Q(a)},updateMuted(a){E=a,f.innerHTML=P(a,A),f.setAttribute("aria-label",a?"Unmute":"Mute")},updateVolume(a){A=a,b.style.width=`${a*100}%`,m.setAttribute("aria-valuenow",String(Math.round(a*100))),f.innerHTML=P(E,a)},setVolumeControlsHidden(a){v.style.display=a?"none":""},show(){s.style.display=""},hide(){s.style.display="none"},destroy(){document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",Z),document.removeEventListener("touchmove",ee),document.removeEventListener("touchend",te),document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",W),document.removeEventListener("touchmove",G),document.removeEventListener("touchend",X),document.removeEventListener("click",J),O.removeEventListener("mousemove",re),O.removeEventListener("mouseleave",se),x&&clearTimeout(x),s.remove()}}}function ke(r,t,e,i,s,n=!1){const o=i?i.split(",").map(Number).filter(p=>!isNaN(p)&&p>0):void 0,d={...o?{speedPresets:o}:{},audioLocked:n},c=Te(r,s,d);return c.updateMuted(t),c.updateVolume(e),c}function le(r,t,e){return t?(e||(e=document.createElement("img"),e.className="hfp-poster",r.appendChild(e)),e.src=t,e):(e==null||e.remove(),null)}function xe(r){return r.composedPath().some(t=>t instanceof HTMLElement&&t.classList.contains("hfp-controls"))}let D=null;function Me(r,t){if(typeof CSSStyleSheet<"u")try{D||(D=new CSSStyleSheet,D.replaceSync(t)),r.adoptedStyleSheets=[D];return}catch{}const e=document.createElement("style");e.textContent=t,r.appendChild(e)}function Se(){const r=document.createElement("div");r.className="hfp-container";const t=document.createElement("iframe");return t.className="hfp-iframe",t.sandbox.add("allow-scripts","allow-same-origin"),t.allow="autoplay; fullscreen",t.referrerPolicy="no-referrer",t.title="HyperFrames Composition",r.appendChild(t),{container:r,iframe:t}}function Le(r,t,e,i){const s=r.offsetWidth,n=r.offsetHeight;if(s===0||n===0)return;const o=Math.min(s/e,n/i);t.style.width=`${e}px`,t.style.height=`${i}px`,t.style.transform=`translate(-50%, -50%) scale(${o})`}const Pe=100;class Re{constructor(t){u(this,"_raf",null);u(this,"_lastUpdateMs",0);this._callbacks=t}start(t,e,i,s){this.stop();const n=()=>{if(s()){this._raf=null;return}let o;try{o=t.time()}catch{this._raf=null;return}const d=i();d>0&&(o=Math.min(o,d));const c=d>0&&o>=d,p=performance.now();if((p-this._lastUpdateMs>Pe||c)&&(this._lastUpdateMs=p,this._callbacks.onTimeUpdate(o,d)),c){if(this._callbacks.getLoop()){this._callbacks.restart();return}try{t.pause()}catch{}this._callbacks.onPaused(),this._raf=null;return}this._raf=requestAnimationFrame(n)};this._raf=requestAnimationFrame(n)}stop(){this._raf!==null&&(cancelAnimationFrame(this._raf),this._raf=null)}get isRunning(){return this._raf!==null}}function Ie(r){const t=Array.from(r.querySelectorAll("[data-composition-id]"));if(t.length===0)return r.body?[r.body]:[];const e=[];for(const i of t)De(i)||e.push(i);return Oe(r),e}function Oe(r){const t=r.body;if(!t||typeof console>"u"||typeof console.warn!="function")return;const e=t.querySelectorAll("audio[data-start], video[data-start]");if(e.length===0)return;const i=[];for(const s of e)s.closest("[data-composition-id]")||i.push(s);i.length!==0&&console.warn(`[hyperframes-player] selectMediaObserverTargets: composition hosts are present, but ${i.length} body-level timed media element(s) sit outside every [data-composition-id] subtree and will not be observed. Move them inside a composition host or the parent-frame proxy will never adopt them.`,i)}function De(r){let t=r.parentElement;for(;t;){if(t.hasAttribute("data-composition-id"))return!0;t=t.parentElement}return!1}function j(r){var e;const t=(e=r.ownerDocument)==null?void 0:e.defaultView;return t&&r instanceof t.Element?!0:r instanceof Element}function w(r){var e;if(!j(r)||r.tagName!=="AUDIO"&&r.tagName!=="VIDEO")return!1;const t=(e=r.ownerDocument)==null?void 0:e.defaultView;return t&&r instanceof t.HTMLMediaElement?!0:r instanceof HTMLMediaElement}const Ne=.05,Fe=2;class Ue{constructor(t){u(this,"_entries",[]);u(this,"_mediaObserver");u(this,"_playbackErrorPosted",!1);u(this,"_audioOwner","runtime");u(this,"_urlAudioEntry",null);u(this,"_urlAudioSrc",null);u(this,"_dispatchEvent");u(this,"_getMuted");u(this,"_getVolume");u(this,"_getPlaybackRate");u(this,"_getCurrentTime");u(this,"_isPaused");this._dispatchEvent=t.dispatchEvent,this._getMuted=t.getMuted,this._getVolume=t.getVolume,this._getPlaybackRate=t.getPlaybackRate,this._getCurrentTime=t.getCurrentTime,this._isPaused=t.isPaused}get audioOwner(){return this._audioOwner}get entries(){return this._entries}resetForIframeLoad(){this._playbackErrorPosted=!1;const t=this._audioOwner==="parent";this._audioOwner="runtime",this.pauseAll(),this.teardownObserver(),t&&this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"runtime",reason:"iframe-reload"}}))}destroy(){this.teardownObserver();for(const t of this._entries)t.el.pause(),t.el.src="";this._entries=[],this._urlAudioEntry=null,this._urlAudioSrc=null}updateMuted(t){for(const e of this._entries)e.el.muted=t}updateVolume(t){for(const e of this._entries)e.el.volume=t}updatePlaybackRate(t){for(const e of this._entries)e.el.playbackRate=t}_playEntry(t){t.el.src&&t.el.play().catch(e=>this._reportPlaybackError(e))}_playEntryIfActive(t){this._refreshEntryBounds(t);const e=this._getCurrentTime()-t.start;e<0||e>=t.duration||this._playEntry(t)}_refreshEntryBounds(t){var s;if(!((s=t.source)!=null&&s.isConnected))return;const e=parseFloat(t.source.getAttribute("data-start")||"0");t.start=Number.isFinite(e)?e:0;const i=parseFloat(t.source.getAttribute("data-duration")||"");t.duration=Number.isFinite(i)&&i>0?i:Number.POSITIVE_INFINITY}_gateEntryPlayback(t,e){return e<0||e>=t.duration?(t.el.paused||t.el.pause(),t.driftSamples=0,!1):(this._audioOwner==="parent"&&!this._isPaused()&&t.el.paused&&this._playEntry(t),!0)}playAll(){for(const t of this._entries)this._playEntryIfActive(t)}pauseAll(){for(const t of this._entries)t.el.pause()}stopAdoptedMedia(){for(const t of this._entries)t.source&&t.el.pause()}seekAll(t){for(const e of this._entries){this._refreshEntryBounds(e);const i=t-e.start;i>=0&&i<e.duration&&(e.el.currentTime=i)}}mirrorTime(t,e){const i=(e==null?void 0:e.force)===!0;for(const s of this._entries){this._refreshEntryBounds(s);const n=t-s.start;this._gateEntryPlayback(s,n)&&(Math.abs(s.el.currentTime-n)>Ne?(s.driftSamples+=1,(i||s.driftSamples>=Fe)&&(s.el.currentTime=n,s.driftSamples=0)):s.driftSamples=0)}}promoteToParentProxy(t,e){if(this._audioOwner==="parent")return;if(this._audioOwner="parent",t)for(const s of t.querySelectorAll("video, audio"))w(s)&&(s.muted=!0);const i=this._getCurrentTime();e?e(i,{force:!0}):this.mirrorTime(i,{force:!0}),this._isPaused()||this.playAll(),this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"parent",reason:"autoplay-blocked"}}))}setupFromIframe(t){const e=t.querySelectorAll("audio[data-start], video[data-start]");for(const i of e)w(i)&&this._adoptIframeMedia(i);this._observeDynamicMedia(t)}setupFromUrl(t){if(this._urlAudioSrc===t&&this._urlAudioEntry)return;this.teardownUrlAudio();const e=this._createEntry(t,"audio",0,1/0);this._urlAudioEntry=e,this._urlAudioSrc=e?t:null,e&&this._audioOwner==="parent"&&!this._isPaused()&&(this.mirrorTime(this._getCurrentTime(),{force:!0}),this.playAll())}teardownUrlAudio(){const t=this._urlAudioEntry;if(this._urlAudioEntry=null,this._urlAudioSrc=null,!t)return;t.el.pause(),t.el.src="";const e=this._entries.indexOf(t);e!==-1&&this._entries.splice(e,1)}teardownObserver(){var t;(t=this._mediaObserver)==null||t.disconnect(),this._mediaObserver=void 0}_reportPlaybackError(t){this._playbackErrorPosted||(this._playbackErrorPosted=!0,this._dispatchEvent(new CustomEvent("playbackerror",{detail:{source:"parent-proxy",error:t}})))}_createEntry(t,e,i,s,n){if(this._entries.some(p=>p.el.src===t))return null;const o=e==="video"?document.createElement("video"):new Audio;o.preload="auto",o.src=t,o.load(),o.muted=this._getMuted(),o.volume=this._getVolume();const d=this._getPlaybackRate();d!==1&&(o.playbackRate=d);const c={el:o,start:i,duration:s,driftSamples:0,source:n};return this._entries.push(c),c}_resolveIframeMediaSrc(t){var i;const e=t.getAttribute("src")||((i=t.querySelector("source"))==null?void 0:i.getAttribute("src"));return e?new URL(e,t.ownerDocument.baseURI).href:null}_adoptIframeMedia(t){if(t.preload==="metadata"||t.preload==="none")return;const e=this._resolveIframeMediaSrc(t);if(!e)return;const i=parseFloat(t.getAttribute("data-start")||"0"),s=parseFloat(t.getAttribute("data-duration")||"Infinity"),n=t.tagName==="VIDEO"?"video":"audio",o=this._createEntry(e,n,i,s,t);o&&this._audioOwner==="parent"&&(this.mirrorTime(this._getCurrentTime(),{force:!0}),this._isPaused()||this._playEntryIfActive(o))}_detachIframeMedia(t){const e=this._resolveIframeMediaSrc(t);if(!e)return;const i=this._entries.findIndex(n=>n.el.src===e);if(i===-1)return;const s=this._entries[i];s.el.pause(),s.el.src="",this._entries.splice(i,1)}_observeDynamicMedia(t){if(this.teardownObserver(),typeof MutationObserver>"u"||!t.body)return;const e=new MutationObserver(n=>{for(const o of n){if(o.type==="attributes"&&o.attributeName==="preload"){const d=o.target;w(d)&&d.matches("audio[data-start], video[data-start]")&&d.preload==="auto"&&this._adoptIframeMedia(d);continue}for(const d of o.addedNodes){if(!j(d))continue;const c=[];w(d)&&d.matches("audio[data-start], video[data-start]")&&c.push(d);const p=d.querySelectorAll("audio[data-start], video[data-start]");for(const h of p)w(h)&&c.push(h);for(const h of c)this._adoptIframeMedia(h)}for(const d of o.removedNodes){if(!j(d))continue;const c=[];w(d)&&d.matches("audio[data-start], video[data-start]")&&c.push(d);const p=d.querySelectorAll("audio[data-start], video[data-start]");for(const h of p)w(h)&&c.push(h);for(const h of c)this._detachIframeMedia(h)}}}),i={childList:!0,subtree:!0,attributes:!0,attributeFilter:["preload"]},s=Ie(t);for(const n of s)e.observe(n,i);this._mediaObserver=e}}const He=100;function Ve(r,t,e,i){const s=(r.frame??0)/t,n=e.duration>0?Math.min(s,e.duration):s,o=!e.paused,d=!r.isPlaying,c=e.duration>0&&n>=e.duration&&(o||r.isPlaying);if(c&&i.getLoop())return i.media.audioOwner==="parent"&&i.media.pauseAll(),i.seek(0),i.play(),{...e,currentTime:n,paused:!1};const p={...e,currentTime:n,paused:d};i.media.audioOwner==="parent"&&(o&&d?i.media.pauseAll():!o&&!d&&i.media.playAll(),i.media.mirrorTime(n));const h=performance.now(),g=d!==e.paused;return(h-e.lastUpdateMs>He||g)&&(p.lastUpdateMs=h,i.updateControlsTime(n,e.duration),i.updateControlsPlaying(!d),i.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:n}}))),c&&(i.media.audioOwner==="parent"&&i.media.pauseAll(),p.paused=!0,i.updateControlsPlaying(!1),i.dispatchEvent(new Event("ended"))),p}const he=30;function $e(r){return Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.start=="number"&&typeof t.duration=="number"):[]}function ze(r,t,e){var s;if(r.source!==t)return;const i=r.data;if(!(!i||i.source!=="hf-preview")){if(i.type==="shader-transition-state"){const n=i.state&&typeof i.state=="object"?i.state:{};e.shaderLoader.update(n,e.getShaderLoadingMode()),e.dispatchEvent(new CustomEvent("shadertransitionstate",{detail:{compositionId:i.compositionId,state:n}}));return}if(i.type==="ready"){e.onRuntimeReady();return}if(i.type==="state"){e.setPlaybackState(Ve({frame:i.frame??0,isPlaying:!!i.isPlaying},he,e.getPlaybackState(),e));return}if(i.type==="media-autoplay-blocked"){if(((s=e.shouldPromoteMediaAutoplayFallback)==null?void 0:s.call(e))===!1)return;let n=null;try{n=e.getIframeDoc()}catch{}e.media.promoteToParentProxy(n,(o,d)=>e.media.mirrorTime(o,d)),e.sendControl("set-media-output-muted",{muted:!0});return}if(i.type==="timeline"&&i.durationInFrames>0){if(Number.isFinite(i.durationInFrames)){const n=e.getPlaybackState(),o=i.durationInFrames/he;e.setPlaybackState({...n,duration:o}),e.updateControlsTime(n.currentTime,o)}e.setScenes($e(i.scenes));return}i.type==="stage-size"&&Number.isFinite(i.width)&&i.width>0&&Number.isFinite(i.height)&&i.height>0&&e.setCompositionSize(i.width,i.height)}}const k="shader-capture-scale",M="shader-loading",je="__hf_shader_capture_scale",Be="__hf_shader_loading",N=["Preparing scene transitions","Sampling outgoing scene motion","Sampling incoming scene motion","Caching transition frames","Finalizing transition preview"];function B(r){if(r===null)return null;const t=Number(r);return!Number.isFinite(t)||t<=0?null:String(Math.min(1,Math.max(.25,t)))}function qe(r){if(r===null||r.trim()==="")return"composition";const t=r.trim().toLowerCase();return t==="none"||t==="false"||t==="0"||t==="off"?"none":t==="player"||t==="true"||t==="1"||t==="on"?"player":"composition"}function ue(r,t,e){e===null?r.delete(t):r.set(t,e)}function We(r,t,e){const i=r.indexOf("#"),s=i>=0?r.slice(0,i):r,n=i>=0?r.slice(i):"",o=s.indexOf("?"),d=o>=0?s.slice(0,o):s,c=o>=0?s.slice(o+1):"",p=new URLSearchParams(c);ue(p,je,t),ue(p,Be,e==="composition"?null:e);const h=p.toString();return`${d}${h?`?${h}`:""}${n}`}function Ge(r,t,e){if(t===null&&e==="composition")return r;const i=[];t!==null&&i.push(`window.__HF_SHADER_CAPTURE_SCALE=${JSON.stringify(t)};`),e!=="composition"&&i.push(`window.__HF_SHADER_LOADING=${JSON.stringify(e)};`);const s=`<script data-hyperframes-player-shader-options>${i.join("")}<\/script>`;return/<head\b[^>]*>/i.test(r)?r.replace(/<head\b[^>]*>/i,n=>`${n}${s}`):/<html\b[^>]*>/i.test(r)?r.replace(/<html\b[^>]*>/i,n=>`${n}${s}`):`${s}${r}`}function S(r){return qe(r.getAttribute(M))}function Xe(r){return Number(B(r.getAttribute(k))??"1")}function V(r,t){return We(t,B(r.getAttribute(k)),S(r))}function $(r,t){return Ge(t,B(r.getAttribute(k)),S(r))}function Ye(){const r=document.createElement("div");r.className="hfp-shader-loader",r.setAttribute("role","status"),r.setAttribute("aria-live","polite"),r.setAttribute("aria-label","Preparing scene transitions"),r.setAttribute("data-hyperframes-ignore",""),r.draggable=!1;const t=f=>{f.preventDefault(),f.stopPropagation()};for(const f of["selectstart","dragstart","pointerdown","mousedown","click","dblclick","contextmenu","touchstart"])r.addEventListener(f,t,{capture:!0});const e=document.createElement("div");e.className="hfp-shader-loader-panel",e.draggable=!1;const i=document.createElement("div");i.className="hfp-shader-loader-mark",i.draggable=!1,i.innerHTML=['<svg width="78" height="78" viewBox="0 0 100 100" fill="none" aria-hidden="true" draggable="false">','<path d="M10.1851 57.8021L33.1145 73.8313C36.2202 75.9978 41.5173 73.5433 42.4816 69.4984L51.7611 30.4271C52.7253 26.3822 48.5802 23.9277 44.4602 26.0942L13.917 42.1235C6.96677 45.7676 4.97564 54.1579 10.1851 57.8021Z" fill="url(#hfp-shader-loader-grad-left)"/>','<path d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z" fill="url(#hfp-shader-loader-grad-right)"/>',"<defs>",'<linearGradient id="hfp-shader-loader-grad-left" x1="48.5676" y1="25" x2="44.7804" y2="71.9384" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>",'<linearGradient id="hfp-shader-loader-grad-right" x1="54.8282" y1="73.8392" x2="72.0989" y2="32.8932" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>","</defs>","</svg>"].join("");const s=document.createElement("div");s.className="hfp-shader-loader-title";const n=document.createElement("span");n.className="hfp-shader-loader-title-text",n.textContent=N[0],s.appendChild(n);const o=document.createElement("div");o.className="hfp-shader-loader-detail",o.textContent="Rendering animated scene samples for shader transitions.";const d=document.createElement("div");d.className="hfp-shader-loader-track",d.setAttribute("aria-hidden","true");const c=document.createElement("div");c.className="hfp-shader-loader-fill",d.appendChild(c);const p=document.createElement("div");p.className="hfp-shader-loader-progress";const h=f=>{const y=document.createElement("div");y.className="hfp-shader-loader-row";const m=document.createElement("span");m.className="hfp-shader-loader-label",m.textContent=f;const b=document.createElement("span");return b.className="hfp-shader-loader-value",y.appendChild(m),y.appendChild(b),p.appendChild(y),{row:y,label:m,value:b}},g=h("transition"),v=h("transition frame");return e.appendChild(i),e.appendChild(s),e.appendChild(o),e.appendChild(d),e.appendChild(p),r.appendChild(e),{root:r,fill:c,title:n,detail:o,transitionValue:g.value,frameLabel:v.label,frameValue:v.value,frameRow:v.row}}const Qe=420;class Je{constructor(t){u(this,"_el");u(this,"_hideTimeout",null);this._el=t}show(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-hiding"),this._el.root.classList.add("hfp-visible")}hide(){if(this._el.root.classList.contains("hfp-hiding")){this._hideTimeout||this._scheduleCleanup();return}this._el.root.classList.contains("hfp-visible")&&(this._el.root.classList.add("hfp-hiding"),this._el.root.classList.remove("hfp-visible"),this._scheduleCleanup())}reset(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-visible","hfp-hiding"),this._el.fill.style.transform="scaleX(0)",this._el.transitionValue.textContent="",this._el.frameValue.textContent="",this._el.frameRow.style.visibility="hidden"}update(t,e){if(e!=="player"){this.reset();return}if(t.ready||!t.loading){this.hide();return}const i=typeof t.progress=="number"&&Number.isFinite(t.progress)?t.progress:0,s=typeof t.total=="number"&&Number.isFinite(t.total)?t.total:0,n=s>0?Math.min(1,Math.max(0,i/s)):0,o=Math.min(N.length-1,Math.floor(n*N.length));this._el.title.textContent=N[o]||"Preparing scene transitions",this._el.detail.textContent=t.phase==="cached"?"Loading cached transition frames before playback.":t.phase==="finalizing"?"Uploading transition textures for smooth playback.":"Rendering animated scene samples for shader transitions.",this._el.fill.style.transform=`scaleX(${n})`,this._el.transitionValue.textContent=t.currentTransition!==void 0&&t.transitionTotal!==void 0?`${t.currentTransition}/${t.transitionTotal}`:s>0?`${i}/${s}`:"";const d=t.transitionFrame!==void 0&&t.transitionFrames!==void 0?`${t.transitionFrame}/${t.transitionFrames}`:"";this._el.frameLabel.textContent=t.phase==="cached"?"cached transition frames":t.phase==="finalizing"?"finalizing transition frames":"rendering transition frames",this._el.frameValue.textContent=d,this._el.frameRow.style.visibility=d?"visible":"hidden",this._el.root.setAttribute("aria-valuenow",String(Math.round(n*100))),this.show()}get hideTimeout(){return this._hideTimeout}destroy(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null)}_scheduleCleanup(){this._hideTimeout&&clearTimeout(this._hideTimeout),this._hideTimeout=setTimeout(()=>{this._el.root.classList.remove("hfp-hiding"),this._hideTimeout=null},Qe)}}const Ke=.1,Ze=5;function z(r){return!Number.isFinite(r)||r<=0?1:Math.max(Ke,Math.min(Ze,r))}class et extends HTMLElement{constructor(){super();u(this,"shadow");u(this,"container");u(this,"iframe");u(this,"posterEl",null);u(this,"controlsApi",null);u(this,"resizeObserver");u(this,"shaderLoader");u(this,"probe");u(this,"_ready",!1);u(this,"_currentTime",0);u(this,"_duration",0);u(this,"_paused",!0);u(this,"_lastUpdateMs",0);u(this,"_volume",1);u(this,"_compositionWidth",1920);u(this,"_compositionHeight",1080);u(this,"_directTimelineAdapter",null);u(this,"_directTimelineClock");u(this,"_parentTickRaf",null);u(this,"_media");u(this,"_scenes",[]);this.shadow=this.attachShadow({mode:"open"}),Me(this.shadow,we),{container:this.container,iframe:this.iframe}=Se(),this.shadow.appendChild(this.container);const e=Ye();this.shadow.appendChild(e.root),this.shaderLoader=new Je(e),this._media=new Ue({dispatchEvent:i=>this.dispatchEvent(i),getMuted:()=>this.muted,getVolume:()=>this._volume,getPlaybackRate:()=>this.playbackRate,getCurrentTime:()=>this._currentTime,isPaused:()=>this._paused}),this._directTimelineClock=new Re({onTimeUpdate:(i,s)=>{var n;this._currentTime=i,(n=this.controlsApi)==null||n.updateTime(i,s),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:i}}))},getLoop:()=>this.loop,restart:()=>{this.seek(0),this.play()},onPaused:()=>{var i;this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),this.dispatchEvent(new Event("ended"))},onEnded:()=>this.loop}),this.probe=new ye(this.iframe,{onReady:i=>this._onProbeReady(i),onError:i=>this.dispatchEvent(new CustomEvent("error",{detail:{message:i}}))}),this.addEventListener("click",i=>{xe(i)||(this._paused?this.play():this.pause())}),this.resizeObserver=new ResizeObserver(()=>this._rescale()),this._onMessage=this._onMessage.bind(this),this._onIframeLoad=this._onIframeLoad.bind(this)}static get observedAttributes(){return["src","srcdoc","width","height","controls","muted","audio-locked","volume","poster","playback-rate","audio-src",k,M]}connectedCallback(){this.resizeObserver.observe(this),window.addEventListener("message",this._onMessage),this.iframe.addEventListener("load",this._onIframeLoad),this.hasAttribute("controls")&&this._setupControls(),this.hasAttribute("poster")&&(this.posterEl=le(this.shadow,this.getAttribute("poster"),this.posterEl)),this.hasAttribute("audio-src")&&this._media.setupFromUrl(this.getAttribute("audio-src")),this.hasAttribute("srcdoc")&&(this.iframe.srcdoc=$(this,this.getAttribute("srcdoc"))),this.hasAttribute("src")&&(this.iframe.src=V(this,this.getAttribute("src"))),!this.hasAttribute("audio-locked")&&this._isLockedHostEnvironment()&&this._applyAudioLock(!0)}disconnectedCallback(){var e;this.resizeObserver.disconnect(),window.removeEventListener("message",this._onMessage),this.iframe.removeEventListener("load",this._onIframeLoad),this.probe.stop(),this._directTimelineClock.stop(),this._stopParentTickClock(),this._directTimelineAdapter=null,this.shaderLoader.destroy(),this._media.destroy(),(e=this.controlsApi)==null||e.destroy()}attributeChangedCallback(e,i,s){var n,o,d,c,p;switch(e){case"src":s&&(this._ready=!1,this.iframe.src=V(this,s));break;case"srcdoc":this._ready=!1,s!==null?this.iframe.srcdoc=$(this,s):this.iframe.removeAttribute("srcdoc");break;case"width":this._compositionWidth=U(s)??1920,this._rescale();break;case"height":this._compositionHeight=U(s)??1080,this._rescale();break;case"controls":s!==null?this._setupControls():((n=this.controlsApi)==null||n.destroy(),this.controlsApi=null);break;case"poster":this.posterEl=le(this.shadow,s,this.posterEl);break;case"playback-rate":{const h=z(parseFloat(s||"1"));this._media.updatePlaybackRate(h),this._sendControl("set-playback-rate",{playbackRate:h}),(d=(o=this._directTimelineAdapter)==null?void 0:o.timeScale)==null||d.call(o,h),(c=this.controlsApi)==null||c.updateSpeed(h),this.dispatchEvent(new Event("ratechange"));break}case"muted":this._handleMutedChange(s);break;case"audio-locked":this._applyAudioLock(s!==null);break;case"volume":{const h=Math.max(0,Math.min(1,parseFloat(s||"1")));this._volume=h,this._media.updateVolume(h),this._sendControl("set-volume",{volume:h}),(p=this.controlsApi)==null||p.updateVolume(h),this.dispatchEvent(new Event("volumechange"));break}case"audio-src":s?this._media.setupFromUrl(s):this._media.teardownUrlAudio();break;case k:case M:this._reloadShaderOptions();break}}get iframeElement(){return this.iframe}get scenes(){return this._scenes}play(){var i,s;(i=this.posterEl)==null||i.remove(),this.posterEl=null,this._duration>0&&this._currentTime>=this._duration&&this.seek(0),this._paused=!1;const e=this._tryDirectTimelinePlay();e||(this._sendControl("play"),this._ready&&!this._directTimelineAdapter&&this._startParentTickClock()),this._media.audioOwner==="parent"&&this._media.playAll(),(s=this.controlsApi)==null||s.updatePlaying(!0),this.dispatchEvent(new Event("play")),e&&this._directTimelineAdapter&&this._directTimelineClock.start(this._directTimelineAdapter,()=>this._currentTime,()=>this._duration,()=>this._paused)}pause(){var e;this._tryDirectTimelinePause()||this._sendControl("pause"),this._directTimelineClock.stop(),this._stopParentTickClock(),this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(e=this.controlsApi)==null||e.updatePlaying(!1),this.dispatchEvent(new Event("pause"))}stopMedia(){this._sendControl("stop-media"),this._stopIframeMedia(),this._media.stopAdoptedMedia()}seek(e){var i,s;!this._trySyncSeek(e)&&!this._tryDirectTimelineSeek(e)&&this._sendControl("seek",{frame:Math.round(e*30)}),this._directTimelineClock.stop(),this._stopParentTickClock(),this._currentTime=e,this._media.audioOwner==="parent"&&(this._media.pauseAll(),this._media.seekAll(e)),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),(s=this.controlsApi)==null||s.updateTime(this._currentTime,this._duration)}setColorGrading(e,i){this._sendControl("set-color-grading",{target:e,grading:i})}clearColorGrading(e){this._sendControl("set-color-grading",{target:e,grading:null})}setColorGradingCompare(e,i){this._sendControl("set-color-grading-compare",{target:e,compare:i})}clearColorGradingCompare(e){this._sendControl("set-color-grading-compare",{target:e,compare:{enabled:!1}})}get currentTime(){return this._currentTime}set currentTime(e){this.seek(e)}get duration(){return this._duration}get paused(){return this._paused}get ready(){return this._ready}get playbackRate(){return z(parseFloat(this.getAttribute("playback-rate")||"1"))}set playbackRate(e){this.setAttribute("playback-rate",String(z(e)))}get shaderCaptureScale(){return Xe(this)}set shaderCaptureScale(e){this.setAttribute(k,String(e))}get shaderLoading(){return S(this)}set shaderLoading(e){e==="composition"?this.removeAttribute(M):this.setAttribute(M,e)}get muted(){return this.hasAttribute("muted")}set muted(e){e?this.setAttribute("muted",""):this.removeAttribute("muted")}get audioLocked(){return this.hasAttribute("audio-locked")}set audioLocked(e){e?this.setAttribute("audio-locked",""):this.removeAttribute("audio-locked")}_isLockedHostEnvironment(){if(typeof navigator>"u")return!1;const e=navigator.userAgent||"";return/\bClaude\/\d/.test(e)&&/\bElectron\b/.test(e)}_isAudioLocked(){return this.hasAttribute("audio-locked")||this._isLockedHostEnvironment()}_isSlideshowPlayer(){return this.closest("hyperframes-slideshow")!==null}_handleMutedChange(e){var i;if(e===null&&this._isAudioLocked()){this.setAttribute("muted","");return}this._media.updateMuted(e!==null),this._setIframeMediaMuted(e!==null),this._sendControl("set-muted",{muted:e!==null}),(i=this.controlsApi)==null||i.updateMuted(e!==null),this.dispatchEvent(new Event("volumechange"))}_applyAudioLock(e){var i;e&&(this.muted=!0),(i=this.controlsApi)==null||i.setVolumeControlsHidden(e)}get volume(){return this._volume}set volume(e){this.setAttribute("volume",String(Math.max(0,Math.min(1,e))))}get loop(){return this.hasAttribute("loop")}set loop(e){e?this.setAttribute("loop",""):this.removeAttribute("loop")}_sendControl(e,i={}){var s;try{(s=this.iframe.contentWindow)==null||s.postMessage({source:"hf-parent",type:"control",action:e,...i},"*")}catch{}}_getSameOriginIframeDocument(){try{return this.iframe.contentDocument}catch{return null}}_setIframeMediaMuted(e){const i=this._getSameOriginIframeDocument();if(i)for(const s of i.querySelectorAll("video, audio"))w(s)&&(s.muted=e||s.defaultMuted)}_stopIframeMedia(){const e=this._getSameOriginIframeDocument();if(e)for(const i of e.querySelectorAll("video, audio"))w(i)&&i.pause()}_replayBridgeState(){this._sendControl("set-muted",{muted:this.muted}),this._sendControl("set-volume",{volume:this._volume}),this._sendControl("set-playback-rate",{playbackRate:this.playbackRate}),this._sendControl("set-native-media-sync-disabled",{disabled:this._isSlideshowPlayer()}),this._sendControl("set-web-audio-media-disabled",{disabled:this._isSlideshowPlayer()})}_reloadShaderOptions(){if(S(this)!=="player"&&this.shaderLoader.reset(),this.hasAttribute("srcdoc")){this.iframe.srcdoc=$(this,this.getAttribute("srcdoc")||"");return}this.hasAttribute("src")&&(this.iframe.src=V(this,this.getAttribute("src")||""))}_trySyncSeek(e){try{const i=this.iframe.contentWindow,s=i==null?void 0:i.__player;return typeof(s==null?void 0:s.seek)!="function"?!1:(s.seek.call(s,e),!0)}catch{return!1}}_withDirectTimeline(e){const i=this._directTimelineAdapter||this.probe.resolveDirectTimelineAdapter();if(!i)return!1;try{return e(i),this._directTimelineAdapter=i,!0}catch{return!1}}_tryDirectTimelineSeek(e){return this._withDirectTimeline(i=>{i.seek(e,!1),i.pause()})}_tryDirectTimelinePlay(){return this._withDirectTimeline(e=>void e.play())}_tryDirectTimelinePause(){return this._withDirectTimeline(e=>void e.pause())}_startParentTickClock(){this._stopParentTickClock();const e=()=>{if(this._paused){this._parentTickRaf=null;return}this._sendControl("tick"),this._parentTickRaf=requestAnimationFrame(e)};this._parentTickRaf=requestAnimationFrame(e)}_stopParentTickClock(){this._parentTickRaf!==null&&(cancelAnimationFrame(this._parentTickRaf),this._parentTickRaf=null)}_onMessage(e){ze(e,this.iframe.contentWindow,{getPlaybackState:()=>({currentTime:this._currentTime,duration:this._duration,paused:this._paused,lastUpdateMs:this._lastUpdateMs}),setPlaybackState:({currentTime:i,duration:s,paused:n,lastUpdateMs:o})=>{this._currentTime=i,this._duration=s,this._paused=n,this._lastUpdateMs=o},getShaderLoadingMode:()=>S(this),shaderLoader:this.shaderLoader,setCompositionSize:(i,s)=>{this._compositionWidth=i,this._compositionHeight=s,this._rescale()},sendControl:(i,s)=>this._sendControl(i,s),getIframeDoc:()=>this.iframe.contentDocument,onRuntimeReady:()=>this._replayBridgeState(),shouldPromoteMediaAutoplayFallback:()=>!this._isSlideshowPlayer(),setScenes:i=>{this._scenes=i,this.dispatchEvent(new CustomEvent("scenes",{detail:{scenes:i}}))},updateControlsTime:(i,s)=>{var n;return(n=this.controlsApi)==null?void 0:n.updateTime(i,s)},updateControlsPlaying:i=>{var s;return(s=this.controlsApi)==null?void 0:s.updatePlaying(i)},dispatchEvent:i=>this.dispatchEvent(i),seek:i=>this.seek(i),play:()=>this.play(),getLoop:()=>this.loop,media:this._media})}_onProbeReady({duration:e,adapter:i,compositionSize:s}){var n;this._duration=e,this._directTimelineAdapter=i.kind==="direct-timeline"?i.timeline:null,this._ready=!0,(n=this.controlsApi)==null||n.updateTime(0,e),this.dispatchEvent(new CustomEvent("ready",{detail:{duration:e}})),s&&(this._compositionWidth=s.width,this._compositionHeight=s.height,this._rescale());try{const o=this.iframe.contentDocument;o&&this._media.setupFromIframe(o)}catch{}this._setIframeMediaMuted(this.muted),this.hasAttribute("autoplay")&&this.play()}_rescale(){Le(this,this.iframe,this._compositionWidth,this._compositionHeight)}_onIframeLoad(){this._directTimelineAdapter=null,this._directTimelineClock.stop(),this._stopParentTickClock(),this.shaderLoader.reset(),this._media.resetForIframeLoad(),this.probe.start()}_setupControls(){this.controlsApi||(this.controlsApi=ke(this.shadow,this.muted,this._volume,this.getAttribute("speed-presets"),{onPlay:()=>this.play(),onPause:()=>this.pause(),onSeek:e=>this.seek(e*this._duration),onSpeedChange:e=>void(this.playbackRate=e),onMuteToggle:()=>void(this.muted=!this.muted),onVolumeChange:e=>void(this.volume=e)},this._isAudioLocked()))}get _audioOwner(){return this._media.audioOwner}get _parentMedia(){return this._media.entries}_mirrorParentMediaTime(e,i){this._media.mirrorTime(e,i)}_promoteToParentProxy(){let e=null;try{e=this.iframe.contentDocument}catch{}this._media.promoteToParentProxy(e,(i,s)=>this._mirrorParentMediaTime(i,s)),this._sendControl("set-media-output-muted",{muted:!0})}_observeDynamicMedia(e){this._media.setupFromIframe(e)}}customElements.get("hyperframes-player")||customElements.define("hyperframes-player",et);export{et as HyperframesPlayer,Ce as SPEED_PRESETS,H as formatSpeed,de as formatTime};
425
+ `,ne='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><polygon points="4,2 16,9 4,16"/></svg>',Ae='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><rect x="3" y="2" width="4" height="14"/><rect x="11" y="2" width="4" height="14"/></svg>',oe='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/><path d="M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',ae='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',Ee='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z" opacity="0.3"/><line x1="18" y1="7" x2="14" y2="17" stroke="currentColor" stroke-width="2"/></svg>',Ce=[.25,.5,1,1.5,2,4];function H(r){return Number.isInteger(r)?`${r}x`:`${r}x`}function de(r){if(!Number.isFinite(r)||r<0)return"0:00";const t=Math.floor(r),e=Math.floor(t/60),i=t%60;return`${e}:${i.toString().padStart(2,"0")}`}function Te(r,t,e={}){const i=e.speedPresets??Ce,s=document.createElement("div");s.className="hfp-controls",s.addEventListener("click",a=>{a.stopPropagation()});const n=document.createElement("button");n.className="hfp-play-btn",n.type="button",n.innerHTML=ne,n.setAttribute("aria-label","Play");const o=document.createElement("div");o.className="hfp-scrubber";const d=document.createElement("div");d.className="hfp-progress",d.style.width="0%",o.appendChild(d);const c=document.createElement("span");c.className="hfp-time",c.textContent="0:00 / 0:00";const p=document.createElement("div");p.className="hfp-speed-wrap";const h=document.createElement("button");h.className="hfp-speed-btn",h.type="button",h.textContent="1x",h.setAttribute("aria-label","Playback speed");const g=document.createElement("div");g.className="hfp-speed-menu",g.setAttribute("role","menu");for(const a of i){const l=document.createElement("button");l.className="hfp-speed-option",l.type="button",l.setAttribute("role","menuitem"),l.dataset.speed=String(a),l.textContent=H(a),a===1&&l.classList.add("hfp-active"),g.appendChild(l)}p.appendChild(g),p.appendChild(h);const v=document.createElement("div");v.className="hfp-volume-wrap";const f=document.createElement("button");f.className="hfp-mute-btn",f.type="button",f.innerHTML=oe,f.setAttribute("aria-label","Mute");const b=document.createElement("div");b.className="hfp-volume-slider-wrap";const m=document.createElement("div");m.className="hfp-volume-slider",m.setAttribute("role","slider"),m.setAttribute("aria-label","Volume"),m.setAttribute("aria-valuemin","0"),m.setAttribute("aria-valuemax","100"),m.setAttribute("aria-valuenow","100"),m.tabIndex=0;const y=document.createElement("div");y.className="hfp-volume-fill",y.style.width="100%",m.appendChild(y),b.appendChild(m),v.appendChild(b),v.appendChild(f),e.audioLocked&&(v.style.display="none"),s.appendChild(n),s.appendChild(o),s.appendChild(c),s.appendChild(v),s.appendChild(p),r.appendChild(s);let L=!1,E=!1,A=1,x=null;i.indexOf(1);const P=(a,l)=>a?Ee:l===0||l<.5?ae:oe;n.addEventListener("click",a=>{a.stopPropagation(),L?t.onPause():t.onPlay()}),f.addEventListener("click",a=>{a.stopPropagation(),t.onMuteToggle()});let C=!1;const R=a=>{const l=m.getBoundingClientRect(),_=Math.max(0,Math.min(1,(a-l.left)/l.width));A=_,y.style.width=`${_*100}%`,m.setAttribute("aria-valuenow",String(Math.round(_*100))),E&&_>0&&t.onMuteToggle(),f.innerHTML=P(E,_),t.onVolumeChange(_)};m.addEventListener("mousedown",a=>{a.stopPropagation(),C=!0,R(a.clientX)});const q=a=>{C&&R(a.clientX)},W=()=>{C=!1};document.addEventListener("mousemove",q),document.addEventListener("mouseup",W),m.addEventListener("touchstart",a=>{C=!0;const l=a.touches[0];l&&R(l.clientX)},{passive:!0});const G=a=>{if(C){const l=a.touches[0];l&&R(l.clientX)}},X=()=>{C=!1};document.addEventListener("touchmove",G,{passive:!0}),document.addEventListener("touchend",X);const Y=.05;m.addEventListener("keydown",a=>{let l=A;if(a.key==="ArrowRight"||a.key==="ArrowUp")l=Math.min(1,A+Y);else if(a.key==="ArrowLeft"||a.key==="ArrowDown")l=Math.max(0,A-Y);else return;a.preventDefault(),a.stopPropagation(),A=l,y.style.width=`${l*100}%`,m.setAttribute("aria-valuenow",String(Math.round(l*100))),E&&l>0&&t.onMuteToggle(),f.innerHTML=P(E,l),t.onVolumeChange(l)});const Q=a=>{for(const l of g.querySelectorAll(".hfp-speed-option"))l.classList.toggle("hfp-active",l.dataset.speed===String(a))};h.addEventListener("click",a=>{a.stopPropagation();const l=g.classList.toggle("hfp-open");h.setAttribute("aria-expanded",String(l))}),g.addEventListener("click",a=>{a.stopPropagation();const l=a.target.closest(".hfp-speed-option");if(!l)return;const _=parseFloat(l.dataset.speed);i.indexOf(_),h.textContent=H(_),Q(_),g.classList.remove("hfp-open"),h.setAttribute("aria-expanded","false"),t.onSpeedChange(_)});const J=()=>{g.classList.remove("hfp-open"),h.setAttribute("aria-expanded","false")};document.addEventListener("click",J);const I=a=>{const l=o.getBoundingClientRect(),_=Math.max(0,Math.min(1,(a-l.left)/l.width));t.onSeek(_)};let T=!1;o.addEventListener("mousedown",a=>{a.stopPropagation(),T=!0,I(a.clientX)});const K=a=>{T&&I(a.clientX)},Z=()=>{T=!1};document.addEventListener("mousemove",K),document.addEventListener("mouseup",Z),o.addEventListener("touchstart",a=>{T=!0;const l=a.touches[0];l&&I(l.clientX)},{passive:!0});const ee=a=>{if(T){const l=a.touches[0];l&&I(l.clientX)}},te=()=>{T=!1};document.addEventListener("touchmove",ee,{passive:!0}),document.addEventListener("touchend",te);const ie=()=>{x&&clearTimeout(x),x=setTimeout(()=>{L&&s.classList.add("hfp-hidden")},3e3)},O=r instanceof ShadowRoot?r.host:r,re=()=>{s.classList.remove("hfp-hidden"),ie()},se=()=>{L&&s.classList.add("hfp-hidden")};return O.addEventListener("mousemove",re),O.addEventListener("mouseleave",se),{updateTime(a,l){const _=l>0?Math.min(a,l):a,ce=l>0?_/l*100:0;d.style.width=`${ce}%`,c.textContent=`${de(_)} / ${de(l)}`},updatePlaying(a){L=a,n.innerHTML=a?Ae:ne,n.setAttribute("aria-label",a?"Pause":"Play"),a?ie():s.classList.remove("hfp-hidden")},updateSpeed(a){i.indexOf(a),h.textContent=H(a),Q(a)},updateMuted(a){E=a,f.innerHTML=P(a,A),f.setAttribute("aria-label",a?"Unmute":"Mute")},updateVolume(a){A=a,y.style.width=`${a*100}%`,m.setAttribute("aria-valuenow",String(Math.round(a*100))),f.innerHTML=P(E,a)},setVolumeControlsHidden(a){v.style.display=a?"none":""},show(){s.style.display=""},hide(){s.style.display="none"},destroy(){document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",Z),document.removeEventListener("touchmove",ee),document.removeEventListener("touchend",te),document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",W),document.removeEventListener("touchmove",G),document.removeEventListener("touchend",X),document.removeEventListener("click",J),O.removeEventListener("mousemove",re),O.removeEventListener("mouseleave",se),x&&clearTimeout(x),s.remove()}}}function ke(r,t,e,i,s,n=!1){const o=i?i.split(",").map(Number).filter(p=>!isNaN(p)&&p>0):void 0,d={...o?{speedPresets:o}:{},audioLocked:n},c=Te(r,s,d);return c.updateMuted(t),c.updateVolume(e),c}function le(r,t,e){return t?(e||(e=document.createElement("img"),e.className="hfp-poster",r.appendChild(e)),e.src=t,e):(e==null||e.remove(),null)}function xe(r){return r.composedPath().some(t=>t instanceof HTMLElement&&t.classList.contains("hfp-controls"))}let D=null;function Me(r,t){if(typeof CSSStyleSheet<"u")try{D||(D=new CSSStyleSheet,D.replaceSync(t)),r.adoptedStyleSheets=[D];return}catch{}const e=document.createElement("style");e.textContent=t,r.appendChild(e)}function Se(){const r=document.createElement("div");r.className="hfp-container";const t=document.createElement("iframe");return t.className="hfp-iframe",t.sandbox.add("allow-scripts","allow-same-origin"),t.allow="autoplay; fullscreen",t.referrerPolicy="no-referrer",t.title="HyperFrames Composition",r.appendChild(t),{container:r,iframe:t}}function Le(r,t,e,i){const s=r.offsetWidth,n=r.offsetHeight;if(s===0||n===0)return;const o=Math.min(s/e,n/i);t.style.width=`${e}px`,t.style.height=`${i}px`,t.style.transform=`translate(-50%, -50%) scale(${o})`}const Pe=100;class Re{constructor(t){u(this,"_raf",null);u(this,"_lastUpdateMs",0);this._callbacks=t}start(t,e,i,s){this.stop();const n=()=>{if(s()){this._raf=null;return}let o;try{o=t.time()}catch{this._raf=null;return}const d=i();d>0&&(o=Math.min(o,d));const c=d>0&&o>=d,p=performance.now();if((p-this._lastUpdateMs>Pe||c)&&(this._lastUpdateMs=p,this._callbacks.onTimeUpdate(o,d)),c){if(this._callbacks.getLoop()){this._callbacks.restart();return}try{t.pause()}catch{}this._callbacks.onPaused(),this._raf=null;return}this._raf=requestAnimationFrame(n)};this._raf=requestAnimationFrame(n)}stop(){this._raf!==null&&(cancelAnimationFrame(this._raf),this._raf=null)}get isRunning(){return this._raf!==null}}function Ie(r){const t=Array.from(r.querySelectorAll("[data-composition-id]"));if(t.length===0)return r.body?[r.body]:[];const e=[];for(const i of t)De(i)||e.push(i);return Oe(r),e}function Oe(r){const t=r.body;if(!t||typeof console>"u"||typeof console.warn!="function")return;const e=t.querySelectorAll("audio[data-start], video[data-start]");if(e.length===0)return;const i=[];for(const s of e)s.closest("[data-composition-id]")||i.push(s);i.length!==0&&console.warn(`[hyperframes-player] selectMediaObserverTargets: composition hosts are present, but ${i.length} body-level timed media element(s) sit outside every [data-composition-id] subtree and will not be observed. Move them inside a composition host or the parent-frame proxy will never adopt them.`,i)}function De(r){let t=r.parentElement;for(;t;){if(t.hasAttribute("data-composition-id"))return!0;t=t.parentElement}return!1}function j(r){var e;const t=(e=r.ownerDocument)==null?void 0:e.defaultView;return t&&r instanceof t.Element?!0:r instanceof Element}function w(r){var e;if(!j(r)||r.tagName!=="AUDIO"&&r.tagName!=="VIDEO")return!1;const t=(e=r.ownerDocument)==null?void 0:e.defaultView;return t&&r instanceof t.HTMLMediaElement?!0:r instanceof HTMLMediaElement}const Ne=.05,Fe=2;class Ue{constructor(t){u(this,"_entries",[]);u(this,"_mediaObserver");u(this,"_playbackErrorPosted",!1);u(this,"_audioOwner","runtime");u(this,"_urlAudioEntry",null);u(this,"_urlAudioSrc",null);u(this,"_dispatchEvent");u(this,"_getMuted");u(this,"_getVolume");u(this,"_getPlaybackRate");u(this,"_getCurrentTime");u(this,"_isPaused");this._dispatchEvent=t.dispatchEvent,this._getMuted=t.getMuted,this._getVolume=t.getVolume,this._getPlaybackRate=t.getPlaybackRate,this._getCurrentTime=t.getCurrentTime,this._isPaused=t.isPaused}get audioOwner(){return this._audioOwner}get entries(){return this._entries}resetForIframeLoad(){this._playbackErrorPosted=!1;const t=this._audioOwner==="parent";this._audioOwner="runtime",this.pauseAll(),this.teardownObserver(),t&&this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"runtime",reason:"iframe-reload"}}))}destroy(){this.teardownObserver();for(const t of this._entries)t.el.pause(),t.el.src="";this._entries=[],this._urlAudioEntry=null,this._urlAudioSrc=null}updateMuted(t){for(const e of this._entries)e.el.muted=t}updateVolume(t){for(const e of this._entries)e.el.volume=t}updatePlaybackRate(t){for(const e of this._entries)e.el.playbackRate=t}_playEntry(t){t.el.src&&t.el.play().catch(e=>this._reportPlaybackError(e))}_playEntryIfActive(t){this._refreshEntryBounds(t);const e=this._getCurrentTime()-t.start;e<0||e>=t.duration||this._playEntry(t)}_refreshEntryBounds(t){var s;if(!((s=t.source)!=null&&s.isConnected))return;const e=parseFloat(t.source.getAttribute("data-start")||"0");t.start=Number.isFinite(e)?e:0;const i=parseFloat(t.source.getAttribute("data-duration")||"");t.duration=Number.isFinite(i)&&i>0?i:Number.POSITIVE_INFINITY}_gateEntryPlayback(t,e){return e<0||e>=t.duration?(t.el.paused||t.el.pause(),t.driftSamples=0,!1):(this._audioOwner==="parent"&&!this._isPaused()&&t.el.paused&&this._playEntry(t),!0)}playAll(){for(const t of this._entries)this._playEntryIfActive(t)}pauseAll(){for(const t of this._entries)t.el.pause()}stopAdoptedMedia(){for(const t of this._entries)t.source&&t.el.pause()}seekAll(t){for(const e of this._entries){this._refreshEntryBounds(e);const i=t-e.start;i>=0&&i<e.duration&&(e.el.currentTime=i)}}mirrorTime(t,e){const i=(e==null?void 0:e.force)===!0;for(const s of this._entries){this._refreshEntryBounds(s);const n=t-s.start;this._gateEntryPlayback(s,n)&&(Math.abs(s.el.currentTime-n)>Ne?(s.driftSamples+=1,(i||s.driftSamples>=Fe)&&(s.el.currentTime=n,s.driftSamples=0)):s.driftSamples=0)}}promoteToParentProxy(t,e){if(this._audioOwner==="parent")return;if(this._audioOwner="parent",t)for(const s of t.querySelectorAll("video, audio"))w(s)&&(s.muted=!0);const i=this._getCurrentTime();e?e(i,{force:!0}):this.mirrorTime(i,{force:!0}),this._isPaused()||this.playAll(),this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"parent",reason:"autoplay-blocked"}}))}setupFromIframe(t){const e=t.querySelectorAll("audio[data-start], video[data-start]");for(const i of e)w(i)&&this._adoptIframeMedia(i);this._observeDynamicMedia(t)}setupFromUrl(t){if(this._urlAudioSrc===t&&this._urlAudioEntry)return;this.teardownUrlAudio();const e=this._createEntry(t,"audio",0,1/0);this._urlAudioEntry=e,this._urlAudioSrc=e?t:null,e&&this._audioOwner==="parent"&&!this._isPaused()&&(this.mirrorTime(this._getCurrentTime(),{force:!0}),this.playAll())}teardownUrlAudio(){const t=this._urlAudioEntry;if(this._urlAudioEntry=null,this._urlAudioSrc=null,!t)return;t.el.pause(),t.el.src="";const e=this._entries.indexOf(t);e!==-1&&this._entries.splice(e,1)}teardownObserver(){var t;(t=this._mediaObserver)==null||t.disconnect(),this._mediaObserver=void 0}_reportPlaybackError(t){this._playbackErrorPosted||(this._playbackErrorPosted=!0,this._dispatchEvent(new CustomEvent("playbackerror",{detail:{source:"parent-proxy",error:t}})))}_createEntry(t,e,i,s,n){if(this._entries.some(p=>p.el.src===t))return null;const o=e==="video"?document.createElement("video"):new Audio;o.preload="auto",o.src=t,o.load(),o.muted=this._getMuted(),o.volume=this._getVolume();const d=this._getPlaybackRate();d!==1&&(o.playbackRate=d);const c={el:o,start:i,duration:s,driftSamples:0,source:n};return this._entries.push(c),c}_resolveIframeMediaSrc(t){var i;const e=t.getAttribute("src")||((i=t.querySelector("source"))==null?void 0:i.getAttribute("src"));return e?new URL(e,t.ownerDocument.baseURI).href:null}_adoptIframeMedia(t){if(t.preload==="metadata"||t.preload==="none")return;const e=this._resolveIframeMediaSrc(t);if(!e)return;const i=parseFloat(t.getAttribute("data-start")||"0"),s=parseFloat(t.getAttribute("data-duration")||"Infinity"),n=t.tagName==="VIDEO"?"video":"audio",o=this._createEntry(e,n,i,s,t);o&&this._audioOwner==="parent"&&(this.mirrorTime(this._getCurrentTime(),{force:!0}),this._isPaused()||this._playEntryIfActive(o))}_detachIframeMedia(t){const e=this._resolveIframeMediaSrc(t);if(!e)return;const i=this._entries.findIndex(n=>n.el.src===e);if(i===-1)return;const s=this._entries[i];s.el.pause(),s.el.src="",this._entries.splice(i,1)}_observeDynamicMedia(t){if(this.teardownObserver(),typeof MutationObserver>"u"||!t.body)return;const e=new MutationObserver(n=>{for(const o of n){if(o.type==="attributes"&&o.attributeName==="preload"){const d=o.target;w(d)&&d.matches("audio[data-start], video[data-start]")&&d.preload==="auto"&&this._adoptIframeMedia(d);continue}for(const d of o.addedNodes){if(!j(d))continue;const c=[];w(d)&&d.matches("audio[data-start], video[data-start]")&&c.push(d);const p=d.querySelectorAll("audio[data-start], video[data-start]");for(const h of p)w(h)&&c.push(h);for(const h of c)this._adoptIframeMedia(h)}for(const d of o.removedNodes){if(!j(d))continue;const c=[];w(d)&&d.matches("audio[data-start], video[data-start]")&&c.push(d);const p=d.querySelectorAll("audio[data-start], video[data-start]");for(const h of p)w(h)&&c.push(h);for(const h of c)this._detachIframeMedia(h)}}}),i={childList:!0,subtree:!0,attributes:!0,attributeFilter:["preload"]},s=Ie(t);for(const n of s)e.observe(n,i);this._mediaObserver=e}}const He=100;function Ve(r,t,e,i){const s=(r.frame??0)/t,n=e.duration>0?Math.min(s,e.duration):s,o=!e.paused,d=!r.isPlaying,c=e.duration>0&&n>=e.duration&&(o||r.isPlaying);if(c&&i.getLoop())return i.media.audioOwner==="parent"&&i.media.pauseAll(),i.seek(0),i.play(),{...e,currentTime:n,paused:!1};const p={...e,currentTime:n,paused:d};i.media.audioOwner==="parent"&&(o&&d?i.media.pauseAll():!o&&!d&&i.media.playAll(),i.media.mirrorTime(n));const h=performance.now(),g=d!==e.paused;return(h-e.lastUpdateMs>He||g)&&(p.lastUpdateMs=h,i.updateControlsTime(n,e.duration),i.updateControlsPlaying(!d),i.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:n}}))),c&&(i.media.audioOwner==="parent"&&i.media.pauseAll(),p.paused=!0,i.updateControlsPlaying(!1),i.dispatchEvent(new Event("ended"))),p}const he=30;function $e(r){return Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.start=="number"&&typeof t.duration=="number"):[]}function ze(r,t,e){var s;if(r.source!==t)return;const i=r.data;if(!(!i||i.source!=="hf-preview")){if(i.type==="shader-transition-state"){const n=i.state&&typeof i.state=="object"?i.state:{};e.shaderLoader.update(n,e.getShaderLoadingMode()),e.dispatchEvent(new CustomEvent("shadertransitionstate",{detail:{compositionId:i.compositionId,state:n}}));return}if(i.type==="ready"){e.onRuntimeReady();return}if(i.type==="state"){e.setPlaybackState(Ve({frame:i.frame??0,isPlaying:!!i.isPlaying},he,e.getPlaybackState(),e));return}if(i.type==="media-autoplay-blocked"){if(((s=e.shouldPromoteMediaAutoplayFallback)==null?void 0:s.call(e))===!1)return;let n=null;try{n=e.getIframeDoc()}catch{}e.media.promoteToParentProxy(n,(o,d)=>e.media.mirrorTime(o,d)),e.sendControl("set-media-output-muted",{muted:!0});return}if(i.type==="timeline"&&i.durationInFrames>0){if(Number.isFinite(i.durationInFrames)){const n=e.getPlaybackState(),o=i.durationInFrames/he;e.setPlaybackState({...n,duration:o}),e.updateControlsTime(n.currentTime,o),e.onRuntimeTimelineReady(o)}e.setScenes($e(i.scenes));return}i.type==="stage-size"&&Number.isFinite(i.width)&&i.width>0&&Number.isFinite(i.height)&&i.height>0&&e.setCompositionSize(i.width,i.height)}}const k="shader-capture-scale",M="shader-loading",je="__hf_shader_capture_scale",Be="__hf_shader_loading",N=["Preparing scene transitions","Sampling outgoing scene motion","Sampling incoming scene motion","Caching transition frames","Finalizing transition preview"];function B(r){if(r===null)return null;const t=Number(r);return!Number.isFinite(t)||t<=0?null:String(Math.min(1,Math.max(.25,t)))}function qe(r){if(r===null||r.trim()==="")return"composition";const t=r.trim().toLowerCase();return t==="none"||t==="false"||t==="0"||t==="off"?"none":t==="player"||t==="true"||t==="1"||t==="on"?"player":"composition"}function ue(r,t,e){e===null?r.delete(t):r.set(t,e)}function We(r,t,e){const i=r.indexOf("#"),s=i>=0?r.slice(0,i):r,n=i>=0?r.slice(i):"",o=s.indexOf("?"),d=o>=0?s.slice(0,o):s,c=o>=0?s.slice(o+1):"",p=new URLSearchParams(c);ue(p,je,t),ue(p,Be,e==="composition"?null:e);const h=p.toString();return`${d}${h?`?${h}`:""}${n}`}function Ge(r,t,e){if(t===null&&e==="composition")return r;const i=[];t!==null&&i.push(`window.__HF_SHADER_CAPTURE_SCALE=${JSON.stringify(t)};`),e!=="composition"&&i.push(`window.__HF_SHADER_LOADING=${JSON.stringify(e)};`);const s=`<script data-hyperframes-player-shader-options>${i.join("")}<\/script>`;return/<head\b[^>]*>/i.test(r)?r.replace(/<head\b[^>]*>/i,n=>`${n}${s}`):/<html\b[^>]*>/i.test(r)?r.replace(/<html\b[^>]*>/i,n=>`${n}${s}`):`${s}${r}`}function S(r){return qe(r.getAttribute(M))}function Xe(r){return Number(B(r.getAttribute(k))??"1")}function V(r,t){return We(t,B(r.getAttribute(k)),S(r))}function $(r,t){return Ge(t,B(r.getAttribute(k)),S(r))}function Ye(){const r=document.createElement("div");r.className="hfp-shader-loader",r.setAttribute("role","status"),r.setAttribute("aria-live","polite"),r.setAttribute("aria-label","Preparing scene transitions"),r.setAttribute("data-hyperframes-ignore",""),r.draggable=!1;const t=f=>{f.preventDefault(),f.stopPropagation()};for(const f of["selectstart","dragstart","pointerdown","mousedown","click","dblclick","contextmenu","touchstart"])r.addEventListener(f,t,{capture:!0});const e=document.createElement("div");e.className="hfp-shader-loader-panel",e.draggable=!1;const i=document.createElement("div");i.className="hfp-shader-loader-mark",i.draggable=!1,i.innerHTML=['<svg width="78" height="78" viewBox="0 0 100 100" fill="none" aria-hidden="true" draggable="false">','<path d="M10.1851 57.8021L33.1145 73.8313C36.2202 75.9978 41.5173 73.5433 42.4816 69.4984L51.7611 30.4271C52.7253 26.3822 48.5802 23.9277 44.4602 26.0942L13.917 42.1235C6.96677 45.7676 4.97564 54.1579 10.1851 57.8021Z" fill="url(#hfp-shader-loader-grad-left)"/>','<path d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z" fill="url(#hfp-shader-loader-grad-right)"/>',"<defs>",'<linearGradient id="hfp-shader-loader-grad-left" x1="48.5676" y1="25" x2="44.7804" y2="71.9384" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>",'<linearGradient id="hfp-shader-loader-grad-right" x1="54.8282" y1="73.8392" x2="72.0989" y2="32.8932" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>","</defs>","</svg>"].join("");const s=document.createElement("div");s.className="hfp-shader-loader-title";const n=document.createElement("span");n.className="hfp-shader-loader-title-text",n.textContent=N[0],s.appendChild(n);const o=document.createElement("div");o.className="hfp-shader-loader-detail",o.textContent="Rendering animated scene samples for shader transitions.";const d=document.createElement("div");d.className="hfp-shader-loader-track",d.setAttribute("aria-hidden","true");const c=document.createElement("div");c.className="hfp-shader-loader-fill",d.appendChild(c);const p=document.createElement("div");p.className="hfp-shader-loader-progress";const h=f=>{const b=document.createElement("div");b.className="hfp-shader-loader-row";const m=document.createElement("span");m.className="hfp-shader-loader-label",m.textContent=f;const y=document.createElement("span");return y.className="hfp-shader-loader-value",b.appendChild(m),b.appendChild(y),p.appendChild(b),{row:b,label:m,value:y}},g=h("transition"),v=h("transition frame");return e.appendChild(i),e.appendChild(s),e.appendChild(o),e.appendChild(d),e.appendChild(p),r.appendChild(e),{root:r,fill:c,title:n,detail:o,transitionValue:g.value,frameLabel:v.label,frameValue:v.value,frameRow:v.row}}const Qe=420;class Je{constructor(t){u(this,"_el");u(this,"_hideTimeout",null);this._el=t}show(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-hiding"),this._el.root.classList.add("hfp-visible")}hide(){if(this._el.root.classList.contains("hfp-hiding")){this._hideTimeout||this._scheduleCleanup();return}this._el.root.classList.contains("hfp-visible")&&(this._el.root.classList.add("hfp-hiding"),this._el.root.classList.remove("hfp-visible"),this._scheduleCleanup())}reset(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-visible","hfp-hiding"),this._el.fill.style.transform="scaleX(0)",this._el.transitionValue.textContent="",this._el.frameValue.textContent="",this._el.frameRow.style.visibility="hidden"}update(t,e){if(e!=="player"){this.reset();return}if(t.ready||!t.loading){this.hide();return}const i=typeof t.progress=="number"&&Number.isFinite(t.progress)?t.progress:0,s=typeof t.total=="number"&&Number.isFinite(t.total)?t.total:0,n=s>0?Math.min(1,Math.max(0,i/s)):0,o=Math.min(N.length-1,Math.floor(n*N.length));this._el.title.textContent=N[o]||"Preparing scene transitions",this._el.detail.textContent=t.phase==="cached"?"Loading cached transition frames before playback.":t.phase==="finalizing"?"Uploading transition textures for smooth playback.":"Rendering animated scene samples for shader transitions.",this._el.fill.style.transform=`scaleX(${n})`,this._el.transitionValue.textContent=t.currentTransition!==void 0&&t.transitionTotal!==void 0?`${t.currentTransition}/${t.transitionTotal}`:s>0?`${i}/${s}`:"";const d=t.transitionFrame!==void 0&&t.transitionFrames!==void 0?`${t.transitionFrame}/${t.transitionFrames}`:"";this._el.frameLabel.textContent=t.phase==="cached"?"cached transition frames":t.phase==="finalizing"?"finalizing transition frames":"rendering transition frames",this._el.frameValue.textContent=d,this._el.frameRow.style.visibility=d?"visible":"hidden",this._el.root.setAttribute("aria-valuenow",String(Math.round(n*100))),this.show()}get hideTimeout(){return this._hideTimeout}destroy(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null)}_scheduleCleanup(){this._hideTimeout&&clearTimeout(this._hideTimeout),this._hideTimeout=setTimeout(()=>{this._el.root.classList.remove("hfp-hiding"),this._hideTimeout=null},Qe)}}const Ke=.1,Ze=5;function z(r){return!Number.isFinite(r)||r<=0?1:Math.max(Ke,Math.min(Ze,r))}class et extends HTMLElement{constructor(){super();u(this,"shadow");u(this,"container");u(this,"iframe");u(this,"posterEl",null);u(this,"controlsApi",null);u(this,"resizeObserver");u(this,"shaderLoader");u(this,"probe");u(this,"_ready",!1);u(this,"_currentTime",0);u(this,"_duration",0);u(this,"_paused",!0);u(this,"_lastUpdateMs",0);u(this,"_volume",1);u(this,"_compositionWidth",1920);u(this,"_compositionHeight",1080);u(this,"_directTimelineAdapter",null);u(this,"_directTimelineClock");u(this,"_parentTickRaf",null);u(this,"_media");u(this,"_scenes",[]);this.shadow=this.attachShadow({mode:"open"}),Me(this.shadow,we),{container:this.container,iframe:this.iframe}=Se(),this.shadow.appendChild(this.container);const e=Ye();this.shadow.appendChild(e.root),this.shaderLoader=new Je(e),this._media=new Ue({dispatchEvent:i=>this.dispatchEvent(i),getMuted:()=>this.muted,getVolume:()=>this._volume,getPlaybackRate:()=>this.playbackRate,getCurrentTime:()=>this._currentTime,isPaused:()=>this._paused}),this._directTimelineClock=new Re({onTimeUpdate:(i,s)=>{var n;this._currentTime=i,(n=this.controlsApi)==null||n.updateTime(i,s),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:i}}))},getLoop:()=>this.loop,restart:()=>{this.seek(0),this.play()},onPaused:()=>{var i;this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),this.dispatchEvent(new Event("ended"))},onEnded:()=>this.loop}),this.probe=new be(this.iframe,{onReady:i=>this._onProbeReady(i),onError:i=>this.dispatchEvent(new CustomEvent("error",{detail:{message:i}}))}),this.addEventListener("click",i=>{xe(i)||(this._paused?this.play():this.pause())}),this.resizeObserver=new ResizeObserver(()=>this._rescale()),this._onMessage=this._onMessage.bind(this),this._onIframeLoad=this._onIframeLoad.bind(this)}static get observedAttributes(){return["src","srcdoc","width","height","controls","muted","audio-locked","volume","poster","playback-rate","audio-src",k,M]}connectedCallback(){this.resizeObserver.observe(this),window.addEventListener("message",this._onMessage),this.iframe.addEventListener("load",this._onIframeLoad),this.hasAttribute("controls")&&this._setupControls(),this.hasAttribute("poster")&&(this.posterEl=le(this.shadow,this.getAttribute("poster"),this.posterEl)),this.hasAttribute("audio-src")&&this._media.setupFromUrl(this.getAttribute("audio-src")),this.hasAttribute("srcdoc")&&(this.iframe.srcdoc=$(this,this.getAttribute("srcdoc"))),this.hasAttribute("src")&&(this.iframe.src=V(this,this.getAttribute("src"))),!this.hasAttribute("audio-locked")&&this._isLockedHostEnvironment()&&this._applyAudioLock(!0)}disconnectedCallback(){var e;this.resizeObserver.disconnect(),window.removeEventListener("message",this._onMessage),this.iframe.removeEventListener("load",this._onIframeLoad),this.probe.stop(),this._directTimelineClock.stop(),this._stopParentTickClock(),this._directTimelineAdapter=null,this.shaderLoader.destroy(),this._media.destroy(),(e=this.controlsApi)==null||e.destroy()}attributeChangedCallback(e,i,s){var n,o,d,c,p;switch(e){case"src":s&&(this._ready=!1,this.iframe.src=V(this,s));break;case"srcdoc":this._ready=!1,s!==null?this.iframe.srcdoc=$(this,s):this.iframe.removeAttribute("srcdoc");break;case"width":this._compositionWidth=U(s)??1920,this._rescale();break;case"height":this._compositionHeight=U(s)??1080,this._rescale();break;case"controls":s!==null?this._setupControls():((n=this.controlsApi)==null||n.destroy(),this.controlsApi=null);break;case"poster":this.posterEl=le(this.shadow,s,this.posterEl);break;case"playback-rate":{const h=z(parseFloat(s||"1"));this._media.updatePlaybackRate(h),this._sendControl("set-playback-rate",{playbackRate:h}),(d=(o=this._directTimelineAdapter)==null?void 0:o.timeScale)==null||d.call(o,h),(c=this.controlsApi)==null||c.updateSpeed(h),this.dispatchEvent(new Event("ratechange"));break}case"muted":this._handleMutedChange(s);break;case"audio-locked":this._applyAudioLock(s!==null);break;case"volume":{const h=Math.max(0,Math.min(1,parseFloat(s||"1")));this._volume=h,this._media.updateVolume(h),this._sendControl("set-volume",{volume:h}),(p=this.controlsApi)==null||p.updateVolume(h),this.dispatchEvent(new Event("volumechange"));break}case"audio-src":s?this._media.setupFromUrl(s):this._media.teardownUrlAudio();break;case k:case M:this._reloadShaderOptions();break}}get iframeElement(){return this.iframe}get scenes(){return this._scenes}play(){var i,s;(i=this.posterEl)==null||i.remove(),this.posterEl=null,this._duration>0&&this._currentTime>=this._duration&&this.seek(0),this._paused=!1;const e=this._tryDirectTimelinePlay();e||(this._sendControl("play"),this._ready&&!this._directTimelineAdapter&&this._startParentTickClock()),this._media.audioOwner==="parent"&&this._media.playAll(),(s=this.controlsApi)==null||s.updatePlaying(!0),this.dispatchEvent(new Event("play")),e&&this._directTimelineAdapter&&this._directTimelineClock.start(this._directTimelineAdapter,()=>this._currentTime,()=>this._duration,()=>this._paused)}pause(){var e;this._tryDirectTimelinePause()||this._sendControl("pause"),this._directTimelineClock.stop(),this._stopParentTickClock(),this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(e=this.controlsApi)==null||e.updatePlaying(!1),this.dispatchEvent(new Event("pause"))}stopMedia(){this._sendControl("stop-media"),this._stopIframeMedia(),this._media.stopAdoptedMedia()}seek(e){var i,s;!this._trySyncSeek(e)&&!this._tryDirectTimelineSeek(e)&&this._sendControl("seek",{frame:Math.round(e*30)}),this._directTimelineClock.stop(),this._stopParentTickClock(),this._currentTime=e,this._media.audioOwner==="parent"&&(this._media.pauseAll(),this._media.seekAll(e)),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),(s=this.controlsApi)==null||s.updateTime(this._currentTime,this._duration)}setColorGrading(e,i){this._sendControl("set-color-grading",{target:e,grading:i})}clearColorGrading(e){this._sendControl("set-color-grading",{target:e,grading:null})}setColorGradingCompare(e,i){this._sendControl("set-color-grading-compare",{target:e,compare:i})}clearColorGradingCompare(e){this._sendControl("set-color-grading-compare",{target:e,compare:{enabled:!1}})}get currentTime(){return this._currentTime}set currentTime(e){this.seek(e)}get duration(){return this._duration}get paused(){return this._paused}get ready(){return this._ready}get playbackRate(){return z(parseFloat(this.getAttribute("playback-rate")||"1"))}set playbackRate(e){this.setAttribute("playback-rate",String(z(e)))}get shaderCaptureScale(){return Xe(this)}set shaderCaptureScale(e){this.setAttribute(k,String(e))}get shaderLoading(){return S(this)}set shaderLoading(e){e==="composition"?this.removeAttribute(M):this.setAttribute(M,e)}get muted(){return this.hasAttribute("muted")}set muted(e){e?this.setAttribute("muted",""):this.removeAttribute("muted")}get audioLocked(){return this.hasAttribute("audio-locked")}set audioLocked(e){e?this.setAttribute("audio-locked",""):this.removeAttribute("audio-locked")}_isLockedHostEnvironment(){if(typeof navigator>"u")return!1;const e=navigator.userAgent||"";return/\bClaude\/\d/.test(e)&&/\bElectron\b/.test(e)}_isAudioLocked(){return this.hasAttribute("audio-locked")||this._isLockedHostEnvironment()}_isSlideshowPlayer(){return this.closest("hyperframes-slideshow")!==null}_handleMutedChange(e){var i;if(e===null&&this._isAudioLocked()){this.setAttribute("muted","");return}this._media.updateMuted(e!==null),this._setIframeMediaMuted(e!==null),this._sendControl("set-muted",{muted:e!==null}),(i=this.controlsApi)==null||i.updateMuted(e!==null),this.dispatchEvent(new Event("volumechange"))}_applyAudioLock(e){var i;e&&(this.muted=!0),(i=this.controlsApi)==null||i.setVolumeControlsHidden(e)}get volume(){return this._volume}set volume(e){this.setAttribute("volume",String(Math.max(0,Math.min(1,e))))}get loop(){return this.hasAttribute("loop")}set loop(e){e?this.setAttribute("loop",""):this.removeAttribute("loop")}_sendControl(e,i={}){var s;try{(s=this.iframe.contentWindow)==null||s.postMessage({source:"hf-parent",type:"control",action:e,...i},"*")}catch{}}_getSameOriginIframeDocument(){try{return this.iframe.contentDocument}catch{return null}}_setIframeMediaMuted(e){const i=this._getSameOriginIframeDocument();if(i)for(const s of i.querySelectorAll("video, audio"))w(s)&&(s.muted=e||s.defaultMuted)}_stopIframeMedia(){const e=this._getSameOriginIframeDocument();if(e)for(const i of e.querySelectorAll("video, audio"))w(i)&&i.pause()}_replayBridgeState(){this._sendControl("set-muted",{muted:this.muted}),this._sendControl("set-volume",{volume:this._volume}),this._sendControl("set-playback-rate",{playbackRate:this.playbackRate}),this._sendControl("set-native-media-sync-disabled",{disabled:this._isSlideshowPlayer()}),this._sendControl("set-web-audio-media-disabled",{disabled:this._isSlideshowPlayer()})}_reloadShaderOptions(){if(S(this)!=="player"&&this.shaderLoader.reset(),this.hasAttribute("srcdoc")){this.iframe.srcdoc=$(this,this.getAttribute("srcdoc")||"");return}this.hasAttribute("src")&&(this.iframe.src=V(this,this.getAttribute("src")||""))}_trySyncSeek(e){try{const i=this.iframe.contentWindow,s=i==null?void 0:i.__player;return typeof(s==null?void 0:s.seek)!="function"?!1:(s.seek.call(s,e),!0)}catch{return!1}}_withDirectTimeline(e){const i=this._directTimelineAdapter||this.probe.resolveDirectTimelineAdapter();if(!i)return!1;try{return e(i),this._directTimelineAdapter=i,!0}catch{return!1}}_tryDirectTimelineSeek(e){return this._withDirectTimeline(i=>{i.seek(e,!1),i.pause()})}_tryDirectTimelinePlay(){return this._withDirectTimeline(e=>void e.play())}_tryDirectTimelinePause(){return this._withDirectTimeline(e=>void e.pause())}_startParentTickClock(){this._stopParentTickClock();const e=()=>{if(this._paused){this._parentTickRaf=null;return}this._sendControl("tick"),this._parentTickRaf=requestAnimationFrame(e)};this._parentTickRaf=requestAnimationFrame(e)}_stopParentTickClock(){this._parentTickRaf!==null&&(cancelAnimationFrame(this._parentTickRaf),this._parentTickRaf=null)}_onMessage(e){ze(e,this.iframe.contentWindow,{getPlaybackState:()=>({currentTime:this._currentTime,duration:this._duration,paused:this._paused,lastUpdateMs:this._lastUpdateMs}),setPlaybackState:({currentTime:i,duration:s,paused:n,lastUpdateMs:o})=>{this._currentTime=i,this._duration=s,this._paused=n,this._lastUpdateMs=o},getShaderLoadingMode:()=>S(this),shaderLoader:this.shaderLoader,setCompositionSize:(i,s)=>{this._compositionWidth=i,this._compositionHeight=s,this._rescale()},sendControl:(i,s)=>this._sendControl(i,s),getIframeDoc:()=>this.iframe.contentDocument,onRuntimeReady:()=>this._replayBridgeState(),onRuntimeTimelineReady:i=>this._onRuntimeTimelineReady(i),shouldPromoteMediaAutoplayFallback:()=>!this._isSlideshowPlayer(),setScenes:i=>{this._scenes=i,this.dispatchEvent(new CustomEvent("scenes",{detail:{scenes:i}}))},updateControlsTime:(i,s)=>{var n;return(n=this.controlsApi)==null?void 0:n.updateTime(i,s)},updateControlsPlaying:i=>{var s;return(s=this.controlsApi)==null?void 0:s.updatePlaying(i)},dispatchEvent:i=>this.dispatchEvent(i),seek:i=>this.seek(i),play:()=>this.play(),getLoop:()=>this.loop,media:this._media})}_onRuntimeTimelineReady(e){var s;if(this._ready)return;this.probe.stop(),this._duration=e,this._directTimelineAdapter=null,this._ready=!0,(s=this.controlsApi)==null||s.updateTime(this._currentTime,e),this.dispatchEvent(new CustomEvent("ready",{detail:{duration:e}}));const i=this._getSameOriginIframeDocument();i&&this._media.setupFromIframe(i),this._replayBridgeState(),this._setIframeMediaMuted(this.muted),this.hasAttribute("autoplay")&&this.play()}_onProbeReady({duration:e,adapter:i,compositionSize:s}){var n;this._duration=e,this._directTimelineAdapter=i.kind==="direct-timeline"?i.timeline:null,this._ready=!0,(n=this.controlsApi)==null||n.updateTime(0,e),this.dispatchEvent(new CustomEvent("ready",{detail:{duration:e}})),s&&(this._compositionWidth=s.width,this._compositionHeight=s.height,this._rescale());try{const o=this.iframe.contentDocument;o&&this._media.setupFromIframe(o)}catch{}this._setIframeMediaMuted(this.muted),this.hasAttribute("autoplay")&&this.play()}_rescale(){Le(this,this.iframe,this._compositionWidth,this._compositionHeight)}_onIframeLoad(){this._directTimelineAdapter=null,this._directTimelineClock.stop(),this._stopParentTickClock(),this.shaderLoader.reset(),this._media.resetForIframeLoad(),this.probe.start()}_setupControls(){this.controlsApi||(this.controlsApi=ke(this.shadow,this.muted,this._volume,this.getAttribute("speed-presets"),{onPlay:()=>this.play(),onPause:()=>this.pause(),onSeek:e=>this.seek(e*this._duration),onSpeedChange:e=>void(this.playbackRate=e),onMuteToggle:()=>void(this.muted=!this.muted),onVolumeChange:e=>void(this.volume=e)},this._isAudioLocked()))}get _audioOwner(){return this._media.audioOwner}get _parentMedia(){return this._media.entries}_mirrorParentMediaTime(e,i){this._media.mirrorTime(e,i)}_promoteToParentProxy(){let e=null;try{e=this.iframe.contentDocument}catch{}this._media.promoteToParentProxy(e,(i,s)=>this._mirrorParentMediaTime(i,s)),this._sendControl("set-media-output-muted",{muted:!0})}_observeDynamicMedia(e){this._media.setupFromIframe(e)}}customElements.get("hyperframes-player")||customElements.define("hyperframes-player",et);export{et as HyperframesPlayer,Ce as SPEED_PRESETS,H as formatSpeed,de as formatTime};
@@ -1 +1 @@
1
- import{g as P}from"./index-Dp0h2I9v.js";function j(c,d){for(var s=0;s<d.length;s++){const a=d[s];if(typeof a!="string"&&!Array.isArray(a)){for(const i in a)if(i!=="default"&&!(i in c)){const l=Object.getOwnPropertyDescriptor(a,i);l&&Object.defineProperty(c,i,l.get?l:{enumerable:!0,get:()=>a[i]})}}}return Object.freeze(Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}))}var v={},w;function k(){if(w)return v;w=1,Object.defineProperty(v,"__esModule",{value:!0}),v.default=d;var c=window.OfflineAudioContext||window.webkitOfflineAudioContext;function d(e){var r=a(e);return r.start(0),[i,y,O(e.sampleRate),s].reduce(function(t,o){return o(t)},r.buffer.getChannelData(0))}function s(e){return e.sort(function(r,t){return t.count-r.count}).splice(0,5)[0].tempo}function a(e){var r=e.length,t=e.numberOfChannels,o=e.sampleRate,n=new c(t,r,o),u=n.createBufferSource();u.buffer=e;var f=n.createBiquadFilter();return f.type="lowpass",u.connect(f),f.connect(n.destination),u}function i(e){for(var r=[],t=.9,o=.3,n=15;r.length<n&&t>=o;)r=l(e,t),t-=.05;if(r.length<n)throw new Error("Could not find enough samples for a reliable detection.");return r}function l(e,r){for(var t=[],o=0,n=e.length;o<n;o+=1)e[o]>r&&(t.push(o),o+=1e4);return t}function y(e){var r=[];return e.forEach(function(t,o){for(var n=function(x){var g=e[o+x]-t,_=r.some(function(h){if(h.interval===g)return h.count+=1});_||r.push({interval:g,count:1})},u=0;u<10;u+=1)n(u)}),r}function O(e){return function(r){var t=[];return r.forEach(function(o){if(o.interval!==0){for(var n=60/(o.interval/e);n<90;)n*=2;for(;n>180;)n/=2;n=Math.round(n);var u=t.some(function(f){if(f.tempo===n)return f.count+=o.count});u||t.push({tempo:n,count:o.count})}}),t}}return v}var p,b;function q(){return b||(b=1,p=k().default),p}var m=q();const A=P(m),D=j({__proto__:null,default:A},[m]);export{D as i};
1
+ import{g as P}from"./index-D_JGXmfx.js";function j(c,d){for(var s=0;s<d.length;s++){const a=d[s];if(typeof a!="string"&&!Array.isArray(a)){for(const i in a)if(i!=="default"&&!(i in c)){const l=Object.getOwnPropertyDescriptor(a,i);l&&Object.defineProperty(c,i,l.get?l:{enumerable:!0,get:()=>a[i]})}}}return Object.freeze(Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}))}var v={},w;function k(){if(w)return v;w=1,Object.defineProperty(v,"__esModule",{value:!0}),v.default=d;var c=window.OfflineAudioContext||window.webkitOfflineAudioContext;function d(e){var r=a(e);return r.start(0),[i,y,O(e.sampleRate),s].reduce(function(t,o){return o(t)},r.buffer.getChannelData(0))}function s(e){return e.sort(function(r,t){return t.count-r.count}).splice(0,5)[0].tempo}function a(e){var r=e.length,t=e.numberOfChannels,o=e.sampleRate,n=new c(t,r,o),u=n.createBufferSource();u.buffer=e;var f=n.createBiquadFilter();return f.type="lowpass",u.connect(f),f.connect(n.destination),u}function i(e){for(var r=[],t=.9,o=.3,n=15;r.length<n&&t>=o;)r=l(e,t),t-=.05;if(r.length<n)throw new Error("Could not find enough samples for a reliable detection.");return r}function l(e,r){for(var t=[],o=0,n=e.length;o<n;o+=1)e[o]>r&&(t.push(o),o+=1e4);return t}function y(e){var r=[];return e.forEach(function(t,o){for(var n=function(x){var g=e[o+x]-t,_=r.some(function(h){if(h.interval===g)return h.count+=1});_||r.push({interval:g,count:1})},u=0;u<10;u+=1)n(u)}),r}function O(e){return function(r){var t=[];return r.forEach(function(o){if(o.interval!==0){for(var n=60/(o.interval/e);n<90;)n*=2;for(;n>180;)n/=2;n=Math.round(n);var u=t.some(function(f){if(f.tempo===n)return f.count+=o.count});u||t.push({tempo:n,count:o.count})}}),t}}return v}var p,b;function q(){return b||(b=1,p=k().default),p}var m=q();const A=P(m),D=j({__proto__:null,default:A},[m]);export{D as i};
@@ -1,4 +1,4 @@
1
- import{n as Qi}from"./index-Dp0h2I9v.js";/*!
1
+ import{n as Qi}from"./index-D_JGXmfx.js";/*!
2
2
  * Copyright (c) 2026-present, Vanilagy and contributors
3
3
  *
4
4
  * This Source Code Form is subject to the terms of the Mozilla Public