@arraypress/waveform-player 1.24.5 → 1.25.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/src/js/core.js CHANGED
@@ -16,10 +16,23 @@ import {
16
16
  clamp,
17
17
  escapeHtml,
18
18
  formatCssLength,
19
+ toFiniteNumber,
20
+ toNumberArray,
19
21
  DEFAULT_SAMPLES
20
22
  } from './utils.js';
21
23
 
22
- import {DEFAULT_OPTIONS, STYLE_DEFAULTS, getColorPreset, COLOR_PRESETS, detectColorScheme} from './themes.js';
24
+ import {
25
+ DEFAULT_OPTIONS,
26
+ STYLE_DEFAULTS,
27
+ getColorPreset,
28
+ COLOR_PRESETS,
29
+ detectColorScheme,
30
+ normalizeOptions,
31
+ normalizeMarkers,
32
+ BUTTON_ALIGNMENTS,
33
+ PLAYBACK_RATE_MIN,
34
+ PLAYBACK_RATE_MAX
35
+ } from './themes.js';
23
36
 
24
37
  /**
25
38
  * Placeholder shown when an artwork URL fails to load (404 / broken) — a muted
@@ -40,12 +53,6 @@ const SEEK_PAGE_SECONDS = 10;
40
53
  // wrapper, moving it off the control the user just operated.
41
54
  const INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
42
55
 
43
- // Recognised `buttonAlign` values. `createDOM` interpolates the resolved value
44
- // into a class name, so an unrecognised value is coerced back to 'auto' rather
45
- // than reaching the template — that guards both configuration paths (constructor
46
- // options and `data-button-align`) at the single point of use.
47
- const BUTTON_ALIGNMENTS = ['auto', 'top', 'center', 'bottom'];
48
-
49
56
  /**
50
57
  * WaveformPlayer - Modern audio player with waveform visualization
51
58
  * @class
@@ -93,8 +100,12 @@ export class WaveformPlayer {
93
100
  if (userOptions.style && !userOptions.waveformStyle) userOptions.waveformStyle = userOptions.style;
94
101
  if (userOptions.src && !userOptions.url) userOptions.url = userOptions.src;
95
102
 
96
- // Merge options: defaults < data attributes < constructor options
97
- this.options = mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions);
103
+ // Merge options: defaults < data attributes < constructor options, then
104
+ // normalize the result. Both configuration paths are untyped, so this is
105
+ // the single point where an unusable value (non-array `playbackRates`,
106
+ // NaN geometry, an unrecognised enum) resolves to its default instead of
107
+ // reaching a consumer that assumes a shape it never checked.
108
+ this.options = normalizeOptions(mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions));
98
109
 
99
110
  // Apply color preset (auto-detect if not specified). Detection reads
100
111
  // the backdrop behind THIS container, so a player dropped into a themed
@@ -253,7 +264,10 @@ export class WaveformPlayer {
253
264
  this.container.innerHTML = '';
254
265
  this.container.className = 'waveform-player';
255
266
 
256
- // Determine button alignment
267
+ // Determine button alignment. normalizeOptions() has already rejected
268
+ // unrecognised values, but the resolved name is interpolated into a
269
+ // class name, so the allowlist is re-checked at the point of use —
270
+ // options stay publicly mutable after construction.
257
271
  let buttonAlign = BUTTON_ALIGNMENTS.includes(this.options.buttonAlign)
258
272
  ? this.options.buttonAlign
259
273
  : 'auto';
@@ -1298,13 +1312,15 @@ export class WaveformPlayer {
1298
1312
  this.progress = 0;
1299
1313
  this.waveformData = [];
1300
1314
 
1301
- // Update options (including preload if specified)
1302
- this.options = mergeOptions(this.options, {
1315
+ // Update options (including preload if specified). Normalized on the
1316
+ // same terms as the constructor — loadTrack takes a fresh, caller-
1317
+ // supplied option set, so it's the second untyped entry point.
1318
+ this.options = normalizeOptions(mergeOptions(this.options, {
1303
1319
  url,
1304
1320
  title: title === null ? this.options.title : title,
1305
1321
  artist: artist === null ? this.options.artist : artist,
1306
1322
  ...options
1307
- });
1323
+ }));
1308
1324
  if (hasArtworkOption) {
1309
1325
  this.options.artwork = options.artwork || null;
1310
1326
  }
@@ -1314,14 +1330,16 @@ export class WaveformPlayer {
1314
1330
  this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : '';
1315
1331
  }
1316
1332
 
1317
- // Apply preload setting if it was changed
1333
+ // Apply preload setting if it was changed. The caller's value decides
1334
+ // WHETHER to apply; the normalized one decides WHAT to apply, so an
1335
+ // unsupported value can't reach the media element.
1318
1336
  if (options.preload && this.audio) {
1319
- this.audio.preload = options.preload;
1337
+ this.audio.preload = this.options.preload;
1320
1338
  }
1321
1339
 
1322
1340
  // Apply crossOrigin if it was changed for this track
1323
1341
  if (options.crossOrigin && this.audio) {
1324
- this.audio.crossOrigin = options.crossOrigin;
1342
+ this.audio.crossOrigin = this.options.crossOrigin;
1325
1343
  }
1326
1344
 
1327
1345
  // Update artist only when explicitly provided. A null artist keeps the
@@ -1340,7 +1358,7 @@ export class WaveformPlayer {
1340
1358
  }
1341
1359
 
1342
1360
  // Clear or update markers
1343
- this.options.markers = options.markers || [];
1361
+ this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
1344
1362
 
1345
1363
  // Reset the waveform to the NEW track's peaks, or null to regenerate
1346
1364
  // from the URL. mergeOptions() above keeps the previous track's
@@ -1383,8 +1401,10 @@ export class WaveformPlayer {
1383
1401
  .then(r => r.json())
1384
1402
  .then(json => {
1385
1403
  this.waveformData = Array.isArray(json) ? json : (json.peaks || []);
1404
+ // A peaks sidecar is a third source of markers, and a remote
1405
+ // one — normalize it on the same terms as the option paths.
1386
1406
  if (json.markers && !this.options.markers?.length) {
1387
- this.options.markers = json.markers;
1407
+ this.options.markers = normalizeMarkers(json.markers);
1388
1408
  this.renderMarkers();
1389
1409
  }
1390
1410
  this.drawWaveform();
@@ -1393,16 +1413,11 @@ export class WaveformPlayer {
1393
1413
  return;
1394
1414
  }
1395
1415
 
1396
- if (typeof data === 'string') {
1397
- try {
1398
- const parsed = JSON.parse(data);
1399
- this.waveformData = Array.isArray(parsed) ? parsed : [];
1400
- } catch {
1401
- this.waveformData = data.split(',').map(Number);
1402
- }
1403
- } else {
1404
- this.waveformData = Array.isArray(data) ? data : [];
1405
- }
1416
+ // Peaks may arrive as an array, a JSON array string, or a bare
1417
+ // comma-separated list — all three collapse into one coercion, which
1418
+ // also drops non-numeric members (the old comma path mapped them to
1419
+ // NaN, and a NaN peak draws as a gap rather than an error).
1420
+ this.waveformData = toNumberArray(data, {fallback: []});
1406
1421
  this.drawWaveform();
1407
1422
  }
1408
1423
 
@@ -2320,15 +2335,21 @@ export class WaveformPlayer {
2320
2335
  }
2321
2336
 
2322
2337
  /**
2323
- * Set the owned `<audio>` element's playback rate (clamped to 0.5–2),
2338
+ * Set the owned `<audio>` element's playback rate (clamped to 0.25–4),
2324
2339
  * persist it onto `this.options.playbackRate`, and refresh the speed UI.
2325
2340
  * Self mode only — a no-op in external mode.
2326
- * @param {number} rate - Desired playback rate; clamped to the 0.5–2 range.
2341
+ *
2342
+ * The clamp bounds the range browsers keep audible; the default speed menu
2343
+ * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2344
+ * bounds. A non-numeric rate is ignored rather than assigned, since
2345
+ * `audio.playbackRate = NaN` throws.
2346
+ * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2327
2347
  */
