@libraz/libcantus 1.0.1 → 1.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.
Files changed (142) hide show
  1. package/README.md +27 -65
  2. package/README_ja.md +28 -66
  3. package/dist/analyze/index.cjs +11 -7
  4. package/dist/analyze/index.cjs.map +1 -1
  5. package/dist/analyze/index.d.cts +79 -144
  6. package/dist/analyze/index.d.ts +79 -144
  7. package/dist/analyze/index.js +20 -16
  8. package/dist/chunk-35NBV2FT.cjs +145 -0
  9. package/dist/chunk-35NBV2FT.cjs.map +1 -0
  10. package/dist/{chunk-UADYAYAT.cjs → chunk-3R3QVKY5.cjs} +1353 -580
  11. package/dist/chunk-3R3QVKY5.cjs.map +1 -0
  12. package/dist/{chunk-WWURE4XT.cjs → chunk-76ZBTRG2.cjs} +624 -729
  13. package/dist/chunk-76ZBTRG2.cjs.map +1 -0
  14. package/dist/{chunk-FVSI36UV.js → chunk-7KG3RTYS.js} +197 -110
  15. package/dist/chunk-7KG3RTYS.js.map +1 -0
  16. package/dist/{chunk-VTI6FOLB.js → chunk-AGOVW7U6.js} +709 -133
  17. package/dist/chunk-AGOVW7U6.js.map +1 -0
  18. package/dist/{chunk-E3F4AHAH.cjs → chunk-CGBADIO5.cjs} +221 -134
  19. package/dist/chunk-CGBADIO5.cjs.map +1 -0
  20. package/dist/{chunk-6XH6QZYQ.cjs → chunk-DSMJRXCZ.cjs} +1455 -849
  21. package/dist/chunk-DSMJRXCZ.cjs.map +1 -0
  22. package/dist/{chunk-PKFNUHDY.js → chunk-FBH75DAY.js} +1218 -612
  23. package/dist/chunk-FBH75DAY.js.map +1 -0
  24. package/dist/chunk-H2KJHBW4.js +3329 -0
  25. package/dist/chunk-H2KJHBW4.js.map +1 -0
  26. package/dist/chunk-HPVSH7SF.cjs +2294 -0
  27. package/dist/chunk-HPVSH7SF.cjs.map +1 -0
  28. package/dist/{chunk-MXO72PLY.cjs → chunk-HWHGOVO6.cjs} +21 -19
  29. package/dist/chunk-HWHGOVO6.cjs.map +1 -0
  30. package/dist/chunk-HYJJ2V2I.js +2294 -0
  31. package/dist/chunk-HYJJ2V2I.js.map +1 -0
  32. package/dist/{chunk-AFM2ULJH.cjs → chunk-J7FHVZII.cjs} +1567 -1067
  33. package/dist/chunk-J7FHVZII.cjs.map +1 -0
  34. package/dist/chunk-K6OZXIR6.js +1 -0
  35. package/dist/{chunk-H3VORETI.js → chunk-M5RYMAFI.js} +487 -592
  36. package/dist/chunk-M5RYMAFI.js.map +1 -0
  37. package/dist/chunk-NB25P3EH.js +363 -0
  38. package/dist/chunk-NB25P3EH.js.map +1 -0
  39. package/dist/{chunk-TTCLJX6D.js → chunk-NFJ4P6ZZ.js} +10 -8
  40. package/dist/chunk-NFJ4P6ZZ.js.map +1 -0
  41. package/dist/chunk-NM7UAMC3.cjs +457 -0
  42. package/dist/chunk-NM7UAMC3.cjs.map +1 -0
  43. package/dist/chunk-PM4XJE2Y.cjs +363 -0
  44. package/dist/chunk-PM4XJE2Y.cjs.map +1 -0
  45. package/dist/chunk-PUKJP2Z5.js +145 -0
  46. package/dist/chunk-PUKJP2Z5.js.map +1 -0
  47. package/dist/{chunk-VOHZB45S.js → chunk-Q6LFSAKV.js} +1321 -821
  48. package/dist/chunk-Q6LFSAKV.js.map +1 -0
  49. package/dist/{chunk-INHVXP6Z.js → chunk-RFIBF2RR.js} +1203 -430
  50. package/dist/chunk-RFIBF2RR.js.map +1 -0
  51. package/dist/{chunk-Q2WGKJNN.cjs → chunk-S5BKZZGM.cjs} +699 -123
  52. package/dist/chunk-S5BKZZGM.cjs.map +1 -0
  53. package/dist/chunk-SGLEQVJH.cjs +3329 -0
  54. package/dist/chunk-SGLEQVJH.cjs.map +1 -0
  55. package/dist/chunk-UGLFDG7L.cjs +1 -0
  56. package/dist/chunk-UGLFDG7L.cjs.map +1 -0
  57. package/dist/{chunk-YH3BIKHH.js → chunk-UMWZ4ZET.js} +146 -49
  58. package/dist/chunk-UMWZ4ZET.js.map +1 -0
  59. package/dist/{index-szBv3496.d.ts → coerce-DP0vYu-x.d.ts} +286 -199
  60. package/dist/{index-C_8o--VE.d.cts → coerce-DRERzdve.d.cts} +286 -199
  61. package/dist/core/index.cjs +9 -5
  62. package/dist/core/index.cjs.map +1 -1
  63. package/dist/core/index.d.cts +122 -108
  64. package/dist/core/index.d.ts +122 -108
  65. package/dist/core/index.js +32 -28
  66. package/dist/generate/index.cjs +8 -8
  67. package/dist/generate/index.d.cts +168 -84
  68. package/dist/generate/index.d.ts +168 -84
  69. package/dist/generate/index.js +7 -7
  70. package/dist/{index-CGpRv5sl.d.cts → index-9eoQs2C1.d.ts} +34 -19
  71. package/dist/{index-CCNJRG-P.d.cts → index-B9QLziDe.d.cts} +293 -56
  72. package/dist/{index-Dzr13q3d.d.cts → index-BBWNZS0f.d.cts} +135 -58
  73. package/dist/{index-9wcMhG73.d.ts → index-BHIUyjhZ.d.ts} +293 -56
  74. package/dist/{index-BGFW-8P2.d.cts → index-BJgP97N1.d.ts} +196 -114
  75. package/dist/{index-CunYKLiu.d.ts → index-BL5N2Oyz.d.cts} +1 -1
  76. package/dist/{index-Cj49F892.d.ts → index-BMweUlm5.d.cts} +63 -23
  77. package/dist/{index-CgHqxdps.d.ts → index-BNSM-DSk.d.cts} +196 -114
  78. package/dist/{index-D57QRbVn.d.ts → index-BRMbPkHE.d.ts} +480 -254
  79. package/dist/{index-Chbst3Jx.d.ts → index-CJBBiAmU.d.ts} +135 -58
  80. package/dist/{index-BkGmlyI3.d.cts → index-CL4b4gUQ.d.ts} +63 -23
  81. package/dist/{index-B9MNZboQ.d.ts → index-Cy15oTvh.d.cts} +52 -22
  82. package/dist/{index-B9MNZboQ.d.cts → index-Cy15oTvh.d.ts} +52 -22
  83. package/dist/{index-BO6xE9YU.d.cts → index-DGCNKAUr.d.cts} +480 -254
  84. package/dist/{index-B4o55NDr.d.cts → index-Dw2DP7vm.d.ts} +1 -1
  85. package/dist/{index-G1uwGGWQ.d.ts → index-cHvbYgJI.d.cts} +34 -19
  86. package/dist/index.cjs +42 -14
  87. package/dist/index.cjs.map +1 -1
  88. package/dist/index.d.cts +14 -14
  89. package/dist/index.d.ts +14 -14
  90. package/dist/index.js +82 -54
  91. package/dist/{masks-DYbE485J.d.cts → masks-Cc7-MzzY.d.ts} +49 -2
  92. package/dist/{masks-DYbE485J.d.ts → masks-pADfTOiD.d.cts} +49 -2
  93. package/dist/model/index.cjs +19 -12
  94. package/dist/model/index.cjs.map +1 -1
  95. package/dist/model/index.d.cts +504 -182
  96. package/dist/model/index.d.ts +504 -182
  97. package/dist/model/index.js +18 -11
  98. package/dist/{positional-Cptlj-xs.d.ts → positional-DJgs6ltD.d.ts} +85 -8
  99. package/dist/{positional-DvH_sd8u.d.cts → positional-DMZer-FM.d.cts} +85 -8
  100. package/dist/theory/index.cjs +35 -6
  101. package/dist/theory/index.cjs.map +1 -1
  102. package/dist/theory/index.d.cts +257 -62
  103. package/dist/theory/index.d.ts +257 -62
  104. package/dist/theory/index.js +41 -12
  105. package/package.json +7 -5
  106. package/dist/chunk-2LCPM3EG.js +0 -3224
  107. package/dist/chunk-2LCPM3EG.js.map +0 -1
  108. package/dist/chunk-6XH6QZYQ.cjs.map +0 -1
  109. package/dist/chunk-6XPTBE7Y.cjs +0 -49
  110. package/dist/chunk-6XPTBE7Y.cjs.map +0 -1
  111. package/dist/chunk-AFM2ULJH.cjs.map +0 -1
  112. package/dist/chunk-B6XNKWZV.cjs +0 -3224
  113. package/dist/chunk-B6XNKWZV.cjs.map +0 -1
  114. package/dist/chunk-E3F4AHAH.cjs.map +0 -1
  115. package/dist/chunk-ELCTZUJJ.js +0 -379
  116. package/dist/chunk-ELCTZUJJ.js.map +0 -1
  117. package/dist/chunk-FVSI36UV.js.map +0 -1
  118. package/dist/chunk-H3VORETI.js.map +0 -1
  119. package/dist/chunk-H42UHPYW.js +0 -1577
  120. package/dist/chunk-H42UHPYW.js.map +0 -1
  121. package/dist/chunk-HFPS7JFD.js +0 -1
  122. package/dist/chunk-INHVXP6Z.js.map +0 -1
  123. package/dist/chunk-K4ZJUGF4.cjs +0 -379
  124. package/dist/chunk-K4ZJUGF4.cjs.map +0 -1
  125. package/dist/chunk-KNJEKLKV.js +0 -49
  126. package/dist/chunk-KNJEKLKV.js.map +0 -1
  127. package/dist/chunk-MXO72PLY.cjs.map +0 -1
  128. package/dist/chunk-NLEU4QSE.cjs +0 -360
  129. package/dist/chunk-NLEU4QSE.cjs.map +0 -1
  130. package/dist/chunk-OE6WK2Y2.cjs +0 -1577
  131. package/dist/chunk-OE6WK2Y2.cjs.map +0 -1
  132. package/dist/chunk-PKFNUHDY.js.map +0 -1
  133. package/dist/chunk-Q2WGKJNN.cjs.map +0 -1
  134. package/dist/chunk-RHIJ3S4I.cjs +0 -1
  135. package/dist/chunk-RHIJ3S4I.cjs.map +0 -1
  136. package/dist/chunk-TTCLJX6D.js.map +0 -1
  137. package/dist/chunk-UADYAYAT.cjs.map +0 -1
  138. package/dist/chunk-VOHZB45S.js.map +0 -1
  139. package/dist/chunk-VTI6FOLB.js.map +0 -1
  140. package/dist/chunk-WWURE4XT.cjs.map +0 -1
  141. package/dist/chunk-YH3BIKHH.js.map +0 -1
  142. /package/dist/{chunk-HFPS7JFD.js.map → chunk-K6OZXIR6.js.map} +0 -0
