@stamprally/react 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 +21 -0
- package/dist/index.cjs +240 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +238 -0
- package/dist/index.js.map +1 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nitta-a
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@stamprally/core');
|
|
4
|
+
var react = require('react');
|
|
5
|
+
|
|
6
|
+
// src/useStampRally.ts
|
|
7
|
+
function getServerSnapshot() {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
function toError(error) {
|
|
11
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
12
|
+
}
|
|
13
|
+
function applyOptimisticAcquire(currentState, action) {
|
|
14
|
+
if (currentState === null || currentState.records.some((record) => record.stampId === action.stampId)) {
|
|
15
|
+
return currentState;
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
...currentState,
|
|
19
|
+
records: [...currentState.records, { stampId: action.stampId, acquiredAt: action.acquiredAt }],
|
|
20
|
+
updatedAt: action.acquiredAt
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function useStampRally(client) {
|
|
24
|
+
const subscribe = react.useCallback(
|
|
25
|
+
(onStoreChange) => client.subscribe(() => onStoreChange()),
|
|
26
|
+
[client]
|
|
27
|
+
);
|
|
28
|
+
const getSnapshot = react.useCallback(() => client.getState(), [client]);
|
|
29
|
+
const rawState = react.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
30
|
+
const [clientStatus, setClientStatus] = react.useState(() => ({
|
|
31
|
+
client,
|
|
32
|
+
isInitializing: client.getState() === null
|
|
33
|
+
}));
|
|
34
|
+
const [clientError, setClientError] = react.useState(null);
|
|
35
|
+
const [isPending, startTransition] = react.useTransition();
|
|
36
|
+
const [optimisticState, addOptimisticAcquire] = react.useOptimistic(rawState, applyOptimisticAcquire);
|
|
37
|
+
react.useEffect(() => {
|
|
38
|
+
let active = true;
|
|
39
|
+
setClientError(null);
|
|
40
|
+
if (rawState !== null) {
|
|
41
|
+
setClientStatus({ client, isInitializing: false });
|
|
42
|
+
return () => {
|
|
43
|
+
active = false;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
setClientStatus({ client, isInitializing: true });
|
|
47
|
+
void client.init().catch((initializationError) => {
|
|
48
|
+
if (active) {
|
|
49
|
+
setClientError({ client, value: toError(initializationError) });
|
|
50
|
+
}
|
|
51
|
+
}).finally(() => {
|
|
52
|
+
if (active) {
|
|
53
|
+
setClientStatus({ client, isInitializing: false });
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
return () => {
|
|
57
|
+
active = false;
|
|
58
|
+
};
|
|
59
|
+
}, [client, rawState]);
|
|
60
|
+
const acquire = react.useCallback(
|
|
61
|
+
(stampId, context, now) => {
|
|
62
|
+
const acquiredAt = now ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
63
|
+
setClientError(null);
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
startTransition(async () => {
|
|
66
|
+
addOptimisticAcquire({ stampId, acquiredAt });
|
|
67
|
+
try {
|
|
68
|
+
const result = await client.acquire(stampId, context, acquiredAt);
|
|
69
|
+
if (!result.ok) {
|
|
70
|
+
setClientError({ client, value: result.error });
|
|
71
|
+
}
|
|
72
|
+
resolve(result);
|
|
73
|
+
} catch (acquireError) {
|
|
74
|
+
const normalizedError = toError(acquireError);
|
|
75
|
+
setClientError({ client, value: normalizedError });
|
|
76
|
+
reject(normalizedError);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
},
|
|
81
|
+
[addOptimisticAcquire, client]
|
|
82
|
+
);
|
|
83
|
+
const reset = react.useCallback(
|
|
84
|
+
(now) => {
|
|
85
|
+
setClientError(null);
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
startTransition(async () => {
|
|
88
|
+
try {
|
|
89
|
+
const nextState = now === void 0 ? await client.reset() : await client.reset(now);
|
|
90
|
+
resolve(nextState);
|
|
91
|
+
} catch (resetError) {
|
|
92
|
+
const normalizedError = toError(resetError);
|
|
93
|
+
setClientError({ client, value: normalizedError });
|
|
94
|
+
reject(normalizedError);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
[client]
|
|
100
|
+
);
|
|
101
|
+
const redeem = react.useCallback(
|
|
102
|
+
(rewardId, options = {}) => {
|
|
103
|
+
setClientError(null);
|
|
104
|
+
return new Promise((resolve, reject) => {
|
|
105
|
+
startTransition(async () => {
|
|
106
|
+
const reward = client.getConfig().rewards?.find((item) => item.id === rewardId);
|
|
107
|
+
if (reward === void 0) {
|
|
108
|
+
const result2 = {
|
|
109
|
+
ok: false,
|
|
110
|
+
error: { code: "REWARD_NOT_FOUND", rewardId }
|
|
111
|
+
};
|
|
112
|
+
setClientError({ client, value: result2.error });
|
|
113
|
+
resolve(result2);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const currentState = client.getState();
|
|
117
|
+
const currentRewardState = currentState?.rewards?.find(
|
|
118
|
+
(state) => state.rewardId === rewardId
|
|
119
|
+
);
|
|
120
|
+
if (currentState === null || currentRewardState === void 0) {
|
|
121
|
+
const result2 = {
|
|
122
|
+
ok: false,
|
|
123
|
+
error: { code: "NOT_AVAILABLE", rewardId }
|
|
124
|
+
};
|
|
125
|
+
setClientError({ client, value: result2.error });
|
|
126
|
+
resolve(result2);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const result = core.consumeReward({
|
|
130
|
+
reward,
|
|
131
|
+
currentState: currentRewardState,
|
|
132
|
+
now: (/* @__PURE__ */ new Date()).toISOString(),
|
|
133
|
+
...options.passcode === void 0 ? {} : { inputPasscode: options.passcode },
|
|
134
|
+
...options.staffId === void 0 ? {} : { staffId: options.staffId }
|
|
135
|
+
});
|
|
136
|
+
if (!result.ok) {
|
|
137
|
+
setClientError({ client, value: result.error });
|
|
138
|
+
resolve(result);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (result.value === currentRewardState) {
|
|
142
|
+
resolve(result);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const nextState = {
|
|
146
|
+
...currentState,
|
|
147
|
+
rewards: (currentState.rewards ?? []).map(
|
|
148
|
+
(state) => state.rewardId === rewardId ? result.value : state
|
|
149
|
+
),
|
|
150
|
+
updatedAt: result.value.consumedAt ?? currentState.updatedAt
|
|
151
|
+
};
|
|
152
|
+
try {
|
|
153
|
+
await client.restore(nextState);
|
|
154
|
+
resolve(result);
|
|
155
|
+
} catch (redeemError) {
|
|
156
|
+
const normalizedError = toError(redeemError);
|
|
157
|
+
setClientError({ client, value: normalizedError });
|
|
158
|
+
reject(normalizedError);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
[client]
|
|
164
|
+
);
|
|
165
|
+
const exportRecoveryCode = react.useCallback(() => {
|
|
166
|
+
const state = client.getState();
|
|
167
|
+
if (state === null) {
|
|
168
|
+
throw new Error("Cannot export recovery code before the rally is initialized.");
|
|
169
|
+
}
|
|
170
|
+
return core.exportProgressToken({
|
|
171
|
+
version: 1,
|
|
172
|
+
rallyId: state.rallyId,
|
|
173
|
+
stamps: state.records,
|
|
174
|
+
rewards: state.rewards ?? [],
|
|
175
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
176
|
+
});
|
|
177
|
+
}, [client]);
|
|
178
|
+
const importRecoveryCode = react.useCallback(
|
|
179
|
+
(token) => {
|
|
180
|
+
setClientError(null);
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
startTransition(async () => {
|
|
183
|
+
const config = client.getConfig();
|
|
184
|
+
const snapshot = core.importProgressToken(token, config.id);
|
|
185
|
+
if (snapshot === null) {
|
|
186
|
+
resolve(false);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const stampIds = new Set(config.stamps.map((stamp) => stamp.id));
|
|
190
|
+
const rewardIds = new Set((config.rewards ?? []).map((reward) => reward.id));
|
|
191
|
+
const importedStampIds = /* @__PURE__ */ new Set();
|
|
192
|
+
const importedRewardIds = /* @__PURE__ */ new Set();
|
|
193
|
+
const stamps = snapshot.stamps.filter((record) => {
|
|
194
|
+
if (!stampIds.has(record.stampId) || importedStampIds.has(record.stampId)) return false;
|
|
195
|
+
importedStampIds.add(record.stampId);
|
|
196
|
+
return true;
|
|
197
|
+
});
|
|
198
|
+
const rewards = snapshot.rewards.filter((state) => {
|
|
199
|
+
if (!rewardIds.has(state.rewardId) || importedRewardIds.has(state.rewardId))
|
|
200
|
+
return false;
|
|
201
|
+
importedRewardIds.add(state.rewardId);
|
|
202
|
+
return true;
|
|
203
|
+
});
|
|
204
|
+
try {
|
|
205
|
+
await client.restore({
|
|
206
|
+
rallyId: config.id,
|
|
207
|
+
records: stamps,
|
|
208
|
+
...config.rewards === void 0 && rewards.length === 0 ? {} : { rewards },
|
|
209
|
+
updatedAt: snapshot.exportedAt
|
|
210
|
+
});
|
|
211
|
+
resolve(true);
|
|
212
|
+
} catch (importError) {
|
|
213
|
+
const normalizedError = toError(importError);
|
|
214
|
+
setClientError({ client, value: normalizedError });
|
|
215
|
+
reject(normalizedError);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
},
|
|
220
|
+
[client]
|
|
221
|
+
);
|
|
222
|
+
const isLoading = rawState === null && (clientStatus.client !== client || clientStatus.isInitializing);
|
|
223
|
+
const error = clientError?.client === client ? clientError.value : null;
|
|
224
|
+
return {
|
|
225
|
+
state: optimisticState,
|
|
226
|
+
isLoading,
|
|
227
|
+
isPending,
|
|
228
|
+
error,
|
|
229
|
+
rewardsState: optimisticState?.rewards ?? [],
|
|
230
|
+
acquire,
|
|
231
|
+
reset,
|
|
232
|
+
redeem,
|
|
233
|
+
exportRecoveryCode,
|
|
234
|
+
importRecoveryCode
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
exports.useStampRally = useStampRally;
|
|
239
|
+
//# sourceMappingURL=index.cjs.map
|
|
240
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/useStampRally.ts"],"names":["useCallback","useSyncExternalStore","useState","useTransition","useOptimistic","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;AAAA,cACnB,SAAS,MAAA,CAAO,EAAA;AAAA,cAChB,OAAA,EAAS,MAAA;AAAA,cACT,GAAI,MAAA,CAAO,OAAA,KAAY,KAAA,CAAA,IAAa,OAAA,CAAQ,WAAW,CAAA,GAAI,EAAC,GAAI,EAAE,OAAA,EAAQ;AAAA,cAC1E,WAAW,QAAA,CAAS;AAAA,aACrB,CAAA;AACD,YAAA,OAAA,CAAQ,IAAI,CAAA;AAAA,UACd,SAAS,WAAA,EAAa;AACpB,YAAA,MAAM,eAAA,GAAkB,QAAQ,WAAW,CAAA;AAC3C,YAAA,cAAA,CAAe,EAAE,MAAA,EAAQ,KAAA,EAAO,eAAA,EAAiB,CAAA;AACjD,YAAA,MAAA,CAAO,eAAe,CAAA;AAAA,UACxB;AAAA,QACF,CAAC,CAAA;AAAA,MACH,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,IACA,CAAC,MAAM;AAAA,GACT;AAEA,EAAA,MAAM,YACJ,QAAA,KAAa,IAAA,KAAS,YAAA,CAAa,MAAA,KAAW,UAAU,YAAA,CAAa,cAAA,CAAA;AACvE,EAAA,MAAM,KAAA,GAAQ,WAAA,EAAa,MAAA,KAAW,MAAA,GAAS,YAAY,KAAA,GAAQ,IAAA;AAEnE,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,eAAA;AAAA,IACP,SAAA;AAAA,IACA,SAAA;AAAA,IACA,KAAA;AAAA,IACA,YAAA,EAAc,eAAA,EAAiB,OAAA,IAAW,EAAC;AAAA,IAC3C,OAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,kBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type {\n ConsumeResult,\n ProcessStampValue,\n Result,\n RewardConsumeError,\n RewardState,\n StampError,\n StampRallyClient,\n StampRallyState,\n VerificationContext,\n} from \"@stamprally/core\";\nimport { consumeReward, exportProgressToken, importProgressToken } from \"@stamprally/core\";\nimport {\n useCallback,\n useEffect,\n useOptimistic,\n useState,\n useSyncExternalStore,\n useTransition,\n} from \"react\";\n\ninterface OptimisticAcquire {\n readonly stampId: string;\n readonly acquiredAt: string;\n}\n\ninterface ClientStatus {\n readonly client: StampRallyClient;\n readonly isInitializing: boolean;\n}\n\ninterface ClientError {\n readonly client: StampRallyClient;\n readonly value: StampError | RewardConsumeError | Error;\n}\n\nexport interface RedeemOptions {\n readonly passcode?: string;\n readonly staffId?: string;\n}\n\nexport interface UseStampRallyReturn {\n readonly state: StampRallyState | null;\n readonly isLoading: boolean;\n readonly isPending: boolean;\n readonly error: StampError | RewardConsumeError | Error | null;\n readonly rewardsState: ReadonlyArray<RewardState>;\n readonly acquire: (\n stampId: string,\n context: VerificationContext,\n now?: string,\n ) => Promise<Result<ProcessStampValue, StampError>>;\n readonly reset: (now?: string) => Promise<StampRallyState>;\n readonly redeem: (rewardId: string, options?: RedeemOptions) => Promise<ConsumeResult>;\n readonly exportRecoveryCode: () => string;\n readonly importRecoveryCode: (token: string) => Promise<boolean>;\n}\n\n/** @deprecated Use UseStampRallyReturn instead. */\nexport type UseStampRallyValue = UseStampRallyReturn;\n\nfunction getServerSnapshot(): null {\n return null;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction applyOptimisticAcquire(\n currentState: StampRallyState | null,\n action: OptimisticAcquire,\n): StampRallyState | null {\n if (\n currentState === null ||\n currentState.records.some((record) => record.stampId === action.stampId)\n ) {\n return currentState;\n }\n\n return {\n ...currentState,\n records: [...currentState.records, { stampId: action.stampId, acquiredAt: action.acquiredAt }],\n updatedAt: action.acquiredAt,\n };\n}\n\nexport function useStampRally(client: StampRallyClient): UseStampRallyReturn {\n const subscribe = useCallback(\n (onStoreChange: () => void) => client.subscribe(() => onStoreChange()),\n [client],\n );\n const getSnapshot = useCallback(() => client.getState(), [client]);\n const rawState = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n const [clientStatus, setClientStatus] = useState<ClientStatus>(() => ({\n client,\n isInitializing: client.getState() === null,\n }));\n const [clientError, setClientError] = useState<ClientError | null>(null);\n const [isPending, startTransition] = useTransition();\n const [optimisticState, addOptimisticAcquire] = useOptimistic(rawState, applyOptimisticAcquire);\n\n useEffect(() => {\n let active = true;\n setClientError(null);\n if (rawState !== null) {\n setClientStatus({ client, isInitializing: false });\n return () => {\n active = false;\n };\n }\n\n setClientStatus({ client, isInitializing: true });\n\n void client\n .init()\n .catch((initializationError: unknown) => {\n if (active) {\n setClientError({ client, value: toError(initializationError) });\n }\n })\n .finally(() => {\n if (active) {\n setClientStatus({ client, isInitializing: false });\n }\n });\n\n return () => {\n active = false;\n };\n }, [client, rawState]);\n\n const acquire = useCallback(\n (\n stampId: string,\n context: VerificationContext,\n now?: string,\n ): Promise<Result<ProcessStampValue, StampError>> => {\n const acquiredAt = now ?? new Date().toISOString();\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n addOptimisticAcquire({ stampId, acquiredAt });\n try {\n const result = await client.acquire(stampId, context, acquiredAt);\n if (!result.ok) {\n setClientError({ client, value: result.error });\n }\n resolve(result);\n } catch (acquireError) {\n const normalizedError = toError(acquireError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [addOptimisticAcquire, client],\n );\n\n const reset = useCallback(\n (now?: string): Promise<StampRallyState> => {\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n try {\n const nextState = now === undefined ? await client.reset() : await client.reset(now);\n resolve(nextState);\n } catch (resetError) {\n const normalizedError = toError(resetError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [client],\n );\n\n const redeem = useCallback(\n (rewardId: string, options: RedeemOptions = {}): Promise<ConsumeResult> => {\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n const reward = client.getConfig().rewards?.find((item) => item.id === rewardId);\n if (reward === undefined) {\n const result: ConsumeResult = {\n ok: false,\n error: { code: \"REWARD_NOT_FOUND\", rewardId },\n };\n setClientError({ client, value: result.error });\n resolve(result);\n return;\n }\n\n const currentState = client.getState();\n const currentRewardState = currentState?.rewards?.find(\n (state) => state.rewardId === rewardId,\n );\n if (currentState === null || currentRewardState === undefined) {\n const result: ConsumeResult = {\n ok: false,\n error: { code: \"NOT_AVAILABLE\", rewardId },\n };\n setClientError({ client, value: result.error });\n resolve(result);\n return;\n }\n\n const result = consumeReward({\n reward,\n currentState: currentRewardState,\n now: new Date().toISOString(),\n ...(options.passcode === undefined ? {} : { inputPasscode: options.passcode }),\n ...(options.staffId === undefined ? {} : { staffId: options.staffId }),\n });\n if (!result.ok) {\n setClientError({ client, value: result.error });\n resolve(result);\n return;\n }\n\n if (result.value === currentRewardState) {\n resolve(result);\n return;\n }\n\n const nextState: StampRallyState = {\n ...currentState,\n rewards: (currentState.rewards ?? []).map((state) =>\n state.rewardId === rewardId ? result.value : state,\n ),\n updatedAt: result.value.consumedAt ?? currentState.updatedAt,\n };\n\n try {\n await client.restore(nextState);\n resolve(result);\n } catch (redeemError) {\n const normalizedError = toError(redeemError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [client],\n );\n\n const exportRecoveryCode = useCallback((): string => {\n const state = client.getState();\n if (state === null) {\n throw new Error(\"Cannot export recovery code before the rally is initialized.\");\n }\n\n return exportProgressToken({\n version: 1,\n rallyId: state.rallyId,\n stamps: state.records,\n rewards: state.rewards ?? [],\n exportedAt: new Date().toISOString(),\n });\n }, [client]);\n\n const importRecoveryCode = useCallback(\n (token: string): Promise<boolean> => {\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n const config = client.getConfig();\n const snapshot = importProgressToken(token, config.id);\n if (snapshot === null) {\n resolve(false);\n return;\n }\n\n const stampIds = new Set(config.stamps.map((stamp) => stamp.id));\n const rewardIds = new Set((config.rewards ?? []).map((reward) => reward.id));\n const importedStampIds = new Set<string>();\n const importedRewardIds = new Set<string>();\n const stamps = snapshot.stamps.filter((record) => {\n if (!stampIds.has(record.stampId) || importedStampIds.has(record.stampId)) return false;\n importedStampIds.add(record.stampId);\n return true;\n });\n const rewards = snapshot.rewards.filter((state) => {\n if (!rewardIds.has(state.rewardId) || importedRewardIds.has(state.rewardId))\n return false;\n importedRewardIds.add(state.rewardId);\n return true;\n });\n\n try {\n await client.restore({\n rallyId: config.id,\n records: stamps,\n ...(config.rewards === undefined && rewards.length === 0 ? {} : { rewards }),\n updatedAt: snapshot.exportedAt,\n });\n resolve(true);\n } catch (importError) {\n const normalizedError = toError(importError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [client],\n );\n\n const isLoading =\n rawState === null && (clientStatus.client !== client || clientStatus.isInitializing);\n const error = clientError?.client === client ? clientError.value : null;\n\n return {\n state: optimisticState,\n isLoading,\n isPending,\n error,\n rewardsState: optimisticState?.rewards ?? [],\n acquire,\n reset,\n redeem,\n exportRecoveryCode,\n importRecoveryCode,\n };\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { StampRallyState, StampError, RewardConsumeError, RewardState, VerificationContext, Result, ProcessStampValue, ConsumeResult, StampRallyClient } from '@stamprally/core';
|
|
2
|
+
|
|
3
|
+
interface RedeemOptions {
|
|
4
|
+
readonly passcode?: string;
|
|
5
|
+
readonly staffId?: string;
|
|
6
|
+
}
|
|
7
|
+
interface UseStampRallyReturn {
|
|
8
|
+
readonly state: StampRallyState | null;
|
|
9
|
+
readonly isLoading: boolean;
|
|
10
|
+
readonly isPending: boolean;
|
|
11
|
+
readonly error: StampError | RewardConsumeError | Error | null;
|
|
12
|
+
readonly rewardsState: ReadonlyArray<RewardState>;
|
|
13
|
+
readonly acquire: (stampId: string, context: VerificationContext, now?: string) => Promise<Result<ProcessStampValue, StampError>>;
|
|
14
|
+
readonly reset: (now?: string) => Promise<StampRallyState>;
|
|
15
|
+
readonly redeem: (rewardId: string, options?: RedeemOptions) => Promise<ConsumeResult>;
|
|
16
|
+
readonly exportRecoveryCode: () => string;
|
|
17
|
+
readonly importRecoveryCode: (token: string) => Promise<boolean>;
|
|
18
|
+
}
|
|
19
|
+
/** @deprecated Use UseStampRallyReturn instead. */
|
|
20
|
+
type UseStampRallyValue = UseStampRallyReturn;
|
|
21
|
+
declare function useStampRally(client: StampRallyClient): UseStampRallyReturn;
|
|
22
|
+
|
|
23
|
+
export { type RedeemOptions, type UseStampRallyReturn, type UseStampRallyValue, useStampRally };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { StampRallyState, StampError, RewardConsumeError, RewardState, VerificationContext, Result, ProcessStampValue, ConsumeResult, StampRallyClient } from '@stamprally/core';
|
|
2
|
+
|
|
3
|
+
interface RedeemOptions {
|
|
4
|
+
readonly passcode?: string;
|
|
5
|
+
readonly staffId?: string;
|
|
6
|
+
}
|
|
7
|
+
interface UseStampRallyReturn {
|
|
8
|
+
readonly state: StampRallyState | null;
|
|
9
|
+
readonly isLoading: boolean;
|
|
10
|
+
readonly isPending: boolean;
|
|
11
|
+
readonly error: StampError | RewardConsumeError | Error | null;
|
|
12
|
+
readonly rewardsState: ReadonlyArray<RewardState>;
|
|
13
|
+
readonly acquire: (stampId: string, context: VerificationContext, now?: string) => Promise<Result<ProcessStampValue, StampError>>;
|
|
14
|
+
readonly reset: (now?: string) => Promise<StampRallyState>;
|
|
15
|
+
readonly redeem: (rewardId: string, options?: RedeemOptions) => Promise<ConsumeResult>;
|
|
16
|
+
readonly exportRecoveryCode: () => string;
|
|
17
|
+
readonly importRecoveryCode: (token: string) => Promise<boolean>;
|
|
18
|
+
}
|
|
19
|
+
/** @deprecated Use UseStampRallyReturn instead. */
|
|
20
|
+
type UseStampRallyValue = UseStampRallyReturn;
|
|
21
|
+
declare function useStampRally(client: StampRallyClient): UseStampRallyReturn;
|
|
22
|
+
|
|
23
|
+
export { type RedeemOptions, type UseStampRallyReturn, type UseStampRallyValue, useStampRally };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { consumeReward, exportProgressToken, importProgressToken } from '@stamprally/core';
|
|
2
|
+
import { useCallback, useSyncExternalStore, useState, useTransition, useOptimistic, useEffect } from 'react';
|
|
3
|
+
|
|
4
|
+
// src/useStampRally.ts
|
|
5
|
+
function getServerSnapshot() {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
function toError(error) {
|
|
9
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
10
|
+
}
|
|
11
|
+
function applyOptimisticAcquire(currentState, action) {
|
|
12
|
+
if (currentState === null || currentState.records.some((record) => record.stampId === action.stampId)) {
|
|
13
|
+
return currentState;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
...currentState,
|
|
17
|
+
records: [...currentState.records, { stampId: action.stampId, acquiredAt: action.acquiredAt }],
|
|
18
|
+
updatedAt: action.acquiredAt
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function useStampRally(client) {
|
|
22
|
+
const subscribe = useCallback(
|
|
23
|
+
(onStoreChange) => client.subscribe(() => onStoreChange()),
|
|
24
|
+
[client]
|
|
25
|
+
);
|
|
26
|
+
const getSnapshot = useCallback(() => client.getState(), [client]);
|
|
27
|
+
const rawState = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
28
|
+
const [clientStatus, setClientStatus] = useState(() => ({
|
|
29
|
+
client,
|
|
30
|
+
isInitializing: client.getState() === null
|
|
31
|
+
}));
|
|
32
|
+
const [clientError, setClientError] = useState(null);
|
|
33
|
+
const [isPending, startTransition] = useTransition();
|
|
34
|
+
const [optimisticState, addOptimisticAcquire] = useOptimistic(rawState, applyOptimisticAcquire);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
let active = true;
|
|
37
|
+
setClientError(null);
|
|
38
|
+
if (rawState !== null) {
|
|
39
|
+
setClientStatus({ client, isInitializing: false });
|
|
40
|
+
return () => {
|
|
41
|
+
active = false;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
setClientStatus({ client, isInitializing: true });
|
|
45
|
+
void client.init().catch((initializationError) => {
|
|
46
|
+
if (active) {
|
|
47
|
+
setClientError({ client, value: toError(initializationError) });
|
|
48
|
+
}
|
|
49
|
+
}).finally(() => {
|
|
50
|
+
if (active) {
|
|
51
|
+
setClientStatus({ client, isInitializing: false });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
return () => {
|
|
55
|
+
active = false;
|
|
56
|
+
};
|
|
57
|
+
}, [client, rawState]);
|
|
58
|
+
const acquire = useCallback(
|
|
59
|
+
(stampId, context, now) => {
|
|
60
|
+
const acquiredAt = now ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
61
|
+
setClientError(null);
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
startTransition(async () => {
|
|
64
|
+
addOptimisticAcquire({ stampId, acquiredAt });
|
|
65
|
+
try {
|
|
66
|
+
const result = await client.acquire(stampId, context, acquiredAt);
|
|
67
|
+
if (!result.ok) {
|
|
68
|
+
setClientError({ client, value: result.error });
|
|
69
|
+
}
|
|
70
|
+
resolve(result);
|
|
71
|
+
} catch (acquireError) {
|
|
72
|
+
const normalizedError = toError(acquireError);
|
|
73
|
+
setClientError({ client, value: normalizedError });
|
|
74
|
+
reject(normalizedError);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
[addOptimisticAcquire, client]
|
|
80
|
+
);
|
|
81
|
+
const reset = useCallback(
|
|
82
|
+
(now) => {
|
|
83
|
+
setClientError(null);
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
startTransition(async () => {
|
|
86
|
+
try {
|
|
87
|
+
const nextState = now === void 0 ? await client.reset() : await client.reset(now);
|
|
88
|
+
resolve(nextState);
|
|
89
|
+
} catch (resetError) {
|
|
90
|
+
const normalizedError = toError(resetError);
|
|
91
|
+
setClientError({ client, value: normalizedError });
|
|
92
|
+
reject(normalizedError);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
},
|
|
97
|
+
[client]
|
|
98
|
+
);
|
|
99
|
+
const redeem = useCallback(
|
|
100
|
+
(rewardId, options = {}) => {
|
|
101
|
+
setClientError(null);
|
|
102
|
+
return new Promise((resolve, reject) => {
|
|
103
|
+
startTransition(async () => {
|
|
104
|
+
const reward = client.getConfig().rewards?.find((item) => item.id === rewardId);
|
|
105
|
+
if (reward === void 0) {
|
|
106
|
+
const result2 = {
|
|
107
|
+
ok: false,
|
|
108
|
+
error: { code: "REWARD_NOT_FOUND", rewardId }
|
|
109
|
+
};
|
|
110
|
+
setClientError({ client, value: result2.error });
|
|
111
|
+
resolve(result2);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const currentState = client.getState();
|
|
115
|
+
const currentRewardState = currentState?.rewards?.find(
|
|
116
|
+
(state) => state.rewardId === rewardId
|
|
117
|
+
);
|
|
118
|
+
if (currentState === null || currentRewardState === void 0) {
|
|
119
|
+
const result2 = {
|
|
120
|
+
ok: false,
|
|
121
|
+
error: { code: "NOT_AVAILABLE", rewardId }
|
|
122
|
+
};
|
|
123
|
+
setClientError({ client, value: result2.error });
|
|
124
|
+
resolve(result2);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const result = consumeReward({
|
|
128
|
+
reward,
|
|
129
|
+
currentState: currentRewardState,
|
|
130
|
+
now: (/* @__PURE__ */ new Date()).toISOString(),
|
|
131
|
+
...options.passcode === void 0 ? {} : { inputPasscode: options.passcode },
|
|
132
|
+
...options.staffId === void 0 ? {} : { staffId: options.staffId }
|
|
133
|
+
});
|
|
134
|
+
if (!result.ok) {
|
|
135
|
+
setClientError({ client, value: result.error });
|
|
136
|
+
resolve(result);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (result.value === currentRewardState) {
|
|
140
|
+
resolve(result);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const nextState = {
|
|
144
|
+
...currentState,
|
|
145
|
+
rewards: (currentState.rewards ?? []).map(
|
|
146
|
+
(state) => state.rewardId === rewardId ? result.value : state
|
|
147
|
+
),
|
|
148
|
+
updatedAt: result.value.consumedAt ?? currentState.updatedAt
|
|
149
|
+
};
|
|
150
|
+
try {
|
|
151
|
+
await client.restore(nextState);
|
|
152
|
+
resolve(result);
|
|
153
|
+
} catch (redeemError) {
|
|
154
|
+
const normalizedError = toError(redeemError);
|
|
155
|
+
setClientError({ client, value: normalizedError });
|
|
156
|
+
reject(normalizedError);
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
[client]
|
|
162
|
+
);
|
|
163
|
+
const exportRecoveryCode = useCallback(() => {
|
|
164
|
+
const state = client.getState();
|
|
165
|
+
if (state === null) {
|
|
166
|
+
throw new Error("Cannot export recovery code before the rally is initialized.");
|
|
167
|
+
}
|
|
168
|
+
return exportProgressToken({
|
|
169
|
+
version: 1,
|
|
170
|
+
rallyId: state.rallyId,
|
|
171
|
+
stamps: state.records,
|
|
172
|
+
rewards: state.rewards ?? [],
|
|
173
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
174
|
+
});
|
|
175
|
+
}, [client]);
|
|
176
|
+
const importRecoveryCode = useCallback(
|
|
177
|
+
(token) => {
|
|
178
|
+
setClientError(null);
|
|
179
|
+
return new Promise((resolve, reject) => {
|
|
180
|
+
startTransition(async () => {
|
|
181
|
+
const config = client.getConfig();
|
|
182
|
+
const snapshot = importProgressToken(token, config.id);
|
|
183
|
+
if (snapshot === null) {
|
|
184
|
+
resolve(false);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const stampIds = new Set(config.stamps.map((stamp) => stamp.id));
|
|
188
|
+
const rewardIds = new Set((config.rewards ?? []).map((reward) => reward.id));
|
|
189
|
+
const importedStampIds = /* @__PURE__ */ new Set();
|
|
190
|
+
const importedRewardIds = /* @__PURE__ */ new Set();
|
|
191
|
+
const stamps = snapshot.stamps.filter((record) => {
|
|
192
|
+
if (!stampIds.has(record.stampId) || importedStampIds.has(record.stampId)) return false;
|
|
193
|
+
importedStampIds.add(record.stampId);
|
|
194
|
+
return true;
|
|
195
|
+
});
|
|
196
|
+
const rewards = snapshot.rewards.filter((state) => {
|
|
197
|
+
if (!rewardIds.has(state.rewardId) || importedRewardIds.has(state.rewardId))
|
|
198
|
+
return false;
|
|
199
|
+
importedRewardIds.add(state.rewardId);
|
|
200
|
+
return true;
|
|
201
|
+
});
|
|
202
|
+
try {
|
|
203
|
+
await client.restore({
|
|
204
|
+
rallyId: config.id,
|
|
205
|
+
records: stamps,
|
|
206
|
+
...config.rewards === void 0 && rewards.length === 0 ? {} : { rewards },
|
|
207
|
+
updatedAt: snapshot.exportedAt
|
|
208
|
+
});
|
|
209
|
+
resolve(true);
|
|
210
|
+
} catch (importError) {
|
|
211
|
+
const normalizedError = toError(importError);
|
|
212
|
+
setClientError({ client, value: normalizedError });
|
|
213
|
+
reject(normalizedError);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
[client]
|
|
219
|
+
);
|
|
220
|
+
const isLoading = rawState === null && (clientStatus.client !== client || clientStatus.isInitializing);
|
|
221
|
+
const error = clientError?.client === client ? clientError.value : null;
|
|
222
|
+
return {
|
|
223
|
+
state: optimisticState,
|
|
224
|
+
isLoading,
|
|
225
|
+
isPending,
|
|
226
|
+
error,
|
|
227
|
+
rewardsState: optimisticState?.rewards ?? [],
|
|
228
|
+
acquire,
|
|
229
|
+
reset,
|
|
230
|
+
redeem,
|
|
231
|
+
exportRecoveryCode,
|
|
232
|
+
importRecoveryCode
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export { useStampRally };
|
|
237
|
+
//# sourceMappingURL=index.js.map
|
|
238
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/useStampRally.ts"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EAAS,MAAA;AAAA,cACT,GAAI,MAAA,CAAO,OAAA,KAAY,KAAA,CAAA,IAAa,OAAA,CAAQ,WAAW,CAAA,GAAI,EAAC,GAAI,EAAE,OAAA,EAAQ;AAAA,cAC1E,WAAW,QAAA,CAAS;AAAA,aACrB,CAAA;AACD,YAAA,OAAA,CAAQ,IAAI,CAAA;AAAA,UACd,SAAS,WAAA,EAAa;AACpB,YAAA,MAAM,eAAA,GAAkB,QAAQ,WAAW,CAAA;AAC3C,YAAA,cAAA,CAAe,EAAE,MAAA,EAAQ,KAAA,EAAO,eAAA,EAAiB,CAAA;AACjD,YAAA,MAAA,CAAO,eAAe,CAAA;AAAA,UACxB;AAAA,QACF,CAAC,CAAA;AAAA,MACH,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,IACA,CAAC,MAAM;AAAA,GACT;AAEA,EAAA,MAAM,YACJ,QAAA,KAAa,IAAA,KAAS,YAAA,CAAa,MAAA,KAAW,UAAU,YAAA,CAAa,cAAA,CAAA;AACvE,EAAA,MAAM,KAAA,GAAQ,WAAA,EAAa,MAAA,KAAW,MAAA,GAAS,YAAY,KAAA,GAAQ,IAAA;AAEnE,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,eAAA;AAAA,IACP,SAAA;AAAA,IACA,SAAA;AAAA,IACA,KAAA;AAAA,IACA,YAAA,EAAc,eAAA,EAAiB,OAAA,IAAW,EAAC;AAAA,IAC3C,OAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,kBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type {\n ConsumeResult,\n ProcessStampValue,\n Result,\n RewardConsumeError,\n RewardState,\n StampError,\n StampRallyClient,\n StampRallyState,\n VerificationContext,\n} from \"@stamprally/core\";\nimport { consumeReward, exportProgressToken, importProgressToken } from \"@stamprally/core\";\nimport {\n useCallback,\n useEffect,\n useOptimistic,\n useState,\n useSyncExternalStore,\n useTransition,\n} from \"react\";\n\ninterface OptimisticAcquire {\n readonly stampId: string;\n readonly acquiredAt: string;\n}\n\ninterface ClientStatus {\n readonly client: StampRallyClient;\n readonly isInitializing: boolean;\n}\n\ninterface ClientError {\n readonly client: StampRallyClient;\n readonly value: StampError | RewardConsumeError | Error;\n}\n\nexport interface RedeemOptions {\n readonly passcode?: string;\n readonly staffId?: string;\n}\n\nexport interface UseStampRallyReturn {\n readonly state: StampRallyState | null;\n readonly isLoading: boolean;\n readonly isPending: boolean;\n readonly error: StampError | RewardConsumeError | Error | null;\n readonly rewardsState: ReadonlyArray<RewardState>;\n readonly acquire: (\n stampId: string,\n context: VerificationContext,\n now?: string,\n ) => Promise<Result<ProcessStampValue, StampError>>;\n readonly reset: (now?: string) => Promise<StampRallyState>;\n readonly redeem: (rewardId: string, options?: RedeemOptions) => Promise<ConsumeResult>;\n readonly exportRecoveryCode: () => string;\n readonly importRecoveryCode: (token: string) => Promise<boolean>;\n}\n\n/** @deprecated Use UseStampRallyReturn instead. */\nexport type UseStampRallyValue = UseStampRallyReturn;\n\nfunction getServerSnapshot(): null {\n return null;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction applyOptimisticAcquire(\n currentState: StampRallyState | null,\n action: OptimisticAcquire,\n): StampRallyState | null {\n if (\n currentState === null ||\n currentState.records.some((record) => record.stampId === action.stampId)\n ) {\n return currentState;\n }\n\n return {\n ...currentState,\n records: [...currentState.records, { stampId: action.stampId, acquiredAt: action.acquiredAt }],\n updatedAt: action.acquiredAt,\n };\n}\n\nexport function useStampRally(client: StampRallyClient): UseStampRallyReturn {\n const subscribe = useCallback(\n (onStoreChange: () => void) => client.subscribe(() => onStoreChange()),\n [client],\n );\n const getSnapshot = useCallback(() => client.getState(), [client]);\n const rawState = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n const [clientStatus, setClientStatus] = useState<ClientStatus>(() => ({\n client,\n isInitializing: client.getState() === null,\n }));\n const [clientError, setClientError] = useState<ClientError | null>(null);\n const [isPending, startTransition] = useTransition();\n const [optimisticState, addOptimisticAcquire] = useOptimistic(rawState, applyOptimisticAcquire);\n\n useEffect(() => {\n let active = true;\n setClientError(null);\n if (rawState !== null) {\n setClientStatus({ client, isInitializing: false });\n return () => {\n active = false;\n };\n }\n\n setClientStatus({ client, isInitializing: true });\n\n void client\n .init()\n .catch((initializationError: unknown) => {\n if (active) {\n setClientError({ client, value: toError(initializationError) });\n }\n })\n .finally(() => {\n if (active) {\n setClientStatus({ client, isInitializing: false });\n }\n });\n\n return () => {\n active = false;\n };\n }, [client, rawState]);\n\n const acquire = useCallback(\n (\n stampId: string,\n context: VerificationContext,\n now?: string,\n ): Promise<Result<ProcessStampValue, StampError>> => {\n const acquiredAt = now ?? new Date().toISOString();\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n addOptimisticAcquire({ stampId, acquiredAt });\n try {\n const result = await client.acquire(stampId, context, acquiredAt);\n if (!result.ok) {\n setClientError({ client, value: result.error });\n }\n resolve(result);\n } catch (acquireError) {\n const normalizedError = toError(acquireError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [addOptimisticAcquire, client],\n );\n\n const reset = useCallback(\n (now?: string): Promise<StampRallyState> => {\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n try {\n const nextState = now === undefined ? await client.reset() : await client.reset(now);\n resolve(nextState);\n } catch (resetError) {\n const normalizedError = toError(resetError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [client],\n );\n\n const redeem = useCallback(\n (rewardId: string, options: RedeemOptions = {}): Promise<ConsumeResult> => {\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n const reward = client.getConfig().rewards?.find((item) => item.id === rewardId);\n if (reward === undefined) {\n const result: ConsumeResult = {\n ok: false,\n error: { code: \"REWARD_NOT_FOUND\", rewardId },\n };\n setClientError({ client, value: result.error });\n resolve(result);\n return;\n }\n\n const currentState = client.getState();\n const currentRewardState = currentState?.rewards?.find(\n (state) => state.rewardId === rewardId,\n );\n if (currentState === null || currentRewardState === undefined) {\n const result: ConsumeResult = {\n ok: false,\n error: { code: \"NOT_AVAILABLE\", rewardId },\n };\n setClientError({ client, value: result.error });\n resolve(result);\n return;\n }\n\n const result = consumeReward({\n reward,\n currentState: currentRewardState,\n now: new Date().toISOString(),\n ...(options.passcode === undefined ? {} : { inputPasscode: options.passcode }),\n ...(options.staffId === undefined ? {} : { staffId: options.staffId }),\n });\n if (!result.ok) {\n setClientError({ client, value: result.error });\n resolve(result);\n return;\n }\n\n if (result.value === currentRewardState) {\n resolve(result);\n return;\n }\n\n const nextState: StampRallyState = {\n ...currentState,\n rewards: (currentState.rewards ?? []).map((state) =>\n state.rewardId === rewardId ? result.value : state,\n ),\n updatedAt: result.value.consumedAt ?? currentState.updatedAt,\n };\n\n try {\n await client.restore(nextState);\n resolve(result);\n } catch (redeemError) {\n const normalizedError = toError(redeemError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [client],\n );\n\n const exportRecoveryCode = useCallback((): string => {\n const state = client.getState();\n if (state === null) {\n throw new Error(\"Cannot export recovery code before the rally is initialized.\");\n }\n\n return exportProgressToken({\n version: 1,\n rallyId: state.rallyId,\n stamps: state.records,\n rewards: state.rewards ?? [],\n exportedAt: new Date().toISOString(),\n });\n }, [client]);\n\n const importRecoveryCode = useCallback(\n (token: string): Promise<boolean> => {\n setClientError(null);\n\n return new Promise((resolve, reject) => {\n startTransition(async () => {\n const config = client.getConfig();\n const snapshot = importProgressToken(token, config.id);\n if (snapshot === null) {\n resolve(false);\n return;\n }\n\n const stampIds = new Set(config.stamps.map((stamp) => stamp.id));\n const rewardIds = new Set((config.rewards ?? []).map((reward) => reward.id));\n const importedStampIds = new Set<string>();\n const importedRewardIds = new Set<string>();\n const stamps = snapshot.stamps.filter((record) => {\n if (!stampIds.has(record.stampId) || importedStampIds.has(record.stampId)) return false;\n importedStampIds.add(record.stampId);\n return true;\n });\n const rewards = snapshot.rewards.filter((state) => {\n if (!rewardIds.has(state.rewardId) || importedRewardIds.has(state.rewardId))\n return false;\n importedRewardIds.add(state.rewardId);\n return true;\n });\n\n try {\n await client.restore({\n rallyId: config.id,\n records: stamps,\n ...(config.rewards === undefined && rewards.length === 0 ? {} : { rewards }),\n updatedAt: snapshot.exportedAt,\n });\n resolve(true);\n } catch (importError) {\n const normalizedError = toError(importError);\n setClientError({ client, value: normalizedError });\n reject(normalizedError);\n }\n });\n });\n },\n [client],\n );\n\n const isLoading =\n rawState === null && (clientStatus.client !== client || clientStatus.isInitializing);\n const error = clientError?.client === client ? clientError.value : null;\n\n return {\n state: optimisticState,\n isLoading,\n isPending,\n error,\n rewardsState: optimisticState?.rewards ?? [],\n acquire,\n reset,\n redeem,\n exportRecoveryCode,\n importRecoveryCode,\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@stamprally/react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React hooks for @stamprally/core.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/nitta-a/stamprally-core-app.git",
|
|
9
|
+
"directory": "packages/react"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/nitta-a/stamprally-core-app/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/nitta-a/stamprally-core-app#readme",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"main": "./dist/index.cjs",
|
|
24
|
+
"module": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.js",
|
|
30
|
+
"require": "./dist/index.cjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@stamprally/core": "0.1.0"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": ">=19.0.0 <20.0.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@testing-library/dom": "^10.4.1",
|
|
41
|
+
"@testing-library/react": "^16.3.2",
|
|
42
|
+
"@types/react": "^19.2.18",
|
|
43
|
+
"jsdom": "^30.0.1",
|
|
44
|
+
"react": "^19.2.8",
|
|
45
|
+
"tsup": "^8.5.1",
|
|
46
|
+
"typescript": "^6.0.3",
|
|
47
|
+
"vitest": "^4.1.11"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsup",
|
|
51
|
+
"dev": "tsup --watch",
|
|
52
|
+
"test": "vitest run",
|
|
53
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
54
|
+
}
|
|
55
|
+
}
|