@hyperscale0/hsx 2.4.0 → 3.0.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 (249) hide show
  1. package/CHANGELOG.md +2 -400
  2. package/README.md +3 -92
  3. package/dist/src/ast.d.ts +99 -310
  4. package/dist/src/ast.d.ts.map +1 -1
  5. package/dist/src/ast.js +16 -69
  6. package/dist/src/ast.js.map +1 -1
  7. package/dist/src/cli.d.ts +6 -19
  8. package/dist/src/cli.d.ts.map +1 -1
  9. package/dist/src/cli.js +76 -315
  10. package/dist/src/cli.js.map +1 -1
  11. package/dist/src/compile.d.ts +23 -73
  12. package/dist/src/compile.d.ts.map +1 -1
  13. package/dist/src/compile.js +1113 -148
  14. package/dist/src/compile.js.map +1 -1
  15. package/dist/src/cost.d.ts +8 -77
  16. package/dist/src/cost.d.ts.map +1 -1
  17. package/dist/src/cost.js +13 -422
  18. package/dist/src/cost.js.map +1 -1
  19. package/dist/src/format.d.ts +8 -7
  20. package/dist/src/format.d.ts.map +1 -1
  21. package/dist/src/format.js +9 -175
  22. package/dist/src/format.js.map +1 -1
  23. package/dist/src/headers.d.ts +35 -0
  24. package/dist/src/headers.d.ts.map +1 -0
  25. package/dist/src/headers.js +108 -0
  26. package/dist/src/headers.js.map +1 -0
  27. package/dist/src/index.d.ts +6 -12
  28. package/dist/src/index.d.ts.map +1 -1
  29. package/dist/src/index.js +4 -9
  30. package/dist/src/index.js.map +1 -1
  31. package/dist/src/lex.d.ts +8 -28
  32. package/dist/src/lex.d.ts.map +1 -1
  33. package/dist/src/lex.js +88 -146
  34. package/dist/src/lex.js.map +1 -1
  35. package/dist/src/parse.d.ts +4 -17
  36. package/dist/src/parse.d.ts.map +1 -1
  37. package/dist/src/parse.js +402 -1040
  38. package/dist/src/parse.js.map +1 -1
  39. package/dist/src/std-bundle.d.ts.map +1 -1
  40. package/dist/src/std-bundle.js +12 -20
  41. package/dist/src/std-bundle.js.map +1 -1
  42. package/dist/src/std-library.d.ts +1 -1
  43. package/dist/src/std-library.d.ts.map +1 -1
  44. package/dist/src/std-library.js +1 -5
  45. package/dist/src/std-library.js.map +1 -1
  46. package/dist/src/tunables.d.ts +7 -0
  47. package/dist/src/tunables.d.ts.map +1 -0
  48. package/dist/src/tunables.js +26 -0
  49. package/dist/src/tunables.js.map +1 -0
  50. package/dist/src/version.d.ts +2 -4
  51. package/dist/src/version.d.ts.map +1 -1
  52. package/dist/src/version.js +2 -4
  53. package/dist/src/version.js.map +1 -1
  54. package/docs/README.md +179 -41
  55. package/docs/headers.md +44 -0
  56. package/examples/cost-table.json +99 -751
  57. package/examples/library.hsx +59 -0
  58. package/package.json +9 -17
  59. package/src/ast.ts +82 -441
  60. package/src/cli.ts +77 -362
  61. package/src/compile.ts +1535 -247
  62. package/src/cost.ts +28 -671
  63. package/src/format.ts +12 -256
  64. package/src/headers.ts +126 -0
  65. package/src/index.ts +7 -39
  66. package/src/lex.ts +99 -195
  67. package/src/parse.ts +403 -1209
  68. package/src/std-bundle.ts +12 -20
  69. package/src/std-library.ts +2 -7
  70. package/src/tunables.ts +31 -0
  71. package/src/version.ts +2 -5
  72. package/std/approvals.hsx +17 -0
  73. package/std/cards.hsx +63 -0
  74. package/std/collections.hsx +31 -0
  75. package/std/escrow.hsx +43 -0
  76. package/std/financing.hsx +372 -0
  77. package/std/insurance.hsx +59 -0
  78. package/std/lending.hsx +115 -0
  79. package/std/marketplace.hsx +24 -0
  80. package/std/money.hsx +195 -0
  81. package/std/savings.hsx +44 -0
  82. package/std/travel.hsx +98 -0
  83. package/std/wallet.hsx +41 -0
  84. package/dist/src/diagnostics.d.ts +0 -13
  85. package/dist/src/diagnostics.d.ts.map +0 -1
  86. package/dist/src/diagnostics.js +0 -587
  87. package/dist/src/diagnostics.js.map +0 -1
  88. package/dist/src/emit.d.ts +0 -51
  89. package/dist/src/emit.d.ts.map +0 -1
  90. package/dist/src/emit.js +0 -192
  91. package/dist/src/emit.js.map +0 -1
  92. package/dist/src/entry-overrides.d.ts +0 -58
  93. package/dist/src/entry-overrides.d.ts.map +0 -1
  94. package/dist/src/entry-overrides.js +0 -284
  95. package/dist/src/entry-overrides.js.map +0 -1
  96. package/dist/src/ir.d.ts +0 -73
  97. package/dist/src/ir.d.ts.map +0 -1
  98. package/dist/src/ir.js +0 -15
  99. package/dist/src/ir.js.map +0 -1
  100. package/dist/src/limits.d.ts +0 -23
  101. package/dist/src/limits.d.ts.map +0 -1
  102. package/dist/src/limits.js +0 -23
  103. package/dist/src/limits.js.map +0 -1
  104. package/dist/src/lsp/server.d.ts +0 -32
  105. package/dist/src/lsp/server.d.ts.map +0 -1
  106. package/dist/src/lsp/server.js +0 -391
  107. package/dist/src/lsp/server.js.map +0 -1
  108. package/dist/src/modules.d.ts +0 -38
  109. package/dist/src/modules.d.ts.map +0 -1
  110. package/dist/src/modules.js +0 -372
  111. package/dist/src/modules.js.map +0 -1
  112. package/dist/src/typecheck.d.ts +0 -8
  113. package/dist/src/typecheck.d.ts.map +0 -1
  114. package/dist/src/typecheck.js +0 -4131
  115. package/dist/src/typecheck.js.map +0 -1
  116. package/docs/guide/01-first-program.md +0 -24
  117. package/docs/guide/02-money.md +0 -25
  118. package/docs/guide/03-instruments.md +0 -93
  119. package/docs/guide/04-lifecycles.md +0 -40
  120. package/docs/guide/05-fees-and-splits.md +0 -45
  121. package/docs/guide/06-schedules.md +0 -26
  122. package/docs/guide/07-composition.md +0 -52
  123. package/docs/guide/08-writing-a-module.md +0 -85
  124. package/docs/guide/09-cost.md +0 -24
  125. package/docs/guide/10-diagnostics.md +0 -27
  126. package/docs/llms-full.txt +0 -3684
  127. package/docs/llms.txt +0 -44
  128. package/docs/piece-plans.md +0 -120
  129. package/docs/playground.md +0 -55
  130. package/docs/reference/cli.md +0 -36
  131. package/docs/reference/diagnostics.md +0 -901
  132. package/docs/reference/grammar.md +0 -38
  133. package/docs/reference/std/advance.md +0 -112
  134. package/docs/reference/std/cancellable_booking.md +0 -159
  135. package/docs/reference/std/captured_payment.md +0 -115
  136. package/docs/reference/std/conditional_disbursement.md +0 -101
  137. package/docs/reference/std/credit_facility.md +0 -108
  138. package/docs/reference/std/held_payment.md +0 -173
  139. package/docs/reference/std/instant_transfer.md +0 -97
  140. package/docs/reference/std/metered.md +0 -89
  141. package/docs/reference/std/pooled_split.md +0 -95
  142. package/docs/reference/std/premium_forward.md +0 -119
  143. package/docs/reference/std/reconciled_payout.md +0 -103
  144. package/docs/reference/std/rotating_pool.md +0 -130
  145. package/docs/reference/std/scheduled.md +0 -136
  146. package/docs/reference/std/security_deposit.md +0 -138
  147. package/docs/reference/std/settlement_batch.md +0 -123
  148. package/docs/reference/std/swap.md +0 -133
  149. package/docs/reference/std/threshold_pool.md +0 -138
  150. package/docs/reference/std/weighted_distribution.md +0 -135
  151. package/docs/reference/types.md +0 -61
  152. package/docs/reference/udl-output.md +0 -13
  153. package/examples/01-first-program/README.md +0 -45
  154. package/examples/01-first-program/tip-jar.hsx +0 -17
  155. package/examples/02-imports-and-modules/README.md +0 -96
  156. package/examples/02-imports-and-modules/photo-booth.hsx +0 -37
  157. package/examples/03-diagnostics/README.md +0 -68
  158. package/examples/03-diagnostics/corner-shop-fixed.hsx +0 -22
  159. package/examples/03-diagnostics/corner-shop.hsx +0 -19
  160. package/examples/04-complete-product/README.md +0 -84
  161. package/examples/04-complete-product/study-hall.hsx +0 -67
  162. package/examples/05-authored-instrument/README.md +0 -5
  163. package/examples/05-authored-instrument/payment.hsx +0 -37
  164. package/examples/05-watch-club/README.md +0 -6
  165. package/examples/05-watch-club/watch-club.hsx +0 -123
  166. package/examples/README.md +0 -48
  167. package/examples/advance/README.md +0 -3
  168. package/examples/advance/advance.hsx +0 -13
  169. package/examples/advance/advance.udl +0 -367
  170. package/examples/cancellable_booking/README.md +0 -3
  171. package/examples/cancellable_booking/cancellable_booking.hsx +0 -14
  172. package/examples/cancellable_booking/cancellable_booking.udl +0 -413
  173. package/examples/captured_payment/README.md +0 -3
  174. package/examples/captured_payment/captured_payment.hsx +0 -17
  175. package/examples/captured_payment/captured_payment.udl +0 -686
  176. package/examples/conditional_disbursement/README.md +0 -3
  177. package/examples/conditional_disbursement/conditional_disbursement.hsx +0 -15
  178. package/examples/conditional_disbursement/conditional_disbursement.udl +0 -418
  179. package/examples/credit_facility/README.md +0 -3
  180. package/examples/credit_facility/credit_facility.hsx +0 -24
  181. package/examples/credit_facility/credit_facility.udl +0 -1396
  182. package/examples/held_payment/README.md +0 -3
  183. package/examples/held_payment/held_payment.hsx +0 -13
  184. package/examples/held_payment/held_payment.udl +0 -569
  185. package/examples/instant_transfer/README.md +0 -3
  186. package/examples/instant_transfer/instant_transfer.hsx +0 -16
  187. package/examples/instant_transfer/instant_transfer.udl +0 -376
  188. package/examples/metered/README.md +0 -3
  189. package/examples/metered/metered.hsx +0 -13
  190. package/examples/metered/metered.udl +0 -253
  191. package/examples/pooled_split/README.md +0 -3
  192. package/examples/pooled_split/pooled_split.hsx +0 -15
  193. package/examples/pooled_split/pooled_split.udl +0 -432
  194. package/examples/premium_forward/README.md +0 -3
  195. package/examples/premium_forward/premium_forward.hsx +0 -19
  196. package/examples/premium_forward/premium_forward.udl +0 -604
  197. package/examples/reconciled_payout/README.md +0 -3
  198. package/examples/reconciled_payout/reconciled_payout.hsx +0 -13
  199. package/examples/reconciled_payout/reconciled_payout.udl +0 -312
  200. package/examples/rotating_pool/README.md +0 -3
  201. package/examples/rotating_pool/rotating_pool.hsx +0 -18
  202. package/examples/rotating_pool/rotating_pool.udl +0 -4370
  203. package/examples/scheduled/README.md +0 -3
  204. package/examples/scheduled/scheduled.hsx +0 -12
  205. package/examples/scheduled/scheduled.udl +0 -355
  206. package/examples/security_deposit/README.md +0 -3
  207. package/examples/security_deposit/security_deposit.hsx +0 -21
  208. package/examples/security_deposit/security_deposit.udl +0 -320
  209. package/examples/settlement_batch/README.md +0 -3
  210. package/examples/settlement_batch/settlement_batch.hsx +0 -19
  211. package/examples/settlement_batch/settlement_batch.udl +0 -757
  212. package/examples/swap/README.md +0 -3
  213. package/examples/swap/swap.hsx +0 -19
  214. package/examples/swap/swap.udl +0 -892
  215. package/examples/threshold_pool/README.md +0 -3
  216. package/examples/threshold_pool/threshold_pool.hsx +0 -16
  217. package/examples/threshold_pool/threshold_pool.udl +0 -680
  218. package/examples/weighted_distribution/README.md +0 -3
  219. package/examples/weighted_distribution/weighted_distribution.hsx +0 -20
  220. package/examples/weighted_distribution/weighted_distribution.udl +0 -348
  221. package/skills/hsx/SKILL.md +0 -449
  222. package/src/diagnostics.ts +0 -620
  223. package/src/emit.ts +0 -282
  224. package/src/entry-overrides.ts +0 -428
  225. package/src/ir.ts +0 -113
  226. package/src/limits.ts +0 -22
  227. package/src/lsp/server.ts +0 -460
  228. package/src/modules.ts +0 -452
  229. package/src/typecheck.ts +0 -5381
  230. package/std/SEMANTICS.md +0 -44
  231. package/std/money_flows/advance.hsx +0 -235
  232. package/std/money_flows/cancellable_booking.hsx +0 -402
  233. package/std/money_flows/captured_payment.hsx +0 -220
  234. package/std/money_flows/conditional_disbursement.hsx +0 -226
  235. package/std/money_flows/credit_facility.hsx +0 -214
  236. package/std/money_flows/held_payment.hsx +0 -812
  237. package/std/money_flows/index.hsx +0 -4
  238. package/std/money_flows/instant_transfer.hsx +0 -231
  239. package/std/money_flows/metered.hsx +0 -104
  240. package/std/money_flows/pooled_split.hsx +0 -109
  241. package/std/money_flows/premium_forward.hsx +0 -307
  242. package/std/money_flows/reconciled_payout.hsx +0 -119
  243. package/std/money_flows/rotating_pool.hsx +0 -305
  244. package/std/money_flows/scheduled.hsx +0 -599
  245. package/std/money_flows/security_deposit.hsx +0 -248
  246. package/std/money_flows/settlement_batch.hsx +0 -173
  247. package/std/money_flows/swap.hsx +0 -1192
  248. package/std/money_flows/threshold_pool.hsx +0 -307
  249. package/std/money_flows/weighted_distribution.hsx +0 -237