@@ -0,0 +1,363 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ var _chunk3R3QVKY5cjs = require('./chunk-3R3QVKY5.cjs');
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ var _chunkS5BKZZGMcjs = require('./chunk-S5BKZZGM.cjs');
23
+
24
+ // src/theory/chordscale/index.ts
25
+ function requireChordScaleMask(name, label = "scale") {
26
+ const canonical = _chunk3R3QVKY5cjs.resolveScaleName.call(void 0, name);
27
+ if (canonical !== void 0 && !Object.hasOwn(_chunk3R3QVKY5cjs.NAMED_SCALES, canonical)) {
28
+ throw new (0, _chunkS5BKZZGMcjs.InvalidInputError)(
29
+ `${label} must name a scale chord-scale theory ranks; ${String(name)} is a world scale`
30
+ );
31
+ }
32
+ return _chunk3R3QVKY5cjs.requireScaleMask.call(void 0, name, label);
33
+ }
34
+ function popcount12(mask) {
35
+ let count = 0;
36
+ for (let n = 0; n < 12; n += 1) {
37
+ count += mask >> n & 1;
38
+ }
39
+ return count;
40
+ }
41
+ function maskHasPitchClass(mask, scaleRootPc, pc) {
42
+ const offset = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, pc - scaleRootPc);
43
+ return (mask >> offset & 1) === 1;
44
+ }
45
+ function scaleMatchesChord(chordPcs, scaleMask, scaleRootPc) {
46
+ _chunk3R3QVKY5cjs.assertModeMask.call(void 0, scaleMask, "scaleMask");
47
+ _chunkS5BKZZGMcjs.assertPitchClass.call(void 0, scaleRootPc, "scaleRootPc");
48
+ const pcs = _chunkS5BKZZGMcjs.assertArray.call(void 0, chordPcs, "chord pitch classes");
49
+ for (let index = 0; index < pcs.length; index += 1) {
50
+ const pc = _chunkS5BKZZGMcjs.assertPitchClass.call(void 0, _nullishCoalesce(pcs[index], () => ( Number.NaN)), `chord pitch classes[${index}]`);
51
+ if (!maskHasPitchClass(scaleMask, scaleRootPc, pc)) {
52
+ return false;
53
+ }
54
+ }
55
+ return true;
56
+ }
57
+ var ALIASED_SCALE_NAMES = /* @__PURE__ */ new Set(["major", "naturalMinor"]);
58
+ var HEPTATONIC_SIZE = 7;
59
+ var SCALE_PREFERENCE = [
60
+ "ionian",
61
+ "major",
62
+ "mixolydian",
63
+ "dorian",
64
+ "lydian",
65
+ "aeolian",
66
+ "naturalMinor",
67
+ "phrygian",
68
+ "locrian"
69
+ ];
70
+ var IDIOMATIC_SCALES = {
71
+ aug: ["wholeTone"],
72
+ m7b5: ["locrian"],
73
+ // The diminished scale played over a diminished seventh is the whole-half
74
+ // octatonic. Its half-whole rotation belongs to the dominant it colours: over
75
+ // a diminished seventh every one of its non-chord tones lands a semitone
76
+ // above a chord tone, so it offers no tension at all.
77
+ dim7: ["octatonicWholeHalf"],
78
+ minMaj7: ["melodicMinor"]
79
+ };
80
+ function conventionalRank(name) {
81
+ const index = SCALE_PREFERENCE.indexOf(name);
82
+ return index < 0 ? SCALE_PREFERENCE.length : index;
83
+ }
84
+ function idiomaticRank(chord, name) {
85
+ const choices = IDIOMATIC_SCALES[chord.quality];
86
+ if (choices === void 0) {
87
+ return 0;
88
+ }
89
+ const index = choices.indexOf(name);
90
+ return index < 0 ? choices.length + 1 : index;
91
+ }
92
+ function isAlteredDominant(chord, scaleName) {
93
+ return chord.quality === "dom7" && scaleName === "altered";
94
+ }
95
+ function chordScales(chord) {
96
+ const data = _chunk3R3QVKY5cjs.toChordData.call(void 0, chord);
97
+ const chordPcs = _chunk3R3QVKY5cjs.chordPitchClasses.call(void 0, data);
98
+ const rootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, data.rootPc);
99
+ const ranked = [];
100
+ const seenMasks = /* @__PURE__ */ new Set();
101
+ for (const name of Object.keys(_chunk3R3QVKY5cjs.NAMED_SCALES)) {
102
+ if (name === "chromatic" || ALIASED_SCALE_NAMES.has(name)) {
103
+ continue;
104
+ }
105
+ const mask = _chunk3R3QVKY5cjs.namedScaleMask.call(void 0, name);
106
+ if (mask === void 0 || seenMasks.has(mask)) {
107
+ continue;
108
+ }
109
+ seenMasks.add(mask);
110
+ if (scaleMatchesChord(chordPcs, mask, rootPc) || isAlteredDominant(data, name)) {
111
+ const size = popcount12(mask);
112
+ ranked.push({
113
+ name,
114
+ extra: size - chordPcs.length,
115
+ size,
116
+ avoid: avoidNotes(data, name).length
117
+ });
118
+ }
119
+ }
120
+ if (ranked.length === 0) {
121
+ if (_chunk3R3QVKY5cjs.NAMED_SCALES.chromatic !== void 0) {
122
+ return [{ name: "chromatic", rootPc }];
123
+ }
124
+ return [];
125
+ }
126
+ const preferHeptatonic = chordPcs.length <= 3;
127
+ ranked.sort((a, b) => {
128
+ const idiomaticA = idiomaticRank(data, a.name);
129
+ const idiomaticB = idiomaticRank(data, b.name);
130
+ if (idiomaticA !== idiomaticB) {
131
+ return idiomaticA - idiomaticB;
132
+ }
133
+ if (preferHeptatonic && a.size === HEPTATONIC_SIZE !== (b.size === HEPTATONIC_SIZE)) {
134
+ return a.size === HEPTATONIC_SIZE ? -1 : 1;
135
+ }
136
+ if (a.extra !== b.extra) {
137
+ return a.extra - b.extra;
138
+ }
139
+ const rankA = conventionalRank(a.name);
140
+ const rankB = conventionalRank(b.name);
141
+ if (rankA !== rankB) {
142
+ return rankA - rankB;
143
+ }
144
+ if (a.avoid !== b.avoid) {
145
+ return a.avoid - b.avoid;
146
+ }
147
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
148
+ });
149
+ return ranked.map((entry) => ({ name: entry.name, rootPc }));
150
+ }
151
+ function avoidNotes(chord, scaleName, opts = {}) {
152
+ const asked = _chunkS5BKZZGMcjs.assertOptions.call(void 0, opts, "opts");
153
+ const mask = requireChordScaleMask(scaleName);
154
+ const data = _chunk3R3QVKY5cjs.toChordData.call(void 0, chord);
155
+ const rootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, data.rootPc);
156
+ const chordPcs = _chunk3R3QVKY5cjs.chordPitchClasses.call(void 0, data);
157
+ const alteredDominant = isAlteredDominant(data, scaleName);
158
+ if (!scaleMatchesChord(chordPcs, mask, rootPc) && !alteredDominant) {
159
+ return [];
160
+ }
161
+ const chordSet = new Set(chordPcs);
162
+ const displaced = new Set(_chunk3R3QVKY5cjs.displacedThirds.call(void 0, data));
163
+ const melodic = asked.use === "melodic";
164
+ const semitoneAboveRoot = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + 1);
165
+ const avoid = [];
166
+ for (let pc = 0; pc < 12; pc += 1) {
167
+ if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {
168
+ continue;
169
+ }
170
+ if (melodic && pc !== semitoneAboveRoot) {
171
+ continue;
172
+ }
173
+ if (!alteredDominant && (chordSet.has(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, pc - 1)) || displaced.has(pc))) {
174
+ avoid.push(pc);
175
+ }
176
+ }
177
+ return avoid.sort((a, b) => a - b);
178
+ }
179
+ var MINOR_RESOLUTION_TENSIONS = [1, 3, 8];
180
+ function resolvesToMinorTonic(chord, chordPcs, target) {
181
+ if (target === void 0) {
182
+ return false;
183
+ }
184
+ const rootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, chord.rootPc);
185
+ const sounds = (semitones) => chordPcs.includes(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + semitones));
186
+ if (!sounds(4) || !sounds(10)) {
187
+ return false;
188
+ }
189
+ const targetRootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, target.rootPc);
190
+ if (targetRootPc !== _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + 5)) {
191
+ return false;
192
+ }
193
+ return _chunk3R3QVKY5cjs.chordPitchClasses.call(void 0, target).includes(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, targetRootPc + 3));
194
+ }
195
+ function availableTensions(chord, scaleName, opts = {}) {
196
+ const asked = _chunkS5BKZZGMcjs.assertOptions.call(void 0, opts, "opts");
197
+ const mask = requireChordScaleMask(scaleName);
198
+ const data = _chunk3R3QVKY5cjs.toChordData.call(void 0, chord);
199
+ const rootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, data.rootPc);
200
+ const chordPcs = _chunk3R3QVKY5cjs.chordPitchClasses.call(void 0, data);
201
+ const alteredDominant = isAlteredDominant(data, scaleName);
202
+ if (!scaleMatchesChord(chordPcs, mask, rootPc) && !alteredDominant) {
203
+ return [];
204
+ }
205
+ const chordSet = new Set(chordPcs);
206
+ const avoidSet = alteredDominant ? /* @__PURE__ */ new Set() : new Set(avoidNotes(data, scaleName));
207
+ const functional = resolvesToMinorTonic(
208
+ data,
209
+ chordPcs,
210
+ asked.resolvesTo === void 0 ? void 0 : _chunk3R3QVKY5cjs.toChordData.call(void 0, asked.resolvesTo)
211
+ ) ? new Set(MINOR_RESOLUTION_TENSIONS.map((semitones) => _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + semitones))) : void 0;
212
+ const tensions = [];
213
+ for (let pc = 0; pc < 12; pc += 1) {
214
+ if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {
215
+ continue;
216
+ }
217
+ if (avoidSet.has(pc) && _optionalChain([functional, 'optionalAccess', _2 => _2.has, 'call', _3 => _3(pc)]) !== true) {
218
+ continue;
219
+ }
220
+ tensions.push(pc);
221
+ }
222
+ return tensions.sort((a, b) => a - b);
223
+ }
224
+ function chordScaleReport(chord, limit) {
225
+ if (limit !== void 0) {
226
+ _chunkS5BKZZGMcjs.assertPositiveInt.call(void 0, limit, "chord-scale report limit");
227
+ }
228
+ const data = _chunk3R3QVKY5cjs.toChordData.call(void 0, chord);
229
+ const matches = chordScales(data);
230
+ const chosen = limit === void 0 ? matches : matches.slice(0, limit);
231
+ return chosen.map((match) => {
232
+ const harmonic = avoidNotes(data, match.name);
233
+ const melodic = new Set(avoidNotes(data, match.name, { use: "melodic" }));
234
+ return {
235
+ name: match.name,
236
+ rootPc: match.rootPc,
237
+ avoid: harmonic.filter((pc) => melodic.has(pc)),
238
+ passing: harmonic.filter((pc) => !melodic.has(pc)),
239
+ tensions: availableTensions(data, match.name)
240
+ };
241
+ });
242
+ }
243
+ var RANK_PENALTY = 0.01;
244
+ function scalePitchClassSet(name, rootPc) {
245
+ const mask = _chunk3R3QVKY5cjs.namedScaleMask.call(void 0, name);
246
+ const pcs = /* @__PURE__ */ new Set();
247
+ if (mask === void 0) {
248
+ return pcs;
249
+ }
250
+ for (let n = 0; n < 12; n += 1) {
251
+ if ((mask >> n & 1) === 1) {
252
+ pcs.add(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + n));
253
+ }
254
+ }
255
+ return pcs;
256
+ }
257
+ function symmetricDifferenceSize(a, b) {
258
+ let count = 0;
259
+ for (const pc of a) {
260
+ if (!b.has(pc)) {
261
+ count += 1;
262
+ }
263
+ }
264
+ for (const pc of b) {
265
+ if (!a.has(pc)) {
266
+ count += 1;
267
+ }
268
+ }
269
+ return count;
270
+ }
271
+ function scalesForChanges(chords) {
272
+ _chunkS5BKZZGMcjs.assertArray.call(void 0, chords, "chord-scale changes");
273
+ _chunkS5BKZZGMcjs.assertGenerationBudget.call(void 0, chords.length, "chord-scale changes");
274
+ if (chords.length === 0) {
275
+ return [];
276
+ }
277
+ const candidateLists = chords.map((chord) => chordScales(chord));
278
+ const pcSets = candidateLists.map(
279
+ (candidates) => candidates.map((match) => scalePitchClassSet(match.name, match.rootPc))
280
+ );
281
+ const first = _nullishCoalesce(candidateLists[0], () => ( []));
282
+ const dp = [first.map((_, j) => j * RANK_PENALTY)];
283
+ const back = [first.map(() => -1)];
284
+ for (let i = 1; i < candidateLists.length; i += 1) {
285
+ const candidates = _nullishCoalesce(candidateLists[i], () => ( []));
286
+ const prevCosts = _nullishCoalesce(dp[i - 1], () => ( []));
287
+ const prevSets = _nullishCoalesce(pcSets[i - 1], () => ( []));
288
+ const curSets = _nullishCoalesce(pcSets[i], () => ( []));
289
+ const stageCosts = [];
290
+ const stageBack = [];
291
+ for (let j = 0; j < candidates.length; j += 1) {
292
+ let bestCost = Number.POSITIVE_INFINITY;
293
+ let bestPrev = -1;
294
+ for (let k = 0; k < prevCosts.length; k += 1) {
295
+ const transition = symmetricDifferenceSize(
296
+ _nullishCoalesce(prevSets[k], () => ( /* @__PURE__ */ new Set())),
297
+ _nullishCoalesce(curSets[j], () => ( /* @__PURE__ */ new Set()))
298
+ );
299
+ const cost = (_nullishCoalesce(prevCosts[k], () => ( 0))) + transition;
300
+ if (cost < bestCost) {
301
+ bestCost = cost;
302
+ bestPrev = k;
303
+ }
304
+ }
305
+ stageCosts.push(bestCost + j * RANK_PENALTY);
306
+ stageBack.push(bestPrev);
307
+ }
308
+ dp.push(stageCosts);
309
+ back.push(stageBack);
310
+ }
311
+ const lastCosts = _nullishCoalesce(dp[dp.length - 1], () => ( []));
312
+ let bestFinal = 0;
313
+ for (let j = 1; j < lastCosts.length; j += 1) {
314
+ if ((_nullishCoalesce(lastCosts[j], () => ( Number.POSITIVE_INFINITY))) < (_nullishCoalesce(lastCosts[bestFinal], () => ( 0)))) {
315
+ bestFinal = j;
316
+ }
317
+ }
318
+ const chosenIndices = new Array(candidateLists.length);
319
+ let current = bestFinal;
320
+ for (let i = candidateLists.length - 1; i >= 0; i -= 1) {
321
+ chosenIndices[i] = current;
322
+ current = _nullishCoalesce(_optionalChain([back, 'access', _4 => _4[i], 'optionalAccess', _5 => _5[current]]), () => ( -1));
323
+ }
324
+ return chords.map((chord, i) => {
325
+ const candidates = _nullishCoalesce(candidateLists[i], () => ( []));
326
+ const scale = _nullishCoalesce(candidates[_nullishCoalesce(chosenIndices[i], () => ( 0))], () => ( { name: "chromatic", rootPc: chord.rootPc }));
327
+ return { chord, scale };
328
+ });
329
+ }
330
+
331
+ // src/theory/harmony/index.ts
332
+ function roleOf(pitch, chord, chordId = 0) {
333
+ _chunkS5BKZZGMcjs.assertFiniteNumber.call(void 0, chordId, "chordId");
334
+ const data = _chunk3R3QVKY5cjs.toChordData.call(void 0, chord);
335
+ const interval = (_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, pitch) - _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, data.rootPc) + 12) % 12;
336
+ const slot = _chunk3R3QVKY5cjs.thirdSlotOf.call(void 0, data);
337
+ const isSuspendedTone = slot.kind === "suspension" && interval === slot.interval;
338
+ const chordRole = _chunk3R3QVKY5cjs.chordToneRole.call(void 0, pitch, data);
339
+ let role;
340
+ let lock;
341
+ if (isSuspendedTone) {
342
+ role = "third";
343
+ lock = "quality";
344
+ } else if (chordRole !== null) {
345
+ role = chordRole;
346
+ lock = chordRole === "root" ? "identity" : chordRole === "third" ? "quality" : "voicing";
347
+ } else {
348
+ role = "tension";
349
+ lock = "voicing";
350
+ }
351
+ return { role, lock, belongsToChordId: chordId };
352
+ }
353
+
354
+
355
+
356
+
357
+
358
+
359
+
360
+
361
+
362
+ exports.scaleMatchesChord = scaleMatchesChord; exports.chordScales = chordScales; exports.avoidNotes = avoidNotes; exports.availableTensions = availableTensions; exports.chordScaleReport = chordScaleReport; exports.scalesForChanges = scalesForChanges; exports.roleOf = roleOf;
363
+ //# sourceMappingURL=chunk-PM4XJE2Y.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/libcantus/libcantus/dist/chunk-PM4XJE2Y.cjs","../src/theory/chordscale/index.ts","../src/theory/harmony/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACaA,SAAS,qBAAA,CAAsB,IAAA,EAAsB,MAAA,EAAQ,OAAA,EAAiB;AAC5E,EAAA,MAAM,UAAA,EAAY,gDAAA,IAAqB,CAAA;AACvC,EAAA,GAAA,CAAI,UAAA,IAAc,KAAA,EAAA,GAAa,CAAC,MAAA,CAAO,MAAA,CAAO,8BAAA,EAAc,SAAS,CAAA,EAAG;AACtE,IAAA,MAAM,IAAI,wCAAA;AAAA,MACR,CAAA,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAGA;AACM,EAAA;AACJ,EAAA;AACE,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAGA;AACE,EAAA;AACA,EAAA;AACF;AAYO;AAOL,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAkBM;AAGA;AASA;AACJ,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAGM;AACC,EAAA;AACL,EAAA;AAAgB;AAAA;AAAA;AAAA;AAKhB,EAAA;AACA,EAAA;AACF;AAGA;AACE,EAAA;AACA,EAAA;AACF;AAGA;AACE,EAAA;AACI,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAOA;AACE,EAAA;AACF;AA6CO;AACL,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACA,MAAA;AAAY,QAAA;AACV,QAAA;AACuB,QAAA;AACvB,QAAA;AAED,MAAA;AACH,IAAA;AACF,EAAA;AACI,EAAA;AAGF,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AAKA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACD,EAAA;AACD,EAAA;AACF;AAwDO;AAKL,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACK,EAAA;AACH,IAAA;AACF,EAAA;AACA,EAAA;AAKA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAWM;AAGN;AAKM,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACK,EAAA;AACH,IAAA;AACF,EAAA;AACA,EAAA;AACI,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AA+CO;AAKL,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACK,EAAA;AACH,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AAEE,EAAA;AAEJ,EAAA;AACA,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAqCO;AACD,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACD,EAAA;AACH;AAgBM;AAGN;AACE,EAAA;AACA,EAAA;AACI,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAGA;AACM,EAAA;AACJ,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAqBO;AACL,EAAA;AACA,EAAA;AACI,EAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AAAmC,IAAA;AAEnC,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AAAmB,2BAAA;AACM,2BAAA;AACD,QAAA;AAExB,QAAA;AACA,QAAA;AACE,UAAA;AACA,UAAA;AAAW,QAAA;AAEf,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACG,IAAA;AACH,IAAA;AACF,EAAA;AAEA,EAAA;AACI,EAAA;AACJ,EAAA;AACE,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AAEA,EAAA;AACI,EAAA;AACJ,EAAA;AACE,IAAA;AACA,IAAA;AACF,EAAA;AAEA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACD,EAAA;AACH;AD5UO;AACA;AExQA;AAGL,EAAA;AACA,EAAA;AACA,EAAA;AAIA,EAAA;AACA,EAAA;AACA,EAAA;AACI,EAAA;AACA,EAAA;AACA,EAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACE,IAAA;AACA,IAAA;AACF,EAAA;AACE,IAAA;AACA,IAAA;AACF,EAAA;AACA,EAAA;AACF;AFqQO;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/libcantus/libcantus/dist/chunk-PM4XJE2Y.cjs","sourcesContent":[null,"import { InvalidInputError } from '../../core/errors/index.js';\nimport { pitchClassOf as pitchClass } from '../../core/pitch/index.js';\nimport {\n assertArray,\n assertGenerationBudget,\n assertOptions,\n assertPitchClass,\n assertPositiveInt,\n} from '../../core/validation/index.js';\nimport type { Chord } from '../chord/index.js';\nimport { chordPitchClasses, displacedThirds } from '../chord/index.js';\nimport type { ScaleNameInput } from '../scale/index.js';\nimport {\n assertModeMask,\n NAMED_SCALES,\n namedScaleMask,\n requireScaleMask,\n resolveScaleName,\n} from '../scale/index.js';\nimport { type ChordLike, toChordData } from '../symbol/index.js';\n\n/**\n * The mask of a scale a chord-scale question may be asked about.\n *\n * Chord-scale theory is a Western practice, so the register of world scales is\n * not a vocabulary these functions answer from: a raga offered as the scale\n * over an altered dominant would read as an answer while being a category\n * error. {@link chordScales} proposes {@link NAMED_SCALES} and nothing else,\n * and the questions asked about one chosen scale accept exactly what it can\n * propose — an alias of a Western scale included, a world scale not.\n *\n * @param name The scale name or alias.\n * @param label What the name is, for the error message.\n * @returns The 12-bit mask.\n * @throws If the name is not a built-in scale, or names a world scale.\n */\nfunction requireChordScaleMask(name: ScaleNameInput, label = 'scale'): number {\n const canonical = resolveScaleName(name);\n if (canonical !== undefined && !Object.hasOwn(NAMED_SCALES, canonical)) {\n throw new InvalidInputError(\n `${label} must name a scale chord-scale theory ranks; ${String(name)} is a world scale`,\n );\n }\n return requireScaleMask(name, label);\n}\n\n/** Count the set bits (scale tones) in a 12-bit mode mask. */\nfunction popcount12(mask: number): number {\n let count = 0;\n for (let n = 0; n < 12; n += 1) {\n count += (mask >> n) & 1;\n }\n return count;\n}\n\n/** Test whether a pitch class belongs to a mode mask rooted on `scaleRootPc`. */\nfunction maskHasPitchClass(mask: number, scaleRootPc: number, pc: number): boolean {\n const offset = pitchClass(pc - scaleRootPc);\n return ((mask >> offset) & 1) === 1;\n}\n\n/**\n * Test whether every chord pitch class is contained in a scale.\n *\n * @param chordPcs The chord's pitch classes (0..11).\n * @param scaleMask The scale's 12-bit mode mask.\n * @param scaleRootPc The pitch class the mask is rooted on.\n * @returns True if the scale is a superset of the chord.\n *\n * @category Scales\n */\nexport function scaleMatchesChord(\n chordPcs: number[],\n scaleMask: number,\n scaleRootPc: number,\n): boolean {\n // The mask is read with bit operations and a pitch class shifts it, so both\n // coerce: an entry that is not a pitch class would silently be read as one.\n assertModeMask(scaleMask, 'scaleMask');\n assertPitchClass(scaleRootPc, 'scaleRootPc');\n const pcs = assertArray<number>(chordPcs, 'chord pitch classes');\n for (let index = 0; index < pcs.length; index += 1) {\n const pc = assertPitchClass(pcs[index] ?? Number.NaN, `chord pitch classes[${index}]`);\n if (!maskHasPitchClass(scaleMask, scaleRootPc, pc)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * A named scale rooted on a pitch class that fits over a chord.\n *\n * @category Scales\n */\nexport type ChordScaleMatch = {\n name: string;\n rootPc: number;\n};\n\n/**\n * Scale names whose mask duplicates another {@link NAMED_SCALES} entry\n * (major/ionian, naturalMinor/aeolian). Chord-scale analysis conventionally\n * speaks in mode names, so these aliases are skipped and only the modal name\n * is reported.\n */\nconst ALIASED_SCALE_NAMES = new Set(['major', 'naturalMinor']);\n\n/** Number of tones in a heptatonic (seven-note) scale. */\nconst HEPTATONIC_SIZE = 7;\n\n/**\n * Conventional preference among equally-fitting scales, brightest first.\n *\n * Several modes fit a chord that states no third or sixth — a power chord, a\n * suspension — equally well. Alphabetical order made `aeolian` the answer for\n * those, naming a minor mode as the best fit for a mode-neutral chord.\n */\nconst SCALE_PREFERENCE = [\n 'ionian',\n 'major',\n 'mixolydian',\n 'dorian',\n 'lydian',\n 'aeolian',\n 'naturalMinor',\n 'phrygian',\n 'locrian',\n] as const;\n\n/** Conventional first choices that pure set-fit ranking cannot express. */\nconst IDIOMATIC_SCALES: Partial<Record<Chord['quality'], readonly string[]>> = {\n aug: ['wholeTone'],\n m7b5: ['locrian'],\n // The diminished scale played over a diminished seventh is the whole-half\n // octatonic. Its half-whole rotation belongs to the dominant it colours: over\n // a diminished seventh every one of its non-chord tones lands a semitone\n // above a chord tone, so it offers no tension at all.\n dim7: ['octatonicWholeHalf'],\n minMaj7: ['melodicMinor'],\n};\n\n/** Position of a scale in {@link SCALE_PREFERENCE}, or last when unlisted. */\nfunction conventionalRank(name: string): number {\n const index = (SCALE_PREFERENCE as readonly string[]).indexOf(name);\n return index < 0 ? SCALE_PREFERENCE.length : index;\n}\n\n/** Whether this scale is an idiomatic color choice for the chord quality. */\nfunction idiomaticRank(chord: Chord, name: string): number {\n const choices = IDIOMATIC_SCALES[chord.quality];\n if (choices === undefined) {\n return 0;\n }\n const index = choices.indexOf(name);\n return index < 0 ? choices.length + 1 : index;\n}\n\n/**\n * An ordinary dominant seventh may use altered colors while retaining its\n * perfect fifth in the voicing; the `7alt` quality makes that alteration\n * explicit, but lead sheets commonly write the shorter `7` here.\n */\nfunction isAlteredDominant(chord: Chord, scaleName: string): boolean {\n return chord.quality === 'dom7' && scaleName === 'altered';\n}\n\n/**\n * List the scales that fit over a chord, best fit first.\n *\n * Only the chord root is considered as the scale root, matching the\n * conventional chord-scale relationship. Every entry of {@link NAMED_SCALES}\n * whose pitch-class set is a superset of the chord's is returned once per\n * distinct pitch-class set (aliased masks such as major/ionian report only the\n * modal name). The chromatic scale is only returned as a fallback when no other\n * scale contains the chord.\n *\n * The ranking applies these keys in order:\n *\n * 1. The idiomatic scales for the chord quality, in the order they are named\n * there, ahead of every scale that is not one of them.\n * 2. For bare triads and smaller chords, heptatonic scales ahead of pentatonics\n * and other sizes: a pentatonic adds no modal color over a triad, so the\n * seven-note modes are the more useful answer.\n * 3. Fewest extra scale tones beyond the chord.\n * 4. Conventional modal preference.\n * 5. Fewest avoid notes, which separates the symmetric and melodic-minor\n * scales the modal preference does not name.\n * 6. Alphabetical order, so the list is stable.\n *\n * The idiomatic key comes first, so the head of the list is the scale a player\n * would name rather than the tightest fit: over `Cm7b5` the locrian mode leads\n * even though the blues scale adds fewer tones, because locrian is what a\n * half-diminished chord is read as. Read further down the list, or pick by name,\n * when the closest fit is what is wanted; {@link scalesForChanges} makes the\n * choice for a whole progression.\n *\n * @param chord The chord to fit scales over, as a chord symbol, chord data, or\n * a `Chord`.\n * @returns The matching scales rooted on the chord root, best fit first.\n *\n * @example\n * ```ts\n * import { makeChord, chordScales } from '@libraz/libcantus';\n * const scales = chordScales(makeChord(0, 'maj7'));\n * // scales for Cmaj7, best fit first; each is { name, rootPc: 0 }\n * ```\n *\n * @category Scales\n */\nexport function chordScales(chord: ChordLike): ChordScaleMatch[] {\n const data = toChordData(chord);\n const chordPcs = chordPitchClasses(data);\n const rootPc = pitchClass(data.rootPc);\n const ranked: { name: string; extra: number; size: number; avoid: number }[] = [];\n const seenMasks = new Set<number>();\n for (const name of Object.keys(NAMED_SCALES)) {\n if (name === 'chromatic' || ALIASED_SCALE_NAMES.has(name)) {\n continue;\n }\n const mask = namedScaleMask(name);\n if (mask === undefined || seenMasks.has(mask)) {\n continue;\n }\n seenMasks.add(mask);\n if (scaleMatchesChord(chordPcs, mask, rootPc) || isAlteredDominant(data, name)) {\n const size = popcount12(mask);\n ranked.push({\n name,\n extra: size - chordPcs.length,\n size,\n avoid: avoidNotes(data, name).length,\n });\n }\n }\n if (ranked.length === 0) {\n // No diatonic-style scale contains the chord; fall back to the chromatic\n // scale, which trivially contains every pitch class.\n if (NAMED_SCALES.chromatic !== undefined) {\n return [{ name: 'chromatic', rootPc }];\n }\n return [];\n }\n const preferHeptatonic = chordPcs.length <= 3;\n ranked.sort((a, b) => {\n const idiomaticA = idiomaticRank(data, a.name);\n const idiomaticB = idiomaticRank(data, b.name);\n if (idiomaticA !== idiomaticB) {\n return idiomaticA - idiomaticB;\n }\n if (preferHeptatonic && (a.size === HEPTATONIC_SIZE) !== (b.size === HEPTATONIC_SIZE)) {\n return a.size === HEPTATONIC_SIZE ? -1 : 1;\n }\n if (a.extra !== b.extra) {\n return a.extra - b.extra;\n }\n const rankA = conventionalRank(a.name);\n const rankB = conventionalRank(b.name);\n if (rankA !== rankB) {\n return rankA - rankB;\n }\n // Among scales the modal preference does not name — the symmetric and\n // melodic-minor scales — the one that clashes with the chord least is the\n // one a player reaches for. Alphabetical order answered with the rotation\n // that leaves nothing playable.\n if (a.avoid !== b.avoid) {\n return a.avoid - b.avoid;\n }\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n });\n return ranked.map((entry) => ({ name: entry.name, rootPc }));\n}\n\n/**\n * Which use an avoid note is judged for: sounding it, or passing through it.\n *\n * `'harmonic'` is the Berklee-style rule in full — a tone that must not be\n * sounded against the chord. `'melodic'` keeps only what a line cannot pass\n * through either, which is the semitone above the root; every other clash\n * resolves as the line moves on.\n *\n * @category Scales\n */\nexport type AvoidNoteUse = 'harmonic' | 'melodic';\n\n/**\n * Options for {@link avoidNotes}.\n *\n * @category Scales\n */\nexport type AvoidNotesOptions = {\n use?: AvoidNoteUse;\n};\n\n/**\n * List a scale's avoid notes over a chord.\n *\n * An avoid note is a non-chord scale tone that lies a semitone directly above a\n * chord tone, or the third a suspension displaced; sounding it against the\n * chord clashes. The scale is rooted on the chord root. If the scale does not\n * contain the chord, no avoid notes exist.\n *\n * The rule states which tones must not be *sounded* against the chord, which is\n * not the same question as which tones a line may not touch. Pass\n * `{ use: 'melodic' }` for the melodic reading: only the semitone above the\n * root survives it, so the result is always a subset of the harmonic one.\n *\n * @param chord The chord providing the chord tones, as a chord symbol, chord\n * data, or a `Chord`.\n * @param scaleName A key of {@link NAMED_SCALES}, or an alias of one. A world\n * scale is not one: chord-scale theory is a Western practice, so a raga named\n * here is rejected rather than answered with a number.\n * @param opts Set `use: 'melodic'` to judge a line rather than a voicing.\n * @returns The avoid-note pitch classes, sorted ascending in [0, 11].\n * @throws If `scaleName` is not a built-in scale. An empty result already\n * means \"this scale has no avoid notes over this chord\"; answering a typo\n * the same way would make the two indistinguishable.\n *\n * @example\n * ```ts\n * import { makeChord, avoidNotes } from '@libraz/libcantus';\n * avoidNotes(makeChord(0, 'maj7'), 'ionian'); // [5] — F clashes with the third\n * avoidNotes(makeChord(0, 'maj7'), 'ionian', { use: 'melodic' }); // [] — a line may pass through it\n * ```\n *\n * @category Scales\n */\nexport function avoidNotes(\n chord: ChordLike,\n scaleName: ScaleNameInput,\n opts: AvoidNotesOptions = {},\n): number[] {\n const asked = assertOptions(opts, 'opts');\n const mask = requireChordScaleMask(scaleName);\n const data = toChordData(chord);\n const rootPc = pitchClass(data.rootPc);\n const chordPcs = chordPitchClasses(data);\n const alteredDominant = isAlteredDominant(data, scaleName);\n if (!scaleMatchesChord(chordPcs, mask, rootPc) && !alteredDominant) {\n return [];\n }\n const chordSet = new Set(chordPcs);\n // Sounding the third a suspension stands in for is what undoes the\n // suspension, so it is an avoid note however consonant it is against the\n // scale. Both thirds are named: a suspension does not say which one it\n // displaced — that is what suspending is — so meeting either one ends it.\n const displaced = new Set(displacedThirds(data));\n const melodic = asked.use === 'melodic';\n const semitoneAboveRoot = pitchClass(rootPc + 1);\n const avoid: number[] = [];\n for (let pc = 0; pc < 12; pc += 1) {\n if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {\n continue;\n }\n if (melodic && pc !== semitoneAboveRoot) {\n continue;\n }\n if (!alteredDominant && (chordSet.has(pitchClass(pc - 1)) || displaced.has(pc))) {\n avoid.push(pc);\n }\n }\n return avoid.sort((a, b) => a - b);\n}\n\n/**\n * Semitones above the root of the colors a dominant takes when it resolves to a\n * minor tonic: the flat ninth, the sharp ninth, and the flat thirteenth.\n *\n * Over a dominant read on its own, each of them sits a semitone above a chord\n * tone and is an avoid note. Heard as the dominant of a minor key they are the\n * key's own tones, and standard practice, so the function the chord serves is\n * what decides.\n */\nconst MINOR_RESOLUTION_TENSIONS = [1, 3, 8] as const;\n\n/** Whether this chord is a dominant seventh resolving down a fifth to minor. */\nfunction resolvesToMinorTonic(\n chord: Chord,\n chordPcs: number[],\n target: Chord | undefined,\n): boolean {\n if (target === undefined) {\n return false;\n }\n const rootPc = pitchClass(chord.rootPc);\n const sounds = (semitones: number): boolean => chordPcs.includes(pitchClass(rootPc + semitones));\n if (!sounds(4) || !sounds(10)) {\n return false;\n }\n const targetRootPc = pitchClass(target.rootPc);\n if (targetRootPc !== pitchClass(rootPc + 5)) {\n return false;\n }\n return chordPitchClasses(target).includes(pitchClass(targetRootPc + 3));\n}\n\n/**\n * Options for {@link availableTensions}.\n *\n * @category Scales\n */\nexport type AvailableTensionsOptions = {\n /**\n * The chord this one resolves to, as a chord symbol, chord data, or a\n * `Chord`.\n */\n resolvesTo?: ChordLike;\n};\n\n/**\n * List a scale's available tensions over a chord.\n *\n * Available tensions are scale tones that are neither chord tones nor avoid\n * notes, i.e. the usable color tones (typically the 9/11/13 region). The scale\n * is rooted on the chord root. If the scale does not contain the chord, there\n * are no available tensions.\n *\n * A tension's availability also depends on what the chord is doing. Pass\n * `resolvesTo` to say which chord this one resolves to: a dominant seventh\n * resolving down a fifth to a minor tonic takes its flat ninth, sharp ninth and\n * flat thirteenth, which read on their own would each be an avoid note. Only\n * scale tones are ever added, so the result stays within the scale.\n *\n * @param chord The chord providing the chord tones, as a chord symbol, chord\n * data, or a `Chord`.\n * @param scaleName A key of {@link NAMED_SCALES}, or an alias of one; a world\n * scale is outside chord-scale theory, as in {@link avoidNotes}.\n * @param opts Set `resolvesTo` to the chord this one resolves to.\n * @returns The available-tension pitch classes, sorted ascending in [0, 11].\n * @throws If `scaleName` is not a built-in scale, as {@link avoidNotes} does.\n *\n * @example\n * ```ts\n * import { makeChord, availableTensions } from '@libraz/libcantus';\n * availableTensions(makeChord(0, 'maj7'), 'ionian'); // [2, 9] — color tones over Cmaj7\n * availableTensions(makeChord(7, 'dom7'), 'phrygianDominant', { resolvesTo: makeChord(0, 'min') });\n * // [3, 8] — the b13 and b9 the resolution to C minor makes available\n * ```\n *\n * @category Scales\n */\nexport function availableTensions(\n chord: ChordLike,\n scaleName: ScaleNameInput,\n opts: AvailableTensionsOptions = {},\n): number[] {\n const asked = assertOptions(opts, 'opts');\n const mask = requireChordScaleMask(scaleName);\n const data = toChordData(chord);\n const rootPc = pitchClass(data.rootPc);\n const chordPcs = chordPitchClasses(data);\n const alteredDominant = isAlteredDominant(data, scaleName);\n if (!scaleMatchesChord(chordPcs, mask, rootPc) && !alteredDominant) {\n return [];\n }\n const chordSet = new Set(chordPcs);\n const avoidSet = alteredDominant ? new Set<number>() : new Set(avoidNotes(data, scaleName));\n const functional = resolvesToMinorTonic(\n data,\n chordPcs,\n asked.resolvesTo === undefined ? undefined : toChordData(asked.resolvesTo),\n )\n ? new Set(MINOR_RESOLUTION_TENSIONS.map((semitones) => pitchClass(rootPc + semitones)))\n : undefined;\n const tensions: number[] = [];\n for (let pc = 0; pc < 12; pc += 1) {\n if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {\n continue;\n }\n if (avoidSet.has(pc) && functional?.has(pc) !== true) {\n continue;\n }\n tensions.push(pc);\n }\n return tensions.sort((a, b) => a - b);\n}\n\n/**\n * A scale fit over a chord, with its non-chord tones sorted by what may be done\n * with them.\n *\n * `avoid`, `passing` and `tensions` partition the scale tones the chord does\n * not state: `avoid` may not be played at all, `passing` may be passed through\n * melodically but not sounded against the chord, and `tensions` may be added\n * freely as color. `avoid` is {@link avoidNotes} under `use: 'melodic'`, and\n * `avoid` together with `passing` is the harmonic reading.\n *\n * @category Scales\n */\nexport type ChordScaleReportEntry = {\n name: string;\n rootPc: number;\n avoid: number[];\n passing: number[];\n tensions: number[];\n};\n\n/**\n * Report the best-fitting scales for a chord with their avoid notes and tensions.\n *\n * Combines {@link chordScales}, {@link avoidNotes}, and {@link availableTensions}\n * into a single ergonomic result, ordered best fit first. The report is read as\n * playing advice, so the tones a line may pass through are reported apart from\n * the ones it may not touch; see {@link ChordScaleReportEntry}.\n *\n * @param chord The chord to analyze, as a chord symbol, chord data, or a\n * `Chord`.\n * @param limit Optional maximum number of scales to report; all by default.\n * @returns One entry per reported scale, best fit first.\n *\n * @category Scales\n */\nexport function chordScaleReport(chord: ChordLike, limit?: number): ChordScaleReportEntry[] {\n if (limit !== undefined) {\n assertPositiveInt(limit, 'chord-scale report limit');\n }\n const data = toChordData(chord);\n const matches = chordScales(data);\n const chosen = limit === undefined ? matches : matches.slice(0, limit);\n return chosen.map((match) => {\n const harmonic = avoidNotes(data, match.name);\n const melodic = new Set(avoidNotes(data, match.name, { use: 'melodic' }));\n return {\n name: match.name,\n rootPc: match.rootPc,\n avoid: harmonic.filter((pc) => melodic.has(pc)),\n passing: harmonic.filter((pc) => !melodic.has(pc)),\n tensions: availableTensions(data, match.name),\n };\n });\n}\n\n/**\n * A chord paired with the scale chosen for it by {@link scalesForChanges}.\n *\n * @category Scales\n */\nexport type ScaleChoice = {\n chord: Chord;\n scale: ChordScaleMatch;\n};\n\n/**\n * Small per-candidate penalty added in {@link scalesForChanges} so that, among\n * choices of otherwise-equal transition cost, the tighter best-fit scale wins.\n */\nconst RANK_PENALTY = 0.01;\n\n/** Build the pitch-class set of a named scale rooted on `rootPc`. */\nfunction scalePitchClassSet(name: string, rootPc: number): Set<number> {\n const mask = namedScaleMask(name);\n const pcs = new Set<number>();\n if (mask === undefined) {\n return pcs;\n }\n for (let n = 0; n < 12; n += 1) {\n if (((mask >> n) & 1) === 1) {\n pcs.add(pitchClass(rootPc + n));\n }\n }\n return pcs;\n}\n\n/** Count pitch classes that belong to exactly one of two sets. */\nfunction symmetricDifferenceSize(a: Set<number>, b: Set<number>): number {\n let count = 0;\n for (const pc of a) {\n if (!b.has(pc)) {\n count += 1;\n }\n }\n for (const pc of b) {\n if (!a.has(pc)) {\n count += 1;\n }\n }\n return count;\n}\n\n/**\n * Choose one scale per chord across a progression, favoring continuity.\n *\n * Each chord's {@link chordScales} candidates form a stage in a Viterbi-style\n * dynamic program. The transition cost between adjacent choices is the number\n * of pitch classes that differ between their pitch-class sets (the symmetric\n * difference), plus a small penalty for straying from a chord's best-fit scale\n * so that ties break toward the tighter fit. The minimum-total-cost path is\n * returned, one {@link ScaleChoice} per input chord in the original order.\n *\n * Each choice pairs its scale with the chord exactly as it was handed in, so\n * this takes plain chord data rather than the wider forms the entry points\n * above accept.\n *\n * @param chords The chord sequence to choose scales for.\n * @returns One scale choice per chord, in input order.\n *\n * @category Scales\n */\nexport function scalesForChanges(chords: readonly Chord[]): ScaleChoice[] {\n assertArray(chords, 'chord-scale changes');\n assertGenerationBudget(chords.length, 'chord-scale changes');\n if (chords.length === 0) {\n return [];\n }\n const candidateLists = chords.map((chord) => chordScales(chord));\n const pcSets = candidateLists.map((candidates) =>\n candidates.map((match) => scalePitchClassSet(match.name, match.rootPc)),\n );\n\n const first = candidateLists[0] ?? [];\n const dp: number[][] = [first.map((_, j) => j * RANK_PENALTY)];\n const back: number[][] = [first.map(() => -1)];\n\n for (let i = 1; i < candidateLists.length; i += 1) {\n const candidates = candidateLists[i] ?? [];\n const prevCosts = dp[i - 1] ?? [];\n const prevSets = pcSets[i - 1] ?? [];\n const curSets = pcSets[i] ?? [];\n const stageCosts: number[] = [];\n const stageBack: number[] = [];\n for (let j = 0; j < candidates.length; j += 1) {\n let bestCost = Number.POSITIVE_INFINITY;\n let bestPrev = -1;\n for (let k = 0; k < prevCosts.length; k += 1) {\n const transition = symmetricDifferenceSize(\n prevSets[k] ?? new Set(),\n curSets[j] ?? new Set(),\n );\n const cost = (prevCosts[k] ?? 0) + transition;\n if (cost < bestCost) {\n bestCost = cost;\n bestPrev = k;\n }\n }\n stageCosts.push(bestCost + j * RANK_PENALTY);\n stageBack.push(bestPrev);\n }\n dp.push(stageCosts);\n back.push(stageBack);\n }\n\n const lastCosts = dp[dp.length - 1] ?? [];\n let bestFinal = 0;\n for (let j = 1; j < lastCosts.length; j += 1) {\n if ((lastCosts[j] ?? Number.POSITIVE_INFINITY) < (lastCosts[bestFinal] ?? 0)) {\n bestFinal = j;\n }\n }\n\n const chosenIndices: number[] = new Array(candidateLists.length);\n let current = bestFinal;\n for (let i = candidateLists.length - 1; i >= 0; i -= 1) {\n chosenIndices[i] = current;\n current = back[i]?.[current] ?? -1;\n }\n\n return chords.map((chord, i) => {\n const candidates = candidateLists[i] ?? [];\n const scale = candidates[chosenIndices[i] ?? 0] ?? { name: 'chromatic', rootPc: chord.rootPc };\n return { chord, scale };\n });\n}\n","import { pitchClassOf } from '../../core/pitch/index.js';\nimport { assertFiniteNumber } from '../../core/validation/index.js';\nimport { type ChordToneRole, chordToneRole, thirdSlotOf } from '../chord/index.js';\nimport { type ChordLike, toChordData } from '../symbol/index.js';\n\n/**\n * Harmonic role a pitch plays within a chord.\n *\n * @category Functional Harmony\n */\nexport type HarmonyRole = ChordToneRole | 'tension' | 'doubling';\n\n/**\n * How firmly a pitch is locked to the chord's identity.\n *\n * - `identity`: moving it produces a different chord (the root).\n * - `quality`: moving it flips the chord quality (the third).\n * - `voicing`: it can move freely without changing chord identity or quality.\n *\n * @category Functional Harmony\n */\nexport type LockLevel = 'identity' | 'quality' | 'voicing';\n\n/**\n * A pitch's role, lock level, and owning chord.\n *\n * @category Functional Harmony\n */\nexport type VoicedRole = {\n role: HarmonyRole;\n lock: LockLevel;\n belongsToChordId: number;\n};\n\n/**\n * Classify a pitch's harmonic role and lock level within a chord.\n *\n * The role comes from the pitch's interval class above the chord root, read\n * against the chord's own template: root (0), third (3/4), fifth (6/7/8),\n * sixth or seventh (9/10/11). Every pitch the template does not claim is\n * `'tension'` — including one that is simply foreign to the chord, which this\n * single-pitch query cannot tell from a colour tone. The root locks the chord\n * identity, the third locks its quality, and everything else is free voicing.\n * Where a chord has no third, the tone standing in its place — the fourth of a\n * `sus4`, the second of a `sus2`, the eleventh of an eleventh chord — takes the\n * third's slot and is locked to `quality`, since moving it changes the chord.\n * At most one interval class of a chord is ever reported as its third, so a\n * consumer reading `lock: 'quality'` as \"this tone identifies the chord\" gets\n * one answer rather than two. Detecting an octave doubling requires the\n * surrounding voicing, which this query does not carry, so `'doubling'` is part\n * of the type — the shared vocabulary of harmonic roles — but is never returned\n * here.\n *\n * @param pitch MIDI pitch or bare pitch class.\n * @param chord The chord providing the root reference, as a chord symbol, chord\n * data, or a `Chord`.\n * @param chordId Identifier stored on the result (defaults to 0).\n * @returns The pitch's role, lock level, and owning chord id.\n * @example\n * ```ts\n * import { roleOf, makeChord } from '@libraz/libcantus';\n * roleOf(64, makeChord(0, 'maj')); // E over C major\n * // { role: 'third', lock: 'quality', belongsToChordId: 0 }\n * ```\n * @category Functional Harmony\n */\nexport function roleOf(pitch: number, chord: ChordLike, chordId = 0): VoicedRole {\n // The id is carried into the result, so a value that is not one would be\n // reported back as the chord this role belongs to.\n assertFiniteNumber(chordId, 'chordId');\n const data = toChordData(chord);\n const interval = (pitchClassOf(pitch) - pitchClassOf(data.rootPc) + 12) % 12;\n // What stands in the third's slot is read where the chord is read, not here:\n // the tone that identifies a chord and the tone the avoid-note rule refuses\n // against it are two consequences of one fact about the chord.\n const slot = thirdSlotOf(data);\n const isSuspendedTone = slot.kind === 'suspension' && interval === slot.interval;\n const chordRole = chordToneRole(pitch, data);\n let role: HarmonyRole;\n let lock: LockLevel;\n if (isSuspendedTone) {\n role = 'third'; // suspended tone occupies the third's quality-defining slot\n lock = 'quality';\n } else if (chordRole !== null) {\n role = chordRole;\n lock = chordRole === 'root' ? 'identity' : chordRole === 'third' ? 'quality' : 'voicing';\n } else {\n role = 'tension';\n lock = 'voicing';\n }\n return { role, lock, belongsToChordId: chordId };\n}\n"]}
@@ -0,0 +1,145 @@
1
+ import {
2
+ BEAT_EPS,
3
+ assertFiniteNumber,
4
+ assertNoteEvents,
5
+ assertOptions
6
+ } from "./chunk-AGOVW7U6.js";
7
+
8
+ // src/core/event-index/index.ts
9
+ function upperBound(values, beat) {
10
+ let low = 0;
11
+ let high = values.length;
12
+ while (low < high) {
13
+ const middle = Math.floor((low + high) / 2);
14
+ if ((values[middle]?.note.startBeat ?? Number.POSITIVE_INFINITY) <= beat) {
15
+ low = middle + 1;
16
+ } else {
17
+ high = middle;
18
+ }
19
+ }
20
+ return low;
21
+ }
22
+ function sortedNoteEvents(events) {
23
+ const sorted = events.map((note) => ({ ...note }));
24
+ sorted.sort((a, b) => a.startBeat - b.startBeat);
25
+ return sorted;
26
+ }
27
+ function createNoteEventIndex(events, options = {}) {
28
+ const asked = assertOptions(options, "options");
29
+ assertNoteEvents(events, asked.name ?? "note events", asked);
30
+ const tieBreak = asked.tieBreak ?? "highest";
31
+ const notes = Object.freeze(
32
+ events.map(
33
+ (note, originalIndex) => Object.freeze({
34
+ note: Object.freeze({ ...note }),
35
+ originalIndex,
36
+ endBeat: note.startBeat + note.durationBeat
37
+ })
38
+ ).sort((a, b) => a.note.startBeat - b.note.startBeat || a.originalIndex - b.originalIndex)
39
+ );
40
+ let maxEndTree;
41
+ let treeSize = 0;
42
+ const endTree = () => {
43
+ if (maxEndTree !== void 0) {
44
+ return maxEndTree;
45
+ }
46
+ treeSize = 1;
47
+ while (treeSize < notes.length) treeSize *= 2;
48
+ const tree = new Array(treeSize * 2).fill(Number.NEGATIVE_INFINITY);
49
+ for (let index = 0; index < notes.length; index += 1) {
50
+ tree[treeSize + index] = notes[index]?.endBeat ?? Number.NEGATIVE_INFINITY;
51
+ }
52
+ for (let index = treeSize - 1; index > 0; index -= 1) {
53
+ tree[index] = Math.max(
54
+ tree[index * 2] ?? Number.NEGATIVE_INFINITY,
55
+ tree[index * 2 + 1] ?? Number.NEGATIVE_INFINITY
56
+ );
57
+ }
58
+ maxEndTree = tree;
59
+ return tree;
60
+ };
61
+ const latestActiveIndex = (exclusive, beat) => {
62
+ const tree = endTree();
63
+ const find = (node, start, end) => {
64
+ if (start >= exclusive || (tree[node] ?? Number.NEGATIVE_INFINITY) <= beat + BEAT_EPS) {
65
+ return -1;
66
+ }
67
+ if (end - start === 1) return start < notes.length ? start : -1;
68
+ const mid = Math.floor((start + end) / 2);
69
+ const right = find(node * 2 + 1, mid, end);
70
+ return right >= 0 ? right : find(node * 2, start, mid);
71
+ };
72
+ return find(1, 0, treeSize);
73
+ };
74
+ return {
75
+ notes,
76
+ at(beat) {
77
+ assertFiniteNumber(beat, "beat");
78
+ const index = latestActiveIndex(upperBound(notes, beat + BEAT_EPS), beat);
79
+ if (index < 0) return void 0;
80
+ const onset = notes[index]?.note.startBeat;
81
+ let best;
82
+ for (let candidateIndex = index; candidateIndex >= 0; candidateIndex -= 1) {
83
+ const indexed = notes[candidateIndex];
84
+ if (indexed !== void 0 && indexed.note.startBeat !== onset) break;
85
+ if (indexed === void 0 || indexed.note.durationBeat <= 0 || indexed.note.startBeat - BEAT_EPS > beat || beat >= indexed.endBeat - BEAT_EPS) {
86
+ continue;
87
+ }
88
+ if (best === void 0) {
89
+ best = indexed;
90
+ continue;
91
+ }
92
+ if (tieBreak === "last") continue;
93
+ const difference = indexed.note.pitch - best.note.pitch;
94
+ const wins = difference === 0 ? indexed.originalIndex < best.originalIndex : difference > 0 === (tieBreak === "highest");
95
+ if (wins) {
96
+ best = indexed;
97
+ }
98
+ }
99
+ return best;
100
+ },
101
+ attacksAt(beat) {
102
+ assertFiniteNumber(beat, "beat");
103
+ let index = upperBound(notes, beat + BEAT_EPS) - 1;
104
+ while (index >= 0) {
105
+ const candidate = notes[index];
106
+ if (candidate === void 0 || Math.abs(candidate.note.startBeat - beat) >= BEAT_EPS) {
107
+ return false;
108
+ }
109
+ if (candidate.note.durationBeat > 0) {
110
+ return true;
111
+ }
112
+ index -= 1;
113
+ }
114
+ return false;
115
+ },
116
+ onsetsBetween(startBeat, endBeat) {
117
+ assertFiniteNumber(startBeat, "startBeat");
118
+ assertFiniteNumber(endBeat, "endBeat");
119
+ const result = [];
120
+ let index = upperBound(notes, startBeat + BEAT_EPS);
121
+ while (index < notes.length) {
122
+ const indexed = notes[index];
123
+ const onset = indexed?.note.startBeat;
124
+ if (indexed === void 0 || onset === void 0 || onset >= endBeat - BEAT_EPS) {
125
+ break;
126
+ }
127
+ index += 1;
128
+ if (indexed.note.durationBeat <= 0) {
129
+ continue;
130
+ }
131
+ const previous = result[result.length - 1];
132
+ if (previous === void 0 || Math.abs(previous - onset) >= BEAT_EPS) {
133
+ result.push(onset);
134
+ }
135
+ }
136
+ return result;
137
+ }
138
+ };
139
+ }
140
+
141
+ export {
142
+ sortedNoteEvents,
143
+ createNoteEventIndex
144
+ };
145
+ //# sourceMappingURL=chunk-PUKJP2Z5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/event-index/index.ts"],"sourcesContent":["import { BEAT_EPS } from '../meter/internal.js';\nimport type { NoteEvent } from '../types.js';\nimport { assertFiniteNumber, assertNoteEvents, assertOptions } from '../validation/index.js';\n\n/**\n * A validated note retaining its position in the caller's original array.\n *\n * @category Core\n */\nexport type IndexedNoteEvent = {\n readonly note: Readonly<NoteEvent>;\n readonly originalIndex: number;\n readonly endBeat: number;\n};\n\n/**\n * Which note wins when several sound from the same onset.\n *\n * `'highest'` and `'lowest'` name a voice, so the answer does not depend on the\n * order the caller happened to store the chord in; `'last'` takes the one\n * latest in the input array. Two notes of the same pitch name no voice apart,\n * so both voice tie-breaks settle a unison on the lower `originalIndex` and\n * name the same note.\n *\n * @category Core\n */\nexport type OnsetTieBreak = 'highest' | 'lowest' | 'last';\n\n/**\n * Binary-searchable, stable-sorted index over note onsets and active spans.\n *\n * @category Core\n */\nexport type NoteEventIndex = {\n notes: readonly IndexedNoteEvent[];\n /**\n * Latest-onset note sounding at `beat`. Simultaneous onsets are resolved by\n * the index's {@link OnsetTieBreak}.\n *\n * @throws If `beat` is not finite.\n */\n at: (beat: number) => IndexedNoteEvent | undefined;\n /**\n * Whether one or more sounding notes attack at `beat`.\n *\n * @throws If `beat` is not finite.\n */\n attacksAt: (beat: number) => boolean;\n /**\n * Unique sounding-note attack beats strictly inside `(startBeat, endBeat)`.\n *\n * @throws If either bound is not finite.\n */\n onsetsBetween: (startBeat: number, endBeat: number) => number[];\n};\n\nfunction upperBound(values: readonly IndexedNoteEvent[], beat: number): number {\n let low = 0;\n let high = values.length;\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n if ((values[middle]?.note.startBeat ?? Number.POSITIVE_INFINITY) <= beat) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return low;\n}\n\n/**\n * Copy note events and put them in stable onset order.\n *\n * The order is the one {@link createNoteEventIndex} numbers its notes in, so a\n * pass may read the sequence here and the index there and see the same notes in\n * the same places. What it does not build is the index itself: a caller that\n * only walks the notes in time order would otherwise pay for a segment tree and\n * a wrapper per note that it never queries.\n *\n * The events are copied, so the sequence is the caller's own and two entries\n * that arrived as one shared object stay two.\n *\n * @param events The events to order; already validated by the caller.\n * @returns The copies, earliest onset first, ties in input order.\n */\nexport function sortedNoteEvents(events: readonly NoteEvent[]): NoteEvent[] {\n const sorted = events.map((note) => ({ ...note }));\n // Array sort is stable, so events sharing an onset keep the order they were\n // given in — the tie-break the index spells out as `originalIndex`.\n sorted.sort((a, b) => a.startBeat - b.startBeat);\n return sorted;\n}\n\n/**\n * How an index reads the events it is built from.\n *\n * @category Core\n */\nexport type NoteEventIndexOptions = {\n allowNonPositiveDuration?: boolean;\n tieBreak?: OnsetTieBreak;\n budget?: number;\n /** What the events are, for the validation error message. */\n name?: string;\n};\n\n/**\n * Validate and stable-sort note events once, then expose onset and active-note\n * lookups that cost `O(log n + k)`, where `k` is how many notes share the onset\n * the answer comes from. Non-positive-duration notes may be retained for\n * callers that intentionally filter them later, but never count as sounding.\n *\n * @category Core\n */\nexport function createNoteEventIndex(\n events: readonly NoteEvent[],\n options: NoteEventIndexOptions = {},\n): NoteEventIndex {\n const asked = assertOptions(options, 'options');\n assertNoteEvents(events, asked.name ?? 'note events', asked);\n const tieBreak = asked.tieBreak ?? 'highest';\n // Each wrapper is frozen, not only the array and the note inside it: `endBeat`\n // is what the active-note search is built from, so a host that writes to it\n // would leave the index answering from a span nothing else knows about.\n const notes = Object.freeze(\n events\n .map((note, originalIndex) =>\n Object.freeze({\n note: Object.freeze({ ...note }),\n originalIndex,\n endBeat: note.startBeat + note.durationBeat,\n }),\n )\n .sort((a, b) => a.note.startBeat - b.note.startBeat || a.originalIndex - b.originalIndex),\n );\n // Segment-tree maxima find the latest active onset in logarithmic time even\n // when an early, very long note would defeat a prefix-max backwards scan.\n //\n // It is built on the first `at` query rather than on construction: the onset\n // queries answer from the sorted notes alone, so a caller that never asks\n // which note is sounding would otherwise pay for a structure it never reads.\n let maxEndTree: number[] | undefined;\n let treeSize = 0;\n const endTree = (): number[] => {\n if (maxEndTree !== undefined) {\n return maxEndTree;\n }\n treeSize = 1;\n while (treeSize < notes.length) treeSize *= 2;\n const tree = new Array<number>(treeSize * 2).fill(Number.NEGATIVE_INFINITY);\n for (let index = 0; index < notes.length; index += 1) {\n tree[treeSize + index] = notes[index]?.endBeat ?? Number.NEGATIVE_INFINITY;\n }\n for (let index = treeSize - 1; index > 0; index -= 1) {\n tree[index] = Math.max(\n tree[index * 2] ?? Number.NEGATIVE_INFINITY,\n tree[index * 2 + 1] ?? Number.NEGATIVE_INFINITY,\n );\n }\n maxEndTree = tree;\n return tree;\n };\n const latestActiveIndex = (exclusive: number, beat: number): number => {\n const tree = endTree();\n const find = (node: number, start: number, end: number): number => {\n if (start >= exclusive || (tree[node] ?? Number.NEGATIVE_INFINITY) <= beat + BEAT_EPS) {\n return -1;\n }\n if (end - start === 1) return start < notes.length ? start : -1;\n const mid = Math.floor((start + end) / 2);\n const right = find(node * 2 + 1, mid, end);\n return right >= 0 ? right : find(node * 2, start, mid);\n };\n return find(1, 0, treeSize);\n };\n\n return {\n notes,\n at(beat) {\n // A query beat comes from wherever the host got it — a scrub position, a\n // parsed field — so it is checked like any other entry argument. `NaN`\n // compares false against every bound, which would read as an open window\n // rather than as the missing value it is.\n assertFiniteNumber(beat, 'beat');\n const index = latestActiveIndex(upperBound(notes, beat + BEAT_EPS), beat);\n if (index < 0) return undefined;\n const onset = notes[index]?.note.startBeat;\n let best: IndexedNoteEvent | undefined;\n for (let candidateIndex = index; candidateIndex >= 0; candidateIndex -= 1) {\n const indexed = notes[candidateIndex];\n if (indexed !== undefined && indexed.note.startBeat !== onset) break;\n if (\n indexed === undefined ||\n indexed.note.durationBeat <= 0 ||\n indexed.note.startBeat - BEAT_EPS > beat ||\n beat >= indexed.endBeat - BEAT_EPS\n ) {\n continue;\n }\n if (best === undefined) {\n best = indexed;\n continue;\n }\n if (tieBreak === 'last') continue;\n const difference = indexed.note.pitch - best.note.pitch;\n // Equal pitches name no voice apart, so they are settled on the lower\n // original index rather than on whichever end of the array the scan\n // happens to reach last — otherwise `'highest'` and `'lowest'` would\n // answer a unison differently.\n const wins =\n difference === 0\n ? indexed.originalIndex < best.originalIndex\n : difference > 0 === (tieBreak === 'highest');\n if (wins) {\n best = indexed;\n }\n }\n return best;\n },\n attacksAt(beat) {\n assertFiniteNumber(beat, 'beat');\n // Only a sounding note attacks: a zero-length artefact must not make\n // `attacksAt(b)` true on a beat where `at(b)` finds nothing.\n let index = upperBound(notes, beat + BEAT_EPS) - 1;\n while (index >= 0) {\n const candidate = notes[index];\n if (candidate === undefined || Math.abs(candidate.note.startBeat - beat) >= BEAT_EPS) {\n return false;\n }\n if (candidate.note.durationBeat > 0) {\n return true;\n }\n index -= 1;\n }\n return false;\n },\n onsetsBetween(startBeat, endBeat) {\n assertFiniteNumber(startBeat, 'startBeat');\n assertFiniteNumber(endBeat, 'endBeat');\n const result: number[] = [];\n let index = upperBound(notes, startBeat + BEAT_EPS);\n while (index < notes.length) {\n const indexed = notes[index];\n const onset = indexed?.note.startBeat;\n if (indexed === undefined || onset === undefined || onset >= endBeat - BEAT_EPS) {\n break;\n }\n index += 1;\n if (indexed.note.durationBeat <= 0) {\n continue;\n }\n const previous = result[result.length - 1];\n if (previous === undefined || Math.abs(previous - onset) >= BEAT_EPS) {\n result.push(onset);\n }\n }\n return result;\n },\n };\n}\n"],"mappings":"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","names":[]}