@xo-cash/utils 0.0.3-development.15864499577 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -81
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -181
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -3,86 +3,6 @@ import { XOInvitationVariableValue, XOTemplate } from "@xo-cash/types";
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { $ZodIssue } from "zod/v4/core";
|
|
5
5
|
|
|
6
|
-
//#region source/event-emitter.d.ts
|
|
7
|
-
type EventMap = Record<string, unknown>;
|
|
8
|
-
type Listener<T> = (detail: T) => void;
|
|
9
|
-
/**
|
|
10
|
-
* Callback returned by {@link on} and {@link once} for removing a listener.
|
|
11
|
-
*/
|
|
12
|
-
type OffCallback = () => void;
|
|
13
|
-
/**
|
|
14
|
-
* A simple event emitter implementation.
|
|
15
|
-
* @template T - The event map type.
|
|
16
|
-
*/
|
|
17
|
-
declare class EventEmitter<T extends EventMap> {
|
|
18
|
-
#private;
|
|
19
|
-
/**
|
|
20
|
-
* Add a listener for an event.
|
|
21
|
-
* @param type - The event type.
|
|
22
|
-
* @param listener - The listener function.
|
|
23
|
-
* @param debounceMilliseconds - The debounce time in milliseconds.
|
|
24
|
-
* @returns An off callback that can be called to stop listening for events.
|
|
25
|
-
*/
|
|
26
|
-
on<K extends keyof T>(type: K, listener: Listener<T[K]>, debounceMilliseconds?: number): OffCallback;
|
|
27
|
-
/**
|
|
28
|
-
* Add a one-time listener for an event.
|
|
29
|
-
* @param type - The event type.
|
|
30
|
-
* @param listener - The listener function.
|
|
31
|
-
* @param debounceMilliseconds - The debounce time in milliseconds.
|
|
32
|
-
* @returns An off callback that can be called to stop listening for events.
|
|
33
|
-
*/
|
|
34
|
-
once<K extends keyof T>(type: K, listener: Listener<T[K]>, debounceMilliseconds?: number): OffCallback;
|
|
35
|
-
/**
|
|
36
|
-
* Remove a listener for an event.
|
|
37
|
-
* @param type - The event type.
|
|
38
|
-
* @param listener - The listener function.
|
|
39
|
-
*/
|
|
40
|
-
off<K extends keyof T>(type: K, listener?: Listener<T[K]>): void;
|
|
41
|
-
/**
|
|
42
|
-
* Emit an event.
|
|
43
|
-
*
|
|
44
|
-
* @remarks The caller is responsible for ensuring the payload suits the intended mutability requirements.
|
|
45
|
-
* By default, the payload will be mutable, so listeners may mutate the payload, effecting both
|
|
46
|
-
* the original object and the other listeners.
|
|
47
|
-
* To prevent this, the caller can use the {@link Object.freeze} or {@link deepFreeze} function to freeze the payload.
|
|
48
|
-
* This will need to be defined in the EventMap using the built-in {@link Readonly} type or the provided {@link DeeplyReadonly} type.
|
|
49
|
-
*
|
|
50
|
-
* @param type - The event type.
|
|
51
|
-
* @param payload - The event payload.
|
|
52
|
-
* @returns True if there are listeners for the event, false otherwise.
|
|
53
|
-
*/
|
|
54
|
-
emit<K extends keyof T>(type: K, payload: T[K]): boolean;
|
|
55
|
-
/**
|
|
56
|
-
* Remove all listeners.
|
|
57
|
-
*/
|
|
58
|
-
removeAllListeners(): void;
|
|
59
|
-
/**
|
|
60
|
-
* Wait for an event to be emitted that matches the provided predicate function's criteria.
|
|
61
|
-
* @param type - The event type.
|
|
62
|
-
* @param predicate - Predicate function to filter for whether the event payload matches the criteria.
|
|
63
|
-
* @param timeoutMs - The timeout in milliseconds.
|
|
64
|
-
* @returns The event payload.
|
|
65
|
-
*/
|
|
66
|
-
waitFor<K extends keyof T>(type: K, predicate: (payload: T[K]) => boolean, timeoutMs?: number): Promise<T[K]>;
|
|
67
|
-
/**
|
|
68
|
-
* Debounce a function.
|
|
69
|
-
*
|
|
70
|
-
* @remarks If {@link off} is called on a listener while it is debounced, the timeout is not cleared with clearTimeout.
|
|
71
|
-
* Instead, the function is no-oped.
|
|
72
|
-
*
|
|
73
|
-
* @param func - The function to debounce.
|
|
74
|
-
* @param wait - The wait time in milliseconds.
|
|
75
|
-
* @returns The debounced function.
|
|
76
|
-
*/
|
|
77
|
-
private debounce;
|
|
78
|
-
/**
|
|
79
|
-
* Make a function cancellable.
|
|
80
|
-
* @param func - The function to make cancelable.
|
|
81
|
-
* @returns The cancellable function with a cancel method.
|
|
82
|
-
*/
|
|
83
|
-
private cancellable;
|
|
84
|
-
}
|
|
85
|
-
//#endregion
|
|
86
6
|
//#region source/extended-json.d.ts
|
|
87
7
|
/**
|
|
88
8
|
* The JSON replacer that encodes `bigint` and `Uint8Array` values in Extended JSON format,
|
|
@@ -1988,5 +1908,5 @@ declare class CashAssemblyVmNumberDecodeError extends Error {
|
|
|
1988
1908
|
*/
|
|
1989
1909
|
declare const serializeTemplate: (template: XOTemplate) => string;
|
|
1990
1910
|
//#endregion
|
|
1991
|
-
export { AsyncPushIterator, CASHASSEMBLY_EVALUATION_PATTERN, CASHASSEMBLY_EXPRESSION_PATTERN, CASHASSEMBLY_LITERAL_TOKEN_PATTERN, CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN, CASHASSEMBLY_VARIABLE_PATTERN, CashAssemblyCompilationFailedError, CashAssemblyNumberNotSafeIntegerError, CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError, CashAssemblyRequiredVariableMissingError, CashAssemblyUnsupportedValueTypeError, CashAssemblyVariableTypeMismatchError, CashAssemblyVmNumberDecodeError, CompileCashAssemblyStringParameters, CompiledCashAssemblyDecodeMode,
|
|
1911
|
+
export { AsyncPushIterator, CASHASSEMBLY_EVALUATION_PATTERN, CASHASSEMBLY_EXPRESSION_PATTERN, CASHASSEMBLY_LITERAL_TOKEN_PATTERN, CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN, CASHASSEMBLY_VARIABLE_PATTERN, CashAssemblyCompilationFailedError, CashAssemblyNumberNotSafeIntegerError, CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError, CashAssemblyRequiredVariableMissingError, CashAssemblyUnsupportedValueTypeError, CashAssemblyVariableTypeMismatchError, CashAssemblyVmNumberDecodeError, CompileCashAssemblyStringParameters, CompiledCashAssemblyDecodeMode, ResolvePrimitiveMethodBytesParameters, SSEEventParser, SSEEventParserOptions, TemplateInvalidError, TemplateJsonMalformedError, TemplateSerializationFailedError, VIEW_PROPERTIES_DESCRIPTION_MAX_LENGTH, VIEW_PROPERTIES_ICON_MAX_LENGTH, VIEW_PROPERTIES_NAME_MAX_LENGTH, bchVmVersionSchema, buildErrorDescription, compileCashAssemblyEvaluations, compileCashAssemblyString, convertValueToBytes, decodeCompiledCashAssemblyEvaluation, extendedJsonReplacer, extendedJsonReviver, extractCashAssemblyEvaluations, extractVariablesFromEvaluations, fromExtendedJson, generateCashAssemblyBytecode, generateTemplateIdentifier, isCashAssemblyExpression, parseTemplate, resolvePrimitiveMethodBytes, satoshisSchema, scriptToScriptHash, serializeTemplate, toExtendedJson, uint8ArraySchema, xoTemplateActionIntentSchema, xoTemplateActionRequirementsSchema, xoTemplateActionRoleRequirementsSchema, xoTemplateActionRoleSchema, xoTemplateActionSchema, xoTemplateAssetAmountsSchema, xoTemplateBaseTypeSchema, xoTemplateConstantSchema, xoTemplateDataSchema, xoTemplateDefaultsSchema, xoTemplateIconSchema, xoTemplateImportDefaultValueSchema, xoTemplateInputSchema, xoTemplateIntentSchema, xoTemplateLockingScriptIntentSchema, xoTemplateLockingScriptRoleSchema, xoTemplateLockingScriptSchema, xoTemplateLockingTypeSchema, xoTemplateNftCapabilitySchema, xoTemplateNonFungibleTokenDetailsSchema, xoTemplateOutputIntentSchema, xoTemplateOutputSchema, xoTemplatePrimitiveTypeSchema, xoTemplateResourceSchema, xoTemplateRoleSlotSchema, xoTemplateRoleSlotsRequirementsSchema, xoTemplateSchema, xoTemplateStateSchema, xoTemplateTokenSchema, xoTemplateTransactionInputSchema, xoTemplateTransactionOutputSchema, xoTemplateTransactionRoleDataSchema, xoTemplateTransactionSchema, xoTemplateVariableSchema, xoTemplateViewPropertiesSchema };
|
|
1992
1912
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../source/
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../source/extended-json.ts","../source/script.ts","../source/sse-session/async-push-iterator.ts","../source/sse-session/types.ts","../source/sse-session/sse-event-parser.ts","../source/template/errors.ts","../source/template/identifier.ts","../source/template/parser.ts","../source/template/schemas.ts","../source/cash-assembly/evaluations.ts","../source/cash-assembly/primitive-evaluations.ts","../source/cash-assembly/bytes.ts","../source/cash-assembly/defaults.ts","../source/cash-assembly/errors.ts","../source/template/serialization.ts"],"mappings":";;;;;;;;;;;;AA8BA;;;;;AAqBA;;;;;AAgCA;;cArDa,oBAAA,GAAwB,YAAA,UAAsB,KAAA;;;AA+D3D;;;;;;;cA1Ca,mBAAA,GAAuB,YAAA,UAAsB,KAAA;AC5C1D;;;;;;AAAA,cD4Ea,cAAA,GAAkB,MAAA;;AE5D/B;;;;;cFsEa,gBAAA,GAAoB,gBAAA;;;;;;;;cCtFpB,kBAAA,GAAsB,MAAA,EAAQ,UAAA;;;;;;;;;ADuB3C;;;;;AAqBA;;;;;AAgCA;;;;;AAUA;;cEtEa,iBAAA;EAAA;;;;;MAuBE,MAAA,CAAA;ED9Bd;;;;;;;ECyCG,IAAA,CAAK,KAAA,EAAO,CAAA;EAlCc;;;;;;EA8C1B,KAAA,CAAM,KAAA,EAAO,KAAA;EAgCQ;;;;;;EAnBrB,KAAA,CAAA;EAzBY;;;;;;;;;EAAA,CA4CX,MAAA,CAAO,aAAA,KAAkB,qBAAA,CAAsB,CAAA;AAAA;;;;;;UClGnC,OAAA;;;AH2BjB;EGtBI,IAAA;;;;AH2CJ;;EGpCI,KAAA;EHoCgC;;AAgCpC;;EG9DI,EAAA;EH8D2B;;AAU/B;;EGlEI,KAAA;AAAA;;;;;;;UCpBa,qBAAA;EJuBJ;EI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AAA;EVxBqB;;AAgCpC;;EUFI,iBAAA,GAAoB,UAAA;AAAA;;AVYxB;;;;;;;;ACtFA;;;;;;cSqJa,2BAAA,GAA+B,UAAA,EAAY,qCAAA,KAAwC,MAAA,SAAe,UAAA;;;;;;;;;AV9H/G;;;cWlBa,mBAAA,GAAuB,KAAA,WAAgB,eAAA,aAA0B,UAAA;;;;;;;;;AXkB9E;;;;;AAqBA;cYvCa,+BAAA,EAA+B,MAAA;;;;AZuE5C;;;;;AAUA;;cYrEa,+BAAA,EAA+B,MAAA;;;;;;AXjB5C;;;;;cW6Ba,6BAAA,EAA6B,MAAA;;;AVb1C;;;;;;cUuBa,kCAAA,EAAkC,MAAA;;;;;;;;;;;;;cAclC,8CAAA,EAA8C,MAAA;;;;;;cCvD9C,wCAAA,SAAiD,KAAA;cAC9C,aAAA;AAAA;AbwBhB;;;AAAA,caXa,kCAAA,SAA2C,KAAA;cACxC,OAAA;AAAA;;;;cASH,qCAAA,SAA8C,KAAA;cAC3C,WAAA,UAAqB,YAAA,UAAsB,UAAA;AAAA;;;;cAS9C,uCAAA,SAAgD,KAAA;cAC7C,UAAA,UAAoB,UAAA,UAAoB,IAAA;AAAA;;;;cAS3C,qCAAA,SAA8C,KAAA;cAC3C,UAAA,UAAoB,YAAA;AAAA;;;;cASvB,qCAAA,SAA8C,KAAA;cAC3C,UAAA,UAAoB,KAAA;AAAA;;AXrCpC;;cW8Ca,yCAAA,SAAkD,KAAA;cAC/C,UAAA,UAAoB,YAAA;AAAA;;;;cASvB,+BAAA,SAAwC,KAAA;cACrC,MAAA;AAAA;;;;;;;;AblDhB;;;cclBa,iBAAA,GAAqB,QAAA,EAAU,UAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -3,186 +3,6 @@ import { BchVmVersions, XOTemplateBaseTypes, XOTemplateLockingTypes, XOTemplateN
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { FungibleTokenAmount, NFTCommitment, PublicKey, Satoshis, SchnorrSignature, TemplateIdentifier, Timestamp, TokenCategory, TransactionHash } from "@xo-cash/primitives";
|
|
5
5
|
|
|
6
|
-
//#region source/errors.ts
|
|
7
|
-
/**
|
|
8
|
-
* Error thrown when a waitFor timeout is reached
|
|
9
|
-
*/
|
|
10
|
-
var WaitForTimeoutError = class extends Error {
|
|
11
|
-
constructor(type) {
|
|
12
|
-
super(`Timeout waiting for event "${type}"`);
|
|
13
|
-
this.name = "WaitForTimeoutError";
|
|
14
|
-
}
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
//#endregion
|
|
18
|
-
//#region source/event-emitter.ts
|
|
19
|
-
/**
|
|
20
|
-
* A simple event emitter implementation.
|
|
21
|
-
* @template T - The event map type.
|
|
22
|
-
*/
|
|
23
|
-
var EventEmitter = class {
|
|
24
|
-
/**
|
|
25
|
-
* The listeners map.
|
|
26
|
-
* @private
|
|
27
|
-
*/
|
|
28
|
-
#listeners = /* @__PURE__ */ new Map();
|
|
29
|
-
/**
|
|
30
|
-
* Add a listener for an event.
|
|
31
|
-
* @param type - The event type.
|
|
32
|
-
* @param listener - The listener function.
|
|
33
|
-
* @param debounceMilliseconds - The debounce time in milliseconds.
|
|
34
|
-
* @returns An off callback that can be called to stop listening for events.
|
|
35
|
-
*/
|
|
36
|
-
on(type, listener, debounceMilliseconds = 0) {
|
|
37
|
-
const { cancel, listener: cancellableListener } = this.cancellable(listener);
|
|
38
|
-
const wrappedListener = debounceMilliseconds > 0 ? this.debounce(cancellableListener, debounceMilliseconds) : cancellableListener;
|
|
39
|
-
if (!this.#listeners.has(type)) this.#listeners.set(type, /* @__PURE__ */ new Set());
|
|
40
|
-
const listenerEntry = {
|
|
41
|
-
listener,
|
|
42
|
-
wrappedListener,
|
|
43
|
-
cancel
|
|
44
|
-
};
|
|
45
|
-
this.#listeners.get(type)?.add(listenerEntry);
|
|
46
|
-
return () => this.off(type, listener);
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Add a one-time listener for an event.
|
|
50
|
-
* @param type - The event type.
|
|
51
|
-
* @param listener - The listener function.
|
|
52
|
-
* @param debounceMilliseconds - The debounce time in milliseconds.
|
|
53
|
-
* @returns An off callback that can be called to stop listening for events.
|
|
54
|
-
*/
|
|
55
|
-
once(type, listener, debounceMilliseconds = 0) {
|
|
56
|
-
const wrappedListener = (detail) => {
|
|
57
|
-
this.off(type, listener);
|
|
58
|
-
listener(detail);
|
|
59
|
-
};
|
|
60
|
-
const { cancel, listener: cancellableListener } = this.cancellable(wrappedListener);
|
|
61
|
-
const debouncedListener = debounceMilliseconds > 0 ? this.debounce(cancellableListener, debounceMilliseconds) : cancellableListener;
|
|
62
|
-
if (!this.#listeners.has(type)) this.#listeners.set(type, /* @__PURE__ */ new Set());
|
|
63
|
-
const listenerEntry = {
|
|
64
|
-
listener,
|
|
65
|
-
wrappedListener: debouncedListener,
|
|
66
|
-
cancel
|
|
67
|
-
};
|
|
68
|
-
this.#listeners.get(type)?.add(listenerEntry);
|
|
69
|
-
return () => this.off(type, listener);
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Remove a listener for an event.
|
|
73
|
-
* @param type - The event type.
|
|
74
|
-
* @param listener - The listener function.
|
|
75
|
-
*/
|
|
76
|
-
off(type, listener) {
|
|
77
|
-
const listeners = this.#listeners.get(type);
|
|
78
|
-
if (!listeners) return;
|
|
79
|
-
Array.from(listeners).filter((entry) => !listener || entry.listener === listener || entry.wrappedListener === listener).forEach((entry) => {
|
|
80
|
-
entry.cancel();
|
|
81
|
-
listeners.delete(entry);
|
|
82
|
-
});
|
|
83
|
-
if (!listener || this.#listeners.get(type)?.size === 0) this.#listeners.delete(type);
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Emit an event.
|
|
87
|
-
*
|
|
88
|
-
* @remarks The caller is responsible for ensuring the payload suits the intended mutability requirements.
|
|
89
|
-
* By default, the payload will be mutable, so listeners may mutate the payload, effecting both
|
|
90
|
-
* the original object and the other listeners.
|
|
91
|
-
* To prevent this, the caller can use the {@link Object.freeze} or {@link deepFreeze} function to freeze the payload.
|
|
92
|
-
* This will need to be defined in the EventMap using the built-in {@link Readonly} type or the provided {@link DeeplyReadonly} type.
|
|
93
|
-
*
|
|
94
|
-
* @param type - The event type.
|
|
95
|
-
* @param payload - The event payload.
|
|
96
|
-
* @returns True if there are listeners for the event, false otherwise.
|
|
97
|
-
*/
|
|
98
|
-
emit(type, payload) {
|
|
99
|
-
const listeners = this.#listeners.get(type);
|
|
100
|
-
if (!listeners) return false;
|
|
101
|
-
listeners.forEach((entry) => {
|
|
102
|
-
try {
|
|
103
|
-
entry.wrappedListener(payload);
|
|
104
|
-
} catch (error) {
|
|
105
|
-
console.error(error);
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
return listeners.size > 0;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Remove all listeners.
|
|
112
|
-
*/
|
|
113
|
-
removeAllListeners() {
|
|
114
|
-
for (const [type, listeners] of this.#listeners.entries()) listeners.forEach((entry) => {
|
|
115
|
-
this.off(type, entry.listener);
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Wait for an event to be emitted that matches the provided predicate function's criteria.
|
|
120
|
-
* @param type - The event type.
|
|
121
|
-
* @param predicate - Predicate function to filter for whether the event payload matches the criteria.
|
|
122
|
-
* @param timeoutMs - The timeout in milliseconds.
|
|
123
|
-
* @returns The event payload.
|
|
124
|
-
*/
|
|
125
|
-
async waitFor(type, predicate, timeoutMs) {
|
|
126
|
-
return new Promise((resolve, reject) => {
|
|
127
|
-
let timeoutId;
|
|
128
|
-
const cleanup = (listener) => {
|
|
129
|
-
this.off(type, listener);
|
|
130
|
-
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
131
|
-
};
|
|
132
|
-
const listener = (payload) => {
|
|
133
|
-
try {
|
|
134
|
-
if (!predicate(payload)) return;
|
|
135
|
-
cleanup(listener);
|
|
136
|
-
resolve(payload);
|
|
137
|
-
} catch (error) {
|
|
138
|
-
cleanup(listener);
|
|
139
|
-
reject(error);
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
if (timeoutMs !== void 0) timeoutId = setTimeout(() => {
|
|
143
|
-
this.off(type, listener);
|
|
144
|
-
reject(new WaitForTimeoutError(String(type)));
|
|
145
|
-
}, timeoutMs);
|
|
146
|
-
this.on(type, listener);
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Debounce a function.
|
|
151
|
-
*
|
|
152
|
-
* @remarks If {@link off} is called on a listener while it is debounced, the timeout is not cleared with clearTimeout.
|
|
153
|
-
* Instead, the function is no-oped.
|
|
154
|
-
*
|
|
155
|
-
* @param func - The function to debounce.
|
|
156
|
-
* @param wait - The wait time in milliseconds.
|
|
157
|
-
* @returns The debounced function.
|
|
158
|
-
*/
|
|
159
|
-
debounce(func, wait) {
|
|
160
|
-
let timeout;
|
|
161
|
-
return (detail) => {
|
|
162
|
-
if (timeout !== void 0) clearTimeout(timeout);
|
|
163
|
-
timeout = setTimeout(() => {
|
|
164
|
-
func(detail);
|
|
165
|
-
}, wait);
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* Make a function cancellable.
|
|
170
|
-
* @param func - The function to make cancelable.
|
|
171
|
-
* @returns The cancellable function with a cancel method.
|
|
172
|
-
*/
|
|
173
|
-
cancellable(func) {
|
|
174
|
-
let cancelled = false;
|
|
175
|
-
return {
|
|
176
|
-
cancel: () => cancelled = true,
|
|
177
|
-
listener: (detail) => {
|
|
178
|
-
if (cancelled) return;
|
|
179
|
-
func(detail);
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
};
|
|
184
|
-
|
|
185
|
-
//#endregion
|
|
186
6
|
//#region source/extended-json.ts
|
|
187
7
|
/**
|
|
188
8
|
* Matches a bigint encoded in Extended JSON format: `<bigint: 123n>`.
|
|
@@ -1715,5 +1535,5 @@ const compileCashAssemblyString = (parameters) => {
|
|
|
1715
1535
|
};
|
|
1716
1536
|
|
|
1717
1537
|
//#endregion
|
|
1718
|
-
export { AsyncPushIterator, CASHASSEMBLY_EVALUATION_PATTERN, CASHASSEMBLY_EXPRESSION_PATTERN, CASHASSEMBLY_LITERAL_TOKEN_PATTERN, CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN, CASHASSEMBLY_VARIABLE_PATTERN, CashAssemblyCompilationFailedError, CashAssemblyNumberNotSafeIntegerError, CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError, CashAssemblyRequiredVariableMissingError, CashAssemblyUnsupportedValueTypeError, CashAssemblyVariableTypeMismatchError, CashAssemblyVmNumberDecodeError,
|
|
1538
|
+
export { AsyncPushIterator, CASHASSEMBLY_EVALUATION_PATTERN, CASHASSEMBLY_EXPRESSION_PATTERN, CASHASSEMBLY_LITERAL_TOKEN_PATTERN, CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN, CASHASSEMBLY_VARIABLE_PATTERN, CashAssemblyCompilationFailedError, CashAssemblyNumberNotSafeIntegerError, CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError, CashAssemblyRequiredVariableMissingError, CashAssemblyUnsupportedValueTypeError, CashAssemblyVariableTypeMismatchError, CashAssemblyVmNumberDecodeError, SSEEventParser, TemplateInvalidError, TemplateJsonMalformedError, TemplateSerializationFailedError, VIEW_PROPERTIES_DESCRIPTION_MAX_LENGTH, VIEW_PROPERTIES_ICON_MAX_LENGTH, VIEW_PROPERTIES_NAME_MAX_LENGTH, bchVmVersionSchema, buildErrorDescription, compileCashAssemblyEvaluations, compileCashAssemblyString, convertValueToBytes, decodeCompiledCashAssemblyEvaluation, extendedJsonReplacer, extendedJsonReviver, extractCashAssemblyEvaluations, extractVariablesFromEvaluations, fromExtendedJson, generateCashAssemblyBytecode, generateTemplateIdentifier, isCashAssemblyExpression, parseTemplate, resolvePrimitiveMethodBytes, satoshisSchema, scriptToScriptHash, serializeTemplate, toExtendedJson, uint8ArraySchema, xoTemplateActionIntentSchema, xoTemplateActionRequirementsSchema, xoTemplateActionRoleRequirementsSchema, xoTemplateActionRoleSchema, xoTemplateActionSchema, xoTemplateAssetAmountsSchema, xoTemplateBaseTypeSchema, xoTemplateConstantSchema, xoTemplateDataSchema, xoTemplateDefaultsSchema, xoTemplateIconSchema, xoTemplateImportDefaultValueSchema, xoTemplateInputSchema, xoTemplateIntentSchema, xoTemplateLockingScriptIntentSchema, xoTemplateLockingScriptRoleSchema, xoTemplateLockingScriptSchema, xoTemplateLockingTypeSchema, xoTemplateNftCapabilitySchema, xoTemplateNonFungibleTokenDetailsSchema, xoTemplateOutputIntentSchema, xoTemplateOutputSchema, xoTemplatePrimitiveTypeSchema, xoTemplateResourceSchema, xoTemplateRoleSlotSchema, xoTemplateRoleSlotsRequirementsSchema, xoTemplateSchema, xoTemplateStateSchema, xoTemplateTokenSchema, xoTemplateTransactionInputSchema, xoTemplateTransactionOutputSchema, xoTemplateTransactionRoleDataSchema, xoTemplateTransactionSchema, xoTemplateVariableSchema, xoTemplateViewPropertiesSchema };
|
|
1719
1539
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#listeners","#stream","#controller","#closed","#textDecoder","#messageBuffer"],"sources":["../source/errors.ts","../source/event-emitter.ts","../source/extended-json.ts","../source/script.ts","../source/sse-session/async-push-iterator.ts","../source/sse-session/constants.ts","../source/sse-session/sse-event-parser.ts","../source/template/errors.ts","../source/template/serialization.ts","../source/template/identifier.ts","../source/template/schemas.ts","../source/template/parser.ts","../source/cash-assembly/errors.ts","../source/cash-assembly/defaults.ts","../source/cash-assembly/bytes.ts","../source/cash-assembly/primitive-evaluations.ts","../source/cash-assembly/evaluations.ts"],"sourcesContent":["/**\n * Error thrown when a waitFor timeout is reached\n */\nexport class WaitForTimeoutError extends Error {\n constructor(type: string) {\n super(`Timeout waiting for event \"${type}\"`);\n this.name = 'WaitForTimeoutError';\n }\n}\n","import type { DeeplyReadonly } from './types.ts';\nimport type { deepFreeze } from './misc.ts';\n\nimport { WaitForTimeoutError } from './errors.ts';\n\nexport type EventMap = Record<string, unknown>;\n\ntype Listener<T> = (detail: T) => void;\n\n/**\n * Internally permits listeners for individual event payloads to be stored\n * in a collection typed with the union of all event payloads.\n */\ntype StoredListener<T> = {\n bivarianceHack(detail: T): void;\n}['bivarianceHack'];\n\n/**\n * A listener entry.\n * @template T - The event payload type.\n */\ninterface ListenerEntry<T> {\n listener: StoredListener<T>;\n wrappedListener: StoredListener<T>;\n cancel: () => void;\n}\n\n/**\n * Callback returned by {@link on} and {@link once} for removing a listener.\n */\nexport type OffCallback = () => void;\n\n/**\n * A simple event emitter implementation.\n * @template T - The event map type.\n */\nexport class EventEmitter<T extends EventMap> {\n /**\n * The listeners map.\n * @private\n */\n #listeners: Map<keyof T, Set<ListenerEntry<T[keyof T]>>> = new Map();\n\n /**\n * Add a listener for an event.\n * @param type - The event type.\n * @param listener - The listener function.\n * @param debounceMilliseconds - The debounce time in milliseconds.\n * @returns An off callback that can be called to stop listening for events.\n */\n on<K extends keyof T>(type: K, listener: Listener<T[K]>, debounceMilliseconds: number = 0): OffCallback {\n const { cancel, listener: cancellableListener } = this.cancellable(listener);\n\n // Create a wrapped listener so that the debounce can be applied.\n const wrappedListener = debounceMilliseconds > 0 ? this.debounce(cancellableListener, debounceMilliseconds) : cancellableListener;\n\n // If the listeners map does not have the event type, create a new set.\n if (!this.#listeners.has(type)) {\n this.#listeners.set(type, new Set());\n }\n\n // Create a listener entry.\n const listenerEntry: ListenerEntry<T[K]> = {\n listener,\n wrappedListener,\n cancel,\n };\n\n // Add the listener entry to the listeners map.\n this.#listeners.get(type)?.add(listenerEntry);\n\n // Return an \"off\" callback that can be called to stop listening for events.\n return () => this.off(type, listener);\n }\n\n /**\n * Add a one-time listener for an event.\n * @param type - The event type.\n * @param listener - The listener function.\n * @param debounceMilliseconds - The debounce time in milliseconds.\n * @returns An off callback that can be called to stop listening for events.\n */\n once<K extends keyof T>(type: K, listener: Listener<T[K]>, debounceMilliseconds: number = 0): OffCallback {\n const wrappedListener: Listener<T[K]> = (detail: T[K]) => {\n this.off(type, listener);\n listener(detail);\n };\n\n // Create a cancellable listener.\n const { cancel, listener: cancellableListener } = this.cancellable(wrappedListener);\n\n // Create a debounced listener.\n const debouncedListener = debounceMilliseconds > 0 ? this.debounce(cancellableListener, debounceMilliseconds) : cancellableListener;\n\n // If the listeners map does not have the event type, create a new set.\n if (!this.#listeners.has(type)) {\n this.#listeners.set(type, new Set());\n }\n\n // Create a listener entry.\n const listenerEntry: ListenerEntry<T[K]> = {\n listener,\n wrappedListener: debouncedListener,\n cancel,\n };\n\n // Add the listener entry to the listeners map.\n this.#listeners.get(type)?.add(listenerEntry);\n\n // Return an \"off\" callback that can be called to stop listening for events.\n return () => this.off(type, listener);\n }\n\n /**\n * Remove a listener for an event.\n * @param type - The event type.\n * @param listener - The listener function.\n */\n off<K extends keyof T>(type: K, listener?: Listener<T[K]>): void {\n // Get the listeners for the event type.\n const listeners = this.#listeners.get(type);\n if (!listeners) return;\n\n // Find the listener entries (If a listener was provided, only 1 entry will be returned. Otherwise, all entries will be returned).\n const listenerEntries = Array.from(listeners).filter((entry) => !listener || entry.listener === listener || entry.wrappedListener === listener);\n\n // Remove the listener entries from the listeners set.\n listenerEntries.forEach((entry) => {\n // Set the wrapped listener to a no-op function to prevent it from being called by debounced events after it's been removed.\n entry.cancel();\n\n // Remove the listener entry from the listeners set.\n listeners.delete(entry);\n });\n\n // If no listener was provided and no listeners are left for the event type, remove the listeners set from the listeners map.\n if (!listener || this.#listeners.get(type)?.size === 0) {\n this.#listeners.delete(type);\n }\n }\n\n /**\n * Emit an event.\n *\n * @remarks The caller is responsible for ensuring the payload suits the intended mutability requirements.\n * By default, the payload will be mutable, so listeners may mutate the payload, effecting both\n * the original object and the other listeners.\n * To prevent this, the caller can use the {@link Object.freeze} or {@link deepFreeze} function to freeze the payload.\n * This will need to be defined in the EventMap using the built-in {@link Readonly} type or the provided {@link DeeplyReadonly} type.\n *\n * @param type - The event type.\n * @param payload - The event payload.\n * @returns True if there are listeners for the event, false otherwise.\n */\n emit<K extends keyof T>(type: K, payload: T[K]): boolean {\n // Get the listeners for the event type.\n const listeners = this.#listeners.get(type);\n if (!listeners) return false;\n\n // Emit the event to all listeners.\n listeners.forEach((entry) => {\n try {\n entry.wrappedListener(payload);\n } catch (error) {\n console.error(error);\n }\n });\n\n // Return true if there are listeners for the event, false otherwise.\n return listeners.size > 0;\n }\n\n /**\n * Remove all listeners.\n */\n removeAllListeners(): void {\n for (const [ type, listeners ] of this.#listeners.entries()) {\n listeners.forEach((entry) => {\n this.off(type, entry.listener);\n });\n }\n }\n\n /**\n * Wait for an event to be emitted that matches the provided predicate function's criteria.\n * @param type - The event type.\n * @param predicate - Predicate function to filter for whether the event payload matches the criteria.\n * @param timeoutMs - The timeout in milliseconds.\n * @returns The event payload.\n */\n async waitFor<K extends keyof T>(type: K, predicate: (payload: T[K]) => boolean, timeoutMs?: number): Promise<T[K]> {\n // Create a promise to wait for the event to be emitted.\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n // Create a cleanup function to remove the listener and clear the timeout if it is still pending.\n const cleanup = (listener: Listener<T[K]>): void => {\n // Remove the listener from the listeners map.\n this.off(type, listener);\n\n // Clear the timeout if it is still pending.\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n };\n\n // Create a listener function.\n const listener = (payload: T[K]): void => {\n try {\n // If the event payload does not match the predicate condition, return.\n if (!predicate(payload)) {\n return;\n }\n\n cleanup(listener);\n resolve(payload);\n } catch (error) {\n cleanup(listener);\n reject(error);\n }\n };\n\n // Set up timeout if specified\n if (timeoutMs !== undefined) {\n timeoutId = setTimeout(() => {\n this.off(type, listener);\n reject(new WaitForTimeoutError(String(type)));\n }, timeoutMs);\n }\n\n // Add the listener to the listeners map.\n this.on(type, listener);\n });\n }\n\n /**\n * Debounce a function.\n *\n * @remarks If {@link off} is called on a listener while it is debounced, the timeout is not cleared with clearTimeout.\n * Instead, the function is no-oped.\n *\n * @param func - The function to debounce.\n * @param wait - The wait time in milliseconds.\n * @returns The debounced function.\n */\n private debounce<K extends keyof T>(func: Listener<T[K]>, wait: number): Listener<T[K]> {\n // Create a timeout variable.\n let timeout: ReturnType<typeof setTimeout>;\n\n return (detail: T[K]) => {\n // If a debounce timer is already pending, clear it before scheduling the next one.\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(() => {\n func(detail);\n }, wait);\n };\n }\n\n /**\n * Make a function cancellable.\n * @param func - The function to make cancelable.\n * @returns The cancellable function with a cancel method.\n */\n private cancellable<K extends keyof T>(func: Listener<T[K]>): { cancel: () => void; listener: Listener<T[K]> } {\n let cancelled = false;\n\n return {\n cancel: (): boolean => (cancelled = true),\n listener: (detail: T[K]): void => {\n if (cancelled) return;\n func(detail);\n },\n };\n }\n}\n","import { binToHex, hexToBin } from '@bitauth/libauth';\n\n/**\n * Matches a bigint encoded in Extended JSON format: `<bigint: 123n>`.\n */\nconst EXTENDED_JSON_BIGINT_PATTERN = /^<bigint: (?<bigint>[+-]?[0-9]+)n>$/u;\n\n/**\n * Matches a Uint8Array encoded in Extended JSON format: `<uint8array: abcd>`.\n */\nconst EXTENDED_JSON_UINT8ARRAY_PATTERN = /^<uint8array: (?<hex>[0-9a-f]*)>$/u;\n\n/**\n * The JSON replacer that encodes `bigint` and `Uint8Array` values in Extended JSON format,\n * compatible with the format expected by `extendedJsonReviver`.\n *\n * - BigInts are encoded as `<bigint: 123n>`.\n * - Uint8Arrays are encoded as `<uint8array: abcd>`.\n * All other values pass through unchanged and if any incompatible type is encountered, an error is thrown.\n *\n * Note: To use this function, pass it as the second argument to `JSON.stringify` when serializing data.\n *\n * Note to developers: Libauth's `stringify` is the replacer. It also serializes functions and symbols,\n * which we do not support. Passing it would let templates include those values, but revival would then fail.\n * This module provides a dedicated replacer and reviver so serialization and deserialization stay aligned.\n *\n * @param _propertyKey The property key being serialized, required by the `JSON.stringify` replacer but not used here.\n * @param value The value to encode or pass through unchanged.\n * @returns The encoded string\n */\nexport const extendedJsonReplacer = (_propertyKey: string, value: unknown): unknown => {\n if (value instanceof Uint8Array) {\n return `<uint8array: ${binToHex(value)}>`;\n }\n\n if (typeof value === 'bigint') {\n return `<bigint: ${value.toString()}n>`;\n }\n\n return value;\n};\n\n/**\n * The JSON reviver that reconstructs `bigint` and `Uint8Array` values encoded by `extendedJsonReplacer`.\n *\n * Note: To use this function, pass it as the second argument to `JSON.parse` when deserializing data.\n *\n * @param _propertyKey The property key being deserialized, required by the `JSON.parse` reviver but not used here.\n * @param value The value to reconstruct or pass through unchanged.\n * @returns The reconstructed value\n */\nexport const extendedJsonReviver = (_propertyKey: string, value: unknown): unknown => {\n // If the value is not a string, return the original value\n if (typeof value !== 'string') {\n return value;\n }\n\n // Match the bigint pattern\n const bigintPatternMatch = value.match(EXTENDED_JSON_BIGINT_PATTERN);\n\n // If the value matches the bigint pattern, return the reconstructed bigint\n if (bigintPatternMatch) {\n return BigInt(bigintPatternMatch.groups!.bigint);\n }\n\n // Match the Uint8Array pattern\n const uint8arrayPatternMatch = value.match(EXTENDED_JSON_UINT8ARRAY_PATTERN);\n\n // If the value matches the Uint8Array pattern, return the reconstructed Uint8Array\n if (uint8arrayPatternMatch) {\n return hexToBin(uint8arrayPatternMatch.groups!.hex);\n }\n\n // If the value does not match either pattern, return the original value\n return value;\n};\n\n/**\n * Serializes an object to a string using the {@link extendedJsonReplacer}.\n *\n * @param object The object to serialize.\n * @returns The string representation of the object in Extended JSON format.\n */\nexport const toExtendedJson = (object: unknown): string => {\n return JSON.stringify(object, extendedJsonReplacer);\n};\n\n/**\n * Deserializes a string to an object using the {@link extendedJsonReviver}.\n *\n * @param serializedObject The string to deserialize.\n * @returns The object reconstructed from the string.\n */\nexport const fromExtendedJson = (serializedObject: string): unknown => {\n return JSON.parse(serializedObject, extendedJsonReviver);\n};\n","import { binToHex, sha256 } from '@bitauth/libauth';\n\n/**\n * Converts a script to a scriptHash.\n * @param {Uint8Array} script - The script to convert.\n * @returns {string} The scriptHash as a reversed hex string.\n */\nexport const scriptToScriptHash = (script: Uint8Array): string => {\n // Hash the script.\n const hash = sha256.hash(script);\n\n // Reverse the hash. (Electrum style, reverse switches to little endian representation)\n const reversed = hash.reverse();\n\n // Convert the reversed hash to hex.\n return binToHex(reversed);\n};\n","/**\n * An async iterable queue that bridges push-based producers and pull-based consumers.\n *\n * Composes an internal {@link ReadableStream} instead of extending it, so producers\n * call {@link push} while consumers use standard async iteration (`for await...of`).\n *\n * ```ts\n * const messages = new AsyncPushIterator<SSEvent>();\n *\n * // Producer (elsewhere)\n * messages.push(event);\n *\n * // Consumer\n * for await (const event of messages) {\n * handle(event);\n * }\n * ```\n *\n * {@link Symbol.asyncIterator} returns `stream.values({ preventCancel: true })` so\n * breaking out of `for await...of` does not cancel the underlying stream. That\n * matters for long-lived sessions where the producer keeps pushing after a consumer\n * stops reading early (for example, test helpers that only collect a fixed count).\n */\nexport class AsyncPushIterator<T> {\n /** ReadableStream backing the async iterator returned from {@link Symbol.asyncIterator}. */\n #stream: ReadableStream<T>;\n\n /** Controller used to enqueue values and close the stream from {@link push} and {@link close}. */\n #controller: ReadableStreamDefaultController<T> | undefined;\n\n /** When true, no more values are accepted and iteration eventually completes. */\n #closed = false;\n\n public constructor() {\n // `start`'s `this` is the underlying source object when using a plain method.\n // An arrow function captures the class instance so the controller is stored here.\n this.#stream = new ReadableStream({\n start: (controller: ReadableStreamDefaultController<T>): void => {\n this.#controller = controller;\n },\n });\n }\n\n /**\n * Flag indicating if the iterator is closed.\n */\n public get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Enqueues a value for the consumer.\n *\n * After {@link close}, pushes are silently dropped.\n *\n * @param value - The next value to yield from the iterator.\n */\n push(value: T): void {\n if (this.#closed) return;\n\n this.#controller?.enqueue(value);\n }\n\n /**\n * Causes any future interactions with the associated stream to error with {@link error}.\n * Calling this will also clear the pending values immediately, so iterators that were listening will not receive them.\n *\n * @param error - The error to throw from the stream.\n */\n error(error: Error): void {\n if (this.#closed) return;\n\n this.#closed = true;\n this.#controller?.error(error);\n }\n\n /**\n * Ends the stream.\n *\n * Marks the iterator closed so future {@link push} calls are ignored.\n * Buffered values are still yielded before iteration completes.\n */\n close(): void {\n this.#closed = true;\n\n try {\n this.#controller?.close();\n } catch {\n // The reader may already have released or cancelled the stream.\n }\n }\n\n /**\n * Returns an async iterator over the composed stream.\n *\n * Uses `preventCancel: true` so early `break` from `for await...of` does not\n * close the stream and block later pushes.\n *\n * Because values are discarded after being read, only a single consumer is supported.\n * Additional consumers will receive a stream lock error. Unread values will be preserved until {@link close} is called.\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n return this.#stream.values({ preventCancel: true });\n }\n}\n","/**\n * Regex that splits decoded SSE text into lines.\n *\n * The SSE wire format is line-oriented (`field: value` per line). Servers may\n * send `\\r\\n` (HTTP default), `\\n` (Unix), or `\\r` (legacy Mac). Matching all\n * three keeps parsing correct regardless of platform or server implementation.\n */\nexport const SSE_LINE_ENDINGS = /\\r\\n|\\r|\\n/;\n\n/**\n * Regex that matches the single optional leading space in an SSE field value.\n *\n * Per the SSE spec, `field: value` may include one space immediately after the\n * colon; that space is not part of the value. Used with `.replace()` to strip\n * it when parsing lines such as `data: hello` → `hello`.\n */\nexport const SSE_FIELD_VALUE_REGEX = /^ /;\n\n/**\n * Regex that matches a trailing newline at the end of a string.\n *\n * Multiple `data:` lines in one event are joined with `\\n`. When the event is\n * completed, this removes any stray trailing newline so callers receive the\n * payload without an extra line break at the end.\n */\nexport const SSE_TRAILING_NEWLINE_REGEX = /\\n$/;\n\n/**\n * The newline character used when normalizing SSE text internally.\n *\n * Used to join consecutive `data:` lines into one payload and to reassemble\n * buffered partial lines between streamed chunks before the next parse call.\n */\nexport const NEW_LINE = '\\n';\n","import type { SSEvent } from './types.ts';\nimport { NEW_LINE, SSE_FIELD_VALUE_REGEX, SSE_LINE_ENDINGS, SSE_TRAILING_NEWLINE_REGEX } from './constants.ts';\n\n/**\n * Optional encoders used when decoding incoming SSE bytes and re-encoding\n * any buffered remainder between chunks.\n */\nexport interface SSEEventParserOptions {\n\n /** Decodes raw stream bytes into text. Defaults to a new `TextDecoder`. */\n textDecoder: TextDecoder;\n}\n\n/**\n * Incrementally parses Server-Sent Events (SSE) from streamed byte chunks.\n *\n * SSE payloads are line-oriented: each event is a sequence of `field: value`\n * lines terminated by a blank line. This parser accepts arbitrary chunk\n * boundaries from a live HTTP response body and emits only complete events.\n *\n * Typical usage is one parser instance per connection, calling {@link parseEvents}\n * for each chunk received from the stream:\n *\n * ```ts\n * const parser = new SSEEventParser();\n *\n * for await (const chunk of response.body) {\n * for (const event of parser.parseEvents(chunk)) {\n * // handle event.data, event.event, event.id, event.retry\n * }\n * }\n * ```\n *\n * Supported fields follow the SSE spec: `data`, `event`, `id`, and `retry`.\n * Multiple `data:` lines in one event are joined with `\\n`. An event is only\n * emitted once a blank line is seen and at least one `data` field was collected.\n */\nexport class SSEEventParser {\n readonly #textDecoder: TextDecoder;\n\n /** Bytes from a partial line or incomplete event, carried over to the next chunk. */\n #messageBuffer: string = '';\n\n /**\n * Creates a parser for one SSE stream.\n *\n * Inject custom encoders in tests or when a non-default character encoding\n * is required; production callers can rely on the defaults.\n *\n * @param options - Optional text encoders for decode/encode of stream bytes.\n */\n constructor(options: Partial<SSEEventParserOptions> = {}) {\n this.#textDecoder = options.textDecoder ?? new TextDecoder();\n }\n\n /**\n * Clears any buffered bytes from a partial line or incomplete event.\n *\n * Call when abandoning a transport so the next connection does not prepend\n * stale bytes to incoming chunks.\n */\n public reset(): void {\n // Clear the message buffer\n this.#messageBuffer = '';\n\n // Reset the decoder to clear any buffered bytes\n this.#textDecoder.decode();\n }\n\n /**\n * Parses all complete SSE events contained in a newly received chunk.\n *\n * The chunk is appended to any bytes buffered from earlier calls. Complete\n * events (blank-line delimited blocks with at least one `data` field) are\n * returned immediately; any trailing partial line or in-progress event stays\n * in the internal buffer until a later chunk completes it.\n *\n * @param chunk - Newly received SSE stream bytes.\n * @returns Zero or more complete parsed SSE events from this chunk.\n */\n public parseEvents(chunk: Uint8Array): SSEvent[] {\n const lines = this.getBufferedLines(chunk);\n\n const eventLines = lines.slice(0, -1);\n\n const events: SSEvent[] = [];\n let event: Partial<SSEvent> = {};\n let processedLineCount = 0;\n\n for (const [ index, line ] of eventLines.entries()) {\n // A blank line indicates the end of an event. If we have received data, we can complete the event\n if (line === '') {\n if (event.data !== undefined) {\n events.push(this.completeEvent(event));\n event = {};\n processedLineCount = index + 1;\n }\n\n continue;\n }\n\n this.parseLine(line, event);\n }\n\n this.storeRemainingLines(lines, processedLineCount);\n\n return events;\n }\n\n /**\n * Appends a new chunk to the buffered bytes and splits the combined payload\n * into lines.\n *\n * Accepts `\\r\\n`, `\\r`, and `\\n` line endings so events parse correctly\n * regardless of server or platform conventions.\n */\n private getBufferedLines(chunk: Uint8Array): string[] {\n this.#messageBuffer += this.#textDecoder.decode(chunk, { stream: true });\n\n return this.#messageBuffer.split(SSE_LINE_ENDINGS);\n }\n\n /**\n * Parses one SSE field line into an in-progress event.\n *\n * Lines without a colon are ignored. A single optional space after the colon\n * is stripped from the field value, per the SSE spec.\n */\n private parseLine(line: string, event: Partial<SSEvent>): void {\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) return;\n\n const field = line.slice(0, colonIndex);\n const value = line.slice(colonIndex + 1).replace(SSE_FIELD_VALUE_REGEX, '');\n\n switch (field) {\n case 'data':\n event.data = event.data ? `${event.data}${NEW_LINE}${value}` : value;\n\n return;\n\n case 'event':\n event.event = value;\n\n return;\n\n case 'id':\n event.id = value;\n\n return;\n\n case 'retry':\n this.parseRetry(value, event);\n\n return;\n }\n }\n\n /**\n * Applies a numeric `retry:` field to an in-progress event.\n *\n * Non-numeric values are ignored rather than failing the parse.\n */\n private parseRetry(value: string, event: Partial<SSEvent>): void {\n const retry = parseInt(value, 10);\n\n if (!isNaN(retry)) {\n event.retry = retry;\n }\n }\n\n /**\n * Constructs a completed SSE event from accumulated fields.\n *\n * Trims a trailing newline from multi-line `data` values so callers receive\n * the payload without an extra line break at the end.\n */\n private completeEvent(event: Partial<SSEvent>): SSEvent {\n return {\n ...event,\n data: event.data?.replace(SSE_TRAILING_NEWLINE_REGEX, ''),\n } as SSEvent;\n }\n\n /**\n * Preserves incomplete trailing lines for the next received chunk.\n *\n * Only lines that were fully processed (through a completed event boundary)\n * are discarded; the remainder is re-encoded into {@link messageBuffer}.\n */\n private storeRemainingLines(lines: string[], processedLineCount: number): void {\n this.#messageBuffer = lines.slice(processedLineCount).join(NEW_LINE);\n }\n}\n","/* eslint-disable max-classes-per-file */\n\nimport type { $ZodIssue } from 'zod/v4/core';\n\n/**\n * Formats the Zod validation failures into a single string with one line each: \"- <field>: <message>\" and top level failures\n * with no field path show as \"(root)\" for better readability.\n *\n * @param issues The Zod validation failures to format.\n * @returns A human readable error string for better debugging.\n */\nexport const buildErrorDescription = (issues: $ZodIssue[]): string => {\n // Initialize an empty array to store the formatted lines.\n const lines: string[] = [];\n\n // Iterate over the issues and format them into a string.\n for (const issue of issues) {\n // Get the issue path.\n const issuePath = issue.path.length > 0 ? issue.path.join('.') : '(root)';\n\n // The prefix that Zod adds to messages.\n const messagePrefix = 'Invalid input: ';\n\n // Remove the prefix for better readability.\n const issueMessage = issue.message.startsWith(messagePrefix) ? issue.message.slice(messagePrefix.length) : issue.message;\n\n // Add the formatted line to the array.\n lines.push(`- ${issuePath}: ${issueMessage}`);\n }\n\n // Return the formatted string.\n return `\\n${lines.join('\\n')}`;\n};\n\n/**\n * Thrown when the provided template does not satisfy the XOTemplate schema.\n */\nexport class TemplateInvalidError extends Error {\n constructor(details: string) {\n const message = `Template invalid: ${details}`;\n super(message);\n this.name = 'TemplateInvalidError';\n }\n}\n\n/**\n * Thrown when a string passed to `deserializeTemplate` cannot be parsed as JSON.\n */\nexport class TemplateJsonMalformedError extends Error {\n constructor(reason: string) {\n super(`Template JSON malformed, expected a valid JSON string: ${reason}`);\n this.name = 'TemplateJsonMalformedError';\n }\n}\n\n/**\n * Thrown when `serializeTemplate` fails to produce a JSON string from the template.\n */\nexport class TemplateSerializationFailedError extends Error {\n constructor(reason: string) {\n super(`Template serialization failed: ${reason}`);\n this.name = 'TemplateSerializationFailedError';\n }\n}\n","import type { XOTemplate } from '@xo-cash/types';\nimport { extendedJsonReplacer, extendedJsonReviver } from '../extended-json.ts';\nimport { TemplateJsonMalformedError, TemplateSerializationFailedError } from './errors.ts';\n\n/**\n * Serializes an XOTemplate to a JSON string. Encodes `bigint` and `Uint8Array` fields in\n * Extended JSON format so they can be reconstructed by `deserializeTemplate`.\n *\n * @param template The template to serialize.\n * @returns A JSON string representation of the template.\n * @throws {TemplateSerializationFailedError} If the template cannot be serialized to JSON.\n */\nexport const serializeTemplate = (template: XOTemplate): string => {\n try {\n // Serialize the template to a JSON string.\n return JSON.stringify(template, extendedJsonReplacer);\n } catch (serializationError) {\n const reason = serializationError instanceof Error ? serializationError.message : 'unknown error while serializing template';\n\n throw new TemplateSerializationFailedError(reason);\n }\n};\n\n/**\n * Deserializes a JSON string back into an XOTemplate object. Restores `bigint` and\n * `Uint8Array` fields encoded in Extended JSON format by `serializeTemplate`.\n *\n * @param serializedTemplate - A JSON string of an XOTemplate object.\n * @returns The reconstructed XOTemplate object.\n * @throws {TemplateJsonMalformedError} If the serialized template is not valid JSON.\n */\nexport const deserializeTemplate = (serializedTemplate: string): XOTemplate => {\n try {\n // Parse the serialized template using the extended JSON reviver.\n return JSON.parse(serializedTemplate, extendedJsonReviver);\n } catch (parsingError) {\n const reason = parsingError instanceof Error ? parsingError.message : 'unknown error while deserializing template';\n\n throw new TemplateJsonMalformedError(reason);\n }\n};\n","import { binToHex, sha256, utf8ToBin } from '@bitauth/libauth';\nimport type { XOTemplate } from '@xo-cash/types';\nimport { serializeTemplate } from './serialization.ts';\n\n/**\n * Generates a deterministic template identifier by hashing the template.\n *\n * Note: This expects a template that has been validated by `parseTemplate`.\n *\n * @param template - The template to generate an identifier for.\n * @returns The sha256 hex identifier for the template.\n */\nexport const generateTemplateIdentifier = (template: XOTemplate): string => {\n // Serialize the template.\n const serializedTemplate = serializeTemplate(template);\n\n // Hash the serialized template.\n const hash = sha256.hash(utf8ToBin(serializedTemplate));\n\n // Convert the hash to hex and return it.\n return binToHex(hash);\n};\n","/* eslint-disable @stylistic/newline-per-chained-call */\nimport { BchVmVersions, XOTemplateBaseTypes, XOTemplatePrimitiveTypes, XOTemplateLockingTypes, XOTemplateNftCapabilities } from '@xo-cash/types';\nimport { z } from 'zod';\n\n// ============================================================\n// Enums\n// ============================================================\n\n/**\n * Validation schema for a BCH VM version identifier. Defines the set of known BCH VM versions\n * that XO templates declare support for.\n *\n * Uses `BchVmVersions` from `@xo-cash/types` so template validation stays aligned with the\n * `BchVmVersion` type.\n *\n * ```\n * {\n * \"supported\": [ \"BCH_2025_05\" ] ← each value\n * }\n * ```\n */\nexport const bchVmVersionSchema = z.enum(BchVmVersions);\n\n/**\n * Validation schema for the capability of a non-fungible token. Defines the three capability\n * types supported on BCH: minting tokens can create new NFTs, mutable tokens can update their\n * commitment, and none tokens cannot be changed after creation.\n *\n * ```\n * {\n * \"inputs|outputs\": {\n * \"[id]\": {\n * \"token\": {\n * \"nft\": {\n * \"capability\": \"minting\" ← this schema\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateNftCapabilitySchema = z.enum(XOTemplateNftCapabilities);\n\n/**\n * Validation schema for a BCH locking script type. Defines the standard locking script types\n * supported on BCH.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"lockingType\": \"p2pkh\" ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateLockingTypeSchema = z.enum(XOTemplateLockingTypes);\n\n/**\n * Validation schema for a base type identifier.\n * Accepts values from XOTemplateBaseTypes for the `type` field on constants, variables, and data.\n */\nexport const xoTemplateBaseTypeSchema = z.enum(XOTemplateBaseTypes);\n\n/**\n * Validation schema for a primitive type identifier.\n * Accepts values from XOTemplatePrimitiveTypes for the `hint` field on constants, variables, and data.\n */\nexport const xoTemplatePrimitiveTypeSchema = z.enum(XOTemplatePrimitiveTypes);\n\n// ============================================================\n// Primitives\n// ============================================================\n\n/**\n * Validation schema for byte array fields i.e. Uint8Array instance.\n */\nexport const uint8ArraySchema = z.instanceof(Uint8Array).describe('A sequence of unsigned 8-bit integers expressed as a Uint8Array.');\n\n/**\n * Validation schema for the Satoshis type i.e. bigint.\n */\nexport const satoshisSchema = z.bigint().describe('A satoshi amount expressed as a bigint.');\n\n// ============================================================\n// Shared\n// ============================================================\n\n/** Maximum character length for name fields on view properties. */\nexport const VIEW_PROPERTIES_NAME_MAX_LENGTH = 1000;\n\n/** Maximum character length for description fields on view properties. */\nexport const VIEW_PROPERTIES_DESCRIPTION_MAX_LENGTH = 5000;\n\n/** Maximum character length for icon fields on view properties. */\nexport const VIEW_PROPERTIES_ICON_MAX_LENGTH = 1000;\n\n/**\n * Validation schema for view properties shared across many template elements i.e. name, description, icon.\n * Extended by most other schemas in this file.\n */\nexport const xoTemplateViewPropertiesSchema = z\n .object({\n name: z.string().max(VIEW_PROPERTIES_NAME_MAX_LENGTH).describe('A short human-readable label for this element.'),\n description: z\n .string()\n .max(VIEW_PROPERTIES_DESCRIPTION_MAX_LENGTH)\n .describe('A human-readable explanation of what this element does and when it is relevant.'),\n icon: z.string().max(VIEW_PROPERTIES_ICON_MAX_LENGTH).optional().describe('An optional icon identifier or URL for this element.'),\n })\n .strict();\n\n// ============================================================\n// Intents\n// ============================================================\n\n/**\n * Validation schema for the base intent structure. Describes the common data parameters shared\n * by all intent types regardless of what they target.\n *\n * An optional templateIdentifier allows the intent to reference a target defined in a different\n * template, enabling cross-template interaction.\n *\n * Extended by: xoTemplateActionIntentSchema, xoTemplateOutputIntentSchema,\n * xoTemplateLockingScriptIntentSchema.\n */\nexport const xoTemplateIntentSchema = z\n .object({\n templateIdentifier: z\n .string()\n .optional()\n .describe('Optional identifier for the template used in this intent. If not provided, uses the current template.'),\n role: z.string().optional().describe('Optional identifier for the role used in this intent.'),\n generate: z.array(z.string()).optional().describe('Identifiers for items to generate when this intent is resolved, e.g. keys or secrets.'),\n variables: z.array(z.record(z.string(), z.unknown())).optional().describe('Variable values to apply when this intent is resolved.'),\n constants: z.array(z.record(z.string(), z.unknown())).optional().describe('Constant values to apply when this intent is resolved.'),\n secrets: z.array(z.record(z.string(), z.unknown())).optional().describe('Secret values to apply when this intent is resolved.'),\n })\n .strict();\n\n/**\n * Validation schema for an action intent. Extends the base intent structure with an action\n * identifier. Used in locking script action lists and in the template's start array.\n *\n * ```\n * {\n * \"start\": [\n * { \"action\": \"...\" } ← this schema\n * ],\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"actions\": [\n * { \"action\": \"...\" } ← this schema\n * ],\n * \"roles\": {\n * \"[roleId]\": {\n * \"actions\": [\n * { \"action\": \"...\" } ← this schema\n * ]\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionIntentSchema = xoTemplateIntentSchema\n .extend({\n action: z.string().describe('The identifier for the intended action.'),\n })\n .strict();\n\n/**\n * Validation schema for an output intent. Extends the base intent structure with an output\n * identifier. Used in the template's defaults block.\n *\n * ```\n * {\n * \"defaults\": {\n * \"change\": { \"output\": \"...\" } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateOutputIntentSchema = xoTemplateIntentSchema\n .extend({\n output: z.string().describe('The identifier for the intended output.'),\n })\n .strict();\n\n/**\n * Validation schema for a locking script intent. Extends the base intent structure with\n * a locking script identifier.\n *\n * @todo The location of this schema in the template JSON is not yet determined.\n */\nexport const xoTemplateLockingScriptIntentSchema = xoTemplateIntentSchema\n .extend({\n lockingScript: z.string().describe('The identifier for the intended locking script.'),\n })\n .strict();\n\n// ============================================================\n// Actions\n// ============================================================\n\n/**\n * Validation schema for the slot count configuration on a role requirement. Declares how many\n * participants of a given role are needed. min sets the lower bound and max sets the upper bound.\n * When max is absent, there is no upper limit.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"requirements\": {\n * \"participants\": [\n * { \"slots\": { \"min\": 1, \"max\": 1 } } ← this schema\n * ]\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateRoleSlotsRequirementsSchema = z\n .object({\n min: z.number().describe('Minimum number of participants required for this role.'),\n max: z.number().optional().describe('Maximum number of participants allowed for this role. Undefined means unlimited.'),\n })\n .strict();\n\n/**\n * Validation schema for the capability requirements declared on a role within an action.\n * Describes what data, secrets, or state the role is responsible for providing when participating in an action.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": {\n * \"requirements\": { \"variables\": [], \"secrets\": [] } ← this schema\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionRoleRequirementsSchema = z\n .object({\n variables: z.array(z.string()).optional().describe('List of variable identifiers required for this role.'),\n secrets: z.array(z.string()).optional().describe('List of secret identifiers required for this role.'),\n })\n .strict();\n\n/**\n * Validation schema for a role-specific definition within an action.\n * All view properties are optional.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionRoleSchema = xoTemplateViewPropertiesSchema\n .partial()\n .extend({\n generate: z\n .array(z.string())\n .optional()\n .describe('Identifiers for data items that should be generated for this role when participating in the action.'),\n\n // Describes under what conditions this role can proceed with the action. All values listed\n // under requirements must be populated for the action to work. This is a developer and\n // author concern. It is not present on intents because intents are used to populate the\n // action rather than to define it, and their fields are flattened accordingly.\n requirements: xoTemplateActionRoleRequirementsSchema.optional().describe('The requirements for this role within this action.'),\n })\n .strict();\n\n/**\n * Validation schema for a role participation requirement in an action's requirements block.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"requirements\": {\n * \"participants\": [\n * { \"role\": \"...\", \"slots\": { } } ← this schema\n * ]\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateRoleSlotSchema = z\n .object({\n role: z.string().describe('The role identifier that this requirement applies to.'),\n slots: xoTemplateRoleSlotsRequirementsSchema.describe('Slot configuration specifying how many participants of this role are required.'),\n })\n .strict();\n\n/**\n * Validation schema for the requirements of an action.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"requirements\": { \"variables\": [], \"participants\": [], \"secrets\": [] } ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionRequirementsSchema = z\n .object({\n variables: z.array(z.string()).optional().describe('List of variable identifiers required for this action.'),\n participants: z.array(xoTemplateRoleSlotSchema).optional().describe('The participants required for this action.'),\n secrets: z.array(z.string()).optional().describe('The secrets required for this action.'),\n })\n .strict();\n\n/**\n * Validation schema for an action definition.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateActionSchema = xoTemplateViewPropertiesSchema\n .extend({\n roles: z.record(z.string(), xoTemplateActionRoleSchema).optional().describe('Specific context for each role participating in this action.'),\n requirements: xoTemplateActionRequirementsSchema.optional().describe('The requirements for this action.'),\n\n // This is a list of conditions that can influence how the action behaves.\n // This needs more work to be done.\n conditions: z.array(z.string()).optional().describe('Conditions that must be met for this action to be available.'),\n\n // A single transaction produced by the action.\n // In future this might be moved to a results block that can have multiple transactions.\n transaction: z\n .string()\n .optional()\n .describe(\"The identifier of the transaction this action produces, referencing an entry in the template's transactions.\"),\n\n // The data that is produced by the action.\n // In future this might be moved to a results block that can have multiple data fields.\n data: z.string().optional().describe(\"The identifier of the data field this action produces, referencing an entry in the template's data.\"),\n })\n .strict();\n\n// ============================================================\n// Tokens & Amounts\n// ============================================================\n\n/**\n * Validation schema for the non-fungible token configuration within a token field.\n *\n * ```\n * {\n * \"inputs|outputs\": {\n * \"[id]\": {\n * \"token\": {\n * \"nft\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateNonFungibleTokenDetailsSchema = z\n .object({\n capability: z\n .union([ xoTemplateNftCapabilitySchema, z.string() ])\n .optional()\n .describe('The capability of the NFT. May be a known capability value or a CashASM expression resolving to a capability.'),\n commitment: z.string().optional().describe('The commitment data for the NFT, as a string or CashASM expression resolving to a commitment.'),\n })\n .strict();\n\n/**\n * Validation schema for the token configuration on inputs and outputs.\n *\n * ```\n * {\n * \"inputs|outputs\": {\n * \"[id]\": {\n * \"token\": { } ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTokenSchema = z\n .object({\n category: z.string().optional().describe('The category of the token, as a string or CashASM expression resolving to a category.'),\n amount: z\n .union([ z.bigint(), z.string(), z.null() ])\n .optional()\n .describe('The amount of fungible tokens as a bigint, a CashASM expression resolving to a bigint, or null indicating no FT is present.'),\n nft: xoTemplateNonFungibleTokenDetailsSchema\n .nullable()\n .optional()\n .describe('Non-fungible token configuration. Null indicates no NFT is present.'),\n })\n .strict();\n\n/**\n * Validation schema for the asset amounts configuration. Used by omitChangeAmounts on inputs\n * and by balance on locking scripts, outputs, and their roles.\n */\nexport const xoTemplateAssetAmountsSchema = z\n .object({\n\n /**\n * The satoshi amount.\n * - `Satoshis`: A specific bigint amount.\n * - `string`: A CashASM expression that resolves to the amount.\n * - `true`: all, i.e. the entire amount\n */\n satoshis: z\n .union([ satoshisSchema, z.string(), z.literal(true) ])\n .optional()\n .describe('The satoshi amount. Accepts a bigint for a specific value, a CashASM expression, or true for the entire amount.'),\n\n /**\n * The fungible token amount.\n * - `FungibleTokenAmount`: A specific bigint amount.\n * - `string`: A CashASM expression that resolves to the amount.\n * - `true`: all, i.e. the entire amount\n */\n fungibleTokens: z\n .union([ z.bigint(), z.string(), z.literal(true) ])\n .optional()\n .describe('The fungible token amount. Accepts a bigint for a specific value, a CashASM expression, or true for the entire amount.'),\n\n /**\n * Whether a non-fungible token is present (0 for absent, 1 for present),\n * or a CashASM expression that evaluates to 0 or 1.\n * - `true`: resolves to 1 if an NFT is present, or 0 if none is present. Use this when\n * the NFT is optional, to express that the NFT is estimated to be part of the balance\n * if present, or absent from it if not.\n * - `0`: None, i.e. nothing is expected to be included\n * - `1`: present and complete, as value > 1 does not make sense for non-fungible tokens\n * - `string`: A CashASM expression that evaluates to 0 or 1.\n */\n nonfungibleTokens: z\n .union([ z.literal(0), z.literal(1), z.string(), z.literal(true) ])\n .optional()\n .describe('Whether an NFT is present: 0 for absent, 1 for present, a CashASM expression evaluating to 0 or 1, or true to estimate the NFT as part of the balance if present, or absent from it if not.'),\n })\n .strict();\n\n// ============================================================\n// Locking Scripts\n// ============================================================\n\n/**\n * Validation schema for the state configuration shared by a locking script and its individual roles.\n * Declares which variables and secrets are tracked in the on-chain state for a given participant.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"state\": { \"variables\": [], \"secrets\": [] } ← this schema\n * \"roles\": {\n * \"[roleId]\": {\n * \"state\": { \"variables\": [], \"secrets\": [] } ← this schema\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateStateSchema = z\n .object({\n variables: z.array(z.string()).optional().describe('List of variable identifiers to track in state.'),\n secrets: z.array(z.string()).optional().describe('List of secret identifiers to track in state.'),\n })\n .strict();\n\n/**\n * Validation schema for a role definition for a locking script.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateLockingScriptRoleSchema = xoTemplateViewPropertiesSchema\n .partial()\n .extend({\n state: xoTemplateStateSchema.optional().describe('List of items to track as state for this role.'),\n actions: z.array(xoTemplateActionIntentSchema).optional().describe('List of action references available to this role.'),\n balance: xoTemplateAssetAmountsSchema.partial().optional().describe('Estimated ownership in the optional set of asset amounts specified.'),\n selectable: z.boolean().optional().describe('Whether outputs locked to this script should be available for coin selection.'),\n privacy: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('Privacy level for outputs locked to this script. A numeric level or a CashASM expression that evaluates to a privacy level.'),\n })\n .strict();\n\n/**\n * Validation schema for a locking script definition.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateLockingScriptSchema = xoTemplateViewPropertiesSchema\n .extend({\n lockingType: xoTemplateLockingTypeSchema.optional().describe('The type of locking mechanism. Defaults to p2s if not specified.'),\n lockingBytecode: z.string().describe('The locking script bytecode.'),\n unlockingBytecode: z.string().optional().describe('Optional default unlocking bytecode when used in automatic coin selection.'),\n actions: z.array(xoTemplateActionIntentSchema).optional().describe('The actions available for this locking script.'),\n state: xoTemplateStateSchema.optional().describe('List of items to track as state for all participants.'),\n balance: xoTemplateAssetAmountsSchema.partial().optional().describe('Estimated ownership in the optional set of asset amounts specified.'),\n selectable: z.boolean().optional().describe('Whether outputs locked to this script should be available for coin selection.'),\n // Might be levels or tags\n privacy: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('Privacy level for outputs locked to this script. A numeric level or a CashASM expression that evaluates to a privacy level.'),\n roles: z\n .record(z.string(), xoTemplateLockingScriptRoleSchema)\n .optional()\n .describe('Specific context for each role participating in this locking script.'),\n })\n .strict();\n\n// ============================================================\n// Inputs\n// ============================================================\n\n/**\n * Validation schema for an input definition in the template. Extends view properties with optional\n * satoshi value, token configuration, and other transaction level fields.\n *\n * ```\n * {\n * \"inputs\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateInputSchema = xoTemplateViewPropertiesSchema\n .extend({\n valueSatoshis: z\n .union([ satoshisSchema, z.string() ])\n .optional()\n .describe('The amount of satoshis for this input as a bigint or a CashASM expression resolving to the amount.'),\n token: xoTemplateTokenSchema.nullable().optional().describe('Token configuration for this input.'),\n sequenceNumber: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('The sequence number of this input as a specific number or a CashASM expression.'),\n unlockingScript: z.string().optional().describe('Identifier of the unlocking script to use for the UTXO provided for this input.'),\n omitChangeAmounts: xoTemplateAssetAmountsSchema\n .optional()\n .describe('Amount of change that should be omitted from the automatic change handling. WARNING: Setting this can result in loss of funds!'),\n })\n .strict();\n\n// ============================================================\n// Outputs\n// ============================================================\n\n/**\n * Validation schema for an output definition. Extends the locking script schema so that\n * every output inherits the same locking script fields and adds output-specific fields.\n *\n * ```\n * {\n * \"outputs\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateOutputSchema = xoTemplateLockingScriptSchema\n .omit({ lockingType: true, lockingBytecode: true, unlockingBytecode: true })\n .extend({\n lockingScript: z.string().describe('Identifier of the locking script to use for this output.'),\n valueSatoshis: z\n .union([ satoshisSchema, z.string() ])\n .optional()\n .describe('The amount of satoshis for this output as a bigint or a CashASM expression resolving to the amount.'),\n token: xoTemplateTokenSchema.nullable().optional().describe('Token configuration for this output.'),\n })\n .strict();\n\n// ============================================================\n// Transactions\n// ============================================================\n\n/**\n * Validation schema for a transaction input reference for a transaction definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": {\n * \"inputs\": [\n * { \"input\": \"...\" } ← this schema\n * ]\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionInputSchema = z\n .object({\n input: z.string().describe('The input definition identifier.'),\n inputIndex: z.number().optional().describe('Optional index of this input in the transaction.'),\n })\n .strict();\n\n/**\n * Validation schema for a transaction output reference for a transaction definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": {\n * \"outputs\": [\n * { \"output\": \"...\" } ← this schema\n * ]\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionOutputSchema = z\n .object({\n output: z.string().describe('The output definition identifier.'),\n outputIndex: z.number().optional().describe('Optional index of this output in the transaction.'),\n })\n .strict();\n\n/**\n * Validation schema for role-specific data for a transaction definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionRoleDataSchema = xoTemplateViewPropertiesSchema\n .partial()\n .extend({\n inputs: z.array(xoTemplateTransactionInputSchema).optional().describe('The inputs required for this role.'),\n outputs: z.array(xoTemplateTransactionOutputSchema).optional().describe('The outputs required for this role.'),\n })\n .strict();\n\n/**\n * Validation schema for a transaction template definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionSchema = xoTemplateViewPropertiesSchema\n .extend({\n version: z.number().optional().describe('The version of the transaction.'),\n locktime: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('The locktime for this transaction as a specific number or a CashASM expression.'),\n inputs: z.array(xoTemplateTransactionInputSchema).describe('The inputs for this transaction.'),\n outputs: z.array(xoTemplateTransactionOutputSchema).describe('The outputs for this transaction.'),\n roles: z\n .record(z.string(), xoTemplateTransactionRoleDataSchema)\n .optional()\n .describe('Specific context for each role participating in this transaction.'),\n composable: z.boolean().optional().describe('Whether this transaction can be composed with other transactions.'),\n })\n .strict();\n\n// ============================================================\n// Template Data\n// ============================================================\n\n/**\n * Validation schema for a constant value definition.\n *\n * ```\n * {\n * \"constants\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateConstantSchema = xoTemplateViewPropertiesSchema\n .extend({\n type: xoTemplateBaseTypeSchema.describe('The data type of this constant.'),\n value: z.unknown().describe('The value of this constant.'),\n hint: xoTemplatePrimitiveTypeSchema.optional().describe('An optional hint to help apps and users understand what this constant represents.'),\n })\n .strict();\n\n/**\n * Validation schema for a data field definition.\n *\n * ```\n * {\n * \"data\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateDataSchema = z\n .object({\n type: xoTemplateBaseTypeSchema.describe('The data type of this data field.'),\n value: z.unknown().describe('The value for this data field.'),\n hint: xoTemplatePrimitiveTypeSchema.optional().describe('An optional hint to help apps and users understand this data field.'),\n })\n .strict();\n\n/**\n * Validation schema for an import default value intent. Extends the base intent with optional\n * view properties that the engine evaluates at runtime to produce human-readable output.\n *\n * ```\n * {\n * \"variables\": {\n * \"[id]\": {\n * \"importDefaultValue\": { } ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateImportDefaultValueSchema = xoTemplateIntentSchema\n // .shape unwraps the ZodObject to the raw field map { name, description, icon } with each field made optional\n .extend(xoTemplateViewPropertiesSchema.partial().shape)\n .strict();\n\n/**\n * Validation schema for a variable definition.\n *\n * ```\n * {\n * \"variables\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateVariableSchema = xoTemplateViewPropertiesSchema\n .extend({\n type: xoTemplateBaseTypeSchema.optional().describe('The data type of this variable.'),\n hint: xoTemplatePrimitiveTypeSchema.optional().describe('A hint to help users understand what value to provide.'),\n\n // A neutral intent that the engine uses to populate the default value for this variable.\n // View properties (name, description, icon) may contain CashASM expressions that the\n // engine evaluates at runtime to produce human-readable output. The engine overrides\n // whatever values are set here when resolving the variable for a participant.\n importDefaultValue: xoTemplateImportDefaultValueSchema\n .optional()\n .describe('A neutral intent that the engine uses to populate the default value for this variable.'),\n })\n .strict();\n\n// ============================================================\n// Template Resources\n// ============================================================\n\n/**\n * Validation schema for a resource reference attached to a template element. Extends view\n * properties with a URL pointing to external documentation or tooling.\n *\n * ```\n * {\n * \"resources\": [\n * { \"name\": \"...\", \"description\": \"...\", \"url\": \"...\" } ← this schema\n * ]\n * }\n * ```\n */\nexport const xoTemplateResourceSchema = xoTemplateViewPropertiesSchema\n .extend({\n url: z.string().describe('The URL for this resource.'),\n })\n .strict();\n\n/**\n * Validation schema for an icon reference.\n *\n * ```\n * {\n * \"icons\": [\n * { \"name\": \"...\", \"hash\": \"...\" } ← this schema\n * ]\n * }\n * ```\n */\nexport const xoTemplateIconSchema = xoTemplateViewPropertiesSchema\n .pick({ name: true })\n .extend({\n hash: z.string().describe('The identifier of the icon.'),\n })\n .strict();\n\n// ============================================================\n// Defaults\n// ============================================================\n\n/**\n * Validation schema for the defaults block of a template.\n *\n * ```\n * {\n * \"defaults\": { } ← this schema\n * }\n * ```\n */\nexport const xoTemplateDefaultsSchema = z\n .object({\n change: xoTemplateOutputIntentSchema.optional().describe('Instructions for how to construct automated change output.'),\n })\n .strict();\n\n// ============================================================\n// Template\n// ============================================================\n\n/**\n * Validation schema for the full XOTemplate type.\n */\nexport const xoTemplateSchema = xoTemplateViewPropertiesSchema\n .extend({\n $schema: z\n .string()\n .describe('The URI that identifies the JSON Schema used by this template. This enables documentation, autocompletion, and validation in JSON documents.'),\n version: z.string().optional().describe('A string identifying the version of this template.'),\n supported: z.array(bchVmVersionSchema).min(1).describe('The BCH VM versions that this template supports. At least one version is required.'),\n defaults: xoTemplateDefaultsSchema.optional().describe('Optional default settings used in this template.'),\n roles: z.record(z.string(), xoTemplateViewPropertiesSchema).describe('The roles defined in this template.'),\n start: z.array(xoTemplateActionIntentSchema).describe('A list of entry points defining which actions are available at the start.'),\n actions: z.record(z.string(), xoTemplateActionSchema).describe('The actions defined in this template.'),\n data: z.record(z.string(), xoTemplateDataSchema).optional().describe('The data fields defined in this template.'),\n transactions: z.record(z.string(), xoTemplateTransactionSchema).optional().describe('The transaction templates defined in this template.'),\n inputs: z.record(z.string(), xoTemplateInputSchema).describe('The inputs defined in this template.'),\n outputs: z.record(z.string(), xoTemplateOutputSchema).describe('The outputs defined in this template.'),\n lockingScripts: z.record(z.string(), xoTemplateLockingScriptSchema).describe('The locking script templates defined in this template.'),\n scripts: z\n .record(z.string(), z.string())\n .describe('Scripts used in this template. Keys are script identifiers, values are bytecode or CashASM expressions.'),\n constants: z.record(z.string(), xoTemplateConstantSchema).optional().describe('The constants defined in this template.'),\n variables: z\n .record(z.string(), xoTemplateVariableSchema)\n .optional()\n .describe(\"The variables that must be provided for use in the template's scripts.\"),\n resources: z.array(xoTemplateResourceSchema).optional().describe('Resource references providing external documentation or tooling links.'),\n icons: z.array(xoTemplateIconSchema).optional().describe('The icons available for use throughout the template.'),\n scenarios: z.unknown().optional().describe('The scenarios defined in this template.'),\n })\n .strict();\n","import type { XOTemplate } from '@xo-cash/types';\nimport { xoTemplateSchema } from './schemas.ts';\nimport { TemplateInvalidError, buildErrorDescription } from './errors.ts';\nimport { deserializeTemplate, serializeTemplate } from './serialization.ts';\n\n/**\n * Accepts a template value and returns a validated XOTemplate object. The input may be\n * either an Extended JSON string or a pre-parsed object. Both are validated\n * against the XOTemplate schema.\n *\n * @param inputTemplate - The value to validate. May be an Extended JSON string or a pre-parsed object.\n * @returns The validated template object\n * @throws {TemplateSerializationFailedError} If a pre-parsed object input cannot be serialized to JSON for normalization.\n * @throws {TemplateJsonMalformedError} If the string input is not valid JSON.\n * @throws {TemplateInvalidError} If the value does not conform to the XOTemplate schema.\n */\nexport const parseTemplate = (inputTemplate: string | XOTemplate): XOTemplate => {\n // Regardless of whether the inputTemplate is a string, an imported template or an in-memory object, serialize and then\n // deserialize it to ensure the output shape is consistent. For example, optional fields explicitly set to 'undefined' would be passed through\n // and then dropped on the string path, resulting in structurally different results for the same template.\n const serializedTemplate = typeof inputTemplate === 'string' ? inputTemplate : serializeTemplate(inputTemplate);\n const templateObject = deserializeTemplate(serializedTemplate);\n\n // Validate the template against the schema.\n const parseResult = xoTemplateSchema.safeParse(templateObject);\n\n if (parseResult.success) {\n // Return the validated template object\n return parseResult.data as XOTemplate;\n }\n\n // Build a human-readable description of every validation failure\n const errorDescription = buildErrorDescription(parseResult.error.issues);\n\n // Throw a typed error with the description\n throw new TemplateInvalidError(errorDescription);\n};\n","/* eslint-disable max-classes-per-file */\n\n/**\n * Error thrown when a required variable is missing.\n */\nexport class CashAssemblyRequiredVariableMissingError extends Error {\n constructor(variableNames?: string[]) {\n const defaultMessage = 'Missing required variable';\n if (variableNames !== undefined && variableNames.length > 0) {\n super(`${defaultMessage}: variableNames [${variableNames.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when cash assembly compilation fails.\n */\nexport class CashAssemblyCompilationFailedError extends Error {\n constructor(message?: string) {\n const defaultMessage = 'Cash assembly compilation failed';\n super(message ? `${defaultMessage}: ${message}` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a variable's runtime type does not match the type required for compilation.\n */\nexport class CashAssemblyVariableTypeMismatchError extends Error {\n constructor(variableKey: string, expectedType: string, actualType: string) {\n const defaultMessage = 'Variable type mismatch';\n super(`${defaultMessage}: variableKey \"${variableKey}\", expected ${expectedType}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when a supported primitive hint does not expose the requested method.\n */\nexport class CashAssemblyPrimitiveMethodMissingError extends Error {\n constructor(identifier: string, methodName: string, hint: string) {\n const defaultMessage = 'CashAssembly primitive method does not exist';\n super(`${defaultMessage}: identifier \"${identifier}\", methodName \"${methodName}\", hint \"${hint}\"`);\n }\n}\n\n/**\n * Error thrown when a value cannot be resolved as bytes.\n */\nexport class CashAssemblyUnsupportedValueTypeError extends Error {\n constructor(identifier: string, returnedType: string) {\n const defaultMessage = 'CashAssembly value type is unsupported for byte resolution';\n super(`${defaultMessage}: identifier \"${identifier}\", returnedType \"${returnedType}\"`);\n }\n}\n\n/**\n * Error thrown when a number cannot be safely encoded as a CashAssembly VM number.\n */\nexport class CashAssemblyNumberNotSafeIntegerError extends Error {\n constructor(identifier: string, value: number) {\n const defaultMessage = 'CashAssembly number is not a safe integer';\n super(`${defaultMessage}: identifier \"${identifier}\", got ${String(value)}`);\n }\n}\n\n/**\n * Error thrown when a supported primitive is selected but its value is missing when provided in the variables map.\n */\nexport class CashAssemblyPrimitiveVariableMissingError extends Error {\n constructor(identifier: string, variableName: string) {\n const defaultMessage = 'CashAssembly primitive variable is missing from the variables map';\n super(`${defaultMessage}: identifier \"${identifier}\", variableName \"${variableName}\"`);\n }\n}\n\n/**\n * Error thrown when compiled evaluation bytes cannot be decoded as a VM number.\n */\nexport class CashAssemblyVmNumberDecodeError extends Error {\n constructor(reason: string) {\n const defaultMessage = 'CashAssembly evaluation could not be decoded as a VM number';\n super(`${defaultMessage}: ${reason}`);\n }\n}\n","/**\n * Detects whether a string is a pure CashAssembly expression.\n *\n * CashAssembly expressions look like `$(<variable>)` or `$(<a> <b>)`. This pattern checks\n * that the entire string is one such expression and nothing else. It will not match if\n * there is other text surrounding the expression.\n *\n * For example:\n * `$(<fee>)` matches (a full expression)\n * `OP_DUP $(<fee>)` does not match (extra text before it)\n * `$()` does not match (empty expression)\n */\nexport const CASHASSEMBLY_EXPRESSION_PATTERN = /^\\$\\([^)]+\\)$/;\n\n/**\n * Finds all CashAssembly evaluations embedded in a larger string.\n *\n * An evaluation looks like `$(...)`, for example `$(<fee>)` or `$(<a> <b>)`. This pattern\n * locates every occurrence in the input and returns them all (global flag `g`).\n * Empty evaluations `$()` are intentionally excluded because they reference no variables.\n *\n * For example, scanning `\"OP_DUP <$(<pubkeyHash>)> OP_HASH160 $(<fee>)\"` would return\n * `['$(<pubkeyHash>)', '$(<fee>)']`.\n */\nexport const CASHASSEMBLY_EVALUATION_PATTERN = /\\$\\([^)]+\\)/g;\n\n/**\n * Extracts variable names from angle-bracket references inside a CashAssembly evaluation.\n *\n * Inside an evaluation like `$(<pubkeyHash> <fee>)`, variables are referenced as `<name>`.\n * This pattern captures the name between the brackets. The global flag `g` allows iterating\n * over every variable reference in a single evaluation string.\n *\n * For example, running this against `$(<pubkeyHash> <fee>)` would return the variable names\n * `[\"pubkeyHash\", \"fee\"]`.\n */\nexport const CASHASSEMBLY_VARIABLE_PATTERN = /<([^>]+)>/g;\n\n/**\n * Identifies CashAssembly literal tokens that appear inside angle-bracket push statements.\n *\n * Inside an evaluation, not everything between `<` and `>` is a variable name. Literals are\n * also valid push contents: numeric literals (e.g. `<0>`, `<32>`), hex literals (`<0x02>`),\n * binary literals (`<0b1010>`), and string literals (`<\"minting\">`, `<'hello'>`). This pattern\n * matches any captured token that starts with a digit or a quote character.\n */\nexport const CASHASSEMBLY_LITERAL_TOKEN_PATTERN = /^[0-9\"']/;\n\n/**\n * Matches a single dot variable method reference inside an angle-bracket identifier.\n *\n * Used to detect primitive method references such as `expiry.toIso8601`.\n *\n * For example:\n * `expiry.toIso8601` matches (base `expiry`, method `toIso8601`)\n * `requestedSatoshis` does not match (no method)\n * `key.schnorr_signature.all_outputs` does not match (more than one dot)\n * `key.public_key` matches the pattern shape but it is only resolved\n * when `hint` maps to a primitive\n */\nexport const CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN = /^([^.]+)\\.([^.]+)$/;\n","import { bigIntToVmNumber, utf8ToBin } from '@bitauth/libauth';\nimport { CashAssemblyNumberNotSafeIntegerError, CashAssemblyUnsupportedValueTypeError } from './errors.ts';\n\n/**\n * Converts a value into bytes representation.\n *\n * @param {unknown} value - Value to encode, should be one of: Uint8Array, bigint, boolean, string, or a safe integer number.\n * @param {string} valueIdentifier - Identifier used in error messages.\n * @returns {Uint8Array} Bytes representation of the value.\n * @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number is not a safe integer.\n * @throws {@link CashAssemblyUnsupportedValueTypeError} When the value type cannot be resolved.\n */\nexport const convertValueToBytes = (value: unknown, valueIdentifier: string): Uint8Array => {\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (typeof value === 'bigint') {\n return bigIntToVmNumber(value);\n }\n\n if (typeof value === 'boolean') {\n // The BCH VM treats an empty byte array as false and any nonempty byte array as true.\n return new Uint8Array(value ? [ 1 ] : []);\n }\n\n if (typeof value === 'string') {\n return utf8ToBin(value);\n }\n\n if (typeof value === 'number') {\n if (Number.isSafeInteger(value) === true) {\n return bigIntToVmNumber(BigInt(value));\n }\n\n throw new CashAssemblyNumberNotSafeIntegerError(valueIdentifier, value);\n }\n\n throw new CashAssemblyUnsupportedValueTypeError(valueIdentifier, typeof value);\n};\n","import {\n FungibleTokenAmount,\n NFTCommitment,\n PublicKey,\n Satoshis,\n SchnorrSignature,\n TemplateIdentifier,\n Timestamp,\n TokenCategory,\n TransactionHash,\n} from '@xo-cash/primitives';\nimport { XOTemplatePrimitiveTypes } from '@xo-cash/types';\nimport type { XOTemplate, XOTemplatePrimitiveType } from '@xo-cash/types';\nimport { CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError } from './errors.ts';\nimport { CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN } from './defaults.ts';\nimport { convertValueToBytes } from './bytes.ts';\n\n/**\n * Template hint values mapped to a primitive class for resolving primitive method evaluations.\n * Keys are values from XOTemplatePrimitiveTypes.\n */\nconst PRIMITIVE_BY_TEMPLATE_HINT = {\n [XOTemplatePrimitiveTypes.FUNGIBLE_TOKEN_AMOUNT]: FungibleTokenAmount,\n [XOTemplatePrimitiveTypes.NFT_COMMITMENT]: NFTCommitment,\n [XOTemplatePrimitiveTypes.PUBLIC_KEY]: PublicKey,\n [XOTemplatePrimitiveTypes.SATOSHIS]: Satoshis,\n [XOTemplatePrimitiveTypes.SCHNORR_SIGNATURE]: SchnorrSignature,\n [XOTemplatePrimitiveTypes.TEMPLATE_IDENTIFIER]: TemplateIdentifier,\n [XOTemplatePrimitiveTypes.TIMESTAMP]: Timestamp,\n [XOTemplatePrimitiveTypes.TOKEN_CATEGORY]: TokenCategory,\n [XOTemplatePrimitiveTypes.TRANSACTION_HASH]: TransactionHash,\n} as const;\n\ntype SupportedPrimitiveHint = keyof typeof PRIMITIVE_BY_TEMPLATE_HINT;\n\n/**\n * Inputs needed to call a primitive method for a `name.method` push.\n */\ntype CallPrimitiveMethodParameters = {\n\n /**\n * Full push identifier from the evaluation, for example `amount.toSatoshis`.\n */\n identifier: string;\n\n /**\n * Method name to call on the constructed primitive, for example `toIso8601`.\n */\n methodName: string;\n\n /**\n * Value for the variable.\n */\n value: unknown;\n\n /**\n * Supported template hint that selects the primitive class.\n */\n hint: SupportedPrimitiveHint;\n};\n\n/**\n * Inputs needed to resolve primitive method pushes from extracted CashAssembly identifiers.\n */\nexport type ResolvePrimitiveMethodBytesParameters = {\n\n /**\n * Variable identifiers from {@link extractVariablesFromEvaluations}, for example\n * `['amount.toSatoshis', 'fee.toSatoshis']`.\n */\n identifiers: string[];\n\n /**\n * Variable names and values object.\n */\n variables: Record<string, unknown>;\n\n /**\n * Template variable definitions. When omitted, no primitive methods are resolved.\n * The `hint` on each entry selects the primitive class.\n */\n templateVariables?: XOTemplate['variables'];\n};\n\n/**\n * Returns true when `hint` maps to a supported primitive class in `PRIMITIVE_BY_TEMPLATE_HINT`.\n *\n * @param {XOTemplatePrimitiveType | undefined} hint - Template variable hint.\n * @returns {boolean} True when the hint selects a supported primitive class.\n */\nconst isSupportedPrimitiveHint = (hint: XOTemplatePrimitiveType | undefined): hint is SupportedPrimitiveHint => {\n return hint !== undefined && Object.hasOwn(PRIMITIVE_BY_TEMPLATE_HINT, hint) === true;\n};\n\n/**\n * Returns true when `methodName` is an own function on the primitive class for `hint`.\n *\n * @param {SupportedPrimitiveHint} hint - Supported template hint.\n * @param {string} methodName - Method name from the evaluation text, for example `toSatoshis`.\n * @returns {boolean} True when that class exposes the named method.\n */\nconst canResolvePrimitiveMethod = (hint: SupportedPrimitiveHint, methodName: string): boolean => {\n const PrimitiveClass = PRIMITIVE_BY_TEMPLATE_HINT[hint];\n\n // Check own properties only so inherited Object.prototype names are rejected without needing a value.\n if (Object.hasOwn(PrimitiveClass.prototype, methodName) === false) {\n return false;\n }\n\n return typeof Reflect.get(PrimitiveClass.prototype, methodName) === 'function';\n};\n\n/**\n * Constructs a primitive from a raw value and calls one instance method on it.\n *\n * Call only after `canResolvePrimitiveMethod` is true for the same hint and method.\n *\n * @param {CallPrimitiveMethodParameters} parameters - Identifier, method, value, and supported hint.\n * @returns {unknown} Method return value, later encoded as CashAssembly push bytes.\n * @throws {@link CashAssemblyPrimitiveMethodMissingError} When the prototype member is not a function.\n * @throws When the primitive constructor rejects the raw value (validation errors from `@xo-cash/primitives`).\n */\nconst callPrimitiveMethod = (parameters: CallPrimitiveMethodParameters): unknown => {\n const { identifier, methodName, value, hint } = parameters;\n\n const PrimitiveClass = PRIMITIVE_BY_TEMPLATE_HINT[hint];\n\n // Constructing runs each primitive's own input validation (range checks, hex length, etc).\n // `as never` satisfies TypeScript across constructors that accept different input shapes.\n const primitiveInstance = new PrimitiveClass(value as never);\n\n // Same prototype member canResolvePrimitiveMethod already verified as an own function.\n const primitiveMethod = Reflect.get(PrimitiveClass.prototype, methodName);\n\n if (typeof primitiveMethod !== 'function') {\n throw new CashAssemblyPrimitiveMethodMissingError(identifier, methodName, hint);\n }\n\n return primitiveMethod.call(primitiveInstance);\n};\n\n/**\n * Resolves supported `base.method` identifiers to CashAssembly variable bytes.\n *\n * Each single dot identifier whose `hint` maps to a supported primitive is resolved and stored under\n * the full identifier (`base.method`). Unsupported or multi dot identifiers are left for CashAssembly.\n *\n * When `templateVariables` is omitted, returns an empty map.\n *\n * @param {ResolvePrimitiveMethodBytesParameters} parameters - Identifiers, values, and optional template metadata.\n * @returns {Record<string, Uint8Array>} Resolved method identifiers mapped to bytes for CashAssembly pushes.\n * @throws {@link CashAssemblyPrimitiveMethodMissingError} When the hint is a supported primitive but the method is missing.\n * @throws {@link CashAssemblyPrimitiveVariableMissingError} When the runtime value is missing from the variables map.\n * @throws {@link CashAssemblyUnsupportedValueTypeError} When the method return type cannot be embedded.\n * @throws {@link CashAssemblyNumberNotSafeIntegerError} When a method return value is a number that is not a safe integer.\n */\nexport const resolvePrimitiveMethodBytes = (parameters: ResolvePrimitiveMethodBytesParameters): Record<string, Uint8Array> => {\n const { identifiers, templateVariables, variables } = parameters;\n\n // Without template metadata there is no hint to select a primitive class.\n if (templateVariables === undefined) {\n return {};\n }\n\n const resolvedBytes: Record<string, Uint8Array> = {};\n\n for (const identifier of identifiers) {\n // The same identifier can appear more than once. Resolve it only once.\n if (Object.hasOwn(resolvedBytes, identifier) === true) {\n continue;\n }\n\n // Find the primitive method reference in the identifier.\n const methodReferenceMatch = identifier.match(CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN);\n\n if (methodReferenceMatch === null) {\n continue;\n }\n\n const [ , baseName, methodName ] = methodReferenceMatch;\n\n // Unknown identifiers and CashAssembly native operations such as someKey.schnorr_signature.all_outputs\n // must be left for CashAssembly rather than treated as primitive failures.\n if (Object.hasOwn(templateVariables, baseName) === false) {\n continue;\n }\n\n const hint = templateVariables[baseName].hint;\n\n if (isSupportedPrimitiveHint(hint) === false) {\n continue;\n }\n\n // Supported hint with an unknown method should be thrown as an error.\n if (canResolvePrimitiveMethod(hint, methodName) === false) {\n throw new CashAssemblyPrimitiveMethodMissingError(identifier, methodName, hint);\n }\n\n // If the method is known but the runtime value is missing, throw an error.\n if (Object.hasOwn(variables, baseName) === false) {\n throw new CashAssemblyPrimitiveVariableMissingError(identifier, baseName);\n }\n\n const methodResult = callPrimitiveMethod({\n identifier,\n methodName,\n value: variables[baseName],\n hint,\n });\n\n // Store the result under identifier.\n resolvedBytes[identifier] = convertValueToBytes(methodResult, identifier);\n }\n\n return resolvedBytes;\n};\n","/**\n * Utilities for parsing, extracting, and compiling CashAssembly expressions.\n *\n * CashAssembly is the scripting language used by Bitauth templates to describe Bitcoin Cash\n * locking and unlocking scripts.\n *\n * ## Syntax (CashAssembly)\n *\n * `<expression>` is a push statement. Compiles the contents and pushes the result onto the VM stack.\n * `<someKey.public_key>` pushes the 33 byte compressed public key. `<1>` pushes the integer 1.\n *\n * `$(<expression>)` is an evaluation. Runs the inner script in the VM and inserts the top stack\n * item as VM bytecode.\n * `$(<someKey.public_key> OP_HASH160)` inserts the HASH160 of the public key.\n *\n * `<$(<expression>)>` is a push of an evaluation result. It evaluates first then pushes.\n * For a P2PKH locking script example see\n * `OP_DUP OP_HASH160 <$(<someKey.public_key> OP_HASH160)> OP_EQUALVERIFY OP_CHECKSIG`.\n *\n * `variableId.operation` is a variable with a compiler resolved operation. `someKey.public_key`\n * produces the public key bytes. `someKey.schnorr_signature.all_outputs` produces a Schnorr\n * signature.\n *\n * Opcodes (`OP_DUP`, `OP_HASH160`, and similar) are inserted as their bytecode equivalent directly.\n *\n * ## Name resolution priority (CashAssembly)\n *\n * When the compiler encounters an identifier it resolves it in this order.\n * 1. Opcode always wins. Naming a variable or script `OP_ADD` will not shadow it.\n * 2. Variable shadows scripts of the same name.\n * 3. Script is the script's bytecode.\n *\n * ## Resolution Order (CashAssembly + Primitive Method Resolution)\n *\n * Supported `<base.method>` pushes are resolved to bytes before CashAssembly compiles.\n * Inside CashAssembly the order is Opcode then Variable then Script.\n */\nimport type { CompilerBch } from '@bitauth/libauth';\nimport { binToHex, binToUtf8, createCompilerBch, vmNumberToBigInt } from '@bitauth/libauth';\nimport type { XOInvitationVariableValue, XOTemplate } from '@xo-cash/types';\nimport {\n CashAssemblyCompilationFailedError,\n CashAssemblyVariableTypeMismatchError,\n CashAssemblyRequiredVariableMissingError,\n CashAssemblyVmNumberDecodeError,\n} from './errors.ts';\nimport {\n CASHASSEMBLY_EVALUATION_PATTERN,\n CASHASSEMBLY_EXPRESSION_PATTERN,\n CASHASSEMBLY_LITERAL_TOKEN_PATTERN,\n CASHASSEMBLY_VARIABLE_PATTERN,\n} from './defaults.ts';\nimport { convertValueToBytes } from './bytes.ts';\nimport { resolvePrimitiveMethodBytes } from './primitive-evaluations.ts';\n\n/**\n * Supported decode modes for compiled CashAssembly evaluation bytes.\n */\nexport type CompiledCashAssemblyDecodeMode = 'utf8' | 'hex' | 'boolean' | 'bigint' | 'uint8array';\n\n/**\n * Parameters for compiling CashAssembly string.\n */\nexport type CompileCashAssemblyStringParameters = {\n\n /**\n * Text that may embed CashAssembly evaluations such as `$(<fee>)` or `$(<expiry.toIso8601>)`.\n */\n cashAssemblyText: string;\n\n /**\n * Used for both primitive method evaluations and normal CashAssembly compilation.\n */\n variables: Record<string, XOInvitationVariableValue | Uint8Array>;\n\n /**\n * The mode to decode compiled evaluation bytes into a string.\n */\n evaluationDecodeMode?: CompiledCashAssemblyDecodeMode;\n\n /**\n * Optional template variable definitions. When provided, each `<name.method>` push whose `hint`\n * maps to a supported primitive class is resolved to bytes before CashAssembly compilation.\n */\n templateVariables?: XOTemplate['variables'];\n};\n\n/**\n * Checks if the expression is a CashAssembly expression.\n *\n * @param {unknown} expression - The expression to check.\n * @returns {boolean} True if the expression is a CashAssembly expression, false otherwise.\n */\nexport const isCashAssemblyExpression = (expression: unknown): boolean => {\n return typeof expression === 'string' && CASHASSEMBLY_EXPRESSION_PATTERN.test(expression);\n};\n\n/**\n * Extracts all CashAssembly evaluations (i.e., substrings like $(...)) from the input text.\n *\n * @param {string} text - The input string to scan for CashAssembly evaluations.\n * @returns {string[]} An array of evaluation strings found in the input.\n *\n * @example\n * extractCashAssemblyEvaluations(\"OP_DUP <$(<foo>)> OP_HASH160 $(<bar>)\");\n * // returns ['$(<foo>)', '$(<bar>)']\n */\nexport const extractCashAssemblyEvaluations = (text: string): string[] => {\n return text.match(CASHASSEMBLY_EVALUATION_PATTERN) ?? [];\n};\n\n/**\n * Returns the segment of `identifier` before the first `.`.\n *\n * When there is no `.`, returns `identifier` unchanged.\n * Multi segment identifiers such as `foo.bar.baz` resolve to `foo`.\n *\n * @param {string} identifier - Identifier that may contain a dot.\n * @returns {string} The base name before the first `.`.\n */\nconst resolveIdentifierBaseName = (identifier: string): string => {\n const firstDotIndex = identifier.indexOf('.');\n\n if (firstDotIndex === -1) {\n return identifier;\n }\n\n return identifier.slice(0, firstDotIndex);\n};\n\n/**\n * Extracts unique variable identifiers enclosed in angle brackets from each evaluation string.\n *\n * CashAssembly literal tokens such as hex bytes, numbers, and quoted strings are excluded via\n * {@link CASHASSEMBLY_LITERAL_TOKEN_PATTERN}. For example, `<0x02>` and `<\"minting\">` are not returned.\n *\n * @param {string[]} evaluations - An array of evaluation strings from which to extract variable names.\n * @returns {string[]} An array of variable names.\n */\nexport const extractVariablesFromEvaluations = (evaluations: string[]): string[] => {\n const uniqueVariables = new Set<string>();\n\n for (const evaluation of evaluations) {\n for (const [ , extractedIdentifier ] of evaluation.matchAll(CASHASSEMBLY_VARIABLE_PATTERN)) {\n if (CASHASSEMBLY_LITERAL_TOKEN_PATTERN.test(extractedIdentifier)) {\n continue;\n }\n\n uniqueVariables.add(extractedIdentifier);\n }\n }\n\n return [ ...uniqueVariables ];\n};\n\n/**\n * Decodes compiled CashAssembly evaluation bytes into a string representation.\n *\n * 'evaluationDecodeMode' determines how the evaluation bytes are interpreted and presented.\n * Use `bigint` for numeric values like satoshis, `utf8` for text labels, `hex` for binary data\n * such as hashes, and `boolean` to represent boolean values.\n *\n * @param {Uint8Array} compiledResult - The compiled evaluation bytecode.\n * @param {CompiledCashAssemblyDecodeMode} [evaluationDecodeMode='utf8'] - The decode mode used to convert\n * bytes to text.\n * @returns {string} The decoded value as a string suitable for inline replacement.\n * @throws {@link CashAssemblyVmNumberDecodeError} When `evaluationDecodeMode` is `bigint` and the bytes are not a VM number.\n */\nexport const decodeCompiledCashAssemblyEvaluation = (\n compiledResult: Uint8Array,\n evaluationDecodeMode: CompiledCashAssemblyDecodeMode = 'utf8',\n): string => {\n // Converts the byte array to a string.\n if (evaluationDecodeMode === 'uint8array') {\n return String(compiledResult);\n }\n\n // Converts the byte array to a boolean string, converting the evaluation result into a true or a false.\n if (evaluationDecodeMode === 'boolean') {\n return compiledResult.length === 0 ? 'false' : 'true';\n }\n\n // Converts the byte array to a hex string.\n if (evaluationDecodeMode === 'hex') {\n return binToHex(compiledResult);\n }\n\n // Converts the byte array to a bigint string.\n if (evaluationDecodeMode === 'bigint') {\n const vmNumberResult = vmNumberToBigInt(compiledResult);\n\n if (typeof vmNumberResult === 'bigint') {\n return vmNumberResult.toString();\n }\n\n throw new CashAssemblyVmNumberDecodeError(vmNumberResult);\n }\n\n // Converts the byte array to a utf8 string.\n return binToUtf8(compiledResult);\n};\n\n/**\n * Generates bytecode for a specific CashAssembly evaluation using given variable values and a prepared compiler.\n *\n * @param {CompilerBch} compiler - The libauth compiler from {@link compileCashAssemblyEvaluations}.\n * @param {string} evaluation - The specific evaluation string to compile.\n * @param {Record<string, Uint8Array>} variables - A record mapping variable names to their values.\n * @returns {Uint8Array} The compiled bytecode.\n * @throws {@link CashAssemblyRequiredVariableMissingError} If a required variable is not present.\n * @throws {@link CashAssemblyVariableTypeMismatchError} If a variable value is not a Uint8Array.\n * @throws {@link CashAssemblyCompilationFailedError} If libauth compilation fails.\n */\nexport const generateCashAssemblyBytecode = (compiler: CompilerBch, evaluation: string, variables: Record<string, Uint8Array>): Uint8Array => {\n const variableNames = extractVariablesFromEvaluations([ evaluation ]);\n\n // Validate that all required variables are provided\n const missingVariables = variableNames.filter((name: string) => !Object.hasOwn(variables, name));\n if (missingVariables.length > 0) {\n throw new CashAssemblyRequiredVariableMissingError(missingVariables);\n }\n\n // Construct the bytecode object using the keys in variableNames, mapping to the values in variables\n const bytecode: Record<string, Uint8Array> = {};\n for (const variableName of variableNames) {\n const value = variables[variableName];\n\n // By the time execution reaches this point, the value should be a Uint8Array.\n if (!(value instanceof Uint8Array)) {\n throw new CashAssemblyVariableTypeMismatchError(variableName, 'Uint8Array', typeof value);\n }\n\n bytecode[variableName] = value;\n }\n\n const compiledBytecode = compiler.generateBytecode({\n data: { bytecode },\n scriptId: evaluation,\n });\n\n if (!compiledBytecode.success) {\n // Collapse libauth's full errors list into one string because\n // CashAssemblyCompilationFailedError only carries a single message.\n let compilationFailureMessage = 'unknown compilation failure';\n\n if ('errors' in compiledBytecode && compiledBytecode.errors.length > 0) {\n compilationFailureMessage = compiledBytecode.errors.map((compilationError) => compilationError.error).join('; ');\n }\n\n throw new CashAssemblyCompilationFailedError(compilationFailureMessage);\n }\n\n return compiledBytecode.bytecode;\n};\n\n/**\n * Prepares a compiler for the provided CashAssembly evaluations, setting required variables as 'WalletData'.\n *\n * @param {string[]} evaluations - Array of evaluation strings (e.g., ['$(<var1>)', '$(<var2> <var3>)']).\n * @returns {CompilerBch} A Libauth compiler instance for use with these evaluations.\n */\nexport const compileCashAssemblyEvaluations = (evaluations: string[]): CompilerBch => {\n // Create a scripts object where each key is the evaluation and the value is also the evaluation\n const scripts: Record<string, string> = {};\n for (const evaluation of evaluations) {\n scripts[evaluation] = evaluation;\n }\n\n // Get the variable names from the evaluations.\n const variableNames = extractVariablesFromEvaluations(evaluations);\n\n // Register each base name once. Dotted pushes share one WalletData entry under the base name.\n const variables: Record<string, { type: 'WalletData' }> = {};\n for (const variableName of variableNames) {\n variables[resolveIdentifierBaseName(variableName)] = { type: 'WalletData' as const };\n }\n\n // Create the libauth compiler.\n const compiler = createCompilerBch({\n scripts,\n variables,\n });\n\n return compiler;\n};\n\n/**\n * Compiles all CashAssembly evaluations in a text string and replaces each evaluation\n * with a decoded string representation.\n *\n * @param {CompileCashAssemblyStringParameters} parameters - Parameters for compiling the CashAssembly string.\n * @param {string} parameters.cashAssemblyText - The string with CashAssembly evaluations.\n * @param {Record<string, XOInvitationVariableValue | Uint8Array>} parameters.variables - Object mapping\n * variable names to values for compilation.\n * @param {CompiledCashAssemblyDecodeMode} [parameters.evaluationDecodeMode='utf8'] - The decode mode used\n * after each evaluation is compiled. See {@link decodeCompiledCashAssemblyEvaluation}.\n * @param {XOTemplate['variables']} [parameters.templateVariables] - Optional template variable definitions\n * used to resolve supported `<name.method>` pushes via each variable's `hint`.\n * @returns {string} Compiled text with all evaluations replaced by decoded string values.\n * @throws {@link CashAssemblyRequiredVariableMissingError} When a required variable is not present in the variables map.\n * @throws {@link CashAssemblyPrimitiveMethodMissingError} When a supported primitive hint has an unknown method.\n * @throws {@link CashAssemblyPrimitiveVariableMissingError} When a supported primitive method is missing its runtime value.\n * @throws {@link CashAssemblyUnsupportedValueTypeError} When a primitive method return type cannot be embedded as bytes.\n * @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number variable is not a safe integer.\n * @throws {@link CashAssemblyVmNumberDecodeError} When `evaluationDecodeMode` is `bigint` and an evaluation is not a VM number.\n */\nexport const compileCashAssemblyString = (parameters: CompileCashAssemblyStringParameters): string => {\n const { cashAssemblyText, variables, evaluationDecodeMode = 'utf8', templateVariables } = parameters;\n\n return cashAssemblyText.replace(CASHASSEMBLY_EVALUATION_PATTERN, (evaluation) => {\n // Extract variable identifiers required by the current evaluation.\n const variableNames = extractVariablesFromEvaluations([ evaluation ]);\n\n const primitiveMethodBytes = resolvePrimitiveMethodBytes({\n identifiers: variableNames,\n templateVariables,\n variables,\n });\n\n // Prefer resolved method bytes. Fall back to converting the raw variable value.\n const missingVariables = variableNames.filter((variableName) => {\n if (Object.hasOwn(primitiveMethodBytes, variableName) === true) {\n return false;\n }\n\n return Object.hasOwn(variables, variableName) === false;\n });\n\n if (missingVariables.length > 0) {\n throw new CashAssemblyRequiredVariableMissingError(missingVariables);\n }\n\n // Convert each variable to its bytes before compilation.\n const variableBytes: Record<string, Uint8Array> = {};\n for (const variableName of variableNames) {\n if (Object.hasOwn(primitiveMethodBytes, variableName) === true) {\n variableBytes[variableName] = primitiveMethodBytes[variableName];\n continue;\n }\n\n variableBytes[variableName] = convertValueToBytes(variables[variableName], variableName);\n }\n\n // Compile the evaluation in isolation.\n const compiler = compileCashAssemblyEvaluations([ evaluation ]);\n\n // Generate the bytes for the evaluation.\n const compilationResult: Uint8Array = generateCashAssemblyBytecode(compiler, evaluation, variableBytes);\n\n // Decode the bytes into a string as per the decode mode.\n return decodeCompiledCashAssemblyEvaluation(compilationResult, evaluationDecodeMode);\n });\n};\n"],"mappings":";;;;;;;;;AAGA,IAAa,sBAAb,cAAyC,MAAM;CAC3C,YAAY,MAAc;AACtB,QAAM,8BAA8B,KAAK,GAAG;AAC5C,OAAK,OAAO;;;;;;;;;;AC8BpB,IAAa,eAAb,MAA8C;;;;;CAK1C,6BAA2D,IAAI,KAAK;;;;;;;;CASpE,GAAsB,MAAS,UAA0B,uBAA+B,GAAgB;EACpG,MAAM,EAAE,QAAQ,UAAU,wBAAwB,KAAK,YAAY,SAAS;EAG5E,MAAM,kBAAkB,uBAAuB,IAAI,KAAK,SAAS,qBAAqB,qBAAqB,GAAG;AAG9G,MAAI,CAAC,MAAKA,UAAW,IAAI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GACrD,aAAa;GACb;GACA;GACH,CAAC;EAGF,MAAM,mBAAmB,cAAc,QAAQ,iBAAiB;AAC5D,OAAI,OAAO,OAAO,sBAAsB,aAAa,KAAK,KACtD,QAAO;AAGX,UAAO,OAAO,OAAO,WAAW,aAAa,KAAK;IACpD;AAEF,MAAI,iBAAiB,SAAS,EAC1B,OAAM,IAAI,yCAAyC,iBAAiB;EAIxE,MAAM,gBAA4C,EAAE;AACpD,OAAK,MAAM,gBAAgB,eAAe;AACtC,OAAI,OAAO,OAAO,sBAAsB,aAAa,KAAK,MAAM;AAC5D,kBAAc,gBAAgB,qBAAqB;AACnD;;AAGJ,iBAAc,gBAAgB,oBAAoB,UAAU,eAAe,aAAa;;AAU5F,SAAO,qCAH+B,6BAHrB,+BAA+B,CAAE,WAAY,CAAC,EAGc,YAAY,cAAc,EAGxC,qBAAqB;GACtF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["#stream","#controller","#closed","#textDecoder","#messageBuffer"],"sources":["../source/extended-json.ts","../source/script.ts","../source/sse-session/async-push-iterator.ts","../source/sse-session/constants.ts","../source/sse-session/sse-event-parser.ts","../source/template/errors.ts","../source/template/serialization.ts","../source/template/identifier.ts","../source/template/schemas.ts","../source/template/parser.ts","../source/cash-assembly/errors.ts","../source/cash-assembly/defaults.ts","../source/cash-assembly/bytes.ts","../source/cash-assembly/primitive-evaluations.ts","../source/cash-assembly/evaluations.ts"],"sourcesContent":["import { binToHex, hexToBin } from '@bitauth/libauth';\n\n/**\n * Matches a bigint encoded in Extended JSON format: `<bigint: 123n>`.\n */\nconst EXTENDED_JSON_BIGINT_PATTERN = /^<bigint: (?<bigint>[+-]?[0-9]+)n>$/u;\n\n/**\n * Matches a Uint8Array encoded in Extended JSON format: `<uint8array: abcd>`.\n */\nconst EXTENDED_JSON_UINT8ARRAY_PATTERN = /^<uint8array: (?<hex>[0-9a-f]*)>$/u;\n\n/**\n * The JSON replacer that encodes `bigint` and `Uint8Array` values in Extended JSON format,\n * compatible with the format expected by `extendedJsonReviver`.\n *\n * - BigInts are encoded as `<bigint: 123n>`.\n * - Uint8Arrays are encoded as `<uint8array: abcd>`.\n * All other values pass through unchanged and if any incompatible type is encountered, an error is thrown.\n *\n * Note: To use this function, pass it as the second argument to `JSON.stringify` when serializing data.\n *\n * Note to developers: Libauth's `stringify` is the replacer. It also serializes functions and symbols,\n * which we do not support. Passing it would let templates include those values, but revival would then fail.\n * This module provides a dedicated replacer and reviver so serialization and deserialization stay aligned.\n *\n * @param _propertyKey The property key being serialized, required by the `JSON.stringify` replacer but not used here.\n * @param value The value to encode or pass through unchanged.\n * @returns The encoded string\n */\nexport const extendedJsonReplacer = (_propertyKey: string, value: unknown): unknown => {\n if (value instanceof Uint8Array) {\n return `<uint8array: ${binToHex(value)}>`;\n }\n\n if (typeof value === 'bigint') {\n return `<bigint: ${value.toString()}n>`;\n }\n\n return value;\n};\n\n/**\n * The JSON reviver that reconstructs `bigint` and `Uint8Array` values encoded by `extendedJsonReplacer`.\n *\n * Note: To use this function, pass it as the second argument to `JSON.parse` when deserializing data.\n *\n * @param _propertyKey The property key being deserialized, required by the `JSON.parse` reviver but not used here.\n * @param value The value to reconstruct or pass through unchanged.\n * @returns The reconstructed value\n */\nexport const extendedJsonReviver = (_propertyKey: string, value: unknown): unknown => {\n // If the value is not a string, return the original value\n if (typeof value !== 'string') {\n return value;\n }\n\n // Match the bigint pattern\n const bigintPatternMatch = value.match(EXTENDED_JSON_BIGINT_PATTERN);\n\n // If the value matches the bigint pattern, return the reconstructed bigint\n if (bigintPatternMatch) {\n return BigInt(bigintPatternMatch.groups!.bigint);\n }\n\n // Match the Uint8Array pattern\n const uint8arrayPatternMatch = value.match(EXTENDED_JSON_UINT8ARRAY_PATTERN);\n\n // If the value matches the Uint8Array pattern, return the reconstructed Uint8Array\n if (uint8arrayPatternMatch) {\n return hexToBin(uint8arrayPatternMatch.groups!.hex);\n }\n\n // If the value does not match either pattern, return the original value\n return value;\n};\n\n/**\n * Serializes an object to a string using the {@link extendedJsonReplacer}.\n *\n * @param object The object to serialize.\n * @returns The string representation of the object in Extended JSON format.\n */\nexport const toExtendedJson = (object: unknown): string => {\n return JSON.stringify(object, extendedJsonReplacer);\n};\n\n/**\n * Deserializes a string to an object using the {@link extendedJsonReviver}.\n *\n * @param serializedObject The string to deserialize.\n * @returns The object reconstructed from the string.\n */\nexport const fromExtendedJson = (serializedObject: string): unknown => {\n return JSON.parse(serializedObject, extendedJsonReviver);\n};\n","import { binToHex, sha256 } from '@bitauth/libauth';\n\n/**\n * Converts a script to a scriptHash.\n * @param {Uint8Array} script - The script to convert.\n * @returns {string} The scriptHash as a reversed hex string.\n */\nexport const scriptToScriptHash = (script: Uint8Array): string => {\n // Hash the script.\n const hash = sha256.hash(script);\n\n // Reverse the hash. (Electrum style, reverse switches to little endian representation)\n const reversed = hash.reverse();\n\n // Convert the reversed hash to hex.\n return binToHex(reversed);\n};\n","/**\n * An async iterable queue that bridges push-based producers and pull-based consumers.\n *\n * Composes an internal {@link ReadableStream} instead of extending it, so producers\n * call {@link push} while consumers use standard async iteration (`for await...of`).\n *\n * ```ts\n * const messages = new AsyncPushIterator<SSEvent>();\n *\n * // Producer (elsewhere)\n * messages.push(event);\n *\n * // Consumer\n * for await (const event of messages) {\n * handle(event);\n * }\n * ```\n *\n * {@link Symbol.asyncIterator} returns `stream.values({ preventCancel: true })` so\n * breaking out of `for await...of` does not cancel the underlying stream. That\n * matters for long-lived sessions where the producer keeps pushing after a consumer\n * stops reading early (for example, test helpers that only collect a fixed count).\n */\nexport class AsyncPushIterator<T> {\n /** ReadableStream backing the async iterator returned from {@link Symbol.asyncIterator}. */\n #stream: ReadableStream<T>;\n\n /** Controller used to enqueue values and close the stream from {@link push} and {@link close}. */\n #controller: ReadableStreamDefaultController<T> | undefined;\n\n /** When true, no more values are accepted and iteration eventually completes. */\n #closed = false;\n\n public constructor() {\n // `start`'s `this` is the underlying source object when using a plain method.\n // An arrow function captures the class instance so the controller is stored here.\n this.#stream = new ReadableStream({\n start: (controller: ReadableStreamDefaultController<T>): void => {\n this.#controller = controller;\n },\n });\n }\n\n /**\n * Flag indicating if the iterator is closed.\n */\n public get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Enqueues a value for the consumer.\n *\n * After {@link close}, pushes are silently dropped.\n *\n * @param value - The next value to yield from the iterator.\n */\n push(value: T): void {\n if (this.#closed) return;\n\n this.#controller?.enqueue(value);\n }\n\n /**\n * Causes any future interactions with the associated stream to error with {@link error}.\n * Calling this will also clear the pending values immediately, so iterators that were listening will not receive them.\n *\n * @param error - The error to throw from the stream.\n */\n error(error: Error): void {\n if (this.#closed) return;\n\n this.#closed = true;\n this.#controller?.error(error);\n }\n\n /**\n * Ends the stream.\n *\n * Marks the iterator closed so future {@link push} calls are ignored.\n * Buffered values are still yielded before iteration completes.\n */\n close(): void {\n this.#closed = true;\n\n try {\n this.#controller?.close();\n } catch {\n // The reader may already have released or cancelled the stream.\n }\n }\n\n /**\n * Returns an async iterator over the composed stream.\n *\n * Uses `preventCancel: true` so early `break` from `for await...of` does not\n * close the stream and block later pushes.\n *\n * Because values are discarded after being read, only a single consumer is supported.\n * Additional consumers will receive a stream lock error. Unread values will be preserved until {@link close} is called.\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n return this.#stream.values({ preventCancel: true });\n }\n}\n","/**\n * Regex that splits decoded SSE text into lines.\n *\n * The SSE wire format is line-oriented (`field: value` per line). Servers may\n * send `\\r\\n` (HTTP default), `\\n` (Unix), or `\\r` (legacy Mac). Matching all\n * three keeps parsing correct regardless of platform or server implementation.\n */\nexport const SSE_LINE_ENDINGS = /\\r\\n|\\r|\\n/;\n\n/**\n * Regex that matches the single optional leading space in an SSE field value.\n *\n * Per the SSE spec, `field: value` may include one space immediately after the\n * colon; that space is not part of the value. Used with `.replace()` to strip\n * it when parsing lines such as `data: hello` → `hello`.\n */\nexport const SSE_FIELD_VALUE_REGEX = /^ /;\n\n/**\n * Regex that matches a trailing newline at the end of a string.\n *\n * Multiple `data:` lines in one event are joined with `\\n`. When the event is\n * completed, this removes any stray trailing newline so callers receive the\n * payload without an extra line break at the end.\n */\nexport const SSE_TRAILING_NEWLINE_REGEX = /\\n$/;\n\n/**\n * The newline character used when normalizing SSE text internally.\n *\n * Used to join consecutive `data:` lines into one payload and to reassemble\n * buffered partial lines between streamed chunks before the next parse call.\n */\nexport const NEW_LINE = '\\n';\n","import type { SSEvent } from './types.ts';\nimport { NEW_LINE, SSE_FIELD_VALUE_REGEX, SSE_LINE_ENDINGS, SSE_TRAILING_NEWLINE_REGEX } from './constants.ts';\n\n/**\n * Optional encoders used when decoding incoming SSE bytes and re-encoding\n * any buffered remainder between chunks.\n */\nexport interface SSEEventParserOptions {\n\n /** Decodes raw stream bytes into text. Defaults to a new `TextDecoder`. */\n textDecoder: TextDecoder;\n}\n\n/**\n * Incrementally parses Server-Sent Events (SSE) from streamed byte chunks.\n *\n * SSE payloads are line-oriented: each event is a sequence of `field: value`\n * lines terminated by a blank line. This parser accepts arbitrary chunk\n * boundaries from a live HTTP response body and emits only complete events.\n *\n * Typical usage is one parser instance per connection, calling {@link parseEvents}\n * for each chunk received from the stream:\n *\n * ```ts\n * const parser = new SSEEventParser();\n *\n * for await (const chunk of response.body) {\n * for (const event of parser.parseEvents(chunk)) {\n * // handle event.data, event.event, event.id, event.retry\n * }\n * }\n * ```\n *\n * Supported fields follow the SSE spec: `data`, `event`, `id`, and `retry`.\n * Multiple `data:` lines in one event are joined with `\\n`. An event is only\n * emitted once a blank line is seen and at least one `data` field was collected.\n */\nexport class SSEEventParser {\n readonly #textDecoder: TextDecoder;\n\n /** Bytes from a partial line or incomplete event, carried over to the next chunk. */\n #messageBuffer: string = '';\n\n /**\n * Creates a parser for one SSE stream.\n *\n * Inject custom encoders in tests or when a non-default character encoding\n * is required; production callers can rely on the defaults.\n *\n * @param options - Optional text encoders for decode/encode of stream bytes.\n */\n constructor(options: Partial<SSEEventParserOptions> = {}) {\n this.#textDecoder = options.textDecoder ?? new TextDecoder();\n }\n\n /**\n * Clears any buffered bytes from a partial line or incomplete event.\n *\n * Call when abandoning a transport so the next connection does not prepend\n * stale bytes to incoming chunks.\n */\n public reset(): void {\n // Clear the message buffer\n this.#messageBuffer = '';\n\n // Reset the decoder to clear any buffered bytes\n this.#textDecoder.decode();\n }\n\n /**\n * Parses all complete SSE events contained in a newly received chunk.\n *\n * The chunk is appended to any bytes buffered from earlier calls. Complete\n * events (blank-line delimited blocks with at least one `data` field) are\n * returned immediately; any trailing partial line or in-progress event stays\n * in the internal buffer until a later chunk completes it.\n *\n * @param chunk - Newly received SSE stream bytes.\n * @returns Zero or more complete parsed SSE events from this chunk.\n */\n public parseEvents(chunk: Uint8Array): SSEvent[] {\n const lines = this.getBufferedLines(chunk);\n\n const eventLines = lines.slice(0, -1);\n\n const events: SSEvent[] = [];\n let event: Partial<SSEvent> = {};\n let processedLineCount = 0;\n\n for (const [ index, line ] of eventLines.entries()) {\n // A blank line indicates the end of an event. If we have received data, we can complete the event\n if (line === '') {\n if (event.data !== undefined) {\n events.push(this.completeEvent(event));\n event = {};\n processedLineCount = index + 1;\n }\n\n continue;\n }\n\n this.parseLine(line, event);\n }\n\n this.storeRemainingLines(lines, processedLineCount);\n\n return events;\n }\n\n /**\n * Appends a new chunk to the buffered bytes and splits the combined payload\n * into lines.\n *\n * Accepts `\\r\\n`, `\\r`, and `\\n` line endings so events parse correctly\n * regardless of server or platform conventions.\n */\n private getBufferedLines(chunk: Uint8Array): string[] {\n this.#messageBuffer += this.#textDecoder.decode(chunk, { stream: true });\n\n return this.#messageBuffer.split(SSE_LINE_ENDINGS);\n }\n\n /**\n * Parses one SSE field line into an in-progress event.\n *\n * Lines without a colon are ignored. A single optional space after the colon\n * is stripped from the field value, per the SSE spec.\n */\n private parseLine(line: string, event: Partial<SSEvent>): void {\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) return;\n\n const field = line.slice(0, colonIndex);\n const value = line.slice(colonIndex + 1).replace(SSE_FIELD_VALUE_REGEX, '');\n\n switch (field) {\n case 'data':\n event.data = event.data ? `${event.data}${NEW_LINE}${value}` : value;\n\n return;\n\n case 'event':\n event.event = value;\n\n return;\n\n case 'id':\n event.id = value;\n\n return;\n\n case 'retry':\n this.parseRetry(value, event);\n\n return;\n }\n }\n\n /**\n * Applies a numeric `retry:` field to an in-progress event.\n *\n * Non-numeric values are ignored rather than failing the parse.\n */\n private parseRetry(value: string, event: Partial<SSEvent>): void {\n const retry = parseInt(value, 10);\n\n if (!isNaN(retry)) {\n event.retry = retry;\n }\n }\n\n /**\n * Constructs a completed SSE event from accumulated fields.\n *\n * Trims a trailing newline from multi-line `data` values so callers receive\n * the payload without an extra line break at the end.\n */\n private completeEvent(event: Partial<SSEvent>): SSEvent {\n return {\n ...event,\n data: event.data?.replace(SSE_TRAILING_NEWLINE_REGEX, ''),\n } as SSEvent;\n }\n\n /**\n * Preserves incomplete trailing lines for the next received chunk.\n *\n * Only lines that were fully processed (through a completed event boundary)\n * are discarded; the remainder is re-encoded into {@link messageBuffer}.\n */\n private storeRemainingLines(lines: string[], processedLineCount: number): void {\n this.#messageBuffer = lines.slice(processedLineCount).join(NEW_LINE);\n }\n}\n","/* eslint-disable max-classes-per-file */\n\nimport type { $ZodIssue } from 'zod/v4/core';\n\n/**\n * Formats the Zod validation failures into a single string with one line each: \"- <field>: <message>\" and top level failures\n * with no field path show as \"(root)\" for better readability.\n *\n * @param issues The Zod validation failures to format.\n * @returns A human readable error string for better debugging.\n */\nexport const buildErrorDescription = (issues: $ZodIssue[]): string => {\n // Initialize an empty array to store the formatted lines.\n const lines: string[] = [];\n\n // Iterate over the issues and format them into a string.\n for (const issue of issues) {\n // Get the issue path.\n const issuePath = issue.path.length > 0 ? issue.path.join('.') : '(root)';\n\n // The prefix that Zod adds to messages.\n const messagePrefix = 'Invalid input: ';\n\n // Remove the prefix for better readability.\n const issueMessage = issue.message.startsWith(messagePrefix) ? issue.message.slice(messagePrefix.length) : issue.message;\n\n // Add the formatted line to the array.\n lines.push(`- ${issuePath}: ${issueMessage}`);\n }\n\n // Return the formatted string.\n return `\\n${lines.join('\\n')}`;\n};\n\n/**\n * Thrown when the provided template does not satisfy the XOTemplate schema.\n */\nexport class TemplateInvalidError extends Error {\n constructor(details: string) {\n const message = `Template invalid: ${details}`;\n super(message);\n this.name = 'TemplateInvalidError';\n }\n}\n\n/**\n * Thrown when a string passed to `deserializeTemplate` cannot be parsed as JSON.\n */\nexport class TemplateJsonMalformedError extends Error {\n constructor(reason: string) {\n super(`Template JSON malformed, expected a valid JSON string: ${reason}`);\n this.name = 'TemplateJsonMalformedError';\n }\n}\n\n/**\n * Thrown when `serializeTemplate` fails to produce a JSON string from the template.\n */\nexport class TemplateSerializationFailedError extends Error {\n constructor(reason: string) {\n super(`Template serialization failed: ${reason}`);\n this.name = 'TemplateSerializationFailedError';\n }\n}\n","import type { XOTemplate } from '@xo-cash/types';\nimport { extendedJsonReplacer, extendedJsonReviver } from '../extended-json.ts';\nimport { TemplateJsonMalformedError, TemplateSerializationFailedError } from './errors.ts';\n\n/**\n * Serializes an XOTemplate to a JSON string. Encodes `bigint` and `Uint8Array` fields in\n * Extended JSON format so they can be reconstructed by `deserializeTemplate`.\n *\n * @param template The template to serialize.\n * @returns A JSON string representation of the template.\n * @throws {TemplateSerializationFailedError} If the template cannot be serialized to JSON.\n */\nexport const serializeTemplate = (template: XOTemplate): string => {\n try {\n // Serialize the template to a JSON string.\n return JSON.stringify(template, extendedJsonReplacer);\n } catch (serializationError) {\n const reason = serializationError instanceof Error ? serializationError.message : 'unknown error while serializing template';\n\n throw new TemplateSerializationFailedError(reason);\n }\n};\n\n/**\n * Deserializes a JSON string back into an XOTemplate object. Restores `bigint` and\n * `Uint8Array` fields encoded in Extended JSON format by `serializeTemplate`.\n *\n * @param serializedTemplate - A JSON string of an XOTemplate object.\n * @returns The reconstructed XOTemplate object.\n * @throws {TemplateJsonMalformedError} If the serialized template is not valid JSON.\n */\nexport const deserializeTemplate = (serializedTemplate: string): XOTemplate => {\n try {\n // Parse the serialized template using the extended JSON reviver.\n return JSON.parse(serializedTemplate, extendedJsonReviver);\n } catch (parsingError) {\n const reason = parsingError instanceof Error ? parsingError.message : 'unknown error while deserializing template';\n\n throw new TemplateJsonMalformedError(reason);\n }\n};\n","import { binToHex, sha256, utf8ToBin } from '@bitauth/libauth';\nimport type { XOTemplate } from '@xo-cash/types';\nimport { serializeTemplate } from './serialization.ts';\n\n/**\n * Generates a deterministic template identifier by hashing the template.\n *\n * Note: This expects a template that has been validated by `parseTemplate`.\n *\n * @param template - The template to generate an identifier for.\n * @returns The sha256 hex identifier for the template.\n */\nexport const generateTemplateIdentifier = (template: XOTemplate): string => {\n // Serialize the template.\n const serializedTemplate = serializeTemplate(template);\n\n // Hash the serialized template.\n const hash = sha256.hash(utf8ToBin(serializedTemplate));\n\n // Convert the hash to hex and return it.\n return binToHex(hash);\n};\n","/* eslint-disable @stylistic/newline-per-chained-call */\nimport { BchVmVersions, XOTemplateBaseTypes, XOTemplatePrimitiveTypes, XOTemplateLockingTypes, XOTemplateNftCapabilities } from '@xo-cash/types';\nimport { z } from 'zod';\n\n// ============================================================\n// Enums\n// ============================================================\n\n/**\n * Validation schema for a BCH VM version identifier. Defines the set of known BCH VM versions\n * that XO templates declare support for.\n *\n * Uses `BchVmVersions` from `@xo-cash/types` so template validation stays aligned with the\n * `BchVmVersion` type.\n *\n * ```\n * {\n * \"supported\": [ \"BCH_2025_05\" ] ← each value\n * }\n * ```\n */\nexport const bchVmVersionSchema = z.enum(BchVmVersions);\n\n/**\n * Validation schema for the capability of a non-fungible token. Defines the three capability\n * types supported on BCH: minting tokens can create new NFTs, mutable tokens can update their\n * commitment, and none tokens cannot be changed after creation.\n *\n * ```\n * {\n * \"inputs|outputs\": {\n * \"[id]\": {\n * \"token\": {\n * \"nft\": {\n * \"capability\": \"minting\" ← this schema\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateNftCapabilitySchema = z.enum(XOTemplateNftCapabilities);\n\n/**\n * Validation schema for a BCH locking script type. Defines the standard locking script types\n * supported on BCH.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"lockingType\": \"p2pkh\" ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateLockingTypeSchema = z.enum(XOTemplateLockingTypes);\n\n/**\n * Validation schema for a base type identifier.\n * Accepts values from XOTemplateBaseTypes for the `type` field on constants, variables, and data.\n */\nexport const xoTemplateBaseTypeSchema = z.enum(XOTemplateBaseTypes);\n\n/**\n * Validation schema for a primitive type identifier.\n * Accepts values from XOTemplatePrimitiveTypes for the `hint` field on constants, variables, and data.\n */\nexport const xoTemplatePrimitiveTypeSchema = z.enum(XOTemplatePrimitiveTypes);\n\n// ============================================================\n// Primitives\n// ============================================================\n\n/**\n * Validation schema for byte array fields i.e. Uint8Array instance.\n */\nexport const uint8ArraySchema = z.instanceof(Uint8Array).describe('A sequence of unsigned 8-bit integers expressed as a Uint8Array.');\n\n/**\n * Validation schema for the Satoshis type i.e. bigint.\n */\nexport const satoshisSchema = z.bigint().describe('A satoshi amount expressed as a bigint.');\n\n// ============================================================\n// Shared\n// ============================================================\n\n/** Maximum character length for name fields on view properties. */\nexport const VIEW_PROPERTIES_NAME_MAX_LENGTH = 1000;\n\n/** Maximum character length for description fields on view properties. */\nexport const VIEW_PROPERTIES_DESCRIPTION_MAX_LENGTH = 5000;\n\n/** Maximum character length for icon fields on view properties. */\nexport const VIEW_PROPERTIES_ICON_MAX_LENGTH = 1000;\n\n/**\n * Validation schema for view properties shared across many template elements i.e. name, description, icon.\n * Extended by most other schemas in this file.\n */\nexport const xoTemplateViewPropertiesSchema = z\n .object({\n name: z.string().max(VIEW_PROPERTIES_NAME_MAX_LENGTH).describe('A short human-readable label for this element.'),\n description: z\n .string()\n .max(VIEW_PROPERTIES_DESCRIPTION_MAX_LENGTH)\n .describe('A human-readable explanation of what this element does and when it is relevant.'),\n icon: z.string().max(VIEW_PROPERTIES_ICON_MAX_LENGTH).optional().describe('An optional icon identifier or URL for this element.'),\n })\n .strict();\n\n// ============================================================\n// Intents\n// ============================================================\n\n/**\n * Validation schema for the base intent structure. Describes the common data parameters shared\n * by all intent types regardless of what they target.\n *\n * An optional templateIdentifier allows the intent to reference a target defined in a different\n * template, enabling cross-template interaction.\n *\n * Extended by: xoTemplateActionIntentSchema, xoTemplateOutputIntentSchema,\n * xoTemplateLockingScriptIntentSchema.\n */\nexport const xoTemplateIntentSchema = z\n .object({\n templateIdentifier: z\n .string()\n .optional()\n .describe('Optional identifier for the template used in this intent. If not provided, uses the current template.'),\n role: z.string().optional().describe('Optional identifier for the role used in this intent.'),\n generate: z.array(z.string()).optional().describe('Identifiers for items to generate when this intent is resolved, e.g. keys or secrets.'),\n variables: z.array(z.record(z.string(), z.unknown())).optional().describe('Variable values to apply when this intent is resolved.'),\n constants: z.array(z.record(z.string(), z.unknown())).optional().describe('Constant values to apply when this intent is resolved.'),\n secrets: z.array(z.record(z.string(), z.unknown())).optional().describe('Secret values to apply when this intent is resolved.'),\n })\n .strict();\n\n/**\n * Validation schema for an action intent. Extends the base intent structure with an action\n * identifier. Used in locking script action lists and in the template's start array.\n *\n * ```\n * {\n * \"start\": [\n * { \"action\": \"...\" } ← this schema\n * ],\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"actions\": [\n * { \"action\": \"...\" } ← this schema\n * ],\n * \"roles\": {\n * \"[roleId]\": {\n * \"actions\": [\n * { \"action\": \"...\" } ← this schema\n * ]\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionIntentSchema = xoTemplateIntentSchema\n .extend({\n action: z.string().describe('The identifier for the intended action.'),\n })\n .strict();\n\n/**\n * Validation schema for an output intent. Extends the base intent structure with an output\n * identifier. Used in the template's defaults block.\n *\n * ```\n * {\n * \"defaults\": {\n * \"change\": { \"output\": \"...\" } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateOutputIntentSchema = xoTemplateIntentSchema\n .extend({\n output: z.string().describe('The identifier for the intended output.'),\n })\n .strict();\n\n/**\n * Validation schema for a locking script intent. Extends the base intent structure with\n * a locking script identifier.\n *\n * @todo The location of this schema in the template JSON is not yet determined.\n */\nexport const xoTemplateLockingScriptIntentSchema = xoTemplateIntentSchema\n .extend({\n lockingScript: z.string().describe('The identifier for the intended locking script.'),\n })\n .strict();\n\n// ============================================================\n// Actions\n// ============================================================\n\n/**\n * Validation schema for the slot count configuration on a role requirement. Declares how many\n * participants of a given role are needed. min sets the lower bound and max sets the upper bound.\n * When max is absent, there is no upper limit.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"requirements\": {\n * \"participants\": [\n * { \"slots\": { \"min\": 1, \"max\": 1 } } ← this schema\n * ]\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateRoleSlotsRequirementsSchema = z\n .object({\n min: z.number().describe('Minimum number of participants required for this role.'),\n max: z.number().optional().describe('Maximum number of participants allowed for this role. Undefined means unlimited.'),\n })\n .strict();\n\n/**\n * Validation schema for the capability requirements declared on a role within an action.\n * Describes what data, secrets, or state the role is responsible for providing when participating in an action.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": {\n * \"requirements\": { \"variables\": [], \"secrets\": [] } ← this schema\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionRoleRequirementsSchema = z\n .object({\n variables: z.array(z.string()).optional().describe('List of variable identifiers required for this role.'),\n secrets: z.array(z.string()).optional().describe('List of secret identifiers required for this role.'),\n })\n .strict();\n\n/**\n * Validation schema for a role-specific definition within an action.\n * All view properties are optional.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionRoleSchema = xoTemplateViewPropertiesSchema\n .partial()\n .extend({\n generate: z\n .array(z.string())\n .optional()\n .describe('Identifiers for data items that should be generated for this role when participating in the action.'),\n\n // Describes under what conditions this role can proceed with the action. All values listed\n // under requirements must be populated for the action to work. This is a developer and\n // author concern. It is not present on intents because intents are used to populate the\n // action rather than to define it, and their fields are flattened accordingly.\n requirements: xoTemplateActionRoleRequirementsSchema.optional().describe('The requirements for this role within this action.'),\n })\n .strict();\n\n/**\n * Validation schema for a role participation requirement in an action's requirements block.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"requirements\": {\n * \"participants\": [\n * { \"role\": \"...\", \"slots\": { } } ← this schema\n * ]\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateRoleSlotSchema = z\n .object({\n role: z.string().describe('The role identifier that this requirement applies to.'),\n slots: xoTemplateRoleSlotsRequirementsSchema.describe('Slot configuration specifying how many participants of this role are required.'),\n })\n .strict();\n\n/**\n * Validation schema for the requirements of an action.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": {\n * \"requirements\": { \"variables\": [], \"participants\": [], \"secrets\": [] } ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateActionRequirementsSchema = z\n .object({\n variables: z.array(z.string()).optional().describe('List of variable identifiers required for this action.'),\n participants: z.array(xoTemplateRoleSlotSchema).optional().describe('The participants required for this action.'),\n secrets: z.array(z.string()).optional().describe('The secrets required for this action.'),\n })\n .strict();\n\n/**\n * Validation schema for an action definition.\n *\n * ```\n * {\n * \"actions\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateActionSchema = xoTemplateViewPropertiesSchema\n .extend({\n roles: z.record(z.string(), xoTemplateActionRoleSchema).optional().describe('Specific context for each role participating in this action.'),\n requirements: xoTemplateActionRequirementsSchema.optional().describe('The requirements for this action.'),\n\n // This is a list of conditions that can influence how the action behaves.\n // This needs more work to be done.\n conditions: z.array(z.string()).optional().describe('Conditions that must be met for this action to be available.'),\n\n // A single transaction produced by the action.\n // In future this might be moved to a results block that can have multiple transactions.\n transaction: z\n .string()\n .optional()\n .describe(\"The identifier of the transaction this action produces, referencing an entry in the template's transactions.\"),\n\n // The data that is produced by the action.\n // In future this might be moved to a results block that can have multiple data fields.\n data: z.string().optional().describe(\"The identifier of the data field this action produces, referencing an entry in the template's data.\"),\n })\n .strict();\n\n// ============================================================\n// Tokens & Amounts\n// ============================================================\n\n/**\n * Validation schema for the non-fungible token configuration within a token field.\n *\n * ```\n * {\n * \"inputs|outputs\": {\n * \"[id]\": {\n * \"token\": {\n * \"nft\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateNonFungibleTokenDetailsSchema = z\n .object({\n capability: z\n .union([ xoTemplateNftCapabilitySchema, z.string() ])\n .optional()\n .describe('The capability of the NFT. May be a known capability value or a CashASM expression resolving to a capability.'),\n commitment: z.string().optional().describe('The commitment data for the NFT, as a string or CashASM expression resolving to a commitment.'),\n })\n .strict();\n\n/**\n * Validation schema for the token configuration on inputs and outputs.\n *\n * ```\n * {\n * \"inputs|outputs\": {\n * \"[id]\": {\n * \"token\": { } ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTokenSchema = z\n .object({\n category: z.string().optional().describe('The category of the token, as a string or CashASM expression resolving to a category.'),\n amount: z\n .union([ z.bigint(), z.string(), z.null() ])\n .optional()\n .describe('The amount of fungible tokens as a bigint, a CashASM expression resolving to a bigint, or null indicating no FT is present.'),\n nft: xoTemplateNonFungibleTokenDetailsSchema\n .nullable()\n .optional()\n .describe('Non-fungible token configuration. Null indicates no NFT is present.'),\n })\n .strict();\n\n/**\n * Validation schema for the asset amounts configuration. Used by omitChangeAmounts on inputs\n * and by balance on locking scripts, outputs, and their roles.\n */\nexport const xoTemplateAssetAmountsSchema = z\n .object({\n\n /**\n * The satoshi amount.\n * - `Satoshis`: A specific bigint amount.\n * - `string`: A CashASM expression that resolves to the amount.\n * - `true`: all, i.e. the entire amount\n */\n satoshis: z\n .union([ satoshisSchema, z.string(), z.literal(true) ])\n .optional()\n .describe('The satoshi amount. Accepts a bigint for a specific value, a CashASM expression, or true for the entire amount.'),\n\n /**\n * The fungible token amount.\n * - `FungibleTokenAmount`: A specific bigint amount.\n * - `string`: A CashASM expression that resolves to the amount.\n * - `true`: all, i.e. the entire amount\n */\n fungibleTokens: z\n .union([ z.bigint(), z.string(), z.literal(true) ])\n .optional()\n .describe('The fungible token amount. Accepts a bigint for a specific value, a CashASM expression, or true for the entire amount.'),\n\n /**\n * Whether a non-fungible token is present (0 for absent, 1 for present),\n * or a CashASM expression that evaluates to 0 or 1.\n * - `true`: resolves to 1 if an NFT is present, or 0 if none is present. Use this when\n * the NFT is optional, to express that the NFT is estimated to be part of the balance\n * if present, or absent from it if not.\n * - `0`: None, i.e. nothing is expected to be included\n * - `1`: present and complete, as value > 1 does not make sense for non-fungible tokens\n * - `string`: A CashASM expression that evaluates to 0 or 1.\n */\n nonfungibleTokens: z\n .union([ z.literal(0), z.literal(1), z.string(), z.literal(true) ])\n .optional()\n .describe('Whether an NFT is present: 0 for absent, 1 for present, a CashASM expression evaluating to 0 or 1, or true to estimate the NFT as part of the balance if present, or absent from it if not.'),\n })\n .strict();\n\n// ============================================================\n// Locking Scripts\n// ============================================================\n\n/**\n * Validation schema for the state configuration shared by a locking script and its individual roles.\n * Declares which variables and secrets are tracked in the on-chain state for a given participant.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"state\": { \"variables\": [], \"secrets\": [] } ← this schema\n * \"roles\": {\n * \"[roleId]\": {\n * \"state\": { \"variables\": [], \"secrets\": [] } ← this schema\n * }\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateStateSchema = z\n .object({\n variables: z.array(z.string()).optional().describe('List of variable identifiers to track in state.'),\n secrets: z.array(z.string()).optional().describe('List of secret identifiers to track in state.'),\n })\n .strict();\n\n/**\n * Validation schema for a role definition for a locking script.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateLockingScriptRoleSchema = xoTemplateViewPropertiesSchema\n .partial()\n .extend({\n state: xoTemplateStateSchema.optional().describe('List of items to track as state for this role.'),\n actions: z.array(xoTemplateActionIntentSchema).optional().describe('List of action references available to this role.'),\n balance: xoTemplateAssetAmountsSchema.partial().optional().describe('Estimated ownership in the optional set of asset amounts specified.'),\n selectable: z.boolean().optional().describe('Whether outputs locked to this script should be available for coin selection.'),\n privacy: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('Privacy level for outputs locked to this script. A numeric level or a CashASM expression that evaluates to a privacy level.'),\n })\n .strict();\n\n/**\n * Validation schema for a locking script definition.\n *\n * ```\n * {\n * \"lockingScripts\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateLockingScriptSchema = xoTemplateViewPropertiesSchema\n .extend({\n lockingType: xoTemplateLockingTypeSchema.optional().describe('The type of locking mechanism. Defaults to p2s if not specified.'),\n lockingBytecode: z.string().describe('The locking script bytecode.'),\n unlockingBytecode: z.string().optional().describe('Optional default unlocking bytecode when used in automatic coin selection.'),\n actions: z.array(xoTemplateActionIntentSchema).optional().describe('The actions available for this locking script.'),\n state: xoTemplateStateSchema.optional().describe('List of items to track as state for all participants.'),\n balance: xoTemplateAssetAmountsSchema.partial().optional().describe('Estimated ownership in the optional set of asset amounts specified.'),\n selectable: z.boolean().optional().describe('Whether outputs locked to this script should be available for coin selection.'),\n // Might be levels or tags\n privacy: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('Privacy level for outputs locked to this script. A numeric level or a CashASM expression that evaluates to a privacy level.'),\n roles: z\n .record(z.string(), xoTemplateLockingScriptRoleSchema)\n .optional()\n .describe('Specific context for each role participating in this locking script.'),\n })\n .strict();\n\n// ============================================================\n// Inputs\n// ============================================================\n\n/**\n * Validation schema for an input definition in the template. Extends view properties with optional\n * satoshi value, token configuration, and other transaction level fields.\n *\n * ```\n * {\n * \"inputs\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateInputSchema = xoTemplateViewPropertiesSchema\n .extend({\n valueSatoshis: z\n .union([ satoshisSchema, z.string() ])\n .optional()\n .describe('The amount of satoshis for this input as a bigint or a CashASM expression resolving to the amount.'),\n token: xoTemplateTokenSchema.nullable().optional().describe('Token configuration for this input.'),\n sequenceNumber: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('The sequence number of this input as a specific number or a CashASM expression.'),\n unlockingScript: z.string().optional().describe('Identifier of the unlocking script to use for the UTXO provided for this input.'),\n omitChangeAmounts: xoTemplateAssetAmountsSchema\n .optional()\n .describe('Amount of change that should be omitted from the automatic change handling. WARNING: Setting this can result in loss of funds!'),\n })\n .strict();\n\n// ============================================================\n// Outputs\n// ============================================================\n\n/**\n * Validation schema for an output definition. Extends the locking script schema so that\n * every output inherits the same locking script fields and adds output-specific fields.\n *\n * ```\n * {\n * \"outputs\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateOutputSchema = xoTemplateLockingScriptSchema\n .omit({ lockingType: true, lockingBytecode: true, unlockingBytecode: true })\n .extend({\n lockingScript: z.string().describe('Identifier of the locking script to use for this output.'),\n valueSatoshis: z\n .union([ satoshisSchema, z.string() ])\n .optional()\n .describe('The amount of satoshis for this output as a bigint or a CashASM expression resolving to the amount.'),\n token: xoTemplateTokenSchema.nullable().optional().describe('Token configuration for this output.'),\n })\n .strict();\n\n// ============================================================\n// Transactions\n// ============================================================\n\n/**\n * Validation schema for a transaction input reference for a transaction definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": {\n * \"inputs\": [\n * { \"input\": \"...\" } ← this schema\n * ]\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionInputSchema = z\n .object({\n input: z.string().describe('The input definition identifier.'),\n inputIndex: z.number().optional().describe('Optional index of this input in the transaction.'),\n })\n .strict();\n\n/**\n * Validation schema for a transaction output reference for a transaction definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": {\n * \"outputs\": [\n * { \"output\": \"...\" } ← this schema\n * ]\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionOutputSchema = z\n .object({\n output: z.string().describe('The output definition identifier.'),\n outputIndex: z.number().optional().describe('Optional index of this output in the transaction.'),\n })\n .strict();\n\n/**\n * Validation schema for role-specific data for a transaction definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": {\n * \"roles\": {\n * \"[roleId]\": { } ← this schema\n * }\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionRoleDataSchema = xoTemplateViewPropertiesSchema\n .partial()\n .extend({\n inputs: z.array(xoTemplateTransactionInputSchema).optional().describe('The inputs required for this role.'),\n outputs: z.array(xoTemplateTransactionOutputSchema).optional().describe('The outputs required for this role.'),\n })\n .strict();\n\n/**\n * Validation schema for a transaction template definition.\n *\n * ```\n * {\n * \"transactions\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateTransactionSchema = xoTemplateViewPropertiesSchema\n .extend({\n version: z.number().optional().describe('The version of the transaction.'),\n locktime: z\n .union([ z.number(), z.string() ])\n .optional()\n .describe('The locktime for this transaction as a specific number or a CashASM expression.'),\n inputs: z.array(xoTemplateTransactionInputSchema).describe('The inputs for this transaction.'),\n outputs: z.array(xoTemplateTransactionOutputSchema).describe('The outputs for this transaction.'),\n roles: z\n .record(z.string(), xoTemplateTransactionRoleDataSchema)\n .optional()\n .describe('Specific context for each role participating in this transaction.'),\n composable: z.boolean().optional().describe('Whether this transaction can be composed with other transactions.'),\n })\n .strict();\n\n// ============================================================\n// Template Data\n// ============================================================\n\n/**\n * Validation schema for a constant value definition.\n *\n * ```\n * {\n * \"constants\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateConstantSchema = xoTemplateViewPropertiesSchema\n .extend({\n type: xoTemplateBaseTypeSchema.describe('The data type of this constant.'),\n value: z.unknown().describe('The value of this constant.'),\n hint: xoTemplatePrimitiveTypeSchema.optional().describe('An optional hint to help apps and users understand what this constant represents.'),\n })\n .strict();\n\n/**\n * Validation schema for a data field definition.\n *\n * ```\n * {\n * \"data\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateDataSchema = z\n .object({\n type: xoTemplateBaseTypeSchema.describe('The data type of this data field.'),\n value: z.unknown().describe('The value for this data field.'),\n hint: xoTemplatePrimitiveTypeSchema.optional().describe('An optional hint to help apps and users understand this data field.'),\n })\n .strict();\n\n/**\n * Validation schema for an import default value intent. Extends the base intent with optional\n * view properties that the engine evaluates at runtime to produce human-readable output.\n *\n * ```\n * {\n * \"variables\": {\n * \"[id]\": {\n * \"importDefaultValue\": { } ← this schema\n * }\n * }\n * }\n * ```\n */\nexport const xoTemplateImportDefaultValueSchema = xoTemplateIntentSchema\n // .shape unwraps the ZodObject to the raw field map { name, description, icon } with each field made optional\n .extend(xoTemplateViewPropertiesSchema.partial().shape)\n .strict();\n\n/**\n * Validation schema for a variable definition.\n *\n * ```\n * {\n * \"variables\": {\n * \"[id]\": { } ← this schema\n * }\n * }\n * ```\n */\nexport const xoTemplateVariableSchema = xoTemplateViewPropertiesSchema\n .extend({\n type: xoTemplateBaseTypeSchema.optional().describe('The data type of this variable.'),\n hint: xoTemplatePrimitiveTypeSchema.optional().describe('A hint to help users understand what value to provide.'),\n\n // A neutral intent that the engine uses to populate the default value for this variable.\n // View properties (name, description, icon) may contain CashASM expressions that the\n // engine evaluates at runtime to produce human-readable output. The engine overrides\n // whatever values are set here when resolving the variable for a participant.\n importDefaultValue: xoTemplateImportDefaultValueSchema\n .optional()\n .describe('A neutral intent that the engine uses to populate the default value for this variable.'),\n })\n .strict();\n\n// ============================================================\n// Template Resources\n// ============================================================\n\n/**\n * Validation schema for a resource reference attached to a template element. Extends view\n * properties with a URL pointing to external documentation or tooling.\n *\n * ```\n * {\n * \"resources\": [\n * { \"name\": \"...\", \"description\": \"...\", \"url\": \"...\" } ← this schema\n * ]\n * }\n * ```\n */\nexport const xoTemplateResourceSchema = xoTemplateViewPropertiesSchema\n .extend({\n url: z.string().describe('The URL for this resource.'),\n })\n .strict();\n\n/**\n * Validation schema for an icon reference.\n *\n * ```\n * {\n * \"icons\": [\n * { \"name\": \"...\", \"hash\": \"...\" } ← this schema\n * ]\n * }\n * ```\n */\nexport const xoTemplateIconSchema = xoTemplateViewPropertiesSchema\n .pick({ name: true })\n .extend({\n hash: z.string().describe('The identifier of the icon.'),\n })\n .strict();\n\n// ============================================================\n// Defaults\n// ============================================================\n\n/**\n * Validation schema for the defaults block of a template.\n *\n * ```\n * {\n * \"defaults\": { } ← this schema\n * }\n * ```\n */\nexport const xoTemplateDefaultsSchema = z\n .object({\n change: xoTemplateOutputIntentSchema.optional().describe('Instructions for how to construct automated change output.'),\n })\n .strict();\n\n// ============================================================\n// Template\n// ============================================================\n\n/**\n * Validation schema for the full XOTemplate type.\n */\nexport const xoTemplateSchema = xoTemplateViewPropertiesSchema\n .extend({\n $schema: z\n .string()\n .describe('The URI that identifies the JSON Schema used by this template. This enables documentation, autocompletion, and validation in JSON documents.'),\n version: z.string().optional().describe('A string identifying the version of this template.'),\n supported: z.array(bchVmVersionSchema).min(1).describe('The BCH VM versions that this template supports. At least one version is required.'),\n defaults: xoTemplateDefaultsSchema.optional().describe('Optional default settings used in this template.'),\n roles: z.record(z.string(), xoTemplateViewPropertiesSchema).describe('The roles defined in this template.'),\n start: z.array(xoTemplateActionIntentSchema).describe('A list of entry points defining which actions are available at the start.'),\n actions: z.record(z.string(), xoTemplateActionSchema).describe('The actions defined in this template.'),\n data: z.record(z.string(), xoTemplateDataSchema).optional().describe('The data fields defined in this template.'),\n transactions: z.record(z.string(), xoTemplateTransactionSchema).optional().describe('The transaction templates defined in this template.'),\n inputs: z.record(z.string(), xoTemplateInputSchema).describe('The inputs defined in this template.'),\n outputs: z.record(z.string(), xoTemplateOutputSchema).describe('The outputs defined in this template.'),\n lockingScripts: z.record(z.string(), xoTemplateLockingScriptSchema).describe('The locking script templates defined in this template.'),\n scripts: z\n .record(z.string(), z.string())\n .describe('Scripts used in this template. Keys are script identifiers, values are bytecode or CashASM expressions.'),\n constants: z.record(z.string(), xoTemplateConstantSchema).optional().describe('The constants defined in this template.'),\n variables: z\n .record(z.string(), xoTemplateVariableSchema)\n .optional()\n .describe(\"The variables that must be provided for use in the template's scripts.\"),\n resources: z.array(xoTemplateResourceSchema).optional().describe('Resource references providing external documentation or tooling links.'),\n icons: z.array(xoTemplateIconSchema).optional().describe('The icons available for use throughout the template.'),\n scenarios: z.unknown().optional().describe('The scenarios defined in this template.'),\n })\n .strict();\n","import type { XOTemplate } from '@xo-cash/types';\nimport { xoTemplateSchema } from './schemas.ts';\nimport { TemplateInvalidError, buildErrorDescription } from './errors.ts';\nimport { deserializeTemplate, serializeTemplate } from './serialization.ts';\n\n/**\n * Accepts a template value and returns a validated XOTemplate object. The input may be\n * either an Extended JSON string or a pre-parsed object. Both are validated\n * against the XOTemplate schema.\n *\n * @param inputTemplate - The value to validate. May be an Extended JSON string or a pre-parsed object.\n * @returns The validated template object\n * @throws {TemplateSerializationFailedError} If a pre-parsed object input cannot be serialized to JSON for normalization.\n * @throws {TemplateJsonMalformedError} If the string input is not valid JSON.\n * @throws {TemplateInvalidError} If the value does not conform to the XOTemplate schema.\n */\nexport const parseTemplate = (inputTemplate: string | XOTemplate): XOTemplate => {\n // Regardless of whether the inputTemplate is a string, an imported template or an in-memory object, serialize and then\n // deserialize it to ensure the output shape is consistent. For example, optional fields explicitly set to 'undefined' would be passed through\n // and then dropped on the string path, resulting in structurally different results for the same template.\n const serializedTemplate = typeof inputTemplate === 'string' ? inputTemplate : serializeTemplate(inputTemplate);\n const templateObject = deserializeTemplate(serializedTemplate);\n\n // Validate the template against the schema.\n const parseResult = xoTemplateSchema.safeParse(templateObject);\n\n if (parseResult.success) {\n // Return the validated template object\n return parseResult.data as XOTemplate;\n }\n\n // Build a human-readable description of every validation failure\n const errorDescription = buildErrorDescription(parseResult.error.issues);\n\n // Throw a typed error with the description\n throw new TemplateInvalidError(errorDescription);\n};\n","/* eslint-disable max-classes-per-file */\n\n/**\n * Error thrown when a required variable is missing.\n */\nexport class CashAssemblyRequiredVariableMissingError extends Error {\n constructor(variableNames?: string[]) {\n const defaultMessage = 'Missing required variable';\n if (variableNames !== undefined && variableNames.length > 0) {\n super(`${defaultMessage}: variableNames [${variableNames.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when cash assembly compilation fails.\n */\nexport class CashAssemblyCompilationFailedError extends Error {\n constructor(message?: string) {\n const defaultMessage = 'Cash assembly compilation failed';\n super(message ? `${defaultMessage}: ${message}` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a variable's runtime type does not match the type required for compilation.\n */\nexport class CashAssemblyVariableTypeMismatchError extends Error {\n constructor(variableKey: string, expectedType: string, actualType: string) {\n const defaultMessage = 'Variable type mismatch';\n super(`${defaultMessage}: variableKey \"${variableKey}\", expected ${expectedType}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when a supported primitive hint does not expose the requested method.\n */\nexport class CashAssemblyPrimitiveMethodMissingError extends Error {\n constructor(identifier: string, methodName: string, hint: string) {\n const defaultMessage = 'CashAssembly primitive method does not exist';\n super(`${defaultMessage}: identifier \"${identifier}\", methodName \"${methodName}\", hint \"${hint}\"`);\n }\n}\n\n/**\n * Error thrown when a value cannot be resolved as bytes.\n */\nexport class CashAssemblyUnsupportedValueTypeError extends Error {\n constructor(identifier: string, returnedType: string) {\n const defaultMessage = 'CashAssembly value type is unsupported for byte resolution';\n super(`${defaultMessage}: identifier \"${identifier}\", returnedType \"${returnedType}\"`);\n }\n}\n\n/**\n * Error thrown when a number cannot be safely encoded as a CashAssembly VM number.\n */\nexport class CashAssemblyNumberNotSafeIntegerError extends Error {\n constructor(identifier: string, value: number) {\n const defaultMessage = 'CashAssembly number is not a safe integer';\n super(`${defaultMessage}: identifier \"${identifier}\", got ${String(value)}`);\n }\n}\n\n/**\n * Error thrown when a supported primitive is selected but its value is missing when provided in the variables map.\n */\nexport class CashAssemblyPrimitiveVariableMissingError extends Error {\n constructor(identifier: string, variableName: string) {\n const defaultMessage = 'CashAssembly primitive variable is missing from the variables map';\n super(`${defaultMessage}: identifier \"${identifier}\", variableName \"${variableName}\"`);\n }\n}\n\n/**\n * Error thrown when compiled evaluation bytes cannot be decoded as a VM number.\n */\nexport class CashAssemblyVmNumberDecodeError extends Error {\n constructor(reason: string) {\n const defaultMessage = 'CashAssembly evaluation could not be decoded as a VM number';\n super(`${defaultMessage}: ${reason}`);\n }\n}\n","/**\n * Detects whether a string is a pure CashAssembly expression.\n *\n * CashAssembly expressions look like `$(<variable>)` or `$(<a> <b>)`. This pattern checks\n * that the entire string is one such expression and nothing else. It will not match if\n * there is other text surrounding the expression.\n *\n * For example:\n * `$(<fee>)` matches (a full expression)\n * `OP_DUP $(<fee>)` does not match (extra text before it)\n * `$()` does not match (empty expression)\n */\nexport const CASHASSEMBLY_EXPRESSION_PATTERN = /^\\$\\([^)]+\\)$/;\n\n/**\n * Finds all CashAssembly evaluations embedded in a larger string.\n *\n * An evaluation looks like `$(...)`, for example `$(<fee>)` or `$(<a> <b>)`. This pattern\n * locates every occurrence in the input and returns them all (global flag `g`).\n * Empty evaluations `$()` are intentionally excluded because they reference no variables.\n *\n * For example, scanning `\"OP_DUP <$(<pubkeyHash>)> OP_HASH160 $(<fee>)\"` would return\n * `['$(<pubkeyHash>)', '$(<fee>)']`.\n */\nexport const CASHASSEMBLY_EVALUATION_PATTERN = /\\$\\([^)]+\\)/g;\n\n/**\n * Extracts variable names from angle-bracket references inside a CashAssembly evaluation.\n *\n * Inside an evaluation like `$(<pubkeyHash> <fee>)`, variables are referenced as `<name>`.\n * This pattern captures the name between the brackets. The global flag `g` allows iterating\n * over every variable reference in a single evaluation string.\n *\n * For example, running this against `$(<pubkeyHash> <fee>)` would return the variable names\n * `[\"pubkeyHash\", \"fee\"]`.\n */\nexport const CASHASSEMBLY_VARIABLE_PATTERN = /<([^>]+)>/g;\n\n/**\n * Identifies CashAssembly literal tokens that appear inside angle-bracket push statements.\n *\n * Inside an evaluation, not everything between `<` and `>` is a variable name. Literals are\n * also valid push contents: numeric literals (e.g. `<0>`, `<32>`), hex literals (`<0x02>`),\n * binary literals (`<0b1010>`), and string literals (`<\"minting\">`, `<'hello'>`). This pattern\n * matches any captured token that starts with a digit or a quote character.\n */\nexport const CASHASSEMBLY_LITERAL_TOKEN_PATTERN = /^[0-9\"']/;\n\n/**\n * Matches a single dot variable method reference inside an angle-bracket identifier.\n *\n * Used to detect primitive method references such as `expiry.toIso8601`.\n *\n * For example:\n * `expiry.toIso8601` matches (base `expiry`, method `toIso8601`)\n * `requestedSatoshis` does not match (no method)\n * `key.schnorr_signature.all_outputs` does not match (more than one dot)\n * `key.public_key` matches the pattern shape but it is only resolved\n * when `hint` maps to a primitive\n */\nexport const CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN = /^([^.]+)\\.([^.]+)$/;\n","import { bigIntToVmNumber, utf8ToBin } from '@bitauth/libauth';\nimport { CashAssemblyNumberNotSafeIntegerError, CashAssemblyUnsupportedValueTypeError } from './errors.ts';\n\n/**\n * Converts a value into bytes representation.\n *\n * @param {unknown} value - Value to encode, should be one of: Uint8Array, bigint, boolean, string, or a safe integer number.\n * @param {string} valueIdentifier - Identifier used in error messages.\n * @returns {Uint8Array} Bytes representation of the value.\n * @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number is not a safe integer.\n * @throws {@link CashAssemblyUnsupportedValueTypeError} When the value type cannot be resolved.\n */\nexport const convertValueToBytes = (value: unknown, valueIdentifier: string): Uint8Array => {\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (typeof value === 'bigint') {\n return bigIntToVmNumber(value);\n }\n\n if (typeof value === 'boolean') {\n // The BCH VM treats an empty byte array as false and any nonempty byte array as true.\n return new Uint8Array(value ? [ 1 ] : []);\n }\n\n if (typeof value === 'string') {\n return utf8ToBin(value);\n }\n\n if (typeof value === 'number') {\n if (Number.isSafeInteger(value) === true) {\n return bigIntToVmNumber(BigInt(value));\n }\n\n throw new CashAssemblyNumberNotSafeIntegerError(valueIdentifier, value);\n }\n\n throw new CashAssemblyUnsupportedValueTypeError(valueIdentifier, typeof value);\n};\n","import {\n FungibleTokenAmount,\n NFTCommitment,\n PublicKey,\n Satoshis,\n SchnorrSignature,\n TemplateIdentifier,\n Timestamp,\n TokenCategory,\n TransactionHash,\n} from '@xo-cash/primitives';\nimport { XOTemplatePrimitiveTypes } from '@xo-cash/types';\nimport type { XOTemplate, XOTemplatePrimitiveType } from '@xo-cash/types';\nimport { CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError } from './errors.ts';\nimport { CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN } from './defaults.ts';\nimport { convertValueToBytes } from './bytes.ts';\n\n/**\n * Template hint values mapped to a primitive class for resolving primitive method evaluations.\n * Keys are values from XOTemplatePrimitiveTypes.\n */\nconst PRIMITIVE_BY_TEMPLATE_HINT = {\n [XOTemplatePrimitiveTypes.FUNGIBLE_TOKEN_AMOUNT]: FungibleTokenAmount,\n [XOTemplatePrimitiveTypes.NFT_COMMITMENT]: NFTCommitment,\n [XOTemplatePrimitiveTypes.PUBLIC_KEY]: PublicKey,\n [XOTemplatePrimitiveTypes.SATOSHIS]: Satoshis,\n [XOTemplatePrimitiveTypes.SCHNORR_SIGNATURE]: SchnorrSignature,\n [XOTemplatePrimitiveTypes.TEMPLATE_IDENTIFIER]: TemplateIdentifier,\n [XOTemplatePrimitiveTypes.TIMESTAMP]: Timestamp,\n [XOTemplatePrimitiveTypes.TOKEN_CATEGORY]: TokenCategory,\n [XOTemplatePrimitiveTypes.TRANSACTION_HASH]: TransactionHash,\n} as const;\n\ntype SupportedPrimitiveHint = keyof typeof PRIMITIVE_BY_TEMPLATE_HINT;\n\n/**\n * Inputs needed to call a primitive method for a `name.method` push.\n */\ntype CallPrimitiveMethodParameters = {\n\n /**\n * Full push identifier from the evaluation, for example `amount.toSatoshis`.\n */\n identifier: string;\n\n /**\n * Method name to call on the constructed primitive, for example `toIso8601`.\n */\n methodName: string;\n\n /**\n * Value for the variable.\n */\n value: unknown;\n\n /**\n * Supported template hint that selects the primitive class.\n */\n hint: SupportedPrimitiveHint;\n};\n\n/**\n * Inputs needed to resolve primitive method pushes from extracted CashAssembly identifiers.\n */\nexport type ResolvePrimitiveMethodBytesParameters = {\n\n /**\n * Variable identifiers from {@link extractVariablesFromEvaluations}, for example\n * `['amount.toSatoshis', 'fee.toSatoshis']`.\n */\n identifiers: string[];\n\n /**\n * Variable names and values object.\n */\n variables: Record<string, unknown>;\n\n /**\n * Template variable definitions. When omitted, no primitive methods are resolved.\n * The `hint` on each entry selects the primitive class.\n */\n templateVariables?: XOTemplate['variables'];\n};\n\n/**\n * Returns true when `hint` maps to a supported primitive class in `PRIMITIVE_BY_TEMPLATE_HINT`.\n *\n * @param {XOTemplatePrimitiveType | undefined} hint - Template variable hint.\n * @returns {boolean} True when the hint selects a supported primitive class.\n */\nconst isSupportedPrimitiveHint = (hint: XOTemplatePrimitiveType | undefined): hint is SupportedPrimitiveHint => {\n return hint !== undefined && Object.hasOwn(PRIMITIVE_BY_TEMPLATE_HINT, hint) === true;\n};\n\n/**\n * Returns true when `methodName` is an own function on the primitive class for `hint`.\n *\n * @param {SupportedPrimitiveHint} hint - Supported template hint.\n * @param {string} methodName - Method name from the evaluation text, for example `toSatoshis`.\n * @returns {boolean} True when that class exposes the named method.\n */\nconst canResolvePrimitiveMethod = (hint: SupportedPrimitiveHint, methodName: string): boolean => {\n const PrimitiveClass = PRIMITIVE_BY_TEMPLATE_HINT[hint];\n\n // Check own properties only so inherited Object.prototype names are rejected without needing a value.\n if (Object.hasOwn(PrimitiveClass.prototype, methodName) === false) {\n return false;\n }\n\n return typeof Reflect.get(PrimitiveClass.prototype, methodName) === 'function';\n};\n\n/**\n * Constructs a primitive from a raw value and calls one instance method on it.\n *\n * Call only after `canResolvePrimitiveMethod` is true for the same hint and method.\n *\n * @param {CallPrimitiveMethodParameters} parameters - Identifier, method, value, and supported hint.\n * @returns {unknown} Method return value, later encoded as CashAssembly push bytes.\n * @throws {@link CashAssemblyPrimitiveMethodMissingError} When the prototype member is not a function.\n * @throws When the primitive constructor rejects the raw value (validation errors from `@xo-cash/primitives`).\n */\nconst callPrimitiveMethod = (parameters: CallPrimitiveMethodParameters): unknown => {\n const { identifier, methodName, value, hint } = parameters;\n\n const PrimitiveClass = PRIMITIVE_BY_TEMPLATE_HINT[hint];\n\n // Constructing runs each primitive's own input validation (range checks, hex length, etc).\n // `as never` satisfies TypeScript across constructors that accept different input shapes.\n const primitiveInstance = new PrimitiveClass(value as never);\n\n // Same prototype member canResolvePrimitiveMethod already verified as an own function.\n const primitiveMethod = Reflect.get(PrimitiveClass.prototype, methodName);\n\n if (typeof primitiveMethod !== 'function') {\n throw new CashAssemblyPrimitiveMethodMissingError(identifier, methodName, hint);\n }\n\n return primitiveMethod.call(primitiveInstance);\n};\n\n/**\n * Resolves supported `base.method` identifiers to CashAssembly variable bytes.\n *\n * Each single dot identifier whose `hint` maps to a supported primitive is resolved and stored under\n * the full identifier (`base.method`). Unsupported or multi dot identifiers are left for CashAssembly.\n *\n * When `templateVariables` is omitted, returns an empty map.\n *\n * @param {ResolvePrimitiveMethodBytesParameters} parameters - Identifiers, values, and optional template metadata.\n * @returns {Record<string, Uint8Array>} Resolved method identifiers mapped to bytes for CashAssembly pushes.\n * @throws {@link CashAssemblyPrimitiveMethodMissingError} When the hint is a supported primitive but the method is missing.\n * @throws {@link CashAssemblyPrimitiveVariableMissingError} When the runtime value is missing from the variables map.\n * @throws {@link CashAssemblyUnsupportedValueTypeError} When the method return type cannot be embedded.\n * @throws {@link CashAssemblyNumberNotSafeIntegerError} When a method return value is a number that is not a safe integer.\n */\nexport const resolvePrimitiveMethodBytes = (parameters: ResolvePrimitiveMethodBytesParameters): Record<string, Uint8Array> => {\n const { identifiers, templateVariables, variables } = parameters;\n\n // Without template metadata there is no hint to select a primitive class.\n if (templateVariables === undefined) {\n return {};\n }\n\n const resolvedBytes: Record<string, Uint8Array> = {};\n\n for (const identifier of identifiers) {\n // The same identifier can appear more than once. Resolve it only once.\n if (Object.hasOwn(resolvedBytes, identifier) === true) {\n continue;\n }\n\n // Find the primitive method reference in the identifier.\n const methodReferenceMatch = identifier.match(CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN);\n\n if (methodReferenceMatch === null) {\n continue;\n }\n\n const [ , baseName, methodName ] = methodReferenceMatch;\n\n // Unknown identifiers and CashAssembly native operations such as someKey.schnorr_signature.all_outputs\n // must be left for CashAssembly rather than treated as primitive failures.\n if (Object.hasOwn(templateVariables, baseName) === false) {\n continue;\n }\n\n const hint = templateVariables[baseName].hint;\n\n if (isSupportedPrimitiveHint(hint) === false) {\n continue;\n }\n\n // Supported hint with an unknown method should be thrown as an error.\n if (canResolvePrimitiveMethod(hint, methodName) === false) {\n throw new CashAssemblyPrimitiveMethodMissingError(identifier, methodName, hint);\n }\n\n // If the method is known but the runtime value is missing, throw an error.\n if (Object.hasOwn(variables, baseName) === false) {\n throw new CashAssemblyPrimitiveVariableMissingError(identifier, baseName);\n }\n\n const methodResult = callPrimitiveMethod({\n identifier,\n methodName,\n value: variables[baseName],\n hint,\n });\n\n // Store the result under identifier.\n resolvedBytes[identifier] = convertValueToBytes(methodResult, identifier);\n }\n\n return resolvedBytes;\n};\n","/**\n * Utilities for parsing, extracting, and compiling CashAssembly expressions.\n *\n * CashAssembly is the scripting language used by Bitauth templates to describe Bitcoin Cash\n * locking and unlocking scripts.\n *\n * ## Syntax (CashAssembly)\n *\n * `<expression>` is a push statement. Compiles the contents and pushes the result onto the VM stack.\n * `<someKey.public_key>` pushes the 33 byte compressed public key. `<1>` pushes the integer 1.\n *\n * `$(<expression>)` is an evaluation. Runs the inner script in the VM and inserts the top stack\n * item as VM bytecode.\n * `$(<someKey.public_key> OP_HASH160)` inserts the HASH160 of the public key.\n *\n * `<$(<expression>)>` is a push of an evaluation result. It evaluates first then pushes.\n * For a P2PKH locking script example see\n * `OP_DUP OP_HASH160 <$(<someKey.public_key> OP_HASH160)> OP_EQUALVERIFY OP_CHECKSIG`.\n *\n * `variableId.operation` is a variable with a compiler resolved operation. `someKey.public_key`\n * produces the public key bytes. `someKey.schnorr_signature.all_outputs` produces a Schnorr\n * signature.\n *\n * Opcodes (`OP_DUP`, `OP_HASH160`, and similar) are inserted as their bytecode equivalent directly.\n *\n * ## Name resolution priority (CashAssembly)\n *\n * When the compiler encounters an identifier it resolves it in this order.\n * 1. Opcode always wins. Naming a variable or script `OP_ADD` will not shadow it.\n * 2. Variable shadows scripts of the same name.\n * 3. Script is the script's bytecode.\n *\n * ## Resolution Order (CashAssembly + Primitive Method Resolution)\n *\n * Supported `<base.method>` pushes are resolved to bytes before CashAssembly compiles.\n * Inside CashAssembly the order is Opcode then Variable then Script.\n */\nimport type { CompilerBch } from '@bitauth/libauth';\nimport { binToHex, binToUtf8, createCompilerBch, vmNumberToBigInt } from '@bitauth/libauth';\nimport type { XOInvitationVariableValue, XOTemplate } from '@xo-cash/types';\nimport {\n CashAssemblyCompilationFailedError,\n CashAssemblyVariableTypeMismatchError,\n CashAssemblyRequiredVariableMissingError,\n CashAssemblyVmNumberDecodeError,\n} from './errors.ts';\nimport {\n CASHASSEMBLY_EVALUATION_PATTERN,\n CASHASSEMBLY_EXPRESSION_PATTERN,\n CASHASSEMBLY_LITERAL_TOKEN_PATTERN,\n CASHASSEMBLY_VARIABLE_PATTERN,\n} from './defaults.ts';\nimport { convertValueToBytes } from './bytes.ts';\nimport { resolvePrimitiveMethodBytes } from './primitive-evaluations.ts';\n\n/**\n * Supported decode modes for compiled CashAssembly evaluation bytes.\n */\nexport type CompiledCashAssemblyDecodeMode = 'utf8' | 'hex' | 'boolean' | 'bigint' | 'uint8array';\n\n/**\n * Parameters for compiling CashAssembly string.\n */\nexport type CompileCashAssemblyStringParameters = {\n\n /**\n * Text that may embed CashAssembly evaluations such as `$(<fee>)` or `$(<expiry.toIso8601>)`.\n */\n cashAssemblyText: string;\n\n /**\n * Used for both primitive method evaluations and normal CashAssembly compilation.\n */\n variables: Record<string, XOInvitationVariableValue | Uint8Array>;\n\n /**\n * The mode to decode compiled evaluation bytes into a string.\n */\n evaluationDecodeMode?: CompiledCashAssemblyDecodeMode;\n\n /**\n * Optional template variable definitions. When provided, each `<name.method>` push whose `hint`\n * maps to a supported primitive class is resolved to bytes before CashAssembly compilation.\n */\n templateVariables?: XOTemplate['variables'];\n};\n\n/**\n * Checks if the expression is a CashAssembly expression.\n *\n * @param {unknown} expression - The expression to check.\n * @returns {boolean} True if the expression is a CashAssembly expression, false otherwise.\n */\nexport const isCashAssemblyExpression = (expression: unknown): boolean => {\n return typeof expression === 'string' && CASHASSEMBLY_EXPRESSION_PATTERN.test(expression);\n};\n\n/**\n * Extracts all CashAssembly evaluations (i.e., substrings like $(...)) from the input text.\n *\n * @param {string} text - The input string to scan for CashAssembly evaluations.\n * @returns {string[]} An array of evaluation strings found in the input.\n *\n * @example\n * extractCashAssemblyEvaluations(\"OP_DUP <$(<foo>)> OP_HASH160 $(<bar>)\");\n * // returns ['$(<foo>)', '$(<bar>)']\n */\nexport const extractCashAssemblyEvaluations = (text: string): string[] => {\n return text.match(CASHASSEMBLY_EVALUATION_PATTERN) ?? [];\n};\n\n/**\n * Returns the segment of `identifier` before the first `.`.\n *\n * When there is no `.`, returns `identifier` unchanged.\n * Multi segment identifiers such as `foo.bar.baz` resolve to `foo`.\n *\n * @param {string} identifier - Identifier that may contain a dot.\n * @returns {string} The base name before the first `.`.\n */\nconst resolveIdentifierBaseName = (identifier: string): string => {\n const firstDotIndex = identifier.indexOf('.');\n\n if (firstDotIndex === -1) {\n return identifier;\n }\n\n return identifier.slice(0, firstDotIndex);\n};\n\n/**\n * Extracts unique variable identifiers enclosed in angle brackets from each evaluation string.\n *\n * CashAssembly literal tokens such as hex bytes, numbers, and quoted strings are excluded via\n * {@link CASHASSEMBLY_LITERAL_TOKEN_PATTERN}. For example, `<0x02>` and `<\"minting\">` are not returned.\n *\n * @param {string[]} evaluations - An array of evaluation strings from which to extract variable names.\n * @returns {string[]} An array of variable names.\n */\nexport const extractVariablesFromEvaluations = (evaluations: string[]): string[] => {\n const uniqueVariables = new Set<string>();\n\n for (const evaluation of evaluations) {\n for (const [ , extractedIdentifier ] of evaluation.matchAll(CASHASSEMBLY_VARIABLE_PATTERN)) {\n if (CASHASSEMBLY_LITERAL_TOKEN_PATTERN.test(extractedIdentifier)) {\n continue;\n }\n\n uniqueVariables.add(extractedIdentifier);\n }\n }\n\n return [ ...uniqueVariables ];\n};\n\n/**\n * Decodes compiled CashAssembly evaluation bytes into a string representation.\n *\n * 'evaluationDecodeMode' determines how the evaluation bytes are interpreted and presented.\n * Use `bigint` for numeric values like satoshis, `utf8` for text labels, `hex` for binary data\n * such as hashes, and `boolean` to represent boolean values.\n *\n * @param {Uint8Array} compiledResult - The compiled evaluation bytecode.\n * @param {CompiledCashAssemblyDecodeMode} [evaluationDecodeMode='utf8'] - The decode mode used to convert\n * bytes to text.\n * @returns {string} The decoded value as a string suitable for inline replacement.\n * @throws {@link CashAssemblyVmNumberDecodeError} When `evaluationDecodeMode` is `bigint` and the bytes are not a VM number.\n */\nexport const decodeCompiledCashAssemblyEvaluation = (\n compiledResult: Uint8Array,\n evaluationDecodeMode: CompiledCashAssemblyDecodeMode = 'utf8',\n): string => {\n // Converts the byte array to a string.\n if (evaluationDecodeMode === 'uint8array') {\n return String(compiledResult);\n }\n\n // Converts the byte array to a boolean string, converting the evaluation result into a true or a false.\n if (evaluationDecodeMode === 'boolean') {\n return compiledResult.length === 0 ? 'false' : 'true';\n }\n\n // Converts the byte array to a hex string.\n if (evaluationDecodeMode === 'hex') {\n return binToHex(compiledResult);\n }\n\n // Converts the byte array to a bigint string.\n if (evaluationDecodeMode === 'bigint') {\n const vmNumberResult = vmNumberToBigInt(compiledResult);\n\n if (typeof vmNumberResult === 'bigint') {\n return vmNumberResult.toString();\n }\n\n throw new CashAssemblyVmNumberDecodeError(vmNumberResult);\n }\n\n // Converts the byte array to a utf8 string.\n return binToUtf8(compiledResult);\n};\n\n/**\n * Generates bytecode for a specific CashAssembly evaluation using given variable values and a prepared compiler.\n *\n * @param {CompilerBch} compiler - The libauth compiler from {@link compileCashAssemblyEvaluations}.\n * @param {string} evaluation - The specific evaluation string to compile.\n * @param {Record<string, Uint8Array>} variables - A record mapping variable names to their values.\n * @returns {Uint8Array} The compiled bytecode.\n * @throws {@link CashAssemblyRequiredVariableMissingError} If a required variable is not present.\n * @throws {@link CashAssemblyVariableTypeMismatchError} If a variable value is not a Uint8Array.\n * @throws {@link CashAssemblyCompilationFailedError} If libauth compilation fails.\n */\nexport const generateCashAssemblyBytecode = (compiler: CompilerBch, evaluation: string, variables: Record<string, Uint8Array>): Uint8Array => {\n const variableNames = extractVariablesFromEvaluations([ evaluation ]);\n\n // Validate that all required variables are provided\n const missingVariables = variableNames.filter((name: string) => !Object.hasOwn(variables, name));\n if (missingVariables.length > 0) {\n throw new CashAssemblyRequiredVariableMissingError(missingVariables);\n }\n\n // Construct the bytecode object using the keys in variableNames, mapping to the values in variables\n const bytecode: Record<string, Uint8Array> = {};\n for (const variableName of variableNames) {\n const value = variables[variableName];\n\n // By the time execution reaches this point, the value should be a Uint8Array.\n if (!(value instanceof Uint8Array)) {\n throw new CashAssemblyVariableTypeMismatchError(variableName, 'Uint8Array', typeof value);\n }\n\n bytecode[variableName] = value;\n }\n\n const compiledBytecode = compiler.generateBytecode({\n data: { bytecode },\n scriptId: evaluation,\n });\n\n if (!compiledBytecode.success) {\n // Collapse libauth's full errors list into one string because\n // CashAssemblyCompilationFailedError only carries a single message.\n let compilationFailureMessage = 'unknown compilation failure';\n\n if ('errors' in compiledBytecode && compiledBytecode.errors.length > 0) {\n compilationFailureMessage = compiledBytecode.errors.map((compilationError) => compilationError.error).join('; ');\n }\n\n throw new CashAssemblyCompilationFailedError(compilationFailureMessage);\n }\n\n return compiledBytecode.bytecode;\n};\n\n/**\n * Prepares a compiler for the provided CashAssembly evaluations, setting required variables as 'WalletData'.\n *\n * @param {string[]} evaluations - Array of evaluation strings (e.g., ['$(<var1>)', '$(<var2> <var3>)']).\n * @returns {CompilerBch} A Libauth compiler instance for use with these evaluations.\n */\nexport const compileCashAssemblyEvaluations = (evaluations: string[]): CompilerBch => {\n // Create a scripts object where each key is the evaluation and the value is also the evaluation\n const scripts: Record<string, string> = {};\n for (const evaluation of evaluations) {\n scripts[evaluation] = evaluation;\n }\n\n // Get the variable names from the evaluations.\n const variableNames = extractVariablesFromEvaluations(evaluations);\n\n // Register each base name once. Dotted pushes share one WalletData entry under the base name.\n const variables: Record<string, { type: 'WalletData' }> = {};\n for (const variableName of variableNames) {\n variables[resolveIdentifierBaseName(variableName)] = { type: 'WalletData' as const };\n }\n\n // Create the libauth compiler.\n const compiler = createCompilerBch({\n scripts,\n variables,\n });\n\n return compiler;\n};\n\n/**\n * Compiles all CashAssembly evaluations in a text string and replaces each evaluation\n * with a decoded string representation.\n *\n * @param {CompileCashAssemblyStringParameters} parameters - Parameters for compiling the CashAssembly string.\n * @param {string} parameters.cashAssemblyText - The string with CashAssembly evaluations.\n * @param {Record<string, XOInvitationVariableValue | Uint8Array>} parameters.variables - Object mapping\n * variable names to values for compilation.\n * @param {CompiledCashAssemblyDecodeMode} [parameters.evaluationDecodeMode='utf8'] - The decode mode used\n * after each evaluation is compiled. See {@link decodeCompiledCashAssemblyEvaluation}.\n * @param {XOTemplate['variables']} [parameters.templateVariables] - Optional template variable definitions\n * used to resolve supported `<name.method>` pushes via each variable's `hint`.\n * @returns {string} Compiled text with all evaluations replaced by decoded string values.\n * @throws {@link CashAssemblyRequiredVariableMissingError} When a required variable is not present in the variables map.\n * @throws {@link CashAssemblyPrimitiveMethodMissingError} When a supported primitive hint has an unknown method.\n * @throws {@link CashAssemblyPrimitiveVariableMissingError} When a supported primitive method is missing its runtime value.\n * @throws {@link CashAssemblyUnsupportedValueTypeError} When a primitive method return type cannot be embedded as bytes.\n * @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number variable is not a safe integer.\n * @throws {@link CashAssemblyVmNumberDecodeError} When `evaluationDecodeMode` is `bigint` and an evaluation is not a VM number.\n */\nexport const compileCashAssemblyString = (parameters: CompileCashAssemblyStringParameters): string => {\n const { cashAssemblyText, variables, evaluationDecodeMode = 'utf8', templateVariables } = parameters;\n\n return cashAssemblyText.replace(CASHASSEMBLY_EVALUATION_PATTERN, (evaluation) => {\n // Extract variable identifiers required by the current evaluation.\n const variableNames = extractVariablesFromEvaluations([ evaluation ]);\n\n const primitiveMethodBytes = resolvePrimitiveMethodBytes({\n identifiers: variableNames,\n templateVariables,\n variables,\n });\n\n // Prefer resolved method bytes. Fall back to converting the raw variable value.\n const missingVariables = variableNames.filter((variableName) => {\n if (Object.hasOwn(primitiveMethodBytes, variableName) === true) {\n return false;\n }\n\n return Object.hasOwn(variables, variableName) === false;\n });\n\n if (missingVariables.length > 0) {\n throw new CashAssemblyRequiredVariableMissingError(missingVariables);\n }\n\n // Convert each variable to its bytes before compilation.\n const variableBytes: Record<string, Uint8Array> = {};\n for (const variableName of variableNames) {\n if (Object.hasOwn(primitiveMethodBytes, variableName) === true) {\n variableBytes[variableName] = primitiveMethodBytes[variableName];\n continue;\n }\n\n variableBytes[variableName] = convertValueToBytes(variables[variableName], variableName);\n }\n\n // Compile the evaluation in isolation.\n const compiler = compileCashAssemblyEvaluations([ evaluation ]);\n\n // Generate the bytes for the evaluation.\n const compilationResult: Uint8Array = generateCashAssemblyBytecode(compiler, evaluation, variableBytes);\n\n // Decode the bytes into a string as per the decode mode.\n return decodeCompiledCashAssemblyEvaluation(compilationResult, evaluationDecodeMode);\n });\n};\n"],"mappings":";;;;;;;;;AAKA,MAAM,+BAA+B;;;;AAKrC,MAAM,mCAAmC;;;;;;;;;;;;;;;;;;;AAoBzC,MAAa,wBAAwB,cAAsB,UAA4B;AACnF,KAAI,iBAAiB,WACjB,QAAO,gBAA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