@hexagen-monaco/sync 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import path8 from 'path';
2
2
  import fs4, { realpathSync, lstatSync, createWriteStream } from 'fs';
3
3
  import fs5 from 'fs/promises';
4
- import { promisify } from 'util';
4
+ import { promisify, types } from 'util';
5
5
  import { exec } from 'child_process';
6
6
  import yaml3 from 'js-yaml';
7
7
  import crypto, { createHash } from 'crypto';
@@ -112,9 +112,9 @@ var SyncJournal = class {
112
112
  if (entry.preContent === null) {
113
113
  try {
114
114
  await fs5.unlink(entry.path);
115
- } catch (err3) {
116
- if (!(err3 instanceof Error && "code" in err3 && err3.code === "ENOENT")) {
117
- throw err3;
115
+ } catch (err4) {
116
+ if (!(err4 instanceof Error && "code" in err4 && err4.code === "ENOENT")) {
117
+ throw err4;
118
118
  }
119
119
  }
120
120
  logger.info(`rolled back (removed) ${relative}`);
@@ -126,11 +126,11 @@ var SyncJournal = class {
126
126
  logger.info(`rolled back (restored) ${relative}`);
127
127
  }
128
128
  outcome.restored += 1;
129
- } catch (err3) {
129
+ } catch (err4) {
130
130
  outcome.failures.push({
131
131
  path: entry.path,
132
132
  intended: entry.preContent === null ? "remove created file" : "restore pre-image",
133
- error: err3 instanceof Error ? err3.message : String(err3)
133
+ error: err4 instanceof Error ? err4.message : String(err4)
134
134
  });
135
135
  }
136
136
  }
@@ -159,13 +159,13 @@ var LockFile = class {
159
159
  this.handle = await this.fsImpl.open(this.lockPath, "wx");
160
160
  this.locked = true;
161
161
  this.logger.debug("[LockFile] Acquired lock");
162
- } catch (err3) {
163
- if (err3 instanceof Error && "code" in err3 && err3.code === "EEXIST") {
162
+ } catch (err4) {
163
+ if (err4 instanceof Error && "code" in err4 && err4.code === "EEXIST") {
164
164
  throw new Error(
165
165
  "Sync already in progress. Wait for other process to complete or remove .architecture/.sync.lock"
166
166
  );
167
167
  }
168
- throw err3;
168
+ throw err4;
169
169
  }
170
170
  }
171
171
  async release() {
@@ -181,14 +181,14 @@ var LockFile = class {
181
181
  await this.fsImpl.unlink(this.lockPath);
182
182
  this.locked = false;
183
183
  this.logger.debug("[LockFile] Released lock");
184
- } catch (err3) {
185
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
184
+ } catch (err4) {
185
+ if (err4 instanceof Error && "code" in err4 && err4.code === "ENOENT") {
186
186
  this.logger.warn("[LockFile] Lock file already removed");
187
187
  this.locked = false;
188
188
  this.handle = null;
189
189
  return;
190
190
  }
191
- throw err3;
191
+ throw err4;
192
192
  }
193
193
  }
194
194
  async forceRelease() {
@@ -515,8 +515,8 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
515
515
  const status = exists ? "updated" : "created";
516
516
  logger.info(`${status} ${relativePath}`);
517
517
  return status;
518
- } catch (err3) {
519
- if (err3 instanceof Error && "code" in err3 && err3.code === "EXDEV") {
518
+ } catch (err4) {
519
+ if (err4 instanceof Error && "code" in err4 && err4.code === "EXDEV") {
520
520
  try {
521
521
  await fs5.copyFile(tmpPath, filePath);
522
522
  await fs5.unlink(tmpPath);
@@ -529,7 +529,7 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
529
529
  }
530
530
  await fs5.unlink(tmpPath).catch(() => {
531
531
  });
532
- throw err3;
532
+ throw err4;
533
533
  }
534
534
  }
535
535
 
@@ -725,18 +725,18 @@ function contentHash2(content) {
725
725
  function detectCircularExports(exportGraph) {
726
726
  const visited = /* @__PURE__ */ new Set();
727
727
  const recursionStack = /* @__PURE__ */ new Set();
728
- const path26 = [];
728
+ const path28 = [];
729
729
  function dfs(node) {
730
730
  if (recursionStack.has(node)) {
731
- const cycleStart = path26.indexOf(node);
732
- return [...path26.slice(cycleStart), node];
731
+ const cycleStart = path28.indexOf(node);
732
+ return [...path28.slice(cycleStart), node];
733
733
  }
734
734
  if (visited.has(node)) {
735
735
  return null;
736
736
  }
737
737
  visited.add(node);
738
738
  recursionStack.add(node);
739
- path26.push(node);
739
+ path28.push(node);
740
740
  const exports$1 = exportGraph.get(node) ?? [];
741
741
  for (const exportPath of exports$1) {
742
742
  const cycle = dfs(exportPath);
@@ -744,7 +744,7 @@ function detectCircularExports(exportGraph) {
744
744
  return cycle;
745
745
  }
746
746
  }
747
- path26.pop();
747
+ path28.pop();
748
748
  recursionStack.delete(node);
749
749
  return null;
750
750
  }
@@ -761,8 +761,8 @@ function generateBarrelContent(entries) {
761
761
  return null;
762
762
  }
763
763
  const exportLines = entries.sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
764
- const path26 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
765
- return `export * from "${path26}";`;
764
+ const path28 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
765
+ return `export * from "${path28}";`;
766
766
  });
767
767
  return `${GENERATED_MARKER2}
768
768
 
@@ -847,11 +847,11 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
847
847
  result.deleted.push(pending.filePath);
848
848
  result.totalOps++;
849
849
  continue;
850
- } catch (err3) {
851
- if (err3 && typeof err3 === "object" && "code" in err3 && err3.code === "ENOENT") {
850
+ } catch (err4) {
851
+ if (err4 && typeof err4 === "object" && "code" in err4 && err4.code === "ENOENT") {
852
852
  continue;
853
853
  }
854
- throw err3;
854
+ throw err4;
855
855
  }
856
856
  }
857
857
  const status = await safeWriteFileAtomic(
@@ -972,11 +972,11 @@ async function shouldGenerateBarrel(barrelPath, preserved, logger) {
972
972
  async function readFileIfExists(filePath) {
973
973
  try {
974
974
  return await fs5.readFile(filePath, "utf8");
975
- } catch (err3) {
976
- if (err3 && typeof err3 === "object" && "code" in err3 && err3.code === "ENOENT") {
975
+ } catch (err4) {
976
+ if (err4 && typeof err4 === "object" && "code" in err4 && err4.code === "ENOENT") {
977
977
  return null;
978
978
  }
979
- throw err3;
979
+ throw err4;
980
980
  }
981
981
  }
982
982
 
@@ -1228,9 +1228,9 @@ async function generateTsconfig(moduleDir, moduleName, config, report) {
1228
1228
  );
1229
1229
  recordWriteStatus(result, filePath, status);
1230
1230
  return result;
1231
- } catch (err3) {
1232
- const message = err3 instanceof Error ? err3.message : String(err3);
1233
- result.error = err3 instanceof Error ? err3 : new Error(`tsconfig generation failed for ${moduleName}: ${message}`);
1231
+ } catch (err4) {
1232
+ const message = err4 instanceof Error ? err4.message : String(err4);
1233
+ result.error = err4 instanceof Error ? err4 : new Error(`tsconfig generation failed for ${moduleName}: ${message}`);
1234
1234
  result.summary = `tsconfig generation failed for ${moduleName}: ${message}`;
1235
1235
  config.logger.error(result.summary);
1236
1236
  if (report) report.record("error", filePath, result.summary);
@@ -1252,8 +1252,8 @@ async function ensurePackageSrcIndex(moduleDir, config, report) {
1252
1252
  await fs5.stat(filePath);
1253
1253
  result.skipped.push(filePath);
1254
1254
  return result;
1255
- } catch (err3) {
1256
- if (err3.code !== "ENOENT") throw err3;
1255
+ } catch (err4) {
1256
+ if (err4.code !== "ENOENT") throw err4;
1257
1257
  }
1258
1258
  if (!config.dryRun) {
1259
1259
  await fs5.mkdir(path8.dirname(filePath), { recursive: true });
@@ -1747,7 +1747,7 @@ function assertValidToolchainVersion(version, source) {
1747
1747
  function resolveToolchainVersion() {
1748
1748
  {
1749
1749
  return assertValidToolchainVersion(
1750
- "0.16.0",
1750
+ "0.17.0",
1751
1751
  "build-injected __HEXAGEN_TOOLCHAIN_VERSION__"
1752
1752
  );
1753
1753
  }
@@ -2028,15 +2028,643 @@ async function generateRootFiles(config, report) {
2028
2028
  result
2029
2029
  );
2030
2030
  return result;
2031
- } catch (err3) {
2032
- const message = err3 instanceof Error ? err3.message : String(err3);
2033
- result.error = err3 instanceof Error ? err3 : new Error(`root-files generation failed: ${message}`);
2031
+ } catch (err4) {
2032
+ const message = err4 instanceof Error ? err4.message : String(err4);
2033
+ result.error = err4 instanceof Error ? err4 : new Error(`root-files generation failed: ${message}`);
2034
2034
  result.summary = `root-files generation failed: ${message}`;
2035
2035
  config.logger.error(result.summary);
2036
2036
  if (report) report.record("error", "root-files", result.summary);
2037
2037
  return result;
2038
2038
  }
2039
2039
  }
2040
+ var MAX_CONTRACT_DEPTH = 8;
2041
+ var MAX_CONTRACT_FIELDS = 64;
2042
+ var MAX_CONTRACT_NODES = 1024;
2043
+ var DEFAULT_CODEC_RUNTIME_MODULE = "@fleet/shared";
2044
+ var RESERVED_FIELD_NAMES = /* @__PURE__ */ new Set([
2045
+ "__proto__",
2046
+ "constructor",
2047
+ "prototype"
2048
+ ]);
2049
+ var PORT_CONTRACT_KINDS = [
2050
+ "object",
2051
+ "array",
2052
+ "string",
2053
+ "integer",
2054
+ "number",
2055
+ "boolean",
2056
+ "enum",
2057
+ "literal",
2058
+ "nullable"
2059
+ ];
2060
+ var KIND_ALLOWED_KEYS = {
2061
+ object: ["kind", "exact", "fields"],
2062
+ array: ["kind", "items", "maxItems"],
2063
+ string: ["kind", "maxLength", "pattern"],
2064
+ integer: ["kind", "min", "max"],
2065
+ number: ["kind", "min", "max"],
2066
+ boolean: ["kind"],
2067
+ enum: ["kind", "values"],
2068
+ literal: ["kind", "value"],
2069
+ nullable: ["kind", "of"]
2070
+ };
2071
+ var PortContractValidationError = class extends Error {
2072
+ code;
2073
+ portName;
2074
+ contractPath;
2075
+ constructor(code, portName2, contractPath, message) {
2076
+ super(`Port contract validation failed (${code}) for port "${portName2}" at ${contractPath}: ${message}`);
2077
+ this.name = "PortContractValidationError";
2078
+ this.code = code;
2079
+ this.portName = portName2;
2080
+ this.contractPath = contractPath;
2081
+ }
2082
+ };
2083
+ function makeFail(portName2, contractPath) {
2084
+ return (code, message) => ({
2085
+ ok: false,
2086
+ error: new PortContractValidationError(code, portName2, contractPath, message)
2087
+ });
2088
+ }
2089
+ function safeIsArray(value) {
2090
+ try {
2091
+ return Array.isArray(value);
2092
+ } catch {
2093
+ return "hostile";
2094
+ }
2095
+ }
2096
+ function isPlainObject(raw, fail) {
2097
+ if (raw === null || raw === void 0 || typeof raw !== "object") {
2098
+ return fail("MALFORMED_CONTRACT", "expected a plain object, got null, undefined, a primitive, or an array");
2099
+ }
2100
+ const arrayCheck = safeIsArray(raw);
2101
+ if (arrayCheck === "hostile") {
2102
+ return fail("HOSTILE_INPUT", "array inspection threw (revoked or hostile proxy)");
2103
+ }
2104
+ if (arrayCheck) {
2105
+ return fail("MALFORMED_CONTRACT", "arrays are not valid contract nodes");
2106
+ }
2107
+ let proto;
2108
+ try {
2109
+ proto = Object.getPrototypeOf(raw);
2110
+ } catch {
2111
+ return fail("HOSTILE_INPUT", "prototype inspection threw (hostile object or proxy trap)");
2112
+ }
2113
+ if (proto !== Object.prototype && proto !== null) {
2114
+ return fail("HOSTILE_INPUT", "non-plain prototype (class instance, Map, Set, Date, or proxy target)");
2115
+ }
2116
+ return { ok: true };
2117
+ }
2118
+ function ownKeys(raw, fail) {
2119
+ try {
2120
+ const names = Object.getOwnPropertyNames(raw);
2121
+ const symbols = Object.getOwnPropertySymbols(raw);
2122
+ return { names, symbols };
2123
+ } catch {
2124
+ return {
2125
+ error: fail("HOSTILE_INPUT", "own-key enumeration threw (hostile proxy trap)").error
2126
+ };
2127
+ }
2128
+ }
2129
+ function readOwnKey(raw, key, names, fail) {
2130
+ if (!names.includes(key)) {
2131
+ return { present: false };
2132
+ }
2133
+ try {
2134
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
2135
+ if (desc === void 0) {
2136
+ return { present: false };
2137
+ }
2138
+ if (desc.get !== void 0 || desc.set !== void 0) {
2139
+ return {
2140
+ error: fail("HOSTILE_INPUT", `property "${key}" is an accessor; getters are never invoked`).error
2141
+ };
2142
+ }
2143
+ return { present: true, value: desc.value };
2144
+ } catch {
2145
+ return {
2146
+ error: fail("HOSTILE_INPUT", `descriptor inspection for "${key}" threw (hostile proxy trap)`).error
2147
+ };
2148
+ }
2149
+ }
2150
+ function isPositiveFiniteInteger(value) {
2151
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && Number.isFinite(value);
2152
+ }
2153
+ function validatePortContractNode(raw, portName2, contractPath, depth, budget) {
2154
+ const fail = makeFail(portName2, contractPath);
2155
+ budget.nodesRemaining -= 1;
2156
+ if (budget.nodesRemaining < 0) {
2157
+ return fail("MAX_NODES_EXCEEDED", `contract exceeds MAX_CONTRACT_NODES (${MAX_CONTRACT_NODES}) total nodes`);
2158
+ }
2159
+ if (raw === null || raw === void 0 || typeof raw !== "object") {
2160
+ return fail("MALFORMED_CONTRACT", "expected a contract node object, got null, undefined, or a primitive");
2161
+ }
2162
+ const nodeArrayCheck = safeIsArray(raw);
2163
+ if (nodeArrayCheck === "hostile") {
2164
+ return fail("HOSTILE_INPUT", "array inspection threw (revoked or hostile proxy)");
2165
+ }
2166
+ if (nodeArrayCheck) {
2167
+ return fail("MALFORMED_CONTRACT", "arrays are not valid contract nodes");
2168
+ }
2169
+ if (depth > MAX_CONTRACT_DEPTH) {
2170
+ return fail("MAX_DEPTH_EXCEEDED", `contract nesting exceeds MAX_CONTRACT_DEPTH (${MAX_CONTRACT_DEPTH})`);
2171
+ }
2172
+ const plain = isPlainObject(raw, fail);
2173
+ if (!plain.ok) {
2174
+ return { ok: false, error: plain.error };
2175
+ }
2176
+ const keys = ownKeys(raw, fail);
2177
+ if ("error" in keys) {
2178
+ return { ok: false, error: keys.error };
2179
+ }
2180
+ if (keys.symbols.length > 0) {
2181
+ return fail("HOSTILE_INPUT", "symbol-keyed properties are refused on contract nodes");
2182
+ }
2183
+ if (keys.names.length > MAX_CONTRACT_FIELDS) {
2184
+ return fail("MAX_FIELDS_EXCEEDED", `more than MAX_CONTRACT_FIELDS (${MAX_CONTRACT_FIELDS}) keys on one node`);
2185
+ }
2186
+ const kindRead = readOwnKey(raw, "kind", keys.names, fail);
2187
+ if ("error" in kindRead) {
2188
+ return { ok: false, error: kindRead.error };
2189
+ }
2190
+ if (!kindRead.present) {
2191
+ return fail("UNKNOWN_KIND", "contract node is missing `kind`");
2192
+ }
2193
+ const kind = kindRead.value;
2194
+ if (typeof kind !== "string" || !PORT_CONTRACT_KINDS.includes(kind)) {
2195
+ return fail("UNKNOWN_KIND", `\`kind\` must be one of ${PORT_CONTRACT_KINDS.join(", ")}`);
2196
+ }
2197
+ const allowed = KIND_ALLOWED_KEYS[kind];
2198
+ for (const name of keys.names) {
2199
+ if (!allowed.includes(name)) {
2200
+ return fail("MALFORMED_CONTRACT", `unknown key "${name}" on a "${kind}" contract node`);
2201
+ }
2202
+ }
2203
+ switch (kind) {
2204
+ case "object": {
2205
+ const exact = readOwnKey(raw, "exact", keys.names, fail);
2206
+ if ("error" in exact) {
2207
+ return { ok: false, error: exact.error };
2208
+ }
2209
+ if (exact.present && exact.value !== true) {
2210
+ return fail("UNSUPPORTED_SHAPE", "object contracts require `exact: true` (objects are always exact)");
2211
+ }
2212
+ const fieldsRead = readOwnKey(raw, "fields", keys.names, fail);
2213
+ if ("error" in fieldsRead) {
2214
+ return { ok: false, error: fieldsRead.error };
2215
+ }
2216
+ if (!fieldsRead.present) {
2217
+ return fail("UNSUPPORTED_SHAPE", "object contract is missing `fields`");
2218
+ }
2219
+ const fields = fieldsRead.value;
2220
+ const fieldsArrayCheck = fields === null || fields === void 0 || typeof fields !== "object" ? false : safeIsArray(fields);
2221
+ if (fieldsArrayCheck === "hostile") {
2222
+ return fail("HOSTILE_INPUT", "array inspection on `fields` threw (revoked or hostile proxy)");
2223
+ }
2224
+ if (fields === null || fields === void 0 || typeof fields !== "object" || fieldsArrayCheck) {
2225
+ return fail("UNSUPPORTED_SHAPE", "`fields` must be a plain object mapping field names to contract nodes");
2226
+ }
2227
+ const plainFields = isPlainObject(fields, fail);
2228
+ if (!plainFields.ok) {
2229
+ return { ok: false, error: plainFields.error };
2230
+ }
2231
+ const fieldKeys = ownKeys(fields, fail);
2232
+ if ("error" in fieldKeys) {
2233
+ return { ok: false, error: fieldKeys.error };
2234
+ }
2235
+ if (fieldKeys.symbols.length > 0) {
2236
+ return fail("HOSTILE_INPUT", "symbol-keyed properties are refused in `fields`");
2237
+ }
2238
+ if (fieldKeys.names.length > MAX_CONTRACT_FIELDS) {
2239
+ return fail("MAX_FIELDS_EXCEEDED", `more than MAX_CONTRACT_FIELDS (${MAX_CONTRACT_FIELDS}) fields in one object`);
2240
+ }
2241
+ for (const fieldName of fieldKeys.names) {
2242
+ const fieldFail = makeFail(portName2, `${contractPath}.fields.${fieldName}`);
2243
+ if (RESERVED_FIELD_NAMES.has(fieldName)) {
2244
+ return fieldFail("RESERVED_FIELD_NAME", `field name "${fieldName}" is reserved and always refused`);
2245
+ }
2246
+ try {
2247
+ const desc = Object.getOwnPropertyDescriptor(fields, fieldName);
2248
+ if (desc === void 0) {
2249
+ return fieldFail("HOSTILE_INPUT", `field "${fieldName}" has no own data descriptor`);
2250
+ }
2251
+ if (desc.get !== void 0 || desc.set !== void 0) {
2252
+ return fieldFail("HOSTILE_INPUT", `field "${fieldName}" is an accessor; getters are never invoked`);
2253
+ }
2254
+ const childPath = `${contractPath}.fields.${fieldName}`;
2255
+ const child = desc.value;
2256
+ const childArrayCheck = child === null || typeof child !== "object" ? false : safeIsArray(child);
2257
+ if (childArrayCheck === "hostile") {
2258
+ return fieldFail("HOSTILE_INPUT", "array inspection on the field value threw (revoked or hostile proxy)");
2259
+ }
2260
+ if (child === null || typeof child !== "object" || childArrayCheck) {
2261
+ return fieldFail("MALFORMED_CONTRACT", "field value must be a contract node or an `{ optional }` wrapper");
2262
+ }
2263
+ const childKeys = ownKeys(child, fieldFail);
2264
+ if ("error" in childKeys) {
2265
+ return { ok: false, error: childKeys.error };
2266
+ }
2267
+ if (childKeys.symbols.length > 0) {
2268
+ return fieldFail("HOSTILE_INPUT", "symbol-keyed properties are refused on contract nodes");
2269
+ }
2270
+ let inner = child;
2271
+ let innerPath = childPath;
2272
+ if (!childKeys.names.includes("kind")) {
2273
+ if (childKeys.names.length !== 1 || childKeys.names[0] !== "optional") {
2274
+ return fieldFail("MALFORMED_CONTRACT", `unknown keys (${childKeys.names.join(", ")}) on an \`{ optional }\` wrapper`);
2275
+ }
2276
+ const optDesc = Object.getOwnPropertyDescriptor(child, "optional");
2277
+ if (optDesc === void 0) {
2278
+ return fieldFail("MALFORMED_CONTRACT", "missing `optional` on the wrapper");
2279
+ }
2280
+ if (optDesc.get !== void 0 || optDesc.set !== void 0) {
2281
+ return fieldFail("HOSTILE_INPUT", "`optional` is an accessor; getters are never invoked");
2282
+ }
2283
+ inner = optDesc.value;
2284
+ innerPath = `${childPath}.optional`;
2285
+ }
2286
+ const innerResult = validatePortContractNode(inner, portName2, innerPath, depth + 1, budget);
2287
+ if (!innerResult.ok) {
2288
+ return innerResult;
2289
+ }
2290
+ } catch (err4) {
2291
+ return fail("HOSTILE_INPUT", `reflection on field "${fieldName}" threw: ${String(err4)}`);
2292
+ }
2293
+ }
2294
+ return { ok: true };
2295
+ }
2296
+ case "array": {
2297
+ const maxItems = readOwnKey(raw, "maxItems", keys.names, fail);
2298
+ if ("error" in maxItems) {
2299
+ return { ok: false, error: maxItems.error };
2300
+ }
2301
+ if (!maxItems.present || !isPositiveFiniteInteger(maxItems.value)) {
2302
+ return fail("MISSING_BOUND", "array contracts require an explicit positive finite integer `maxItems`");
2303
+ }
2304
+ const items = readOwnKey(raw, "items", keys.names, fail);
2305
+ if ("error" in items) {
2306
+ return { ok: false, error: items.error };
2307
+ }
2308
+ if (!items.present) {
2309
+ return fail("UNSUPPORTED_SHAPE", "array contract is missing `items`");
2310
+ }
2311
+ return validatePortContractNode(items.value, portName2, `${contractPath}.items`, depth + 1, budget);
2312
+ }
2313
+ case "string": {
2314
+ const maxLength = readOwnKey(raw, "maxLength", keys.names, fail);
2315
+ if ("error" in maxLength) {
2316
+ return { ok: false, error: maxLength.error };
2317
+ }
2318
+ if (!maxLength.present || !isPositiveFiniteInteger(maxLength.value)) {
2319
+ return fail("MISSING_BOUND", "string contracts require an explicit positive finite integer `maxLength`");
2320
+ }
2321
+ const pattern = readOwnKey(raw, "pattern", keys.names, fail);
2322
+ if ("error" in pattern) {
2323
+ return { ok: false, error: pattern.error };
2324
+ }
2325
+ if (pattern.present) {
2326
+ if (typeof pattern.value !== "string") {
2327
+ return fail("UNSUPPORTED_SHAPE", "`pattern` must be a string source of a valid RegExp");
2328
+ }
2329
+ try {
2330
+ new RegExp(pattern.value);
2331
+ } catch {
2332
+ return fail("UNSUPPORTED_SHAPE", `\`pattern\` is not a valid RegExp source: ${JSON.stringify(pattern.value)}`);
2333
+ }
2334
+ }
2335
+ return { ok: true };
2336
+ }
2337
+ case "integer":
2338
+ case "number": {
2339
+ for (const boundKey of ["min", "max"]) {
2340
+ const bound = readOwnKey(raw, boundKey, keys.names, fail);
2341
+ if ("error" in bound) {
2342
+ return { ok: false, error: bound.error };
2343
+ }
2344
+ if (bound.present) {
2345
+ if (typeof bound.value !== "number" || !Number.isFinite(bound.value)) {
2346
+ return fail("UNSUPPORTED_SHAPE", `\`${boundKey}\` must be a finite number`);
2347
+ }
2348
+ }
2349
+ }
2350
+ const min = readOwnKey(raw, "min", keys.names, fail);
2351
+ const max = readOwnKey(raw, "max", keys.names, fail);
2352
+ if ("error" in min) {
2353
+ return { ok: false, error: min.error };
2354
+ }
2355
+ if ("error" in max) {
2356
+ return { ok: false, error: max.error };
2357
+ }
2358
+ if (min.present && max.present && min.value > max.value) {
2359
+ return fail("UNSUPPORTED_SHAPE", "`min` must be <= `max`");
2360
+ }
2361
+ return { ok: true };
2362
+ }
2363
+ case "boolean":
2364
+ return { ok: true };
2365
+ case "enum": {
2366
+ const values = readOwnKey(raw, "values", keys.names, fail);
2367
+ if ("error" in values) {
2368
+ return { ok: false, error: values.error };
2369
+ }
2370
+ if (!values.present) {
2371
+ return fail("UNSUPPORTED_SHAPE", "enum contract is missing `values`");
2372
+ }
2373
+ const list = values.value;
2374
+ let isArray;
2375
+ let arrayLength = 0;
2376
+ try {
2377
+ isArray = Array.isArray(list);
2378
+ if (isArray) {
2379
+ arrayLength = list.length;
2380
+ }
2381
+ } catch (err4) {
2382
+ return fail("HOSTILE_INPUT", `array inspection on \`values\` threw: ${String(err4)}`);
2383
+ }
2384
+ if (!isArray) {
2385
+ return fail("HOSTILE_INPUT", "`values` must be a genuine array, not an iterable, array-like, or other object");
2386
+ }
2387
+ const arr = list;
2388
+ if (arrayLength > MAX_CONTRACT_FIELDS) {
2389
+ return fail("MAX_FIELDS_EXCEEDED", `enum \`values\` exceeds MAX_CONTRACT_FIELDS (${MAX_CONTRACT_FIELDS})`);
2390
+ }
2391
+ if (arrayLength === 0) {
2392
+ return fail("UNSUPPORTED_SHAPE", "enum `values` must be a non-empty array of strings");
2393
+ }
2394
+ for (let i = 0; i < arrayLength; i += 1) {
2395
+ try {
2396
+ const desc = Object.getOwnPropertyDescriptor(arr, i);
2397
+ if (desc === void 0) {
2398
+ return fail("HOSTILE_INPUT", `enum \`values\` has a hole at index ${i}`);
2399
+ }
2400
+ if (desc.get !== void 0 || desc.set !== void 0) {
2401
+ return fail("HOSTILE_INPUT", `enum \`values\`[${i}] is an accessor; getters are never invoked`);
2402
+ }
2403
+ if (typeof desc.value !== "string") {
2404
+ return fail("UNSUPPORTED_SHAPE", `enum \`values\`[${i}] must be a string`);
2405
+ }
2406
+ } catch (err4) {
2407
+ return fail("HOSTILE_INPUT", `descriptor inspection on \`values\`[${i}] threw: ${String(err4)}`);
2408
+ }
2409
+ }
2410
+ return { ok: true };
2411
+ }
2412
+ case "literal": {
2413
+ const value = readOwnKey(raw, "value", keys.names, fail);
2414
+ if ("error" in value) {
2415
+ return { ok: false, error: value.error };
2416
+ }
2417
+ if (!value.present) {
2418
+ return fail("UNSUPPORTED_SHAPE", "literal contract is missing `value`");
2419
+ }
2420
+ const v = value.value;
2421
+ const isPrimitive = v === null || typeof v === "string" || typeof v === "number" && Number.isFinite(v) || typeof v === "boolean";
2422
+ if (!isPrimitive) {
2423
+ return fail("UNSUPPORTED_SHAPE", "literal `value` must be a string, finite number, boolean, or null");
2424
+ }
2425
+ return { ok: true };
2426
+ }
2427
+ case "nullable": {
2428
+ const of = readOwnKey(raw, "of", keys.names, fail);
2429
+ if ("error" in of) {
2430
+ return { ok: false, error: of.error };
2431
+ }
2432
+ if (!of.present) {
2433
+ return fail("UNSUPPORTED_SHAPE", "nullable contract is missing `of`");
2434
+ }
2435
+ return validatePortContractNode(of.value, portName2, `${contractPath}.of`, depth + 1, budget);
2436
+ }
2437
+ }
2438
+ }
2439
+ function validatePortContract(contracts, portName2) {
2440
+ const contractPath = "contracts";
2441
+ const fail = makeFail(portName2, contractPath);
2442
+ const plain = isPlainObject(contracts, fail);
2443
+ if (!plain.ok) {
2444
+ return { ok: false, error: plain.error };
2445
+ }
2446
+ const keys = ownKeys(contracts, fail);
2447
+ if ("error" in keys) {
2448
+ return { ok: false, error: keys.error };
2449
+ }
2450
+ if (keys.symbols.length > 0) {
2451
+ return fail("HOSTILE_INPUT", "symbol-keyed properties are refused on the contracts block");
2452
+ }
2453
+ for (const name of keys.names) {
2454
+ if (name !== "request") {
2455
+ return fail("MALFORMED_CONTRACT", `unknown key "${name}" on the contracts block; only \`request\` is allowed`);
2456
+ }
2457
+ }
2458
+ if (!keys.names.includes("request")) {
2459
+ return fail("MALFORMED_CONTRACT", "contracts block is missing `request`");
2460
+ }
2461
+ const request = readOwnKey(contracts, "request", keys.names, fail);
2462
+ if ("error" in request) {
2463
+ return { ok: false, error: request.error };
2464
+ }
2465
+ if (!request.present) {
2466
+ return fail("MALFORMED_CONTRACT", "contracts block is missing `request`");
2467
+ }
2468
+ return validatePortContractNode(request.value, portName2, `${contractPath}.request`, 1, { nodesRemaining: MAX_CONTRACT_NODES });
2469
+ }
2470
+ function readOwnData(value, key) {
2471
+ try {
2472
+ const desc = Object.getOwnPropertyDescriptor(value, key);
2473
+ if (desc === void 0) {
2474
+ return { present: false };
2475
+ }
2476
+ if (desc.get !== void 0 || desc.set !== void 0) {
2477
+ return { present: false, error: "accessor; getters are never invoked" };
2478
+ }
2479
+ return { present: true, value: desc.value };
2480
+ } catch (err4) {
2481
+ return {
2482
+ present: false,
2483
+ error: `reflection threw: ${String(err4)}`
2484
+ };
2485
+ }
2486
+ }
2487
+ function inspectDenseArray(value) {
2488
+ try {
2489
+ if (!Array.isArray(value)) {
2490
+ return { kind: "not-array" };
2491
+ }
2492
+ const length = value.length;
2493
+ for (let i = 0; i < length; i += 1) {
2494
+ if (!(i in value)) {
2495
+ return {
2496
+ kind: "hostile",
2497
+ message: `sparse array (hole at index ${i})`
2498
+ };
2499
+ }
2500
+ }
2501
+ return { kind: "dense", length };
2502
+ } catch (err4) {
2503
+ return {
2504
+ kind: "hostile",
2505
+ message: `array inspection threw: ${String(err4)}`
2506
+ };
2507
+ }
2508
+ }
2509
+ function readDenseElement(arr, index) {
2510
+ try {
2511
+ const desc = Object.getOwnPropertyDescriptor(arr, String(index));
2512
+ if (desc === void 0) {
2513
+ return { error: `missing own data descriptor at index ${index}` };
2514
+ }
2515
+ if (desc.get !== void 0 || desc.set !== void 0) {
2516
+ return {
2517
+ error: `index ${index} is an accessor; getters are never invoked`
2518
+ };
2519
+ }
2520
+ return { value: desc.value };
2521
+ } catch (err4) {
2522
+ return {
2523
+ error: `descriptor inspection at index ${index} threw: ${String(err4)}`
2524
+ };
2525
+ }
2526
+ }
2527
+ function hostile(portName2, contractPath, message) {
2528
+ return {
2529
+ ok: false,
2530
+ error: new PortContractValidationError("HOSTILE_INPUT", portName2, contractPath, message)
2531
+ };
2532
+ }
2533
+ function validateManifestPortContracts(manifest) {
2534
+ if (manifest === null || typeof manifest !== "object") {
2535
+ return { ok: true };
2536
+ }
2537
+ const manifestShape = inspectDenseArray(manifest);
2538
+ if (manifestShape.kind === "hostile") {
2539
+ return hostile("<unnamed>", "manifest", manifestShape.message);
2540
+ }
2541
+ if (manifestShape.kind === "dense") {
2542
+ return { ok: true };
2543
+ }
2544
+ const boundedContextsRead = readOwnData(manifest, "bounded_contexts");
2545
+ if (boundedContextsRead.error !== void 0) {
2546
+ return hostile("<unnamed>", "manifest.bounded_contexts", boundedContextsRead.error);
2547
+ }
2548
+ if (!boundedContextsRead.present) {
2549
+ return { ok: true };
2550
+ }
2551
+ const contexts = boundedContextsRead.value;
2552
+ const contextsShape = inspectDenseArray(contexts);
2553
+ if (contextsShape.kind === "hostile") {
2554
+ return hostile("<unnamed>", "manifest.bounded_contexts", contextsShape.message);
2555
+ }
2556
+ if (contextsShape.kind !== "dense") {
2557
+ return { ok: true };
2558
+ }
2559
+ const contextsList = contexts;
2560
+ for (let ci = 0; ci < contextsShape.length; ci += 1) {
2561
+ const contextRead = readDenseElement(contextsList, ci);
2562
+ if ("error" in contextRead) {
2563
+ return hostile("<unnamed>", "bounded_contexts", contextRead.error);
2564
+ }
2565
+ const context = contextRead.value;
2566
+ if (context === null || typeof context !== "object") {
2567
+ continue;
2568
+ }
2569
+ const contextShape = inspectDenseArray(context);
2570
+ if (contextShape.kind === "hostile") {
2571
+ return hostile("<unnamed>", "bounded_contexts", contextShape.message);
2572
+ }
2573
+ if (contextShape.kind === "dense") {
2574
+ continue;
2575
+ }
2576
+ const layersRead = readOwnData(context, "layers");
2577
+ if (layersRead.error !== void 0) {
2578
+ return hostile("<unnamed>", "bounded_contexts.layers", layersRead.error);
2579
+ }
2580
+ if (!layersRead.present) {
2581
+ continue;
2582
+ }
2583
+ const layers = layersRead.value;
2584
+ if (layers === null || typeof layers !== "object") {
2585
+ continue;
2586
+ }
2587
+ const applicationRead = readOwnData(layers, "application");
2588
+ if (applicationRead.error !== void 0) {
2589
+ return hostile("<unnamed>", "bounded_contexts.layers.application", applicationRead.error);
2590
+ }
2591
+ if (!applicationRead.present) {
2592
+ continue;
2593
+ }
2594
+ const application = applicationRead.value;
2595
+ if (application === null || typeof application !== "object") {
2596
+ continue;
2597
+ }
2598
+ const portsRead = readOwnData(application, "ports");
2599
+ if (portsRead.error !== void 0) {
2600
+ return hostile("<unnamed>", "bounded_contexts.layers.application.ports", portsRead.error);
2601
+ }
2602
+ if (!portsRead.present) {
2603
+ continue;
2604
+ }
2605
+ const ports = portsRead.value;
2606
+ if (ports === null || typeof ports !== "object") {
2607
+ continue;
2608
+ }
2609
+ for (const direction of ["in", "out"]) {
2610
+ const listRead = readOwnData(ports, direction);
2611
+ if (listRead.error !== void 0) {
2612
+ return hostile("<unnamed>", `ports.${direction}`, listRead.error);
2613
+ }
2614
+ if (!listRead.present) {
2615
+ continue;
2616
+ }
2617
+ const list = listRead.value;
2618
+ const listShape = inspectDenseArray(list);
2619
+ if (listShape.kind === "hostile") {
2620
+ return hostile("<unnamed>", `ports.${direction}`, listShape.message);
2621
+ }
2622
+ if (listShape.kind !== "dense") {
2623
+ continue;
2624
+ }
2625
+ const listArr = list;
2626
+ for (let pi = 0; pi < listShape.length; pi += 1) {
2627
+ const portRead = readDenseElement(listArr, pi);
2628
+ if ("error" in portRead) {
2629
+ return hostile("<unnamed>", `ports.${direction}`, portRead.error);
2630
+ }
2631
+ const port = portRead.value;
2632
+ if (port === null || typeof port !== "object") {
2633
+ continue;
2634
+ }
2635
+ const portShape = inspectDenseArray(port);
2636
+ if (portShape.kind === "hostile") {
2637
+ return hostile("<unnamed>", `ports.${direction}`, portShape.message);
2638
+ }
2639
+ if (portShape.kind === "dense") {
2640
+ continue;
2641
+ }
2642
+ const portNameRead = readOwnData(port, "name");
2643
+ if (portNameRead.error !== void 0) {
2644
+ return hostile("<unnamed>", `ports.${direction}[name]`, portNameRead.error);
2645
+ }
2646
+ const portName2 = portNameRead.present && typeof portNameRead.value === "string" ? portNameRead.value : "<unnamed>";
2647
+ const contractsRead = readOwnData(port, "contracts");
2648
+ if (contractsRead.error !== void 0) {
2649
+ return hostile(portName2, "contracts", contractsRead.error);
2650
+ }
2651
+ if (!contractsRead.present) {
2652
+ continue;
2653
+ }
2654
+ const result = validatePortContract(contractsRead.value, portName2);
2655
+ if (!result.ok) {
2656
+ return result;
2657
+ }
2658
+ }
2659
+ }
2660
+ }
2661
+ return { ok: true };
2662
+ }
2663
+ var CodecGeneratorBlockSchema = z.object({
2664
+ runtimeModule: z.string().min(1).default(DEFAULT_CODEC_RUNTIME_MODULE)
2665
+ }).passthrough();
2666
+
2667
+ // ../project-configuration/dist/domain/model/manifest-schema/manifest-schema.js
2040
2668
  function caseInsensitiveEnum(schema, dir = "lower") {
2041
2669
  return z.preprocess((value) => typeof value === "string" ? dir === "lower" ? value.trim().toLowerCase() : value.trim().toUpperCase() : value, schema);
2042
2670
  }
