-
-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathshared.ts
More file actions
370 lines (323 loc) · 10.3 KB
/
Copy pathshared.ts
File metadata and controls
370 lines (323 loc) · 10.3 KB
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
import type { CSSProperties } from 'react'
import { libraries, type LibraryId } from '~/libraries'
import { composeApplicationStarterInput } from '~/utils/partners'
import {
type ApplicationStarterAnalysis,
sanitizeStarterPrompt,
type ApplicationStarterRequest,
type ApplicationStarterResult,
} from '~/utils/application-starter'
export type StarterTone = 'cyan' | 'emerald' | 'violet'
export type StarterDeployProvider =
| 'cloudflare'
| 'netlify'
| 'railway'
| 'vercel'
export type StarterPackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn'
export type StarterToolchain = 'biome' | 'eslint'
export interface StarterPalette {
button: 'cyan' | 'emerald' | 'purple'
chip: string
chipSelected: string
ring: string
}
export interface ApplicationStarterBuilderIntegration {
applyResult: (result: ApplicationStarterResult) => Promise<boolean>
}
export interface ApplicationStarterAnonymousQuota {
limit: number
remaining: number
resetAt: string
}
export interface ApplicationStarterStatusResponse {
anonymousGenerationQuota: ApplicationStarterAnonymousQuota | null
authenticated: boolean
}
export interface StarterTryLibrary {
description?: string
id: LibraryId
label: string
locked: boolean
tagline: string
textStyle: string
}
export type StarterPartnerButtonStyle = CSSProperties & {
'--starter-partner-border-hover'?: string
'--starter-partner-hover-border-color'?: string
}
const nextJsMigrationPattern =
/migrat(?:e|ing|ion).*(next(?:\.js)?)|(next(?:\.js)?).*(migrat(?:e|ing|ion))/i
const remixMigrationPattern =
/migrat(?:e|ing|ion).*(remix|react[\s-]?router)|(remix|react[\s-]?router).*(migrat(?:e|ing|ion))/i
const migrationRepositoryUrlPattern = /^(https?:\/\/\S+|git@\S+|ssh:\/\/\S+)$/i
export const STARTER_NEXTJS_MIGRATION_GUIDE_URL =
'https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js'
export const STARTER_REMIX_MIGRATION_GUIDE_URL =
'https://tanstack.com/router/latest/docs/guide/how-to/migrate-from-react-router'
export const starterPinnedLibraryIds = [
'start',
'router',
'intent',
'cli',
] as const satisfies Array<LibraryId>
export const starterAddonLibraryIds = [
'query',
'table',
'form',
'store',
'db',
'ai',
'hotkeys',
'pacer',
'virtual',
] as const satisfies Array<LibraryId>
const starterTryLibraryIds = [
...starterPinnedLibraryIds,
...starterAddonLibraryIds,
] as const satisfies Array<LibraryId>
export const starterTryLibraries = starterTryLibraryIds.flatMap((libraryId) => {
const library = libraries.find((candidate) => candidate.id === libraryId)
if (!library) {
return []
}
return [
{
description: library.description,
id: library.id,
label: library.name.replace(/^TanStack\s+/, ''),
locked: starterPinnedLibraryIds.some(
(pinnedLibraryId) => pinnedLibraryId === library.id,
),
tagline: library.tagline,
textStyle: library.textStyle,
},
]
})
export const toneClasses: Record<StarterTone, StarterPalette> = {
cyan: {
button: 'cyan',
chip: 'border-gray-200 bg-white text-gray-600 hover:border-cyan-200 hover:text-cyan-700 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-300 dark:hover:border-cyan-900 dark:hover:text-cyan-200',
chipSelected:
'border-cyan-300 bg-cyan-50 text-cyan-700 dark:border-cyan-800 dark:bg-cyan-950/40 dark:text-cyan-200',
ring: 'focus:ring-cyan-500',
},
emerald: {
button: 'emerald',
chip: 'border-gray-200 bg-white text-gray-600 hover:border-emerald-200 hover:text-emerald-700 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-300 dark:hover:border-emerald-900 dark:hover:text-emerald-200',
chipSelected:
'border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200',
ring: 'focus:ring-emerald-500',
},
violet: {
button: 'purple',
chip: 'border-gray-200 bg-white text-gray-600 hover:border-violet-200 hover:text-violet-700 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-300 dark:hover:border-violet-900 dark:hover:text-violet-200',
chipSelected:
'border-violet-300 bg-violet-50 text-violet-700 dark:border-violet-800 dark:bg-violet-950/40 dark:text-violet-200',
ring: 'focus:ring-violet-500',
},
}
export const starterLoadingPhrases = [
'Charting the route...',
'Smoothing the shoreline...',
'Scanning the horizon...',
'Catching a better breeze...',
'Hoisting a fresh draft...',
'Finding calmer waters...',
]
export function isPinnedStarterLibrary(libraryId: LibraryId) {
return starterPinnedLibraryIds.some(
(pinnedLibraryId) => pinnedLibraryId === libraryId,
)
}
export function isNextJsMigrationInput(input: string) {
return nextJsMigrationPattern.test(input)
}
export function isRemixMigrationInput(input: string) {
return remixMigrationPattern.test(input)
}
export function getStarterMigrationGuideUrl(input: string) {
if (isNextJsMigrationInput(input)) {
return STARTER_NEXTJS_MIGRATION_GUIDE_URL
}
if (isRemixMigrationInput(input)) {
return STARTER_REMIX_MIGRATION_GUIDE_URL
}
return null
}
export function normalizeMigrationRepositoryUrl(value: string) {
return value.trim()
}
export function isValidMigrationRepositoryUrl(value: string) {
return migrationRepositoryUrlPattern.test(value)
}
export function composeStarterInput({
forceRouterOnly = false,
inferredPartners,
input,
migrationRepositoryUrl,
packageManager,
selectedLibraries,
selectedPartners,
toolchain,
}: {
forceRouterOnly?: boolean
inferredPartners: Array<string>
input: string
migrationRepositoryUrl: string
packageManager?: StarterPackageManager
selectedLibraries: Array<LibraryId>
selectedPartners: Array<string>
toolchain?: StarterToolchain
}) {
const composedInput = composeApplicationStarterInput(
input,
selectedPartners,
inferredPartners,
{
forceRouterOnly,
},
)
const normalizedRepositoryUrl = normalizeMigrationRepositoryUrl(
migrationRepositoryUrl,
)
const selectedTryLibraries = starterTryLibraries.filter((library) =>
selectedLibraries.includes(library.id),
)
const selectedAddonLibraries = selectedTryLibraries.filter(
(library) => !library.locked,
)
const libraryInstruction = selectedAddonLibraries.length
? `Include and demonstrate these TanStack libraries in the project: ${selectedTryLibraries
.map((library) => `TanStack ${library.label}`)
.join(', ')}.`
: ''
const packageManagerInstruction = packageManager
? `Use ${packageManager} for package management.`
: ''
const toolchainInstruction = toolchain
? `Use ${toolchain} as the project toolchain.`
: ''
const baseInput = [
composedInput,
libraryInstruction,
packageManagerInstruction,
toolchainInstruction,
]
.filter(Boolean)
.join('\n\n')
if (!isNextJsMigrationInput(input) || !normalizedRepositoryUrl) {
return baseInput
}
return [
baseInput,
'',
`Legacy repository URL: ${normalizedRepositoryUrl}`,
'After scaffolding the new app, clone the legacy project into ./legacy-source and migrate it incrementally into the fresh TanStack app.',
]
.filter(Boolean)
.join('\n')
}
export function colorWithAlpha(color: string | undefined, alpha: number) {
if (!color?.startsWith('#')) {
return undefined
}
const normalized =
color.length === 4
? color
.slice(1)
.split('')
.map((part) => `${part}${part}`)
.join('')
: color.slice(1)
if (normalized.length !== 6) {
return undefined
}
const red = Number.parseInt(normalized.slice(0, 2), 16)
const green = Number.parseInt(normalized.slice(2, 4), 16)
const blue = Number.parseInt(normalized.slice(4, 6), 16)
return `rgba(${red}, ${green}, ${blue}, ${alpha})`
}
export async function resolveApplicationStarter(
request: ApplicationStarterRequest,
) {
const response = await fetch('/api/application-starter/resolve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
if (!response.ok) {
const error = await response.json().catch(() => null)
throw new ApplicationStarterError(
error?.details || error?.error || 'Failed to resolve application starter',
{
code: error?.code,
loginRequired: error?.loginRequired,
retryAfter: error?.retryAfter,
},
)
}
const result = (await response.json()) as ApplicationStarterResult
return {
...result,
prompt: sanitizeStarterPrompt(result.prompt),
}
}
export async function analyzeApplicationStarter(
request: ApplicationStarterRequest,
) {
const response = await fetch('/api/application-starter/resolve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...request,
mode: 'analyze',
}),
})
if (!response.ok) {
const error = await response.json().catch(() => null)
throw new ApplicationStarterError(
error?.details || error?.error || 'Failed to analyze application starter',
{
code: error?.code,
loginRequired: error?.loginRequired,
retryAfter: error?.retryAfter,
},
)
}
return (await response.json()) as ApplicationStarterAnalysis
}
export function isApplicationStarterStatusResponse(
value: unknown,
): value is ApplicationStarterStatusResponse {
if (typeof value !== 'object' || value === null) {
return false
}
const candidate = value as Record<string, unknown>
const quota = candidate.anonymousGenerationQuota
const quotaRecord =
typeof quota === 'object' && quota !== null
? (quota as Record<string, unknown>)
: null
const hasValidQuota =
quota === null ||
(quotaRecord !== null &&
typeof quotaRecord.limit === 'number' &&
typeof quotaRecord.remaining === 'number' &&
typeof quotaRecord.resetAt === 'string')
return typeof candidate.authenticated === 'boolean' && hasValidQuota
}
export class ApplicationStarterError extends Error {
code?: string
loginRequired?: boolean
retryAfter?: number
constructor(
message: string,
options?: { code?: string; loginRequired?: boolean; retryAfter?: number },
) {
super(message)
this.name = 'ApplicationStarterError'
this.code = options?.code
this.loginRequired = options?.loginRequired
this.retryAfter = options?.retryAfter
}
}