@libraz/libcantus 0.9.2 → 0.9.4

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 (200) hide show
  1. package/README.md +6 -5
  2. package/dist/analyze/index.cjs +41 -1676
  3. package/dist/analyze/index.cjs.map +1 -1
  4. package/dist/analyze/index.d.cts +194 -122
  5. package/dist/analyze/index.d.ts +194 -122
  6. package/dist/analyze/index.js +19 -8
  7. package/dist/chunk-36N73KZ3.cjs +246 -0
  8. package/dist/chunk-36N73KZ3.cjs.map +1 -0
  9. package/dist/chunk-4HLLZPXT.cjs +3077 -0
  10. package/dist/chunk-4HLLZPXT.cjs.map +1 -0
  11. package/dist/chunk-7MGZ7D62.cjs +498 -0
  12. package/dist/chunk-7MGZ7D62.cjs.map +1 -0
  13. package/dist/{chunk-R3S2LUBH.js → chunk-7NKDPF74.js} +660 -305
  14. package/dist/chunk-7NKDPF74.js.map +1 -0
  15. package/dist/chunk-CAN76NCU.cjs +679 -0
  16. package/dist/chunk-CAN76NCU.cjs.map +1 -0
  17. package/dist/{chunk-7Y7WF64D.js → chunk-D2FAJBYL.js} +104 -35
  18. package/dist/chunk-D2FAJBYL.js.map +1 -0
  19. package/dist/{chunk-COKTX2G5.js → chunk-EHVEBWM5.js} +1052 -510
  20. package/dist/chunk-EHVEBWM5.js.map +1 -0
  21. package/dist/chunk-FCANXBAT.cjs +30 -0
  22. package/dist/chunk-FCANXBAT.cjs.map +1 -0
  23. package/dist/chunk-FNDWXRRI.cjs +479 -0
  24. package/dist/chunk-FNDWXRRI.cjs.map +1 -0
  25. package/dist/{chunk-GQKN5KDT.js → chunk-GQSGS2N4.js} +43 -29
  26. package/dist/chunk-GQSGS2N4.js.map +1 -0
  27. package/dist/chunk-HKGYCQ34.js +53 -0
  28. package/dist/chunk-HKGYCQ34.js.map +1 -0
  29. package/dist/chunk-I24MV65U.js +106 -0
  30. package/dist/chunk-I24MV65U.js.map +1 -0
  31. package/dist/{chunk-LN7ZZMD2.js → chunk-KMHOICIY.js} +322 -173
  32. package/dist/chunk-KMHOICIY.js.map +1 -0
  33. package/dist/chunk-LW53AHQU.cjs +1117 -0
  34. package/dist/chunk-LW53AHQU.cjs.map +1 -0
  35. package/dist/chunk-N6IHQUOX.js +1 -0
  36. package/dist/chunk-N6IHQUOX.js.map +1 -0
  37. package/dist/chunk-NKIBQ6PT.js +30 -0
  38. package/dist/chunk-NKIBQ6PT.js.map +1 -0
  39. package/dist/chunk-NP4NA2FB.cjs +106 -0
  40. package/dist/chunk-NP4NA2FB.cjs.map +1 -0
  41. package/dist/chunk-NVE34YGZ.cjs +1449 -0
  42. package/dist/chunk-NVE34YGZ.cjs.map +1 -0
  43. package/dist/{chunk-A4532ZFR.js → chunk-NYYWMV2C.js} +115 -47
  44. package/dist/chunk-NYYWMV2C.js.map +1 -0
  45. package/dist/{chunk-5HTNMQW4.js → chunk-Q2XUP227.js} +310 -118
  46. package/dist/chunk-Q2XUP227.js.map +1 -0
  47. package/dist/chunk-Q6OP4U43.cjs +327 -0
  48. package/dist/chunk-Q6OP4U43.cjs.map +1 -0
  49. package/dist/chunk-RC6GBMCD.cjs +845 -0
  50. package/dist/chunk-RC6GBMCD.cjs.map +1 -0
  51. package/dist/{chunk-XTC3X6MS.js → chunk-RK35RIN7.js} +453 -152
  52. package/dist/chunk-RK35RIN7.js.map +1 -0
  53. package/dist/chunk-RUMU3UA6.cjs +53 -0
  54. package/dist/chunk-RUMU3UA6.cjs.map +1 -0
  55. package/dist/chunk-T64C7ZD7.cjs +1 -0
  56. package/dist/chunk-T64C7ZD7.cjs.map +1 -0
  57. package/dist/chunk-XEBG3G53.js +498 -0
  58. package/dist/chunk-XEBG3G53.js.map +1 -0
  59. package/dist/chunk-YLEMGEFH.js +246 -0
  60. package/dist/chunk-YLEMGEFH.js.map +1 -0
  61. package/dist/chunk-ZEJR4TKL.cjs +173 -0
  62. package/dist/chunk-ZEJR4TKL.cjs.map +1 -0
  63. package/dist/core/index.cjs +130 -431
  64. package/dist/core/index.cjs.map +1 -1
  65. package/dist/core/index.d.cts +331 -17
  66. package/dist/core/index.d.ts +331 -17
  67. package/dist/core/index.js +71 -13
  68. package/dist/{function-2bJW1Zp_.d.ts → function-BtiZb9i9.d.ts} +28 -7
  69. package/dist/{function-r2sh-jOO.d.cts → function-DNugAOrt.d.cts} +28 -7
  70. package/dist/generate/index.cjs +30 -3751
  71. package/dist/generate/index.cjs.map +1 -1
  72. package/dist/generate/index.d.cts +373 -59
  73. package/dist/generate/index.d.ts +373 -59
  74. package/dist/generate/index.js +23 -9
  75. package/dist/{index-DZ1M21do.d.cts → index-6VR8-kit.d.ts} +20 -4
  76. package/dist/index-70p168VM.d.ts +192 -0
  77. package/dist/{index-D_ZTUNKp.d.cts → index-Be74mcon.d.cts} +18 -17
  78. package/dist/index-BtXT6UQ0.d.cts +192 -0
  79. package/dist/{index-BMPxwjwV.d.ts → index-C5UBbQ4G.d.ts} +18 -17
  80. package/dist/{index-BOBXBNwP.d.cts → index-C83mZI1P.d.ts} +93 -8
  81. package/dist/{index-BdeQ1r_p.d.cts → index-D6b6na69.d.cts} +14 -11
  82. package/dist/{index-Cl7mhOFM.d.cts → index-DXd9JikN.d.cts} +92 -10
  83. package/dist/{index-Cl7mhOFM.d.ts → index-DXd9JikN.d.ts} +92 -10
  84. package/dist/index-OG65ocOr.d.cts +272 -0
  85. package/dist/index-OG65ocOr.d.ts +272 -0
  86. package/dist/{index-BreoJRw0.d.ts → index-tJhkmQgE.d.cts} +20 -4
  87. package/dist/{index-CP3wAfEH.d.ts → index-tSQh-xwY.d.ts} +14 -11
  88. package/dist/{index-CM5W4rcm.d.ts → index-y_ak9_Hi.d.cts} +93 -8
  89. package/dist/index.cjs +419 -6848
  90. package/dist/index.cjs.map +1 -1
  91. package/dist/index.d.cts +14 -13
  92. package/dist/index.d.ts +14 -13
  93. package/dist/index.js +132 -27
  94. package/dist/model/index.cjs +8 -2423
  95. package/dist/model/index.cjs.map +1 -1
  96. package/dist/model/index.d.cts +433 -74
  97. package/dist/model/index.d.ts +433 -74
  98. package/dist/model/index.js +6 -7
  99. package/dist/styled-DIRkk9Uz.d.ts +506 -0
  100. package/dist/styled-DJbkJQfj.d.cts +506 -0
  101. package/dist/theory/index.cjs +172 -1676
  102. package/dist/theory/index.cjs.map +1 -1
  103. package/dist/theory/index.d.cts +151 -233
  104. package/dist/theory/index.d.ts +151 -233
  105. package/dist/theory/index.js +31 -7
  106. package/dist/{types-MGP29r3t.d.cts → types-BN6_Q9Kl.d.cts} +11 -2
  107. package/dist/{types-MGP29r3t.d.ts → types-BN6_Q9Kl.d.ts} +11 -2
  108. package/package.json +73 -24
  109. package/dist/chunk-5HTNMQW4.js.map +0 -1
  110. package/dist/chunk-7Y7WF64D.js.map +0 -1
  111. package/dist/chunk-A4532ZFR.js.map +0 -1
  112. package/dist/chunk-BHUT2S5G.js +0 -22
  113. package/dist/chunk-BHUT2S5G.js.map +0 -1
  114. package/dist/chunk-CCBLVAPK.js +0 -42
  115. package/dist/chunk-CCBLVAPK.js.map +0 -1
  116. package/dist/chunk-COKTX2G5.js.map +0 -1
  117. package/dist/chunk-DYWFNC4A.js +0 -152
  118. package/dist/chunk-DYWFNC4A.js.map +0 -1
  119. package/dist/chunk-GQKN5KDT.js.map +0 -1
  120. package/dist/chunk-LN7ZZMD2.js.map +0 -1
  121. package/dist/chunk-MSWFZF7J.js +0 -118
  122. package/dist/chunk-MSWFZF7J.js.map +0 -1
  123. package/dist/chunk-R3S2LUBH.js.map +0 -1
  124. package/dist/chunk-SDM3VJJ5.js +0 -41
  125. package/dist/chunk-SDM3VJJ5.js.map +0 -1
  126. package/dist/chunk-XTC3X6MS.js.map +0 -1
  127. package/dist/chunk-ZXW5YIWK.js +0 -55
  128. package/dist/chunk-ZXW5YIWK.js.map +0 -1
  129. package/dist/index-CGMZNCx6.d.cts +0 -140
  130. package/dist/index-CGMZNCx6.d.ts +0 -140
  131. package/dist/styled-BjXtOFNk.d.cts +0 -282
  132. package/dist/styled-D7BAx3S3.d.ts +0 -282
  133. package/src/analyze/arrange/index.ts +0 -21
  134. package/src/analyze/arrange/internal.ts +0 -125
  135. package/src/analyze/arrange/tension.ts +0 -187
  136. package/src/analyze/arrange/tracks.ts +0 -279
  137. package/src/analyze/detect/index.ts +0 -235
  138. package/src/analyze/functional/borrowed.ts +0 -84
  139. package/src/analyze/functional/cadence.ts +0 -66
  140. package/src/analyze/functional/function.ts +0 -184
  141. package/src/analyze/functional/index.ts +0 -23
  142. package/src/analyze/functional/internal.ts +0 -29
  143. package/src/analyze/functional/roman.ts +0 -393
  144. package/src/analyze/index.ts +0 -49
  145. package/src/analyze/timeline/index.ts +0 -415
  146. package/src/analyze/voice/index.ts +0 -330
  147. package/src/core/index.ts +0 -47
  148. package/src/core/interval/index.ts +0 -81
  149. package/src/core/meter/index.ts +0 -282
  150. package/src/core/pitch/index.ts +0 -311
  151. package/src/core/random/index.ts +0 -53
  152. package/src/core/tuning/index.ts +0 -156
  153. package/src/core/types.ts +0 -29
  154. package/src/generate/bass/index.ts +0 -350
  155. package/src/generate/countermelody/index.ts +0 -379
  156. package/src/generate/drums/beat.ts +0 -266
  157. package/src/generate/drums/euclid.ts +0 -58
  158. package/src/generate/drums/fills.ts +0 -356
  159. package/src/generate/drums/ghost.ts +0 -119
  160. package/src/generate/drums/hihat.ts +0 -285
  161. package/src/generate/drums/hit.ts +0 -31
  162. package/src/generate/drums/index.ts +0 -329
  163. package/src/generate/drums/internal.ts +0 -257
  164. package/src/generate/drums/kick.ts +0 -160
  165. package/src/generate/drums/percussion.ts +0 -121
  166. package/src/generate/drums/rng.ts +0 -7
  167. package/src/generate/drums/swing.ts +0 -71
  168. package/src/generate/groove/index.ts +0 -326
  169. package/src/generate/harmonize/index.ts +0 -440
  170. package/src/generate/index.ts +0 -59
  171. package/src/generate/motif/index.ts +0 -398
  172. package/src/generate/progression/index.ts +0 -370
  173. package/src/generate/reharmony/index.ts +0 -330
  174. package/src/generate/rhythm/index.ts +0 -165
  175. package/src/index.ts +0 -247
  176. package/src/model/chord.ts +0 -423
  177. package/src/model/index.ts +0 -15
  178. package/src/model/interval.ts +0 -82
  179. package/src/model/key.ts +0 -266
  180. package/src/model/note.ts +0 -176
  181. package/src/model/progression.ts +0 -161
  182. package/src/model/shared.ts +0 -12
  183. package/src/theory/chord/index.ts +0 -373
  184. package/src/theory/chordscale/index.ts +0 -374
  185. package/src/theory/counterpoint/index.ts +0 -230
  186. package/src/theory/harmony/index.ts +0 -92
  187. package/src/theory/index.ts +0 -107
  188. package/src/theory/safety/index.ts +0 -419
  189. package/src/theory/scale/degrees.ts +0 -123
  190. package/src/theory/scale/index.ts +0 -28
  191. package/src/theory/scale/key.ts +0 -56
  192. package/src/theory/scale/masks.ts +0 -153
  193. package/src/theory/spelling/index.ts +0 -182
  194. package/src/theory/symbol/index.ts +0 -268
  195. package/src/theory/voicing/index.ts +0 -5
  196. package/src/theory/voicing/internal.ts +0 -168
  197. package/src/theory/voicing/leading.ts +0 -112
  198. package/src/theory/voicing/satb.ts +0 -195
  199. package/src/theory/voicing/styled.ts +0 -176
  200. package/tsconfig.json +0 -23
