@fulmenhq/tsfulmen 0.2.10 → 0.3.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +1 -1
  3. package/dist/appidentity/index.js +156 -4150
  4. package/dist/appidentity/index.js.map +1 -1
  5. package/dist/bin/prometheus-cli.d.ts +1 -0
  6. package/dist/bin/prometheus-cli.js +9331 -0
  7. package/dist/bin/prometheus-cli.js.map +1 -0
  8. package/dist/bin/schema-cli.d.ts +1 -0
  9. package/dist/bin/schema-cli.js +6104 -0
  10. package/dist/bin/schema-cli.js.map +1 -0
  11. package/dist/bin/signals-cli.d.ts +1 -0
  12. package/dist/bin/signals-cli.js +2104 -0
  13. package/dist/bin/signals-cli.js.map +1 -0
  14. package/dist/config/index.js +29 -4915
  15. package/dist/config/index.js.map +1 -1
  16. package/dist/crucible/index.js +120 -5336
  17. package/dist/crucible/index.js.map +1 -1
  18. package/dist/errors/index.js +52 -4434
  19. package/dist/errors/index.js.map +1 -1
  20. package/dist/foundry/index.js +197 -1874
  21. package/dist/foundry/index.js.map +1 -1
  22. package/dist/fulpack/index.js +43 -31
  23. package/dist/fulpack/index.js.map +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +204 -4185
  26. package/dist/index.js.map +1 -1
  27. package/dist/pathfinder/index.js +47 -4378
  28. package/dist/pathfinder/index.js.map +1 -1
  29. package/dist/reports/license-inventory.csv +17 -17
  30. package/dist/schema/index.js +0 -4
  31. package/dist/schema/index.js.map +1 -1
  32. package/dist/signals/index.js +231 -3570
  33. package/dist/signals/index.js.map +1 -1
  34. package/dist/telemetry/http/index.js +94 -5280
  35. package/dist/telemetry/http/index.js.map +1 -1
  36. package/dist/telemetry/index.js +70 -4786
  37. package/dist/telemetry/index.js.map +1 -1
  38. package/dist/telemetry/prometheus/index.js +461 -4450
  39. package/dist/telemetry/prometheus/index.js.map +1 -1
  40. package/package.json +13 -8
@@ -1,29 +1,20 @@
1
- import { readFile, access, mkdir, writeFile } from 'fs/promises';
2
- import { dirname, extname, join, relative } from 'path';
3
- import { parse, stringify } from 'yaml';
1
+ import { readFile, access } from 'fs/promises';
2
+ import { join, dirname, relative, extname } from 'path';
3
+ import { parse } from 'yaml';
4
4
  import addFormats from 'ajv-formats';
5
- import { spawn } from 'child_process';
5
+ import 'child_process';
6
6
  import { fileURLToPath } from 'url';
7
7
  import glob from 'fast-glob';
8
8
  import Ajv from 'ajv';
9
9
  import Ajv2019 from 'ajv/dist/2019.js';
10
10
  import Ajv2020 from 'ajv/dist/2020.js';
11
11
  import AjvDraft04 from 'ajv-draft-04';
12
- import { Readable } from 'stream';
13
- import picomatch from 'picomatch';
14
- import { suggest as suggest$1, substringSimilarity, score as score$1, normalize as normalize$1, jaro_winkler, damerau_levenshtein, osa_distance, levenshtein } from '@3leaps/string-metrics-wasm';
15
- import 'crypto';
16
- import { Command } from 'commander';
12
+ import 'commander';
17
13
 
18
- var __defProp = Object.defineProperty;
19
14
  var __getOwnPropNames = Object.getOwnPropertyNames;
20
15
  var __esm = (fn, res) => function __init() {
21
16
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
22
17
  };
23
- var __export = (target, all) => {
24
- for (var name in all)
25
- __defProp(target, name, { get: all[name], enumerable: true });
26
- };
27
18
 
28
19
  // src/telemetry/counter.ts
29
20
  var Counter;
@@ -824,23 +815,9 @@ var init_ajv_formats = __esm({
824
815
  });
825
816
 
826
817
  // src/schema/errors.ts