package/src/emit.ts DELETED
@@ -1,282 +0,0 @@
1
- import {
2
- validateUdl,
3
- resolveUdlActionPlans,
4
- udlClauseVocabulary,
5
- type UdlDocument,
6
- type UdlIssueCode,
7
- } from "@hyperscale0/udl";
8
- import type {
9
- JsonValue,
10
- TypedInstrument,
11
- TypedProgram,
12
- ResolvedProgramActionPlan,
13
- } from "./ir.ts";
14
-
15
- import { hsxClauseDiagnosticCode } from "./diagnostics.ts";
16
-
17
- export interface OriginMapEntry {
18
- readonly path: string;
19
- readonly span: { readonly end: number; readonly start: number };
20
- }
21
-
22
- export interface GeneralLoweringIssue {
23
- readonly code: string;
24
- readonly fix: string;
25
- readonly message: string;
26
- readonly path: string;
27
- readonly span: { readonly end: number; readonly start: number };
28
- readonly udlCode: UdlIssueCode;
29
- }
30
-
31
- export type GeneralLowerResult =
32
- | { readonly issues: readonly GeneralLoweringIssue[]; readonly ok: false }
33
- | {
34
- readonly ok: true;
35
- readonly value: {
36
- readonly document: UdlDocument;
37
- readonly actionPlans?: readonly ResolvedProgramActionPlan[];
38
- readonly originMap: readonly OriginMapEntry[];
39
- };
40
- };
41
-
42
- export function lowerGeneralProgram(program: TypedProgram): GeneralLowerResult {
43
- const candidate = {
44
- instruments: program.instruments.map(generalInstrumentValue),
45
- product: program.name,
46
- subjects: program.subjects.map((subject) => ({
47
- declaredValue: subject.declaredValue,
48
- kind: subject.kind,
49
- schema: subject.schema,
50
- title: subject.title,
51
- version: subject.version,
52
- })),
53
- title: program.title,
54
- udl: 1,
55
- version: 1,
56
- };
57
- const unresolved = unresolvedCompilerMarkers(candidate);
58
- if (unresolved.length > 0) {
59
- const origins = originMapFor(program);
60
- return {
61
- issues: unresolved.map(({ marker, path }) => ({
62
- code: "HSX1603",
63
- fix: "correct the compile-time block keys or parameter bindings",
64
- message: `${path}: emitted value contains unresolved compiler marker ${marker}`,
65
- path,
66
- span: originForUdlPath(path, origins)?.span ?? program.origin,
67
- udlCode: "UDL1003",
68
- })),
69
- ok: false,
70
- };
71
- }
72
- const validation = validateUdl(candidate, {
73
- requireDecisionPartyBindings: true,
74
- });
75
- if (!validation.ok) {
76
- const origins = originMapFor(program);
77
- return {
78
- issues: validation.issues.map((issue) => {
79
- const origin = originForUdlPath(issue.path, origins);
80
- return {
81
- code:
82
- issue.category === "invalid_semantics"
83
- ? hsxClauseDiagnosticCode(issue.code)
84
- : "HSX1601",
85
- fix: issue.fix,
86
- message: `${issue.path}: ${issue.message}`,
87
- path: issue.path,
88
- span: origin?.span ?? program.origin,
89
- udlCode: issue.code,
90
- };
91
- }),
92
- ok: false,
93
- };
94
- }
95
- const document = validation.value;
96
- const actionPlans = document.instruments.flatMap((instrument) =>
97
- resolveUdlActionPlans(instrument).plans.map((plan) => ({
98
- ...plan,
99
- instrument: instrument.id,
100
- })),
101
- );
102
- return {
103
- ok: true,
104
- value: {
105
- document,
106
- ...(actionPlans.length > 0 ? { actionPlans } : {}),
107
- originMap: originMapFor(program),
108
- },
109
- };
110
- }
111
-
112
- const COMPILER_MARKERS = ["__hsx_none__", "invalid_compile_time_name"] as const;
113
-
114
- function unresolvedCompilerMarkers(
115
- value: unknown,
116
- path = "$",
117
- ): readonly { readonly marker: string; readonly path: string }[] {
118
- if (typeof value === "string") {
119
- return COMPILER_MARKERS.filter((marker) => value.includes(marker)).map(
120
- (marker) => ({ marker, path }),
121
- );
122
- }
123
- if (Array.isArray(value)) {
124
- return value.flatMap((item, index) =>
125
- unresolvedCompilerMarkers(item, `${path}[${index}]`),
126
- );
127
- }
128
- if (!value || typeof value !== "object") return [];
129
- return Object.entries(value).flatMap(([key, item]) => {
130
- const childPath = /^[A-Za-z_][A-Za-z0-9_]*$/.test(key)
131
- ? `${path}.${key}`
132
- : `${path}[${JSON.stringify(key)}]`;
133
- const keyIssues = COMPILER_MARKERS.filter((marker) =>
134
- key.includes(marker),
135
- ).map((marker) => ({ marker, path: childPath }));
136
- return [...keyIssues, ...unresolvedCompilerMarkers(item, childPath)];
137
- });
138
- }
139
-
140
- export function originForUdlPath<T extends { readonly path: string }>(
141
- path: string,
142
- origins: readonly T[],
143
- ): T | undefined {
144
- let longestMatch: T | undefined;
145
- let longestLength = -1;
146
- let rootFallback: T | undefined;
147
-
148
- for (let i = 0; i < origins.length; i += 1) {
149
- const entry = origins[i]!;
150
- const entryPath = entry.path;
151
- if (rootFallback === undefined && entryPath === "$") {
152
- rootFallback = entry;
153
- }
154
- const entryLen = entryPath.length;
155
- if (
156
- path === entryPath ||
157
- (path.length > entryLen &&
158
- (path.charCodeAt(entryLen) === 46 ||
159
- path.charCodeAt(entryLen) === 91) &&
160
- path.startsWith(entryPath))
161
- ) {
162
- if (entryLen > longestLength) {
163
- longestMatch = entry;
164
- longestLength = entryLen;
165
- }
166
- }
167
- }
168
-
169
- return longestMatch ?? rootFallback;
170
- }
171
-
172
- export function requiredFields(instrument: TypedInstrument): string[] {
173
- const explicit = instrument.slots.required;
174
- if (
175
- Array.isArray(explicit) &&
176
- explicit.every((field): field is string => typeof field === "string")
177
- ) {
178
- return [...explicit];
179
- }
180
- const required = new Set(
181
- instrument.fields
182
- .filter((field) => field.required)
183
- .map((field) => field.name),
184
- );
185
- const partyFields =
186
- instrument.slots.parties &&
187
- typeof instrument.slots.parties === "object" &&
188
- !Array.isArray(instrument.slots.parties)
189
- ? Object.values(instrument.slots.parties).filter(
190
- (value): value is string =>
191
- typeof value === "string" && required.has(value),
192
- )
193
- : [];
194
- return [
195
- ...new Set(partyFields),
196
- ...instrument.fields
197
- .map((field) => field.name)
198
- .filter((name) => required.has(name) && !partyFields.includes(name)),
199
- ];
200
- }
201
-
202
- function originMapFor(program: TypedProgram): OriginMapEntry[] {
203
- const entries: OriginMapEntry[] = [{ path: "$", span: program.origin }];
204
- program.subjects.forEach((subject, index) => {
205
- entries.push({ path: `$.subjects[${index}]`, span: subject.origin });
206
- });
207
- program.instruments.forEach((instrument, index) => {
208
- const base = `$.instruments[${index}]`;
209
- entries.push({ path: base, span: instrument.origin });
210
- instrument.fields.forEach((field) => {
211
- entries.push({
212
- path: `${base}.fields.${field.name}`,
213
- span: field.origin,
214
- });
215
- });
216
- instrument.actions.forEach((action) => {
217
- entries.push({
218
- path: `${base}.actions.${action.name}`,
219
- span: action.origin,
220
- });
221
- });
222
- });
223
- return entries;
224
- }
225
-
226
- /** Emit a canonical clause value through the same generic HSX block syntax. */
227
- export function emitUdlClause(
228
- scope: "instrument" | "action",
229
- target: string,
230
- value: JsonValue,
231
- ): string {
232
- const clause = udlClauseVocabulary.find(
233
- (entry) => entry.scope === scope && entry.target === target,
234
- );
235
- if (!clause) throw new Error(`Unknown ${scope} clause ${target}`);
236
- return `${clause.spelling.replaceAll(" ", "_")}: ${clauseLiteral(value)};`;
237
- }
238
-
239
- function clauseLiteral(value: JsonValue): string {
240
- if (Array.isArray(value)) return `[${value.map(clauseLiteral).join(", ")}]`;
241
- if (value !== null && typeof value === "object") {
242
- return `{ ${Object.entries(value)
243
- .map(([key, item]) => `${JSON.stringify(key)}: ${clauseLiteral(item)};`)
244
- .join(" ")} }`;
245
- }
246
- if (
247
- value === null ||
248
- (typeof value === "number" && !Number.isSafeInteger(value))
249
- ) {
250
- throw new Error(
251
- "HSX clause literals require non-null values and safe integers",
252
- );
253
- }
254
- return JSON.stringify(value);
255
- }
256
-
257
- export function hasActionPlanClauses(instrument: TypedInstrument): boolean {
258
- return (
259
- instrument.slots.piecePlan !== undefined ||
260
- instrument.slots.actionLibrary !== undefined ||
261
- instrument.actions.some(
262
- (action) =>
263
- action.slots.calls !== undefined ||
264
- action.slots.pieceStage !== undefined,
265
- )
266
- );
267
- }
268
-
269
- export function generalInstrumentValue(instrument: TypedInstrument) {
270
- return {
271
- ...instrument.slots,
272
- actionOrder: instrument.actions.map((action) => action.name),
273
- actions: Object.fromEntries(
274
- instrument.actions.map((action) => [action.name, action.slots]),
275
- ),
276
- fields: Object.fromEntries(
277
- instrument.fields.map((field) => [field.name, field.schema]),
278
- ),
279
- id: instrument.id,
280
- required: requiredFields(instrument),
281
- };
282
- }
@@ -1,428 +0,0 @@
1
- /**
2
- * Data-driven replacement of existing settlement entries. This is not syntax:
3
- * callers select a slot that already exists in the parsed program, replace its
4
- * literal value, then run the ordinary general compiler again.
5
- */
6
-
7
- import type {
8
- BlockExpr,
9
- Entry,
10
- Expr,
11
- InstrumentApplyDecl,
12
- Program,
13
- } from "./ast.ts";
14
-
15
- export type ProgramEntryOverrideValue =
16
- | { readonly kind: "integer"; readonly value: number }
17
- | { readonly kind: "basis_points"; readonly value: number }
18
- | {
19
- readonly currency: string;
20
- readonly kind: "money";
21
- readonly value: number;
22
- }
23
- | { readonly kind: "duration"; readonly value: string };
24
-
25
- export type ProgramEntryOverrideBounds =
26
- | { readonly max: number; readonly min: number }
27
- | {
28
- readonly currency: string;
29
- readonly max: number;
30
- readonly min: number;
31
- }
32
- | { readonly max: string; readonly min: string };
33
-
34
- export interface ProgramEntryOverride {
35
- readonly bounds: ProgramEntryOverrideBounds;
36
- readonly settlement: string;
37
- /** Entry keys below the settlement body, for example `["fees", "merchant"]`. */
38
- readonly path: readonly [string, ...string[]];
39
- readonly value: ProgramEntryOverrideValue;
40
- }
41
-
42
- export interface ProgramEntryOverrideIssue {
43
- readonly code:
44
- | "invalid_bounds"
45
- | "invalid_target"
46
- | "invalid_value"
47
- | "missing_settlement";
48
- readonly message: string;
49
- readonly settlement: string;
50
- readonly path: readonly string[];
51
- }
52
-
53
- type OverrideResult =
54
- | {
55
- readonly ok: true;
56
- readonly program: Program;
57
- }
58
- | {
59
- readonly issues: readonly ProgramEntryOverrideIssue[];
60
- readonly ok: false;
61
- };
62
-
63
- function percentRaw(bps: number): string {
64
- const whole = Math.floor(bps / 100);
65
- const fraction = bps % 100;
66
- return fraction === 0
67
- ? `${whole}`
68
- : `${whole}.${String(fraction).padStart(2, "0").replace(/0$/, "")}`;
69
- }
70
-
71
- function durationMagnitude(
72
- value: string,
73
- ): { readonly amount: number; readonly family: "days" | "months" } | undefined {
74
- const match = /^P([1-9][0-9]{0,3})([DWMY])$/.exec(value);
75
- if (!match) return undefined;
76
- const amount = Number(match[1]);
77
- switch (match[2]) {
78
- case "D":
79
- return { amount, family: "days" };
80
- case "W":
81
- return { amount: amount * 7, family: "days" };
82
- case "M":
83
- return { amount, family: "months" };
84
- case "Y":
85
- return { amount: amount * 12, family: "months" };
86
- default:
87
- return undefined;
88
- }
89
- }
90
-
91
- function replacementExpr(
92
- current: Expr,
93
- value: ProgramEntryOverrideValue,
94
- ): { readonly expr?: Expr; readonly issue?: string } {
95
- if (value.kind === "integer") {
96
- return current.kind === "number"
97
- ? {
98
- expr: {
99
- kind: "number",
100
- raw: String(value.value),
101
- span: current.span,
102
- },
103
- }
104
- : { issue: "target is not an integer literal" };
105
- }
106
- if (value.kind === "basis_points") {
107
- return current.kind === "percent"
108
- ? {
109
- expr: {
110
- bps: value.value,
111
- kind: "percent",
112
- raw: percentRaw(value.value),
113
- span: current.span,
114
- },
115
- }
116
- : { issue: "target is not a percentage literal" };
117
- }
118
- if (value.kind === "duration") {
119
- return current.kind === "ident" && durationMagnitude(current.name)
120
- ? {
121
- expr: { kind: "ident", name: value.value, span: current.span },
122
- }
123
- : { issue: "target is not an ISO-8601 duration literal" };
124
- }
125
- if (
126
- current.kind !== "binding" ||
127
- current.type.kind !== "call" ||
128
- current.type.callee.name !== "money" ||
129
- current.type.args.length !== 2 ||
130
- current.type.args[0]?.kind !== "ident" ||
131
- current.type.args[1]?.kind !== "number"
132
- ) {
133
- return { issue: "target is not a fixed money literal" };
134
- }
135
- if (current.type.args[0].name !== value.currency) {
136
- return {
137
- issue: `target currency ${current.type.args[0].name} does not match ${value.currency}`,
138
- };
139
- }
140
- return {
141
- expr: {
142
- ...current,
143
- type: {
144
- ...current.type,
145
- args: [
146
- current.type.args[0],
147
- {
148
- kind: "number",
149
- raw: String(value.value),
150
- span: current.type.args[1].span,
151
- },
152
- ],
153
- },
154
- },
155
- };
156
- }
157
-
158
- function selectedEntry(
159
- block: BlockExpr,
160
- path: readonly string[],
161
- ):
162
- | {
163
- readonly match: { readonly entry: Entry; readonly index: number };
164
- readonly tail: readonly string[];
165
- }
166
- | { readonly issue: string } {
167
- const [head, ...tail] = path;
168
- const matches = block.entries
169
- .map((entry, index) => ({ entry, index }))
170
- .filter(({ entry }) => entry.key.name === head);
171
- if (matches.length === 0) return { issue: `entry ${head} does not exist` };
172
- if (matches.length === 1) return { match: matches[0]!, tail };
173
- const occurrence = Number(tail[0]);
174
- if (!Number.isInteger(occurrence) || occurrence < 0) {
175
- return { issue: `entry ${head} is ambiguous` };
176
- }
177
- const match = matches[occurrence];
178
- return match
179
- ? { match, tail: tail.slice(1) }
180
- : { issue: `entry ${head} occurrence ${occurrence} does not exist` };
181
- }
182
-
183
- function replaceEntry(
184
- block: BlockExpr,
185
- path: readonly string[],
186
- value: ProgramEntryOverrideValue,
187
- ): { readonly block?: BlockExpr; readonly issue?: string } {
188
- const selected = selectedEntry(block, path);
189
- if (!("match" in selected)) return selected;
190
- const { match, tail } = selected;
191
- let nextEntry: Entry;
192
- if (tail.length === 0) {
193
- const replacement = replacementExpr(match.entry.value, value);
194
- if (!replacement.expr) return replacement;
195
- nextEntry = {
196
- ...match.entry,
197
- value: replacement.expr,
198
- };
199
- } else if (
200
- tail.length === 1 &&
201
- tail[0] === "within" &&
202
- match.entry.value.kind === "port_ref" &&
203
- match.entry.value.within
204
- ) {
205
- const replacement = replacementExpr(match.entry.value.within, value);
206
- if (!replacement.expr || replacement.expr.kind !== "ident") {
207
- return replacement;
208
- }
209
- nextEntry = {
210
- ...match.entry,
211
- value: { ...match.entry.value, within: replacement.expr },
212
- };
213
- } else {
214
- if (match.entry.value.kind !== "block") {
215
- return { issue: `entry ${match.entry.key.name} is not a block` };
216
- }
217
- const nested = replaceEntry(match.entry.value, tail, value);
218
- if (!nested.block) return nested;
219
- nextEntry = { ...match.entry, value: nested.block };
220
- }
221
-
222
- return {
223
- block: {
224
- ...block,
225
- entries: block.entries.map((entry, index) =>
226
- index === match.index ? nextEntry : entry,
227
- ),
228
- },
229
- };
230
- }
231
-
232
- function settlementByName(
233
- program: Program,
234
- name: string,
235
- ): InstrumentApplyDecl | undefined {
236
- return program.decls.find(
237
- (decl): decl is InstrumentApplyDecl =>
238
- decl.kind === "instrument_apply" && decl.name.name === name,
239
- );
240
- }
241
-
242
- function applicationBody(settlement: InstrumentApplyDecl): BlockExpr {
243
- return {
244
- entries: settlement.application.args.flatMap((argument) =>
245
- argument.kind === "binding"
246
- ? [
247
- {
248
- key: argument.name,
249
- qualifiers: [],
250
- span: argument.span,
251
- value: argument.type,
252
- },
253
- ]
254
- : [],
255
- ),
256
- kind: "block",
257
- span: settlement.application.span,
258
- };
259
- }
260
-
261
- function validateOverride(
262
- override: ProgramEntryOverride,
263
- ): ProgramEntryOverrideIssue | undefined {
264
- const { max, min } = override.bounds;
265
- if (override.value.kind === "duration") {
266
- if (typeof min !== "string" || typeof max !== "string") {
267
- return issue(
268
- override,
269
- "invalid_bounds",
270
- "duration bounds must be ISO-8601 durations",
271
- );
272
- }
273
- const minDuration = durationMagnitude(min);
274
- const maxDuration = durationMagnitude(max);
275
- if (
276
- !minDuration ||
277
- !maxDuration ||
278
- minDuration.family !== maxDuration.family ||
279
- minDuration.amount > maxDuration.amount
280
- ) {
281
- return issue(
282
- override,
283
- "invalid_bounds",
284
- `duration bounds ${min}..${max} must be valid, comparable, and ordered`,
285
- );
286
- }
287
- const value = durationMagnitude(override.value.value);
288
- if (
289
- !value ||
290
- value.family !== minDuration.family ||
291
- value.amount < minDuration.amount ||
292
- value.amount > maxDuration.amount
293
- ) {
294
- return issue(
295
- override,
296
- "invalid_value",
297
- `override value ${override.value.value} is outside ${min}..${max}`,
298
- );
299
- }
300
- return undefined;
301
- }
302
- if (typeof min !== "number" || typeof max !== "number") {
303
- return issue(
304
- override,
305
- "invalid_bounds",
306
- "numeric bounds must be finite nonnegative integers",
307
- );
308
- }
309
- if (
310
- !Number.isFinite(min) ||
311
- !Number.isInteger(min) ||
312
- min < 0 ||
313
- !Number.isFinite(max) ||
314
- !Number.isInteger(max) ||
315
- max < min
316
- ) {
317
- return issue(
318
- override,
319
- "invalid_bounds",
320
- `override bounds ${min}..${max} must be finite nonnegative integers with min at most max`,
321
- );
322
- }
323
-
324
- const { value } = override.value;
325
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {
326
- return issue(
327
- override,
328
- "invalid_value",
329
- `override value ${value} must be a finite nonnegative integer`,
330
- );
331
- }
332
- if (value < min || value > max) {
333
- return issue(
334
- override,
335
- "invalid_value",
336
- `override value ${value} is outside ${min}..${max}`,
337
- );
338
- }
339
- if (override.value.kind === "money") {
340
- const boundsCurrency =
341
- "currency" in override.bounds ? override.bounds.currency : undefined;
342
- if (!boundsCurrency || boundsCurrency !== override.value.currency) {
343
- return issue(
344
- override,
345
- "invalid_bounds",
346
- `money bounds must use currency ${override.value.currency}`,
347
- );
348
- }
349
- }
350
- }
351
-
352
- function issue(
353
- override: ProgramEntryOverride,
354
- code: ProgramEntryOverrideIssue["code"],
355
- message: string,
356
- ): ProgramEntryOverrideIssue {
357
- return {
358
- code,
359
- message,
360
- path: override.path,
361
- settlement: override.settlement,
362
- };
363
- }
364
-
365
- /**
366
- * Applies every override atomically. A missing or non-literal slot returns
367
- * issues and no program, so callers never lower a partially configured shape.
368
- */
369
- export function overrideProgramEntries(
370
- program: Program,
371
- overrides: readonly ProgramEntryOverride[],
372
- ): OverrideResult {
373
- let current = program;
374
- const issues: ProgramEntryOverrideIssue[] = [];
375
- for (const override of overrides) {
376
- const validationIssue = validateOverride(override);
377
- if (validationIssue) {
378
- issues.push(validationIssue);
379
- continue;
380
- }
381
- const settlement = settlementByName(current, override.settlement);
382
- if (!settlement) {
383
- issues.push({
384
- code: "missing_settlement",
385
- message: `settlement ${override.settlement} does not exist`,
386
- path: override.path,
387
- settlement: override.settlement,
388
- });
389
- continue;
390
- }
391
- const replaced = replaceEntry(
392
- applicationBody(settlement),
393
- override.path,
394
- override.value,
395
- );
396
- if (!replaced.block) {
397
- issues.push({
398
- code: "invalid_target",
399
- message: replaced.issue ?? "entry override failed",
400
- path: override.path,
401
- settlement: override.settlement,
402
- });
403
- continue;
404
- }
405
- current = {
406
- ...current,
407
- decls: current.decls.map((decl) =>
408
- decl === settlement
409
- ? {
410
- ...settlement,
411
- application: {
412
- ...settlement.application,
413
- args: replaced.block!.entries.map((entry) => ({
414
- kind: "binding" as const,
415
- name: entry.key,
416
- span: entry.span,
417
- type: entry.value,
418
- })),
419
- },
420
- }
421
- : decl,
422
- ),
423
- };
424
- }
425
- return issues.length > 0
426
- ? { issues, ok: false }
427
- : { ok: true, program: current };
428
- }