@@ -1,1697 +1,62 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
19
2
 
20
- // src/analyze/index.ts
21
- var analyze_exports = {};
22
- __export(analyze_exports, {
23
- analyzeArrangement: () => analyzeArrangement,
24
- analyzeChord: () => analyzeChord,
25
- analyzeVoice: () => analyzeVoice,
26
- borrowedSource: () => borrowedSource,
27
- chordTimelineFromChords: () => chordTimelineFromChords,
28
- chordTimelineFromNotes: () => chordTimelineFromNotes,
29
- chordToRoman: () => chordToRoman,
30
- detectCadence: () => detectCadence,
31
- detectCadences: () => detectCadences,
32
- detectChord: () => detectChord,
33
- detectChordBest: () => detectChordBest,
34
- detectKey: () => detectKey,
35
- functionOf: () => functionOf,
36
- isBorrowedChord: () => isBorrowedChord,
37
- isDiatonic: () => isDiatonic,
38
- isMinorKey: () => isMinorKey,
39
- parallelKey: () => parallelKey,
40
- romanToChord: () => romanToChord,
41
- secondaryDominant: () => secondaryDominant,
42
- tensionCurve: () => tensionCurve
43
- });
44
- module.exports = __toCommonJS(analyze_exports);
45
3
 
46
- // src/core/meter/index.ts
47
- var EPS = 1e-9;
48
- function isMultiple(value, unit) {
49
- if (unit === 0) {
50
- return false;
51
- }
52
- const ratio = value / unit;
53
- return Math.abs(ratio - Math.round(ratio)) < EPS;
54
- }
55
- function parseTimeSignature(text) {
56
- const match = /^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(text);
57
- if (!match) {
58
- throw new Error(`Invalid time signature: ${text}`);
59
- }
60
- const numerator = Number.parseInt(match[1] ?? "", 10);
61
- const denominator = Number.parseInt(match[2] ?? "", 10);
62
- if (numerator <= 0 || denominator <= 0) {
63
- throw new Error(`Invalid time signature: ${text}`);
64
- }
65
- return { numerator, denominator };
66
- }
67
- function formatTimeSignature(ts) {
68
- return `${ts.numerator}/${ts.denominator}`;
69
- }
70
- function isCompound(ts) {
71
- return ts.numerator % 3 === 0 && ts.numerator > 3;
72
- }
73
- function unitBeats(ts) {
74
- return 4 / ts.denominator;
75
- }
76
- function beatsPerBar(ts) {
77
- return ts.numerator * unitBeats(ts);
78
- }
79
- function pulseBeats(ts) {
80
- return isCompound(ts) ? 3 * unitBeats(ts) : unitBeats(ts);
81
- }
82
- function pulsesPerBar(ts) {
83
- return beatsPerBar(ts) / pulseBeats(ts);
84
- }
85
- function isValidGrouping(grouping, pulses) {
86
- if (grouping.length === 0) {
87
- return false;
88
- }
89
- let sum = 0;
90
- for (const g of grouping) {
91
- if (!Number.isInteger(g) || g <= 0) {
92
- return false;
93
- }
94
- sum += g;
95
- }
96
- return sum === pulses;
97
- }
98
- function isGroupHead(grouping, pulseIndex) {
99
- let acc = 0;
100
- for (const g of grouping) {
101
- if (acc === pulseIndex) {
102
- return true;
103
- }
104
- acc += g;
105
- }
106
- return false;
107
- }
108
- function beatToBarPosition(beatInQuarters, ts) {
109
- const barLen = beatsPerBar(ts);
110
- const bar = Math.floor(beatInQuarters / barLen);
111
- return { bar, beat: beatInQuarters - bar * barLen };
112
- }
113
- function metricWeight(beatInQuarters, ts) {
114
- const { beat } = beatToBarPosition(beatInQuarters, ts);
115
- const pulse = pulseBeats(ts);
116
- if (!isMultiple(beat, pulse)) {
117
- return 0;
118
- }
119
- const pulses = pulsesPerBar(ts);
120
- const pulseIndex = Math.round(beat / pulse) % pulses;
121
- if (pulseIndex === 0) {
122
- return 3;
123
- }
124
- const grouping = ts.grouping;
125
- if (grouping !== void 0) {
126
- if (!isValidGrouping(grouping, pulses)) {
127
- throw new Error(
128
- `Invalid grouping [${grouping.join(", ")}] for ${formatTimeSignature(ts)}: entries must be positive integers summing to ${pulses}`
129
- );
130
- }
131
- return isGroupHead(grouping, pulseIndex) ? 2 : 1;
132
- }
133
- if (pulses % 2 === 0 && pulseIndex === pulses / 2) {
134
- return 2;
135
- }
136
- return 1;
137
- }
138
- function isStrongBeat(beatInQuarters, ts) {
139
- return metricWeight(beatInQuarters, ts) >= 2;
140
- }
141
4
 
142
- // src/theory/scale/degrees.ts
143
- function pitchClass(pitch) {
144
- return (Math.trunc(pitch) % 12 + 12) % 12;
145
- }
146
- function scaleOffset(pitch, key) {
147
- return (pitchClass(pitch) - pitchClass(key.rootPc) + 12) % 12;
148
- }
149
- function isScaleTone(pitch, key) {
150
- return (key.modeMask12 >> scaleOffset(pitch, key) & 1) === 1;
151
- }
152
- function scaleTonesInDegreeOrder(key) {
153
- const root = pitchClass(key.rootPc);
154
- const pcs = [];
155
- for (let n = 0; n < 12; n += 1) {
156
- if ((key.modeMask12 >> n & 1) === 1) {
157
- pcs.push((root + n) % 12);
158
- }
159
- }
160
- return pcs;
161
- }
162
5
 
163
- // src/theory/scale/masks.ts
164
- function maskFromOffsets(offsets) {
165
- let mask = 1;
166
- for (const offset of offsets) {
167
- mask |= 1 << (offset % 12 + 12) % 12;
168
- }
169
- return mask;
170
- }
171
- var MAJOR_MASK = 2741;
172
- var NATURAL_MINOR_MASK = 1453;
173
- var HARMONIC_MINOR_MASK = maskFromOffsets([0, 2, 3, 5, 7, 8, 11]);
174
- var MELODIC_MINOR_MASK = maskFromOffsets([0, 2, 3, 5, 7, 9, 11]);
175
- var DORIAN_MASK = maskFromOffsets([0, 2, 3, 5, 7, 9, 10]);
176
- var PHRYGIAN_MASK = maskFromOffsets([0, 1, 3, 5, 7, 8, 10]);
177
- var LYDIAN_MASK = maskFromOffsets([0, 2, 4, 6, 7, 9, 11]);
178
- var MIXOLYDIAN_MASK = maskFromOffsets([0, 2, 4, 5, 7, 9, 10]);
179
- var LOCRIAN_MASK = maskFromOffsets([0, 1, 3, 5, 6, 8, 10]);
180
- var MAJOR_PENTATONIC_MASK = maskFromOffsets([0, 2, 4, 7, 9]);
181
- var MINOR_PENTATONIC_MASK = maskFromOffsets([0, 3, 5, 7, 10]);
182
- var BLUES_MASK = maskFromOffsets([0, 3, 5, 6, 7, 10]);
183
- var WHOLE_TONE_MASK = maskFromOffsets([0, 2, 4, 6, 8, 10]);
184
- var OCTATONIC_HALF_WHOLE_MASK = maskFromOffsets([0, 1, 3, 4, 6, 7, 9, 10]);
185
- var OCTATONIC_WHOLE_HALF_MASK = maskFromOffsets([0, 2, 3, 5, 6, 8, 9, 11]);
186
6
 
187
- // src/theory/scale/key.ts
188
- function majorKey(rootPc) {
189
- return { rootPc: (rootPc % 12 + 12) % 12, modeMask12: MAJOR_MASK };
190
- }
191
- function minorKey(rootPc) {
192
- return { rootPc: (rootPc % 12 + 12) % 12, modeMask12: NATURAL_MINOR_MASK };
193
- }
194
7
 
