silgi 0.34.10 → 0.34.12

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/dist/build.mjs CHANGED
@@ -14,6 +14,7 @@ import 'unimport';
14
14
  import '@clack/prompts';
15
15
  import 'node:fs';
16
16
  import 'dotenv';
17
+ import 'knitwork';
17
18
  import 'mlly';
18
19
  import 'dev-jiti';
19
20
  import './cli/compatibility.mjs';
@@ -26,7 +27,6 @@ import 'ufo';
26
27
  import 'node:fs/promises';
27
28
  import 'globby';
28
29
  import 'ignore';
29
- import 'knitwork';
30
30
  import 'klona';
31
31
  import 'silgi/runtime';
32
32
  import 'unstorage';
@@ -2,12 +2,13 @@ import { consola } from 'consola';
2
2
  import { createHooks, createDebugger } from 'hookable';
3
3
  import { resolve, join, relative, extname, basename, dirname, isAbsolute } from 'pathe';
4
4
  import { useSilgiCLI, replaceRuntimeValues, silgiCLICtx, autoImportTypes } from 'silgi';
5
- import { isPresents, addTemplate, addCoreFile, relativeWithDot, hash, removeExtension, resolveAlias, directoryToURL, addImports, baseHeaderBannerComment, writeFile, normalizeTemplate, useLogger, resolveSilgiPath, hasSilgiModule, genEnsureSafeVar, toArray, isDirectory } from 'silgi/kit';
5
+ import { isPresents, addTemplate, addCoreFile, genEnsureSafeVar, relativeWithDot, hash, removeExtension, resolveAlias, directoryToURL, addImports, baseHeaderBannerComment, writeFile, normalizeTemplate, useLogger, resolveSilgiPath, hasSilgiModule, toArray, isDirectory } from 'silgi/kit';
6
6
  import { runtimeDir } from 'silgi/runtime/meta';
7
7
  import { scanExports, createUnimport, toExports } from 'unimport';
8
8
  import * as p from '@clack/prompts';
9
9
  import { existsSync, promises, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
10
10
  import * as dotenv from 'dotenv';
11
+ import { genImport, genTypeImport, genObjectFromRawEntries, genAugmentation } from 'knitwork';
11
12
  import { findTypeExports, findExports, resolvePath, parseNodeModulePath, lookupNodeModuleSubpath } from 'mlly';
12
13
  import { createJiti } from 'dev-jiti';
13
14
  import { h as hasInstalledModule } from './compatibility.mjs';
@@ -18,7 +19,6 @@ import { withTrailingSlash, isRelative } from 'ufo';
18
19
  import { readFile, readdir } from 'node:fs/promises';
19
20
  import { globby } from 'globby';
20
21
  import ignore from 'ignore';
21
- import { genImport, genTypeImport, genAugmentation, genObjectFromRawEntries } from 'knitwork';
22
22
  import { klona } from 'klona';
23
23
  import { useSilgiRuntimeConfig, initRuntimeConfig } from 'silgi/runtime';
24
24
  import { createStorage, builtinDrivers } from 'unstorage';
@@ -223,6 +223,52 @@ async function h3Framework(silgi, skip = false) {
223
223
  }
224
224
  }
225
225
 
226
+ async function nextJS(silgi, skip = false) {
227
+ if (!isPresents(["next"]) && skip === false)
228
+ return;
229
+ if (isPresents(["next"])) {
230
+ silgi.hook("after:schema.ts", (data) => {
231
+ data.unshift("type FrameworkContextExtends = {}");
232
+ });
233
+ }
234
+ const defaultConfig = {
235
+ serverExternalPackages: [
236
+ "mlly",
237
+ "silgi",
238
+ "h3",
239
+ "@silgi/openapi",
240
+ "@silgi/scalar",
241
+ "@silgi/ecosystem"
242
+ ],
243
+ eslint: {
244
+ ignoreDuringBuilds: true
245
+ },
246
+ output: "standalone"
247
+ };
248
+ await silgi.callHook("nextjs:prepare", {
249
+ config: defaultConfig
250
+ });
251
+ const template = [
252
+ genImport("defu", ["defu"]),
253
+ genTypeImport("next", ["NextConfig"]),
254
+ "export function withNextConfig(config: NextConfig) {",
255
+ "return defu(config,",
256
+ // TODO: make the output code more properly intend.
257
+ genObjectFromRawEntries(
258
+ Object.entries(defaultConfig).map(([key, value]) => [key, genEnsureSafeVar(value)]),
259
+ ""
260
+ ),
261
+ ")}",
262
+ ""
263
+ ];
264
+ addTemplate({
265
+ filename: "next.config.ts",
266
+ where: ".silgi",
267
+ write: true,
268
+ getContents: () => template.join("\n")
269
+ });
270
+ }
271
+
226
272
  async function nitroFramework(silgi, skip = false) {
227
273
  if (!isPresents(["nitro"]) && skip === false)
228
274
  return;
@@ -276,7 +322,8 @@ const frameworkSetup = [
276
322
  emptyFramework,
277
323
  h3Framework,
278
324
  nitroFramework,
279
- nuxtFramework
325
+ nuxtFramework,
326
+ nextJS
280
327
  ];
281
328
 
282
329
  async function registerModuleExportScan(silgi) {
@@ -1059,33 +1106,21 @@ async function prepareScanFile(silgi) {
1059
1106
  }),
1060
1107
  ""
1061
1108
  ];
