silgi 0.41.31 → 0.41.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from 'citty';
3
3
 
4
- const version = "0.41.31";
4
+ const version = "0.41.34";
5
5
  const packageJson = {
6
6
  version: version};
7
7
 
@@ -1,33 +1,23 @@
1
- import { SilgiConfig, Silgi, SilgiEvent, HTTPMethod, SilgiSchema, RouteEntry, CustomRequestInit, SilgiRuntimeContext, BaseMethodSchema, MergeAll, ServiceSetupsForMethods, ServiceDefinitionByMethodAndPath, Routers, ServiceSetup, MiddlewareSetup, SilgiRuntimeShareds, Resolvers, SilgiURL, StorageConfig, SilgiCLI, SilgiStorageBase, SilgiRuntimeConfig } from 'silgi/types';
1
+ import { SilgiRuntimeConfig, SilgiConfig, Silgi, SilgiEvent, SilgiRuntimeContext, SilgiSchema, RouteEntry, CustomRequestInit, SilgiCLI, SilgiStorageBase, MergeAll, Routers, HTTPMethod, MiddlewareSetup, Resolvers, SilgiURL, BaseMethodSchema, ServiceSetupsForMethods, ServiceDefinitionByMethodAndPath, ServiceSetup, SilgiRuntimeShareds, StorageConfig } from 'silgi/types';
2
+ import { ServerRequest } from 'srvx';
2
3
  import { GraphQLResolveInfo } from 'graphql';
3
- import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { Storage, StorageValue } from 'unstorage';
5
4
  import { UseContext } from 'unctx';
5
+ import { Storage, StorageValue } from 'unstorage';
6
+ import { StandardSchemaV1 } from '@standard-schema/spec';
6
7
 
7
- declare function createSilgi(config: SilgiConfig): Promise<Silgi>;
8
-
9
- /**
10
- * Fetch API for Silgi framework
11
- */
12
- declare function silgiFetch<Schema extends SilgiSchema = SilgiSchema, Method extends RouteEntry<Schema>['method'] = RouteEntry<Schema>['method'], Path extends Extract<RouteEntry<Schema>, {
13
- method: Method;
14
- }>['path'] = Extract<RouteEntry<Schema>, {
15
- method: Method;
16
- }>['path'], Resolved extends boolean = true, HiddenParameters extends boolean = true>(_request: Path, options?: CustomRequestInit<Schema, Method, Path, Resolved, HiddenParameters>, context?: SilgiRuntimeContext): Promise<Response | Promise<Response>>;
8
+ declare function updateRuntimeStorage(runtime: any): void;
17
9
  /**
18
- * Fetch API for Silgi framework using standard Request options
10
+ * Get access to silgi instance.
11
+ *
12
+ * Throws an error if silgi instance is unavailable.
13
+ * @example
14
+ * ```js
15
+ * const runtime = useRuntime()
16
+ * ```
19
17
  */
20
- declare function silgiFetch(_request: Request | URL, options?: RequestInit & {
21
- pathParams?: Record<string, any>;
22
- }, context?: SilgiRuntimeContext): Promise<Response | Promise<Response>>;
23
- declare function middleware(event: SilgiEvent, url?: {
24
- path?: string;
25
- method?: string;
26
- }): Promise<any>;
27
- declare function handler(event: SilgiEvent, url?: {
28
- path?: string;
29
- method?: HTTPMethod | '';
30
- }, input?: any, parent?: any, info?: GraphQLResolveInfo): Promise<any>;
18
+ declare function useRuntime(): SilgiRuntimeConfig;
19
+
20
+ declare function createSilgi(config: SilgiConfig): Promise<Silgi>;
31
21
 
32
22
  /**
33
23
  * LICENSE: MIT
@@ -97,6 +87,26 @@ declare function createError<DataT = unknown>(input: string | (Partial<SilgiErro
97
87
  */
98
88
  declare function isError<DataT = unknown>(input: any): input is SilgiError<DataT>;
99
89
 
90
+ declare class SilgiHttpEvent implements SilgiEvent {
91
+ static __is_event__: boolean;
92
+ req: ServerRequest;
93
+ url: URL;
94
+ context: SilgiRuntimeContext;
95
+ _res?: SilgiEventResponse;
96
+ constructor(req: ServerRequest, context?: SilgiRuntimeContext);
97
+ _chain: Promise<unknown> | undefined;
98
+ [x: string]: unknown;
99
+ get res(): SilgiEventResponse;
100
+ toString(): string;
101
+ toJSON(): string;
102
+ }
103
+ declare class SilgiEventResponse {
104
+ status?: number;
105
+ statusText?: string;
106
+ _headers?: Headers;
107
+ get headers(): Headers;
108
+ }
109
+
100
110
  type MaybePromise<T> = T | Promise<T>;
