@libraz/libcantus 1.3.0 → 1.4.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 (130) hide show
  1. package/NOTICE +63 -0
  2. package/README.md +3 -1
  3. package/README_ja.md +13 -11
  4. package/dist/analyze/index.cjs +7 -7
  5. package/dist/analyze/index.cjs.map +1 -1
  6. package/dist/analyze/index.d.cts +14 -12
  7. package/dist/analyze/index.d.ts +14 -12
  8. package/dist/analyze/index.js +6 -6
  9. package/dist/{chunk-NB25P3EH.js → chunk-2G5MCGYU.js} +33 -11
  10. package/dist/chunk-2G5MCGYU.js.map +1 -0
  11. package/dist/{chunk-NM7UAMC3.cjs → chunk-3FDBMIPR.cjs} +64 -64
  12. package/dist/chunk-3FDBMIPR.cjs.map +1 -0
  13. package/dist/{chunk-YFA7X2F6.cjs → chunk-3MDOEFIQ.cjs} +411 -327
  14. package/dist/chunk-3MDOEFIQ.cjs.map +1 -0
  15. package/dist/{chunk-IPEF6NWB.js → chunk-5MWRBYAT.js} +278 -154
  16. package/dist/chunk-5MWRBYAT.js.map +1 -0
  17. package/dist/{chunk-B2PW6EHN.cjs → chunk-6TTBEON3.cjs} +1253 -889
  18. package/dist/chunk-6TTBEON3.cjs.map +1 -0
  19. package/dist/{chunk-UMWZ4ZET.js → chunk-7NQ6AL3H.js} +4 -4
  20. package/dist/chunk-7NQ6AL3H.js.map +1 -0
  21. package/dist/{chunk-PWC4CRWT.cjs → chunk-E3QO3UET.cjs} +31 -23
  22. package/dist/chunk-E3QO3UET.cjs.map +1 -0
  23. package/dist/{chunk-GNVN4PPJ.js → chunk-FJFULJZE.js} +531 -213
  24. package/dist/chunk-FJFULJZE.js.map +1 -0
  25. package/dist/{chunk-CPMB7P75.js → chunk-FK3DGAIZ.js} +608 -244
  26. package/dist/chunk-FK3DGAIZ.js.map +1 -0
  27. package/dist/chunk-GEDTJHAC.cjs.map +1 -1
  28. package/dist/{chunk-RFIBF2RR.js → chunk-H7FVMBUC.js} +138 -65
  29. package/dist/chunk-H7FVMBUC.js.map +1 -0
  30. package/dist/{chunk-4R2LWV7E.cjs → chunk-HYSVSFNI.cjs} +664 -540
  31. package/dist/chunk-HYSVSFNI.cjs.map +1 -0
  32. package/dist/{chunk-35NBV2FT.cjs → chunk-KMYGRFZ6.cjs} +47 -24
  33. package/dist/chunk-KMYGRFZ6.cjs.map +1 -0
  34. package/dist/{chunk-IFZDWIKM.cjs → chunk-LQZQDBCD.cjs} +1048 -730
  35. package/dist/chunk-LQZQDBCD.cjs.map +1 -0
  36. package/dist/{chunk-PM4XJE2Y.cjs → chunk-P3CPXAJ5.cjs} +76 -54
  37. package/dist/chunk-P3CPXAJ5.cjs.map +1 -0
  38. package/dist/{chunk-S5BKZZGM.cjs → chunk-S3QELJUE.cjs} +72 -56
  39. package/dist/chunk-S3QELJUE.cjs.map +1 -0
  40. package/dist/{chunk-PUKJP2Z5.js → chunk-TXFWSU5D.js} +31 -8
  41. package/dist/chunk-TXFWSU5D.js.map +1 -0
  42. package/dist/{chunk-76ZBTRG2.cjs → chunk-U4EQTDGN.cjs} +258 -218
  43. package/dist/chunk-U4EQTDGN.cjs.map +1 -0
  44. package/dist/chunk-UGLFDG7L.cjs.map +1 -1
  45. package/dist/{chunk-MLBPXA4Z.js → chunk-UTE5A36R.js} +198 -114
  46. package/dist/chunk-UTE5A36R.js.map +1 -0
  47. package/dist/{chunk-ZBUROTJQ.js → chunk-UZKQISRF.js} +17 -9
  48. package/dist/chunk-UZKQISRF.js.map +1 -0
  49. package/dist/{chunk-7KG3RTYS.js → chunk-VL5NXVCN.js} +281 -155
  50. package/dist/chunk-VL5NXVCN.js.map +1 -0
  51. package/dist/{chunk-CGBADIO5.cjs → chunk-WOMCXN2W.cjs} +328 -202
  52. package/dist/chunk-WOMCXN2W.cjs.map +1 -0
  53. package/dist/{chunk-3R3QVKY5.cjs → chunk-YDGMWH43.cjs} +397 -324
  54. package/dist/chunk-YDGMWH43.cjs.map +1 -0
  55. package/dist/{chunk-AGOVW7U6.js → chunk-YYVXRV3V.js} +72 -56
  56. package/dist/chunk-YYVXRV3V.js.map +1 -0
  57. package/dist/{chunk-M5RYMAFI.js → chunk-ZLNSH4UL.js} +71 -31
  58. package/dist/chunk-ZLNSH4UL.js.map +1 -0
  59. package/dist/{coerce-DRERzdve.d.cts → coerce-CUhHc3Tu.d.ts} +16 -8
  60. package/dist/{coerce-DP0vYu-x.d.ts → coerce-Ytt2Eiq9.d.cts} +16 -8
  61. package/dist/core/index.cjs +5 -5
  62. package/dist/core/index.cjs.map +1 -1
  63. package/dist/core/index.d.cts +9 -8
  64. package/dist/core/index.d.ts +9 -8
  65. package/dist/core/index.js +4 -4
  66. package/dist/generate/index.cjs +8 -8
  67. package/dist/generate/index.cjs.map +1 -1
  68. package/dist/generate/index.d.cts +28 -18
  69. package/dist/generate/index.d.ts +28 -18
  70. package/dist/generate/index.js +7 -7
  71. package/dist/{index-BMweUlm5.d.cts → index-5VJgKz_Q.d.cts} +6 -2
  72. package/dist/{index-BHIUyjhZ.d.ts → index-BLuDesVG.d.ts} +20 -13
  73. package/dist/{index-B9QLziDe.d.cts → index-BV6APVa6.d.cts} +20 -13
  74. package/dist/{index-CL4b4gUQ.d.ts → index-Bf0Sv8a9.d.ts} +6 -2
  75. package/dist/{index-Dw2DP7vm.d.ts → index-BkT21EMv.d.cts} +3 -2
  76. package/dist/{index-BL5N2Oyz.d.cts → index-C7KCaTRz.d.ts} +3 -2
  77. package/dist/{index-Cy15oTvh.d.ts → index-C9MYbuKS.d.cts} +7 -3
  78. package/dist/{index-Cy15oTvh.d.cts → index-C9MYbuKS.d.ts} +7 -3
  79. package/dist/{index-CY-3NVfy.d.cts → index-DVInzCDS.d.cts} +53 -29
  80. package/dist/{index-9eoQs2C1.d.ts → index-Dg-SAfhz.d.ts} +6 -4
  81. package/dist/{index-zaZdmnU4.d.ts → index-jgeug9EA.d.ts} +53 -29
  82. package/dist/{index-cHvbYgJI.d.cts → index-pQihL4z7.d.cts} +6 -4
  83. package/dist/index.cjs +13 -13
  84. package/dist/index.cjs.map +1 -1
  85. package/dist/index.d.cts +11 -11
  86. package/dist/index.d.ts +11 -11
  87. package/dist/index.js +12 -12
  88. package/dist/{masks-Cc7-MzzY.d.ts → masks-BnzXnBj0.d.cts} +3 -2
  89. package/dist/{masks-pADfTOiD.d.cts → masks-tycmkrgs.d.ts} +3 -2
  90. package/dist/model/index.cjs +12 -12
  91. package/dist/model/index.cjs.map +1 -1
  92. package/dist/model/index.d.cts +63 -48
  93. package/dist/model/index.d.ts +63 -48
  94. package/dist/model/index.js +11 -11
  95. package/dist/{positional-DJgs6ltD.d.ts → positional-CscpxtlE.d.cts} +3 -2
  96. package/dist/{positional-DMZer-FM.d.cts → positional-DLnfUgqG.d.ts} +3 -2
  97. package/dist/{profile-DLdlIpS9.d.ts → profile-B4WqcM4H.d.ts} +25 -17
  98. package/dist/{profile-CQMEqdH9.d.cts → profile-BJd1XkPB.d.cts} +25 -17
  99. package/dist/theory/index.cjs +5 -5
  100. package/dist/theory/index.cjs.map +1 -1
  101. package/dist/theory/index.d.cts +18 -14
  102. package/dist/theory/index.d.ts +18 -14
  103. package/dist/theory/index.js +4 -4
  104. package/dist/{types-D-XgxGvp.d.cts → types-7mGFwvMm.d.ts} +45 -22
  105. package/dist/{types-Dh7C064C.d.ts → types-_ofpb2be.d.cts} +45 -22
  106. package/package.json +13 -13
  107. package/dist/chunk-35NBV2FT.cjs.map +0 -1
  108. package/dist/chunk-3R3QVKY5.cjs.map +0 -1
  109. package/dist/chunk-4R2LWV7E.cjs.map +0 -1
  110. package/dist/chunk-76ZBTRG2.cjs.map +0 -1
  111. package/dist/chunk-7KG3RTYS.js.map +0 -1
  112. package/dist/chunk-AGOVW7U6.js.map +0 -1
  113. package/dist/chunk-B2PW6EHN.cjs.map +0 -1
  114. package/dist/chunk-CGBADIO5.cjs.map +0 -1
  115. package/dist/chunk-CPMB7P75.js.map +0 -1
  116. package/dist/chunk-GNVN4PPJ.js.map +0 -1
  117. package/dist/chunk-IFZDWIKM.cjs.map +0 -1
  118. package/dist/chunk-IPEF6NWB.js.map +0 -1
  119. package/dist/chunk-M5RYMAFI.js.map +0 -1
  120. package/dist/chunk-MLBPXA4Z.js.map +0 -1
  121. package/dist/chunk-NB25P3EH.js.map +0 -1
  122. package/dist/chunk-NM7UAMC3.cjs.map +0 -1
  123. package/dist/chunk-PM4XJE2Y.cjs.map +0 -1
  124. package/dist/chunk-PUKJP2Z5.js.map +0 -1
  125. package/dist/chunk-PWC4CRWT.cjs.map +0 -1
  126. package/dist/chunk-RFIBF2RR.js.map +0 -1
  127. package/dist/chunk-S5BKZZGM.cjs.map +0 -1
  128. package/dist/chunk-UMWZ4ZET.js.map +0 -1
  129. package/dist/chunk-YFA7X2F6.cjs.map +0 -1
  130. package/dist/chunk-ZBUROTJQ.js.map +0 -1