1109
+ const generateExport = (name, items, defaultEmpty = "{}") => {
1110
+ const hasItems = items.length > 0;
1111
+ return [
1112
+ `export const ${name} = ${hasItems ? "deepMergeObjects([" : defaultEmpty}`,
1113
+ ...items.map((item) => ` ${item},`),
1114
+ hasItems ? "])" : defaultEmpty === "{}" ? "}" : "",
1115
+ ""
1116
+ ];
1117
+ };
1062
1118
  const importData = [
1063
1119
  "",
1064
- scanned.schemas.length > 0 ? "export const schemas = deepMergeObjects([" : "export const schemas = {",
1065
- ...scanned.schemas.map((name) => {
1066
- return ` ${name},`;
1067
- }),
1068
- scanned.schemas.length > 0 ? "])" : "}",
1069
- "",
1070
- scanned.services.length > 0 ? "export const services = deepMergeObjects([" : "export const services = {",
1071
- ...scanned.services.map((name) => {
1072
- return ` ${name},`;
1073
- }),
1074
- scanned.services.length > 0 ? "])" : "}",
1075
- "",
1076
- scanned.shareds.length > 0 ? "export const shareds = deepMergeObjects([" : "export const shareds = {",
1077
- ...scanned.shareds.map((name) => {
1078
- return ` ${name},`;
1079
- }),
1080
- "",
1081
- scanned.shareds.length > 0 ? "])" : "}",
1082
- "",
1083
- scanned.routers.length > 0 ? "export const routers = deepMergeObjects([" : "export const routers = {",
1084
- ...scanned.routers.map((name) => {
1085
- return ` ${name},`;
1086
- }),
1087
- scanned.routers.length > 0 ? "])" : "}",
1088
- ""
1120
+ ...generateExport("schemas", scanned.schemas),
1121
+ ...generateExport("services", scanned.services),
1122
+ ...generateExport("shareds", scanned.shareds, "undefined"),
1123
+ ...generateExport("routers", scanned.routers)
1089
1124
  ];
1090
1125
  await silgi.callHook("after:scan.ts", importData);
1091
1126
  importData.unshift(...importsContent);
@@ -1394,14 +1429,14 @@ async function createSilgiCLI(config = {}, opts = {}) {
1394
1429
  packageImport: "silgi/runtime/internal/debug"
1395
1430
  });
1396
1431
  }
1397
- for (const framework of frameworkSetup) {
1398
- await framework(silgi);
1399
- }
1400
1432
  await scanAndSyncOptions(silgi);
1401
1433
  await scanModules$1(silgi);
1402
1434
  await scanSilgiExports();
1403
1435
  await installModules(silgi, true);
1404
1436
  useCLIRuntimeConfig(silgi);
1437
+ for (const framework of frameworkSetup) {
1438
+ await framework(silgi);
1439
+ }
1405
1440
  await writeScanFiles(silgi);
1406
1441
  silgi.storage = await createStorageCLI(silgi);