101
111
  interface SilgiHandlerConfig {
102
112
  debug?: boolean;
@@ -111,42 +121,47 @@ declare const kNotFound: symbol;
111
121
  declare const kHandled: symbol;
112
122
  declare function handleResponse(val: unknown, event: SilgiEvent, config: SilgiHandlerConfig): Response | Promise<Response>;
113
123
 
114
- declare function getEvent<T extends SilgiEvent>(event?: SilgiEvent): T;
115
- declare function getEventContext<T extends SilgiRuntimeContext>(event?: SilgiEvent): T;
124
+ /**
125
+ * Fetch API for Silgi framework
126
+ */
127
+ declare function silgiFetch<Schema extends SilgiSchema = SilgiSchema, Method extends RouteEntry<Schema>['method'] = RouteEntry<Schema>['method'], Path extends Extract<RouteEntry<Schema>, {
128
+ method: Method;
129
+ }>['path'] = Extract<RouteEntry<Schema>, {
130
+ method: Method;
131
+ }>['path'], Resolved extends boolean = true, HiddenParameters extends boolean = true>(_request: Path, options?: CustomRequestInit<Schema, Method, Path, Resolved, HiddenParameters>, context?: SilgiRuntimeContext): Promise<Response | Promise<Response>>;
132
+ /**
133
+ * Fetch API for Silgi framework using standard Request options
134
+ */
135
+ declare function silgiFetch(_request: Request | URL, options?: RequestInit & {
136
+ pathParams?: Record<string, any>;
137
+ }, context?: SilgiRuntimeContext): Promise<Response | Promise<Response>>;
138
+ declare function middleware(event: SilgiEvent): Promise<any>;
139
+ declare function handler(event: SilgiEvent, middlewareMode?: boolean, input?: any, parent?: any, info?: GraphQLResolveInfo, callBack?: () => any | Promise<any>): Promise<any>;
140
+
141
+ declare const silgiCLICtx: UseContext<SilgiCLI>;
142
+ declare function useSilgiCLI(): SilgiCLI;
143
+ declare function tryUseSilgiCLI(): SilgiCLI | null;
144
+
145
+ declare function storageMount<T extends Storage = Storage>(silgi?: Silgi): (base: keyof SilgiStorageBase, driver: Parameters<Storage['mount']>[1]) => T;
116
146
 
147
+ declare const silgiCtx: UseContext<Silgi>;
148
+ declare function useSilgi(): Silgi;
117
149
  /**
118
- * Creates a type-safe API route schema definition.
119
- *
120
- * This utility function helps you define API schemas with proper typing for
121
- * input, output, path parameters, and query parameters.
122
- *
123
- * @template Path - API path from Routers type
124
- * @template Method - HTTP method
125
- *
126
- * @param params - Schema configuration parameters
127
- * @param params.path - Complete API path
128
- * @param params.method - HTTP method(s) as an array (optional)
129
- * @param params.setup - Schema definition for the specified methods
130
- * @returns Route schema object with complete type information
150
+ * Get access to Nuxt instance.
131
151
  *
152
+ * Returns null if Nuxt instance is unavailable.
132
153
  * @example
133
- * // Define a user API schema with GET and POST methods sharing the same schema
134
- * const userSchema = createSchema({
135
- * path: '/api/v1/users',
136
- * method: ['GET', 'POST'],
137
- * setup: {
138
- * output: z.object({
139
- * users: z.array(z.object({ id: z.string(), name: z.string() }))
140
- * })
141
- * }
142
- * });
154
+ * ```js
155
+ * const silgi = tryUseSilgi()
156
+ * if (silgi) {
157
+ * // Do something
158
+ * }
159
+ * ```
143
160
  */
144
- declare function createSchema<Key extends string, Schema extends BaseMethodSchema>(params: {
145
- key: Key;
146
- setup: Schema;
147
- }): {
148
- [K in Key]: Schema;
149
- };
161
+ declare function tryUseSilgi(): Silgi | null;
162
+
163
+ declare function getEvent<T extends SilgiEvent>(event?: SilgiEvent): T;
164
+ declare function getEventContext<T extends SilgiRuntimeContext>(event?: SilgiEvent): T;
150
165
 
151
166
  /**
152
167
  * Merges multiple service definition objects into a single object.
@@ -157,13 +172,6 @@ declare function createSchema<Key extends string, Schema extends BaseMethodSchem
157
172
  */
158
173
  declare function deepMergeObjects<T extends readonly Record<string, any>[]>(schemas: [...T]): MergeAll<T>;
159
174
 
160
- /**
161
- * ServiceSetup tipinden oluşan bir yardımcı fonksiyon.
162
- * Tip güvenliğini artırmak için ServiceSetup objesini doğrudan döndürür.
163
- */
164
- declare function defineServiceSetup<Parent extends StandardSchemaV1, Method extends HTTPMethod, Path extends keyof Routers, Input extends StandardSchemaV1 = StandardSchemaV1, Output extends StandardSchemaV1 = StandardSchemaV1, PathParams extends StandardSchemaV1 | undefined | never = undefined, QueryParams extends StandardSchemaV1 | undefined | never = undefined, Resolved extends boolean = false, HiddenParameters extends boolean = false>(setup: Omit<ServiceSetup<Parent, Method, Path, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>, 'method' | 'path' | 'apiType'>): Omit<ServiceSetup<Parent, Method, Path, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>, 'method' | 'path' | 'apiType'>;
165
- declare function createService<Path extends string, Method extends HTTPMethod, Parent extends StandardSchemaV1 = StandardSchemaV1, Input extends StandardSchemaV1 = StandardSchemaV1, Output extends StandardSchemaV1 = StandardSchemaV1, PathParams extends StandardSchemaV1 | undefined | never = undefined, QueryParams extends StandardSchemaV1 | undefined | never = undefined, Resolved extends boolean = false, HiddenParameters extends boolean = false>(params: ServiceSetupsForMethods<Parent, Method, Path, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>): ServiceDefinitionByMethodAndPath<Path, Method, Parent, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>;
166
-
167
175
  type WildcardVariants<Path extends string, Acc extends string = ''> = Path extends `${infer Head}/${infer Tail}` ? Tail extends '' ? `${Acc}${Head}` : `${Acc}${Head}/${Tail}` | `${Acc}${Head}/*` | `${Acc}${Head}/**` | WildcardVariants<Tail, `${Acc}${Head}/`> : `${Acc}${Path}`;
168
176
  type MiddlewarePath<S extends WildcardVariants<keyof Routers>> = S | 'global';
169
177
  interface CreateMiddlewareParams<S extends WildcardVariants<keyof Routers>, UsedMethod extends readonly HTTPMethod[] = readonly HTTPMethod[], Key extends string = string> {
@@ -184,53 +192,60 @@ declare function createMiddleware<S extends WildcardVariants<keyof Routers>, Use
184
192
  path: Path;
185
193
  }): CreateMiddlewareResult<Path, UsedMethod, Key>;