@@ -9,8 +9,8 @@
9
9
 
10
10
 
11
11
 
12
- var _chunk3R3QVKY5cjs = require('./chunk-3R3QVKY5.cjs');
13
12
 
13
+ var _chunkYDGMWH43cjs = require('./chunk-YDGMWH43.cjs');
14
14
 
15
15
 
16
16
 
@@ -19,17 +19,19 @@ var _chunk3R3QVKY5cjs = require('./chunk-3R3QVKY5.cjs');
19
19
 
20
20
 
21
21
 
22
- var _chunkS5BKZZGMcjs = require('./chunk-S5BKZZGM.cjs');
22
+
23
+
24
+ var _chunkS3QELJUEcjs = require('./chunk-S3QELJUE.cjs');
23
25
 
24
26
  // src/theory/chordscale/index.ts
25
27
  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)(
28
+ const canonical = _chunkYDGMWH43cjs.resolveScaleName.call(void 0, name);
29
+ if (canonical !== void 0 && !Object.hasOwn(_chunkYDGMWH43cjs.NAMED_SCALES, canonical)) {
30
+ throw new (0, _chunkS3QELJUEcjs.InvalidInputError)(
29
31
  `${label} must name a scale chord-scale theory ranks; ${String(name)} is a world scale`
30
32
  );
31
33
  }
32
- return _chunk3R3QVKY5cjs.requireScaleMask.call(void 0, name, label);
34
+ return _chunkYDGMWH43cjs.requireScaleMask.call(void 0, name, label);
33
35
  }
