@usagekit/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +2 -0
- package/dist/contracts.d.ts +499 -0
- package/dist/contracts.js +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/money.d.ts +8 -0
- package/dist/money.js +17 -0
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +7 -0
- package/dist/quantity.d.ts +4 -0
- package/dist/quantity.js +19 -0
- package/dist/windows.d.ts +7 -0
- package/dist/windows.js +24 -0
- package/dist/wire.d.ts +4 -0
- package/dist/wire.js +28 -0
- package/package.json +30 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
export type ValidationFailure = {
|
|
2
|
+
outcome: "invalid";
|
|
3
|
+
field: string;
|
|
4
|
+
reason: string;
|
|
5
|
+
};
|
|
6
|
+
/** Exact USD units: 1 unit = 1/10000 cent. */
|
|
7
|
+
export type Money = {
|
|
8
|
+
units: bigint;
|
|
9
|
+
currency: "USD";
|
|
10
|
+
};
|
|
11
|
+
/** Amount = value * 10^-scale. Scale is a nonnegative integer. */
|
|
12
|
+
export type Quantity = {
|
|
13
|
+
value: bigint;
|
|
14
|
+
scale: number;
|
|
15
|
+
unit: string;
|
|
16
|
+
};
|
|
17
|
+
export type AccessCredential = {
|
|
18
|
+
/** Host-defined kind, for example "api_key" | "personal_token" | "oauth_client" | "session". */
|
|
19
|
+
kind: string;
|
|
20
|
+
/** Stable identifier of that credential in the host. Never the secret. */
|
|
21
|
+
id: string;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Two separate identities: accessCredential authenticates the caller to the host and
|
|
25
|
+
* remains stable across provider rotation. providerCredentialVersion identifies the
|
|
26
|
+
* provider connection's secret version at dispatch, never the caller.
|
|
27
|
+
*/
|
|
28
|
+
export type Scope = {
|
|
29
|
+
namespace: string;
|
|
30
|
+
/** Budget owner: user, team, or the platform's own principal. */
|
|
31
|
+
principal: string;
|
|
32
|
+
/** Initiating identity when it differs from the owner: a member, a guest session, a worker. */
|
|
33
|
+
actor?: string;
|
|
34
|
+
group?: string;
|
|
35
|
+
connection: string;
|
|
36
|
+
/** Who called the host application. Used for per-token budgets and attribution. */
|
|
37
|
+
accessCredential?: AccessCredential;
|
|
38
|
+
/** Which provider secret version was used. Rotation identity, not caller identity. */
|
|
39
|
+
providerCredentialVersion?: string;
|
|
40
|
+
};
|
|
41
|
+
export type FundingSource = "byok" | "platform";
|
|
42
|
+
export type Surface = "app" | "programmatic";
|
|
43
|
+
export type Source = "app" | "worker" | "api" | "sdk" | "cli" | "mcp" | "proxy";
|
|
44
|
+
/** Timestamps are UTC ISO strings. Resolved reservation epochs remain immutable. */
|
|
45
|
+
export type BudgetWindow = {
|
|
46
|
+
kind: "calendar_month";
|
|
47
|
+
timezone: "UTC";
|
|
48
|
+
} | {
|
|
49
|
+
kind: "provider_cycle";
|
|
50
|
+
cycleId: string;
|
|
51
|
+
startsAt: string;
|
|
52
|
+
endsAt: string;
|
|
53
|
+
} | {
|
|
54
|
+
kind: "rolling";
|
|
55
|
+
days: number;
|
|
56
|
+
} | {
|
|
57
|
+
kind: "since_reset";
|
|
58
|
+
epoch: string;
|
|
59
|
+
startsAt: string;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Each variant names one constraint in a namespace.
|
|
63
|
+
* A platform_pool bounds spend shared by many principals and applies to operations
|
|
64
|
+
* naming that pool in ReserveInput. It is not the platform principal's own budget.
|
|
65
|
+
* A wallet is not a budget: the host ledger owns balances, holds and charges,
|
|
66
|
+
* coordinated through the host credit bridge. A wallet-level monthly cap may still
|
|
67
|
+
* be a principal Budget because the cap is a constraint, not a balance.
|
|
68
|
+
*/
|
|
69
|
+
export type BudgetScope = {
|
|
70
|
+
kind: "principal";
|
|
71
|
+
namespace: string;
|
|
72
|
+
principal: string;
|
|
73
|
+
} | {
|
|
74
|
+
kind: "group";
|
|
75
|
+
namespace: string;
|
|
76
|
+
group: string;
|
|
77
|
+
} | {
|
|
78
|
+
kind: "connection";
|
|
79
|
+
namespace: string;
|
|
80
|
+
connection: string;
|
|
81
|
+
} | {
|
|
82
|
+
kind: "access_credential";
|
|
83
|
+
namespace: string;
|
|
84
|
+
accessCredential: AccessCredential;
|
|
85
|
+
} | {
|
|
86
|
+
kind: "platform_pool";
|
|
87
|
+
namespace: string;
|
|
88
|
+
poolId: string;
|
|
89
|
+
};
|
|
90
|
+
export type Budget = {
|
|
91
|
+
id: string;
|
|
92
|
+
version: number;
|
|
93
|
+
scope: BudgetScope;
|
|
94
|
+
surface: Surface | "any";
|
|
95
|
+
unit: string;
|
|
96
|
+
limit: Quantity | null;
|
|
97
|
+
window: BudgetWindow;
|
|
98
|
+
onExceed: "block" | "warn";
|
|
99
|
+
};
|
|
100
|
+
export type LifecycleState = "reserved" | "dispatch_intended" | "pending" | "settled" | "released";
|
|
101
|
+
export type Certainty = "measured" | "estimated" | "unknown";
|
|
102
|
+
export type Measurement = {
|
|
103
|
+
unit: string;
|
|
104
|
+
quantity: Quantity;
|
|
105
|
+
certainty: "measured" | "estimated";
|
|
106
|
+
} | {
|
|
107
|
+
unit: string;
|
|
108
|
+
quantity: null;
|
|
109
|
+
certainty: "unknown";
|
|
110
|
+
};
|
|
111
|
+
export type Cost = {
|
|
112
|
+
certainty: "measured" | "estimated";
|
|
113
|
+
money: Money;
|
|
114
|
+
} | {
|
|
115
|
+
certainty: "unknown";
|
|
116
|
+
money: null;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Receipt certainty is derived from its measurements and cost, never stored separately.
|
|
120
|
+
* Corrections append a receipt whose supersedes ID names an existing receipt.
|
|
121
|
+
* Effective evidence is the latest receipt not superseded by another receipt.
|
|
122
|
+
* Superseded receipts remain in the operation's history.
|
|
123
|
+
*/
|
|
124
|
+
export type Receipt = {
|
|
125
|
+
id: string;
|
|
126
|
+
supersedes?: string;
|
|
127
|
+
measurements: readonly Measurement[];
|
|
128
|
+
cost: Cost;
|
|
129
|
+
providerRequestId?: string;
|
|
130
|
+
providerPriceVersion?: string;
|
|
131
|
+
evidenceRef?: string;
|
|
132
|
+
occurredAt: string;
|
|
133
|
+
recordedAt: string;
|
|
134
|
+
cached: boolean;
|
|
135
|
+
failed: boolean;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Store selects all applying budgets atomically inside reserve; Meter's pre-resolution
|
|
139
|
+
* is advisory and never sufficient for admission.
|
|
140
|
+
* Match namespace and the bound: principal, group, connection, accessCredential by
|
|
141
|
+
* kind and id, or poolId listed in platformPools. Match surface or "any".
|
|
142
|
+
* Each applicable budget's unit must appear in estimate. A missing bounded unit is
|
|
143
|
+
* a Meter validation error, not permission to bypass the bound. Store re-checks this
|
|
144
|
+
* against current budgets. Units without budgets are recorded without a bound.
|
|
145
|
+
* Use the current budget version at reservation time; snapshot its resolved epoch
|
|
146
|
+
* and version into budgetEpochs. Check every applying budget in one atomic command.
|
|
147
|
+
* Return the first exceeded bound in deterministic host-policy order; default:
|
|
148
|
+
* platform_pool, principal, group, connection, access_credential.
|
|
149
|
+
* A guest session is actor, not budget owner. The platform or a dedicated guest
|
|
150
|
+
* principal owns the operation; its pool and host-enforced session limit both apply.
|
|
151
|
+
*/
|
|
152
|
+
export type ReserveInput = {
|
|
153
|
+
/** Durable dispatch identity. Reuse with different semantics is a conflict. */
|
|
154
|
+
operationId: string;
|
|
155
|
+
/** Undispatched lifetime, 1..86400000 ms; defaults to five minutes. Replay never extends it.
|
|
156
|
+
* Queued hosts must take dispatch intent at enqueue and carry the lease, or cover queue delay with this lifetime.
|
|
157
|
+
*/
|
|
158
|
+
reservationTtlMs?: number;
|
|
159
|
+
scope: Scope;
|
|
160
|
+
fundingSource: FundingSource;
|
|
161
|
+
/** Platform pools this operation draws from, when the provider key is platform-funded. */
|
|
162
|
+
platformPools?: readonly string[];
|
|
163
|
+
costOwner: string;
|
|
164
|
+
creditAccountRef?: string;
|
|
165
|
+
customerPriceVersion?: string;
|
|
166
|
+
surface: Surface;
|
|
167
|
+
source: Source;
|
|
168
|
+
provider: string;
|
|
169
|
+
operation: string;
|
|
170
|
+
estimate: readonly Quantity[];
|
|
171
|
+
correlationId?: string;
|
|
172
|
+
parentOperationId?: string;
|
|
173
|
+
};
|
|
174
|
+
/** Expiry fences dispatch. Explicit release or expiry maintenance changes state; reads never mutate. */
|
|
175
|
+
export type Operation = ReserveInput & {
|
|
176
|
+
reservationExpiresAt: string;
|
|
177
|
+
state: LifecycleState;
|
|
178
|
+
version: number;
|
|
179
|
+
createdAt: string;
|
|
180
|
+
updatedAt: string;
|
|
181
|
+
budgetEpochs: readonly {
|
|
182
|
+
budgetId: string;
|
|
183
|
+
budgetVersion: number;
|
|
184
|
+
epoch: string;
|
|
185
|
+
startsAt: string;
|
|
186
|
+
endsAt: string | null;
|
|
187
|
+
}[];
|
|
188
|
+
/** Append-only, oldest first. Corrections never remove historical receipts. */
|
|
189
|
+
receipts: readonly Receipt[];
|
|
190
|
+
/** Dispatch or recovery lease. Expired leases remain visible until replaced. */
|
|
191
|
+
lease: Lease | null;
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Identical operationId and semantic fields return replayed: true in any lifecycle state.
|
|
195
|
+
* A replay never authorizes dispatch. Different semantic fields return semantic_mismatch.
|
|
196
|
+
* Budget denial returns AllowanceExceeded data, not an expected-outcome exception.
|
|
197
|
+
*/
|
|
198
|
+
export type ReserveResult = ValidationFailure | {
|
|
199
|
+
outcome: "invalid";
|
|
200
|
+
reason: "missing_estimate_unit";
|
|
201
|
+
unit: string;
|
|
202
|
+
operation: null;
|
|
203
|
+
} | {
|
|
204
|
+
outcome: "reserved";
|
|
205
|
+
replayed: false;
|
|
206
|
+
operation: Operation;
|
|
207
|
+
warnings: readonly AllowanceExceeded[];
|
|
208
|
+
} | {
|
|
209
|
+
outcome: "reserved";
|
|
210
|
+
replayed: true;
|
|
211
|
+
operation: Operation;
|
|
212
|
+
warnings: readonly AllowanceExceeded[];
|
|
213
|
+
} | {
|
|
214
|
+
outcome: "exceeded";
|
|
215
|
+
exceeded: AllowanceExceeded;
|
|
216
|
+
operation: null;
|
|
217
|
+
} | {
|
|
218
|
+
outcome: "conflict";
|
|
219
|
+
reason: "semantic_mismatch";
|
|
220
|
+
operation: Operation;
|
|
221
|
+
};
|
|
222
|
+
export type OperationRef = Pick<Scope, "namespace" | "principal"> & {
|
|
223
|
+
operationId: string;
|
|
224
|
+
};
|
|
225
|
+
export type OperationCommand = OperationRef & {
|
|
226
|
+
/** Replay key for this mutation; checked before optimistic version validation. */
|
|
227
|
+
commandId: string;
|
|
228
|
+
expectedVersion: number;
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* An active dispatch lease permits the first upstream call and settlement by its holder.
|
|
232
|
+
* Renew for long calls. Expiry changes no operation state and never permits redispatch.
|
|
233
|
+
* Each recovery claim issues a new leaseId and fences the previous holder out.
|
|
234
|
+
* Implementations bind the caller to the authenticated holder, not a caller-supplied assertion.
|
|
235
|
+
*/
|
|
236
|
+
export type Lease = {
|
|
237
|
+
leaseId: string;
|
|
238
|
+
holder: string;
|
|
239
|
+
expiresAt: string;
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* Only the first intent returns granted: true. Replaying its commandId returns
|
|
243
|
+
* already_dispatched, as does another commandId on an already intended operation.
|
|
244
|
+
* Neither replay nor lease expiry grants another upstream call.
|
|
245
|
+
*/
|
|
246
|
+
export type DispatchGrant = ValidationFailure | {
|
|
247
|
+
granted: true;
|
|
248
|
+
operation: Operation;
|
|
249
|
+
lease: Lease;
|
|
250
|
+
} | {
|
|
251
|
+
granted: false;
|
|
252
|
+
operation: Operation | null;
|
|
253
|
+
reason: "already_dispatched" | "version_conflict" | "not_reserved" | "released" | "reservation_expired";
|
|
254
|
+
};
|
|
255
|
+
export type DispatchIntentInput = OperationCommand & {
|
|
256
|
+
/** Opaque worker identity used for fencing and diagnostics. */
|
|
257
|
+
holder: string;
|
|
258
|
+
leaseTtlMs: number;
|
|
259
|
+
};
|
|
260
|
+
/**
|
|
261
|
+
* No command journal or commandId. Renewal uses max(current expiry, now + TTL).
|
|
262
|
+
* Repeating at the same clock instant is idempotent; a later retry can extend expiry.
|
|
263
|
+
* It never shortens the lease, changes the operation version, or regrants dispatch.
|
|
264
|
+
*/
|
|
265
|
+
export type LeaseRenewalInput = OperationRef & {
|
|
266
|
+
leaseId: string;
|
|
267
|
+
leaseTtlMs: number;
|
|
268
|
+
};
|
|
269
|
+
/**
|
|
270
|
+
* Only the current holder may renew an active lease. Renewal after expiry fails.
|
|
271
|
+
* A rejected holder must stop work and hand over to recovery.
|
|
272
|
+
*/
|
|
273
|
+
export type LeaseRenewal = ValidationFailure | {
|
|
274
|
+
renewed: true;
|
|
275
|
+
lease: Lease;
|
|
276
|
+
} | {
|
|
277
|
+
renewed: false;
|
|
278
|
+
reason: "expired" | "not_holder" | "not_active";
|
|
279
|
+
};
|
|
280
|
+
export type RecoveryClaimInput = OperationRef & {
|
|
281
|
+
holder: string;
|
|
282
|
+
leaseTtlMs: number;
|
|
283
|
+
};
|
|
284
|
+
/**
|
|
285
|
+
* Claim only dispatch_intended or pending operations with no active lease.
|
|
286
|
+
* Issue a new leaseId; the previous holder is fenced out.
|
|
287
|
+
* Recovery never redispatches. It resolves provider evidence or supported upstream
|
|
288
|
+
* idempotency evidence, then settles, corrects, or leaves pending uncertain exposure.
|
|
289
|
+
*/
|
|
290
|
+
export type RecoveryClaim = ValidationFailure | {
|
|
291
|
+
claimed: true;
|
|
292
|
+
operation: Operation;
|
|
293
|
+
lease: Lease;
|
|
294
|
+
} | {
|
|
295
|
+
claimed: false;
|
|
296
|
+
operation: Operation | null;
|
|
297
|
+
reason: "lease_active" | "not_recoverable" | "not_found";
|
|
298
|
+
};
|
|
299
|
+
/**
|
|
300
|
+
* Lease authority requires an active dispatch lease held by the caller.
|
|
301
|
+
* Recovery authority requires the active lease issued by claimForRecovery.
|
|
302
|
+
* Late evidence requires host authorization and no active lease. Settle accepts pending
|
|
303
|
+
* only; correcting settled work requires replacesReceiptId and reason. Every new command
|
|
304
|
+
* checks expectedVersion. Identical successful replays return the recorded result.
|
|
305
|
+
* The store records source. This path needs no dispatch lease.
|
|
306
|
+
*/
|
|
307
|
+
export type Authority = {
|
|
308
|
+
kind: "lease";
|
|
309
|
+
leaseId: string;
|
|
310
|
+
} | {
|
|
311
|
+
kind: "recovery";
|
|
312
|
+
leaseId: string;
|
|
313
|
+
} | {
|
|
314
|
+
kind: "late_evidence";
|
|
315
|
+
source: string;
|
|
316
|
+
};
|
|
317
|
+
export type SettleInput = OperationCommand & {
|
|
318
|
+
authority: Authority;
|
|
319
|
+
receipt: Receipt;
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* Host-authorized cancellation needs reserved state and an atomic version check, not a lease.
|
|
323
|
+
* After dispatch intent, release always rejects with not_reserved.
|
|
324
|
+
*/
|
|
325
|
+
export type ReleaseInput = OperationCommand & {
|
|
326
|
+
reason: string;
|
|
327
|
+
};
|
|
328
|
+
/** Same authority rules as settle; append only, with an existing receipt as the target. */
|
|
329
|
+
export type CorrectionInput = OperationCommand & {
|
|
330
|
+
authority: Authority;
|
|
331
|
+
receipt: Receipt;
|
|
332
|
+
replacesReceiptId: string;
|
|
333
|
+
reason: string;
|
|
334
|
+
};
|
|
335
|
+
/**
|
|
336
|
+
* Identical command replay returns the stored result with replayed: true.
|
|
337
|
+
* Reusing commandId with a different receipt returns receipt_conflict.
|
|
338
|
+
* Successful accounting may retain pending state when exposure remains unknown.
|
|
339
|
+
*/
|
|
340
|
+
export type SettleResult = ValidationFailure | {
|
|
341
|
+
outcome: "settled";
|
|
342
|
+
replayed: boolean;
|
|
343
|
+
operation: Operation;
|
|
344
|
+
} | {
|
|
345
|
+
outcome: "rejected";
|
|
346
|
+
reason: "not_holder" | "lease_expired" | "version_conflict" | "invalid_state" | "receipt_conflict";
|
|
347
|
+
operation: Operation | null;
|
|
348
|
+
};
|
|
349
|
+
/** Identical successful command replay returns the stored result with replayed: true. */
|
|
350
|
+
export type ReleaseResult = ValidationFailure | {
|
|
351
|
+
outcome: "released";
|
|
352
|
+
replayed: boolean;
|
|
353
|
+
operation: Operation;
|
|
354
|
+
} | {
|
|
355
|
+
outcome: "rejected";
|
|
356
|
+
reason: "not_reserved" | "version_conflict";
|
|
357
|
+
operation: Operation | null;
|
|
358
|
+
};
|
|
359
|
+
/** Requested data scope only; this is not authorization. Pool reads follow AccessContext pool rules. */
|
|
360
|
+
export type UsageScope = {
|
|
361
|
+
kind: "principal";
|
|
362
|
+
namespace: string;
|
|
363
|
+
principal: string;
|
|
364
|
+
} | {
|
|
365
|
+
kind: "group";
|
|
366
|
+
namespace: string;
|
|
367
|
+
group: string;
|
|
368
|
+
} | {
|
|
369
|
+
kind: "namespace";
|
|
370
|
+
namespace: string;
|
|
371
|
+
} | {
|
|
372
|
+
kind: "platform_pool";
|
|
373
|
+
namespace: string;
|
|
374
|
+
poolId: string;
|
|
375
|
+
};
|
|
376
|
+
/**
|
|
377
|
+
* Built by the host from its verified session or token.
|
|
378
|
+
* HTTP builds this context from authentication, never the request body or query string.
|
|
379
|
+
* Namespace must match. Principal and group scopes require their corresponding
|
|
380
|
+
* readable list or "*". Connection and access-credential scopes require a readable
|
|
381
|
+
* owning principal or group: the host resolver supplies ownership to Meter for authorization.
|
|
382
|
+
* A pool scope requires readablePools membership, "*", or canManageBudgets.
|
|
383
|
+
*/
|
|
384
|
+
export type AccessContext = {
|
|
385
|
+
namespace: string;
|
|
386
|
+
/** Principals the caller may read. "*" means the whole namespace. */
|
|
387
|
+
readablePrincipals: readonly string[] | "*";
|
|
388
|
+
readableGroups: readonly string[] | "*";
|
|
389
|
+
readablePools: readonly string[] | "*";
|
|
390
|
+
canReadBillingDetail: boolean;
|
|
391
|
+
canManageBudgets: boolean;
|
|
392
|
+
};
|
|
393
|
+
/** groupBy: "principal" is allowed only for group or namespace scope. */
|
|
394
|
+
export type UsageQuery = {
|
|
395
|
+
scope: UsageScope;
|
|
396
|
+
from: string;
|
|
397
|
+
to: string;
|
|
398
|
+
connection?: string;
|
|
399
|
+
units: readonly string[];
|
|
400
|
+
groupBy: readonly ("principal" | "provider" | "operation" | "surface" | "source" | "connection" | "day" | "access_credential" | "platform_pool")[];
|
|
401
|
+
cursor?: string;
|
|
402
|
+
limit?: number;
|
|
403
|
+
};
|
|
404
|
+
export type UsageRow = {
|
|
405
|
+
dimensions: Readonly<Record<string, string>>;
|
|
406
|
+
measurements: readonly Measurement[];
|
|
407
|
+
cost: Cost;
|
|
408
|
+
fundingSource: FundingSource;
|
|
409
|
+
costOwner: string;
|
|
410
|
+
unknownOperations: bigint;
|
|
411
|
+
};
|
|
412
|
+
export type UsagePage = {
|
|
413
|
+
rows: readonly UsageRow[];
|
|
414
|
+
asOf: string;
|
|
415
|
+
watermark: string;
|
|
416
|
+
nextCursor?: string;
|
|
417
|
+
};
|
|
418
|
+
/** Budgets defined for exactly this scope, regardless of any operation. */
|
|
419
|
+
export type DefinedBudgetsQuery = {
|
|
420
|
+
scope: BudgetScope;
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* All budgets that would apply to the operation's scope, surface, units and pools.
|
|
424
|
+
* Requires the operation's principal to be readable. Statuses for unreadable pools
|
|
425
|
+
* must redact budget.limit, used, reserved and remaining to null, with redacted: true.
|
|
426
|
+
* Listing does not reserve capacity or replace the atomic admission check.
|
|
427
|
+
*/
|
|
428
|
+
export type ApplicableBudgetsQuery = {
|
|
429
|
+
scope: Scope;
|
|
430
|
+
surface: Surface;
|
|
431
|
+
units: readonly string[];
|
|
432
|
+
platformPools?: readonly string[];
|
|
433
|
+
};
|
|
434
|
+
export type BudgetStatus = {
|
|
435
|
+
budget: Budget;
|
|
436
|
+
epoch: {
|
|
437
|
+
epoch: string;
|
|
438
|
+
startsAt: string;
|
|
439
|
+
endsAt: string | null;
|
|
440
|
+
};
|
|
441
|
+
used: Quantity | null;
|
|
442
|
+
reserved: Quantity | null;
|
|
443
|
+
remaining: Quantity | null;
|
|
444
|
+
/** Set when the caller may see that a bound applies but not its figures. */
|
|
445
|
+
redacted?: true;
|
|
446
|
+
};
|
|
447
|
+
/** A scope wider than AccessContext is forbidden; never silently widen or narrow it. */
|
|
448
|
+
export type ReadResult<T> = ValidationFailure | {
|
|
449
|
+
outcome: "ok";
|
|
450
|
+
value: T;
|
|
451
|
+
} | {
|
|
452
|
+
outcome: "forbidden";
|
|
453
|
+
};
|
|
454
|
+
/** Data-only budget denial. A P1 implementation may wrap it in a runtime error class. */
|
|
455
|
+
export interface AllowanceExceeded {
|
|
456
|
+
readonly code: "allowance_exceeded";
|
|
457
|
+
readonly budget: Budget;
|
|
458
|
+
readonly used: Quantity;
|
|
459
|
+
readonly reserved: Quantity;
|
|
460
|
+
readonly resetsAt: string | null;
|
|
461
|
+
}
|
|
462
|
+
/** Trusted maintenance command. Host authorizes namespace-wide cleanup; no provider call or charge is undone. */
|
|
463
|
+
export type ExpireReservationsInput = {
|
|
464
|
+
namespace: string;
|
|
465
|
+
limit?: number;
|
|
466
|
+
};
|
|
467
|
+
export type ExpireReservationsResult = ValidationFailure | {
|
|
468
|
+
outcome: "expired";
|
|
469
|
+
count: number;
|
|
470
|
+
hasMore: boolean;
|
|
471
|
+
};
|
|
472
|
+
/**
|
|
473
|
+
* One interface for embedded and remote implementations.
|
|
474
|
+
* All reads require verified server context and return forbidden for unauthorized scope.
|
|
475
|
+
* Meter validates inputs and resolves host policy; Store repeats all concurrent checks atomically.
|
|
476
|
+
* Embedded hosts must schedule expireReservations themselves; the local server does so every thirty seconds.
|
|
477
|
+
* Admission sweeps at most one default batch. Maintenance owns the remaining expired backlog.
|
|
478
|
+
*/
|
|
479
|
+
export interface Meter {
|
|
480
|
+
expireReservations(input: ExpireReservationsInput): Promise<ExpireReservationsResult>;
|
|
481
|
+
reserve(input: ReserveInput): Promise<ReserveResult>;
|
|
482
|
+
markDispatchIntent(input: DispatchIntentInput): Promise<DispatchGrant>;
|
|
483
|
+
renewLease(input: LeaseRenewalInput): Promise<LeaseRenewal>;
|
|
484
|
+
claimForRecovery(input: RecoveryClaimInput): Promise<RecoveryClaim>;
|
|
485
|
+
settle(input: SettleInput): Promise<SettleResult>;
|
|
486
|
+
correct(input: CorrectionInput): Promise<SettleResult>;
|
|
487
|
+
releaseUndispatched(input: ReleaseInput): Promise<ReleaseResult>;
|
|
488
|
+
getOperation(access: AccessContext, input: OperationRef): Promise<ReadResult<Operation | null>>;
|
|
489
|
+
usage(access: AccessContext, query: UsageQuery): Promise<ReadResult<UsagePage>>;
|
|
490
|
+
definedBudgets(access: AccessContext, query: DefinedBudgetsQuery): Promise<ReadResult<readonly Budget[]>>;
|
|
491
|
+
applicableBudgets(access: AccessContext, query: ApplicableBudgetsQuery): Promise<ReadResult<readonly BudgetStatus[]>>;
|
|
492
|
+
}
|
|
493
|
+
/** Trusted host admission policy; Store applies order in the atomic command. */
|
|
494
|
+
export type AdmissionPolicy = {
|
|
495
|
+
budgetOrder: readonly BudgetScope["kind"][];
|
|
496
|
+
};
|
|
497
|
+
export type BudgetOwner = Extract<BudgetScope, {
|
|
498
|
+
kind: "principal" | "group";
|
|
499
|
+
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type { Money, Quantity, AccessCredential, Scope, FundingSource, Surface, Source, BudgetWindow, BudgetScope, Budget, LifecycleState, Certainty, Measurement, Cost, Receipt, ReserveInput, ReserveResult, Operation, OperationRef, OperationCommand, Lease, DispatchGrant, DispatchIntentInput, LeaseRenewalInput, LeaseRenewal, RecoveryClaimInput, RecoveryClaim, Authority, SettleInput, ReleaseInput, CorrectionInput, SettleResult, ReleaseResult, UsageScope, AccessContext, UsageQuery, UsageRow, UsagePage, DefinedBudgetsQuery, ApplicableBudgetsQuery, BudgetStatus, ReadResult, AllowanceExceeded, Meter, } from "./contracts.js";
|
|
2
|
+
export { resolveWindow } from "./windows.js";
|
|
3
|
+
export type { ResolvedWindow } from "./windows.js";
|
|
4
|
+
export { fromDecimalString, toDecimalString, add as addMoney, sub as subtractMoney, compare as compareMoney, } from "./money.js";
|
|
5
|
+
export { normalizeScale, add as addQuantity, compare as compareQuantity } from "./quantity.js";
|
|
6
|
+
export type { ValidationFailure, AdmissionPolicy, BudgetOwner } from "./contracts.js";
|
|
7
|
+
export { defaultBudgetOrder } from "./policy.js";
|
|
8
|
+
export type { ExpireReservationsInput, ExpireReservationsResult } from "./contracts.js";
|
|
9
|
+
export { decodeMeterJson } from "./wire.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { resolveWindow } from "./windows.js";
|
|
2
|
+
export { fromDecimalString, toDecimalString, add as addMoney, sub as subtractMoney, compare as compareMoney, } from "./money.js";
|
|
3
|
+
export { normalizeScale, add as addQuantity, compare as compareQuantity } from "./quantity.js";
|
|
4
|
+
export { defaultBudgetOrder } from "./policy.js";
|
|
5
|
+
export { decodeMeterJson } from "./wire.js";
|
package/dist/money.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Money } from "./contracts.js";
|
|
2
|
+
export declare function fromDecimalString(cents: string, options?: {
|
|
3
|
+
allowNegative?: boolean;
|
|
4
|
+
}): Money;
|
|
5
|
+
export declare function toDecimalString(m: Money): string;
|
|
6
|
+
export declare const add: (a: Money, b: Money) => Money;
|
|
7
|
+
export declare const sub: (a: Money, b: Money) => Money;
|
|
8
|
+
export declare const compare: (a: Money, b: Money) => -1 | 0 | 1;
|
package/dist/money.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function fromDecimalString(cents, options = {}) {
|
|
2
|
+
if (!/^-?\d+(\.\d{1,4})?$/.test(cents) || (!options.allowNegative && cents.startsWith("-")))
|
|
3
|
+
throw new Error("InvalidInput: cents");
|
|
4
|
+
const [whole, fraction = ""] = cents.replace("-", "").split(".");
|
|
5
|
+
return {
|
|
6
|
+
currency: "USD",
|
|
7
|
+
units: (BigInt(whole) * 10000n + BigInt(fraction.padEnd(4, "0"))) *
|
|
8
|
+
(cents.startsWith("-") ? -1n : 1n),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export function toDecimalString(m) {
|
|
12
|
+
const n = m.units < 0n ? -m.units : m.units;
|
|
13
|
+
return `${m.units < 0n ? "-" : ""}${n / 10000n}.${(n % 10000n).toString().padStart(4, "0")}`;
|
|
14
|
+
}
|
|
15
|
+
export const add = (a, b) => ({ currency: "USD", units: a.units + b.units });
|
|
16
|
+
export const sub = (a, b) => ({ currency: "USD", units: a.units - b.units });
|
|
17
|
+
export const compare = (a, b) => a.units < b.units ? -1 : a.units > b.units ? 1 : 0;
|
package/dist/policy.d.ts
ADDED
package/dist/policy.js
ADDED
package/dist/quantity.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function normalizeScale(q, scale) {
|
|
2
|
+
if (!Number.isSafeInteger(scale) || scale < q.scale || scale > 18)
|
|
3
|
+
throw new Error("InvalidInput: scale");
|
|
4
|
+
return { ...q, scale, value: q.value * 10n ** BigInt(scale - q.scale) };
|
|
5
|
+
}
|
|
6
|
+
function pair(a, b) {
|
|
7
|
+
if (a.unit !== b.unit)
|
|
8
|
+
throw new Error("UnitMismatch");
|
|
9
|
+
const scale = Math.max(a.scale, b.scale);
|
|
10
|
+
return [normalizeScale(a, scale), normalizeScale(b, scale)];
|
|
11
|
+
}
|
|
12
|
+
export function add(a, b) {
|
|
13
|
+
const [x, y] = pair(a, b);
|
|
14
|
+
return { ...x, value: x.value + y.value };
|
|
15
|
+
}
|
|
16
|
+
export function compare(a, b) {
|
|
17
|
+
const [x, y] = pair(a, b);
|
|
18
|
+
return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
|
|
19
|
+
}
|
package/dist/windows.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function resolveWindow(window, now) {
|
|
2
|
+
if (!Number.isFinite(now.getTime()))
|
|
3
|
+
throw new Error("InvalidInput: now");
|
|
4
|
+
if (window.kind === "rolling")
|
|
5
|
+
throw new Error("UnsupportedWindow: rollingWindows");
|
|
6
|
+
if (window.kind === "calendar_month") {
|
|
7
|
+
const year = now.getUTCFullYear(), month = now.getUTCMonth();
|
|
8
|
+
return {
|
|
9
|
+
epoch: now.toISOString().slice(0, 7),
|
|
10
|
+
startsAt: new Date(Date.UTC(year, month, 1)).toISOString(),
|
|
11
|
+
endsAt: new Date(Date.UTC(year, month + 1, 1)).toISOString(),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
const starts = new Date(window.startsAt), ends = window.kind === "provider_cycle" ? new Date(window.endsAt) : null;
|
|
15
|
+
if (!Number.isFinite(starts.getTime()) || (ends && !Number.isFinite(ends.getTime())))
|
|
16
|
+
throw new Error("InvalidInput: window");
|
|
17
|
+
if (now < starts || (ends && now >= ends))
|
|
18
|
+
throw new Error("InactiveWindow");
|
|
19
|
+
return {
|
|
20
|
+
epoch: window.kind === "provider_cycle" ? window.cycleId : window.epoch,
|
|
21
|
+
startsAt: starts.toISOString(),
|
|
22
|
+
endsAt: ends?.toISOString() ?? null,
|
|
23
|
+
};
|
|
24
|
+
}
|
package/dist/wire.d.ts
ADDED
package/dist/wire.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Restore integers only in recognizable Meter DTOs. Generic metadata fields retain their strings.
|
|
2
|
+
* This performs conversion, not validation. HTTP validates strict wire schemas before calling it.
|
|
3
|
+
*/
|
|
4
|
+
export function decodeMeterJson(text) {
|
|
5
|
+
const decimal = (v) => typeof v === "string" && /^-?\d+$/.test(v);
|
|
6
|
+
return JSON.parse(text, (_key, value) => {
|
|
7
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
8
|
+
return value;
|
|
9
|
+
const v = value, keys = Object.keys(v);
|
|
10
|
+
if (keys.length === 2 && v.currency === "USD" && decimal(v.units))
|
|
11
|
+
return { ...v, units: BigInt(v.units) };
|
|
12
|
+
if (keys.length === 3 &&
|
|
13
|
+
typeof v.unit === "string" &&
|
|
14
|
+
typeof v.scale === "number" &&
|
|
15
|
+
decimal(v.value))
|
|
16
|
+
return { ...v, value: BigInt(v.value) };
|
|
17
|
+
if (v.dimensions &&
|
|
18
|
+
typeof v.dimensions === "object" &&
|
|
19
|
+
Array.isArray(v.measurements) &&
|
|
20
|
+
v.cost &&
|
|
21
|
+
typeof v.cost === "object" &&
|
|
22
|
+
["byok", "platform"].includes(String(v.fundingSource)) &&
|
|
23
|
+
typeof v.costOwner === "string" &&
|
|
24
|
+
decimal(v.unknownOperations))
|
|
25
|
+
return { ...v, unknownOperations: BigInt(v.unknownOperations) };
|
|
26
|
+
return value;
|
|
27
|
+
});
|
|
28
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@usagekit/core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"description": "Exact quantities, ownership and pure domain types.",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist",
|
|
15
|
+
"!dist/**/*.tsbuildinfo",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"NOTICE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc -b",
|
|
21
|
+
"typecheck": "tsc -b",
|
|
22
|
+
"prepublishOnly": "node ../../scripts/publish-guard.mjs",
|
|
23
|
+
"prepack": "node ../../scripts/package-license.mjs"
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "restricted",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
}
|
|
30
|
+
}
|