186
194
 
187
- declare function createShared(shared: Partial<SilgiRuntimeShareds>): SilgiRuntimeShareds;
195
+ declare function createResolver(resolver: Resolvers): Resolvers;
196
+ declare function getUrlPrefix(path: string, method?: string): SilgiURL;
188
197
 
189
198
  /**
190
199
  * Recursively replaces values starting with 'runtime.' with their actual values from runtime config
191
200
  */
192
201
  declare function replaceRuntimeValues(obj: any, runtime: any): any;
193
202
 
194
- declare function createResolver(resolver: Resolvers): Resolvers;
195
- declare function getUrlPrefix(path: string, method?: string): SilgiURL;
196
-
197
- declare function createStorage(silgi: Silgi): Promise<Storage<StorageValue>>;
198
- declare function useSilgiStorage<T extends StorageValue = StorageValue>(base?: StorageConfig<T>['base'] | (string & {})): Storage<T>;
199
-
200
- declare const silgiCtx: UseContext<Silgi>;
201
- declare function useSilgi(): Silgi;
202
203
  /**
203
- * Get access to Nuxt instance.
204
+ * Creates a type-safe API route schema definition.
205
+ *
206
+ * This utility function helps you define API schemas with proper typing for
207
+ * input, output, path parameters, and query parameters.
208
+ *
209
+ * @template Path - API path from Routers type
210
+ * @template Method - HTTP method
211
+ *
212
+ * @param params - Schema configuration parameters
213
+ * @param params.path - Complete API path
214
+ * @param params.method - HTTP method(s) as an array (optional)
215
+ * @param params.setup - Schema definition for the specified methods
216
+ * @returns Route schema object with complete type information
204
217
  *
205
- * Returns null if Nuxt instance is unavailable.
206
218
  * @example
207
- * ```js
208
- * const silgi = tryUseSilgi()
209
- * if (silgi) {
210
- * // Do something
211
- * }
212
- * ```
219
+ * // Define a user API schema with GET and POST methods sharing the same schema
220
+ * const userSchema = createSchema({
221
+ * path: '/api/v1/users',
222
+ * method: ['GET', 'POST'],
223
+ * setup: {
224
+ * output: z.object({
225
+ * users: z.array(z.object({ id: z.string(), name: z.string() }))
226
+ * })
227
+ * }
228
+ * });
213
229
  */
214
- declare function tryUseSilgi(): Silgi | null;
215
-
216
- declare const silgiCLICtx: UseContext<SilgiCLI>;
217
- declare function useSilgiCLI(): SilgiCLI;
218
- declare function tryUseSilgiCLI(): SilgiCLI | null;
219
-
220
- declare function storageMount<T extends Storage = Storage>(silgi?: Silgi): (base: keyof SilgiStorageBase, driver: Parameters<Storage['mount']>[1]) => T;
230
+ declare function createSchema<Key extends string, Schema extends BaseMethodSchema>(params: {
231
+ key: Key;
232
+ setup: Schema;
233
+ }): {
234
+ [K in Key]: Schema;
235
+ };
221
236
 
222
- declare function updateRuntimeStorage(runtime: any): void;
223
237
  /**
224
- * Get access to silgi instance.
225
- *
226
- * Throws an error if silgi instance is unavailable.
227
- * @example
228
- * ```js
229
- * const runtime = useRuntime()
230
- * ```
238
+ * ServiceSetup tipinden oluşan bir yardımcı fonksiyon.
239
+ * Tip güvenliğini artırmak için ServiceSetup objesini doğrudan döndürür.
231
240
  */
232
- declare function useRuntime(): SilgiRuntimeConfig;
241
+ declare function defineServiceSetup<Parent extends StandardSchemaV1, Method extends HTTPMethod, Path extends keyof Routers, Input extends StandardSchemaV1 = StandardSchemaV1, Output extends StandardSchemaV1 = StandardSchemaV1, PathParams extends StandardSchemaV1 | undefined | never = undefined, QueryParams extends StandardSchemaV1 | undefined | never = undefined, Resolved extends boolean = false, HiddenParameters extends boolean = false>(setup: Omit<ServiceSetup<Parent, Method, Path, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>, 'method' | 'path'>): Omit<ServiceSetup<Parent, Method, Path, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>, 'method' | 'path'>;
242
+ declare function createService<Path extends string, Method extends HTTPMethod, Parent extends StandardSchemaV1 = StandardSchemaV1, Input extends StandardSchemaV1 = StandardSchemaV1, Output extends StandardSchemaV1 = StandardSchemaV1, PathParams extends StandardSchemaV1 | undefined | never = undefined, QueryParams extends StandardSchemaV1 | undefined | never = undefined, Resolved extends boolean = false, HiddenParameters extends boolean = false>(params: ServiceSetupsForMethods<Parent, Method, Path, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>): ServiceDefinitionByMethodAndPath<Path, Method, Parent, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>;
243
+
244
+ declare function createShared(shared: Partial<SilgiRuntimeShareds>): SilgiRuntimeShareds;
245
+
246
+ declare function createStorage(silgi: Silgi): Promise<Storage<StorageValue>>;
247
+ declare function useSilgiStorage<T extends StorageValue = StorageValue>(base?: StorageConfig<T>['base'] | (string & {})): Storage<T>;
233
248
 
234
249
  declare const autoImportTypes: string[];
235
250
 
236
- export { SilgiError, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCLICtx, silgiCtx, silgiFetch, storageMount, tryUseSilgi, tryUseSilgiCLI, updateRuntimeStorage, useRuntime, useSilgi, useSilgiCLI, useSilgiStorage };
251
+ export { SilgiError, SilgiHttpEvent, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCLICtx, silgiCtx, silgiFetch, storageMount, tryUseSilgi, tryUseSilgiCLI, updateRuntimeStorage, useRuntime, useSilgi, useSilgiCLI, useSilgiStorage };
@@ -1,3 +1,5 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { createContext, getContext } from 'unctx';
1
3
  import { toJsonSchema } from '@standard-community/standard-json';