34
36
  function popcount12(mask) {
35
37
  let count = 0;
@@ -39,22 +41,23 @@ function popcount12(mask) {
39
41
  return count;
40
42
  }
41
43
  function maskHasPitchClass(mask, scaleRootPc, pc) {
42
- const offset = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, pc - scaleRootPc);
44
+ const offset = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, pc - scaleRootPc);
43
45
  return (mask >> offset & 1) === 1;
44
46
  }
45
47
  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");
48
+ _chunkYDGMWH43cjs.assertModeMask.call(void 0, scaleMask, "scaleMask");
49
+ _chunkS3QELJUEcjs.assertPitchClass.call(void 0, scaleRootPc, "scaleRootPc");
50
+ const pcs = _chunkS3QELJUEcjs.assertArray.call(void 0, chordPcs, "chord pitch classes");
49
51
  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}]`);
52
+ const pc = _chunkS3QELJUEcjs.assertPitchClass.call(void 0, _nullishCoalesce(pcs[index], () => ( Number.NaN)), `chord pitch classes[${index}]`);
51
53
  if (!maskHasPitchClass(scaleMask, scaleRootPc, pc)) {
52
54
  return false;
53
55
  }
54
56
  }
55
57
  return true;
56
58
  }
57
- var ALIASED_SCALE_NAMES = /* @__PURE__ */ new Set(["major", "naturalMinor"]);
59
+ var ALIASED_SCALE_NAME_LIST = ["major", "naturalMinor"];
60
+ var ALIASED_SCALE_NAMES = new Set(ALIASED_SCALE_NAME_LIST);
58
61
  var HEPTATONIC_SIZE = 7;
59
62
  var SCALE_PREFERENCE = [
60
63
  "ionian",
@@ -90,19 +93,26 @@ function idiomaticRank(chord, name) {
90
93
  return index < 0 ? choices.length + 1 : index;
91
94
  }
92
95
  function isAlteredDominant(chord, scaleName) {
93
- return chord.quality === "dom7" && scaleName === "altered";
96
+ if (scaleName !== "altered" || !_chunkYDGMWH43cjs.soundsDominantSeventh.call(void 0, chord)) {
97
+ return false;
98
+ }
99
+ const mask = _chunkYDGMWH43cjs.namedScaleMask.call(void 0, scaleName);
100
+ const rootPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, chord.rootPc);
101
+ const fifthPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, rootPc + 7);
102
+ return mask !== void 0 && _chunkYDGMWH43cjs.chordPitchClasses.call(void 0, chord).every((pc) => pc === fifthPc || maskHasPitchClass(mask, rootPc, pc));
94
103
  }
95
104
  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);
105
+ const data = _chunkYDGMWH43cjs.toChordData.call(void 0, chord);
106
+ const chordPcs = _chunkYDGMWH43cjs.chordPitchClasses.call(void 0, data);
107
+ const rootPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, data.rootPc);
99
108
  const ranked = [];
109
+ const writesTension = chordPcs.some((pc) => ![0, 4, 7, 10].includes(_chunkS3QELJUEcjs.pitchClassOf.call(void 0, pc - rootPc)));
100
110
  const seenMasks = /* @__PURE__ */ new Set();
101
- for (const name of Object.keys(_chunk3R3QVKY5cjs.NAMED_SCALES)) {
111
+ for (const name of Object.keys(_chunkYDGMWH43cjs.NAMED_SCALES)) {
102
112
  if (name === "chromatic" || ALIASED_SCALE_NAMES.has(name)) {
103
113
  continue;
104
114
  }
105
- const mask = _chunk3R3QVKY5cjs.namedScaleMask.call(void 0, name);
115
+ const mask = _chunkYDGMWH43cjs.namedScaleMask.call(void 0, name);
106
116
  if (mask === void 0 || seenMasks.has(mask)) {
107
117
  continue;
108
118
  }
@@ -113,12 +123,15 @@ function chordScales(chord) {
113
123
  name,
114
124
  extra: size - chordPcs.length,
115
125
  size,
116
- avoid: avoidNotes(data, name).length
126
+ avoid: clashingNotes(data, mask, false).length,
127
+ // Eligible only through the fifth exemption: a scale that holds every
128
+ // written tone is the better answer for a chord that writes a tension.
129
+ borrowed: writesTension && !scaleMatchesChord(chordPcs, mask, rootPc)
117
130
  });
118
131
  }
119
132
  }
120
133
  if (ranked.length === 0) {
121
- if (_chunk3R3QVKY5cjs.NAMED_SCALES.chromatic !== void 0) {
134
+ if (_chunkYDGMWH43cjs.NAMED_SCALES.chromatic !== void 0) {
122
135
  return [{ name: "chromatic", rootPc }];
123
136
  }
124
137
  return [];
@@ -133,6 +146,9 @@ function chordScales(chord) {
133
146
  if (preferHeptatonic && a.size === HEPTATONIC_SIZE !== (b.size === HEPTATONIC_SIZE)) {
134
147
  return a.size === HEPTATONIC_SIZE ? -1 : 1;
135
148
  }
149
+ if (a.borrowed !== b.borrowed) {
150
+ return a.borrowed ? 1 : -1;
151
+ }
136
152
  if (a.extra !== b.extra) {
137
153
  return a.extra - b.extra;
138
154
  }
@@ -149,28 +165,34 @@ function chordScales(chord) {
149
165
  return ranked.map((entry) => ({ name: entry.name, rootPc }));
150
166
  }
151
167
  function avoidNotes(chord, scaleName, opts = {}) {
152
- const asked = _chunkS5BKZZGMcjs.assertOptions.call(void 0, opts, "opts");
168
+ const asked = _chunkS3QELJUEcjs.assertOptions.call(void 0, opts, "opts");
153
169
  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) {
170
+ const data = _chunkYDGMWH43cjs.toChordData.call(void 0, chord);
171
+ const use = _chunkS3QELJUEcjs.assertOneOf.call(void 0, _nullishCoalesce(asked.use, () => ( "harmonic")), ["harmonic", "melodic"], "avoid-note use");
172
+ if (isAlteredDominant(data, scaleName)) {
173
+ return [];
174
+ }
175
+ return clashingNotes(data, mask, use === "melodic");
176
+ }
177
+ function clashingNotes(data, mask, melodic) {
178
+ const rootPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, data.rootPc);
179
+ const chordPcs = _chunkYDGMWH43cjs.chordPitchClasses.call(void 0, data);
180
+ if (!scaleMatchesChord(chordPcs, mask, rootPc)) {
159
181
  return [];
160
182
  }
161
183
  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);
184
+ const displaced = new Set(_chunkYDGMWH43cjs.displacedThirds.call(void 0, data));
185
+ const semitoneAboveRoot = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, rootPc + 1);
186
+ const dominantNinth = _chunkYDGMWH43cjs.soundsDominantSeventh.call(void 0, data) ? semitoneAboveRoot : void 0;
165
187
  const avoid = [];
166
188
  for (let pc = 0; pc < 12; pc += 1) {
167
- if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {
189
+ if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc) || pc === dominantNinth) {
168
190
  continue;
169
191
  }
170
192
  if (melodic && pc !== semitoneAboveRoot) {
171
193
  continue;
172
194
  }
173
- if (!alteredDominant && (chordSet.has(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, pc - 1)) || displaced.has(pc))) {
195
+ if (chordSet.has(_chunkS3QELJUEcjs.pitchClassOf.call(void 0, pc - 1)) || displaced.has(pc)) {
174
196
  avoid.push(pc);
175
197
  }
176
198
  }
@@ -181,23 +203,23 @@ function resolvesToMinorTonic(chord, chordPcs, target) {
181
203
  if (target === void 0) {
182
204
  return false;
183
205
  }
184
- const rootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, chord.rootPc);
185
- const sounds = (semitones) => chordPcs.includes(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + semitones));
206
+ const rootPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, chord.rootPc);
207
+ const sounds = (semitones) => chordPcs.includes(_chunkS3QELJUEcjs.pitchClassOf.call(void 0, rootPc + semitones));
186
208
  if (!sounds(4) || !sounds(10)) {
187
209
  return false;
188
210
  }
189
- const targetRootPc = _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, target.rootPc);
190
- if (targetRootPc !== _chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + 5)) {
211
+ const targetRootPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, target.rootPc);
212
+ if (targetRootPc !== _chunkS3QELJUEcjs.pitchClassOf.call(void 0, rootPc + 5)) {
191
213
  return false;
192
214
  }
193
- return _chunk3R3QVKY5cjs.chordPitchClasses.call(void 0, target).includes(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, targetRootPc + 3));
215
+ return _chunkYDGMWH43cjs.chordPitchClasses.call(void 0, target).includes(_chunkS3QELJUEcjs.pitchClassOf.call(void 0, targetRootPc + 3));
194
216
  }
195
217
  function availableTensions(chord, scaleName, opts = {}) {
196
- const asked = _chunkS5BKZZGMcjs.assertOptions.call(void 0, opts, "opts");
218
+ const asked = _chunkS3QELJUEcjs.assertOptions.call(void 0, opts, "opts");
197
219
  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);
220
+ const data = _chunkYDGMWH43cjs.toChordData.call(void 0, chord);
221
+ const rootPc = _chunkS3QELJUEcjs.pitchClassOf.call(void 0, data.rootPc);
222
+ const chordPcs = _chunkYDGMWH43cjs.chordPitchClasses.call(void 0, data);
201
223
  const alteredDominant = isAlteredDominant(data, scaleName);
202
224
  if (!scaleMatchesChord(chordPcs, mask, rootPc) && !alteredDominant) {
203
225
  return [];
@@ -207,8 +229,8 @@ function availableTensions(chord, scaleName, opts = {}) {
207
229
  const functional = resolvesToMinorTonic(
208
230
  data,
209
231
  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;
232
+ asked.resolvesTo === void 0 ? void 0 : _chunkYDGMWH43cjs.toChordData.call(void 0, asked.resolvesTo)
233
+ ) ? new Set(MINOR_RESOLUTION_TENSIONS.map((semitones) => _chunkS3QELJUEcjs.pitchClassOf.call(void 0, rootPc + semitones))) : void 0;
212
234
  const tensions = [];
213
235
  for (let pc = 0; pc < 12; pc += 1) {
214
236
  if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {
@@ -223,9 +245,9 @@ function availableTensions(chord, scaleName, opts = {}) {
223
245
  }
224
246
  function chordScaleReport(chord, limit) {
225
247
  if (limit !== void 0) {
226
- _chunkS5BKZZGMcjs.assertPositiveInt.call(void 0, limit, "chord-scale report limit");
248
+ _chunkS3QELJUEcjs.assertPositiveInt.call(void 0, limit, "chord-scale report limit");
227
249
  }
228
- const data = _chunk3R3QVKY5cjs.toChordData.call(void 0, chord);
250
+ const data = _chunkYDGMWH43cjs.toChordData.call(void 0, chord);
229
251
  const matches = chordScales(data);
230
252
  const chosen = limit === void 0 ? matches : matches.slice(0, limit);
231
253
  return chosen.map((match) => {
@@ -242,14 +264,14 @@ function chordScaleReport(chord, limit) {
242
264
  }
243
265
  var RANK_PENALTY = 0.01;
244
266
  function scalePitchClassSet(name, rootPc) {
245
- const mask = _chunk3R3QVKY5cjs.namedScaleMask.call(void 0, name);
267
+ const mask = _chunkYDGMWH43cjs.namedScaleMask.call(void 0, name);
246
268
  const pcs = /* @__PURE__ */ new Set();
247
269
  if (mask === void 0) {
248
270
  return pcs;
249
271
  }
250
272
  for (let n = 0; n < 12; n += 1) {
251
273
  if ((mask >> n & 1) === 1) {
252
- pcs.add(_chunkS5BKZZGMcjs.pitchClassOf.call(void 0, rootPc + n));
274
+ pcs.add(_chunkS3QELJUEcjs.pitchClassOf.call(void 0, rootPc + n));
253
275
  }
254
276
  }
255
277
  return pcs;
@@ -269,8 +291,8 @@ function symmetricDifferenceSize(a, b) {
269
291
  return count;
270
292
  }
271
293
  function scalesForChanges(chords) {
272
- _chunkS5BKZZGMcjs.assertArray.call(void 0, chords, "chord-scale changes");
273
- _chunkS5BKZZGMcjs.assertGenerationBudget.call(void 0, chords.length, "chord-scale changes");
294
+ _chunkS3QELJUEcjs.assertArray.call(void 0, chords, "chord-scale changes");
295
+ _chunkS3QELJUEcjs.assertGenerationBudget.call(void 0, chords.length, "chord-scale changes");
274
296
  if (chords.length === 0) {
275
297
  return [];
276
298
  }
@@ -330,12 +352,12 @@ function scalesForChanges(chords) {
330
352
 
331
353
  // src/theory/harmony/index.ts
332
354
  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);
355
+ _chunkS3QELJUEcjs.assertFiniteNumber.call(void 0, chordId, "chordId");
356
+ const data = _chunkYDGMWH43cjs.toChordData.call(void 0, chord);
357
+ const interval = (_chunkS3QELJUEcjs.pitchClassOf.call(void 0, pitch) - _chunkS3QELJUEcjs.pitchClassOf.call(void 0, data.rootPc) + 12) % 12;
358
+ const slot = _chunkYDGMWH43cjs.thirdSlotOf.call(void 0, data);
337
359
  const isSuspendedTone = slot.kind === "suspension" && interval === slot.interval;
338
- const chordRole = _chunk3R3QVKY5cjs.chordToneRole.call(void 0, pitch, data);
360
+ const chordRole = _chunkYDGMWH43cjs.chordToneRole.call(void 0, pitch, data);
339
361
  let role;
340
362
  let lock;
341
363
  if (isSuspendedTone) {
@@ -360,4 +382,4 @@ function roleOf(pitch, chord, chordId = 0) {
360
382
 
361
383
 
362
384
  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
385
+ //# sourceMappingURL=chunk-P3CPXAJ5.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/libcantus/libcantus/ts/dist/chunk-P3CPXAJ5.cjs","../src/theory/chordscale/index.ts","../src/theory/harmony/index.ts"],"names":[],"mappings":"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","file":"/home/runner/work/libcantus/libcantus/ts/dist/chunk-P3CPXAJ5.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 assertOneOf,\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';\nimport { soundsDominantSeventh } from '../tendency/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 */\nexport const ALIASED_SCALE_NAME_LIST: readonly string[] = ['major', 'naturalMinor'];\n\nconst ALIASED_SCALE_NAMES = new Set(ALIASED_SCALE_NAME_LIST);\n\n/** Number of tones in a heptatonic (seven-note) scale. */\nexport const 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 */\nexport const 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. */\nexport const 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 * A dominant seventh may use altered colors while retaining its perfect fifth\n * in the voicing. It is read from the tones, as every dominant is: a major\n * third with a minor seventh whose only tones outside the altered scale are the\n * fifth, so `7`, `7alt`, `7b9`, `7#9` and `7b13` all take it while `9` and `13`\n * do not. Lead sheets commonly write the shorter `7` here.\n */\nfunction isAlteredDominant(chord: Chord, scaleName: string): boolean {\n if (scaleName !== 'altered' || !soundsDominantSeventh(chord)) {\n return false;\n }\n const mask = namedScaleMask(scaleName);\n const rootPc = pitchClass(chord.rootPc);\n const fifthPc = pitchClass(rootPc + 7);\n return (\n mask !== undefined &&\n chordPitchClasses(chord).every((pc) => pc === fifthPc || maskHasPitchClass(mask, rootPc, pc))\n );\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: {\n name: string;\n extra: number;\n size: number;\n avoid: number;\n borrowed: boolean;\n }[] = [];\n // A tone beyond the plain seventh chord is a written alteration or extension.\n const writesTension = chordPcs.some((pc) => ![0, 4, 7, 10].includes(pitchClass(pc - rootPc)));\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: clashingNotes(data, mask, false).length,\n // Eligible only through the fifth exemption: a scale that holds every\n // written tone is the better answer for a chord that writes a tension.\n borrowed: writesTension && !scaleMatchesChord(chordPcs, mask, rootPc),\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.borrowed !== b.borrowed) {\n return a.borrowed ? 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 — 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. Over a chord that sounds a dominant seventh\n * the semitone above the root is the flat ninth, a tension under either use\n * whichever scale supplies it; the flat thirteenth stays a harmonic avoid note.\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 use = assertOneOf(asked.use ?? 'harmonic', ['harmonic', 'melodic'], 'avoid-note use');\n if (isAlteredDominant(data, scaleName)) {\n return [];\n }\n return clashingNotes(data, mask, use === 'melodic');\n}\n\n/**\n * The scale tones that clash with the chord by the avoid-note rule, whatever\n * function the chord serves: {@link avoidNotes} before the altered dominant's\n * exemption. Empty when the scale does not contain the chord.\n */\nfunction clashingNotes(data: Chord, mask: number, melodic: boolean): number[] {\n const rootPc = pitchClass(data.rootPc);\n const chordPcs = chordPitchClasses(data);\n if (!scaleMatchesChord(chordPcs, mask, rootPc)) {\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 semitoneAboveRoot = pitchClass(rootPc + 1);\n // The flat ninth is a dominant's own tension, whichever scale supplies it.\n const dominantNinth = soundsDominantSeventh(data) ? semitoneAboveRoot : undefined;\n const avoid: number[] = [];\n for (let pc = 0; pc < 12; pc += 1) {\n if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc) || pc === dominantNinth) {\n continue;\n }\n if (melodic && pc !== semitoneAboveRoot) {\n continue;\n }\n if (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, the flat ninth is already a tension and the\n * others sit a semitone above a chord tone. Heard as the dominant of a minor key\n * they are the key's own tones, and standard practice, so the function the\n * chord serves is what decides.\n */\nexport const 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 sharp ninth and flat\n * thirteenth as well as the flat ninth every dominant takes. 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 b9, and the b13 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 */\nexport const 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"]}
@@ -169,29 +169,52 @@ function describesMap(index, map) {
169
169
  }
