@windrun-huaiin/backend-core 31.0.0 → 31.0.1

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,566 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  var tslib = require('tslib');
4
- var anonymous_aggregate_service = require('../../../../../services/aggregate/anonymous.aggregate.service.js');
5
4
  var authUtils = require('../../../../../auth/auth-utils.js');
6
- var server = require('@windrun-huaiin/third-ui/fingerprint/server');
7
- var server$1 = require('next/server');
8
- var userContextService = require('../../../../../services/context/user-context-service.js');
9
- var userContextFinalizer = require('../../../../../services/context/user-context-finalizer.js');
5
+ var routeShared = require('./route-shared.js');
10
6
 
11
- /* eslint-disable @typescript-eslint/no-explicit-any */
12
- // Fix BigInt serialization issue
13
- BigInt.prototype.toJSON = function () {
14
- return this.toString();
15
- };
16
- // ==================== Utilities ====================
17
- /** Create a successful response payload */
18
- function createSuccessResponse(params) {
19
- const response = Object.assign({ success: true, xUser: userContextService.mapUserToXUser(params.entities.user), xCredit: params.entities.credit ? userContextService.mapCreditToXCredit(params.entities.credit) : null, xSubscription: userContextService.mapSubscriptionToXSubscription(params.entities.subscription), isNewUser: params.isNewUser }, params.options);
20
- return userContextFinalizer.finalizeUserContext(response);
21
- }
22
- /** Create an error response */
23
- function createErrorResponse(message, status = 400) {
24
- const errorResponse = { error: message };
25
- return server$1.NextResponse.json(errorResponse, { status });
26
- }
27
- const SOURCE_REF_MAX_LENGTH = 2048;
28
- const QUERY_PARAM_MAX_LENGTH = 512;
29
- const USER_AGENT_MAX_LENGTH = 1024;
30
- const FIRST_TOUCH_HEADER_MAX_LENGTH = 4096;
31
- const FIRST_TOUCH_HEADER_NAME = 'x-first-touch';
32
- function normalizeSourceRef(ref) {
33
- if (!ref) {
34
- return null;
35
- }
36
- const trimmed = ref.trim();
37
- if (!trimmed) {
38
- return null;
39
- }
40
- return trimmed.length > SOURCE_REF_MAX_LENGTH
41
- ? trimmed.slice(0, SOURCE_REF_MAX_LENGTH)
42
- : trimmed;
43
- }
44
- function normalizeQueryParam(value) {
45
- if (!value) {
46
- return null;
47
- }
48
- const trimmed = value.trim();
49
- if (!trimmed) {
50
- return null;
51
- }
52
- return trimmed.length > QUERY_PARAM_MAX_LENGTH
53
- ? trimmed.slice(0, QUERY_PARAM_MAX_LENGTH)
54
- : trimmed;
55
- }
56
- function decodeHeaderValue(value) {
57
- try {
58
- return decodeURIComponent(value);
59
- }
60
- catch (_a) {
61
- return null;
62
- }
63
- }
64
- function mergeSourceRef(target, source) {
65
- if (!source) {
66
- return;
67
- }
68
- const entries = Object.entries(source);
69
- for (const [key, value] of entries) {
70
- if (value === undefined || value === null) {
71
- continue;
72
- }
73
- if (target[key] === undefined) {
74
- target[key] = value;
75
- }
76
- }
77
- }
78
- function applySearchParams(sourceRef, params) {
79
- const setIfEmpty = (key, value) => {
80
- if (sourceRef[key] !== undefined) {
81
- return;
82
- }
83
- const normalized = normalizeQueryParam(value);
84
- if (normalized) {
85
- sourceRef[key] = normalized;
86
- }
87
- };
88
- setIfEmpty('utmSource', params.get('utm_source'));
89
- setIfEmpty('utmMedium', params.get('utm_medium'));
90
- setIfEmpty('utmCampaign', params.get('utm_campaign'));
91
- setIfEmpty('utmTerm', params.get('utm_term'));
92
- setIfEmpty('utmContent', params.get('utm_content'));
93
- setIfEmpty('utmId', params.get('utm_id'));
94
- setIfEmpty('ref', params.get('ref'));
95
- setIfEmpty('gclid', params.get('gclid'));
96
- setIfEmpty('fbclid', params.get('fbclid'));
97
- setIfEmpty('msclkid', params.get('msclkid'));
98
- setIfEmpty('ttclid', params.get('ttclid'));
99
- setIfEmpty('twclid', params.get('twclid'));
100
- setIfEmpty('liFatId', params.get('li_fat_id'));
101
- }
102
- function normalizeHost(host) {
103
- if (!host) {
104
- return null;
105
- }
106
- return host.trim().toLowerCase() || null;
107
- }
108
- function getRootDomain(host) {
109
- const normalizedHost = normalizeHost(host);
110
- if (!normalizedHost) {
111
- return null;
112
- }
113
- const hostname = normalizedHost.split(':')[0];
114
- if (hostname === 'localhost' || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) {
115
- return hostname;
116
- }
117
- const parts = hostname.split('.').filter(Boolean);
118
- if (parts.length <= 2) {
119
- return hostname;
120
- }
121
- return parts.slice(-2).join('.');
122
- }
123
- function isInternalReferer(landingHost, refererHost) {
124
- const normalizedLandingHost = normalizeHost(landingHost);
125
- const normalizedRefererHost = normalizeHost(refererHost);
126
- if (!normalizedLandingHost || !normalizedRefererHost) {
127
- return false;
128
- }
129
- if (normalizedLandingHost === normalizedRefererHost) {
130
- return true;
131
- }
132
- return normalizedLandingHost.endsWith(`.${normalizedRefererHost}`)
133
- || normalizedRefererHost.endsWith(`.${normalizedLandingHost}`);
134
- }
135
- function detectPlatform(value) {
136
- const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
137
- if (!normalized) {
138
- return null;
139
- }
140
- const matcherList = [
141
- { pattern: /chatgpt|chat-openai|openai/, platform: 'openai', channel: 'ai' },
142
- { pattern: /claude|anthropic/, platform: 'anthropic', channel: 'ai' },
143
- { pattern: /perplexity/, platform: 'perplexity', channel: 'ai' },
144
- { pattern: /gemini/, platform: 'gemini', channel: 'ai' },
145
- { pattern: /copilot/, platform: 'copilot', channel: 'ai' },
146
- { pattern: /google/, platform: 'google', channel: 'search' },
147
- { pattern: /bing/, platform: 'bing', channel: 'search' },
148
- { pattern: /baidu/, platform: 'baidu', channel: 'search' },
149
- { pattern: /yahoo/, platform: 'yahoo', channel: 'search' },
150
- { pattern: /duckduckgo/, platform: 'duckduckgo', channel: 'search' },
151
- { pattern: /facebook/, platform: 'facebook', channel: 'social' },
152
- { pattern: /instagram/, platform: 'instagram', channel: 'social' },
153
- { pattern: /x\.com|twitter/, platform: 'x', channel: 'social' },
154
- { pattern: /linkedin/, platform: 'linkedin', channel: 'social' },
155
- { pattern: /reddit/, platform: 'reddit', channel: 'social' },
156
- { pattern: /youtube/, platform: 'youtube', channel: 'social' },
157
- ];
158
- const matched = matcherList.find(({ pattern }) => pattern.test(normalized));
159
- if (!matched) {
160
- return null;
161
- }
162
- return matched.platform;
163
- }
164
- function detectChannelFromPlatform(platform) {
165
- switch (platform) {
166
- case 'openai':
167
- case 'anthropic':
168
- case 'perplexity':
169
- case 'gemini':
170
- case 'copilot':
171
- return 'ai';
172
- case 'google':
173
- case 'bing':
174
- case 'baidu':
175
- case 'yahoo':
176
- case 'duckduckgo':
177
- return 'search';
178
- case 'facebook':
179
- case 'instagram':
180
- case 'x':
181
- case 'linkedin':
182
- case 'reddit':
183
- case 'youtube':
184
- return 'social';
185
- default:
186
- return null;
187
- }
188
- }
189
- function detectChannelFromUtmMedium(value) {
190
- const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
191
- if (!normalized) {
192
- return null;
193
- }
194
- if (/^(cpc|ppc|paid|paid_search|display|banner|affiliate|email|newsletter|push|sms)$/.test(normalized)) {
195
- return 'campaign';
196
- }
197
- if (/^(social|social_paid|social-organic|social_organic)$/.test(normalized)) {
198
- return 'social';
199
- }
200
- if (/^(organic|seo|search)$/.test(normalized)) {
201
- return 'search';
202
- }
203
- if (/^(referral|partner)$/.test(normalized)) {
204
- return 'referral';
205
- }
206
- if (/^(ai|llm)$/.test(normalized)) {
207
- return 'ai';
208
- }
209
- return 'campaign';
210
- }
211
- function parseUserAgent(request) {
212
- var _a, _b, _c, _d, _e;
213
- const userAgentHeader = request.headers.get('user-agent');
214
- const secChUaMobile = (_a = normalizeQueryParam(request.headers.get('sec-ch-ua-mobile'))) !== null && _a !== void 0 ? _a : undefined;
215
- const secChUaPlatform = (_b = normalizeQueryParam(request.headers.get('sec-ch-ua-platform'))) !== null && _b !== void 0 ? _b : undefined;
216
- const userAgent = (_d = (_c = normalizeSourceRef(userAgentHeader)) === null || _c === void 0 ? void 0 : _c.slice(0, USER_AGENT_MAX_LENGTH)) !== null && _d !== void 0 ? _d : undefined;
217
- const ua = (_e = userAgent === null || userAgent === void 0 ? void 0 : userAgent.toLowerCase()) !== null && _e !== void 0 ? _e : '';
218
- let deviceType = 'desktop';
219
- if (!ua) {
220
- deviceType = 'unknown';
221
- }
222
- else if (/bot|spider|crawler|curl|wget|headless/.test(ua)) {
223
- deviceType = 'bot';
224
- }
225
- else if (/ipad|tablet/.test(ua)) {
226
- deviceType = 'tablet';
227
- }
228
- else if (/mobi|iphone|android/.test(ua) || secChUaMobile === '?1') {
229
- deviceType = 'mobile';
230
- }
231
- let os = 'Unknown';
232
- if (/iphone|ipad|ipod/.test(ua)) {
233
- os = 'iOS';
234
- }
235
- else if (/android/.test(ua)) {
236
- os = 'Android';
237
- }
238
- else if (/windows nt/.test(ua)) {
239
- os = 'Windows';
240
- }
241
- else if (/mac os x|macintosh/.test(ua)) {
242
- os = 'macOS';
243
- }
244
- else if (/cros/.test(ua)) {
245
- os = 'Chrome OS';
246
- }
247
- else if (/linux/.test(ua)) {
248
- os = 'Linux';
249
- }
250
- if (secChUaPlatform) {
251
- const normalizedPlatform = secChUaPlatform.replaceAll('"', '');
252
- if (normalizedPlatform && normalizedPlatform !== 'Unknown') {
253
- os = normalizedPlatform;
254
- }
255
- }
256
- let browser = 'Unknown';
257
- if (/edg\//.test(ua)) {
258
- browser = 'Edge';
259
- }
260
- else if (/opr\//.test(ua) || /opera/.test(ua)) {
261
- browser = 'Opera';
262
- }
263
- else if (/samsungbrowser\//.test(ua)) {
264
- browser = 'Samsung Internet';
265
- }
266
- else if (/crios\//.test(ua) || /chrome\//.test(ua)) {
267
- browser = 'Chrome';
268
- }
269
- else if (/firefox\//.test(ua)) {
270
- browser = 'Firefox';
271
- }
272
- else if (/safari\//.test(ua) && !/chrome\//.test(ua) && !/crios\//.test(ua)) {
273
- browser = 'Safari';
274
- }
275
- return {
276
- userAgent,
277
- deviceType,
278
- os,
279
- browser,
280
- secChUaMobile,
281
- secChUaPlatform,
282
- };
283
- }
284
- function parseFirstTouchHeader(request) {
285
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
286
- const rawHeader = request.headers.get(FIRST_TOUCH_HEADER_NAME);
287
- const normalizedHeader = (_a = normalizeSourceRef(rawHeader)) === null || _a === void 0 ? void 0 : _a.slice(0, FIRST_TOUCH_HEADER_MAX_LENGTH);
288
- if (!normalizedHeader) {
289
- return null;
290
- }
291
- const decodedHeader = decodeHeaderValue(normalizedHeader);
292
- if (!decodedHeader) {
293
- return null;
294
- }
295
- try {
296
- const parsed = JSON.parse(decodedHeader);
297
- const sourceRef = {};
298
- sourceRef.capturedAt = (_b = normalizeQueryParam(typeof parsed.capturedAt === 'string' ? parsed.capturedAt : null)) !== null && _b !== void 0 ? _b : undefined;
299
- sourceRef.landingUrl = (_c = normalizeSourceRef(typeof parsed.landingUrl === 'string' ? parsed.landingUrl : null)) !== null && _c !== void 0 ? _c : undefined;
300
- sourceRef.landingPath = (_d = normalizeSourceRef(typeof parsed.landingPath === 'string' ? parsed.landingPath : null)) !== null && _d !== void 0 ? _d : undefined;
301
- sourceRef.landingHost = (_e = normalizeHost(typeof parsed.landingHost === 'string' ? parsed.landingHost : null)) !== null && _e !== void 0 ? _e : undefined;
302
- sourceRef.ref = (_f = normalizeQueryParam(typeof parsed.ref === 'string' ? parsed.ref : null)) !== null && _f !== void 0 ? _f : undefined;
303
- sourceRef.utmSource = (_g = normalizeQueryParam(typeof parsed.utmSource === 'string' ? parsed.utmSource : null)) !== null && _g !== void 0 ? _g : undefined;
304
- sourceRef.utmMedium = (_h = normalizeQueryParam(typeof parsed.utmMedium === 'string' ? parsed.utmMedium : null)) !== null && _h !== void 0 ? _h : undefined;
305
- sourceRef.utmCampaign = (_j = normalizeQueryParam(typeof parsed.utmCampaign === 'string' ? parsed.utmCampaign : null)) !== null && _j !== void 0 ? _j : undefined;
306
- sourceRef.utmTerm = (_k = normalizeQueryParam(typeof parsed.utmTerm === 'string' ? parsed.utmTerm : null)) !== null && _k !== void 0 ? _k : undefined;
307
- sourceRef.utmContent = (_l = normalizeQueryParam(typeof parsed.utmContent === 'string' ? parsed.utmContent : null)) !== null && _l !== void 0 ? _l : undefined;
308
- sourceRef.utmId = (_m = normalizeQueryParam(typeof parsed.utmId === 'string' ? parsed.utmId : null)) !== null && _m !== void 0 ? _m : undefined;
309
- sourceRef.gclid = (_o = normalizeQueryParam(typeof parsed.gclid === 'string' ? parsed.gclid : null)) !== null && _o !== void 0 ? _o : undefined;
310
- sourceRef.fbclid = (_p = normalizeQueryParam(typeof parsed.fbclid === 'string' ? parsed.fbclid : null)) !== null && _p !== void 0 ? _p : undefined;
311
- sourceRef.msclkid = (_q = normalizeQueryParam(typeof parsed.msclkid === 'string' ? parsed.msclkid : null)) !== null && _q !== void 0 ? _q : undefined;
312
- sourceRef.ttclid = (_r = normalizeQueryParam(typeof parsed.ttclid === 'string' ? parsed.ttclid : null)) !== null && _r !== void 0 ? _r : undefined;
313
- sourceRef.twclid = (_s = normalizeQueryParam(typeof parsed.twclid === 'string' ? parsed.twclid : null)) !== null && _s !== void 0 ? _s : undefined;
314
- sourceRef.liFatId = (_t = normalizeQueryParam(typeof parsed.liFatId === 'string' ? parsed.liFatId : null)) !== null && _t !== void 0 ? _t : undefined;
315
- const externalReferrer = normalizeSourceRef(typeof parsed.externalReferrer === 'string' ? parsed.externalReferrer : null);
316
- if (externalReferrer) {
317
- sourceRef.httpRefer = externalReferrer;
318
- try {
319
- const refererUrl = new URL(externalReferrer);
320
- sourceRef.refererHost = (_u = normalizeHost(refererUrl.host)) !== null && _u !== void 0 ? _u : undefined;
321
- sourceRef.refererPath = (_v = normalizeSourceRef(refererUrl.pathname)) !== null && _v !== void 0 ? _v : undefined;
322
- sourceRef.refererDomain = (_w = getRootDomain(refererUrl.host)) !== null && _w !== void 0 ? _w : undefined;
323
- applySearchParams(sourceRef, refererUrl.searchParams);
324
- }
325
- catch (error) {
326
- console.warn('Failed to parse first-touch referrer url:', error);
327
- }
328
- }
329
- return Object.keys(sourceRef).length > 0 ? sourceRef : null;
330
- }
331
- catch (error) {
332
- console.warn('Failed to parse first-touch header:', error);
333
- return null;
334
- }
335
- }
336
- function finalizeAttribution(sourceRef) {
337
- var _a, _b, _c, _d, _e;
338
- const landingHost = normalizeHost(sourceRef.landingHost);
339
- const refererHost = normalizeHost(sourceRef.refererHost);
340
- const internal = isInternalReferer(landingHost, refererHost);
341
- const hasCampaignMarker = Boolean(sourceRef.utmSource
342
- || sourceRef.utmMedium
343
- || sourceRef.utmCampaign
344
- || sourceRef.utmTerm
345
- || sourceRef.utmContent
346
- || sourceRef.utmId
347
- || sourceRef.ref
348
- || sourceRef.gclid
349
- || sourceRef.fbclid
350
- || sourceRef.msclkid
351
- || sourceRef.ttclid
352
- || sourceRef.twclid
353
- || sourceRef.liFatId);
354
- if (internal) {
355
- sourceRef.isInternalReferer = true;
356
- }
357
- const utmPlatform = detectPlatform(sourceRef.utmSource) || detectPlatform(sourceRef.ref);
358
- if (utmPlatform) {
359
- sourceRef.sourcePlatform = utmPlatform;
360
- sourceRef.sourceChannel = (_c = (_b = (_a = detectChannelFromPlatform(utmPlatform)) !== null && _a !== void 0 ? _a : detectChannelFromUtmMedium(sourceRef.utmMedium)) !== null && _b !== void 0 ? _b : sourceRef.sourceChannel) !== null && _c !== void 0 ? _c : 'campaign';
361
- sourceRef.sourceType = 'campaign';
362
- return;
363
- }
364
- if (sourceRef.gclid) {
365
- sourceRef.sourcePlatform = 'google';
366
- sourceRef.sourceChannel = 'search';
367
- sourceRef.sourceType = 'campaign';
368
- return;
369
- }
370
- if (sourceRef.msclkid) {
371
- sourceRef.sourcePlatform = 'bing';
372
- sourceRef.sourceChannel = 'search';
373
- sourceRef.sourceType = 'campaign';
374
- return;
375
- }
376
- if (sourceRef.fbclid) {
377
- sourceRef.sourcePlatform = 'facebook';
378
- sourceRef.sourceChannel = 'social';
379
- sourceRef.sourceType = 'campaign';
380
- return;
381
- }
382
- if (sourceRef.ttclid) {
383
- sourceRef.sourcePlatform = 'tiktok';
384
- sourceRef.sourceChannel = 'social';
385
- sourceRef.sourceType = 'campaign';
386
- return;
387
- }
388
- if (sourceRef.twclid) {
389
- sourceRef.sourcePlatform = 'x';
390
- sourceRef.sourceChannel = 'social';
391
- sourceRef.sourceType = 'campaign';
392
- return;
393
- }
394
- if (sourceRef.liFatId) {
395
- sourceRef.sourcePlatform = 'linkedin';
396
- sourceRef.sourceChannel = 'social';
397
- sourceRef.sourceType = 'campaign';
398
- return;
399
- }
400
- if (hasCampaignMarker) {
401
- sourceRef.sourcePlatform = 'other';
402
- sourceRef.sourceChannel = (_d = detectChannelFromUtmMedium(sourceRef.utmMedium)) !== null && _d !== void 0 ? _d : 'campaign';
403
- sourceRef.sourceType = 'campaign';
404
- return;
405
- }
406
- if (!internal && refererHost) {
407
- const refererPlatform = detectPlatform(refererHost) || detectPlatform(sourceRef.httpRefer);
408
- sourceRef.sourcePlatform = refererPlatform !== null && refererPlatform !== void 0 ? refererPlatform : 'other';
409
- sourceRef.sourceChannel = (_e = detectChannelFromPlatform(refererPlatform)) !== null && _e !== void 0 ? _e : 'referral';
410
- sourceRef.sourceType = 'referer';
411
- return;
412
- }
413
- sourceRef.sourcePlatform = 'direct';
414
- sourceRef.sourceChannel = 'direct';
415
- sourceRef.sourceType = 'direct';
416
- }
417
- // Extract the user's first-touch attribution source.
418
- function extractSourceRef(request) {
419
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
420
- const headerRef = request.headers.get('referer') || request.headers.get('referrer');
421
- const customRef = request.headers.get('x-source-ref');
422
- const queryRef = request.nextUrl.searchParams.get('ref');
423
- const firstTouchRef = parseFirstTouchHeader(request);
424
- const sourceRef = Object.assign({}, parseUserAgent(request));
425
- mergeSourceRef(sourceRef, firstTouchRef);
426
- sourceRef.landingUrl = (_b = (_a = sourceRef.landingUrl) !== null && _a !== void 0 ? _a : normalizeSourceRef(request.nextUrl.toString())) !== null && _b !== void 0 ? _b : undefined;
427
- sourceRef.landingPath = (_d = (_c = sourceRef.landingPath) !== null && _c !== void 0 ? _c : normalizeSourceRef(request.nextUrl.pathname)) !== null && _d !== void 0 ? _d : undefined;
428
- sourceRef.landingHost = (_f = (_e = sourceRef.landingHost) !== null && _e !== void 0 ? _e : normalizeHost(request.nextUrl.host)) !== null && _f !== void 0 ? _f : undefined;
429
- sourceRef.ref = (_h = (_g = sourceRef.ref) !== null && _g !== void 0 ? _g : normalizeQueryParam(queryRef)) !== null && _h !== void 0 ? _h : undefined;
430
- let normalizedHttpRef = null;
431
- const candidates = [customRef, headerRef];
432
- for (const candidate of candidates) {
433
- const normalized = normalizeSourceRef(candidate);
434
- if (normalized) {
435
- normalizedHttpRef = normalized;
436
- sourceRef.httpRefer = (_j = sourceRef.httpRefer) !== null && _j !== void 0 ? _j : normalized;
437
- break;
438
- }
439
- }
440
- const searchParams = request.nextUrl.searchParams;
441
- applySearchParams(sourceRef, searchParams);
442
- if (normalizedHttpRef) {
443
- try {
444
- const refererUrl = new URL(normalizedHttpRef);
445
- sourceRef.refererHost = (_l = (_k = sourceRef.refererHost) !== null && _k !== void 0 ? _k : normalizeHost(refererUrl.host)) !== null && _l !== void 0 ? _l : undefined;
446
- sourceRef.refererPath = (_o = (_m = sourceRef.refererPath) !== null && _m !== void 0 ? _m : normalizeSourceRef(refererUrl.pathname)) !== null && _o !== void 0 ? _o : undefined;
447
- sourceRef.refererDomain = (_q = (_p = sourceRef.refererDomain) !== null && _p !== void 0 ? _p : getRootDomain(refererUrl.host)) !== null && _q !== void 0 ? _q : undefined;
448
- applySearchParams(sourceRef, refererUrl.searchParams);
449
- }
450
- catch (error) {
451
- console.warn('Failed to parse referer url for utm/ref:', error);
452
- }
453
- }
454
- finalizeAttribution(sourceRef);
455
- return Object.keys(sourceRef).length > 0 ? sourceRef : null;
456
- }
457
7
  /**
458
- * Query the user by Clerk user ID and return response data.
459
- */
460
- function getUserByClerkId(clerkUserId) {
461
- return tslib.__awaiter(this, void 0, void 0, function* () {
462
- const entities = yield userContextService.fetchUserContextByClerkUserId(clerkUserId);
463
- if (!entities) {
464
- return null;
465
- }
466
- return createSuccessResponse({
467
- entities,
468
- isNewUser: false,
469
- });
470
- });
471
- }
472
- /**
473
- * Query the user by fingerprint ID and return response data.
474
- */
475
- function getUserByFingerprintId(fingerprintId) {
476
- return tslib.__awaiter(this, void 0, void 0, function* () {
477
- const result = yield userContextService.fetchLatestUserContextByFingerprintId(fingerprintId);
478
- if (!result) {
479
- return null;
480
- }
481
- const { totalUsersOnDevice, hasAnonymousUser } = result, entities = tslib.__rest(result, ["totalUsersOnDevice", "hasAnonymousUser"]);
482
- return createSuccessResponse({
483
- entities,
484
- isNewUser: false,
485
- options: {
486
- totalUsersOnDevice,
487
- hasAnonymousUser,
488
- },
489
- });
490
- });
491
- }
492
- /**
493
- * Shared fingerprint request handling logic.
494
- */
495
- function handleFingerprintRequest(request_1) {
496
- return tslib.__awaiter(this, arguments, void 0, function* (request, options = {}) {
497
- var _a;
498
- // Extract the fingerprint ID from the request.
499
- const fingerprintId = server.extractFingerprintFromNextRequest(request);
500
- // Validate the fingerprint ID.
501
- if (!fingerprintId) {
502
- return createErrorResponse('Invalid or missing fingerprint ID');
503
- }
504
- console.log('Received fingerprintId:', fingerprintId);
505
- const authIdentity = yield authUtils.getOptionalServerAuthIdentity();
506
- const clerkUserId = (_a = authIdentity === null || authIdentity === void 0 ? void 0 : authIdentity.providerUserId) !== null && _a !== void 0 ? _a : null;
507
- try {
508
- // Prefer Clerk user ID lookup when the user is authenticated.
509
- let existingUserResult = null;
510
- if (clerkUserId) {
511
- // Authenticated users are always resolved by clerkUserId.
512
- existingUserResult = yield getUserByClerkId(clerkUserId);
513
- if (existingUserResult && existingUserResult.xUser.fingerprintId !== fingerprintId) {
514
- // The authenticated user's fingerprint changed. Clerk still identifies the account as the same user.
515
- // Trust clerkUserId as the source of truth and keep resolving the user's own data by login identity.
516
- // A single fingerprint can be associated with multiple accounts, so no mutation is needed here.
517
- console.warn(`Current login user used diff fp_ids: ${clerkUserId}, db_fp_id=${existingUserResult.xUser.fingerprintId}, req_fp_id=${fingerprintId}`);
518
- }
519
- }
520
- else {
521
- // For anonymous requests, fall back to fingerprint lookup.
522
- existingUserResult = yield getUserByFingerprintId(fingerprintId);
523
- }
524
- if (existingUserResult) {
525
- return server$1.NextResponse.json(existingUserResult);
526
- }
527
- // If the user does not exist and creation is disabled, return 404.
528
- if (!options.createIfNotExists) {
529
- return createErrorResponse('User not found', 404);
530
- }
531
- const sourceRef = extractSourceRef(request);
532
- const anonymousInitResult = yield anonymous_aggregate_service.anonymousAggregateService.getOrCreateByFingerprintId(fingerprintId, { sourceRef: sourceRef !== null && sourceRef !== void 0 ? sourceRef : undefined });
533
- if (anonymousInitResult.isNewUser) {
534
- console.log(`Created new anonymous user ${anonymousInitResult.user.userId} with fingerprint ${fingerprintId}`);
535
- }
536
- // Return the created or existing context.
537
- const response = createSuccessResponse({
538
- entities: {
539
- user: anonymousInitResult.user,
540
- credit: anonymousInitResult.credit,
541
- subscription: anonymousInitResult.subscription,
542
- },
543
- isNewUser: anonymousInitResult.isNewUser,
544
- options: {
545
- totalUsersOnDevice: anonymousInitResult.totalUsersOnDevice,
546
- hasAnonymousUser: anonymousInitResult.hasAnonymousUser,
547
- },
548
- });
549
- return server$1.NextResponse.json(response);
550
- }
551
- catch (error) {
552
- console.error('Fingerprint request error:', error);
553
- return createErrorResponse('Internal server error', 500);
554
- }
555
- });
556
- }
557
- /**
558
- * Anonymous user initialization API.
8
+ * Clerk-aware anonymous user initialization API.
559
9
  * POST /api/user/anonymous/init
560
10
  */
561
11
  function POST(request) {
562
12
  return tslib.__awaiter(this, void 0, void 0, function* () {
563
- return handleFingerprintRequest(request, { createIfNotExists: true });
13
+ return routeShared.handleFingerprintRequest(request, {
14
+ createIfNotExists: true,
15
+ getAuthIdentity: authUtils.getOptionalServerAuthIdentity,
16
+ });
564
17
  });
565
18
  }
566
19