@mpgd/adapter-devvit 0.4.0 → 0.6.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.
@@ -0,0 +1,23 @@
1
+ import type { DevvitDurableOperationStore } from './post-operation.js';
2
+ export interface DevvitRedisSetOptions {
3
+ readonly nx?: boolean;
4
+ readonly xx?: boolean;
5
+ readonly expiration?: Date;
6
+ }
7
+ export interface DevvitRedisTransactionLike {
8
+ multi(): Promise<void>;
9
+ discard(): Promise<unknown>;
10
+ set(key: string, value: string, options?: DevvitRedisSetOptions): Promise<unknown>;
11
+ del(...keys: readonly string[]): Promise<unknown>;
12
+ exec(): Promise<readonly unknown[] | null>;
13
+ unwatch(): Promise<unknown>;
14
+ }
15
+ export interface DevvitRedisLike {
16
+ get(key: string): Promise<string | undefined>;
17
+ set(key: string, value: string, options?: DevvitRedisSetOptions): Promise<string | undefined | null>;
18
+ watch(...keys: readonly string[]): Promise<DevvitRedisTransactionLike>;
19
+ }
20
+ export interface DevvitRedisPostOperationStoreOptions {
21
+ readonly transactionAttempts?: number;
22
+ }
23
+ export declare function createDevvitRedisPostOperationStore(redis: DevvitRedisLike, options?: DevvitRedisPostOperationStoreOptions): DevvitDurableOperationStore;
@@ -0,0 +1,110 @@
1
+ const defaultTransactionAttempts = 3;
2
+ const maximumTransactionAttempts = 32;
3
+ export function createDevvitRedisPostOperationStore(redis, options = {}) {
4
+ const transactionAttempts = normalizeTransactionAttempts(options.transactionAttempts);
5
+ return {
6
+ read(key) {
7
+ return redis.get(key);
8
+ },
9
+ async create(key, value) {
10
+ return setIfAbsent(redis, key, value);
11
+ },
12
+ async compareAndSet(key, expectedValue, nextValue) {
13
+ return mutateIfValue({
14
+ redis,
15
+ key,
16
+ expectedValue,
17
+ transactionAttempts,
18
+ queueMutation: (transaction) => transaction.set(key, nextValue),
19
+ });
20
+ },
21
+ async createLease(key, token, expiresAt) {
22
+ assertExpirationDate(expiresAt);
23
+ return setIfAbsent(redis, key, token, { expiration: expiresAt });
24
+ },
25
+ async releaseLease(key, token) {
26
+ await mutateIfValue({
27
+ redis,
28
+ key,
29
+ expectedValue: token,
30
+ transactionAttempts,
31
+ queueMutation: (transaction) => transaction.del(key),
32
+ });
33
+ },
34
+ };
35
+ }
36
+ async function setIfAbsent(redis, key, value, options = {}) {
37
+ const result = await redis.set(key, value, {
38
+ ...options,
39
+ nx: true,
40
+ });
41
+ if (result === 'OK') {
42
+ return true;
43
+ }
44
+ // Devvit Redis represents a failed SET NX with an empty/nil response.
45
+ if (result === '' || result === undefined || result === null) {
46
+ return false;
47
+ }
48
+ throw new Error(`Devvit Redis SET NX returned an unsupported response: ${result}`);
49
+ }
50
+ async function mutateIfValue(input) {
51
+ for (let attempt = 0; attempt < input.transactionAttempts; attempt += 1) {
52
+ const transaction = await input.redis.watch(input.key);
53
+ let multiStarted = false;
54
+ try {
55
+ const currentValue = await input.redis.get(input.key);
56
+ if (currentValue !== input.expectedValue) {
57
+ await transaction.unwatch();
58
+ return false;
59
+ }
60
+ await transaction.multi();
61
+ multiStarted = true;
62
+ await input.queueMutation(transaction);
63
+ const results = await transaction.exec();
64
+ if (results === null) {
65
+ continue;
66
+ }
67
+ if (!Array.isArray(results)) {
68
+ throw new Error('Devvit Redis transaction returned an unsupported response.');
69
+ }
70
+ if (results.length > 0) {
71
+ return true;
72
+ }
73
+ }
74
+ catch (error) {
75
+ await bestEffortReset(transaction, multiStarted);
76
+ throw error;
77
+ }
78
+ }
79
+ throw new Error(`Devvit Redis transaction contention exceeded ${String(input.transactionAttempts)} attempts for key: ${input.key}`);
80
+ }
81
+ async function bestEffortReset(transaction, multiStarted) {
82
+ try {
83
+ if (multiStarted) {
84
+ await transaction.discard();
85
+ }
86
+ else {
87
+ await transaction.unwatch();
88
+ }
89
+ }
90
+ catch {
91
+ // Preserve the original Redis failure; this cleanup is best-effort.
92
+ }
93
+ }
94
+ function normalizeTransactionAttempts(value) {
95
+ const transactionAttempts = value ?? defaultTransactionAttempts;
96
+ if (!Number.isSafeInteger(transactionAttempts)
97
+ || transactionAttempts < 1
98
+ || transactionAttempts > maximumTransactionAttempts) {
99
+ throw new TypeError(`transactionAttempts must be a safe integer from 1 to ${String(maximumTransactionAttempts)}.`);
100
+ }
101
+ return transactionAttempts;
102
+ }
103
+ function assertExpirationDate(value) {
104
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime())) {
105
+ throw new TypeError('Devvit Redis lease expiration must be a valid Date.');
106
+ }
107
+ if (value.getTime() <= Date.now()) {
108
+ throw new TypeError('Devvit Redis lease expiration must be in the future.');
109
+ }
110
+ }
@@ -0,0 +1,37 @@
1
+ import { type VerifiedLeaderboardService } from '@mpgd/game-services/verified-leaderboard';
2
+ export interface DevvitVerifiedLeaderboardRedisMember {
3
+ readonly member: string;
4
+ readonly score: number;
5
+ }
6
+ export interface DevvitVerifiedLeaderboardRedisTransactionLike {
7
+ multi(): Promise<void>;
8
+ discard(): Promise<unknown>;
9
+ set(key: string, value: string): Promise<unknown>;
10
+ hSet(key: string, fieldValues: Record<string, string>): Promise<unknown>;
11
+ hDel(key: string, fields: string[]): Promise<unknown>;
12
+ zAdd(key: string, ...members: DevvitVerifiedLeaderboardRedisMember[]): Promise<unknown>;
13
+ zRem(key: string, members: string[]): Promise<unknown>;
14
+ exec(): Promise<readonly unknown[] | null>;
15
+ unwatch(): Promise<unknown>;
16
+ }
17
+ export interface DevvitVerifiedLeaderboardRedisLike {
18
+ get(key: string): Promise<string | undefined>;
19
+ hGet(key: string, field: string): Promise<string | undefined>;
20
+ zRange(key: string, start: number, stop: number): Promise<DevvitVerifiedLeaderboardRedisMember[]>;
21
+ watch(...keys: string[]): Promise<DevvitVerifiedLeaderboardRedisTransactionLike>;
22
+ }
23
+ export interface DevvitRedisVerifiedLeaderboardServiceOptions {
24
+ /** Redis-safe namespace shared by every board created by this provider. */
25
+ readonly keyPrefix?: string;
26
+ /** Maximum optimistic transaction attempts after WATCH contention. */
27
+ readonly transactionAttempts?: number;
28
+ /** Clock used for snapshot generation timestamps. */
29
+ readonly now?: () => string;
30
+ }
31
+ /**
32
+ * Durable Devvit Redis provider for modest verified leaderboards. Writes are
33
+ * fenced with WATCH/MULTI/EXEC and keep the original idempotency response.
34
+ * Reads and writes load retained entries to reproduce the contract's exact
35
+ * JavaScript ordering, including UTF-16 tie breakers and cursor traversal.
36
+ */
37
+ export declare function createDevvitRedisVerifiedLeaderboardService(redis: DevvitVerifiedLeaderboardRedisLike, options?: DevvitRedisVerifiedLeaderboardServiceOptions): VerifiedLeaderboardService;
@@ -0,0 +1,435 @@
1
+ import { assertGetVerifiedLeaderboardSnapshotRequest, assertRecordVerifiedLeaderboardAttemptRequest, assertRecordVerifiedLeaderboardAttemptResponse, assertVerifiedLeaderboardAttempt, assertVerifiedLeaderboardDefinition, assertVerifiedLeaderboardSnapshot, createVerifiedLeaderboardCursor, parseVerifiedLeaderboardCursor, } from '@mpgd/game-services/verified-leaderboard';
2
+ const defaultKeyPrefix = 'mpgd:verified-leaderboard:v1';
3
+ const defaultSnapshotLimit = 10;
4
+ const defaultTransactionAttempts = 3;
5
+ const maximumTransactionAttempts = 32;
6
+ const keyPrefixPattern = /^[A-Za-z0-9:_-]{1,128}$/;
7
+ /**
8
+ * Durable Devvit Redis provider for modest verified leaderboards. Writes are
9
+ * fenced with WATCH/MULTI/EXEC and keep the original idempotency response.
10
+ * Reads and writes load retained entries to reproduce the contract's exact
11
+ * JavaScript ordering, including UTF-16 tie breakers and cursor traversal.
12
+ */
13
+ export function createDevvitRedisVerifiedLeaderboardService(redis, options = {}) {
14
+ const keyPrefix = normalizeKeyPrefix(options.keyPrefix);
15
+ const transactionAttempts = normalizeTransactionAttempts(options.transactionAttempts);
16
+ const now = options.now ?? (() => new Date().toISOString());
17
+ return {
18
+ async recordVerifiedAttempt(input) {
19
+ assertRecordVerifiedLeaderboardAttemptRequest(input);
20
+ const request = cloneRecordRequest(input);
21
+ const keys = await createBoardKeys(keyPrefix, request.definition.leaderboardId);
22
+ const attemptMember = await createDigest(request.attempt.attemptId);
23
+ for (let transactionAttempt = 0; transactionAttempt < transactionAttempts; transactionAttempt += 1) {
24
+ const transaction = await redis.watch(...keys.watched);
25
+ let multiStarted = false;
26
+ try {
27
+ const storedDefinition = await readDefinition(redis, keys);
28
+ const definition = ensureDefinition(storedDefinition, request.definition);
29
+ const existingRaw = await redis.hGet(keys.attempts, attemptMember);
30
+ if (existingRaw !== undefined) {
31
+ const existing = parseStoredAttemptDecision(existingRaw, keys.attempts);
32
+ assertSameAttempt(existing.attempt, request.attempt);
33
+ await transaction.unwatch();
34
+ return cloneRecordResponse(existing.response, true);
35
+ }
36
+ const rankedAttempts = await readRankedAttempts(redis, keys, definition, transactionAttempts);
37
+ assertAvailableAttemptMember(rankedAttempts, attemptMember, request.attempt);
38
+ const retainedAttempt = rankedAttempts.find((candidate) => candidate.attempt.participantId === request.attempt.participantId);
39
+ const shouldRetain = retainedAttempt === undefined
40
+ || shouldReplaceRetainedAttempt(definition, retainedAttempt.attempt, request.attempt);
41
+ const nextRankedAttempts = shouldRetain
42
+ ? replaceRetainedAttempt(rankedAttempts, retainedAttempt, {
43
+ member: attemptMember,
44
+ attempt: request.attempt,
45
+ })
46
+ : rankedAttempts;
47
+ const response = createRecordResponse(definition, request.attempt, nextRankedAttempts);
48
+ await transaction.multi();
49
+ multiStarted = true;
50
+ if (storedDefinition === undefined) {
51
+ await transaction.set(keys.definition, JSON.stringify(definition));
52
+ }
53
+ if (shouldRetain) {
54
+ if (retainedAttempt !== undefined) {
55
+ await transaction.zRem(keys.ranking, [retainedAttempt.member]);
56
+ await transaction.hDel(keys.entries, [retainedAttempt.member]);
57
+ }
58
+ await transaction.zAdd(keys.ranking, {
59
+ member: attemptMember,
60
+ score: redisRankingScore(definition.scoreOrder, request.attempt.score),
61
+ });
62
+ await transaction.hSet(keys.entries, {
63
+ [attemptMember]: serializeRetainedAttempt(request.attempt),
64
+ });
65
+ }
66
+ await transaction.hSet(keys.attempts, {
67
+ [attemptMember]: serializeAttemptDecision(request.attempt, response),
68
+ });
69
+ const results = await transaction.exec();
70
+ if (results === null || (Array.isArray(results) && results.length === 0)) {
71
+ continue;
72
+ }
73
+ if (!Array.isArray(results)) {
74
+ throw new Error('Devvit Redis transaction returned an unsupported response.');
75
+ }
76
+ return response;
77
+ }
78
+ catch (error) {
79
+ await bestEffortReset(transaction, multiStarted);
80
+ throw error;
81
+ }
82
+ }
83
+ throw new Error('Devvit Redis verified leaderboard transaction contention exceeded '
84
+ + `${String(transactionAttempts)} attempts for board: `
85
+ + request.definition.leaderboardId);
86
+ },
87
+ async getSnapshot(input) {
88
+ assertGetVerifiedLeaderboardSnapshotRequest(input);
89
+ const request = {
90
+ leaderboardId: input.leaderboardId,
91
+ ...(input.participantId === undefined ? {} : { participantId: input.participantId }),
92
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
93
+ ...(input.cursor === undefined ? {} : { cursor: input.cursor }),
94
+ };
95
+ const keys = await createBoardKeys(keyPrefix, request.leaderboardId);
96
+ const definition = await readDefinition(redis, keys);
97
+ if (definition === undefined) {
98
+ return undefined;
99
+ }
100
+ const rankedAttempts = await readRankedAttempts(redis, keys, definition, transactionAttempts);
101
+ const rankedEntries = toRankedEntries(rankedAttempts);
102
+ const cursorPosition = request.cursor === undefined
103
+ ? undefined
104
+ : parseVerifiedLeaderboardCursor(request.cursor, definition);
105
+ const firstPageIndex = cursorPosition === undefined
106
+ ? 0
107
+ : rankedEntries.findIndex((entry) => compareEntryToCursor(definition.scoreOrder, entry, cursorPosition) > 0);
108
+ const pageStart = firstPageIndex < 0 ? rankedEntries.length : firstPageIndex;
109
+ const pageEnd = pageStart + (request.limit ?? defaultSnapshotLimit);
110
+ const entries = rankedEntries.slice(pageStart, pageEnd);
111
+ const participantEntry = request.participantId === undefined
112
+ ? undefined
113
+ : rankedEntries.find((entry) => entry.participantId === request.participantId);
114
+ const lastEntry = entries.at(-1);
115
+ const nextCursor = lastEntry !== undefined && pageEnd < rankedEntries.length
116
+ ? createVerifiedLeaderboardCursor(definition, lastEntry)
117
+ : undefined;
118
+ const snapshot = {
119
+ definition: cloneDefinition(definition),
120
+ entries,
121
+ ...(participantEntry === undefined ? {} : { participantEntry }),
122
+ totalParticipants: rankedEntries.length,
123
+ generatedAt: now(),
124
+ ...(nextCursor === undefined ? {} : { nextCursor }),
125
+ };
126
+ assertVerifiedLeaderboardSnapshot(snapshot);
127
+ return snapshot;
128
+ },
129
+ };
130
+ }
131
+ async function createBoardKeys(keyPrefix, leaderboardId) {
132
+ const boardDigest = await createDigest(leaderboardId);
133
+ const base = `${keyPrefix}:${boardDigest}`;
134
+ const keys = {
135
+ definition: `${base}:definition`,
136
+ attempts: `${base}:attempts`,
137
+ entries: `${base}:entries`,
138
+ ranking: `${base}:ranking`,
139
+ };
140
+ return {
141
+ ...keys,
142
+ watched: [keys.definition, keys.attempts, keys.entries, keys.ranking],
143
+ };
144
+ }
145
+ async function createDigest(input) {
146
+ const subtle = globalThis.crypto?.subtle;
147
+ if (subtle === undefined) {
148
+ throw new Error('Web Crypto is required for Devvit Redis leaderboard keys.');
149
+ }
150
+ const bytes = new Uint8Array(input.length * 2);
151
+ for (let index = 0; index < input.length; index += 1) {
152
+ const codeUnit = input.charCodeAt(index);
153
+ bytes[index * 2] = codeUnit >>> 8;
154
+ bytes[index * 2 + 1] = codeUnit & 0xff;
155
+ }
156
+ const digest = new Uint8Array(await subtle.digest('SHA-256', bytes));
157
+ return [...digest]
158
+ .map((value) => value.toString(16).padStart(2, '0'))
159
+ .join('');
160
+ }
161
+ async function readDefinition(redis, keys) {
162
+ const raw = await redis.get(keys.definition);
163
+ if (raw === undefined) {
164
+ return undefined;
165
+ }
166
+ const parsed = parseJson(raw, keys.definition);
167
+ assertVerifiedLeaderboardDefinition(parsed);
168
+ return cloneDefinition(parsed);
169
+ }
170
+ async function readRankedAttempts(redis, keys, definition, readAttempts) {
171
+ for (let attempt = 0; attempt < readAttempts; attempt += 1) {
172
+ const rankedAttempts = await tryReadRankedAttempts(redis, keys, definition);
173
+ if (rankedAttempts !== undefined) {
174
+ return rankedAttempts;
175
+ }
176
+ }
177
+ throw new Error('Devvit Redis retained entries changed during '
178
+ + `${String(readAttempts)} consecutive reads for ${keys.ranking}.`);
179
+ }
180
+ async function tryReadRankedAttempts(redis, keys, definition) {
181
+ const members = await redis.zRange(keys.ranking, 0, -1);
182
+ if (members.length === 0) {
183
+ return [];
184
+ }
185
+ const values = await Promise.all(members.map(({ member }) => redis.hGet(keys.entries, member)));
186
+ const rankedAttempts = [];
187
+ for (const [index, member] of members.entries()) {
188
+ const raw = values[index];
189
+ if (raw === undefined) {
190
+ return undefined;
191
+ }
192
+ const stored = parseStoredRetainedAttempt(raw, keys.entries);
193
+ const expectedScore = redisRankingScore(definition.scoreOrder, stored.attempt.score);
194
+ if (member.score !== expectedScore) {
195
+ throw new Error(`Devvit Redis retained entry score is inconsistent for ${keys.ranking}.`);
196
+ }
197
+ rankedAttempts.push({ member: member.member, attempt: stored.attempt });
198
+ }
199
+ assertUniqueRetainedParticipants(rankedAttempts, keys.entries);
200
+ return rankedAttempts.sort((left, right) => compareAttempts(definition.scoreOrder, left.attempt, right.attempt));
201
+ }
202
+ function ensureDefinition(existing, input) {
203
+ if (existing === undefined) {
204
+ return cloneDefinition(input);
205
+ }
206
+ if (existing.leaderboardId !== input.leaderboardId) {
207
+ throw new Error('Devvit Redis leaderboard key digest collision detected.');
208
+ }
209
+ if (existing.scoreOrder !== input.scoreOrder
210
+ || existing.attemptSelection !== input.attemptSelection) {
211
+ throw new Error(`Leaderboard definition conflict for ${JSON.stringify(input.leaderboardId)}.`);
212
+ }
213
+ return existing;
214
+ }
215
+ function assertAvailableAttemptMember(rankedAttempts, member, attempt) {
216
+ const existing = rankedAttempts.find((candidate) => candidate.member === member);
217
+ if (existing !== undefined && existing.attempt.attemptId !== attempt.attemptId) {
218
+ throw new Error('Devvit Redis attempt key digest collision detected.');
219
+ }
220
+ }
221
+ function assertUniqueRetainedParticipants(rankedAttempts, entriesKey) {
222
+ const participantIds = new Set();
223
+ for (const { attempt } of rankedAttempts) {
224
+ if (participantIds.has(attempt.participantId)) {
225
+ throw new Error(`Devvit Redis contains duplicate retained participants for ${entriesKey}.`);
226
+ }
227
+ participantIds.add(attempt.participantId);
228
+ }
229
+ }
230
+ function replaceRetainedAttempt(rankedAttempts, retainedAttempt, candidate) {
231
+ const remainingAttempts = rankedAttempts.filter((item) => item !== retainedAttempt);
232
+ return [...remainingAttempts, candidate];
233
+ }
234
+ function createRecordResponse(definition, attempted, rankedAttempts) {
235
+ const entry = toRankedEntries([...rankedAttempts].sort((left, right) => compareAttempts(definition.scoreOrder, left.attempt, right.attempt))).find((candidate) => candidate.participantId === attempted.participantId);
236
+ if (entry === undefined) {
237
+ throw new Error('Retained leaderboard entry was not found after recording an attempt.');
238
+ }
239
+ const retained = entry.attemptId === attempted.attemptId;
240
+ const response = {
241
+ recorded: true,
242
+ alreadyProcessed: false,
243
+ retained,
244
+ entry,
245
+ ...(retained ? {} : { reason: 'ATTEMPT_NOT_RETAINED' }),
246
+ };
247
+ assertRecordVerifiedLeaderboardAttemptResponse(response);
248
+ return response;
249
+ }
250
+ function toRankedEntries(rankedAttempts) {
251
+ return rankedAttempts.map(({ attempt }, index) => ({
252
+ rank: index + 1,
253
+ participantId: attempt.participantId,
254
+ ...(attempt.participantLabel === undefined
255
+ ? {}
256
+ : { participantLabel: attempt.participantLabel }),
257
+ attemptId: attempt.attemptId,
258
+ score: attempt.score,
259
+ completedAt: attempt.completedAt,
260
+ }));
261
+ }
262
+ function shouldReplaceRetainedAttempt(definition, retained, candidate) {
263
+ if (definition.attemptSelection === 'first') {
264
+ return compareAttemptChronology(candidate, retained) < 0;
265
+ }
266
+ return compareAttempts(definition.scoreOrder, candidate, retained) < 0;
267
+ }
268
+ function compareAttemptChronology(left, right) {
269
+ const completedAtComparison = Date.parse(left.completedAt) - Date.parse(right.completedAt);
270
+ if (completedAtComparison !== 0) {
271
+ return completedAtComparison;
272
+ }
273
+ return compareOrdinal(left.attemptId, right.attemptId);
274
+ }
275
+ function compareAttempts(scoreOrder, left, right) {
276
+ if (left.score !== right.score) {
277
+ return scoreOrder === 'ascending' ? left.score - right.score : right.score - left.score;
278
+ }
279
+ return compareAttemptChronology(left, right);
280
+ }
281
+ function compareEntryToCursor(scoreOrder, entry, cursor) {
282
+ if (entry.score !== cursor.score) {
283
+ const comparison = entry.score - cursor.score;
284
+ return scoreOrder === 'ascending' ? comparison : -comparison;
285
+ }
286
+ const completedAtComparison = Date.parse(entry.completedAt) - cursor.completedAtMs;
287
+ if (completedAtComparison !== 0) {
288
+ return completedAtComparison;
289
+ }
290
+ return compareOrdinal(entry.attemptId, cursor.attemptId);
291
+ }
292
+ function compareOrdinal(left, right) {
293
+ if (left < right) {
294
+ return -1;
295
+ }
296
+ if (left > right) {
297
+ return 1;
298
+ }
299
+ return 0;
300
+ }
301
+ function redisRankingScore(scoreOrder, score) {
302
+ return scoreOrder === 'ascending' ? score : -score;
303
+ }
304
+ function assertSameAttempt(existing, candidate) {
305
+ if (existing.participantId !== candidate.participantId
306
+ || existing.attemptId !== candidate.attemptId
307
+ || existing.score !== candidate.score
308
+ || Date.parse(existing.completedAt) !== Date.parse(candidate.completedAt)
309
+ || existing.verification.authorityId !== candidate.verification.authorityId
310
+ || existing.verification.evidenceId !== candidate.verification.evidenceId
311
+ || Date.parse(existing.verification.verifiedAt)
312
+ !== Date.parse(candidate.verification.verifiedAt)) {
313
+ throw new Error(`Attempt id conflict for ${JSON.stringify(candidate.attemptId)}.`);
314
+ }
315
+ }
316
+ function serializeAttemptDecision(attempt, response) {
317
+ return JSON.stringify({ version: 1, attempt, response });
318
+ }
319
+ function serializeRetainedAttempt(attempt) {
320
+ return JSON.stringify({ version: 1, attempt });
321
+ }
322
+ function parseStoredAttemptDecision(raw, key) {
323
+ const parsed = parseJson(raw, key);
324
+ assertStoredRecord(parsed, key);
325
+ if (parsed.version !== 1) {
326
+ throw new Error(`Unsupported Devvit Redis record version for ${key}.`);
327
+ }
328
+ assertVerifiedLeaderboardAttempt(parsed.attempt);
329
+ assertRecordVerifiedLeaderboardAttemptResponse(parsed.response);
330
+ return {
331
+ version: 1,
332
+ attempt: cloneAttempt(parsed.attempt),
333
+ response: cloneRecordResponse(parsed.response, parsed.response.alreadyProcessed),
334
+ };
335
+ }
336
+ function parseStoredRetainedAttempt(raw, key) {
337
+ const parsed = parseJson(raw, key);
338
+ assertStoredRecord(parsed, key);
339
+ if (parsed.version !== 1) {
340
+ throw new Error(`Unsupported Devvit Redis record version for ${key}.`);
341
+ }
342
+ assertVerifiedLeaderboardAttempt(parsed.attempt);
343
+ return { version: 1, attempt: cloneAttempt(parsed.attempt) };
344
+ }
345
+ function parseJson(raw, key) {
346
+ try {
347
+ return JSON.parse(raw);
348
+ }
349
+ catch (error) {
350
+ throw new Error(`Invalid Devvit Redis JSON record for ${key}.`, { cause: error });
351
+ }
352
+ }
353
+ function assertStoredRecord(input, key) {
354
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
355
+ throw new Error(`Invalid Devvit Redis record for ${key}.`);
356
+ }
357
+ }
358
+ function cloneRecordRequest(input) {
359
+ return {
360
+ definition: cloneDefinition(input.definition),
361
+ attempt: cloneAttempt(input.attempt),
362
+ };
363
+ }
364
+ function cloneDefinition(input) {
365
+ return {
366
+ leaderboardId: input.leaderboardId,
367
+ scoreOrder: input.scoreOrder,
368
+ attemptSelection: input.attemptSelection,
369
+ };
370
+ }
371
+ function cloneAttempt(input) {
372
+ return {
373
+ participantId: input.participantId,
374
+ ...(input.participantLabel === undefined
375
+ ? {}
376
+ : { participantLabel: input.participantLabel }),
377
+ attemptId: input.attemptId,
378
+ score: input.score,
379
+ completedAt: input.completedAt,
380
+ verification: {
381
+ authorityId: input.verification.authorityId,
382
+ evidenceId: input.verification.evidenceId,
383
+ verifiedAt: input.verification.verifiedAt,
384
+ },
385
+ };
386
+ }
387
+ function cloneRecordResponse(input, alreadyProcessed) {
388
+ const response = {
389
+ recorded: true,
390
+ alreadyProcessed,
391
+ retained: input.retained,
392
+ entry: {
393
+ rank: input.entry.rank,
394
+ participantId: input.entry.participantId,
395
+ ...(input.entry.participantLabel === undefined
396
+ ? {}
397
+ : { participantLabel: input.entry.participantLabel }),
398
+ attemptId: input.entry.attemptId,
399
+ score: input.entry.score,
400
+ completedAt: input.entry.completedAt,
401
+ },
402
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
403
+ };
404
+ assertRecordVerifiedLeaderboardAttemptResponse(response);
405
+ return response;
406
+ }
407
+ async function bestEffortReset(transaction, multiStarted) {
408
+ try {
409
+ if (multiStarted) {
410
+ await transaction.discard();
411
+ }
412
+ else {
413
+ await transaction.unwatch();
414
+ }
415
+ }
416
+ catch {
417
+ // Preserve the original Redis failure; this cleanup is best-effort.
418
+ }
419
+ }
420
+ function normalizeKeyPrefix(value) {
421
+ const keyPrefix = value ?? defaultKeyPrefix;
422
+ if (!keyPrefixPattern.test(keyPrefix)) {
423
+ throw new TypeError('keyPrefix must contain 1 to 128 ASCII letters, digits, colons, underscores, or hyphens.');
424
+ }
425
+ return keyPrefix;
426
+ }
427
+ function normalizeTransactionAttempts(value) {
428
+ const transactionAttempts = value ?? defaultTransactionAttempts;
429
+ if (!Number.isSafeInteger(transactionAttempts)
430
+ || transactionAttempts < 1
431
+ || transactionAttempts > maximumTransactionAttempts) {
432
+ throw new TypeError(`transactionAttempts must be a safe integer from 1 to ${String(maximumTransactionAttempts)}.`);
433
+ }
434
+ return transactionAttempts;
435
+ }
@@ -0,0 +1,17 @@
1
+ export type DevvitSurfaceMode = 'inline' | 'expanded';
2
+ export type DevvitSurfaceResult = 'inline-preview' | 'expanded-game';
3
+ export interface DevvitSurfaceClient {
4
+ getWebViewMode(): DevvitSurfaceMode;
5
+ }
6
+ export interface DevvitSurfaceOptions {
7
+ readonly client: DevvitSurfaceClient;
8
+ readonly mountInlinePreview: () => void | Promise<void>;
9
+ readonly loadExpandedGame: () => void | Promise<void>;
10
+ readonly onModeUnavailable?: (error: unknown) => void;
11
+ }
12
+ /**
13
+ * Starts the light inline surface when Devvit reports inline mode and defers the
14
+ * game bundle until an expanded surface is active. Outside a Devvit host, the
15
+ * expanded game remains available for local browser development.
16
+ */
17
+ export declare function startDevvitSurface(options: DevvitSurfaceOptions): Promise<DevvitSurfaceResult>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Starts the light inline surface when Devvit reports inline mode and defers the
3
+ * game bundle until an expanded surface is active. Outside a Devvit host, the
4
+ * expanded game remains available for local browser development.
5
+ */
6
+ export async function startDevvitSurface(options) {
7
+ let mode;
8
+ try {
9
+ mode = options.client.getWebViewMode();
10
+ }
11
+ catch (error) {
12
+ options.onModeUnavailable?.(error);
13
+ await options.loadExpandedGame();
14
+ return 'expanded-game';
15
+ }
16
+ if (mode === 'inline') {
17
+ await options.mountInlinePreview();
18
+ return 'inline-preview';
19
+ }
20
+ await options.loadExpandedGame();
21
+ return 'expanded-game';
22
+ }
package/dist/web.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { ShareResult } from '@mpgd/platform';
2
+ import { type DevvitSurfaceOptions, type DevvitSurfaceResult } from './surface.js';
3
+ export type { DevvitSurfaceClient, DevvitSurfaceMode, DevvitSurfaceOptions, DevvitSurfaceResult, } from './surface.js';
4
+ export type DevvitWebSurfaceOptions = Omit<DevvitSurfaceOptions, 'client'>;
5
+ export interface DevvitShareSheetOptions {
6
+ readonly data?: string;
7
+ readonly title?: string;
8
+ readonly text?: string;
9
+ }
10
+ export declare function startDevvitWebSurface(options: DevvitWebSurfaceOptions): Promise<DevvitSurfaceResult>;
11
+ export declare function requestDevvitExpandedMode(event: MouseEvent, entry: string): Promise<void>;
12
+ /**
13
+ * Presents Devvit's native share surface without claiming that the user
14
+ * completed sharing. Devvit does not report a completion callback.
15
+ */
16
+ export declare function presentDevvitShareSheet(options: DevvitShareSheetOptions): Promise<ShareResult>;