-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.ts
871 lines (775 loc) · 28 KB
/
api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
import { NextRequest, NextResponse } from 'next/server.js'
import punycode from 'punycode'
import { getPayload } from 'payload'
import config from '../payload.config'
import { PayloadDB } from './db'
import { auth } from '../auth'
import { UAParser } from 'ua-parser-js'
import { geolocation } from '@vercel/functions'
import { continents, countries, flags, locations, metros } from './constants/cf'
import { nanoid } from 'nanoid'
import { getOrganizationByASN } from './utils/asn-lookup'
import { parentDomains, childDomains, sdks } from '../domains.config'
/**
* Context object passed to API handlers
*/
export type ApiContext = {
params: Record<string, string | string[]>
url: URL
path: string
domain: string
origin: string
user: any
permissions: any
payload: any
db: PayloadDB
req: NextRequest
cf?: any // Cloudflare data fetched from cf.json endpoint
}
/**
* Type definition for the user object in API responses
*/
export interface APIUser {
id?: string
email?: string
name?: string
authenticated: boolean
admin?: boolean
plan: string
browser?: string
userAgent?: string
os?: string
ip: string
isp: string
asOrg?: string
flag: string
zipcode: string
city: string
metro?: string
region: string
country?: string
continent?: string
requestId: string
localTime: string
timezone: string
edgeLocation?: string
edgeDistanceMiles?: number
edgeDistanceKilometers?: number
latencyMilliseconds: number
recentInteractions: number
trustScore?: number
serviceLatency?: number
authMethod?: string
authWorkerDomain?: string
links?: {
profile?: string
account?: string
usage?: string
upgrade?: string
logs?: string
[key: string]: string | undefined
}
}
/**
* Type definition for the API header object in responses
*/
export interface APIHeader {
name: string
description: string
home: string
login: string
signup: string
admin: string
docs: string
repo: string
sdk: string
site: string
from: string // Added from field
[key: string]: string
}
export type ApiHandler<T = any> = (req: NextRequest, ctx: ApiContext) => Promise<T> | T
/**
* Function to get user information from the request
*/
export async function getUser(request: NextRequest, payload?: any): Promise<APIUser> {
const now = new Date()
const url = new URL(request.url)
const domain = punycode.toUnicode(url.hostname)
const origin = url.protocol + '//' + domain + (url.port ? ':' + url.port : '')
const isCloudflareWorker = 'cf' in request
const cf = isCloudflareWorker ? (request as any).cf :
(request as any)._cf || undefined
const geo = !isCloudflareWorker ? geolocation(request) : undefined
const ip = request.headers.get('cf-connecting-ip') || request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || '127.0.0.1'
const userAgent = request.headers.get('user-agent') || ''
const ua = userAgent ? new UAParser(userAgent).getResult() : { browser: { name: 'unknown' }, os: { name: 'unknown' } }
const asn = request.headers.get('cf-ray')?.split('-')[0] || request.headers.get('x-vercel-ip-asn') || ''
const asOrgPromise = asn ? getOrganizationByASN(asn) : Promise.resolve(null)
const isp = cf?.asOrganization?.toString() || request.headers.get('x-vercel-ip-org') || 'Unknown ISP' // Will update with asOrg later
let latitude = 0,
longitude = 0
if (cf?.latitude && cf?.longitude) {
latitude = Number(cf.latitude)
longitude = Number(cf.longitude)
} else if (geo?.latitude && geo?.longitude) {
latitude = Number(geo.latitude)
longitude = Number(geo.longitude)
}
const colo = cf?.colo ? locations[cf.colo as keyof typeof locations] : undefined
let edgeDistance: number | undefined = undefined
if (colo && latitude && longitude) {
const latDiff = colo.lat - latitude
const lonDiff = colo.lon - longitude
const distance = Math.sqrt(latDiff * latDiff + lonDiff * lonDiff) * 111 // Rough km conversion
edgeDistance = Math.round(distance / (cf?.country === 'US' || geo?.country === 'US' ? 1.60934 : 1)) // Convert to miles if US
}
let localTime = ''
try {
localTime = now.toLocaleString('en-US', {
timeZone: cf?.timezone ? cf.timezone.toString() : 'UTC',
})
} catch (error) {
console.log({ error })
localTime = now.toLocaleString('en-US', {
timeZone: 'UTC',
})
}
const links = {
profile: origin + '/profile',
account: origin + '/account',
usage: origin + '/usage',
upgrade: origin + '/upgrade',
logs: origin + '/logs',
}
const countryCode = cf?.country || geo?.country || ''
const countryFlag = countryCode ? flags[countryCode as keyof typeof flags] || '🏳️' : '🏳️'
const countryName = countryCode ? countries[countryCode as keyof typeof countries]?.name : undefined
const cfWorkerHeader = request.headers.get('cf-worker')
if (cfWorkerHeader && isCloudflareWorker && payload) {
try {
const { isCloudflareIP } = await import('./utils/cloudflare-ip')
if (await isCloudflareIP(ip)) {
const workerDomain = cfWorkerHeader.trim()
const apiKeyWithDomain = await payload.db.apikeys.findOne({
where: {
cfWorkerDomains: {
elemMatch: {
domain: workerDomain,
},
},
},
})
if (apiKeyWithDomain) {
const user = await payload.db.users.findByID(apiKeyWithDomain.user)
if (user) {
const asOrg = await asOrgPromise
return {
id: user.id,
email: user.email,
name: user.name,
authenticated: true,
admin: user.role === 'admin',
plan: user.plan || 'Free',
browser: ua?.browser?.name,
userAgent: ua?.browser?.name === undefined && userAgent ? userAgent : undefined,
os: ua?.os?.name as string,
ip,
isp: cf?.asOrganization?.toString() || request.headers.get('x-vercel-ip-org') || asOrg || 'Unknown ISP',
asOrg: asOrg || undefined,
flag: countryFlag,
zipcode: cf?.postalCode?.toString() || request.headers.get('x-vercel-ip-zipcode') || '',
city: cf?.city?.toString() || geo?.city || request.headers.get('x-vercel-ip-city') || '',
metro: cf?.metroCode ? metros[Number(cf.metroCode) as keyof typeof metros] : undefined,
region: cf?.region?.toString() || geo?.countryRegion || request.headers.get('x-vercel-ip-region') || '',
country: countryName,
continent: cf?.continent ? continents[cf.continent as keyof typeof continents] : undefined,
requestId: cf ? request.headers.get('cf-ray') + '-' + cf.colo : request.headers.get('x-vercel-id') || '',
localTime,
timezone: cf?.timezone?.toString() || 'UTC',
edgeLocation: colo?.city || geo?.region,
edgeDistanceMiles: cf?.country === 'US' || geo?.country === 'US' ? edgeDistance : undefined,
edgeDistanceKilometers: cf?.country === 'US' || geo?.country === 'US' ? undefined : edgeDistance,
latencyMilliseconds: cf?.clientTcpRtt ? Number(cf.clientTcpRtt) : 0,
recentInteractions: 0,
trustScore: cf?.botManagement ? (cf.botManagement as any).score : undefined,
links,
authMethod: 'cloudflare-worker',
authWorkerDomain: workerDomain,
}
}
}
}
} catch (error) {
console.error('Error in Cloudflare Worker authentication:', error)
}
}
const asOrg = await asOrgPromise
return {
authenticated: false, // This would be determined by authentication logic
admin: undefined, // This would be determined by authentication logic
plan: 'Free', // This would be determined by user data
browser: ua?.browser?.name,
userAgent: ua?.browser?.name === undefined && userAgent ? userAgent : undefined,
os: ua?.os?.name as string,
ip,
isp: cf?.asOrganization?.toString() || request.headers.get('x-vercel-ip-org') || asOrg || 'Unknown ISP',
asOrg: asOrg || undefined,
flag: countryFlag,
zipcode: cf?.postalCode?.toString() || request.headers.get('x-vercel-ip-zipcode') || '',
city: cf?.city?.toString() || geo?.city || request.headers.get('x-vercel-ip-city') || '',
metro: cf?.metroCode ? metros[Number(cf.metroCode) as keyof typeof metros] : undefined,
region: cf?.region?.toString() || geo?.countryRegion || request.headers.get('x-vercel-ip-region') || '',
country: countryName,
continent: cf?.continent ? continents[cf.continent as keyof typeof continents] : undefined,
requestId: cf ? request.headers.get('cf-ray') + '-' + cf.colo : request.headers.get('x-vercel-id') || '',
localTime,
timezone: cf?.timezone?.toString() || 'UTC',
edgeLocation: colo?.city || geo?.region,
edgeDistanceMiles: cf?.country === 'US' || geo?.country === 'US' ? edgeDistance : undefined,
edgeDistanceKilometers: cf?.country === 'US' || geo?.country === 'US' ? undefined : edgeDistance,
latencyMilliseconds: cf?.clientTcpRtt ? Number(cf.clientTcpRtt) : 0,
recentInteractions: 0, // This would be determined by user data
trustScore: cf?.botManagement ? (cf.botManagement as any).score : undefined,
links,
}
}
/**
* Function to get API header object
*/
export function getApiHeader(request: NextRequest, description?: string): APIHeader {
const url = new URL(request.url)
const domain = punycode.toUnicode(url.hostname)
const origin = url.protocol + '//' + domain + (url.port ? ':' + url.port : '')
const packageName = domain
const isPreview = domain === 'localhost' || domain.endsWith('dev.driv.ly')
let rootDomain = 'workflows'
if (isPreview && domain !== 'localhost') {
const parts = domain.split('.')
if (parts.length > 2) {
rootDomain = parts[0]
}
}
let site = domain.endsWith('.do') ? `https://${domain}` : 'https://apis.do'
let from = 'https://dotdo.ai'
if (isPreview) {
site = `${origin}/sites/workflows.do` // Always use workflows.do for preview domains
from = `${origin}/sites`
}
const sdkUrl = sdks.includes(packageName) ? `https://npmjs.com/${packageName}` : 'https://npmjs.com/workflows.do'
return {
name: domain,
description: description || 'Economically valuable work delivered through simple APIs',
home: origin,
login: origin + '/login',
signup: origin + '/signup',
admin: origin + '/admin',
docs: origin + '/docs',
repo: 'https://github.com/drivly/ai',
sdk: sdkUrl,
site, // Use the variable we created
from, // Add the new field
}
}
let _currentRequest: NextRequest | null = null
let _currentContext: ApiContext | null = null
/**
* Creates an API handler with enhanced context
* @param handler - Function to handle the API request
* @returns Next.js API handler function
*/
const createApiHandler = <T = any>(handler: ApiHandler<T>) => {
return async (req: NextRequest, context: { params: Promise<Record<string, string | string[]>> }) => {
try {
let payload: any
let db: PayloadDB
let permissions: any = {}
let user: any = {}
try {
payload = await getPayload({ config })
db = {} as PayloadDB
const collections = payload.collections || {}
for (const collectionName of Object.keys(collections)) {
db[collectionName] = {
find: async (query = {}) => {
return payload.find({
collection: collectionName,
where: query,
})
},
findOne: async (query = {}) => {
const result = await payload.find({
collection: collectionName,
where: query,
limit: 1,
})
return result.docs?.[0] || null
},
get: async (id, query = {}) => {
return payload.findByID({
collection: collectionName,
id,
...query,
})
},
create: async (data, query = {}) => {
return payload.create({
collection: collectionName,
data,
...query,
})
},
update: async (id, data, query = {}) => {
return payload.update({
collection: collectionName,
id,
data,
...query,
})
},
upsert: async (id, data, query = {}) => {
try {
await payload.findByID({
collection: collectionName,
id,
})
return payload.update({
collection: collectionName,
id,
data,
...query,
})
} catch (error) {
return payload.create({
collection: collectionName,
data: { id, ...data },
...query,
})
}
},
set: async (id, data, query = {}) => {
return payload.update({
collection: collectionName,
id,
data,
...query,
})
},
delete: async (id, query = {}) => {
return payload.delete({
collection: collectionName,
id,
...query,
})
},
}
}
try {
// const authResult = await payload.auth.me()
// permissions = authResult?.permissions || {}
// user = authResult?.user || {}
const authResult = await payload.auth(req)
permissions = authResult?.permissions || {}
user = authResult?.user || {}
} catch (authError) {
console.error('Error fetching auth info:', authError)
}
} catch (error) {
console.error('Error initializing payload:', error)
throw error
}
const params = await context.params
const url = new URL(req.url)
const path = url.pathname
const domain = punycode.toUnicode(url.hostname)
const origin = url.protocol + '//' + domain + (url.port ? ':' + url.port : '')
const ctx: ApiContext = {
params,
url,
path,
domain,
origin,
user,
permissions,
payload,
db,
req,
cf: (req as any)._cf, // Include Cloudflare data fetched from middleware
}
_currentRequest = req
_currentContext = ctx
const result = await handler(req, ctx)
_currentRequest = null
_currentContext = null
const enhancedUser = await getUser(req, payload)
let authUser: Record<string, any> = {}
try {
const session = await auth()
authUser = session?.user || {}
} catch (authError) {
console.error('Error fetching AuthJS session:', authError)
}
const mergedUser = {
name: authUser?.name || user?.name || enhancedUser.name,
email: authUser?.email || user?.email || enhancedUser.email,
...enhancedUser,
authenticated: (user?.id || authUser?.id) ? true : false,
admin: (user?.admin || authUser?.role === 'admin') ? true : undefined,
plan: user?.plan || 'Free',
}
const apiDescription =
typeof result === 'object' && result !== null && result && 'api' in result && typeof (result as any).api === 'object' && (result as any).api !== null
? (result as any).api.description
: undefined
const api = getApiHeader(req, apiDescription)
const responseBody = {
api,
...result,
user: mergedUser,
}
return new NextResponse(JSON.stringify(responseBody, null, 2), {
headers: { 'content-type': 'application/json; charset=utf-8' },
})
} catch (error) {
console.error('API Error:', error)
_currentRequest = null
_currentContext = null
try {
getPayload({ config })
.then((payloadInstance) => {
payloadInstance
.create({
collection: 'errors',
data: {
message: error instanceof Error ? error.message : 'Unknown API Error',
stack: error instanceof Error ? error.stack : undefined,
digest: `api-error-${Date.now()}`,
url: req.url,
source: 'api-handler',
},
})
.catch((logError: Error) => console.error('Error logging to errors collection:', logError))
})
.catch((initError: Error) => console.error('Failed to initialize payload for error logging:', initError))
} catch (logError) {
console.error('Failed to log error to collection:', logError)
}
const status = error instanceof Error && 'statusCode' in error ? (error as any).statusCode : 500
const errorMessage = error instanceof Error ? error.message : 'Internal Server Error'
const errorResponseBody = {
error: {
message: errorMessage,
status,
...(process.env.NODE_ENV === 'development' && { stack: error instanceof Error ? error.stack?.split('\n') : undefined }),
}
}
return new NextResponse(JSON.stringify(errorResponseBody, null, 2), {
status,
headers: { 'content-type': 'application/json; charset=utf-8' },
})
}
}
}
// NOTE: Do not import from clickable-apis or simple-payload packages until things stabilize.
// We're using the native implementation directly to avoid dependency issues.
// Later we can extract these functions into those packages if needed.
export const API = createApiHandler
/**
* Creates a standardized error response object
* @param message Error message
* @param status HTTP status code
* @param additionalInfo Additional information to include in the error object
* @returns Standardized error response object
*/
export const createErrorResponse = (
message: string,
status: number,
additionalInfo: Record<string, any> = {}
) => {
return {
error: {
message,
status,
...additionalInfo,
},
}
}
export const modifyQueryString = (param?: string, value?: string | number) => {
if (!param) {
throw new Error('Parameter name is required')
}
if (value === undefined) {
throw new Error('Parameter value is required')
}
if (!_currentRequest) {
throw new Error('No URL provided and no current request available')
}
const url = new URL(_currentRequest.url)
url.searchParams.set(param, value.toString())
return url.toString()
}
/**
* Generates a short unique ID (SQID) for sharing responses
* @param requestId - The original request ID to encode
* @returns A short unique ID for sharing
*/
export const generateShareId = (requestId: string): string => {
return nanoid(10)
}
/**
* Decodes a share ID back to the original request ID
* This would typically involve a database lookup in production
* @param shareId - The share ID to decode
* @returns The original request ID or null if not found
*/
export const getRequestIdFromShareId = async (shareId: string, db: PayloadDB): Promise<string | null> => {
try {
const share = await db.shares?.findOne({ shareId })
return share?.requestId || null
} catch (error) {
console.error('Error retrieving request ID from share ID:', error)
return null
}
}
/**
* Stores a mapping between a share ID and request ID
* @param shareId - The generated share ID
* @param requestId - The original request ID
* @param response - The response data to be shared
* @param db - Database instance
*/
export const storeShareMapping = async (shareId: string, requestId: string, response: Record<string, any>, db: PayloadDB): Promise<void> => {
try {
await db.shares?.create({
shareId,
requestId,
response,
createdAt: new Date(),
})
} catch (error) {
console.error('Error storing share mapping:', error)
}
}
/**
* Generates sharing links for various social platforms
* @param shareId - The share ID to include in the links
* @param title - The title or content summary to share
* @param url - The base URL for sharing (defaults to current domain)
* @returns Object containing sharing links for various platforms
*/
export const generateSharingLinks = (shareId: string, title: string, url?: string): Record<string, string> => {
const baseUrl = url || (_currentRequest ? new URL(_currentRequest.url).origin : 'https://api.do')
const shareUrl = `${baseUrl}/share/${shareId}`
const encodedTitle = encodeURIComponent(title)
const encodedUrl = encodeURIComponent(shareUrl)
return {
url: shareUrl,
twitter: `https://twitter.com/intent/tweet?text=${encodedTitle}&url=${encodedUrl}`,
linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`,
facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`,
email: `mailto:?subject=${encodedTitle}&body=${encodedUrl}`,
sms: `sms:?body=${encodedTitle} ${shareUrl}`,
bluesky: `https://bsky.app/intent/compose?text=${encodedTitle} ${encodedUrl}`,
instagram: `https://www.instagram.com/?url=${encodedUrl}`,
tiktok: `https://www.tiktok.com/upload?url=${encodedUrl}`,
}
}
/**
* Generates pagination links for API responses
* @param request - The NextRequest object
* @param page - Current page number
* @param limit - Items per page
* @param totalItems - Total number of items
* @returns Object containing home, next, and prev links
*/
export const generatePaginationLinks = (request: NextRequest, page: number, limit: number, totalItems: number): { home: string; next?: string; prev?: string } => {
const url = new URL(request.url)
const baseUrl = url.origin + url.pathname
const searchParams = url.searchParams
const links: { home: string; next?: string; prev?: string } = {
home: baseUrl,
}
if (totalItems === limit) {
const nextParams = new URLSearchParams(searchParams)
nextParams.set('page', (page + 1).toString())
links.next = `${baseUrl}?${nextParams.toString()}`
}
if (page > 1) {
const prevParams = new URLSearchParams(searchParams)
prevParams.set('page', (page - 1).toString())
links.prev = `${baseUrl}?${prevParams.toString()}`
}
return links
}
/**
* Generates complete pagination links for API responses including first and last pages
* @param request - The NextRequest object
* @param page - Current page number
* @param limit - Items per page
* @param totalItems - Total number of items
* @param totalPages - Total number of pages
* @returns Object containing home, first, last, next, and prev links
*/
export const generateCompletePaginationLinks = (
request: NextRequest,
page: number,
limit: number,
totalItems: number,
totalPages: number,
): { home: string; first: string; last?: string; next?: string; prev?: string } => {
const baseLinks = generatePaginationLinks(request, page, limit, totalItems)
const url = new URL(request.url)
const baseUrl = url.origin + url.pathname
const searchParams = url.searchParams
const links: {
home: string
first: string
last?: string
next?: string
prev?: string
} = {
...baseLinks,
first: '', // Will be set below
}
const firstParams = new URLSearchParams(searchParams)
firstParams.set('page', '1')
links.first = `${baseUrl}?${firstParams.toString()}`
if (totalPages > 1) {
const lastParams = new URLSearchParams(searchParams)
lastParams.set('page', totalPages.toString())
links.last = `${baseUrl}?${lastParams.toString()}`
}
return links
}
/**
* Generates a function link for a given function name
* @param request - The NextRequest object
* @param functionName - Name of the function
* @returns URL string pointing to the function
*/
export const generateFunctionLink = (request: NextRequest, functionName: string): string => {
const url = new URL(request.url)
return `${url.origin}/functions/${functionName}`
}
/**
* Creates a functions object with function names as keys and links as values
* @param request - The NextRequest object
* @param functions - Array of function objects with name property
* @returns Object with function names as keys and links as values
*/
export const createFunctionsObject = (request: NextRequest, functions: Array<{ name: string; [key: string]: any }> | any): Record<string, string> => {
const functionsObject: Record<string, string> = {}
if (Array.isArray(functions)) {
for (let i = 0; i < functions.length; i++) {
const func = functions[i]
if (func && typeof func === 'object' && func.name) {
functionsObject[func.name] = generateFunctionLink(request, func.name)
}
}
} else if (functions && typeof functions === 'object') {
const keys = Object.keys(functions)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
functionsObject[key] = generateFunctionLink(request, key)
}
}
return functionsObject
}
/**
* Enhances an API response with sharing capabilities
* @param response - The original API response
* @param requestId - The request ID to use for generating the share ID
* @param title - Optional title for the shared content
* @returns The enhanced response with sharing links
*/
export const addSharingToResponse = async <T extends Record<string, any>>(
response: T,
requestId: string,
title?: string,
db?: PayloadDB,
): Promise<T & { share: { id: string; links: Record<string, string> } }> => {
const shareId = generateShareId(requestId)
const shareTitle = title || response.title || 'Check out this AI response'
if (db?.shares) {
await storeShareMapping(shareId, requestId, response, db)
}
return {
...response,
share: {
id: shareId,
links: generateSharingLinks(shareId, shareTitle),
},
}
}
/**
* API handler for the /share/:id route
* Retrieves the original response using the share ID and returns it
* @param params - Object containing the share ID
* @param db - Database instance
* @returns The original response or an error
*/
export const handleShareRequest = async (params: { id: string }, db: PayloadDB): Promise<Record<string, any>> => {
try {
const { id } = params
const share = await db.shares?.findOne({ shareId: id })
if (!share) {
return {
error: {
message: 'Shared content not found',
status: 404
}
}
}
return {
...share.response,
shared: true,
sharedAt: share.createdAt,
}
} catch (error) {
console.error('Error handling share request:', error)
return {
error: {
message: 'Failed to retrieve shared content',
status: 500
}
}
}
}
/**
* Checks if a domain has a "shortcut path"
* A shortcut path is a domain that has a direct .do equivalent
* @param domain - The domain to check
* @returns Boolean indicating if the domain has a shortcut path
*/
const hasShortcutPath = (domain?: string): boolean => {
if (!domain) return false
const baseDomain = domain.replace(/\.do(\.mw|\.gt)?$/, '')
return parentDomains[baseDomain] !== undefined || Object.values(childDomains).some((children) => children.includes(baseDomain))
}
/**
* Formats a URL based on domain type and user preference
* @param path - The relative path (e.g., 'functions')
* @param options - Options for formatting the URL
* @returns Formatted URL string
*/
export const formatUrl = (
path: string,
options: {
origin: string
domain?: string
showDomains?: boolean
defaultDomain?: string
},
): string => {
const { origin, domain, showDomains, defaultDomain } = options
const shouldShowDomains = showDomains ?? (domain === 'apis.do' || hasShortcutPath(domain))
if (shouldShowDomains && defaultDomain) {
let tldVariant = ''
if (domain) {
if (domain.endsWith('.do.gt')) tldVariant = '.gt'
else if (domain.endsWith('.do.mw')) tldVariant = '.mw'
}
const domainWithCorrectTLD = defaultDomain.replace(/\.do$/, `.do${tldVariant}`)
return `https://${domainWithCorrectTLD}`
}
return `${origin}/${path}`
}