827
- var errors_exports = {};
828
- __export(errors_exports, {
829
- ExportErrorReason: () => ExportErrorReason,
830
- SchemaExportError: () => SchemaExportError,
831
- SchemaValidationError: () => SchemaValidationError
832
- });
833
- var ExportErrorReason, SchemaValidationError, SchemaExportError;
818
+ var SchemaValidationError;
834
819
  var init_errors = __esm({
835
820
  "src/schema/errors.ts"() {
836
- ExportErrorReason = /* @__PURE__ */ ((ExportErrorReason2) => {
837
- ExportErrorReason2["FILE_EXISTS"] = "FILE_EXISTS";
838
- ExportErrorReason2["WRITE_FAILED"] = "WRITE_FAILED";
839
- ExportErrorReason2["INVALID_FORMAT"] = "INVALID_FORMAT";
840
- ExportErrorReason2["PROVENANCE_FAILED"] = "PROVENANCE_FAILED";
841
- ExportErrorReason2["UNKNOWN"] = "UNKNOWN";
842
- return ExportErrorReason2;
843
- })(ExportErrorReason || {});
844
821
  SchemaValidationError = class _SchemaValidationError extends Error {
845
822
  constructor(message, schemaId, diagnostics = [], source, cause) {
846
823
  super(message);
@@ -980,370 +957,36 @@ Source: ${this.source.type}`;
980
957
  };
981
958
  }
982
959
  };
983
- SchemaExportError = class _SchemaExportError extends SchemaValidationError {
984
- constructor(message, reason, schemaId, outPath, cause) {
985
- super(message, schemaId, [], void 0, cause);
986
- this.reason = reason;
987
- this.schemaId = schemaId;
988
- this.outPath = outPath;
989
- this.cause = cause;
990
- this.name = "SchemaExportError";
991
- if (Error.captureStackTrace) {
992
- Error.captureStackTrace(this, _SchemaExportError);
993
- }
994
- }
995
- /**
996
- * Create error for file already exists
997
- */
998
- static fileExists(outPath) {
999
- return new _SchemaExportError(
1000
- `Output file already exists: ${outPath}. Use overwrite option to replace.`,
1001
- "FILE_EXISTS" /* FILE_EXISTS */,
1002
- void 0,
1003
- outPath
1004
- );
1005
- }
1006
- /**
1007
- * Create error for invalid export format
1008
- */
1009
- static invalidFormat(format, outPath) {
1010
- return new _SchemaExportError(
1011
- `Invalid export format: ${format}. Must be 'json' or 'yaml'.`,
1012
- "INVALID_FORMAT" /* INVALID_FORMAT */,
1013
- void 0,
1014
- outPath
1015
- );
1016
- }
1017
- /**
1018
- * Create error for write failure
1019
- */
1020
- static writeFailed(outPath, error) {
1021
- return new _SchemaExportError(
1022
- `Failed to write schema to ${outPath}: ${error.message}`,
1023
- "WRITE_FAILED" /* WRITE_FAILED */,
1024
- void 0,
1025
- outPath,
1026
- error
1027
- );
1028
- }
1029
- /**
1030
- * Create error for provenance extraction failure
1031
- */
1032
- static provenanceFailed(details, error) {
1033
- return new _SchemaExportError(
1034
- `Failed to extract provenance metadata: ${details}`,
1035
- "PROVENANCE_FAILED" /* PROVENANCE_FAILED */,
1036
- void 0,
1037
- void 0,
1038
- error
1039
- );
1040
- }
1041
- };
1042
960
  }
1043
961
  });
1044
962
 
1045
963
  // src/schema/utils.ts
1046
- function formatDiagnostics(diagnostics) {
1047
- if (diagnostics.length === 0) {
1048
- return "No validation issues found.";
1049
- }
1050
- const lines = [];
1051
- const errors = diagnostics.filter((d) => d.severity === "ERROR");
1052
- const warnings = diagnostics.filter((d) => d.severity === "WARN");
1053
- if (errors.length > 0) {
1054
- lines.push(`\u274C ${errors.length} error(s) found:`);
1055
- errors.forEach((diag, index) => {
1056
- lines.push(` ${index + 1}. ${diag.message}`);
1057
- if (diag.pointer) {
1058
- lines.push(` at ${diag.pointer}`);
1059
- }
1060
- if (diag.keyword) {
1061
- lines.push(` keyword: ${diag.keyword}`);
1062
- }
1063
- });
1064
- }
1065
- if (warnings.length > 0) {
1066
- lines.push("");
1067
- lines.push(`\u26A0\uFE0F ${warnings.length} warning(s) found:`);
1068
- warnings.forEach((diag, index) => {
1069
- lines.push(` ${index + 1}. ${diag.message}`);
1070
- if (diag.pointer) {
1071
- lines.push(` at ${diag.pointer}`);
1072
- }
1073
- });
1074
- }
1075
- return lines.join("\n");
1076
- }
1077
- function createDiagnostic(pointer, message, keyword, severity = "ERROR", source = "ajv", data) {
1078
- return {
1079
- pointer,
1080
- message,
1081
- keyword,
1082
- severity,
1083
- source,
1084
- data
1085
- };
1086
- }
1087
964
  var init_utils = __esm({
1088
965
  "src/schema/utils.ts"() {
1089
966
  init_errors();
1090
967
  }
1091
968
  });
1092
- async function detectGoneat(customPath) {
1093
- if (customPath) {
1094
- try {
1095
- await access(customPath);
1096
- return customPath;
1097
- } catch {
1098
- return null;
1099
- }
1100
- }
1101
- if (process.env.GONEAT_PATH) {
1102
- try {
1103
- await access(process.env.GONEAT_PATH);
1104
- return process.env.GONEAT_PATH;
1105
- } catch {
1106
- }
1107
- }
1108
- try {
1109
- await access("./bin/goneat");
1110
- return "./bin/goneat";
1111
- } catch {
1112
- }
1113
- return "goneat";
1114
- }
1115
- async function isGoneatAvailable(goneatPath) {
1116
- let pathToTest;
1117
- if (goneatPath) {
1118
- pathToTest = goneatPath;
1119
- } else {
1120
- pathToTest = await detectGoneat();
1121
- if (!pathToTest) return false;
1122
- }
1123
- return new Promise((resolve) => {
1124
- const proc = spawn(pathToTest, ["version"], { stdio: "ignore" });
1125
- const timeout = setTimeout(() => {
1126
- proc.kill();
1127
- resolve(false);
1128
- }, 5e3);
1129
- proc.on("close", (code) => {
1130
- clearTimeout(timeout);
1131
- resolve(code === 0);
1132
- });
1133
- proc.on("error", () => {
1134
- clearTimeout(timeout);
1135
- resolve(false);
1136
- });
1137
- });
1138
- }
1139
- async function runGoneatValidation(schemaPath, dataPath, goneatPath) {
1140
- const detected = await detectGoneat(goneatPath);
1141
- if (!detected) {
1142
- return {
1143
- valid: false,
1144
- diagnostics: [
1145
- createDiagnostic(
1146
- "",
1147
- "goneat binary not found. Install goneat or specify path with --goneat-path",
1148
- "goneat-unavailable",
1149
- "ERROR",
1150
- "goneat"
1151
- )
1152
- ],
1153
- source: "goneat"
1154
- };
1155
- }
1156
- if (!await isGoneatAvailable(detected)) {
1157
- return {
1158
- valid: false,
1159
- diagnostics: [
1160
- createDiagnostic(
1161
- "",
1162
- `goneat binary found at '${detected}' but not executable or version check failed`,
1163
- "goneat-not-executable",
1164
- "ERROR",
1165
- "goneat"
1166
- )
1167
- ],
1168
- source: "goneat"
1169
- };
1170
- }
1171
- return new Promise((resolve) => {
1172
- const args = [
1173
- "schema",
1174
- "validate",
1175
- "--schema",
1176
- schemaPath,
1177
- "--data",
1178
- dataPath,
1179
- "--format",
1180
- "json"
1181
- ];
1182
- const proc = spawn(detected, args);
1183
- let stdout = "";
1184
- let stderr = "";
1185
- proc.stdout.on("data", (data) => {
1186
- stdout += data.toString();
1187
- });
1188
- proc.stderr.on("data", (data) => {
1189
- stderr += data.toString();
1190
- });
1191
- proc.on("close", (code) => {
1192
- let output;
1193
- try {
1194
- output = JSON.parse(stdout);
1195
- } catch {
1196
- resolve({
1197
- valid: false,
1198
- diagnostics: [
1199
- createDiagnostic(
1200
- "",
1201
- `goneat validation failed: ${stderr || "unknown error"}`,
1202
- "goneat-error",
1203
- "ERROR",
1204
- "goneat"
1205
- )
1206
- ],
1207
- source: "goneat"
1208
- });
1209
- return;
1210
- }
1211
- const diagnostics = output.errors?.map(
1212
- (error) => createDiagnostic(
1213
- error.path || "",
1214
- error.message,
1215
- error.keyword || "validation",
1216
- "ERROR",
1217
- "goneat"
1218
- )
1219
- ) || [];
1220
- resolve({
1221
- valid: code === 0 && output.valid,
1222
- diagnostics,
1223
- source: "goneat"
1224
- });
1225
- });
1226
- proc.on("error", (error) => {
1227
- resolve({
1228
- valid: false,
1229
- diagnostics: [
1230
- createDiagnostic(
1231
- "",
1232
- `Failed to execute goneat: ${error.message}`,
1233
- "goneat-spawn-error",
1234
- "ERROR",
1235
- "goneat"
1236
- )
1237
- ],
1238
- source: "goneat"
1239
- });
1240
- });
1241
- });
1242
- }
1243
969
  var init_goneat_bridge = __esm({
1244
970
  "src/schema/goneat-bridge.ts"() {
1245
971
  init_utils();
1246
972
  }
1247
973
  });
1248
- function parseSchemaInput(input) {
1249
- if (!input) {
1250
- throw SchemaValidationError.parseFailed(
1251
- { type: "string", content: "" },
1252
- new Error("schema content is empty")
1253
- );
1254
- }
1255
- try {
1256
- if (typeof input === "string") {
1257
- try {
1258
- return JSON.parse(input);
1259
- } catch {
1260
- return parse(input);
1261
- }
1262
- }
1263
- if (Buffer.isBuffer(input)) {
1264
- const content = input.toString("utf-8");
1265
- try {
1266
- return JSON.parse(content);
1267
- } catch {
1268
- return parse(content);
1269
- }
1270
- }
1271
- return input;
1272
- } catch (error) {
1273
- throw SchemaValidationError.parseFailed(
1274
- {
1275
- type: typeof input === "string" ? "string" : "object",
1276
- content: typeof input === "string" ? input : JSON.stringify(input)
1277
- },
1278
- error
1279
- );
1280
- }
1281
- }
1282
- function sortObjectKeys(obj) {
1283
- if (obj === null || typeof obj !== "object") {
1284
- return obj;
1285
- }
1286
- if (Array.isArray(obj)) {
1287
- return obj.map(sortObjectKeys);
1288
- }
1289
- const sorted = {};
1290
- const keys = Object.keys(obj).sort();
1291
- for (const key of keys) {
1292
- sorted[key] = sortObjectKeys(obj[key]);
1293
- }
1294
- return sorted;
1295
- }
1296
- function normalizeSchema(input, options = {}) {
1297
- try {
1298
- const parsed = parseSchemaInput(input);
1299
- const sorted = sortObjectKeys(parsed);
1300
- if (options.compact) {
1301
- return JSON.stringify(sorted);
1302
- }
1303
- return JSON.stringify(sorted, null, 2);
1304
- } catch (error) {
1305
- if (error instanceof SchemaValidationError) {
1306
- throw error;
1307
- }
1308
- throw SchemaValidationError.parseFailed(
1309
- {
1310
- type: typeof input === "string" ? "string" : "object",
1311
- content: typeof input === "string" ? input : JSON.stringify(input)
1312
- },
1313
- error
1314
- );
1315
- }
1316
- }
1317
- function compareSchemas(schemaA, schemaB, options = {}) {
1318
- const normalizedA = normalizeSchema(schemaA, options);
1319
- const normalizedB = normalizeSchema(schemaB, options);
1320
- return {
1321
- equal: normalizedA === normalizedB,
1322
- normalizedA,
1323
- normalizedB
1324
- };
1325
- }
1326
974
  var init_normalizer = __esm({
1327
975
  "src/schema/normalizer.ts"() {
1328
976
  init_errors();
1329
977
  }
1330
978
  });
1331
979
  function optionsChanged(newOptions) {
1332
- if (!newOptions && !globalRegistryOptions) return false;
1333
- if (!newOptions || !globalRegistryOptions) return true;
1334
- return newOptions.baseDir !== globalRegistryOptions.baseDir || JSON.stringify(newOptions.patterns) !== JSON.stringify(globalRegistryOptions.patterns) || newOptions.followSymlinks !== globalRegistryOptions.followSymlinks || newOptions.maxDepth !== globalRegistryOptions.maxDepth;
980
+ if (!globalRegistryOptions) return false;
981
+ return true;
1335
982
  }
1336
983
  function getSchemaRegistry(options) {
1337
- if (!globalRegistry || optionsChanged(options)) {
984
+ if (!globalRegistry || optionsChanged()) {
1338
985
  globalRegistry = new SchemaRegistry(options);
1339
986
  globalRegistryOptions = options;
1340
987
  }
1341
988
  return globalRegistry;
1342
989
  }
1343
- async function listSchemas(prefix, options) {
1344
- const registry = getSchemaRegistry(options);
1345
- return registry.listSchemas(prefix);
1346
- }
1347
990
  var DEFAULT_PATTERNS, SchemaRegistry, globalRegistry, globalRegistryOptions;
1348
991
  var init_registry2 = __esm({
1349
992
  "src/schema/registry.ts"() {
@@ -1364,9 +1007,9 @@ var init_registry2 = __esm({
1364
1007
  * Get default schema directory using import.meta.url
1365
1008
  */
1366
1009
  getDefaultSchemaDir() {
1367
- const __filename3 = fileURLToPath(import.meta.url);
1368
- const __dirname4 = dirname(__filename3);
1369
- return join(__dirname4, "..", "..", "schemas", "crucible-ts");
1010
+ const __filename = fileURLToPath(import.meta.url);
1011
+ const __dirname2 = dirname(__filename);
1012
+ return join(__dirname2, "..", "..", "schemas", "crucible-ts");
1370
1013
  }
1371
1014
  /**
1372
1015
  * Build logical schema ID from file path
@@ -1526,25 +1169,11 @@ var init_registry2 = __esm({
1526
1169
  };
1527
1170
  }
1528
1171
  });
1529
-
1530
- // src/schema/validator.ts
1531
- var validator_exports = {};
1532
- __export(validator_exports, {
1533
- clearCache: () => clearCache,
1534
- compileSchema: () => compileSchema,
1535
- compileSchemaById: () => compileSchemaById,
1536
- getCacheSize: () => getCacheSize,
1537
- validateData: () => validateData,
1538
- validateDataBySchemaId: () => validateDataBySchemaId,
1539
- validateFile: () => validateFile,
1540
- validateFileBySchemaId: () => validateFileBySchemaId,
1541
- validateSchema: () => validateSchema
1542
- });
1543
1172
  async function loadMetaSchema(draft) {
1544
- const __filename3 = fileURLToPath(import.meta.url);
1545
- const __dirname4 = dirname(__filename3);
1173
+ const __filename = fileURLToPath(import.meta.url);
1174
+ const __dirname2 = dirname(__filename);
1546
1175
  const metaSchemaPath = join(
1547
- __dirname4,
1176
+ __dirname2,
1548
1177
  "..",
1549
1178
  "..",
1550
1179
  "schemas",
@@ -1560,9 +1189,9 @@ async function loadVocabularySchemas(draft) {
1560
1189
  if (draft !== "draft-2019-09" && draft !== "draft-2020-12") {
1561
1190
  return [];
1562
1191
  }
1563
- const __filename3 = fileURLToPath(import.meta.url);
1564
- const __dirname4 = dirname(__filename3);
1565
- const vocabDir = join(__dirname4, "..", "..", "schemas", "crucible-ts", "meta", draft, "meta");
1192
+ const __filename = fileURLToPath(import.meta.url);
1193
+ const __dirname2 = dirname(__filename);
1194
+ const vocabDir = join(__dirname2, "..", "..", "schemas", "crucible-ts", "meta", draft, "meta");
1566
1195
  const vocabFiles = draft === "draft-2020-12" ? [
1567
1196
  "core.json",
1568
1197
  "applicator.json",
@@ -1590,9 +1219,9 @@ async function loadVocabularySchemas(draft) {
1590
1219
  return schemas;
1591
1220
  }
1592
1221
  async function loadReferencedSchema(uri) {
1593
- const __filename3 = fileURLToPath(import.meta.url);
1594
- const __dirname4 = dirname(__filename3);
1595
- const repoRoot = join(__dirname4, "..", "..");
1222
+ const __filename = fileURLToPath(import.meta.url);
1223
+ const __dirname2 = dirname(__filename);
1224
+ const repoRoot = join(__dirname2, "..", "..");
1596
1225
  let resolvedPath;
1597
1226
  if (uri.startsWith("https://schemas.fulmenhq.dev/")) {
1598
1227
  let relativePath = uri.replace("https://schemas.fulmenhq.dev/", "");
@@ -1741,130 +1370,6 @@ async function compileSchema(schema, options = {}) {
1741
1370
  );
1742
1371
  }
1743
1372
  }
1744
- function validateData(data, validator) {
1745
- const valid = validator(data);
1746
- const result = {
1747
- valid,
1748
- diagnostics: [],
1749
- source: "ajv"
1750
- };
1751
- if (!valid && validator.errors) {
1752
- const errors = validator.errors;
1753
- if (Array.isArray(errors)) {
1754
- result.diagnostics = errors.map(
1755
- (error) => createDiagnostic(
1756
- error.instancePath || "",
1757
- error.message || "Validation failed",
1758
- error.keyword || "unknown",
1759
- "ERROR",
1760
- "ajv"
1761
- )
1762
- );
1763
- }
1764
- metrics.counter("schema_validation_errors").inc();
1765
- } else {
1766
- metrics.counter("schema_validations").inc();
1767
- }
1768
- return result;
1769
- }
1770
- async function validateFile(filePath, validator) {
1771
- try {
1772
- const content = await readFile(filePath, "utf-8");
1773
- let data;
1774
- try {
1775
- data = JSON.parse(content);
1776
- } catch {
1777
- data = parse(content);
1778
- }
1779
- return validateData(data, validator);
1780
- } catch (error) {
1781
- if (error instanceof SchemaValidationError) {
1782
- throw error;
1783
- }
1784
- throw SchemaValidationError.validationFailed(
1785
- filePath,
1786
- [
1787
- createDiagnostic(
1788
- "",
1789
- `Failed to read or parse file: ${error.message}`,
1790
- "file-read",
1791
- "ERROR",
1792
- "ajv"
1793
- )
1794
- ],
1795
- { type: "file", id: filePath }
1796
- );
1797
- }
1798
- }
1799
- async function validateSchema(schema) {
1800
- try {
1801
- let parsedSchema;
1802
- if (typeof schema === "string") {
1803
- try {
1804
- parsedSchema = JSON.parse(schema);
1805
- } catch {
1806
- parsedSchema = parse(schema);
1807
- }
1808
- } else if (Buffer.isBuffer(schema)) {
1809
- const content = schema.toString("utf-8");
1810
- try {
1811
- parsedSchema = JSON.parse(content);
1812
- } catch {
1813
- parsedSchema = parse(content);
1814
- }
1815
- } else {
1816
- parsedSchema = schema;
1817
- }
1818
- const dialect = detectDialect(parsedSchema);
1819
- const ajv = await getAjv(dialect);
1820
- const metaValid = ajv.validateSchema(parsedSchema);
1821
- if (!metaValid && ajv.errors) {
1822
- const diagnostics = ajv.errors.map(
1823
- (error) => createDiagnostic(
1824
- error.instancePath || "",
1825
- error.message || "Schema meta-validation failed",
1826
- error.keyword || "unknown",
1827
- "ERROR",
1828
- "ajv"
1829
- )
1830
- );
1831
- return { valid: false, diagnostics, source: "ajv" };
1832
- }
1833
- await compileSchema(parsedSchema);
1834
- return {
1835
- valid: true,
1836
- diagnostics: [],
1837
- source: "ajv"
1838
- };
1839
- } catch (error) {
1840
- if (error instanceof SchemaValidationError) {
1841
- return {
1842
- valid: false,
1843
- diagnostics: error.diagnostics,
1844
- source: "ajv"
1845
- };
1846
- }
1847
- return {
1848
- valid: false,
1849
- diagnostics: [
1850
- createDiagnostic(
1851
- "",
1852
- `Schema validation failed: ${error.message}`,
1853
- "schema-validation",
1854
- "ERROR",
1855
- "ajv"
1856
- )
1857
- ],
1858
- source: "ajv"
1859
- };
1860
- }
1861
- }
1862
- function clearCache() {
1863
- schemaCache.clear();
1864
- }
1865
- function getCacheSize() {
1866
- return schemaCache.size;
1867
- }
1868
1373
  async function compileSchemaById(schemaId, registryOptions) {
1869
1374
  try {
1870
1375
  const registry = getSchemaRegistry(registryOptions);
@@ -1883,24 +1388,6 @@ async function compileSchemaById(schemaId, registryOptions) {
1883
1388
  throw error;
1884
1389
  }
1885
1390
  }
1886
- async function validateDataBySchemaId(data, schemaId, registryOptions) {
1887
- try {
1888
- const validator = await compileSchemaById(schemaId, registryOptions);
1889
- return validateData(data, validator);
1890
- } catch (error) {
1891
- metrics.counter("schema_validation_errors").inc();
1892
- throw error;
1893
- }
1894
- }
1895
- async function validateFileBySchemaId(filePath, schemaId, registryOptions) {
1896
- try {
1897
- const validator = await compileSchemaById(schemaId, registryOptions);
1898
- return validateFile(filePath, validator);
1899
- } catch (error) {
1900
- metrics.counter("schema_validation_errors").inc();
1901
- throw error;
1902
- }
1903
- }
1904
1391
  var ajvInstances, metaschemaReady, schemaCache;
1905
1392
  var init_validator = __esm({
1906
1393
  "src/schema/validator.ts"() {
@@ -1914,174 +1401,15 @@ var init_validator = __esm({
1914
1401
  schemaCache = /* @__PURE__ */ new Map();
1915
1402
  }
1916
1403
  });
1917
-
1918
- // src/schema/export.ts
1919
- var export_exports = {};
1920
- __export(export_exports, {
1921
- exportSchema: () => exportSchema,
1922
- stripProvenance: () => stripProvenance
1923
- });
1924
- async function extractProvenanceMetadata(schemaId) {
1925
- try {
1926
- const __filename3 = fileURLToPath(import.meta.url);
1927
- const __dirname4 = dirname(__filename3);
1928
- const metadataPath = join(__dirname4, "..", "..", ".crucible", "metadata", "metadata.yaml");
1929
- const metadataContent = await readFile(metadataPath, "utf-8");
1930
- const metadata = parse(metadataContent);
1931
- const crucibleSource = metadata.sources?.[0];
1932
- const crucibleVersion = crucibleSource?.version || "unknown";
1933
- const revision = crucibleSource?.commit;
1934
- const pkgPath = join(__dirname4, "..", "..", "package.json");
1935
- const pkgContent = await readFile(pkgPath, "utf-8");
1936
- const pkg = JSON.parse(pkgContent);
1937
- return {
1938
- schema_id: schemaId,
1939
- crucible_version: crucibleVersion,
1940
- library_version: pkg.version,
1941
- revision,
1942
- exported_at: (/* @__PURE__ */ new Date()).toISOString(),
1943
- export_source: "tsfulmen"
1944
- };
1945
- } catch (error) {
1946
- throw SchemaExportError.provenanceFailed(error.message, error);
1947
- }
1948
- }
1949
- function embedProvenance(schemaContent, provenance, format) {
1950
- if (format === "json") {
1951
- const withProvenance = {
1952
- ...schemaContent,
1953
- $comment: {
1954
- ...typeof schemaContent.$comment === "object" ? schemaContent.$comment : {},
1955
- "x-crucible-source": provenance
1956
- }
1957
- };
1958
- return JSON.stringify(withProvenance, null, 2);
1959
- }
1960
- const yamlContent = stringify(schemaContent, {
1961
- indent: 2,
1962
- lineWidth: 0
1963
- });
1964
- const provenanceComment = [
1965
- "# x-crucible-source:",
1966
- `# schema_id: ${provenance.schema_id}`,
1967
- `# crucible_version: ${provenance.crucible_version}`,
1968
- `# library_version: ${provenance.library_version}`,
1969
- ...provenance.revision ? [`# revision: ${provenance.revision}`] : [],
1970
- `# exported_at: ${provenance.exported_at}`,
1971
- `# export_source: ${provenance.export_source}`,
1972
- ""
1973
- ].join("\n");
1974
- return provenanceComment + yamlContent;
1975
- }
1976
- function detectFormat(outPath, formatOption) {
1977
- if (formatOption && formatOption !== "auto") {
1978
- return formatOption;
1979
- }
1980
- const ext = extname(outPath).toLowerCase();
1981
- switch (ext) {
1982
- case ".json":
1983
- return "json";
1984
- case ".yaml":
1985
- case ".yml":
1986
- return "yaml";
1987
- default:
1988
- throw SchemaExportError.invalidFormat(ext, outPath);
1989
- }
1990
- }
1991
- async function exportSchema(options) {
1992
- const {
1993
- schemaId,
1994
- outPath,
1995
- includeProvenance = true,
1996
- validate = true,
1997
- overwrite = false,
1998
- format: formatOption,
1999
- baseDir
2000
- } = options;
2001
- const format = detectFormat(outPath, formatOption);
2002
- if (!overwrite) {
2003
- try {
2004
- await access(outPath);
2005
- throw SchemaExportError.fileExists(outPath);
2006
- } catch (error) {
2007
- if (error.code !== "ENOENT") {
2008
- throw error;
2009
- }
2010
- }
2011
- }
2012
- const registry = getSchemaRegistry({ baseDir });
2013
- const schema = await registry.getSchema(schemaId);
2014
- const schemaContent = await readFile(schema.path, "utf-8");
2015
- if (validate) {
2016
- const validationResult = await validateSchema(schemaContent);
2017
- if (!validationResult.valid) {
2018
- throw SchemaValidationError.validationFailed(schemaId, validationResult.diagnostics, {
2019
- type: "file",
2020
- id: schema.path
2021
- });
2022
- }
2023
- }
2024
- let schemaObject;
2025
- try {
2026
- schemaObject = JSON.parse(schemaContent);
2027
- } catch {
2028
- schemaObject = parse(schemaContent);
2029
- }
2030
- Object.freeze(schemaObject);
2031
- let provenance;
2032
- let outputContent;
2033
- if (includeProvenance) {
2034
- provenance = await extractProvenanceMetadata(schemaId);
2035
- outputContent = embedProvenance(schemaObject, provenance, format);
2036
- } else {
2037
- if (format === "json") {
2038
- outputContent = JSON.stringify(schemaObject, null, 2);
2039
- } else {
2040
- outputContent = stringify(schemaObject, { indent: 2, lineWidth: 0 });
2041
- }
2042
- }
2043
- await mkdir(dirname(outPath), { recursive: true });
2044
- try {
2045
- await writeFile(outPath, outputContent, "utf-8");
2046
- } catch (error) {
2047
- throw SchemaExportError.writeFailed(outPath, error);
2048
- }
2049
- return {
2050
- success: true,
2051
- schemaId,
2052
- outPath,
2053
- format,
2054
- includeProvenance,
2055
- provenance
2056
- };
2057
- }
2058
- function stripProvenance(content) {
2059
- try {
2060
- const parsed = JSON.parse(content);
2061
- if (parsed.$comment && typeof parsed.$comment === "object") {
2062
- const comment = { ...parsed.$comment };
2063
- delete comment["x-crucible-source"];
2064
- if (Object.keys(comment).length === 0) {
2065
- delete parsed.$comment;
2066
- } else {
2067
- parsed.$comment = comment;
2068
- }
2069
- }
2070
- return JSON.stringify(parsed, null, 2);
2071
- } catch {
2072
- const lines = content.split("\n");
2073
- const filtered = lines.filter((line) => {
2074
- const trimmed = line.trim();
2075
- return !(trimmed.startsWith("# x-crucible-source:") || trimmed.startsWith("# ") && /^#\s+(schema_id|crucible_version|library_version|revision|exported_at|export_source):/.test(
2076
- trimmed
2077
- ));
2078
- });
2079
- while (filtered.length > 0 && filtered[0]?.trim() === "") {
2080
- filtered.shift();
2081
- }
2082
- return filtered.join("\n");
1404
+ var init_cli = __esm({
1405
+ "src/schema/cli.ts"() {
1406
+ init_goneat_bridge();
1407
+ init_normalizer();
1408
+ init_registry2();
1409
+ init_utils();
1410
+ init_validator();
2083
1411
  }
2084
- }
1412
+ });
2085
1413
  var init_export = __esm({
2086
1414
  "src/schema/export.ts"() {
2087
1415
  init_errors();
@@ -2090,4096 +1418,52 @@ var init_export = __esm({
2090
1418
  }
2091
1419
  });
2092
1420
 
2093
- // src/foundry/errors.ts
2094
- var FoundryCatalogError;
2095
- var init_errors2 = __esm({
2096
- "src/foundry/errors.ts"() {
2097
- FoundryCatalogError = class _FoundryCatalogError extends Error {
2098
- constructor(message, catalog, cause) {
2099
- super(message);
2100
- this.catalog = catalog;
2101
- this.cause = cause;
2102
- this.name = "FoundryCatalogError";
2103
- if (Error.captureStackTrace) {
2104
- Error.captureStackTrace(this, _FoundryCatalogError);
2105
- }
2106
- }
2107
- static invalidSchema(catalog, details, cause) {
2108
- return new _FoundryCatalogError(
2109
- `Invalid schema in ${catalog} catalog: ${details}`,
2110
- catalog,
2111
- cause
2112
- );
2113
- }
2114
- static missingCatalog(catalog) {
2115
- return new _FoundryCatalogError(`Catalog ${catalog} not found or could not be loaded`, catalog);
2116
- }
2117
- static invalidPattern(patternId, details) {
2118
- return new _FoundryCatalogError(`Invalid pattern ${patternId}: ${details}`, "patterns");
2119
- }
2120
- static compilationError(patternId, details, cause) {
2121
- return new _FoundryCatalogError(
2122
- `Failed to compile pattern ${patternId}: ${details}`,
2123
- "patterns",
2124
- cause
2125
- );
2126
- }
2127
- };
1421
+ // src/schema/index.ts
1422
+ var init_schema = __esm({
1423
+ "src/schema/index.ts"() {
1424
+ init_ajv_formats();
1425
+ init_cli();
1426
+ init_errors();
1427
+ init_export();
1428
+ init_goneat_bridge();
1429
+ init_normalizer();
1430
+ init_registry2();
1431
+ init_utils();
1432
+ init_validator();
2128
1433
  }
2129
1434
  });
2130
- async function loadCatalog(filePath, catalogName, schemaId) {
2131
- try {
2132
- let content;
2133
- if (typeof Bun !== "undefined") {
2134
- try {
2135
- const file = Bun.file(filePath);
2136
- if (!await file.exists()) {
2137
- throw FoundryCatalogError.missingCatalog(catalogName);
2138
- }
2139
- content = await file.text();
2140
- } catch (error) {
2141
- if (error instanceof Error && error.message.includes("No such file")) {
2142
- throw FoundryCatalogError.missingCatalog(catalogName);
2143
- }
2144
- throw error;
2145
- }
2146
- } else {
2147
- try {
2148
- content = await readFile(filePath, "utf-8");
2149
- } catch (error) {
2150
- if (error.code === "ENOENT") {
2151
- throw FoundryCatalogError.missingCatalog(catalogName);
2152
- }
2153
- throw error;
2154
- }
2155
- }
2156
- const data = parse(content);
2157
- const result = await validateDataBySchemaId(data, schemaId);
2158
- if (!result.valid) {
2159
- const errorMessages = result.diagnostics.map((d) => `${d.pointer}: ${d.message}`).join("; ");
2160
- throw FoundryCatalogError.invalidSchema(
2161
- catalogName,
2162
- `Schema validation failed: ${errorMessages}`
2163
- );
2164
- }
2165
- return data;
2166
- } catch (error) {
2167
- if (error instanceof FoundryCatalogError) {
2168
- throw error;
2169
- }
2170
- const err = error;
2171
- if (err.code === "ENOENT") {
2172
- throw FoundryCatalogError.missingCatalog(catalogName);
2173
- } else if (err.code === "EACCES") {
2174
- throw FoundryCatalogError.invalidSchema(
2175
- catalogName,
2176
- "Permission denied accessing catalog file",
2177
- err
2178
- );
2179
- } else if (err.code === "EISDIR") {
2180
- throw FoundryCatalogError.invalidSchema(
2181
- catalogName,
2182
- "Expected file but found directory",
2183
- err
2184
- );
2185
- } else if (err.code === "EMFILE" || err.code === "ENFILE") {
2186
- throw FoundryCatalogError.invalidSchema(catalogName, "Too many open files", err);
1435
+
1436
+ // src/telemetry/validators.ts
1437
+ async function validateMetricsEvent(event) {
1438
+ return MetricsValidator.getInstance().validate(event);
1439
+ }
1440
+ async function validateMetricsEvents(events) {
1441
+ for (const event of events) {
1442
+ if (!await validateMetricsEvent(event)) {
1443
+ return false;
2187
1444
  }
2188
- throw FoundryCatalogError.invalidSchema(catalogName, "Failed to load catalog", err);
2189
1445
  }
1446
+ return true;
2190
1447
  }
2191
- async function loadPatternCatalog() {
2192
- return loadCatalog(SSOT_PATHS.patterns, "patterns", SCHEMA_IDS.patterns);
1448
+ function getValidationErrors() {
1449
+ return MetricsValidator.getInstance().getErrors();
2193
1450
  }
2194
- async function loadHttpStatusCatalog() {
2195
- return loadCatalog(
2196
- SSOT_PATHS.httpStatuses,
2197
- "httpStatuses",
2198
- SCHEMA_IDS.httpStatuses
2199
- );
1451
+ function formatValidationErrors(errors) {
1452
+ return errors.map((err) => {
1453
+ const path = err.instancePath || "(root)";
1454
+ const message = err.message || "validation failed";
1455
+ return `${path}: ${message}`;
1456
+ }).join("; ");
2200
1457
  }
2201
- async function loadMimeTypeCatalog() {
2202
- return loadCatalog(SSOT_PATHS.mimeTypes, "mimeTypes", SCHEMA_IDS.mimeTypes);
2203
- }
2204
- async function loadCountryCodeCatalog() {
2205
- return loadCatalog(
2206
- SSOT_PATHS.countryCodes,
2207
- "countryCodes",
2208
- SCHEMA_IDS.countryCodes
2209
- );
2210
- }
2211
- async function loadAllCatalogs() {
2212
- const [patterns, httpStatuses, mimeTypes, countryCodes] = await Promise.all([
2213
- loadPatternCatalog(),
2214
- loadHttpStatusCatalog(),
2215
- loadMimeTypeCatalog(),
2216
- loadCountryCodeCatalog()
2217
- ]);
2218
- return { patterns, httpStatuses, mimeTypes, countryCodes };
2219
- }
2220
- var __filename, __dirname2, SSOT_PATHS, SCHEMA_IDS;
2221
- var init_loader = __esm({
2222
- "src/foundry/loader.ts"() {
2223
- init_validator();
2224
- init_errors2();
2225
- __filename = fileURLToPath(import.meta.url);
2226
- __dirname2 = dirname(__filename);
2227
- SSOT_PATHS = {
2228
- patterns: join(__dirname2, "../../config/crucible-ts/library/foundry/patterns.yaml"),
2229
- httpStatuses: join(__dirname2, "../../config/crucible-ts/library/foundry/http-statuses.yaml"),
2230
- mimeTypes: join(__dirname2, "../../config/crucible-ts/library/foundry/mime-types.yaml"),
2231
- countryCodes: join(__dirname2, "../../config/crucible-ts/library/foundry/country-codes.yaml")
2232
- };
2233
- SCHEMA_IDS = {
2234
- patterns: "library/foundry/v1.0.0/patterns",
2235
- httpStatuses: "library/foundry/v1.0.0/http-status-groups",
2236
- mimeTypes: "library/foundry/v1.0.0/mime-types",
2237
- countryCodes: "library/foundry/v1.0.0/country-codes"
2238
- };
2239
- }
2240
- });
2241
-
2242
- // src/foundry/country-codes.ts
2243
- function deepClone(obj) {
2244
- if (obj === null || typeof obj !== "object") {
2245
- return obj;
2246
- }
2247
- if (Array.isArray(obj)) {
2248
- return obj.map((item) => deepClone(item));
2249
- }
2250
- const cloned = {};
2251
- for (const key in obj) {
2252
- if (Object.hasOwn(obj, key)) {
2253
- cloned[key] = deepClone(obj[key]);
2254
- }
2255
- }
2256
- return cloned;
2257
- }
2258
- function deepFreeze(obj) {
2259
- Object.freeze(obj);
2260
- for (const key in obj) {
2261
- if (Object.hasOwn(obj, key)) {
2262
- const value = obj[key];
2263
- if (value !== null && typeof value === "object") {
2264
- deepFreeze(value);
2265
- }
2266
- }
2267
- }
2268
- return obj;
2269
- }
2270
- function normalizeNumeric(code) {
2271
- const str = typeof code === "number" ? code.toString() : code;
2272
- return str.padStart(3, "0");
2273
- }
2274
- async function ensureCatalogLoaded() {
2275
- if (catalogCache !== null) {
2276
- return;
2277
- }
2278
- catalogCache = await loadCountryCodeCatalog();
2279
- for (const country of catalogCache.countries) {
2280
- alpha2Index.set(country.alpha2.toUpperCase(), country);
2281
- alpha3Index.set(country.alpha3.toUpperCase(), country);
2282
- const normalized = normalizeNumeric(country.numeric);
2283
- numericIndex.set(normalized, country);
2284
- }
2285
- }
2286
- async function getCountryByAlpha2(code) {
2287
- await ensureCatalogLoaded();
2288
- const normalized = code.toUpperCase();
2289
- const country = alpha2Index.get(normalized);
2290
- return country ? deepFreeze(deepClone(country)) : null;
2291
- }
2292
- async function getCountryByAlpha3(code) {
2293
- await ensureCatalogLoaded();
2294
- const normalized = code.toUpperCase();
2295
- const country = alpha3Index.get(normalized);
2296
- return country ? deepFreeze(deepClone(country)) : null;
2297
- }
2298
- async function getCountryByNumeric(code) {
2299
- await ensureCatalogLoaded();
2300
- const normalized = normalizeNumeric(code);
2301
- const country = numericIndex.get(normalized);
2302
- return country ? deepFreeze(deepClone(country)) : null;
2303
- }
2304
- async function listCountries() {
2305
- await ensureCatalogLoaded();
2306
- return Array.from(alpha2Index.values()).map((c) => deepFreeze(deepClone(c)));
2307
- }
2308
- function clearCountryCodeCache() {
2309
- catalogCache = null;
2310
- alpha2Index.clear();
2311
- alpha3Index.clear();
2312
- numericIndex.clear();
2313
- }
2314
- var catalogCache, alpha2Index, alpha3Index, numericIndex;
2315
- var init_country_codes = __esm({
2316
- "src/foundry/country-codes.ts"() {
2317
- init_loader();
2318
- catalogCache = null;
2319
- alpha2Index = /* @__PURE__ */ new Map();
2320
- alpha3Index = /* @__PURE__ */ new Map();
2321
- numericIndex = /* @__PURE__ */ new Map();
2322
- }
2323
- });
2324
-
2325
- // src/crucible/foundry/exitCodes.ts
2326
- function getExitCodeInfo(code) {
2327
- return exitCodeMetadata[code];
2328
- }
2329
- var exitCodes, exitCodeMetadata, EXIT_CODES_VERSION;
2330
- var init_exitCodes = __esm({
2331
- "src/crucible/foundry/exitCodes.ts"() {
2332
- exitCodes = {
2333
- // Standard Exit Codes (0-1)
2334
- // POSIX standard success and generic failure codes
2335
- EXIT_SUCCESS: 0,
2336
- EXIT_FAILURE: 1,
2337
- // Networking & Port Management (10-19)
2338
- // Network-related failures (ports, connectivity, etc.)
2339
- EXIT_PORT_IN_USE: 10,
2340
- EXIT_PORT_RANGE_EXHAUSTED: 11,
2341
- EXIT_INSTANCE_ALREADY_RUNNING: 12,
2342
- EXIT_NETWORK_UNREACHABLE: 13,
2343
- EXIT_CONNECTION_REFUSED: 14,
2344
- EXIT_CONNECTION_TIMEOUT: 15,
2345
- // Configuration & Validation (20-29)
2346
- // Configuration errors, validation failures, version mismatches
2347
- EXIT_CONFIG_INVALID: 20,
2348
- EXIT_MISSING_DEPENDENCY: 21,
2349
- EXIT_SSOT_VERSION_MISMATCH: 22,
2350
- EXIT_CONFIG_FILE_NOT_FOUND: 23,
2351
- EXIT_ENVIRONMENT_INVALID: 24,
2352
- // Runtime Errors (30-39)
2353
- // Errors during normal operation (health checks, database, etc.)
2354
- EXIT_HEALTH_CHECK_FAILED: 30,
2355
- EXIT_DATABASE_UNAVAILABLE: 31,
2356
- EXIT_EXTERNAL_SERVICE_UNAVAILABLE: 32,
2357
- EXIT_RESOURCE_EXHAUSTED: 33,
2358
- EXIT_OPERATION_TIMEOUT: 34,
2359
- // Command-Line Usage Errors (40-49)
2360
- // Invalid arguments, missing required flags, usage errors
2361
- EXIT_INVALID_ARGUMENT: 40,
2362
- EXIT_MISSING_REQUIRED_ARGUMENT: 41,
2363
- EXIT_USAGE: 64,
2364
- // Permissions & File Access (50-59)
2365
- // Permission denied, file not found, access errors
2366
- EXIT_PERMISSION_DENIED: 50,
2367
- EXIT_FILE_NOT_FOUND: 51,
2368
- EXIT_DIRECTORY_NOT_FOUND: 52,
2369
- EXIT_FILE_READ_ERROR: 53,
2370
- EXIT_FILE_WRITE_ERROR: 54,
2371
- // Data & Processing Errors (60-69)
2372
- // Data validation, parsing, transformation failures
2373
- EXIT_DATA_INVALID: 60,
2374
- EXIT_PARSE_ERROR: 61,
2375
- EXIT_TRANSFORMATION_FAILED: 62,
2376
- EXIT_DATA_CORRUPT: 63,
2377
- // Security & Authentication (70-79)
2378
- // Authentication failures, authorization errors, security violations
2379
- EXIT_AUTHENTICATION_FAILED: 70,
2380
- EXIT_AUTHORIZATION_FAILED: 71,
2381
- EXIT_SECURITY_VIOLATION: 72,
2382
- EXIT_CERTIFICATE_INVALID: 73,
2383
- // Observability & Monitoring (80-89)
2384
- // Observability infrastructure failures. Use when observability is CRITICAL to operation (e.g., monitoring agents, telemetry exporters). For workhorses where observability is auxiliary: - Log warning and continue (don't exit) - Emit degraded health status - Only exit if explicitly configured (fail_on_observability_error: true)
2385
- EXIT_METRICS_UNAVAILABLE: 80,
2386
- EXIT_TRACING_FAILED: 81,
2387
- EXIT_LOGGING_FAILED: 82,
2388
- EXIT_ALERT_SYSTEM_FAILED: 83,
2389
- EXIT_STRUCTURED_LOGGING_FAILED: 84,
2390
- // Testing & Validation (91-99)
2391
- // Test execution outcomes and validation failures. NOTE: Test harnesses MUST use EXIT_SUCCESS (0) for successful test runs per ecosystem conventions (pytest, Go testing, Jest all use 0 for success). Codes in this category are for FAILURES and exceptional conditions only.
2392
- EXIT_TEST_FAILURE: 91,
2393
- EXIT_TEST_ERROR: 92,
2394
- EXIT_TEST_INTERRUPTED: 93,
2395
- EXIT_TEST_USAGE_ERROR: 94,
2396
- EXIT_TEST_NO_TESTS_COLLECTED: 95,
2397
- EXIT_COVERAGE_THRESHOLD_NOT_MET: 96,
2398
- // Shell & Process Control (124-127)
2399
- // Exit codes from shell conventions and process control utilities (timeout, exec)
2400
- EXIT_TIMEOUT: 124,
2401
- EXIT_TIMEOUT_INTERNAL: 125,
2402
- EXIT_CANNOT_EXECUTE: 126,
2403
- EXIT_NOT_FOUND: 127,
2404
- // Signal-Induced Exits (128-165)
2405
- // Process terminated by Unix signals (128+N pattern per POSIX). Signal codes follow Linux numbering; macOS/FreeBSD differ for SIGUSR1/SIGUSR2. For full signal semantics, see config/library/foundry/signals.yaml. For signal handling patterns, see docs/standards/library/modules/signal-handling.md.
2406
- EXIT_SIGNAL_HUP: 129,
2407
- EXIT_SIGNAL_INT: 130,
2408
- EXIT_SIGNAL_QUIT: 131,
2409
- EXIT_SIGNAL_KILL: 137,
2410
- EXIT_SIGNAL_PIPE: 141,
2411
- EXIT_SIGNAL_ALRM: 142,
2412
- EXIT_SIGNAL_TERM: 143,
2413
- EXIT_SIGNAL_USR1: 138,
2414
- EXIT_SIGNAL_USR2: 140
2415
- };
2416
- exitCodeMetadata = {
2417
- 0: {
2418
- code: 0,
2419
- name: "EXIT_SUCCESS",
2420
- description: "Successful execution",
2421
- context: "Command completed without errors",
2422
- category: "standard"
2423
- },
2424
- 1: {
2425
- code: 1,
2426
- name: "EXIT_FAILURE",
2427
- description: "Generic failure (unspecified error)",
2428
- context: "Use when no more specific exit code applies",
2429
- category: "standard"
2430
- },
2431
- 10: {
2432
- code: 10,
2433
- name: "EXIT_PORT_IN_USE",
2434
- description: "Specified port is already in use",
2435
- context: "Server startup when port unavailable and fail_if_unavailable strategy",
2436
- category: "networking"
2437
- },
2438
- 11: {
2439
- code: 11,
2440
- name: "EXIT_PORT_RANGE_EXHAUSTED",
2441
- description: "No available ports in configured range",
2442
- context: "Server startup when all ports in environment range occupied",
2443
- category: "networking"
2444
- },
2445
- 12: {
2446
- code: 12,
2447
- name: "EXIT_INSTANCE_ALREADY_RUNNING",
2448
- description: "Another instance already running on target port",
2449
- context: "Server startup when PID registry shows active process on port",
2450
- category: "networking"
2451
- },
2452
- 13: {
2453
- code: 13,
2454
- name: "EXIT_NETWORK_UNREACHABLE",
2455
- description: "Network destination unreachable",
2456
- context: "Client connections, health checks, external service validation",
2457
- category: "networking"
2458
- },
2459
- 14: {
2460
- code: 14,
2461
- name: "EXIT_CONNECTION_REFUSED",
2462
- description: "Connection refused by remote host",
2463
- context: "Database connections, API endpoints, upstream services",
2464
- category: "networking"
2465
- },
2466
- 15: {
2467
- code: 15,
2468
- name: "EXIT_CONNECTION_TIMEOUT",
2469
- description: "Connection attempt timed out",
2470
- context: "Slow networks, unresponsive services, firewall blocks",
2471
- category: "networking"
2472
- },
2473
- 20: {
2474
- code: 20,
2475
- name: "EXIT_CONFIG_INVALID",
2476
- description: "Configuration file failed validation",
2477
- context: "Startup validation, schema mismatches, invalid YAML/JSON",
2478
- category: "configuration",
2479
- retryHint: "no_retry"
2480
- },
2481
- 21: {
2482
- code: 21,
2483
- name: "EXIT_MISSING_DEPENDENCY",
2484
- description: "Required dependency not found",
2485
- context: "Missing binaries, libraries, or runtime requirements",
2486
- category: "configuration",
2487
- retryHint: "investigate"
2488
- },
2489
- 22: {
2490
- code: 22,
2491
- name: "EXIT_SSOT_VERSION_MISMATCH",
2492
- description: "SSOT (Crucible) version incompatible",
2493
- context: "Helper library detects unsupported Crucible version",
2494
- category: "configuration",
2495
- retryHint: "no_retry"
2496
- },
2497
- 23: {
2498
- code: 23,
2499
- name: "EXIT_CONFIG_FILE_NOT_FOUND",
2500
- description: "Required configuration file not found",
2501
- context: "Explicitly specified config path doesn't exist",
2502
- category: "configuration"
2503
- },
2504
- 24: {
2505
- code: 24,
2506
- name: "EXIT_ENVIRONMENT_INVALID",
2507
- description: "Invalid or unsupported environment specification",
2508
- context: "Unknown environment name, missing environment config",
2509
- category: "configuration"
2510
- },
2511
- 30: {
2512
- code: 30,
2513
- name: "EXIT_HEALTH_CHECK_FAILED",
2514
- description: "Health check endpoint returned non-healthy status",
2515
- context: "Startup health validation, readiness probes",
2516
- category: "runtime",
2517
- retryHint: "retry"
2518
- },
2519
- 31: {
2520
- code: 31,
2521
- name: "EXIT_DATABASE_UNAVAILABLE",
2522
- description: "Database connection failed or unavailable",
2523
- context: "Startup connection checks, critical query failures",
2524
- category: "runtime",
2525
- retryHint: "retry"
2526
- },
2527
- 32: {
2528
- code: 32,
2529
- name: "EXIT_EXTERNAL_SERVICE_UNAVAILABLE",
2530
- description: "Required external service unavailable",
2531
- context: "API dependencies, message queues, cache servers",
2532
- category: "runtime"
2533
- },
2534
- 33: {
2535
- code: 33,
2536
- name: "EXIT_RESOURCE_EXHAUSTED",
2537
- description: "System resources exhausted (memory, disk, file descriptors)",
2538
- context: "Out-of-memory, disk full, too many open files",
2539
- category: "runtime",
2540
- retryHint: "investigate"
2541
- },
2542
- 34: {
2543
- code: 34,
2544
- name: "EXIT_OPERATION_TIMEOUT",
2545
- description: "Operation exceeded timeout threshold",
2546
- context: "Long-running tasks, async operations, batch processing",
2547
- category: "runtime",
2548
- retryHint: "retry"
2549
- },
2550
- 40: {
2551
- code: 40,
2552
- name: "EXIT_INVALID_ARGUMENT",
2553
- description: "Invalid command-line argument or flag value",
2554
- context: "Type errors, out-of-range values, malformed input",
2555
- category: "usage"
2556
- },
2557
- 41: {
2558
- code: 41,
2559
- name: "EXIT_MISSING_REQUIRED_ARGUMENT",
2560
- description: "Required command-line argument not provided",
2561
- context: "Missing --config, --port, or other required flags",
2562
- category: "usage"
2563
- },
2564
- 64: {
2565
- code: 64,
2566
- name: "EXIT_USAGE",
2567
- description: "Command-line usage error",
2568
- context: "BSD sysexits.h EX_USAGE - wrong number of arguments, bad syntax",
2569
- category: "usage",
2570
- bsdEquivalent: "EX_USAGE"
2571
- },
2572
- 50: {
2573
- code: 50,
2574
- name: "EXIT_PERMISSION_DENIED",
2575
- description: "Insufficient permissions for operation",
2576
- context: "File access, port binding (<1024), privileged operations",
2577
- category: "permissions"
2578
- },
2579
- 51: {
2580
- code: 51,
2581
- name: "EXIT_FILE_NOT_FOUND",
2582
- description: "Required file not found",
2583
- context: "Assets, templates, data files (not config - use 23)",
2584
- category: "permissions"
2585
- },
2586
- 52: {
2587
- code: 52,
2588
- name: "EXIT_DIRECTORY_NOT_FOUND",
2589
- description: "Required directory not found",
2590
- context: "State directories, log paths, data directories",
2591
- category: "permissions"
2592
- },
2593
- 53: {
2594
- code: 53,
2595
- name: "EXIT_FILE_READ_ERROR",
2596
- description: "Error reading file",
2597
- context: "Corrupt files, I/O errors, encoding issues",
2598
- category: "permissions"
2599
- },
2600
- 54: {
2601
- code: 54,
2602
- name: "EXIT_FILE_WRITE_ERROR",
2603
- description: "Error writing file",
2604
- context: "Disk full, read-only filesystem, permission errors",
2605
- category: "permissions"
2606
- },
2607
- 60: {
2608
- code: 60,
2609
- name: "EXIT_DATA_INVALID",
2610
- description: "Input data failed validation",
2611
- context: "Schema validation, business rule violations",
2612
- category: "data"
2613
- },
2614
- 61: {
2615
- code: 61,
2616
- name: "EXIT_PARSE_ERROR",
2617
- description: "Error parsing input data",
2618
- context: "Malformed JSON/YAML/XML, syntax errors",
2619
- category: "data"
2620
- },
2621
- 62: {
2622
- code: 62,
2623
- name: "EXIT_TRANSFORMATION_FAILED",
2624
- description: "Data transformation or conversion failed",
2625
- context: "Type conversions, format transformations, encoding changes",
2626
- category: "data"
2627
- },
2628
- 63: {
2629
- code: 63,
2630
- name: "EXIT_DATA_CORRUPT",
2631
- description: "Data corruption detected",
2632
- context: "Checksum failures, integrity violations",
2633
- category: "data"
2634
- },
2635
- 70: {
2636
- code: 70,
2637
- name: "EXIT_AUTHENTICATION_FAILED",
2638
- description: "Authentication failed",
2639
- context: "Invalid credentials, expired tokens, auth service unavailable",
2640
- category: "security"
2641
- },
2642
- 71: {
2643
- code: 71,
2644
- name: "EXIT_AUTHORIZATION_FAILED",
2645
- description: "Authorization failed (authenticated but insufficient permissions)",
2646
- context: "RBAC failures, scope violations, resource access denied",
2647
- category: "security"
2648
- },
2649
- 72: {
2650
- code: 72,
2651
- name: "EXIT_SECURITY_VIOLATION",
2652
- description: "Security policy violation detected",
2653
- context: "Suspicious activity, rate limit exceeded, IP blocklist",
2654
- category: "security"
2655
- },
2656
- 73: {
2657
- code: 73,
2658
- name: "EXIT_CERTIFICATE_INVALID",
2659
- description: "TLS/SSL certificate validation failed",
2660
- context: "Expired certs, untrusted CAs, hostname mismatches",
2661
- category: "security",
2662
- bsdEquivalent: "EX_PROTOCOL"
2663
- },
2664
- 80: {
2665
- code: 80,
2666
- name: "EXIT_METRICS_UNAVAILABLE",
2667
- description: "Metrics endpoint or collection system unavailable",
2668
- context: "Use for observability-focused tools (Prometheus exporters, StatsD agents).\nWorkhorses SHOULD log warning and continue unless configured to fail-fast.\n",
2669
- category: "observability"
2670
- },
2671
- 81: {
2672
- code: 81,
2673
- name: "EXIT_TRACING_FAILED",
2674
- description: "Distributed tracing system unavailable",
2675
- context: "OTLP exporter failed, Jaeger collector unreachable",
2676
- category: "observability"
2677
- },
2678
- 82: {
2679
- code: 82,
2680
- name: "EXIT_LOGGING_FAILED",
2681
- description: "Logging system unavailable or misconfigured",
2682
- context: "Log aggregator unreachable, log file unwritable",
2683
- category: "observability"
2684
- },
2685
- 83: {
2686
- code: 83,
2687
- name: "EXIT_ALERT_SYSTEM_FAILED",
2688
- description: "Alerting system unavailable",
2689
- context: "PagerDuty API failed, Slack webhook unreachable",
2690
- category: "observability"
2691
- },
2692
- 84: {
2693
- code: 84,
2694
- name: "EXIT_STRUCTURED_LOGGING_FAILED",
2695
- description: "Structured logging system unavailable",
2696
- context: "JSON log aggregator unreachable, log schema validation failed",
2697
- category: "observability"
2698
- },
2699
- 91: {
2700
- code: 91,
2701
- name: "EXIT_TEST_FAILURE",
2702
- description: "One or more tests failed",
2703
- context: "Test assertions failed, expected behavior not met.\nMaps to pytest exit code 1, Go test failure, Jest failure.\n",
2704
- category: "testing"
2705
- },
2706
- 92: {
2707
- code: 92,
2708
- name: "EXIT_TEST_ERROR",
2709
- description: "Test execution error (not test failure)",
2710
- context: "Test setup failed, fixture unavailable, test harness error.\nMaps to pytest exit code 3 (internal error).\n",
2711
- category: "testing"
2712
- },
2713
- 93: {
2714
- code: 93,
2715
- name: "EXIT_TEST_INTERRUPTED",
2716
- description: "Test run interrupted by user or system",
2717
- context: "Ctrl+C during tests, system signal, user cancellation.\nMaps to pytest exit code 2.\n",
2718
- category: "testing"
2719
- },
2720
- 94: {
2721
- code: 94,
2722
- name: "EXIT_TEST_USAGE_ERROR",
2723
- description: "Test command usage error",
2724
- context: "Invalid test arguments, bad configuration.\nMaps to pytest exit code 4.\n",
2725
- category: "testing"
2726
- },
2727
- 95: {
2728
- code: 95,
2729
- name: "EXIT_TEST_NO_TESTS_COLLECTED",
2730
- description: "No tests found or all tests skipped",
2731
- context: "Empty test suite, all tests deselected or skipped.\nMaps to pytest exit code 5.\n",
2732
- category: "testing"
2733
- },
2734
- 96: {
2735
- code: 96,
2736
- name: "EXIT_COVERAGE_THRESHOLD_NOT_MET",
2737
- description: "Test coverage below required threshold",
2738
- context: "Code coverage validation, quality gate failure",
2739
- category: "testing"
2740
- },
2741
- 124: {
2742
- code: 124,
2743
- name: "EXIT_TIMEOUT",
2744
- description: "Command timed out before completion",
2745
- context: "GNU timeout or similar utility terminated command after deadline",
2746
- category: "shell"
2747
- },
2748
- 125: {
2749
- code: 125,
2750
- name: "EXIT_TIMEOUT_INTERNAL",
2751
- description: "Timeout utility itself failed",
2752
- context: "Error in timeout tool before or during command execution (not command failure)",
2753
- category: "shell"
2754
- },
2755
- 126: {
2756
- code: 126,
2757
- name: "EXIT_CANNOT_EXECUTE",
2758
- description: "Command found but could not be executed",
2759
- context: "Permission denied, not executable, exec format error",
2760
- category: "shell",
2761
- bsdEquivalent: "EX_NOPERM (partial)"
2762
- },
2763
- 127: {
2764
- code: 127,
2765
- name: "EXIT_NOT_FOUND",
2766
- description: "Command not found",
2767
- context: "Executable not found in PATH or specified path does not exist",
2768
- category: "shell",
2769
- bsdEquivalent: "EX_UNAVAILABLE (partial)"
2770
- },
2771
- 129: {
2772
- code: 129,
2773
- name: "EXIT_SIGNAL_HUP",
2774
- description: "Hangup signal (SIGHUP) - config reload via restart",
2775
- context: "Config reload via restart-based pattern (mandatory schema validation).\nProcess exits with 129, supervisor restarts with new config.\nSee signals.yaml for reload behavior definition.",
2776
- category: "signals",
2777
- bsdEquivalent: "128 + 1"
2778
- },
2779
- 130: {
2780
- code: 130,
2781
- name: "EXIT_SIGNAL_INT",
2782
- description: "Interrupt signal (SIGINT) - user interrupt with Ctrl+C double-tap",
2783
- context: "Ctrl+C pressed. First tap initiates graceful shutdown, second within 2s forces immediate exit.\nSame exit code (130) for both graceful and force modes.\nSee signals.yaml for double-tap behavior definition.",
2784
- category: "signals",
2785
- bsdEquivalent: "128 + 2"
2786
- },
2787
- 131: {
2788
- code: 131,
2789
- name: "EXIT_SIGNAL_QUIT",
2790
- description: "Quit signal (SIGQUIT) - immediate exit",
2791
- context: "Ctrl+\\ on Unix, Ctrl+Break on Windows. Immediate termination without cleanup.\nUse for emergency shutdown or debugging (core dumps).",
2792
- category: "signals",
2793
- bsdEquivalent: "128 + 3"
2794
- },
2795
- 137: {
2796
- code: 137,
2797
- name: "EXIT_SIGNAL_KILL",
2798
- description: "Kill signal (SIGKILL)",
2799
- context: "Forceful termination, non-graceful shutdown (not catchable)",
2800
- category: "signals",
2801
- bsdEquivalent: "128 + 9",
2802
- pythonNote: "Cannot be caught in Python (OS-level)"
2803
- },
2804
- 141: {
2805
- code: 141,
2806
- name: "EXIT_SIGNAL_PIPE",
2807
- description: "Broken pipe (SIGPIPE) - observe only",
2808
- context: "Writing to closed pipe/socket. Fulmen default is observe_only (log + graceful exit).\nApplications may override to ignore for network services.\nSee signals.yaml for SIGPIPE handling guidance.",
2809
- category: "signals",
2810
- bsdEquivalent: "128 + 13",
2811
- pythonNote: "Raised as BrokenPipeError exception"
2812
- },
2813
- 142: {
2814
- code: 142,
2815
- name: "EXIT_SIGNAL_ALRM",
2816
- description: "Alarm signal (SIGALRM) - watchdog timeout",
2817
- context: "Watchdog timer expired. Treat as timeout-induced exit.\nWatchdog pattern out of scope for v1.0.0 module implementations.",
2818
- category: "signals",
2819
- bsdEquivalent: "128 + 14",
2820
- pythonNote: "Supported by signal module, rarely used in practice"
2821
- },
2822
- 143: {
2823
- code: 143,
2824
- name: "EXIT_SIGNAL_TERM",
2825
- description: "Termination signal (SIGTERM) - graceful shutdown",
2826
- context: "Graceful shutdown requested by container orchestrator or process supervisor.\nStandard 30-second timeout for cleanup. Applications run cleanup handlers before exit.\nSee signals.yaml for graceful shutdown behavior definition.",
2827
- category: "signals",
2828
- bsdEquivalent: "128 + 15",
2829
- pythonNote: "Default signal for graceful shutdown"
2830
- },
2831
- 138: {
2832
- code: 138,
2833
- name: "EXIT_SIGNAL_USR1",
2834
- description: "User-defined signal 1 (SIGUSR1) - custom handler",
2835
- context: "Application-specific signal (e.g., reopen logs, dump stats, trigger profiling).\nApplications register custom handlers. Exit code 138 on Linux (128+10).\nPlatform differences: macOS/FreeBSD use signal 30 (exit 158), not 10.",
2836
- category: "signals"
2837
- },
2838
- 140: {
2839
- code: 140,
2840
- name: "EXIT_SIGNAL_USR2",
2841
- description: "User-defined signal 2 (SIGUSR2) - custom handler",
2842
- context: "Application-specific signal (e.g., toggle debug mode, rotate credentials).\nApplications register custom handlers. Exit code 140 on Linux (128+12).\nPlatform differences: macOS/FreeBSD use signal 31 (exit 159), not 12.",
2843
- category: "signals"
2844
- }
2845
- };
2846
- EXIT_CODES_VERSION = "v1.0.0";
2847
- }
2848
- });
2849
-
2850
- // src/foundry/exit-codes/capabilities.ts
2851
- function supportsSignalExitCodes() {
2852
- return process.platform !== "win32";
2853
- }
2854
- function getPlatform() {
2855
- return process.platform;
2856
- }
2857
- function isWindows() {
2858
- return process.platform === "win32";
2859
- }
2860
- function isPOSIX() {
2861
- return !isWindows();
2862
- }
2863
- function getPlatformCapabilities() {
2864
- return {
2865
- platform: getPlatform(),
2866
- supportsSignalExitCodes: supportsSignalExitCodes(),
2867
- isPOSIX: isPOSIX(),
2868
- isWindows: isWindows()
2869
- };
2870
- }
2871
- var init_capabilities = __esm({
2872
- "src/foundry/exit-codes/capabilities.ts"() {
2873
- }
2874
- });
2875
-
2876
- // src/foundry/exit-codes/simplified.ts
2877
- function mapExitCodeToSimplified(code, mode = "basic" /* BASIC */) {
2878
- if (code === 0) {
2879
- return 0;
2880
- }
2881
- if (mode === "basic" /* BASIC */) {
2882
- return 1;
2883
- }
2884
- const info = exitCodeMetadata[code];
2885
- if (!info) {
2886
- return 3;
2887
- }
2888
- if (info.retryHint === "retry") {
2889
- return 1;
2890
- }
2891
- if (info.retryHint === "no_retry") {
2892
- return 2;
2893
- }
2894
- if (info.retryHint === "investigate") {
2895
- return 3;
2896
- }
2897
- switch (info.category) {
2898
- case "configuration":
2899
- case "usage":
2900
- return 2;
2901
- case "networking":
2902
- case "runtime":
2903
- return 1;
2904
- case "permissions":
2905
- case "data":
2906
- return 2;
2907
- case "security":
2908
- return 3;
2909
- case "observability":
2910
- return 1;
2911
- case "testing":
2912
- return 1;
2913
- case "signals":
2914
- return 3;
2915
- default:
2916
- return 1;
2917
- }
2918
- }
2919
- function getSimplifiedCodes(mode) {
2920
- switch (mode) {
2921
- case "basic" /* BASIC */:
2922
- return [0, 1];
2923
- case "severity" /* SEVERITY */:
2924
- return [0, 1, 2, 3];
2925
- default:
2926
- return [0, 1];
2927
- }
2928
- }
2929
- function getSimplifiedCodeDescription(code, mode) {
2930
- if (mode === "basic" /* BASIC */) {
2931
- switch (code) {
2932
- case 0:
2933
- return "Success";
2934
- case 1:
2935
- return "Failure";
2936
- default:
2937
- return "Unknown";
2938
- }
2939
- }
2940
- if (mode === "severity" /* SEVERITY */) {
2941
- switch (code) {
2942
- case 0:
2943
- return "Success";
2944
- case 1:
2945
- return "Recoverable error (retry possible)";
2946
- case 2:
2947
- return "Configuration error (fix config, don't retry)";
2948
- case 3:
2949
- return "Fatal error (investigate required)";
2950
- default:
2951
- return "Unknown";
2952
- }
2953
- }
2954
- return "Unknown mode";
2955
- }
2956
- var SimplifiedMode;
2957
- var init_simplified = __esm({
2958
- "src/foundry/exit-codes/simplified.ts"() {
2959
- init_exitCodes();
2960
- SimplifiedMode = /* @__PURE__ */ ((SimplifiedMode2) => {
2961
- SimplifiedMode2["BASIC"] = "basic";
2962
- SimplifiedMode2["SEVERITY"] = "severity";
2963
- return SimplifiedMode2;
2964
- })(SimplifiedMode || {});
2965
- }
2966
- });
2967
-
2968
- // src/foundry/exit-codes/index.ts
2969
- var init_exit_codes = __esm({
2970
- "src/foundry/exit-codes/index.ts"() {
2971
- init_exitCodes();
2972
- init_capabilities();
2973
- init_simplified();
2974
- }
2975
- });
2976
-
2977
- // src/foundry/http-statuses.ts
2978
- function deepClone2(obj) {
2979
- if (obj === null || typeof obj !== "object") {
2980
- return obj;
2981
- }
2982
- if (Array.isArray(obj)) {
2983
- return obj.map((item) => deepClone2(item));
2984
- }
2985
- const cloned = {};
2986
- for (const key in obj) {
2987
- if (Object.hasOwn(obj, key)) {
2988
- cloned[key] = deepClone2(obj[key]);
2989
- }
2990
- }
2991
- return cloned;
2992
- }
2993
- function deepFreeze2(obj) {
2994
- Object.freeze(obj);
2995
- for (const key in obj) {
2996
- if (Object.hasOwn(obj, key)) {
2997
- const value = obj[key];
2998
- if (value !== null && typeof value === "object") {
2999
- deepFreeze2(value);
3000
- }
3001
- }
3002
- }
3003
- return obj;
3004
- }
3005
- async function ensureCatalogLoaded2() {
3006
- if (catalogCache2 !== null) {
3007
- return;
3008
- }
3009
- catalogCache2 = await loadHttpStatusCatalog();
3010
- for (const group of catalogCache2.groups) {
3011
- const groupId = group.id;
3012
- for (const code of group.codes) {
3013
- statusCodeIndex.set(code.value, {
3014
- value: code.value,
3015
- reason: code.reason,
3016
- group: groupId
3017
- });
3018
- }
3019
- }
3020
- }
3021
- async function getHttpStatus(code) {
3022
- await ensureCatalogLoaded2();
3023
- const status = statusCodeIndex.get(code);
3024
- return status ? deepFreeze2(deepClone2(status)) : null;
3025
- }
3026
- function isInformational(code) {
3027
- return code >= 100 && code < 200;
3028
- }
3029
- function isSuccess(code) {
3030
- return code >= 200 && code < 300;
3031
- }
3032
- function isRedirection(code) {
3033
- return code >= 300 && code < 400;
3034
- }
3035
- function isClientError(code) {
3036
- return code >= 400 && code < 500;
3037
- }
3038
- function isServerError(code) {
3039
- return code >= 500 && code < 600;
3040
- }
3041
- async function listHttpStatuses() {
3042
- await ensureCatalogLoaded2();
3043
- return Array.from(statusCodeIndex.values()).map((s) => deepFreeze2(deepClone2(s)));
3044
- }
3045
- async function getStatusReason(code) {
3046
- const status = await getHttpStatus(code);
3047
- return status?.reason ?? null;
3048
- }
3049
- function clearHttpStatusCache() {
3050
- catalogCache2 = null;
3051
- statusCodeIndex.clear();
3052
- }
3053
- var catalogCache2, statusCodeIndex;
3054
- var init_http_statuses = __esm({
3055
- "src/foundry/http-statuses.ts"() {
3056
- init_loader();
3057
- catalogCache2 = null;
3058
- statusCodeIndex = /* @__PURE__ */ new Map();
3059
- }
3060
- });
3061
-
3062
- // src/foundry/magic-numbers.ts
3063
- function hasBOM(buffer) {
3064
- if (buffer.length < 3) return false;
3065
- return buffer[0] === UTF8_BOM[0] && buffer[1] === UTF8_BOM[1] && buffer[2] === UTF8_BOM[2];
3066
- }
3067
- function getBOMOffset(buffer) {
3068
- return hasBOM(buffer) ? 3 : 0;
3069
- }
3070
- var UTF8_BOM, XML_PATTERNS, JSON_PATTERNS, YAML_PATTERNS, NDJSON_PATTERNS, CSV_PATTERNS, PROTOBUF_PATTERNS, TEXT_PATTERNS, MAGIC_NUMBER_DATABASE;
3071
- var init_magic_numbers = __esm({
3072
- "src/foundry/magic-numbers.ts"() {
3073
- UTF8_BOM = [239, 187, 191];
3074
- XML_PATTERNS = [
3075
- {
3076
- offset: 0,
3077
- bytes: [60, 63, 120, 109, 108],
3078
- description: "XML declaration: <?xml"
3079
- },
3080
- {
3081
- offset: 0,
3082
- bytes: [239, 187, 191, 60, 63, 120, 109, 108],
3083
- description: "XML with UTF-8 BOM: BOM + <?xml"
3084
- }
3085
- ];
3086
- JSON_PATTERNS = [
3087
- {
3088
- offset: 0,
3089
- bytes: [123],
3090
- description: "JSON object start: {"
3091
- },
3092
- {
3093
- offset: 0,
3094
- bytes: [91],
3095
- description: "JSON array start: ["
3096
- },
3097
- {
3098
- offset: 0,
3099
- bytes: [239, 187, 191, 123],
3100
- description: "JSON object with BOM: BOM + {"
3101
- },
3102
- {
3103
- offset: 0,
3104
- bytes: [239, 187, 191, 91],
3105
- description: "JSON array with BOM: BOM + ["
3106
- }
3107
- ];
3108
- YAML_PATTERNS = [
3109
- {
3110
- offset: 0,
3111
- bytes: [45, 45, 45],
3112
- description: "YAML document marker: ---"
3113
- },
3114
- {
3115
- offset: 0,
3116
- bytes: [37, 89, 65, 77, 76],
3117
- description: "YAML directive: %YAML"
3118
- }
3119
- ];
3120
- NDJSON_PATTERNS = [];
3121
- CSV_PATTERNS = [];
3122
- PROTOBUF_PATTERNS = [];
3123
- TEXT_PATTERNS = [];
3124
- MAGIC_NUMBER_DATABASE = [
3125
- {
3126
- mimeType: "application/xml",
3127
- patterns: XML_PATTERNS,
3128
- priority: 10,
3129
- matchStrategy: "exact"
3130
- },
3131
- {
3132
- mimeType: "application/x-ndjson",
3133
- patterns: NDJSON_PATTERNS,
3134
- priority: 9,
3135
- matchStrategy: "heuristic"
3136
- },
3137
- {
3138
- mimeType: "application/json",
3139
- patterns: JSON_PATTERNS,
3140
- priority: 8,
3141
- matchStrategy: "exact"
3142
- },
3143
- {
3144
- mimeType: "application/yaml",
3145
- patterns: YAML_PATTERNS,
3146
- priority: 7,
3147
- matchStrategy: "exact"
3148
- },
3149
- {
3150
- mimeType: "application/yaml",
3151
- patterns: [],
3152
- priority: 6.5,
3153
- matchStrategy: "heuristic"
3154
- },
3155
- {
3156
- mimeType: "text/csv",
3157
- patterns: CSV_PATTERNS,
3158
- priority: 6,
3159
- matchStrategy: "heuristic"
3160
- },
3161
- {
3162
- mimeType: "application/x-protobuf",
3163
- patterns: PROTOBUF_PATTERNS,
3164
- priority: 5,
3165
- matchStrategy: "heuristic"
3166
- },
3167
- {
3168
- mimeType: "text/plain",
3169
- patterns: TEXT_PATTERNS,
3170
- priority: 1,
3171
- matchStrategy: "heuristic"
3172
- }
3173
- ];
3174
- }
3175
- });
3176
-
3177
- // src/foundry/detector.ts
3178
- function createDetector(catalog) {
3179
- return new MimeTypeDetector(MAGIC_NUMBER_DATABASE, catalog);
3180
- }
3181
- var MimeTypeDetector;
3182
- var init_detector = __esm({
3183
- "src/foundry/detector.ts"() {
3184
- init_magic_numbers();
3185
- MimeTypeDetector = class {
3186
- patterns;
3187
- catalog;
3188
- constructor(patterns, catalog) {
3189
- this.patterns = [...patterns].sort((a, b) => b.priority - a.priority);
3190
- this.catalog = catalog;
3191
- }
3192
- /**
3193
- * Detect MIME type from buffer content
3194
- */
3195
- detect(buffer, _options = {}) {
3196
- const offset = getBOMOffset(buffer);
3197
- const workingBuffer = offset > 0 ? buffer.subarray(offset) : buffer;
3198
- for (const pattern of this.patterns) {
3199
- if (pattern.matchStrategy === "exact" && this.matchPattern(workingBuffer, pattern)) {
3200
- return this.catalog.get(pattern.mimeType) || null;
3201
- }
3202
- if (pattern.matchStrategy === "heuristic" && this.matchHeuristic(workingBuffer, pattern)) {
3203
- return this.catalog.get(pattern.mimeType) || null;
3204
- }
3205
- }
3206
- return null;
3207
- }
3208
- /**
3209
- * Match buffer against a pattern signature
3210
- */
3211
- matchPattern(buffer, signature) {
3212
- for (const pattern of signature.patterns) {
3213
- if (this.matchBytes(buffer, pattern)) {
3214
- return true;
3215
- }
3216
- }
3217
- return false;
3218
- }
3219
- /**
3220
- * Match bytes at specified offset with optional masking
3221
- */
3222
- matchBytes(buffer, pattern) {
3223
- const { offset, bytes, mask } = pattern;
3224
- if (buffer.length < offset + bytes.length) {
3225
- return false;
3226
- }
3227
- for (let i = 0; i < bytes.length; i++) {
3228
- const bufferByte = buffer[offset + i];
3229
- const patternByte = bytes[i];
3230
- const maskByte = mask ? mask[i] : 255;
3231
- if ((bufferByte & maskByte) !== (patternByte & maskByte)) {
3232
- return false;
3233
- }
3234
- }
3235
- return true;
3236
- }
3237
- /**
3238
- * Heuristic detection for formats without magic numbers
3239
- */
3240
- matchHeuristic(buffer, signature) {
3241
- switch (signature.mimeType) {
3242
- case "application/x-ndjson":
3243
- return this.detectNDJSON(buffer);
3244
- case "application/yaml":
3245
- return this.detectYAML(buffer);
3246
- case "text/csv":
3247
- return this.detectCSV(buffer);
3248
- case "application/x-protobuf":
3249
- return this.detectProtobuf(buffer);
3250
- case "text/plain":
3251
- return this.detectPlainText(buffer);
3252
- default:
3253
- return false;
3254
- }
3255
- }
3256
- /**
3257
- * Detect NDJSON (newline-delimited JSON)
3258
- */
3259
- detectNDJSON(buffer) {
3260
- try {
3261
- const text = buffer.toString("utf-8", 0, Math.min(buffer.length, 512));
3262
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
3263
- if (lines.length < 2) return false;
3264
- const linesToCheck = Math.min(3, lines.length);
3265
- let validJsonLines = 0;
3266
- for (let i = 0; i < linesToCheck; i++) {
3267
- try {
3268
- JSON.parse(lines[i]);
3269
- validJsonLines++;
3270
- } catch {
3271
- return false;
3272
- }
3273
- }
3274
- return validJsonLines >= 2;
3275
- } catch {
3276
- return false;
3277
- }
3278
- }
3279
- /**
3280
- * Detect YAML format (heuristic for files without --- header)
3281
- */
3282
- detectYAML(buffer) {
3283
- try {
3284
- const text = buffer.toString("utf-8", 0, Math.min(buffer.length, 512));
3285
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
3286
- if (lines.length === 0) return false;
3287
- let yamlIndicators = 0;
3288
- let nonYamlIndicators = 0;
3289
- for (const line of lines.slice(0, 10)) {
3290
- const trimmed = line.trim();
3291
- if (trimmed.startsWith("#")) continue;
3292
- if (/^[\w"'-]+\s*:\s*.+$/.test(trimmed)) {
3293
- yamlIndicators++;
3294
- continue;
3295
- }
3296
- if (/^-\s+/.test(trimmed)) {
3297
- yamlIndicators++;
3298
- continue;
3299
- }
3300
- if (trimmed.startsWith("{") || trimmed.startsWith("[") || trimmed.endsWith(",")) {
3301
- nonYamlIndicators++;
3302
- }
3303
- }
3304
- return yamlIndicators >= 2 && nonYamlIndicators === 0;
3305
- } catch {
3306
- return false;
3307
- }
3308
- }
3309
- /**
3310
- * Detect CSV format
3311
- */
3312
- detectCSV(buffer) {
3313
- try {
3314
- const text = buffer.toString("utf-8", 0, Math.min(buffer.length, 512));
3315
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
3316
- if (lines.length < 2) return false;
3317
- const delimiters = [",", ";", " "];
3318
- for (const delimiter of delimiters) {
3319
- const counts = lines.map((line) => {
3320
- const escaped = delimiter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3321
- const matches = line.match(new RegExp(escaped, "g"));
3322
- return matches ? matches.length : 0;
3323
- });
3324
- const firstCount = counts[0];
3325
- if (firstCount > 0 && counts.every((count) => count === firstCount)) {
3326
- return true;
3327
- }
3328
- }
3329
- return false;
3330
- } catch {
3331
- return false;
3332
- }
3333
- }
3334
- /**
3335
- * Detect protobuf binary format
3336
- */
3337
- detectProtobuf(buffer) {
3338
- if (buffer.length < 4) return false;
3339
- const firstByte = buffer[0];
3340
- const wireType = firstByte & 7;
3341
- const fieldNumber = firstByte >> 3;
3342
- const hasValidWireType = wireType === 0 || wireType === 1 || wireType === 2 || wireType === 5;
3343
- const hasValidFieldNumber = fieldNumber > 0 && fieldNumber < 100;
3344
- const isBinary = this.isBinaryContent(buffer);
3345
- return hasValidWireType && hasValidFieldNumber && isBinary;
3346
- }
3347
- /**
3348
- * Detect plain text format
3349
- */
3350
- detectPlainText(buffer) {
3351
- const sample = buffer.subarray(0, Math.min(buffer.length, 512));
3352
- if (sample.length === 0) return false;
3353
- let binaryBytes = 0;
3354
- for (const byte of sample) {
3355
- if (byte === 0 || byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
3356
- binaryBytes++;
3357
- }
3358
- }
3359
- return binaryBytes / sample.length < 0.05;
3360
- }
3361
- /**
3362
- * Check if buffer contains binary content
3363
- */
3364
- isBinaryContent(buffer) {
3365
- const sample = buffer.subarray(0, Math.min(buffer.length, 512));
3366
- let binaryBytes = 0;
3367
- for (const byte of sample) {
3368
- if (byte === 0 || byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
3369
- binaryBytes++;
3370
- }
3371
- }
3372
- return binaryBytes / sample.length > 0.1;
3373
- }
3374
- };
3375
- }
3376
- });
3377
- function deepClone3(obj) {
3378
- if (obj === null || typeof obj !== "object") {
3379
- return obj;
3380
- }
3381
- if (Array.isArray(obj)) {
3382
- return obj.map((item) => deepClone3(item));
3383
- }
3384
- const cloned = {};
3385
- for (const key in obj) {
3386
- if (Object.hasOwn(obj, key)) {
3387
- cloned[key] = deepClone3(obj[key]);
3388
- }
3389
- }
3390
- return cloned;
3391
- }
3392
- function deepFreeze3(obj) {
3393
- Object.freeze(obj);
3394
- for (const key in obj) {
3395
- if (Object.hasOwn(obj, key)) {
3396
- const value = obj[key];
3397
- if (value !== null && typeof value === "object") {
3398
- deepFreeze3(value);
3399
- }
3400
- }
3401
- }
3402
- return obj;
3403
- }
3404
- async function ensureCatalogLoaded3() {
3405
- if (catalogCache3 !== null) {
3406
- return;
3407
- }
3408
- catalogCache3 = await loadMimeTypeCatalog();
3409
- for (const mimeType of catalogCache3.types) {
3410
- mimeStringIndex.set(mimeType.mime.toLowerCase(), mimeType);
3411
- for (const ext of mimeType.extensions) {
3412
- const normalized = ext.toLowerCase().replace(/^\./, "");
3413
- extensionIndex.set(normalized, mimeType);
3414
- }
3415
- }
3416
- detectorInstance = createDetector(mimeStringIndex);
3417
- }
3418
- async function getMimeType(mimeString) {
3419
- await ensureCatalogLoaded3();
3420
- const normalized = mimeString.toLowerCase();
3421
- const mimeType = mimeStringIndex.get(normalized);
3422
- return mimeType ? deepFreeze3(deepClone3(mimeType)) : null;
3423
- }
3424
- async function getMimeTypeByExtension(extension) {
3425
- await ensureCatalogLoaded3();
3426
- const normalized = extension.toLowerCase().replace(/^\./, "");
3427
- const mimeType = extensionIndex.get(normalized);
3428
- return mimeType ? deepFreeze3(deepClone3(mimeType)) : null;
3429
- }
3430
- async function isSupportedMimeType(mime) {
3431
- await ensureCatalogLoaded3();
3432
- return mimeStringIndex.has(mime.toLowerCase());
3433
- }
3434
- async function detectMimeType(input, options) {
3435
- await ensureCatalogLoaded3();
3436
- if (!detectorInstance) {
3437
- throw new Error("Detector not initialized");
3438
- }
3439
- if (typeof input === "string") {
3440
- return detectMimeTypeFromFile(input, options);
3441
- }
3442
- if (Buffer.isBuffer(input)) {
3443
- return detectMimeTypeFromBuffer(input, options);
3444
- }
3445
- return detectMimeTypeFromStream(input, options);
3446
- }
3447
- async function detectMimeTypeFromFile(filePath, options = {}) {
3448
- await ensureCatalogLoaded3();
3449
- if (!detectorInstance) {
3450
- throw new Error("Detector not initialized");
3451
- }
3452
- const bytesToRead = options.bytesToRead || 512;
3453
- if (typeof Bun !== "undefined") {
3454
- const file = Bun.file(filePath);
3455
- if (!await file.exists()) {
3456
- return null;
3457
- }
3458
- const slice = file.slice(0, bytesToRead);
3459
- const arrayBuffer = await slice.arrayBuffer();
3460
- const buffer = Buffer.from(arrayBuffer);
3461
- return detectMimeTypeFromBuffer(buffer, options);
3462
- }
3463
- try {
3464
- const buffer = await readFile(filePath, { encoding: null });
3465
- const sample = buffer.subarray(0, Math.min(buffer.length, bytesToRead));
3466
- return detectMimeTypeFromBuffer(sample, options);
3467
- } catch (error) {
3468
- if (error.code === "ENOENT") {
3469
- return null;
3470
- }
3471
- throw error;
3472
- }
3473
- }
3474
- function detectMimeTypeFromBuffer(buffer, options = {}) {
3475
- if (!detectorInstance) {
3476
- throw new Error("Detector not initialized");
3477
- }
3478
- const result = detectorInstance.detect(buffer, options);
3479
- return result ? deepFreeze3(deepClone3(result)) : null;
3480
- }
3481
- async function detectMimeTypeFromStream(stream, options = {}) {
3482
- await ensureCatalogLoaded3();
3483
- const bytesToRead = options.bytesToRead || 512;
3484
- const chunks = [];
3485
- let totalBytes = 0;
3486
- const webStream = typeof stream.getReader === "function" ? stream : Readable.toWeb(stream);
3487
- const reader = webStream.getReader();
3488
- try {
3489
- while (totalBytes < bytesToRead) {
3490
- const { value, done } = await reader.read();
3491
- if (done) break;
3492
- chunks.push(value);
3493
- totalBytes += value.length;
3494
- }
3495
- const buffer = Buffer.concat(chunks.map((c) => Buffer.from(c)));
3496
- const sample = buffer.subarray(0, Math.min(buffer.length, bytesToRead));
3497
- return detectMimeTypeFromBuffer(sample, options);
3498
- } finally {
3499
- reader.releaseLock();
3500
- }
3501
- }
3502
- function matchMagicNumber(buffer, mimeType) {
3503
- if (!detectorInstance) {
3504
- throw new Error("Detector not initialized");
3505
- }
3506
- const result = detectorInstance.detect(buffer);
3507
- return result?.mime === mimeType;
3508
- }
3509
- async function listMimeTypes() {
3510
- await ensureCatalogLoaded3();
3511
- return Array.from(mimeStringIndex.values()).map((m) => deepFreeze3(deepClone3(m)));
3512
- }
3513
- function clearMimeTypeCache() {
3514
- catalogCache3 = null;
3515
- mimeStringIndex.clear();
3516
- extensionIndex.clear();
3517
- detectorInstance = null;
3518
- }
3519
- var catalogCache3, mimeStringIndex, extensionIndex, detectorInstance;
3520
- var init_mime_types = __esm({
3521
- "src/foundry/mime-types.ts"() {
3522
- init_detector();
3523
- init_loader();
3524
- catalogCache3 = null;
3525
- mimeStringIndex = /* @__PURE__ */ new Map();
3526
- extensionIndex = /* @__PURE__ */ new Map();
3527
- detectorInstance = null;
3528
- }
3529
- });
3530
- function deepClone4(obj) {
3531
- if (obj === null || typeof obj !== "object") {
3532
- return obj;
3533
- }
3534
- if (Array.isArray(obj)) {
3535
- return obj.map((item) => deepClone4(item));
3536
- }
3537
- const cloned = {};
3538
- for (const key in obj) {
3539
- if (Object.hasOwn(obj, key)) {
3540
- cloned[key] = deepClone4(obj[key]);
3541
- }
3542
- }
3543
- return cloned;
3544
- }
3545
- function deepFreeze4(obj) {
3546
- Object.freeze(obj);
3547
- for (const key in obj) {
3548
- if (Object.hasOwn(obj, key)) {
3549
- const value = obj[key];
3550
- if (value !== null && typeof value === "object") {
3551
- deepFreeze4(value);
3552
- }
3553
- }
3554
- }
3555
- return obj;
3556
- }
3557
- async function ensureCatalogLoaded4() {
3558
- if (catalogCache4 !== null) {
3559
- return;
3560
- }
3561
- catalogCache4 = await loadPatternCatalog();
3562
- for (const pattern of catalogCache4.patterns) {
3563
- patternIndex.set(pattern.id, pattern);
3564
- }
3565
- }
3566
- async function getPattern(id) {
3567
- await ensureCatalogLoaded4();
3568
- const pattern = patternIndex.get(id);
3569
- return pattern ? deepFreeze4(deepClone4(pattern)) : null;
3570
- }
3571
- async function getPatternRegex(id) {
3572
- await ensureCatalogLoaded4();
3573
- const pattern = patternIndex.get(id);
3574
- if (!pattern) {
3575
- return null;
3576
- }
3577
- if (pattern.kind !== "regex") {
3578
- throw FoundryCatalogError.invalidSchema(
3579
- "patterns",
3580
- `Pattern '${id}' is not a regex pattern (kind: ${pattern.kind})`
3581
- );
3582
- }
3583
- const cached = compiledRegexCache.get(id);
3584
- if (cached !== void 0) {
3585
- return cached;
3586
- }
3587
- let flags = "";
3588
- if (pattern.flags?.typescript?.ignoreCase) {
3589
- flags += "i";
3590
- }
3591
- const hasUnicodePropertyEscapes = /\\p\{/.test(pattern.pattern);
3592
- if (pattern.flags?.typescript?.unicode || hasUnicodePropertyEscapes) {
3593
- flags += "u";
3594
- }
3595
- const regex = new RegExp(pattern.pattern, flags);
3596
- compiledRegexCache.set(id, regex);
3597
- return regex;
3598
- }
3599
- function getCompiledGlob(id, pattern) {
3600
- const cached = compiledGlobCache.get(id);
3601
- if (cached !== void 0) {
3602
- return cached;
3603
- }
3604
- const matcher = picomatch(pattern);
3605
- compiledGlobCache.set(id, matcher);
3606
- return matcher;
3607
- }
3608
- async function matchPattern(id, value) {
3609
- await ensureCatalogLoaded4();
3610
- const pattern = patternIndex.get(id);
3611
- if (!pattern) {
3612
- throw FoundryCatalogError.missingCatalog(`Pattern '${id}' not found`);
3613
- }
3614
- if (pattern.kind === "regex") {
3615
- const regex = await getPatternRegex(id);
3616
- return regex ? regex.test(value) : false;
3617
- }
3618
- if (pattern.kind === "glob") {
3619
- const matcher = getCompiledGlob(id, pattern.pattern);
3620
- return matcher(value);
3621
- }
3622
- if (pattern.kind === "literal") {
3623
- return pattern.pattern === value;
3624
- }
3625
- throw FoundryCatalogError.invalidSchema("patterns", `Unknown pattern kind: ${pattern.kind}`);
3626
- }
3627
- async function listPatterns() {
3628
- await ensureCatalogLoaded4();
3629
- return Array.from(patternIndex.values()).map((p) => deepFreeze4(deepClone4(p)));
3630
- }
3631
- async function describePattern(id) {
3632
- const pattern = await getPattern(id);
3633
- return pattern?.description ?? null;
3634
- }
3635
- function clearPatternCache() {
3636
- catalogCache4 = null;
3637
- patternIndex.clear();
3638
- compiledRegexCache.clear();
3639
- compiledGlobCache.clear();
3640
- }
3641
- var catalogCache4, patternIndex, compiledRegexCache, compiledGlobCache;
3642
- var init_patterns = __esm({
3643
- "src/foundry/patterns.ts"() {
3644
- init_errors2();
3645
- init_loader();
3646
- catalogCache4 = null;
3647
- patternIndex = /* @__PURE__ */ new Map();
3648
- compiledRegexCache = /* @__PURE__ */ new Map();
3649
- compiledGlobCache = /* @__PURE__ */ new Map();
3650
- }
3651
- });
3652
- function getConfigPath() {
3653
- if (__dirname3.includes("/dist/")) {
3654
- return join(__dirname3, "../../config/crucible-ts/library/foundry/signals.yaml");
3655
- }
3656
- return join(__dirname3, "../../../config/crucible-ts/library/foundry/signals.yaml");
3657
- }
3658
- async function loadCatalog2() {
3659
- const filePath = SSOT_PATHS2.signals;
3660
- const catalogName = "signals";
3661
- try {
3662
- let content;
3663
- if (typeof Bun !== "undefined") {
3664
- try {
3665
- const file = Bun.file(filePath);
3666
- if (!await file.exists()) {
3667
- throw FoundryCatalogError.missingCatalog(catalogName);
3668
- }
3669
- content = await file.text();
3670
- } catch (error) {
3671
- if (error instanceof Error && error.message.includes("No such file")) {
3672
- throw FoundryCatalogError.missingCatalog(catalogName);
3673
- }
3674
- throw error;
3675
- }
3676
- } else {
3677
- try {
3678
- content = await readFile(filePath, "utf-8");
3679
- } catch (error) {
3680
- if (error.code === "ENOENT") {
3681
- throw FoundryCatalogError.missingCatalog(catalogName);
3682
- }
3683
- throw error;
3684
- }
3685
- }
3686
- const data = parse(content);
3687
- const result = await validateDataBySchemaId(data, SCHEMA_ID);
3688
- if (!result.valid) {
3689
- const errorMessages = result.diagnostics.map((d) => `${d.pointer}: ${d.message}`).join("; ");
3690
- throw FoundryCatalogError.invalidSchema(
3691
- catalogName,
3692
- `Schema validation failed: ${errorMessages}`
3693
- );
3694
- }
3695
- return data;
3696
- } catch (error) {
3697
- if (error instanceof FoundryCatalogError) {
3698
- throw error;
3699
- }
3700
- const err = error;
3701
- if (err.code === "ENOENT") {
3702
- throw FoundryCatalogError.missingCatalog(catalogName);
3703
- } else if (err.code === "EACCES") {
3704
- throw FoundryCatalogError.invalidSchema(
3705
- catalogName,
3706
- "Permission denied accessing catalog file",
3707
- err
3708
- );
3709
- } else if (err.code === "EISDIR") {
3710
- throw FoundryCatalogError.invalidSchema(
3711
- catalogName,
3712
- "Expected file but found directory",
3713
- err
3714
- );
3715
- } else if (err.code === "EMFILE" || err.code === "ENFILE") {
3716
- throw FoundryCatalogError.invalidSchema(catalogName, "Too many open files", err);
3717
- }
3718
- throw FoundryCatalogError.invalidSchema(catalogName, "Failed to load catalog", err);
3719
- }
3720
- }
3721
- async function getCatalog() {
3722
- if (!cachedCatalog) {
3723
- cachedCatalog = await loadCatalog2();
3724
- }
3725
- return cachedCatalog;
3726
- }
3727
- async function getSignalsVersion() {
3728
- const catalog = await getCatalog();
3729
- return catalog.version;
3730
- }
3731
- async function listSignals() {
3732
- const catalog = await getCatalog();
3733
- return catalog.signals.map((signal) => ({ ...signal }));
3734
- }
3735
- async function getSignal(identifier) {
3736
- const catalog = await getCatalog();
3737
- const signal = catalog.signals.find((s) => s.id === identifier || s.name === identifier);
3738
- return signal ? { ...signal } : null;
3739
- }
3740
- async function listBehaviors() {
3741
- const catalog = await getCatalog();
3742
- return catalog.behaviors.map((behavior) => ({ ...behavior }));
3743
- }
3744
- async function getBehavior(id) {
3745
- const catalog = await getCatalog();
3746
- const behavior = catalog.behaviors.find((b) => b.id === id);
3747
- return behavior ? { ...behavior } : null;
3748
- }
3749
- async function getSignalCatalog() {
3750
- return await getCatalog();
3751
- }
3752
- var __filename2, __dirname3, SSOT_PATHS2, SCHEMA_ID, cachedCatalog;
3753
- var init_catalog = __esm({
3754
- "src/foundry/signals/catalog.ts"() {
3755
- init_validator();
3756
- init_errors2();
3757
- __filename2 = fileURLToPath(import.meta.url);
3758
- __dirname3 = dirname(__filename2);
3759
- SSOT_PATHS2 = {
3760
- signals: getConfigPath()
3761
- };
3762
- SCHEMA_ID = "library/foundry/v1.0.0/signals";
3763
- cachedCatalog = null;
3764
- }
3765
- });
3766
-
3767
- // src/foundry/signals/capabilities.ts
3768
- function getPlatform2() {
3769
- const platform = process.platform;
3770
- switch (platform) {
3771
- case "linux":
3772
- return "linux";
3773
- case "darwin":
3774
- return "darwin";
3775
- case "win32":
3776
- return "win32";
3777
- case "freebsd":
3778
- return "freebsd";
3779
- default:
3780
- return "unknown";
3781
- }
3782
- }
3783
- function isPOSIX2() {
3784
- const platform = getPlatform2();
3785
- return platform === "linux" || platform === "darwin" || platform === "freebsd";
3786
- }
3787
- function isWindows2() {
3788
- return getPlatform2() === "win32";
3789
- }
3790
- async function supportsSignal(signalName) {
3791
- const signal = await getSignal(signalName);
3792
- if (!signal) {
3793
- return false;
3794
- }
3795
- if (isPOSIX2()) {
3796
- return true;
3797
- }
3798
- if (isWindows2()) {
3799
- return signal.windows_event !== null;
3800
- }
3801
- return false;
3802
- }
3803
- function supportsSignalExitCodes2() {
3804
- return isPOSIX2();
3805
- }
3806
- async function getPlatformCapabilities2() {
3807
- const platform = getPlatform2();
3808
- const isPosix = isPOSIX2();
3809
- const isWin = isWindows2();
3810
- const catalog = await getSignalCatalog();
3811
- const supported = [];
3812
- const unsupported = [];
3813
- const mapped = [];
3814
- for (const signal of catalog.signals) {
3815
- if (isPosix) {
3816
- supported.push(signal.name);
3817
- } else if (isWin) {
3818
- if (signal.windows_event !== null) {
3819
- supported.push(signal.name);
3820
- mapped.push(signal.name);
3821
- } else {
3822
- unsupported.push(signal.name);
3823
- }
3824
- } else {
3825
- unsupported.push(signal.name);
3826
- }
3827
- }
3828
- return {
3829
- platform,
3830
- isPOSIX: isPosix,
3831
- isWindows: isWin,
3832
- supportsNativeSignals: isPosix,
3833
- supportsSignalExitCodes: supportsSignalExitCodes2(),
3834
- supportedSignals: supported,
3835
- unsupportedSignals: unsupported,
3836
- mappedSignals: mapped
3837
- };
3838
- }
3839
- async function getSignalNumber(signalName) {
3840
- const signal = await getSignal(signalName);
3841
- if (!signal) {
3842
- return null;
3843
- }
3844
- const platform = getPlatform2();
3845
- if (signal.platform_overrides) {
3846
- if (platform === "darwin" && signal.platform_overrides.darwin !== void 0) {
3847
- return signal.platform_overrides.darwin;
3848
- }
3849
- if (platform === "freebsd" && signal.platform_overrides.freebsd !== void 0) {
3850
- return signal.platform_overrides.freebsd;
3851
- }
3852
- }
3853
- return signal.unix_number;
3854
- }
3855
- async function getWindowsEvent(signalName) {
3856
- const signal = await getSignal(signalName);
3857
- if (!signal) {
3858
- return null;
3859
- }
3860
- return signal.windows_event;
3861
- }
3862
- var init_capabilities2 = __esm({
3863
- "src/foundry/signals/capabilities.ts"() {
3864
- init_catalog();
3865
- }
3866
- });
3867
-
3868
- // src/foundry/signals/config-reload-endpoint.ts
3869
- function createConfigReloadEndpoint(options) {
3870
- const { loader, validator, onReload: onReload2, auth, rateLimit, logger, telemetry } = options;
3871
- return async (payload, req) => {
3872
- const correlationId = payload.correlation_id ?? generateCorrelationId();
3873
- const authResult = await auth(req);
3874
- if (!authResult.authenticated) {
3875
- if (logger) {
3876
- logger.warn("Config reload endpoint: authentication failed", {
3877
- correlation_id: correlationId,
3878
- reason: authResult.reason
3879
- });
3880
- }
3881
- if (telemetry) {
3882
- telemetry.emit("fulmen.config.http_endpoint.auth_failed", {
3883
- correlation_id: correlationId
3884
- });
3885
- }
3886
- return {
3887
- status: "error",
3888
- error: "authentication_failed",
3889
- message: authResult.reason || "Authentication required",
3890
- statusCode: 401
3891
- };
3892
- }
3893
- const identity = authResult.identity || "unknown";
3894
- if (rateLimit) {
3895
- const rateLimitResult = await rateLimit(identity);
3896
- if (!rateLimitResult.allowed) {
3897
- if (logger) {
3898
- logger.warn("Config reload endpoint: rate limit exceeded", {
3899
- correlation_id: correlationId,
3900
- identity
3901
- });
3902
- }
3903
- if (telemetry) {
3904
- telemetry.emit("fulmen.config.http_endpoint.rate_limited", {
3905
- correlation_id: correlationId
3906
- });
3907
- }
3908
- return {
3909
- status: "error",
3910
- error: "rate_limit_exceeded",
3911
- message: "Rate limit exceeded. Please try again later.",
3912
- statusCode: 429
3913
- };
3914
- }
3915
- }
3916
- if (telemetry) {
3917
- telemetry.emit("fulmen.config.http_endpoint.reload_requested", {
3918
- correlation_id: correlationId
3919
- });
3920
- }
3921
- try {
3922
- const config = await loader();
3923
- if (validator) {
3924
- const validation = await validator(config);
3925
- if (!validation.valid) {
3926
- if (logger) {
3927
- logger.warn("Config reload endpoint: validation failed", {
3928
- correlation_id: correlationId,
3929
- error_count: validation.errors?.length ?? 0
3930
- });
3931
- }
3932
- if (telemetry) {
3933
- telemetry.emit("fulmen.config.http_endpoint.reload_rejected", {
3934
- correlation_id: correlationId,
3935
- reason: "validation_failed"
3936
- });
3937
- }
3938
- return {
3939
- status: "error",
3940
- error: "validation_failed",
3941
- message: "Configuration validation failed",
3942
- validation_errors: validation.errors,
3943
- statusCode: 422
3944
- };
3945
- }
3946
- }
3947
- if (onReload2) {
3948
- await onReload2(config);
3949
- }
3950
- if (telemetry) {
3951
- telemetry.emit("fulmen.config.http_endpoint.reload_accepted", {
3952
- correlation_id: correlationId
3953
- });
3954
- }
3955
- if (logger) {
3956
- logger.info("Config reload endpoint: reload accepted", {
3957
- correlation_id: correlationId,
3958
- reason: payload.reason
3959
- });
3960
- }
3961
- return {
3962
- status: "reloaded",
3963
- correlation_id: correlationId,
3964
- message: "Configuration reloaded",
3965
- statusCode: 200
3966
- };
3967
- } catch (error) {
3968
- if (logger) {
3969
- logger.warn("Config reload endpoint: reload failed", {
3970
- correlation_id: correlationId,
3971
- error: error instanceof Error ? error.message : String(error)
3972
- });
3973
- }
3974
- if (telemetry) {
3975
- telemetry.emit("fulmen.config.http_endpoint.reload_error", {
3976
- correlation_id: correlationId,
3977
- error_type: error instanceof Error ? error.constructor.name : "unknown"
3978
- });
3979
- }
3980
- return {
3981
- status: "error",
3982
- error: "reload_failed",
3983
- message: error instanceof Error ? error.message : String(error),
3984
- statusCode: 500
3985
- };
3986
- }
3987
- };
3988
- }
3989
- function generateCorrelationId() {
3990
- return `cfg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
3991
- }
3992
- var init_config_reload_endpoint = __esm({
3993
- "src/foundry/signals/config-reload-endpoint.ts"() {
3994
- }
3995
- });
3996
-
3997
- // src/appidentity/runtime.ts
3998
- function detectRuntime() {
3999
- const versions = process.versions;
4000
- if (typeof versions.bun === "string" && versions.bun.length > 0) {
4001
- return { name: "bun", version: versions.bun };
4002
- }
4003
- if (typeof versions.node === "string" && versions.node.length > 0) {
4004
- return { name: "node", version: versions.node };
4005
- }
4006
- return { name: "unknown" };
4007
- }
4008
- function buildRuntimeInfo(options = {}) {
4009
- const runtime = detectRuntime();
4010
- const serviceName = options.serviceName ?? options.identity?.app.binary_name ?? "unknown-service";
4011
- const vendor = options.vendor ?? options.identity?.app.vendor;
4012
- return {
4013
- service: {
4014
- name: serviceName,
4015
- vendor,
4016
- version: options.version
4017
- },
4018
- runtime,
4019
- platform: {
4020
- os: process.platform,
4021
- arch: process.arch
4022
- }
4023
- };
4024
- }
4025
- var init_runtime = __esm({
4026
- "src/appidentity/runtime.ts"() {
4027
- }
4028
- });
4029
-
4030
- // src/foundry/signals/control-discovery-endpoint.ts
4031
- function createControlDiscoveryEndpoint(options) {
4032
- const { identity, version, endpoints, auth, authSummary, logger, telemetry } = options;
4033
- return async (req) => {
4034
- if (auth) {
4035
- const authResult = await auth(req);
4036
- if (!authResult.authenticated) {
4037
- if (logger) {
4038
- logger.warn("Control discovery endpoint: authentication failed", {
4039
- reason: authResult.reason
4040
- });
4041
- }
4042
- if (telemetry) {
4043
- telemetry.emit("fulmen.control.discovery.auth_failed", {
4044
- service: identity.app.binary_name
4045
- });
4046
- }
4047
- return {
4048
- status: "error",
4049
- error: "authentication_failed",
4050
- message: authResult.reason || "Authentication required",
4051
- statusCode: 401
4052
- };
4053
- }
4054
- }
4055
- if (telemetry) {
4056
- telemetry.emit("fulmen.control.discovery.served", {
4057
- service: identity.app.binary_name
4058
- });
4059
- }
4060
- const runtime = buildRuntimeInfo({ identity, version });
4061
- return {
4062
- status: "ok",
4063
- service: {
4064
- name: identity.app.binary_name,
4065
- vendor: identity.app.vendor,
4066
- version
4067
- },
4068
- runtime: {
4069
- name: runtime.runtime.name,
4070
- version: runtime.runtime.version,
4071
- platform: runtime.platform.os,
4072
- arch: runtime.platform.arch
4073
- },
4074
- auth_summary: authSummary,
4075
- endpoints,
4076
- statusCode: 200
4077
- };
4078
- };
4079
- }
4080
- var init_control_discovery_endpoint = __esm({
4081
- "src/foundry/signals/control-discovery-endpoint.ts"() {
4082
- init_runtime();
4083
- }
4084
- });
4085
-
4086
- // src/foundry/signals/convenience.ts
4087
- async function onShutdown(manager, handler, options = {}) {
4088
- await manager.register("SIGTERM", handler, options);
4089
- await manager.register("SIGINT", handler, options);
4090
- }
4091
- async function onReload(manager, handler, options = {}) {
4092
- await manager.register("SIGHUP", handler, options);
4093
- }
4094
- async function onUSR1(manager, handler, options = {}) {
4095
- await manager.register("SIGUSR1", handler, options);
4096
- }
4097
- async function onUSR2(manager, handler, options = {}) {
4098
- await manager.register("SIGUSR2", handler, options);
4099
- }
4100
- async function onEmergencyQuit(manager, handler, options = {}) {
4101
- await manager.register("SIGQUIT", handler, options);
4102
- }
4103
- async function onAnyShutdown(manager, handler, options = {}) {
4104
- await manager.register("SIGTERM", handler, options);
4105
- await manager.register("SIGINT", handler, options);
4106
- await manager.register("SIGQUIT", handler, options);
4107
- }
4108
- var init_convenience = __esm({
4109
- "src/foundry/signals/convenience.ts"() {
4110
- }
4111
- });
4112
-
4113
- // src/foundry/signals/double-tap.ts
4114
- async function createDoubleTapTracker(signalName, config = {}) {
4115
- const signal = await getSignal(signalName);
4116
- const defaultWindowMs = signal?.double_tap_window_seconds ? signal.double_tap_window_seconds * 1e3 : 2e3;
4117
- const defaultExitCode = signal?.double_tap_exit_code || 130;
4118
- const defaultHintMessage = signal?.double_tap_message || "Press Ctrl+C again within 2s to force quit";
4119
- return {
4120
- firstTapTime: null,
4121
- windowMs: config.windowMs ?? defaultWindowMs,
4122
- exitCode: config.exitCode ?? defaultExitCode,
4123
- hintMessage: config.hintMessage ?? defaultHintMessage,
4124
- logger: config.logger,
4125
- testMode: config.testMode ?? false
4126
- };
4127
- }
4128
- function handleDoubleTap(state) {
4129
- const now = Date.now();
4130
- if (state.firstTapTime === null) {
4131
- state.firstTapTime = now;
4132
- if (state.logger) {
4133
- state.logger.info(state.hintMessage);
4134
- } else {
4135
- console.log(state.hintMessage);
4136
- }
4137
- return false;
4138
- }
4139
- const elapsed = now - state.firstTapTime;
4140
- if (elapsed < state.windowMs) {
4141
- if (state.logger) {
4142
- state.logger.info("Force quitting...");
4143
- } else {
4144
- console.log("Force quitting...");
4145
- }
4146
- if (!state.testMode) {
4147
- process.exit(state.exitCode);
4148
- }
4149
- return true;
4150
- }
4151
- state.firstTapTime = now;
4152
- if (state.logger) {
4153
- state.logger.info(state.hintMessage);
4154
- } else {
4155
- console.log(state.hintMessage);
4156
- }
4157
- return false;
4158
- }
4159
- function resetDoubleTap(state) {
4160
- state.firstTapTime = null;
4161
- }
4162
- function isWithinWindow(state) {
4163
- if (state.firstTapTime === null) {
4164
- return false;
4165
- }
4166
- const elapsed = Date.now() - state.firstTapTime;
4167
- return elapsed < state.windowMs;
4168
- }
4169
- function getWindowTimeRemaining(state) {
4170
- if (state.firstTapTime === null) {
4171
- return null;
4172
- }
4173
- const elapsed = Date.now() - state.firstTapTime;
4174
- const remaining = state.windowMs - elapsed;
4175
- return remaining > 0 ? remaining : null;
4176
- }
4177
- var init_double_tap = __esm({
4178
- "src/foundry/signals/double-tap.ts"() {
4179
- init_catalog();
4180
- }
4181
- });
4182
-
4183
- // src/foundry/signals/windows.ts
4184
- async function handleWindowsFallback(signalName, options = {}) {
4185
- const signal = await getSignal(signalName);
4186
- if (!signal) {
4187
- return {
4188
- supported: false,
4189
- logged: false
4190
- };
4191
- }
4192
- if (signal.windows_event !== null) {
4193
- return {
4194
- supported: true,
4195
- logged: false
4196
- };
4197
- }
4198
- const fallback = signal.windows_fallback;
4199
- if (!fallback) {
4200
- return {
4201
- supported: false,
4202
- logged: false
4203
- };
4204
- }
4205
- if (options.silent) {
4206
- return {
4207
- supported: false,
4208
- fallback,
4209
- logged: false
4210
- };
4211
- }
4212
- const logger = options.logger || defaultLogger;
4213
- const telemetry = options.telemetry;
4214
- const logMeta = {
4215
- signal: signal.name,
4216
- platform: "windows",
4217
- fallback: fallback.fallback_behavior,
4218
- operation_hint: fallback.operation_hint
4219
- };
4220
- logger.info(fallback.log_message, logMeta);
4221
- if (telemetry) {
4222
- telemetry.emit(fallback.telemetry_event, fallback.telemetry_tags);
4223
- }
4224
- return {
4225
- supported: false,
4226
- fallback,
4227
- logged: true
4228
- };
4229
- }
4230
- async function getFallbackMetadata(signalName) {
4231
- const signal = await getSignal(signalName);
4232
- if (!signal || !signal.windows_fallback) {
4233
- return null;
4234
- }
4235
- return signal.windows_fallback;
4236
- }
4237
- async function requiresFallback(signalName) {
4238
- const signal = await getSignal(signalName);
4239
- if (!signal) {
4240
- return false;
4241
- }
4242
- return signal.windows_event === null && signal.windows_fallback !== void 0;
4243
- }
4244
- async function getHttpFallbackGuidance(signalName) {
4245
- const fallback = await getFallbackMetadata(signalName);
4246
- if (!fallback || fallback.fallback_behavior !== "http_admin_endpoint") {
4247
- return null;
4248
- }
4249
- return fallback.operation_hint;
4250
- }
4251
- var defaultLogger;
4252
- var init_windows = __esm({
4253
- "src/foundry/signals/windows.ts"() {
4254
- init_catalog();
4255
- defaultLogger = {
4256
- info(message, meta) {
4257
- if (meta) {
4258
- console.info(message, meta);
4259
- } else {
4260
- console.info(message);
4261
- }
4262
- },
4263
- warn(message, meta) {
4264
- if (meta) {
4265
- console.warn(message, meta);
4266
- } else {
4267
- console.warn(message);
4268
- }
4269
- }
4270
- };
4271
- }
4272
- });
4273
-
4274
- // src/foundry/signals/guards.ts
4275
- async function ensureSupported(signalName, options = {}) {
4276
- const { includeGuidance = true } = options;
4277
- const signal = await getSignal(signalName);
4278
- if (!signal) {
4279
- throw FoundryCatalogError.invalidSchema(
4280
- "signals",
4281
- `Signal "${signalName}" not found in catalog. Valid signals: SIGTERM, SIGINT, SIGHUP, SIGQUIT, SIGPIPE, SIGALRM, SIGUSR1, SIGUSR2`
4282
- );
4283
- }
4284
- const supported = await supportsSignal(signalName);
4285
- if (supported) {
4286
- return;
4287
- }
4288
- let message = `Signal ${signal.name} is not supported on this platform`;
4289
- if (isWindows2() && includeGuidance) {
4290
- const fallback = await getFallbackMetadata(signalName);
4291
- if (fallback) {
4292
- message += `. ${fallback.log_message}`;
4293
- switch (fallback.fallback_behavior) {
4294
- case "http_admin_endpoint":
4295
- message += `. Use HTTP endpoint: ${fallback.operation_hint}`;
4296
- break;
4297
- case "exception_handling":
4298
- message += `. Alternative: ${fallback.operation_hint}`;
4299
- break;
4300
- case "timer_api":
4301
- message += `. Alternative: ${fallback.operation_hint}`;
4302
- break;
4303
- }
4304
- }
4305
- }
4306
- throw FoundryCatalogError.invalidSchema("signals", message);
4307
- }
4308
- function ensureSignalExitCodesSupported() {
4309
- if (!isPOSIX2()) {
4310
- throw FoundryCatalogError.invalidSchema(
4311
- "signals",
4312
- "Signal-based exit codes (128+N pattern) are not supported on this platform. Windows does not propagate signal numbers via exit codes. Use explicit exit codes or monitor via HTTP admin endpoint."
4313
- );
4314
- }
4315
- }
4316
- function ensurePOSIX() {
4317
- if (!isPOSIX2()) {
4318
- throw FoundryCatalogError.invalidSchema(
4319
- "signals",
4320
- "This operation requires a POSIX-compliant platform (Linux, macOS, FreeBSD). Current platform does not support native signal handling."
4321
- );
4322
- }
4323
- }
4324
- function ensureWindows() {
4325
- if (!isWindows2()) {
4326
- throw FoundryCatalogError.invalidSchema(
4327
- "signals",
4328
- "This operation requires Windows platform. Current platform uses native signals."
4329
- );
4330
- }
4331
- }
4332
- var init_guards = __esm({
4333
- "src/foundry/signals/guards.ts"() {
4334
- init_errors2();
4335
- init_capabilities2();
4336
- init_catalog();
4337
- init_windows();
4338
- }
4339
- });
4340
-
4341
- // src/foundry/signals/http-helper.ts
4342
- function createSignalEndpoint(options) {
4343
- const { manager, auth, rateLimit, logger, telemetry, allowedSignals } = options;
4344
- return async (payload, req) => {
4345
- const correlationId = payload.correlation_id ?? generateCorrelationId2();
4346
- const authResult = await auth(req);
4347
- if (!authResult.authenticated) {
4348
- if (logger) {
4349
- logger.warn("Signal endpoint: authentication failed", {
4350
- correlation_id: correlationId,
4351
- reason: authResult.reason
4352
- });
4353
- }
4354
- if (telemetry) {
4355
- telemetry.emit("fulmen.signal.http_endpoint.auth_failed", {
4356
- correlation_id: correlationId
4357
- });
4358
- }
4359
- return {
4360
- status: "error",
4361
- error: "authentication_failed",
4362
- message: authResult.reason || "Authentication required",
4363
- statusCode: 401
4364
- };
4365
- }
4366
- const identity = authResult.identity || "unknown";
4367
- if (!payload.signal) {
4368
- return {
4369
- status: "error",
4370
- error: "invalid_request",
4371
- message: "Signal name is required",
4372
- statusCode: 400
4373
- };
4374
- }
4375
- const signalName = normalizeSignalName(payload.signal);
4376
- const defaultAllowed = [
4377
- "SIGHUP",
4378
- "SIGTERM",
4379
- "SIGINT",
4380
- "SIGQUIT",
4381
- "SIGUSR1",
4382
- "SIGUSR2",
4383
- "SIGPIPE",
4384
- "SIGALRM"
4385
- ];
4386
- const allowed = (allowedSignals || defaultAllowed).map((s) => normalizeSignalName(s));
4387
- if (!allowed.includes(signalName)) {
4388
- return {
4389
- status: "error",
4390
- error: "invalid_signal",
4391
- message: `Signal '${payload.signal}' is not recognized. Valid signals: ${allowed.join(", ")}`,
4392
- valid_signals: allowed,
4393
- statusCode: 400
4394
- };
4395
- }
4396
- const supported = await supportsSignal(signalName);
4397
- if (!supported) {
4398
- return {
4399
- status: "error",
4400
- error: "signal_not_supported",
4401
- message: `Signal ${signalName} is not supported on this platform`,
4402
- statusCode: 400
4403
- };
4404
- }
4405
- if (rateLimit) {
4406
- const rateLimitResult = await rateLimit(identity, signalName);
4407
- if (!rateLimitResult.allowed) {
4408
- if (logger) {
4409
- logger.warn("Signal endpoint: rate limit exceeded", {
4410
- correlation_id: correlationId,
4411
- identity,
4412
- signal: signalName
4413
- });
4414
- }
4415
- if (telemetry) {
4416
- telemetry.emit("fulmen.signal.http_endpoint.rate_limited", {
4417
- correlation_id: correlationId,
4418
- signal: signalName
4419
- });
4420
- }
4421
- return {
4422
- status: "error",
4423
- error: "rate_limit_exceeded",
4424
- message: "Rate limit exceeded. Please try again later.",
4425
- statusCode: 429
4426
- };
4427
- }
4428
- }
4429
- if (logger) {
4430
- logger.info("Signal endpoint: signal received", {
4431
- correlation_id: correlationId,
4432
- identity,
4433
- signal: signalName,
4434
- reason: payload.reason
4435
- });
4436
- }
4437
- if (telemetry) {
4438
- telemetry.emit("fulmen.signal.http_endpoint.signal_received", {
4439
- correlation_id: correlationId,
4440
- signal: signalName
4441
- });
4442
- }
4443
- void manager.trigger(signalName).catch((error) => {
4444
- if (logger) {
4445
- logger.warn("Signal handler execution failed", {
4446
- correlation_id: correlationId,
4447
- signal: signalName,
4448
- error: error instanceof Error ? error.message : String(error)
4449
- });
4450
- }
4451
- });
4452
- return {
4453
- status: "accepted",
4454
- signal: signalName,
4455
- correlation_id: correlationId,
4456
- message: "Signal will be processed asynchronously",
4457
- statusCode: 202
4458
- };
4459
- };
4460
- }
4461
- function normalizeSignalName(signal) {
4462
- const upper = signal.toUpperCase();
4463
- if (upper.startsWith("SIG")) {
4464
- return upper;
4465
- }
4466
- return `SIG${upper}`;
4467
- }
4468
- function generateCorrelationId2() {
4469
- return `sig-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
4470
- }
4471
- function createBearerTokenAuth(expectedToken) {
4472
- return (req) => {
4473
- const headers = req.headers;
4474
- const authHeader = headers?.authorization || headers?.Authorization;
4475
- if (!authHeader) {
4476
- return {
4477
- authenticated: false,
4478
- reason: "Missing Authorization header"
4479
- };
4480
- }
4481
- const [scheme, token] = authHeader.split(" ");
4482
- if (scheme !== "Bearer" || token !== expectedToken) {
4483
- return {
4484
- authenticated: false,
4485
- reason: "Invalid bearer token"
4486
- };
4487
- }
4488
- return {
4489
- authenticated: true,
4490
- identity: "bearer-token-user"
4491
- };
4492
- };
4493
- }
4494
- function createSimpleRateLimiter(requestsPerMinute) {
4495
- const requests = /* @__PURE__ */ new Map();
4496
- const windowMs = 6e4;
4497
- return (identity) => {
4498
- const now = Date.now();
4499
- const key = identity;
4500
- let timestamps = requests.get(key) || [];
4501
- timestamps = timestamps.filter((ts) => now - ts < windowMs);
4502
- if (timestamps.length >= requestsPerMinute) {
4503
- const oldestTimestamp = Math.min(...timestamps);
4504
- const resetAt = oldestTimestamp + windowMs;
4505
- return {
4506
- allowed: false,
4507
- remaining: 0,
4508
- reset_at: resetAt
4509
- };
4510
- }
4511
- timestamps.push(now);
4512
- requests.set(key, timestamps);
4513
- return {
4514
- allowed: true,
4515
- remaining: requestsPerMinute - timestamps.length,
4516
- reset_at: now + windowMs
4517
- };
4518
- };
4519
- }
4520
- var init_http_helper = __esm({
4521
- "src/foundry/signals/http-helper.ts"() {
4522
- init_capabilities2();
4523
- }
4524
- });
4525
-
4526
- // src/foundry/signals/manager.ts
4527
- function createSignalManager(options = {}) {
4528
- return new SignalManager(options);
4529
- }
4530
- var SignalManager;
4531
- var init_manager = __esm({
4532
- "src/foundry/signals/manager.ts"() {
4533
- init_capabilities2();
4534
- init_catalog();
4535
- init_double_tap();
4536
- init_windows();
4537
- SignalManager = class {
4538
- handlers = /* @__PURE__ */ new Map();
4539
- nativeListeners = /* @__PURE__ */ new Map();
4540
- options;
4541
- handlerIdCounter = 0;
4542
- doubleTapTrackers = /* @__PURE__ */ new Map();
4543
- shuttingDown = false;
4544
- constructor(options = {}) {
4545
- this.options = {
4546
- defaultTimeoutMs: options.defaultTimeoutMs ?? 3e4,
4547
- timeoutBehavior: options.timeoutBehavior ?? "log_and_continue",
4548
- testMode: options.testMode ?? false,
4549
- doubleTapWindowMs: options.doubleTapWindowMs ?? 2e3,
4550
- doubleTapExitCode: options.doubleTapExitCode ?? 130,
4551
- logger: options.logger,
4552
- telemetry: options.telemetry
4553
- };
4554
- }
4555
- /**
4556
- * Register a signal handler
4557
- *
4558
- * @param signal - Signal name (e.g., "SIGTERM") or NodeJS.Signals
4559
- * @param handler - Handler function
4560
- * @param options - Handler options
4561
- */
4562
- async register(signal, handler, options = {}) {
4563
- const signalName = typeof signal === "string" ? signal : signal;
4564
- const supported = await supportsSignal(signalName);
4565
- if (!supported) {
4566
- if (isWindows2()) {
4567
- await handleWindowsFallback(signalName, {
4568
- logger: this.options.logger,
4569
- telemetry: this.options.telemetry
4570
- });
4571
- }
4572
- return;
4573
- }
4574
- if (!this.handlers.has(signalName)) {
4575
- this.handlers.set(signalName, []);
4576
- }
4577
- const registration = {
4578
- signal: signalName,
4579
- handler,
4580
- priority: options.priority ?? 0,
4581
- timeoutMs: options.timeoutMs ?? this.options.defaultTimeoutMs,
4582
- id: options.id ?? `handler-${++this.handlerIdCounter}`,
4583
- registeredAt: Date.now()
4584
- };
4585
- const handlers = this.handlers.get(signalName);
4586
- if (!handlers) {
4587
- throw new Error(`Handler list not initialized for signal ${signalName}`);
4588
- }
4589
- handlers.push(registration);
4590
- handlers.sort((a, b) => {
4591
- if (a.priority !== b.priority) {
4592
- return b.priority - a.priority;
4593
- }
4594
- return a.registeredAt - b.registeredAt;
4595
- });
4596
- if (!this.nativeListeners.has(signalName)) {
4597
- await this.registerNativeListener(signalName);
4598
- }
4599
- if (this.options.logger) {
4600
- this.options.logger.info(`Signal handler registered: ${signalName}`, {
4601
- handler_id: registration.id,
4602
- priority: registration.priority,
4603
- timeout_ms: registration.timeoutMs
4604
- });
4605
- }
4606
- if (this.options.telemetry) {
4607
- this.options.telemetry.emit("fulmen.signal.handler_registered", {
4608
- signal: signalName,
4609
- handler_id: registration.id,
4610
- priority: String(registration.priority)
4611
- });
4612
- }
4613
- }
4614
- /**
4615
- * Register native Node.js signal listener
4616
- */
4617
- async registerNativeListener(signalName) {
4618
- const signal = await getSignal(signalName);
4619
- if (!signal) {
4620
- return;
4621
- }
4622
- const useDoubleTap = signal.default_behavior === "graceful_shutdown_with_double_tap";
4623
- if (useDoubleTap) {
4624
- const tracker = await createDoubleTapTracker(signalName, {
4625
- windowMs: this.options.doubleTapWindowMs,
4626
- exitCode: this.options.doubleTapExitCode,
4627
- logger: this.options.logger,
4628
- testMode: this.options.testMode
4629
- });
4630
- this.doubleTapTrackers.set(signalName, tracker);
4631
- }
4632
- const listener = async (sig) => {
4633
- if (useDoubleTap) {
4634
- const tracker = this.doubleTapTrackers.get(signalName);
4635
- if (tracker) {
4636
- const forceQuit = handleDoubleTap(tracker);
4637
- if (forceQuit) {
4638
- return;
4639
- }
4640
- }
4641
- }
4642
- await this.executeHandlers(signalName, sig);
4643
- };
4644
- process.on(signalName, listener);
4645
- this.nativeListeners.set(signalName, listener);
4646
- }
4647
- /**
4648
- * Execute all registered handlers for a signal
4649
- */
4650
- async executeHandlers(signalName, signal) {
4651
- const handlers = this.handlers.get(signalName);
4652
- if (!handlers || handlers.length === 0) {
4653
- return;
4654
- }
4655
- this.shuttingDown = true;
4656
- if (this.options.logger) {
4657
- this.options.logger.info(`Signal received: ${signalName}`, {
4658
- handler_count: handlers.length
4659
- });
4660
- }
4661
- for (const registration of handlers) {
4662
- try {
4663
- await this.executeWithTimeout(registration, signal);
4664
- } catch (error) {
4665
- if (this.options.logger) {
4666
- this.options.logger.warn(`Signal handler failed: ${signalName}`, {
4667
- handler_id: registration.id,
4668
- error: error instanceof Error ? error.message : String(error)
4669
- });
4670
- }
4671
- if (this.options.telemetry) {
4672
- this.options.telemetry.emit("fulmen.signal.handler_error", {
4673
- signal: signalName,
4674
- handler_id: registration.id,
4675
- error_type: error instanceof Error ? error.constructor.name : "unknown"
4676
- });
4677
- }
4678
- if (this.options.timeoutBehavior === "force_exit") {
4679
- const exitCode = (await getSignal(signalName))?.exit_code ?? 1;
4680
- if (!this.options.testMode) {
4681
- process.exit(exitCode);
4682
- }
4683
- return;
4684
- }
4685
- }
4686
- }
4687
- const tracker = this.doubleTapTrackers.get(signalName);
4688
- if (tracker) {
4689
- resetDoubleTap(tracker);
4690
- }
4691
- }
4692
- /**
4693
- * Execute a handler with timeout enforcement
4694
- */
4695
- async executeWithTimeout(registration, signal) {
4696
- const timeoutPromise = new Promise((_, reject) => {
4697
- setTimeout(() => {
4698
- reject(new Error(`Handler timeout exceeded: ${registration.timeoutMs}ms`));
4699
- }, registration.timeoutMs);
4700
- });
4701
- const handlerPromise = Promise.resolve(registration.handler(signal));
4702
- try {
4703
- await Promise.race([handlerPromise, timeoutPromise]);
4704
- if (this.options.telemetry) {
4705
- this.options.telemetry.emit("fulmen.signal.handler_completed", {
4706
- signal: registration.signal,
4707
- handler_id: registration.id
4708
- });
4709
- }
4710
- } catch (error) {
4711
- if (this.options.telemetry) {
4712
- this.options.telemetry.emit("fulmen.signal.handler_timeout", {
4713
- signal: registration.signal,
4714
- handler_id: registration.id,
4715
- timeout_ms: String(registration.timeoutMs)
4716
- });
4717
- }
4718
- throw error;
4719
- }
4720
- }
4721
- /**
4722
- * Unregister a signal handler
4723
- *
4724
- * @param signal - Signal name
4725
- * @param handler - Handler to remove (if not provided, removes all handlers)
4726
- */
4727
- unregister(signal, handler) {
4728
- const handlers = this.handlers.get(signal);
4729
- if (!handlers) {
4730
- return;
4731
- }
4732
- if (handler) {
4733
- const index = handlers.findIndex((h) => h.handler === handler);
4734
- if (index !== -1) {
4735
- handlers.splice(index, 1);
4736
- }
4737
- } else {
4738
- handlers.length = 0;
4739
- }
4740
- if (handlers.length === 0) {
4741
- const listener = this.nativeListeners.get(signal);
4742
- if (listener) {
4743
- process.off(signal, listener);
4744
- this.nativeListeners.delete(signal);
4745
- }
4746
- this.handlers.delete(signal);
4747
- }
4748
- }
4749
- /**
4750
- * Check if a signal has registered handlers
4751
- */
4752
- isRegistered(signal) {
4753
- const handlers = this.handlers.get(signal);
4754
- return handlers !== void 0 && handlers.length > 0;
4755
- }
4756
- /**
4757
- * Get handler count for a signal
4758
- */
4759
- getHandlerCount(signal) {
4760
- const handlers = this.handlers.get(signal);
4761
- return handlers?.length ?? 0;
4762
- }
4763
- /**
4764
- * Trigger signal handlers manually (for testing)
4765
- *
4766
- * @param signal - Signal name
4767
- */
4768
- async trigger(signal) {
4769
- const handlers = this.handlers.get(signal);
4770
- if (!handlers || handlers.length === 0) {
4771
- return;
4772
- }
4773
- await this.executeHandlers(signal, signal);
4774
- }
4775
- /**
4776
- * Shutdown the signal manager and cleanup all handlers
4777
- */
4778
- async shutdown() {
4779
- for (const [signal, listener] of this.nativeListeners.entries()) {
4780
- process.off(signal, listener);
4781
- }
4782
- this.nativeListeners.clear();
4783
- this.handlers.clear();
4784
- this.doubleTapTrackers.clear();
4785
- this.shuttingDown = false;
4786
- }
4787
- /**
4788
- * Check if manager is currently shutting down
4789
- */
4790
- isShuttingDown() {
4791
- return this.shuttingDown;
4792
- }
4793
- };
4794
- }
4795
- });
4796
-
4797
- // src/foundry/signals/reload.ts
4798
- function createConfigReloadHandler(options) {
4799
- const {
4800
- loader,
4801
- validator,
4802
- onValidated,
4803
- exitCode = 129,
4804
- logger,
4805
- telemetry,
4806
- testMode = false
4807
- } = options;
4808
- return async () => {
4809
- if (logger) {
4810
- logger.info("Config reload requested (SIGHUP)");
4811
- }
4812
- if (telemetry) {
4813
- telemetry.emit("fulmen.signal.config_reload_requested", {
4814
- signal: "SIGHUP"
4815
- });
4816
- }
4817
- try {
4818
- const newConfig = await loader();
4819
- const result = await validator(newConfig);
4820
- if (!result.valid) {
4821
- if (logger) {
4822
- logger.warn("Config validation failed - continuing with current config", {
4823
- error_count: result.errors?.length ?? 0,
4824
- errors: result.errors
4825
- });
4826
- }
4827
- if (telemetry) {
4828
- telemetry.emit("fulmen.signal.config_reload_rejected", {
4829
- signal: "SIGHUP",
4830
- reason: "validation_failed",
4831
- error_count: String(result.errors?.length ?? 0)
4832
- });
4833
- }
4834
- return;
4835
- }
4836
- if (logger) {
4837
- logger.info("Config validation succeeded - exiting for restart");
4838
- }
4839
- if (telemetry) {
4840
- telemetry.emit("fulmen.signal.config_reload_accepted", {
4841
- signal: "SIGHUP"
4842
- });
4843
- }
4844
- if (onValidated) {
4845
- await onValidated(newConfig);
4846
- }
4847
- if (!testMode) {
4848
- process.exit(exitCode);
4849
- }
4850
- } catch (error) {
4851
- if (logger) {
4852
- logger.warn("Config reload failed with error - continuing with current config", {
4853
- error: error instanceof Error ? error.message : String(error)
4854
- });
4855
- }
4856
- if (telemetry) {
4857
- telemetry.emit("fulmen.signal.config_reload_error", {
4858
- signal: "SIGHUP",
4859
- error_type: error instanceof Error ? error.constructor.name : "unknown"
4860
- });
4861
- }
4862
- }
4863
- };
4864
- }
4865
- var ConfigReloadTracker;
4866
- var init_reload = __esm({
4867
- "src/foundry/signals/reload.ts"() {
4868
- ConfigReloadTracker = class {
4869
- failures = 0;
4870
- lastFailureTime = null;
4871
- maxFailures;
4872
- logger;
4873
- telemetry;
4874
- constructor(options) {
4875
- this.maxFailures = options.maxFailures ?? 3;
4876
- this.logger = options.logger;
4877
- this.telemetry = options.telemetry;
4878
- }
4879
- /**
4880
- * Record a reload failure
4881
- *
4882
- * @returns true if threshold exceeded, false otherwise
4883
- */
4884
- recordFailure() {
4885
- this.failures++;
4886
- this.lastFailureTime = Date.now();
4887
- if (this.failures >= this.maxFailures) {
4888
- if (this.logger) {
4889
- this.logger.warn(
4890
- `${this.failures} consecutive config reload failures - check config source`,
4891
- {
4892
- failure_count: this.failures,
4893
- threshold: this.maxFailures
4894
- }
4895
- );
4896
- }
4897
- if (this.telemetry) {
4898
- this.telemetry.emit("fulmen.signal.config_reload_threshold_exceeded", {
4899
- failure_count: String(this.failures),
4900
- threshold: String(this.maxFailures)
4901
- });
4902
- }
4903
- return true;
4904
- }
4905
- return false;
4906
- }
4907
- /**
4908
- * Record a successful reload (resets counter)
4909
- */
4910
- recordSuccess() {
4911
- this.failures = 0;
4912
- this.lastFailureTime = null;
4913
- }
4914
- /**
4915
- * Get current failure count
4916
- */
4917
- getFailureCount() {
4918
- return this.failures;
4919
- }
4920
- /**
4921
- * Get last failure timestamp
4922
- */
4923
- getLastFailureTime() {
4924
- return this.lastFailureTime;
4925
- }
4926
- };
4927
- }
4928
- });
4929
-
4930
- // src/foundry/signals/index.ts
4931
- var init_signals = __esm({
4932
- "src/foundry/signals/index.ts"() {
4933
- init_capabilities2();
4934
- init_catalog();
4935
- init_config_reload_endpoint();
4936
- init_control_discovery_endpoint();
4937
- init_convenience();
4938
- init_double_tap();
4939
- init_guards();
4940
- init_http_helper();
4941
- init_manager();
4942
- init_reload();
4943
- init_windows();
4944
- }
4945
- });
4946
- function distance(a, b, metric = "levenshtein") {
4947
- switch (metric) {
4948
- case "levenshtein":
4949
- return levenshtein(a, b);
4950
- case "damerau_osa":
4951
- return osa_distance(a, b);
4952
- case "damerau_unrestricted":
4953
- return damerau_levenshtein(a, b);
4954
- case "jaro_winkler":
4955
- return jaro_winkler(a, b);
4956
- case "substring":
4957
- return substringSimilarity(a, b).score;
4958
- default:
4959
- throw new Error(
4960
- `Invalid metric '${metric}': must be one of: levenshtein, damerau_osa, damerau_unrestricted, jaro_winkler, substring`
4961
- );
4962
- }
4963
- }
4964
- var init_distance = __esm({
4965
- "src/foundry/similarity/distance.ts"() {
4966
- }
4967
- });
4968
-
4969
- // src/foundry/similarity/errors.ts
4970
- var init_errors3 = __esm({
4971
- "src/foundry/similarity/errors.ts"() {
4972
- init_errors2();
4973
- }
4974
- });
4975
- function toNormalizationLocale(locale) {
4976
- if (!locale) {
4977
- return void 0;
4978
- }
4979
- if (locale === "tr" || locale === "az" || locale === "lt") {
4980
- return locale;
4981
- }
4982
- return void 0;
4983
- }
4984
- function normalize(value, preset = "default", locale) {
4985
- if (typeof preset === "object") {
4986
- const targetPreset = preset.stripAccents ? "aggressive" : "default";
4987
- const targetLocale = toNormalizationLocale(preset.locale ?? locale);
4988
- return normalize$1(value, targetPreset, targetLocale);
4989
- }
4990
- return normalize$1(value, preset, toNormalizationLocale(locale));
4991
- }
4992
- function casefold(value, locale) {
4993
- if (locale === "tr") {
4994
- return value.toLocaleLowerCase("tr-TR");
4995
- }
4996
- return value.toLowerCase();
4997
- }
4998
- function stripAccents(value) {
4999
- return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
5000
- }
5001
- function equalsIgnoreCase(a, b, options) {
5002
- return normalize(a, options) === normalize(b, options);
5003
- }
5004
- var init_normalization = __esm({
5005
- "src/foundry/similarity/normalization.ts"() {
5006
- }
5007
- });
5008
- function score(a, b, metric = "levenshtein") {
5009
- if (metric === "substring") {
5010
- return substringSimilarity(a, b).score;
5011
- }
5012
- return score$1(a, b, metric);
5013
- }
5014
- var init_score = __esm({
5015
- "src/foundry/similarity/score.ts"() {
5016
- }
5017
- });
5018
- function suggest(input, candidates, options) {
5019
- const metric = options?.metric ?? DEFAULT_METRIC;
5020
- const minScore = options?.minScore ?? DEFAULT_MIN_SCORE;
5021
- const maxSuggestions = options?.maxSuggestions ?? DEFAULT_MAX_SUGGESTIONS;
5022
- let normalizePreset = options?.normalizePreset ?? DEFAULT_NORMALIZE_PRESET;
5023
- if (options?.normalize === false) {
5024
- normalizePreset = "none";
5025
- } else if (options?.normalize === true && !options?.normalizePreset) {
5026
- normalizePreset = "default";
5027
- }
5028
- const wasmOptions = {
5029
- metric,
5030
- normalizePreset,
5031
- minScore,
5032
- maxSuggestions,
5033
- preferPrefix: options?.preferPrefix,
5034
- jaroPrefixScale: options?.jaroPrefixScale,
5035
- jaroMaxPrefix: options?.jaroMaxPrefix
5036
- };
5037
- const results = suggest$1(input, candidates, wasmOptions);
5038
- return results.map((r) => ({
5039
- value: r.value,
5040
- score: r.score,
5041
- matchedRange: r.matchedRange,
5042
- reason: r.reason,
5043
- normalizedValue: r.normalizedValue
5044
- }));
5045
- }
5046
- var DEFAULT_MIN_SCORE, DEFAULT_MAX_SUGGESTIONS, DEFAULT_METRIC, DEFAULT_NORMALIZE_PRESET;
5047
- var init_suggest = __esm({
5048
- "src/foundry/similarity/suggest.ts"() {
5049
- DEFAULT_MIN_SCORE = 0.6;
5050
- DEFAULT_MAX_SUGGESTIONS = 3;
5051
- DEFAULT_METRIC = "levenshtein";
5052
- DEFAULT_NORMALIZE_PRESET = "default";
5053
- }
5054
- });
5055
-
5056
- // src/foundry/similarity/index.ts
5057
- var init_similarity = __esm({
5058
- "src/foundry/similarity/index.ts"() {
5059
- init_distance();
5060
- init_errors3();
5061
- init_normalization();
5062
- init_score();
5063
- init_suggest();
5064
- }
5065
- });
5066
-
5067
- // src/foundry/index.ts
5068
- var foundry_exports = {};
5069
- __export(foundry_exports, {
5070
- ConfigReloadTracker: () => ConfigReloadTracker,
5071
- EXIT_CODES_VERSION: () => EXIT_CODES_VERSION,
5072
- FoundryCatalogError: () => FoundryCatalogError,
5073
- SignalManager: () => SignalManager,
5074
- SimplifiedMode: () => SimplifiedMode,
5075
- VERSION: () => VERSION,
5076
- casefold: () => casefold,
5077
- clearCountryCodeCache: () => clearCountryCodeCache,
5078
- clearHttpStatusCache: () => clearHttpStatusCache,
5079
- clearMimeTypeCache: () => clearMimeTypeCache,
5080
- clearPatternCache: () => clearPatternCache,
5081
- createBearerTokenAuth: () => createBearerTokenAuth,
5082
- createConfigReloadEndpoint: () => createConfigReloadEndpoint,
5083
- createConfigReloadHandler: () => createConfigReloadHandler,
5084
- createControlDiscoveryEndpoint: () => createControlDiscoveryEndpoint,
5085
- createDoubleTapTracker: () => createDoubleTapTracker,
5086
- createSignalEndpoint: () => createSignalEndpoint,
5087
- createSignalManager: () => createSignalManager,
5088
- createSimpleRateLimiter: () => createSimpleRateLimiter,
5089
- describePattern: () => describePattern,
5090
- detectMimeType: () => detectMimeType,
5091
- detectMimeTypeFromBuffer: () => detectMimeTypeFromBuffer,
5092
- detectMimeTypeFromFile: () => detectMimeTypeFromFile,
5093
- detectMimeTypeFromStream: () => detectMimeTypeFromStream,
5094
- distance: () => distance,
5095
- ensurePOSIX: () => ensurePOSIX,
5096
- ensureSignalExitCodesSupported: () => ensureSignalExitCodesSupported,
5097
- ensureSupported: () => ensureSupported,
5098
- ensureWindows: () => ensureWindows,
5099
- equalsIgnoreCase: () => equalsIgnoreCase,
5100
- exitCodeMetadata: () => exitCodeMetadata,
5101
- exitCodes: () => exitCodes,
5102
- getBehavior: () => getBehavior,
5103
- getCountryByAlpha2: () => getCountryByAlpha2,
5104
- getCountryByAlpha3: () => getCountryByAlpha3,
5105
- getCountryByNumeric: () => getCountryByNumeric,
5106
- getExitCodeInfo: () => getExitCodeInfo,
5107
- getFallbackMetadata: () => getFallbackMetadata,
5108
- getHttpFallbackGuidance: () => getHttpFallbackGuidance,
5109
- getHttpStatus: () => getHttpStatus,
5110
- getMimeType: () => getMimeType,
5111
- getMimeTypeByExtension: () => getMimeTypeByExtension,
5112
- getPattern: () => getPattern,
5113
- getPatternRegex: () => getPatternRegex,
5114
- getPlatform: () => getPlatform,
5115
- getPlatformCapabilities: () => getPlatformCapabilities,
5116
- getSignal: () => getSignal,
5117
- getSignalCatalog: () => getSignalCatalog,
5118
- getSignalNumber: () => getSignalNumber,
5119
- getSignalPlatformCapabilities: () => getPlatformCapabilities2,
5120
- getSignalsVersion: () => getSignalsVersion,
5121
- getSimplifiedCodeDescription: () => getSimplifiedCodeDescription,
5122
- getSimplifiedCodes: () => getSimplifiedCodes,
5123
- getStatusReason: () => getStatusReason,
5124
- getWindowTimeRemaining: () => getWindowTimeRemaining,
5125
- getWindowsEvent: () => getWindowsEvent,
5126
- handleDoubleTap: () => handleDoubleTap,
5127
- handleWindowsFallback: () => handleWindowsFallback,
5128
- isClientError: () => isClientError,
5129
- isInformational: () => isInformational,
5130
- isPOSIX: () => isPOSIX,
5131
- isRedirection: () => isRedirection,
5132
- isServerError: () => isServerError,
5133
- isSignalPOSIX: () => isPOSIX2,
5134
- isSignalWindows: () => isWindows2,
5135
- isSuccess: () => isSuccess,
5136
- isSupportedMimeType: () => isSupportedMimeType,
5137
- isWindows: () => isWindows,
5138
- isWithinWindow: () => isWithinWindow,
5139
- listBehaviors: () => listBehaviors,
5140
- listCountries: () => listCountries,
5141
- listHttpStatuses: () => listHttpStatuses,
5142
- listMimeTypes: () => listMimeTypes,
5143
- listPatterns: () => listPatterns,
5144
- listSignals: () => listSignals,
5145
- loadAllCatalogs: () => loadAllCatalogs,
5146
- loadCountryCodeCatalog: () => loadCountryCodeCatalog,
5147
- loadHttpStatusCatalog: () => loadHttpStatusCatalog,
5148
- loadMimeTypeCatalog: () => loadMimeTypeCatalog,
5149
- loadPatternCatalog: () => loadPatternCatalog,
5150
- mapExitCodeToSimplified: () => mapExitCodeToSimplified,
5151
- matchMagicNumber: () => matchMagicNumber,
5152
- matchPattern: () => matchPattern,
5153
- normalize: () => normalize,
5154
- onAnyShutdown: () => onAnyShutdown,
5155
- onEmergencyQuit: () => onEmergencyQuit,
5156
- onReload: () => onReload,
5157
- onShutdown: () => onShutdown,
5158
- onUSR1: () => onUSR1,
5159
- onUSR2: () => onUSR2,
5160
- requiresFallback: () => requiresFallback,
5161
- resetDoubleTap: () => resetDoubleTap,
5162
- score: () => score,
5163
- stripAccents: () => stripAccents,
5164
- suggest: () => suggest,
5165
- supportsSignal: () => supportsSignal,
5166
- supportsSignalBasedExitCodes: () => supportsSignalExitCodes2,
5167
- supportsSignalExitCodes: () => supportsSignalExitCodes
5168
- });
5169
- var VERSION;
5170
- var init_foundry = __esm({
5171
- "src/foundry/index.ts"() {
5172
- init_country_codes();
5173
- init_errors2();
5174
- init_exit_codes();
5175
- init_http_statuses();
5176
- init_loader();
5177
- init_mime_types();
5178
- init_patterns();
5179
- init_signals();
5180
- init_similarity();
5181
- VERSION = "0.1.1";
5182
- }
5183
- });
5184
-
5185
- // src/appidentity/cache.ts
5186
- function getCachedIdentity() {
5187
- return cachedIdentity;
5188
- }
5189
- function setCachedIdentity(identity) {
5190
- cachedIdentity = identity;
5191
- }
5192
- function clearIdentityCache() {
5193
- cachedIdentity = null;
5194
- }
5195
- var cachedIdentity;
5196
- var init_cache = __esm({
5197
- "src/appidentity/cache.ts"() {
5198
- cachedIdentity = null;
5199
- }
5200
- });
5201
-
5202
- // src/appidentity/constants.ts
5203
- var APP_IDENTITY_FILENAME, APP_IDENTITY_DIR, APP_IDENTITY_ENV_VAR, APP_IDENTITY_SCHEMA_ID, MAX_ANCESTOR_SEARCH_DEPTH;
5204
- var init_constants = __esm({
5205
- "src/appidentity/constants.ts"() {
5206
- APP_IDENTITY_FILENAME = "app.yaml";
5207
- APP_IDENTITY_DIR = ".fulmen";
5208
- APP_IDENTITY_ENV_VAR = "FULMEN_APP_IDENTITY_PATH";
5209
- APP_IDENTITY_SCHEMA_ID = "config/repository/app-identity/v1.0.0/app-identity";
5210
- MAX_ANCESTOR_SEARCH_DEPTH = 20;
5211
- }
5212
- });
5213
- var init_correlation = __esm({
5214
- "src/errors/correlation.ts"() {
5215
- }
5216
- });
5217
-
5218
- // src/errors/severity.ts
5219
- function getDefaultSeverity() {
5220
- return {
5221
- name: Severity.MEDIUM,
5222
- level: 2
5223
- };
5224
- }
5225
- var Severity, SEVERITY_LEVELS;
5226
- var init_severity = __esm({
5227
- "src/errors/severity.ts"() {
5228
- Severity = {
5229
- INFO: "info",
5230
- LOW: "low",
5231
- MEDIUM: "medium",
5232
- HIGH: "high",
5233
- CRITICAL: "critical"
5234
- };
5235
- SEVERITY_LEVELS = {
5236
- info: 0,
5237
- low: 1,
5238
- medium: 2,
5239
- high: 3,
5240
- critical: 4
5241
- };
5242
- }
5243
- });
5244
-
5245
- // src/errors/serialization.ts
5246
- function extractErrorMessage(error) {
5247
- if (error instanceof Error) {
5248
- return error.message;
5249
- }
5250
- if (isErrorLike(error)) {
5251
- return error.message;
5252
- }
5253
- if (typeof error === "string") {
5254
- return error;
5255
- }
5256
- return String(error);
5257
- }
5258
- function extractStackTrace(error) {
5259
- if (error instanceof Error) {
5260
- return error.stack;
5261
- }
5262
- if (isErrorLike(error) && typeof error.stack === "string") {
5263
- return error.stack;
5264
- }
5265
- return void 0;
5266
- }
5267
- function isErrorLike(value) {
5268
- return typeof value === "object" && value !== null && "message" in value && typeof value.message === "string";
5269
- }
5270
- var init_serialization = __esm({
5271
- "src/errors/serialization.ts"() {
5272
- init_severity();
5273
- }
5274
- });
5275
-
5276
- // src/errors/validators.ts
5277
- async function validateErrorData(data) {
5278
- return ErrorValidator.getInstance().validate(data);
5279
- }
5280
- var ErrorValidator;
5281
- var init_validators = __esm({
5282
- "src/errors/validators.ts"() {
5283
- init_schema();
5284
- ErrorValidator = class _ErrorValidator {
5285
- static instance;
5286
- validateFn = null;
5287
- initPromise = null;
5288
- initError = null;
5289
- constructor() {
5290
- }
5291
- /**
5292
- * Get singleton instance
5293
- */
5294
- static getInstance() {
5295
- if (!_ErrorValidator.instance) {
5296
- _ErrorValidator.instance = new _ErrorValidator();
5297
- }
5298
- return _ErrorValidator.instance;
5299
- }
5300
- /**
5301
- * Initialize validator (lazy load, async)
5302
- */
5303
- async init() {
5304
- if (this.validateFn !== null || this.initError !== null) {
5305
- return;
5306
- }
5307
- if (this.initPromise) {
5308
- return this.initPromise;
5309
- }
5310
- this.initPromise = (async () => {
5311
- try {
5312
- await compileSchemaById("pathfinder/v1.0.0/error-response");
5313
- await compileSchemaById("assessment/v1.0.0/severity-definitions");
5314
- this.validateFn = await compileSchemaById("error-handling/v1.0.0/error-response");
5315
- } catch (err) {
5316
- this.initError = err instanceof Error ? err : new Error(String(err));
5317
- throw new Error(`Failed to initialize error validator: ${this.initError.message}`);
5318
- }
5319
- })();
5320
- return this.initPromise;
5321
- }
5322
- /**
5323
- * Validate error data against schema
5324
- *
5325
- * @param data - Data to validate
5326
- * @returns Promise resolving to true if valid, false otherwise
5327
- * @throws {Error} If validator failed to initialize
5328
- */
5329
- async validate(data) {
5330
- if (this.validateFn === null) {
5331
- await this.init();
5332
- }
5333
- if (this.initError) {
5334
- throw this.initError;
5335
- }
5336
- if (!this.validateFn) {
5337
- throw new Error("Validator not initialized");
5338
- }
5339
- return this.validateFn(data);
5340
- }
5341
- /**
5342
- * Get validation errors from last validation
5343
- *
5344
- * @returns Validation errors or null
5345
- */
5346
- getErrors() {
5347
- if (!this.validateFn) {
5348
- return null;
5349
- }
5350
- return this.validateFn.errors;
5351
- }
5352
- /**
5353
- * Reset validator state (for testing)
5354
- * @internal
5355
- */
5356
- static _reset() {
5357
- _ErrorValidator.instance = new _ErrorValidator();
5358
- }
5359
- };
5360
- }
5361
- });
5362
-
5363
- // src/errors/fulmen-error.ts
5364
- function isFulmenErrorData(value) {
5365
- return typeof value === "object" && value !== null && "code" in value && typeof value.code === "string" && "message" in value && typeof value.message === "string";
5366
- }
5367
- var FulmenError;
5368
- var init_fulmen_error = __esm({
5369
- "src/errors/fulmen-error.ts"() {
5370
- init_serialization();
5371
- init_severity();
5372
- init_validators();
5373
- FulmenError = class _FulmenError extends Error {
5374
- data;
5375
- constructor(data) {
5376
- super(data.message);
5377
- this.name = "FulmenError";
5378
- this.data = Object.freeze({ ...data });
5379
- Error.captureStackTrace(this, _FulmenError);
5380
- }
5381
- /**
5382
- * Serialize to JSON (schema-compliant)
5383
- */
5384
- toJSON() {
5385
- return this.data;
5386
- }
5387
- /**
5388
- * Check equality with another FulmenError
5389
- */
5390
- equals(other) {
5391
- return JSON.stringify(this.data) === JSON.stringify(other.data);
5392
- }
5393
- /**
5394
- * Get severity level for comparison
5395
- */
5396
- getSeverityLevel() {
5397
- return this.data.severity_level ?? SEVERITY_LEVELS[this.data.severity ?? "medium"];
5398
- }
5399
- /**
5400
- * Wrap an existing error with FulmenError structure
5401
- *
5402
- * @param error - Error to wrap (Error instance or FulmenErrorData)
5403
- * @param options - Additional error options
5404
- * @returns New FulmenError instance
5405
- *
5406
- * @example
5407
- * ```typescript
5408
- * try {
5409
- * throw new Error('Config invalid');
5410
- * } catch (err) {
5411
- * const fulmenErr = FulmenError.wrap(err, {
5412
- * code: 'CONFIG_INVALID',
5413
- * severity: 'high',
5414
- * exit_code: 2
5415
- * });
5416
- * throw fulmenErr;
5417
- * }
5418
- * ```
5419
- */
5420
- static wrap(error, options = {}) {
5421
- if (error instanceof _FulmenError) {
5422
- const effectiveSeverity = options.severity ?? error.data.severity ?? Severity.MEDIUM;
5423
- const effectiveSeverityLevel = SEVERITY_LEVELS[effectiveSeverity];
5424
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
5425
- return new _FulmenError({
5426
- ...error.data,
5427
- ...options,
5428
- code: options.code ?? error.data.code,
5429
- message: error.data.message,
5430
- severity: effectiveSeverity,
5431
- // Consistent severity
5432
- severity_level: effectiveSeverityLevel,
5433
- // Recomputed level
5434
- timestamp
5435
- // Updated timestamp
5436
- });
5437
- }
5438
- if (isFulmenErrorData(error)) {
5439
- const defaultSeverity = getDefaultSeverity();
5440
- const effectiveSeverity = options.severity ?? error.severity ?? defaultSeverity.name;
5441
- const effectiveSeverityLevel = SEVERITY_LEVELS[effectiveSeverity];
5442
- return new _FulmenError({
5443
- ...error,
5444
- ...options,
5445
- severity: effectiveSeverity,
5446
- severity_level: effectiveSeverityLevel,
5447
- // Recomputed, not from error.severity_level
5448
- timestamp: error.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
5449
- });
5450
- }
5451
- return _FulmenError.fromError(error, options);
5452
- }
5453
- /**
5454
- * Create FulmenError from native Error object
5455
- *
5456
- * @param err - Native Error instance
5457
- * @param options - Error options
5458
- * @returns New FulmenError instance
5459
- *
5460
- * @example
5461
- * ```typescript
5462
- * const err = new TypeError('Invalid type');
5463
- * const fulmenErr = FulmenError.fromError(err, {
5464
- * code: 'TYPE_ERROR',
5465
- * severity: 'medium'
5466
- * });
5467
- * ```
5468
- */
5469
- static fromError(err, options = {}) {
5470
- const code = options.code ?? "UNKNOWN_ERROR";
5471
- const severity = options.severity ?? Severity.MEDIUM;
5472
- const severityLevel = SEVERITY_LEVELS[severity];
5473
- const message = extractErrorMessage(err);
5474
- const stack = extractStackTrace(err);
5475
- const data = {
5476
- code,
5477
- message,
5478
- severity,
5479
- severity_level: severityLevel,
5480
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5481
- ...options,
5482
- context: {
5483
- ...options.context,
5484
- originalName: err instanceof Error ? err.name : typeof err,
5485
- stack
5486
- },
5487
- original: stack || message
5488
- };
5489
- return new _FulmenError(data);
5490
- }
5491
- /**
5492
- * Validate error data against schema
5493
- *
5494
- * @param data - Error data to validate
5495
- * @returns Promise resolving to true if valid
5496
- *
5497
- * @example
5498
- * ```typescript
5499
- * const data = { code: 'TEST', message: 'Test error' };
5500
- * if (await FulmenError.validate(data)) {
5501
- * const err = new FulmenError(data);
5502
- * }
5503
- * ```
5504
- */
5505
- static async validate(data) {
5506
- return validateErrorData(data);
5507
- }
5508
- /**
5509
- * Exit process with structured error
5510
- *
5511
- * Logs error as JSON and exits with specified exit code.
5512
- * Mockable for testing (override process.exit).
5513
- *
5514
- * @param error - FulmenError instance
5515
- * @param options - Exit options
5516
- *
5517
- * @example
5518
- * ```typescript
5519
- * const err = FulmenError.fromError(new Error('Fatal'), {
5520
- * code: 'FATAL_ERROR',
5521
- * exit_code: 1
5522
- * });
5523
- * FulmenError.exitWithError(err); // Exits with code 1
5524
- * ```
5525
- */
5526
- static exitWithError(error, options = {}) {
5527
- const logger = options.logger ?? console.error;
5528
- const exitCode = error.data.exit_code ?? 1;
5529
- logger(JSON.stringify(error.toJSON(), null, 2));
5530
- process.exit(exitCode);
5531
- }
5532
- };
5533
- }
5534
- });
5535
-
5536
- // src/errors/index.ts
5537
- var init_errors4 = __esm({
5538
- "src/errors/index.ts"() {
5539
- init_correlation();
5540
- init_fulmen_error();
5541
- init_serialization();
5542
- init_severity();
5543
- init_validators();
5544
- }
5545
- });
5546
-
5547
- // src/appidentity/errors.ts
5548
- var errors_exports2 = {};
5549
- __export(errors_exports2, {
5550
- AppIdentityError: () => AppIdentityError
5551
- });
5552
- var AppIdentityError;
5553
- var init_errors5 = __esm({
5554
- "src/appidentity/errors.ts"() {
5555
- init_errors4();
5556
- AppIdentityError = class _AppIdentityError extends FulmenError {
5557
- identityPath;
5558
- constructor(message, identityPath, cause) {
5559
- let errorData;
5560
- if (cause) {
5561
- errorData = FulmenError.fromError(cause, {
5562
- code: "APP_IDENTITY_ERROR",
5563
- severity: "high",
5564
- context: { identityPath }
5565
- }).data;
5566
- } else {
5567
- errorData = {
5568
- code: "APP_IDENTITY_ERROR",
5569
- message,
5570
- severity: "high",
5571
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5572
- context: { identityPath }
5573
- };
5574
- }
5575
- super(errorData);
5576
- this.name = "AppIdentityError";
5577
- this.identityPath = identityPath;
5578
- if (Error.captureStackTrace) {
5579
- Error.captureStackTrace(this, _AppIdentityError);
5580
- }
5581
- }
5582
- /**
5583
- * Create error for identity not found
5584
- */
5585
- static notFound(searchedPaths) {
5586
- const message = `App identity not found
5587
- Searched paths:
5588
- ${searchedPaths.map((p) => ` - ${p}`).join("\n")}`;
5589
- return new _AppIdentityError(message);
5590
- }
5591
- /**
5592
- * Create error for schema validation failure
5593
- */
5594
- static validationFailed(path, diagnostics) {
5595
- const errorCount = diagnostics.filter((d) => d.severity === "ERROR").length;
5596
- const warningCount = diagnostics.filter((d) => d.severity === "WARN").length;
5597
- let message = `Invalid app identity: ${path}
5598
- `;
5599
- message += `Validation errors: ${errorCount} error(s), ${warningCount} warning(s)
5600
- `;
5601
- const displayDiagnostics = diagnostics.slice(0, 3);
5602
- for (const diag of displayDiagnostics) {
5603
- message += ` - ${diag.message}`;
5604
- if (diag.pointer) {
5605
- message += ` at ${diag.pointer}`;
5606
- }
5607
- message += "\n";
5608
- }
5609
- if (diagnostics.length > 3) {
5610
- message += ` ... and ${diagnostics.length - 3} more
5611
- `;
5612
- }
5613
- return new _AppIdentityError(message, path);
5614
- }
5615
- /**
5616
- * Create error for environment variable override pointing to missing file
5617
- */
5618
- static envOverrideMissing(envPath) {
5619
- const message = `FULMEN_APP_IDENTITY_PATH points to missing file: ${envPath}
5620
- `;
5621
- return new _AppIdentityError(message, envPath);
5622
- }
5623
- /**
5624
- * Create error for YAML parsing failure
5625
- */
5626
- static parseFailed(path, cause) {
5627
- const message = `Failed to parse identity file: ${path}
5628
- ${cause.message}`;
5629
- return new _AppIdentityError(message, path, cause);
5630
- }
5631
- /**
5632
- * Create error for file read failure
5633
- */
5634
- static readFailed(path, cause) {
5635
- const message = `Failed to read identity file: ${path}
5636
- ${cause.message}`;
5637
- return new _AppIdentityError(message, path, cause);
5638
- }
5639
- /**
5640
- * Create error for embedded identity already registered
5641
- *
5642
- * Uses first-wins semantics - once registered, cannot be replaced
5643
- */
5644
- static alreadyRegistered() {
5645
- const message = "Embedded identity already registered. Registration uses first-wins semantics and cannot be replaced.";
5646
- return new _AppIdentityError(message);
5647
- }
5648
- /**
5649
- * Create error for embedded identity YAML parsing failure
5650
- */
5651
- static embeddedParseFailed(cause) {
5652
- const message = `Failed to parse embedded identity YAML: ${cause.message}`;
5653
- return new _AppIdentityError(message, void 0, cause);
5654
- }
5655
- /**
5656
- * Create error for embedded identity schema validation failure
5657
- */
5658
- static embeddedValidationFailed(diagnostics) {
5659
- const errorCount = diagnostics.filter((d) => d.severity === "ERROR").length;
5660
- const warningCount = diagnostics.filter((d) => d.severity === "WARN").length;
5661
- let message = "Invalid embedded identity\n";
5662
- message += `Validation errors: ${errorCount} error(s), ${warningCount} warning(s)
5663
- `;
5664
- const displayDiagnostics = diagnostics.slice(0, 3);
5665
- for (const diag of displayDiagnostics) {
5666
- message += ` - ${diag.message}`;
5667
- if (diag.pointer) {
5668
- message += ` at ${diag.pointer}`;
5669
- }
5670
- message += "\n";
5671
- }
5672
- if (diagnostics.length > 3) {
5673
- message += ` ... and ${diagnostics.length - 3} more
5674
- `;
5675
- }
5676
- return new _AppIdentityError(message);
5677
- }
5678
- };
5679
- }
5680
- });
5681
- async function discoverIdentityPath(options) {
5682
- if (options?.path) {
5683
- const exists = await fileExists(options.path);
5684
- if (!exists) {
5685
- throw AppIdentityError.notFound([options.path]);
5686
- }
5687
- return { path: options.path, source: "explicit" };
5688
- }
5689
- const envPath = process.env[APP_IDENTITY_ENV_VAR];
5690
- if (envPath) {
5691
- const exists = await fileExists(envPath);
5692
- if (!exists) {
5693
- throw AppIdentityError.envOverrideMissing(envPath);
5694
- }
5695
- return { path: envPath, source: "env" };
5696
- }
5697
- const startDir = options?.startDir || process.cwd();
5698
- const result = await searchAncestors(startDir);
5699
- if (result) {
5700
- return { path: result, source: "ancestor" };
5701
- }
5702
- return null;
5703
- }
5704
- async function searchAncestors(startDir) {
5705
- let currentDir = startDir;
5706
- const searchedPaths = [];
5707
- for (let i = 0; i < MAX_ANCESTOR_SEARCH_DEPTH; i++) {
5708
- const candidatePath = join(currentDir, APP_IDENTITY_DIR, APP_IDENTITY_FILENAME);
5709
- searchedPaths.push(candidatePath);
5710
- if (await fileExists(candidatePath)) {
5711
- return candidatePath;
5712
- }
5713
- const parentDir = dirname(currentDir);
5714
- if (parentDir === currentDir) {
5715
- throw AppIdentityError.notFound(searchedPaths);
5716
- }
5717
- currentDir = parentDir;
5718
- }
5719
- throw AppIdentityError.notFound(searchedPaths);
5720
- }
5721
- async function fileExists(path) {
5722
- try {
5723
- await access(path);
5724
- return true;
5725
- } catch {
5726
- return false;
5727
- }
5728
- }
5729
- var init_discovery = __esm({
5730
- "src/appidentity/discovery.ts"() {
5731
- init_constants();
5732
- init_errors5();
5733
- }
5734
- });
5735
- function getEmbeddedIdentity() {
5736
- return embeddedIdentity;
5737
- }
5738
- var embeddedIdentity;
5739
- var init_embedded = __esm({
5740
- "src/appidentity/embedded.ts"() {
5741
- init_schema();
5742
- init_constants();
5743
- init_errors5();
5744
- embeddedIdentity = null;
5745
- }
5746
- });
5747
-
5748
- // src/appidentity/loader.ts
5749
- var loader_exports = {};
5750
- __export(loader_exports, {
5751
- clearIdentityCache: () => clearIdentityCache,
5752
- getCachedIdentity: () => getCachedIdentity,
5753
- loadIdentity: () => loadIdentity
5754
- });
5755
- function deepFreeze5(obj) {
5756
- Object.freeze(obj);
5757
- Object.getOwnPropertyNames(obj).forEach((prop) => {
5758
- const value = obj[prop];
5759
- if (value !== null && (typeof value === "object" || typeof value === "function") && !Object.isFrozen(value)) {
5760
- deepFreeze5(value);
5761
- }
5762
- });
5763
- return obj;
5764
- }
5765
- async function loadIdentity(options) {
5766
- if (options?.identity) {
5767
- return deepFreeze5(structuredClone(options.identity));
5768
- }
5769
- if (!options?.skipCache) {
5770
- const cached = getCachedIdentity();
5771
- if (cached) {
5772
- return cached;
5773
- }
5774
- }
5775
- let discovery;
5776
- try {
5777
- discovery = await discoverIdentityPath({
5778
- path: options?.path,
5779
- startDir: options?.startDir
5780
- });
5781
- } catch (error) {
5782
- const hasExplicitPath = Boolean(options?.path);
5783
- const hasEnvOverride = Boolean(process.env[APP_IDENTITY_ENV_VAR]);
5784
- if (!hasExplicitPath && !hasEnvOverride && error instanceof AppIdentityError) {
5785
- const embedded = getEmbeddedIdentity();
5786
- if (embedded) {
5787
- setCachedIdentity(embedded);
5788
- return embedded;
5789
- }
5790
- }
5791
- throw error;
5792
- }
5793
- if (!discovery) {
5794
- const embedded = getEmbeddedIdentity();
5795
- if (embedded) {
5796
- setCachedIdentity(embedded);
5797
- return embedded;
5798
- }
5799
- throw AppIdentityError.notFound([]);
5800
- }
5801
- let content;
5802
- try {
5803
- content = await readFile(discovery.path, "utf-8");
5804
- } catch (error) {
5805
- throw AppIdentityError.readFailed(
5806
- discovery.path,
5807
- error instanceof Error ? error : new Error(String(error))
5808
- );
5809
- }
5810
- let parsed;
5811
- try {
5812
- parsed = parse(content);
5813
- } catch (error) {
5814
- throw AppIdentityError.parseFailed(
5815
- discovery.path,
5816
- error instanceof Error ? error : new Error(String(error))
5817
- );
5818
- }
5819
- if (!options?.skipValidation) {
5820
- const result = await validateDataBySchemaId(parsed, APP_IDENTITY_SCHEMA_ID);
5821
- if (!result.valid) {
5822
- throw AppIdentityError.validationFailed(discovery.path, result.diagnostics);
5823
- }
5824
- }
5825
- const identity = deepFreeze5(structuredClone(parsed));
5826
- setCachedIdentity(identity);
5827
- return identity;
5828
- }
5829
- var init_loader2 = __esm({
5830
- "src/appidentity/loader.ts"() {
5831
- init_schema();
5832
- init_cache();
5833
- init_constants();
5834
- init_discovery();
5835
- init_embedded();
5836
- init_errors5();
5837
- }
5838
- });
5839
- function createCLI(options = {}) {
5840
- const program = new Command();
5841
- program.name("tsfulmen-schema").description("Schema validation and discovery CLI for Fulmen (developer tool)").version("0.1.0");
5842
- program.command("list").description("List available schemas from registry").argument("[prefix]", "Filter schemas by prefix").option("--base-dir <path>", "Override schema base directory").action(async (prefix, cmdOptions) => {
5843
- try {
5844
- const schemas = await listSchemas(prefix, {
5845
- baseDir: cmdOptions?.baseDir || options.baseDir
5846
- });
5847
- if (schemas.length === 0) {
5848
- console.log("No schemas found");
5849
- return;
5850
- }
5851
- console.log(`Found ${schemas.length} schema(s):
5852
- `);
5853
- for (const schema of schemas) {
5854
- console.log(` ${schema.id}`);
5855
- console.log(` Format: ${schema.format}`);
5856
- console.log(` Path: ${schema.relativePath}`);
5857
- if (schema.description) {
5858
- console.log(` Description: ${schema.description}`);
5859
- }
5860
- console.log();
5861
- }
5862
- } catch (error) {
5863
- console.error("Error listing schemas:", error.message);
5864
- process.exit(1);
5865
- }
5866
- });
5867
- program.command("show").description("Show schema details").requiredOption("--schema-id <id>", "Schema ID to show").option("--base-dir <path>", "Override schema base directory").action(async (cmdOptions) => {
5868
- try {
5869
- const registry = getSchemaRegistry({
5870
- baseDir: cmdOptions.baseDir || options.baseDir
5871
- });
5872
- const schema = await registry.getSchema(cmdOptions.schemaId);
5873
- console.log("Schema Details:\n");
5874
- console.log(` ID: ${schema.id}`);
5875
- console.log(` Format: ${schema.format}`);
5876
- console.log(` Path: ${schema.path}`);
5877
- console.log(` Relative Path: ${schema.relativePath}`);
5878
- if (schema.version) {
5879
- console.log(` Version: ${schema.version}`);
5880
- }
5881
- if (schema.description) {
5882
- console.log(` Description: ${schema.description}`);
5883
- }
5884
- if (schema.schemaDraft) {
5885
- console.log(` Schema Draft: ${schema.schemaDraft}`);
5886
- }
5887
- const content = await readFile(schema.path, "utf-8");
5888
- console.log("\nSchema Content:");
5889
- console.log(content);
5890
- } catch (error) {
5891
- console.error("Error showing schema:", error.message);
5892
- process.exit(1);
5893
- }
5894
- });
5895
- program.command("validate").description("Validate data file against schema").requiredOption("--schema-id <id>", "Schema ID to validate against").argument("<file>", "Data file to validate").option("--use-goneat", "Use goneat for validation (requires goneat binary)").option("--goneat-path <path>", "Path to goneat binary").option("--base-dir <path>", "Override schema base directory").action(
5896
- async (file, cmdOptions) => {
5897
- try {
5898
- let result;
5899
- if (cmdOptions.useGoneat) {
5900
- const available = await isGoneatAvailable(cmdOptions.goneatPath);
5901
- if (!available) {
5902
- console.error("\u274C goneat not available. Install goneat or remove --use-goneat flag.");
5903
- console.error(" AJV validation (default) works without external dependencies.");
5904
- process.exit(1);
5905
- }
5906
- const registry = getSchemaRegistry({
5907
- baseDir: cmdOptions.baseDir || options.baseDir
5908
- });
5909
- const schema = await registry.getSchema(cmdOptions.schemaId);
5910
- console.log("Using goneat validation...");
5911
- result = await runGoneatValidation(schema.path, file, cmdOptions.goneatPath);
5912
- } else {
5913
- console.log("Using AJV validation...");
5914
- result = await validateFileBySchemaId(file, cmdOptions.schemaId, {
5915
- baseDir: cmdOptions.baseDir || options.baseDir
5916
- });
5917
- }
5918
- if (result.valid) {
5919
- console.log(`\u2705 Validation passed (${result.source})`);
5920
- process.exit(0);
5921
- } else {
5922
- console.log(`\u274C Validation failed (${result.source})`);
5923
- console.log("\nDiagnostics:");
5924
- console.log(formatDiagnostics(result.diagnostics));
5925
- process.exit(1);
5926
- }
5927
- } catch (error) {
5928
- console.error("Error validating file:", error.message);
5929
- process.exit(1);
5930
- }
5931
- }
5932
- );
5933
- program.command("validate-schema").description("Validate a schema file itself").argument("<file>", "Schema file to validate").action(async (file) => {
5934
- try {
5935
- const content = await readFile(file, "utf-8");
5936
- const { validateSchema: validateSchema2 } = await Promise.resolve().then(() => (init_validator(), validator_exports));
5937
- const result = await validateSchema2(content);
5938
- if (result.valid) {
5939
- console.log("\u2705 Schema is valid");
5940
- process.exit(0);
5941
- } else {
5942
- console.log("\u274C Schema is invalid");
5943
- console.log("\nDiagnostics:");
5944
- console.log(formatDiagnostics(result.diagnostics));
5945
- process.exit(1);
5946
- }
5947
- } catch (error) {
5948
- console.error("Error validating schema:", error.message);
5949
- process.exit(1);
5950
- }
5951
- });
5952
- program.command("normalize").description("Normalize schema to canonical JSON format").argument("<file>", "Schema file to normalize").option("--compact", "Output compact JSON (no formatting)").option("-o, --output <file>", "Write to output file instead of stdout").action(async (file, cmdOptions) => {
5953
- try {
5954
- const content = await readFile(file, "utf-8");
5955
- const normalized = normalizeSchema(content, {
5956
- compact: cmdOptions.compact
5957
- });
5958
- if (cmdOptions.output) {
5959
- await writeFile(cmdOptions.output, normalized, "utf-8");
5960
- console.log(`\u2705 Normalized schema written to ${cmdOptions.output}`);
5961
- } else {
5962
- console.log(normalized);
5963
- }
5964
- } catch (error) {
5965
- console.error("Error normalizing schema:", error.message);
5966
- process.exit(1);
5967
- }
5968
- });
5969
- program.command("compare").description("Compare two schemas for semantic equality").argument("<file1>", "First schema file").argument("<file2>", "Second schema file").option("--show-normalized", "Show normalized outputs").action(async (file1, file2, cmdOptions) => {
5970
- try {
5971
- const content1 = await readFile(file1, "utf-8");
5972
- const content2 = await readFile(file2, "utf-8");
5973
- const result = compareSchemas(content1, content2);
5974
- if (result.equal) {
5975
- console.log("\u2705 Schemas are semantically equal");
5976
- } else {
5977
- console.log("\u274C Schemas differ");
5978
- }
5979
- if (cmdOptions.showNormalized) {
5980
- console.log("\nNormalized Schema 1:");
5981
- console.log(result.normalizedA);
5982
- console.log("\nNormalized Schema 2:");
5983
- console.log(result.normalizedB);
5984
- }
5985
- process.exit(result.equal ? 0 : 1);
5986
- } catch (error) {
5987
- console.error("Error comparing schemas:", error.message);
5988
- process.exit(1);
5989
- }
5990
- });
5991
- program.command("export").description("Export schema from registry to file with provenance").requiredOption("--schema-id <id>", "Schema ID to export").requiredOption("--out <path>", "Output file path").option("--force", "Overwrite existing file", false).option("--no-provenance", "Exclude provenance metadata").option("--no-validate", "Skip schema validation before export").option("--format <format>", "Export format (json|yaml|auto)", "auto").option("--base-dir <path>", "Override schema base directory").action(
5992
- async (cmdOptions) => {
5993
- try {
5994
- const { exportSchema: exportSchema2 } = await Promise.resolve().then(() => (init_export(), export_exports));
5995
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
5996
- const result = await exportSchema2({
5997
- schemaId: cmdOptions.schemaId,
5998
- outPath: cmdOptions.out,
5999
- includeProvenance: cmdOptions.provenance ?? true,
6000
- validate: cmdOptions.validate ?? true,
6001
- overwrite: cmdOptions.force ?? false,
6002
- format: cmdOptions.format ?? "auto",
6003
- baseDir: cmdOptions.baseDir || options.baseDir
6004
- });
6005
- console.log("\u2705 Schema exported successfully");
6006
- console.log(` Schema ID: ${result.schemaId}`);
6007
- console.log(` Output: ${result.outPath}`);
6008
- console.log(` Format: ${result.format}`);
6009
- if (result.provenance) {
6010
- console.log("\nProvenance:");
6011
- console.log(` Crucible: ${result.provenance.crucible_version}`);
6012
- console.log(` Library: ${result.provenance.library_version}`);
6013
- if (result.provenance.revision) {
6014
- console.log(` Revision: ${result.provenance.revision}`);
6015
- }
6016
- console.log(` Exported: ${result.provenance.exported_at}`);
6017
- }
6018
- process.exit(exitCodes2.EXIT_SUCCESS);
6019
- } catch (error) {
6020
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6021
- const { SchemaExportError: SchemaExportError2, SchemaValidationError: SchemaValidationError2, ExportErrorReason: ExportErrorReason2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
6022
- console.error("\u274C Schema export failed:", error.message);
6023
- if (error instanceof SchemaExportError2) {
6024
- if (error.outPath) {
6025
- console.error(` Output path: ${error.outPath}`);
6026
- }
6027
- switch (error.reason) {
6028
- case ExportErrorReason2.FILE_EXISTS:
6029
- case ExportErrorReason2.WRITE_FAILED:
6030
- process.exit(exitCodes2.EXIT_FILE_WRITE_ERROR);
6031
- break;
6032
- case ExportErrorReason2.INVALID_FORMAT:
6033
- process.exit(exitCodes2.EXIT_INVALID_ARGUMENT);
6034
- break;
6035
- default:
6036
- process.exit(exitCodes2.EXIT_FAILURE);
6037
- }
6038
- }
6039
- if (error instanceof SchemaValidationError2) {
6040
- const errorMsg = error.message.toLowerCase();
6041
- if (errorMsg.includes("not found")) {
6042
- process.exit(exitCodes2.EXIT_FILE_NOT_FOUND);
6043
- }
6044
- process.exit(exitCodes2.EXIT_DATA_INVALID);
6045
- }
6046
- process.exit(exitCodes2.EXIT_FAILURE);
6047
- }
6048
- }
6049
- );
6050
- program.command("identity-show").description("Show application identity from .fulmen/app.yaml").option("--path <path>", "Explicit path to app.yaml").option("--json", "Output as JSON").action(async (cmdOptions) => {
6051
- try {
6052
- const { loadIdentity: loadIdentity2 } = await Promise.resolve().then(() => (init_loader2(), loader_exports));
6053
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6054
- const identity = await loadIdentity2({ path: cmdOptions.path });
6055
- if (cmdOptions.json) {
6056
- console.log(JSON.stringify(identity, null, 2));
6057
- } else {
6058
- console.log("Application Identity:\n");
6059
- console.log(` Binary Name: ${identity.app.binary_name}`);
6060
- console.log(` Vendor: ${identity.app.vendor}`);
6061
- console.log(` Env Prefix: ${identity.app.env_prefix}`);
6062
- console.log(` Config Name: ${identity.app.config_name}`);
6063
- console.log(` Description: ${identity.app.description}`);
6064
- if (identity.metadata) {
6065
- console.log("\nMetadata:");
6066
- if (identity.metadata.license) {
6067
- console.log(` License: ${identity.metadata.license}`);
6068
- }
6069
- if (identity.metadata.repository_category) {
6070
- console.log(` Category: ${identity.metadata.repository_category}`);
6071
- }
6072
- if (identity.metadata.telemetry_namespace) {
6073
- console.log(` Telemetry: ${identity.metadata.telemetry_namespace}`);
6074
- }
6075
- if (identity.metadata.project_url) {
6076
- console.log(` Project URL: ${identity.metadata.project_url}`);
6077
- }
6078
- }
6079
- }
6080
- process.exit(exitCodes2.EXIT_SUCCESS);
6081
- } catch (error) {
6082
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6083
- const { AppIdentityError: AppIdentityError2 } = await Promise.resolve().then(() => (init_errors5(), errors_exports2));
6084
- console.error("\u274C Failed to load identity:", error.message);
6085
- if (error instanceof AppIdentityError2) {
6086
- if (error.message.includes("not found")) {
6087
- process.exit(exitCodes2.EXIT_FILE_NOT_FOUND);
6088
- }
6089
- if (error.message.includes("Invalid") || error.message.includes("validation")) {
6090
- process.exit(exitCodes2.EXIT_DATA_INVALID);
6091
- }
6092
- }
6093
- process.exit(exitCodes2.EXIT_FAILURE);
6094
- }
6095
- });
6096
- program.command("identity-validate").description("Validate application identity against schema").argument("[file]", "Path to app.yaml (defaults to discovery)").action(async (file) => {
6097
- try {
6098
- const { loadIdentity: loadIdentity2 } = await Promise.resolve().then(() => (init_loader2(), loader_exports));
6099
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6100
- console.log("Validating application identity...");
6101
- const identity = await loadIdentity2({ path: file });
6102
- console.log("\u2705 Identity is valid");
6103
- console.log(` Binary: ${identity.app.binary_name}`);
6104
- console.log(` Vendor: ${identity.app.vendor}`);
6105
- process.exit(exitCodes2.EXIT_SUCCESS);
6106
- } catch (error) {
6107
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6108
- const { AppIdentityError: AppIdentityError2 } = await Promise.resolve().then(() => (init_errors5(), errors_exports2));
6109
- console.error("\u274C Identity validation failed:", error.message);
6110
- if (error instanceof AppIdentityError2) {
6111
- if (error.message.includes("not found")) {
6112
- process.exit(exitCodes2.EXIT_FILE_NOT_FOUND);
6113
- }
6114
- if (error.message.includes("Invalid") || error.message.includes("validation")) {
6115
- process.exit(exitCodes2.EXIT_DATA_INVALID);
6116
- }
6117
- }
6118
- process.exit(exitCodes2.EXIT_FAILURE);
6119
- }
6120
- });
6121
- return program;
6122
- }
6123
- var init_cli = __esm({
6124
- "src/schema/cli.ts"() {
6125
- init_goneat_bridge();
6126
- init_normalizer();
6127
- init_registry2();
6128
- init_utils();
6129
- init_validator();
6130
- if (import.meta.url === `file://${process.argv[1]}`) {
6131
- const program = createCLI();
6132
- program.parse(process.argv);
6133
- }
6134
- }
6135
- });
6136
-
6137
- // src/schema/index.ts
6138
- var init_schema = __esm({
6139
- "src/schema/index.ts"() {
6140
- init_ajv_formats();
6141
- init_cli();
6142
- init_errors();
6143
- init_export();
6144
- init_goneat_bridge();
6145
- init_normalizer();
6146
- init_registry2();
6147
- init_utils();
6148
- init_validator();
6149
- }
6150
- });
6151
-
6152
- // src/telemetry/validators.ts
6153
- async function validateMetricsEvent(event) {
6154
- return MetricsValidator.getInstance().validate(event);
6155
- }
6156
- async function validateMetricsEvents(events) {
6157
- for (const event of events) {
6158
- if (!await validateMetricsEvent(event)) {
6159
- return false;
6160
- }
6161
- }
6162
- return true;
6163
- }
6164
- function getValidationErrors2() {
6165
- return MetricsValidator.getInstance().getErrors();
6166
- }
6167
- function formatValidationErrors2(errors) {
6168
- return errors.map((err) => {
6169
- const path = err.instancePath || "(root)";
6170
- const message = err.message || "validation failed";
6171
- return `${path}: ${message}`;
6172
- }).join("; ");
6173
- }
6174
- async function assertValidMetricsEvent(event) {
6175
- if (!await validateMetricsEvent(event)) {
6176
- const errors = getValidationErrors2();
6177
- const message = errors ? formatValidationErrors2(errors) : "Metrics event validation failed";
6178
- throw new Error(`Invalid metrics event: ${message}`);
6179
- }
1458
+ async function assertValidMetricsEvent(event) {
1459
+ if (!await validateMetricsEvent(event)) {
1460
+ const errors = getValidationErrors();
1461
+ const message = errors ? formatValidationErrors(errors) : "Metrics event validation failed";
1462
+ throw new Error(`Invalid metrics event: ${message}`);
1463
+ }
6180
1464
  }
6181
1465
  var MetricsValidator;
6182
- var init_validators2 = __esm({
1466
+ var init_validators = __esm({
6183
1467
  "src/telemetry/validators.ts"() {
6184
1468
  init_schema();
6185
1469
  MetricsValidator = class _MetricsValidator {
@@ -6257,7 +1541,7 @@ var init_validators2 = __esm({
6257
1541
  });
6258
1542
 
6259
1543
  // src/telemetry/index.ts
6260
- var VERSION2, metrics;
1544
+ var VERSION, metrics;
6261
1545
  var init_telemetry = __esm({
6262
1546
  "src/telemetry/index.ts"() {
6263
1547
  init_registry();
@@ -6267,13 +1551,13 @@ var init_telemetry = __esm({
6267
1551
  init_histogram();
6268
1552
  init_taxonomy();
6269
1553
  init_types();
6270
- init_validators2();
6271
- VERSION2 = "1.0.0";
1554
+ init_validators();
1555
+ VERSION = "1.0.0";
6272
1556
  metrics = new MetricsRegistry();
6273
1557
  }
6274
1558
  });
6275
1559
  init_telemetry();
6276
1560
 
6277
- export { Counter, DEFAULT_MS_BUCKETS, Gauge, Histogram, MetricsRegistry, VERSION2 as VERSION, assertValidMetricsEvent, formatValidationErrors2 as formatValidationErrors, getDefaultBuckets, getDefaultUnit, getMetric, getTaxonomy, getValidationErrors2 as getValidationErrors, isHistogramSummary, isValidMetricName2 as isValidMetricName, isValidMetricName as isValidMetricNameTaxonomy, isValidMetricUnit, metrics, validateMetricsEvent, validateMetricsEvents };
1561
+ export { Counter, DEFAULT_MS_BUCKETS, Gauge, Histogram, MetricsRegistry, VERSION, assertValidMetricsEvent, formatValidationErrors, getDefaultBuckets, getDefaultUnit, getMetric, getTaxonomy, getValidationErrors, isHistogramSummary, isValidMetricName2 as isValidMetricName, isValidMetricName as isValidMetricNameTaxonomy, isValidMetricUnit, metrics, validateMetricsEvent, validateMetricsEvents };
6278
1562
  //# sourceMappingURL=index.js.map
6279
1563
  //# sourceMappingURL=index.js.map