@jskit-ai/rewarded-core 0.2.4 → 0.2.5

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.
@@ -1,18 +1,17 @@
1
- import { normalizeSurfaceId } from "@jskit-ai/kernel/shared/surface/registry";
2
1
  import { checkRouteVisibility } from "@jskit-ai/kernel/shared/support/visibility";
3
- import { resolveScopedApiBasePath } from "@jskit-ai/kernel/shared/surface";
4
2
  import {
5
- createTransportResponseSchema,
3
+ buildTransportResponseSchema,
6
4
  withStandardErrorResponses
7
5
  } from "@jskit-ai/http-runtime/shared/validators/errorResponses";
8
6
  import { routeParamsValidator } from "@jskit-ai/workspaces-core/server/validators/routeParamsValidator";
7
+ import { resolveWorkspaceRoutePath } from "@jskit-ai/workspaces-core/server/support/workspaceRoutePaths";
9
8
  import { buildWorkspaceInputFromRouteParams } from "@jskit-ai/workspaces-core/server/support/workspaceRouteInput";
10
9
  import {
11
10
  ACTION_CURRENT,
12
11
  ACTION_START,
13
12
  ACTION_GRANT,
14
13
  ACTION_CLOSE
15
- } from "./actions.js";
14
+ } from "./rewardedActions.js";
16
15
  import {
17
16
  currentQueryInputValidator,
18
17
  startCommandInputValidator,
@@ -24,9 +23,11 @@ import {
24
23
  closeSessionOutputValidator
25
24
  } from "./inputSchemas.js";
26
25
 
27
- function createWorkflowResponses(outputValidator) {
26
+ const REWARDED_ROUTE_SURFACE = "app";
27
+
28
+ function buildWorkflowResponses(outputValidator) {
28
29
  return withStandardErrorResponses({
29
- 200: createTransportResponseSchema(
30
+ 200: buildTransportResponseSchema(
30
31
  outputValidator.schema.toJsonSchema({
31
32
  mode: outputValidator.mode
32
33
  })
@@ -36,35 +37,25 @@ function createWorkflowResponses(outputValidator) {
36
37
  });
37
38
  }
38
39
 
39
- function registerRoutes(
40
- router,
41
- {
42
- routeOwnershipFilter = "workspace_user",
43
- routeSurface = "app",
44
- routeRelativePath = "rewarded"
45
- } = {}
46
- ) {
47
- if (!router || typeof router.register !== "function") {
48
- throw new Error("registerRoutes requires an HTTP router.");
49
- }
50
- const normalizedRouteSurface = normalizeSurfaceId(routeSurface);
51
- const routeBase = resolveScopedApiBasePath({
52
- routeBase: "/w/:workspaceSlug",
53
- relativePath: routeRelativePath,
54
- strictParams: false
55
- });
56
- const visibility = checkRouteVisibility(routeOwnershipFilter);
40
+ /**
41
+ * Registers the Rewarded gate routes: the app surface's workspace routes under `rewarded`, for the
42
+ * workspace's signed-in user.
43
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
44
+ */
45
+ function registerRewardedRoutes(router) {
46
+ const routeBase = resolveWorkspaceRoutePath("rewarded");
47
+ const visibility = checkRouteVisibility("workspace_user");
57
48
 
58
49
  router.register(
59
50
  "GET",
60
51
  `${routeBase}/current`,
61
52
  {
62
53
  auth: "required",
63
- surface: normalizedRouteSurface,
54
+ surface: REWARDED_ROUTE_SURFACE,
64
55
  visibility,
65
56
  params: routeParamsValidator,
66
57
  query: currentQueryInputValidator,
67
- responses: createWorkflowResponses(currentStateOutputValidator),
58
+ responses: buildWorkflowResponses(currentStateOutputValidator),
68
59
  meta: {
69
60
  tags: ["rewarded"],
70
61
  summary: "Read the current Rewarded gate state."
@@ -87,11 +78,11 @@ function registerRoutes(
87
78
  `${routeBase}/start`,
88
79
  {
89
80
  auth: "required",
90
- surface: normalizedRouteSurface,
81
+ surface: REWARDED_ROUTE_SURFACE,
91
82
  visibility,
92
83
  params: routeParamsValidator,
93
84
  body: startCommandInputValidator,
94
- responses: createWorkflowResponses(startGateOutputValidator),
85
+ responses: buildWorkflowResponses(startGateOutputValidator),
95
86
  meta: {
96
87
  tags: ["rewarded"],
97
88
  summary: "Start a Rewarded watch session."
@@ -114,11 +105,11 @@ function registerRoutes(
114
105
  `${routeBase}/grant`,
115
106
  {
116
107
  auth: "required",
117
- surface: normalizedRouteSurface,
108
+ surface: REWARDED_ROUTE_SURFACE,
118
109
  visibility,
119
110
  params: routeParamsValidator,
120
111
  body: grantCommandInputValidator,
121
- responses: createWorkflowResponses(grantRewardOutputValidator),
112
+ responses: buildWorkflowResponses(grantRewardOutputValidator),
122
113
  meta: {
123
114
  tags: ["rewarded"],
124
115
  summary: "Grant a Rewarded unlock after a rewarded ad completes."
@@ -141,11 +132,11 @@ function registerRoutes(
141
132
  `${routeBase}/close`,
142
133
  {
143
134
  auth: "required",
144
- surface: normalizedRouteSurface,
135
+ surface: REWARDED_ROUTE_SURFACE,
145
136
  visibility,
146
137
  params: routeParamsValidator,
147
138
  body: closeCommandInputValidator,
148
- responses: createWorkflowResponses(closeSessionOutputValidator),
139
+ responses: buildWorkflowResponses(closeSessionOutputValidator),
149
140
  meta: {
150
141
  tags: ["rewarded"],
151
142
  summary: "Close a Rewarded watch session without granting a reward."
@@ -164,4 +155,4 @@ function registerRoutes(
164
155
  );
165
156
  }
166
157
 
167
- export { registerRoutes };
158
+ export { registerRewardedRoutes };
@@ -1,43 +1,34 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
- import { normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
+ import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
  import { simplifyJsonApiDocument } from "@jskit-ai/http-runtime/shared";
4
+ import { resolveActionUser } from "@jskit-ai/users-core/server/resolveActionUser";
4
5
 
5
6
  const REWARDED_SURFACE = "app";
6
7
 
7
- function resolveActionUser(context, input) {
8
- const payload = normalizeObject(input);
9
- const request = context?.requestMeta?.request || null;
10
- return payload.user || request?.user || context?.actor || null;
11
- }
12
-
13
- function normalizeRecordList(document = null) {
8
+ function normalizeRecordList(document) {
14
9
  const simplified = simplifyJsonApiDocument(document);
15
10
  return Array.isArray(simplified) ? simplified.filter(Boolean) : [];
16
11
  }
17
12
 
18
- function normalizeRecord(document = null) {
13
+ function normalizeRecord(document) {
19
14
  const simplified = simplifyJsonApiDocument(document);
20
15
  return simplified && typeof simplified === "object" && !Array.isArray(simplified) ? simplified : null;
21
16
  }
22
17
 
23
- function normalizeGateKey(value = "") {
24
- return normalizeText(value);
18
+ /**
19
+ * Lower-case text, or the fallback when there is none.
20
+ * @param {unknown} value
21
+ * @param {string} fallback
22
+ */
23
+ function normalizeKeyword(value, fallback) {
24
+ return normalizeText(value).toLowerCase() || fallback;
25
25
  }
26
26
 
27
- function normalizeSurface(value = "", { fallback = REWARDED_SURFACE } = {}) {
28
- const normalized = normalizeText(value).toLowerCase();
29
- return normalized || fallback;
30
- }
31
-
32
- function toIsoOrNull(value = null) {
33
- if (!value) {
34
- return null;
35
- }
36
- const date = value instanceof Date ? value : new Date(value);
37
- return Number.isNaN(date.getTime()) ? null : date.toISOString();
27
+ function toIsoOrNull(value) {
28
+ return parseDate(value)?.toISOString() ?? null;
38
29
  }
39
30
 
40
- function parseDate(value = null) {
31
+ function parseDate(value) {
41
32
  if (!value) {
42
33
  return null;
43
34
  }
@@ -63,31 +54,31 @@ function requireActor(context, input) {
63
54
  return actor;
64
55
  }
65
56
 
66
- function requireWorkspaceSlug(input = {}) {
67
- const workspaceSlug = normalizeText(input?.workspaceSlug).toLowerCase();
57
+ function requireWorkspaceSlug(input) {
58
+ const workspaceSlug = normalizeText(input.workspaceSlug).toLowerCase();
68
59
  if (!workspaceSlug) {
69
60
  throw new AppError(400, "workspaceSlug is required.", { code: "rewarded.request.workspaceSlugRequired" });
70
61
  }
71
62
  return workspaceSlug;
72
63
  }
73
64
 
74
- function requireGateKey(input = {}) {
75
- const gateKey = normalizeGateKey(input?.gateKey);
65
+ function requireGateKey(input) {
66
+ const gateKey = normalizeText(input.gateKey);
76
67
  if (!gateKey) {
77
68
  throw new AppError(400, "gateKey is required.", { code: "rewarded.request.gateKeyRequired" });
78
69
  }
79
70
  return gateKey;
80
71
  }
81
72
 
82
- function formatRule(rule = null) {
73
+ function formatRule(rule) {
83
74
  if (!rule) {
84
75
  return null;
85
76
  }
86
77
 
87
78
  return {
88
79
  id: rule.id || null,
89
- gateKey: normalizeGateKey(rule.gateKey),
90
- surface: normalizeSurface(rule.surface, { fallback: REWARDED_SURFACE }),
80
+ gateKey: normalizeText(rule.gateKey),
81
+ surface: normalizeKeyword(rule.surface, REWARDED_SURFACE),
91
82
  enabled: rule.enabled === true,
92
83
  unlockMinutes: Number(rule.unlockMinutes || 0),
93
84
  cooldownMinutes: Number(rule.cooldownMinutes || 0),
@@ -97,30 +88,30 @@ function formatRule(rule = null) {
97
88
  };
98
89
  }
99
90
 
100
- function formatProviderConfig(record = null) {
91
+ function formatProviderConfig(record) {
101
92
  if (!record) {
102
93
  return null;
103
94
  }
104
95
 
105
96
  return {
106
97
  id: record.id || null,
107
- surface: normalizeSurface(record.surface, { fallback: REWARDED_SURFACE }),
98
+ surface: normalizeKeyword(record.surface, REWARDED_SURFACE),
108
99
  enabled: record.enabled === true,
109
100
  placement: normalizeText(record.placement),
110
101
  provider: normalizeText(record.provider)
111
102
  };
112
103
  }
113
104
 
114
- function formatWatchSession(record = null) {
105
+ function formatWatchSession(record) {
115
106
  if (!record) {
116
107
  return null;
117
108
  }
118
109
 
119
110
  return {
120
111
  id: record.id || null,
121
- gateKey: normalizeGateKey(record.gateKey),
112
+ gateKey: normalizeText(record.gateKey),
122
113
  providerConfigId: record.providerConfigId || null,
123
- status: normalizeSurface(record.status, { fallback: "started" }),
114
+ status: normalizeKeyword(record.status, "started"),
124
115
  startedAt: toIsoOrNull(record.startedAt),
125
116
  rewardedAt: toIsoOrNull(record.rewardedAt),
126
117
  completedAt: toIsoOrNull(record.completedAt),
@@ -128,14 +119,14 @@ function formatWatchSession(record = null) {
128
119
  };
129
120
  }
130
121
 
131
- function formatUnlockReceipt(record = null) {
122
+ function formatUnlockReceipt(record) {
132
123
  if (!record) {
133
124
  return null;
134
125
  }
135
126
 
136
127
  return {
137
128
  id: record.id || null,
138
- gateKey: normalizeGateKey(record.gateKey),
129
+ gateKey: normalizeText(record.gateKey),
139
130
  providerConfigId: record.providerConfigId || null,
140
131
  watchSessionId: record.watchSessionId || null,
141
132
  grantedAt: toIsoOrNull(record.grantedAt),
@@ -143,97 +134,86 @@ function formatUnlockReceipt(record = null) {
143
134
  };
144
135
  }
145
136
 
146
- function isFutureDate(value = null, now = new Date()) {
137
+ function isFutureDate(value, now) {
147
138
  const date = parseDate(value);
148
139
  return !!date && date.getTime() > now.getTime();
149
140
  }
150
141
 
142
+ /** @typedef {import("@jskit-ai/crud-core/server/types").CrudRepository} CrudRepository */
143
+ /** @typedef {{ context: object, trx?: import("@jskit-ai/database-runtime/server/types").RuntimeKnexTransaction }} RewardedRepositoryOptions */
144
+
145
+ /**
146
+ * The Rewarded gate workflow over its four resources' repositories and the
147
+ * application's grant policy. Each operation takes the validated input and
148
+ * `{ context }`, the action context.
149
+ * @param {object} dependencies
150
+ * @param {import("./types.js").RewardedGrantPolicy} dependencies.grantPolicy
151
+ * @param {CrudRepository} dependencies.rewardedRulesRepository
152
+ * @param {CrudRepository} dependencies.rewardedProviderConfigsRepository
153
+ * @param {CrudRepository} dependencies.rewardedWatchSessionsRepository
154
+ * @param {CrudRepository} dependencies.rewardedUnlockReceiptsRepository
155
+ */
151
156
  function createService({
152
- authorizeGrant,
157
+ grantPolicy,
153
158
  rewardedRulesRepository,
154
159
  rewardedProviderConfigsRepository,
155
160
  rewardedWatchSessionsRepository,
156
161
  rewardedUnlockReceiptsRepository
157
- } = {}) {
158
- if (typeof authorizeGrant !== "function") {
159
- throw new TypeError("createService requires application authorizeGrant policy.");
160
- }
161
- if (!rewardedRulesRepository) {
162
- throw new TypeError("createService requires rewardedRulesRepository.");
163
- }
164
- if (!rewardedProviderConfigsRepository) {
165
- throw new TypeError("createService requires rewardedProviderConfigsRepository.");
166
- }
167
- if (!rewardedWatchSessionsRepository) {
168
- throw new TypeError("createService requires rewardedWatchSessionsRepository.");
169
- }
170
- if (!rewardedUnlockReceiptsRepository) {
171
- throw new TypeError("createService requires rewardedUnlockReceiptsRepository.");
162
+ }) {
163
+ /**
164
+ * @param {CrudRepository} repository
165
+ * @param {RewardedRepositoryOptions} repositoryOptions
166
+ */
167
+ async function listRecords(repository, query, repositoryOptions) {
168
+ return normalizeRecordList(await repository.queryDocuments(query, repositoryOptions));
172
169
  }
173
170
 
174
- async function queryFirst(repository, query = {}, options = {}) {
175
- const rows = normalizeRecordList(await repository.queryDocuments(query, options));
176
- return rows[0] || null;
171
+ /**
172
+ * @param {CrudRepository} repository
173
+ * @param {RewardedRepositoryOptions} repositoryOptions
174
+ */
175
+ async function queryFirst(repository, query, repositoryOptions) {
176
+ return (await listRecords(repository, query, repositoryOptions))[0] || null;
177
177
  }
178
178
 
179
- async function listRecords(repository, query = {}, options = {}) {
180
- return normalizeRecordList(await repository.queryDocuments(query, options));
181
- }
182
-
183
- async function resolveRule({ gateKey, surface, context, trx }) {
184
- const filters = {
185
- gateKey,
186
- enabled: "true"
187
- };
188
- if (surface) {
189
- filters.surface = surface;
190
- }
179
+ /** @param {RewardedRepositoryOptions} repositoryOptions */
180
+ async function resolveRule(gateKey, repositoryOptions) {
191
181
  return queryFirst(rewardedRulesRepository, {
192
- ...filters,
182
+ gateKey,
183
+ enabled: "true",
184
+ surface: REWARDED_SURFACE,
193
185
  sort: ["-updatedAt"],
194
186
  limit: 1
195
- }, {
196
- context,
197
- trx
198
- });
187
+ }, repositoryOptions);
199
188
  }
200
189
 
201
- async function resolveProviderConfig({ surface, context, trx }) {
190
+ /** @param {RewardedRepositoryOptions} repositoryOptions */
191
+ async function resolveProviderConfig(repositoryOptions) {
202
192
  return queryFirst(rewardedProviderConfigsRepository, {
203
- surface,
193
+ surface: REWARDED_SURFACE,
204
194
  enabled: "true",
205
195
  sort: ["-updatedAt"],
206
196
  limit: 1
207
- }, {
208
- context,
209
- trx
210
- });
197
+ }, repositoryOptions);
211
198
  }
212
199
 
213
- async function resolveUnlockReceipts({ gateKey, context, trx, limit = 25 }) {
200
+ /** @param {RewardedRepositoryOptions} repositoryOptions */
201
+ async function resolveUnlockReceipts(gateKey, repositoryOptions) {
214
202
  return listRecords(rewardedUnlockReceiptsRepository, {
215
203
  gateKey,
216
204
  sort: ["-grantedAt"],
217
- limit
218
- }, {
219
- context,
220
- trx
221
- });
205
+ limit: 25
206
+ }, repositoryOptions);
222
207
  }
223
208
 
224
- async function evaluateGate(input = {}, options = {}) {
225
- requireActor(options?.context || null, input);
209
+ async function evaluateGate(input, context) {
210
+ requireActor(context, input);
226
211
  const workspaceSlug = requireWorkspaceSlug(input);
227
212
  const gateKey = requireGateKey(input);
228
213
  const surface = REWARDED_SURFACE;
229
214
  const now = new Date();
230
215
 
231
- const ruleRecord = await resolveRule({
232
- gateKey,
233
- surface,
234
- context: options?.context || null,
235
- trx: options?.trx || null
236
- });
216
+ const ruleRecord = await resolveRule(gateKey, { context });
237
217
 
238
218
  if (!ruleRecord) {
239
219
  return {
@@ -252,11 +232,7 @@ function createService({
252
232
  };
253
233
  }
254
234
 
255
- const providerConfigRecord = await resolveProviderConfig({
256
- surface,
257
- context: options?.context || null,
258
- trx: options?.trx || null
259
- });
235
+ const providerConfigRecord = await resolveProviderConfig({ context });
260
236
  if (!providerConfigRecord) {
261
237
  return {
262
238
  gateKey,
@@ -276,11 +252,7 @@ function createService({
276
252
 
277
253
  const rule = formatRule(ruleRecord);
278
254
  const providerConfig = formatProviderConfig(providerConfigRecord);
279
- const receipts = await resolveUnlockReceipts({
280
- gateKey,
281
- context: options?.context || null,
282
- trx: options?.trx || null
283
- });
255
+ const receipts = await resolveUnlockReceipts(gateKey, { context });
284
256
  const activeReceiptRecord = receipts.find((entry) => isFutureDate(entry?.unlockedUntil, now)) || null;
285
257
  const activeUnlock = formatUnlockReceipt(activeReceiptRecord);
286
258
 
@@ -379,12 +351,12 @@ function createService({
379
351
  };
380
352
  }
381
353
 
382
- async function getCurrentState(input = {}, options = {}) {
383
- return evaluateGate(input, options);
354
+ async function getCurrentState(input, { context }) {
355
+ return evaluateGate(input, context);
384
356
  }
385
357
 
386
- async function startGate(input = {}, options = {}) {
387
- const state = await evaluateGate(input, options);
358
+ async function startGate(input, { context }) {
359
+ const state = await evaluateGate(input, context);
388
360
  if (!state.enabled || !state.available || !state.blocked) {
389
361
  return {
390
362
  ...state,
@@ -399,10 +371,7 @@ function createService({
399
371
  status: "started",
400
372
  startedAt: new Date().toISOString()
401
373
  },
402
- {
403
- context: options?.context || null,
404
- trx: options?.trx || null
405
- }
374
+ { context }
406
375
  ));
407
376
 
408
377
  return {
@@ -411,26 +380,23 @@ function createService({
411
380
  };
412
381
  }
413
382
 
414
- async function grantReward(input = {}, options = {}) {
415
- requireActor(options?.context || null, input);
383
+ async function grantReward(input, { context }) {
384
+ requireActor(context, input);
416
385
  const workspaceSlug = requireWorkspaceSlug(input);
417
- const sessionId = input?.sessionId == null ? "" : String(input.sessionId).trim();
386
+ const sessionId = input.sessionId == null ? "" : String(input.sessionId).trim();
418
387
  if (!sessionId) {
419
388
  throw new AppError(400, "sessionId is required.", { code: "rewarded.request.sessionIdRequired" });
420
389
  }
421
390
 
422
391
  return rewardedWatchSessionsRepository.withTransaction(async (trx) => {
423
- const sessionRecord = normalizeRecord(await rewardedWatchSessionsRepository.getDocumentById(sessionId, {}, {
424
- context: options?.context || null,
425
- trx
426
- }));
392
+ const sessionRecord = normalizeRecord(await rewardedWatchSessionsRepository.getDocumentById(sessionId, {}, { context, trx }));
427
393
  if (!sessionRecord) {
428
394
  throw new AppError(404, "Watch session not found.", { code: "rewarded.session.notFound" });
429
395
  }
430
396
 
431
- const authorized = await authorizeGrant({
397
+ const authorized = await grantPolicy.authorizeGrant({
432
398
  session: formatWatchSession(sessionRecord),
433
- context: options?.context || null,
399
+ context,
434
400
  trx
435
401
  });
436
402
  if (authorized !== true) {
@@ -445,25 +411,17 @@ function createService({
445
411
  watchSessionId: sessionId,
446
412
  sort: ["-grantedAt"],
447
413
  limit: 1
448
- }, {
449
- context: options?.context || null,
450
- trx
451
- });
414
+ }, { context, trx });
452
415
  return {
453
416
  unlocked: true,
454
417
  workspaceSlug,
455
- gateKey: normalizeGateKey(sessionRecord.gateKey),
418
+ gateKey: normalizeText(sessionRecord.gateKey),
456
419
  unlock: formatUnlockReceipt(receiptRecord),
457
420
  session: formatWatchSession(sessionRecord)
458
421
  };
459
422
  }
460
423
 
461
- const ruleRecord = await resolveRule({
462
- gateKey: normalizeGateKey(sessionRecord.gateKey),
463
- surface: REWARDED_SURFACE,
464
- context: options?.context || null,
465
- trx
466
- });
424
+ const ruleRecord = await resolveRule(normalizeText(sessionRecord.gateKey), { context, trx });
467
425
  if (!ruleRecord) {
468
426
  throw new AppError(409, "No rewarded rule is configured for this session.", {
469
427
  code: "rewarded.session.ruleMissing"
@@ -481,48 +439,39 @@ function createService({
481
439
  rewardedAt: nowIso,
482
440
  completedAt: nowIso
483
441
  },
484
- {
485
- context: options?.context || null,
486
- trx
487
- }
442
+ { context, trx }
488
443
  ));
489
444
 
490
445
  const createdReceipt = normalizeRecord(await rewardedUnlockReceiptsRepository.createDocument(
491
446
  {
492
- gateKey: normalizeGateKey(sessionRecord.gateKey),
447
+ gateKey: normalizeText(sessionRecord.gateKey),
493
448
  providerConfigId: sessionRecord.providerConfigId || null,
494
449
  watchSessionId: sessionId,
495
450
  grantedAt: nowIso,
496
451
  unlockedUntil: unlockedUntil.toISOString()
497
452
  },
498
- {
499
- context: options?.context || null,
500
- trx
501
- }
453
+ { context, trx }
502
454
  ));
503
455
 
504
456
  return {
505
457
  unlocked: true,
506
458
  workspaceSlug,
507
- gateKey: normalizeGateKey(sessionRecord.gateKey),
459
+ gateKey: normalizeText(sessionRecord.gateKey),
508
460
  unlock: formatUnlockReceipt(createdReceipt),
509
461
  session: formatWatchSession(updatedSession)
510
462
  };
511
463
  });
512
464
  }
513
465
 
514
- async function closeSession(input = {}, options = {}) {
515
- requireActor(options?.context || null, input);
466
+ async function closeSession(input, { context }) {
467
+ requireActor(context, input);
516
468
  const workspaceSlug = requireWorkspaceSlug(input);
517
- const sessionId = input?.sessionId == null ? "" : String(input.sessionId).trim();
469
+ const sessionId = input.sessionId == null ? "" : String(input.sessionId).trim();
518
470
  if (!sessionId) {
519
471
  throw new AppError(400, "sessionId is required.", { code: "rewarded.request.sessionIdRequired" });
520
472
  }
521
473
 
522
- const sessionRecord = normalizeRecord(await rewardedWatchSessionsRepository.getDocumentById(sessionId, {}, {
523
- context: options?.context || null,
524
- trx: options?.trx || null
525
- }));
474
+ const sessionRecord = normalizeRecord(await rewardedWatchSessionsRepository.getDocumentById(sessionId, {}, { context }));
526
475
  if (!sessionRecord) {
527
476
  throw new AppError(404, "Watch session not found.", { code: "rewarded.session.notFound" });
528
477
  }
@@ -531,7 +480,7 @@ function createService({
531
480
  return {
532
481
  closed: false,
533
482
  workspaceSlug,
534
- gateKey: normalizeGateKey(sessionRecord.gateKey),
483
+ gateKey: normalizeText(sessionRecord.gateKey),
535
484
  session: formatWatchSession(sessionRecord),
536
485
  reason: "already-rewarded"
537
486
  };
@@ -543,16 +492,13 @@ function createService({
543
492
  status: "closed",
544
493
  closedAt: new Date().toISOString()
545
494
  },
546
- {
547
- context: options?.context || null,
548
- trx: options?.trx || null
549
- }
495
+ { context }
550
496
  ));
551
497
 
552
498
  return {
553
499
  closed: true,
554
500
  workspaceSlug,
555
- gateKey: normalizeGateKey(closedSession?.gateKey || sessionRecord.gateKey),
501
+ gateKey: normalizeText(closedSession?.gateKey || sessionRecord.gateKey),
556
502
  session: formatWatchSession(closedSession)
557
503
  };
558
504
  }