@@ -2064,9 +2692,106 @@ var RelationshipSchema = z.object({
2064
2692
  }).optional(),
2065
2693
  notes: z.string().optional()
2066
2694
  });
2067
- var PortDefinitionSchema = z.object({
2695
+ var PortDefinitionSchema = z.preprocess((raw, ctx) => {
2696
+ const arrayCheck = safeIsArray(raw);
2697
+ if (arrayCheck === "hostile") {
2698
+ ctx.addIssue({
2699
+ code: z.ZodIssueCode.custom,
2700
+ path: ["contracts"],
2701
+ message: `HOSTILE_INPUT: array inspection threw (revoked or hostile proxy)`
2702
+ });
2703
+ return z.NEVER;
2704
+ }
2705
+ if (raw === null || typeof raw !== "object" || arrayCheck) {
2706
+ return raw;
2707
+ }
2708
+ let contractsDesc;
2709
+ try {
2710
+ contractsDesc = Object.getOwnPropertyDescriptor(raw, "contracts");
2711
+ } catch {
2712
+ ctx.addIssue({
2713
+ code: z.ZodIssueCode.custom,
2714
+ path: ["contracts"],
2715
+ message: `HOSTILE_INPUT: descriptor inspection on "contracts" threw`
2716
+ });
2717
+ return z.NEVER;
2718
+ }
2719
+ if (contractsDesc !== void 0 && (contractsDesc.get !== void 0 || contractsDesc.set !== void 0)) {
2720
+ ctx.addIssue({
2721
+ code: z.ZodIssueCode.custom,
2722
+ path: ["contracts"],
2723
+ message: `HOSTILE_INPUT: "contracts" is an accessor; getters are never invoked`
2724
+ });
2725
+ return z.NEVER;
2726
+ }
2727
+ const copy = {};
2728
+ for (const key of ["name", "owner"]) {
2729
+ try {
2730
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
2731
+ if (desc !== void 0 && desc.get === void 0 && desc.set === void 0) {
2732
+ copy[key] = desc.value;
2733
+ }
2734
+ } catch {
2735
+ }
2736
+ }
2737
+ if (contractsDesc !== void 0) {
2738
+ const contractsArrayCheck = safeIsArray(contractsDesc.value);
2739
+ if (contractsDesc.value !== null && typeof contractsDesc.value === "object" && contractsArrayCheck === "hostile") {
2740
+ ctx.addIssue({
2741
+ code: z.ZodIssueCode.custom,
2742
+ path: ["contracts"],
2743
+ message: `HOSTILE_INPUT: array inspection on "contracts" threw (revoked or hostile proxy)`
2744
+ });
2745
+ return z.NEVER;
2746
+ }
2747
+ copy.contracts = contractsDesc.value;
2748
+ }
2749
+ return copy;
2750
+ }, z.object({
2068
2751
  name: z.string(),
2069
- owner: z.string().optional()
2752
+ owner: z.string().optional(),
2753
+ // Declared as `z.unknown()` WITHOUT `.optional()` semantics relied on for
2754
+ // presence: the presence check happens in `superRefine` below via
2755
+ // `Object.getOwnPropertyDescriptor(port, "contracts")` only — never
2756
+ // `port.contracts` — so a present own `contracts` property whose value is
2757
+ // `undefined` is MALFORMED, while an absent key passes untouched. The deep
2758
+ // validation itself lives in validatePortContract (port-contract-schema.ts)
2759
+ // so Zod never parses untrusted `contracts:` data before descriptor
2760
+ // inspection runs. The preprocess above guarantees this object only ever
2761
+ // sees plain data.
2762
+ contracts: z.unknown().optional()
2763
+ })).superRefine((val, ctx) => {
2764
+ let desc;
2765
+ try {
2766
+ desc = Object.getOwnPropertyDescriptor(val, "contracts");
2767
+ } catch {
2768
+ ctx.addIssue({
2769
+ code: z.ZodIssueCode.custom,
2770
+ path: ["contracts"],
2771
+ message: `HOSTILE_INPUT: descriptor inspection on "contracts" threw`
2772
+ });
2773
+ return;
2774
+ }
2775
+ if (desc === void 0) {
2776
+ return;
2777
+ }
2778
+ if (desc.get !== void 0 || desc.set !== void 0) {
2779
+ ctx.addIssue({
2780
+ code: z.ZodIssueCode.custom,
2781
+ path: ["contracts"],
2782
+ message: `HOSTILE_INPUT: "contracts" is an accessor; getters are never invoked`
2783
+ });
2784
+ return;
2785
+ }
2786
+ const portName2 = typeof val.name === "string" ? val.name : "<unnamed>";
2787
+ const result = validatePortContract(desc.value, portName2);
2788
+ if (!result.ok) {
2789
+ ctx.addIssue({
2790
+ code: z.ZodIssueCode.custom,
2791
+ path: ["contracts"],
2792
+ message: result.error.message
2793
+ });
2794
+ }
2070
2795
  });
2071
2796
  var LegacyOrNewPortSchema = z.union([
2072
2797
  z.string(),
@@ -2134,7 +2859,12 @@ var CrossContextEdgeSchema = z.object({
2134
2859
  operations: z.array(z.string()).optional(),
2135
2860
  integrationPattern: z.enum(["open-host", "acl"]).optional()
2136
2861
  });
2137
- var GeneratorBlockSchema = z.object({ name: z.string().min(1).optional() }).passthrough();
2862
+ var GeneratorBlockSchema = z.object({
2863
+ name: z.string().min(1).optional(),
2864
+ // Typed codec block (H1). When present without `runtimeModule`, the
2865
+ // runtime module defaults to "@fleet/shared" (CodecGeneratorBlockSchema).
2866
+ codec: CodecGeneratorBlockSchema.optional()
2867
+ }).passthrough();
2138
2868
  var IndexManifestSchema = z.object({
2139
2869
  // Toolchain-compatibility stamp (see manifest-schema-version.ts). Note
2140
2870
  // `version` below is a DIFFERENT field — its `"2.0"` string is the
@@ -2411,7 +3141,10 @@ var GeneratorSyncSchema = z.object({
2411
3141
  var GeneratorConfigSchema = z.object({
2412
3142
  name: z.string().min(1).optional(),
2413
3143
  version: z.string().optional(),
2414
- sync: GeneratorSyncSchema.optional()
3144
+ sync: GeneratorSyncSchema.optional(),
3145
+ // Typed codec block (H1): `runtimeModule` defaults to "@fleet/shared" when
3146
+ // `codec` is present without it; `codec` stays undefined when absent.
3147
+ codec: CodecGeneratorBlockSchema.optional()
2415
3148
  }).passthrough();
2416
3149
  var WorkspaceConfigSchema = z.object({
2417
3150
  monorepo: MonorepoConfigSchema.optional(),
@@ -3778,9 +4511,9 @@ async function generateEslintConfig(moduleDir, moduleName, config, report, optio
3778
4511
  );
3779
4512
  recordWriteStatus(result, filePath, status);
3780
4513
  return result;
3781
- } catch (err3) {
3782
- const message = err3 instanceof Error ? err3.message : String(err3);
3783
- result.error = err3 instanceof Error ? err3 : new Error(`eslint generation failed for ${moduleName}: ${message}`);
4514
+ } catch (err4) {
4515
+ const message = err4 instanceof Error ? err4.message : String(err4);
4516
+ result.error = err4 instanceof Error ? err4 : new Error(`eslint generation failed for ${moduleName}: ${message}`);
3784
4517
  result.summary = `eslint generation failed for ${moduleName}: ${message}`;
3785
4518
  config.logger.error(result.summary);
3786
4519
  if (report) report.record("error", filePath, result.summary);
@@ -3848,8 +4581,8 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
3848
4581
  if (!config.dryRun && isInScope(target, config)) {
3849
4582
  try {
3850
4583
  await fs5.mkdir(path8.dirname(target), { recursive: true });
3851
- } catch (err3) {
3852
- const message = err3 instanceof Error ? err3.message : String(err3);
4584
+ } catch (err4) {
4585
+ const message = err4 instanceof Error ? err4.message : String(err4);
3853
4586
  config.logger.error(
3854
4587
  `[apps] failed to create dir for "${appName}" file ${relPath}: ${message}`
3855
4588
  );
@@ -3944,8 +4677,8 @@ async function generateApps(config, report) {
3944
4677
  try {
3945
4678
  await fs5.mkdir(appDir, { recursive: true });
3946
4679
  await fs5.mkdir(srcDir, { recursive: true });
3947
- } catch (err3) {
3948
- const message = err3 instanceof Error ? err3.message : String(err3);
4680
+ } catch (err4) {
4681
+ const message = err4 instanceof Error ? err4.message : String(err4);
3949
4682
  config.logger.error(
3950
4683
  `[apps] failed to create directory for "${app.name}": ${message}`
3951
4684
  );
@@ -4034,9 +4767,9 @@ async function generateApps(config, report) {
4034
4767
  result.summary = `apps: ${result.created.length} created, ${result.updated.length} updated, ${result.skipped.length} skipped`;
4035
4768
  }
4036
4769
  return result;
4037
- } catch (err3) {
4038
- const message = err3 instanceof Error ? err3.message : String(err3);
4039
- result.error = err3 instanceof Error ? err3 : new Error(`apps generation failed: ${message}`);
4770
+ } catch (err4) {
4771
+ const message = err4 instanceof Error ? err4.message : String(err4);
4772
+ result.error = err4 instanceof Error ? err4 : new Error(`apps generation failed: ${message}`);
4040
4773
  result.summary = `apps generation failed: ${message}`;
4041
4774
  config.logger.error(result.summary);
4042
4775
  if (report) report.record("error", "apps", result.summary);
@@ -4729,9 +5462,9 @@ async function writeStubFile(filePath, content, config, report) {
4729
5462
  );
4730
5463
  }
4731
5464
  return "skipped";
4732
- } catch (err3) {
4733
- if (!(err3 instanceof Error) || err3.code !== "ENOENT") {
4734
- throw err3;
5465
+ } catch (err4) {
5466
+ if (!(err4 instanceof Error) || err4.code !== "ENOENT") {
5467
+ throw err4;
4735
5468
  }
4736
5469
  }
4737
5470
  if (!config.dryRun) {
@@ -4895,12 +5628,2454 @@ async function generateStubs(moduleDir, moduleName, config, report) {
4895
5628
  }
4896
5629
  return result;
4897
5630
  }
4898
- var OHS_NOTE = "\n *\n * Open Host Service (open-host): this is this context's published language for consuming contexts — keep it stable.";
4899
- var ACL_NOTE = "\n *\n * Anti-Corruption Layer (acl): translate the upstream contract into this context's own domain model; do not leak provider types inward.";
4900
- function addAll(map, key, values) {
4901
- const set = map.get(key) ?? /* @__PURE__ */ new Set();
4902
- values.forEach((v) => set.add(v));
4903
- map.set(key, set);
5631
+
5632
+ // src/domain/services/codec-schema-builder.ts
5633
+ function ok2(value) {
5634
+ return { success: true, value };
5635
+ }
5636
+ function err2(error) {
5637
+ return { success: false, error };
5638
+ }
5639
+ var CodecGeneratorError = class extends Error {
5640
+ code;
5641
+ path;
5642
+ constructor(code, path28, message) {
5643
+ super(message);
5644
+ this.name = "CodecGeneratorError";
5645
+ this.code = code;
5646
+ this.path = path28;
5647
+ }
5648
+ };
5649
+ var POLLUTING_KEYS = /* @__PURE__ */ new Set([
5650
+ "__proto__",
5651
+ "constructor",
5652
+ "prototype"
5653
+ ]);
5654
+ var MAX_CONTRACT_DEPTH2 = 16;
5655
+ var MAX_OBJECT_FIELDS = 64;
5656
+ var MAX_ENUM_VALUES = 64;
5657
+ var MAX_TOTAL_NODES = 512;
5658
+ var DEFAULT_RUNTIME_MODULE = "@fleet/shared";
5659
+ function isPlainObjectSafe(value, path28) {
5660
+ let proto;
5661
+ try {
5662
+ proto = typeof value === "object" && value !== null ? Object.getPrototypeOf(value) : void 0;
5663
+ } catch {
5664
+ return err2(
5665
+ new CodecGeneratorError(
5666
+ "HOSTILE_INPUT",
5667
+ path28,
5668
+ `reflection threw while reading the prototype at ${path28} (hostile Proxy trap)`
5669
+ )
5670
+ );
5671
+ }
5672
+ return ok2(
5673
+ typeof value === "object" && value !== null && (proto === Object.prototype || proto === null)
5674
+ );
5675
+ }
5676
+ function readOwnDataProperty(obj, key, path28) {
5677
+ const plain = isPlainObjectSafe(obj, path28);
5678
+ if (!plain.success) return plain;
5679
+ if (!plain.value) {
5680
+ return err2(
5681
+ new CodecGeneratorError(
5682
+ "HOSTILE_INPUT",
5683
+ path28,
5684
+ `expected a plain object at ${path28}, got non-plain or non-object value`
5685
+ )
5686
+ );
5687
+ }
5688
+ if (POLLUTING_KEYS.has(key)) {
5689
+ return err2(
5690
+ new CodecGeneratorError(
5691
+ "PROTOTYPE_POLLUTION",
5692
+ path28,
5693
+ `refusing prototype-polluting key "${key}" at ${path28}`
5694
+ )
5695
+ );
5696
+ }
5697
+ let desc;
5698
+ try {
5699
+ desc = Object.getOwnPropertyDescriptor(obj, key);
5700
+ } catch {
5701
+ return err2(
5702
+ new CodecGeneratorError(
5703
+ "HOSTILE_INPUT",
5704
+ path28,
5705
+ `reflection threw while reading "${key}" at ${path28} (hostile Proxy trap)`
5706
+ )
5707
+ );
5708
+ }
5709
+ if (desc && ("get" in desc || "set" in desc)) {
5710
+ return err2(
5711
+ new CodecGeneratorError(
5712
+ "HOSTILE_INPUT",
5713
+ path28,
5714
+ `refusing accessor property "${key}" at ${path28} (getters are never invoked)`
5715
+ )
5716
+ );
5717
+ }
5718
+ return ok2(desc?.value);
5719
+ }
5720
+ function hasOwnDataProperty(obj, key, path28) {
5721
+ const plain = isPlainObjectSafe(obj, path28);
5722
+ if (!plain.success) return plain;
5723
+ if (!plain.value) {
5724
+ return err2(
5725
+ new CodecGeneratorError(
5726
+ "HOSTILE_INPUT",
5727
+ path28,
5728
+ `expected a plain object at ${path28}, got non-plain or non-object value`
5729
+ )
5730
+ );
5731
+ }
5732
+ if (POLLUTING_KEYS.has(key)) {
5733
+ return err2(
5734
+ new CodecGeneratorError(
5735
+ "PROTOTYPE_POLLUTION",
5736
+ path28,
5737
+ `refusing prototype-polluting key "${key}" at ${path28}`
5738
+ )
5739
+ );
5740
+ }
5741
+ let desc;
5742
+ try {
5743
+ desc = Object.getOwnPropertyDescriptor(obj, key);
5744
+ } catch {
5745
+ return err2(
5746
+ new CodecGeneratorError(
5747
+ "HOSTILE_INPUT",
5748
+ path28,
5749
+ `reflection threw while reading "${key}" at ${path28} (hostile Proxy trap)`
5750
+ )
5751
+ );
5752
+ }
5753
+ return ok2(desc !== void 0);
5754
+ }
5755
+ function readDenseArray(val, maxLen, path28) {
5756
+ let isArray;
5757
+ let proto;
5758
+ let lenDesc;
5759
+ try {
5760
+ isArray = Array.isArray(val);
5761
+ proto = isArray ? Object.getPrototypeOf(val) : void 0;
5762
+ lenDesc = isArray ? Object.getOwnPropertyDescriptor(val, "length") : void 0;
5763
+ } catch {
5764
+ return err2(
5765
+ new CodecGeneratorError(
5766
+ "HOSTILE_INPUT",
5767
+ path28,
5768
+ `reflection threw while inspecting array at ${path28} (hostile Proxy trap)`
5769
+ )
5770
+ );
5771
+ }
5772
+ if (!isArray) {
5773
+ return err2(
5774
+ new CodecGeneratorError(
5775
+ "MALFORMED_CONTRACT",
5776
+ path28,
5777
+ `expected a dense array at ${path28}, got a non-array (or array-like) value`
5778
+ )
5779
+ );
5780
+ }
5781
+ if (proto !== Array.prototype && proto !== null) {
5782
+ return err2(
5783
+ new CodecGeneratorError(
5784
+ "HOSTILE_INPUT",
5785
+ path28,
5786
+ `array at ${path28} has a non-plain prototype`
5787
+ )
5788
+ );
5789
+ }
5790
+ if (!lenDesc || "get" in lenDesc || "set" in lenDesc) {
5791
+ return err2(
5792
+ new CodecGeneratorError(
5793
+ "HOSTILE_INPUT",
5794
+ path28,
5795
+ `array "length" at ${path28} is missing or an accessor`
5796
+ )
5797
+ );
5798
+ }
5799
+ const len = lenDesc.value;
5800
+ if (typeof len !== "number" || !Number.isSafeInteger(len) || len < 0) {
5801
+ return err2(
5802
+ new CodecGeneratorError(
5803
+ "MALFORMED_CONTRACT",
5804
+ path28,
5805
+ `array "length" at ${path28} is not a non-negative safe integer`
5806
+ )
5807
+ );
5808
+ }
5809
+ if (len > maxLen) {
5810
+ return err2(
5811
+ new CodecGeneratorError(
5812
+ "BOUNDS_EXCEEDED",
5813
+ path28,
5814
+ `array at ${path28} has ${len} items, exceeding the bound ${maxLen}`
5815
+ )
5816
+ );
5817
+ }
5818
+ const items = [];
5819
+ for (let i = 0; i < len; i++) {
5820
+ let desc;
5821
+ try {
5822
+ desc = Object.getOwnPropertyDescriptor(val, String(i));
5823
+ } catch {
5824
+ return err2(
5825
+ new CodecGeneratorError(
5826
+ "HOSTILE_INPUT",
5827
+ path28,
5828
+ `reflection threw while reading index ${i} at ${path28}`
5829
+ )
5830
+ );
5831
+ }
5832
+ if (!desc) {
5833
+ return err2(
5834
+ new CodecGeneratorError(
5835
+ "HOSTILE_INPUT",
5836
+ path28,
5837
+ `sparse array hole at index ${i} of ${path28}`
5838
+ )
5839
+ );
5840
+ }
5841
+ if ("get" in desc || "set" in desc) {
5842
+ return err2(
5843
+ new CodecGeneratorError(
5844
+ "HOSTILE_INPUT",
5845
+ path28,
5846
+ `accessor at index ${i} of ${path28} (getters are never invoked)`
5847
+ )
5848
+ );
5849
+ }
5850
+ items.push(desc.value);
5851
+ }
5852
+ return ok2(items);
5853
+ }
5854
+ function resolveRuntimeModule(manifest) {
5855
+ const codecResult = readOwnDataProperty(manifest, "codec", "codec");
5856
+ if (!codecResult.success) return codecResult;
5857
+ const codec = codecResult.value;
5858
+ if (codec === void 0) return ok2(DEFAULT_RUNTIME_MODULE);
5859
+ const modResult = readOwnDataProperty(
5860
+ codec,
5861
+ "runtimeModule",
5862
+ "codec.runtimeModule"
5863
+ );
5864
+ if (!modResult.success) return modResult;
5865
+ const mod = modResult.value;
5866
+ if (mod === void 0) return ok2(DEFAULT_RUNTIME_MODULE);
5867
+ if (typeof mod !== "string" || mod.length === 0 || mod.length > 256) {
5868
+ return err2(
5869
+ new CodecGeneratorError(
5870
+ "MALFORMED_RUNTIME_MODULE",
5871
+ "codec.runtimeModule",
5872
+ `codec.runtimeModule must be a non-empty string of at most 256 characters`
5873
+ )
5874
+ );
5875
+ }
5876
+ if (/["'`\n\r]/.test(mod)) {
5877
+ return err2(
5878
+ new CodecGeneratorError(
5879
+ "MALFORMED_RUNTIME_MODULE",
5880
+ "codec.runtimeModule",
5881
+ `codec.runtimeModule contains quotes, newlines or control characters`
5882
+ )
5883
+ );
5884
+ }
5885
+ for (let i = 0; i < mod.length; i++) {
5886
+ if (mod.charCodeAt(i) < 32 || mod.charCodeAt(i) === 127) {
5887
+ return err2(
5888
+ new CodecGeneratorError(
5889
+ "MALFORMED_RUNTIME_MODULE",
5890
+ "codec.runtimeModule",
5891
+ `codec.runtimeModule contains quotes, newlines or control characters`
5892
+ )
5893
+ );
5894
+ }
5895
+ }
5896
+ return ok2(mod);
5897
+ }
5898
+ function isUnsupportedKind(kind) {
5899
+ return kind === "union" || kind === "tuple" || kind === "record" || kind === "any" || kind === "unknown";
5900
+ }
5901
+ function buildNode(node, path28, depth, counter) {
5902
+ if (depth > MAX_CONTRACT_DEPTH2) {
5903
+ return err2(
5904
+ new CodecGeneratorError(
5905
+ "BOUNDS_EXCEEDED",
5906
+ path28,
5907
+ `contract nesting exceeds MAX_CONTRACT_DEPTH (${MAX_CONTRACT_DEPTH2}) at ${path28}`
5908
+ )
5909
+ );
5910
+ }
5911
+ if (typeof node !== "object" || node === null) {
5912
+ return err2(
5913
+ new CodecGeneratorError(
5914
+ "MALFORMED_CONTRACT",
5915
+ path28,
5916
+ `expected a contract node (object) at ${path28}, got ${node === null ? "null" : typeof node}`
5917
+ )
5918
+ );
5919
+ }
5920
+ counter.count += 1;
5921
+ if (counter.count > MAX_TOTAL_NODES) {
5922
+ return err2(
5923
+ new CodecGeneratorError(
5924
+ "BOUNDS_EXCEEDED",
5925
+ path28,
5926
+ `contract tree exceeds MAX_TOTAL_NODES (${MAX_TOTAL_NODES}) at ${path28}`
5927
+ )
5928
+ );
5929
+ }
5930
+ const kindResult = readOwnDataProperty(node, "kind", path28);
5931
+ if (!kindResult.success) return kindResult;
5932
+ const kind = kindResult.value;
5933
+ if (typeof kind !== "string") {
5934
+ return err2(
5935
+ new CodecGeneratorError(
5936
+ "UNKNOWN_TYPE",
5937
+ path28,
5938
+ `contract "kind" at ${path28} is not a string`
5939
+ )
5940
+ );
5941
+ }
5942
+ switch (kind) {
5943
+ case "string": {
5944
+ const minLengthResult = readOwnDataProperty(node, "minLength", path28);
5945
+ if (!minLengthResult.success) return minLengthResult;
5946
+ const hasMinLength = hasOwnDataProperty(node, "minLength", path28);
5947
+ if (!hasMinLength.success) return hasMinLength;
5948
+ if (hasMinLength.value) {
5949
+ return err2(
5950
+ new CodecGeneratorError(
5951
+ "UNSUPPORTED_SHAPE",
5952
+ path28,
5953
+ `string contracts with minLength are not supported at ${path28}`
5954
+ )
5955
+ );
5956
+ }
5957
+ const maxResult = readOwnDataProperty(node, "maxLength", path28);
5958
+ if (!maxResult.success) return maxResult;
5959
+ const maxLength = maxResult.value;
5960
+ if (maxLength === void 0) {
5961
+ return err2(
5962
+ new CodecGeneratorError(
5963
+ "MISSING_BOUND",
5964
+ path28,
5965
+ `string at ${path28} requires a positive safe-integer maxLength`
5966
+ )
5967
+ );
5968
+ }
5969
+ if (typeof maxLength !== "number" || !Number.isSafeInteger(maxLength) || maxLength <= 0) {
5970
+ return err2(
5971
+ new CodecGeneratorError(
5972
+ "MALFORMED_CONTRACT",
5973
+ path28,
5974
+ `string "maxLength" at ${path28} is not a positive safe integer`
5975
+ )
5976
+ );
5977
+ }
5978
+ const patternResult = readOwnDataProperty(node, "pattern", path28);
5979
+ if (!patternResult.success) return patternResult;
5980
+ const pattern = patternResult.value;
5981
+ if (pattern === void 0) {
5982
+ return ok2({ kind: "string", maxLength });
5983
+ }
5984
+ if (typeof pattern !== "string") {
5985
+ return err2(
5986
+ new CodecGeneratorError(
5987
+ "MALFORMED_CONTRACT",
5988
+ path28,
5989
+ `string "pattern" at ${path28} is not a string`
5990
+ )
5991
+ );
5992
+ }
5993
+ return ok2({ kind: "string", maxLength, pattern });
5994
+ }
5995
+ case "array": {
5996
+ const maxResult = readOwnDataProperty(node, "maxItems", path28);
5997
+ if (!maxResult.success) return maxResult;
5998
+ const maxItems = maxResult.value;
5999
+ if (maxItems === void 0) {
6000
+ return err2(
6001
+ new CodecGeneratorError(
6002
+ "MISSING_BOUND",
6003
+ path28,
6004
+ `array at ${path28} requires a positive safe-integer maxItems`
6005
+ )
6006
+ );
6007
+ }
6008
+ if (typeof maxItems !== "number" || !Number.isSafeInteger(maxItems) || maxItems <= 0) {
6009
+ return err2(
6010
+ new CodecGeneratorError(
6011
+ "MALFORMED_CONTRACT",
6012
+ path28,
6013
+ `array "maxItems" at ${path28} is not a positive safe integer`
6014
+ )
6015
+ );
6016
+ }
6017
+ const itemsResult = readOwnDataProperty(node, "items", path28);
6018
+ if (!itemsResult.success) return itemsResult;
6019
+ if (itemsResult.value === void 0) {
6020
+ return err2(
6021
+ new CodecGeneratorError(
6022
+ "MALFORMED_CONTRACT",
6023
+ path28,
6024
+ `array at ${path28} is missing "items"`
6025
+ )
6026
+ );
6027
+ }
6028
+ const items = buildNode(
6029
+ itemsResult.value,
6030
+ `${path28}.items`,
6031
+ depth + 1,
6032
+ counter
6033
+ );
6034
+ if (!items.success) return items;
6035
+ return ok2({ kind: "array", items: items.value, maxItems });
6036
+ }
6037
+ case "object": {
6038
+ const exactResult = readOwnDataProperty(node, "exact", path28);
6039
+ if (!exactResult.success) return exactResult;
6040
+ if (exactResult.value !== void 0 && exactResult.value !== true) {
6041
+ return err2(
6042
+ new CodecGeneratorError(
6043
+ "UNSUPPORTED_SHAPE",
6044
+ path28,
6045
+ `non-exact objects (exact: false) are not supported at ${path28}`
6046
+ )
6047
+ );
6048
+ }
6049
+ const fieldsResult = readOwnDataProperty(node, "fields", path28);
6050
+ if (!fieldsResult.success) return fieldsResult;
6051
+ const fieldsRaw = fieldsResult.value;
6052
+ if (fieldsRaw === void 0) {
6053
+ return err2(
6054
+ new CodecGeneratorError(
6055
+ "MALFORMED_CONTRACT",
6056
+ path28,
6057
+ `object at ${path28} is missing a plain-object "fields"`
6058
+ )
6059
+ );
6060
+ }
6061
+ const fieldsPlain = isPlainObjectSafe(fieldsRaw, path28);
6062
+ if (!fieldsPlain.success) return fieldsPlain;
6063
+ if (!fieldsPlain.value) {
6064
+ return err2(
6065
+ new CodecGeneratorError(
6066
+ "MALFORMED_CONTRACT",
6067
+ path28,
6068
+ `object at ${path28} is missing a plain-object "fields"`
6069
+ )
6070
+ );
6071
+ }
6072
+ const enumerableKeys = [];
6073
+ try {
6074
+ for (const key in fieldsRaw) {
6075
+ if (Object.prototype.hasOwnProperty.call(fieldsRaw, key)) {
6076
+ enumerableKeys.push(key);
6077
+ if (enumerableKeys.length > MAX_OBJECT_FIELDS) {
6078
+ return err2(
6079
+ new CodecGeneratorError(
6080
+ "BOUNDS_EXCEEDED",
6081
+ path28,
6082
+ `object at ${path28} exceeds MAX_OBJECT_FIELDS (${MAX_OBJECT_FIELDS}) before key materialization`
6083
+ )
6084
+ );
6085
+ }
6086
+ }
6087
+ }
6088
+ } catch {
6089
+ return err2(
6090
+ new CodecGeneratorError(
6091
+ "HOSTILE_INPUT",
6092
+ path28,
6093
+ `reflection threw while enumerating fields at ${path28}`
6094
+ )
6095
+ );
6096
+ }
6097
+ let keys;
6098
+ try {
6099
+ keys = Object.getOwnPropertyNames(fieldsRaw);
6100
+ } catch {
6101
+ return err2(
6102
+ new CodecGeneratorError(
6103
+ "HOSTILE_INPUT",
6104
+ path28,
6105
+ `reflection threw while enumerating fields at ${path28}`
6106
+ )
6107
+ );
6108
+ }
6109
+ if (keys.length !== enumerableKeys.length) {
6110
+ return err2(
6111
+ new CodecGeneratorError(
6112
+ "HOSTILE_INPUT",
6113
+ path28,
6114
+ `object at ${path28} carries non-enumerable own properties on "fields" (count cannot be established cheaply)`
6115
+ )
6116
+ );
6117
+ }
6118
+ if (keys.length > MAX_OBJECT_FIELDS) {
6119
+ return err2(
6120
+ new CodecGeneratorError(
6121
+ "BOUNDS_EXCEEDED",
6122
+ path28,
6123
+ `object at ${path28} has ${keys.length} fields, exceeding MAX_OBJECT_FIELDS (${MAX_OBJECT_FIELDS})`
6124
+ )
6125
+ );
6126
+ }
6127
+ const fields = {};
6128
+ for (const key of keys) {
6129
+ const fieldResult = readOwnDataProperty(
6130
+ fieldsRaw,
6131
+ key,
6132
+ `${path28}.${key}`
6133
+ );
6134
+ if (!fieldResult.success) return fieldResult;
6135
+ const built = buildNode(
6136
+ fieldResult.value,
6137
+ `${path28}.${key}`,
6138
+ depth + 1,
6139
+ counter
6140
+ );
6141
+ if (!built.success) return built;
6142
+ fields[key] = built.value;
6143
+ }
6144
+ return ok2({ kind: "object", exact: true, fields });
6145
+ }
6146
+ case "integer":
6147
+ case "number": {
6148
+ const out = {
6149
+ kind
6150
+ };
6151
+ const minResult = readOwnDataProperty(node, "min", path28);
6152
+ if (!minResult.success) return minResult;
6153
+ const maxResult = readOwnDataProperty(node, "max", path28);
6154
+ if (!maxResult.success) return maxResult;
6155
+ const min = minResult.value;
6156
+ const max = maxResult.value;
6157
+ if (min !== void 0) {
6158
+ if (typeof min !== "number") {
6159
+ return err2(
6160
+ new CodecGeneratorError(
6161
+ "MALFORMED_CONTRACT",
6162
+ path28,
6163
+ `integer/number "min" at ${path28} is not a finite number`
6164
+ )
6165
+ );
6166
+ }
6167
+ const valid = kind === "integer" ? Number.isSafeInteger(min) : Number.isFinite(min);
6168
+ if (!valid) {
6169
+ return err2(
6170
+ new CodecGeneratorError(
6171
+ "MALFORMED_CONTRACT",
6172
+ path28,
6173
+ `integer/number "min" at ${path28} is not a finite number`
6174
+ )
6175
+ );
6176
+ }
6177
+ out.min = min;
6178
+ }
6179
+ if (max !== void 0) {
6180
+ if (typeof max !== "number") {
6181
+ return err2(
6182
+ new CodecGeneratorError(
6183
+ "MALFORMED_CONTRACT",
6184
+ path28,
6185
+ `integer/number "max" at ${path28} is not a finite number`
6186
+ )
6187
+ );
6188
+ }
6189
+ const valid = kind === "integer" ? Number.isSafeInteger(max) : Number.isFinite(max);
6190
+ if (!valid) {
6191
+ return err2(
6192
+ new CodecGeneratorError(
6193
+ "MALFORMED_CONTRACT",
6194
+ path28,
6195
+ `integer/number "max" at ${path28} is not a finite number`
6196
+ )
6197
+ );
6198
+ }
6199
+ out.max = max;
6200
+ }
6201
+ if (out.min !== void 0 && out.max !== void 0 && out.min > out.max) {
6202
+ return err2(
6203
+ new CodecGeneratorError(
6204
+ "MALFORMED_CONTRACT",
6205
+ path28,
6206
+ `min > max at ${path28}`
6207
+ )
6208
+ );
6209
+ }
6210
+ return ok2(out);
6211
+ }
6212
+ case "boolean":
6213
+ return ok2({ kind: "boolean" });
6214
+ case "enum": {
6215
+ const valuesResult = readOwnDataProperty(node, "values", path28);
6216
+ if (!valuesResult.success) return valuesResult;
6217
+ if (valuesResult.value === void 0) {
6218
+ return err2(
6219
+ new CodecGeneratorError(
6220
+ "MALFORMED_CONTRACT",
6221
+ path28,
6222
+ `enum at ${path28} is missing "values"`
6223
+ )
6224
+ );
6225
+ }
6226
+ const dense = readDenseArray(
6227
+ valuesResult.value,
6228
+ MAX_ENUM_VALUES,
6229
+ `${path28}.values`
6230
+ );
6231
+ if (!dense.success) return dense;
6232
+ const values = dense.value;
6233
+ if (values.length < 1) {
6234
+ return err2(
6235
+ new CodecGeneratorError(
6236
+ "MALFORMED_CONTRACT",
6237
+ path28,
6238
+ `enum at ${path28} has an empty "values" array`
6239
+ )
6240
+ );
6241
+ }
6242
+ const strs = [];
6243
+ for (const v of values) {
6244
+ if (typeof v !== "string") {
6245
+ return err2(
6246
+ new CodecGeneratorError(
6247
+ "MALFORMED_CONTRACT",
6248
+ path28,
6249
+ `enum at ${path28} contains a non-string value`
6250
+ )
6251
+ );
6252
+ }
6253
+ strs.push(v);
6254
+ }
6255
+ return ok2({ kind: "enum", values: strs });
6256
+ }
6257
+ case "literal": {
6258
+ const valueResult = readOwnDataProperty(node, "value", path28);
6259
+ if (!valueResult.success) return valueResult;
6260
+ const value = valueResult.value;
6261
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && value !== null) {
6262
+ return err2(
6263
+ new CodecGeneratorError(
6264
+ "MALFORMED_CONTRACT",
6265
+ path28,
6266
+ `literal at ${path28} must carry a string/number/boolean/null value`
6267
+ )
6268
+ );
6269
+ }
6270
+ if (typeof value === "number" && !Number.isFinite(value)) {
6271
+ return err2(
6272
+ new CodecGeneratorError(
6273
+ "MALFORMED_CONTRACT",
6274
+ path28,
6275
+ `literal at ${path28} must be a finite number (NaN and Infinity are refused)`
6276
+ )
6277
+ );
6278
+ }
6279
+ return ok2({ kind: "literal", value });
6280
+ }
6281
+ case "nullable": {
6282
+ const ofResult = readOwnDataProperty(node, "of", path28);
6283
+ if (!ofResult.success) return ofResult;
6284
+ if (ofResult.value === void 0) {
6285
+ return err2(
6286
+ new CodecGeneratorError(
6287
+ "MALFORMED_CONTRACT",
6288
+ path28,
6289
+ `nullable at ${path28} is missing "of"`
6290
+ )
6291
+ );
6292
+ }
6293
+ const of = buildNode(ofResult.value, `${path28}.of`, depth + 1, counter);
6294
+ if (!of.success) return of;
6295
+ return ok2({ kind: "nullable", of: of.value });
6296
+ }
6297
+ default:
6298
+ if (isUnsupportedKind(kind)) {
6299
+ return err2(
6300
+ new CodecGeneratorError(
6301
+ "UNSUPPORTED_SHAPE",
6302
+ path28,
6303
+ `unsupported contract shape "${kind}" at ${path28}`
6304
+ )
6305
+ );
6306
+ }
6307
+ return err2(
6308
+ new CodecGeneratorError(
6309
+ "UNKNOWN_TYPE",
6310
+ path28,
6311
+ `unknown contract kind "${kind}" at ${path28}`
6312
+ )
6313
+ );
6314
+ }
6315
+ }
6316
+ function buildCodecSchema(rawContract, pathPrefix = "contract") {
6317
+ const counter = { count: 0 };
6318
+ if (typeof rawContract === "object" && rawContract !== null) {
6319
+ const kindPeek = readOwnDataProperty(rawContract, "kind", pathPrefix);
6320
+ if (kindPeek.success && kindPeek.value === void 0) {
6321
+ const requestPeek = readOwnDataProperty(
6322
+ rawContract,
6323
+ "request",
6324
+ pathPrefix
6325
+ );
6326
+ if (!requestPeek.success) return requestPeek;
6327
+ if (requestPeek.value !== void 0) {
6328
+ return buildNode(
6329
+ requestPeek.value,
6330
+ `${pathPrefix}.request`,
6331
+ 1,
6332
+ counter
6333
+ );
6334
+ }
6335
+ } else if (!kindPeek.success) {
6336
+ return kindPeek;
6337
+ }
6338
+ }
6339
+ return buildNode(rawContract, pathPrefix, 1, counter);
6340
+ }
6341
+ function compareCodePoint(a, b) {
6342
+ return a < b ? -1 : a > b ? 1 : 0;
6343
+ }
6344
+ function tsTypeOf(schema) {
6345
+ switch (schema.kind) {
6346
+ case "object": {
6347
+ const entries = Object.keys(schema.fields).sort(compareCodePoint);
6348
+ const parts = entries.map((key) => {
6349
+ const safeKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
6350
+ return `readonly ${safeKey}: ${tsTypeOf(schema.fields[key])};`;
6351
+ });
6352
+ return parts.length === 0 ? "{}" : `{ ${parts.join(" ")} }`;
6353
+ }
6354
+ case "array":
6355
+ return `ReadonlyArray<${tsTypeOf(schema.items)}>`;
6356
+ case "string":
6357
+ return "string";
6358
+ case "integer":
6359
+ case "number":
6360
+ return "number";
6361
+ case "boolean":
6362
+ return "boolean";
6363
+ case "enum":
6364
+ return schema.values.map((v) => JSON.stringify(v)).sort(compareCodePoint).join(" | ");
6365
+ case "literal":
6366
+ return schema.value === null ? "null" : JSON.stringify(schema.value);
6367
+ case "nullable":
6368
+ return `${tsTypeOf(schema.of)} | null`;
6369
+ }
6370
+ }
6371
+ function renderSchemaLiteral(schema, indent) {
6372
+ const inner = `${indent} `;
6373
+ switch (schema.kind) {
6374
+ case "object": {
6375
+ const keys = Object.keys(schema.fields).sort(compareCodePoint);
6376
+ const lines = keys.map(
6377
+ (key) => `${inner}${JSON.stringify(key)}: ${renderSchemaLiteral(schema.fields[key], inner)},`
6378
+ );
6379
+ return `{ kind: "object", exact: true, fields: {
6380
+ ${lines.join("\n")}
6381
+ ${indent}} }`;
6382
+ }
6383
+ case "array":
6384
+ return `{ kind: "array", items: ${renderSchemaLiteral(schema.items, inner)}, maxItems: ${schema.maxItems} }`;
6385
+ case "string": {
6386
+ const pattern = schema.pattern !== void 0 ? `, pattern: ${JSON.stringify(schema.pattern)}` : "";
6387
+ return `{ kind: "string", maxLength: ${schema.maxLength}${pattern} }`;
6388
+ }
6389
+ case "integer":
6390
+ case "number": {
6391
+ const min = schema.min !== void 0 ? `, min: ${schema.min}` : "";
6392
+ const max = schema.max !== void 0 ? `, max: ${schema.max}` : "";
6393
+ return `{ kind: "${schema.kind}"${min}${max} }`;
6394
+ }
6395
+ case "boolean":
6396
+ return `{ kind: "boolean" }`;
6397
+ case "enum":
6398
+ return `{ kind: "enum", values: [${schema.values.map((v) => JSON.stringify(v)).join(", ")}] }`;
6399
+ case "literal":
6400
+ return `{ kind: "literal", value: ${JSON.stringify(schema.value)} }`;
6401
+ case "nullable":
6402
+ return `{ kind: "nullable", of: ${renderSchemaLiteral(schema.of, inner)} }`;
6403
+ }
6404
+ }
6405
+ function renderCodecModule(input) {
6406
+ const { portName: portName2, schemaId, runtimeModule, schema } = input;
6407
+ const tsType = tsTypeOf(schema);
6408
+ const literal = renderSchemaLiteral(schema, " ");
6409
+ return `// @generated by @hexagen/sync
6410
+ import { createCodec, type Codec, type CodecEnv, type CodecSchema, type Validated } from ${JSON.stringify(runtimeModule)};
6411
+
6412
+ export type ${portName2}Request = Validated<${tsType}>;
6413
+
6414
+ const schema = ${literal} as const satisfies CodecSchema;
6415
+
6416
+ export function create${portName2}Codec(env: CodecEnv): Codec<${tsType}> {
6417
+ return createCodec<${tsType}>(${JSON.stringify(schemaId)}, schema, env);
6418
+ }
6419
+ `;
6420
+ }
6421
+
6422
+ // src/generators/codecs.ts
6423
+ var MAX_BOUNDED_CONTEXTS = 64;
6424
+ var MAX_PORTS_PER_DIRECTION = 64;
6425
+ async function generateCodecs(moduleDir, moduleName, config, report) {
6426
+ const result = createEmptyResult();
6427
+ try {
6428
+ const runtimeModuleResult = resolveRuntimeModule(config.manifest);
6429
+ if (!runtimeModuleResult.success) {
6430
+ result.error = runtimeModuleResult.error;
6431
+ return result;
6432
+ }
6433
+ const runtimeModule = runtimeModuleResult.value;
6434
+ const layersResult = readLayersConfig(config.manifest);
6435
+ if (!layersResult.success) {
6436
+ result.error = layersResult.error;
6437
+ return result;
6438
+ }
6439
+ const layersConfig = layersResult.value;
6440
+ return await emitCodecs(
6441
+ moduleDir,
6442
+ moduleName,
6443
+ config,
6444
+ report,
6445
+ result,
6446
+ runtimeModule,
6447
+ layersConfig
6448
+ );
6449
+ } catch (thrown) {
6450
+ result.error = thrown instanceof CodecGeneratorError ? thrown : thrown instanceof Error ? thrown : new Error(String(thrown));
6451
+ return result;
6452
+ }
6453
+ }
6454
+ function readLayersConfig(manifest) {
6455
+ const gen = readOwnDataProperty(manifest, "generator", "generator");
6456
+ if (!gen.success) return gen;
6457
+ if (gen.value === void 0) return ok2(void 0);
6458
+ const sync = readOwnDataProperty(gen.value, "sync", "generator.sync");
6459
+ if (!sync.success) return sync;
6460
+ if (sync.value === void 0) return ok2(void 0);
6461
+ const layers = readOwnDataProperty(
6462
+ sync.value,
6463
+ "layers",
6464
+ "generator.sync.layers"
6465
+ );
6466
+ if (!layers.success) return layers;
6467
+ const layersRaw = layers.value;
6468
+ if (layersRaw === void 0) return ok2(void 0);
6469
+ const app = readOwnDataProperty(
6470
+ layersRaw,
6471
+ "application",
6472
+ "generator.sync.layers.application"
6473
+ );
6474
+ if (!app.success) return app;
6475
+ if (app.value === void 0) return ok2({});
6476
+ const folder = readOwnDataProperty(
6477
+ app.value,
6478
+ "folder",
6479
+ "generator.sync.layers.application.folder"
6480
+ );
6481
+ if (!folder.success) return folder;
6482
+ const folderValue = folder.value;
6483
+ if (folderValue !== void 0 && typeof folderValue !== "string") {
6484
+ return err2(
6485
+ new CodecGeneratorError(
6486
+ "HOSTILE_INPUT",
6487
+ "generator.sync.layers.application.folder",
6488
+ `layer "folder" at generator.sync.layers.application.folder is not a string`
6489
+ )
6490
+ );
6491
+ }
6492
+ return ok2({
6493
+ application: { folder: folderValue }
6494
+ });
6495
+ }
6496
+ async function emitCodecs(moduleDir, moduleName, config, report, result, runtimeModule, layersConfig) {
6497
+ const manifest = config.manifest;
6498
+ const bcsResult = readOwnDataProperty(
6499
+ manifest,
6500
+ "bounded_contexts",
6501
+ "bounded_contexts"
6502
+ );
6503
+ if (!bcsResult.success) {
6504
+ result.error = bcsResult.error;
6505
+ return result;
6506
+ }
6507
+ if (bcsResult.value === void 0) return result;
6508
+ const bcs = readDenseArray(
6509
+ bcsResult.value,
6510
+ MAX_BOUNDED_CONTEXTS,
6511
+ "bounded_contexts"
6512
+ );
6513
+ if (!bcs.success) {
6514
+ result.error = bcs.error;
6515
+ return result;
6516
+ }
6517
+ let context;
6518
+ let found = false;
6519
+ for (const rawContext of bcs.value) {
6520
+ const nameResult = readOwnDataProperty(
6521
+ rawContext,
6522
+ "name",
6523
+ "bounded_contexts[].name"
6524
+ );
6525
+ if (!nameResult.success) {
6526
+ result.error = nameResult.error;
6527
+ return result;
6528
+ }
6529
+ if (nameResult.value === moduleName) {
6530
+ context = rawContext;
6531
+ found = true;
6532
+ break;
6533
+ }
6534
+ }
6535
+ if (!found) return result;
6536
+ const layersResult = readOwnDataProperty(context, "layers", "layers");
6537
+ if (!layersResult.success) {
6538
+ result.error = layersResult.error;
6539
+ return result;
6540
+ }
6541
+ if (layersResult.value === void 0) return result;
6542
+ const appResult = readOwnDataProperty(
6543
+ layersResult.value,
6544
+ "application",
6545
+ "layers.application"
6546
+ );
6547
+ if (!appResult.success) {
6548
+ result.error = appResult.error;
6549
+ return result;
6550
+ }
6551
+ if (appResult.value === void 0) return result;
6552
+ const portsResult = readOwnDataProperty(
6553
+ appResult.value,
6554
+ "ports",
6555
+ "layers.application.ports"
6556
+ );
6557
+ if (!portsResult.success) {
6558
+ result.error = portsResult.error;
6559
+ return result;
6560
+ }
6561
+ if (portsResult.value === void 0) return result;
6562
+ for (const direction of ["in", "out"]) {
6563
+ const dirResult = readOwnDataProperty(
6564
+ portsResult.value,
6565
+ direction,
6566
+ `layers.application.ports.${direction}`
6567
+ );
6568
+ if (!dirResult.success) {
6569
+ result.error = dirResult.error;
6570
+ return result;
6571
+ }
6572
+ if (dirResult.value === void 0) continue;
6573
+ const ports = readDenseArray(
6574
+ dirResult.value,
6575
+ MAX_PORTS_PER_DIRECTION,
6576
+ `layers.application.ports.${direction}`
6577
+ );
6578
+ if (!ports.success) {
6579
+ result.error = ports.error;
6580
+ return result;
6581
+ }
6582
+ const subdir = resolveEmissionDir(
6583
+ layersConfig,
6584
+ `application/ports/${direction}`
6585
+ );
6586
+ for (const port of ports.value) {
6587
+ const emitted = await emitPortCodec(
6588
+ port,
6589
+ direction,
6590
+ moduleDir,
6591
+ subdir,
6592
+ moduleName,
6593
+ runtimeModule,
6594
+ config,
6595
+ report,
6596
+ result
6597
+ );
6598
+ if (!emitted) return result;
6599
+ }
6600
+ }
6601
+ return result;
6602
+ }
6603
+ async function emitPortCodec(port, direction, moduleDir, subdir, moduleName, runtimeModule, config, report, result) {
6604
+ if (typeof port === "string") return true;
6605
+ const contractsResult = readOwnDataProperty(
6606
+ port,
6607
+ "contracts",
6608
+ `${moduleName}.ports.${direction}[].contracts`
6609
+ );
6610
+ if (!contractsResult.success) {
6611
+ result.error = contractsResult.error;
6612
+ return false;
6613
+ }
6614
+ if (contractsResult.value === void 0) return true;
6615
+ const nameResult = readOwnDataProperty(
6616
+ port,
6617
+ "name",
6618
+ `${moduleName}.ports.${direction}[].name`
6619
+ );
6620
+ if (!nameResult.success) {
6621
+ result.error = nameResult.error;
6622
+ return false;
6623
+ }
6624
+ const rawName = nameResult.value;
6625
+ if (typeof rawName !== "string" || rawName.length === 0) {
6626
+ result.error = new CodecGeneratorError(
6627
+ "MALFORMED_CONTRACT",
6628
+ `${moduleName}.ports.${direction}[].name`,
6629
+ `port "name" must be a non-empty string`
6630
+ );
6631
+ return false;
6632
+ }
6633
+ const namingTemplate = direction === "in" ? DEFAULT_NAMING.inPort : DEFAULT_NAMING.outPort;
6634
+ const portPascalName = normalizeStubName(rawName, namingTemplate);
6635
+ const filePath = path8.join(moduleDir, subdir, `${portPascalName}.codec.ts`);
6636
+ const schemaResult = buildCodecSchema(
6637
+ contractsResult.value,
6638
+ `${moduleName}.${portPascalName}`
6639
+ );
6640
+ if (!schemaResult.success) {
6641
+ result.error = schemaResult.error;
6642
+ return false;
6643
+ }
6644
+ const content = renderCodecModule({
6645
+ portName: portPascalName,
6646
+ schemaId: `${moduleName}.${portPascalName}`,
6647
+ runtimeModule,
6648
+ schema: schemaResult.value
6649
+ });
6650
+ if (!isInScope(filePath, config)) {
6651
+ config.logger.debug(
6652
+ `skipped (outside --only) ${path8.relative(config.workspaceRoot, filePath)}`
6653
+ );
6654
+ recordWriteStatus(result, filePath, "skipped");
6655
+ return true;
6656
+ }
6657
+ if (!config.dryRun) {
6658
+ await fs5.mkdir(path8.dirname(filePath), { recursive: true });
6659
+ }
6660
+ const status = await safeWriteFileAtomic(
6661
+ filePath,
6662
+ content,
6663
+ config,
6664
+ report,
6665
+ false
6666
+ );
6667
+ recordWriteStatus(result, filePath, status);
6668
+ return true;
6669
+ }
6670
+
6671
+ // src/domain/services/codec-sample-synthesizer.ts
6672
+ var isProxyDetector = null;
6673
+ function installIsProxyDetector(fn) {
6674
+ isProxyDetector = fn;
6675
+ }
6676
+ function looksLikeProxy(value) {
6677
+ return isProxyDetector !== null && isProxyDetector(value);
6678
+ }
6679
+ var CodecTestGeneratorError = class extends Error {
6680
+ code;
6681
+ path;
6682
+ constructor(code, path28, message) {
6683
+ super(message);
6684
+ this.name = "CodecTestGeneratorError";
6685
+ this.code = code;
6686
+ this.path = path28;
6687
+ }
6688
+ };
6689
+ var MAX_PORTS_PER_CONTEXT = 64;
6690
+ var MAX_BOUNDED_CONTEXTS2 = 64;
6691
+ var MAX_SAMPLE_CONTRACT_DEPTH = 8;
6692
+ var MAX_CONTRACT_FIELDS2 = 64;
6693
+ var MAX_CONTRACT_NODES2 = 512;
6694
+ var MAX_SAMPLE_BYTES = 8192;
6695
+ var MAX_ARRAY_ITEMS_BOUND = 1e4;
6696
+ var MAX_STRING_LENGTH_BOUND = 65536;
6697
+ var MAX_PATTERN_LENGTH = 256;
6698
+ var MAX_PATTERN_STEPS = 1e4;
6699
+ var POLLUTING_KEYS2 = /* @__PURE__ */ new Set([
6700
+ "__proto__",
6701
+ "constructor",
6702
+ "prototype"
6703
+ ]);
6704
+ function hostile2(path28, message) {
6705
+ return new CodecTestGeneratorError("HOSTILE_INPUT", path28, message);
6706
+ }
6707
+ function readOwnPlainProperty(obj, key) {
6708
+ if (obj === null || typeof obj !== "object") {
6709
+ throw hostile2(
6710
+ key,
6711
+ `expected a plain object to read "${key}" from, got ${obj === null ? "null" : typeof obj}`
6712
+ );
6713
+ }
6714
+ if (looksLikeProxy(obj)) {
6715
+ throw hostile2(key, `refusing a Proxy while reading "${key}"`);
6716
+ }
6717
+ let proto;
6718
+ try {
6719
+ proto = Object.getPrototypeOf(obj);
6720
+ } catch {
6721
+ throw hostile2(
6722
+ key,
6723
+ `reflection threw while reading the prototype (hostile Proxy trap)`
6724
+ );
6725
+ }
6726
+ if (proto !== Object.prototype && proto !== null) {
6727
+ throw hostile2(key, `non-plain prototype while reading "${key}"`);
6728
+ }
6729
+ if (POLLUTING_KEYS2.has(key)) {
6730
+ throw hostile2(key, `refusing prototype-polluting key "${key}"`);
6731
+ }
6732
+ let desc;
6733
+ try {
6734
+ desc = Object.getOwnPropertyDescriptor(obj, key);
6735
+ } catch {
6736
+ throw hostile2(
6737
+ key,
6738
+ `reflection threw while reading "${key}" (hostile Proxy trap)`
6739
+ );
6740
+ }
6741
+ if (desc && (desc.get !== void 0 || desc.set !== void 0)) {
6742
+ throw hostile2(
6743
+ key,
6744
+ `refusing accessor property "${key}" (getters are never invoked)`
6745
+ );
6746
+ }
6747
+ return desc?.value;
6748
+ }
6749
+ function validatePlainRecord(value) {
6750
+ if (value === null || value === void 0) {
6751
+ throw hostile2(
6752
+ "record",
6753
+ `expected a plain record, got ${value === null ? "null" : "undefined"}`
6754
+ );
6755
+ }
6756
+ if (typeof value !== "object") {
6757
+ throw hostile2(
6758
+ "record",
6759
+ `expected a plain record, got the primitive ${typeof value}`
6760
+ );
6761
+ }
6762
+ if (looksLikeProxy(value)) {
6763
+ throw hostile2(
6764
+ "record",
6765
+ `refusing a Proxy where a plain record is required`
6766
+ );
6767
+ }
6768
+ let proto;
6769
+ try {
6770
+ proto = Object.getPrototypeOf(value);
6771
+ } catch {
6772
+ throw hostile2("record", `reflection threw while reading the prototype`);
6773
+ }
6774
+ if (proto !== Object.prototype && proto !== null) {
6775
+ throw hostile2(
6776
+ "record",
6777
+ `non-plain prototype where a plain record is required`
6778
+ );
6779
+ }
6780
+ if (Array.isArray(value)) {
6781
+ throw hostile2(
6782
+ "record",
6783
+ `refusing an array where a plain record is required`
6784
+ );
6785
+ }
6786
+ }
6787
+ function chargeNodes(budget, path28) {
6788
+ budget.nodes += 1;
6789
+ if (budget.nodes > MAX_CONTRACT_NODES2) {
6790
+ throw new CodecTestGeneratorError(
6791
+ "TIMEOUT_OR_BUDGET",
6792
+ path28,
6793
+ `contract exceeds the global schema-node budget (MAX_CONTRACT_NODES = ${MAX_CONTRACT_NODES2}) at ${path28}`
6794
+ );
6795
+ }
6796
+ }
6797
+ function chargeBytes(budget, n, path28) {
6798
+ budget.bytes += n;
6799
+ if (budget.discardBytes === true) return;
6800
+ if (budget.bytes > MAX_SAMPLE_BYTES) {
6801
+ throw new CodecTestGeneratorError(
6802
+ "TIMEOUT_OR_BUDGET",
6803
+ path28,
6804
+ `synthesized sample exceeds the byte budget (MAX_SAMPLE_BYTES = ${MAX_SAMPLE_BYTES}) at ${path28}`
6805
+ );
6806
+ }
6807
+ }
6808
+ function jsonUtf8Length(value) {
6809
+ let total = 2;
6810
+ let i = 0;
6811
+ while (i < value.length) {
6812
+ const cp = value.codePointAt(i);
6813
+ if (cp === 8 || cp === 9 || cp === 10 || cp === 12 || cp === 13) {
6814
+ total += 2;
6815
+ } else if (cp < 32 || cp >= 55296 && cp <= 57343) {
6816
+ total += 6;
6817
+ } else if (cp === 34 || cp === 92) {
6818
+ total += 2;
6819
+ } else if (cp < 127) {
6820
+ total += 1;
6821
+ } else if (cp < 2048) {
6822
+ total += 2;
6823
+ } else if (cp < 65536) {
6824
+ total += 3;
6825
+ } else {
6826
+ total += 4;
6827
+ }
6828
+ i += cp > 65535 ? 2 : 1;
6829
+ }
6830
+ return total;
6831
+ }
6832
+ function chargeJsonString(budget, value, path28) {
6833
+ chargeBytes(budget, jsonUtf8Length(value), path28);
6834
+ }
6835
+ function readBoundedDenseArray(value, maxLen, path28) {
6836
+ if (looksLikeProxy(value)) {
6837
+ throw hostile2(path28, `refusing a Proxy array at ${path28}`);
6838
+ }
6839
+ let isArray;
6840
+ try {
6841
+ isArray = Array.isArray(value);
6842
+ } catch {
6843
+ throw hostile2(path28, `reflection threw while inspecting the array`);
6844
+ }
6845
+ if (!isArray) {
6846
+ throw hostile2(path28, `expected a dense array at ${path28}`);
6847
+ }
6848
+ const arr = value;
6849
+ let proto;
6850
+ let lenDesc;
6851
+ try {
6852
+ proto = Object.getPrototypeOf(arr);
6853
+ lenDesc = Object.getOwnPropertyDescriptor(arr, "length");
6854
+ } catch {
6855
+ throw hostile2(path28, `reflection threw while inspecting the array`);
6856
+ }
6857
+ if (proto !== Array.prototype && proto !== null) {
6858
+ throw hostile2(path28, `array at ${path28} has a non-plain prototype`);
6859
+ }
6860
+ if (!lenDesc || lenDesc.get !== void 0 || lenDesc.set !== void 0) {
6861
+ throw hostile2(path28, `array "length" at ${path28} is missing or an accessor`);
6862
+ }
6863
+ const len = lenDesc.value;
6864
+ if (typeof len !== "number" || !Number.isSafeInteger(len) || len < 0) {
6865
+ throw hostile2(path28, `array "length" at ${path28} is not a safe integer`);
6866
+ }
6867
+ if (len > maxLen) {
6868
+ throw hostile2(
6869
+ path28,
6870
+ `array at ${path28} has ${len} items, exceeding the bound ${maxLen}`
6871
+ );
6872
+ }
6873
+ const items = [];
6874
+ for (let i = 0; i < len; i++) {
6875
+ let present;
6876
+ try {
6877
+ present = i in arr;
6878
+ } catch {
6879
+ throw hostile2(path28, `reflection threw while probing index ${i}`);
6880
+ }
6881
+ if (!present) {
6882
+ throw hostile2(path28, `sparse array hole at index ${i} of ${path28}`);
6883
+ }
6884
+ let desc;
6885
+ try {
6886
+ desc = Object.getOwnPropertyDescriptor(value, String(i));
6887
+ } catch {
6888
+ throw hostile2(path28, `reflection threw while reading index ${i}`);
6889
+ }
6890
+ if (!desc) {
6891
+ throw hostile2(path28, `missing element at index ${i} of ${path28}`);
6892
+ }
6893
+ if (desc.get !== void 0 || desc.set !== void 0) {
6894
+ throw hostile2(
6895
+ path28,
6896
+ `accessor at index ${i} of ${path28} (getters are never invoked)`
6897
+ );
6898
+ }
6899
+ items.push(desc.value);
6900
+ }
6901
+ return items;
6902
+ }
6903
+ function peek(p) {
6904
+ return p.i < p.src.length ? p.src[p.i] : void 0;
6905
+ }
6906
+ function parsePatternOrThrow(src) {
6907
+ const p = { src, i: 0 };
6908
+ const node = parseAlternation(p, true);
6909
+ if (p.i < p.src.length) {
6910
+ throw new CodecTestGeneratorError(
6911
+ "MALFORMED_CONTRACT",
6912
+ "string.pattern",
6913
+ `unexpected "${p.src[p.i]}" in pattern at offset ${p.i}`
6914
+ );
6915
+ }
6916
+ return node;
6917
+ }
6918
+ function parseAlternation(p, top) {
6919
+ const opts = [parseSequence(p, top)];
6920
+ while (peek(p) === "|") {
6921
+ p.i += 1;
6922
+ opts.push(parseSequence(p, top));
6923
+ }
6924
+ return opts.length === 1 ? opts[0] : { t: "alt", opts };
6925
+ }
6926
+ function parseSequence(p, top) {
6927
+ const parts = [];
6928
+ for (; ; ) {
6929
+ const c = peek(p);
6930
+ if (c === void 0 || c === "|" || c === ")" && !top) break;
6931
+ parts.push(parseQuantified(p));
6932
+ }
6933
+ return { t: "seq", parts };
6934
+ }
6935
+ function parseQuantified(p) {
6936
+ const atom = parseAtom(p);
6937
+ const c = peek(p);
6938
+ if (c === "*") {
6939
+ p.i += 1;
6940
+ return { t: "quant", node: atom, min: 0, max: Number.POSITIVE_INFINITY };
6941
+ }
6942
+ if (c === "+") {
6943
+ p.i += 1;
6944
+ return { t: "quant", node: atom, min: 1, max: Number.POSITIVE_INFINITY };
6945
+ }
6946
+ if (c === "?") {
6947
+ p.i += 1;
6948
+ return { t: "quant", node: atom, min: 0, max: 1 };
6949
+ }
6950
+ if (c === "{") {
6951
+ const bound = parseBound(p);
6952
+ if (bound === null) {
6953
+ throw new CodecTestGeneratorError(
6954
+ "MALFORMED_CONTRACT",
6955
+ "string.pattern",
6956
+ `invalid or nested quantifier in pattern at offset ${p.i}`
6957
+ );
6958
+ }
6959
+ return { t: "quant", node: atom, min: bound.min, max: bound.max };
6960
+ }
6961
+ return atom;
6962
+ }
6963
+ function parseBound(p) {
6964
+ const start = p.i;
6965
+ p.i += 1;
6966
+ const min = parseDigits(p);
6967
+ if (min === null) {
6968
+ p.i = start;
6969
+ return null;
6970
+ }
6971
+ let max = min;
6972
+ if (peek(p) === ",") {
6973
+ p.i += 1;
6974
+ if (peek(p) === "}") {
6975
+ max = Number.POSITIVE_INFINITY;
6976
+ } else {
6977
+ const n = parseDigits(p);
6978
+ if (n === null) {
6979
+ p.i = start;
6980
+ return null;
6981
+ }
6982
+ max = n;
6983
+ }
6984
+ }
6985
+ if (peek(p) !== "}" || max < min) {
6986
+ p.i = start;
6987
+ return null;
6988
+ }
6989
+ p.i += 1;
6990
+ return { min, max };
6991
+ }
6992
+ function parseDigits(p) {
6993
+ const start = p.i;
6994
+ while (p.i < p.src.length && /[0-9]/.test(p.src[p.i])) {
6995
+ p.i += 1;
6996
+ }
6997
+ if (p.i === start) return null;
6998
+ const n = Number.parseInt(p.src.slice(start, p.i), 10);
6999
+ return Number.isSafeInteger(n) ? n : null;
7000
+ }
7001
+ function parseClassEscape(p) {
7002
+ const c = p.src[p.i];
7003
+ p.i += 1;
7004
+ if (c === "d") return { t: "digit", neg: false };
7005
+ if (c === "D") return { t: "digit", neg: true };
7006
+ if (c === "w") return { t: "word", neg: false };
7007
+ if (c === "W") return { t: "word", neg: true };
7008
+ if (c === "s") return { t: "space", neg: false };
7009
+ if (c === "S") return { t: "space", neg: true };
7010
+ const literal = c === "n" ? "\n" : c === "t" ? " " : c === "r" ? "\r" : c;
7011
+ return { t: "char", ch: literal };
7012
+ }
7013
+ function parseAtom(p) {
7014
+ const c = peek(p);
7015
+ if (c === void 0) {
7016
+ throw new CodecTestGeneratorError(
7017
+ "MALFORMED_CONTRACT",
7018
+ "string.pattern",
7019
+ `unexpected end of pattern`
7020
+ );
7021
+ }
7022
+ if (c === "(") {
7023
+ p.i += 1;
7024
+ if (peek(p) === "?") {
7025
+ throw new CodecTestGeneratorError(
7026
+ "MALFORMED_CONTRACT",
7027
+ "string.pattern",
7028
+ `unsupported group construct (?...) in pattern at offset ${p.i}`
7029
+ );
7030
+ }
7031
+ const inner = parseAlternation(p, false);
7032
+ if (peek(p) !== ")") {
7033
+ throw new CodecTestGeneratorError(
7034
+ "MALFORMED_CONTRACT",
7035
+ "string.pattern",
7036
+ `unmatched "(" in pattern at offset ${p.i}`
7037
+ );
7038
+ }
7039
+ p.i += 1;
7040
+ return inner;
7041
+ }
7042
+ if (c === "[") {
7043
+ p.i += 1;
7044
+ return parseClass(p);
7045
+ }
7046
+ if (c === "^") {
7047
+ p.i += 1;
7048
+ return { t: "start" };
7049
+ }
7050
+ if (c === "$") {
7051
+ p.i += 1;
7052
+ return { t: "end" };
7053
+ }
7054
+ if (c === ".") {
7055
+ p.i += 1;
7056
+ return { t: "any" };
7057
+ }
7058
+ if (c === "\\") {
7059
+ p.i += 1;
7060
+ const e = peek(p);
7061
+ if (e === void 0) {
7062
+ throw new CodecTestGeneratorError(
7063
+ "MALFORMED_CONTRACT",
7064
+ "string.pattern",
7065
+ `dangling escape at end of pattern`
7066
+ );
7067
+ }
7068
+ if (e >= "1" && e <= "9") {
7069
+ throw new CodecTestGeneratorError(
7070
+ "MALFORMED_CONTRACT",
7071
+ "string.pattern",
7072
+ `backreferences are not supported in pattern at offset ${p.i}`
7073
+ );
7074
+ }
7075
+ if (e === "b" || e === "B") {
7076
+ throw new CodecTestGeneratorError(
7077
+ "MALFORMED_CONTRACT",
7078
+ "string.pattern",
7079
+ `word boundaries are not supported in pattern at offset ${p.i}`
7080
+ );
7081
+ }
7082
+ if (e === "d" || e === "D" || e === "w" || e === "W" || e === "s" || e === "S") {
7083
+ const item = parseClassEscape(p);
7084
+ return { t: "class", neg: false, items: [item] };
7085
+ }
7086
+ p.i += 1;
7087
+ const literal = e === "n" ? "\n" : e === "t" ? " " : e === "r" ? "\r" : e;
7088
+ return { t: "char", ch: literal };
7089
+ }
7090
+ if (c === "*" || c === "+" || c === "?" || c === ")") {
7091
+ throw new CodecTestGeneratorError(
7092
+ "MALFORMED_CONTRACT",
7093
+ "string.pattern",
7094
+ `unexpected "${c}" in pattern at offset ${p.i}`
7095
+ );
7096
+ }
7097
+ p.i += 1;
7098
+ return { t: "char", ch: c };
7099
+ }
7100
+ function parseClass(p) {
7101
+ const neg = peek(p) === "^";
7102
+ if (neg) p.i += 1;
7103
+ const items = [];
7104
+ for (; ; ) {
7105
+ const c = peek(p);
7106
+ if (c === void 0) {
7107
+ throw new CodecTestGeneratorError(
7108
+ "MALFORMED_CONTRACT",
7109
+ "string.pattern",
7110
+ `unmatched "[" in pattern`
7111
+ );
7112
+ }
7113
+ if (c === "]") {
7114
+ p.i += 1;
7115
+ break;
7116
+ }
7117
+ let item;
7118
+ if (c === "\\") {
7119
+ p.i += 1;
7120
+ item = parseClassEscape(p);
7121
+ } else {
7122
+ p.i += 1;
7123
+ item = { t: "char", ch: c };
7124
+ }
7125
+ const next = peek(p);
7126
+ if (item.t === "char" && next === "-" && p.i + 1 < p.src.length && p.src[p.i + 1] !== "]") {
7127
+ p.i += 1;
7128
+ let hi;
7129
+ if (peek(p) === "\\") {
7130
+ p.i += 1;
7131
+ const hiItem = parseClassEscape(p);
7132
+ if (hiItem.t !== "char") {
7133
+ throw new CodecTestGeneratorError(
7134
+ "MALFORMED_CONTRACT",
7135
+ "string.pattern",
7136
+ `invalid range end in character class`
7137
+ );
7138
+ }
7139
+ hi = hiItem.ch;
7140
+ } else {
7141
+ hi = p.src[p.i];
7142
+ p.i += 1;
7143
+ }
7144
+ if (item.ch > hi) {
7145
+ throw new CodecTestGeneratorError(
7146
+ "MALFORMED_CONTRACT",
7147
+ "string.pattern",
7148
+ `character-class range out of order (${item.ch}-${hi})`
7149
+ );
7150
+ }
7151
+ items.push({ t: "range", lo: item.ch, hi });
7152
+ } else {
7153
+ items.push(item);
7154
+ }
7155
+ }
7156
+ if (items.length === 0) {
7157
+ throw new CodecTestGeneratorError(
7158
+ "MALFORMED_CONTRACT",
7159
+ "string.pattern",
7160
+ `empty character class "[]"`
7161
+ );
7162
+ }
7163
+ return { t: "class", neg, items };
7164
+ }
7165
+ function step(state) {
7166
+ state.steps += 1;
7167
+ if (state.steps > MAX_PATTERN_STEPS) {
7168
+ throw new CodecTestGeneratorError(
7169
+ "TIMEOUT_OR_BUDGET",
7170
+ "string.pattern",
7171
+ `pattern matching exceeded the step budget (MAX_PATTERN_STEPS = ${MAX_PATTERN_STEPS})`
7172
+ );
7173
+ }
7174
+ }
7175
+ function classMatches(node, ch) {
7176
+ let matched = false;
7177
+ for (const item of node.items) {
7178
+ if (item.t === "char") {
7179
+ if (ch === item.ch) matched = true;
7180
+ } else if (item.t === "range") {
7181
+ if (ch >= item.lo && ch <= item.hi) matched = true;
7182
+ } else if (item.t === "digit") {
7183
+ const isDigit = ch >= "0" && ch <= "9";
7184
+ if (isDigit !== item.neg) matched = true;
7185
+ } else if (item.t === "word") {
7186
+ const isWord = ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "_";
7187
+ if (isWord !== item.neg) matched = true;
7188
+ } else {
7189
+ const isSpace = ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f";
7190
+ if (isSpace !== item.neg) matched = true;
7191
+ }
7192
+ if (matched) break;
7193
+ }
7194
+ return node.neg ? !matched : matched;
7195
+ }
7196
+ var RESUME = 0;
7197
+ var DONE = 1;
7198
+ var FAIL = 2;
7199
+ function matchesPatternBounded(pattern, sample) {
7200
+ if (pattern.length > MAX_PATTERN_LENGTH) {
7201
+ throw new CodecTestGeneratorError(
7202
+ "TIMEOUT_OR_BUDGET",
7203
+ "string.pattern",
7204
+ `pattern size ${pattern.length} exceeds the budget (MAX_PATTERN_LENGTH = ${MAX_PATTERN_LENGTH})`
7205
+ );
7206
+ }
7207
+ const ast = parsePatternOrThrow(pattern);
7208
+ const s = sample;
7209
+ const state = { steps: 0 };
7210
+ let stack = [];
7211
+ const choices = [];
7212
+ let cur = { node: ast, si: 0 };
7213
+ let finished = false;
7214
+ const deliver = (p) => {
7215
+ for (; ; ) {
7216
+ const frame = stack.pop();
7217
+ if (frame === void 0) {
7218
+ if (p === s.length) {
7219
+ finished = true;
7220
+ return DONE;
7221
+ }
7222
+ return FAIL;
7223
+ }
7224
+ switch (frame.t) {
7225
+ case "seq": {
7226
+ if (frame.idx < frame.parts.length) {
7227
+ stack.push({ t: "seq", parts: frame.parts, idx: frame.idx + 1 });
7228
+ cur = { node: frame.parts[frame.idx], si: p };
7229
+ return RESUME;
7230
+ }
7231
+ break;
7232
+ }
7233
+ case "quant": {
7234
+ step(state);
7235
+ if (frame.count < frame.q.min) {
7236
+ stack.push({
7237
+ t: "quantRep",
7238
+ q: frame.q,
7239
+ count: frame.count,
7240
+ p
7241
+ });
7242
+ cur = { node: frame.q.node, si: p };
7243
+ return RESUME;
7244
+ }
7245
+ if (frame.count < frame.q.max) {
7246
+ choices.push({
7247
+ frames: stack.slice(),
7248
+ alts: [{ deliverP: p }]
7249
+ });
7250
+ stack.push({
7251
+ t: "quantRep",
7252
+ q: frame.q,
7253
+ count: frame.count,
7254
+ p
7255
+ });
7256
+ cur = { node: frame.q.node, si: p };
7257
+ return RESUME;
7258
+ }
7259
+ break;
7260
+ }
7261
+ case "quantRep": {
7262
+ if (frame.p === p) return FAIL;
7263
+ stack.push({
7264
+ t: "quant",
7265
+ q: frame.q,
7266
+ count: frame.count + 1,
7267
+ p
7268
+ });
7269
+ break;
7270
+ }
7271
+ }
7272
+ }
7273
+ };
7274
+ const backtrack = () => {
7275
+ cur = null;
7276
+ for (; ; ) {
7277
+ const choice = choices.pop();
7278
+ if (choice === void 0) return false;
7279
+ stack = choice.frames;
7280
+ const alt = choice.alts.shift();
7281
+ if (alt === void 0) continue;
7282
+ if (choice.alts.length > 0) {
7283
+ choices.push(choice);
7284
+ }
7285
+ if ("node" in alt) {
7286
+ cur = { node: alt.node, si: alt.si };
7287
+ return true;
7288
+ }
7289
+ const r = deliver(alt.deliverP);
7290
+ if (r === RESUME) return true;
7291
+ if (r === DONE) return true;
7292
+ }
7293
+ };
7294
+ for (; ; ) {
7295
+ const active = cur;
7296
+ if (active === null) {
7297
+ if (!backtrack()) return false;
7298
+ if (finished) return true;
7299
+ continue;
7300
+ }
7301
+ step(state);
7302
+ const { node, si } = active;
7303
+ let outcome = FAIL;
7304
+ switch (node.t) {
7305
+ case "char":
7306
+ outcome = si < s.length && s[si] === node.ch ? deliver(si + 1) : FAIL;
7307
+ break;
7308
+ case "any":
7309
+ outcome = si < s.length && s[si] !== "\n" ? deliver(si + 1) : FAIL;
7310
+ break;
7311
+ case "class":
7312
+ outcome = si < s.length && classMatches(node, s[si]) ? deliver(si + 1) : FAIL;
7313
+ break;
7314
+ case "start":
7315
+ outcome = si === 0 ? deliver(si) : FAIL;
7316
+ break;
7317
+ case "end":
7318
+ outcome = si === s.length ? deliver(si) : FAIL;
7319
+ break;
7320
+ case "seq": {
7321
+ if (node.parts.length === 0) {
7322
+ outcome = deliver(si);
7323
+ } else {
7324
+ stack.push({ t: "seq", parts: node.parts, idx: 1 });
7325
+ cur = { node: node.parts[0], si };
7326
+ outcome = RESUME;
7327
+ }
7328
+ break;
7329
+ }
7330
+ case "alt": {
7331
+ if (node.opts.length === 0) {
7332
+ outcome = FAIL;
7333
+ } else {
7334
+ choices.push({
7335
+ frames: stack.slice(),
7336
+ alts: node.opts.slice(1).map((opt) => ({ node: opt, si }))
7337
+ });
7338
+ cur = { node: node.opts[0], si };
7339
+ outcome = RESUME;
7340
+ }
7341
+ break;
7342
+ }
7343
+ case "quant": {
7344
+ stack.push({ t: "quant", q: node, count: 0, p: si });
7345
+ outcome = deliver(si);
7346
+ break;
7347
+ }
7348
+ }
7349
+ if (outcome === DONE) return true;
7350
+ if (outcome === FAIL) {
7351
+ if (!backtrack()) return false;
7352
+ if (finished) return true;
7353
+ }
7354
+ }
7355
+ }
7356
+ function isPlainObjectSafe2(node) {
7357
+ if (node === null || typeof node !== "object") return false;
7358
+ if (looksLikeProxy(node)) return false;
7359
+ try {
7360
+ const proto = Object.getPrototypeOf(node);
7361
+ return proto === Object.prototype || proto === null;
7362
+ } catch {
7363
+ return false;
7364
+ }
7365
+ }
7366
+ function synthesizeNode(node, path28, depth, budget) {
7367
+ if (depth > MAX_SAMPLE_CONTRACT_DEPTH) {
7368
+ throw new CodecTestGeneratorError(
7369
+ "UNSUPPORTED_NESTED_SHAPE",
7370
+ path28,
7371
+ `contract nesting exceeds MAX_SAMPLE_CONTRACT_DEPTH (${MAX_SAMPLE_CONTRACT_DEPTH}) at ${path28}`
7372
+ );
7373
+ }
7374
+ if (typeof node !== "object" || node === null) {
7375
+ throw new CodecTestGeneratorError(
7376
+ "MALFORMED_CONTRACT",
7377
+ path28,
7378
+ `expected a contract object at ${path28}, got ${node === null ? "null" : typeof node}`
7379
+ );
7380
+ }
7381
+ if (looksLikeProxy(node)) {
7382
+ throw hostile2(path28, `refusing a Proxy contract node at ${path28}`);
7383
+ }
7384
+ let proto;
7385
+ try {
7386
+ proto = Object.getPrototypeOf(node);
7387
+ } catch {
7388
+ throw hostile2(path28, `reflection threw while reading the prototype`);
7389
+ }
7390
+ if (proto !== Object.prototype && proto !== null) {
7391
+ throw hostile2(path28, `non-plain contract node at ${path28}`);
7392
+ }
7393
+ chargeNodes(budget, path28);
7394
+ const kind = readOwnPlainProperty(node, "kind");
7395
+ if (kind === void 0) {
7396
+ throw new CodecTestGeneratorError(
7397
+ "MALFORMED_CONTRACT",
7398
+ path28,
7399
+ `contract at ${path28} is missing "kind"`
7400
+ );
7401
+ }
7402
+ if (typeof kind !== "string") {
7403
+ throw new CodecTestGeneratorError(
7404
+ "MALFORMED_CONTRACT",
7405
+ path28,
7406
+ `contract "kind" at ${path28} is not a string`
7407
+ );
7408
+ }
7409
+ switch (kind) {
7410
+ case "object": {
7411
+ const exact = readOwnPlainProperty(node, "exact");
7412
+ if (exact !== true) {
7413
+ throw new CodecTestGeneratorError(
7414
+ "MALFORMED_CONTRACT",
7415
+ path28,
7416
+ `object contract at ${path28} requires exact: true`
7417
+ );
7418
+ }
7419
+ const fields = readOwnPlainProperty(node, "fields");
7420
+ validatePlainRecord(fields);
7421
+ let keys;
7422
+ try {
7423
+ keys = Object.keys(fields);
7424
+ } catch {
7425
+ throw hostile2(path28, `reflection threw while enumerating fields`);
7426
+ }
7427
+ for (const key of keys) {
7428
+ if (POLLUTING_KEYS2.has(key)) {
7429
+ throw hostile2(path28, `prototype-polluting field key "${key}"`);
7430
+ }
7431
+ }
7432
+ if (keys.length > MAX_CONTRACT_FIELDS2) {
7433
+ throw new CodecTestGeneratorError(
7434
+ "TIMEOUT_OR_BUDGET",
7435
+ path28,
7436
+ `object at ${path28} has ${keys.length} fields, exceeding MAX_CONTRACT_FIELDS (${MAX_CONTRACT_FIELDS2})`
7437
+ );
7438
+ }
7439
+ const sample = {};
7440
+ chargeBytes(budget, 2, path28);
7441
+ for (const key of [...keys].sort(
7442
+ (a, b) => a < b ? -1 : a > b ? 1 : 0
7443
+ )) {
7444
+ chargeJsonString(budget, key, path28);
7445
+ chargeBytes(budget, 2, path28);
7446
+ let field = readOwnPlainProperty(fields, key);
7447
+ if (isPlainObjectSafe2(field)) {
7448
+ const optional = readOwnPlainProperty(field, "optional");
7449
+ if (optional !== void 0 && isPlainObjectSafe2(optional)) {
7450
+ field = optional;
7451
+ }
7452
+ }
7453
+ sample[key] = synthesizeNode(
7454
+ field,
7455
+ `${path28}.${key}`,
7456
+ depth + 1,
7457
+ budget
7458
+ );
7459
+ }
7460
+ return sample;
7461
+ }
7462
+ case "array": {
7463
+ const maxItems = readOwnPlainProperty(node, "maxItems");
7464
+ if (maxItems === void 0) {
7465
+ throw new CodecTestGeneratorError(
7466
+ "MISSING_BOUND",
7467
+ path28,
7468
+ `array contract at ${path28} requires a positive integer maxItems (1 <= maxItems <= ${MAX_ARRAY_ITEMS_BOUND})`
7469
+ );
7470
+ }
7471
+ if (typeof maxItems !== "number" || !Number.isSafeInteger(maxItems) || maxItems < 1 || maxItems > MAX_ARRAY_ITEMS_BOUND) {
7472
+ throw new CodecTestGeneratorError(
7473
+ "MISSING_BOUND",
7474
+ path28,
7475
+ `array "maxItems" at ${path28} must be a positive integer <= ${MAX_ARRAY_ITEMS_BOUND}`
7476
+ );
7477
+ }
7478
+ const items = readOwnPlainProperty(node, "items");
7479
+ if (items === void 0) {
7480
+ throw new CodecTestGeneratorError(
7481
+ "MALFORMED_CONTRACT",
7482
+ path28,
7483
+ `array contract at ${path28} is missing "items"`
7484
+ );
7485
+ }
7486
+ chargeBytes(budget, 2, path28);
7487
+ return [synthesizeNode(items, `${path28}.items`, depth + 1, budget)];
7488
+ }
7489
+ case "string": {
7490
+ const maxLength = readOwnPlainProperty(node, "maxLength");
7491
+ if (maxLength === void 0) {
7492
+ throw new CodecTestGeneratorError(
7493
+ "MISSING_BOUND",
7494
+ path28,
7495
+ `string contract at ${path28} requires a positive integer maxLength (1 <= maxLength <= ${MAX_STRING_LENGTH_BOUND})`
7496
+ );
7497
+ }
7498
+ if (typeof maxLength !== "number" || !Number.isSafeInteger(maxLength) || maxLength < 1 || maxLength > MAX_STRING_LENGTH_BOUND) {
7499
+ throw new CodecTestGeneratorError(
7500
+ "MISSING_BOUND",
7501
+ path28,
7502
+ `string "maxLength" at ${path28} must be a positive integer <= ${MAX_STRING_LENGTH_BOUND}`
7503
+ );
7504
+ }
7505
+ const pattern = readOwnPlainProperty(node, "pattern");
7506
+ if (pattern !== void 0) {
7507
+ if (typeof pattern !== "string" || pattern.length === 0) {
7508
+ throw new CodecTestGeneratorError(
7509
+ "MALFORMED_CONTRACT",
7510
+ path28,
7511
+ `string "pattern" at ${path28} must be a non-empty string`
7512
+ );
7513
+ }
7514
+ if (pattern.length > MAX_PATTERN_LENGTH) {
7515
+ throw new CodecTestGeneratorError(
7516
+ "TIMEOUT_OR_BUDGET",
7517
+ "string.pattern",
7518
+ `pattern size ${pattern.length} exceeds the budget (MAX_PATTERN_LENGTH = ${MAX_PATTERN_LENGTH})`
7519
+ );
7520
+ }
7521
+ parsePatternOrThrow(pattern);
7522
+ const example = readOwnPlainProperty(node, "example");
7523
+ if (example === void 0 || typeof example !== "string") {
7524
+ throw new CodecTestGeneratorError(
7525
+ "MISSING_PATTERN_EXAMPLE",
7526
+ path28,
7527
+ `pattern string at ${path28} requires an explicit "example" matching the pattern`
7528
+ );
7529
+ }
7530
+ if (!matchesPatternBounded(pattern, example)) {
7531
+ throw new CodecTestGeneratorError(
7532
+ "MISSING_PATTERN_EXAMPLE",
7533
+ path28,
7534
+ `pattern string at ${path28} requires an explicit "example" matching the pattern`
7535
+ );
7536
+ }
7537
+ if (example.length > maxLength) {
7538
+ throw new CodecTestGeneratorError(
7539
+ "MISSING_PATTERN_EXAMPLE",
7540
+ path28,
7541
+ `pattern string "example" at ${path28} is longer than the string bound maxLength (${maxLength}) and is not a valid sample`
7542
+ );
7543
+ }
7544
+ chargeJsonString(budget, example, path28);
7545
+ return example;
7546
+ }
7547
+ chargeJsonString(budget, "a", path28);
7548
+ return "a".repeat(Math.min(1, maxLength));
7549
+ }
7550
+ case "integer":
7551
+ case "number": {
7552
+ const min = readOwnPlainProperty(node, "min");
7553
+ const max = readOwnPlainProperty(node, "max");
7554
+ if (min !== void 0 && (typeof min !== "number" || !Number.isFinite(min))) {
7555
+ throw new CodecTestGeneratorError(
7556
+ "MALFORMED_CONTRACT",
7557
+ path28,
7558
+ `${kind} "min" at ${path28} must be a finite number`
7559
+ );
7560
+ }
7561
+ if (max !== void 0 && (typeof max !== "number" || !Number.isFinite(max))) {
7562
+ throw new CodecTestGeneratorError(
7563
+ "MALFORMED_CONTRACT",
7564
+ path28,
7565
+ `${kind} "max" at ${path28} must be a finite number`
7566
+ );
7567
+ }
7568
+ if (min !== void 0 && max !== void 0 && min > max) {
7569
+ throw new CodecTestGeneratorError(
7570
+ "UNSUPPORTED_NESTED_SHAPE",
7571
+ path28,
7572
+ `inverted numeric bounds (min > max) at ${path28}`
7573
+ );
7574
+ }
7575
+ let value = min ?? 0;
7576
+ if (min === void 0 && max !== void 0 && max < 0) {
7577
+ value = max;
7578
+ }
7579
+ if (kind === "integer") {
7580
+ if (min !== void 0) {
7581
+ value = Math.ceil(min);
7582
+ if (Object.is(value, -0)) value = 0;
7583
+ if (max !== void 0 && value > max) {
7584
+ throw new CodecTestGeneratorError(
7585
+ "UNSUPPORTED_NESTED_SHAPE",
7586
+ path28,
7587
+ `integer bounds at ${path28} contain no integer (min: ${min}, max: ${max})`
7588
+ );
7589
+ }
7590
+ } else if (max !== void 0 && max < 0) {
7591
+ value = Math.floor(max);
7592
+ } else {
7593
+ value = 0;
7594
+ }
7595
+ }
7596
+ chargeBytes(budget, String(value).length, path28);
7597
+ return value;
7598
+ }
7599
+ case "boolean":
7600
+ chargeBytes(budget, 5, path28);
7601
+ return false;
7602
+ case "enum": {
7603
+ const values = readOwnPlainProperty(node, "values");
7604
+ if (values === void 0) {
7605
+ throw new CodecTestGeneratorError(
7606
+ "MALFORMED_CONTRACT",
7607
+ path28,
7608
+ `enum contract at ${path28} is missing "values"`
7609
+ );
7610
+ }
7611
+ const dense = readBoundedDenseArray(
7612
+ values,
7613
+ MAX_CONTRACT_FIELDS2,
7614
+ `${path28}.values`
7615
+ );
7616
+ if (dense.length === 0) {
7617
+ throw new CodecTestGeneratorError(
7618
+ "UNSUPPORTED_NESTED_SHAPE",
7619
+ path28,
7620
+ `enum at ${path28} has an empty "values" array`
7621
+ );
7622
+ }
7623
+ for (const v of dense) {
7624
+ if (typeof v !== "string") {
7625
+ throw new CodecTestGeneratorError(
7626
+ "UNSUPPORTED_NESTED_SHAPE",
7627
+ path28,
7628
+ `enum at ${path28} contains a non-string value`
7629
+ );
7630
+ }
7631
+ }
7632
+ const first = dense[0];
7633
+ chargeJsonString(budget, first, path28);
7634
+ return first;
7635
+ }
7636
+ case "literal": {
7637
+ const value = readOwnPlainProperty(node, "value");
7638
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && value !== null) {
7639
+ throw new CodecTestGeneratorError(
7640
+ "UNSUPPORTED_NESTED_SHAPE",
7641
+ path28,
7642
+ `literal at ${path28} must carry a string/number/boolean/null value`
7643
+ );
7644
+ }
7645
+ if (typeof value === "number" && !Number.isFinite(value)) {
7646
+ throw new CodecTestGeneratorError(
7647
+ "MALFORMED_CONTRACT",
7648
+ path28,
7649
+ `literal at ${path28} must be a finite number`
7650
+ );
7651
+ }
7652
+ chargeBytes(
7653
+ budget,
7654
+ typeof value === "string" ? jsonUtf8Length(value) : value === null ? 4 : String(value).length,
7655
+ path28
7656
+ );
7657
+ return value;
7658
+ }
7659
+ case "nullable": {
7660
+ const of = readOwnPlainProperty(node, "of");
7661
+ if (of === void 0) {
7662
+ throw new CodecTestGeneratorError(
7663
+ "MALFORMED_CONTRACT",
7664
+ path28,
7665
+ `nullable contract at ${path28} is missing "of"`
7666
+ );
7667
+ }
7668
+ const innerBudget = {
7669
+ nodes: budget.nodes,
7670
+ bytes: 0,
7671
+ discardBytes: true
7672
+ };
7673
+ synthesizeNode(of, `${path28}.of`, depth + 1, innerBudget);
7674
+ budget.nodes = innerBudget.nodes;
7675
+ chargeBytes(budget, 4, path28);
7676
+ return null;
7677
+ }
7678
+ default:
7679
+ throw new CodecTestGeneratorError(
7680
+ "UNKNOWN_TYPE",
7681
+ path28,
7682
+ `unknown contract kind "${kind}" at ${path28}`
7683
+ );
7684
+ }
7685
+ }
7686
+ function synthesizeValidSample(contract, portLabel) {
7687
+ const budget = { nodes: 0, bytes: 0 };
7688
+ const sample = synthesizeNode(contract, portLabel, 1, budget);
7689
+ if (budget.bytes > MAX_SAMPLE_BYTES) {
7690
+ throw new CodecTestGeneratorError(
7691
+ "TIMEOUT_OR_BUDGET",
7692
+ portLabel,
7693
+ `synthesized sample for ${portLabel} exceeds MAX_SAMPLE_BYTES (${MAX_SAMPLE_BYTES})`
7694
+ );
7695
+ }
7696
+ return sample;
7697
+ }
7698
+
7699
+ // src/generators/codec-test.ts
7700
+ installIsProxyDetector(types.isProxy);
7701
+ var DEFAULT_RUNTIME_MODULE2 = "@fleet/shared";
7702
+ var SAFE_SPECIFIER_CHARS = /^[A-Za-z0-9@/._-]*$/;
7703
+ function malformedRuntimeModule() {
7704
+ return new CodecTestGeneratorError(
7705
+ "MALFORMED_CONTRACT",
7706
+ "generator.codec.runtimeModule",
7707
+ `generator.codec.runtimeModule must be a non-empty safe package or relative ("./…") specifier without whitespace or control characters`
7708
+ );
7709
+ }
7710
+ function validateRuntimeModule(value) {
7711
+ if (typeof value !== "string" || value.length === 0 || value.length > 256) {
7712
+ throw malformedRuntimeModule();
7713
+ }
7714
+ if (value.startsWith("./")) {
7715
+ const body = value.slice(2);
7716
+ if (!SAFE_SPECIFIER_CHARS.test(body) || body.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) {
7717
+ throw malformedRuntimeModule();
7718
+ }
7719
+ } else if (!/^[A-Za-z0-9@]/.test(value) || !SAFE_SPECIFIER_CHARS.test(value) || value.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) {
7720
+ throw malformedRuntimeModule();
7721
+ }
7722
+ return value;
7723
+ }
7724
+ var SAFE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
7725
+ function malformedName(what, value) {
7726
+ return new CodecTestGeneratorError(
7727
+ "MALFORMED_CONTRACT",
7728
+ what,
7729
+ `${what} must be a non-empty safe name (no path separators, traversal, or control characters), got ${typeof value}`
7730
+ );
7731
+ }
7732
+ function validateSafeName(value, what) {
7733
+ if (typeof value !== "string" || value.length === 0 || value.length > 128 || !SAFE_NAME_PATTERN.test(value) || value.includes("..")) {
7734
+ throw malformedName(what, value);
7735
+ }
7736
+ return value;
7737
+ }
7738
+ function resolveRuntimeModuleSafe(manifest) {
7739
+ const gen = readOwnPlainProperty(manifest, "generator");
7740
+ if (gen === void 0) return DEFAULT_RUNTIME_MODULE2;
7741
+ const sync = readOwnPlainProperty(gen, "codec");
7742
+ if (sync === void 0) return DEFAULT_RUNTIME_MODULE2;
7743
+ const runtimeModule = readOwnPlainProperty(sync, "runtimeModule");
7744
+ if (runtimeModule === void 0) return DEFAULT_RUNTIME_MODULE2;
7745
+ return validateRuntimeModule(runtimeModule);
7746
+ }
7747
+ async function generateCodecTests(moduleDir, moduleName, config, report) {
7748
+ const result = createEmptyResult();
7749
+ try {
7750
+ validateSafeName(moduleName, "moduleName");
7751
+ const manifest = config.manifest;
7752
+ const context = findBoundedContext(manifest, moduleName);
7753
+ if (context === void 0) return result;
7754
+ const runtimeModule = resolveRuntimeModuleSafe(manifest);
7755
+ const layers = readOwnPlainProperty(context, "layers");
7756
+ if (layers === void 0) return result;
7757
+ const application = readOwnPlainProperty(layers, "application");
7758
+ if (application === void 0) return result;
7759
+ const ports = readOwnPlainProperty(application, "ports");
7760
+ if (ports === void 0) return result;
7761
+ for (const direction of ["in", "out"]) {
7762
+ const directionPorts = readOwnPlainProperty(ports, direction);
7763
+ if (directionPorts === void 0) continue;
7764
+ const portList = readPortList(
7765
+ directionPorts,
7766
+ `layers.application.ports.${direction}`
7767
+ );
7768
+ for (const port of portList) {
7769
+ await emitPortCodecTest(
7770
+ port,
7771
+ direction,
7772
+ moduleDir,
7773
+ moduleName,
7774
+ runtimeModule,
7775
+ config,
7776
+ report,
7777
+ result
7778
+ );
7779
+ if (result.error) return result;
7780
+ }
7781
+ }
7782
+ return result;
7783
+ } catch (thrown) {
7784
+ const error = thrown instanceof CodecTestGeneratorError ? thrown : new CodecTestGeneratorError(
7785
+ "IO_FAILURE",
7786
+ null,
7787
+ thrown instanceof Error ? thrown.message : String(thrown)
7788
+ );
7789
+ result.error = error;
7790
+ result.summary = `CodecTests failed for ${moduleName}: [${error.code}] ${error.message}`;
7791
+ config.logger.error(result.summary);
7792
+ report?.record(
7793
+ "error",
7794
+ path8.join(moduleDir, "__tests__", "codecs"),
7795
+ result.summary
7796
+ );
7797
+ return result;
7798
+ }
7799
+ }
7800
+ function findBoundedContext(manifest, moduleName) {
7801
+ const contexts = readOwnPlainProperty(manifest, "bounded_contexts");
7802
+ if (contexts === void 0) return void 0;
7803
+ if (looksLikeProxy(contexts)) {
7804
+ throw new CodecTestGeneratorError(
7805
+ "HOSTILE_INPUT",
7806
+ "bounded_contexts",
7807
+ `bounded_contexts is a detectable Proxy (Proxies are refused before reflection)`
7808
+ );
7809
+ }
7810
+ let isArray;
7811
+ try {
7812
+ isArray = Array.isArray(contexts);
7813
+ } catch {
7814
+ throw new CodecTestGeneratorError(
7815
+ "HOSTILE_INPUT",
7816
+ "bounded_contexts",
7817
+ `reflection threw while inspecting bounded_contexts (revoked Proxy)`
7818
+ );
7819
+ }
7820
+ if (!isArray) {
7821
+ throw new CodecTestGeneratorError(
7822
+ "HOSTILE_INPUT",
7823
+ "bounded_contexts",
7824
+ `bounded_contexts must be a dense array`
7825
+ );
7826
+ }
7827
+ const ctxArr = contexts;
7828
+ let ctxLen;
7829
+ try {
7830
+ ctxLen = ctxArr.length;
7831
+ } catch {
7832
+ throw new CodecTestGeneratorError(
7833
+ "HOSTILE_INPUT",
7834
+ "bounded_contexts",
7835
+ `reflection threw while reading the length of bounded_contexts`
7836
+ );
7837
+ }
7838
+ if (ctxLen > MAX_BOUNDED_CONTEXTS2) {
7839
+ throw new CodecTestGeneratorError(
7840
+ "HOSTILE_INPUT",
7841
+ "bounded_contexts",
7842
+ `bounded_contexts has ${ctxLen} entries, exceeding MAX_BOUNDED_CONTEXTS (${MAX_BOUNDED_CONTEXTS2})`
7843
+ );
7844
+ }
7845
+ for (let i = 0; i < ctxLen; i++) {
7846
+ let present;
7847
+ try {
7848
+ present = i in ctxArr;
7849
+ } catch {
7850
+ throw new CodecTestGeneratorError(
7851
+ "HOSTILE_INPUT",
7852
+ `bounded_contexts[${i}]`,
7853
+ `reflection threw while probing index ${i} of bounded_contexts`
7854
+ );
7855
+ }
7856
+ if (!present) {
7857
+ throw new CodecTestGeneratorError(
7858
+ "HOSTILE_INPUT",
7859
+ `bounded_contexts[${i}]`,
7860
+ `sparse array hole at index ${i} of bounded_contexts`
7861
+ );
7862
+ }
7863
+ let desc;
7864
+ try {
7865
+ desc = Object.getOwnPropertyDescriptor(ctxArr, String(i));
7866
+ } catch {
7867
+ throw new CodecTestGeneratorError(
7868
+ "HOSTILE_INPUT",
7869
+ `bounded_contexts[${i}]`,
7870
+ `reflection threw while reading index ${i} of bounded_contexts`
7871
+ );
7872
+ }
7873
+ if (!desc || desc.get !== void 0 || desc.set !== void 0) {
7874
+ throw new CodecTestGeneratorError(
7875
+ "HOSTILE_INPUT",
7876
+ `bounded_contexts[${i}]`,
7877
+ `missing or accessor entry at index ${i} of bounded_contexts`
7878
+ );
7879
+ }
7880
+ const entry = desc.value;
7881
+ validatePlainRecord(entry);
7882
+ const name = readOwnPlainProperty(entry, "name");
7883
+ if (name === void 0) continue;
7884
+ if (name === moduleName) return entry;
7885
+ }
7886
+ return void 0;
7887
+ }
7888
+ function readPortList(value, label) {
7889
+ if (looksLikeProxy(value)) {
7890
+ throw new CodecTestGeneratorError(
7891
+ "HOSTILE_INPUT",
7892
+ label,
7893
+ `${label} is a detectable Proxy (Proxies are refused before reflection)`
7894
+ );
7895
+ }
7896
+ let isArray;
7897
+ try {
7898
+ isArray = Array.isArray(value);
7899
+ } catch {
7900
+ throw new CodecTestGeneratorError(
7901
+ "HOSTILE_INPUT",
7902
+ label,
7903
+ `reflection threw while inspecting ${label} (revoked Proxy)`
7904
+ );
7905
+ }
7906
+ if (!isArray) {
7907
+ throw new CodecTestGeneratorError(
7908
+ "HOSTILE_INPUT",
7909
+ label,
7910
+ `${label} must be a dense array (arrays, array-likes and non-iterables are refused)`
7911
+ );
7912
+ }
7913
+ let proto;
7914
+ let lenDesc;
7915
+ try {
7916
+ proto = Object.getPrototypeOf(value);
7917
+ lenDesc = Object.getOwnPropertyDescriptor(value, "length");
7918
+ } catch {
7919
+ throw new CodecTestGeneratorError(
7920
+ "HOSTILE_INPUT",
7921
+ label,
7922
+ `reflection threw while inspecting ${label} (hostile Proxy trap)`
7923
+ );
7924
+ }
7925
+ if (proto !== Array.prototype && proto !== null) {
7926
+ throw new CodecTestGeneratorError(
7927
+ "HOSTILE_INPUT",
7928
+ label,
7929
+ `${label} has a non-plain array prototype`
7930
+ );
7931
+ }
7932
+ if (!lenDesc || lenDesc.get !== void 0 || lenDesc.set !== void 0) {
7933
+ throw new CodecTestGeneratorError(
7934
+ "HOSTILE_INPUT",
7935
+ label,
7936
+ `${label} "length" is missing or an accessor`
7937
+ );
7938
+ }
7939
+ const len = lenDesc.value;
7940
+ if (typeof len !== "number" || !Number.isSafeInteger(len) || len < 0) {
7941
+ throw new CodecTestGeneratorError(
7942
+ "HOSTILE_INPUT",
7943
+ label,
7944
+ `${label} "length" is not a non-negative safe integer`
7945
+ );
7946
+ }
7947
+ if (len > MAX_PORTS_PER_CONTEXT) {
7948
+ throw new CodecTestGeneratorError(
7949
+ "HOSTILE_INPUT",
7950
+ label,
7951
+ `${label} has ${len} entries, exceeding MAX_PORTS_PER_CONTEXT (${MAX_PORTS_PER_CONTEXT})`
7952
+ );
7953
+ }
7954
+ const ports = [];
7955
+ for (let i = 0; i < len; i++) {
7956
+ let desc;
7957
+ try {
7958
+ desc = Object.getOwnPropertyDescriptor(value, String(i));
7959
+ } catch {
7960
+ throw new CodecTestGeneratorError(
7961
+ "HOSTILE_INPUT",
7962
+ label,
7963
+ `reflection threw while reading index ${i} of ${label}`
7964
+ );
7965
+ }
7966
+ if (!desc) {
7967
+ throw new CodecTestGeneratorError(
7968
+ "HOSTILE_INPUT",
7969
+ `${label}[${i}]`,
7970
+ `sparse array hole at index ${i} of ${label}`
7971
+ );
7972
+ }
7973
+ if (desc.get !== void 0 || desc.set !== void 0) {
7974
+ throw new CodecTestGeneratorError(
7975
+ "HOSTILE_INPUT",
7976
+ `${label}[${i}]`,
7977
+ `accessor at index ${i} of ${label} (getters are never invoked)`
7978
+ );
7979
+ }
7980
+ ports.push(desc.value);
7981
+ }
7982
+ return ports;
7983
+ }
7984
+ async function emitPortCodecTest(port, direction, moduleDir, moduleName, runtimeModule, config, report, result) {
7985
+ const label = `${moduleName}.ports.${direction}[]`;
7986
+ if (typeof port === "string") {
7987
+ validateSafeName(port, `${label}.name`);
7988
+ return;
7989
+ }
7990
+ validatePlainRecord(port);
7991
+ const rawName = readOwnPlainProperty(port, "name");
7992
+ if (rawName === void 0) {
7993
+ throw new CodecTestGeneratorError(
7994
+ "MALFORMED_CONTRACT",
7995
+ `${label}.name`,
7996
+ `port entry at ${label} is missing a "name"`
7997
+ );
7998
+ }
7999
+ validateSafeName(rawName, `${label}.name`);
8000
+ const contracts = readOwnPlainProperty(port, "contracts");
8001
+ if (contracts === void 0) return;
8002
+ validatePlainRecord(contracts);
8003
+ const request = readOwnPlainProperty(contracts, "request");
8004
+ if (request === void 0) {
8005
+ throw new CodecTestGeneratorError(
8006
+ "MALFORMED_CONTRACT",
8007
+ `${label}.contracts.request`,
8008
+ `contracts at ${label} is missing a "request" schema`
8009
+ );
8010
+ }
8011
+ const portLabel = `${moduleName}.${direction}.${validateSafeName(rawName, `${label}.name`)}`;
8012
+ const rawPortName = validateSafeName(rawName, `${label}.name`);
8013
+ const sample = synthesizeValidSample(request, portLabel);
8014
+ const portName2 = toPascalCaseIdentifier(
8015
+ rawPortName.replace(/\.(in|out)-port\.ts$/, "")
8016
+ );
8017
+ const portFileBase = rawPortName.replace(/\.ts$/, "");
8018
+ const filePath = path8.join(
8019
+ moduleDir,
8020
+ "__tests__",
8021
+ "codecs",
8022
+ `${portName2}.codec.test.ts`
8023
+ );
8024
+ const content = renderCodecTest({
8025
+ portName: portName2,
8026
+ portFileBase,
8027
+ runtimeModule,
8028
+ sample
8029
+ });
8030
+ if (!isInScope(filePath, config)) {
8031
+ config.logger.debug(
8032
+ `skipped (outside --only) ${path8.relative(config.workspaceRoot, filePath)}`
8033
+ );
8034
+ recordWriteStatus(result, filePath, "skipped");
8035
+ return;
8036
+ }
8037
+ const status = await safeWriteFileAtomic(
8038
+ filePath,
8039
+ content,
8040
+ config,
8041
+ report,
8042
+ false
8043
+ );
8044
+ recordWriteStatus(result, filePath, status);
8045
+ }
8046
+ function renderCodecTest(input) {
8047
+ const { portName: portName2, portFileBase, runtimeModule, sample } = input;
8048
+ return `// @generated by @hexagen/sync
8049
+ import { describe, it, expect } from "vitest";
8050
+ import { types } from "node:util";
8051
+ import { ADVERSARIAL_CORPUS, type CodecEnv, type DecodeResult } from ${JSON.stringify(runtimeModule)};
8052
+ import { create${portName2}Codec } from "../../src/application/ports/${portFileBase}.codec.js";
8053
+
8054
+ const env: CodecEnv = { isProxy: types.isProxy };
8055
+ const codec = create${portName2}Codec(env);
8056
+
8057
+ const VALID_SAMPLE = ${JSON.stringify(sample, null, 2)} as const;
8058
+
8059
+ describe.each(ADVERSARIAL_CORPUS)("${portName2} codec refuses adversarial entries", (entry) => {
8060
+ it("refuses the adversarial entry", () => {
8061
+ const res: DecodeResult<unknown> = codec.decode(entry.build());
8062
+ expect(res.ok).toBe(false);
8063
+ });
8064
+ });
8065
+
8066
+ it("decodes the synthesized valid sample and freezes the value", () => {
8067
+ const res = codec.decode(VALID_SAMPLE);
8068
+ expect(res.ok).toBe(true);
8069
+ if (res.ok) expect(Object.isFrozen(res.value)).toBe(true);
8070
+ });
8071
+ `;
8072
+ }
8073
+ var OHS_NOTE = "\n *\n * Open Host Service (open-host): this is this context's published language for consuming contexts — keep it stable.";
8074
+ var ACL_NOTE = "\n *\n * Anti-Corruption Layer (acl): translate the upstream contract into this context's own domain model; do not leak provider types inward.";
8075
+ function addAll(map, key, values) {
8076
+ const set = map.get(key) ?? /* @__PURE__ */ new Set();
8077
+ values.forEach((v) => set.add(v));
8078
+ map.set(key, set);
4904
8079
  }
4905
8080
  function toCamelCase(pascal) {
4906
8081
  return pascal.length > 0 ? pascal.charAt(0).toLowerCase() + pascal.slice(1) : pascal;
@@ -5213,8 +8388,8 @@ async function generateSharedKernel(config, report) {
5213
8388
  await fs5.stat(kernelPath);
5214
8389
  result.skipped.push(kernelPath);
5215
8390
  return result;
5216
- } catch (err3) {
5217
- if (err3.code !== "ENOENT") throw err3;
8391
+ } catch (err4) {
8392
+ if (err4.code !== "ENOENT") throw err4;
5218
8393
  }
5219
8394
  if (!config.dryRun) {
5220
8395
  await fs5.mkdir(path8.dirname(kernelPath), { recursive: true });
@@ -5252,9 +8427,9 @@ async function ensureDependenciesBuilt(config, options = {}) {
5252
8427
  if (stdout) logger.debug(stdout);
5253
8428
  if (stderr) logger.warn(stderr);
5254
8429
  logger.info("Pre‑flight build completed.");
5255
- } catch (err3) {
5256
- const e = err3;
5257
- const errorDetails = e.stderr || e.stdout || e.message || String(err3);
8430
+ } catch (err4) {
8431
+ const e = err4;
8432
+ const errorDetails = e.stderr || e.stdout || e.message || String(err4);
5258
8433
  logger.error(`Pre-flight build failed. Aborting sync.`);
5259
8434
  logger.error(`Build error: ${errorDetails}`);
5260
8435
  throw new Error("Preflight build failed — sync aborted");
@@ -5330,8 +8505,8 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
5330
8505
  if (realResolved !== realArchRoot && !realResolved.startsWith(archRootWithSep)) {
5331
8506
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
5332
8507
  }
5333
- } catch (err3) {
5334
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
8508
+ } catch (err4) {
8509
+ if (err4 instanceof Error && "code" in err4 && err4.code === "ENOENT") {
5335
8510
  let checkPath = archRoot;
5336
8511
  const pathSegments = path8.relative(archRoot, resolved).split(path8.sep);
5337
8512
  for (const segment of pathSegments) {
@@ -5356,7 +8531,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
5356
8531
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
5357
8532
  }
5358
8533
  } else {
5359
- throw err3;
8534
+ throw err4;
5360
8535
  }
5361
8536
  }
5362
8537
  }
@@ -5372,6 +8547,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
5372
8547
  ...parsed,
5373
8548
  description: parsed.description ?? "Auto-generated manifest"
5374
8549
  };
8550
+ const contractCheck = validateManifestPortContracts(manifestData);
8551
+ if (!contractCheck.ok) {
8552
+ throw contractCheck.error;
8553
+ }
5375
8554
  const validated = ManifestSchema.parse(manifestData);
5376
8555
  return validated;
5377
8556
  }
@@ -5394,11 +8573,11 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
5394
8573
  let sideCarContent;
5395
8574
  try {
5396
8575
  sideCarContent = await fs5.readFile(sideCarPath, "utf-8");
5397
- } catch (err3) {
5398
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
8576
+ } catch (err4) {
8577
+ if (err4 instanceof Error && "code" in err4 && err4.code === "ENOENT") {
5399
8578
  throw new Error(`Workspace config file not found: ${sideCarPath}`);
5400
8579
  }
5401
- throw err3;
8580
+ throw err4;
5402
8581
  }
5403
8582
  const sideCarResult = WorkspaceConfigSchema.safeParse(yaml3.load(sideCarContent));
5404
8583
  if (!sideCarResult.success) {
@@ -5420,13 +8599,19 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
5420
8599
  let contextContent;
5421
8600
  try {
5422
8601
  contextContent = await fs5.readFile(contextFilePath, "utf-8");
5423
- } catch (err3) {
5424
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
8602
+ } catch (err4) {
8603
+ if (err4 instanceof Error && "code" in err4 && err4.code === "ENOENT") {
5425
8604
  throw new Error(`Context file not found: ${contextFilePath}`);
5426
8605
  }
5427
- throw err3;
8606
+ throw err4;
5428
8607
  }
5429
8608
  const contextParsed = yaml3.load(contextContent);
8609
+ const contextContractCheck = validateManifestPortContracts({
8610
+ bounded_contexts: [contextParsed]
8611
+ });
8612
+ if (!contextContractCheck.ok) {
8613
+ throw contextContractCheck.error;
8614
+ }
5430
8615
  const contextResult = BoundedContextSchema.safeParse(contextParsed);
5431
8616
  if (!contextResult.success) {
5432
8617
  throw new Error(`Bounded context "${indexEntry.name}" validation failed: ${contextResult.error.message}`);
@@ -5455,11 +8640,11 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
5455
8640
  let appContent;
5456
8641
  try {
5457
8642
  appContent = await fs5.readFile(appFilePath, "utf-8");
5458
- } catch (err3) {
5459
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
8643
+ } catch (err4) {
8644
+ if (err4 instanceof Error && "code" in err4 && err4.code === "ENOENT") {
5460
8645
  throw new Error(`App file not found: ${appFilePath}`);
5461
8646
  }
5462
- throw err3;
8647
+ throw err4;
5463
8648
  }
5464
8649
  const appParsed = yaml3.load(appContent);
5465
8650
  const appResult = AppSchema.safeParse(appParsed);
@@ -5474,8 +8659,8 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
5474
8659
  // src/sync-engine-init.ts
5475
8660
  var __filename$1 = fileURLToPath(import.meta.url);
5476
8661
  var __dirname$1 = path8.dirname(__filename$1);
5477
- function isENOENT(err3) {
5478
- return err3 instanceof Error && "code" in err3 && err3.code === "ENOENT";
8662
+ function isENOENT(err4) {
8663
+ return err4 instanceof Error && "code" in err4 && err4.code === "ENOENT";
5479
8664
  }
5480
8665
  async function findRootFrom(startDir, problems) {
5481
8666
  let currentDir = startDir;
@@ -5487,9 +8672,9 @@ async function findRootFrom(startDir, problems) {
5487
8672
  if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
5488
8673
  return currentDir;
5489
8674
  }
5490
- } catch (err3) {
5491
- if (!isENOENT(err3)) {
5492
- const reason = err3 instanceof Error ? err3.message : String(err3);
8675
+ } catch (err4) {
8676
+ if (!isENOENT(err4)) {
8677
+ const reason = err4 instanceof Error ? err4.message : String(err4);
5493
8678
  problems.push(new Error(`${pkgPath}: ${reason}`));
5494
8679
  }
5495
8680
  }
@@ -5529,15 +8714,15 @@ async function loadManifest(workspaceRoot, flags, options) {
5529
8714
  );
5530
8715
  logger.info(`Loaded manifest from ${manifestPath}`);
5531
8716
  return { manifest, manifestMissing: false };
5532
- } catch (err3) {
5533
- if (isENOENT(err3) && dryRun) {
8717
+ } catch (err4) {
8718
+ if (isENOENT(err4) && dryRun) {
5534
8719
  logger.warn(`Manifest not found — using empty for dry-run`);
5535
8720
  return {
5536
8721
  manifest: { description: "Empty manifest", bounded_contexts: [] },
5537
8722
  manifestMissing: true
5538
8723
  };
5539
8724
  }
5540
- const message = err3 instanceof Error ? err3.message : "Unknown parse error";
8725
+ const message = err4 instanceof Error ? err4.message : "Unknown parse error";
5541
8726
  throw new Error(`Failed to parse manifest: ${message}`);
5542
8727
  }
5543
8728
  }
@@ -5563,9 +8748,9 @@ function validateManifest(manifest, flags) {
5563
8748
  try {
5564
8749
  ManifestSchema.parse(manifest);
5565
8750
  logger.debug("[Manifest] Zod Schema Validation passed");
5566
- } catch (err3) {
5567
- if (err3 instanceof Error) {
5568
- logger.warn(`[Manifest] Schema Validation warning: ${err3.message}`);
8751
+ } catch (err4) {
8752
+ if (err4 instanceof Error) {
8753
+ logger.warn(`[Manifest] Schema Validation warning: ${err4.message}`);
5569
8754
  }
5570
8755
  }
5571
8756
  logger.debug("[Manifest] Validation passed");
@@ -5664,6 +8849,7 @@ var SyncEngine = class {
5664
8849
  const tsconfigs = createEmptyResult();
5665
8850
  const eslint = createEmptyResult();
5666
8851
  const stubs = createEmptyResult();
8852
+ const codecs = createEmptyResult();
5667
8853
  for (const module of modules) {
5668
8854
  const moduleName = module.name;
5669
8855
  const moduleDir = path8.join(this.workspaceRoot, "packages", moduleName);
@@ -5708,12 +8894,19 @@ var SyncEngine = class {
5708
8894
  config,
5709
8895
  this.report
5710
8896
  );
8897
+ const codecResult = await generateCodecs(
8898
+ moduleDir,
8899
+ moduleName,
8900
+ config,
8901
+ this.report
8902
+ );
5711
8903
  this.noteFailure("Barrels", barrelResult);
5712
8904
  this.noteFailure("package.json", pkgResult);
5713
8905
  this.noteFailure("tsconfig.json", tsResult);
5714
8906
  this.noteFailure("src/index.ts", srcIndexResult);
5715
8907
  this.noteFailure("ESLint", eslintResult);
5716
8908
  this.noteFailure("Stubs", stubResult);
8909
+ this.noteFailure("Codecs", codecResult);
5717
8910
  if (this.partialConfig.mode === "self-regen") {
5718
8911
  await reapLegacyFolders(moduleDir, config, this.report);
5719
8912
  }
@@ -5723,6 +8916,7 @@ var SyncEngine = class {
5723
8916
  mergeResult2(tsconfigs, srcIndexResult);
5724
8917
  mergeResult2(eslint, eslintResult);
5725
8918
  mergeResult2(stubs, stubResult);
8919
+ mergeResult2(codecs, codecResult);
5726
8920
  }
5727
8921
  return {
5728
8922
  rootFiles: createEmptyResult(),
@@ -5732,9 +8926,152 @@ var SyncEngine = class {
5732
8926
  tsconfigs,
5733
8927
  eslint,
5734
8928
  stubs,
8929
+ codecs,
5735
8930
  apps: createEmptyResult(),
5736
- totalOps: barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps
8931
+ totalOps: barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps + codecs.totalOps
8932
+ };
8933
+ }
8934
+ /**
8935
+ * Lane H3: emit the adversarial codec tests under `<moduleDir>/__tests__/codecs/`
8936
+ * for every contract-bearing port. Mirrors the generateCoreArtifacts
8937
+ * per-module loop and failure discipline: each module's result is noted via
8938
+ * noteFailure("CodecTests", ...) BEFORE mergeResult folds it (merge keeps
8939
+ * only the first error), and the merged row feeds the run summary.
8940
+ */
8941
+ async generateCodecTestArtifacts() {
8942
+ const config = this.getConfig();
8943
+ const { logger } = config;
8944
+ const codecTests = createEmptyResult();
8945
+ const fail = (error) => {
8946
+ const failure = createEmptyResult();
8947
+ failure.error = error;
8948
+ failure.summary = `CodecTests failed: [${error.code}] ${error.message}`;
8949
+ this.noteFailure("CodecTests", failure);
8950
+ mergeResult2(codecTests, failure);
8951
+ return codecTests;
5737
8952
  };
8953
+ let contexts;
8954
+ try {
8955
+ contexts = readOwnPlainProperty(config.manifest, "bounded_contexts");
8956
+ } catch (thrown) {
8957
+ return fail(
8958
+ thrown instanceof CodecTestGeneratorError ? thrown : new CodecTestGeneratorError(
8959
+ "HOSTILE_INPUT",
8960
+ "bounded_contexts",
8961
+ thrown instanceof Error ? thrown.message : String(thrown)
8962
+ )
8963
+ );
8964
+ }
8965
+ if (contexts === void 0) return codecTests;
8966
+ let isArray;
8967
+ try {
8968
+ isArray = Array.isArray(contexts);
8969
+ } catch {
8970
+ return fail(
8971
+ new CodecTestGeneratorError(
8972
+ "HOSTILE_INPUT",
8973
+ "bounded_contexts",
8974
+ `reflection threw while inspecting bounded_contexts (revoked Proxy)`
8975
+ )
8976
+ );
8977
+ }
8978
+ if (!isArray || looksLikeProxy(contexts)) {
8979
+ return fail(
8980
+ new CodecTestGeneratorError(
8981
+ "HOSTILE_INPUT",
8982
+ "bounded_contexts",
8983
+ `bounded_contexts must be a dense non-Proxy array`
8984
+ )
8985
+ );
8986
+ }
8987
+ let ctxLen;
8988
+ try {
8989
+ ctxLen = contexts.length;
8990
+ } catch {
8991
+ return fail(
8992
+ new CodecTestGeneratorError(
8993
+ "HOSTILE_INPUT",
8994
+ "bounded_contexts",
8995
+ `reflection threw while reading the length of bounded_contexts`
8996
+ )
8997
+ );
8998
+ }
8999
+ if (ctxLen > MAX_BOUNDED_CONTEXTS2) {
9000
+ return fail(
9001
+ new CodecTestGeneratorError(
9002
+ "HOSTILE_INPUT",
9003
+ "bounded_contexts",
9004
+ `bounded_contexts has ${ctxLen} entries, exceeding MAX_BOUNDED_CONTEXTS (${MAX_BOUNDED_CONTEXTS2})`
9005
+ )
9006
+ );
9007
+ }
9008
+ for (let i = 0; i < ctxLen; i++) {
9009
+ let desc;
9010
+ try {
9011
+ desc = Object.getOwnPropertyDescriptor(contexts, String(i));
9012
+ } catch {
9013
+ return fail(
9014
+ new CodecTestGeneratorError(
9015
+ "HOSTILE_INPUT",
9016
+ `bounded_contexts[${i}]`,
9017
+ `reflection threw while reading index ${i} of bounded_contexts`
9018
+ )
9019
+ );
9020
+ }
9021
+ if (!desc || desc.get !== void 0 || desc.set !== void 0) {
9022
+ return fail(
9023
+ new CodecTestGeneratorError(
9024
+ "HOSTILE_INPUT",
9025
+ `bounded_contexts[${i}]`,
9026
+ `missing or accessor entry at index ${i} of bounded_contexts`
9027
+ )
9028
+ );
9029
+ }
9030
+ const entry = desc.value;
9031
+ try {
9032
+ validatePlainRecord(entry);
9033
+ } catch (thrown) {
9034
+ return fail(
9035
+ thrown instanceof CodecTestGeneratorError ? thrown : new CodecTestGeneratorError(
9036
+ "HOSTILE_INPUT",
9037
+ `bounded_contexts[${i}]`,
9038
+ thrown instanceof Error ? thrown.message : String(thrown)
9039
+ )
9040
+ );
9041
+ }
9042
+ let moduleName;
9043
+ try {
9044
+ moduleName = readOwnPlainProperty(entry, "name");
9045
+ } catch (thrown) {
9046
+ return fail(
9047
+ thrown instanceof CodecTestGeneratorError ? thrown : new CodecTestGeneratorError(
9048
+ "HOSTILE_INPUT",
9049
+ `bounded_contexts[${i}].name`,
9050
+ thrown instanceof Error ? thrown.message : String(thrown)
9051
+ )
9052
+ );
9053
+ }
9054
+ if (typeof moduleName !== "string" || moduleName.length === 0 || moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
9055
+ return fail(
9056
+ new CodecTestGeneratorError(
9057
+ "MALFORMED_CONTRACT",
9058
+ `bounded_contexts[${i}].name`,
9059
+ `bounded context at index ${i} has an invalid module name (non-string, empty, or a path-traversal shape)`
9060
+ )
9061
+ );
9062
+ }
9063
+ const moduleDir = path8.join(this.workspaceRoot, "packages", moduleName);
9064
+ logger.info(`Generating codec tests for module: ${moduleName}`);
9065
+ const codecTestResult = await generateCodecTests(
9066
+ moduleDir,
9067
+ moduleName,
9068
+ config,
9069
+ this.report
9070
+ );
9071
+ this.noteFailure("CodecTests", codecTestResult);
9072
+ mergeResult2(codecTests, codecTestResult);
9073
+ }
9074
+ return codecTests;
5738
9075
  }
5739
9076
  async run() {
5740
9077
  resetPortAnalysisMemo();
@@ -5808,15 +9145,15 @@ var SyncEngine = class {
5808
9145
  lockFile = new LockFile(this.workspaceRoot);
5809
9146
  try {
5810
9147
  await lockFile.acquire();
5811
- } catch (err3) {
5812
- if (err3 instanceof Error && err3.message.includes("Sync already in progress")) {
9148
+ } catch (err4) {
9149
+ if (err4 instanceof Error && err4.message.includes("Sync already in progress")) {
5813
9150
  logger.error("Sync aborted: another sync is in progress");
5814
9151
  throw new Error("Sync aborted: another sync is in progress");
5815
9152
  }
5816
9153
  logger.error(
5817
- `Lock acquire failed: ${err3 instanceof Error ? err3.message : String(err3)}`
9154
+ `Lock acquire failed: ${err4 instanceof Error ? err4.message : String(err4)}`
5818
9155
  );
5819
- throw err3;
9156
+ throw err4;
5820
9157
  }
5821
9158
  }
5822
9159
  if (mode === "self-regen") {
@@ -5842,7 +9179,8 @@ var SyncEngine = class {
5842
9179
  const layerResult = await this.ensureDirectories();
5843
9180
  this.noteFailure("Layers", layerResult);
5844
9181
  const coreResults = await this.generateCoreArtifacts();
5845
- const { pkgs, tsconfigs, eslint, stubs } = coreResults;
9182
+ const codecTests = await this.generateCodecTestArtifacts();
9183
+ const { pkgs, tsconfigs, eslint, stubs, codecs } = coreResults;
5846
9184
  const firstPassBarrels = coreResults.barrels;
5847
9185
  const appsResult = await generateApps(this.fullConfig, this.report);
5848
9186
  this.noteFailure("Apps", appsResult);
@@ -5885,6 +9223,8 @@ var SyncEngine = class {
5885
9223
  ["tsconfig.json", tsconfigs],
5886
9224
  ["ESLint", eslint],
5887
9225
  ["Stubs", stubs],
9226
+ ["Codecs", codecs],
9227
+ ["CodecTests", codecTests],
5888
9228
  ["Apps", appsResult]
5889
9229
  ];
5890
9230
  const runSummary = {
@@ -5958,8 +9298,8 @@ Sync completed with ${this.failures.length} generator failure(s) — see the FAI
5958
9298
  logger.info(`• ${label} : ${formatted}`);
5959
9299
  }
5960
9300
  return runSummary;
5961
- } catch (err3) {
5962
- const message = err3 instanceof Error ? err3.message : "Unknown sync error";
9301
+ } catch (err4) {
9302
+ const message = err4 instanceof Error ? err4.message : "Unknown sync error";
5963
9303
  logger.error(`Sync failed: ${message}`);
5964
9304
  if (!dryRun) {
5965
9305
  if (this.journal.size === 0) {
@@ -5997,7 +9337,7 @@ Sync completed with ${this.failures.length} generator failure(s) — see the FAI
5997
9337
  }
5998
9338
  }
5999
9339
  }
6000
- throw err3;
9340
+ throw err4;
6001
9341
  } finally {
6002
9342
  if (lockFile) {
6003
9343
  try {
@@ -6043,15 +9383,15 @@ function createPrefixedLogger(prefix, options = {}) {
6043
9383
  if (!shouldLog(LogLevel.DEBUG)) return;
6044
9384
  console.debug(formatMessage(LogLevel.DEBUG, msg), ctx ?? "");
6045
9385
  },
6046
- errorWithException: (err3, msg, ctx) => {
6047
- const errorMessage = msg ?? (err3 instanceof Error ? err3.message : String(err3));
9386
+ errorWithException: (err4, msg, ctx) => {
9387
+ const errorMessage = msg ?? (err4 instanceof Error ? err4.message : String(err4));
6048
9388
  const errorContext = {
6049
9389
  ...ctx,
6050
- exceptionType: err3 instanceof Error ? err3.constructor.name : "unknown"
9390
+ exceptionType: err4 instanceof Error ? err4.constructor.name : "unknown"
6051
9391
  };
6052
9392
  console.error(formatMessage(LogLevel.ERROR, errorMessage), errorContext);
6053
- if (err3 instanceof Error && err3.stack) {
6054
- console.error(err3.stack);
9393
+ if (err4 instanceof Error && err4.stack) {
9394
+ console.error(err4.stack);
6055
9395
  }
6056
9396
  }
6057
9397
  };
@@ -6120,10 +9460,10 @@ function parseArgs(rawArgs) {
6120
9460
  }
6121
9461
 
6122
9462
  // src/domain/result.ts
6123
- function ok2(value) {
9463
+ function ok3(value) {
6124
9464
  return { success: true, value };
6125
9465
  }
6126
- function err2(error) {
9466
+ function err3(error) {
6127
9467
  return { success: false, error };
6128
9468
  }
6129
9469
  var execAsync3 = promisify(exec);
@@ -6137,19 +9477,19 @@ async function loadManifest2(workspaceRoot) {
6137
9477
  workspaceRoot,
6138
9478
  manifestPath
6139
9479
  );
6140
- return ok2(manifest);
9480
+ return ok3(manifest);
6141
9481
  } catch (errObj) {
6142
9482
  if (errObj instanceof Error && "code" in errObj && errObj.code === "ENOENT") {
6143
- return err2(new Error(".architecture/manifest.yaml not found"));
9483
+ return err3(new Error(".architecture/manifest.yaml not found"));
6144
9484
  }
6145
- return err2(errObj instanceof Error ? errObj : new Error(String(errObj)));
9485
+ return err3(errObj instanceof Error ? errObj : new Error(String(errObj)));
6146
9486
  }
6147
9487
  }
6148
9488
  async function validateManifest2(workspaceRoot) {
6149
9489
  try {
6150
9490
  const bin = resolveArchLinterBin(workspaceRoot);
6151
9491
  if (bin === null) {
6152
- return err2(
9492
+ return err3(
6153
9493
  new Error(
6154
9494
  "arch-linter not found — install @hexagen-monaco/arch-linter (run your package manager's install)"
6155
9495
  )
@@ -6160,12 +9500,12 @@ async function validateManifest2(workspaceRoot) {
6160
9500
  timeout: 3e4
6161
9501
  });
6162
9502
  void stderr;
6163
- return ok2({ valid: true, errors: [] });
9503
+ return ok3({ valid: true, errors: [] });
6164
9504
  } catch (errObj) {
6165
9505
  const error = errObj;
6166
9506
  const message = error.stderr ? String(error.stderr) : error.message || "Unknown linter error";
6167
9507
  const errors = message.split("\n").filter((line) => line.trim().length > 0);
6168
- return ok2({ valid: false, errors });
9508
+ return ok3({ valid: false, errors });
6169
9509
  }
6170
9510
  }
6171
9511
  async function saveManifest(workspaceRoot, manifest) {
@@ -6176,12 +9516,12 @@ async function saveManifest(workspaceRoot, manifest) {
6176
9516
  );
6177
9517
  const content = yaml3.dump(manifest, { indent: 2 });
6178
9518
  await fs5.writeFile(manifestPath, content, "utf-8");
6179
- return ok2(void 0);
9519
+ return ok3(void 0);
6180
9520
  } catch (errObj) {
6181
- return err2(errObj);
9521
+ return err3(errObj);
6182
9522
  }
6183
9523
  }
6184
9524
 
6185
- export { DEFAULT_NAMING, DEFAULT_TEMPLATES, SyncEngine, buildDriftFiles, createEmptyResult, err2 as err, isIndexManifest, loadManifest2 as loadManifest, mergeSplitManifest, ok2 as ok, parseArgs, portName, recordWriteStatus, sanitizeScope, saveManifest, validateManifest2 as validateManifest };
9525
+ export { DEFAULT_NAMING, DEFAULT_TEMPLATES, SyncEngine, buildDriftFiles, createEmptyResult, err3 as err, isIndexManifest, loadManifest2 as loadManifest, mergeSplitManifest, ok3 as ok, parseArgs, portName, recordWriteStatus, sanitizeScope, saveManifest, validateManifest2 as validateManifest };
6186
9526
  //# sourceMappingURL=index.js.map
6187
9527
  //# sourceMappingURL=index.js.map