@moldea.ai/cli 12.0.0 → 13.0.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.
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import process$1 from "node:process";
3
- import { createHash, timingSafeEqual } from "node:crypto";
4
- import { execFile, spawn } from "node:child_process";
5
- import { TextDecoder as TextDecoder$1 } from "node:util";
2
+ import { getErrorCode } from "jg-exception";
3
+ import { ERRORS } from "jg-process";
4
+ import { timingSafeEqual } from "node:crypto";
5
+ import { hashValue } from "jg-crypto";
6
+ import { deepFreeze, stringifyJsonDeterministically, takeWithinByteBudget } from "jg-utilities";
7
+ import { ERRORS as ERRORS$1, assertGitSucceeded, readGitVersion, runGit } from "jg-git-commands";
6
8
  import { SUPPORTED_REPOSITORY_FORMAT_VERSIONS } from "@moldea.ai/core";
7
9
  //#region \0rolldown/runtime.js
8
10
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
@@ -54,59 +56,6 @@ var MoldeaCliOutputPageException = class extends Error {
54
56
  }
55
57
  };
56
58
  //#endregion
57
- //#region src/json-serialization/serializer.ts
58
- /** Compares strings by Unicode code point rather than UTF-16 code unit. */
59
- var compareUnicodeCodePoints = (left, right) => {
60
- const leftCodePoints = [...left];
61
- const rightCodePoints = [...right];
62
- const sharedLength = Math.min(leftCodePoints.length, rightCodePoints.length);
63
- for (let index = 0; index < sharedLength; index += 1) {
64
- const leftCodePoint = leftCodePoints[index]?.codePointAt(0);
65
- const rightCodePoint = rightCodePoints[index]?.codePointAt(0);
66
- if (leftCodePoint === void 0 || rightCodePoint === void 0) throw new TypeError("The JSON object key could not be compared.");
67
- if (leftCodePoint !== rightCodePoint) return leftCodePoint - rightCodePoint;
68
- }
69
- return leftCodePoints.length - rightCodePoints.length;
70
- };
71
- /** Serializes one validated JSON value with recursively sorted object keys. */
72
- var serializeJsonValue = (value, ancestors) => {
73
- if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
74
- if (typeof value === "number") {
75
- if (!Number.isFinite(value)) throw new TypeError("The JSON number must be finite.");
76
- return JSON.stringify(Object.is(value, -0) ? 0 : value);
77
- }
78
- if (typeof value !== "object") throw new TypeError("The value is not supported by the CLI JSON contract.");
79
- if (ancestors.has(value)) throw new TypeError("The CLI JSON value must not contain a cycle.");
80
- ancestors.add(value);
81
- try {
82
- if (Array.isArray(value)) {
83
- const serializedEntries = [];
84
- for (let index = 0; index < value.length; index += 1) {
85
- if (!Object.hasOwn(value, index)) throw new TypeError("The CLI JSON array must not contain empty slots.");
86
- serializedEntries.push(serializeJsonValue(value[index], ancestors));
87
- }
88
- return `[${serializedEntries.join(",")}]`;
89
- }
90
- const prototype = Object.getPrototypeOf(value);
91
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("The CLI JSON object must be a plain record.");
92
- if (Object.getOwnPropertySymbols(value).length > 0) throw new TypeError("The CLI JSON object must not contain symbol keys.");
93
- const record = value;
94
- return `{${Object.keys(record).sort(compareUnicodeCodePoints).map((key) => `${JSON.stringify(key)}:${serializeJsonValue(record[key], ancestors)}`).join(",")}}`;
95
- } finally {
96
- ancestors.delete(value);
97
- }
98
- };
99
- /**
100
- * Serializes one CLI JSON value with exact recursive Unicode code-point key ordering.
101
- * @param value The closed JSON value to serialize.
102
- * @returns Compact deterministic JSON without a trailing line feed.
103
- * @throws
104
- * - If the value contains unsupported, non-finite, symbolic, class-backed, or cyclic data
105
- */
106
- var serializeJsonDeterministically = (value) => {
107
- return serializeJsonValue(value, /* @__PURE__ */ new Set());
108
- };
109
- //#endregion
110
59
  //#region src/output-page/cursor.ts
111
60
  var SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u;
112
61
  var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
@@ -121,7 +70,7 @@ var CURSOR_DOCUMENT_KEYS = Object.freeze([
121
70
  ]);
122
71
  /** Calculates one stable SHA-256 identifier for deterministic JSON text. */
123
72
  var calculateMoldeaCliJsonDigest = (value) => {
124
- return `sha256:${createHash("sha256").update(serializeJsonDeterministically(value), "utf8").digest("hex")}`;
73
+ return `sha256:${hashValue(stringifyJsonDeterministically(value, { strict: true }))}`;
125
74
  };
126
75
  /** Calculates the checksum for one cursor payload without its checksum field. */
127
76
  var calculateCursorChecksum = (payload) => {
@@ -154,7 +103,7 @@ var encodeMoldeaCliCursor = (command, filters, snapshotDigest, lastKey, sourceCu
154
103
  ...payload,
155
104
  checksum: calculateCursorChecksum(payload)
156
105
  };
157
- return Buffer.from(serializeJsonDeterministically(document), "utf8").toString("base64url");
106
+ return Buffer.from(stringifyJsonDeterministically(document, { strict: true }), "utf8").toString("base64url");
158
107
  };