170
170
  return true;
171
171
  }
172
- function buildMeterIndex(map, validated) {
173
- const startBeats = new Array(map.length);
174
- const signatures = new Array(map.length);
175
- const barAnchors = new Array(map.length);
176
- const barBeats = new Array(map.length);
177
- const barsBefore = new Array(map.length);
172
+ function meterSegments(map) {
173
+ const segments = new Array(map.length);
178
174
  let bars = 0;
175
+ let atZero = 0;
179
176
  for (let i = 0; i < map.length; i += 1) {
180
177
  const entry = map[i];
181
178
  const startBeat = _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _ => _.startBeat]), () => ( 0));
182
179
  const barLen = entry === void 0 ? 0 : barBeatsOf(entry.ts);
183
- const anchor = i === 0 ? 0 : startBeat;
184
- startBeats[i] = startBeat;
185
- signatures[i] = entry === void 0 ? { numerator: 4, denominator: 4 } : copyTimeSignature(entry.ts);
186
- barAnchors[i] = anchor;
187
- barBeats[i] = barLen;
188
- barsBefore[i] = bars;
180
+ const barAnchor = i === 0 ? 0 : startBeat;
181
+ segments[i] = {
182
+ startBeat,
183
+ ts: entry === void 0 ? { numerator: 4, denominator: 4 } : copyTimeSignature(entry.ts),
184
+ barAnchor,
185
+ barBeats: barLen,
186
+ barsBefore: bars
187
+ };
188
+ if (i > 0 && startBeat <= BEAT_EPS) {
189
+ atZero = i;
190
+ }
189
191
  const next = map[i + 1];