2
4
  import consola, { createConsola } from 'consola';
3
5
  import { defu } from 'defu';
@@ -5,14 +7,32 @@ import { createHooks } from 'hookable';
5
7
  import { createRouter, addRoute, findRoute, findAllRoutes } from 'rou3';
6
8
  import { getServicePath } from 'silgi/kit';
7
9
  import { useRuntimeConfig, sharedRuntimeConfig } from 'silgi/runtime';
8
- import { getContext, createContext } from 'unctx';
9
10
  import { Buffer } from 'node:buffer';
10
11
  import { klona } from 'klona';
11
12
  import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
12
13
  import { isDevelopment } from 'std-env';
13
14
  import { FastURL, FastResponse } from 'srvx';
14
15
  export { s as silgiCLICtx, t as tryUseSilgiCLI, u as useSilgiCLI } from '../_chunks/silgiApp.mjs';
15
- import { AsyncLocalStorage } from 'node:async_hooks';
16
+
17
+ const asyncRuntimeStorage = createContext({
18
+ asyncContext: true,
19
+ AsyncLocalStorage
20
+ });
21
+ function updateRuntimeStorage(runtime) {
22
+ if (asyncRuntimeStorage.tryUse()) {
23
+ asyncRuntimeStorage.unset();
24
+ asyncRuntimeStorage.set(runtime);
25
+ } else {
26
+ asyncRuntimeStorage.set(runtime);
27
+ }
28
+ }
29
+ function useRuntime() {
30
+ const instance = asyncRuntimeStorage.tryUse();
31
+ if (!instance) {
32
+ throw new Error("Runtime instance is unavailable!");
33
+ }
34
+ return instance;
35
+ }
16
36
 
17
37
  const silgiCtx = getContext("silgi");
18
38
  function useSilgi() {
@@ -354,30 +374,13 @@ async function createSilgi(config) {
354
374
  }, {});
355
375
  }
356
376
  }
357
- if (object.apiType === "rest-graphql") {
358
- addRoute(silgi.router, "", routeWithParams, {
359
- method: "",
360
- route: routeWithParams,
361
- service: object,
362
- queryParams: queryParamNames,
363
- pathParams: pathParamNames
364
- });
365
- addRoute(silgi.router, method, routeWithParams, {
366
- method,
367
- route: routeWithParams,
368
- service: object,
369
- queryParams: queryParamNames,
370
- pathParams: pathParamNames
371
- });
372
- } else {
373
- addRoute(silgi.router, method, routeWithParams, {
374
- method,
375
- route: routeWithParams,
376
- service: object,
377
- queryParams: queryParamNames,
378
- pathParams: pathParamNames
379
- });
380
- }
377
+ addRoute(silgi.router, method, routeWithParams, {
378
+ method,
379
+ route: routeWithParams,
380
+ service: object,
381
+ queryParams: queryParamNames,
382
+ pathParams: pathParamNames
383
+ });
381
384
  }