159
108
  /**
160
109
  * Decodes and validates one opaque continuation cursor.
@@ -223,56 +172,29 @@ var createMoldeaCliOutputPage = (input) => {
223
172
  if (input.measure(emptyPage, 2) > input.maxOutputBytes) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
224
173
  return emptyPage;
225
174
  }
226
- const selectedRecords = [];
227
- let selectedCursor = null;
228
- let serializedRecordsUtf8Bytes = 2;
229
- for (let endIndex = startIndex + 1; endIndex <= input.records.length; endIndex += 1) {
230
- const record = input.records[endIndex - 1];
231
- if (record === void 0) throw new TypeError("An output page record is missing.");
232
- const serializedRecordUtf8Bytes = Buffer.byteLength(serializeJsonDeterministically(record), "utf8");
233
- serializedRecordsUtf8Bytes += serializedRecordUtf8Bytes + (endIndex > startIndex + 1 ? 1 : 0);
234
- selectedRecords.push(record);
175
+ /** Creates the cursor that continues after a page ending with the record at this end index. */
176
+ const createCursor = (record, endIndex) => {
235
177
  const sourceCursor = input.sourceCursorForRecord?.(record) ?? null;
236
- const cursor = (input.sourceCursorForRecord === void 0 ? endIndex < input.records.length : sourceCursor !== null) ? encodeMoldeaCliCursor(input.command, input.filters, input.snapshotDigest, record.key, sourceCursor) : null;
237
- const candidate = Object.freeze({
238
- cursor,
239
- records: selectedRecords
240
- });
241
- if (input.measure(candidate, serializedRecordsUtf8Bytes) > input.maxOutputBytes) {
242
- selectedRecords.pop();
243
- break;
244
- }
245
- selectedCursor = cursor;
246
- }
247
- if (selectedRecords.length === 0) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
178
+ return (input.sourceCursorForRecord === void 0 ? endIndex < input.records.length : sourceCursor !== null) ? encodeMoldeaCliCursor(input.command, input.filters, input.snapshotDigest, record.key, sourceCursor) : null;
179
+ };
180
+ const selectedRecords = takeWithinByteBudget(input.records.slice(startIndex), {
181
+ maxBytes: input.maxOutputBytes,
182
+ measurePage: (page, itemsBytes) => input.measure(Object.freeze({
183
+ cursor: createCursor(page[page.length - 1], startIndex + page.length),
184
+ records: page
185
+ }), itemsBytes)
186
+ });
187
+ const lastRecord = selectedRecords[selectedRecords.length - 1];
188
+ if (lastRecord === void 0) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
248
189
  return Object.freeze({
249
- cursor: selectedCursor,
250
- records: Object.freeze([...selectedRecords])
190
+ cursor: createCursor(lastRecord, startIndex + selectedRecords.length),
191
+ records: Object.freeze(selectedRecords)
251
192
  });
252
193
  };
253
194
  //#endregion
254
195
  //#region src/command-line/validations.ts
255
196
  var POSITIVE_INTEGER_PATTERN = /^\d+$/u;
256
197
  /**
257
- * Determines whether text contains only Unicode scalar values.
258
- * @param text The text to validate.
259
- * @returns Whether the text contains no unpaired UTF-16 surrogate.
260
- */
261
- var hasOnlyUnicodeScalarValues = (text) => {
262
- for (let index = 0; index < text.length; index += 1) {
263
- const codeUnit = text.charCodeAt(index);
264
- if (codeUnit >= 55296 && codeUnit <= 56319) {
265
- if (index + 1 >= text.length) return false;
266
- const trailingCodeUnit = text.charCodeAt(index + 1);
267
- if (trailingCodeUnit < 56320 || trailingCodeUnit > 57343) return false;
268
- index += 1;
269
- continue;
270
- }
271
- if (codeUnit >= 56320 && codeUnit <= 57343) return false;
272
- }
273
- return true;
274
- };
275
- /**
276
198
  * Parses one strict base-10 positive safe integer option value.
277
199
  * @param input The untrusted command-line token.
278
200
  * @returns The parsed integer, or null when the token is invalid.
@@ -301,11 +223,11 @@ var areMoldeaCliResourceLimitsConsistent = (limits) => {
301
223
  * @returns Whether the token is non-empty scalar text without NUL.
302
224
  */
303
225
  var isRepositoryDirectoryInputValid = (input) => {
304
- return input.length > 0 && !input.includes("\0") && hasOnlyUnicodeScalarValues(input);
226
+ return input.length > 0 && !input.includes("\0") && input.isWellFormed();
305
227
  };
306
228
  /** Determines whether one opaque cursor token is bounded safe scalar text. */
307
229
  var isMoldeaCliCursorInputValid = (input) => {
308
- return input.length > 0 && input.length <= 16384 && !input.includes("\0") && hasOnlyUnicodeScalarValues(input);
230
+ return input.length > 0 && input.length <= 16384 && !input.includes("\0") && input.isWellFormed();
309
231
  };
310
232
  //#endregion
311
233
  //#region src/command-line/parser.ts