190
192
  if (next !== void 0 && barLen > 0) {
191
- bars += Math.max(1, Math.ceil((next.startBeat - anchor) / barLen - BEAT_EPS));
193
+ const span = Math.ceil((next.startBeat - barAnchor) / barLen - BEAT_EPS);
194
+ bars += i === 0 ? span : Math.max(1, span);
192
195
  }
193
196
  }
194
- const index = { startBeats, signatures, barAnchors, barBeats, barsBefore, validated };
197
+ const zero = segments[atZero];
198
+ if (atZero > 0 && zero !== void 0 && zero.barBeats > 0) {
199
+ const shift = zero.barsBefore + Math.floor(-zero.barAnchor / zero.barBeats + BEAT_EPS);
200
+ if (shift !== 0) {
201
+ for (const segment of segments) {
202
+ segment.barsBefore -= shift;
203
+ }
204
+ }
205
+ }
206
+ return segments;
207
+ }
208
+ function buildMeterIndex(map, validated) {
209
+ const segments = meterSegments(map);
210
+ const index = {
211
+ startBeats: segments.map((segment) => segment.startBeat),
212
+ signatures: segments.map((segment) => segment.ts),
213
+ barAnchors: segments.map((segment) => segment.barAnchor),
214
+ barBeats: segments.map((segment) => segment.barBeats),
215
+ barsBefore: segments.map((segment) => segment.barsBefore),
216
+ validated
217
+ };
195
218
  INDEX_CACHE.set(map, index);
196
219
  return rememberRead(map, index);
197
220
  }