195
- // src/theory/chord/index.ts
196
- var QUALITY_INTERVALS = {
197
- maj: [0, 4, 7],
198
- min: [0, 3, 7],
199
- dim: [0, 3, 6],
200
- aug: [0, 4, 8],
201
- majb5: [0, 4, 6],
202
- maj7: [0, 4, 7, 11],
203
- min7: [0, 3, 7, 10],
204
- dom7: [0, 4, 7, 10],
205
- dim7: [0, 3, 6, 9],
206
- m7b5: [0, 3, 6, 10],
207
- minMaj7: [0, 3, 7, 11],
208
- aug7: [0, 4, 8, 10],
209
- augMaj7: [0, 4, 8, 11],
210
- "6": [0, 4, 7, 9],
211
- min6: [0, 3, 7, 9],
212
- "6/9": [0, 4, 7, 9, 14],
213
- sus2: [0, 2, 7],
214
- sus4: [0, 5, 7],
215
- add9: [0, 4, 7, 14],
216
- add11: [0, 4, 7, 17],
217
- maj9: [0, 4, 7, 11, 14],
218
- min9: [0, 3, 7, 10, 14],
219
- dom9: [0, 4, 7, 10, 14],
220
- "7b9": [0, 4, 7, 10, 13],
221
- "7#9": [0, 4, 7, 10, 15],
222
- "7#11": [0, 4, 7, 10, 18],
223
- "7b13": [0, 4, 7, 10, 20],
224
- "11": [0, 7, 10, 14, 17],
225
- "13": [0, 4, 7, 10, 14, 21],
226
- "5": [0, 7]
227
- };
228
- function pitchClass2(value) {
229
- return (Math.trunc(value) % 12 + 12) % 12;
230
- }
231
- function chordQualities() {
232
- return Object.keys(QUALITY_INTERVALS);
233
- }
234
- function makeChord(rootPc, quality, bassPc) {
235
- const chord = {
236
- rootPc: pitchClass2(rootPc),
237
- quality,
238
- intervals: [...QUALITY_INTERVALS[quality]]
239
- };
240
- if (bassPc !== void 0) {
241
- chord.bassPc = pitchClass2(bassPc);
242
- }
243
- return chord;
244
- }
245
- function chordPitchClasses(chord) {
246
- const set = /* @__PURE__ */ new Set();
247
- for (const interval of chord.intervals) {
248
- set.add(pitchClass2(chord.rootPc + interval));
249
- }
250
- return [...set].sort((a, b) => a - b);
251
- }
252
- function chordToneOffsets(chord) {
253
- return new Set(chord.intervals.map((i) => (i % 12 + 12) % 12));
254
- }
255
- function chordToneRole(pitch, chord) {
256
- const interval = (pitchClass2(pitch) - pitchClass2(chord.rootPc) + 12) % 12;
257
- const tones = chordToneOffsets(chord);
258
- if (interval === 0) {
259
- return "root";
260
- }
261
- if (interval === 3 || interval === 4) {
262
- return tones.has(interval) ? "third" : null;
263
- }
264
- if (interval === 7) {
265
- return tones.has(7) ? "fifth" : null;
266
- }
267
- if (interval === 6) {
268
- return tones.has(6) && !tones.has(7) ? "fifth" : null;
269
- }
270
- if (interval === 8) {
271
- return tones.has(8) && !tones.has(7) ? "fifth" : null;
272
- }
273
- if (interval === 9) {
274
- const hasHigherSeventh = tones.has(10) || tones.has(11);
275
- const isDiminishedSeventh = tones.has(3) && tones.has(6) && !hasHigherSeventh;
276
- if (isDiminishedSeventh) {
277
- return "seventh";
278
- }
279
- if (tones.has(9) && !hasHigherSeventh) {
280
- return "sixth";
281
- }
282
- return null;
283
- }
284
- if (interval === 10 || interval === 11) {
285
- return tones.has(interval) ? "seventh" : null;
286
- }
287
- return null;
288
- }
289
8
 
290
- // src/core/interval/index.ts
291
- function simpleInterval(semitones) {
292
- return Math.abs(semitones) % 12;
293
- }
294
- function isConsonantInterval(semitones, twoVoice = true) {
295
- const pc = simpleInterval(semitones);
296
- if (pc === 5) {
297
- return !twoVoice;
298
- }
299
- return pc === 0 || pc === 3 || pc === 4 || pc === 7 || pc === 8 || pc === 9;
300
- }
301
9
 
302
- // src/theory/counterpoint/index.ts
303
- function pitchClass3(pitch) {
304
- return (Math.trunc(pitch) % 12 + 12) % 12;
305
- }
306
- function createsVerticalDissonance(a, b, twoVoice) {
307
- return !isConsonantInterval(a - b, twoVoice);
308
- }
309
- function isForbiddenMelodicLeap(prev, cur) {
310
- const semis = Math.abs(cur - prev);
311
- return semis === 6 || semis === 10 || semis === 11 || semis > 12;
312
- }
313
- function simpleClass(semitones) {
314
- return Math.abs(semitones) % 12;
315
- }
316
- function isPerfectClass(cls) {
317
- return cls === 0 || cls === 7;
318
- }
319
- function similarMotion(aMove, bMove) {
320
- return aMove !== 0 && bMove !== 0 && aMove > 0 === bMove > 0;
321
- }
322
- function bothVoicesMove(aMove, bMove) {
323
- return aMove !== 0 && bMove !== 0;
324
- }
325
- function createsParallelPerfect(aPrev, aCur, bPrev, bCur) {
326
- if (!bothVoicesMove(aCur - aPrev, bCur - bPrev)) {
327
- return false;
328
- }
329
- const nowClass = simpleClass(aCur - bCur);
330
- const prevClass = simpleClass(aPrev - bPrev);
331
- return isPerfectClass(nowClass) && nowClass === prevClass;
332
- }
333
- function createsHiddenParallelPerfect(aPrev, aCur, bPrev, bCur) {
334
- const aMove = aCur - aPrev;
335
- const bMove = bCur - bPrev;
336
- if (!similarMotion(aMove, bMove)) {
337
- return false;
338
- }
339
- const nowClass = simpleClass(aCur - bCur);
340
- const prevClass = simpleClass(aPrev - bPrev);
341
- if (!isPerfectClass(nowClass) || prevClass === nowClass) {
342
- return false;
343
- }
344
- const upperMove = aCur >= bCur ? aMove : bMove;
345
- if (Math.abs(upperMove) <= 2) {
346
- return false;
347
- }
348
- return true;
349
- }
350
- function isLeadingToneResolution(prev, cur, key) {
351
- const tonic = pitchClass3(key.rootPc);
352
- const leading = (tonic + 11) % 12;
353
- if (pitchClass3(prev) !== leading || pitchClass3(cur) !== tonic) {
354
- return false;
355
- }
356
- return cur > prev && cur - prev <= 2;
357
- }
10
+ var _chunkRC6GBMCDcjs = require('../chunk-RC6GBMCD.cjs');
11
+ require('../chunk-36N73KZ3.cjs');
358
12
 
359
- // src/theory/safety/index.ts
360
- var SUGGESTION_WINDOW = 12;
361
- var MAX_SUGGESTIONS = 3;
362
- function pitchClass4(pitch) {
363
- return (Math.trunc(pitch) % 12 + 12) % 12;
364
- }
365
- function intervalAboveRoot(pitch, chord) {
366
- return ((pitchClass4(pitch) - pitchClass4(chord.rootPc)) % 12 + 12) % 12;
367
- }
368
- function isChordMember(pitch, chord) {
369
- return chordPitchClasses(chord).includes(pitchClass4(pitch));
370
- }
371
- function avoidsFourth(chord) {
372
- return chord.intervals.includes(4) && !chord.intervals.includes(5);
373
- }
374
- function avoidsMajorSeventh(chord) {
375
- return chord.intervals.includes(4) && chord.intervals.includes(10);
376
- }
377
- function stepResolution(pitch, chord) {
378
- for (let delta = 1; delta <= 2; delta += 1) {
379
- if (isChordMember(pitch - delta, chord)) {
380
- return pitch - delta;
381
- }
382
- }
383
- return void 0;
384
- }
385
- function evaluateSafety(q) {
386
- return evaluateInternal(q, true);
387
- }
388
- function evaluateInternal(q, collectSuggestions) {
389
- let reasons = 0;
390
- let level = 0 /* Safe */;
391
- let resolveTo;
392
- const raise = (l) => {
393
- if (l > level) {
394
- level = l;
395
- }
396
- };
397
- const avoidSeverity = q.profile === "strict" ? 2 /* Dissonant */ : 1 /* Warning */;
398
- const parallelSeverity = avoidSeverity;
399
- const pitch = q.candidatePitch;
400
- if (q.vocalLow !== void 0 && pitch < q.vocalLow || q.vocalHigh !== void 0 && pitch > q.vocalHigh) {
401
- reasons |= 32 /* OutOfRange */;
402
- raise(1 /* Warning */);
403
- }
404
- const inScale = isScaleTone(pitch, q.key);
405
- const chord = q.chord;
406
- if (chord && isChordMember(pitch, chord)) {
407
- reasons |= 1 /* ChordTone */;
408
- } else if (chord) {
409
- const ic = intervalAboveRoot(pitch, chord);
410
- const isTension = ic === 2 || ic === 5 || ic === 9;
411
- const avoid = ic === 5 && avoidsFourth(chord) || ic === 11 && avoidsMajorSeventh(chord);
412
- if (avoid) {
413
- reasons |= 4 /* AvoidNote */;
414
- if (isTension) {
415
- reasons |= 2 /* Tension */;
416
- }
417
- reasons |= 32768 /* NeedsResolution */;
418
- resolveTo = stepResolution(pitch, chord);
419
- raise(avoidSeverity);
420
- } else if (isTension && inScale) {
421
- reasons |= 2 /* Tension */;
422
- raise(1 /* Warning */);
423
- } else if (inScale) {
424
- reasons |= 8 /* ScaleTone */;
425
- raise(1 /* Warning */);
426
- } else {
427
- reasons |= 16 /* NonScale */;
428
- raise(2 /* Dissonant */);
429
- }
430
- } else if (inScale) {
431
- reasons |= 8 /* ScaleTone */;
432
- raise(1 /* Warning */);
433
- } else {
434
- reasons |= 16 /* NonScale */;
435
- raise(2 /* Dissonant */);
436
- }
437
- if (chord && !(chord.intervals.includes(4) && chord.intervals.includes(10))) {
438
- const ic = intervalAboveRoot(pitch, chord);
439
- const toneOffsets = chord.intervals.map((i) => (i % 12 + 12) % 12);
440
- if (toneOffsets.some((t) => Math.abs(ic - t) === 6)) {
441
- reasons |= 64 /* Tritone */;
442
- }
443
- }
444
- if (q.prevPitch !== void 0) {
445
- const pc = Math.abs(pitch - q.prevPitch) % 12;
446
- if (pc === 6) {
447
- reasons |= 64 /* Tritone */;
448
- }
449
- if (isForbiddenMelodicLeap(q.prevPitch, pitch)) {
450
- reasons |= 128 /* LargeLeap */;
451
- }
452
- if (pc === 1) {
453
- reasons |= 256 /* MinorSecond */;
454
- }
455
- if (pc === 11) {
456
- reasons |= 512 /* MajorSeventh */;
457
- }
458
- }
459
- if (q.strongBeat) {
460
- const twoVoice = q.otherVoices.length === 1;
461
- const prev = q.prevPitch;
462
- for (const ov of q.otherVoices) {
463
- if (!createsVerticalDissonance(pitch, ov.pitch, twoVoice)) {
464
- continue;
465
- }
466
- reasons |= 1024 /* VerticalDissonance */;
467
- raise(2 /* Dissonant */);
468
- if (prev !== void 0 && pitch === prev && ov.prevPitch !== void 0 && !createsVerticalDissonance(prev, ov.prevPitch, twoVoice)) {
469
- reasons |= 16384 /* Suspension */;
470
- }
471
- }
472
- }
473
- if (q.prevPitch !== void 0) {
474
- const prev = q.prevPitch;
475
- for (const ov of q.otherVoices) {
476
- if (ov.prevPitch === void 0) {
477
- continue;
478
- }
479
- if (createsParallelPerfect(prev, pitch, ov.prevPitch, ov.pitch)) {
480
- reasons |= 2048 /* ParallelPerfect */;
481
- raise(parallelSeverity);
482
- }
483
- if (createsHiddenParallelPerfect(prev, pitch, ov.prevPitch, ov.pitch)) {
484
- reasons |= 4096 /* HiddenParallel */;
485
- raise(parallelSeverity);
486
- }
487
- const crossedNow = pitch - ov.pitch;
488
- const crossedPrev = prev - ov.prevPitch;
489
- if (crossedNow !== 0 && crossedPrev !== 0 && crossedNow > 0 !== crossedPrev > 0) {
490
- reasons |= 8192 /* VoiceCrossing */;
491
- raise(parallelSeverity);
492
- }
493
- }
494
- }
495
- const result = { safety: level, reasons, rationale: describe(reasons, q) };
496
- if (resolveTo !== void 0) {
497
- result.resolveTo = resolveTo;
498
- }
499
- if (collectSuggestions && level !== 0 /* Safe */) {
500
- const suggestions = findSafeNearby(q, pitch);
501
- if (suggestions.length > 0) {
502
- result.suggestions = suggestions;
503
- }
504
- }
505
- return result;
506
- }
507
- function findSafeNearby(q, candidate) {
508
- const out = [];
509
- for (let d = 1; d <= SUGGESTION_WINDOW; d += 1) {
510
- for (const p of [candidate - d, candidate + d]) {
511
- if (evaluateInternal({ ...q, candidatePitch: p }, false).safety === 0 /* Safe */) {
512
- out.push(p);
513
- if (out.length >= MAX_SUGGESTIONS) {
514
- return out;
515
- }
516
- }
517
- }
518
- }
519
- return out;
520
- }
521
- function describe(reasons, q) {
522
- if (reasons & 32 /* OutOfRange */) {
523
- return "Outside the target vocal range";
524
- }
525
- if (reasons & 16384 /* Suspension */) {
526
- return "Prepared suspension \u2014 a held consonance now dissonant, awaiting resolution";
527
- }
528
- if (reasons & 1024 /* VerticalDissonance */) {
529
- return "Dissonant against a sounding voice on a strong beat";
530
- }
531
- if (reasons & 4 /* AvoidNote */) {
532
- return "Avoid note \u2014 clashes with a chord tone a semitone away";
533
- }
534
- if (reasons & 2048 /* ParallelPerfect */) {
535
- return "Parallel perfect interval with another voice";
536
- }
537
- if (reasons & 4096 /* HiddenParallel */) {
538
- return "Hidden perfect interval by similar motion";
539
- }
540
- if (reasons & 8192 /* VoiceCrossing */) {
541
- return "Crosses another voice";
542
- }
543
- if (reasons & 1 /* ChordTone */) {
544
- return "Chord tone";
545
- }
546
- if (reasons & 2 /* Tension */) {
547
- return "Chord tension";
548
- }
549
- if (reasons & 16 /* NonScale */) {
550
- return "Outside the key";
551
- }
552
- if (reasons & 8 /* ScaleTone */) {
553
- return "Scale tone, not in the chord";
554
- }
555
- return q.chord ? "Placeable" : "No chord context";
556
- }
557
13
 
