@alfredmouelle/create-stack 0.1.1 → 0.2.0
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.
- package/README.md +41 -18
- package/_stack/apps/next-base/.turbo/turbo-typecheck.log +1 -0
- package/_stack/apps/next-base/.vscode/settings.json +35 -0
- package/_stack/apps/next-base/.zed/settings.json +45 -0
- package/_stack/apps/next-base/src/components/ui/spinner.tsx +1 -1
- package/_stack/apps/next-base/src/emails/components/components.tsx +2 -2
- package/_stack/apps/next-base/src/emails/components/context.tsx +1 -1
- package/_stack/apps/next-base/src/emails/components/theme.ts +6 -7
- package/_stack/apps/next-base/src/env.ts +2 -3
- package/_stack/apps/next-base/src/lib/date.ts +1 -1
- package/_stack/apps/next-base/src/server/auth/guards.ts +1 -1
- package/_stack/apps/next-base/src/server/better-auth/config.ts +1 -1
- package/_stack/apps/next-base/src/server/better-auth/server.ts +2 -2
- package/_stack/apps/next-base/src/server/db/schemas/index.ts +1 -1
- package/_stack/apps/next-base/src/server/db/seed.ts +2 -2
- package/_stack/apps/next-base/src/server/email/adapters/resend/index.ts +3 -3
- package/_stack/apps/next-base/src/server/email/core/address.ts +3 -3
- package/_stack/apps/next-base/src/server/email/core/port.ts +13 -20
- package/_stack/apps/next-base/src/server/email/core/render.ts +2 -2
- package/_stack/apps/next-base/src/server/email/factory.ts +7 -9
- package/_stack/apps/next-base/src/server/email/index.ts +1 -1
- package/_stack/apps/next-base/src/trpc/react.tsx +2 -2
- package/_stack/apps/next-base/src/trpc/server.ts +1 -1
- package/_stack/apps/tanstack-base/.turbo/turbo-typecheck.log +1 -0
- package/_stack/apps/tanstack-base/.vscode/settings.json +35 -0
- package/_stack/apps/tanstack-base/.zed/settings.json +45 -0
- package/_stack/apps/tanstack-base/src/components/form/text-field.tsx +1 -1
- package/_stack/apps/tanstack-base/src/components/ui/spinner.tsx +1 -1
- package/_stack/apps/tanstack-base/src/emails/components/components.tsx +2 -2
- package/_stack/apps/tanstack-base/src/emails/components/context.tsx +1 -1
- package/_stack/apps/tanstack-base/src/emails/components/theme.ts +6 -7
- package/_stack/apps/tanstack-base/src/env.ts +2 -6
- package/_stack/apps/tanstack-base/src/lib/date.ts +1 -1
- package/_stack/apps/tanstack-base/src/routes/__root.tsx +1 -1
- package/_stack/apps/tanstack-base/src/routes/_authed.tsx +1 -4
- package/_stack/apps/tanstack-base/src/routes/api/auth/$.ts +1 -1
- package/_stack/apps/tanstack-base/src/routes/api.trpc.$.tsx +1 -2
- package/_stack/apps/tanstack-base/src/server/better-auth/config.ts +1 -1
- package/_stack/apps/tanstack-base/src/server/better-auth/session.ts +6 -7
- package/_stack/apps/tanstack-base/src/server/db/schemas/index.ts +1 -1
- package/_stack/apps/tanstack-base/src/server/db/seed.ts +2 -2
- package/_stack/apps/tanstack-base/src/server/email/adapters/resend/index.ts +3 -3
- package/_stack/apps/tanstack-base/src/server/email/core/address.ts +3 -3
- package/_stack/apps/tanstack-base/src/server/email/core/port.ts +12 -22
- package/_stack/apps/tanstack-base/src/server/email/core/render.ts +1 -1
- package/_stack/apps/tanstack-base/src/server/email/factory.ts +7 -8
- package/_stack/apps/tanstack-base/src/server/email/index.ts +1 -1
- package/_stack/packages/analytics/package.json +26 -0
- package/_stack/packages/analytics/src/adapters/noop/index.ts +12 -0
- package/_stack/packages/analytics/src/adapters/plausible/config.ts +10 -0
- package/_stack/packages/analytics/src/adapters/plausible/index.ts +94 -0
- package/_stack/packages/analytics/src/adapters/posthog/config.ts +7 -0
- package/_stack/packages/analytics/src/adapters/posthog/index.ts +50 -0
- package/_stack/packages/analytics/src/core/port.ts +30 -0
- package/_stack/packages/analytics/src/index.ts +17 -0
- package/_stack/packages/cache/package.json +25 -0
- package/_stack/packages/cache/src/adapters/memory/index.ts +51 -0
- package/_stack/packages/cache/src/adapters/redis/config.ts +8 -0
- package/_stack/packages/cache/src/adapters/redis/index.ts +73 -0
- package/_stack/packages/cache/src/core/port.ts +29 -0
- package/_stack/packages/cache/src/core/wrap.ts +20 -0
- package/_stack/packages/cache/src/index.ts +12 -0
- package/_stack/packages/error-tracking/package.json +25 -0
- package/_stack/packages/error-tracking/src/adapters/console/index.ts +43 -0
- package/_stack/packages/error-tracking/src/adapters/sentry/config.ts +8 -0
- package/_stack/packages/error-tracking/src/adapters/sentry/index.ts +72 -0
- package/_stack/packages/error-tracking/src/core/port.ts +39 -0
- package/_stack/packages/error-tracking/src/index.ts +14 -0
- package/_stack/packages/http/package.json +20 -0
- package/_stack/packages/http/src/api.ts +373 -0
- package/_stack/packages/http/src/index.ts +14 -0
- package/_stack/packages/http/src/responses.ts +25 -0
- package/_stack/packages/http/src/types.ts +9 -0
- package/_stack/packages/jobs/package.json +27 -0
- package/_stack/packages/jobs/src/adapters/inngest/config.ts +8 -0
- package/_stack/packages/jobs/src/adapters/inngest/index.ts +93 -0
- package/_stack/packages/jobs/src/adapters/memory/index.ts +31 -0
- package/_stack/packages/jobs/src/adapters/trigger/config.ts +8 -0
- package/_stack/packages/jobs/src/adapters/trigger/index.ts +85 -0
- package/_stack/packages/jobs/src/core/port.ts +37 -0
- package/_stack/packages/jobs/src/index.ts +23 -0
- package/_stack/packages/logger/package.json +25 -0
- package/_stack/packages/logger/src/adapters/console/config.ts +7 -0
- package/_stack/packages/logger/src/adapters/console/index.ts +69 -0
- package/_stack/packages/logger/src/adapters/pino/index.ts +54 -0
- package/_stack/packages/logger/src/core/port.ts +21 -0
- package/_stack/packages/logger/src/index.ts +12 -0
- package/_stack/packages/mailer/src/adapters/brevo/index.ts +3 -3
- package/_stack/packages/mailer/src/adapters/resend/index.ts +3 -3
- package/_stack/packages/mailer/src/adapters/ses/config.ts +3 -3
- package/_stack/packages/mailer/src/adapters/ses/index.ts +4 -5
- package/_stack/packages/storage/package.json +27 -0
- package/_stack/packages/storage/src/adapters/gcs/config.ts +8 -0
- package/_stack/packages/storage/src/adapters/gcs/index.ts +111 -0
- package/_stack/packages/storage/src/adapters/local/config.ts +8 -0
- package/_stack/packages/storage/src/adapters/local/index.ts +78 -0
- package/_stack/packages/storage/src/adapters/r2/config.ts +8 -0
- package/_stack/packages/storage/src/adapters/r2/index.ts +39 -0
- package/_stack/packages/storage/src/adapters/s3/config.ts +11 -0
- package/_stack/packages/storage/src/adapters/s3/index.ts +143 -0
- package/_stack/packages/storage/src/core/port.ts +41 -0
- package/_stack/packages/storage/src/index.ts +21 -0
- package/index.mjs +89 -55
- package/lib/build.mjs +21 -11
- package/lib/capabilities.mjs +375 -0
- package/lib/env.mjs +26 -6
- package/lib/foundations.mjs +35 -0
- package/lib/identity.mjs +4 -5
- package/lib/mailer.mjs +9 -13
- package/lib/paths.mjs +15 -0
- package/lib/scaffold.mjs +12 -11
- package/lib/strip.mjs +9 -24
- package/lib/util.mjs +8 -9
- package/package.json +1 -1
- package/_stack/packages/mailer/capability.json +0 -28
- package/_stack/patterns/README.md +0 -58
- package/_stack/patterns/_baseline/env.ts +0 -31
- package/_stack/patterns/_baseline/tsconfig.json +0 -27
- package/_stack/patterns/better-auth/pattern.json +0 -73
- package/_stack/patterns/better-auth-next/pattern.json +0 -76
- package/_stack/patterns/data-table/pattern.json +0 -43
- package/_stack/patterns/drizzle/pattern.json +0 -61
- package/_stack/patterns/trpc/pattern.json +0 -61
- package/_stack/patterns/trpc-next/pattern.json +0 -64
- package/lib/manifests.mjs +0 -61
- /package/{_stack/patterns/_baseline → templates}/README-author.md +0 -0
- /package/{_stack/patterns/_baseline → templates}/biome.jsonc +0 -0
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
export type ApiFetchMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'
|
|
2
|
+
|
|
3
|
+
export type ApiParseMode = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'none'
|
|
4
|
+
|
|
5
|
+
export type QueryValue = string | number | boolean | null | undefined
|
|
6
|
+
|
|
7
|
+
export type QueryParams = Record<string, QueryValue | QueryValue[]> | URLSearchParams
|
|
8
|
+
|
|
9
|
+
export interface ApiFetchOptions {
|
|
10
|
+
method?: ApiFetchMethod
|
|
11
|
+
baseUrl?: string
|
|
12
|
+
query?: QueryParams
|
|
13
|
+
body?: unknown
|
|
14
|
+
headers?: HeadersInit
|
|
15
|
+
signal?: AbortSignal
|
|
16
|
+
timeoutMs?: number
|
|
17
|
+
parseAs?: ApiParseMode
|
|
18
|
+
credentials?: RequestCredentials
|
|
19
|
+
cache?: RequestCache
|
|
20
|
+
init?: RequestInit
|
|
21
|
+
/** Inject custom fetch (mock in tests, scoped client in adapters). */
|
|
22
|
+
fetchImpl?: typeof globalThis.fetch
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class ApiFetchError extends Error {
|
|
26
|
+
readonly status: number
|
|
27
|
+
readonly statusText: string
|
|
28
|
+
readonly url: string
|
|
29
|
+
readonly method: string
|
|
30
|
+
readonly body: unknown
|
|
31
|
+
readonly response?: Response
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
message: string,
|
|
35
|
+
details: {
|
|
36
|
+
status: number
|
|
37
|
+
statusText: string
|
|
38
|
+
url: string
|
|
39
|
+
method: string
|
|
40
|
+
body?: unknown
|
|
41
|
+
response?: Response
|
|
42
|
+
cause?: unknown
|
|
43
|
+
},
|
|
44
|
+
) {
|
|
45
|
+
super(message, { cause: details.cause })
|
|
46
|
+
this.name = 'ApiFetchError'
|
|
47
|
+
this.status = details.status
|
|
48
|
+
this.statusText = details.statusText
|
|
49
|
+
this.url = details.url
|
|
50
|
+
this.method = details.method
|
|
51
|
+
this.body = details.body
|
|
52
|
+
this.response = details.response
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
get isNetworkError(): boolean {
|
|
56
|
+
return this.status === 0
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
get isTimeout(): boolean {
|
|
60
|
+
return this.status === 408 || this.status === 504
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
get serverMessage(): string | undefined {
|
|
64
|
+
const body = this.body
|
|
65
|
+
if (typeof body === 'string') return body.trim() || undefined
|
|
66
|
+
if (body && typeof body === 'object') {
|
|
67
|
+
const record = body as Record<string, unknown>
|
|
68
|
+
for (const key of ['error', 'message', 'detail']) {
|
|
69
|
+
const value = record[key]
|
|
70
|
+
if (typeof value === 'string' && value.trim()) return value
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return undefined
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function isApiFetchError(error: unknown): error is ApiFetchError {
|
|
78
|
+
return error instanceof ApiFetchError
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export class ApiParseError extends Error {
|
|
82
|
+
readonly url: string
|
|
83
|
+
readonly method: string
|
|
84
|
+
readonly status: number
|
|
85
|
+
readonly raw: string
|
|
86
|
+
readonly response: Response
|
|
87
|
+
|
|
88
|
+
constructor(
|
|
89
|
+
message: string,
|
|
90
|
+
details: {
|
|
91
|
+
url: string
|
|
92
|
+
method: string
|
|
93
|
+
status: number
|
|
94
|
+
raw: string
|
|
95
|
+
response: Response
|
|
96
|
+
cause?: unknown
|
|
97
|
+
},
|
|
98
|
+
) {
|
|
99
|
+
super(message, { cause: details.cause })
|
|
100
|
+
this.name = 'ApiParseError'
|
|
101
|
+
this.url = details.url
|
|
102
|
+
this.method = details.method
|
|
103
|
+
this.status = details.status
|
|
104
|
+
this.raw = details.raw
|
|
105
|
+
this.response = details.response
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function isApiParseError(error: unknown): error is ApiParseError {
|
|
110
|
+
return error instanceof ApiParseError
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isCancellation(error: unknown): boolean {
|
|
114
|
+
return (
|
|
115
|
+
error instanceof DOMException && (error.name === 'AbortError' || error.name === 'TimeoutError')
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isTimeoutAbort(error: unknown): boolean {
|
|
120
|
+
return error instanceof DOMException && error.name === 'TimeoutError'
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function timeoutError(
|
|
124
|
+
error: unknown,
|
|
125
|
+
url: string,
|
|
126
|
+
method: string,
|
|
127
|
+
response?: Response,
|
|
128
|
+
): ApiFetchError {
|
|
129
|
+
return new ApiFetchError(`${method} ${url} timed out`, {
|
|
130
|
+
status: 408,
|
|
131
|
+
statusText: 'Request Timeout',
|
|
132
|
+
url,
|
|
133
|
+
method,
|
|
134
|
+
response,
|
|
135
|
+
cause: error,
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isRawBody(body: unknown): body is BodyInit {
|
|
140
|
+
return (
|
|
141
|
+
typeof body === 'string' ||
|
|
142
|
+
body instanceof FormData ||
|
|
143
|
+
body instanceof URLSearchParams ||
|
|
144
|
+
body instanceof Blob ||
|
|
145
|
+
body instanceof ArrayBuffer ||
|
|
146
|
+
ArrayBuffer.isView(body) ||
|
|
147
|
+
(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream)
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function toSearchParams(query: QueryParams): URLSearchParams {
|
|
152
|
+
if (query instanceof URLSearchParams) return query
|
|
153
|
+
const params = new URLSearchParams()
|
|
154
|
+
for (const [key, value] of Object.entries(query)) {
|
|
155
|
+
if (value === null || value === undefined) continue
|
|
156
|
+
const values = Array.isArray(value) ? value : [value]
|
|
157
|
+
for (const item of values) {
|
|
158
|
+
if (item === null || item === undefined) continue
|
|
159
|
+
params.append(key, String(item))
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return params
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function buildUrl(
|
|
166
|
+
path: string,
|
|
167
|
+
baseUrl: string | undefined,
|
|
168
|
+
query: QueryParams | undefined,
|
|
169
|
+
): string {
|
|
170
|
+
const isAbsolute = /^[a-z][a-z\d+.-]*:\/\//i.test(path)
|
|
171
|
+
const base = baseUrl ? baseUrl.replace(/\/+$/, '') : ''
|
|
172
|
+
let url = isAbsolute || !base ? path : `${base}${path.startsWith('/') ? path : `/${path}`}`
|
|
173
|
+
|
|
174
|
+
if (query) {
|
|
175
|
+
const qs = toSearchParams(query).toString()
|
|
176
|
+
if (qs) url += `${url.includes('?') ? '&' : '?'}${qs}`
|
|
177
|
+
}
|
|
178
|
+
return url
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function resolveSignal(
|
|
182
|
+
signal: AbortSignal | undefined,
|
|
183
|
+
timeoutMs: number | undefined,
|
|
184
|
+
): AbortSignal | undefined {
|
|
185
|
+
if (timeoutMs === undefined) return signal
|
|
186
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
187
|
+
if (!signal) return timeout
|
|
188
|
+
if (typeof AbortSignal.any === 'function') {
|
|
189
|
+
return AbortSignal.any([signal, timeout])
|
|
190
|
+
}
|
|
191
|
+
return signal
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function inferParseMode(response: Response): ApiParseMode {
|
|
195
|
+
const contentType = response.headers.get('content-type') ?? ''
|
|
196
|
+
if (contentType.includes('application/json') || contentType.includes('+json')) {
|
|
197
|
+
return 'json'
|
|
198
|
+
}
|
|
199
|
+
if (!contentType || contentType.startsWith('text/')) return 'text'
|
|
200
|
+
return 'blob'
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function parseResponse<T>(
|
|
204
|
+
response: Response,
|
|
205
|
+
parseAs: ApiParseMode | undefined,
|
|
206
|
+
url: string,
|
|
207
|
+
method: string,
|
|
208
|
+
): Promise<T> {
|
|
209
|
+
if (parseAs === 'none' || response.status === 204 || response.status === 205) {
|
|
210
|
+
return undefined as T
|
|
211
|
+
}
|
|
212
|
+
const mode = parseAs ?? inferParseMode(response)
|
|
213
|
+
try {
|
|
214
|
+
switch (mode) {
|
|
215
|
+
case 'json': {
|
|
216
|
+
const text = await response.text()
|
|
217
|
+
if (!text) return undefined as T
|
|
218
|
+
try {
|
|
219
|
+
return JSON.parse(text) as T
|
|
220
|
+
} catch (error) {
|
|
221
|
+
throw new ApiParseError(`${method} ${url}: invalid JSON response`, {
|
|
222
|
+
url,
|
|
223
|
+
method,
|
|
224
|
+
status: response.status,
|
|
225
|
+
raw: text,
|
|
226
|
+
response,
|
|
227
|
+
cause: error,
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
case 'text':
|
|
232
|
+
return (await response.text()) as T
|
|
233
|
+
case 'blob':
|
|
234
|
+
return (await response.blob()) as T
|
|
235
|
+
case 'arrayBuffer':
|
|
236
|
+
return (await response.arrayBuffer()) as T
|
|
237
|
+
default:
|
|
238
|
+
return undefined as T
|
|
239
|
+
}
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (error instanceof ApiParseError) throw error
|
|
242
|
+
if (isTimeoutAbort(error)) throw timeoutError(error, url, method, response)
|
|
243
|
+
if (isCancellation(error)) throw error
|
|
244
|
+
throw new ApiParseError(`${method} ${url}: failed to read response body`, {
|
|
245
|
+
url,
|
|
246
|
+
method,
|
|
247
|
+
status: response.status,
|
|
248
|
+
raw: '',
|
|
249
|
+
response,
|
|
250
|
+
cause: error,
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function parseErrorBody(response: Response): Promise<unknown> {
|
|
256
|
+
try {
|
|
257
|
+
const text = await response.text()
|
|
258
|
+
if (!text) return undefined
|
|
259
|
+
const contentType = response.headers.get('content-type') ?? ''
|
|
260
|
+
if (contentType.includes('json')) {
|
|
261
|
+
try {
|
|
262
|
+
return JSON.parse(text)
|
|
263
|
+
} catch {
|
|
264
|
+
return text
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return text
|
|
268
|
+
} catch {
|
|
269
|
+
return undefined
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function buildRequestHeaders(
|
|
274
|
+
headers: HeadersInit | undefined,
|
|
275
|
+
initHeaders: HeadersInit | undefined,
|
|
276
|
+
parseAs: ApiParseMode | undefined,
|
|
277
|
+
): Headers {
|
|
278
|
+
const requestHeaders = new Headers(initHeaders)
|
|
279
|
+
if (headers) {
|
|
280
|
+
new Headers(headers).forEach((value, key) => {
|
|
281
|
+
requestHeaders.set(key, value)
|
|
282
|
+
})
|
|
283
|
+
}
|
|
284
|
+
if (!requestHeaders.has('Accept') && parseAs !== 'blob' && parseAs !== 'arrayBuffer') {
|
|
285
|
+
requestHeaders.set('Accept', 'application/json')
|
|
286
|
+
}
|
|
287
|
+
return requestHeaders
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function buildRequestBody(
|
|
291
|
+
body: unknown,
|
|
292
|
+
method: ApiFetchMethod,
|
|
293
|
+
requestHeaders: Headers,
|
|
294
|
+
): BodyInit | undefined {
|
|
295
|
+
const sendsBody = body !== undefined && body !== null
|
|
296
|
+
if (!sendsBody || method === 'GET' || method === 'HEAD') return undefined
|
|
297
|
+
if (isRawBody(body)) return body
|
|
298
|
+
if (!requestHeaders.has('Content-Type')) {
|
|
299
|
+
requestHeaders.set('Content-Type', 'application/json')
|
|
300
|
+
}
|
|
301
|
+
return JSON.stringify(body)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Typed `fetch` wrapper: URL/query building, JSON encoding, timeouts,
|
|
306
|
+
* content-negotiated parsing, `ApiFetchError`/`ApiParseError` on failure.
|
|
307
|
+
* Non-2xx throws.
|
|
308
|
+
*/
|
|
309
|
+
export async function apiFetch<T = unknown>(
|
|
310
|
+
path: string,
|
|
311
|
+
options: ApiFetchOptions = {},
|
|
312
|
+
): Promise<T> {
|
|
313
|
+
const {
|
|
314
|
+
method = 'GET',
|
|
315
|
+
baseUrl,
|
|
316
|
+
query,
|
|
317
|
+
body,
|
|
318
|
+
headers,
|
|
319
|
+
signal,
|
|
320
|
+
timeoutMs,
|
|
321
|
+
parseAs,
|
|
322
|
+
credentials,
|
|
323
|
+
cache,
|
|
324
|
+
init,
|
|
325
|
+
fetchImpl,
|
|
326
|
+
} = options
|
|
327
|
+
|
|
328
|
+
const doFetch = fetchImpl ?? globalThis.fetch
|
|
329
|
+
const url = buildUrl(path, baseUrl, query)
|
|
330
|
+
const requestHeaders = buildRequestHeaders(headers, init?.headers, parseAs)
|
|
331
|
+
const requestBody = buildRequestBody(body, method, requestHeaders)
|
|
332
|
+
|
|
333
|
+
const userSignal = signal ?? init?.signal ?? undefined
|
|
334
|
+
const requestInit: RequestInit = { ...init }
|
|
335
|
+
requestInit.method = method
|
|
336
|
+
requestInit.headers = requestHeaders
|
|
337
|
+
requestInit.signal = resolveSignal(userSignal, timeoutMs)
|
|
338
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
339
|
+
requestInit.body = undefined
|
|
340
|
+
} else if (requestBody !== undefined) {
|
|
341
|
+
requestInit.body = requestBody
|
|
342
|
+
}
|
|
343
|
+
if (credentials !== undefined) requestInit.credentials = credentials
|
|
344
|
+
if (cache !== undefined) requestInit.cache = cache
|
|
345
|
+
|
|
346
|
+
let response: Response
|
|
347
|
+
try {
|
|
348
|
+
response = await doFetch(url, requestInit)
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (isTimeoutAbort(error)) throw timeoutError(error, url, method)
|
|
351
|
+
if (isCancellation(error)) throw error
|
|
352
|
+
throw new ApiFetchError(`${method} ${url} failed: network error`, {
|
|
353
|
+
status: 0,
|
|
354
|
+
statusText: '',
|
|
355
|
+
url,
|
|
356
|
+
method,
|
|
357
|
+
cause: error,
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (!response.ok) {
|
|
362
|
+
throw new ApiFetchError(`${method} ${url} → ${response.status} ${response.statusText}`.trim(), {
|
|
363
|
+
status: response.status,
|
|
364
|
+
statusText: response.statusText,
|
|
365
|
+
url,
|
|
366
|
+
method,
|
|
367
|
+
body: await parseErrorBody(response),
|
|
368
|
+
response,
|
|
369
|
+
})
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return parseResponse<T>(response, parseAs, url, method)
|
|
373
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export {
|
|
2
|
+
ApiFetchError,
|
|
3
|
+
type ApiFetchMethod,
|
|
4
|
+
type ApiFetchOptions,
|
|
5
|
+
ApiParseError,
|
|
6
|
+
type ApiParseMode,
|
|
7
|
+
apiFetch,
|
|
8
|
+
isApiFetchError,
|
|
9
|
+
isApiParseError,
|
|
10
|
+
type QueryParams,
|
|
11
|
+
type QueryValue,
|
|
12
|
+
} from './api.js'
|
|
13
|
+
export { error, json, noContent, text } from './responses.js'
|
|
14
|
+
export type { FetchHandler, WebhookHandler } from './types.js'
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** JSON `Response` with correct content-type. */
|
|
2
|
+
export function json(data: unknown, init: ResponseInit = {}): Response {
|
|
3
|
+
return new Response(JSON.stringify(data), {
|
|
4
|
+
...init,
|
|
5
|
+
headers: { 'content-type': 'application/json', ...init.headers },
|
|
6
|
+
})
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** `204 No Content` — canonical webhook ack. */
|
|
10
|
+
export function noContent(init: ResponseInit = {}): Response {
|
|
11
|
+
return new Response(null, { status: 204, ...init })
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Plain-text `Response`. */
|
|
15
|
+
export function text(body: string, init: ResponseInit = {}): Response {
|
|
16
|
+
return new Response(body, {
|
|
17
|
+
...init,
|
|
18
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', ...init.headers },
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** JSON error envelope. */
|
|
23
|
+
export function error(message: string, status = 400, init: ResponseInit = {}): Response {
|
|
24
|
+
return json({ error: message }, { ...init, status })
|
|
25
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web Fetch `Request -> Response` handler. Next.js route handlers and TanStack
|
|
3
|
+
* Start server routes both speak it, so HTTP surfaces (webhooks, callbacks)
|
|
4
|
+
* target this type; mounting is a one-line shim per framework.
|
|
5
|
+
*/
|
|
6
|
+
export type FetchHandler = (request: Request) => Response | Promise<Response>
|
|
7
|
+
|
|
8
|
+
/** Alias of {@link FetchHandler}; documents intent at call sites. */
|
|
9
|
+
export type WebhookHandler = FetchHandler
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@alfredmouelle/jobs",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"build": "tsdown",
|
|
11
|
+
"test": "vitest run",
|
|
12
|
+
"test:watch": "vitest",
|
|
13
|
+
"typecheck": "tsc --noEmit"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@alfredmouelle/http": "workspace:*",
|
|
17
|
+
"@trigger.dev/sdk": "^4.4.6",
|
|
18
|
+
"inngest": "^4.7.0",
|
|
19
|
+
"valibot": "^1.4.1"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/node": "^22.10.2",
|
|
23
|
+
"tsdown": "^0.22.3",
|
|
24
|
+
"typescript": "^5.9.3",
|
|
25
|
+
"vitest": "^4.1.9"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { FetchHandler } from '@alfredmouelle/http'
|
|
2
|
+
import { Inngest } from 'inngest'
|
|
3
|
+
import * as v from 'valibot'
|
|
4
|
+
import type { JobDefinition, JobEvent, JobsPort } from '../../core/port.js'
|
|
5
|
+
import { JobsError } from '../../core/port.js'
|
|
6
|
+
import { InngestConfigSchema } from './config.js'
|
|
7
|
+
|
|
8
|
+
/** Opaque Inngest function from `createFunction`. */
|
|
9
|
+
export type InngestFunction = unknown
|
|
10
|
+
|
|
11
|
+
/** Structural view of the Inngest client; real `Inngest` satisfies it, tests mock it. */
|
|
12
|
+
export interface InngestLike {
|
|
13
|
+
send(payload: { name: string; data: unknown }): Promise<unknown>
|
|
14
|
+
createFunction(
|
|
15
|
+
config: { id: string },
|
|
16
|
+
trigger: { event: string },
|
|
17
|
+
handler: (ctx: { event: { name: string; data: unknown } }) => Promise<void> | void,
|
|
18
|
+
): InngestFunction
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface InngestAdapterOptions {
|
|
22
|
+
/** Inngest app id (`new Inngest({ id })`). */
|
|
23
|
+
id: string
|
|
24
|
+
/** Inject custom/mock client. Defaults to real `Inngest`. */
|
|
25
|
+
client?: InngestLike
|
|
26
|
+
/** Event key for sending in production. */
|
|
27
|
+
eventKey?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface InngestJobsAdapter extends JobsPort {
|
|
31
|
+
/** Functions from `defineJob`, for Inngest's `serve`. */
|
|
32
|
+
readonly functions: InngestFunction[]
|
|
33
|
+
/** Underlying client for advanced use (steps, cron, concurrency, …). */
|
|
34
|
+
readonly client: InngestLike
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function inngestAdapter(options: InngestAdapterOptions): InngestJobsAdapter {
|
|
38
|
+
// Validate early: bad id fails at construction, not trigger().
|
|
39
|
+
const config = v.parse(InngestConfigSchema, { id: options.id, eventKey: options.eventKey })
|
|
40
|
+
const client: InngestLike =
|
|
41
|
+
options.client ??
|
|
42
|
+
(new Inngest({ id: config.id, eventKey: config.eventKey }) as unknown as InngestLike)
|
|
43
|
+
|
|
44
|
+
const functions: InngestFunction[] = []
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
name: 'inngest',
|
|
48
|
+
functions,
|
|
49
|
+
client,
|
|
50
|
+
defineJob<T>(def: JobDefinition<T>): JobDefinition<T> {
|
|
51
|
+
const fn = client.createFunction({ id: def.id }, { event: def.event }, ({ event }) =>
|
|
52
|
+
def.handler(event as JobEvent<T>),
|
|
53
|
+
)
|
|
54
|
+
functions.push(fn)
|
|
55
|
+
return def
|
|
56
|
+
},
|
|
57
|
+
async trigger<T>(event: JobEvent<T>): Promise<void> {
|
|
58
|
+
try {
|
|
59
|
+
await client.send({ name: event.name, data: event.data })
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
throw new JobsError('Failed to send event to Inngest', { adapter: 'inngest', cause })
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Collect functions for `serve({ client, functions })`. */
|
|
68
|
+
export function inngestFunctions(adapter: InngestJobsAdapter): InngestFunction[] {
|
|
69
|
+
return adapter.functions
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Inngest's framework-agnostic `serve` (e.g. `inngest/edge`). Loosely typed so
|
|
74
|
+
* the real `serve` (richer options than our `InngestLike`) is accepted.
|
|
75
|
+
*/
|
|
76
|
+
// biome-ignore lint/suspicious/noExplicitAny: accepts the real serve whose options are richer than InngestLike
|
|
77
|
+
export type InngestServe = (options: any) => FetchHandler
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* {@link FetchHandler} serving the adapter's functions. Pass Inngest's `serve`
|
|
81
|
+
* (from `inngest/edge`); the handler mounts in Next.js or TanStack Start unchanged.
|
|
82
|
+
*/
|
|
83
|
+
export function inngestServeHandler<TServe extends InngestServe>(
|
|
84
|
+
adapter: InngestJobsAdapter,
|
|
85
|
+
serve: TServe,
|
|
86
|
+
options: { signingKey?: string } = {},
|
|
87
|
+
): FetchHandler {
|
|
88
|
+
return serve({
|
|
89
|
+
client: adapter.client,
|
|
90
|
+
functions: adapter.functions,
|
|
91
|
+
signingKey: options.signingKey,
|
|
92
|
+
} as Parameters<TServe>[0])
|
|
93
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { JobDefinition, JobEvent, JobsPort } from '../../core/port.js'
|
|
2
|
+
|
|
3
|
+
export interface MemoryJobsAdapter extends JobsPort {
|
|
4
|
+
/** Registered jobs, keyed by subscribed event name. */
|
|
5
|
+
readonly jobs: ReadonlyMap<string, JobDefinition[]>
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* In-process jobs adapter for dev/tests. `trigger` runs every matching handler
|
|
10
|
+
* inline (awaiting async) — no queue, no network. Unit-test jobs without Inngest.
|
|
11
|
+
*/
|
|
12
|
+
export function memoryAdapter(): MemoryJobsAdapter {
|
|
13
|
+
const jobs = new Map<string, JobDefinition[]>()
|
|
14
|
+
|
|
15
|
+
return {
|
|
16
|
+
name: 'memory',
|
|
17
|
+
jobs,
|
|
18
|
+
defineJob<T>(def: JobDefinition<T>): JobDefinition<T> {
|
|
19
|
+
const existing = jobs.get(def.event) ?? []
|
|
20
|
+
existing.push(def as JobDefinition)
|
|
21
|
+
jobs.set(def.event, existing)
|
|
22
|
+
return def
|
|
23
|
+
},
|
|
24
|
+
async trigger<T>(event: JobEvent<T>): Promise<void> {
|
|
25
|
+
const handlers = jobs.get(event.name) ?? []
|
|
26
|
+
for (const def of handlers) {
|
|
27
|
+
await def.handler(event)
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import * as v from 'valibot'
|
|
2
|
+
|
|
3
|
+
export const TriggerDevConfigSchema = v.object({
|
|
4
|
+
/** Trigger auth key. Falls back to `TRIGGER_SECRET_KEY`. */
|
|
5
|
+
secretKey: v.optional(v.string()),
|
|
6
|
+
})
|
|
7
|
+
|
|
8
|
+
export type TriggerDevConfig = v.InferOutput<typeof TriggerDevConfigSchema>
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { configure, task, tasks } from '@trigger.dev/sdk'
|
|
2
|
+
import * as v from 'valibot'
|
|
3
|
+
import type { JobDefinition, JobEvent, JobsPort } from '../../core/port.js'
|
|
4
|
+
import { JobsError } from '../../core/port.js'
|
|
5
|
+
import { TriggerDevConfigSchema } from './config.js'
|
|
6
|
+
|
|
7
|
+
/** Opaque Trigger.dev task from `task()`. */
|
|
8
|
+
export type TriggerTask = unknown
|
|
9
|
+
|
|
10
|
+
/** Structural view of the Trigger.dev SDK; real `task`/`tasks.trigger` satisfy it, tests mock it. */
|
|
11
|
+
export interface TriggerDevLike {
|
|
12
|
+
task(config: { id: string; run: (payload: unknown) => Promise<void> | void }): TriggerTask
|
|
13
|
+
trigger(id: string, payload: unknown): Promise<unknown>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface TriggerDevAdapterOptions {
|
|
17
|
+
/** Trigger auth key. Defaults to `TRIGGER_SECRET_KEY`. */
|
|
18
|
+
secretKey?: string
|
|
19
|
+
/** Inject custom/mock SDK. Defaults to real `@trigger.dev/sdk`. */
|
|
20
|
+
client?: TriggerDevLike
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface TriggerDevJobsAdapter extends JobsPort {
|
|
24
|
+
/** Tasks from `defineJob`, to re-export from your Trigger.dev `dirs`. */
|
|
25
|
+
readonly tasks: TriggerTask[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Bridge real SDK to {@link TriggerDevLike}; richer signatures narrowed here. */
|
|
29
|
+
function defaultClient(secretKey?: string): TriggerDevLike {
|
|
30
|
+
if (secretKey) configure({ secretKey })
|
|
31
|
+
return {
|
|
32
|
+
task: task as unknown as TriggerDevLike['task'],
|
|
33
|
+
trigger: (id, payload) =>
|
|
34
|
+
(tasks.trigger as (id: string, payload: unknown) => Promise<unknown>)(id, payload),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Trigger.dev jobs adapter. Each {@link JobDefinition} becomes a task; `trigger`
|
|
40
|
+
* routes an event to every task subscribed to its `name`.
|
|
41
|
+
*
|
|
42
|
+
* No event bus (tasks trigger by id), so the adapter keeps an event → task-ids
|
|
43
|
+
* map and fans out on `trigger`. Created tasks collect on `adapter.tasks` for
|
|
44
|
+
* re-export from a file under your `dirs` (how the CLI discovers them).
|
|
45
|
+
*/
|
|
46
|
+
export function triggerDevAdapter(options: TriggerDevAdapterOptions = {}): TriggerDevJobsAdapter {
|
|
47
|
+
const config = v.parse(TriggerDevConfigSchema, { secretKey: options.secretKey })
|
|
48
|
+
const client: TriggerDevLike = options.client ?? defaultClient(config.secretKey)
|
|
49
|
+
|
|
50
|
+
const createdTasks: TriggerTask[] = []
|
|
51
|
+
// event name -> subscribed task ids
|
|
52
|
+
const routes = new Map<string, string[]>()
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
name: 'trigger.dev',
|
|
56
|
+
tasks: createdTasks,
|
|
57
|
+
defineJob<T>(def: JobDefinition<T>): JobDefinition<T> {
|
|
58
|
+
const created = client.task({
|
|
59
|
+
id: def.id,
|
|
60
|
+
run: (payload) => def.handler({ name: def.event, data: payload } as JobEvent<T>),
|
|
61
|
+
})
|
|
62
|
+
createdTasks.push(created)
|
|
63
|
+
const ids = routes.get(def.event) ?? []
|
|
64
|
+
ids.push(def.id)
|
|
65
|
+
routes.set(def.event, ids)
|
|
66
|
+
return def
|
|
67
|
+
},
|
|
68
|
+
async trigger<T>(event: JobEvent<T>): Promise<void> {
|
|
69
|
+
const ids = routes.get(event.name) ?? []
|
|
70
|
+
try {
|
|
71
|
+
await Promise.all(ids.map((id) => client.trigger(id, event.data)))
|
|
72
|
+
} catch (cause) {
|
|
73
|
+
throw new JobsError('Failed to trigger Trigger.dev task', {
|
|
74
|
+
adapter: 'trigger.dev',
|
|
75
|
+
cause,
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Collect tasks to re-export from a file under your `dirs`. */
|
|
83
|
+
export function triggerDevTasks(adapter: TriggerDevJobsAdapter): TriggerTask[] {
|
|
84
|
+
return adapter.tasks
|
|
85
|
+
}
|