emviz 0.4.0 → 0.6.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
@@ -389,7 +389,7 @@ var require_utils = __commonJS({
389
389
  if (node.type === "range") node.type = "text";
390
390
  return acc;
391
391
  }, []);
392
- exports.flatten = (...args2) => {
392
+ exports.flatten = (...args) => {
393
393
  const result = [];
394
394
  const flat = (arr) => {
395
395
  for (let i = 0; i < arr.length; i++) {
@@ -404,7 +404,7 @@ var require_utils = __commonJS({
404
404
  }
405
405
  return result;
406
406
  };
407
- flat(args2);
407
+ flat(args);
408
408
  return result;
409
409
  };
410
410
  }
@@ -756,8 +756,8 @@ var require_fill_range = __commonJS({
756
756
  }
757
757
  return toRegexRange(start, end, options);
758
758
  };
759
- var rangeError = (...args2) => {
760
- return new RangeError("Invalid range arguments: " + util.inspect(...args2));
759
+ var rangeError = (...args) => {
760
+ return new RangeError("Invalid range arguments: " + util.inspect(...args));
761
761
  };
762
762
  var invalidRange = (start, end, options) => {
763
763
  if (options.strictRanges === true) throw rangeError([start, end]);
@@ -895,10 +895,10 @@ var require_compile = __commonJS({
895
895
  return node.value;
896
896
  }
897
897
  if (node.nodes && node.ranges > 0) {
898
- const args2 = utils.reduce(node.nodes);
899
- const range = fill(...args2, { ...options, wrap: false, toRegex: true, strictZeros: true });
898
+ const args = utils.reduce(node.nodes);
899
+ const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });
900
900
  if (range.length !== 0) {
901
- return args2.length > 1 && range.length > 1 ? `(${range})` : range;
901
+ return args.length > 1 && range.length > 1 ? `(${range})` : range;
902
902
  }
903
903
  }
904
904
  if (node.nodes) {
@@ -962,11 +962,11 @@ var require_expand = __commonJS({
962
962
  return;
963
963
  }
964
964
  if (node.nodes && node.ranges > 0) {
965
- const args2 = utils.reduce(node.nodes);
966
- if (utils.exceedsLimit(...args2, options.step, rangeLimit)) {
965
+ const args = utils.reduce(node.nodes);
966
+ if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
967
967
  throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
968
968
  }
969
- let range = fill(...args2, options);
969
+ let range = fill(...args, options);
970
970
  if (range.length === 0) {
971
971
  range = stringify(node, options);
972
972
  }
@@ -2015,16 +2015,16 @@ var require_parse2 = __commonJS({
2015
2015
  REGEX_SPECIAL_CHARS_BACKREF,
2016
2016
  REPLACEMENTS
2017
2017
  } = constants;
2018
- var expandRange = (args2, options) => {
2018
+ var expandRange = (args, options) => {
2019
2019
  if (typeof options.expandRange === "function") {
2020
- return options.expandRange(...args2, options);
2020
+ return options.expandRange(...args, options);
2021
2021
  }
2022
- args2.sort();
2023
- const value = `[${args2.join("-")}]`;
2022
+ args.sort();
2023
+ const value = `[${args.join("-")}]`;
2024
2024
  try {
2025
2025
  new RegExp(value);
2026
2026
  } catch (ex) {
2027
- return args2.map((v) => utils.escapeRegex(v)).join("..");
2027
+ return args.map((v) => utils.escapeRegex(v)).join("..");
2028
2028
  }
2029
2029
  return value;
2030
2030
  };
@@ -3287,8 +3287,8 @@ var require_micromatch = __commonJS({
3287
3287
  return match.slice(1).map((v) => v === void 0 ? "" : v);
3288
3288
  }
3289
3289
  };
3290
- micromatch.makeRe = (...args2) => picomatch.makeRe(...args2);
3291
- micromatch.scan = (...args2) => picomatch.scan(...args2);
3290
+ micromatch.makeRe = (...args) => picomatch.makeRe(...args);
3291
+ micromatch.scan = (...args) => picomatch.scan(...args);
3292
3292
  micromatch.parse = (patterns, options) => {
3293
3293
  let res = [];
3294
3294
  for (let pattern of [].concat(patterns || [])) {
@@ -3489,11 +3489,11 @@ var require_merge2 = __commonJS({
3489
3489
  module.exports = merge2;
3490
3490
  function merge2() {
3491
3491
  const streamsQueue = [];
3492
- const args2 = slice.call(arguments);
3492
+ const args = slice.call(arguments);
3493
3493
  let merging = false;
3494
- let options = args2[args2.length - 1];
3494
+ let options = args[args.length - 1];
3495
3495
  if (options && !Array.isArray(options) && options.pipe == null) {
3496
- args2.pop();
3496
+ args.pop();
3497
3497
  } else {
3498
3498
  options = {};
3499
3499
  }
@@ -3574,8 +3574,8 @@ var require_merge2 = __commonJS({
3574
3574
  mergedStream.on("unpipe", function(stream) {
3575
3575
  stream.emit("merge2UnpipeEnd");
3576
3576
  });
3577
- if (args2.length) {
3578
- addStream.apply(null, args2);
3577
+ if (args.length) {
3578
+ addStream.apply(null, args);
3579
3579
  }
3580
3580
  return mergedStream;
3581
3581
  }
@@ -13108,18 +13108,224 @@ var require_dist = __commonJS({
13108
13108
  // src/index.ts
13109
13109
  import fs7 from "node:fs";
13110
13110
  import http from "node:http";
13111
+ import { randomUUID as randomUUID2 } from "node:crypto";
13111
13112
  import path7 from "node:path";
13112
13113
  import { execFileSync as execFileSync3 } from "node:child_process";
13113
13114
  import { fileURLToPath } from "node:url";
13114
13115
 
13115
13116
  // ../parser/dist/index.js
13116
13117
  var import_fast_glob = __toESM(require_out4(), 1);
13117
- var import_yaml4 = __toESM(require_dist(), 1);
13118
+ var import_yaml5 = __toESM(require_dist(), 1);
13118
13119
  import fs2 from "node:fs";
13119
13120
  import path2 from "node:path";
13120
13121
 
13121
- // ../parser/dist/actors.js
13122
+ // ../parser/dist/features.js
13122
13123
  var import_yaml = __toESM(require_dist(), 1);
13124
+ function record(value) {
13125
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13126
+ }
13127
+ function identifier(value) {
13128
+ return typeof value === "string" && value.length > 0 && value.trim() === value;
13129
+ }
13130
+ function documentIssues(content, path8, kind) {
13131
+ let raw;
13132
+ try {
13133
+ raw = import_yaml.default.parse(content);
13134
+ } catch (error) {
13135
+ return [{ check: "F1", path: path8, message: `Invalid YAML: ${error instanceof Error ? error.message : String(error)}` }];
13136
+ }
13137
+ if (!record(raw))
13138
+ return [];
13139
+ const issues = [];
13140
+ if (raw.kind !== void 0 && raw.kind !== kind) {
13141
+ issues.push({ check: "F1", path: path8, message: `Expected kind "${kind}", received "${String(raw.kind)}".` });
13142
+ }
13143
+ if (raw.schema_version !== void 0 && raw.schema_version !== 1) {
13144
+ issues.push({ check: "F1", path: path8, message: `Unsupported schema_version "${String(raw.schema_version)}". Supported version is 1.` });
13145
+ }
13146
+ if (raw.kind === void 0 !== (raw.schema_version === void 0)) {
13147
+ issues.push({ check: "F1", path: path8, message: "kind and schema_version must be supplied together." });
13148
+ }
13149
+ return issues;
13150
+ }
13151
+ function parseFeatureFiles(files) {
13152
+ const stories = [];
13153
+ const timelines = [];
13154
+ const modelIssues = [];
13155
+ const featureIds = /* @__PURE__ */ new Set();
13156
+ for (const file of files) {
13157
+ const issue = (message) => modelIssues.push({ check: "F1", path: file.path, message });
13158
+ let raw;
13159
+ try {
13160
+ raw = import_yaml.default.parse(file.content);
13161
+ } catch (error) {
13162
+ issue(`Invalid feature YAML: ${error instanceof Error ? error.message : String(error)}`);
13163
+ continue;
13164
+ }
13165
+ if (!record(raw)) {
13166
+ issue("Feature document must be a mapping.");
13167
+ continue;
13168
+ }
13169
+ if (raw.kind !== "feature" || raw.schema_version !== 1) {
13170
+ issue('Feature document requires kind "feature" and schema_version 1.');
13171
+ continue;
13172
+ }
13173
+ if (!identifier(raw.id)) {
13174
+ issue("Feature requires a nonempty string id.");
13175
+ continue;
13176
+ }
13177
+ if (featureIds.has(raw.id)) {
13178
+ issue(`Duplicate feature id "${raw.id}".`);
13179
+ continue;
13180
+ }
13181
+ featureIds.add(raw.id);
13182
+ const featureIssueStart = modelIssues.length;
13183
+ if (!identifier(raw.name))
13184
+ issue("Feature name must be a nonempty string without surrounding whitespace.");
13185
+ const featureName = identifier(raw.name) ? raw.name : file.path;
13186
+ const localStories = /* @__PURE__ */ new Map();
13187
+ if (!Array.isArray(raw.stories)) {
13188
+ issue("Feature stories must be an array.");
13189
+ } else {
13190
+ for (const entry of raw.stories) {
13191
+ if (!record(entry) || !identifier(entry.id)) {
13192
+ issue("Each story requires a nonempty string id.");
13193
+ continue;
13194
+ }
13195
+ if (localStories.has(entry.id)) {
13196
+ issue(`Duplicate story id "${entry.id}".`);
13197
+ continue;
13198
+ }
13199
+ if (!identifier(entry.name))
13200
+ issue(`Story "${entry.id}" requires a nonempty name.`);
13201
+ const slices = [];
13202
+ if (!Array.isArray(entry.slices)) {
13203
+ issue(`Story "${entry.id}" slices must be an array.`);
13204
+ } else {
13205
+ for (const slice of entry.slices) {
13206
+ if (!identifier(slice) || slice.startsWith("/") || /^[A-Za-z]:/.test(slice) || slice.includes("\\") || slice.split("/").includes("..")) {
13207
+ issue(`Story "${entry.id}" slice references must be project-relative paths without parent traversal.`);
13208
+ continue;
13209
+ }
13210
+ const normalized = slice.split("/").filter((part) => part && part !== ".").join("/");
13211
+ if (!normalized) {
13212
+ issue(`Story "${entry.id}" slice reference must identify a file, not the project root.`);
13213
+ continue;
13214
+ }
13215
+ if (slices.includes(normalized))
13216
+ issue(`Story "${entry.id}" repeats slice "${normalized}".`);
13217
+ else
13218
+ slices.push(normalized);
13219
+ }
13220
+ }
13221
+ const story = {
13222
+ id: JSON.stringify([raw.id, entry.id]),
13223
+ localId: entry.id,
13224
+ featureName,
13225
+ name: identifier(entry.name) ? entry.name : entry.id,
13226
+ description: typeof entry.description === "string" ? entry.description : "",
13227
+ path: file.path,
13228
+ slices
13229
+ };
13230
+ localStories.set(entry.id, story);
13231
+ stories.push(story);
13232
+ }
13233
+ }
13234
+ if (modelIssues.length > featureIssueStart)
13235
+ continue;
13236
+ if (!Array.isArray(raw.timelines)) {
13237
+ issue("Feature timelines must be an array.");
13238
+ continue;
13239
+ }
13240
+ const timelineIds = /* @__PURE__ */ new Set();
13241
+ for (const entry of raw.timelines) {
13242
+ const issueStart = modelIssues.length;
13243
+ if (!record(entry) || !identifier(entry.id)) {
13244
+ issue("Each timeline requires a nonempty string id.");
13245
+ continue;
13246
+ }
13247
+ if (timelineIds.has(entry.id)) {
13248
+ issue(`Duplicate timeline id "${entry.id}".`);
13249
+ continue;
13250
+ }
13251
+ timelineIds.add(entry.id);
13252
+ if (!identifier(entry.name))
13253
+ issue(`Timeline "${entry.id}" requires a nonempty name.`);
13254
+ if (!Array.isArray(entry.steps) || entry.steps.length === 0) {
13255
+ issue(`Timeline "${entry.id}" steps must be a nonempty array.`);
13256
+ continue;
13257
+ }
13258
+ const steps = [];
13259
+ const stepIds = /* @__PURE__ */ new Set();
13260
+ const usedStories = /* @__PURE__ */ new Set();
13261
+ const usedSlices = /* @__PURE__ */ new Set();
13262
+ for (const step of entry.steps) {
13263
+ if (!record(step) || !identifier(step.id)) {
13264
+ issue(`Timeline "${entry.id}" requires a string id for every step.`);
13265
+ continue;
13266
+ }
13267
+ if (stepIds.has(step.id))
13268
+ issue(`Timeline "${entry.id}" repeats step id "${step.id}".`);
13269
+ stepIds.add(step.id);
13270
+ const story = typeof step.story === "string" ? localStories.get(step.story) : void 0;
13271
+ if (!story) {
13272
+ issue(`Timeline "${entry.id}" step "${step.id}" references unknown story "${String(step.story)}".`);
13273
+ continue;
13274
+ }
13275
+ if (usedStories.has(story.id))
13276
+ issue(`Timeline "${entry.id}" repeats story "${step.story}". Use separate timelines for alternative presentations.`);
13277
+ usedStories.add(story.id);
13278
+ for (const slice of story.slices) {
13279
+ if (usedSlices.has(slice))
13280
+ issue(`Timeline "${entry.id}" repeats slice "${slice}" across stories.`);
13281
+ usedSlices.add(slice);
13282
+ }
13283
+ const after = [];
13284
+ if (step.after !== void 0) {
13285
+ if (!Array.isArray(step.after) || !step.after.every(identifier)) {
13286
+ issue(`Timeline "${entry.id}" step "${step.id}" after must be an array of step ids.`);
13287
+ } else {
13288
+ for (const predecessor of step.after) {
13289
+ if (after.includes(predecessor))
13290
+ issue(`Step "${step.id}" repeats predecessor "${predecessor}".`);
13291
+ else
13292
+ after.push(predecessor);
13293
+ }
13294
+ }
13295
+ }
13296
+ steps.push({ id: step.id, storyId: story.id, after });
13297
+ }
13298
+ for (const step of steps) {
13299
+ for (const predecessor of step.after) {
13300
+ if (!stepIds.has(predecessor))
13301
+ issue(`Step "${step.id}" references unknown predecessor "${predecessor}".`);
13302
+ }
13303
+ }
13304
+ const pending = new Set(steps.map((step) => step.id));
13305
+ while (pending.size > 0) {
13306
+ const ready = steps.filter((step) => pending.has(step.id) && step.after.every((id) => !pending.has(id)));
13307
+ if (ready.length === 0) {
13308
+ issue(`Timeline "${entry.id}" contains a layout cycle involving ${[...pending].join(", ")}.`);
13309
+ break;
13310
+ }
13311
+ for (const step of ready)
13312
+ pending.delete(step.id);
13313
+ }
13314
+ if (modelIssues.length === issueStart) {
13315
+ timelines.push({
13316
+ id: JSON.stringify([raw.id, entry.id]),
13317
+ name: entry.name,
13318
+ path: file.path,
13319
+ steps
13320
+ });
13321
+ }
13322
+ }
13323
+ }
13324
+ return { stories, timelines, modelIssues };
13325
+ }
13326
+
13327
+ // ../parser/dist/actors.js
13328
+ var import_yaml2 = __toESM(require_dist(), 1);
13123
13329
  var palette = ["#2563EB", "#7C3AED", "#0F766E", "#B45309", "#BE185D", "#4338CA", "#047857", "#9F1239"];
13124
13330
  function actorColor(id) {
13125
13331
  let hash = 0;
@@ -13152,7 +13358,7 @@ function loadActors(content, sourcePath, slices) {
13152
13358
  if (content !== void 0) {
13153
13359
  let raw;
13154
13360
  try {
13155
- raw = import_yaml.default.parse(content);
13361
+ raw = import_yaml2.default.parse(content);
13156
13362
  } catch (error) {
13157
13363
  issue(`Invalid actor registry: ${error instanceof Error ? error.message : String(error)}`);
13158
13364
  }
@@ -13243,15 +13449,15 @@ function graphIds(project) {
13243
13449
  identities.set(base, keys);
13244
13450
  };
13245
13451
  for (const story of project.stories)
13246
- register(storyId(story.path), [story.path]);
13452
+ register(storyId(story.id ?? story.path), [story.id ?? story.path]);
13247
13453
  for (const event of project.events)
13248
13454
  register(eventId(event.name), [event.name]);
13249
13455
  for (const slice of project.slices) {
13250
13456
  register(sliceId(slice.path), [slice.path]);
13251
13457
  register(screenId(slice.path), [slice.path]);
13252
- slice.commands.forEach((command2, index) => {
13253
- register(commandId(command2.name), localIdentity(slice.path, slice.commands, index));
13254
- for (const name of command2.produces)
13458
+ slice.commands.forEach((command, index) => {
13459
+ register(commandId(command.name), localIdentity(slice.path, slice.commands, index));
13460
+ for (const name of command.produces)
13255
13461
  register(eventId(name), [name]);
13256
13462
  });
13257
13463
  slice.queries.forEach((query, index) => {
@@ -13281,11 +13487,11 @@ function buildGraph(project) {
13281
13487
  edges.set(key, { id: key, kind, source, target, ...label === void 0 ? {} : { label } });
13282
13488
  };
13283
13489
  for (const story of project.stories) {
13284
- const currentId = id(storyId(story.path), [story.path]);
13490
+ const currentId = id(storyId(story.id ?? story.path), [story.id ?? story.path]);
13285
13491
  for (const slicePath of new Set(story.slices)) {
13286
13492
  storyIdsBySlicePath.set(slicePath, [...storyIdsBySlicePath.get(slicePath) ?? [], currentId]);
13287
13493
  }
13288
- nodes.push({ id: currentId, type: "story", label: story.name, sourcePath: story.path, description: story.description });
13494
+ nodes.push({ id: currentId, type: "story", label: story.name, storyId: story.id, sourceName: story.localId, sourcePath: story.path, description: story.description });
13289
13495
  }
13290
13496
  for (const event of project.events) {
13291
13497
  nodes.push({ id: eventNodeId(event.name), type: "event", label: event.name, sourceName: event.name, sourcePath: event.sourcePath, fields: event.fields, description: event.description });
@@ -13293,7 +13499,7 @@ function buildGraph(project) {
13293
13499
  for (const slice of project.slices) {
13294
13500
  const currentSliceId = id(sliceId(slice.path), [slice.path]);
13295
13501
  const currentScreenId = id(screenId(slice.path), [slice.path]);
13296
- const shared = { storyName: slice.storyName, sliceTitle: slice.title, sourcePath: slice.path, raw: slice.raw };
13502
+ const shared = { storyName: slice.storyName, storyId: slice.storyId, sliceTitle: slice.title, sourcePath: slice.path, raw: slice.raw };
13297
13503
  nodes.push({ ...shared, id: currentSliceId, type: "slice", label: slice.title });
13298
13504
  for (const story of storyIdsBySlicePath.get(slice.path) ?? []) {
13299
13505
  connect("story-slice", story, currentSliceId);
@@ -13318,12 +13524,12 @@ function buildGraph(project) {
13318
13524
  for (const name of query.fromEvents)
13319
13525
  connect("event-query", eventNodeId(name), currentId, name);
13320
13526
  });
13321
- slice.commands.forEach((command2, index) => {
13322
- const currentId = id(commandId(command2.name), localIdentity(slice.path, slice.commands, index));
13323
- nodes.push({ ...shared, id: currentId, type: "command", label: command2.name, sourceName: command2.name, fields: command2.fields });
13324
- if (slice.screen.executes.includes(command2.name))
13527
+ slice.commands.forEach((command, index) => {
13528
+ const currentId = id(commandId(command.name), localIdentity(slice.path, slice.commands, index));
13529
+ nodes.push({ ...shared, id: currentId, type: "command", label: command.name, sourceName: command.name, fields: command.fields });
13530
+ if (slice.screen.executes.includes(command.name))
13325
13531
  connect("screen-command", currentScreenId, currentId);
13326
- for (const name of command2.produces)
13532
+ for (const name of command.produces)
13327
13533
  connect("command-event", currentId, eventNodeId(name), name);
13328
13534
  });
13329
13535
  slice.gwt.forEach((scenario, index) => {
@@ -13344,7 +13550,7 @@ function buildGraph(project) {
13344
13550
  }
13345
13551
 
13346
13552
  // ../parser/dist/config.js
13347
- var import_yaml2 = __toESM(require_dist(), 1);
13553
+ var import_yaml3 = __toESM(require_dist(), 1);
13348
13554
  import fs from "node:fs";
13349
13555
  import path from "node:path";
13350
13556
  function findProjectRoot(startDir) {
@@ -13368,7 +13574,7 @@ function readConfig(projectRoot) {
13368
13574
  return parseConfig(fs.readFileSync(configPath, "utf8"));
13369
13575
  }
13370
13576
  function parseConfig(content) {
13371
- const raw = import_yaml2.default.parse(content);
13577
+ const raw = import_yaml3.default.parse(content);
13372
13578
  const eventModelDir = raw?.paths?.event_model_dir ?? "event-model";
13373
13579
  const featuresDir = raw?.paths?.features_dir ?? "src/features";
13374
13580
  const sliceExtension = raw?.paths?.slice_extension ?? ".slice.yaml";
@@ -13386,7 +13592,7 @@ function parseConfig(content) {
13386
13592
  }
13387
13593
 
13388
13594
  // ../parser/dist/browser.js
13389
- var import_yaml3 = __toESM(require_dist(), 1);
13595
+ var import_yaml4 = __toESM(require_dist(), 1);
13390
13596
  function normalizeRelativePath(filePath) {
13391
13597
  const parts = [];
13392
13598
  for (const part of filePath.replaceAll("\\", "/").split("/")) {
@@ -13407,7 +13613,7 @@ function asStringArray(value) {
13407
13613
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13408
13614
  }
13409
13615
  function parseEventsText(sourcePath, content) {
13410
- const raw = import_yaml3.default.parse(content);
13616
+ const raw = import_yaml4.default.parse(content);
13411
13617
  const eventMap = raw?.events && typeof raw.events === "object" ? raw.events : raw ?? {};
13412
13618
  return Object.entries(eventMap).map(([name, entry]) => ({
13413
13619
  name,
@@ -13417,7 +13623,7 @@ function parseEventsText(sourcePath, content) {
13417
13623
  }));
13418
13624
  }
13419
13625
  function parseStoryText(storyPath, content) {
13420
- const raw = import_yaml3.default.parse(content);
13626
+ const raw = import_yaml4.default.parse(content);
13421
13627
  return {
13422
13628
  name: typeof raw?.name === "string" ? raw.name : basename(storyPath, ".yaml"),
13423
13629
  description: typeof raw?.description === "string" ? raw.description : "",
@@ -13466,11 +13672,12 @@ function parseScreen(raw) {
13466
13672
  };
13467
13673
  }
13468
13674
  function parseSliceText(slicePath, content, storyBySlice) {
13469
- const raw = import_yaml3.default.parse(content);
13675
+ const raw = import_yaml4.default.parse(content);
13470
13676
  return {
13471
13677
  title: typeof raw?.slice === "string" ? raw.slice : basename(slicePath),
13472
13678
  path: slicePath,
13473
- storyName: storyBySlice.get(slicePath),
13679
+ storyName: storyBySlice.get(slicePath)?.name,
13680
+ storyId: storyBySlice.get(slicePath)?.id,
13474
13681
  screen: parseScreen(raw?.screen),
13475
13682
  commands: parseCommands(raw?.commands),
13476
13683
  queries: parseQueries(raw?.queries),
@@ -13481,7 +13688,7 @@ function parseSliceText(slicePath, content, storyBySlice) {
13481
13688
  function loadEventModelProjectFromFiles(files, options = {}) {
13482
13689
  const normalizedFiles = new Map(files.map((file) => [normalizeRelativePath(file.path), file.content]));
13483
13690
  const configContent = normalizedFiles.get(".event-modeling/config.yaml");
13484
- const configRaw = configContent ? import_yaml3.default.parse(configContent) : null;
13691
+ const configRaw = configContent ? import_yaml4.default.parse(configContent) : null;
13485
13692
  const eventModelDir = configRaw?.paths?.event_model_dir ?? "event-model";
13486
13693
  const featuresDir = configRaw?.paths?.features_dir ?? "event-model/features";
13487
13694
  const sliceExtension = configRaw?.paths?.slice_extension ?? ".slice.yaml";
@@ -13492,16 +13699,28 @@ function loadEventModelProjectFromFiles(files, options = {}) {
13492
13699
  if (eventsContent === void 0)
13493
13700
  throw new Error(`Missing events file: ${eventsFile}`);
13494
13701
  const events = parseEventsText(eventsFile, eventsContent);
13702
+ const featureData = parseFeatureFiles([...normalizedFiles.entries()].filter(([filePath]) => (featuresDir === "" || filePath.startsWith(`${featuresDir}/`)) && filePath.endsWith(".feature.yaml")).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path8, content]) => ({ path: path8, content })));
13495
13703
  const stories = [...normalizedFiles.entries()].filter(([filePath]) => filePath.split("/").slice(0, -1).join("/") === storiesDir && filePath.endsWith(".yaml")).sort(([a], [b]) => a.localeCompare(b)).map(([filePath, content]) => parseStoryText(filePath, content));
13704
+ stories.push(...featureData.stories);
13496
13705
  const storyBySlice = /* @__PURE__ */ new Map();
13497
13706
  for (const story of stories)
13498
13707
  for (const slicePath of story.slices)
13499
- storyBySlice.set(normalizeRelativePath(slicePath), story.name);
13708
+ storyBySlice.set(normalizeRelativePath(slicePath), story);
13500
13709
  const storySlicePaths = stories.flatMap((story) => story.slices.map(normalizeRelativePath));
13501
13710
  const discoveredSlicePaths = [...normalizedFiles.keys()].filter((filePath) => (featuresDir === "" || filePath.startsWith(`${featuresDir}/`)) && filePath.endsWith(sliceExtension));
13502
13711
  const slicePaths = [.../* @__PURE__ */ new Set([...storySlicePaths, ...discoveredSlicePaths])].sort();
13503
13712
  const slices = slicePaths.filter((filePath) => normalizedFiles.has(filePath)).map((filePath) => parseSliceText(filePath, normalizedFiles.get(filePath) ?? "", storyBySlice));
13504
13713
  const actorData = loadActors(normalizedFiles.get(actorsFile), actorsFile, slices);
13714
+ const sourceDocuments = [
13715
+ { path: eventsFile, kind: "events" },
13716
+ ...stories.filter((story) => !story.id).map((story) => ({ path: story.path, kind: "story" })),
13717
+ ...slices.map((slice) => ({ path: slice.path, kind: "slice" })),
13718
+ ...normalizedFiles.has(actorsFile) ? [{ path: actorsFile, kind: "actors" }] : []
13719
+ ];
13720
+ const modelIssues = [
13721
+ ...featureData.modelIssues,
13722
+ ...sourceDocuments.flatMap((source) => documentIssues(normalizedFiles.get(source.path) ?? "", source.path, source.kind))
13723
+ ];
13505
13724
  const projectWithoutGraph = {
13506
13725
  root: options.root ?? "browser-import",
13507
13726
  config: {
@@ -13510,6 +13729,8 @@ function loadEventModelProjectFromFiles(files, options = {}) {
13510
13729
  },
13511
13730
  events,
13512
13731
  stories,
13732
+ timelines: featureData.timelines,
13733
+ modelIssues,
13513
13734
  slices,
13514
13735
  ...actorData
13515
13736
  };
@@ -13540,7 +13761,7 @@ function resolveProjectPath(projectRoot, relativePath) {
13540
13761
  return path2.resolve(projectRoot, relativePath);
13541
13762
  }
13542
13763
  function parseEventsText2(sourcePath, content) {
13543
- const raw = import_yaml4.default.parse(content);
13764
+ const raw = import_yaml5.default.parse(content);
13544
13765
  const eventMap = raw?.events && typeof raw.events === "object" ? raw.events : raw ?? {};
13545
13766
  return Object.entries(eventMap).map(([name, entry]) => ({
13546
13767
  name,
@@ -13554,7 +13775,7 @@ function parseEvents(projectRoot, eventsPath) {
13554
13775
  return parseEventsText2(rel(projectRoot, absolutePath), fs2.readFileSync(absolutePath, "utf8"));
13555
13776
  }
13556
13777
  function parseStoryText2(storyPath, content) {
13557
- const raw = import_yaml4.default.parse(content);
13778
+ const raw = import_yaml5.default.parse(content);
13558
13779
  return {
13559
13780
  name: typeof raw?.name === "string" ? raw.name : path2.basename(storyPath, ".yaml"),
13560
13781
  description: typeof raw?.description === "string" ? raw.description : "",
@@ -13607,11 +13828,12 @@ function parseScreen2(raw) {
13607
13828
  };
13608
13829
  }
13609
13830
  function parseSliceText2(slicePath, content, storyBySlice) {
13610
- const raw = import_yaml4.default.parse(content);
13831
+ const raw = import_yaml5.default.parse(content);
13611
13832
  return {
13612
13833
  title: typeof raw?.slice === "string" ? raw.slice : path2.basename(slicePath),
13613
13834
  path: slicePath,
13614
- storyName: storyBySlice.get(slicePath),
13835
+ storyName: storyBySlice.get(slicePath)?.name,
13836
+ storyId: storyBySlice.get(slicePath)?.id,
13615
13837
  screen: parseScreen2(raw?.screen),
13616
13838
  commands: parseCommands2(raw?.commands),
13617
13839
  queries: parseQueries2(raw?.queries),
@@ -13623,7 +13845,7 @@ function parseSlices(projectRoot, stories, sliceGlob) {
13623
13845
  const storyBySlice = /* @__PURE__ */ new Map();
13624
13846
  for (const story of stories) {
13625
13847
  for (const slicePath of story.slices) {
13626
- storyBySlice.set(slicePath, story.name);
13848
+ storyBySlice.set(slicePath, story);
13627
13849
  }
13628
13850
  }
13629
13851
  const storySlices = stories.flatMap((story) => story.slices);
@@ -13639,13 +13861,29 @@ function loadEventModelProject(startDir) {
13639
13861
  const root = findProjectRoot(startDir);
13640
13862
  const config = readConfig(root);
13641
13863
  const events = parseEvents(root, config.paths.eventsFile);
13642
- const stories = parseStories(root, config.paths.storiesDir);
13864
+ const featureFiles = import_fast_glob.default.sync(path2.posix.join(config.paths.featuresDir, "**/*.feature.yaml"), {
13865
+ cwd: root,
13866
+ onlyFiles: true,
13867
+ ignore: ["node_modules/**", ".git/**", "dist/**", "build/**"]
13868
+ }).sort().map((filePath) => ({ path: filePath, content: fs2.readFileSync(resolveProjectPath(root, filePath), "utf8") }));
13869
+ const featureData = parseFeatureFiles(featureFiles);
13870
+ const stories = [...parseStories(root, config.paths.storiesDir), ...featureData.stories];
13643
13871
  const slices = parseSlices(root, stories, path2.posix.join(config.paths.featuresDir, `**/*${config.paths.sliceExtension}`));
13644
13872
  const actorsPath = config.paths.actorsFile ?? path2.posix.join(config.paths.eventModelDir, "actors.yaml");
13645
13873
  const absoluteActorsPath = resolveProjectPath(root, actorsPath);
13646
13874
  const actorsContent = fs2.existsSync(absoluteActorsPath) ? fs2.readFileSync(absoluteActorsPath, "utf8") : void 0;
13647
13875
  const actorData = loadActors(actorsContent, actorsPath, slices);
13648
- const projectWithoutGraph = { root, config, events, stories, slices, ...actorData };
13876
+ const sourceDocuments = [
13877
+ { path: config.paths.eventsFile, kind: "events" },
13878
+ ...stories.filter((story) => !story.id).map((story) => ({ path: story.path, kind: "story" })),
13879
+ ...slices.map((slice) => ({ path: slice.path, kind: "slice" })),
13880
+ ...actorsContent === void 0 ? [] : [{ path: actorsPath, kind: "actors" }]
13881
+ ];
13882
+ const modelIssues = [
13883
+ ...featureData.modelIssues,
13884
+ ...sourceDocuments.flatMap((source) => documentIssues(fs2.readFileSync(resolveProjectPath(root, source.path), "utf8"), source.path, source.kind))
13885
+ ];
13886
+ const projectWithoutGraph = { root, config, events, stories, slices, timelines: featureData.timelines, modelIssues, ...actorData };
13649
13887
  const graph = buildGraph(projectWithoutGraph);
13650
13888
  return {
13651
13889
  ...projectWithoutGraph,
@@ -13671,6 +13909,19 @@ function materializeGitRef(ref, cwd = process.cwd()) {
13671
13909
  maxBuffer: 20 * 1024 * 1024
13672
13910
  });
13673
13911
  const config = parseConfig(configText);
13912
+ for (const directory of [config.paths.featuresDir, config.paths.storiesDir]) {
13913
+ const normalized = path3.posix.normalize(directory);
13914
+ if (path3.isAbsolute(normalized) || normalized === ".." || normalized.startsWith("../")) {
13915
+ throw new Error("Model directories must stay inside the project directory.");
13916
+ }
13917
+ const tracked = execFileSync("git", ["ls-tree", "-r", "-z", "--name-only", ref, "--", normalized], {
13918
+ cwd,
13919
+ encoding: "utf8"
13920
+ }).split("\0").filter(Boolean);
13921
+ for (const file of tracked) {
13922
+ if ((file.endsWith(".yaml") || file.endsWith(config.paths.sliceExtension)) && !files.includes(file)) files.push(file);
13923
+ }
13924
+ }
13674
13925
  const actorsFile = path3.posix.normalize(config.paths.actorsFile ?? path3.posix.join(config.paths.eventModelDir, "actors.yaml"));
13675
13926
  if (path3.isAbsolute(actorsFile) || actorsFile === ".." || actorsFile.startsWith("../")) {
13676
13927
  throw new Error("Actor registry must stay inside the project directory.");
@@ -13703,7 +13954,7 @@ import path4 from "node:path";
13703
13954
  function selectorForNode(node) {
13704
13955
  switch (node.type) {
13705
13956
  case "story":
13706
- return { name: node.label };
13957
+ return node.storyId ? { name: node.label, storyId: node.storyId } : { name: node.label };
13707
13958
  case "slice":
13708
13959
  return { slice: node.label };
13709
13960
  case "screen":
@@ -13759,6 +14010,7 @@ function comparableNode(node) {
13759
14010
  type: node.type,
13760
14011
  label: node.label,
13761
14012
  storyName: node.storyName,
14013
+ storyId: node.storyId,
13762
14014
  sliceTitle: node.sliceTitle,
13763
14015
  sourceName: node.sourceName,
13764
14016
  actors: node.actors,
@@ -13798,11 +14050,13 @@ function cloneProject(project) {
13798
14050
  events: project.events.map((event) => ({ ...event })),
13799
14051
  actors: project.actors?.map((actor) => ({ ...actor })),
13800
14052
  actorIssues: project.actorIssues?.map((issue) => ({ ...issue })),
14053
+ timelines: project.timelines?.map((timeline) => structuredClone(timeline)),
14054
+ modelIssues: project.modelIssues?.map((issue) => ({ ...issue })),
13801
14055
  stories: project.stories.map((story) => ({ ...story, slices: [...story.slices] })),
13802
14056
  slices: project.slices.map((slice) => ({
13803
14057
  ...slice,
13804
14058
  screen: { ...slice.screen, actors: [...slice.screen.actors], reads: [...slice.screen.reads], executes: [...slice.screen.executes] },
13805
- commands: slice.commands.map((command2) => ({ ...command2, produces: [...command2.produces] })),
14059
+ commands: slice.commands.map((command) => ({ ...command, produces: [...command.produces] })),
13806
14060
  queries: slice.queries.map((query) => ({ ...query, fromEvents: [...query.fromEvents] })),
13807
14061
  gwt: slice.gwt.map((scenario) => ({
13808
14062
  ...scenario,
@@ -13844,14 +14098,14 @@ function uniqueEdgeId(existingIds, id) {
13844
14098
  return next;
13845
14099
  }
13846
14100
  function mergeRemovedModelContainers(merged, base) {
13847
- const storyNames = new Set(merged.stories.map((story) => story.name));
14101
+ const storyNames = new Set(merged.stories.map((story) => story.id ?? story.name));
13848
14102
  const slicePaths = new Set(merged.slices.map((slice) => slice.path));
13849
14103
  const eventNames = new Set(merged.events.map((event) => event.name));
13850
14104
  for (const story of base.stories) {
13851
- if (storyNames.has(story.name))
14105
+ if (storyNames.has(story.id ?? story.name))
13852
14106
  continue;
13853
14107
  merged.stories.push({ ...story, slices: [...story.slices] });
13854
- storyNames.add(story.name);
14108
+ storyNames.add(story.id ?? story.name);
13855
14109
  }
13856
14110
  for (const slice of base.slices) {
13857
14111
  if (slicePaths.has(slice.path))
@@ -13859,7 +14113,7 @@ function mergeRemovedModelContainers(merged, base) {
13859
14113
  merged.slices.push({
13860
14114
  ...slice,
13861
14115
  screen: { ...slice.screen, actors: [...slice.screen.actors], reads: [...slice.screen.reads], executes: [...slice.screen.executes] },
13862
- commands: slice.commands.map((command2) => ({ ...command2, produces: [...command2.produces] })),
14116
+ commands: slice.commands.map((command) => ({ ...command, produces: [...command.produces] })),
13863
14117
  queries: slice.queries.map((query) => ({ ...query, fromEvents: [...query.fromEvents] })),
13864
14118
  gwt: slice.gwt.map((scenario) => ({
13865
14119
  ...scenario,
@@ -13902,6 +14156,7 @@ function buildGraphSidecar(project, existing) {
13902
14156
  events: project.config.paths.eventsFile,
13903
14157
  actors: project.config.paths.actorsFile,
13904
14158
  stories: [`${project.config.paths.storiesDir}/**/*.yaml`],
14159
+ features: [`${project.config.paths.featuresDir}/**/*.feature.yaml`],
13905
14160
  slices: [`${project.config.paths.featuresDir}/**/*${project.config.paths.sliceExtension}`]
13906
14161
  },
13907
14162
  nodes: Object.fromEntries(Object.entries(mergedNodes).sort(([a], [b]) => {
@@ -13922,6 +14177,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13922
14177
  return new Map(project.nodes.map((node) => {
13923
14178
  if (node.type === "event")
13924
14179
  return [node.id, nodeKey(node)];
14180
+ if (node.type === "story" && node.storyId)
14181
+ return [node.id, stableJson({ type: "story", storyId: node.storyId })];
13925
14182
  const key = stableJson({ selector: nodeKey(node), sourcePath: node.sourcePath });
13926
14183
  const occurrence = occurrences.get(key) ?? 0;
13927
14184
  occurrences.set(key, occurrence + 1);
@@ -13992,6 +14249,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13992
14249
  diff: {
13993
14250
  base: { label: labels.base ?? "base" },
13994
14251
  target: { label: labels.target ?? "target" },
14252
+ previousTimelines: base.timelines ? structuredClone(base.timelines) : [],
14253
+ timelinesChanged: stableJson(base.timelines ?? []) !== stableJson(target.timelines ?? []),
13995
14254
  previousGwtNodes,
13996
14255
  previousNodes,
13997
14256
  previousEdges,
@@ -14145,7 +14404,10 @@ function connectedComponentCount(project) {
14145
14404
  return components;
14146
14405
  }
14147
14406
  function validateEventModelProject(project, snapshot) {
14148
- const findings = (project.actorIssues ?? []).map((issue) => finding("error", "A1", issue.message, issue.path));
14407
+ const findings = [
14408
+ ...(project.actorIssues ?? []).map((issue) => finding("error", "A1", issue.message, issue.path)),
14409
+ ...(project.modelIssues ?? []).map((issue) => finding("error", issue.check, issue.message, issue.path))
14410
+ ];
14149
14411
  const eventNames = new Set(project.events.map((event) => event.name));
14150
14412
  const produced = /* @__PURE__ */ new Map();
14151
14413
  const consumed = /* @__PURE__ */ new Map();
@@ -14172,7 +14434,7 @@ function validateEventModelProject(project, snapshot) {
14172
14434
  }
14173
14435
  }
14174
14436
  for (const slice of project.slices) {
14175
- const commandNames = slice.commands.map((command2) => command2.name);
14437
+ const commandNames = slice.commands.map((command) => command.name);
14176
14438
  const queryNames = slice.queries.map((query) => query.name);
14177
14439
  for (const name of duplicates(commandNames)) {
14178
14440
  findings.push(finding("error", "L9", `Command "${name}" is duplicated within slice "${slice.title}".`, slice.path));
@@ -14205,15 +14467,15 @@ function validateEventModelProject(project, snapshot) {
14205
14467
  if (slice.commands.length > 0 && slice.gwt.length === 0) {
14206
14468
  findings.push(finding("warning", "M1", `Command slice "${slice.title}" has no GWT scenarios.`, slice.path));
14207
14469
  }
14208
- for (const command2 of slice.commands) {
14209
- if (!command2.fields?.trim()) {
14210
- findings.push(finding("warning", "L6", `Command "${command2.name}" has no fields block.`, slice.path));
14470
+ for (const command of slice.commands) {
14471
+ if (!command.fields?.trim()) {
14472
+ findings.push(finding("warning", "L6", `Command "${command.name}" has no fields block.`, slice.path));
14211
14473
  }
14212
- for (const eventName of command2.produces) {
14474
+ for (const eventName of command.produces) {
14213
14475
  if (!eventNames.has(eventName)) {
14214
- findings.push(finding("error", "G1", `Command "${command2.name}" produces unregistered event "${eventName}".`, slice.path));
14476
+ findings.push(finding("error", "G1", `Command "${command.name}" produces unregistered event "${eventName}".`, slice.path));
14215
14477
  }
14216
- produced.set(eventName, [...produced.get(eventName) ?? [], `${slice.title}.${command2.name}`]);
14478
+ produced.set(eventName, [...produced.get(eventName) ?? [], `${slice.title}.${command.name}`]);
14217
14479
  }
14218
14480
  }
14219
14481
  for (const query of slice.queries) {
@@ -14259,7 +14521,7 @@ function validateEventModelProject(project, snapshot) {
14259
14521
  findings.push(finding("error", "G3", `Event "${eventName}" is read by ${consumers.join(", ")} but no command produces it.`));
14260
14522
  }
14261
14523
  }
14262
- for (const name of duplicates(project.slices.flatMap((slice) => slice.commands.map((command2) => command2.name)))) {
14524
+ for (const name of duplicates(project.slices.flatMap((slice) => slice.commands.map((command) => command.name)))) {
14263
14525
  findings.push(finding("warning", "M5", `Command name "${name}" is used in multiple slices; command names should be globally unique.`));
14264
14526
  }
14265
14527
  for (const name of duplicates(project.slices.flatMap((slice) => slice.queries.map((query) => query.name)))) {
@@ -14295,8 +14557,66 @@ function validateEventModelProject(project, snapshot) {
14295
14557
  // src/feedback.ts
14296
14558
  import fs6 from "node:fs";
14297
14559
  import path6 from "node:path";
14298
- import { randomUUID, createHash, timingSafeEqual } from "node:crypto";
14560
+ import { randomUUID, createHash } from "node:crypto";
14299
14561
  import { execFileSync as execFileSync2 } from "node:child_process";
14562
+
14563
+ // src/network.ts
14564
+ import { isIP } from "node:net";
14565
+ import { timingSafeEqual } from "node:crypto";
14566
+ function parseHost(value = "127.0.0.1") {
14567
+ const host = value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
14568
+ const family = isIP(host);
14569
+ if (!family || value.startsWith("[") && family !== 6 || host.includes("%")) throw new Error("--host must be a concrete IPv4 or IPv6 address. DNS names and wildcard addresses are not supported.");
14570
+ const normalized = family === 6 ? new URL("http://[" + host + "]/").hostname.slice(1, -1) : host;
14571
+ if (normalized === "0.0.0.0" || normalized === "::" || normalized === "::ffff:0:0") {
14572
+ throw new Error("--host must select one interface address. Wildcard addresses are not supported.");
14573
+ }
14574
+ return normalized;
14575
+ }
14576
+ function parseHostArgs(values) {
14577
+ let host = "127.0.0.1";
14578
+ let provided = false;
14579
+ const args = [];
14580
+ for (let index = 0; index < values.length; index++) {
14581
+ const value = values[index];
14582
+ if (value !== "--host" && !value.startsWith("--host=")) {
14583
+ args.push(value);
14584
+ continue;
14585
+ }
14586
+ if (provided) throw new Error("--host may be specified only once.");
14587
+ const address = value === "--host" ? values[++index] : value.slice("--host=".length);
14588
+ if (!address || address.startsWith("--")) throw new Error("--host requires an IPv4 or IPv6 address.");
14589
+ host = parseHost(address);
14590
+ provided = true;
14591
+ }
14592
+ return { host, args, provided };
14593
+ }
14594
+ function isLoopbackHost(host) {
14595
+ return host === "::1" || host.startsWith("127.");
14596
+ }
14597
+ function serverOrigin(host, port) {
14598
+ return "http://" + (host.includes(":") ? "[" + host + "]" : host) + ":" + port;
14599
+ }
14600
+ function trustedRequest(req, port, host = "127.0.0.1") {
14601
+ const authority = new URL(serverOrigin(host, port)).host;
14602
+ const allowed = host === "127.0.0.1" ? [authority, "localhost:" + port] : [authority];
14603
+ const requestHost = req.headers.host;
14604
+ if (!requestHost || !allowed.includes(requestHost)) return false;
14605
+ const origin = req.headers.origin;
14606
+ return origin === void 0 || origin === "http://" + requestHost;
14607
+ }
14608
+ function validToken(req, expected) {
14609
+ const token = req.headers["x-emviz-token"];
14610
+ if (typeof token !== "string") return false;
14611
+ const actual = Buffer.from(token);
14612
+ const wanted = Buffer.from(expected);
14613
+ return actual.length === wanted.length && timingSafeEqual(actual, wanted);
14614
+ }
14615
+ function apiRequestAuthorized(req, pathname, host, token) {
14616
+ return isLoopbackHost(host) || pathname !== "/api" && !pathname.startsWith("/api/") || validToken(req, token);
14617
+ }
14618
+
14619
+ // src/feedback.ts
14300
14620
  var FeedbackError = class extends Error {
14301
14621
  constructor(status, message) {
14302
14622
  super(message);
@@ -14388,6 +14708,7 @@ function readSnapshot(target) {
14388
14708
  };
14389
14709
  walk(config.paths.storiesDir, false, ".yaml");
14390
14710
  walk(config.paths.featuresDir, true, config.paths.sliceExtension);
14711
+ walk(config.paths.featuresDir, true, ".feature.yaml");
14391
14712
  const preliminary = parseFiles(root, files, config);
14392
14713
  for (const source of preliminary.stories.flatMap((story) => story.slices)) {
14393
14714
  const key = sourceKey(root, source);
@@ -14410,7 +14731,7 @@ function readSnapshot(target) {
14410
14731
  function gitBaseline(snapshot) {
14411
14732
  const root = snapshot.project.root;
14412
14733
  try {
14413
- const git = (args2) => execFileSync2("git", ["-C", root, ...args2], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
14734
+ const git = (args) => execFileSync2("git", ["-C", root, ...args], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
14414
14735
  const commit = git(["rev-parse", "--verify", "HEAD^{commit}"]).trim();
14415
14736
  const repoRoot = git(["rev-parse", "--show-toplevel"]).trim();
14416
14737
  const prefix = path6.relative(fs6.realpathSync(repoRoot), fs6.realpathSync(root)).split(path6.sep).join("/");
@@ -14437,7 +14758,7 @@ function gitBaseline(snapshot) {
14437
14758
  const isStory = (path6.posix.dirname(key) === "." ? "" : path6.posix.dirname(key)) === config.paths.storiesDir && !path6.posix.basename(key).startsWith(".") && key.endsWith(".yaml");
14438
14759
  const relative = config.paths.featuresDir ? key.slice(config.paths.featuresDir.length + 1) : key;
14439
14760
  const ignored = relative.split("/").some((part) => part.startsWith(".")) || ["node_modules/", "dist/", "build/"].some((directory) => key.startsWith(directory));
14440
- const isSlice = !ignored && (config.paths.featuresDir === "" || key.startsWith(config.paths.featuresDir + "/")) && key.endsWith(config.paths.sliceExtension);
14761
+ const isSlice = !ignored && (config.paths.featuresDir === "" || key.startsWith(config.paths.featuresDir + "/")) && (key.endsWith(config.paths.sliceExtension) || key.endsWith(".feature.yaml"));
14441
14762
  if (isStory || isSlice) read(key);
14442
14763
  }
14443
14764
  const preliminary = parseFiles(root, files, config);
@@ -14451,6 +14772,67 @@ function textField(value, name, max) {
14451
14772
  if (typeof value !== "string" || !value.trim() || value.length > max) throw new FeedbackError(400, name + " must contain 1 to " + max + " characters.");
14452
14773
  return value;
14453
14774
  }
14775
+ function parseBatch(body) {
14776
+ const clientBatchId = textField(body.clientBatchId, "clientBatchId", 100);
14777
+ if (!Array.isArray(body.items) || body.items.length < 1 || body.items.length > 20) {
14778
+ throw new FeedbackError(400, "A batch must contain 1 to 20 items.");
14779
+ }
14780
+ const ids = /* @__PURE__ */ new Set();
14781
+ let messageLength = 0;
14782
+ const items = body.items.map((value) => {
14783
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new FeedbackError(400, "Expected a feedback item.");
14784
+ const item = value;
14785
+ const parsed = {
14786
+ id: textField(item.id, "item id", 100),
14787
+ nodeId: textField(item.nodeId, "nodeId", 500),
14788
+ reference: textField(item.reference, "reference", 1e3),
14789
+ revision: textField(item.revision, "revision", 100),
14790
+ message: textField(item.message, "message", 4e3)
14791
+ };
14792
+ if (ids.has(parsed.id)) throw new FeedbackError(400, "Batch item IDs must be unique.");
14793
+ ids.add(parsed.id);
14794
+ messageLength += parsed.message.length;
14795
+ return parsed;
14796
+ });
14797
+ if (messageLength > 16e3) throw new FeedbackError(413, "Batch messages exceed 16000 characters.");
14798
+ return { clientBatchId, items };
14799
+ }
14800
+ function nodeIdentity(node) {
14801
+ return JSON.stringify([node.type, node.sourcePath, node.sourceName, node.label, node.sliceTitle, node.type === "story" ? node.storyId : void 0]);
14802
+ }
14803
+ function uniqueNodeIds(project) {
14804
+ const ids = /* @__PURE__ */ new Map();
14805
+ for (const node of project.nodes) {
14806
+ const key = nodeIdentity(node);
14807
+ ids.set(key, ids.has(key) ? void 0 : node.id);
14808
+ }
14809
+ return ids;
14810
+ }
14811
+ function captureNode(snapshot, nodeId) {
14812
+ const node = snapshot.project.nodes.find((item) => item.id === nodeId);
14813
+ if (!node) throw new FeedbackError(409, "This element is no longer in the current model.");
14814
+ const reference = "em://" + (snapshot.graphSidecar?.model.id ?? "event_model") + "/" + nodeId;
14815
+ const yaml = node.sourcePath && snapshot.files.get(node.sourcePath) || node.raw || node.fields || node.description || node.label;
14816
+ if (yaml.length > 64e3) throw new FeedbackError(413, "Selected source exceeds 64000 characters.");
14817
+ const related = snapshot.project.edges.filter((edge) => edge.source === nodeId || edge.target === nodeId);
14818
+ const context = JSON.stringify({ node, validationFindings: snapshot.validation.findings.filter((finding2) => finding2.nodeId === nodeId || finding2.path === node.sourcePath), connections: related.map((edge) => ({ ...edge, sourceNode: snapshot.project.nodes.find((item) => item.id === edge.source), targetNode: snapshot.project.nodes.find((item) => item.id === edge.target) })) });
14819
+ if (context.length > 128e3) throw new FeedbackError(413, "Connected context exceeds 128000 characters.");
14820
+ return { reference, sourcePath: node.sourcePath, yaml, context };
14821
+ }
14822
+ function batchRequest(input, receipt) {
14823
+ const first = input.items[0];
14824
+ const message = "Batch feedback for " + input.items.length + " nodes. Address every item below before replying once.\n\n" + input.items.map((item, index) => index + 1 + ". " + item.reference + "\n" + item.message).join("\n\n");
14825
+ return {
14826
+ id: receipt.id,
14827
+ clientRequestId: input.clientBatchId,
14828
+ clientBatchId: input.clientBatchId,
14829
+ items: input.items,
14830
+ message,
14831
+ nodeId: first.nodeId,
14832
+ reference: first.reference,
14833
+ createdAt: receipt.createdAt
14834
+ };
14835
+ }
14454
14836
  var FeedbackSession = class {
14455
14837
  constructor(target) {
14456
14838
  this.target = target;
@@ -14464,6 +14846,7 @@ var FeedbackSession = class {
14464
14846
  baseline;
14465
14847
  state = { status: "idle" };
14466
14848
  history = [];
14849
+ batchReceipts = /* @__PURE__ */ new Map();
14467
14850
  lastSeen;
14468
14851
  error;
14469
14852
  waiter;
@@ -14501,10 +14884,16 @@ var FeedbackSession = class {
14501
14884
  project = result.project;
14502
14885
  diff = result.diff;
14503
14886
  }
14887
+ const currentIds = uniqueNodeIds(this.current.project);
14888
+ const currentNodeIds = Object.fromEntries(project.nodes.flatMap((node) => {
14889
+ const id = currentIds.get(nodeIdentity(node));
14890
+ return id === void 0 || diff?.nodeStatus[node.id] === "removed" ? [] : [[node.id, id]];
14891
+ }));
14504
14892
  return {
14505
14893
  sessionId: this.id,
14506
14894
  token: this.token,
14507
14895
  revision: this.current.revision,
14896
+ currentNodeIds,
14508
14897
  project: { ...project, graphSidecar: displayed.graphSidecar },
14509
14898
  validation: displayed.validation,
14510
14899
  diff,
@@ -14524,6 +14913,7 @@ var FeedbackSession = class {
14524
14913
  const message = textField(body.message, "message", 4e3);
14525
14914
  const nodeId = textField(body.nodeId, "nodeId", 500);
14526
14915
  const revision = textField(body.revision, "revision", 100);
14916
+ if (this.batchReceipts.has(clientRequestId)) throw new FeedbackError(409, "Request ID already belongs to a batch.");
14527
14917
  const active = "context" in this.state ? this.state.context?.request : void 0;
14528
14918
  const known = active?.clientRequestId === clientRequestId ? active : this.history.find((item) => item.clientRequestId === clientRequestId);
14529
14919
  if (known?.clientRequestId === clientRequestId) {
@@ -14534,22 +14924,51 @@ var FeedbackSession = class {
14534
14924
  if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14535
14925
  const snapshot = this.refresh();
14536
14926
  if (revision !== snapshot.revision) throw new FeedbackError(409, "Model changed. Refresh and select the element again.");
14537
- const node = snapshot.project.nodes.find((item) => item.id === nodeId);
14538
- if (!node) throw new FeedbackError(409, "This element is no longer in the current model.");
14927
+ const captured = captureNode(snapshot, nodeId);
14539
14928
  const request = {
14540
14929
  id: randomUUID(),
14541
14930
  clientRequestId,
14542
14931
  message,
14543
14932
  nodeId,
14544
14933
  createdAt: Date.now(),
14545
- reference: "em://" + (snapshot.graphSidecar?.model.id ?? "event_model") + "/" + nodeId
14546
- };
14547
- const yaml = node.sourcePath && snapshot.files.get(node.sourcePath) || node.raw || node.fields || node.description || node.label;
14548
- if (yaml.length > 64e3) throw new FeedbackError(413, "Selected source exceeds 64000 characters.");
14549
- const related = snapshot.project.edges.filter((edge) => edge.source === nodeId || edge.target === nodeId);
14550
- const context = JSON.stringify({ node, validationFindings: snapshot.validation.findings.filter((finding2) => finding2.nodeId === nodeId || finding2.path === node.sourcePath), connections: related.map((edge) => ({ ...edge, sourceNode: snapshot.project.nodes.find((item) => item.id === edge.source), targetNode: snapshot.project.nodes.find((item) => item.id === edge.target) })) });
14551
- if (context.length > 128e3) throw new FeedbackError(413, "Connected context exceeds 128000 characters.");
14552
- this.state = { status: "queued", context: { request, revision, sourcePath: node.sourcePath, yaml, context } };
14934
+ reference: captured.reference
14935
+ };
14936
+ this.state = { status: "queued", context: { request, revision, ...captured } };
14937
+ this.waiter?.();
14938
+ return request;
14939
+ }
14940
+ submitBatch(body) {
14941
+ const input = parseBatch(body);
14942
+ const fingerprint = createHash("sha256").update(JSON.stringify(input)).digest("hex");
14943
+ const active = "context" in this.state ? this.state.context?.request : void 0;
14944
+ const receipt = this.batchReceipts.get(input.clientBatchId);
14945
+ if (receipt) {
14946
+ if (receipt.fingerprint !== fingerprint) throw new FeedbackError(409, "Batch ID already used with different content.");
14947
+ return active?.id === receipt.id ? active : this.history.find((item) => item.id === receipt.id) ?? batchRequest(input, receipt);
14948
+ }
14949
+ if (active?.clientRequestId === input.clientBatchId || this.history.some((item) => item.clientRequestId === input.clientBatchId)) {
14950
+ throw new FeedbackError(409, "Batch ID already belongs to a request.");
14951
+ }
14952
+ if (this.state.status === "stopped") throw new FeedbackError(409, "Feedback is stopped.");
14953
+ if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14954
+ if (this.batchReceipts.size >= 1e3) throw new FeedbackError(429, "This session has accepted 1000 batches. Restart the project server before sending another batch.");
14955
+ const snapshot = this.refresh();
14956
+ const currentIds = uniqueNodeIds(snapshot.project);
14957
+ const items = input.items.map((item) => {
14958
+ if (item.revision !== snapshot.revision) throw new FeedbackError(409, "Model changed. Review and queue each element again.");
14959
+ const captured = captureNode(snapshot, item.nodeId);
14960
+ if (item.reference !== captured.reference) throw new FeedbackError(409, "An item reference does not match its current node.");
14961
+ const node = snapshot.project.nodes.find((candidate) => candidate.id === item.nodeId);
14962
+ if (currentIds.get(nodeIdentity(node)) !== node.id) throw new FeedbackError(409, "An item is ambiguous. Select a uniquely named current node.");
14963
+ return { ...item, ...captured };
14964
+ });
14965
+ const context = JSON.stringify({ kind: "batch", revision: snapshot.revision, items });
14966
+ if (Buffer.byteLength(context) > 1024 * 1024) throw new FeedbackError(413, "Batch captured context exceeds 1 MiB.");
14967
+ const accepted = { fingerprint, id: randomUUID(), createdAt: Date.now() };
14968
+ const request = batchRequest(input, accepted);
14969
+ const yaml = items.map((item, index) => "# Item " + (index + 1) + " " + item.reference + "\n" + item.yaml).join("\n\n");
14970
+ this.batchReceipts.set(input.clientBatchId, accepted);
14971
+ this.state = { status: "queued", context: { request, items, revision: snapshot.revision, yaml, context } };
14553
14972
  this.waiter?.();
14554
14973
  return request;
14555
14974
  }
@@ -14581,7 +15000,7 @@ var FeedbackSession = class {
14581
15000
  if (this.state.status === "queued") {
14582
15001
  const before = this.refresh();
14583
15002
  if (before.revision !== this.state.context.revision) {
14584
- this.archive({ ...this.state.context.request, reply: "Model changed before the agent started. Select the element and send again." });
15003
+ this.archive({ ...this.state.context.request, reply: this.state.context.items ? "Model changed before the agent started. Review every item and send a new batch." : "Model changed before the agent started. Select the element and send again." });
14585
15004
  this.state = { status: "idle" };
14586
15005
  throw new FeedbackError(409, "Model changed before claim. Request cancelled.");
14587
15006
  }
@@ -14589,7 +15008,7 @@ var FeedbackSession = class {
14589
15008
  this.state = { status: "working", context: this.state.context, agentId, before };
14590
15009
  }
14591
15010
  if (this.state.status === "working") {
14592
- return { status: "request", request: { ...this.state.context.request, sourcePath: this.state.context.sourcePath, yaml: this.state.context.yaml, context: this.state.context.context, projectRoot: this.current.project.root, revision: this.state.context.revision }, next_step: "Edit canonical YAML directly, validate it, then run emviz reply with this request ID and the same --url, --token, and --agent. Do not start a second request or commit/reset files automatically." };
15011
+ return { status: "request", request: { ...this.state.context.request, ...this.state.context.items ? { items: this.state.context.items } : {}, sourcePath: this.state.context.sourcePath, yaml: this.state.context.yaml, context: this.state.context.context, projectRoot: this.current.project.root, revision: this.state.context.revision }, next_step: (this.state.context.items ? "Apply all feedback items as one batch using their captured node references and context. Re-read current files before each edit without retargeting an item. Reply once after the whole batch. " : "") + "Edit canonical YAML directly, validate it, then run emviz reply with this request ID and the same --url, --token, and --agent. Do not start a second request or commit/reset files automatically." };
14593
15012
  }
14594
15013
  return { status: "timeout", next_step: "Run emviz poll again with the same --url, --token, and --agent. Wait in the foreground." };
14595
15014
  } finally {
@@ -14626,21 +15045,7 @@ var FeedbackSession = class {
14626
15045
  this.state = { status: "idle" };
14627
15046
  }
14628
15047
  };
14629
- function trustedRequest(req, port) {
14630
- const allowed = /* @__PURE__ */ new Set(["localhost:" + port, "127.0.0.1:" + port]);
14631
- const host = req.headers.host;
14632
- if (!host || !allowed.has(host)) return false;
14633
- const origin = req.headers.origin;
14634
- return origin === void 0 || origin === "http://" + host;
14635
- }
14636
- function validToken(req, expected) {
14637
- const token = req.headers["x-emviz-token"];
14638
- if (typeof token !== "string") return false;
14639
- const actual = Buffer.from(token);
14640
- const wanted = Buffer.from(expected);
14641
- return actual.length === wanted.length && timingSafeEqual(actual, wanted);
14642
- }
14643
- async function readJson(req) {
15048
+ async function readJson(req, maxBytes = 32768) {
14644
15049
  if (req.headers["content-type"]?.split(";")[0] !== "application/json") throw new FeedbackError(415, "Use application/json.");
14645
15050
  const content = await new Promise((resolve, reject) => {
14646
15051
  let size = 0;
@@ -14649,10 +15054,10 @@ async function readJson(req) {
14649
15054
  req.on("data", (chunk) => {
14650
15055
  if (failed) return;
14651
15056
  size += chunk.length;
14652
- if (size > 32768) {
15057
+ if (size > maxBytes) {
14653
15058
  failed = true;
14654
15059
  parts.length = 0;
14655
- reject(new FeedbackError(413, "Request exceeds 32 KiB."));
15060
+ reject(new FeedbackError(413, "Request exceeds " + maxBytes / 1024 + " KiB."));
14656
15061
  } else parts.push(chunk);
14657
15062
  });
14658
15063
  req.once("end", () => {
@@ -14693,11 +15098,14 @@ async function handleFeedback(req, res, session, close) {
14693
15098
  return true;
14694
15099
  }
14695
15100
  if (req.method !== "POST") throw new FeedbackError(405, "Method not allowed.");
14696
- const body = await readJson(req);
15101
+ const body = await readJson(req, url.pathname === "/api/feedback/batch" ? 128 * 1024 : 32768);
14697
15102
  switch (url.pathname) {
14698
15103
  case "/api/feedback/request":
14699
15104
  send(session.submit(body));
14700
15105
  break;
15106
+ case "/api/feedback/batch":
15107
+ send(session.submitBatch(body));
15108
+ break;
14701
15109
  case "/api/feedback/reply":
14702
15110
  send({ request: session.reply(body), next_step: "Run emviz poll with the same connection options." });
14703
15111
  break;
@@ -14739,22 +15147,23 @@ function parseConnection(values) {
14739
15147
  } else positional.push(value);
14740
15148
  }
14741
15149
  const url = new URL(options.get("--url") ?? "");
14742
- if (url.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(url.hostname) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error("--url must be a loopback HTTP origin.");
15150
+ if (url.protocol !== "http:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error("--url must be an HTTP origin without credentials, path, query, or fragment. Use url, not viewerUrl.");
15151
+ if (url.hostname !== "localhost") parseHost(url.hostname);
14743
15152
  const token = options.get("--token");
14744
15153
  if (!token) throw new Error("--token is required. Use the token printed by emviz open.");
14745
15154
  return { url, token, agent: options.get("--agent"), positional };
14746
15155
  }
14747
- async function runAgentCommand(command2, values) {
15156
+ async function runAgentCommand(command, values) {
14748
15157
  const connection = parseConnection(values);
14749
- if ((command2 === "poll" || command2 === "reply") && !connection.agent) throw new Error("--agent is required. Reuse one unique ID throughout the session.");
14750
- const route = command2 === "poll" ? "/api/feedback/poll?agent=" + encodeURIComponent(connection.agent) : "/api/feedback/" + command2;
14751
- const body = command2 === "reply" ? { id: connection.positional[0], reply: connection.positional[1], agent: connection.agent } : {};
14752
- if (command2 === "reply" && connection.positional.length !== 2) throw new Error("Usage: emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
14753
- if (command2 !== "reply" && connection.positional.length) throw new Error("Unexpected positional argument.");
15158
+ if ((command === "poll" || command === "reply") && !connection.agent) throw new Error("--agent is required. Reuse one unique ID throughout the session.");
15159
+ const route = command === "poll" ? "/api/feedback/poll?agent=" + encodeURIComponent(connection.agent) : "/api/feedback/" + command;
15160
+ const body = command === "reply" ? { id: connection.positional[0], reply: connection.positional[1], agent: connection.agent } : {};
15161
+ if (command === "reply" && connection.positional.length !== 2) throw new Error("Usage: emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
15162
+ if (command !== "reply" && connection.positional.length) throw new Error("Unexpected positional argument.");
14754
15163
  const response = await fetch(new URL(route, connection.url), {
14755
- method: command2 === "poll" ? "GET" : "POST",
15164
+ method: command === "poll" ? "GET" : "POST",
14756
15165
  headers: { "X-Emviz-Token": connection.token, "Content-Type": "application/json" },
14757
- body: command2 === "poll" ? void 0 : JSON.stringify(body),
15166
+ body: command === "poll" ? void 0 : JSON.stringify(body),
14758
15167
  signal: AbortSignal.timeout(3e4),
14759
15168
  redirect: "error"
14760
15169
  });
@@ -14762,8 +15171,9 @@ async function runAgentCommand(command2, values) {
14762
15171
  console.log(JSON.stringify(result));
14763
15172
  if (!response.ok) process.exitCode = 1;
14764
15173
  }
14765
- async function openProject(entry, target) {
14766
- const child = spawn(process.execPath, [entry, "serve", target], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
15174
+ async function openProject(entry, target, host = "127.0.0.1") {
15175
+ const address = parseHost(host);
15176
+ const child = spawn(process.execPath, [entry, "serve", target, "--host", address], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
14767
15177
  await new Promise((resolve, reject) => {
14768
15178
  const timer = setTimeout(() => {
14769
15179
  child.kill();
@@ -14789,8 +15199,6 @@ async function openProject(entry, target) {
14789
15199
  }
14790
15200
 
14791
15201
  // src/index.ts
14792
- var args = process.argv.slice(2);
14793
- var command = args[0];
14794
15202
  function resolveTarget(value) {
14795
15203
  return path7.resolve(process.cwd(), value ?? ".");
14796
15204
  }
@@ -14924,7 +15332,7 @@ function serveApp(req, res, appRoot) {
14924
15332
  }
14925
15333
  serveFile(res, path7.join(appRoot, "index.html"));
14926
15334
  }
14927
- function listenWithFallback(server, port) {
15335
+ function listenWithFallback(server, port, host) {
14928
15336
  return new Promise((resolve, reject) => {
14929
15337
  const tryListen = (nextPort) => {
14930
15338
  server.once("error", (error) => {
@@ -14935,14 +15343,14 @@ function listenWithFallback(server, port) {
14935
15343
  }
14936
15344
  reject(error);
14937
15345
  });
14938
- server.listen(nextPort, "127.0.0.1", () => {
15346
+ server.listen(nextPort, host, () => {
14939
15347
  resolve(server.address().port);
14940
15348
  });
14941
15349
  };
14942
15350
  tryListen(port);
14943
15351
  });
14944
15352
  }
14945
- async function runServer(targetDir, diffState) {
15353
+ async function runServer(host, targetDir, diffState) {
14946
15354
  if (targetDir) {
14947
15355
  const initial = readSnapshot(targetDir);
14948
15356
  if (!initial.graphSidecar) {
@@ -14952,6 +15360,7 @@ async function runServer(targetDir, diffState) {
14952
15360
  }
14953
15361
  const appRoot = path7.resolve(path7.dirname(fileURLToPath(import.meta.url)), "app");
14954
15362
  const feedback = targetDir ? new FeedbackSession(targetDir) : void 0;
15363
+ const token = feedback?.token ?? randomUUID2();
14955
15364
  let listeningPort = 0;
14956
15365
  const server = http.createServer((req, res) => {
14957
15366
  void respond(req, res).catch((error) => {
@@ -14968,13 +15377,19 @@ async function runServer(targetDir, diffState) {
14968
15377
  timer.unref();
14969
15378
  };
14970
15379
  const respond = async (req, res) => {
14971
- if (!trustedRequest(req, listeningPort)) {
15380
+ res.setHeader("cache-control", "no-store");
15381
+ res.setHeader("referrer-policy", "no-referrer");
15382
+ if (!trustedRequest(req, listeningPort, host)) {
14972
15383
  sendText(res, 403, "Forbidden Host or Origin");
14973
15384
  return;
14974
15385
  }
14975
- res.setHeader("cache-control", "no-store");
15386
+ const url2 = new URL(req.url ?? "/", serverOrigin(host, listeningPort));
15387
+ if (!apiRequestAuthorized(req, url2.pathname, host, token)) {
15388
+ res.statusCode = 403;
15389
+ sendJson(res, { error: "Invalid session token. Open the complete viewerUrl printed by emviz in this browser." });
15390
+ return;
15391
+ }
14976
15392
  if (feedback && await handleFeedback(req, res, feedback, close)) return;
14977
- const url2 = new URL(req.url ?? "/", "http://localhost");
14978
15393
  if (req.method !== "GET" && req.method !== "HEAD") {
14979
15394
  sendText(res, 405, "Method not allowed");
14980
15395
  return;
@@ -15019,17 +15434,19 @@ async function runServer(targetDir, diffState) {
15019
15434
  }
15020
15435
  serveApp(req, res, appRoot);
15021
15436
  };
15022
- const port = await listenWithFallback(server, 5173);
15437
+ const port = await listenWithFallback(server, 5173, host);
15023
15438
  listeningPort = port;
15024
- const url = `http://127.0.0.1:${port}/`;
15439
+ const url = serverOrigin(host, port) + "/";
15440
+ const viewerUrl = isLoopbackHost(host) ? url : url + "#token=" + encodeURIComponent(token);
15025
15441
  if (feedback) {
15026
- const ready = { url, token: feedback.token, pid: process.pid, next_step: `Run emviz poll --url ${url} --token ${feedback.token} --agent <unique-agent-id> in your external agent.` };
15442
+ const ready = { url, viewerUrl, token, pid: process.pid, next_step: `Run emviz poll --url ${url} --token ${token} --agent <unique-agent-id> in your external agent.` };
15027
15443
  if (process.send) process.send(ready);
15028
15444
  else console.log(JSON.stringify(ready));
15029
15445
  }
15030
15446
  process.once("SIGTERM", close);
15031
15447
  process.once("SIGINT", close);
15032
- console.log(` \u279C Local: http://localhost:${port}/`);
15448
+ console.log(` \u279C ${isLoopbackHost(host) ? "Local" : "Remote"}: ${viewerUrl}`);
15449
+ if (!isLoopbackHost(host)) console.warn("Remote access requires the complete viewerUrl. Treat that link and the token as secrets. HTTP is unencrypted; use a trusted private network such as Tailscale.");
15033
15450
  if (diffState) {
15034
15451
  console.log(`Diff: ${diffState.diff.base.label} -> ${diffState.diff.target.label}`);
15035
15452
  } else {
@@ -15037,17 +15454,22 @@ async function runServer(targetDir, diffState) {
15037
15454
  }
15038
15455
  }
15039
15456
  async function main() {
15040
- if (command === "open") {
15041
- if (args.length > 2) throw new Error("Usage: emviz open [project-dir]");
15042
- await openProject(fileURLToPath(import.meta.url), resolveTarget(args[1]));
15457
+ const rawArgs = process.argv.slice(2);
15458
+ if (["poll", "reply", "stop", "close"].includes(rawArgs[0])) {
15459
+ await runAgentCommand(rawArgs[0], rawArgs.slice(1));
15043
15460
  return;
15044
15461
  }
15045
- if (command === "serve") {
15046
- await runServer(resolveTarget(args[1]));
15462
+ const { host, args, provided } = parseHostArgs(rawArgs);
15463
+ const command = args[0];
15464
+ if (provided && ["sync", "init", "poll", "reply", "stop", "close"].includes(command)) throw new Error("--host is only supported by server commands.");
15465
+ if (command === "open") {
15466
+ if (args.length > 2) throw new Error("Usage: emviz open [project-dir] [--host <ip>]");
15467
+ await openProject(fileURLToPath(import.meta.url), resolveTarget(args[1]), host);
15047
15468
  return;
15048
15469
  }
15049
- if (["poll", "reply", "stop", "close"].includes(command)) {
15050
- await runAgentCommand(command, args.slice(1));
15470
+ if (command === "serve") {
15471
+ if (args.length > 2) throw new Error("Usage: emviz serve [project-dir] [--host <ip>]");
15472
+ await runServer(host, resolveTarget(args[1]));
15051
15473
  return;
15052
15474
  }
15053
15475
  if (command === "sync") {
@@ -15062,22 +15484,26 @@ async function main() {
15062
15484
  if (command === "diff") {
15063
15485
  const diffArgs = parseDiffArgs(args.slice(1));
15064
15486
  const diffState = loadDiffServerState(diffArgs.base, diffArgs.target);
15065
- await runServer(void 0, diffState);
15487
+ await runServer(host, void 0, diffState);
15066
15488
  return;
15067
15489
  }
15068
15490
  if (command === "--help" || command === "-h") {
15069
- console.log("Usage: emviz [project-dir]");
15070
- console.log(" emviz open [project-dir]");
15491
+ console.log("Usage: emviz [project-dir] [--host <ip>]");
15492
+ console.log(" emviz open [project-dir] [--host <ip>]");
15493
+ console.log(" emviz serve [project-dir] [--host <ip>]");
15071
15494
  console.log(" emviz poll --url <url> --token <token> --agent <id>");
15072
15495
  console.log(" emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
15073
15496
  console.log(" emviz stop|close --url <url> --token <token>");
15074
15497
  console.log(" emviz sync [project-dir]");
15075
- console.log(" emviz diff [base-ref-or-dir] [project-dir]");
15076
- console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir>");
15498
+ console.log(" emviz diff [base-ref-or-dir] [project-dir] [--host <ip>]");
15499
+ console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir> [--host <ip>]");
15077
15500
  console.log(" emviz init [project-dir] (deprecated alias for sync)");
15501
+ console.log("Default host: 127.0.0.1. Use a concrete IPv4 or IPv6 interface address. DNS names and wildcard binds are rejected.");
15502
+ console.log("Remote browser access uses the printed viewerUrl. Agent commands use url and --token.");
15078
15503
  return;
15079
15504
  }
15080
- await runServer(command ? resolveTarget(command) : void 0);
15505
+ if (args.length > 1 || command?.startsWith("-")) throw new Error("Usage: emviz [project-dir] [--host <ip>]");
15506
+ await runServer(host, command ? resolveTarget(command) : void 0);
15081
15507
  }
15082
15508
  main().catch((error) => {
15083
15509
  console.error(error instanceof Error ? error.message : error);