382
385
  if (!silgi._middlewareRouter) {
383
386
  silgi._middlewareRouter = createRouter();
@@ -433,7 +436,7 @@ async function createSilgi(config) {
433
436
  return silgi;
434
437
  }
435
438
 
436
- class _SilgiEvent {
439
+ class SilgiHttpEvent {
437
440
  static __is_event__ = true;
438
441
  req;
439
442
  url;
@@ -446,6 +449,7 @@ class _SilgiEvent {
446
449
  const _url = req._url;
447
450
  this.url = _url && _url instanceof URL ? _url : new FastURL(req.url);
448
451
  }
452
+ _chain;
449
453
  get res() {
450
454
  if (!this._res) {
451
455
  this._res = new SilgiEventResponse();
@@ -471,6 +475,139 @@ class SilgiEventResponse {
471
475
  }
472
476
  }
473
477
 
478
+ const kNotFound = /* @__PURE__ */ Symbol.for("silgi.notFound");
479
+ const kHandled = /* @__PURE__ */ Symbol.for("silgi.handled");
480
+ function handleResponse(val, event, config) {
481
+ if (val && val instanceof Promise) {
482
+ return val.catch((error) => error).then((resolvedVal) => handleResponse(resolvedVal, event, config));
483
+ }
484
+ const response = prepareResponse(val, event, config);
485
+ if (response instanceof Promise) {
486
+ return handleResponse(response, event, config);
487
+ }
488
+ const { onBeforeResponse } = config;
489
+ return onBeforeResponse ? Promise.resolve(onBeforeResponse(event, response)).then(() => response) : response;
490
+ }
491
+ function prepareResponse(val, event, config, nested) {
492
+ if (val === kHandled) {
493
+ return new FastResponse(null);
494
+ }
495
+ if (val === kNotFound) {
496
+ val = createError({
497
+ statusCode: 404,
498
+ statusMessage: `Cannot find any route matching [${event.req.method}] ${event.url}`
499
+ });
500
+ }
501
+ if (val && val instanceof Error) {
502
+ const error = createError(val);
503
+ const { onError } = config;
504
+ return onError && !nested ? Promise.resolve(onError(error, event)).catch((error2) => error2).then((newVal) => prepareResponse(newVal ?? val, event, config, true)) : errorResponse(error, config.debug);
505
+ }
506
+ const eventHeaders = event.res._headers;
507
+ if (!(val instanceof Response)) {
508
+ const res = prepareResponseBody(val, event, config);
509
+ const status = event.res.status;
510
+ return new FastResponse(
511
+ nullBody(event.req.method, status) ? null : res.body,
512
+ {
513
+ status,
514
+ statusText: event.res.statusText,
515
+ headers: res.headers && eventHeaders ? mergeHeaders(res.headers, eventHeaders) : res.headers || eventHeaders
516
+ }
517
+ );
518
+ }
519
+ if (!eventHeaders) {
520
+ return val;
521
+ }
522
+ return new FastResponse(
523
+ nullBody(event.req.method, val.status) ? null : val.body,
524
+ {
525
+ status: val.status,
526
+ statusText: val.statusText,
527
+ headers: mergeHeaders(eventHeaders, val.headers)
528
+ }
529
+ );
530
+ }
531
+ function nullBody(method, status) {
532
+ return method === "HEAD" || status === 100 || status === 101 || status === 102 || status === 204 || status === 205 || status === 304;
533
+ }
534
+ function mergeHeaders(base, merge) {
535
+ const mergedHeaders = new Headers(base);
536
+ for (const [name, value] of merge) {
537
+ if (name === "set-cookie") {
538
+ mergedHeaders.append(name, value);
539
+ } else {
540
+ mergedHeaders.set(name, value);
541
+ }
542
+ }
543
+ return mergedHeaders;
544
+ }
545
+ const emptyHeaders = new Headers({ "content-length": "0" });
546
+ const jsonHeaders = new Headers({
547
+ "content-type": "application/json;charset=UTF-8"
548
+ });
549
+ function prepareResponseBody(val, event, config) {
550
+ if (val === null || val === void 0) {
551
+ return { body: "", headers: emptyHeaders };
552
+ }
553
+ const valType = typeof val;
554
+ if (valType === "string") {
555
+ return { body: val };
556
+ }
557
+ if (val instanceof Uint8Array) {
558
+ event.res.headers.set("content-length", val.byteLength.toString());
559
+ return { body: val };
560
+ }
561
+ if (isJSONSerializable(val, valType)) {
562
+ return {
563
+ body: JSON.stringify(val, void 0, config.debug ? 2 : void 0),
564
+ headers: jsonHeaders
565
+ };
566
+ }
567
+ if (valType === "bigint") {
568
+ return { body: val.toString(), headers: jsonHeaders };
569
+ }
570
+ if (val instanceof Blob) {
571
+ const headers = {
572
+ "content-type": val.type,
573
+ "content-length": val.size.toString()
574
+ };
575
+ if ("name" in val) {
576
+ const filename = encodeURIComponent(val.name);
577
+ headers["content-disposition"] = `filename="${filename}"; filename*=UTF-8''${filename}`;
578
+ }
579
+ return { body: val.stream(), headers };
580
+ }
581
+ if (valType === "symbol") {
582
+ return { body: val.toString() };
583
+ }
584
+ if (valType === "function") {
585
+ return { body: `${val.name}()` };
586
+ }
587
+ return { body: val };
588
+ }
589
+ function errorResponse(error, debug) {
590
+ return new FastResponse(
591
+ JSON.stringify(
592
+ {
593
+ statusCode: error.statusCode,
594
+ statusMessage: error.statusMessage,
595
+ data: error.data,
596
+ stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : void 0
597
+ },
598
+ null,
599
+ 2
600
+ ),
601
+ {
602
+ status: error.statusCode,
603
+ statusText: error.statusMessage,
604
+ headers: {
605
+ "content-type": "application/json; charset=utf-8"
606
+ }
607
+ }
608
+ );
609
+ }
610
+
474
611
  async function parseRequestInput(req) {
475
612
  const contentType = req.headers.get("content-type") || "";
476
613
  if (contentType.startsWith("application/json")) {
@@ -646,15 +783,7 @@ function getUrlPrefix(path, method) {
646
783
  async function orchestrate(route, event, _input, parent, info) {
647
784
  const silgiCtx = useSilgi();
648
785
  const isGraphQL = event.context.protocol === "GRAPHQL";
649
- const silgiURL = !isGraphQL ? getUrlPrefix(route.route || event.req.url, route.method) : {
650
- methodName: route.method || "GET",
651
- namespaceName: "graphql",
652
- prefixName: "/api",
653
- path: route.route || "",
654
- raw: route.route || "",
655
- pathParams: {},
656
- queryParams: {}
657
- };
786
+ const silgiURL = getUrlPrefix(route.route || event.req.url, route.method);
658
787
  const input = _input || (route.service?.rules?.readBeforeBody === false || isGraphQL ? {} : await parseRequestInput(event.req));
659
788
  const hookContext = { earlyReturnValue: false };
660
789
  const routerParams = _input ? input.path : getRouterParams(event);
@@ -790,139 +919,6 @@ async function cacheExecute(input, route, silgiURL, event) {
790
919
  };
791
920
  }
792
921
 
793
- const kNotFound = /* @__PURE__ */ Symbol.for("silgi.notFound");
794
- const kHandled = /* @__PURE__ */ Symbol.for("silgi.handled");
795
- function handleResponse(val, event, config) {
796
- if (val && val instanceof Promise) {
797
- return val.catch((error) => error).then((resolvedVal) => handleResponse(resolvedVal, event, config));
798
- }
799
- const response = prepareResponse(val, event, config);
800
- if (response instanceof Promise) {
801
- return handleResponse(response, event, config);
802
- }
803
- const { onBeforeResponse } = config;
804
- return onBeforeResponse ? Promise.resolve(onBeforeResponse(event, response)).then(() => response) : response;
805
- }
806
- function prepareResponse(val, event, config, nested) {
807
- if (val === kHandled) {
808
- return new FastResponse(null);
809
- }
810
- if (val === kNotFound) {
811
- val = createError({
812
- statusCode: 404,
813
- statusMessage: `Cannot find any route matching [${event.req.method}] ${event.url}`
814
- });
815
- }
816
- if (val && val instanceof Error) {
817
- const error = createError(val);
818
- const { onError } = config;
819
- return onError && !nested ? Promise.resolve(onError(error, event)).catch((error2) => error2).then((newVal) => prepareResponse(newVal ?? val, event, config, true)) : errorResponse(error, config.debug);
820
- }
821
- const eventHeaders = event.res._headers;
822
- if (!(val instanceof Response)) {
823
- const res = prepareResponseBody(val, event, config);
824
- const status = event.res.status;
825
- return new FastResponse(
826
- nullBody(event.req.method, status) ? null : res.body,
827
- {
828
- status,
829
- statusText: event.res.statusText,
830
- headers: res.headers && eventHeaders ? mergeHeaders(res.headers, eventHeaders) : res.headers || eventHeaders
831
- }
832
- );
833
- }
834
- if (!eventHeaders) {
835
- return val;
836
- }
837
- return new FastResponse(
838
- nullBody(event.req.method, val.status) ? null : val.body,
839
- {
840
- status: val.status,
841
- statusText: val.statusText,
842
- headers: mergeHeaders(eventHeaders, val.headers)
843
- }
844
- );
845
- }
846
- function nullBody(method, status) {
847
- return method === "HEAD" || status === 100 || status === 101 || status === 102 || status === 204 || status === 205 || status === 304;
848
- }
849
- function mergeHeaders(base, merge) {
850
- const mergedHeaders = new Headers(base);
851
- for (const [name, value] of merge) {
852
- if (name === "set-cookie") {
853
- mergedHeaders.append(name, value);
854
- } else {
855
- mergedHeaders.set(name, value);
856
- }
857
- }
858
- return mergedHeaders;
859
- }
860
- const emptyHeaders = new Headers({ "content-length": "0" });
861
- const jsonHeaders = new Headers({
862
- "content-type": "application/json;charset=UTF-8"
863
- });
864
- function prepareResponseBody(val, event, config) {
865
- if (val === null || val === void 0) {
866
- return { body: "", headers: emptyHeaders };
867
- }
868
- const valType = typeof val;
869
- if (valType === "string") {
870
- return { body: val };
871
- }
872
- if (val instanceof Uint8Array) {
873
- event.res.headers.set("content-length", val.byteLength.toString());
874
- return { body: val };
875
- }
876
- if (isJSONSerializable(val, valType)) {
877
- return {
878
- body: JSON.stringify(val, void 0, config.debug ? 2 : void 0),
879
- headers: jsonHeaders
880
- };
881
- }
882
- if (valType === "bigint") {
883
- return { body: val.toString(), headers: jsonHeaders };
884
- }
885
- if (val instanceof Blob) {
886
- const headers = {
887
- "content-type": val.type,
888
- "content-length": val.size.toString()
889
- };
890
- if ("name" in val) {
891
- const filename = encodeURIComponent(val.name);
892
- headers["content-disposition"] = `filename="${filename}"; filename*=UTF-8''${filename}`;
893
- }
894
- return { body: val.stream(), headers };
895
- }
896
- if (valType === "symbol") {
897
- return { body: val.toString() };
898
- }
899
- if (valType === "function") {
900
- return { body: `${val.name}()` };
901
- }
902
- return { body: val };
903
- }
904
- function errorResponse(error, debug) {
905
- return new FastResponse(
906
- JSON.stringify(
907
- {
908
- statusCode: error.statusCode,
909
- statusMessage: error.statusMessage,
910
- data: error.data,
911
- stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : void 0
912
- },
913
- null,
914
- 2
915
- ),
916
- {
917
- status: error.statusCode,
918
- statusText: error.statusMessage,
919
- headers: {
920
- "content-type": "application/json; charset=utf-8"
921
- }
922
- }
923
- );
924
- }
925
-
926
922
  function getHeader(name, headers) {
927
923
  if (!headers) {
928
924
  return;
@@ -972,7 +968,7 @@ async function silgiFetch(_request, options, context) {
972
968
  } else {
973
969
  request = _request;
974
970
  }
975
- const silgiEvent = new _SilgiEvent(request, context);
971
+ const silgiEvent = new SilgiHttpEvent(request, context);
976
972
  let handlerRes;
977
973
  try {
978
974
  handlerRes = handler(silgiEvent);
@@ -981,9 +977,9 @@ async function silgiFetch(_request, options, context) {
981
977
  }
982
978
  return handleResponse(handlerRes, silgiEvent, {});
983
979
  }
984
- async function middleware(event, url) {
980
+ async function middleware(event) {
985
981
  const silgiContext = useSilgi();
986
- const pathname = url?.path || event.url.pathname;
982
+ event._chain = Promise.resolve(await silgiContext.callHook("request:on", event));
987
983
  let _chain = void 0;
988
984
  const _middleware = silgiContext.globalMiddlewares;
989
985
  if (_middleware) {
@@ -1020,7 +1016,7 @@ async function middleware(event, url) {
1020
1016
  }
1021
1017
  const _mRouter = silgiContext._middlewareRouter;
1022
1018
  if (_mRouter) {
1023
- const matches = findAllRoutes(_mRouter, url?.method || event.req.method, pathname);
1019
+ const matches = findAllRoutes(_mRouter, event.req.method, event.url.pathname);
1024
1020
  if (matches.length > 0) {
1025
1021
  _chain = _chain || Promise.resolve();
1026
1022
  for (const match of matches) {
@@ -1028,9 +1024,7 @@ async function middleware(event, url) {
1028
1024
  if (_previous !== void 0 && _previous !== kNotFound) {
1029
1025
  return _previous;
1030
1026
  }
1031
- const allowedMethod = match.data.method ?? "";
1032
- const methodIsAllowed = allowedMethod === event.req.method || event.protocol === "GRAPHQL";
1033
- if (!methodIsAllowed || !match.data.middleware) {
1027
+ if (!(match.data.method === event.req.method) || !match.data.middleware) {
1034
1028
  return;
1035
1029
  }
1036
1030
  event.context.params = match.params;
@@ -1053,52 +1047,24 @@ async function middleware(event, url) {
1053
1047
  }
1054
1048
  }
1055
1049
  }
1056
- return _chain;
1050
+ event._chain = _chain;
1057
1051
  }
1058
- async function handler(event, url, input, parent, info) {
1059
- url ??= {};
1060
- url.method = event.context.protocol === "GRAPHQL" ? "" : url.method || event.req.method;
1061
- const silgiCtx = useSilgi();
1062
- const pathname = url?.path || event.url.pathname;
1063
- let _chain = void 0;
1064
- _chain = Promise.resolve(await silgiCtx.callHook("request:on", event));
1065
- const data = middleware(event, url);
1066
- _chain = data;
1067
- if (silgiCtx.router) {
1068
- const match = findRoute(silgiCtx.router, url.method, pathname);
1069
- if (match) {
1070
- if (url.method === "" && input) {
1071
- if (input?.path) {
1072
- const expectedPathKeys = Object.keys(match.data.pathParams ?? {});
1073
- const inputPathKeys = Object.keys(input.path);
1074
- for (const key of inputPathKeys) {
1075
- if (!expectedPathKeys.includes(key)) {
1076
- throw createError({
1077
- message: `Unexpected path param key: ${key}`,
1078
- statusCode: 400,
1079
- statusMessage: "Invalid path parameter"
1080
- });
1081
- }
1082
- }
1083
- match.data.pathParams = input.path;
1084
- }
1085
- if (input?.query) {
1086
- const expectedQueryKeys = Object.keys(match.data.queryParams ?? {});
1087
- const inputQueryKeys = Object.keys(input.query);
1088
- for (const key of inputQueryKeys) {
1089
- if (!expectedQueryKeys.includes(key)) {
1090
- throw createError({
1091
- message: `Unexpected query param key: ${key}`,
1092
- statusCode: 400,
1093
- statusMessage: "Invalid query parameter"
1094
- });
1095
- }
1096
- }
1097
- match.data.queryParams = input.query;
1098
- }
1052
+ async function handler(event, middlewareMode = false, input, parent, info, callBack) {
1053
+ event._chain = middleware(event);
1054
+ if (middlewareMode) {
1055
+ if (event._chain) {
1056
+ const data = await event._chain;
1057
+ if (data !== void 0 && data !== kNotFound) {
1058
+ return data;
1099
1059
  }
1100
- if (_chain) {
1101
- return _chain.then(async (_previous) => {
1060
+ }
1061
+ }
1062
+ const silgiContext = useSilgi();
1063
+ if (silgiContext.router) {
1064
+ const match = findRoute(silgiContext.router, event.req.method, event.url.pathname);
1065
+ if (match) {
1066
+ if (event._chain) {
1067
+ return event._chain.then(async (_previous) => {
1102
1068
  if (_previous !== void 0 && _previous !== kNotFound) {
1103
1069
  return _previous;
1104
1070
  }
@@ -1113,11 +1079,23 @@ async function handler(event, url, input, parent, info) {
1113
1079
  }
1114
1080
  }
1115
1081
  }
1116
- return _chain ? _chain.then(
1082
+ return event._chain ? event._chain.then(
1117
1083
  (_previous) => _previous === void 0 ? kNotFound : _previous
1118
1084
  ) : kNotFound;
1119
1085
  }
1120
1086
 
1087
+ function storageMount(silgi) {
1088
+ const _silgi = silgi || useSilgi();
1089
+ return (base, driver) => {
1090
+ const existingStorage = _silgi.storage.getMount(base);
1091
+ if (existingStorage) {
1092
+ return existingStorage.driver;
1093
+ }
1094
+ const storage = _silgi.storage.mount(base, driver);
1095
+ return storage;
1096
+ };
1097
+ }
1098
+
1121
1099
  function getEvent(event) {
1122
1100
  if (event?.event) {
1123
1101
  return getEvent(event.event);
@@ -1129,16 +1107,6 @@ function getEventContext(event) {
1129
1107
  return _event.context;
1130
1108
  }
1131
1109
 
1132
- function createSchema(params) {
1133
- const { key, setup } = params;
1134
- const result = {};
1135
- result[key] = {
1136
- setup,
1137
- key
1138
- };
1139
- return result;
1140
- }
1141
-
1142
1110
  function deepMerge(target, source) {
1143
1111
  if (typeof target !== "object" || target === null)
1144
1112
  return source;
@@ -1162,15 +1130,6 @@ function deepMergeObjects(schemas) {
1162
1130
  return merged;
1163
1131
  }
1164
1132
 
1165
- function defineServiceSetup(setup) {
1166
- return setup;
1167
- }
1168
- function createService(params) {
1169
- return {
1170
- [`${params.method}:${params.path}`]: params
1171
- };
1172
- }
1173
-
1174
1133
  function createMiddleware(params) {
1175
1134
  return {
1176
1135
  [`${params.key}:${params.path}`]: {
@@ -1182,40 +1141,27 @@ function createMiddleware(params) {
1182
1141
  };
1183
1142
  }
1184
1143
 
1185
- function createShared(shared) {
1186
- return shared;
1144
+ function createSchema(params) {
1145
+ const { key, setup } = params;
1146
+ const result = {};
1147
+ result[key] = {
1148
+ setup,
1149
+ key
1150
+ };
1151
+ return result;
1187
1152
  }
1188
1153
 
1189
- function storageMount(silgi) {
1190
- const _silgi = silgi || useSilgi();
1191
- return (base, driver) => {
1192
- const existingStorage = _silgi.storage.getMount(base);
1193
- if (existingStorage) {
1194
- return existingStorage.driver;
1195
- }
1196
- const storage = _silgi.storage.mount(base, driver);
1197
- return storage;
1154
+ function defineServiceSetup(setup) {
1155
+ return setup;
1156
+ }
1157
+ function createService(params) {
1158
+ return {
1159
+ [`${params.method}:${params.path}`]: params
1198
1160
  };
1199
1161
  }
1200
1162
 
1201
- const asyncRuntimeStorage = createContext({
1202
- asyncContext: true,
1203
- AsyncLocalStorage
1204
- });
1205
- function updateRuntimeStorage(runtime) {
1206
- if (asyncRuntimeStorage.tryUse()) {
1207
- asyncRuntimeStorage.unset();
1208
- asyncRuntimeStorage.set(runtime);
1209
- } else {
1210
- asyncRuntimeStorage.set(runtime);
1211
- }
1212
- }
1213
- function useRuntime() {
1214
- const instance = asyncRuntimeStorage.tryUse();
1215
- if (!instance) {
1216
- throw new Error("Runtime instance is unavailable!");
1217
- }
1218
- return instance;
1163
+ function createShared(shared) {
1164
+ return shared;
1219
1165
  }
1220
1166
 
1221
1167
  const autoImportTypes = [
@@ -1225,4 +1171,4 @@ const autoImportTypes = [
1225
1171
  "ExtractQueryParamsFromURI"
1226
1172
  ];
1227
1173
 
1228
- export { SilgiError, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCtx, silgiFetch, storageMount, tryUseSilgi, updateRuntimeStorage, useRuntime, useSilgi, useSilgiStorage };
1174
+ export { SilgiError, SilgiHttpEvent, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCtx, silgiFetch, storageMount, tryUseSilgi, updateRuntimeStorage, useRuntime, useSilgi, useSilgiStorage };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
- export { SilgiError, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCLICtx, silgiCtx, silgiFetch, storageMount, tryUseSilgi, tryUseSilgiCLI, updateRuntimeStorage, useRuntime, useSilgi, useSilgiCLI, useSilgiStorage } from './core/index.mjs';
1
+ export { SilgiError, SilgiHttpEvent, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCLICtx, silgiCtx, silgiFetch, storageMount, tryUseSilgi, tryUseSilgiCLI, updateRuntimeStorage, useRuntime, useSilgi, useSilgiCLI, useSilgiStorage } from './core/index.mjs';
2
2
  import 'silgi/types';
3
+ import 'srvx';
3
4
  import 'graphql';
4
- import '@standard-schema/spec';
5
- import 'unstorage';
6
5
  import 'unctx';
6
+ import 'unstorage';
7
+ import '@standard-schema/spec';
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
- export { SilgiError, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCtx, silgiFetch, storageMount, tryUseSilgi, updateRuntimeStorage, useRuntime, useSilgi, useSilgiStorage } from './core/index.mjs';
1
+ export { SilgiError, SilgiHttpEvent, autoImportTypes, createError, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCtx, silgiFetch, storageMount, tryUseSilgi, updateRuntimeStorage, useRuntime, useSilgi, useSilgiStorage } from './core/index.mjs';
2
2
  export { s as silgiCLICtx, t as tryUseSilgiCLI, u as useSilgiCLI } from './_chunks/silgiApp.mjs';
3
+ import 'node:async_hooks';
4
+ import 'unctx';
3
5
  import '@standard-community/standard-json';
4
6
  import 'consola';
5
7
  import 'defu';
@@ -7,10 +9,8 @@ import 'hookable';
7
9
  import 'rou3';
8
10
  import 'silgi/kit';
9
11
  import 'silgi/runtime';
10
- import 'unctx';
11
12
  import 'node:buffer';
12
13
  import 'klona';
13
14
  import 'unstorage';
14
15
  import 'std-env';
15
16
  import 'srvx';
16
- import 'node:async_hooks';
@@ -106,6 +106,7 @@ type EventProtocol = 'GRAPHQL' | 'HTTP' | 'WEBSOCKET';
106
106
  * Bu nitrojs, h3 event or request context.
107
107
  */
108
108
  interface SilgiEvent extends Record<string, unknown> {
109
+ _chain: Promise<unknown> | undefined;
109
110
  /**
110
111
  * Event context.
111
112
  */
@@ -270,7 +271,6 @@ type ServiceHandler<Parent extends StandardSchemaV1, Input extends StandardSchem
270
271
  interface ServiceSetup<Parent extends StandardSchemaV1 = StandardSchemaV1, Method extends HTTPMethod = HTTPMethod, Path extends string = string, Input extends StandardSchemaV1 = StandardSchemaV1, Output extends StandardSchemaV1 = StandardSchemaV1, PathParams extends StandardSchemaV1 | undefined | never = undefined, QueryParams extends StandardSchemaV1 | undefined | never = undefined, Resolved extends boolean = false, HiddenParameters extends boolean = false> {
271
272
  path: Path;
272
273
  method: Method;
273
- apiType: 'rest' | 'rest-graphql';
274
274
  handler?: ServiceHandler<Parent, Input, Output, PathParams, QueryParams, Resolved, HiddenParameters>;
275
275
  rules?: MergeRouteRules;
276
276
  modules?: Partial<SetupModuleOption>;
@@ -469,7 +469,7 @@ interface ResolvedModuleMeta extends ModuleMeta {
469
469
  }
470
470
  type ModuleHookContext = Readonly<{
471
471
  event?: SilgiEvent;
472
- url: SilgiURL;
472
+ url?: SilgiURL;
473
473
  input?: unknown;
474
474
  result?: unknown;
475
475
  route?: SilgiRoute;
@@ -477,7 +477,7 @@ type ModuleHookContext = Readonly<{
477
477
  success?: boolean;
478
478
  cached?: boolean;
479
479
  }> & {
480
- hookContext: {
480
+ hookContext?: {
481
481
  earlyReturnValue: any | false;
482
482
  };
483
483
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "silgi",
3
3
  "type": "module",
4
- "version": "0.41.31",
4
+ "version": "0.41.34",
5
5
  "private": false,
6
6
  "sideEffects": false,
7
7
  "exports": {