silgi 0.7.1 → 0.7.2

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.
Files changed (83) hide show
  1. package/dist/_chunks/index.mjs +5 -0
  2. package/dist/cli/{utils/compatibility.mjs → compatibility.mjs} +1 -1
  3. package/dist/cli/config/index.d.mts +11 -0
  4. package/dist/cli/config/index.d.ts +11 -0
  5. package/dist/{core/config/types.mjs → cli/config/index.mjs} +19 -2
  6. package/dist/cli/index.mjs +3 -3
  7. package/dist/cli/loader.mjs +581 -0
  8. package/dist/cli/prepare.mjs +1488 -0
  9. package/dist/core/index.d.mts +2 -10
  10. package/dist/core/index.d.ts +2 -10
  11. package/dist/core/index.mjs +943 -16
  12. package/dist/ecosystem/nitro/index.mjs +62 -1
  13. package/dist/ecosystem/nuxt/module.mjs +1 -1
  14. package/dist/kit/index.mjs +299 -10
  15. package/dist/meta/index.d.mts +1 -1
  16. package/dist/meta/index.d.ts +1 -1
  17. package/dist/meta/index.mjs +1 -1
  18. package/package.json +5 -1
  19. package/dist/cli/build/framework/h3.mjs +0 -46
  20. package/dist/cli/build/framework/index.mjs +0 -7
  21. package/dist/cli/build/framework/nitro.mjs +0 -28
  22. package/dist/cli/build/framework/nuxt.mjs +0 -9
  23. package/dist/cli/build/prepare.mjs +0 -7
  24. package/dist/cli/build/scanURIs.mjs +0 -27
  25. package/dist/cli/build/template/framework.mjs +0 -91
  26. package/dist/cli/build/template/schema.mjs +0 -115
  27. package/dist/cli/build/template/silgi.mjs +0 -149
  28. package/dist/cli/build/types.mjs +0 -130
  29. package/dist/cli/commands/prepare.mjs +0 -49
  30. package/dist/cli/common.mjs +0 -13
  31. package/dist/cli/core/app.mjs +0 -89
  32. package/dist/cli/core/scan.mjs +0 -40
  33. package/dist/cli/core/silgi.mjs +0 -77
  34. package/dist/cli/core/storage.mjs +0 -11
  35. package/dist/cli/core/templates.mjs +0 -29
  36. package/dist/cli/module/exportScan.mjs +0 -69
  37. package/dist/cli/module/install.mjs +0 -52
  38. package/dist/cli/module/scan.mjs +0 -141
  39. package/dist/cli/utils/generateRouterDTS.mjs +0 -84
  40. package/dist/cli/utils/ignore.mjs +0 -46
  41. package/dist/cli/utils/readCoreFile.mjs +0 -47
  42. package/dist/cli/utils/scan.mjs +0 -147
  43. package/dist/cli/utils/storage.mjs +0 -21
  44. package/dist/cli/utils/uri.mjs +0 -71
  45. package/dist/core/config/defaults.mjs +0 -96
  46. package/dist/core/config/loader.mjs +0 -98
  47. package/dist/core/config/resolvers/compatibility.mjs +0 -90
  48. package/dist/core/config/resolvers/imports.mjs +0 -96
  49. package/dist/core/config/resolvers/paths.mjs +0 -194
  50. package/dist/core/config/resolvers/storage.mjs +0 -25
  51. package/dist/core/config/resolvers/url.mjs +0 -7
  52. package/dist/core/createSilgi.mjs +0 -84
  53. package/dist/core/error.mjs +0 -227
  54. package/dist/core/fetch/ofetch.mjs +0 -35
  55. package/dist/core/parser.mjs +0 -136
  56. package/dist/core/silgi.mjs +0 -114
  57. package/dist/core/silgiApp.mjs +0 -15
  58. package/dist/core/unctx.mjs +0 -27
  59. package/dist/core/uris/uri.mjs +0 -33
  60. package/dist/core/uris/utils.mjs +0 -127
  61. package/dist/core/utils/event.mjs +0 -5
  62. package/dist/core/utils/global.mjs +0 -12
  63. package/dist/core/utils/merge.mjs +0 -25
  64. package/dist/core/utils/schema.mjs +0 -5
  65. package/dist/core/utils/service.mjs +0 -5
  66. package/dist/core/utils/shared.mjs +0 -5
  67. package/dist/core/utils/storage.mjs +0 -70
  68. package/dist/ecosystem/nitro/module.mjs +0 -62
  69. package/dist/kit/esm.mjs +0 -10
  70. package/dist/kit/fs.mjs +0 -25
  71. package/dist/kit/isFramework.mjs +0 -25
  72. package/dist/kit/logger.mjs +0 -8
  73. package/dist/kit/module.mjs +0 -73
  74. package/dist/kit/path.mjs +0 -34
  75. package/dist/kit/preset.mjs +0 -6
  76. package/dist/kit/resolve.mjs +0 -78
  77. package/dist/kit/template.mjs +0 -47
  78. package/dist/kit/utils.mjs +0 -20
  79. package/dist/package.json.mjs +0 -5
  80. package/dist/schema/common.mjs +0 -43
  81. package/dist/schema/index.mjs +0 -9
  82. package/dist/schema/internal.mjs +0 -22
  83. /package/dist/cli/{commands/init.mjs → init.mjs} +0 -0