558
- // src/analyze/functional/internal.ts
559
- function mod12(n) {
560
- return (n % 12 + 12) % 12;
561
- }
562
- function degreeRootPc(degreeNumber, key) {
563
- const tones = scaleTonesInDegreeOrder(key);
564
- if (tones.length === 0) {
565
- return mod12(key.rootPc);
566
- }
567
- return tones[(degreeNumber - 1) % tones.length] ?? mod12(key.rootPc);
568
- }
569
- function isNeapolitan(chord, key) {
570
- return mod12(chord.rootPc - key.rootPc) === 1 && chord.quality === "maj";
571
- }
572
14
 
573
- // src/analyze/functional/roman.ts
574
- var ROMAN = ["I", "II", "III", "IV", "V", "VI", "VII"];
575
- var ROMAN_TO_DEGREE = {
576
- I: 1,
577
- II: 2,
578
- III: 3,
579
- IV: 4,
580
- V: 5,
581
- VI: 6,
582
- VII: 7
583
- };
584
- var OFFSET_SPELLING = [
585
- [1, ""],
586
- [2, "b"],
587
- [2, ""],
588
- [3, "b"],
589
- [3, ""],
590
- [4, ""],
591
- [4, "#"],
592
- [5, ""],
593
- [6, "b"],
594
- [6, ""],
595
- [7, "b"],
596
- [7, ""]
597
- ];
598
- function seventhQuality(base, halfDim) {
599
- if (halfDim) {
600
- return "m7b5";
601
- }
602
- if (base === "dim") {
603
- return "dim7";
604
- }
605
- if (base === "aug") {
606
- return "aug7";
607
- }
608
- return base === "maj" ? "dom7" : "min7";
609
- }
610
- var INVERSION_FIGURES = /* @__PURE__ */ new Set(["6", "64", "65", "43", "42", "2", "7"]);
611
- var ROMAN_STYLE = {
612
- maj: { lower: false, suffix: "" },
613
- min: { lower: true, suffix: "" },
614
- dim: { lower: true, suffix: "o" },
615
- aug: { lower: false, suffix: "+" },
616
- maj7: { lower: false, suffix: "maj7" },
617
- min7: { lower: true, suffix: "7" },
618
- dom7: { lower: false, suffix: "7" },
619
- dim7: { lower: true, suffix: "o7" },
620
- m7b5: { lower: true, suffix: "\xF87" },
621
- minMaj7: { lower: true, suffix: "maj7" },
622
- aug7: { lower: false, suffix: "+7" },
623
- augMaj7: { lower: false, suffix: "+maj7" },
624
- majb5: { lower: false, suffix: "b5" },
625
- "6": { lower: false, suffix: "add6" },
626
- min6: { lower: true, suffix: "add6" },
627
- "6/9": { lower: false, suffix: "69" },
628
- sus2: { lower: false, suffix: "sus2" },
629
- sus4: { lower: false, suffix: "sus4" },
630
- add9: { lower: false, suffix: "add9" },
631
- add11: { lower: false, suffix: "add11" },
632
- maj9: { lower: false, suffix: "maj9" },
633
- min9: { lower: true, suffix: "9" },
634
- dom9: { lower: false, suffix: "9" },
635
- "7b9": { lower: false, suffix: "7b9" },
636
- "7#9": { lower: false, suffix: "7#9" },
637
- "7#11": { lower: false, suffix: "7#11" },
638
- "7b13": { lower: false, suffix: "7b13" },
639
- "11": { lower: false, suffix: "11" },
640
- "13": { lower: false, suffix: "13" },
641
- "5": { lower: false, suffix: "5" }
642
- };
643
- var SUFFIX_QUALITY = new Map(
644
- Object.entries(ROMAN_STYLE).map(
645
- ([quality, style]) => [`${style.lower ? "l" : "u"}:${style.suffix}`, quality]
646
- )
647
- );
648
- function parseInversion(figures) {
649
- if (figures === "65") {
650
- return { inversion: 1, seventh: true };
651
- }
652
- if (figures === "43") {
653
- return { inversion: 2, seventh: true };
654
- }
655
- if (figures === "42" || figures === "2") {
656
- return { inversion: 3, seventh: true };
657
- }
658
- if (figures === "7") {
659
- return { inversion: 0, seventh: true };
660
- }
661
- if (figures === "64") {
662
- return { inversion: 2, seventh: false };
663
- }
664
- if (figures === "6") {
665
- return { inversion: 1, seventh: false };
666
- }
667
- return { inversion: 0, seventh: false };
668
- }
669
- function parseSimpleRoman(text, key) {
670
- const match = /^([b#]?)([iIvV]+)(.*)$/.exec(text.trim());
671
- if (!match) {
672
- throw new Error(`Invalid Roman numeral: ${text}`);
673
- }
674
- const accidental = match[1] === "b" ? -1 : match[1] === "#" ? 1 : 0;
675
- const glyph = (match[2] ?? "").toUpperCase();
676
- const degreeNumber = ROMAN_TO_DEGREE[glyph];
677
- if (degreeNumber === void 0) {
678
- throw new Error(`Invalid Roman numeral: ${text}`);
679
- }
680
- const isUpper = (match[2] ?? "")[0] === (match[2] ?? "")[0]?.toUpperCase();
681
- const suffix = match[3] ?? "";
682
- const rootPc = mod12(degreeRootPc(degreeNumber, key) + accidental);
683
- const canonical = SUFFIX_QUALITY.get(`${isUpper ? "u" : "l"}:${suffix}`);
684
- if (canonical !== void 0) {
685
- return { rootPc, quality: canonical, inversion: 0 };
686
- }
687
- const isDim = /o|°|dim/.test(suffix);
688
- const isAug = /\+|aug/.test(suffix);
689
- const isHalfDim = /ø/.test(suffix);
690
- const explicitMaj7 = /maj7|M7/.test(suffix);
691
- const figures = suffix.replace(/maj7|M7/g, "").replace(/[^0-9]/g, "");
692
- if (figures !== "" && !INVERSION_FIGURES.has(figures)) {
693
- throw new Error(`Unsupported figured-bass or extension "${figures}" in Roman numeral: ${text}`);
694
- }
695
- const { inversion, seventh } = parseInversion(figures);
696
- const hasSeventh = explicitMaj7 || seventh || isHalfDim;
697
- let base;
698
- if (isDim || isHalfDim) {
699
- base = "dim";
700
- } else if (isAug) {
701
- base = "aug";
702
- } else {
703
- base = isUpper ? "maj" : "min";
704
- }
705
- let quality;
706
- if (explicitMaj7) {
707
- quality = base === "min" ? "minMaj7" : base === "aug" ? "augMaj7" : "maj7";
708
- } else if (hasSeventh) {
709
- quality = seventhQuality(base, isHalfDim);
710
- } else if (base === "dim") {
711
- quality = "dim";
712
- } else if (base === "aug") {
713
- quality = "aug";
714
- } else {
715
- quality = base;
716
- }
717
- return { rootPc, quality, inversion };
718
- }
719
- function chordFromParsed(parsed) {
720
- const chord = makeChord(parsed.rootPc, parsed.quality);
721
- if (parsed.inversion > 0 && parsed.inversion < chord.intervals.length) {
722
- chord.bassPc = mod12(parsed.rootPc + (chord.intervals[parsed.inversion] ?? 0));
723
- }
724
- return chord;
725
- }
726
- function romanToChord(text, key) {
727
- const trimmed = text.trim();
728
- const slash = trimmed.indexOf("/");
729
- if (slash >= 0) {
730
- const applied = trimmed.slice(0, slash);
731
- const target = trimmed.slice(slash + 1);
732
- const targetRoot = parseSimpleRoman(target, key).rootPc;
733
- const localKey = majorKey(targetRoot);
734
- return chordFromParsed(parseSimpleRoman(applied, localKey));
735
- }
736
- return chordFromParsed(parseSimpleRoman(trimmed, key));
737
- }
738
- function romanStyle(quality) {
739
- return ROMAN_STYLE[quality];
740
- }
741
- function romanSpelling(rootPc, key) {
742
- const tones = scaleTonesInDegreeOrder(key);
743
- const diatonic = tones.indexOf(mod12(rootPc));
744
- if (diatonic >= 0) {
745
- return { degreeNumber: diatonic + 1, accidental: "" };
746
- }
747
- for (let i = 0; i < tones.length; i += 1) {
748
- const degreeNumber2 = i + 1;
749
- if (degreeNumber2 === 1 || degreeNumber2 === 5) {
750
- continue;
751
- }
752
- if (mod12((tones[i] ?? 0) - 1) === mod12(rootPc)) {
753
- return { degreeNumber: degreeNumber2, accidental: "b" };
754
- }
755
- }
756
- for (let i = 0; i < tones.length; i += 1) {
757
- if (mod12((tones[i] ?? 0) + 1) === mod12(rootPc)) {
758
- return { degreeNumber: i + 1, accidental: "#" };
759
- }
760
- }
761
- const [degreeNumber, accidental] = OFFSET_SPELLING[mod12(rootPc - key.rootPc)] ?? [1, ""];
762
- return { degreeNumber, accidental };
763
- }
764
- function baseMarker(quality) {
765
- if (quality === "dim" || quality === "dim7") {
766
- return "o";
767
- }
768
- if (quality === "m7b5") {
769
- return "\xF8";
770
- }
771
- if (quality === "aug" || quality === "aug7") {
772
- return "+";
773
- }
774
- if (quality === "augMaj7") {
775
- return "+maj7";
776
- }
777
- if (quality === "maj7" || quality === "minMaj7") {
778
- return "maj7";
779
- }
780
- return "";
781
- }
782
- var TRIAD_FIGURES = { 1: "6", 2: "64" };
783
- var SEVENTH_FIGURES = { 1: "65", 2: "43", 3: "42" };
784
- var TRIAD_FIGURE_QUALITIES = /* @__PURE__ */ new Set(["maj", "min", "dim", "aug"]);
785
- var SEVENTH_FIGURE_QUALITIES = /* @__PURE__ */ new Set([
786
- "maj7",
787
- "min7",
788
- "dom7",
789
- "dim7",
790
- "m7b5",
791
- "minMaj7",
792
- "aug7",
793
- "augMaj7"
794
- ]);
795
- function chordToRoman(chord, key) {
796
- const { degreeNumber, accidental } = romanSpelling(chord.rootPc, key);
797
- const { lower, suffix } = romanStyle(chord.quality);
798
- const numeral = ROMAN[degreeNumber - 1] ?? "I";
799
- const cased = lower ? numeral.toLowerCase() : numeral;
800
- let inversion = 0;
801
- if (chord.bassPc !== void 0) {
802
- const idx = chord.intervals.findIndex((iv) => mod12(chord.rootPc + iv) === chord.bassPc);
803
- if (idx > 0) {
804
- inversion = idx;
805
- }
806
- }
807
- if (inversion > 0) {
808
- const figure = SEVENTH_FIGURE_QUALITIES.has(chord.quality) ? SEVENTH_FIGURES[inversion] : TRIAD_FIGURE_QUALITIES.has(chord.quality) ? TRIAD_FIGURES[inversion] : void 0;
809
- if (figure !== void 0) {
810
- return `${accidental}${cased}${baseMarker(chord.quality)}${figure}`;
811
- }
812
- }
813
- return `${accidental}${cased}${suffix}`;
814
- }
815
15
 
816
- // src/analyze/functional/function.ts
817
- var FUNCTION_BY_OFFSET = [
818
- "tonic",
819
- // 0 I
820
- "subdominant",
821
- // 1 bII (Neapolitan)
822
- "subdominant",
823
- // 2 ii
824
- "tonic",
825
- // 3 bIII
826
- "tonic",
827
- // 4 iii
828
- "subdominant",
829
- // 5 IV
830
- "dominant",
831
- // 6 #IV / bV
832
- "dominant",
833
- // 7 V
834
- "subdominant",
835
- // 8 bVI
836
- "tonic",
837
- // 9 vi
838
- "subdominant",
839
- // 10 bVII
840
- "dominant"
841
- // 11 vii
842
- ];
843
- function isMinorKey(key) {
844
- const hasMinorThird = key.modeMask12 >> 3 & 1;
845
- const hasMajorThird2 = key.modeMask12 >> 4 & 1;
846
- return Boolean(hasMinorThird) && !hasMajorThird2;
847
- }
848
- function functionOf(chord, key) {
849
- return FUNCTION_BY_OFFSET[mod12(chord.rootPc - key.rootPc)] ?? "tonic";
850
- }
851
- function isDiatonic(chord, key) {
852
- return chordPitchClasses(chord).every((pc) => isScaleTone(pc, key));
853
- }
854
- function parallelKey(key) {
855
- return {
856
- rootPc: mod12(key.rootPc),
857
- modeMask12: isMinorKey(key) ? MAJOR_MASK : NATURAL_MINOR_MASK
858
- };
859
- }
860
- function isDiminishedQuality(quality) {
861
- return quality === "dim" || quality === "dim7" || quality === "m7b5";
862
- }
863
- function hasMajorThird(chord) {
864
- return chord.intervals.some((interval) => mod12(interval) === 4);
865
- }
866
- function qualityAwareFunction(chord, key) {
867
- const offset = mod12(chord.rootPc - key.rootPc);
868
- if (isDiminishedQuality(chord.quality) && (offset === 11 || offset === 6)) {
869
- return "dominant";
870
- }
871
- if (isNeapolitan(chord, key)) {
872
- return "subdominant";
873
- }
874
- if (!isMinorKey(key) && hasMajorThird(chord) && (offset === 8 || offset === 10)) {
875
- return "subdominant";
876
- }
877
- return functionOf(chord, key);
878
- }
879
- function analyzeChord(chord, key) {
880
- const source = borrowedSource(chord, key);
881
- return {
882
- function: qualityAwareFunction(chord, key),
883
- borrowed: source !== null,
884
- source,
885
- roman: chordToRoman(chord, key)
886
- };
887
- }
888
- function secondaryDominant(targetDegree, key) {
889
- const targetRoot = degreeRootPc(targetDegree + 1, key);
890
- return makeChord(mod12(targetRoot + 7), "dom7");
891
- }
892
16
 
893
- // src/analyze/functional/borrowed.ts
894
- function isHarmonicMinorAlteration(chord, key) {
895
- return isMinorKey(key) && isDiatonic(chord, { rootPc: mod12(key.rootPc), modeMask12: HARMONIC_MINOR_MASK });
896
- }
897
- function isBorrowedChord(chord, key) {
898
- if (isDiatonic(chord, key)) {
899
- return false;
900
- }
901
- if (isHarmonicMinorAlteration(chord, key)) {
902
- return false;
903
- }
904
- return isDiatonic(chord, parallelKey(key));
905
- }
906
- function borrowedSource(chord, key) {
907
- if (isDiatonic(chord, key)) {
908
- return null;
909
- }
910
- if (isNeapolitan(chord, key)) {
911
- return "neapolitan";
912
- }
913
- if (isBorrowedChord(chord, key)) {
914
- return isMinorKey(key) ? "parallel-major" : "parallel-minor";
915
- }
916
- return null;
917
- }
918
17
 
919
- // src/analyze/functional/cadence.ts
920
- function detectCadence(from, to, key) {
921
- const tonic = mod12(key.rootPc);
922
- const fromOffset = mod12(from.rootPc - tonic);
923
- const toOffset = mod12(to.rootPc - tonic);
924
- const deceptiveTargets = isMinorKey(key) ? [8] : [8, 9];
925
- if (fromOffset === 7 && toOffset === 0) {
926
- return "authentic";
927
- }
928
- if (fromOffset === 5 && toOffset === 0) {
929
- return "plagal";
930
- }
931
- if (fromOffset === 7 && deceptiveTargets.includes(toOffset)) {
932
- return "deceptive";
933
- }
934
- if (toOffset === 7 && fromOffset !== 7) {
935
- return "half";
936
- }
937
- return null;
938
- }
939
18
 
940
- // src/analyze/detect/index.ts
941
- function pitchClass5(value) {
942
- return (Math.trunc(value) % 12 + 12) % 12;
943
- }
944
- function uniquePitchClasses(pitches) {
945
- return [...new Set(pitches.map(pitchClass5))].sort((a, b) => a - b);
946
- }
947
- function detectChord(pitches) {
948
- const input = uniquePitchClasses(pitches);
949
- if (input.length === 0) {
950
- return [];
951
- }
952
- const bassPc = pitchClass5(Math.min(...pitches));
953
- const inputSet = new Set(input);
954
- const matches = [];
955
- const qualities = chordQualities();
956
- for (const rootPc of input) {
957
- for (const quality of qualities) {
958
- const chord = makeChord(rootPc, quality);
959
- const tones = chordPitchClasses(chord);
960
- const toneSet = new Set(tones);
961
- const missingPcs = tones.filter((pc) => !inputSet.has(pc));
962
- const fifthPc = pitchClass5(rootPc + 7);
963
- if (missingPcs.length > 1 || missingPcs.length === 1 && missingPcs[0] !== fifthPc) {
964
- continue;
965
- }
966
- const extraPcs = input.filter((pc) => !toneSet.has(pc));
967
- const bassIndex = chord.intervals.findIndex((iv) => pitchClass5(rootPc + iv) === bassPc);
968
- const inversion = bassIndex > 0 ? bassIndex : 0;
969
- const match = {
970
- rootPc,
971
- quality,
972
- missingPcs,
973
- extraPcs,
974
- exact: extraPcs.length === 0 && missingPcs.length === 0,
975
- inversion
976
- };
977
- if (inversion > 0) {
978
- match.bassPc = bassPc;
979
- }
980
- matches.push(match);
981
- }
982
- }
983
- matches.sort((a, b) => {
984
- if (a.extraPcs.length !== b.extraPcs.length) {
985
- return a.extraPcs.length - b.extraPcs.length;
986
- }
987
- if (a.missingPcs.length !== b.missingPcs.length) {
988
- return a.missingPcs.length - b.missingPcs.length;
989
- }
990
- if (a.inversion === 0 !== (b.inversion === 0)) {
991
- return a.inversion === 0 ? -1 : 1;
992
- }
993
- const aSize = chordPitchClasses(makeChord(a.rootPc, a.quality)).length;
994
- const bSize = chordPitchClasses(makeChord(b.rootPc, b.quality)).length;
995
- return bSize - aSize;
996
- });
997
- return matches;
998
- }
999
- function detectChordBest(pitches) {
1000
- const best = detectChord(pitches)[0];
1001
- if (!best) {
1002
- return null;
1003
- }
1004
- return makeChord(best.rootPc, best.quality, best.bassPc);
1005
- }
1006
- var MINOR_MASK_VARIANTS = [NATURAL_MINOR_MASK, HARMONIC_MINOR_MASK, MELODIC_MINOR_MASK];
1007
- function detectKey(pitches) {
1008
- const input = uniquePitchClasses(pitches);
1009
- if (input.length === 0) {
1010
- return [];
1011
- }
1012
- const counts = /* @__PURE__ */ new Map();
1013
- for (const pc of pitches.map(pitchClass5)) {
1014
- counts.set(pc, (counts.get(pc) ?? 0) + 1);
1015
- }
1016
- const total = pitches.length;
1017
- const results = [];
1018
- for (let tonic = 0; tonic < 12; tonic += 1) {
1019
- for (const mode of ["major", "minor"]) {
1020
- const key = mode === "major" ? majorKey(tonic) : minorKey(tonic);
1021
- const masks = mode === "major" ? [MAJOR_MASK] : MINOR_MASK_VARIANTS;
1022
- let inScale = 0;
1023
- let weighted = Number.NEGATIVE_INFINITY;
1024
- for (const mask of masks) {
1025
- let variantInScale = 0;
1026
- let variantWeighted = 0;
1027
- for (const pc of input) {
1028
- const offset = (pc - tonic + 12) % 12;
1029
- if (mask >> offset & 1) {
1030
- variantInScale += 1;
1031
- }
1032
- }
1033
- for (const [pc, count] of counts) {
1034
- const offset = (pc - tonic + 12) % 12;
1035
- if (mask >> offset & 1) {
1036
- variantWeighted += count;
1037
- }
1038
- }
1039
- if (variantWeighted > weighted) {
1040
- weighted = variantWeighted;
1041
- inScale = variantInScale;
1042
- }
1043
- }
1044
- weighted += (counts.get(tonic) ?? 0) * 0.5;
1045
- results.push({
1046
- key,
1047
- mode,
1048
- fit: inScale / input.length,
1049
- score: weighted / total
1050
- });
1051
- }
1052
- }
1053
- results.sort((a, b) => b.score - a.score);
1054
- return results.map(({ key, mode, fit }) => ({ key, mode, fit }));
1055
- }
1056
19
 
1057
- // src/analyze/timeline/index.ts
1058
- function chordTimelineFromChords(chords, totalBeats) {
1059
- const sorted = [...chords].sort((a, b) => a.startBeat - b.startBeat);
1060
- const segments = sorted.map((gc, i) => {
1061
- const next = sorted[i + 1];
1062
- const endBeat = Math.max(gc.startBeat, next ? next.startBeat : totalBeats);
1063
- return {
1064
- startBeat: gc.startBeat,
1065
- endBeat,
1066
- chord: makeChord(gc.rootPc, gc.quality, gc.bassPc)
1067
- };
1068
- }).filter((seg) => seg.endBeat > seg.startBeat);
1069
- return { at: segmentLookup(segments), segments };
1070
- }
1071
- function segmentLookup(segments) {
1072
- return (beat) => {
1073
- for (const seg of segments) {
1074
- if (beat >= seg.startBeat && beat < seg.endBeat) {
1075
- return seg.chord;
1076
- }
1077
- }
1078
- return null;
1079
- };
1080
- }
1081
- var EPS2 = 1e-9;
1082
- var NOISE_THRESHOLD_RATIO = 0.2;
1083
- var MAX_DETECTION_PCS = 6;
1084
- var FALLBACK_PCS = 3;
1085
- var INEXACT_CONFIDENCE_FACTOR = 0.85;
1086
- var DIATONIC_BONUS = 0.5;
1087
- var EXACT_BONUS = 0.5;
1088
- var MISMATCH_PENALTY = 0.3;
1089
- function pitchClass6(value) {
1090
- return (Math.trunc(value) % 12 + 12) % 12;
1091
- }
1092
- function scoreMatch(match, weights, maxWeight, key) {
1093
- const rootWeight = maxWeight > 0 ? (weights[match.rootPc] ?? 0) / maxWeight : 0;
1094
- const tones = chordPitchClasses(makeChord(match.rootPc, match.quality));
1095
- let score = rootWeight;
1096
- if (tones.every((pc) => isScaleTone(pc, key))) {
1097
- score += DIATONIC_BONUS;
1098
- }
1099
- if (match.exact) {
1100
- score += EXACT_BONUS;
1101
- }
1102
- score -= MISMATCH_PENALTY * (match.extraPcs.length + match.missingPcs.length);
1103
- return score;
1104
- }
1105
- function chordConfidence(chord, weights, totalWeight, exact) {
1106
- const tones = new Set(chordPitchClasses(chord));
1107
- let chordWeight = 0;
1108
- for (let pc = 0; pc < 12; pc += 1) {
1109
- if (tones.has(pc)) {
1110
- chordWeight += weights[pc] ?? 0;
1111
- }
1112
- }
1113
- const raw = totalWeight > 0 ? chordWeight / totalWeight : 0;
1114
- const confidence = Math.min(1, Math.max(0, raw));
1115
- return exact ? confidence : confidence * INEXACT_CONFIDENCE_FACTOR;
1116
- }
1117
- function analyzeWindow(notes, windowStart, windowEnd, ts, key) {
1118
- const weights = new Array(12).fill(0);
1119
- let lowestPitch = Number.POSITIVE_INFINITY;
1120
- for (const note of notes) {
1121
- const noteEnd = note.startBeat + note.durationBeat;
1122
- const overlap = Math.min(noteEnd, windowEnd) - Math.max(note.startBeat, windowStart);
1123
- if (overlap <= EPS2) {
1124
- continue;
1125
- }
1126
- const velocityFactor = note.velocity !== void 0 ? note.velocity / 127 : 1;
1127
- const onsetInWindow = note.startBeat >= windowStart - EPS2 && note.startBeat < windowEnd - EPS2;
1128
- const accent = onsetInWindow ? 1 + metricWeight(note.startBeat, ts) / 3 : 1;
1129
- const pc = pitchClass6(note.pitch);
1130
- weights[pc] = (weights[pc] ?? 0) + overlap * velocityFactor * accent;
1131
- if (note.pitch < lowestPitch) {
1132
- lowestPitch = note.pitch;
1133
- }
1134
- }
1135
- let totalWeight = 0;
1136
- let maxWeight = 0;
1137
- for (const w of weights) {
1138
- totalWeight += w;
1139
- maxWeight = Math.max(maxWeight, w);
1140
- }
1141
- if (totalWeight <= EPS2) {
1142
- return null;
1143
- }
1144
- const ranked = weights.map((weight, pc) => ({ pc, weight })).filter(({ weight }) => weight > 0).sort((a, b) => b.weight - a.weight || a.pc - b.pc);
1145
- const selected = ranked.filter(({ weight }) => weight >= maxWeight * NOISE_THRESHOLD_RATIO).slice(0, MAX_DETECTION_PCS).map(({ pc }) => pc);
1146
- const bassPc = pitchClass6(lowestPitch);
1147
- const anchorPc = selected.includes(bassPc) ? bassPc : selected[0] ?? bassPc;
1148
- const detectionPitches = selected.map((pc) => pc === anchorPc ? pc : pc + 12);
1149
- const matches = detectChord(detectionPitches);
1150
- let bestMatch = null;
1151
- let bestScore = Number.NEGATIVE_INFINITY;
1152
- for (const match of matches) {
1153
- const score = scoreMatch(match, weights, maxWeight, key);
1154
- if (score > bestScore) {
1155
- bestScore = score;
1156
- bestMatch = match;
1157
- }
1158
- }
1159
- if (bestMatch) {
1160
- const chord = makeChord(bestMatch.rootPc, bestMatch.quality, bestMatch.bassPc);
1161
- return { chord, confidence: chordConfidence(chord, weights, totalWeight, bestMatch.exact) };
1162
- }
1163
- const fallback = detectChordBest(selected.slice(0, FALLBACK_PCS));
1164
- if (fallback) {
1165
- return { chord: fallback, confidence: chordConfidence(fallback, weights, totalWeight, false) };
1166
- }
1167
- return null;
1168
- }
1169
- function sameChord(a, b) {
1170
- return a.rootPc === b.rootPc && a.quality === b.quality && a.bassPc === b.bassPc;
1171
- }
1172
- function chordTimelineFromNotes(notes, opts = {}) {
1173
- const ts = opts.ts ?? parseTimeSignature("4/4");
1174
- const harmonicRhythm = opts.harmonicRhythm ?? beatsPerBar(ts);
1175
- if (!(harmonicRhythm > 0)) {
1176
- throw new Error(`Invalid harmonic rhythm: ${harmonicRhythm}`);
1177
- }
1178
- const sounding = notes.filter((note) => note.durationBeat > 0);
1179
- const lastNoteEnd = sounding.reduce((end, n) => Math.max(end, n.startBeat + n.durationBeat), 0);
1180
- const totalBeats = opts.totalBeats ?? lastNoteEnd;
1181
- const key = opts.key ?? detectKey(sounding.map((n) => n.pitch))[0]?.key ?? majorKey(0);
1182
- const segments = [];
1183
- const segmentConfidence = [];
1184
- const windowCount = Math.max(0, Math.ceil(totalBeats / harmonicRhythm - EPS2));
1185
- for (let i = 0; i < windowCount; i += 1) {
1186
- const start = i * harmonicRhythm;
1187
- const end = Math.min(start + harmonicRhythm, totalBeats);
1188
- const inferred = analyzeWindow(sounding, start, end, ts, key);
1189
- if (!inferred) {
1190
- continue;
1191
- }
1192
- const last = segments[segments.length - 1];
1193
- if (last && sameChord(last.chord, inferred.chord) && Math.abs(last.endBeat - start) < EPS2) {
1194
- const lastLength = last.endBeat - last.startBeat;
1195
- const length = end - start;
1196
- const lastConfidence = segmentConfidence[segmentConfidence.length - 1] ?? 0;
1197
- segmentConfidence[segmentConfidence.length - 1] = (lastConfidence * lastLength + inferred.confidence * length) / (lastLength + length);
1198
- last.endBeat = end;
1199
- } else {
1200
- segments.push({ startBeat: start, endBeat: end, chord: inferred.chord });
1201
- segmentConfidence.push(inferred.confidence);
1202
- }
1203
- }
1204
- return {
1205
- timeline: { at: segmentLookup(segments), segments },
1206
- key,
1207
- segmentConfidence
1208
- };
1209
- }
1210
- function detectCadences(timeline, key) {
1211
- const hits = [];
1212
- for (let i = 1; i < timeline.segments.length; i += 1) {
1213
- const prev = timeline.segments[i - 1];
1214
- const cur = timeline.segments[i];
1215
- if (!prev || !cur) {
1216
- continue;
1217
- }
1218
- if (Math.abs(cur.startBeat - prev.endBeat) > EPS2) {
1219
- continue;
1220
- }
1221
- const type = detectCadence(prev.chord, cur.chord, key);
1222
- if (type !== null) {
1223
- hits.push({ atBeat: cur.startBeat, type, from: prev.chord, to: cur.chord });
1224
- }
1225
- }
1226
- return hits;
1227
- }
1228
20
 
1229
- // src/analyze/arrange/internal.ts
1230
- var EPS3 = 1e-9;
1231
- function covers(note, beat) {
1232
- return beat >= note.startBeat - EPS3 && beat < note.endBeat - EPS3;
1233
- }
1234
- function poolNotes(tracks) {
1235
- const notes = [];
1236
- for (const track of tracks) {
1237
- for (const note of track.notes) {
1238
- if (note.durationBeat > 0) {
1239
- notes.push(note);
1240
- }
1241
- }
1242
- }
1243
- return notes;
1244
- }
1245
- function splitIntoSubVoices(ordered) {
1246
- const lanes = [];
1247
- for (const note of ordered) {
1248
- const lane = lanes.find((candidate) => {
1249
- const last = candidate[candidate.length - 1];
1250
- return last !== void 0 && last.startBeat + last.durationBeat <= note.startBeat + EPS3;
1251
- });
1252
- if (lane) {
1253
- lane.push(note);
1254
- } else {
1255
- lanes.push([note]);
1256
- }
1257
- }
1258
- return lanes;
1259
- }
1260
- function prepareTracks(tracks) {
1261
- let nextId = 0;
1262
- return tracks.map((track, index) => {
1263
- const ordered = track.notes.filter((note) => note.durationBeat > 0).sort((a, b) => a.startBeat - b.startBeat || a.pitch - b.pitch).map((note) => ({ ...note, id: nextId++ }));
1264
- const voices = splitIntoSubVoices(ordered).map((voice) => ({
1265
- voice,
1266
- sounding: voice.map((note, i) => {
1267
- const prev = i > 0 ? voice[i - 1] : void 0;
1268
- return {
1269
- pitch: note.pitch,
1270
- prevPitch: prev?.pitch,
1271
- startBeat: note.startBeat,
1272
- endBeat: note.startBeat + note.durationBeat
1273
- };
1274
- })
1275
- }));
1276
- return {
1277
- name: track.name ?? `track ${index + 1}`,
1278
- role: track.role ?? "other",
1279
- voices
1280
- };
1281
- });
1282
- }
1283
21
 
1284
- // src/analyze/arrange/tension.ts
1285
- var FUNCTION_TENSION = {
1286
- tonic: 0,
1287
- subdominant: 0.5,
1288
- dominant: 1
1289
- };
1290
- var FUNCTION_WEIGHT = 0.5;
1291
- var DISSONANCE_WEIGHT = 0.35;
1292
- var SPAN_WEIGHT = 0.15;
1293
- var SPAN_SATURATION = 24;
1294
- function pitchClass7(pitch) {
1295
- return (Math.trunc(pitch) % 12 + 12) % 12;
1296
- }
1297
- function clamp01(value) {
1298
- return Math.min(1, Math.max(0, value));
1299
- }
1300
- function tensionCurve(tracks, opts = {}) {
1301
- const ts = opts.ts ?? parseTimeSignature("4/4");
1302
- const profile = opts.profile ?? "pop";
1303
- const step = opts.step ?? 1;
1304
- if (!(step > 0)) {
1305
- throw new Error(`Invalid tension sampling step: ${step}`);
1306
- }
1307
- const pooled = poolNotes(tracks);
1308
- const totalBeats = pooled.reduce((end, n) => Math.max(end, n.startBeat + n.durationBeat), 0);
1309
- const { timeline, key } = chordTimelineFromNotes(pooled, {
1310
- key: opts.key,
1311
- ts,
1312
- harmonicRhythm: opts.harmonicRhythm
1313
- });
1314
- const prepared = prepareTracks(tracks);
1315
- const points = [];
1316
- const sampleCount = Math.max(0, Math.ceil(totalBeats / step - EPS3));
1317
- for (let i = 0; i < sampleCount; i += 1) {
1318
- const beat = i * step;
1319
- points.push({ beat, tension: sampleTension(prepared, timeline, key, ts, profile, beat) });
1320
- }
1321
- return points;
1322
- }
1323
- function allSounding(prepared, beat) {
1324
- const out = [];
1325
- for (let t = 0; t < prepared.length; t += 1) {
1326
- const track = prepared[t];
1327
- if (!track) {
1328
- continue;
1329
- }
1330
- for (const subVoice of track.voices) {
1331
- for (const note of subVoice.sounding) {
1332
- if (covers(note, beat)) {
1333
- out.push({ pitch: note.pitch, track: t });
1334
- }
1335
- }
1336
- }
1337
- }
1338
- return out;
1339
- }
1340
- function sampleTension(prepared, timeline, key, ts, profile, beat) {
1341
- const sounding = allSounding(prepared, beat);
1342
- if (sounding.length === 0) {
1343
- return 0;
1344
- }
1345
- const chord = timeline.at(beat);
1346
- const functionScore = chord ? FUNCTION_TENSION[functionOf(chord, key)] : 0;
1347
- const chordPcs = chord ? new Set(chordPitchClasses(chord)) : null;
1348
- const strongBeat = isStrongBeat(beat, ts);
1349
- let nonChord = 0;
1350
- let dissonant = 0;
1351
- for (let i = 0; i < sounding.length; i += 1) {
1352
- const voice = sounding[i];
1353
- if (!voice) {
1354
- continue;
1355
- }
1356
- if (chordPcs && !chordPcs.has(pitchClass7(voice.pitch))) {
1357
- nonChord += 1;
1358
- }
1359
- const others = sounding.filter((_, j) => j !== i).map((s) => ({ pitch: s.pitch }));
1360
- const result = evaluateSafety({
1361
- profile,
1362
- candidatePitch: voice.pitch,
1363
- chord,
1364
- key,
1365
- otherVoices: others,
1366
- strongBeat
1367
- });
1368
- if (result.safety === 2 /* Dissonant */) {
1369
- dissonant += 1;
1370
- }
1371
- }
1372
- const dissonanceScore = Math.max(nonChord, dissonant) / sounding.length;
1373
- let low = Number.POSITIVE_INFINITY;
1374
- let high = Number.NEGATIVE_INFINITY;
1375
- for (const voice of sounding) {
1376
- low = Math.min(low, voice.pitch);
1377
- high = Math.max(high, voice.pitch);
1378
- }
1379
- const spanScore = Math.min(1, (high - low) / SPAN_SATURATION);
1380
- return clamp01(
1381
- FUNCTION_WEIGHT * functionScore + DISSONANCE_WEIGHT * dissonanceScore + SPAN_WEIGHT * spanScore
1382
- );
1383
- }
1384
22
 
1385
- // src/analyze/voice/index.ts
1386
- var EPS4 = 1e-9;
1387
- function pitchClass8(pitch) {
1388
- return (Math.trunc(pitch) % 12 + 12) % 12;
1389
- }
1390
- function intervalAboveRoot2(pitch, chord) {
1391
- return ((pitchClass8(pitch) - pitchClass8(chord.rootPc)) % 12 + 12) % 12;
1392
- }
1393
- function intervalAboveBass(pitch, others, chord) {
1394
- let bass = Number.POSITIVE_INFINITY;
1395
- for (const ov of others) {
1396
- bass = Math.min(bass, ov.pitch);
1397
- }
1398
- if (Number.isFinite(bass) && bass < pitch) {
1399
- return ((pitch - bass) % 12 + 12) % 12;
1400
- }
1401
- const ref = chord.bassPc ?? chord.rootPc;
1402
- return ((pitchClass8(pitch) - pitchClass8(ref)) % 12 + 12) % 12;
1403
- }
1404
- function tensionDegree(ic) {
1405
- if (ic === 1 || ic === 2) {
1406
- return 9;
1407
- }
1408
- if (ic === 5 || ic === 6) {
1409
- return 11;
1410
- }
1411
- return 13;
1412
- }
1413
- function isChordMember2(pitch, chord) {
1414
- return chord ? chordPitchClasses(chord).includes(pitchClass8(pitch)) : false;
1415
- }
1416
- function isStep(a, b) {
1417
- const d = Math.abs(a - b);
1418
- return d === 1 || d === 2;
1419
- }
1420
- function suspensionType(ic, delta) {
1421
- let type;
1422
- if (delta > 0) {
1423
- type = "sus2-3";
1424
- } else if (ic === 2) {
1425
- type = "sus9-8";
1426
- } else if (ic === 10 || ic === 11) {
1427
- type = "sus7-6";
1428
- } else {
1429
- type = "sus4-3";
1430
- }
1431
- return { kind: "suspension", type, resolveTo: 0 };
1432
- }
1433
- function stepResolution2(pitch, chord) {
1434
- for (let delta = 1; delta <= 2; delta += 1) {
1435
- if (isChordMember2(pitch - delta, chord)) {
1436
- return pitch - delta;
1437
- }
1438
- }
1439
- return void 0;
1440
- }
1441
- function analyzeVoice(voice, chordAtBeat, key, otherVoicesAtBeat) {
1442
- const result = [];
1443
- for (let i = 0; i < voice.length; i += 1) {
1444
- const note = voice[i];
1445
- if (!note) {
1446
- continue;
1447
- }
1448
- const prevNote = i > 0 ? voice[i - 1] : void 0;
1449
- const nextNote = i + 1 < voice.length ? voice[i + 1] : void 0;
1450
- const prev = prevNote !== void 0 && prevNote.startBeat < note.startBeat - EPS4 ? prevNote : void 0;
1451
- const next = nextNote !== void 0 && nextNote.startBeat > note.startBeat + EPS4 ? nextNote : void 0;
1452
- const chord = chordAtBeat(note.startBeat);
1453
- const labels = [];
1454
- const member = isChordMember2(note.pitch, chord);
1455
- let handled = false;
1456
- if (chord && member) {
1457
- const role = chordToneRole(note.pitch, chord);
1458
- if (role) {
1459
- labels.push({ kind: "chordTone", role });
1460
- } else {
1461
- const ic = intervalAboveRoot2(note.pitch, chord);
1462
- labels.push({ kind: "tension", degree: tensionDegree(ic) });
1463
- }
1464
- handled = true;
1465
- }
1466
- if (!handled && chord && prev && next) {
1467
- const prevChord = chordAtBeat(prev.startBeat);
1468
- const prepared = prev.pitch === note.pitch && isChordMember2(prev.pitch, prevChord);
1469
- const resolves = isStep(next.pitch, note.pitch);
1470
- const others = otherVoicesAtBeat(note.startBeat);
1471
- const verticallyDissonant = others.some(
1472
- (ov) => createsVerticalDissonance(note.pitch, ov.pitch, true)
1473
- );
1474
- if (prepared && verticallyDissonant && resolves) {
1475
- const ic = intervalAboveBass(note.pitch, others, chord);
1476
- const sus = suspensionType(ic, next.pitch - note.pitch);
1477
- sus.resolveTo = next.pitch;
1478
- labels.push(sus);
1479
- handled = true;
1480
- }
1481
- }
1482
- if (!handled && chord && prev && next) {
1483
- const prevMember = isChordMember2(prev.pitch, chordAtBeat(prev.startBeat));
1484
- const nextMember = isChordMember2(next.pitch, chordAtBeat(next.startBeat));
1485
- const up = note.pitch - prev.pitch > 0;
1486
- const contInto = next.pitch - note.pitch > 0;
1487
- const sameDir = note.pitch !== prev.pitch && next.pitch !== note.pitch && up === contInto;
1488
- if (prevMember && nextMember && !member && isStep(note.pitch, prev.pitch) && isStep(next.pitch, note.pitch) && sameDir) {
1489
- labels.push({ kind: "passing" });
1490
- handled = true;
1491
- }
1492
- }
1493
- if (!handled && chord && prev && next && !member && prev.pitch === next.pitch && isChordMember2(prev.pitch, chordAtBeat(prev.startBeat)) && isStep(note.pitch, prev.pitch)) {
1494
- labels.push({ kind: "neighbor" });
1495
- handled = true;
1496
- }
1497
- if (!handled && chord && next && !member && note.pitch === next.pitch) {
1498
- const nextChord = chordAtBeat(next.startBeat);
1499
- if (isChordMember2(next.pitch, nextChord)) {
1500
- labels.push({ kind: "anticipation" });
1501
- handled = true;
1502
- }
1503
- }
1504
- if (!handled && chord && prev && next && !member) {
1505
- const prevMember = isChordMember2(prev.pitch, chordAtBeat(prev.startBeat));
1506
- const nextMember = isChordMember2(next.pitch, chordAtBeat(next.startBeat));
1507
- const stepFromPrev = isStep(note.pitch, prev.pitch);
1508
- const leapToNext = Math.abs(next.pitch - note.pitch) >= 3;
1509
- const opposite = note.pitch - prev.pitch > 0 !== next.pitch - note.pitch > 0;
1510
- if (prevMember && nextMember && stepFromPrev && leapToNext && opposite) {
1511
- labels.push({ kind: "escape" });
1512
- handled = true;
1513
- }
1514
- }
1515
- if (!handled && chord && !member) {
1516
- const ic = intervalAboveRoot2(note.pitch, chord);
1517
- const isTension = ic === 2 || ic === 5 || ic === 9;
1518
- const avoid = ic === 5 && chord.intervals.includes(4) && !chord.intervals.includes(5) || ic === 11 && chord.intervals.includes(4) && chord.intervals.includes(10);
1519
- if (avoid) {
1520
- labels.push({ kind: "avoid" });
1521
- const resolveTo = stepResolution2(note.pitch, chord);
1522
- if (resolveTo !== void 0) {
1523
- labels.push({ kind: "needsResolution", resolveTo });
1524
- }
1525
- } else if (isTension) {
1526
- labels.push({ kind: "tension", degree: tensionDegree(ic) });
1527
- } else {
1528
- const resolveTo = stepResolution2(note.pitch, chord);
1529
- if (resolveTo !== void 0) {
1530
- labels.push({ kind: "needsResolution", resolveTo });
1531
- }
1532
- }
1533
- }
1534
- if (next && isLeadingToneResolution(note.pitch, next.pitch, key)) {
1535
- labels.push({ kind: "leadingTone", resolveTo: next.pitch });
1536
- }
1537
- result.push({ noteId: note.id, labels, rationale: describe2(labels) });
1538
- }
1539
- return result;
1540
- }
1541
- function describe2(labels) {
1542
- const primary = labels[0];
1543
- if (!primary) {
1544
- return "Unclassified note";
1545
- }
1546
- switch (primary.kind) {
1547
- case "chordTone":
1548
- return `Chord ${primary.role}`;
1549
- case "tension":
1550
- return `${primary.degree}th tension`;
1551
- case "avoid":
1552
- return "Avoid note";
1553
- case "passing":
1554
- return "Passing tone between chord tones";
1555
- case "neighbor":
1556
- return "Neighbor tone";
1557
- case "suspension":
1558
- return `Suspension (${primary.type})`;
1559
- case "anticipation":
1560
- return "Anticipation of the next chord";
1561
- case "escape":
1562
- return "Escape tone";
1563
- case "needsResolution":
1564
- return "Unresolved dissonance";
1565
- case "leadingTone":
1566
- return "Leading tone resolving to the tonic";
1567
- }
1568
- }
1569
23
 
1570
- // src/analyze/arrange/tracks.ts
1571
- function otherVoicesSounding(prepared, excludeTrack, excludeVoice, beat) {
1572
- const out = [];
1573
- for (let t = 0; t < prepared.length; t += 1) {
1574
- const track = prepared[t];
1575
- if (!track) {
1576
- continue;
1577
- }
1578
- for (let v = 0; v < track.voices.length; v += 1) {
1579
- if (t === excludeTrack && v === excludeVoice) {
1580
- continue;
1581
- }
1582
- const subVoice = track.voices[v];
1583
- if (!subVoice) {
1584
- continue;
1585
- }
1586
- for (const note of subVoice.sounding) {
1587
- if (!covers(note, beat)) {
1588
- continue;
1589
- }
1590
- const snap = { pitch: note.pitch };
1591
- if (note.prevPitch !== void 0) {
1592
- snap.prevPitch = note.prevPitch;
1593
- }
1594
- out.push(snap);
1595
- }
1596
- }
1597
- }
1598
- return out;
1599
- }
1600
- function evaluationBeats(note, timeline) {
1601
- const noteEnd = note.startBeat + note.durationBeat;
1602
- const beats = [note.startBeat];
1603
- for (const segment of timeline.segments) {
1604
- if (segment.startBeat > note.startBeat + EPS3 && segment.startBeat < noteEnd - EPS3) {
1605
- beats.push(segment.startBeat);
1606
- }
1607
- }
1608
- return beats;
1609
- }
1610
- function analyzeArrangement(tracks, opts = {}) {
1611
- const ts = opts.ts ?? parseTimeSignature("4/4");
1612
- const profile = opts.profile ?? "pop";
1613
- const pooled = poolNotes(tracks);
1614
- const { timeline, key, segmentConfidence } = chordTimelineFromNotes(pooled, {
1615
- key: opts.key,
1616
- ts,
1617
- harmonicRhythm: opts.harmonicRhythm
1618
- });
1619
- const cadences = detectCadences(timeline, key);
1620
- const prepared = prepareTracks(tracks);
1621
- const trackAnalyses = [];
1622
- const conflicts = [];
1623
- for (let t = 0; t < prepared.length; t += 1) {
1624
- const track = prepared[t];
1625
- if (!track) {
1626
- continue;
1627
- }
1628
- const notes = [];
1629
- for (let v = 0; v < track.voices.length; v += 1) {
1630
- const subVoice = track.voices[v];
1631
- if (!subVoice) {
1632
- continue;
1633
- }
1634
- notes.push(
1635
- ...analyzeVoice(
1636
- subVoice.voice,
1637
- timeline.at,
1638
- key,
1639
- (beat) => otherVoicesSounding(prepared, t, v, beat)
1640
- )
1641
- );
1642
- for (const note of subVoice.voice) {
1643
- for (const beat of evaluationBeats(note, timeline)) {
1644
- const result = evaluateSafety({
1645
- profile,
1646
- candidatePitch: note.pitch,
1647
- chord: timeline.at(beat),
1648
- key,
1649
- otherVoices: otherVoicesSounding(prepared, t, v, beat),
1650
- strongBeat: isStrongBeat(beat, ts)
1651
- });
1652
- if (result.safety !== 0 /* Safe */) {
1653
- const conflict = {
1654
- beat,
1655
- trackName: track.name,
1656
- pitch: note.pitch,
1657
- safety: result.safety,
1658
- reasons: result.reasons
1659
- };
1660
- if (result.rationale !== void 0) {
1661
- conflict.rationale = result.rationale;
1662
- }
1663
- conflicts.push(conflict);
1664
- }
1665
- }
1666
- }
1667
- }
1668
- notes.sort((a, b) => a.noteId - b.noteId);
1669
- trackAnalyses.push({ name: track.name, role: track.role, notes });
1670
- }
1671
- conflicts.sort((a, b) => b.safety - a.safety || a.beat - b.beat);
1672
- return { key, timeline, segmentConfidence, cadences, tracks: trackAnalyses, conflicts };
1673
- }
1674
- // Annotate the CommonJS export names for ESM import in node:
1675
- 0 && (module.exports = {
1676
- analyzeArrangement,
1677
- analyzeChord,
1678
- analyzeVoice,
1679
- borrowedSource,
1680
- chordTimelineFromChords,
1681
- chordTimelineFromNotes,
1682
- chordToRoman,
1683
- detectCadence,
1684
- detectCadences,
1685
- detectChord,
1686
- detectChordBest,
1687
- detectKey,
1688
- functionOf,
1689
- isBorrowedChord,
1690
- isDiatonic,
1691
- isMinorKey,
1692
- parallelKey,
1693
- romanToChord,
1694
- secondaryDominant,
1695
- tensionCurve
1696
- });
24
+
25
+
26
+
27
+
28
+
29
+ var _chunkCAN76NCUcjs = require('../chunk-CAN76NCU.cjs');
30
+
31
+
32
+ var _chunkQ6OP4U43cjs = require('../chunk-Q6OP4U43.cjs');
33
+ require('../chunk-FNDWXRRI.cjs');
34
+ require('../chunk-7MGZ7D62.cjs');
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+ exports.NoteSafety = _chunkQ6OP4U43cjs.NoteSafety; exports.analyzeArrangement = _chunkRC6GBMCDcjs.analyzeArrangement; exports.analyzeChord = _chunkCAN76NCUcjs.analyzeChord; exports.analyzeVoice = _chunkRC6GBMCDcjs.analyzeVoice; exports.borrowedSource = _chunkCAN76NCUcjs.borrowedSource; exports.chordTimelineFromChords = _chunkRC6GBMCDcjs.chordTimelineFromChords; exports.chordTimelineFromNotes = _chunkRC6GBMCDcjs.chordTimelineFromNotes; exports.chordToRoman = _chunkCAN76NCUcjs.chordToRoman; exports.detectCadence = _chunkCAN76NCUcjs.detectCadence; exports.detectCadences = _chunkRC6GBMCDcjs.detectCadences; exports.detectChord = _chunkCAN76NCUcjs.detectChord; exports.detectChordBest = _chunkCAN76NCUcjs.detectChordBest; exports.detectKey = _chunkCAN76NCUcjs.detectKey; exports.detectKeyBest = _chunkCAN76NCUcjs.detectKeyBest; exports.detectKeyFromNotes = _chunkCAN76NCUcjs.detectKeyFromNotes; exports.functionOf = _chunkCAN76NCUcjs.functionOf; exports.isBorrowedChord = _chunkCAN76NCUcjs.isBorrowedChord; exports.isDiatonic = _chunkCAN76NCUcjs.isDiatonic; exports.isMinorKey = _chunkCAN76NCUcjs.isMinorKey; exports.parallelKey = _chunkCAN76NCUcjs.parallelKey; exports.romanToChord = _chunkCAN76NCUcjs.romanToChord; exports.secondaryDominant = _chunkCAN76NCUcjs.secondaryDominant; exports.tensionCurve = _chunkRC6GBMCDcjs.tensionCurve; exports.tensionCurveFrom = _chunkRC6GBMCDcjs.tensionCurveFrom; exports.toVoiceNotes = _chunkRC6GBMCDcjs.toVoiceNotes;
1697
62
  //# sourceMappingURL=index.cjs.map