@duraxis/cli 0.3.0 → 0.5.1
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/CHANGELOG.md +29 -0
- package/README.md +20 -71
- package/dist/admin.command-Dt5MnwJw.js +299 -0
- package/dist/admin.command-Dt5MnwJw.js.map +1 -0
- package/dist/cli.d.ts +7 -0
- package/dist/commands/admin.command.d.ts +3 -0
- package/dist/commands/doctor.command.d.ts +9 -0
- package/dist/commands/init.command.d.ts +3 -0
- package/dist/commands/migration.command.d.ts +3 -0
- package/dist/commands/minimal-admin.d.ts +4 -0
- package/dist/config-BKscNXeW.js +204 -0
- package/dist/config-BKscNXeW.js.map +1 -0
- package/dist/config.d.ts +10 -8
- package/dist/dependencies/configured-registry.d.ts +3 -0
- package/dist/dependencies/dependency-resolver.d.ts +2 -0
- package/dist/dependencies/installed-package.d.ts +1 -0
- package/dist/dependencies/package-manager.d.ts +10 -0
- package/dist/dependencies/registry-client.d.ts +21 -0
- package/dist/dependencies/version-compatibility.d.ts +9 -0
- package/dist/file-plan-D-Sj3yv0.js +130 -0
- package/dist/file-plan-D-Sj3yv0.js.map +1 -0
- package/dist/filesystem/file-plan.d.ts +32 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +366 -551
- package/dist/index.js.map +1 -1
- package/dist/init/initialization-options.d.ts +32 -0
- package/dist/init/initialization-planner.d.ts +10 -0
- package/dist/init/nest-integration.d.ts +2 -0
- package/dist/init/project-detector.d.ts +27 -0
- package/dist/init/static-config.d.ts +16 -0
- package/dist/init.command-DrO29773.js +167 -0
- package/dist/init.command-DrO29773.js.map +1 -0
- package/dist/initialization-planner-B41PNGWc.js +315 -0
- package/dist/initialization-planner-B41PNGWc.js.map +1 -0
- package/dist/migration.command-dhRbN4UI.js +361 -0
- package/dist/migration.command-dhRbN4UI.js.map +1 -0
- package/dist/minimal-admin-B4ur_cON.js +232 -0
- package/dist/minimal-admin-B4ur_cON.js.map +1 -0
- package/dist/nest-integration-KCc7ZaG6.js +93 -0
- package/dist/nest-integration-KCc7ZaG6.js.map +1 -0
- package/dist/package-manager-Ca5ArUf-.js +269 -0
- package/dist/package-manager-Ca5ArUf-.js.map +1 -0
- package/dist/project-detector-BQWeQZ8Q.js +174 -0
- package/dist/project-detector-BQWeQZ8Q.js.map +1 -0
- package/dist/registry/argument-parser.d.ts +65 -0
- package/dist/registry/command-registry.d.ts +198 -0
- package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
- package/dist/static-config-g_7qN12_.js +109 -0
- package/dist/static-config-g_7qN12_.js.map +1 -0
- package/dist/templates/project.d.ts +10 -0
- package/dist/terminal/prompts.d.ts +2 -0
- package/package.json +13 -8
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
+
import { access, readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
4
|
+
import { readFileSync, statSync } from "node:fs";
|
|
5
|
+
import { registerHooks } from "node:module";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import ts from "typescript";
|
|
8
|
+
import { createDatabase, normalizeDuraxisConnection, selectDuraxisConnection } from "@duraxis/core";
|
|
9
|
+
import { discoverEntities } from "@duraxis/orm";
|
|
10
|
+
// src/runtime.mjs
|
|
11
|
+
var MINIMUM_NODE_VERSION = "24.15.0";
|
|
12
|
+
/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */
|
|
13
|
+
function assertSupportedRuntime(version = process.versions.node) {
|
|
14
|
+
const actual = version.split(".").map(Number);
|
|
15
|
+
const minimum = MINIMUM_NODE_VERSION.split(".").map(Number);
|
|
16
|
+
const difference = actual.findIndex((part, index) => part !== minimum[index]);
|
|
17
|
+
if (!(/^\d+\.\d+\.\d+$/.test(version) && (difference === -1 || actual[difference] > minimum[difference]))) throw new Error(`Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\nCurrent version: ${version}\nPlease upgrade your Node.js installation.`);
|
|
18
|
+
}
|
|
19
|
+
// src/typescript-loader.ts
|
|
20
|
+
var sourceExtensions = {
|
|
21
|
+
".js": ".ts",
|
|
22
|
+
".mjs": ".mts",
|
|
23
|
+
".cjs": ".cts"
|
|
24
|
+
};
|
|
25
|
+
var hooks;
|
|
26
|
+
var modules = /* @__PURE__ */ new Set();
|
|
27
|
+
function localFile(value) {
|
|
28
|
+
if (!value.startsWith("file:")) return;
|
|
29
|
+
const url = new URL(value);
|
|
30
|
+
if (fileURLToPath(url).split(/[\\/]/).includes("node_modules")) return;
|
|
31
|
+
return url;
|
|
32
|
+
}
|
|
33
|
+
function exists(url) {
|
|
34
|
+
try {
|
|
35
|
+
return statSync(url).isFile();
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (["ENOENT", "ENOTDIR"].includes(error.code ?? "")) return false;
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function remember(url) {
|
|
42
|
+
if (localFile(url)) modules.add(url);
|
|
43
|
+
}
|
|
44
|
+
/** One hook pair per library instance, limited to explicitly loaded local module graphs. */
|
|
45
|
+
function initializeTypeScriptLoader(entry) {
|
|
46
|
+
assertSupportedRuntime();
|
|
47
|
+
remember(entry.href);
|
|
48
|
+
if (hooks) return;
|
|
49
|
+
hooks = registerHooks({
|
|
50
|
+
resolve(specifier, context, nextResolve) {
|
|
51
|
+
const managed = /^(?:\.{1,2}[\\/]|\/|file:)/.test(specifier) && (modules.has(specifier) || context.parentURL !== void 0 && modules.has(context.parentURL));
|
|
52
|
+
try {
|
|
53
|
+
const resolved = nextResolve(specifier, context);
|
|
54
|
+
if (managed) remember(resolved.url);
|
|
55
|
+
return resolved;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (!managed || !["ERR_MODULE_NOT_FOUND", "MODULE_NOT_FOUND"].includes(error.code ?? "")) throw error;
|
|
58
|
+
const requested = localFile(new URL(specifier, context.parentURL).href);
|
|
59
|
+
if (!requested || exists(requested)) throw error;
|
|
60
|
+
const path = fileURLToPath(requested);
|
|
61
|
+
const extension = extname(path);
|
|
62
|
+
const mapped = sourceExtensions[extension];
|
|
63
|
+
if (!mapped) throw error;
|
|
64
|
+
const candidate = pathToFileURL(path.slice(0, -extension.length) + mapped);
|
|
65
|
+
candidate.search = requested.search;
|
|
66
|
+
candidate.hash = requested.hash;
|
|
67
|
+
if (!exists(candidate)) throw error;
|
|
68
|
+
const resolved = nextResolve(context.conditions.includes("require") ? fileURLToPath(candidate) : candidate.href, context);
|
|
69
|
+
remember(resolved.url);
|
|
70
|
+
return resolved;
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
load(url, context, nextLoad) {
|
|
74
|
+
if (!modules.has(url)) return nextLoad(url, context);
|
|
75
|
+
const file = localFile(url);
|
|
76
|
+
if (!file) return nextLoad(url, context);
|
|
77
|
+
const path = fileURLToPath(file);
|
|
78
|
+
if (!/\.(?:ts|mts|cts)$/.test(path) || /\.d\.(?:ts|mts|cts)$/.test(path)) return nextLoad(url, context);
|
|
79
|
+
let commonjs = path.endsWith(".cts");
|
|
80
|
+
if (path.endsWith(".ts")) {
|
|
81
|
+
let directory = dirname(path);
|
|
82
|
+
while (true) {
|
|
83
|
+
try {
|
|
84
|
+
commonjs = JSON.parse(readFileSync(join(directory, "package.json"), "utf8")).type !== "module";
|
|
85
|
+
break;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error.code !== "ENOENT") throw error;
|
|
88
|
+
}
|
|
89
|
+
if (dirname(directory) === directory) {
|
|
90
|
+
commonjs = true;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
directory = dirname(directory);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const result = ts.transpileModule(readFileSync(file, "utf8"), {
|
|
97
|
+
fileName: path,
|
|
98
|
+
reportDiagnostics: true,
|
|
99
|
+
compilerOptions: {
|
|
100
|
+
target: ts.ScriptTarget.ES2022,
|
|
101
|
+
module: commonjs ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext,
|
|
102
|
+
experimentalDecorators: true,
|
|
103
|
+
emitDecoratorMetadata: true,
|
|
104
|
+
useDefineForClassFields: false,
|
|
105
|
+
sourceMap: false
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
const errors = (result.diagnostics ?? []).filter((item) => item.category == ts.DiagnosticCategory.Error);
|
|
109
|
+
if (errors.length) throw new Error(ts.formatDiagnosticsWithColorAndContext(errors, {
|
|
110
|
+
getCurrentDirectory: () => process.cwd(),
|
|
111
|
+
getCanonicalFileName: (file) => file,
|
|
112
|
+
getNewLine: () => "\n"
|
|
113
|
+
}));
|
|
114
|
+
return {
|
|
115
|
+
format: commonjs ? "commonjs" : "module",
|
|
116
|
+
source: (commonjs ? "\"use strict\";\nrequire = require(\"node:module\").createRequire(__filename);\n" : "") + result.outputText,
|
|
117
|
+
shortCircuit: true
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */
|
|
123
|
+
function disposeTypeScriptLoader() {
|
|
124
|
+
hooks?.deregister();
|
|
125
|
+
hooks = void 0;
|
|
126
|
+
}
|
|
127
|
+
// src/config.ts
|
|
128
|
+
var config_exports = /* @__PURE__ */ __exportAll({ loadConfig: () => loadConfig });
|
|
129
|
+
async function importFile(path) {
|
|
130
|
+
const url = path instanceof URL ? path : pathToFileURL(path);
|
|
131
|
+
initializeTypeScriptLoader(url);
|
|
132
|
+
return import(url.href);
|
|
133
|
+
}
|
|
134
|
+
async function loadConfig(cwd, explicit, database) {
|
|
135
|
+
let path;
|
|
136
|
+
if (explicit) path = resolve(cwd, explicit);
|
|
137
|
+
else {
|
|
138
|
+
let directory = resolve(cwd);
|
|
139
|
+
while (true) {
|
|
140
|
+
for (const name of [
|
|
141
|
+
"duraxis.config.ts",
|
|
142
|
+
"duraxis.config.mts",
|
|
143
|
+
"duraxis.config.js",
|
|
144
|
+
"duraxis.config.mjs",
|
|
145
|
+
"duraxis.config.cts",
|
|
146
|
+
"duraxis.config.cjs"
|
|
147
|
+
]) {
|
|
148
|
+
const candidate = resolve(directory, name);
|
|
149
|
+
try {
|
|
150
|
+
await access(candidate);
|
|
151
|
+
path = candidate;
|
|
152
|
+
break;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error.code != "ENOENT") throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (!path) {
|
|
158
|
+
const project = await (await import("./project-detector-BQWeQZ8Q.js")).detectProject(directory, true);
|
|
159
|
+
if (project.configFiles.length > 1) throw new Error("Multiple Duraxis configurations found; select one with --config");
|
|
160
|
+
if (project.configFiles.length === 1) path = resolve(directory, project.configFiles[0]);
|
|
161
|
+
}
|
|
162
|
+
if (path || dirname(directory) == directory) break;
|
|
163
|
+
directory = dirname(directory);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (!path) throw new Error("No duraxis.config.ts or JavaScript configuration found");
|
|
167
|
+
let base = (await importFile(path)).default;
|
|
168
|
+
if (base && "default" in base) base = base.default;
|
|
169
|
+
if (!base || typeof base !== "object" || !("driver" in base) && !("connections" in base)) throw new Error("Invalid Duraxis configuration; configure a driver or named connections");
|
|
170
|
+
const selected = selectDuraxisConnection(base, database);
|
|
171
|
+
const options = normalizeDuraxisConnection({
|
|
172
|
+
...selected,
|
|
173
|
+
location: selected.location ?? path
|
|
174
|
+
});
|
|
175
|
+
const context = options.context;
|
|
176
|
+
const moduleFormat = /\.[cm][jt]s$/.test(path) ? /\.c[jt]s$/.test(path) ? "cjs" : "esm" : (await (await import("./project-detector-BQWeQZ8Q.js")).detectProject(context.root, true)).moduleFormat;
|
|
177
|
+
let discover = discoverEntities;
|
|
178
|
+
if (moduleFormat === "cjs" && (options.entities !== void 0 || options.autoLoadEntities)) discover = (await import("node:module")).createRequire(path)("@duraxis/orm").discoverEntities;
|
|
179
|
+
return {
|
|
180
|
+
config: {
|
|
181
|
+
settings: {
|
|
182
|
+
...selected,
|
|
183
|
+
database: options.database,
|
|
184
|
+
schema: options.schema,
|
|
185
|
+
migrations: options.migrations
|
|
186
|
+
},
|
|
187
|
+
createDatabase: () => createDatabase(options),
|
|
188
|
+
...options.entities !== void 0 || options.autoLoadEntities ? { entities: () => discover(options, (url) => importFile(url)) } : {},
|
|
189
|
+
...options.migrations ? { migrations: options.migrations } : {},
|
|
190
|
+
moduleFormat
|
|
191
|
+
},
|
|
192
|
+
root: context.root,
|
|
193
|
+
path
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
async function readJSON(path) {
|
|
197
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
198
|
+
}
|
|
199
|
+
function requireMigrationConfig(config) {
|
|
200
|
+
if (!config.migrations) throw new Error("Migrations are disabled for this connection. Enable them before running migration commands.");
|
|
201
|
+
}
|
|
202
|
+
export { requireMigrationConfig as a, readJSON as i, importFile as n, disposeTypeScriptLoader as o, loadConfig as r, config_exports as t };
|
|
203
|
+
|
|
204
|
+
//# sourceMappingURL=config-BKscNXeW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-BKscNXeW.js","names":[],"sources":["../src/runtime.mjs","../src/typescript-loader.ts","../src/config.ts"],"sourcesContent":["export const MINIMUM_NODE_VERSION = \"24.15.0\";\n\n/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */\nexport function assertSupportedRuntime(version = process.versions.node) {\n const actual = version.split(\".\").map(Number);\n const minimum = MINIMUM_NODE_VERSION.split(\".\").map(Number);\n const difference = actual.findIndex((part, index) => part !== minimum[index]);\n const supported =\n /^\\d+\\.\\d+\\.\\d+$/.test(version) &&\n (difference === -1 || actual[difference] > minimum[difference]);\n if (!supported)\n throw new Error(\n `Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\\nCurrent version: ${version}\\nPlease upgrade your Node.js installation.`,\n );\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport { registerHooks, type ModuleHooks } from \"node:module\";\nimport { extname, dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport ts from \"typescript\";\nimport { assertSupportedRuntime } from \"./runtime.mjs\";\n\nconst sourceExtensions: Readonly<Record<string, string>> = {\n \".js\": \".ts\",\n \".mjs\": \".mts\",\n \".cjs\": \".cts\",\n};\nlet hooks: ModuleHooks | undefined;\nconst modules = new Set<string>();\n\nfunction localFile(value: string): URL | undefined {\n if (!value.startsWith(\"file:\")) return;\n const url = new URL(value);\n const path = fileURLToPath(url);\n if (path.split(/[\\\\/]/).includes(\"node_modules\")) return;\n return url;\n}\nfunction exists(url: URL): boolean {\n try {\n return statSync(url).isFile();\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return false;\n throw error;\n }\n}\nfunction remember(url: string): void {\n if (localFile(url)) modules.add(url);\n}\n\n/** One hook pair per library instance, limited to explicitly loaded local module graphs. */\nexport function initializeTypeScriptLoader(entry: URL): void {\n assertSupportedRuntime();\n remember(entry.href);\n if (hooks) return;\n hooks = registerHooks({\n resolve(specifier, context, nextResolve) {\n const relative = /^(?:\\.{1,2}[\\\\/]|\\/|file:)/.test(specifier);\n const managed =\n relative &&\n (modules.has(specifier) ||\n (context.parentURL !== undefined && modules.has(context.parentURL)));\n try {\n const resolved = nextResolve(specifier, context);\n if (managed) remember(resolved.url);\n return resolved;\n } catch (error) {\n if (\n !managed ||\n ![\"ERR_MODULE_NOT_FOUND\", \"MODULE_NOT_FOUND\"].includes(\n (error as NodeJS.ErrnoException).code ?? \"\",\n )\n )\n throw error;\n const requested = localFile(new URL(specifier, context.parentURL).href);\n if (!requested || exists(requested)) throw error;\n const path = fileURLToPath(requested);\n const extension = extname(path);\n const mapped = sourceExtensions[extension];\n if (!mapped) throw error;\n const candidate = pathToFileURL(path.slice(0, -extension.length) + mapped);\n candidate.search = requested.search;\n candidate.hash = requested.hash;\n if (!exists(candidate)) throw error;\n const resolved = nextResolve(\n context.conditions.includes(\"require\") ? fileURLToPath(candidate) : candidate.href,\n context,\n );\n remember(resolved.url);\n return resolved;\n }\n },\n load(url, context, nextLoad) {\n if (!modules.has(url)) return nextLoad(url, context);\n const file = localFile(url);\n if (!file) return nextLoad(url, context);\n const path = fileURLToPath(file);\n if (!/\\.(?:ts|mts|cts)$/.test(path) || /\\.d\\.(?:ts|mts|cts)$/.test(path))\n return nextLoad(url, context);\n let commonjs = path.endsWith(\".cts\");\n if (path.endsWith(\".ts\")) {\n let directory = dirname(path);\n while (true) {\n try {\n commonjs =\n JSON.parse(readFileSync(join(directory, \"package.json\"), \"utf8\")).type !== \"module\";\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n if (dirname(directory) === directory) {\n commonjs = true;\n break;\n }\n directory = dirname(directory);\n }\n }\n const result = ts.transpileModule(readFileSync(file, \"utf8\"), {\n fileName: path,\n reportDiagnostics: true,\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: commonjs ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext,\n\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n sourceMap: false,\n },\n });\n const errors = (result.diagnostics ?? []).filter(\n (item) => item.category == ts.DiagnosticCategory.Error,\n );\n if (errors.length)\n throw new Error(\n ts.formatDiagnosticsWithColorAndContext(errors, {\n getCurrentDirectory: () => process.cwd(),\n getCanonicalFileName: (file) => file,\n getNewLine: () => \"\\n\",\n }),\n );\n // Imported CommonJS source otherwise receives the ESM translator's synthetic\n // require, which bypasses customization hooks. Use Node's hook-aware require.\n return {\n format: commonjs ? \"commonjs\" : \"module\",\n source:\n (commonjs\n ? '\"use strict\";\\nrequire = require(\"node:module\").createRequire(__filename);\\n'\n : \"\") + result.outputText,\n shortCircuit: true,\n };\n },\n });\n}\n\n/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */\nexport function disposeTypeScriptLoader(): void {\n hooks?.deregister();\n hooks = undefined;\n // Retain graph identity alongside Node's module cache so cached callbacks can\n // resolve further imports after a later initialization.\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { initializeTypeScriptLoader } from \"./typescript-loader.js\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n createDatabase,\n normalizeDuraxisConnection,\n selectDuraxisConnection,\n type DuraxisConfiguration,\n type DuraxisDatabase,\n} from \"@duraxis/core\";\nimport { discoverEntities } from \"@duraxis/orm\";\nimport type { EntityClass } from \"@duraxis/orm\";\n\nexport interface DuraxisConnectionConfig {\n readonly settings?: unknown;\n readonly moduleFormat?: \"esm\" | \"cjs\";\n readonly entities?:\n readonly EntityClass[] | (() => readonly EntityClass[] | Promise<readonly EntityClass[]>);\n readonly migrations?: {\n readonly directory: string;\n readonly snapshots: string;\n readonly format?: \"ts\" | \"js\" | \"mts\" | \"mjs\";\n };\n readonly createDatabase: () => DuraxisDatabase | Promise<DuraxisDatabase>;\n}\n\nexport type DuraxisConfig = DuraxisConfiguration;\n\nexport async function importFile(path: string | URL): Promise<unknown> {\n const url = path instanceof URL ? path : pathToFileURL(path);\n initializeTypeScriptLoader(url);\n return import(url.href);\n}\n\nexport async function loadConfig(\n cwd: string,\n explicit?: string,\n database?: string,\n): Promise<{ config: DuraxisConnectionConfig; root: string; path: string }> {\n let path: string | undefined;\n\n if (explicit) path = resolve(cwd, explicit);\n else {\n let directory = resolve(cwd);\n\n while (true) {\n for (const name of [\n \"duraxis.config.ts\",\n \"duraxis.config.mts\",\n \"duraxis.config.js\",\n \"duraxis.config.mjs\",\n \"duraxis.config.cts\",\n \"duraxis.config.cjs\",\n ]) {\n const candidate = resolve(directory, name);\n\n try {\n await access(candidate);\n\n path = candidate;\n\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n }\n\n if (!path) {\n const project = await (\n await import(\"./init/project-detector.js\")\n ).detectProject(directory, true);\n if (project.configFiles.length > 1)\n throw new Error(\"Multiple Duraxis configurations found; select one with --config\");\n if (project.configFiles.length === 1) path = resolve(directory, project.configFiles[0]!);\n }\n if (path || dirname(directory) == directory) break;\n\n directory = dirname(directory);\n }\n }\n\n if (!path) throw new Error(\"No duraxis.config.ts or JavaScript configuration found\");\n\n const module = (await importFile(path)) as { default?: DuraxisConfig };\n\n let base = module.default;\n // TypeScript CommonJS default exports may be wrapped by Node's ESM namespace.\n if (base && \"default\" in base) base = (base as unknown as { default: DuraxisConfig }).default;\n if (!base || typeof base !== \"object\" || (!(\"driver\" in base) && !(\"connections\" in base)))\n throw new Error(\"Invalid Duraxis configuration; configure a driver or named connections\");\n const selected = selectDuraxisConnection(base as unknown as DuraxisConfiguration, database);\n const options = normalizeDuraxisConnection({\n ...selected,\n location: selected.location ?? path,\n });\n const context = options.context;\n const moduleFormat = /\\.[cm][jt]s$/.test(path)\n ? /\\.c[jt]s$/.test(path)\n ? \"cjs\"\n : \"esm\"\n : (await (await import(\"./init/project-detector.js\")).detectProject(context.root, true))\n .moduleFormat;\n let discover = discoverEntities;\n if (moduleFormat === \"cjs\" && (options.entities !== undefined || options.autoLoadEntities)) {\n const require = (await import(\"node:module\")).createRequire(path);\n discover = (require(\"@duraxis/orm\") as typeof import(\"@duraxis/orm\")).discoverEntities;\n }\n const config: DuraxisConnectionConfig = {\n settings: {\n ...selected,\n database: options.database,\n schema: options.schema,\n migrations: options.migrations,\n },\n createDatabase: () => createDatabase(options),\n ...(options.entities !== undefined || options.autoLoadEntities\n ? { entities: () => discover(options, (url) => importFile(url)) }\n : {}),\n ...(options.migrations ? { migrations: options.migrations } : {}),\n moduleFormat,\n };\n return { config, root: context.root, path };\n}\n\nexport async function readJSON<T>(path: string): Promise<T> {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n}\n\nexport function requireMigrationConfig(\n config: DuraxisConnectionConfig,\n): asserts config is DuraxisConnectionConfig & {\n migrations: NonNullable<DuraxisConnectionConfig[\"migrations\"]>;\n} {\n if (!config.migrations)\n throw new Error(\n \"Migrations are disabled for this connection. Enable them before running migration commands.\",\n );\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAa,uBAAuB;;AAGpC,SAAgB,uBAAuB,UAAU,QAAQ,SAAS,MAAM;CACtE,MAAM,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC5C,MAAM,UAAU,qBAAqB,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC1D,MAAM,aAAa,OAAO,WAAW,MAAM,UAAU,SAAS,QAAQ,MAAM;CAI5E,IAAI,EAFF,kBAAkB,KAAK,OAAO,MAC7B,eAAe,MAAM,OAAO,cAAc,QAAQ,eAEnD,MAAM,IAAI,MACR,4BAA4B,qBAAqB,+BAA+B,QAAQ,4CAC1F;AACJ;;ACPA,IAAM,mBAAqD;CACzD,OAAO;CACP,QAAQ;CACR,QAAQ;AACV;AACA,IAAI;AACJ,IAAM,0BAAU,IAAI,IAAY;AAEhC,SAAS,UAAU,OAAgC;CACjD,IAAI,CAAC,MAAM,WAAW,OAAO,GAAG;CAChC,MAAM,MAAM,IAAI,IAAI,KAAK;CAEzB,IADa,cAAc,GACvB,CAAA,CAAK,MAAM,OAAO,CAAC,CAAC,SAAS,cAAc,GAAG;CAClD,OAAO;AACT;AACA,SAAS,OAAO,KAAmB;CACjC,IAAI;EACF,OAAO,SAAS,GAAG,CAAC,CAAC,OAAO;CAC9B,SAAS,OAAO;EACd,IAAI,CAAC,UAAU,SAAS,CAAC,CAAC,SAAU,MAAgC,QAAQ,EAAE,GAAG,OAAO;EACxF,MAAM;CACR;AACF;AACA,SAAS,SAAS,KAAmB;CACnC,IAAI,UAAU,GAAG,GAAG,QAAQ,IAAI,GAAG;AACrC;;AAGA,SAAgB,2BAA2B,OAAkB;CAC3D,uBAAuB;CACvB,SAAS,MAAM,IAAI;CACnB,IAAI,OAAO;CACX,QAAQ,cAAc;EACpB,QAAQ,WAAW,SAA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cAAc,IAChD,CAAA,CAAQ,cAAc,CAAC,CAAmC;CAgBxE,OAAO;EAAE,QAAA;GAbP,UAAU;IACR,GAAG;IACH,UAAU,QAAQ;IAClB,QAAQ,QAAQ;IAChB,YAAY,QAAQ;GACtB;GACA,sBAAsB,eAAe,OAAO;GAC5C,GAAI,QAAQ,aAAa,KAAA,KAAa,QAAQ,mBAC1C,EAAE,gBAAgB,SAAS,UAAU,QAAQ,WAAW,GAAG,CAAC,EAAE,IAC9D,CAAC;GACL,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D;EAEO;EAAQ,MAAM,QAAQ;EAAM;CAAK;AAC5C;AAEA,eAAsB,SAAY,MAA0B;CAC1D,OAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;AAChD;AAEA,SAAgB,uBACd,QAGA;CACA,IAAI,CAAC,OAAO,YACV,MAAM,IAAI,MACR,6FACF;AACJ"}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type DuraxisConfiguration, type DuraxisDatabase } from "@duraxis/core";
|
|
2
2
|
import type { EntityClass } from "@duraxis/orm";
|
|
3
3
|
export interface DuraxisConnectionConfig {
|
|
4
|
-
readonly
|
|
5
|
-
readonly
|
|
4
|
+
readonly settings?: unknown;
|
|
5
|
+
readonly moduleFormat?: "esm" | "cjs";
|
|
6
|
+
readonly entities?: readonly EntityClass[] | (() => readonly EntityClass[] | Promise<readonly EntityClass[]>);
|
|
7
|
+
readonly migrations?: {
|
|
6
8
|
readonly directory: string;
|
|
7
9
|
readonly snapshots: string;
|
|
8
|
-
readonly format?: "ts" | "js";
|
|
10
|
+
readonly format?: "ts" | "js" | "mts" | "mjs";
|
|
9
11
|
};
|
|
10
12
|
readonly createDatabase: () => DuraxisDatabase | Promise<DuraxisDatabase>;
|
|
11
13
|
}
|
|
12
|
-
export
|
|
13
|
-
readonly databases?: Readonly<Record<string, DuraxisConnectionConfig>>;
|
|
14
|
-
}
|
|
15
|
-
export declare function defineDuraxisConfig<const T extends DuraxisConfig>(config: T): T;
|
|
14
|
+
export type DuraxisConfig = DuraxisConfiguration;
|
|
16
15
|
export declare function importFile(path: string | URL): Promise<unknown>;
|
|
17
16
|
export declare function loadConfig(cwd: string, explicit?: string, database?: string): Promise<{
|
|
18
17
|
config: DuraxisConnectionConfig;
|
|
@@ -20,3 +19,6 @@ export declare function loadConfig(cwd: string, explicit?: string, database?: st
|
|
|
20
19
|
path: string;
|
|
21
20
|
}>;
|
|
22
21
|
export declare function readJSON<T>(path: string): Promise<T>;
|
|
22
|
+
export declare function requireMigrationConfig(config: DuraxisConnectionConfig): asserts config is DuraxisConnectionConfig & {
|
|
23
|
+
migrations: NonNullable<DuraxisConnectionConfig["migrations"]>;
|
|
24
|
+
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { RegistryClient } from "./registry-client.js";
|
|
2
|
+
export declare function resolveDependencies(names: readonly string[], existing: Record<string, string>, registry: RegistryClient, prerelease?: boolean, node?: string, preserveExisting?: boolean): Promise<Record<string, string>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function installedPackage(root: string, name: string): Promise<Record<string, unknown> | undefined>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type PackageManager } from "../init/project-detector.js";
|
|
2
|
+
export interface ProcessRequest {
|
|
3
|
+
command: string;
|
|
4
|
+
args: readonly string[];
|
|
5
|
+
cwd: string;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
}
|
|
8
|
+
export type ProcessRunner = (request: ProcessRequest) => Promise<void>;
|
|
9
|
+
export declare const runProcess: ProcessRunner;
|
|
10
|
+
export declare function installCommands(manager: PackageManager, dependencies: Record<string, string>, development: Record<string, string>): string[][];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface PublishedVersion {
|
|
2
|
+
version: string;
|
|
3
|
+
dependencies: Record<string, string>;
|
|
4
|
+
peers: Record<string, string>;
|
|
5
|
+
optionalPeers: Set<string>;
|
|
6
|
+
node?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface PackageMetadata {
|
|
9
|
+
name: string;
|
|
10
|
+
versions: PublishedVersion[];
|
|
11
|
+
tags: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
export declare class RegistryClient {
|
|
14
|
+
private readonly registry;
|
|
15
|
+
private readonly request;
|
|
16
|
+
private readonly signal?;
|
|
17
|
+
private readonly cache;
|
|
18
|
+
constructor(registry?: string, request?: typeof fetch, signal?: AbortSignal | undefined);
|
|
19
|
+
get(name: string): Promise<PackageMetadata>;
|
|
20
|
+
private load;
|
|
21
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface Version {
|
|
2
|
+
major: number;
|
|
3
|
+
minor: number;
|
|
4
|
+
patch: number;
|
|
5
|
+
prerelease: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function version(value: string): Version;
|
|
8
|
+
export declare function compare(a: string, b: string): number;
|
|
9
|
+
export declare function satisfies(actual: string, range: string): boolean;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { chmod, lstat, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
// src/filesystem/file-plan.ts
|
|
5
|
+
function safeRelative(path) {
|
|
6
|
+
if (!path || isAbsolute(path) || path.includes("\\") || path.includes("\0") || path.split("/").some((p) => p === ".." || p === "." || !p) || path.includes(":")) throw new Error(`Unsafe project path: ${path}`);
|
|
7
|
+
return path;
|
|
8
|
+
}
|
|
9
|
+
async function assertNoSymlinks(path) {
|
|
10
|
+
let cursor = resolve(path);
|
|
11
|
+
while (true) {
|
|
12
|
+
try {
|
|
13
|
+
if ((await lstat(cursor)).isSymbolicLink()) throw new Error(`Symlinks are not allowed in managed paths: ${cursor}`);
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
16
|
+
}
|
|
17
|
+
if (dirname(cursor) === cursor) break;
|
|
18
|
+
cursor = dirname(cursor);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
async function addFile(plan, path, content, update = false) {
|
|
22
|
+
safeRelative(path);
|
|
23
|
+
const target = resolve(plan.root, path);
|
|
24
|
+
await assertNoSymlinks(target);
|
|
25
|
+
let before;
|
|
26
|
+
try {
|
|
27
|
+
before = await readFile(target, "utf8");
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
30
|
+
}
|
|
31
|
+
if (before === content) return;
|
|
32
|
+
if (before !== void 0 && !update) throw new Error(`Refusing to overwrite ${path}`);
|
|
33
|
+
if (plan.files.some((f) => f.path === path)) throw new Error(`Duplicate planned file: ${path}`);
|
|
34
|
+
plan.files.push({
|
|
35
|
+
path,
|
|
36
|
+
content,
|
|
37
|
+
...before === void 0 ? {} : { before }
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async function executeFiles(plan, after) {
|
|
41
|
+
await assertNoSymlinks(plan.root);
|
|
42
|
+
await mkdir(plan.root, { recursive: true });
|
|
43
|
+
const lockPath = join(plan.root, ".duraxis-init.lock");
|
|
44
|
+
const lock = await import("node:fs/promises").then((fs) => fs.open(lockPath, "wx"));
|
|
45
|
+
const applied = [];
|
|
46
|
+
const createdDirectories = [];
|
|
47
|
+
const ensureDirectory = async (path) => {
|
|
48
|
+
if (path === plan.root) return;
|
|
49
|
+
if (relative(plan.root, path).startsWith("..")) throw new Error("Directory escapes project");
|
|
50
|
+
await assertNoSymlinks(path);
|
|
51
|
+
try {
|
|
52
|
+
if (!(await lstat(path)).isDirectory()) throw new Error("Expected a directory");
|
|
53
|
+
return;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
56
|
+
}
|
|
57
|
+
await ensureDirectory(dirname(path));
|
|
58
|
+
await mkdir(path);
|
|
59
|
+
createdDirectories.push(path);
|
|
60
|
+
};
|
|
61
|
+
const replace = async (target, content) => {
|
|
62
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
63
|
+
try {
|
|
64
|
+
const mode = (await lstat(target)).mode & 511;
|
|
65
|
+
await writeFile(temporary, content, {
|
|
66
|
+
flag: "wx",
|
|
67
|
+
mode
|
|
68
|
+
});
|
|
69
|
+
await chmod(temporary, mode);
|
|
70
|
+
await rename(temporary, target);
|
|
71
|
+
} finally {
|
|
72
|
+
await unlink(temporary).catch((error) => {
|
|
73
|
+
if (error.code !== "ENOENT") throw error;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
for (const path of plan.directories) await ensureDirectory(resolve(plan.root, safeRelative(path)));
|
|
79
|
+
for (const file of plan.files) {
|
|
80
|
+
const target = resolve(plan.root, safeRelative(file.path));
|
|
81
|
+
await assertNoSymlinks(target);
|
|
82
|
+
await ensureDirectory(dirname(target));
|
|
83
|
+
if (file.before === void 0) await writeFile(target, file.content, { flag: "wx" });
|
|
84
|
+
else {
|
|
85
|
+
if (await readFile(target, "utf8") !== file.before) throw new Error(`File changed since planning: ${file.path}`);
|
|
86
|
+
await replace(target, file.content);
|
|
87
|
+
}
|
|
88
|
+
applied.push(file);
|
|
89
|
+
}
|
|
90
|
+
return await after();
|
|
91
|
+
} catch (cause) {
|
|
92
|
+
const failures = [];
|
|
93
|
+
for (const file of applied.reverse()) try {
|
|
94
|
+
const target = resolve(plan.root, file.path);
|
|
95
|
+
await assertNoSymlinks(target);
|
|
96
|
+
if (await readFile(target, "utf8") !== file.content) throw new Error(`Rollback preserved a concurrently changed file: ${file.path}`);
|
|
97
|
+
if (file.before === void 0) await unlink(target);
|
|
98
|
+
else await replace(target, file.before);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
failures.push(error);
|
|
101
|
+
}
|
|
102
|
+
for (const path of createdDirectories.reverse()) await rmdir(path).catch((error) => {
|
|
103
|
+
if (!["ENOTEMPTY", "ENOENT"].includes(error.code)) failures.push(error);
|
|
104
|
+
});
|
|
105
|
+
if (failures.length) throw new AggregateError([cause, ...failures], "Initialization failed; some files changed externally and were preserved. Inspect package.json and lockfiles before retrying.");
|
|
106
|
+
throw cause;
|
|
107
|
+
} finally {
|
|
108
|
+
await lock.close();
|
|
109
|
+
await unlink(lockPath);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** Public plans describe changes without echoing secrets in existing file contents. */
|
|
113
|
+
function describePlan(plan) {
|
|
114
|
+
return {
|
|
115
|
+
root: plan.root,
|
|
116
|
+
files: plan.files.map((file) => ({
|
|
117
|
+
path: file.path,
|
|
118
|
+
action: file.before === void 0 ? "create" : "modify",
|
|
119
|
+
bytes: Buffer.byteLength(file.content)
|
|
120
|
+
})),
|
|
121
|
+
directories: plan.directories,
|
|
122
|
+
dependencies: plan.dependencies,
|
|
123
|
+
devDependencies: plan.devDependencies,
|
|
124
|
+
commands: plan.commands,
|
|
125
|
+
warnings: plan.warnings
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export { addFile, describePlan, executeFiles, safeRelative };
|
|
129
|
+
|
|
130
|
+
//# sourceMappingURL=file-plan-D-Sj3yv0.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-plan-D-Sj3yv0.js","names":[],"sources":["../src/filesystem/file-plan.ts"],"sourcesContent":["import { lstat, readFile, writeFile, mkdir, rename, unlink, rmdir, chmod } from \"node:fs/promises\";\nimport { resolve, relative, dirname, isAbsolute, join } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nexport interface FileChange {\n path: string;\n content: string;\n before?: string;\n}\nexport interface FilePlan {\n root: string;\n files: FileChange[];\n directories: string[];\n warnings: string[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n commands: string[][];\n}\nexport function safeRelative(path: string): string {\n if (\n !path ||\n isAbsolute(path) ||\n path.includes(\"\\\\\") ||\n path.includes(\"\\0\") ||\n path.split(\"/\").some((p) => p === \"..\" || p === \".\" || !p) ||\n path.includes(\":\")\n )\n throw new Error(`Unsafe project path: ${path}`);\n return path;\n}\nexport async function assertNoSymlinks(path: string): Promise<void> {\n const absolute = resolve(path);\n let cursor = absolute;\n while (true) {\n try {\n if ((await lstat(cursor)).isSymbolicLink())\n throw new Error(`Symlinks are not allowed in managed paths: ${cursor}`);\n } catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")) throw error;\n }\n if (dirname(cursor) === cursor) break;\n cursor = dirname(cursor);\n }\n}\nexport async function addFile(\n plan: FilePlan,\n path: string,\n content: string,\n update = false,\n): Promise<void> {\n safeRelative(path);\n const target = resolve(plan.root, path);\n await assertNoSymlinks(target);\n let before: string | undefined;\n try {\n before = await readFile(target, \"utf8\");\n } catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")) throw error;\n }\n if (before === content) return;\n if (before !== undefined && !update) throw new Error(`Refusing to overwrite ${path}`);\n if (plan.files.some((f) => f.path === path)) throw new Error(`Duplicate planned file: ${path}`);\n plan.files.push({ path, content, ...(before === undefined ? {} : { before }) });\n}\nexport async function executeFiles<T>(plan: FilePlan, after: () => Promise<T>): Promise<T> {\n await assertNoSymlinks(plan.root);\n await mkdir(plan.root, { recursive: true });\n const lockPath = join(plan.root, \".duraxis-init.lock\");\n const lock = await import(\"node:fs/promises\").then((fs) => fs.open(lockPath, \"wx\"));\n const applied: FileChange[] = [];\n const createdDirectories: string[] = [];\n const ensureDirectory = async (path: string): Promise<void> => {\n if (path === plan.root) return;\n if (relative(plan.root, path).startsWith(\"..\")) throw new Error(\"Directory escapes project\");\n await assertNoSymlinks(path);\n try {\n const stat = await lstat(path);\n if (!stat.isDirectory()) throw new Error(\"Expected a directory\");\n return;\n } catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")) throw error;\n }\n await ensureDirectory(dirname(path));\n await mkdir(path);\n createdDirectories.push(path);\n };\n const replace = async (target: string, content: string) => {\n const temporary = `${target}.${randomUUID()}.tmp`;\n try {\n const mode = (await lstat(target)).mode & 0o777;\n await writeFile(temporary, content, { flag: \"wx\", mode });\n await chmod(temporary, mode);\n await rename(temporary, target);\n } finally {\n await unlink(temporary).catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n });\n }\n };\n try {\n for (const path of plan.directories)\n await ensureDirectory(resolve(plan.root, safeRelative(path)));\n for (const file of plan.files) {\n const target = resolve(plan.root, safeRelative(file.path));\n await assertNoSymlinks(target);\n await ensureDirectory(dirname(target));\n if (file.before === undefined) await writeFile(target, file.content, { flag: \"wx\" });\n else {\n if ((await readFile(target, \"utf8\")) !== file.before)\n throw new Error(`File changed since planning: ${file.path}`);\n await replace(target, file.content);\n }\n applied.push(file);\n }\n return await after();\n } catch (cause) {\n const failures: unknown[] = [];\n for (const file of applied.reverse())\n try {\n const target = resolve(plan.root, file.path);\n await assertNoSymlinks(target);\n if ((await readFile(target, \"utf8\")) !== file.content)\n throw new Error(`Rollback preserved a concurrently changed file: ${file.path}`);\n if (file.before === undefined) await unlink(target);\n else await replace(target, file.before);\n } catch (error) {\n failures.push(error);\n }\n for (const path of createdDirectories.reverse())\n await rmdir(path).catch((error) => {\n if (![\"ENOTEMPTY\", \"ENOENT\"].includes(error.code)) failures.push(error);\n });\n if (failures.length)\n throw new AggregateError(\n [cause, ...failures],\n \"Initialization failed; some files changed externally and were preserved. Inspect package.json and lockfiles before retrying.\",\n );\n throw cause;\n } finally {\n await lock.close();\n await unlink(lockPath);\n }\n}\n\n/** Public plans describe changes without echoing secrets in existing file contents. */\nexport function describePlan(plan: FilePlan) {\n return {\n root: plan.root,\n files: plan.files.map((file) => ({\n path: file.path,\n action: file.before === undefined ? \"create\" : \"modify\",\n bytes: Buffer.byteLength(file.content),\n })),\n directories: plan.directories,\n dependencies: plan.dependencies,\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R,UAAU;EACR,MAAM,KAAK,MAAM;EACjB,MAAM,OAAO,QAAQ;CACvB;AACF;;AAGA,SAAgB,aAAa,MAAgB;CAC3C,OAAO;EACL,MAAM,KAAK;EACX,OAAO,KAAK,MAAM,KAAK,UAAU;GAC/B,MAAM,KAAK;GACX,QAAQ,KAAK,WAAW,KAAA,IAAY,WAAW;GAC/C,OAAO,OAAO,WAAW,KAAK,OAAO;EACvC,EAAE;EACF,aAAa,KAAK;EAClB,cAAc,KAAK;EACnB,iBAAiB,KAAK;EACtB,UAAU,KAAK;EACf,UAAU,KAAK;CACjB;AACF"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface FileChange {
|
|
2
|
+
path: string;
|
|
3
|
+
content: string;
|
|
4
|
+
before?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface FilePlan {
|
|
7
|
+
root: string;
|
|
8
|
+
files: FileChange[];
|
|
9
|
+
directories: string[];
|
|
10
|
+
warnings: string[];
|
|
11
|
+
dependencies: Record<string, string>;
|
|
12
|
+
devDependencies: Record<string, string>;
|
|
13
|
+
commands: string[][];
|
|
14
|
+
}
|
|
15
|
+
export declare function safeRelative(path: string): string;
|
|
16
|
+
export declare function assertNoSymlinks(path: string): Promise<void>;
|
|
17
|
+
export declare function addFile(plan: FilePlan, path: string, content: string, update?: boolean): Promise<void>;
|
|
18
|
+
export declare function executeFiles<T>(plan: FilePlan, after: () => Promise<T>): Promise<T>;
|
|
19
|
+
/** Public plans describe changes without echoing secrets in existing file contents. */
|
|
20
|
+
export declare function describePlan(plan: FilePlan): {
|
|
21
|
+
root: string;
|
|
22
|
+
files: {
|
|
23
|
+
path: string;
|
|
24
|
+
action: string;
|
|
25
|
+
bytes: number;
|
|
26
|
+
}[];
|
|
27
|
+
directories: string[];
|
|
28
|
+
dependencies: Record<string, string>;
|
|
29
|
+
devDependencies: Record<string, string>;
|
|
30
|
+
commands: string[][];
|
|
31
|
+
warnings: string[];
|
|
32
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { runCLI } from "./cli.js";
|
|
2
2
|
export type { CLIIO } from "./cli.js";
|
|
3
|
-
export {
|
|
3
|
+
export { loadConfig } from "./config.js";
|
|
4
4
|
export type { DuraxisConfig, DuraxisConnectionConfig } from "./config.js";
|
|
5
5
|
export { disposeTypeScriptLoader } from "./typescript-loader.js";
|