@@ -285,9 +308,16 @@ function describeRejected(value) {
285
308
  }
286
309
  return value.length <= MAX_ECHOED_LENGTH ? JSON.stringify(value) : `${JSON.stringify(value.slice(0, MAX_ECHOED_LENGTH))} (truncated from ${value.length} characters)`;
287
310
  }
311
+ function receivedText(value) {
312
+ try {
313
+ return `${value}`;
314
+ } catch (e) {
315
+ return describeRejected(value);
316
+ }
317
+ }
288
318
  function assertFiniteNumber(value, name) {
289
319
  if (!Number.isFinite(value)) {
290
- throw new InvalidInputError(`${name} must be finite; received ${value}`);
320
+ throw new InvalidInputError(`${name} must be finite; received ${receivedText(value)}`);
291
321
  }
292
322
  return value;
293
323
  }
@@ -433,7 +463,7 @@ function assertTimeSignature(ts, name = "time signature") {
433
463
  }
434
464
  function assertMeterMap(meters, name = "meters") {
435
465
  if (!Array.isArray(meters)) {
436
- throw new InvalidInputError(`${name} must be an array; received ${typeof meters}`);
466
+ throw new InvalidInputError(`${name} must be an array; received ${describeRejected(meters)}`);
437
467
  }
438
468
  if (meters.length === 0) {
439
469
  throw new InvalidInputError(`${name} must not be empty`);
@@ -496,7 +526,7 @@ function assertNoteEvent(event, name = "note event", options = {}) {
496
526
  function assertNoteEvents(events, name = "note events", options = {}) {
497
527
  const asked = assertOptions(options, `${name} options`);
498
528
  if (!Array.isArray(events)) {
499
- throw new InvalidInputError(`${name} must be an array; received ${typeof events}`);
529
+ throw new InvalidInputError(`${name} must be an array; received ${describeRejected(events)}`);
500
530
  }
501
531
  assertGenerationBudget(events.length, `${name} count`, asked.budget);
502
532
  for (let index = 0; index < events.length; index += 1) {
@@ -592,7 +622,7 @@ function parseEnglish(text) {
592
622
  }
593
623
  const note = { letter, alter };
594
624
  if (match[3] !== void 0) {
595
- note.octave = Number.parseInt(match[3], 10);
625
+ note.octave = octaveOf(match[3]);
596
626
  }
597
627
  return note;
598
628
  }
@@ -733,7 +763,11 @@ function splitOctave(text) {
733
763
  return { name: text, octave: void 0 };
734
764
  }
735
765
  const signed = start > 0 && text.charAt(start - 1) === "-" ? start - 1 : start;
736
- return { name: text.slice(0, signed), octave: Number.parseInt(text.slice(signed), 10) };
766
+ return { name: text.slice(0, signed), octave: octaveOf(text.slice(signed)) };
767
+ }
768
+ function octaveOf(digits) {
769
+ const octave = Number.parseInt(digits, 10);
770
+ return octave === 0 ? 0 : octave;
737
771
  }
738
772
  function parseIn(text, system) {
739
773
  const table = tableOf(system);
@@ -999,12 +1033,16 @@ function transposeNote(note, semitones, opts) {
999
1033
  const octaves = Math.floor(magnitude / 12);
1000
1034
  const withinOctave = magnitude % 12;
1001
1035
  const letterSteps = direction * ((_nullishCoalesce(LETTER_STEPS_BY_SEMITONE[withinOctave], () => ( 0))) + 7 * octaves);
1002
- const absoluteLetter = mod7(note.letter) + letterSteps;
1036
+ return landOnLetter(note, mod7(note.letter) + letterSteps, steps);
1037
+ }
1038
+ function landOnLetter(note, absoluteLetter, steps) {
1003
1039
  const letter = mod7(absoluteLetter);
1004
1040
  const natural = _nullishCoalesce(LETTER_SEMITONES[letter], () => ( 0));
1005
1041
  if (note.octave === void 0) {
1042
+ const source = _nullishCoalesce(LETTER_SEMITONES[mod7(note.letter)], () => ( 0));
1043
+ const wrapped = 12 * Math.floor(absoluteLetter / 7);
1006
1044
  return assertNote(
1007
- { letter, alter: alterFor(natural, mod12(noteToPitchClass(note) + steps)) },
1045
+ { letter, alter: note.alter + source + steps - wrapped - natural },
1008
1046
  "transposed note"
1009
1047
  );
1010
1048
  }
@@ -1017,10 +1055,6 @@ function transposeNote(note, semitones, opts) {
1017
1055
  function bareOf(note) {
1018
1056
  return { letter: note.letter, alter: note.alter };
1019
1057
  }
1020
- function alterFor(natural, pc) {
1021
- const d = mod12(pc - natural);
1022
- return d > 6 ? d - 12 : d;
1023
- }
1024
1058
  var SIMPLE_REFERENCE = [0, 0, 2, 4, 5, 7, 9, 11];
1025
1059
  function isPerfectNumber(simpleNumber) {
1026
1060
  return simpleNumber === 1 || simpleNumber === 4 || simpleNumber === 5;
@@ -1030,7 +1064,7 @@ function qualityFromSpan(numberValue, semitones) {
1030
1064
  const simple = numberValue - 7 * octaves;
1031
1065
  const reference = (_nullishCoalesce(SIMPLE_REFERENCE[simple], () => ( 0))) + 12 * octaves;
1032
1066
  const delta = semitones - reference;
1033
- const repeat = (glyph, count) => `${glyph}${glyph.repeat(Math.min(count, MAX_ALTER * 2) - 1)}`;
1067
+ const repeat = (glyph, count) => `${glyph}${glyph.repeat(Math.min(count, MAX_ALTER * 2 + 1) - 1)}`;
1034
1068
  if (isPerfectNumber(simple)) {
1035
1069
  if (delta === 0) {
1036
1070
  return "P";
@@ -1170,21 +1204,7 @@ function transposeByInterval(given, named) {
1170
1204
  assertInteger(interval.number, "interval.number", 1, MAX_INTERVAL_NUMBER);
1171
1205
  assertFiniteNumber(interval.semitones, "interval.semitones");
1172
1206
  const letterSteps = (interval.number - 1) * (isDescendingInterval(interval) ? -1 : 1);
1173
- const absoluteLetter = mod7(note.letter) + letterSteps;
1174
- const letter = mod7(absoluteLetter);
1175
- const natural = _nullishCoalesce(LETTER_SEMITONES[letter], () => ( 0));
1176
- const steps = Math.round(interval.semitones);
1177
- if (note.octave === void 0) {
1178
- return assertNote(
1179
- { letter, alter: alterFor(natural, mod12(noteToPitchClass(note) + steps)) },
1180
- "transposed note"
1181
- );
1182
- }
1183
- const octave = note.octave + Math.floor(absoluteLetter / 7);
1184
- return assertNote(
1185
- { letter, alter: noteToMidi(note) + steps - ((octave + 1) * 12 + natural), octave },
1186
- "transposed note"
1187
- );
1207
+ return landOnLetter(note, mod7(note.letter) + letterSteps, Math.round(interval.semitones));
1188
1208
  }
1189
1209
  function diatonicIndex(note) {
1190
1210
  return mod7(note.letter) + 7 * (_nullishCoalesce(note.octave, () => ( 0)));
@@ -1204,15 +1224,11 @@ function spelledInterval(a, b) {
1204
1224
  letterSteps = diatonicIndex(b) - diatonicIndex(a);
1205
1225
  semitones = noteToMidi(b) - noteToMidi(a);
1206
1226
  } else {
1207
- letterSteps = mod7(b.letter - a.letter);
1208
- let rawSemis = mod12(noteToPitchClass(b) - noteToPitchClass(a));
1209
- const reference = _nullishCoalesce(SIMPLE_REFERENCE[letterSteps + 1], () => ( 0));
1210
- if (reference - rawSemis > 6) {
1211
- rawSemis += 12;
1212
- } else if (rawSemis - reference > 6) {
1213
- rawSemis -= 12;
1214
- }
1215
- semitones = rawSemis;
1227
+ const fromLetter = mod7(a.letter);
1228
+ const toLetter = mod7(b.letter);
1229
+ letterSteps = mod7(toLetter - fromLetter);
1230
+ const wrapped = toLetter < fromLetter ? 12 : 0;
1231
+ semitones = (_nullishCoalesce(LETTER_SEMITONES[toLetter], () => ( 0))) + wrapped - (_nullishCoalesce(LETTER_SEMITONES[fromLetter], () => ( 0))) + b.alter - a.alter;
1216
1232
  }
1217
1233
  const absSteps = Math.abs(letterSteps);
1218
1234
  const number = absSteps + 1;
@@ -1519,17 +1535,17 @@ function metricGridUnit(meter) {
1519
1535
  if (!isMeterMap(resolved)) {
1520
1536
  return pulseBeatsOf(resolved);
1521
1537
  }
1538
+ const segments = meterSegments(resolved);
1522
1539
  let unit = 0;
1523
- for (const change of resolved) {
1524
- unit = commonStep(unit, pulseBeatsOf(change.ts));
1540
+ for (const segment of segments) {
1541
+ unit = commonStep(unit, pulseBeatsOf(segment.ts));
1525
1542
  }
1526
1543
  if (unit <= 0) {
1527
1544
  return pulseBeatsOf(DEFAULT_TS);
1528
1545
  }
1529
- const origin = _nullishCoalesce(_optionalChain([resolved, 'access', _8 => _8[0], 'optionalAccess', _9 => _9.startBeat]), () => ( 0));
1530
1546
  let onChanges = unit;
1531
- for (const change of resolved) {
1532
- onChanges = commonStep(onChanges, Math.abs(change.startBeat - origin));
1547
+ for (const segment of segments) {
1548
+ onChanges = commonStep(onChanges, Math.abs(segment.barAnchor));
1533
1549
  }
1534
1550
  return onChanges * MAX_CHANGE_DIVISIONS >= unit - BEAT_EPS ? onChanges : unit;
1535
1551
  }
@@ -1637,4 +1653,4 @@ function tuplet(totalBeats, count) {
1637
1653
 
1638
1654
 
1639
1655
  exports.parseFailure = parseFailure; exports.unwrapParse = unwrapParse; exports.InvalidInputError = InvalidInputError; exports.NoSolutionError = NoSolutionError; exports.BudgetExceededError = BudgetExceededError; exports.isLibcantusError = isLibcantusError; exports.ARTICULATIONS = ARTICULATIONS; exports.BEAT_EPS = BEAT_EPS; exports.DEFAULT_GENERATION_BUDGET = DEFAULT_GENERATION_BUDGET; exports.describeRejected = describeRejected; exports.assertFiniteNumber = assertFiniteNumber; exports.assertInteger = assertInteger; exports.assertMidiPitch = assertMidiPitch; exports.assertPitchClass = assertPitchClass; exports.clampToMidi = clampToMidi; exports.assertDegree = assertDegree; exports.assertFiniteSemitones = assertFiniteSemitones; exports.dropSilentNotes = dropSilentNotes; exports.soundingNotesOnly = soundingNotesOnly; exports.assertArray = assertArray; exports.assertRecord = assertRecord; exports.assertOptions = assertOptions; exports.assertFlag = assertFlag; exports.assertFunction = assertFunction; exports.assertOneOf = assertOneOf; exports.assertPositiveInt = assertPositiveInt; exports.assertRange = assertRange; exports.assertGenerationBudget = assertGenerationBudget; exports.allocateCandidateTable = allocateCandidateTable; exports.allocateChoiceTable = allocateChoiceTable; exports.assertTimeSignature = assertTimeSignature; exports.assertMeterMap = assertMeterMap; exports.assertNoteEvent = assertNoteEvent; exports.assertNoteEvents = assertNoteEvents; exports.MAX_NAME_ACCIDENTALS = MAX_NAME_ACCIDENTALS; exports.maxNoteNameLength = maxNoteNameLength; exports.detectNoteNameSystem = detectNoteNameSystem; exports.pitchClassOf = pitchClassOf; exports.diatonicLetterOf = diatonicLetterOf; exports.naturalPitchClassOf = naturalPitchClassOf; exports.parseNote = parseNote; exports.tryParseNote = tryParseNote; exports.formatNote = formatNote; exports.parseKeyName = parseKeyName; exports.tryParseKeyName = tryParseKeyName; exports.formatKeyName = formatKeyName; exports.noteToPitchClass = noteToPitchClass; exports.noteToMidi = noteToMidi; exports.midiToNote = midiToNote; exports.transposeNote = transposeNote; exports.intervalSemitones = intervalSemitones; exports.parseInterval = parseInterval; exports.tryParseInterval = tryParseInterval; exports.toSpelledInterval = toSpelledInterval; exports.toNoteData = toNoteData; exports.transposeByInterval = transposeByInterval; exports.spelledInterval = spelledInterval; exports.ConsonanceClass = ConsonanceClass; exports.classifyInterval = classifyInterval; exports.isPerfectInterval = isPerfectInterval; exports.isConsonantInterval = isConsonantInterval; exports.toMeterData = toMeterData; exports.parseTimeSignature = parseTimeSignature; exports.tryParseTimeSignature = tryParseTimeSignature; exports.formatTimeSignature = formatTimeSignature; exports.isCompound = isCompound; exports.beatsPerBar = beatsPerBar; exports.meterAt = meterAt; exports.barStartBeat = barStartBeat; exports.barIndexAt = barIndexAt; exports.beatsPerBarAt = beatsPerBarAt; exports.resolveMeters = resolveMeters; exports.pulsesPerBar = pulsesPerBar; exports.beatToBarPosition = beatToBarPosition; exports.pulseBeats = pulseBeats; exports.barPositionToPulse = barPositionToPulse; exports.formatBarPosition = formatBarPosition; exports.barPositionToBeat = barPositionToBeat; exports.metricWeight = metricWeight; exports.metricGridUnit = metricGridUnit; exports.isStrongBeat = isStrongBeat; exports.tuplet = tuplet;
1640
- //# sourceMappingURL=chunk-S5BKZZGM.cjs.map
1656
+ //# sourceMappingURL=chunk-S3QELJUE.cjs.map