@windrun-huaiin/backend-core 14.0.0 → 14.1.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 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../src/app/api/user/anonymous/init/route.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA0QxD;;;GAGG;AACH,wBAAsB,IAAI,CAAC,OAAO,EAAE,WAAW,kCAE9C"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../src/app/api/user/anonymous/init/route.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAgoBxD;;;GAGG;AACH,wBAAsB,IAAI,CAAC,OAAO,EAAE,WAAW,kCAE9C"}
@@ -25,6 +25,9 @@ function createErrorResponse(message, status = 400) {
25
25
  }
26
26
  const SOURCE_REF_MAX_LENGTH = 2048;
27
27
  const QUERY_PARAM_MAX_LENGTH = 512;
28
+ const USER_AGENT_MAX_LENGTH = 1024;
29
+ const FIRST_TOUCH_HEADER_MAX_LENGTH = 4096;
30
+ const FIRST_TOUCH_HEADER_NAME = 'x-first-touch';
28
31
  function normalizeSourceRef(ref) {
29
32
  if (!ref) {
30
33
  return null;
@@ -49,6 +52,28 @@ function normalizeQueryParam(value) {
49
52
  ? trimmed.slice(0, QUERY_PARAM_MAX_LENGTH)
50
53
  : trimmed;
51
54
  }
55
+ function decodeHeaderValue(value) {
56
+ try {
57
+ return decodeURIComponent(value);
58
+ }
59
+ catch (_a) {
60
+ return null;
61
+ }
62
+ }
63
+ function mergeSourceRef(target, source) {
64
+ if (!source) {
65
+ return;
66
+ }
67
+ const entries = Object.entries(source);
68
+ for (const [key, value] of entries) {
69
+ if (value === undefined || value === null) {
70
+ continue;
71
+ }
72
+ if (target[key] === undefined) {
73
+ target[key] = value;
74
+ }
75
+ }
76
+ }
52
77
  function applySearchParams(sourceRef, params) {
53
78
  const setIfEmpty = (key, value) => {
54
79
  if (sourceRef[key] !== undefined) {
@@ -64,26 +89,309 @@ function applySearchParams(sourceRef, params) {
64
89
  setIfEmpty('utmCampaign', params.get('utm_campaign'));
65
90
  setIfEmpty('utmTerm', params.get('utm_term'));
66
91
  setIfEmpty('utmContent', params.get('utm_content'));
92
+ setIfEmpty('utmId', params.get('utm_id'));
67
93
  setIfEmpty('ref', params.get('ref'));
94
+ setIfEmpty('gclid', params.get('gclid'));
95
+ setIfEmpty('fbclid', params.get('fbclid'));
96
+ setIfEmpty('msclkid', params.get('msclkid'));
97
+ setIfEmpty('ttclid', params.get('ttclid'));
98
+ setIfEmpty('twclid', params.get('twclid'));
99
+ setIfEmpty('liFatId', params.get('li_fat_id'));
100
+ }
101
+ function normalizeHost(host) {
102
+ if (!host) {
103
+ return null;
104
+ }
105
+ return host.trim().toLowerCase() || null;
106
+ }
107
+ function getRootDomain(host) {
108
+ const normalizedHost = normalizeHost(host);
109
+ if (!normalizedHost) {
110
+ return null;
111
+ }
112
+ const hostname = normalizedHost.split(':')[0];
113
+ if (hostname === 'localhost' || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) {
114
+ return hostname;
115
+ }
116
+ const parts = hostname.split('.').filter(Boolean);
117
+ if (parts.length <= 2) {
118
+ return hostname;
119
+ }
120
+ return parts.slice(-2).join('.');
121
+ }
122
+ function isInternalReferer(landingHost, refererHost) {
123
+ const normalizedLandingHost = normalizeHost(landingHost);
124
+ const normalizedRefererHost = normalizeHost(refererHost);
125
+ if (!normalizedLandingHost || !normalizedRefererHost) {
126
+ return false;
127
+ }
128
+ if (normalizedLandingHost === normalizedRefererHost) {
129
+ return true;
130
+ }
131
+ return normalizedLandingHost.endsWith(`.${normalizedRefererHost}`)
132
+ || normalizedRefererHost.endsWith(`.${normalizedLandingHost}`);
133
+ }
134
+ function detectPlatform(value) {
135
+ const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
136
+ if (!normalized) {
137
+ return null;
138
+ }
139
+ const matcherList = [
140
+ { pattern: /chatgpt|chat-openai|openai/, platform: 'openai', channel: 'ai' },
141
+ { pattern: /claude|anthropic/, platform: 'anthropic', channel: 'ai' },
142
+ { pattern: /perplexity/, platform: 'perplexity', channel: 'ai' },
143
+ { pattern: /gemini/, platform: 'gemini', channel: 'ai' },
144
+ { pattern: /copilot/, platform: 'copilot', channel: 'ai' },
145
+ { pattern: /google/, platform: 'google', channel: 'search' },
146
+ { pattern: /bing/, platform: 'bing', channel: 'search' },
147
+ { pattern: /baidu/, platform: 'baidu', channel: 'search' },
148
+ { pattern: /yahoo/, platform: 'yahoo', channel: 'search' },
149
+ { pattern: /duckduckgo/, platform: 'duckduckgo', channel: 'search' },
150
+ { pattern: /facebook/, platform: 'facebook', channel: 'social' },
151
+ { pattern: /instagram/, platform: 'instagram', channel: 'social' },
152
+ { pattern: /x\.com|twitter/, platform: 'x', channel: 'social' },
153
+ { pattern: /linkedin/, platform: 'linkedin', channel: 'social' },
154
+ { pattern: /reddit/, platform: 'reddit', channel: 'social' },
155
+ { pattern: /youtube/, platform: 'youtube', channel: 'social' },
156
+ ];
157
+ const matched = matcherList.find(({ pattern }) => pattern.test(normalized));
158
+ if (!matched) {
159
+ return null;
160
+ }
161
+ return matched.platform;
162
+ }
163
+ function detectChannelFromPlatform(platform) {
164
+ switch (platform) {
165
+ case 'openai':
166
+ case 'anthropic':
167
+ case 'perplexity':
168
+ case 'gemini':
169
+ case 'copilot':
170
+ return 'ai';
171
+ case 'google':
172
+ case 'bing':
173
+ case 'baidu':
174
+ case 'yahoo':
175
+ case 'duckduckgo':
176
+ return 'search';
177
+ case 'facebook':
178
+ case 'instagram':
179
+ case 'x':
180
+ case 'linkedin':
181
+ case 'reddit':
182
+ case 'youtube':
183
+ return 'social';
184
+ default:
185
+ return null;
186
+ }
187
+ }
188
+ function parseUserAgent(request) {
189
+ var _a, _b, _c, _d, _e;
190
+ const userAgentHeader = request.headers.get('user-agent');
191
+ const secChUaMobile = (_a = normalizeQueryParam(request.headers.get('sec-ch-ua-mobile'))) !== null && _a !== void 0 ? _a : undefined;
192
+ const secChUaPlatform = (_b = normalizeQueryParam(request.headers.get('sec-ch-ua-platform'))) !== null && _b !== void 0 ? _b : undefined;
193
+ 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;
194
+ const ua = (_e = userAgent === null || userAgent === void 0 ? void 0 : userAgent.toLowerCase()) !== null && _e !== void 0 ? _e : '';
195
+ let deviceType = 'desktop';
196
+ if (!ua) {
197
+ deviceType = 'unknown';
198
+ }
199
+ else if (/bot|spider|crawler|curl|wget|headless/.test(ua)) {
200
+ deviceType = 'bot';
201
+ }
202
+ else if (/ipad|tablet/.test(ua)) {
203
+ deviceType = 'tablet';
204
+ }
205
+ else if (/mobi|iphone|android/.test(ua) || secChUaMobile === '?1') {
206
+ deviceType = 'mobile';
207
+ }
208
+ let os = 'Unknown';
209
+ if (/iphone|ipad|ipod/.test(ua)) {
210
+ os = 'iOS';
211
+ }
212
+ else if (/android/.test(ua)) {
213
+ os = 'Android';
214
+ }
215
+ else if (/windows nt/.test(ua)) {
216
+ os = 'Windows';
217
+ }
218
+ else if (/mac os x|macintosh/.test(ua)) {
219
+ os = 'macOS';
220
+ }
221
+ else if (/cros/.test(ua)) {
222
+ os = 'Chrome OS';
223
+ }
224
+ else if (/linux/.test(ua)) {
225
+ os = 'Linux';
226
+ }
227
+ if (secChUaPlatform) {
228
+ const normalizedPlatform = secChUaPlatform.replaceAll('"', '');
229
+ if (normalizedPlatform && normalizedPlatform !== 'Unknown') {
230
+ os = normalizedPlatform;
231
+ }
232
+ }
233
+ let browser = 'Unknown';
234
+ if (/edg\//.test(ua)) {
235
+ browser = 'Edge';
236
+ }
237
+ else if (/opr\//.test(ua) || /opera/.test(ua)) {
238
+ browser = 'Opera';
239
+ }
240
+ else if (/samsungbrowser\//.test(ua)) {
241
+ browser = 'Samsung Internet';
242
+ }
243
+ else if (/crios\//.test(ua) || /chrome\//.test(ua)) {
244
+ browser = 'Chrome';
245
+ }
246
+ else if (/firefox\//.test(ua)) {
247
+ browser = 'Firefox';
248
+ }
249
+ else if (/safari\//.test(ua) && !/chrome\//.test(ua) && !/crios\//.test(ua)) {
250
+ browser = 'Safari';
251
+ }
252
+ return {
253
+ userAgent,
254
+ deviceType,
255
+ os,
256
+ browser,
257
+ secChUaMobile,
258
+ secChUaPlatform,
259
+ };
260
+ }
261
+ function parseFirstTouchHeader(request) {
262
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
263
+ const rawHeader = request.headers.get(FIRST_TOUCH_HEADER_NAME);
264
+ const normalizedHeader = (_a = normalizeSourceRef(rawHeader)) === null || _a === void 0 ? void 0 : _a.slice(0, FIRST_TOUCH_HEADER_MAX_LENGTH);
265
+ if (!normalizedHeader) {
266
+ return null;
267
+ }
268
+ const decodedHeader = decodeHeaderValue(normalizedHeader);
269
+ if (!decodedHeader) {
270
+ return null;
271
+ }
272
+ try {
273
+ const parsed = JSON.parse(decodedHeader);
274
+ const sourceRef = {};
275
+ sourceRef.capturedAt = (_b = normalizeQueryParam(typeof parsed.capturedAt === 'string' ? parsed.capturedAt : null)) !== null && _b !== void 0 ? _b : undefined;
276
+ sourceRef.landingUrl = (_c = normalizeSourceRef(typeof parsed.landingUrl === 'string' ? parsed.landingUrl : null)) !== null && _c !== void 0 ? _c : undefined;
277
+ sourceRef.landingPath = (_d = normalizeSourceRef(typeof parsed.landingPath === 'string' ? parsed.landingPath : null)) !== null && _d !== void 0 ? _d : undefined;
278
+ sourceRef.landingHost = (_e = normalizeHost(typeof parsed.landingHost === 'string' ? parsed.landingHost : null)) !== null && _e !== void 0 ? _e : undefined;
279
+ sourceRef.ref = (_f = normalizeQueryParam(typeof parsed.ref === 'string' ? parsed.ref : null)) !== null && _f !== void 0 ? _f : undefined;
280
+ sourceRef.utmSource = (_g = normalizeQueryParam(typeof parsed.utmSource === 'string' ? parsed.utmSource : null)) !== null && _g !== void 0 ? _g : undefined;
281
+ sourceRef.utmMedium = (_h = normalizeQueryParam(typeof parsed.utmMedium === 'string' ? parsed.utmMedium : null)) !== null && _h !== void 0 ? _h : undefined;
282
+ sourceRef.utmCampaign = (_j = normalizeQueryParam(typeof parsed.utmCampaign === 'string' ? parsed.utmCampaign : null)) !== null && _j !== void 0 ? _j : undefined;
283
+ sourceRef.utmTerm = (_k = normalizeQueryParam(typeof parsed.utmTerm === 'string' ? parsed.utmTerm : null)) !== null && _k !== void 0 ? _k : undefined;
284
+ sourceRef.utmContent = (_l = normalizeQueryParam(typeof parsed.utmContent === 'string' ? parsed.utmContent : null)) !== null && _l !== void 0 ? _l : undefined;
285
+ sourceRef.utmId = (_m = normalizeQueryParam(typeof parsed.utmId === 'string' ? parsed.utmId : null)) !== null && _m !== void 0 ? _m : undefined;
286
+ sourceRef.gclid = (_o = normalizeQueryParam(typeof parsed.gclid === 'string' ? parsed.gclid : null)) !== null && _o !== void 0 ? _o : undefined;
287
+ sourceRef.fbclid = (_p = normalizeQueryParam(typeof parsed.fbclid === 'string' ? parsed.fbclid : null)) !== null && _p !== void 0 ? _p : undefined;
288
+ sourceRef.msclkid = (_q = normalizeQueryParam(typeof parsed.msclkid === 'string' ? parsed.msclkid : null)) !== null && _q !== void 0 ? _q : undefined;
289
+ sourceRef.ttclid = (_r = normalizeQueryParam(typeof parsed.ttclid === 'string' ? parsed.ttclid : null)) !== null && _r !== void 0 ? _r : undefined;
290
+ sourceRef.twclid = (_s = normalizeQueryParam(typeof parsed.twclid === 'string' ? parsed.twclid : null)) !== null && _s !== void 0 ? _s : undefined;
291
+ sourceRef.liFatId = (_t = normalizeQueryParam(typeof parsed.liFatId === 'string' ? parsed.liFatId : null)) !== null && _t !== void 0 ? _t : undefined;
292
+ const externalReferrer = normalizeSourceRef(typeof parsed.externalReferrer === 'string' ? parsed.externalReferrer : null);
293
+ if (externalReferrer) {
294
+ sourceRef.httpRefer = externalReferrer;
295
+ try {
296
+ const refererUrl = new URL(externalReferrer);
297
+ sourceRef.refererHost = (_u = normalizeHost(refererUrl.host)) !== null && _u !== void 0 ? _u : undefined;
298
+ sourceRef.refererPath = (_v = normalizeSourceRef(refererUrl.pathname)) !== null && _v !== void 0 ? _v : undefined;
299
+ sourceRef.refererDomain = (_w = getRootDomain(refererUrl.host)) !== null && _w !== void 0 ? _w : undefined;
300
+ applySearchParams(sourceRef, refererUrl.searchParams);
301
+ }
302
+ catch (error) {
303
+ console.warn('Failed to parse first-touch referrer url:', error);
304
+ }
305
+ }
306
+ return Object.keys(sourceRef).length > 0 ? sourceRef : null;
307
+ }
308
+ catch (error) {
309
+ console.warn('Failed to parse first-touch header:', error);
310
+ return null;
311
+ }
312
+ }
313
+ function finalizeAttribution(sourceRef) {
314
+ var _a, _b, _c, _d;
315
+ const landingHost = normalizeHost(sourceRef.landingHost);
316
+ const refererHost = normalizeHost(sourceRef.refererHost);
317
+ const internal = isInternalReferer(landingHost, refererHost);
318
+ if (internal) {
319
+ sourceRef.isInternalReferer = true;
320
+ }
321
+ const utmPlatform = detectPlatform(sourceRef.utmSource) || detectPlatform(sourceRef.ref);
322
+ if (utmPlatform) {
323
+ sourceRef.sourcePlatform = utmPlatform;
324
+ sourceRef.sourceChannel = (_b = (_a = detectChannelFromPlatform(utmPlatform)) !== null && _a !== void 0 ? _a : sourceRef.sourceChannel) !== null && _b !== void 0 ? _b : 'campaign';
325
+ sourceRef.sourceType = 'campaign';
326
+ return;
327
+ }
328
+ if (sourceRef.gclid) {
329
+ sourceRef.sourcePlatform = 'google';
330
+ sourceRef.sourceChannel = 'search';
331
+ sourceRef.sourceType = 'campaign';
332
+ return;
333
+ }
334
+ if (sourceRef.msclkid) {
335
+ sourceRef.sourcePlatform = 'bing';
336
+ sourceRef.sourceChannel = 'search';
337
+ sourceRef.sourceType = 'campaign';
338
+ return;
339
+ }
340
+ if (sourceRef.fbclid) {
341
+ sourceRef.sourcePlatform = 'facebook';
342
+ sourceRef.sourceChannel = 'social';
343
+ sourceRef.sourceType = 'campaign';
344
+ return;
345
+ }
346
+ if (sourceRef.ttclid) {
347
+ sourceRef.sourcePlatform = 'tiktok';
348
+ sourceRef.sourceChannel = 'social';
349
+ sourceRef.sourceType = 'campaign';
350
+ return;
351
+ }
352
+ if (sourceRef.twclid) {
353
+ sourceRef.sourcePlatform = 'x';
354
+ sourceRef.sourceChannel = 'social';
355
+ sourceRef.sourceType = 'campaign';
356
+ return;
357
+ }
358
+ if (sourceRef.liFatId) {
359
+ sourceRef.sourcePlatform = 'linkedin';
360
+ sourceRef.sourceChannel = 'social';
361
+ sourceRef.sourceType = 'campaign';
362
+ return;
363
+ }
364
+ if (!internal && refererHost) {
365
+ const refererPlatform = detectPlatform(refererHost) || detectPlatform(sourceRef.httpRefer);
366
+ sourceRef.sourcePlatform = (_c = refererPlatform !== null && refererPlatform !== void 0 ? refererPlatform : getRootDomain(refererHost)) !== null && _c !== void 0 ? _c : refererHost;
367
+ sourceRef.sourceChannel = (_d = detectChannelFromPlatform(refererPlatform)) !== null && _d !== void 0 ? _d : 'referral';
368
+ sourceRef.sourceType = 'referer';
369
+ return;
370
+ }
371
+ sourceRef.sourcePlatform = 'direct';
372
+ sourceRef.sourceChannel = 'direct';
373
+ sourceRef.sourceType = 'direct';
68
374
  }
69
375
  // 提取用户首次访问来源
70
376
  function extractSourceRef(request) {
377
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
71
378
  const headerRef = request.headers.get('referer') || request.headers.get('referrer');
72
379
  const customRef = request.headers.get('x-source-ref');
73
380
  const queryRef = request.nextUrl.searchParams.get('ref');
74
- console.log({
75
- headerRef,
76
- customRef,
77
- queryRef
78
- });
79
- const sourceRef = {};
381
+ const firstTouchRef = parseFirstTouchHeader(request);
382
+ const sourceRef = Object.assign({}, parseUserAgent(request));
383
+ mergeSourceRef(sourceRef, firstTouchRef);
384
+ sourceRef.landingUrl = (_b = (_a = sourceRef.landingUrl) !== null && _a !== void 0 ? _a : normalizeSourceRef(request.nextUrl.toString())) !== null && _b !== void 0 ? _b : undefined;
385
+ sourceRef.landingPath = (_d = (_c = sourceRef.landingPath) !== null && _c !== void 0 ? _c : normalizeSourceRef(request.nextUrl.pathname)) !== null && _d !== void 0 ? _d : undefined;
386
+ sourceRef.landingHost = (_f = (_e = sourceRef.landingHost) !== null && _e !== void 0 ? _e : normalizeHost(request.nextUrl.host)) !== null && _f !== void 0 ? _f : undefined;
387
+ sourceRef.ref = (_h = (_g = sourceRef.ref) !== null && _g !== void 0 ? _g : normalizeQueryParam(queryRef)) !== null && _h !== void 0 ? _h : undefined;
80
388
  let normalizedHttpRef = null;
81
- const candidates = [headerRef, customRef, queryRef];
389
+ const candidates = [customRef, headerRef];
82
390
  for (const candidate of candidates) {
83
391
  const normalized = normalizeSourceRef(candidate);
84
392
  if (normalized) {
85
393
  normalizedHttpRef = normalized;
86
- sourceRef.httpRefer = normalized;
394
+ sourceRef.httpRefer = (_j = sourceRef.httpRefer) !== null && _j !== void 0 ? _j : normalized;
87
395
  break;
88
396
  }
89
397
  }
@@ -92,12 +400,16 @@ function extractSourceRef(request) {
92
400
  if (normalizedHttpRef) {
93
401
  try {
94
402
  const refererUrl = new URL(normalizedHttpRef);
403
+ sourceRef.refererHost = (_l = (_k = sourceRef.refererHost) !== null && _k !== void 0 ? _k : normalizeHost(refererUrl.host)) !== null && _l !== void 0 ? _l : undefined;
404
+ sourceRef.refererPath = (_o = (_m = sourceRef.refererPath) !== null && _m !== void 0 ? _m : normalizeSourceRef(refererUrl.pathname)) !== null && _o !== void 0 ? _o : undefined;
405
+ sourceRef.refererDomain = (_q = (_p = sourceRef.refererDomain) !== null && _p !== void 0 ? _p : getRootDomain(refererUrl.host)) !== null && _q !== void 0 ? _q : undefined;
95
406
  applySearchParams(sourceRef, refererUrl.searchParams);
96
407
  }
97
408
  catch (error) {
98
409
  console.warn('Failed to parse referer url for utm/ref:', error);
99
410
  }
100
411
  }
412
+ finalizeAttribution(sourceRef);
101
413
  return Object.keys(sourceRef).length > 0 ? sourceRef : null;
102
414
  }
103
415
  /**