@voltro/plugin-economy 0.0.0-stage → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG.md +24329 -0
  2. package/LICENSE +61 -0
  3. package/README.md +2719 -2
  4. package/SECURITY.md +56 -0
  5. package/THIRD-PARTY-NOTICES.md +9189 -0
  6. package/dist/amount.js +21 -0
  7. package/dist/appleIap.server.js +263 -0
  8. package/dist/appleIapNotifications.server.js +163 -0
  9. package/dist/appleIapTrust.server.js +31 -0
  10. package/dist/bundleValue.server.js +113 -0
  11. package/dist/canonicalDataJson.js +11 -0
  12. package/dist/capture.js +54 -0
  13. package/dist/codePort.fixture.js +124 -0
  14. package/dist/codeStore.server.js +440 -0
  15. package/dist/codeTables.entity.js +44 -0
  16. package/dist/codes.d.ts +150 -0
  17. package/dist/codes.js +83 -0
  18. package/dist/components.d.ts +397 -0
  19. package/dist/components.js +284 -0
  20. package/dist/consistency.server.js +116 -0
  21. package/dist/containerStore.server.js +688 -0
  22. package/dist/containerStore.testFixtures.js +76 -0
  23. package/dist/containerTables.entity.js +46 -0
  24. package/dist/containers.d.ts +311 -0
  25. package/dist/containers.fixture.js +129 -0
  26. package/dist/containers.js +215 -0
  27. package/dist/containers.server.js +40 -0
  28. package/dist/containersPort.fixture.js +75 -0
  29. package/dist/currency.js +33 -0
  30. package/dist/declarationFixtures.js +62 -0
  31. package/dist/economy-app/events/economy.refundReversed.event.ts +1 -0
  32. package/dist/economy-app/events/economy.refunded.event.ts +1 -0
  33. package/dist/economyPort.fixture.js +125 -0
  34. package/dist/errors.d.ts +14 -0
  35. package/dist/errors.js +22 -0
  36. package/dist/events.d.ts +46 -0
  37. package/dist/events.js +1 -0
  38. package/dist/googleIap.server.js +392 -0
  39. package/dist/googleIapNotifications.server.js +131 -0
  40. package/dist/googleIapSubscription.server.js +184 -0
  41. package/dist/iap.d.ts +309 -0
  42. package/dist/iap.js +304 -0
  43. package/dist/iap.testFixtures.js +145 -0
  44. package/dist/iapAccountTables.entity.js +40 -0
  45. package/dist/iapAccounts.server.js +201 -0
  46. package/dist/iapBinding.server.js +524 -0
  47. package/dist/iapCheckout.server.js +98 -0
  48. package/dist/iapCompletion.server.js +56 -0
  49. package/dist/iapCurrentState.server.js +108 -0
  50. package/dist/iapCurrentState.testFixtures.js +23 -0
  51. package/dist/iapCurrentStatePort.fixture.js +64 -0
  52. package/dist/iapEntitlements.d.ts +79 -0
  53. package/dist/iapEntitlements.js +58 -0
  54. package/dist/iapEntitlements.server.js +49 -0
  55. package/dist/iapEntitlementsBinding.server.js +106 -0
  56. package/dist/iapEntitlementsPort.fixture.js +81 -0
  57. package/dist/iapInstalledEntitlements.testFixtures.js +76 -0
  58. package/dist/iapInstalledNotifications.testFixtures.js +94 -0
  59. package/dist/iapInventoryRefunds.server.js +262 -0
  60. package/dist/iapNotificationCustodyPort.fixture.js +68 -0
  61. package/dist/iapNotificationPort.fixture.js +74 -0
  62. package/dist/iapNotificationProcessor.server.js +135 -0
  63. package/dist/iapNotificationProcessor.testFixtures.js +64 -0
  64. package/dist/iapNotificationProcessorPort.fixture.js +56 -0
  65. package/dist/iapNotificationSchedule.server.js +70 -0
  66. package/dist/iapNotificationStore.server.js +353 -0
  67. package/dist/iapNotificationStore.testFixtures.js +32 -0
  68. package/dist/iapNotificationTables.entity.js +49 -0
  69. package/dist/iapNotificationTarget.server.js +37 -0
  70. package/dist/iapNotificationTarget.testFixtures.js +30 -0
  71. package/dist/iapNotifications.d.ts +644 -0
  72. package/dist/iapNotifications.js +6 -0
  73. package/dist/iapNotifications.server.js +96 -0
  74. package/dist/iapNotificationsBinding.server.js +233 -0
  75. package/dist/iapNotificationsSystemPort.fixture.js +51 -0
  76. package/dist/iapPlugin.testFixtures.js +60 -0
  77. package/dist/iapPort.fixture.js +75 -0
  78. package/dist/iapProviderCapture.server.js +18 -0
  79. package/dist/iapRecovery.d.ts +146 -0
  80. package/dist/iapRecovery.js +90 -0
  81. package/dist/iapRefundEventDelivery.server.js +83 -0
  82. package/dist/iapRefundEvents.js +45 -0
  83. package/dist/iapRefundEventsPort.fixture.js +60 -0
  84. package/dist/iapRefundPort.fixture.js +55 -0
  85. package/dist/iapRefundTables.entity.js +56 -0
  86. package/dist/iapRefunds.d.ts +755 -0
  87. package/dist/iapRefunds.js +6 -0
  88. package/dist/iapRefunds.server.js +554 -0
  89. package/dist/iapRefunds.testFixtures.js +65 -0
  90. package/dist/iapSpendAdmission.server.js +99 -0
  91. package/dist/iapStore.server.js +741 -0
  92. package/dist/iapStore.testFixtures.js +128 -0
  93. package/dist/iapTables.entity.js +81 -0
  94. package/dist/iapVerification.server.js +121 -0
  95. package/dist/index.d.ts +2984 -0
  96. package/dist/index.js +15 -0
  97. package/dist/intentionRecovery.js +134 -0
  98. package/dist/ledger.js +78 -0
  99. package/dist/loyalty.d.ts +274 -0
  100. package/dist/loyalty.fixture.js +93 -0
  101. package/dist/loyalty.js +312 -0
  102. package/dist/loyaltyBinding.server.js +204 -0
  103. package/dist/loyaltyPort.fixture.js +87 -0
  104. package/dist/loyaltyShopSource.server.js +91 -0
  105. package/dist/loyaltyStore.server.js +553 -0
  106. package/dist/loyaltyStore.testFixtures.js +83 -0
  107. package/dist/loyaltyTables.entity.js +50 -0
  108. package/dist/offerMerchandising.fixture.js +115 -0
  109. package/dist/offerMerchandising.js +283 -0
  110. package/dist/offerPolicies.d.ts +441 -0
  111. package/dist/offerPolicies.fixture.js +54 -0
  112. package/dist/offerPolicies.js +268 -0
  113. package/dist/piggyBanks.d.ts +272 -0
  114. package/dist/piggyBanks.fixture.js +71 -0
  115. package/dist/piggyBanks.js +201 -0
  116. package/dist/piggyBinding.server.js +205 -0
  117. package/dist/piggyPort.fixture.js +73 -0
  118. package/dist/piggyStore.server.js +611 -0
  119. package/dist/piggyStore.testFixtures.js +98 -0
  120. package/dist/piggyTables.entity.js +41 -0
  121. package/dist/plugin.js +1048 -0
  122. package/dist/port.js +13 -0
  123. package/dist/price.d.ts +99 -0
  124. package/dist/price.js +144 -0
  125. package/dist/purchaseRecovery.js +56 -0
  126. package/dist/reports.server.js +115 -0
  127. package/dist/rpc.d.ts +3201 -0
  128. package/dist/rpc.js +1201 -0
  129. package/dist/sanctionsTradeAuthority.server.js +80 -0
  130. package/dist/server.d.ts +3856 -0
  131. package/dist/server.js +43 -0
  132. package/dist/shop.d.ts +279 -0
  133. package/dist/shop.js +196 -0
  134. package/dist/shop.testFixtures.js +114 -0
  135. package/dist/shopPort.fixture.js +72 -0
  136. package/dist/shopPresentation.js +68 -0
  137. package/dist/shopStore.server.js +624 -0
  138. package/dist/shopTables.entity.js +63 -0
  139. package/dist/shopUiCopy.js +57 -0
  140. package/dist/spendLimits.d.ts +140 -0
  141. package/dist/spendLimits.fixture.js +53 -0
  142. package/dist/spendLimits.js +155 -0
  143. package/dist/spendLimitsPort.fixture.js +120 -0
  144. package/dist/subscriptionBinding.server.js +211 -0
  145. package/dist/subscriptionStore.server.js +643 -0
  146. package/dist/subscriptionStore.testFixtures.js +72 -0
  147. package/dist/subscriptionTables.entity.js +37 -0
  148. package/dist/subscriptions.d.ts +394 -0
  149. package/dist/subscriptions.fixture.js +97 -0
  150. package/dist/subscriptions.js +213 -0
  151. package/dist/subscriptionsPort.fixture.js +76 -0
  152. package/dist/systemFixtures.js +89 -0
  153. package/dist/tables.entity.js +83 -0
  154. package/dist/testing.d.ts +4615 -0
  155. package/dist/testing.js +29 -0
  156. package/dist/tradeAuthority.server.js +172 -0
  157. package/dist/tradeBinding.server.js +201 -0
  158. package/dist/tradeComponents.js +342 -0
  159. package/dist/tradeEscrow.server.js +232 -0
  160. package/dist/tradeEscrow.testFixtures.js +133 -0
  161. package/dist/tradeExpiry.server.js +43 -0
  162. package/dist/tradeRecovery.js +48 -0
  163. package/dist/tradeStore.server.js +750 -0
  164. package/dist/tradeStore.testFixtures.js +73 -0
  165. package/dist/tradeTables.entity.js +66 -0
  166. package/dist/tradeUiCopy.js +79 -0
  167. package/dist/trades.d.ts +246 -0
  168. package/dist/trades.fixture.js +103 -0
  169. package/dist/trades.js +289 -0
  170. package/dist/tradesPort.fixture.js +94 -0
  171. package/dist/walletEscrow.js +106 -0
  172. package/dist/walletEscrow.server.js +376 -0
  173. package/dist/walletKeys.server.js +5 -0
  174. package/dist/walletStore.js +571 -0
  175. package/dist/web.d.ts +2257 -0
  176. package/dist/web.js +9 -0
  177. package/package.json +161 -4
