@danylohotvianskyi/bobra-framework 0.1.9 → 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/batteries/auth/hash.ts +102 -36
- package/batteries/auth/token-metadata.ts +25 -8
- package/batteries/auth/token.ts +5 -5
- package/batteries/openapi/index.ts +62 -41
- package/batteries/openapi/merge-openapi.ts +125 -33
- package/core/config.ts +40 -14
- package/core/discovery.ts +16 -10
- package/core/env-resolver.ts +25 -11
- package/core/factory.ts +150 -77
- package/core/spa.ts +14 -8
- package/db/client.ts +80 -415
- package/db/drizzle-clients.ts +65 -0
- package/db/failover.ts +300 -0
- package/db/index.ts +1 -0
- package/db/migrate.ts +7 -6
- package/db/pgedge.ts +307 -0
- package/db/test/client.test.ts +297 -0
- package/db/token-auth.ts +40 -0
- package/db/types.ts +96 -0
- package/dist/batteries/auth/hash.d.ts +10 -2
- package/dist/batteries/auth/hash.js +78 -43
- package/dist/batteries/auth/hash.js.map +1 -1
- package/dist/batteries/auth/token-metadata.d.ts +3 -3
- package/dist/batteries/auth/token-metadata.js +14 -6
- package/dist/batteries/auth/token-metadata.js.map +1 -1
- package/dist/batteries/auth/token.d.ts +3 -3
- package/dist/batteries/auth/token.js +2 -2
- package/dist/batteries/auth/token.js.map +1 -1
- package/dist/batteries/openapi/index.d.ts +51 -13
- package/dist/batteries/openapi/index.js +25 -15
- package/dist/batteries/openapi/index.js.map +1 -1
- package/dist/batteries/openapi/merge-openapi.d.ts +26 -2
- package/dist/batteries/openapi/merge-openapi.js +83 -26
- package/dist/batteries/openapi/merge-openapi.js.map +1 -1
- package/dist/core/config.d.ts +26 -9
- package/dist/core/config.js +8 -7
- package/dist/core/config.js.map +1 -1
- package/dist/core/discovery.d.ts +18 -9
- package/dist/core/discovery.js +1 -1
- package/dist/core/discovery.js.map +1 -1
- package/dist/core/env-resolver.d.ts +7 -4
- package/dist/core/env-resolver.js +7 -5
- package/dist/core/env-resolver.js.map +1 -1
- package/dist/core/factory.d.ts +36 -16
- package/dist/core/factory.js +70 -38
- package/dist/core/factory.js.map +1 -1
- package/dist/core/spa.js +9 -4
- package/dist/core/spa.js.map +1 -1
- package/dist/db/client.d.ts +16 -66
- package/dist/db/client.js +40 -311
- package/dist/db/client.js.map +1 -1
- package/dist/db/drizzle-clients.d.ts +6 -0
- package/dist/db/drizzle-clients.js +42 -0
- package/dist/db/drizzle-clients.js.map +1 -0
- package/dist/db/failover.d.ts +39 -0
- package/dist/db/failover.js +251 -0
- package/dist/db/failover.js.map +1 -0
- package/dist/db/index.d.ts +1 -0
- package/dist/db/index.js +1 -0
- package/dist/db/index.js.map +1 -1
- package/dist/db/migrate.js +4 -4
- package/dist/db/migrate.js.map +1 -1
- package/dist/db/pgedge.d.ts +14 -0
- package/dist/db/pgedge.js +218 -0
- package/dist/db/pgedge.js.map +1 -0
- package/dist/db/token-auth.d.ts +34 -0
- package/dist/db/token-auth.js +15 -0
- package/dist/db/token-auth.js.map +1 -0
- package/dist/db/types.d.ts +82 -0
- package/dist/db/types.js +2 -0
- package/dist/db/types.js.map +1 -0
- package/dist/logging/logger.d.ts +13 -13
- package/dist/logging/logger.js +11 -2
- package/dist/logging/logger.js.map +1 -1
- package/dist/logging/logging-middleware.d.ts +1 -1
- package/dist/logging/logging-middleware.js +6 -6
- package/dist/logging/logging-middleware.js.map +1 -1
- package/dist/middleware/ensure-api-token.d.ts +33 -4
- package/dist/middleware/ensure-api-token.js.map +1 -1
- package/dist/middleware/utils.d.ts +5 -1
- package/dist/middleware/utils.js +11 -7
- package/dist/middleware/utils.js.map +1 -1
- package/dist/network/router.d.ts +9 -6
- package/dist/network/router.js +3 -1
- package/dist/network/router.js.map +1 -1
- package/dist/network/service-discovery.d.ts +1 -1
- package/dist/network/service-discovery.js.map +1 -1
- package/dist/network/service-fetch.d.ts +6 -9
- package/dist/network/service-fetch.js +14 -4
- package/dist/network/service-fetch.js.map +1 -1
- package/dist/node/generate-wrangler-config.d.ts +28 -4
- package/dist/node/generate-wrangler-config.js +75 -20
- package/dist/node/generate-wrangler-config.js.map +1 -1
- package/logging/logger.ts +31 -21
- package/logging/logging-middleware.ts +12 -9
- package/middleware/ensure-api-token.ts +8 -6
- package/middleware/utils.ts +26 -8
- package/network/router.ts +17 -13
- package/network/service-discovery.ts +1 -1
- package/network/service-fetch.ts +26 -17
- package/node/generate-wrangler-config.ts +160 -24
- package/package.json +10 -7
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import type { TokenValidationProvider } from '../batteries/auth/token-validation';
|
|
2
2
|
import { validateToken, extractAuthToken } from '../batteries/auth/token-validation';
|
|
3
|
+
import { Context } from 'hono';
|
|
4
|
+
import type { RouterEnv } from '../network/router';
|
|
3
5
|
|
|
4
6
|
export interface EnsureApiTokenOptions {
|
|
5
|
-
getTokenValidationProvider: (c:
|
|
6
|
-
getOrgContext?: (c:
|
|
7
|
-
verifyTokenScope?: (env:
|
|
7
|
+
getTokenValidationProvider: (c: Context<{ Bindings: RouterEnv; Variables: { _apiTokenFromQuery?: string; apiToken?: unknown } }>) => TokenValidationProvider;
|
|
8
|
+
getOrgContext?: (c: Context<{ Bindings: RouterEnv; Variables: { _apiTokenFromQuery?: string; apiToken?: unknown } }>) => Promise<string | null> | string | null;
|
|
9
|
+
verifyTokenScope?: (env: RouterEnv, orgContext: string, tokenUid: string) => Promise<boolean>;
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
export function ensureApiToken(options: EnsureApiTokenOptions) {
|
|
11
|
-
return async (c:
|
|
12
|
-
const env = c.env
|
|
13
|
+
return async (c: Context<{ Bindings: RouterEnv; Variables: { _apiTokenFromQuery?: string; apiToken?: unknown } }>, next: () => Promise<void>) => {
|
|
14
|
+
const env = c.env;
|
|
13
15
|
|
|
14
16
|
let rawToken = extractAuthToken(c.req.raw as Request);
|
|
15
17
|
|
|
@@ -39,7 +41,7 @@ export function ensureApiToken(options: EnsureApiTokenOptions) {
|
|
|
39
41
|
return c.json({ valid: false, reason: 'Organization context required' }, 400);
|
|
40
42
|
}
|
|
41
43
|
|
|
42
|
-
const isLinked = await options.verifyTokenScope(env, orgContext
|
|
44
|
+
const isLinked = await options.verifyTokenScope(env, orgContext, result.tokenInfo.uid);
|
|
43
45
|
if (!isLinked) {
|
|
44
46
|
return c.json({ valid: false, reason: 'Token is not linked to this organization' }, 403);
|
|
45
47
|
}
|
package/middleware/utils.ts
CHANGED
|
@@ -2,35 +2,53 @@ export function nowMs(): number {
|
|
|
2
2
|
return Date.now();
|
|
3
3
|
}
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
type JwtPayloadLike = { exp?: number } | Record<string, unknown> | null | undefined;
|
|
6
|
+
|
|
7
|
+
interface GlobalBase64Support {
|
|
8
|
+
btoa?: (input: string) => string;
|
|
9
|
+
Buffer?: {
|
|
10
|
+
from: (input: string) => { toString: (encoding: string) => string };
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function computeExpiryFromJwtPayload(payload: JwtPayloadLike, fallbackMs = 5 * 60 * 1000): number {
|
|
15
|
+
if (payload && typeof payload === 'object' && 'exp' in payload && typeof payload.exp === 'number') {
|
|
7
16
|
return payload.exp * 1000 - 30_000; // safety window
|
|
8
17
|
}
|
|
9
18
|
return nowMs() + fallbackMs;
|
|
10
19
|
}
|
|
11
20
|
|
|
12
21
|
export function toBase64(input: string): string {
|
|
22
|
+
const globals = globalThis as typeof globalThis & GlobalBase64Support;
|
|
23
|
+
|
|
13
24
|
try {
|
|
14
|
-
const btoaFn =
|
|
25
|
+
const btoaFn = globals.btoa;
|
|
15
26
|
if (typeof btoaFn === 'function') return btoaFn(input);
|
|
16
27
|
} catch { }
|
|
28
|
+
|
|
17
29
|
try {
|
|
18
|
-
const
|
|
19
|
-
if (
|
|
30
|
+
const bufferRef = globals.Buffer;
|
|
31
|
+
if (bufferRef?.from) return bufferRef.from(input).toString('base64');
|
|
20
32
|
} catch { }
|
|
33
|
+
|
|
21
34
|
// Minimal fallback
|
|
22
35
|
const encoder = new TextEncoder();
|
|
23
36
|
const bytes = encoder.encode(input);
|
|
24
37
|
let binary = '';
|
|
25
38
|
for (const b of bytes) binary += String.fromCharCode(b);
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
|
|
40
|
+
const fallbackBtoa = globals.btoa;
|
|
41
|
+
if (typeof fallbackBtoa === 'function') {
|
|
42
|
+
return fallbackBtoa(binary);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
throw new Error('No Base64 encoder available in current runtime');
|
|
28
46
|
}
|
|
29
47
|
|
|
30
48
|
export async function sha256Hex(input: string): Promise<string> {
|
|
31
49
|
const data = new TextEncoder().encode(input);
|
|
32
50
|
// crypto.subtle is available in Workers runtime
|
|
33
|
-
const digest = await
|
|
51
|
+
const digest = await crypto.subtle.digest('SHA-256', data);
|
|
34
52
|
const bytes = new Uint8Array(digest);
|
|
35
53
|
let hex = '';
|
|
36
54
|
for (const b of bytes) hex += b.toString(16).padStart(2, '0');
|
package/network/router.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
1
|
+
import { Hono, Context } from 'hono';
|
|
2
2
|
import { cors } from 'hono/cors';
|
|
3
3
|
import type { AppConfig, RouteConfig } from '../core/config';
|
|
4
|
+
import type { ExecutionContext } from '@cloudflare/workers-types';
|
|
4
5
|
import {
|
|
5
6
|
getRouterBasePath,
|
|
6
7
|
getWorkerBasePath,
|
|
@@ -13,7 +14,8 @@ import { simpleHonoLogger } from '../logging/logging-middleware';
|
|
|
13
14
|
|
|
14
15
|
export interface RouterEnv {
|
|
15
16
|
CONFIG_CONTENT?: string;
|
|
16
|
-
|
|
17
|
+
// Dynamic service bindings - unknown is necessary here because bindings are determined at runtime
|
|
18
|
+
[key: string]: unknown;
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
export function getServicesFromRoutes(routes: RouteConfig[]): string[] {
|
|
@@ -33,13 +35,15 @@ export function findMatchingRoute(path: string, routes: RouteConfig[]): RouteCon
|
|
|
33
35
|
return null;
|
|
34
36
|
}
|
|
35
37
|
|
|
36
|
-
export function getServiceBinding(serviceName: string, env: RouterEnv):
|
|
38
|
+
export function getServiceBinding(serviceName: string, env: RouterEnv): unknown {
|
|
37
39
|
const bindingName = serviceToBindingName(serviceName);
|
|
38
40
|
const binding = env[bindingName];
|
|
39
41
|
|
|
40
42
|
if (!binding) {
|
|
41
43
|
getLogger().error(`Service binding not found: ${bindingName} for service ${serviceName}`);
|
|
42
|
-
getLogger().info('Available bindings:',
|
|
44
|
+
getLogger().info('Available bindings:', {
|
|
45
|
+
bindings: Object.keys(env).filter(key => key.endsWith('_WORKER') || key.endsWith('_SERVICE'))
|
|
46
|
+
});
|
|
43
47
|
}
|
|
44
48
|
|
|
45
49
|
return binding;
|
|
@@ -50,7 +54,7 @@ export function getServiceBinding(serviceName: string, env: RouterEnv): any {
|
|
|
50
54
|
* `workerName` is injected into `X-Forwarded-By` for tracing.
|
|
51
55
|
*/
|
|
52
56
|
export async function handleServiceProxy(
|
|
53
|
-
c:
|
|
57
|
+
c: Context<{ Bindings: RouterEnv }>,
|
|
54
58
|
config: AppConfig,
|
|
55
59
|
serviceName: string,
|
|
56
60
|
remainingPath: string,
|
|
@@ -64,13 +68,13 @@ export async function handleServiceProxy(
|
|
|
64
68
|
}, 404);
|
|
65
69
|
}
|
|
66
70
|
|
|
67
|
-
const serviceConfig = config.router.services.find((s:
|
|
71
|
+
const serviceConfig = config.router.services.find((s: { service: string }) => s.service === serviceName);
|
|
68
72
|
if (!serviceConfig) {
|
|
69
73
|
return c.json({
|
|
70
74
|
success: false,
|
|
71
75
|
error: 'Service not found in router configuration',
|
|
72
76
|
service: serviceName,
|
|
73
|
-
available_services: config.router.services.map((s:
|
|
77
|
+
available_services: config.router.services.map((s: { service: string }) => s.service)
|
|
74
78
|
}, 404);
|
|
75
79
|
}
|
|
76
80
|
|
|
@@ -89,7 +93,7 @@ export async function handleServiceProxy(
|
|
|
89
93
|
newHeaders.set('X-Forwarded-By', workerName);
|
|
90
94
|
newHeaders.set('X-Original-Path', c.req.path);
|
|
91
95
|
// Forward CF location data for pgEdge geo-routing
|
|
92
|
-
const cf = (c.req.raw as
|
|
96
|
+
const cf = (c.req.raw as Request & { cf?: { continent?: string; colo?: string } }).cf;
|
|
93
97
|
if (cf?.continent) newHeaders.set('X-CF-Continent', cf.continent);
|
|
94
98
|
if (cf?.colo) newHeaders.set('X-CF-Colo', cf.colo);
|
|
95
99
|
|
|
@@ -127,7 +131,7 @@ export async function handleServiceProxy(
|
|
|
127
131
|
body: c.req.method !== 'GET' && c.req.method !== 'HEAD' ? await c.req.text() : undefined
|
|
128
132
|
});
|
|
129
133
|
|
|
130
|
-
response = await serviceBinding.fetch(newRequest);
|
|
134
|
+
response = await (serviceBinding as { fetch: (req: Request) => Promise<Response> }).fetch(newRequest);
|
|
131
135
|
}
|
|
132
136
|
|
|
133
137
|
return response;
|
|
@@ -154,7 +158,7 @@ export interface CreateRouterAppOptions {
|
|
|
154
158
|
* Optional hook to build the public config response object.
|
|
155
159
|
* If omitted, a default response with router basePath + workers is returned.
|
|
156
160
|
*/
|
|
157
|
-
buildPublicConfig?: (config: AppConfig, env: RouterEnv) => Record<string,
|
|
161
|
+
buildPublicConfig?: (config: AppConfig, env: RouterEnv) => Record<string, unknown>;
|
|
158
162
|
}
|
|
159
163
|
|
|
160
164
|
/**
|
|
@@ -345,7 +349,7 @@ export function createRouterApp(
|
|
|
345
349
|
const newHeaders = new Headers(c.req.raw.headers);
|
|
346
350
|
newHeaders.set('X-Forwarded-Url', c.req.url);
|
|
347
351
|
// Forward CF location data for pgEdge geo-routing
|
|
348
|
-
const cf = (c.req.raw as
|
|
352
|
+
const cf = (c.req.raw as Request & { cf?: { continent?: string; colo?: string } }).cf;
|
|
349
353
|
if (cf?.continent) newHeaders.set('X-CF-Continent', cf.continent);
|
|
350
354
|
if (cf?.colo) newHeaders.set('X-CF-Colo', cf.colo);
|
|
351
355
|
const orgUid = c.req.query('org_uid');
|
|
@@ -359,7 +363,7 @@ export function createRouterApp(
|
|
|
359
363
|
body: c.req.method !== 'GET' && c.req.method !== 'HEAD' ? await c.req.text() : undefined
|
|
360
364
|
});
|
|
361
365
|
|
|
362
|
-
const response = await service.fetch(newRequest);
|
|
366
|
+
const response = await (service as { fetch: (req: Request) => Promise<Response> }).fetch(newRequest);
|
|
363
367
|
return response;
|
|
364
368
|
|
|
365
369
|
} catch (error) {
|
|
@@ -381,7 +385,7 @@ export function createRouterApp(
|
|
|
381
385
|
*/
|
|
382
386
|
export function createRouterWorker(options: CreateRouterAppOptions) {
|
|
383
387
|
return {
|
|
384
|
-
async fetch(request: Request, env: RouterEnv, ctx:
|
|
388
|
+
async fetch(request: Request, env: RouterEnv, ctx: ExecutionContext): Promise<Response> {
|
|
385
389
|
try {
|
|
386
390
|
const config = await loadConfig(env);
|
|
387
391
|
|
|
@@ -9,7 +9,7 @@ import { Context, Next } from 'hono';
|
|
|
9
9
|
* Logs warnings when config doesn't match available bindings/handlers.
|
|
10
10
|
*/
|
|
11
11
|
export function serviceDiscoveryMiddleware(
|
|
12
|
-
env:
|
|
12
|
+
env: Record<string, unknown>,
|
|
13
13
|
config: AppConfig,
|
|
14
14
|
workerName: string
|
|
15
15
|
): MiddlewareHandler {
|
package/network/service-fetch.ts
CHANGED
|
@@ -7,12 +7,16 @@ import {
|
|
|
7
7
|
getServiceDiscovery,
|
|
8
8
|
getFetchInstance,
|
|
9
9
|
getRouterBasePath,
|
|
10
|
-
getRouterWorkerName
|
|
10
|
+
getRouterWorkerName,
|
|
11
|
+
type FetchInstance
|
|
11
12
|
} from '../core/config';
|
|
13
|
+
import { Context } from 'hono';
|
|
14
|
+
import type { RouterEnv } from './router';
|
|
12
15
|
|
|
13
16
|
// Convenience function for simple handler calls
|
|
14
17
|
export async function callHandler(
|
|
15
|
-
|
|
18
|
+
// Replaced WorkerEnv with RouterEnv for consistency
|
|
19
|
+
env: RouterEnv,
|
|
16
20
|
handlerName: string,
|
|
17
21
|
uri: string,
|
|
18
22
|
options: RequestInit = {}
|
|
@@ -22,7 +26,8 @@ export async function callHandler(
|
|
|
22
26
|
|
|
23
27
|
// Convenience function for simple service calls
|
|
24
28
|
export async function callService(
|
|
25
|
-
|
|
29
|
+
// Replaced WorkerEnv with RouterEnv for consistency
|
|
30
|
+
env: RouterEnv,
|
|
26
31
|
serviceName: string,
|
|
27
32
|
uri: string,
|
|
28
33
|
options: RequestInit = {}
|
|
@@ -31,9 +36,9 @@ export async function callService(
|
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
// Redact Authorization headers from options for debug logging
|
|
34
|
-
function redactOptions(options?: RequestInit):
|
|
39
|
+
function redactOptions(options?: RequestInit): RequestInit | undefined {
|
|
35
40
|
try {
|
|
36
|
-
const o:
|
|
41
|
+
const o: RequestInit | undefined = options ? JSON.parse(JSON.stringify(options)) : undefined;
|
|
37
42
|
if (o && o.headers) {
|
|
38
43
|
const h = new Headers(o.headers);
|
|
39
44
|
if (h.has('Authorization')) h.set('Authorization', 'Bearer ***');
|
|
@@ -46,20 +51,22 @@ function redactOptions(options?: RequestInit): any {
|
|
|
46
51
|
|
|
47
52
|
// Core inter-service communication utility
|
|
48
53
|
export async function serviceFetch(
|
|
49
|
-
|
|
50
|
-
|
|
54
|
+
// Replaced any with RouterEnv - matches framework's environment interface
|
|
55
|
+
env: RouterEnv,
|
|
56
|
+
fetchInstance: FetchInstance | string,
|
|
51
57
|
uri: string,
|
|
52
58
|
options: RequestInit = {},
|
|
53
|
-
|
|
59
|
+
// Replaced any with Hono Context - standard request context
|
|
60
|
+
ctx?: Context
|
|
54
61
|
): Promise<Response> {
|
|
55
62
|
const config = await loadConfig(env);
|
|
56
63
|
const workerName = env.WORKER_NAME || 'default-worker';
|
|
57
64
|
|
|
58
|
-
const discovery = getServiceDiscovery(env, config, workerName, appWorkerRegistry);
|
|
65
|
+
const discovery = getServiceDiscovery(env, config, workerName as string, appWorkerRegistry);
|
|
59
66
|
const routerWorkerName = getRouterWorkerName(config);
|
|
60
67
|
|
|
61
68
|
// If fetchInstance is a string, resolve it to an actual instance
|
|
62
|
-
let instance:
|
|
69
|
+
let instance: FetchInstance | null;
|
|
63
70
|
|
|
64
71
|
if (typeof fetchInstance === 'string') {
|
|
65
72
|
instance = getFetchInstance(fetchInstance, discovery, env);
|
|
@@ -82,7 +89,9 @@ export async function serviceFetch(
|
|
|
82
89
|
const headers = new Headers(initCopy.headers || {});
|
|
83
90
|
if (!headers.has('Authorization') && !headers.has('X-Authorization')) {
|
|
84
91
|
try {
|
|
85
|
-
const ctxHeaders
|
|
92
|
+
const ctxHeaders = {
|
|
93
|
+
get: (name: string) => ctx?.req?.header(name) || null
|
|
94
|
+
};
|
|
86
95
|
const authVal = ctxHeaders?.get?.('Authorization') || ctxHeaders?.get?.('X-Authorization');
|
|
87
96
|
if (authVal) headers.set('Authorization', authVal);
|
|
88
97
|
} catch { }
|
|
@@ -109,17 +118,17 @@ export async function serviceFetch(
|
|
|
109
118
|
hasExternalUrl: !!instance.external_url
|
|
110
119
|
});
|
|
111
120
|
|
|
112
|
-
const workerBasePath = getWorkerBasePath(config, workerName);
|
|
121
|
+
const workerBasePath = getWorkerBasePath(config, workerName as string);
|
|
113
122
|
const routerBasePath = getRouterBasePath(config);
|
|
114
123
|
|
|
115
124
|
// Case 1: Handler on same worker — use in-memory Hono app.fetch
|
|
116
125
|
if (instance.type === 'handler' && discovery.initializedHandlers.includes(instance.name)) {
|
|
117
|
-
const handler = appWorkerRegistry.getHandler(workerName, instance.name);
|
|
126
|
+
const handler = appWorkerRegistry.getHandler(workerName as string, instance.name);
|
|
118
127
|
if (!handler) {
|
|
119
128
|
throw new Error(`Handler '${instance.name}' not found in discovery`);
|
|
120
129
|
}
|
|
121
130
|
|
|
122
|
-
const workerApp = appWorkerRegistry.getMainApp(workerName);
|
|
131
|
+
const workerApp = appWorkerRegistry.getMainApp(workerName as string);
|
|
123
132
|
if (!workerApp) {
|
|
124
133
|
throw new Error(`Worker app '${workerName}' not found in registry`);
|
|
125
134
|
}
|
|
@@ -175,7 +184,7 @@ export async function serviceFetch(
|
|
|
175
184
|
});
|
|
176
185
|
const init = ensureAuthHeader(options);
|
|
177
186
|
const url = uri.startsWith('http') ? uri : `http://internal${uri.startsWith('/') ? uri : '/' + uri}`;
|
|
178
|
-
return await instance.binding.fetch(url, init);
|
|
187
|
+
return await (instance.binding as { fetch: (url: string, init?: RequestInit) => Promise<Response> }).fetch(url, init);
|
|
179
188
|
} catch (error) {
|
|
180
189
|
getLogger().error(`Direct service binding call failed for ${instance.name}`, error instanceof Error ? error : new Error(String(error)));
|
|
181
190
|
throw error;
|
|
@@ -247,7 +256,7 @@ export async function serviceFetch(
|
|
|
247
256
|
});
|
|
248
257
|
const init = ensureAuthHeader(options);
|
|
249
258
|
const url = routerPath.startsWith('http') ? routerPath : `http://internal${routerPath.startsWith('/') ? routerPath : '/' + routerPath}`;
|
|
250
|
-
return await routerBinding.fetch(url, init);
|
|
259
|
+
return await (routerBinding as { fetch: (url: string, init?: RequestInit) => Promise<Response> }).fetch(url, init);
|
|
251
260
|
}
|
|
252
261
|
}
|
|
253
262
|
|
|
@@ -291,7 +300,7 @@ export async function serviceFetch(
|
|
|
291
300
|
});
|
|
292
301
|
const init = ensureAuthHeader(options);
|
|
293
302
|
const url = serviceProxyPath.startsWith('http') ? serviceProxyPath : `http://internal${serviceProxyPath.startsWith('/') ? serviceProxyPath : '/' + serviceProxyPath}`;
|
|
294
|
-
return await routerBinding.fetch(url, init);
|
|
303
|
+
return await (routerBinding as { fetch: (url: string, init?: RequestInit) => Promise<Response> }).fetch(url, init);
|
|
295
304
|
}
|
|
296
305
|
}
|
|
297
306
|
|
|
@@ -24,7 +24,9 @@ import {
|
|
|
24
24
|
import { JSONValue } from 'hono/utils/types';
|
|
25
25
|
import { gzipSync } from 'zlib';
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
export type { AppConfig } from '../core/config.js';
|
|
28
|
+
|
|
29
|
+
export interface WranglerConfig {
|
|
28
30
|
name: string;
|
|
29
31
|
main: string;
|
|
30
32
|
compatibility_date: string;
|
|
@@ -111,6 +113,66 @@ interface WranglerConfig {
|
|
|
111
113
|
enabled?: boolean;
|
|
112
114
|
};
|
|
113
115
|
};
|
|
116
|
+
// observability?: {
|
|
117
|
+
// traces?: {
|
|
118
|
+
// enabled?: boolean;
|
|
119
|
+
// destinations?: string[];
|
|
120
|
+
// };
|
|
121
|
+
// logs?: {
|
|
122
|
+
// enabled?: boolean;
|
|
123
|
+
// destinations?: string[];
|
|
124
|
+
// };
|
|
125
|
+
// };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface WranglerConfigExtensionContext<
|
|
129
|
+
TConfig extends AppConfig = AppConfig,
|
|
130
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
131
|
+
> {
|
|
132
|
+
config: TConfig;
|
|
133
|
+
workerType: string;
|
|
134
|
+
workerName: string;
|
|
135
|
+
wranglerConfig: TWranglerConfig;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface WranglerConfigWriteContext<
|
|
139
|
+
TConfig extends AppConfig = AppConfig,
|
|
140
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
141
|
+
> extends WranglerConfigExtensionContext<TConfig, TWranglerConfig> {
|
|
142
|
+
configFile: string;
|
|
143
|
+
outputFile: string;
|
|
144
|
+
outputDir: string;
|
|
145
|
+
outputContent: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface WranglerConfigGeneratorExtension<
|
|
149
|
+
TConfig extends AppConfig = AppConfig,
|
|
150
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
151
|
+
> {
|
|
152
|
+
validateConfig?: (config: TConfig) => void;
|
|
153
|
+
extendWranglerConfig?: (
|
|
154
|
+
context: WranglerConfigExtensionContext<TConfig, TWranglerConfig>
|
|
155
|
+
) => TWranglerConfig | void;
|
|
156
|
+
serializeOutput?: (wranglerConfig: TWranglerConfig) => string;
|
|
157
|
+
onBeforeWrite?: (context: WranglerConfigWriteContext<TConfig, TWranglerConfig>) => void;
|
|
158
|
+
onAfterWrite?: (context: WranglerConfigWriteContext<TConfig, TWranglerConfig>) => void;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface GenerateWranglerMainOptions<
|
|
162
|
+
TConfig extends AppConfig = AppConfig,
|
|
163
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
164
|
+
> {
|
|
165
|
+
args?: string[];
|
|
166
|
+
extension?: WranglerConfigGeneratorExtension<TConfig, TWranglerConfig>;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function defineWranglerConfigExtension<
|
|
170
|
+
TConfig extends AppConfig = AppConfig,
|
|
171
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
172
|
+
>(
|
|
173
|
+
extension: WranglerConfigGeneratorExtension<TConfig, TWranglerConfig>
|
|
174
|
+
): WranglerConfigGeneratorExtension<TConfig, TWranglerConfig> {
|
|
175
|
+
return extension;
|
|
114
176
|
}
|
|
115
177
|
|
|
116
178
|
function normalizePathValue(p?: string): string {
|
|
@@ -120,9 +182,17 @@ function normalizePathValue(p?: string): string {
|
|
|
120
182
|
return v;
|
|
121
183
|
}
|
|
122
184
|
|
|
123
|
-
export function generateWranglerConfig
|
|
185
|
+
export function generateWranglerConfig<
|
|
186
|
+
TConfig extends AppConfig = AppConfig,
|
|
187
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
188
|
+
>(
|
|
189
|
+
config: TConfig,
|
|
190
|
+
workerType: string,
|
|
191
|
+
workerName: string,
|
|
192
|
+
extension?: WranglerConfigGeneratorExtension<TConfig, TWranglerConfig>
|
|
193
|
+
): TWranglerConfig {
|
|
124
194
|
const configYaml = dump(config);
|
|
125
|
-
const compressed = gzipSync(configYaml
|
|
195
|
+
const compressed = gzipSync(configYaml);
|
|
126
196
|
const configContent = compressed.toString('base64');
|
|
127
197
|
|
|
128
198
|
let wranglerConfig: WranglerConfig;
|
|
@@ -142,8 +212,24 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
142
212
|
PGEDGE_LOCATIONS: JSON.stringify(config.pgEdge?.locations || []),
|
|
143
213
|
...(config.deployment_context && { DEPLOYMENT_CONTEXT: config.deployment_context }),
|
|
144
214
|
...config.vars,
|
|
145
|
-
...routerConfig?.vars
|
|
215
|
+
...routerConfig?.vars,
|
|
216
|
+
PGEDGE_FAILOVER_ENABLED: config.pgEdge?.connection_fallback ?? true
|
|
146
217
|
},
|
|
218
|
+
// observability: {
|
|
219
|
+
// ...(routerObservability?.traces ? {
|
|
220
|
+
// traces: {
|
|
221
|
+
// enabled: routerObservability?.traces?.enabled || false,
|
|
222
|
+
// ...(Array.isArray(routerObservability?.traces?.destinations)
|
|
223
|
+
// ? { destinations: routerObservability.traces.destinations }
|
|
224
|
+
// : {}),
|
|
225
|
+
// },
|
|
226
|
+
// } : {}),
|
|
227
|
+
// logs: {
|
|
228
|
+
// enabled: routerObservability?.logs?.enabled || false,
|
|
229
|
+
// ...(Array.isArray(routerObservability?.logs?.destinations)
|
|
230
|
+
// ? { destinations: routerObservability.logs.destinations }
|
|
231
|
+
// : {}),
|
|
232
|
+
// }
|
|
147
233
|
observability: {
|
|
148
234
|
logs: {
|
|
149
235
|
enabled: routerConfig?.observability?.logs?.enabled || false
|
|
@@ -151,9 +237,8 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
151
237
|
}
|
|
152
238
|
};
|
|
153
239
|
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
let runWorkerFirstConfig: boolean | string[] | undefined = rcAny?.assets?.run_worker_first;
|
|
240
|
+
const assetsDirectory: string | undefined = routerConfig?.assets?.directory || 'public';
|
|
241
|
+
let runWorkerFirstConfig: boolean | string[] | undefined = routerConfig?.assets?.run_worker_first;
|
|
157
242
|
|
|
158
243
|
const patterns = new Set<string>();
|
|
159
244
|
|
|
@@ -185,8 +270,8 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
185
270
|
} else {
|
|
186
271
|
runWorkerFirst = Array.from(patterns);
|
|
187
272
|
}
|
|
188
|
-
const notFoundHandling: 'single-page-application' | '404-page' | 'none' | undefined =
|
|
189
|
-
const htmlHandling: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none' | undefined =
|
|
273
|
+
const notFoundHandling: 'single-page-application' | '404-page' | 'none' | undefined = routerConfig?.assets?.not_found_handling || 'single-page-application';
|
|
274
|
+
const htmlHandling: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none' | undefined = routerConfig?.assets?.html_handling;
|
|
190
275
|
wranglerConfig.assets = {
|
|
191
276
|
directory: assetsDirectory,
|
|
192
277
|
binding: 'ASSETS',
|
|
@@ -252,8 +337,25 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
252
337
|
PGEDGE_LOCATIONS: JSON.stringify(config.pgEdge?.locations || []),
|
|
253
338
|
...(config.deployment_context && { DEPLOYMENT_CONTEXT: config.deployment_context }),
|
|
254
339
|
...config.vars,
|
|
255
|
-
...workerConfig?.vars
|
|
340
|
+
...workerConfig?.vars,
|
|
341
|
+
PGEDGE_FAILOVER_ENABLED: config.pgEdge?.connection_fallback ?? true
|
|
256
342
|
},
|
|
343
|
+
// observability: {
|
|
344
|
+
// ...(workerObservability?.traces ? {
|
|
345
|
+
// traces: {
|
|
346
|
+
// enabled: workerObservability?.traces?.enabled || false,
|
|
347
|
+
// ...(Array.isArray(workerObservability?.traces?.destinations)
|
|
348
|
+
// ? { destinations: workerObservability.traces.destinations }
|
|
349
|
+
// : {}),
|
|
350
|
+
// },
|
|
351
|
+
// } : {}),
|
|
352
|
+
// logs: {
|
|
353
|
+
// enabled: workerObservability?.logs?.enabled || false,
|
|
354
|
+
// ...(Array.isArray(workerObservability?.logs?.destinations)
|
|
355
|
+
// ? { destinations: workerObservability.logs.destinations }
|
|
356
|
+
// : {}),
|
|
357
|
+
// }
|
|
358
|
+
// }
|
|
257
359
|
observability: {
|
|
258
360
|
logs: {
|
|
259
361
|
enabled: workerConfig?.observability?.logs?.enabled || false
|
|
@@ -271,10 +373,9 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
271
373
|
}
|
|
272
374
|
}
|
|
273
375
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
let runWorkerFirstConfig: boolean | string[] | undefined = workerConfigAny?.assets?.run_worker_first;
|
|
376
|
+
if (workerConfig?.assets) {
|
|
377
|
+
const assetsDirectory: string | undefined = workerConfig.assets.directory || 'public';
|
|
378
|
+
let runWorkerFirstConfig: boolean | string[] | undefined = workerConfig.assets.run_worker_first;
|
|
278
379
|
|
|
279
380
|
const patterns = new Set<string>();
|
|
280
381
|
if (Array.isArray(runWorkerFirstConfig)) {
|
|
@@ -288,8 +389,8 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
288
389
|
runWorkerFirst = Array.from(patterns);
|
|
289
390
|
}
|
|
290
391
|
|
|
291
|
-
const notFoundHandling: 'single-page-application' | '404-page' | 'none' | undefined =
|
|
292
|
-
const htmlHandling: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none' | undefined =
|
|
392
|
+
const notFoundHandling: 'single-page-application' | '404-page' | 'none' | undefined = workerConfig.assets.not_found_handling || 'single-page-application';
|
|
393
|
+
const htmlHandling: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none' | undefined = workerConfig.assets.html_handling;
|
|
293
394
|
|
|
294
395
|
wranglerConfig.assets = {
|
|
295
396
|
directory: assetsDirectory,
|
|
@@ -304,7 +405,7 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
304
405
|
try {
|
|
305
406
|
const dbBinding = getDatabaseBinding(config, workerName);
|
|
306
407
|
if (dbBinding.type === 'hyperdrive') {
|
|
307
|
-
const flatHyperdriveConfigs = flattenHyperdriveConfigs(dbBinding.config
|
|
408
|
+
const flatHyperdriveConfigs = flattenHyperdriveConfigs(dbBinding.config);
|
|
308
409
|
wranglerConfig.hyperdrive = flatHyperdriveConfigs.map((hdConfig) => ({
|
|
309
410
|
binding: hdConfig.binding,
|
|
310
411
|
id: hdConfig.id,
|
|
@@ -381,7 +482,15 @@ export function generateWranglerConfig(config: AppConfig, workerType: string, wo
|
|
|
381
482
|
}
|
|
382
483
|
}
|
|
383
484
|
|
|
384
|
-
|
|
485
|
+
const baseWranglerConfig = wranglerConfig as TWranglerConfig;
|
|
486
|
+
const extendedWranglerConfig = extension?.extendWranglerConfig?.({
|
|
487
|
+
config,
|
|
488
|
+
workerType,
|
|
489
|
+
workerName,
|
|
490
|
+
wranglerConfig: baseWranglerConfig,
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
return extendedWranglerConfig || baseWranglerConfig;
|
|
385
494
|
}
|
|
386
495
|
|
|
387
496
|
function copyDevVarsToWorker(workerDir: string, repoRoot: string) {
|
|
@@ -428,8 +537,13 @@ function storeHash(outputDir: string, hash: string): void {
|
|
|
428
537
|
}
|
|
429
538
|
}
|
|
430
539
|
|
|
431
|
-
export function main
|
|
432
|
-
|
|
540
|
+
export function main<
|
|
541
|
+
TConfig extends AppConfig = AppConfig,
|
|
542
|
+
TWranglerConfig extends WranglerConfig = WranglerConfig,
|
|
543
|
+
>(
|
|
544
|
+
options: GenerateWranglerMainOptions<TConfig, TWranglerConfig> = {}
|
|
545
|
+
) {
|
|
546
|
+
const args = options.args ?? (typeof process !== 'undefined' ? process.argv.slice(2) : []);
|
|
433
547
|
const configFile = args[0] || process.env.CONFIG_PATH || 'config.yml';
|
|
434
548
|
const outputFile = args[1] || 'wrangler.jsonc';
|
|
435
549
|
const workerType = args[2] || 'worker';
|
|
@@ -446,7 +560,7 @@ export function main() {
|
|
|
446
560
|
|
|
447
561
|
try {
|
|
448
562
|
const yamlContent = fs.readFileSync(configFile, 'utf8');
|
|
449
|
-
const config = load(yamlContent) as
|
|
563
|
+
const config = load(yamlContent) as TConfig;
|
|
450
564
|
|
|
451
565
|
if (!config.cors || !config.server) {
|
|
452
566
|
throw new Error('Config must include cors and server sections');
|
|
@@ -456,7 +570,14 @@ export function main() {
|
|
|
456
570
|
throw new Error('Server config must include name and version');
|
|
457
571
|
}
|
|
458
572
|
|
|
459
|
-
|
|
573
|
+
options.extension?.validateConfig?.(config);
|
|
574
|
+
|
|
575
|
+
const wranglerConfig = generateWranglerConfig<TConfig, TWranglerConfig>(
|
|
576
|
+
config,
|
|
577
|
+
workerType,
|
|
578
|
+
workerName,
|
|
579
|
+
options.extension
|
|
580
|
+
);
|
|
460
581
|
|
|
461
582
|
const outputDir = path.dirname(outputFile);
|
|
462
583
|
if (!fs.existsSync(outputDir)) {
|
|
@@ -471,7 +592,8 @@ export function main() {
|
|
|
471
592
|
} catch { }
|
|
472
593
|
}
|
|
473
594
|
|
|
474
|
-
const outputContent =
|
|
595
|
+
const outputContent = options.extension?.serializeOutput?.(wranglerConfig)
|
|
596
|
+
?? JSON.stringify(wranglerConfig, null, 2);
|
|
475
597
|
const newHash = generateHash(outputContent);
|
|
476
598
|
|
|
477
599
|
if (fs.existsSync(outputFile)) {
|
|
@@ -491,10 +613,24 @@ export function main() {
|
|
|
491
613
|
console.log(` Worker type: ${workerType}`);
|
|
492
614
|
console.log(` Worker name: ${workerName}`);
|
|
493
615
|
|
|
616
|
+
const writeContext: WranglerConfigWriteContext<TConfig, TWranglerConfig> = {
|
|
617
|
+
config,
|
|
618
|
+
workerType,
|
|
619
|
+
workerName,
|
|
620
|
+
wranglerConfig,
|
|
621
|
+
configFile,
|
|
622
|
+
outputFile,
|
|
623
|
+
outputDir,
|
|
624
|
+
outputContent,
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
options.extension?.onBeforeWrite?.(writeContext);
|
|
628
|
+
|
|
494
629
|
fs.writeFileSync(outputFile, outputContent);
|
|
495
630
|
|
|
496
631
|
storeHash(outputDir, newHash);
|
|
497
632
|
copyDevVarsToWorker(outputDir, repoRoot);
|
|
633
|
+
options.extension?.onAfterWrite?.(writeContext);
|
|
498
634
|
|
|
499
635
|
console.log(`✅ Generated ${outputFile} successfully`);
|
|
500
636
|
console.log(` Worker name: ${wranglerConfig.name}`);
|
|
@@ -531,7 +667,7 @@ export function main() {
|
|
|
531
667
|
const dbBinding = getDatabaseBinding(config, workerName);
|
|
532
668
|
console.log(` Database: ${dbBinding.type} (worker-specific)`);
|
|
533
669
|
if (dbBinding.type === 'hyperdrive') {
|
|
534
|
-
const flatHyperdriveConfigs = flattenHyperdriveConfigs(dbBinding.config
|
|
670
|
+
const flatHyperdriveConfigs = flattenHyperdriveConfigs(dbBinding.config);
|
|
535
671
|
const bindingNames = flatHyperdriveConfigs.map((cfg) => cfg.binding);
|
|
536
672
|
console.log(` Hyperdrive bindings: ${bindingNames.join(', ')}`);
|
|
537
673
|
} else if (dbBinding.type === 'd1') {
|