2328
2348
  setPlaybackRate(rate) {
2329
2349
  if (!this.audio) return;
2330
2350
 
2331
- const clampedRate = clamp(rate, 0.5, 2);
2351
+ const clampedRate = toFiniteNumber(rate, null, {min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX});
2352
+ if (clampedRate === null) return;
2332
2353
  this.audio.playbackRate = clampedRate;
2333
2354
  this.options.playbackRate = clampedRate;
2334
2355
 
package/src/js/themes.js CHANGED
@@ -3,7 +3,16 @@
3
3
  * @description Color presets and default options for WaveformPlayer
4
4
  */
5
5
 
6
- import {parseColor, perceivedBrightness, DEFAULT_SAMPLES} from './utils.js';
6
+ import {
7
+ parseColor,
8
+ perceivedBrightness,
9
+ toArray,
10
+ toBool,
11
+ toEnum,
12
+ toFiniteNumber,
13
+ toNumberArray,
14
+ DEFAULT_SAMPLES
15
+ } from './utils.js';
7
16
 
8
17
  /**
9
18
  * Brightness (0–255) above which a backdrop counts as light.
@@ -400,4 +409,223 @@ export const STYLE_DEFAULTS = {
400
409
  blocks: {barWidth: 4, barSpacing: 2},
401
410
  dots: {barWidth: 3, barSpacing: 3},
402
411
  seekbar: {barWidth: 1, barSpacing: 0}
403
- };
412
+ };
413
+
414
+ /**
415
+ * Permitted `buttonAlign` values. `auto` resolves per waveform style at DOM
416
+ * build time (bottom for `bars`, center otherwise).
417
+ * @type {string[]}
418
+ */
419
+ export const BUTTON_ALIGNMENTS = ['auto', 'top', 'center', 'bottom'];
420
+
421
+ /**
422
+ * Playback-rate bounds. Single source of truth for both the `setPlaybackRate()`
423
+ * clamp and the `playbackRates` menu — an offered rate the setter would refuse
424
+ * leaves the speed label reading one thing while the audio plays another.
425
+ *
426
+ * The window is deliberately wider than the default menu (0.5–2). Audiobook and
427
+ * podcast UIs routinely want 2.5x or 3x, and there's no reason the *setter* should
428
+ * cap what the menu merely doesn't offer by default. 0.25–4 is the conservative
429
+ * limit: browsers keep audio audible and pitch-corrected across that range and
430
+ * start muting it beyond, so a rate outside these bounds would play silently.
431
+ * @type {number}
432
+ */
433
+ export const PLAYBACK_RATE_MIN = 0.25;
434
+ export const PLAYBACK_RATE_MAX = 4;
435
+
436
+ /**
437
+ * Closed vocabularies for the enumerated options, keyed by option name. Each
438
+ * unrecognised value resolves to that option's {@link DEFAULT_OPTIONS} entry.
439
+ * @type {Object<string, string[]>}
440
+ * @private
441
+ */
442
+ const ENUMS = {
443
+ buttonAlign: BUTTON_ALIGNMENTS,
444
+ layout: ['default', 'preview'],
445
+ buttonStyle: ['circle', 'minimal'],
446
+ artworkPosition: ['info', 'button'],
447
+ waveformStyle: Object.keys(STYLE_DEFAULTS),
448
+ waveformGradient: ['vertical', 'horizontal', 'diagonal'],
449
+ audioMode: ['self', 'external'],
450
+ preload: ['none', 'metadata', 'auto'],
451
+ colorPreset: Object.keys(COLOR_PRESETS),
452
+ // Anything other than these two makes the browser fall back to 'anonymous',
453
+ // which forces a CORS request the caller never asked for — so a bad value
454
+ // has to resolve to null (no crossorigin attribute), not pass through.
455
+ crossOrigin: ['anonymous', 'use-credentials']
456
+ };
457
+
458
+ /**
459
+ * Numeric options and their acceptable ranges. Out-of-range values are clamped;
460
+ * non-numeric ones fall back to the default.
461
+ * @type {Object<string, {min?: number, max?: number, integer?: boolean}>}
462
+ * @private
463
+ */
464
+ const NUMBERS = {
465
+ height: {min: 1, integer: true},
466
+ samples: {min: 1, integer: true},
467
+ barWidth: {min: 0},
468
+ barSpacing: {min: 0},
469
+ barRadius: {min: 0},
470
+ bpm: {min: 1},
471
+ // Matches the clamp in setPlaybackRate() — the menu must not offer a rate
472
+ // the setter would then silently refuse.
473
+ playbackRate: {min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX}
474
+ };
475
+
476
+ /**
477
+ * Boolean feature flags. Coerced with {@link toBool} so the string `'false'`
478
+ * (a `data-*` value, or a wrapper that stringified a prop) doesn't read as true.
479
+ * @type {string[]}
480
+ * @private
481
+ */
482
+ const BOOLEANS = [
483
+ 'autoplay', 'showControls', 'showInfo', 'showTime', 'showHoverTime',
484
+ 'seekHandle', 'showBPM', 'singlePlay', 'playOnSeek', 'enableMediaSession',
485
+ 'showMarkers', 'accessibleSeek', 'showPlaybackSpeed'
486
+ ];
487
+
488
+ /**
489
+ * Callback options. A non-function here would throw at call time, deep inside
490
+ * playback, rather than at the point the bad value was supplied.
491
+ * @type {string[]}
492
+ * @private
493
+ */
494
+ const CALLBACKS = [
495
+ 'onLoad', 'onPlay', 'onPause', 'onEnd', 'onError', 'onTimeUpdate',
496
+ 'onNextTrack', 'onPreviousTrack'
497
+ ];
498
+
499
+ /**
500
+ * Warn about an option that was supplied but unusable. Invalid options resolve
501
+ * to their default rather than throwing, so without this they'd fail silently —
502
+ * a `NaN` height renders an invisible player with an empty console.
503
+ * @param {string} key - Option name.
504
+ * @param {*} value - The rejected value.
505
+ * @private
506
+ */
507
+ function warnInvalid(key, value) {
508
+ console.warn(`[WaveformPlayer] Invalid ${key} option, using default:`, value);
509
+ }
510
+
511
+ /**
512
+ * Normalize a marker list into renderable markers.
513
+ *
514
+ * Accepts an array or a JSON array string, and keeps only entries that are
515
+ * objects with a finite, non-negative `time` — `renderMarkers()` divides by
516
+ * duration and writes the result into `style.left`, so a non-numeric time
517
+ * produces `left: NaN%` and silently stacks every bad marker at the left edge.
518
+ * A missing `label` becomes `''` rather than reaching the tooltip and the
519
+ * marker's `aria-label` as the string `"undefined"`.
520
+ *
521
+ * @param {*} value - Candidate marker list.
522
+ * @returns {Array<Object>} Renderable markers (empty when nothing survives).
523
+ */
524
+ export function normalizeMarkers(value) {
525
+ const list = toArray(value);
526
+ if (!list) {
527
+ if (value != null) warnInvalid('markers', value);
528
+ return [];
529
+ }
530
+
531
+ return list.reduce((markers, marker) => {
532
+ const time = marker && typeof marker === 'object'
533
+ ? toFiniteNumber(marker.time, null, {min: 0})
534
+ : null;
535
+
536
+ if (time === null) {
537
+ warnInvalid('marker', marker);
538
+ return markers;
539
+ }
540
+
541
+ markers.push({...marker, time, label: marker.label == null ? '' : marker.label});
542
+ return markers;
543
+ }, []);
544
+ }
545
+
546
+ /**
547
+ * Normalize a merged option set in place, resolving every unusable value to its
548
+ * {@link DEFAULT_OPTIONS} entry.
549
+ *
550
+ * Options arrive from three untyped directions — `data-*` attributes, framework
551
+ * wrappers forwarding props, and hand-written JS — and the consumers downstream
552
+ * assume shapes that none of those paths guarantee. `playbackRates.map()` and
553
+ * `markers.forEach()` throw outright on valid-but-non-array JSON (`JSON.parse`
554
+ * validates syntax, not shape); `NaN` geometry sizes the canvas to nothing; and
555
+ * unrecognised enum values reach class names and DOM properties. Normalizing
556
+ * once, on the merged object, covers both configuration paths and every wrapper
557
+ * at a single point.
558
+ *
559
+ * Mutates and returns the same object, so it can be dropped in directly after
560
+ * {@link mergeOptions}. Options left unset (`null`) are untouched — `null` is
561
+ * the documented "inherit / auto-detect" state for colours, `bpm`, `buttonSize`
562
+ * and the callbacks.
563
+ *
564
+ * @param {Object} options - Merged options object (mutated).
565
+ * @returns {Object} The same object, normalized.
566
+ */
567
+ export function normalizeOptions(options) {
568
+ // Only normalize what the caller actually supplied — mergeOptions() drops
569
+ // null/undefined sources, so a null here is a default that means "unset".
570
+ const supplied = (key) => options[key] != null;
571
+
572
+ // Fall back to the documented default, warning only when a real value was
573
+ // rejected (an unset option is not a mistake).
574
+ const reject = (key) => {
575
+ warnInvalid(key, options[key]);
576
+ options[key] = DEFAULT_OPTIONS[key];
577
+ };
578
+
579
+ for (const [key, range] of Object.entries(NUMBERS)) {
580
+ if (!supplied(key)) continue;
581
+ const n = toFiniteNumber(options[key], null, range);
582
+ if (n === null) reject(key); else options[key] = n;
583
+ }
584
+
585
+ for (const [key, allowed] of Object.entries(ENUMS)) {
586
+ if (supplied(key) && toEnum(options[key], allowed) === null) reject(key);
587
+ }
588
+
589
+ for (const key of BOOLEANS) {
590
+ options[key] = toBool(options[key]);
591
+ }
592
+
593
+ for (const key of CALLBACKS) {
594
+ if (supplied(key) && typeof options[key] !== 'function') reject(key);
595
+ }
596
+
597
+ // Speed menu: every offered rate must be one setPlaybackRate() will honour,
598
+ // or the menu label and the audio disagree. Members are interpolated into
599
+ // markup, so non-numeric entries must not survive.
600
+ if (supplied('playbackRates')) {
601
+ const rates = toNumberArray(options.playbackRates, {
602
+ min: PLAYBACK_RATE_MIN,
603
+ max: PLAYBACK_RATE_MAX,
604
+ fallback: null
605
+ });
606
+ if (rates === null) reject('playbackRates'); else options.playbackRates = rates;
607
+ }
608
+
609
+ options.markers = normalizeMarkers(options.markers);
610
+
611
+ // A CSS length is a number (px) or a verbatim unit string ('4rem'); both
612
+ // reach an inline style attribute, escaped, via formatCssLength().
613
+ for (const key of ['buttonSize', 'buttonRadius']) {
614
+ if (!supplied(key)) continue;
615
+ const value = options[key];
616
+ const ok = typeof value === 'number'
617
+ ? Number.isFinite(value)
618
+ : typeof value === 'string' && value.trim() !== '';
619
+ if (!ok) reject(key);
620
+ }
621
+
622
+ // A colour is a CSS colour string or an array of gradient stops; anything
623
+ // else resolves to null so the theme preset fills it in instead.
624
+ for (const key of ['waveformColor', 'progressColor']) {
625
+ if (!supplied(key)) continue;
626
+ const value = options[key];
627
+ if (!(typeof value === 'string' && value.trim() !== '') && !Array.isArray(value)) reject(key);
628
+ }
629
+
630
+ return options;
631
+ }
package/src/js/utils.js CHANGED
@@ -87,6 +87,131 @@ export function clamp(value, min = 0, max = 1) {
87
87
  return Math.max(min, Math.min(value, max));
88
88
  }
89
89
 
90
+ /**
91
+ * Coerce a value to a finite number, clamped into an optional range.
92
+ *
93
+ * Options reach the player from three untyped directions — `data-*` attributes,
94
+ * framework wrappers that forward strings, and hand-written JS — so a value that
95
+ * *should* be a number routinely isn't. Anything non-numeric (`NaN`,
96
+ * `Infinity`, `null`, `''`, objects, arrays) returns `fallback` rather than
97
+ * poisoning arithmetic downstream: a `NaN` height silently sizes the canvas to
98
+ * zero, which looks like a broken player rather than a bad option.
99
+ *
100
+ * Numeric strings are accepted (`'64'` → `64`) but non-numeric ones are not
101
+ * (`'64px'` → `fallback`); the `data-*` layer has already run `parseInt`/
102
+ * `parseFloat` by the time values arrive here.
103
+ *
104
+ * @param {*} value - Candidate value.
105
+ * @param {*} [fallback=null] - Returned when `value` isn't a finite number.
106
+ * @param {Object} [opts={}] - Bounds.
107
+ * @param {number} [opts.min=-Infinity] - Lower bound (clamped, not rejected).
108
+ * @param {number} [opts.max=Infinity] - Upper bound (clamped, not rejected).
109
+ * @param {boolean} [opts.integer=false] - Round the result to a whole number.
110
+ * @returns {number|*} The finite, clamped number, or `fallback`.
111
+ */
112
+ export function toFiniteNumber(value, fallback = null, opts = {}) {
113
+ const {min = -Infinity, max = Infinity, integer = false} = opts;
114
+ const n = typeof value === 'number'
115
+ ? value
116
+ : (typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN);
117
+
118
+ if (!Number.isFinite(n)) return fallback;
119
+
120
+ const bounded = clamp(n, min, max);
121
+ return integer ? Math.round(bounded) : bounded;
122
+ }
123
+
124
+ /**
125
+ * Coerce a value to an array, accepting either a real array or a JSON string
126
+ * that parses to one (`'[1,2]'`). Anything else — including valid JSON that
127
+ * isn't an array, like `'2'` or `'{"a":1}'` — returns `fallback`.
128
+ *
129
+ * This is the guard `JSON.parse` alone doesn't give you: parsing only validates
130
+ * *syntax*, so well-formed non-array JSON sails through and detonates at the
131
+ * first `.map()`/`.forEach()` call site.
132
+ *
133
+ * @param {*} value - Candidate value.
134
+ * @param {*} [fallback=null] - Returned when `value` isn't (or doesn't parse to) an array.
135
+ * @returns {Array|*} The array, or `fallback`.
136
+ */
137
+ export function toArray(value, fallback = null) {
138
+ if (Array.isArray(value)) return value;
139
+
140
+ if (typeof value === 'string' && value.trim().startsWith('[')) {
141
+ try {
142
+ const parsed = JSON.parse(value);
143
+ if (Array.isArray(parsed)) return parsed;
144
+ } catch (e) { /* fall through to the fallback */ }
145
+ }
146
+
147
+ return fallback;
148
+ }
149
+
150
+ /**
151
+ * Coerce a value to an array of finite numbers.
152
+ *
153
+ * Accepts a real array, a JSON array string (`'[0.5,1,2]'`), or a plain
154
+ * delimited list (`'0.5, 1, 2'`) — the last of which is what an author naturally
155
+ * types into a `data-*` attribute. Members that aren't finite numbers, or that
156
+ * fall outside `[min, max]`, are **dropped** rather than clamped, so a
157
+ * mistyped entry can't quietly masquerade as a supported one. An empty result
158
+ * returns `fallback`.
159
+ *
160
+ * @param {*} value - Candidate value.
161
+ * @param {Object} [opts={}] - Bounds and fallback.
162
+ * @param {number} [opts.min=-Infinity] - Lowest acceptable member.
163
+ * @param {number} [opts.max=Infinity] - Highest acceptable member.
164
+ * @param {*} [opts.fallback=null] - Returned when nothing usable survives.
165
+ * @returns {number[]|*} Numbers within range, or `fallback`.
166
+ */
167
+ export function toNumberArray(value, opts = {}) {
168
+ const {min = -Infinity, max = Infinity, fallback = null} = opts;
169
+
170
+ let list = toArray(value);
171
+ if (!list && typeof value === 'string' && value.trim() !== '') {
172
+ list = value.split(/[,\s]+/);
173
+ }
174
+ if (!list) return fallback;
175
+
176
+ const numbers = list
177
+ .map(v => toFiniteNumber(v))
178
+ .filter(n => n !== null && n >= min && n <= max);
179
+
180
+ return numbers.length ? numbers : fallback;
181
+ }
182
+
183
+ /**
184
+ * Return `value` when it is one of `allowed`, else `fallback`. Used for the
185
+ * option surface's closed vocabularies (`layout`, `preload`, `audioMode`, …) so
186
+ * an unrecognised value resolves to the documented default instead of reaching
187
+ * a class name, a DOM property, or a lookup that silently misses.
188
+ *
189
+ * @param {*} value - Candidate value.
190
+ * @param {Array} allowed - Permitted values.
191
+ * @param {*} [fallback=null] - Returned when `value` isn't permitted.
192
+ * @returns {*} `value` if allowed, else `fallback`.
193
+ */
194
+ export function toEnum(value, allowed, fallback = null) {
195
+ return allowed.includes(value) ? value : fallback;
196
+ }
197
+
198
+ /**
199
+ * Coerce a value to a boolean, treating the strings `'false'` and `'0'` as
200
+ * false. Plain `Boolean()` would make both truthy, and both arrive routinely
201
+ * from attribute-shaped sources (a `data-*` value, or a framework wrapper that
202
+ * stringifies props before forwarding them).
203
+ *
204
+ * @param {*} value - Candidate value.
205
+ * @returns {boolean} The coerced boolean.
206
+ */
207
+ export function toBool(value) {
208
+ if (typeof value === 'string') {
209
+ const v = value.trim().toLowerCase();
210
+ return v !== '' && v !== 'false' && v !== '0';
211
+ }
212
+ return !!value;
213
+ }
214
+
90
215
  /**
91
216
  * Read a boolean `data-*` flag. Returns `undefined` when the attribute is
92
217
  * absent (preserving the sparse-options contract) and otherwise compares the
@@ -119,9 +244,13 @@ function parseColorValue(value) {
119
244
  * Only attributes that are actually present are copied, so the returned object
120
245
  * is sparse and never overrides defaults with `undefined`. Numeric attributes
121
246
  * are coerced with `parseInt`/`parseFloat`, boolean flags are compared against
122
- * the literal string `'true'`, and JSON-valued attributes (`markers`,
123
- * `playbackRates`) are parsed defensively — a parse failure is warned about and
124
- * the attribute is skipped rather than thrown.
247
+ * the literal string `'true'`, and list-valued attributes (`markers`,
248
+ * `playbackRates`) are parsed defensively — anything that isn't a list is
249
+ * warned about and skipped rather than thrown or passed on.
250
+ *
251
+ * This layer only reads and shapes; it does not police values. Ranges and
252
+ * vocabularies are enforced by `normalizeOptions` on the merged result, so the
253
+ * constructor path gets the same guarantees as the `data-*` path.
125
254
  *
126
255
  * Several attributes are shorthand aliases of a canonical long form: `data-src`
127
256
  * → `url`, `data-style` → `waveformStyle`. When both are present the canonical
@@ -158,12 +287,16 @@ export function parseDataAttributes(element) {
158
287
  options[optKey] = /^\d+(\.\d+)?$/.test(raw.trim()) ? parseFloat(raw) : raw;
159
288
  };
160
289
 
161
- // Parse a JSON-valued attribute defensively — warn and skip on bad JSON.
162
- const setJson = (optKey, dataKey = optKey) => {
290
+ // Parse a JSON-array attribute defensively — warn and skip anything that
291
+ // isn't an array. Checking the SHAPE (not just that JSON.parse succeeded)
292
+ // is what stops well-formed non-array JSON like `2` or `{"a":1}` reaching a
293
+ // consumer that will call .map()/.forEach() on it.
294
+ const setJsonArray = (optKey, dataKey = optKey) => {
163
295
  const raw = element.dataset[dataKey];
164
296
  if (!raw) return;
165
- try { options[optKey] = JSON.parse(raw); }
166
- catch (e) { console.warn(`[WaveformPlayer] Invalid ${dataKey} JSON:`, e); }
297
+ const parsed = toArray(raw);
298
+ if (parsed) options[optKey] = parsed;
299
+ else console.warn(`[WaveformPlayer] Invalid ${dataKey} attribute, expected a JSON array:`, raw);
167
300
  };
168
301
 
169
302
  // Core attributes. `data-src` is a shorthand alias for `data-url`;
@@ -228,12 +361,19 @@ export function parseDataAttributes(element) {
228
361
  if (element.dataset.waveform) options.waveform = element.dataset.waveform;
229
362
 
230
363
  // Markers
231
- setJson('markers');
364
+ setJsonArray('markers');
232
365
 
233
366
  // Playback controls
234
367
  setNum('playbackRate', 'playbackRate', true);
235
368
  setBool('showPlaybackSpeed');
236
- setJson('playbackRates');
369
+ // Rates accept a JSON array (`[0.5,1,2]`) or the bare list an author is
370
+ // more likely to type (`0.5, 1, 2`). Range is enforced later, against the
371
+ // same bounds setPlaybackRate() clamps to.
372
+ if (element.dataset.playbackRates) {
373
+ const rates = toNumberArray(element.dataset.playbackRates);
374
+ if (rates) options.playbackRates = rates;
375
+ else console.warn('[WaveformPlayer] Invalid playbackRates attribute:', element.dataset.playbackRates);
376
+ }
237
377
 
238
378
  // Media Session API
239
379
  setBool('enableMediaSession');