@@ -1,127 +0,0 @@
1
- import { ErrorFactory, HttpStatus } from '../error.mjs';
2
-
3
- function parseURI(uri, uris) {
4
- if (!uri) {
5
- throw ErrorFactory.create({
6
- message: "URI cannot be empty",
7
- httpStatus: HttpStatus.BAD_REQUEST,
8
- context: { uri }
9
- });
10
- }
11
- if (!uris) {
12
- throw ErrorFactory.create({
13
- message: "URIs configuration is not provided",
14
- httpStatus: HttpStatus.INTERNAL_SERVER_ERROR,
15
- context: { uri }
16
- });
17
- }
18
- const cleanUri = uri.replace(/^\/*(srn\/)?/, "").replace(/\/*$/, "");
19
- const [path, queryString] = cleanUri.split("?");
20
- const parts = path.split("/");
21
- const query = queryString ? Object.fromEntries(
22
- queryString.split("&").map((param) => param.split("="))
23
- ) : void 0;
24
- const method = query?.method ? query?.method.toLowerCase() : void 0;
25
- const namespaceName = parts[0];
26
- const serviceName = parts[1];
27
- const methodName = method || parts[2];
28
- const actionName = method ? parts[2] : parts[3];
29
- if (!namespaceName || !serviceName || !methodName || !actionName) {
30
- throw ErrorFactory.create({
31
- message: "Invalid URI format: Insufficient path segments",
32
- httpStatus: HttpStatus.BAD_REQUEST,
33
- context: {
34
- uri,
35
- cleanUri,
36
- partsLength: parts.length,
37
- method,
38
- namespaceName,
39
- serviceName,
40
- methodName,
41
- actionName
42
- }
43
- });
44
- }
45
- const baseUri = `${namespaceName}/${serviceName}/${methodName}/${actionName}`;
46
- const paramStartIndex = method ? 3 : 4;
47
- const parameters = parts.slice(paramStartIndex);
48
- const normalizedUri = method ? `${namespaceName}/${serviceName}/${method}/${actionName}${parameters.length ? `/${parameters.join("/")}` : ""}` : cleanUri;
49
- const template = uris[baseUri];
50
- if (template === void 0) {
51
- throw ErrorFactory.create({
52
- message: "No route found for URI",
53
- httpStatus: HttpStatus.NOT_FOUND,
54
- context: {
55
- uri,
56
- baseUri
57
- }
58
- });
59
- }
60
- if (template === "") {
61
- if (parameters.length > 0) {
62
- throw ErrorFactory.create({
63
- message: "No parameters expected for this route",
64
- httpStatus: HttpStatus.BAD_REQUEST,
65
- context: {
66
- uri,
67
- baseUri,
68
- extraParams: parameters
69
- }
70
- });
71
- }
72
- return {
73
- namespaceName,
74
- serviceName,
75
- methodName,
76
- actionName,
77
- raw: normalizedUri,
78
- parts: [namespaceName, serviceName, methodName, actionName],
79
- routerParams: {},
80
- query: method ? void 0 : query,
81
- uri: baseUri
82
- };
83
- }
84
- const routeTemplate = typeof template === "string" ? template : template.pattern;
85
- const validators = typeof template === "string" ? void 0 : template.validators;
86
- const routerParams = {};
87
- const templateParts = routeTemplate.split("/").filter(Boolean);
88
- const paramValues = parameters;
89
- let valueIndex = 0;
90
- templateParts.forEach((part) => {
91
- if (part.startsWith(":")) {
92
- const paramName = part.substring(1);
93
- const paramValue = paramValues[valueIndex];
94
- if (validators?.[paramName] && paramValue) {
95
- if (!validators[paramName](paramValue)) {
96
- throw ErrorFactory.create({
97
- message: "Invalid value for parameter",
98
- httpStatus: HttpStatus.UNPROCESSABLE_ENTITY,
99
- context: {
100
- uri,
101
- paramName,
102
- paramValue,
103
- validatorName: paramName
104
- }
105
- });
106
- }
107
- }
108
- routerParams[paramName] = paramValue || void 0;
109
- valueIndex++;
110
- } else if (part && part === paramValues[valueIndex]) {
111
- valueIndex++;
112
- }
113
- });
114
- return {
115
- namespaceName,
116
- serviceName,
117
- methodName,
118
- actionName,
119
- raw: normalizedUri,
120
- parts: [namespaceName, serviceName, methodName, actionName],
121
- routerParams,
122
- query: method ? void 0 : query,
123
- uri: baseUri
124
- };
125
- }
126
-
127
- export { parseURI };
@@ -1,5 +0,0 @@
1
- function getEvent(event) {
2
- return event.event || event || {};
3
- }
4
-
5
- export { getEvent };
@@ -1,12 +0,0 @@
1
- import { lstatSync } from 'node:fs';
2
- import { dirname, isAbsolute } from 'pathe';
3
-
4
- function getDirectory(p) {
5
- try {
6
- return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
7
- } catch {
8
- }
9
- return p;
10
- }
11
-
12
- export { getDirectory };
@@ -1,25 +0,0 @@
1
- function merge(items, maxLevel = 4, currentLevel = 3) {
2
- const arrayItems = Array.isArray(items) ? items : [items];
3
- return arrayItems.reduce((acc, item) => {
4
- Object.keys(item).forEach((key) => {
5
- if (typeof item[key] === "object" && item[key] !== null && currentLevel < maxLevel) {
6
- acc[key] = acc[key] || {};
7
- acc[key] = merge([acc[key], item[key]], maxLevel, currentLevel + 1);
8
- } else {
9
- acc[key] = item[key];
10
- }
11
- });
12
- return acc;
13
- }, {});
14
- }
15
- function mergeSchemas(typesOrArray) {
16
- return merge(typesOrArray);
17
- }
18
- function mergeServices(servicesOrArray) {
19
- return merge(servicesOrArray);
20
- }
21
- function mergeShared(sharedOrArray) {
22
- return merge(sharedOrArray, 1, 1);
23
- }
24
-
25
- export { mergeSchemas, mergeServices, mergeShared };
@@ -1,5 +0,0 @@
1
- function createSchema(silgiType) {
2
- return silgiType;
3
- }
4
-
5
- export { createSchema };
@@ -1,5 +0,0 @@
1
- function createService(variables) {
2
- return variables;
3
- }
4
-
5
- export { createService };
@@ -1,5 +0,0 @@
1
- function createShared(shared) {
2
- return shared;
3
- }
4
-
5
- export { createShared };
@@ -1,70 +0,0 @@
1
- import { Buffer } from 'node:buffer';
2
- import { klona } from 'klona';
3
- import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
4
- import memoryDriver from 'unstorage/drivers/memory';
5
- import { ErrorFactory, HttpStatus } from '../error.mjs';
6
- import { useSilgi } from '../unctx.mjs';
7
-
8
- async function createStorage(silgi) {
9
- const storage = createStorage$1();
10
- const mounts = klona({
11
- ...silgi.options.storage,
12
- ...silgi.options.devStorage
13
- });
14
- for (const [path, opts] of Object.entries(mounts)) {
15
- if (opts.driver) {
16
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
17
- storage.mount("/memory:cache", memoryDriver());
18
- storage.mount(path, driver(opts));
19
- } else {
20
- silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
21
- }
22
- }
23
- return storage;
24
- }
25
- function useSilgiStorage(base = "/memory:cache") {
26
- const silgi = useSilgi();
27
- return base ? prefixStorage(silgi.storage, base) : silgi.storage;
28
- }
29
- async function generateStorageKey(params) {
30
- const {
31
- operation,
32
- input,
33
- keyGenerator,
34
- requestId,
35
- storageOptions
36
- } = params;
37
- const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
38
- const parts = [
39
- cacheScopePrefix,
40
- // Always include scope prefix first
41
- operation.namespaceName,
42
- operation.serviceName,
43
- operation.methodName
44
- ].filter(Boolean);
45
- if (storageOptions?.scope === "request") {
46
- if (!requestId) {
47
- throw ErrorFactory.create({
48
- code: HttpStatus.BAD_REQUEST,
49
- message: "Request ID is required for request-scoped cache",
50
- context: {
51
- requestId,
52
- operation,
53
- input,
54
- storageOptions,
55
- keyGenerator
56
- }
57
- });
58
- }
59
- parts.push(requestId);
60
- }
61
- if (keyGenerator) {
62
- const customKey = await Promise.resolve(keyGenerator(input));
63
- parts.push(customKey);
64
- } else {
65
- parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
66
- }
67
- return Buffer.from(parts.join(":")).toString("base64");
68
- }
69
-
70
- export { createStorage, generateStorageKey, useSilgiStorage };
@@ -1,62 +0,0 @@
1
- import { execSync } from 'node:child_process';
2
- import { fileURLToPath } from 'node:url';
3
- import { resolve, dirname, join } from 'pathe';
4
- import { loadOptions } from 'silgi/core';
5
- import { relativeWithDot } from 'silgi/kit';
6
- import { autoImportTypes } from 'silgi/types';
7
-
8
- const module = {
9
- name: "silgi",
10
- setup: async (nitro) => {
11
- const silgiConfig = await loadOptions({});
12
- nitro.options.plugins = nitro.options.plugins || [];
13
- nitro.options.plugins.push(
14
- fileURLToPath(new URL("runtime/plugin", import.meta.url))
15
- );
16
- const tsConfigPath = resolve(
17
- nitro.options.buildDir,
18
- nitro.options.typescript.tsconfigPath
19
- );
20
- const tsconfigDir = dirname(tsConfigPath);
21
- nitro.options.typescript.strict = true;
22
- nitro.options.typescript.tsConfig ??= {};
23
- nitro.options.typescript.tsConfig.extends = "./silgi.tsconfig.json";
24
- nitro.options.typescript.tsConfig.include ??= [];
25
- nitro.options.typescript.tsConfig.exclude ??= [];
26
- if (silgiConfig.typescript.internalPaths || silgiConfig.stub) {
27
- nitro.options.alias ||= {};
28
- nitro.options.alias = {
29
- ...nitro.options.alias,
30
- ...silgiConfig.alias
31
- // 'silgi/runtime': fileURLToPath(`${new URL(pkgDir, import.meta.url)}dist/runtime/`),
32
- };
33
- }
34
- nitro.options.typescript.tsConfig.include.push(join(relativeWithDot(tsconfigDir, silgiConfig.build.dir), "**/*"));
35
- nitro.options.typescript.tsConfig.compilerOptions ??= {};
36
- nitro.options.typescript.tsConfig.compilerOptions.paths ??= {};
37
- nitro.hooks.hook("types:extend", async () => {
38
- const isStub = silgiConfig.stub ? "pnpm silgi prepare --stub" : "pnpm silgi prepare";
39
- execSync(isStub, { stdio: "inherit", cwd: nitro.options.rootDir, env: process.env });
40
- });
41
- nitro.options.exportConditions ??= [];
42
- nitro.options.exportConditions.push(...silgiConfig.conditions);
43
- if (nitro.options.imports) {
44
- nitro.options.imports.dirs ??= [];
45
- nitro.options.imports.dirs.push(
46
- join(silgiConfig.silgi.serverDir, "**/*")
47
- );
48
- nitro.options.imports.presets ??= [];
49
- nitro.options.imports.presets.push({
50
- from: "silgi",
51
- imports: ["silgi"]
52
- });
53
- nitro.options.imports.presets.push({
54
- from: "silgi/types",
55
- imports: autoImportTypes.map((type) => type),
56
- type: true
57
- });
58
- }
59
- }
60
- };
61
-
62
- export { module as default };
package/dist/kit/esm.mjs DELETED
@@ -1,10 +0,0 @@
1
- import { resolvePath } from 'mlly';
2
-
3
- async function tryResolveModule(id, url = import.meta.url) {
4
- try {
5
- return await resolvePath(id, { url });
6
- } catch {
7
- }
8
- }
9
-
10
- export { tryResolveModule };
package/dist/kit/fs.mjs DELETED
@@ -1,25 +0,0 @@
1
- import fsp from 'node:fs/promises';
2
- import { consola } from 'consola';
3
- import { dirname } from 'pathe';
4
- import { prettyPath } from './path.mjs';
5
-
6
- async function writeFile(file, contents, log = false) {
7
- await fsp.mkdir(dirname(file), { recursive: true });
8
- await fsp.writeFile(
9
- file,
10
- contents,
11
- typeof contents === "string" ? "utf8" : void 0
12
- );
13
- if (log) {
14
- consola.info("Generated", prettyPath(file));
15
- }
16
- }
17
- async function isDirectory(path) {
18
- try {
19
- return (await fsp.stat(path)).isDirectory();
20
- } catch {
21
- return false;
22
- }
23
- }
24
-
25
- export { isDirectory, writeFile };
@@ -1,25 +0,0 @@
1
- import { useSilgi } from 'silgi/core';
2
-
3
- function isNuxt() {
4
- const silgi = useSilgi();
5
- if (silgi.options.present === "nitro" || silgi.options.present === "h3" || silgi.options.present === "nuxt") {
6
- return true;
7
- }
8
- return false;
9
- }
10
- function isNitro() {
11
- const silgi = useSilgi();
12
- if (silgi.options.present === "nitro" || silgi.options.present === "h3") {
13
- return true;
14
- }
15
- return false;
16
- }
17
- function isH3() {
18
- const silgi = useSilgi();
19
- if (silgi.options.present === "h3") {
20
- return true;
21
- }
22
- return false;
23
- }
24
-
25
- export { isH3, isNitro, isNuxt };
@@ -1,8 +0,0 @@
1
- import { consola } from 'consola';
2
-
3
- const logger = consola;
4
- function useLogger(tag, options = {}) {
5
- return tag ? logger.create(options).withTag(tag) : logger;
6
- }
7
-
8
- export { logger, useLogger };
@@ -1,73 +0,0 @@
1
- import { defu } from 'defu';
2
- import { tryUseSilgiCLI, useSilgiCLI } from 'silgi/core';
3
- import { checkSilgiCompatibility } from '../cli/utils/compatibility.mjs';
4
-
5
- function defineSilgiModule(definition) {
6
- if (definition) {
7
- return _defineSilgiModule(definition);
8
- }
9
- return {
10
- with: (definition2) => _defineSilgiModule(definition2)
11
- };
12
- }
13
- function _defineSilgiModule(definition) {
14
- if (typeof definition === "function") {
15
- return _defineSilgiModule({ setup: definition });
16
- }
17
- const module = defu(definition, { meta: {} });
18
- module.meta.configKey ||= module.meta.name;
19
- async function getOptions(inlineOptions, silgi = useSilgiCLI()) {
20
- const nuxtConfigOptionsKey = module.meta.configKey || module.meta.name;
21
- const nuxtConfigOptions = nuxtConfigOptionsKey && nuxtConfigOptionsKey in silgi.options ? silgi.options[nuxtConfigOptionsKey] : {};
22
- const optionsDefaults = module.defaults instanceof Function ? await module.defaults(silgi) : module.defaults ?? {};
23
- const options = defu(inlineOptions, nuxtConfigOptions, optionsDefaults);
24
- return Promise.resolve(options);
25
- }
26
- async function silgiNormalizedModule(inlineOptions, silgi = tryUseSilgiCLI()) {
27
- if (!silgi) {
28
- throw new TypeError("Cannot use module outside of Silgi context");
29
- }
30
- const uniqueKey = module.meta.configKey || module.meta.name;
31
- if (uniqueKey) {
32
- silgi._requiredModules ||= {};
33
- if (silgi._requiredModules[uniqueKey]) {
34
- return false;
35
- }
36
- silgi._requiredModules[uniqueKey] = true;
37
- }
38
- if (module.meta.compatibility) {
39
- const issues = await checkSilgiCompatibility(module.meta.compatibility, silgi);
40
- if (issues.length) {
41
- silgi.logger.warn(`Module \`${module.meta.name}\` is disabled due to incompatibility issues:
42
- ${issues.toString()}`);
43
- return;
44
- }
45
- }
46
- const _options = await getOptions(inlineOptions, silgi);
47
- if (module.hooks) {
48
- silgi.hooks.addHooks(module.hooks);
49
- }
50
- const start = performance.now();
51
- const res = await module.setup?.call(null, _options, silgi) ?? {};
52
- const perf = performance.now() - start;
53
- const setupTime = Math.round(perf * 100) / 100;
54
- if (setupTime > 5e3 && uniqueKey !== "@silgi/telemetry") {
55
- silgi.logger.warn(`Slow module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
56
- } else if (silgi.options.debug) {
57
- silgi.logger.info(`Module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
58
- }
59
- if (res === false) {
60
- return false;
61
- }
62
- return defu(res, {
63
- timings: {
64
- setup: setupTime
65
- }
66
- });
67
- }
68
- silgiNormalizedModule.getMeta = () => Promise.resolve(module.meta);
69
- silgiNormalizedModule.getOptions = getOptions;
70
- return silgiNormalizedModule;
71
- }
72
-
73
- export { _defineSilgiModule, defineSilgiModule };
package/dist/kit/path.mjs DELETED
@@ -1,34 +0,0 @@
1
- import consola from 'consola';
2
- import { colors } from 'consola/utils';
3
- import { getProperty } from 'dot-prop';
4
- import { relative, resolve } from 'pathe';
5
-
6
- function prettyPath(p, highlight = true) {
7
- p = relative(process.cwd(), p);
8
- return highlight ? colors.cyan(p) : p;
9
- }
10
- function resolveSilgiPath(path, silgiCLIOptions, base) {
11
- if (typeof path !== "string") {
12
- throw new TypeError(`Invalid path: ${path}`);
13
- }
14
- path = _compilePathTemplate(path)(silgiCLIOptions);
15
- for (const base2 in silgiCLIOptions.alias) {
16
- if (path.startsWith(base2)) {
17
- path = silgiCLIOptions.alias[base2] + path.slice(base2.length);
18
- }
19
- }
20
- return resolve(base || silgiCLIOptions.srcDir, path);
21
- }
22
- function _compilePathTemplate(contents) {
23
- return (params) => contents.replace(/\{\{ ?([\w.]+) ?\}\}/g, (_, match) => {
24
- const val = getProperty(params, match);
25
- if (!val) {
26
- consola.warn(
27
- `cannot resolve template param '${match}' in ${contents.slice(0, 20)}`
28
- );
29
- }
30
- return val || `${match}`;
31
- });
32
- }
33
-
34
- export { prettyPath, resolveSilgiPath };
@@ -1,6 +0,0 @@
1
- function defineSilgiPreset(preset, meta) {
2
- if (meta?.url && typeof preset !== "function") ;
3
- return { ...preset, _meta: meta };
4
- }
5
-
6
- export { defineSilgiPreset };
@@ -1,78 +0,0 @@
1
- import { existsSync, promises } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { resolvePath as resolvePath$1 } from 'mlly';
4
- import { dirname, resolve, normalize, isAbsolute, join } from 'pathe';
5
- import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
6
-
7
- async function resolvePath(path, opts = {}) {
8
- const _path = path;
9
- path = normalize(path);
10
- if (isAbsolute(path)) {
11
- if (existsSync(path) && !await isDirectory(path)) {
12
- return path;
13
- }
14
- }
15
- const cwd = opts.cwd || process.cwd();
16
- const extensions = opts.extensions || [".ts", ".mjs", ".cjs", ".json"];
17
- const modulesDir = opts.modulesDir || [];
18
- path = resolveAlias(path);
19
- if (!isAbsolute(path)) {
20
- path = resolve(cwd, path);
21
- }
22
- let _isDir = false;
23
- if (existsSync(path)) {
24
- _isDir = await isDirectory(path);
25
- if (!_isDir) {
26
- return path;
27
- }
28
- }
29
- for (const ext of extensions) {
30
- const pathWithExt = path + ext;
31
- if (existsSync(pathWithExt)) {
32
- return pathWithExt;
33
- }
34
- const pathWithIndex = join(path, `index${ext}`);
35
- if (_isDir && existsSync(pathWithIndex)) {
36
- return pathWithIndex;
37
- }
38
- }
39
- const resolveModulePath = await resolvePath$1(_path, { url: [cwd, ...modulesDir] }).catch(() => null);
40
- if (resolveModulePath) {
41
- return resolveModulePath;
42
- }
43
- return opts.fallbackToOriginal ? _path : path;
44
- }
45
- async function isDirectory(path) {
46
- return (await promises.lstat(path)).isDirectory();
47
- }
48
- function resolveAlias(path, alias) {
49
- return resolveAlias$1(path, alias || {});
50
- }
51
- function createResolver(base) {
52
- if (!base) {
53
- throw new Error("`base` argument is missing for createResolver(base)!");
54
- }
55
- base = base.toString();
56
- if (base.startsWith("file://")) {
57
- base = dirname(fileURLToPath(base));
58
- }
59
- return {
60
- resolve: (...path) => resolve(base, ...path),
61
- resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
62
- };
63
- }
64
- async function resolveSilgiModule(base, paths) {
65
- const resolved = [];
66
- const resolver = createResolver(base);
67
- for (const path of paths) {
68
- if (path.startsWith(base)) {
69
- resolved.push(path.split("/index.ts")[0]);
70
- } else {
71
- const resolvedPath = await resolver.resolvePath(path);
72
- resolved.push(resolvedPath.slice(0, resolvedPath.lastIndexOf(path) + path.length));
73
- }
74
- }
75
- return resolved;
76
- }
77
-
78
- export { createResolver, resolveAlias, resolvePath, resolveSilgiModule };
@@ -1,47 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { hash } from 'ohash';
3
- import { parse, basename, resolve } from 'pathe';
4
- import { useSilgiCLI } from 'silgi/core';
5
- import { filterInPlace } from './utils.mjs';
6
-
7
- function addTemplate(_template) {
8
- const silgi = useSilgiCLI();
9
- const template = normalizeTemplate(_template);
10
- filterInPlace(silgi.options.build.templates, (p) => normalizeTemplate(p).dst !== template.dst);
11
- silgi.options.build.templates.push(template);
12
- return template;
13
- }
14
- function normalizeTemplate(template, buildDir) {
15
- if (!template) {
16
- throw new Error(`Invalid template: ${JSON.stringify(template)}`);
17
- }
18
- if (typeof template === "string") {
19
- template = { src: template };
20
- } else {
21
- template = { ...template };
22
- }
23
- if (template.src) {
24
- if (!existsSync(template.src)) {
25
- throw new Error(`Template not found: ${template.src}`);
26
- }
27
- if (!template.filename) {
28
- const srcPath = parse(template.src);
29
- template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src)}${srcPath.ext}`;
30
- }
31
- }
32
- if (!template.src && !template.getContents) {
33
- throw new Error(`Invalid template. Either \`getContents\` or \`src\` should be provided: ${JSON.stringify(template)}`);
34
- }
35
- if (!template.filename) {
36
- throw new Error(`Invalid template. \`filename\` must be provided: ${JSON.stringify(template)}`);
37
- }
38
- if (template.filename.endsWith(".d.ts")) {
39
- template.write = true;
40
- }
41
- if (!template.dst) {
42
- template.dst = resolve(buildDir ?? useSilgiCLI().options.silgi.serverDir, template.filename);
43
- }
44
- return template;
45
- }
46
-
47
- export { addTemplate, normalizeTemplate };
@@ -1,20 +0,0 @@
1
- import { relative } from 'pathe';
2
-
3
- const RELATIVE_RE = /^([^.])/;
4
- function relativeWithDot(from, to) {
5
- return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
6
- }
7
- function toArray(value) {
8
- return Array.isArray(value) ? value : [value];
9
- }
10
- function filterInPlace(array, predicate) {
11
- for (let i = array.length; i--; i >= 0) {
12
- if (!predicate(array[i], i, array)) {
13
- array.splice(i, 1);
14
- }
15
- }
16
- return array;
17
- }
18
- const MODE_RE = /\.(server|client)(\.\w+)*$/;
19
-
20
- export { MODE_RE, filterInPlace, relativeWithDot, toArray };
@@ -1,5 +0,0 @@
1
- const version = "0.7.1";
2
- const packageJson = {
3
- version: version};
4
-
5
- export { packageJson as default, version };