1407
1442
  silgi.hooks.hook("close", async () => {
@@ -1791,20 +1826,6 @@ async function prepareSchema(silgi) {
1791
1826
  ""
1792
1827
  ];
1793
1828
  const importData = [
1794
- generateTypes(
1795
- await resolveSchema(
1796
- {
1797
- ...silgi.options.namespaces?.reduce((acc, key) => ({ ...acc, [key]: "" }), {}) || {}
1798
- }
1799
- ),
1800
- {
1801
- interfaceName: "InferredNamespaces",
1802
- addExport: false,
1803
- addDefaults: false,
1804
- allowExtraKeys: false,
1805
- indentation: 0
1806
- }
1807
- ),
1808
1829
  "",
1809
1830
  `type SchemaExtends = typeof import('${silgiScanTS}')['schemas']`,
1810
1831
  `type BaseServices = typeof import('${silgiScanTS}')['services']`,
@@ -1877,7 +1898,6 @@ async function prepareSchema(silgi) {
1877
1898
  FrameworkContext: [{}, { extends: ["FrameworkContextExtends"] }],
1878
1899
  SilgiSchema: [{}, { extends: ["SchemaExtends"] }],
1879
1900
  ServicesObject: [{}, { extends: ["BaseServices"] }],
1880
- SilgiNamespaces: [{}, { extends: ["InferredNamespaces"] }],
1881
1901
  SilgiStorageBase: [{}, { extends: ["SilgiStorageBaseExtends"] }],
1882
1902
  SilgiURIs: [{}, { extends: ["SilgiURIsMerge"] }],
1883
1903
  SilgiRuntimeContext: [{}, { extends: ["SilgiModuleContextExtends"] }],
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from 'citty';
3
3
 
4
- const version = "0.34.10";
4
+ const version = "0.34.12";
5
5
  const packageJson = {
6
6
  version: version};
7
7
 
package/dist/cli/init.mjs CHANGED
@@ -13,6 +13,7 @@ import 'silgi/kit';
13
13
  import 'silgi/runtime/meta';
14
14
  import 'unimport';
15
15
  import 'dotenv';
16
+ import 'knitwork';
16
17
  import 'mlly';
17
18
  import 'dev-jiti';
18
19
  import './compatibility.mjs';
@@ -23,7 +24,6 @@ import 'exsolve';
23
24
  import 'ufo';
24
25
  import 'globby';
25
26
  import 'ignore';
26
- import 'knitwork';
27
27
  import 'klona';
28
28
  import 'silgi/runtime';
29
29
  import 'unstorage';
@@ -69,8 +69,6 @@ const command = defineCommand({
69
69
  "export default defineSilgiConfig({",
70
70
  ` preset: '${framework}',`,
71
71
  ` compatibilityDate: '${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}',`,
72
- " // Please create a namespace for your project",
73
- " namespaces: [],",
74
72
  "",
75
73
  "})",
76
74
  ""
@@ -15,6 +15,7 @@ import 'unimport';
15
15
  import '@clack/prompts';
16
16
  import 'node:fs';
17
17
  import 'dotenv';
18
+ import 'knitwork';
18
19
  import 'mlly';
19
20
  import 'dev-jiti';
20
21
  import './compatibility.mjs';
@@ -26,7 +27,6 @@ import 'ufo';
26
27
  import 'node:fs/promises';
27
28
  import 'globby';
28
29
  import 'ignore';
29
- import 'knitwork';
30
30
  import 'klona';
31
31
  import 'silgi/runtime';
32
32
  import 'unstorage';
@@ -17,6 +17,7 @@ import 'unimport';
17
17
  import '@clack/prompts';
18
18
  import 'node:fs';
19
19
  import 'dotenv';
20
+ import 'knitwork';
20
21
  import 'mlly';
21
22
  import 'dev-jiti';
22
23
  import './compatibility.mjs';
@@ -28,7 +29,6 @@ import 'ufo';
28
29
  import 'node:fs/promises';
29
30
  import 'globby';
30
31
  import 'ignore';
31
- import 'knitwork';
32
32
  import 'klona';
33
33
  import 'silgi/runtime';
34
34
  import 'unstorage';
@@ -1,4 +1,4 @@
1
- import { SilgiConfig, Silgi, SilgiEvent, SilgiSchema, ServiceSetup, CustomRequestInit, SilgiRuntimeContext, AllPrefixes, NamespacesForPrefix, RoutesForPrefixAndNamespace, HTTPMethod, ExtractPathParamKeys, MergeAll, SilgiRuntimeShareds, RouteConfig, SilgiURL, StorageConfig, SilgiCLI, SilgiStorageBase } from 'silgi/types';
1
+ import { SilgiConfig, Silgi, SilgiEvent, SilgiSchema, ServiceSetup, CustomRequestInit, SilgiRuntimeContext, AllPrefixes, NamespacesForPrefix, RoutesForPrefixAndNamespace, MethodSchemas, MergeAll, ServiceMethods, SilgiRuntimeShareds, RouteConfig, SilgiURL, StorageConfig, SilgiCLI, SilgiStorageBase } from 'silgi/types';
2
2
  import { StandardSchemaV1 } from '@standard-schema/spec';
3
3
  import { Storage, StorageValue } from 'unstorage';
4
4
  import { UseContext } from 'unctx';
@@ -106,62 +106,6 @@ declare function handleResponse(val: unknown, event: SilgiEvent, config: SilgiHa
106
106
  declare function getEvent<T extends SilgiEvent>(event?: SilgiEvent): T;
107
107
  declare function getEventContext<T extends SilgiRuntimeContext>(event?: SilgiEvent): T;
108
108
 
109
- /**
110
- * Creates an object type representing path parameters extracted from a URL pattern.
111
- *
112
- * @example
113
- * PathParamsObject<'/users/:id/posts/:postId'> // { id: string | number, postId: string | number }
114
- */
115
- type PathParamsObject<S extends string> = {
116
- [K in ExtractPathParamKeys<S>]: string | number;
117
- };
118
- /**
119
- * Determines if a URL pattern contains any path parameters.
120
- *
121
- * @example
122
- * HasPathParams<'/users/:id'> // true
123
- * HasPathParams<'/users'> // false
124
- */
125
- type HasPathParams<S extends string> = ExtractPathParamKeys<S> extends never ? false : true;
126
- /**
127
- * Base schema definition for API method handlers.
128
- * Defines the structure of input/output data.
129
- */
130
- interface BaseMethodSchema {
131
- /** Schema for request body */
132
- input?: StandardSchemaV1;
133
- /** Schema for response body */
134
- output?: StandardSchemaV1;
135
- /** Schema for URL query parameters */
136
- queryParams?: StandardSchemaV1;
137
- /** Schema for source data (contextual information) */
138
- source?: StandardSchemaV1;
139
- }
140
- /**
141
- * Interface for adding path parameters schema to method definitions.
142
- */
143
- interface WithPathParams<PathParamsStr extends string> {
144
- /** Schema for path parameters */
145
- pathParams: StandardSchemaV1<PathParamsObject<PathParamsStr>>;
146
- }
147
- /**
148
- * Defines the schema structure for HTTP methods, conditionally including
149
- * path parameters based on the URL pattern.
150
- *
151
- * @example
152
- * // For a route with path parameters:
153
- * type UserMethodSchema = MethodSchemas<'/:id'>
154
- * // Result includes required pathParams for each method
155
- *
156
- * // For a route without path parameters:
157
- * type ListMethodSchema = MethodSchemas<''>
158
- * // Result doesn't allow pathParams property
159
- */
160
- type MethodSchemas<PathParamsStr extends string = ''> = {
161
- [K in HTTPMethod]?: HasPathParams<PathParamsStr> extends true ? BaseMethodSchema & WithPathParams<PathParamsStr> : BaseMethodSchema & {
162
- pathParams?: never;
163
- };
164
- };
165
109
  /**
166
110
  * Creates a type-safe API route schema definition.
167
111
  *
@@ -288,9 +232,6 @@ declare function createSchema<P extends AllPrefixes, N extends NamespacesForPref
288
232
  */
289
233
  declare function deepMergeObjects<T extends readonly Record<string, any>[]>(schemas: [...T]): MergeAll<T>;
290
234
 
291
- type ServiceMethods<Schema extends SilgiSchema, Path extends keyof Schema, Resolved extends boolean = false, HiddenParameters extends boolean = false> = {
292
- [M in keyof Schema[Path]]?: ServiceSetup<Schema, Path, M, Resolved, HiddenParameters>;
293
- };
294
235
  declare function createService<Schema extends SilgiSchema, Path extends keyof Schema, Resolved extends boolean = false, Methods extends ServiceMethods<Schema, Path, Resolved> = ServiceMethods<Schema, Path, Resolved>>(params: {
295
236
  path: Path;
296
237
  methods: Methods;
@@ -15,8 +15,9 @@ import { H3Event, HTTPMethod as HTTPMethod$1, Session } from 'h3';
15
15
  import * as nitropack_types from 'nitropack/types';
16
16
  import { NitroRuntimeConfig } from 'nitropack/types';
17
17
  import { Defu } from 'defu';
18
- import { Stats } from 'node:fs';
19
18
  import * as next from 'next';
19
+ import { NextConfig } from 'next';
20
+ import { Stats } from 'node:fs';
20
21
  import { ESMImport, ESMCodeGenOptions } from 'knitwork';
21
22
  import { Unimport } from 'unimport';
22
23
  import { Storage, TransactionOptions, BuiltinDriverName, StorageValue } from 'unstorage';
@@ -304,6 +305,9 @@ interface SilgiCLIHooks extends SilgiHooks {
304
305
  'app:templatesGenerated': (app: SilgiCLI, templates: ResolvedSilgiTemplate[], options?: GenerateAppOptions) => HookResult;
305
306
  'scanFiles:done': (app: SilgiCLI) => HookResult;
306
307
  'prepare:commands': (commands: Commands[]) => HookResult;
308
+ 'nextjs:prepare': (data: {
309
+ config: NextConfig;
310
+ }) => HookResult;
307
311
  }
308
312
  type TSReference = {
309
313
  types: string;
@@ -316,6 +320,9 @@ interface GenerateAppOptions {
316
320
  filter?: (template: ResolvedSilgiTemplate<any>) => boolean;
317
321
  }
318
322
 
323
+ type ServiceMethods<Schema extends SilgiSchema$1, Path extends keyof Schema, Resolved extends boolean = false, HiddenParameters extends boolean = false> = {
324
+ [M in keyof Schema[Path]]?: ServiceSetup<Schema, Path, M, Resolved, HiddenParameters>;
325
+ };
319
326
  /**
320
327
  * Yardımcı tipler
321
328
  */
@@ -368,24 +375,20 @@ interface ServiceSetup<Schema extends SilgiSchema$1 = SilgiSchema$1, Route exten
368
375
  storage?: StorageConfig$1<ServiceHandlerInput<Schema, Route, Method, HiddenParameters>>;
369
376
  }
370
377
  /**
371
- * Servis tanımı (tek bir route+method için)
378
+ * Represents a fully resolved service definition that maps route paths
379
+ * to their method handlers and configurations.
380
+ *
381
+ * This interface is designed to be compatible with the structure created
382
+ * by the createService function.
372
383
  */
373
- type ServiceDefinition<Schema extends SilgiSchema$1, Route extends keyof Schema, Method extends keyof Schema[Route], Resolved extends boolean = false> = {
374
- [R in Route]: {
375
- [M in Method]: ServiceSetup<Schema, R, M, Resolved>;
384
+ interface ResolvedServiceDefinition$1 {
385
+ [routePath: string]: {
386
+ [method: string]: {
387
+ handler: (...args: any[]) => Promise<any>;
388
+ modules?: Partial<SilgiRuntimeActions$1>;
389
+ storage?: StorageConfig$1<any>;
390
+ };
376
391
  };
377
- };
378
- /**
379
- * Çoklu servisleri birleştirmek için yardımcı tip
380
- */
381
- type MergeServiceDefinitions<T extends object[]> = T extends [infer F, ...infer R] ? F & MergeServiceDefinitions<R extends object[] ? R : []> : unknown;
382
- /**
383
- * Servis oluşturmak için parametreler
384
- */
385
- interface CreateServiceParams<Schema extends SilgiSchema$1, Route extends keyof Schema, Method extends keyof Schema[Route], Resolved extends boolean = false> {
386
- route: Route;
387
- method: Method;
388
- setup: ServiceSetup<Schema, Route, Method, Resolved>;
389
392
  }
390
393
  /**
391
394
  * SilgiURL tipi
@@ -497,14 +500,9 @@ interface SilgiModule<TOptions extends ModuleOptionsCustom = ModuleOptionsCustom
497
500
 
498
501
  interface SilgiRuntimeMethods {
499
502
  }
500
- interface SilgiNamespaces {
501
- }
502
503
  type CommandType = 'run' | 'prepare' | 'install' | 'dev' | 'init';
503
- interface DefaultNamespaces extends SilgiNamespaces {
504
- }
505
504
  interface SilgiRouterTypes {
506
505
  }
507
- type BaseSilgiMethodType = 'post' | 'delete' | 'put' | 'get' | keyof SilgiRuntimeMethods | (string & {});
508
506
  interface DefaultHooks {
509
507
  }
510
508
  type DeepPartial<T> = T extends (...args: any[]) => any ? T : T extends Record<string, any> ? {
@@ -563,7 +561,6 @@ interface SilgiCLIOptions extends PresetOptions {
563
561
  [key: string]: any;
564
562
  };
565
563
  storages: string[];
566
- namespaces: string[];
567
564
  hooks: NestedHooks<SilgiCLIHooks$1>;
568
565
  plugins: {
569
566
  path: string;
@@ -828,43 +825,140 @@ interface CapturedErrorContext {
828
825
  }
829
826
  type CaptureError = (silgi: Silgi, error: Error, context: CapturedErrorContext) => void;
830
827
 
828
+ /**
829
+ * Main interface containing all route definitions.
830
+ * Example:
831
+ * {
832
+ * "/api/blueSpace/basket/getBook": { ... }
833
+ * }
834
+ */
835
+ interface Routers {
836
+ }
837
+ /**
838
+ * Extracts the prefix (first segment) from a URL, including the leading slash.
839
+ * @example ExtractPrefix<'/api/blueSpace/basket'> // '/api'
840
+ */
841
+ type ExtractPrefix<URL extends string> = URL extends `/${infer Prefix}/${string}` ? `/${Prefix}` : never;
842
+ /**
843
+ * Extracts the namespace (second segment) from a URL, including the leading slash.
844
+ * @example ExtractNamespace<'/api/blueSpace/basket'> // '/blueSpace'
845
+ */
846
+ type ExtractNamespace<URL extends string> = URL extends `/${string}/${infer Namespace}/${string}` ? `/${Namespace}` : never;
847
+ /**
848
+ * Extracts the route (third and subsequent segments) from a URL, including the leading slash.
849
+ * @example ExtractRoute<'/api/blueSpace/basket/getBook'> // '/basket/getBook'
850
+ */
851
+ type ExtractRoute<URL extends string> = URL extends `/${string}/${string}/${infer Route}` ? `/${Route}` : never;
852
+ /**
853
+ * Gets all route keys from Routers as strings.
854
+ * All keys should start with a leading slash.
855
+ */
856
+ type RouterKeys = keyof Routers & string;
857
+ /**
858
+ * Extracts all prefixes (first segment) in the system, including the leading slash.
859
+ * @example AllPrefixes // '/api' | ...
860
+ */
861
+ type AllPrefixes = RouterKeys extends infer K ? K extends string ? ExtractPrefix<K> : never : never;
862
+ /**
863
+ * Extracts all namespaces (second segment) for a given prefix, including the leading slash.
864
+ * @example NamespacesForPrefix<'/api'> // '/blueSpace' | ...
865
+ */
866
+ type NamespacesForPrefix<P extends string> = RouterKeys extends infer K ? K extends string ? K extends `${P}/${infer N}/${string}` ? `/${N}` : never : never : never;
867
+ /**
868
+ * Extracts all routes (third and subsequent segments) for a given prefix and namespace, including the leading slash.
869
+ * @example RoutesForPrefixAndNamespace<'/api', '/blueSpace'> // '/basket/getBook' | ...
870
+ */
871
+ type RoutesForPrefixAndNamespace<P extends string, N extends string> = RouterKeys extends infer K ? K extends string ? K extends `${P}${N}${infer R}` ? `${R}` : never : never : never;
872
+ /**
873
+ * Extracts path parameter keys from a URL pattern string.
874
+ *
875
+ * @example
876
+ * ExtractPathParamKeys<'/users/:id/posts/:postId'> // 'id' | 'postId'
877
+ * ExtractPathParamKeys<'/users/:id?'> // 'id'
878
+ */
879
+ type ExtractPathParamKeys<S extends string> = S extends `${string}:${infer Param}/${infer Rest}` ? Param extends `${infer Key}?` ? Key | ExtractPathParamKeys<Rest> : Param | ExtractPathParamKeys<Rest> : S extends `${string}:${infer Param}` ? Param extends `${infer Key}?` ? Key : Param : never;
880
+ /**
881
+ * Route configuration interface.
882
+ */
883
+ interface RouteConfig<T> {
884
+ route: T;
885
+ setup?: any;
886
+ }
887
+
831
888
  interface SilgiSchema {
832
889
  }
833
890
  interface MergedSilgiSchema {
834
891
  }
835
892
  /**
836
- * Utility type for schema generics to avoid repetition
893
+ * Creates an object type representing path parameters extracted from a URL pattern.
894
+ *
895
+ * @example
896
+ * PathParamsObject<'/users/:id/posts/:postId'> // { id: string | number, postId: string | number }
897
+ */
898
+ type PathParamsObject<S extends string> = {
899
+ [K in ExtractPathParamKeys<S>]: string | number;
900
+ };
901
+ /**
902
+ * Determines if a URL pattern contains any path parameters.
903
+ *
904
+ * @example
905
+ * HasPathParams<'/users/:id'> // true
906
+ * HasPathParams<'/users'> // false
907
+ */
908
+ type HasPathParams<S extends string> = ExtractPathParamKeys<S> extends never ? false : true;
909
+ /**
910
+ * Base schema definition for API method handlers.
911
+ * Defines the structure of input/output data.
912
+ */
913
+ interface BaseMethodSchema {
914
+ /** Schema for request body */
915
+ input?: StandardSchemaV1;
916
+ /** Schema for response body */
917
+ output?: StandardSchemaV1;
918
+ /** Schema for URL query parameters */
919
+ queryParams?: StandardSchemaV1;
920
+ /** Schema for source data (contextual information) */
921
+ source?: StandardSchemaV1;
922
+ }
923
+ /**
924
+ * Interface for adding path parameters schema to method definitions.
837
925
  */
838
- interface SchemaParams<TInput extends StandardSchemaV1 | undefined = undefined, TOutput extends StandardSchemaV1 | undefined = undefined, TPathParams extends StandardSchemaV1 | undefined = undefined, TQueryParams extends StandardSchemaV1 | undefined = undefined, TSource extends StandardSchemaV1 | undefined = undefined> {
839
- input?: TInput;
840
- output?: TOutput;
841
- pathParams?: TPathParams;
842
- queryParams?: TQueryParams;
843
- source?: TSource;
926
+ interface WithPathParams<PathParamsStr extends string> {
927
+ /** Schema for path parameters */
928
+ pathParams: StandardSchemaV1<PathParamsObject<PathParamsStr>>;
844
929
  }
845
930
  /**
846
- * Defines the structure for schema components within a service endpoint.
847
- * Allows specifying schemas for input, output, path parameters, query parameters, and source data.
848
- * @template TInput - The schema type for the request body/input.
849
- * @template TOutput - The schema type for the response body/output.
850
- * @template TPathParams - The schema type for URL path parameters.
851
- * @template TQueryParams - The schema type for URL query parameters.
852
- * @template TSource - The schema type for the source data or context.
931
+ * Defines the schema structure for HTTP methods, conditionally including
932
+ * path parameters based on the URL pattern.
933
+ *
934
+ * @example
935
+ * // For a route with path parameters:
936
+ * type UserMethodSchema = MethodSchemas<'/:id'>
937
+ * // Result includes required pathParams for each method
938
+ *
939
+ * // For a route without path parameters:
940
+ * type ListMethodSchema = MethodSchemas<''>
941
+ * // Result doesn't allow pathParams property
942
+ */
943
+ type MethodSchemas<PathParamsStr extends string = ''> = {
944
+ [K in HTTPMethod$1]?: HasPathParams<PathParamsStr> extends true ? BaseMethodSchema & WithPathParams<PathParamsStr> : BaseMethodSchema & {
945
+ pathParams?: never;
946
+ };
947
+ };
948
+ /**
949
+ * Represents a fully resolved schema definition that maps API route paths
950
+ * to their method schemas.
853
951
  */
854
- type SchemaDefinition<TInput extends StandardSchemaV1 | undefined = undefined, TOutput extends StandardSchemaV1 | undefined = undefined, TPathParams extends StandardSchemaV1 | undefined = undefined, TQueryParams extends StandardSchemaV1 | undefined = undefined, TSource extends StandardSchemaV1 | undefined = undefined> = SchemaParams<TInput, TOutput, TPathParams, TQueryParams, TSource>;
952
+ interface ResolvedSchema {
953
+ [routePath: string]: MethodSchemas<string>;
954
+ }
855
955
  /**
856
- * ResolvedServiceDefinition: ServiceDefinition with generics resolved.
857
- * Represents the fully resolved service definition structure.
956
+ * Represents a schema definition that has been fully resolved,
957
+ * typically after processing and validating all schema components.
858
958
  */
859
959
  interface ResolvedSchemaDefinition {
860
- [route: string]: {
861
- [method in HTTPMethod$1]: {
862
- input?: StandardSchemaV1;
863
- output?: StandardSchemaV1;
864
- pathParams?: StandardSchemaV1;
865
- queryParams?: StandardSchemaV1;
866
- source?: StandardSchemaV1;
867
- };
960
+ [key: string]: {
961
+ [method: string]: BaseMethodSchema;
868
962
  };
869
963
  }
870
964
 
@@ -907,7 +1001,8 @@ interface ExtendShared {
907
1001
 
908
1002
  interface FrameworkContext {
909
1003
  }
910
- type HTTPMethod = 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
1004
+ type StandardHTTPMethod = 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
1005
+ type HTTPMethod = SilgiRuntimeMethods extends Record<string, any> ? keyof SilgiRuntimeMethods | StandardHTTPMethod : StandardHTTPMethod;
911
1006
  interface SilgiRoute {
912
1007
  route: string;
913
1008
  method?: HTTPMethod;
@@ -918,7 +1013,7 @@ interface Silgi {
918
1013
  router: RouterContext<SilgiRoute>;
919
1014
  routerPrefixs: string[];
920
1015
  schemas: ResolvedSchemaDefinition;
921
- services: ResolvedServiceDefinition;
1016
+ services: ResolvedServiceDefinition$1;
922
1017
  shared: SilgiRuntimeShareds;
923
1018
  plugins: SilgiAppPlugin[];
924
1019
  framework: FrameworkContext;
@@ -1093,64 +1188,4 @@ interface GraphQLJSON {
1093
1188
  references: any;
1094
1189
  }
1095
1190
 
1096
- /**
1097
- * Main interface containing all route definitions.
1098
- * Example:
1099
- * {
1100
- * "/api/blueSpace/basket/getBook": { ... }
1101
- * }
1102
- */
1103
- interface Routers {
1104
- }
1105
- /**
1106
- * Extracts the prefix (first segment) from a URL, including the leading slash.
1107
- * @example ExtractPrefix<'/api/blueSpace/basket'> // '/api'
1108
- */
1109
- type ExtractPrefix<URL extends string> = URL extends `/${infer Prefix}/${string}` ? `/${Prefix}` : never;
1110
- /**
1111
- * Extracts the namespace (second segment) from a URL, including the leading slash.
1112
- * @example ExtractNamespace<'/api/blueSpace/basket'> // '/blueSpace'
1113
- */
1114
- type ExtractNamespace<URL extends string> = URL extends `/${string}/${infer Namespace}/${string}` ? `/${Namespace}` : never;
1115
- /**
1116
- * Extracts the route (third and subsequent segments) from a URL, including the leading slash.
1117
- * @example ExtractRoute<'/api/blueSpace/basket/getBook'> // '/basket/getBook'
1118
- */
1119
- type ExtractRoute<URL extends string> = URL extends `/${string}/${string}/${infer Route}` ? `/${Route}` : never;
1120
- /**
1121
- * Gets all route keys from Routers as strings.
1122
- * All keys should start with a leading slash.
1123
- */
1124
- type RouterKeys = keyof Routers & string;
1125
- /**
1126
- * Extracts all prefixes (first segment) in the system, including the leading slash.
1127
- * @example AllPrefixes // '/api' | ...
1128
- */
1129
- type AllPrefixes = RouterKeys extends infer K ? K extends string ? ExtractPrefix<K> : never : never;
1130
- /**
1131
- * Extracts all namespaces (second segment) for a given prefix, including the leading slash.
1132
- * @example NamespacesForPrefix<'/api'> // '/blueSpace' | ...
1133
- */
1134
- type NamespacesForPrefix<P extends string> = RouterKeys extends infer K ? K extends string ? K extends `${P}/${infer N}/${string}` ? `/${N}` : never : never : never;
1135
- /**
1136
- * Extracts all routes (third and subsequent segments) for a given prefix and namespace, including the leading slash.
1137
- * @example RoutesForPrefixAndNamespace<'/api', '/blueSpace'> // '/basket/getBook' | ...
1138
- */
1139
- type RoutesForPrefixAndNamespace<P extends string, N extends string> = RouterKeys extends infer K ? K extends string ? K extends `${P}${N}${infer R}` ? `${R}` : never : never : never;
1140
- /**
1141
- * Extracts path parameter keys from a URL pattern string.
1142
- *
1143
- * @example
1144
- * ExtractPathParamKeys<'/users/:id/posts/:postId'> // 'id' | 'postId'
1145
- * ExtractPathParamKeys<'/users/:id?'> // 'id'
1146
- */
1147
- type ExtractPathParamKeys<S extends string> = S extends `${string}:${infer Param}/${infer Rest}` ? Param extends `${infer Key}?` ? Key | ExtractPathParamKeys<Rest> : Param | ExtractPathParamKeys<Rest> : S extends `${string}:${infer Param}` ? Param extends `${infer Key}?` ? Key : Param : never;
1148
- /**
1149
- * Route configuration interface.
1150
- */
1151
- interface RouteConfig<T> {
1152
- route: T;
1153
- setup?: any;
1154
- }
1155
-
1156
- export type { AllPaths, AllPrefixes, AppConfig, Awaitable, BaseSilgiMethodType, BuildSilgi, CaptureError, CapturedErrorContext, CommandType, Commands, CreateServiceParams, CustomRequestInit, DeepPartial, DeepRequired, DefaultHooks, DefaultNamespaces, DefineFrameworkOptions, DotenvOptions, EnvOptions, EventHandlerResponse, ExtendContext, ExtendShared, ExtractNamespace, ExtractPathParamKeys, ExtractPathParams, ExtractPrefix, ExtractRoute, FrameworkContext, GenImport, GenerateAppOptions, GraphQLJSON, HTTPMethod, HookResult, HttpMethod, LoadConfigOptions, MergeAll, MergeServiceDefinitions, MergedSilgiSchema, ModuleDefinition, ModuleHookContext, ModuleMeta, ModuleOptionsCustom, ModuleSetupInstallResult, ModuleSetupReturn, NamespacesForPrefix, NitroBuildInfo, RequiredServiceType, ResolvedModuleMeta, ResolvedModuleOptions, ResolvedSchemaDefinition, ResolvedSilgiTemplate, RouteConfig, RouterParams, Routers, RoutesForPrefixAndNamespace, ScanFile, Schema, SchemaDefinition, SchemaParams, ServiceDefinition, ServiceHandler, ServiceHandlerInput, ServiceHandlerOutput, ServiceHandlerSource, ServiceSetup, Silgi, SilgiAppPlugin, SilgiCLI, SilgiCLIConfig, SilgiCLIDynamicConfig, SilgiCLIHooks, SilgiCLIOptions, SilgiCommands, SilgiCompatibility, SilgiCompatibilityIssue, SilgiCompatibilityIssues, SilgiConfig, SilgiEvent, SilgiFetchClient, SilgiFetchOptions, SilgiFrameworkInfo, SilgiHooks, SilgiModule, SilgiModuleInput, SilgiModuleOptions, SilgiNamespaces, SilgiOptions, SilgiPreset, SilgiPresetMeta, SilgiRoute, SilgiRouterTypes, SilgiRuntimeActions, SilgiRuntimeConfig, SilgiRuntimeContext, SilgiRuntimeHooks, SilgiRuntimeMethods, SilgiRuntimeOptions, SilgiRuntimeShareds, SilgiRuntimeSharedsExtend, SilgiSchema, SilgiStorageBase, SilgiTemplate, SilgiURL, StorageConfig, StorageKeyGenerator, StorageKeyParams, StorageMounts, TSReference, TrimAfterFourSlashes };
1191
+ export type { AllPaths, AllPrefixes, AppConfig, Awaitable, BuildSilgi, CaptureError, CapturedErrorContext, CommandType, Commands, CustomRequestInit, DeepPartial, DeepRequired, DefaultHooks, DefineFrameworkOptions, DotenvOptions, EnvOptions, EventHandlerResponse, ExtendContext, ExtendShared, ExtractNamespace, ExtractPathParamKeys, ExtractPathParams, ExtractPrefix, ExtractRoute, FrameworkContext, GenImport, GenerateAppOptions, GraphQLJSON, HTTPMethod, HookResult, HttpMethod, LoadConfigOptions, MergeAll, MergedSilgiSchema, MethodSchemas, ModuleDefinition, ModuleHookContext, ModuleMeta, ModuleOptionsCustom, ModuleSetupInstallResult, ModuleSetupReturn, NamespacesForPrefix, NitroBuildInfo, RequiredServiceType, ResolvedModuleMeta, ResolvedModuleOptions, ResolvedSchema, ResolvedSchemaDefinition, ResolvedServiceDefinition$1 as ResolvedServiceDefinition, ResolvedSilgiTemplate, RouteConfig, RouterParams, Routers, RoutesForPrefixAndNamespace, ScanFile, Schema, ServiceHandler, ServiceHandlerInput, ServiceHandlerOutput, ServiceHandlerSource, ServiceMethods, ServiceSetup, Silgi, SilgiAppPlugin, SilgiCLI, SilgiCLIConfig, SilgiCLIDynamicConfig, SilgiCLIHooks, SilgiCLIOptions, SilgiCommands, SilgiCompatibility, SilgiCompatibilityIssue, SilgiCompatibilityIssues, SilgiConfig, SilgiEvent, SilgiFetchClient, SilgiFetchOptions, SilgiFrameworkInfo, SilgiHooks, SilgiModule, SilgiModuleInput, SilgiModuleOptions, SilgiOptions, SilgiPreset, SilgiPresetMeta, SilgiRoute, SilgiRouterTypes, SilgiRuntimeActions, SilgiRuntimeConfig, SilgiRuntimeContext, SilgiRuntimeHooks, SilgiRuntimeMethods, SilgiRuntimeOptions, SilgiRuntimeShareds, SilgiRuntimeSharedsExtend, SilgiSchema, SilgiStorageBase, SilgiTemplate, SilgiURL, StandardHTTPMethod, StorageConfig, StorageKeyGenerator, StorageKeyParams, StorageMounts, TSReference, TrimAfterFourSlashes, WithPathParams };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "silgi",
3
3
  "type": "module",
4
- "version": "0.34.10",
4
+ "version": "0.34.12",
5
5
  "private": false,
6
6
  "sideEffects": false,
7
7
  "exports": {