@@ -0,0 +1,624 @@
1
+ import { EconomyError as e, economyError as t } from "./errors.js";
2
+ import { dataList as n, dataObject as r, identifier as i } from "./capture.js";
3
+ import { captureCurrencies as a } from "./currency.js";
4
+ import { defaultPriceResolver as o, priceResolverContext as s, resolvePrice as c } from "./price.js";
5
+ import { captureShopOrderReceipt as l, defineShopOffer as u, shopBuyIntent as d, shopInteger as f, shopPayment as p } from "./shop.js";
6
+ import { canonicalDataJson as m } from "./canonicalDataJson.js";
7
+ import { shopCountersTable as h, shopOffersTable as g, shopOrdersTable as _, shopSubjectsTable as v, shopTenantsTable as y } from "./shopTables.entity.js";
8
+ import { Effect as b, Result as x } from "effect";
9
+ import { systemSubject as S } from "@voltro/protocol";
10
+ import { createHash as C } from "node:crypto";
11
+ import { and as w, eq as T, queryFor as E } from "@voltro/database";
12
+ import { executeSqlMutations as ee, prepareSqlMutation as D, prepareSqlMutationGroup as O } from "@voltro/database/sql";
13
+ import { InventoryError as k } from "@voltro/plugin-inventory/errors";
14
+ //#region src/shopStore.server.ts
15
+ var A = (e) => C("sha256").update(m(e)).digest("hex"), j = (e, t) => A({
16
+ offer: e,
17
+ rulesVersion: i(t)
18
+ }), M = (e, ...t) => e + A(t).slice(0, 56), N = (n) => n instanceof e ? n : n instanceof k && [
19
+ "conflict",
20
+ "erased",
21
+ "limit_exceeded",
22
+ "forbidden",
23
+ "not_found",
24
+ "invalid_record"
25
+ ].includes(n.code) ? t(n.code) : t("unavailable"), P = (e) => b.tryPromise({
26
+ try: e,
27
+ catch: N
28
+ }), F = (e) => {
29
+ try {
30
+ return e();
31
+ } catch (e) {
32
+ return b.fail(N(e));
33
+ }
34
+ }, I = async (e) => {
35
+ let t = await b.runPromise(b.result(e));
36
+ if (x.isFailure(t)) throw t.failure;
37
+ return t.success;
38
+ }, L = (e) => {
39
+ let n = e instanceof Date ? e.getTime() : typeof e == "string" ? Date.parse(e) : NaN;
40
+ if (!Number.isSafeInteger(n) || n < 0 || n > 864e13) throw t("invalid_record");
41
+ return n;
42
+ }, R = (e) => {
43
+ let n = structuredClone(e);
44
+ if (n.type !== "user") throw t("forbidden");
45
+ return i(n.id), i(n.tenantId), Object.freeze(n);
46
+ }, z = S("economy.shop"), B = (e, t, n, r) => Object.freeze([
47
+ Object.freeze({
48
+ id: M("esc_", e, n, "global"),
49
+ offerId: n,
50
+ scope: "global",
51
+ ownerKey: null,
52
+ day: null
53
+ }),
54
+ Object.freeze({
55
+ id: M("esc_", e, n, "player", t),
56
+ offerId: n,
57
+ scope: "player",
58
+ ownerKey: t,
59
+ day: null
60
+ }),
61
+ Object.freeze({
62
+ id: M("esc_", e, n, "day", t, String(Math.floor(r / 864e5))),
63
+ offerId: n,
64
+ scope: "day",
65
+ ownerKey: t,
66
+ day: Math.floor(r / 864e5)
67
+ })
68
+ ].sort((e, t) => e.id < t.id ? -1 : +(e.id > t.id))), V = class extends Error {
69
+ constructor() {
70
+ super("Accepted shop order replay"), this.name = "ShopReplay";
71
+ }
72
+ }, H = (e) => {
73
+ let s = r(e, [
74
+ "offers",
75
+ "currencies",
76
+ "realMoney",
77
+ "priceResolver",
78
+ "contextSource",
79
+ "version",
80
+ "systemAccount",
81
+ "maxOrders",
82
+ "maxAuditRows",
83
+ "now",
84
+ "economy",
85
+ "inventory"
86
+ ]), c = a(e.currencies), l = s.realMoney ?? !1, d = s.priceResolver ?? o, p = s.now ?? Date.now;
87
+ if (typeof l != "boolean" || typeof d != "function" || typeof p != "function") throw t("invalid_input");
88
+ let m = Object.freeze(n(e.offers, 256).map((e) => u(e, c, l)));
89
+ if (!m.length || new Set(m.map((e) => e.id)).size !== m.length || !e.economy || typeof e.economy.prepareTransfer != "function" || m.some((e) => e.items.length) && (!e.inventory || typeof e.inventory.prepareGrant != "function")) throw t("invalid_input");
90
+ let h = e.contextSource;
91
+ if (h !== void 0 && typeof h.read != "function" || m.some((e) => e.segment !== null || e.flag !== null || e.countries.length) && h === void 0) throw t("invalid_input");
92
+ let g = i(s.version ?? "default.v1");
93
+ if ((d !== o || h !== void 0) && g === "default.v1") throw t("invalid_input");
94
+ return Object.freeze({
95
+ offers: m,
96
+ currencies: c,
97
+ realMoney: l,
98
+ priceResolver: d,
99
+ version: g,
100
+ contextSource: h === void 0 ? void 0 : Object.freeze({ read: h.read.bind(h) }),
101
+ economy: Object.freeze({ prepareTransfer: e.economy.prepareTransfer.bind(e.economy) }),
102
+ inventory: e.inventory === void 0 ? void 0 : Object.freeze({ prepareGrant: e.inventory.prepareGrant.bind(e.inventory) }),
103
+ systemAccount: i(s.systemAccount ?? "shop"),
104
+ maxOrders: f(s.maxOrders ?? 1e4, 1, 1e5),
105
+ maxAuditRows: f(s.maxAuditRows ?? 1e4, 1, 1e5),
106
+ now: p
107
+ });
108
+ }, U = (e, o) => {
109
+ let b = H(o), x = () => f(b.now(), 0, 864e13), S = (e, t) => M("esh_", e, t), C = async (t) => {
110
+ await e.insertIgnore(y.tableName, {
111
+ id: M("est_", t),
112
+ tenantId: t,
113
+ admission: 0
114
+ }, { conflictColumns: ["id"] });
115
+ }, k = async (e, n) => {
116
+ let r = M("est_", n);
117
+ if (await e.updateMany(y.tableName, { admission: 0 }, { where: T("id", r) }) !== 1) throw t("unavailable");
118
+ let i = (await e.query(E(y).where(T("id", r)).limit(1).descriptor))[0];
119
+ if (!i || i.tenantId !== n) throw t("invalid_record");
120
+ }, N = async (t, n) => {
121
+ await e.insertIgnore(v.tableName, {
122
+ id: S(t, n),
123
+ tenantId: t,
124
+ ownerId: n,
125
+ erased: !1,
126
+ admission: 0
127
+ }, { conflictColumns: ["id"] });
128
+ }, U = async (e, n, r, i = !1) => {
129
+ let a = S(n, r);
130
+ if (await e.updateMany(v.tableName, { admission: 0 }, { where: T("id", a) }) !== 1) throw t("unavailable");
131
+ let o = (await e.query(E(v).where(T("id", a)).limit(1).descriptor))[0];
132
+ if (!o || o.tenantId !== n) throw t("invalid_record");
133
+ if (o.erased === !0) {
134
+ if (i && o.ownerId === null) return;
135
+ throw t("erased");
136
+ }
137
+ if (o.ownerId !== r || o.erased !== !1) throw t("invalid_record");
138
+ }, W = async (e, n, r, i) => {
139
+ let a = (await e.query(E(_).where(T("id", i)).limit(1).descriptor))[0];
140
+ if (a && (a.tenantId !== n || a.ownerKey !== S(n, r) || a.ownerId !== r)) throw t("invalid_record");
141
+ return a;
142
+ }, G = (e) => {
143
+ if (e.state !== "fulfilled" || e.intent === null || e.digest === null) throw t("invalid_record");
144
+ let n = r(e.intent, [
145
+ "request",
146
+ "offer",
147
+ "currencies",
148
+ "realMoney",
149
+ "rulesVersion",
150
+ "price",
151
+ "adjustments",
152
+ "quotedAt",
153
+ "at",
154
+ "counters"
155
+ ], "invalid_record");
156
+ i(n.rulesVersion, "invalid_record");
157
+ let o = r(n.request, [
158
+ "tenantId",
159
+ "ownerId",
160
+ "offerId",
161
+ "offerVersion",
162
+ "offerDigest",
163
+ "requestId",
164
+ "currency",
165
+ "qty"
166
+ ], "invalid_record"), { tenantId: h, ownerId: g, ..._ } = o, v = d({
167
+ offerId: _.offerId,
168
+ offerVersion: _.offerVersion,
169
+ offerDigest: _.offerDigest,
170
+ requestId: _.requestId,
171
+ currency: _.currency === null ? void 0 : _.currency,
172
+ qty: _.qty
173
+ }), y = a(n.currencies), b = u(n.offer, y, n.realMoney), x = c(s(b.price, y, n.realMoney, n.adjustments), () => n.price), C = l(e.receipt), w = p(x, v.currency, v.qty), T = f(n.quotedAt, 0, 864e13);
174
+ if (A(o) !== e.digest || M("eso_", i(h), i(g), v.requestId) !== e.id || e.tenantId !== h || e.ownerId !== g || e.ownerKey !== S(String(h), String(g)) || v.offerId !== b.id || v.offerVersion !== b.version || v.offerDigest !== j(b, String(n.rulesVersion)) || C.offerVersion !== b.version || C.offerDigest !== v.offerDigest || v.qty > b.maxQuantity || C.orderId !== e.id || C.offerId !== b.id || C.quantity !== v.qty || C.at !== n.at || T > C.at || b.from !== null && T < b.from || b.until !== null && T >= b.until || L(e.createdAt) > C.at || L(e.fulfilledAt) !== C.at || e.acceptedQty !== C.quantity || m(C.pricePaid) !== m(w) || m(e.counterKeys) !== m(B(String(h), String(e.ownerKey), b.id, T)) || m(n.counters) !== m(e.counterKeys)) throw t("invalid_record");
175
+ let E = [...w.kind === "virtual" && BigInt(w.amount) > 0n ? [{
176
+ currency: w.currency,
177
+ amount: w.amount
178
+ }] : [], ...b.currencies.map((e) => ({
179
+ currency: e.currency,
180
+ amount: (BigInt(e.amount) * BigInt(v.qty)).toString()
181
+ }))];
182
+ if (C.transfers.length !== E.length || C.grants.length !== b.items.length) throw t("invalid_record");
183
+ for (let [n, r] of C.transfers.entries()) if (r.currency !== E[n]?.currency || r.amount !== E[n]?.amount || r.txId !== M("ect_", String(h), M("esr_", String(e.id), "transfer", String(n))) || r.at > C.at) throw t("invalid_record");
184
+ for (let [n, r] of C.grants.entries()) if (r.operationId !== M("ivo_", String(h), "player", String(g), M("esr_", String(e.id), "grant", String(n))) || r.at > C.at || r.changes.reduce((e, t) => e + t.delta, 0) !== b.items[n].qty * v.qty) throw t("invalid_record");
185
+ if ((/* @__PURE__ */ new Set([...C.transfers.map((e) => e.txId), ...C.grants.map((e) => e.operationId)])).size !== C.transfers.length + C.grants.length) throw t("invalid_record");
186
+ return C;
187
+ }, K = async (e, n) => {
188
+ let a = r(n.intent, [
189
+ "request",
190
+ "offer",
191
+ "currencies",
192
+ "realMoney",
193
+ "rulesVersion",
194
+ "price",
195
+ "adjustments",
196
+ "quotedAt",
197
+ "at",
198
+ "counters"
199
+ ], "invalid_record"), o = r(a.offer, [
200
+ "id",
201
+ "version",
202
+ "titleKey",
203
+ "price",
204
+ "items",
205
+ "currencies",
206
+ "from",
207
+ "until",
208
+ "segment",
209
+ "flag",
210
+ "countries",
211
+ "limits",
212
+ "oneTime",
213
+ "maxQuantity"
214
+ ], "invalid_record"), s = M("esf_", String(n.tenantId), i(o.id), i(o.version)), c = (await e.query(E(g).where(T("id", s)).limit(1).descriptor))[0];
215
+ if (!c || c.tenantId !== n.tenantId || c.offerId !== o.id || c.version !== o.version || c.rulesVersion !== a.rulesVersion || m(c.definition) !== m(o)) throw t("invalid_record");
216
+ }, q = async (e, n, i) => {
217
+ if (n.from !== null && i < n.from || n.until !== null && i >= n.until) return;
218
+ let a = b.contextSource === void 0 ? {
219
+ eligible: !0,
220
+ adjustments: []
221
+ } : r(await I(b.contextSource.read(Object.freeze({
222
+ subject: e,
223
+ offer: n,
224
+ at: i
225
+ }))), ["eligible", "adjustments"]);
226
+ if (typeof a.eligible != "boolean") throw t("invalid_input");
227
+ if (!a.eligible) return;
228
+ let o = s(n.price, b.currencies, b.realMoney, a.adjustments);
229
+ return Object.freeze({
230
+ offer: n,
231
+ price: c(o, b.priceResolver),
232
+ adjustments: o.adjustments
233
+ });
234
+ }, J = async (n, r, i, a) => e.transactional(async (e) => {
235
+ await U(e, n, r);
236
+ let o = await W(e, n, r, i);
237
+ if (o?.state === "fulfilled") {
238
+ if (o.digest !== a) throw t("conflict");
239
+ return await K(e, o), G(o);
240
+ }
241
+ if (o?.state === "erased") throw t("erased");
242
+ }), Y = (n, r) => F(() => {
243
+ let i = R(n), a = d(r), o = i.tenantId, s = i.id, c = Object.freeze({
244
+ tenantId: o,
245
+ ownerId: s,
246
+ ...a
247
+ }), u = A(c), v = M("eso_", o, s, a.requestId);
248
+ return P(async () => {
249
+ await C(o), await N(o, s);
250
+ let n = await J(o, s, v, u);
251
+ if (n) return n;
252
+ let r = b.offers.find((e) => e.id === a.offerId);
253
+ if (!r) throw t("not_found");
254
+ if (a.offerVersion !== r.version || a.offerDigest !== j(r, b.version)) throw t("conflict");
255
+ if (a.qty > r.maxQuantity) throw t("limit_exceeded");
256
+ let d = x(), y = await q(i, r, d);
257
+ if (!y) throw t("forbidden");
258
+ let A = p(y.price, a.currency, a.qty), P = B(o, S(o, s), r.id, d);
259
+ await e.transactional(async (e) => {
260
+ await k(e, o), await U(e, o, s);
261
+ let n = await W(e, o, s, v);
262
+ if (n) {
263
+ if (n.state === "fulfilled" && n.digest !== u) throw t("conflict");
264
+ if (n.state === "erased") throw t("erased");
265
+ } else {
266
+ if ((await e.query(E(_).where(w(T("tenantId", o), T("ownerKey", S(o, s)))).limit(b.maxOrders + 1).descriptor)).length >= b.maxOrders) throw t("limit_exceeded");
267
+ await e.insert(_.tableName, {
268
+ id: v,
269
+ tenantId: o,
270
+ ownerId: s,
271
+ ownerKey: S(o, s),
272
+ state: "pending",
273
+ digest: null,
274
+ intent: null,
275
+ receipt: null,
276
+ acceptedQty: null,
277
+ counterKeys: null,
278
+ admission: 0,
279
+ createdAt: new Date(d),
280
+ fulfilledAt: null
281
+ });
282
+ }
283
+ });
284
+ let F = M("esf_", o, r.id, r.version), R = {
285
+ id: F,
286
+ tenantId: o,
287
+ offerId: r.id,
288
+ version: r.version,
289
+ rulesVersion: b.version,
290
+ definition: r
291
+ };
292
+ await e.insertIgnore(g.tableName, R, { conflictColumns: ["id"] });
293
+ for (let t of P) await e.insertIgnore(h.tableName, {
294
+ ...t,
295
+ tenantId: o,
296
+ units: 0,
297
+ admission: 0
298
+ }, { conflictColumns: ["id"] });
299
+ let H = [];
300
+ H.push(D(e, async (e) => {
301
+ if (await k(e, o), await U(e, o, s), await e.updateMany(_.tableName, { admission: 0 }, { where: T("id", v) }) !== 1) throw t("unavailable");
302
+ let n = await W(e, o, s, v);
303
+ if (n?.state === "fulfilled") throw n.digest === u ? (await K(e, n), G(n), new V()) : t("conflict");
304
+ if (!n || n.state !== "pending" || n.digest !== null || n.intent !== null || n.receipt !== null || n.acceptedQty !== null || n.counterKeys !== null || n.fulfilledAt !== null || L(n.createdAt) > d) throw t("invalid_record");
305
+ let i = (await e.query(E(g).where(T("id", F)).limit(1).descriptor))[0];
306
+ if (!i || m(i) !== m(R)) throw t("conflict");
307
+ for (let n of P) {
308
+ if (await e.updateMany(h.tableName, { admission: 0 }, { where: T("id", n.id) }) !== 1) throw t("unavailable");
309
+ let i = (await e.query(E(h).where(T("id", n.id)).limit(1).descriptor))[0];
310
+ if (!i || i.tenantId !== o || [
311
+ "offerId",
312
+ "scope",
313
+ "ownerKey",
314
+ "day"
315
+ ].some((e) => i[e] !== n[e])) throw t("invalid_record");
316
+ let s = f(i.units, 0, 2147483647) + a.qty, c = n.scope === "global" ? r.limits.global : n.scope === "player" ? r.limits.perPlayer : r.limits.perDay;
317
+ if (s > 2147483647 || c !== null && s > c) throw t("limit_exceeded");
318
+ await e.update(h.tableName, n.id, { units: s });
319
+ }
320
+ return null;
321
+ }));
322
+ let Y = [...A.kind === "virtual" && BigInt(A.amount) > 0n ? [{
323
+ currency: A.currency,
324
+ amount: A.amount,
325
+ from: {
326
+ kind: "wallet",
327
+ ownerKind: "player",
328
+ ownerId: s
329
+ },
330
+ to: {
331
+ kind: "system",
332
+ id: b.systemAccount
333
+ }
334
+ }] : [], ...r.currencies.map((e) => ({
335
+ currency: e.currency,
336
+ amount: (BigInt(e.amount) * BigInt(a.qty)).toString(),
337
+ from: {
338
+ kind: "system",
339
+ id: b.systemAccount
340
+ },
341
+ to: {
342
+ kind: "wallet",
343
+ ownerKind: "player",
344
+ ownerId: s
345
+ }
346
+ }))];
347
+ for (let [e, t] of Y.entries()) H.push(await I(b.economy.prepareTransfer(z, {
348
+ tenantId: o,
349
+ requestId: M("esr_", v, "transfer", String(e)),
350
+ ...t,
351
+ reason: "shop.purchase",
352
+ ref: {
353
+ kind: "order",
354
+ id: v
355
+ }
356
+ })));
357
+ for (let [e, n] of r.items.entries()) {
358
+ if (!b.inventory) throw t("unavailable");
359
+ H.push(await I(b.inventory.prepareGrant(z, {
360
+ tenantId: o,
361
+ owner: {
362
+ ownerKind: "player",
363
+ ownerId: s
364
+ },
365
+ requestId: M("esr_", v, "grant", String(e)),
366
+ itemId: n.itemId,
367
+ qty: n.qty * a.qty,
368
+ reason: "shop.purchase",
369
+ ref: {
370
+ kind: "order",
371
+ id: v
372
+ }
373
+ })));
374
+ }
375
+ let X = x();
376
+ if (X < d) throw t("invalid_record");
377
+ let Z = O(e, H, async (e, n) => {
378
+ let i = n.slice(1, Y.length + 1), f = n.slice(Y.length + 1), p = l({
379
+ orderId: v,
380
+ offerId: r.id,
381
+ offerVersion: r.version,
382
+ offerDigest: a.offerDigest,
383
+ quantity: a.qty,
384
+ at: X,
385
+ pricePaid: A,
386
+ transfers: i,
387
+ grants: f
388
+ }), m = {
389
+ request: c,
390
+ offer: r,
391
+ currencies: b.currencies,
392
+ realMoney: b.realMoney,
393
+ rulesVersion: b.version,
394
+ price: y.price,
395
+ adjustments: y.adjustments,
396
+ quotedAt: d,
397
+ at: X,
398
+ counters: P
399
+ };
400
+ await e.update(_.tableName, v, {
401
+ state: "fulfilled",
402
+ digest: u,
403
+ intent: m,
404
+ receipt: p,
405
+ acceptedQty: a.qty,
406
+ counterKeys: P,
407
+ fulfilledAt: new Date(X)
408
+ });
409
+ let h = await W(e, o, s, v);
410
+ if (!h) throw t("invalid_record");
411
+ return G(h);
412
+ });
413
+ try {
414
+ return (await ee(e, [Z]))[0];
415
+ } catch (e) {
416
+ if (e instanceof V) {
417
+ let e = await J(o, s, v, u);
418
+ if (e) return e;
419
+ }
420
+ throw e;
421
+ }
422
+ });
423
+ }), X = (n, r) => F(() => {
424
+ let i = R(n), a = d(r), o = i.tenantId, s = i.id, c = A({
425
+ tenantId: o,
426
+ ownerId: s,
427
+ ...a
428
+ }), l = M("eso_", o, s, a.requestId);
429
+ return P(() => e.transactional(async (e) => {
430
+ let n = async () => {
431
+ let n = (await e.query(E(v).where(T("id", S(o, s))).limit(1).descriptor))[0];
432
+ if (n && n.erased === !0) throw t("erased");
433
+ if (n && (n.tenantId !== o || n.ownerId !== s || n.erased !== !1)) throw t("invalid_record");
434
+ return n;
435
+ }, r = await n(), i = await W(e, o, s, l);
436
+ if (i && !r) throw t("invalid_record");
437
+ if (!i) return await n(), Object.freeze({
438
+ requestId: a.requestId,
439
+ state: "not-observed"
440
+ });
441
+ if (i.state === "erased") throw t("erased");
442
+ if (i.state === "fulfilled") {
443
+ if (i.digest !== c) throw t("conflict");
444
+ await K(e, i);
445
+ let r = G(i);
446
+ return await n(), Object.freeze({
447
+ requestId: a.requestId,
448
+ state: "fulfilled",
449
+ receipt: r
450
+ });
451
+ }
452
+ if (i.state !== "pending" || i.digest !== null || i.intent !== null || i.receipt !== null || i.acceptedQty !== null || i.counterKeys !== null || i.fulfilledAt !== null) throw t("invalid_record");
453
+ return L(i.createdAt), await n(), Object.freeze({
454
+ requestId: a.requestId,
455
+ state: "pending"
456
+ });
457
+ }));
458
+ }), Z = (n) => F(() => {
459
+ let r = R(n);
460
+ return P(async () => {
461
+ let n = (await e.query(E(v).where(T("id", S(r.tenantId, r.id))).limit(1).descriptor))[0];
462
+ if (n && (n.erased === !0 || n.ownerId !== r.id || n.tenantId !== r.tenantId)) throw t("erased");
463
+ let i = x(), a = [];
464
+ for (let e of b.offers) {
465
+ let t = await q(r, e, i);
466
+ t && a.push(Object.freeze({
467
+ offer: e,
468
+ offerDigest: j(e, b.version),
469
+ price: t.price
470
+ }));
471
+ }
472
+ return Object.freeze(a);
473
+ });
474
+ }), Q = (n, a) => F(() => {
475
+ let o = r(n, [
476
+ "tenantId",
477
+ "subjectId",
478
+ "kind"
479
+ ]), s = i(o.tenantId), c = i(o.subjectId);
480
+ if (o.kind !== "user" && o.kind !== "guest") throw t("invalid_input");
481
+ return P(async () => (await C(s), await N(s, c), e.transactional(async (e) => {
482
+ await k(e, s), await U(e, s, c, !0);
483
+ let n = await e.query(E(_).where(w(T("tenantId", s), T("ownerKey", S(s, c)))).orderBy("id", "asc").limit(b.maxOrders + 1).descriptor);
484
+ if (n.length > b.maxOrders) throw t("limit_exceeded");
485
+ return a(e, s, c, n);
486
+ })));
487
+ }), te = (e) => Q(e, async (e, n, r, i) => {
488
+ let a = [];
489
+ for (let n of i) {
490
+ if (n.state === "fulfilled") await K(e, n), G(n);
491
+ else if (n.state !== "pending" || n.receipt !== null || n.intent !== null || n.digest !== null || n.acceptedQty !== null || n.counterKeys !== null) throw t("invalid_record");
492
+ a.push(Object.freeze({
493
+ id: n.id,
494
+ state: n.state,
495
+ createdAt: L(n.createdAt),
496
+ fulfilledAt: n.fulfilledAt === null ? null : L(n.fulfilledAt),
497
+ intent: n.intent,
498
+ receipt: n.receipt
499
+ }));
500
+ }
501
+ return Object.freeze({ orders: Object.freeze(a) });
502
+ }), ne = (e) => Q(e, async (e, t, i, a) => {
503
+ for (let t of a) {
504
+ t.state === "fulfilled" && (await K(e, t), G(t));
505
+ let i = n(t.counterKeys ?? [], 3, "invalid_record").filter((e) => r(e, [
506
+ "id",
507
+ "offerId",
508
+ "scope",
509
+ "ownerKey",
510
+ "day"
511
+ ], "invalid_record").scope === "global");
512
+ await e.update(_.tableName, String(t.id), {
513
+ ownerId: null,
514
+ ownerKey: null,
515
+ state: "erased",
516
+ digest: null,
517
+ intent: null,
518
+ receipt: null,
519
+ counterKeys: t.acceptedQty === null ? null : i
520
+ });
521
+ }
522
+ await e.deleteMany(h.tableName, { where: w(T("tenantId", t), T("ownerKey", S(t, i))) }), await e.update(v.tableName, S(t, i), {
523
+ ownerId: null,
524
+ erased: !0
525
+ });
526
+ }), $ = (a) => (o, s) => F(() => {
527
+ let c = structuredClone(o), l = i(s);
528
+ if (c.type !== "system") throw t("forbidden");
529
+ return P(async () => (await C(l), e.transactional(async (e) => {
530
+ await k(e, l);
531
+ let o = await e.query(E(_).where(T("tenantId", l)).orderBy("id", "asc").limit(b.maxAuditRows + 1).descriptor), s = await e.query(E(h).where(T("tenantId", l)).orderBy("id", "asc").limit(b.maxAuditRows + 1).descriptor);
532
+ if (o.length > b.maxAuditRows || s.length > b.maxAuditRows) throw t("limit_exceeded");
533
+ for (let e of s) {
534
+ let n = i(e.id), r = i(e.offerId), a = e.ownerKey, o = e.day, s;
535
+ if (e.scope === "global" && a === null && o === null) s = M("esc_", l, r, "global");
536
+ else if (e.scope === "player" && typeof a == "string" && o === null) s = M("esc_", l, r, "player", i(a));
537
+ else if (e.scope === "day" && typeof a == "string") s = M("esc_", l, r, "day", i(a), String(f(o, 0, 1e8)));
538
+ else throw t("invalid_record");
539
+ if (n !== s || e.tenantId !== l) throw t("invalid_record");
540
+ f(e.units, 0, 2147483647);
541
+ }
542
+ let c = /* @__PURE__ */ new Map(), u = 0;
543
+ for (let a of o) {
544
+ if (a.state === "pending") {
545
+ if (a.acceptedQty !== null || a.counterKeys !== null || a.intent !== null || a.receipt !== null || a.digest !== null || a.fulfilledAt !== null) throw t("invalid_record");
546
+ continue;
547
+ }
548
+ if (a.state === "fulfilled") await K(e, a), G(a);
549
+ else if (a.state !== "erased" || a.ownerId !== null || a.ownerKey !== null || a.intent !== null || a.receipt !== null || a.digest !== null) throw t("invalid_record");
550
+ if (a.acceptedQty === null) {
551
+ if (a.counterKeys !== null || a.fulfilledAt !== null) throw t("invalid_record");
552
+ continue;
553
+ }
554
+ let o = f(a.acceptedQty, 1, 1e3), s = a.state === "fulfilled" ? f(r(a.intent, [
555
+ "request",
556
+ "offer",
557
+ "currencies",
558
+ "realMoney",
559
+ "rulesVersion",
560
+ "price",
561
+ "adjustments",
562
+ "quotedAt",
563
+ "at",
564
+ "counters"
565
+ ], "invalid_record").quotedAt, 0, 864e13) : L(a.fulfilledAt), d = n(a.counterKeys, 3, "invalid_record");
566
+ if (u++, d.length !== (a.state === "erased" ? 1 : 3)) throw t("invalid_record");
567
+ let p = /* @__PURE__ */ new Set();
568
+ for (let e of d) {
569
+ let n = r(e, [
570
+ "id",
571
+ "offerId",
572
+ "scope",
573
+ "ownerKey",
574
+ "day"
575
+ ], "invalid_record"), u = i(n.id), d = i(n.offerId), f = B(l, String(a.ownerKey), d, s).find((e) => e.id === u);
576
+ if (!f || p.has(u) || m(f) !== m(n) || a.state === "erased" && f.scope !== "global") throw t("invalid_record");
577
+ p.add(u);
578
+ let h = (c.get(u)?.units ?? 0) + o;
579
+ if (h > 2147483647) throw t("limit_exceeded");
580
+ c.set(u, {
581
+ ...f,
582
+ units: h
583
+ });
584
+ }
585
+ }
586
+ let d = s.every((e) => {
587
+ let t = c.get(String(e.id));
588
+ return t ? e.units === t.units && [
589
+ "offerId",
590
+ "scope",
591
+ "ownerKey",
592
+ "day"
593
+ ].every((n) => e[n] === t[n]) : e.units === 0;
594
+ }) && [...c.keys()].every((e) => s.some((t) => t.id === e));
595
+ if (a && !d) {
596
+ for (let t of c.values()) s.find((e) => e.id === t.id) ? await e.update(h.tableName, t.id, {
597
+ ...t,
598
+ admission: 0
599
+ }) : await e.insert(h.tableName, {
600
+ ...t,
601
+ tenantId: l,
602
+ admission: 0
603
+ });
604
+ for (let t of s) c.has(String(t.id)) || await e.update(h.tableName, String(t.id), { units: 0 });
605
+ }
606
+ return Object.freeze({
607
+ matches: a ? !0 : d,
608
+ acceptedOrders: u,
609
+ counters: c.size
610
+ });
611
+ })));
612
+ });
613
+ return Object.freeze({
614
+ offers: Z,
615
+ buy: Y,
616
+ receipt: X,
617
+ exportSubject: te,
618
+ eraseSubject: ne,
619
+ auditShop: $(!1),
620
+ rebuildShop: $(!0)
621
+ });
622
+ };
623
+ //#endregion
624
+ export { U as dataStoreShop, H as resolveShopStoreOptions, j as shopOfferDigest };
@@ -0,0 +1,63 @@
1
+ import { boolean as e, id as t, integer as n, json as r, table as i, text as a, timestamp as o } from "@voltro/database";
2
+ //#region src/shopTables.entity.ts
3
+ var s = () => a().maxLength(120).externalId().sensitive("pii"), c = i("_voltro_eco_shop_tenants", {
4
+ id: t({ prefix: "est" }),
5
+ tenantId: s(),
6
+ admission: n().serverOnly()
7
+ }).index(["tenantId"]), l = i("_voltro_eco_shop_subjects", {
8
+ id: t({ prefix: "esh" }),
9
+ tenantId: s(),
10
+ ownerId: a().maxLength(120).nullable().externalId().sensitive("pii"),
11
+ erased: e().serverOnly(),
12
+ admission: n().serverOnly()
13
+ }).index(["tenantId", "ownerId"]), u = i("_voltro_eco_offers", {
14
+ id: t({ prefix: "esf" }),
15
+ tenantId: s(),
16
+ offerId: a().maxLength(120).safe(),
17
+ version: a().maxLength(120).safe(),
18
+ rulesVersion: a().maxLength(120).serverOnly(),
19
+ definition: r().serverOnly()
20
+ }).index([
21
+ "tenantId",
22
+ "offerId",
23
+ "version"
24
+ ]), d = i("_voltro_eco_orders", {
25
+ id: t({ prefix: "eso" }),
26
+ tenantId: s(),
27
+ ownerId: a().maxLength(120).nullable().externalId().sensitive("pii"),
28
+ ownerKey: a().maxLength(64).nullable().serverOnly(),
29
+ state: a().maxLength(16).oneOf([
30
+ "pending",
31
+ "fulfilled",
32
+ "erased"
33
+ ]).serverOnly(),
34
+ digest: a().maxLength(64).nullable().serverOnly(),
35
+ intent: r().nullable().serverOnly(),
36
+ receipt: r().nullable().serverOnly(),
37
+ acceptedQty: n().nullable().safe(),
38
+ counterKeys: r().nullable().serverOnly(),
39
+ admission: n().serverOnly(),
40
+ createdAt: o().safe(),
41
+ fulfilledAt: o().nullable().safe()
42
+ }).index(["tenantId", "ownerKey"]).index(["tenantId", "state"]), f = i("_voltro_eco_shop_counters", {
43
+ id: t({ prefix: "esc" }),
44
+ tenantId: s(),
45
+ offerId: a().maxLength(120).safe(),
46
+ scope: a().maxLength(16).oneOf([
47
+ "global",
48
+ "player",
49
+ "day"
50
+ ]).safe(),
51
+ ownerKey: a().maxLength(64).nullable().serverOnly(),
52
+ day: n().nullable().safe(),
53
+ units: n().safe(),
54
+ admission: n().serverOnly()
55
+ }).index(["tenantId", "ownerKey"]).index(["tenantId", "offerId"]), p = [
56
+ c,
57
+ l,
58
+ u,
59
+ d,
60
+ f
61
+ ];
62
+ //#endregion
63
+ export { f as shopCountersTable, u as shopOffersTable, d as shopOrdersTable, l as shopSubjectsTable, p as shopTables, c as shopTenantsTable };