@@ -642,13 +564,14 @@ var EMPTY_ERROR_DETAILS = Object.freeze({});
642
564
  /**
643
565
  * Creates one immutable safe error from a CLI- or Git-owned definition.
644
566
  * @param code The stable executable-owned error code.
567
+ * @param details Safe fixed details, such as the Git subcommand that failed.
645
568
  * @returns The complete safe error object.
646
569
  */
647
- var createMoldeaCliOwnedError = (code) => {
570
+ var createMoldeaCliOwnedError = (code, details = EMPTY_ERROR_DETAILS) => {
648
571
  const definition = MOLDEA_CLI_ERROR_DEFINITIONS[code];
649
572
  return Object.freeze({
650
573
  code,
651
- details: EMPTY_ERROR_DETAILS,
574
+ details: Object.freeze({ ...details }),
652
575
  message: definition.message,
653
576
  path: null,
654
577
  retryable: definition.retryable,
@@ -666,8 +589,8 @@ var createMoldeaCliJsonEnvelope = (input) => Object.freeze({
666
589
  schemaVersion: 7,
667
590
  status: input.status
668
591
  });
669
- /** Serializes one schema 7 envelope with its required trailing line feed. */
670
- var serializeMoldeaCliJsonEnvelope = (input) => `${serializeJsonDeterministically(createMoldeaCliJsonEnvelope(input))}\n`;
592
+ /** Serializes one schema 7 envelope, keys in RFC 8785 order, with its trailing line feed. */
593
+ var serializeMoldeaCliJsonEnvelope = (input) => `${stringifyJsonDeterministically(createMoldeaCliJsonEnvelope(input), { strict: true })}\n`;
671
594
  //#endregion
672
595
  //#region src/presentation/formatters.ts
673
596
  var DIAGNOSTIC_ENTITY_KEYS = [
@@ -941,346 +864,122 @@ var createMoldeaCliInspectProjection = (inspection) => {
941
864
  });
942
865
  };
943
866
  //#endregion
944
- //#region src/git-process/constants.ts
945
- var GIT_PROCESS_GLOBAL_ARGUMENTS = [
946
- "--no-pager",
947
- "-c",
948
- "color.ui=false",
949
- "-c",
950
- "core.fsmonitor=false",
951
- "-c",
952
- "submodule.recurse=false"
953
- ];
954
- var MAX_GIT_PROCESS_DIAGNOSTIC_BYTES = 4096;
955
- var GIT_PROCESS_REMOVED_ENVIRONMENT_NAMES = [
956
- "GIT_DIR",
957
- "GIT_WORK_TREE",
958
- "GIT_INDEX_FILE",
959
- "GIT_OBJECT_DIRECTORY",
960
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
961
- "GIT_COMMON_DIR",
962
- "GIT_CEILING_DIRECTORIES",
963
- "GIT_DISCOVERY_ACROSS_FILESYSTEM",
964
- "GIT_NAMESPACE",
965
- "GIT_SHALLOW_FILE",
966
- "GIT_ATTR_SOURCE",
967
- "GIT_CONFIG",
968
- "GIT_CONFIG_SYSTEM",
969
- "GIT_CONFIG_GLOBAL",
970
- "GIT_CONFIG_NOSYSTEM",
971
- "GIT_CONFIG_PARAMETERS",
972
- "GIT_CONFIG_COUNT",
973
- "GIT_EXEC_PATH",
974
- "GIT_LITERAL_PATHSPECS",
975
- "GIT_GLOB_PATHSPECS",
976
- "GIT_NOGLOB_PATHSPECS",
977
- "GIT_ICASE_PATHSPECS"
978
- ];
979
- var GIT_PROCESS_REMOVED_ENVIRONMENT_PREFIXES = [
980
- "GIT_CONFIG_KEY_",
981
- "GIT_CONFIG_VALUE_",
982
- "GIT_TRACE"
983
- ];
984
- var GIT_PROCESS_ENVIRONMENT_OVERRIDES = Object.freeze({
985
- LC_ALL: "C",
986
- LANG: "C",
987
- LANGUAGE: "C",
988
- GIT_OPTIONAL_LOCKS: "0",
989
- GIT_PAGER: "",
990
- PAGER: "",
991
- GIT_TERMINAL_PROMPT: "0",
992
- NO_COLOR: "1"
993
- });
994
- //#endregion
995
- //#region src/git-process/environment.ts
996
- var REMOVED_ENVIRONMENT_NAMES = new Set(GIT_PROCESS_REMOVED_ENVIRONMENT_NAMES.map((name) => name.toUpperCase()));
867
+ //#region src/git-command/utilities.ts
997
868
  /**
998
- * Determines whether an inherited environment variable can alter Git behavior.
999
- * @param name The environment variable name.
1000
- * @returns Whether the variable must be removed.
869
+ * Creates one immutable Git failure.
870
+ * @param reason Why the command failed.
871
+ * @param subcommand The fixed Git subcommand that failed, when the caller knows it.
872
+ * @returns The failed read result.
1001
873
  */
1002
- var isRemovedEnvironmentVariable = (name) => {
1003
- const normalizedName = name.toUpperCase();
1004
- return REMOVED_ENVIRONMENT_NAMES.has(normalizedName) || GIT_PROCESS_REMOVED_ENVIRONMENT_PREFIXES.some((prefix) => normalizedName.startsWith(prefix));
1005
- };
874
+ var createGitFailure = (reason, subcommand) => Object.freeze({
875
+ kind: "failed",
876
+ reason,
877
+ ...subcommand === void 0 ? {} : { subcommand }
878
+ });
1006
879
  /**
1007
- * Creates the immutable, deterministic environment used by Git subprocesses.
1008
- * @param environment The host environment to sanitize.
1009
- * @returns A frozen environment that preserves unrelated variables.
880
+ * Classifies one Git error by its code, without retaining its diagnostics.
881
+ * @param error The error a Git command or read rejected with.
882
+ * @param signal The command's cancellation signal, whose abort takes precedence.
883
+ * @returns The failure reason.
1010
884
  */
1011
- var createGitProcessEnvironment = (environment) => {
1012
- const sanitizedEnvironment = {};
1013
- for (const [name, environmentValue] of Object.entries(environment)) if (environmentValue !== void 0 && !isRemovedEnvironmentVariable(name) && !(name.toUpperCase() in GIT_PROCESS_ENVIRONMENT_OVERRIDES)) sanitizedEnvironment[name] = environmentValue;
1014
- return Object.freeze({
1015
- ...sanitizedEnvironment,
1016
- ...GIT_PROCESS_ENVIRONMENT_OVERRIDES
1017
- });
885
+ var classifyGitFailure = (error, signal) => {
886
+ if (signal?.aborted === true) return "aborted";
887
+ switch (getErrorCode(error)) {
888
+ case ERRORS$1.GIT_NOT_FOUND: return "not-found";
889
+ case ERRORS$1.GIT_REPOSITORY_NOT_FOUND: return "repository-not-found";
890
+ case ERRORS$1.GIT_ACCESS_DENIED: return "access-denied";
891
+ case ERRORS$1.GIT_OUTPUT_INVALID: return "output-invalid";
892
+ case ERRORS.PROCESS_OUTPUT_TOO_LARGE: return "output-limit-exceeded";
893
+ case ERRORS.PROCESS_START_FAILED: {
894
+ const causeCode = getErrorCode(error.cause);
895
+ return causeCode === "EACCES" || causeCode === "EPERM" ? "access-denied" : "command-failed";
896
+ }
897
+ default: return "command-failed";
898
+ }
1018
899
  };
1019
- //#endregion
1020
- //#region src/git-process/utilities.ts
1021
900
  /**
1022
- * Classifies a subprocess error without retaining provider diagnostics.
1023
- * @param error The Node.js subprocess error, or null for a nonzero exit.
1024
- * @param stderr The bounded process diagnostic used only for classification.
1025
- * @returns The normalized failure reason.
901
+ * Runs one typed Git read and turns its rejection into a failure reason.
902
+ * @param read The read, such as one of jg-git-commands' typed commands.
903
+ * @param signal The read's cancellation signal.
904
+ * @param subcommand The fixed Git subcommand the read runs, named in its failure.
905
+ * @returns A promise resolving to the read's value, or why it failed.
1026
906
  */
1027
- var classifyGitProcessError = (error, stderr) => {
1028
- const errorCode = error instanceof Error && "code" in error && typeof error.code === "string" ? error.code.toUpperCase() : "";
1029
- if (errorCode === "ENOENT") return "not-found";
1030
- if (errorCode === "EACCES" || errorCode === "EPERM") return "access-denied";
1031
- if (errorCode === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "output-limit-exceeded";
1032
- const diagnostic = new TextDecoder().decode(stderr);
1033
- if (diagnostic.startsWith("fatal: not a git repository")) return "repository-not-found";
1034
- if (diagnostic.startsWith("fatal: detected dubious ownership in repository at ") || diagnostic.startsWith("fatal: ") && /: Permission denied(?:\r?\n)?$/u.test(diagnostic)) return "access-denied";
1035
- return "command-failed";
907
+ var readGit = async (read, signal, subcommand) => {
908
+ try {
909
+ return Object.freeze({
910
+ kind: "completed",
911
+ value: await read()
912
+ });
913
+ } catch (error) {
914
+ return createGitFailure(classifyGitFailure(error, signal), subcommand);
915
+ }
1036
916
  };
1037
- //#endregion
1038
- //#region src/git-process/executor.ts
1039
917
  /**
1040
- * Executes Git directly with trusted arguments, a sanitized environment, and bounded output.
1041
- * @param options The trusted arguments, environment, output limit, and optional signal.
1042
- * @returns A promise that resolves to normalized process output or failure.
918
+ * Checks one finished Git command. Git exits with 0 after warning on stderr that it skipped
919
+ * something, so any diagnostic fails a command that otherwise succeeded.
920
+ * @param result The command's result, as bytes.
921
+ * @param subcommand The Git subcommand that ran.
922
+ * @returns Why the command failed, or null when it succeeded without diagnostics.
1043
923
  */
1044
- var executeGitProcess = async (options) => new Promise((resolve) => {
1045
- if (options.signal?.aborted) {
1046
- resolve(Object.freeze({
1047
- kind: "failed",
1048
- reason: "aborted"
1049
- }));
1050
- return;
924
+ var checkGitResult = (result, subcommand) => {
925
+ if (result.stderr.byteLength > 4096) return "output-invalid";
926
+ try {
927
+ assertGitSucceeded(result, subcommand);
928
+ } catch (error) {
929
+ return classifyGitFailure(error);
1051
930
  }
1052
- execFile("git", [...GIT_PROCESS_GLOBAL_ARGUMENTS, ...options.arguments], {
1053
- encoding: "buffer",
1054
- env: createGitProcessEnvironment(options.environment ?? process$1.env),
1055
- maxBuffer: options.maxBufferBytes,
1056
- shell: false,
1057
- ...options.signal === void 0 ? {} : { signal: options.signal },
1058
- windowsHide: true
1059
- }, (error, stdout, stderr) => {
1060
- if (options.signal?.aborted) {
1061
- resolve(Object.freeze({
1062
- kind: "failed",
1063
- reason: "aborted"
1064
- }));
1065
- return;
1066
- }
1067
- if (error) {
1068
- resolve(Object.freeze({
1069
- kind: "failed",
1070
- reason: classifyGitProcessError(error, stderr)
1071
- }));
1072
- return;
1073
- }
1074
- resolve(Object.freeze({
1075
- kind: "completed",
1076
- stdout: Uint8Array.from(stdout),
1077
- stderr: Uint8Array.from(stderr)
1078
- }));
1079
- });
1080
- });
931
+ return result.stderr.byteLength === 0 ? null : "output-invalid";
932
+ };
1081
933
  //#endregion
1082
- //#region src/git-process/streaming-executor.ts
1083
- /** Concatenates the bounded stderr chunks retained for classification. */
1084
- var concatenateChunks = (chunks, byteLength) => Uint8Array.from(Buffer.concat(chunks, byteLength));
934
+ //#region src/git-command/run-git-command.ts
1085
935
  /**
1086
- * Executes Git directly while consuming bounded stdout incrementally.
1087
- * @param options The trusted arguments, optional stdin and signal, consumer, environment, and limits.
1088
- * @returns A promise that resolves to a normalized streamed process result.
936
+ * Runs one read-only Git command through jg-git-commands, bounded by the caller's combined output
937
+ * limit and the CLI's timeout, and refuses any stderr. A failure names the subcommand.
938
+ * @param args The command's trusted arguments, its subcommand first.
939
+ * @param options The working directory, output limit, stdin, and cancellation.
940
+ * @returns A promise resolving to the command's stdout, or why it failed.
1089
941
  */
1090
- var executeGitStreamingProcess = async (options) => new Promise((resolve, reject) => {
1091
- if (options.signal?.aborted) {
1092
- resolve(Object.freeze({
1093
- kind: "failed",
1094
- reason: "aborted"
1095
- }));
1096
- return;
1097
- }
1098
- const stdin = options.stdin === void 0 ? null : Uint8Array.from(options.stdin);
1099
- const stderrChunks = [];
1100
- let failureReason = null;
1101
- let isSettled = false;
1102
- let stderrBytes = 0;
1103
- let stdoutBytes = 0;
1104
- const childProcess = spawn("git", [...GIT_PROCESS_GLOBAL_ARGUMENTS, ...options.arguments], {
1105
- env: createGitProcessEnvironment(options.environment ?? process$1.env),
1106
- shell: false,
1107
- ...options.signal === void 0 ? {} : { signal: options.signal },
1108
- stdio: [
1109
- stdin === null ? "ignore" : "pipe",
1110
- "pipe",
1111
- "pipe"
1112
- ],
1113
- windowsHide: true
1114
- });
1115
- const { stderr, stdout } = childProcess;
1116
- if (stderr === null || stdout === null) {
1117
- childProcess.on("error", () => void 0);
1118
- childProcess.kill();
1119
- resolve(Object.freeze({
1120
- kind: "failed",
1121
- reason: "command-failed"
1122
- }));
1123
- return;
1124
- }
1125
- stdout.on("data", (chunk) => {
1126
- if (failureReason !== null || isSettled) return;
1127
- if (stdoutBytes + chunk.byteLength > options.maxStdoutBytes) {
1128
- failureReason = "stdout-limit-exceeded";
1129
- childProcess.kill();
1130
- return;
1131
- }
1132
- stdoutBytes += chunk.byteLength;
1133
- try {
1134
- options.consumeStdout(Uint8Array.from(chunk));
1135
- } catch (error) {
1136
- isSettled = true;
1137
- childProcess.kill();
1138
- reject(error instanceof Error ? error : new Error("The Git stdout consumer failed.", { cause: error }));
1139
- }
1140
- });
1141
- stderr.on("data", (chunk) => {
1142
- if (failureReason !== null || isSettled) return;
1143
- if (stderrBytes + chunk.byteLength > options.maxStderrBytes) {
1144
- failureReason = "stderr-limit-exceeded";
1145
- childProcess.kill();
1146
- return;
1147
- }
1148
- stderrBytes += chunk.byteLength;
1149
- stderrChunks.push(chunk);
1150
- });
1151
- childProcess.on("error", (error) => {
1152
- if (failureReason !== null || isSettled) return;
1153
- isSettled = true;
1154
- resolve(Object.freeze({
1155
- kind: "failed",
1156
- reason: options.signal?.aborted ? "aborted" : classifyGitProcessError(error, concatenateChunks(stderrChunks, stderrBytes))
1157
- }));
1158
- });
1159
- childProcess.on("close", (exitCode) => {
1160
- if (isSettled) return;
1161
- isSettled = true;
1162
- if (failureReason !== null) {
1163
- resolve(Object.freeze({
1164
- kind: "failed",
1165
- reason: failureReason
1166
- }));
1167
- return;
1168
- }
1169
- if (options.signal?.aborted) {
1170
- resolve(Object.freeze({
1171
- kind: "failed",
1172
- reason: "aborted"
1173
- }));
1174
- return;
1175
- }
1176
- const stderr = concatenateChunks(stderrChunks, stderrBytes);
1177
- if (exitCode !== 0) {
1178
- resolve(Object.freeze({
1179
- kind: "failed",
1180
- reason: classifyGitProcessError(null, stderr)
1181
- }));
1182
- return;
1183
- }
1184
- resolve(Object.freeze({
1185
- kind: "completed",
1186
- stderr,
1187
- stdoutBytes
1188
- }));
1189
- });
1190
- if (stdin !== null) {
1191
- if (childProcess.stdin === null) {
1192
- failureReason = "command-failed";
1193
- childProcess.kill();
1194
- return;
1195
- }
1196
- childProcess.stdin.on("error", () => {
1197
- if (failureReason !== null || isSettled) return;
1198
- failureReason = "command-failed";
1199
- childProcess.kill();
1200
- });
1201
- try {
1202
- childProcess.stdin.end(stdin);
1203
- } catch {
1204
- failureReason = "command-failed";
1205
- childProcess.kill();
1206
- }
1207
- }
1208
- });
942
+ var runGitCommand = async (args, { cwd, input, maxOutputBytes, signal }) => {
943
+ const subcommand = args[0];
944
+ const execution = await readGit(() => runGit(args, {
945
+ cwd,
946
+ encoding: "buffer",
947
+ maxOutputBytes,
948
+ timeoutSeconds: 300,
949
+ ...input === void 0 ? {} : { input },
950
+ ...signal === void 0 ? {} : { signal }
951
+ }), signal, subcommand);
952
+ if (execution.kind === "failed") return execution;
953
+ const reason = checkGitResult(execution.value, subcommand ?? "");
954
+ return reason === null ? Object.freeze({
955
+ kind: "completed",
956
+ value: execution.value.stdout
957
+ }) : createGitFailure(reason, subcommand);
958
+ };
1209
959
  //#endregion
1210
960
  //#region src/git-version/constants.ts
1211
961
  var MINIMUM_GIT_VERSION_COMPONENTS = Object.freeze({
1212
962
  major: 2,
1213
- minor: 30,
963
+ minor: 32,
1214
964
  patch: 0
1215
965
  });
1216
966
  var MINIMUM_GIT_VERSION = `${MINIMUM_GIT_VERSION_COMPONENTS.major}.${MINIMUM_GIT_VERSION_COMPONENTS.minor}.${MINIMUM_GIT_VERSION_COMPONENTS.patch}`;
1217
967
  var MAX_GIT_VERSION_OUTPUT_BYTES = 4096;
1218
968
  //#endregion
1219
- //#region src/git-version/parser.ts
1220
- var GIT_VERSION_PATTERN = /^git version (0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:[.-][0-9A-Za-z]+)*(?: \([0-9A-Za-z](?:[0-9A-Za-z ._+/-]*[0-9A-Za-z])?\))?$/;
1221
- var UTF8_DECODER = new TextDecoder$1("utf-8", {
1222
- fatal: true,
1223
- ignoreBOM: true
1224
- });
1225
- /**
1226
- * Decodes one terminated Git version line as strict UTF-8.
1227
- * @param output The bounded stdout bytes from `git --version`.
1228
- * @returns The line without its terminator, or null when invalid.
1229
- */
1230
- var decodeGitVersionLine = (output) => {
1231
- let decodedOutput;
1232
- try {
1233
- decodedOutput = UTF8_DECODER.decode(output);
1234
- } catch {
1235
- return null;
1236
- }
1237
- if (decodedOutput.startsWith("")) return null;
1238
- if (decodedOutput.endsWith("\r\n")) return decodedOutput.slice(0, -2);
1239
- if (decodedOutput.endsWith("\n")) return decodedOutput.slice(0, -1);
1240
- return null;
1241
- };
1242
- /**
1243
- * Parses a strict `git --version` response without accepting arbitrary prose.
1244
- * @param output The bounded stdout bytes from Git.
1245
- * @returns The frozen numeric version, or null when the output is invalid.
1246
- */
1247
- var parseGitVersionOutput = (output) => {
1248
- const versionLine = decodeGitVersionLine(output);
1249
- if (versionLine === null || versionLine.includes("\r") || versionLine.includes("\n")) return null;
1250
- const match = GIT_VERSION_PATTERN.exec(versionLine);
1251
- if (match === null) return null;
1252
- const majorText = match[1];
1253
- const minorText = match[2];
1254
- const patchText = match[3];
1255
- if (majorText === void 0 || minorText === void 0 || patchText === void 0) return null;
1256
- const major = Number(majorText);
1257
- const minor = Number(minorText);
1258
- const patch = Number(patchText);
1259
- if (![
1260
- major,
1261
- minor,
1262
- patch
1263
- ].every(Number.isSafeInteger)) return null;
1264
- return Object.freeze({
1265
- major,
1266
- minor,
1267
- patch
1268
- });
1269
- };
1270
- //#endregion
1271
969
  //#region src/git-version/preflight.ts
1272
970
  /**
1273
- * Maps process failures to stable safe CLI errors.
1274
- * @param reason The normalized subprocess failure reason.
971
+ * Maps Git failures to stable safe CLI errors.
972
+ * @param reason The normalized Git failure reason.
1275
973
  * @returns The public Git error code.
1276
974
  */
1277
- var mapGitProcessFailure = (reason) => {
975
+ var mapGitFailure = (reason) => {
1278
976
  switch (reason) {
1279
977
  case "aborted": return "GIT_OPERATION_ABORTED";
1280
978
  case "not-found": return "GIT_NOT_FOUND";
1281
- case "repository-not-found": return "GIT_COMMAND_FAILED";
1282
979
  case "access-denied": return "GIT_ACCESS_DENIED";
1283
- case "output-limit-exceeded": return "GIT_VERSION_INVALID";
980
+ case "output-limit-exceeded":
981
+ case "output-invalid": return "GIT_VERSION_INVALID";
982
+ case "repository-not-found":
1284
983
  case "command-failed": return "GIT_COMMAND_FAILED";
1285
984
  }
1286
985
  };
@@ -1295,36 +994,27 @@ var isGitVersionSupported = (version) => {
1295
994
  return version.patch >= MINIMUM_GIT_VERSION_COMPONENTS.patch;
1296
995
  };
1297
996
  /**
1298
- * Creates a Git prerequisite check around an injectable process boundary.
1299
- * @param processExecutor The normalized Git subprocess executor.
997
+ * Creates a Git prerequisite check around an injectable typed version read.
998
+ * @param readVersion The installed Git version read.
1300
999
  * @returns A preflight that validates the installed Git version.
1301
1000
  */
1302
- var createGitVersionPreflight = (processExecutor = executeGitProcess) => async (signal) => {
1303
- const processResult = await processExecutor({
1304
- arguments: ["--version"],
1305
- maxBufferBytes: MAX_GIT_VERSION_OUTPUT_BYTES,
1001
+ var createGitVersionPreflight = (readVersion = readGitVersion) => async (directory, signal) => {
1002
+ const versionResult = await readGit(() => readVersion(directory, {
1003
+ maxOutputBytes: MAX_GIT_VERSION_OUTPUT_BYTES,
1004
+ timeoutSeconds: 300,
1306
1005
  ...signal === void 0 ? {} : { signal }
1307
- });
1308
- if (processResult.kind === "failed") return Object.freeze({
1309
- errorCode: mapGitProcessFailure(processResult.reason),
1310
- kind: "failed"
1311
- });
1312
- if (processResult.stderr.byteLength > 0) return Object.freeze({
1313
- errorCode: "GIT_VERSION_INVALID",
1314
- kind: "failed"
1315
- });
1316
- const version = parseGitVersionOutput(processResult.stdout);
1317
- if (version === null) return Object.freeze({
1318
- errorCode: "GIT_VERSION_INVALID",
1006
+ }), signal);
1007
+ if (versionResult.kind === "failed") return Object.freeze({
1008
+ errorCode: mapGitFailure(versionResult.reason),
1319
1009
  kind: "failed"
1320
1010
  });
1321
- if (!isGitVersionSupported(version)) return Object.freeze({
1011
+ if (!isGitVersionSupported(versionResult.value)) return Object.freeze({
1322
1012
  errorCode: "GIT_VERSION_UNSUPPORTED",
1323
1013
  kind: "failed"
1324
1014
  });
1325
1015
  return Object.freeze({
1326
1016
  kind: "supported",
1327
- version
1017
+ version: Object.freeze({ ...versionResult.value })
1328
1018
  });
1329
1019
  };
1330
1020
  //#endregion
@@ -2740,9 +2430,9 @@ var MOLDEA_CLI_FOUNDATIONAL_PACKAGE_NAMES = Object.freeze([
2740
2430
  "@moldea.ai/repository-fs"
2741
2431
  ]);
2742
2432
  var MOLDEA_CLI_FIRST_CLASS_PACKAGE_RANGES = Object.freeze({
2743
- "@moldea.ai/core": "^8.0.0",
2744
- "@moldea.ai/repository": "^3.0.0",
2745
- "@moldea.ai/repository-fs": "^3.0.0"
2433
+ "@moldea.ai/core": "^9.0.0",
2434
+ "@moldea.ai/repository": "^4.0.0",
2435
+ "@moldea.ai/repository-fs": "^4.0.0"
2746
2436
  });
2747
2437
  //#endregion
2748
2438
  //#region src/composition/validations.ts
@@ -2774,19 +2464,6 @@ var isMoldeaCliCompositionStateValid = (input) => {
2774
2464
  //#endregion
2775
2465
  //#region src/composition/transformers.ts
2776
2466
  var compareIdentifiers = (left, right) => left < right ? -1 : left > right ? 1 : 0;
2777
- /** Recursively freezes a composition result without retaining mutable input ownership. */
2778
- var freezeCompositionValue = (value) => {
2779
- const pendingValues = [value];
2780
- const visitedValues = /* @__PURE__ */ new Set();
2781
- while (pendingValues.length > 0) {
2782
- const currentValue = pendingValues.pop();
2783
- if (currentValue === void 0 || visitedValues.has(currentValue)) continue;
2784
- visitedValues.add(currentValue);
2785
- for (const nestedValue of Object.values(currentValue)) if (typeof nestedValue === "object" && nestedValue !== null) pendingValues.push(nestedValue);
2786
- Object.freeze(currentValue);
2787
- }
2788
- return value;
2789
- };
2790
2467
  /**
2791
2468
  * Creates the compact immutable composition result from validated installed state.
2792
2469
  * @param input The already validated installed and executable composition.
@@ -2797,7 +2474,7 @@ var createMoldeaCliCompositionResult = (input) => {
2797
2474
  name,
2798
2475
  version
2799
2476
  })).sort((left, right) => compareIdentifiers(left.name, right.name));
2800
- return freezeCompositionValue({
2477
+ return deepFreeze({
2801
2478
  minimumGitVersion: input.minimumGitVersion,
2802
2479
  packages,
2803
2480
  repositoryFormatVersions: [...input.coreSupportedRepositoryFormatVersions].sort((left, right) => left - right),
@@ -2835,6 +2512,6 @@ var resolveInstalledMoldeaCliComposition = (input) => resolveMoldeaCliCompositio
2835
2512
  packageMetadata: input.packageMetadata
2836
2513
  });
2837
2514
  //#endregion
2838
- export { hasOnlyUnicodeScalarValues as A, formatMoldeaCliJsonError as C, createMoldeaCliOwnedError as D, formatMoldeaCliJsonValidateResult as E, encodeMoldeaCliCursor as F, MoldeaCliOutputPageException as I, MOLDEA_CLI_COMMANDS as L, createMoldeaCliOutputPage as M, calculateMoldeaCliJsonDigest as N, MOLDEA_CLI_GIT_WORKING_TREE_SOURCE as O, decodeMoldeaCliCursor as P, formatMoldeaCliJsonContentResult as S, formatMoldeaCliJsonScopeResult as T, formatMoldeaCliHumanError as _, require_semver as a, formatMoldeaCliHumanValidateResult as b, executeGitStreamingProcess as c, createMoldeaCliDiagnosticRecord as d, createMoldeaCliInspectProjection as f, formatMoldeaCliHumanContentResult as g, formatMoldeaCliHumanCompositionResult as h, isMoldeaCliCompositionStateValid as i, isRepositoryDirectoryInputValid as j, parseMoldeaCliArguments as k, executeGitProcess as l, formatMoldeaCliHelp as m, resolveMoldeaCliComposition as n, MoldeaCliCompositionException as o, createMoldeaCliValidateProjection as p, createMoldeaCliCompositionResult as r, createGitVersionPreflight as s, resolveInstalledMoldeaCliComposition as t, MAX_GIT_PROCESS_DIAGNOSTIC_BYTES as u, formatMoldeaCliHumanInspectResult as v, formatMoldeaCliJsonInspectResult as w, formatMoldeaCliJsonCompositionResult as x, formatMoldeaCliHumanScopeResult as y };
2515
+ export { createMoldeaCliOutputPage as A, formatMoldeaCliJsonInspectResult as C, MOLDEA_CLI_GIT_WORKING_TREE_SOURCE as D, createMoldeaCliOwnedError as E, MOLDEA_CLI_COMMANDS as F, decodeMoldeaCliCursor as M, encodeMoldeaCliCursor as N, parseMoldeaCliArguments as O, MoldeaCliOutputPageException as P, formatMoldeaCliJsonError as S, formatMoldeaCliJsonValidateResult as T, formatMoldeaCliHumanInspectResult as _, require_semver as a, formatMoldeaCliJsonCompositionResult as b, runGitCommand as c, createMoldeaCliInspectProjection as d, createMoldeaCliValidateProjection as f, formatMoldeaCliHumanError as g, formatMoldeaCliHumanContentResult as h, isMoldeaCliCompositionStateValid as i, calculateMoldeaCliJsonDigest as j, isRepositoryDirectoryInputValid as k, readGit as l, formatMoldeaCliHumanCompositionResult as m, resolveMoldeaCliComposition as n, MoldeaCliCompositionException as o, formatMoldeaCliHelp as p, createMoldeaCliCompositionResult as r, createGitVersionPreflight as s, resolveInstalledMoldeaCliComposition as t, createMoldeaCliDiagnosticRecord as u, formatMoldeaCliHumanScopeResult as v, formatMoldeaCliJsonScopeResult as w, formatMoldeaCliJsonContentResult as x, formatMoldeaCliHumanValidateResult as y };
2839
2516
 
2840
- //# sourceMappingURL=composition-DX66KnuP.js.map
2517
+ //# sourceMappingURL=composition-C9TNzN2e.js.map