@hussmartinez/audio-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { SdkError, coreLimits, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, sdkCoreMessages } from "@hussmartinez/sdk-core";
1
+ import { SdkError, applyCommands, checkFile, coreLimits, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, locate, plural, resolveAssetsBase, sdkCoreMessages, sequenceOffsets, withProcessingTime } from "@hussmartinez/sdk-core";
2
2
  // src/core/errors/audio-error.ts
3
3
  var AudioError = class extends SdkError {
4
4
  name = "AudioError";
@@ -7,30 +7,10 @@ function isAudioError(value, code) {
7
7
  return isSdkError(value, code) && value.name === "AudioError";
8
8
  }
9
9
  // src/core/errors/abort.ts
10
- function asAudioError(reason, message = "Audio processing failed.") {
11
- if (reason instanceof AudioError) return reason;
12
- if (isSdkError(reason)) return new AudioError(reason.code, reason.message, {
13
- ...reason.details === void 0 ? {} : { details: reason.details },
14
- cause: reason
15
- });
16
- return new AudioError("UNKNOWN", message, { cause: reason });
17
- }
18
- function abortError(signal) {
19
- const { reason } = signal;
20
- if (reason instanceof AudioError) return reason;
21
- if (isSdkError(reason)) return asAudioError(reason);
22
- const timedOut = reason instanceof DOMException && reason.name === "TimeoutError";
23
- return new AudioError(timedOut ? "TIMEOUT" : "ABORTED", timedOut ? "The operation timed out." : "The operation was cancelled.", { cause: reason });
24
- }
25
- function throwIfAborted(signal) {
26
- if (signal?.aborted) throw abortError(signal);
27
- }
28
- // src/adapters/assets-url.ts
29
- function assetsBase(assetsUrl) {
30
- if (assetsUrl === void 0) return void 0;
31
- const base = new URL(String(assetsUrl), globalThis.location?.href).href;
32
- return base.endsWith("/") ? base : `${base}/`;
33
- }
10
+ var { adapt: asAudioError, abortError, throwIfAborted } = /* @__PURE__ */ createErrorHelpers(AudioError, {
11
+ fallbackCode: "UNKNOWN",
12
+ fallbackMessage: "Audio processing failed."
13
+ });
34
14
  var LEVEL_FACTOR = 4;
35
15
  function buildPyramid(finest, bucket = 256) {
36
16
  const levels = [];
@@ -140,14 +120,13 @@ async function decodeOnPage(file, probe, decoder, createBuffer, signal) {
140
120
  // src/adapters/audio-engine.ts
141
121
  var BLOCK_FRAMES = 65536;
142
122
  function createAudioEngine(options = {}) {
143
- const base = assetsBase(options.assetsUrl);
144
- const selfHosted = base === void 0 ? void 0 : `${base}audio/audio.worker.js`;
123
+ const selfHosted = options.assetsUrl === void 0 ? void 0 : new URL("audio/audio.worker.js", resolveAssetsBase(options.assetsUrl)).href;
145
124
  return createEngine({
146
125
  loadWorker: selfHosted ? async () => () => new Worker(selfHosted, {
147
126
  type: "module",
148
127
  name: "hm-audio"
149
- }) : async () => (await import("./lazy/inline-worker-CexEKodJ.js")).createInlineWorker,
150
- version: "0.1.0",
128
+ }) : async () => (await import("./lazy/inline-worker-CkUV_wKW.js")).createInlineWorker,
129
+ version: "0.2.0",
151
130
  ...selfHosted ? { asset: selfHosted } : {},
152
131
  createBuffer: (bufferOptions) => new AudioBuffer(bufferOptions),
153
132
  decodePlatform: webAudioDecoder,
@@ -166,29 +145,15 @@ function createEngine(environment) {
166
145
  return startWorker();
167
146
  },
168
147
  errorClasses: { AudioError },
148
+ packageVersion: environment.version,
149
+ ...environment.asset === void 0 ? {} : { workerAsset: environment.asset },
169
150
  ...environment.idleTimeout === void 0 ? {} : { idleTimeout: environment.idleTimeout }
170
151
  });
171
152
  let main;
172
153
  let analysis;
173
- let versionChecked;
174
154
  async function ready() {
175
155
  if (destroyed) throw new Error("The audio engine has been destroyed.");
176
156
  startWorker ??= await environment.loadWorker();
177
- versionChecked ??= (async () => {
178
- main ??= newClient();
179
- const actual = await main.call("version", void 0);
180
- if (actual !== environment.version) throw new AudioError("WORKER_START_FAILED", "The audio worker isn't this version of the SDK. Copy dist/assets again after upgrading.", { details: {
181
- asset: environment.asset ?? "inline",
182
- expected: environment.version,
183
- actual
184
- } });
185
- })();
186
- try {
187
- await versionChecked;
188
- } catch (error) {
189
- versionChecked = void 0;
190
- throw error;
191
- }
192
157
  }
193
158
  async function run(work) {
194
159
  try {
@@ -346,7 +311,7 @@ var audioLimitDefinitions = {
346
311
  },
347
312
  maxSampleRate: {
348
313
  code: "SAMPLE_RATE_TOO_HIGH",
349
- unit: "count",
314
+ unit: "hertz",
350
315
  default: 192e3
351
316
  },
352
317
  maxSessionSize: {
@@ -362,6 +327,661 @@ var audioLimitDefinitions = {
362
327
  }
363
328
  };
364
329
  var audioLimits = /* @__PURE__ */ defineLimits(audioLimitDefinitions, { errorClass: AudioError });
330
+ // src/core/model/plan.ts
331
+ var EMPTY_METADATA = Object.freeze({
332
+ title: "",
333
+ artist: "",
334
+ album: "",
335
+ year: "",
336
+ comment: ""
337
+ });
338
+ var NO_FADE = Object.freeze({
339
+ frames: 0,
340
+ curve: "linear"
341
+ });
342
+ function clipLength(clip) {
343
+ return clip.end - clip.start;
344
+ }
345
+ function planLength(plan) {
346
+ let total = 0;
347
+ for (const clip of plan.clips) total += clipLength(clip);
348
+ return total;
349
+ }
350
+ function clipOffsets(plan) {
351
+ return clipBoundaries(plan).slice(0, -1);
352
+ }
353
+ function clipBoundaries(plan) {
354
+ return sequenceOffsets(plan.clips.map(clipLength));
355
+ }
356
+ var MIN_GAIN_DB = -120;
357
+ var MAX_GAIN_DB = 120;
358
+ var isFrames = (value) => Number.isSafeInteger(value) && value >= 0;
359
+ function clipProblem(clip, sourceFrames) {
360
+ if (![
361
+ clip.start,
362
+ clip.end,
363
+ clip.fadeIn.frames,
364
+ clip.fadeOut.frames
365
+ ].every(isFrames)) return "invalid-frames";
366
+ if (clip.end <= clip.start) return "clip-too-short";
367
+ if (clip.end > sourceFrames) return "clip-outside-source";
368
+ if (typeof clip.gainDb !== "number" || !(clip.gainDb >= -120 && clip.gainDb <= 120)) return "gain-out-of-range";
369
+ if (clip.fadeIn.frames + clip.fadeOut.frames > clipLength(clip)) return "fades-too-long";
370
+ }
371
+ // src/core/operations/commands.ts
372
+ var MAX_METADATA_LENGTH = 1e3;
373
+ var CURVES = /* @__PURE__ */ new Set(["linear", "equalPower"]);
374
+ var Invalid = class extends Error {
375
+ reason;
376
+ constructor(reason, message) {
377
+ super(message);
378
+ this.reason = reason;
379
+ }
380
+ };
381
+ function invalid(reason, message) {
382
+ throw new Invalid(reason, message);
383
+ }
384
+ function isRecord(value) {
385
+ return typeof value === "object" && value !== null;
386
+ }
387
+ function isKey(value) {
388
+ return typeof value === "string" && value.length > 0;
389
+ }
390
+ function isIndex(value, max) {
391
+ return Number.isSafeInteger(value) && value >= 0 && value <= max;
392
+ }
393
+ function fade(value, name) {
394
+ if (!isRecord(value)) invalid("malformed-command", `${name} isn't a fade`);
395
+ onlyFields(value, FADE_FIELDS, name);
396
+ if (typeof value.curve !== "string" || !CURVES.has(value.curve)) invalid("invalid-fade-curve", `${name}'s curve isn't linear or equalPower`);
397
+ return {
398
+ frames: value.frames,
399
+ curve: value.curve
400
+ };
401
+ }
402
+ var COMMAND_FIELDS = {
403
+ "audio.insertClips": [
404
+ "at",
405
+ "clips",
406
+ "splitKey"
407
+ ],
408
+ "audio.removeClips": ["keys"],
409
+ "audio.restoreClips": ["entries"],
410
+ "audio.replaceClips": [
411
+ "index",
412
+ "count",
413
+ "clips"
414
+ ],
415
+ "audio.updateClips": ["clips"],
416
+ "audio.deleteRange": [
417
+ "start",
418
+ "end",
419
+ "newKey"
420
+ ],
421
+ "audio.trimClip": [
422
+ "key",
423
+ "start",
424
+ "end"
425
+ ],
426
+ "audio.splitClip": [
427
+ "key",
428
+ "at",
429
+ "newKey"
430
+ ],
431
+ "audio.moveClips": ["keys", "to"],
432
+ "audio.reorderClips": ["order"],
433
+ "audio.setGain": ["keys", "gainDb"],
434
+ "audio.setFade": [
435
+ "key",
436
+ "edge",
437
+ "frames",
438
+ "curve"
439
+ ],
440
+ "audio.setMetadata": ["field", "value"]
441
+ };
442
+ var CLIP_FIELDS = [
443
+ "key",
444
+ "source",
445
+ "start",
446
+ "end",
447
+ "gainDb",
448
+ "fadeIn",
449
+ "fadeOut"
450
+ ];
451
+ var FADE_FIELDS = ["frames", "curve"];
452
+ var ENTRY_FIELDS = ["index", "clip"];
453
+ function onlyFields(value, allowed, what) {
454
+ for (const [field, content] of Object.entries(value)) if (content !== void 0 && !allowed.includes(field)) invalid("malformed-command", `${what} has no field ${field}`);
455
+ }
456
+ function optionalKey(value, name) {
457
+ if (value !== void 0 && !isKey(value)) invalid("malformed-command", `${name} must be a non-empty string`);
458
+ return value;
459
+ }
460
+ function checkClip(value, sourceFrames) {
461
+ if (!isRecord(value) || !isKey(value.key) || !isKey(value.source)) invalid("malformed-command", "a clip needs a key and a source");
462
+ onlyFields(value, CLIP_FIELDS, "a clip");
463
+ const clip = {
464
+ key: value.key,
465
+ source: value.source,
466
+ start: value.start,
467
+ end: value.end,
468
+ gainDb: value.gainDb,
469
+ fadeIn: fade(value.fadeIn, "fadeIn"),
470
+ fadeOut: fade(value.fadeOut, "fadeOut")
471
+ };
472
+ const frames = sourceFrames(clip.source);
473
+ if (frames === void 0) invalid("unknown-source", `the session has no source ${clip.source}`);
474
+ const problem = clipProblem(clip, frames);
475
+ if (problem) invalid(problem, `clip ${clip.key} isn't valid within its source`);
476
+ return clip;
477
+ }
478
+ function checkClips(values, sourceFrames) {
479
+ if (!Array.isArray(values)) invalid("malformed-command", "clips must be a list");
480
+ return values.map((value) => checkClip(value, sourceFrames));
481
+ }
482
+ function checkNewKeys(keys, existing) {
483
+ const taken = new Set(existing);
484
+ const seen = /* @__PURE__ */ new Set();
485
+ for (const key of keys) {
486
+ if (!isKey(key)) invalid("malformed-command", "a key must be a non-empty string");
487
+ if (taken.has(key)) invalid("key-taken", `the key ${key} is taken`);
488
+ if (seen.has(key)) invalid("duplicate-key", `the key ${key} appears twice`);
489
+ seen.add(key);
490
+ }
491
+ }
492
+ function positions(plan, keys) {
493
+ if (!Array.isArray(keys)) invalid("malformed-command", "keys must be a list");
494
+ if (keys.length === 0) invalid("no-clips", "it needs at least one clip");
495
+ const wanted = new Set(keys);
496
+ if (wanted.size !== keys.length) invalid("duplicate-key", "a clip appears twice");
497
+ const found = [];
498
+ plan.clips.forEach((clip, index) => {
499
+ if (wanted.has(clip.key)) found.push(index);
500
+ });
501
+ if (found.length !== wanted.size) invalid("unknown-clip", "the plan doesn't have every clip");
502
+ return found;
503
+ }
504
+ function position(plan, key) {
505
+ return positions(plan, [key])[0];
506
+ }
507
+ function fitFades(clip) {
508
+ const length = clipLength(clip);
509
+ const total = clip.fadeIn.frames + clip.fadeOut.frames;
510
+ if (total <= length || !(length > 0)) return clip;
511
+ return {
512
+ ...clip,
513
+ fadeIn: {
514
+ ...clip.fadeIn,
515
+ frames: Math.floor(clip.fadeIn.frames * length / total)
516
+ },
517
+ fadeOut: {
518
+ ...clip.fadeOut,
519
+ frames: Math.floor(clip.fadeOut.frames * length / total)
520
+ }
521
+ };
522
+ }
523
+ function part(clip, from, to, key) {
524
+ const length = clipLength(clip);
525
+ return fitFades({
526
+ ...clip,
527
+ key,
528
+ start: clip.start + from,
529
+ end: clip.start + to,
530
+ fadeIn: from === 0 ? clip.fadeIn : NO_FADE,
531
+ fadeOut: to === length ? clip.fadeOut : NO_FADE
532
+ });
533
+ }
534
+ function locate$1(plan, frame) {
535
+ if (!isIndex(frame, planLength(plan))) invalid("frame-outside-plan", "the frame is outside the plan");
536
+ const found = locate(clipBoundaries(plan), frame);
537
+ return found ? {
538
+ index: found.index,
539
+ offset: found.within
540
+ } : {
541
+ index: plan.clips.length,
542
+ offset: 0
543
+ };
544
+ }
545
+ function withClips(plan, clips) {
546
+ return {
547
+ ...plan,
548
+ clips
549
+ };
550
+ }
551
+ function splice(plan, index, count, clips) {
552
+ return withClips(plan, [
553
+ ...plan.clips.slice(0, index),
554
+ ...clips,
555
+ ...plan.clips.slice(index + count)
556
+ ]);
557
+ }
558
+ function updateByKey(plan, clips) {
559
+ const byKey = new Map(clips.map((clip) => [clip.key, clip]));
560
+ return withClips(plan, plan.clips.map((clip) => byKey.get(clip.key) ?? clip));
561
+ }
562
+ function apply(plan, command, sourceFrames) {
563
+ if (!isRecord(command)) invalid("malformed-command", "a command is an object");
564
+ const fields = Object.hasOwn(COMMAND_FIELDS, command.type) ? COMMAND_FIELDS[command.type] : void 0;
565
+ if (!fields) invalid("unknown-command", "unknown command");
566
+ onlyFields(command, ["type", ...fields], command.type);
567
+ switch (command.type) {
568
+ case "audio.insertClips": {
569
+ const clips = checkClips(command.clips, sourceFrames);
570
+ if (clips.length === 0) invalid("no-clips", "it needs at least one clip");
571
+ const keys = clips.map((clip) => clip.key);
572
+ checkNewKeys(keys, plan.clips.map((clip) => clip.key));
573
+ const splitKey = optionalKey(command.splitKey, "splitKey");
574
+ const { index, offset } = locate$1(plan, command.at);
575
+ if (offset === 0) return {
576
+ state: splice(plan, index, 0, clips),
577
+ inverse: {
578
+ type: "audio.replaceClips",
579
+ index,
580
+ count: clips.length,
581
+ clips: []
582
+ }
583
+ };
584
+ if (splitKey === void 0) invalid("new-key-required", "inserting inside a clip needs a splitKey");
585
+ checkNewKeys([splitKey], [...plan.clips.map((clip) => clip.key), ...keys]);
586
+ const split = plan.clips[index];
587
+ const parts = [
588
+ part(split, 0, offset, split.key),
589
+ ...clips,
590
+ part(split, offset, clipLength(split), splitKey)
591
+ ];
592
+ return {
593
+ state: splice(plan, index, 1, parts),
594
+ inverse: {
595
+ type: "audio.replaceClips",
596
+ index,
597
+ count: parts.length,
598
+ clips: [split]
599
+ }
600
+ };
601
+ }
602
+ case "audio.removeClips": {
603
+ const at = positions(plan, command.keys);
604
+ const removed = new Set(at);
605
+ return {
606
+ state: withClips(plan, plan.clips.filter((_, index) => !removed.has(index))),
607
+ inverse: {
608
+ type: "audio.restoreClips",
609
+ entries: at.map((index) => ({
610
+ index,
611
+ clip: plan.clips[index]
612
+ }))
613
+ }
614
+ };
615
+ }
616
+ case "audio.restoreClips": {
617
+ if (!Array.isArray(command.entries)) invalid("malformed-command", "entries must be a list");
618
+ if (command.entries.length === 0) invalid("no-clips", "it needs at least one clip");
619
+ const entries = command.entries.map((entry) => {
620
+ if (!isRecord(entry)) invalid("malformed-command", "an entry needs an index and a clip");
621
+ onlyFields(entry, ENTRY_FIELDS, "an entry");
622
+ return {
623
+ index: entry.index,
624
+ clip: checkClip(entry.clip, sourceFrames)
625
+ };
626
+ });
627
+ checkNewKeys(entries.map(({ clip }) => clip.key), plan.clips.map((clip) => clip.key));
628
+ const clips = [...plan.clips];
629
+ let previous = -1;
630
+ for (const { index, clip } of entries) {
631
+ if (!isIndex(index, clips.length) || index <= previous) invalid("invalid-index", `clip ${clip.key} can't be restored at index ${String(index)}`);
632
+ clips.splice(index, 0, clip);
633
+ previous = index;
634
+ }
635
+ return {
636
+ state: withClips(plan, clips),
637
+ inverse: {
638
+ type: "audio.removeClips",
639
+ keys: entries.map(({ clip }) => clip.key)
640
+ }
641
+ };
642
+ }
643
+ case "audio.replaceClips": {
644
+ const { index, count } = command;
645
+ if (!isIndex(index, plan.clips.length) || !isIndex(count, plan.clips.length - index)) invalid("invalid-index", "the run of clips is outside the plan");
646
+ const clips = checkClips(command.clips, sourceFrames);
647
+ if (count === 0 && clips.length === 0) invalid("empty-change", "it changes nothing");
648
+ const removed = plan.clips.slice(index, index + count);
649
+ checkNewKeys(clips.map((clip) => clip.key), [...plan.clips.slice(0, index), ...plan.clips.slice(index + count)].map((clip) => clip.key));
650
+ return {
651
+ state: splice(plan, index, count, clips),
652
+ inverse: {
653
+ type: "audio.replaceClips",
654
+ index,
655
+ count: clips.length,
656
+ clips: removed
657
+ }
658
+ };
659
+ }
660
+ case "audio.updateClips": {
661
+ const clips = checkClips(command.clips, sourceFrames);
662
+ const at = positions(plan, clips.map((clip) => clip.key));
663
+ return {
664
+ state: updateByKey(plan, clips),
665
+ inverse: {
666
+ type: "audio.updateClips",
667
+ clips: at.map((index) => plan.clips[index])
668
+ }
669
+ };
670
+ }
671
+ case "audio.deleteRange": {
672
+ const { start, end } = command;
673
+ const newKey = optionalKey(command.newKey, "newKey");
674
+ if (!isIndex(start, planLength(plan)) || !isIndex(end, planLength(plan))) invalid("frame-outside-plan", "the range must be inside the plan");
675
+ if (end <= start) invalid("empty-range", "the range must be at least one frame long");
676
+ const first = locate$1(plan, start);
677
+ const last = locate$1(plan, end - 1);
678
+ const firstClip = plan.clips[first.index];
679
+ const lastClip = plan.clips[last.index];
680
+ const kept = [];
681
+ if (first.offset > 0) kept.push(part(firstClip, 0, first.offset, firstClip.key));
682
+ if (last.offset + 1 < clipLength(lastClip)) {
683
+ let key = lastClip.key;
684
+ if (first.index === last.index && first.offset > 0) {
685
+ if (newKey === void 0) invalid("new-key-required", "deleting inside a clip needs a newKey");
686
+ checkNewKeys([newKey], plan.clips.map((clip) => clip.key));
687
+ key = newKey;
688
+ }
689
+ kept.push(part(lastClip, last.offset + 1, clipLength(lastClip), key));
690
+ }
691
+ const count = last.index - first.index + 1;
692
+ return {
693
+ state: splice(plan, first.index, count, kept),
694
+ inverse: {
695
+ type: "audio.replaceClips",
696
+ index: first.index,
697
+ count: kept.length,
698
+ clips: plan.clips.slice(first.index, first.index + count)
699
+ }
700
+ };
701
+ }
702
+ case "audio.trimClip": {
703
+ const index = position(plan, command.key);
704
+ const clip = plan.clips[index];
705
+ return {
706
+ state: updateByKey(plan, [checkClip(fitFades({
707
+ ...clip,
708
+ start: command.start,
709
+ end: command.end
710
+ }), sourceFrames)]),
711
+ inverse: {
712
+ type: "audio.updateClips",
713
+ clips: [clip]
714
+ }
715
+ };
716
+ }
717
+ case "audio.splitClip": {
718
+ const index = position(plan, command.key);
719
+ const clip = plan.clips[index];
720
+ const { index: within, offset } = locate$1(plan, command.at);
721
+ if (within !== index || offset === 0) invalid("not-inside-clip", "the frame must be strictly inside the clip");
722
+ checkNewKeys([command.newKey], plan.clips.map((entry) => entry.key));
723
+ return {
724
+ state: splice(plan, index, 1, [part(clip, 0, offset, clip.key), part(clip, offset, clipLength(clip), command.newKey)]),
725
+ inverse: {
726
+ type: "audio.replaceClips",
727
+ index,
728
+ count: 2,
729
+ clips: [clip]
730
+ }
731
+ };
732
+ }
733
+ case "audio.moveClips": {
734
+ const moved = new Set(positions(plan, command.keys));
735
+ const block = plan.clips.filter((_, index) => moved.has(index));
736
+ const rest = plan.clips.filter((_, index) => !moved.has(index));
737
+ if (!isIndex(command.to, rest.length)) invalid("invalid-index", "the clips can't move there");
738
+ return {
739
+ state: withClips(plan, [
740
+ ...rest.slice(0, command.to),
741
+ ...block,
742
+ ...rest.slice(command.to)
743
+ ]),
744
+ inverse: {
745
+ type: "audio.reorderClips",
746
+ order: plan.clips.map((clip) => clip.key)
747
+ }
748
+ };
749
+ }
750
+ case "audio.reorderClips": {
751
+ const { order } = command;
752
+ const byKey = new Map(plan.clips.map((clip) => [clip.key, clip]));
753
+ if (!Array.isArray(order) || order.length !== plan.clips.length || new Set(order).size !== order.length || order.some((key) => !byKey.has(key))) invalid("invalid-order", "the order must list every clip exactly once");
754
+ return {
755
+ state: withClips(plan, order.map((key) => byKey.get(key))),
756
+ inverse: {
757
+ type: "audio.reorderClips",
758
+ order: plan.clips.map((clip) => clip.key)
759
+ }
760
+ };
761
+ }
762
+ case "audio.setGain": {
763
+ const at = positions(plan, command.keys);
764
+ const gainDb = command.gainDb;
765
+ if (typeof gainDb !== "number" || !(gainDb >= -120 && gainDb <= 120)) invalid("gain-out-of-range", `gain must be from ${MIN_GAIN_DB} to 120 dB`);
766
+ const before = at.map((index) => plan.clips[index]);
767
+ return {
768
+ state: updateByKey(plan, before.map((clip) => ({
769
+ ...clip,
770
+ gainDb
771
+ }))),
772
+ inverse: {
773
+ type: "audio.updateClips",
774
+ clips: before
775
+ }
776
+ };
777
+ }
778
+ case "audio.setFade": {
779
+ const clip = plan.clips[position(plan, command.key)];
780
+ const { edge, frames } = command;
781
+ if (edge !== "in" && edge !== "out") invalid("invalid-edge", "the edge must be in or out");
782
+ const next = {
783
+ frames,
784
+ curve: fade({
785
+ frames,
786
+ curve: command.curve
787
+ }, "the fade").curve
788
+ };
789
+ return {
790
+ state: updateByKey(plan, [checkClip(edge === "in" ? {
791
+ ...clip,
792
+ fadeIn: next
793
+ } : {
794
+ ...clip,
795
+ fadeOut: next
796
+ }, sourceFrames)]),
797
+ inverse: {
798
+ type: "audio.updateClips",
799
+ clips: [clip]
800
+ }
801
+ };
802
+ }
803
+ case "audio.setMetadata": {
804
+ const { field, value } = command;
805
+ if (typeof field !== "string" || !Object.hasOwn(EMPTY_METADATA, field)) invalid("unknown-metadata-field", "there's no such metadata field");
806
+ if (typeof value !== "string") invalid("malformed-command", "a metadata value must be text");
807
+ if (value.length > 1e3) invalid("metadata-too-long", `a metadata value can have at most ${MAX_METADATA_LENGTH} characters`);
808
+ return {
809
+ state: {
810
+ ...plan,
811
+ metadata: {
812
+ ...plan.metadata,
813
+ [field]: value
814
+ }
815
+ },
816
+ inverse: {
817
+ type: "audio.setMetadata",
818
+ field,
819
+ value: plan.metadata[field]
820
+ }
821
+ };
822
+ }
823
+ default: return invalid("unknown-command", "unknown command");
824
+ }
825
+ }
826
+ function createPlanReducer(sourceFrames) {
827
+ return (plan, command) => {
828
+ try {
829
+ return apply(plan, command, sourceFrames);
830
+ } catch (error) {
831
+ if (!(error instanceof Invalid)) throw error;
832
+ const type = isRecord(command) && typeof command.type === "string" ? command.type : "";
833
+ const known = type.startsWith("audio.") && type.length <= 64;
834
+ throw new AudioError("INVALID_COMMAND", `Invalid ${known ? type : "command"}: ${error.message}.`, { details: known ? {
835
+ command: type,
836
+ reason: error.reason
837
+ } : { reason: error.reason } });
838
+ }
839
+ };
840
+ }
841
+ // src/core/format/plan-document.ts
842
+ var AUDIO_PLAN_FORMAT = "hm-audio-plan";
843
+ var AUDIO_PLAN_VERSION = 1;
844
+ var DOCUMENT_FIELDS = [
845
+ "format",
846
+ "version",
847
+ "sampleRate",
848
+ "channels",
849
+ "sources",
850
+ "clips",
851
+ "metadata"
852
+ ];
853
+ var SOURCE_FIELDS = ["frames", "asset"];
854
+ var ASSET_FIELDS = [
855
+ "asset",
856
+ "mediaType",
857
+ "size"
858
+ ];
859
+ var METADATA_FIELDS = [
860
+ "title",
861
+ "artist",
862
+ "album",
863
+ "year",
864
+ "comment"
865
+ ];
866
+ var ASSET_ID = /^sha256:[0-9a-f]{64}$/;
867
+ var MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;
868
+ function malformed(message) {
869
+ return invalid("malformed-command", message);
870
+ }
871
+ var isCount = (value, min) => Number.isSafeInteger(value) && value >= min;
872
+ function readAsset(value) {
873
+ if (!isRecord(value)) malformed("an asset is an object");
874
+ onlyFields(value, ASSET_FIELDS, "an asset");
875
+ const { asset, mediaType, size } = value;
876
+ if (typeof asset !== "string" || !ASSET_ID.test(asset)) malformed("an asset id is sha256:<hex>");
877
+ if (typeof mediaType !== "string" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) malformed("a media type is type/subtype, in lowercase");
878
+ if (!isCount(size, 0)) malformed("an asset's size is a whole number of bytes");
879
+ return {
880
+ asset,
881
+ mediaType,
882
+ size
883
+ };
884
+ }
885
+ function readSources(value) {
886
+ if (!isRecord(value) || Array.isArray(value)) malformed("sources is an object");
887
+ return Object.fromEntries(Object.entries(value).map(([id, source]) => {
888
+ if (!isKey(id)) malformed("a source id is a non-empty string");
889
+ if (!isRecord(source)) malformed("a source is an object");
890
+ onlyFields(source, SOURCE_FIELDS, "a source");
891
+ if (!isCount(source.frames, 1)) malformed("a source's frames are a whole number above 0");
892
+ return [id, source.asset === void 0 ? { frames: source.frames } : {
893
+ frames: source.frames,
894
+ asset: readAsset(source.asset)
895
+ }];
896
+ }));
897
+ }
898
+ function readMetadata(value) {
899
+ if (!isRecord(value)) malformed("metadata is an object");
900
+ onlyFields(value, METADATA_FIELDS, "metadata");
901
+ const fields = METADATA_FIELDS.map((field) => {
902
+ const text = value[field];
903
+ if (typeof text !== "string") malformed(`metadata.${field} is text`);
904
+ if (text.length > 1e3) invalid("metadata-too-long", `metadata.${field} is over ${MAX_METADATA_LENGTH} characters`);
905
+ return [field, text];
906
+ });
907
+ return Object.fromEntries(fields);
908
+ }
909
+ function read(value) {
910
+ if (!isRecord(value) || Array.isArray(value)) malformed("a document is an object");
911
+ const { format, version } = value;
912
+ if (typeof format !== "string") malformed("format is text");
913
+ if (format !== "hm-audio-plan") throw new AudioError("UNSUPPORTED_FORMAT", `This isn't an ${AUDIO_PLAN_FORMAT} document.`, { details: {
914
+ format: AUDIO_PLAN_FORMAT,
915
+ reason: "unknown-format"
916
+ } });
917
+ if (Number.isSafeInteger(version) && version > 1) throw new AudioError("UNSUPPORTED_FORMAT", `This ${AUDIO_PLAN_FORMAT} document is a later version than this release reads.`, { details: {
918
+ format: AUDIO_PLAN_FORMAT,
919
+ reason: "unknown-format-version"
920
+ } });
921
+ if (version !== 1) malformed("version is 1");
922
+ onlyFields(value, DOCUMENT_FIELDS, "a document");
923
+ if (!isCount(value.sampleRate, 1)) malformed("sampleRate is a whole number above 0");
924
+ if (!isCount(value.channels, 1)) malformed("channels is a whole number above 0");
925
+ const sources = readSources(value.sources);
926
+ if (!Array.isArray(value.clips)) malformed("clips is a list");
927
+ const lookup = (id) => Object.hasOwn(sources, id) ? sources[id]?.frames : void 0;
928
+ const clips = value.clips.map((clip) => checkClip(clip, lookup));
929
+ const keys = /* @__PURE__ */ new Set();
930
+ for (const { key } of clips) {
931
+ if (keys.has(key)) invalid("duplicate-key", `two clips have the key ${key}`);
932
+ keys.add(key);
933
+ }
934
+ return {
935
+ plan: {
936
+ sampleRate: value.sampleRate,
937
+ channels: value.channels,
938
+ clips,
939
+ metadata: readMetadata(value.metadata)
940
+ },
941
+ sources
942
+ };
943
+ }
944
+ function readAudioPlanDocument(value) {
945
+ try {
946
+ return read(value);
947
+ } catch (error) {
948
+ if (!(error instanceof Invalid)) throw error;
949
+ const reason = error.reason === "malformed-command" ? "malformed-document" : error.reason;
950
+ throw new AudioError("INVALID_DOCUMENT", `Invalid ${AUDIO_PLAN_FORMAT} document: ${error.message}.`, { details: {
951
+ format: AUDIO_PLAN_FORMAT,
952
+ reason
953
+ } });
954
+ }
955
+ }
956
+ function toAudioPlanDocument(plan, sources) {
957
+ for (const clip of plan.clips) if (!Object.hasOwn(sources, clip.source)) throw new TypeError(`The sources don't include ${clip.source}, which clip ${clip.key} uses.`);
958
+ return {
959
+ format: AUDIO_PLAN_FORMAT,
960
+ version: 1,
961
+ sampleRate: plan.sampleRate,
962
+ channels: plan.channels,
963
+ sources: Object.fromEntries(Object.entries(sources).map(([id, { frames, asset }]) => [id, asset === void 0 ? { frames } : {
964
+ frames,
965
+ asset: { ...asset }
966
+ }])),
967
+ clips: plan.clips.map(({ key, source, start, end, gainDb, fadeIn, fadeOut }) => ({
968
+ key,
969
+ source,
970
+ start,
971
+ end,
972
+ gainDb,
973
+ fadeIn: {
974
+ frames: fadeIn.frames,
975
+ curve: fadeIn.curve
976
+ },
977
+ fadeOut: {
978
+ frames: fadeOut.frames,
979
+ curve: fadeOut.curve
980
+ }
981
+ })),
982
+ metadata: { ...plan.metadata }
983
+ };
984
+ }
365
985
  // src/core/model/envelope.ts
366
986
  function dbToGain(db) {
367
987
  return 10 ** (db / 20);
@@ -385,39 +1005,423 @@ function framesToSeconds(frames, sampleRate) {
385
1005
  function secondsToFrames(seconds, sampleRate) {
386
1006
  return Math.round(seconds * sampleRate);
387
1007
  }
388
- // src/core/model/plan.ts
389
- var EMPTY_METADATA = Object.freeze({
390
- title: "",
391
- artist: "",
392
- album: "",
393
- year: "",
394
- comment: ""
395
- });
396
- var NO_FADE = Object.freeze({
397
- frames: 0,
398
- curve: "linear"
399
- });
400
- function clipLength(clip) {
401
- return clip.end - clip.start;
1008
+ // src/core/session/session.ts
1009
+ var BYTES_PER_SAMPLE = 4;
1010
+ function clipsOf(command) {
1011
+ switch (command.type) {
1012
+ case "audio.insertClips":
1013
+ case "audio.replaceClips":
1014
+ case "audio.updateClips": return command.clips;
1015
+ case "audio.restoreClips": return command.entries.map((entry) => entry.clip);
1016
+ default: return [];
1017
+ }
402
1018
  }
403
- function planLength(plan) {
404
- let total = 0;
405
- for (const clip of plan.clips) total += clipLength(clip);
406
- return total;
1019
+ function keysOf(command) {
1020
+ const keys = clipsOf(command).map((clip) => clip.key);
1021
+ if ("newKey" in command && typeof command.newKey === "string") keys.push(command.newKey);
1022
+ if ("splitKey" in command && typeof command.splitKey === "string") keys.push(command.splitKey);
1023
+ return keys;
407
1024
  }
408
- function clipOffsets(plan) {
409
- const offsets = [];
410
- let at = 0;
411
- for (const clip of plan.clips) {
412
- offsets.push(at);
413
- at += clipLength(clip);
1025
+ function createAudioSession(options) {
1026
+ const { engine } = options;
1027
+ const policy = audioLimits.resolve(options.filePolicy);
1028
+ const history = createHistory();
1029
+ const sources = /* @__PURE__ */ new Map();
1030
+ const reducer = createPlanReducer((id) => sources.get(id)?.info.frames);
1031
+ let plan;
1032
+ let status = "empty";
1033
+ let error;
1034
+ let busy = 0;
1035
+ let selection;
1036
+ let nextKey = 0;
1037
+ let nextSource = 0;
1038
+ const loading = /* @__PURE__ */ new Set();
1039
+ const cancelLoads = (message) => {
1040
+ for (const controller of loading) controller.abort(new AudioError("ABORTED", message));
1041
+ };
1042
+ let generation = 0;
1043
+ const superseded = (since) => since !== generation ? new AudioError("ABORTED", "The recording was closed or replaced.") : void 0;
1044
+ const heldBytes = () => {
1045
+ let total = 0;
1046
+ for (const source of sources.values()) total += source.bytes;
1047
+ return total;
1048
+ };
1049
+ function referenced(steps) {
1050
+ const ids = new Set(plan?.clips.map((clip) => clip.source));
1051
+ for (const { commands, inverses } of steps) for (const command of [...commands, ...inverses]) for (const clip of clipsOf(command)) ids.add(clip.source);
1052
+ return ids;
1053
+ }
1054
+ function collect() {
1055
+ const keep = referenced(history.steps);
1056
+ for (const id of sources.keys()) if (!keep.has(id)) sources.delete(id);
414
1057
  }
415
- return offsets;
1058
+ function stepsToDrop(extra) {
1059
+ const { maximum } = policy.limits.maxSessionSize;
1060
+ const order = history.dropOrder;
1061
+ for (let count = 0; count <= order.length; count += 1) {
1062
+ const kept = new Set(order.slice(count));
1063
+ const ids = referenced(history.steps.filter((entry) => kept.has(entry)));
1064
+ let total = extra;
1065
+ for (const id of ids) total += sources.get(id)?.bytes ?? 0;
1066
+ if (total <= maximum) return count;
1067
+ }
1068
+ }
1069
+ function sessionWarnings() {
1070
+ const found = [...sources.values()].flatMap((source) => source.warnings);
1071
+ const bytes = heldBytes();
1072
+ if (bytes > 0 && bytes >= policy.limits.maxSessionSize.warning) found.push({
1073
+ type: "limit",
1074
+ limit: "maxSessionSize",
1075
+ actual: bytes
1076
+ });
1077
+ const clips = plan?.clips.length ?? 0;
1078
+ if (clips > 0 && clips >= policy.limits.maxClips.warning) found.push({
1079
+ type: "limit",
1080
+ limit: "maxClips",
1081
+ actual: clips
1082
+ });
1083
+ return found;
1084
+ }
1085
+ function makeSnapshot() {
1086
+ return Object.freeze({
1087
+ status,
1088
+ plan,
1089
+ sources: Object.freeze([...sources.values()].map((source) => source.info)),
1090
+ canUndo: history.canUndo,
1091
+ canRedo: history.canRedo,
1092
+ historyTrimmed: history.trimmed,
1093
+ busy: busy > 0,
1094
+ error,
1095
+ warnings: Object.freeze(sessionWarnings()),
1096
+ sessionBytes: heldBytes(),
1097
+ selection
1098
+ });
1099
+ }
1100
+ const store = createStore(makeSnapshot());
1101
+ function changed() {
1102
+ if (selection) {
1103
+ const end = Math.min(selection.end, plan ? planLength(plan) : 0);
1104
+ selection = selection.start < end ? {
1105
+ start: selection.start,
1106
+ end
1107
+ } : void 0;
1108
+ }
1109
+ store.set(makeSnapshot());
1110
+ }
1111
+ function emit(event) {
1112
+ try {
1113
+ options.onEvent?.(event);
1114
+ } catch {}
1115
+ }
1116
+ function facts(source) {
1117
+ const { info } = source;
1118
+ return {
1119
+ durationSeconds: framesToSeconds(info.frames, info.sampleRate),
1120
+ sampleRate: info.sampleRate,
1121
+ channels: info.channels,
1122
+ container: info.container,
1123
+ codec: info.codec,
1124
+ truncated: source.warnings.some((warning) => warning.type === "truncated")
1125
+ };
1126
+ }
1127
+ async function load(file, signal, onProgress, beforeDecode) {
1128
+ if (!(file instanceof Blob)) throw new TypeError("A recording must be a Blob or a File.");
1129
+ nextSource += 1;
1130
+ const id = `s${nextSource}`;
1131
+ const warnings = [];
1132
+ const warnAt = (limit, actual) => {
1133
+ if (policy.check(limit, actual) === "warning") warnings.push({
1134
+ type: "limit",
1135
+ limit,
1136
+ actual,
1137
+ source: id
1138
+ });
1139
+ };
1140
+ if (checkFile(policy, file) === "warning") warnings.push({
1141
+ type: "limit",
1142
+ limit: "maxFileSize",
1143
+ actual: file.size,
1144
+ source: id
1145
+ });
1146
+ const probe = await withProcessingTime(policy, (limited) => engine.probe(file, { signal: limited }), { signal });
1147
+ warnAt("maxChannels", probe.channels);
1148
+ warnAt("maxSampleRate", probe.sampleRate);
1149
+ warnAt("maxDuration", Math.ceil(probe.frameBound * 1e3 / probe.sampleRate));
1150
+ warnAt("maxDecodedSize", probe.frameBound * probe.channels * BYTES_PER_SAMPLE);
1151
+ beforeDecode(probe);
1152
+ const audio = await withProcessingTime(policy, (limited) => engine.decode(file, probe, {
1153
+ signal: limited,
1154
+ ...onProgress ? { onProgress } : {}
1155
+ }), { signal });
1156
+ const frames = Math.min(audio.length, probe.frameBound);
1157
+ const channels = audio.numberOfChannels;
1158
+ if (audio.sampleRate !== probe.sampleRate || channels < 1 || channels > probe.channels) throw new AudioError("INVALID_AUDIO", "The decoder's output doesn't match the probe.", { details: {
1159
+ container: probe.container,
1160
+ codec: probe.codec
1161
+ } });
1162
+ if (frames < 1) throw new AudioError("DECODE_FAILED", "The recording decoded to no audio.", { details: { codec: probe.codec } });
1163
+ const peaks = await withProcessingTime(policy, (limited) => engine.peaks(audio, { signal: limited }), { signal });
1164
+ throwIfAborted(signal);
1165
+ if (probe.declaredFrames !== void 0 && probe.declaredFrames > frames) warnings.push({
1166
+ type: "truncated",
1167
+ source: id,
1168
+ frames,
1169
+ declaredFrames: probe.declaredFrames
1170
+ });
1171
+ return {
1172
+ info: Object.freeze({
1173
+ id,
1174
+ sampleRate: audio.sampleRate,
1175
+ channels,
1176
+ frames,
1177
+ container: probe.container,
1178
+ codec: probe.codec
1179
+ }),
1180
+ audio,
1181
+ peaks,
1182
+ bytes: frames * channels * BYTES_PER_SAMPLE,
1183
+ warnings: Object.freeze(warnings)
1184
+ };
1185
+ }
1186
+ async function track(signal, replaces, run) {
1187
+ if (replaces) cancelLoads("A newer recording replaced this one.");
1188
+ const controller = new AbortController();
1189
+ loading.add(controller);
1190
+ const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
1191
+ busy += 1;
1192
+ changed();
1193
+ try {
1194
+ return await run(combined);
1195
+ } finally {
1196
+ busy -= 1;
1197
+ loading.delete(controller);
1198
+ changed();
1199
+ }
1200
+ }
1201
+ function applyChecked(current, commands) {
1202
+ const result = applyCommands(reducer, current, commands);
1203
+ if (result.state.clips.length > current.clips.length) policy.check("maxClips", result.state.clips.length);
1204
+ return result;
1205
+ }
1206
+ function commit(result, commands) {
1207
+ plan = result.state;
1208
+ history.push({
1209
+ commands,
1210
+ inverses: result.inverses
1211
+ });
1212
+ collect();
1213
+ }
1214
+ function newKey() {
1215
+ const used = new Set(plan?.clips.map((clip) => clip.key));
1216
+ for (const { commands, inverses } of history.steps) for (const command of [...commands, ...inverses]) for (const key of keysOf(command)) used.add(key);
1217
+ let key;
1218
+ do {
1219
+ nextKey += 1;
1220
+ key = `c${nextKey}`;
1221
+ } while (used.has(key));
1222
+ return key;
1223
+ }
1224
+ return {
1225
+ getSnapshot: store.getSnapshot,
1226
+ subscribe: store.subscribe,
1227
+ async open(file, callOptions = {}) {
1228
+ generation += 1;
1229
+ const started = generation;
1230
+ status = "opening";
1231
+ error = void 0;
1232
+ try {
1233
+ const source = await track(callOptions.signal, true, (signal) => load(file, signal, callOptions.onProgress, () => {}));
1234
+ const replaced = superseded(started);
1235
+ if (replaced) throw replaced;
1236
+ policy.check("maxSessionSize", source.bytes);
1237
+ sources.clear();
1238
+ history.clear();
1239
+ sources.set(source.info.id, source);
1240
+ plan = {
1241
+ sampleRate: source.info.sampleRate,
1242
+ channels: source.info.channels,
1243
+ clips: [{
1244
+ key: newKey(),
1245
+ source: source.info.id,
1246
+ start: 0,
1247
+ end: source.info.frames,
1248
+ gainDb: 0,
1249
+ fadeIn: NO_FADE,
1250
+ fadeOut: NO_FADE
1251
+ }],
1252
+ metadata: EMPTY_METADATA
1253
+ };
1254
+ selection = void 0;
1255
+ status = "ready";
1256
+ changed();
1257
+ emit({
1258
+ type: "recording_opened",
1259
+ ...facts(source)
1260
+ });
1261
+ } catch (reason) {
1262
+ const failure = asAudioError(reason, "The recording couldn't be opened.");
1263
+ if (started !== generation) throw failure;
1264
+ status = plan ? "ready" : "error";
1265
+ error = failure;
1266
+ changed();
1267
+ emit({
1268
+ type: "failed",
1269
+ operation: "open",
1270
+ code: failure.code
1271
+ });
1272
+ throw failure;
1273
+ }
1274
+ },
1275
+ async insert(file, insertOptions = {}) {
1276
+ if (!plan || status !== "ready") throw new AudioError("INVALID_COMMAND", "Open a recording before inserting another.", { details: { reason: "no-recording" } });
1277
+ const started = generation;
1278
+ error = void 0;
1279
+ try {
1280
+ const source = await track(insertOptions.signal, false, (signal) => {
1281
+ policy.check("maxFiles", sources.size + 1);
1282
+ return load(file, signal, insertOptions.onProgress, (probe) => {
1283
+ const rate = plan?.sampleRate;
1284
+ if (probe.sampleRate !== rate) throw new AudioError("UNSUPPORTED_FORMAT", `Recordings at ${probe.sampleRate} Hz can't be inserted into a ${rate} Hz session yet.`, { details: { sampleRate: probe.sampleRate } });
1285
+ });
1286
+ });
1287
+ const replaced = superseded(started);
1288
+ if (replaced) throw replaced;
1289
+ const current = plan;
1290
+ const drop = stepsToDrop(source.bytes);
1291
+ if (drop === void 0) throw policy.error("maxSessionSize", heldBytes() + source.bytes);
1292
+ const commands = [{
1293
+ type: "audio.insertClips",
1294
+ at: insertOptions.at ?? planLength(current),
1295
+ clips: [{
1296
+ key: newKey(),
1297
+ source: source.info.id,
1298
+ start: 0,
1299
+ end: source.info.frames,
1300
+ gainDb: 0,
1301
+ fadeIn: NO_FADE,
1302
+ fadeOut: NO_FADE
1303
+ }],
1304
+ splitKey: newKey()
1305
+ }];
1306
+ sources.set(source.info.id, source);
1307
+ let result;
1308
+ try {
1309
+ result = applyChecked(current, commands);
1310
+ } catch (reason) {
1311
+ sources.delete(source.info.id);
1312
+ throw reason;
1313
+ }
1314
+ history.drop(drop);
1315
+ commit(result, commands);
1316
+ changed();
1317
+ emit({
1318
+ type: "recording_inserted",
1319
+ ...facts(source)
1320
+ });
1321
+ } catch (reason) {
1322
+ const failure = asAudioError(reason, "The recording couldn't be inserted.");
1323
+ if (started !== generation) throw failure;
1324
+ error = failure;
1325
+ changed();
1326
+ emit({
1327
+ type: "failed",
1328
+ operation: "insert",
1329
+ code: failure.code
1330
+ });
1331
+ throw failure;
1332
+ }
1333
+ },
1334
+ execute(commands) {
1335
+ const list = Array.isArray(commands) ? [...commands] : [commands];
1336
+ if (list.length === 0) return;
1337
+ try {
1338
+ if (!plan) throw new AudioError("INVALID_COMMAND", "Open a recording before editing it.", { details: { reason: "no-recording" } });
1339
+ let copies;
1340
+ try {
1341
+ copies = structuredClone(list);
1342
+ } catch (reason) {
1343
+ throw new AudioError("INVALID_COMMAND", "Commands must be plain data.", {
1344
+ cause: reason,
1345
+ details: { reason: "not-plain-data" }
1346
+ });
1347
+ }
1348
+ commit(applyChecked(plan, copies), copies);
1349
+ } catch (reason) {
1350
+ const failure = asAudioError(reason);
1351
+ emit({
1352
+ type: "failed",
1353
+ operation: "command",
1354
+ code: failure.code
1355
+ });
1356
+ throw failure;
1357
+ }
1358
+ changed();
1359
+ emit({
1360
+ type: "command",
1361
+ commands: list.map((command) => command.type)
1362
+ });
1363
+ },
1364
+ group: (fn) => history.group(fn),
1365
+ createKey: newKey,
1366
+ undo() {
1367
+ const current = plan;
1368
+ const entry = current && history.undo();
1369
+ if (!current || !entry) return;
1370
+ try {
1371
+ plan = applyCommands(reducer, current, entry.inverses).state;
1372
+ } catch (reason) {
1373
+ history.restore("undo");
1374
+ throw reason;
1375
+ }
1376
+ changed();
1377
+ emit({ type: "undo" });
1378
+ },
1379
+ redo() {
1380
+ const current = plan;
1381
+ const entry = current && history.redo();
1382
+ if (!current || !entry) return;
1383
+ try {
1384
+ plan = applyCommands(reducer, current, entry.commands).state;
1385
+ } catch (reason) {
1386
+ history.restore("redo");
1387
+ throw reason;
1388
+ }
1389
+ changed();
1390
+ emit({ type: "redo" });
1391
+ },
1392
+ select(range) {
1393
+ let next;
1394
+ if (range) {
1395
+ const { start, end } = range;
1396
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) throw new RangeError("A selection is a range of whole frames.");
1397
+ const length = plan ? planLength(plan) : 0;
1398
+ const from = Math.max(0, Math.min(start, end, length));
1399
+ const to = Math.min(length, Math.max(start, end, 0));
1400
+ next = from < to ? {
1401
+ start: from,
1402
+ end: to
1403
+ } : void 0;
1404
+ }
1405
+ if (next?.start === selection?.start && next?.end === selection?.end) return;
1406
+ selection = next;
1407
+ changed();
1408
+ },
1409
+ getPeaks: (id) => sources.get(id)?.peaks,
1410
+ async close() {
1411
+ generation += 1;
1412
+ cancelLoads("The recording was closed.");
1413
+ const hadRecording = plan !== void 0;
1414
+ sources.clear();
1415
+ history.clear();
1416
+ plan = void 0;
1417
+ selection = void 0;
1418
+ error = void 0;
1419
+ status = "empty";
1420
+ changed();
1421
+ if (hadRecording) emit({ type: "recording_closed" });
1422
+ }
1423
+ };
416
1424
  }
417
- // src/core/operations/commands.ts
418
- var MIN_GAIN_DB = -120;
419
- var MAX_GAIN_DB = 120;
420
- var MAX_METADATA_LENGTH = 1e3;
421
1425
  // src/messages/en.ts
422
1426
  var audioMessages = /* @__PURE__ */ defineMessages({
423
1427
  ...sdkCoreMessages,
@@ -425,7 +1429,8 @@ var audioMessages = /* @__PURE__ */ defineMessages({
425
1429
  "errors.UNSUPPORTED_FORMAT": "This audio format isn't supported. Try converting the file to WAV, then open it again.",
426
1430
  "errors.DECODE_FAILED": "This browser can't play this kind of audio. Try another browser, or convert the file to WAV.",
427
1431
  "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
428
- "errors.DURATION_TOO_LONG": "This recording is longer than the editor can open.",
1432
+ "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't an audio project.",
1433
+ "errors.DURATION_TOO_LONG": "This recording is {actual, duration} long, which is over the {maximum, duration} limit.",
429
1434
  "errors.TOO_MANY_CHANNELS": "This recording has {actual, number} channels, which is over the {maximum, number}-channel limit.",
430
1435
  "errors.SAMPLE_RATE_TOO_HIGH": "This recording's sample rate is {actual, number} Hz, which is over the {maximum, number} Hz limit.",
431
1436
  "errors.SESSION_TOO_LARGE": "The open recordings would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Remove a recording, or clear the undo history, and try again.",
@@ -433,15 +1438,16 @@ var audioMessages = /* @__PURE__ */ defineMessages({
433
1438
  one: "A recording can have {maximum} clip. Join or delete clips, and try again.",
434
1439
  other: "A recording can have up to {maximum} clips. Join or delete clips, and try again."
435
1440
  }),
436
- "warnings.maxDuration": "This recording is long, and may be slow to open and edit.",
1441
+ "warnings.maxDuration": "This recording is {actual, duration} long, and may be slow to open and edit.",
437
1442
  "warnings.maxChannels": "This recording has {actual, number} channels, and may be slow to edit.",
438
1443
  "warnings.maxSampleRate": "This recording's sample rate is {actual, number} Hz, and it may be slow to edit.",
439
1444
  "warnings.maxSessionSize": "The open recordings use {actual, fileSize} of memory. Clearing the undo history frees memory.",
440
1445
  "warnings.maxClips": /* @__PURE__ */ plural("actual", {
441
1446
  one: "This recording has {actual} clip. Many clips may be slow to play and export.",
442
1447
  other: "This recording has {actual} clips. Many clips may be slow to play and export."
443
- })
1448
+ }),
1449
+ "warnings.truncated": "This recording looks incomplete, perhaps from an interrupted recording or download. It opened with the audio it holds."
444
1450
  });
445
- export { AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MIN_GAIN_DB, NO_FADE, audioLimitDefinitions, audioLimits, audioMessages, clipLength, clipOffsets, createAudioEngine, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, secondsToFrames };
1451
+ export { AUDIO_PLAN_FORMAT, AUDIO_PLAN_VERSION, AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MIN_GAIN_DB, NO_FADE, audioLimitDefinitions, audioLimits, audioMessages, clipLength, clipOffsets, createAudioEngine, createAudioSession, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, readAudioPlanDocument, secondsToFrames, toAudioPlanDocument };
446
1452
 
447
1453
  //# sourceMappingURL=index.js.map